util.c 67 KB

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