util.c 160 KB

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