util.c 87 KB

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