util.c 142 KB

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