config.c 210 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2013, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file config.c
  8. * \brief Code to parse and interpret configuration files.
  9. **/
  10. #define CONFIG_PRIVATE
  11. #include "or.h"
  12. #include "addressmap.h"
  13. #include "channel.h"
  14. #include "circuitbuild.h"
  15. #include "circuitlist.h"
  16. #include "circuitmux.h"
  17. #include "circuitmux_ewma.h"
  18. #include "config.h"
  19. #include "connection.h"
  20. #include "connection_edge.h"
  21. #include "connection_or.h"
  22. #include "control.h"
  23. #include "confparse.h"
  24. #include "cpuworker.h"
  25. #include "dirserv.h"
  26. #include "dirvote.h"
  27. #include "dns.h"
  28. #include "entrynodes.h"
  29. #include "geoip.h"
  30. #include "hibernate.h"
  31. #include "main.h"
  32. #include "networkstatus.h"
  33. #include "nodelist.h"
  34. #include "policies.h"
  35. #include "relay.h"
  36. #include "rendclient.h"
  37. #include "rendservice.h"
  38. #include "rephist.h"
  39. #include "router.h"
  40. #include "util.h"
  41. #include "routerlist.h"
  42. #include "routerset.h"
  43. #include "statefile.h"
  44. #include "transports.h"
  45. #ifdef _WIN32
  46. #include <shlobj.h>
  47. #endif
  48. #include "procmon.h"
  49. /* From main.c */
  50. extern int quiet_level;
  51. /** A list of abbreviations and aliases to map command-line options, obsolete
  52. * option names, or alternative option names, to their current values. */
  53. static config_abbrev_t option_abbrevs_[] = {
  54. PLURAL(AuthDirBadDirCC),
  55. PLURAL(AuthDirBadExitCC),
  56. PLURAL(AuthDirInvalidCC),
  57. PLURAL(AuthDirRejectCC),
  58. PLURAL(ExitNode),
  59. PLURAL(EntryNode),
  60. PLURAL(ExcludeNode),
  61. PLURAL(FirewallPort),
  62. PLURAL(LongLivedPort),
  63. PLURAL(HiddenServiceNode),
  64. PLURAL(HiddenServiceExcludeNode),
  65. PLURAL(NumCPU),
  66. PLURAL(RendNode),
  67. PLURAL(RendExcludeNode),
  68. PLURAL(StrictEntryNode),
  69. PLURAL(StrictExitNode),
  70. PLURAL(StrictNode),
  71. { "l", "Log", 1, 0},
  72. { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
  73. { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
  74. { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
  75. { "BandwidthRateBytes", "BandwidthRate", 0, 0},
  76. { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
  77. { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
  78. { "DirServer", "DirAuthority", 0, 0}, /* XXXX024 later, make this warn? */
  79. { "MaxConn", "ConnLimit", 0, 1},
  80. { "ORBindAddress", "ORListenAddress", 0, 0},
  81. { "DirBindAddress", "DirListenAddress", 0, 0},
  82. { "SocksBindAddress", "SocksListenAddress", 0, 0},
  83. { "UseHelperNodes", "UseEntryGuards", 0, 0},
  84. { "NumHelperNodes", "NumEntryGuards", 0, 0},
  85. { "UseEntryNodes", "UseEntryGuards", 0, 0},
  86. { "NumEntryNodes", "NumEntryGuards", 0, 0},
  87. { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
  88. { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
  89. { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0},
  90. { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
  91. { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
  92. { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
  93. { "StrictEntryNodes", "StrictNodes", 0, 1},
  94. { "StrictExitNodes", "StrictNodes", 0, 1},
  95. { "VirtualAddrNetwork", "VirtualAddrNetworkIPv4", 0, 0},
  96. { "_UseFilteringSSLBufferevents", "UseFilteringSSLBufferevents", 0, 1},
  97. { NULL, NULL, 0, 0},
  98. };
  99. /** An entry for config_vars: "The option <b>name</b> has type
  100. * CONFIG_TYPE_<b>conftype</b>, and corresponds to
  101. * or_options_t.<b>member</b>"
  102. */
  103. #define VAR(name,conftype,member,initvalue) \
  104. { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
  105. initvalue }
  106. /** As VAR, but the option name and member name are the same. */
  107. #define V(member,conftype,initvalue) \
  108. VAR(#member, conftype, member, initvalue)
  109. /** An entry for config_vars: "The option <b>name</b> is obsolete." */
  110. #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
  111. #define VPORT(member,conftype,initvalue) \
  112. VAR(#member, conftype, member ## _lines, initvalue)
  113. /** Array of configuration options. Until we disallow nonstandard
  114. * abbreviations, order is significant, since the first matching option will
  115. * be chosen first.
  116. */
  117. static config_var_t option_vars_[] = {
  118. OBSOLETE("AccountingMaxKB"),
  119. V(AccountingMax, MEMUNIT, "0 bytes"),
  120. V(AccountingStart, STRING, NULL),
  121. V(Address, STRING, NULL),
  122. V(AllowDotExit, BOOL, "0"),
  123. V(AllowInvalidNodes, CSV, "middle,rendezvous"),
  124. V(AllowNonRFC953Hostnames, BOOL, "0"),
  125. V(AllowSingleHopCircuits, BOOL, "0"),
  126. V(AllowSingleHopExits, BOOL, "0"),
  127. V(AlternateBridgeAuthority, LINELIST, NULL),
  128. V(AlternateDirAuthority, LINELIST, NULL),
  129. V(AlternateHSAuthority, LINELIST, NULL),
  130. V(AssumeReachable, BOOL, "0"),
  131. V(AuthDirBadDir, LINELIST, NULL),
  132. V(AuthDirBadDirCCs, CSV, ""),
  133. V(AuthDirBadExit, LINELIST, NULL),
  134. V(AuthDirBadExitCCs, CSV, ""),
  135. V(AuthDirInvalid, LINELIST, NULL),
  136. V(AuthDirInvalidCCs, CSV, ""),
  137. V(AuthDirFastGuarantee, MEMUNIT, "100 KB"),
  138. V(AuthDirGuardBWGuarantee, MEMUNIT, "250 KB"),
  139. V(AuthDirReject, LINELIST, NULL),
  140. V(AuthDirRejectCCs, CSV, ""),
  141. V(AuthDirRejectUnlisted, BOOL, "0"),
  142. V(AuthDirListBadDirs, BOOL, "0"),
  143. V(AuthDirListBadExits, BOOL, "0"),
  144. V(AuthDirMaxServersPerAddr, UINT, "2"),
  145. V(AuthDirMaxServersPerAuthAddr,UINT, "5"),
  146. V(AuthDirHasIPv6Connectivity, BOOL, "0"),
  147. VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
  148. V(AutomapHostsOnResolve, BOOL, "0"),
  149. V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
  150. V(AvoidDiskWrites, BOOL, "0"),
  151. V(BandwidthBurst, MEMUNIT, "1 GB"),
  152. V(BandwidthRate, MEMUNIT, "1 GB"),
  153. V(BridgeAuthoritativeDir, BOOL, "0"),
  154. VAR("Bridge", LINELIST, Bridges, NULL),
  155. V(BridgePassword, STRING, NULL),
  156. V(BridgeRecordUsageByCountry, BOOL, "1"),
  157. V(BridgeRelay, BOOL, "0"),
  158. V(CellStatistics, BOOL, "0"),
  159. V(LearnCircuitBuildTimeout, BOOL, "1"),
  160. V(CircuitBuildTimeout, INTERVAL, "0"),
  161. V(CircuitIdleTimeout, INTERVAL, "1 hour"),
  162. V(CircuitStreamTimeout, INTERVAL, "0"),
  163. V(CircuitPriorityHalflife, DOUBLE, "-100.0"), /*negative:'Use default'*/
  164. V(ClientDNSRejectInternalAddresses, BOOL,"1"),
  165. V(ClientOnly, BOOL, "0"),
  166. V(ClientPreferIPv6ORPort, BOOL, "0"),
  167. V(ClientRejectInternalAddresses, BOOL, "1"),
  168. V(ClientTransportPlugin, LINELIST, NULL),
  169. V(ClientUseIPv6, BOOL, "0"),
  170. V(ConsensusParams, STRING, NULL),
  171. V(ConnLimit, UINT, "1000"),
  172. V(ConnDirectionStatistics, BOOL, "0"),
  173. V(ConstrainedSockets, BOOL, "0"),
  174. V(ConstrainedSockSize, MEMUNIT, "8192"),
  175. V(ContactInfo, STRING, NULL),
  176. V(ControlListenAddress, LINELIST, NULL),
  177. VPORT(ControlPort, LINELIST, NULL),
  178. V(ControlPortFileGroupReadable,BOOL, "0"),
  179. V(ControlPortWriteToFile, FILENAME, NULL),
  180. V(ControlSocket, LINELIST, NULL),
  181. V(ControlSocketsGroupWritable, BOOL, "0"),
  182. V(CookieAuthentication, BOOL, "0"),
  183. V(CookieAuthFileGroupReadable, BOOL, "0"),
  184. V(CookieAuthFile, STRING, NULL),
  185. V(CountPrivateBandwidth, BOOL, "0"),
  186. V(DataDirectory, FILENAME, NULL),
  187. OBSOLETE("DebugLogFile"),
  188. V(DisableNetwork, BOOL, "0"),
  189. V(DirAllowPrivateAddresses, BOOL, "0"),
  190. V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
  191. V(DirListenAddress, LINELIST, NULL),
  192. OBSOLETE("DirFetchPeriod"),
  193. V(DirPolicy, LINELIST, NULL),
  194. VPORT(DirPort, LINELIST, NULL),
  195. V(DirPortFrontPage, FILENAME, NULL),
  196. OBSOLETE("DirPostPeriod"),
  197. OBSOLETE("DirRecordUsageByCountry"),
  198. OBSOLETE("DirRecordUsageGranularity"),
  199. OBSOLETE("DirRecordUsageRetainIPs"),
  200. OBSOLETE("DirRecordUsageSaveInterval"),
  201. V(DirReqStatistics, BOOL, "1"),
  202. VAR("DirAuthority", LINELIST, DirAuthorities, NULL),
  203. V(DirAuthorityFallbackRate, DOUBLE, "1.0"),
  204. V(DisableAllSwap, BOOL, "0"),
  205. V(DisableDebuggerAttachment, BOOL, "1"),
  206. V(DisableIOCP, BOOL, "1"),
  207. V(DisableV2DirectoryInfo_, BOOL, "0"),
  208. V(DynamicDHGroups, BOOL, "0"),
  209. VPORT(DNSPort, LINELIST, NULL),
  210. V(DNSListenAddress, LINELIST, NULL),
  211. V(DownloadExtraInfo, BOOL, "0"),
  212. V(EnforceDistinctSubnets, BOOL, "1"),
  213. V(EntryNodes, ROUTERSET, NULL),
  214. V(EntryStatistics, BOOL, "0"),
  215. V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
  216. V(ExcludeNodes, ROUTERSET, NULL),
  217. V(ExcludeExitNodes, ROUTERSET, NULL),
  218. V(ExcludeSingleHopRelays, BOOL, "1"),
  219. V(ExitNodes, ROUTERSET, NULL),
  220. V(ExitPolicy, LINELIST, NULL),
  221. V(ExitPolicyRejectPrivate, BOOL, "1"),
  222. V(ExitPortStatistics, BOOL, "0"),
  223. V(ExtendAllowPrivateAddresses, BOOL, "0"),
  224. V(ExtraInfoStatistics, BOOL, "1"),
  225. V(FallbackDir, LINELIST, NULL),
  226. OBSOLETE("FallbackNetworkstatusFile"),
  227. V(FascistFirewall, BOOL, "0"),
  228. V(FirewallPorts, CSV, ""),
  229. V(FastFirstHopPK, BOOL, "1"),
  230. V(FetchDirInfoEarly, BOOL, "0"),
  231. V(FetchDirInfoExtraEarly, BOOL, "0"),
  232. V(FetchServerDescriptors, BOOL, "1"),
  233. V(FetchHidServDescriptors, BOOL, "1"),
  234. V(FetchUselessDescriptors, BOOL, "0"),
  235. V(FetchV2Networkstatus, BOOL, "0"),
  236. V(GeoIPExcludeUnknown, AUTOBOOL, "auto"),
  237. #ifdef _WIN32
  238. V(GeoIPFile, FILENAME, "<default>"),
  239. V(GeoIPv6File, FILENAME, "<default>"),
  240. #else
  241. V(GeoIPFile, FILENAME,
  242. SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
  243. V(GeoIPv6File, FILENAME,
  244. SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip6"),
  245. #endif
  246. OBSOLETE("GiveGuardFlagTo_CVE_2011_2768_VulnerableRelays"),
  247. OBSOLETE("Group"),
  248. V(GuardLifetime, INTERVAL, "0 minutes"),
  249. V(HardwareAccel, BOOL, "0"),
  250. V(HeartbeatPeriod, INTERVAL, "6 hours"),
  251. V(AccelName, STRING, NULL),
  252. V(AccelDir, FILENAME, NULL),
  253. V(HashedControlPassword, LINELIST, NULL),
  254. V(HidServDirectoryV2, BOOL, "1"),
  255. VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
  256. OBSOLETE("HiddenServiceExcludeNodes"),
  257. OBSOLETE("HiddenServiceNodes"),
  258. VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
  259. VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
  260. VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
  261. VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
  262. V(HidServAuth, LINELIST, NULL),
  263. V(HSAuthoritativeDir, BOOL, "0"),
  264. OBSOLETE("HSAuthorityRecordStats"),
  265. V(CloseHSClientCircuitsImmediatelyOnTimeout, BOOL, "0"),
  266. V(CloseHSServiceRendCircuitsImmediatelyOnTimeout, BOOL, "0"),
  267. V(HTTPProxy, STRING, NULL),
  268. V(HTTPProxyAuthenticator, STRING, NULL),
  269. V(HTTPSProxy, STRING, NULL),
  270. V(HTTPSProxyAuthenticator, STRING, NULL),
  271. V(IPv6Exit, BOOL, "0"),
  272. VAR("ServerTransportPlugin", LINELIST, ServerTransportPlugin, NULL),
  273. V(ServerTransportListenAddr, LINELIST, NULL),
  274. V(Socks4Proxy, STRING, NULL),
  275. V(Socks5Proxy, STRING, NULL),
  276. V(Socks5ProxyUsername, STRING, NULL),
  277. V(Socks5ProxyPassword, STRING, NULL),
  278. OBSOLETE("IgnoreVersion"),
  279. V(KeepalivePeriod, INTERVAL, "5 minutes"),
  280. VAR("Log", LINELIST, Logs, NULL),
  281. V(LogMessageDomains, BOOL, "0"),
  282. OBSOLETE("LinkPadding"),
  283. OBSOLETE("LogLevel"),
  284. OBSOLETE("LogFile"),
  285. V(LogTimeGranularity, MSEC_INTERVAL, "1 second"),
  286. V(LongLivedPorts, CSV,
  287. "21,22,706,1863,5050,5190,5222,5223,6523,6667,6697,8300"),
  288. VAR("MapAddress", LINELIST, AddressMap, NULL),
  289. V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
  290. V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
  291. V(MaxClientCircuitsPending, UINT, "32"),
  292. OBSOLETE("MaxOnionsPending"),
  293. V(MaxOnionQueueDelay, MSEC_INTERVAL, "1750 msec"),
  294. V(MinMeasuredBWsForAuthToIgnoreAdvertised, INT, "500"),
  295. OBSOLETE("MonthlyAccountingStart"),
  296. V(MyFamily, STRING, NULL),
  297. V(NewCircuitPeriod, INTERVAL, "30 seconds"),
  298. VAR("NamingAuthoritativeDirectory",BOOL, NamingAuthoritativeDir, "0"),
  299. V(NATDListenAddress, LINELIST, NULL),
  300. VPORT(NATDPort, LINELIST, NULL),
  301. V(Nickname, STRING, NULL),
  302. V(WarnUnsafeSocks, BOOL, "1"),
  303. OBSOLETE("NoPublish"),
  304. VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
  305. V(NumCPUs, UINT, "0"),
  306. V(NumDirectoryGuards, UINT, "3"),
  307. V(NumEntryGuards, UINT, "3"),
  308. V(ORListenAddress, LINELIST, NULL),
  309. VPORT(ORPort, LINELIST, NULL),
  310. V(OutboundBindAddress, LINELIST, NULL),
  311. OBSOLETE("PathBiasDisableRate"),
  312. V(PathBiasCircThreshold, INT, "-1"),
  313. V(PathBiasNoticeRate, DOUBLE, "-1"),
  314. V(PathBiasWarnRate, DOUBLE, "-1"),
  315. V(PathBiasExtremeRate, DOUBLE, "-1"),
  316. V(PathBiasScaleThreshold, INT, "-1"),
  317. OBSOLETE("PathBiasScaleFactor"),
  318. OBSOLETE("PathBiasMultFactor"),
  319. V(PathBiasDropGuards, AUTOBOOL, "0"),
  320. OBSOLETE("PathBiasUseCloseCounts"),
  321. V(PathBiasUseThreshold, INT, "-1"),
  322. V(PathBiasNoticeUseRate, DOUBLE, "-1"),
  323. V(PathBiasExtremeUseRate, DOUBLE, "-1"),
  324. V(PathBiasScaleUseThreshold, INT, "-1"),
  325. V(PathsNeededToBuildCircuits, DOUBLE, "-1"),
  326. OBSOLETE("PathlenCoinWeight"),
  327. V(PerConnBWBurst, MEMUNIT, "0"),
  328. V(PerConnBWRate, MEMUNIT, "0"),
  329. V(PidFile, STRING, NULL),
  330. V(TestingTorNetwork, BOOL, "0"),
  331. V(OptimisticData, AUTOBOOL, "auto"),
  332. V(PortForwarding, BOOL, "0"),
  333. V(PortForwardingHelper, FILENAME, "tor-fw-helper"),
  334. V(PreferTunneledDirConns, BOOL, "1"),
  335. V(ProtocolWarnings, BOOL, "0"),
  336. V(PublishServerDescriptor, CSV, "1"),
  337. V(PublishHidServDescriptors, BOOL, "1"),
  338. V(ReachableAddresses, LINELIST, NULL),
  339. V(ReachableDirAddresses, LINELIST, NULL),
  340. V(ReachableORAddresses, LINELIST, NULL),
  341. V(RecommendedVersions, LINELIST, NULL),
  342. V(RecommendedClientVersions, LINELIST, NULL),
  343. V(RecommendedServerVersions, LINELIST, NULL),
  344. OBSOLETE("RedirectExit"),
  345. V(RefuseUnknownExits, AUTOBOOL, "auto"),
  346. V(RejectPlaintextPorts, CSV, ""),
  347. V(RelayBandwidthBurst, MEMUNIT, "0"),
  348. V(RelayBandwidthRate, MEMUNIT, "0"),
  349. OBSOLETE("RendExcludeNodes"),
  350. OBSOLETE("RendNodes"),
  351. V(RendPostPeriod, INTERVAL, "1 hour"),
  352. V(RephistTrackTime, INTERVAL, "24 hours"),
  353. OBSOLETE("RouterFile"),
  354. V(RunAsDaemon, BOOL, "0"),
  355. // V(RunTesting, BOOL, "0"),
  356. OBSOLETE("RunTesting"), // currently unused
  357. V(SafeLogging, STRING, "1"),
  358. V(SafeSocks, BOOL, "0"),
  359. V(ServerDNSAllowBrokenConfig, BOOL, "1"),
  360. V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
  361. V(ServerDNSDetectHijacking, BOOL, "1"),
  362. V(ServerDNSRandomizeCase, BOOL, "1"),
  363. V(ServerDNSResolvConfFile, STRING, NULL),
  364. V(ServerDNSSearchDomains, BOOL, "0"),
  365. V(ServerDNSTestAddresses, CSV,
  366. "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
  367. V(ShutdownWaitLength, INTERVAL, "30 seconds"),
  368. V(SocksListenAddress, LINELIST, NULL),
  369. V(SocksPolicy, LINELIST, NULL),
  370. VPORT(SocksPort, LINELIST, NULL),
  371. V(SocksTimeout, INTERVAL, "2 minutes"),
  372. V(SSLKeyLifetime, INTERVAL, "0"),
  373. OBSOLETE("StatusFetchPeriod"),
  374. V(StrictNodes, BOOL, "0"),
  375. OBSOLETE("SysLog"),
  376. V(TestSocks, BOOL, "0"),
  377. OBSOLETE("TestVia"),
  378. V(TokenBucketRefillInterval, MSEC_INTERVAL, "100 msec"),
  379. V(Tor2webMode, BOOL, "0"),
  380. V(TLSECGroup, STRING, NULL),
  381. V(TrackHostExits, CSV, NULL),
  382. V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
  383. OBSOLETE("TrafficShaping"),
  384. V(TransListenAddress, LINELIST, NULL),
  385. VPORT(TransPort, LINELIST, NULL),
  386. V(TunnelDirConns, BOOL, "1"),
  387. V(UpdateBridgesFromAuthority, BOOL, "0"),
  388. V(UseBridges, BOOL, "0"),
  389. V(UseEntryGuards, BOOL, "1"),
  390. V(UseEntryGuardsAsDirGuards, BOOL, "1"),
  391. V(UseMicrodescriptors, AUTOBOOL, "auto"),
  392. V(UseNTorHandshake, AUTOBOOL, "auto"),
  393. V(User, STRING, NULL),
  394. V(UserspaceIOCPBuffers, BOOL, "0"),
  395. VAR("V1AuthoritativeDirectory",BOOL, V1AuthoritativeDir, "0"),
  396. VAR("V2AuthoritativeDirectory",BOOL, V2AuthoritativeDir, "0"),
  397. VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
  398. V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
  399. V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
  400. V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
  401. V(V3AuthVotingInterval, INTERVAL, "1 hour"),
  402. V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
  403. V(V3AuthDistDelay, INTERVAL, "5 minutes"),
  404. V(V3AuthNIntervalsValid, UINT, "3"),
  405. V(V3AuthUseLegacyKey, BOOL, "0"),
  406. V(V3BandwidthsFile, FILENAME, NULL),
  407. VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
  408. V(VirtualAddrNetworkIPv4, STRING, "127.192.0.0/10"),
  409. V(VirtualAddrNetworkIPv6, STRING, "[FE80::]/10"),
  410. V(WarnPlaintextPorts, CSV, "23,109,110,143"),
  411. V(UseFilteringSSLBufferevents, BOOL, "0"),
  412. VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
  413. VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
  414. VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
  415. VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
  416. VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
  417. NULL),
  418. VAR("__OwningControllerProcess",STRING,OwningControllerProcess, NULL),
  419. V(MinUptimeHidServDirectoryV2, INTERVAL, "25 hours"),
  420. V(VoteOnHidServDirectoriesV2, BOOL, "1"),
  421. VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "0"),
  422. { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
  423. };
  424. /** Override default values with these if the user sets the TestingTorNetwork
  425. * option. */
  426. static const config_var_t testing_tor_network_defaults[] = {
  427. V(ServerDNSAllowBrokenConfig, BOOL, "1"),
  428. V(DirAllowPrivateAddresses, BOOL, "1"),
  429. V(EnforceDistinctSubnets, BOOL, "0"),
  430. V(AssumeReachable, BOOL, "1"),
  431. V(AuthDirMaxServersPerAddr, UINT, "0"),
  432. V(AuthDirMaxServersPerAuthAddr,UINT, "0"),
  433. V(ClientDNSRejectInternalAddresses, BOOL,"0"),
  434. V(ClientRejectInternalAddresses, BOOL, "0"),
  435. V(CountPrivateBandwidth, BOOL, "1"),
  436. V(ExitPolicyRejectPrivate, BOOL, "0"),
  437. V(ExtendAllowPrivateAddresses, BOOL, "1"),
  438. V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
  439. V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
  440. V(V3AuthDistDelay, INTERVAL, "20 seconds"),
  441. V(TestingV3AuthInitialVotingInterval, INTERVAL, "5 minutes"),
  442. V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
  443. V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
  444. V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
  445. V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
  446. V(MinUptimeHidServDirectoryV2, INTERVAL, "0 minutes"),
  447. VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "1"),
  448. { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
  449. };
  450. #undef VAR
  451. #undef V
  452. #undef OBSOLETE
  453. #ifdef _WIN32
  454. static char *get_windows_conf_root(void);
  455. #endif
  456. static int options_validate(or_options_t *old_options,
  457. or_options_t *options,
  458. int from_setconf, char **msg);
  459. static int options_act_reversible(const or_options_t *old_options, char **msg);
  460. static int options_act(const or_options_t *old_options);
  461. static int options_transition_allowed(const or_options_t *old,
  462. const or_options_t *new,
  463. char **msg);
  464. static int options_transition_affects_workers(
  465. const or_options_t *old_options, const or_options_t *new_options);
  466. static int options_transition_affects_descriptor(
  467. const or_options_t *old_options, const or_options_t *new_options);
  468. static int check_nickname_list(const char *lst, const char *name, char **msg);
  469. static int parse_bridge_line(const char *line, int validate_only);
  470. static int parse_client_transport_line(const char *line, int validate_only);
  471. static int parse_server_transport_line(const char *line, int validate_only);
  472. static char *get_bindaddr_from_transport_listen_line(const char *line,
  473. const char *transport);
  474. static int parse_dir_authority_line(const char *line,
  475. dirinfo_type_t required_type,
  476. int validate_only);
  477. static int parse_dir_fallback_line(const char *line,
  478. int validate_only);
  479. static void port_cfg_free(port_cfg_t *port);
  480. static int parse_ports(or_options_t *options, int validate_only,
  481. char **msg_out, int *n_ports_out);
  482. static int check_server_ports(const smartlist_t *ports,
  483. const or_options_t *options);
  484. static int validate_data_directory(or_options_t *options);
  485. static int write_configuration_file(const char *fname,
  486. const or_options_t *options);
  487. static int options_init_logs(or_options_t *options, int validate_only);
  488. static void init_libevent(const or_options_t *options);
  489. static int opt_streq(const char *s1, const char *s2);
  490. static int parse_outbound_addresses(or_options_t *options, int validate_only,
  491. char **msg);
  492. static void config_maybe_load_geoip_files_(const or_options_t *options,
  493. const or_options_t *old_options);
  494. /** Magic value for or_options_t. */
  495. #define OR_OPTIONS_MAGIC 9090909
  496. /** Configuration format for or_options_t. */
  497. static config_format_t options_format = {
  498. sizeof(or_options_t),
  499. OR_OPTIONS_MAGIC,
  500. STRUCT_OFFSET(or_options_t, magic_),
  501. option_abbrevs_,
  502. option_vars_,
  503. (validate_fn_t)options_validate,
  504. NULL
  505. };
  506. /*
  507. * Functions to read and write the global options pointer.
  508. */
  509. /** Command-line and config-file options. */
  510. static or_options_t *global_options = NULL;
  511. /** The fallback options_t object; this is where we look for options not
  512. * in torrc before we fall back to Tor's defaults. */
  513. static or_options_t *global_default_options = NULL;
  514. /** Name of most recently read torrc file. */
  515. static char *torrc_fname = NULL;
  516. /** Name of the most recently read torrc-defaults file.*/
  517. static char *torrc_defaults_fname;
  518. /** Configuration Options set by command line. */
  519. static config_line_t *global_cmdline_options = NULL;
  520. /** Contents of most recently read DirPortFrontPage file. */
  521. static char *global_dirfrontpagecontents = NULL;
  522. /** List of port_cfg_t for all configured ports. */
  523. static smartlist_t *configured_ports = NULL;
  524. /** Return the contents of our frontpage string, or NULL if not configured. */
  525. const char *
  526. get_dirportfrontpage(void)
  527. {
  528. return global_dirfrontpagecontents;
  529. }
  530. /** Return the currently configured options. */
  531. or_options_t *
  532. get_options_mutable(void)
  533. {
  534. tor_assert(global_options);
  535. return global_options;
  536. }
  537. /** Returns the currently configured options */
  538. const or_options_t *
  539. get_options(void)
  540. {
  541. return get_options_mutable();
  542. }
  543. /** Change the current global options to contain <b>new_val</b> instead of
  544. * their current value; take action based on the new value; free the old value
  545. * as necessary. Returns 0 on success, -1 on failure.
  546. */
  547. int
  548. set_options(or_options_t *new_val, char **msg)
  549. {
  550. int i;
  551. smartlist_t *elements;
  552. config_line_t *line;
  553. or_options_t *old_options = global_options;
  554. global_options = new_val;
  555. /* Note that we pass the *old* options below, for comparison. It
  556. * pulls the new options directly out of global_options. */
  557. if (options_act_reversible(old_options, msg)<0) {
  558. tor_assert(*msg);
  559. global_options = old_options;
  560. return -1;
  561. }
  562. if (options_act(old_options) < 0) { /* acting on the options failed. die. */
  563. log_err(LD_BUG,
  564. "Acting on config options left us in a broken state. Dying.");
  565. exit(1);
  566. }
  567. /* Issues a CONF_CHANGED event to notify controller of the change. If Tor is
  568. * just starting up then the old_options will be undefined. */
  569. if (old_options && old_options != global_options) {
  570. elements = smartlist_new();
  571. for (i=0; options_format.vars[i].name; ++i) {
  572. const config_var_t *var = &options_format.vars[i];
  573. const char *var_name = var->name;
  574. if (var->type == CONFIG_TYPE_LINELIST_S ||
  575. var->type == CONFIG_TYPE_OBSOLETE) {
  576. continue;
  577. }
  578. if (!config_is_same(&options_format, new_val, old_options, var_name)) {
  579. line = config_get_assigned_option(&options_format, new_val,
  580. var_name, 1);
  581. if (line) {
  582. config_line_t *next;
  583. for (; line; line = next) {
  584. next = line->next;
  585. smartlist_add(elements, line->key);
  586. smartlist_add(elements, line->value);
  587. tor_free(line);
  588. }
  589. } else {
  590. smartlist_add(elements, (char*)options_format.vars[i].name);
  591. smartlist_add(elements, NULL);
  592. }
  593. }
  594. }
  595. control_event_conf_changed(elements);
  596. smartlist_free(elements);
  597. }
  598. if (old_options != global_options)
  599. config_free(&options_format, old_options);
  600. return 0;
  601. }
  602. extern const char tor_git_revision[]; /* from tor_main.c */
  603. /** The version of this Tor process, as parsed. */
  604. static char *the_tor_version = NULL;
  605. /** A shorter version of this Tor process's version, for export in our router
  606. * descriptor. (Does not include the git version, if any.) */
  607. static char *the_short_tor_version = NULL;
  608. /** Return the current Tor version. */
  609. const char *
  610. get_version(void)
  611. {
  612. if (the_tor_version == NULL) {
  613. if (strlen(tor_git_revision)) {
  614. tor_asprintf(&the_tor_version, "%s (git-%s)", get_short_version(),
  615. tor_git_revision);
  616. } else {
  617. the_tor_version = tor_strdup(get_short_version());
  618. }
  619. }
  620. return the_tor_version;
  621. }
  622. /** Return the current Tor version, without any git tag. */
  623. const char *
  624. get_short_version(void)
  625. {
  626. if (the_short_tor_version == NULL) {
  627. #ifdef TOR_BUILD_TAG
  628. tor_asprintf(&the_short_tor_version, "%s (%s)", VERSION, TOR_BUILD_TAG);
  629. #else
  630. the_short_tor_version = tor_strdup(VERSION);
  631. #endif
  632. }
  633. return the_short_tor_version;
  634. }
  635. /** Release additional memory allocated in options
  636. */
  637. static void
  638. or_options_free(or_options_t *options)
  639. {
  640. if (!options)
  641. return;
  642. routerset_free(options->ExcludeExitNodesUnion_);
  643. if (options->NodeFamilySets) {
  644. SMARTLIST_FOREACH(options->NodeFamilySets, routerset_t *,
  645. rs, routerset_free(rs));
  646. smartlist_free(options->NodeFamilySets);
  647. }
  648. tor_free(options->BridgePassword_AuthDigest_);
  649. config_free(&options_format, options);
  650. }
  651. /** Release all memory and resources held by global configuration structures.
  652. */
  653. void
  654. config_free_all(void)
  655. {
  656. or_options_free(global_options);
  657. global_options = NULL;
  658. or_options_free(global_default_options);
  659. global_default_options = NULL;
  660. config_free_lines(global_cmdline_options);
  661. global_cmdline_options = NULL;
  662. if (configured_ports) {
  663. SMARTLIST_FOREACH(configured_ports,
  664. port_cfg_t *, p, port_cfg_free(p));
  665. smartlist_free(configured_ports);
  666. configured_ports = NULL;
  667. }
  668. tor_free(torrc_fname);
  669. tor_free(torrc_defaults_fname);
  670. tor_free(the_tor_version);
  671. tor_free(global_dirfrontpagecontents);
  672. tor_free(the_short_tor_version);
  673. tor_free(the_tor_version);
  674. }
  675. /** Make <b>address</b> -- a piece of information related to our operation as
  676. * a client -- safe to log according to the settings in options->SafeLogging,
  677. * and return it.
  678. *
  679. * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
  680. */
  681. const char *
  682. safe_str_client(const char *address)
  683. {
  684. tor_assert(address);
  685. if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
  686. return "[scrubbed]";
  687. else
  688. return address;
  689. }
  690. /** Make <b>address</b> -- a piece of information of unspecified sensitivity
  691. * -- safe to log according to the settings in options->SafeLogging, and
  692. * return it.
  693. *
  694. * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
  695. * otherwise.)
  696. */
  697. const char *
  698. safe_str(const char *address)
  699. {
  700. tor_assert(address);
  701. if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
  702. return "[scrubbed]";
  703. else
  704. return address;
  705. }
  706. /** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
  707. * escaped(): don't use this outside the main thread, or twice in the same
  708. * log statement. */
  709. const char *
  710. escaped_safe_str_client(const char *address)
  711. {
  712. if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
  713. return "[scrubbed]";
  714. else
  715. return escaped(address);
  716. }
  717. /** Equivalent to escaped(safe_str(address)). See reentrancy note on
  718. * escaped(): don't use this outside the main thread, or twice in the same
  719. * log statement. */
  720. const char *
  721. escaped_safe_str(const char *address)
  722. {
  723. if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
  724. return "[scrubbed]";
  725. else
  726. return escaped(address);
  727. }
  728. /** Add the default directory authorities directly into the trusted dir list,
  729. * but only add them insofar as they share bits with <b>type</b>. */
  730. static void
  731. add_default_trusted_dir_authorities(dirinfo_type_t type)
  732. {
  733. int i;
  734. const char *authorities[] = {
  735. "moria1 orport=9101 no-v2 "
  736. "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
  737. "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
  738. "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
  739. "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
  740. "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
  741. "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
  742. "Tonga orport=443 bridge no-v2 82.94.251.203:80 "
  743. "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
  744. "turtles orport=9090 no-v2 "
  745. "v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
  746. "76.73.17.194:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
  747. "gabelmoo orport=443 no-v2 "
  748. "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
  749. "212.112.245.170:80 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
  750. "dannenberg orport=443 no-v2 "
  751. "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
  752. "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
  753. "urras orport=80 no-v2 v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
  754. "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
  755. "maatuska orport=80 no-v2 "
  756. "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
  757. "171.25.193.9:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
  758. "Faravahar orport=443 no-v2 "
  759. "v3ident=EFCBE720AB3A82B99F9E953CD5BF50F7EEFC7B97 "
  760. "154.35.32.5:80 CF6D 0AAF B385 BE71 B8E1 11FC 5CFF 4B47 9237 33BC",
  761. NULL
  762. };
  763. for (i=0; authorities[i]; i++) {
  764. if (parse_dir_authority_line(authorities[i], type, 0)<0) {
  765. log_err(LD_BUG, "Couldn't parse internal DirAuthority line %s",
  766. authorities[i]);
  767. }
  768. }
  769. }
  770. /** Add the default fallback directory servers into the fallback directory
  771. * server list. */
  772. static void
  773. add_default_fallback_dir_servers(void)
  774. {
  775. int i;
  776. const char *fallback[] = {
  777. NULL
  778. };
  779. for (i=0; fallback[i]; i++) {
  780. if (parse_dir_fallback_line(fallback[i], 0)<0) {
  781. log_err(LD_BUG, "Couldn't parse internal FallbackDir line %s",
  782. fallback[i]);
  783. }
  784. }
  785. }
  786. /** Look at all the config options for using alternate directory
  787. * authorities, and make sure none of them are broken. Also, warn the
  788. * user if we changed any dangerous ones.
  789. */
  790. static int
  791. validate_dir_servers(or_options_t *options, or_options_t *old_options)
  792. {
  793. config_line_t *cl;
  794. if (options->DirAuthorities &&
  795. (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
  796. options->AlternateHSAuthority)) {
  797. log_warn(LD_CONFIG,
  798. "You cannot set both DirAuthority and Alternate*Authority.");
  799. return -1;
  800. }
  801. /* do we want to complain to the user about being partitionable? */
  802. if ((options->DirAuthorities &&
  803. (!old_options ||
  804. !config_lines_eq(options->DirAuthorities,
  805. old_options->DirAuthorities))) ||
  806. (options->AlternateDirAuthority &&
  807. (!old_options ||
  808. !config_lines_eq(options->AlternateDirAuthority,
  809. old_options->AlternateDirAuthority)))) {
  810. log_warn(LD_CONFIG,
  811. "You have used DirAuthority or AlternateDirAuthority to "
  812. "specify alternate directory authorities in "
  813. "your configuration. This is potentially dangerous: it can "
  814. "make you look different from all other Tor users, and hurt "
  815. "your anonymity. Even if you've specified the same "
  816. "authorities as Tor uses by default, the defaults could "
  817. "change in the future. Be sure you know what you're doing.");
  818. }
  819. /* Now go through the four ways you can configure an alternate
  820. * set of directory authorities, and make sure none are broken. */
  821. for (cl = options->DirAuthorities; cl; cl = cl->next)
  822. if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
  823. return -1;
  824. for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
  825. if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
  826. return -1;
  827. for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
  828. if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
  829. return -1;
  830. for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
  831. if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
  832. return -1;
  833. for (cl = options->FallbackDir; cl; cl = cl->next)
  834. if (parse_dir_fallback_line(cl->value, 1)<0)
  835. return -1;
  836. return 0;
  837. }
  838. /** Look at all the config options and assign new dir authorities
  839. * as appropriate.
  840. */
  841. static int
  842. consider_adding_dir_servers(const or_options_t *options,
  843. const or_options_t *old_options)
  844. {
  845. config_line_t *cl;
  846. int need_to_update =
  847. !smartlist_len(router_get_trusted_dir_servers()) ||
  848. !smartlist_len(router_get_fallback_dir_servers()) || !old_options ||
  849. !config_lines_eq(options->DirAuthorities, old_options->DirAuthorities) ||
  850. !config_lines_eq(options->FallbackDir, old_options->FallbackDir) ||
  851. !config_lines_eq(options->AlternateBridgeAuthority,
  852. old_options->AlternateBridgeAuthority) ||
  853. !config_lines_eq(options->AlternateDirAuthority,
  854. old_options->AlternateDirAuthority) ||
  855. !config_lines_eq(options->AlternateHSAuthority,
  856. old_options->AlternateHSAuthority);
  857. if (!need_to_update)
  858. return 0; /* all done */
  859. /* Start from a clean slate. */
  860. clear_dir_servers();
  861. if (!options->DirAuthorities) {
  862. /* then we may want some of the defaults */
  863. dirinfo_type_t type = NO_DIRINFO;
  864. if (!options->AlternateBridgeAuthority)
  865. type |= BRIDGE_DIRINFO;
  866. if (!options->AlternateDirAuthority)
  867. type |= V1_DIRINFO | V2_DIRINFO | V3_DIRINFO | EXTRAINFO_DIRINFO |
  868. MICRODESC_DIRINFO;
  869. if (!options->AlternateHSAuthority)
  870. type |= HIDSERV_DIRINFO;
  871. add_default_trusted_dir_authorities(type);
  872. }
  873. if (!options->FallbackDir)
  874. add_default_fallback_dir_servers();
  875. for (cl = options->DirAuthorities; cl; cl = cl->next)
  876. if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
  877. return -1;
  878. for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
  879. if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
  880. return -1;
  881. for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
  882. if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
  883. return -1;
  884. for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
  885. if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
  886. return -1;
  887. for (cl = options->FallbackDir; cl; cl = cl->next)
  888. if (parse_dir_fallback_line(cl->value, 0)<0)
  889. return -1;
  890. return 0;
  891. }
  892. /** Fetch the active option list, and take actions based on it. All of the
  893. * things we do should survive being done repeatedly. If present,
  894. * <b>old_options</b> contains the previous value of the options.
  895. *
  896. * Return 0 if all goes well, return -1 if things went badly.
  897. */
  898. static int
  899. options_act_reversible(const or_options_t *old_options, char **msg)
  900. {
  901. smartlist_t *new_listeners = smartlist_new();
  902. smartlist_t *replaced_listeners = smartlist_new();
  903. static int libevent_initialized = 0;
  904. or_options_t *options = get_options_mutable();
  905. int running_tor = options->command == CMD_RUN_TOR;
  906. int set_conn_limit = 0;
  907. int r = -1;
  908. int logs_marked = 0;
  909. /* Daemonize _first_, since we only want to open most of this stuff in
  910. * the subprocess. Libevent bases can't be reliably inherited across
  911. * processes. */
  912. if (running_tor && options->RunAsDaemon) {
  913. /* No need to roll back, since you can't change the value. */
  914. start_daemon();
  915. }
  916. #ifndef HAVE_SYS_UN_H
  917. if (options->ControlSocket || options->ControlSocketsGroupWritable) {
  918. *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported "
  919. "on this OS/with this build.");
  920. goto rollback;
  921. }
  922. #else
  923. if (options->ControlSocketsGroupWritable && !options->ControlSocket) {
  924. *msg = tor_strdup("Setting ControlSocketGroupWritable without setting"
  925. "a ControlSocket makes no sense.");
  926. goto rollback;
  927. }
  928. #endif
  929. if (running_tor) {
  930. int n_ports=0;
  931. /* We need to set the connection limit before we can open the listeners. */
  932. if (set_max_file_descriptors((unsigned)options->ConnLimit,
  933. &options->ConnLimit_) < 0) {
  934. *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
  935. goto rollback;
  936. }
  937. set_conn_limit = 1;
  938. /* Set up libevent. (We need to do this before we can register the
  939. * listeners as listeners.) */
  940. if (running_tor && !libevent_initialized) {
  941. init_libevent(options);
  942. libevent_initialized = 1;
  943. }
  944. /* Adjust the port configuration so we can launch listeners. */
  945. if (parse_ports(options, 0, msg, &n_ports)) {
  946. if (!*msg)
  947. *msg = tor_strdup("Unexpected problem parsing port config");
  948. goto rollback;
  949. }
  950. /* Set the hibernation state appropriately.*/
  951. consider_hibernation(time(NULL));
  952. /* Launch the listeners. (We do this before we setuid, so we can bind to
  953. * ports under 1024.) We don't want to rebind if we're hibernating. If
  954. * networking is disabled, this will close all but the control listeners,
  955. * but disable those. */
  956. if (!we_are_hibernating()) {
  957. if (retry_all_listeners(replaced_listeners, new_listeners,
  958. options->DisableNetwork) < 0) {
  959. *msg = tor_strdup("Failed to bind one of the listener ports.");
  960. goto rollback;
  961. }
  962. }
  963. if (options->DisableNetwork) {
  964. /* Aggressively close non-controller stuff, NOW */
  965. log_notice(LD_NET, "DisableNetwork is set. Tor will not make or accept "
  966. "non-control network connections. Shutting down all existing "
  967. "connections.");
  968. connection_mark_all_noncontrol_connections();
  969. }
  970. }
  971. #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
  972. /* Open /dev/pf before dropping privileges. */
  973. if (options->TransPort_set) {
  974. if (get_pf_socket() < 0) {
  975. *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
  976. goto rollback;
  977. }
  978. }
  979. #endif
  980. /* Attempt to lock all current and future memory with mlockall() only once */
  981. if (options->DisableAllSwap) {
  982. if (tor_mlockall() == -1) {
  983. *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
  984. "permissions?");
  985. goto done;
  986. }
  987. }
  988. /* Setuid/setgid as appropriate */
  989. if (options->User) {
  990. if (switch_id(options->User) != 0) {
  991. /* No need to roll back, since you can't change the value. */
  992. *msg = tor_strdup("Problem with User value. See logs for details.");
  993. goto done;
  994. }
  995. }
  996. /* Ensure data directory is private; create if possible. */
  997. if (check_private_dir(options->DataDirectory,
  998. running_tor ? CPD_CREATE : CPD_CHECK,
  999. options->User)<0) {
  1000. tor_asprintf(msg,
  1001. "Couldn't access/create private data directory \"%s\"",
  1002. options->DataDirectory);
  1003. goto done;
  1004. /* No need to roll back, since you can't change the value. */
  1005. }
  1006. /* Write control ports to disk as appropriate */
  1007. control_ports_write_to_file();
  1008. if (directory_caches_v2_dir_info(options)) {
  1009. char *fn = NULL;
  1010. tor_asprintf(&fn, "%s"PATH_SEPARATOR"cached-status",
  1011. options->DataDirectory);
  1012. if (check_private_dir(fn, running_tor ? CPD_CREATE : CPD_CHECK,
  1013. options->User) < 0) {
  1014. tor_asprintf(msg,
  1015. "Couldn't access/create private data directory \"%s\"", fn);
  1016. tor_free(fn);
  1017. goto done;
  1018. }
  1019. tor_free(fn);
  1020. }
  1021. /* Bail out at this point if we're not going to be a client or server:
  1022. * we don't run Tor itself. */
  1023. if (!running_tor)
  1024. goto commit;
  1025. mark_logs_temp(); /* Close current logs once new logs are open. */
  1026. logs_marked = 1;
  1027. if (options_init_logs(options, 0)<0) { /* Configure the tor_log(s) */
  1028. *msg = tor_strdup("Failed to init Log options. See logs for details.");
  1029. goto rollback;
  1030. }
  1031. commit:
  1032. r = 0;
  1033. if (logs_marked) {
  1034. log_severity_list_t *severity =
  1035. tor_malloc_zero(sizeof(log_severity_list_t));
  1036. close_temp_logs();
  1037. add_callback_log(severity, control_event_logmsg);
  1038. control_adjust_event_log_severity();
  1039. tor_free(severity);
  1040. }
  1041. SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
  1042. {
  1043. log_notice(LD_NET, "Closing old %s on %s:%d",
  1044. conn_type_to_string(conn->type), conn->address, conn->port);
  1045. connection_close_immediate(conn);
  1046. connection_mark_for_close(conn);
  1047. });
  1048. goto done;
  1049. rollback:
  1050. r = -1;
  1051. tor_assert(*msg);
  1052. if (logs_marked) {
  1053. rollback_log_changes();
  1054. control_adjust_event_log_severity();
  1055. }
  1056. if (set_conn_limit && old_options)
  1057. set_max_file_descriptors((unsigned)old_options->ConnLimit,
  1058. &options->ConnLimit_);
  1059. SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
  1060. {
  1061. log_notice(LD_NET, "Closing partially-constructed %s on %s:%d",
  1062. conn_type_to_string(conn->type), conn->address, conn->port);
  1063. connection_close_immediate(conn);
  1064. connection_mark_for_close(conn);
  1065. });
  1066. done:
  1067. smartlist_free(new_listeners);
  1068. smartlist_free(replaced_listeners);
  1069. return r;
  1070. }
  1071. /** If we need to have a GEOIP ip-to-country map to run with our configured
  1072. * options, return 1 and set *<b>reason_out</b> to a description of why. */
  1073. int
  1074. options_need_geoip_info(const or_options_t *options, const char **reason_out)
  1075. {
  1076. int bridge_usage =
  1077. options->BridgeRelay && options->BridgeRecordUsageByCountry;
  1078. int routerset_usage =
  1079. routerset_needs_geoip(options->EntryNodes) ||
  1080. routerset_needs_geoip(options->ExitNodes) ||
  1081. routerset_needs_geoip(options->ExcludeExitNodes) ||
  1082. routerset_needs_geoip(options->ExcludeNodes);
  1083. if (routerset_usage && reason_out) {
  1084. *reason_out = "We've been configured to use (or avoid) nodes in certain "
  1085. "countries, and we need GEOIP information to figure out which ones they "
  1086. "are.";
  1087. } else if (bridge_usage && reason_out) {
  1088. *reason_out = "We've been configured to see which countries can access "
  1089. "us as a bridge, and we need GEOIP information to tell which countries "
  1090. "clients are in.";
  1091. }
  1092. return bridge_usage || routerset_usage;
  1093. }
  1094. /** Return the bandwidthrate that we are going to report to the authorities
  1095. * based on the config options. */
  1096. uint32_t
  1097. get_effective_bwrate(const or_options_t *options)
  1098. {
  1099. uint64_t bw = options->BandwidthRate;
  1100. if (bw > options->MaxAdvertisedBandwidth)
  1101. bw = options->MaxAdvertisedBandwidth;
  1102. if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
  1103. bw = options->RelayBandwidthRate;
  1104. /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
  1105. return (uint32_t)bw;
  1106. }
  1107. /** Return the bandwidthburst that we are going to report to the authorities
  1108. * based on the config options. */
  1109. uint32_t
  1110. get_effective_bwburst(const or_options_t *options)
  1111. {
  1112. uint64_t bw = options->BandwidthBurst;
  1113. if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
  1114. bw = options->RelayBandwidthBurst;
  1115. /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
  1116. return (uint32_t)bw;
  1117. }
  1118. /** Return True if any changes from <b>old_options</b> to
  1119. * <b>new_options</b> needs us to refresh our TLS context. */
  1120. static int
  1121. options_transition_requires_fresh_tls_context(const or_options_t *old_options,
  1122. const or_options_t *new_options)
  1123. {
  1124. tor_assert(new_options);
  1125. if (!old_options)
  1126. return 0;
  1127. if ((old_options->DynamicDHGroups != new_options->DynamicDHGroups)) {
  1128. return 1;
  1129. }
  1130. if (!opt_streq(old_options->TLSECGroup, new_options->TLSECGroup))
  1131. return 1;
  1132. return 0;
  1133. }
  1134. /** Fetch the active option list, and take actions based on it. All of the
  1135. * things we do should survive being done repeatedly. If present,
  1136. * <b>old_options</b> contains the previous value of the options.
  1137. *
  1138. * Return 0 if all goes well, return -1 if it's time to die.
  1139. *
  1140. * Note: We haven't moved all the "act on new configuration" logic
  1141. * here yet. Some is still in do_hup() and other places.
  1142. */
  1143. static int
  1144. options_act(const or_options_t *old_options)
  1145. {
  1146. config_line_t *cl;
  1147. or_options_t *options = get_options_mutable();
  1148. int running_tor = options->command == CMD_RUN_TOR;
  1149. char *msg=NULL;
  1150. const int transition_affects_workers =
  1151. old_options && options_transition_affects_workers(old_options, options);
  1152. int old_ewma_enabled;
  1153. /* disable ptrace and later, other basic debugging techniques */
  1154. {
  1155. /* Remember if we already disabled debugger attachment */
  1156. static int disabled_debugger_attach = 0;
  1157. /* Remember if we already warned about being configured not to disable
  1158. * debugger attachment */
  1159. static int warned_debugger_attach = 0;
  1160. /* Don't disable debugger attachment when we're running the unit tests. */
  1161. if (options->DisableDebuggerAttachment && !disabled_debugger_attach &&
  1162. running_tor) {
  1163. int ok = tor_disable_debugger_attach();
  1164. if (warned_debugger_attach && ok == 1) {
  1165. log_notice(LD_CONFIG, "Disabled attaching debuggers for unprivileged "
  1166. "users.");
  1167. }
  1168. disabled_debugger_attach = (ok == 1);
  1169. } else if (!options->DisableDebuggerAttachment &&
  1170. !warned_debugger_attach) {
  1171. log_notice(LD_CONFIG, "Not disabling debugger attaching for "
  1172. "unprivileged users.");
  1173. warned_debugger_attach = 1;
  1174. }
  1175. }
  1176. if (running_tor && !have_lockfile()) {
  1177. if (try_locking(options, 1) < 0)
  1178. return -1;
  1179. }
  1180. if (consider_adding_dir_servers(options, old_options) < 0)
  1181. return -1;
  1182. #ifdef NON_ANONYMOUS_MODE_ENABLED
  1183. log_warn(LD_GENERAL, "This copy of Tor was compiled to run in a "
  1184. "non-anonymous mode. It will provide NO ANONYMITY.");
  1185. #endif
  1186. #ifdef ENABLE_TOR2WEB_MODE
  1187. if (!options->Tor2webMode) {
  1188. log_err(LD_CONFIG, "This copy of Tor was compiled to run in "
  1189. "'tor2web mode'. It can only be run with the Tor2webMode torrc "
  1190. "option enabled.");
  1191. return -1;
  1192. }
  1193. #else
  1194. if (options->Tor2webMode) {
  1195. log_err(LD_CONFIG, "This copy of Tor was not compiled to run in "
  1196. "'tor2web mode'. It cannot be run with the Tor2webMode torrc "
  1197. "option enabled. To enable Tor2webMode recompile with the "
  1198. "--enable-tor2webmode option.");
  1199. return -1;
  1200. }
  1201. #endif
  1202. if (options->Bridges) {
  1203. mark_bridge_list();
  1204. for (cl = options->Bridges; cl; cl = cl->next) {
  1205. if (parse_bridge_line(cl->value, 0)<0) {
  1206. log_warn(LD_BUG,
  1207. "Previously validated Bridge line could not be added!");
  1208. return -1;
  1209. }
  1210. }
  1211. sweep_bridge_list();
  1212. }
  1213. if (running_tor && rend_config_services(options, 0)<0) {
  1214. log_warn(LD_BUG,
  1215. "Previously validated hidden services line could not be added!");
  1216. return -1;
  1217. }
  1218. if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
  1219. log_warn(LD_BUG, "Previously validated client authorization for "
  1220. "hidden services could not be added!");
  1221. return -1;
  1222. }
  1223. /* Load state */
  1224. if (! or_state_loaded() && running_tor) {
  1225. if (or_state_load())
  1226. return -1;
  1227. rep_hist_load_mtbf_data(time(NULL));
  1228. }
  1229. mark_transport_list();
  1230. pt_prepare_proxy_list_for_config_read();
  1231. if (options->ClientTransportPlugin) {
  1232. for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
  1233. if (parse_client_transport_line(cl->value, 0)<0) {
  1234. log_warn(LD_BUG,
  1235. "Previously validated ClientTransportPlugin line "
  1236. "could not be added!");
  1237. return -1;
  1238. }
  1239. }
  1240. }
  1241. if (options->ServerTransportPlugin && server_mode(options)) {
  1242. for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
  1243. if (parse_server_transport_line(cl->value, 0)<0) {
  1244. log_warn(LD_BUG,
  1245. "Previously validated ServerTransportPlugin line "
  1246. "could not be added!");
  1247. return -1;
  1248. }
  1249. }
  1250. }
  1251. sweep_transport_list();
  1252. sweep_proxy_list();
  1253. /* Bail out at this point if we're not going to be a client or server:
  1254. * we want to not fork, and to log stuff to stderr. */
  1255. if (!running_tor)
  1256. return 0;
  1257. /* Finish backgrounding the process */
  1258. if (options->RunAsDaemon) {
  1259. /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
  1260. finish_daemon(options->DataDirectory);
  1261. }
  1262. /* If needed, generate a new TLS DH prime according to the current torrc. */
  1263. if (server_mode(options) && options->DynamicDHGroups) {
  1264. char *keydir = get_datadir_fname("keys");
  1265. if (check_private_dir(keydir, CPD_CREATE, options->User)) {
  1266. tor_free(keydir);
  1267. return -1;
  1268. }
  1269. tor_free(keydir);
  1270. if (!old_options || !old_options->DynamicDHGroups) {
  1271. char *fname = get_datadir_fname2("keys", "dynamic_dh_params");
  1272. crypto_set_tls_dh_prime(fname);
  1273. tor_free(fname);
  1274. }
  1275. } else { /* clients don't need a dynamic DH prime. */
  1276. crypto_set_tls_dh_prime(NULL);
  1277. }
  1278. /* We want to reinit keys as needed before we do much of anything else:
  1279. keys are important, and other things can depend on them. */
  1280. if (transition_affects_workers ||
  1281. (options->V3AuthoritativeDir && (!old_options ||
  1282. !old_options->V3AuthoritativeDir))) {
  1283. if (init_keys() < 0) {
  1284. log_warn(LD_BUG,"Error initializing keys; exiting");
  1285. return -1;
  1286. }
  1287. } else if (old_options &&
  1288. options_transition_requires_fresh_tls_context(old_options,
  1289. options)) {
  1290. if (router_initialize_tls_context() < 0) {
  1291. log_warn(LD_BUG,"Error initializing TLS context.");
  1292. return -1;
  1293. }
  1294. }
  1295. /* Write our PID to the PID file. If we do not have write permissions we
  1296. * will log a warning */
  1297. if (options->PidFile)
  1298. write_pidfile(options->PidFile);
  1299. /* Register addressmap directives */
  1300. config_register_addressmaps(options);
  1301. parse_virtual_addr_network(options->VirtualAddrNetworkIPv4, AF_INET,0,NULL);
  1302. parse_virtual_addr_network(options->VirtualAddrNetworkIPv6, AF_INET6,0,NULL);
  1303. /* Update address policies. */
  1304. if (policies_parse_from_options(options) < 0) {
  1305. /* This should be impossible, but let's be sure. */
  1306. log_warn(LD_BUG,"Error parsing already-validated policy options.");
  1307. return -1;
  1308. }
  1309. if (init_cookie_authentication(options->CookieAuthentication) < 0) {
  1310. log_warn(LD_CONFIG,"Error creating cookie authentication file.");
  1311. return -1;
  1312. }
  1313. monitor_owning_controller_process(options->OwningControllerProcess);
  1314. /* reload keys as needed for rendezvous services. */
  1315. if (rend_service_load_all_keys()<0) {
  1316. log_warn(LD_GENERAL,"Error loading rendezvous service keys");
  1317. return -1;
  1318. }
  1319. /* Set up accounting */
  1320. if (accounting_parse_options(options, 0)<0) {
  1321. log_warn(LD_CONFIG,"Error in accounting options");
  1322. return -1;
  1323. }
  1324. if (accounting_is_enabled(options))
  1325. configure_accounting(time(NULL));
  1326. #ifdef USE_BUFFEREVENTS
  1327. /* If we're using the bufferevents implementation and our rate limits
  1328. * changed, we need to tell the rate-limiting system about it. */
  1329. if (!old_options ||
  1330. old_options->BandwidthRate != options->BandwidthRate ||
  1331. old_options->BandwidthBurst != options->BandwidthBurst ||
  1332. old_options->RelayBandwidthRate != options->RelayBandwidthRate ||
  1333. old_options->RelayBandwidthBurst != options->RelayBandwidthBurst)
  1334. connection_bucket_init();
  1335. #endif
  1336. old_ewma_enabled = cell_ewma_enabled();
  1337. /* Change the cell EWMA settings */
  1338. cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
  1339. /* If we just enabled ewma, set the cmux policy on all active channels */
  1340. if (cell_ewma_enabled() && !old_ewma_enabled) {
  1341. channel_set_cmux_policy_everywhere(&ewma_policy);
  1342. } else if (!cell_ewma_enabled() && old_ewma_enabled) {
  1343. /* Turn it off everywhere */
  1344. channel_set_cmux_policy_everywhere(NULL);
  1345. }
  1346. /* Update the BridgePassword's hashed version as needed. We store this as a
  1347. * digest so that we can do side-channel-proof comparisons on it.
  1348. */
  1349. if (options->BridgePassword) {
  1350. char *http_authenticator;
  1351. http_authenticator = alloc_http_authenticator(options->BridgePassword);
  1352. if (!http_authenticator) {
  1353. log_warn(LD_BUG, "Unable to allocate HTTP authenticator. Not setting "
  1354. "BridgePassword.");
  1355. return -1;
  1356. }
  1357. options->BridgePassword_AuthDigest_ = tor_malloc(DIGEST256_LEN);
  1358. crypto_digest256(options->BridgePassword_AuthDigest_,
  1359. http_authenticator, strlen(http_authenticator),
  1360. DIGEST_SHA256);
  1361. tor_free(http_authenticator);
  1362. }
  1363. if (parse_outbound_addresses(options, 0, &msg) < 0) {
  1364. log_warn(LD_BUG, "Failed parsing oubound bind addresses: %s", msg);
  1365. tor_free(msg);
  1366. return -1;
  1367. }
  1368. /* Check for transitions that need action. */
  1369. if (old_options) {
  1370. int revise_trackexithosts = 0;
  1371. int revise_automap_entries = 0;
  1372. if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
  1373. options->UseBridges != old_options->UseBridges ||
  1374. (options->UseBridges &&
  1375. !config_lines_eq(options->Bridges, old_options->Bridges)) ||
  1376. !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes) ||
  1377. !routerset_equal(old_options->ExcludeExitNodes,
  1378. options->ExcludeExitNodes) ||
  1379. !routerset_equal(old_options->EntryNodes, options->EntryNodes) ||
  1380. !routerset_equal(old_options->ExitNodes, options->ExitNodes) ||
  1381. options->StrictNodes != old_options->StrictNodes) {
  1382. log_info(LD_CIRC,
  1383. "Changed to using entry guards or bridges, or changed "
  1384. "preferred or excluded node lists. "
  1385. "Abandoning previous circuits.");
  1386. circuit_mark_all_unused_circs();
  1387. circuit_mark_all_dirty_circs_as_unusable();
  1388. revise_trackexithosts = 1;
  1389. }
  1390. if (!smartlist_strings_eq(old_options->TrackHostExits,
  1391. options->TrackHostExits))
  1392. revise_trackexithosts = 1;
  1393. if (revise_trackexithosts)
  1394. addressmap_clear_excluded_trackexithosts(options);
  1395. if (!options->AutomapHostsOnResolve) {
  1396. if (old_options->AutomapHostsOnResolve)
  1397. revise_automap_entries = 1;
  1398. } else {
  1399. if (!smartlist_strings_eq(old_options->AutomapHostsSuffixes,
  1400. options->AutomapHostsSuffixes))
  1401. revise_automap_entries = 1;
  1402. else if (!opt_streq(old_options->VirtualAddrNetworkIPv4,
  1403. options->VirtualAddrNetworkIPv4) ||
  1404. !opt_streq(old_options->VirtualAddrNetworkIPv6,
  1405. options->VirtualAddrNetworkIPv6))
  1406. revise_automap_entries = 1;
  1407. }
  1408. if (revise_automap_entries)
  1409. addressmap_clear_invalid_automaps(options);
  1410. /* How long should we delay counting bridge stats after becoming a bridge?
  1411. * We use this so we don't count people who used our bridge thinking it is
  1412. * a relay. If you change this, don't forget to change the log message
  1413. * below. It's 4 hours (the time it takes to stop being used by clients)
  1414. * plus some extra time for clock skew. */
  1415. #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
  1416. if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
  1417. int was_relay = 0;
  1418. if (options->BridgeRelay) {
  1419. time_t int_start = time(NULL);
  1420. if (config_lines_eq(old_options->ORPort_lines,options->ORPort_lines)) {
  1421. int_start += RELAY_BRIDGE_STATS_DELAY;
  1422. was_relay = 1;
  1423. }
  1424. geoip_bridge_stats_init(int_start);
  1425. log_info(LD_CONFIG, "We are acting as a bridge now. Starting new "
  1426. "GeoIP stats interval%s.", was_relay ? " in 6 "
  1427. "hours from now" : "");
  1428. } else {
  1429. geoip_bridge_stats_term();
  1430. log_info(LD_GENERAL, "We are no longer acting as a bridge. "
  1431. "Forgetting GeoIP stats.");
  1432. }
  1433. }
  1434. if (transition_affects_workers) {
  1435. log_info(LD_GENERAL,
  1436. "Worker-related options changed. Rotating workers.");
  1437. if (server_mode(options) && !server_mode(old_options)) {
  1438. ip_address_changed(0);
  1439. if (can_complete_circuit || !any_predicted_circuits(time(NULL)))
  1440. inform_testing_reachability();
  1441. }
  1442. cpuworkers_rotate();
  1443. if (dns_reset())
  1444. return -1;
  1445. } else {
  1446. if (dns_reset())
  1447. return -1;
  1448. }
  1449. if (options->PerConnBWRate != old_options->PerConnBWRate ||
  1450. options->PerConnBWBurst != old_options->PerConnBWBurst)
  1451. connection_or_update_token_buckets(get_connection_array(), options);
  1452. }
  1453. config_maybe_load_geoip_files_(options, old_options);
  1454. if (geoip_is_loaded(AF_INET) && options->GeoIPExcludeUnknown) {
  1455. /* ExcludeUnknown is true or "auto" */
  1456. const int is_auto = options->GeoIPExcludeUnknown == -1;
  1457. int changed;
  1458. changed = routerset_add_unknown_ccs(&options->ExcludeNodes, is_auto);
  1459. changed += routerset_add_unknown_ccs(&options->ExcludeExitNodes, is_auto);
  1460. if (changed)
  1461. routerset_add_unknown_ccs(&options->ExcludeExitNodesUnion_, is_auto);
  1462. }
  1463. if (options->CellStatistics || options->DirReqStatistics ||
  1464. options->EntryStatistics || options->ExitPortStatistics ||
  1465. options->ConnDirectionStatistics ||
  1466. options->BridgeAuthoritativeDir) {
  1467. time_t now = time(NULL);
  1468. int print_notice = 0;
  1469. /* If we aren't acting as a server, we can't collect stats anyway. */
  1470. if (!server_mode(options)) {
  1471. options->CellStatistics = 0;
  1472. options->DirReqStatistics = 0;
  1473. options->EntryStatistics = 0;
  1474. options->ExitPortStatistics = 0;
  1475. }
  1476. if ((!old_options || !old_options->CellStatistics) &&
  1477. options->CellStatistics) {
  1478. rep_hist_buffer_stats_init(now);
  1479. print_notice = 1;
  1480. }
  1481. if ((!old_options || !old_options->DirReqStatistics) &&
  1482. options->DirReqStatistics) {
  1483. if (geoip_is_loaded(AF_INET)) {
  1484. geoip_dirreq_stats_init(now);
  1485. print_notice = 1;
  1486. } else {
  1487. options->DirReqStatistics = 0;
  1488. /* Don't warn Tor clients, they don't use statistics */
  1489. if (options->ORPort_set)
  1490. log_notice(LD_CONFIG, "Configured to measure directory request "
  1491. "statistics, but no GeoIP database found. "
  1492. "Please specify a GeoIP database using the "
  1493. "GeoIPFile option.");
  1494. }
  1495. }
  1496. if ((!old_options || !old_options->EntryStatistics) &&
  1497. options->EntryStatistics && !should_record_bridge_info(options)) {
  1498. if (geoip_is_loaded(AF_INET) || geoip_is_loaded(AF_INET6)) {
  1499. geoip_entry_stats_init(now);
  1500. print_notice = 1;
  1501. } else {
  1502. options->EntryStatistics = 0;
  1503. log_notice(LD_CONFIG, "Configured to measure entry node "
  1504. "statistics, but no GeoIP database found. "
  1505. "Please specify a GeoIP database using the "
  1506. "GeoIPFile option.");
  1507. }
  1508. }
  1509. if ((!old_options || !old_options->ExitPortStatistics) &&
  1510. options->ExitPortStatistics) {
  1511. rep_hist_exit_stats_init(now);
  1512. print_notice = 1;
  1513. }
  1514. if ((!old_options || !old_options->ConnDirectionStatistics) &&
  1515. options->ConnDirectionStatistics) {
  1516. rep_hist_conn_stats_init(now);
  1517. }
  1518. if ((!old_options || !old_options->BridgeAuthoritativeDir) &&
  1519. options->BridgeAuthoritativeDir) {
  1520. rep_hist_desc_stats_init(now);
  1521. print_notice = 1;
  1522. }
  1523. if (print_notice)
  1524. log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
  1525. "the *-stats files that will first be written to the "
  1526. "data directory in 24 hours from now.");
  1527. }
  1528. if (old_options && old_options->CellStatistics &&
  1529. !options->CellStatistics)
  1530. rep_hist_buffer_stats_term();
  1531. if (old_options && old_options->DirReqStatistics &&
  1532. !options->DirReqStatistics)
  1533. geoip_dirreq_stats_term();
  1534. if (old_options && old_options->EntryStatistics &&
  1535. !options->EntryStatistics)
  1536. geoip_entry_stats_term();
  1537. if (old_options && old_options->ExitPortStatistics &&
  1538. !options->ExitPortStatistics)
  1539. rep_hist_exit_stats_term();
  1540. if (old_options && old_options->ConnDirectionStatistics &&
  1541. !options->ConnDirectionStatistics)
  1542. rep_hist_conn_stats_term();
  1543. if (old_options && old_options->BridgeAuthoritativeDir &&
  1544. !options->BridgeAuthoritativeDir)
  1545. rep_hist_desc_stats_term();
  1546. /* Check if we need to parse and add the EntryNodes config option. */
  1547. if (options->EntryNodes &&
  1548. (!old_options ||
  1549. !routerset_equal(old_options->EntryNodes,options->EntryNodes) ||
  1550. !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes)))
  1551. entry_nodes_should_be_added();
  1552. /* Since our options changed, we might need to regenerate and upload our
  1553. * server descriptor.
  1554. */
  1555. if (!old_options ||
  1556. options_transition_affects_descriptor(old_options, options))
  1557. mark_my_descriptor_dirty("config change");
  1558. /* We may need to reschedule some directory stuff if our status changed. */
  1559. if (old_options) {
  1560. if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
  1561. dirvote_recalculate_timing(options, time(NULL));
  1562. if (!bool_eq(directory_fetches_dir_info_early(options),
  1563. directory_fetches_dir_info_early(old_options)) ||
  1564. !bool_eq(directory_fetches_dir_info_later(options),
  1565. directory_fetches_dir_info_later(old_options))) {
  1566. /* Make sure update_router_have_min_dir_info gets called. */
  1567. router_dir_info_changed();
  1568. /* We might need to download a new consensus status later or sooner than
  1569. * we had expected. */
  1570. update_consensus_networkstatus_fetch_time(time(NULL));
  1571. }
  1572. }
  1573. /* Load the webpage we're going to serve every time someone asks for '/' on
  1574. our DirPort. */
  1575. tor_free(global_dirfrontpagecontents);
  1576. if (options->DirPortFrontPage) {
  1577. global_dirfrontpagecontents =
  1578. read_file_to_str(options->DirPortFrontPage, 0, NULL);
  1579. if (!global_dirfrontpagecontents) {
  1580. log_warn(LD_CONFIG,
  1581. "DirPortFrontPage file '%s' not found. Continuing anyway.",
  1582. options->DirPortFrontPage);
  1583. }
  1584. }
  1585. return 0;
  1586. }
  1587. /** Helper: Read a list of configuration options from the command line.
  1588. * If successful, put them in *<b>result</b> and return 0, and return
  1589. * -1 and leave *<b>result</b> alone. */
  1590. static int
  1591. config_get_commandlines(int argc, char **argv, config_line_t **result)
  1592. {
  1593. config_line_t *front = NULL;
  1594. config_line_t **new = &front;
  1595. char *s;
  1596. int i = 1;
  1597. while (i < argc) {
  1598. unsigned command = CONFIG_LINE_NORMAL;
  1599. int want_arg = 1;
  1600. if (!strcmp(argv[i],"-f") ||
  1601. !strcmp(argv[i],"--defaults-torrc") ||
  1602. !strcmp(argv[i],"--hash-password")) {
  1603. i += 2; /* command-line option with argument. ignore them. */
  1604. continue;
  1605. } else if (!strcmp(argv[i],"--list-fingerprint") ||
  1606. !strcmp(argv[i],"--verify-config") ||
  1607. !strcmp(argv[i],"--ignore-missing-torrc") ||
  1608. !strcmp(argv[i],"--quiet") ||
  1609. !strcmp(argv[i],"--hush")) {
  1610. i += 1; /* command-line option. ignore it. */
  1611. continue;
  1612. } else if (!strcmp(argv[i],"--nt-service") ||
  1613. !strcmp(argv[i],"-nt-service")) {
  1614. i += 1;
  1615. continue;
  1616. }
  1617. *new = tor_malloc_zero(sizeof(config_line_t));
  1618. s = argv[i];
  1619. /* Each keyword may be prefixed with one or two dashes. */
  1620. if (*s == '-')
  1621. s++;
  1622. if (*s == '-')
  1623. s++;
  1624. /* Figure out the command, if any. */
  1625. if (*s == '+') {
  1626. s++;
  1627. command = CONFIG_LINE_APPEND;
  1628. } else if (*s == '/') {
  1629. s++;
  1630. command = CONFIG_LINE_CLEAR;
  1631. /* A 'clear' command has no argument. */
  1632. want_arg = 0;
  1633. }
  1634. if (want_arg && i == argc-1) {
  1635. log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
  1636. argv[i]);
  1637. config_free_lines(front);
  1638. return -1;
  1639. }
  1640. (*new)->key = tor_strdup(config_expand_abbrev(&options_format, s, 1, 1));
  1641. (*new)->value = want_arg ? tor_strdup(argv[i+1]) : tor_strdup("");
  1642. (*new)->command = command;
  1643. (*new)->next = NULL;
  1644. log_debug(LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
  1645. (*new)->key, (*new)->value);
  1646. new = &((*new)->next);
  1647. i += want_arg ? 2 : 1;
  1648. }
  1649. *result = front;
  1650. return 0;
  1651. }
  1652. /** Return true iff key is a valid configuration option. */
  1653. int
  1654. option_is_recognized(const char *key)
  1655. {
  1656. const config_var_t *var = config_find_option(&options_format, key);
  1657. return (var != NULL);
  1658. }
  1659. /** Return the canonical name of a configuration option, or NULL
  1660. * if no such option exists. */
  1661. const char *
  1662. option_get_canonical_name(const char *key)
  1663. {
  1664. const config_var_t *var = config_find_option(&options_format, key);
  1665. return var ? var->name : NULL;
  1666. }
  1667. /** Return a canonical list of the options assigned for key.
  1668. */
  1669. config_line_t *
  1670. option_get_assignment(const or_options_t *options, const char *key)
  1671. {
  1672. return config_get_assigned_option(&options_format, options, key, 1);
  1673. }
  1674. /** Try assigning <b>list</b> to the global options. You do this by duping
  1675. * options, assigning list to the new one, then validating it. If it's
  1676. * ok, then throw out the old one and stick with the new one. Else,
  1677. * revert to old and return failure. Return SETOPT_OK on success, or
  1678. * a setopt_err_t on failure.
  1679. *
  1680. * If not success, point *<b>msg</b> to a newly allocated string describing
  1681. * what went wrong.
  1682. */
  1683. setopt_err_t
  1684. options_trial_assign(config_line_t *list, int use_defaults,
  1685. int clear_first, char **msg)
  1686. {
  1687. int r;
  1688. or_options_t *trial_options = config_dup(&options_format, get_options());
  1689. if ((r=config_assign(&options_format, trial_options,
  1690. list, use_defaults, clear_first, msg)) < 0) {
  1691. config_free(&options_format, trial_options);
  1692. return r;
  1693. }
  1694. if (options_validate(get_options_mutable(), trial_options, 1, msg) < 0) {
  1695. config_free(&options_format, trial_options);
  1696. return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
  1697. }
  1698. if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
  1699. config_free(&options_format, trial_options);
  1700. return SETOPT_ERR_TRANSITION;
  1701. }
  1702. if (set_options(trial_options, msg)<0) {
  1703. config_free(&options_format, trial_options);
  1704. return SETOPT_ERR_SETTING;
  1705. }
  1706. /* we liked it. put it in place. */
  1707. return SETOPT_OK;
  1708. }
  1709. /** Print a usage message for tor. */
  1710. static void
  1711. print_usage(void)
  1712. {
  1713. printf(
  1714. "Copyright (c) 2001-2004, Roger Dingledine\n"
  1715. "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
  1716. "Copyright (c) 2007-2013, The Tor Project, Inc.\n\n"
  1717. "tor -f <torrc> [args]\n"
  1718. "See man page for options, or https://www.torproject.org/ for "
  1719. "documentation.\n");
  1720. }
  1721. /** Print all non-obsolete torrc options. */
  1722. static void
  1723. list_torrc_options(void)
  1724. {
  1725. int i;
  1726. smartlist_t *lines = smartlist_new();
  1727. for (i = 0; option_vars_[i].name; ++i) {
  1728. const config_var_t *var = &option_vars_[i];
  1729. if (var->type == CONFIG_TYPE_OBSOLETE ||
  1730. var->type == CONFIG_TYPE_LINELIST_V)
  1731. continue;
  1732. printf("%s\n", var->name);
  1733. }
  1734. smartlist_free(lines);
  1735. }
  1736. /** Last value actually set by resolve_my_address. */
  1737. static uint32_t last_resolved_addr = 0;
  1738. /** Accessor for last_resolved_addr from outside this file. */
  1739. uint32_t
  1740. get_last_resolved_addr(void)
  1741. {
  1742. return last_resolved_addr;
  1743. }
  1744. /**
  1745. * Use <b>options-\>Address</b> to guess our public IP address.
  1746. *
  1747. * Return 0 if all is well, or -1 if we can't find a suitable
  1748. * public IP address.
  1749. *
  1750. * If we are returning 0:
  1751. * - Put our public IP address (in host order) into *<b>addr_out</b>.
  1752. * - If <b>method_out</b> is non-NULL, set *<b>method_out</b> to a static
  1753. * string describing how we arrived at our answer.
  1754. * - If <b>hostname_out</b> is non-NULL, and we resolved a hostname to
  1755. * get our address, set *<b>hostname_out</b> to a newly allocated string
  1756. * holding that hostname. (If we didn't get our address by resolving a
  1757. * hostname, set *<b>hostname_out</b> to NULL.)
  1758. *
  1759. * XXXX ipv6
  1760. */
  1761. int
  1762. resolve_my_address(int warn_severity, const or_options_t *options,
  1763. uint32_t *addr_out,
  1764. const char **method_out, char **hostname_out)
  1765. {
  1766. struct in_addr in;
  1767. uint32_t addr; /* host order */
  1768. char hostname[256];
  1769. const char *method_used;
  1770. const char *hostname_used;
  1771. int explicit_ip=1;
  1772. int explicit_hostname=1;
  1773. int from_interface=0;
  1774. char *addr_string = NULL;
  1775. const char *address = options->Address;
  1776. int notice_severity = warn_severity <= LOG_NOTICE ?
  1777. LOG_NOTICE : warn_severity;
  1778. tor_assert(addr_out);
  1779. /*
  1780. * Step one: Fill in 'hostname' to be our best guess.
  1781. */
  1782. if (address && *address) {
  1783. strlcpy(hostname, address, sizeof(hostname));
  1784. } else { /* then we need to guess our address */
  1785. explicit_ip = 0; /* it's implicit */
  1786. explicit_hostname = 0; /* it's implicit */
  1787. if (gethostname(hostname, sizeof(hostname)) < 0) {
  1788. log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
  1789. return -1;
  1790. }
  1791. log_debug(LD_CONFIG, "Guessed local host name as '%s'", hostname);
  1792. }
  1793. /*
  1794. * Step two: Now that we know 'hostname', parse it or resolve it. If
  1795. * it doesn't parse or resolve, look at the interface address. Set 'addr'
  1796. * to be our (host-order) 32-bit answer.
  1797. */
  1798. if (tor_inet_aton(hostname, &in) == 0) {
  1799. /* then we have to resolve it */
  1800. explicit_ip = 0;
  1801. if (tor_lookup_hostname(hostname, &addr)) { /* failed to resolve */
  1802. uint32_t interface_ip; /* host order */
  1803. if (explicit_hostname) {
  1804. log_fn(warn_severity, LD_CONFIG,
  1805. "Could not resolve local Address '%s'. Failing.", hostname);
  1806. return -1;
  1807. }
  1808. log_fn(notice_severity, LD_CONFIG,
  1809. "Could not resolve guessed local hostname '%s'. "
  1810. "Trying something else.", hostname);
  1811. if (get_interface_address(warn_severity, &interface_ip)) {
  1812. log_fn(warn_severity, LD_CONFIG,
  1813. "Could not get local interface IP address. Failing.");
  1814. return -1;
  1815. }
  1816. from_interface = 1;
  1817. addr = interface_ip;
  1818. log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
  1819. "local interface. Using that.", fmt_addr32(addr));
  1820. strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
  1821. } else { /* resolved hostname into addr */
  1822. if (!explicit_hostname &&
  1823. is_internal_IP(addr, 0)) {
  1824. uint32_t interface_ip;
  1825. log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
  1826. "resolves to a private IP address (%s). Trying something "
  1827. "else.", hostname, fmt_addr32(addr));
  1828. if (get_interface_address(warn_severity, &interface_ip)) {
  1829. log_fn(warn_severity, LD_CONFIG,
  1830. "Could not get local interface IP address. Too bad.");
  1831. } else if (is_internal_IP(interface_ip, 0)) {
  1832. log_fn(notice_severity, LD_CONFIG,
  1833. "Interface IP address '%s' is a private address too. "
  1834. "Ignoring.", fmt_addr32(interface_ip));
  1835. } else {
  1836. from_interface = 1;
  1837. addr = interface_ip;
  1838. log_fn(notice_severity, LD_CONFIG,
  1839. "Learned IP address '%s' for local interface."
  1840. " Using that.", fmt_addr32(addr));
  1841. strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
  1842. }
  1843. }
  1844. }
  1845. } else {
  1846. addr = ntohl(in.s_addr); /* set addr so that addr_string is not
  1847. * illformed */
  1848. }
  1849. /*
  1850. * Step three: Check whether 'addr' is an internal IP address, and error
  1851. * out if it is and we don't want that.
  1852. */
  1853. addr_string = tor_dup_ip(addr);
  1854. if (is_internal_IP(addr, 0)) {
  1855. /* make sure we're ok with publishing an internal IP */
  1856. if (!options->DirAuthorities && !options->AlternateDirAuthority) {
  1857. /* if they are using the default authorities, disallow internal IPs
  1858. * always. */
  1859. log_fn(warn_severity, LD_CONFIG,
  1860. "Address '%s' resolves to private IP address '%s'. "
  1861. "Tor servers that use the default DirAuthorities must have "
  1862. "public IP addresses.", hostname, addr_string);
  1863. tor_free(addr_string);
  1864. return -1;
  1865. }
  1866. if (!explicit_ip) {
  1867. /* even if they've set their own authorities, require an explicit IP if
  1868. * they're using an internal address. */
  1869. log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
  1870. "IP address '%s'. Please set the Address config option to be "
  1871. "the IP address you want to use.", hostname, addr_string);
  1872. tor_free(addr_string);
  1873. return -1;
  1874. }
  1875. }
  1876. /*
  1877. * Step four: We have a winner! 'addr' is our answer for sure, and
  1878. * 'addr_string' is its string form. Fill out the various fields to
  1879. * say how we decided it.
  1880. */
  1881. log_debug(LD_CONFIG, "Resolved Address to '%s'.", addr_string);
  1882. if (explicit_ip) {
  1883. method_used = "CONFIGURED";
  1884. hostname_used = NULL;
  1885. } else if (explicit_hostname) {
  1886. method_used = "RESOLVED";
  1887. hostname_used = hostname;
  1888. } else if (from_interface) {
  1889. method_used = "INTERFACE";
  1890. hostname_used = NULL;
  1891. } else {
  1892. method_used = "GETHOSTNAME";
  1893. hostname_used = hostname;
  1894. }
  1895. *addr_out = addr;
  1896. if (method_out)
  1897. *method_out = method_used;
  1898. if (hostname_out)
  1899. *hostname_out = hostname_used ? tor_strdup(hostname_used) : NULL;
  1900. /*
  1901. * Step five: Check if the answer has changed since last time (or if
  1902. * there was no last time), and if so call various functions to keep
  1903. * us up-to-date.
  1904. */
  1905. if (last_resolved_addr && last_resolved_addr != *addr_out) {
  1906. /* Leave this as a notice, regardless of the requested severity,
  1907. * at least until dynamic IP address support becomes bulletproof. */
  1908. log_notice(LD_NET,
  1909. "Your IP address seems to have changed to %s "
  1910. "(METHOD=%s%s%s). Updating.",
  1911. addr_string, method_used,
  1912. hostname_used ? " HOSTNAME=" : "",
  1913. hostname_used ? hostname_used : "");
  1914. ip_address_changed(0);
  1915. }
  1916. if (last_resolved_addr != *addr_out) {
  1917. control_event_server_status(LOG_NOTICE,
  1918. "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s%s%s",
  1919. addr_string, method_used,
  1920. hostname_used ? " HOSTNAME=" : "",
  1921. hostname_used ? hostname_used : "");
  1922. }
  1923. last_resolved_addr = *addr_out;
  1924. /*
  1925. * And finally, clean up and return success.
  1926. */
  1927. tor_free(addr_string);
  1928. return 0;
  1929. }
  1930. /** Return true iff <b>addr</b> is judged to be on the same network as us, or
  1931. * on a private network.
  1932. */
  1933. int
  1934. is_local_addr(const tor_addr_t *addr)
  1935. {
  1936. if (tor_addr_is_internal(addr, 0))
  1937. return 1;
  1938. /* Check whether ip is on the same /24 as we are. */
  1939. if (get_options()->EnforceDistinctSubnets == 0)
  1940. return 0;
  1941. if (tor_addr_family(addr) == AF_INET) {
  1942. /*XXXX023 IP6 what corresponds to an /24? */
  1943. uint32_t ip = tor_addr_to_ipv4h(addr);
  1944. /* It's possible that this next check will hit before the first time
  1945. * resolve_my_address actually succeeds. (For clients, it is likely that
  1946. * resolve_my_address will never be called at all). In those cases,
  1947. * last_resolved_addr will be 0, and so checking to see whether ip is on
  1948. * the same /24 as last_resolved_addr will be the same as checking whether
  1949. * it was on net 0, which is already done by is_internal_IP.
  1950. */
  1951. if ((last_resolved_addr & (uint32_t)0xffffff00ul)
  1952. == (ip & (uint32_t)0xffffff00ul))
  1953. return 1;
  1954. }
  1955. return 0;
  1956. }
  1957. /** Return a new empty or_options_t. Used for testing. */
  1958. or_options_t *
  1959. options_new(void)
  1960. {
  1961. return config_new(&options_format);
  1962. }
  1963. /** Set <b>options</b> to hold reasonable defaults for most options.
  1964. * Each option defaults to zero. */
  1965. void
  1966. options_init(or_options_t *options)
  1967. {
  1968. config_init(&options_format, options);
  1969. }
  1970. /** Return a string containing a possible configuration file that would give
  1971. * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
  1972. * include options that are the same as Tor's defaults.
  1973. */
  1974. char *
  1975. options_dump(const or_options_t *options, int minimal)
  1976. {
  1977. return config_dump(&options_format, global_default_options,
  1978. options, minimal, 0);
  1979. }
  1980. /** Return 0 if every element of sl is a string holding a decimal
  1981. * representation of a port number, or if sl is NULL.
  1982. * Otherwise set *msg and return -1. */
  1983. static int
  1984. validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
  1985. {
  1986. int i;
  1987. tor_assert(name);
  1988. if (!sl)
  1989. return 0;
  1990. SMARTLIST_FOREACH(sl, const char *, cp,
  1991. {
  1992. i = atoi(cp);
  1993. if (i < 1 || i > 65535) {
  1994. tor_asprintf(msg, "Port '%s' out of range in %s", cp, name);
  1995. return -1;
  1996. }
  1997. });
  1998. return 0;
  1999. }
  2000. /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
  2001. * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
  2002. * Else return 0.
  2003. */
  2004. static int
  2005. ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
  2006. {
  2007. if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
  2008. /* This handles an understandable special case where somebody says "2gb"
  2009. * whereas our actual maximum is 2gb-1 (INT_MAX) */
  2010. --*value;
  2011. }
  2012. if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
  2013. tor_asprintf(msg, "%s ("U64_FORMAT") must be at most %d",
  2014. desc, U64_PRINTF_ARG(*value),
  2015. ROUTER_MAX_DECLARED_BANDWIDTH);
  2016. return -1;
  2017. }
  2018. return 0;
  2019. }
  2020. /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
  2021. * and write it to <b>options</b>-\>PublishServerDescriptor_. Treat "1"
  2022. * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
  2023. * Treat "0" as "".
  2024. * Return 0 on success or -1 if not a recognized authority type (in which
  2025. * case the value of PublishServerDescriptor_ is undefined). */
  2026. static int
  2027. compute_publishserverdescriptor(or_options_t *options)
  2028. {
  2029. smartlist_t *list = options->PublishServerDescriptor;
  2030. dirinfo_type_t *auth = &options->PublishServerDescriptor_;
  2031. *auth = NO_DIRINFO;
  2032. if (!list) /* empty list, answer is none */
  2033. return 0;
  2034. SMARTLIST_FOREACH_BEGIN(list, const char *, string) {
  2035. if (!strcasecmp(string, "v1"))
  2036. *auth |= V1_DIRINFO;
  2037. else if (!strcmp(string, "1"))
  2038. if (options->BridgeRelay)
  2039. *auth |= BRIDGE_DIRINFO;
  2040. else
  2041. *auth |= V2_DIRINFO | V3_DIRINFO;
  2042. else if (!strcasecmp(string, "v2"))
  2043. *auth |= V2_DIRINFO;
  2044. else if (!strcasecmp(string, "v3"))
  2045. *auth |= V3_DIRINFO;
  2046. else if (!strcasecmp(string, "bridge"))
  2047. *auth |= BRIDGE_DIRINFO;
  2048. else if (!strcasecmp(string, "hidserv"))
  2049. log_warn(LD_CONFIG,
  2050. "PublishServerDescriptor hidserv is invalid. See "
  2051. "PublishHidServDescriptors.");
  2052. else if (!strcasecmp(string, "") || !strcmp(string, "0"))
  2053. /* no authority */;
  2054. else
  2055. return -1;
  2056. } SMARTLIST_FOREACH_END(string);
  2057. return 0;
  2058. }
  2059. /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
  2060. * services can overload the directory system. */
  2061. #define MIN_REND_POST_PERIOD (10*60)
  2062. /** Highest allowable value for RendPostPeriod. */
  2063. #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
  2064. /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
  2065. * will generate too many circuits and potentially overload the network. */
  2066. #define MIN_MAX_CIRCUIT_DIRTINESS 10
  2067. /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
  2068. * will generate too many circuits and potentially overload the network. */
  2069. #define MIN_CIRCUIT_STREAM_TIMEOUT 10
  2070. /** Lowest allowable value for HeartbeatPeriod; if this is too low, we might
  2071. * expose more information than we're comfortable with. */
  2072. #define MIN_HEARTBEAT_PERIOD (30*60)
  2073. /** Lowest recommended value for CircuitBuildTimeout; if it is set too low
  2074. * and LearnCircuitBuildTimeout is off, the failure rate for circuit
  2075. * construction may be very high. In that case, if it is set below this
  2076. * threshold emit a warning.
  2077. * */
  2078. #define RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT (10)
  2079. /** Return 0 if every setting in <b>options</b> is reasonable, and a
  2080. * permissible transition from <b>old_options</b>. Else return -1.
  2081. * Should have no side effects, except for normalizing the contents of
  2082. * <b>options</b>.
  2083. *
  2084. * On error, tor_strdup an error explanation into *<b>msg</b>.
  2085. *
  2086. * XXX
  2087. * If <b>from_setconf</b>, we were called by the controller, and our
  2088. * Log line should stay empty. If it's 0, then give us a default log
  2089. * if there are no logs defined.
  2090. */
  2091. static int
  2092. options_validate(or_options_t *old_options, or_options_t *options,
  2093. int from_setconf, char **msg)
  2094. {
  2095. int i;
  2096. config_line_t *cl;
  2097. const char *uname = get_uname();
  2098. int n_ports=0;
  2099. #define REJECT(arg) \
  2100. STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
  2101. #define COMPLAIN(arg) STMT_BEGIN log_warn(LD_CONFIG, arg); STMT_END
  2102. tor_assert(msg);
  2103. *msg = NULL;
  2104. if (server_mode(options) &&
  2105. (!strcmpstart(uname, "Windows 95") ||
  2106. !strcmpstart(uname, "Windows 98") ||
  2107. !strcmpstart(uname, "Windows Me"))) {
  2108. log_warn(LD_CONFIG, "Tor is running as a server, but you are "
  2109. "running %s; this probably won't work. See "
  2110. "https://wiki.torproject.org/TheOnionRouter/TorFAQ#ServerOS "
  2111. "for details.", uname);
  2112. }
  2113. if (parse_ports(options, 1, msg, &n_ports) < 0)
  2114. return -1;
  2115. if (parse_outbound_addresses(options, 1, msg) < 0)
  2116. return -1;
  2117. if (validate_data_directory(options)<0)
  2118. REJECT("Invalid DataDirectory");
  2119. if (options->Nickname == NULL) {
  2120. if (server_mode(options)) {
  2121. options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
  2122. }
  2123. } else {
  2124. if (!is_legal_nickname(options->Nickname)) {
  2125. tor_asprintf(msg,
  2126. "Nickname '%s' is wrong length or contains illegal characters.",
  2127. options->Nickname);
  2128. return -1;
  2129. }
  2130. }
  2131. if (server_mode(options) && !options->ContactInfo)
  2132. log_notice(LD_CONFIG, "Your ContactInfo config option is not set. "
  2133. "Please consider setting it, so we can contact you if your server is "
  2134. "misconfigured or something else goes wrong.");
  2135. /* Special case on first boot if no Log options are given. */
  2136. if (!options->Logs && !options->RunAsDaemon && !from_setconf) {
  2137. if (quiet_level == 0)
  2138. config_line_append(&options->Logs, "Log", "notice stdout");
  2139. else if (quiet_level == 1)
  2140. config_line_append(&options->Logs, "Log", "warn stdout");
  2141. }
  2142. if (options_init_logs(options, 1)<0) /* Validate the tor_log(s) */
  2143. REJECT("Failed to validate Log options. See logs for details.");
  2144. if (authdir_mode(options)) {
  2145. /* confirm that our address isn't broken, so we can complain now */
  2146. uint32_t tmp;
  2147. if (resolve_my_address(LOG_WARN, options, &tmp, NULL, NULL) < 0)
  2148. REJECT("Failed to resolve/guess local address. See logs for details.");
  2149. }
  2150. #ifndef _WIN32
  2151. if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
  2152. REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
  2153. #endif
  2154. /* XXXX require that the only port not be DirPort? */
  2155. /* XXXX require that at least one port be listened-upon. */
  2156. if (n_ports == 0 && !options->RendConfigLines)
  2157. log_warn(LD_CONFIG,
  2158. "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
  2159. "undefined, and there aren't any hidden services configured. "
  2160. "Tor will still run, but probably won't do anything.");
  2161. #ifndef USE_TRANSPARENT
  2162. /* XXXX024 I think we can remove this TransListenAddress */
  2163. if (options->TransPort_set || options->TransListenAddress)
  2164. REJECT("TransPort and TransListenAddress are disabled in this build.");
  2165. #endif
  2166. if (options->TokenBucketRefillInterval <= 0
  2167. || options->TokenBucketRefillInterval > 1000) {
  2168. REJECT("TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
  2169. }
  2170. if (options->DisableV2DirectoryInfo_ && ! authdir_mode(options)) {
  2171. REJECT("DisableV2DirectoryInfo_ set, but we aren't an authority.");
  2172. }
  2173. if (options->ExcludeExitNodes || options->ExcludeNodes) {
  2174. options->ExcludeExitNodesUnion_ = routerset_new();
  2175. routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeExitNodes);
  2176. routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeNodes);
  2177. }
  2178. if (options->NodeFamilies) {
  2179. options->NodeFamilySets = smartlist_new();
  2180. for (cl = options->NodeFamilies; cl; cl = cl->next) {
  2181. routerset_t *rs = routerset_new();
  2182. if (routerset_parse(rs, cl->value, cl->key) == 0) {
  2183. smartlist_add(options->NodeFamilySets, rs);
  2184. } else {
  2185. routerset_free(rs);
  2186. }
  2187. }
  2188. }
  2189. if (options->TLSECGroup && (strcasecmp(options->TLSECGroup, "P256") &&
  2190. strcasecmp(options->TLSECGroup, "P224"))) {
  2191. COMPLAIN("Unrecognized TLSECGroup: Falling back to the default.");
  2192. tor_free(options->TLSECGroup);
  2193. }
  2194. if (options->ExcludeNodes && options->StrictNodes) {
  2195. COMPLAIN("You have asked to exclude certain relays from all positions "
  2196. "in your circuits. Expect hidden services and other Tor "
  2197. "features to be broken in unpredictable ways.");
  2198. }
  2199. if (options->AuthoritativeDir) {
  2200. if (!options->ContactInfo && !options->TestingTorNetwork)
  2201. REJECT("Authoritative directory servers must set ContactInfo");
  2202. if (options->V1AuthoritativeDir && !options->RecommendedVersions)
  2203. REJECT("V1 authoritative dir servers must set RecommendedVersions.");
  2204. if (!options->RecommendedClientVersions)
  2205. options->RecommendedClientVersions =
  2206. config_lines_dup(options->RecommendedVersions);
  2207. if (!options->RecommendedServerVersions)
  2208. options->RecommendedServerVersions =
  2209. config_lines_dup(options->RecommendedVersions);
  2210. if (options->VersioningAuthoritativeDir &&
  2211. (!options->RecommendedClientVersions ||
  2212. !options->RecommendedServerVersions))
  2213. REJECT("Versioning authoritative dir servers must set "
  2214. "Recommended*Versions.");
  2215. if (options->UseEntryGuards) {
  2216. log_info(LD_CONFIG, "Authoritative directory servers can't set "
  2217. "UseEntryGuards. Disabling.");
  2218. options->UseEntryGuards = 0;
  2219. }
  2220. if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
  2221. log_info(LD_CONFIG, "Authoritative directories always try to download "
  2222. "extra-info documents. Setting DownloadExtraInfo.");
  2223. options->DownloadExtraInfo = 1;
  2224. }
  2225. if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
  2226. options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
  2227. options->V3AuthoritativeDir))
  2228. REJECT("AuthoritativeDir is set, but none of "
  2229. "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
  2230. /* If we have a v3bandwidthsfile and it's broken, complain on startup */
  2231. if (options->V3BandwidthsFile && !old_options) {
  2232. dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
  2233. }
  2234. }
  2235. if (options->AuthoritativeDir && !options->DirPort_set)
  2236. REJECT("Running as authoritative directory, but no DirPort set.");
  2237. if (options->AuthoritativeDir && !options->ORPort_set)
  2238. REJECT("Running as authoritative directory, but no ORPort set.");
  2239. if (options->AuthoritativeDir && options->ClientOnly)
  2240. REJECT("Running as authoritative directory, but ClientOnly also set.");
  2241. if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
  2242. REJECT("FetchDirInfoExtraEarly requires that you also set "
  2243. "FetchDirInfoEarly");
  2244. if (options->HSAuthoritativeDir && proxy_mode(options))
  2245. REJECT("Running as authoritative v0 HS directory, but also configured "
  2246. "as a client.");
  2247. if (options->ConnLimit <= 0) {
  2248. tor_asprintf(msg,
  2249. "ConnLimit must be greater than 0, but was set to %d",
  2250. options->ConnLimit);
  2251. return -1;
  2252. }
  2253. if (options->PathsNeededToBuildCircuits >= 0.0) {
  2254. if (options->PathsNeededToBuildCircuits < 0.25) {
  2255. log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too low. Increasing "
  2256. "to 0.25");
  2257. options->PathsNeededToBuildCircuits = 0.25;
  2258. } else if (options->PathsNeededToBuildCircuits < 0.95) {
  2259. log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too high. Decreasing "
  2260. "to 0.95");
  2261. options->PathsNeededToBuildCircuits = 0.95;
  2262. }
  2263. }
  2264. if (options->MaxClientCircuitsPending <= 0 ||
  2265. options->MaxClientCircuitsPending > MAX_MAX_CLIENT_CIRCUITS_PENDING) {
  2266. tor_asprintf(msg,
  2267. "MaxClientCircuitsPending must be between 1 and %d, but "
  2268. "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING,
  2269. options->MaxClientCircuitsPending);
  2270. return -1;
  2271. }
  2272. if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
  2273. return -1;
  2274. if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
  2275. return -1;
  2276. if (validate_ports_csv(options->RejectPlaintextPorts,
  2277. "RejectPlaintextPorts", msg) < 0)
  2278. return -1;
  2279. if (validate_ports_csv(options->WarnPlaintextPorts,
  2280. "WarnPlaintextPorts", msg) < 0)
  2281. return -1;
  2282. if (options->FascistFirewall && !options->ReachableAddresses) {
  2283. if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
  2284. /* We already have firewall ports set, so migrate them to
  2285. * ReachableAddresses, which will set ReachableORAddresses and
  2286. * ReachableDirAddresses if they aren't set explicitly. */
  2287. smartlist_t *instead = smartlist_new();
  2288. config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
  2289. new_line->key = tor_strdup("ReachableAddresses");
  2290. /* If we're configured with the old format, we need to prepend some
  2291. * open ports. */
  2292. SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
  2293. {
  2294. int p = atoi(portno);
  2295. if (p<0) continue;
  2296. smartlist_add_asprintf(instead, "*:%d", p);
  2297. });
  2298. new_line->value = smartlist_join_strings(instead,",",0,NULL);
  2299. /* These have been deprecated since 0.1.1.5-alpha-cvs */
  2300. log_notice(LD_CONFIG,
  2301. "Converting FascistFirewall and FirewallPorts "
  2302. "config options to new format: \"ReachableAddresses %s\"",
  2303. new_line->value);
  2304. options->ReachableAddresses = new_line;
  2305. SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
  2306. smartlist_free(instead);
  2307. } else {
  2308. /* We do not have FirewallPorts set, so add 80 to
  2309. * ReachableDirAddresses, and 443 to ReachableORAddresses. */
  2310. if (!options->ReachableDirAddresses) {
  2311. config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
  2312. new_line->key = tor_strdup("ReachableDirAddresses");
  2313. new_line->value = tor_strdup("*:80");
  2314. options->ReachableDirAddresses = new_line;
  2315. log_notice(LD_CONFIG, "Converting FascistFirewall config option "
  2316. "to new format: \"ReachableDirAddresses *:80\"");
  2317. }
  2318. if (!options->ReachableORAddresses) {
  2319. config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
  2320. new_line->key = tor_strdup("ReachableORAddresses");
  2321. new_line->value = tor_strdup("*:443");
  2322. options->ReachableORAddresses = new_line;
  2323. log_notice(LD_CONFIG, "Converting FascistFirewall config option "
  2324. "to new format: \"ReachableORAddresses *:443\"");
  2325. }
  2326. }
  2327. }
  2328. for (i=0; i<3; i++) {
  2329. config_line_t **linep =
  2330. (i==0) ? &options->ReachableAddresses :
  2331. (i==1) ? &options->ReachableORAddresses :
  2332. &options->ReachableDirAddresses;
  2333. if (!*linep)
  2334. continue;
  2335. /* We need to end with a reject *:*, not an implicit accept *:* */
  2336. for (;;) {
  2337. if (!strcmp((*linep)->value, "reject *:*")) /* already there */
  2338. break;
  2339. linep = &((*linep)->next);
  2340. if (!*linep) {
  2341. *linep = tor_malloc_zero(sizeof(config_line_t));
  2342. (*linep)->key = tor_strdup(
  2343. (i==0) ? "ReachableAddresses" :
  2344. (i==1) ? "ReachableORAddresses" :
  2345. "ReachableDirAddresses");
  2346. (*linep)->value = tor_strdup("reject *:*");
  2347. break;
  2348. }
  2349. }
  2350. }
  2351. if ((options->ReachableAddresses ||
  2352. options->ReachableORAddresses ||
  2353. options->ReachableDirAddresses) &&
  2354. server_mode(options))
  2355. REJECT("Servers must be able to freely connect to the rest "
  2356. "of the Internet, so they must not set Reachable*Addresses "
  2357. "or FascistFirewall.");
  2358. if (options->UseBridges &&
  2359. server_mode(options))
  2360. REJECT("Servers must be able to freely connect to the rest "
  2361. "of the Internet, so they must not set UseBridges.");
  2362. /* If both of these are set, we'll end up with funny behavior where we
  2363. * demand enough entrynodes be up and running else we won't build
  2364. * circuits, yet we never actually use them. */
  2365. if (options->UseBridges && options->EntryNodes)
  2366. REJECT("You cannot set both UseBridges and EntryNodes.");
  2367. if (options->EntryNodes && !options->UseEntryGuards) {
  2368. REJECT("If EntryNodes is set, UseEntryGuards must be enabled.");
  2369. }
  2370. options->AllowInvalid_ = 0;
  2371. if (options->AllowInvalidNodes) {
  2372. SMARTLIST_FOREACH_BEGIN(options->AllowInvalidNodes, const char *, cp) {
  2373. if (!strcasecmp(cp, "entry"))
  2374. options->AllowInvalid_ |= ALLOW_INVALID_ENTRY;
  2375. else if (!strcasecmp(cp, "exit"))
  2376. options->AllowInvalid_ |= ALLOW_INVALID_EXIT;
  2377. else if (!strcasecmp(cp, "middle"))
  2378. options->AllowInvalid_ |= ALLOW_INVALID_MIDDLE;
  2379. else if (!strcasecmp(cp, "introduction"))
  2380. options->AllowInvalid_ |= ALLOW_INVALID_INTRODUCTION;
  2381. else if (!strcasecmp(cp, "rendezvous"))
  2382. options->AllowInvalid_ |= ALLOW_INVALID_RENDEZVOUS;
  2383. else {
  2384. tor_asprintf(msg,
  2385. "Unrecognized value '%s' in AllowInvalidNodes", cp);
  2386. return -1;
  2387. }
  2388. } SMARTLIST_FOREACH_END(cp);
  2389. }
  2390. if (!options->SafeLogging ||
  2391. !strcasecmp(options->SafeLogging, "0")) {
  2392. options->SafeLogging_ = SAFELOG_SCRUB_NONE;
  2393. } else if (!strcasecmp(options->SafeLogging, "relay")) {
  2394. options->SafeLogging_ = SAFELOG_SCRUB_RELAY;
  2395. } else if (!strcasecmp(options->SafeLogging, "1")) {
  2396. options->SafeLogging_ = SAFELOG_SCRUB_ALL;
  2397. } else {
  2398. tor_asprintf(msg,
  2399. "Unrecognized value '%s' in SafeLogging",
  2400. escaped(options->SafeLogging));
  2401. return -1;
  2402. }
  2403. if (compute_publishserverdescriptor(options) < 0) {
  2404. tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
  2405. return -1;
  2406. }
  2407. if ((options->BridgeRelay
  2408. || options->PublishServerDescriptor_ & BRIDGE_DIRINFO)
  2409. && (options->PublishServerDescriptor_
  2410. & (V1_DIRINFO|V2_DIRINFO|V3_DIRINFO))) {
  2411. REJECT("Bridges are not supposed to publish router descriptors to the "
  2412. "directory authorities. Please correct your "
  2413. "PublishServerDescriptor line.");
  2414. }
  2415. if (options->BridgeRelay && options->DirPort_set) {
  2416. log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
  2417. "DirPort");
  2418. config_free_lines(options->DirPort_lines);
  2419. options->DirPort_lines = NULL;
  2420. options->DirPort_set = 0;
  2421. }
  2422. if (options->MinUptimeHidServDirectoryV2 < 0) {
  2423. log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
  2424. "least 0 seconds. Changing to 0.");
  2425. options->MinUptimeHidServDirectoryV2 = 0;
  2426. }
  2427. if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
  2428. log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
  2429. "raising to %d seconds.", MIN_REND_POST_PERIOD);
  2430. options->RendPostPeriod = MIN_REND_POST_PERIOD;
  2431. }
  2432. if (options->RendPostPeriod > MAX_DIR_PERIOD) {
  2433. log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
  2434. MAX_DIR_PERIOD);
  2435. options->RendPostPeriod = MAX_DIR_PERIOD;
  2436. }
  2437. if (options->Tor2webMode && options->LearnCircuitBuildTimeout) {
  2438. /* LearnCircuitBuildTimeout and Tor2webMode are incompatible in
  2439. * two ways:
  2440. *
  2441. * - LearnCircuitBuildTimeout results in a low CBT, which
  2442. * Tor2webMode's use of one-hop rendezvous circuits lowers
  2443. * much further, producing *far* too many timeouts.
  2444. *
  2445. * - The adaptive CBT code does not update its timeout estimate
  2446. * using build times for single-hop circuits.
  2447. *
  2448. * If we fix both of these issues someday, we should test
  2449. * Tor2webMode with LearnCircuitBuildTimeout on again. */
  2450. log_notice(LD_CONFIG,"Tor2webMode is enabled; turning "
  2451. "LearnCircuitBuildTimeout off.");
  2452. options->LearnCircuitBuildTimeout = 0;
  2453. }
  2454. if (options->Tor2webMode && options->UseEntryGuards) {
  2455. /* tor2web mode clients do not (and should not) use entry guards
  2456. * in any meaningful way. Further, tor2web mode causes the hidden
  2457. * service client code to do things which break the path bias
  2458. * detector, and it's far easier to turn off entry guards (and
  2459. * thus the path bias detector with it) than to figure out how to
  2460. * make a piece of code which cannot possibly help tor2web mode
  2461. * users compatible with tor2web mode.
  2462. */
  2463. log_notice(LD_CONFIG,
  2464. "Tor2WebMode is enabled; disabling UseEntryGuards.");
  2465. options->UseEntryGuards = 0;
  2466. }
  2467. if (!(options->UseEntryGuards) &&
  2468. (options->RendConfigLines != NULL)) {
  2469. log_warn(LD_CONFIG,
  2470. "UseEntryGuards is disabled, but you have configured one or more "
  2471. "hidden services on this Tor instance. Your hidden services "
  2472. "will be very easy to locate using a well-known attack -- see "
  2473. "http://freehaven.net/anonbib/#hs-attack06 for details.");
  2474. }
  2475. if (!options->LearnCircuitBuildTimeout && options->CircuitBuildTimeout &&
  2476. options->CircuitBuildTimeout < RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT) {
  2477. log_warn(LD_CONFIG,
  2478. "CircuitBuildTimeout is shorter (%d seconds) than the recommended "
  2479. "minimum (%d seconds), and LearnCircuitBuildTimeout is disabled. "
  2480. "If tor isn't working, raise this value or enable "
  2481. "LearnCircuitBuildTimeout.",
  2482. options->CircuitBuildTimeout,
  2483. RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT );
  2484. } else if (!options->LearnCircuitBuildTimeout &&
  2485. !options->CircuitBuildTimeout) {
  2486. log_notice(LD_CONFIG, "You disabled LearnCircuitBuildTimeout, but didn't "
  2487. "a CircuitBuildTimeout. I'll pick a plausible default.");
  2488. }
  2489. if (options->PathBiasNoticeRate > 1.0) {
  2490. tor_asprintf(msg,
  2491. "PathBiasNoticeRate is too high. "
  2492. "It must be between 0 and 1.0");
  2493. return -1;
  2494. }
  2495. if (options->PathBiasWarnRate > 1.0) {
  2496. tor_asprintf(msg,
  2497. "PathBiasWarnRate is too high. "
  2498. "It must be between 0 and 1.0");
  2499. return -1;
  2500. }
  2501. if (options->PathBiasExtremeRate > 1.0) {
  2502. tor_asprintf(msg,
  2503. "PathBiasExtremeRate is too high. "
  2504. "It must be between 0 and 1.0");
  2505. return -1;
  2506. }
  2507. if (options->PathBiasNoticeUseRate > 1.0) {
  2508. tor_asprintf(msg,
  2509. "PathBiasNoticeUseRate is too high. "
  2510. "It must be between 0 and 1.0");
  2511. return -1;
  2512. }
  2513. if (options->PathBiasExtremeUseRate > 1.0) {
  2514. tor_asprintf(msg,
  2515. "PathBiasExtremeUseRate is too high. "
  2516. "It must be between 0 and 1.0");
  2517. return -1;
  2518. }
  2519. if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
  2520. log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
  2521. "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
  2522. options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
  2523. }
  2524. if (options->CircuitStreamTimeout &&
  2525. options->CircuitStreamTimeout < MIN_CIRCUIT_STREAM_TIMEOUT) {
  2526. log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
  2527. "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
  2528. options->CircuitStreamTimeout = MIN_CIRCUIT_STREAM_TIMEOUT;
  2529. }
  2530. if (options->HeartbeatPeriod &&
  2531. options->HeartbeatPeriod < MIN_HEARTBEAT_PERIOD) {
  2532. log_warn(LD_CONFIG, "HeartbeatPeriod option is too short; "
  2533. "raising to %d seconds.", MIN_HEARTBEAT_PERIOD);
  2534. options->HeartbeatPeriod = MIN_HEARTBEAT_PERIOD;
  2535. }
  2536. if (options->KeepalivePeriod < 1)
  2537. REJECT("KeepalivePeriod option must be positive.");
  2538. if (ensure_bandwidth_cap(&options->BandwidthRate,
  2539. "BandwidthRate", msg) < 0)
  2540. return -1;
  2541. if (ensure_bandwidth_cap(&options->BandwidthBurst,
  2542. "BandwidthBurst", msg) < 0)
  2543. return -1;
  2544. if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
  2545. "MaxAdvertisedBandwidth", msg) < 0)
  2546. return -1;
  2547. if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
  2548. "RelayBandwidthRate", msg) < 0)
  2549. return -1;
  2550. if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
  2551. "RelayBandwidthBurst", msg) < 0)
  2552. return -1;
  2553. if (ensure_bandwidth_cap(&options->PerConnBWRate,
  2554. "PerConnBWRate", msg) < 0)
  2555. return -1;
  2556. if (ensure_bandwidth_cap(&options->PerConnBWBurst,
  2557. "PerConnBWBurst", msg) < 0)
  2558. return -1;
  2559. if (ensure_bandwidth_cap(&options->AuthDirFastGuarantee,
  2560. "AuthDirFastGuarantee", msg) < 0)
  2561. return -1;
  2562. if (ensure_bandwidth_cap(&options->AuthDirGuardBWGuarantee,
  2563. "AuthDirGuardBWGuarantee", msg) < 0)
  2564. return -1;
  2565. if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
  2566. options->RelayBandwidthBurst = options->RelayBandwidthRate;
  2567. if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
  2568. options->RelayBandwidthRate = options->RelayBandwidthBurst;
  2569. if (server_mode(options)) {
  2570. if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
  2571. tor_asprintf(msg,
  2572. "BandwidthRate is set to %d bytes/second. "
  2573. "For servers, it must be at least %d.",
  2574. (int)options->BandwidthRate,
  2575. ROUTER_REQUIRED_MIN_BANDWIDTH);
  2576. return -1;
  2577. } else if (options->MaxAdvertisedBandwidth <
  2578. ROUTER_REQUIRED_MIN_BANDWIDTH/2) {
  2579. tor_asprintf(msg,
  2580. "MaxAdvertisedBandwidth is set to %d bytes/second. "
  2581. "For servers, it must be at least %d.",
  2582. (int)options->MaxAdvertisedBandwidth,
  2583. ROUTER_REQUIRED_MIN_BANDWIDTH/2);
  2584. return -1;
  2585. }
  2586. if (options->RelayBandwidthRate &&
  2587. options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
  2588. tor_asprintf(msg,
  2589. "RelayBandwidthRate is set to %d bytes/second. "
  2590. "For servers, it must be at least %d.",
  2591. (int)options->RelayBandwidthRate,
  2592. ROUTER_REQUIRED_MIN_BANDWIDTH);
  2593. return -1;
  2594. }
  2595. }
  2596. if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
  2597. REJECT("RelayBandwidthBurst must be at least equal "
  2598. "to RelayBandwidthRate.");
  2599. if (options->BandwidthRate > options->BandwidthBurst)
  2600. REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
  2601. /* if they set relaybandwidth* really high but left bandwidth*
  2602. * at the default, raise the defaults. */
  2603. if (options->RelayBandwidthRate > options->BandwidthRate)
  2604. options->BandwidthRate = options->RelayBandwidthRate;
  2605. if (options->RelayBandwidthBurst > options->BandwidthBurst)
  2606. options->BandwidthBurst = options->RelayBandwidthBurst;
  2607. if (accounting_parse_options(options, 1)<0)
  2608. REJECT("Failed to parse accounting options. See logs for details.");
  2609. if (options->AccountingMax) {
  2610. if (options->RendConfigLines && server_mode(options)) {
  2611. log_warn(LD_CONFIG, "Using accounting with a hidden service and an "
  2612. "ORPort is risky: your hidden service(s) and your public "
  2613. "address will all turn off at the same time, which may alert "
  2614. "observers that they are being run by the same party.");
  2615. } else if (config_count_key(options->RendConfigLines,
  2616. "HiddenServiceDir") > 1) {
  2617. log_warn(LD_CONFIG, "Using accounting with multiple hidden services is "
  2618. "risky: they will all turn off at the same time, which may "
  2619. "alert observers that they are being run by the same party.");
  2620. }
  2621. }
  2622. if (options->HTTPProxy) { /* parse it now */
  2623. if (tor_addr_port_lookup(options->HTTPProxy,
  2624. &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
  2625. REJECT("HTTPProxy failed to parse or resolve. Please fix.");
  2626. if (options->HTTPProxyPort == 0) { /* give it a default */
  2627. options->HTTPProxyPort = 80;
  2628. }
  2629. }
  2630. if (options->HTTPProxyAuthenticator) {
  2631. if (strlen(options->HTTPProxyAuthenticator) >= 512)
  2632. REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
  2633. }
  2634. if (options->HTTPSProxy) { /* parse it now */
  2635. if (tor_addr_port_lookup(options->HTTPSProxy,
  2636. &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
  2637. REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
  2638. if (options->HTTPSProxyPort == 0) { /* give it a default */
  2639. options->HTTPSProxyPort = 443;
  2640. }
  2641. }
  2642. if (options->HTTPSProxyAuthenticator) {
  2643. if (strlen(options->HTTPSProxyAuthenticator) >= 512)
  2644. REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
  2645. }
  2646. if (options->Socks4Proxy) { /* parse it now */
  2647. if (tor_addr_port_lookup(options->Socks4Proxy,
  2648. &options->Socks4ProxyAddr,
  2649. &options->Socks4ProxyPort) <0)
  2650. REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
  2651. if (options->Socks4ProxyPort == 0) { /* give it a default */
  2652. options->Socks4ProxyPort = 1080;
  2653. }
  2654. }
  2655. if (options->Socks5Proxy) { /* parse it now */
  2656. if (tor_addr_port_lookup(options->Socks5Proxy,
  2657. &options->Socks5ProxyAddr,
  2658. &options->Socks5ProxyPort) <0)
  2659. REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
  2660. if (options->Socks5ProxyPort == 0) { /* give it a default */
  2661. options->Socks5ProxyPort = 1080;
  2662. }
  2663. }
  2664. /* Check if more than one proxy type has been enabled. */
  2665. if (!!options->Socks4Proxy + !!options->Socks5Proxy +
  2666. !!options->HTTPSProxy + !!options->ClientTransportPlugin > 1)
  2667. REJECT("You have configured more than one proxy type. "
  2668. "(Socks4Proxy|Socks5Proxy|HTTPSProxy|ClientTransportPlugin)");
  2669. /* Check if the proxies will give surprising behavior. */
  2670. if (options->HTTPProxy && !(options->Socks4Proxy ||
  2671. options->Socks5Proxy ||
  2672. options->HTTPSProxy)) {
  2673. log_warn(LD_CONFIG, "HTTPProxy configured, but no SOCKS proxy or "
  2674. "HTTPS proxy configured. Watch out: this configuration will "
  2675. "proxy unencrypted directory connections only.");
  2676. }
  2677. if (options->Socks5ProxyUsername) {
  2678. size_t len;
  2679. len = strlen(options->Socks5ProxyUsername);
  2680. if (len < 1 || len > 255)
  2681. REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
  2682. if (!options->Socks5ProxyPassword)
  2683. REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
  2684. len = strlen(options->Socks5ProxyPassword);
  2685. if (len < 1 || len > 255)
  2686. REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
  2687. } else if (options->Socks5ProxyPassword)
  2688. REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
  2689. if (options->HashedControlPassword) {
  2690. smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
  2691. if (!sl) {
  2692. REJECT("Bad HashedControlPassword: wrong length or bad encoding");
  2693. } else {
  2694. SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
  2695. smartlist_free(sl);
  2696. }
  2697. }
  2698. if (options->HashedControlSessionPassword) {
  2699. smartlist_t *sl = decode_hashed_passwords(
  2700. options->HashedControlSessionPassword);
  2701. if (!sl) {
  2702. REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
  2703. } else {
  2704. SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
  2705. smartlist_free(sl);
  2706. }
  2707. }
  2708. if (options->OwningControllerProcess) {
  2709. const char *validate_pspec_msg = NULL;
  2710. if (tor_validate_process_specifier(options->OwningControllerProcess,
  2711. &validate_pspec_msg)) {
  2712. tor_asprintf(msg, "Bad OwningControllerProcess: %s",
  2713. validate_pspec_msg);
  2714. return -1;
  2715. }
  2716. }
  2717. if (options->ControlPort_set && !options->HashedControlPassword &&
  2718. !options->HashedControlSessionPassword &&
  2719. !options->CookieAuthentication) {
  2720. log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
  2721. "has been configured. This means that any program on your "
  2722. "computer can reconfigure your Tor. That's bad! You should "
  2723. "upgrade your Tor controller as soon as possible.");
  2724. }
  2725. if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
  2726. log_warn(LD_CONFIG, "CookieAuthFileGroupReadable is set, but will have "
  2727. "no effect: you must specify an explicit CookieAuthFile to "
  2728. "have it group-readable.");
  2729. }
  2730. if (options->UseEntryGuards && ! options->NumEntryGuards)
  2731. REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
  2732. if (options->MyFamily && options->BridgeRelay) {
  2733. log_warn(LD_CONFIG, "Listing a family for a bridge relay is not "
  2734. "supported: it can reveal bridge fingerprints to censors. "
  2735. "You should also make sure you aren't listing this bridge's "
  2736. "fingerprint in any other MyFamily.");
  2737. }
  2738. if (check_nickname_list(options->MyFamily, "MyFamily", msg))
  2739. return -1;
  2740. for (cl = options->NodeFamilies; cl; cl = cl->next) {
  2741. routerset_t *rs = routerset_new();
  2742. if (routerset_parse(rs, cl->value, cl->key)) {
  2743. routerset_free(rs);
  2744. return -1;
  2745. }
  2746. routerset_free(rs);
  2747. }
  2748. if (validate_addr_policies(options, msg) < 0)
  2749. return -1;
  2750. if (validate_dir_servers(options, old_options) < 0)
  2751. REJECT("Directory authority/fallback line did not parse. See logs "
  2752. "for details.");
  2753. if (options->UseBridges && !options->Bridges)
  2754. REJECT("If you set UseBridges, you must specify at least one bridge.");
  2755. if (options->UseBridges && !options->TunnelDirConns)
  2756. REJECT("If you set UseBridges, you must set TunnelDirConns.");
  2757. for (cl = options->Bridges; cl; cl = cl->next) {
  2758. if (parse_bridge_line(cl->value, 1)<0)
  2759. REJECT("Bridge line did not parse. See logs for details.");
  2760. }
  2761. for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
  2762. if (parse_client_transport_line(cl->value, 1)<0)
  2763. REJECT("Transport line did not parse. See logs for details.");
  2764. }
  2765. for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
  2766. if (parse_server_transport_line(cl->value, 1)<0)
  2767. REJECT("Server transport line did not parse. See logs for details.");
  2768. }
  2769. if (options->ServerTransportPlugin && !server_mode(options)) {
  2770. log_notice(LD_GENERAL, "Tor is not configured as a relay but you specified"
  2771. " a ServerTransportPlugin line (%s). The ServerTransportPlugin "
  2772. "line will be ignored.",
  2773. escaped(options->ServerTransportPlugin->value));
  2774. }
  2775. for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
  2776. /** If get_bindaddr_from_transport_listen_line() fails with
  2777. 'transport' being NULL, it means that something went wrong
  2778. while parsing the ServerTransportListenAddr line. */
  2779. char *bindaddr = get_bindaddr_from_transport_listen_line(cl->value, NULL);
  2780. if (!bindaddr)
  2781. REJECT("ServerTransportListenAddr did not parse. See logs for details.");
  2782. tor_free(bindaddr);
  2783. }
  2784. if (options->ServerTransportListenAddr && !options->ServerTransportPlugin) {
  2785. log_notice(LD_GENERAL, "You need at least a single managed-proxy to "
  2786. "specify a transport listen address. The "
  2787. "ServerTransportListenAddr line will be ignored.");
  2788. }
  2789. if (options->ConstrainedSockets) {
  2790. /* If the user wants to constrain socket buffer use, make sure the desired
  2791. * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
  2792. if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
  2793. options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
  2794. options->ConstrainedSockSize % 1024) {
  2795. tor_asprintf(msg,
  2796. "ConstrainedSockSize is invalid. Must be a value between %d and %d "
  2797. "in 1024 byte increments.",
  2798. MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
  2799. return -1;
  2800. }
  2801. if (options->DirPort_set) {
  2802. /* Providing cached directory entries while system TCP buffers are scarce
  2803. * will exacerbate the socket errors. Suggest that this be disabled. */
  2804. COMPLAIN("You have requested constrained socket buffers while also "
  2805. "serving directory entries via DirPort. It is strongly "
  2806. "suggested that you disable serving directory requests when "
  2807. "system TCP buffer resources are scarce.");
  2808. }
  2809. }
  2810. if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
  2811. options->V3AuthVotingInterval/2) {
  2812. REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
  2813. "V3AuthVotingInterval");
  2814. }
  2815. if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
  2816. REJECT("V3AuthVoteDelay is way too low.");
  2817. if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
  2818. REJECT("V3AuthDistDelay is way too low.");
  2819. if (options->V3AuthNIntervalsValid < 2)
  2820. REJECT("V3AuthNIntervalsValid must be at least 2.");
  2821. if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
  2822. REJECT("V3AuthVotingInterval is insanely low.");
  2823. } else if (options->V3AuthVotingInterval > 24*60*60) {
  2824. REJECT("V3AuthVotingInterval is insanely high.");
  2825. } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
  2826. COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
  2827. }
  2828. if (rend_config_services(options, 1) < 0)
  2829. REJECT("Failed to configure rendezvous options. See logs for details.");
  2830. /* Parse client-side authorization for hidden services. */
  2831. if (rend_parse_service_authorization(options, 1) < 0)
  2832. REJECT("Failed to configure client authorization for hidden services. "
  2833. "See logs for details.");
  2834. if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv4,
  2835. AF_INET, 1, msg)<0)
  2836. return -1;
  2837. if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv6,
  2838. AF_INET6, 1, msg)<0)
  2839. return -1;
  2840. if (options->PreferTunneledDirConns && !options->TunnelDirConns)
  2841. REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
  2842. if ((options->Socks4Proxy || options->Socks5Proxy) &&
  2843. !options->HTTPProxy && !options->PreferTunneledDirConns)
  2844. REJECT("When Socks4Proxy or Socks5Proxy is configured, "
  2845. "PreferTunneledDirConns and TunnelDirConns must both be "
  2846. "set to 1, or HTTPProxy must be configured.");
  2847. if (options->AutomapHostsSuffixes) {
  2848. SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
  2849. {
  2850. size_t len = strlen(suf);
  2851. if (len && suf[len-1] == '.')
  2852. suf[len-1] = '\0';
  2853. });
  2854. }
  2855. if (options->TestingTorNetwork &&
  2856. !(options->DirAuthorities ||
  2857. (options->AlternateDirAuthority &&
  2858. options->AlternateBridgeAuthority))) {
  2859. REJECT("TestingTorNetwork may only be configured in combination with "
  2860. "a non-default set of DirServer or both of AlternateDirAuthority "
  2861. "and AlternateBridgeAuthority configured.");
  2862. }
  2863. if (options->AllowSingleHopExits && !options->DirAuthorities) {
  2864. COMPLAIN("You have set AllowSingleHopExits; now your relay will allow "
  2865. "others to make one-hop exits. However, since by default most "
  2866. "clients avoid relays that set this option, most clients will "
  2867. "ignore you.");
  2868. }
  2869. /*XXXX checking for defaults manually like this is a bit fragile.*/
  2870. /* Keep changes to hard-coded values synchronous to man page and default
  2871. * values table. */
  2872. if (options->TestingV3AuthInitialVotingInterval != 30*60 &&
  2873. !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
  2874. REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
  2875. "Tor networks!");
  2876. } else if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
  2877. REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
  2878. } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
  2879. REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
  2880. "30 minutes.");
  2881. }
  2882. if (options->TestingV3AuthInitialVoteDelay != 5*60 &&
  2883. !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
  2884. REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
  2885. "Tor networks!");
  2886. } else if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
  2887. REJECT("TestingV3AuthInitialVoteDelay is way too low.");
  2888. }
  2889. if (options->TestingV3AuthInitialDistDelay != 5*60 &&
  2890. !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
  2891. REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
  2892. "Tor networks!");
  2893. } else if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
  2894. REJECT("TestingV3AuthInitialDistDelay is way too low.");
  2895. }
  2896. if (options->TestingV3AuthInitialVoteDelay +
  2897. options->TestingV3AuthInitialDistDelay >=
  2898. options->TestingV3AuthInitialVotingInterval/2) {
  2899. REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
  2900. "must be less than half TestingV3AuthInitialVotingInterval");
  2901. }
  2902. if (options->TestingAuthDirTimeToLearnReachability != 30*60 &&
  2903. !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
  2904. REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
  2905. "testing Tor networks!");
  2906. } else if (options->TestingAuthDirTimeToLearnReachability < 0) {
  2907. REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
  2908. } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
  2909. COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
  2910. }
  2911. if (options->TestingEstimatedDescriptorPropagationTime != 10*60 &&
  2912. !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
  2913. REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
  2914. "testing Tor networks!");
  2915. } else if (options->TestingEstimatedDescriptorPropagationTime < 0) {
  2916. REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
  2917. } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
  2918. COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
  2919. }
  2920. if (options->TestingTorNetwork) {
  2921. log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
  2922. "almost unusable in the public Tor network, and is "
  2923. "therefore only advised if you are building a "
  2924. "testing Tor network!");
  2925. }
  2926. if (options->AccelName && !options->HardwareAccel)
  2927. options->HardwareAccel = 1;
  2928. if (options->AccelDir && !options->AccelName)
  2929. REJECT("Can't use hardware crypto accelerator dir without engine name.");
  2930. if (options->PublishServerDescriptor)
  2931. SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
  2932. if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
  2933. if (smartlist_len(options->PublishServerDescriptor) > 1) {
  2934. COMPLAIN("You have passed a list of multiple arguments to the "
  2935. "PublishServerDescriptor option that includes 0 or 1. "
  2936. "0 or 1 should only be used as the sole argument. "
  2937. "This configuration will be rejected in a future release.");
  2938. break;
  2939. }
  2940. });
  2941. if (options->BridgeRelay == 1 && ! options->ORPort_set)
  2942. REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
  2943. "combination.");
  2944. return 0;
  2945. #undef REJECT
  2946. #undef COMPLAIN
  2947. }
  2948. /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
  2949. * equal strings. */
  2950. static int
  2951. opt_streq(const char *s1, const char *s2)
  2952. {
  2953. return 0 == strcmp_opt(s1, s2);
  2954. }
  2955. /** Check if any of the previous options have changed but aren't allowed to. */
  2956. static int
  2957. options_transition_allowed(const or_options_t *old,
  2958. const or_options_t *new_val,
  2959. char **msg)
  2960. {
  2961. if (!old)
  2962. return 0;
  2963. if (!opt_streq(old->PidFile, new_val->PidFile)) {
  2964. *msg = tor_strdup("PidFile is not allowed to change.");
  2965. return -1;
  2966. }
  2967. if (old->RunAsDaemon != new_val->RunAsDaemon) {
  2968. *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
  2969. "is not allowed.");
  2970. return -1;
  2971. }
  2972. if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
  2973. tor_asprintf(msg,
  2974. "While Tor is running, changing DataDirectory "
  2975. "(\"%s\"->\"%s\") is not allowed.",
  2976. old->DataDirectory, new_val->DataDirectory);
  2977. return -1;
  2978. }
  2979. if (!opt_streq(old->User, new_val->User)) {
  2980. *msg = tor_strdup("While Tor is running, changing User is not allowed.");
  2981. return -1;
  2982. }
  2983. if ((old->HardwareAccel != new_val->HardwareAccel)
  2984. || !opt_streq(old->AccelName, new_val->AccelName)
  2985. || !opt_streq(old->AccelDir, new_val->AccelDir)) {
  2986. *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
  2987. "acceleration engine is not allowed.");
  2988. return -1;
  2989. }
  2990. if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
  2991. *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
  2992. "is not allowed.");
  2993. return -1;
  2994. }
  2995. if (old->DisableAllSwap != new_val->DisableAllSwap) {
  2996. *msg = tor_strdup("While Tor is running, changing DisableAllSwap "
  2997. "is not allowed.");
  2998. return -1;
  2999. }
  3000. if (old->TokenBucketRefillInterval != new_val->TokenBucketRefillInterval) {
  3001. *msg = tor_strdup("While Tor is running, changing TokenBucketRefill"
  3002. "Interval is not allowed");
  3003. return -1;
  3004. }
  3005. if (old->DisableIOCP != new_val->DisableIOCP) {
  3006. *msg = tor_strdup("While Tor is running, changing DisableIOCP "
  3007. "is not allowed.");
  3008. return -1;
  3009. }
  3010. if (old->DisableDebuggerAttachment &&
  3011. !new_val->DisableDebuggerAttachment) {
  3012. *msg = tor_strdup("While Tor is running, disabling "
  3013. "DisableDebuggerAttachment is not allowed.");
  3014. return -1;
  3015. }
  3016. return 0;
  3017. }
  3018. /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
  3019. * will require us to rotate the CPU and DNS workers; else return 0. */
  3020. static int
  3021. options_transition_affects_workers(const or_options_t *old_options,
  3022. const or_options_t *new_options)
  3023. {
  3024. if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
  3025. old_options->NumCPUs != new_options->NumCPUs ||
  3026. !config_lines_eq(old_options->ORPort_lines, new_options->ORPort_lines) ||
  3027. old_options->ServerDNSSearchDomains !=
  3028. new_options->ServerDNSSearchDomains ||
  3029. old_options->SafeLogging_ != new_options->SafeLogging_ ||
  3030. old_options->ClientOnly != new_options->ClientOnly ||
  3031. public_server_mode(old_options) != public_server_mode(new_options) ||
  3032. !config_lines_eq(old_options->Logs, new_options->Logs) ||
  3033. old_options->LogMessageDomains != new_options->LogMessageDomains)
  3034. return 1;
  3035. /* Check whether log options match. */
  3036. /* Nothing that changed matters. */
  3037. return 0;
  3038. }
  3039. /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
  3040. * will require us to generate a new descriptor; else return 0. */
  3041. static int
  3042. options_transition_affects_descriptor(const or_options_t *old_options,
  3043. const or_options_t *new_options)
  3044. {
  3045. /* XXX We can be smarter here. If your DirPort isn't being
  3046. * published and you just turned it off, no need to republish. Etc. */
  3047. if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
  3048. !opt_streq(old_options->Nickname,new_options->Nickname) ||
  3049. !opt_streq(old_options->Address,new_options->Address) ||
  3050. !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
  3051. old_options->ExitPolicyRejectPrivate !=
  3052. new_options->ExitPolicyRejectPrivate ||
  3053. old_options->IPv6Exit != new_options->IPv6Exit ||
  3054. !config_lines_eq(old_options->ORPort_lines,
  3055. new_options->ORPort_lines) ||
  3056. !config_lines_eq(old_options->DirPort_lines,
  3057. new_options->DirPort_lines) ||
  3058. old_options->ClientOnly != new_options->ClientOnly ||
  3059. old_options->DisableNetwork != new_options->DisableNetwork ||
  3060. old_options->PublishServerDescriptor_ !=
  3061. new_options->PublishServerDescriptor_ ||
  3062. get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
  3063. get_effective_bwburst(old_options) !=
  3064. get_effective_bwburst(new_options) ||
  3065. !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
  3066. !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
  3067. !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
  3068. old_options->AccountingMax != new_options->AccountingMax ||
  3069. public_server_mode(old_options) != public_server_mode(new_options))
  3070. return 1;
  3071. return 0;
  3072. }
  3073. #ifdef _WIN32
  3074. /** Return the directory on windows where we expect to find our application
  3075. * data. */
  3076. static char *
  3077. get_windows_conf_root(void)
  3078. {
  3079. static int is_set = 0;
  3080. static char path[MAX_PATH*2+1];
  3081. TCHAR tpath[MAX_PATH] = {0};
  3082. LPITEMIDLIST idl;
  3083. IMalloc *m;
  3084. HRESULT result;
  3085. if (is_set)
  3086. return path;
  3087. /* Find X:\documents and settings\username\application data\ .
  3088. * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
  3089. */
  3090. #ifdef ENABLE_LOCAL_APPDATA
  3091. #define APPDATA_PATH CSIDL_LOCAL_APPDATA
  3092. #else
  3093. #define APPDATA_PATH CSIDL_APPDATA
  3094. #endif
  3095. if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
  3096. getcwd(path,MAX_PATH);
  3097. is_set = 1;
  3098. log_warn(LD_CONFIG,
  3099. "I couldn't find your application data folder: are you "
  3100. "running an ancient version of Windows 95? Defaulting to \"%s\"",
  3101. path);
  3102. return path;
  3103. }
  3104. /* Convert the path from an "ID List" (whatever that is!) to a path. */
  3105. result = SHGetPathFromIDList(idl, tpath);
  3106. #ifdef UNICODE
  3107. wcstombs(path,tpath,sizeof(path));
  3108. path[sizeof(path)-1] = '\0';
  3109. #else
  3110. strlcpy(path,tpath,sizeof(path));
  3111. #endif
  3112. /* Now we need to free the memory that the path-idl was stored in. In
  3113. * typical Windows fashion, we can't just call 'free()' on it. */
  3114. SHGetMalloc(&m);
  3115. if (m) {
  3116. m->lpVtbl->Free(m, idl);
  3117. m->lpVtbl->Release(m);
  3118. }
  3119. if (!SUCCEEDED(result)) {
  3120. return NULL;
  3121. }
  3122. strlcat(path,"\\tor",MAX_PATH);
  3123. is_set = 1;
  3124. return path;
  3125. }
  3126. #endif
  3127. /** Return the default location for our torrc file (if <b>defaults_file</b> is
  3128. * false), or for the torrc-defaults file (if <b>defaults_file</b> is true). */
  3129. static const char *
  3130. get_default_conf_file(int defaults_file)
  3131. {
  3132. #ifdef _WIN32
  3133. if (defaults_file) {
  3134. static char defaults_path[MAX_PATH+1];
  3135. tor_snprintf(defaults_path, MAX_PATH, "%s\\torrc-defaults",
  3136. get_windows_conf_root());
  3137. return defaults_path;
  3138. } else {
  3139. static char path[MAX_PATH+1];
  3140. tor_snprintf(path, MAX_PATH, "%s\\torrc",
  3141. get_windows_conf_root());
  3142. return path;
  3143. }
  3144. #else
  3145. return defaults_file ? CONFDIR "/torrc-defaults" : CONFDIR "/torrc";
  3146. #endif
  3147. }
  3148. /** Verify whether lst is a string containing valid-looking comma-separated
  3149. * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
  3150. */
  3151. static int
  3152. check_nickname_list(const char *lst, const char *name, char **msg)
  3153. {
  3154. int r = 0;
  3155. smartlist_t *sl;
  3156. if (!lst)
  3157. return 0;
  3158. sl = smartlist_new();
  3159. smartlist_split_string(sl, lst, ",",
  3160. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
  3161. SMARTLIST_FOREACH(sl, const char *, s,
  3162. {
  3163. if (!is_legal_nickname_or_hexdigest(s)) {
  3164. tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
  3165. r = -1;
  3166. break;
  3167. }
  3168. });
  3169. SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
  3170. smartlist_free(sl);
  3171. return r;
  3172. }
  3173. /** Learn config file name from command line arguments, or use the default.
  3174. *
  3175. * If <b>defaults_file</b> is true, we're looking for torrc-defaults;
  3176. * otherwise, we're looking for the regular torrc_file.
  3177. *
  3178. * Set *<b>using_default_fname</b> to true if we're using the default
  3179. * configuration file name; or false if we've set it from the command line.
  3180. *
  3181. * Set *<b>ignore_missing_torrc</b> to true if we should ignore the resulting
  3182. * filename if it doesn't exist.
  3183. */
  3184. static char *
  3185. find_torrc_filename(int argc, char **argv,
  3186. int defaults_file,
  3187. int *using_default_fname, int *ignore_missing_torrc)
  3188. {
  3189. char *fname=NULL;
  3190. int i;
  3191. const char *fname_opt = defaults_file ? "--defaults-torrc" : "-f";
  3192. const char *ignore_opt = defaults_file ? NULL : "--ignore-missing-torrc";
  3193. if (defaults_file)
  3194. *ignore_missing_torrc = 1;
  3195. for (i = 1; i < argc; ++i) {
  3196. if (i < argc-1 && !strcmp(argv[i],fname_opt)) {
  3197. if (fname) {
  3198. log_warn(LD_CONFIG, "Duplicate %s options on command line.",
  3199. fname_opt);
  3200. tor_free(fname);
  3201. }
  3202. fname = expand_filename(argv[i+1]);
  3203. {
  3204. char *absfname;
  3205. absfname = make_path_absolute(fname);
  3206. tor_free(fname);
  3207. fname = absfname;
  3208. }
  3209. *using_default_fname = 0;
  3210. ++i;
  3211. } else if (ignore_opt && !strcmp(argv[i],ignore_opt)) {
  3212. *ignore_missing_torrc = 1;
  3213. }
  3214. }
  3215. if (*using_default_fname) {
  3216. /* didn't find one, try CONFDIR */
  3217. const char *dflt = get_default_conf_file(defaults_file);
  3218. if (dflt && file_status(dflt) == FN_FILE) {
  3219. fname = tor_strdup(dflt);
  3220. } else {
  3221. #ifndef _WIN32
  3222. char *fn = NULL;
  3223. if (!defaults_file)
  3224. fn = expand_filename("~/.torrc");
  3225. if (fn && file_status(fn) == FN_FILE) {
  3226. fname = fn;
  3227. } else {
  3228. tor_free(fn);
  3229. fname = tor_strdup(dflt);
  3230. }
  3231. #else
  3232. fname = tor_strdup(dflt);
  3233. #endif
  3234. }
  3235. }
  3236. return fname;
  3237. }
  3238. /** Load a configuration file from disk, setting torrc_fname or
  3239. * torrc_defaults_fname if successful.
  3240. *
  3241. * If <b>defaults_file</b> is true, load torrc-defaults; otherwise load torrc.
  3242. *
  3243. * Return the contents of the file on success, and NULL on failure.
  3244. */
  3245. static char *
  3246. load_torrc_from_disk(int argc, char **argv, int defaults_file)
  3247. {
  3248. char *fname=NULL;
  3249. char *cf = NULL;
  3250. int using_default_torrc = 1;
  3251. int ignore_missing_torrc = 0;
  3252. char **fname_var = defaults_file ? &torrc_defaults_fname : &torrc_fname;
  3253. fname = find_torrc_filename(argc, argv, defaults_file,
  3254. &using_default_torrc, &ignore_missing_torrc);
  3255. tor_assert(fname);
  3256. log_debug(LD_CONFIG, "Opening config file \"%s\"", fname);
  3257. tor_free(*fname_var);
  3258. *fname_var = fname;
  3259. /* Open config file */
  3260. if (file_status(fname) != FN_FILE ||
  3261. !(cf = read_file_to_str(fname,0,NULL))) {
  3262. if (using_default_torrc == 1 || ignore_missing_torrc) {
  3263. if (!defaults_file)
  3264. log_notice(LD_CONFIG, "Configuration file \"%s\" not present, "
  3265. "using reasonable defaults.", fname);
  3266. tor_free(fname); /* sets fname to NULL */
  3267. *fname_var = NULL;
  3268. cf = tor_strdup("");
  3269. } else {
  3270. log_warn(LD_CONFIG,
  3271. "Unable to open configuration file \"%s\".", fname);
  3272. goto err;
  3273. }
  3274. } else {
  3275. log_notice(LD_CONFIG, "Read configuration file \"%s\".", fname);
  3276. }
  3277. return cf;
  3278. err:
  3279. tor_free(fname);
  3280. *fname_var = NULL;
  3281. return NULL;
  3282. }
  3283. /** Read a configuration file into <b>options</b>, finding the configuration
  3284. * file location based on the command line. After loading the file
  3285. * call options_init_from_string() to load the config.
  3286. * Return 0 if success, -1 if failure. */
  3287. int
  3288. options_init_from_torrc(int argc, char **argv)
  3289. {
  3290. char *cf=NULL, *cf_defaults=NULL;
  3291. int i, command;
  3292. int retval = -1;
  3293. static char **backup_argv;
  3294. static int backup_argc;
  3295. char *command_arg = NULL;
  3296. char *errmsg=NULL;
  3297. if (argv) { /* first time we're called. save command line args */
  3298. backup_argv = argv;
  3299. backup_argc = argc;
  3300. } else { /* we're reloading. need to clean up old options first. */
  3301. argv = backup_argv;
  3302. argc = backup_argc;
  3303. }
  3304. if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
  3305. print_usage();
  3306. exit(0);
  3307. }
  3308. if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
  3309. /* For documenting validating whether we've documented everything. */
  3310. list_torrc_options();
  3311. exit(0);
  3312. }
  3313. if (argc > 1 && (!strcmp(argv[1],"--version"))) {
  3314. printf("Tor version %s.\n",get_version());
  3315. exit(0);
  3316. }
  3317. if (argc > 1 && (!strcmp(argv[1],"--digests"))) {
  3318. printf("Tor version %s.\n",get_version());
  3319. printf("%s", libor_get_digests());
  3320. printf("%s", tor_get_digests());
  3321. exit(0);
  3322. }
  3323. /* Go through command-line variables */
  3324. if (!global_cmdline_options) {
  3325. /* Or we could redo the list every time we pass this place.
  3326. * It does not really matter */
  3327. if (config_get_commandlines(argc, argv, &global_cmdline_options) < 0) {
  3328. goto err;
  3329. }
  3330. }
  3331. command = CMD_RUN_TOR;
  3332. for (i = 1; i < argc; ++i) {
  3333. if (!strcmp(argv[i],"--list-fingerprint")) {
  3334. command = CMD_LIST_FINGERPRINT;
  3335. } else if (!strcmp(argv[i],"--hash-password")) {
  3336. command = CMD_HASH_PASSWORD;
  3337. command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
  3338. ++i;
  3339. } else if (!strcmp(argv[i],"--verify-config")) {
  3340. command = CMD_VERIFY_CONFIG;
  3341. }
  3342. }
  3343. if (command == CMD_HASH_PASSWORD) {
  3344. cf = tor_strdup("");
  3345. } else {
  3346. cf_defaults = load_torrc_from_disk(argc, argv, 1);
  3347. cf = load_torrc_from_disk(argc, argv, 0);
  3348. if (!cf)
  3349. goto err;
  3350. }
  3351. retval = options_init_from_string(cf_defaults, cf, command, command_arg,
  3352. &errmsg);
  3353. err:
  3354. tor_free(cf);
  3355. tor_free(cf_defaults);
  3356. if (errmsg) {
  3357. log_warn(LD_CONFIG,"%s", errmsg);
  3358. tor_free(errmsg);
  3359. }
  3360. return retval < 0 ? -1 : 0;
  3361. }
  3362. /** Load the options from the configuration in <b>cf</b>, validate
  3363. * them for consistency and take actions based on them.
  3364. *
  3365. * Return 0 if success, negative on error:
  3366. * * -1 for general errors.
  3367. * * -2 for failure to parse/validate,
  3368. * * -3 for transition not allowed
  3369. * * -4 for error while setting the new options
  3370. */
  3371. setopt_err_t
  3372. options_init_from_string(const char *cf_defaults, const char *cf,
  3373. int command, const char *command_arg,
  3374. char **msg)
  3375. {
  3376. or_options_t *oldoptions, *newoptions, *newdefaultoptions=NULL;
  3377. config_line_t *cl;
  3378. int retval, i;
  3379. setopt_err_t err = SETOPT_ERR_MISC;
  3380. tor_assert(msg);
  3381. oldoptions = global_options; /* get_options unfortunately asserts if
  3382. this is the first time we run*/
  3383. newoptions = tor_malloc_zero(sizeof(or_options_t));
  3384. newoptions->magic_ = OR_OPTIONS_MAGIC;
  3385. options_init(newoptions);
  3386. newoptions->command = command;
  3387. newoptions->command_arg = command_arg;
  3388. for (i = 0; i < 2; ++i) {
  3389. const char *body = i==0 ? cf_defaults : cf;
  3390. if (!body)
  3391. continue;
  3392. /* get config lines, assign them */
  3393. retval = config_get_lines(body, &cl, 1);
  3394. if (retval < 0) {
  3395. err = SETOPT_ERR_PARSE;
  3396. goto err;
  3397. }
  3398. retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
  3399. config_free_lines(cl);
  3400. if (retval < 0) {
  3401. err = SETOPT_ERR_PARSE;
  3402. goto err;
  3403. }
  3404. if (i==0)
  3405. newdefaultoptions = config_dup(&options_format, newoptions);
  3406. }
  3407. /* Go through command-line variables too */
  3408. retval = config_assign(&options_format, newoptions,
  3409. global_cmdline_options, 0, 0, msg);
  3410. if (retval < 0) {
  3411. err = SETOPT_ERR_PARSE;
  3412. goto err;
  3413. }
  3414. /* If this is a testing network configuration, change defaults
  3415. * for a list of dependent config options, re-initialize newoptions
  3416. * with the new defaults, and assign all options to it second time. */
  3417. if (newoptions->TestingTorNetwork) {
  3418. /* XXXX this is a bit of a kludge. perhaps there's a better way to do
  3419. * this? We could, for example, make the parsing algorithm do two passes
  3420. * over the configuration. If it finds any "suite" options like
  3421. * TestingTorNetwork, it could change the defaults before its second pass.
  3422. * Not urgent so long as this seems to work, but at any sign of trouble,
  3423. * let's clean it up. -NM */
  3424. /* Change defaults. */
  3425. int i;
  3426. for (i = 0; testing_tor_network_defaults[i].name; ++i) {
  3427. const config_var_t *new_var = &testing_tor_network_defaults[i];
  3428. config_var_t *old_var =
  3429. config_find_option_mutable(&options_format, new_var->name);
  3430. tor_assert(new_var);
  3431. tor_assert(old_var);
  3432. old_var->initvalue = new_var->initvalue;
  3433. }
  3434. /* Clear newoptions and re-initialize them with new defaults. */
  3435. config_free(&options_format, newoptions);
  3436. config_free(&options_format, newdefaultoptions);
  3437. newdefaultoptions = NULL;
  3438. newoptions = tor_malloc_zero(sizeof(or_options_t));
  3439. newoptions->magic_ = OR_OPTIONS_MAGIC;
  3440. options_init(newoptions);
  3441. newoptions->command = command;
  3442. newoptions->command_arg = command_arg;
  3443. /* Assign all options a second time. */
  3444. for (i = 0; i < 2; ++i) {
  3445. const char *body = i==0 ? cf_defaults : cf;
  3446. if (!body)
  3447. continue;
  3448. /* get config lines, assign them */
  3449. retval = config_get_lines(body, &cl, 1);
  3450. if (retval < 0) {
  3451. err = SETOPT_ERR_PARSE;
  3452. goto err;
  3453. }
  3454. retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
  3455. config_free_lines(cl);
  3456. if (retval < 0) {
  3457. err = SETOPT_ERR_PARSE;
  3458. goto err;
  3459. }
  3460. if (i==0)
  3461. newdefaultoptions = config_dup(&options_format, newoptions);
  3462. }
  3463. /* Assign command-line variables a second time too */
  3464. retval = config_assign(&options_format, newoptions,
  3465. global_cmdline_options, 0, 0, msg);
  3466. if (retval < 0) {
  3467. err = SETOPT_ERR_PARSE;
  3468. goto err;
  3469. }
  3470. }
  3471. /* Validate newoptions */
  3472. if (options_validate(oldoptions, newoptions, 0, msg) < 0) {
  3473. err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
  3474. goto err;
  3475. }
  3476. if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
  3477. err = SETOPT_ERR_TRANSITION;
  3478. goto err;
  3479. }
  3480. if (set_options(newoptions, msg)) {
  3481. err = SETOPT_ERR_SETTING;
  3482. goto err; /* frees and replaces old options */
  3483. }
  3484. config_free(&options_format, global_default_options);
  3485. global_default_options = newdefaultoptions;
  3486. return SETOPT_OK;
  3487. err:
  3488. config_free(&options_format, newoptions);
  3489. config_free(&options_format, newdefaultoptions);
  3490. if (*msg) {
  3491. char *old_msg = *msg;
  3492. tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
  3493. tor_free(old_msg);
  3494. }
  3495. return err;
  3496. }
  3497. /** Return the location for our configuration file.
  3498. */
  3499. const char *
  3500. get_torrc_fname(int defaults_fname)
  3501. {
  3502. const char *fname = defaults_fname ? torrc_defaults_fname : torrc_fname;
  3503. if (fname)
  3504. return fname;
  3505. else
  3506. return get_default_conf_file(defaults_fname);
  3507. }
  3508. /** Adjust the address map based on the MapAddress elements in the
  3509. * configuration <b>options</b>
  3510. */
  3511. void
  3512. config_register_addressmaps(const or_options_t *options)
  3513. {
  3514. smartlist_t *elts;
  3515. config_line_t *opt;
  3516. const char *from, *to, *msg;
  3517. addressmap_clear_configured();
  3518. elts = smartlist_new();
  3519. for (opt = options->AddressMap; opt; opt = opt->next) {
  3520. smartlist_split_string(elts, opt->value, NULL,
  3521. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  3522. if (smartlist_len(elts) < 2) {
  3523. log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
  3524. opt->value);
  3525. goto cleanup;
  3526. }
  3527. from = smartlist_get(elts,0);
  3528. to = smartlist_get(elts,1);
  3529. if (to[0] == '.' || from[0] == '.') {
  3530. log_warn(LD_CONFIG,"MapAddress '%s' is ambiguous - address starts with a"
  3531. "'.'. Ignoring.",opt->value);
  3532. goto cleanup;
  3533. }
  3534. if (addressmap_register_auto(from, to, 0, ADDRMAPSRC_TORRC, &msg) < 0) {
  3535. log_warn(LD_CONFIG,"MapAddress '%s' failed: %s. Ignoring.", opt->value,
  3536. msg);
  3537. goto cleanup;
  3538. }
  3539. if (smartlist_len(elts) > 2)
  3540. log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
  3541. cleanup:
  3542. SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
  3543. smartlist_clear(elts);
  3544. }
  3545. smartlist_free(elts);
  3546. }
  3547. /** As addressmap_register(), but detect the wildcarded status of "from" and
  3548. * "to", and do not steal a reference to <b>to</b>. */
  3549. /* XXXX024 move to connection_edge.c */
  3550. int
  3551. addressmap_register_auto(const char *from, const char *to,
  3552. time_t expires,
  3553. addressmap_entry_source_t addrmap_source,
  3554. const char **msg)
  3555. {
  3556. int from_wildcard = 0, to_wildcard = 0;
  3557. *msg = "whoops, forgot the error message";
  3558. if (1) {
  3559. if (!strcmp(to, "*") || !strcmp(from, "*")) {
  3560. *msg = "can't remap from or to *";
  3561. return -1;
  3562. }
  3563. /* Detect asterisks in expressions of type: '*.example.com' */
  3564. if (!strncmp(from,"*.",2)) {
  3565. from += 2;
  3566. from_wildcard = 1;
  3567. }
  3568. if (!strncmp(to,"*.",2)) {
  3569. to += 2;
  3570. to_wildcard = 1;
  3571. }
  3572. if (to_wildcard && !from_wildcard) {
  3573. *msg = "can only use wildcard (i.e. '*.') if 'from' address "
  3574. "uses wildcard also";
  3575. return -1;
  3576. }
  3577. if (address_is_invalid_destination(to, 1)) {
  3578. *msg = "destination is invalid";
  3579. return -1;
  3580. }
  3581. addressmap_register(from, tor_strdup(to), expires, addrmap_source,
  3582. from_wildcard, to_wildcard);
  3583. }
  3584. return 0;
  3585. }
  3586. /**
  3587. * Initialize the logs based on the configuration file.
  3588. */
  3589. static int
  3590. options_init_logs(or_options_t *options, int validate_only)
  3591. {
  3592. config_line_t *opt;
  3593. int ok;
  3594. smartlist_t *elts;
  3595. int daemon =
  3596. #ifdef _WIN32
  3597. 0;
  3598. #else
  3599. options->RunAsDaemon;
  3600. #endif
  3601. if (options->LogTimeGranularity <= 0) {
  3602. log_warn(LD_CONFIG, "Log time granularity '%d' has to be positive.",
  3603. options->LogTimeGranularity);
  3604. return -1;
  3605. } else if (1000 % options->LogTimeGranularity != 0 &&
  3606. options->LogTimeGranularity % 1000 != 0) {
  3607. int granularity = options->LogTimeGranularity;
  3608. if (granularity < 40) {
  3609. do granularity++;
  3610. while (1000 % granularity != 0);
  3611. } else if (granularity < 1000) {
  3612. granularity = 1000 / granularity;
  3613. while (1000 % granularity != 0)
  3614. granularity--;
  3615. granularity = 1000 / granularity;
  3616. } else {
  3617. granularity = 1000 * ((granularity / 1000) + 1);
  3618. }
  3619. log_warn(LD_CONFIG, "Log time granularity '%d' has to be either a "
  3620. "divisor or a multiple of 1 second. Changing to "
  3621. "'%d'.",
  3622. options->LogTimeGranularity, granularity);
  3623. if (!validate_only)
  3624. set_log_time_granularity(granularity);
  3625. } else {
  3626. if (!validate_only)
  3627. set_log_time_granularity(options->LogTimeGranularity);
  3628. }
  3629. ok = 1;
  3630. elts = smartlist_new();
  3631. for (opt = options->Logs; opt; opt = opt->next) {
  3632. log_severity_list_t *severity;
  3633. const char *cfg = opt->value;
  3634. severity = tor_malloc_zero(sizeof(log_severity_list_t));
  3635. if (parse_log_severity_config(&cfg, severity) < 0) {
  3636. log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
  3637. opt->value);
  3638. ok = 0; goto cleanup;
  3639. }
  3640. smartlist_split_string(elts, cfg, NULL,
  3641. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  3642. if (smartlist_len(elts) == 0)
  3643. smartlist_add(elts, tor_strdup("stdout"));
  3644. if (smartlist_len(elts) == 1 &&
  3645. (!strcasecmp(smartlist_get(elts,0), "stdout") ||
  3646. !strcasecmp(smartlist_get(elts,0), "stderr"))) {
  3647. int err = smartlist_len(elts) &&
  3648. !strcasecmp(smartlist_get(elts,0), "stderr");
  3649. if (!validate_only) {
  3650. if (daemon) {
  3651. log_warn(LD_CONFIG,
  3652. "Can't log to %s with RunAsDaemon set; skipping stdout",
  3653. err?"stderr":"stdout");
  3654. } else {
  3655. add_stream_log(severity, err?"<stderr>":"<stdout>",
  3656. fileno(err?stderr:stdout));
  3657. }
  3658. }
  3659. goto cleanup;
  3660. }
  3661. if (smartlist_len(elts) == 1 &&
  3662. !strcasecmp(smartlist_get(elts,0), "syslog")) {
  3663. #ifdef HAVE_SYSLOG_H
  3664. if (!validate_only) {
  3665. add_syslog_log(severity);
  3666. }
  3667. #else
  3668. log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
  3669. #endif
  3670. goto cleanup;
  3671. }
  3672. if (smartlist_len(elts) == 2 &&
  3673. !strcasecmp(smartlist_get(elts,0), "file")) {
  3674. if (!validate_only) {
  3675. char *fname = expand_filename(smartlist_get(elts, 1));
  3676. if (add_file_log(severity, fname) < 0) {
  3677. log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
  3678. opt->value, strerror(errno));
  3679. ok = 0;
  3680. }
  3681. tor_free(fname);
  3682. }
  3683. goto cleanup;
  3684. }
  3685. log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
  3686. opt->value);
  3687. ok = 0; goto cleanup;
  3688. cleanup:
  3689. SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
  3690. smartlist_clear(elts);
  3691. tor_free(severity);
  3692. }
  3693. smartlist_free(elts);
  3694. if (ok && !validate_only)
  3695. logs_set_domain_logging(options->LogMessageDomains);
  3696. return ok?0:-1;
  3697. }
  3698. /** Read the contents of a Bridge line from <b>line</b>. Return 0
  3699. * if the line is well-formed, and -1 if it isn't. If
  3700. * <b>validate_only</b> is 0, and the line is well-formed, then add
  3701. * the bridge described in the line to our internal bridge list. */
  3702. static int
  3703. parse_bridge_line(const char *line, int validate_only)
  3704. {
  3705. smartlist_t *items = NULL;
  3706. int r;
  3707. char *addrport=NULL, *fingerprint=NULL;
  3708. char *transport_name=NULL;
  3709. char *field1=NULL;
  3710. tor_addr_t addr;
  3711. uint16_t port = 0;
  3712. char digest[DIGEST_LEN];
  3713. items = smartlist_new();
  3714. smartlist_split_string(items, line, NULL,
  3715. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  3716. if (smartlist_len(items) < 1) {
  3717. log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
  3718. goto err;
  3719. }
  3720. /* field1 is either a transport name or addrport */
  3721. field1 = smartlist_get(items, 0);
  3722. smartlist_del_keeporder(items, 0);
  3723. if (!(strstr(field1, ".") || strstr(field1, ":"))) {
  3724. /* new-style bridge line */
  3725. transport_name = field1;
  3726. if (smartlist_len(items) < 1) {
  3727. log_warn(LD_CONFIG, "Too few items to Bridge line.");
  3728. goto err;
  3729. }
  3730. addrport = smartlist_get(items, 0);
  3731. smartlist_del_keeporder(items, 0);
  3732. } else {
  3733. addrport = field1;
  3734. }
  3735. if (tor_addr_port_lookup(addrport, &addr, &port)<0) {
  3736. log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
  3737. goto err;
  3738. }
  3739. if (!port) {
  3740. log_info(LD_CONFIG,
  3741. "Bridge address '%s' has no port; using default port 443.",
  3742. addrport);
  3743. port = 443;
  3744. }
  3745. if (smartlist_len(items)) {
  3746. fingerprint = smartlist_join_strings(items, "", 0, NULL);
  3747. if (strlen(fingerprint) != HEX_DIGEST_LEN) {
  3748. log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
  3749. goto err;
  3750. }
  3751. if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
  3752. log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
  3753. goto err;
  3754. }
  3755. }
  3756. if (!validate_only) {
  3757. log_debug(LD_DIR, "Bridge at %s (transport: %s) (%s)",
  3758. fmt_addrport(&addr, port),
  3759. transport_name ? transport_name : "no transport",
  3760. fingerprint ? fingerprint : "no key listed");
  3761. bridge_add_from_config(&addr, port,
  3762. fingerprint ? digest : NULL, transport_name);
  3763. }
  3764. r = 0;
  3765. goto done;
  3766. err:
  3767. r = -1;
  3768. done:
  3769. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  3770. smartlist_free(items);
  3771. tor_free(addrport);
  3772. tor_free(transport_name);
  3773. tor_free(fingerprint);
  3774. return r;
  3775. }
  3776. /** Read the contents of a ClientTransportPlugin line from
  3777. * <b>line</b>. Return 0 if the line is well-formed, and -1 if it
  3778. * isn't.
  3779. *
  3780. * If <b>validate_only</b> is 0, and the line is well-formed:
  3781. * - If it's an external proxy line, add the transport described in the line to
  3782. * our internal transport list.
  3783. * - If it's a managed proxy line, launch the managed proxy. */
  3784. static int
  3785. parse_client_transport_line(const char *line, int validate_only)
  3786. {
  3787. smartlist_t *items = NULL;
  3788. int r;
  3789. char *field2=NULL;
  3790. const char *transports=NULL;
  3791. smartlist_t *transport_list=NULL;
  3792. char *addrport=NULL;
  3793. tor_addr_t addr;
  3794. uint16_t port = 0;
  3795. int socks_ver=PROXY_NONE;
  3796. /* managed proxy options */
  3797. int is_managed=0;
  3798. char **proxy_argv=NULL;
  3799. char **tmp=NULL;
  3800. int proxy_argc,i;
  3801. int line_length;
  3802. items = smartlist_new();
  3803. smartlist_split_string(items, line, NULL,
  3804. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  3805. line_length = smartlist_len(items);
  3806. if (line_length < 3) {
  3807. log_warn(LD_CONFIG, "Too few arguments on ClientTransportPlugin line.");
  3808. goto err;
  3809. }
  3810. /* Get the first line element, split it to commas into
  3811. transport_list (in case it's multiple transports) and validate
  3812. the transport names. */
  3813. transports = smartlist_get(items, 0);
  3814. transport_list = smartlist_new();
  3815. smartlist_split_string(transport_list, transports, ",",
  3816. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3817. SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
  3818. if (!string_is_C_identifier(transport_name)) {
  3819. log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
  3820. transport_name);
  3821. goto err;
  3822. }
  3823. } SMARTLIST_FOREACH_END(transport_name);
  3824. /* field2 is either a SOCKS version or "exec" */
  3825. field2 = smartlist_get(items, 1);
  3826. if (!strcmp(field2,"socks4")) {
  3827. socks_ver = PROXY_SOCKS4;
  3828. } else if (!strcmp(field2,"socks5")) {
  3829. socks_ver = PROXY_SOCKS5;
  3830. } else if (!strcmp(field2,"exec")) {
  3831. is_managed=1;
  3832. } else {
  3833. log_warn(LD_CONFIG, "Strange ClientTransportPlugin field '%s'.",
  3834. field2);
  3835. goto err;
  3836. }
  3837. if (is_managed) { /* managed */
  3838. if (!validate_only) { /* if we are not just validating, use the
  3839. rest of the line as the argv of the proxy
  3840. to be launched */
  3841. proxy_argc = line_length-2;
  3842. tor_assert(proxy_argc > 0);
  3843. proxy_argv = tor_malloc_zero(sizeof(char*)*(proxy_argc+1));
  3844. tmp = proxy_argv;
  3845. for (i=0;i<proxy_argc;i++) { /* store arguments */
  3846. *tmp++ = smartlist_get(items, 2);
  3847. smartlist_del_keeporder(items, 2);
  3848. }
  3849. *tmp = NULL; /*terminated with NULL, just like execve() likes it*/
  3850. /* kickstart the thing */
  3851. pt_kickstart_client_proxy(transport_list, proxy_argv);
  3852. }
  3853. } else { /* external */
  3854. if (smartlist_len(transport_list) != 1) {
  3855. log_warn(LD_CONFIG, "You can't have an external proxy with "
  3856. "more than one transports.");
  3857. goto err;
  3858. }
  3859. addrport = smartlist_get(items, 2);
  3860. if (tor_addr_port_lookup(addrport, &addr, &port)<0) {
  3861. log_warn(LD_CONFIG, "Error parsing transport "
  3862. "address '%s'", addrport);
  3863. goto err;
  3864. }
  3865. if (!port) {
  3866. log_warn(LD_CONFIG,
  3867. "Transport address '%s' has no port.", addrport);
  3868. goto err;
  3869. }
  3870. if (!validate_only) {
  3871. transport_add_from_config(&addr, port, smartlist_get(transport_list, 0),
  3872. socks_ver);
  3873. log_info(LD_DIR, "Transport '%s' found at %s",
  3874. transports, fmt_addrport(&addr, port));
  3875. }
  3876. }
  3877. r = 0;
  3878. goto done;
  3879. err:
  3880. r = -1;
  3881. done:
  3882. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  3883. smartlist_free(items);
  3884. if (transport_list) {
  3885. SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
  3886. smartlist_free(transport_list);
  3887. }
  3888. return r;
  3889. }
  3890. /** Given a ServerTransportListenAddr <b>line</b>, return its
  3891. * <address:port> string. Return NULL if the line was not
  3892. * well-formed.
  3893. *
  3894. * If <b>transport</b> is set, return NULL if the line is not
  3895. * referring to <b>transport</b>.
  3896. *
  3897. * The returned string is allocated on the heap and it's the
  3898. * responsibility of the caller to free it. */
  3899. static char *
  3900. get_bindaddr_from_transport_listen_line(const char *line,const char *transport)
  3901. {
  3902. smartlist_t *items = NULL;
  3903. const char *parsed_transport = NULL;
  3904. char *addrport = NULL;
  3905. tor_addr_t addr;
  3906. uint16_t port = 0;
  3907. items = smartlist_new();
  3908. smartlist_split_string(items, line, NULL,
  3909. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  3910. if (smartlist_len(items) < 2) {
  3911. log_warn(LD_CONFIG,"Too few arguments on ServerTransportListenAddr line.");
  3912. goto err;
  3913. }
  3914. parsed_transport = smartlist_get(items, 0);
  3915. addrport = tor_strdup(smartlist_get(items, 1));
  3916. /* If 'transport' is given, check if it matches the one on the line */
  3917. if (transport && strcmp(transport, parsed_transport))
  3918. goto err;
  3919. /* Validate addrport */
  3920. if (tor_addr_port_parse(LOG_WARN, addrport, &addr, &port)<0) {
  3921. log_warn(LD_CONFIG, "Error parsing ServerTransportListenAddr "
  3922. "address '%s'", addrport);
  3923. goto err;
  3924. }
  3925. goto done;
  3926. err:
  3927. tor_free(addrport);
  3928. addrport = NULL;
  3929. done:
  3930. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  3931. smartlist_free(items);
  3932. return addrport;
  3933. }
  3934. /** Given the name of a pluggable transport in <b>transport</b>, check
  3935. * the configuration file to see if the user has explicitly asked for
  3936. * it to listen on a specific port. Return a <address:port> string if
  3937. * so, otherwise NULL. */
  3938. char *
  3939. get_transport_bindaddr_from_config(const char *transport)
  3940. {
  3941. config_line_t *cl;
  3942. const or_options_t *options = get_options();
  3943. for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
  3944. char *bindaddr =
  3945. get_bindaddr_from_transport_listen_line(cl->value, transport);
  3946. if (bindaddr)
  3947. return bindaddr;
  3948. }
  3949. return NULL;
  3950. }
  3951. /** Read the contents of a ServerTransportPlugin line from
  3952. * <b>line</b>. Return 0 if the line is well-formed, and -1 if it
  3953. * isn't.
  3954. * If <b>validate_only</b> is 0, the line is well-formed, and it's a
  3955. * managed proxy line, launch the managed proxy. */
  3956. static int
  3957. parse_server_transport_line(const char *line, int validate_only)
  3958. {
  3959. smartlist_t *items = NULL;
  3960. int r;
  3961. const char *transports=NULL;
  3962. smartlist_t *transport_list=NULL;
  3963. char *type=NULL;
  3964. char *addrport=NULL;
  3965. tor_addr_t addr;
  3966. uint16_t port = 0;
  3967. /* managed proxy options */
  3968. int is_managed=0;
  3969. char **proxy_argv=NULL;
  3970. char **tmp=NULL;
  3971. int proxy_argc,i;
  3972. int line_length;
  3973. items = smartlist_new();
  3974. smartlist_split_string(items, line, NULL,
  3975. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  3976. line_length = smartlist_len(items);
  3977. if (line_length < 3) {
  3978. log_warn(LD_CONFIG, "Too few arguments on ServerTransportPlugin line.");
  3979. goto err;
  3980. }
  3981. /* Get the first line element, split it to commas into
  3982. transport_list (in case it's multiple transports) and validate
  3983. the transport names. */
  3984. transports = smartlist_get(items, 0);
  3985. transport_list = smartlist_new();
  3986. smartlist_split_string(transport_list, transports, ",",
  3987. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3988. SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
  3989. if (!string_is_C_identifier(transport_name)) {
  3990. log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
  3991. transport_name);
  3992. goto err;
  3993. }
  3994. } SMARTLIST_FOREACH_END(transport_name);
  3995. type = smartlist_get(items, 1);
  3996. if (!strcmp(type, "exec")) {
  3997. is_managed=1;
  3998. } else if (!strcmp(type, "proxy")) {
  3999. is_managed=0;
  4000. } else {
  4001. log_warn(LD_CONFIG, "Strange ServerTransportPlugin type '%s'", type);
  4002. goto err;
  4003. }
  4004. if (is_managed) { /* managed */
  4005. if (!validate_only) {
  4006. proxy_argc = line_length-2;
  4007. tor_assert(proxy_argc > 0);
  4008. proxy_argv = tor_malloc_zero(sizeof(char*)*(proxy_argc+1));
  4009. tmp = proxy_argv;
  4010. for (i=0;i<proxy_argc;i++) { /* store arguments */
  4011. *tmp++ = smartlist_get(items, 2);
  4012. smartlist_del_keeporder(items, 2);
  4013. }
  4014. *tmp = NULL; /*terminated with NULL, just like execve() likes it*/
  4015. /* kickstart the thing */
  4016. pt_kickstart_server_proxy(transport_list, proxy_argv);
  4017. }
  4018. } else { /* external */
  4019. if (smartlist_len(transport_list) != 1) {
  4020. log_warn(LD_CONFIG, "You can't have an external proxy with "
  4021. "more than one transports.");
  4022. goto err;
  4023. }
  4024. addrport = smartlist_get(items, 2);
  4025. if (tor_addr_port_lookup(addrport, &addr, &port)<0) {
  4026. log_warn(LD_CONFIG, "Error parsing transport "
  4027. "address '%s'", addrport);
  4028. goto err;
  4029. }
  4030. if (!port) {
  4031. log_warn(LD_CONFIG,
  4032. "Transport address '%s' has no port.", addrport);
  4033. goto err;
  4034. }
  4035. if (!validate_only) {
  4036. log_info(LD_DIR, "Server transport '%s' at %s.",
  4037. transports, fmt_addrport(&addr, port));
  4038. }
  4039. }
  4040. r = 0;
  4041. goto done;
  4042. err:
  4043. r = -1;
  4044. done:
  4045. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  4046. smartlist_free(items);
  4047. if (transport_list) {
  4048. SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
  4049. smartlist_free(transport_list);
  4050. }
  4051. return r;
  4052. }
  4053. /** Read the contents of a DirAuthority line from <b>line</b>. If
  4054. * <b>validate_only</b> is 0, and the line is well-formed, and it
  4055. * shares any bits with <b>required_type</b> or <b>required_type</b>
  4056. * is 0, then add the dirserver described in the line (minus whatever
  4057. * bits it's missing) as a valid authority. Return 0 on success,
  4058. * or -1 if the line isn't well-formed or if we can't add it. */
  4059. static int
  4060. parse_dir_authority_line(const char *line, dirinfo_type_t required_type,
  4061. int validate_only)
  4062. {
  4063. smartlist_t *items = NULL;
  4064. int r;
  4065. char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
  4066. uint16_t dir_port = 0, or_port = 0;
  4067. char digest[DIGEST_LEN];
  4068. char v3_digest[DIGEST_LEN];
  4069. dirinfo_type_t type = V2_DIRINFO;
  4070. int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
  4071. double weight = 1.0;
  4072. items = smartlist_new();
  4073. smartlist_split_string(items, line, NULL,
  4074. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  4075. if (smartlist_len(items) < 1) {
  4076. log_warn(LD_CONFIG, "No arguments on DirServer line.");
  4077. goto err;
  4078. }
  4079. if (is_legal_nickname(smartlist_get(items, 0))) {
  4080. nickname = smartlist_get(items, 0);
  4081. smartlist_del_keeporder(items, 0);
  4082. }
  4083. while (smartlist_len(items)) {
  4084. char *flag = smartlist_get(items, 0);
  4085. if (TOR_ISDIGIT(flag[0]))
  4086. break;
  4087. if (!strcasecmp(flag, "v1")) {
  4088. type |= (V1_DIRINFO | HIDSERV_DIRINFO);
  4089. } else if (!strcasecmp(flag, "hs")) {
  4090. type |= HIDSERV_DIRINFO;
  4091. } else if (!strcasecmp(flag, "no-hs")) {
  4092. is_not_hidserv_authority = 1;
  4093. } else if (!strcasecmp(flag, "bridge")) {
  4094. type |= BRIDGE_DIRINFO;
  4095. } else if (!strcasecmp(flag, "no-v2")) {
  4096. is_not_v2_authority = 1;
  4097. } else if (!strcasecmpstart(flag, "orport=")) {
  4098. int ok;
  4099. char *portstring = flag + strlen("orport=");
  4100. or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
  4101. if (!ok)
  4102. log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
  4103. portstring);
  4104. } else if (!strcmpstart(flag, "weight=")) {
  4105. int ok;
  4106. const char *wstring = flag + strlen("weight=");
  4107. weight = tor_parse_double(wstring, 0, UINT64_MAX, &ok, NULL);
  4108. if (!ok) {
  4109. log_warn(LD_CONFIG, "Invalid weight '%s' on DirAuthority line.",flag);
  4110. weight=1.0;
  4111. }
  4112. } else if (!strcasecmpstart(flag, "v3ident=")) {
  4113. char *idstr = flag + strlen("v3ident=");
  4114. if (strlen(idstr) != HEX_DIGEST_LEN ||
  4115. base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
  4116. log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
  4117. flag);
  4118. } else {
  4119. type |= V3_DIRINFO|EXTRAINFO_DIRINFO|MICRODESC_DIRINFO;
  4120. }
  4121. } else {
  4122. log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
  4123. flag);
  4124. }
  4125. tor_free(flag);
  4126. smartlist_del_keeporder(items, 0);
  4127. }
  4128. if (is_not_hidserv_authority)
  4129. type &= ~HIDSERV_DIRINFO;
  4130. if (is_not_v2_authority)
  4131. type &= ~V2_DIRINFO;
  4132. if (smartlist_len(items) < 2) {
  4133. log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
  4134. goto err;
  4135. }
  4136. addrport = smartlist_get(items, 0);
  4137. smartlist_del_keeporder(items, 0);
  4138. if (addr_port_lookup(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
  4139. log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
  4140. goto err;
  4141. }
  4142. if (!dir_port) {
  4143. log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
  4144. goto err;
  4145. }
  4146. fingerprint = smartlist_join_strings(items, "", 0, NULL);
  4147. if (strlen(fingerprint) != HEX_DIGEST_LEN) {
  4148. log_warn(LD_CONFIG, "Key digest '%s' for DirServer is wrong length %d.",
  4149. fingerprint, (int)strlen(fingerprint));
  4150. goto err;
  4151. }
  4152. if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
  4153. /* a known bad fingerprint. refuse to use it. We can remove this
  4154. * clause once Tor 0.1.2.17 is obsolete. */
  4155. log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
  4156. "torrc file (%s), or reinstall Tor and use the default torrc.",
  4157. get_torrc_fname(0));
  4158. goto err;
  4159. }
  4160. if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
  4161. log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
  4162. goto err;
  4163. }
  4164. if (!validate_only && (!required_type || required_type & type)) {
  4165. dir_server_t *ds;
  4166. if (required_type)
  4167. type &= required_type; /* pare down what we think of them as an
  4168. * authority for. */
  4169. log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
  4170. address, (int)dir_port, (char*)smartlist_get(items,0));
  4171. if (!(ds = trusted_dir_server_new(nickname, address, dir_port, or_port,
  4172. digest, v3_digest, type, weight)))
  4173. goto err;
  4174. dir_server_add(ds);
  4175. }
  4176. r = 0;
  4177. goto done;
  4178. err:
  4179. r = -1;
  4180. done:
  4181. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  4182. smartlist_free(items);
  4183. tor_free(addrport);
  4184. tor_free(address);
  4185. tor_free(nickname);
  4186. tor_free(fingerprint);
  4187. return r;
  4188. }
  4189. /** Read the contents of a FallbackDir line from <b>line</b>. If
  4190. * <b>validate_only</b> is 0, and the line is well-formed, then add the
  4191. * dirserver described in the line as a fallback directory. Return 0 on
  4192. * success, or -1 if the line isn't well-formed or if we can't add it. */
  4193. static int
  4194. parse_dir_fallback_line(const char *line,
  4195. int validate_only)
  4196. {
  4197. int r = -1;
  4198. smartlist_t *items = smartlist_new(), *positional = smartlist_new();
  4199. int orport = -1;
  4200. uint16_t dirport;
  4201. tor_addr_t addr;
  4202. int ok;
  4203. char id[DIGEST_LEN];
  4204. char *address=NULL;
  4205. double weight=1.0;
  4206. memset(id, 0, sizeof(id));
  4207. smartlist_split_string(items, line, NULL,
  4208. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  4209. SMARTLIST_FOREACH_BEGIN(items, const char *, cp) {
  4210. const char *eq = strchr(cp, '=');
  4211. ok = 1;
  4212. if (! eq) {
  4213. smartlist_add(positional, (char*)cp);
  4214. continue;
  4215. }
  4216. if (!strcmpstart(cp, "orport=")) {
  4217. orport = (int)tor_parse_long(cp+strlen("orport="), 10,
  4218. 1, 65535, &ok, NULL);
  4219. } else if (!strcmpstart(cp, "id=")) {
  4220. ok = !base16_decode(id, DIGEST_LEN,
  4221. cp+strlen("id="), strlen(cp)-strlen("id="));
  4222. } else if (!strcmpstart(cp, "weight=")) {
  4223. int ok;
  4224. const char *wstring = cp + strlen("weight=");
  4225. weight = tor_parse_double(wstring, 0, UINT64_MAX, &ok, NULL);
  4226. if (!ok) {
  4227. log_warn(LD_CONFIG, "Invalid weight '%s' on FallbackDir line.", cp);
  4228. weight=1.0;
  4229. }
  4230. }
  4231. if (!ok) {
  4232. log_warn(LD_CONFIG, "Bad FallbackDir option %s", escaped(cp));
  4233. goto end;
  4234. }
  4235. } SMARTLIST_FOREACH_END(cp);
  4236. if (smartlist_len(positional) != 1) {
  4237. log_warn(LD_CONFIG, "Couldn't parse FallbackDir line %s", escaped(line));
  4238. goto end;
  4239. }
  4240. if (tor_digest_is_zero(id)) {
  4241. log_warn(LD_CONFIG, "Missing identity on FallbackDir line");
  4242. goto end;
  4243. }
  4244. if (orport <= 0) {
  4245. log_warn(LD_CONFIG, "Missing orport on FallbackDir line");
  4246. goto end;
  4247. }
  4248. if (tor_addr_port_split(LOG_INFO, smartlist_get(positional, 0),
  4249. &address, &dirport) < 0 ||
  4250. tor_addr_parse(&addr, address)<0) {
  4251. log_warn(LD_CONFIG, "Couldn't parse address:port %s on FallbackDir line",
  4252. (const char*)smartlist_get(positional, 0));
  4253. goto end;
  4254. }
  4255. if (!validate_only) {
  4256. dir_server_t *ds;
  4257. ds = fallback_dir_server_new(&addr, dirport, orport, id, weight);
  4258. if (!ds) {
  4259. log_warn(LD_CONFIG, "Couldn't create FallbackDir %s", escaped(line));
  4260. goto end;
  4261. }
  4262. dir_server_add(ds);
  4263. }
  4264. r = 0;
  4265. end:
  4266. SMARTLIST_FOREACH(items, char *, cp, tor_free(cp));
  4267. smartlist_free(items);
  4268. smartlist_free(positional);
  4269. tor_free(address);
  4270. return r;
  4271. }
  4272. /** Allocate and return a new port_cfg_t with reasonable defaults. */
  4273. static port_cfg_t *
  4274. port_cfg_new(void)
  4275. {
  4276. port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t));
  4277. cfg->ipv4_traffic = 1;
  4278. cfg->cache_ipv4_answers = 1;
  4279. cfg->prefer_ipv6_virtaddr = 1;
  4280. return cfg;
  4281. }
  4282. /** Free all storage held in <b>port</b> */
  4283. static void
  4284. port_cfg_free(port_cfg_t *port)
  4285. {
  4286. tor_free(port);
  4287. }
  4288. /** Warn for every port in <b>ports</b> of type <b>listener_type</b> that is
  4289. * on a publicly routable address. */
  4290. static void
  4291. warn_nonlocal_client_ports(const smartlist_t *ports, const char *portname,
  4292. int listener_type)
  4293. {
  4294. SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
  4295. if (port->type != listener_type)
  4296. continue;
  4297. if (port->is_unix_addr) {
  4298. /* Unix sockets aren't accessible over a network. */
  4299. } else if (!tor_addr_is_internal(&port->addr, 1)) {
  4300. log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
  4301. "Other people on the Internet might find your computer and "
  4302. "use it as an open proxy. Please don't allow this unless you "
  4303. "have a good reason.",
  4304. fmt_addrport(&port->addr, port->port), portname);
  4305. } else if (!tor_addr_is_loopback(&port->addr)) {
  4306. log_notice(LD_CONFIG, "You configured a non-loopback address '%s' "
  4307. "for %sPort. This allows everybody on your local network to "
  4308. "use your machine as a proxy. Make sure this is what you "
  4309. "wanted.",
  4310. fmt_addrport(&port->addr, port->port), portname);
  4311. }
  4312. } SMARTLIST_FOREACH_END(port);
  4313. }
  4314. /** Given a list of port_cfg_t in <b>ports</b>, warn any controller port there
  4315. * is listening on any non-loopback address. If <b>forbid</b> is true,
  4316. * then emit a stronger warning and remove the port from the list.
  4317. */
  4318. static void
  4319. warn_nonlocal_controller_ports(smartlist_t *ports, unsigned forbid)
  4320. {
  4321. int warned = 0;
  4322. SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
  4323. if (port->type != CONN_TYPE_CONTROL_LISTENER)
  4324. continue;
  4325. if (port->is_unix_addr)
  4326. continue;
  4327. if (!tor_addr_is_loopback(&port->addr)) {
  4328. if (forbid) {
  4329. if (!warned)
  4330. log_warn(LD_CONFIG,
  4331. "You have a ControlPort set to accept "
  4332. "unauthenticated connections from a non-local address. "
  4333. "This means that programs not running on your computer "
  4334. "can reconfigure your Tor, without even having to guess a "
  4335. "password. That's so bad that I'm closing your ControlPort "
  4336. "for you. If you need to control your Tor remotely, try "
  4337. "enabling authentication and using a tool like stunnel or "
  4338. "ssh to encrypt remote access.");
  4339. warned = 1;
  4340. port_cfg_free(port);
  4341. SMARTLIST_DEL_CURRENT(ports, port);
  4342. } else {
  4343. log_warn(LD_CONFIG, "You have a ControlPort set to accept "
  4344. "connections from a non-local address. This means that "
  4345. "programs not running on your computer can reconfigure your "
  4346. "Tor. That's pretty bad, since the controller "
  4347. "protocol isn't encrypted! Maybe you should just listen on "
  4348. "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
  4349. "remote connections to your control port.");
  4350. return; /* No point in checking the rest */
  4351. }
  4352. }
  4353. } SMARTLIST_FOREACH_END(port);
  4354. }
  4355. #define CL_PORT_NO_OPTIONS (1u<<0)
  4356. #define CL_PORT_WARN_NONLOCAL (1u<<1)
  4357. #define CL_PORT_ALLOW_EXTRA_LISTENADDR (1u<<2)
  4358. #define CL_PORT_SERVER_OPTIONS (1u<<3)
  4359. #define CL_PORT_FORBID_NONLOCAL (1u<<4)
  4360. #define CL_PORT_TAKES_HOSTNAMES (1u<<5)
  4361. /**
  4362. * Parse port configuration for a single port type.
  4363. *
  4364. * Read entries of the "FooPort" type from the list <b>ports</b>, and
  4365. * entries of the "FooListenAddress" type from the list
  4366. * <b>listenaddrs</b>. Two syntaxes are supported: a legacy syntax
  4367. * where FooPort is at most a single entry containing a port number and
  4368. * where FooListenAddress has any number of address:port combinations;
  4369. * and a new syntax where there are no FooListenAddress entries and
  4370. * where FooPort can have any number of entries of the format
  4371. * "[Address:][Port] IsolationOptions".
  4372. *
  4373. * In log messages, describe the port type as <b>portname</b>.
  4374. *
  4375. * If no address is specified, default to <b>defaultaddr</b>. If no
  4376. * FooPort is given, default to defaultport (if 0, there is no default).
  4377. *
  4378. * If CL_PORT_NO_OPTIONS is set in <b>flags</b>, do not allow stream
  4379. * isolation options in the FooPort entries.
  4380. *
  4381. * If CL_PORT_WARN_NONLOCAL is set in <b>flags</b>, warn if any of the
  4382. * ports are not on a local address. If CL_PORT_FORBID_NONLOCAL is set,
  4383. * this is a contrl port with no password set: don't even allow it.
  4384. *
  4385. * Unless CL_PORT_ALLOW_EXTRA_LISTENADDR is set in <b>flags</b>, warn
  4386. * if FooListenAddress is set but FooPort is 0.
  4387. *
  4388. * If CL_PORT_SERVER_OPTIONS is set in <b>flags</b>, do not allow stream
  4389. * isolation options in the FooPort entries; instead allow the
  4390. * server-port option set.
  4391. *
  4392. * If CL_PORT_TAKES_HOSTNAMES is set in <b>flags</b>, allow the options
  4393. * {No,}IPv{4,6}Traffic.
  4394. *
  4395. * On success, if <b>out</b> is given, add a new port_cfg_t entry to
  4396. * <b>out</b> for every port that the client should listen on. Return 0
  4397. * on success, -1 on failure.
  4398. */
  4399. static int
  4400. parse_port_config(smartlist_t *out,
  4401. const config_line_t *ports,
  4402. const config_line_t *listenaddrs,
  4403. const char *portname,
  4404. int listener_type,
  4405. const char *defaultaddr,
  4406. int defaultport,
  4407. unsigned flags)
  4408. {
  4409. smartlist_t *elts;
  4410. int retval = -1;
  4411. const unsigned is_control = (listener_type == CONN_TYPE_CONTROL_LISTENER);
  4412. const unsigned allow_no_options = flags & CL_PORT_NO_OPTIONS;
  4413. const unsigned use_server_options = flags & CL_PORT_SERVER_OPTIONS;
  4414. const unsigned warn_nonlocal = flags & CL_PORT_WARN_NONLOCAL;
  4415. const unsigned forbid_nonlocal = flags & CL_PORT_FORBID_NONLOCAL;
  4416. const unsigned allow_spurious_listenaddr =
  4417. flags & CL_PORT_ALLOW_EXTRA_LISTENADDR;
  4418. const unsigned takes_hostnames = flags & CL_PORT_TAKES_HOSTNAMES;
  4419. int got_zero_port=0, got_nonzero_port=0;
  4420. /* FooListenAddress is deprecated; let's make it work like it used to work,
  4421. * though. */
  4422. if (listenaddrs) {
  4423. int mainport = defaultport;
  4424. if (ports && ports->next) {
  4425. log_warn(LD_CONFIG, "%sListenAddress can't be used when there are "
  4426. "multiple %sPort lines", portname, portname);
  4427. return -1;
  4428. } else if (ports) {
  4429. if (!strcmp(ports->value, "auto")) {
  4430. mainport = CFG_AUTO_PORT;
  4431. } else {
  4432. int ok;
  4433. mainport = (int)tor_parse_long(ports->value, 10, 0, 65535, &ok, NULL);
  4434. if (!ok) {
  4435. log_warn(LD_CONFIG, "%sListenAddress can only be used with a single "
  4436. "%sPort with value \"auto\" or 1-65535 and no options set.",
  4437. portname, portname);
  4438. return -1;
  4439. }
  4440. }
  4441. }
  4442. if (mainport == 0) {
  4443. if (allow_spurious_listenaddr)
  4444. return 1; /*DOCDOC*/
  4445. log_warn(LD_CONFIG, "%sPort must be defined if %sListenAddress is used",
  4446. portname, portname);
  4447. return -1;
  4448. }
  4449. if (use_server_options && out) {
  4450. /* Add a no_listen port. */
  4451. port_cfg_t *cfg = port_cfg_new();
  4452. cfg->type = listener_type;
  4453. cfg->port = mainport;
  4454. tor_addr_make_unspec(&cfg->addr); /* Server ports default to 0.0.0.0 */
  4455. cfg->no_listen = 1;
  4456. cfg->bind_ipv4_only = 1;
  4457. cfg->ipv4_traffic = 1;
  4458. cfg->prefer_ipv6_virtaddr = 1;
  4459. smartlist_add(out, cfg);
  4460. }
  4461. for (; listenaddrs; listenaddrs = listenaddrs->next) {
  4462. tor_addr_t addr;
  4463. uint16_t port = 0;
  4464. if (tor_addr_port_lookup(listenaddrs->value, &addr, &port) < 0) {
  4465. log_warn(LD_CONFIG, "Unable to parse %sListenAddress '%s'",
  4466. portname, listenaddrs->value);
  4467. return -1;
  4468. }
  4469. if (out) {
  4470. port_cfg_t *cfg = port_cfg_new();
  4471. cfg->type = listener_type;
  4472. cfg->port = port ? port : mainport;
  4473. tor_addr_copy(&cfg->addr, &addr);
  4474. cfg->session_group = SESSION_GROUP_UNSET;
  4475. cfg->isolation_flags = ISO_DEFAULT;
  4476. cfg->no_advertise = 1;
  4477. smartlist_add(out, cfg);
  4478. }
  4479. }
  4480. if (warn_nonlocal && out) {
  4481. if (is_control)
  4482. warn_nonlocal_controller_ports(out, forbid_nonlocal);
  4483. else
  4484. warn_nonlocal_client_ports(out, portname, listener_type);
  4485. }
  4486. return 0;
  4487. } /* end if (listenaddrs) */
  4488. /* No ListenAddress lines. If there's no FooPort, then maybe make a default
  4489. * one. */
  4490. if (! ports) {
  4491. if (defaultport && out) {
  4492. port_cfg_t *cfg = port_cfg_new();
  4493. cfg->type = listener_type;
  4494. cfg->port = defaultport;
  4495. tor_addr_parse(&cfg->addr, defaultaddr);
  4496. cfg->session_group = SESSION_GROUP_UNSET;
  4497. cfg->isolation_flags = ISO_DEFAULT;
  4498. smartlist_add(out, cfg);
  4499. }
  4500. return 0;
  4501. }
  4502. /* At last we can actually parse the FooPort lines. The syntax is:
  4503. * [Addr:](Port|auto) [Options].*/
  4504. elts = smartlist_new();
  4505. for (; ports; ports = ports->next) {
  4506. tor_addr_t addr;
  4507. int port;
  4508. int sessiongroup = SESSION_GROUP_UNSET;
  4509. unsigned isolation = ISO_DEFAULT;
  4510. char *addrport;
  4511. uint16_t ptmp=0;
  4512. int ok;
  4513. int no_listen = 0, no_advertise = 0, all_addrs = 0,
  4514. bind_ipv4_only = 0, bind_ipv6_only = 0,
  4515. ipv4_traffic = 1, ipv6_traffic = 0, prefer_ipv6 = 0,
  4516. cache_ipv4 = 1, use_cached_ipv4 = 0,
  4517. cache_ipv6 = 0, use_cached_ipv6 = 0,
  4518. prefer_ipv6_automap = 1;
  4519. smartlist_split_string(elts, ports->value, NULL,
  4520. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  4521. if (smartlist_len(elts) == 0) {
  4522. log_warn(LD_CONFIG, "Invalid %sPort line with no value", portname);
  4523. goto err;
  4524. }
  4525. if (allow_no_options && smartlist_len(elts) > 1) {
  4526. log_warn(LD_CONFIG, "Too many options on %sPort line", portname);
  4527. goto err;
  4528. }
  4529. /* Now parse the addr/port value */
  4530. addrport = smartlist_get(elts, 0);
  4531. if (!strcmp(addrport, "auto")) {
  4532. port = CFG_AUTO_PORT;
  4533. tor_addr_parse(&addr, defaultaddr);
  4534. } else if (!strcasecmpend(addrport, ":auto")) {
  4535. char *addrtmp = tor_strndup(addrport, strlen(addrport)-5);
  4536. port = CFG_AUTO_PORT;
  4537. if (tor_addr_port_lookup(addrtmp, &addr, &ptmp)<0 || ptmp) {
  4538. log_warn(LD_CONFIG, "Invalid address '%s' for %sPort",
  4539. escaped(addrport), portname);
  4540. tor_free(addrtmp);
  4541. goto err;
  4542. }
  4543. } else {
  4544. /* Try parsing integer port before address, because, who knows?
  4545. "9050" might be a valid address. */
  4546. port = (int) tor_parse_long(addrport, 10, 0, 65535, &ok, NULL);
  4547. if (ok) {
  4548. tor_addr_parse(&addr, defaultaddr);
  4549. } else if (tor_addr_port_lookup(addrport, &addr, &ptmp) == 0) {
  4550. if (ptmp == 0) {
  4551. log_warn(LD_CONFIG, "%sPort line has address but no port", portname);
  4552. goto err;
  4553. }
  4554. port = ptmp;
  4555. } else {
  4556. log_warn(LD_CONFIG, "Couldn't parse address '%s' for %sPort",
  4557. escaped(addrport), portname);
  4558. goto err;
  4559. }
  4560. }
  4561. /* Now parse the rest of the options, if any. */
  4562. if (use_server_options) {
  4563. /* This is a server port; parse advertising options */
  4564. SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
  4565. if (elt_sl_idx == 0)
  4566. continue; /* Skip addr:port */
  4567. if (!strcasecmp(elt, "NoAdvertise")) {
  4568. no_advertise = 1;
  4569. } else if (!strcasecmp(elt, "NoListen")) {
  4570. no_listen = 1;
  4571. #if 0
  4572. /* not implemented yet. */
  4573. } else if (!strcasecmp(elt, "AllAddrs")) {
  4574. all_addrs = 1;
  4575. #endif
  4576. } else if (!strcasecmp(elt, "IPv4Only")) {
  4577. bind_ipv4_only = 1;
  4578. } else if (!strcasecmp(elt, "IPv6Only")) {
  4579. bind_ipv6_only = 1;
  4580. } else {
  4581. log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
  4582. portname, escaped(elt));
  4583. }
  4584. } SMARTLIST_FOREACH_END(elt);
  4585. if (no_advertise && no_listen) {
  4586. log_warn(LD_CONFIG, "Tried to set both NoListen and NoAdvertise "
  4587. "on %sPort line '%s'",
  4588. portname, escaped(ports->value));
  4589. goto err;
  4590. }
  4591. if (bind_ipv4_only && bind_ipv6_only) {
  4592. log_warn(LD_CONFIG, "Tried to set both IPv4Only and IPv6Only "
  4593. "on %sPort line '%s'",
  4594. portname, escaped(ports->value));
  4595. goto err;
  4596. }
  4597. if (bind_ipv4_only && tor_addr_family(&addr) == AF_INET6) {
  4598. log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv6",
  4599. portname);
  4600. goto err;
  4601. }
  4602. if (bind_ipv6_only && tor_addr_family(&addr) == AF_INET) {
  4603. log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv4",
  4604. portname);
  4605. goto err;
  4606. }
  4607. } else {
  4608. /* This is a client port; parse isolation options */
  4609. SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
  4610. int no = 0, isoflag = 0;
  4611. const char *elt_orig = elt;
  4612. if (elt_sl_idx == 0)
  4613. continue; /* Skip addr:port */
  4614. if (!strcasecmpstart(elt, "SessionGroup=")) {
  4615. int group = (int)tor_parse_long(elt+strlen("SessionGroup="),
  4616. 10, 0, INT_MAX, &ok, NULL);
  4617. if (!ok) {
  4618. log_warn(LD_CONFIG, "Invalid %sPort option '%s'",
  4619. portname, escaped(elt));
  4620. goto err;
  4621. }
  4622. if (sessiongroup >= 0) {
  4623. log_warn(LD_CONFIG, "Multiple SessionGroup options on %sPort",
  4624. portname);
  4625. goto err;
  4626. }
  4627. sessiongroup = group;
  4628. continue;
  4629. }
  4630. if (!strcasecmpstart(elt, "No")) {
  4631. no = 1;
  4632. elt += 2;
  4633. }
  4634. if (takes_hostnames) {
  4635. if (!strcasecmp(elt, "IPv4Traffic")) {
  4636. ipv4_traffic = ! no;
  4637. continue;
  4638. } else if (!strcasecmp(elt, "IPv6Traffic")) {
  4639. ipv6_traffic = ! no;
  4640. continue;
  4641. } else if (!strcasecmp(elt, "PreferIPv6")) {
  4642. prefer_ipv6 = ! no;
  4643. continue;
  4644. }
  4645. }
  4646. if (!strcasecmp(elt, "CacheIPv4DNS")) {
  4647. cache_ipv4 = ! no;
  4648. continue;
  4649. } else if (!strcasecmp(elt, "CacheIPv6DNS")) {
  4650. cache_ipv6 = ! no;
  4651. continue;
  4652. } else if (!strcasecmp(elt, "CacheDNS")) {
  4653. cache_ipv4 = cache_ipv6 = ! no;
  4654. continue;
  4655. } else if (!strcasecmp(elt, "UseIPv4Cache")) {
  4656. use_cached_ipv4 = ! no;
  4657. continue;
  4658. } else if (!strcasecmp(elt, "UseIPv6Cache")) {
  4659. use_cached_ipv6 = ! no;
  4660. continue;
  4661. } else if (!strcasecmp(elt, "UseDNSCache")) {
  4662. use_cached_ipv4 = use_cached_ipv6 = ! no;
  4663. continue;
  4664. } else if (!strcasecmp(elt, "PreferIPv6Automap")) {
  4665. prefer_ipv6_automap = ! no;
  4666. continue;
  4667. }
  4668. if (!strcasecmpend(elt, "s"))
  4669. elt[strlen(elt)-1] = '\0'; /* kill plurals. */
  4670. if (!strcasecmp(elt, "IsolateDestPort")) {
  4671. isoflag = ISO_DESTPORT;
  4672. } else if (!strcasecmp(elt, "IsolateDestAddr")) {
  4673. isoflag = ISO_DESTADDR;
  4674. } else if (!strcasecmp(elt, "IsolateSOCKSAuth")) {
  4675. isoflag = ISO_SOCKSAUTH;
  4676. } else if (!strcasecmp(elt, "IsolateClientProtocol")) {
  4677. isoflag = ISO_CLIENTPROTO;
  4678. } else if (!strcasecmp(elt, "IsolateClientAddr")) {
  4679. isoflag = ISO_CLIENTADDR;
  4680. } else {
  4681. log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
  4682. portname, escaped(elt_orig));
  4683. }
  4684. if (no) {
  4685. isolation &= ~isoflag;
  4686. } else {
  4687. isolation |= isoflag;
  4688. }
  4689. } SMARTLIST_FOREACH_END(elt);
  4690. }
  4691. if (port)
  4692. got_nonzero_port = 1;
  4693. else
  4694. got_zero_port = 1;
  4695. if (ipv4_traffic == 0 && ipv6_traffic == 0) {
  4696. log_warn(LD_CONFIG, "You have a %sPort entry with both IPv4 and "
  4697. "IPv6 disabled; that won't work.", portname);
  4698. goto err;
  4699. }
  4700. if (out && port) {
  4701. port_cfg_t *cfg = port_cfg_new();
  4702. tor_addr_copy(&cfg->addr, &addr);
  4703. cfg->port = port;
  4704. cfg->type = listener_type;
  4705. cfg->isolation_flags = isolation;
  4706. cfg->session_group = sessiongroup;
  4707. cfg->no_advertise = no_advertise;
  4708. cfg->no_listen = no_listen;
  4709. cfg->all_addrs = all_addrs;
  4710. cfg->bind_ipv4_only = bind_ipv4_only;
  4711. cfg->bind_ipv6_only = bind_ipv6_only;
  4712. cfg->ipv4_traffic = ipv4_traffic;
  4713. cfg->ipv6_traffic = ipv6_traffic;
  4714. cfg->prefer_ipv6 = prefer_ipv6;
  4715. cfg->cache_ipv4_answers = cache_ipv4;
  4716. cfg->cache_ipv6_answers = cache_ipv6;
  4717. cfg->use_cached_ipv4_answers = use_cached_ipv4;
  4718. cfg->use_cached_ipv6_answers = use_cached_ipv6;
  4719. cfg->prefer_ipv6_virtaddr = prefer_ipv6_automap;
  4720. smartlist_add(out, cfg);
  4721. }
  4722. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  4723. smartlist_clear(elts);
  4724. }
  4725. if (warn_nonlocal && out) {
  4726. if (is_control)
  4727. warn_nonlocal_controller_ports(out, forbid_nonlocal);
  4728. else
  4729. warn_nonlocal_client_ports(out, portname, listener_type);
  4730. }
  4731. if (got_zero_port && got_nonzero_port) {
  4732. log_warn(LD_CONFIG, "You specified a nonzero %sPort along with '%sPort 0' "
  4733. "in the same configuration. Did you mean to disable %sPort or "
  4734. "not?", portname, portname, portname);
  4735. goto err;
  4736. }
  4737. retval = 0;
  4738. err:
  4739. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  4740. smartlist_free(elts);
  4741. return retval;
  4742. }
  4743. /** Parse a list of config_line_t for an AF_UNIX unix socket listener option
  4744. * from <b>cfg</b> and add them to <b>out</b>. No fancy options are
  4745. * supported: the line contains nothing but the path to the AF_UNIX socket. */
  4746. static int
  4747. parse_unix_socket_config(smartlist_t *out, const config_line_t *cfg,
  4748. int listener_type)
  4749. {
  4750. if (!out)
  4751. return 0;
  4752. for ( ; cfg; cfg = cfg->next) {
  4753. size_t len = strlen(cfg->value);
  4754. port_cfg_t *port = tor_malloc_zero(sizeof(port_cfg_t) + len + 1);
  4755. port->is_unix_addr = 1;
  4756. memcpy(port->unix_addr, cfg->value, len+1);
  4757. port->type = listener_type;
  4758. smartlist_add(out, port);
  4759. }
  4760. return 0;
  4761. }
  4762. /** Return the number of ports which are actually going to listen with type
  4763. * <b>listenertype</b>. Do not count no_listen ports. Do not count unix
  4764. * sockets. */
  4765. static int
  4766. count_real_listeners(const smartlist_t *ports, int listenertype)
  4767. {
  4768. int n = 0;
  4769. SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
  4770. if (port->no_listen || port->is_unix_addr)
  4771. continue;
  4772. if (port->type != listenertype)
  4773. continue;
  4774. ++n;
  4775. } SMARTLIST_FOREACH_END(port);
  4776. return n;
  4777. }
  4778. /** Parse all client port types (Socks, DNS, Trans, NATD) from
  4779. * <b>options</b>. On success, set *<b>n_ports_out</b> to the number
  4780. * of ports that are listed, update the *Port_set values in
  4781. * <b>options</b>, and return 0. On failure, set *<b>msg</b> to a
  4782. * description of the problem and return -1.
  4783. *
  4784. * If <b>validate_only</b> is false, set configured_client_ports to the
  4785. * new list of ports parsed from <b>options</b>.
  4786. **/
  4787. static int
  4788. parse_ports(or_options_t *options, int validate_only,
  4789. char **msg, int *n_ports_out)
  4790. {
  4791. smartlist_t *ports;
  4792. int retval = -1;
  4793. ports = smartlist_new();
  4794. *n_ports_out = 0;
  4795. if (parse_port_config(ports,
  4796. options->SocksPort_lines, options->SocksListenAddress,
  4797. "Socks", CONN_TYPE_AP_LISTENER,
  4798. "127.0.0.1", 9050,
  4799. CL_PORT_WARN_NONLOCAL|CL_PORT_ALLOW_EXTRA_LISTENADDR|
  4800. CL_PORT_TAKES_HOSTNAMES) < 0) {
  4801. *msg = tor_strdup("Invalid SocksPort/SocksListenAddress configuration");
  4802. goto err;
  4803. }
  4804. if (parse_port_config(ports,
  4805. options->DNSPort_lines, options->DNSListenAddress,
  4806. "DNS", CONN_TYPE_AP_DNS_LISTENER,
  4807. "127.0.0.1", 0,
  4808. CL_PORT_WARN_NONLOCAL|CL_PORT_TAKES_HOSTNAMES) < 0) {
  4809. *msg = tor_strdup("Invalid DNSPort/DNSListenAddress configuration");
  4810. goto err;
  4811. }
  4812. if (parse_port_config(ports,
  4813. options->TransPort_lines, options->TransListenAddress,
  4814. "Trans", CONN_TYPE_AP_TRANS_LISTENER,
  4815. "127.0.0.1", 0,
  4816. CL_PORT_WARN_NONLOCAL) < 0) {
  4817. *msg = tor_strdup("Invalid TransPort/TransListenAddress configuration");
  4818. goto err;
  4819. }
  4820. if (parse_port_config(ports,
  4821. options->NATDPort_lines, options->NATDListenAddress,
  4822. "NATD", CONN_TYPE_AP_NATD_LISTENER,
  4823. "127.0.0.1", 0,
  4824. CL_PORT_WARN_NONLOCAL) < 0) {
  4825. *msg = tor_strdup("Invalid NatdPort/NatdListenAddress configuration");
  4826. goto err;
  4827. }
  4828. {
  4829. unsigned control_port_flags = CL_PORT_NO_OPTIONS | CL_PORT_WARN_NONLOCAL;
  4830. const int any_passwords = (options->HashedControlPassword ||
  4831. options->HashedControlSessionPassword ||
  4832. options->CookieAuthentication);
  4833. if (! any_passwords)
  4834. control_port_flags |= CL_PORT_FORBID_NONLOCAL;
  4835. if (parse_port_config(ports,
  4836. options->ControlPort_lines,
  4837. options->ControlListenAddress,
  4838. "Control", CONN_TYPE_CONTROL_LISTENER,
  4839. "127.0.0.1", 0,
  4840. control_port_flags) < 0) {
  4841. *msg = tor_strdup("Invalid ControlPort/ControlListenAddress "
  4842. "configuration");
  4843. goto err;
  4844. }
  4845. if (parse_unix_socket_config(ports,
  4846. options->ControlSocket,
  4847. CONN_TYPE_CONTROL_LISTENER) < 0) {
  4848. *msg = tor_strdup("Invalid ControlSocket configuration");
  4849. goto err;
  4850. }
  4851. }
  4852. if (! options->ClientOnly) {
  4853. if (parse_port_config(ports,
  4854. options->ORPort_lines, options->ORListenAddress,
  4855. "OR", CONN_TYPE_OR_LISTENER,
  4856. "0.0.0.0", 0,
  4857. CL_PORT_SERVER_OPTIONS) < 0) {
  4858. *msg = tor_strdup("Invalid ORPort/ORListenAddress configuration");
  4859. goto err;
  4860. }
  4861. if (parse_port_config(ports,
  4862. options->DirPort_lines, options->DirListenAddress,
  4863. "Dir", CONN_TYPE_DIR_LISTENER,
  4864. "0.0.0.0", 0,
  4865. CL_PORT_SERVER_OPTIONS) < 0) {
  4866. *msg = tor_strdup("Invalid DirPort/DirListenAddress configuration");
  4867. goto err;
  4868. }
  4869. }
  4870. if (check_server_ports(ports, options) < 0) {
  4871. *msg = tor_strdup("Misconfigured server ports");
  4872. goto err;
  4873. }
  4874. *n_ports_out = smartlist_len(ports);
  4875. retval = 0;
  4876. /* Update the *Port_set options. The !! here is to force a boolean out of
  4877. an integer. */
  4878. options->ORPort_set =
  4879. !! count_real_listeners(ports, CONN_TYPE_OR_LISTENER);
  4880. options->SocksPort_set =
  4881. !! count_real_listeners(ports, CONN_TYPE_AP_LISTENER);
  4882. options->TransPort_set =
  4883. !! count_real_listeners(ports, CONN_TYPE_AP_TRANS_LISTENER);
  4884. options->NATDPort_set =
  4885. !! count_real_listeners(ports, CONN_TYPE_AP_NATD_LISTENER);
  4886. options->ControlPort_set =
  4887. !! count_real_listeners(ports, CONN_TYPE_CONTROL_LISTENER);
  4888. options->DirPort_set =
  4889. !! count_real_listeners(ports, CONN_TYPE_DIR_LISTENER);
  4890. options->DNSPort_set =
  4891. !! count_real_listeners(ports, CONN_TYPE_AP_DNS_LISTENER);
  4892. if (!validate_only) {
  4893. if (configured_ports) {
  4894. SMARTLIST_FOREACH(configured_ports,
  4895. port_cfg_t *, p, port_cfg_free(p));
  4896. smartlist_free(configured_ports);
  4897. }
  4898. configured_ports = ports;
  4899. ports = NULL; /* prevent free below. */
  4900. }
  4901. err:
  4902. if (ports) {
  4903. SMARTLIST_FOREACH(ports, port_cfg_t *, p, port_cfg_free(p));
  4904. smartlist_free(ports);
  4905. }
  4906. return retval;
  4907. }
  4908. /** Given a list of <b>port_cfg_t</b> in <b>ports</b>, check them for internal
  4909. * consistency and warn as appropriate. */
  4910. static int
  4911. check_server_ports(const smartlist_t *ports,
  4912. const or_options_t *options)
  4913. {
  4914. int n_orport_advertised = 0;
  4915. int n_orport_advertised_ipv4 = 0;
  4916. int n_orport_listeners = 0;
  4917. int n_dirport_advertised = 0;
  4918. int n_dirport_listeners = 0;
  4919. int n_low_port = 0;
  4920. int r = 0;
  4921. SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
  4922. if (port->type == CONN_TYPE_DIR_LISTENER) {
  4923. if (! port->no_advertise)
  4924. ++n_dirport_advertised;
  4925. if (! port->no_listen)
  4926. ++n_dirport_listeners;
  4927. } else if (port->type == CONN_TYPE_OR_LISTENER) {
  4928. if (! port->no_advertise) {
  4929. ++n_orport_advertised;
  4930. if (tor_addr_family(&port->addr) == AF_INET ||
  4931. (tor_addr_family(&port->addr) == AF_UNSPEC &&
  4932. !port->bind_ipv6_only))
  4933. ++n_orport_advertised_ipv4;
  4934. }
  4935. if (! port->no_listen)
  4936. ++n_orport_listeners;
  4937. } else {
  4938. continue;
  4939. }
  4940. #ifndef _WIN32
  4941. if (!port->no_listen && port->port < 1024)
  4942. ++n_low_port;
  4943. #endif
  4944. } SMARTLIST_FOREACH_END(port);
  4945. if (n_orport_advertised && !n_orport_listeners) {
  4946. log_warn(LD_CONFIG, "We are advertising an ORPort, but not actually "
  4947. "listening on one.");
  4948. r = -1;
  4949. }
  4950. if (n_dirport_advertised && !n_dirport_listeners) {
  4951. log_warn(LD_CONFIG, "We are advertising a DirPort, but not actually "
  4952. "listening on one.");
  4953. r = -1;
  4954. }
  4955. if (n_dirport_advertised > 1) {
  4956. log_warn(LD_CONFIG, "Can't advertise more than one DirPort.");
  4957. r = -1;
  4958. }
  4959. if (n_orport_advertised && !n_orport_advertised_ipv4 &&
  4960. !options->BridgeRelay) {
  4961. log_warn(LD_CONFIG, "Configured non-bridge only to listen on an IPv6 "
  4962. "address.");
  4963. r = -1;
  4964. }
  4965. if (n_low_port && options->AccountingMax) {
  4966. log_warn(LD_CONFIG,
  4967. "You have set AccountingMax to use hibernation. You have also "
  4968. "chosen a low DirPort or OrPort. This combination can make Tor stop "
  4969. "working when it tries to re-attach the port after a period of "
  4970. "hibernation. Please choose a different port or turn off "
  4971. "hibernation unless you know this combination will work on your "
  4972. "platform.");
  4973. }
  4974. return r;
  4975. }
  4976. /** Return a list of port_cfg_t for client ports parsed from the
  4977. * options. */
  4978. const smartlist_t *
  4979. get_configured_ports(void)
  4980. {
  4981. if (!configured_ports)
  4982. configured_ports = smartlist_new();
  4983. return configured_ports;
  4984. }
  4985. /** Return an address:port string representation of the address
  4986. * where the first <b>listener_type</b> listener waits for
  4987. * connections. Return NULL if we couldn't find a listener. The
  4988. * string is allocated on the heap and it's the responsibility of the
  4989. * caller to free it after use.
  4990. *
  4991. * This function is meant to be used by the pluggable transport proxy
  4992. * spawning code, please make sure that it fits your purposes before
  4993. * using it. */
  4994. char *
  4995. get_first_listener_addrport_string(int listener_type)
  4996. {
  4997. static const char *ipv4_localhost = "127.0.0.1";
  4998. static const char *ipv6_localhost = "[::1]";
  4999. const char *address;
  5000. uint16_t port;
  5001. char *string = NULL;
  5002. if (!configured_ports)
  5003. return NULL;
  5004. SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
  5005. if (cfg->no_listen)
  5006. continue;
  5007. if (cfg->type == listener_type &&
  5008. tor_addr_family(&cfg->addr) != AF_UNSPEC) {
  5009. /* We found the first listener of the type we are interested in! */
  5010. /* If a listener is listening on INADDR_ANY, assume that it's
  5011. also listening on 127.0.0.1, and point the transport proxy
  5012. there: */
  5013. if (tor_addr_is_null(&cfg->addr))
  5014. address = tor_addr_is_v4(&cfg->addr) ? ipv4_localhost : ipv6_localhost;
  5015. else
  5016. address = fmt_and_decorate_addr(&cfg->addr);
  5017. /* If a listener is configured with port 'auto', we are forced
  5018. to iterate all listener connections and find out in which
  5019. port it ended up listening: */
  5020. if (cfg->port == CFG_AUTO_PORT) {
  5021. port = router_get_active_listener_port_by_type(listener_type);
  5022. if (!port)
  5023. return NULL;
  5024. } else {
  5025. port = cfg->port;
  5026. }
  5027. tor_asprintf(&string, "%s:%u", address, port);
  5028. return string;
  5029. }
  5030. } SMARTLIST_FOREACH_END(cfg);
  5031. return NULL;
  5032. }
  5033. /** Return the first advertised port of type <b>listener_type</b> in
  5034. <b>address_family</b>. */
  5035. int
  5036. get_first_advertised_port_by_type_af(int listener_type, int address_family)
  5037. {
  5038. if (!configured_ports)
  5039. return 0;
  5040. SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
  5041. if (cfg->type == listener_type &&
  5042. !cfg->no_advertise &&
  5043. (tor_addr_family(&cfg->addr) == address_family ||
  5044. tor_addr_family(&cfg->addr) == AF_UNSPEC)) {
  5045. if (tor_addr_family(&cfg->addr) != AF_UNSPEC ||
  5046. (address_family == AF_INET && !cfg->bind_ipv6_only) ||
  5047. (address_family == AF_INET6 && !cfg->bind_ipv4_only)) {
  5048. return cfg->port;
  5049. }
  5050. }
  5051. } SMARTLIST_FOREACH_END(cfg);
  5052. return 0;
  5053. }
  5054. /** Adjust the value of options->DataDirectory, or fill it in if it's
  5055. * absent. Return 0 on success, -1 on failure. */
  5056. static int
  5057. normalize_data_directory(or_options_t *options)
  5058. {
  5059. #ifdef _WIN32
  5060. char *p;
  5061. if (options->DataDirectory)
  5062. return 0; /* all set */
  5063. p = tor_malloc(MAX_PATH);
  5064. strlcpy(p,get_windows_conf_root(),MAX_PATH);
  5065. options->DataDirectory = p;
  5066. return 0;
  5067. #else
  5068. const char *d = options->DataDirectory;
  5069. if (!d)
  5070. d = "~/.tor";
  5071. if (strncmp(d,"~/",2) == 0) {
  5072. char *fn = expand_filename(d);
  5073. if (!fn) {
  5074. log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
  5075. return -1;
  5076. }
  5077. if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
  5078. /* If our homedir is /, we probably don't want to use it. */
  5079. /* Default to LOCALSTATEDIR/tor which is probably closer to what we
  5080. * want. */
  5081. log_warn(LD_CONFIG,
  5082. "Default DataDirectory is \"~/.tor\". This expands to "
  5083. "\"%s\", which is probably not what you want. Using "
  5084. "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
  5085. tor_free(fn);
  5086. fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
  5087. }
  5088. tor_free(options->DataDirectory);
  5089. options->DataDirectory = fn;
  5090. }
  5091. return 0;
  5092. #endif
  5093. }
  5094. /** Check and normalize the value of options->DataDirectory; return 0 if it
  5095. * is sane, -1 otherwise. */
  5096. static int
  5097. validate_data_directory(or_options_t *options)
  5098. {
  5099. if (normalize_data_directory(options) < 0)
  5100. return -1;
  5101. tor_assert(options->DataDirectory);
  5102. if (strlen(options->DataDirectory) > (512-128)) {
  5103. log_warn(LD_CONFIG, "DataDirectory is too long.");
  5104. return -1;
  5105. }
  5106. return 0;
  5107. }
  5108. /** This string must remain the same forevermore. It is how we
  5109. * recognize that the torrc file doesn't need to be backed up. */
  5110. #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
  5111. "if you edit it, comments will not be preserved"
  5112. /** This string can change; it tries to give the reader an idea
  5113. * that editing this file by hand is not a good plan. */
  5114. #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
  5115. "to torrc.orig.1 or similar, and Tor will ignore it"
  5116. /** Save a configuration file for the configuration in <b>options</b>
  5117. * into the file <b>fname</b>. If the file already exists, and
  5118. * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
  5119. * replace it. Return 0 on success, -1 on failure. */
  5120. static int
  5121. write_configuration_file(const char *fname, const or_options_t *options)
  5122. {
  5123. char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
  5124. int rename_old = 0, r;
  5125. tor_assert(fname);
  5126. switch (file_status(fname)) {
  5127. case FN_FILE:
  5128. old_val = read_file_to_str(fname, 0, NULL);
  5129. if (!old_val || strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
  5130. rename_old = 1;
  5131. }
  5132. tor_free(old_val);
  5133. break;
  5134. case FN_NOENT:
  5135. break;
  5136. case FN_ERROR:
  5137. case FN_DIR:
  5138. default:
  5139. log_warn(LD_CONFIG,
  5140. "Config file \"%s\" is not a file? Failing.", fname);
  5141. return -1;
  5142. }
  5143. if (!(new_conf = options_dump(options, 1))) {
  5144. log_warn(LD_BUG, "Couldn't get configuration string");
  5145. goto err;
  5146. }
  5147. tor_asprintf(&new_val, "%s\n%s\n\n%s",
  5148. GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
  5149. if (rename_old) {
  5150. int i = 1;
  5151. char *fn_tmp = NULL;
  5152. while (1) {
  5153. tor_asprintf(&fn_tmp, "%s.orig.%d", fname, i);
  5154. if (file_status(fn_tmp) == FN_NOENT)
  5155. break;
  5156. tor_free(fn_tmp);
  5157. ++i;
  5158. }
  5159. log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
  5160. if (rename(fname, fn_tmp) < 0) {
  5161. log_warn(LD_FS,
  5162. "Couldn't rename configuration file \"%s\" to \"%s\": %s",
  5163. fname, fn_tmp, strerror(errno));
  5164. tor_free(fn_tmp);
  5165. goto err;
  5166. }
  5167. tor_free(fn_tmp);
  5168. }
  5169. if (write_str_to_file(fname, new_val, 0) < 0)
  5170. goto err;
  5171. r = 0;
  5172. goto done;
  5173. err:
  5174. r = -1;
  5175. done:
  5176. tor_free(new_val);
  5177. tor_free(new_conf);
  5178. return r;
  5179. }
  5180. /**
  5181. * Save the current configuration file value to disk. Return 0 on
  5182. * success, -1 on failure.
  5183. **/
  5184. int
  5185. options_save_current(void)
  5186. {
  5187. /* This fails if we can't write to our configuration file.
  5188. *
  5189. * If we try falling back to datadirectory or something, we have a better
  5190. * chance of saving the configuration, but a better chance of doing
  5191. * something the user never expected. */
  5192. return write_configuration_file(get_torrc_fname(0), get_options());
  5193. }
  5194. /** Return the number of cpus configured in <b>options</b>. If we are
  5195. * told to auto-detect the number of cpus, return the auto-detected number. */
  5196. int
  5197. get_num_cpus(const or_options_t *options)
  5198. {
  5199. if (options->NumCPUs == 0) {
  5200. int n = compute_num_cpus();
  5201. return (n >= 1) ? n : 1;
  5202. } else {
  5203. return options->NumCPUs;
  5204. }
  5205. }
  5206. /**
  5207. * Initialize the libevent library.
  5208. */
  5209. static void
  5210. init_libevent(const or_options_t *options)
  5211. {
  5212. const char *badness=NULL;
  5213. tor_libevent_cfg cfg;
  5214. tor_assert(options);
  5215. configure_libevent_logging();
  5216. /* If the kernel complains that some method (say, epoll) doesn't
  5217. * exist, we don't care about it, since libevent will cope.
  5218. */
  5219. suppress_libevent_log_msg("Function not implemented");
  5220. tor_check_libevent_header_compatibility();
  5221. memset(&cfg, 0, sizeof(cfg));
  5222. cfg.disable_iocp = options->DisableIOCP;
  5223. cfg.num_cpus = get_num_cpus(options);
  5224. cfg.msec_per_tick = options->TokenBucketRefillInterval;
  5225. tor_libevent_initialize(&cfg);
  5226. suppress_libevent_log_msg(NULL);
  5227. tor_check_libevent_version(tor_libevent_get_method(),
  5228. server_mode(get_options()),
  5229. &badness);
  5230. if (badness) {
  5231. const char *v = tor_libevent_get_version_str();
  5232. const char *m = tor_libevent_get_method();
  5233. control_event_general_status(LOG_WARN,
  5234. "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
  5235. v, m, badness);
  5236. }
  5237. }
  5238. /** Return a newly allocated string holding a filename relative to the data
  5239. * directory. If <b>sub1</b> is present, it is the first path component after
  5240. * the data directory. If <b>sub2</b> is also present, it is the second path
  5241. * component after the data directory. If <b>suffix</b> is present, it
  5242. * is appended to the filename.
  5243. *
  5244. * Examples:
  5245. * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
  5246. * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
  5247. * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
  5248. * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
  5249. *
  5250. * Note: Consider using the get_datadir_fname* macros in or.h.
  5251. */
  5252. char *
  5253. options_get_datadir_fname2_suffix(const or_options_t *options,
  5254. const char *sub1, const char *sub2,
  5255. const char *suffix)
  5256. {
  5257. char *fname = NULL;
  5258. size_t len;
  5259. tor_assert(options);
  5260. tor_assert(options->DataDirectory);
  5261. tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
  5262. len = strlen(options->DataDirectory);
  5263. if (sub1) {
  5264. len += strlen(sub1)+1;
  5265. if (sub2)
  5266. len += strlen(sub2)+1;
  5267. }
  5268. if (suffix)
  5269. len += strlen(suffix);
  5270. len++;
  5271. fname = tor_malloc(len);
  5272. if (sub1) {
  5273. if (sub2) {
  5274. tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
  5275. options->DataDirectory, sub1, sub2);
  5276. } else {
  5277. tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
  5278. options->DataDirectory, sub1);
  5279. }
  5280. } else {
  5281. strlcpy(fname, options->DataDirectory, len);
  5282. }
  5283. if (suffix)
  5284. strlcat(fname, suffix, len);
  5285. return fname;
  5286. }
  5287. /** Given a file name check to see whether the file exists but has not been
  5288. * modified for a very long time. If so, remove it. */
  5289. void
  5290. remove_file_if_very_old(const char *fname, time_t now)
  5291. {
  5292. #define VERY_OLD_FILE_AGE (28*24*60*60)
  5293. struct stat st;
  5294. if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
  5295. char buf[ISO_TIME_LEN+1];
  5296. format_local_iso_time(buf, st.st_mtime);
  5297. log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
  5298. "Removing it.", fname, buf);
  5299. unlink(fname);
  5300. }
  5301. }
  5302. /** Return a smartlist of ports that must be forwarded by
  5303. * tor-fw-helper. The smartlist contains the ports in a string format
  5304. * that is understandable by tor-fw-helper. */
  5305. smartlist_t *
  5306. get_list_of_ports_to_forward(void)
  5307. {
  5308. smartlist_t *ports_to_forward = smartlist_new();
  5309. int port = 0;
  5310. /** XXX TODO tor-fw-helper does not support forwarding ports to
  5311. other hosts than the local one. If the user is binding to a
  5312. different IP address, tor-fw-helper won't work. */
  5313. port = router_get_advertised_or_port(get_options()); /* Get ORPort */
  5314. if (port)
  5315. smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
  5316. port = router_get_advertised_dir_port(get_options(), 0); /* Get DirPort */
  5317. if (port)
  5318. smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
  5319. /* Get ports of transport proxies */
  5320. {
  5321. smartlist_t *transport_ports = get_transport_proxy_ports();
  5322. if (transport_ports) {
  5323. smartlist_add_all(ports_to_forward, transport_ports);
  5324. smartlist_free(transport_ports);
  5325. }
  5326. }
  5327. if (!smartlist_len(ports_to_forward)) {
  5328. smartlist_free(ports_to_forward);
  5329. ports_to_forward = NULL;
  5330. }
  5331. return ports_to_forward;
  5332. }
  5333. /** Helper to implement GETINFO functions about configuration variables (not
  5334. * their values). Given a "config/names" question, set *<b>answer</b> to a
  5335. * new string describing the supported configuration variables and their
  5336. * types. */
  5337. int
  5338. getinfo_helper_config(control_connection_t *conn,
  5339. const char *question, char **answer,
  5340. const char **errmsg)
  5341. {
  5342. (void) conn;
  5343. (void) errmsg;
  5344. if (!strcmp(question, "config/names")) {
  5345. smartlist_t *sl = smartlist_new();
  5346. int i;
  5347. for (i = 0; option_vars_[i].name; ++i) {
  5348. const config_var_t *var = &option_vars_[i];
  5349. const char *type;
  5350. /* don't tell controller about triple-underscore options */
  5351. if (!strncmp(option_vars_[i].name, "___", 3))
  5352. continue;
  5353. switch (var->type) {
  5354. case CONFIG_TYPE_STRING: type = "String"; break;
  5355. case CONFIG_TYPE_FILENAME: type = "Filename"; break;
  5356. case CONFIG_TYPE_UINT: type = "Integer"; break;
  5357. case CONFIG_TYPE_INT: type = "SignedInteger"; break;
  5358. case CONFIG_TYPE_PORT: type = "Port"; break;
  5359. case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
  5360. case CONFIG_TYPE_MSEC_INTERVAL: type = "TimeMsecInterval"; break;
  5361. case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
  5362. case CONFIG_TYPE_DOUBLE: type = "Float"; break;
  5363. case CONFIG_TYPE_BOOL: type = "Boolean"; break;
  5364. case CONFIG_TYPE_AUTOBOOL: type = "Boolean+Auto"; break;
  5365. case CONFIG_TYPE_ISOTIME: type = "Time"; break;
  5366. case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
  5367. case CONFIG_TYPE_CSV: type = "CommaList"; break;
  5368. case CONFIG_TYPE_LINELIST: type = "LineList"; break;
  5369. case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
  5370. case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
  5371. default:
  5372. case CONFIG_TYPE_OBSOLETE:
  5373. type = NULL; break;
  5374. }
  5375. if (!type)
  5376. continue;
  5377. smartlist_add_asprintf(sl, "%s %s\n",var->name,type);
  5378. }
  5379. *answer = smartlist_join_strings(sl, "", 0, NULL);
  5380. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  5381. smartlist_free(sl);
  5382. } else if (!strcmp(question, "config/defaults")) {
  5383. smartlist_t *sl = smartlist_new();
  5384. int i;
  5385. for (i = 0; option_vars_[i].name; ++i) {
  5386. const config_var_t *var = &option_vars_[i];
  5387. if (var->initvalue != NULL) {
  5388. char *val = esc_for_log(var->initvalue);
  5389. smartlist_add_asprintf(sl, "%s %s\n",var->name,val);
  5390. tor_free(val);
  5391. }
  5392. }
  5393. *answer = smartlist_join_strings(sl, "", 0, NULL);
  5394. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  5395. smartlist_free(sl);
  5396. }
  5397. return 0;
  5398. }
  5399. /** Parse outbound bind address option lines. If <b>validate_only</b>
  5400. * is not 0 update OutboundBindAddressIPv4_ and
  5401. * OutboundBindAddressIPv6_ in <b>options</b>. On failure, set
  5402. * <b>msg</b> (if provided) to a newly allocated string containing a
  5403. * description of the problem and return -1. */
  5404. static int
  5405. parse_outbound_addresses(or_options_t *options, int validate_only, char **msg)
  5406. {
  5407. const config_line_t *lines = options->OutboundBindAddress;
  5408. int found_v4 = 0, found_v6 = 0;
  5409. if (!validate_only) {
  5410. memset(&options->OutboundBindAddressIPv4_, 0,
  5411. sizeof(options->OutboundBindAddressIPv4_));
  5412. memset(&options->OutboundBindAddressIPv6_, 0,
  5413. sizeof(options->OutboundBindAddressIPv6_));
  5414. }
  5415. while (lines) {
  5416. tor_addr_t addr, *dst_addr = NULL;
  5417. int af = tor_addr_parse(&addr, lines->value);
  5418. switch (af) {
  5419. case AF_INET:
  5420. if (found_v4) {
  5421. if (msg)
  5422. tor_asprintf(msg, "Multiple IPv4 outbound bind addresses "
  5423. "configured: %s", lines->value);
  5424. return -1;
  5425. }
  5426. found_v4 = 1;
  5427. dst_addr = &options->OutboundBindAddressIPv4_;
  5428. break;
  5429. case AF_INET6:
  5430. if (found_v6) {
  5431. if (msg)
  5432. tor_asprintf(msg, "Multiple IPv6 outbound bind addresses "
  5433. "configured: %s", lines->value);
  5434. return -1;
  5435. }
  5436. found_v6 = 1;
  5437. dst_addr = &options->OutboundBindAddressIPv6_;
  5438. break;
  5439. default:
  5440. if (msg)
  5441. tor_asprintf(msg, "Outbound bind address '%s' didn't parse.",
  5442. lines->value);
  5443. return -1;
  5444. }
  5445. if (!validate_only)
  5446. tor_addr_copy(dst_addr, &addr);
  5447. lines = lines->next;
  5448. }
  5449. return 0;
  5450. }
  5451. /** Load one of the geoip files, <a>family</a> determining which
  5452. * one. <a>default_fname</a> is used if on Windows and
  5453. * <a>fname</a> equals "<default>". */
  5454. static void
  5455. config_load_geoip_file_(sa_family_t family,
  5456. const char *fname,
  5457. const char *default_fname)
  5458. {
  5459. #ifdef _WIN32
  5460. char *free_fname = NULL; /* Used to hold any temporary-allocated value */
  5461. /* XXXX Don't use this "<default>" junk; make our filename options
  5462. * understand prefixes somehow. -NM */
  5463. if (!strcmp(fname, "<default>")) {
  5464. const char *conf_root = get_windows_conf_root();
  5465. tor_asprintf(&free_fname, "%s\\%s", conf_root, default_fname);
  5466. fname = free_fname;
  5467. }
  5468. geoip_load_file(family, fname);
  5469. tor_free(free_fname);
  5470. #else
  5471. (void)default_fname;
  5472. geoip_load_file(family, fname);
  5473. #endif
  5474. }
  5475. /** Load geoip files for IPv4 and IPv6 if <a>options</a> and
  5476. * <a>old_options</a> indicate we should. */
  5477. static void
  5478. config_maybe_load_geoip_files_(const or_options_t *options,
  5479. const or_options_t *old_options)
  5480. {
  5481. /* XXXX024 Reload GeoIPFile on SIGHUP. -NM */
  5482. if (options->GeoIPFile &&
  5483. ((!old_options || !opt_streq(old_options->GeoIPFile,
  5484. options->GeoIPFile))
  5485. || !geoip_is_loaded(AF_INET)))
  5486. config_load_geoip_file_(AF_INET, options->GeoIPFile, "geoip");
  5487. if (options->GeoIPv6File &&
  5488. ((!old_options || !opt_streq(old_options->GeoIPv6File,
  5489. options->GeoIPv6File))
  5490. || !geoip_is_loaded(AF_INET6)))
  5491. config_load_geoip_file_(AF_INET6, options->GeoIPv6File, "geoip6");
  5492. }