config.c 286 KB

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