util.c 156 KB

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