util.c 68 KB

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