util.c 138 KB

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