util.c 73 KB

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