config.c 290 KB

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