util.c 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569
  1. /* Copyright (c) 2003, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2010, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file util.c
  7. * \brief Common functions for strings, IO, network, data structures,
  8. * process control.
  9. **/
  10. /* This is required on rh7 to make strptime not complain.
  11. */
  12. #define _GNU_SOURCE
  13. #include "orconfig.h"
  14. #include "util.h"
  15. #include "log.h"
  16. #include "crypto.h"
  17. #include "torint.h"
  18. #include "container.h"
  19. #include "address.h"
  20. #ifdef MS_WINDOWS
  21. #include <io.h>
  22. #include <direct.h>
  23. #include <process.h>
  24. #else
  25. #include <dirent.h>
  26. #include <pwd.h>
  27. #endif
  28. #include <stdlib.h>
  29. #include <stdio.h>
  30. #include <string.h>
  31. #include <assert.h>
  32. #ifdef HAVE_NETINET_IN_H
  33. #include <netinet/in.h>
  34. #endif
  35. #ifdef HAVE_ARPA_INET_H
  36. #include <arpa/inet.h>
  37. #endif
  38. #ifdef HAVE_ERRNO_H
  39. #include <errno.h>
  40. #endif
  41. #ifdef HAVE_SYS_SOCKET_H
  42. #include <sys/socket.h>
  43. #endif
  44. #ifdef HAVE_SYS_TIME_H
  45. #include <sys/time.h>
  46. #endif
  47. #ifdef HAVE_UNISTD_H
  48. #include <unistd.h>
  49. #endif
  50. #ifdef HAVE_SYS_STAT_H
  51. #include <sys/stat.h>
  52. #endif
  53. #ifdef HAVE_SYS_FCNTL_H
  54. #include <sys/fcntl.h>
  55. #endif
  56. #ifdef HAVE_FCNTL_H
  57. #include <fcntl.h>
  58. #endif
  59. #ifdef HAVE_TIME_H
  60. #include <time.h>
  61. #endif
  62. #ifdef HAVE_MALLOC_MALLOC_H
  63. #include <malloc/malloc.h>
  64. #endif
  65. #ifdef HAVE_MALLOC_H
  66. #ifndef OPENBSD
  67. /* OpenBSD has a malloc.h, but for our purposes, it only exists in order to
  68. * scold us for being so stupid as to autodetect its presence. To be fair,
  69. * they've done this since 1996, when autoconf was only 5 years old. */
  70. #include <malloc.h>
  71. #endif
  72. #endif
  73. #ifdef HAVE_MALLOC_NP_H
  74. #include <malloc_np.h>
  75. #endif
  76. /* =====
  77. * Memory management
  78. * ===== */
  79. #ifdef USE_DMALLOC
  80. #undef strndup
  81. #include <dmalloc.h>
  82. /* Macro to pass the extra dmalloc args to another function. */
  83. #define DMALLOC_FN_ARGS , file, line
  84. #if defined(HAVE_DMALLOC_STRDUP)
  85. /* the dmalloc_strdup should be fine as defined */
  86. #elif defined(HAVE_DMALLOC_STRNDUP)
  87. #define dmalloc_strdup(file, line, string, xalloc_b) \
  88. dmalloc_strndup(file, line, (string), -1, xalloc_b)
  89. #else
  90. #error "No dmalloc_strdup or equivalent"
  91. #endif
  92. #else /* not using dmalloc */
  93. #define DMALLOC_FN_ARGS
  94. #endif
  95. /** Allocate a chunk of <b>size</b> bytes of memory, and return a pointer to
  96. * result. On error, log and terminate the process. (Same as malloc(size),
  97. * but never returns NULL.)
  98. *
  99. * <b>file</b> and <b>line</b> are used if dmalloc is enabled, and
  100. * ignored otherwise.
  101. */
  102. void *
  103. _tor_malloc(size_t size DMALLOC_PARAMS)
  104. {
  105. void *result;
  106. #ifndef MALLOC_ZERO_WORKS
  107. /* Some libc mallocs don't work when size==0. Override them. */
  108. if (size==0) {
  109. size=1;
  110. }
  111. #endif
  112. #ifdef USE_DMALLOC
  113. result = dmalloc_malloc(file, line, size, DMALLOC_FUNC_MALLOC, 0, 0);
  114. #else
  115. result = malloc(size);
  116. #endif
  117. if (PREDICT_UNLIKELY(result == NULL)) {
  118. log_err(LD_MM,"Out of memory on malloc(). Dying.");
  119. /* If these functions die within a worker process, they won't call
  120. * spawn_exit, but that's ok, since the parent will run out of memory soon
  121. * anyway. */
  122. exit(1);
  123. }
  124. return result;
  125. }
  126. /** Allocate a chunk of <b>size</b> bytes of memory, fill the memory with
  127. * zero bytes, and return a pointer to the result. Log and terminate
  128. * the process on error. (Same as calloc(size,1), but never returns NULL.)
  129. */
  130. void *
  131. _tor_malloc_zero(size_t size DMALLOC_PARAMS)
  132. {
  133. /* You may ask yourself, "wouldn't it be smart to use calloc instead of
  134. * malloc+memset? Perhaps libc's calloc knows some nifty optimization trick
  135. * we don't!" Indeed it does, but its optimizations are only a big win when
  136. * we're allocating something very big (it knows if it just got the memory
  137. * from the OS in a pre-zeroed state). We don't want to use tor_malloc_zero
  138. * for big stuff, so we don't bother with calloc. */
  139. void *result = _tor_malloc(size DMALLOC_FN_ARGS);
  140. memset(result, 0, size);
  141. return result;
  142. }
  143. /** Change the size of the memory block pointed to by <b>ptr</b> to <b>size</b>
  144. * bytes long; return the new memory block. On error, log and
  145. * terminate. (Like realloc(ptr,size), but never returns NULL.)
  146. */
  147. void *
  148. _tor_realloc(void *ptr, size_t size DMALLOC_PARAMS)
  149. {
  150. void *result;
  151. #ifdef USE_DMALLOC
  152. result = dmalloc_realloc(file, line, ptr, size, DMALLOC_FUNC_REALLOC, 0);
  153. #else
  154. result = realloc(ptr, size);
  155. #endif
  156. if (PREDICT_UNLIKELY(result == NULL)) {
  157. log_err(LD_MM,"Out of memory on realloc(). Dying.");
  158. exit(1);
  159. }
  160. return result;
  161. }
  162. /** Return a newly allocated copy of the NUL-terminated string s. On
  163. * error, log and terminate. (Like strdup(s), but never returns
  164. * NULL.)
  165. */
  166. char *
  167. _tor_strdup(const char *s DMALLOC_PARAMS)
  168. {
  169. char *dup;
  170. tor_assert(s);
  171. #ifdef USE_DMALLOC
  172. dup = dmalloc_strdup(file, line, s, 0);
  173. #else
  174. dup = strdup(s);
  175. #endif
  176. if (PREDICT_UNLIKELY(dup == NULL)) {
  177. log_err(LD_MM,"Out of memory on strdup(). Dying.");
  178. exit(1);
  179. }
  180. return dup;
  181. }
  182. /** Allocate and return a new string containing the first <b>n</b>
  183. * characters of <b>s</b>. If <b>s</b> is longer than <b>n</b>
  184. * characters, only the first <b>n</b> are copied. The result is
  185. * always NUL-terminated. (Like strndup(s,n), but never returns
  186. * NULL.)
  187. */
  188. char *
  189. _tor_strndup(const char *s, size_t n DMALLOC_PARAMS)
  190. {
  191. char *dup;
  192. tor_assert(s);
  193. dup = _tor_malloc((n+1) DMALLOC_FN_ARGS);
  194. /* Performance note: Ordinarily we prefer strlcpy to strncpy. But
  195. * this function gets called a whole lot, and platform strncpy is
  196. * much faster than strlcpy when strlen(s) is much longer than n.
  197. */
  198. strncpy(dup, s, n);
  199. dup[n]='\0';
  200. return dup;
  201. }
  202. /** Allocate a chunk of <b>len</b> bytes, with the same contents as the
  203. * <b>len</b> bytes starting at <b>mem</b>. */
  204. void *
  205. _tor_memdup(const void *mem, size_t len DMALLOC_PARAMS)
  206. {
  207. char *dup;
  208. tor_assert(mem);
  209. dup = _tor_malloc(len DMALLOC_FN_ARGS);
  210. memcpy(dup, mem, len);
  211. return dup;
  212. }
  213. /** Helper for places that need to take a function pointer to the right
  214. * spelling of "free()". */
  215. void
  216. _tor_free(void *mem)
  217. {
  218. tor_free(mem);
  219. }
  220. #if defined(HAVE_MALLOC_GOOD_SIZE) && !defined(HAVE_MALLOC_GOOD_SIZE_PROTOTYPE)
  221. /* Some version of Mac OSX have malloc_good_size in their libc, but not
  222. * actually defined in malloc/malloc.h. We detect this and work around it by
  223. * prototyping.
  224. */
  225. extern size_t malloc_good_size(size_t size);
  226. #endif
  227. /** Allocate and return a chunk of memory of size at least *<b>size</b>, using
  228. * the same resources we would use to malloc *<b>sizep</b>. Set *<b>sizep</b>
  229. * to the number of usable bytes in the chunk of memory. */
  230. void *
  231. _tor_malloc_roundup(size_t *sizep DMALLOC_PARAMS)
  232. {
  233. #ifdef HAVE_MALLOC_GOOD_SIZE
  234. *sizep = malloc_good_size(*sizep);
  235. return _tor_malloc(*sizep DMALLOC_FN_ARGS);
  236. #elif 0 && defined(HAVE_MALLOC_USABLE_SIZE) && !defined(USE_DMALLOC)
  237. /* Never use malloc_usable_size(); it makes valgrind really unhappy,
  238. * and doesn't win much in terms of usable space where it exists. */
  239. void *result = _tor_malloc(*sizep DMALLOC_FN_ARGS);
  240. *sizep = malloc_usable_size(result);
  241. return result;
  242. #else
  243. return _tor_malloc(*sizep DMALLOC_FN_ARGS);
  244. #endif
  245. }
  246. /** Call the platform malloc info function, and dump the results to the log at
  247. * level <b>severity</b>. If no such function exists, do nothing. */
  248. void
  249. tor_log_mallinfo(int severity)
  250. {
  251. #ifdef HAVE_MALLINFO
  252. struct mallinfo mi;
  253. memset(&mi, 0, sizeof(mi));
  254. mi = mallinfo();
  255. log(severity, LD_MM,
  256. "mallinfo() said: arena=%d, ordblks=%d, smblks=%d, hblks=%d, "
  257. "hblkhd=%d, usmblks=%d, fsmblks=%d, uordblks=%d, fordblks=%d, "
  258. "keepcost=%d",
  259. mi.arena, mi.ordblks, mi.smblks, mi.hblks,
  260. mi.hblkhd, mi.usmblks, mi.fsmblks, mi.uordblks, mi.fordblks,
  261. mi.keepcost);
  262. #else
  263. (void)severity;
  264. #endif
  265. #ifdef USE_DMALLOC
  266. dmalloc_log_changed(0, /* Since the program started. */
  267. 1, /* Log info about non-freed pointers. */
  268. 0, /* Do not log info about freed pointers. */
  269. 0 /* Do not log individual pointers. */
  270. );
  271. #endif
  272. }
  273. /* =====
  274. * Math
  275. * ===== */
  276. /** Returns floor(log2(u64)). If u64 is 0, (incorrectly) returns 0. */
  277. int
  278. tor_log2(uint64_t u64)
  279. {
  280. int r = 0;
  281. if (u64 >= (U64_LITERAL(1)<<32)) {
  282. u64 >>= 32;
  283. r = 32;
  284. }
  285. if (u64 >= (U64_LITERAL(1)<<16)) {
  286. u64 >>= 16;
  287. r += 16;
  288. }
  289. if (u64 >= (U64_LITERAL(1)<<8)) {
  290. u64 >>= 8;
  291. r += 8;
  292. }
  293. if (u64 >= (U64_LITERAL(1)<<4)) {
  294. u64 >>= 4;
  295. r += 4;
  296. }
  297. if (u64 >= (U64_LITERAL(1)<<2)) {
  298. u64 >>= 2;
  299. r += 2;
  300. }
  301. if (u64 >= (U64_LITERAL(1)<<1)) {
  302. u64 >>= 1;
  303. r += 1;
  304. }
  305. return r;
  306. }
  307. /** Return the power of 2 closest to <b>u64</b>. */
  308. uint64_t
  309. round_to_power_of_2(uint64_t u64)
  310. {
  311. int lg2 = tor_log2(u64);
  312. uint64_t low = U64_LITERAL(1) << lg2, high = U64_LITERAL(1) << (lg2+1);
  313. if (high - u64 < u64 - low)
  314. return high;
  315. else
  316. return low;
  317. }
  318. /* =====
  319. * String manipulation
  320. * ===== */
  321. /** Remove from the string <b>s</b> every character which appears in
  322. * <b>strip</b>. */
  323. void
  324. tor_strstrip(char *s, const char *strip)
  325. {
  326. char *read = s;
  327. while (*read) {
  328. if (strchr(strip, *read)) {
  329. ++read;
  330. } else {
  331. *s++ = *read++;
  332. }
  333. }
  334. *s = '\0';
  335. }
  336. /** Return a pointer to a NUL-terminated hexadecimal string encoding
  337. * the first <b>fromlen</b> bytes of <b>from</b>. (fromlen must be \<= 32.) The
  338. * result does not need to be deallocated, but repeated calls to
  339. * hex_str will trash old results.
  340. */
  341. const char *
  342. hex_str(const char *from, size_t fromlen)
  343. {
  344. static char buf[65];
  345. if (fromlen>(sizeof(buf)-1)/2)
  346. fromlen = (sizeof(buf)-1)/2;
  347. base16_encode(buf,sizeof(buf),from,fromlen);
  348. return buf;
  349. }
  350. /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
  351. * lowercase. */
  352. void
  353. tor_strlower(char *s)
  354. {
  355. while (*s) {
  356. *s = TOR_TOLOWER(*s);
  357. ++s;
  358. }
  359. }
  360. /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
  361. * lowercase. */
  362. void
  363. tor_strupper(char *s)
  364. {
  365. while (*s) {
  366. *s = TOR_TOUPPER(*s);
  367. ++s;
  368. }
  369. }
  370. /** Return 1 if every character in <b>s</b> is printable, else return 0.
  371. */
  372. int
  373. tor_strisprint(const char *s)
  374. {
  375. while (*s) {
  376. if (!TOR_ISPRINT(*s))
  377. return 0;
  378. s++;
  379. }
  380. return 1;
  381. }
  382. /** Return 1 if no character in <b>s</b> is uppercase, else return 0.
  383. */
  384. int
  385. tor_strisnonupper(const char *s)
  386. {
  387. while (*s) {
  388. if (TOR_ISUPPER(*s))
  389. return 0;
  390. s++;
  391. }
  392. return 1;
  393. }
  394. /** Compares the first strlen(s2) characters of s1 with s2. Returns as for
  395. * strcmp.
  396. */
  397. int
  398. strcmpstart(const char *s1, const char *s2)
  399. {
  400. size_t n = strlen(s2);
  401. return strncmp(s1, s2, n);
  402. }
  403. /** Compare the s1_len-byte string <b>s1</b> with <b>s2</b>,
  404. * without depending on a terminating nul in s1. Sorting order is first by
  405. * length, then lexically; return values are as for strcmp.
  406. */
  407. int
  408. strcmp_len(const char *s1, const char *s2, size_t s1_len)
  409. {
  410. size_t s2_len = strlen(s2);
  411. if (s1_len < s2_len)
  412. return -1;
  413. if (s1_len > s2_len)
  414. return 1;
  415. return memcmp(s1, s2, s2_len);
  416. }
  417. /** Compares the first strlen(s2) characters of s1 with s2. Returns as for
  418. * strcasecmp.
  419. */
  420. int
  421. strcasecmpstart(const char *s1, const char *s2)
  422. {
  423. size_t n = strlen(s2);
  424. return strncasecmp(s1, s2, n);
  425. }
  426. /** Compares the last strlen(s2) characters of s1 with s2. Returns as for
  427. * strcmp.
  428. */
  429. int
  430. strcmpend(const char *s1, const char *s2)
  431. {
  432. size_t n1 = strlen(s1), n2 = strlen(s2);
  433. if (n2>n1)
  434. return strcmp(s1,s2);
  435. else
  436. return strncmp(s1+(n1-n2), s2, n2);
  437. }
  438. /** Compares the last strlen(s2) characters of s1 with s2. Returns as for
  439. * strcasecmp.
  440. */
  441. int
  442. strcasecmpend(const char *s1, const char *s2)
  443. {
  444. size_t n1 = strlen(s1), n2 = strlen(s2);
  445. if (n2>n1) /* then they can't be the same; figure out which is bigger */
  446. return strcasecmp(s1,s2);
  447. else
  448. return strncasecmp(s1+(n1-n2), s2, n2);
  449. }
  450. /** Compare the value of the string <b>prefix</b> with the start of the
  451. * <b>memlen</b>-byte memory chunk at <b>mem</b>. Return as for strcmp.
  452. *
  453. * [As memcmp(mem, prefix, strlen(prefix)) but returns -1 if memlen is less
  454. * than strlen(prefix).]
  455. */
  456. int
  457. memcmpstart(const void *mem, size_t memlen,
  458. const char *prefix)
  459. {
  460. size_t plen = strlen(prefix);
  461. if (memlen < plen)
  462. return -1;
  463. return memcmp(mem, prefix, plen);
  464. }
  465. /** Return a pointer to the first char of s that is not whitespace and
  466. * not a comment, or to the terminating NUL if no such character exists.
  467. */
  468. const char *
  469. eat_whitespace(const char *s)
  470. {
  471. tor_assert(s);
  472. while (1) {
  473. switch (*s) {
  474. case '\0':
  475. default:
  476. return s;
  477. case ' ':
  478. case '\t':
  479. case '\n':
  480. case '\r':
  481. ++s;
  482. break;
  483. case '#':
  484. ++s;
  485. while (*s && *s != '\n')
  486. ++s;
  487. }
  488. }
  489. }
  490. /** Return a pointer to the first char of s that is not whitespace and
  491. * not a comment, or to the terminating NUL if no such character exists.
  492. */
  493. const char *
  494. eat_whitespace_eos(const char *s, const char *eos)
  495. {
  496. tor_assert(s);
  497. tor_assert(eos && s <= eos);
  498. while (s < eos) {
  499. switch (*s) {
  500. case '\0':
  501. default:
  502. return s;
  503. case ' ':
  504. case '\t':
  505. case '\n':
  506. case '\r':
  507. ++s;
  508. break;
  509. case '#':
  510. ++s;
  511. while (s < eos && *s && *s != '\n')
  512. ++s;
  513. }
  514. }
  515. return s;
  516. }
  517. /** Return a pointer to the first char of s that is not a space or a tab
  518. * or a \\r, or to the terminating NUL if no such character exists. */
  519. const char *
  520. eat_whitespace_no_nl(const char *s)
  521. {
  522. while (*s == ' ' || *s == '\t' || *s == '\r')
  523. ++s;
  524. return s;
  525. }
  526. /** As eat_whitespace_no_nl, but stop at <b>eos</b> whether we have
  527. * found a non-whitespace character or not. */
  528. const char *
  529. eat_whitespace_eos_no_nl(const char *s, const char *eos)
  530. {
  531. while (s < eos && (*s == ' ' || *s == '\t' || *s == '\r'))
  532. ++s;
  533. return s;
  534. }
  535. /** Return a pointer to the first char of s that is whitespace or <b>#</b>,
  536. * or to the terminating NUL if no such character exists.
  537. */
  538. const char *
  539. find_whitespace(const char *s)
  540. {
  541. /* tor_assert(s); */
  542. while (1) {
  543. switch (*s)
  544. {
  545. case '\0':
  546. case '#':
  547. case ' ':
  548. case '\r':
  549. case '\n':
  550. case '\t':
  551. return s;
  552. default:
  553. ++s;
  554. }
  555. }
  556. }
  557. /** As find_whitespace, but stop at <b>eos</b> whether we have found a
  558. * whitespace or not. */
  559. const char *
  560. find_whitespace_eos(const char *s, const char *eos)
  561. {
  562. /* tor_assert(s); */
  563. while (s < eos) {
  564. switch (*s)
  565. {
  566. case '\0':
  567. case '#':
  568. case ' ':
  569. case '\r':
  570. case '\n':
  571. case '\t':
  572. return s;
  573. default:
  574. ++s;
  575. }
  576. }
  577. return s;
  578. }
  579. /** Return true iff the 'len' bytes at 'mem' are all zero. */
  580. int
  581. tor_mem_is_zero(const char *mem, size_t len)
  582. {
  583. static const char ZERO[] = {
  584. 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
  585. };
  586. while (len >= sizeof(ZERO)) {
  587. if (memcmp(mem, ZERO, sizeof(ZERO)))
  588. return 0;
  589. len -= sizeof(ZERO);
  590. mem += sizeof(ZERO);
  591. }
  592. /* Deal with leftover bytes. */
  593. if (len)
  594. return ! memcmp(mem, ZERO, len);
  595. return 1;
  596. }
  597. /** Return true iff the DIGEST_LEN bytes in digest are all zero. */
  598. int
  599. tor_digest_is_zero(const char *digest)
  600. {
  601. return tor_mem_is_zero(digest, DIGEST_LEN);
  602. }
  603. /* Helper: common code to check whether the result of a strtol or strtoul or
  604. * strtoll is correct. */
  605. #define CHECK_STRTOX_RESULT() \
  606. /* Was at least one character converted? */ \
  607. if (endptr == s) \
  608. goto err; \
  609. /* Were there unexpected unconverted characters? */ \
  610. if (!next && *endptr) \
  611. goto err; \
  612. /* Is r within limits? */ \
  613. if (r < min || r > max) \
  614. goto err; \
  615. if (ok) *ok = 1; \
  616. if (next) *next = endptr; \
  617. return r; \
  618. err: \
  619. if (ok) *ok = 0; \
  620. if (next) *next = endptr; \
  621. return 0
  622. /** Extract a long from the start of s, in the given numeric base. If
  623. * there is unconverted data and next is provided, set *next to the
  624. * first unconverted character. An error has occurred if no characters
  625. * are converted; or if there are unconverted characters and next is NULL; or
  626. * if the parsed value is not between min and max. When no error occurs,
  627. * return the parsed value and set *ok (if provided) to 1. When an error
  628. * occurs, return 0 and set *ok (if provided) to 0.
  629. */
  630. long
  631. tor_parse_long(const char *s, int base, long min, long max,
  632. int *ok, char **next)
  633. {
  634. char *endptr;
  635. long r;
  636. r = strtol(s, &endptr, base);
  637. CHECK_STRTOX_RESULT();
  638. }
  639. /** As tor_parse_long(), but return an unsigned long. */
  640. unsigned long
  641. tor_parse_ulong(const char *s, int base, unsigned long min,
  642. unsigned long max, int *ok, char **next)
  643. {
  644. char *endptr;
  645. unsigned long r;
  646. r = strtoul(s, &endptr, base);
  647. CHECK_STRTOX_RESULT();
  648. }
  649. /** As tor_parse_log, but return a unit64_t. Only base 10 is guaranteed to
  650. * work for now. */
  651. uint64_t
  652. tor_parse_uint64(const char *s, int base, uint64_t min,
  653. uint64_t max, int *ok, char **next)
  654. {
  655. char *endptr;
  656. uint64_t r;
  657. #ifdef HAVE_STRTOULL
  658. r = (uint64_t)strtoull(s, &endptr, base);
  659. #elif defined(MS_WINDOWS)
  660. #if defined(_MSC_VER) && _MSC_VER < 1300
  661. tor_assert(base <= 10);
  662. r = (uint64_t)_atoi64(s);
  663. endptr = (char*)s;
  664. while (TOR_ISSPACE(*endptr)) endptr++;
  665. while (TOR_ISDIGIT(*endptr)) endptr++;
  666. #else
  667. r = (uint64_t)_strtoui64(s, &endptr, base);
  668. #endif
  669. #elif SIZEOF_LONG == 8
  670. r = (uint64_t)strtoul(s, &endptr, base);
  671. #else
  672. #error "I don't know how to parse 64-bit numbers."
  673. #endif
  674. CHECK_STRTOX_RESULT();
  675. }
  676. /** Encode the <b>srclen</b> bytes at <b>src</b> in a NUL-terminated,
  677. * uppercase hexadecimal string; store it in the <b>destlen</b>-byte buffer
  678. * <b>dest</b>.
  679. */
  680. void
  681. base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  682. {
  683. const char *end;
  684. char *cp;
  685. tor_assert(destlen >= srclen*2+1);
  686. tor_assert(destlen < SIZE_T_CEILING);
  687. cp = dest;
  688. end = src+srclen;
  689. while (src<end) {
  690. *cp++ = "0123456789ABCDEF"[ (*(const uint8_t*)src) >> 4 ];
  691. *cp++ = "0123456789ABCDEF"[ (*(const uint8_t*)src) & 0xf ];
  692. ++src;
  693. }
  694. *cp = '\0';
  695. }
  696. /** Helper: given a hex digit, return its value, or -1 if it isn't hex. */
  697. static INLINE int
  698. _hex_decode_digit(char c)
  699. {
  700. switch (c) {
  701. case '0': return 0;
  702. case '1': return 1;
  703. case '2': return 2;
  704. case '3': return 3;
  705. case '4': return 4;
  706. case '5': return 5;
  707. case '6': return 6;
  708. case '7': return 7;
  709. case '8': return 8;
  710. case '9': return 9;
  711. case 'A': case 'a': return 10;
  712. case 'B': case 'b': return 11;
  713. case 'C': case 'c': return 12;
  714. case 'D': case 'd': return 13;
  715. case 'E': case 'e': return 14;
  716. case 'F': case 'f': return 15;
  717. default:
  718. return -1;
  719. }
  720. }
  721. /** Helper: given a hex digit, return its value, or -1 if it isn't hex. */
  722. int
  723. hex_decode_digit(char c)
  724. {
  725. return _hex_decode_digit(c);
  726. }
  727. /** Given a hexadecimal string of <b>srclen</b> bytes in <b>src</b>, decode it
  728. * and store the result in the <b>destlen</b>-byte buffer at <b>dest</b>.
  729. * Return 0 on success, -1 on failure. */
  730. int
  731. base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  732. {
  733. const char *end;
  734. int v1,v2;
  735. if ((srclen % 2) != 0)
  736. return -1;
  737. if (destlen < srclen/2 || destlen > SIZE_T_CEILING)
  738. return -1;
  739. end = src+srclen;
  740. while (src<end) {
  741. v1 = _hex_decode_digit(*src);
  742. v2 = _hex_decode_digit(*(src+1));
  743. if (v1<0||v2<0)
  744. return -1;
  745. *(uint8_t*)dest = (v1<<4)|v2;
  746. ++dest;
  747. src+=2;
  748. }
  749. return 0;
  750. }
  751. /** Allocate and return a new string representing the contents of <b>s</b>,
  752. * surrounded by quotes and using standard C escapes.
  753. *
  754. * Generally, we use this for logging values that come in over the network to
  755. * keep them from tricking users, and for sending certain values to the
  756. * controller.
  757. *
  758. * We trust values from the resolver, OS, configuration file, and command line
  759. * to not be maliciously ill-formed. We validate incoming routerdescs and
  760. * SOCKS requests and addresses from BEGIN cells as they're parsed;
  761. * afterwards, we trust them as non-malicious.
  762. */
  763. char *
  764. esc_for_log(const char *s)
  765. {
  766. const char *cp;
  767. char *result, *outp;
  768. size_t len = 3;
  769. if (!s) {
  770. return tor_strdup("");
  771. }
  772. for (cp = s; *cp; ++cp) {
  773. switch (*cp) {
  774. case '\\':
  775. case '\"':
  776. case '\'':
  777. len += 2;
  778. break;
  779. default:
  780. if (TOR_ISPRINT(*cp) && ((uint8_t)*cp)<127)
  781. ++len;
  782. else
  783. len += 4;
  784. break;
  785. }
  786. }
  787. result = outp = tor_malloc(len);
  788. *outp++ = '\"';
  789. for (cp = s; *cp; ++cp) {
  790. switch (*cp) {
  791. case '\\':
  792. case '\"':
  793. case '\'':
  794. *outp++ = '\\';
  795. *outp++ = *cp;
  796. break;
  797. case '\n':
  798. *outp++ = '\\';
  799. *outp++ = 'n';
  800. break;
  801. case '\t':
  802. *outp++ = '\\';
  803. *outp++ = 't';
  804. break;
  805. case '\r':
  806. *outp++ = '\\';
  807. *outp++ = 'r';
  808. break;
  809. default:
  810. if (TOR_ISPRINT(*cp) && ((uint8_t)*cp)<127) {
  811. *outp++ = *cp;
  812. } else {
  813. tor_snprintf(outp, 5, "\\%03o", (int)(uint8_t) *cp);
  814. outp += 4;
  815. }
  816. break;
  817. }
  818. }
  819. *outp++ = '\"';
  820. *outp++ = 0;
  821. return result;
  822. }
  823. /** Allocate and return a new string representing the contents of <b>s</b>,
  824. * surrounded by quotes and using standard C escapes.
  825. *
  826. * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
  827. * thread. Also, each call invalidates the last-returned value, so don't
  828. * try log_warn(LD_GENERAL, "%s %s", escaped(a), escaped(b));
  829. */
  830. const char *
  831. escaped(const char *s)
  832. {
  833. static char *_escaped_val = NULL;
  834. if (_escaped_val)
  835. tor_free(_escaped_val);
  836. if (s)
  837. _escaped_val = esc_for_log(s);
  838. else
  839. _escaped_val = NULL;
  840. return _escaped_val;
  841. }
  842. /** Rudimentary string wrapping code: given a un-wrapped <b>string</b> (no
  843. * newlines!), break the string into newline-terminated lines of no more than
  844. * <b>width</b> characters long (not counting newline) and insert them into
  845. * <b>out</b> in order. Precede the first line with prefix0, and subsequent
  846. * lines with prefixRest.
  847. */
  848. /* This uses a stupid greedy wrapping algorithm right now:
  849. * - For each line:
  850. * - Try to fit as much stuff as possible, but break on a space.
  851. * - If the first "word" of the line will extend beyond the allowable
  852. * width, break the word at the end of the width.
  853. */
  854. void
  855. wrap_string(smartlist_t *out, const char *string, size_t width,
  856. const char *prefix0, const char *prefixRest)
  857. {
  858. size_t p0Len, pRestLen, pCurLen;
  859. const char *eos, *prefixCur;
  860. tor_assert(out);
  861. tor_assert(string);
  862. tor_assert(width);
  863. if (!prefix0)
  864. prefix0 = "";
  865. if (!prefixRest)
  866. prefixRest = "";
  867. p0Len = strlen(prefix0);
  868. pRestLen = strlen(prefixRest);
  869. tor_assert(width > p0Len && width > pRestLen);
  870. eos = strchr(string, '\0');
  871. tor_assert(eos);
  872. pCurLen = p0Len;
  873. prefixCur = prefix0;
  874. while ((eos-string)+pCurLen > width) {
  875. const char *eol = string + width - pCurLen;
  876. while (eol > string && *eol != ' ')
  877. --eol;
  878. /* eol is now the last space that can fit, or the start of the string. */
  879. if (eol > string) {
  880. size_t line_len = (eol-string) + pCurLen + 2;
  881. char *line = tor_malloc(line_len);
  882. memcpy(line, prefixCur, pCurLen);
  883. memcpy(line+pCurLen, string, eol-string);
  884. line[line_len-2] = '\n';
  885. line[line_len-1] = '\0';
  886. smartlist_add(out, line);
  887. string = eol + 1;
  888. } else {
  889. size_t line_len = width + 2;
  890. char *line = tor_malloc(line_len);
  891. memcpy(line, prefixCur, pCurLen);
  892. memcpy(line+pCurLen, string, width - pCurLen);
  893. line[line_len-2] = '\n';
  894. line[line_len-1] = '\0';
  895. smartlist_add(out, line);
  896. string += width-pCurLen;
  897. }
  898. prefixCur = prefixRest;
  899. pCurLen = pRestLen;
  900. }
  901. if (string < eos) {
  902. size_t line_len = (eos-string) + pCurLen + 2;
  903. char *line = tor_malloc(line_len);
  904. memcpy(line, prefixCur, pCurLen);
  905. memcpy(line+pCurLen, string, eos-string);
  906. line[line_len-2] = '\n';
  907. line[line_len-1] = '\0';
  908. smartlist_add(out, line);
  909. }
  910. }
  911. /* =====
  912. * Time
  913. * ===== */
  914. /** Return the number of microseconds elapsed between *start and *end.
  915. */
  916. long
  917. tv_udiff(const struct timeval *start, const struct timeval *end)
  918. {
  919. long udiff;
  920. long secdiff = end->tv_sec - start->tv_sec;
  921. if (labs(secdiff+1) > LONG_MAX/1000000) {
  922. log_warn(LD_GENERAL, "comparing times too far apart.");
  923. return LONG_MAX;
  924. }
  925. udiff = secdiff*1000000L + (end->tv_usec - start->tv_usec);
  926. return udiff;
  927. }
  928. /** Yield true iff <b>y</b> is a leap-year. */
  929. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  930. /** Helper: Return the number of leap-days between Jan 1, y1 and Jan 1, y2. */
  931. static int
  932. n_leapdays(int y1, int y2)
  933. {
  934. --y1;
  935. --y2;
  936. return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
  937. }
  938. /** Number of days per month in non-leap year; used by tor_timegm. */
  939. static const int days_per_month[] =
  940. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  941. /** Return a time_t given a struct tm. The result is given in GMT, and
  942. * does not account for leap seconds.
  943. */
  944. time_t
  945. tor_timegm(struct tm *tm)
  946. {
  947. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  948. * It's way more brute-force than fiddling with tzset().
  949. */
  950. time_t year, days, hours, minutes, seconds;
  951. int i;
  952. year = tm->tm_year + 1900;
  953. if (year < 1970 || tm->tm_mon < 0 || tm->tm_mon > 11) {
  954. log_warn(LD_BUG, "Out-of-range argument to tor_timegm");
  955. return -1;
  956. }
  957. tor_assert(year < INT_MAX);
  958. days = 365 * (year-1970) + n_leapdays(1970,(int)year);
  959. for (i = 0; i < tm->tm_mon; ++i)
  960. days += days_per_month[i];
  961. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  962. ++days;
  963. days += tm->tm_mday - 1;
  964. hours = days*24 + tm->tm_hour;
  965. minutes = hours*60 + tm->tm_min;
  966. seconds = minutes*60 + tm->tm_sec;
  967. return seconds;
  968. }
  969. /* strftime is locale-specific, so we need to replace those parts */
  970. /** A c-locale array of 3-letter names of weekdays, starting with Sun. */
  971. static const char *WEEKDAY_NAMES[] =
  972. { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  973. /** A c-locale array of 3-letter names of months, starting with Jan. */
  974. static const char *MONTH_NAMES[] =
  975. { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  976. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  977. /** Set <b>buf</b> to the RFC1123 encoding of the GMT value of <b>t</b>.
  978. * The buffer must be at least RFC1123_TIME_LEN+1 bytes long.
  979. *
  980. * (RFC1123 format is Fri, 29 Sep 2006 15:54:20 GMT)
  981. */
  982. void
  983. format_rfc1123_time(char *buf, time_t t)
  984. {
  985. struct tm tm;
  986. tor_gmtime_r(&t, &tm);
  987. strftime(buf, RFC1123_TIME_LEN+1, "___, %d ___ %Y %H:%M:%S GMT", &tm);
  988. tor_assert(tm.tm_wday >= 0);
  989. tor_assert(tm.tm_wday <= 6);
  990. memcpy(buf, WEEKDAY_NAMES[tm.tm_wday], 3);
  991. tor_assert(tm.tm_wday >= 0);
  992. tor_assert(tm.tm_mon <= 11);
  993. memcpy(buf+8, MONTH_NAMES[tm.tm_mon], 3);
  994. }
  995. /** Parse the the RFC1123 encoding of some time (in GMT) from <b>buf</b>,
  996. * and store the result in *<b>t</b>.
  997. *
  998. * Return 0 on success, -1 on failure.
  999. */
  1000. int
  1001. parse_rfc1123_time(const char *buf, time_t *t)
  1002. {
  1003. struct tm tm;
  1004. char month[4];
  1005. char weekday[4];
  1006. int i, m;
  1007. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  1008. if (strlen(buf) != RFC1123_TIME_LEN)
  1009. return -1;
  1010. memset(&tm, 0, sizeof(tm));
  1011. if (tor_sscanf(buf, "%3s, %2u %3s %u %2u:%2u:%2u GMT", weekday,
  1012. &tm_mday, month, &tm_year, &tm_hour,
  1013. &tm_min, &tm_sec) < 7) {
  1014. char *esc = esc_for_log(buf);
  1015. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  1016. tor_free(esc);
  1017. return -1;
  1018. }
  1019. if (tm_mday > 31 || tm_hour > 23 || tm_min > 59 || tm_sec > 61) {
  1020. char *esc = esc_for_log(buf);
  1021. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  1022. tor_free(esc);
  1023. return -1;
  1024. }
  1025. tm.tm_mday = (int)tm_mday;
  1026. tm.tm_year = (int)tm_year;
  1027. tm.tm_hour = (int)tm_hour;
  1028. tm.tm_min = (int)tm_min;
  1029. tm.tm_sec = (int)tm_sec;
  1030. m = -1;
  1031. for (i = 0; i < 12; ++i) {
  1032. if (!strcmp(month, MONTH_NAMES[i])) {
  1033. m = i;
  1034. break;
  1035. }
  1036. }
  1037. if (m<0) {
  1038. char *esc = esc_for_log(buf);
  1039. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s: No such month", esc);
  1040. tor_free(esc);
  1041. return -1;
  1042. }
  1043. tm.tm_mon = m;
  1044. if (tm.tm_year < 1970) {
  1045. char *esc = esc_for_log(buf);
  1046. log_warn(LD_GENERAL,
  1047. "Got invalid RFC1123 time %s. (Before 1970)", esc);
  1048. tor_free(esc);
  1049. return -1;
  1050. }
  1051. tm.tm_year -= 1900;
  1052. *t = tor_timegm(&tm);
  1053. return 0;
  1054. }
  1055. /** Set <b>buf</b> to the ISO8601 encoding of the local value of <b>t</b>.
  1056. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  1057. *
  1058. * (ISO8601 format is 2006-10-29 10:57:20)
  1059. */
  1060. void
  1061. format_local_iso_time(char *buf, time_t t)
  1062. {
  1063. struct tm tm;
  1064. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t, &tm));
  1065. }
  1066. /** Set <b>buf</b> to the ISO8601 encoding of the GMT value of <b>t</b>.
  1067. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  1068. */
  1069. void
  1070. format_iso_time(char *buf, time_t t)
  1071. {
  1072. struct tm tm;
  1073. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t, &tm));
  1074. }
  1075. /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
  1076. * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
  1077. * failure. Ignore extraneous stuff in <b>cp</b> separated by whitespace from
  1078. * the end of the time string. */
  1079. int
  1080. parse_iso_time(const char *cp, time_t *t)
  1081. {
  1082. struct tm st_tm;
  1083. unsigned int year=0, month=0, day=0, hour=100, minute=100, second=100;
  1084. if (tor_sscanf(cp, "%u-%2u-%2u %2u:%2u:%2u", &year, &month,
  1085. &day, &hour, &minute, &second) < 6) {
  1086. char *esc = esc_for_log(cp);
  1087. log_warn(LD_GENERAL, "ISO time %s was unparseable", esc);
  1088. tor_free(esc);
  1089. return -1;
  1090. }
  1091. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  1092. hour > 23 || minute > 59 || second > 61) {
  1093. char *esc = esc_for_log(cp);
  1094. log_warn(LD_GENERAL, "ISO time %s was nonsensical", esc);
  1095. tor_free(esc);
  1096. return -1;
  1097. }
  1098. st_tm.tm_year = year-1900;
  1099. st_tm.tm_mon = month-1;
  1100. st_tm.tm_mday = day;
  1101. st_tm.tm_hour = hour;
  1102. st_tm.tm_min = minute;
  1103. st_tm.tm_sec = second;
  1104. if (st_tm.tm_year < 70) {
  1105. char *esc = esc_for_log(cp);
  1106. log_warn(LD_GENERAL, "Got invalid ISO time %s. (Before 1970)", esc);
  1107. tor_free(esc);
  1108. return -1;
  1109. }
  1110. *t = tor_timegm(&st_tm);
  1111. return 0;
  1112. }
  1113. /** Given a <b>date</b> in one of the three formats allowed by HTTP (ugh),
  1114. * parse it into <b>tm</b>. Return 0 on success, negative on failure. */
  1115. int
  1116. parse_http_time(const char *date, struct tm *tm)
  1117. {
  1118. const char *cp;
  1119. char month[4];
  1120. char wkday[4];
  1121. int i;
  1122. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  1123. tor_assert(tm);
  1124. memset(tm, 0, sizeof(*tm));
  1125. /* First, try RFC1123 or RFC850 format: skip the weekday. */
  1126. if ((cp = strchr(date, ','))) {
  1127. ++cp;
  1128. if (tor_sscanf(date, "%2u %3s %4u %2u:%2u:%2u GMT",
  1129. &tm_mday, month, &tm_year,
  1130. &tm_hour, &tm_min, &tm_sec) == 6) {
  1131. /* rfc1123-date */
  1132. tm_year -= 1900;
  1133. } else if (tor_sscanf(date, "%2u-%3s-%2u %2u:%2u:%2u GMT",
  1134. &tm_mday, month, &tm_year,
  1135. &tm_hour, &tm_min, &tm_sec) == 6) {
  1136. /* rfc850-date */
  1137. } else {
  1138. return -1;
  1139. }
  1140. } else {
  1141. /* No comma; possibly asctime() format. */
  1142. if (tor_sscanf(date, "%3s %3s %2u %2u:%2u:%2u %4u",
  1143. wkday, month, &tm_mday,
  1144. &tm_hour, &tm_min, &tm_sec, &tm_year) == 7) {
  1145. tm_year -= 1900;
  1146. } else {
  1147. return -1;
  1148. }
  1149. }
  1150. tm->tm_mday = (int)tm_mday;
  1151. tm->tm_year = (int)tm_year;
  1152. tm->tm_hour = (int)tm_hour;
  1153. tm->tm_min = (int)tm_min;
  1154. tm->tm_sec = (int)tm_sec;
  1155. month[3] = '\0';
  1156. /* Okay, now decode the month. */
  1157. for (i = 0; i < 12; ++i) {
  1158. if (!strcasecmp(MONTH_NAMES[i], month)) {
  1159. tm->tm_mon = i+1;
  1160. }
  1161. }
  1162. if (tm->tm_year < 0 ||
  1163. tm->tm_mon < 1 || tm->tm_mon > 12 ||
  1164. tm->tm_mday < 0 || tm->tm_mday > 31 ||
  1165. tm->tm_hour < 0 || tm->tm_hour > 23 ||
  1166. tm->tm_min < 0 || tm->tm_min > 59 ||
  1167. tm->tm_sec < 0 || tm->tm_sec > 61)
  1168. return -1; /* Out of range, or bad month. */
  1169. return 0;
  1170. }
  1171. /** Given an <b>interval</b> in seconds, try to write it to the
  1172. * <b>out_len</b>-byte buffer in <b>out</b> in a human-readable form.
  1173. * Return 0 on success, -1 on failure.
  1174. */
  1175. int
  1176. format_time_interval(char *out, size_t out_len, long interval)
  1177. {
  1178. /* We only report seconds if there's no hours. */
  1179. long sec = 0, min = 0, hour = 0, day = 0;
  1180. if (interval < 0)
  1181. interval = -interval;
  1182. if (interval >= 86400) {
  1183. day = interval / 86400;
  1184. interval %= 86400;
  1185. }
  1186. if (interval >= 3600) {
  1187. hour = interval / 3600;
  1188. interval %= 3600;
  1189. }
  1190. if (interval >= 60) {
  1191. min = interval / 60;
  1192. interval %= 60;
  1193. }
  1194. sec = interval;
  1195. if (day) {
  1196. return tor_snprintf(out, out_len, "%ld days, %ld hours, %ld minutes",
  1197. day, hour, min);
  1198. } else if (hour) {
  1199. return tor_snprintf(out, out_len, "%ld hours, %ld minutes", hour, min);
  1200. } else if (min) {
  1201. return tor_snprintf(out, out_len, "%ld minutes, %ld seconds", min, sec);
  1202. } else {
  1203. return tor_snprintf(out, out_len, "%ld seconds", sec);
  1204. }
  1205. }
  1206. /* =====
  1207. * Cached time
  1208. * ===== */
  1209. #ifndef TIME_IS_FAST
  1210. /** Cached estimate of the current time. Updated around once per second;
  1211. * may be a few seconds off if we are really busy. This is a hack to avoid
  1212. * calling time(NULL) (which not everybody has optimized) on critical paths.
  1213. */
  1214. static time_t cached_approx_time = 0;
  1215. /** Return a cached estimate of the current time from when
  1216. * update_approx_time() was last called. This is a hack to avoid calling
  1217. * time(NULL) on critical paths: please do not even think of calling it
  1218. * anywhere else. */
  1219. time_t
  1220. approx_time(void)
  1221. {
  1222. return cached_approx_time;
  1223. }
  1224. /** Update the cached estimate of the current time. This function SHOULD be
  1225. * called once per second, and MUST be called before the first call to
  1226. * get_approx_time. */
  1227. void
  1228. update_approx_time(time_t now)
  1229. {
  1230. cached_approx_time = now;
  1231. }
  1232. #endif
  1233. /* =====
  1234. * Fuzzy time
  1235. * XXXX022 Use this consistently or rip most of it out.
  1236. * ===== */
  1237. /* In a perfect world, everybody would run NTP, and NTP would be perfect, so
  1238. * if we wanted to know "Is the current time before time X?" we could just say
  1239. * "time(NULL) < X".
  1240. *
  1241. * But unfortunately, many users are running Tor in an imperfect world, on
  1242. * even more imperfect computers. Hence, we need to track time oddly. We
  1243. * model the user's computer as being "skewed" from accurate time by
  1244. * -<b>ftime_skew</b> seconds, such that our best guess of the current time is
  1245. * time(NULL)+ftime_skew. We also assume that our measurements of time may
  1246. * have up to <b>ftime_slop</b> seconds of inaccuracy; IOW, our window of
  1247. * estimate for the current time is now + ftime_skew +/- ftime_slop.
  1248. */
  1249. /** Our current estimate of our skew, such that we think the current time is
  1250. * closest to time(NULL)+ftime_skew. */
  1251. static int ftime_skew = 0;
  1252. /** Tolerance during time comparisons, in seconds. */
  1253. static int ftime_slop = 60;
  1254. /** Set the largest amount of sloppiness we'll allow in fuzzy time
  1255. * comparisons. */
  1256. void
  1257. ftime_set_maximum_sloppiness(int seconds)
  1258. {
  1259. tor_assert(seconds >= 0);
  1260. ftime_slop = seconds;
  1261. }
  1262. /** Set the amount by which we believe our system clock to differ from
  1263. * real time. */
  1264. void
  1265. ftime_set_estimated_skew(int seconds)
  1266. {
  1267. ftime_skew = seconds;
  1268. }
  1269. #if 0
  1270. void
  1271. ftime_get_window(time_t now, ftime_t *ft_out)
  1272. {
  1273. ft_out->earliest = now + ftime_skew - ftime_slop;
  1274. ft_out->latest = now + ftime_skew + ftime_slop;
  1275. }
  1276. #endif
  1277. /** Return true iff we think that <b>now</b> might be after <b>when</b>. */
  1278. int
  1279. ftime_maybe_after(time_t now, time_t when)
  1280. {
  1281. /* It may be after when iff the latest possible current time is after when */
  1282. return (now + ftime_skew + ftime_slop) >= when;
  1283. }
  1284. /** Return true iff we think that <b>now</b> might be before <b>when</b>. */
  1285. int
  1286. ftime_maybe_before(time_t now, time_t when)
  1287. {
  1288. /* It may be before when iff the earliest possible current time is before */
  1289. return (now + ftime_skew - ftime_slop) < when;
  1290. }
  1291. /** Return true if we think that <b>now</b> is definitely after <b>when</b>. */
  1292. int
  1293. ftime_definitely_after(time_t now, time_t when)
  1294. {
  1295. /* It is definitely after when if the earliest time it could be is still
  1296. * after when. */
  1297. return (now + ftime_skew - ftime_slop) >= when;
  1298. }
  1299. /** Return true if we think that <b>now</b> is definitely before <b>when</b>.
  1300. */
  1301. int
  1302. ftime_definitely_before(time_t now, time_t when)
  1303. {
  1304. /* It is definitely before when if the latest time it could be is still
  1305. * before when. */
  1306. return (now + ftime_skew + ftime_slop) < when;
  1307. }
  1308. /* =====
  1309. * File helpers
  1310. * ===== */
  1311. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  1312. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  1313. * was returned by open(). Return the number of bytes written, or -1
  1314. * on error. Only use if fd is a blocking fd. */
  1315. ssize_t
  1316. write_all(int fd, const char *buf, size_t count, int isSocket)
  1317. {
  1318. size_t written = 0;
  1319. ssize_t result;
  1320. tor_assert(count < SSIZE_T_MAX);
  1321. while (written != count) {
  1322. if (isSocket)
  1323. result = tor_socket_send(fd, buf+written, count-written, 0);
  1324. else
  1325. result = write(fd, buf+written, count-written);
  1326. if (result<0)
  1327. return -1;
  1328. written += result;
  1329. }
  1330. return (ssize_t)count;
  1331. }
  1332. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  1333. * or reach the end of the file. <b>isSocket</b> must be 1 if fd
  1334. * was returned by socket() or accept(), and 0 if fd was returned by
  1335. * open(). Return the number of bytes read, or -1 on error. Only use
  1336. * if fd is a blocking fd. */
  1337. ssize_t
  1338. read_all(int fd, char *buf, size_t count, int isSocket)
  1339. {
  1340. size_t numread = 0;
  1341. ssize_t result;
  1342. if (count > SIZE_T_CEILING || count > SSIZE_T_MAX)
  1343. return -1;
  1344. while (numread != count) {
  1345. if (isSocket)
  1346. result = tor_socket_recv(fd, buf+numread, count-numread, 0);
  1347. else
  1348. result = read(fd, buf+numread, count-numread);
  1349. if (result<0)
  1350. return -1;
  1351. else if (result == 0)
  1352. break;
  1353. numread += result;
  1354. }
  1355. return (ssize_t)numread;
  1356. }
  1357. /*
  1358. * Filesystem operations.
  1359. */
  1360. /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
  1361. * we do nothing. On Windows, we remove a trailing slash, unless the path is
  1362. * the root of a disk. */
  1363. static void
  1364. clean_name_for_stat(char *name)
  1365. {
  1366. #ifdef MS_WINDOWS
  1367. size_t len = strlen(name);
  1368. if (!len)
  1369. return;
  1370. if (name[len-1]=='\\' || name[len-1]=='/') {
  1371. if (len == 1 || (len==3 && name[1]==':'))
  1372. return;
  1373. name[len-1]='\0';
  1374. }
  1375. #else
  1376. (void)name;
  1377. #endif
  1378. }
  1379. /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  1380. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  1381. * directory. On FN_ERROR, sets errno. */
  1382. file_status_t
  1383. file_status(const char *fname)
  1384. {
  1385. struct stat st;
  1386. char *f;
  1387. int r;
  1388. f = tor_strdup(fname);
  1389. clean_name_for_stat(f);
  1390. r = stat(f, &st);
  1391. tor_free(f);
  1392. if (r) {
  1393. if (errno == ENOENT) {
  1394. return FN_NOENT;
  1395. }
  1396. return FN_ERROR;
  1397. }
  1398. if (st.st_mode & S_IFDIR)
  1399. return FN_DIR;
  1400. else if (st.st_mode & S_IFREG)
  1401. return FN_FILE;
  1402. else
  1403. return FN_ERROR;
  1404. }
  1405. /** Check whether dirname exists and is private. If yes return 0. If
  1406. * it does not exist, and check==CPD_CREATE is set, try to create it
  1407. * and return 0 on success. If it does not exist, and
  1408. * check==CPD_CHECK, and we think we can create it, return 0. Else
  1409. * return -1. */
  1410. int
  1411. check_private_dir(const char *dirname, cpd_check_t check)
  1412. {
  1413. int r;
  1414. struct stat st;
  1415. char *f;
  1416. tor_assert(dirname);
  1417. f = tor_strdup(dirname);
  1418. clean_name_for_stat(f);
  1419. r = stat(f, &st);
  1420. tor_free(f);
  1421. if (r) {
  1422. if (errno != ENOENT) {
  1423. log(LOG_WARN, LD_FS, "Directory %s cannot be read: %s", dirname,
  1424. strerror(errno));
  1425. return -1;
  1426. }
  1427. if (check == CPD_NONE) {
  1428. log(LOG_WARN, LD_FS, "Directory %s does not exist.", dirname);
  1429. return -1;
  1430. } else if (check == CPD_CREATE) {
  1431. log_info(LD_GENERAL, "Creating directory %s", dirname);
  1432. #ifdef MS_WINDOWS
  1433. r = mkdir(dirname);
  1434. #else
  1435. r = mkdir(dirname, 0700);
  1436. #endif
  1437. if (r) {
  1438. log(LOG_WARN, LD_FS, "Error creating directory %s: %s", dirname,
  1439. strerror(errno));
  1440. return -1;
  1441. }
  1442. }
  1443. /* XXXX In the case where check==CPD_CHECK, we should look at the
  1444. * parent directory a little harder. */
  1445. return 0;
  1446. }
  1447. if (!(st.st_mode & S_IFDIR)) {
  1448. log(LOG_WARN, LD_FS, "%s is not a directory", dirname);
  1449. return -1;
  1450. }
  1451. #ifndef MS_WINDOWS
  1452. if (st.st_uid != getuid()) {
  1453. struct passwd *pw = NULL;
  1454. char *process_ownername = NULL;
  1455. pw = getpwuid(getuid());
  1456. process_ownername = pw ? tor_strdup(pw->pw_name) : tor_strdup("<unknown>");
  1457. pw = getpwuid(st.st_uid);
  1458. log(LOG_WARN, LD_FS, "%s is not owned by this user (%s, %d) but by "
  1459. "%s (%d). Perhaps you are running Tor as the wrong user?",
  1460. dirname, process_ownername, (int)getuid(),
  1461. pw ? pw->pw_name : "<unknown>", (int)st.st_uid);
  1462. tor_free(process_ownername);
  1463. return -1;
  1464. }
  1465. if (st.st_mode & 0077) {
  1466. log(LOG_WARN, LD_FS, "Fixing permissions on directory %s", dirname);
  1467. if (chmod(dirname, 0700)) {
  1468. log(LOG_WARN, LD_FS, "Could not chmod directory %s: %s", dirname,
  1469. strerror(errno));
  1470. return -1;
  1471. } else {
  1472. return 0;
  1473. }
  1474. }
  1475. #endif
  1476. return 0;
  1477. }
  1478. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite
  1479. * the previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  1480. *
  1481. * This function replaces the old file atomically, if possible. This
  1482. * function, and all other functions in util.c that create files, create them
  1483. * with mode 0600.
  1484. */
  1485. int
  1486. write_str_to_file(const char *fname, const char *str, int bin)
  1487. {
  1488. #ifdef MS_WINDOWS
  1489. if (!bin && strchr(str, '\r')) {
  1490. log_warn(LD_BUG,
  1491. "We're writing a text string that already contains a CR.");
  1492. }
  1493. #endif
  1494. return write_bytes_to_file(fname, str, strlen(str), bin);
  1495. }
  1496. /** Represents a file that we're writing to, with support for atomic commit:
  1497. * we can write into a a temporary file, and either remove the file on
  1498. * failure, or replace the original file on success. */
  1499. struct open_file_t {
  1500. char *tempname; /**< Name of the temporary file. */
  1501. char *filename; /**< Name of the original file. */
  1502. int rename_on_close; /**< Are we using the temporary file or not? */
  1503. int fd; /**< fd for the open file. */
  1504. FILE *stdio_file; /**< stdio wrapper for <b>fd</b>. */
  1505. };
  1506. /** Try to start writing to the file in <b>fname</b>, passing the flags
  1507. * <b>open_flags</b> to the open() syscall, creating the file (if needed) with
  1508. * access value <b>mode</b>. If the O_APPEND flag is set, we append to the
  1509. * original file. Otherwise, we open a new temporary file in the same
  1510. * directory, and either replace the original or remove the temporary file
  1511. * when we're done.
  1512. *
  1513. * Return the fd for the newly opened file, and store working data in
  1514. * *<b>data_out</b>. The caller should not close the fd manually:
  1515. * instead, call finish_writing_to_file() or abort_writing_to_file().
  1516. * Returns -1 on failure.
  1517. *
  1518. * NOTE: When not appending, the flags O_CREAT and O_TRUNC are treated
  1519. * as true and the flag O_EXCL is treated as false.
  1520. *
  1521. * NOTE: Ordinarily, O_APPEND means "seek to the end of the file before each
  1522. * write()". We don't do that.
  1523. */
  1524. int
  1525. start_writing_to_file(const char *fname, int open_flags, int mode,
  1526. open_file_t **data_out)
  1527. {
  1528. size_t tempname_len = strlen(fname)+16;
  1529. open_file_t *new_file = tor_malloc_zero(sizeof(open_file_t));
  1530. const char *open_name;
  1531. int append = 0;
  1532. tor_assert(fname);
  1533. tor_assert(data_out);
  1534. #if (O_BINARY != 0 && O_TEXT != 0)
  1535. tor_assert((open_flags & (O_BINARY|O_TEXT)) != 0);
  1536. #endif
  1537. new_file->fd = -1;
  1538. tor_assert(tempname_len > strlen(fname)); /*check for overflow*/
  1539. new_file->filename = tor_strdup(fname);
  1540. if (open_flags & O_APPEND) {
  1541. open_name = fname;
  1542. new_file->rename_on_close = 0;
  1543. append = 1;
  1544. open_flags &= ~O_APPEND;
  1545. } else {
  1546. open_name = new_file->tempname = tor_malloc(tempname_len);
  1547. if (tor_snprintf(new_file->tempname, tempname_len, "%s.tmp", fname)<0) {
  1548. log(LOG_WARN, LD_GENERAL, "Failed to generate filename");
  1549. goto err;
  1550. }
  1551. /* We always replace an existing temporary file if there is one. */
  1552. open_flags |= O_CREAT|O_TRUNC;
  1553. open_flags &= ~O_EXCL;
  1554. new_file->rename_on_close = 1;
  1555. }
  1556. if ((new_file->fd = open(open_name, open_flags, mode)) < 0) {
  1557. log(LOG_WARN, LD_FS, "Couldn't open \"%s\" (%s) for writing: %s",
  1558. open_name, fname, strerror(errno));
  1559. goto err;
  1560. }
  1561. if (append) {
  1562. if (tor_fd_seekend(new_file->fd) < 0) {
  1563. log_warn(LD_FS, "Couldn't seek to end of file \"%s\": %s", open_name,
  1564. strerror(errno));
  1565. goto err;
  1566. }
  1567. }
  1568. *data_out = new_file;
  1569. return new_file->fd;
  1570. err:
  1571. if (new_file->fd >= 0)
  1572. close(new_file->fd);
  1573. *data_out = NULL;
  1574. tor_free(new_file->filename);
  1575. tor_free(new_file->tempname);
  1576. tor_free(new_file);
  1577. return -1;
  1578. }
  1579. /** Given <b>file_data</b> from start_writing_to_file(), return a stdio FILE*
  1580. * that can be used to write to the same file. The caller should not mix
  1581. * stdio calls with non-stdio calls. */
  1582. FILE *
  1583. fdopen_file(open_file_t *file_data)
  1584. {
  1585. tor_assert(file_data);
  1586. if (file_data->stdio_file)
  1587. return file_data->stdio_file;
  1588. tor_assert(file_data->fd >= 0);
  1589. if (!(file_data->stdio_file = fdopen(file_data->fd, "a"))) {
  1590. log_warn(LD_FS, "Couldn't fdopen \"%s\" [%d]: %s", file_data->filename,
  1591. file_data->fd, strerror(errno));
  1592. }
  1593. return file_data->stdio_file;
  1594. }
  1595. /** Combines start_writing_to_file with fdopen_file(): arguments are as
  1596. * for start_writing_to_file, but */
  1597. FILE *
  1598. start_writing_to_stdio_file(const char *fname, int open_flags, int mode,
  1599. open_file_t **data_out)
  1600. {
  1601. FILE *res;
  1602. if (start_writing_to_file(fname, open_flags, mode, data_out)<0)
  1603. return NULL;
  1604. if (!(res = fdopen_file(*data_out))) {
  1605. abort_writing_to_file(*data_out);
  1606. *data_out = NULL;
  1607. }
  1608. return res;
  1609. }
  1610. /** Helper function: close and free the underlying file and memory in
  1611. * <b>file_data</b>. If we were writing into a temporary file, then delete
  1612. * that file (if abort_write is true) or replaces the target file with
  1613. * the temporary file (if abort_write is false). */
  1614. static int
  1615. finish_writing_to_file_impl(open_file_t *file_data, int abort_write)
  1616. {
  1617. int r = 0;
  1618. tor_assert(file_data && file_data->filename);
  1619. if (file_data->stdio_file) {
  1620. if (fclose(file_data->stdio_file)) {
  1621. log_warn(LD_FS, "Error closing \"%s\": %s", file_data->filename,
  1622. strerror(errno));
  1623. abort_write = r = -1;
  1624. }
  1625. } else if (file_data->fd >= 0 && close(file_data->fd) < 0) {
  1626. log_warn(LD_FS, "Error flushing \"%s\": %s", file_data->filename,
  1627. strerror(errno));
  1628. abort_write = r = -1;
  1629. }
  1630. if (file_data->rename_on_close) {
  1631. tor_assert(file_data->tempname && file_data->filename);
  1632. if (abort_write) {
  1633. unlink(file_data->tempname);
  1634. } else {
  1635. tor_assert(strcmp(file_data->filename, file_data->tempname));
  1636. if (replace_file(file_data->tempname, file_data->filename)) {
  1637. log_warn(LD_FS, "Error replacing \"%s\": %s", file_data->filename,
  1638. strerror(errno));
  1639. r = -1;
  1640. }
  1641. }
  1642. }
  1643. tor_free(file_data->filename);
  1644. tor_free(file_data->tempname);
  1645. tor_free(file_data);
  1646. return r;
  1647. }
  1648. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1649. * needed, and if using a temporary file, replace the original file with
  1650. * the temporary file. */
  1651. int
  1652. finish_writing_to_file(open_file_t *file_data)
  1653. {
  1654. return finish_writing_to_file_impl(file_data, 0);
  1655. }
  1656. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1657. * needed, and if using a temporary file, delete it. */
  1658. int
  1659. abort_writing_to_file(open_file_t *file_data)
  1660. {
  1661. return finish_writing_to_file_impl(file_data, 1);
  1662. }
  1663. /** Helper: given a set of flags as passed to open(2), open the file
  1664. * <b>fname</b> and write all the sized_chunk_t structs in <b>chunks</b> to
  1665. * the file. Do so as atomically as possible e.g. by opening temp files and
  1666. * renaming. */
  1667. static int
  1668. write_chunks_to_file_impl(const char *fname, const smartlist_t *chunks,
  1669. int open_flags)
  1670. {
  1671. open_file_t *file = NULL;
  1672. int fd;
  1673. ssize_t result;
  1674. fd = start_writing_to_file(fname, open_flags, 0600, &file);
  1675. if (fd<0)
  1676. return -1;
  1677. SMARTLIST_FOREACH(chunks, sized_chunk_t *, chunk,
  1678. {
  1679. result = write_all(fd, chunk->bytes, chunk->len, 0);
  1680. if (result < 0) {
  1681. log(LOG_WARN, LD_FS, "Error writing to \"%s\": %s", fname,
  1682. strerror(errno));
  1683. goto err;
  1684. }
  1685. tor_assert((size_t)result == chunk->len);
  1686. });
  1687. return finish_writing_to_file(file);
  1688. err:
  1689. abort_writing_to_file(file);
  1690. return -1;
  1691. }
  1692. /** Given a smartlist of sized_chunk_t, write them atomically to a file
  1693. * <b>fname</b>, overwriting or creating the file as necessary. */
  1694. int
  1695. write_chunks_to_file(const char *fname, const smartlist_t *chunks, int bin)
  1696. {
  1697. int flags = OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT);
  1698. return write_chunks_to_file_impl(fname, chunks, flags);
  1699. }
  1700. /** As write_str_to_file, but does not assume a NUL-terminated
  1701. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  1702. int
  1703. write_bytes_to_file(const char *fname, const char *str, size_t len,
  1704. int bin)
  1705. {
  1706. int flags = OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT);
  1707. int r;
  1708. sized_chunk_t c = { str, len };
  1709. smartlist_t *chunks = smartlist_create();
  1710. smartlist_add(chunks, &c);
  1711. r = write_chunks_to_file_impl(fname, chunks, flags);
  1712. smartlist_free(chunks);
  1713. return r;
  1714. }
  1715. /** As write_bytes_to_file, but if the file already exists, append the bytes
  1716. * to the end of the file instead of overwriting it. */
  1717. int
  1718. append_bytes_to_file(const char *fname, const char *str, size_t len,
  1719. int bin)
  1720. {
  1721. int flags = OPEN_FLAGS_APPEND|(bin?O_BINARY:O_TEXT);
  1722. int r;
  1723. sized_chunk_t c = { str, len };
  1724. smartlist_t *chunks = smartlist_create();
  1725. smartlist_add(chunks, &c);
  1726. r = write_chunks_to_file_impl(fname, chunks, flags);
  1727. smartlist_free(chunks);
  1728. return r;
  1729. }
  1730. /** Read the contents of <b>filename</b> into a newly allocated
  1731. * string; return the string on success or NULL on failure.
  1732. *
  1733. * If <b>stat_out</b> is provided, store the result of stat()ing the
  1734. * file into <b>stat_out</b>.
  1735. *
  1736. * If <b>flags</b> &amp; RFTS_BIN, open the file in binary mode.
  1737. * If <b>flags</b> &amp; RFTS_IGNORE_MISSING, don't warn if the file
  1738. * doesn't exist.
  1739. */
  1740. /*
  1741. * This function <em>may</em> return an erroneous result if the file
  1742. * is modified while it is running, but must not crash or overflow.
  1743. * Right now, the error case occurs when the file length grows between
  1744. * the call to stat and the call to read_all: the resulting string will
  1745. * be truncated.
  1746. */
  1747. char *
  1748. read_file_to_str(const char *filename, int flags, struct stat *stat_out)
  1749. {
  1750. int fd; /* router file */
  1751. struct stat statbuf;
  1752. char *string;
  1753. ssize_t r;
  1754. int bin = flags & RFTS_BIN;
  1755. tor_assert(filename);
  1756. fd = open(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  1757. if (fd<0) {
  1758. int severity = LOG_WARN;
  1759. int save_errno = errno;
  1760. if (errno == ENOENT && (flags & RFTS_IGNORE_MISSING))
  1761. severity = LOG_INFO;
  1762. log_fn(severity, LD_FS,"Could not open \"%s\": %s ",filename,
  1763. strerror(errno));
  1764. errno = save_errno;
  1765. return NULL;
  1766. }
  1767. if (fstat(fd, &statbuf)<0) {
  1768. int save_errno = errno;
  1769. close(fd);
  1770. log_warn(LD_FS,"Could not fstat \"%s\".",filename);
  1771. errno = save_errno;
  1772. return NULL;
  1773. }
  1774. if ((uint64_t)(statbuf.st_size)+1 > SIZE_T_MAX)
  1775. return NULL;
  1776. string = tor_malloc((size_t)(statbuf.st_size+1));
  1777. r = read_all(fd,string,(size_t)statbuf.st_size,0);
  1778. if (r<0) {
  1779. int save_errno = errno;
  1780. log_warn(LD_FS,"Error reading from file \"%s\": %s", filename,
  1781. strerror(errno));
  1782. tor_free(string);
  1783. close(fd);
  1784. errno = save_errno;
  1785. return NULL;
  1786. }
  1787. string[r] = '\0'; /* NUL-terminate the result. */
  1788. #ifdef MS_WINDOWS
  1789. if (!bin && strchr(string, '\r')) {
  1790. log_debug(LD_FS, "We didn't convert CRLF to LF as well as we hoped "
  1791. "when reading %s. Coping.",
  1792. filename);
  1793. tor_strstrip(string, "\r");
  1794. r = strlen(string);
  1795. }
  1796. if (!bin) {
  1797. statbuf.st_size = (size_t) r;
  1798. } else
  1799. #endif
  1800. if (r != statbuf.st_size) {
  1801. /* Unless we're using text mode on win32, we'd better have an exact
  1802. * match for size. */
  1803. int save_errno = errno;
  1804. log_warn(LD_FS,"Could read only %d of %ld bytes of file \"%s\".",
  1805. (int)r, (long)statbuf.st_size,filename);
  1806. tor_free(string);
  1807. close(fd);
  1808. errno = save_errno;
  1809. return NULL;
  1810. }
  1811. close(fd);
  1812. if (stat_out) {
  1813. memcpy(stat_out, &statbuf, sizeof(struct stat));
  1814. }
  1815. return string;
  1816. }
  1817. #define TOR_ISODIGIT(c) ('0' <= (c) && (c) <= '7')
  1818. /** Given a c-style double-quoted escaped string in <b>s</b>, extract and
  1819. * decode its contents into a newly allocated string. On success, assign this
  1820. * string to *<b>result</b>, assign its length to <b>size_out</b> (if
  1821. * provided), and return a pointer to the position in <b>s</b> immediately
  1822. * after the string. On failure, return NULL.
  1823. */
  1824. static const char *
  1825. unescape_string(const char *s, char **result, size_t *size_out)
  1826. {
  1827. const char *cp;
  1828. char *out;
  1829. if (s[0] != '\"')
  1830. return NULL;
  1831. cp = s+1;
  1832. while (1) {
  1833. switch (*cp) {
  1834. case '\0':
  1835. case '\n':
  1836. return NULL;
  1837. case '\"':
  1838. goto end_of_loop;
  1839. case '\\':
  1840. if ((cp[1] == 'x' || cp[1] == 'X')
  1841. && TOR_ISXDIGIT(cp[2]) && TOR_ISXDIGIT(cp[3])) {
  1842. cp += 4;
  1843. } else if (TOR_ISODIGIT(cp[1])) {
  1844. cp += 2;
  1845. if (TOR_ISODIGIT(*cp)) ++cp;
  1846. if (TOR_ISODIGIT(*cp)) ++cp;
  1847. } else if (cp[1]) {
  1848. cp += 2;
  1849. } else {
  1850. return NULL;
  1851. }
  1852. break;
  1853. default:
  1854. ++cp;
  1855. break;
  1856. }
  1857. }
  1858. end_of_loop:
  1859. out = *result = tor_malloc(cp-s + 1);
  1860. cp = s+1;
  1861. while (1) {
  1862. switch (*cp)
  1863. {
  1864. case '\"':
  1865. *out = '\0';
  1866. if (size_out) *size_out = out - *result;
  1867. return cp+1;
  1868. case '\0':
  1869. tor_fragile_assert();
  1870. tor_free(*result);
  1871. return NULL;
  1872. case '\\':
  1873. switch (cp[1])
  1874. {
  1875. case 'n': *out++ = '\n'; cp += 2; break;
  1876. case 'r': *out++ = '\r'; cp += 2; break;
  1877. case 't': *out++ = '\t'; cp += 2; break;
  1878. case 'x': case 'X':
  1879. *out++ = ((hex_decode_digit(cp[2])<<4) +
  1880. hex_decode_digit(cp[3]));
  1881. cp += 4;
  1882. break;
  1883. case '0': case '1': case '2': case '3': case '4': case '5':
  1884. case '6': case '7':
  1885. {
  1886. int n = cp[1]-'0';
  1887. cp += 2;
  1888. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  1889. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  1890. if (n > 255) { tor_free(*result); return NULL; }
  1891. *out++ = (char)n;
  1892. }
  1893. break;
  1894. case '\'':
  1895. case '\"':
  1896. case '\\':
  1897. case '\?':
  1898. *out++ = cp[1];
  1899. cp += 2;
  1900. break;
  1901. default:
  1902. tor_free(*result); return NULL;
  1903. }
  1904. break;
  1905. default:
  1906. *out++ = *cp++;
  1907. }
  1908. }
  1909. }
  1910. /** Given a string containing part of a configuration file or similar format,
  1911. * advance past comments and whitespace and try to parse a single line. If we
  1912. * parse a line successfully, set *<b>key_out</b> to a new string holding the
  1913. * key portion and *<b>value_out</b> to a new string holding the value portion
  1914. * of the line, and return a pointer to the start of the next line. If we run
  1915. * out of data, return a pointer to the end of the string. If we encounter an
  1916. * error, return NULL.
  1917. */
  1918. const char *
  1919. parse_config_line_from_str(const char *line, char **key_out, char **value_out)
  1920. {
  1921. const char *key, *val, *cp;
  1922. tor_assert(key_out);
  1923. tor_assert(value_out);
  1924. *key_out = *value_out = NULL;
  1925. key = val = NULL;
  1926. /* Skip until the first keyword. */
  1927. while (1) {
  1928. while (TOR_ISSPACE(*line))
  1929. ++line;
  1930. if (*line == '#') {
  1931. while (*line && *line != '\n')
  1932. ++line;
  1933. } else {
  1934. break;
  1935. }
  1936. }
  1937. if (!*line) { /* End of string? */
  1938. *key_out = *value_out = NULL;
  1939. return line;
  1940. }
  1941. /* Skip until the next space. */
  1942. key = line;
  1943. while (*line && !TOR_ISSPACE(*line) && *line != '#')
  1944. ++line;
  1945. *key_out = tor_strndup(key, line-key);
  1946. /* Skip until the value. */
  1947. while (*line == ' ' || *line == '\t')
  1948. ++line;
  1949. val = line;
  1950. /* Find the end of the line. */
  1951. if (*line == '\"') {
  1952. if (!(line = unescape_string(line, value_out, NULL)))
  1953. return NULL;
  1954. while (*line == ' ' || *line == '\t')
  1955. ++line;
  1956. if (*line && *line != '#' && *line != '\n')
  1957. return NULL;
  1958. } else {
  1959. while (*line && *line != '\n' && *line != '#')
  1960. ++line;
  1961. if (*line == '\n') {
  1962. cp = line++;
  1963. } else {
  1964. cp = line;
  1965. }
  1966. while (cp>val && TOR_ISSPACE(*(cp-1)))
  1967. --cp;
  1968. tor_assert(cp >= val);
  1969. *value_out = tor_strndup(val, cp-val);
  1970. }
  1971. if (*line == '#') {
  1972. do {
  1973. ++line;
  1974. } while (*line && *line != '\n');
  1975. }
  1976. while (TOR_ISSPACE(*line)) ++line;
  1977. return line;
  1978. }
  1979. /** Expand any homedir prefix on <b>filename</b>; return a newly allocated
  1980. * string. */
  1981. char *
  1982. expand_filename(const char *filename)
  1983. {
  1984. tor_assert(filename);
  1985. if (*filename == '~') {
  1986. size_t len;
  1987. char *home, *result;
  1988. const char *rest;
  1989. if (filename[1] == '/' || filename[1] == '\0') {
  1990. home = getenv("HOME");
  1991. if (!home) {
  1992. log_warn(LD_CONFIG, "Couldn't find $HOME environment variable while "
  1993. "expanding \"%s\"", filename);
  1994. return NULL;
  1995. }
  1996. home = tor_strdup(home);
  1997. rest = strlen(filename)>=2?(filename+2):"";
  1998. } else {
  1999. #ifdef HAVE_PWD_H
  2000. char *username, *slash;
  2001. slash = strchr(filename, '/');
  2002. if (slash)
  2003. username = tor_strndup(filename+1,slash-filename-1);
  2004. else
  2005. username = tor_strdup(filename+1);
  2006. if (!(home = get_user_homedir(username))) {
  2007. log_warn(LD_CONFIG,"Couldn't get homedir for \"%s\"",username);
  2008. tor_free(username);
  2009. return NULL;
  2010. }
  2011. tor_free(username);
  2012. rest = slash ? (slash+1) : "";
  2013. #else
  2014. log_warn(LD_CONFIG, "Couldn't expend homedir on system without pwd.h");
  2015. return tor_strdup(filename);
  2016. #endif
  2017. }
  2018. tor_assert(home);
  2019. /* Remove trailing slash. */
  2020. if (strlen(home)>1 && !strcmpend(home,PATH_SEPARATOR)) {
  2021. home[strlen(home)-1] = '\0';
  2022. }
  2023. /* Plus one for /, plus one for NUL.
  2024. * Round up to 16 in case we can't do math. */
  2025. len = strlen(home)+strlen(rest)+16;
  2026. result = tor_malloc(len);
  2027. tor_snprintf(result,len,"%s"PATH_SEPARATOR"%s",home,rest);
  2028. tor_free(home);
  2029. return result;
  2030. } else {
  2031. return tor_strdup(filename);
  2032. }
  2033. }
  2034. #define MAX_SCANF_WIDTH 9999
  2035. /** DOCDOC */
  2036. static int
  2037. digit_to_num(char d)
  2038. {
  2039. int num = ((int)d) - (int)'0';
  2040. tor_assert(num <= 9 && num >= 0);
  2041. return num;
  2042. }
  2043. /** DOCDOC */
  2044. static int
  2045. scan_unsigned(const char **bufp, unsigned *out, int width)
  2046. {
  2047. unsigned result = 0;
  2048. int scanned_so_far = 0;
  2049. if (!bufp || !*bufp || !out)
  2050. return -1;
  2051. if (width<0)
  2052. width=MAX_SCANF_WIDTH;
  2053. while (**bufp && TOR_ISDIGIT(**bufp) && scanned_so_far < width) {
  2054. int digit = digit_to_num(*(*bufp)++);
  2055. unsigned new_result = result * 10 + digit;
  2056. if (new_result > UINT32_MAX || new_result < result)
  2057. return -1; /* over/underflow. */
  2058. result = new_result;
  2059. ++scanned_so_far;
  2060. }
  2061. if (!scanned_so_far) /* No actual digits scanned */
  2062. return -1;
  2063. *out = result;
  2064. return 0;
  2065. }
  2066. /** DOCDOC */
  2067. static int
  2068. scan_string(const char **bufp, char *out, int width)
  2069. {
  2070. int scanned_so_far = 0;
  2071. if (!bufp || !out || width < 0)
  2072. return -1;
  2073. while (**bufp && ! TOR_ISSPACE(**bufp) && scanned_so_far < width) {
  2074. *out++ = *(*bufp)++;
  2075. ++scanned_so_far;
  2076. }
  2077. *out = '\0';
  2078. return 0;
  2079. }
  2080. /** Locale-independent, minimal, no-surprises scanf variant, accepting only a
  2081. * restricted pattern format. For more info on what it supports, see
  2082. * tor_sscanf() documentation. */
  2083. int
  2084. tor_vsscanf(const char *buf, const char *pattern, va_list ap)
  2085. {
  2086. int n_matched = 0;
  2087. while (*pattern) {
  2088. if (*pattern != '%') {
  2089. if (*buf == *pattern) {
  2090. ++buf;
  2091. ++pattern;
  2092. continue;
  2093. } else {
  2094. return n_matched;
  2095. }
  2096. } else {
  2097. int width = -1;
  2098. ++pattern;
  2099. if (TOR_ISDIGIT(*pattern)) {
  2100. width = digit_to_num(*pattern++);
  2101. while (TOR_ISDIGIT(*pattern)) {
  2102. width *= 10;
  2103. width += digit_to_num(*pattern++);
  2104. if (width > MAX_SCANF_WIDTH)
  2105. return -1;
  2106. }
  2107. if (!width) /* No zero-width things. */
  2108. return -1;
  2109. }
  2110. if (*pattern == 'u') {
  2111. unsigned *u = va_arg(ap, unsigned *);
  2112. if (!*buf)
  2113. return n_matched;
  2114. if (scan_unsigned(&buf, u, width)<0)
  2115. return n_matched;
  2116. ++pattern;
  2117. ++n_matched;
  2118. } else if (*pattern == 's') {
  2119. char *s = va_arg(ap, char *);
  2120. if (width < 0)
  2121. return -1;
  2122. if (scan_string(&buf, s, width)<0)
  2123. return n_matched;
  2124. ++pattern;
  2125. ++n_matched;
  2126. } else if (*pattern == 'c') {
  2127. char *ch = va_arg(ap, char *);
  2128. if (width != -1)
  2129. return -1;
  2130. if (!*buf)
  2131. return n_matched;
  2132. *ch = *buf++;
  2133. ++pattern;
  2134. ++n_matched;
  2135. } else if (*pattern == '%') {
  2136. if (*buf != '%')
  2137. return -1;
  2138. ++buf;
  2139. ++pattern;
  2140. } else {
  2141. return -1; /* Unrecognized pattern component. */
  2142. }
  2143. }
  2144. }
  2145. return n_matched;
  2146. }
  2147. /** Minimal sscanf replacement: parse <b>buf</b> according to <b>pattern</b>
  2148. * and store the results in the corresponding argument fields. Differs from
  2149. * sscanf in that it: Only handles %u and %Ns. Does not handle arbitrarily
  2150. * long widths. %u does not consume any space. Is locale-independent.
  2151. * Returns -1 on malformed patterns. */
  2152. int
  2153. tor_sscanf(const char *buf, const char *pattern, ...)
  2154. {
  2155. int r;
  2156. va_list ap;
  2157. va_start(ap, pattern);
  2158. r = tor_vsscanf(buf, pattern, ap);
  2159. va_end(ap);
  2160. return r;
  2161. }
  2162. /** Return a new list containing the filenames in the directory <b>dirname</b>.
  2163. * Return NULL on error or if <b>dirname</b> is not a directory.
  2164. */
  2165. smartlist_t *
  2166. tor_listdir(const char *dirname)
  2167. {
  2168. smartlist_t *result;
  2169. #ifdef MS_WINDOWS
  2170. char *pattern;
  2171. HANDLE handle;
  2172. WIN32_FIND_DATA findData;
  2173. size_t pattern_len = strlen(dirname)+16;
  2174. pattern = tor_malloc(pattern_len);
  2175. tor_snprintf(pattern, pattern_len, "%s\\*", dirname);
  2176. if (INVALID_HANDLE_VALUE == (handle = FindFirstFile(pattern, &findData))) {
  2177. tor_free(pattern);
  2178. return NULL;
  2179. }
  2180. result = smartlist_create();
  2181. while (1) {
  2182. if (strcmp(findData.cFileName, ".") &&
  2183. strcmp(findData.cFileName, "..")) {
  2184. smartlist_add(result, tor_strdup(findData.cFileName));
  2185. }
  2186. if (!FindNextFile(handle, &findData)) {
  2187. DWORD err;
  2188. if ((err = GetLastError()) != ERROR_NO_MORE_FILES) {
  2189. char *errstr = format_win32_error(err);
  2190. log_warn(LD_FS, "Error reading directory '%s': %s", dirname, errstr);
  2191. tor_free(errstr);
  2192. }
  2193. break;
  2194. }
  2195. }
  2196. FindClose(handle);
  2197. tor_free(pattern);
  2198. #else
  2199. DIR *d;
  2200. struct dirent *de;
  2201. if (!(d = opendir(dirname)))
  2202. return NULL;
  2203. result = smartlist_create();
  2204. while ((de = readdir(d))) {
  2205. if (!strcmp(de->d_name, ".") ||
  2206. !strcmp(de->d_name, ".."))
  2207. continue;
  2208. smartlist_add(result, tor_strdup(de->d_name));
  2209. }
  2210. closedir(d);
  2211. #endif
  2212. return result;
  2213. }
  2214. /** Return true iff <b>filename</b> is a relative path. */
  2215. int
  2216. path_is_relative(const char *filename)
  2217. {
  2218. if (filename && filename[0] == '/')
  2219. return 0;
  2220. #ifdef MS_WINDOWS
  2221. else if (filename && filename[0] == '\\')
  2222. return 0;
  2223. else if (filename && strlen(filename)>3 && TOR_ISALPHA(filename[0]) &&
  2224. filename[1] == ':' && filename[2] == '\\')
  2225. return 0;
  2226. #endif
  2227. else
  2228. return 1;
  2229. }
  2230. /* =====
  2231. * Process helpers
  2232. * ===== */
  2233. #ifndef MS_WINDOWS
  2234. /* Based on code contributed by christian grothoff */
  2235. /** True iff we've called start_daemon(). */
  2236. static int start_daemon_called = 0;
  2237. /** True iff we've called finish_daemon(). */
  2238. static int finish_daemon_called = 0;
  2239. /** Socketpair used to communicate between parent and child process while
  2240. * daemonizing. */
  2241. static int daemon_filedes[2];
  2242. /** Start putting the process into daemon mode: fork and drop all resources
  2243. * except standard fds. The parent process never returns, but stays around
  2244. * until finish_daemon is called. (Note: it's safe to call this more
  2245. * than once: calls after the first are ignored.)
  2246. */
  2247. void
  2248. start_daemon(void)
  2249. {
  2250. pid_t pid;
  2251. if (start_daemon_called)
  2252. return;
  2253. start_daemon_called = 1;
  2254. if (pipe(daemon_filedes)) {
  2255. log_err(LD_GENERAL,"pipe failed; exiting. Error was %s", strerror(errno));
  2256. exit(1);
  2257. }
  2258. pid = fork();
  2259. if (pid < 0) {
  2260. log_err(LD_GENERAL,"fork failed. Exiting.");
  2261. exit(1);
  2262. }
  2263. if (pid) { /* Parent */
  2264. int ok;
  2265. char c;
  2266. close(daemon_filedes[1]); /* we only read */
  2267. ok = -1;
  2268. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  2269. if (c == '.')
  2270. ok = 1;
  2271. }
  2272. fflush(stdout);
  2273. if (ok == 1)
  2274. exit(0);
  2275. else
  2276. exit(1); /* child reported error */
  2277. } else { /* Child */
  2278. close(daemon_filedes[0]); /* we only write */
  2279. pid = setsid(); /* Detach from controlling terminal */
  2280. /*
  2281. * Fork one more time, so the parent (the session group leader) can exit.
  2282. * This means that we, as a non-session group leader, can never regain a
  2283. * controlling terminal. This part is recommended by Stevens's
  2284. * _Advanced Programming in the Unix Environment_.
  2285. */
  2286. if (fork() != 0) {
  2287. exit(0);
  2288. }
  2289. set_main_thread(); /* We are now the main thread. */
  2290. return;
  2291. }
  2292. }
  2293. /** Finish putting the process into daemon mode: drop standard fds, and tell
  2294. * the parent process to exit. (Note: it's safe to call this more than once:
  2295. * calls after the first are ignored. Calls start_daemon first if it hasn't
  2296. * been called already.)
  2297. */
  2298. void
  2299. finish_daemon(const char *desired_cwd)
  2300. {
  2301. int nullfd;
  2302. char c = '.';
  2303. if (finish_daemon_called)
  2304. return;
  2305. if (!start_daemon_called)
  2306. start_daemon();
  2307. finish_daemon_called = 1;
  2308. if (!desired_cwd)
  2309. desired_cwd = "/";
  2310. /* Don't hold the wrong FS mounted */
  2311. if (chdir(desired_cwd) < 0) {
  2312. log_err(LD_GENERAL,"chdir to \"%s\" failed. Exiting.",desired_cwd);
  2313. exit(1);
  2314. }
  2315. nullfd = open("/dev/null", O_RDWR);
  2316. if (nullfd < 0) {
  2317. log_err(LD_GENERAL,"/dev/null can't be opened. Exiting.");
  2318. exit(1);
  2319. }
  2320. /* close fds linking to invoking terminal, but
  2321. * close usual incoming fds, but redirect them somewhere
  2322. * useful so the fds don't get reallocated elsewhere.
  2323. */
  2324. if (dup2(nullfd,0) < 0 ||
  2325. dup2(nullfd,1) < 0 ||
  2326. dup2(nullfd,2) < 0) {
  2327. log_err(LD_GENERAL,"dup2 failed. Exiting.");
  2328. exit(1);
  2329. }
  2330. if (nullfd > 2)
  2331. close(nullfd);
  2332. /* signal success */
  2333. if (write(daemon_filedes[1], &c, sizeof(char)) != sizeof(char)) {
  2334. log_err(LD_GENERAL,"write failed. Exiting.");
  2335. }
  2336. close(daemon_filedes[1]);
  2337. }
  2338. #else
  2339. /* defined(MS_WINDOWS) */
  2340. void
  2341. start_daemon(void)
  2342. {
  2343. }
  2344. void
  2345. finish_daemon(const char *cp)
  2346. {
  2347. (void)cp;
  2348. }
  2349. #endif
  2350. /** Write the current process ID, followed by NL, into <b>filename</b>.
  2351. */
  2352. void
  2353. write_pidfile(char *filename)
  2354. {
  2355. FILE *pidfile;
  2356. if ((pidfile = fopen(filename, "w")) == NULL) {
  2357. log_warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
  2358. strerror(errno));
  2359. } else {
  2360. #ifdef MS_WINDOWS
  2361. fprintf(pidfile, "%d\n", (int)_getpid());
  2362. #else
  2363. fprintf(pidfile, "%d\n", (int)getpid());
  2364. #endif
  2365. fclose(pidfile);
  2366. }
  2367. }