util.c 136 KB

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