util.c 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741
  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 "log.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. len += 2;
  862. break;
  863. default:
  864. if (TOR_ISPRINT(*cp) && ((uint8_t)*cp)<127)
  865. ++len;
  866. else
  867. len += 4;
  868. break;
  869. }
  870. }
  871. result = outp = tor_malloc(len);
  872. *outp++ = '\"';
  873. for (cp = s; *cp; ++cp) {
  874. switch (*cp) {
  875. case '\\':
  876. case '\"':
  877. case '\'':
  878. *outp++ = '\\';
  879. *outp++ = *cp;
  880. break;
  881. case '\n':
  882. *outp++ = '\\';
  883. *outp++ = 'n';
  884. break;
  885. case '\t':
  886. *outp++ = '\\';
  887. *outp++ = 't';
  888. break;
  889. case '\r':
  890. *outp++ = '\\';
  891. *outp++ = 'r';
  892. break;
  893. default:
  894. if (TOR_ISPRINT(*cp) && ((uint8_t)*cp)<127) {
  895. *outp++ = *cp;
  896. } else {
  897. tor_snprintf(outp, 5, "\\%03o", (int)(uint8_t) *cp);
  898. outp += 4;
  899. }
  900. break;
  901. }
  902. }
  903. *outp++ = '\"';
  904. *outp++ = 0;
  905. return result;
  906. }
  907. /** Allocate and return a new string representing the contents of <b>s</b>,
  908. * surrounded by quotes and using standard C escapes.
  909. *
  910. * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
  911. * thread. Also, each call invalidates the last-returned value, so don't
  912. * try log_warn(LD_GENERAL, "%s %s", escaped(a), escaped(b));
  913. */
  914. const char *
  915. escaped(const char *s)
  916. {
  917. static char *_escaped_val = NULL;
  918. tor_free(_escaped_val);
  919. if (s)
  920. _escaped_val = esc_for_log(s);
  921. else
  922. _escaped_val = NULL;
  923. return _escaped_val;
  924. }
  925. /** Rudimentary string wrapping code: given a un-wrapped <b>string</b> (no
  926. * newlines!), break the string into newline-terminated lines of no more than
  927. * <b>width</b> characters long (not counting newline) and insert them into
  928. * <b>out</b> in order. Precede the first line with prefix0, and subsequent
  929. * lines with prefixRest.
  930. */
  931. /* This uses a stupid greedy wrapping algorithm right now:
  932. * - For each line:
  933. * - Try to fit as much stuff as possible, but break on a space.
  934. * - If the first "word" of the line will extend beyond the allowable
  935. * width, break the word at the end of the width.
  936. */
  937. void
  938. wrap_string(smartlist_t *out, const char *string, size_t width,
  939. const char *prefix0, const char *prefixRest)
  940. {
  941. size_t p0Len, pRestLen, pCurLen;
  942. const char *eos, *prefixCur;
  943. tor_assert(out);
  944. tor_assert(string);
  945. tor_assert(width);
  946. if (!prefix0)
  947. prefix0 = "";
  948. if (!prefixRest)
  949. prefixRest = "";
  950. p0Len = strlen(prefix0);
  951. pRestLen = strlen(prefixRest);
  952. tor_assert(width > p0Len && width > pRestLen);
  953. eos = strchr(string, '\0');
  954. tor_assert(eos);
  955. pCurLen = p0Len;
  956. prefixCur = prefix0;
  957. while ((eos-string)+pCurLen > width) {
  958. const char *eol = string + width - pCurLen;
  959. while (eol > string && *eol != ' ')
  960. --eol;
  961. /* eol is now the last space that can fit, or the start of the string. */
  962. if (eol > string) {
  963. size_t line_len = (eol-string) + pCurLen + 2;
  964. char *line = tor_malloc(line_len);
  965. memcpy(line, prefixCur, pCurLen);
  966. memcpy(line+pCurLen, string, eol-string);
  967. line[line_len-2] = '\n';
  968. line[line_len-1] = '\0';
  969. smartlist_add(out, line);
  970. string = eol + 1;
  971. } else {
  972. size_t line_len = width + 2;
  973. char *line = tor_malloc(line_len);
  974. memcpy(line, prefixCur, pCurLen);
  975. memcpy(line+pCurLen, string, width - pCurLen);
  976. line[line_len-2] = '\n';
  977. line[line_len-1] = '\0';
  978. smartlist_add(out, line);
  979. string += width-pCurLen;
  980. }
  981. prefixCur = prefixRest;
  982. pCurLen = pRestLen;
  983. }
  984. if (string < eos) {
  985. size_t line_len = (eos-string) + pCurLen + 2;
  986. char *line = tor_malloc(line_len);
  987. memcpy(line, prefixCur, pCurLen);
  988. memcpy(line+pCurLen, string, eos-string);
  989. line[line_len-2] = '\n';
  990. line[line_len-1] = '\0';
  991. smartlist_add(out, line);
  992. }
  993. }
  994. /* =====
  995. * Time
  996. * ===== */
  997. /**
  998. * Converts struct timeval to a double value.
  999. * Preserves microsecond precision, but just barely.
  1000. * Error is approx +/- 0.1 usec when dealing with epoch values.
  1001. */
  1002. double
  1003. tv_to_double(const struct timeval *tv)
  1004. {
  1005. double conv = tv->tv_sec;
  1006. conv += tv->tv_usec/1000000.0;
  1007. return conv;
  1008. }
  1009. /**
  1010. * Converts timeval to milliseconds.
  1011. */
  1012. int64_t
  1013. tv_to_msec(const struct timeval *tv)
  1014. {
  1015. int64_t conv = ((int64_t)tv->tv_sec)*1000L;
  1016. /* Round ghetto-style */
  1017. conv += ((int64_t)tv->tv_usec+500)/1000L;
  1018. return conv;
  1019. }
  1020. /**
  1021. * Converts timeval to microseconds.
  1022. */
  1023. int64_t
  1024. tv_to_usec(const struct timeval *tv)
  1025. {
  1026. int64_t conv = ((int64_t)tv->tv_sec)*1000000L;
  1027. conv += tv->tv_usec;
  1028. return conv;
  1029. }
  1030. /** Return the number of microseconds elapsed between *start and *end.
  1031. */
  1032. long
  1033. tv_udiff(const struct timeval *start, const struct timeval *end)
  1034. {
  1035. long udiff;
  1036. long secdiff = end->tv_sec - start->tv_sec;
  1037. if (labs(secdiff+1) > LONG_MAX/1000000) {
  1038. log_warn(LD_GENERAL, "comparing times on microsecond detail too far "
  1039. "apart: %ld seconds", secdiff);
  1040. return LONG_MAX;
  1041. }
  1042. udiff = secdiff*1000000L + (end->tv_usec - start->tv_usec);
  1043. return udiff;
  1044. }
  1045. /** Return the number of milliseconds elapsed between *start and *end.
  1046. */
  1047. long
  1048. tv_mdiff(const struct timeval *start, const struct timeval *end)
  1049. {
  1050. long mdiff;
  1051. long secdiff = end->tv_sec - start->tv_sec;
  1052. if (labs(secdiff+1) > LONG_MAX/1000) {
  1053. log_warn(LD_GENERAL, "comparing times on millisecond detail too far "
  1054. "apart: %ld seconds", secdiff);
  1055. return LONG_MAX;
  1056. }
  1057. /* Subtract and round */
  1058. mdiff = secdiff*1000L +
  1059. ((long)end->tv_usec - (long)start->tv_usec + 500L) / 1000L;
  1060. return mdiff;
  1061. }
  1062. /** Yield true iff <b>y</b> is a leap-year. */
  1063. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  1064. /** Helper: Return the number of leap-days between Jan 1, y1 and Jan 1, y2. */
  1065. static int
  1066. n_leapdays(int y1, int y2)
  1067. {
  1068. --y1;
  1069. --y2;
  1070. return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
  1071. }
  1072. /** Number of days per month in non-leap year; used by tor_timegm. */
  1073. static const int days_per_month[] =
  1074. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  1075. /** Return a time_t given a struct tm. The result is given in GMT, and
  1076. * does not account for leap seconds.
  1077. */
  1078. time_t
  1079. tor_timegm(struct tm *tm)
  1080. {
  1081. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  1082. * It's way more brute-force than fiddling with tzset().
  1083. */
  1084. time_t year, days, hours, minutes, seconds;
  1085. int i;
  1086. year = tm->tm_year + 1900;
  1087. if (year < 1970 || tm->tm_mon < 0 || tm->tm_mon > 11) {
  1088. log_warn(LD_BUG, "Out-of-range argument to tor_timegm");
  1089. return -1;
  1090. }
  1091. tor_assert(year < INT_MAX);
  1092. days = 365 * (year-1970) + n_leapdays(1970,(int)year);
  1093. for (i = 0; i < tm->tm_mon; ++i)
  1094. days += days_per_month[i];
  1095. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  1096. ++days;
  1097. days += tm->tm_mday - 1;
  1098. hours = days*24 + tm->tm_hour;
  1099. minutes = hours*60 + tm->tm_min;
  1100. seconds = minutes*60 + tm->tm_sec;
  1101. return seconds;
  1102. }
  1103. /* strftime is locale-specific, so we need to replace those parts */
  1104. /** A c-locale array of 3-letter names of weekdays, starting with Sun. */
  1105. static const char *WEEKDAY_NAMES[] =
  1106. { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1107. /** A c-locale array of 3-letter names of months, starting with Jan. */
  1108. static const char *MONTH_NAMES[] =
  1109. { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  1110. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1111. /** Set <b>buf</b> to the RFC1123 encoding of the GMT value of <b>t</b>.
  1112. * The buffer must be at least RFC1123_TIME_LEN+1 bytes long.
  1113. *
  1114. * (RFC1123 format is Fri, 29 Sep 2006 15:54:20 GMT)
  1115. */
  1116. void
  1117. format_rfc1123_time(char *buf, time_t t)
  1118. {
  1119. struct tm tm;
  1120. tor_gmtime_r(&t, &tm);
  1121. strftime(buf, RFC1123_TIME_LEN+1, "___, %d ___ %Y %H:%M:%S GMT", &tm);
  1122. tor_assert(tm.tm_wday >= 0);
  1123. tor_assert(tm.tm_wday <= 6);
  1124. memcpy(buf, WEEKDAY_NAMES[tm.tm_wday], 3);
  1125. tor_assert(tm.tm_wday >= 0);
  1126. tor_assert(tm.tm_mon <= 11);
  1127. memcpy(buf+8, MONTH_NAMES[tm.tm_mon], 3);
  1128. }
  1129. /** Parse the RFC1123 encoding of some time (in GMT) from <b>buf</b>,
  1130. * and store the result in *<b>t</b>.
  1131. *
  1132. * Return 0 on success, -1 on failure.
  1133. */
  1134. int
  1135. parse_rfc1123_time(const char *buf, time_t *t)
  1136. {
  1137. struct tm tm;
  1138. char month[4];
  1139. char weekday[4];
  1140. int i, m;
  1141. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  1142. if (strlen(buf) != RFC1123_TIME_LEN)
  1143. return -1;
  1144. memset(&tm, 0, sizeof(tm));
  1145. if (tor_sscanf(buf, "%3s, %2u %3s %u %2u:%2u:%2u GMT", weekday,
  1146. &tm_mday, month, &tm_year, &tm_hour,
  1147. &tm_min, &tm_sec) < 7) {
  1148. char *esc = esc_for_log(buf);
  1149. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  1150. tor_free(esc);
  1151. return -1;
  1152. }
  1153. if (tm_mday > 31 || tm_hour > 23 || tm_min > 59 || tm_sec > 61) {
  1154. char *esc = esc_for_log(buf);
  1155. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  1156. tor_free(esc);
  1157. return -1;
  1158. }
  1159. tm.tm_mday = (int)tm_mday;
  1160. tm.tm_year = (int)tm_year;
  1161. tm.tm_hour = (int)tm_hour;
  1162. tm.tm_min = (int)tm_min;
  1163. tm.tm_sec = (int)tm_sec;
  1164. m = -1;
  1165. for (i = 0; i < 12; ++i) {
  1166. if (!strcmp(month, MONTH_NAMES[i])) {
  1167. m = i;
  1168. break;
  1169. }
  1170. }
  1171. if (m<0) {
  1172. char *esc = esc_for_log(buf);
  1173. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s: No such month", esc);
  1174. tor_free(esc);
  1175. return -1;
  1176. }
  1177. tm.tm_mon = m;
  1178. if (tm.tm_year < 1970) {
  1179. char *esc = esc_for_log(buf);
  1180. log_warn(LD_GENERAL,
  1181. "Got invalid RFC1123 time %s. (Before 1970)", esc);
  1182. tor_free(esc);
  1183. return -1;
  1184. }
  1185. tm.tm_year -= 1900;
  1186. *t = tor_timegm(&tm);
  1187. return 0;
  1188. }
  1189. /** Set <b>buf</b> to the ISO8601 encoding of the local value of <b>t</b>.
  1190. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  1191. *
  1192. * (ISO8601 format is 2006-10-29 10:57:20)
  1193. */
  1194. void
  1195. format_local_iso_time(char *buf, time_t t)
  1196. {
  1197. struct tm tm;
  1198. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t, &tm));
  1199. }
  1200. /** Set <b>buf</b> to the ISO8601 encoding of the GMT value of <b>t</b>.
  1201. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  1202. */
  1203. void
  1204. format_iso_time(char *buf, time_t t)
  1205. {
  1206. struct tm tm;
  1207. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t, &tm));
  1208. }
  1209. /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
  1210. * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
  1211. * failure. Ignore extraneous stuff in <b>cp</b> separated by whitespace from
  1212. * the end of the time string. */
  1213. int
  1214. parse_iso_time(const char *cp, time_t *t)
  1215. {
  1216. struct tm st_tm;
  1217. unsigned int year=0, month=0, day=0, hour=100, minute=100, second=100;
  1218. if (tor_sscanf(cp, "%u-%2u-%2u %2u:%2u:%2u", &year, &month,
  1219. &day, &hour, &minute, &second) < 6) {
  1220. char *esc = esc_for_log(cp);
  1221. log_warn(LD_GENERAL, "ISO time %s was unparseable", esc);
  1222. tor_free(esc);
  1223. return -1;
  1224. }
  1225. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  1226. hour > 23 || minute > 59 || second > 61) {
  1227. char *esc = esc_for_log(cp);
  1228. log_warn(LD_GENERAL, "ISO time %s was nonsensical", esc);
  1229. tor_free(esc);
  1230. return -1;
  1231. }
  1232. st_tm.tm_year = year-1900;
  1233. st_tm.tm_mon = month-1;
  1234. st_tm.tm_mday = day;
  1235. st_tm.tm_hour = hour;
  1236. st_tm.tm_min = minute;
  1237. st_tm.tm_sec = second;
  1238. if (st_tm.tm_year < 70) {
  1239. char *esc = esc_for_log(cp);
  1240. log_warn(LD_GENERAL, "Got invalid ISO time %s. (Before 1970)", esc);
  1241. tor_free(esc);
  1242. return -1;
  1243. }
  1244. *t = tor_timegm(&st_tm);
  1245. return 0;
  1246. }
  1247. /** Given a <b>date</b> in one of the three formats allowed by HTTP (ugh),
  1248. * parse it into <b>tm</b>. Return 0 on success, negative on failure. */
  1249. int
  1250. parse_http_time(const char *date, struct tm *tm)
  1251. {
  1252. const char *cp;
  1253. char month[4];
  1254. char wkday[4];
  1255. int i;
  1256. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  1257. tor_assert(tm);
  1258. memset(tm, 0, sizeof(*tm));
  1259. /* First, try RFC1123 or RFC850 format: skip the weekday. */
  1260. if ((cp = strchr(date, ','))) {
  1261. ++cp;
  1262. if (tor_sscanf(date, "%2u %3s %4u %2u:%2u:%2u GMT",
  1263. &tm_mday, month, &tm_year,
  1264. &tm_hour, &tm_min, &tm_sec) == 6) {
  1265. /* rfc1123-date */
  1266. tm_year -= 1900;
  1267. } else if (tor_sscanf(date, "%2u-%3s-%2u %2u:%2u:%2u GMT",
  1268. &tm_mday, month, &tm_year,
  1269. &tm_hour, &tm_min, &tm_sec) == 6) {
  1270. /* rfc850-date */
  1271. } else {
  1272. return -1;
  1273. }
  1274. } else {
  1275. /* No comma; possibly asctime() format. */
  1276. if (tor_sscanf(date, "%3s %3s %2u %2u:%2u:%2u %4u",
  1277. wkday, month, &tm_mday,
  1278. &tm_hour, &tm_min, &tm_sec, &tm_year) == 7) {
  1279. tm_year -= 1900;
  1280. } else {
  1281. return -1;
  1282. }
  1283. }
  1284. tm->tm_mday = (int)tm_mday;
  1285. tm->tm_year = (int)tm_year;
  1286. tm->tm_hour = (int)tm_hour;
  1287. tm->tm_min = (int)tm_min;
  1288. tm->tm_sec = (int)tm_sec;
  1289. month[3] = '\0';
  1290. /* Okay, now decode the month. */
  1291. for (i = 0; i < 12; ++i) {
  1292. if (!strcasecmp(MONTH_NAMES[i], month)) {
  1293. tm->tm_mon = i+1;
  1294. }
  1295. }
  1296. if (tm->tm_year < 0 ||
  1297. tm->tm_mon < 1 || tm->tm_mon > 12 ||
  1298. tm->tm_mday < 0 || tm->tm_mday > 31 ||
  1299. tm->tm_hour < 0 || tm->tm_hour > 23 ||
  1300. tm->tm_min < 0 || tm->tm_min > 59 ||
  1301. tm->tm_sec < 0 || tm->tm_sec > 61)
  1302. return -1; /* Out of range, or bad month. */
  1303. return 0;
  1304. }
  1305. /** Given an <b>interval</b> in seconds, try to write it to the
  1306. * <b>out_len</b>-byte buffer in <b>out</b> in a human-readable form.
  1307. * Return 0 on success, -1 on failure.
  1308. */
  1309. int
  1310. format_time_interval(char *out, size_t out_len, long interval)
  1311. {
  1312. /* We only report seconds if there's no hours. */
  1313. long sec = 0, min = 0, hour = 0, day = 0;
  1314. if (interval < 0)
  1315. interval = -interval;
  1316. if (interval >= 86400) {
  1317. day = interval / 86400;
  1318. interval %= 86400;
  1319. }
  1320. if (interval >= 3600) {
  1321. hour = interval / 3600;
  1322. interval %= 3600;
  1323. }
  1324. if (interval >= 60) {
  1325. min = interval / 60;
  1326. interval %= 60;
  1327. }
  1328. sec = interval;
  1329. if (day) {
  1330. return tor_snprintf(out, out_len, "%ld days, %ld hours, %ld minutes",
  1331. day, hour, min);
  1332. } else if (hour) {
  1333. return tor_snprintf(out, out_len, "%ld hours, %ld minutes", hour, min);
  1334. } else if (min) {
  1335. return tor_snprintf(out, out_len, "%ld minutes, %ld seconds", min, sec);
  1336. } else {
  1337. return tor_snprintf(out, out_len, "%ld seconds", sec);
  1338. }
  1339. }
  1340. /* =====
  1341. * Cached time
  1342. * ===== */
  1343. #ifndef TIME_IS_FAST
  1344. /** Cached estimate of the current time. Updated around once per second;
  1345. * may be a few seconds off if we are really busy. This is a hack to avoid
  1346. * calling time(NULL) (which not everybody has optimized) on critical paths.
  1347. */
  1348. static time_t cached_approx_time = 0;
  1349. /** Return a cached estimate of the current time from when
  1350. * update_approx_time() was last called. This is a hack to avoid calling
  1351. * time(NULL) on critical paths: please do not even think of calling it
  1352. * anywhere else. */
  1353. time_t
  1354. approx_time(void)
  1355. {
  1356. return cached_approx_time;
  1357. }
  1358. /** Update the cached estimate of the current time. This function SHOULD be
  1359. * called once per second, and MUST be called before the first call to
  1360. * get_approx_time. */
  1361. void
  1362. update_approx_time(time_t now)
  1363. {
  1364. cached_approx_time = now;
  1365. }
  1366. #endif
  1367. /* =====
  1368. * Fuzzy time
  1369. * XXXX022 Use this consistently or rip most of it out.
  1370. * ===== */
  1371. /* In a perfect world, everybody would run NTP, and NTP would be perfect, so
  1372. * if we wanted to know "Is the current time before time X?" we could just say
  1373. * "time(NULL) < X".
  1374. *
  1375. * But unfortunately, many users are running Tor in an imperfect world, on
  1376. * even more imperfect computers. Hence, we need to track time oddly. We
  1377. * model the user's computer as being "skewed" from accurate time by
  1378. * -<b>ftime_skew</b> seconds, such that our best guess of the current time is
  1379. * time(NULL)+ftime_skew. We also assume that our measurements of time may
  1380. * have up to <b>ftime_slop</b> seconds of inaccuracy; IOW, our window of
  1381. * estimate for the current time is now + ftime_skew +/- ftime_slop.
  1382. */
  1383. /** Our current estimate of our skew, such that we think the current time is
  1384. * closest to time(NULL)+ftime_skew. */
  1385. static int ftime_skew = 0;
  1386. /** Tolerance during time comparisons, in seconds. */
  1387. static int ftime_slop = 60;
  1388. /** Set the largest amount of sloppiness we'll allow in fuzzy time
  1389. * comparisons. */
  1390. void
  1391. ftime_set_maximum_sloppiness(int seconds)
  1392. {
  1393. tor_assert(seconds >= 0);
  1394. ftime_slop = seconds;
  1395. }
  1396. /** Set the amount by which we believe our system clock to differ from
  1397. * real time. */
  1398. void
  1399. ftime_set_estimated_skew(int seconds)
  1400. {
  1401. ftime_skew = seconds;
  1402. }
  1403. #if 0
  1404. void
  1405. ftime_get_window(time_t now, ftime_t *ft_out)
  1406. {
  1407. ft_out->earliest = now + ftime_skew - ftime_slop;
  1408. ft_out->latest = now + ftime_skew + ftime_slop;
  1409. }
  1410. #endif
  1411. /** Return true iff we think that <b>now</b> might be after <b>when</b>. */
  1412. int
  1413. ftime_maybe_after(time_t now, time_t when)
  1414. {
  1415. /* It may be after when iff the latest possible current time is after when */
  1416. return (now + ftime_skew + ftime_slop) >= when;
  1417. }
  1418. /** Return true iff we think that <b>now</b> might be before <b>when</b>. */
  1419. int
  1420. ftime_maybe_before(time_t now, time_t when)
  1421. {
  1422. /* It may be before when iff the earliest possible current time is before */
  1423. return (now + ftime_skew - ftime_slop) < when;
  1424. }
  1425. /** Return true if we think that <b>now</b> is definitely after <b>when</b>. */
  1426. int
  1427. ftime_definitely_after(time_t now, time_t when)
  1428. {
  1429. /* It is definitely after when if the earliest time it could be is still
  1430. * after when. */
  1431. return (now + ftime_skew - ftime_slop) >= when;
  1432. }
  1433. /** Return true if we think that <b>now</b> is definitely before <b>when</b>.
  1434. */
  1435. int
  1436. ftime_definitely_before(time_t now, time_t when)
  1437. {
  1438. /* It is definitely before when if the latest time it could be is still
  1439. * before when. */
  1440. return (now + ftime_skew + ftime_slop) < when;
  1441. }
  1442. /* =====
  1443. * File helpers
  1444. * ===== */
  1445. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  1446. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  1447. * was returned by open(). Return the number of bytes written, or -1
  1448. * on error. Only use if fd is a blocking fd. */
  1449. ssize_t
  1450. write_all(int fd, const char *buf, size_t count, int isSocket)
  1451. {
  1452. size_t written = 0;
  1453. ssize_t result;
  1454. tor_assert(count < SSIZE_T_MAX);
  1455. while (written != count) {
  1456. if (isSocket)
  1457. result = tor_socket_send(fd, buf+written, count-written, 0);
  1458. else
  1459. result = write(fd, buf+written, count-written);
  1460. if (result<0)
  1461. return -1;
  1462. written += result;
  1463. }
  1464. return (ssize_t)count;
  1465. }
  1466. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  1467. * or reach the end of the file. <b>isSocket</b> must be 1 if fd
  1468. * was returned by socket() or accept(), and 0 if fd was returned by
  1469. * open(). Return the number of bytes read, or -1 on error. Only use
  1470. * if fd is a blocking fd. */
  1471. ssize_t
  1472. read_all(int fd, char *buf, size_t count, int isSocket)
  1473. {
  1474. size_t numread = 0;
  1475. ssize_t result;
  1476. if (count > SIZE_T_CEILING || count > SSIZE_T_MAX)
  1477. return -1;
  1478. while (numread != count) {
  1479. if (isSocket)
  1480. result = tor_socket_recv(fd, buf+numread, count-numread, 0);
  1481. else
  1482. result = read(fd, buf+numread, count-numread);
  1483. if (result<0)
  1484. return -1;
  1485. else if (result == 0)
  1486. break;
  1487. numread += result;
  1488. }
  1489. return (ssize_t)numread;
  1490. }
  1491. /*
  1492. * Filesystem operations.
  1493. */
  1494. /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
  1495. * we do nothing. On Windows, we remove a trailing slash, unless the path is
  1496. * the root of a disk. */
  1497. static void
  1498. clean_name_for_stat(char *name)
  1499. {
  1500. #ifdef MS_WINDOWS
  1501. size_t len = strlen(name);
  1502. if (!len)
  1503. return;
  1504. if (name[len-1]=='\\' || name[len-1]=='/') {
  1505. if (len == 1 || (len==3 && name[1]==':'))
  1506. return;
  1507. name[len-1]='\0';
  1508. }
  1509. #else
  1510. (void)name;
  1511. #endif
  1512. }
  1513. /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  1514. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  1515. * directory. On FN_ERROR, sets errno. */
  1516. file_status_t
  1517. file_status(const char *fname)
  1518. {
  1519. struct stat st;
  1520. char *f;
  1521. int r;
  1522. f = tor_strdup(fname);
  1523. clean_name_for_stat(f);
  1524. r = stat(f, &st);
  1525. tor_free(f);
  1526. if (r) {
  1527. if (errno == ENOENT) {
  1528. return FN_NOENT;
  1529. }
  1530. return FN_ERROR;
  1531. }
  1532. if (st.st_mode & S_IFDIR)
  1533. return FN_DIR;
  1534. else if (st.st_mode & S_IFREG)
  1535. return FN_FILE;
  1536. else
  1537. return FN_ERROR;
  1538. }
  1539. /** Check whether dirname exists and is private. If yes return 0. If
  1540. * it does not exist, and check==CPD_CREATE is set, try to create it
  1541. * and return 0 on success. If it does not exist, and
  1542. * check==CPD_CHECK, and we think we can create it, return 0. Else
  1543. * return -1. */
  1544. int
  1545. check_private_dir(const char *dirname, cpd_check_t check)
  1546. {
  1547. int r;
  1548. struct stat st;
  1549. char *f;
  1550. tor_assert(dirname);
  1551. f = tor_strdup(dirname);
  1552. clean_name_for_stat(f);
  1553. r = stat(f, &st);
  1554. tor_free(f);
  1555. if (r) {
  1556. if (errno != ENOENT) {
  1557. log_warn(LD_FS, "Directory %s cannot be read: %s", dirname,
  1558. strerror(errno));
  1559. return -1;
  1560. }
  1561. if (check == CPD_NONE) {
  1562. log_warn(LD_FS, "Directory %s does not exist.", dirname);
  1563. return -1;
  1564. } else if (check == CPD_CREATE) {
  1565. log_info(LD_GENERAL, "Creating directory %s", dirname);
  1566. #if defined (MS_WINDOWS) && !defined (WINCE)
  1567. r = mkdir(dirname);
  1568. #else
  1569. r = mkdir(dirname, 0700);
  1570. #endif
  1571. if (r) {
  1572. log_warn(LD_FS, "Error creating directory %s: %s", dirname,
  1573. strerror(errno));
  1574. return -1;
  1575. }
  1576. }
  1577. /* XXXX In the case where check==CPD_CHECK, we should look at the
  1578. * parent directory a little harder. */
  1579. return 0;
  1580. }
  1581. if (!(st.st_mode & S_IFDIR)) {
  1582. log_warn(LD_FS, "%s is not a directory", dirname);
  1583. return -1;
  1584. }
  1585. #ifndef MS_WINDOWS
  1586. if (st.st_uid != getuid()) {
  1587. struct passwd *pw = NULL;
  1588. char *process_ownername = NULL;
  1589. pw = getpwuid(getuid());
  1590. process_ownername = pw ? tor_strdup(pw->pw_name) : tor_strdup("<unknown>");
  1591. pw = getpwuid(st.st_uid);
  1592. log_warn(LD_FS, "%s is not owned by this user (%s, %d) but by "
  1593. "%s (%d). Perhaps you are running Tor as the wrong user?",
  1594. dirname, process_ownername, (int)getuid(),
  1595. pw ? pw->pw_name : "<unknown>", (int)st.st_uid);
  1596. tor_free(process_ownername);
  1597. return -1;
  1598. }
  1599. if (st.st_mode & 0077) {
  1600. log_warn(LD_FS, "Fixing permissions on directory %s", dirname);
  1601. if (chmod(dirname, 0700)) {
  1602. log_warn(LD_FS, "Could not chmod directory %s: %s", dirname,
  1603. strerror(errno));
  1604. return -1;
  1605. } else {
  1606. return 0;
  1607. }
  1608. }
  1609. #endif
  1610. return 0;
  1611. }
  1612. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite
  1613. * the previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  1614. *
  1615. * This function replaces the old file atomically, if possible. This
  1616. * function, and all other functions in util.c that create files, create them
  1617. * with mode 0600.
  1618. */
  1619. int
  1620. write_str_to_file(const char *fname, const char *str, int bin)
  1621. {
  1622. #ifdef MS_WINDOWS
  1623. if (!bin && strchr(str, '\r')) {
  1624. log_warn(LD_BUG,
  1625. "We're writing a text string that already contains a CR.");
  1626. }
  1627. #endif
  1628. return write_bytes_to_file(fname, str, strlen(str), bin);
  1629. }
  1630. /** Represents a file that we're writing to, with support for atomic commit:
  1631. * we can write into a temporary file, and either remove the file on
  1632. * failure, or replace the original file on success. */
  1633. struct open_file_t {
  1634. char *tempname; /**< Name of the temporary file. */
  1635. char *filename; /**< Name of the original file. */
  1636. unsigned rename_on_close:1; /**< Are we using the temporary file or not? */
  1637. unsigned binary:1; /**< Did we open in binary mode? */
  1638. int fd; /**< fd for the open file. */
  1639. FILE *stdio_file; /**< stdio wrapper for <b>fd</b>. */
  1640. };
  1641. /** Try to start writing to the file in <b>fname</b>, passing the flags
  1642. * <b>open_flags</b> to the open() syscall, creating the file (if needed) with
  1643. * access value <b>mode</b>. If the O_APPEND flag is set, we append to the
  1644. * original file. Otherwise, we open a new temporary file in the same
  1645. * directory, and either replace the original or remove the temporary file
  1646. * when we're done.
  1647. *
  1648. * Return the fd for the newly opened file, and store working data in
  1649. * *<b>data_out</b>. The caller should not close the fd manually:
  1650. * instead, call finish_writing_to_file() or abort_writing_to_file().
  1651. * Returns -1 on failure.
  1652. *
  1653. * NOTE: When not appending, the flags O_CREAT and O_TRUNC are treated
  1654. * as true and the flag O_EXCL is treated as false.
  1655. *
  1656. * NOTE: Ordinarily, O_APPEND means "seek to the end of the file before each
  1657. * write()". We don't do that.
  1658. */
  1659. int
  1660. start_writing_to_file(const char *fname, int open_flags, int mode,
  1661. open_file_t **data_out)
  1662. {
  1663. size_t tempname_len = strlen(fname)+16;
  1664. open_file_t *new_file = tor_malloc_zero(sizeof(open_file_t));
  1665. const char *open_name;
  1666. int append = 0;
  1667. tor_assert(fname);
  1668. tor_assert(data_out);
  1669. #if (O_BINARY != 0 && O_TEXT != 0)
  1670. tor_assert((open_flags & (O_BINARY|O_TEXT)) != 0);
  1671. #endif
  1672. new_file->fd = -1;
  1673. tor_assert(tempname_len > strlen(fname)); /*check for overflow*/
  1674. new_file->filename = tor_strdup(fname);
  1675. if (open_flags & O_APPEND) {
  1676. open_name = fname;
  1677. new_file->rename_on_close = 0;
  1678. append = 1;
  1679. open_flags &= ~O_APPEND;
  1680. } else {
  1681. open_name = new_file->tempname = tor_malloc(tempname_len);
  1682. if (tor_snprintf(new_file->tempname, tempname_len, "%s.tmp", fname)<0) {
  1683. log_warn(LD_GENERAL, "Failed to generate filename");
  1684. goto err;
  1685. }
  1686. /* We always replace an existing temporary file if there is one. */
  1687. open_flags |= O_CREAT|O_TRUNC;
  1688. open_flags &= ~O_EXCL;
  1689. new_file->rename_on_close = 1;
  1690. }
  1691. if (open_flags & O_BINARY)
  1692. new_file->binary = 1;
  1693. new_file->fd = open(open_name, open_flags, mode);
  1694. if (new_file->fd < 0) {
  1695. log_warn(LD_FS, "Couldn't open \"%s\" (%s) for writing: %s",
  1696. open_name, fname, strerror(errno));
  1697. goto err;
  1698. }
  1699. if (append) {
  1700. if (tor_fd_seekend(new_file->fd) < 0) {
  1701. log_warn(LD_FS, "Couldn't seek to end of file \"%s\": %s", open_name,
  1702. strerror(errno));
  1703. goto err;
  1704. }
  1705. }
  1706. *data_out = new_file;
  1707. return new_file->fd;
  1708. err:
  1709. if (new_file->fd >= 0)
  1710. close(new_file->fd);
  1711. *data_out = NULL;
  1712. tor_free(new_file->filename);
  1713. tor_free(new_file->tempname);
  1714. tor_free(new_file);
  1715. return -1;
  1716. }
  1717. /** Given <b>file_data</b> from start_writing_to_file(), return a stdio FILE*
  1718. * that can be used to write to the same file. The caller should not mix
  1719. * stdio calls with non-stdio calls. */
  1720. FILE *
  1721. fdopen_file(open_file_t *file_data)
  1722. {
  1723. tor_assert(file_data);
  1724. if (file_data->stdio_file)
  1725. return file_data->stdio_file;
  1726. tor_assert(file_data->fd >= 0);
  1727. if (!(file_data->stdio_file = fdopen(file_data->fd,
  1728. file_data->binary?"ab":"a"))) {
  1729. log_warn(LD_FS, "Couldn't fdopen \"%s\" [%d]: %s", file_data->filename,
  1730. file_data->fd, strerror(errno));
  1731. }
  1732. return file_data->stdio_file;
  1733. }
  1734. /** Combines start_writing_to_file with fdopen_file(): arguments are as
  1735. * for start_writing_to_file, but */
  1736. FILE *
  1737. start_writing_to_stdio_file(const char *fname, int open_flags, int mode,
  1738. open_file_t **data_out)
  1739. {
  1740. FILE *res;
  1741. if (start_writing_to_file(fname, open_flags, mode, data_out)<0)
  1742. return NULL;
  1743. if (!(res = fdopen_file(*data_out))) {
  1744. abort_writing_to_file(*data_out);
  1745. *data_out = NULL;
  1746. }
  1747. return res;
  1748. }
  1749. /** Helper function: close and free the underlying file and memory in
  1750. * <b>file_data</b>. If we were writing into a temporary file, then delete
  1751. * that file (if abort_write is true) or replaces the target file with
  1752. * the temporary file (if abort_write is false). */
  1753. static int
  1754. finish_writing_to_file_impl(open_file_t *file_data, int abort_write)
  1755. {
  1756. int r = 0;
  1757. tor_assert(file_data && file_data->filename);
  1758. if (file_data->stdio_file) {
  1759. if (fclose(file_data->stdio_file)) {
  1760. log_warn(LD_FS, "Error closing \"%s\": %s", file_data->filename,
  1761. strerror(errno));
  1762. abort_write = r = -1;
  1763. }
  1764. } else if (file_data->fd >= 0 && close(file_data->fd) < 0) {
  1765. log_warn(LD_FS, "Error flushing \"%s\": %s", file_data->filename,
  1766. strerror(errno));
  1767. abort_write = r = -1;
  1768. }
  1769. if (file_data->rename_on_close) {
  1770. tor_assert(file_data->tempname && file_data->filename);
  1771. if (abort_write) {
  1772. unlink(file_data->tempname);
  1773. } else {
  1774. tor_assert(strcmp(file_data->filename, file_data->tempname));
  1775. if (replace_file(file_data->tempname, file_data->filename)) {
  1776. log_warn(LD_FS, "Error replacing \"%s\": %s", file_data->filename,
  1777. strerror(errno));
  1778. r = -1;
  1779. }
  1780. }
  1781. }
  1782. tor_free(file_data->filename);
  1783. tor_free(file_data->tempname);
  1784. tor_free(file_data);
  1785. return r;
  1786. }
  1787. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1788. * needed, and if using a temporary file, replace the original file with
  1789. * the temporary file. */
  1790. int
  1791. finish_writing_to_file(open_file_t *file_data)
  1792. {
  1793. return finish_writing_to_file_impl(file_data, 0);
  1794. }
  1795. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1796. * needed, and if using a temporary file, delete it. */
  1797. int
  1798. abort_writing_to_file(open_file_t *file_data)
  1799. {
  1800. return finish_writing_to_file_impl(file_data, 1);
  1801. }
  1802. /** Helper: given a set of flags as passed to open(2), open the file
  1803. * <b>fname</b> and write all the sized_chunk_t structs in <b>chunks</b> to
  1804. * the file. Do so as atomically as possible e.g. by opening temp files and
  1805. * renaming. */
  1806. static int
  1807. write_chunks_to_file_impl(const char *fname, const smartlist_t *chunks,
  1808. int open_flags)
  1809. {
  1810. open_file_t *file = NULL;
  1811. int fd;
  1812. ssize_t result;
  1813. fd = start_writing_to_file(fname, open_flags, 0600, &file);
  1814. if (fd<0)
  1815. return -1;
  1816. SMARTLIST_FOREACH(chunks, sized_chunk_t *, chunk,
  1817. {
  1818. result = write_all(fd, chunk->bytes, chunk->len, 0);
  1819. if (result < 0) {
  1820. log_warn(LD_FS, "Error writing to \"%s\": %s", fname,
  1821. strerror(errno));
  1822. goto err;
  1823. }
  1824. tor_assert((size_t)result == chunk->len);
  1825. });
  1826. return finish_writing_to_file(file);
  1827. err:
  1828. abort_writing_to_file(file);
  1829. return -1;
  1830. }
  1831. /** Given a smartlist of sized_chunk_t, write them atomically to a file
  1832. * <b>fname</b>, overwriting or creating the file as necessary. */
  1833. int
  1834. write_chunks_to_file(const char *fname, const smartlist_t *chunks, int bin)
  1835. {
  1836. int flags = OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT);
  1837. return write_chunks_to_file_impl(fname, chunks, flags);
  1838. }
  1839. /** As write_str_to_file, but does not assume a NUL-terminated
  1840. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  1841. int
  1842. write_bytes_to_file(const char *fname, const char *str, size_t len,
  1843. int bin)
  1844. {
  1845. int flags = OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT);
  1846. int r;
  1847. sized_chunk_t c = { str, len };
  1848. smartlist_t *chunks = smartlist_create();
  1849. smartlist_add(chunks, &c);
  1850. r = write_chunks_to_file_impl(fname, chunks, flags);
  1851. smartlist_free(chunks);
  1852. return r;
  1853. }
  1854. /** As write_bytes_to_file, but if the file already exists, append the bytes
  1855. * to the end of the file instead of overwriting it. */
  1856. int
  1857. append_bytes_to_file(const char *fname, const char *str, size_t len,
  1858. int bin)
  1859. {
  1860. int flags = OPEN_FLAGS_APPEND|(bin?O_BINARY:O_TEXT);
  1861. int r;
  1862. sized_chunk_t c = { str, len };
  1863. smartlist_t *chunks = smartlist_create();
  1864. smartlist_add(chunks, &c);
  1865. r = write_chunks_to_file_impl(fname, chunks, flags);
  1866. smartlist_free(chunks);
  1867. return r;
  1868. }
  1869. /** Read the contents of <b>filename</b> into a newly allocated
  1870. * string; return the string on success or NULL on failure.
  1871. *
  1872. * If <b>stat_out</b> is provided, store the result of stat()ing the
  1873. * file into <b>stat_out</b>.
  1874. *
  1875. * If <b>flags</b> &amp; RFTS_BIN, open the file in binary mode.
  1876. * If <b>flags</b> &amp; RFTS_IGNORE_MISSING, don't warn if the file
  1877. * doesn't exist.
  1878. */
  1879. /*
  1880. * This function <em>may</em> return an erroneous result if the file
  1881. * is modified while it is running, but must not crash or overflow.
  1882. * Right now, the error case occurs when the file length grows between
  1883. * the call to stat and the call to read_all: the resulting string will
  1884. * be truncated.
  1885. */
  1886. char *
  1887. read_file_to_str(const char *filename, int flags, struct stat *stat_out)
  1888. {
  1889. int fd; /* router file */
  1890. struct stat statbuf;
  1891. char *string;
  1892. ssize_t r;
  1893. int bin = flags & RFTS_BIN;
  1894. tor_assert(filename);
  1895. fd = open(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  1896. if (fd<0) {
  1897. int severity = LOG_WARN;
  1898. int save_errno = errno;
  1899. if (errno == ENOENT && (flags & RFTS_IGNORE_MISSING))
  1900. severity = LOG_INFO;
  1901. log_fn(severity, LD_FS,"Could not open \"%s\": %s ",filename,
  1902. strerror(errno));
  1903. errno = save_errno;
  1904. return NULL;
  1905. }
  1906. if (fstat(fd, &statbuf)<0) {
  1907. int save_errno = errno;
  1908. close(fd);
  1909. log_warn(LD_FS,"Could not fstat \"%s\".",filename);
  1910. errno = save_errno;
  1911. return NULL;
  1912. }
  1913. if ((uint64_t)(statbuf.st_size)+1 > SIZE_T_MAX)
  1914. return NULL;
  1915. string = tor_malloc((size_t)(statbuf.st_size+1));
  1916. r = read_all(fd,string,(size_t)statbuf.st_size,0);
  1917. if (r<0) {
  1918. int save_errno = errno;
  1919. log_warn(LD_FS,"Error reading from file \"%s\": %s", filename,
  1920. strerror(errno));
  1921. tor_free(string);
  1922. close(fd);
  1923. errno = save_errno;
  1924. return NULL;
  1925. }
  1926. string[r] = '\0'; /* NUL-terminate the result. */
  1927. #ifdef MS_WINDOWS
  1928. if (!bin && strchr(string, '\r')) {
  1929. log_debug(LD_FS, "We didn't convert CRLF to LF as well as we hoped "
  1930. "when reading %s. Coping.",
  1931. filename);
  1932. tor_strstrip(string, "\r");
  1933. r = strlen(string);
  1934. }
  1935. if (!bin) {
  1936. statbuf.st_size = (size_t) r;
  1937. } else
  1938. #endif
  1939. if (r != statbuf.st_size) {
  1940. /* Unless we're using text mode on win32, we'd better have an exact
  1941. * match for size. */
  1942. int save_errno = errno;
  1943. log_warn(LD_FS,"Could read only %d of %ld bytes of file \"%s\".",
  1944. (int)r, (long)statbuf.st_size,filename);
  1945. tor_free(string);
  1946. close(fd);
  1947. errno = save_errno;
  1948. return NULL;
  1949. }
  1950. close(fd);
  1951. if (stat_out) {
  1952. memcpy(stat_out, &statbuf, sizeof(struct stat));
  1953. }
  1954. return string;
  1955. }
  1956. #define TOR_ISODIGIT(c) ('0' <= (c) && (c) <= '7')
  1957. /** Given a c-style double-quoted escaped string in <b>s</b>, extract and
  1958. * decode its contents into a newly allocated string. On success, assign this
  1959. * string to *<b>result</b>, assign its length to <b>size_out</b> (if
  1960. * provided), and return a pointer to the position in <b>s</b> immediately
  1961. * after the string. On failure, return NULL.
  1962. */
  1963. static const char *
  1964. unescape_string(const char *s, char **result, size_t *size_out)
  1965. {
  1966. const char *cp;
  1967. char *out;
  1968. if (s[0] != '\"')
  1969. return NULL;
  1970. cp = s+1;
  1971. while (1) {
  1972. switch (*cp) {
  1973. case '\0':
  1974. case '\n':
  1975. return NULL;
  1976. case '\"':
  1977. goto end_of_loop;
  1978. case '\\':
  1979. if ((cp[1] == 'x' || cp[1] == 'X')
  1980. && TOR_ISXDIGIT(cp[2]) && TOR_ISXDIGIT(cp[3])) {
  1981. cp += 4;
  1982. } else if (TOR_ISODIGIT(cp[1])) {
  1983. cp += 2;
  1984. if (TOR_ISODIGIT(*cp)) ++cp;
  1985. if (TOR_ISODIGIT(*cp)) ++cp;
  1986. } else if (cp[1]) {
  1987. cp += 2;
  1988. } else {
  1989. return NULL;
  1990. }
  1991. break;
  1992. default:
  1993. ++cp;
  1994. break;
  1995. }
  1996. }
  1997. end_of_loop:
  1998. out = *result = tor_malloc(cp-s + 1);
  1999. cp = s+1;
  2000. while (1) {
  2001. switch (*cp)
  2002. {
  2003. case '\"':
  2004. *out = '\0';
  2005. if (size_out) *size_out = out - *result;
  2006. return cp+1;
  2007. case '\0':
  2008. tor_fragile_assert();
  2009. tor_free(*result);
  2010. return NULL;
  2011. case '\\':
  2012. switch (cp[1])
  2013. {
  2014. case 'n': *out++ = '\n'; cp += 2; break;
  2015. case 'r': *out++ = '\r'; cp += 2; break;
  2016. case 't': *out++ = '\t'; cp += 2; break;
  2017. case 'x': case 'X':
  2018. *out++ = ((hex_decode_digit(cp[2])<<4) +
  2019. hex_decode_digit(cp[3]));
  2020. cp += 4;
  2021. break;
  2022. case '0': case '1': case '2': case '3': case '4': case '5':
  2023. case '6': case '7':
  2024. {
  2025. int n = cp[1]-'0';
  2026. cp += 2;
  2027. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2028. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2029. if (n > 255) { tor_free(*result); return NULL; }
  2030. *out++ = (char)n;
  2031. }
  2032. break;
  2033. case '\'':
  2034. case '\"':
  2035. case '\\':
  2036. case '\?':
  2037. *out++ = cp[1];
  2038. cp += 2;
  2039. break;
  2040. default:
  2041. tor_free(*result); return NULL;
  2042. }
  2043. break;
  2044. default:
  2045. *out++ = *cp++;
  2046. }
  2047. }
  2048. }
  2049. /** Given a string containing part of a configuration file or similar format,
  2050. * advance past comments and whitespace and try to parse a single line. If we
  2051. * parse a line successfully, set *<b>key_out</b> to a new string holding the
  2052. * key portion and *<b>value_out</b> to a new string holding the value portion
  2053. * of the line, and return a pointer to the start of the next line. If we run
  2054. * out of data, return a pointer to the end of the string. If we encounter an
  2055. * error, return NULL.
  2056. */
  2057. const char *
  2058. parse_config_line_from_str(const char *line, char **key_out, char **value_out)
  2059. {
  2060. const char *key, *val, *cp;
  2061. tor_assert(key_out);
  2062. tor_assert(value_out);
  2063. *key_out = *value_out = NULL;
  2064. key = val = NULL;
  2065. /* Skip until the first keyword. */
  2066. while (1) {
  2067. while (TOR_ISSPACE(*line))
  2068. ++line;
  2069. if (*line == '#') {
  2070. while (*line && *line != '\n')
  2071. ++line;
  2072. } else {
  2073. break;
  2074. }
  2075. }
  2076. if (!*line) { /* End of string? */
  2077. *key_out = *value_out = NULL;
  2078. return line;
  2079. }
  2080. /* Skip until the next space. */
  2081. key = line;
  2082. while (*line && !TOR_ISSPACE(*line) && *line != '#')
  2083. ++line;
  2084. *key_out = tor_strndup(key, line-key);
  2085. /* Skip until the value. */
  2086. while (*line == ' ' || *line == '\t')
  2087. ++line;
  2088. val = line;
  2089. /* Find the end of the line. */
  2090. if (*line == '\"') {
  2091. if (!(line = unescape_string(line, value_out, NULL)))
  2092. return NULL;
  2093. while (*line == ' ' || *line == '\t')
  2094. ++line;
  2095. if (*line && *line != '#' && *line != '\n')
  2096. return NULL;
  2097. } else {
  2098. while (*line && *line != '\n' && *line != '#')
  2099. ++line;
  2100. if (*line == '\n') {
  2101. cp = line++;
  2102. } else {
  2103. cp = line;
  2104. }
  2105. while (cp>val && TOR_ISSPACE(*(cp-1)))
  2106. --cp;
  2107. tor_assert(cp >= val);
  2108. *value_out = tor_strndup(val, cp-val);
  2109. }
  2110. if (*line == '#') {
  2111. do {
  2112. ++line;
  2113. } while (*line && *line != '\n');
  2114. }
  2115. while (TOR_ISSPACE(*line)) ++line;
  2116. return line;
  2117. }
  2118. /** Expand any homedir prefix on <b>filename</b>; return a newly allocated
  2119. * string. */
  2120. char *
  2121. expand_filename(const char *filename)
  2122. {
  2123. tor_assert(filename);
  2124. #ifdef MS_WINDOWS
  2125. return tor_strdup(filename);
  2126. #else
  2127. if (*filename == '~') {
  2128. char *home, *result=NULL;
  2129. const char *rest;
  2130. if (filename[1] == '/' || filename[1] == '\0') {
  2131. home = getenv("HOME");
  2132. if (!home) {
  2133. log_warn(LD_CONFIG, "Couldn't find $HOME environment variable while "
  2134. "expanding \"%s\"; defaulting to \"\".", filename);
  2135. home = tor_strdup("");
  2136. } else {
  2137. home = tor_strdup(home);
  2138. }
  2139. rest = strlen(filename)>=2?(filename+2):"";
  2140. } else {
  2141. #ifdef HAVE_PWD_H
  2142. char *username, *slash;
  2143. slash = strchr(filename, '/');
  2144. if (slash)
  2145. username = tor_strndup(filename+1,slash-filename-1);
  2146. else
  2147. username = tor_strdup(filename+1);
  2148. if (!(home = get_user_homedir(username))) {
  2149. log_warn(LD_CONFIG,"Couldn't get homedir for \"%s\"",username);
  2150. tor_free(username);
  2151. return NULL;
  2152. }
  2153. tor_free(username);
  2154. rest = slash ? (slash+1) : "";
  2155. #else
  2156. log_warn(LD_CONFIG, "Couldn't expend homedir on system without pwd.h");
  2157. return tor_strdup(filename);
  2158. #endif
  2159. }
  2160. tor_assert(home);
  2161. /* Remove trailing slash. */
  2162. if (strlen(home)>1 && !strcmpend(home,PATH_SEPARATOR)) {
  2163. home[strlen(home)-1] = '\0';
  2164. }
  2165. tor_asprintf(&result,"%s"PATH_SEPARATOR"%s",home,rest);
  2166. tor_free(home);
  2167. return result;
  2168. } else {
  2169. return tor_strdup(filename);
  2170. }
  2171. #endif
  2172. }
  2173. #define MAX_SCANF_WIDTH 9999
  2174. /** Helper: given an ASCII-encoded decimal digit, return its numeric value.
  2175. * NOTE: requires that its input be in-bounds. */
  2176. static int
  2177. digit_to_num(char d)
  2178. {
  2179. int num = ((int)d) - (int)'0';
  2180. tor_assert(num <= 9 && num >= 0);
  2181. return num;
  2182. }
  2183. /** Helper: Read an unsigned int from *<b>bufp</b> of up to <b>width</b>
  2184. * characters. (Handle arbitrary width if <b>width</b> is less than 0.) On
  2185. * success, store the result in <b>out</b>, advance bufp to the next
  2186. * character, and return 0. On failure, return -1. */
  2187. static int
  2188. scan_unsigned(const char **bufp, unsigned *out, int width)
  2189. {
  2190. unsigned result = 0;
  2191. int scanned_so_far = 0;
  2192. if (!bufp || !*bufp || !out)
  2193. return -1;
  2194. if (width<0)
  2195. width=MAX_SCANF_WIDTH;
  2196. while (**bufp && TOR_ISDIGIT(**bufp) && scanned_so_far < width) {
  2197. int digit = digit_to_num(*(*bufp)++);
  2198. unsigned new_result = result * 10 + digit;
  2199. if (new_result > UINT32_MAX || new_result < result)
  2200. return -1; /* over/underflow. */
  2201. result = new_result;
  2202. ++scanned_so_far;
  2203. }
  2204. if (!scanned_so_far) /* No actual digits scanned */
  2205. return -1;
  2206. *out = result;
  2207. return 0;
  2208. }
  2209. /** Helper: copy up to <b>width</b> non-space characters from <b>bufp</b> to
  2210. * <b>out</b>. Make sure <b>out</b> is nul-terminated. Advance <b>bufp</b>
  2211. * to the next non-space character or the EOS. */
  2212. static int
  2213. scan_string(const char **bufp, char *out, int width)
  2214. {
  2215. int scanned_so_far = 0;
  2216. if (!bufp || !out || width < 0)
  2217. return -1;
  2218. while (**bufp && ! TOR_ISSPACE(**bufp) && scanned_so_far < width) {
  2219. *out++ = *(*bufp)++;
  2220. ++scanned_so_far;
  2221. }
  2222. *out = '\0';
  2223. return 0;
  2224. }
  2225. /** Locale-independent, minimal, no-surprises scanf variant, accepting only a
  2226. * restricted pattern format. For more info on what it supports, see
  2227. * tor_sscanf() documentation. */
  2228. int
  2229. tor_vsscanf(const char *buf, const char *pattern, va_list ap)
  2230. {
  2231. int n_matched = 0;
  2232. while (*pattern) {
  2233. if (*pattern != '%') {
  2234. if (*buf == *pattern) {
  2235. ++buf;
  2236. ++pattern;
  2237. continue;
  2238. } else {
  2239. return n_matched;
  2240. }
  2241. } else {
  2242. int width = -1;
  2243. ++pattern;
  2244. if (TOR_ISDIGIT(*pattern)) {
  2245. width = digit_to_num(*pattern++);
  2246. while (TOR_ISDIGIT(*pattern)) {
  2247. width *= 10;
  2248. width += digit_to_num(*pattern++);
  2249. if (width > MAX_SCANF_WIDTH)
  2250. return -1;
  2251. }
  2252. if (!width) /* No zero-width things. */
  2253. return -1;
  2254. }
  2255. if (*pattern == 'u') {
  2256. unsigned *u = va_arg(ap, unsigned *);
  2257. if (!*buf)
  2258. return n_matched;
  2259. if (scan_unsigned(&buf, u, width)<0)
  2260. return n_matched;
  2261. ++pattern;
  2262. ++n_matched;
  2263. } else if (*pattern == 's') {
  2264. char *s = va_arg(ap, char *);
  2265. if (width < 0)
  2266. return -1;
  2267. if (scan_string(&buf, s, width)<0)
  2268. return n_matched;
  2269. ++pattern;
  2270. ++n_matched;
  2271. } else if (*pattern == 'c') {
  2272. char *ch = va_arg(ap, char *);
  2273. if (width != -1)
  2274. return -1;
  2275. if (!*buf)
  2276. return n_matched;
  2277. *ch = *buf++;
  2278. ++pattern;
  2279. ++n_matched;
  2280. } else if (*pattern == '%') {
  2281. if (*buf != '%')
  2282. return -1;
  2283. ++buf;
  2284. ++pattern;
  2285. } else {
  2286. return -1; /* Unrecognized pattern component. */
  2287. }
  2288. }
  2289. }
  2290. return n_matched;
  2291. }
  2292. /** Minimal sscanf replacement: parse <b>buf</b> according to <b>pattern</b>
  2293. * and store the results in the corresponding argument fields. Differs from
  2294. * sscanf in that it: Only handles %u and %Ns. Does not handle arbitrarily
  2295. * long widths. %u does not consume any space. Is locale-independent.
  2296. * Returns -1 on malformed patterns.
  2297. *
  2298. * (As with other locale-independent functions, we need this to parse data that
  2299. * is in ASCII without worrying that the C library's locale-handling will make
  2300. * miscellaneous characters look like numbers, spaces, and so on.)
  2301. */
  2302. int
  2303. tor_sscanf(const char *buf, const char *pattern, ...)
  2304. {
  2305. int r;
  2306. va_list ap;
  2307. va_start(ap, pattern);
  2308. r = tor_vsscanf(buf, pattern, ap);
  2309. va_end(ap);
  2310. return r;
  2311. }
  2312. /** Return a new list containing the filenames in the directory <b>dirname</b>.
  2313. * Return NULL on error or if <b>dirname</b> is not a directory.
  2314. */
  2315. smartlist_t *
  2316. tor_listdir(const char *dirname)
  2317. {
  2318. smartlist_t *result;
  2319. #ifdef MS_WINDOWS
  2320. char *pattern;
  2321. WCHAR wpattern[MAX_PATH] = {0};
  2322. char name[MAX_PATH] = {0};
  2323. HANDLE handle;
  2324. WIN32_FIND_DATAW findData;
  2325. size_t pattern_len = strlen(dirname)+16;
  2326. pattern = tor_malloc(pattern_len);
  2327. tor_snprintf(pattern, pattern_len, "%s\\*", dirname);
  2328. mbstowcs(wpattern,pattern,MAX_PATH);
  2329. if (INVALID_HANDLE_VALUE == (handle = FindFirstFileW(wpattern, &findData))) {
  2330. tor_free(pattern);
  2331. return NULL;
  2332. }
  2333. wcstombs(name,findData.cFileName,MAX_PATH);
  2334. result = smartlist_create();
  2335. while (1) {
  2336. if (strcmp(name, ".") &&
  2337. strcmp(name, "..")) {
  2338. smartlist_add(result, tor_strdup(name));
  2339. }
  2340. if (!FindNextFileW(handle, &findData)) {
  2341. DWORD err;
  2342. if ((err = GetLastError()) != ERROR_NO_MORE_FILES) {
  2343. char *errstr = format_win32_error(err);
  2344. log_warn(LD_FS, "Error reading directory '%s': %s", dirname, errstr);
  2345. tor_free(errstr);
  2346. }
  2347. break;
  2348. }
  2349. }
  2350. FindClose(handle);
  2351. tor_free(pattern);
  2352. #else
  2353. DIR *d;
  2354. struct dirent *de;
  2355. if (!(d = opendir(dirname)))
  2356. return NULL;
  2357. result = smartlist_create();
  2358. while ((de = readdir(d))) {
  2359. if (!strcmp(de->d_name, ".") ||
  2360. !strcmp(de->d_name, ".."))
  2361. continue;
  2362. smartlist_add(result, tor_strdup(de->d_name));
  2363. }
  2364. closedir(d);
  2365. #endif
  2366. return result;
  2367. }
  2368. /** Return true iff <b>filename</b> is a relative path. */
  2369. int
  2370. path_is_relative(const char *filename)
  2371. {
  2372. if (filename && filename[0] == '/')
  2373. return 0;
  2374. #ifdef MS_WINDOWS
  2375. else if (filename && filename[0] == '\\')
  2376. return 0;
  2377. else if (filename && strlen(filename)>3 && TOR_ISALPHA(filename[0]) &&
  2378. filename[1] == ':' && filename[2] == '\\')
  2379. return 0;
  2380. #endif
  2381. else
  2382. return 1;
  2383. }
  2384. /* =====
  2385. * Process helpers
  2386. * ===== */
  2387. #ifndef MS_WINDOWS
  2388. /* Based on code contributed by christian grothoff */
  2389. /** True iff we've called start_daemon(). */
  2390. static int start_daemon_called = 0;
  2391. /** True iff we've called finish_daemon(). */
  2392. static int finish_daemon_called = 0;
  2393. /** Socketpair used to communicate between parent and child process while
  2394. * daemonizing. */
  2395. static int daemon_filedes[2];
  2396. /** Start putting the process into daemon mode: fork and drop all resources
  2397. * except standard fds. The parent process never returns, but stays around
  2398. * until finish_daemon is called. (Note: it's safe to call this more
  2399. * than once: calls after the first are ignored.)
  2400. */
  2401. void
  2402. start_daemon(void)
  2403. {
  2404. pid_t pid;
  2405. if (start_daemon_called)
  2406. return;
  2407. start_daemon_called = 1;
  2408. if (pipe(daemon_filedes)) {
  2409. log_err(LD_GENERAL,"pipe failed; exiting. Error was %s", strerror(errno));
  2410. exit(1);
  2411. }
  2412. pid = fork();
  2413. if (pid < 0) {
  2414. log_err(LD_GENERAL,"fork failed. Exiting.");
  2415. exit(1);
  2416. }
  2417. if (pid) { /* Parent */
  2418. int ok;
  2419. char c;
  2420. close(daemon_filedes[1]); /* we only read */
  2421. ok = -1;
  2422. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  2423. if (c == '.')
  2424. ok = 1;
  2425. }
  2426. fflush(stdout);
  2427. if (ok == 1)
  2428. exit(0);
  2429. else
  2430. exit(1); /* child reported error */
  2431. } else { /* Child */
  2432. close(daemon_filedes[0]); /* we only write */
  2433. pid = setsid(); /* Detach from controlling terminal */
  2434. /*
  2435. * Fork one more time, so the parent (the session group leader) can exit.
  2436. * This means that we, as a non-session group leader, can never regain a
  2437. * controlling terminal. This part is recommended by Stevens's
  2438. * _Advanced Programming in the Unix Environment_.
  2439. */
  2440. if (fork() != 0) {
  2441. exit(0);
  2442. }
  2443. set_main_thread(); /* We are now the main thread. */
  2444. return;
  2445. }
  2446. }
  2447. /** Finish putting the process into daemon mode: drop standard fds, and tell
  2448. * the parent process to exit. (Note: it's safe to call this more than once:
  2449. * calls after the first are ignored. Calls start_daemon first if it hasn't
  2450. * been called already.)
  2451. */
  2452. void
  2453. finish_daemon(const char *desired_cwd)
  2454. {
  2455. int nullfd;
  2456. char c = '.';
  2457. if (finish_daemon_called)
  2458. return;
  2459. if (!start_daemon_called)
  2460. start_daemon();
  2461. finish_daemon_called = 1;
  2462. if (!desired_cwd)
  2463. desired_cwd = "/";
  2464. /* Don't hold the wrong FS mounted */
  2465. if (chdir(desired_cwd) < 0) {
  2466. log_err(LD_GENERAL,"chdir to \"%s\" failed. Exiting.",desired_cwd);
  2467. exit(1);
  2468. }
  2469. nullfd = open("/dev/null", O_RDWR);
  2470. if (nullfd < 0) {
  2471. log_err(LD_GENERAL,"/dev/null can't be opened. Exiting.");
  2472. exit(1);
  2473. }
  2474. /* close fds linking to invoking terminal, but
  2475. * close usual incoming fds, but redirect them somewhere
  2476. * useful so the fds don't get reallocated elsewhere.
  2477. */
  2478. if (dup2(nullfd,0) < 0 ||
  2479. dup2(nullfd,1) < 0 ||
  2480. dup2(nullfd,2) < 0) {
  2481. log_err(LD_GENERAL,"dup2 failed. Exiting.");
  2482. exit(1);
  2483. }
  2484. if (nullfd > 2)
  2485. close(nullfd);
  2486. /* signal success */
  2487. if (write(daemon_filedes[1], &c, sizeof(char)) != sizeof(char)) {
  2488. log_err(LD_GENERAL,"write failed. Exiting.");
  2489. }
  2490. close(daemon_filedes[1]);
  2491. }
  2492. #else
  2493. /* defined(MS_WINDOWS) */
  2494. void
  2495. start_daemon(void)
  2496. {
  2497. }
  2498. void
  2499. finish_daemon(const char *cp)
  2500. {
  2501. (void)cp;
  2502. }
  2503. #endif
  2504. /** Write the current process ID, followed by NL, into <b>filename</b>.
  2505. */
  2506. void
  2507. write_pidfile(char *filename)
  2508. {
  2509. FILE *pidfile;
  2510. if ((pidfile = fopen(filename, "w")) == NULL) {
  2511. log_warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
  2512. strerror(errno));
  2513. } else {
  2514. #ifdef MS_WINDOWS
  2515. fprintf(pidfile, "%d\n", (int)_getpid());
  2516. #else
  2517. fprintf(pidfile, "%d\n", (int)getpid());
  2518. #endif
  2519. fclose(pidfile);
  2520. }
  2521. }