config.c 231 KB

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