util.c 141 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003
  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 "lib/container/smartlist.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. * Rate limiting
  1612. * ===== */
  1613. /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return the number
  1614. * of calls to rate_limit_is_ready (including this one!) since the last time
  1615. * rate_limit_is_ready returned nonzero. Otherwise return 0.
  1616. * If the call number hits <b>RATELIM_TOOMANY</b> limit, drop a warning
  1617. * about this event and stop counting. */
  1618. static int
  1619. rate_limit_is_ready(ratelim_t *lim, time_t now)
  1620. {
  1621. if (lim->rate + lim->last_allowed <= now) {
  1622. int res = lim->n_calls_since_last_time + 1;
  1623. lim->last_allowed = now;
  1624. lim->n_calls_since_last_time = 0;
  1625. return res;
  1626. } else {
  1627. if (lim->n_calls_since_last_time <= RATELIM_TOOMANY) {
  1628. ++lim->n_calls_since_last_time;
  1629. }
  1630. return 0;
  1631. }
  1632. }
  1633. /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return a newly
  1634. * allocated string indicating how many messages were suppressed, suitable to
  1635. * append to a log message. Otherwise return NULL. */
  1636. char *
  1637. rate_limit_log(ratelim_t *lim, time_t now)
  1638. {
  1639. int n;
  1640. if ((n = rate_limit_is_ready(lim, now))) {
  1641. if (n == 1) {
  1642. return tor_strdup("");
  1643. } else {
  1644. char *cp=NULL;
  1645. const char *opt_over = (n >= RATELIM_TOOMANY) ? "over " : "";
  1646. /* XXXX this is not exactly correct: the messages could have occurred
  1647. * any time between the old value of lim->allowed and now. */
  1648. tor_asprintf(&cp,
  1649. " [%s%d similar message(s) suppressed in last %d seconds]",
  1650. opt_over, n-1, lim->rate);
  1651. return cp;
  1652. }
  1653. } else {
  1654. return NULL;
  1655. }
  1656. }
  1657. /* =====
  1658. * File helpers
  1659. * ===== */
  1660. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  1661. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  1662. * was returned by open(). Return the number of bytes written, or -1
  1663. * on error. Only use if fd is a blocking fd. */
  1664. ssize_t
  1665. write_all(tor_socket_t fd, const char *buf, size_t count, int isSocket)
  1666. {
  1667. size_t written = 0;
  1668. ssize_t result;
  1669. raw_assert(count < SSIZE_MAX);
  1670. while (written != count) {
  1671. if (isSocket)
  1672. result = tor_socket_send(fd, buf+written, count-written, 0);
  1673. else
  1674. result = write((int)fd, buf+written, count-written);
  1675. if (result<0)
  1676. return -1;
  1677. written += result;
  1678. }
  1679. return (ssize_t)count;
  1680. }
  1681. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  1682. * or reach the end of the file. <b>isSocket</b> must be 1 if fd
  1683. * was returned by socket() or accept(), and 0 if fd was returned by
  1684. * open(). Return the number of bytes read, or -1 on error. Only use
  1685. * if fd is a blocking fd. */
  1686. ssize_t
  1687. read_all(tor_socket_t fd, char *buf, size_t count, int isSocket)
  1688. {
  1689. size_t numread = 0;
  1690. ssize_t result;
  1691. if (count > SIZE_T_CEILING || count > SSIZE_MAX) {
  1692. errno = EINVAL;
  1693. return -1;
  1694. }
  1695. while (numread < count) {
  1696. if (isSocket)
  1697. result = tor_socket_recv(fd, buf+numread, count-numread, 0);
  1698. else
  1699. result = read((int)fd, buf+numread, count-numread);
  1700. if (result<0)
  1701. return -1;
  1702. else if (result == 0)
  1703. break;
  1704. numread += result;
  1705. }
  1706. return (ssize_t)numread;
  1707. }
  1708. /*
  1709. * Filesystem operations.
  1710. */
  1711. /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
  1712. * we do nothing. On Windows, we remove a trailing slash, unless the path is
  1713. * the root of a disk. */
  1714. static void
  1715. clean_name_for_stat(char *name)
  1716. {
  1717. #ifdef _WIN32
  1718. size_t len = strlen(name);
  1719. if (!len)
  1720. return;
  1721. if (name[len-1]=='\\' || name[len-1]=='/') {
  1722. if (len == 1 || (len==3 && name[1]==':'))
  1723. return;
  1724. name[len-1]='\0';
  1725. }
  1726. #else /* !(defined(_WIN32)) */
  1727. (void)name;
  1728. #endif /* defined(_WIN32) */
  1729. }
  1730. /** Wrapper for unlink() to make it mockable for the test suite; returns 0
  1731. * if unlinking the file succeeded, -1 and sets errno if unlinking fails.
  1732. */
  1733. MOCK_IMPL(int,
  1734. tor_unlink,(const char *pathname))
  1735. {
  1736. return unlink(pathname);
  1737. }
  1738. /** Return:
  1739. * FN_ERROR if filename can't be read, is NULL, or is zero-length,
  1740. * FN_NOENT if it doesn't exist,
  1741. * FN_FILE if it is a non-empty regular file, or a FIFO on unix-like systems,
  1742. * FN_EMPTY for zero-byte regular files,
  1743. * FN_DIR if it's a directory, and
  1744. * FN_ERROR for any other file type.
  1745. * On FN_ERROR and FN_NOENT, sets errno. (errno is not set when FN_ERROR
  1746. * is returned due to an unhandled file type.) */
  1747. file_status_t
  1748. file_status(const char *fname)
  1749. {
  1750. struct stat st;
  1751. char *f;
  1752. int r;
  1753. if (!fname || strlen(fname) == 0) {
  1754. return FN_ERROR;
  1755. }
  1756. f = tor_strdup(fname);
  1757. clean_name_for_stat(f);
  1758. log_debug(LD_FS, "stat()ing %s", f);
  1759. r = stat(sandbox_intern_string(f), &st);
  1760. tor_free(f);
  1761. if (r) {
  1762. if (errno == ENOENT) {
  1763. return FN_NOENT;
  1764. }
  1765. return FN_ERROR;
  1766. }
  1767. if (st.st_mode & S_IFDIR) {
  1768. return FN_DIR;
  1769. } else if (st.st_mode & S_IFREG) {
  1770. if (st.st_size > 0) {
  1771. return FN_FILE;
  1772. } else if (st.st_size == 0) {
  1773. return FN_EMPTY;
  1774. } else {
  1775. return FN_ERROR;
  1776. }
  1777. #ifndef _WIN32
  1778. } else if (st.st_mode & S_IFIFO) {
  1779. return FN_FILE;
  1780. #endif
  1781. } else {
  1782. return FN_ERROR;
  1783. }
  1784. }
  1785. /** Check whether <b>dirname</b> exists and is private. If yes return 0.
  1786. * If <b>dirname</b> does not exist:
  1787. * - if <b>check</b>&CPD_CREATE, try to create it and return 0 on success.
  1788. * - if <b>check</b>&CPD_CHECK, and we think we can create it, return 0.
  1789. * - if <b>check</b>&CPD_CHECK is false, and the directory exists, return 0.
  1790. * - otherwise, return -1.
  1791. * If CPD_GROUP_OK is set, then it's okay if the directory
  1792. * is group-readable, but in all cases we create the directory mode 0700.
  1793. * If CPD_GROUP_READ is set, existing directory behaves as CPD_GROUP_OK and
  1794. * if the directory is created it will use mode 0750 with group read
  1795. * permission. Group read privileges also assume execute permission
  1796. * as norm for directories. If CPD_CHECK_MODE_ONLY is set, then we don't
  1797. * alter the directory permissions if they are too permissive:
  1798. * we just return -1.
  1799. * When effective_user is not NULL, check permissions against the given user
  1800. * and its primary group.
  1801. */
  1802. MOCK_IMPL(int,
  1803. check_private_dir,(const char *dirname, cpd_check_t check,
  1804. const char *effective_user))
  1805. {
  1806. int r;
  1807. struct stat st;
  1808. tor_assert(dirname);
  1809. #ifndef _WIN32
  1810. int fd;
  1811. const struct passwd *pw = NULL;
  1812. uid_t running_uid;
  1813. gid_t running_gid;
  1814. /*
  1815. * Goal is to harden the implementation by removing any
  1816. * potential for race between stat() and chmod().
  1817. * chmod() accepts filename as argument. If an attacker can move
  1818. * the file between stat() and chmod(), a potential race exists.
  1819. *
  1820. * Several suggestions taken from:
  1821. * https://developer.apple.com/library/mac/documentation/
  1822. * Security/Conceptual/SecureCodingGuide/Articles/RaceConditions.html
  1823. */
  1824. /* Open directory.
  1825. * O_NOFOLLOW to ensure that it does not follow symbolic links */
  1826. fd = open(sandbox_intern_string(dirname), O_NOFOLLOW);
  1827. /* Was there an error? Maybe the directory does not exist? */
  1828. if (fd == -1) {
  1829. if (errno != ENOENT) {
  1830. /* Other directory error */
  1831. log_warn(LD_FS, "Directory %s cannot be read: %s", dirname,
  1832. strerror(errno));
  1833. return -1;
  1834. }
  1835. /* Received ENOENT: Directory does not exist */
  1836. /* Should we create the directory? */
  1837. if (check & CPD_CREATE) {
  1838. log_info(LD_GENERAL, "Creating directory %s", dirname);
  1839. if (check & CPD_GROUP_READ) {
  1840. r = mkdir(dirname, 0750);
  1841. } else {
  1842. r = mkdir(dirname, 0700);
  1843. }
  1844. /* check for mkdir() error */
  1845. if (r) {
  1846. log_warn(LD_FS, "Error creating directory %s: %s", dirname,
  1847. strerror(errno));
  1848. return -1;
  1849. }
  1850. /* we just created the directory. try to open it again.
  1851. * permissions on the directory will be checked again below.*/
  1852. fd = open(sandbox_intern_string(dirname), O_NOFOLLOW);
  1853. if (fd == -1) {
  1854. log_warn(LD_FS, "Could not reopen recently created directory %s: %s",
  1855. dirname,
  1856. strerror(errno));
  1857. return -1;
  1858. } else {
  1859. close(fd);
  1860. }
  1861. } else if (!(check & CPD_CHECK)) {
  1862. log_warn(LD_FS, "Directory %s does not exist.", dirname);
  1863. return -1;
  1864. }
  1865. /* XXXX In the case where check==CPD_CHECK, we should look at the
  1866. * parent directory a little harder. */
  1867. return 0;
  1868. }
  1869. tor_assert(fd >= 0);
  1870. //f = tor_strdup(dirname);
  1871. //clean_name_for_stat(f);
  1872. log_debug(LD_FS, "stat()ing %s", dirname);
  1873. //r = stat(sandbox_intern_string(f), &st);
  1874. r = fstat(fd, &st);
  1875. if (r == -1) {
  1876. log_warn(LD_FS, "fstat() on directory %s failed.", dirname);
  1877. close(fd);
  1878. return -1;
  1879. }
  1880. //tor_free(f);
  1881. /* check that dirname is a directory */
  1882. if (!(st.st_mode & S_IFDIR)) {
  1883. log_warn(LD_FS, "%s is not a directory", dirname);
  1884. close(fd);
  1885. return -1;
  1886. }
  1887. if (effective_user) {
  1888. /* Look up the user and group information.
  1889. * If we have a problem, bail out. */
  1890. pw = tor_getpwnam(effective_user);
  1891. if (pw == NULL) {
  1892. log_warn(LD_CONFIG, "Error setting configured user: %s not found",
  1893. effective_user);
  1894. close(fd);
  1895. return -1;
  1896. }
  1897. running_uid = pw->pw_uid;
  1898. running_gid = pw->pw_gid;
  1899. } else {
  1900. running_uid = getuid();
  1901. running_gid = getgid();
  1902. }
  1903. if (st.st_uid != running_uid) {
  1904. char *process_ownername = NULL, *file_ownername = NULL;
  1905. {
  1906. const struct passwd *pw_running = tor_getpwuid(running_uid);
  1907. process_ownername = pw_running ? tor_strdup(pw_running->pw_name) :
  1908. tor_strdup("<unknown>");
  1909. }
  1910. {
  1911. const struct passwd *pw_stat = tor_getpwuid(st.st_uid);
  1912. file_ownername = pw_stat ? tor_strdup(pw_stat->pw_name) :
  1913. tor_strdup("<unknown>");
  1914. }
  1915. log_warn(LD_FS, "%s is not owned by this user (%s, %d) but by "
  1916. "%s (%d). Perhaps you are running Tor as the wrong user?",
  1917. dirname, process_ownername, (int)running_uid,
  1918. file_ownername, (int)st.st_uid);
  1919. tor_free(process_ownername);
  1920. tor_free(file_ownername);
  1921. close(fd);
  1922. return -1;
  1923. }
  1924. if ( (check & (CPD_GROUP_OK|CPD_GROUP_READ))
  1925. && (st.st_gid != running_gid) && (st.st_gid != 0)) {
  1926. struct group *gr;
  1927. char *process_groupname = NULL;
  1928. gr = getgrgid(running_gid);
  1929. process_groupname = gr ? tor_strdup(gr->gr_name) : tor_strdup("<unknown>");
  1930. gr = getgrgid(st.st_gid);
  1931. log_warn(LD_FS, "%s is not owned by this group (%s, %d) but by group "
  1932. "%s (%d). Are you running Tor as the wrong user?",
  1933. dirname, process_groupname, (int)running_gid,
  1934. gr ? gr->gr_name : "<unknown>", (int)st.st_gid);
  1935. tor_free(process_groupname);
  1936. close(fd);
  1937. return -1;
  1938. }
  1939. unsigned unwanted_bits = 0;
  1940. if (check & (CPD_GROUP_OK|CPD_GROUP_READ)) {
  1941. unwanted_bits = 0027;
  1942. } else {
  1943. unwanted_bits = 0077;
  1944. }
  1945. unsigned check_bits_filter = ~0;
  1946. if (check & CPD_RELAX_DIRMODE_CHECK) {
  1947. check_bits_filter = 0022;
  1948. }
  1949. if ((st.st_mode & unwanted_bits & check_bits_filter) != 0) {
  1950. unsigned new_mode;
  1951. if (check & CPD_CHECK_MODE_ONLY) {
  1952. log_warn(LD_FS, "Permissions on directory %s are too permissive.",
  1953. dirname);
  1954. close(fd);
  1955. return -1;
  1956. }
  1957. log_warn(LD_FS, "Fixing permissions on directory %s", dirname);
  1958. new_mode = st.st_mode;
  1959. new_mode |= 0700; /* Owner should have rwx */
  1960. if (check & CPD_GROUP_READ) {
  1961. new_mode |= 0050; /* Group should have rx */
  1962. }
  1963. new_mode &= ~unwanted_bits; /* Clear the bits that we didn't want set...*/
  1964. if (fchmod(fd, new_mode)) {
  1965. log_warn(LD_FS, "Could not chmod directory %s: %s", dirname,
  1966. strerror(errno));
  1967. close(fd);
  1968. return -1;
  1969. } else {
  1970. close(fd);
  1971. return 0;
  1972. }
  1973. }
  1974. close(fd);
  1975. #else /* !(!defined(_WIN32)) */
  1976. /* Win32 case: we can't open() a directory. */
  1977. (void)effective_user;
  1978. char *f = tor_strdup(dirname);
  1979. clean_name_for_stat(f);
  1980. log_debug(LD_FS, "stat()ing %s", f);
  1981. r = stat(sandbox_intern_string(f), &st);
  1982. tor_free(f);
  1983. if (r) {
  1984. if (errno != ENOENT) {
  1985. log_warn(LD_FS, "Directory %s cannot be read: %s", dirname,
  1986. strerror(errno));
  1987. return -1;
  1988. }
  1989. if (check & CPD_CREATE) {
  1990. log_info(LD_GENERAL, "Creating directory %s", dirname);
  1991. r = mkdir(dirname);
  1992. if (r) {
  1993. log_warn(LD_FS, "Error creating directory %s: %s", dirname,
  1994. strerror(errno));
  1995. return -1;
  1996. }
  1997. } else if (!(check & CPD_CHECK)) {
  1998. log_warn(LD_FS, "Directory %s does not exist.", dirname);
  1999. return -1;
  2000. }
  2001. return 0;
  2002. }
  2003. if (!(st.st_mode & S_IFDIR)) {
  2004. log_warn(LD_FS, "%s is not a directory", dirname);
  2005. return -1;
  2006. }
  2007. #endif /* !defined(_WIN32) */
  2008. return 0;
  2009. }
  2010. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite
  2011. * the previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  2012. *
  2013. * This function replaces the old file atomically, if possible. This
  2014. * function, and all other functions in util.c that create files, create them
  2015. * with mode 0600.
  2016. */
  2017. MOCK_IMPL(int,
  2018. write_str_to_file,(const char *fname, const char *str, int bin))
  2019. {
  2020. #ifdef _WIN32
  2021. if (!bin && strchr(str, '\r')) {
  2022. log_warn(LD_BUG,
  2023. "We're writing a text string that already contains a CR to %s",
  2024. escaped(fname));
  2025. }
  2026. #endif /* defined(_WIN32) */
  2027. return write_bytes_to_file(fname, str, strlen(str), bin);
  2028. }
  2029. /** Represents a file that we're writing to, with support for atomic commit:
  2030. * we can write into a temporary file, and either remove the file on
  2031. * failure, or replace the original file on success. */
  2032. struct open_file_t {
  2033. char *tempname; /**< Name of the temporary file. */
  2034. char *filename; /**< Name of the original file. */
  2035. unsigned rename_on_close:1; /**< Are we using the temporary file or not? */
  2036. unsigned binary:1; /**< Did we open in binary mode? */
  2037. int fd; /**< fd for the open file. */
  2038. FILE *stdio_file; /**< stdio wrapper for <b>fd</b>. */
  2039. };
  2040. /** Try to start writing to the file in <b>fname</b>, passing the flags
  2041. * <b>open_flags</b> to the open() syscall, creating the file (if needed) with
  2042. * access value <b>mode</b>. If the O_APPEND flag is set, we append to the
  2043. * original file. Otherwise, we open a new temporary file in the same
  2044. * directory, and either replace the original or remove the temporary file
  2045. * when we're done.
  2046. *
  2047. * Return the fd for the newly opened file, and store working data in
  2048. * *<b>data_out</b>. The caller should not close the fd manually:
  2049. * instead, call finish_writing_to_file() or abort_writing_to_file().
  2050. * Returns -1 on failure.
  2051. *
  2052. * NOTE: When not appending, the flags O_CREAT and O_TRUNC are treated
  2053. * as true and the flag O_EXCL is treated as false.
  2054. *
  2055. * NOTE: Ordinarily, O_APPEND means "seek to the end of the file before each
  2056. * write()". We don't do that.
  2057. */
  2058. int
  2059. start_writing_to_file(const char *fname, int open_flags, int mode,
  2060. open_file_t **data_out)
  2061. {
  2062. open_file_t *new_file = tor_malloc_zero(sizeof(open_file_t));
  2063. const char *open_name;
  2064. int append = 0;
  2065. tor_assert(fname);
  2066. tor_assert(data_out);
  2067. #if (O_BINARY != 0 && O_TEXT != 0)
  2068. tor_assert((open_flags & (O_BINARY|O_TEXT)) != 0);
  2069. #endif
  2070. new_file->fd = -1;
  2071. new_file->filename = tor_strdup(fname);
  2072. if (open_flags & O_APPEND) {
  2073. open_name = fname;
  2074. new_file->rename_on_close = 0;
  2075. append = 1;
  2076. open_flags &= ~O_APPEND;
  2077. } else {
  2078. tor_asprintf(&new_file->tempname, "%s.tmp", fname);
  2079. open_name = new_file->tempname;
  2080. /* We always replace an existing temporary file if there is one. */
  2081. open_flags |= O_CREAT|O_TRUNC;
  2082. open_flags &= ~O_EXCL;
  2083. new_file->rename_on_close = 1;
  2084. }
  2085. #if O_BINARY != 0
  2086. if (open_flags & O_BINARY)
  2087. new_file->binary = 1;
  2088. #endif
  2089. new_file->fd = tor_open_cloexec(open_name, open_flags, mode);
  2090. if (new_file->fd < 0) {
  2091. log_warn(LD_FS, "Couldn't open \"%s\" (%s) for writing: %s",
  2092. open_name, fname, strerror(errno));
  2093. goto err;
  2094. }
  2095. if (append) {
  2096. if (tor_fd_seekend(new_file->fd) < 0) {
  2097. log_warn(LD_FS, "Couldn't seek to end of file \"%s\": %s", open_name,
  2098. strerror(errno));
  2099. goto err;
  2100. }
  2101. }
  2102. *data_out = new_file;
  2103. return new_file->fd;
  2104. err:
  2105. if (new_file->fd >= 0)
  2106. close(new_file->fd);
  2107. *data_out = NULL;
  2108. tor_free(new_file->filename);
  2109. tor_free(new_file->tempname);
  2110. tor_free(new_file);
  2111. return -1;
  2112. }
  2113. /** Given <b>file_data</b> from start_writing_to_file(), return a stdio FILE*
  2114. * that can be used to write to the same file. The caller should not mix
  2115. * stdio calls with non-stdio calls. */
  2116. FILE *
  2117. fdopen_file(open_file_t *file_data)
  2118. {
  2119. tor_assert(file_data);
  2120. if (file_data->stdio_file)
  2121. return file_data->stdio_file;
  2122. tor_assert(file_data->fd >= 0);
  2123. if (!(file_data->stdio_file = fdopen(file_data->fd,
  2124. file_data->binary?"ab":"a"))) {
  2125. log_warn(LD_FS, "Couldn't fdopen \"%s\" [%d]: %s", file_data->filename,
  2126. file_data->fd, strerror(errno));
  2127. }
  2128. return file_data->stdio_file;
  2129. }
  2130. /** Combines start_writing_to_file with fdopen_file(): arguments are as
  2131. * for start_writing_to_file, but */
  2132. FILE *
  2133. start_writing_to_stdio_file(const char *fname, int open_flags, int mode,
  2134. open_file_t **data_out)
  2135. {
  2136. FILE *res;
  2137. if (start_writing_to_file(fname, open_flags, mode, data_out)<0)
  2138. return NULL;
  2139. if (!(res = fdopen_file(*data_out))) {
  2140. abort_writing_to_file(*data_out);
  2141. *data_out = NULL;
  2142. }
  2143. return res;
  2144. }
  2145. /** Helper function: close and free the underlying file and memory in
  2146. * <b>file_data</b>. If we were writing into a temporary file, then delete
  2147. * that file (if abort_write is true) or replaces the target file with
  2148. * the temporary file (if abort_write is false). */
  2149. static int
  2150. finish_writing_to_file_impl(open_file_t *file_data, int abort_write)
  2151. {
  2152. int r = 0;
  2153. tor_assert(file_data && file_data->filename);
  2154. if (file_data->stdio_file) {
  2155. if (fclose(file_data->stdio_file)) {
  2156. log_warn(LD_FS, "Error closing \"%s\": %s", file_data->filename,
  2157. strerror(errno));
  2158. abort_write = r = -1;
  2159. }
  2160. } else if (file_data->fd >= 0 && close(file_data->fd) < 0) {
  2161. log_warn(LD_FS, "Error flushing \"%s\": %s", file_data->filename,
  2162. strerror(errno));
  2163. abort_write = r = -1;
  2164. }
  2165. if (file_data->rename_on_close) {
  2166. tor_assert(file_data->tempname && file_data->filename);
  2167. if (!abort_write) {
  2168. tor_assert(strcmp(file_data->filename, file_data->tempname));
  2169. if (replace_file(file_data->tempname, file_data->filename)) {
  2170. log_warn(LD_FS, "Error replacing \"%s\": %s", file_data->filename,
  2171. strerror(errno));
  2172. abort_write = r = -1;
  2173. }
  2174. }
  2175. if (abort_write) {
  2176. int res = unlink(file_data->tempname);
  2177. if (res != 0) {
  2178. /* We couldn't unlink and we'll leave a mess behind */
  2179. log_warn(LD_FS, "Failed to unlink %s: %s",
  2180. file_data->tempname, strerror(errno));
  2181. r = -1;
  2182. }
  2183. }
  2184. }
  2185. tor_free(file_data->filename);
  2186. tor_free(file_data->tempname);
  2187. tor_free(file_data);
  2188. return r;
  2189. }
  2190. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  2191. * needed, and if using a temporary file, replace the original file with
  2192. * the temporary file. */
  2193. int
  2194. finish_writing_to_file(open_file_t *file_data)
  2195. {
  2196. return finish_writing_to_file_impl(file_data, 0);
  2197. }
  2198. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  2199. * needed, and if using a temporary file, delete it. */
  2200. int
  2201. abort_writing_to_file(open_file_t *file_data)
  2202. {
  2203. return finish_writing_to_file_impl(file_data, 1);
  2204. }
  2205. /** Helper: given a set of flags as passed to open(2), open the file
  2206. * <b>fname</b> and write all the sized_chunk_t structs in <b>chunks</b> to
  2207. * the file. Do so as atomically as possible e.g. by opening temp files and
  2208. * renaming. */
  2209. static int
  2210. write_chunks_to_file_impl(const char *fname, const smartlist_t *chunks,
  2211. int open_flags)
  2212. {
  2213. open_file_t *file = NULL;
  2214. int fd;
  2215. ssize_t result;
  2216. fd = start_writing_to_file(fname, open_flags, 0600, &file);
  2217. if (fd<0)
  2218. return -1;
  2219. SMARTLIST_FOREACH(chunks, sized_chunk_t *, chunk,
  2220. {
  2221. result = write_all(fd, chunk->bytes, chunk->len, 0);
  2222. if (result < 0) {
  2223. log_warn(LD_FS, "Error writing to \"%s\": %s", fname,
  2224. strerror(errno));
  2225. goto err;
  2226. }
  2227. tor_assert((size_t)result == chunk->len);
  2228. });
  2229. return finish_writing_to_file(file);
  2230. err:
  2231. abort_writing_to_file(file);
  2232. return -1;
  2233. }
  2234. /** Given a smartlist of sized_chunk_t, write them to a file
  2235. * <b>fname</b>, overwriting or creating the file as necessary.
  2236. * If <b>no_tempfile</b> is 0 then the file will be written
  2237. * atomically. */
  2238. int
  2239. write_chunks_to_file(const char *fname, const smartlist_t *chunks, int bin,
  2240. int no_tempfile)
  2241. {
  2242. int flags = OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT);
  2243. if (no_tempfile) {
  2244. /* O_APPEND stops write_chunks_to_file from using tempfiles */
  2245. flags |= O_APPEND;
  2246. }
  2247. return write_chunks_to_file_impl(fname, chunks, flags);
  2248. }
  2249. /** Write <b>len</b> bytes, starting at <b>str</b>, to <b>fname</b>
  2250. using the open() flags passed in <b>flags</b>. */
  2251. static int
  2252. write_bytes_to_file_impl(const char *fname, const char *str, size_t len,
  2253. int flags)
  2254. {
  2255. int r;
  2256. sized_chunk_t c = { str, len };
  2257. smartlist_t *chunks = smartlist_new();
  2258. smartlist_add(chunks, &c);
  2259. r = write_chunks_to_file_impl(fname, chunks, flags);
  2260. smartlist_free(chunks);
  2261. return r;
  2262. }
  2263. /** As write_str_to_file, but does not assume a NUL-terminated
  2264. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  2265. MOCK_IMPL(int,
  2266. write_bytes_to_file,(const char *fname, const char *str, size_t len,
  2267. int bin))
  2268. {
  2269. return write_bytes_to_file_impl(fname, str, len,
  2270. OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT));
  2271. }
  2272. /** As write_bytes_to_file, but if the file already exists, append the bytes
  2273. * to the end of the file instead of overwriting it. */
  2274. int
  2275. append_bytes_to_file(const char *fname, const char *str, size_t len,
  2276. int bin)
  2277. {
  2278. return write_bytes_to_file_impl(fname, str, len,
  2279. OPEN_FLAGS_APPEND|(bin?O_BINARY:O_TEXT));
  2280. }
  2281. /** Like write_str_to_file(), but also return -1 if there was a file
  2282. already residing in <b>fname</b>. */
  2283. int
  2284. write_bytes_to_new_file(const char *fname, const char *str, size_t len,
  2285. int bin)
  2286. {
  2287. return write_bytes_to_file_impl(fname, str, len,
  2288. OPEN_FLAGS_DONT_REPLACE|
  2289. (bin?O_BINARY:O_TEXT));
  2290. }
  2291. /**
  2292. * Read the contents of the open file <b>fd</b> presuming it is a FIFO
  2293. * (or similar) file descriptor for which the size of the file isn't
  2294. * known ahead of time. Return NULL on failure, and a NUL-terminated
  2295. * string on success. On success, set <b>sz_out</b> to the number of
  2296. * bytes read.
  2297. */
  2298. char *
  2299. read_file_to_str_until_eof(int fd, size_t max_bytes_to_read, size_t *sz_out)
  2300. {
  2301. ssize_t r;
  2302. size_t pos = 0;
  2303. char *string = NULL;
  2304. size_t string_max = 0;
  2305. if (max_bytes_to_read+1 >= SIZE_T_CEILING) {
  2306. errno = EINVAL;
  2307. return NULL;
  2308. }
  2309. do {
  2310. /* XXXX This "add 1K" approach is a little goofy; if we care about
  2311. * performance here, we should be doubling. But in practice we shouldn't
  2312. * be using this function on big files anyway. */
  2313. string_max = pos + 1024;
  2314. if (string_max > max_bytes_to_read)
  2315. string_max = max_bytes_to_read + 1;
  2316. string = tor_realloc(string, string_max);
  2317. r = read(fd, string + pos, string_max - pos - 1);
  2318. if (r < 0) {
  2319. int save_errno = errno;
  2320. tor_free(string);
  2321. errno = save_errno;
  2322. return NULL;
  2323. }
  2324. pos += r;
  2325. } while (r > 0 && pos < max_bytes_to_read);
  2326. tor_assert(pos < string_max);
  2327. *sz_out = pos;
  2328. string[pos] = '\0';
  2329. return string;
  2330. }
  2331. /** Read the contents of <b>filename</b> into a newly allocated
  2332. * string; return the string on success or NULL on failure.
  2333. *
  2334. * If <b>stat_out</b> is provided, store the result of stat()ing the
  2335. * file into <b>stat_out</b>.
  2336. *
  2337. * If <b>flags</b> &amp; RFTS_BIN, open the file in binary mode.
  2338. * If <b>flags</b> &amp; RFTS_IGNORE_MISSING, don't warn if the file
  2339. * doesn't exist.
  2340. */
  2341. /*
  2342. * This function <em>may</em> return an erroneous result if the file
  2343. * is modified while it is running, but must not crash or overflow.
  2344. * Right now, the error case occurs when the file length grows between
  2345. * the call to stat and the call to read_all: the resulting string will
  2346. * be truncated.
  2347. */
  2348. MOCK_IMPL(char *,
  2349. read_file_to_str, (const char *filename, int flags, struct stat *stat_out))
  2350. {
  2351. int fd; /* router file */
  2352. struct stat statbuf;
  2353. char *string;
  2354. ssize_t r;
  2355. int bin = flags & RFTS_BIN;
  2356. tor_assert(filename);
  2357. fd = tor_open_cloexec(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  2358. if (fd<0) {
  2359. int severity = LOG_WARN;
  2360. int save_errno = errno;
  2361. if (errno == ENOENT && (flags & RFTS_IGNORE_MISSING))
  2362. severity = LOG_INFO;
  2363. log_fn(severity, LD_FS,"Could not open \"%s\": %s",filename,
  2364. strerror(errno));
  2365. errno = save_errno;
  2366. return NULL;
  2367. }
  2368. if (fstat(fd, &statbuf)<0) {
  2369. int save_errno = errno;
  2370. close(fd);
  2371. log_warn(LD_FS,"Could not fstat \"%s\".",filename);
  2372. errno = save_errno;
  2373. return NULL;
  2374. }
  2375. #ifndef _WIN32
  2376. /** When we detect that we're reading from a FIFO, don't read more than
  2377. * this many bytes. It's insane overkill for most uses. */
  2378. #define FIFO_READ_MAX (1024*1024)
  2379. if (S_ISFIFO(statbuf.st_mode)) {
  2380. size_t sz = 0;
  2381. string = read_file_to_str_until_eof(fd, FIFO_READ_MAX, &sz);
  2382. int save_errno = errno;
  2383. if (string && stat_out) {
  2384. statbuf.st_size = sz;
  2385. memcpy(stat_out, &statbuf, sizeof(struct stat));
  2386. }
  2387. close(fd);
  2388. if (!string)
  2389. errno = save_errno;
  2390. return string;
  2391. }
  2392. #endif /* !defined(_WIN32) */
  2393. if ((uint64_t)(statbuf.st_size)+1 >= SIZE_T_CEILING) {
  2394. close(fd);
  2395. errno = EINVAL;
  2396. return NULL;
  2397. }
  2398. string = tor_malloc((size_t)(statbuf.st_size+1));
  2399. r = read_all(fd,string,(size_t)statbuf.st_size,0);
  2400. if (r<0) {
  2401. int save_errno = errno;
  2402. log_warn(LD_FS,"Error reading from file \"%s\": %s", filename,
  2403. strerror(errno));
  2404. tor_free(string);
  2405. close(fd);
  2406. errno = save_errno;
  2407. return NULL;
  2408. }
  2409. string[r] = '\0'; /* NUL-terminate the result. */
  2410. #if defined(_WIN32) || defined(__CYGWIN__)
  2411. if (!bin && strchr(string, '\r')) {
  2412. log_debug(LD_FS, "We didn't convert CRLF to LF as well as we hoped "
  2413. "when reading %s. Coping.",
  2414. filename);
  2415. tor_strstrip(string, "\r");
  2416. r = strlen(string);
  2417. }
  2418. if (!bin) {
  2419. statbuf.st_size = (size_t) r;
  2420. } else
  2421. #endif /* defined(_WIN32) || defined(__CYGWIN__) */
  2422. if (r != statbuf.st_size) {
  2423. /* Unless we're using text mode on win32, we'd better have an exact
  2424. * match for size. */
  2425. int save_errno = errno;
  2426. log_warn(LD_FS,"Could read only %d of %ld bytes of file \"%s\".",
  2427. (int)r, (long)statbuf.st_size,filename);
  2428. tor_free(string);
  2429. close(fd);
  2430. errno = save_errno;
  2431. return NULL;
  2432. }
  2433. close(fd);
  2434. if (stat_out) {
  2435. memcpy(stat_out, &statbuf, sizeof(struct stat));
  2436. }
  2437. return string;
  2438. }
  2439. #define TOR_ISODIGIT(c) ('0' <= (c) && (c) <= '7')
  2440. /** Given a c-style double-quoted escaped string in <b>s</b>, extract and
  2441. * decode its contents into a newly allocated string. On success, assign this
  2442. * string to *<b>result</b>, assign its length to <b>size_out</b> (if
  2443. * provided), and return a pointer to the position in <b>s</b> immediately
  2444. * after the string. On failure, return NULL.
  2445. */
  2446. const char *
  2447. unescape_string(const char *s, char **result, size_t *size_out)
  2448. {
  2449. const char *cp;
  2450. char *out;
  2451. if (s[0] != '\"')
  2452. return NULL;
  2453. cp = s+1;
  2454. while (1) {
  2455. switch (*cp) {
  2456. case '\0':
  2457. case '\n':
  2458. return NULL;
  2459. case '\"':
  2460. goto end_of_loop;
  2461. case '\\':
  2462. if (cp[1] == 'x' || cp[1] == 'X') {
  2463. if (!(TOR_ISXDIGIT(cp[2]) && TOR_ISXDIGIT(cp[3])))
  2464. return NULL;
  2465. cp += 4;
  2466. } else if (TOR_ISODIGIT(cp[1])) {
  2467. cp += 2;
  2468. if (TOR_ISODIGIT(*cp)) ++cp;
  2469. if (TOR_ISODIGIT(*cp)) ++cp;
  2470. } else if (cp[1] == 'n' || cp[1] == 'r' || cp[1] == 't' || cp[1] == '"'
  2471. || cp[1] == '\\' || cp[1] == '\'') {
  2472. cp += 2;
  2473. } else {
  2474. return NULL;
  2475. }
  2476. break;
  2477. default:
  2478. ++cp;
  2479. break;
  2480. }
  2481. }
  2482. end_of_loop:
  2483. out = *result = tor_malloc(cp-s + 1);
  2484. cp = s+1;
  2485. while (1) {
  2486. switch (*cp)
  2487. {
  2488. case '\"':
  2489. *out = '\0';
  2490. if (size_out) *size_out = out - *result;
  2491. return cp+1;
  2492. /* LCOV_EXCL_START -- we caught this in parse_config_from_line. */
  2493. case '\0':
  2494. tor_fragile_assert();
  2495. tor_free(*result);
  2496. return NULL;
  2497. /* LCOV_EXCL_STOP */
  2498. case '\\':
  2499. switch (cp[1])
  2500. {
  2501. case 'n': *out++ = '\n'; cp += 2; break;
  2502. case 'r': *out++ = '\r'; cp += 2; break;
  2503. case 't': *out++ = '\t'; cp += 2; break;
  2504. case 'x': case 'X':
  2505. {
  2506. int x1, x2;
  2507. x1 = hex_decode_digit(cp[2]);
  2508. x2 = hex_decode_digit(cp[3]);
  2509. if (x1 == -1 || x2 == -1) {
  2510. /* LCOV_EXCL_START */
  2511. /* we caught this above in the initial loop. */
  2512. tor_assert_nonfatal_unreached();
  2513. tor_free(*result);
  2514. return NULL;
  2515. /* LCOV_EXCL_STOP */
  2516. }
  2517. *out++ = ((x1<<4) + x2);
  2518. cp += 4;
  2519. }
  2520. break;
  2521. case '0': case '1': case '2': case '3': case '4': case '5':
  2522. case '6': case '7':
  2523. {
  2524. int n = cp[1]-'0';
  2525. cp += 2;
  2526. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2527. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2528. if (n > 255) { tor_free(*result); return NULL; }
  2529. *out++ = (char)n;
  2530. }
  2531. break;
  2532. case '\'':
  2533. case '\"':
  2534. case '\\':
  2535. case '\?':
  2536. *out++ = cp[1];
  2537. cp += 2;
  2538. break;
  2539. /* LCOV_EXCL_START */
  2540. default:
  2541. /* we caught this above in the initial loop. */
  2542. tor_assert_nonfatal_unreached();
  2543. tor_free(*result); return NULL;
  2544. /* LCOV_EXCL_STOP */
  2545. }
  2546. break;
  2547. default:
  2548. *out++ = *cp++;
  2549. }
  2550. }
  2551. }
  2552. /** Removes enclosing quotes from <b>path</b> and unescapes quotes between the
  2553. * enclosing quotes. Backslashes are not unescaped. Return the unquoted
  2554. * <b>path</b> on success or 0 if <b>path</b> is not quoted correctly. */
  2555. char *
  2556. get_unquoted_path(const char *path)
  2557. {
  2558. size_t len = strlen(path);
  2559. if (len == 0) {
  2560. return tor_strdup("");
  2561. }
  2562. int has_start_quote = (path[0] == '\"');
  2563. int has_end_quote = (len > 0 && path[len-1] == '\"');
  2564. if (has_start_quote != has_end_quote || (len == 1 && has_start_quote)) {
  2565. return NULL;
  2566. }
  2567. char *unquoted_path = tor_malloc(len - has_start_quote - has_end_quote + 1);
  2568. char *s = unquoted_path;
  2569. size_t i;
  2570. for (i = has_start_quote; i < len - has_end_quote; i++) {
  2571. if (path[i] == '\"' && (i > 0 && path[i-1] == '\\')) {
  2572. *(s-1) = path[i];
  2573. } else if (path[i] != '\"') {
  2574. *s++ = path[i];
  2575. } else { /* unescaped quote */
  2576. tor_free(unquoted_path);
  2577. return NULL;
  2578. }
  2579. }
  2580. *s = '\0';
  2581. return unquoted_path;
  2582. }
  2583. /** Expand any homedir prefix on <b>filename</b>; return a newly allocated
  2584. * string. */
  2585. char *
  2586. expand_filename(const char *filename)
  2587. {
  2588. tor_assert(filename);
  2589. #ifdef _WIN32
  2590. /* Might consider using GetFullPathName() as described here:
  2591. * http://etutorials.org/Programming/secure+programming/
  2592. * Chapter+3.+Input+Validation/3.7+Validating+Filenames+and+Paths/
  2593. */
  2594. return tor_strdup(filename);
  2595. #else /* !(defined(_WIN32)) */
  2596. if (*filename == '~') {
  2597. char *home, *result=NULL;
  2598. const char *rest;
  2599. if (filename[1] == '/' || filename[1] == '\0') {
  2600. home = getenv("HOME");
  2601. if (!home) {
  2602. log_warn(LD_CONFIG, "Couldn't find $HOME environment variable while "
  2603. "expanding \"%s\"; defaulting to \"\".", filename);
  2604. home = tor_strdup("");
  2605. } else {
  2606. home = tor_strdup(home);
  2607. }
  2608. rest = strlen(filename)>=2?(filename+2):"";
  2609. } else {
  2610. #ifdef HAVE_PWD_H
  2611. char *username, *slash;
  2612. slash = strchr(filename, '/');
  2613. if (slash)
  2614. username = tor_strndup(filename+1,slash-filename-1);
  2615. else
  2616. username = tor_strdup(filename+1);
  2617. if (!(home = get_user_homedir(username))) {
  2618. log_warn(LD_CONFIG,"Couldn't get homedir for \"%s\"",username);
  2619. tor_free(username);
  2620. return NULL;
  2621. }
  2622. tor_free(username);
  2623. rest = slash ? (slash+1) : "";
  2624. #else /* !(defined(HAVE_PWD_H)) */
  2625. log_warn(LD_CONFIG, "Couldn't expand homedir on system without pwd.h");
  2626. return tor_strdup(filename);
  2627. #endif /* defined(HAVE_PWD_H) */
  2628. }
  2629. tor_assert(home);
  2630. /* Remove trailing slash. */
  2631. if (strlen(home)>1 && !strcmpend(home,PATH_SEPARATOR)) {
  2632. home[strlen(home)-1] = '\0';
  2633. }
  2634. tor_asprintf(&result,"%s"PATH_SEPARATOR"%s",home,rest);
  2635. tor_free(home);
  2636. return result;
  2637. } else {
  2638. return tor_strdup(filename);
  2639. }
  2640. #endif /* defined(_WIN32) */
  2641. }
  2642. #define MAX_SCANF_WIDTH 9999
  2643. /** Helper: given an ASCII-encoded decimal digit, return its numeric value.
  2644. * NOTE: requires that its input be in-bounds. */
  2645. static int
  2646. digit_to_num(char d)
  2647. {
  2648. int num = ((int)d) - (int)'0';
  2649. tor_assert(num <= 9 && num >= 0);
  2650. return num;
  2651. }
  2652. /** Helper: Read an unsigned int from *<b>bufp</b> of up to <b>width</b>
  2653. * characters. (Handle arbitrary width if <b>width</b> is less than 0.) On
  2654. * success, store the result in <b>out</b>, advance bufp to the next
  2655. * character, and return 0. On failure, return -1. */
  2656. static int
  2657. scan_unsigned(const char **bufp, unsigned long *out, int width, unsigned base)
  2658. {
  2659. unsigned long result = 0;
  2660. int scanned_so_far = 0;
  2661. const int hex = base==16;
  2662. tor_assert(base == 10 || base == 16);
  2663. if (!bufp || !*bufp || !out)
  2664. return -1;
  2665. if (width<0)
  2666. width=MAX_SCANF_WIDTH;
  2667. while (**bufp && (hex?TOR_ISXDIGIT(**bufp):TOR_ISDIGIT(**bufp))
  2668. && scanned_so_far < width) {
  2669. unsigned digit = hex?hex_decode_digit(*(*bufp)++):digit_to_num(*(*bufp)++);
  2670. // Check for overflow beforehand, without actually causing any overflow
  2671. // This preserves functionality on compilers that don't wrap overflow
  2672. // (i.e. that trap or optimise away overflow)
  2673. // result * base + digit > ULONG_MAX
  2674. // result * base > ULONG_MAX - digit
  2675. if (result > (ULONG_MAX - digit)/base)
  2676. return -1; /* Processing this digit would overflow */
  2677. result = result * base + digit;
  2678. ++scanned_so_far;
  2679. }
  2680. if (!scanned_so_far) /* No actual digits scanned */
  2681. return -1;
  2682. *out = result;
  2683. return 0;
  2684. }
  2685. /** Helper: Read an signed int from *<b>bufp</b> of up to <b>width</b>
  2686. * characters. (Handle arbitrary width if <b>width</b> is less than 0.) On
  2687. * success, store the result in <b>out</b>, advance bufp to the next
  2688. * character, and return 0. On failure, return -1. */
  2689. static int
  2690. scan_signed(const char **bufp, long *out, int width)
  2691. {
  2692. int neg = 0;
  2693. unsigned long result = 0;
  2694. if (!bufp || !*bufp || !out)
  2695. return -1;
  2696. if (width<0)
  2697. width=MAX_SCANF_WIDTH;
  2698. if (**bufp == '-') {
  2699. neg = 1;
  2700. ++*bufp;
  2701. --width;
  2702. }
  2703. if (scan_unsigned(bufp, &result, width, 10) < 0)
  2704. return -1;
  2705. if (neg && result > 0) {
  2706. if (result > ((unsigned long)LONG_MAX) + 1)
  2707. return -1; /* Underflow */
  2708. else if (result == ((unsigned long)LONG_MAX) + 1)
  2709. *out = LONG_MIN;
  2710. else {
  2711. /* We once had a far more clever no-overflow conversion here, but
  2712. * some versions of GCC apparently ran it into the ground. Now
  2713. * we just check for LONG_MIN explicitly.
  2714. */
  2715. *out = -(long)result;
  2716. }
  2717. } else {
  2718. if (result > LONG_MAX)
  2719. return -1; /* Overflow */
  2720. *out = (long)result;
  2721. }
  2722. return 0;
  2723. }
  2724. /** Helper: Read a decimal-formatted double from *<b>bufp</b> of up to
  2725. * <b>width</b> characters. (Handle arbitrary width if <b>width</b> is less
  2726. * than 0.) On success, store the result in <b>out</b>, advance bufp to the
  2727. * next character, and return 0. On failure, return -1. */
  2728. static int
  2729. scan_double(const char **bufp, double *out, int width)
  2730. {
  2731. int neg = 0;
  2732. double result = 0;
  2733. int scanned_so_far = 0;
  2734. if (!bufp || !*bufp || !out)
  2735. return -1;
  2736. if (width<0)
  2737. width=MAX_SCANF_WIDTH;
  2738. if (**bufp == '-') {
  2739. neg = 1;
  2740. ++*bufp;
  2741. }
  2742. while (**bufp && TOR_ISDIGIT(**bufp) && scanned_so_far < width) {
  2743. const int digit = digit_to_num(*(*bufp)++);
  2744. result = result * 10 + digit;
  2745. ++scanned_so_far;
  2746. }
  2747. if (**bufp == '.') {
  2748. double fracval = 0, denominator = 1;
  2749. ++*bufp;
  2750. ++scanned_so_far;
  2751. while (**bufp && TOR_ISDIGIT(**bufp) && scanned_so_far < width) {
  2752. const int digit = digit_to_num(*(*bufp)++);
  2753. fracval = fracval * 10 + digit;
  2754. denominator *= 10;
  2755. ++scanned_so_far;
  2756. }
  2757. result += fracval / denominator;
  2758. }
  2759. if (!scanned_so_far) /* No actual digits scanned */
  2760. return -1;
  2761. *out = neg ? -result : result;
  2762. return 0;
  2763. }
  2764. /** Helper: copy up to <b>width</b> non-space characters from <b>bufp</b> to
  2765. * <b>out</b>. Make sure <b>out</b> is nul-terminated. Advance <b>bufp</b>
  2766. * to the next non-space character or the EOS. */
  2767. static int
  2768. scan_string(const char **bufp, char *out, int width)
  2769. {
  2770. int scanned_so_far = 0;
  2771. if (!bufp || !out || width < 0)
  2772. return -1;
  2773. while (**bufp && ! TOR_ISSPACE(**bufp) && scanned_so_far < width) {
  2774. *out++ = *(*bufp)++;
  2775. ++scanned_so_far;
  2776. }
  2777. *out = '\0';
  2778. return 0;
  2779. }
  2780. /** Locale-independent, minimal, no-surprises scanf variant, accepting only a
  2781. * restricted pattern format. For more info on what it supports, see
  2782. * tor_sscanf() documentation. */
  2783. int
  2784. tor_vsscanf(const char *buf, const char *pattern, va_list ap)
  2785. {
  2786. int n_matched = 0;
  2787. while (*pattern) {
  2788. if (*pattern != '%') {
  2789. if (*buf == *pattern) {
  2790. ++buf;
  2791. ++pattern;
  2792. continue;
  2793. } else {
  2794. return n_matched;
  2795. }
  2796. } else {
  2797. int width = -1;
  2798. int longmod = 0;
  2799. ++pattern;
  2800. if (TOR_ISDIGIT(*pattern)) {
  2801. width = digit_to_num(*pattern++);
  2802. while (TOR_ISDIGIT(*pattern)) {
  2803. width *= 10;
  2804. width += digit_to_num(*pattern++);
  2805. if (width > MAX_SCANF_WIDTH)
  2806. return -1;
  2807. }
  2808. if (!width) /* No zero-width things. */
  2809. return -1;
  2810. }
  2811. if (*pattern == 'l') {
  2812. longmod = 1;
  2813. ++pattern;
  2814. }
  2815. if (*pattern == 'u' || *pattern == 'x') {
  2816. unsigned long u;
  2817. const int base = (*pattern == 'u') ? 10 : 16;
  2818. if (!*buf)
  2819. return n_matched;
  2820. if (scan_unsigned(&buf, &u, width, base)<0)
  2821. return n_matched;
  2822. if (longmod) {
  2823. unsigned long *out = va_arg(ap, unsigned long *);
  2824. *out = u;
  2825. } else {
  2826. unsigned *out = va_arg(ap, unsigned *);
  2827. if (u > UINT_MAX)
  2828. return n_matched;
  2829. *out = (unsigned) u;
  2830. }
  2831. ++pattern;
  2832. ++n_matched;
  2833. } else if (*pattern == 'f') {
  2834. double *d = va_arg(ap, double *);
  2835. if (!longmod)
  2836. return -1; /* float not supported */
  2837. if (!*buf)
  2838. return n_matched;
  2839. if (scan_double(&buf, d, width)<0)
  2840. return n_matched;
  2841. ++pattern;
  2842. ++n_matched;
  2843. } else if (*pattern == 'd') {
  2844. long lng=0;
  2845. if (scan_signed(&buf, &lng, width)<0)
  2846. return n_matched;
  2847. if (longmod) {
  2848. long *out = va_arg(ap, long *);
  2849. *out = lng;
  2850. } else {
  2851. int *out = va_arg(ap, int *);
  2852. #if LONG_MAX > INT_MAX
  2853. if (lng < INT_MIN || lng > INT_MAX)
  2854. return n_matched;
  2855. #endif
  2856. *out = (int)lng;
  2857. }
  2858. ++pattern;
  2859. ++n_matched;
  2860. } else if (*pattern == 's') {
  2861. char *s = va_arg(ap, char *);
  2862. if (longmod)
  2863. return -1;
  2864. if (width < 0)
  2865. return -1;
  2866. if (scan_string(&buf, s, width)<0)
  2867. return n_matched;
  2868. ++pattern;
  2869. ++n_matched;
  2870. } else if (*pattern == 'c') {
  2871. char *ch = va_arg(ap, char *);
  2872. if (longmod)
  2873. return -1;
  2874. if (width != -1)
  2875. return -1;
  2876. if (!*buf)
  2877. return n_matched;
  2878. *ch = *buf++;
  2879. ++pattern;
  2880. ++n_matched;
  2881. } else if (*pattern == '%') {
  2882. if (*buf != '%')
  2883. return n_matched;
  2884. if (longmod)
  2885. return -1;
  2886. ++buf;
  2887. ++pattern;
  2888. } else {
  2889. return -1; /* Unrecognized pattern component. */
  2890. }
  2891. }
  2892. }
  2893. return n_matched;
  2894. }
  2895. /** Minimal sscanf replacement: parse <b>buf</b> according to <b>pattern</b>
  2896. * and store the results in the corresponding argument fields. Differs from
  2897. * sscanf in that:
  2898. * <ul><li>It only handles %u, %lu, %x, %lx, %[NUM]s, %d, %ld, %lf, and %c.
  2899. * <li>It only handles decimal inputs for %lf. (12.3, not 1.23e1)
  2900. * <li>It does not handle arbitrarily long widths.
  2901. * <li>Numbers do not consume any space characters.
  2902. * <li>It is locale-independent.
  2903. * <li>%u and %x do not consume any space.
  2904. * <li>It returns -1 on malformed patterns.</ul>
  2905. *
  2906. * (As with other locale-independent functions, we need this to parse data that
  2907. * is in ASCII without worrying that the C library's locale-handling will make
  2908. * miscellaneous characters look like numbers, spaces, and so on.)
  2909. */
  2910. int
  2911. tor_sscanf(const char *buf, const char *pattern, ...)
  2912. {
  2913. int r;
  2914. va_list ap;
  2915. va_start(ap, pattern);
  2916. r = tor_vsscanf(buf, pattern, ap);
  2917. va_end(ap);
  2918. return r;
  2919. }
  2920. /** Append the string produced by tor_asprintf(<b>pattern</b>, <b>...</b>)
  2921. * to <b>sl</b>. */
  2922. void
  2923. smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern, ...)
  2924. {
  2925. va_list ap;
  2926. va_start(ap, pattern);
  2927. smartlist_add_vasprintf(sl, pattern, ap);
  2928. va_end(ap);
  2929. }
  2930. /** va_list-based backend of smartlist_add_asprintf. */
  2931. void
  2932. smartlist_add_vasprintf(struct smartlist_t *sl, const char *pattern,
  2933. va_list args)
  2934. {
  2935. char *str = NULL;
  2936. tor_vasprintf(&str, pattern, args);
  2937. tor_assert(str != NULL);
  2938. smartlist_add(sl, str);
  2939. }
  2940. /** Return a new list containing the filenames in the directory <b>dirname</b>.
  2941. * Return NULL on error or if <b>dirname</b> is not a directory.
  2942. */
  2943. MOCK_IMPL(smartlist_t *,
  2944. tor_listdir, (const char *dirname))
  2945. {
  2946. smartlist_t *result;
  2947. #ifdef _WIN32
  2948. char *pattern=NULL;
  2949. TCHAR tpattern[MAX_PATH] = {0};
  2950. char name[MAX_PATH*2+1] = {0};
  2951. HANDLE handle;
  2952. WIN32_FIND_DATA findData;
  2953. tor_asprintf(&pattern, "%s\\*", dirname);
  2954. #ifdef UNICODE
  2955. mbstowcs(tpattern,pattern,MAX_PATH);
  2956. #else
  2957. strlcpy(tpattern, pattern, MAX_PATH);
  2958. #endif
  2959. if (INVALID_HANDLE_VALUE == (handle = FindFirstFile(tpattern, &findData))) {
  2960. tor_free(pattern);
  2961. return NULL;
  2962. }
  2963. result = smartlist_new();
  2964. while (1) {
  2965. #ifdef UNICODE
  2966. wcstombs(name,findData.cFileName,MAX_PATH);
  2967. name[sizeof(name)-1] = '\0';
  2968. #else
  2969. strlcpy(name,findData.cFileName,sizeof(name));
  2970. #endif /* defined(UNICODE) */
  2971. if (strcmp(name, ".") &&
  2972. strcmp(name, "..")) {
  2973. smartlist_add_strdup(result, name);
  2974. }
  2975. if (!FindNextFile(handle, &findData)) {
  2976. DWORD err;
  2977. if ((err = GetLastError()) != ERROR_NO_MORE_FILES) {
  2978. char *errstr = format_win32_error(err);
  2979. log_warn(LD_FS, "Error reading directory '%s': %s", dirname, errstr);
  2980. tor_free(errstr);
  2981. }
  2982. break;
  2983. }
  2984. }
  2985. FindClose(handle);
  2986. tor_free(pattern);
  2987. #else /* !(defined(_WIN32)) */
  2988. const char *prot_dname = sandbox_intern_string(dirname);
  2989. DIR *d;
  2990. struct dirent *de;
  2991. if (!(d = opendir(prot_dname)))
  2992. return NULL;
  2993. result = smartlist_new();
  2994. while ((de = readdir(d))) {
  2995. if (!strcmp(de->d_name, ".") ||
  2996. !strcmp(de->d_name, ".."))
  2997. continue;
  2998. smartlist_add_strdup(result, de->d_name);
  2999. }
  3000. closedir(d);
  3001. #endif /* defined(_WIN32) */
  3002. return result;
  3003. }
  3004. /** Return true iff <b>filename</b> is a relative path. */
  3005. int
  3006. path_is_relative(const char *filename)
  3007. {
  3008. if (filename && filename[0] == '/')
  3009. return 0;
  3010. #ifdef _WIN32
  3011. else if (filename && filename[0] == '\\')
  3012. return 0;
  3013. else if (filename && strlen(filename)>3 && TOR_ISALPHA(filename[0]) &&
  3014. filename[1] == ':' && filename[2] == '\\')
  3015. return 0;
  3016. #endif /* defined(_WIN32) */
  3017. else
  3018. return 1;
  3019. }
  3020. /* =====
  3021. * Process helpers
  3022. * ===== */
  3023. #ifndef _WIN32
  3024. /* Based on code contributed by christian grothoff */
  3025. /** True iff we've called start_daemon(). */
  3026. static int start_daemon_called = 0;
  3027. /** True iff we've called finish_daemon(). */
  3028. static int finish_daemon_called = 0;
  3029. /** Socketpair used to communicate between parent and child process while
  3030. * daemonizing. */
  3031. static int daemon_filedes[2];
  3032. /** Start putting the process into daemon mode: fork and drop all resources
  3033. * except standard fds. The parent process never returns, but stays around
  3034. * until finish_daemon is called. (Note: it's safe to call this more
  3035. * than once: calls after the first are ignored.)
  3036. */
  3037. void
  3038. start_daemon(void)
  3039. {
  3040. pid_t pid;
  3041. if (start_daemon_called)
  3042. return;
  3043. start_daemon_called = 1;
  3044. if (pipe(daemon_filedes)) {
  3045. /* LCOV_EXCL_START */
  3046. log_err(LD_GENERAL,"pipe failed; exiting. Error was %s", strerror(errno));
  3047. exit(1); // exit ok: during daemonize, pipe failed.
  3048. /* LCOV_EXCL_STOP */
  3049. }
  3050. pid = fork();
  3051. if (pid < 0) {
  3052. /* LCOV_EXCL_START */
  3053. log_err(LD_GENERAL,"fork failed. Exiting.");
  3054. exit(1); // exit ok: during daemonize, fork failed
  3055. /* LCOV_EXCL_STOP */
  3056. }
  3057. if (pid) { /* Parent */
  3058. int ok;
  3059. char c;
  3060. close(daemon_filedes[1]); /* we only read */
  3061. ok = -1;
  3062. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  3063. if (c == '.')
  3064. ok = 1;
  3065. }
  3066. fflush(stdout);
  3067. if (ok == 1)
  3068. exit(0); // exit ok: during daemonize, daemonizing.
  3069. else
  3070. exit(1); /* child reported error. exit ok: daemonize failed. */
  3071. } else { /* Child */
  3072. close(daemon_filedes[0]); /* we only write */
  3073. (void) setsid(); /* Detach from controlling terminal */
  3074. /*
  3075. * Fork one more time, so the parent (the session group leader) can exit.
  3076. * This means that we, as a non-session group leader, can never regain a
  3077. * controlling terminal. This part is recommended by Stevens's
  3078. * _Advanced Programming in the Unix Environment_.
  3079. */
  3080. if (fork() != 0) {
  3081. exit(0); // exit ok: during daemonize, fork failed (2)
  3082. }
  3083. set_main_thread(); /* We are now the main thread. */
  3084. return;
  3085. }
  3086. }
  3087. /** Finish putting the process into daemon mode: drop standard fds, and tell
  3088. * the parent process to exit. (Note: it's safe to call this more than once:
  3089. * calls after the first are ignored. Calls start_daemon first if it hasn't
  3090. * been called already.)
  3091. */
  3092. void
  3093. finish_daemon(const char *desired_cwd)
  3094. {
  3095. int nullfd;
  3096. char c = '.';
  3097. if (finish_daemon_called)
  3098. return;
  3099. if (!start_daemon_called)
  3100. start_daemon();
  3101. finish_daemon_called = 1;
  3102. if (!desired_cwd)
  3103. desired_cwd = "/";
  3104. /* Don't hold the wrong FS mounted */
  3105. if (chdir(desired_cwd) < 0) {
  3106. log_err(LD_GENERAL,"chdir to \"%s\" failed. Exiting.",desired_cwd);
  3107. exit(1); // exit ok: during daemonize, chdir failed.
  3108. }
  3109. nullfd = tor_open_cloexec("/dev/null", O_RDWR, 0);
  3110. if (nullfd < 0) {
  3111. /* LCOV_EXCL_START */
  3112. log_err(LD_GENERAL,"/dev/null can't be opened. Exiting.");
  3113. exit(1); // exit ok: during daemonize, couldn't open /dev/null
  3114. /* LCOV_EXCL_STOP */
  3115. }
  3116. /* close fds linking to invoking terminal, but
  3117. * close usual incoming fds, but redirect them somewhere
  3118. * useful so the fds don't get reallocated elsewhere.
  3119. */
  3120. if (dup2(nullfd,0) < 0 ||
  3121. dup2(nullfd,1) < 0 ||
  3122. dup2(nullfd,2) < 0) {
  3123. /* LCOV_EXCL_START */
  3124. log_err(LD_GENERAL,"dup2 failed. Exiting.");
  3125. exit(1); // exit ok: during daemonize, dup2 failed.
  3126. /* LCOV_EXCL_STOP */
  3127. }
  3128. if (nullfd > 2)
  3129. close(nullfd);
  3130. /* signal success */
  3131. if (write(daemon_filedes[1], &c, sizeof(char)) != sizeof(char)) {
  3132. log_err(LD_GENERAL,"write failed. Exiting.");
  3133. }
  3134. close(daemon_filedes[1]);
  3135. }
  3136. #else /* !(!defined(_WIN32)) */
  3137. /* defined(_WIN32) */
  3138. void
  3139. start_daemon(void)
  3140. {
  3141. }
  3142. void
  3143. finish_daemon(const char *cp)
  3144. {
  3145. (void)cp;
  3146. }
  3147. #endif /* !defined(_WIN32) */
  3148. /** Write the current process ID, followed by NL, into <b>filename</b>.
  3149. * Return 0 on success, -1 on failure.
  3150. */
  3151. int
  3152. write_pidfile(const char *filename)
  3153. {
  3154. FILE *pidfile;
  3155. if ((pidfile = fopen(filename, "w")) == NULL) {
  3156. log_warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
  3157. strerror(errno));
  3158. return -1;
  3159. } else {
  3160. #ifdef _WIN32
  3161. int pid = (int)_getpid();
  3162. #else
  3163. int pid = (int)getpid();
  3164. #endif
  3165. int rv = 0;
  3166. if (fprintf(pidfile, "%d\n", pid) < 0)
  3167. rv = -1;
  3168. if (fclose(pidfile) < 0)
  3169. rv = -1;
  3170. return rv;
  3171. }
  3172. }
  3173. #ifdef _WIN32
  3174. HANDLE
  3175. load_windows_system_library(const TCHAR *library_name)
  3176. {
  3177. TCHAR path[MAX_PATH];
  3178. unsigned n;
  3179. n = GetSystemDirectory(path, MAX_PATH);
  3180. if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
  3181. return 0;
  3182. _tcscat(path, TEXT("\\"));
  3183. _tcscat(path, library_name);
  3184. return LoadLibrary(path);
  3185. }
  3186. #endif /* defined(_WIN32) */
  3187. /** Format a single argument for being put on a Windows command line.
  3188. * Returns a newly allocated string */
  3189. static char *
  3190. format_win_cmdline_argument(const char *arg)
  3191. {
  3192. char *formatted_arg;
  3193. char need_quotes;
  3194. const char *c;
  3195. int i;
  3196. int bs_counter = 0;
  3197. /* Backslash we can point to when one is inserted into the string */
  3198. const char backslash = '\\';
  3199. /* Smartlist of *char */
  3200. smartlist_t *arg_chars;
  3201. arg_chars = smartlist_new();
  3202. /* Quote string if it contains whitespace or is empty */
  3203. need_quotes = (strchr(arg, ' ') || strchr(arg, '\t') || '\0' == arg[0]);
  3204. /* Build up smartlist of *chars */
  3205. for (c=arg; *c != '\0'; c++) {
  3206. if ('"' == *c) {
  3207. /* Double up backslashes preceding a quote */
  3208. for (i=0; i<(bs_counter*2); i++)
  3209. smartlist_add(arg_chars, (void*)&backslash);
  3210. bs_counter = 0;
  3211. /* Escape the quote */
  3212. smartlist_add(arg_chars, (void*)&backslash);
  3213. smartlist_add(arg_chars, (void*)c);
  3214. } else if ('\\' == *c) {
  3215. /* Count backslashes until we know whether to double up */
  3216. bs_counter++;
  3217. } else {
  3218. /* Don't double up slashes preceding a non-quote */
  3219. for (i=0; i<bs_counter; i++)
  3220. smartlist_add(arg_chars, (void*)&backslash);
  3221. bs_counter = 0;
  3222. smartlist_add(arg_chars, (void*)c);
  3223. }
  3224. }
  3225. /* Don't double up trailing backslashes */
  3226. for (i=0; i<bs_counter; i++)
  3227. smartlist_add(arg_chars, (void*)&backslash);
  3228. /* Allocate space for argument, quotes (if needed), and terminator */
  3229. const size_t formatted_arg_len = smartlist_len(arg_chars) +
  3230. (need_quotes ? 2 : 0) + 1;
  3231. formatted_arg = tor_malloc_zero(formatted_arg_len);
  3232. /* Add leading quote */
  3233. i=0;
  3234. if (need_quotes)
  3235. formatted_arg[i++] = '"';
  3236. /* Add characters */
  3237. SMARTLIST_FOREACH(arg_chars, char*, ch,
  3238. {
  3239. formatted_arg[i++] = *ch;
  3240. });
  3241. /* Add trailing quote */
  3242. if (need_quotes)
  3243. formatted_arg[i++] = '"';
  3244. formatted_arg[i] = '\0';
  3245. smartlist_free(arg_chars);
  3246. return formatted_arg;
  3247. }
  3248. /** Format a command line for use on Windows, which takes the command as a
  3249. * string rather than string array. Follows the rules from "Parsing C++
  3250. * Command-Line Arguments" in MSDN. Algorithm based on list2cmdline in the
  3251. * Python subprocess module. Returns a newly allocated string */
  3252. char *
  3253. tor_join_win_cmdline(const char *argv[])
  3254. {
  3255. smartlist_t *argv_list;
  3256. char *joined_argv;
  3257. int i;
  3258. /* Format each argument and put the result in a smartlist */
  3259. argv_list = smartlist_new();
  3260. for (i=0; argv[i] != NULL; i++) {
  3261. smartlist_add(argv_list, (void *)format_win_cmdline_argument(argv[i]));
  3262. }
  3263. /* Join the arguments with whitespace */
  3264. joined_argv = smartlist_join_strings(argv_list, " ", 0, NULL);
  3265. /* Free the newly allocated arguments, and the smartlist */
  3266. SMARTLIST_FOREACH(argv_list, char *, arg,
  3267. {
  3268. tor_free(arg);
  3269. });
  3270. smartlist_free(argv_list);
  3271. return joined_argv;
  3272. }
  3273. #ifndef _WIN32
  3274. /** Format <b>child_state</b> and <b>saved_errno</b> as a hex string placed in
  3275. * <b>hex_errno</b>. Called between fork and _exit, so must be signal-handler
  3276. * safe.
  3277. *
  3278. * <b>hex_errno</b> must have at least HEX_ERRNO_SIZE+1 bytes available.
  3279. *
  3280. * The format of <b>hex_errno</b> is: "CHILD_STATE/ERRNO\n", left-padded
  3281. * with spaces. CHILD_STATE indicates where
  3282. * in the process of starting the child process did the failure occur (see
  3283. * CHILD_STATE_* macros for definition), and SAVED_ERRNO is the value of
  3284. * errno when the failure occurred.
  3285. *
  3286. * On success return the number of characters added to hex_errno, not counting
  3287. * the terminating NUL; return -1 on error.
  3288. */
  3289. STATIC int
  3290. format_helper_exit_status(unsigned char child_state, int saved_errno,
  3291. char *hex_errno)
  3292. {
  3293. unsigned int unsigned_errno;
  3294. int written, left;
  3295. char *cur;
  3296. size_t i;
  3297. int res = -1;
  3298. /* Fill hex_errno with spaces, and a trailing newline (memset may
  3299. not be signal handler safe, so we can't use it) */
  3300. for (i = 0; i < (HEX_ERRNO_SIZE - 1); i++)
  3301. hex_errno[i] = ' ';
  3302. hex_errno[HEX_ERRNO_SIZE - 1] = '\n';
  3303. /* Convert errno to be unsigned for hex conversion */
  3304. if (saved_errno < 0) {
  3305. // Avoid overflow on the cast to unsigned int when result is INT_MIN
  3306. // by adding 1 to the signed int negative value,
  3307. // then, after it has been negated and cast to unsigned,
  3308. // adding the original 1 back (the double-addition is intentional).
  3309. // Otherwise, the cast to signed could cause a temporary int
  3310. // to equal INT_MAX + 1, which is undefined.
  3311. unsigned_errno = ((unsigned int) -(saved_errno + 1)) + 1;
  3312. } else {
  3313. unsigned_errno = (unsigned int) saved_errno;
  3314. }
  3315. /*
  3316. * Count how many chars of space we have left, and keep a pointer into the
  3317. * current point in the buffer.
  3318. */
  3319. left = HEX_ERRNO_SIZE+1;
  3320. cur = hex_errno;
  3321. /* Emit child_state */
  3322. written = format_hex_number_sigsafe(child_state, cur, left);
  3323. if (written <= 0)
  3324. goto err;
  3325. /* Adjust left and cur */
  3326. left -= written;
  3327. cur += written;
  3328. if (left <= 0)
  3329. goto err;
  3330. /* Now the '/' */
  3331. *cur = '/';
  3332. /* Adjust left and cur */
  3333. ++cur;
  3334. --left;
  3335. if (left <= 0)
  3336. goto err;
  3337. /* Need minus? */
  3338. if (saved_errno < 0) {
  3339. *cur = '-';
  3340. ++cur;
  3341. --left;
  3342. if (left <= 0)
  3343. goto err;
  3344. }
  3345. /* Emit unsigned_errno */
  3346. written = format_hex_number_sigsafe(unsigned_errno, cur, left);
  3347. if (written <= 0)
  3348. goto err;
  3349. /* Adjust left and cur */
  3350. left -= written;
  3351. cur += written;
  3352. /* Check that we have enough space left for a newline and a NUL */
  3353. if (left <= 1)
  3354. goto err;
  3355. /* Emit the newline and NUL */
  3356. *cur++ = '\n';
  3357. *cur++ = '\0';
  3358. res = (int)(cur - hex_errno - 1);
  3359. goto done;
  3360. err:
  3361. /*
  3362. * In error exit, just write a '\0' in the first char so whatever called
  3363. * this at least won't fall off the end.
  3364. */
  3365. *hex_errno = '\0';
  3366. done:
  3367. return res;
  3368. }
  3369. #endif /* !defined(_WIN32) */
  3370. /* Maximum number of file descriptors, if we cannot get it via sysconf() */
  3371. #define DEFAULT_MAX_FD 256
  3372. /** Terminate the process of <b>process_handle</b>, if that process has not
  3373. * already exited.
  3374. *
  3375. * Return 0 if we succeeded in terminating the process (or if the process
  3376. * already exited), and -1 if we tried to kill the process but failed.
  3377. *
  3378. * Based on code originally borrowed from Python's os.kill. */
  3379. int
  3380. tor_terminate_process(process_handle_t *process_handle)
  3381. {
  3382. #ifdef _WIN32
  3383. if (tor_get_exit_code(process_handle, 0, NULL) == PROCESS_EXIT_RUNNING) {
  3384. HANDLE handle = process_handle->pid.hProcess;
  3385. if (!TerminateProcess(handle, 0))
  3386. return -1;
  3387. else
  3388. return 0;
  3389. }
  3390. #else /* !(defined(_WIN32)) */
  3391. if (process_handle->waitpid_cb) {
  3392. /* We haven't got a waitpid yet, so we can just kill off the process. */
  3393. return kill(process_handle->pid, SIGTERM);
  3394. }
  3395. #endif /* defined(_WIN32) */
  3396. return 0; /* We didn't need to kill the process, so report success */
  3397. }
  3398. /** Return the Process ID of <b>process_handle</b>. */
  3399. int
  3400. tor_process_get_pid(process_handle_t *process_handle)
  3401. {
  3402. #ifdef _WIN32
  3403. return (int) process_handle->pid.dwProcessId;
  3404. #else
  3405. return (int) process_handle->pid;
  3406. #endif
  3407. }
  3408. #ifdef _WIN32
  3409. HANDLE
  3410. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  3411. {
  3412. return process_handle->stdout_pipe;
  3413. }
  3414. #else /* !(defined(_WIN32)) */
  3415. /* DOCDOC tor_process_get_stdout_pipe */
  3416. int
  3417. tor_process_get_stdout_pipe(process_handle_t *process_handle)
  3418. {
  3419. return process_handle->stdout_pipe;
  3420. }
  3421. #endif /* defined(_WIN32) */
  3422. /* DOCDOC process_handle_new */
  3423. static process_handle_t *
  3424. process_handle_new(void)
  3425. {
  3426. process_handle_t *out = tor_malloc_zero(sizeof(process_handle_t));
  3427. #ifdef _WIN32
  3428. out->stdin_pipe = INVALID_HANDLE_VALUE;
  3429. out->stdout_pipe = INVALID_HANDLE_VALUE;
  3430. out->stderr_pipe = INVALID_HANDLE_VALUE;
  3431. #else
  3432. out->stdin_pipe = -1;
  3433. out->stdout_pipe = -1;
  3434. out->stderr_pipe = -1;
  3435. #endif /* defined(_WIN32) */
  3436. return out;
  3437. }
  3438. #ifndef _WIN32
  3439. /** Invoked when a process that we've launched via tor_spawn_background() has
  3440. * been found to have terminated.
  3441. */
  3442. static void
  3443. process_handle_waitpid_cb(int status, void *arg)
  3444. {
  3445. process_handle_t *process_handle = arg;
  3446. process_handle->waitpid_exit_status = status;
  3447. clear_waitpid_callback(process_handle->waitpid_cb);
  3448. if (process_handle->status == PROCESS_STATUS_RUNNING)
  3449. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  3450. process_handle->waitpid_cb = 0;
  3451. }
  3452. #endif /* !defined(_WIN32) */
  3453. /**
  3454. * @name child-process states
  3455. *
  3456. * Each of these values represents a possible state that a child process can
  3457. * be in. They're used to determine what to say when telling the parent how
  3458. * far along we were before failure.
  3459. *
  3460. * @{
  3461. */
  3462. #define CHILD_STATE_INIT 0
  3463. #define CHILD_STATE_PIPE 1
  3464. #define CHILD_STATE_MAXFD 2
  3465. #define CHILD_STATE_FORK 3
  3466. #define CHILD_STATE_DUPOUT 4
  3467. #define CHILD_STATE_DUPERR 5
  3468. #define CHILD_STATE_DUPIN 6
  3469. #define CHILD_STATE_CLOSEFD 7
  3470. #define CHILD_STATE_EXEC 8
  3471. #define CHILD_STATE_FAILEXEC 9
  3472. /** @} */
  3473. /**
  3474. * Boolean. If true, then Tor may call execve or CreateProcess via
  3475. * tor_spawn_background.
  3476. **/
  3477. static int may_spawn_background_process = 1;
  3478. /**
  3479. * Turn off may_spawn_background_process, so that all future calls to
  3480. * tor_spawn_background are guaranteed to fail.
  3481. **/
  3482. void
  3483. tor_disable_spawning_background_processes(void)
  3484. {
  3485. may_spawn_background_process = 0;
  3486. }
  3487. /** Start a program in the background. If <b>filename</b> contains a '/', then
  3488. * it will be treated as an absolute or relative path. Otherwise, on
  3489. * non-Windows systems, the system path will be searched for <b>filename</b>.
  3490. * On Windows, only the current directory will be searched. Here, to search the
  3491. * system path (as well as the application directory, current working
  3492. * directory, and system directories), set filename to NULL.
  3493. *
  3494. * The strings in <b>argv</b> will be passed as the command line arguments of
  3495. * the child program (following convention, argv[0] should normally be the
  3496. * filename of the executable, and this must be the case if <b>filename</b> is
  3497. * NULL). The last element of argv must be NULL. A handle to the child process
  3498. * will be returned in process_handle (which must be non-NULL). Read
  3499. * process_handle.status to find out if the process was successfully launched.
  3500. * For convenience, process_handle.status is returned by this function.
  3501. *
  3502. * Some parts of this code are based on the POSIX subprocess module from
  3503. * Python, and example code from
  3504. * http://msdn.microsoft.com/en-us/library/ms682499%28v=vs.85%29.aspx.
  3505. */
  3506. int
  3507. tor_spawn_background(const char *const filename, const char **argv,
  3508. process_environment_t *env,
  3509. process_handle_t **process_handle_out)
  3510. {
  3511. if (BUG(may_spawn_background_process == 0)) {
  3512. /* We should never reach this point if we're forbidden to spawn
  3513. * processes. Instead we should have caught the attempt earlier. */
  3514. return PROCESS_STATUS_ERROR;
  3515. }
  3516. #ifdef _WIN32
  3517. HANDLE stdout_pipe_read = NULL;
  3518. HANDLE stdout_pipe_write = NULL;
  3519. HANDLE stderr_pipe_read = NULL;
  3520. HANDLE stderr_pipe_write = NULL;
  3521. HANDLE stdin_pipe_read = NULL;
  3522. HANDLE stdin_pipe_write = NULL;
  3523. process_handle_t *process_handle;
  3524. int status;
  3525. STARTUPINFOA siStartInfo;
  3526. BOOL retval = FALSE;
  3527. SECURITY_ATTRIBUTES saAttr;
  3528. char *joined_argv;
  3529. saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  3530. saAttr.bInheritHandle = TRUE;
  3531. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  3532. saAttr.lpSecurityDescriptor = NULL;
  3533. /* Assume failure to start process */
  3534. status = PROCESS_STATUS_ERROR;
  3535. /* Set up pipe for stdout */
  3536. if (!CreatePipe(&stdout_pipe_read, &stdout_pipe_write, &saAttr, 0)) {
  3537. log_warn(LD_GENERAL,
  3538. "Failed to create pipe for stdout communication with child process: %s",
  3539. format_win32_error(GetLastError()));
  3540. return status;
  3541. }
  3542. if (!SetHandleInformation(stdout_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  3543. log_warn(LD_GENERAL,
  3544. "Failed to configure pipe for stdout communication with child "
  3545. "process: %s", format_win32_error(GetLastError()));
  3546. return status;
  3547. }
  3548. /* Set up pipe for stderr */
  3549. if (!CreatePipe(&stderr_pipe_read, &stderr_pipe_write, &saAttr, 0)) {
  3550. log_warn(LD_GENERAL,
  3551. "Failed to create pipe for stderr communication with child process: %s",
  3552. format_win32_error(GetLastError()));
  3553. return status;
  3554. }
  3555. if (!SetHandleInformation(stderr_pipe_read, HANDLE_FLAG_INHERIT, 0)) {
  3556. log_warn(LD_GENERAL,
  3557. "Failed to configure pipe for stderr communication with child "
  3558. "process: %s", format_win32_error(GetLastError()));
  3559. return status;
  3560. }
  3561. /* Set up pipe for stdin */
  3562. if (!CreatePipe(&stdin_pipe_read, &stdin_pipe_write, &saAttr, 0)) {
  3563. log_warn(LD_GENERAL,
  3564. "Failed to create pipe for stdin communication with child process: %s",
  3565. format_win32_error(GetLastError()));
  3566. return status;
  3567. }
  3568. if (!SetHandleInformation(stdin_pipe_write, HANDLE_FLAG_INHERIT, 0)) {
  3569. log_warn(LD_GENERAL,
  3570. "Failed to configure pipe for stdin communication with child "
  3571. "process: %s", format_win32_error(GetLastError()));
  3572. return status;
  3573. }
  3574. /* Create the child process */
  3575. /* Windows expects argv to be a whitespace delimited string, so join argv up
  3576. */
  3577. joined_argv = tor_join_win_cmdline(argv);
  3578. process_handle = process_handle_new();
  3579. process_handle->status = status;
  3580. ZeroMemory(&(process_handle->pid), sizeof(PROCESS_INFORMATION));
  3581. ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
  3582. siStartInfo.cb = sizeof(STARTUPINFO);
  3583. siStartInfo.hStdError = stderr_pipe_write;
  3584. siStartInfo.hStdOutput = stdout_pipe_write;
  3585. siStartInfo.hStdInput = stdin_pipe_read;
  3586. siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
  3587. /* Create the child process */
  3588. retval = CreateProcessA(filename, // module name
  3589. joined_argv, // command line
  3590. /* TODO: should we set explicit security attributes? (#2046, comment 5) */
  3591. NULL, // process security attributes
  3592. NULL, // primary thread security attributes
  3593. TRUE, // handles are inherited
  3594. /*(TODO: set CREATE_NEW CONSOLE/PROCESS_GROUP to make GetExitCodeProcess()
  3595. * work?) */
  3596. CREATE_NO_WINDOW, // creation flags
  3597. (env==NULL) ? NULL : env->windows_environment_block,
  3598. NULL, // use parent's current directory
  3599. &siStartInfo, // STARTUPINFO pointer
  3600. &(process_handle->pid)); // receives PROCESS_INFORMATION
  3601. tor_free(joined_argv);
  3602. if (!retval) {
  3603. log_warn(LD_GENERAL,
  3604. "Failed to create child process %s: %s", filename?filename:argv[0],
  3605. format_win32_error(GetLastError()));
  3606. tor_free(process_handle);
  3607. } else {
  3608. /* TODO: Close hProcess and hThread in process_handle->pid? */
  3609. process_handle->stdout_pipe = stdout_pipe_read;
  3610. process_handle->stderr_pipe = stderr_pipe_read;
  3611. process_handle->stdin_pipe = stdin_pipe_write;
  3612. status = process_handle->status = PROCESS_STATUS_RUNNING;
  3613. }
  3614. /* TODO: Close pipes on exit */
  3615. *process_handle_out = process_handle;
  3616. return status;
  3617. #else /* !(defined(_WIN32)) */
  3618. pid_t pid;
  3619. int stdout_pipe[2];
  3620. int stderr_pipe[2];
  3621. int stdin_pipe[2];
  3622. int fd, retval;
  3623. process_handle_t *process_handle;
  3624. int status;
  3625. const char *error_message = SPAWN_ERROR_MESSAGE;
  3626. size_t error_message_length;
  3627. /* Represents where in the process of spawning the program is;
  3628. this is used for printing out the error message */
  3629. unsigned char child_state = CHILD_STATE_INIT;
  3630. char hex_errno[HEX_ERRNO_SIZE + 2]; /* + 1 should be sufficient actually */
  3631. static int max_fd = -1;
  3632. status = PROCESS_STATUS_ERROR;
  3633. /* We do the strlen here because strlen() is not signal handler safe,
  3634. and we are not allowed to use unsafe functions between fork and exec */
  3635. error_message_length = strlen(error_message);
  3636. // child_state = CHILD_STATE_PIPE;
  3637. /* Set up pipe for redirecting stdout, stderr, and stdin of child */
  3638. retval = pipe(stdout_pipe);
  3639. if (-1 == retval) {
  3640. log_warn(LD_GENERAL,
  3641. "Failed to set up pipe for stdout communication with child process: %s",
  3642. strerror(errno));
  3643. return status;
  3644. }
  3645. retval = pipe(stderr_pipe);
  3646. if (-1 == retval) {
  3647. log_warn(LD_GENERAL,
  3648. "Failed to set up pipe for stderr communication with child process: %s",
  3649. strerror(errno));
  3650. close(stdout_pipe[0]);
  3651. close(stdout_pipe[1]);
  3652. return status;
  3653. }
  3654. retval = pipe(stdin_pipe);
  3655. if (-1 == retval) {
  3656. log_warn(LD_GENERAL,
  3657. "Failed to set up pipe for stdin communication with child process: %s",
  3658. strerror(errno));
  3659. close(stdout_pipe[0]);
  3660. close(stdout_pipe[1]);
  3661. close(stderr_pipe[0]);
  3662. close(stderr_pipe[1]);
  3663. return status;
  3664. }
  3665. // child_state = CHILD_STATE_MAXFD;
  3666. #ifdef _SC_OPEN_MAX
  3667. if (-1 == max_fd) {
  3668. max_fd = (int) sysconf(_SC_OPEN_MAX);
  3669. if (max_fd == -1) {
  3670. max_fd = DEFAULT_MAX_FD;
  3671. log_warn(LD_GENERAL,
  3672. "Cannot find maximum file descriptor, assuming %d", max_fd);
  3673. }
  3674. }
  3675. #else /* !(defined(_SC_OPEN_MAX)) */
  3676. max_fd = DEFAULT_MAX_FD;
  3677. #endif /* defined(_SC_OPEN_MAX) */
  3678. // child_state = CHILD_STATE_FORK;
  3679. pid = fork();
  3680. if (0 == pid) {
  3681. /* In child */
  3682. #if defined(HAVE_SYS_PRCTL_H) && defined(__linux__)
  3683. /* Attempt to have the kernel issue a SIGTERM if the parent
  3684. * goes away. Certain attributes of the binary being execve()ed
  3685. * will clear this during the execve() call, but it's better
  3686. * than nothing.
  3687. */
  3688. prctl(PR_SET_PDEATHSIG, SIGTERM);
  3689. #endif /* defined(HAVE_SYS_PRCTL_H) && defined(__linux__) */
  3690. child_state = CHILD_STATE_DUPOUT;
  3691. /* Link child stdout to the write end of the pipe */
  3692. retval = dup2(stdout_pipe[1], STDOUT_FILENO);
  3693. if (-1 == retval)
  3694. goto error;
  3695. child_state = CHILD_STATE_DUPERR;
  3696. /* Link child stderr to the write end of the pipe */
  3697. retval = dup2(stderr_pipe[1], STDERR_FILENO);
  3698. if (-1 == retval)
  3699. goto error;
  3700. child_state = CHILD_STATE_DUPIN;
  3701. /* Link child stdin to the read end of the pipe */
  3702. retval = dup2(stdin_pipe[0], STDIN_FILENO);
  3703. if (-1 == retval)
  3704. goto error;
  3705. // child_state = CHILD_STATE_CLOSEFD;
  3706. close(stderr_pipe[0]);
  3707. close(stderr_pipe[1]);
  3708. close(stdout_pipe[0]);
  3709. close(stdout_pipe[1]);
  3710. close(stdin_pipe[0]);
  3711. close(stdin_pipe[1]);
  3712. /* Close all other fds, including the read end of the pipe */
  3713. /* XXX: We should now be doing enough FD_CLOEXEC setting to make
  3714. * this needless. */
  3715. for (fd = STDERR_FILENO + 1; fd < max_fd; fd++) {
  3716. close(fd);
  3717. }
  3718. // child_state = CHILD_STATE_EXEC;
  3719. /* Call the requested program. We need the cast because
  3720. execvp doesn't define argv as const, even though it
  3721. does not modify the arguments */
  3722. if (env)
  3723. execve(filename, (char *const *) argv, env->unixoid_environment_block);
  3724. else {
  3725. static char *new_env[] = { NULL };
  3726. execve(filename, (char *const *) argv, new_env);
  3727. }
  3728. /* If we got here, the exec or open(/dev/null) failed */
  3729. child_state = CHILD_STATE_FAILEXEC;
  3730. error:
  3731. {
  3732. /* XXX: are we leaking fds from the pipe? */
  3733. int n, err=0;
  3734. ssize_t nbytes;
  3735. n = format_helper_exit_status(child_state, errno, hex_errno);
  3736. if (n >= 0) {
  3737. /* Write the error message. GCC requires that we check the return
  3738. value, but there is nothing we can do if it fails */
  3739. /* TODO: Don't use STDOUT, use a pipe set up just for this purpose */
  3740. nbytes = write(STDOUT_FILENO, error_message, error_message_length);
  3741. err = (nbytes < 0);
  3742. nbytes = write(STDOUT_FILENO, hex_errno, n);
  3743. err += (nbytes < 0);
  3744. }
  3745. _exit(err?254:255); // exit ok: in child.
  3746. }
  3747. /* Never reached, but avoids compiler warning */
  3748. return status; // LCOV_EXCL_LINE
  3749. }
  3750. /* In parent */
  3751. if (-1 == pid) {
  3752. log_warn(LD_GENERAL, "Failed to fork child process: %s", strerror(errno));
  3753. close(stdin_pipe[0]);
  3754. close(stdin_pipe[1]);
  3755. close(stdout_pipe[0]);
  3756. close(stdout_pipe[1]);
  3757. close(stderr_pipe[0]);
  3758. close(stderr_pipe[1]);
  3759. return status;
  3760. }
  3761. process_handle = process_handle_new();
  3762. process_handle->status = status;
  3763. process_handle->pid = pid;
  3764. /* TODO: If the child process forked but failed to exec, waitpid it */
  3765. /* Return read end of the pipes to caller, and close write end */
  3766. process_handle->stdout_pipe = stdout_pipe[0];
  3767. retval = close(stdout_pipe[1]);
  3768. if (-1 == retval) {
  3769. log_warn(LD_GENERAL,
  3770. "Failed to close write end of stdout pipe in parent process: %s",
  3771. strerror(errno));
  3772. }
  3773. process_handle->waitpid_cb = set_waitpid_callback(pid,
  3774. process_handle_waitpid_cb,
  3775. process_handle);
  3776. process_handle->stderr_pipe = stderr_pipe[0];
  3777. retval = close(stderr_pipe[1]);
  3778. if (-1 == retval) {
  3779. log_warn(LD_GENERAL,
  3780. "Failed to close write end of stderr pipe in parent process: %s",
  3781. strerror(errno));
  3782. }
  3783. /* Return write end of the stdin pipe to caller, and close the read end */
  3784. process_handle->stdin_pipe = stdin_pipe[1];
  3785. retval = close(stdin_pipe[0]);
  3786. if (-1 == retval) {
  3787. log_warn(LD_GENERAL,
  3788. "Failed to close read end of stdin pipe in parent process: %s",
  3789. strerror(errno));
  3790. }
  3791. status = process_handle->status = PROCESS_STATUS_RUNNING;
  3792. /* Set stdin/stdout/stderr pipes to be non-blocking */
  3793. if (fcntl(process_handle->stdout_pipe, F_SETFL, O_NONBLOCK) < 0 ||
  3794. fcntl(process_handle->stderr_pipe, F_SETFL, O_NONBLOCK) < 0 ||
  3795. fcntl(process_handle->stdin_pipe, F_SETFL, O_NONBLOCK) < 0) {
  3796. log_warn(LD_GENERAL, "Failed to set stderror/stdout/stdin pipes "
  3797. "nonblocking in parent process: %s", strerror(errno));
  3798. }
  3799. *process_handle_out = process_handle;
  3800. return status;
  3801. #endif /* defined(_WIN32) */
  3802. }
  3803. /** Destroy all resources allocated by the process handle in
  3804. * <b>process_handle</b>.
  3805. * If <b>also_terminate_process</b> is true, also terminate the
  3806. * process of the process handle. */
  3807. MOCK_IMPL(void,
  3808. tor_process_handle_destroy,(process_handle_t *process_handle,
  3809. int also_terminate_process))
  3810. {
  3811. if (!process_handle)
  3812. return;
  3813. if (also_terminate_process) {
  3814. if (tor_terminate_process(process_handle) < 0) {
  3815. const char *errstr =
  3816. #ifdef _WIN32
  3817. format_win32_error(GetLastError());
  3818. #else
  3819. strerror(errno);
  3820. #endif
  3821. log_notice(LD_GENERAL, "Failed to terminate process with "
  3822. "PID '%d' ('%s').", tor_process_get_pid(process_handle),
  3823. errstr);
  3824. } else {
  3825. log_info(LD_GENERAL, "Terminated process with PID '%d'.",
  3826. tor_process_get_pid(process_handle));
  3827. }
  3828. }
  3829. process_handle->status = PROCESS_STATUS_NOTRUNNING;
  3830. #ifdef _WIN32
  3831. if (process_handle->stdout_pipe)
  3832. CloseHandle(process_handle->stdout_pipe);
  3833. if (process_handle->stderr_pipe)
  3834. CloseHandle(process_handle->stderr_pipe);
  3835. if (process_handle->stdin_pipe)
  3836. CloseHandle(process_handle->stdin_pipe);
  3837. #else /* !(defined(_WIN32)) */
  3838. close(process_handle->stdout_pipe);
  3839. close(process_handle->stderr_pipe);
  3840. close(process_handle->stdin_pipe);
  3841. clear_waitpid_callback(process_handle->waitpid_cb);
  3842. #endif /* defined(_WIN32) */
  3843. memset(process_handle, 0x0f, sizeof(process_handle_t));
  3844. tor_free(process_handle);
  3845. }
  3846. /** Get the exit code of a process specified by <b>process_handle</b> and store
  3847. * it in <b>exit_code</b>, if set to a non-NULL value. If <b>block</b> is set
  3848. * to true, the call will block until the process has exited. Otherwise if
  3849. * the process is still running, the function will return
  3850. * PROCESS_EXIT_RUNNING, and exit_code will be left unchanged. Returns
  3851. * PROCESS_EXIT_EXITED if the process did exit. If there is a failure,
  3852. * PROCESS_EXIT_ERROR will be returned and the contents of exit_code (if
  3853. * non-NULL) will be undefined. N.B. Under *nix operating systems, this will
  3854. * probably not work in Tor, because waitpid() is called in main.c to reap any
  3855. * terminated child processes.*/
  3856. int
  3857. tor_get_exit_code(process_handle_t *process_handle,
  3858. int block, int *exit_code)
  3859. {
  3860. #ifdef _WIN32
  3861. DWORD retval;
  3862. BOOL success;
  3863. if (block) {
  3864. /* Wait for the process to exit */
  3865. retval = WaitForSingleObject(process_handle->pid.hProcess, INFINITE);
  3866. if (retval != WAIT_OBJECT_0) {
  3867. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  3868. (int)retval, format_win32_error(GetLastError()));
  3869. return PROCESS_EXIT_ERROR;
  3870. }
  3871. } else {
  3872. retval = WaitForSingleObject(process_handle->pid.hProcess, 0);
  3873. if (WAIT_TIMEOUT == retval) {
  3874. /* Process has not exited */
  3875. return PROCESS_EXIT_RUNNING;
  3876. } else if (retval != WAIT_OBJECT_0) {
  3877. log_warn(LD_GENERAL, "WaitForSingleObject() failed (%d): %s",
  3878. (int)retval, format_win32_error(GetLastError()));
  3879. return PROCESS_EXIT_ERROR;
  3880. }
  3881. }
  3882. if (exit_code != NULL) {
  3883. success = GetExitCodeProcess(process_handle->pid.hProcess,
  3884. (PDWORD)exit_code);
  3885. if (!success) {
  3886. log_warn(LD_GENERAL, "GetExitCodeProcess() failed: %s",
  3887. format_win32_error(GetLastError()));
  3888. return PROCESS_EXIT_ERROR;
  3889. }
  3890. }
  3891. #else /* !(defined(_WIN32)) */
  3892. int stat_loc;
  3893. int retval;
  3894. if (process_handle->waitpid_cb) {
  3895. /* We haven't processed a SIGCHLD yet. */
  3896. retval = waitpid(process_handle->pid, &stat_loc, block?0:WNOHANG);
  3897. if (retval == process_handle->pid) {
  3898. clear_waitpid_callback(process_handle->waitpid_cb);
  3899. process_handle->waitpid_cb = NULL;
  3900. process_handle->waitpid_exit_status = stat_loc;
  3901. }
  3902. } else {
  3903. /* We already got a SIGCHLD for this process, and handled it. */
  3904. retval = process_handle->pid;
  3905. stat_loc = process_handle->waitpid_exit_status;
  3906. }
  3907. if (!block && 0 == retval) {
  3908. /* Process has not exited */
  3909. return PROCESS_EXIT_RUNNING;
  3910. } else if (retval != process_handle->pid) {
  3911. log_warn(LD_GENERAL, "waitpid() failed for PID %d: %s",
  3912. (int)process_handle->pid, strerror(errno));
  3913. return PROCESS_EXIT_ERROR;
  3914. }
  3915. if (!WIFEXITED(stat_loc)) {
  3916. log_warn(LD_GENERAL, "Process %d did not exit normally",
  3917. (int)process_handle->pid);
  3918. return PROCESS_EXIT_ERROR;
  3919. }
  3920. if (exit_code != NULL)
  3921. *exit_code = WEXITSTATUS(stat_loc);
  3922. #endif /* defined(_WIN32) */
  3923. return PROCESS_EXIT_EXITED;
  3924. }
  3925. /** Helper: return the number of characters in <b>s</b> preceding the first
  3926. * occurrence of <b>ch</b>. If <b>ch</b> does not occur in <b>s</b>, return
  3927. * the length of <b>s</b>. Should be equivalent to strspn(s, "ch"). */
  3928. static inline size_t
  3929. str_num_before(const char *s, char ch)
  3930. {
  3931. const char *cp = strchr(s, ch);
  3932. if (cp)
  3933. return cp - s;
  3934. else
  3935. return strlen(s);
  3936. }
  3937. /** Return non-zero iff getenv would consider <b>s1</b> and <b>s2</b>
  3938. * to have the same name as strings in a process's environment. */
  3939. int
  3940. environment_variable_names_equal(const char *s1, const char *s2)
  3941. {
  3942. size_t s1_name_len = str_num_before(s1, '=');
  3943. size_t s2_name_len = str_num_before(s2, '=');
  3944. return (s1_name_len == s2_name_len &&
  3945. tor_memeq(s1, s2, s1_name_len));
  3946. }
  3947. /** Free <b>env</b> (assuming it was produced by
  3948. * process_environment_make). */
  3949. void
  3950. process_environment_free_(process_environment_t *env)
  3951. {
  3952. if (env == NULL) return;
  3953. /* As both an optimization hack to reduce consing on Unixoid systems
  3954. * and a nice way to ensure that some otherwise-Windows-specific
  3955. * code will always get tested before changes to it get merged, the
  3956. * strings which env->unixoid_environment_block points to are packed
  3957. * into env->windows_environment_block. */
  3958. tor_free(env->unixoid_environment_block);
  3959. tor_free(env->windows_environment_block);
  3960. tor_free(env);
  3961. }
  3962. /** Make a process_environment_t containing the environment variables
  3963. * specified in <b>env_vars</b> (as C strings of the form
  3964. * "NAME=VALUE"). */
  3965. process_environment_t *
  3966. process_environment_make(struct smartlist_t *env_vars)
  3967. {
  3968. process_environment_t *env = tor_malloc_zero(sizeof(process_environment_t));
  3969. int n_env_vars = smartlist_len(env_vars);
  3970. int i;
  3971. size_t total_env_length;
  3972. smartlist_t *env_vars_sorted;
  3973. tor_assert(n_env_vars + 1 != 0);
  3974. env->unixoid_environment_block = tor_calloc(n_env_vars + 1, sizeof(char *));
  3975. /* env->unixoid_environment_block is already NULL-terminated,
  3976. * because we assume that NULL == 0 (and check that during compilation). */
  3977. total_env_length = 1; /* terminating NUL of terminating empty string */
  3978. for (i = 0; i < n_env_vars; ++i) {
  3979. const char *s = smartlist_get(env_vars, (int)i);
  3980. size_t slen = strlen(s);
  3981. tor_assert(slen + 1 != 0);
  3982. tor_assert(slen + 1 < SIZE_MAX - total_env_length);
  3983. total_env_length += slen + 1;
  3984. }
  3985. env->windows_environment_block = tor_malloc_zero(total_env_length);
  3986. /* env->windows_environment_block is already
  3987. * (NUL-terminated-empty-string)-terminated. */
  3988. /* Some versions of Windows supposedly require that environment
  3989. * blocks be sorted. Or maybe some Windows programs (or their
  3990. * runtime libraries) fail to look up strings in non-sorted
  3991. * environment blocks.
  3992. *
  3993. * Also, sorting strings makes it easy to find duplicate environment
  3994. * variables and environment-variable strings without an '=' on all
  3995. * OSes, and they can cause badness. Let's complain about those. */
  3996. env_vars_sorted = smartlist_new();
  3997. smartlist_add_all(env_vars_sorted, env_vars);
  3998. smartlist_sort_strings(env_vars_sorted);
  3999. /* Now copy the strings into the environment blocks. */
  4000. {
  4001. char *cp = env->windows_environment_block;
  4002. const char *prev_env_var = NULL;
  4003. for (i = 0; i < n_env_vars; ++i) {
  4004. const char *s = smartlist_get(env_vars_sorted, (int)i);
  4005. size_t slen = strlen(s);
  4006. size_t s_name_len = str_num_before(s, '=');
  4007. if (s_name_len == slen) {
  4008. log_warn(LD_GENERAL,
  4009. "Preparing an environment containing a variable "
  4010. "without a value: %s",
  4011. s);
  4012. }
  4013. if (prev_env_var != NULL &&
  4014. environment_variable_names_equal(s, prev_env_var)) {
  4015. log_warn(LD_GENERAL,
  4016. "Preparing an environment containing two variables "
  4017. "with the same name: %s and %s",
  4018. prev_env_var, s);
  4019. }
  4020. prev_env_var = s;
  4021. /* Actually copy the string into the environment. */
  4022. memcpy(cp, s, slen+1);
  4023. env->unixoid_environment_block[i] = cp;
  4024. cp += slen+1;
  4025. }
  4026. tor_assert(cp == env->windows_environment_block + total_env_length - 1);
  4027. }
  4028. smartlist_free(env_vars_sorted);
  4029. return env;
  4030. }
  4031. /** Return a newly allocated smartlist containing every variable in
  4032. * this process's environment, as a NUL-terminated string of the form
  4033. * "NAME=VALUE". Note that on some/many/most/all OSes, the parent
  4034. * process can put strings not of that form in our environment;
  4035. * callers should try to not get crashed by that.
  4036. *
  4037. * The returned strings are heap-allocated, and must be freed by the
  4038. * caller. */
  4039. struct smartlist_t *
  4040. get_current_process_environment_variables(void)
  4041. {
  4042. smartlist_t *sl = smartlist_new();
  4043. char **environ_tmp; /* Not const char ** ? Really? */
  4044. for (environ_tmp = get_environment(); *environ_tmp; ++environ_tmp) {
  4045. smartlist_add_strdup(sl, *environ_tmp);
  4046. }
  4047. return sl;
  4048. }
  4049. /** For each string s in <b>env_vars</b> such that
  4050. * environment_variable_names_equal(s, <b>new_var</b>), remove it; if
  4051. * <b>free_p</b> is non-zero, call <b>free_old</b>(s). If
  4052. * <b>new_var</b> contains '=', insert it into <b>env_vars</b>. */
  4053. void
  4054. set_environment_variable_in_smartlist(struct smartlist_t *env_vars,
  4055. const char *new_var,
  4056. void (*free_old)(void*),
  4057. int free_p)
  4058. {
  4059. SMARTLIST_FOREACH_BEGIN(env_vars, const char *, s) {
  4060. if (environment_variable_names_equal(s, new_var)) {
  4061. SMARTLIST_DEL_CURRENT(env_vars, s);
  4062. if (free_p) {
  4063. free_old((void *)s);
  4064. }
  4065. }
  4066. } SMARTLIST_FOREACH_END(s);
  4067. if (strchr(new_var, '=') != NULL) {
  4068. smartlist_add(env_vars, (void *)new_var);
  4069. }
  4070. }
  4071. #ifdef _WIN32
  4072. /** Read from a handle <b>h</b> into <b>buf</b>, up to <b>count</b> bytes. If
  4073. * <b>hProcess</b> is NULL, the function will return immediately if there is
  4074. * nothing more to read. Otherwise <b>hProcess</b> should be set to the handle
  4075. * to the process owning the <b>h</b>. In this case, the function will exit
  4076. * only once the process has exited, or <b>count</b> bytes are read. Returns
  4077. * the number of bytes read, or -1 on error. */
  4078. ssize_t
  4079. tor_read_all_handle(HANDLE h, char *buf, size_t count,
  4080. const process_handle_t *process)
  4081. {
  4082. size_t numread = 0;
  4083. BOOL retval;
  4084. DWORD byte_count;
  4085. BOOL process_exited = FALSE;
  4086. if (count > SIZE_T_CEILING || count > SSIZE_MAX)
  4087. return -1;
  4088. while (numread < count) {
  4089. /* Check if there is anything to read */
  4090. retval = PeekNamedPipe(h, NULL, 0, NULL, &byte_count, NULL);
  4091. if (!retval) {
  4092. log_warn(LD_GENERAL,
  4093. "Failed to peek from handle: %s",
  4094. format_win32_error(GetLastError()));
  4095. return -1;
  4096. } else if (0 == byte_count) {
  4097. /* Nothing available: process exited or it is busy */
  4098. /* Exit if we don't know whether the process is running */
  4099. if (NULL == process)
  4100. break;
  4101. /* The process exited and there's nothing left to read from it */
  4102. if (process_exited)
  4103. break;
  4104. /* If process is not running, check for output one more time in case
  4105. it wrote something after the peek was performed. Otherwise keep on
  4106. waiting for output */
  4107. tor_assert(process != NULL);
  4108. byte_count = WaitForSingleObject(process->pid.hProcess, 0);
  4109. if (WAIT_TIMEOUT != byte_count)
  4110. process_exited = TRUE;
  4111. continue;
  4112. }
  4113. /* There is data to read; read it */
  4114. retval = ReadFile(h, buf+numread, count-numread, &byte_count, NULL);
  4115. tor_assert(byte_count + numread <= count);
  4116. if (!retval) {
  4117. log_warn(LD_GENERAL, "Failed to read from handle: %s",
  4118. format_win32_error(GetLastError()));
  4119. return -1;
  4120. } else if (0 == byte_count) {
  4121. /* End of file */
  4122. break;
  4123. }
  4124. numread += byte_count;
  4125. }
  4126. return (ssize_t)numread;
  4127. }
  4128. #else /* !(defined(_WIN32)) */
  4129. /** Read from a handle <b>fd</b> into <b>buf</b>, up to <b>count</b> bytes. If
  4130. * <b>process</b> is NULL, the function will return immediately if there is
  4131. * nothing more to read. Otherwise data will be read until end of file, or
  4132. * <b>count</b> bytes are read. Returns the number of bytes read, or -1 on
  4133. * error. Sets <b>eof</b> to true if <b>eof</b> is not NULL and the end of the
  4134. * file has been reached. */
  4135. ssize_t
  4136. tor_read_all_handle(int fd, char *buf, size_t count,
  4137. const process_handle_t *process,
  4138. int *eof)
  4139. {
  4140. size_t numread = 0;
  4141. ssize_t result;
  4142. if (eof)
  4143. *eof = 0;
  4144. if (count > SIZE_T_CEILING || count > SSIZE_MAX)
  4145. return -1;
  4146. while (numread < count) {
  4147. result = read(fd, buf+numread, count-numread);
  4148. if (result == 0) {
  4149. log_debug(LD_GENERAL, "read() reached end of file");
  4150. if (eof)
  4151. *eof = 1;
  4152. break;
  4153. } else if (result < 0 && errno == EAGAIN) {
  4154. if (process)
  4155. continue;
  4156. else
  4157. break;
  4158. } else if (result < 0) {
  4159. log_warn(LD_GENERAL, "read() failed: %s", strerror(errno));
  4160. return -1;
  4161. }
  4162. numread += result;
  4163. }
  4164. log_debug(LD_GENERAL, "read() read %d bytes from handle", (int)numread);
  4165. return (ssize_t)numread;
  4166. }
  4167. #endif /* defined(_WIN32) */
  4168. /** Read from stdout of a process until the process exits. */
  4169. ssize_t
  4170. tor_read_all_from_process_stdout(const process_handle_t *process_handle,
  4171. char *buf, size_t count)
  4172. {
  4173. #ifdef _WIN32
  4174. return tor_read_all_handle(process_handle->stdout_pipe, buf, count,
  4175. process_handle);
  4176. #else
  4177. return tor_read_all_handle(process_handle->stdout_pipe, buf, count,
  4178. process_handle, NULL);
  4179. #endif /* defined(_WIN32) */
  4180. }
  4181. /** Read from stdout of a process until the process exits. */
  4182. ssize_t
  4183. tor_read_all_from_process_stderr(const process_handle_t *process_handle,
  4184. char *buf, size_t count)
  4185. {
  4186. #ifdef _WIN32
  4187. return tor_read_all_handle(process_handle->stderr_pipe, buf, count,
  4188. process_handle);
  4189. #else
  4190. return tor_read_all_handle(process_handle->stderr_pipe, buf, count,
  4191. process_handle, NULL);
  4192. #endif /* defined(_WIN32) */
  4193. }
  4194. /** Split buf into lines, and add to smartlist. The buffer <b>buf</b> will be
  4195. * modified. The resulting smartlist will consist of pointers to buf, so there
  4196. * is no need to free the contents of sl. <b>buf</b> must be a NUL-terminated
  4197. * string. <b>len</b> should be set to the length of the buffer excluding the
  4198. * NUL. Non-printable characters (including NUL) will be replaced with "." */
  4199. int
  4200. tor_split_lines(smartlist_t *sl, char *buf, int len)
  4201. {
  4202. /* Index in buf of the start of the current line */
  4203. int start = 0;
  4204. /* Index in buf of the current character being processed */
  4205. int cur = 0;
  4206. /* Are we currently in a line */
  4207. char in_line = 0;
  4208. /* Loop over string */
  4209. while (cur < len) {
  4210. /* Loop until end of line or end of string */
  4211. for (; cur < len; cur++) {
  4212. if (in_line) {
  4213. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  4214. /* End of line */
  4215. buf[cur] = '\0';
  4216. /* Point cur to the next line */
  4217. cur++;
  4218. /* Line starts at start and ends with a nul */
  4219. break;
  4220. } else {
  4221. if (!TOR_ISPRINT(buf[cur]))
  4222. buf[cur] = '.';
  4223. }
  4224. } else {
  4225. if ('\r' == buf[cur] || '\n' == buf[cur]) {
  4226. /* Skip leading vertical space */
  4227. ;
  4228. } else {
  4229. in_line = 1;
  4230. start = cur;
  4231. if (!TOR_ISPRINT(buf[cur]))
  4232. buf[cur] = '.';
  4233. }
  4234. }
  4235. }
  4236. /* We are at the end of the line or end of string. If in_line is true there
  4237. * is a line which starts at buf+start and ends at a NUL. cur points to
  4238. * the character after the NUL. */
  4239. if (in_line)
  4240. smartlist_add(sl, (void *)(buf+start));
  4241. in_line = 0;
  4242. }
  4243. return smartlist_len(sl);
  4244. }
  4245. /** Return a string corresponding to <b>stream_status</b>. */
  4246. const char *
  4247. stream_status_to_string(enum stream_status stream_status)
  4248. {
  4249. switch (stream_status) {
  4250. case IO_STREAM_OKAY:
  4251. return "okay";
  4252. case IO_STREAM_EAGAIN:
  4253. return "temporarily unavailable";
  4254. case IO_STREAM_TERM:
  4255. return "terminated";
  4256. case IO_STREAM_CLOSED:
  4257. return "closed";
  4258. default:
  4259. tor_fragile_assert();
  4260. return "unknown";
  4261. }
  4262. }
  4263. #ifdef _WIN32
  4264. /** Return a smartlist containing lines outputted from
  4265. * <b>handle</b>. Return NULL on error, and set
  4266. * <b>stream_status_out</b> appropriately. */
  4267. MOCK_IMPL(smartlist_t *,
  4268. tor_get_lines_from_handle, (HANDLE *handle,
  4269. enum stream_status *stream_status_out))
  4270. {
  4271. int pos;
  4272. char stdout_buf[600] = {0};
  4273. smartlist_t *lines = NULL;
  4274. tor_assert(stream_status_out);
  4275. *stream_status_out = IO_STREAM_TERM;
  4276. pos = tor_read_all_handle(handle, stdout_buf, sizeof(stdout_buf) - 1, NULL);
  4277. if (pos < 0) {
  4278. *stream_status_out = IO_STREAM_TERM;
  4279. return NULL;
  4280. }
  4281. if (pos == 0) {
  4282. *stream_status_out = IO_STREAM_EAGAIN;
  4283. return NULL;
  4284. }
  4285. /* End with a null even if there isn't a \r\n at the end */
  4286. /* TODO: What if this is a partial line? */
  4287. stdout_buf[pos] = '\0';
  4288. /* Split up the buffer */
  4289. lines = smartlist_new();
  4290. tor_split_lines(lines, stdout_buf, pos);
  4291. /* Currently 'lines' is populated with strings residing on the
  4292. stack. Replace them with their exact copies on the heap: */
  4293. SMARTLIST_FOREACH(lines, char *, line,
  4294. SMARTLIST_REPLACE_CURRENT(lines, line, tor_strdup(line)));
  4295. *stream_status_out = IO_STREAM_OKAY;
  4296. return lines;
  4297. }
  4298. #else /* !(defined(_WIN32)) */
  4299. /** Return a smartlist containing lines outputted from
  4300. * <b>fd</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, (int fd, enum stream_status *stream_status_out))
  4304. {
  4305. enum stream_status stream_status;
  4306. char stdout_buf[400];
  4307. smartlist_t *lines = NULL;
  4308. while (1) {
  4309. memset(stdout_buf, 0, sizeof(stdout_buf));
  4310. stream_status = get_string_from_pipe(fd,
  4311. stdout_buf, sizeof(stdout_buf) - 1);
  4312. if (stream_status != IO_STREAM_OKAY)
  4313. goto done;
  4314. if (!lines) lines = smartlist_new();
  4315. smartlist_split_string(lines, stdout_buf, "\n", 0, 0);
  4316. }
  4317. done:
  4318. *stream_status_out = stream_status;
  4319. return lines;
  4320. }
  4321. #endif /* defined(_WIN32) */
  4322. /** Reads from <b>fd</b> and stores input in <b>buf_out</b> making
  4323. * sure it's below <b>count</b> bytes.
  4324. * If the string has a trailing newline, we strip it off.
  4325. *
  4326. * This function is specifically created to handle input from managed
  4327. * proxies, according to the pluggable transports spec. Make sure it
  4328. * fits your needs before using it.
  4329. *
  4330. * Returns:
  4331. * IO_STREAM_CLOSED: If the stream is closed.
  4332. * IO_STREAM_EAGAIN: If there is nothing to read and we should check back
  4333. * later.
  4334. * IO_STREAM_TERM: If something is wrong with the stream.
  4335. * IO_STREAM_OKAY: If everything went okay and we got a string
  4336. * in <b>buf_out</b>. */
  4337. enum stream_status
  4338. get_string_from_pipe(int fd, char *buf_out, size_t count)
  4339. {
  4340. ssize_t ret;
  4341. tor_assert(count <= INT_MAX);
  4342. ret = read(fd, buf_out, count);
  4343. if (ret == 0)
  4344. return IO_STREAM_CLOSED;
  4345. else if (ret < 0 && errno == EAGAIN)
  4346. return IO_STREAM_EAGAIN;
  4347. else if (ret < 0)
  4348. return IO_STREAM_TERM;
  4349. if (buf_out[ret - 1] == '\n') {
  4350. /* Remove the trailing newline */
  4351. buf_out[ret - 1] = '\0';
  4352. } else
  4353. buf_out[ret] = '\0';
  4354. return IO_STREAM_OKAY;
  4355. }
  4356. /** Initialize the insecure RNG <b>rng</b> from a seed value <b>seed</b>. */
  4357. void
  4358. tor_init_weak_random(tor_weak_rng_t *rng, unsigned seed)
  4359. {
  4360. rng->state = (uint32_t)(seed & 0x7fffffff);
  4361. }
  4362. /** Return a randomly chosen value in the range 0..TOR_WEAK_RANDOM_MAX based
  4363. * on the RNG state of <b>rng</b>. This entropy will not be cryptographically
  4364. * strong; do not rely on it for anything an adversary should not be able to
  4365. * predict. */
  4366. int32_t
  4367. tor_weak_random(tor_weak_rng_t *rng)
  4368. {
  4369. /* Here's a linear congruential generator. OpenBSD and glibc use these
  4370. * parameters; they aren't too bad, and should have maximal period over the
  4371. * range 0..INT32_MAX. We don't want to use the platform rand() or random(),
  4372. * since some platforms have bad weak RNGs that only return values in the
  4373. * range 0..INT16_MAX, which just isn't enough. */
  4374. rng->state = (rng->state * 1103515245 + 12345) & 0x7fffffff;
  4375. return (int32_t) rng->state;
  4376. }
  4377. /** Return a random number in the range [0 , <b>top</b>). {That is, the range
  4378. * of integers i such that 0 <= i < top.} Chooses uniformly. Requires that
  4379. * top is greater than 0. This randomness is not cryptographically strong; do
  4380. * not rely on it for anything an adversary should not be able to predict. */
  4381. int32_t
  4382. tor_weak_random_range(tor_weak_rng_t *rng, int32_t top)
  4383. {
  4384. /* We don't want to just do tor_weak_random() % top, since random() is often
  4385. * implemented with an LCG whose modulus is a power of 2, and those are
  4386. * cyclic in their low-order bits. */
  4387. int divisor, result;
  4388. tor_assert(top > 0);
  4389. divisor = TOR_WEAK_RANDOM_MAX / top;
  4390. do {
  4391. result = (int32_t)(tor_weak_random(rng) / divisor);
  4392. } while (result >= top);
  4393. return result;
  4394. }
  4395. /** Cast a given double value to a int64_t. Return 0 if number is NaN.
  4396. * Returns either INT64_MIN or INT64_MAX if number is outside of the int64_t
  4397. * range. */
  4398. int64_t
  4399. clamp_double_to_int64(double number)
  4400. {
  4401. int exponent;
  4402. #if defined(MINGW_ANY) && GCC_VERSION >= 409
  4403. /*
  4404. Mingw's math.h uses gcc's __builtin_choose_expr() facility to declare
  4405. isnan, isfinite, and signbit. But as implemented in at least some
  4406. versions of gcc, __builtin_choose_expr() can generate type warnings
  4407. even from branches that are not taken. So, suppress those warnings.
  4408. */
  4409. #define PROBLEMATIC_FLOAT_CONVERSION_WARNING
  4410. DISABLE_GCC_WARNING(float-conversion)
  4411. #endif /* defined(MINGW_ANY) && GCC_VERSION >= 409 */
  4412. /*
  4413. With clang 4.0 we apparently run into "double promotion" warnings here,
  4414. since clang thinks we're promoting a double to a long double.
  4415. */
  4416. #if defined(__clang__)
  4417. #if __has_warning("-Wdouble-promotion")
  4418. #define PROBLEMATIC_DOUBLE_PROMOTION_WARNING
  4419. DISABLE_GCC_WARNING(double-promotion)
  4420. #endif
  4421. #endif /* defined(__clang__) */
  4422. /* NaN is a special case that can't be used with the logic below. */
  4423. if (isnan(number)) {
  4424. return 0;
  4425. }
  4426. /* Time to validate if result can overflows a int64_t value. Fun with
  4427. * float! Find that exponent exp such that
  4428. * number == x * 2^exp
  4429. * for some x with abs(x) in [0.5, 1.0). Note that this implies that the
  4430. * magnitude of number is strictly less than 2^exp.
  4431. *
  4432. * If number is infinite, the call to frexp is legal but the contents of
  4433. * are exponent unspecified. */
  4434. frexp(number, &exponent);
  4435. /* If the magnitude of number is strictly less than 2^63, the truncated
  4436. * version of number is guaranteed to be representable. The only
  4437. * representable integer for which this is not the case is INT64_MIN, but
  4438. * it is covered by the logic below. */
  4439. if (isfinite(number) && exponent <= 63) {
  4440. return (int64_t)number;
  4441. }
  4442. /* Handle infinities and finite numbers with magnitude >= 2^63. */
  4443. return signbit(number) ? INT64_MIN : INT64_MAX;
  4444. #ifdef PROBLEMATIC_DOUBLE_PROMOTION_WARNING
  4445. ENABLE_GCC_WARNING(double-promotion)
  4446. #endif
  4447. #ifdef PROBLEMATIC_FLOAT_CONVERSION_WARNING
  4448. ENABLE_GCC_WARNING(float-conversion)
  4449. #endif
  4450. }
  4451. /** Return a uint64_t value from <b>a</b> in network byte order. */
  4452. uint64_t
  4453. tor_htonll(uint64_t a)
  4454. {
  4455. #ifdef WORDS_BIGENDIAN
  4456. /* Big endian. */
  4457. return a;
  4458. #else /* WORDS_BIGENDIAN */
  4459. /* Little endian. The worst... */
  4460. return htonl((uint32_t)(a>>32)) |
  4461. (((uint64_t)htonl((uint32_t)a))<<32);
  4462. #endif /* defined(WORDS_BIGENDIAN) */
  4463. }
  4464. /** Return a uint64_t value from <b>a</b> in host byte order. */
  4465. uint64_t
  4466. tor_ntohll(uint64_t a)
  4467. {
  4468. return tor_htonll(a);
  4469. }