util.c 96 KB

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