util.c 63 KB

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