config.c 299 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463
  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-2017, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file config.c
  8. * \brief Code to interpret the user's configuration of Tor.
  9. *
  10. * This module handles torrc configuration file, including parsing it,
  11. * combining it with torrc.defaults and the command line, allowing
  12. * user changes to it (via editing and SIGHUP or via the control port),
  13. * writing it back to disk (because of SAVECONF from the control port),
  14. * and -- most importantly, acting on it.
  15. *
  16. * The module additionally has some tools for manipulating and
  17. * inspecting values that are calculated as a result of the
  18. * configured options.
  19. *
  20. * <h3>How to add new options</h3>
  21. *
  22. * To add new items to the torrc, there are a minimum of three places to edit:
  23. * <ul>
  24. * <li>The or_options_t structure in or.h, where the options are stored.
  25. * <li>The option_vars_ array below in this module, which configures
  26. * the names of the torrc options, their types, their multiplicities,
  27. * and their mappings to fields in or_options_t.
  28. * <li>The manual in doc/tor.1.txt, to document what the new option
  29. * is, and how it works.
  30. * </ul>
  31. *
  32. * Additionally, you might need to edit these places too:
  33. * <ul>
  34. * <li>options_validate() below, in case you want to reject some possible
  35. * values of the new configuration option.
  36. * <li>options_transition_allowed() below, in case you need to
  37. * forbid some or all changes in the option while Tor is
  38. * running.
  39. * <li>options_transition_affects_workers(), in case changes in the option
  40. * might require Tor to relaunch or reconfigure its worker threads.
  41. * <li>options_transition_affects_descriptor(), in case changes in the
  42. * option might require a Tor relay to build and publish a new server
  43. * descriptor.
  44. * <li>options_act() and/or options_act_reversible(), in case there's some
  45. * action that needs to be taken immediately based on the option's
  46. * value.
  47. * </ul>
  48. *
  49. * <h3>Changing the value of an option</h3>
  50. *
  51. * Because of the SAVECONF command from the control port, it's a bad
  52. * idea to change the value of any user-configured option in the
  53. * or_options_t. If you want to sometimes do this anyway, we recommend
  54. * that you create a secondary field in or_options_t; that you have the
  55. * user option linked only to the secondary field; that you use the
  56. * secondary field to initialize the one that Tor actually looks at; and that
  57. * you use the one Tor looks as the one that you modify.
  58. **/
  59. #define CONFIG_PRIVATE
  60. #include "or.h"
  61. #include "bridges.h"
  62. #include "compat.h"
  63. #include "addressmap.h"
  64. #include "channel.h"
  65. #include "circuitbuild.h"
  66. #include "circuitlist.h"
  67. #include "circuitmux.h"
  68. #include "circuitmux_ewma.h"
  69. #include "circuitstats.h"
  70. #include "compress.h"
  71. #include "config.h"
  72. #include "connection.h"
  73. #include "connection_edge.h"
  74. #include "connection_or.h"
  75. #include "consdiffmgr.h"
  76. #include "control.h"
  77. #include "confparse.h"
  78. #include "cpuworker.h"
  79. #include "dirserv.h"
  80. #include "dirvote.h"
  81. #include "dns.h"
  82. #include "dos.h"
  83. #include "entrynodes.h"
  84. #include "git_revision.h"
  85. #include "geoip.h"
  86. #include "hibernate.h"
  87. #include "main.h"
  88. #include "networkstatus.h"
  89. #include "nodelist.h"
  90. #include "policies.h"
  91. #include "relay.h"
  92. #include "rendclient.h"
  93. #include "rendservice.h"
  94. #include "hs_config.h"
  95. #include "rephist.h"
  96. #include "router.h"
  97. #include "sandbox.h"
  98. #include "util.h"
  99. #include "routerlist.h"
  100. #include "routerset.h"
  101. #include "scheduler.h"
  102. #include "statefile.h"
  103. #include "transports.h"
  104. #include "ext_orport.h"
  105. #ifdef _WIN32
  106. #include <shlobj.h>
  107. #endif
  108. #include "procmon.h"
  109. #ifdef HAVE_SYSTEMD
  110. # if defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__)
  111. /* Systemd's use of gcc's __INCLUDE_LEVEL__ extension macro appears to confuse
  112. * Coverity. Here's a kludge to unconfuse it.
  113. */
  114. # define __INCLUDE_LEVEL__ 2
  115. #endif /* defined(__COVERITY__) && !defined(__INCLUDE_LEVEL__) */
  116. #include <systemd/sd-daemon.h>
  117. #endif /* defined(HAVE_SYSTEMD) */
  118. /* Prefix used to indicate a Unix socket in a FooPort configuration. */
  119. static const char unix_socket_prefix[] = "unix:";
  120. /* Prefix used to indicate a Unix socket with spaces in it, in a FooPort
  121. * configuration. */
  122. static const char unix_q_socket_prefix[] = "unix:\"";
  123. /** A list of abbreviations and aliases to map command-line options, obsolete
  124. * option names, or alternative option names, to their current values. */
  125. static config_abbrev_t option_abbrevs_[] = {
  126. PLURAL(AuthDirBadDirCC),
  127. PLURAL(AuthDirBadExitCC),
  128. PLURAL(AuthDirInvalidCC),
  129. PLURAL(AuthDirRejectCC),
  130. PLURAL(EntryNode),
  131. PLURAL(ExcludeNode),
  132. PLURAL(Tor2webRendezvousPoint),
  133. PLURAL(FirewallPort),
  134. PLURAL(LongLivedPort),
  135. PLURAL(HiddenServiceNode),
  136. PLURAL(HiddenServiceExcludeNode),
  137. PLURAL(NumCPU),
  138. PLURAL(RendNode),
  139. PLURAL(RecommendedPackage),
  140. PLURAL(RendExcludeNode),
  141. PLURAL(StrictEntryNode),
  142. PLURAL(StrictExitNode),
  143. PLURAL(StrictNode),
  144. { "l", "Log", 1, 0},
  145. { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
  146. { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
  147. { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
  148. { "BandwidthRateBytes", "BandwidthRate", 0, 0},
  149. { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
  150. { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
  151. { "DirServer", "DirAuthority", 0, 0}, /* XXXX later, make this warn? */
  152. { "MaxConn", "ConnLimit", 0, 1},
  153. { "MaxMemInCellQueues", "MaxMemInQueues", 0, 0},
  154. { "ORBindAddress", "ORListenAddress", 0, 0},
  155. { "DirBindAddress", "DirListenAddress", 0, 0},
  156. { "SocksBindAddress", "SocksListenAddress", 0, 0},
  157. { "UseHelperNodes", "UseEntryGuards", 0, 0},
  158. { "NumHelperNodes", "NumEntryGuards", 0, 0},
  159. { "UseEntryNodes", "UseEntryGuards", 0, 0},
  160. { "NumEntryNodes", "NumEntryGuards", 0, 0},
  161. { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
  162. { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
  163. { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0},
  164. { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
  165. { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
  166. { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
  167. { "VirtualAddrNetwork", "VirtualAddrNetworkIPv4", 0, 0},
  168. { NULL, NULL, 0, 0},
  169. };
  170. /** dummy instance of or_options_t, used for type-checking its
  171. * members with CONF_CHECK_VAR_TYPE. */
  172. DUMMY_TYPECHECK_INSTANCE(or_options_t);
  173. /** An entry for config_vars: "The option <b>name</b> has type
  174. * CONFIG_TYPE_<b>conftype</b>, and corresponds to
  175. * or_options_t.<b>member</b>"
  176. */
  177. #define VAR(name,conftype,member,initvalue) \
  178. { name, CONFIG_TYPE_ ## conftype, offsetof(or_options_t, member), \
  179. initvalue CONF_TEST_MEMBERS(or_options_t, conftype, member) }
  180. /** As VAR, but the option name and member name are the same. */
  181. #define V(member,conftype,initvalue) \
  182. VAR(#member, conftype, member, initvalue)
  183. /** An entry for config_vars: "The option <b>name</b> is obsolete." */
  184. #ifdef TOR_UNIT_TESTS
  185. #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL, {.INT=NULL} }
  186. #else
  187. #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
  188. #endif
  189. /**
  190. * Macro to declare *Port options. Each one comes in three entries.
  191. * For example, most users should use "SocksPort" to configure the
  192. * socks port, but TorBrowser wants to use __SocksPort so that it
  193. * isn't stored by SAVECONF. The SocksPortLines virtual option is
  194. * used to query both options from the controller.
  195. */
  196. #define VPORT(member) \
  197. VAR(#member "Lines", LINELIST_V, member ## _lines, NULL), \
  198. VAR(#member, LINELIST_S, member ## _lines, NULL), \
  199. VAR("__" #member, LINELIST_S, member ## _lines, NULL)
  200. /** Array of configuration options. Until we disallow nonstandard
  201. * abbreviations, order is significant, since the first matching option will
  202. * be chosen first.
  203. */
  204. static config_var_t option_vars_[] = {
  205. V(AccountingMax, MEMUNIT, "0 bytes"),
  206. VAR("AccountingRule", STRING, AccountingRule_option, "max"),
  207. V(AccountingStart, STRING, NULL),
  208. V(Address, STRING, NULL),
  209. OBSOLETE("AllowDotExit"),
  210. OBSOLETE("AllowInvalidNodes"),
  211. V(AllowNonRFC953Hostnames, BOOL, "0"),
  212. OBSOLETE("AllowSingleHopCircuits"),
  213. OBSOLETE("AllowSingleHopExits"),
  214. V(AlternateBridgeAuthority, LINELIST, NULL),
  215. V(AlternateDirAuthority, LINELIST, NULL),
  216. OBSOLETE("AlternateHSAuthority"),
  217. V(AssumeReachable, BOOL, "0"),
  218. OBSOLETE("AuthDirBadDir"),
  219. OBSOLETE("AuthDirBadDirCCs"),
  220. V(AuthDirBadExit, LINELIST, NULL),
  221. V(AuthDirBadExitCCs, CSV, ""),
  222. V(AuthDirInvalid, LINELIST, NULL),
  223. V(AuthDirInvalidCCs, CSV, ""),
  224. V(AuthDirFastGuarantee, MEMUNIT, "100 KB"),
  225. V(AuthDirGuardBWGuarantee, MEMUNIT, "2 MB"),
  226. V(AuthDirPinKeys, BOOL, "1"),
  227. V(AuthDirReject, LINELIST, NULL),
  228. V(AuthDirRejectCCs, CSV, ""),
  229. OBSOLETE("AuthDirRejectUnlisted"),
  230. OBSOLETE("AuthDirListBadDirs"),
  231. V(AuthDirListBadExits, BOOL, "0"),
  232. V(AuthDirMaxServersPerAddr, UINT, "2"),
  233. OBSOLETE("AuthDirMaxServersPerAuthAddr"),
  234. V(AuthDirHasIPv6Connectivity, BOOL, "0"),
  235. VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
  236. V(AutomapHostsOnResolve, BOOL, "0"),
  237. V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
  238. V(AvoidDiskWrites, BOOL, "0"),
  239. V(BandwidthBurst, MEMUNIT, "1 GB"),
  240. V(BandwidthRate, MEMUNIT, "1 GB"),
  241. V(BridgeAuthoritativeDir, BOOL, "0"),
  242. VAR("Bridge", LINELIST, Bridges, NULL),
  243. V(BridgePassword, STRING, NULL),
  244. V(BridgeRecordUsageByCountry, BOOL, "1"),
  245. V(BridgeRelay, BOOL, "0"),
  246. V(BridgeDistribution, STRING, NULL),
  247. VAR("CacheDirectory", FILENAME, CacheDirectory_option, NULL),
  248. V(CacheDirectoryGroupReadable, BOOL, "0"),
  249. V(CellStatistics, BOOL, "0"),
  250. V(PaddingStatistics, BOOL, "1"),
  251. V(LearnCircuitBuildTimeout, BOOL, "1"),
  252. V(CircuitBuildTimeout, INTERVAL, "0"),
  253. OBSOLETE("CircuitIdleTimeout"),
  254. V(CircuitsAvailableTimeout, INTERVAL, "0"),
  255. V(CircuitStreamTimeout, INTERVAL, "0"),
  256. V(CircuitPriorityHalflife, DOUBLE, "-100.0"), /*negative:'Use default'*/
  257. V(ClientDNSRejectInternalAddresses, BOOL,"1"),
  258. V(ClientOnly, BOOL, "0"),
  259. V(ClientPreferIPv6ORPort, AUTOBOOL, "auto"),
  260. V(ClientPreferIPv6DirPort, AUTOBOOL, "auto"),
  261. V(ClientRejectInternalAddresses, BOOL, "1"),
  262. V(ClientTransportPlugin, LINELIST, NULL),
  263. V(ClientUseIPv6, BOOL, "0"),
  264. V(ClientUseIPv4, BOOL, "1"),
  265. V(ConsensusParams, STRING, NULL),
  266. V(ConnLimit, UINT, "1000"),
  267. V(ConnDirectionStatistics, BOOL, "0"),
  268. V(ConstrainedSockets, BOOL, "0"),
  269. V(ConstrainedSockSize, MEMUNIT, "8192"),
  270. V(ContactInfo, STRING, NULL),
  271. OBSOLETE("ControlListenAddress"),
  272. VPORT(ControlPort),
  273. V(ControlPortFileGroupReadable,BOOL, "0"),
  274. V(ControlPortWriteToFile, FILENAME, NULL),
  275. V(ControlSocket, LINELIST, NULL),
  276. V(ControlSocketsGroupWritable, BOOL, "0"),
  277. V(SocksSocketsGroupWritable, BOOL, "0"),
  278. V(CookieAuthentication, BOOL, "0"),
  279. V(CookieAuthFileGroupReadable, BOOL, "0"),
  280. V(CookieAuthFile, STRING, NULL),
  281. V(CountPrivateBandwidth, BOOL, "0"),
  282. VAR("DataDirectory", FILENAME, DataDirectory_option, NULL),
  283. V(DataDirectoryGroupReadable, BOOL, "0"),
  284. V(DisableOOSCheck, BOOL, "1"),
  285. V(DisableNetwork, BOOL, "0"),
  286. V(DirAllowPrivateAddresses, BOOL, "0"),
  287. V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
  288. OBSOLETE("DirListenAddress"),
  289. V(DirPolicy, LINELIST, NULL),
  290. VPORT(DirPort),
  291. V(DirPortFrontPage, FILENAME, NULL),
  292. VAR("DirReqStatistics", BOOL, DirReqStatistics_option, "1"),
  293. VAR("DirAuthority", LINELIST, DirAuthorities, NULL),
  294. V(DirCache, BOOL, "1"),
  295. /* A DirAuthorityFallbackRate of 0.1 means that 0.5% of clients try an
  296. * authority when all fallbacks are up, and 2% try an authority when 25% of
  297. * fallbacks are down. (We rebuild the list when 25% of fallbacks are down).
  298. *
  299. * We want to reduce load on authorities, but keep these two figures within
  300. * an order of magnitude, so there isn't too much load shifting to
  301. * authorities when fallbacks go down. */
  302. V(DirAuthorityFallbackRate, DOUBLE, "0.1"),
  303. V(DisableAllSwap, BOOL, "0"),
  304. V(DisableDebuggerAttachment, BOOL, "1"),
  305. OBSOLETE("DisableIOCP"),
  306. OBSOLETE("DisableV2DirectoryInfo_"),
  307. OBSOLETE("DynamicDHGroups"),
  308. VPORT(DNSPort),
  309. OBSOLETE("DNSListenAddress"),
  310. /* DoS circuit creation options. */
  311. V(DoSCircuitCreationEnabled, AUTOBOOL, "auto"),
  312. V(DoSCircuitCreationMinConnections, UINT, "0"),
  313. V(DoSCircuitCreationRate, UINT, "0"),
  314. V(DoSCircuitCreationBurst, UINT, "0"),
  315. V(DoSCircuitCreationDefenseType, INT, "0"),
  316. V(DoSCircuitCreationDefenseTimePeriod, INTERVAL, "0"),
  317. /* DoS connection options. */
  318. V(DoSConnectionEnabled, AUTOBOOL, "auto"),
  319. V(DoSConnectionMaxConcurrentCount, UINT, "0"),
  320. V(DoSConnectionDefenseType, INT, "0"),
  321. /* DoS single hop client options. */
  322. V(DoSRefuseSingleHopClientRendezvous, AUTOBOOL, "auto"),
  323. V(DownloadExtraInfo, BOOL, "0"),
  324. V(TestingEnableConnBwEvent, BOOL, "0"),
  325. V(TestingEnableCellStatsEvent, BOOL, "0"),
  326. V(TestingEnableTbEmptyEvent, BOOL, "0"),
  327. V(EnforceDistinctSubnets, BOOL, "1"),
  328. V(EntryNodes, ROUTERSET, NULL),
  329. V(EntryStatistics, BOOL, "0"),
  330. V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
  331. V(ExcludeNodes, ROUTERSET, NULL),
  332. V(ExcludeExitNodes, ROUTERSET, NULL),
  333. OBSOLETE("ExcludeSingleHopRelays"),
  334. V(ExitNodes, ROUTERSET, NULL),
  335. V(ExitPolicy, LINELIST, NULL),
  336. V(ExitPolicyRejectPrivate, BOOL, "1"),
  337. V(ExitPolicyRejectLocalInterfaces, BOOL, "0"),
  338. V(ExitPortStatistics, BOOL, "0"),
  339. V(ExtendAllowPrivateAddresses, BOOL, "0"),
  340. V(ExitRelay, AUTOBOOL, "auto"),
  341. VPORT(ExtORPort),
  342. V(ExtORPortCookieAuthFile, STRING, NULL),
  343. V(ExtORPortCookieAuthFileGroupReadable, BOOL, "0"),
  344. V(ExtraInfoStatistics, BOOL, "1"),
  345. V(ExtendByEd25519ID, AUTOBOOL, "auto"),
  346. V(FallbackDir, LINELIST, NULL),
  347. V(UseDefaultFallbackDirs, BOOL, "1"),
  348. OBSOLETE("FallbackNetworkstatusFile"),
  349. V(FascistFirewall, BOOL, "0"),
  350. V(FirewallPorts, CSV, ""),
  351. OBSOLETE("FastFirstHopPK"),
  352. V(FetchDirInfoEarly, BOOL, "0"),
  353. V(FetchDirInfoExtraEarly, BOOL, "0"),
  354. V(FetchServerDescriptors, BOOL, "1"),
  355. V(FetchHidServDescriptors, BOOL, "1"),
  356. V(FetchUselessDescriptors, BOOL, "0"),
  357. OBSOLETE("FetchV2Networkstatus"),
  358. V(GeoIPExcludeUnknown, AUTOBOOL, "auto"),
  359. #ifdef _WIN32
  360. V(GeoIPFile, FILENAME, "<default>"),
  361. V(GeoIPv6File, FILENAME, "<default>"),
  362. #else
  363. V(GeoIPFile, FILENAME,
  364. SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
  365. V(GeoIPv6File, FILENAME,
  366. SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip6"),
  367. #endif /* defined(_WIN32) */
  368. OBSOLETE("Group"),
  369. V(GuardLifetime, INTERVAL, "0 minutes"),
  370. V(HardwareAccel, BOOL, "0"),
  371. V(HeartbeatPeriod, INTERVAL, "6 hours"),
  372. V(MainloopStats, BOOL, "0"),
  373. V(AccelName, STRING, NULL),
  374. V(AccelDir, FILENAME, NULL),
  375. V(HashedControlPassword, LINELIST, NULL),
  376. OBSOLETE("HidServDirectoryV2"),
  377. VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
  378. VAR("HiddenServiceDirGroupReadable", LINELIST_S, RendConfigLines, NULL),
  379. VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
  380. VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
  381. VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
  382. VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
  383. VAR("HiddenServiceAllowUnknownPorts",LINELIST_S, RendConfigLines, NULL),
  384. VAR("HiddenServiceMaxStreams",LINELIST_S, RendConfigLines, NULL),
  385. VAR("HiddenServiceMaxStreamsCloseCircuit",LINELIST_S, RendConfigLines, NULL),
  386. VAR("HiddenServiceNumIntroductionPoints", LINELIST_S, RendConfigLines, NULL),
  387. VAR("HiddenServiceStatistics", BOOL, HiddenServiceStatistics_option, "1"),
  388. V(HidServAuth, LINELIST, NULL),
  389. OBSOLETE("CloseHSClientCircuitsImmediatelyOnTimeout"),
  390. OBSOLETE("CloseHSServiceRendCircuitsImmediatelyOnTimeout"),
  391. V(HiddenServiceSingleHopMode, BOOL, "0"),
  392. V(HiddenServiceNonAnonymousMode,BOOL, "0"),
  393. V(HTTPProxy, STRING, NULL),
  394. V(HTTPProxyAuthenticator, STRING, NULL),
  395. V(HTTPSProxy, STRING, NULL),
  396. V(HTTPSProxyAuthenticator, STRING, NULL),
  397. VPORT(HTTPTunnelPort),
  398. V(IPv6Exit, BOOL, "0"),
  399. VAR("ServerTransportPlugin", LINELIST, ServerTransportPlugin, NULL),
  400. V(ServerTransportListenAddr, LINELIST, NULL),
  401. V(ServerTransportOptions, LINELIST, NULL),
  402. V(SigningKeyLifetime, INTERVAL, "30 days"),
  403. V(Socks4Proxy, STRING, NULL),
  404. V(Socks5Proxy, STRING, NULL),
  405. V(Socks5ProxyUsername, STRING, NULL),
  406. V(Socks5ProxyPassword, STRING, NULL),
  407. VAR("KeyDirectory", FILENAME, KeyDirectory_option, NULL),
  408. V(KeyDirectoryGroupReadable, BOOL, "0"),
  409. VAR("_HSLayer2Nodes", ROUTERSET, HSLayer2Nodes, NULL),
  410. VAR("_HSLayer3Nodes", ROUTERSET, HSLayer3Nodes, NULL),
  411. V(KeepalivePeriod, INTERVAL, "5 minutes"),
  412. V(KeepBindCapabilities, AUTOBOOL, "auto"),
  413. VAR("Log", LINELIST, Logs, NULL),
  414. V(LogMessageDomains, BOOL, "0"),
  415. V(LogTimeGranularity, MSEC_INTERVAL, "1 second"),
  416. V(TruncateLogFile, BOOL, "0"),
  417. V(SyslogIdentityTag, STRING, NULL),
  418. V(AndroidIdentityTag, STRING, NULL),
  419. V(LongLivedPorts, CSV,
  420. "21,22,706,1863,5050,5190,5222,5223,6523,6667,6697,8300"),
  421. VAR("MapAddress", LINELIST, AddressMap, NULL),
  422. V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
  423. V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
  424. V(MaxClientCircuitsPending, UINT, "32"),
  425. V(MaxConsensusAgeForDiffs, INTERVAL, "0 seconds"),
  426. VAR("MaxMemInQueues", MEMUNIT, MaxMemInQueues_raw, "0"),
  427. OBSOLETE("MaxOnionsPending"),
  428. V(MaxOnionQueueDelay, MSEC_INTERVAL, "1750 msec"),
  429. V(MaxUnparseableDescSizeToLog, MEMUNIT, "10 MB"),
  430. V(MinMeasuredBWsForAuthToIgnoreAdvertised, INT, "500"),
  431. VAR("MyFamily", LINELIST, MyFamily_lines, NULL),
  432. V(NewCircuitPeriod, INTERVAL, "30 seconds"),
  433. OBSOLETE("NamingAuthoritativeDirectory"),
  434. OBSOLETE("NATDListenAddress"),
  435. VPORT(NATDPort),
  436. V(Nickname, STRING, NULL),
  437. OBSOLETE("PredictedPortsRelevanceTime"),
  438. OBSOLETE("WarnUnsafeSocks"),
  439. VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
  440. V(NoExec, BOOL, "0"),
  441. V(NumCPUs, UINT, "0"),
  442. V(NumDirectoryGuards, UINT, "0"),
  443. V(NumEntryGuards, UINT, "0"),
  444. V(OfflineMasterKey, BOOL, "0"),
  445. OBSOLETE("ORListenAddress"),
  446. VPORT(ORPort),
  447. V(OutboundBindAddress, LINELIST, NULL),
  448. V(OutboundBindAddressOR, LINELIST, NULL),
  449. V(OutboundBindAddressExit, LINELIST, NULL),
  450. OBSOLETE("PathBiasDisableRate"),
  451. V(PathBiasCircThreshold, INT, "-1"),
  452. V(PathBiasNoticeRate, DOUBLE, "-1"),
  453. V(PathBiasWarnRate, DOUBLE, "-1"),
  454. V(PathBiasExtremeRate, DOUBLE, "-1"),
  455. V(PathBiasScaleThreshold, INT, "-1"),
  456. OBSOLETE("PathBiasScaleFactor"),
  457. OBSOLETE("PathBiasMultFactor"),
  458. V(PathBiasDropGuards, AUTOBOOL, "0"),
  459. OBSOLETE("PathBiasUseCloseCounts"),
  460. V(PathBiasUseThreshold, INT, "-1"),
  461. V(PathBiasNoticeUseRate, DOUBLE, "-1"),
  462. V(PathBiasExtremeUseRate, DOUBLE, "-1"),
  463. V(PathBiasScaleUseThreshold, INT, "-1"),
  464. V(PathsNeededToBuildCircuits, DOUBLE, "-1"),
  465. V(PerConnBWBurst, MEMUNIT, "0"),
  466. V(PerConnBWRate, MEMUNIT, "0"),
  467. V(PidFile, STRING, NULL),
  468. V(TestingTorNetwork, BOOL, "0"),
  469. V(TestingMinExitFlagThreshold, MEMUNIT, "0"),
  470. V(TestingMinFastFlagThreshold, MEMUNIT, "0"),
  471. V(TestingLinkCertLifetime, INTERVAL, "2 days"),
  472. V(TestingAuthKeyLifetime, INTERVAL, "2 days"),
  473. V(TestingLinkKeySlop, INTERVAL, "3 hours"),
  474. V(TestingAuthKeySlop, INTERVAL, "3 hours"),
  475. V(TestingSigningKeySlop, INTERVAL, "1 day"),
  476. V(OptimisticData, AUTOBOOL, "auto"),
  477. V(PortForwarding, BOOL, "0"),
  478. V(PortForwardingHelper, FILENAME, "tor-fw-helper"),
  479. OBSOLETE("PreferTunneledDirConns"),
  480. V(ProtocolWarnings, BOOL, "0"),
  481. V(PublishServerDescriptor, CSV, "1"),
  482. V(PublishHidServDescriptors, BOOL, "1"),
  483. V(ReachableAddresses, LINELIST, NULL),
  484. V(ReachableDirAddresses, LINELIST, NULL),
  485. V(ReachableORAddresses, LINELIST, NULL),
  486. V(RecommendedVersions, LINELIST, NULL),
  487. V(RecommendedClientVersions, LINELIST, NULL),
  488. V(RecommendedServerVersions, LINELIST, NULL),
  489. V(RecommendedPackages, LINELIST, NULL),
  490. V(ReducedConnectionPadding, BOOL, "0"),
  491. V(ConnectionPadding, AUTOBOOL, "auto"),
  492. V(RefuseUnknownExits, AUTOBOOL, "auto"),
  493. V(RejectPlaintextPorts, CSV, ""),
  494. V(RelayBandwidthBurst, MEMUNIT, "0"),
  495. V(RelayBandwidthRate, MEMUNIT, "0"),
  496. V(RendPostPeriod, INTERVAL, "1 hour"),
  497. V(RephistTrackTime, INTERVAL, "24 hours"),
  498. V(RunAsDaemon, BOOL, "0"),
  499. V(ReducedExitPolicy, BOOL, "0"),
  500. OBSOLETE("RunTesting"), // currently unused
  501. V(Sandbox, BOOL, "0"),
  502. V(SafeLogging, STRING, "1"),
  503. V(SafeSocks, BOOL, "0"),
  504. V(ServerDNSAllowBrokenConfig, BOOL, "1"),
  505. V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
  506. V(ServerDNSDetectHijacking, BOOL, "1"),
  507. V(ServerDNSRandomizeCase, BOOL, "1"),
  508. V(ServerDNSResolvConfFile, STRING, NULL),
  509. V(ServerDNSSearchDomains, BOOL, "0"),
  510. V(ServerDNSTestAddresses, CSV,
  511. "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
  512. OBSOLETE("SchedulerLowWaterMark__"),
  513. OBSOLETE("SchedulerHighWaterMark__"),
  514. OBSOLETE("SchedulerMaxFlushCells__"),
  515. V(KISTSchedRunInterval, MSEC_INTERVAL, "0 msec"),
  516. V(KISTSockBufSizeFactor, DOUBLE, "1.0"),
  517. V(Schedulers, CSV, "KIST,KISTLite,Vanilla"),
  518. V(ShutdownWaitLength, INTERVAL, "30 seconds"),
  519. OBSOLETE("SocksListenAddress"),
  520. V(SocksPolicy, LINELIST, NULL),
  521. VPORT(SocksPort),
  522. V(SocksTimeout, INTERVAL, "2 minutes"),
  523. V(SSLKeyLifetime, INTERVAL, "0"),
  524. OBSOLETE("StrictEntryNodes"),
  525. OBSOLETE("StrictExitNodes"),
  526. V(StrictNodes, BOOL, "0"),
  527. OBSOLETE("Support022HiddenServices"),
  528. V(TestSocks, BOOL, "0"),
  529. V(TokenBucketRefillInterval, MSEC_INTERVAL, "100 msec"),
  530. V(Tor2webMode, BOOL, "0"),
  531. V(Tor2webRendezvousPoints, ROUTERSET, NULL),
  532. OBSOLETE("TLSECGroup"),
  533. V(TrackHostExits, CSV, NULL),
  534. V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
  535. OBSOLETE("TransListenAddress"),
  536. VPORT(TransPort),
  537. V(TransProxyType, STRING, "default"),
  538. OBSOLETE("TunnelDirConns"),
  539. V(UpdateBridgesFromAuthority, BOOL, "0"),
  540. V(UseBridges, BOOL, "0"),
  541. VAR("UseEntryGuards", BOOL, UseEntryGuards_option, "1"),
  542. OBSOLETE("UseEntryGuardsAsDirGuards"),
  543. V(UseGuardFraction, AUTOBOOL, "auto"),
  544. V(UseMicrodescriptors, AUTOBOOL, "auto"),
  545. OBSOLETE("UseNTorHandshake"),
  546. V(User, STRING, NULL),
  547. OBSOLETE("UserspaceIOCPBuffers"),
  548. V(AuthDirSharedRandomness, BOOL, "1"),
  549. V(AuthDirTestEd25519LinkKeys, BOOL, "1"),
  550. OBSOLETE("V1AuthoritativeDirectory"),
  551. OBSOLETE("V2AuthoritativeDirectory"),
  552. VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
  553. V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
  554. V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
  555. V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
  556. V(TestingV3AuthVotingStartOffset, INTERVAL, "0"),
  557. V(V3AuthVotingInterval, INTERVAL, "1 hour"),
  558. V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
  559. V(V3AuthDistDelay, INTERVAL, "5 minutes"),
  560. V(V3AuthNIntervalsValid, UINT, "3"),
  561. V(V3AuthUseLegacyKey, BOOL, "0"),
  562. V(V3BandwidthsFile, FILENAME, NULL),
  563. V(GuardfractionFile, FILENAME, NULL),
  564. VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
  565. OBSOLETE("VoteOnHidServDirectoriesV2"),
  566. V(VirtualAddrNetworkIPv4, STRING, "127.192.0.0/10"),
  567. V(VirtualAddrNetworkIPv6, STRING, "[FE80::]/10"),
  568. V(WarnPlaintextPorts, CSV, "23,109,110,143"),
  569. OBSOLETE("UseFilteringSSLBufferevents"),
  570. OBSOLETE("__UseFilteringSSLBufferevents"),
  571. VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
  572. VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
  573. VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
  574. VAR("__DisableSignalHandlers", BOOL, DisableSignalHandlers, "0"),
  575. VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
  576. VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
  577. NULL),
  578. VAR("__OwningControllerProcess",STRING,OwningControllerProcess, NULL),
  579. VAR("__OwningControllerFD",INT,OwningControllerFD, "-1"),
  580. V(MinUptimeHidServDirectoryV2, INTERVAL, "96 hours"),
  581. V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 60, 60, 120, "
  582. "300, 900, 2147483647"),
  583. V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 60, 300, 600, "
  584. "2147483647"),
  585. V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
  586. "300, 600, 1800, 1800, 1800, 1800, "
  587. "1800, 3600, 7200"),
  588. V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 60, "
  589. "300, 600, 1800, 3600, 3600, 3600, "
  590. "10800, 21600, 43200"),
  591. /* With the ClientBootstrapConsensus*Download* below:
  592. * Clients with only authorities will try:
  593. * - at least 3 authorities over 10 seconds, then exponentially backoff,
  594. * with the next attempt 3-21 seconds later,
  595. * Clients with authorities and fallbacks will try:
  596. * - at least 2 authorities and 4 fallbacks over 21 seconds, then
  597. * exponentially backoff, with the next attempts 4-33 seconds later,
  598. * Clients will also retry when an application request arrives.
  599. * After a number of failed requests, clients retry every 3 days + 1 hour.
  600. *
  601. * Clients used to try 2 authorities over 10 seconds, then wait for
  602. * 60 minutes or an application request.
  603. *
  604. * When clients have authorities and fallbacks available, they use these
  605. * schedules: (we stagger the times to avoid thundering herds) */
  606. V(ClientBootstrapConsensusAuthorityDownloadSchedule, CSV_INTERVAL,
  607. "6, 11, 3600, 10800, 25200, 54000, 111600, 262800" /* 3 days + 1 hour */),
  608. V(ClientBootstrapConsensusFallbackDownloadSchedule, CSV_INTERVAL,
  609. "0, 1, 4, 11, 3600, 10800, 25200, 54000, 111600, 262800"),
  610. /* When clients only have authorities available, they use this schedule: */
  611. V(ClientBootstrapConsensusAuthorityOnlyDownloadSchedule, CSV_INTERVAL,
  612. "0, 3, 7, 3600, 10800, 25200, 54000, 111600, 262800"),
  613. /* We don't want to overwhelm slow networks (or mirrors whose replies are
  614. * blocked), but we also don't want to fail if only some mirrors are
  615. * blackholed. Clients will try 3 directories simultaneously.
  616. * (Relays never use simultaneous connections.) */
  617. V(ClientBootstrapConsensusMaxInProgressTries, UINT, "3"),
  618. /* When a client has any running bridges, check each bridge occasionally,
  619. * whether or not that bridge is actually up. */
  620. V(TestingBridgeDownloadSchedule, CSV_INTERVAL,
  621. "10800, 25200, 54000, 111600, 262800"),
  622. /* When a client is just starting, or has no running bridges, check each
  623. * bridge a few times quickly, and then try again later. These schedules
  624. * are much longer than the other schedules, because we try each and every
  625. * configured bridge with this schedule. */
  626. V(TestingBridgeBootstrapDownloadSchedule, CSV_INTERVAL,
  627. "0, 30, 90, 600, 3600, 10800, 25200, 54000, 111600, 262800"),
  628. V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "10 minutes"),
  629. V(TestingDirConnectionMaxStall, INTERVAL, "5 minutes"),
  630. V(TestingConsensusMaxDownloadTries, UINT, "8"),
  631. /* Since we try connections rapidly and simultaneously, we can afford
  632. * to give up earlier. (This protects against overloading directories.) */
  633. V(ClientBootstrapConsensusMaxDownloadTries, UINT, "7"),
  634. /* We want to give up much earlier if we're only using authorities. */
  635. V(ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries, UINT, "4"),
  636. V(TestingDescriptorMaxDownloadTries, UINT, "8"),
  637. V(TestingMicrodescMaxDownloadTries, UINT, "8"),
  638. V(TestingCertMaxDownloadTries, UINT, "8"),
  639. V(TestingDirAuthVoteExit, ROUTERSET, NULL),
  640. V(TestingDirAuthVoteExitIsStrict, BOOL, "0"),
  641. V(TestingDirAuthVoteGuard, ROUTERSET, NULL),
  642. V(TestingDirAuthVoteGuardIsStrict, BOOL, "0"),
  643. V(TestingDirAuthVoteHSDir, ROUTERSET, NULL),
  644. V(TestingDirAuthVoteHSDirIsStrict, BOOL, "0"),
  645. VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "0"),
  646. END_OF_CONFIG_VARS
  647. };
  648. /** Override default values with these if the user sets the TestingTorNetwork
  649. * option. */
  650. static const config_var_t testing_tor_network_defaults[] = {
  651. V(DirAllowPrivateAddresses, BOOL, "1"),
  652. V(EnforceDistinctSubnets, BOOL, "0"),
  653. V(AssumeReachable, BOOL, "1"),
  654. V(AuthDirMaxServersPerAddr, UINT, "0"),
  655. V(ClientBootstrapConsensusAuthorityDownloadSchedule, CSV_INTERVAL,
  656. "0, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
  657. V(ClientBootstrapConsensusFallbackDownloadSchedule, CSV_INTERVAL,
  658. "0, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
  659. V(ClientBootstrapConsensusAuthorityOnlyDownloadSchedule, CSV_INTERVAL,
  660. "0, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 16, 32, 60"),
  661. V(ClientBootstrapConsensusMaxDownloadTries, UINT, "80"),
  662. V(ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries, UINT, "80"),
  663. V(ClientDNSRejectInternalAddresses, BOOL,"0"),
  664. V(ClientRejectInternalAddresses, BOOL, "0"),
  665. V(CountPrivateBandwidth, BOOL, "1"),
  666. V(ExitPolicyRejectPrivate, BOOL, "0"),
  667. V(ExtendAllowPrivateAddresses, BOOL, "1"),
  668. V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
  669. V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
  670. V(V3AuthDistDelay, INTERVAL, "20 seconds"),
  671. V(TestingV3AuthInitialVotingInterval, INTERVAL, "150 seconds"),
  672. V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
  673. V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
  674. V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
  675. V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
  676. V(MinUptimeHidServDirectoryV2, INTERVAL, "0 minutes"),
  677. V(TestingServerDownloadSchedule, CSV_INTERVAL, "0, 0, 0, 5, 10, 15, "
  678. "20, 30, 60"),
  679. V(TestingClientDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, 15, 20, "
  680. "30, 60"),
  681. V(TestingServerConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
  682. "15, 20, 30, 60"),
  683. V(TestingClientConsensusDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
  684. "15, 20, 30, 60"),
  685. V(TestingBridgeDownloadSchedule, CSV_INTERVAL, "10, 30, 60"),
  686. V(TestingBridgeBootstrapDownloadSchedule, CSV_INTERVAL, "0, 0, 5, 10, "
  687. "15, 20, 30, 60"),
  688. V(TestingClientMaxIntervalWithoutRequest, INTERVAL, "5 seconds"),
  689. V(TestingDirConnectionMaxStall, INTERVAL, "30 seconds"),
  690. V(TestingConsensusMaxDownloadTries, UINT, "80"),
  691. V(TestingDescriptorMaxDownloadTries, UINT, "80"),
  692. V(TestingMicrodescMaxDownloadTries, UINT, "80"),
  693. V(TestingCertMaxDownloadTries, UINT, "80"),
  694. V(TestingEnableConnBwEvent, BOOL, "1"),
  695. V(TestingEnableCellStatsEvent, BOOL, "1"),
  696. V(TestingEnableTbEmptyEvent, BOOL, "1"),
  697. VAR("___UsingTestNetworkDefaults", BOOL, UsingTestNetworkDefaults_, "1"),
  698. V(RendPostPeriod, INTERVAL, "2 minutes"),
  699. END_OF_CONFIG_VARS
  700. };
  701. #undef VAR
  702. #undef V
  703. #undef OBSOLETE
  704. static const config_deprecation_t option_deprecation_notes_[] = {
  705. /* Deprecated since 0.3.2.0-alpha. */
  706. { "HTTPProxy", "It only applies to direct unencrypted HTTP connections "
  707. "to your directory server, which your Tor probably wasn't using." },
  708. { "HTTPProxyAuthenticator", "HTTPProxy is deprecated in favor of HTTPSProxy "
  709. "which should be used with HTTPSProxyAuthenticator." },
  710. /* End of options deprecated since 0.3.2.1-alpha */
  711. /* Options deprecated since 0.3.2.2-alpha */
  712. { "ReachableDirAddresses", "It has no effect on relays, and has had no "
  713. "effect on clients since 0.2.8." },
  714. { "ClientPreferIPv6DirPort", "It has no effect on relays, and has had no "
  715. "effect on clients since 0.2.8." },
  716. /* End of options deprecated since 0.3.2.2-alpha. */
  717. { NULL, NULL }
  718. };
  719. #ifdef _WIN32
  720. static char *get_windows_conf_root(void);
  721. #endif
  722. static int options_act_reversible(const or_options_t *old_options, char **msg);
  723. static int options_transition_allowed(const or_options_t *old,
  724. const or_options_t *new,
  725. char **msg);
  726. static int options_transition_affects_workers(
  727. const or_options_t *old_options, const or_options_t *new_options);
  728. static int options_transition_affects_descriptor(
  729. const or_options_t *old_options, const or_options_t *new_options);
  730. static int normalize_nickname_list(config_line_t **normalized_out,
  731. const config_line_t *lst, const char *name,
  732. char **msg);
  733. static char *get_bindaddr_from_transport_listen_line(const char *line,
  734. const char *transport);
  735. static int parse_ports(or_options_t *options, int validate_only,
  736. char **msg_out, int *n_ports_out,
  737. int *world_writable_control_socket);
  738. static int check_server_ports(const smartlist_t *ports,
  739. const or_options_t *options,
  740. int *num_low_ports_out);
  741. static int validate_data_directories(or_options_t *options);
  742. static int write_configuration_file(const char *fname,
  743. const or_options_t *options);
  744. static int options_init_logs(const or_options_t *old_options,
  745. or_options_t *options, int validate_only);
  746. static void init_libevent(const or_options_t *options);
  747. static int opt_streq(const char *s1, const char *s2);
  748. static int parse_outbound_addresses(or_options_t *options, int validate_only,
  749. char **msg);
  750. static void config_maybe_load_geoip_files_(const or_options_t *options,
  751. const or_options_t *old_options);
  752. static int options_validate_cb(void *old_options, void *options,
  753. void *default_options,
  754. int from_setconf, char **msg);
  755. static uint64_t compute_real_max_mem_in_queues(const uint64_t val,
  756. int log_guess);
  757. static void cleanup_protocol_warning_severity_level(void);
  758. static void set_protocol_warning_severity_level(int warning_severity);
  759. /** Magic value for or_options_t. */
  760. #define OR_OPTIONS_MAGIC 9090909
  761. /** Configuration format for or_options_t. */
  762. STATIC config_format_t options_format = {
  763. sizeof(or_options_t),
  764. OR_OPTIONS_MAGIC,
  765. offsetof(or_options_t, magic_),
  766. option_abbrevs_,
  767. option_deprecation_notes_,
  768. option_vars_,
  769. options_validate_cb,
  770. NULL
  771. };
  772. /*
  773. * Functions to read and write the global options pointer.
  774. */
  775. /** Command-line and config-file options. */
  776. static or_options_t *global_options = NULL;
  777. /** The fallback options_t object; this is where we look for options not
  778. * in torrc before we fall back to Tor's defaults. */
  779. static or_options_t *global_default_options = NULL;
  780. /** Name of most recently read torrc file. */
  781. static char *torrc_fname = NULL;
  782. /** Name of the most recently read torrc-defaults file.*/
  783. static char *torrc_defaults_fname = NULL;
  784. /** Configuration options set by command line. */
  785. static config_line_t *global_cmdline_options = NULL;
  786. /** Non-configuration options set by the command line */
  787. static config_line_t *global_cmdline_only_options = NULL;
  788. /** Boolean: Have we parsed the command line? */
  789. static int have_parsed_cmdline = 0;
  790. /** Contents of most recently read DirPortFrontPage file. */
  791. static char *global_dirfrontpagecontents = NULL;
  792. /** List of port_cfg_t for all configured ports. */
  793. static smartlist_t *configured_ports = NULL;
  794. /** True iff we're currently validating options, and any calls to
  795. * get_options() are likely to be bugs. */
  796. static int in_option_validation = 0;
  797. /* True iff we've initialized libevent */
  798. static int libevent_initialized = 0;
  799. /** Return the contents of our frontpage string, or NULL if not configured. */
  800. MOCK_IMPL(const char*,
  801. get_dirportfrontpage, (void))
  802. {
  803. return global_dirfrontpagecontents;
  804. }
  805. /** Returns the currently configured options. */
  806. MOCK_IMPL(or_options_t *,
  807. get_options_mutable, (void))
  808. {
  809. tor_assert(global_options);
  810. tor_assert_nonfatal(! in_option_validation);
  811. return global_options;
  812. }
  813. /** Returns the currently configured options */
  814. MOCK_IMPL(const or_options_t *,
  815. get_options,(void))
  816. {
  817. return get_options_mutable();
  818. }
  819. /** Change the current global options to contain <b>new_val</b> instead of
  820. * their current value; take action based on the new value; free the old value
  821. * as necessary. Returns 0 on success, -1 on failure.
  822. */
  823. int
  824. set_options(or_options_t *new_val, char **msg)
  825. {
  826. int i;
  827. smartlist_t *elements;
  828. config_line_t *line;
  829. or_options_t *old_options = global_options;
  830. global_options = new_val;
  831. /* Note that we pass the *old* options below, for comparison. It
  832. * pulls the new options directly out of global_options. */
  833. if (options_act_reversible(old_options, msg)<0) {
  834. tor_assert(*msg);
  835. global_options = old_options;
  836. return -1;
  837. }
  838. if (options_act(old_options) < 0) { /* acting on the options failed. die. */
  839. if (! tor_event_loop_shutdown_is_pending()) {
  840. log_err(LD_BUG,
  841. "Acting on config options left us in a broken state. Dying.");
  842. tor_shutdown_event_loop_and_exit(1);
  843. }
  844. return -1;
  845. }
  846. /* Issues a CONF_CHANGED event to notify controller of the change. If Tor is
  847. * just starting up then the old_options will be undefined. */
  848. if (old_options && old_options != global_options) {
  849. elements = smartlist_new();
  850. for (i=0; options_format.vars[i].name; ++i) {
  851. const config_var_t *var = &options_format.vars[i];
  852. const char *var_name = var->name;
  853. if (var->type == CONFIG_TYPE_LINELIST_S ||
  854. var->type == CONFIG_TYPE_OBSOLETE) {
  855. continue;
  856. }
  857. if (!config_is_same(&options_format, new_val, old_options, var_name)) {
  858. line = config_get_assigned_option(&options_format, new_val,
  859. var_name, 1);
  860. if (line) {
  861. config_line_t *next;
  862. for (; line; line = next) {
  863. next = line->next;
  864. smartlist_add(elements, line->key);
  865. smartlist_add(elements, line->value);
  866. tor_free(line);
  867. }
  868. } else {
  869. smartlist_add_strdup(elements, options_format.vars[i].name);
  870. smartlist_add(elements, NULL);
  871. }
  872. }
  873. }
  874. control_event_conf_changed(elements);
  875. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  876. smartlist_free(elements);
  877. }
  878. if (old_options != global_options)
  879. or_options_free(old_options);
  880. return 0;
  881. }
  882. /** The version of this Tor process, as parsed. */
  883. static char *the_tor_version = NULL;
  884. /** A shorter version of this Tor process's version, for export in our router
  885. * descriptor. (Does not include the git version, if any.) */
  886. static char *the_short_tor_version = NULL;
  887. /** Return the current Tor version. */
  888. const char *
  889. get_version(void)
  890. {
  891. if (the_tor_version == NULL) {
  892. if (strlen(tor_git_revision)) {
  893. tor_asprintf(&the_tor_version, "%s (git-%s)", get_short_version(),
  894. tor_git_revision);
  895. } else {
  896. the_tor_version = tor_strdup(get_short_version());
  897. }
  898. }
  899. return the_tor_version;
  900. }
  901. /** Return the current Tor version, without any git tag. */
  902. const char *
  903. get_short_version(void)
  904. {
  905. if (the_short_tor_version == NULL) {
  906. #ifdef TOR_BUILD_TAG
  907. tor_asprintf(&the_short_tor_version, "%s (%s)", VERSION, TOR_BUILD_TAG);
  908. #else
  909. the_short_tor_version = tor_strdup(VERSION);
  910. #endif
  911. }
  912. return the_short_tor_version;
  913. }
  914. /** Release additional memory allocated in options
  915. */
  916. STATIC void
  917. or_options_free_(or_options_t *options)
  918. {
  919. if (!options)
  920. return;
  921. routerset_free(options->ExcludeExitNodesUnion_);
  922. if (options->NodeFamilySets) {
  923. SMARTLIST_FOREACH(options->NodeFamilySets, routerset_t *,
  924. rs, routerset_free(rs));
  925. smartlist_free(options->NodeFamilySets);
  926. }
  927. if (options->SchedulerTypes_) {
  928. SMARTLIST_FOREACH(options->SchedulerTypes_, int *, i, tor_free(i));
  929. smartlist_free(options->SchedulerTypes_);
  930. }
  931. if (options->FilesOpenedByIncludes) {
  932. SMARTLIST_FOREACH(options->FilesOpenedByIncludes, char *, f, tor_free(f));
  933. smartlist_free(options->FilesOpenedByIncludes);
  934. }
  935. tor_free(options->DataDirectory);
  936. tor_free(options->CacheDirectory);
  937. tor_free(options->KeyDirectory);
  938. tor_free(options->BridgePassword_AuthDigest_);
  939. tor_free(options->command_arg);
  940. tor_free(options->master_key_fname);
  941. config_free_lines(options->MyFamily);
  942. config_free(&options_format, options);
  943. }
  944. /** Release all memory and resources held by global configuration structures.
  945. */
  946. void
  947. config_free_all(void)
  948. {
  949. or_options_free(global_options);
  950. global_options = NULL;
  951. or_options_free(global_default_options);
  952. global_default_options = NULL;
  953. config_free_lines(global_cmdline_options);
  954. global_cmdline_options = NULL;
  955. config_free_lines(global_cmdline_only_options);
  956. global_cmdline_only_options = NULL;
  957. if (configured_ports) {
  958. SMARTLIST_FOREACH(configured_ports,
  959. port_cfg_t *, p, port_cfg_free(p));
  960. smartlist_free(configured_ports);
  961. configured_ports = NULL;
  962. }
  963. tor_free(torrc_fname);
  964. tor_free(torrc_defaults_fname);
  965. tor_free(global_dirfrontpagecontents);
  966. tor_free(the_short_tor_version);
  967. tor_free(the_tor_version);
  968. cleanup_protocol_warning_severity_level();
  969. have_parsed_cmdline = 0;
  970. libevent_initialized = 0;
  971. }
  972. /** Make <b>address</b> -- a piece of information related to our operation as
  973. * a client -- safe to log according to the settings in options->SafeLogging,
  974. * and return it.
  975. *
  976. * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
  977. */
  978. const char *
  979. safe_str_client(const char *address)
  980. {
  981. tor_assert(address);
  982. if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
  983. return "[scrubbed]";
  984. else
  985. return address;
  986. }
  987. /** Make <b>address</b> -- a piece of information of unspecified sensitivity
  988. * -- safe to log according to the settings in options->SafeLogging, and
  989. * return it.
  990. *
  991. * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
  992. * otherwise.)
  993. */
  994. const char *
  995. safe_str(const char *address)
  996. {
  997. tor_assert(address);
  998. if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
  999. return "[scrubbed]";
  1000. else
  1001. return address;
  1002. }
  1003. /** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
  1004. * escaped(): don't use this outside the main thread, or twice in the same
  1005. * log statement. */
  1006. const char *
  1007. escaped_safe_str_client(const char *address)
  1008. {
  1009. if (get_options()->SafeLogging_ == SAFELOG_SCRUB_ALL)
  1010. return "[scrubbed]";
  1011. else
  1012. return escaped(address);
  1013. }
  1014. /** Equivalent to escaped(safe_str(address)). See reentrancy note on
  1015. * escaped(): don't use this outside the main thread, or twice in the same
  1016. * log statement. */
  1017. const char *
  1018. escaped_safe_str(const char *address)
  1019. {
  1020. if (get_options()->SafeLogging_ != SAFELOG_SCRUB_NONE)
  1021. return "[scrubbed]";
  1022. else
  1023. return escaped(address);
  1024. }
  1025. /**
  1026. * The severity level that should be used for warnings of severity
  1027. * LOG_PROTOCOL_WARN.
  1028. *
  1029. * We keep this outside the options, and we use an atomic_counter_t, in case
  1030. * one thread needs to use LOG_PROTOCOL_WARN while an option transition is
  1031. * happening in the main thread.
  1032. */
  1033. static atomic_counter_t protocol_warning_severity_level;
  1034. /** Return the severity level that should be used for warnings of severity
  1035. * LOG_PROTOCOL_WARN. */
  1036. int
  1037. get_protocol_warning_severity_level(void)
  1038. {
  1039. return (int) atomic_counter_get(&protocol_warning_severity_level);
  1040. }
  1041. /** Set the protocol warning severity level to <b>severity</b>. */
  1042. static void
  1043. set_protocol_warning_severity_level(int warning_severity)
  1044. {
  1045. atomic_counter_exchange(&protocol_warning_severity_level,
  1046. warning_severity);
  1047. }
  1048. /**
  1049. * Initialize the log warning severity level for protocol warnings. Call
  1050. * only once at startup.
  1051. */
  1052. void
  1053. init_protocol_warning_severity_level(void)
  1054. {
  1055. atomic_counter_init(&protocol_warning_severity_level);
  1056. set_protocol_warning_severity_level(LOG_WARN);
  1057. }
  1058. /**
  1059. * Tear down protocol_warning_severity_level.
  1060. */
  1061. static void
  1062. cleanup_protocol_warning_severity_level(void)
  1063. {
  1064. atomic_counter_destroy(&protocol_warning_severity_level);
  1065. }
  1066. /** List of default directory authorities */
  1067. static const char *default_authorities[] = {
  1068. "moria1 orport=9101 "
  1069. "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
  1070. "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
  1071. "tor26 orport=443 "
  1072. "v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
  1073. "ipv6=[2001:858:2:2:aabb:0:563b:1526]:443 "
  1074. "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
  1075. "dizum orport=443 "
  1076. "v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
  1077. "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
  1078. "Bifroest orport=443 bridge "
  1079. "37.218.247.217:80 1D8F 3A91 C37C 5D1C 4C19 B1AD 1D0C FBE8 BF72 D8E1",
  1080. "gabelmoo orport=443 "
  1081. "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
  1082. "ipv6=[2001:638:a000:4140::ffff:189]:443 "
  1083. "131.188.40.189:80 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
  1084. "dannenberg orport=443 "
  1085. "v3ident=0232AF901C31A04EE9848595AF9BB7620D4C5B2E "
  1086. "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
  1087. "maatuska orport=80 "
  1088. "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
  1089. "ipv6=[2001:67c:289c::9]:80 "
  1090. "171.25.193.9:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
  1091. "Faravahar orport=443 "
  1092. "v3ident=EFCBE720AB3A82B99F9E953CD5BF50F7EEFC7B97 "
  1093. "154.35.175.225:80 CF6D 0AAF B385 BE71 B8E1 11FC 5CFF 4B47 9237 33BC",
  1094. "longclaw orport=443 "
  1095. "v3ident=23D15D965BC35114467363C165C4F724B64B4F66 "
  1096. "199.58.81.140:80 74A9 1064 6BCE EFBC D2E8 74FC 1DC9 9743 0F96 8145",
  1097. "bastet orport=443 "
  1098. "v3ident=27102BC123E7AF1D4741AE047E160C91ADC76B21 "
  1099. "ipv6=[2620:13:4000:6000::1000:118]:443 "
  1100. "204.13.164.118:80 24E2 F139 121D 4394 C54B 5BCC 368B 3B41 1857 C413",
  1101. NULL
  1102. };
  1103. /** List of fallback directory authorities. The list is generated by opt-in of
  1104. * relays that meet certain stability criteria.
  1105. */
  1106. static const char *default_fallbacks[] = {
  1107. #include "fallback_dirs.inc"
  1108. NULL
  1109. };
  1110. /** Add the default directory authorities directly into the trusted dir list,
  1111. * but only add them insofar as they share bits with <b>type</b>.
  1112. * Each authority's bits are restricted to the bits shared with <b>type</b>.
  1113. * If <b>type</b> is ALL_DIRINFO or NO_DIRINFO (zero), add all authorities. */
  1114. STATIC void
  1115. add_default_trusted_dir_authorities(dirinfo_type_t type)
  1116. {
  1117. int i;
  1118. for (i=0; default_authorities[i]; i++) {
  1119. if (parse_dir_authority_line(default_authorities[i], type, 0)<0) {
  1120. log_err(LD_BUG, "Couldn't parse internal DirAuthority line %s",
  1121. default_authorities[i]);
  1122. }
  1123. }
  1124. }
  1125. /** Add the default fallback directory servers into the fallback directory
  1126. * server list. */
  1127. MOCK_IMPL(void,
  1128. add_default_fallback_dir_servers,(void))
  1129. {
  1130. int i;
  1131. for (i=0; default_fallbacks[i]; i++) {
  1132. if (parse_dir_fallback_line(default_fallbacks[i], 0)<0) {
  1133. log_err(LD_BUG, "Couldn't parse internal FallbackDir line %s",
  1134. default_fallbacks[i]);
  1135. }
  1136. }
  1137. }
  1138. /** Look at all the config options for using alternate directory
  1139. * authorities, and make sure none of them are broken. Also, warn the
  1140. * user if we changed any dangerous ones.
  1141. */
  1142. static int
  1143. validate_dir_servers(or_options_t *options, or_options_t *old_options)
  1144. {
  1145. config_line_t *cl;
  1146. if (options->DirAuthorities &&
  1147. (options->AlternateDirAuthority || options->AlternateBridgeAuthority)) {
  1148. log_warn(LD_CONFIG,
  1149. "You cannot set both DirAuthority and Alternate*Authority.");
  1150. return -1;
  1151. }
  1152. /* do we want to complain to the user about being partitionable? */
  1153. if ((options->DirAuthorities &&
  1154. (!old_options ||
  1155. !config_lines_eq(options->DirAuthorities,
  1156. old_options->DirAuthorities))) ||
  1157. (options->AlternateDirAuthority &&
  1158. (!old_options ||
  1159. !config_lines_eq(options->AlternateDirAuthority,
  1160. old_options->AlternateDirAuthority)))) {
  1161. log_warn(LD_CONFIG,
  1162. "You have used DirAuthority or AlternateDirAuthority to "
  1163. "specify alternate directory authorities in "
  1164. "your configuration. This is potentially dangerous: it can "
  1165. "make you look different from all other Tor users, and hurt "
  1166. "your anonymity. Even if you've specified the same "
  1167. "authorities as Tor uses by default, the defaults could "
  1168. "change in the future. Be sure you know what you're doing.");
  1169. }
  1170. /* Now go through the four ways you can configure an alternate
  1171. * set of directory authorities, and make sure none are broken. */
  1172. for (cl = options->DirAuthorities; cl; cl = cl->next)
  1173. if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
  1174. return -1;
  1175. for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
  1176. if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
  1177. return -1;
  1178. for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
  1179. if (parse_dir_authority_line(cl->value, NO_DIRINFO, 1)<0)
  1180. return -1;
  1181. for (cl = options->FallbackDir; cl; cl = cl->next)
  1182. if (parse_dir_fallback_line(cl->value, 1)<0)
  1183. return -1;
  1184. return 0;
  1185. }
  1186. /** Look at all the config options and assign new dir authorities
  1187. * as appropriate.
  1188. */
  1189. int
  1190. consider_adding_dir_servers(const or_options_t *options,
  1191. const or_options_t *old_options)
  1192. {
  1193. config_line_t *cl;
  1194. int need_to_update =
  1195. !smartlist_len(router_get_trusted_dir_servers()) ||
  1196. !smartlist_len(router_get_fallback_dir_servers()) || !old_options ||
  1197. !config_lines_eq(options->DirAuthorities, old_options->DirAuthorities) ||
  1198. !config_lines_eq(options->FallbackDir, old_options->FallbackDir) ||
  1199. (options->UseDefaultFallbackDirs != old_options->UseDefaultFallbackDirs) ||
  1200. !config_lines_eq(options->AlternateBridgeAuthority,
  1201. old_options->AlternateBridgeAuthority) ||
  1202. !config_lines_eq(options->AlternateDirAuthority,
  1203. old_options->AlternateDirAuthority);
  1204. if (!need_to_update)
  1205. return 0; /* all done */
  1206. /* "You cannot set both DirAuthority and Alternate*Authority."
  1207. * Checking that this restriction holds allows us to simplify
  1208. * the unit tests. */
  1209. tor_assert(!(options->DirAuthorities &&
  1210. (options->AlternateDirAuthority
  1211. || options->AlternateBridgeAuthority)));
  1212. /* Start from a clean slate. */
  1213. clear_dir_servers();
  1214. if (!options->DirAuthorities) {
  1215. /* then we may want some of the defaults */
  1216. dirinfo_type_t type = NO_DIRINFO;
  1217. if (!options->AlternateBridgeAuthority) {
  1218. type |= BRIDGE_DIRINFO;
  1219. }
  1220. if (!options->AlternateDirAuthority) {
  1221. type |= V3_DIRINFO | EXTRAINFO_DIRINFO | MICRODESC_DIRINFO;
  1222. /* Only add the default fallback directories when the DirAuthorities,
  1223. * AlternateDirAuthority, and FallbackDir directory config options
  1224. * are set to their defaults, and when UseDefaultFallbackDirs is 1. */
  1225. if (!options->FallbackDir && options->UseDefaultFallbackDirs) {
  1226. add_default_fallback_dir_servers();
  1227. }
  1228. }
  1229. /* if type == NO_DIRINFO, we don't want to add any of the
  1230. * default authorities, because we've replaced them all */
  1231. if (type != NO_DIRINFO)
  1232. add_default_trusted_dir_authorities(type);
  1233. }
  1234. for (cl = options->DirAuthorities; cl; cl = cl->next)
  1235. if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
  1236. return -1;
  1237. for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
  1238. if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
  1239. return -1;
  1240. for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
  1241. if (parse_dir_authority_line(cl->value, NO_DIRINFO, 0)<0)
  1242. return -1;
  1243. for (cl = options->FallbackDir; cl; cl = cl->next)
  1244. if (parse_dir_fallback_line(cl->value, 0)<0)
  1245. return -1;
  1246. return 0;
  1247. }
  1248. /**
  1249. * Make sure that <b>directory</b> exists, with appropriate ownership and
  1250. * permissions (as modified by <b>group_readable</b>). If <b>create</b>,
  1251. * create the directory if it is missing. Return 0 on success.
  1252. * On failure, return -1 and set *<b>msg_out</b>.
  1253. */
  1254. static int
  1255. check_and_create_data_directory(int create,
  1256. const char *directory,
  1257. int group_readable,
  1258. const char *owner,
  1259. char **msg_out)
  1260. {
  1261. cpd_check_t cpd_opts = create ? CPD_CREATE : CPD_CHECK;
  1262. if (group_readable)
  1263. cpd_opts |= CPD_GROUP_READ;
  1264. if (check_private_dir(directory,
  1265. cpd_opts,
  1266. owner) < 0) {
  1267. tor_asprintf(msg_out,
  1268. "Couldn't %s private data directory \"%s\"",
  1269. create ? "create" : "access",
  1270. directory);
  1271. return -1;
  1272. }
  1273. #ifndef _WIN32
  1274. if (group_readable) {
  1275. /* Only new dirs created get new opts, also enforce group read. */
  1276. if (chmod(directory, 0750)) {
  1277. log_warn(LD_FS,"Unable to make %s group-readable: %s",
  1278. directory, strerror(errno));
  1279. }
  1280. }
  1281. #endif /* !defined(_WIN32) */
  1282. return 0;
  1283. }
  1284. /**
  1285. * Ensure that our keys directory exists, with appropriate permissions.
  1286. * Return 0 on success, -1 on failure.
  1287. */
  1288. int
  1289. create_keys_directory(const or_options_t *options)
  1290. {
  1291. /* Make sure DataDirectory exists, and is private. */
  1292. cpd_check_t cpd_opts = CPD_CREATE;
  1293. if (options->DataDirectoryGroupReadable)
  1294. cpd_opts |= CPD_GROUP_READ;
  1295. if (check_private_dir(options->DataDirectory, cpd_opts, options->User)) {
  1296. log_err(LD_OR, "Can't create/check datadirectory %s",
  1297. options->DataDirectory);
  1298. return -1;
  1299. }
  1300. /* Check the key directory. */
  1301. if (check_private_dir(options->KeyDirectory, CPD_CREATE, options->User)) {
  1302. return -1;
  1303. }
  1304. return 0;
  1305. }
  1306. /* Helps determine flags to pass to switch_id. */
  1307. static int have_low_ports = -1;
  1308. /** Fetch the active option list, and take actions based on it. All of the
  1309. * things we do should survive being done repeatedly. If present,
  1310. * <b>old_options</b> contains the previous value of the options.
  1311. *
  1312. * Return 0 if all goes well, return -1 if things went badly.
  1313. */
  1314. static int
  1315. options_act_reversible(const or_options_t *old_options, char **msg)
  1316. {
  1317. smartlist_t *new_listeners = smartlist_new();
  1318. smartlist_t *replaced_listeners = smartlist_new();
  1319. or_options_t *options = get_options_mutable();
  1320. int running_tor = options->command == CMD_RUN_TOR;
  1321. int set_conn_limit = 0;
  1322. int r = -1;
  1323. int logs_marked = 0, logs_initialized = 0;
  1324. int old_min_log_level = get_min_log_level();
  1325. /* Daemonize _first_, since we only want to open most of this stuff in
  1326. * the subprocess. Libevent bases can't be reliably inherited across
  1327. * processes. */
  1328. if (running_tor && options->RunAsDaemon) {
  1329. /* No need to roll back, since you can't change the value. */
  1330. start_daemon();
  1331. }
  1332. #ifdef HAVE_SYSTEMD
  1333. /* Our PID may have changed, inform supervisor */
  1334. sd_notifyf(0, "MAINPID=%ld\n", (long int)getpid());
  1335. #endif
  1336. #ifndef HAVE_SYS_UN_H
  1337. if (options->ControlSocket || options->ControlSocketsGroupWritable) {
  1338. *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported "
  1339. "on this OS/with this build.");
  1340. goto rollback;
  1341. }
  1342. #else /* !(!defined(HAVE_SYS_UN_H)) */
  1343. if (options->ControlSocketsGroupWritable && !options->ControlSocket) {
  1344. *msg = tor_strdup("Setting ControlSocketGroupWritable without setting"
  1345. "a ControlSocket makes no sense.");
  1346. goto rollback;
  1347. }
  1348. #endif /* !defined(HAVE_SYS_UN_H) */
  1349. if (running_tor) {
  1350. int n_ports=0;
  1351. /* We need to set the connection limit before we can open the listeners. */
  1352. if (! sandbox_is_active()) {
  1353. if (set_max_file_descriptors((unsigned)options->ConnLimit,
  1354. &options->ConnLimit_) < 0) {
  1355. *msg = tor_strdup("Problem with ConnLimit value. "
  1356. "See logs for details.");
  1357. goto rollback;
  1358. }
  1359. set_conn_limit = 1;
  1360. } else {
  1361. tor_assert(old_options);
  1362. options->ConnLimit_ = old_options->ConnLimit_;
  1363. }
  1364. /* Set up libevent. (We need to do this before we can register the
  1365. * listeners as listeners.) */
  1366. if (running_tor && !libevent_initialized) {
  1367. init_libevent(options);
  1368. libevent_initialized = 1;
  1369. /* This has to come up after libevent is initialized. */
  1370. control_initialize_event_queue();
  1371. /*
  1372. * Initialize the scheduler - this has to come after
  1373. * options_init_from_torrc() sets up libevent - why yes, that seems
  1374. * completely sensible to hide the libevent setup in the option parsing
  1375. * code! It also needs to happen before init_keys(), so it needs to
  1376. * happen here too. How yucky. */
  1377. scheduler_init();
  1378. }
  1379. /* Adjust the port configuration so we can launch listeners. */
  1380. if (parse_ports(options, 0, msg, &n_ports, NULL)) {
  1381. if (!*msg)
  1382. *msg = tor_strdup("Unexpected problem parsing port config");
  1383. goto rollback;
  1384. }
  1385. /* Set the hibernation state appropriately.*/
  1386. consider_hibernation(time(NULL));
  1387. /* Launch the listeners. (We do this before we setuid, so we can bind to
  1388. * ports under 1024.) We don't want to rebind if we're hibernating. If
  1389. * networking is disabled, this will close all but the control listeners,
  1390. * but disable those. */
  1391. if (!we_are_hibernating()) {
  1392. if (retry_all_listeners(replaced_listeners, new_listeners,
  1393. options->DisableNetwork) < 0) {
  1394. *msg = tor_strdup("Failed to bind one of the listener ports.");
  1395. goto rollback;
  1396. }
  1397. }
  1398. if (options->DisableNetwork) {
  1399. /* Aggressively close non-controller stuff, NOW */
  1400. log_notice(LD_NET, "DisableNetwork is set. Tor will not make or accept "
  1401. "non-control network connections. Shutting down all existing "
  1402. "connections.");
  1403. connection_mark_all_noncontrol_connections();
  1404. /* We can't complete circuits until the network is re-enabled. */
  1405. note_that_we_maybe_cant_complete_circuits();
  1406. }
  1407. }
  1408. #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
  1409. /* Open /dev/pf before dropping privileges. */
  1410. if (options->TransPort_set &&
  1411. options->TransProxyType_parsed == TPT_DEFAULT) {
  1412. if (get_pf_socket() < 0) {
  1413. *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
  1414. goto rollback;
  1415. }
  1416. }
  1417. #endif /* defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H) */
  1418. /* Attempt to lock all current and future memory with mlockall() only once */
  1419. if (options->DisableAllSwap) {
  1420. if (tor_mlockall() == -1) {
  1421. *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
  1422. "permissions?");
  1423. goto done;
  1424. }
  1425. }
  1426. /* Setuid/setgid as appropriate */
  1427. if (options->User) {
  1428. tor_assert(have_low_ports != -1);
  1429. unsigned switch_id_flags = 0;
  1430. if (options->KeepBindCapabilities == 1) {
  1431. switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
  1432. switch_id_flags |= SWITCH_ID_WARN_IF_NO_CAPS;
  1433. }
  1434. if (options->KeepBindCapabilities == -1 && have_low_ports) {
  1435. switch_id_flags |= SWITCH_ID_KEEP_BINDLOW;
  1436. }
  1437. if (switch_id(options->User, switch_id_flags) != 0) {
  1438. /* No need to roll back, since you can't change the value. */
  1439. *msg = tor_strdup("Problem with User value. See logs for details.");
  1440. goto done;
  1441. }
  1442. }
  1443. /* Ensure data directory is private; create if possible. */
  1444. /* It's okay to do this in "options_act_reversible()" even though it isn't
  1445. * actually reversible, since you can't change the DataDirectory while
  1446. * Tor is running. */
  1447. if (check_and_create_data_directory(running_tor /* create */,
  1448. options->DataDirectory,
  1449. options->DataDirectoryGroupReadable,
  1450. options->User,
  1451. msg) < 0) {
  1452. goto done;
  1453. }
  1454. if (check_and_create_data_directory(running_tor /* create */,
  1455. options->KeyDirectory,
  1456. options->KeyDirectoryGroupReadable,
  1457. options->User,
  1458. msg) < 0) {
  1459. goto done;
  1460. }
  1461. if (check_and_create_data_directory(running_tor /* create */,
  1462. options->CacheDirectory,
  1463. options->CacheDirectoryGroupReadable,
  1464. options->User,
  1465. msg) < 0) {
  1466. goto done;
  1467. }
  1468. /* Bail out at this point if we're not going to be a client or server:
  1469. * we don't run Tor itself. */
  1470. if (!running_tor)
  1471. goto commit;
  1472. mark_logs_temp(); /* Close current logs once new logs are open. */
  1473. logs_marked = 1;
  1474. /* Configure the tor_log(s) */
  1475. if (options_init_logs(old_options, options, 0)<0) {
  1476. *msg = tor_strdup("Failed to init Log options. See logs for details.");
  1477. goto rollback;
  1478. }
  1479. logs_initialized = 1;
  1480. commit:
  1481. r = 0;
  1482. if (logs_marked) {
  1483. log_severity_list_t *severity =
  1484. tor_malloc_zero(sizeof(log_severity_list_t));
  1485. close_temp_logs();
  1486. add_callback_log(severity, control_event_logmsg);
  1487. control_adjust_event_log_severity();
  1488. tor_free(severity);
  1489. tor_log_update_sigsafe_err_fds();
  1490. }
  1491. if (logs_initialized) {
  1492. flush_log_messages_from_startup();
  1493. }
  1494. {
  1495. const char *badness = NULL;
  1496. int bad_safelog = 0, bad_severity = 0, new_badness = 0;
  1497. if (options->SafeLogging_ != SAFELOG_SCRUB_ALL) {
  1498. bad_safelog = 1;
  1499. if (!old_options || old_options->SafeLogging_ != options->SafeLogging_)
  1500. new_badness = 1;
  1501. }
  1502. if (get_min_log_level() >= LOG_INFO) {
  1503. bad_severity = 1;
  1504. if (get_min_log_level() != old_min_log_level)
  1505. new_badness = 1;
  1506. }
  1507. if (bad_safelog && bad_severity)
  1508. badness = "you disabled SafeLogging, and "
  1509. "you're logging more than \"notice\"";
  1510. else if (bad_safelog)
  1511. badness = "you disabled SafeLogging";
  1512. else
  1513. badness = "you're logging more than \"notice\"";
  1514. if (new_badness)
  1515. log_warn(LD_GENERAL, "Your log may contain sensitive information - %s. "
  1516. "Don't log unless it serves an important reason. "
  1517. "Overwrite the log afterwards.", badness);
  1518. }
  1519. SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
  1520. {
  1521. int marked = conn->marked_for_close;
  1522. log_notice(LD_NET, "Closing old %s on %s:%d",
  1523. conn_type_to_string(conn->type), conn->address, conn->port);
  1524. connection_close_immediate(conn);
  1525. if (!marked) {
  1526. connection_mark_for_close(conn);
  1527. }
  1528. });
  1529. if (set_conn_limit) {
  1530. /*
  1531. * If we adjusted the conn limit, recompute the OOS threshold too
  1532. *
  1533. * How many possible sockets to keep in reserve? If we have lots of
  1534. * possible sockets, keep this below a limit and set ConnLimit_high_thresh
  1535. * very close to ConnLimit_, but if ConnLimit_ is low, shrink it in
  1536. * proportion.
  1537. *
  1538. * Somewhat arbitrarily, set socks_in_reserve to 5% of ConnLimit_, but
  1539. * cap it at 64.
  1540. */
  1541. int socks_in_reserve = options->ConnLimit_ / 20;
  1542. if (socks_in_reserve > 64) socks_in_reserve = 64;
  1543. options->ConnLimit_high_thresh = options->ConnLimit_ - socks_in_reserve;
  1544. options->ConnLimit_low_thresh = (options->ConnLimit_ / 4) * 3;
  1545. log_info(LD_GENERAL,
  1546. "Recomputed OOS thresholds: ConnLimit %d, ConnLimit_ %d, "
  1547. "ConnLimit_high_thresh %d, ConnLimit_low_thresh %d",
  1548. options->ConnLimit, options->ConnLimit_,
  1549. options->ConnLimit_high_thresh,
  1550. options->ConnLimit_low_thresh);
  1551. /* Give the OOS handler a chance with the new thresholds */
  1552. connection_check_oos(get_n_open_sockets(), 0);
  1553. }
  1554. goto done;
  1555. rollback:
  1556. r = -1;
  1557. tor_assert(*msg);
  1558. if (logs_marked) {
  1559. rollback_log_changes();
  1560. control_adjust_event_log_severity();
  1561. }
  1562. if (set_conn_limit && old_options)
  1563. set_max_file_descriptors((unsigned)old_options->ConnLimit,
  1564. &options->ConnLimit_);
  1565. SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
  1566. {
  1567. log_notice(LD_NET, "Closing partially-constructed %s on %s:%d",
  1568. conn_type_to_string(conn->type), conn->address, conn->port);
  1569. connection_close_immediate(conn);
  1570. connection_mark_for_close(conn);
  1571. });
  1572. done:
  1573. smartlist_free(new_listeners);
  1574. smartlist_free(replaced_listeners);
  1575. return r;
  1576. }
  1577. /** If we need to have a GEOIP ip-to-country map to run with our configured
  1578. * options, return 1 and set *<b>reason_out</b> to a description of why. */
  1579. int
  1580. options_need_geoip_info(const or_options_t *options, const char **reason_out)
  1581. {
  1582. int bridge_usage =
  1583. options->BridgeRelay && options->BridgeRecordUsageByCountry;
  1584. int routerset_usage =
  1585. routerset_needs_geoip(options->EntryNodes) ||
  1586. routerset_needs_geoip(options->ExitNodes) ||
  1587. routerset_needs_geoip(options->ExcludeExitNodes) ||
  1588. routerset_needs_geoip(options->ExcludeNodes) ||
  1589. routerset_needs_geoip(options->HSLayer2Nodes) ||
  1590. routerset_needs_geoip(options->HSLayer3Nodes) ||
  1591. routerset_needs_geoip(options->Tor2webRendezvousPoints);
  1592. if (routerset_usage && reason_out) {
  1593. *reason_out = "We've been configured to use (or avoid) nodes in certain "
  1594. "countries, and we need GEOIP information to figure out which ones they "
  1595. "are.";
  1596. } else if (bridge_usage && reason_out) {
  1597. *reason_out = "We've been configured to see which countries can access "
  1598. "us as a bridge, and we need GEOIP information to tell which countries "
  1599. "clients are in.";
  1600. }
  1601. return bridge_usage || routerset_usage;
  1602. }
  1603. /** Return the bandwidthrate that we are going to report to the authorities
  1604. * based on the config options. */
  1605. uint32_t
  1606. get_effective_bwrate(const or_options_t *options)
  1607. {
  1608. uint64_t bw = options->BandwidthRate;
  1609. if (bw > options->MaxAdvertisedBandwidth)
  1610. bw = options->MaxAdvertisedBandwidth;
  1611. if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
  1612. bw = options->RelayBandwidthRate;
  1613. /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
  1614. return (uint32_t)bw;
  1615. }
  1616. /** Return the bandwidthburst that we are going to report to the authorities
  1617. * based on the config options. */
  1618. uint32_t
  1619. get_effective_bwburst(const or_options_t *options)
  1620. {
  1621. uint64_t bw = options->BandwidthBurst;
  1622. if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
  1623. bw = options->RelayBandwidthBurst;
  1624. /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
  1625. return (uint32_t)bw;
  1626. }
  1627. /* Used in the various options_transition_affects* functions. */
  1628. #define YES_IF_CHANGED_BOOL(opt) \
  1629. if (!CFG_EQ_BOOL(old_options, new_options, opt)) return 1;
  1630. #define YES_IF_CHANGED_INT(opt) \
  1631. if (!CFG_EQ_INT(old_options, new_options, opt)) return 1;
  1632. #define YES_IF_CHANGED_STRING(opt) \
  1633. if (!CFG_EQ_STRING(old_options, new_options, opt)) return 1;
  1634. #define YES_IF_CHANGED_LINELIST(opt) \
  1635. if (!CFG_EQ_LINELIST(old_options, new_options, opt)) return 1;
  1636. #define YES_IF_CHANGED_SMARTLIST(opt) \
  1637. if (!CFG_EQ_SMARTLIST(old_options, new_options, opt)) return 1;
  1638. #define YES_IF_CHANGED_ROUTERSET(opt) \
  1639. if (!CFG_EQ_ROUTERSET(old_options, new_options, opt)) return 1;
  1640. /**
  1641. * Return true if changing the configuration from <b>old</b> to <b>new</b>
  1642. * affects the guard subsystem.
  1643. */
  1644. static int
  1645. options_transition_affects_guards(const or_options_t *old_options,
  1646. const or_options_t *new_options)
  1647. {
  1648. /* NOTE: Make sure this function stays in sync with
  1649. * node_passes_guard_filter */
  1650. tor_assert(old_options);
  1651. tor_assert(new_options);
  1652. YES_IF_CHANGED_BOOL(UseEntryGuards);
  1653. YES_IF_CHANGED_BOOL(UseBridges);
  1654. YES_IF_CHANGED_BOOL(ClientUseIPv4);
  1655. YES_IF_CHANGED_BOOL(ClientUseIPv6);
  1656. YES_IF_CHANGED_BOOL(FascistFirewall);
  1657. YES_IF_CHANGED_ROUTERSET(ExcludeNodes);
  1658. YES_IF_CHANGED_ROUTERSET(EntryNodes);
  1659. YES_IF_CHANGED_SMARTLIST(FirewallPorts);
  1660. YES_IF_CHANGED_LINELIST(Bridges);
  1661. YES_IF_CHANGED_LINELIST(ReachableORAddresses);
  1662. YES_IF_CHANGED_LINELIST(ReachableDirAddresses);
  1663. return 0;
  1664. }
  1665. /** Fetch the active option list, and take actions based on it. All of the
  1666. * things we do should survive being done repeatedly. If present,
  1667. * <b>old_options</b> contains the previous value of the options.
  1668. *
  1669. * Return 0 if all goes well, return -1 if it's time to die.
  1670. *
  1671. * Note: We haven't moved all the "act on new configuration" logic
  1672. * here yet. Some is still in do_hup() and other places.
  1673. */
  1674. STATIC int
  1675. options_act(const or_options_t *old_options)
  1676. {
  1677. config_line_t *cl;
  1678. or_options_t *options = get_options_mutable();
  1679. int running_tor = options->command == CMD_RUN_TOR;
  1680. char *msg=NULL;
  1681. const int transition_affects_workers =
  1682. old_options && options_transition_affects_workers(old_options, options);
  1683. int old_ewma_enabled;
  1684. const int transition_affects_guards =
  1685. old_options && options_transition_affects_guards(old_options, options);
  1686. if (options->NoExec || options->Sandbox) {
  1687. tor_disable_spawning_background_processes();
  1688. }
  1689. /* disable ptrace and later, other basic debugging techniques */
  1690. {
  1691. /* Remember if we already disabled debugger attachment */
  1692. static int disabled_debugger_attach = 0;
  1693. /* Remember if we already warned about being configured not to disable
  1694. * debugger attachment */
  1695. static int warned_debugger_attach = 0;
  1696. /* Don't disable debugger attachment when we're running the unit tests. */
  1697. if (options->DisableDebuggerAttachment && !disabled_debugger_attach &&
  1698. running_tor) {
  1699. int ok = tor_disable_debugger_attach();
  1700. /* LCOV_EXCL_START the warned_debugger_attach is 0 can't reach inside. */
  1701. if (warned_debugger_attach && ok == 1) {
  1702. log_notice(LD_CONFIG, "Disabled attaching debuggers for unprivileged "
  1703. "users.");
  1704. }
  1705. /* LCOV_EXCL_STOP */
  1706. disabled_debugger_attach = (ok == 1);
  1707. } else if (!options->DisableDebuggerAttachment &&
  1708. !warned_debugger_attach) {
  1709. log_notice(LD_CONFIG, "Not disabling debugger attaching for "
  1710. "unprivileged users.");
  1711. warned_debugger_attach = 1;
  1712. }
  1713. }
  1714. /* Write control ports to disk as appropriate */
  1715. control_ports_write_to_file();
  1716. if (running_tor && !have_lockfile()) {
  1717. if (try_locking(options, 1) < 0)
  1718. return -1;
  1719. }
  1720. {
  1721. int warning_severity = options->ProtocolWarnings ? LOG_WARN : LOG_INFO;
  1722. set_protocol_warning_severity_level(warning_severity);
  1723. }
  1724. if (consider_adding_dir_servers(options, old_options) < 0) {
  1725. // XXXX This should get validated earlier, and committed here, to
  1726. // XXXX lower opportunities for reaching an error case.
  1727. return -1;
  1728. }
  1729. if (rend_non_anonymous_mode_enabled(options)) {
  1730. log_warn(LD_GENERAL, "This copy of Tor was compiled or configured to run "
  1731. "in a non-anonymous mode. It will provide NO ANONYMITY.");
  1732. }
  1733. #ifdef ENABLE_TOR2WEB_MODE
  1734. /* LCOV_EXCL_START */
  1735. // XXXX This should move into options_validate()
  1736. if (!options->Tor2webMode) {
  1737. log_err(LD_CONFIG, "This copy of Tor was compiled to run in "
  1738. "'tor2web mode'. It can only be run with the Tor2webMode torrc "
  1739. "option enabled.");
  1740. return -1;
  1741. }
  1742. /* LCOV_EXCL_STOP */
  1743. #else /* !(defined(ENABLE_TOR2WEB_MODE)) */
  1744. // XXXX This should move into options_validate()
  1745. if (options->Tor2webMode) {
  1746. log_err(LD_CONFIG, "This copy of Tor was not compiled to run in "
  1747. "'tor2web mode'. It cannot be run with the Tor2webMode torrc "
  1748. "option enabled. To enable Tor2webMode recompile with the "
  1749. "--enable-tor2web-mode option.");
  1750. return -1;
  1751. }
  1752. #endif /* defined(ENABLE_TOR2WEB_MODE) */
  1753. /* If we are a bridge with a pluggable transport proxy but no
  1754. Extended ORPort, inform the user that they are missing out. */
  1755. if (server_mode(options) && options->ServerTransportPlugin &&
  1756. !options->ExtORPort_lines) {
  1757. log_notice(LD_CONFIG, "We use pluggable transports but the Extended "
  1758. "ORPort is disabled. Tor and your pluggable transports proxy "
  1759. "communicate with each other via the Extended ORPort so it "
  1760. "is suggested you enable it: it will also allow your Bridge "
  1761. "to collect statistics about its clients that use pluggable "
  1762. "transports. Please enable it using the ExtORPort torrc option "
  1763. "(e.g. set 'ExtORPort auto').");
  1764. }
  1765. if (options->Bridges) {
  1766. mark_bridge_list();
  1767. for (cl = options->Bridges; cl; cl = cl->next) {
  1768. bridge_line_t *bridge_line = parse_bridge_line(cl->value);
  1769. if (!bridge_line) {
  1770. // LCOV_EXCL_START
  1771. log_warn(LD_BUG,
  1772. "Previously validated Bridge line could not be added!");
  1773. return -1;
  1774. // LCOV_EXCL_STOP
  1775. }
  1776. bridge_add_from_config(bridge_line);
  1777. }
  1778. sweep_bridge_list();
  1779. }
  1780. if (running_tor && hs_config_service_all(options, 0)<0) {
  1781. // LCOV_EXCL_START
  1782. log_warn(LD_BUG,
  1783. "Previously validated hidden services line could not be added!");
  1784. return -1;
  1785. // LCOV_EXCL_STOP
  1786. }
  1787. if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
  1788. // LCOV_EXCL_START
  1789. log_warn(LD_BUG, "Previously validated client authorization for "
  1790. "hidden services could not be added!");
  1791. return -1;
  1792. // LCOV_EXCL_STOP
  1793. }
  1794. if (running_tor && !old_options && options->OwningControllerFD != -1) {
  1795. #ifdef _WIN32
  1796. log_warn(LD_CONFIG, "OwningControllerFD is not supported on Windows. "
  1797. "If you need it, tell the Tor developers.");
  1798. return -1;
  1799. #else
  1800. const unsigned ctrl_flags =
  1801. CC_LOCAL_FD_IS_OWNER |
  1802. CC_LOCAL_FD_IS_AUTHENTICATED;
  1803. tor_socket_t ctrl_sock = (tor_socket_t)options->OwningControllerFD;
  1804. if (control_connection_add_local_fd(ctrl_sock, ctrl_flags) < 0) {
  1805. log_warn(LD_CONFIG, "Could not add local controller connection with "
  1806. "given FD.");
  1807. return -1;
  1808. }
  1809. #endif /* defined(_WIN32) */
  1810. }
  1811. /* Load state */
  1812. if (! or_state_loaded() && running_tor) {
  1813. if (or_state_load())
  1814. return -1;
  1815. rep_hist_load_mtbf_data(time(NULL));
  1816. }
  1817. /* If we have an ExtORPort, initialize its auth cookie. */
  1818. if (running_tor &&
  1819. init_ext_or_cookie_authentication(!!options->ExtORPort_lines) < 0) {
  1820. log_warn(LD_CONFIG,"Error creating Extended ORPort cookie file.");
  1821. return -1;
  1822. }
  1823. mark_transport_list();
  1824. pt_prepare_proxy_list_for_config_read();
  1825. if (!options->DisableNetwork) {
  1826. if (options->ClientTransportPlugin) {
  1827. for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
  1828. if (parse_transport_line(options, cl->value, 0, 0) < 0) {
  1829. // LCOV_EXCL_START
  1830. log_warn(LD_BUG,
  1831. "Previously validated ClientTransportPlugin line "
  1832. "could not be added!");
  1833. return -1;
  1834. // LCOV_EXCL_STOP
  1835. }
  1836. }
  1837. }
  1838. if (options->ServerTransportPlugin && server_mode(options)) {
  1839. for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
  1840. if (parse_transport_line(options, cl->value, 0, 1) < 0) {
  1841. // LCOV_EXCL_START
  1842. log_warn(LD_BUG,
  1843. "Previously validated ServerTransportPlugin line "
  1844. "could not be added!");
  1845. return -1;
  1846. // LCOV_EXCL_STOP
  1847. }
  1848. }
  1849. }
  1850. }
  1851. sweep_transport_list();
  1852. sweep_proxy_list();
  1853. /* Start the PT proxy configuration. By doing this configuration
  1854. here, we also figure out which proxies need to be restarted and
  1855. which not. */
  1856. if (pt_proxies_configuration_pending() && !net_is_disabled())
  1857. pt_configure_remaining_proxies();
  1858. /* Bail out at this point if we're not going to be a client or server:
  1859. * we want to not fork, and to log stuff to stderr. */
  1860. if (!running_tor)
  1861. return 0;
  1862. /* Finish backgrounding the process */
  1863. if (options->RunAsDaemon) {
  1864. /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
  1865. finish_daemon(options->DataDirectory);
  1866. }
  1867. /* We want to reinit keys as needed before we do much of anything else:
  1868. keys are important, and other things can depend on them. */
  1869. if (transition_affects_workers ||
  1870. (options->V3AuthoritativeDir && (!old_options ||
  1871. !old_options->V3AuthoritativeDir))) {
  1872. if (init_keys() < 0) {
  1873. log_warn(LD_BUG,"Error initializing keys; exiting");
  1874. return -1;
  1875. }
  1876. }
  1877. /* Write our PID to the PID file. If we do not have write permissions we
  1878. * will log a warning and exit. */
  1879. if (options->PidFile && !sandbox_is_active()) {
  1880. if (write_pidfile(options->PidFile) < 0) {
  1881. log_err(LD_CONFIG, "Unable to write PIDFile %s",
  1882. escaped(options->PidFile));
  1883. return -1;
  1884. }
  1885. }
  1886. /* Register addressmap directives */
  1887. config_register_addressmaps(options);
  1888. parse_virtual_addr_network(options->VirtualAddrNetworkIPv4, AF_INET,0,NULL);
  1889. parse_virtual_addr_network(options->VirtualAddrNetworkIPv6, AF_INET6,0,NULL);
  1890. /* Update address policies. */
  1891. if (policies_parse_from_options(options) < 0) {
  1892. /* This should be impossible, but let's be sure. */
  1893. log_warn(LD_BUG,"Error parsing already-validated policy options.");
  1894. return -1;
  1895. }
  1896. if (server_mode(options)) {
  1897. static int cdm_initialized = 0;
  1898. if (cdm_initialized == 0) {
  1899. cdm_initialized = 1;
  1900. consdiffmgr_configure(NULL);
  1901. consdiffmgr_validate();
  1902. }
  1903. }
  1904. if (init_control_cookie_authentication(options->CookieAuthentication) < 0) {
  1905. log_warn(LD_CONFIG,"Error creating control cookie authentication file.");
  1906. return -1;
  1907. }
  1908. monitor_owning_controller_process(options->OwningControllerProcess);
  1909. /* reload keys as needed for rendezvous services. */
  1910. if (hs_service_load_all_keys() < 0) {
  1911. log_warn(LD_GENERAL,"Error loading rendezvous service keys");
  1912. return -1;
  1913. }
  1914. /* Inform the scheduler subsystem that a configuration changed happened. It
  1915. * might be a change of scheduler or parameter. */
  1916. scheduler_conf_changed();
  1917. /* Set up accounting */
  1918. if (accounting_parse_options(options, 0)<0) {
  1919. // LCOV_EXCL_START
  1920. log_warn(LD_BUG,"Error in previously validated accounting options");
  1921. return -1;
  1922. // LCOV_EXCL_STOP
  1923. }
  1924. if (accounting_is_enabled(options))
  1925. configure_accounting(time(NULL));
  1926. old_ewma_enabled = cell_ewma_enabled();
  1927. /* Change the cell EWMA settings */
  1928. cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
  1929. /* If we just enabled ewma, set the cmux policy on all active channels */
  1930. if (cell_ewma_enabled() && !old_ewma_enabled) {
  1931. channel_set_cmux_policy_everywhere(&ewma_policy);
  1932. } else if (!cell_ewma_enabled() && old_ewma_enabled) {
  1933. /* Turn it off everywhere */
  1934. channel_set_cmux_policy_everywhere(NULL);
  1935. }
  1936. /* Update the BridgePassword's hashed version as needed. We store this as a
  1937. * digest so that we can do side-channel-proof comparisons on it.
  1938. */
  1939. if (options->BridgePassword) {
  1940. char *http_authenticator;
  1941. http_authenticator = alloc_http_authenticator(options->BridgePassword);
  1942. if (!http_authenticator) {
  1943. // XXXX This should get validated in options_validate().
  1944. log_warn(LD_BUG, "Unable to allocate HTTP authenticator. Not setting "
  1945. "BridgePassword.");
  1946. return -1;
  1947. }
  1948. options->BridgePassword_AuthDigest_ = tor_malloc(DIGEST256_LEN);
  1949. crypto_digest256(options->BridgePassword_AuthDigest_,
  1950. http_authenticator, strlen(http_authenticator),
  1951. DIGEST_SHA256);
  1952. tor_free(http_authenticator);
  1953. }
  1954. if (parse_outbound_addresses(options, 0, &msg) < 0) {
  1955. // LCOV_EXCL_START
  1956. log_warn(LD_BUG, "Failed parsing previously validated outbound "
  1957. "bind addresses: %s", msg);
  1958. tor_free(msg);
  1959. return -1;
  1960. // LCOV_EXCL_STOP
  1961. }
  1962. config_maybe_load_geoip_files_(options, old_options);
  1963. if (geoip_is_loaded(AF_INET) && options->GeoIPExcludeUnknown) {
  1964. /* ExcludeUnknown is true or "auto" */
  1965. const int is_auto = options->GeoIPExcludeUnknown == -1;
  1966. int changed;
  1967. changed = routerset_add_unknown_ccs(&options->ExcludeNodes, is_auto);
  1968. changed += routerset_add_unknown_ccs(&options->ExcludeExitNodes, is_auto);
  1969. if (changed)
  1970. routerset_add_unknown_ccs(&options->ExcludeExitNodesUnion_, is_auto);
  1971. }
  1972. /* Check for transitions that need action. */
  1973. if (old_options) {
  1974. int revise_trackexithosts = 0;
  1975. int revise_automap_entries = 0;
  1976. int abandon_circuits = 0;
  1977. if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
  1978. options->UseBridges != old_options->UseBridges ||
  1979. (options->UseBridges &&
  1980. !config_lines_eq(options->Bridges, old_options->Bridges)) ||
  1981. !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes) ||
  1982. !routerset_equal(old_options->ExcludeExitNodes,
  1983. options->ExcludeExitNodes) ||
  1984. !routerset_equal(old_options->EntryNodes, options->EntryNodes) ||
  1985. !routerset_equal(old_options->ExitNodes, options->ExitNodes) ||
  1986. !routerset_equal(old_options->HSLayer2Nodes,
  1987. options->HSLayer2Nodes) ||
  1988. !routerset_equal(old_options->HSLayer3Nodes,
  1989. options->HSLayer3Nodes) ||
  1990. !routerset_equal(old_options->Tor2webRendezvousPoints,
  1991. options->Tor2webRendezvousPoints) ||
  1992. options->StrictNodes != old_options->StrictNodes) {
  1993. log_info(LD_CIRC,
  1994. "Changed to using entry guards or bridges, or changed "
  1995. "preferred or excluded node lists. "
  1996. "Abandoning previous circuits.");
  1997. abandon_circuits = 1;
  1998. }
  1999. if (transition_affects_guards) {
  2000. if (guards_update_all()) {
  2001. abandon_circuits = 1;
  2002. }
  2003. }
  2004. if (abandon_circuits) {
  2005. circuit_mark_all_unused_circs();
  2006. circuit_mark_all_dirty_circs_as_unusable();
  2007. revise_trackexithosts = 1;
  2008. }
  2009. if (!smartlist_strings_eq(old_options->TrackHostExits,
  2010. options->TrackHostExits))
  2011. revise_trackexithosts = 1;
  2012. if (revise_trackexithosts)
  2013. addressmap_clear_excluded_trackexithosts(options);
  2014. if (!options->AutomapHostsOnResolve &&
  2015. old_options->AutomapHostsOnResolve) {
  2016. revise_automap_entries = 1;
  2017. } else {
  2018. if (!smartlist_strings_eq(old_options->AutomapHostsSuffixes,
  2019. options->AutomapHostsSuffixes))
  2020. revise_automap_entries = 1;
  2021. else if (!opt_streq(old_options->VirtualAddrNetworkIPv4,
  2022. options->VirtualAddrNetworkIPv4) ||
  2023. !opt_streq(old_options->VirtualAddrNetworkIPv6,
  2024. options->VirtualAddrNetworkIPv6))
  2025. revise_automap_entries = 1;
  2026. }
  2027. if (revise_automap_entries)
  2028. addressmap_clear_invalid_automaps(options);
  2029. /* How long should we delay counting bridge stats after becoming a bridge?
  2030. * We use this so we don't count clients who used our bridge thinking it is
  2031. * a relay. If you change this, don't forget to change the log message
  2032. * below. It's 4 hours (the time it takes to stop being used by clients)
  2033. * plus some extra time for clock skew. */
  2034. #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
  2035. if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
  2036. int was_relay = 0;
  2037. if (options->BridgeRelay) {
  2038. time_t int_start = time(NULL);
  2039. if (config_lines_eq(old_options->ORPort_lines,options->ORPort_lines)) {
  2040. int_start += RELAY_BRIDGE_STATS_DELAY;
  2041. was_relay = 1;
  2042. }
  2043. geoip_bridge_stats_init(int_start);
  2044. log_info(LD_CONFIG, "We are acting as a bridge now. Starting new "
  2045. "GeoIP stats interval%s.", was_relay ? " in 6 "
  2046. "hours from now" : "");
  2047. } else {
  2048. geoip_bridge_stats_term();
  2049. log_info(LD_GENERAL, "We are no longer acting as a bridge. "
  2050. "Forgetting GeoIP stats.");
  2051. }
  2052. }
  2053. if (transition_affects_workers) {
  2054. log_info(LD_GENERAL,
  2055. "Worker-related options changed. Rotating workers.");
  2056. if (server_mode(options) && !server_mode(old_options)) {
  2057. cpu_init();
  2058. ip_address_changed(0);
  2059. if (have_completed_a_circuit() || !any_predicted_circuits(time(NULL)))
  2060. inform_testing_reachability();
  2061. }
  2062. cpuworkers_rotate_keyinfo();
  2063. if (dns_reset())
  2064. return -1;
  2065. } else {
  2066. if (dns_reset())
  2067. return -1;
  2068. }
  2069. if (options->PerConnBWRate != old_options->PerConnBWRate ||
  2070. options->PerConnBWBurst != old_options->PerConnBWBurst)
  2071. connection_or_update_token_buckets(get_connection_array(), options);
  2072. if (options->MainloopStats != old_options->MainloopStats) {
  2073. reset_main_loop_counters();
  2074. }
  2075. }
  2076. /* Only collect directory-request statistics on relays and bridges. */
  2077. options->DirReqStatistics = options->DirReqStatistics_option &&
  2078. server_mode(options);
  2079. options->HiddenServiceStatistics =
  2080. options->HiddenServiceStatistics_option && server_mode(options);
  2081. if (options->CellStatistics || options->DirReqStatistics ||
  2082. options->EntryStatistics || options->ExitPortStatistics ||
  2083. options->ConnDirectionStatistics ||
  2084. options->HiddenServiceStatistics ||
  2085. options->BridgeAuthoritativeDir) {
  2086. time_t now = time(NULL);
  2087. int print_notice = 0;
  2088. /* Only collect other relay-only statistics on relays. */
  2089. if (!public_server_mode(options)) {
  2090. options->CellStatistics = 0;
  2091. options->EntryStatistics = 0;
  2092. options->ConnDirectionStatistics = 0;
  2093. options->ExitPortStatistics = 0;
  2094. }
  2095. if ((!old_options || !old_options->CellStatistics) &&
  2096. options->CellStatistics) {
  2097. rep_hist_buffer_stats_init(now);
  2098. print_notice = 1;
  2099. }
  2100. if ((!old_options || !old_options->DirReqStatistics) &&
  2101. options->DirReqStatistics) {
  2102. if (geoip_is_loaded(AF_INET)) {
  2103. geoip_dirreq_stats_init(now);
  2104. print_notice = 1;
  2105. } else {
  2106. /* disable statistics collection since we have no geoip file */
  2107. options->DirReqStatistics = 0;
  2108. if (options->ORPort_set)
  2109. log_notice(LD_CONFIG, "Configured to measure directory request "
  2110. "statistics, but no GeoIP database found. "
  2111. "Please specify a GeoIP database using the "
  2112. "GeoIPFile option.");
  2113. }
  2114. }
  2115. if ((!old_options || !old_options->EntryStatistics) &&
  2116. options->EntryStatistics && !should_record_bridge_info(options)) {
  2117. if (geoip_is_loaded(AF_INET) || geoip_is_loaded(AF_INET6)) {
  2118. geoip_entry_stats_init(now);
  2119. print_notice = 1;
  2120. } else {
  2121. options->EntryStatistics = 0;
  2122. log_notice(LD_CONFIG, "Configured to measure entry node "
  2123. "statistics, but no GeoIP database found. "
  2124. "Please specify a GeoIP database using the "
  2125. "GeoIPFile option.");
  2126. }
  2127. }
  2128. if ((!old_options || !old_options->ExitPortStatistics) &&
  2129. options->ExitPortStatistics) {
  2130. rep_hist_exit_stats_init(now);
  2131. print_notice = 1;
  2132. }
  2133. if ((!old_options || !old_options->ConnDirectionStatistics) &&
  2134. options->ConnDirectionStatistics) {
  2135. rep_hist_conn_stats_init(now);
  2136. }
  2137. if ((!old_options || !old_options->HiddenServiceStatistics) &&
  2138. options->HiddenServiceStatistics) {
  2139. log_info(LD_CONFIG, "Configured to measure hidden service statistics.");
  2140. rep_hist_hs_stats_init(now);
  2141. }
  2142. if ((!old_options || !old_options->BridgeAuthoritativeDir) &&
  2143. options->BridgeAuthoritativeDir) {
  2144. rep_hist_desc_stats_init(now);
  2145. print_notice = 1;
  2146. }
  2147. if (print_notice)
  2148. log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
  2149. "the *-stats files that will first be written to the "
  2150. "data directory in 24 hours from now.");
  2151. }
  2152. /* If we used to have statistics enabled but we just disabled them,
  2153. stop gathering them. */
  2154. if (old_options && old_options->CellStatistics &&
  2155. !options->CellStatistics)
  2156. rep_hist_buffer_stats_term();
  2157. if (old_options && old_options->DirReqStatistics &&
  2158. !options->DirReqStatistics)
  2159. geoip_dirreq_stats_term();
  2160. if (old_options && old_options->EntryStatistics &&
  2161. !options->EntryStatistics)
  2162. geoip_entry_stats_term();
  2163. if (old_options && old_options->HiddenServiceStatistics &&
  2164. !options->HiddenServiceStatistics)
  2165. rep_hist_hs_stats_term();
  2166. if (old_options && old_options->ExitPortStatistics &&
  2167. !options->ExitPortStatistics)
  2168. rep_hist_exit_stats_term();
  2169. if (old_options && old_options->ConnDirectionStatistics &&
  2170. !options->ConnDirectionStatistics)
  2171. rep_hist_conn_stats_term();
  2172. if (old_options && old_options->BridgeAuthoritativeDir &&
  2173. !options->BridgeAuthoritativeDir)
  2174. rep_hist_desc_stats_term();
  2175. /* Since our options changed, we might need to regenerate and upload our
  2176. * server descriptor.
  2177. */
  2178. if (!old_options ||
  2179. options_transition_affects_descriptor(old_options, options))
  2180. mark_my_descriptor_dirty("config change");
  2181. /* We may need to reschedule some directory stuff if our status changed. */
  2182. if (old_options) {
  2183. if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
  2184. dirvote_recalculate_timing(options, time(NULL));
  2185. if (!bool_eq(directory_fetches_dir_info_early(options),
  2186. directory_fetches_dir_info_early(old_options)) ||
  2187. !bool_eq(directory_fetches_dir_info_later(options),
  2188. directory_fetches_dir_info_later(old_options))) {
  2189. /* Make sure update_router_have_minimum_dir_info() gets called. */
  2190. router_dir_info_changed();
  2191. /* We might need to download a new consensus status later or sooner than
  2192. * we had expected. */
  2193. update_consensus_networkstatus_fetch_time(time(NULL));
  2194. }
  2195. }
  2196. /* DoS mitigation subsystem only applies to public relay. */
  2197. if (public_server_mode(options)) {
  2198. /* If we are configured as a relay, initialize the subsystem. Even on HUP,
  2199. * this is safe to call as it will load data from the current options
  2200. * or/and the consensus. */
  2201. dos_init();
  2202. } else if (old_options && public_server_mode(old_options)) {
  2203. /* Going from relay to non relay, clean it up. */
  2204. dos_free_all();
  2205. }
  2206. /* Load the webpage we're going to serve every time someone asks for '/' on
  2207. our DirPort. */
  2208. tor_free(global_dirfrontpagecontents);
  2209. if (options->DirPortFrontPage) {
  2210. global_dirfrontpagecontents =
  2211. read_file_to_str(options->DirPortFrontPage, 0, NULL);
  2212. if (!global_dirfrontpagecontents) {
  2213. log_warn(LD_CONFIG,
  2214. "DirPortFrontPage file '%s' not found. Continuing anyway.",
  2215. options->DirPortFrontPage);
  2216. }
  2217. }
  2218. return 0;
  2219. }
  2220. typedef enum {
  2221. TAKES_NO_ARGUMENT = 0,
  2222. ARGUMENT_NECESSARY = 1,
  2223. ARGUMENT_OPTIONAL = 2
  2224. } takes_argument_t;
  2225. static const struct {
  2226. const char *name;
  2227. takes_argument_t takes_argument;
  2228. } CMDLINE_ONLY_OPTIONS[] = {
  2229. { "-f", ARGUMENT_NECESSARY },
  2230. { "--allow-missing-torrc", TAKES_NO_ARGUMENT },
  2231. { "--defaults-torrc", ARGUMENT_NECESSARY },
  2232. { "--hash-password", ARGUMENT_NECESSARY },
  2233. { "--dump-config", ARGUMENT_OPTIONAL },
  2234. { "--list-fingerprint", TAKES_NO_ARGUMENT },
  2235. { "--keygen", TAKES_NO_ARGUMENT },
  2236. { "--key-expiration", ARGUMENT_OPTIONAL },
  2237. { "--newpass", TAKES_NO_ARGUMENT },
  2238. { "--no-passphrase", TAKES_NO_ARGUMENT },
  2239. { "--passphrase-fd", ARGUMENT_NECESSARY },
  2240. { "--verify-config", TAKES_NO_ARGUMENT },
  2241. { "--ignore-missing-torrc", TAKES_NO_ARGUMENT },
  2242. { "--quiet", TAKES_NO_ARGUMENT },
  2243. { "--hush", TAKES_NO_ARGUMENT },
  2244. { "--version", TAKES_NO_ARGUMENT },
  2245. { "--library-versions", TAKES_NO_ARGUMENT },
  2246. { "-h", TAKES_NO_ARGUMENT },
  2247. { "--help", TAKES_NO_ARGUMENT },
  2248. { "--list-torrc-options", TAKES_NO_ARGUMENT },
  2249. { "--list-deprecated-options",TAKES_NO_ARGUMENT },
  2250. { "--nt-service", TAKES_NO_ARGUMENT },
  2251. { "-nt-service", TAKES_NO_ARGUMENT },
  2252. { NULL, 0 },
  2253. };
  2254. /** Helper: Read a list of configuration options from the command line. If
  2255. * successful, or if ignore_errors is set, put them in *<b>result</b>, put the
  2256. * commandline-only options in *<b>cmdline_result</b>, and return 0;
  2257. * otherwise, return -1 and leave *<b>result</b> and <b>cmdline_result</b>
  2258. * alone. */
  2259. int
  2260. config_parse_commandline(int argc, char **argv, int ignore_errors,
  2261. config_line_t **result,
  2262. config_line_t **cmdline_result)
  2263. {
  2264. config_line_t *param = NULL;
  2265. config_line_t *front = NULL;
  2266. config_line_t **new = &front;
  2267. config_line_t *front_cmdline = NULL;
  2268. config_line_t **new_cmdline = &front_cmdline;
  2269. char *s, *arg;
  2270. int i = 1;
  2271. while (i < argc) {
  2272. unsigned command = CONFIG_LINE_NORMAL;
  2273. takes_argument_t want_arg = ARGUMENT_NECESSARY;
  2274. int is_cmdline = 0;
  2275. int j;
  2276. for (j = 0; CMDLINE_ONLY_OPTIONS[j].name != NULL; ++j) {
  2277. if (!strcmp(argv[i], CMDLINE_ONLY_OPTIONS[j].name)) {
  2278. is_cmdline = 1;
  2279. want_arg = CMDLINE_ONLY_OPTIONS[j].takes_argument;
  2280. break;
  2281. }
  2282. }
  2283. s = argv[i];
  2284. /* Each keyword may be prefixed with one or two dashes. */
  2285. if (*s == '-')
  2286. s++;
  2287. if (*s == '-')
  2288. s++;
  2289. /* Figure out the command, if any. */
  2290. if (*s == '+') {
  2291. s++;
  2292. command = CONFIG_LINE_APPEND;
  2293. } else if (*s == '/') {
  2294. s++;
  2295. command = CONFIG_LINE_CLEAR;
  2296. /* A 'clear' command has no argument. */
  2297. want_arg = 0;
  2298. }
  2299. const int is_last = (i == argc-1);
  2300. if (want_arg == ARGUMENT_NECESSARY && is_last) {
  2301. if (ignore_errors) {
  2302. arg = tor_strdup("");
  2303. } else {
  2304. log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
  2305. argv[i]);
  2306. config_free_lines(front);
  2307. config_free_lines(front_cmdline);
  2308. return -1;
  2309. }
  2310. } else if (want_arg == ARGUMENT_OPTIONAL && is_last) {
  2311. arg = tor_strdup("");
  2312. } else {
  2313. arg = (want_arg != TAKES_NO_ARGUMENT) ? tor_strdup(argv[i+1]) :
  2314. tor_strdup("");
  2315. }
  2316. param = tor_malloc_zero(sizeof(config_line_t));
  2317. param->key = is_cmdline ? tor_strdup(argv[i]) :
  2318. tor_strdup(config_expand_abbrev(&options_format, s, 1, 1));
  2319. param->value = arg;
  2320. param->command = command;
  2321. param->next = NULL;
  2322. log_debug(LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
  2323. param->key, param->value);
  2324. if (is_cmdline) {
  2325. *new_cmdline = param;
  2326. new_cmdline = &((*new_cmdline)->next);
  2327. } else {
  2328. *new = param;
  2329. new = &((*new)->next);
  2330. }
  2331. i += want_arg ? 2 : 1;
  2332. }
  2333. *cmdline_result = front_cmdline;
  2334. *result = front;
  2335. return 0;
  2336. }
  2337. /** Return true iff key is a valid configuration option. */
  2338. int
  2339. option_is_recognized(const char *key)
  2340. {
  2341. const config_var_t *var = config_find_option(&options_format, key);
  2342. return (var != NULL);
  2343. }
  2344. /** Return the canonical name of a configuration option, or NULL
  2345. * if no such option exists. */
  2346. const char *
  2347. option_get_canonical_name(const char *key)
  2348. {
  2349. const config_var_t *var = config_find_option(&options_format, key);
  2350. return var ? var->name : NULL;
  2351. }
  2352. /** Return a canonical list of the options assigned for key.
  2353. */
  2354. config_line_t *
  2355. option_get_assignment(const or_options_t *options, const char *key)
  2356. {
  2357. return config_get_assigned_option(&options_format, options, key, 1);
  2358. }
  2359. /** Try assigning <b>list</b> to the global options. You do this by duping
  2360. * options, assigning list to the new one, then validating it. If it's
  2361. * ok, then throw out the old one and stick with the new one. Else,
  2362. * revert to old and return failure. Return SETOPT_OK on success, or
  2363. * a setopt_err_t on failure.
  2364. *
  2365. * If not success, point *<b>msg</b> to a newly allocated string describing
  2366. * what went wrong.
  2367. */
  2368. setopt_err_t
  2369. options_trial_assign(config_line_t *list, unsigned flags, char **msg)
  2370. {
  2371. int r;
  2372. or_options_t *trial_options = config_dup(&options_format, get_options());
  2373. if ((r=config_assign(&options_format, trial_options,
  2374. list, flags, msg)) < 0) {
  2375. or_options_free(trial_options);
  2376. return r;
  2377. }
  2378. setopt_err_t rv;
  2379. or_options_t *cur_options = get_options_mutable();
  2380. in_option_validation = 1;
  2381. if (options_validate(cur_options, trial_options,
  2382. global_default_options, 1, msg) < 0) {
  2383. or_options_free(trial_options);
  2384. rv = SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
  2385. goto done;
  2386. }
  2387. if (options_transition_allowed(cur_options, trial_options, msg) < 0) {
  2388. or_options_free(trial_options);
  2389. rv = SETOPT_ERR_TRANSITION;
  2390. goto done;
  2391. }
  2392. in_option_validation = 0;
  2393. if (set_options(trial_options, msg)<0) {
  2394. or_options_free(trial_options);
  2395. rv = SETOPT_ERR_SETTING;
  2396. goto done;
  2397. }
  2398. /* we liked it. put it in place. */
  2399. rv = SETOPT_OK;
  2400. done:
  2401. in_option_validation = 0;
  2402. return rv;
  2403. }
  2404. /** Print a usage message for tor. */
  2405. static void
  2406. print_usage(void)
  2407. {
  2408. printf(
  2409. "Copyright (c) 2001-2004, Roger Dingledine\n"
  2410. "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
  2411. "Copyright (c) 2007-2017, The Tor Project, Inc.\n\n"
  2412. "tor -f <torrc> [args]\n"
  2413. "See man page for options, or https://www.torproject.org/ for "
  2414. "documentation.\n");
  2415. }
  2416. /** Print all non-obsolete torrc options. */
  2417. static void
  2418. list_torrc_options(void)
  2419. {
  2420. int i;
  2421. for (i = 0; option_vars_[i].name; ++i) {
  2422. const config_var_t *var = &option_vars_[i];
  2423. if (var->type == CONFIG_TYPE_OBSOLETE ||
  2424. var->type == CONFIG_TYPE_LINELIST_V)
  2425. continue;
  2426. printf("%s\n", var->name);
  2427. }
  2428. }
  2429. /** Print all deprecated but non-obsolete torrc options. */
  2430. static void
  2431. list_deprecated_options(void)
  2432. {
  2433. const config_deprecation_t *d;
  2434. for (d = option_deprecation_notes_; d->name; ++d) {
  2435. printf("%s\n", d->name);
  2436. }
  2437. }
  2438. /** Last value actually set by resolve_my_address. */
  2439. static uint32_t last_resolved_addr = 0;
  2440. /** Accessor for last_resolved_addr from outside this file. */
  2441. uint32_t
  2442. get_last_resolved_addr(void)
  2443. {
  2444. return last_resolved_addr;
  2445. }
  2446. /** Reset last_resolved_addr from outside this file. */
  2447. void
  2448. reset_last_resolved_addr(void)
  2449. {
  2450. last_resolved_addr = 0;
  2451. }
  2452. /* Return true if <b>options</b> is using the default authorities, and false
  2453. * if any authority-related option has been overridden. */
  2454. int
  2455. using_default_dir_authorities(const or_options_t *options)
  2456. {
  2457. return (!options->DirAuthorities && !options->AlternateDirAuthority);
  2458. }
  2459. /**
  2460. * Attempt getting our non-local (as judged by tor_addr_is_internal()
  2461. * function) IP address using following techniques, listed in
  2462. * order from best (most desirable, try first) to worst (least
  2463. * desirable, try if everything else fails).
  2464. *
  2465. * First, attempt using <b>options-\>Address</b> to get our
  2466. * non-local IP address.
  2467. *
  2468. * If <b>options-\>Address</b> represents a non-local IP address,
  2469. * consider it ours.
  2470. *
  2471. * If <b>options-\>Address</b> is a DNS name that resolves to
  2472. * a non-local IP address, consider this IP address ours.
  2473. *
  2474. * If <b>options-\>Address</b> is NULL, fall back to getting local
  2475. * hostname and using it in above-described ways to try and
  2476. * get our IP address.
  2477. *
  2478. * In case local hostname cannot be resolved to a non-local IP
  2479. * address, try getting an IP address of network interface
  2480. * in hopes it will be non-local one.
  2481. *
  2482. * Fail if one or more of the following is true:
  2483. * - DNS name in <b>options-\>Address</b> cannot be resolved.
  2484. * - <b>options-\>Address</b> is a local host address.
  2485. * - Attempt at getting local hostname fails.
  2486. * - Attempt at getting network interface address fails.
  2487. *
  2488. * Return 0 if all is well, or -1 if we can't find a suitable
  2489. * public IP address.
  2490. *
  2491. * If we are returning 0:
  2492. * - Put our public IP address (in host order) into *<b>addr_out</b>.
  2493. * - If <b>method_out</b> is non-NULL, set *<b>method_out</b> to a static
  2494. * string describing how we arrived at our answer.
  2495. * - "CONFIGURED" - parsed from IP address string in
  2496. * <b>options-\>Address</b>
  2497. * - "RESOLVED" - resolved from DNS name in <b>options-\>Address</b>
  2498. * - "GETHOSTNAME" - resolved from a local hostname.
  2499. * - "INTERFACE" - retrieved from a network interface.
  2500. * - If <b>hostname_out</b> is non-NULL, and we resolved a hostname to
  2501. * get our address, set *<b>hostname_out</b> to a newly allocated string
  2502. * holding that hostname. (If we didn't get our address by resolving a
  2503. * hostname, set *<b>hostname_out</b> to NULL.)
  2504. *
  2505. * XXXX ipv6
  2506. */
  2507. int
  2508. resolve_my_address(int warn_severity, const or_options_t *options,
  2509. uint32_t *addr_out,
  2510. const char **method_out, char **hostname_out)
  2511. {
  2512. struct in_addr in;
  2513. uint32_t addr; /* host order */
  2514. char hostname[256];
  2515. const char *method_used;
  2516. const char *hostname_used;
  2517. int explicit_ip=1;
  2518. int explicit_hostname=1;
  2519. int from_interface=0;
  2520. char *addr_string = NULL;
  2521. const char *address = options->Address;
  2522. int notice_severity = warn_severity <= LOG_NOTICE ?
  2523. LOG_NOTICE : warn_severity;
  2524. tor_addr_t myaddr;
  2525. tor_assert(addr_out);
  2526. /*
  2527. * Step one: Fill in 'hostname' to be our best guess.
  2528. */
  2529. if (address && *address) {
  2530. strlcpy(hostname, address, sizeof(hostname));
  2531. } else { /* then we need to guess our address */
  2532. explicit_ip = 0; /* it's implicit */
  2533. explicit_hostname = 0; /* it's implicit */
  2534. if (tor_gethostname(hostname, sizeof(hostname)) < 0) {
  2535. log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
  2536. return -1;
  2537. }
  2538. log_debug(LD_CONFIG, "Guessed local host name as '%s'", hostname);
  2539. }
  2540. /*
  2541. * Step two: Now that we know 'hostname', parse it or resolve it. If
  2542. * it doesn't parse or resolve, look at the interface address. Set 'addr'
  2543. * to be our (host-order) 32-bit answer.
  2544. */
  2545. if (tor_inet_aton(hostname, &in) == 0) {
  2546. /* then we have to resolve it */
  2547. explicit_ip = 0;
  2548. if (tor_lookup_hostname(hostname, &addr)) { /* failed to resolve */
  2549. uint32_t interface_ip; /* host order */
  2550. if (explicit_hostname) {
  2551. log_fn(warn_severity, LD_CONFIG,
  2552. "Could not resolve local Address '%s'. Failing.", hostname);
  2553. return -1;
  2554. }
  2555. log_fn(notice_severity, LD_CONFIG,
  2556. "Could not resolve guessed local hostname '%s'. "
  2557. "Trying something else.", hostname);
  2558. if (get_interface_address(warn_severity, &interface_ip)) {
  2559. log_fn(warn_severity, LD_CONFIG,
  2560. "Could not get local interface IP address. Failing.");
  2561. return -1;
  2562. }
  2563. from_interface = 1;
  2564. addr = interface_ip;
  2565. log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
  2566. "local interface. Using that.", fmt_addr32(addr));
  2567. strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
  2568. } else { /* resolved hostname into addr */
  2569. tor_addr_from_ipv4h(&myaddr, addr);
  2570. if (!explicit_hostname &&
  2571. tor_addr_is_internal(&myaddr, 0)) {
  2572. tor_addr_t interface_ip;
  2573. log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
  2574. "resolves to a private IP address (%s). Trying something "
  2575. "else.", hostname, fmt_addr32(addr));
  2576. if (get_interface_address6(warn_severity, AF_INET, &interface_ip)<0) {
  2577. log_fn(warn_severity, LD_CONFIG,
  2578. "Could not get local interface IP address. Too bad.");
  2579. } else if (tor_addr_is_internal(&interface_ip, 0)) {
  2580. log_fn(notice_severity, LD_CONFIG,
  2581. "Interface IP address '%s' is a private address too. "
  2582. "Ignoring.", fmt_addr(&interface_ip));
  2583. } else {
  2584. from_interface = 1;
  2585. addr = tor_addr_to_ipv4h(&interface_ip);
  2586. log_fn(notice_severity, LD_CONFIG,
  2587. "Learned IP address '%s' for local interface."
  2588. " Using that.", fmt_addr32(addr));
  2589. strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
  2590. }
  2591. }
  2592. }
  2593. } else {
  2594. addr = ntohl(in.s_addr); /* set addr so that addr_string is not
  2595. * illformed */
  2596. }
  2597. /*
  2598. * Step three: Check whether 'addr' is an internal IP address, and error
  2599. * out if it is and we don't want that.
  2600. */
  2601. tor_addr_from_ipv4h(&myaddr,addr);
  2602. addr_string = tor_dup_ip(addr);
  2603. if (tor_addr_is_internal(&myaddr, 0)) {
  2604. /* make sure we're ok with publishing an internal IP */
  2605. if (using_default_dir_authorities(options)) {
  2606. /* if they are using the default authorities, disallow internal IPs
  2607. * always. */
  2608. log_fn(warn_severity, LD_CONFIG,
  2609. "Address '%s' resolves to private IP address '%s'. "
  2610. "Tor servers that use the default DirAuthorities must have "
  2611. "public IP addresses.", hostname, addr_string);
  2612. tor_free(addr_string);
  2613. return -1;
  2614. }
  2615. if (!explicit_ip) {
  2616. /* even if they've set their own authorities, require an explicit IP if
  2617. * they're using an internal address. */
  2618. log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
  2619. "IP address '%s'. Please set the Address config option to be "
  2620. "the IP address you want to use.", hostname, addr_string);
  2621. tor_free(addr_string);
  2622. return -1;
  2623. }
  2624. }
  2625. /*
  2626. * Step four: We have a winner! 'addr' is our answer for sure, and
  2627. * 'addr_string' is its string form. Fill out the various fields to
  2628. * say how we decided it.
  2629. */
  2630. log_debug(LD_CONFIG, "Resolved Address to '%s'.", addr_string);
  2631. if (explicit_ip) {
  2632. method_used = "CONFIGURED";
  2633. hostname_used = NULL;
  2634. } else if (explicit_hostname) {
  2635. method_used = "RESOLVED";
  2636. hostname_used = hostname;
  2637. } else if (from_interface) {
  2638. method_used = "INTERFACE";
  2639. hostname_used = NULL;
  2640. } else {
  2641. method_used = "GETHOSTNAME";
  2642. hostname_used = hostname;
  2643. }
  2644. *addr_out = addr;
  2645. if (method_out)
  2646. *method_out = method_used;
  2647. if (hostname_out)
  2648. *hostname_out = hostname_used ? tor_strdup(hostname_used) : NULL;
  2649. /*
  2650. * Step five: Check if the answer has changed since last time (or if
  2651. * there was no last time), and if so call various functions to keep
  2652. * us up-to-date.
  2653. */
  2654. if (last_resolved_addr && last_resolved_addr != *addr_out) {
  2655. /* Leave this as a notice, regardless of the requested severity,
  2656. * at least until dynamic IP address support becomes bulletproof. */
  2657. log_notice(LD_NET,
  2658. "Your IP address seems to have changed to %s "
  2659. "(METHOD=%s%s%s). Updating.",
  2660. addr_string, method_used,
  2661. hostname_used ? " HOSTNAME=" : "",
  2662. hostname_used ? hostname_used : "");
  2663. ip_address_changed(0);
  2664. }
  2665. if (last_resolved_addr != *addr_out) {
  2666. control_event_server_status(LOG_NOTICE,
  2667. "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s%s%s",
  2668. addr_string, method_used,
  2669. hostname_used ? " HOSTNAME=" : "",
  2670. hostname_used ? hostname_used : "");
  2671. }
  2672. last_resolved_addr = *addr_out;
  2673. /*
  2674. * And finally, clean up and return success.
  2675. */
  2676. tor_free(addr_string);
  2677. return 0;
  2678. }
  2679. /** Return true iff <b>addr</b> is judged to be on the same network as us, or
  2680. * on a private network.
  2681. */
  2682. MOCK_IMPL(int,
  2683. is_local_addr, (const tor_addr_t *addr))
  2684. {
  2685. if (tor_addr_is_internal(addr, 0))
  2686. return 1;
  2687. /* Check whether ip is on the same /24 as we are. */
  2688. if (get_options()->EnforceDistinctSubnets == 0)
  2689. return 0;
  2690. if (tor_addr_family(addr) == AF_INET) {
  2691. uint32_t ip = tor_addr_to_ipv4h(addr);
  2692. /* It's possible that this next check will hit before the first time
  2693. * resolve_my_address actually succeeds. (For clients, it is likely that
  2694. * resolve_my_address will never be called at all). In those cases,
  2695. * last_resolved_addr will be 0, and so checking to see whether ip is on
  2696. * the same /24 as last_resolved_addr will be the same as checking whether
  2697. * it was on net 0, which is already done by tor_addr_is_internal.
  2698. */
  2699. if ((last_resolved_addr & (uint32_t)0xffffff00ul)
  2700. == (ip & (uint32_t)0xffffff00ul))
  2701. return 1;
  2702. }
  2703. return 0;
  2704. }
  2705. /** Return a new empty or_options_t. Used for testing. */
  2706. or_options_t *
  2707. options_new(void)
  2708. {
  2709. return config_new(&options_format);
  2710. }
  2711. /** Set <b>options</b> to hold reasonable defaults for most options.
  2712. * Each option defaults to zero. */
  2713. void
  2714. options_init(or_options_t *options)
  2715. {
  2716. config_init(&options_format, options);
  2717. }
  2718. /** Return a string containing a possible configuration file that would give
  2719. * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
  2720. * include options that are the same as Tor's defaults.
  2721. */
  2722. char *
  2723. options_dump(const or_options_t *options, int how_to_dump)
  2724. {
  2725. const or_options_t *use_defaults;
  2726. int minimal;
  2727. switch (how_to_dump) {
  2728. case OPTIONS_DUMP_MINIMAL:
  2729. use_defaults = global_default_options;
  2730. minimal = 1;
  2731. break;
  2732. case OPTIONS_DUMP_DEFAULTS:
  2733. use_defaults = NULL;
  2734. minimal = 1;
  2735. break;
  2736. case OPTIONS_DUMP_ALL:
  2737. use_defaults = NULL;
  2738. minimal = 0;
  2739. break;
  2740. default:
  2741. log_warn(LD_BUG, "Bogus value for how_to_dump==%d", how_to_dump);
  2742. return NULL;
  2743. }
  2744. return config_dump(&options_format, use_defaults, options, minimal, 0);
  2745. }
  2746. /** Return 0 if every element of sl is a string holding a decimal
  2747. * representation of a port number, or if sl is NULL.
  2748. * Otherwise set *msg and return -1. */
  2749. static int
  2750. validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
  2751. {
  2752. int i;
  2753. tor_assert(name);
  2754. if (!sl)
  2755. return 0;
  2756. SMARTLIST_FOREACH(sl, const char *, cp,
  2757. {
  2758. i = atoi(cp);
  2759. if (i < 1 || i > 65535) {
  2760. tor_asprintf(msg, "Port '%s' out of range in %s", cp, name);
  2761. return -1;
  2762. }
  2763. });
  2764. return 0;
  2765. }
  2766. /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
  2767. * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
  2768. * Else return 0.
  2769. */
  2770. static int
  2771. ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
  2772. {
  2773. if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
  2774. /* This handles an understandable special case where somebody says "2gb"
  2775. * whereas our actual maximum is 2gb-1 (INT_MAX) */
  2776. --*value;
  2777. }
  2778. if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
  2779. tor_asprintf(msg, "%s ("U64_FORMAT") must be at most %d",
  2780. desc, U64_PRINTF_ARG(*value),
  2781. ROUTER_MAX_DECLARED_BANDWIDTH);
  2782. return -1;
  2783. }
  2784. return 0;
  2785. }
  2786. /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
  2787. * and write it to <b>options</b>-\>PublishServerDescriptor_. Treat "1"
  2788. * as "v3" unless BridgeRelay is 1, in which case treat it as "bridge".
  2789. * Treat "0" as "".
  2790. * Return 0 on success or -1 if not a recognized authority type (in which
  2791. * case the value of PublishServerDescriptor_ is undefined). */
  2792. static int
  2793. compute_publishserverdescriptor(or_options_t *options)
  2794. {
  2795. smartlist_t *list = options->PublishServerDescriptor;
  2796. dirinfo_type_t *auth = &options->PublishServerDescriptor_;
  2797. *auth = NO_DIRINFO;
  2798. if (!list) /* empty list, answer is none */
  2799. return 0;
  2800. SMARTLIST_FOREACH_BEGIN(list, const char *, string) {
  2801. if (!strcasecmp(string, "v1"))
  2802. log_warn(LD_CONFIG, "PublishServerDescriptor v1 has no effect, because "
  2803. "there are no v1 directory authorities anymore.");
  2804. else if (!strcmp(string, "1"))
  2805. if (options->BridgeRelay)
  2806. *auth |= BRIDGE_DIRINFO;
  2807. else
  2808. *auth |= V3_DIRINFO;
  2809. else if (!strcasecmp(string, "v2"))
  2810. log_warn(LD_CONFIG, "PublishServerDescriptor v2 has no effect, because "
  2811. "there are no v2 directory authorities anymore.");
  2812. else if (!strcasecmp(string, "v3"))
  2813. *auth |= V3_DIRINFO;
  2814. else if (!strcasecmp(string, "bridge"))
  2815. *auth |= BRIDGE_DIRINFO;
  2816. else if (!strcasecmp(string, "hidserv"))
  2817. log_warn(LD_CONFIG,
  2818. "PublishServerDescriptor hidserv is invalid. See "
  2819. "PublishHidServDescriptors.");
  2820. else if (!strcasecmp(string, "") || !strcmp(string, "0"))
  2821. /* no authority */;
  2822. else
  2823. return -1;
  2824. } SMARTLIST_FOREACH_END(string);
  2825. return 0;
  2826. }
  2827. /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
  2828. * services can overload the directory system. */
  2829. #define MIN_REND_POST_PERIOD (10*60)
  2830. #define MIN_REND_POST_PERIOD_TESTING (5)
  2831. /** Highest allowable value for CircuitsAvailableTimeout.
  2832. * If this is too large, client connections will stay open for too long,
  2833. * incurring extra padding overhead. */
  2834. #define MAX_CIRCS_AVAILABLE_TIME (24*60*60)
  2835. /** Highest allowable value for RendPostPeriod. */
  2836. #define MAX_DIR_PERIOD ((7*24*60*60)/2)
  2837. /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
  2838. * will generate too many circuits and potentially overload the network. */
  2839. #define MIN_MAX_CIRCUIT_DIRTINESS 10
  2840. /** Highest allowable value for MaxCircuitDirtiness: prevents time_t
  2841. * overflows. */
  2842. #define MAX_MAX_CIRCUIT_DIRTINESS (30*24*60*60)
  2843. /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
  2844. * will generate too many circuits and potentially overload the network. */
  2845. #define MIN_CIRCUIT_STREAM_TIMEOUT 10
  2846. /** Lowest recommended value for CircuitBuildTimeout; if it is set too low
  2847. * and LearnCircuitBuildTimeout is off, the failure rate for circuit
  2848. * construction may be very high. In that case, if it is set below this
  2849. * threshold emit a warning.
  2850. * */
  2851. #define RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT (10)
  2852. static int
  2853. options_validate_cb(void *old_options, void *options, void *default_options,
  2854. int from_setconf, char **msg)
  2855. {
  2856. in_option_validation = 1;
  2857. int rv = options_validate(old_options, options, default_options,
  2858. from_setconf, msg);
  2859. in_option_validation = 0;
  2860. return rv;
  2861. }
  2862. #define REJECT(arg) \
  2863. STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
  2864. #if defined(__GNUC__) && __GNUC__ <= 3
  2865. #define COMPLAIN(args...) \
  2866. STMT_BEGIN log_warn(LD_CONFIG, args); STMT_END
  2867. #else
  2868. #define COMPLAIN(args, ...) \
  2869. STMT_BEGIN log_warn(LD_CONFIG, args, ##__VA_ARGS__); STMT_END
  2870. #endif /* defined(__GNUC__) && __GNUC__ <= 3 */
  2871. /** Log a warning message iff <b>filepath</b> is not absolute.
  2872. * Warning message must contain option name <b>option</b> and
  2873. * an absolute path that <b>filepath</b> will resolve to.
  2874. *
  2875. * In case <b>filepath</b> is absolute, do nothing.
  2876. *
  2877. * Return 1 if there were relative paths; 0 otherwise.
  2878. */
  2879. static int
  2880. warn_if_option_path_is_relative(const char *option,
  2881. char *filepath)
  2882. {
  2883. if (filepath && path_is_relative(filepath)) {
  2884. char *abs_path = make_path_absolute(filepath);
  2885. COMPLAIN("Path for %s (%s) is relative and will resolve to %s."
  2886. " Is this what you wanted?", option, filepath, abs_path);
  2887. tor_free(abs_path);
  2888. return 1;
  2889. }
  2890. return 0;
  2891. }
  2892. /** Scan <b>options</b> for occurrences of relative file/directory
  2893. * path and log a warning whenever it is found.
  2894. *
  2895. * Return 1 if there were relative paths; 0 otherwise.
  2896. */
  2897. static int
  2898. warn_about_relative_paths(or_options_t *options)
  2899. {
  2900. tor_assert(options);
  2901. int n = 0;
  2902. n += warn_if_option_path_is_relative("CookieAuthFile",
  2903. options->CookieAuthFile);
  2904. n += warn_if_option_path_is_relative("ExtORPortCookieAuthFile",
  2905. options->ExtORPortCookieAuthFile);
  2906. n += warn_if_option_path_is_relative("DirPortFrontPage",
  2907. options->DirPortFrontPage);
  2908. n += warn_if_option_path_is_relative("V3BandwidthsFile",
  2909. options->V3BandwidthsFile);
  2910. n += warn_if_option_path_is_relative("ControlPortWriteToFile",
  2911. options->ControlPortWriteToFile);
  2912. n += warn_if_option_path_is_relative("GeoIPFile",options->GeoIPFile);
  2913. n += warn_if_option_path_is_relative("GeoIPv6File",options->GeoIPv6File);
  2914. n += warn_if_option_path_is_relative("Log",options->DebugLogFile);
  2915. n += warn_if_option_path_is_relative("AccelDir",options->AccelDir);
  2916. n += warn_if_option_path_is_relative("DataDirectory",options->DataDirectory);
  2917. n += warn_if_option_path_is_relative("PidFile",options->PidFile);
  2918. for (config_line_t *hs_line = options->RendConfigLines; hs_line;
  2919. hs_line = hs_line->next) {
  2920. if (!strcasecmp(hs_line->key, "HiddenServiceDir"))
  2921. n += warn_if_option_path_is_relative("HiddenServiceDir",hs_line->value);
  2922. }
  2923. return n != 0;
  2924. }
  2925. /* Validate options related to the scheduler. From the Schedulers list, the
  2926. * SchedulerTypes_ list is created with int values so once we select the
  2927. * scheduler, which can happen anytime at runtime, we don't have to parse
  2928. * strings and thus be quick.
  2929. *
  2930. * Return 0 on success else -1 and msg is set with an error message. */
  2931. static int
  2932. options_validate_scheduler(or_options_t *options, char **msg)
  2933. {
  2934. tor_assert(options);
  2935. tor_assert(msg);
  2936. if (!options->Schedulers || smartlist_len(options->Schedulers) == 0) {
  2937. REJECT("Empty Schedulers list. Either remove the option so the defaults "
  2938. "can be used or set at least one value.");
  2939. }
  2940. /* Ok, we do have scheduler types, validate them. */
  2941. options->SchedulerTypes_ = smartlist_new();
  2942. SMARTLIST_FOREACH_BEGIN(options->Schedulers, const char *, type) {
  2943. int *sched_type;
  2944. if (!strcasecmp("KISTLite", type)) {
  2945. sched_type = tor_malloc_zero(sizeof(int));
  2946. *sched_type = SCHEDULER_KIST_LITE;
  2947. smartlist_add(options->SchedulerTypes_, sched_type);
  2948. } else if (!strcasecmp("KIST", type)) {
  2949. sched_type = tor_malloc_zero(sizeof(int));
  2950. *sched_type = SCHEDULER_KIST;
  2951. smartlist_add(options->SchedulerTypes_, sched_type);
  2952. } else if (!strcasecmp("Vanilla", type)) {
  2953. sched_type = tor_malloc_zero(sizeof(int));
  2954. *sched_type = SCHEDULER_VANILLA;
  2955. smartlist_add(options->SchedulerTypes_, sched_type);
  2956. } else {
  2957. tor_asprintf(msg, "Unknown type %s in option Schedulers. "
  2958. "Possible values are KIST, KISTLite and Vanilla.",
  2959. escaped(type));
  2960. return -1;
  2961. }
  2962. } SMARTLIST_FOREACH_END(type);
  2963. if (options->KISTSockBufSizeFactor < 0) {
  2964. REJECT("KISTSockBufSizeFactor must be at least 0");
  2965. }
  2966. /* Don't need to validate that the Interval is less than anything because
  2967. * zero is valid and all negative values are valid. */
  2968. if (options->KISTSchedRunInterval > KIST_SCHED_RUN_INTERVAL_MAX) {
  2969. tor_asprintf(msg, "KISTSchedRunInterval must not be more than %d (ms)",
  2970. KIST_SCHED_RUN_INTERVAL_MAX);
  2971. return -1;
  2972. }
  2973. return 0;
  2974. }
  2975. /* Validate options related to single onion services.
  2976. * Modifies some options that are incompatible with single onion services.
  2977. * On failure returns -1, and sets *msg to an error string.
  2978. * Returns 0 on success. */
  2979. STATIC int
  2980. options_validate_single_onion(or_options_t *options, char **msg)
  2981. {
  2982. /* The two single onion service options must have matching values. */
  2983. if (options->HiddenServiceSingleHopMode &&
  2984. !options->HiddenServiceNonAnonymousMode) {
  2985. REJECT("HiddenServiceSingleHopMode does not provide any server anonymity. "
  2986. "It must be used with HiddenServiceNonAnonymousMode set to 1.");
  2987. }
  2988. if (options->HiddenServiceNonAnonymousMode &&
  2989. !options->HiddenServiceSingleHopMode) {
  2990. REJECT("HiddenServiceNonAnonymousMode does not provide any server "
  2991. "anonymity. It must be used with HiddenServiceSingleHopMode set to "
  2992. "1.");
  2993. }
  2994. /* Now that we've checked that the two options are consistent, we can safely
  2995. * call the rend_service_* functions that abstract these options. */
  2996. /* If you run an anonymous client with an active Single Onion service, the
  2997. * client loses anonymity. */
  2998. const int client_port_set = (options->SocksPort_set ||
  2999. options->TransPort_set ||
  3000. options->NATDPort_set ||
  3001. options->DNSPort_set ||
  3002. options->HTTPTunnelPort_set);
  3003. if (rend_service_non_anonymous_mode_enabled(options) && client_port_set &&
  3004. !options->Tor2webMode) {
  3005. REJECT("HiddenServiceNonAnonymousMode is incompatible with using Tor as "
  3006. "an anonymous client. Please set Socks/Trans/NATD/DNSPort to 0, or "
  3007. "revert HiddenServiceNonAnonymousMode to 0.");
  3008. }
  3009. /* If you run a hidden service in non-anonymous mode, the hidden service
  3010. * loses anonymity, even if SOCKSPort / Tor2web mode isn't used. */
  3011. if (!rend_service_non_anonymous_mode_enabled(options) &&
  3012. options->RendConfigLines && options->Tor2webMode) {
  3013. REJECT("Non-anonymous (Tor2web) mode is incompatible with using Tor as a "
  3014. "hidden service. Please remove all HiddenServiceDir lines, or use "
  3015. "a version of tor compiled without --enable-tor2web-mode, or use "
  3016. "HiddenServiceNonAnonymousMode.");
  3017. }
  3018. if (rend_service_allow_non_anonymous_connection(options)
  3019. && options->UseEntryGuards) {
  3020. /* Single Onion services only use entry guards when uploading descriptors;
  3021. * all other connections are one-hop. Further, Single Onions causes the
  3022. * hidden service code to do things which break the path bias
  3023. * detector, and it's far easier to turn off entry guards (and
  3024. * thus the path bias detector with it) than to figure out how to
  3025. * make path bias compatible with single onions.
  3026. */
  3027. log_notice(LD_CONFIG,
  3028. "HiddenServiceSingleHopMode is enabled; disabling "
  3029. "UseEntryGuards.");
  3030. options->UseEntryGuards = 0;
  3031. }
  3032. return 0;
  3033. }
  3034. /** Return 0 if every setting in <b>options</b> is reasonable, is a
  3035. * permissible transition from <b>old_options</b>, and none of the
  3036. * testing-only settings differ from <b>default_options</b> unless in
  3037. * testing mode. Else return -1. Should have no side effects, except for
  3038. * normalizing the contents of <b>options</b>.
  3039. *
  3040. * On error, tor_strdup an error explanation into *<b>msg</b>.
  3041. *
  3042. * XXX
  3043. * If <b>from_setconf</b>, we were called by the controller, and our
  3044. * Log line should stay empty. If it's 0, then give us a default log
  3045. * if there are no logs defined.
  3046. */
  3047. STATIC int
  3048. options_validate(or_options_t *old_options, or_options_t *options,
  3049. or_options_t *default_options, int from_setconf, char **msg)
  3050. {
  3051. int i;
  3052. config_line_t *cl;
  3053. const char *uname = get_uname();
  3054. int n_ports=0;
  3055. int world_writable_control_socket=0;
  3056. tor_assert(msg);
  3057. *msg = NULL;
  3058. if (parse_ports(options, 1, msg, &n_ports,
  3059. &world_writable_control_socket) < 0)
  3060. return -1;
  3061. /* Set UseEntryGuards from the configured value, before we check it below.
  3062. * We change UseEntryGuards when it's incompatible with other options,
  3063. * but leave UseEntryGuards_option with the original value.
  3064. * Always use the value of UseEntryGuards, not UseEntryGuards_option. */
  3065. options->UseEntryGuards = options->UseEntryGuards_option;
  3066. if (warn_about_relative_paths(options) && options->RunAsDaemon) {
  3067. REJECT("You have specified at least one relative path (see above) "
  3068. "with the RunAsDaemon option. RunAsDaemon is not compatible "
  3069. "with relative paths.");
  3070. }
  3071. if (server_mode(options) &&
  3072. (!strcmpstart(uname, "Windows 95") ||
  3073. !strcmpstart(uname, "Windows 98") ||
  3074. !strcmpstart(uname, "Windows Me"))) {
  3075. log_warn(LD_CONFIG, "Tor is running as a server, but you are "
  3076. "running %s; this probably won't work. See "
  3077. "https://www.torproject.org/docs/faq.html#BestOSForRelay "
  3078. "for details.", uname);
  3079. }
  3080. if (parse_outbound_addresses(options, 1, msg) < 0)
  3081. return -1;
  3082. if (validate_data_directories(options)<0)
  3083. REJECT("Invalid DataDirectory");
  3084. if (options->Nickname == NULL) {
  3085. if (server_mode(options)) {
  3086. options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
  3087. }
  3088. } else {
  3089. if (!is_legal_nickname(options->Nickname)) {
  3090. tor_asprintf(msg,
  3091. "Nickname '%s', nicknames must be between 1 and 19 characters "
  3092. "inclusive, and must contain only the characters [a-zA-Z0-9].",
  3093. options->Nickname);
  3094. return -1;
  3095. }
  3096. }
  3097. if (server_mode(options) && !options->ContactInfo)
  3098. log_notice(LD_CONFIG, "Your ContactInfo config option is not set. "
  3099. "Please consider setting it, so we can contact you if your server is "
  3100. "misconfigured or something else goes wrong.");
  3101. /* Special case on first boot if no Log options are given. */
  3102. if (!options->Logs && !options->RunAsDaemon && !from_setconf) {
  3103. if (quiet_level == 0)
  3104. config_line_append(&options->Logs, "Log", "notice stdout");
  3105. else if (quiet_level == 1)
  3106. config_line_append(&options->Logs, "Log", "warn stdout");
  3107. }
  3108. /* Validate the tor_log(s) */
  3109. if (options_init_logs(old_options, options, 1)<0)
  3110. REJECT("Failed to validate Log options. See logs for details.");
  3111. if (authdir_mode(options)) {
  3112. /* confirm that our address isn't broken, so we can complain now */
  3113. uint32_t tmp;
  3114. if (resolve_my_address(LOG_WARN, options, &tmp, NULL, NULL) < 0)
  3115. REJECT("Failed to resolve/guess local address. See logs for details.");
  3116. }
  3117. if (server_mode(options) && options->RendConfigLines)
  3118. log_warn(LD_CONFIG,
  3119. "Tor is currently configured as a relay and a hidden service. "
  3120. "That's not very secure: you should probably run your hidden service "
  3121. "in a separate Tor process, at least -- see "
  3122. "https://trac.torproject.org/8742");
  3123. /* XXXX require that the only port not be DirPort? */
  3124. /* XXXX require that at least one port be listened-upon. */
  3125. if (n_ports == 0 && !options->RendConfigLines)
  3126. log_warn(LD_CONFIG,
  3127. "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
  3128. "undefined, and there aren't any hidden services configured. "
  3129. "Tor will still run, but probably won't do anything.");
  3130. options->TransProxyType_parsed = TPT_DEFAULT;
  3131. #ifdef USE_TRANSPARENT
  3132. if (options->TransProxyType) {
  3133. if (!strcasecmp(options->TransProxyType, "default")) {
  3134. options->TransProxyType_parsed = TPT_DEFAULT;
  3135. } else if (!strcasecmp(options->TransProxyType, "pf-divert")) {
  3136. #if !defined(OpenBSD) && !defined( DARWIN )
  3137. /* Later versions of OS X have pf */
  3138. REJECT("pf-divert is a OpenBSD-specific "
  3139. "and OS X/Darwin-specific feature.");
  3140. #else
  3141. options->TransProxyType_parsed = TPT_PF_DIVERT;
  3142. #endif /* !defined(OpenBSD) && !defined( DARWIN ) */
  3143. } else if (!strcasecmp(options->TransProxyType, "tproxy")) {
  3144. #if !defined(__linux__)
  3145. REJECT("TPROXY is a Linux-specific feature.");
  3146. #else
  3147. options->TransProxyType_parsed = TPT_TPROXY;
  3148. #endif
  3149. } else if (!strcasecmp(options->TransProxyType, "ipfw")) {
  3150. #ifndef KERNEL_MAY_SUPPORT_IPFW
  3151. /* Earlier versions of OS X have ipfw */
  3152. REJECT("ipfw is a FreeBSD-specific "
  3153. "and OS X/Darwin-specific feature.");
  3154. #else
  3155. options->TransProxyType_parsed = TPT_IPFW;
  3156. #endif /* !defined(KERNEL_MAY_SUPPORT_IPFW) */
  3157. } else {
  3158. REJECT("Unrecognized value for TransProxyType");
  3159. }
  3160. if (strcasecmp(options->TransProxyType, "default") &&
  3161. !options->TransPort_set) {
  3162. REJECT("Cannot use TransProxyType without any valid TransPort.");
  3163. }
  3164. }
  3165. #else /* !(defined(USE_TRANSPARENT)) */
  3166. if (options->TransPort_set)
  3167. REJECT("TransPort is disabled in this build.");
  3168. #endif /* defined(USE_TRANSPARENT) */
  3169. if (options->TokenBucketRefillInterval <= 0
  3170. || options->TokenBucketRefillInterval > 1000) {
  3171. REJECT("TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
  3172. }
  3173. if (options->ExcludeExitNodes || options->ExcludeNodes) {
  3174. options->ExcludeExitNodesUnion_ = routerset_new();
  3175. routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeExitNodes);
  3176. routerset_union(options->ExcludeExitNodesUnion_,options->ExcludeNodes);
  3177. }
  3178. if (options->NodeFamilies) {
  3179. options->NodeFamilySets = smartlist_new();
  3180. for (cl = options->NodeFamilies; cl; cl = cl->next) {
  3181. routerset_t *rs = routerset_new();
  3182. if (routerset_parse(rs, cl->value, cl->key) == 0) {
  3183. smartlist_add(options->NodeFamilySets, rs);
  3184. } else {
  3185. routerset_free(rs);
  3186. }
  3187. }
  3188. }
  3189. if (options->ExcludeNodes && options->StrictNodes) {
  3190. COMPLAIN("You have asked to exclude certain relays from all positions "
  3191. "in your circuits. Expect hidden services and other Tor "
  3192. "features to be broken in unpredictable ways.");
  3193. }
  3194. for (cl = options->RecommendedPackages; cl; cl = cl->next) {
  3195. if (! validate_recommended_package_line(cl->value)) {
  3196. log_warn(LD_CONFIG, "Invalid RecommendedPackage line %s will be ignored",
  3197. escaped(cl->value));
  3198. }
  3199. }
  3200. if (options->AuthoritativeDir) {
  3201. if (!options->ContactInfo && !options->TestingTorNetwork)
  3202. REJECT("Authoritative directory servers must set ContactInfo");
  3203. if (!options->RecommendedClientVersions)
  3204. options->RecommendedClientVersions =
  3205. config_lines_dup(options->RecommendedVersions);
  3206. if (!options->RecommendedServerVersions)
  3207. options->RecommendedServerVersions =
  3208. config_lines_dup(options->RecommendedVersions);
  3209. if (options->VersioningAuthoritativeDir &&
  3210. (!options->RecommendedClientVersions ||
  3211. !options->RecommendedServerVersions))
  3212. REJECT("Versioning authoritative dir servers must set "
  3213. "Recommended*Versions.");
  3214. if (options->UseEntryGuards) {
  3215. log_info(LD_CONFIG, "Authoritative directory servers can't set "
  3216. "UseEntryGuards. Disabling.");
  3217. options->UseEntryGuards = 0;
  3218. }
  3219. if (!options->DownloadExtraInfo && authdir_mode_v3(options)) {
  3220. log_info(LD_CONFIG, "Authoritative directories always try to download "
  3221. "extra-info documents. Setting DownloadExtraInfo.");
  3222. options->DownloadExtraInfo = 1;
  3223. }
  3224. if (!(options->BridgeAuthoritativeDir ||
  3225. options->V3AuthoritativeDir))
  3226. REJECT("AuthoritativeDir is set, but none of "
  3227. "(Bridge/V3)AuthoritativeDir is set.");
  3228. /* If we have a v3bandwidthsfile and it's broken, complain on startup */
  3229. if (options->V3BandwidthsFile && !old_options) {
  3230. dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
  3231. }
  3232. /* same for guardfraction file */
  3233. if (options->GuardfractionFile && !old_options) {
  3234. dirserv_read_guardfraction_file(options->GuardfractionFile, NULL);
  3235. }
  3236. }
  3237. if (options->AuthoritativeDir && !options->DirPort_set)
  3238. REJECT("Running as authoritative directory, but no DirPort set.");
  3239. if (options->AuthoritativeDir && !options->ORPort_set)
  3240. REJECT("Running as authoritative directory, but no ORPort set.");
  3241. if (options->AuthoritativeDir && options->ClientOnly)
  3242. REJECT("Running as authoritative directory, but ClientOnly also set.");
  3243. if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
  3244. REJECT("FetchDirInfoExtraEarly requires that you also set "
  3245. "FetchDirInfoEarly");
  3246. if (options->ConnLimit <= 0) {
  3247. tor_asprintf(msg,
  3248. "ConnLimit must be greater than 0, but was set to %d",
  3249. options->ConnLimit);
  3250. return -1;
  3251. }
  3252. if (options->PathsNeededToBuildCircuits >= 0.0) {
  3253. if (options->PathsNeededToBuildCircuits < 0.25) {
  3254. log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too low. Increasing "
  3255. "to 0.25");
  3256. options->PathsNeededToBuildCircuits = 0.25;
  3257. } else if (options->PathsNeededToBuildCircuits > 0.95) {
  3258. log_warn(LD_CONFIG, "PathsNeededToBuildCircuits is too high. Decreasing "
  3259. "to 0.95");
  3260. options->PathsNeededToBuildCircuits = 0.95;
  3261. }
  3262. }
  3263. if (options->MaxClientCircuitsPending <= 0 ||
  3264. options->MaxClientCircuitsPending > MAX_MAX_CLIENT_CIRCUITS_PENDING) {
  3265. tor_asprintf(msg,
  3266. "MaxClientCircuitsPending must be between 1 and %d, but "
  3267. "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING,
  3268. options->MaxClientCircuitsPending);
  3269. return -1;
  3270. }
  3271. if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
  3272. return -1;
  3273. if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
  3274. return -1;
  3275. if (validate_ports_csv(options->RejectPlaintextPorts,
  3276. "RejectPlaintextPorts", msg) < 0)
  3277. return -1;
  3278. if (validate_ports_csv(options->WarnPlaintextPorts,
  3279. "WarnPlaintextPorts", msg) < 0)
  3280. return -1;
  3281. if (options->FascistFirewall && !options->ReachableAddresses) {
  3282. if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
  3283. /* We already have firewall ports set, so migrate them to
  3284. * ReachableAddresses, which will set ReachableORAddresses and
  3285. * ReachableDirAddresses if they aren't set explicitly. */
  3286. smartlist_t *instead = smartlist_new();
  3287. config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
  3288. new_line->key = tor_strdup("ReachableAddresses");
  3289. /* If we're configured with the old format, we need to prepend some
  3290. * open ports. */
  3291. SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
  3292. {
  3293. int p = atoi(portno);
  3294. if (p<0) continue;
  3295. smartlist_add_asprintf(instead, "*:%d", p);
  3296. });
  3297. new_line->value = smartlist_join_strings(instead,",",0,NULL);
  3298. /* These have been deprecated since 0.1.1.5-alpha-cvs */
  3299. log_notice(LD_CONFIG,
  3300. "Converting FascistFirewall and FirewallPorts "
  3301. "config options to new format: \"ReachableAddresses %s\"",
  3302. new_line->value);
  3303. options->ReachableAddresses = new_line;
  3304. SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
  3305. smartlist_free(instead);
  3306. } else {
  3307. /* We do not have FirewallPorts set, so add 80 to
  3308. * ReachableDirAddresses, and 443 to ReachableORAddresses. */
  3309. if (!options->ReachableDirAddresses) {
  3310. config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
  3311. new_line->key = tor_strdup("ReachableDirAddresses");
  3312. new_line->value = tor_strdup("*:80");
  3313. options->ReachableDirAddresses = new_line;
  3314. log_notice(LD_CONFIG, "Converting FascistFirewall config option "
  3315. "to new format: \"ReachableDirAddresses *:80\"");
  3316. }
  3317. if (!options->ReachableORAddresses) {
  3318. config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
  3319. new_line->key = tor_strdup("ReachableORAddresses");
  3320. new_line->value = tor_strdup("*:443");
  3321. options->ReachableORAddresses = new_line;
  3322. log_notice(LD_CONFIG, "Converting FascistFirewall config option "
  3323. "to new format: \"ReachableORAddresses *:443\"");
  3324. }
  3325. }
  3326. }
  3327. /* Terminate Reachable*Addresses with reject *
  3328. */
  3329. for (i=0; i<3; i++) {
  3330. config_line_t **linep =
  3331. (i==0) ? &options->ReachableAddresses :
  3332. (i==1) ? &options->ReachableORAddresses :
  3333. &options->ReachableDirAddresses;
  3334. if (!*linep)
  3335. continue;
  3336. /* We need to end with a reject *:*, not an implicit accept *:* */
  3337. for (;;) {
  3338. linep = &((*linep)->next);
  3339. if (!*linep) {
  3340. *linep = tor_malloc_zero(sizeof(config_line_t));
  3341. (*linep)->key = tor_strdup(
  3342. (i==0) ? "ReachableAddresses" :
  3343. (i==1) ? "ReachableORAddresses" :
  3344. "ReachableDirAddresses");
  3345. (*linep)->value = tor_strdup("reject *:*");
  3346. break;
  3347. }
  3348. }
  3349. }
  3350. if ((options->ReachableAddresses ||
  3351. options->ReachableORAddresses ||
  3352. options->ReachableDirAddresses ||
  3353. options->ClientUseIPv4 == 0) &&
  3354. server_mode(options))
  3355. REJECT("Servers must be able to freely connect to the rest "
  3356. "of the Internet, so they must not set Reachable*Addresses "
  3357. "or FascistFirewall or FirewallPorts or ClientUseIPv4 0.");
  3358. if (options->UseBridges &&
  3359. server_mode(options))
  3360. REJECT("Servers must be able to freely connect to the rest "
  3361. "of the Internet, so they must not set UseBridges.");
  3362. /* If both of these are set, we'll end up with funny behavior where we
  3363. * demand enough entrynodes be up and running else we won't build
  3364. * circuits, yet we never actually use them. */
  3365. if (options->UseBridges && options->EntryNodes)
  3366. REJECT("You cannot set both UseBridges and EntryNodes.");
  3367. /* If we have UseBridges as 1 and UseEntryGuards as 0, we end up bypassing
  3368. * the use of bridges */
  3369. if (options->UseBridges && !options->UseEntryGuards)
  3370. REJECT("Setting UseBridges requires also setting UseEntryGuards.");
  3371. options->MaxMemInQueues =
  3372. compute_real_max_mem_in_queues(options->MaxMemInQueues_raw,
  3373. server_mode(options));
  3374. options->MaxMemInQueues_low_threshold = (options->MaxMemInQueues / 4) * 3;
  3375. if (!options->SafeLogging ||
  3376. !strcasecmp(options->SafeLogging, "0")) {
  3377. options->SafeLogging_ = SAFELOG_SCRUB_NONE;
  3378. } else if (!strcasecmp(options->SafeLogging, "relay")) {
  3379. options->SafeLogging_ = SAFELOG_SCRUB_RELAY;
  3380. } else if (!strcasecmp(options->SafeLogging, "1")) {
  3381. options->SafeLogging_ = SAFELOG_SCRUB_ALL;
  3382. } else {
  3383. tor_asprintf(msg,
  3384. "Unrecognized value '%s' in SafeLogging",
  3385. escaped(options->SafeLogging));
  3386. return -1;
  3387. }
  3388. if (compute_publishserverdescriptor(options) < 0) {
  3389. tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
  3390. return -1;
  3391. }
  3392. if ((options->BridgeRelay
  3393. || options->PublishServerDescriptor_ & BRIDGE_DIRINFO)
  3394. && (options->PublishServerDescriptor_ & V3_DIRINFO)) {
  3395. REJECT("Bridges are not supposed to publish router descriptors to the "
  3396. "directory authorities. Please correct your "
  3397. "PublishServerDescriptor line.");
  3398. }
  3399. if (options->BridgeRelay && options->DirPort_set) {
  3400. log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
  3401. "DirPort");
  3402. config_free_lines(options->DirPort_lines);
  3403. options->DirPort_lines = NULL;
  3404. options->DirPort_set = 0;
  3405. }
  3406. if (server_mode(options) && options->ConnectionPadding != -1) {
  3407. REJECT("Relays must use 'auto' for the ConnectionPadding setting.");
  3408. }
  3409. if (server_mode(options) && options->ReducedConnectionPadding != 0) {
  3410. REJECT("Relays cannot set ReducedConnectionPadding. ");
  3411. }
  3412. if (options->BridgeDistribution) {
  3413. if (!options->BridgeRelay) {
  3414. REJECT("You set BridgeDistribution, but you didn't set BridgeRelay!");
  3415. }
  3416. if (check_bridge_distribution_setting(options->BridgeDistribution) < 0) {
  3417. REJECT("Invalid BridgeDistribution value.");
  3418. }
  3419. }
  3420. if (options->MinUptimeHidServDirectoryV2 < 0) {
  3421. log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
  3422. "least 0 seconds. Changing to 0.");
  3423. options->MinUptimeHidServDirectoryV2 = 0;
  3424. }
  3425. const int min_rendpostperiod =
  3426. options->TestingTorNetwork ?
  3427. MIN_REND_POST_PERIOD_TESTING : MIN_REND_POST_PERIOD;
  3428. if (options->RendPostPeriod < min_rendpostperiod) {
  3429. log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
  3430. "raising to %d seconds.", min_rendpostperiod);
  3431. options->RendPostPeriod = min_rendpostperiod;
  3432. }
  3433. if (options->RendPostPeriod > MAX_DIR_PERIOD) {
  3434. log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
  3435. MAX_DIR_PERIOD);
  3436. options->RendPostPeriod = MAX_DIR_PERIOD;
  3437. }
  3438. /* Check the Single Onion Service options */
  3439. if (options_validate_single_onion(options, msg) < 0)
  3440. return -1;
  3441. if (options->CircuitsAvailableTimeout > MAX_CIRCS_AVAILABLE_TIME) {
  3442. // options_t is immutable for new code (the above code is older),
  3443. // so just make the user fix the value themselves rather than
  3444. // silently keep a shadow value lower than what they asked for.
  3445. REJECT("CircuitsAvailableTimeout is too large. Max is 24 hours.");
  3446. }
  3447. #ifdef ENABLE_TOR2WEB_MODE
  3448. if (options->Tor2webMode && options->UseEntryGuards) {
  3449. /* tor2web mode clients do not (and should not) use entry guards
  3450. * in any meaningful way. Further, tor2web mode causes the hidden
  3451. * service client code to do things which break the path bias
  3452. * detector, and it's far easier to turn off entry guards (and
  3453. * thus the path bias detector with it) than to figure out how to
  3454. * make a piece of code which cannot possibly help tor2web mode
  3455. * users compatible with tor2web mode.
  3456. */
  3457. log_notice(LD_CONFIG,
  3458. "Tor2WebMode is enabled; disabling UseEntryGuards.");
  3459. options->UseEntryGuards = 0;
  3460. }
  3461. #endif /* defined(ENABLE_TOR2WEB_MODE) */
  3462. if (options->Tor2webRendezvousPoints && !options->Tor2webMode) {
  3463. REJECT("Tor2webRendezvousPoints cannot be set without Tor2webMode.");
  3464. }
  3465. if (options->EntryNodes && !options->UseEntryGuards) {
  3466. REJECT("If EntryNodes is set, UseEntryGuards must be enabled.");
  3467. }
  3468. if (!(options->UseEntryGuards) &&
  3469. (options->RendConfigLines != NULL) &&
  3470. !rend_service_allow_non_anonymous_connection(options)) {
  3471. log_warn(LD_CONFIG,
  3472. "UseEntryGuards is disabled, but you have configured one or more "
  3473. "hidden services on this Tor instance. Your hidden services "
  3474. "will be very easy to locate using a well-known attack -- see "
  3475. "http://freehaven.net/anonbib/#hs-attack06 for details.");
  3476. }
  3477. if (options->EntryNodes &&
  3478. routerset_is_list(options->EntryNodes) &&
  3479. (routerset_len(options->EntryNodes) == 1) &&
  3480. (options->RendConfigLines != NULL)) {
  3481. tor_asprintf(msg,
  3482. "You have one single EntryNodes and at least one hidden service "
  3483. "configured. This is bad because it's very easy to locate your "
  3484. "entry guard which can then lead to the deanonymization of your "
  3485. "hidden service -- for more details, see "
  3486. "https://trac.torproject.org/projects/tor/ticket/14917. "
  3487. "For this reason, the use of one EntryNodes with an hidden "
  3488. "service is prohibited until a better solution is found.");
  3489. return -1;
  3490. }
  3491. /* Inform the hidden service operator that pinning EntryNodes can possibly
  3492. * be harmful for the service anonymity. */
  3493. if (options->EntryNodes &&
  3494. routerset_is_list(options->EntryNodes) &&
  3495. (options->RendConfigLines != NULL)) {
  3496. log_warn(LD_CONFIG,
  3497. "EntryNodes is set with multiple entries and at least one "
  3498. "hidden service is configured. Pinning entry nodes can possibly "
  3499. "be harmful to the service anonymity. Because of this, we "
  3500. "recommend you either don't do that or make sure you know what "
  3501. "you are doing. For more details, please look at "
  3502. "https://trac.torproject.org/projects/tor/ticket/21155.");
  3503. }
  3504. /* Single Onion Services: non-anonymous hidden services */
  3505. if (rend_service_non_anonymous_mode_enabled(options)) {
  3506. log_warn(LD_CONFIG,
  3507. "HiddenServiceNonAnonymousMode is set. Every hidden service on "
  3508. "this tor instance is NON-ANONYMOUS. If "
  3509. "the HiddenServiceNonAnonymousMode option is changed, Tor will "
  3510. "refuse to launch hidden services from the same directories, to "
  3511. "protect your anonymity against config errors. This setting is "
  3512. "for experimental use only.");
  3513. }
  3514. if (!options->LearnCircuitBuildTimeout && options->CircuitBuildTimeout &&
  3515. options->CircuitBuildTimeout < RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT) {
  3516. log_warn(LD_CONFIG,
  3517. "CircuitBuildTimeout is shorter (%d seconds) than the recommended "
  3518. "minimum (%d seconds), and LearnCircuitBuildTimeout is disabled. "
  3519. "If tor isn't working, raise this value or enable "
  3520. "LearnCircuitBuildTimeout.",
  3521. options->CircuitBuildTimeout,
  3522. RECOMMENDED_MIN_CIRCUIT_BUILD_TIMEOUT );
  3523. } else if (!options->LearnCircuitBuildTimeout &&
  3524. !options->CircuitBuildTimeout) {
  3525. int severity = LOG_NOTICE;
  3526. /* Be a little quieter if we've deliberately disabled
  3527. * LearnCircuitBuildTimeout. */
  3528. if (circuit_build_times_disabled_(options, 1)) {
  3529. severity = LOG_INFO;
  3530. }
  3531. log_fn(severity, LD_CONFIG, "You disabled LearnCircuitBuildTimeout, but "
  3532. "didn't specify a CircuitBuildTimeout. I'll pick a plausible "
  3533. "default.");
  3534. }
  3535. if (options->PathBiasNoticeRate > 1.0) {
  3536. tor_asprintf(msg,
  3537. "PathBiasNoticeRate is too high. "
  3538. "It must be between 0 and 1.0");
  3539. return -1;
  3540. }
  3541. if (options->PathBiasWarnRate > 1.0) {
  3542. tor_asprintf(msg,
  3543. "PathBiasWarnRate is too high. "
  3544. "It must be between 0 and 1.0");
  3545. return -1;
  3546. }
  3547. if (options->PathBiasExtremeRate > 1.0) {
  3548. tor_asprintf(msg,
  3549. "PathBiasExtremeRate is too high. "
  3550. "It must be between 0 and 1.0");
  3551. return -1;
  3552. }
  3553. if (options->PathBiasNoticeUseRate > 1.0) {
  3554. tor_asprintf(msg,
  3555. "PathBiasNoticeUseRate is too high. "
  3556. "It must be between 0 and 1.0");
  3557. return -1;
  3558. }
  3559. if (options->PathBiasExtremeUseRate > 1.0) {
  3560. tor_asprintf(msg,
  3561. "PathBiasExtremeUseRate is too high. "
  3562. "It must be between 0 and 1.0");
  3563. return -1;
  3564. }
  3565. if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
  3566. log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
  3567. "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
  3568. options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
  3569. }
  3570. if (options->MaxCircuitDirtiness > MAX_MAX_CIRCUIT_DIRTINESS) {
  3571. log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too high; "
  3572. "setting to %d days.", MAX_MAX_CIRCUIT_DIRTINESS/86400);
  3573. options->MaxCircuitDirtiness = MAX_MAX_CIRCUIT_DIRTINESS;
  3574. }
  3575. if (options->CircuitStreamTimeout &&
  3576. options->CircuitStreamTimeout < MIN_CIRCUIT_STREAM_TIMEOUT) {
  3577. log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
  3578. "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
  3579. options->CircuitStreamTimeout = MIN_CIRCUIT_STREAM_TIMEOUT;
  3580. }
  3581. if (options->HeartbeatPeriod &&
  3582. options->HeartbeatPeriod < MIN_HEARTBEAT_PERIOD) {
  3583. log_warn(LD_CONFIG, "HeartbeatPeriod option is too short; "
  3584. "raising to %d seconds.", MIN_HEARTBEAT_PERIOD);
  3585. options->HeartbeatPeriod = MIN_HEARTBEAT_PERIOD;
  3586. }
  3587. if (options->KeepalivePeriod < 1)
  3588. REJECT("KeepalivePeriod option must be positive.");
  3589. if (options->PortForwarding && options->Sandbox) {
  3590. REJECT("PortForwarding is not compatible with Sandbox; at most one can "
  3591. "be set");
  3592. }
  3593. if (options->PortForwarding && options->NoExec) {
  3594. COMPLAIN("Both PortForwarding and NoExec are set; PortForwarding will "
  3595. "be ignored.");
  3596. }
  3597. if (ensure_bandwidth_cap(&options->BandwidthRate,
  3598. "BandwidthRate", msg) < 0)
  3599. return -1;
  3600. if (ensure_bandwidth_cap(&options->BandwidthBurst,
  3601. "BandwidthBurst", msg) < 0)
  3602. return -1;
  3603. if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
  3604. "MaxAdvertisedBandwidth", msg) < 0)
  3605. return -1;
  3606. if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
  3607. "RelayBandwidthRate", msg) < 0)
  3608. return -1;
  3609. if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
  3610. "RelayBandwidthBurst", msg) < 0)
  3611. return -1;
  3612. if (ensure_bandwidth_cap(&options->PerConnBWRate,
  3613. "PerConnBWRate", msg) < 0)
  3614. return -1;
  3615. if (ensure_bandwidth_cap(&options->PerConnBWBurst,
  3616. "PerConnBWBurst", msg) < 0)
  3617. return -1;
  3618. if (ensure_bandwidth_cap(&options->AuthDirFastGuarantee,
  3619. "AuthDirFastGuarantee", msg) < 0)
  3620. return -1;
  3621. if (ensure_bandwidth_cap(&options->AuthDirGuardBWGuarantee,
  3622. "AuthDirGuardBWGuarantee", msg) < 0)
  3623. return -1;
  3624. if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
  3625. options->RelayBandwidthBurst = options->RelayBandwidthRate;
  3626. if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
  3627. options->RelayBandwidthRate = options->RelayBandwidthBurst;
  3628. if (server_mode(options)) {
  3629. const unsigned required_min_bw =
  3630. public_server_mode(options) ?
  3631. RELAY_REQUIRED_MIN_BANDWIDTH : BRIDGE_REQUIRED_MIN_BANDWIDTH;
  3632. const char * const optbridge =
  3633. public_server_mode(options) ? "" : "bridge ";
  3634. if (options->BandwidthRate < required_min_bw) {
  3635. tor_asprintf(msg,
  3636. "BandwidthRate is set to %d bytes/second. "
  3637. "For %sservers, it must be at least %u.",
  3638. (int)options->BandwidthRate, optbridge,
  3639. required_min_bw);
  3640. return -1;
  3641. } else if (options->MaxAdvertisedBandwidth <
  3642. required_min_bw/2) {
  3643. tor_asprintf(msg,
  3644. "MaxAdvertisedBandwidth is set to %d bytes/second. "
  3645. "For %sservers, it must be at least %u.",
  3646. (int)options->MaxAdvertisedBandwidth, optbridge,
  3647. required_min_bw/2);
  3648. return -1;
  3649. }
  3650. if (options->RelayBandwidthRate &&
  3651. options->RelayBandwidthRate < required_min_bw) {
  3652. tor_asprintf(msg,
  3653. "RelayBandwidthRate is set to %d bytes/second. "
  3654. "For %sservers, it must be at least %u.",
  3655. (int)options->RelayBandwidthRate, optbridge,
  3656. required_min_bw);
  3657. return -1;
  3658. }
  3659. }
  3660. if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
  3661. REJECT("RelayBandwidthBurst must be at least equal "
  3662. "to RelayBandwidthRate.");
  3663. if (options->BandwidthRate > options->BandwidthBurst)
  3664. REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
  3665. /* if they set relaybandwidth* really high but left bandwidth*
  3666. * at the default, raise the defaults. */
  3667. if (options->RelayBandwidthRate > options->BandwidthRate)
  3668. options->BandwidthRate = options->RelayBandwidthRate;
  3669. if (options->RelayBandwidthBurst > options->BandwidthBurst)
  3670. options->BandwidthBurst = options->RelayBandwidthBurst;
  3671. if (accounting_parse_options(options, 1)<0)
  3672. REJECT("Failed to parse accounting options. See logs for details.");
  3673. if (options->AccountingMax) {
  3674. if (options->RendConfigLines && server_mode(options)) {
  3675. log_warn(LD_CONFIG, "Using accounting with a hidden service and an "
  3676. "ORPort is risky: your hidden service(s) and your public "
  3677. "address will all turn off at the same time, which may alert "
  3678. "observers that they are being run by the same party.");
  3679. } else if (config_count_key(options->RendConfigLines,
  3680. "HiddenServiceDir") > 1) {
  3681. log_warn(LD_CONFIG, "Using accounting with multiple hidden services is "
  3682. "risky: they will all turn off at the same time, which may "
  3683. "alert observers that they are being run by the same party.");
  3684. }
  3685. }
  3686. options->AccountingRule = ACCT_MAX;
  3687. if (options->AccountingRule_option) {
  3688. if (!strcmp(options->AccountingRule_option, "sum"))
  3689. options->AccountingRule = ACCT_SUM;
  3690. else if (!strcmp(options->AccountingRule_option, "max"))
  3691. options->AccountingRule = ACCT_MAX;
  3692. else if (!strcmp(options->AccountingRule_option, "in"))
  3693. options->AccountingRule = ACCT_IN;
  3694. else if (!strcmp(options->AccountingRule_option, "out"))
  3695. options->AccountingRule = ACCT_OUT;
  3696. else
  3697. REJECT("AccountingRule must be 'sum', 'max', 'in', or 'out'");
  3698. }
  3699. if (options->DirPort_set && !options->DirCache) {
  3700. REJECT("DirPort configured but DirCache disabled. DirPort requires "
  3701. "DirCache.");
  3702. }
  3703. if (options->BridgeRelay && !options->DirCache) {
  3704. REJECT("We're a bridge but DirCache is disabled. BridgeRelay requires "
  3705. "DirCache.");
  3706. }
  3707. if (server_mode(options)) {
  3708. char *dircache_msg = NULL;
  3709. if (have_enough_mem_for_dircache(options, 0, &dircache_msg)) {
  3710. log_warn(LD_CONFIG, "%s", dircache_msg);
  3711. tor_free(dircache_msg);
  3712. }
  3713. }
  3714. if (options->HTTPProxy) { /* parse it now */
  3715. if (tor_addr_port_lookup(options->HTTPProxy,
  3716. &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
  3717. REJECT("HTTPProxy failed to parse or resolve. Please fix.");
  3718. if (options->HTTPProxyPort == 0) { /* give it a default */
  3719. options->HTTPProxyPort = 80;
  3720. }
  3721. }
  3722. if (options->HTTPProxyAuthenticator) {
  3723. if (strlen(options->HTTPProxyAuthenticator) >= 512)
  3724. REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
  3725. }
  3726. if (options->HTTPSProxy) { /* parse it now */
  3727. if (tor_addr_port_lookup(options->HTTPSProxy,
  3728. &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
  3729. REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
  3730. if (options->HTTPSProxyPort == 0) { /* give it a default */
  3731. options->HTTPSProxyPort = 443;
  3732. }
  3733. }
  3734. if (options->HTTPSProxyAuthenticator) {
  3735. if (strlen(options->HTTPSProxyAuthenticator) >= 512)
  3736. REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
  3737. }
  3738. if (options->Socks4Proxy) { /* parse it now */
  3739. if (tor_addr_port_lookup(options->Socks4Proxy,
  3740. &options->Socks4ProxyAddr,
  3741. &options->Socks4ProxyPort) <0)
  3742. REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
  3743. if (options->Socks4ProxyPort == 0) { /* give it a default */
  3744. options->Socks4ProxyPort = 1080;
  3745. }
  3746. }
  3747. if (options->Socks5Proxy) { /* parse it now */
  3748. if (tor_addr_port_lookup(options->Socks5Proxy,
  3749. &options->Socks5ProxyAddr,
  3750. &options->Socks5ProxyPort) <0)
  3751. REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
  3752. if (options->Socks5ProxyPort == 0) { /* give it a default */
  3753. options->Socks5ProxyPort = 1080;
  3754. }
  3755. }
  3756. /* Check if more than one exclusive proxy type has been enabled. */
  3757. if (!!options->Socks4Proxy + !!options->Socks5Proxy +
  3758. !!options->HTTPSProxy > 1)
  3759. REJECT("You have configured more than one proxy type. "
  3760. "(Socks4Proxy|Socks5Proxy|HTTPSProxy)");
  3761. /* Check if the proxies will give surprising behavior. */
  3762. if (options->HTTPProxy && !(options->Socks4Proxy ||
  3763. options->Socks5Proxy ||
  3764. options->HTTPSProxy)) {
  3765. log_warn(LD_CONFIG, "HTTPProxy configured, but no SOCKS proxy or "
  3766. "HTTPS proxy configured. Watch out: this configuration will "
  3767. "proxy unencrypted directory connections only.");
  3768. }
  3769. if (options->Socks5ProxyUsername) {
  3770. size_t len;
  3771. len = strlen(options->Socks5ProxyUsername);
  3772. if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
  3773. REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
  3774. if (!options->Socks5ProxyPassword)
  3775. REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
  3776. len = strlen(options->Socks5ProxyPassword);
  3777. if (len < 1 || len > MAX_SOCKS5_AUTH_FIELD_SIZE)
  3778. REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
  3779. } else if (options->Socks5ProxyPassword)
  3780. REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
  3781. if (options->HashedControlPassword) {
  3782. smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
  3783. if (!sl) {
  3784. REJECT("Bad HashedControlPassword: wrong length or bad encoding");
  3785. } else {
  3786. SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
  3787. smartlist_free(sl);
  3788. }
  3789. }
  3790. if (options->HashedControlSessionPassword) {
  3791. smartlist_t *sl = decode_hashed_passwords(
  3792. options->HashedControlSessionPassword);
  3793. if (!sl) {
  3794. REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
  3795. } else {
  3796. SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
  3797. smartlist_free(sl);
  3798. }
  3799. }
  3800. if (options->OwningControllerProcess) {
  3801. const char *validate_pspec_msg = NULL;
  3802. if (tor_validate_process_specifier(options->OwningControllerProcess,
  3803. &validate_pspec_msg)) {
  3804. tor_asprintf(msg, "Bad OwningControllerProcess: %s",
  3805. validate_pspec_msg);
  3806. return -1;
  3807. }
  3808. }
  3809. if ((options->ControlPort_set || world_writable_control_socket) &&
  3810. !options->HashedControlPassword &&
  3811. !options->HashedControlSessionPassword &&
  3812. !options->CookieAuthentication) {
  3813. log_warn(LD_CONFIG, "Control%s is %s, but no authentication method "
  3814. "has been configured. This means that any program on your "
  3815. "computer can reconfigure your Tor. That's bad! You should "
  3816. "upgrade your Tor controller as soon as possible.",
  3817. options->ControlPort_set ? "Port" : "Socket",
  3818. options->ControlPort_set ? "open" : "world writable");
  3819. }
  3820. if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
  3821. log_warn(LD_CONFIG, "CookieAuthFileGroupReadable is set, but will have "
  3822. "no effect: you must specify an explicit CookieAuthFile to "
  3823. "have it group-readable.");
  3824. }
  3825. if (options->MyFamily_lines && options->BridgeRelay) {
  3826. log_warn(LD_CONFIG, "Listing a family for a bridge relay is not "
  3827. "supported: it can reveal bridge fingerprints to censors. "
  3828. "You should also make sure you aren't listing this bridge's "
  3829. "fingerprint in any other MyFamily.");
  3830. }
  3831. if (normalize_nickname_list(&options->MyFamily,
  3832. options->MyFamily_lines, "MyFamily", msg))
  3833. return -1;
  3834. for (cl = options->NodeFamilies; cl; cl = cl->next) {
  3835. routerset_t *rs = routerset_new();
  3836. if (routerset_parse(rs, cl->value, cl->key)) {
  3837. routerset_free(rs);
  3838. return -1;
  3839. }
  3840. routerset_free(rs);
  3841. }
  3842. if (validate_addr_policies(options, msg) < 0)
  3843. return -1;
  3844. /* If FallbackDir is set, we don't UseDefaultFallbackDirs */
  3845. if (options->UseDefaultFallbackDirs && options->FallbackDir) {
  3846. log_info(LD_CONFIG, "You have set UseDefaultFallbackDirs 1 and "
  3847. "FallbackDir(s). Ignoring UseDefaultFallbackDirs, and "
  3848. "using the FallbackDir(s) you have set.");
  3849. }
  3850. if (validate_dir_servers(options, old_options) < 0)
  3851. REJECT("Directory authority/fallback line did not parse. See logs "
  3852. "for details.");
  3853. if (options->UseBridges && !options->Bridges)
  3854. REJECT("If you set UseBridges, you must specify at least one bridge.");
  3855. for (cl = options->Bridges; cl; cl = cl->next) {
  3856. bridge_line_t *bridge_line = parse_bridge_line(cl->value);
  3857. if (!bridge_line)
  3858. REJECT("Bridge line did not parse. See logs for details.");
  3859. bridge_line_free(bridge_line);
  3860. }
  3861. for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
  3862. if (parse_transport_line(options, cl->value, 1, 0) < 0)
  3863. REJECT("Invalid client transport line. See logs for details.");
  3864. }
  3865. for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
  3866. if (parse_transport_line(options, cl->value, 1, 1) < 0)
  3867. REJECT("Invalid server transport line. See logs for details.");
  3868. }
  3869. if (options->ServerTransportPlugin && !server_mode(options)) {
  3870. log_notice(LD_GENERAL, "Tor is not configured as a relay but you specified"
  3871. " a ServerTransportPlugin line (%s). The ServerTransportPlugin "
  3872. "line will be ignored.",
  3873. escaped(options->ServerTransportPlugin->value));
  3874. }
  3875. for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
  3876. /** If get_bindaddr_from_transport_listen_line() fails with
  3877. 'transport' being NULL, it means that something went wrong
  3878. while parsing the ServerTransportListenAddr line. */
  3879. char *bindaddr = get_bindaddr_from_transport_listen_line(cl->value, NULL);
  3880. if (!bindaddr)
  3881. REJECT("ServerTransportListenAddr did not parse. See logs for details.");
  3882. tor_free(bindaddr);
  3883. }
  3884. if (options->ServerTransportListenAddr && !options->ServerTransportPlugin) {
  3885. log_notice(LD_GENERAL, "You need at least a single managed-proxy to "
  3886. "specify a transport listen address. The "
  3887. "ServerTransportListenAddr line will be ignored.");
  3888. }
  3889. for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
  3890. /** If get_options_from_transport_options_line() fails with
  3891. 'transport' being NULL, it means that something went wrong
  3892. while parsing the ServerTransportOptions line. */
  3893. smartlist_t *options_sl =
  3894. get_options_from_transport_options_line(cl->value, NULL);
  3895. if (!options_sl)
  3896. REJECT("ServerTransportOptions did not parse. See logs for details.");
  3897. SMARTLIST_FOREACH(options_sl, char *, cp, tor_free(cp));
  3898. smartlist_free(options_sl);
  3899. }
  3900. if (options->ConstrainedSockets) {
  3901. /* If the user wants to constrain socket buffer use, make sure the desired
  3902. * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
  3903. if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
  3904. options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
  3905. options->ConstrainedSockSize % 1024) {
  3906. tor_asprintf(msg,
  3907. "ConstrainedSockSize is invalid. Must be a value between %d and %d "
  3908. "in 1024 byte increments.",
  3909. MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
  3910. return -1;
  3911. }
  3912. if (options->DirPort_set) {
  3913. /* Providing cached directory entries while system TCP buffers are scarce
  3914. * will exacerbate the socket errors. Suggest that this be disabled. */
  3915. COMPLAIN("You have requested constrained socket buffers while also "
  3916. "serving directory entries via DirPort. It is strongly "
  3917. "suggested that you disable serving directory requests when "
  3918. "system TCP buffer resources are scarce.");
  3919. }
  3920. }
  3921. if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
  3922. options->V3AuthVotingInterval/2) {
  3923. /*
  3924. This doesn't work, but it seems like it should:
  3925. what code is preventing the interval being less than twice the lead-up?
  3926. if (options->TestingTorNetwork) {
  3927. if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
  3928. options->V3AuthVotingInterval) {
  3929. REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than "
  3930. "V3AuthVotingInterval");
  3931. } else {
  3932. COMPLAIN("V3AuthVoteDelay plus V3AuthDistDelay is more than half "
  3933. "V3AuthVotingInterval. This may lead to "
  3934. "consensus instability, particularly if clocks drift.");
  3935. }
  3936. } else {
  3937. */
  3938. REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
  3939. "V3AuthVotingInterval");
  3940. /*
  3941. }
  3942. */
  3943. }
  3944. if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS) {
  3945. if (options->TestingTorNetwork) {
  3946. if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS_TESTING) {
  3947. REJECT("V3AuthVoteDelay is way too low.");
  3948. } else {
  3949. COMPLAIN("V3AuthVoteDelay is very low. "
  3950. "This may lead to failure to vote for a consensus.");
  3951. }
  3952. } else {
  3953. REJECT("V3AuthVoteDelay is way too low.");
  3954. }
  3955. }
  3956. if (options->V3AuthDistDelay < MIN_DIST_SECONDS) {
  3957. if (options->TestingTorNetwork) {
  3958. if (options->V3AuthDistDelay < MIN_DIST_SECONDS_TESTING) {
  3959. REJECT("V3AuthDistDelay is way too low.");
  3960. } else {
  3961. COMPLAIN("V3AuthDistDelay is very low. "
  3962. "This may lead to missing votes in a consensus.");
  3963. }
  3964. } else {
  3965. REJECT("V3AuthDistDelay is way too low.");
  3966. }
  3967. }
  3968. if (options->V3AuthNIntervalsValid < 2)
  3969. REJECT("V3AuthNIntervalsValid must be at least 2.");
  3970. if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
  3971. if (options->TestingTorNetwork) {
  3972. if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL_TESTING) {
  3973. REJECT("V3AuthVotingInterval is insanely low.");
  3974. } else {
  3975. COMPLAIN("V3AuthVotingInterval is very low. "
  3976. "This may lead to failure to synchronise for a consensus.");
  3977. }
  3978. } else {
  3979. REJECT("V3AuthVotingInterval is insanely low.");
  3980. }
  3981. } else if (options->V3AuthVotingInterval > 24*60*60) {
  3982. REJECT("V3AuthVotingInterval is insanely high.");
  3983. } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
  3984. COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
  3985. }
  3986. if (hs_config_service_all(options, 1) < 0)
  3987. REJECT("Failed to configure rendezvous options. See logs for details.");
  3988. /* Parse client-side authorization for hidden services. */
  3989. if (rend_parse_service_authorization(options, 1) < 0)
  3990. REJECT("Failed to configure client authorization for hidden services. "
  3991. "See logs for details.");
  3992. if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv4,
  3993. AF_INET, 1, msg)<0)
  3994. return -1;
  3995. if (parse_virtual_addr_network(options->VirtualAddrNetworkIPv6,
  3996. AF_INET6, 1, msg)<0)
  3997. return -1;
  3998. if (options->TestingTorNetwork &&
  3999. !(options->DirAuthorities ||
  4000. (options->AlternateDirAuthority &&
  4001. options->AlternateBridgeAuthority))) {
  4002. REJECT("TestingTorNetwork may only be configured in combination with "
  4003. "a non-default set of DirAuthority or both of "
  4004. "AlternateDirAuthority and AlternateBridgeAuthority configured.");
  4005. }
  4006. #define CHECK_DEFAULT(arg) \
  4007. STMT_BEGIN \
  4008. if (!options->TestingTorNetwork && \
  4009. !options->UsingTestNetworkDefaults_ && \
  4010. !config_is_same(&options_format,options, \
  4011. default_options,#arg)) { \
  4012. REJECT(#arg " may only be changed in testing Tor " \
  4013. "networks!"); \
  4014. } STMT_END
  4015. CHECK_DEFAULT(TestingV3AuthInitialVotingInterval);
  4016. CHECK_DEFAULT(TestingV3AuthInitialVoteDelay);
  4017. CHECK_DEFAULT(TestingV3AuthInitialDistDelay);
  4018. CHECK_DEFAULT(TestingV3AuthVotingStartOffset);
  4019. CHECK_DEFAULT(TestingAuthDirTimeToLearnReachability);
  4020. CHECK_DEFAULT(TestingEstimatedDescriptorPropagationTime);
  4021. CHECK_DEFAULT(TestingServerDownloadSchedule);
  4022. CHECK_DEFAULT(TestingClientDownloadSchedule);
  4023. CHECK_DEFAULT(TestingServerConsensusDownloadSchedule);
  4024. CHECK_DEFAULT(TestingClientConsensusDownloadSchedule);
  4025. CHECK_DEFAULT(TestingBridgeDownloadSchedule);
  4026. CHECK_DEFAULT(TestingBridgeBootstrapDownloadSchedule);
  4027. CHECK_DEFAULT(TestingClientMaxIntervalWithoutRequest);
  4028. CHECK_DEFAULT(TestingDirConnectionMaxStall);
  4029. CHECK_DEFAULT(TestingConsensusMaxDownloadTries);
  4030. CHECK_DEFAULT(TestingDescriptorMaxDownloadTries);
  4031. CHECK_DEFAULT(TestingMicrodescMaxDownloadTries);
  4032. CHECK_DEFAULT(TestingCertMaxDownloadTries);
  4033. CHECK_DEFAULT(TestingAuthKeyLifetime);
  4034. CHECK_DEFAULT(TestingLinkCertLifetime);
  4035. CHECK_DEFAULT(TestingSigningKeySlop);
  4036. CHECK_DEFAULT(TestingAuthKeySlop);
  4037. CHECK_DEFAULT(TestingLinkKeySlop);
  4038. #undef CHECK_DEFAULT
  4039. if (!options->ClientDNSRejectInternalAddresses &&
  4040. !(options->DirAuthorities ||
  4041. (options->AlternateDirAuthority && options->AlternateBridgeAuthority)))
  4042. REJECT("ClientDNSRejectInternalAddresses used for default network.");
  4043. if (options->SigningKeyLifetime < options->TestingSigningKeySlop*2)
  4044. REJECT("SigningKeyLifetime is too short.");
  4045. if (options->TestingLinkCertLifetime < options->TestingAuthKeySlop*2)
  4046. REJECT("LinkCertLifetime is too short.");
  4047. if (options->TestingAuthKeyLifetime < options->TestingLinkKeySlop*2)
  4048. REJECT("TestingAuthKeyLifetime is too short.");
  4049. if (options->TestingV3AuthInitialVotingInterval
  4050. < MIN_VOTE_INTERVAL_TESTING_INITIAL) {
  4051. REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
  4052. } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
  4053. REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
  4054. "30 minutes.");
  4055. }
  4056. if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS_TESTING) {
  4057. REJECT("TestingV3AuthInitialVoteDelay is way too low.");
  4058. }
  4059. if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS_TESTING) {
  4060. REJECT("TestingV3AuthInitialDistDelay is way too low.");
  4061. }
  4062. if (options->TestingV3AuthInitialVoteDelay +
  4063. options->TestingV3AuthInitialDistDelay >=
  4064. options->TestingV3AuthInitialVotingInterval) {
  4065. REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
  4066. "must be less than TestingV3AuthInitialVotingInterval");
  4067. }
  4068. if (options->TestingV3AuthVotingStartOffset >
  4069. MIN(options->TestingV3AuthInitialVotingInterval,
  4070. options->V3AuthVotingInterval)) {
  4071. REJECT("TestingV3AuthVotingStartOffset is higher than the voting "
  4072. "interval.");
  4073. } else if (options->TestingV3AuthVotingStartOffset < 0) {
  4074. REJECT("TestingV3AuthVotingStartOffset must be non-negative.");
  4075. }
  4076. if (options->TestingAuthDirTimeToLearnReachability < 0) {
  4077. REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
  4078. } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
  4079. COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
  4080. }
  4081. if (options->TestingEstimatedDescriptorPropagationTime < 0) {
  4082. REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
  4083. } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
  4084. COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
  4085. }
  4086. if (options->TestingClientMaxIntervalWithoutRequest < 1) {
  4087. REJECT("TestingClientMaxIntervalWithoutRequest is way too low.");
  4088. } else if (options->TestingClientMaxIntervalWithoutRequest > 3600) {
  4089. COMPLAIN("TestingClientMaxIntervalWithoutRequest is insanely high.");
  4090. }
  4091. if (options->TestingDirConnectionMaxStall < 5) {
  4092. REJECT("TestingDirConnectionMaxStall is way too low.");
  4093. } else if (options->TestingDirConnectionMaxStall > 3600) {
  4094. COMPLAIN("TestingDirConnectionMaxStall is insanely high.");
  4095. }
  4096. if (options->TestingConsensusMaxDownloadTries < 2) {
  4097. REJECT("TestingConsensusMaxDownloadTries must be greater than 2.");
  4098. } else if (options->TestingConsensusMaxDownloadTries > 800) {
  4099. COMPLAIN("TestingConsensusMaxDownloadTries is insanely high.");
  4100. }
  4101. if (options->ClientBootstrapConsensusMaxDownloadTries < 2) {
  4102. REJECT("ClientBootstrapConsensusMaxDownloadTries must be greater "
  4103. "than 2."
  4104. );
  4105. } else if (options->ClientBootstrapConsensusMaxDownloadTries > 800) {
  4106. COMPLAIN("ClientBootstrapConsensusMaxDownloadTries is insanely "
  4107. "high.");
  4108. }
  4109. if (options->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries
  4110. < 2) {
  4111. REJECT("ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries must "
  4112. "be greater than 2."
  4113. );
  4114. } else if (
  4115. options->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries
  4116. > 800) {
  4117. COMPLAIN("ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries is "
  4118. "insanely high.");
  4119. }
  4120. if (options->ClientBootstrapConsensusMaxInProgressTries < 1) {
  4121. REJECT("ClientBootstrapConsensusMaxInProgressTries must be greater "
  4122. "than 0.");
  4123. } else if (options->ClientBootstrapConsensusMaxInProgressTries
  4124. > 100) {
  4125. COMPLAIN("ClientBootstrapConsensusMaxInProgressTries is insanely "
  4126. "high.");
  4127. }
  4128. if (options->TestingDescriptorMaxDownloadTries < 2) {
  4129. REJECT("TestingDescriptorMaxDownloadTries must be greater than 1.");
  4130. } else if (options->TestingDescriptorMaxDownloadTries > 800) {
  4131. COMPLAIN("TestingDescriptorMaxDownloadTries is insanely high.");
  4132. }
  4133. if (options->TestingMicrodescMaxDownloadTries < 2) {
  4134. REJECT("TestingMicrodescMaxDownloadTries must be greater than 1.");
  4135. } else if (options->TestingMicrodescMaxDownloadTries > 800) {
  4136. COMPLAIN("TestingMicrodescMaxDownloadTries is insanely high.");
  4137. }
  4138. if (options->TestingCertMaxDownloadTries < 2) {
  4139. REJECT("TestingCertMaxDownloadTries must be greater than 1.");
  4140. } else if (options->TestingCertMaxDownloadTries > 800) {
  4141. COMPLAIN("TestingCertMaxDownloadTries is insanely high.");
  4142. }
  4143. if (options->TestingEnableConnBwEvent &&
  4144. !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
  4145. REJECT("TestingEnableConnBwEvent may only be changed in testing "
  4146. "Tor networks!");
  4147. }
  4148. if (options->TestingEnableCellStatsEvent &&
  4149. !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
  4150. REJECT("TestingEnableCellStatsEvent may only be changed in testing "
  4151. "Tor networks!");
  4152. }
  4153. if (options->TestingEnableTbEmptyEvent &&
  4154. !options->TestingTorNetwork && !options->UsingTestNetworkDefaults_) {
  4155. REJECT("TestingEnableTbEmptyEvent may only be changed in testing "
  4156. "Tor networks!");
  4157. }
  4158. if (options->TestingTorNetwork) {
  4159. log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
  4160. "almost unusable in the public Tor network, and is "
  4161. "therefore only advised if you are building a "
  4162. "testing Tor network!");
  4163. }
  4164. if (options->AccelName && !options->HardwareAccel)
  4165. options->HardwareAccel = 1;
  4166. if (options->AccelDir && !options->AccelName)
  4167. REJECT("Can't use hardware crypto accelerator dir without engine name.");
  4168. if (options->PublishServerDescriptor)
  4169. SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
  4170. if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
  4171. if (smartlist_len(options->PublishServerDescriptor) > 1) {
  4172. COMPLAIN("You have passed a list of multiple arguments to the "
  4173. "PublishServerDescriptor option that includes 0 or 1. "
  4174. "0 or 1 should only be used as the sole argument. "
  4175. "This configuration will be rejected in a future release.");
  4176. break;
  4177. }
  4178. });
  4179. if (options->BridgeRelay == 1 && ! options->ORPort_set)
  4180. REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
  4181. "combination.");
  4182. if (options_validate_scheduler(options, msg) < 0) {
  4183. return -1;
  4184. }
  4185. return 0;
  4186. }
  4187. #undef REJECT
  4188. #undef COMPLAIN
  4189. /* Given the value that the user has set for MaxMemInQueues, compute the
  4190. * actual maximum value. We clip this value if it's too low, and autodetect
  4191. * it if it's set to 0. */
  4192. static uint64_t
  4193. compute_real_max_mem_in_queues(const uint64_t val, int log_guess)
  4194. {
  4195. uint64_t result;
  4196. if (val == 0) {
  4197. #define ONE_GIGABYTE (U64_LITERAL(1) << 30)
  4198. #define ONE_MEGABYTE (U64_LITERAL(1) << 20)
  4199. #if SIZEOF_VOID_P >= 8
  4200. #define MAX_DEFAULT_MAXMEM (8*ONE_GIGABYTE)
  4201. #else
  4202. #define MAX_DEFAULT_MAXMEM (2*ONE_GIGABYTE)
  4203. #endif
  4204. /* The user didn't pick a memory limit. Choose a very large one
  4205. * that is still smaller than the system memory */
  4206. static int notice_sent = 0;
  4207. size_t ram = 0;
  4208. if (get_total_system_memory(&ram) < 0) {
  4209. /* We couldn't determine our total system memory! */
  4210. #if SIZEOF_VOID_P >= 8
  4211. /* 64-bit system. Let's hope for 8 GB. */
  4212. result = 8 * ONE_GIGABYTE;
  4213. #else
  4214. /* (presumably) 32-bit system. Let's hope for 1 GB. */
  4215. result = ONE_GIGABYTE;
  4216. #endif /* SIZEOF_VOID_P >= 8 */
  4217. } else {
  4218. /* We detected it, so let's pick 3/4 of the total RAM as our limit. */
  4219. const uint64_t avail = (ram / 4) * 3;
  4220. /* Make sure it's in range from 0.25 GB to 8 GB. */
  4221. if (avail > MAX_DEFAULT_MAXMEM) {
  4222. /* If you want to use more than this much RAM, you need to configure
  4223. it yourself */
  4224. result = MAX_DEFAULT_MAXMEM;
  4225. } else if (avail < ONE_GIGABYTE / 4) {
  4226. result = ONE_GIGABYTE / 4;
  4227. } else {
  4228. result = avail;
  4229. }
  4230. }
  4231. if (log_guess && ! notice_sent) {
  4232. log_notice(LD_CONFIG, "%sMaxMemInQueues is set to "U64_FORMAT" MB. "
  4233. "You can override this by setting MaxMemInQueues by hand.",
  4234. ram ? "Based on detected system memory, " : "",
  4235. U64_PRINTF_ARG(result / ONE_MEGABYTE));
  4236. notice_sent = 1;
  4237. }
  4238. return result;
  4239. } else if (val < ONE_GIGABYTE / 4) {
  4240. log_warn(LD_CONFIG, "MaxMemInQueues must be at least 256 MB for now. "
  4241. "Ideally, have it as large as you can afford.");
  4242. return ONE_GIGABYTE / 4;
  4243. } else {
  4244. /* The value was fine all along */
  4245. return val;
  4246. }
  4247. }
  4248. /* If we have less than 300 MB suggest disabling dircache */
  4249. #define DIRCACHE_MIN_MEM_MB 300
  4250. #define DIRCACHE_MIN_MEM_BYTES (DIRCACHE_MIN_MEM_MB*ONE_MEGABYTE)
  4251. #define STRINGIFY(val) #val
  4252. /** Create a warning message for emitting if we are a dircache but may not have
  4253. * enough system memory, or if we are not a dircache but probably should be.
  4254. * Return -1 when a message is returned in *msg*, else return 0. */
  4255. STATIC int
  4256. have_enough_mem_for_dircache(const or_options_t *options, size_t total_mem,
  4257. char **msg)
  4258. {
  4259. *msg = NULL;
  4260. /* XXX We should possibly be looking at MaxMemInQueues here
  4261. * unconditionally. Or we should believe total_mem unconditionally. */
  4262. if (total_mem == 0) {
  4263. if (get_total_system_memory(&total_mem) < 0) {
  4264. total_mem = options->MaxMemInQueues >= SIZE_MAX ?
  4265. SIZE_MAX : (size_t)options->MaxMemInQueues;
  4266. }
  4267. }
  4268. if (options->DirCache) {
  4269. if (total_mem < DIRCACHE_MIN_MEM_BYTES) {
  4270. if (options->BridgeRelay) {
  4271. *msg = tor_strdup("Running a Bridge with less than "
  4272. STRINGIFY(DIRCACHE_MIN_MEM_MB) " MB of memory is not "
  4273. "recommended.");
  4274. } else {
  4275. *msg = tor_strdup("Being a directory cache (default) with less than "
  4276. STRINGIFY(DIRCACHE_MIN_MEM_MB) " MB of memory is not "
  4277. "recommended and may consume most of the available "
  4278. "resources, consider disabling this functionality by "
  4279. "setting the DirCache option to 0.");
  4280. }
  4281. }
  4282. } else {
  4283. if (total_mem >= DIRCACHE_MIN_MEM_BYTES) {
  4284. *msg = tor_strdup("DirCache is disabled and we are configured as a "
  4285. "relay. This may disqualify us from becoming a guard in the "
  4286. "future.");
  4287. }
  4288. }
  4289. return *msg == NULL ? 0 : -1;
  4290. }
  4291. #undef STRINGIFY
  4292. /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
  4293. * equal strings. */
  4294. static int
  4295. opt_streq(const char *s1, const char *s2)
  4296. {
  4297. return 0 == strcmp_opt(s1, s2);
  4298. }
  4299. /** Check if any of the previous options have changed but aren't allowed to. */
  4300. static int
  4301. options_transition_allowed(const or_options_t *old,
  4302. const or_options_t *new_val,
  4303. char **msg)
  4304. {
  4305. if (!old)
  4306. return 0;
  4307. #define BAD_CHANGE_TO(opt, how) do { \
  4308. *msg = tor_strdup("While Tor is running"how", changing " #opt \
  4309. " is not allowed"); \
  4310. return -1; \
  4311. } while (0)
  4312. #define NO_CHANGE_BOOL(opt) \
  4313. if (! CFG_EQ_BOOL(old, new_val, opt)) BAD_CHANGE_TO(opt,"")
  4314. #define NO_CHANGE_INT(opt) \
  4315. if (! CFG_EQ_INT(old, new_val, opt)) BAD_CHANGE_TO(opt,"")
  4316. #define NO_CHANGE_STRING(opt) \
  4317. if (! CFG_EQ_STRING(old, new_val, opt)) BAD_CHANGE_TO(opt,"")
  4318. NO_CHANGE_STRING(PidFile);
  4319. NO_CHANGE_BOOL(RunAsDaemon);
  4320. NO_CHANGE_BOOL(Sandbox);
  4321. NO_CHANGE_STRING(DataDirectory);
  4322. NO_CHANGE_STRING(KeyDirectory);
  4323. NO_CHANGE_STRING(CacheDirectory);
  4324. NO_CHANGE_STRING(User);
  4325. NO_CHANGE_BOOL(KeepBindCapabilities);
  4326. NO_CHANGE_STRING(SyslogIdentityTag);
  4327. NO_CHANGE_STRING(AndroidIdentityTag);
  4328. NO_CHANGE_BOOL(HardwareAccel);
  4329. NO_CHANGE_STRING(AccelName);
  4330. NO_CHANGE_STRING(AccelDir);
  4331. NO_CHANGE_BOOL(TestingTorNetwork);
  4332. NO_CHANGE_BOOL(DisableAllSwap);
  4333. NO_CHANGE_INT(TokenBucketRefillInterval);
  4334. NO_CHANGE_BOOL(HiddenServiceSingleHopMode);
  4335. NO_CHANGE_BOOL(HiddenServiceNonAnonymousMode);
  4336. NO_CHANGE_BOOL(DisableDebuggerAttachment);
  4337. NO_CHANGE_BOOL(NoExec);
  4338. NO_CHANGE_INT(OwningControllerFD);
  4339. NO_CHANGE_BOOL(DisableSignalHandlers);
  4340. if (sandbox_is_active()) {
  4341. #define SB_NOCHANGE_STR(opt) \
  4342. if (! CFG_EQ_STRING(old, new_val, opt)) \
  4343. BAD_CHANGE_TO(opt," with Sandbox active")
  4344. #define SB_NOCHANGE_LINELIST(opt) \
  4345. if (! CFG_EQ_LINELIST(old, new_val, opt)) \
  4346. BAD_CHANGE_TO(opt," with Sandbox active")
  4347. #define SB_NOCHANGE_INT(opt) \
  4348. if (! CFG_EQ_INT(old, new_val, opt)) \
  4349. BAD_CHANGE_TO(opt," with Sandbox active")
  4350. SB_NOCHANGE_STR(Address);
  4351. SB_NOCHANGE_STR(ServerDNSResolvConfFile);
  4352. SB_NOCHANGE_STR(DirPortFrontPage);
  4353. SB_NOCHANGE_STR(CookieAuthFile);
  4354. SB_NOCHANGE_STR(ExtORPortCookieAuthFile);
  4355. SB_NOCHANGE_LINELIST(Logs);
  4356. SB_NOCHANGE_INT(ConnLimit);
  4357. if (server_mode(old) != server_mode(new_val)) {
  4358. *msg = tor_strdup("Can't start/stop being a server while "
  4359. "Sandbox is active");
  4360. return -1;
  4361. }
  4362. }
  4363. #undef SB_NOCHANGE_LINELIST
  4364. #undef SB_NOCHANGE_STR
  4365. #undef SB_NOCHANGE_INT
  4366. #undef BAD_CHANGE_TO
  4367. #undef NO_CHANGE_BOOL
  4368. #undef NO_CHANGE_INT
  4369. #undef NO_CHANGE_STRING
  4370. return 0;
  4371. }
  4372. /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
  4373. * will require us to rotate the CPU and DNS workers; else return 0. */
  4374. static int
  4375. options_transition_affects_workers(const or_options_t *old_options,
  4376. const or_options_t *new_options)
  4377. {
  4378. YES_IF_CHANGED_STRING(DataDirectory);
  4379. YES_IF_CHANGED_INT(NumCPUs);
  4380. YES_IF_CHANGED_LINELIST(ORPort_lines);
  4381. YES_IF_CHANGED_BOOL(ServerDNSSearchDomains);
  4382. YES_IF_CHANGED_BOOL(SafeLogging_);
  4383. YES_IF_CHANGED_BOOL(ClientOnly);
  4384. YES_IF_CHANGED_BOOL(LogMessageDomains);
  4385. YES_IF_CHANGED_LINELIST(Logs);
  4386. if (server_mode(old_options) != server_mode(new_options) ||
  4387. public_server_mode(old_options) != public_server_mode(new_options))
  4388. return 1;
  4389. /* Nothing that changed matters. */
  4390. return 0;
  4391. }
  4392. /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
  4393. * will require us to generate a new descriptor; else return 0. */
  4394. static int
  4395. options_transition_affects_descriptor(const or_options_t *old_options,
  4396. const or_options_t *new_options)
  4397. {
  4398. /* XXX We can be smarter here. If your DirPort isn't being
  4399. * published and you just turned it off, no need to republish. Etc. */
  4400. YES_IF_CHANGED_STRING(DataDirectory);
  4401. YES_IF_CHANGED_STRING(Nickname);
  4402. YES_IF_CHANGED_STRING(Address);
  4403. YES_IF_CHANGED_LINELIST(ExitPolicy);
  4404. YES_IF_CHANGED_BOOL(ExitRelay);
  4405. YES_IF_CHANGED_BOOL(ExitPolicyRejectPrivate);
  4406. YES_IF_CHANGED_BOOL(ExitPolicyRejectLocalInterfaces);
  4407. YES_IF_CHANGED_BOOL(IPv6Exit);
  4408. YES_IF_CHANGED_LINELIST(ORPort_lines);
  4409. YES_IF_CHANGED_LINELIST(DirPort_lines);
  4410. YES_IF_CHANGED_LINELIST(DirPort_lines);
  4411. YES_IF_CHANGED_BOOL(ClientOnly);
  4412. YES_IF_CHANGED_BOOL(DisableNetwork);
  4413. YES_IF_CHANGED_BOOL(PublishServerDescriptor_);
  4414. YES_IF_CHANGED_STRING(ContactInfo);
  4415. YES_IF_CHANGED_STRING(BridgeDistribution);
  4416. YES_IF_CHANGED_LINELIST(MyFamily);
  4417. YES_IF_CHANGED_STRING(AccountingStart);
  4418. YES_IF_CHANGED_INT(AccountingMax);
  4419. YES_IF_CHANGED_INT(AccountingRule);
  4420. YES_IF_CHANGED_BOOL(DirCache);
  4421. YES_IF_CHANGED_BOOL(AssumeReachable);
  4422. if (get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
  4423. get_effective_bwburst(old_options) !=
  4424. get_effective_bwburst(new_options) ||
  4425. public_server_mode(old_options) != public_server_mode(new_options))
  4426. return 1;
  4427. return 0;
  4428. }
  4429. #ifdef _WIN32
  4430. /** Return the directory on windows where we expect to find our application
  4431. * data. */
  4432. static char *
  4433. get_windows_conf_root(void)
  4434. {
  4435. static int is_set = 0;
  4436. static char path[MAX_PATH*2+1];
  4437. TCHAR tpath[MAX_PATH] = {0};
  4438. LPITEMIDLIST idl;
  4439. IMalloc *m;
  4440. HRESULT result;
  4441. if (is_set)
  4442. return path;
  4443. /* Find X:\documents and settings\username\application data\ .
  4444. * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
  4445. */
  4446. #ifdef ENABLE_LOCAL_APPDATA
  4447. #define APPDATA_PATH CSIDL_LOCAL_APPDATA
  4448. #else
  4449. #define APPDATA_PATH CSIDL_APPDATA
  4450. #endif
  4451. if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
  4452. getcwd(path,MAX_PATH);
  4453. is_set = 1;
  4454. log_warn(LD_CONFIG,
  4455. "I couldn't find your application data folder: are you "
  4456. "running an ancient version of Windows 95? Defaulting to \"%s\"",
  4457. path);
  4458. return path;
  4459. }
  4460. /* Convert the path from an "ID List" (whatever that is!) to a path. */
  4461. result = SHGetPathFromIDList(idl, tpath);
  4462. #ifdef UNICODE
  4463. wcstombs(path,tpath,sizeof(path));
  4464. path[sizeof(path)-1] = '\0';
  4465. #else
  4466. strlcpy(path,tpath,sizeof(path));
  4467. #endif /* defined(UNICODE) */
  4468. /* Now we need to free the memory that the path-idl was stored in. In
  4469. * typical Windows fashion, we can't just call 'free()' on it. */
  4470. SHGetMalloc(&m);
  4471. if (m) {
  4472. m->lpVtbl->Free(m, idl);
  4473. m->lpVtbl->Release(m);
  4474. }
  4475. if (!SUCCEEDED(result)) {
  4476. return NULL;
  4477. }
  4478. strlcat(path,"\\tor",MAX_PATH);
  4479. is_set = 1;
  4480. return path;
  4481. }
  4482. #endif /* defined(_WIN32) */
  4483. /** Return the default location for our torrc file (if <b>defaults_file</b> is
  4484. * false), or for the torrc-defaults file (if <b>defaults_file</b> is true). */
  4485. static const char *
  4486. get_default_conf_file(int defaults_file)
  4487. {
  4488. #ifdef DISABLE_SYSTEM_TORRC
  4489. (void) defaults_file;
  4490. return NULL;
  4491. #elif defined(_WIN32)
  4492. if (defaults_file) {
  4493. static char defaults_path[MAX_PATH+1];
  4494. tor_snprintf(defaults_path, MAX_PATH, "%s\\torrc-defaults",
  4495. get_windows_conf_root());
  4496. return defaults_path;
  4497. } else {
  4498. static char path[MAX_PATH+1];
  4499. tor_snprintf(path, MAX_PATH, "%s\\torrc",
  4500. get_windows_conf_root());
  4501. return path;
  4502. }
  4503. #else
  4504. return defaults_file ? CONFDIR "/torrc-defaults" : CONFDIR "/torrc";
  4505. #endif /* defined(DISABLE_SYSTEM_TORRC) || ... */
  4506. }
  4507. /** Verify whether lst is a list of strings containing valid-looking
  4508. * comma-separated nicknames, or NULL. Will normalise <b>lst</b> to prefix '$'
  4509. * to any nickname or fingerprint that needs it. Also splits comma-separated
  4510. * list elements into multiple elements. Return 0 on success.
  4511. * Warn and return -1 on failure.
  4512. */
  4513. static int
  4514. normalize_nickname_list(config_line_t **normalized_out,
  4515. const config_line_t *lst, const char *name,
  4516. char **msg)
  4517. {
  4518. if (!lst)
  4519. return 0;
  4520. config_line_t *new_nicknames = NULL;
  4521. config_line_t **new_nicknames_next = &new_nicknames;
  4522. const config_line_t *cl;
  4523. for (cl = lst; cl; cl = cl->next) {
  4524. const char *line = cl->value;
  4525. if (!line)
  4526. continue;
  4527. int valid_line = 1;
  4528. smartlist_t *sl = smartlist_new();
  4529. smartlist_split_string(sl, line, ",",
  4530. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
  4531. SMARTLIST_FOREACH_BEGIN(sl, char *, s)
  4532. {
  4533. char *normalized = NULL;
  4534. if (!is_legal_nickname_or_hexdigest(s)) {
  4535. // check if first char is dollar
  4536. if (s[0] != '$') {
  4537. // Try again but with a dollar symbol prepended
  4538. char *prepended;
  4539. tor_asprintf(&prepended, "$%s", s);
  4540. if (is_legal_nickname_or_hexdigest(prepended)) {
  4541. // The nickname is valid when it's prepended, set it as the
  4542. // normalized version
  4543. normalized = prepended;
  4544. } else {
  4545. // Still not valid, free and fallback to error message
  4546. tor_free(prepended);
  4547. }
  4548. }
  4549. if (!normalized) {
  4550. tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
  4551. valid_line = 0;
  4552. break;
  4553. }
  4554. } else {
  4555. normalized = tor_strdup(s);
  4556. }
  4557. config_line_t *next = tor_malloc_zero(sizeof(*next));
  4558. next->key = tor_strdup(cl->key);
  4559. next->value = normalized;
  4560. next->next = NULL;
  4561. *new_nicknames_next = next;
  4562. new_nicknames_next = &next->next;
  4563. } SMARTLIST_FOREACH_END(s);
  4564. SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
  4565. smartlist_free(sl);
  4566. if (!valid_line) {
  4567. config_free_lines(new_nicknames);
  4568. return -1;
  4569. }
  4570. }
  4571. *normalized_out = new_nicknames;
  4572. return 0;
  4573. }
  4574. /** Learn config file name from command line arguments, or use the default.
  4575. *
  4576. * If <b>defaults_file</b> is true, we're looking for torrc-defaults;
  4577. * otherwise, we're looking for the regular torrc_file.
  4578. *
  4579. * Set *<b>using_default_fname</b> to true if we're using the default
  4580. * configuration file name; or false if we've set it from the command line.
  4581. *
  4582. * Set *<b>ignore_missing_torrc</b> to true if we should ignore the resulting
  4583. * filename if it doesn't exist.
  4584. */
  4585. static char *
  4586. find_torrc_filename(config_line_t *cmd_arg,
  4587. int defaults_file,
  4588. int *using_default_fname, int *ignore_missing_torrc)
  4589. {
  4590. char *fname=NULL;
  4591. config_line_t *p_index;
  4592. const char *fname_opt = defaults_file ? "--defaults-torrc" : "-f";
  4593. const char *ignore_opt = defaults_file ? NULL : "--ignore-missing-torrc";
  4594. if (defaults_file)
  4595. *ignore_missing_torrc = 1;
  4596. for (p_index = cmd_arg; p_index; p_index = p_index->next) {
  4597. if (!strcmp(p_index->key, fname_opt)) {
  4598. if (fname) {
  4599. log_warn(LD_CONFIG, "Duplicate %s options on command line.",
  4600. fname_opt);
  4601. tor_free(fname);
  4602. }
  4603. fname = expand_filename(p_index->value);
  4604. {
  4605. char *absfname;
  4606. absfname = make_path_absolute(fname);
  4607. tor_free(fname);
  4608. fname = absfname;
  4609. }
  4610. *using_default_fname = 0;
  4611. } else if (ignore_opt && !strcmp(p_index->key,ignore_opt)) {
  4612. *ignore_missing_torrc = 1;
  4613. }
  4614. }
  4615. if (*using_default_fname) {
  4616. /* didn't find one, try CONFDIR */
  4617. const char *dflt = get_default_conf_file(defaults_file);
  4618. file_status_t st = file_status(dflt);
  4619. if (dflt && (st == FN_FILE || st == FN_EMPTY)) {
  4620. fname = tor_strdup(dflt);
  4621. } else {
  4622. #ifndef _WIN32
  4623. char *fn = NULL;
  4624. if (!defaults_file) {
  4625. fn = expand_filename("~/.torrc");
  4626. }
  4627. if (fn) {
  4628. file_status_t hmst = file_status(fn);
  4629. if (hmst == FN_FILE || hmst == FN_EMPTY || dflt == NULL) {
  4630. fname = fn;
  4631. } else {
  4632. tor_free(fn);
  4633. fname = tor_strdup(dflt);
  4634. }
  4635. } else {
  4636. fname = dflt ? tor_strdup(dflt) : NULL;
  4637. }
  4638. #else /* !(!defined(_WIN32)) */
  4639. fname = dflt ? tor_strdup(dflt) : NULL;
  4640. #endif /* !defined(_WIN32) */
  4641. }
  4642. }
  4643. return fname;
  4644. }
  4645. /** Read the torrc from standard input and return it as a string.
  4646. * Upon failure, return NULL.
  4647. */
  4648. static char *
  4649. load_torrc_from_stdin(void)
  4650. {
  4651. size_t sz_out;
  4652. return read_file_to_str_until_eof(STDIN_FILENO,SIZE_MAX,&sz_out);
  4653. }
  4654. /** Load a configuration file from disk, setting torrc_fname or
  4655. * torrc_defaults_fname if successful.
  4656. *
  4657. * If <b>defaults_file</b> is true, load torrc-defaults; otherwise load torrc.
  4658. *
  4659. * Return the contents of the file on success, and NULL on failure.
  4660. */
  4661. static char *
  4662. load_torrc_from_disk(config_line_t *cmd_arg, int defaults_file)
  4663. {
  4664. char *fname=NULL;
  4665. char *cf = NULL;
  4666. int using_default_torrc = 1;
  4667. int ignore_missing_torrc = 0;
  4668. char **fname_var = defaults_file ? &torrc_defaults_fname : &torrc_fname;
  4669. if (*fname_var == NULL) {
  4670. fname = find_torrc_filename(cmd_arg, defaults_file,
  4671. &using_default_torrc, &ignore_missing_torrc);
  4672. tor_free(*fname_var);
  4673. *fname_var = fname;
  4674. } else {
  4675. fname = *fname_var;
  4676. }
  4677. log_debug(LD_CONFIG, "Opening config file \"%s\"", fname?fname:"<NULL>");
  4678. /* Open config file */
  4679. file_status_t st = fname ? file_status(fname) : FN_EMPTY;
  4680. if (fname == NULL ||
  4681. !(st == FN_FILE || st == FN_EMPTY) ||
  4682. !(cf = read_file_to_str(fname,0,NULL))) {
  4683. if (using_default_torrc == 1 || ignore_missing_torrc) {
  4684. if (!defaults_file)
  4685. log_notice(LD_CONFIG, "Configuration file \"%s\" not present, "
  4686. "using reasonable defaults.", fname);
  4687. tor_free(fname); /* sets fname to NULL */
  4688. *fname_var = NULL;
  4689. cf = tor_strdup("");
  4690. } else {
  4691. log_warn(LD_CONFIG,
  4692. "Unable to open configuration file \"%s\".", fname);
  4693. goto err;
  4694. }
  4695. } else {
  4696. log_notice(LD_CONFIG, "Read configuration file \"%s\".", fname);
  4697. }
  4698. return cf;
  4699. err:
  4700. tor_free(fname);
  4701. *fname_var = NULL;
  4702. return NULL;
  4703. }
  4704. /** Read a configuration file into <b>options</b>, finding the configuration
  4705. * file location based on the command line. After loading the file
  4706. * call options_init_from_string() to load the config.
  4707. * Return 0 if success, -1 if failure, and 1 if we succeeded but should exit
  4708. * anyway. */
  4709. int
  4710. options_init_from_torrc(int argc, char **argv)
  4711. {
  4712. char *cf=NULL, *cf_defaults=NULL;
  4713. int command;
  4714. int retval = -1;
  4715. char *command_arg = NULL;
  4716. char *errmsg=NULL;
  4717. config_line_t *p_index = NULL;
  4718. config_line_t *cmdline_only_options = NULL;
  4719. /* Go through command-line variables */
  4720. if (! have_parsed_cmdline) {
  4721. /* Or we could redo the list every time we pass this place.
  4722. * It does not really matter */
  4723. if (config_parse_commandline(argc, argv, 0, &global_cmdline_options,
  4724. &global_cmdline_only_options) < 0) {
  4725. goto err;
  4726. }
  4727. have_parsed_cmdline = 1;
  4728. }
  4729. cmdline_only_options = global_cmdline_only_options;
  4730. if (config_line_find(cmdline_only_options, "-h") ||
  4731. config_line_find(cmdline_only_options, "--help")) {
  4732. print_usage();
  4733. return 1;
  4734. }
  4735. if (config_line_find(cmdline_only_options, "--list-torrc-options")) {
  4736. /* For validating whether we've documented everything. */
  4737. list_torrc_options();
  4738. return 1;
  4739. }
  4740. if (config_line_find(cmdline_only_options, "--list-deprecated-options")) {
  4741. /* For validating whether what we have deprecated really exists. */
  4742. list_deprecated_options();
  4743. return 1;
  4744. }
  4745. if (config_line_find(cmdline_only_options, "--version")) {
  4746. printf("Tor version %s.\n",get_version());
  4747. return 1;
  4748. }
  4749. if (config_line_find(cmdline_only_options, "--library-versions")) {
  4750. printf("Tor version %s. \n", get_version());
  4751. printf("Library versions\tCompiled\t\tRuntime\n");
  4752. printf("Libevent\t\t%-15s\t\t%s\n",
  4753. tor_libevent_get_header_version_str(),
  4754. tor_libevent_get_version_str());
  4755. printf("OpenSSL \t\t%-15s\t\t%s\n",
  4756. crypto_openssl_get_header_version_str(),
  4757. crypto_openssl_get_version_str());
  4758. if (tor_compress_supports_method(ZLIB_METHOD)) {
  4759. printf("Zlib \t\t%-15s\t\t%s\n",
  4760. tor_compress_version_str(ZLIB_METHOD),
  4761. tor_compress_header_version_str(ZLIB_METHOD));
  4762. }
  4763. if (tor_compress_supports_method(LZMA_METHOD)) {
  4764. printf("Liblzma \t\t%-15s\t\t%s\n",
  4765. tor_compress_version_str(LZMA_METHOD),
  4766. tor_compress_header_version_str(LZMA_METHOD));
  4767. }
  4768. if (tor_compress_supports_method(ZSTD_METHOD)) {
  4769. printf("Libzstd \t\t%-15s\t\t%s\n",
  4770. tor_compress_version_str(ZSTD_METHOD),
  4771. tor_compress_header_version_str(ZSTD_METHOD));
  4772. }
  4773. //TODO: Hex versions?
  4774. return 1;
  4775. }
  4776. command = CMD_RUN_TOR;
  4777. for (p_index = cmdline_only_options; p_index; p_index = p_index->next) {
  4778. if (!strcmp(p_index->key,"--keygen")) {
  4779. command = CMD_KEYGEN;
  4780. } else if (!strcmp(p_index->key, "--key-expiration")) {
  4781. command = CMD_KEY_EXPIRATION;
  4782. command_arg = p_index->value;
  4783. } else if (!strcmp(p_index->key,"--list-fingerprint")) {
  4784. command = CMD_LIST_FINGERPRINT;
  4785. } else if (!strcmp(p_index->key, "--hash-password")) {
  4786. command = CMD_HASH_PASSWORD;
  4787. command_arg = p_index->value;
  4788. } else if (!strcmp(p_index->key, "--dump-config")) {
  4789. command = CMD_DUMP_CONFIG;
  4790. command_arg = p_index->value;
  4791. } else if (!strcmp(p_index->key, "--verify-config")) {
  4792. command = CMD_VERIFY_CONFIG;
  4793. }
  4794. }
  4795. if (command == CMD_HASH_PASSWORD) {
  4796. cf_defaults = tor_strdup("");
  4797. cf = tor_strdup("");
  4798. } else {
  4799. cf_defaults = load_torrc_from_disk(cmdline_only_options, 1);
  4800. const config_line_t *f_line = config_line_find(cmdline_only_options,
  4801. "-f");
  4802. const int read_torrc_from_stdin =
  4803. (f_line != NULL && strcmp(f_line->value, "-") == 0);
  4804. if (read_torrc_from_stdin) {
  4805. cf = load_torrc_from_stdin();
  4806. } else {
  4807. cf = load_torrc_from_disk(cmdline_only_options, 0);
  4808. }
  4809. if (!cf) {
  4810. if (config_line_find(cmdline_only_options, "--allow-missing-torrc")) {
  4811. cf = tor_strdup("");
  4812. } else {
  4813. goto err;
  4814. }
  4815. }
  4816. }
  4817. retval = options_init_from_string(cf_defaults, cf, command, command_arg,
  4818. &errmsg);
  4819. if (retval < 0)
  4820. goto err;
  4821. if (config_line_find(cmdline_only_options, "--no-passphrase")) {
  4822. if (command == CMD_KEYGEN) {
  4823. get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_OFF;
  4824. } else {
  4825. log_err(LD_CONFIG, "--no-passphrase specified without --keygen!");
  4826. retval = -1;
  4827. goto err;
  4828. }
  4829. }
  4830. if (config_line_find(cmdline_only_options, "--newpass")) {
  4831. if (command == CMD_KEYGEN) {
  4832. get_options_mutable()->change_key_passphrase = 1;
  4833. } else {
  4834. log_err(LD_CONFIG, "--newpass specified without --keygen!");
  4835. retval = -1;
  4836. goto err;
  4837. }
  4838. }
  4839. {
  4840. const config_line_t *fd_line = config_line_find(cmdline_only_options,
  4841. "--passphrase-fd");
  4842. if (fd_line) {
  4843. if (get_options()->keygen_force_passphrase == FORCE_PASSPHRASE_OFF) {
  4844. log_err(LD_CONFIG, "--no-passphrase specified with --passphrase-fd!");
  4845. retval = -1;
  4846. goto err;
  4847. } else if (command != CMD_KEYGEN) {
  4848. log_err(LD_CONFIG, "--passphrase-fd specified without --keygen!");
  4849. retval = -1;
  4850. goto err;
  4851. } else {
  4852. const char *v = fd_line->value;
  4853. int ok = 1;
  4854. long fd = tor_parse_long(v, 10, 0, INT_MAX, &ok, NULL);
  4855. if (fd < 0 || ok == 0) {
  4856. log_err(LD_CONFIG, "Invalid --passphrase-fd value %s", escaped(v));
  4857. retval = -1;
  4858. goto err;
  4859. }
  4860. get_options_mutable()->keygen_passphrase_fd = (int)fd;
  4861. get_options_mutable()->use_keygen_passphrase_fd = 1;
  4862. get_options_mutable()->keygen_force_passphrase = FORCE_PASSPHRASE_ON;
  4863. }
  4864. }
  4865. }
  4866. {
  4867. const config_line_t *key_line = config_line_find(cmdline_only_options,
  4868. "--master-key");
  4869. if (key_line) {
  4870. if (command != CMD_KEYGEN) {
  4871. log_err(LD_CONFIG, "--master-key without --keygen!");
  4872. retval = -1;
  4873. goto err;
  4874. } else {
  4875. get_options_mutable()->master_key_fname = tor_strdup(key_line->value);
  4876. }
  4877. }
  4878. }
  4879. err:
  4880. tor_free(cf);
  4881. tor_free(cf_defaults);
  4882. if (errmsg) {
  4883. log_warn(LD_CONFIG,"%s", errmsg);
  4884. tor_free(errmsg);
  4885. }
  4886. return retval < 0 ? -1 : 0;
  4887. }
  4888. /** Load the options from the configuration in <b>cf</b>, validate
  4889. * them for consistency and take actions based on them.
  4890. *
  4891. * Return 0 if success, negative on error:
  4892. * * -1 for general errors.
  4893. * * -2 for failure to parse/validate,
  4894. * * -3 for transition not allowed
  4895. * * -4 for error while setting the new options
  4896. */
  4897. setopt_err_t
  4898. options_init_from_string(const char *cf_defaults, const char *cf,
  4899. int command, const char *command_arg,
  4900. char **msg)
  4901. {
  4902. or_options_t *oldoptions, *newoptions, *newdefaultoptions=NULL;
  4903. config_line_t *cl;
  4904. int retval;
  4905. setopt_err_t err = SETOPT_ERR_MISC;
  4906. int cf_has_include = 0;
  4907. tor_assert(msg);
  4908. oldoptions = global_options; /* get_options unfortunately asserts if
  4909. this is the first time we run*/
  4910. newoptions = tor_malloc_zero(sizeof(or_options_t));
  4911. newoptions->magic_ = OR_OPTIONS_MAGIC;
  4912. options_init(newoptions);
  4913. newoptions->command = command;
  4914. newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
  4915. smartlist_t *opened_files = smartlist_new();
  4916. for (int i = 0; i < 2; ++i) {
  4917. const char *body = i==0 ? cf_defaults : cf;
  4918. if (!body)
  4919. continue;
  4920. /* get config lines, assign them */
  4921. retval = config_get_lines_include(body, &cl, 1,
  4922. body == cf ? &cf_has_include : NULL,
  4923. opened_files);
  4924. if (retval < 0) {
  4925. err = SETOPT_ERR_PARSE;
  4926. goto err;
  4927. }
  4928. retval = config_assign(&options_format, newoptions, cl,
  4929. CAL_WARN_DEPRECATIONS, msg);
  4930. config_free_lines(cl);
  4931. if (retval < 0) {
  4932. err = SETOPT_ERR_PARSE;
  4933. goto err;
  4934. }
  4935. if (i==0)
  4936. newdefaultoptions = config_dup(&options_format, newoptions);
  4937. }
  4938. if (newdefaultoptions == NULL) {
  4939. newdefaultoptions = config_dup(&options_format, global_default_options);
  4940. }
  4941. /* Go through command-line variables too */
  4942. retval = config_assign(&options_format, newoptions,
  4943. global_cmdline_options, CAL_WARN_DEPRECATIONS, msg);
  4944. if (retval < 0) {
  4945. err = SETOPT_ERR_PARSE;
  4946. goto err;
  4947. }
  4948. newoptions->IncludeUsed = cf_has_include;
  4949. newoptions->FilesOpenedByIncludes = opened_files;
  4950. /* If this is a testing network configuration, change defaults
  4951. * for a list of dependent config options, re-initialize newoptions
  4952. * with the new defaults, and assign all options to it second time. */
  4953. if (newoptions->TestingTorNetwork) {
  4954. /* XXXX this is a bit of a kludge. perhaps there's a better way to do
  4955. * this? We could, for example, make the parsing algorithm do two passes
  4956. * over the configuration. If it finds any "suite" options like
  4957. * TestingTorNetwork, it could change the defaults before its second pass.
  4958. * Not urgent so long as this seems to work, but at any sign of trouble,
  4959. * let's clean it up. -NM */
  4960. /* Change defaults. */
  4961. for (int i = 0; testing_tor_network_defaults[i].name; ++i) {
  4962. const config_var_t *new_var = &testing_tor_network_defaults[i];
  4963. config_var_t *old_var =
  4964. config_find_option_mutable(&options_format, new_var->name);
  4965. tor_assert(new_var);
  4966. tor_assert(old_var);
  4967. old_var->initvalue = new_var->initvalue;
  4968. if ((config_find_deprecation(&options_format, new_var->name))) {
  4969. log_warn(LD_GENERAL, "Testing options override the deprecated "
  4970. "option %s. Is that intentional?",
  4971. new_var->name);
  4972. }
  4973. }
  4974. /* Clear newoptions and re-initialize them with new defaults. */
  4975. or_options_free(newoptions);
  4976. or_options_free(newdefaultoptions);
  4977. newdefaultoptions = NULL;
  4978. newoptions = tor_malloc_zero(sizeof(or_options_t));
  4979. newoptions->magic_ = OR_OPTIONS_MAGIC;
  4980. options_init(newoptions);
  4981. newoptions->command = command;
  4982. newoptions->command_arg = command_arg ? tor_strdup(command_arg) : NULL;
  4983. /* Assign all options a second time. */
  4984. opened_files = smartlist_new();
  4985. for (int i = 0; i < 2; ++i) {
  4986. const char *body = i==0 ? cf_defaults : cf;
  4987. if (!body)
  4988. continue;
  4989. /* get config lines, assign them */
  4990. retval = config_get_lines_include(body, &cl, 1,
  4991. body == cf ? &cf_has_include : NULL,
  4992. opened_files);
  4993. if (retval < 0) {
  4994. err = SETOPT_ERR_PARSE;
  4995. goto err;
  4996. }
  4997. retval = config_assign(&options_format, newoptions, cl, 0, msg);
  4998. config_free_lines(cl);
  4999. if (retval < 0) {
  5000. err = SETOPT_ERR_PARSE;
  5001. goto err;
  5002. }
  5003. if (i==0)
  5004. newdefaultoptions = config_dup(&options_format, newoptions);
  5005. }
  5006. /* Assign command-line variables a second time too */
  5007. retval = config_assign(&options_format, newoptions,
  5008. global_cmdline_options, 0, msg);
  5009. if (retval < 0) {
  5010. err = SETOPT_ERR_PARSE;
  5011. goto err;
  5012. }
  5013. }
  5014. newoptions->IncludeUsed = cf_has_include;
  5015. in_option_validation = 1;
  5016. newoptions->FilesOpenedByIncludes = opened_files;
  5017. /* Validate newoptions */
  5018. if (options_validate(oldoptions, newoptions, newdefaultoptions,
  5019. 0, msg) < 0) {
  5020. err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
  5021. goto err;
  5022. }
  5023. if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
  5024. err = SETOPT_ERR_TRANSITION;
  5025. goto err;
  5026. }
  5027. in_option_validation = 0;
  5028. if (set_options(newoptions, msg)) {
  5029. err = SETOPT_ERR_SETTING;
  5030. goto err; /* frees and replaces old options */
  5031. }
  5032. or_options_free(global_default_options);
  5033. global_default_options = newdefaultoptions;
  5034. return SETOPT_OK;
  5035. err:
  5036. in_option_validation = 0;
  5037. if (opened_files) {
  5038. SMARTLIST_FOREACH(opened_files, char *, f, tor_free(f));
  5039. smartlist_free(opened_files);
  5040. }
  5041. // may have been set to opened_files, avoid double free
  5042. newoptions->FilesOpenedByIncludes = NULL;
  5043. or_options_free(newoptions);
  5044. or_options_free(newdefaultoptions);
  5045. if (*msg) {
  5046. char *old_msg = *msg;
  5047. tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
  5048. tor_free(old_msg);
  5049. }
  5050. return err;
  5051. }
  5052. /** Return the location for our configuration file. May return NULL.
  5053. */
  5054. const char *
  5055. get_torrc_fname(int defaults_fname)
  5056. {
  5057. const char *fname = defaults_fname ? torrc_defaults_fname : torrc_fname;
  5058. if (fname)
  5059. return fname;
  5060. else
  5061. return get_default_conf_file(defaults_fname);
  5062. }
  5063. /** Adjust the address map based on the MapAddress elements in the
  5064. * configuration <b>options</b>
  5065. */
  5066. void
  5067. config_register_addressmaps(const or_options_t *options)
  5068. {
  5069. smartlist_t *elts;
  5070. config_line_t *opt;
  5071. const char *from, *to, *msg;
  5072. addressmap_clear_configured();
  5073. elts = smartlist_new();
  5074. for (opt = options->AddressMap; opt; opt = opt->next) {
  5075. smartlist_split_string(elts, opt->value, NULL,
  5076. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  5077. if (smartlist_len(elts) < 2) {
  5078. log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
  5079. opt->value);
  5080. goto cleanup;
  5081. }
  5082. from = smartlist_get(elts,0);
  5083. to = smartlist_get(elts,1);
  5084. if (to[0] == '.' || from[0] == '.') {
  5085. log_warn(LD_CONFIG,"MapAddress '%s' is ambiguous - address starts with a"
  5086. "'.'. Ignoring.",opt->value);
  5087. goto cleanup;
  5088. }
  5089. if (addressmap_register_auto(from, to, 0, ADDRMAPSRC_TORRC, &msg) < 0) {
  5090. log_warn(LD_CONFIG,"MapAddress '%s' failed: %s. Ignoring.", opt->value,
  5091. msg);
  5092. goto cleanup;
  5093. }
  5094. if (smartlist_len(elts) > 2)
  5095. log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
  5096. cleanup:
  5097. SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
  5098. smartlist_clear(elts);
  5099. }
  5100. smartlist_free(elts);
  5101. }
  5102. /** As addressmap_register(), but detect the wildcarded status of "from" and
  5103. * "to", and do not steal a reference to <b>to</b>. */
  5104. /* XXXX move to connection_edge.c */
  5105. int
  5106. addressmap_register_auto(const char *from, const char *to,
  5107. time_t expires,
  5108. addressmap_entry_source_t addrmap_source,
  5109. const char **msg)
  5110. {
  5111. int from_wildcard = 0, to_wildcard = 0;
  5112. *msg = "whoops, forgot the error message";
  5113. if (!strcmp(to, "*") || !strcmp(from, "*")) {
  5114. *msg = "can't remap from or to *";
  5115. return -1;
  5116. }
  5117. /* Detect asterisks in expressions of type: '*.example.com' */
  5118. if (!strncmp(from,"*.",2)) {
  5119. from += 2;
  5120. from_wildcard = 1;
  5121. }
  5122. if (!strncmp(to,"*.",2)) {
  5123. to += 2;
  5124. to_wildcard = 1;
  5125. }
  5126. if (to_wildcard && !from_wildcard) {
  5127. *msg = "can only use wildcard (i.e. '*.') if 'from' address "
  5128. "uses wildcard also";
  5129. return -1;
  5130. }
  5131. if (address_is_invalid_destination(to, 1)) {
  5132. *msg = "destination is invalid";
  5133. return -1;
  5134. }
  5135. addressmap_register(from, tor_strdup(to), expires, addrmap_source,
  5136. from_wildcard, to_wildcard);
  5137. return 0;
  5138. }
  5139. /**
  5140. * Initialize the logs based on the configuration file.
  5141. */
  5142. static int
  5143. options_init_logs(const or_options_t *old_options, or_options_t *options,
  5144. int validate_only)
  5145. {
  5146. config_line_t *opt;
  5147. int ok;
  5148. smartlist_t *elts;
  5149. int run_as_daemon =
  5150. #ifdef _WIN32
  5151. 0;
  5152. #else
  5153. options->RunAsDaemon;
  5154. #endif
  5155. if (options->LogTimeGranularity <= 0) {
  5156. log_warn(LD_CONFIG, "Log time granularity '%d' has to be positive.",
  5157. options->LogTimeGranularity);
  5158. return -1;
  5159. } else if (1000 % options->LogTimeGranularity != 0 &&
  5160. options->LogTimeGranularity % 1000 != 0) {
  5161. int granularity = options->LogTimeGranularity;
  5162. if (granularity < 40) {
  5163. do granularity++;
  5164. while (1000 % granularity != 0);
  5165. } else if (granularity < 1000) {
  5166. granularity = 1000 / granularity;
  5167. while (1000 % granularity != 0)
  5168. granularity--;
  5169. granularity = 1000 / granularity;
  5170. } else {
  5171. granularity = 1000 * ((granularity / 1000) + 1);
  5172. }
  5173. log_warn(LD_CONFIG, "Log time granularity '%d' has to be either a "
  5174. "divisor or a multiple of 1 second. Changing to "
  5175. "'%d'.",
  5176. options->LogTimeGranularity, granularity);
  5177. if (!validate_only)
  5178. set_log_time_granularity(granularity);
  5179. } else {
  5180. if (!validate_only)
  5181. set_log_time_granularity(options->LogTimeGranularity);
  5182. }
  5183. ok = 1;
  5184. elts = smartlist_new();
  5185. for (opt = options->Logs; opt; opt = opt->next) {
  5186. log_severity_list_t *severity;
  5187. const char *cfg = opt->value;
  5188. severity = tor_malloc_zero(sizeof(log_severity_list_t));
  5189. if (parse_log_severity_config(&cfg, severity) < 0) {
  5190. log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
  5191. opt->value);
  5192. ok = 0; goto cleanup;
  5193. }
  5194. smartlist_split_string(elts, cfg, NULL,
  5195. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  5196. if (smartlist_len(elts) == 0)
  5197. smartlist_add_strdup(elts, "stdout");
  5198. if (smartlist_len(elts) == 1 &&
  5199. (!strcasecmp(smartlist_get(elts,0), "stdout") ||
  5200. !strcasecmp(smartlist_get(elts,0), "stderr"))) {
  5201. int err = smartlist_len(elts) &&
  5202. !strcasecmp(smartlist_get(elts,0), "stderr");
  5203. if (!validate_only) {
  5204. if (run_as_daemon) {
  5205. log_warn(LD_CONFIG,
  5206. "Can't log to %s with RunAsDaemon set; skipping stdout",
  5207. err?"stderr":"stdout");
  5208. } else {
  5209. add_stream_log(severity, err?"<stderr>":"<stdout>",
  5210. fileno(err?stderr:stdout));
  5211. }
  5212. }
  5213. goto cleanup;
  5214. }
  5215. if (smartlist_len(elts) == 1) {
  5216. if (!strcasecmp(smartlist_get(elts,0), "syslog")) {
  5217. #ifdef HAVE_SYSLOG_H
  5218. if (!validate_only) {
  5219. add_syslog_log(severity, options->SyslogIdentityTag);
  5220. }
  5221. #else
  5222. log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
  5223. #endif /* defined(HAVE_SYSLOG_H) */
  5224. goto cleanup;
  5225. }
  5226. if (!strcasecmp(smartlist_get(elts, 0), "android")) {
  5227. #ifdef HAVE_ANDROID_LOG_H
  5228. if (!validate_only) {
  5229. add_android_log(severity, options->AndroidIdentityTag);
  5230. }
  5231. #else
  5232. log_warn(LD_CONFIG, "Android logging is not supported"
  5233. " on this system. Sorry.");
  5234. #endif // HAVE_ANDROID_LOG_H.
  5235. goto cleanup;
  5236. }
  5237. }
  5238. if (smartlist_len(elts) == 2 &&
  5239. !strcasecmp(smartlist_get(elts,0), "file")) {
  5240. if (!validate_only) {
  5241. char *fname = expand_filename(smartlist_get(elts, 1));
  5242. /* Truncate if TruncateLogFile is set and we haven't seen this option
  5243. line before. */
  5244. int truncate_log = 0;
  5245. if (options->TruncateLogFile) {
  5246. truncate_log = 1;
  5247. if (old_options) {
  5248. config_line_t *opt2;
  5249. for (opt2 = old_options->Logs; opt2; opt2 = opt2->next)
  5250. if (!strcmp(opt->value, opt2->value)) {
  5251. truncate_log = 0;
  5252. break;
  5253. }
  5254. }
  5255. }
  5256. if (add_file_log(severity, fname, truncate_log) < 0) {
  5257. log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
  5258. opt->value, strerror(errno));
  5259. ok = 0;
  5260. }
  5261. tor_free(fname);
  5262. }
  5263. goto cleanup;
  5264. }
  5265. log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
  5266. opt->value);
  5267. ok = 0; goto cleanup;
  5268. cleanup:
  5269. SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
  5270. smartlist_clear(elts);
  5271. tor_free(severity);
  5272. }
  5273. smartlist_free(elts);
  5274. if (ok && !validate_only)
  5275. logs_set_domain_logging(options->LogMessageDomains);
  5276. return ok?0:-1;
  5277. }
  5278. /** Given a smartlist of SOCKS arguments to be passed to a transport
  5279. * proxy in <b>args</b>, validate them and return -1 if they are
  5280. * corrupted. Return 0 if they seem OK. */
  5281. static int
  5282. validate_transport_socks_arguments(const smartlist_t *args)
  5283. {
  5284. char *socks_string = NULL;
  5285. size_t socks_string_len;
  5286. tor_assert(args);
  5287. tor_assert(smartlist_len(args) > 0);
  5288. SMARTLIST_FOREACH_BEGIN(args, const char *, s) {
  5289. if (!string_is_key_value(LOG_WARN, s)) { /* items should be k=v items */
  5290. log_warn(LD_CONFIG, "'%s' is not a k=v item.", s);
  5291. return -1;
  5292. }
  5293. } SMARTLIST_FOREACH_END(s);
  5294. socks_string = pt_stringify_socks_args(args);
  5295. if (!socks_string)
  5296. return -1;
  5297. socks_string_len = strlen(socks_string);
  5298. tor_free(socks_string);
  5299. if (socks_string_len > MAX_SOCKS5_AUTH_SIZE_TOTAL) {
  5300. log_warn(LD_CONFIG, "SOCKS arguments can't be more than %u bytes (%lu).",
  5301. MAX_SOCKS5_AUTH_SIZE_TOTAL,
  5302. (unsigned long) socks_string_len);
  5303. return -1;
  5304. }
  5305. return 0;
  5306. }
  5307. /** Deallocate a bridge_line_t structure. */
  5308. /* private */ void
  5309. bridge_line_free_(bridge_line_t *bridge_line)
  5310. {
  5311. if (!bridge_line)
  5312. return;
  5313. if (bridge_line->socks_args) {
  5314. SMARTLIST_FOREACH(bridge_line->socks_args, char*, s, tor_free(s));
  5315. smartlist_free(bridge_line->socks_args);
  5316. }
  5317. tor_free(bridge_line->transport_name);
  5318. tor_free(bridge_line);
  5319. }
  5320. /** Parse the contents of a string, <b>line</b>, containing a Bridge line,
  5321. * into a bridge_line_t.
  5322. *
  5323. * Validates that the IP:PORT, fingerprint, and SOCKS arguments (given to the
  5324. * Pluggable Transport, if a one was specified) are well-formed.
  5325. *
  5326. * Returns NULL If the Bridge line could not be validated, and returns a
  5327. * bridge_line_t containing the parsed information otherwise.
  5328. *
  5329. * Bridge line format:
  5330. * Bridge [transport] IP:PORT [id-fingerprint] [k=v] [k=v] ...
  5331. */
  5332. /* private */ bridge_line_t *
  5333. parse_bridge_line(const char *line)
  5334. {
  5335. smartlist_t *items = NULL;
  5336. char *addrport=NULL, *fingerprint=NULL;
  5337. char *field=NULL;
  5338. bridge_line_t *bridge_line = tor_malloc_zero(sizeof(bridge_line_t));
  5339. items = smartlist_new();
  5340. smartlist_split_string(items, line, NULL,
  5341. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  5342. if (smartlist_len(items) < 1) {
  5343. log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
  5344. goto err;
  5345. }
  5346. /* first field is either a transport name or addrport */
  5347. field = smartlist_get(items, 0);
  5348. smartlist_del_keeporder(items, 0);
  5349. if (string_is_C_identifier(field)) {
  5350. /* It's a transport name. */
  5351. bridge_line->transport_name = field;
  5352. if (smartlist_len(items) < 1) {
  5353. log_warn(LD_CONFIG, "Too few items to Bridge line.");
  5354. goto err;
  5355. }
  5356. addrport = smartlist_get(items, 0); /* Next field is addrport then. */
  5357. smartlist_del_keeporder(items, 0);
  5358. } else {
  5359. addrport = field;
  5360. }
  5361. if (tor_addr_port_parse(LOG_INFO, addrport,
  5362. &bridge_line->addr, &bridge_line->port, 443)<0) {
  5363. log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
  5364. goto err;
  5365. }
  5366. /* If transports are enabled, next field could be a fingerprint or a
  5367. socks argument. If transports are disabled, next field must be
  5368. a fingerprint. */
  5369. if (smartlist_len(items)) {
  5370. if (bridge_line->transport_name) { /* transports enabled: */
  5371. field = smartlist_get(items, 0);
  5372. smartlist_del_keeporder(items, 0);
  5373. /* If it's a key=value pair, then it's a SOCKS argument for the
  5374. transport proxy... */
  5375. if (string_is_key_value(LOG_DEBUG, field)) {
  5376. bridge_line->socks_args = smartlist_new();
  5377. smartlist_add(bridge_line->socks_args, field);
  5378. } else { /* ...otherwise, it's the bridge fingerprint. */
  5379. fingerprint = field;
  5380. }
  5381. } else { /* transports disabled: */
  5382. fingerprint = smartlist_join_strings(items, "", 0, NULL);
  5383. }
  5384. }
  5385. /* Handle fingerprint, if it was provided. */
  5386. if (fingerprint) {
  5387. if (strlen(fingerprint) != HEX_DIGEST_LEN) {
  5388. log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
  5389. goto err;
  5390. }
  5391. if (base16_decode(bridge_line->digest, DIGEST_LEN,
  5392. fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
  5393. log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
  5394. goto err;
  5395. }
  5396. }
  5397. /* If we are using transports, any remaining items in the smartlist
  5398. should be k=v values. */
  5399. if (bridge_line->transport_name && smartlist_len(items)) {
  5400. if (!bridge_line->socks_args)
  5401. bridge_line->socks_args = smartlist_new();
  5402. /* append remaining items of 'items' to 'socks_args' */
  5403. smartlist_add_all(bridge_line->socks_args, items);
  5404. smartlist_clear(items);
  5405. tor_assert(smartlist_len(bridge_line->socks_args) > 0);
  5406. }
  5407. if (bridge_line->socks_args) {
  5408. if (validate_transport_socks_arguments(bridge_line->socks_args) < 0)
  5409. goto err;
  5410. }
  5411. goto done;
  5412. err:
  5413. bridge_line_free(bridge_line);
  5414. bridge_line = NULL;
  5415. done:
  5416. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  5417. smartlist_free(items);
  5418. tor_free(addrport);
  5419. tor_free(fingerprint);
  5420. return bridge_line;
  5421. }
  5422. /** Read the contents of a ClientTransportPlugin or ServerTransportPlugin
  5423. * line from <b>line</b>, depending on the value of <b>server</b>. Return 0
  5424. * if the line is well-formed, and -1 if it isn't.
  5425. *
  5426. * If <b>validate_only</b> is 0, the line is well-formed, and the transport is
  5427. * needed by some bridge:
  5428. * - If it's an external proxy line, add the transport described in the line to
  5429. * our internal transport list.
  5430. * - If it's a managed proxy line, launch the managed proxy.
  5431. */
  5432. STATIC int
  5433. parse_transport_line(const or_options_t *options,
  5434. const char *line, int validate_only,
  5435. int server)
  5436. {
  5437. smartlist_t *items = NULL;
  5438. int r;
  5439. const char *transports = NULL;
  5440. smartlist_t *transport_list = NULL;
  5441. char *type = NULL;
  5442. char *addrport = NULL;
  5443. tor_addr_t addr;
  5444. uint16_t port = 0;
  5445. int socks_ver = PROXY_NONE;
  5446. /* managed proxy options */
  5447. int is_managed = 0;
  5448. char **proxy_argv = NULL;
  5449. char **tmp = NULL;
  5450. int proxy_argc, i;
  5451. int is_useless_proxy = 1;
  5452. int line_length;
  5453. /* Split the line into space-separated tokens */
  5454. items = smartlist_new();
  5455. smartlist_split_string(items, line, NULL,
  5456. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  5457. line_length = smartlist_len(items);
  5458. if (line_length < 3) {
  5459. log_warn(LD_CONFIG,
  5460. "Too few arguments on %sTransportPlugin line.",
  5461. server ? "Server" : "Client");
  5462. goto err;
  5463. }
  5464. /* Get the first line element, split it to commas into
  5465. transport_list (in case it's multiple transports) and validate
  5466. the transport names. */
  5467. transports = smartlist_get(items, 0);
  5468. transport_list = smartlist_new();
  5469. smartlist_split_string(transport_list, transports, ",",
  5470. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  5471. SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
  5472. /* validate transport names */
  5473. if (!string_is_C_identifier(transport_name)) {
  5474. log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
  5475. transport_name);
  5476. goto err;
  5477. }
  5478. /* see if we actually need the transports provided by this proxy */
  5479. if (!validate_only && transport_is_needed(transport_name))
  5480. is_useless_proxy = 0;
  5481. } SMARTLIST_FOREACH_END(transport_name);
  5482. type = smartlist_get(items, 1);
  5483. if (!strcmp(type, "exec")) {
  5484. is_managed = 1;
  5485. } else if (server && !strcmp(type, "proxy")) {
  5486. /* 'proxy' syntax only with ServerTransportPlugin */
  5487. is_managed = 0;
  5488. } else if (!server && !strcmp(type, "socks4")) {
  5489. /* 'socks4' syntax only with ClientTransportPlugin */
  5490. is_managed = 0;
  5491. socks_ver = PROXY_SOCKS4;
  5492. } else if (!server && !strcmp(type, "socks5")) {
  5493. /* 'socks5' syntax only with ClientTransportPlugin */
  5494. is_managed = 0;
  5495. socks_ver = PROXY_SOCKS5;
  5496. } else {
  5497. log_warn(LD_CONFIG,
  5498. "Strange %sTransportPlugin type '%s'",
  5499. server ? "Server" : "Client", type);
  5500. goto err;
  5501. }
  5502. if (is_managed && options->Sandbox) {
  5503. log_warn(LD_CONFIG,
  5504. "Managed proxies are not compatible with Sandbox mode."
  5505. "(%sTransportPlugin line was %s)",
  5506. server ? "Server" : "Client", escaped(line));
  5507. goto err;
  5508. }
  5509. if (is_managed && options->NoExec) {
  5510. log_warn(LD_CONFIG,
  5511. "Managed proxies are not compatible with NoExec mode; ignoring."
  5512. "(%sTransportPlugin line was %s)",
  5513. server ? "Server" : "Client", escaped(line));
  5514. r = 0;
  5515. goto done;
  5516. }
  5517. if (is_managed) {
  5518. /* managed */
  5519. if (!server && !validate_only && is_useless_proxy) {
  5520. log_info(LD_GENERAL,
  5521. "Pluggable transport proxy (%s) does not provide "
  5522. "any needed transports and will not be launched.",
  5523. line);
  5524. }
  5525. /*
  5526. * If we are not just validating, use the rest of the line as the
  5527. * argv of the proxy to be launched. Also, make sure that we are
  5528. * only launching proxies that contribute useful transports.
  5529. */
  5530. if (!validate_only && (server || !is_useless_proxy)) {
  5531. proxy_argc = line_length - 2;
  5532. tor_assert(proxy_argc > 0);
  5533. proxy_argv = tor_calloc((proxy_argc + 1), sizeof(char *));
  5534. tmp = proxy_argv;
  5535. for (i = 0; i < proxy_argc; i++) {
  5536. /* store arguments */
  5537. *tmp++ = smartlist_get(items, 2);
  5538. smartlist_del_keeporder(items, 2);
  5539. }
  5540. *tmp = NULL; /* terminated with NULL, just like execve() likes it */
  5541. /* kickstart the thing */
  5542. if (server) {
  5543. pt_kickstart_server_proxy(transport_list, proxy_argv);
  5544. } else {
  5545. pt_kickstart_client_proxy(transport_list, proxy_argv);
  5546. }
  5547. }
  5548. } else {
  5549. /* external */
  5550. /* ClientTransportPlugins connecting through a proxy is managed only. */
  5551. if (!server && (options->Socks4Proxy || options->Socks5Proxy ||
  5552. options->HTTPSProxy)) {
  5553. log_warn(LD_CONFIG, "You have configured an external proxy with another "
  5554. "proxy type. (Socks4Proxy|Socks5Proxy|HTTPSProxy)");
  5555. goto err;
  5556. }
  5557. if (smartlist_len(transport_list) != 1) {
  5558. log_warn(LD_CONFIG,
  5559. "You can't have an external proxy with more than "
  5560. "one transport.");
  5561. goto err;
  5562. }
  5563. addrport = smartlist_get(items, 2);
  5564. if (tor_addr_port_lookup(addrport, &addr, &port) < 0) {
  5565. log_warn(LD_CONFIG,
  5566. "Error parsing transport address '%s'", addrport);
  5567. goto err;
  5568. }
  5569. if (!port) {
  5570. log_warn(LD_CONFIG,
  5571. "Transport address '%s' has no port.", addrport);
  5572. goto err;
  5573. }
  5574. if (!validate_only) {
  5575. log_info(LD_DIR, "%s '%s' at %s.",
  5576. server ? "Server transport" : "Transport",
  5577. transports, fmt_addrport(&addr, port));
  5578. if (!server) {
  5579. transport_add_from_config(&addr, port,
  5580. smartlist_get(transport_list, 0),
  5581. socks_ver);
  5582. }
  5583. }
  5584. }
  5585. r = 0;
  5586. goto done;
  5587. err:
  5588. r = -1;
  5589. done:
  5590. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  5591. smartlist_free(items);
  5592. if (transport_list) {
  5593. SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
  5594. smartlist_free(transport_list);
  5595. }
  5596. return r;
  5597. }
  5598. /** Given a ServerTransportListenAddr <b>line</b>, return its
  5599. * <address:port> string. Return NULL if the line was not
  5600. * well-formed.
  5601. *
  5602. * If <b>transport</b> is set, return NULL if the line is not
  5603. * referring to <b>transport</b>.
  5604. *
  5605. * The returned string is allocated on the heap and it's the
  5606. * responsibility of the caller to free it. */
  5607. static char *
  5608. get_bindaddr_from_transport_listen_line(const char *line,const char *transport)
  5609. {
  5610. smartlist_t *items = NULL;
  5611. const char *parsed_transport = NULL;
  5612. char *addrport = NULL;
  5613. tor_addr_t addr;
  5614. uint16_t port = 0;
  5615. items = smartlist_new();
  5616. smartlist_split_string(items, line, NULL,
  5617. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  5618. if (smartlist_len(items) < 2) {
  5619. log_warn(LD_CONFIG,"Too few arguments on ServerTransportListenAddr line.");
  5620. goto err;
  5621. }
  5622. parsed_transport = smartlist_get(items, 0);
  5623. addrport = tor_strdup(smartlist_get(items, 1));
  5624. /* If 'transport' is given, check if it matches the one on the line */
  5625. if (transport && strcmp(transport, parsed_transport))
  5626. goto err;
  5627. /* Validate addrport */
  5628. if (tor_addr_port_parse(LOG_WARN, addrport, &addr, &port, -1)<0) {
  5629. log_warn(LD_CONFIG, "Error parsing ServerTransportListenAddr "
  5630. "address '%s'", addrport);
  5631. goto err;
  5632. }
  5633. goto done;
  5634. err:
  5635. tor_free(addrport);
  5636. addrport = NULL;
  5637. done:
  5638. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  5639. smartlist_free(items);
  5640. return addrport;
  5641. }
  5642. /** Given a ServerTransportOptions <b>line</b>, return a smartlist
  5643. * with the options. Return NULL if the line was not well-formed.
  5644. *
  5645. * If <b>transport</b> is set, return NULL if the line is not
  5646. * referring to <b>transport</b>.
  5647. *
  5648. * The returned smartlist and its strings are allocated on the heap
  5649. * and it's the responsibility of the caller to free it. */
  5650. smartlist_t *
  5651. get_options_from_transport_options_line(const char *line,const char *transport)
  5652. {
  5653. smartlist_t *items = smartlist_new();
  5654. smartlist_t *options = smartlist_new();
  5655. const char *parsed_transport = NULL;
  5656. smartlist_split_string(items, line, NULL,
  5657. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  5658. if (smartlist_len(items) < 2) {
  5659. log_warn(LD_CONFIG,"Too few arguments on ServerTransportOptions line.");
  5660. goto err;
  5661. }
  5662. parsed_transport = smartlist_get(items, 0);
  5663. /* If 'transport' is given, check if it matches the one on the line */
  5664. if (transport && strcmp(transport, parsed_transport))
  5665. goto err;
  5666. SMARTLIST_FOREACH_BEGIN(items, const char *, option) {
  5667. if (option_sl_idx == 0) /* skip the transport field (first field)*/
  5668. continue;
  5669. /* validate that it's a k=v value */
  5670. if (!string_is_key_value(LOG_WARN, option)) {
  5671. log_warn(LD_CONFIG, "%s is not a k=v value.", escaped(option));
  5672. goto err;
  5673. }
  5674. /* add it to the options smartlist */
  5675. smartlist_add_strdup(options, option);
  5676. log_debug(LD_CONFIG, "Added %s to the list of options", escaped(option));
  5677. } SMARTLIST_FOREACH_END(option);
  5678. goto done;
  5679. err:
  5680. SMARTLIST_FOREACH(options, char*, s, tor_free(s));
  5681. smartlist_free(options);
  5682. options = NULL;
  5683. done:
  5684. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  5685. smartlist_free(items);
  5686. return options;
  5687. }
  5688. /** Given the name of a pluggable transport in <b>transport</b>, check
  5689. * the configuration file to see if the user has explicitly asked for
  5690. * it to listen on a specific port. Return a <address:port> string if
  5691. * so, otherwise NULL. */
  5692. char *
  5693. get_transport_bindaddr_from_config(const char *transport)
  5694. {
  5695. config_line_t *cl;
  5696. const or_options_t *options = get_options();
  5697. for (cl = options->ServerTransportListenAddr; cl; cl = cl->next) {
  5698. char *bindaddr =
  5699. get_bindaddr_from_transport_listen_line(cl->value, transport);
  5700. if (bindaddr)
  5701. return bindaddr;
  5702. }
  5703. return NULL;
  5704. }
  5705. /** Given the name of a pluggable transport in <b>transport</b>, check
  5706. * the configuration file to see if the user has asked us to pass any
  5707. * parameters to the pluggable transport. Return a smartlist
  5708. * containing the parameters, otherwise NULL. */
  5709. smartlist_t *
  5710. get_options_for_server_transport(const char *transport)
  5711. {
  5712. config_line_t *cl;
  5713. const or_options_t *options = get_options();
  5714. for (cl = options->ServerTransportOptions; cl; cl = cl->next) {
  5715. smartlist_t *options_sl =
  5716. get_options_from_transport_options_line(cl->value, transport);
  5717. if (options_sl)
  5718. return options_sl;
  5719. }
  5720. return NULL;
  5721. }
  5722. /** Read the contents of a DirAuthority line from <b>line</b>. If
  5723. * <b>validate_only</b> is 0, and the line is well-formed, and it
  5724. * shares any bits with <b>required_type</b> or <b>required_type</b>
  5725. * is NO_DIRINFO (zero), then add the dirserver described in the line
  5726. * (minus whatever bits it's missing) as a valid authority.
  5727. * Return 0 on success or filtering out by type,
  5728. * or -1 if the line isn't well-formed or if we can't add it. */
  5729. STATIC int
  5730. parse_dir_authority_line(const char *line, dirinfo_type_t required_type,
  5731. int validate_only)
  5732. {
  5733. smartlist_t *items = NULL;
  5734. int r;
  5735. char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
  5736. tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
  5737. uint16_t dir_port = 0, or_port = 0;
  5738. char digest[DIGEST_LEN];
  5739. char v3_digest[DIGEST_LEN];
  5740. dirinfo_type_t type = 0;
  5741. double weight = 1.0;
  5742. memset(v3_digest, 0, sizeof(v3_digest));
  5743. items = smartlist_new();
  5744. smartlist_split_string(items, line, NULL,
  5745. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  5746. if (smartlist_len(items) < 1) {
  5747. log_warn(LD_CONFIG, "No arguments on DirAuthority line.");
  5748. goto err;
  5749. }
  5750. if (is_legal_nickname(smartlist_get(items, 0))) {
  5751. nickname = smartlist_get(items, 0);
  5752. smartlist_del_keeporder(items, 0);
  5753. }
  5754. while (smartlist_len(items)) {
  5755. char *flag = smartlist_get(items, 0);
  5756. if (TOR_ISDIGIT(flag[0]))
  5757. break;
  5758. if (!strcasecmp(flag, "hs") ||
  5759. !strcasecmp(flag, "no-hs")) {
  5760. log_warn(LD_CONFIG, "The DirAuthority options 'hs' and 'no-hs' are "
  5761. "obsolete; you don't need them any more.");
  5762. } else if (!strcasecmp(flag, "bridge")) {
  5763. type |= BRIDGE_DIRINFO;
  5764. } else if (!strcasecmp(flag, "no-v2")) {
  5765. /* obsolete, but may still be contained in DirAuthority lines generated
  5766. by various tools */;
  5767. } else if (!strcasecmpstart(flag, "orport=")) {
  5768. int ok;
  5769. char *portstring = flag + strlen("orport=");
  5770. or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
  5771. if (!ok)
  5772. log_warn(LD_CONFIG, "Invalid orport '%s' on DirAuthority line.",
  5773. portstring);
  5774. } else if (!strcmpstart(flag, "weight=")) {
  5775. int ok;
  5776. const char *wstring = flag + strlen("weight=");
  5777. weight = tor_parse_double(wstring, 0, (double)UINT64_MAX, &ok, NULL);
  5778. if (!ok) {
  5779. log_warn(LD_CONFIG, "Invalid weight '%s' on DirAuthority line.",flag);
  5780. weight=1.0;
  5781. }
  5782. } else if (!strcasecmpstart(flag, "v3ident=")) {
  5783. char *idstr = flag + strlen("v3ident=");
  5784. if (strlen(idstr) != HEX_DIGEST_LEN ||
  5785. base16_decode(v3_digest, DIGEST_LEN,
  5786. idstr, HEX_DIGEST_LEN) != DIGEST_LEN) {
  5787. log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirAuthority line",
  5788. flag);
  5789. } else {
  5790. type |= V3_DIRINFO|EXTRAINFO_DIRINFO|MICRODESC_DIRINFO;
  5791. }
  5792. } else if (!strcasecmpstart(flag, "ipv6=")) {
  5793. if (ipv6_addrport_ptr) {
  5794. log_warn(LD_CONFIG, "Redundant ipv6 addr/port on DirAuthority line");
  5795. } else {
  5796. if (tor_addr_port_parse(LOG_WARN, flag+strlen("ipv6="),
  5797. &ipv6_addrport.addr, &ipv6_addrport.port,
  5798. -1) < 0
  5799. || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
  5800. log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on DirAuthority line",
  5801. escaped(flag));
  5802. goto err;
  5803. }
  5804. ipv6_addrport_ptr = &ipv6_addrport;
  5805. }
  5806. } else {
  5807. log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirAuthority line",
  5808. flag);
  5809. }
  5810. tor_free(flag);
  5811. smartlist_del_keeporder(items, 0);
  5812. }
  5813. if (smartlist_len(items) < 2) {
  5814. log_warn(LD_CONFIG, "Too few arguments to DirAuthority line.");
  5815. goto err;
  5816. }
  5817. addrport = smartlist_get(items, 0);
  5818. smartlist_del_keeporder(items, 0);
  5819. if (addr_port_lookup(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
  5820. log_warn(LD_CONFIG, "Error parsing DirAuthority address '%s'", addrport);
  5821. goto err;
  5822. }
  5823. if (!dir_port) {
  5824. log_warn(LD_CONFIG, "Missing port in DirAuthority address '%s'",addrport);
  5825. goto err;
  5826. }
  5827. fingerprint = smartlist_join_strings(items, "", 0, NULL);
  5828. if (strlen(fingerprint) != HEX_DIGEST_LEN) {
  5829. log_warn(LD_CONFIG, "Key digest '%s' for DirAuthority is wrong length %d.",
  5830. fingerprint, (int)strlen(fingerprint));
  5831. goto err;
  5832. }
  5833. if (base16_decode(digest, DIGEST_LEN,
  5834. fingerprint, HEX_DIGEST_LEN) != DIGEST_LEN) {
  5835. log_warn(LD_CONFIG, "Unable to decode DirAuthority key digest.");
  5836. goto err;
  5837. }
  5838. if (!validate_only && (!required_type || required_type & type)) {
  5839. dir_server_t *ds;
  5840. if (required_type)
  5841. type &= required_type; /* pare down what we think of them as an
  5842. * authority for. */
  5843. log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
  5844. address, (int)dir_port, (char*)smartlist_get(items,0));
  5845. if (!(ds = trusted_dir_server_new(nickname, address, dir_port, or_port,
  5846. ipv6_addrport_ptr,
  5847. digest, v3_digest, type, weight)))
  5848. goto err;
  5849. dir_server_add(ds);
  5850. }
  5851. r = 0;
  5852. goto done;
  5853. err:
  5854. r = -1;
  5855. done:
  5856. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  5857. smartlist_free(items);
  5858. tor_free(addrport);
  5859. tor_free(address);
  5860. tor_free(nickname);
  5861. tor_free(fingerprint);
  5862. return r;
  5863. }
  5864. /** Read the contents of a FallbackDir line from <b>line</b>. If
  5865. * <b>validate_only</b> is 0, and the line is well-formed, then add the
  5866. * dirserver described in the line as a fallback directory. Return 0 on
  5867. * success, or -1 if the line isn't well-formed or if we can't add it. */
  5868. int
  5869. parse_dir_fallback_line(const char *line,
  5870. int validate_only)
  5871. {
  5872. int r = -1;
  5873. smartlist_t *items = smartlist_new(), *positional = smartlist_new();
  5874. int orport = -1;
  5875. uint16_t dirport;
  5876. tor_addr_t addr;
  5877. int ok;
  5878. char id[DIGEST_LEN];
  5879. char *address=NULL;
  5880. tor_addr_port_t ipv6_addrport, *ipv6_addrport_ptr = NULL;
  5881. double weight=1.0;
  5882. memset(id, 0, sizeof(id));
  5883. smartlist_split_string(items, line, NULL,
  5884. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  5885. SMARTLIST_FOREACH_BEGIN(items, const char *, cp) {
  5886. const char *eq = strchr(cp, '=');
  5887. ok = 1;
  5888. if (! eq) {
  5889. smartlist_add(positional, (char*)cp);
  5890. continue;
  5891. }
  5892. if (!strcmpstart(cp, "orport=")) {
  5893. orport = (int)tor_parse_long(cp+strlen("orport="), 10,
  5894. 1, 65535, &ok, NULL);
  5895. } else if (!strcmpstart(cp, "id=")) {
  5896. ok = base16_decode(id, DIGEST_LEN, cp+strlen("id="),
  5897. strlen(cp)-strlen("id=")) == DIGEST_LEN;
  5898. } else if (!strcasecmpstart(cp, "ipv6=")) {
  5899. if (ipv6_addrport_ptr) {
  5900. log_warn(LD_CONFIG, "Redundant ipv6 addr/port on FallbackDir line");
  5901. } else {
  5902. if (tor_addr_port_parse(LOG_WARN, cp+strlen("ipv6="),
  5903. &ipv6_addrport.addr, &ipv6_addrport.port,
  5904. -1) < 0
  5905. || tor_addr_family(&ipv6_addrport.addr) != AF_INET6) {
  5906. log_warn(LD_CONFIG, "Bad ipv6 addr/port %s on FallbackDir line",
  5907. escaped(cp));
  5908. goto end;
  5909. }
  5910. ipv6_addrport_ptr = &ipv6_addrport;
  5911. }
  5912. } else if (!strcmpstart(cp, "weight=")) {
  5913. int num_ok;
  5914. const char *wstring = cp + strlen("weight=");
  5915. weight = tor_parse_double(wstring, 0, (double)UINT64_MAX, &num_ok, NULL);
  5916. if (!num_ok) {
  5917. log_warn(LD_CONFIG, "Invalid weight '%s' on FallbackDir line.", cp);
  5918. weight=1.0;
  5919. }
  5920. }
  5921. if (!ok) {
  5922. log_warn(LD_CONFIG, "Bad FallbackDir option %s", escaped(cp));
  5923. goto end;
  5924. }
  5925. } SMARTLIST_FOREACH_END(cp);
  5926. if (smartlist_len(positional) != 1) {
  5927. log_warn(LD_CONFIG, "Couldn't parse FallbackDir line %s", escaped(line));
  5928. goto end;
  5929. }
  5930. if (tor_digest_is_zero(id)) {
  5931. log_warn(LD_CONFIG, "Missing identity on FallbackDir line");
  5932. goto end;
  5933. }
  5934. if (orport <= 0) {
  5935. log_warn(LD_CONFIG, "Missing orport on FallbackDir line");
  5936. goto end;
  5937. }
  5938. if (tor_addr_port_split(LOG_INFO, smartlist_get(positional, 0),
  5939. &address, &dirport) < 0 ||
  5940. tor_addr_parse(&addr, address)<0) {
  5941. log_warn(LD_CONFIG, "Couldn't parse address:port %s on FallbackDir line",
  5942. (const char*)smartlist_get(positional, 0));
  5943. goto end;
  5944. }
  5945. if (!validate_only) {
  5946. dir_server_t *ds;
  5947. ds = fallback_dir_server_new(&addr, dirport, orport, ipv6_addrport_ptr,
  5948. id, weight);
  5949. if (!ds) {
  5950. log_warn(LD_CONFIG, "Couldn't create FallbackDir %s", escaped(line));
  5951. goto end;
  5952. }
  5953. dir_server_add(ds);
  5954. }
  5955. r = 0;
  5956. end:
  5957. SMARTLIST_FOREACH(items, char *, cp, tor_free(cp));
  5958. smartlist_free(items);
  5959. smartlist_free(positional);
  5960. tor_free(address);
  5961. return r;
  5962. }
  5963. /** Allocate and return a new port_cfg_t with reasonable defaults. */
  5964. STATIC port_cfg_t *
  5965. port_cfg_new(size_t namelen)
  5966. {
  5967. tor_assert(namelen <= SIZE_T_CEILING - sizeof(port_cfg_t) - 1);
  5968. port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t) + namelen + 1);
  5969. cfg->entry_cfg.ipv4_traffic = 1;
  5970. cfg->entry_cfg.ipv6_traffic = 1;
  5971. cfg->entry_cfg.dns_request = 1;
  5972. cfg->entry_cfg.onion_traffic = 1;
  5973. cfg->entry_cfg.prefer_ipv6_virtaddr = 1;
  5974. return cfg;
  5975. }
  5976. /** Free all storage held in <b>port</b> */
  5977. STATIC void
  5978. port_cfg_free_(port_cfg_t *port)
  5979. {
  5980. tor_free(port);
  5981. }
  5982. /** Warn for every port in <b>ports</b> of type <b>listener_type</b> that is
  5983. * on a publicly routable address. */
  5984. static void
  5985. warn_nonlocal_client_ports(const smartlist_t *ports,
  5986. const char *portname,
  5987. const int listener_type)
  5988. {
  5989. SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
  5990. if (port->type != listener_type)
  5991. continue;
  5992. if (port->is_unix_addr) {
  5993. /* Unix sockets aren't accessible over a network. */
  5994. } else if (!tor_addr_is_internal(&port->addr, 1)) {
  5995. log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
  5996. "Other people on the Internet might find your computer and "
  5997. "use it as an open proxy. Please don't allow this unless you "
  5998. "have a good reason.",
  5999. fmt_addrport(&port->addr, port->port), portname);
  6000. } else if (!tor_addr_is_loopback(&port->addr)) {
  6001. log_notice(LD_CONFIG, "You configured a non-loopback address '%s' "
  6002. "for %sPort. This allows everybody on your local network to "
  6003. "use your machine as a proxy. Make sure this is what you "
  6004. "wanted.",
  6005. fmt_addrport(&port->addr, port->port), portname);
  6006. }
  6007. } SMARTLIST_FOREACH_END(port);
  6008. }
  6009. /** Warn for every Extended ORPort port in <b>ports</b> that is on a
  6010. * publicly routable address. */
  6011. static void
  6012. warn_nonlocal_ext_orports(const smartlist_t *ports, const char *portname)
  6013. {
  6014. SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
  6015. if (port->type != CONN_TYPE_EXT_OR_LISTENER)
  6016. continue;
  6017. if (port->is_unix_addr)
  6018. continue;
  6019. /* XXX maybe warn even if address is RFC1918? */
  6020. if (!tor_addr_is_internal(&port->addr, 1)) {
  6021. log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
  6022. "This is not advised; this address is supposed to only be "
  6023. "exposed on localhost so that your pluggable transport "
  6024. "proxies can connect to it.",
  6025. fmt_addrport(&port->addr, port->port), portname);
  6026. }
  6027. } SMARTLIST_FOREACH_END(port);
  6028. }
  6029. /** Given a list of port_cfg_t in <b>ports</b>, warn if any controller port
  6030. * there is listening on any non-loopback address. If <b>forbid_nonlocal</b>
  6031. * is true, then emit a stronger warning and remove the port from the list.
  6032. */
  6033. static void
  6034. warn_nonlocal_controller_ports(smartlist_t *ports, unsigned forbid_nonlocal)
  6035. {
  6036. int warned = 0;
  6037. SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
  6038. if (port->type != CONN_TYPE_CONTROL_LISTENER)
  6039. continue;
  6040. if (port->is_unix_addr)
  6041. continue;
  6042. if (!tor_addr_is_loopback(&port->addr)) {
  6043. if (forbid_nonlocal) {
  6044. if (!warned)
  6045. log_warn(LD_CONFIG,
  6046. "You have a ControlPort set to accept "
  6047. "unauthenticated connections from a non-local address. "
  6048. "This means that programs not running on your computer "
  6049. "can reconfigure your Tor, without even having to guess a "
  6050. "password. That's so bad that I'm closing your ControlPort "
  6051. "for you. If you need to control your Tor remotely, try "
  6052. "enabling authentication and using a tool like stunnel or "
  6053. "ssh to encrypt remote access.");
  6054. warned = 1;
  6055. port_cfg_free(port);
  6056. SMARTLIST_DEL_CURRENT(ports, port);
  6057. } else {
  6058. log_warn(LD_CONFIG, "You have a ControlPort set to accept "
  6059. "connections from a non-local address. This means that "
  6060. "programs not running on your computer can reconfigure your "
  6061. "Tor. That's pretty bad, since the controller "
  6062. "protocol isn't encrypted! Maybe you should just listen on "
  6063. "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
  6064. "remote connections to your control port.");
  6065. return; /* No point in checking the rest */
  6066. }
  6067. }
  6068. } SMARTLIST_FOREACH_END(port);
  6069. }
  6070. /**
  6071. * Take a string (<b>line</b>) that begins with either an address:port, a
  6072. * port, or an AF_UNIX address, optionally quoted, prefixed with
  6073. * "unix:". Parse that line, and on success, set <b>addrport_out</b> to a new
  6074. * string containing the beginning portion (without prefix). Iff there was a
  6075. * unix: prefix, set <b>is_unix_out</b> to true. On success, also set
  6076. * <b>rest_out</b> to point to the part of the line after the address portion.
  6077. *
  6078. * Return 0 on success, -1 on failure.
  6079. */
  6080. int
  6081. port_cfg_line_extract_addrport(const char *line,
  6082. char **addrport_out,
  6083. int *is_unix_out,
  6084. const char **rest_out)
  6085. {
  6086. tor_assert(line);
  6087. tor_assert(addrport_out);
  6088. tor_assert(is_unix_out);
  6089. tor_assert(rest_out);
  6090. line = eat_whitespace(line);
  6091. if (!strcmpstart(line, unix_q_socket_prefix)) {
  6092. // It starts with unix:"
  6093. size_t sz;
  6094. *is_unix_out = 1;
  6095. *addrport_out = NULL;
  6096. line += strlen(unix_socket_prefix); /*No q: Keep the quote */
  6097. *rest_out = unescape_string(line, addrport_out, &sz);
  6098. if (!*rest_out || (*addrport_out && sz != strlen(*addrport_out))) {
  6099. tor_free(*addrport_out);
  6100. return -1;
  6101. }
  6102. *rest_out = eat_whitespace(*rest_out);
  6103. return 0;
  6104. } else {
  6105. // Is there a unix: prefix?
  6106. if (!strcmpstart(line, unix_socket_prefix)) {
  6107. line += strlen(unix_socket_prefix);
  6108. *is_unix_out = 1;
  6109. } else {
  6110. *is_unix_out = 0;
  6111. }
  6112. const char *end = find_whitespace(line);
  6113. if (BUG(!end)) {
  6114. end = strchr(line, '\0'); // LCOV_EXCL_LINE -- this can't be NULL
  6115. }
  6116. tor_assert(end && end >= line);
  6117. *addrport_out = tor_strndup(line, end - line);
  6118. *rest_out = eat_whitespace(end);
  6119. return 0;
  6120. }
  6121. }
  6122. static void
  6123. warn_client_dns_cache(const char *option, int disabling)
  6124. {
  6125. if (disabling)
  6126. return;
  6127. warn_deprecated_option(option,
  6128. "Client-side DNS cacheing enables a wide variety of route-"
  6129. "capture attacks. If a single bad exit node lies to you about "
  6130. "an IP address, cacheing that address would make you visit "
  6131. "an address of the attacker's choice every time you connected "
  6132. "to your destination.");
  6133. }
  6134. /**
  6135. * Validate the configured bridge distribution method from a BridgeDistribution
  6136. * config line.
  6137. *
  6138. * The input <b>bd</b>, is a string taken from the BridgeDistribution config
  6139. * line (if present). If the option wasn't set, return 0 immediately. The
  6140. * BridgeDistribution option is then validated. Currently valid, recognised
  6141. * options are:
  6142. *
  6143. * - "none"
  6144. * - "any"
  6145. * - "https"
  6146. * - "email"
  6147. * - "moat"
  6148. * - "hyphae"
  6149. *
  6150. * If the option string is unrecognised, a warning will be logged and 0 is
  6151. * returned. If the option string contains an invalid character, -1 is
  6152. * returned.
  6153. **/
  6154. STATIC int
  6155. check_bridge_distribution_setting(const char *bd)
  6156. {
  6157. if (bd == NULL)
  6158. return 0;
  6159. const char *RECOGNIZED[] = {
  6160. "none", "any", "https", "email", "moat", "hyphae"
  6161. };
  6162. unsigned i;
  6163. for (i = 0; i < ARRAY_LENGTH(RECOGNIZED); ++i) {
  6164. if (!strcmp(bd, RECOGNIZED[i]))
  6165. return 0;
  6166. }
  6167. const char *cp = bd;
  6168. // Method = (KeywordChar | "_") +
  6169. while (TOR_ISALNUM(*cp) || *cp == '-' || *cp == '_')
  6170. ++cp;
  6171. if (*cp == 0) {
  6172. log_warn(LD_CONFIG, "Unrecognized BridgeDistribution value %s. I'll "
  6173. "assume you know what you are doing...", escaped(bd));
  6174. return 0; // we reached the end of the string; all is well
  6175. } else {
  6176. return -1; // we found a bad character in the string.
  6177. }
  6178. }
  6179. /**
  6180. * Parse port configuration for a single port type.
  6181. *
  6182. * Read entries of the "FooPort" type from the list <b>ports</b>. Syntax is
  6183. * that FooPort can have any number of entries of the format
  6184. * "[Address:][Port] IsolationOptions".
  6185. *
  6186. * In log messages, describe the port type as <b>portname</b>.
  6187. *
  6188. * If no address is specified, default to <b>defaultaddr</b>. If no
  6189. * FooPort is given, default to defaultport (if 0, there is no default).
  6190. *
  6191. * If CL_PORT_NO_STREAM_OPTIONS is set in <b>flags</b>, do not allow stream
  6192. * isolation options in the FooPort entries.
  6193. *
  6194. * If CL_PORT_WARN_NONLOCAL is set in <b>flags</b>, warn if any of the
  6195. * ports are not on a local address. If CL_PORT_FORBID_NONLOCAL is set,
  6196. * this is a control port with no password set: don't even allow it.
  6197. *
  6198. * If CL_PORT_SERVER_OPTIONS is set in <b>flags</b>, do not allow stream
  6199. * isolation options in the FooPort entries; instead allow the
  6200. * server-port option set.
  6201. *
  6202. * If CL_PORT_TAKES_HOSTNAMES is set in <b>flags</b>, allow the options
  6203. * {No,}IPv{4,6}Traffic.
  6204. *
  6205. * On success, if <b>out</b> is given, add a new port_cfg_t entry to
  6206. * <b>out</b> for every port that the client should listen on. Return 0
  6207. * on success, -1 on failure.
  6208. */
  6209. STATIC int
  6210. parse_port_config(smartlist_t *out,
  6211. const config_line_t *ports,
  6212. const char *portname,
  6213. int listener_type,
  6214. const char *defaultaddr,
  6215. int defaultport,
  6216. const unsigned flags)
  6217. {
  6218. smartlist_t *elts;
  6219. int retval = -1;
  6220. const unsigned is_control = (listener_type == CONN_TYPE_CONTROL_LISTENER);
  6221. const unsigned is_ext_orport = (listener_type == CONN_TYPE_EXT_OR_LISTENER);
  6222. const unsigned allow_no_stream_options = flags & CL_PORT_NO_STREAM_OPTIONS;
  6223. const unsigned use_server_options = flags & CL_PORT_SERVER_OPTIONS;
  6224. const unsigned warn_nonlocal = flags & CL_PORT_WARN_NONLOCAL;
  6225. const unsigned forbid_nonlocal = flags & CL_PORT_FORBID_NONLOCAL;
  6226. const unsigned default_to_group_writable =
  6227. flags & CL_PORT_DFLT_GROUP_WRITABLE;
  6228. const unsigned takes_hostnames = flags & CL_PORT_TAKES_HOSTNAMES;
  6229. const unsigned is_unix_socket = flags & CL_PORT_IS_UNIXSOCKET;
  6230. int got_zero_port=0, got_nonzero_port=0;
  6231. char *unix_socket_path = NULL;
  6232. /* If there's no FooPort, then maybe make a default one. */
  6233. if (! ports) {
  6234. if (defaultport && defaultaddr && out) {
  6235. port_cfg_t *cfg = port_cfg_new(is_unix_socket ? strlen(defaultaddr) : 0);
  6236. cfg->type = listener_type;
  6237. if (is_unix_socket) {
  6238. tor_addr_make_unspec(&cfg->addr);
  6239. memcpy(cfg->unix_addr, defaultaddr, strlen(defaultaddr) + 1);
  6240. cfg->is_unix_addr = 1;
  6241. } else {
  6242. cfg->port = defaultport;
  6243. tor_addr_parse(&cfg->addr, defaultaddr);
  6244. }
  6245. cfg->entry_cfg.session_group = SESSION_GROUP_UNSET;
  6246. cfg->entry_cfg.isolation_flags = ISO_DEFAULT;
  6247. smartlist_add(out, cfg);
  6248. }
  6249. return 0;
  6250. }
  6251. /* At last we can actually parse the FooPort lines. The syntax is:
  6252. * [Addr:](Port|auto) [Options].*/
  6253. elts = smartlist_new();
  6254. char *addrport = NULL;
  6255. for (; ports; ports = ports->next) {
  6256. tor_addr_t addr;
  6257. int port;
  6258. int sessiongroup = SESSION_GROUP_UNSET;
  6259. unsigned isolation = ISO_DEFAULT;
  6260. int prefer_no_auth = 0;
  6261. int socks_iso_keep_alive = 0;
  6262. uint16_t ptmp=0;
  6263. int ok;
  6264. /* This must be kept in sync with port_cfg_new's defaults */
  6265. int no_listen = 0, no_advertise = 0, all_addrs = 0,
  6266. bind_ipv4_only = 0, bind_ipv6_only = 0,
  6267. ipv4_traffic = 1, ipv6_traffic = 1, prefer_ipv6 = 0, dns_request = 1,
  6268. onion_traffic = 1,
  6269. cache_ipv4 = 0, use_cached_ipv4 = 0,
  6270. cache_ipv6 = 0, use_cached_ipv6 = 0,
  6271. prefer_ipv6_automap = 1, world_writable = 0, group_writable = 0,
  6272. relax_dirmode_check = 0,
  6273. has_used_unix_socket_only_option = 0;
  6274. int is_unix_tagged_addr = 0;
  6275. const char *rest_of_line = NULL;
  6276. if (port_cfg_line_extract_addrport(ports->value,
  6277. &addrport, &is_unix_tagged_addr, &rest_of_line)<0) {
  6278. log_warn(LD_CONFIG, "Invalid %sPort line with unparsable address",
  6279. portname);
  6280. goto err;
  6281. }
  6282. if (strlen(addrport) == 0) {
  6283. log_warn(LD_CONFIG, "Invalid %sPort line with no address", portname);
  6284. goto err;
  6285. }
  6286. /* Split the remainder... */
  6287. smartlist_split_string(elts, rest_of_line, NULL,
  6288. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  6289. /* Let's start to check if it's a Unix socket path. */
  6290. if (is_unix_tagged_addr) {
  6291. #ifndef HAVE_SYS_UN_H
  6292. log_warn(LD_CONFIG, "Unix sockets not supported on this system.");
  6293. goto err;
  6294. #endif
  6295. unix_socket_path = addrport;
  6296. addrport = NULL;
  6297. }
  6298. if (unix_socket_path &&
  6299. ! conn_listener_type_supports_af_unix(listener_type)) {
  6300. log_warn(LD_CONFIG, "%sPort does not support unix sockets", portname);
  6301. goto err;
  6302. }
  6303. if (unix_socket_path) {
  6304. port = 1;
  6305. } else if (is_unix_socket) {
  6306. if (BUG(!addrport))
  6307. goto err; // LCOV_EXCL_LINE unreachable, but coverity can't tell that
  6308. unix_socket_path = tor_strdup(addrport);
  6309. if (!strcmp(addrport, "0"))
  6310. port = 0;
  6311. else
  6312. port = 1;
  6313. } else if (!strcmp(addrport, "auto")) {
  6314. port = CFG_AUTO_PORT;
  6315. int af = tor_addr_parse(&addr, defaultaddr);
  6316. tor_assert(af >= 0);
  6317. } else if (!strcasecmpend(addrport, ":auto")) {
  6318. char *addrtmp = tor_strndup(addrport, strlen(addrport)-5);
  6319. port = CFG_AUTO_PORT;
  6320. if (tor_addr_port_lookup(addrtmp, &addr, &ptmp)<0 || ptmp) {
  6321. log_warn(LD_CONFIG, "Invalid address '%s' for %sPort",
  6322. escaped(addrport), portname);
  6323. tor_free(addrtmp);
  6324. goto err;
  6325. }
  6326. tor_free(addrtmp);
  6327. } else {
  6328. /* Try parsing integer port before address, because, who knows?
  6329. "9050" might be a valid address. */
  6330. port = (int) tor_parse_long(addrport, 10, 0, 65535, &ok, NULL);
  6331. if (ok) {
  6332. int af = tor_addr_parse(&addr, defaultaddr);
  6333. tor_assert(af >= 0);
  6334. } else if (tor_addr_port_lookup(addrport, &addr, &ptmp) == 0) {
  6335. if (ptmp == 0) {
  6336. log_warn(LD_CONFIG, "%sPort line has address but no port", portname);
  6337. goto err;
  6338. }
  6339. port = ptmp;
  6340. } else {
  6341. log_warn(LD_CONFIG, "Couldn't parse address %s for %sPort",
  6342. escaped(addrport), portname);
  6343. goto err;
  6344. }
  6345. }
  6346. if (unix_socket_path && default_to_group_writable)
  6347. group_writable = 1;
  6348. /* Now parse the rest of the options, if any. */
  6349. if (use_server_options) {
  6350. /* This is a server port; parse advertising options */
  6351. SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
  6352. if (!strcasecmp(elt, "NoAdvertise")) {
  6353. no_advertise = 1;
  6354. } else if (!strcasecmp(elt, "NoListen")) {
  6355. no_listen = 1;
  6356. #if 0
  6357. /* not implemented yet. */
  6358. } else if (!strcasecmp(elt, "AllAddrs")) {
  6359. all_addrs = 1;
  6360. #endif /* 0 */
  6361. } else if (!strcasecmp(elt, "IPv4Only")) {
  6362. bind_ipv4_only = 1;
  6363. } else if (!strcasecmp(elt, "IPv6Only")) {
  6364. bind_ipv6_only = 1;
  6365. } else {
  6366. log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
  6367. portname, escaped(elt));
  6368. }
  6369. } SMARTLIST_FOREACH_END(elt);
  6370. if (no_advertise && no_listen) {
  6371. log_warn(LD_CONFIG, "Tried to set both NoListen and NoAdvertise "
  6372. "on %sPort line '%s'",
  6373. portname, escaped(ports->value));
  6374. goto err;
  6375. }
  6376. if (bind_ipv4_only && bind_ipv6_only) {
  6377. log_warn(LD_CONFIG, "Tried to set both IPv4Only and IPv6Only "
  6378. "on %sPort line '%s'",
  6379. portname, escaped(ports->value));
  6380. goto err;
  6381. }
  6382. if (bind_ipv4_only && tor_addr_family(&addr) == AF_INET6) {
  6383. log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv6",
  6384. portname);
  6385. goto err;
  6386. }
  6387. if (bind_ipv6_only && tor_addr_family(&addr) == AF_INET) {
  6388. log_warn(LD_CONFIG, "Could not interpret %sPort address as IPv4",
  6389. portname);
  6390. goto err;
  6391. }
  6392. } else {
  6393. /* This is a client port; parse isolation options */
  6394. SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
  6395. int no = 0, isoflag = 0;
  6396. const char *elt_orig = elt;
  6397. if (!strcasecmpstart(elt, "SessionGroup=")) {
  6398. int group = (int)tor_parse_long(elt+strlen("SessionGroup="),
  6399. 10, 0, INT_MAX, &ok, NULL);
  6400. if (!ok || !allow_no_stream_options) {
  6401. log_warn(LD_CONFIG, "Invalid %sPort option '%s'",
  6402. portname, escaped(elt));
  6403. goto err;
  6404. }
  6405. if (sessiongroup >= 0) {
  6406. log_warn(LD_CONFIG, "Multiple SessionGroup options on %sPort",
  6407. portname);
  6408. goto err;
  6409. }
  6410. sessiongroup = group;
  6411. continue;
  6412. }
  6413. if (!strcasecmpstart(elt, "No")) {
  6414. no = 1;
  6415. elt += 2;
  6416. }
  6417. if (!strcasecmp(elt, "GroupWritable")) {
  6418. group_writable = !no;
  6419. has_used_unix_socket_only_option = 1;
  6420. continue;
  6421. } else if (!strcasecmp(elt, "WorldWritable")) {
  6422. world_writable = !no;
  6423. has_used_unix_socket_only_option = 1;
  6424. continue;
  6425. } else if (!strcasecmp(elt, "RelaxDirModeCheck")) {
  6426. relax_dirmode_check = !no;
  6427. has_used_unix_socket_only_option = 1;
  6428. continue;
  6429. }
  6430. if (allow_no_stream_options) {
  6431. log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
  6432. portname, escaped(elt));
  6433. continue;
  6434. }
  6435. if (takes_hostnames) {
  6436. if (!strcasecmp(elt, "IPv4Traffic")) {
  6437. ipv4_traffic = ! no;
  6438. continue;
  6439. } else if (!strcasecmp(elt, "IPv6Traffic")) {
  6440. ipv6_traffic = ! no;
  6441. continue;
  6442. } else if (!strcasecmp(elt, "PreferIPv6")) {
  6443. prefer_ipv6 = ! no;
  6444. continue;
  6445. } else if (!strcasecmp(elt, "DNSRequest")) {
  6446. dns_request = ! no;
  6447. continue;
  6448. } else if (!strcasecmp(elt, "OnionTraffic")) {
  6449. onion_traffic = ! no;
  6450. continue;
  6451. } else if (!strcasecmp(elt, "OnionTrafficOnly")) {
  6452. /* Only connect to .onion addresses. Equivalent to
  6453. * NoDNSRequest, NoIPv4Traffic, NoIPv6Traffic. The option
  6454. * NoOnionTrafficOnly is not supported, it's too confusing. */
  6455. if (no) {
  6456. log_warn(LD_CONFIG, "Unsupported %sPort option 'No%s'. Use "
  6457. "DNSRequest, IPv4Traffic, and/or IPv6Traffic instead.",
  6458. portname, escaped(elt));
  6459. } else {
  6460. ipv4_traffic = ipv6_traffic = dns_request = 0;
  6461. }
  6462. continue;
  6463. }
  6464. }
  6465. if (!strcasecmp(elt, "CacheIPv4DNS")) {
  6466. warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
  6467. cache_ipv4 = ! no;
  6468. continue;
  6469. } else if (!strcasecmp(elt, "CacheIPv6DNS")) {
  6470. warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
  6471. cache_ipv6 = ! no;
  6472. continue;
  6473. } else if (!strcasecmp(elt, "CacheDNS")) {
  6474. warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
  6475. cache_ipv4 = cache_ipv6 = ! no;
  6476. continue;
  6477. } else if (!strcasecmp(elt, "UseIPv4Cache")) {
  6478. warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
  6479. use_cached_ipv4 = ! no;
  6480. continue;
  6481. } else if (!strcasecmp(elt, "UseIPv6Cache")) {
  6482. warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
  6483. use_cached_ipv6 = ! no;
  6484. continue;
  6485. } else if (!strcasecmp(elt, "UseDNSCache")) {
  6486. warn_client_dns_cache(elt, no); // since 0.2.9.2-alpha
  6487. use_cached_ipv4 = use_cached_ipv6 = ! no;
  6488. continue;
  6489. } else if (!strcasecmp(elt, "PreferIPv6Automap")) {
  6490. prefer_ipv6_automap = ! no;
  6491. continue;
  6492. } else if (!strcasecmp(elt, "PreferSOCKSNoAuth")) {
  6493. prefer_no_auth = ! no;
  6494. continue;
  6495. } else if (!strcasecmp(elt, "KeepAliveIsolateSOCKSAuth")) {
  6496. socks_iso_keep_alive = ! no;
  6497. continue;
  6498. }
  6499. if (!strcasecmpend(elt, "s"))
  6500. elt[strlen(elt)-1] = '\0'; /* kill plurals. */
  6501. if (!strcasecmp(elt, "IsolateDestPort")) {
  6502. isoflag = ISO_DESTPORT;
  6503. } else if (!strcasecmp(elt, "IsolateDestAddr")) {
  6504. isoflag = ISO_DESTADDR;
  6505. } else if (!strcasecmp(elt, "IsolateSOCKSAuth")) {
  6506. isoflag = ISO_SOCKSAUTH;
  6507. } else if (!strcasecmp(elt, "IsolateClientProtocol")) {
  6508. isoflag = ISO_CLIENTPROTO;
  6509. } else if (!strcasecmp(elt, "IsolateClientAddr")) {
  6510. isoflag = ISO_CLIENTADDR;
  6511. } else {
  6512. log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
  6513. portname, escaped(elt_orig));
  6514. }
  6515. if (no) {
  6516. isolation &= ~isoflag;
  6517. } else {
  6518. isolation |= isoflag;
  6519. }
  6520. } SMARTLIST_FOREACH_END(elt);
  6521. }
  6522. if (port)
  6523. got_nonzero_port = 1;
  6524. else
  6525. got_zero_port = 1;
  6526. if (dns_request == 0 && listener_type == CONN_TYPE_AP_DNS_LISTENER) {
  6527. log_warn(LD_CONFIG, "You have a %sPort entry with DNS disabled; that "
  6528. "won't work.", portname);
  6529. goto err;
  6530. }
  6531. if (ipv4_traffic == 0 && ipv6_traffic == 0 && onion_traffic == 0
  6532. && listener_type != CONN_TYPE_AP_DNS_LISTENER) {
  6533. log_warn(LD_CONFIG, "You have a %sPort entry with all of IPv4 and "
  6534. "IPv6 and .onion disabled; that won't work.", portname);
  6535. goto err;
  6536. }
  6537. if (dns_request == 1 && ipv4_traffic == 0 && ipv6_traffic == 0
  6538. && listener_type != CONN_TYPE_AP_DNS_LISTENER) {
  6539. log_warn(LD_CONFIG, "You have a %sPort entry with DNSRequest enabled, "
  6540. "but IPv4 and IPv6 disabled; DNS-based sites won't work.",
  6541. portname);
  6542. goto err;
  6543. }
  6544. if ( has_used_unix_socket_only_option && ! unix_socket_path) {
  6545. log_warn(LD_CONFIG, "You have a %sPort entry with GroupWritable, "
  6546. "WorldWritable, or RelaxDirModeCheck, but it is not a "
  6547. "unix socket.", portname);
  6548. goto err;
  6549. }
  6550. if (!(isolation & ISO_SOCKSAUTH) && socks_iso_keep_alive) {
  6551. log_warn(LD_CONFIG, "You have a %sPort entry with both "
  6552. "NoIsolateSOCKSAuth and KeepAliveIsolateSOCKSAuth set.",
  6553. portname);
  6554. goto err;
  6555. }
  6556. if (unix_socket_path && (isolation & ISO_CLIENTADDR)) {
  6557. /* `IsolateClientAddr` is nonsensical in the context of AF_LOCAL.
  6558. * just silently remove the isolation flag.
  6559. */
  6560. isolation &= ~ISO_CLIENTADDR;
  6561. }
  6562. if (out && port) {
  6563. size_t namelen = unix_socket_path ? strlen(unix_socket_path) : 0;
  6564. port_cfg_t *cfg = port_cfg_new(namelen);
  6565. if (unix_socket_path) {
  6566. tor_addr_make_unspec(&cfg->addr);
  6567. memcpy(cfg->unix_addr, unix_socket_path, namelen + 1);
  6568. cfg->is_unix_addr = 1;
  6569. tor_free(unix_socket_path);
  6570. } else {
  6571. tor_addr_copy(&cfg->addr, &addr);
  6572. cfg->port = port;
  6573. }
  6574. cfg->type = listener_type;
  6575. cfg->is_world_writable = world_writable;
  6576. cfg->is_group_writable = group_writable;
  6577. cfg->relax_dirmode_check = relax_dirmode_check;
  6578. cfg->entry_cfg.isolation_flags = isolation;
  6579. cfg->entry_cfg.session_group = sessiongroup;
  6580. cfg->server_cfg.no_advertise = no_advertise;
  6581. cfg->server_cfg.no_listen = no_listen;
  6582. cfg->server_cfg.all_addrs = all_addrs;
  6583. cfg->server_cfg.bind_ipv4_only = bind_ipv4_only;
  6584. cfg->server_cfg.bind_ipv6_only = bind_ipv6_only;
  6585. cfg->entry_cfg.ipv4_traffic = ipv4_traffic;
  6586. cfg->entry_cfg.ipv6_traffic = ipv6_traffic;
  6587. cfg->entry_cfg.prefer_ipv6 = prefer_ipv6;
  6588. cfg->entry_cfg.dns_request = dns_request;
  6589. cfg->entry_cfg.onion_traffic = onion_traffic;
  6590. cfg->entry_cfg.cache_ipv4_answers = cache_ipv4;
  6591. cfg->entry_cfg.cache_ipv6_answers = cache_ipv6;
  6592. cfg->entry_cfg.use_cached_ipv4_answers = use_cached_ipv4;
  6593. cfg->entry_cfg.use_cached_ipv6_answers = use_cached_ipv6;
  6594. cfg->entry_cfg.prefer_ipv6_virtaddr = prefer_ipv6_automap;
  6595. cfg->entry_cfg.socks_prefer_no_auth = prefer_no_auth;
  6596. if (! (isolation & ISO_SOCKSAUTH))
  6597. cfg->entry_cfg.socks_prefer_no_auth = 1;
  6598. cfg->entry_cfg.socks_iso_keep_alive = socks_iso_keep_alive;
  6599. smartlist_add(out, cfg);
  6600. }
  6601. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  6602. smartlist_clear(elts);
  6603. tor_free(addrport);
  6604. tor_free(unix_socket_path);
  6605. }
  6606. if (warn_nonlocal && out) {
  6607. if (is_control)
  6608. warn_nonlocal_controller_ports(out, forbid_nonlocal);
  6609. else if (is_ext_orport)
  6610. warn_nonlocal_ext_orports(out, portname);
  6611. else
  6612. warn_nonlocal_client_ports(out, portname, listener_type);
  6613. }
  6614. if (got_zero_port && got_nonzero_port) {
  6615. log_warn(LD_CONFIG, "You specified a nonzero %sPort along with '%sPort 0' "
  6616. "in the same configuration. Did you mean to disable %sPort or "
  6617. "not?", portname, portname, portname);
  6618. goto err;
  6619. }
  6620. retval = 0;
  6621. err:
  6622. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  6623. smartlist_free(elts);
  6624. tor_free(unix_socket_path);
  6625. tor_free(addrport);
  6626. return retval;
  6627. }
  6628. /** Return the number of ports which are actually going to listen with type
  6629. * <b>listenertype</b>. Do not count no_listen ports. Only count unix
  6630. * sockets if count_sockets is true. */
  6631. static int
  6632. count_real_listeners(const smartlist_t *ports, int listenertype,
  6633. int count_sockets)
  6634. {
  6635. int n = 0;
  6636. SMARTLIST_FOREACH_BEGIN(ports, port_cfg_t *, port) {
  6637. if (port->server_cfg.no_listen)
  6638. continue;
  6639. if (!count_sockets && port->is_unix_addr)
  6640. continue;
  6641. if (port->type != listenertype)
  6642. continue;
  6643. ++n;
  6644. } SMARTLIST_FOREACH_END(port);
  6645. return n;
  6646. }
  6647. /** Parse all ports from <b>options</b>. On success, set *<b>n_ports_out</b>
  6648. * to the number of ports that are listed, update the *Port_set values in
  6649. * <b>options</b>, and return 0. On failure, set *<b>msg</b> to a
  6650. * description of the problem and return -1.
  6651. *
  6652. * If <b>validate_only</b> is false, set configured_client_ports to the
  6653. * new list of ports parsed from <b>options</b>.
  6654. **/
  6655. static int
  6656. parse_ports(or_options_t *options, int validate_only,
  6657. char **msg, int *n_ports_out,
  6658. int *world_writable_control_socket)
  6659. {
  6660. smartlist_t *ports;
  6661. int retval = -1;
  6662. ports = smartlist_new();
  6663. *n_ports_out = 0;
  6664. const unsigned gw_flag = options->SocksSocketsGroupWritable ?
  6665. CL_PORT_DFLT_GROUP_WRITABLE : 0;
  6666. if (parse_port_config(ports,
  6667. options->SocksPort_lines,
  6668. "Socks", CONN_TYPE_AP_LISTENER,
  6669. "127.0.0.1", 9050,
  6670. ((validate_only ? 0 : CL_PORT_WARN_NONLOCAL)
  6671. | CL_PORT_TAKES_HOSTNAMES | gw_flag)) < 0) {
  6672. *msg = tor_strdup("Invalid SocksPort configuration");
  6673. goto err;
  6674. }
  6675. if (parse_port_config(ports,
  6676. options->DNSPort_lines,
  6677. "DNS", CONN_TYPE_AP_DNS_LISTENER,
  6678. "127.0.0.1", 0,
  6679. CL_PORT_WARN_NONLOCAL|CL_PORT_TAKES_HOSTNAMES) < 0) {
  6680. *msg = tor_strdup("Invalid DNSPort configuration");
  6681. goto err;
  6682. }
  6683. if (parse_port_config(ports,
  6684. options->TransPort_lines,
  6685. "Trans", CONN_TYPE_AP_TRANS_LISTENER,
  6686. "127.0.0.1", 0,
  6687. CL_PORT_WARN_NONLOCAL) < 0) {
  6688. *msg = tor_strdup("Invalid TransPort configuration");
  6689. goto err;
  6690. }
  6691. if (parse_port_config(ports,
  6692. options->NATDPort_lines,
  6693. "NATD", CONN_TYPE_AP_NATD_LISTENER,
  6694. "127.0.0.1", 0,
  6695. CL_PORT_WARN_NONLOCAL) < 0) {
  6696. *msg = tor_strdup("Invalid NatdPort configuration");
  6697. goto err;
  6698. }
  6699. if (parse_port_config(ports,
  6700. options->HTTPTunnelPort_lines,
  6701. "HTTP Tunnel", CONN_TYPE_AP_HTTP_CONNECT_LISTENER,
  6702. "127.0.0.1", 0,
  6703. ((validate_only ? 0 : CL_PORT_WARN_NONLOCAL)
  6704. | CL_PORT_TAKES_HOSTNAMES | gw_flag)) < 0) {
  6705. *msg = tor_strdup("Invalid HTTPTunnelPort configuration");
  6706. goto err;
  6707. }
  6708. {
  6709. unsigned control_port_flags = CL_PORT_NO_STREAM_OPTIONS |
  6710. CL_PORT_WARN_NONLOCAL;
  6711. const int any_passwords = (options->HashedControlPassword ||
  6712. options->HashedControlSessionPassword ||
  6713. options->CookieAuthentication);
  6714. if (! any_passwords)
  6715. control_port_flags |= CL_PORT_FORBID_NONLOCAL;
  6716. if (options->ControlSocketsGroupWritable)
  6717. control_port_flags |= CL_PORT_DFLT_GROUP_WRITABLE;
  6718. if (parse_port_config(ports,
  6719. options->ControlPort_lines,
  6720. "Control", CONN_TYPE_CONTROL_LISTENER,
  6721. "127.0.0.1", 0,
  6722. control_port_flags) < 0) {
  6723. *msg = tor_strdup("Invalid ControlPort configuration");
  6724. goto err;
  6725. }
  6726. if (parse_port_config(ports, options->ControlSocket,
  6727. "ControlSocket",
  6728. CONN_TYPE_CONTROL_LISTENER, NULL, 0,
  6729. control_port_flags | CL_PORT_IS_UNIXSOCKET) < 0) {
  6730. *msg = tor_strdup("Invalid ControlSocket configuration");
  6731. goto err;
  6732. }
  6733. }
  6734. if (! options->ClientOnly) {
  6735. if (parse_port_config(ports,
  6736. options->ORPort_lines,
  6737. "OR", CONN_TYPE_OR_LISTENER,
  6738. "0.0.0.0", 0,
  6739. CL_PORT_SERVER_OPTIONS) < 0) {
  6740. *msg = tor_strdup("Invalid ORPort configuration");
  6741. goto err;
  6742. }
  6743. if (parse_port_config(ports,
  6744. options->ExtORPort_lines,
  6745. "ExtOR", CONN_TYPE_EXT_OR_LISTENER,
  6746. "127.0.0.1", 0,
  6747. CL_PORT_SERVER_OPTIONS|CL_PORT_WARN_NONLOCAL) < 0) {
  6748. *msg = tor_strdup("Invalid ExtORPort configuration");
  6749. goto err;
  6750. }
  6751. if (parse_port_config(ports,
  6752. options->DirPort_lines,
  6753. "Dir", CONN_TYPE_DIR_LISTENER,
  6754. "0.0.0.0", 0,
  6755. CL_PORT_SERVER_OPTIONS) < 0) {
  6756. *msg = tor_strdup("Invalid DirPort configuration");
  6757. goto err;
  6758. }
  6759. }
  6760. int n_low_ports = 0;
  6761. if (check_server_ports(ports, options, &n_low_ports) < 0) {
  6762. *msg = tor_strdup("Misconfigured server ports");
  6763. goto err;
  6764. }
  6765. if (have_low_ports < 0)
  6766. have_low_ports = (n_low_ports > 0);
  6767. *n_ports_out = smartlist_len(ports);
  6768. retval = 0;
  6769. /* Update the *Port_set options. The !! here is to force a boolean out of
  6770. an integer. */
  6771. options->ORPort_set =
  6772. !! count_real_listeners(ports, CONN_TYPE_OR_LISTENER, 0);
  6773. options->SocksPort_set =
  6774. !! count_real_listeners(ports, CONN_TYPE_AP_LISTENER, 1);
  6775. options->TransPort_set =
  6776. !! count_real_listeners(ports, CONN_TYPE_AP_TRANS_LISTENER, 1);
  6777. options->NATDPort_set =
  6778. !! count_real_listeners(ports, CONN_TYPE_AP_NATD_LISTENER, 1);
  6779. options->HTTPTunnelPort_set =
  6780. !! count_real_listeners(ports, CONN_TYPE_AP_HTTP_CONNECT_LISTENER, 1);
  6781. /* Use options->ControlSocket to test if a control socket is set */
  6782. options->ControlPort_set =
  6783. !! count_real_listeners(ports, CONN_TYPE_CONTROL_LISTENER, 0);
  6784. options->DirPort_set =
  6785. !! count_real_listeners(ports, CONN_TYPE_DIR_LISTENER, 0);
  6786. options->DNSPort_set =
  6787. !! count_real_listeners(ports, CONN_TYPE_AP_DNS_LISTENER, 1);
  6788. options->ExtORPort_set =
  6789. !! count_real_listeners(ports, CONN_TYPE_EXT_OR_LISTENER, 0);
  6790. if (world_writable_control_socket) {
  6791. SMARTLIST_FOREACH(ports, port_cfg_t *, p,
  6792. if (p->type == CONN_TYPE_CONTROL_LISTENER &&
  6793. p->is_unix_addr &&
  6794. p->is_world_writable) {
  6795. *world_writable_control_socket = 1;
  6796. break;
  6797. });
  6798. }
  6799. if (!validate_only) {
  6800. if (configured_ports) {
  6801. SMARTLIST_FOREACH(configured_ports,
  6802. port_cfg_t *, p, port_cfg_free(p));
  6803. smartlist_free(configured_ports);
  6804. }
  6805. configured_ports = ports;
  6806. ports = NULL; /* prevent free below. */
  6807. }
  6808. err:
  6809. if (ports) {
  6810. SMARTLIST_FOREACH(ports, port_cfg_t *, p, port_cfg_free(p));
  6811. smartlist_free(ports);
  6812. }
  6813. return retval;
  6814. }
  6815. /* Does port bind to IPv4? */
  6816. static int
  6817. port_binds_ipv4(const port_cfg_t *port)
  6818. {
  6819. return tor_addr_family(&port->addr) == AF_INET ||
  6820. (tor_addr_family(&port->addr) == AF_UNSPEC
  6821. && !port->server_cfg.bind_ipv6_only);
  6822. }
  6823. /* Does port bind to IPv6? */
  6824. static int
  6825. port_binds_ipv6(const port_cfg_t *port)
  6826. {
  6827. return tor_addr_family(&port->addr) == AF_INET6 ||
  6828. (tor_addr_family(&port->addr) == AF_UNSPEC
  6829. && !port->server_cfg.bind_ipv4_only);
  6830. }
  6831. /** Given a list of <b>port_cfg_t</b> in <b>ports</b>, check them for internal
  6832. * consistency and warn as appropriate. Set *<b>n_low_ports_out</b> to the
  6833. * number of sub-1024 ports we will be binding. */
  6834. static int
  6835. check_server_ports(const smartlist_t *ports,
  6836. const or_options_t *options,
  6837. int *n_low_ports_out)
  6838. {
  6839. int n_orport_advertised = 0;
  6840. int n_orport_advertised_ipv4 = 0;
  6841. int n_orport_listeners = 0;
  6842. int n_dirport_advertised = 0;
  6843. int n_dirport_listeners = 0;
  6844. int n_low_port = 0;
  6845. int r = 0;
  6846. SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
  6847. if (port->type == CONN_TYPE_DIR_LISTENER) {
  6848. if (! port->server_cfg.no_advertise)
  6849. ++n_dirport_advertised;
  6850. if (! port->server_cfg.no_listen)
  6851. ++n_dirport_listeners;
  6852. } else if (port->type == CONN_TYPE_OR_LISTENER) {
  6853. if (! port->server_cfg.no_advertise) {
  6854. ++n_orport_advertised;
  6855. if (port_binds_ipv4(port))
  6856. ++n_orport_advertised_ipv4;
  6857. }
  6858. if (! port->server_cfg.no_listen)
  6859. ++n_orport_listeners;
  6860. } else {
  6861. continue;
  6862. }
  6863. #ifndef _WIN32
  6864. if (!port->server_cfg.no_listen && port->port < 1024)
  6865. ++n_low_port;
  6866. #endif
  6867. } SMARTLIST_FOREACH_END(port);
  6868. if (n_orport_advertised && !n_orport_listeners) {
  6869. log_warn(LD_CONFIG, "We are advertising an ORPort, but not actually "
  6870. "listening on one.");
  6871. r = -1;
  6872. }
  6873. if (n_orport_listeners && !n_orport_advertised) {
  6874. log_warn(LD_CONFIG, "We are listening on an ORPort, but not advertising "
  6875. "any ORPorts. This will keep us from building a %s "
  6876. "descriptor, and make us impossible to use.",
  6877. options->BridgeRelay ? "bridge" : "router");
  6878. r = -1;
  6879. }
  6880. if (n_dirport_advertised && !n_dirport_listeners) {
  6881. log_warn(LD_CONFIG, "We are advertising a DirPort, but not actually "
  6882. "listening on one.");
  6883. r = -1;
  6884. }
  6885. if (n_dirport_advertised > 1) {
  6886. log_warn(LD_CONFIG, "Can't advertise more than one DirPort.");
  6887. r = -1;
  6888. }
  6889. if (n_orport_advertised && !n_orport_advertised_ipv4 &&
  6890. !options->BridgeRelay) {
  6891. log_warn(LD_CONFIG, "Configured non-bridge only to listen on an IPv6 "
  6892. "address.");
  6893. r = -1;
  6894. }
  6895. if (n_low_port && options->AccountingMax &&
  6896. (!have_capability_support() || options->KeepBindCapabilities == 0)) {
  6897. const char *extra = "";
  6898. if (options->KeepBindCapabilities == 0 && have_capability_support())
  6899. extra = ", and you have disabled KeepBindCapabilities.";
  6900. log_warn(LD_CONFIG,
  6901. "You have set AccountingMax to use hibernation. You have also "
  6902. "chosen a low DirPort or OrPort%s."
  6903. "This combination can make Tor stop "
  6904. "working when it tries to re-attach the port after a period of "
  6905. "hibernation. Please choose a different port or turn off "
  6906. "hibernation unless you know this combination will work on your "
  6907. "platform.", extra);
  6908. }
  6909. if (n_low_ports_out)
  6910. *n_low_ports_out = n_low_port;
  6911. return r;
  6912. }
  6913. /** Return a list of port_cfg_t for client ports parsed from the
  6914. * options. */
  6915. MOCK_IMPL(const smartlist_t *,
  6916. get_configured_ports,(void))
  6917. {
  6918. if (!configured_ports)
  6919. configured_ports = smartlist_new();
  6920. return configured_ports;
  6921. }
  6922. /** Return an address:port string representation of the address
  6923. * where the first <b>listener_type</b> listener waits for
  6924. * connections. Return NULL if we couldn't find a listener. The
  6925. * string is allocated on the heap and it's the responsibility of the
  6926. * caller to free it after use.
  6927. *
  6928. * This function is meant to be used by the pluggable transport proxy
  6929. * spawning code, please make sure that it fits your purposes before
  6930. * using it. */
  6931. char *
  6932. get_first_listener_addrport_string(int listener_type)
  6933. {
  6934. static const char *ipv4_localhost = "127.0.0.1";
  6935. static const char *ipv6_localhost = "[::1]";
  6936. const char *address;
  6937. uint16_t port;
  6938. char *string = NULL;
  6939. if (!configured_ports)
  6940. return NULL;
  6941. SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
  6942. if (cfg->server_cfg.no_listen)
  6943. continue;
  6944. if (cfg->type == listener_type &&
  6945. tor_addr_family(&cfg->addr) != AF_UNSPEC) {
  6946. /* We found the first listener of the type we are interested in! */
  6947. /* If a listener is listening on INADDR_ANY, assume that it's
  6948. also listening on 127.0.0.1, and point the transport proxy
  6949. there: */
  6950. if (tor_addr_is_null(&cfg->addr))
  6951. address = tor_addr_is_v4(&cfg->addr) ? ipv4_localhost : ipv6_localhost;
  6952. else
  6953. address = fmt_and_decorate_addr(&cfg->addr);
  6954. /* If a listener is configured with port 'auto', we are forced
  6955. to iterate all listener connections and find out in which
  6956. port it ended up listening: */
  6957. if (cfg->port == CFG_AUTO_PORT) {
  6958. port = router_get_active_listener_port_by_type_af(listener_type,
  6959. tor_addr_family(&cfg->addr));
  6960. if (!port)
  6961. return NULL;
  6962. } else {
  6963. port = cfg->port;
  6964. }
  6965. tor_asprintf(&string, "%s:%u", address, port);
  6966. return string;
  6967. }
  6968. } SMARTLIST_FOREACH_END(cfg);
  6969. return NULL;
  6970. }
  6971. /** Return the first advertised port of type <b>listener_type</b> in
  6972. * <b>address_family</b>. Returns 0 when no port is found, and when passed
  6973. * AF_UNSPEC. */
  6974. int
  6975. get_first_advertised_port_by_type_af(int listener_type, int address_family)
  6976. {
  6977. if (address_family == AF_UNSPEC)
  6978. return 0;
  6979. const smartlist_t *conf_ports = get_configured_ports();
  6980. SMARTLIST_FOREACH_BEGIN(conf_ports, const port_cfg_t *, cfg) {
  6981. if (cfg->type == listener_type &&
  6982. !cfg->server_cfg.no_advertise) {
  6983. if ((address_family == AF_INET && port_binds_ipv4(cfg)) ||
  6984. (address_family == AF_INET6 && port_binds_ipv6(cfg))) {
  6985. return cfg->port;
  6986. }
  6987. }
  6988. } SMARTLIST_FOREACH_END(cfg);
  6989. return 0;
  6990. }
  6991. /** Return the first advertised address of type <b>listener_type</b> in
  6992. * <b>address_family</b>. Returns NULL if there is no advertised address,
  6993. * and when passed AF_UNSPEC. */
  6994. const tor_addr_t *
  6995. get_first_advertised_addr_by_type_af(int listener_type, int address_family)
  6996. {
  6997. if (address_family == AF_UNSPEC)
  6998. return NULL;
  6999. if (!configured_ports)
  7000. return NULL;
  7001. SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
  7002. if (cfg->type == listener_type &&
  7003. !cfg->server_cfg.no_advertise) {
  7004. if ((address_family == AF_INET && port_binds_ipv4(cfg)) ||
  7005. (address_family == AF_INET6 && port_binds_ipv6(cfg))) {
  7006. return &cfg->addr;
  7007. }
  7008. }
  7009. } SMARTLIST_FOREACH_END(cfg);
  7010. return NULL;
  7011. }
  7012. /** Return 1 if a port exists of type <b>listener_type</b> on <b>addr</b> and
  7013. * <b>port</b>. If <b>check_wildcard</b> is true, INADDR[6]_ANY and AF_UNSPEC
  7014. * addresses match any address of the appropriate family; and port -1 matches
  7015. * any port.
  7016. * To match auto ports, pass CFG_PORT_AUTO. (Does not match on the actual
  7017. * automatically chosen listener ports.) */
  7018. int
  7019. port_exists_by_type_addr_port(int listener_type, const tor_addr_t *addr,
  7020. int port, int check_wildcard)
  7021. {
  7022. if (!configured_ports || !addr)
  7023. return 0;
  7024. SMARTLIST_FOREACH_BEGIN(configured_ports, const port_cfg_t *, cfg) {
  7025. if (cfg->type == listener_type) {
  7026. if (cfg->port == port || (check_wildcard && port == -1)) {
  7027. /* Exact match */
  7028. if (tor_addr_eq(&cfg->addr, addr)) {
  7029. return 1;
  7030. }
  7031. /* Skip wildcard matches if we're not doing them */
  7032. if (!check_wildcard) {
  7033. continue;
  7034. }
  7035. /* Wildcard matches IPv4 */
  7036. const int cfg_v4 = port_binds_ipv4(cfg);
  7037. const int cfg_any_v4 = tor_addr_is_null(&cfg->addr) && cfg_v4;
  7038. const int addr_v4 = tor_addr_family(addr) == AF_INET ||
  7039. tor_addr_family(addr) == AF_UNSPEC;
  7040. const int addr_any_v4 = tor_addr_is_null(&cfg->addr) && addr_v4;
  7041. if ((cfg_any_v4 && addr_v4) || (cfg_v4 && addr_any_v4)) {
  7042. return 1;
  7043. }
  7044. /* Wildcard matches IPv6 */
  7045. const int cfg_v6 = port_binds_ipv6(cfg);
  7046. const int cfg_any_v6 = tor_addr_is_null(&cfg->addr) && cfg_v6;
  7047. const int addr_v6 = tor_addr_family(addr) == AF_INET6 ||
  7048. tor_addr_family(addr) == AF_UNSPEC;
  7049. const int addr_any_v6 = tor_addr_is_null(&cfg->addr) && addr_v6;
  7050. if ((cfg_any_v6 && addr_v6) || (cfg_v6 && addr_any_v6)) {
  7051. return 1;
  7052. }
  7053. }
  7054. }
  7055. } SMARTLIST_FOREACH_END(cfg);
  7056. return 0;
  7057. }
  7058. /* Like port_exists_by_type_addr_port, but accepts a host-order IPv4 address
  7059. * instead. */
  7060. int
  7061. port_exists_by_type_addr32h_port(int listener_type, uint32_t addr_ipv4h,
  7062. int port, int check_wildcard)
  7063. {
  7064. tor_addr_t ipv4;
  7065. tor_addr_from_ipv4h(&ipv4, addr_ipv4h);
  7066. return port_exists_by_type_addr_port(listener_type, &ipv4, port,
  7067. check_wildcard);
  7068. }
  7069. /** Allocate and return a good value for the DataDirectory based on
  7070. * <b>val</b>, which may be NULL. Return NULL on failure. */
  7071. static char *
  7072. get_data_directory(const char *val)
  7073. {
  7074. #ifdef _WIN32
  7075. if (val) {
  7076. return tor_strdup(val);
  7077. } else {
  7078. return tor_strdup(get_windows_conf_root());
  7079. }
  7080. #else /* !(defined(_WIN32)) */
  7081. const char *d = val;
  7082. if (!d)
  7083. d = "~/.tor";
  7084. if (!strcmpstart(d, "~/")) {
  7085. char *fn = expand_filename(d);
  7086. if (!fn) {
  7087. log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
  7088. return NULL;
  7089. }
  7090. if (!val && !strcmp(fn,"/.tor")) {
  7091. /* If our homedir is /, we probably don't want to use it. */
  7092. /* Default to LOCALSTATEDIR/tor which is probably closer to what we
  7093. * want. */
  7094. log_warn(LD_CONFIG,
  7095. "Default DataDirectory is \"~/.tor\". This expands to "
  7096. "\"%s\", which is probably not what you want. Using "
  7097. "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
  7098. tor_free(fn);
  7099. fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
  7100. }
  7101. return fn;
  7102. }
  7103. return tor_strdup(d);
  7104. #endif /* defined(_WIN32) */
  7105. }
  7106. /** Check and normalize the values of options->{Key,Data,Cache}Directory;
  7107. * return 0 if it is sane, -1 otherwise. */
  7108. static int
  7109. validate_data_directories(or_options_t *options)
  7110. {
  7111. tor_free(options->DataDirectory);
  7112. options->DataDirectory = get_data_directory(options->DataDirectory_option);
  7113. if (!options->DataDirectory)
  7114. return -1;
  7115. if (strlen(options->DataDirectory) > (512-128)) {
  7116. log_warn(LD_CONFIG, "DataDirectory is too long.");
  7117. return -1;
  7118. }
  7119. tor_free(options->KeyDirectory);
  7120. if (options->KeyDirectory_option) {
  7121. options->KeyDirectory = get_data_directory(options->KeyDirectory_option);
  7122. if (!options->KeyDirectory)
  7123. return -1;
  7124. } else {
  7125. /* Default to the data directory's keys subdir */
  7126. tor_asprintf(&options->KeyDirectory, "%s"PATH_SEPARATOR"keys",
  7127. options->DataDirectory);
  7128. }
  7129. tor_free(options->CacheDirectory);
  7130. if (options->CacheDirectory_option) {
  7131. options->CacheDirectory = get_data_directory(
  7132. options->CacheDirectory_option);
  7133. if (!options->CacheDirectory)
  7134. return -1;
  7135. } else {
  7136. /* Default to the data directory. */
  7137. options->CacheDirectory = tor_strdup(options->DataDirectory);
  7138. }
  7139. return 0;
  7140. }
  7141. /** This string must remain the same forevermore. It is how we
  7142. * recognize that the torrc file doesn't need to be backed up. */
  7143. #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
  7144. "if you edit it, comments will not be preserved"
  7145. /** This string can change; it tries to give the reader an idea
  7146. * that editing this file by hand is not a good plan. */
  7147. #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
  7148. "to torrc.orig.1 or similar, and Tor will ignore it"
  7149. /** Save a configuration file for the configuration in <b>options</b>
  7150. * into the file <b>fname</b>. If the file already exists, and
  7151. * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
  7152. * replace it. Return 0 on success, -1 on failure. */
  7153. static int
  7154. write_configuration_file(const char *fname, const or_options_t *options)
  7155. {
  7156. char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
  7157. int rename_old = 0, r;
  7158. if (!fname)
  7159. return -1;
  7160. switch (file_status(fname)) {
  7161. /* create backups of old config files, even if they're empty */
  7162. case FN_FILE:
  7163. case FN_EMPTY:
  7164. old_val = read_file_to_str(fname, 0, NULL);
  7165. if (!old_val || strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
  7166. rename_old = 1;
  7167. }
  7168. tor_free(old_val);
  7169. break;
  7170. case FN_NOENT:
  7171. break;
  7172. case FN_ERROR:
  7173. case FN_DIR:
  7174. default:
  7175. log_warn(LD_CONFIG,
  7176. "Config file \"%s\" is not a file? Failing.", fname);
  7177. return -1;
  7178. }
  7179. if (!(new_conf = options_dump(options, OPTIONS_DUMP_MINIMAL))) {
  7180. log_warn(LD_BUG, "Couldn't get configuration string");
  7181. goto err;
  7182. }
  7183. tor_asprintf(&new_val, "%s\n%s\n\n%s",
  7184. GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
  7185. if (rename_old) {
  7186. int i = 1;
  7187. char *fn_tmp = NULL;
  7188. while (1) {
  7189. tor_asprintf(&fn_tmp, "%s.orig.%d", fname, i);
  7190. if (file_status(fn_tmp) == FN_NOENT)
  7191. break;
  7192. tor_free(fn_tmp);
  7193. ++i;
  7194. }
  7195. log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
  7196. if (tor_rename(fname, fn_tmp) < 0) {//XXXX sandbox doesn't allow
  7197. log_warn(LD_FS,
  7198. "Couldn't rename configuration file \"%s\" to \"%s\": %s",
  7199. fname, fn_tmp, strerror(errno));
  7200. tor_free(fn_tmp);
  7201. goto err;
  7202. }
  7203. tor_free(fn_tmp);
  7204. }
  7205. if (write_str_to_file(fname, new_val, 0) < 0)
  7206. goto err;
  7207. r = 0;
  7208. goto done;
  7209. err:
  7210. r = -1;
  7211. done:
  7212. tor_free(new_val);
  7213. tor_free(new_conf);
  7214. return r;
  7215. }
  7216. /**
  7217. * Save the current configuration file value to disk. Return 0 on
  7218. * success, -1 on failure.
  7219. **/
  7220. int
  7221. options_save_current(void)
  7222. {
  7223. /* This fails if we can't write to our configuration file.
  7224. *
  7225. * If we try falling back to datadirectory or something, we have a better
  7226. * chance of saving the configuration, but a better chance of doing
  7227. * something the user never expected. */
  7228. return write_configuration_file(get_torrc_fname(0), get_options());
  7229. }
  7230. /** Return the number of cpus configured in <b>options</b>. If we are
  7231. * told to auto-detect the number of cpus, return the auto-detected number. */
  7232. int
  7233. get_num_cpus(const or_options_t *options)
  7234. {
  7235. if (options->NumCPUs == 0) {
  7236. int n = compute_num_cpus();
  7237. return (n >= 1) ? n : 1;
  7238. } else {
  7239. return options->NumCPUs;
  7240. }
  7241. }
  7242. /**
  7243. * Initialize the libevent library.
  7244. */
  7245. static void
  7246. init_libevent(const or_options_t *options)
  7247. {
  7248. tor_libevent_cfg cfg;
  7249. tor_assert(options);
  7250. configure_libevent_logging();
  7251. /* If the kernel complains that some method (say, epoll) doesn't
  7252. * exist, we don't care about it, since libevent will cope.
  7253. */
  7254. suppress_libevent_log_msg("Function not implemented");
  7255. memset(&cfg, 0, sizeof(cfg));
  7256. cfg.num_cpus = get_num_cpus(options);
  7257. cfg.msec_per_tick = options->TokenBucketRefillInterval;
  7258. tor_libevent_initialize(&cfg);
  7259. suppress_libevent_log_msg(NULL);
  7260. }
  7261. /** Return a newly allocated string holding a filename relative to the
  7262. * directory in <b>options</b> specified by <b>roottype</b>.
  7263. * If <b>sub1</b> is present, it is the first path component after
  7264. * the data directory. If <b>sub2</b> is also present, it is the second path
  7265. * component after the data directory. If <b>suffix</b> is present, it
  7266. * is appended to the filename.
  7267. *
  7268. * Note: Consider using macros in config.h that wrap this function;
  7269. * you should probably never need to call it as-is.
  7270. */
  7271. MOCK_IMPL(char *,
  7272. options_get_dir_fname2_suffix,(const or_options_t *options,
  7273. directory_root_t roottype,
  7274. const char *sub1, const char *sub2,
  7275. const char *suffix))
  7276. {
  7277. tor_assert(options);
  7278. const char *rootdir = NULL;
  7279. switch (roottype) {
  7280. case DIRROOT_DATADIR:
  7281. rootdir = options->DataDirectory;
  7282. break;
  7283. case DIRROOT_CACHEDIR:
  7284. rootdir = options->CacheDirectory;
  7285. break;
  7286. case DIRROOT_KEYDIR:
  7287. rootdir = options->KeyDirectory;
  7288. break;
  7289. default:
  7290. tor_assert_unreached();
  7291. break;
  7292. }
  7293. tor_assert(rootdir);
  7294. if (!suffix)
  7295. suffix = "";
  7296. char *fname = NULL;
  7297. if (sub1 == NULL) {
  7298. tor_asprintf(&fname, "%s%s", rootdir, suffix);
  7299. tor_assert(!sub2); /* If sub2 is present, sub1 must be present. */
  7300. } else if (sub2 == NULL) {
  7301. tor_asprintf(&fname, "%s"PATH_SEPARATOR"%s%s", rootdir, sub1, suffix);
  7302. } else {
  7303. tor_asprintf(&fname, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s%s",
  7304. rootdir, sub1, sub2, suffix);
  7305. }
  7306. return fname;
  7307. }
  7308. /** Check wether the data directory has a private subdirectory
  7309. * <b>subdir</b>. If not, try to create it. Return 0 on success,
  7310. * -1 otherwise. */
  7311. int
  7312. check_or_create_data_subdir(const char *subdir)
  7313. {
  7314. char *statsdir = get_datadir_fname(subdir);
  7315. int return_val = 0;
  7316. if (check_private_dir(statsdir, CPD_CREATE, get_options()->User) < 0) {
  7317. log_warn(LD_HIST, "Unable to create %s/ directory!", subdir);
  7318. return_val = -1;
  7319. }
  7320. tor_free(statsdir);
  7321. return return_val;
  7322. }
  7323. /** Create a file named <b>fname</b> with contents <b>str</b> in the
  7324. * subdirectory <b>subdir</b> of the data directory. <b>descr</b>
  7325. * should be a short description of the file's content and will be
  7326. * used for the warning message, if it's present and the write process
  7327. * fails. Return 0 on success, -1 otherwise.*/
  7328. int
  7329. write_to_data_subdir(const char* subdir, const char* fname,
  7330. const char* str, const char* descr)
  7331. {
  7332. char *filename = get_datadir_fname2(subdir, fname);
  7333. int return_val = 0;
  7334. if (write_str_to_file(filename, str, 0) < 0) {
  7335. log_warn(LD_HIST, "Unable to write %s to disk!", descr ? descr : fname);
  7336. return_val = -1;
  7337. }
  7338. tor_free(filename);
  7339. return return_val;
  7340. }
  7341. /** Return a smartlist of ports that must be forwarded by
  7342. * tor-fw-helper. The smartlist contains the ports in a string format
  7343. * that is understandable by tor-fw-helper. */
  7344. smartlist_t *
  7345. get_list_of_ports_to_forward(void)
  7346. {
  7347. smartlist_t *ports_to_forward = smartlist_new();
  7348. int port = 0;
  7349. /** XXX TODO tor-fw-helper does not support forwarding ports to
  7350. other hosts than the local one. If the user is binding to a
  7351. different IP address, tor-fw-helper won't work. */
  7352. port = router_get_advertised_or_port(get_options()); /* Get ORPort */
  7353. if (port)
  7354. smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
  7355. port = router_get_advertised_dir_port(get_options(), 0); /* Get DirPort */
  7356. if (port)
  7357. smartlist_add_asprintf(ports_to_forward, "%d:%d", port, port);
  7358. /* Get ports of transport proxies */
  7359. {
  7360. smartlist_t *transport_ports = get_transport_proxy_ports();
  7361. if (transport_ports) {
  7362. smartlist_add_all(ports_to_forward, transport_ports);
  7363. smartlist_free(transport_ports);
  7364. }
  7365. }
  7366. if (!smartlist_len(ports_to_forward)) {
  7367. smartlist_free(ports_to_forward);
  7368. ports_to_forward = NULL;
  7369. }
  7370. return ports_to_forward;
  7371. }
  7372. /** Helper to implement GETINFO functions about configuration variables (not
  7373. * their values). Given a "config/names" question, set *<b>answer</b> to a
  7374. * new string describing the supported configuration variables and their
  7375. * types. */
  7376. int
  7377. getinfo_helper_config(control_connection_t *conn,
  7378. const char *question, char **answer,
  7379. const char **errmsg)
  7380. {
  7381. (void) conn;
  7382. (void) errmsg;
  7383. if (!strcmp(question, "config/names")) {
  7384. smartlist_t *sl = smartlist_new();
  7385. int i;
  7386. for (i = 0; option_vars_[i].name; ++i) {
  7387. const config_var_t *var = &option_vars_[i];
  7388. const char *type;
  7389. /* don't tell controller about triple-underscore options */
  7390. if (!strncmp(option_vars_[i].name, "___", 3))
  7391. continue;
  7392. switch (var->type) {
  7393. case CONFIG_TYPE_STRING: type = "String"; break;
  7394. case CONFIG_TYPE_FILENAME: type = "Filename"; break;
  7395. case CONFIG_TYPE_UINT: type = "Integer"; break;
  7396. case CONFIG_TYPE_INT: type = "SignedInteger"; break;
  7397. case CONFIG_TYPE_PORT: type = "Port"; break;
  7398. case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
  7399. case CONFIG_TYPE_MSEC_INTERVAL: type = "TimeMsecInterval"; break;
  7400. case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
  7401. case CONFIG_TYPE_DOUBLE: type = "Float"; break;
  7402. case CONFIG_TYPE_BOOL: type = "Boolean"; break;
  7403. case CONFIG_TYPE_AUTOBOOL: type = "Boolean+Auto"; break;
  7404. case CONFIG_TYPE_ISOTIME: type = "Time"; break;
  7405. case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
  7406. case CONFIG_TYPE_CSV: type = "CommaList"; break;
  7407. case CONFIG_TYPE_CSV_INTERVAL: type = "TimeIntervalCommaList"; break;
  7408. case CONFIG_TYPE_LINELIST: type = "LineList"; break;
  7409. case CONFIG_TYPE_LINELIST_S: type = "Dependent"; break;
  7410. case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
  7411. default:
  7412. case CONFIG_TYPE_OBSOLETE:
  7413. type = NULL; break;
  7414. }
  7415. if (!type)
  7416. continue;
  7417. smartlist_add_asprintf(sl, "%s %s\n",var->name,type);
  7418. }
  7419. *answer = smartlist_join_strings(sl, "", 0, NULL);
  7420. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  7421. smartlist_free(sl);
  7422. } else if (!strcmp(question, "config/defaults")) {
  7423. smartlist_t *sl = smartlist_new();
  7424. int dirauth_lines_seen = 0, fallback_lines_seen = 0;
  7425. for (int i = 0; option_vars_[i].name; ++i) {
  7426. const config_var_t *var = &option_vars_[i];
  7427. if (var->initvalue != NULL) {
  7428. if (strcmp(option_vars_[i].name, "DirAuthority") == 0) {
  7429. /*
  7430. * Count dirauth lines we have a default for; we'll use the
  7431. * count later to decide whether to add the defaults manually
  7432. */
  7433. ++dirauth_lines_seen;
  7434. }
  7435. if (strcmp(option_vars_[i].name, "FallbackDir") == 0) {
  7436. /*
  7437. * Similarly count fallback lines, so that we can decided later
  7438. * to add the defaults manually.
  7439. */
  7440. ++fallback_lines_seen;
  7441. }
  7442. char *val = esc_for_log(var->initvalue);
  7443. smartlist_add_asprintf(sl, "%s %s\n",var->name,val);
  7444. tor_free(val);
  7445. }
  7446. }
  7447. if (dirauth_lines_seen == 0) {
  7448. /*
  7449. * We didn't see any directory authorities with default values,
  7450. * so add the list of default authorities manually.
  7451. */
  7452. /*
  7453. * default_authorities is defined earlier in this file and
  7454. * is a const char ** NULL-terminated array of dirauth config
  7455. * lines.
  7456. */
  7457. for (const char **i = default_authorities; *i != NULL; ++i) {
  7458. char *val = esc_for_log(*i);
  7459. smartlist_add_asprintf(sl, "DirAuthority %s\n", val);
  7460. tor_free(val);
  7461. }
  7462. }
  7463. if (fallback_lines_seen == 0 &&
  7464. get_options()->UseDefaultFallbackDirs == 1) {
  7465. /*
  7466. * We didn't see any explicitly configured fallback mirrors,
  7467. * so add the defaults to the list manually.
  7468. *
  7469. * default_fallbacks is included earlier in this file and
  7470. * is a const char ** NULL-terminated array of fallback config lines.
  7471. */
  7472. const char **i;
  7473. for (i = default_fallbacks; *i != NULL; ++i) {
  7474. char *val = esc_for_log(*i);
  7475. smartlist_add_asprintf(sl, "FallbackDir %s\n", val);
  7476. tor_free(val);
  7477. }
  7478. }
  7479. *answer = smartlist_join_strings(sl, "", 0, NULL);
  7480. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  7481. smartlist_free(sl);
  7482. }
  7483. return 0;
  7484. }
  7485. /* Check whether an address has already been set against the options
  7486. * depending on address family and destination type. Any exsting
  7487. * value will lead to a fail, even if it is the same value. If not
  7488. * set and not only validating, copy it into this location too.
  7489. * Returns 0 on success or -1 if this address is already set.
  7490. */
  7491. static int
  7492. verify_and_store_outbound_address(sa_family_t family, tor_addr_t *addr,
  7493. outbound_addr_t type, or_options_t *options, int validate_only)
  7494. {
  7495. if (type>=OUTBOUND_ADDR_MAX || (family!=AF_INET && family!=AF_INET6)) {
  7496. return -1;
  7497. }
  7498. int fam_index=0;
  7499. if (family==AF_INET6) {
  7500. fam_index=1;
  7501. }
  7502. tor_addr_t *dest=&options->OutboundBindAddresses[type][fam_index];
  7503. if (!tor_addr_is_null(dest)) {
  7504. return -1;
  7505. }
  7506. if (!validate_only) {
  7507. tor_addr_copy(dest, addr);
  7508. }
  7509. return 0;
  7510. }
  7511. /* Parse a list of address lines for a specific destination type.
  7512. * Will store them into the options if not validate_only. If a
  7513. * problem occurs, a suitable error message is store in msg.
  7514. * Returns 0 on success or -1 if any address is already set.
  7515. */
  7516. static int
  7517. parse_outbound_address_lines(const config_line_t *lines, outbound_addr_t type,
  7518. or_options_t *options, int validate_only, char **msg)
  7519. {
  7520. tor_addr_t addr;
  7521. sa_family_t family;
  7522. while (lines) {
  7523. family = tor_addr_parse(&addr, lines->value);
  7524. if (verify_and_store_outbound_address(family, &addr, type,
  7525. options, validate_only)) {
  7526. if (msg)
  7527. tor_asprintf(msg, "Multiple%s%s outbound bind addresses "
  7528. "configured: %s",
  7529. family==AF_INET?" IPv4":(family==AF_INET6?" IPv6":""),
  7530. type==OUTBOUND_ADDR_OR?" OR":
  7531. (type==OUTBOUND_ADDR_EXIT?" exit":""), lines->value);
  7532. return -1;
  7533. }
  7534. lines = lines->next;
  7535. }
  7536. return 0;
  7537. }
  7538. /** Parse outbound bind address option lines. If <b>validate_only</b>
  7539. * is not 0 update OutboundBindAddresses in <b>options</b>.
  7540. * Only one address can be set for any of these values.
  7541. * On failure, set <b>msg</b> (if provided) to a newly allocated string
  7542. * containing a description of the problem and return -1.
  7543. */
  7544. static int
  7545. parse_outbound_addresses(or_options_t *options, int validate_only, char **msg)
  7546. {
  7547. if (!validate_only) {
  7548. memset(&options->OutboundBindAddresses, 0,
  7549. sizeof(options->OutboundBindAddresses));
  7550. }
  7551. if (parse_outbound_address_lines(options->OutboundBindAddress,
  7552. OUTBOUND_ADDR_EXIT_AND_OR, options,
  7553. validate_only, msg) < 0) {
  7554. goto err;
  7555. }
  7556. if (parse_outbound_address_lines(options->OutboundBindAddressOR,
  7557. OUTBOUND_ADDR_OR, options, validate_only,
  7558. msg) < 0) {
  7559. goto err;
  7560. }
  7561. if (parse_outbound_address_lines(options->OutboundBindAddressExit,
  7562. OUTBOUND_ADDR_EXIT, options, validate_only,
  7563. msg) < 0) {
  7564. goto err;
  7565. }
  7566. return 0;
  7567. err:
  7568. return -1;
  7569. }
  7570. /** Load one of the geoip files, <a>family</a> determining which
  7571. * one. <a>default_fname</a> is used if on Windows and
  7572. * <a>fname</a> equals "<default>". */
  7573. static void
  7574. config_load_geoip_file_(sa_family_t family,
  7575. const char *fname,
  7576. const char *default_fname)
  7577. {
  7578. #ifdef _WIN32
  7579. char *free_fname = NULL; /* Used to hold any temporary-allocated value */
  7580. /* XXXX Don't use this "<default>" junk; make our filename options
  7581. * understand prefixes somehow. -NM */
  7582. if (!strcmp(fname, "<default>")) {
  7583. const char *conf_root = get_windows_conf_root();
  7584. tor_asprintf(&free_fname, "%s\\%s", conf_root, default_fname);
  7585. fname = free_fname;
  7586. }
  7587. geoip_load_file(family, fname);
  7588. tor_free(free_fname);
  7589. #else /* !(defined(_WIN32)) */
  7590. (void)default_fname;
  7591. geoip_load_file(family, fname);
  7592. #endif /* defined(_WIN32) */
  7593. }
  7594. /** Load geoip files for IPv4 and IPv6 if <a>options</a> and
  7595. * <a>old_options</a> indicate we should. */
  7596. static void
  7597. config_maybe_load_geoip_files_(const or_options_t *options,
  7598. const or_options_t *old_options)
  7599. {
  7600. /* XXXX Reload GeoIPFile on SIGHUP. -NM */
  7601. if (options->GeoIPFile &&
  7602. ((!old_options || !opt_streq(old_options->GeoIPFile,
  7603. options->GeoIPFile))
  7604. || !geoip_is_loaded(AF_INET)))
  7605. config_load_geoip_file_(AF_INET, options->GeoIPFile, "geoip");
  7606. if (options->GeoIPv6File &&
  7607. ((!old_options || !opt_streq(old_options->GeoIPv6File,
  7608. options->GeoIPv6File))
  7609. || !geoip_is_loaded(AF_INET6)))
  7610. config_load_geoip_file_(AF_INET6, options->GeoIPv6File, "geoip6");
  7611. }
  7612. /** Initialize cookie authentication (used so far by the ControlPort
  7613. * and Extended ORPort).
  7614. *
  7615. * Allocate memory and create a cookie (of length <b>cookie_len</b>)
  7616. * in <b>cookie_out</b>.
  7617. * Then write it down to <b>fname</b> and prepend it with <b>header</b>.
  7618. *
  7619. * If <b>group_readable</b> is set, set <b>fname</b> to be readable
  7620. * by the default GID.
  7621. *
  7622. * If the whole procedure was successful, set
  7623. * <b>cookie_is_set_out</b> to True. */
  7624. int
  7625. init_cookie_authentication(const char *fname, const char *header,
  7626. int cookie_len, int group_readable,
  7627. uint8_t **cookie_out, int *cookie_is_set_out)
  7628. {
  7629. char cookie_file_str_len = strlen(header) + cookie_len;
  7630. char *cookie_file_str = tor_malloc(cookie_file_str_len);
  7631. int retval = -1;
  7632. /* We don't want to generate a new cookie every time we call
  7633. * options_act(). One should be enough. */
  7634. if (*cookie_is_set_out) {
  7635. retval = 0; /* we are all set */
  7636. goto done;
  7637. }
  7638. /* If we've already set the cookie, free it before re-setting
  7639. it. This can happen if we previously generated a cookie, but
  7640. couldn't write it to a disk. */
  7641. if (*cookie_out)
  7642. tor_free(*cookie_out);
  7643. /* Generate the cookie */
  7644. *cookie_out = tor_malloc(cookie_len);
  7645. crypto_rand((char *)*cookie_out, cookie_len);
  7646. /* Create the string that should be written on the file. */
  7647. memcpy(cookie_file_str, header, strlen(header));
  7648. memcpy(cookie_file_str+strlen(header), *cookie_out, cookie_len);
  7649. if (write_bytes_to_file(fname, cookie_file_str, cookie_file_str_len, 1)) {
  7650. log_warn(LD_FS,"Error writing auth cookie to %s.", escaped(fname));
  7651. goto done;
  7652. }
  7653. #ifndef _WIN32
  7654. if (group_readable) {
  7655. if (chmod(fname, 0640)) {
  7656. log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
  7657. }
  7658. }
  7659. #else /* !(!defined(_WIN32)) */
  7660. (void) group_readable;
  7661. #endif /* !defined(_WIN32) */
  7662. /* Success! */
  7663. log_info(LD_GENERAL, "Generated auth cookie file in '%s'.", escaped(fname));
  7664. *cookie_is_set_out = 1;
  7665. retval = 0;
  7666. done:
  7667. memwipe(cookie_file_str, 0, cookie_file_str_len);
  7668. tor_free(cookie_file_str);
  7669. return retval;
  7670. }