config.c 288 KB

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