util.c 72 KB

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