util.c 138 KB

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