util.c 68 KB

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