util.c 155 KB

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