util.c 121 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397
  1. /* Copyright (c) 2003, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2011, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file util.c
  7. * \brief Common functions for strings, IO, network, data structures,
  8. * process control.
  9. **/
  10. /* This is required on rh7 to make strptime not complain.
  11. */
  12. #define _GNU_SOURCE
  13. #include "orconfig.h"
  14. #ifdef HAVE_FCNTL_H
  15. #include <fcntl.h>
  16. #endif
  17. #define UTIL_PRIVATE
  18. #include "util.h"
  19. #include "torlog.h"
  20. #undef log
  21. #include "crypto.h"
  22. #include "torint.h"
  23. #include "container.h"
  24. #include "address.h"
  25. #ifdef _WIN32
  26. #include <io.h>
  27. #include <direct.h>
  28. #include <process.h>
  29. #include <tchar.h>
  30. #include <Winbase.h>
  31. #else
  32. #include <dirent.h>
  33. #include <pwd.h>
  34. #include <grp.h>
  35. #endif
  36. /* math.h needs this on Linux */
  37. #ifndef __USE_ISOC99
  38. #define __USE_ISOC99 1
  39. #endif
  40. #include <math.h>
  41. #include <stdlib.h>
  42. #include <stdio.h>
  43. #include <string.h>
  44. #include <assert.h>
  45. #include <signal.h>
  46. #ifdef HAVE_NETINET_IN_H
  47. #include <netinet/in.h>
  48. #endif
  49. #ifdef HAVE_ARPA_INET_H
  50. #include <arpa/inet.h>
  51. #endif
  52. #ifdef HAVE_ERRNO_H
  53. #include <errno.h>
  54. #endif
  55. #ifdef HAVE_SYS_SOCKET_H
  56. #include <sys/socket.h>
  57. #endif
  58. #ifdef HAVE_SYS_TIME_H
  59. #include <sys/time.h>
  60. #endif
  61. #ifdef HAVE_UNISTD_H
  62. #include <unistd.h>
  63. #endif
  64. #ifdef HAVE_SYS_STAT_H
  65. #include <sys/stat.h>
  66. #endif
  67. #ifdef HAVE_SYS_FCNTL_H
  68. #include <sys/fcntl.h>
  69. #endif
  70. #ifdef HAVE_TIME_H
  71. #include <time.h>
  72. #endif
  73. #ifdef HAVE_MALLOC_MALLOC_H
  74. #include <malloc/malloc.h>
  75. #endif
  76. #ifdef HAVE_MALLOC_H
  77. #ifndef OPENBSD
  78. /* OpenBSD has a malloc.h, but for our purposes, it only exists in order to
  79. * scold us for being so stupid as to autodetect its presence. To be fair,
  80. * they've done this since 1996, when autoconf was only 5 years old. */
  81. #include <malloc.h>
  82. #endif
  83. #endif
  84. #ifdef HAVE_MALLOC_NP_H
  85. #include <malloc_np.h>
  86. #endif
  87. #ifdef HAVE_SYS_WAIT_H
  88. #include <sys/wait.h>
  89. #endif
  90. /* =====
  91. * Memory management
  92. * ===== */
  93. #ifdef USE_DMALLOC
  94. #undef strndup
  95. #include <dmalloc.h>
  96. /* Macro to pass the extra dmalloc args to another function. */
  97. #define DMALLOC_FN_ARGS , file, line
  98. #if defined(HAVE_DMALLOC_STRDUP)
  99. /* the dmalloc_strdup should be fine as defined */
  100. #elif defined(HAVE_DMALLOC_STRNDUP)
  101. #define dmalloc_strdup(file, line, string, xalloc_b) \
  102. dmalloc_strndup(file, line, (string), -1, xalloc_b)
  103. #else
  104. #error "No dmalloc_strdup or equivalent"
  105. #endif
  106. #else /* not using dmalloc */
  107. #define DMALLOC_FN_ARGS
  108. #endif
  109. /** Allocate a chunk of <b>size</b> bytes of memory, and return a pointer to
  110. * result. On error, log and terminate the process. (Same as malloc(size),
  111. * but never returns NULL.)
  112. *
  113. * <b>file</b> and <b>line</b> are used if dmalloc is enabled, and
  114. * ignored otherwise.
  115. */
  116. void *
  117. _tor_malloc(size_t size DMALLOC_PARAMS)
  118. {
  119. void *result;
  120. tor_assert(size < SIZE_T_CEILING);
  121. #ifndef MALLOC_ZERO_WORKS
  122. /* Some libc mallocs don't work when size==0. Override them. */
  123. if (size==0) {
  124. size=1;
  125. }
  126. #endif
  127. #ifdef USE_DMALLOC
  128. result = dmalloc_malloc(file, line, size, DMALLOC_FUNC_MALLOC, 0, 0);
  129. #else
  130. result = malloc(size);
  131. #endif
  132. if (PREDICT_UNLIKELY(result == NULL)) {
  133. log_err(LD_MM,"Out of memory on malloc(). Dying.");
  134. /* If these functions die within a worker process, they won't call
  135. * spawn_exit, but that's ok, since the parent will run out of memory soon
  136. * anyway. */
  137. exit(1);
  138. }
  139. return result;
  140. }
  141. /** Allocate a chunk of <b>size</b> bytes of memory, fill the memory with
  142. * zero bytes, and return a pointer to the result. Log and terminate
  143. * the process on error. (Same as calloc(size,1), but never returns NULL.)
  144. */
  145. void *
  146. _tor_malloc_zero(size_t size DMALLOC_PARAMS)
  147. {
  148. /* You may ask yourself, "wouldn't it be smart to use calloc instead of
  149. * malloc+memset? Perhaps libc's calloc knows some nifty optimization trick
  150. * we don't!" Indeed it does, but its optimizations are only a big win when
  151. * we're allocating something very big (it knows if it just got the memory
  152. * from the OS in a pre-zeroed state). We don't want to use tor_malloc_zero
  153. * for big stuff, so we don't bother with calloc. */
  154. void *result = _tor_malloc(size DMALLOC_FN_ARGS);
  155. memset(result, 0, size);
  156. return result;
  157. }
  158. /** Allocate a chunk of <b>nmemb</b>*<b>size</b> bytes of memory, fill
  159. * the memory with zero bytes, and return a pointer to the result.
  160. * Log and terminate the process on error. (Same as
  161. * calloc(<b>nmemb</b>,<b>size</b>), but never returns NULL.)
  162. *
  163. * XXXX This implementation probably asserts in cases where it could
  164. * work, because it only tries dividing SIZE_MAX by size (according to
  165. * the calloc(3) man page, the size of an element of the nmemb-element
  166. * array to be allocated), not by nmemb (which could in theory be
  167. * smaller than size). Don't do that then.
  168. */
  169. void *
  170. _tor_calloc(size_t nmemb, size_t size DMALLOC_PARAMS)
  171. {
  172. /* You may ask yourself, "wouldn't it be smart to use calloc instead of
  173. * malloc+memset? Perhaps libc's calloc knows some nifty optimization trick
  174. * we don't!" Indeed it does, but its optimizations are only a big win when
  175. * we're allocating something very big (it knows if it just got the memory
  176. * from the OS in a pre-zeroed state). We don't want to use tor_malloc_zero
  177. * for big stuff, so we don't bother with calloc. */
  178. void *result;
  179. size_t max_nmemb = (size == 0) ? SIZE_MAX : SIZE_MAX/size;
  180. tor_assert(nmemb < max_nmemb);
  181. result = _tor_malloc_zero((nmemb * size) DMALLOC_FN_ARGS);
  182. return result;
  183. }
  184. /** Change the size of the memory block pointed to by <b>ptr</b> to <b>size</b>
  185. * bytes long; return the new memory block. On error, log and
  186. * terminate. (Like realloc(ptr,size), but never returns NULL.)
  187. */
  188. void *
  189. _tor_realloc(void *ptr, size_t size DMALLOC_PARAMS)
  190. {
  191. void *result;
  192. tor_assert(size < SIZE_T_CEILING);
  193. #ifdef USE_DMALLOC
  194. result = dmalloc_realloc(file, line, ptr, size, DMALLOC_FUNC_REALLOC, 0);
  195. #else
  196. result = realloc(ptr, size);
  197. #endif
  198. if (PREDICT_UNLIKELY(result == NULL)) {
  199. log_err(LD_MM,"Out of memory on realloc(). Dying.");
  200. exit(1);
  201. }
  202. return result;
  203. }
  204. /** Return a newly allocated copy of the NUL-terminated string s. On
  205. * error, log and terminate. (Like strdup(s), but never returns
  206. * NULL.)
  207. */
  208. char *
  209. _tor_strdup(const char *s DMALLOC_PARAMS)
  210. {
  211. char *dup;
  212. tor_assert(s);
  213. #ifdef USE_DMALLOC
  214. dup = dmalloc_strdup(file, line, s, 0);
  215. #else
  216. dup = strdup(s);
  217. #endif
  218. if (PREDICT_UNLIKELY(dup == NULL)) {
  219. log_err(LD_MM,"Out of memory on strdup(). Dying.");
  220. exit(1);
  221. }
  222. return dup;
  223. }
  224. /** Allocate and return a new string containing the first <b>n</b>
  225. * characters of <b>s</b>. If <b>s</b> is longer than <b>n</b>
  226. * characters, only the first <b>n</b> are copied. The result is
  227. * always NUL-terminated. (Like strndup(s,n), but never returns
  228. * NULL.)
  229. */
  230. char *
  231. _tor_strndup(const char *s, size_t n DMALLOC_PARAMS)
  232. {
  233. char *dup;
  234. tor_assert(s);
  235. tor_assert(n < SIZE_T_CEILING);
  236. dup = _tor_malloc((n+1) DMALLOC_FN_ARGS);
  237. /* Performance note: Ordinarily we prefer strlcpy to strncpy. But
  238. * this function gets called a whole lot, and platform strncpy is
  239. * much faster than strlcpy when strlen(s) is much longer than n.
  240. */
  241. strncpy(dup, s, n);
  242. dup[n]='\0';
  243. return dup;
  244. }
  245. /** Allocate a chunk of <b>len</b> bytes, with the same contents as the
  246. * <b>len</b> bytes starting at <b>mem</b>. */
  247. void *
  248. _tor_memdup(const void *mem, size_t len DMALLOC_PARAMS)
  249. {
  250. char *dup;
  251. tor_assert(len < SIZE_T_CEILING);
  252. tor_assert(mem);
  253. dup = _tor_malloc(len DMALLOC_FN_ARGS);
  254. memcpy(dup, mem, len);
  255. return dup;
  256. }
  257. /** Helper for places that need to take a function pointer to the right
  258. * spelling of "free()". */
  259. void
  260. _tor_free(void *mem)
  261. {
  262. tor_free(mem);
  263. }
  264. #if defined(HAVE_MALLOC_GOOD_SIZE) && !defined(HAVE_MALLOC_GOOD_SIZE_PROTOTYPE)
  265. /* Some version of Mac OSX have malloc_good_size in their libc, but not
  266. * actually defined in malloc/malloc.h. We detect this and work around it by
  267. * prototyping.
  268. */
  269. extern size_t malloc_good_size(size_t size);
  270. #endif
  271. /** Allocate and return a chunk of memory of size at least *<b>size</b>, using
  272. * the same resources we would use to malloc *<b>sizep</b>. Set *<b>sizep</b>
  273. * to the number of usable bytes in the chunk of memory. */
  274. void *
  275. _tor_malloc_roundup(size_t *sizep DMALLOC_PARAMS)
  276. {
  277. #ifdef HAVE_MALLOC_GOOD_SIZE
  278. tor_assert(*sizep < SIZE_T_CEILING);
  279. *sizep = malloc_good_size(*sizep);
  280. return _tor_malloc(*sizep DMALLOC_FN_ARGS);
  281. #elif 0 && defined(HAVE_MALLOC_USABLE_SIZE) && !defined(USE_DMALLOC)
  282. /* Never use malloc_usable_size(); it makes valgrind really unhappy,
  283. * and doesn't win much in terms of usable space where it exists. */
  284. void *result;
  285. tor_assert(*sizep < SIZE_T_CEILING);
  286. result = _tor_malloc(*sizep DMALLOC_FN_ARGS);
  287. *sizep = malloc_usable_size(result);
  288. return result;
  289. #else
  290. return _tor_malloc(*sizep DMALLOC_FN_ARGS);
  291. #endif
  292. }
  293. /** Call the platform malloc info function, and dump the results to the log at
  294. * level <b>severity</b>. If no such function exists, do nothing. */
  295. void
  296. tor_log_mallinfo(int severity)
  297. {
  298. #ifdef HAVE_MALLINFO
  299. struct mallinfo mi;
  300. memset(&mi, 0, sizeof(mi));
  301. mi = mallinfo();
  302. tor_log(severity, LD_MM,
  303. "mallinfo() said: arena=%d, ordblks=%d, smblks=%d, hblks=%d, "
  304. "hblkhd=%d, usmblks=%d, fsmblks=%d, uordblks=%d, fordblks=%d, "
  305. "keepcost=%d",
  306. mi.arena, mi.ordblks, mi.smblks, mi.hblks,
  307. mi.hblkhd, mi.usmblks, mi.fsmblks, mi.uordblks, mi.fordblks,
  308. mi.keepcost);
  309. #else
  310. (void)severity;
  311. #endif
  312. #ifdef USE_DMALLOC
  313. dmalloc_log_changed(0, /* Since the program started. */
  314. 1, /* Log info about non-freed pointers. */
  315. 0, /* Do not log info about freed pointers. */
  316. 0 /* Do not log individual pointers. */
  317. );
  318. #endif
  319. }
  320. /* =====
  321. * Math
  322. * ===== */
  323. /**
  324. * Returns the natural logarithm of d base 2. We define this wrapper here so
  325. * as to make it easier not to conflict with Tor's log() macro.
  326. */
  327. double
  328. tor_mathlog(double d)
  329. {
  330. return log(d);
  331. }
  332. /** Return the long integer closest to d. We define this wrapper here so
  333. * that not all users of math.h need to use the right incancations to get
  334. * the c99 functions. */
  335. long
  336. tor_lround(double d)
  337. {
  338. #if defined(HAVE_LROUND)
  339. return lround(d);
  340. #elif defined(HAVE_RINT)
  341. return (long)rint(d);
  342. #else
  343. return (long)(d > 0 ? d + 0.5 : ceil(d - 0.5));
  344. #endif
  345. }
  346. /** Returns floor(log2(u64)). If u64 is 0, (incorrectly) returns 0. */
  347. int
  348. tor_log2(uint64_t u64)
  349. {
  350. int r = 0;
  351. if (u64 >= (U64_LITERAL(1)<<32)) {
  352. u64 >>= 32;
  353. r = 32;
  354. }
  355. if (u64 >= (U64_LITERAL(1)<<16)) {
  356. u64 >>= 16;
  357. r += 16;
  358. }
  359. if (u64 >= (U64_LITERAL(1)<<8)) {
  360. u64 >>= 8;
  361. r += 8;
  362. }
  363. if (u64 >= (U64_LITERAL(1)<<4)) {
  364. u64 >>= 4;
  365. r += 4;
  366. }
  367. if (u64 >= (U64_LITERAL(1)<<2)) {
  368. u64 >>= 2;
  369. r += 2;
  370. }
  371. if (u64 >= (U64_LITERAL(1)<<1)) {
  372. u64 >>= 1;
  373. r += 1;
  374. }
  375. return r;
  376. }
  377. /** Return the power of 2 closest to <b>u64</b>. */
  378. uint64_t
  379. round_to_power_of_2(uint64_t u64)
  380. {
  381. int lg2 = tor_log2(u64);
  382. uint64_t low = U64_LITERAL(1) << lg2, high = U64_LITERAL(1) << (lg2+1);
  383. if (high - u64 < u64 - low)
  384. return high;
  385. else
  386. return low;
  387. }
  388. /** Return the lowest x such that x is at least <b>number</b>, and x modulo
  389. * <b>divisor</b> == 0. */
  390. unsigned
  391. round_to_next_multiple_of(unsigned number, unsigned divisor)
  392. {
  393. number += divisor - 1;
  394. number -= number % divisor;
  395. return number;
  396. }
  397. /** Return the lowest x such that x is at least <b>number</b>, and x modulo
  398. * <b>divisor</b> == 0. */
  399. uint32_t
  400. round_uint32_to_next_multiple_of(uint32_t number, uint32_t divisor)
  401. {
  402. number += divisor - 1;
  403. number -= number % divisor;
  404. return number;
  405. }
  406. /** Return the lowest x such that x is at least <b>number</b>, and x modulo
  407. * <b>divisor</b> == 0. */
  408. uint64_t
  409. round_uint64_to_next_multiple_of(uint64_t number, uint64_t divisor)
  410. {
  411. number += divisor - 1;
  412. number -= number % divisor;
  413. return number;
  414. }
  415. /** Return the number of bits set in <b>v</b>. */
  416. int
  417. n_bits_set_u8(uint8_t v)
  418. {
  419. static const int nybble_table[] = {
  420. 0, /* 0000 */
  421. 1, /* 0001 */
  422. 1, /* 0010 */
  423. 2, /* 0011 */
  424. 1, /* 0100 */
  425. 2, /* 0101 */
  426. 2, /* 0110 */
  427. 3, /* 0111 */
  428. 1, /* 1000 */
  429. 2, /* 1001 */
  430. 2, /* 1010 */
  431. 3, /* 1011 */
  432. 2, /* 1100 */
  433. 3, /* 1101 */
  434. 3, /* 1110 */
  435. 4, /* 1111 */
  436. };
  437. return nybble_table[v & 15] + nybble_table[v>>4];
  438. }
  439. /* =====
  440. * String manipulation
  441. * ===== */
  442. /** Remove from the string <b>s</b> every character which appears in
  443. * <b>strip</b>. */
  444. void
  445. tor_strstrip(char *s, const char *strip)
  446. {
  447. char *read = s;
  448. while (*read) {
  449. if (strchr(strip, *read)) {
  450. ++read;
  451. } else {
  452. *s++ = *read++;
  453. }
  454. }
  455. *s = '\0';
  456. }
  457. /** Return a pointer to a NUL-terminated hexadecimal string encoding
  458. * the first <b>fromlen</b> bytes of <b>from</b>. (fromlen must be \<= 32.) The
  459. * result does not need to be deallocated, but repeated calls to
  460. * hex_str will trash old results.
  461. */
  462. const char *
  463. hex_str(const char *from, size_t fromlen)
  464. {
  465. static char buf[65];
  466. if (fromlen>(sizeof(buf)-1)/2)
  467. fromlen = (sizeof(buf)-1)/2;
  468. base16_encode(buf,sizeof(buf),from,fromlen);
  469. return buf;
  470. }
  471. /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
  472. * lowercase. */
  473. void
  474. tor_strlower(char *s)
  475. {
  476. while (*s) {
  477. *s = TOR_TOLOWER(*s);
  478. ++s;
  479. }
  480. }
  481. /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
  482. * lowercase. */
  483. void
  484. tor_strupper(char *s)
  485. {
  486. while (*s) {
  487. *s = TOR_TOUPPER(*s);
  488. ++s;
  489. }
  490. }
  491. /** Return 1 if every character in <b>s</b> is printable, else return 0.
  492. */
  493. int
  494. tor_strisprint(const char *s)
  495. {
  496. while (*s) {
  497. if (!TOR_ISPRINT(*s))
  498. return 0;
  499. s++;
  500. }
  501. return 1;
  502. }
  503. /** Return 1 if no character in <b>s</b> is uppercase, else return 0.
  504. */
  505. int
  506. tor_strisnonupper(const char *s)
  507. {
  508. while (*s) {
  509. if (TOR_ISUPPER(*s))
  510. return 0;
  511. s++;
  512. }
  513. return 1;
  514. }
  515. /** As strcmp, except that either string may be NULL. The NULL string is
  516. * considered to be before any non-NULL string. */
  517. int
  518. strcmp_opt(const char *s1, const char *s2)
  519. {
  520. if (!s1) {
  521. if (!s2)
  522. return 0;
  523. else
  524. return -1;
  525. } else if (!s2) {
  526. return 1;
  527. } else {
  528. return strcmp(s1, s2);
  529. }
  530. }
  531. /** Compares the first strlen(s2) characters of s1 with s2. Returns as for
  532. * strcmp.
  533. */
  534. int
  535. strcmpstart(const char *s1, const char *s2)
  536. {
  537. size_t n = strlen(s2);
  538. return strncmp(s1, s2, n);
  539. }
  540. /** Compare the s1_len-byte string <b>s1</b> with <b>s2</b>,
  541. * without depending on a terminating nul in s1. Sorting order is first by
  542. * length, then lexically; return values are as for strcmp.
  543. */
  544. int
  545. strcmp_len(const char *s1, const char *s2, size_t s1_len)
  546. {
  547. size_t s2_len = strlen(s2);
  548. if (s1_len < s2_len)
  549. return -1;
  550. if (s1_len > s2_len)
  551. return 1;
  552. return fast_memcmp(s1, s2, s2_len);
  553. }
  554. /** Compares the first strlen(s2) characters of s1 with s2. Returns as for
  555. * strcasecmp.
  556. */
  557. int
  558. strcasecmpstart(const char *s1, const char *s2)
  559. {
  560. size_t n = strlen(s2);
  561. return strncasecmp(s1, s2, n);
  562. }
  563. /** Compares the last strlen(s2) characters of s1 with s2. Returns as for
  564. * strcmp.
  565. */
  566. int
  567. strcmpend(const char *s1, const char *s2)
  568. {
  569. size_t n1 = strlen(s1), n2 = strlen(s2);
  570. if (n2>n1)
  571. return strcmp(s1,s2);
  572. else
  573. return strncmp(s1+(n1-n2), s2, n2);
  574. }
  575. /** Compares the last strlen(s2) characters of s1 with s2. Returns as for
  576. * strcasecmp.
  577. */
  578. int
  579. strcasecmpend(const char *s1, const char *s2)
  580. {
  581. size_t n1 = strlen(s1), n2 = strlen(s2);
  582. if (n2>n1) /* then they can't be the same; figure out which is bigger */
  583. return strcasecmp(s1,s2);
  584. else
  585. return strncasecmp(s1+(n1-n2), s2, n2);
  586. }
  587. /** Compare the value of the string <b>prefix</b> with the start of the
  588. * <b>memlen</b>-byte memory chunk at <b>mem</b>. Return as for strcmp.
  589. *
  590. * [As fast_memcmp(mem, prefix, strlen(prefix)) but returns -1 if memlen is
  591. * less than strlen(prefix).]
  592. */
  593. int
  594. fast_memcmpstart(const void *mem, size_t memlen,
  595. const char *prefix)
  596. {
  597. size_t plen = strlen(prefix);
  598. if (memlen < plen)
  599. return -1;
  600. return fast_memcmp(mem, prefix, plen);
  601. }
  602. /** Return a pointer to the first char of s that is not whitespace and
  603. * not a comment, or to the terminating NUL if no such character exists.
  604. */
  605. const char *
  606. eat_whitespace(const char *s)
  607. {
  608. tor_assert(s);
  609. while (1) {
  610. switch (*s) {
  611. case '\0':
  612. default:
  613. return s;
  614. case ' ':
  615. case '\t':
  616. case '\n':
  617. case '\r':
  618. ++s;
  619. break;
  620. case '#':
  621. ++s;
  622. while (*s && *s != '\n')
  623. ++s;
  624. }
  625. }
  626. }
  627. /** Return a pointer to the first char of s that is not whitespace and
  628. * not a comment, or to the terminating NUL if no such character exists.
  629. */
  630. const char *
  631. eat_whitespace_eos(const char *s, const char *eos)
  632. {
  633. tor_assert(s);
  634. tor_assert(eos && s <= eos);
  635. while (s < eos) {
  636. switch (*s) {
  637. case '\0':
  638. default:
  639. return s;
  640. case ' ':
  641. case '\t':
  642. case '\n':
  643. case '\r':
  644. ++s;
  645. break;
  646. case '#':
  647. ++s;
  648. while (s < eos && *s && *s != '\n')
  649. ++s;
  650. }
  651. }
  652. return s;
  653. }
  654. /** Return a pointer to the first char of s that is not a space or a tab
  655. * or a \\r, or to the terminating NUL if no such character exists. */
  656. const char *
  657. eat_whitespace_no_nl(const char *s)
  658. {
  659. while (*s == ' ' || *s == '\t' || *s == '\r')
  660. ++s;
  661. return s;
  662. }
  663. /** As eat_whitespace_no_nl, but stop at <b>eos</b> whether we have
  664. * found a non-whitespace character or not. */
  665. const char *
  666. eat_whitespace_eos_no_nl(const char *s, const char *eos)
  667. {
  668. while (s < eos && (*s == ' ' || *s == '\t' || *s == '\r'))
  669. ++s;
  670. return s;
  671. }
  672. /** Return a pointer to the first char of s that is whitespace or <b>#</b>,
  673. * or to the terminating NUL if no such character exists.
  674. */
  675. const char *
  676. find_whitespace(const char *s)
  677. {
  678. /* tor_assert(s); */
  679. while (1) {
  680. switch (*s)
  681. {
  682. case '\0':
  683. case '#':
  684. case ' ':
  685. case '\r':
  686. case '\n':
  687. case '\t':
  688. return s;
  689. default:
  690. ++s;
  691. }
  692. }
  693. }
  694. /** As find_whitespace, but stop at <b>eos</b> whether we have found a
  695. * whitespace or not. */
  696. const char *
  697. find_whitespace_eos(const char *s, const char *eos)
  698. {
  699. /* tor_assert(s); */
  700. while (s < eos) {
  701. switch (*s)
  702. {
  703. case '\0':
  704. case '#':
  705. case ' ':
  706. case '\r':
  707. case '\n':
  708. case '\t':
  709. return s;
  710. default:
  711. ++s;
  712. }
  713. }
  714. return s;
  715. }
  716. /** Return the first occurrence of <b>needle</b> in <b>haystack</b> that
  717. * occurs at the start of a line (that is, at the beginning of <b>haystack</b>
  718. * or immediately after a newline). Return NULL if no such string is found.
  719. */
  720. const char *
  721. find_str_at_start_of_line(const char *haystack, const char *needle)
  722. {
  723. size_t needle_len = strlen(needle);
  724. do {
  725. if (!strncmp(haystack, needle, needle_len))
  726. return haystack;
  727. haystack = strchr(haystack, '\n');
  728. if (!haystack)
  729. return NULL;
  730. else
  731. ++haystack;
  732. } while (*haystack);
  733. return NULL;
  734. }
  735. /** Returns true if <b>string</b> could be a C identifier.
  736. A C identifier must begin with a letter or an underscore and the
  737. rest of its characters can be letters, numbers or underscores. No
  738. length limit is imposed. */
  739. int
  740. string_is_C_identifier(const char *string)
  741. {
  742. size_t iter;
  743. size_t length = strlen(string);
  744. if (!length)
  745. return 0;
  746. for (iter = 0; iter < length ; iter++) {
  747. if (iter == 0) {
  748. if (!(TOR_ISALPHA(string[iter]) ||
  749. string[iter] == '_'))
  750. return 0;
  751. } else {
  752. if (!(TOR_ISALPHA(string[iter]) ||
  753. TOR_ISDIGIT(string[iter]) ||
  754. string[iter] == '_'))
  755. return 0;
  756. }
  757. }
  758. return 1;
  759. }
  760. /** Return true iff the 'len' bytes at 'mem' are all zero. */
  761. int
  762. tor_mem_is_zero(const char *mem, size_t len)
  763. {
  764. static const char ZERO[] = {
  765. 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,
  766. };
  767. while (len >= sizeof(ZERO)) {
  768. /* It's safe to use fast_memcmp here, since the very worst thing an
  769. * attacker could learn is how many initial bytes of a secret were zero */
  770. if (fast_memcmp(mem, ZERO, sizeof(ZERO)))
  771. return 0;
  772. len -= sizeof(ZERO);
  773. mem += sizeof(ZERO);
  774. }
  775. /* Deal with leftover bytes. */
  776. if (len)
  777. return fast_memeq(mem, ZERO, len);
  778. return 1;
  779. }
  780. /** Return true iff the DIGEST_LEN bytes in digest are all zero. */
  781. int
  782. tor_digest_is_zero(const char *digest)
  783. {
  784. static const uint8_t ZERO_DIGEST[] = {
  785. 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0
  786. };
  787. return tor_memeq(digest, ZERO_DIGEST, DIGEST_LEN);
  788. }
  789. /** Return true iff the DIGEST256_LEN bytes in digest are all zero. */
  790. int
  791. tor_digest256_is_zero(const char *digest)
  792. {
  793. return tor_mem_is_zero(digest, DIGEST256_LEN);
  794. }
  795. /* Helper: common code to check whether the result of a strtol or strtoul or
  796. * strtoll is correct. */
  797. #define CHECK_STRTOX_RESULT() \
  798. /* Was at least one character converted? */ \
  799. if (endptr == s) \
  800. goto err; \
  801. /* Were there unexpected unconverted characters? */ \
  802. if (!next && *endptr) \
  803. goto err; \
  804. /* Is r within limits? */ \
  805. if (r < min || r > max) \
  806. goto err; \
  807. if (ok) *ok = 1; \
  808. if (next) *next = endptr; \
  809. return r; \
  810. err: \
  811. if (ok) *ok = 0; \
  812. if (next) *next = endptr; \
  813. return 0
  814. /** Extract a long from the start of <b>s</b>, in the given numeric
  815. * <b>base</b>. If <b>base</b> is 0, <b>s</b> is parsed as a decimal,
  816. * octal, or hex number in the syntax of a C integer literal. If
  817. * there is unconverted data and <b>next</b> is provided, set
  818. * *<b>next</b> to the first unconverted character. An error has
  819. * occurred if no characters are converted; or if there are
  820. * unconverted characters and <b>next</b> is NULL; or if the parsed
  821. * value is not between <b>min</b> and <b>max</b>. When no error
  822. * occurs, return the parsed value and set *<b>ok</b> (if provided) to
  823. * 1. When an error occurs, return 0 and set *<b>ok</b> (if provided)
  824. * to 0.
  825. */
  826. long
  827. tor_parse_long(const char *s, int base, long min, long max,
  828. int *ok, char **next)
  829. {
  830. char *endptr;
  831. long r;
  832. if (base < 0) {
  833. if (ok)
  834. *ok = 0;
  835. return 0;
  836. }
  837. r = strtol(s, &endptr, base);
  838. CHECK_STRTOX_RESULT();
  839. }
  840. /** As tor_parse_long(), but return an unsigned long. */
  841. unsigned long
  842. tor_parse_ulong(const char *s, int base, unsigned long min,
  843. unsigned long max, int *ok, char **next)
  844. {
  845. char *endptr;
  846. unsigned long r;
  847. if (base < 0) {
  848. if (ok)
  849. *ok = 0;
  850. return 0;
  851. }
  852. r = strtoul(s, &endptr, base);
  853. CHECK_STRTOX_RESULT();
  854. }
  855. /** As tor_parse_long(), but return a double. */
  856. double
  857. tor_parse_double(const char *s, double min, double max, int *ok, char **next)
  858. {
  859. char *endptr;
  860. double r;
  861. r = strtod(s, &endptr);
  862. CHECK_STRTOX_RESULT();
  863. }
  864. /** As tor_parse_long, but return a uint64_t. Only base 10 is guaranteed to
  865. * work for now. */
  866. uint64_t
  867. tor_parse_uint64(const char *s, int base, uint64_t min,
  868. uint64_t max, int *ok, char **next)
  869. {
  870. char *endptr;
  871. uint64_t r;
  872. if (base < 0) {
  873. if (ok)
  874. *ok = 0;
  875. return 0;
  876. }
  877. #ifdef HAVE_STRTOULL
  878. r = (uint64_t)strtoull(s, &endptr, base);
  879. #elif defined(_WIN32)
  880. #if defined(_MSC_VER) && _MSC_VER < 1300
  881. tor_assert(base <= 10);
  882. r = (uint64_t)_atoi64(s);
  883. endptr = (char*)s;
  884. while (TOR_ISSPACE(*endptr)) endptr++;
  885. while (TOR_ISDIGIT(*endptr)) endptr++;
  886. #else
  887. r = (uint64_t)_strtoui64(s, &endptr, base);
  888. #endif
  889. #elif SIZEOF_LONG == 8
  890. r = (uint64_t)strtoul(s, &endptr, base);
  891. #else
  892. #error "I don't know how to parse 64-bit numbers."
  893. #endif
  894. CHECK_STRTOX_RESULT();
  895. }
  896. /** Encode the <b>srclen</b> bytes at <b>src</b> in a NUL-terminated,
  897. * uppercase hexadecimal string; store it in the <b>destlen</b>-byte buffer
  898. * <b>dest</b>.
  899. */
  900. void
  901. base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  902. {
  903. const char *end;
  904. char *cp;
  905. tor_assert(destlen >= srclen*2+1);
  906. tor_assert(destlen < SIZE_T_CEILING);
  907. cp = dest;
  908. end = src+srclen;
  909. while (src<end) {
  910. *cp++ = "0123456789ABCDEF"[ (*(const uint8_t*)src) >> 4 ];
  911. *cp++ = "0123456789ABCDEF"[ (*(const uint8_t*)src) & 0xf ];
  912. ++src;
  913. }
  914. *cp = '\0';
  915. }
  916. /** Helper: given a hex digit, return its value, or -1 if it isn't hex. */
  917. static INLINE int
  918. _hex_decode_digit(char c)
  919. {
  920. switch (c) {
  921. case '0': return 0;
  922. case '1': return 1;
  923. case '2': return 2;
  924. case '3': return 3;
  925. case '4': return 4;
  926. case '5': return 5;
  927. case '6': return 6;
  928. case '7': return 7;
  929. case '8': return 8;
  930. case '9': return 9;
  931. case 'A': case 'a': return 10;
  932. case 'B': case 'b': return 11;
  933. case 'C': case 'c': return 12;
  934. case 'D': case 'd': return 13;
  935. case 'E': case 'e': return 14;
  936. case 'F': case 'f': return 15;
  937. default:
  938. return -1;
  939. }
  940. }
  941. /** Helper: given a hex digit, return its value, or -1 if it isn't hex. */
  942. int
  943. hex_decode_digit(char c)
  944. {
  945. return _hex_decode_digit(c);
  946. }
  947. /** Given a hexadecimal string of <b>srclen</b> bytes in <b>src</b>, decode it
  948. * and store the result in the <b>destlen</b>-byte buffer at <b>dest</b>.
  949. * Return 0 on success, -1 on failure. */
  950. int
  951. base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  952. {
  953. const char *end;
  954. int v1,v2;
  955. if ((srclen % 2) != 0)
  956. return -1;
  957. if (destlen < srclen/2 || destlen > SIZE_T_CEILING)
  958. return -1;
  959. end = src+srclen;
  960. while (src<end) {
  961. v1 = _hex_decode_digit(*src);
  962. v2 = _hex_decode_digit(*(src+1));
  963. if (v1<0||v2<0)
  964. return -1;
  965. *(uint8_t*)dest = (v1<<4)|v2;
  966. ++dest;
  967. src+=2;
  968. }
  969. return 0;
  970. }
  971. /** Allocate and return a new string representing the contents of <b>s</b>,
  972. * surrounded by quotes and using standard C escapes.
  973. *
  974. * Generally, we use this for logging values that come in over the network to
  975. * keep them from tricking users, and for sending certain values to the
  976. * controller.
  977. *
  978. * We trust values from the resolver, OS, configuration file, and command line
  979. * to not be maliciously ill-formed. We validate incoming routerdescs and
  980. * SOCKS requests and addresses from BEGIN cells as they're parsed;
  981. * afterwards, we trust them as non-malicious.
  982. */
  983. char *
  984. esc_for_log(const char *s)
  985. {
  986. const char *cp;
  987. char *result, *outp;
  988. size_t len = 3;
  989. if (!s) {
  990. return tor_strdup("(null)");
  991. }
  992. for (cp = s; *cp; ++cp) {
  993. switch (*cp) {
  994. case '\\':
  995. case '\"':
  996. case '\'':
  997. case '\r':
  998. case '\n':
  999. case '\t':
  1000. len += 2;
  1001. break;
  1002. default:
  1003. if (TOR_ISPRINT(*cp) && ((uint8_t)*cp)<127)
  1004. ++len;
  1005. else
  1006. len += 4;
  1007. break;
  1008. }
  1009. }
  1010. result = outp = tor_malloc(len);
  1011. *outp++ = '\"';
  1012. for (cp = s; *cp; ++cp) {
  1013. switch (*cp) {
  1014. case '\\':
  1015. case '\"':
  1016. case '\'':
  1017. *outp++ = '\\';
  1018. *outp++ = *cp;
  1019. break;
  1020. case '\n':
  1021. *outp++ = '\\';
  1022. *outp++ = 'n';
  1023. break;
  1024. case '\t':
  1025. *outp++ = '\\';
  1026. *outp++ = 't';
  1027. break;
  1028. case '\r':
  1029. *outp++ = '\\';
  1030. *outp++ = 'r';
  1031. break;
  1032. default:
  1033. if (TOR_ISPRINT(*cp) && ((uint8_t)*cp)<127) {
  1034. *outp++ = *cp;
  1035. } else {
  1036. tor_snprintf(outp, 5, "\\%03o", (int)(uint8_t) *cp);
  1037. outp += 4;
  1038. }
  1039. break;
  1040. }
  1041. }
  1042. *outp++ = '\"';
  1043. *outp++ = 0;
  1044. return result;
  1045. }
  1046. /** Allocate and return a new string representing the contents of <b>s</b>,
  1047. * surrounded by quotes and using standard C escapes.
  1048. *
  1049. * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
  1050. * thread. Also, each call invalidates the last-returned value, so don't
  1051. * try log_warn(LD_GENERAL, "%s %s", escaped(a), escaped(b));
  1052. */
  1053. const char *
  1054. escaped(const char *s)
  1055. {
  1056. static char *_escaped_val = NULL;
  1057. tor_free(_escaped_val);
  1058. if (s)
  1059. _escaped_val = esc_for_log(s);
  1060. else
  1061. _escaped_val = NULL;
  1062. return _escaped_val;
  1063. }
  1064. /** Rudimentary string wrapping code: given a un-wrapped <b>string</b> (no
  1065. * newlines!), break the string into newline-terminated lines of no more than
  1066. * <b>width</b> characters long (not counting newline) and insert them into
  1067. * <b>out</b> in order. Precede the first line with prefix0, and subsequent
  1068. * lines with prefixRest.
  1069. */
  1070. /* This uses a stupid greedy wrapping algorithm right now:
  1071. * - For each line:
  1072. * - Try to fit as much stuff as possible, but break on a space.
  1073. * - If the first "word" of the line will extend beyond the allowable
  1074. * width, break the word at the end of the width.
  1075. */
  1076. void
  1077. wrap_string(smartlist_t *out, const char *string, size_t width,
  1078. const char *prefix0, const char *prefixRest)
  1079. {
  1080. size_t p0Len, pRestLen, pCurLen;
  1081. const char *eos, *prefixCur;
  1082. tor_assert(out);
  1083. tor_assert(string);
  1084. tor_assert(width);
  1085. if (!prefix0)
  1086. prefix0 = "";
  1087. if (!prefixRest)
  1088. prefixRest = "";
  1089. p0Len = strlen(prefix0);
  1090. pRestLen = strlen(prefixRest);
  1091. tor_assert(width > p0Len && width > pRestLen);
  1092. eos = strchr(string, '\0');
  1093. tor_assert(eos);
  1094. pCurLen = p0Len;
  1095. prefixCur = prefix0;
  1096. while ((eos-string)+pCurLen > width) {
  1097. const char *eol = string + width - pCurLen;
  1098. while (eol > string && *eol != ' ')
  1099. --eol;
  1100. /* eol is now the last space that can fit, or the start of the string. */
  1101. if (eol > string) {
  1102. size_t line_len = (eol-string) + pCurLen + 2;
  1103. char *line = tor_malloc(line_len);
  1104. memcpy(line, prefixCur, pCurLen);
  1105. memcpy(line+pCurLen, string, eol-string);
  1106. line[line_len-2] = '\n';
  1107. line[line_len-1] = '\0';
  1108. smartlist_add(out, line);
  1109. string = eol + 1;
  1110. } else {
  1111. size_t line_len = width + 2;
  1112. char *line = tor_malloc(line_len);
  1113. memcpy(line, prefixCur, pCurLen);
  1114. memcpy(line+pCurLen, string, width - pCurLen);
  1115. line[line_len-2] = '\n';
  1116. line[line_len-1] = '\0';
  1117. smartlist_add(out, line);
  1118. string += width-pCurLen;
  1119. }
  1120. prefixCur = prefixRest;
  1121. pCurLen = pRestLen;
  1122. }
  1123. if (string < eos) {
  1124. size_t line_len = (eos-string) + pCurLen + 2;
  1125. char *line = tor_malloc(line_len);
  1126. memcpy(line, prefixCur, pCurLen);
  1127. memcpy(line+pCurLen, string, eos-string);
  1128. line[line_len-2] = '\n';
  1129. line[line_len-1] = '\0';
  1130. smartlist_add(out, line);
  1131. }
  1132. }
  1133. /* =====
  1134. * Time
  1135. * ===== */
  1136. /**
  1137. * Converts struct timeval to a double value.
  1138. * Preserves microsecond precision, but just barely.
  1139. * Error is approx +/- 0.1 usec when dealing with epoch values.
  1140. */
  1141. double
  1142. tv_to_double(const struct timeval *tv)
  1143. {
  1144. double conv = tv->tv_sec;
  1145. conv += tv->tv_usec/1000000.0;
  1146. return conv;
  1147. }
  1148. /**
  1149. * Converts timeval to milliseconds.
  1150. */
  1151. int64_t
  1152. tv_to_msec(const struct timeval *tv)
  1153. {
  1154. int64_t conv = ((int64_t)tv->tv_sec)*1000L;
  1155. /* Round ghetto-style */
  1156. conv += ((int64_t)tv->tv_usec+500)/1000L;
  1157. return conv;
  1158. }
  1159. /**
  1160. * Converts timeval to microseconds.
  1161. */
  1162. int64_t
  1163. tv_to_usec(const struct timeval *tv)
  1164. {
  1165. int64_t conv = ((int64_t)tv->tv_sec)*1000000L;
  1166. conv += tv->tv_usec;
  1167. return conv;
  1168. }
  1169. /** Return the number of microseconds elapsed between *start and *end.
  1170. */
  1171. long
  1172. tv_udiff(const struct timeval *start, const struct timeval *end)
  1173. {
  1174. long udiff;
  1175. long secdiff = end->tv_sec - start->tv_sec;
  1176. if (labs(secdiff+1) > LONG_MAX/1000000) {
  1177. log_warn(LD_GENERAL, "comparing times on microsecond detail too far "
  1178. "apart: %ld seconds", secdiff);
  1179. return LONG_MAX;
  1180. }
  1181. udiff = secdiff*1000000L + (end->tv_usec - start->tv_usec);
  1182. return udiff;
  1183. }
  1184. /** Return the number of milliseconds elapsed between *start and *end.
  1185. */
  1186. long
  1187. tv_mdiff(const struct timeval *start, const struct timeval *end)
  1188. {
  1189. long mdiff;
  1190. long secdiff = end->tv_sec - start->tv_sec;
  1191. if (labs(secdiff+1) > LONG_MAX/1000) {
  1192. log_warn(LD_GENERAL, "comparing times on millisecond detail too far "
  1193. "apart: %ld seconds", secdiff);
  1194. return LONG_MAX;
  1195. }
  1196. /* Subtract and round */
  1197. mdiff = secdiff*1000L +
  1198. ((long)end->tv_usec - (long)start->tv_usec + 500L) / 1000L;
  1199. return mdiff;
  1200. }
  1201. /** Yield true iff <b>y</b> is a leap-year. */
  1202. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  1203. /** Helper: Return the number of leap-days between Jan 1, y1 and Jan 1, y2. */
  1204. static int
  1205. n_leapdays(int y1, int y2)
  1206. {
  1207. --y1;
  1208. --y2;
  1209. return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
  1210. }
  1211. /** Number of days per month in non-leap year; used by tor_timegm. */
  1212. static const int days_per_month[] =
  1213. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  1214. /** Return a time_t given a struct tm. The result is given in GMT, and
  1215. * does not account for leap seconds.
  1216. */
  1217. time_t
  1218. tor_timegm(struct tm *tm)
  1219. {
  1220. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  1221. * It's way more brute-force than fiddling with tzset().
  1222. */
  1223. time_t year, days, hours, minutes, seconds;
  1224. int i;
  1225. year = tm->tm_year + 1900;
  1226. if (year < 1970 || tm->tm_mon < 0 || tm->tm_mon > 11) {
  1227. log_warn(LD_BUG, "Out-of-range argument to tor_timegm");
  1228. return -1;
  1229. }
  1230. tor_assert(year < INT_MAX);
  1231. days = 365 * (year-1970) + n_leapdays(1970,(int)year);
  1232. for (i = 0; i < tm->tm_mon; ++i)
  1233. days += days_per_month[i];
  1234. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  1235. ++days;
  1236. days += tm->tm_mday - 1;
  1237. hours = days*24 + tm->tm_hour;
  1238. minutes = hours*60 + tm->tm_min;
  1239. seconds = minutes*60 + tm->tm_sec;
  1240. return seconds;
  1241. }
  1242. /* strftime is locale-specific, so we need to replace those parts */
  1243. /** A c-locale array of 3-letter names of weekdays, starting with Sun. */
  1244. static const char *WEEKDAY_NAMES[] =
  1245. { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1246. /** A c-locale array of 3-letter names of months, starting with Jan. */
  1247. static const char *MONTH_NAMES[] =
  1248. { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  1249. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1250. /** Set <b>buf</b> to the RFC1123 encoding of the GMT value of <b>t</b>.
  1251. * The buffer must be at least RFC1123_TIME_LEN+1 bytes long.
  1252. *
  1253. * (RFC1123 format is Fri, 29 Sep 2006 15:54:20 GMT)
  1254. */
  1255. void
  1256. format_rfc1123_time(char *buf, time_t t)
  1257. {
  1258. struct tm tm;
  1259. tor_gmtime_r(&t, &tm);
  1260. strftime(buf, RFC1123_TIME_LEN+1, "___, %d ___ %Y %H:%M:%S GMT", &tm);
  1261. tor_assert(tm.tm_wday >= 0);
  1262. tor_assert(tm.tm_wday <= 6);
  1263. memcpy(buf, WEEKDAY_NAMES[tm.tm_wday], 3);
  1264. tor_assert(tm.tm_wday >= 0);
  1265. tor_assert(tm.tm_mon <= 11);
  1266. memcpy(buf+8, MONTH_NAMES[tm.tm_mon], 3);
  1267. }
  1268. /** Parse the RFC1123 encoding of some time (in GMT) from <b>buf</b>,
  1269. * and store the result in *<b>t</b>.
  1270. *
  1271. * Return 0 on success, -1 on failure.
  1272. */
  1273. int
  1274. parse_rfc1123_time(const char *buf, time_t *t)
  1275. {
  1276. struct tm tm;
  1277. char month[4];
  1278. char weekday[4];
  1279. int i, m;
  1280. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  1281. if (strlen(buf) != RFC1123_TIME_LEN)
  1282. return -1;
  1283. memset(&tm, 0, sizeof(tm));
  1284. if (tor_sscanf(buf, "%3s, %2u %3s %u %2u:%2u:%2u GMT", weekday,
  1285. &tm_mday, month, &tm_year, &tm_hour,
  1286. &tm_min, &tm_sec) < 7) {
  1287. char *esc = esc_for_log(buf);
  1288. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  1289. tor_free(esc);
  1290. return -1;
  1291. }
  1292. if (tm_mday > 31 || tm_hour > 23 || tm_min > 59 || tm_sec > 61) {
  1293. char *esc = esc_for_log(buf);
  1294. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  1295. tor_free(esc);
  1296. return -1;
  1297. }
  1298. tm.tm_mday = (int)tm_mday;
  1299. tm.tm_year = (int)tm_year;
  1300. tm.tm_hour = (int)tm_hour;
  1301. tm.tm_min = (int)tm_min;
  1302. tm.tm_sec = (int)tm_sec;
  1303. m = -1;
  1304. for (i = 0; i < 12; ++i) {
  1305. if (!strcmp(month, MONTH_NAMES[i])) {
  1306. m = i;
  1307. break;
  1308. }
  1309. }
  1310. if (m<0) {
  1311. char *esc = esc_for_log(buf);
  1312. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s: No such month", esc);
  1313. tor_free(esc);
  1314. return -1;
  1315. }
  1316. tm.tm_mon = m;
  1317. if (tm.tm_year < 1970) {
  1318. char *esc = esc_for_log(buf);
  1319. log_warn(LD_GENERAL,
  1320. "Got invalid RFC1123 time %s. (Before 1970)", esc);
  1321. tor_free(esc);
  1322. return -1;
  1323. }
  1324. tm.tm_year -= 1900;
  1325. *t = tor_timegm(&tm);
  1326. return 0;
  1327. }
  1328. /** Set <b>buf</b> to the ISO8601 encoding of the local value of <b>t</b>.
  1329. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  1330. *
  1331. * (ISO8601 format is 2006-10-29 10:57:20)
  1332. */
  1333. void
  1334. format_local_iso_time(char *buf, time_t t)
  1335. {
  1336. struct tm tm;
  1337. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t, &tm));
  1338. }
  1339. /** Set <b>buf</b> to the ISO8601 encoding of the GMT value of <b>t</b>.
  1340. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  1341. */
  1342. void
  1343. format_iso_time(char *buf, time_t t)
  1344. {
  1345. struct tm tm;
  1346. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t, &tm));
  1347. }
  1348. /** As format_iso_time, but use the yyyy-mm-ddThh:mm:ss format to avoid
  1349. * embedding an internal space. */
  1350. void
  1351. format_iso_time_nospace(char *buf, time_t t)
  1352. {
  1353. format_iso_time(buf, t);
  1354. buf[10] = 'T';
  1355. }
  1356. /** As format_iso_time_nospace, but include microseconds in decimal
  1357. * fixed-point format. Requires that buf be at least ISO_TIME_USEC_LEN+1
  1358. * bytes long. */
  1359. void
  1360. format_iso_time_nospace_usec(char *buf, const struct timeval *tv)
  1361. {
  1362. tor_assert(tv);
  1363. format_iso_time_nospace(buf, tv->tv_sec);
  1364. tor_snprintf(buf+ISO_TIME_LEN, 8, ".%06d", (int)tv->tv_usec);
  1365. }
  1366. /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
  1367. * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
  1368. * failure. Ignore extraneous stuff in <b>cp</b> separated by whitespace from
  1369. * the end of the time string. */
  1370. int
  1371. parse_iso_time(const char *cp, time_t *t)
  1372. {
  1373. struct tm st_tm;
  1374. unsigned int year=0, month=0, day=0, hour=100, minute=100, second=100;
  1375. if (tor_sscanf(cp, "%u-%2u-%2u %2u:%2u:%2u", &year, &month,
  1376. &day, &hour, &minute, &second) < 6) {
  1377. char *esc = esc_for_log(cp);
  1378. log_warn(LD_GENERAL, "ISO time %s was unparseable", esc);
  1379. tor_free(esc);
  1380. return -1;
  1381. }
  1382. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  1383. hour > 23 || minute > 59 || second > 61) {
  1384. char *esc = esc_for_log(cp);
  1385. log_warn(LD_GENERAL, "ISO time %s was nonsensical", esc);
  1386. tor_free(esc);
  1387. return -1;
  1388. }
  1389. st_tm.tm_year = year-1900;
  1390. st_tm.tm_mon = month-1;
  1391. st_tm.tm_mday = day;
  1392. st_tm.tm_hour = hour;
  1393. st_tm.tm_min = minute;
  1394. st_tm.tm_sec = second;
  1395. if (st_tm.tm_year < 70) {
  1396. char *esc = esc_for_log(cp);
  1397. log_warn(LD_GENERAL, "Got invalid ISO time %s. (Before 1970)", esc);
  1398. tor_free(esc);
  1399. return -1;
  1400. }
  1401. *t = tor_timegm(&st_tm);
  1402. return 0;
  1403. }
  1404. /** Given a <b>date</b> in one of the three formats allowed by HTTP (ugh),
  1405. * parse it into <b>tm</b>. Return 0 on success, negative on failure. */
  1406. int
  1407. parse_http_time(const char *date, struct tm *tm)
  1408. {
  1409. const char *cp;
  1410. char month[4];
  1411. char wkday[4];
  1412. int i;
  1413. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  1414. tor_assert(tm);
  1415. memset(tm, 0, sizeof(*tm));
  1416. /* First, try RFC1123 or RFC850 format: skip the weekday. */
  1417. if ((cp = strchr(date, ','))) {
  1418. ++cp;
  1419. if (tor_sscanf(date, "%2u %3s %4u %2u:%2u:%2u GMT",
  1420. &tm_mday, month, &tm_year,
  1421. &tm_hour, &tm_min, &tm_sec) == 6) {
  1422. /* rfc1123-date */
  1423. tm_year -= 1900;
  1424. } else if (tor_sscanf(date, "%2u-%3s-%2u %2u:%2u:%2u GMT",
  1425. &tm_mday, month, &tm_year,
  1426. &tm_hour, &tm_min, &tm_sec) == 6) {
  1427. /* rfc850-date */
  1428. } else {
  1429. return -1;
  1430. }
  1431. } else {
  1432. /* No comma; possibly asctime() format. */
  1433. if (tor_sscanf(date, "%3s %3s %2u %2u:%2u:%2u %4u",
  1434. wkday, month, &tm_mday,
  1435. &tm_hour, &tm_min, &tm_sec, &tm_year) == 7) {
  1436. tm_year -= 1900;
  1437. } else {
  1438. return -1;
  1439. }
  1440. }
  1441. tm->tm_mday = (int)tm_mday;
  1442. tm->tm_year = (int)tm_year;
  1443. tm->tm_hour = (int)tm_hour;
  1444. tm->tm_min = (int)tm_min;
  1445. tm->tm_sec = (int)tm_sec;
  1446. month[3] = '\0';
  1447. /* Okay, now decode the month. */
  1448. for (i = 0; i < 12; ++i) {
  1449. if (!strcasecmp(MONTH_NAMES[i], month)) {
  1450. tm->tm_mon = i+1;
  1451. }
  1452. }
  1453. if (tm->tm_year < 0 ||
  1454. tm->tm_mon < 1 || tm->tm_mon > 12 ||
  1455. tm->tm_mday < 0 || tm->tm_mday > 31 ||
  1456. tm->tm_hour < 0 || tm->tm_hour > 23 ||
  1457. tm->tm_min < 0 || tm->tm_min > 59 ||
  1458. tm->tm_sec < 0 || tm->tm_sec > 61)
  1459. return -1; /* Out of range, or bad month. */
  1460. return 0;
  1461. }
  1462. /** Given an <b>interval</b> in seconds, try to write it to the
  1463. * <b>out_len</b>-byte buffer in <b>out</b> in a human-readable form.
  1464. * Return 0 on success, -1 on failure.
  1465. */
  1466. int
  1467. format_time_interval(char *out, size_t out_len, long interval)
  1468. {
  1469. /* We only report seconds if there's no hours. */
  1470. long sec = 0, min = 0, hour = 0, day = 0;
  1471. if (interval < 0)
  1472. interval = -interval;
  1473. if (interval >= 86400) {
  1474. day = interval / 86400;
  1475. interval %= 86400;
  1476. }
  1477. if (interval >= 3600) {
  1478. hour = interval / 3600;
  1479. interval %= 3600;
  1480. }
  1481. if (interval >= 60) {
  1482. min = interval / 60;
  1483. interval %= 60;
  1484. }
  1485. sec = interval;
  1486. if (day) {
  1487. return tor_snprintf(out, out_len, "%ld days, %ld hours, %ld minutes",
  1488. day, hour, min);
  1489. } else if (hour) {
  1490. return tor_snprintf(out, out_len, "%ld hours, %ld minutes", hour, min);
  1491. } else if (min) {
  1492. return tor_snprintf(out, out_len, "%ld minutes, %ld seconds", min, sec);
  1493. } else {
  1494. return tor_snprintf(out, out_len, "%ld seconds", sec);
  1495. }
  1496. }
  1497. /* =====
  1498. * Cached time
  1499. * ===== */
  1500. #ifndef TIME_IS_FAST
  1501. /** Cached estimate of the current time. Updated around once per second;
  1502. * may be a few seconds off if we are really busy. This is a hack to avoid
  1503. * calling time(NULL) (which not everybody has optimized) on critical paths.
  1504. */
  1505. static time_t cached_approx_time = 0;
  1506. /** Return a cached estimate of the current time from when
  1507. * update_approx_time() was last called. This is a hack to avoid calling
  1508. * time(NULL) on critical paths: please do not even think of calling it
  1509. * anywhere else. */
  1510. time_t
  1511. approx_time(void)
  1512. {
  1513. return cached_approx_time;
  1514. }
  1515. /** Update the cached estimate of the current time. This function SHOULD be
  1516. * called once per second, and MUST be called before the first call to
  1517. * get_approx_time. */
  1518. void
  1519. update_approx_time(time_t now)
  1520. {
  1521. cached_approx_time = now;
  1522. }
  1523. #endif
  1524. /* =====
  1525. * Rate limiting
  1526. * ===== */
  1527. /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return the number
  1528. * of calls to rate_limit_is_ready (including this one!) since the last time
  1529. * rate_limit_is_ready returned nonzero. Otherwise return 0. */
  1530. static int
  1531. rate_limit_is_ready(ratelim_t *lim, time_t now)
  1532. {
  1533. if (lim->rate + lim->last_allowed <= now) {
  1534. int res = lim->n_calls_since_last_time + 1;
  1535. lim->last_allowed = now;
  1536. lim->n_calls_since_last_time = 0;
  1537. return res;
  1538. } else {
  1539. ++lim->n_calls_since_last_time;
  1540. return 0;
  1541. }
  1542. }
  1543. /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return a newly
  1544. * allocated string indicating how many messages were suppressed, suitable to
  1545. * append to a log message. Otherwise return NULL. */
  1546. char *
  1547. rate_limit_log(ratelim_t *lim, time_t now)
  1548. {
  1549. int n;
  1550. if ((n = rate_limit_is_ready(lim, now))) {
  1551. if (n == 1) {
  1552. return tor_strdup("");
  1553. } else {
  1554. char *cp=NULL;
  1555. tor_asprintf(&cp,
  1556. " [%d similar message(s) suppressed in last %d seconds]",
  1557. n-1, lim->rate);
  1558. return cp;
  1559. }
  1560. } else {
  1561. return NULL;
  1562. }
  1563. }
  1564. /* =====
  1565. * File helpers
  1566. * ===== */
  1567. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  1568. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  1569. * was returned by open(). Return the number of bytes written, or -1
  1570. * on error. Only use if fd is a blocking fd. */
  1571. ssize_t
  1572. write_all(tor_socket_t fd, const char *buf, size_t count, int isSocket)
  1573. {
  1574. size_t written = 0;
  1575. ssize_t result;
  1576. tor_assert(count < SSIZE_T_MAX);
  1577. while (written != count) {
  1578. if (isSocket)
  1579. result = tor_socket_send(fd, buf+written, count-written, 0);
  1580. else
  1581. result = write((int)fd, buf+written, count-written);
  1582. if (result<0)
  1583. return -1;
  1584. written += result;
  1585. }
  1586. return (ssize_t)count;
  1587. }
  1588. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  1589. * or reach the end of the file. <b>isSocket</b> must be 1 if fd
  1590. * was returned by socket() or accept(), and 0 if fd was returned by
  1591. * open(). Return the number of bytes read, or -1 on error. Only use
  1592. * if fd is a blocking fd. */
  1593. ssize_t
  1594. read_all(tor_socket_t fd, char *buf, size_t count, int isSocket)
  1595. {
  1596. size_t numread = 0;
  1597. ssize_t result;
  1598. if (count > SIZE_T_CEILING || count > SSIZE_T_MAX)
  1599. return -1;
  1600. while (numread != count) {
  1601. if (isSocket)
  1602. result = tor_socket_recv(fd, buf+numread, count-numread, 0);
  1603. else
  1604. result = read((int)fd, buf+numread, count-numread);
  1605. if (result<0)
  1606. return -1;
  1607. else if (result == 0)
  1608. break;
  1609. numread += result;
  1610. }
  1611. return (ssize_t)numread;
  1612. }
  1613. /*
  1614. * Filesystem operations.
  1615. */
  1616. /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
  1617. * we do nothing. On Windows, we remove a trailing slash, unless the path is
  1618. * the root of a disk. */
  1619. static void
  1620. clean_name_for_stat(char *name)
  1621. {
  1622. #ifdef _WIN32
  1623. size_t len = strlen(name);
  1624. if (!len)
  1625. return;
  1626. if (name[len-1]=='\\' || name[len-1]=='/') {
  1627. if (len == 1 || (len==3 && name[1]==':'))
  1628. return;
  1629. name[len-1]='\0';
  1630. }
  1631. #else
  1632. (void)name;
  1633. #endif
  1634. }
  1635. /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  1636. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  1637. * directory. On FN_ERROR, sets errno. */
  1638. file_status_t
  1639. file_status(const char *fname)
  1640. {
  1641. struct stat st;
  1642. char *f;
  1643. int r;
  1644. f = tor_strdup(fname);
  1645. clean_name_for_stat(f);
  1646. r = stat(f, &st);
  1647. tor_free(f);
  1648. if (r) {
  1649. if (errno == ENOENT) {
  1650. return FN_NOENT;
  1651. }
  1652. return FN_ERROR;
  1653. }
  1654. if (st.st_mode & S_IFDIR)
  1655. return FN_DIR;
  1656. else if (st.st_mode & S_IFREG)
  1657. return FN_FILE;
  1658. else
  1659. return FN_ERROR;
  1660. }
  1661. /** Check whether <b>dirname</b> exists and is private. If yes return 0. If
  1662. * it does not exist, and <b>check</b>&CPD_CREATE is set, try to create it
  1663. * and return 0 on success. If it does not exist, and
  1664. * <b>check</b>&CPD_CHECK, and we think we can create it, return 0. Else
  1665. * return -1. If CPD_GROUP_OK is set, then it's okay if the directory
  1666. * is group-readable, but in all cases we create the directory mode 0700.
  1667. * If CPD_CHECK_MODE_ONLY is set, then we don't alter the directory permissions
  1668. * if they are too permissive: we just return -1.
  1669. * When effective_user is not NULL, check permissions against the given user
  1670. * and its primary group.
  1671. */
  1672. int
  1673. check_private_dir(const char *dirname, cpd_check_t check,
  1674. const char *effective_user)
  1675. {
  1676. int r;
  1677. struct stat st;
  1678. char *f;
  1679. #ifndef _WIN32
  1680. int mask;
  1681. struct passwd *pw = NULL;
  1682. uid_t running_uid;
  1683. gid_t running_gid;
  1684. #else
  1685. (void)effective_user;
  1686. #endif
  1687. tor_assert(dirname);
  1688. f = tor_strdup(dirname);
  1689. clean_name_for_stat(f);
  1690. r = stat(f, &st);
  1691. tor_free(f);
  1692. if (r) {
  1693. if (errno != ENOENT) {
  1694. log_warn(LD_FS, "Directory %s cannot be read: %s", dirname,
  1695. strerror(errno));
  1696. return -1;
  1697. }
  1698. if (check & CPD_CREATE) {
  1699. log_info(LD_GENERAL, "Creating directory %s", dirname);
  1700. #if defined (_WIN32) && !defined (WINCE)
  1701. r = mkdir(dirname);
  1702. #else
  1703. r = mkdir(dirname, 0700);
  1704. #endif
  1705. if (r) {
  1706. log_warn(LD_FS, "Error creating directory %s: %s", dirname,
  1707. strerror(errno));
  1708. return -1;
  1709. }
  1710. } else if (!(check & CPD_CHECK)) {
  1711. log_warn(LD_FS, "Directory %s does not exist.", dirname);
  1712. return -1;
  1713. }
  1714. /* XXXX In the case where check==CPD_CHECK, we should look at the
  1715. * parent directory a little harder. */
  1716. return 0;
  1717. }
  1718. if (!(st.st_mode & S_IFDIR)) {
  1719. log_warn(LD_FS, "%s is not a directory", dirname);
  1720. return -1;
  1721. }
  1722. #ifndef _WIN32
  1723. if (effective_user) {
  1724. /* Look up the user and group information.
  1725. * If we have a problem, bail out. */
  1726. pw = getpwnam(effective_user);
  1727. if (pw == NULL) {
  1728. log_warn(LD_CONFIG, "Error setting configured user: %s not found",
  1729. effective_user);
  1730. return -1;
  1731. }
  1732. running_uid = pw->pw_uid;
  1733. running_gid = pw->pw_gid;
  1734. } else {
  1735. running_uid = getuid();
  1736. running_gid = getgid();
  1737. }
  1738. if (st.st_uid != running_uid) {
  1739. struct passwd *pw = NULL;
  1740. char *process_ownername = NULL;
  1741. pw = getpwuid(running_uid);
  1742. process_ownername = pw ? tor_strdup(pw->pw_name) : tor_strdup("<unknown>");
  1743. pw = getpwuid(st.st_uid);
  1744. log_warn(LD_FS, "%s is not owned by this user (%s, %d) but by "
  1745. "%s (%d). Perhaps you are running Tor as the wrong user?",
  1746. dirname, process_ownername, (int)running_uid,
  1747. pw ? pw->pw_name : "<unknown>", (int)st.st_uid);
  1748. tor_free(process_ownername);
  1749. return -1;
  1750. }
  1751. if ((check & CPD_GROUP_OK) && st.st_gid != running_gid) {
  1752. struct group *gr;
  1753. char *process_groupname = NULL;
  1754. gr = getgrgid(running_gid);
  1755. process_groupname = gr ? tor_strdup(gr->gr_name) : tor_strdup("<unknown>");
  1756. gr = getgrgid(st.st_gid);
  1757. log_warn(LD_FS, "%s is not owned by this group (%s, %d) but by group "
  1758. "%s (%d). Are you running Tor as the wrong user?",
  1759. dirname, process_groupname, (int)running_gid,
  1760. gr ? gr->gr_name : "<unknown>", (int)st.st_gid);
  1761. tor_free(process_groupname);
  1762. return -1;
  1763. }
  1764. if (check & CPD_GROUP_OK) {
  1765. mask = 0027;
  1766. } else {
  1767. mask = 0077;
  1768. }
  1769. if (st.st_mode & mask) {
  1770. unsigned new_mode;
  1771. if (check & CPD_CHECK_MODE_ONLY) {
  1772. log_warn(LD_FS, "Permissions on directory %s are too permissive.",
  1773. dirname);
  1774. return -1;
  1775. }
  1776. log_warn(LD_FS, "Fixing permissions on directory %s", dirname);
  1777. new_mode = st.st_mode;
  1778. new_mode |= 0700; /* Owner should have rwx */
  1779. new_mode &= ~mask; /* Clear the other bits that we didn't want set...*/
  1780. if (chmod(dirname, new_mode)) {
  1781. log_warn(LD_FS, "Could not chmod directory %s: %s", dirname,
  1782. strerror(errno));
  1783. return -1;
  1784. } else {
  1785. return 0;
  1786. }
  1787. }
  1788. #endif
  1789. return 0;
  1790. }
  1791. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite
  1792. * the previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  1793. *
  1794. * This function replaces the old file atomically, if possible. This
  1795. * function, and all other functions in util.c that create files, create them
  1796. * with mode 0600.
  1797. */
  1798. int
  1799. write_str_to_file(const char *fname, const char *str, int bin)
  1800. {
  1801. #ifdef _WIN32
  1802. if (!bin && strchr(str, '\r')) {
  1803. log_warn(LD_BUG,
  1804. "We're writing a text string that already contains a CR.");
  1805. }
  1806. #endif
  1807. return write_bytes_to_file(fname, str, strlen(str), bin);
  1808. }
  1809. /** Represents a file that we're writing to, with support for atomic commit:
  1810. * we can write into a temporary file, and either remove the file on
  1811. * failure, or replace the original file on success. */
  1812. struct open_file_t {
  1813. char *tempname; /**< Name of the temporary file. */
  1814. char *filename; /**< Name of the original file. */
  1815. unsigned rename_on_close:1; /**< Are we using the temporary file or not? */
  1816. unsigned binary:1; /**< Did we open in binary mode? */
  1817. int fd; /**< fd for the open file. */
  1818. FILE *stdio_file; /**< stdio wrapper for <b>fd</b>. */
  1819. };
  1820. /** Try to start writing to the file in <b>fname</b>, passing the flags
  1821. * <b>open_flags</b> to the open() syscall, creating the file (if needed) with
  1822. * access value <b>mode</b>. If the O_APPEND flag is set, we append to the
  1823. * original file. Otherwise, we open a new temporary file in the same
  1824. * directory, and either replace the original or remove the temporary file
  1825. * when we're done.
  1826. *
  1827. * Return the fd for the newly opened file, and store working data in
  1828. * *<b>data_out</b>. The caller should not close the fd manually:
  1829. * instead, call finish_writing_to_file() or abort_writing_to_file().
  1830. * Returns -1 on failure.
  1831. *
  1832. * NOTE: When not appending, the flags O_CREAT and O_TRUNC are treated
  1833. * as true and the flag O_EXCL is treated as false.
  1834. *
  1835. * NOTE: Ordinarily, O_APPEND means "seek to the end of the file before each
  1836. * write()". We don't do that.
  1837. */
  1838. int
  1839. start_writing_to_file(const char *fname, int open_flags, int mode,
  1840. open_file_t **data_out)
  1841. {
  1842. open_file_t *new_file = tor_malloc_zero(sizeof(open_file_t));
  1843. const char *open_name;
  1844. int append = 0;
  1845. tor_assert(fname);
  1846. tor_assert(data_out);
  1847. #if (O_BINARY != 0 && O_TEXT != 0)
  1848. tor_assert((open_flags & (O_BINARY|O_TEXT)) != 0);
  1849. #endif
  1850. new_file->fd = -1;
  1851. new_file->filename = tor_strdup(fname);
  1852. if (open_flags & O_APPEND) {
  1853. open_name = fname;
  1854. new_file->rename_on_close = 0;
  1855. append = 1;
  1856. open_flags &= ~O_APPEND;
  1857. } else {
  1858. tor_asprintf(&new_file->tempname, "%s.tmp", fname);
  1859. open_name = new_file->tempname;
  1860. /* We always replace an existing temporary file if there is one. */
  1861. open_flags |= O_CREAT|O_TRUNC;
  1862. open_flags &= ~O_EXCL;
  1863. new_file->rename_on_close = 1;
  1864. }
  1865. if (open_flags & O_BINARY)
  1866. new_file->binary = 1;
  1867. new_file->fd = tor_open_cloexec(open_name, open_flags, mode);
  1868. if (new_file->fd < 0) {
  1869. log_warn(LD_FS, "Couldn't open \"%s\" (%s) for writing: %s",
  1870. open_name, fname, strerror(errno));
  1871. goto err;
  1872. }
  1873. if (append) {
  1874. if (tor_fd_seekend(new_file->fd) < 0) {
  1875. log_warn(LD_FS, "Couldn't seek to end of file \"%s\": %s", open_name,
  1876. strerror(errno));
  1877. goto err;
  1878. }
  1879. }
  1880. *data_out = new_file;
  1881. return new_file->fd;
  1882. err:
  1883. if (new_file->fd >= 0)
  1884. close(new_file->fd);
  1885. *data_out = NULL;
  1886. tor_free(new_file->filename);
  1887. tor_free(new_file->tempname);
  1888. tor_free(new_file);
  1889. return -1;
  1890. }
  1891. /** Given <b>file_data</b> from start_writing_to_file(), return a stdio FILE*
  1892. * that can be used to write to the same file. The caller should not mix
  1893. * stdio calls with non-stdio calls. */
  1894. FILE *
  1895. fdopen_file(open_file_t *file_data)
  1896. {
  1897. tor_assert(file_data);
  1898. if (file_data->stdio_file)
  1899. return file_data->stdio_file;
  1900. tor_assert(file_data->fd >= 0);
  1901. if (!(file_data->stdio_file = fdopen(file_data->fd,
  1902. file_data->binary?"ab":"a"))) {
  1903. log_warn(LD_FS, "Couldn't fdopen \"%s\" [%d]: %s", file_data->filename,
  1904. file_data->fd, strerror(errno));
  1905. }
  1906. return file_data->stdio_file;
  1907. }
  1908. /** Combines start_writing_to_file with fdopen_file(): arguments are as
  1909. * for start_writing_to_file, but */
  1910. FILE *
  1911. start_writing_to_stdio_file(const char *fname, int open_flags, int mode,
  1912. open_file_t **data_out)
  1913. {
  1914. FILE *res;
  1915. if (start_writing_to_file(fname, open_flags, mode, data_out)<0)
  1916. return NULL;
  1917. if (!(res = fdopen_file(*data_out))) {
  1918. abort_writing_to_file(*data_out);
  1919. *data_out = NULL;
  1920. }
  1921. return res;
  1922. }
  1923. /** Helper function: close and free the underlying file and memory in
  1924. * <b>file_data</b>. If we were writing into a temporary file, then delete
  1925. * that file (if abort_write is true) or replaces the target file with
  1926. * the temporary file (if abort_write is false). */
  1927. static int
  1928. finish_writing_to_file_impl(open_file_t *file_data, int abort_write)
  1929. {
  1930. int r = 0;
  1931. tor_assert(file_data && file_data->filename);
  1932. if (file_data->stdio_file) {
  1933. if (fclose(file_data->stdio_file)) {
  1934. log_warn(LD_FS, "Error closing \"%s\": %s", file_data->filename,
  1935. strerror(errno));
  1936. abort_write = r = -1;
  1937. }
  1938. } else if (file_data->fd >= 0 && close(file_data->fd) < 0) {
  1939. log_warn(LD_FS, "Error flushing \"%s\": %s", file_data->filename,
  1940. strerror(errno));
  1941. abort_write = r = -1;
  1942. }
  1943. if (file_data->rename_on_close) {
  1944. tor_assert(file_data->tempname && file_data->filename);
  1945. if (abort_write) {
  1946. unlink(file_data->tempname);
  1947. } else {
  1948. tor_assert(strcmp(file_data->filename, file_data->tempname));
  1949. if (replace_file(file_data->tempname, file_data->filename)) {
  1950. log_warn(LD_FS, "Error replacing \"%s\": %s", file_data->filename,
  1951. strerror(errno));
  1952. r = -1;
  1953. }
  1954. }
  1955. }
  1956. tor_free(file_data->filename);
  1957. tor_free(file_data->tempname);
  1958. tor_free(file_data);
  1959. return r;
  1960. }
  1961. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1962. * needed, and if using a temporary file, replace the original file with
  1963. * the temporary file. */
  1964. int
  1965. finish_writing_to_file(open_file_t *file_data)
  1966. {
  1967. return finish_writing_to_file_impl(file_data, 0);
  1968. }
  1969. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1970. * needed, and if using a temporary file, delete it. */
  1971. int
  1972. abort_writing_to_file(open_file_t *file_data)
  1973. {
  1974. return finish_writing_to_file_impl(file_data, 1);
  1975. }
  1976. /** Helper: given a set of flags as passed to open(2), open the file
  1977. * <b>fname</b> and write all the sized_chunk_t structs in <b>chunks</b> to
  1978. * the file. Do so as atomically as possible e.g. by opening temp files and
  1979. * renaming. */
  1980. static int
  1981. write_chunks_to_file_impl(const char *fname, const smartlist_t *chunks,
  1982. int open_flags)
  1983. {
  1984. open_file_t *file = NULL;
  1985. int fd;
  1986. ssize_t result;
  1987. fd = start_writing_to_file(fname, open_flags, 0600, &file);
  1988. if (fd<0)
  1989. return -1;
  1990. SMARTLIST_FOREACH(chunks, sized_chunk_t *, chunk,
  1991. {
  1992. result = write_all(fd, chunk->bytes, chunk->len, 0);
  1993. if (result < 0) {
  1994. log_warn(LD_FS, "Error writing to \"%s\": %s", fname,
  1995. strerror(errno));
  1996. goto err;
  1997. }
  1998. tor_assert((size_t)result == chunk->len);
  1999. });
  2000. return finish_writing_to_file(file);
  2001. err:
  2002. abort_writing_to_file(file);
  2003. return -1;
  2004. }
  2005. /** Given a smartlist of sized_chunk_t, write them atomically to a file
  2006. * <b>fname</b>, overwriting or creating the file as necessary. */
  2007. int
  2008. write_chunks_to_file(const char *fname, const smartlist_t *chunks, int bin)
  2009. {
  2010. int flags = OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT);
  2011. return write_chunks_to_file_impl(fname, chunks, flags);
  2012. }
  2013. /** Write <b>len</b> bytes, starting at <b>str</b>, to <b>fname</b>
  2014. using the open() flags passed in <b>flags</b>. */
  2015. static int
  2016. write_bytes_to_file_impl(const char *fname, const char *str, size_t len,
  2017. int flags)
  2018. {
  2019. int r;
  2020. sized_chunk_t c = { str, len };
  2021. smartlist_t *chunks = smartlist_new();
  2022. smartlist_add(chunks, &c);
  2023. r = write_chunks_to_file_impl(fname, chunks, flags);
  2024. smartlist_free(chunks);
  2025. return r;
  2026. }
  2027. /** As write_str_to_file, but does not assume a NUL-terminated
  2028. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  2029. int
  2030. write_bytes_to_file(const char *fname, const char *str, size_t len,
  2031. int bin)
  2032. {
  2033. return write_bytes_to_file_impl(fname, str, len,
  2034. OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT));
  2035. }
  2036. /** As write_bytes_to_file, but if the file already exists, append the bytes
  2037. * to the end of the file instead of overwriting it. */
  2038. int
  2039. append_bytes_to_file(const char *fname, const char *str, size_t len,
  2040. int bin)
  2041. {
  2042. return write_bytes_to_file_impl(fname, str, len,
  2043. OPEN_FLAGS_APPEND|(bin?O_BINARY:O_TEXT));
  2044. }
  2045. /** Like write_str_to_file(), but also return -1 if there was a file
  2046. already residing in <b>fname</b>. */
  2047. int
  2048. write_bytes_to_new_file(const char *fname, const char *str, size_t len,
  2049. int bin)
  2050. {
  2051. return write_bytes_to_file_impl(fname, str, len,
  2052. OPEN_FLAGS_DONT_REPLACE|
  2053. (bin?O_BINARY:O_TEXT));
  2054. }
  2055. /** Read the contents of <b>filename</b> into a newly allocated
  2056. * string; return the string on success or NULL on failure.
  2057. *
  2058. * If <b>stat_out</b> is provided, store the result of stat()ing the
  2059. * file into <b>stat_out</b>.
  2060. *
  2061. * If <b>flags</b> &amp; RFTS_BIN, open the file in binary mode.
  2062. * If <b>flags</b> &amp; RFTS_IGNORE_MISSING, don't warn if the file
  2063. * doesn't exist.
  2064. */
  2065. /*
  2066. * This function <em>may</em> return an erroneous result if the file
  2067. * is modified while it is running, but must not crash or overflow.
  2068. * Right now, the error case occurs when the file length grows between
  2069. * the call to stat and the call to read_all: the resulting string will
  2070. * be truncated.
  2071. */
  2072. char *
  2073. read_file_to_str(const char *filename, int flags, struct stat *stat_out)
  2074. {
  2075. int fd; /* router file */
  2076. struct stat statbuf;
  2077. char *string;
  2078. ssize_t r;
  2079. int bin = flags & RFTS_BIN;
  2080. tor_assert(filename);
  2081. fd = tor_open_cloexec(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  2082. if (fd<0) {
  2083. int severity = LOG_WARN;
  2084. int save_errno = errno;
  2085. if (errno == ENOENT && (flags & RFTS_IGNORE_MISSING))
  2086. severity = LOG_INFO;
  2087. log_fn(severity, LD_FS,"Could not open \"%s\": %s",filename,
  2088. strerror(errno));
  2089. errno = save_errno;
  2090. return NULL;
  2091. }
  2092. if (fstat(fd, &statbuf)<0) {
  2093. int save_errno = errno;
  2094. close(fd);
  2095. log_warn(LD_FS,"Could not fstat \"%s\".",filename);
  2096. errno = save_errno;
  2097. return NULL;
  2098. }
  2099. if ((uint64_t)(statbuf.st_size)+1 >= SIZE_T_CEILING)
  2100. return NULL;
  2101. string = tor_malloc((size_t)(statbuf.st_size+1));
  2102. r = read_all(fd,string,(size_t)statbuf.st_size,0);
  2103. if (r<0) {
  2104. int save_errno = errno;
  2105. log_warn(LD_FS,"Error reading from file \"%s\": %s", filename,
  2106. strerror(errno));
  2107. tor_free(string);
  2108. close(fd);
  2109. errno = save_errno;
  2110. return NULL;
  2111. }
  2112. string[r] = '\0'; /* NUL-terminate the result. */
  2113. #ifdef _WIN32
  2114. if (!bin && strchr(string, '\r')) {
  2115. log_debug(LD_FS, "We didn't convert CRLF to LF as well as we hoped "
  2116. "when reading %s. Coping.",
  2117. filename);
  2118. tor_strstrip(string, "\r");
  2119. r = strlen(string);
  2120. }
  2121. if (!bin) {
  2122. statbuf.st_size = (size_t) r;
  2123. } else
  2124. #endif
  2125. if (r != statbuf.st_size) {
  2126. /* Unless we're using text mode on win32, we'd better have an exact
  2127. * match for size. */
  2128. int save_errno = errno;
  2129. log_warn(LD_FS,"Could read only %d of %ld bytes of file \"%s\".",
  2130. (int)r, (long)statbuf.st_size,filename);
  2131. tor_free(string);
  2132. close(fd);
  2133. errno = save_errno;
  2134. return NULL;
  2135. }
  2136. close(fd);
  2137. if (stat_out) {
  2138. memcpy(stat_out, &statbuf, sizeof(struct stat));
  2139. }
  2140. return string;
  2141. }
  2142. #define TOR_ISODIGIT(c) ('0' <= (c) && (c) <= '7')
  2143. /** Given a c-style double-quoted escaped string in <b>s</b>, extract and
  2144. * decode its contents into a newly allocated string. On success, assign this
  2145. * string to *<b>result</b>, assign its length to <b>size_out</b> (if
  2146. * provided), and return a pointer to the position in <b>s</b> immediately
  2147. * after the string. On failure, return NULL.
  2148. */
  2149. static const char *
  2150. unescape_string(const char *s, char **result, size_t *size_out)
  2151. {
  2152. const char *cp;
  2153. char *out;
  2154. if (s[0] != '\"')
  2155. return NULL;
  2156. cp = s+1;
  2157. while (1) {
  2158. switch (*cp) {
  2159. case '\0':
  2160. case '\n':
  2161. return NULL;
  2162. case '\"':
  2163. goto end_of_loop;
  2164. case '\\':
  2165. if (cp[1] == 'x' || cp[1] == 'X') {
  2166. if (!(TOR_ISXDIGIT(cp[2]) && TOR_ISXDIGIT(cp[3])))
  2167. return NULL;
  2168. cp += 4;
  2169. } else if (TOR_ISODIGIT(cp[1])) {
  2170. cp += 2;
  2171. if (TOR_ISODIGIT(*cp)) ++cp;
  2172. if (TOR_ISODIGIT(*cp)) ++cp;
  2173. } else if (cp[1] == 'n' || cp[1] == 'r' || cp[1] == 't' || cp[1] == '"'
  2174. || cp[1] == '\\' || cp[1] == '\'') {
  2175. cp += 2;
  2176. } else {
  2177. return NULL;
  2178. }
  2179. break;
  2180. default:
  2181. ++cp;
  2182. break;
  2183. }
  2184. }
  2185. end_of_loop:
  2186. out = *result = tor_malloc(cp-s + 1);
  2187. cp = s+1;
  2188. while (1) {
  2189. switch (*cp)
  2190. {
  2191. case '\"':
  2192. *out = '\0';
  2193. if (size_out) *size_out = out - *result;
  2194. return cp+1;
  2195. case '\0':
  2196. tor_fragile_assert();
  2197. tor_free(*result);
  2198. return NULL;
  2199. case '\\':
  2200. switch (cp[1])
  2201. {
  2202. case 'n': *out++ = '\n'; cp += 2; break;
  2203. case 'r': *out++ = '\r'; cp += 2; break;
  2204. case 't': *out++ = '\t'; cp += 2; break;
  2205. case 'x': case 'X':
  2206. {
  2207. int x1, x2;
  2208. x1 = hex_decode_digit(cp[2]);
  2209. x2 = hex_decode_digit(cp[3]);
  2210. if (x1 == -1 || x2 == -1) {
  2211. tor_free(*result);
  2212. return NULL;
  2213. }
  2214. *out++ = ((x1<<4) + x2);
  2215. cp += 4;
  2216. }
  2217. break;
  2218. case '0': case '1': case '2': case '3': case '4': case '5':
  2219. case '6': case '7':
  2220. {
  2221. int n = cp[1]-'0';
  2222. cp += 2;
  2223. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2224. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2225. if (n > 255) { tor_free(*result); return NULL; }
  2226. *out++ = (char)n;
  2227. }
  2228. break;
  2229. case '\'':
  2230. case '\"':
  2231. case '\\':
  2232. case '\?':
  2233. *out++ = cp[1];
  2234. cp += 2;
  2235. break;
  2236. default:
  2237. tor_free(*result); return NULL;
  2238. }
  2239. break;
  2240. default:
  2241. *out++ = *cp++;
  2242. }
  2243. }
  2244. }
  2245. /** Given a string containing part of a configuration file or similar format,
  2246. * advance past comments and whitespace and try to parse a single line. If we
  2247. * parse a line successfully, set *<b>key_out</b> to a new string holding the
  2248. * key portion and *<b>value_out</b> to a new string holding the value portion
  2249. * of the line, and return a pointer to the start of the next line. If we run
  2250. * out of data, return a pointer to the end of the string. If we encounter an
  2251. * error, return NULL.
  2252. */
  2253. const char *
  2254. parse_config_line_from_str(const char *line, char **key_out, char **value_out)
  2255. {
  2256. /* I believe the file format here is supposed to be:
  2257. FILE = (EMPTYLINE | LINE)* (EMPTYLASTLINE | LASTLINE)?
  2258. EMPTYLASTLINE = SPACE* | COMMENT
  2259. EMPTYLINE = EMPTYLASTLINE NL
  2260. SPACE = ' ' | '\r' | '\t'
  2261. COMMENT = '#' NOT-NL*
  2262. NOT-NL = Any character except '\n'
  2263. NL = '\n'
  2264. LASTLINE = SPACE* KEY SPACE* VALUES
  2265. LINE = LASTLINE NL
  2266. KEY = KEYCHAR+
  2267. KEYCHAR = Any character except ' ', '\r', '\n', '\t', '#', "\"
  2268. VALUES = QUOTEDVALUE | NORMALVALUE
  2269. QUOTEDVALUE = QUOTE QVCHAR* QUOTE EOLSPACE?
  2270. QUOTE = '"'
  2271. QVCHAR = KEYCHAR | ESC ('n' | 't' | 'r' | '"' | ESC |'\'' | OCTAL | HEX)
  2272. ESC = "\\"
  2273. OCTAL = ODIGIT (ODIGIT ODIGIT?)?
  2274. HEX = ('x' | 'X') HEXDIGIT HEXDIGIT
  2275. ODIGIT = '0' .. '7'
  2276. HEXDIGIT = '0'..'9' | 'a' .. 'f' | 'A' .. 'F'
  2277. EOLSPACE = SPACE* COMMENT?
  2278. NORMALVALUE = (VALCHAR | ESC ESC_IGNORE | CONTINUATION)* EOLSPACE?
  2279. VALCHAR = Any character except ESC, '#', and '\n'
  2280. ESC_IGNORE = Any character except '#' or '\n'
  2281. CONTINUATION = ESC NL ( COMMENT NL )*
  2282. */
  2283. const char *key, *val, *cp;
  2284. int continuation = 0;
  2285. tor_assert(key_out);
  2286. tor_assert(value_out);
  2287. *key_out = *value_out = NULL;
  2288. key = val = NULL;
  2289. /* Skip until the first keyword. */
  2290. while (1) {
  2291. while (TOR_ISSPACE(*line))
  2292. ++line;
  2293. if (*line == '#') {
  2294. while (*line && *line != '\n')
  2295. ++line;
  2296. } else {
  2297. break;
  2298. }
  2299. }
  2300. if (!*line) { /* End of string? */
  2301. *key_out = *value_out = NULL;
  2302. return line;
  2303. }
  2304. /* Skip until the next space or \ followed by newline. */
  2305. key = line;
  2306. while (*line && !TOR_ISSPACE(*line) && *line != '#' &&
  2307. ! (line[0] == '\\' && line[1] == '\n'))
  2308. ++line;
  2309. *key_out = tor_strndup(key, line-key);
  2310. /* Skip until the value. */
  2311. while (*line == ' ' || *line == '\t')
  2312. ++line;
  2313. val = line;
  2314. /* Find the end of the line. */
  2315. if (*line == '\"') { // XXX No continuation handling is done here
  2316. if (!(line = unescape_string(line, value_out, NULL)))
  2317. return NULL;
  2318. while (*line == ' ' || *line == '\t')
  2319. ++line;
  2320. if (*line && *line != '#' && *line != '\n')
  2321. return NULL;
  2322. } else {
  2323. /* Look for the end of the line. */
  2324. while (*line && *line != '\n' && (*line != '#' || continuation)) {
  2325. if (*line == '\\' && line[1] == '\n') {
  2326. continuation = 1;
  2327. line += 2;
  2328. } else if (*line == '#') {
  2329. do {
  2330. ++line;
  2331. } while (*line && *line != '\n');
  2332. if (*line == '\n')
  2333. ++line;
  2334. } else {
  2335. ++line;
  2336. }
  2337. }
  2338. if (*line == '\n') {
  2339. cp = line++;
  2340. } else {
  2341. cp = line;
  2342. }
  2343. /* Now back cp up to be the last nonspace character */
  2344. while (cp>val && TOR_ISSPACE(*(cp-1)))
  2345. --cp;
  2346. tor_assert(cp >= val);
  2347. /* Now copy out and decode the value. */
  2348. *value_out = tor_strndup(val, cp-val);
  2349. if (continuation) {
  2350. char *v_out, *v_in;
  2351. v_out = v_in = *value_out;
  2352. while (*v_in) {
  2353. if (*v_in == '#') {
  2354. do {
  2355. ++v_in;
  2356. } while (*v_in && *v_in != '\n');
  2357. if (*v_in == '\n')
  2358. ++v_in;
  2359. } else if (v_in[0] == '\\' && v_in[1] == '\n') {
  2360. v_in += 2;
  2361. } else {
  2362. *v_out++ = *v_in++;
  2363. }
  2364. }
  2365. *v_out = '\0';
  2366. }
  2367. }
  2368. if (*line == '#') {
  2369. do {
  2370. ++line;
  2371. } while (*line && *line != '\n');
  2372. }
  2373. while (TOR_ISSPACE(*line)) ++line;
  2374. return line;
  2375. }
  2376. /** Expand any homedir prefix on <b>filename</b>; return a newly allocated
  2377. * string. */
  2378. char *
  2379. expand_filename(const char *filename)
  2380. {
  2381. tor_assert(filename);
  2382. #ifdef _WIN32
  2383. return tor_strdup(filename);
  2384. #else
  2385. if (*filename == '~') {
  2386. char *home, *result=NULL;
  2387. const char *rest;
  2388. if (filename[1] == '/' || filename[1] == '\0') {
  2389. home = getenv("HOME");
  2390. if (!home) {
  2391. log_warn(LD_CONFIG, "Couldn't find $HOME environment variable while "
  2392. "expanding \"%s\"; defaulting to \"\".", filename);
  2393. home = tor_strdup("");
  2394. } else {
  2395. home = tor_strdup(home);
  2396. }
  2397. rest = strlen(filename)>=2?(filename+2):"";
  2398. } else {
  2399. #ifdef HAVE_PWD_H
  2400. char *username, *slash;
  2401. slash = strchr(filename, '/');
  2402. if (slash)
  2403. username = tor_strndup(filename+1,slash-filename-1);
  2404. else
  2405. username = tor_strdup(filename+1);
  2406. if (!(home = get_user_homedir(username))) {
  2407. log_warn(LD_CONFIG,"Couldn't get homedir for \"%s\"",username);
  2408. tor_free(username);
  2409. return NULL;
  2410. }
  2411. tor_free(username);
  2412. rest = slash ? (slash+1) : "";
  2413. #else
  2414. log_warn(LD_CONFIG, "Couldn't expend homedir on system without pwd.h");
  2415. return tor_strdup(filename);
  2416. #endif
  2417. }
  2418. tor_assert(home);
  2419. /* Remove trailing slash. */
  2420. if (strlen(home)>1 && !strcmpend(home,PATH_SEPARATOR)) {
  2421. home[strlen(home)-1] = '\0';
  2422. }
  2423. tor_asprintf(&result,"%s"PATH_SEPARATOR"%s",home,rest);
  2424. tor_free(home);
  2425. return result;
  2426. } else {
  2427. return tor_strdup(filename);
  2428. }
  2429. #endif
  2430. }
  2431. #define MAX_SCANF_WIDTH 9999
  2432. /** Helper: given an ASCII-encoded decimal digit, return its numeric value.
  2433. * NOTE: requires that its input be in-bounds. */
  2434. static int
  2435. digit_to_num(char d)
  2436. {
  2437. int num = ((int)d) - (int)'0';
  2438. tor_assert(num <= 9 && num >= 0);
  2439. return num;
  2440. }
  2441. /** Helper: Read an unsigned int from *<b>bufp</b> of up to <b>width</b>
  2442. * characters. (Handle arbitrary width if <b>width</b> is less than 0.) On
  2443. * success, store the result in <b>out</b>, advance bufp to the next
  2444. * character, and return 0. On failure, return -1. */
  2445. static int
  2446. scan_unsigned(const char **bufp, unsigned *out, int width, int base)
  2447. {
  2448. unsigned result = 0;
  2449. int scanned_so_far = 0;
  2450. const int hex = base==16;
  2451. tor_assert(base == 10 || base == 16);
  2452. if (!bufp || !*bufp || !out)
  2453. return -1;
  2454. if (width<0)
  2455. width=MAX_SCANF_WIDTH;
  2456. while (**bufp && (hex?TOR_ISXDIGIT(**bufp):TOR_ISDIGIT(**bufp))
  2457. && scanned_so_far < width) {
  2458. int digit = hex?hex_decode_digit(*(*bufp)++):digit_to_num(*(*bufp)++);
  2459. unsigned new_result = result * base + digit;
  2460. if (new_result > UINT32_MAX || new_result < result)
  2461. return -1; /* over/underflow. */
  2462. result = new_result;
  2463. ++scanned_so_far;
  2464. }
  2465. if (!scanned_so_far) /* No actual digits scanned */
  2466. return -1;
  2467. *out = result;
  2468. return 0;
  2469. }
  2470. /** Helper: copy up to <b>width</b> non-space characters from <b>bufp</b> to
  2471. * <b>out</b>. Make sure <b>out</b> is nul-terminated. Advance <b>bufp</b>
  2472. * to the next non-space character or the EOS. */
  2473. static int
  2474. scan_string(const char **bufp, char *out, int width)
  2475. {
  2476. int scanned_so_far = 0;
  2477. if (!bufp || !out || width < 0)
  2478. return -1;
  2479. while (**bufp && ! TOR_ISSPACE(**bufp) && scanned_so_far < width) {
  2480. *out++ = *(*bufp)++;
  2481. ++scanned_so_far;
  2482. }
  2483. *out = '\0';
  2484. return 0;
  2485. }
  2486. /** Locale-independent, minimal, no-surprises scanf variant, accepting only a
  2487. * restricted pattern format. For more info on what it supports, see
  2488. * tor_sscanf() documentation. */
  2489. int
  2490. tor_vsscanf(const char *buf, const char *pattern, va_list ap)
  2491. {
  2492. int n_matched = 0;
  2493. while (*pattern) {
  2494. if (*pattern != '%') {
  2495. if (*buf == *pattern) {
  2496. ++buf;
  2497. ++pattern;
  2498. continue;
  2499. } else {
  2500. return n_matched;
  2501. }
  2502. } else {
  2503. int width = -1;
  2504. ++pattern;
  2505. if (TOR_ISDIGIT(*pattern)) {
  2506. width = digit_to_num(*pattern++);
  2507. while (TOR_ISDIGIT(*pattern)) {
  2508. width *= 10;
  2509. width += digit_to_num(*pattern++);
  2510. if (width > MAX_SCANF_WIDTH)
  2511. return -1;
  2512. }
  2513. if (!width) /* No zero-width things. */
  2514. return -1;
  2515. }
  2516. if (*pattern == 'u' || *pattern == 'x') {
  2517. unsigned *u = va_arg(ap, unsigned *);
  2518. const int base = (*pattern == 'u') ? 10 : 16;
  2519. if (!*buf)
  2520. return n_matched;
  2521. if (scan_unsigned(&buf, u, width, base)<0)
  2522. return n_matched;
  2523. ++pattern;
  2524. ++n_matched;
  2525. } else if (*pattern == 's') {
  2526. char *s = va_arg(ap, char *);
  2527. if (width < 0)
  2528. return -1;
  2529. if (scan_string(&buf, s, width)<0)
  2530. return n_matched;
  2531. ++pattern;
  2532. ++n_matched;
  2533. } else if (*pattern == 'c') {
  2534. char *ch = va_arg(ap, char *);
  2535. if (width != -1)
  2536. return -1;
  2537. if (!*buf)
  2538. return n_matched;
  2539. *ch = *buf++;
  2540. ++pattern;
  2541. ++n_matched;
  2542. } else if (*pattern == '%') {
  2543. if (*buf != '%')
  2544. return -1;
  2545. ++buf;
  2546. ++pattern;
  2547. } else {
  2548. return -1; /* Unrecognized pattern component. */
  2549. }
  2550. }
  2551. }
  2552. return n_matched;
  2553. }
  2554. /** Minimal sscanf replacement: parse <b>buf</b> according to <b>pattern</b>
  2555. * and store the results in the corresponding argument fields. Differs from
  2556. * sscanf in that it: Only handles %u, %x, %c and %Ns. Does not handle
  2557. * arbitrarily long widths. %u and %x do not consume any space. Is
  2558. * locale-independent. Returns -1 on malformed patterns.
  2559. *
  2560. * (As with other locale-independent functions, we need this to parse data that
  2561. * is in ASCII without worrying that the C library's locale-handling will make
  2562. * miscellaneous characters look like numbers, spaces, and so on.)
  2563. */
  2564. int
  2565. tor_sscanf(const char *buf, const char *pattern, ...)
  2566. {
  2567. int r;
  2568. va_list ap;
  2569. va_start(ap, pattern);
  2570. r = tor_vsscanf(buf, pattern, ap);
  2571. va_end(ap);
  2572. return r;
  2573. }
  2574. /** Append the string produced by tor_asprintf(<b>pattern</b>, <b>...</b>)
  2575. * to <b>sl</b>. */
  2576. void
  2577. smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern, ...)
  2578. {
  2579. va_list ap;
  2580. va_start(ap, pattern);
  2581. smartlist_add_vasprintf(sl, pattern, ap);
  2582. va_end(ap);
  2583. }
  2584. /** va_list-based backend of smartlist_add_asprintf. */
  2585. void
  2586. smartlist_add_vasprintf(struct smartlist_t *sl, const char *pattern,
  2587. va_list args)
  2588. {
  2589. char *str = NULL;
  2590. tor_vasprintf(&str, pattern, args);
  2591. tor_assert(str != NULL);
  2592. smartlist_add(sl, str);
  2593. }
  2594. /** Return a new list containing the filenames in the directory <b>dirname</b>.
  2595. * Return NULL on error or if <b>dirname</b> is not a directory.
  2596. */
  2597. smartlist_t *
  2598. tor_listdir(const char *dirname)
  2599. {
  2600. smartlist_t *result;
  2601. #ifdef _WIN32
  2602. char *pattern=NULL;
  2603. TCHAR tpattern[MAX_PATH] = {0};
  2604. char name[MAX_PATH] = {0};
  2605. HANDLE handle;
  2606. WIN32_FIND_DATA findData;
  2607. tor_asprintf(&pattern, "%s\\*", dirname);
  2608. #ifdef UNICODE
  2609. mbstowcs(tpattern,pattern,MAX_PATH);
  2610. #else
  2611. strlcpy(tpattern, pattern, MAX_PATH);
  2612. #endif
  2613. if (INVALID_HANDLE_VALUE == (handle = FindFirstFile(tpattern, &findData))) {
  2614. tor_free(pattern);
  2615. return NULL;
  2616. }
  2617. result = smartlist_new();
  2618. while (1) {
  2619. #ifdef UNICODE
  2620. wcstombs(name,findData.cFileName,MAX_PATH);
  2621. #else
  2622. strlcpy(name,findData.cFileName,sizeof(name));
  2623. #endif
  2624. if (strcmp(name, ".") &&
  2625. strcmp(name, "..")) {
  2626. smartlist_add(result, tor_strdup(name));
  2627. }
  2628. if (!FindNextFile(handle, &findData)) {
  2629. DWORD err;
  2630. if ((err = GetLastError()) != ERROR_NO_MORE_FILES) {
  2631. char *errstr = format_win32_error(err);
  2632. log_warn(LD_FS, "Error reading directory '%s': %s", dirname, errstr);
  2633. tor_free(errstr);
  2634. }
  2635. break;
  2636. }
  2637. }
  2638. FindClose(handle);
  2639. tor_free(pattern);
  2640. #else
  2641. DIR *d;
  2642. struct dirent *de;
  2643. if (!(d = opendir(dirname)))
  2644. return NULL;
  2645. result = smartlist_new();
  2646. while ((de = readdir(d))) {
  2647. if (!strcmp(de->d_name, ".") ||
  2648. !strcmp(de->d_name, ".."))
  2649. continue;
  2650. smartlist_add(result, tor_strdup(de->d_name));
  2651. }
  2652. closedir(d);
  2653. #endif
  2654. return result;
  2655. }
  2656. /** Return true iff <b>filename</b> is a relative path. */
  2657. int
  2658. path_is_relative(const char *filename)
  2659. {
  2660. if (filename && filename[0] == '/')
  2661. return 0;
  2662. #ifdef _WIN32
  2663. else if (filename && filename[0] == '\\')
  2664. return 0;
  2665. else if (filename && strlen(filename)>3 && TOR_ISALPHA(filename[0]) &&
  2666. filename[1] == ':' && filename[2] == '\\')
  2667. return 0;
  2668. #endif
  2669. else
  2670. return 1;
  2671. }
  2672. /* =====
  2673. * Process helpers
  2674. * ===== */
  2675. #ifndef _WIN32
  2676. /* Based on code contributed by christian grothoff */
  2677. /** True iff we've called start_daemon(). */
  2678. static int start_daemon_called = 0;
  2679. /** True iff we've called finish_daemon(). */
  2680. static int finish_daemon_called = 0;
  2681. /** Socketpair used to communicate between parent and child process while
  2682. * daemonizing. */
  2683. static int daemon_filedes[2];
  2684. /** Start putting the process into daemon mode: fork and drop all resources
  2685. * except standard fds. The parent process never returns, but stays around
  2686. * until finish_daemon is called. (Note: it's safe to call this more
  2687. * than once: calls after the first are ignored.)
  2688. */
  2689. void
  2690. start_daemon(void)
  2691. {
  2692. pid_t pid;
  2693. if (start_daemon_called)
  2694. return;
  2695. start_daemon_called = 1;
  2696. if (pipe(daemon_filedes)) {
  2697. log_err(LD_GENERAL,"pipe failed; exiting. Error was %s", strerror(errno));
  2698. exit(1);
  2699. }
  2700. pid = fork();
  2701. if (pid < 0) {
  2702. log_err(LD_GENERAL,"fork failed. Exiting.");
  2703. exit(1);
  2704. }
  2705. if (pid) { /* Parent */
  2706. int ok;
  2707. char c;
  2708. close(daemon_filedes[1]); /* we only read */
  2709. ok = -1;
  2710. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  2711. if (c == '.')
  2712. ok = 1;
  2713. }
  2714. fflush(stdout);
  2715. if (ok == 1)
  2716. exit(0);
  2717. else
  2718. exit(1); /* child reported error */
  2719. } else { /* Child */
  2720. close(daemon_filedes[0]); /* we only write */
  2721. pid = setsid(); /* Detach from controlling terminal */
  2722. /*
  2723. * Fork one more time, so the parent (the session group leader) can exit.
  2724. * This means that we, as a non-session group leader, can never regain a
  2725. * controlling terminal. This part is recommended by Stevens's
  2726. * _Advanced Programming in the Unix Environment_.
  2727. */
  2728. if (fork() != 0) {
  2729. exit(0);
  2730. }
  2731. set_main_thread(); /* We are now the main thread. */
  2732. return;
  2733. }
  2734. }
  2735. /** Finish putting the process into daemon mode: drop standard fds, and tell
  2736. * the parent process to exit. (Note: it's safe to call this more than once:
  2737. * calls after the first are ignored. Calls start_daemon first if it hasn't
  2738. * been called already.)
  2739. */
  2740. void
  2741. finish_daemon(const char *desired_cwd)
  2742. {
  2743. int nullfd;
  2744. char c = '.';
  2745. if (finish_daemon_called)
  2746. return;
  2747. if (!start_daemon_called)
  2748. start_daemon();
  2749. finish_daemon_called = 1;
  2750. if (!desired_cwd)
  2751. desired_cwd = "/";
  2752. /* Don't hold the wrong FS mounted */
  2753. if (chdir(desired_cwd) < 0) {
  2754. log_err(LD_GENERAL,"chdir to \"%s\" failed. Exiting.",desired_cwd);
  2755. exit(1);
  2756. }
  2757. nullfd = tor_open_cloexec("/dev/null", O_RDWR, 0);
  2758. if (nullfd < 0) {
  2759. log_err(LD_GENERAL,"/dev/null can't be opened. Exiting.");
  2760. exit(1);
  2761. }
  2762. /* close fds linking to invoking terminal, but
  2763. * close usual incoming fds, but redirect them somewhere
  2764. * useful so the fds don't get reallocated elsewhere.
  2765. */
  2766. if (dup2(nullfd,0) < 0 ||
  2767. dup2(nullfd,1) < 0 ||
  2768. dup2(nullfd,2) < 0) {
  2769. log_err(LD_GENERAL,"dup2 failed. Exiting.");
  2770. exit(1);
  2771. }
  2772. if (nullfd > 2)
  2773. close(nullfd);
  2774. /* signal success */
  2775. if (write(daemon_filedes[1], &c, sizeof(char)) != sizeof(char)) {
  2776. log_err(LD_GENERAL,"write failed. Exiting.");
  2777. }
  2778. close(daemon_filedes[1]);
  2779. }
  2780. #else
  2781. /* defined(_WIN32) */
  2782. void
  2783. start_daemon(void)
  2784. {
  2785. }
  2786. void
  2787. finish_daemon(const char *cp)
  2788. {
  2789. (void)cp;
  2790. }
  2791. #endif
  2792. /** Write the current process ID, followed by NL, into <b>filename</b>.
  2793. */
  2794. void
  2795. write_pidfile(char *filename)
  2796. {
  2797. FILE *pidfile;
  2798. if ((pidfile = fopen(filename, "w")) == NULL) {
  2799. log_warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
  2800. strerror(errno));
  2801. } else {
  2802. #ifdef _WIN32
  2803. fprintf(pidfile, "%d\n", (int)_getpid());
  2804. #else
  2805. fprintf(pidfile, "%d\n", (int)getpid());
  2806. #endif
  2807. fclose(pidfile);
  2808. }
  2809. }
  2810. #ifdef _WIN32
  2811. HANDLE
  2812. load_windows_system_library(const TCHAR *library_name)
  2813. {
  2814. TCHAR path[MAX_PATH];
  2815. unsigned n;
  2816. n = GetSystemDirectory(path, MAX_PATH);
  2817. if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
  2818. return 0;
  2819. _tcscat(path, TEXT("\\"));
  2820. _tcscat(path, library_name);
  2821. return LoadLibrary(path);
  2822. }
  2823. #endif
  2824. /** Format a single argument for being put on a Windows command line.
  2825. * Returns a newly allocated string */
  2826. static char *
  2827. format_win_cmdline_argument(const char *arg)
  2828. {
  2829. char *formatted_arg;
  2830. char need_quotes;
  2831. const char *c;
  2832. int i;
  2833. int bs_counter = 0;
  2834. /* Backslash we can point to when one is inserted into the string */
  2835. const char backslash = '\\';
  2836. /* Smartlist of *char */
  2837. smartlist_t *arg_chars;
  2838. arg_chars = smartlist_new();
  2839. /* Quote string if it contains whitespace or is empty */
  2840. need_quotes = (strchr(arg, ' ') || strchr(arg, '\t') || '\0' == arg[0]);
  2841. /* Build up smartlist of *chars */
  2842. for (c=arg; *c != '\0'; c++) {
  2843. if ('"' == *c) {
  2844. /* Double up backslashes preceding a quote */
  2845. for (i=0; i<(bs_counter*2); i++)
  2846. smartlist_add(arg_chars, (void*)&backslash);
  2847. bs_counter = 0;
  2848. /* Escape the quote */
  2849. smartlist_add(arg_chars, (void*)&backslash);
  2850. smartlist_add(arg_chars, (void*)c);
  2851. } else if ('\\' == *c) {
  2852. /* Count backslashes until we know whether to double up */
  2853. bs_counter++;
  2854. } else {
  2855. /* Don't double up slashes preceding a non-quote */
  2856. for (i=0; i<bs_counter; i++)
  2857. smartlist_add(arg_chars, (void*)&backslash);
  2858. bs_counter = 0;
  2859. smartlist_add(arg_chars, (void*)c);
  2860. }
  2861. }
  2862. /* Don't double up trailing backslashes */
  2863. for (i=0; i<bs_counter; i++)
  2864. smartlist_add(arg_chars, (void*)&backslash);
  2865. /* Allocate space for argument, quotes (if needed), and terminator */
  2866. formatted_arg = tor_malloc(sizeof(char) *
  2867. (smartlist_len(arg_chars) + (need_quotes?2:0) + 1));
  2868. /* Add leading quote */
  2869. i=0;
  2870. if (need_quotes)
  2871. formatted_arg[i++] = '"';
  2872. /* Add characters */
  2873. SMARTLIST_FOREACH(arg_chars, char*, c,
  2874. {
  2875. formatted_arg[i++] = *c;
  2876. });
  2877. /* Add trailing quote */
  2878. if (need_quotes)
  2879. formatted_arg[i++] = '"';
  2880. formatted_arg[i] = '\0';
  2881. smartlist_free(arg_chars);
  2882. return formatted_arg;
  2883. }
  2884. /** Format a command line for use on Windows, which takes the command as a
  2885. * string rather than string array. Follows the rules from "Parsing C++
  2886. * Command-Line Arguments" in MSDN. Algorithm based on list2cmdline in the
  2887. * Python subprocess module. Returns a newly allocated string */
  2888. char *
  2889. tor_join_win_cmdline(const char *argv[])
  2890. {
  2891. smartlist_t *argv_list;
  2892. char *joined_argv;
  2893. int i;
  2894. /* Format each argument and put the result in a smartlist */
  2895. argv_list = smartlist_new();
  2896. for (i=0; argv[i] != NULL; i++) {
  2897. smartlist_add(argv_list, (void *)format_win_cmdline_argument(argv[i]));
  2898. }
  2899. /* Join the arguments with whitespace */
  2900. joined_argv = smartlist_join_strings(argv_list, " ", 0, NULL);
  2901. /* Free the newly allocated arguments, and the smartlist */
  2902. SMARTLIST_FOREACH(argv_list, char *, arg,
  2903. {
  2904. tor_free(arg);
  2905. });
  2906. smartlist_free(argv_list);
  2907. return joined_argv;
  2908. }
  2909. /** Format <b>child_state</b> and <b>saved_errno</b> as a hex string placed in
  2910. * <b>hex_errno</b>. Called between fork and _exit, so must be signal-handler
  2911. * safe.
  2912. *
  2913. * <b>hex_errno</b> must have at least HEX_ERRNO_SIZE bytes available.
  2914. *
  2915. * The format of <b>hex_errno</b> is: "CHILD_STATE/ERRNO\n", left-padded
  2916. * with spaces. Note that there is no trailing \0. CHILD_STATE indicates where
  2917. * in the processs of starting the child process did the failure occur (see
  2918. * CHILD_STATE_* macros for definition), and SAVED_ERRNO is the value of
  2919. * errno when the failure occurred.
  2920. */
  2921. void
  2922. format_helper_exit_status(unsigned char child_state, int saved_errno,
  2923. char *hex_errno)
  2924. {
  2925. unsigned int unsigned_errno;
  2926. char *cur;
  2927. size_t i;
  2928. /* Fill hex_errno with spaces, and a trailing newline (memset may
  2929. not be signal handler safe, so we can't use it) */
  2930. for (i = 0; i < (HEX_ERRNO_SIZE - 1); i++)
  2931. hex_errno[i] = ' ';
  2932. hex_errno[HEX_ERRNO_SIZE - 1] = '\n';
  2933. /* Convert errno to be unsigned for hex conversion */
  2934. if (saved_errno < 0) {
  2935. unsigned_errno = (unsigned int) -saved_errno;
  2936. } else {
  2937. unsigned_errno = (unsigned int) saved_errno;
  2938. }
  2939. /* Convert errno to hex (start before \n) */
  2940. cur = hex_errno + HEX_ERRNO_SIZE - 2;
  2941. /* Check for overflow on first iteration of the loop */
  2942. if (cur < hex_errno)
  2943. return;
  2944. do {
  2945. *cur-- = "0123456789ABCDEF"[unsigned_errno % 16];
  2946. unsigned_errno /= 16;
  2947. } while (unsigned_errno != 0 && cur >= hex_errno);
  2948. /* Prepend the minus sign if errno was negative */
  2949. if (saved_errno < 0 && cur >= hex_errno)
  2950. *cur-- = '-';
  2951. /* Leave a gap */
  2952. if (cur >= hex_errno)
  2953. *cur-- = '/';
  2954. /* Check for overflow on first iteration of the loop */
  2955. if (cur < hex_errno)
  2956. return;
  2957. /* Convert child_state to hex */
  2958. do {
  2959. *cur-- = "0123456789ABCDEF"[child_state % 16];
  2960. child_state /= 16;
  2961. } while (child_state != 0 && cur >= hex_errno);
  2962. }
  2963. /* Maximum number of file descriptors, if we cannot get it via sysconf() */
  2964. #define DEFAULT_MAX_FD 256
  2965. /** Terminate the process of <b>process_handle</b>.
  2966. * Code borrowed from Python's os.kill. */
  2967. int
  2968. tor_terminate_process(process_handle_t *process_handle)
  2969. {
  2970. #ifdef _WIN32
  2971. if (tor_get_exit_code(process_handle, 0, NULL) == PROCESS_EXIT_RUNNING) {
  2972. HANDLE handle;
  2973. /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
  2974. attempt to open and terminate the process. */
  2975. handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE,
  2976. process_handle->pid.dwProcessId);
  2977. if (!handle)
  2978. return -1;
  2979. if (!TerminateProcess(handle, 0))
  2980. return -1;
  2981. else
  2982. return 0;
  2983. }
  2984. #else /* Unix */
  2985. return kill(process_handle->pid, SIGTERM);
  2986. #endif
  2987. return -1;
  2988. }
  2989. /** Return the Process ID of <b>process_handle</b>. */
  2990. int
  2991. tor_process_get_pid(process_handle_t *process_handle)
  2992. {
  2993. #ifdef _WIN32
  2994. return (int) process_handle->pid.dwProcessId;
  2995. #else
  2996. return (int) process_handle->pid;
  2997. #endif
  2998. }
  2999. #ifdef _WIN32
  3000. HANDLE
  3001. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  3002. {
  3003. return process_handle->stdout_pipe;
  3004. }
  3005. #else
  3006. FILE *
  3007. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  3008. {
  3009. return process_handle->stdout_handle;
  3010. }
  3011. #endif
  3012. static process_handle_t *
  3013. process_handle_new(void)
  3014. {
  3015. process_handle_t *out = tor_malloc_zero(sizeof(process_handle_t));
  3016. #ifndef _WIN32
  3017. out->stdout_pipe = -1;
  3018. out->stderr_pipe = -1;
  3019. #endif
  3020. return out;
  3021. }
  3022. /*DOCDOC*/
  3023. #define CHILD_STATE_INIT 0
  3024. #define CHILD_STATE_PIPE 1
  3025. #define CHILD_STATE_MAXFD 2
  3026. #define CHILD_STATE_FORK 3
  3027. #define CHILD_STATE_DUPOUT 4
  3028. #define CHILD_STATE_DUPERR 5
  3029. #define CHILD_STATE_REDIRECT 6
  3030. #define CHILD_STATE_CLOSEFD 7
  3031. #define CHILD_STATE_EXEC 8
  3032. #define CHILD_STATE_FAILEXEC 9
  3033. /** Start a program in the background. If <b>filename</b> contains a '/', then
  3034. * it will be treated as an absolute or relative path. Otherwise, on
  3035. * non-Windows systems, the system path will be searched for <b>filename</b>.
  3036. * On Windows, only the current directory will be searched. Here, to search the
  3037. * system path (as well as the application directory, current working
  3038. * directory, and system directories), set filename to NULL.
  3039. *
  3040. * The strings in <b>argv</b> will be passed as the command line arguments of
  3041. * the child program (following convention, argv[0] should normally be the
  3042. * filename of the executable, and this must be the case if <b>filename</b> is
  3043. * NULL). The last element of argv must be NULL. A handle to the child process
  3044. * will be returned in process_handle (which must be non-NULL). Read
  3045. * process_handle.status to find out if the process was successfully launched.
  3046. * For convenience, process_handle.status is returned by this function.
  3047. *
  3048. * Some parts of this code are based on the POSIX subprocess module from
  3049. * Python, and example code from
  3050. * http://msdn.microsoft.com/en-us/library/ms682499%28v=vs.85%29.aspx.
  3051. */
  3052. int
  3053. tor_spawn_background(const char *const filename, const char **argv,
  3054. process_environment_t *env,
  3055. process_handle_t **process_handle_out)
  3056. {
  3057. #ifdef _WIN32
  3058. HANDLE stdout_pipe_read = NULL;
  3059. HANDLE stdout_pipe_write = NULL;
  3060. HANDLE stderr_pipe_read = NULL;
  3061. HANDLE stderr_pipe_write = NULL;
  3062. process_handle_t *process_handle;
  3063. int status;
  3064. STARTUPINFO siStartInfo;
  3065. BOOL retval = FALSE;
  3066. SECURITY_ATTRIBUTES saAttr;
  3067. char *joined_argv;
  3068. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  3069. saAttr.bInheritHandle = TRUE;
  3070. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  3071. saAttr.lpSecurityDescriptor = NULL;
  3072. /* Assume failure to start process */
  3073. status = PROCESS_STATUS_ERROR;
  3074. /* Set up pipe for stdout */
  3075. if (!CreatePipe(&stdout_pipe_read, &stdout_pipe_write, &saAttr, 0)) {
  3076. log_warn(LD_GENERAL,
  3077. "Failed to create pipe for stdout communication with child process: %s",
  3078. format_win32_error(GetLastError()));
  3079. return status;
  3080. }
  3081. if (!SetHandleInformation(stdout_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  3082. log_warn(LD_GENERAL,
  3083. "Failed to configure pipe for stdout communication with child "
  3084. "process: %s", format_win32_error(GetLastError()));
  3085. return status;
  3086. }
  3087. /* Set up pipe for stderr */
  3088. if (!CreatePipe(&stderr_pipe_read, &stderr_pipe_write, &saAttr, 0)) {
  3089. log_warn(LD_GENERAL,
  3090. "Failed to create pipe for stderr communication with child process: %s",
  3091. format_win32_error(GetLastError()));
  3092. return status;
  3093. }
  3094. if (!SetHandleInformation(stderr_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  3095. log_warn(LD_GENERAL,
  3096. "Failed to configure pipe for stderr communication with child "
  3097. "process: %s", format_win32_error(GetLastError()));
  3098. return status;
  3099. }
  3100. /* Create the child process */
  3101. /* Windows expects argv to be a whitespace delimited string, so join argv up
  3102. */
  3103. joined_argv = tor_join_win_cmdline(argv);
  3104. process_handle = process_handle_new();
  3105. process_handle->status = status;
  3106. ZeroMemory(&(process_handle->pid), sizeof(PROCESS_INFORMATION));
  3107. ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
  3108. siStartInfo.cb = sizeof(STARTUPINFO);
  3109. siStartInfo.hStdError = stderr_pipe_write;
  3110. siStartInfo.hStdOutput = stdout_pipe_write;
  3111. siStartInfo.hStdInput = NULL;
  3112. siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
  3113. /* Create the child process */
  3114. retval = CreateProcess(filename, // module name
  3115. joined_argv, // command line
  3116. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  3117. NULL, // process security attributes
  3118. NULL, // primary thread security attributes
  3119. TRUE, // handles are inherited
  3120. /*(TODO: set CREATE_NEW CONSOLE/PROCESS_GROUP to make GetExitCodeProcess()
  3121. * work?) */
  3122. 0, // creation flags
  3123. (env==NULL) ? NULL : env->windows_environment_block,
  3124. NULL, // use parent's current directory
  3125. &siStartInfo, // STARTUPINFO pointer
  3126. &(process_handle->pid)); // receives PROCESS_INFORMATION
  3127. tor_free(joined_argv);
  3128. if (!retval) {
  3129. log_warn(LD_GENERAL,
  3130. "Failed to create child process %s: %s", filename?filename:argv[0],
  3131. format_win32_error(GetLastError()));
  3132. tor_free(process_handle);
  3133. } else {
  3134. /* TODO: Close hProcess and hThread in process_handle->pid? */
  3135. process_handle->stdout_pipe = stdout_pipe_read;
  3136. process_handle->stderr_pipe = stderr_pipe_read;
  3137. status = process_handle->status = PROCESS_STATUS_RUNNING;
  3138. }
  3139. /* TODO: Close pipes on exit */
  3140. *process_handle_out = process_handle;
  3141. return status;
  3142. #else // _WIN32
  3143. pid_t pid;
  3144. int stdout_pipe[2];
  3145. int stderr_pipe[2];
  3146. int fd, retval;
  3147. ssize_t nbytes;
  3148. process_handle_t *process_handle;
  3149. int status;
  3150. const char *error_message = SPAWN_ERROR_MESSAGE;
  3151. size_t error_message_length;
  3152. /* Represents where in the process of spawning the program is;
  3153. this is used for printing out the error message */
  3154. unsigned char child_state = CHILD_STATE_INIT;
  3155. char hex_errno[HEX_ERRNO_SIZE];
  3156. static int max_fd = -1;
  3157. status = PROCESS_STATUS_ERROR;
  3158. /* We do the strlen here because strlen() is not signal handler safe,
  3159. and we are not allowed to use unsafe functions between fork and exec */
  3160. error_message_length = strlen(error_message);
  3161. child_state = CHILD_STATE_PIPE;
  3162. /* Set up pipe for redirecting stdout and stderr of child */
  3163. retval = pipe(stdout_pipe);
  3164. if (-1 == retval) {
  3165. log_warn(LD_GENERAL,
  3166. "Failed to set up pipe for stdout communication with child process: %s",
  3167. strerror(errno));
  3168. return status;
  3169. }
  3170. retval = pipe(stderr_pipe);
  3171. if (-1 == retval) {
  3172. log_warn(LD_GENERAL,
  3173. "Failed to set up pipe for stderr communication with child process: %s",
  3174. strerror(errno));
  3175. close(stdout_pipe[0]);
  3176. close(stdout_pipe[1]);
  3177. return status;
  3178. }
  3179. child_state = CHILD_STATE_MAXFD;
  3180. #ifdef _SC_OPEN_MAX
  3181. if (-1 != max_fd) {
  3182. max_fd = (int) sysconf(_SC_OPEN_MAX);
  3183. if (max_fd == -1)
  3184. max_fd = DEFAULT_MAX_FD;
  3185. log_warn(LD_GENERAL,
  3186. "Cannot find maximum file descriptor, assuming %d", max_fd);
  3187. }
  3188. #else
  3189. max_fd = DEFAULT_MAX_FD;
  3190. #endif
  3191. child_state = CHILD_STATE_FORK;
  3192. pid = fork();
  3193. if (0 == pid) {
  3194. /* In child */
  3195. child_state = CHILD_STATE_DUPOUT;
  3196. /* Link child stdout to the write end of the pipe */
  3197. retval = dup2(stdout_pipe[1], STDOUT_FILENO);
  3198. if (-1 == retval)
  3199. goto error;
  3200. child_state = CHILD_STATE_DUPERR;
  3201. /* Link child stderr to the write end of the pipe */
  3202. retval = dup2(stderr_pipe[1], STDERR_FILENO);
  3203. if (-1 == retval)
  3204. goto error;
  3205. child_state = CHILD_STATE_REDIRECT;
  3206. /* Link stdin to /dev/null */
  3207. fd = open("/dev/null", O_RDONLY); /* NOT cloexec, obviously. */
  3208. if (fd != -1)
  3209. dup2(fd, STDIN_FILENO);
  3210. else
  3211. goto error;
  3212. child_state = CHILD_STATE_CLOSEFD;
  3213. close(stderr_pipe[0]);
  3214. close(stderr_pipe[1]);
  3215. close(stdout_pipe[0]);
  3216. close(stdout_pipe[1]);
  3217. close(fd);
  3218. /* Close all other fds, including the read end of the pipe */
  3219. /* XXX: We should now be doing enough FD_CLOEXEC setting to make
  3220. * this needless. */
  3221. for (fd = STDERR_FILENO + 1; fd < max_fd; fd++) {
  3222. close(fd);
  3223. }
  3224. child_state = CHILD_STATE_EXEC;
  3225. /* Call the requested program. We need the cast because
  3226. execvp doesn't define argv as const, even though it
  3227. does not modify the arguments */
  3228. if (env)
  3229. execve(filename, (char *const *) argv, env->unixoid_environment_block);
  3230. else
  3231. execvp(filename, (char *const *) argv);
  3232. /* If we got here, the exec or open(/dev/null) failed */
  3233. child_state = CHILD_STATE_FAILEXEC;
  3234. error:
  3235. /* XXX: are we leaking fds from the pipe? */
  3236. format_helper_exit_status(child_state, errno, hex_errno);
  3237. /* Write the error message. GCC requires that we check the return
  3238. value, but there is nothing we can do if it fails */
  3239. /* TODO: Don't use STDOUT, use a pipe set up just for this purpose */
  3240. nbytes = write(STDOUT_FILENO, error_message, error_message_length);
  3241. nbytes = write(STDOUT_FILENO, hex_errno, sizeof(hex_errno));
  3242. (void) nbytes;
  3243. _exit(255);
  3244. /* Never reached, but avoids compiler warning */
  3245. return status;
  3246. }
  3247. /* In parent */
  3248. if (-1 == pid) {
  3249. log_warn(LD_GENERAL, "Failed to fork child process: %s", strerror(errno));
  3250. close(stdout_pipe[0]);
  3251. close(stdout_pipe[1]);
  3252. close(stderr_pipe[0]);
  3253. close(stderr_pipe[1]);
  3254. return status;
  3255. }
  3256. process_handle = process_handle_new();
  3257. process_handle->status = status;
  3258. process_handle->pid = pid;
  3259. /* TODO: If the child process forked but failed to exec, waitpid it */
  3260. /* Return read end of the pipes to caller, and close write end */
  3261. process_handle->stdout_pipe = stdout_pipe[0];
  3262. retval = close(stdout_pipe[1]);
  3263. if (-1 == retval) {
  3264. log_warn(LD_GENERAL,
  3265. "Failed to close write end of stdout pipe in parent process: %s",
  3266. strerror(errno));
  3267. }
  3268. process_handle->stderr_pipe = stderr_pipe[0];
  3269. retval = close(stderr_pipe[1]);
  3270. if (-1 == retval) {
  3271. log_warn(LD_GENERAL,
  3272. "Failed to close write end of stderr pipe in parent process: %s",
  3273. strerror(errno));
  3274. }
  3275. status = process_handle->status = PROCESS_STATUS_RUNNING;
  3276. /* Set stdout/stderr pipes to be non-blocking */
  3277. fcntl(process_handle->stdout_pipe, F_SETFL, O_NONBLOCK);
  3278. fcntl(process_handle->stderr_pipe, F_SETFL, O_NONBLOCK);
  3279. /* Open the buffered IO streams */
  3280. process_handle->stdout_handle = fdopen(process_handle->stdout_pipe, "r");
  3281. process_handle->stderr_handle = fdopen(process_handle->stderr_pipe, "r");
  3282. *process_handle_out = process_handle;
  3283. return process_handle->status;
  3284. #endif // _WIN32
  3285. }
  3286. /** Destroy all resources allocated by the process handle in
  3287. * <b>process_handle</b>.
  3288. * If <b>also_terminate_process</b> is true, also terminate the
  3289. * process of the process handle. */
  3290. void
  3291. tor_process_handle_destroy(process_handle_t *process_handle,
  3292. int also_terminate_process)
  3293. {
  3294. if (!process_handle)
  3295. return;
  3296. if (also_terminate_process) {
  3297. if (tor_terminate_process(process_handle) < 0) {
  3298. log_notice(LD_GENERAL, "Failed to terminate process with PID '%d'",
  3299. tor_process_get_pid(process_handle));
  3300. } else {
  3301. log_info(LD_GENERAL, "Terminated process with PID '%d'",
  3302. tor_process_get_pid(process_handle));
  3303. }
  3304. }
  3305. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  3306. #ifdef _WIN32
  3307. if (process_handle->stdout_pipe)
  3308. CloseHandle(process_handle->stdout_pipe);
  3309. if (process_handle->stderr_pipe)
  3310. CloseHandle(process_handle->stderr_pipe);
  3311. #else
  3312. if (process_handle->stdout_handle)
  3313. fclose(process_handle->stdout_handle);
  3314. if (process_handle->stderr_handle)
  3315. fclose(process_handle->stderr_handle);
  3316. #endif
  3317. memset(process_handle, 0x0f, sizeof(process_handle_t));
  3318. tor_free(process_handle);
  3319. }
  3320. /** Get the exit code of a process specified by <b>process_handle</b> and store
  3321. * it in <b>exit_code</b>, if set to a non-NULL value. If <b>block</b> is set
  3322. * to true, the call will block until the process has exited. Otherwise if
  3323. * the process is still running, the function will return
  3324. * PROCESS_EXIT_RUNNING, and exit_code will be left unchanged. Returns
  3325. * PROCESS_EXIT_EXITED if the process did exit. If there is a failure,
  3326. * PROCESS_EXIT_ERROR will be returned and the contents of exit_code (if
  3327. * non-NULL) will be undefined. N.B. Under *nix operating systems, this will
  3328. * probably not work in Tor, because waitpid() is called in main.c to reap any
  3329. * terminated child processes.*/
  3330. int
  3331. tor_get_exit_code(const process_handle_t *process_handle,
  3332. int block, int *exit_code)
  3333. {
  3334. #ifdef _WIN32
  3335. DWORD retval;
  3336. BOOL success;
  3337. if (block) {
  3338. /* Wait for the process to exit */
  3339. retval = WaitForSingleObject(process_handle->pid.hProcess, INFINITE);
  3340. if (retval != WAIT_OBJECT_0) {
  3341. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  3342. (int)retval, format_win32_error(GetLastError()));
  3343. return PROCESS_EXIT_ERROR;
  3344. }
  3345. } else {
  3346. retval = WaitForSingleObject(process_handle->pid.hProcess, 0);
  3347. if (WAIT_TIMEOUT == retval) {
  3348. /* Process has not exited */
  3349. return PROCESS_EXIT_RUNNING;
  3350. } else if (retval != WAIT_OBJECT_0) {
  3351. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  3352. (int)retval, format_win32_error(GetLastError()));
  3353. return PROCESS_EXIT_ERROR;
  3354. }
  3355. }
  3356. if (exit_code != NULL) {
  3357. success = GetExitCodeProcess(process_handle->pid.hProcess,
  3358. (PDWORD)exit_code);
  3359. if (!success) {
  3360. log_warn(LD_GENERAL, "GetExitCodeProcess() failed: %s",
  3361. format_win32_error(GetLastError()));
  3362. return PROCESS_EXIT_ERROR;
  3363. }
  3364. }
  3365. #else
  3366. int stat_loc;
  3367. int retval;
  3368. retval = waitpid(process_handle->pid, &stat_loc, block?0:WNOHANG);
  3369. if (!block && 0 == retval) {
  3370. /* Process has not exited */
  3371. return PROCESS_EXIT_RUNNING;
  3372. } else if (retval != process_handle->pid) {
  3373. log_warn(LD_GENERAL, "waitpid() failed for PID %d: %s",
  3374. process_handle->pid, strerror(errno));
  3375. return PROCESS_EXIT_ERROR;
  3376. }
  3377. if (!WIFEXITED(stat_loc)) {
  3378. log_warn(LD_GENERAL, "Process %d did not exit normally",
  3379. process_handle->pid);
  3380. return PROCESS_EXIT_ERROR;
  3381. }
  3382. if (exit_code != NULL)
  3383. *exit_code = WEXITSTATUS(stat_loc);
  3384. #endif // _WIN32
  3385. return PROCESS_EXIT_EXITED;
  3386. }
  3387. /** Return non-zero iff getenv would consider <b>s1</b> and <b>s2</b>
  3388. * to have the same name as strings in a process's environment. */
  3389. int
  3390. environment_variable_names_equal(const char *s1, const char *s2)
  3391. {
  3392. size_t s1_name_len = strcspn(s1, "=");
  3393. size_t s2_name_len = strcspn(s2, "=");
  3394. return (s1_name_len == s2_name_len &&
  3395. tor_memeq(s1, s2, s1_name_len));
  3396. }
  3397. /** Free <b>env</b> (assuming it was produced by
  3398. * process_environment_make). */
  3399. void
  3400. process_environment_free(process_environment_t *env)
  3401. {
  3402. if (env == NULL) return;
  3403. /* As both an optimization hack to reduce consing on Unixoid systems
  3404. * and a nice way to ensure that some otherwise-Windows-specific
  3405. * code will always get tested before changes to it get merged, the
  3406. * strings which env->unixoid_environment_block points to are packed
  3407. * into env->windows_environment_block. */
  3408. tor_free(env->unixoid_environment_block);
  3409. tor_free(env->windows_environment_block);
  3410. tor_free(env);
  3411. }
  3412. /** Make a process_environment_t containing the environment variables
  3413. * specified in <b>env_vars</b> (as C strings of the form
  3414. * "NAME=VALUE"). */
  3415. process_environment_t *
  3416. process_environment_make(struct smartlist_t *env_vars)
  3417. {
  3418. process_environment_t *env = tor_malloc_zero(sizeof(process_environment_t));
  3419. size_t n_env_vars = smartlist_len(env_vars);
  3420. size_t i;
  3421. size_t total_env_length;
  3422. smartlist_t *env_vars_sorted;
  3423. tor_assert(n_env_vars + 1 != 0);
  3424. env->unixoid_environment_block = tor_calloc(n_env_vars + 1, sizeof(char *));
  3425. /* env->unixoid_environment_block is already NULL-terminated,
  3426. * because we assume that NULL == 0 (and check that during compilation). */
  3427. total_env_length = 1; /* terminating NUL of terminating empty string */
  3428. for (i = 0; i < n_env_vars; ++i) {
  3429. const char *s = smartlist_get(env_vars, i);
  3430. size_t slen = strlen(s);
  3431. tor_assert(slen + 1 != 0);
  3432. tor_assert(slen + 1 < SIZE_MAX - total_env_length);
  3433. total_env_length += slen + 1;
  3434. }
  3435. env->windows_environment_block = tor_malloc_zero(total_env_length);
  3436. /* env->windows_environment_block is already
  3437. * (NUL-terminated-empty-string)-terminated. */
  3438. /* Some versions of Windows supposedly require that environment
  3439. * blocks be sorted. Or maybe some Windows programs (or their
  3440. * runtime libraries) fail to look up strings in non-sorted
  3441. * environment blocks.
  3442. *
  3443. * Also, sorting strings makes it easy to find duplicate environment
  3444. * variables and environment-variable strings without an '=' on all
  3445. * OSes, and they can cause badness. Let's complain about those. */
  3446. env_vars_sorted = smartlist_new();
  3447. smartlist_add_all(env_vars_sorted, env_vars);
  3448. smartlist_sort_strings(env_vars_sorted);
  3449. /* Now copy the strings into the environment blocks. */
  3450. {
  3451. char *cp = env->windows_environment_block;
  3452. const char *prev_env_var = NULL;
  3453. for (i = 0; i < n_env_vars; ++i) {
  3454. const char *s = smartlist_get(env_vars_sorted, i);
  3455. size_t slen = strlen(s);
  3456. size_t s_name_len = strcspn(s, "=");
  3457. if (s_name_len == slen) {
  3458. log_warn(LD_GENERAL,
  3459. "Preparing an environment containing a variable "
  3460. "without a value: %s",
  3461. s);
  3462. }
  3463. if (prev_env_var != NULL &&
  3464. environment_variable_names_equal(s, prev_env_var)) {
  3465. log_warn(LD_GENERAL,
  3466. "Preparing an environment containing two variables "
  3467. "with the same name: %s and %s",
  3468. prev_env_var, s);
  3469. }
  3470. prev_env_var = s;
  3471. /* Actually copy the string into the environment. */
  3472. memcpy(cp, s, slen+1);
  3473. env->unixoid_environment_block[i] = cp;
  3474. cp += slen+1;
  3475. }
  3476. tor_assert(cp == env->windows_environment_block + total_env_length - 1);
  3477. }
  3478. smartlist_free(env_vars_sorted);
  3479. return env;
  3480. }
  3481. /** Return a newly allocated smartlist containing every variable in
  3482. * this process's environment, as a NUL-terminated string of the form
  3483. * "NAME=VALUE". Note that on some/many/most/all OSes, the parent
  3484. * process can put strings not of that form in our environment;
  3485. * callers should try to not get crashed by that.
  3486. *
  3487. * The returned strings are heap-allocated, and must be freed by the
  3488. * caller. */
  3489. struct smartlist_t *
  3490. get_current_process_environment_variables(void)
  3491. {
  3492. smartlist_t *sl = smartlist_new();
  3493. char **environ_tmp; /* Not const char ** ? Really? */
  3494. for (environ_tmp = get_environment(); *environ_tmp; ++environ_tmp) {
  3495. smartlist_add(sl, tor_strdup(*environ_tmp));
  3496. }
  3497. return sl;
  3498. }
  3499. /** For each string s in <b>env_vars</b> such that
  3500. * environment_variable_names_equal(s, <b>new_var</b>), remove it; if
  3501. * <b>free_p</b> is non-zero, call <b>free_old</b>(s). If
  3502. * <b>new_var</b> contains '=', insert it into <b>env_vars</b>. */
  3503. void
  3504. set_environment_variable_in_smartlist(struct smartlist_t *env_vars,
  3505. const char *new_var,
  3506. void (*free_old)(void*),
  3507. int free_p)
  3508. {
  3509. SMARTLIST_FOREACH_BEGIN(env_vars, const char *, s) {
  3510. if (environment_variable_names_equal(s, new_var)) {
  3511. SMARTLIST_DEL_CURRENT(env_vars, s);
  3512. if (free_p) {
  3513. free_old((void *)s);
  3514. }
  3515. }
  3516. } SMARTLIST_FOREACH_END(s);
  3517. if (strchr(new_var, '=') != NULL) {
  3518. smartlist_add(env_vars, (void *)new_var);
  3519. }
  3520. }
  3521. #ifdef _WIN32
  3522. /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
  3523. * <b>hProcess</b> is NULL, the function will return immediately if there is
  3524. * nothing more to read. Otherwise <b>hProcess</b> should be set to the handle
  3525. * to the process owning the <b>h</b>. In this case, the function will exit
  3526. * only once the process has exited, or <b>count</b> bytes are read. Returns
  3527. * the number of bytes read, or -1 on error. */
  3528. ssize_t
  3529. tor_read_all_handle(HANDLE h, char *buf, size_t count,
  3530. const process_handle_t *process)
  3531. {
  3532. size_t numread = 0;
  3533. BOOL retval;
  3534. DWORD byte_count;
  3535. BOOL process_exited = FALSE;
  3536. if (count > SIZE_T_CEILING || count > SSIZE_T_MAX)
  3537. return -1;
  3538. while (numread != count) {
  3539. /* Check if there is anything to read */
  3540. retval = PeekNamedPipe(h, NULL, 0, NULL, &byte_count, NULL);
  3541. if (!retval) {
  3542. log_warn(LD_GENERAL,
  3543. "Failed to peek from handle: %s",
  3544. format_win32_error(GetLastError()));
  3545. return -1;
  3546. } else if (0 == byte_count) {
  3547. /* Nothing available: process exited or it is busy */
  3548. /* Exit if we don't know whether the process is running */
  3549. if (NULL == process)
  3550. break;
  3551. /* The process exited and there's nothing left to read from it */
  3552. if (process_exited)
  3553. break;
  3554. /* If process is not running, check for output one more time in case
  3555. it wrote something after the peek was performed. Otherwise keep on
  3556. waiting for output */
  3557. tor_assert(process != NULL);
  3558. byte_count = WaitForSingleObject(process->pid.hProcess, 0);
  3559. if (WAIT_TIMEOUT != byte_count)
  3560. process_exited = TRUE;
  3561. continue;
  3562. }
  3563. /* There is data to read; read it */
  3564. retval = ReadFile(h, buf+numread, count-numread, &byte_count, NULL);
  3565. tor_assert(byte_count + numread <= count);
  3566. if (!retval) {
  3567. log_warn(LD_GENERAL, "Failed to read from handle: %s",
  3568. format_win32_error(GetLastError()));
  3569. return -1;
  3570. } else if (0 == byte_count) {
  3571. /* End of file */
  3572. break;
  3573. }
  3574. numread += byte_count;
  3575. }
  3576. return (ssize_t)numread;
  3577. }
  3578. #else
  3579. /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
  3580. * <b>process</b> is NULL, the function will return immediately if there is
  3581. * nothing more to read. Otherwise data will be read until end of file, or
  3582. * <b>count</b> bytes are read. Returns the number of bytes read, or -1 on
  3583. * error. Sets <b>eof</b> to true if <b>eof</b> is not NULL and the end of the
  3584. * file has been reached. */
  3585. ssize_t
  3586. tor_read_all_handle(FILE *h, char *buf, size_t count,
  3587. const process_handle_t *process,
  3588. int *eof)
  3589. {
  3590. size_t numread = 0;
  3591. char *retval;
  3592. if (eof)
  3593. *eof = 0;
  3594. if (count > SIZE_T_CEILING || count > SSIZE_T_MAX)
  3595. return -1;
  3596. while (numread != count) {
  3597. /* Use fgets because that is what we use in log_from_pipe() */
  3598. retval = fgets(buf+numread, (int)(count-numread), h);
  3599. if (NULL == retval) {
  3600. if (feof(h)) {
  3601. log_debug(LD_GENERAL, "fgets() reached end of file");
  3602. if (eof)
  3603. *eof = 1;
  3604. break;
  3605. } else {
  3606. if (EAGAIN == errno) {
  3607. if (process)
  3608. continue;
  3609. else
  3610. break;
  3611. } else {
  3612. log_warn(LD_GENERAL, "fgets() from handle failed: %s",
  3613. strerror(errno));
  3614. return -1;
  3615. }
  3616. }
  3617. }
  3618. tor_assert(retval != NULL);
  3619. tor_assert(strlen(retval) + numread <= count);
  3620. numread += strlen(retval);
  3621. }
  3622. log_debug(LD_GENERAL, "fgets() read %d bytes from handle", (int)numread);
  3623. return (ssize_t)numread;
  3624. }
  3625. #endif
  3626. /** Read from stdout of a process until the process exits. */
  3627. ssize_t
  3628. tor_read_all_from_process_stdout(const process_handle_t *process_handle,
  3629. char *buf, size_t count)
  3630. {
  3631. #ifdef _WIN32
  3632. return tor_read_all_handle(process_handle->stdout_pipe, buf, count,
  3633. process_handle);
  3634. #else
  3635. return tor_read_all_handle(process_handle->stdout_handle, buf, count,
  3636. process_handle, NULL);
  3637. #endif
  3638. }
  3639. /** Read from stdout of a process until the process exits. */
  3640. ssize_t
  3641. tor_read_all_from_process_stderr(const process_handle_t *process_handle,
  3642. char *buf, size_t count)
  3643. {
  3644. #ifdef _WIN32
  3645. return tor_read_all_handle(process_handle->stderr_pipe, buf, count,
  3646. process_handle);
  3647. #else
  3648. return tor_read_all_handle(process_handle->stderr_handle, buf, count,
  3649. process_handle, NULL);
  3650. #endif
  3651. }
  3652. /** Split buf into lines, and add to smartlist. The buffer <b>buf</b> will be
  3653. * modified. The resulting smartlist will consist of pointers to buf, so there
  3654. * is no need to free the contents of sl. <b>buf</b> must be a NUL-terminated
  3655. * string. <b>len</b> should be set to the length of the buffer excluding the
  3656. * NUL. Non-printable characters (including NUL) will be replaced with "." */
  3657. int
  3658. tor_split_lines(smartlist_t *sl, char *buf, int len)
  3659. {
  3660. /* Index in buf of the start of the current line */
  3661. int start = 0;
  3662. /* Index in buf of the current character being processed */
  3663. int cur = 0;
  3664. /* Are we currently in a line */
  3665. char in_line = 0;
  3666. /* Loop over string */
  3667. while (cur < len) {
  3668. /* Loop until end of line or end of string */
  3669. for (; cur < len; cur++) {
  3670. if (in_line) {
  3671. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  3672. /* End of line */
  3673. buf[cur] = '\0';
  3674. /* Point cur to the next line */
  3675. cur++;
  3676. /* Line starts at start and ends with a nul */
  3677. break;
  3678. } else {
  3679. if (!TOR_ISPRINT(buf[cur]))
  3680. buf[cur] = '.';
  3681. }
  3682. } else {
  3683. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  3684. /* Skip leading vertical space */
  3685. ;
  3686. } else {
  3687. in_line = 1;
  3688. start = cur;
  3689. if (!TOR_ISPRINT(buf[cur]))
  3690. buf[cur] = '.';
  3691. }
  3692. }
  3693. }
  3694. /* We are at the end of the line or end of string. If in_line is true there
  3695. * is a line which starts at buf+start and ends at a NUL. cur points to
  3696. * the character after the NUL. */
  3697. if (in_line)
  3698. smartlist_add(sl, (void *)(buf+start));
  3699. in_line = 0;
  3700. }
  3701. return smartlist_len(sl);
  3702. }
  3703. #ifdef _WIN32
  3704. /** Read from stream, and send lines to log at the specified log level.
  3705. * Returns -1 if there is a error reading, and 0 otherwise.
  3706. * If the generated stream is flushed more often than on new lines, or
  3707. * a read exceeds 256 bytes, lines will be truncated. This should be fixed,
  3708. * along with the corresponding problem on *nix (see bug #2045).
  3709. */
  3710. static int
  3711. log_from_handle(HANDLE *pipe, int severity)
  3712. {
  3713. char buf[256];
  3714. int pos;
  3715. smartlist_t *lines;
  3716. pos = tor_read_all_handle(pipe, buf, sizeof(buf) - 1, NULL);
  3717. if (pos < 0) {
  3718. /* Error */
  3719. log_warn(LD_GENERAL, "Failed to read data from subprocess");
  3720. return -1;
  3721. }
  3722. if (0 == pos) {
  3723. /* There's nothing to read (process is busy or has exited) */
  3724. log_debug(LD_GENERAL, "Subprocess had nothing to say");
  3725. return 0;
  3726. }
  3727. /* End with a null even if there isn't a \r\n at the end */
  3728. /* TODO: What if this is a partial line? */
  3729. buf[pos] = '\0';
  3730. log_debug(LD_GENERAL, "Subprocess had %d bytes to say", pos);
  3731. /* Split up the buffer */
  3732. lines = smartlist_new();
  3733. tor_split_lines(lines, buf, pos);
  3734. /* Log each line */
  3735. SMARTLIST_FOREACH(lines, char *, line,
  3736. {
  3737. log_fn(severity, LD_GENERAL, "Port forwarding helper says: %s", line);
  3738. });
  3739. smartlist_free(lines);
  3740. return 0;
  3741. }
  3742. #else
  3743. /** Read from stream, and send lines to log at the specified log level.
  3744. * Returns 1 if stream is closed normally, -1 if there is a error reading, and
  3745. * 0 otherwise. Handles lines from tor-fw-helper and
  3746. * tor_spawn_background() specially.
  3747. */
  3748. static int
  3749. log_from_pipe(FILE *stream, int severity, const char *executable,
  3750. int *child_status)
  3751. {
  3752. char buf[256];
  3753. enum stream_status r;
  3754. for (;;) {
  3755. r = get_string_from_pipe(stream, buf, sizeof(buf) - 1);
  3756. if (r == IO_STREAM_CLOSED) {
  3757. return 1;
  3758. } else if (r == IO_STREAM_EAGAIN) {
  3759. return 0;
  3760. } else if (r == IO_STREAM_TERM) {
  3761. return -1;
  3762. }
  3763. tor_assert(r == IO_STREAM_OKAY);
  3764. /* Check if buf starts with SPAWN_ERROR_MESSAGE */
  3765. if (strcmpstart(buf, SPAWN_ERROR_MESSAGE) == 0) {
  3766. /* Parse error message */
  3767. int retval, child_state, saved_errno;
  3768. retval = tor_sscanf(buf, SPAWN_ERROR_MESSAGE "%x/%x",
  3769. &child_state, &saved_errno);
  3770. if (retval == 2) {
  3771. log_warn(LD_GENERAL,
  3772. "Failed to start child process \"%s\" in state %d: %s",
  3773. executable, child_state, strerror(saved_errno));
  3774. if (child_status)
  3775. *child_status = 1;
  3776. } else {
  3777. /* Failed to parse message from child process, log it as a
  3778. warning */
  3779. log_warn(LD_GENERAL,
  3780. "Unexpected message from port forwarding helper \"%s\": %s",
  3781. executable, buf);
  3782. }
  3783. } else {
  3784. log_fn(severity, LD_GENERAL, "Port forwarding helper says: %s", buf);
  3785. }
  3786. }
  3787. /* We should never get here */
  3788. return -1;
  3789. }
  3790. #endif
  3791. /** Reads from <b>stream</b> and stores input in <b>buf_out</b> making
  3792. * sure it's below <b>count</b> bytes.
  3793. * If the string has a trailing newline, we strip it off.
  3794. *
  3795. * This function is specifically created to handle input from managed
  3796. * proxies, according to the pluggable transports spec. Make sure it
  3797. * fits your needs before using it.
  3798. *
  3799. * Returns:
  3800. * IO_STREAM_CLOSED: If the stream is closed.
  3801. * IO_STREAM_EAGAIN: If there is nothing to read and we should check back
  3802. * later.
  3803. * IO_STREAM_TERM: If something is wrong with the stream.
  3804. * IO_STREAM_OKAY: If everything went okay and we got a string
  3805. * in <b>buf_out</b>. */
  3806. enum stream_status
  3807. get_string_from_pipe(FILE *stream, char *buf_out, size_t count)
  3808. {
  3809. char *retval;
  3810. size_t len;
  3811. tor_assert(count <= INT_MAX);
  3812. retval = fgets(buf_out, (int)count, stream);
  3813. if (!retval) {
  3814. if (feof(stream)) {
  3815. /* Program has closed stream (probably it exited) */
  3816. /* TODO: check error */
  3817. return IO_STREAM_CLOSED;
  3818. } else {
  3819. if (EAGAIN == errno) {
  3820. /* Nothing more to read, try again next time */
  3821. return IO_STREAM_EAGAIN;
  3822. } else {
  3823. /* There was a problem, abandon this child process */
  3824. return IO_STREAM_TERM;
  3825. }
  3826. }
  3827. } else {
  3828. len = strlen(buf_out);
  3829. tor_assert(len>0);
  3830. if (buf_out[len - 1] == '\n') {
  3831. /* Remove the trailing newline */
  3832. buf_out[len - 1] = '\0';
  3833. } else {
  3834. /* No newline; check whether we overflowed the buffer */
  3835. if (!feof(stream))
  3836. log_info(LD_GENERAL,
  3837. "Line from stream was truncated: %s", buf_out);
  3838. /* TODO: What to do with this error? */
  3839. }
  3840. return IO_STREAM_OKAY;
  3841. }
  3842. /* We should never get here */
  3843. return IO_STREAM_TERM;
  3844. }
  3845. void
  3846. tor_check_port_forwarding(const char *filename, int dir_port, int or_port,
  3847. time_t now)
  3848. {
  3849. /* When fw-helper succeeds, how long do we wait until running it again */
  3850. #define TIME_TO_EXEC_FWHELPER_SUCCESS 300
  3851. /* When fw-helper failed to start, how long do we wait until running it again
  3852. */
  3853. #define TIME_TO_EXEC_FWHELPER_FAIL 60
  3854. /* Static variables are initialized to zero, so child_handle.status=0
  3855. * which corresponds to it not running on startup */
  3856. static process_handle_t *child_handle=NULL;
  3857. static time_t time_to_run_helper = 0;
  3858. int stdout_status, stderr_status, retval;
  3859. const char *argv[10];
  3860. char s_dirport[6], s_orport[6];
  3861. tor_assert(filename);
  3862. /* Set up command line for tor-fw-helper */
  3863. snprintf(s_dirport, sizeof s_dirport, "%d", dir_port);
  3864. snprintf(s_orport, sizeof s_orport, "%d", or_port);
  3865. /* TODO: Allow different internal and external ports */
  3866. argv[0] = filename;
  3867. argv[1] = "--internal-or-port";
  3868. argv[2] = s_orport;
  3869. argv[3] = "--external-or-port";
  3870. argv[4] = s_orport;
  3871. argv[5] = "--internal-dir-port";
  3872. argv[6] = s_dirport;
  3873. argv[7] = "--external-dir-port";
  3874. argv[8] = s_dirport;
  3875. argv[9] = NULL;
  3876. /* Start the child, if it is not already running */
  3877. if ((!child_handle || child_handle->status != PROCESS_STATUS_RUNNING) &&
  3878. time_to_run_helper < now) {
  3879. int status;
  3880. /* Assume tor-fw-helper will succeed, start it later*/
  3881. time_to_run_helper = now + TIME_TO_EXEC_FWHELPER_SUCCESS;
  3882. if (child_handle) {
  3883. tor_process_handle_destroy(child_handle, 1);
  3884. child_handle = NULL;
  3885. }
  3886. #ifdef _WIN32
  3887. /* Passing NULL as lpApplicationName makes Windows search for the .exe */
  3888. status = tor_spawn_background(NULL, argv, NULL, &child_handle);
  3889. #else
  3890. status = tor_spawn_background(filename, argv, NULL, &child_handle);
  3891. #endif
  3892. if (PROCESS_STATUS_ERROR == status) {
  3893. log_warn(LD_GENERAL, "Failed to start port forwarding helper %s",
  3894. filename);
  3895. time_to_run_helper = now + TIME_TO_EXEC_FWHELPER_FAIL;
  3896. return;
  3897. }
  3898. log_info(LD_GENERAL,
  3899. "Started port forwarding helper (%s) with pid '%d'",
  3900. filename, tor_process_get_pid(child_handle));
  3901. }
  3902. /* If child is running, read from its stdout and stderr) */
  3903. if (child_handle && PROCESS_STATUS_RUNNING == child_handle->status) {
  3904. /* Read from stdout/stderr and log result */
  3905. retval = 0;
  3906. #ifdef _WIN32
  3907. stdout_status = log_from_handle(child_handle->stdout_pipe, LOG_INFO);
  3908. stderr_status = log_from_handle(child_handle->stderr_pipe, LOG_WARN);
  3909. /* If we got this far (on Windows), the process started */
  3910. retval = 0;
  3911. #else
  3912. stdout_status = log_from_pipe(child_handle->stdout_handle,
  3913. LOG_INFO, filename, &retval);
  3914. stderr_status = log_from_pipe(child_handle->stderr_handle,
  3915. LOG_WARN, filename, &retval);
  3916. #endif
  3917. if (retval) {
  3918. /* There was a problem in the child process */
  3919. time_to_run_helper = now + TIME_TO_EXEC_FWHELPER_FAIL;
  3920. }
  3921. /* Combine the two statuses in order of severity */
  3922. if (-1 == stdout_status || -1 == stderr_status)
  3923. /* There was a failure */
  3924. retval = -1;
  3925. #ifdef _WIN32
  3926. else if (!child_handle || tor_get_exit_code(child_handle, 0, NULL) !=
  3927. PROCESS_EXIT_RUNNING) {
  3928. /* process has exited or there was an error */
  3929. /* TODO: Do something with the process return value */
  3930. /* TODO: What if the process output something since
  3931. * between log_from_handle and tor_get_exit_code? */
  3932. retval = 1;
  3933. }
  3934. #else
  3935. else if (1 == stdout_status || 1 == stderr_status)
  3936. /* stdout or stderr was closed, the process probably
  3937. * exited. It will be reaped by waitpid() in main.c */
  3938. /* TODO: Do something with the process return value */
  3939. retval = 1;
  3940. #endif
  3941. else
  3942. /* Both are fine */
  3943. retval = 0;
  3944. /* If either pipe indicates a failure, act on it */
  3945. if (0 != retval) {
  3946. if (1 == retval) {
  3947. log_info(LD_GENERAL, "Port forwarding helper terminated");
  3948. child_handle->status = PROCESS_STATUS_NOTRUNNING;
  3949. } else {
  3950. log_warn(LD_GENERAL, "Failed to read from port forwarding helper");
  3951. child_handle->status = PROCESS_STATUS_ERROR;
  3952. }
  3953. /* TODO: The child might not actually be finished (maybe it failed or
  3954. closed stdout/stderr), so maybe we shouldn't start another? */
  3955. }
  3956. }
  3957. }