util.c 67 KB

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