util.c 140 KB

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