config.c 289 KB

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