util.c 90 KB

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