util.c 63 KB

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