util.c 155 KB

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