util.c 67 KB

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