util.c 69 KB

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