util.c 152 KB

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