util.c 162 KB

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