util.c 158 KB

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