util.c 155 KB

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