config.c 215 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465
  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-2011, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file config.c
  8. * \brief Code to parse and interpret configuration files.
  9. **/
  10. #define CONFIG_PRIVATE
  11. #include "or.h"
  12. #include "circuitbuild.h"
  13. #include "circuitlist.h"
  14. #include "config.h"
  15. #include "connection.h"
  16. #include "connection_edge.h"
  17. #include "connection_or.h"
  18. #include "control.h"
  19. #include "cpuworker.h"
  20. #include "dirserv.h"
  21. #include "dirvote.h"
  22. #include "dns.h"
  23. #include "geoip.h"
  24. #include "hibernate.h"
  25. #include "main.h"
  26. #include "networkstatus.h"
  27. #include "policies.h"
  28. #include "relay.h"
  29. #include "rendclient.h"
  30. #include "rendservice.h"
  31. #include "rephist.h"
  32. #include "router.h"
  33. #include "util.h"
  34. #include "routerlist.h"
  35. #include "transports.h"
  36. #ifdef MS_WINDOWS
  37. #include <shlobj.h>
  38. #endif
  39. #include "procmon.h"
  40. /* From main.c */
  41. extern int quiet_level;
  42. /** Enumeration of types which option values can take */
  43. typedef enum config_type_t {
  44. CONFIG_TYPE_STRING = 0, /**< An arbitrary string. */
  45. CONFIG_TYPE_FILENAME, /**< A filename: some prefixes get expanded. */
  46. CONFIG_TYPE_UINT, /**< A non-negative integer less than MAX_INT */
  47. CONFIG_TYPE_PORT, /**< A port from 1...65535, 0 for "not set", or
  48. * "auto". */
  49. CONFIG_TYPE_INTERVAL, /**< A number of seconds, with optional units*/
  50. CONFIG_TYPE_MSEC_INTERVAL,/**< A number of milliseconds, with optional
  51. * units */
  52. CONFIG_TYPE_MEMUNIT, /**< A number of bytes, with optional units*/
  53. CONFIG_TYPE_DOUBLE, /**< A floating-point value */
  54. CONFIG_TYPE_BOOL, /**< A boolean value, expressed as 0 or 1. */
  55. CONFIG_TYPE_AUTOBOOL, /**< A boolean+auto value, expressed 0 for false,
  56. * 1 for true, and -1 for auto */
  57. CONFIG_TYPE_ISOTIME, /**< An ISO-formatted time relative to GMT. */
  58. CONFIG_TYPE_CSV, /**< A list of strings, separated by commas and
  59. * optional whitespace. */
  60. CONFIG_TYPE_LINELIST, /**< Uninterpreted config lines */
  61. CONFIG_TYPE_LINELIST_S, /**< Uninterpreted, context-sensitive config lines,
  62. * mixed with other keywords. */
  63. CONFIG_TYPE_LINELIST_V, /**< Catch-all "virtual" option to summarize
  64. * context-sensitive config lines when fetching.
  65. */
  66. CONFIG_TYPE_ROUTERSET, /**< A list of router names, addrs, and fps,
  67. * parsed into a routerset_t. */
  68. CONFIG_TYPE_OBSOLETE, /**< Obsolete (ignored) option. */
  69. } config_type_t;
  70. /** An abbreviation for a configuration option allowed on the command line. */
  71. typedef struct config_abbrev_t {
  72. const char *abbreviated;
  73. const char *full;
  74. int commandline_only;
  75. int warn;
  76. } config_abbrev_t;
  77. /* Handy macro for declaring "In the config file or on the command line,
  78. * you can abbreviate <b>tok</b>s as <b>tok</b>". */
  79. #define PLURAL(tok) { #tok, #tok "s", 0, 0 }
  80. /** A list of abbreviations and aliases to map command-line options, obsolete
  81. * option names, or alternative option names, to their current values. */
  82. static config_abbrev_t _option_abbrevs[] = {
  83. PLURAL(ExitNode),
  84. PLURAL(EntryNode),
  85. PLURAL(ExcludeNode),
  86. PLURAL(FirewallPort),
  87. PLURAL(LongLivedPort),
  88. PLURAL(HiddenServiceNode),
  89. PLURAL(HiddenServiceExcludeNode),
  90. PLURAL(NumCPU),
  91. PLURAL(RendNode),
  92. PLURAL(RendExcludeNode),
  93. PLURAL(StrictEntryNode),
  94. PLURAL(StrictExitNode),
  95. PLURAL(StrictNode),
  96. { "l", "Log", 1, 0},
  97. { "AllowUnverifiedNodes", "AllowInvalidNodes", 0, 0},
  98. { "AutomapHostSuffixes", "AutomapHostsSuffixes", 0, 0},
  99. { "AutomapHostOnResolve", "AutomapHostsOnResolve", 0, 0},
  100. { "BandwidthRateBytes", "BandwidthRate", 0, 0},
  101. { "BandwidthBurstBytes", "BandwidthBurst", 0, 0},
  102. { "DirFetchPostPeriod", "StatusFetchPeriod", 0, 0},
  103. { "MaxConn", "ConnLimit", 0, 1},
  104. { "ORBindAddress", "ORListenAddress", 0, 0},
  105. { "DirBindAddress", "DirListenAddress", 0, 0},
  106. { "SocksBindAddress", "SocksListenAddress", 0, 0},
  107. { "UseHelperNodes", "UseEntryGuards", 0, 0},
  108. { "NumHelperNodes", "NumEntryGuards", 0, 0},
  109. { "UseEntryNodes", "UseEntryGuards", 0, 0},
  110. { "NumEntryNodes", "NumEntryGuards", 0, 0},
  111. { "ResolvConf", "ServerDNSResolvConfFile", 0, 1},
  112. { "SearchDomains", "ServerDNSSearchDomains", 0, 1},
  113. { "ServerDNSAllowBrokenResolvConf", "ServerDNSAllowBrokenConfig", 0, 0},
  114. { "PreferTunnelledDirConns", "PreferTunneledDirConns", 0, 0},
  115. { "BridgeAuthoritativeDirectory", "BridgeAuthoritativeDir", 0, 0},
  116. { "HashedControlPassword", "__HashedControlSessionPassword", 1, 0},
  117. { "StrictEntryNodes", "StrictNodes", 0, 1},
  118. { "StrictExitNodes", "StrictNodes", 0, 1},
  119. { NULL, NULL, 0, 0},
  120. };
  121. /** A list of state-file "abbreviations," for compatibility. */
  122. static config_abbrev_t _state_abbrevs[] = {
  123. { "AccountingBytesReadInterval", "AccountingBytesReadInInterval", 0, 0 },
  124. { "HelperNode", "EntryGuard", 0, 0 },
  125. { "HelperNodeDownSince", "EntryGuardDownSince", 0, 0 },
  126. { "HelperNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
  127. { "EntryNode", "EntryGuard", 0, 0 },
  128. { "EntryNodeDownSince", "EntryGuardDownSince", 0, 0 },
  129. { "EntryNodeUnlistedSince", "EntryGuardUnlistedSince", 0, 0 },
  130. { NULL, NULL, 0, 0},
  131. };
  132. #undef PLURAL
  133. /** A variable allowed in the configuration file or on the command line. */
  134. typedef struct config_var_t {
  135. const char *name; /**< The full keyword (case insensitive). */
  136. config_type_t type; /**< How to interpret the type and turn it into a
  137. * value. */
  138. off_t var_offset; /**< Offset of the corresponding member of or_options_t. */
  139. const char *initvalue; /**< String (or null) describing initial value. */
  140. } config_var_t;
  141. /** An entry for config_vars: "The option <b>name</b> has type
  142. * CONFIG_TYPE_<b>conftype</b>, and corresponds to
  143. * or_options_t.<b>member</b>"
  144. */
  145. #define VAR(name,conftype,member,initvalue) \
  146. { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_options_t, member), \
  147. initvalue }
  148. /** As VAR, but the option name and member name are the same. */
  149. #define V(member,conftype,initvalue) \
  150. VAR(#member, conftype, member, initvalue)
  151. /** An entry for config_vars: "The option <b>name</b> is obsolete." */
  152. #define OBSOLETE(name) { name, CONFIG_TYPE_OBSOLETE, 0, NULL }
  153. /** Array of configuration options. Until we disallow nonstandard
  154. * abbreviations, order is significant, since the first matching option will
  155. * be chosen first.
  156. */
  157. static config_var_t _option_vars[] = {
  158. OBSOLETE("AccountingMaxKB"),
  159. V(AccountingMax, MEMUNIT, "0 bytes"),
  160. V(AccountingStart, STRING, NULL),
  161. V(Address, STRING, NULL),
  162. V(AllowDotExit, BOOL, "0"),
  163. V(AllowInvalidNodes, CSV, "middle,rendezvous"),
  164. V(AllowNonRFC953Hostnames, BOOL, "0"),
  165. V(AllowSingleHopCircuits, BOOL, "0"),
  166. V(AllowSingleHopExits, BOOL, "0"),
  167. V(AlternateBridgeAuthority, LINELIST, NULL),
  168. V(AlternateDirAuthority, LINELIST, NULL),
  169. V(AlternateHSAuthority, LINELIST, NULL),
  170. V(AssumeReachable, BOOL, "0"),
  171. V(AuthDirBadDir, LINELIST, NULL),
  172. V(AuthDirBadExit, LINELIST, NULL),
  173. V(AuthDirInvalid, LINELIST, NULL),
  174. V(AuthDirReject, LINELIST, NULL),
  175. V(AuthDirRejectUnlisted, BOOL, "0"),
  176. V(AuthDirListBadDirs, BOOL, "0"),
  177. V(AuthDirListBadExits, BOOL, "0"),
  178. V(AuthDirMaxServersPerAddr, UINT, "2"),
  179. V(AuthDirMaxServersPerAuthAddr,UINT, "5"),
  180. VAR("AuthoritativeDirectory", BOOL, AuthoritativeDir, "0"),
  181. V(AutomapHostsOnResolve, BOOL, "0"),
  182. V(AutomapHostsSuffixes, CSV, ".onion,.exit"),
  183. V(AvoidDiskWrites, BOOL, "0"),
  184. V(BandwidthBurst, MEMUNIT, "10 MB"),
  185. V(BandwidthRate, MEMUNIT, "5 MB"),
  186. V(BridgeAuthoritativeDir, BOOL, "0"),
  187. VAR("Bridge", LINELIST, Bridges, NULL),
  188. V(BridgePassword, STRING, NULL),
  189. V(BridgeRecordUsageByCountry, BOOL, "1"),
  190. V(BridgeRelay, BOOL, "0"),
  191. V(CellStatistics, BOOL, "0"),
  192. V(LearnCircuitBuildTimeout, BOOL, "1"),
  193. V(CircuitBuildTimeout, INTERVAL, "0"),
  194. V(CircuitIdleTimeout, INTERVAL, "1 hour"),
  195. V(CircuitStreamTimeout, INTERVAL, "0"),
  196. V(CircuitPriorityHalflife, DOUBLE, "-100.0"), /*negative:'Use default'*/
  197. V(ClientDNSRejectInternalAddresses, BOOL,"1"),
  198. V(ClientOnly, BOOL, "0"),
  199. V(ClientRejectInternalAddresses, BOOL, "1"),
  200. V(ClientTransportPlugin, LINELIST, NULL),
  201. V(ConsensusParams, STRING, NULL),
  202. V(ConnLimit, UINT, "1000"),
  203. V(ConnDirectionStatistics, BOOL, "0"),
  204. V(ConstrainedSockets, BOOL, "0"),
  205. V(ConstrainedSockSize, MEMUNIT, "8192"),
  206. V(ContactInfo, STRING, NULL),
  207. V(ControlListenAddress, LINELIST, NULL),
  208. V(ControlPort, PORT, "0"),
  209. V(ControlPortFileGroupReadable,BOOL, "0"),
  210. V(ControlPortWriteToFile, FILENAME, NULL),
  211. V(ControlSocket, LINELIST, NULL),
  212. V(ControlSocketsGroupWritable, BOOL, "0"),
  213. V(CookieAuthentication, BOOL, "0"),
  214. V(CookieAuthFileGroupReadable, BOOL, "0"),
  215. V(CookieAuthFile, STRING, NULL),
  216. V(CountPrivateBandwidth, BOOL, "0"),
  217. V(DataDirectory, FILENAME, NULL),
  218. OBSOLETE("DebugLogFile"),
  219. V(DirAllowPrivateAddresses, BOOL, NULL),
  220. V(TestingAuthDirTimeToLearnReachability, INTERVAL, "30 minutes"),
  221. V(DirListenAddress, LINELIST, NULL),
  222. OBSOLETE("DirFetchPeriod"),
  223. V(DirPolicy, LINELIST, NULL),
  224. V(DirPort, PORT, "0"),
  225. V(DirPortFrontPage, FILENAME, NULL),
  226. OBSOLETE("DirPostPeriod"),
  227. OBSOLETE("DirRecordUsageByCountry"),
  228. OBSOLETE("DirRecordUsageGranularity"),
  229. OBSOLETE("DirRecordUsageRetainIPs"),
  230. OBSOLETE("DirRecordUsageSaveInterval"),
  231. V(DirReqStatistics, BOOL, "1"),
  232. VAR("DirServer", LINELIST, DirServers, NULL),
  233. V(DisableAllSwap, BOOL, "0"),
  234. V(DisableIOCP, BOOL, "1"),
  235. V(DNSPort, LINELIST, NULL),
  236. V(DNSListenAddress, LINELIST, NULL),
  237. V(DownloadExtraInfo, BOOL, "0"),
  238. V(EnforceDistinctSubnets, BOOL, "1"),
  239. V(EntryNodes, ROUTERSET, NULL),
  240. V(EntryStatistics, BOOL, "0"),
  241. V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "10 minutes"),
  242. V(ExcludeNodes, ROUTERSET, NULL),
  243. V(ExcludeExitNodes, ROUTERSET, NULL),
  244. V(ExcludeSingleHopRelays, BOOL, "1"),
  245. V(ExitNodes, ROUTERSET, NULL),
  246. V(ExitPolicy, LINELIST, NULL),
  247. V(ExitPolicyRejectPrivate, BOOL, "1"),
  248. V(ExitPortStatistics, BOOL, "0"),
  249. V(ExtraInfoStatistics, BOOL, "1"),
  250. #if defined (WINCE)
  251. V(FallbackNetworkstatusFile, FILENAME, "fallback-consensus"),
  252. #else
  253. V(FallbackNetworkstatusFile, FILENAME,
  254. SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "fallback-consensus"),
  255. #endif
  256. V(FascistFirewall, BOOL, "0"),
  257. V(FirewallPorts, CSV, ""),
  258. V(FastFirstHopPK, BOOL, "1"),
  259. V(FetchDirInfoEarly, BOOL, "0"),
  260. V(FetchDirInfoExtraEarly, BOOL, "0"),
  261. V(FetchServerDescriptors, BOOL, "1"),
  262. V(FetchHidServDescriptors, BOOL, "1"),
  263. V(FetchUselessDescriptors, BOOL, "0"),
  264. V(FetchV2Networkstatus, BOOL, "0"),
  265. #ifdef WIN32
  266. V(GeoIPFile, FILENAME, "<default>"),
  267. #else
  268. V(GeoIPFile, FILENAME,
  269. SHARE_DATADIR PATH_SEPARATOR "tor" PATH_SEPARATOR "geoip"),
  270. #endif
  271. OBSOLETE("Group"),
  272. V(HardwareAccel, BOOL, "0"),
  273. V(HeartbeatPeriod, INTERVAL, "6 hours"),
  274. V(AccelName, STRING, NULL),
  275. V(AccelDir, FILENAME, NULL),
  276. V(HashedControlPassword, LINELIST, NULL),
  277. V(HidServDirectoryV2, BOOL, "1"),
  278. VAR("HiddenServiceDir", LINELIST_S, RendConfigLines, NULL),
  279. OBSOLETE("HiddenServiceExcludeNodes"),
  280. OBSOLETE("HiddenServiceNodes"),
  281. VAR("HiddenServiceOptions",LINELIST_V, RendConfigLines, NULL),
  282. VAR("HiddenServicePort", LINELIST_S, RendConfigLines, NULL),
  283. VAR("HiddenServiceVersion",LINELIST_S, RendConfigLines, NULL),
  284. VAR("HiddenServiceAuthorizeClient",LINELIST_S,RendConfigLines, NULL),
  285. V(HidServAuth, LINELIST, NULL),
  286. V(HSAuthoritativeDir, BOOL, "0"),
  287. OBSOLETE("HSAuthorityRecordStats"),
  288. V(HTTPProxy, STRING, NULL),
  289. V(HTTPProxyAuthenticator, STRING, NULL),
  290. V(HTTPSProxy, STRING, NULL),
  291. V(HTTPSProxyAuthenticator, STRING, NULL),
  292. VAR("ServerTransportPlugin", LINELIST, ServerTransportPlugin, NULL),
  293. V(Socks4Proxy, STRING, NULL),
  294. V(Socks5Proxy, STRING, NULL),
  295. V(Socks5ProxyUsername, STRING, NULL),
  296. V(Socks5ProxyPassword, STRING, NULL),
  297. OBSOLETE("IgnoreVersion"),
  298. V(KeepalivePeriod, INTERVAL, "5 minutes"),
  299. VAR("Log", LINELIST, Logs, NULL),
  300. V(LogMessageDomains, BOOL, "0"),
  301. OBSOLETE("LinkPadding"),
  302. OBSOLETE("LogLevel"),
  303. OBSOLETE("LogFile"),
  304. V(LogTimeGranularity, MSEC_INTERVAL, "1 second"),
  305. V(LongLivedPorts, CSV,
  306. "21,22,706,1863,5050,5190,5222,5223,6523,6667,6697,8300"),
  307. VAR("MapAddress", LINELIST, AddressMap, NULL),
  308. V(MaxAdvertisedBandwidth, MEMUNIT, "1 GB"),
  309. V(MaxCircuitDirtiness, INTERVAL, "10 minutes"),
  310. V(MaxClientCircuitsPending, UINT, "32"),
  311. V(MaxOnionsPending, UINT, "100"),
  312. OBSOLETE("MonthlyAccountingStart"),
  313. V(MyFamily, STRING, NULL),
  314. V(NewCircuitPeriod, INTERVAL, "30 seconds"),
  315. VAR("NamingAuthoritativeDirectory",BOOL, NamingAuthoritativeDir, "0"),
  316. V(NATDListenAddress, LINELIST, NULL),
  317. V(NATDPort, LINELIST, NULL),
  318. V(Nickname, STRING, NULL),
  319. V(WarnUnsafeSocks, BOOL, "1"),
  320. OBSOLETE("NoPublish"),
  321. VAR("NodeFamily", LINELIST, NodeFamilies, NULL),
  322. V(NumCPUs, UINT, "0"),
  323. V(NumEntryGuards, UINT, "3"),
  324. V(ORListenAddress, LINELIST, NULL),
  325. V(ORPort, PORT, "0"),
  326. V(OutboundBindAddress, STRING, NULL),
  327. OBSOLETE("PathlenCoinWeight"),
  328. V(PerConnBWBurst, MEMUNIT, "0"),
  329. V(PerConnBWRate, MEMUNIT, "0"),
  330. V(PidFile, STRING, NULL),
  331. V(TestingTorNetwork, BOOL, "0"),
  332. V(OptimisticData, AUTOBOOL, "auto"),
  333. V(PortForwarding, BOOL, "0"),
  334. V(PortForwardingHelper, FILENAME, "tor-fw-helper"),
  335. V(PreferTunneledDirConns, BOOL, "1"),
  336. V(ProtocolWarnings, BOOL, "0"),
  337. V(PublishServerDescriptor, CSV, "1"),
  338. V(PublishHidServDescriptors, BOOL, "1"),
  339. V(ReachableAddresses, LINELIST, NULL),
  340. V(ReachableDirAddresses, LINELIST, NULL),
  341. V(ReachableORAddresses, LINELIST, NULL),
  342. V(RecommendedVersions, LINELIST, NULL),
  343. V(RecommendedClientVersions, LINELIST, NULL),
  344. V(RecommendedServerVersions, LINELIST, NULL),
  345. OBSOLETE("RedirectExit"),
  346. V(RefuseUnknownExits, AUTOBOOL, "auto"),
  347. V(RejectPlaintextPorts, CSV, ""),
  348. V(RelayBandwidthBurst, MEMUNIT, "0"),
  349. V(RelayBandwidthRate, MEMUNIT, "0"),
  350. OBSOLETE("RendExcludeNodes"),
  351. OBSOLETE("RendNodes"),
  352. V(RendPostPeriod, INTERVAL, "1 hour"),
  353. V(RephistTrackTime, INTERVAL, "24 hours"),
  354. OBSOLETE("RouterFile"),
  355. V(RunAsDaemon, BOOL, "0"),
  356. // V(RunTesting, BOOL, "0"),
  357. OBSOLETE("RunTesting"), // currently unused
  358. V(SafeLogging, STRING, "1"),
  359. V(SafeSocks, BOOL, "0"),
  360. V(ServerDNSAllowBrokenConfig, BOOL, "1"),
  361. V(ServerDNSAllowNonRFC953Hostnames, BOOL,"0"),
  362. V(ServerDNSDetectHijacking, BOOL, "1"),
  363. V(ServerDNSRandomizeCase, BOOL, "1"),
  364. V(ServerDNSResolvConfFile, STRING, NULL),
  365. V(ServerDNSSearchDomains, BOOL, "0"),
  366. V(ServerDNSTestAddresses, CSV,
  367. "www.google.com,www.mit.edu,www.yahoo.com,www.slashdot.org"),
  368. V(ShutdownWaitLength, INTERVAL, "30 seconds"),
  369. V(SocksListenAddress, LINELIST, NULL),
  370. V(SocksPolicy, LINELIST, NULL),
  371. V(SocksPort, LINELIST, NULL),
  372. V(SocksTimeout, INTERVAL, "2 minutes"),
  373. OBSOLETE("StatusFetchPeriod"),
  374. V(StrictNodes, BOOL, "0"),
  375. OBSOLETE("SysLog"),
  376. V(TestSocks, BOOL, "0"),
  377. OBSOLETE("TestVia"),
  378. V(TokenBucketRefillInterval, MSEC_INTERVAL, "100 msec"),
  379. V(TrackHostExits, CSV, NULL),
  380. V(TrackHostExitsExpire, INTERVAL, "30 minutes"),
  381. OBSOLETE("TrafficShaping"),
  382. V(TransListenAddress, LINELIST, NULL),
  383. V(TransPort, LINELIST, NULL),
  384. V(TunnelDirConns, BOOL, "1"),
  385. V(UpdateBridgesFromAuthority, BOOL, "0"),
  386. V(UseBridges, BOOL, "0"),
  387. V(UseEntryGuards, BOOL, "1"),
  388. V(UseMicrodescriptors, AUTOBOOL, "auto"),
  389. V(User, STRING, NULL),
  390. VAR("V1AuthoritativeDirectory",BOOL, V1AuthoritativeDir, "0"),
  391. VAR("V2AuthoritativeDirectory",BOOL, V2AuthoritativeDir, "0"),
  392. VAR("V3AuthoritativeDirectory",BOOL, V3AuthoritativeDir, "0"),
  393. V(TestingV3AuthInitialVotingInterval, INTERVAL, "30 minutes"),
  394. V(TestingV3AuthInitialVoteDelay, INTERVAL, "5 minutes"),
  395. V(TestingV3AuthInitialDistDelay, INTERVAL, "5 minutes"),
  396. V(V3AuthVotingInterval, INTERVAL, "1 hour"),
  397. V(V3AuthVoteDelay, INTERVAL, "5 minutes"),
  398. V(V3AuthDistDelay, INTERVAL, "5 minutes"),
  399. V(V3AuthNIntervalsValid, UINT, "3"),
  400. V(V3AuthUseLegacyKey, BOOL, "0"),
  401. V(V3BandwidthsFile, FILENAME, NULL),
  402. VAR("VersioningAuthoritativeDirectory",BOOL,VersioningAuthoritativeDir, "0"),
  403. V(VirtualAddrNetwork, STRING, "127.192.0.0/10"),
  404. V(WarnPlaintextPorts, CSV, "23,109,110,143"),
  405. V(_UseFilteringSSLBufferevents, BOOL, "0"),
  406. VAR("__ReloadTorrcOnSIGHUP", BOOL, ReloadTorrcOnSIGHUP, "1"),
  407. VAR("__AllDirActionsPrivate", BOOL, AllDirActionsPrivate, "0"),
  408. VAR("__DisablePredictedCircuits",BOOL,DisablePredictedCircuits, "0"),
  409. VAR("__LeaveStreamsUnattached",BOOL, LeaveStreamsUnattached, "0"),
  410. VAR("__HashedControlSessionPassword", LINELIST, HashedControlSessionPassword,
  411. NULL),
  412. VAR("__OwningControllerProcess",STRING,OwningControllerProcess, NULL),
  413. V(MinUptimeHidServDirectoryV2, INTERVAL, "25 hours"),
  414. V(VoteOnHidServDirectoriesV2, BOOL, "1"),
  415. V(_UsingTestNetworkDefaults, BOOL, "0"),
  416. { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
  417. };
  418. /** Override default values with these if the user sets the TestingTorNetwork
  419. * option. */
  420. static const config_var_t testing_tor_network_defaults[] = {
  421. V(ServerDNSAllowBrokenConfig, BOOL, "1"),
  422. V(DirAllowPrivateAddresses, BOOL, "1"),
  423. V(EnforceDistinctSubnets, BOOL, "0"),
  424. V(AssumeReachable, BOOL, "1"),
  425. V(AuthDirMaxServersPerAddr, UINT, "0"),
  426. V(AuthDirMaxServersPerAuthAddr,UINT, "0"),
  427. V(ClientDNSRejectInternalAddresses, BOOL,"0"),
  428. V(ClientRejectInternalAddresses, BOOL, "0"),
  429. V(CountPrivateBandwidth, BOOL, "1"),
  430. V(ExitPolicyRejectPrivate, BOOL, "0"),
  431. V(V3AuthVotingInterval, INTERVAL, "5 minutes"),
  432. V(V3AuthVoteDelay, INTERVAL, "20 seconds"),
  433. V(V3AuthDistDelay, INTERVAL, "20 seconds"),
  434. V(TestingV3AuthInitialVotingInterval, INTERVAL, "5 minutes"),
  435. V(TestingV3AuthInitialVoteDelay, INTERVAL, "20 seconds"),
  436. V(TestingV3AuthInitialDistDelay, INTERVAL, "20 seconds"),
  437. V(TestingAuthDirTimeToLearnReachability, INTERVAL, "0 minutes"),
  438. V(TestingEstimatedDescriptorPropagationTime, INTERVAL, "0 minutes"),
  439. V(MinUptimeHidServDirectoryV2, INTERVAL, "0 minutes"),
  440. V(_UsingTestNetworkDefaults, BOOL, "1"),
  441. { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
  442. };
  443. #undef VAR
  444. #define VAR(name,conftype,member,initvalue) \
  445. { name, CONFIG_TYPE_ ## conftype, STRUCT_OFFSET(or_state_t, member), \
  446. initvalue }
  447. /** Array of "state" variables saved to the ~/.tor/state file. */
  448. static config_var_t _state_vars[] = {
  449. V(AccountingBytesReadInInterval, MEMUNIT, NULL),
  450. V(AccountingBytesWrittenInInterval, MEMUNIT, NULL),
  451. V(AccountingExpectedUsage, MEMUNIT, NULL),
  452. V(AccountingIntervalStart, ISOTIME, NULL),
  453. V(AccountingSecondsActive, INTERVAL, NULL),
  454. V(AccountingSecondsToReachSoftLimit,INTERVAL, NULL),
  455. V(AccountingSoftLimitHitAt, ISOTIME, NULL),
  456. V(AccountingBytesAtSoftLimit, MEMUNIT, NULL),
  457. VAR("EntryGuard", LINELIST_S, EntryGuards, NULL),
  458. VAR("EntryGuardDownSince", LINELIST_S, EntryGuards, NULL),
  459. VAR("EntryGuardUnlistedSince", LINELIST_S, EntryGuards, NULL),
  460. VAR("EntryGuardAddedBy", LINELIST_S, EntryGuards, NULL),
  461. V(EntryGuards, LINELIST_V, NULL),
  462. VAR("TransportProxy", LINELIST_S, TransportProxies, NULL),
  463. V(TransportProxies, LINELIST_V, NULL),
  464. V(BWHistoryReadEnds, ISOTIME, NULL),
  465. V(BWHistoryReadInterval, UINT, "900"),
  466. V(BWHistoryReadValues, CSV, ""),
  467. V(BWHistoryReadMaxima, CSV, ""),
  468. V(BWHistoryWriteEnds, ISOTIME, NULL),
  469. V(BWHistoryWriteInterval, UINT, "900"),
  470. V(BWHistoryWriteValues, CSV, ""),
  471. V(BWHistoryWriteMaxima, CSV, ""),
  472. V(BWHistoryDirReadEnds, ISOTIME, NULL),
  473. V(BWHistoryDirReadInterval, UINT, "900"),
  474. V(BWHistoryDirReadValues, CSV, ""),
  475. V(BWHistoryDirReadMaxima, CSV, ""),
  476. V(BWHistoryDirWriteEnds, ISOTIME, NULL),
  477. V(BWHistoryDirWriteInterval, UINT, "900"),
  478. V(BWHistoryDirWriteValues, CSV, ""),
  479. V(BWHistoryDirWriteMaxima, CSV, ""),
  480. V(TorVersion, STRING, NULL),
  481. V(LastRotatedOnionKey, ISOTIME, NULL),
  482. V(LastWritten, ISOTIME, NULL),
  483. V(TotalBuildTimes, UINT, NULL),
  484. V(CircuitBuildAbandonedCount, UINT, "0"),
  485. VAR("CircuitBuildTimeBin", LINELIST_S, BuildtimeHistogram, NULL),
  486. VAR("BuildtimeHistogram", LINELIST_V, BuildtimeHistogram, NULL),
  487. { NULL, CONFIG_TYPE_OBSOLETE, 0, NULL }
  488. };
  489. #undef VAR
  490. #undef V
  491. #undef OBSOLETE
  492. /** Represents an English description of a configuration variable; used when
  493. * generating configuration file comments. */
  494. typedef struct config_var_description_t {
  495. const char *name;
  496. const char *description;
  497. } config_var_description_t;
  498. /** Type of a callback to validate whether a given configuration is
  499. * well-formed and consistent. See options_trial_assign() for documentation
  500. * of arguments. */
  501. typedef int (*validate_fn_t)(void*,void*,int,char**);
  502. /** Information on the keys, value types, key-to-struct-member mappings,
  503. * variable descriptions, validation functions, and abbreviations for a
  504. * configuration or storage format. */
  505. typedef struct {
  506. size_t size; /**< Size of the struct that everything gets parsed into. */
  507. uint32_t magic; /**< Required 'magic value' to make sure we have a struct
  508. * of the right type. */
  509. off_t magic_offset; /**< Offset of the magic value within the struct. */
  510. config_abbrev_t *abbrevs; /**< List of abbreviations that we expand when
  511. * parsing this format. */
  512. config_var_t *vars; /**< List of variables we recognize, their default
  513. * values, and where we stick them in the structure. */
  514. validate_fn_t validate_fn; /**< Function to validate config. */
  515. /** If present, extra is a LINELIST variable for unrecognized
  516. * lines. Otherwise, unrecognized lines are an error. */
  517. config_var_t *extra;
  518. } config_format_t;
  519. /** Macro: assert that <b>cfg</b> has the right magic field for format
  520. * <b>fmt</b>. */
  521. #define CHECK(fmt, cfg) STMT_BEGIN \
  522. tor_assert(fmt && cfg); \
  523. tor_assert((fmt)->magic == \
  524. *(uint32_t*)STRUCT_VAR_P(cfg,fmt->magic_offset)); \
  525. STMT_END
  526. #ifdef MS_WINDOWS
  527. static char *get_windows_conf_root(void);
  528. #endif
  529. static void config_line_append(config_line_t **lst,
  530. const char *key, const char *val);
  531. static void option_clear(const config_format_t *fmt, or_options_t *options,
  532. const config_var_t *var);
  533. static void option_reset(const config_format_t *fmt, or_options_t *options,
  534. const config_var_t *var, int use_defaults);
  535. static void config_free(const config_format_t *fmt, void *options);
  536. static int config_lines_eq(config_line_t *a, config_line_t *b);
  537. static int option_is_same(const config_format_t *fmt,
  538. const or_options_t *o1, const or_options_t *o2,
  539. const char *name);
  540. static or_options_t *options_dup(const config_format_t *fmt,
  541. const or_options_t *old);
  542. static int options_validate(or_options_t *old_options,
  543. or_options_t *options,
  544. int from_setconf, char **msg);
  545. static int options_act_reversible(const or_options_t *old_options, char **msg);
  546. static int options_act(const or_options_t *old_options);
  547. static int options_transition_allowed(const or_options_t *old,
  548. const or_options_t *new,
  549. char **msg);
  550. static int options_transition_affects_workers(
  551. const or_options_t *old_options, const or_options_t *new_options);
  552. static int options_transition_affects_descriptor(
  553. const or_options_t *old_options, const or_options_t *new_options);
  554. static int check_nickname_list(const char *lst, const char *name, char **msg);
  555. static int parse_bridge_line(const char *line, int validate_only);
  556. static int parse_client_transport_line(const char *line, int validate_only);
  557. static int parse_server_transport_line(const char *line, int validate_only);
  558. static int parse_dir_server_line(const char *line,
  559. dirinfo_type_t required_type,
  560. int validate_only);
  561. static void port_cfg_free(port_cfg_t *port);
  562. static int parse_client_ports(const or_options_t *options, int validate_only,
  563. char **msg_out, int *n_ports_out);
  564. static int validate_data_directory(or_options_t *options);
  565. static int write_configuration_file(const char *fname,
  566. const or_options_t *options);
  567. static config_line_t *get_assigned_option(const config_format_t *fmt,
  568. const void *options, const char *key,
  569. int escape_val);
  570. static void config_init(const config_format_t *fmt, void *options);
  571. static int or_state_validate(or_state_t *old_options, or_state_t *options,
  572. int from_setconf, char **msg);
  573. static int or_state_load(void);
  574. static int options_init_logs(or_options_t *options, int validate_only);
  575. static int is_listening_on_low_port(int port_option,
  576. const config_line_t *listen_options);
  577. static uint64_t config_parse_memunit(const char *s, int *ok);
  578. static int config_parse_msec_interval(const char *s, int *ok);
  579. static int config_parse_interval(const char *s, int *ok);
  580. static void init_libevent(const or_options_t *options);
  581. static int opt_streq(const char *s1, const char *s2);
  582. /** Magic value for or_options_t. */
  583. #define OR_OPTIONS_MAGIC 9090909
  584. /** Configuration format for or_options_t. */
  585. static config_format_t options_format = {
  586. sizeof(or_options_t),
  587. OR_OPTIONS_MAGIC,
  588. STRUCT_OFFSET(or_options_t, _magic),
  589. _option_abbrevs,
  590. _option_vars,
  591. (validate_fn_t)options_validate,
  592. NULL
  593. };
  594. /** Magic value for or_state_t. */
  595. #define OR_STATE_MAGIC 0x57A73f57
  596. /** "Extra" variable in the state that receives lines we can't parse. This
  597. * lets us preserve options from versions of Tor newer than us. */
  598. static config_var_t state_extra_var = {
  599. "__extra", CONFIG_TYPE_LINELIST, STRUCT_OFFSET(or_state_t, ExtraLines), NULL
  600. };
  601. /** Configuration format for or_state_t. */
  602. static const config_format_t state_format = {
  603. sizeof(or_state_t),
  604. OR_STATE_MAGIC,
  605. STRUCT_OFFSET(or_state_t, _magic),
  606. _state_abbrevs,
  607. _state_vars,
  608. (validate_fn_t)or_state_validate,
  609. &state_extra_var,
  610. };
  611. /*
  612. * Functions to read and write the global options pointer.
  613. */
  614. /** Command-line and config-file options. */
  615. static or_options_t *global_options = NULL;
  616. /** Name of most recently read torrc file. */
  617. static char *torrc_fname = NULL;
  618. /** Persistent serialized state. */
  619. static or_state_t *global_state = NULL;
  620. /** Configuration Options set by command line. */
  621. static config_line_t *global_cmdline_options = NULL;
  622. /** Contents of most recently read DirPortFrontPage file. */
  623. static char *global_dirfrontpagecontents = NULL;
  624. /** List of port_cfg_t for client-level (SOCKS, DNS, Trans, NATD) ports. */
  625. static smartlist_t *configured_client_ports = NULL;
  626. /** Return the contents of our frontpage string, or NULL if not configured. */
  627. const char *
  628. get_dirportfrontpage(void)
  629. {
  630. return global_dirfrontpagecontents;
  631. }
  632. /** Allocate an empty configuration object of a given format type. */
  633. static void *
  634. config_alloc(const config_format_t *fmt)
  635. {
  636. void *opts = tor_malloc_zero(fmt->size);
  637. *(uint32_t*)STRUCT_VAR_P(opts, fmt->magic_offset) = fmt->magic;
  638. CHECK(fmt, opts);
  639. return opts;
  640. }
  641. /** Return the currently configured options. */
  642. or_options_t *
  643. get_options_mutable(void)
  644. {
  645. tor_assert(global_options);
  646. return global_options;
  647. }
  648. /** Returns the currently configured options */
  649. const or_options_t *
  650. get_options(void)
  651. {
  652. return get_options_mutable();
  653. }
  654. /** Change the current global options to contain <b>new_val</b> instead of
  655. * their current value; take action based on the new value; free the old value
  656. * as necessary. Returns 0 on success, -1 on failure.
  657. */
  658. int
  659. set_options(or_options_t *new_val, char **msg)
  660. {
  661. int i;
  662. smartlist_t *elements;
  663. config_line_t *line;
  664. or_options_t *old_options = global_options;
  665. global_options = new_val;
  666. /* Note that we pass the *old* options below, for comparison. It
  667. * pulls the new options directly out of global_options. */
  668. if (options_act_reversible(old_options, msg)<0) {
  669. tor_assert(*msg);
  670. global_options = old_options;
  671. return -1;
  672. }
  673. if (options_act(old_options) < 0) { /* acting on the options failed. die. */
  674. log_err(LD_BUG,
  675. "Acting on config options left us in a broken state. Dying.");
  676. exit(1);
  677. }
  678. /* Issues a CONF_CHANGED event to notify controller of the change. If Tor is
  679. * just starting up then the old_options will be undefined. */
  680. if (old_options) {
  681. elements = smartlist_create();
  682. for (i=0; options_format.vars[i].name; ++i) {
  683. const config_var_t *var = &options_format.vars[i];
  684. const char *var_name = var->name;
  685. if (var->type == CONFIG_TYPE_LINELIST_S ||
  686. var->type == CONFIG_TYPE_OBSOLETE) {
  687. continue;
  688. }
  689. if (!option_is_same(&options_format, new_val, old_options, var_name)) {
  690. line = get_assigned_option(&options_format, new_val, var_name, 1);
  691. if (line) {
  692. for (; line; line = line->next) {
  693. smartlist_add(elements, line->key);
  694. smartlist_add(elements, line->value);
  695. }
  696. } else {
  697. smartlist_add(elements, (char*)options_format.vars[i].name);
  698. smartlist_add(elements, NULL);
  699. }
  700. }
  701. }
  702. control_event_conf_changed(elements);
  703. smartlist_free(elements);
  704. }
  705. config_free(&options_format, old_options);
  706. return 0;
  707. }
  708. extern const char tor_git_revision[]; /* from tor_main.c */
  709. /** The version of this Tor process, as parsed. */
  710. static char *_version = NULL;
  711. /** Return the current Tor version. */
  712. const char *
  713. get_version(void)
  714. {
  715. if (_version == NULL) {
  716. if (strlen(tor_git_revision)) {
  717. size_t len = strlen(VERSION)+strlen(tor_git_revision)+16;
  718. _version = tor_malloc(len);
  719. tor_snprintf(_version, len, "%s (git-%s)", VERSION, tor_git_revision);
  720. } else {
  721. _version = tor_strdup(VERSION);
  722. }
  723. }
  724. return _version;
  725. }
  726. /** Release additional memory allocated in options
  727. */
  728. static void
  729. or_options_free(or_options_t *options)
  730. {
  731. if (!options)
  732. return;
  733. routerset_free(options->_ExcludeExitNodesUnion);
  734. if (options->NodeFamilySets) {
  735. SMARTLIST_FOREACH(options->NodeFamilySets, routerset_t *,
  736. rs, routerset_free(rs));
  737. smartlist_free(options->NodeFamilySets);
  738. }
  739. config_free(&options_format, options);
  740. }
  741. /** Release all memory and resources held by global configuration structures.
  742. */
  743. void
  744. config_free_all(void)
  745. {
  746. or_options_free(global_options);
  747. global_options = NULL;
  748. config_free(&state_format, global_state);
  749. global_state = NULL;
  750. config_free_lines(global_cmdline_options);
  751. global_cmdline_options = NULL;
  752. if (configured_client_ports) {
  753. SMARTLIST_FOREACH(configured_client_ports,
  754. port_cfg_t *, p, tor_free(p));
  755. smartlist_free(configured_client_ports);
  756. configured_client_ports = NULL;
  757. }
  758. tor_free(torrc_fname);
  759. tor_free(_version);
  760. tor_free(global_dirfrontpagecontents);
  761. }
  762. /** Make <b>address</b> -- a piece of information related to our operation as
  763. * a client -- safe to log according to the settings in options->SafeLogging,
  764. * and return it.
  765. *
  766. * (We return "[scrubbed]" if SafeLogging is "1", and address otherwise.)
  767. */
  768. const char *
  769. safe_str_client(const char *address)
  770. {
  771. tor_assert(address);
  772. if (get_options()->_SafeLogging == SAFELOG_SCRUB_ALL)
  773. return "[scrubbed]";
  774. else
  775. return address;
  776. }
  777. /** Make <b>address</b> -- a piece of information of unspecified sensitivity
  778. * -- safe to log according to the settings in options->SafeLogging, and
  779. * return it.
  780. *
  781. * (We return "[scrubbed]" if SafeLogging is anything besides "0", and address
  782. * otherwise.)
  783. */
  784. const char *
  785. safe_str(const char *address)
  786. {
  787. tor_assert(address);
  788. if (get_options()->_SafeLogging != SAFELOG_SCRUB_NONE)
  789. return "[scrubbed]";
  790. else
  791. return address;
  792. }
  793. /** Equivalent to escaped(safe_str_client(address)). See reentrancy note on
  794. * escaped(): don't use this outside the main thread, or twice in the same
  795. * log statement. */
  796. const char *
  797. escaped_safe_str_client(const char *address)
  798. {
  799. if (get_options()->_SafeLogging == SAFELOG_SCRUB_ALL)
  800. return "[scrubbed]";
  801. else
  802. return escaped(address);
  803. }
  804. /** Equivalent to escaped(safe_str(address)). See reentrancy note on
  805. * escaped(): don't use this outside the main thread, or twice in the same
  806. * log statement. */
  807. const char *
  808. escaped_safe_str(const char *address)
  809. {
  810. if (get_options()->_SafeLogging != SAFELOG_SCRUB_NONE)
  811. return "[scrubbed]";
  812. else
  813. return escaped(address);
  814. }
  815. /** Add the default directory authorities directly into the trusted dir list,
  816. * but only add them insofar as they share bits with <b>type</b>. */
  817. static void
  818. add_default_trusted_dir_authorities(dirinfo_type_t type)
  819. {
  820. int i;
  821. const char *dirservers[] = {
  822. "moria1 orport=9101 no-v2 "
  823. "v3ident=D586D18309DED4CD6D57C18FDB97EFA96D330566 "
  824. "128.31.0.39:9131 9695 DFC3 5FFE B861 329B 9F1A B04C 4639 7020 CE31",
  825. "tor26 v1 orport=443 v3ident=14C131DFC5C6F93646BE72FA1401C02A8DF2E8B4 "
  826. "86.59.21.38:80 847B 1F85 0344 D787 6491 A548 92F9 0493 4E4E B85D",
  827. "dizum orport=443 v3ident=E8A9C45EDE6D711294FADF8E7951F4DE6CA56B58 "
  828. "194.109.206.212:80 7EA6 EAD6 FD83 083C 538F 4403 8BBF A077 587D D755",
  829. "Tonga orport=443 bridge no-v2 82.94.251.203:80 "
  830. "4A0C CD2D DC79 9508 3D73 F5D6 6710 0C8A 5831 F16D",
  831. "ides orport=9090 no-v2 v3ident=27B6B5996C426270A5C95488AA5BCEB6BCC86956 "
  832. "216.224.124.114:9030 F397 038A DC51 3361 35E7 B80B D99C A384 4360 292B",
  833. "gabelmoo orport=443 no-v2 "
  834. "v3ident=ED03BB616EB2F60BEC80151114BB25CEF515B226 "
  835. "212.112.245.170:80 F204 4413 DAC2 E02E 3D6B CF47 35A1 9BCA 1DE9 7281",
  836. "dannenberg orport=443 no-v2 "
  837. "v3ident=585769C78764D58426B8B52B6651A5A71137189A "
  838. "193.23.244.244:80 7BE6 83E6 5D48 1413 21C5 ED92 F075 C553 64AC 7123",
  839. "urras orport=80 no-v2 v3ident=80550987E1D626E3EBA5E5E75A458DE0626D088C "
  840. "208.83.223.34:443 0AD3 FA88 4D18 F89E EA2D 89C0 1937 9E0E 7FD9 4417",
  841. "maatuska orport=80 no-v2 "
  842. "v3ident=49015F787433103580E3B66A1707A00E60F2D15B "
  843. "213.115.239.118:443 BD6A 8292 55CB 08E6 6FBE 7D37 4836 3586 E46B 3810",
  844. NULL
  845. };
  846. for (i=0; dirservers[i]; i++) {
  847. if (parse_dir_server_line(dirservers[i], type, 0)<0) {
  848. log_err(LD_BUG, "Couldn't parse internal dirserver line %s",
  849. dirservers[i]);
  850. }
  851. }
  852. }
  853. /** Look at all the config options for using alternate directory
  854. * authorities, and make sure none of them are broken. Also, warn the
  855. * user if we changed any dangerous ones.
  856. */
  857. static int
  858. validate_dir_authorities(or_options_t *options, or_options_t *old_options)
  859. {
  860. config_line_t *cl;
  861. if (options->DirServers &&
  862. (options->AlternateDirAuthority || options->AlternateBridgeAuthority ||
  863. options->AlternateHSAuthority)) {
  864. log_warn(LD_CONFIG,
  865. "You cannot set both DirServers and Alternate*Authority.");
  866. return -1;
  867. }
  868. /* do we want to complain to the user about being partitionable? */
  869. if ((options->DirServers &&
  870. (!old_options ||
  871. !config_lines_eq(options->DirServers, old_options->DirServers))) ||
  872. (options->AlternateDirAuthority &&
  873. (!old_options ||
  874. !config_lines_eq(options->AlternateDirAuthority,
  875. old_options->AlternateDirAuthority)))) {
  876. log_warn(LD_CONFIG,
  877. "You have used DirServer or AlternateDirAuthority to "
  878. "specify alternate directory authorities in "
  879. "your configuration. This is potentially dangerous: it can "
  880. "make you look different from all other Tor users, and hurt "
  881. "your anonymity. Even if you've specified the same "
  882. "authorities as Tor uses by default, the defaults could "
  883. "change in the future. Be sure you know what you're doing.");
  884. }
  885. /* Now go through the four ways you can configure an alternate
  886. * set of directory authorities, and make sure none are broken. */
  887. for (cl = options->DirServers; cl; cl = cl->next)
  888. if (parse_dir_server_line(cl->value, NO_DIRINFO, 1)<0)
  889. return -1;
  890. for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
  891. if (parse_dir_server_line(cl->value, NO_DIRINFO, 1)<0)
  892. return -1;
  893. for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
  894. if (parse_dir_server_line(cl->value, NO_DIRINFO, 1)<0)
  895. return -1;
  896. for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
  897. if (parse_dir_server_line(cl->value, NO_DIRINFO, 1)<0)
  898. return -1;
  899. return 0;
  900. }
  901. /** Look at all the config options and assign new dir authorities
  902. * as appropriate.
  903. */
  904. static int
  905. consider_adding_dir_authorities(const or_options_t *options,
  906. const or_options_t *old_options)
  907. {
  908. config_line_t *cl;
  909. int need_to_update =
  910. !smartlist_len(router_get_trusted_dir_servers()) || !old_options ||
  911. !config_lines_eq(options->DirServers, old_options->DirServers) ||
  912. !config_lines_eq(options->AlternateBridgeAuthority,
  913. old_options->AlternateBridgeAuthority) ||
  914. !config_lines_eq(options->AlternateDirAuthority,
  915. old_options->AlternateDirAuthority) ||
  916. !config_lines_eq(options->AlternateHSAuthority,
  917. old_options->AlternateHSAuthority);
  918. if (!need_to_update)
  919. return 0; /* all done */
  920. /* Start from a clean slate. */
  921. clear_trusted_dir_servers();
  922. if (!options->DirServers) {
  923. /* then we may want some of the defaults */
  924. dirinfo_type_t type = NO_DIRINFO;
  925. if (!options->AlternateBridgeAuthority)
  926. type |= BRIDGE_DIRINFO;
  927. if (!options->AlternateDirAuthority)
  928. type |= V1_DIRINFO | V2_DIRINFO | V3_DIRINFO | EXTRAINFO_DIRINFO |
  929. MICRODESC_DIRINFO;
  930. if (!options->AlternateHSAuthority)
  931. type |= HIDSERV_DIRINFO;
  932. add_default_trusted_dir_authorities(type);
  933. }
  934. for (cl = options->DirServers; cl; cl = cl->next)
  935. if (parse_dir_server_line(cl->value, NO_DIRINFO, 0)<0)
  936. return -1;
  937. for (cl = options->AlternateBridgeAuthority; cl; cl = cl->next)
  938. if (parse_dir_server_line(cl->value, NO_DIRINFO, 0)<0)
  939. return -1;
  940. for (cl = options->AlternateDirAuthority; cl; cl = cl->next)
  941. if (parse_dir_server_line(cl->value, NO_DIRINFO, 0)<0)
  942. return -1;
  943. for (cl = options->AlternateHSAuthority; cl; cl = cl->next)
  944. if (parse_dir_server_line(cl->value, NO_DIRINFO, 0)<0)
  945. return -1;
  946. return 0;
  947. }
  948. /** Fetch the active option list, and take actions based on it. All of the
  949. * things we do should survive being done repeatedly. If present,
  950. * <b>old_options</b> contains the previous value of the options.
  951. *
  952. * Return 0 if all goes well, return -1 if things went badly.
  953. */
  954. static int
  955. options_act_reversible(const or_options_t *old_options, char **msg)
  956. {
  957. smartlist_t *new_listeners = smartlist_create();
  958. smartlist_t *replaced_listeners = smartlist_create();
  959. static int libevent_initialized = 0;
  960. or_options_t *options = get_options_mutable();
  961. int running_tor = options->command == CMD_RUN_TOR;
  962. int set_conn_limit = 0;
  963. int r = -1;
  964. int logs_marked = 0;
  965. /* Daemonize _first_, since we only want to open most of this stuff in
  966. * the subprocess. Libevent bases can't be reliably inherited across
  967. * processes. */
  968. if (running_tor && options->RunAsDaemon) {
  969. /* No need to roll back, since you can't change the value. */
  970. start_daemon();
  971. }
  972. #ifndef HAVE_SYS_UN_H
  973. if (options->ControlSocket || options->ControlSocketsGroupWritable) {
  974. *msg = tor_strdup("Unix domain sockets (ControlSocket) not supported "
  975. "on this OS/with this build.");
  976. goto rollback;
  977. }
  978. #else
  979. if (options->ControlSocketsGroupWritable && !options->ControlSocket) {
  980. *msg = tor_strdup("Setting ControlSocketGroupWritable without setting"
  981. "a ControlSocket makes no sense.");
  982. goto rollback;
  983. }
  984. #endif
  985. if (running_tor) {
  986. int n_client_ports=0;
  987. /* We need to set the connection limit before we can open the listeners. */
  988. if (set_max_file_descriptors((unsigned)options->ConnLimit,
  989. &options->_ConnLimit) < 0) {
  990. *msg = tor_strdup("Problem with ConnLimit value. See logs for details.");
  991. goto rollback;
  992. }
  993. set_conn_limit = 1;
  994. /* Set up libevent. (We need to do this before we can register the
  995. * listeners as listeners.) */
  996. if (running_tor && !libevent_initialized) {
  997. init_libevent(options);
  998. libevent_initialized = 1;
  999. }
  1000. /* Adjust the client port configuration so we can launch listeners. */
  1001. if (parse_client_ports(options, 0, msg, &n_client_ports))
  1002. return -1;
  1003. /* Set the hibernation state appropriately.*/
  1004. consider_hibernation(time(NULL));
  1005. /* Launch the listeners. (We do this before we setuid, so we can bind to
  1006. * ports under 1024.) We don't want to rebind if we're hibernating. */
  1007. if (!we_are_hibernating()) {
  1008. if (retry_all_listeners(replaced_listeners, new_listeners) < 0) {
  1009. *msg = tor_strdup("Failed to bind one of the listener ports.");
  1010. goto rollback;
  1011. }
  1012. }
  1013. }
  1014. #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
  1015. /* Open /dev/pf before dropping privileges. */
  1016. if (options->TransPort) {
  1017. if (get_pf_socket() < 0) {
  1018. *msg = tor_strdup("Unable to open /dev/pf for transparent proxy.");
  1019. goto rollback;
  1020. }
  1021. }
  1022. #endif
  1023. /* Attempt to lock all current and future memory with mlockall() only once */
  1024. if (options->DisableAllSwap) {
  1025. if (tor_mlockall() == -1) {
  1026. *msg = tor_strdup("DisableAllSwap failure. Do you have proper "
  1027. "permissions?");
  1028. goto done;
  1029. }
  1030. }
  1031. /* Setuid/setgid as appropriate */
  1032. if (options->User) {
  1033. if (switch_id(options->User) != 0) {
  1034. /* No need to roll back, since you can't change the value. */
  1035. *msg = tor_strdup("Problem with User value. See logs for details.");
  1036. goto done;
  1037. }
  1038. }
  1039. /* Ensure data directory is private; create if possible. */
  1040. if (check_private_dir(options->DataDirectory,
  1041. running_tor ? CPD_CREATE : CPD_CHECK,
  1042. options->User)<0) {
  1043. tor_asprintf(msg,
  1044. "Couldn't access/create private data directory \"%s\"",
  1045. options->DataDirectory);
  1046. goto done;
  1047. /* No need to roll back, since you can't change the value. */
  1048. }
  1049. /* Write control ports to disk as appropriate */
  1050. control_ports_write_to_file();
  1051. if (directory_caches_v2_dir_info(options)) {
  1052. size_t len = strlen(options->DataDirectory)+32;
  1053. char *fn = tor_malloc(len);
  1054. tor_snprintf(fn, len, "%s"PATH_SEPARATOR"cached-status",
  1055. options->DataDirectory);
  1056. if (check_private_dir(fn, running_tor ? CPD_CREATE : CPD_CHECK,
  1057. options->User) < 0) {
  1058. tor_asprintf(msg,
  1059. "Couldn't access/create private data directory \"%s\"", fn);
  1060. tor_free(fn);
  1061. goto done;
  1062. }
  1063. tor_free(fn);
  1064. }
  1065. /* Bail out at this point if we're not going to be a client or server:
  1066. * we don't run Tor itself. */
  1067. if (!running_tor)
  1068. goto commit;
  1069. mark_logs_temp(); /* Close current logs once new logs are open. */
  1070. logs_marked = 1;
  1071. if (options_init_logs(options, 0)<0) { /* Configure the log(s) */
  1072. *msg = tor_strdup("Failed to init Log options. See logs for details.");
  1073. goto rollback;
  1074. }
  1075. commit:
  1076. r = 0;
  1077. if (logs_marked) {
  1078. log_severity_list_t *severity =
  1079. tor_malloc_zero(sizeof(log_severity_list_t));
  1080. close_temp_logs();
  1081. add_callback_log(severity, control_event_logmsg);
  1082. control_adjust_event_log_severity();
  1083. tor_free(severity);
  1084. }
  1085. SMARTLIST_FOREACH(replaced_listeners, connection_t *, conn,
  1086. {
  1087. log_notice(LD_NET, "Closing old %s on %s:%d",
  1088. conn_type_to_string(conn->type), conn->address, conn->port);
  1089. connection_close_immediate(conn);
  1090. connection_mark_for_close(conn);
  1091. });
  1092. goto done;
  1093. rollback:
  1094. r = -1;
  1095. tor_assert(*msg);
  1096. if (logs_marked) {
  1097. rollback_log_changes();
  1098. control_adjust_event_log_severity();
  1099. }
  1100. if (set_conn_limit && old_options)
  1101. set_max_file_descriptors((unsigned)old_options->ConnLimit,
  1102. &options->_ConnLimit);
  1103. SMARTLIST_FOREACH(new_listeners, connection_t *, conn,
  1104. {
  1105. log_notice(LD_NET, "Closing partially-constructed listener %s on %s:%d",
  1106. conn_type_to_string(conn->type), conn->address, conn->port);
  1107. connection_close_immediate(conn);
  1108. connection_mark_for_close(conn);
  1109. });
  1110. done:
  1111. smartlist_free(new_listeners);
  1112. smartlist_free(replaced_listeners);
  1113. return r;
  1114. }
  1115. /** If we need to have a GEOIP ip-to-country map to run with our configured
  1116. * options, return 1 and set *<b>reason_out</b> to a description of why. */
  1117. int
  1118. options_need_geoip_info(const or_options_t *options, const char **reason_out)
  1119. {
  1120. int bridge_usage =
  1121. options->BridgeRelay && options->BridgeRecordUsageByCountry;
  1122. int routerset_usage =
  1123. routerset_needs_geoip(options->EntryNodes) ||
  1124. routerset_needs_geoip(options->ExitNodes) ||
  1125. routerset_needs_geoip(options->ExcludeExitNodes) ||
  1126. routerset_needs_geoip(options->ExcludeNodes);
  1127. if (routerset_usage && reason_out) {
  1128. *reason_out = "We've been configured to use (or avoid) nodes in certain "
  1129. "countries, and we need GEOIP information to figure out which ones they "
  1130. "are.";
  1131. } else if (bridge_usage && reason_out) {
  1132. *reason_out = "We've been configured to see which countries can access "
  1133. "us as a bridge, and we need GEOIP information to tell which countries "
  1134. "clients are in.";
  1135. }
  1136. return bridge_usage || routerset_usage;
  1137. }
  1138. /** Return the bandwidthrate that we are going to report to the authorities
  1139. * based on the config options. */
  1140. uint32_t
  1141. get_effective_bwrate(const or_options_t *options)
  1142. {
  1143. uint64_t bw = options->BandwidthRate;
  1144. if (bw > options->MaxAdvertisedBandwidth)
  1145. bw = options->MaxAdvertisedBandwidth;
  1146. if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
  1147. bw = options->RelayBandwidthRate;
  1148. /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
  1149. return (uint32_t)bw;
  1150. }
  1151. /** Return the bandwidthburst that we are going to report to the authorities
  1152. * based on the config options. */
  1153. uint32_t
  1154. get_effective_bwburst(const or_options_t *options)
  1155. {
  1156. uint64_t bw = options->BandwidthBurst;
  1157. if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
  1158. bw = options->RelayBandwidthBurst;
  1159. /* ensure_bandwidth_cap() makes sure that this cast can't overflow. */
  1160. return (uint32_t)bw;
  1161. }
  1162. /** Fetch the active option list, and take actions based on it. All of the
  1163. * things we do should survive being done repeatedly. If present,
  1164. * <b>old_options</b> contains the previous value of the options.
  1165. *
  1166. * Return 0 if all goes well, return -1 if it's time to die.
  1167. *
  1168. * Note: We haven't moved all the "act on new configuration" logic
  1169. * here yet. Some is still in do_hup() and other places.
  1170. */
  1171. static int
  1172. options_act(const or_options_t *old_options)
  1173. {
  1174. config_line_t *cl;
  1175. or_options_t *options = get_options_mutable();
  1176. int running_tor = options->command == CMD_RUN_TOR;
  1177. char *msg;
  1178. const int transition_affects_workers =
  1179. old_options && options_transition_affects_workers(old_options, options);
  1180. if (running_tor && !have_lockfile()) {
  1181. if (try_locking(options, 1) < 0)
  1182. return -1;
  1183. }
  1184. if (consider_adding_dir_authorities(options, old_options) < 0)
  1185. return -1;
  1186. if (options->Bridges) {
  1187. mark_bridge_list();
  1188. for (cl = options->Bridges; cl; cl = cl->next) {
  1189. if (parse_bridge_line(cl->value, 0)<0) {
  1190. log_warn(LD_BUG,
  1191. "Previously validated Bridge line could not be added!");
  1192. return -1;
  1193. }
  1194. }
  1195. sweep_bridge_list();
  1196. }
  1197. if (running_tor && rend_config_services(options, 0)<0) {
  1198. log_warn(LD_BUG,
  1199. "Previously validated hidden services line could not be added!");
  1200. return -1;
  1201. }
  1202. if (running_tor && rend_parse_service_authorization(options, 0) < 0) {
  1203. log_warn(LD_BUG, "Previously validated client authorization for "
  1204. "hidden services could not be added!");
  1205. return -1;
  1206. }
  1207. /* Load state */
  1208. if (! global_state && running_tor) {
  1209. if (or_state_load())
  1210. return -1;
  1211. rep_hist_load_mtbf_data(time(NULL));
  1212. }
  1213. mark_transport_list();
  1214. pt_prepare_proxy_list_for_config_read();
  1215. if (options->ClientTransportPlugin) {
  1216. for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
  1217. if (parse_client_transport_line(cl->value, 0)<0) {
  1218. log_warn(LD_BUG,
  1219. "Previously validated ClientTransportPlugin line "
  1220. "could not be added!");
  1221. return -1;
  1222. }
  1223. }
  1224. }
  1225. if (options->ServerTransportPlugin) {
  1226. for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
  1227. if (parse_server_transport_line(cl->value, 0)<0) {
  1228. log_warn(LD_BUG,
  1229. "Previously validated ServerTransportPlugin line "
  1230. "could not be added!");
  1231. return -1;
  1232. }
  1233. }
  1234. }
  1235. sweep_transport_list();
  1236. sweep_proxy_list();
  1237. /* Bail out at this point if we're not going to be a client or server:
  1238. * we want to not fork, and to log stuff to stderr. */
  1239. if (!running_tor)
  1240. return 0;
  1241. /* Finish backgrounding the process */
  1242. if (options->RunAsDaemon) {
  1243. /* We may be calling this for the n'th time (on SIGHUP), but it's safe. */
  1244. finish_daemon(options->DataDirectory);
  1245. }
  1246. /* We want to reinit keys as needed before we do much of anything else:
  1247. keys are important, and other things can depend on them. */
  1248. if (transition_affects_workers ||
  1249. (options->V3AuthoritativeDir && (!old_options ||
  1250. !old_options->V3AuthoritativeDir))) {
  1251. if (init_keys() < 0) {
  1252. log_warn(LD_BUG,"Error initializing keys; exiting");
  1253. return -1;
  1254. }
  1255. }
  1256. /* Write our PID to the PID file. If we do not have write permissions we
  1257. * will log a warning */
  1258. if (options->PidFile)
  1259. write_pidfile(options->PidFile);
  1260. /* Register addressmap directives */
  1261. config_register_addressmaps(options);
  1262. parse_virtual_addr_network(options->VirtualAddrNetwork, 0, &msg);
  1263. /* Update address policies. */
  1264. if (policies_parse_from_options(options) < 0) {
  1265. /* This should be impossible, but let's be sure. */
  1266. log_warn(LD_BUG,"Error parsing already-validated policy options.");
  1267. return -1;
  1268. }
  1269. if (init_cookie_authentication(options->CookieAuthentication) < 0) {
  1270. log_warn(LD_CONFIG,"Error creating cookie authentication file.");
  1271. return -1;
  1272. }
  1273. monitor_owning_controller_process(options->OwningControllerProcess);
  1274. /* reload keys as needed for rendezvous services. */
  1275. if (rend_service_load_keys()<0) {
  1276. log_warn(LD_GENERAL,"Error loading rendezvous service keys");
  1277. return -1;
  1278. }
  1279. /* Set up accounting */
  1280. if (accounting_parse_options(options, 0)<0) {
  1281. log_warn(LD_CONFIG,"Error in accounting options");
  1282. return -1;
  1283. }
  1284. if (accounting_is_enabled(options))
  1285. configure_accounting(time(NULL));
  1286. #ifdef USE_BUFFEREVENTS
  1287. /* If we're using the bufferevents implementation and our rate limits
  1288. * changed, we need to tell the rate-limiting system about it. */
  1289. if (!old_options ||
  1290. old_options->BandwidthRate != options->BandwidthRate ||
  1291. old_options->BandwidthBurst != options->BandwidthBurst ||
  1292. old_options->RelayBandwidthRate != options->RelayBandwidthRate ||
  1293. old_options->RelayBandwidthBurst != options->RelayBandwidthBurst)
  1294. connection_bucket_init();
  1295. #endif
  1296. /* Change the cell EWMA settings */
  1297. cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
  1298. /* Check for transitions that need action. */
  1299. if (old_options) {
  1300. int revise_trackexithosts = 0;
  1301. int revise_automap_entries = 0;
  1302. if ((options->UseEntryGuards && !old_options->UseEntryGuards) ||
  1303. options->UseBridges != old_options->UseBridges ||
  1304. (options->UseBridges &&
  1305. !config_lines_eq(options->Bridges, old_options->Bridges)) ||
  1306. !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes) ||
  1307. !routerset_equal(old_options->ExcludeExitNodes,
  1308. options->ExcludeExitNodes) ||
  1309. !routerset_equal(old_options->EntryNodes, options->EntryNodes) ||
  1310. !routerset_equal(old_options->ExitNodes, options->ExitNodes) ||
  1311. options->StrictNodes != old_options->StrictNodes) {
  1312. log_info(LD_CIRC,
  1313. "Changed to using entry guards or bridges, or changed "
  1314. "preferred or excluded node lists. "
  1315. "Abandoning previous circuits.");
  1316. circuit_mark_all_unused_circs();
  1317. circuit_expire_all_dirty_circs();
  1318. revise_trackexithosts = 1;
  1319. }
  1320. if (!smartlist_strings_eq(old_options->TrackHostExits,
  1321. options->TrackHostExits))
  1322. revise_trackexithosts = 1;
  1323. if (revise_trackexithosts)
  1324. addressmap_clear_excluded_trackexithosts(options);
  1325. if (!options->AutomapHostsOnResolve) {
  1326. if (old_options->AutomapHostsOnResolve)
  1327. revise_automap_entries = 1;
  1328. } else {
  1329. if (!smartlist_strings_eq(old_options->AutomapHostsSuffixes,
  1330. options->AutomapHostsSuffixes))
  1331. revise_automap_entries = 1;
  1332. else if (!opt_streq(old_options->VirtualAddrNetwork,
  1333. options->VirtualAddrNetwork))
  1334. revise_automap_entries = 1;
  1335. }
  1336. if (revise_automap_entries)
  1337. addressmap_clear_invalid_automaps(options);
  1338. /* How long should we delay counting bridge stats after becoming a bridge?
  1339. * We use this so we don't count people who used our bridge thinking it is
  1340. * a relay. If you change this, don't forget to change the log message
  1341. * below. It's 4 hours (the time it takes to stop being used by clients)
  1342. * plus some extra time for clock skew. */
  1343. #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
  1344. if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
  1345. int was_relay = 0;
  1346. if (options->BridgeRelay) {
  1347. time_t int_start = time(NULL);
  1348. if (old_options->ORPort == options->ORPort) {
  1349. int_start += RELAY_BRIDGE_STATS_DELAY;
  1350. was_relay = 1;
  1351. }
  1352. geoip_bridge_stats_init(int_start);
  1353. log_info(LD_CONFIG, "We are acting as a bridge now. Starting new "
  1354. "GeoIP stats interval%s.", was_relay ? " in 6 "
  1355. "hours from now" : "");
  1356. } else {
  1357. geoip_bridge_stats_term();
  1358. log_info(LD_GENERAL, "We are no longer acting as a bridge. "
  1359. "Forgetting GeoIP stats.");
  1360. }
  1361. }
  1362. if (transition_affects_workers) {
  1363. log_info(LD_GENERAL,
  1364. "Worker-related options changed. Rotating workers.");
  1365. if (server_mode(options) && !server_mode(old_options)) {
  1366. ip_address_changed(0);
  1367. if (can_complete_circuit || !any_predicted_circuits(time(NULL)))
  1368. inform_testing_reachability();
  1369. }
  1370. cpuworkers_rotate();
  1371. if (dns_reset())
  1372. return -1;
  1373. } else {
  1374. if (dns_reset())
  1375. return -1;
  1376. }
  1377. if (options->PerConnBWRate != old_options->PerConnBWRate ||
  1378. options->PerConnBWBurst != old_options->PerConnBWBurst)
  1379. connection_or_update_token_buckets(get_connection_array(), options);
  1380. }
  1381. /* Maybe load geoip file */
  1382. if (options->GeoIPFile &&
  1383. ((!old_options || !opt_streq(old_options->GeoIPFile, options->GeoIPFile))
  1384. || !geoip_is_loaded())) {
  1385. /* XXXX Don't use this "<default>" junk; make our filename options
  1386. * understand prefixes somehow. -NM */
  1387. /* XXXX023 Reload GeoIPFile on SIGHUP. -NM */
  1388. char *actual_fname = tor_strdup(options->GeoIPFile);
  1389. #ifdef WIN32
  1390. if (!strcmp(actual_fname, "<default>")) {
  1391. const char *conf_root = get_windows_conf_root();
  1392. size_t len = strlen(conf_root)+16;
  1393. tor_free(actual_fname);
  1394. actual_fname = tor_malloc(len+1);
  1395. tor_snprintf(actual_fname, len, "%s\\geoip", conf_root);
  1396. }
  1397. #endif
  1398. geoip_load_file(actual_fname, options);
  1399. tor_free(actual_fname);
  1400. }
  1401. if (options->CellStatistics || options->DirReqStatistics ||
  1402. options->EntryStatistics || options->ExitPortStatistics ||
  1403. options->ConnDirectionStatistics ||
  1404. options->BridgeAuthoritativeDir) {
  1405. time_t now = time(NULL);
  1406. int print_notice = 0;
  1407. if ((!old_options || !old_options->CellStatistics) &&
  1408. options->CellStatistics) {
  1409. rep_hist_buffer_stats_init(now);
  1410. print_notice = 1;
  1411. }
  1412. if ((!old_options || !old_options->DirReqStatistics) &&
  1413. options->DirReqStatistics) {
  1414. if (geoip_is_loaded()) {
  1415. geoip_dirreq_stats_init(now);
  1416. print_notice = 1;
  1417. } else {
  1418. options->DirReqStatistics = 0;
  1419. /* Don't warn Tor clients, they don't use statistics */
  1420. if (options->ORPort)
  1421. log_notice(LD_CONFIG, "Configured to measure directory request "
  1422. "statistics, but no GeoIP database found. "
  1423. "Please specify a GeoIP database using the "
  1424. "GeoIPFile option.");
  1425. }
  1426. }
  1427. if ((!old_options || !old_options->EntryStatistics) &&
  1428. options->EntryStatistics && !should_record_bridge_info(options)) {
  1429. if (geoip_is_loaded()) {
  1430. geoip_entry_stats_init(now);
  1431. print_notice = 1;
  1432. } else {
  1433. options->EntryStatistics = 0;
  1434. log_notice(LD_CONFIG, "Configured to measure entry node "
  1435. "statistics, but no GeoIP database found. "
  1436. "Please specify a GeoIP database using the "
  1437. "GeoIPFile option.");
  1438. }
  1439. }
  1440. if ((!old_options || !old_options->ExitPortStatistics) &&
  1441. options->ExitPortStatistics) {
  1442. rep_hist_exit_stats_init(now);
  1443. print_notice = 1;
  1444. }
  1445. if ((!old_options || !old_options->ConnDirectionStatistics) &&
  1446. options->ConnDirectionStatistics) {
  1447. rep_hist_conn_stats_init(now);
  1448. }
  1449. if (!old_options || !old_options->BridgeAuthoritativeDir) {
  1450. rep_hist_desc_stats_init(now);
  1451. print_notice = 1;
  1452. }
  1453. if (print_notice)
  1454. log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
  1455. "the *-stats files that will first be written to the "
  1456. "data directory in 24 hours from now.");
  1457. }
  1458. if (old_options && old_options->CellStatistics &&
  1459. !options->CellStatistics)
  1460. rep_hist_buffer_stats_term();
  1461. if (old_options && old_options->DirReqStatistics &&
  1462. !options->DirReqStatistics)
  1463. geoip_dirreq_stats_term();
  1464. if (old_options && old_options->EntryStatistics &&
  1465. !options->EntryStatistics)
  1466. geoip_entry_stats_term();
  1467. if (old_options && old_options->ExitPortStatistics &&
  1468. !options->ExitPortStatistics)
  1469. rep_hist_exit_stats_term();
  1470. if (old_options && old_options->ConnDirectionStatistics &&
  1471. !options->ConnDirectionStatistics)
  1472. rep_hist_conn_stats_term();
  1473. if (old_options && old_options->BridgeAuthoritativeDir &&
  1474. !options->BridgeAuthoritativeDir)
  1475. rep_hist_desc_stats_term();
  1476. /* Check if we need to parse and add the EntryNodes config option. */
  1477. if (options->EntryNodes &&
  1478. (!old_options ||
  1479. !routerset_equal(old_options->EntryNodes,options->EntryNodes) ||
  1480. !routerset_equal(old_options->ExcludeNodes,options->ExcludeNodes)))
  1481. entry_nodes_should_be_added();
  1482. /* Since our options changed, we might need to regenerate and upload our
  1483. * server descriptor.
  1484. */
  1485. if (!old_options ||
  1486. options_transition_affects_descriptor(old_options, options))
  1487. mark_my_descriptor_dirty("config change");
  1488. /* We may need to reschedule some directory stuff if our status changed. */
  1489. if (old_options) {
  1490. if (authdir_mode_v3(options) && !authdir_mode_v3(old_options))
  1491. dirvote_recalculate_timing(options, time(NULL));
  1492. if (!bool_eq(directory_fetches_dir_info_early(options),
  1493. directory_fetches_dir_info_early(old_options)) ||
  1494. !bool_eq(directory_fetches_dir_info_later(options),
  1495. directory_fetches_dir_info_later(old_options))) {
  1496. /* Make sure update_router_have_min_dir_info gets called. */
  1497. router_dir_info_changed();
  1498. /* We might need to download a new consensus status later or sooner than
  1499. * we had expected. */
  1500. update_consensus_networkstatus_fetch_time(time(NULL));
  1501. }
  1502. }
  1503. /* Load the webpage we're going to serve every time someone asks for '/' on
  1504. our DirPort. */
  1505. tor_free(global_dirfrontpagecontents);
  1506. if (options->DirPortFrontPage) {
  1507. global_dirfrontpagecontents =
  1508. read_file_to_str(options->DirPortFrontPage, 0, NULL);
  1509. if (!global_dirfrontpagecontents) {
  1510. log_warn(LD_CONFIG,
  1511. "DirPortFrontPage file '%s' not found. Continuing anyway.",
  1512. options->DirPortFrontPage);
  1513. }
  1514. }
  1515. return 0;
  1516. }
  1517. /*
  1518. * Functions to parse config options
  1519. */
  1520. /** If <b>option</b> is an official abbreviation for a longer option,
  1521. * return the longer option. Otherwise return <b>option</b>.
  1522. * If <b>command_line</b> is set, apply all abbreviations. Otherwise, only
  1523. * apply abbreviations that work for the config file and the command line.
  1524. * If <b>warn_obsolete</b> is set, warn about deprecated names. */
  1525. static const char *
  1526. expand_abbrev(const config_format_t *fmt, const char *option, int command_line,
  1527. int warn_obsolete)
  1528. {
  1529. int i;
  1530. if (! fmt->abbrevs)
  1531. return option;
  1532. for (i=0; fmt->abbrevs[i].abbreviated; ++i) {
  1533. /* Abbreviations are case insensitive. */
  1534. if (!strcasecmp(option,fmt->abbrevs[i].abbreviated) &&
  1535. (command_line || !fmt->abbrevs[i].commandline_only)) {
  1536. if (warn_obsolete && fmt->abbrevs[i].warn) {
  1537. log_warn(LD_CONFIG,
  1538. "The configuration option '%s' is deprecated; "
  1539. "use '%s' instead.",
  1540. fmt->abbrevs[i].abbreviated,
  1541. fmt->abbrevs[i].full);
  1542. }
  1543. /* Keep going through the list in case we want to rewrite it more.
  1544. * (We could imagine recursing here, but I don't want to get the
  1545. * user into an infinite loop if we craft our list wrong.) */
  1546. option = fmt->abbrevs[i].full;
  1547. }
  1548. }
  1549. return option;
  1550. }
  1551. /** Helper: Read a list of configuration options from the command line.
  1552. * If successful, put them in *<b>result</b> and return 0, and return
  1553. * -1 and leave *<b>result</b> alone. */
  1554. static int
  1555. config_get_commandlines(int argc, char **argv, config_line_t **result)
  1556. {
  1557. config_line_t *front = NULL;
  1558. config_line_t **new = &front;
  1559. char *s;
  1560. int i = 1;
  1561. while (i < argc) {
  1562. if (!strcmp(argv[i],"-f") ||
  1563. !strcmp(argv[i],"--hash-password")) {
  1564. i += 2; /* command-line option with argument. ignore them. */
  1565. continue;
  1566. } else if (!strcmp(argv[i],"--list-fingerprint") ||
  1567. !strcmp(argv[i],"--verify-config") ||
  1568. !strcmp(argv[i],"--ignore-missing-torrc") ||
  1569. !strcmp(argv[i],"--quiet") ||
  1570. !strcmp(argv[i],"--hush")) {
  1571. i += 1; /* command-line option. ignore it. */
  1572. continue;
  1573. } else if (!strcmp(argv[i],"--nt-service") ||
  1574. !strcmp(argv[i],"-nt-service")) {
  1575. i += 1;
  1576. continue;
  1577. }
  1578. if (i == argc-1) {
  1579. log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
  1580. argv[i]);
  1581. config_free_lines(front);
  1582. return -1;
  1583. }
  1584. *new = tor_malloc_zero(sizeof(config_line_t));
  1585. s = argv[i];
  1586. /* Each keyword may be prefixed with one or two dashes. */
  1587. if (*s == '-')
  1588. s++;
  1589. if (*s == '-')
  1590. s++;
  1591. (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
  1592. (*new)->value = tor_strdup(argv[i+1]);
  1593. (*new)->next = NULL;
  1594. log(LOG_DEBUG, LD_CONFIG, "command line: parsed keyword '%s', value '%s'",
  1595. (*new)->key, (*new)->value);
  1596. new = &((*new)->next);
  1597. i += 2;
  1598. }
  1599. *result = front;
  1600. return 0;
  1601. }
  1602. /** Helper: allocate a new configuration option mapping 'key' to 'val',
  1603. * append it to *<b>lst</b>. */
  1604. static void
  1605. config_line_append(config_line_t **lst,
  1606. const char *key,
  1607. const char *val)
  1608. {
  1609. config_line_t *newline;
  1610. newline = tor_malloc(sizeof(config_line_t));
  1611. newline->key = tor_strdup(key);
  1612. newline->value = tor_strdup(val);
  1613. newline->next = NULL;
  1614. while (*lst)
  1615. lst = &((*lst)->next);
  1616. (*lst) = newline;
  1617. }
  1618. /** Helper: parse the config string and strdup into key/value
  1619. * strings. Set *result to the list, or NULL if parsing the string
  1620. * failed. Return 0 on success, -1 on failure. Warn and ignore any
  1621. * misformatted lines. */
  1622. int
  1623. config_get_lines(const char *string, config_line_t **result)
  1624. {
  1625. config_line_t *list = NULL, **next;
  1626. char *k, *v;
  1627. next = &list;
  1628. do {
  1629. k = v = NULL;
  1630. string = parse_config_line_from_str(string, &k, &v);
  1631. if (!string) {
  1632. config_free_lines(list);
  1633. tor_free(k);
  1634. tor_free(v);
  1635. return -1;
  1636. }
  1637. if (k && v) {
  1638. /* This list can get long, so we keep a pointer to the end of it
  1639. * rather than using config_line_append over and over and getting
  1640. * n^2 performance. */
  1641. *next = tor_malloc(sizeof(config_line_t));
  1642. (*next)->key = k;
  1643. (*next)->value = v;
  1644. (*next)->next = NULL;
  1645. next = &((*next)->next);
  1646. } else {
  1647. tor_free(k);
  1648. tor_free(v);
  1649. }
  1650. } while (*string);
  1651. *result = list;
  1652. return 0;
  1653. }
  1654. /**
  1655. * Free all the configuration lines on the linked list <b>front</b>.
  1656. */
  1657. void
  1658. config_free_lines(config_line_t *front)
  1659. {
  1660. config_line_t *tmp;
  1661. while (front) {
  1662. tmp = front;
  1663. front = tmp->next;
  1664. tor_free(tmp->key);
  1665. tor_free(tmp->value);
  1666. tor_free(tmp);
  1667. }
  1668. }
  1669. /** As config_find_option, but return a non-const pointer. */
  1670. static config_var_t *
  1671. config_find_option_mutable(config_format_t *fmt, const char *key)
  1672. {
  1673. int i;
  1674. size_t keylen = strlen(key);
  1675. if (!keylen)
  1676. return NULL; /* if they say "--" on the command line, it's not an option */
  1677. /* First, check for an exact (case-insensitive) match */
  1678. for (i=0; fmt->vars[i].name; ++i) {
  1679. if (!strcasecmp(key, fmt->vars[i].name)) {
  1680. return &fmt->vars[i];
  1681. }
  1682. }
  1683. /* If none, check for an abbreviated match */
  1684. for (i=0; fmt->vars[i].name; ++i) {
  1685. if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
  1686. log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
  1687. "Please use '%s' instead",
  1688. key, fmt->vars[i].name);
  1689. return &fmt->vars[i];
  1690. }
  1691. }
  1692. /* Okay, unrecognized option */
  1693. return NULL;
  1694. }
  1695. /** If <b>key</b> is a configuration option, return the corresponding const
  1696. * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
  1697. * warn, and return the corresponding const config_var_t. Otherwise return
  1698. * NULL.
  1699. */
  1700. static const config_var_t *
  1701. config_find_option(const config_format_t *fmt, const char *key)
  1702. {
  1703. return config_find_option_mutable((config_format_t*)fmt, key);
  1704. }
  1705. /** Return the number of option entries in <b>fmt</b>. */
  1706. static int
  1707. config_count_options(const config_format_t *fmt)
  1708. {
  1709. int i;
  1710. for (i=0; fmt->vars[i].name; ++i)
  1711. ;
  1712. return i;
  1713. }
  1714. /*
  1715. * Functions to assign config options.
  1716. */
  1717. /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
  1718. * with <b>c</b>-\>value and return 0, or return -1 if bad value.
  1719. *
  1720. * Called from config_assign_line() and option_reset().
  1721. */
  1722. static int
  1723. config_assign_value(const config_format_t *fmt, or_options_t *options,
  1724. config_line_t *c, char **msg)
  1725. {
  1726. int i, ok;
  1727. const config_var_t *var;
  1728. void *lvalue;
  1729. CHECK(fmt, options);
  1730. var = config_find_option(fmt, c->key);
  1731. tor_assert(var);
  1732. lvalue = STRUCT_VAR_P(options, var->var_offset);
  1733. switch (var->type) {
  1734. case CONFIG_TYPE_PORT:
  1735. if (!strcasecmp(c->value, "auto")) {
  1736. *(int *)lvalue = CFG_AUTO_PORT;
  1737. break;
  1738. }
  1739. /* fall through */
  1740. case CONFIG_TYPE_UINT:
  1741. i = (int)tor_parse_long(c->value, 10, 0,
  1742. var->type==CONFIG_TYPE_PORT ? 65535 : INT_MAX,
  1743. &ok, NULL);
  1744. if (!ok) {
  1745. tor_asprintf(msg,
  1746. "Int keyword '%s %s' is malformed or out of bounds.",
  1747. c->key, c->value);
  1748. return -1;
  1749. }
  1750. *(int *)lvalue = i;
  1751. break;
  1752. case CONFIG_TYPE_INTERVAL: {
  1753. i = config_parse_interval(c->value, &ok);
  1754. if (!ok) {
  1755. tor_asprintf(msg,
  1756. "Interval '%s %s' is malformed or out of bounds.",
  1757. c->key, c->value);
  1758. return -1;
  1759. }
  1760. *(int *)lvalue = i;
  1761. break;
  1762. }
  1763. case CONFIG_TYPE_MSEC_INTERVAL: {
  1764. i = config_parse_msec_interval(c->value, &ok);
  1765. if (!ok) {
  1766. tor_asprintf(msg,
  1767. "Msec interval '%s %s' is malformed or out of bounds.",
  1768. c->key, c->value);
  1769. return -1;
  1770. }
  1771. *(int *)lvalue = i;
  1772. break;
  1773. }
  1774. case CONFIG_TYPE_MEMUNIT: {
  1775. uint64_t u64 = config_parse_memunit(c->value, &ok);
  1776. if (!ok) {
  1777. tor_asprintf(msg,
  1778. "Value '%s %s' is malformed or out of bounds.",
  1779. c->key, c->value);
  1780. return -1;
  1781. }
  1782. *(uint64_t *)lvalue = u64;
  1783. break;
  1784. }
  1785. case CONFIG_TYPE_BOOL:
  1786. i = (int)tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
  1787. if (!ok) {
  1788. tor_asprintf(msg,
  1789. "Boolean '%s %s' expects 0 or 1.",
  1790. c->key, c->value);
  1791. return -1;
  1792. }
  1793. *(int *)lvalue = i;
  1794. break;
  1795. case CONFIG_TYPE_AUTOBOOL:
  1796. if (!strcmp(c->value, "auto"))
  1797. *(int *)lvalue = -1;
  1798. else if (!strcmp(c->value, "0"))
  1799. *(int *)lvalue = 0;
  1800. else if (!strcmp(c->value, "1"))
  1801. *(int *)lvalue = 1;
  1802. else {
  1803. tor_asprintf(msg, "Boolean '%s %s' expects 0, 1, or 'auto'.",
  1804. c->key, c->value);
  1805. return -1;
  1806. }
  1807. break;
  1808. case CONFIG_TYPE_STRING:
  1809. case CONFIG_TYPE_FILENAME:
  1810. tor_free(*(char **)lvalue);
  1811. *(char **)lvalue = tor_strdup(c->value);
  1812. break;
  1813. case CONFIG_TYPE_DOUBLE:
  1814. *(double *)lvalue = atof(c->value);
  1815. break;
  1816. case CONFIG_TYPE_ISOTIME:
  1817. if (parse_iso_time(c->value, (time_t *)lvalue)) {
  1818. tor_asprintf(msg,
  1819. "Invalid time '%s' for keyword '%s'", c->value, c->key);
  1820. return -1;
  1821. }
  1822. break;
  1823. case CONFIG_TYPE_ROUTERSET:
  1824. if (*(routerset_t**)lvalue) {
  1825. routerset_free(*(routerset_t**)lvalue);
  1826. }
  1827. *(routerset_t**)lvalue = routerset_new();
  1828. if (routerset_parse(*(routerset_t**)lvalue, c->value, c->key)<0) {
  1829. tor_asprintf(msg, "Invalid exit list '%s' for option '%s'",
  1830. c->value, c->key);
  1831. return -1;
  1832. }
  1833. break;
  1834. case CONFIG_TYPE_CSV:
  1835. if (*(smartlist_t**)lvalue) {
  1836. SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
  1837. smartlist_clear(*(smartlist_t**)lvalue);
  1838. } else {
  1839. *(smartlist_t**)lvalue = smartlist_create();
  1840. }
  1841. smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
  1842. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1843. break;
  1844. case CONFIG_TYPE_LINELIST:
  1845. case CONFIG_TYPE_LINELIST_S:
  1846. config_line_append((config_line_t**)lvalue, c->key, c->value);
  1847. break;
  1848. case CONFIG_TYPE_OBSOLETE:
  1849. log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
  1850. break;
  1851. case CONFIG_TYPE_LINELIST_V:
  1852. tor_asprintf(msg,
  1853. "You may not provide a value for virtual option '%s'", c->key);
  1854. return -1;
  1855. default:
  1856. tor_assert(0);
  1857. break;
  1858. }
  1859. return 0;
  1860. }
  1861. /** If <b>c</b> is a syntactically valid configuration line, update
  1862. * <b>options</b> with its value and return 0. Otherwise return -1 for bad
  1863. * key, -2 for bad value.
  1864. *
  1865. * If <b>clear_first</b> is set, clear the value first. Then if
  1866. * <b>use_defaults</b> is set, set the value to the default.
  1867. *
  1868. * Called from config_assign().
  1869. */
  1870. static int
  1871. config_assign_line(const config_format_t *fmt, or_options_t *options,
  1872. config_line_t *c, int use_defaults,
  1873. int clear_first, bitarray_t *options_seen, char **msg)
  1874. {
  1875. const config_var_t *var;
  1876. CHECK(fmt, options);
  1877. var = config_find_option(fmt, c->key);
  1878. if (!var) {
  1879. if (fmt->extra) {
  1880. void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
  1881. log_info(LD_CONFIG,
  1882. "Found unrecognized option '%s'; saving it.", c->key);
  1883. config_line_append((config_line_t**)lvalue, c->key, c->value);
  1884. return 0;
  1885. } else {
  1886. tor_asprintf(msg,
  1887. "Unknown option '%s'. Failing.", c->key);
  1888. return -1;
  1889. }
  1890. }
  1891. /* Put keyword into canonical case. */
  1892. if (strcmp(var->name, c->key)) {
  1893. tor_free(c->key);
  1894. c->key = tor_strdup(var->name);
  1895. }
  1896. if (!strlen(c->value)) {
  1897. /* reset or clear it, then return */
  1898. if (!clear_first) {
  1899. if (var->type == CONFIG_TYPE_LINELIST ||
  1900. var->type == CONFIG_TYPE_LINELIST_S) {
  1901. /* We got an empty linelist from the torrc or command line.
  1902. As a special case, call this an error. Warn and ignore. */
  1903. log_warn(LD_CONFIG,
  1904. "Linelist option '%s' has no value. Skipping.", c->key);
  1905. } else { /* not already cleared */
  1906. option_reset(fmt, options, var, use_defaults);
  1907. }
  1908. }
  1909. return 0;
  1910. }
  1911. if (options_seen && (var->type != CONFIG_TYPE_LINELIST &&
  1912. var->type != CONFIG_TYPE_LINELIST_S)) {
  1913. /* We're tracking which options we've seen, and this option is not
  1914. * supposed to occur more than once. */
  1915. int var_index = (int)(var - fmt->vars);
  1916. if (bitarray_is_set(options_seen, var_index)) {
  1917. log_warn(LD_CONFIG, "Option '%s' used more than once; all but the last "
  1918. "value will be ignored.", var->name);
  1919. }
  1920. bitarray_set(options_seen, var_index);
  1921. }
  1922. if (config_assign_value(fmt, options, c, msg) < 0)
  1923. return -2;
  1924. return 0;
  1925. }
  1926. /** Restore the option named <b>key</b> in options to its default value.
  1927. * Called from config_assign(). */
  1928. static void
  1929. config_reset_line(const config_format_t *fmt, or_options_t *options,
  1930. const char *key, int use_defaults)
  1931. {
  1932. const config_var_t *var;
  1933. CHECK(fmt, options);
  1934. var = config_find_option(fmt, key);
  1935. if (!var)
  1936. return; /* give error on next pass. */
  1937. option_reset(fmt, options, var, use_defaults);
  1938. }
  1939. /** Return true iff key is a valid configuration option. */
  1940. int
  1941. option_is_recognized(const char *key)
  1942. {
  1943. const config_var_t *var = config_find_option(&options_format, key);
  1944. return (var != NULL);
  1945. }
  1946. /** Return the canonical name of a configuration option, or NULL
  1947. * if no such option exists. */
  1948. const char *
  1949. option_get_canonical_name(const char *key)
  1950. {
  1951. const config_var_t *var = config_find_option(&options_format, key);
  1952. return var ? var->name : NULL;
  1953. }
  1954. /** Return a canonical list of the options assigned for key.
  1955. */
  1956. config_line_t *
  1957. option_get_assignment(const or_options_t *options, const char *key)
  1958. {
  1959. return get_assigned_option(&options_format, options, key, 1);
  1960. }
  1961. /** Return true iff value needs to be quoted and escaped to be used in
  1962. * a configuration file. */
  1963. static int
  1964. config_value_needs_escape(const char *value)
  1965. {
  1966. if (*value == '\"')
  1967. return 1;
  1968. while (*value) {
  1969. switch (*value)
  1970. {
  1971. case '\r':
  1972. case '\n':
  1973. case '#':
  1974. /* Note: quotes and backspaces need special handling when we are using
  1975. * quotes, not otherwise, so they don't trigger escaping on their
  1976. * own. */
  1977. return 1;
  1978. default:
  1979. if (!TOR_ISPRINT(*value))
  1980. return 1;
  1981. }
  1982. ++value;
  1983. }
  1984. return 0;
  1985. }
  1986. /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
  1987. static config_line_t *
  1988. config_lines_dup(const config_line_t *inp)
  1989. {
  1990. config_line_t *result = NULL;
  1991. config_line_t **next_out = &result;
  1992. while (inp) {
  1993. *next_out = tor_malloc(sizeof(config_line_t));
  1994. (*next_out)->key = tor_strdup(inp->key);
  1995. (*next_out)->value = tor_strdup(inp->value);
  1996. inp = inp->next;
  1997. next_out = &((*next_out)->next);
  1998. }
  1999. (*next_out) = NULL;
  2000. return result;
  2001. }
  2002. /** Return newly allocated line or lines corresponding to <b>key</b> in the
  2003. * configuration <b>options</b>. If <b>escape_val</b> is true and a
  2004. * value needs to be quoted before it's put in a config file, quote and
  2005. * escape that value. Return NULL if no such key exists. */
  2006. static config_line_t *
  2007. get_assigned_option(const config_format_t *fmt, const void *options,
  2008. const char *key, int escape_val)
  2009. {
  2010. const config_var_t *var;
  2011. const void *value;
  2012. config_line_t *result;
  2013. tor_assert(options && key);
  2014. CHECK(fmt, options);
  2015. var = config_find_option(fmt, key);
  2016. if (!var) {
  2017. log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
  2018. return NULL;
  2019. }
  2020. value = STRUCT_VAR_P(options, var->var_offset);
  2021. result = tor_malloc_zero(sizeof(config_line_t));
  2022. result->key = tor_strdup(var->name);
  2023. switch (var->type)
  2024. {
  2025. case CONFIG_TYPE_STRING:
  2026. case CONFIG_TYPE_FILENAME:
  2027. if (*(char**)value) {
  2028. result->value = tor_strdup(*(char**)value);
  2029. } else {
  2030. tor_free(result->key);
  2031. tor_free(result);
  2032. return NULL;
  2033. }
  2034. break;
  2035. case CONFIG_TYPE_ISOTIME:
  2036. if (*(time_t*)value) {
  2037. result->value = tor_malloc(ISO_TIME_LEN+1);
  2038. format_iso_time(result->value, *(time_t*)value);
  2039. } else {
  2040. tor_free(result->key);
  2041. tor_free(result);
  2042. }
  2043. escape_val = 0; /* Can't need escape. */
  2044. break;
  2045. case CONFIG_TYPE_PORT:
  2046. if (*(int*)value == CFG_AUTO_PORT) {
  2047. result->value = tor_strdup("auto");
  2048. escape_val = 0;
  2049. break;
  2050. }
  2051. /* fall through */
  2052. case CONFIG_TYPE_INTERVAL:
  2053. case CONFIG_TYPE_MSEC_INTERVAL:
  2054. case CONFIG_TYPE_UINT:
  2055. /* This means every or_options_t uint or bool element
  2056. * needs to be an int. Not, say, a uint16_t or char. */
  2057. tor_asprintf(&result->value, "%d", *(int*)value);
  2058. escape_val = 0; /* Can't need escape. */
  2059. break;
  2060. case CONFIG_TYPE_MEMUNIT:
  2061. tor_asprintf(&result->value, U64_FORMAT,
  2062. U64_PRINTF_ARG(*(uint64_t*)value));
  2063. escape_val = 0; /* Can't need escape. */
  2064. break;
  2065. case CONFIG_TYPE_DOUBLE:
  2066. tor_asprintf(&result->value, "%f", *(double*)value);
  2067. escape_val = 0; /* Can't need escape. */
  2068. break;
  2069. case CONFIG_TYPE_AUTOBOOL:
  2070. if (*(int*)value == -1) {
  2071. result->value = tor_strdup("auto");
  2072. escape_val = 0;
  2073. break;
  2074. }
  2075. /* fall through */
  2076. case CONFIG_TYPE_BOOL:
  2077. result->value = tor_strdup(*(int*)value ? "1" : "0");
  2078. escape_val = 0; /* Can't need escape. */
  2079. break;
  2080. case CONFIG_TYPE_ROUTERSET:
  2081. result->value = routerset_to_string(*(routerset_t**)value);
  2082. break;
  2083. case CONFIG_TYPE_CSV:
  2084. if (*(smartlist_t**)value)
  2085. result->value =
  2086. smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
  2087. else
  2088. result->value = tor_strdup("");
  2089. break;
  2090. case CONFIG_TYPE_OBSOLETE:
  2091. log_fn(LOG_PROTOCOL_WARN, LD_CONFIG,
  2092. "You asked me for the value of an obsolete config option '%s'.",
  2093. key);
  2094. tor_free(result->key);
  2095. tor_free(result);
  2096. return NULL;
  2097. case CONFIG_TYPE_LINELIST_S:
  2098. log_warn(LD_CONFIG,
  2099. "Can't return context-sensitive '%s' on its own", key);
  2100. tor_free(result->key);
  2101. tor_free(result);
  2102. return NULL;
  2103. case CONFIG_TYPE_LINELIST:
  2104. case CONFIG_TYPE_LINELIST_V:
  2105. tor_free(result->key);
  2106. tor_free(result);
  2107. result = config_lines_dup(*(const config_line_t**)value);
  2108. break;
  2109. default:
  2110. tor_free(result->key);
  2111. tor_free(result);
  2112. log_warn(LD_BUG,"Unknown type %d for known key '%s'",
  2113. var->type, key);
  2114. return NULL;
  2115. }
  2116. if (escape_val) {
  2117. config_line_t *line;
  2118. for (line = result; line; line = line->next) {
  2119. if (line->value && config_value_needs_escape(line->value)) {
  2120. char *newval = esc_for_log(line->value);
  2121. tor_free(line->value);
  2122. line->value = newval;
  2123. }
  2124. }
  2125. }
  2126. return result;
  2127. }
  2128. /** Iterate through the linked list of requested options <b>list</b>.
  2129. * For each item, convert as appropriate and assign to <b>options</b>.
  2130. * If an item is unrecognized, set *msg and return -1 immediately,
  2131. * else return 0 for success.
  2132. *
  2133. * If <b>clear_first</b>, interpret config options as replacing (not
  2134. * extending) their previous values. If <b>clear_first</b> is set,
  2135. * then <b>use_defaults</b> to decide if you set to defaults after
  2136. * clearing, or make the value 0 or NULL.
  2137. *
  2138. * Here are the use cases:
  2139. * 1. A non-empty AllowInvalid line in your torrc. Appends to current
  2140. * if linelist, replaces current if csv.
  2141. * 2. An empty AllowInvalid line in your torrc. Should clear it.
  2142. * 3. "RESETCONF AllowInvalid" sets it to default.
  2143. * 4. "SETCONF AllowInvalid" makes it NULL.
  2144. * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
  2145. *
  2146. * Use_defaults Clear_first
  2147. * 0 0 "append"
  2148. * 1 0 undefined, don't use
  2149. * 0 1 "set to null first"
  2150. * 1 1 "set to defaults first"
  2151. * Return 0 on success, -1 on bad key, -2 on bad value.
  2152. *
  2153. * As an additional special case, if a LINELIST config option has
  2154. * no value and clear_first is 0, then warn and ignore it.
  2155. */
  2156. /*
  2157. There are three call cases for config_assign() currently.
  2158. Case one: Torrc entry
  2159. options_init_from_torrc() calls config_assign(0, 0)
  2160. calls config_assign_line(0, 0).
  2161. if value is empty, calls option_reset(0) and returns.
  2162. calls config_assign_value(), appends.
  2163. Case two: setconf
  2164. options_trial_assign() calls config_assign(0, 1)
  2165. calls config_reset_line(0)
  2166. calls option_reset(0)
  2167. calls option_clear().
  2168. calls config_assign_line(0, 1).
  2169. if value is empty, returns.
  2170. calls config_assign_value(), appends.
  2171. Case three: resetconf
  2172. options_trial_assign() calls config_assign(1, 1)
  2173. calls config_reset_line(1)
  2174. calls option_reset(1)
  2175. calls option_clear().
  2176. calls config_assign_value(default)
  2177. calls config_assign_line(1, 1).
  2178. returns.
  2179. */
  2180. static int
  2181. config_assign(const config_format_t *fmt, void *options, config_line_t *list,
  2182. int use_defaults, int clear_first, char **msg)
  2183. {
  2184. config_line_t *p;
  2185. bitarray_t *options_seen;
  2186. const int n_options = config_count_options(fmt);
  2187. CHECK(fmt, options);
  2188. /* pass 1: normalize keys */
  2189. for (p = list; p; p = p->next) {
  2190. const char *full = expand_abbrev(fmt, p->key, 0, 1);
  2191. if (strcmp(full,p->key)) {
  2192. tor_free(p->key);
  2193. p->key = tor_strdup(full);
  2194. }
  2195. }
  2196. /* pass 2: if we're reading from a resetting source, clear all
  2197. * mentioned config options, and maybe set to their defaults. */
  2198. if (clear_first) {
  2199. for (p = list; p; p = p->next)
  2200. config_reset_line(fmt, options, p->key, use_defaults);
  2201. }
  2202. options_seen = bitarray_init_zero(n_options);
  2203. /* pass 3: assign. */
  2204. while (list) {
  2205. int r;
  2206. if ((r=config_assign_line(fmt, options, list, use_defaults,
  2207. clear_first, options_seen, msg))) {
  2208. bitarray_free(options_seen);
  2209. return r;
  2210. }
  2211. list = list->next;
  2212. }
  2213. bitarray_free(options_seen);
  2214. return 0;
  2215. }
  2216. /** Try assigning <b>list</b> to the global options. You do this by duping
  2217. * options, assigning list to the new one, then validating it. If it's
  2218. * ok, then throw out the old one and stick with the new one. Else,
  2219. * revert to old and return failure. Return SETOPT_OK on success, or
  2220. * a setopt_err_t on failure.
  2221. *
  2222. * If not success, point *<b>msg</b> to a newly allocated string describing
  2223. * what went wrong.
  2224. */
  2225. setopt_err_t
  2226. options_trial_assign(config_line_t *list, int use_defaults,
  2227. int clear_first, char **msg)
  2228. {
  2229. int r;
  2230. or_options_t *trial_options = options_dup(&options_format, get_options());
  2231. if ((r=config_assign(&options_format, trial_options,
  2232. list, use_defaults, clear_first, msg)) < 0) {
  2233. config_free(&options_format, trial_options);
  2234. return r;
  2235. }
  2236. if (options_validate(get_options_mutable(), trial_options, 1, msg) < 0) {
  2237. config_free(&options_format, trial_options);
  2238. return SETOPT_ERR_PARSE; /*XXX make this a separate return value. */
  2239. }
  2240. if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
  2241. config_free(&options_format, trial_options);
  2242. return SETOPT_ERR_TRANSITION;
  2243. }
  2244. if (set_options(trial_options, msg)<0) {
  2245. config_free(&options_format, trial_options);
  2246. return SETOPT_ERR_SETTING;
  2247. }
  2248. /* we liked it. put it in place. */
  2249. return SETOPT_OK;
  2250. }
  2251. /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
  2252. * Called from option_reset() and config_free(). */
  2253. static void
  2254. option_clear(const config_format_t *fmt, or_options_t *options,
  2255. const config_var_t *var)
  2256. {
  2257. void *lvalue = STRUCT_VAR_P(options, var->var_offset);
  2258. (void)fmt; /* unused */
  2259. switch (var->type) {
  2260. case CONFIG_TYPE_STRING:
  2261. case CONFIG_TYPE_FILENAME:
  2262. tor_free(*(char**)lvalue);
  2263. break;
  2264. case CONFIG_TYPE_DOUBLE:
  2265. *(double*)lvalue = 0.0;
  2266. break;
  2267. case CONFIG_TYPE_ISOTIME:
  2268. *(time_t*)lvalue = 0;
  2269. break;
  2270. case CONFIG_TYPE_INTERVAL:
  2271. case CONFIG_TYPE_MSEC_INTERVAL:
  2272. case CONFIG_TYPE_UINT:
  2273. case CONFIG_TYPE_PORT:
  2274. case CONFIG_TYPE_BOOL:
  2275. *(int*)lvalue = 0;
  2276. break;
  2277. case CONFIG_TYPE_AUTOBOOL:
  2278. *(int*)lvalue = -1;
  2279. break;
  2280. case CONFIG_TYPE_MEMUNIT:
  2281. *(uint64_t*)lvalue = 0;
  2282. break;
  2283. case CONFIG_TYPE_ROUTERSET:
  2284. if (*(routerset_t**)lvalue) {
  2285. routerset_free(*(routerset_t**)lvalue);
  2286. *(routerset_t**)lvalue = NULL;
  2287. }
  2288. break;
  2289. case CONFIG_TYPE_CSV:
  2290. if (*(smartlist_t**)lvalue) {
  2291. SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
  2292. smartlist_free(*(smartlist_t **)lvalue);
  2293. *(smartlist_t **)lvalue = NULL;
  2294. }
  2295. break;
  2296. case CONFIG_TYPE_LINELIST:
  2297. case CONFIG_TYPE_LINELIST_S:
  2298. config_free_lines(*(config_line_t **)lvalue);
  2299. *(config_line_t **)lvalue = NULL;
  2300. break;
  2301. case CONFIG_TYPE_LINELIST_V:
  2302. /* handled by linelist_s. */
  2303. break;
  2304. case CONFIG_TYPE_OBSOLETE:
  2305. break;
  2306. }
  2307. }
  2308. /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
  2309. * <b>use_defaults</b>, set it to its default value.
  2310. * Called by config_init() and option_reset_line() and option_assign_line(). */
  2311. static void
  2312. option_reset(const config_format_t *fmt, or_options_t *options,
  2313. const config_var_t *var, int use_defaults)
  2314. {
  2315. config_line_t *c;
  2316. char *msg = NULL;
  2317. CHECK(fmt, options);
  2318. option_clear(fmt, options, var); /* clear it first */
  2319. if (!use_defaults)
  2320. return; /* all done */
  2321. if (var->initvalue) {
  2322. c = tor_malloc_zero(sizeof(config_line_t));
  2323. c->key = tor_strdup(var->name);
  2324. c->value = tor_strdup(var->initvalue);
  2325. if (config_assign_value(fmt, options, c, &msg) < 0) {
  2326. log_warn(LD_BUG, "Failed to assign default: %s", msg);
  2327. tor_free(msg); /* if this happens it's a bug */
  2328. }
  2329. config_free_lines(c);
  2330. }
  2331. }
  2332. /** Print a usage message for tor. */
  2333. static void
  2334. print_usage(void)
  2335. {
  2336. printf(
  2337. "Copyright (c) 2001-2004, Roger Dingledine\n"
  2338. "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
  2339. "Copyright (c) 2007-2011, The Tor Project, Inc.\n\n"
  2340. "tor -f <torrc> [args]\n"
  2341. "See man page for options, or https://www.torproject.org/ for "
  2342. "documentation.\n");
  2343. }
  2344. /** Print all non-obsolete torrc options. */
  2345. static void
  2346. list_torrc_options(void)
  2347. {
  2348. int i;
  2349. smartlist_t *lines = smartlist_create();
  2350. for (i = 0; _option_vars[i].name; ++i) {
  2351. const config_var_t *var = &_option_vars[i];
  2352. if (var->type == CONFIG_TYPE_OBSOLETE ||
  2353. var->type == CONFIG_TYPE_LINELIST_V)
  2354. continue;
  2355. printf("%s\n", var->name);
  2356. }
  2357. smartlist_free(lines);
  2358. }
  2359. /** Last value actually set by resolve_my_address. */
  2360. static uint32_t last_resolved_addr = 0;
  2361. /**
  2362. * Based on <b>options-\>Address</b>, guess our public IP address and put it
  2363. * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
  2364. * set *<b>hostname_out</b> to a new string holding the hostname we used to
  2365. * get the address. Return 0 if all is well, or -1 if we can't find a suitable
  2366. * public IP address.
  2367. */
  2368. int
  2369. resolve_my_address(int warn_severity, const or_options_t *options,
  2370. uint32_t *addr_out, char **hostname_out)
  2371. {
  2372. struct in_addr in;
  2373. uint32_t addr; /* host order */
  2374. char hostname[256];
  2375. int explicit_ip=1;
  2376. int explicit_hostname=1;
  2377. int from_interface=0;
  2378. char *addr_string = NULL;
  2379. const char *address = options->Address;
  2380. int notice_severity = warn_severity <= LOG_NOTICE ?
  2381. LOG_NOTICE : warn_severity;
  2382. tor_assert(addr_out);
  2383. if (address && *address) {
  2384. strlcpy(hostname, address, sizeof(hostname));
  2385. } else { /* then we need to guess our address */
  2386. explicit_ip = 0; /* it's implicit */
  2387. explicit_hostname = 0; /* it's implicit */
  2388. if (gethostname(hostname, sizeof(hostname)) < 0) {
  2389. log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
  2390. return -1;
  2391. }
  2392. log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
  2393. }
  2394. /* now we know hostname. resolve it and keep only the IP address */
  2395. if (tor_inet_aton(hostname, &in) == 0) {
  2396. /* then we have to resolve it */
  2397. explicit_ip = 0;
  2398. if (tor_lookup_hostname(hostname, &addr)) { /* failed to resolve */
  2399. uint32_t interface_ip; /* host order */
  2400. if (explicit_hostname) {
  2401. log_fn(warn_severity, LD_CONFIG,
  2402. "Could not resolve local Address '%s'. Failing.", hostname);
  2403. return -1;
  2404. }
  2405. log_fn(notice_severity, LD_CONFIG,
  2406. "Could not resolve guessed local hostname '%s'. "
  2407. "Trying something else.", hostname);
  2408. if (get_interface_address(warn_severity, &interface_ip)) {
  2409. log_fn(warn_severity, LD_CONFIG,
  2410. "Could not get local interface IP address. Failing.");
  2411. return -1;
  2412. }
  2413. from_interface = 1;
  2414. addr = interface_ip;
  2415. log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
  2416. "local interface. Using that.", fmt_addr32(addr));
  2417. strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
  2418. } else { /* resolved hostname into addr */
  2419. if (!explicit_hostname &&
  2420. is_internal_IP(addr, 0)) {
  2421. uint32_t interface_ip;
  2422. log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
  2423. "resolves to a private IP address (%s). Trying something "
  2424. "else.", hostname, fmt_addr32(addr));
  2425. if (get_interface_address(warn_severity, &interface_ip)) {
  2426. log_fn(warn_severity, LD_CONFIG,
  2427. "Could not get local interface IP address. Too bad.");
  2428. } else if (is_internal_IP(interface_ip, 0)) {
  2429. log_fn(notice_severity, LD_CONFIG,
  2430. "Interface IP address '%s' is a private address too. "
  2431. "Ignoring.", fmt_addr32(interface_ip));
  2432. } else {
  2433. from_interface = 1;
  2434. addr = interface_ip;
  2435. log_fn(notice_severity, LD_CONFIG,
  2436. "Learned IP address '%s' for local interface."
  2437. " Using that.", fmt_addr32(addr));
  2438. strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
  2439. }
  2440. }
  2441. }
  2442. } else {
  2443. addr = ntohl(in.s_addr); /* set addr so that addr_string is not
  2444. * illformed */
  2445. }
  2446. addr_string = tor_dup_ip(addr);
  2447. if (is_internal_IP(addr, 0)) {
  2448. /* make sure we're ok with publishing an internal IP */
  2449. if (!options->DirServers && !options->AlternateDirAuthority) {
  2450. /* if they are using the default dirservers, disallow internal IPs
  2451. * always. */
  2452. log_fn(warn_severity, LD_CONFIG,
  2453. "Address '%s' resolves to private IP address '%s'. "
  2454. "Tor servers that use the default DirServers must have public "
  2455. "IP addresses.", hostname, addr_string);
  2456. tor_free(addr_string);
  2457. return -1;
  2458. }
  2459. if (!explicit_ip) {
  2460. /* even if they've set their own dirservers, require an explicit IP if
  2461. * they're using an internal address. */
  2462. log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
  2463. "IP address '%s'. Please set the Address config option to be "
  2464. "the IP address you want to use.", hostname, addr_string);
  2465. tor_free(addr_string);
  2466. return -1;
  2467. }
  2468. }
  2469. log_debug(LD_CONFIG, "Resolved Address to '%s'.", fmt_addr32(addr));
  2470. *addr_out = addr;
  2471. if (last_resolved_addr && last_resolved_addr != *addr_out) {
  2472. /* Leave this as a notice, regardless of the requested severity,
  2473. * at least until dynamic IP address support becomes bulletproof. */
  2474. log_notice(LD_NET,
  2475. "Your IP address seems to have changed to %s. Updating.",
  2476. addr_string);
  2477. ip_address_changed(0);
  2478. }
  2479. if (last_resolved_addr != *addr_out) {
  2480. const char *method;
  2481. const char *h = hostname;
  2482. if (explicit_ip) {
  2483. method = "CONFIGURED";
  2484. h = NULL;
  2485. } else if (explicit_hostname) {
  2486. method = "RESOLVED";
  2487. } else if (from_interface) {
  2488. method = "INTERFACE";
  2489. h = NULL;
  2490. } else {
  2491. method = "GETHOSTNAME";
  2492. }
  2493. control_event_server_status(LOG_NOTICE,
  2494. "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
  2495. addr_string, method, h?"HOSTNAME=":"", h);
  2496. }
  2497. last_resolved_addr = *addr_out;
  2498. if (hostname_out)
  2499. *hostname_out = tor_strdup(hostname);
  2500. tor_free(addr_string);
  2501. return 0;
  2502. }
  2503. /** Return true iff <b>addr</b> is judged to be on the same network as us, or
  2504. * on a private network.
  2505. */
  2506. int
  2507. is_local_addr(const tor_addr_t *addr)
  2508. {
  2509. if (tor_addr_is_internal(addr, 0))
  2510. return 1;
  2511. /* Check whether ip is on the same /24 as we are. */
  2512. if (get_options()->EnforceDistinctSubnets == 0)
  2513. return 0;
  2514. if (tor_addr_family(addr) == AF_INET) {
  2515. /*XXXX023 IP6 what corresponds to an /24? */
  2516. uint32_t ip = tor_addr_to_ipv4h(addr);
  2517. /* It's possible that this next check will hit before the first time
  2518. * resolve_my_address actually succeeds. (For clients, it is likely that
  2519. * resolve_my_address will never be called at all). In those cases,
  2520. * last_resolved_addr will be 0, and so checking to see whether ip is on
  2521. * the same /24 as last_resolved_addr will be the same as checking whether
  2522. * it was on net 0, which is already done by is_internal_IP.
  2523. */
  2524. if ((last_resolved_addr & (uint32_t)0xffffff00ul)
  2525. == (ip & (uint32_t)0xffffff00ul))
  2526. return 1;
  2527. }
  2528. return 0;
  2529. }
  2530. /** Release storage held by <b>options</b>. */
  2531. static void
  2532. config_free(const config_format_t *fmt, void *options)
  2533. {
  2534. int i;
  2535. if (!options)
  2536. return;
  2537. tor_assert(fmt);
  2538. for (i=0; fmt->vars[i].name; ++i)
  2539. option_clear(fmt, options, &(fmt->vars[i]));
  2540. if (fmt->extra) {
  2541. config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
  2542. config_free_lines(*linep);
  2543. *linep = NULL;
  2544. }
  2545. tor_free(options);
  2546. }
  2547. /** Return true iff a and b contain identical keys and values in identical
  2548. * order. */
  2549. static int
  2550. config_lines_eq(config_line_t *a, config_line_t *b)
  2551. {
  2552. while (a && b) {
  2553. if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
  2554. return 0;
  2555. a = a->next;
  2556. b = b->next;
  2557. }
  2558. if (a || b)
  2559. return 0;
  2560. return 1;
  2561. }
  2562. /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
  2563. * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
  2564. */
  2565. static int
  2566. option_is_same(const config_format_t *fmt,
  2567. const or_options_t *o1, const or_options_t *o2,
  2568. const char *name)
  2569. {
  2570. config_line_t *c1, *c2;
  2571. int r = 1;
  2572. CHECK(fmt, o1);
  2573. CHECK(fmt, o2);
  2574. c1 = get_assigned_option(fmt, o1, name, 0);
  2575. c2 = get_assigned_option(fmt, o2, name, 0);
  2576. r = config_lines_eq(c1, c2);
  2577. config_free_lines(c1);
  2578. config_free_lines(c2);
  2579. return r;
  2580. }
  2581. /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
  2582. static or_options_t *
  2583. options_dup(const config_format_t *fmt, const or_options_t *old)
  2584. {
  2585. or_options_t *newopts;
  2586. int i;
  2587. config_line_t *line;
  2588. newopts = config_alloc(fmt);
  2589. for (i=0; fmt->vars[i].name; ++i) {
  2590. if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
  2591. continue;
  2592. if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
  2593. continue;
  2594. line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
  2595. if (line) {
  2596. char *msg = NULL;
  2597. if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
  2598. log_err(LD_BUG, "Config_get_assigned_option() generated "
  2599. "something we couldn't config_assign(): %s", msg);
  2600. tor_free(msg);
  2601. tor_assert(0);
  2602. }
  2603. }
  2604. config_free_lines(line);
  2605. }
  2606. return newopts;
  2607. }
  2608. /** Return a new empty or_options_t. Used for testing. */
  2609. or_options_t *
  2610. options_new(void)
  2611. {
  2612. return config_alloc(&options_format);
  2613. }
  2614. /** Set <b>options</b> to hold reasonable defaults for most options.
  2615. * Each option defaults to zero. */
  2616. void
  2617. options_init(or_options_t *options)
  2618. {
  2619. config_init(&options_format, options);
  2620. }
  2621. /* Check if the port number given in <b>port_option</b> in combination with
  2622. * the specified port in <b>listen_options</b> will result in Tor actually
  2623. * opening a low port (meaning a port lower than 1024). Return 1 if
  2624. * it is, or 0 if it isn't or the concept of a low port isn't applicable for
  2625. * the platform we're on. */
  2626. static int
  2627. is_listening_on_low_port(int port_option,
  2628. const config_line_t *listen_options)
  2629. {
  2630. #ifdef MS_WINDOWS
  2631. (void) port_option;
  2632. (void) listen_options;
  2633. return 0; /* No port is too low for windows. */
  2634. #else
  2635. const config_line_t *l;
  2636. uint16_t p;
  2637. if (port_option == 0)
  2638. return 0; /* We're not listening */
  2639. if (listen_options == NULL)
  2640. return (port_option < 1024);
  2641. for (l = listen_options; l; l = l->next) {
  2642. addr_port_lookup(LOG_WARN, l->value, NULL, NULL, &p);
  2643. if (p<1024) {
  2644. return 1;
  2645. }
  2646. }
  2647. return 0;
  2648. #endif
  2649. }
  2650. /** Set all vars in the configuration object <b>options</b> to their default
  2651. * values. */
  2652. static void
  2653. config_init(const config_format_t *fmt, void *options)
  2654. {
  2655. int i;
  2656. const config_var_t *var;
  2657. CHECK(fmt, options);
  2658. for (i=0; fmt->vars[i].name; ++i) {
  2659. var = &fmt->vars[i];
  2660. if (!var->initvalue)
  2661. continue; /* defaults to NULL or 0 */
  2662. option_reset(fmt, options, var, 1);
  2663. }
  2664. }
  2665. /** Allocate and return a new string holding the written-out values of the vars
  2666. * in 'options'. If 'minimal', do not write out any default-valued vars.
  2667. * Else, if comment_defaults, write default values as comments.
  2668. */
  2669. static char *
  2670. config_dump(const config_format_t *fmt, const void *options, int minimal,
  2671. int comment_defaults)
  2672. {
  2673. smartlist_t *elements;
  2674. or_options_t *defaults;
  2675. config_line_t *line, *assigned;
  2676. char *result;
  2677. int i;
  2678. char *msg = NULL;
  2679. defaults = config_alloc(fmt);
  2680. config_init(fmt, defaults);
  2681. /* XXX use a 1 here so we don't add a new log line while dumping */
  2682. if (fmt->validate_fn(NULL,defaults, 1, &msg) < 0) {
  2683. log_err(LD_BUG, "Failed to validate default config.");
  2684. tor_free(msg);
  2685. tor_assert(0);
  2686. }
  2687. elements = smartlist_create();
  2688. for (i=0; fmt->vars[i].name; ++i) {
  2689. int comment_option = 0;
  2690. if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
  2691. fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
  2692. continue;
  2693. /* Don't save 'hidden' control variables. */
  2694. if (!strcmpstart(fmt->vars[i].name, "__"))
  2695. continue;
  2696. if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
  2697. continue;
  2698. else if (comment_defaults &&
  2699. option_is_same(fmt, options, defaults, fmt->vars[i].name))
  2700. comment_option = 1;
  2701. line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
  2702. for (; line; line = line->next) {
  2703. char *tmp;
  2704. tor_asprintf(&tmp, "%s%s %s\n",
  2705. comment_option ? "# " : "",
  2706. line->key, line->value);
  2707. smartlist_add(elements, tmp);
  2708. }
  2709. config_free_lines(assigned);
  2710. }
  2711. if (fmt->extra) {
  2712. line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
  2713. for (; line; line = line->next) {
  2714. char *tmp;
  2715. tor_asprintf(&tmp, "%s %s\n", line->key, line->value);
  2716. smartlist_add(elements, tmp);
  2717. }
  2718. }
  2719. result = smartlist_join_strings(elements, "", 0, NULL);
  2720. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  2721. smartlist_free(elements);
  2722. config_free(fmt, defaults);
  2723. return result;
  2724. }
  2725. /** Return a string containing a possible configuration file that would give
  2726. * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
  2727. * include options that are the same as Tor's defaults.
  2728. */
  2729. char *
  2730. options_dump(const or_options_t *options, int minimal)
  2731. {
  2732. return config_dump(&options_format, options, minimal, 0);
  2733. }
  2734. /** Return 0 if every element of sl is a string holding a decimal
  2735. * representation of a port number, or if sl is NULL.
  2736. * Otherwise set *msg and return -1. */
  2737. static int
  2738. validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
  2739. {
  2740. int i;
  2741. tor_assert(name);
  2742. if (!sl)
  2743. return 0;
  2744. SMARTLIST_FOREACH(sl, const char *, cp,
  2745. {
  2746. i = atoi(cp);
  2747. if (i < 1 || i > 65535) {
  2748. tor_asprintf(msg, "Port '%s' out of range in %s", cp, name);
  2749. return -1;
  2750. }
  2751. });
  2752. return 0;
  2753. }
  2754. /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
  2755. * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
  2756. * Else return 0.
  2757. */
  2758. static int
  2759. ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
  2760. {
  2761. if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
  2762. /* This handles an understandable special case where somebody says "2gb"
  2763. * whereas our actual maximum is 2gb-1 (INT_MAX) */
  2764. --*value;
  2765. }
  2766. if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
  2767. tor_asprintf(msg, "%s ("U64_FORMAT") must be at most %d",
  2768. desc, U64_PRINTF_ARG(*value),
  2769. ROUTER_MAX_DECLARED_BANDWIDTH);
  2770. return -1;
  2771. }
  2772. return 0;
  2773. }
  2774. /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
  2775. * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
  2776. * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
  2777. * Treat "0" as "".
  2778. * Return 0 on success or -1 if not a recognized authority type (in which
  2779. * case the value of _PublishServerDescriptor is undefined). */
  2780. static int
  2781. compute_publishserverdescriptor(or_options_t *options)
  2782. {
  2783. smartlist_t *list = options->PublishServerDescriptor;
  2784. dirinfo_type_t *auth = &options->_PublishServerDescriptor;
  2785. *auth = NO_DIRINFO;
  2786. if (!list) /* empty list, answer is none */
  2787. return 0;
  2788. SMARTLIST_FOREACH(list, const char *, string, {
  2789. if (!strcasecmp(string, "v1"))
  2790. *auth |= V1_DIRINFO;
  2791. else if (!strcmp(string, "1"))
  2792. if (options->BridgeRelay)
  2793. *auth |= BRIDGE_DIRINFO;
  2794. else
  2795. *auth |= V2_DIRINFO | V3_DIRINFO;
  2796. else if (!strcasecmp(string, "v2"))
  2797. *auth |= V2_DIRINFO;
  2798. else if (!strcasecmp(string, "v3"))
  2799. *auth |= V3_DIRINFO;
  2800. else if (!strcasecmp(string, "bridge"))
  2801. *auth |= BRIDGE_DIRINFO;
  2802. else if (!strcasecmp(string, "hidserv"))
  2803. log_warn(LD_CONFIG,
  2804. "PublishServerDescriptor hidserv is invalid. See "
  2805. "PublishHidServDescriptors.");
  2806. else if (!strcasecmp(string, "") || !strcmp(string, "0"))
  2807. /* no authority */;
  2808. else
  2809. return -1;
  2810. });
  2811. return 0;
  2812. }
  2813. /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
  2814. * services can overload the directory system. */
  2815. #define MIN_REND_POST_PERIOD (10*60)
  2816. /** Highest allowable value for RendPostPeriod. */
  2817. #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
  2818. /** Lowest allowable value for MaxCircuitDirtiness; if this is too low, Tor
  2819. * will generate too many circuits and potentially overload the network. */
  2820. #define MIN_MAX_CIRCUIT_DIRTINESS 10
  2821. /** Lowest allowable value for CircuitStreamTimeout; if this is too low, Tor
  2822. * will generate too many circuits and potentially overload the network. */
  2823. #define MIN_CIRCUIT_STREAM_TIMEOUT 10
  2824. /** Lowest allowable value for HeartbeatPeriod; if this is too low, we might
  2825. * expose more information than we're comfortable with. */
  2826. #define MIN_HEARTBEAT_PERIOD (30*60)
  2827. /** Return 0 if every setting in <b>options</b> is reasonable, and a
  2828. * permissible transition from <b>old_options</b>. Else return -1.
  2829. * Should have no side effects, except for normalizing the contents of
  2830. * <b>options</b>.
  2831. *
  2832. * On error, tor_strdup an error explanation into *<b>msg</b>.
  2833. *
  2834. * XXX
  2835. * If <b>from_setconf</b>, we were called by the controller, and our
  2836. * Log line should stay empty. If it's 0, then give us a default log
  2837. * if there are no logs defined.
  2838. */
  2839. static int
  2840. options_validate(or_options_t *old_options, or_options_t *options,
  2841. int from_setconf, char **msg)
  2842. {
  2843. int i;
  2844. config_line_t *cl;
  2845. const char *uname = get_uname();
  2846. int n_client_ports=0;
  2847. #define REJECT(arg) \
  2848. STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
  2849. #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
  2850. tor_assert(msg);
  2851. *msg = NULL;
  2852. if (server_mode(options) &&
  2853. (!strcmpstart(uname, "Windows 95") ||
  2854. !strcmpstart(uname, "Windows 98") ||
  2855. !strcmpstart(uname, "Windows Me"))) {
  2856. log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
  2857. "running %s; this probably won't work. See "
  2858. "https://wiki.torproject.org/TheOnionRouter/TorFAQ#ServerOS "
  2859. "for details.", uname);
  2860. }
  2861. if (options->ORPort == 0 && options->ORListenAddress != NULL)
  2862. REJECT("ORPort must be defined if ORListenAddress is defined.");
  2863. if (options->DirPort == 0 && options->DirListenAddress != NULL)
  2864. REJECT("DirPort must be defined if DirListenAddress is defined.");
  2865. if (parse_client_ports(options, 1, msg, &n_client_ports) < 0)
  2866. return -1;
  2867. if (validate_data_directory(options)<0)
  2868. REJECT("Invalid DataDirectory");
  2869. if (options->Nickname == NULL) {
  2870. if (server_mode(options)) {
  2871. options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
  2872. }
  2873. } else {
  2874. if (!is_legal_nickname(options->Nickname)) {
  2875. tor_asprintf(msg,
  2876. "Nickname '%s' is wrong length or contains illegal characters.",
  2877. options->Nickname);
  2878. return -1;
  2879. }
  2880. }
  2881. if (server_mode(options) && !options->ContactInfo)
  2882. log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
  2883. "Please consider setting it, so we can contact you if your server is "
  2884. "misconfigured or something else goes wrong.");
  2885. /* Special case on first boot if no Log options are given. */
  2886. if (!options->Logs && !options->RunAsDaemon && !from_setconf) {
  2887. if (quiet_level == 0)
  2888. config_line_append(&options->Logs, "Log", "notice stdout");
  2889. else if (quiet_level == 1)
  2890. config_line_append(&options->Logs, "Log", "warn stdout");
  2891. }
  2892. if (options_init_logs(options, 1)<0) /* Validate the log(s) */
  2893. REJECT("Failed to validate Log options. See logs for details.");
  2894. if (authdir_mode(options)) {
  2895. /* confirm that our address isn't broken, so we can complain now */
  2896. uint32_t tmp;
  2897. if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
  2898. REJECT("Failed to resolve/guess local address. See logs for details.");
  2899. }
  2900. #ifndef MS_WINDOWS
  2901. if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
  2902. REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
  2903. #endif
  2904. if (n_client_ports == 0 && options->ORPort == 0 && !options->RendConfigLines)
  2905. log(LOG_WARN, LD_CONFIG,
  2906. "SocksPort, TransPort, NATDPort, DNSPort, and ORPort are all "
  2907. "undefined, and there aren't any hidden services configured. "
  2908. "Tor will still run, but probably won't do anything.");
  2909. #ifndef USE_TRANSPARENT
  2910. if (options->TransPort || options->TransListenAddress)
  2911. REJECT("TransPort and TransListenAddress are disabled in this build.");
  2912. #endif
  2913. if (options->TokenBucketRefillInterval <= 0
  2914. || options->TokenBucketRefillInterval > 1000) {
  2915. REJECT("TokenBucketRefillInterval must be between 1 and 1000 inclusive.");
  2916. }
  2917. if (options->AccountingMax &&
  2918. (is_listening_on_low_port(options->ORPort, options->ORListenAddress) ||
  2919. is_listening_on_low_port(options->DirPort, options->DirListenAddress)))
  2920. {
  2921. log(LOG_WARN, LD_CONFIG,
  2922. "You have set AccountingMax to use hibernation. You have also "
  2923. "chosen a low DirPort or OrPort. This combination can make Tor stop "
  2924. "working when it tries to re-attach the port after a period of "
  2925. "hibernation. Please choose a different port or turn off "
  2926. "hibernation unless you know this combination will work on your "
  2927. "platform.");
  2928. }
  2929. if (options->ExcludeExitNodes || options->ExcludeNodes) {
  2930. options->_ExcludeExitNodesUnion = routerset_new();
  2931. routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeExitNodes);
  2932. routerset_union(options->_ExcludeExitNodesUnion,options->ExcludeNodes);
  2933. }
  2934. if (options->NodeFamilies) {
  2935. options->NodeFamilySets = smartlist_create();
  2936. for (cl = options->NodeFamilies; cl; cl = cl->next) {
  2937. routerset_t *rs = routerset_new();
  2938. if (routerset_parse(rs, cl->value, cl->key) == 0) {
  2939. smartlist_add(options->NodeFamilySets, rs);
  2940. } else {
  2941. routerset_free(rs);
  2942. }
  2943. }
  2944. }
  2945. if (options->ExcludeNodes && options->StrictNodes) {
  2946. COMPLAIN("You have asked to exclude certain relays from all positions "
  2947. "in your circuits. Expect hidden services and other Tor "
  2948. "features to be broken in unpredictable ways.");
  2949. }
  2950. if (options->AuthoritativeDir) {
  2951. if (!options->ContactInfo && !options->TestingTorNetwork)
  2952. REJECT("Authoritative directory servers must set ContactInfo");
  2953. if (options->V1AuthoritativeDir && !options->RecommendedVersions)
  2954. REJECT("V1 authoritative dir servers must set RecommendedVersions.");
  2955. if (!options->RecommendedClientVersions)
  2956. options->RecommendedClientVersions =
  2957. config_lines_dup(options->RecommendedVersions);
  2958. if (!options->RecommendedServerVersions)
  2959. options->RecommendedServerVersions =
  2960. config_lines_dup(options->RecommendedVersions);
  2961. if (options->VersioningAuthoritativeDir &&
  2962. (!options->RecommendedClientVersions ||
  2963. !options->RecommendedServerVersions))
  2964. REJECT("Versioning authoritative dir servers must set "
  2965. "Recommended*Versions.");
  2966. if (options->UseEntryGuards) {
  2967. log_info(LD_CONFIG, "Authoritative directory servers can't set "
  2968. "UseEntryGuards. Disabling.");
  2969. options->UseEntryGuards = 0;
  2970. }
  2971. if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
  2972. log_info(LD_CONFIG, "Authoritative directories always try to download "
  2973. "extra-info documents. Setting DownloadExtraInfo.");
  2974. options->DownloadExtraInfo = 1;
  2975. }
  2976. if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
  2977. options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
  2978. options->V3AuthoritativeDir))
  2979. REJECT("AuthoritativeDir is set, but none of "
  2980. "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
  2981. /* If we have a v3bandwidthsfile and it's broken, complain on startup */
  2982. if (options->V3BandwidthsFile && !old_options) {
  2983. dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
  2984. }
  2985. }
  2986. if (options->AuthoritativeDir && !options->DirPort)
  2987. REJECT("Running as authoritative directory, but no DirPort set.");
  2988. if (options->AuthoritativeDir && !options->ORPort)
  2989. REJECT("Running as authoritative directory, but no ORPort set.");
  2990. if (options->AuthoritativeDir && options->ClientOnly)
  2991. REJECT("Running as authoritative directory, but ClientOnly also set.");
  2992. if (options->FetchDirInfoExtraEarly && !options->FetchDirInfoEarly)
  2993. REJECT("FetchDirInfoExtraEarly requires that you also set "
  2994. "FetchDirInfoEarly");
  2995. if (options->HSAuthoritativeDir && proxy_mode(options))
  2996. REJECT("Running as authoritative v0 HS directory, but also configured "
  2997. "as a client.");
  2998. if (options->ConnLimit <= 0) {
  2999. tor_asprintf(msg,
  3000. "ConnLimit must be greater than 0, but was set to %d",
  3001. options->ConnLimit);
  3002. return -1;
  3003. }
  3004. if (options->MaxClientCircuitsPending <= 0 ||
  3005. options->MaxClientCircuitsPending > MAX_MAX_CLIENT_CIRCUITS_PENDING) {
  3006. tor_asprintf(msg,
  3007. "MaxClientCircuitsPending must be between 1 and %d, but "
  3008. "was set to %d", MAX_MAX_CLIENT_CIRCUITS_PENDING,
  3009. options->MaxClientCircuitsPending);
  3010. return -1;
  3011. }
  3012. if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
  3013. return -1;
  3014. if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
  3015. return -1;
  3016. if (validate_ports_csv(options->RejectPlaintextPorts,
  3017. "RejectPlaintextPorts", msg) < 0)
  3018. return -1;
  3019. if (validate_ports_csv(options->WarnPlaintextPorts,
  3020. "WarnPlaintextPorts", msg) < 0)
  3021. return -1;
  3022. if (options->FascistFirewall && !options->ReachableAddresses) {
  3023. if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
  3024. /* We already have firewall ports set, so migrate them to
  3025. * ReachableAddresses, which will set ReachableORAddresses and
  3026. * ReachableDirAddresses if they aren't set explicitly. */
  3027. smartlist_t *instead = smartlist_create();
  3028. config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
  3029. new_line->key = tor_strdup("ReachableAddresses");
  3030. /* If we're configured with the old format, we need to prepend some
  3031. * open ports. */
  3032. SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
  3033. {
  3034. int p = atoi(portno);
  3035. char *s;
  3036. if (p<0) continue;
  3037. s = tor_malloc(16);
  3038. tor_snprintf(s, 16, "*:%d", p);
  3039. smartlist_add(instead, s);
  3040. });
  3041. new_line->value = smartlist_join_strings(instead,",",0,NULL);
  3042. /* These have been deprecated since 0.1.1.5-alpha-cvs */
  3043. log(LOG_NOTICE, LD_CONFIG,
  3044. "Converting FascistFirewall and FirewallPorts "
  3045. "config options to new format: \"ReachableAddresses %s\"",
  3046. new_line->value);
  3047. options->ReachableAddresses = new_line;
  3048. SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
  3049. smartlist_free(instead);
  3050. } else {
  3051. /* We do not have FirewallPorts set, so add 80 to
  3052. * ReachableDirAddresses, and 443 to ReachableORAddresses. */
  3053. if (!options->ReachableDirAddresses) {
  3054. config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
  3055. new_line->key = tor_strdup("ReachableDirAddresses");
  3056. new_line->value = tor_strdup("*:80");
  3057. options->ReachableDirAddresses = new_line;
  3058. log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
  3059. "to new format: \"ReachableDirAddresses *:80\"");
  3060. }
  3061. if (!options->ReachableORAddresses) {
  3062. config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
  3063. new_line->key = tor_strdup("ReachableORAddresses");
  3064. new_line->value = tor_strdup("*:443");
  3065. options->ReachableORAddresses = new_line;
  3066. log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
  3067. "to new format: \"ReachableORAddresses *:443\"");
  3068. }
  3069. }
  3070. }
  3071. for (i=0; i<3; i++) {
  3072. config_line_t **linep =
  3073. (i==0) ? &options->ReachableAddresses :
  3074. (i==1) ? &options->ReachableORAddresses :
  3075. &options->ReachableDirAddresses;
  3076. if (!*linep)
  3077. continue;
  3078. /* We need to end with a reject *:*, not an implicit accept *:* */
  3079. for (;;) {
  3080. if (!strcmp((*linep)->value, "reject *:*")) /* already there */
  3081. break;
  3082. linep = &((*linep)->next);
  3083. if (!*linep) {
  3084. *linep = tor_malloc_zero(sizeof(config_line_t));
  3085. (*linep)->key = tor_strdup(
  3086. (i==0) ? "ReachableAddresses" :
  3087. (i==1) ? "ReachableORAddresses" :
  3088. "ReachableDirAddresses");
  3089. (*linep)->value = tor_strdup("reject *:*");
  3090. break;
  3091. }
  3092. }
  3093. }
  3094. if ((options->ReachableAddresses ||
  3095. options->ReachableORAddresses ||
  3096. options->ReachableDirAddresses) &&
  3097. server_mode(options))
  3098. REJECT("Servers must be able to freely connect to the rest "
  3099. "of the Internet, so they must not set Reachable*Addresses "
  3100. "or FascistFirewall.");
  3101. if (options->UseBridges &&
  3102. server_mode(options))
  3103. REJECT("Servers must be able to freely connect to the rest "
  3104. "of the Internet, so they must not set UseBridges.");
  3105. /* If both of these are set, we'll end up with funny behavior where we
  3106. * demand enough entrynodes be up and running else we won't build
  3107. * circuits, yet we never actually use them. */
  3108. if (options->UseBridges && options->EntryNodes)
  3109. REJECT("You cannot set both UseBridges and EntryNodes.");
  3110. options->_AllowInvalid = 0;
  3111. if (options->AllowInvalidNodes) {
  3112. SMARTLIST_FOREACH(options->AllowInvalidNodes, const char *, cp, {
  3113. if (!strcasecmp(cp, "entry"))
  3114. options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
  3115. else if (!strcasecmp(cp, "exit"))
  3116. options->_AllowInvalid |= ALLOW_INVALID_EXIT;
  3117. else if (!strcasecmp(cp, "middle"))
  3118. options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
  3119. else if (!strcasecmp(cp, "introduction"))
  3120. options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
  3121. else if (!strcasecmp(cp, "rendezvous"))
  3122. options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
  3123. else {
  3124. tor_asprintf(msg,
  3125. "Unrecognized value '%s' in AllowInvalidNodes", cp);
  3126. return -1;
  3127. }
  3128. });
  3129. }
  3130. if (!options->SafeLogging ||
  3131. !strcasecmp(options->SafeLogging, "0")) {
  3132. options->_SafeLogging = SAFELOG_SCRUB_NONE;
  3133. } else if (!strcasecmp(options->SafeLogging, "relay")) {
  3134. options->_SafeLogging = SAFELOG_SCRUB_RELAY;
  3135. } else if (!strcasecmp(options->SafeLogging, "1")) {
  3136. options->_SafeLogging = SAFELOG_SCRUB_ALL;
  3137. } else {
  3138. tor_asprintf(msg,
  3139. "Unrecognized value '%s' in SafeLogging",
  3140. escaped(options->SafeLogging));
  3141. return -1;
  3142. }
  3143. if (compute_publishserverdescriptor(options) < 0) {
  3144. tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
  3145. return -1;
  3146. }
  3147. if ((options->BridgeRelay
  3148. || options->_PublishServerDescriptor & BRIDGE_DIRINFO)
  3149. && (options->_PublishServerDescriptor
  3150. & (V1_DIRINFO|V2_DIRINFO|V3_DIRINFO))) {
  3151. REJECT("Bridges are not supposed to publish router descriptors to the "
  3152. "directory authorities. Please correct your "
  3153. "PublishServerDescriptor line.");
  3154. }
  3155. if (options->BridgeRelay && options->DirPort) {
  3156. log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
  3157. "DirPort");
  3158. options->DirPort = 0;
  3159. }
  3160. if (options->MinUptimeHidServDirectoryV2 < 0) {
  3161. log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
  3162. "least 0 seconds. Changing to 0.");
  3163. options->MinUptimeHidServDirectoryV2 = 0;
  3164. }
  3165. if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
  3166. log_warn(LD_CONFIG, "RendPostPeriod option is too short; "
  3167. "raising to %d seconds.", MIN_REND_POST_PERIOD);
  3168. options->RendPostPeriod = MIN_REND_POST_PERIOD;
  3169. }
  3170. if (options->RendPostPeriod > MAX_DIR_PERIOD) {
  3171. log_warn(LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
  3172. MAX_DIR_PERIOD);
  3173. options->RendPostPeriod = MAX_DIR_PERIOD;
  3174. }
  3175. if (options->MaxCircuitDirtiness < MIN_MAX_CIRCUIT_DIRTINESS) {
  3176. log_warn(LD_CONFIG, "MaxCircuitDirtiness option is too short; "
  3177. "raising to %d seconds.", MIN_MAX_CIRCUIT_DIRTINESS);
  3178. options->MaxCircuitDirtiness = MIN_MAX_CIRCUIT_DIRTINESS;
  3179. }
  3180. if (options->CircuitStreamTimeout &&
  3181. options->CircuitStreamTimeout < MIN_CIRCUIT_STREAM_TIMEOUT) {
  3182. log_warn(LD_CONFIG, "CircuitStreamTimeout option is too short; "
  3183. "raising to %d seconds.", MIN_CIRCUIT_STREAM_TIMEOUT);
  3184. options->CircuitStreamTimeout = MIN_CIRCUIT_STREAM_TIMEOUT;
  3185. }
  3186. if (options->HeartbeatPeriod &&
  3187. options->HeartbeatPeriod < MIN_HEARTBEAT_PERIOD) {
  3188. log_warn(LD_CONFIG, "HeartbeatPeriod option is too short; "
  3189. "raising to %d seconds.", MIN_HEARTBEAT_PERIOD);
  3190. options->HeartbeatPeriod = MIN_HEARTBEAT_PERIOD;
  3191. }
  3192. if (options->KeepalivePeriod < 1)
  3193. REJECT("KeepalivePeriod option must be positive.");
  3194. if (ensure_bandwidth_cap(&options->BandwidthRate,
  3195. "BandwidthRate", msg) < 0)
  3196. return -1;
  3197. if (ensure_bandwidth_cap(&options->BandwidthBurst,
  3198. "BandwidthBurst", msg) < 0)
  3199. return -1;
  3200. if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
  3201. "MaxAdvertisedBandwidth", msg) < 0)
  3202. return -1;
  3203. if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
  3204. "RelayBandwidthRate", msg) < 0)
  3205. return -1;
  3206. if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
  3207. "RelayBandwidthBurst", msg) < 0)
  3208. return -1;
  3209. if (ensure_bandwidth_cap(&options->PerConnBWRate,
  3210. "PerConnBWRate", msg) < 0)
  3211. return -1;
  3212. if (ensure_bandwidth_cap(&options->PerConnBWBurst,
  3213. "PerConnBWBurst", msg) < 0)
  3214. return -1;
  3215. if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
  3216. options->RelayBandwidthBurst = options->RelayBandwidthRate;
  3217. if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
  3218. options->RelayBandwidthRate = options->RelayBandwidthBurst;
  3219. if (server_mode(options)) {
  3220. if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
  3221. tor_asprintf(msg,
  3222. "BandwidthRate is set to %d bytes/second. "
  3223. "For servers, it must be at least %d.",
  3224. (int)options->BandwidthRate,
  3225. ROUTER_REQUIRED_MIN_BANDWIDTH);
  3226. return -1;
  3227. } else if (options->MaxAdvertisedBandwidth <
  3228. ROUTER_REQUIRED_MIN_BANDWIDTH/2) {
  3229. tor_asprintf(msg,
  3230. "MaxAdvertisedBandwidth is set to %d bytes/second. "
  3231. "For servers, it must be at least %d.",
  3232. (int)options->MaxAdvertisedBandwidth,
  3233. ROUTER_REQUIRED_MIN_BANDWIDTH/2);
  3234. return -1;
  3235. }
  3236. if (options->RelayBandwidthRate &&
  3237. options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
  3238. tor_asprintf(msg,
  3239. "RelayBandwidthRate is set to %d bytes/second. "
  3240. "For servers, it must be at least %d.",
  3241. (int)options->RelayBandwidthRate,
  3242. ROUTER_REQUIRED_MIN_BANDWIDTH);
  3243. return -1;
  3244. }
  3245. }
  3246. if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
  3247. REJECT("RelayBandwidthBurst must be at least equal "
  3248. "to RelayBandwidthRate.");
  3249. if (options->BandwidthRate > options->BandwidthBurst)
  3250. REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
  3251. /* if they set relaybandwidth* really high but left bandwidth*
  3252. * at the default, raise the defaults. */
  3253. if (options->RelayBandwidthRate > options->BandwidthRate)
  3254. options->BandwidthRate = options->RelayBandwidthRate;
  3255. if (options->RelayBandwidthBurst > options->BandwidthBurst)
  3256. options->BandwidthBurst = options->RelayBandwidthBurst;
  3257. if (accounting_parse_options(options, 1)<0)
  3258. REJECT("Failed to parse accounting options. See logs for details.");
  3259. if (options->HTTPProxy) { /* parse it now */
  3260. if (tor_addr_port_lookup(options->HTTPProxy,
  3261. &options->HTTPProxyAddr, &options->HTTPProxyPort) < 0)
  3262. REJECT("HTTPProxy failed to parse or resolve. Please fix.");
  3263. if (options->HTTPProxyPort == 0) { /* give it a default */
  3264. options->HTTPProxyPort = 80;
  3265. }
  3266. }
  3267. if (options->HTTPProxyAuthenticator) {
  3268. if (strlen(options->HTTPProxyAuthenticator) >= 512)
  3269. REJECT("HTTPProxyAuthenticator is too long (>= 512 chars).");
  3270. }
  3271. if (options->HTTPSProxy) { /* parse it now */
  3272. if (tor_addr_port_lookup(options->HTTPSProxy,
  3273. &options->HTTPSProxyAddr, &options->HTTPSProxyPort) <0)
  3274. REJECT("HTTPSProxy failed to parse or resolve. Please fix.");
  3275. if (options->HTTPSProxyPort == 0) { /* give it a default */
  3276. options->HTTPSProxyPort = 443;
  3277. }
  3278. }
  3279. if (options->HTTPSProxyAuthenticator) {
  3280. if (strlen(options->HTTPSProxyAuthenticator) >= 512)
  3281. REJECT("HTTPSProxyAuthenticator is too long (>= 512 chars).");
  3282. }
  3283. if (options->Socks4Proxy) { /* parse it now */
  3284. if (tor_addr_port_lookup(options->Socks4Proxy,
  3285. &options->Socks4ProxyAddr,
  3286. &options->Socks4ProxyPort) <0)
  3287. REJECT("Socks4Proxy failed to parse or resolve. Please fix.");
  3288. if (options->Socks4ProxyPort == 0) { /* give it a default */
  3289. options->Socks4ProxyPort = 1080;
  3290. }
  3291. }
  3292. if (options->Socks5Proxy) { /* parse it now */
  3293. if (tor_addr_port_lookup(options->Socks5Proxy,
  3294. &options->Socks5ProxyAddr,
  3295. &options->Socks5ProxyPort) <0)
  3296. REJECT("Socks5Proxy failed to parse or resolve. Please fix.");
  3297. if (options->Socks5ProxyPort == 0) { /* give it a default */
  3298. options->Socks5ProxyPort = 1080;
  3299. }
  3300. }
  3301. /* Check if more than one proxy type has been enabled. */
  3302. if (!!options->Socks4Proxy + !!options->Socks5Proxy +
  3303. !!options->HTTPSProxy + !!options->ClientTransportPlugin > 1)
  3304. REJECT("You have configured more than one proxy type. "
  3305. "(Socks4Proxy|Socks5Proxy|HTTPSProxy|ClientTransportPlugin)");
  3306. if (options->Socks5ProxyUsername) {
  3307. size_t len;
  3308. len = strlen(options->Socks5ProxyUsername);
  3309. if (len < 1 || len > 255)
  3310. REJECT("Socks5ProxyUsername must be between 1 and 255 characters.");
  3311. if (!options->Socks5ProxyPassword)
  3312. REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
  3313. len = strlen(options->Socks5ProxyPassword);
  3314. if (len < 1 || len > 255)
  3315. REJECT("Socks5ProxyPassword must be between 1 and 255 characters.");
  3316. } else if (options->Socks5ProxyPassword)
  3317. REJECT("Socks5ProxyPassword must be included with Socks5ProxyUsername.");
  3318. if (options->HashedControlPassword) {
  3319. smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
  3320. if (!sl) {
  3321. REJECT("Bad HashedControlPassword: wrong length or bad encoding");
  3322. } else {
  3323. SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
  3324. smartlist_free(sl);
  3325. }
  3326. }
  3327. if (options->HashedControlSessionPassword) {
  3328. smartlist_t *sl = decode_hashed_passwords(
  3329. options->HashedControlSessionPassword);
  3330. if (!sl) {
  3331. REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
  3332. } else {
  3333. SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
  3334. smartlist_free(sl);
  3335. }
  3336. }
  3337. if (options->OwningControllerProcess) {
  3338. const char *validate_pspec_msg = NULL;
  3339. if (tor_validate_process_specifier(options->OwningControllerProcess,
  3340. &validate_pspec_msg)) {
  3341. tor_asprintf(msg, "Bad OwningControllerProcess: %s",
  3342. validate_pspec_msg);
  3343. return -1;
  3344. }
  3345. }
  3346. if (options->ControlListenAddress) {
  3347. int all_are_local = 1;
  3348. config_line_t *ln;
  3349. for (ln = options->ControlListenAddress; ln; ln = ln->next) {
  3350. if (strcmpstart(ln->value, "127."))
  3351. all_are_local = 0;
  3352. }
  3353. if (!all_are_local) {
  3354. if (!options->HashedControlPassword &&
  3355. !options->HashedControlSessionPassword &&
  3356. !options->CookieAuthentication) {
  3357. log_warn(LD_CONFIG,
  3358. "You have a ControlListenAddress set to accept "
  3359. "unauthenticated connections from a non-local address. "
  3360. "This means that programs not running on your computer "
  3361. "can reconfigure your Tor, without even having to guess a "
  3362. "password. That's so bad that I'm closing your ControlPort "
  3363. "for you. If you need to control your Tor remotely, try "
  3364. "enabling authentication and using a tool like stunnel or "
  3365. "ssh to encrypt remote access.");
  3366. options->ControlPort = 0;
  3367. } else {
  3368. log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
  3369. "connections from a non-local address. This means that "
  3370. "programs not running on your computer can reconfigure your "
  3371. "Tor. That's pretty bad, since the controller "
  3372. "protocol isn't encrypted! Maybe you should just listen on "
  3373. "127.0.0.1 and use a tool like stunnel or ssh to encrypt "
  3374. "remote connections to your control port.");
  3375. }
  3376. }
  3377. }
  3378. if (options->ControlPort && !options->HashedControlPassword &&
  3379. !options->HashedControlSessionPassword &&
  3380. !options->CookieAuthentication) {
  3381. log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
  3382. "has been configured. This means that any program on your "
  3383. "computer can reconfigure your Tor. That's bad! You should "
  3384. "upgrade your Tor controller as soon as possible.");
  3385. }
  3386. if (options->CookieAuthFileGroupReadable && !options->CookieAuthFile) {
  3387. log_warn(LD_CONFIG, "CookieAuthFileGroupReadable is set, but will have "
  3388. "no effect: you must specify an explicit CookieAuthFile to "
  3389. "have it group-readable.");
  3390. }
  3391. if (options->UseEntryGuards && ! options->NumEntryGuards)
  3392. REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
  3393. if (check_nickname_list(options->MyFamily, "MyFamily", msg))
  3394. return -1;
  3395. for (cl = options->NodeFamilies; cl; cl = cl->next) {
  3396. routerset_t *rs = routerset_new();
  3397. if (routerset_parse(rs, cl->value, cl->key)) {
  3398. routerset_free(rs);
  3399. return -1;
  3400. }
  3401. routerset_free(rs);
  3402. }
  3403. if (validate_addr_policies(options, msg) < 0)
  3404. return -1;
  3405. if (validate_dir_authorities(options, old_options) < 0)
  3406. REJECT("Directory authority line did not parse. See logs for details.");
  3407. if (options->UseBridges && !options->Bridges)
  3408. REJECT("If you set UseBridges, you must specify at least one bridge.");
  3409. if (options->UseBridges && !options->TunnelDirConns)
  3410. REJECT("If you set UseBridges, you must set TunnelDirConns.");
  3411. for (cl = options->Bridges; cl; cl = cl->next) {
  3412. if (parse_bridge_line(cl->value, 1)<0)
  3413. REJECT("Bridge line did not parse. See logs for details.");
  3414. }
  3415. for (cl = options->ClientTransportPlugin; cl; cl = cl->next) {
  3416. if (parse_client_transport_line(cl->value, 1)<0)
  3417. REJECT("Transport line did not parse. See logs for details.");
  3418. }
  3419. for (cl = options->ServerTransportPlugin; cl; cl = cl->next) {
  3420. if (parse_server_transport_line(cl->value, 1)<0)
  3421. REJECT("Server transport line did not parse. See logs for details.");
  3422. }
  3423. if (options->ConstrainedSockets) {
  3424. /* If the user wants to constrain socket buffer use, make sure the desired
  3425. * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
  3426. if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
  3427. options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
  3428. options->ConstrainedSockSize % 1024) {
  3429. tor_asprintf(msg,
  3430. "ConstrainedSockSize is invalid. Must be a value between %d and %d "
  3431. "in 1024 byte increments.",
  3432. MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
  3433. return -1;
  3434. }
  3435. if (options->DirPort) {
  3436. /* Providing cached directory entries while system TCP buffers are scarce
  3437. * will exacerbate the socket errors. Suggest that this be disabled. */
  3438. COMPLAIN("You have requested constrained socket buffers while also "
  3439. "serving directory entries via DirPort. It is strongly "
  3440. "suggested that you disable serving directory requests when "
  3441. "system TCP buffer resources are scarce.");
  3442. }
  3443. }
  3444. if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
  3445. options->V3AuthVotingInterval/2) {
  3446. REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
  3447. "V3AuthVotingInterval");
  3448. }
  3449. if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
  3450. REJECT("V3AuthVoteDelay is way too low.");
  3451. if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
  3452. REJECT("V3AuthDistDelay is way too low.");
  3453. if (options->V3AuthNIntervalsValid < 2)
  3454. REJECT("V3AuthNIntervalsValid must be at least 2.");
  3455. if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
  3456. REJECT("V3AuthVotingInterval is insanely low.");
  3457. } else if (options->V3AuthVotingInterval > 24*60*60) {
  3458. REJECT("V3AuthVotingInterval is insanely high.");
  3459. } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
  3460. COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
  3461. }
  3462. if (rend_config_services(options, 1) < 0)
  3463. REJECT("Failed to configure rendezvous options. See logs for details.");
  3464. /* Parse client-side authorization for hidden services. */
  3465. if (rend_parse_service_authorization(options, 1) < 0)
  3466. REJECT("Failed to configure client authorization for hidden services. "
  3467. "See logs for details.");
  3468. if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
  3469. return -1;
  3470. if (options->PreferTunneledDirConns && !options->TunnelDirConns)
  3471. REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
  3472. if ((options->Socks4Proxy || options->Socks5Proxy) &&
  3473. !options->HTTPProxy && !options->PreferTunneledDirConns)
  3474. REJECT("When Socks4Proxy or Socks5Proxy is configured, "
  3475. "PreferTunneledDirConns and TunnelDirConns must both be "
  3476. "set to 1, or HTTPProxy must be configured.");
  3477. if (options->AutomapHostsSuffixes) {
  3478. SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
  3479. {
  3480. size_t len = strlen(suf);
  3481. if (len && suf[len-1] == '.')
  3482. suf[len-1] = '\0';
  3483. });
  3484. }
  3485. if (options->TestingTorNetwork && !options->DirServers) {
  3486. REJECT("TestingTorNetwork may only be configured in combination with "
  3487. "a non-default set of DirServers.");
  3488. }
  3489. if (options->AllowSingleHopExits && !options->DirServers) {
  3490. COMPLAIN("You have set AllowSingleHopExits; now your relay will allow "
  3491. "others to make one-hop exits. However, since by default most "
  3492. "clients avoid relays that set this option, most clients will "
  3493. "ignore you.");
  3494. }
  3495. /*XXXX023 checking for defaults manually like this is a bit fragile.*/
  3496. /* Keep changes to hard-coded values synchronous to man page and default
  3497. * values table. */
  3498. if (options->TestingV3AuthInitialVotingInterval != 30*60 &&
  3499. !options->TestingTorNetwork && !options->_UsingTestNetworkDefaults) {
  3500. REJECT("TestingV3AuthInitialVotingInterval may only be changed in testing "
  3501. "Tor networks!");
  3502. } else if (options->TestingV3AuthInitialVotingInterval < MIN_VOTE_INTERVAL) {
  3503. REJECT("TestingV3AuthInitialVotingInterval is insanely low.");
  3504. } else if (((30*60) % options->TestingV3AuthInitialVotingInterval) != 0) {
  3505. REJECT("TestingV3AuthInitialVotingInterval does not divide evenly into "
  3506. "30 minutes.");
  3507. }
  3508. if (options->TestingV3AuthInitialVoteDelay != 5*60 &&
  3509. !options->TestingTorNetwork && !options->_UsingTestNetworkDefaults) {
  3510. REJECT("TestingV3AuthInitialVoteDelay may only be changed in testing "
  3511. "Tor networks!");
  3512. } else if (options->TestingV3AuthInitialVoteDelay < MIN_VOTE_SECONDS) {
  3513. REJECT("TestingV3AuthInitialVoteDelay is way too low.");
  3514. }
  3515. if (options->TestingV3AuthInitialDistDelay != 5*60 &&
  3516. !options->TestingTorNetwork && !options->_UsingTestNetworkDefaults) {
  3517. REJECT("TestingV3AuthInitialDistDelay may only be changed in testing "
  3518. "Tor networks!");
  3519. } else if (options->TestingV3AuthInitialDistDelay < MIN_DIST_SECONDS) {
  3520. REJECT("TestingV3AuthInitialDistDelay is way too low.");
  3521. }
  3522. if (options->TestingV3AuthInitialVoteDelay +
  3523. options->TestingV3AuthInitialDistDelay >=
  3524. options->TestingV3AuthInitialVotingInterval/2) {
  3525. REJECT("TestingV3AuthInitialVoteDelay plus TestingV3AuthInitialDistDelay "
  3526. "must be less than half TestingV3AuthInitialVotingInterval");
  3527. }
  3528. if (options->TestingAuthDirTimeToLearnReachability != 30*60 &&
  3529. !options->TestingTorNetwork && !options->_UsingTestNetworkDefaults) {
  3530. REJECT("TestingAuthDirTimeToLearnReachability may only be changed in "
  3531. "testing Tor networks!");
  3532. } else if (options->TestingAuthDirTimeToLearnReachability < 0) {
  3533. REJECT("TestingAuthDirTimeToLearnReachability must be non-negative.");
  3534. } else if (options->TestingAuthDirTimeToLearnReachability > 2*60*60) {
  3535. COMPLAIN("TestingAuthDirTimeToLearnReachability is insanely high.");
  3536. }
  3537. if (options->TestingEstimatedDescriptorPropagationTime != 10*60 &&
  3538. !options->TestingTorNetwork && !options->_UsingTestNetworkDefaults) {
  3539. REJECT("TestingEstimatedDescriptorPropagationTime may only be changed in "
  3540. "testing Tor networks!");
  3541. } else if (options->TestingEstimatedDescriptorPropagationTime < 0) {
  3542. REJECT("TestingEstimatedDescriptorPropagationTime must be non-negative.");
  3543. } else if (options->TestingEstimatedDescriptorPropagationTime > 60*60) {
  3544. COMPLAIN("TestingEstimatedDescriptorPropagationTime is insanely high.");
  3545. }
  3546. if (options->TestingTorNetwork) {
  3547. log_warn(LD_CONFIG, "TestingTorNetwork is set. This will make your node "
  3548. "almost unusable in the public Tor network, and is "
  3549. "therefore only advised if you are building a "
  3550. "testing Tor network!");
  3551. }
  3552. if (options->AccelName && !options->HardwareAccel)
  3553. options->HardwareAccel = 1;
  3554. if (options->AccelDir && !options->AccelName)
  3555. REJECT("Can't use hardware crypto accelerator dir without engine name.");
  3556. if (options->PublishServerDescriptor)
  3557. SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
  3558. if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
  3559. if (smartlist_len(options->PublishServerDescriptor) > 1) {
  3560. COMPLAIN("You have passed a list of multiple arguments to the "
  3561. "PublishServerDescriptor option that includes 0 or 1. "
  3562. "0 or 1 should only be used as the sole argument. "
  3563. "This configuration will be rejected in a future release.");
  3564. break;
  3565. }
  3566. });
  3567. if (options->BridgeRelay == 1 && options->ORPort == 0)
  3568. REJECT("BridgeRelay is 1, ORPort is 0. This is an invalid combination.");
  3569. return 0;
  3570. #undef REJECT
  3571. #undef COMPLAIN
  3572. }
  3573. /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
  3574. * equal strings. */
  3575. static int
  3576. opt_streq(const char *s1, const char *s2)
  3577. {
  3578. return 0 == strcmp_opt(s1, s2);
  3579. }
  3580. /** Check if any of the previous options have changed but aren't allowed to. */
  3581. static int
  3582. options_transition_allowed(const or_options_t *old,
  3583. const or_options_t *new_val,
  3584. char **msg)
  3585. {
  3586. if (!old)
  3587. return 0;
  3588. if (!opt_streq(old->PidFile, new_val->PidFile)) {
  3589. *msg = tor_strdup("PidFile is not allowed to change.");
  3590. return -1;
  3591. }
  3592. if (old->RunAsDaemon != new_val->RunAsDaemon) {
  3593. *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
  3594. "is not allowed.");
  3595. return -1;
  3596. }
  3597. if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
  3598. tor_asprintf(msg,
  3599. "While Tor is running, changing DataDirectory "
  3600. "(\"%s\"->\"%s\") is not allowed.",
  3601. old->DataDirectory, new_val->DataDirectory);
  3602. return -1;
  3603. }
  3604. if (!opt_streq(old->User, new_val->User)) {
  3605. *msg = tor_strdup("While Tor is running, changing User is not allowed.");
  3606. return -1;
  3607. }
  3608. if ((old->HardwareAccel != new_val->HardwareAccel)
  3609. || !opt_streq(old->AccelName, new_val->AccelName)
  3610. || !opt_streq(old->AccelDir, new_val->AccelDir)) {
  3611. *msg = tor_strdup("While Tor is running, changing OpenSSL hardware "
  3612. "acceleration engine is not allowed.");
  3613. return -1;
  3614. }
  3615. if (old->TestingTorNetwork != new_val->TestingTorNetwork) {
  3616. *msg = tor_strdup("While Tor is running, changing TestingTorNetwork "
  3617. "is not allowed.");
  3618. return -1;
  3619. }
  3620. if (old->DisableAllSwap != new_val->DisableAllSwap) {
  3621. *msg = tor_strdup("While Tor is running, changing DisableAllSwap "
  3622. "is not allowed.");
  3623. return -1;
  3624. }
  3625. if (old->TokenBucketRefillInterval != new_val->TokenBucketRefillInterval) {
  3626. *msg = tor_strdup("While Tor is running, changing TokenBucketRefill"
  3627. "Interval is not allowed");
  3628. return -1;
  3629. }
  3630. if (old->DisableIOCP != new_val->DisableIOCP) {
  3631. *msg = tor_strdup("While Tor is running, changing DisableIOCP "
  3632. "is not allowed.");
  3633. return -1;
  3634. }
  3635. return 0;
  3636. }
  3637. /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
  3638. * will require us to rotate the CPU and DNS workers; else return 0. */
  3639. static int
  3640. options_transition_affects_workers(const or_options_t *old_options,
  3641. const or_options_t *new_options)
  3642. {
  3643. if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
  3644. old_options->NumCPUs != new_options->NumCPUs ||
  3645. old_options->ORPort != new_options->ORPort ||
  3646. old_options->ServerDNSSearchDomains !=
  3647. new_options->ServerDNSSearchDomains ||
  3648. old_options->_SafeLogging != new_options->_SafeLogging ||
  3649. old_options->ClientOnly != new_options->ClientOnly ||
  3650. public_server_mode(old_options) != public_server_mode(new_options) ||
  3651. !config_lines_eq(old_options->Logs, new_options->Logs) ||
  3652. old_options->LogMessageDomains != new_options->LogMessageDomains)
  3653. return 1;
  3654. /* Check whether log options match. */
  3655. /* Nothing that changed matters. */
  3656. return 0;
  3657. }
  3658. /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
  3659. * will require us to generate a new descriptor; else return 0. */
  3660. static int
  3661. options_transition_affects_descriptor(const or_options_t *old_options,
  3662. const or_options_t *new_options)
  3663. {
  3664. /* XXX We can be smarter here. If your DirPort isn't being
  3665. * published and you just turned it off, no need to republish. Etc. */
  3666. if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
  3667. !opt_streq(old_options->Nickname,new_options->Nickname) ||
  3668. !opt_streq(old_options->Address,new_options->Address) ||
  3669. !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
  3670. old_options->ExitPolicyRejectPrivate !=
  3671. new_options->ExitPolicyRejectPrivate ||
  3672. old_options->ORPort != new_options->ORPort ||
  3673. old_options->DirPort != new_options->DirPort ||
  3674. old_options->ClientOnly != new_options->ClientOnly ||
  3675. old_options->_PublishServerDescriptor !=
  3676. new_options->_PublishServerDescriptor ||
  3677. get_effective_bwrate(old_options) != get_effective_bwrate(new_options) ||
  3678. get_effective_bwburst(old_options) !=
  3679. get_effective_bwburst(new_options) ||
  3680. !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
  3681. !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
  3682. !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
  3683. old_options->AccountingMax != new_options->AccountingMax ||
  3684. public_server_mode(old_options) != public_server_mode(new_options))
  3685. return 1;
  3686. return 0;
  3687. }
  3688. #ifdef MS_WINDOWS
  3689. /** Return the directory on windows where we expect to find our application
  3690. * data. */
  3691. static char *
  3692. get_windows_conf_root(void)
  3693. {
  3694. static int is_set = 0;
  3695. static char path[MAX_PATH+1];
  3696. TCHAR tpath[MAX_PATH] = {0};
  3697. LPITEMIDLIST idl;
  3698. IMalloc *m;
  3699. HRESULT result;
  3700. if (is_set)
  3701. return path;
  3702. /* Find X:\documents and settings\username\application data\ .
  3703. * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
  3704. */
  3705. #ifdef ENABLE_LOCAL_APPDATA
  3706. #define APPDATA_PATH CSIDL_LOCAL_APPDATA
  3707. #else
  3708. #define APPDATA_PATH CSIDL_APPDATA
  3709. #endif
  3710. if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, APPDATA_PATH, &idl))) {
  3711. getcwd(path,MAX_PATH);
  3712. is_set = 1;
  3713. log_warn(LD_CONFIG,
  3714. "I couldn't find your application data folder: are you "
  3715. "running an ancient version of Windows 95? Defaulting to \"%s\"",
  3716. path);
  3717. return path;
  3718. }
  3719. /* Convert the path from an "ID List" (whatever that is!) to a path. */
  3720. result = SHGetPathFromIDList(idl, tpath);
  3721. #ifdef UNICODE
  3722. wcstombs(path,tpath,MAX_PATH);
  3723. #else
  3724. strlcpy(path,tpath,sizeof(path));
  3725. #endif
  3726. /* Now we need to free the memory that the path-idl was stored in. In
  3727. * typical Windows fashion, we can't just call 'free()' on it. */
  3728. SHGetMalloc(&m);
  3729. if (m) {
  3730. m->lpVtbl->Free(m, idl);
  3731. m->lpVtbl->Release(m);
  3732. }
  3733. if (!SUCCEEDED(result)) {
  3734. return NULL;
  3735. }
  3736. strlcat(path,"\\tor",MAX_PATH);
  3737. is_set = 1;
  3738. return path;
  3739. }
  3740. #endif
  3741. /** Return the default location for our torrc file. */
  3742. static const char *
  3743. get_default_conf_file(void)
  3744. {
  3745. #ifdef MS_WINDOWS
  3746. static char path[MAX_PATH+1];
  3747. strlcpy(path, get_windows_conf_root(), MAX_PATH);
  3748. strlcat(path,"\\torrc",MAX_PATH);
  3749. return path;
  3750. #else
  3751. return (CONFDIR "/torrc");
  3752. #endif
  3753. }
  3754. /** Verify whether lst is a string containing valid-looking comma-separated
  3755. * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
  3756. */
  3757. static int
  3758. check_nickname_list(const char *lst, const char *name, char **msg)
  3759. {
  3760. int r = 0;
  3761. smartlist_t *sl;
  3762. if (!lst)
  3763. return 0;
  3764. sl = smartlist_create();
  3765. smartlist_split_string(sl, lst, ",",
  3766. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
  3767. SMARTLIST_FOREACH(sl, const char *, s,
  3768. {
  3769. if (!is_legal_nickname_or_hexdigest(s)) {
  3770. tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
  3771. r = -1;
  3772. break;
  3773. }
  3774. });
  3775. SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
  3776. smartlist_free(sl);
  3777. return r;
  3778. }
  3779. /** Learn config file name from command line arguments, or use the default */
  3780. static char *
  3781. find_torrc_filename(int argc, char **argv,
  3782. int *using_default_torrc, int *ignore_missing_torrc)
  3783. {
  3784. char *fname=NULL;
  3785. int i;
  3786. for (i = 1; i < argc; ++i) {
  3787. if (i < argc-1 && !strcmp(argv[i],"-f")) {
  3788. if (fname) {
  3789. log(LOG_WARN, LD_CONFIG, "Duplicate -f options on command line.");
  3790. tor_free(fname);
  3791. }
  3792. fname = expand_filename(argv[i+1]);
  3793. *using_default_torrc = 0;
  3794. ++i;
  3795. } else if (!strcmp(argv[i],"--ignore-missing-torrc")) {
  3796. *ignore_missing_torrc = 1;
  3797. }
  3798. }
  3799. if (*using_default_torrc) {
  3800. /* didn't find one, try CONFDIR */
  3801. const char *dflt = get_default_conf_file();
  3802. if (dflt && file_status(dflt) == FN_FILE) {
  3803. fname = tor_strdup(dflt);
  3804. } else {
  3805. #ifndef MS_WINDOWS
  3806. char *fn;
  3807. fn = expand_filename("~/.torrc");
  3808. if (fn && file_status(fn) == FN_FILE) {
  3809. fname = fn;
  3810. } else {
  3811. tor_free(fn);
  3812. fname = tor_strdup(dflt);
  3813. }
  3814. #else
  3815. fname = tor_strdup(dflt);
  3816. #endif
  3817. }
  3818. }
  3819. return fname;
  3820. }
  3821. /** Load torrc from disk, setting torrc_fname if successful */
  3822. static char *
  3823. load_torrc_from_disk(int argc, char **argv)
  3824. {
  3825. char *fname=NULL;
  3826. char *cf = NULL;
  3827. int using_default_torrc = 1;
  3828. int ignore_missing_torrc = 0;
  3829. fname = find_torrc_filename(argc, argv,
  3830. &using_default_torrc, &ignore_missing_torrc);
  3831. tor_assert(fname);
  3832. log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
  3833. tor_free(torrc_fname);
  3834. torrc_fname = fname;
  3835. /* Open config file */
  3836. if (file_status(fname) != FN_FILE ||
  3837. !(cf = read_file_to_str(fname,0,NULL))) {
  3838. if (using_default_torrc == 1 || ignore_missing_torrc ) {
  3839. log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
  3840. "using reasonable defaults.", fname);
  3841. tor_free(fname); /* sets fname to NULL */
  3842. torrc_fname = NULL;
  3843. cf = tor_strdup("");
  3844. } else {
  3845. log(LOG_WARN, LD_CONFIG,
  3846. "Unable to open configuration file \"%s\".", fname);
  3847. goto err;
  3848. }
  3849. } else {
  3850. log(LOG_NOTICE, LD_CONFIG, "Read configuration file \"%s\".", fname);
  3851. }
  3852. return cf;
  3853. err:
  3854. tor_free(fname);
  3855. torrc_fname = NULL;
  3856. return NULL;
  3857. }
  3858. /** Read a configuration file into <b>options</b>, finding the configuration
  3859. * file location based on the command line. After loading the file
  3860. * call options_init_from_string() to load the config.
  3861. * Return 0 if success, -1 if failure. */
  3862. int
  3863. options_init_from_torrc(int argc, char **argv)
  3864. {
  3865. char *cf=NULL;
  3866. int i, retval, command;
  3867. static char **backup_argv;
  3868. static int backup_argc;
  3869. char *command_arg = NULL;
  3870. char *errmsg=NULL;
  3871. if (argv) { /* first time we're called. save command line args */
  3872. backup_argv = argv;
  3873. backup_argc = argc;
  3874. } else { /* we're reloading. need to clean up old options first. */
  3875. argv = backup_argv;
  3876. argc = backup_argc;
  3877. }
  3878. if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
  3879. print_usage();
  3880. exit(0);
  3881. }
  3882. if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
  3883. /* For documenting validating whether we've documented everything. */
  3884. list_torrc_options();
  3885. exit(0);
  3886. }
  3887. if (argc > 1 && (!strcmp(argv[1],"--version"))) {
  3888. printf("Tor version %s.\n",get_version());
  3889. exit(0);
  3890. }
  3891. if (argc > 1 && (!strcmp(argv[1],"--digests"))) {
  3892. printf("Tor version %s.\n",get_version());
  3893. printf("%s", libor_get_digests());
  3894. printf("%s", tor_get_digests());
  3895. exit(0);
  3896. }
  3897. /* Go through command-line variables */
  3898. if (!global_cmdline_options) {
  3899. /* Or we could redo the list every time we pass this place.
  3900. * It does not really matter */
  3901. if (config_get_commandlines(argc, argv, &global_cmdline_options) < 0) {
  3902. goto err;
  3903. }
  3904. }
  3905. command = CMD_RUN_TOR;
  3906. for (i = 1; i < argc; ++i) {
  3907. if (!strcmp(argv[i],"--list-fingerprint")) {
  3908. command = CMD_LIST_FINGERPRINT;
  3909. } else if (!strcmp(argv[i],"--hash-password")) {
  3910. command = CMD_HASH_PASSWORD;
  3911. command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
  3912. ++i;
  3913. } else if (!strcmp(argv[i],"--verify-config")) {
  3914. command = CMD_VERIFY_CONFIG;
  3915. }
  3916. }
  3917. if (command == CMD_HASH_PASSWORD) {
  3918. cf = tor_strdup("");
  3919. } else {
  3920. cf = load_torrc_from_disk(argc, argv);
  3921. if (!cf)
  3922. goto err;
  3923. }
  3924. retval = options_init_from_string(cf, command, command_arg, &errmsg);
  3925. tor_free(cf);
  3926. if (retval < 0)
  3927. goto err;
  3928. return 0;
  3929. err:
  3930. if (errmsg) {
  3931. log(LOG_WARN,LD_CONFIG,"%s", errmsg);
  3932. tor_free(errmsg);
  3933. }
  3934. return -1;
  3935. }
  3936. /** Load the options from the configuration in <b>cf</b>, validate
  3937. * them for consistency and take actions based on them.
  3938. *
  3939. * Return 0 if success, negative on error:
  3940. * * -1 for general errors.
  3941. * * -2 for failure to parse/validate,
  3942. * * -3 for transition not allowed
  3943. * * -4 for error while setting the new options
  3944. */
  3945. setopt_err_t
  3946. options_init_from_string(const char *cf,
  3947. int command, const char *command_arg,
  3948. char **msg)
  3949. {
  3950. or_options_t *oldoptions, *newoptions;
  3951. config_line_t *cl;
  3952. int retval;
  3953. setopt_err_t err = SETOPT_ERR_MISC;
  3954. tor_assert(msg);
  3955. oldoptions = global_options; /* get_options unfortunately asserts if
  3956. this is the first time we run*/
  3957. newoptions = tor_malloc_zero(sizeof(or_options_t));
  3958. newoptions->_magic = OR_OPTIONS_MAGIC;
  3959. options_init(newoptions);
  3960. newoptions->command = command;
  3961. newoptions->command_arg = command_arg;
  3962. /* get config lines, assign them */
  3963. retval = config_get_lines(cf, &cl);
  3964. if (retval < 0) {
  3965. err = SETOPT_ERR_PARSE;
  3966. goto err;
  3967. }
  3968. retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
  3969. config_free_lines(cl);
  3970. if (retval < 0) {
  3971. err = SETOPT_ERR_PARSE;
  3972. goto err;
  3973. }
  3974. /* Go through command-line variables too */
  3975. retval = config_assign(&options_format, newoptions,
  3976. global_cmdline_options, 0, 0, msg);
  3977. if (retval < 0) {
  3978. err = SETOPT_ERR_PARSE;
  3979. goto err;
  3980. }
  3981. /* If this is a testing network configuration, change defaults
  3982. * for a list of dependent config options, re-initialize newoptions
  3983. * with the new defaults, and assign all options to it second time. */
  3984. if (newoptions->TestingTorNetwork) {
  3985. /* XXXX this is a bit of a kludge. perhaps there's a better way to do
  3986. * this? We could, for example, make the parsing algorithm do two passes
  3987. * over the configuration. If it finds any "suite" options like
  3988. * TestingTorNetwork, it could change the defaults before its second pass.
  3989. * Not urgent so long as this seems to work, but at any sign of trouble,
  3990. * let's clean it up. -NM */
  3991. /* Change defaults. */
  3992. int i;
  3993. for (i = 0; testing_tor_network_defaults[i].name; ++i) {
  3994. const config_var_t *new_var = &testing_tor_network_defaults[i];
  3995. config_var_t *old_var =
  3996. config_find_option_mutable(&options_format, new_var->name);
  3997. tor_assert(new_var);
  3998. tor_assert(old_var);
  3999. old_var->initvalue = new_var->initvalue;
  4000. }
  4001. /* Clear newoptions and re-initialize them with new defaults. */
  4002. config_free(&options_format, newoptions);
  4003. newoptions = tor_malloc_zero(sizeof(or_options_t));
  4004. newoptions->_magic = OR_OPTIONS_MAGIC;
  4005. options_init(newoptions);
  4006. newoptions->command = command;
  4007. newoptions->command_arg = command_arg;
  4008. /* Assign all options a second time. */
  4009. retval = config_get_lines(cf, &cl);
  4010. if (retval < 0) {
  4011. err = SETOPT_ERR_PARSE;
  4012. goto err;
  4013. }
  4014. retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
  4015. config_free_lines(cl);
  4016. if (retval < 0) {
  4017. err = SETOPT_ERR_PARSE;
  4018. goto err;
  4019. }
  4020. retval = config_assign(&options_format, newoptions,
  4021. global_cmdline_options, 0, 0, msg);
  4022. if (retval < 0) {
  4023. err = SETOPT_ERR_PARSE;
  4024. goto err;
  4025. }
  4026. }
  4027. /* Validate newoptions */
  4028. if (options_validate(oldoptions, newoptions, 0, msg) < 0) {
  4029. err = SETOPT_ERR_PARSE; /*XXX make this a separate return value.*/
  4030. goto err;
  4031. }
  4032. if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
  4033. err = SETOPT_ERR_TRANSITION;
  4034. goto err;
  4035. }
  4036. if (set_options(newoptions, msg)) {
  4037. err = SETOPT_ERR_SETTING;
  4038. goto err; /* frees and replaces old options */
  4039. }
  4040. return SETOPT_OK;
  4041. err:
  4042. config_free(&options_format, newoptions);
  4043. if (*msg) {
  4044. char *old_msg = *msg;
  4045. tor_asprintf(msg, "Failed to parse/validate config: %s", old_msg);
  4046. tor_free(old_msg);
  4047. }
  4048. return err;
  4049. }
  4050. /** Return the location for our configuration file.
  4051. */
  4052. const char *
  4053. get_torrc_fname(void)
  4054. {
  4055. if (torrc_fname)
  4056. return torrc_fname;
  4057. else
  4058. return get_default_conf_file();
  4059. }
  4060. /** Adjust the address map based on the MapAddress elements in the
  4061. * configuration <b>options</b>
  4062. */
  4063. void
  4064. config_register_addressmaps(const or_options_t *options)
  4065. {
  4066. smartlist_t *elts;
  4067. config_line_t *opt;
  4068. char *from, *to;
  4069. addressmap_clear_configured();
  4070. elts = smartlist_create();
  4071. for (opt = options->AddressMap; opt; opt = opt->next) {
  4072. smartlist_split_string(elts, opt->value, NULL,
  4073. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  4074. if (smartlist_len(elts) >= 2) {
  4075. from = smartlist_get(elts,0);
  4076. to = smartlist_get(elts,1);
  4077. if (address_is_invalid_destination(to, 1)) {
  4078. log_warn(LD_CONFIG,
  4079. "Skipping invalid argument '%s' to MapAddress", to);
  4080. } else {
  4081. addressmap_register(from, tor_strdup(to), 0, ADDRMAPSRC_TORRC);
  4082. if (smartlist_len(elts)>2) {
  4083. log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
  4084. }
  4085. }
  4086. } else {
  4087. log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
  4088. opt->value);
  4089. }
  4090. SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
  4091. smartlist_clear(elts);
  4092. }
  4093. smartlist_free(elts);
  4094. }
  4095. /**
  4096. * Initialize the logs based on the configuration file.
  4097. */
  4098. static int
  4099. options_init_logs(or_options_t *options, int validate_only)
  4100. {
  4101. config_line_t *opt;
  4102. int ok;
  4103. smartlist_t *elts;
  4104. int daemon =
  4105. #ifdef MS_WINDOWS
  4106. 0;
  4107. #else
  4108. options->RunAsDaemon;
  4109. #endif
  4110. if (options->LogTimeGranularity <= 0) {
  4111. log_warn(LD_CONFIG, "Log time granularity '%d' has to be positive.",
  4112. options->LogTimeGranularity);
  4113. return -1;
  4114. } else if (1000 % options->LogTimeGranularity != 0 &&
  4115. options->LogTimeGranularity % 1000 != 0) {
  4116. int granularity = options->LogTimeGranularity;
  4117. if (granularity < 40) {
  4118. do granularity++;
  4119. while (1000 % granularity != 0);
  4120. } else if (granularity < 1000) {
  4121. granularity = 1000 / granularity;
  4122. while (1000 % granularity != 0)
  4123. granularity--;
  4124. granularity = 1000 / granularity;
  4125. } else {
  4126. granularity = 1000 * ((granularity / 1000) + 1);
  4127. }
  4128. log_warn(LD_CONFIG, "Log time granularity '%d' has to be either a "
  4129. "divisor or a multiple of 1 second. Changing to "
  4130. "'%d'.",
  4131. options->LogTimeGranularity, granularity);
  4132. if (!validate_only)
  4133. set_log_time_granularity(granularity);
  4134. } else {
  4135. if (!validate_only)
  4136. set_log_time_granularity(options->LogTimeGranularity);
  4137. }
  4138. ok = 1;
  4139. elts = smartlist_create();
  4140. for (opt = options->Logs; opt; opt = opt->next) {
  4141. log_severity_list_t *severity;
  4142. const char *cfg = opt->value;
  4143. severity = tor_malloc_zero(sizeof(log_severity_list_t));
  4144. if (parse_log_severity_config(&cfg, severity) < 0) {
  4145. log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
  4146. opt->value);
  4147. ok = 0; goto cleanup;
  4148. }
  4149. smartlist_split_string(elts, cfg, NULL,
  4150. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  4151. if (smartlist_len(elts) == 0)
  4152. smartlist_add(elts, tor_strdup("stdout"));
  4153. if (smartlist_len(elts) == 1 &&
  4154. (!strcasecmp(smartlist_get(elts,0), "stdout") ||
  4155. !strcasecmp(smartlist_get(elts,0), "stderr"))) {
  4156. int err = smartlist_len(elts) &&
  4157. !strcasecmp(smartlist_get(elts,0), "stderr");
  4158. if (!validate_only) {
  4159. if (daemon) {
  4160. log_warn(LD_CONFIG,
  4161. "Can't log to %s with RunAsDaemon set; skipping stdout",
  4162. err?"stderr":"stdout");
  4163. } else {
  4164. add_stream_log(severity, err?"<stderr>":"<stdout>",
  4165. fileno(err?stderr:stdout));
  4166. }
  4167. }
  4168. goto cleanup;
  4169. }
  4170. if (smartlist_len(elts) == 1 &&
  4171. !strcasecmp(smartlist_get(elts,0), "syslog")) {
  4172. #ifdef HAVE_SYSLOG_H
  4173. if (!validate_only) {
  4174. add_syslog_log(severity);
  4175. }
  4176. #else
  4177. log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
  4178. #endif
  4179. goto cleanup;
  4180. }
  4181. if (smartlist_len(elts) == 2 &&
  4182. !strcasecmp(smartlist_get(elts,0), "file")) {
  4183. if (!validate_only) {
  4184. char *fname = expand_filename(smartlist_get(elts, 1));
  4185. if (add_file_log(severity, fname) < 0) {
  4186. log_warn(LD_CONFIG, "Couldn't open file for 'Log %s': %s",
  4187. opt->value, strerror(errno));
  4188. ok = 0;
  4189. }
  4190. tor_free(fname);
  4191. }
  4192. goto cleanup;
  4193. }
  4194. log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
  4195. opt->value);
  4196. ok = 0; goto cleanup;
  4197. cleanup:
  4198. SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
  4199. smartlist_clear(elts);
  4200. tor_free(severity);
  4201. }
  4202. smartlist_free(elts);
  4203. if (ok && !validate_only)
  4204. logs_set_domain_logging(options->LogMessageDomains);
  4205. return ok?0:-1;
  4206. }
  4207. /** Read the contents of a Bridge line from <b>line</b>. Return 0
  4208. * if the line is well-formed, and -1 if it isn't. If
  4209. * <b>validate_only</b> is 0, and the line is well-formed, then add
  4210. * the bridge described in the line to our internal bridge list. */
  4211. static int
  4212. parse_bridge_line(const char *line, int validate_only)
  4213. {
  4214. smartlist_t *items = NULL;
  4215. int r;
  4216. char *addrport=NULL, *fingerprint=NULL;
  4217. char *transport_name=NULL;
  4218. char *field1=NULL;
  4219. tor_addr_t addr;
  4220. uint16_t port = 0;
  4221. char digest[DIGEST_LEN];
  4222. items = smartlist_create();
  4223. smartlist_split_string(items, line, NULL,
  4224. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  4225. if (smartlist_len(items) < 1) {
  4226. log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
  4227. goto err;
  4228. }
  4229. /* field1 is either a transport name or addrport */
  4230. field1 = smartlist_get(items, 0);
  4231. smartlist_del_keeporder(items, 0);
  4232. if (!(strstr(field1, ".") || strstr(field1, ":"))) {
  4233. /* new-style bridge line */
  4234. transport_name = field1;
  4235. if (smartlist_len(items) < 1) {
  4236. log_warn(LD_CONFIG, "Too few items to Bridge line.");
  4237. goto err;
  4238. }
  4239. addrport = smartlist_get(items, 0);
  4240. smartlist_del_keeporder(items, 0);
  4241. } else {
  4242. addrport = field1;
  4243. }
  4244. if (tor_addr_port_lookup(addrport, &addr, &port)<0) {
  4245. log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
  4246. goto err;
  4247. }
  4248. if (!port) {
  4249. log_info(LD_CONFIG,
  4250. "Bridge address '%s' has no port; using default port 443.",
  4251. addrport);
  4252. port = 443;
  4253. }
  4254. if (smartlist_len(items)) {
  4255. fingerprint = smartlist_join_strings(items, "", 0, NULL);
  4256. if (strlen(fingerprint) != HEX_DIGEST_LEN) {
  4257. log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
  4258. goto err;
  4259. }
  4260. if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
  4261. log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
  4262. goto err;
  4263. }
  4264. }
  4265. if (!validate_only) {
  4266. log_debug(LD_DIR, "Bridge at %s:%d (transport: %s) (%s)",
  4267. fmt_addr(&addr), (int)port,
  4268. transport_name ? transport_name : "no transport",
  4269. fingerprint ? fingerprint : "no key listed");
  4270. bridge_add_from_config(&addr, port,
  4271. fingerprint ? digest : NULL, transport_name);
  4272. }
  4273. r = 0;
  4274. goto done;
  4275. err:
  4276. r = -1;
  4277. done:
  4278. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  4279. smartlist_free(items);
  4280. tor_free(addrport);
  4281. tor_free(transport_name);
  4282. tor_free(fingerprint);
  4283. return r;
  4284. }
  4285. /** Read the contents of a ClientTransportPlugin line from
  4286. * <b>line</b>. Return 0 if the line is well-formed, and -1 if it
  4287. * isn't.
  4288. *
  4289. * If <b>validate_only</b> is 0, and the line is well-formed:
  4290. * - If it's an external proxy line, add the transport described in the line to
  4291. * our internal transport list.
  4292. * - If it's a managed proxy line, launch the managed proxy. */
  4293. static int
  4294. parse_client_transport_line(const char *line, int validate_only)
  4295. {
  4296. smartlist_t *items = NULL;
  4297. int r;
  4298. char *field2=NULL;
  4299. const char *transports=NULL;
  4300. smartlist_t *transport_list=NULL;
  4301. char *addrport=NULL;
  4302. tor_addr_t addr;
  4303. uint16_t port = 0;
  4304. int socks_ver=PROXY_NONE;
  4305. /* managed proxy options */
  4306. int is_managed=0;
  4307. char **proxy_argv=NULL;
  4308. char **tmp=NULL;
  4309. int proxy_argc,i;
  4310. int line_length;
  4311. items = smartlist_create();
  4312. smartlist_split_string(items, line, NULL,
  4313. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  4314. line_length = smartlist_len(items);
  4315. if (line_length < 3) {
  4316. log_warn(LD_CONFIG, "Too few arguments on ClientTransportPlugin line.");
  4317. goto err;
  4318. }
  4319. /* Get the first line element, split it to commas into
  4320. transport_list (in case it's multiple transports) and validate
  4321. the transport names. */
  4322. transports = smartlist_get(items, 0);
  4323. transport_list = smartlist_create();
  4324. smartlist_split_string(transport_list, transports, ",",
  4325. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  4326. SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
  4327. if (!string_is_C_identifier(transport_name)) {
  4328. log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
  4329. transport_name);
  4330. goto err;
  4331. }
  4332. } SMARTLIST_FOREACH_END(transport_name);
  4333. /* field2 is either a SOCKS version or "exec" */
  4334. field2 = smartlist_get(items, 1);
  4335. if (!strcmp(field2,"socks4")) {
  4336. socks_ver = PROXY_SOCKS4;
  4337. } else if (!strcmp(field2,"socks5")) {
  4338. socks_ver = PROXY_SOCKS5;
  4339. } else if (!strcmp(field2,"exec")) {
  4340. is_managed=1;
  4341. } else {
  4342. log_warn(LD_CONFIG, "Strange ClientTransportPlugin field '%s'.",
  4343. field2);
  4344. goto err;
  4345. }
  4346. if (is_managed) { /* managed */
  4347. if (!validate_only) { /* if we are not just validating, use the
  4348. rest of the line as the argv of the proxy
  4349. to be launched */
  4350. proxy_argc = line_length-2;
  4351. tor_assert(proxy_argc > 0);
  4352. proxy_argv = tor_malloc_zero(sizeof(char*)*(proxy_argc+1));
  4353. tmp = proxy_argv;
  4354. for (i=0;i<proxy_argc;i++) { /* store arguments */
  4355. *tmp++ = smartlist_get(items, 2);
  4356. smartlist_del_keeporder(items, 2);
  4357. }
  4358. *tmp = NULL; /*terminated with NUL pointer, just like execve() likes it*/
  4359. /* kickstart the thing */
  4360. pt_kickstart_client_proxy(transport_list, proxy_argv);
  4361. }
  4362. } else { /* external */
  4363. if (smartlist_len(transport_list) != 1) {
  4364. log_warn(LD_CONFIG, "You can't have an external proxy with "
  4365. "more than one transports.");
  4366. goto err;
  4367. }
  4368. addrport = smartlist_get(items, 2);
  4369. if (tor_addr_port_lookup(addrport, &addr, &port)<0) {
  4370. log_warn(LD_CONFIG, "Error parsing transport "
  4371. "address '%s'", addrport);
  4372. goto err;
  4373. }
  4374. if (!port) {
  4375. log_warn(LD_CONFIG,
  4376. "Transport address '%s' has no port.", addrport);
  4377. goto err;
  4378. }
  4379. if (!validate_only) {
  4380. transport_add_from_config(&addr, port, smartlist_get(transport_list, 0),
  4381. socks_ver);
  4382. log_info(LD_DIR, "Transport '%s' found at %s:%d",
  4383. transports, fmt_addr(&addr), (int)port);
  4384. }
  4385. }
  4386. r = 0;
  4387. goto done;
  4388. err:
  4389. r = -1;
  4390. done:
  4391. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  4392. smartlist_free(items);
  4393. SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
  4394. smartlist_free(transport_list);
  4395. return r;
  4396. }
  4397. /** Read the contents of a ServerTransportPlugin line from
  4398. * <b>line</b>. Return 0 if the line is well-formed, and -1 if it
  4399. * isn't.
  4400. * If <b>validate_only</b> is 0, the line is well-formed, and it's a
  4401. * managed proxy line, launch the managed proxy. */
  4402. static int
  4403. parse_server_transport_line(const char *line, int validate_only)
  4404. {
  4405. smartlist_t *items = NULL;
  4406. int r;
  4407. const char *transports=NULL;
  4408. smartlist_t *transport_list=NULL;
  4409. char *type=NULL;
  4410. char *addrport=NULL;
  4411. tor_addr_t addr;
  4412. uint16_t port = 0;
  4413. /* managed proxy options */
  4414. int is_managed=0;
  4415. char **proxy_argv=NULL;
  4416. char **tmp=NULL;
  4417. int proxy_argc,i;
  4418. int line_length;
  4419. items = smartlist_create();
  4420. smartlist_split_string(items, line, NULL,
  4421. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  4422. line_length = smartlist_len(items);
  4423. if (line_length < 3) {
  4424. log_warn(LD_CONFIG, "Too few arguments on ServerTransportPlugin line.");
  4425. goto err;
  4426. }
  4427. /* Get the first line element, split it to commas into
  4428. transport_list (in case it's multiple transports) and validate
  4429. the transport names. */
  4430. transports = smartlist_get(items, 0);
  4431. transport_list = smartlist_create();
  4432. smartlist_split_string(transport_list, transports, ",",
  4433. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  4434. SMARTLIST_FOREACH_BEGIN(transport_list, const char *, transport_name) {
  4435. if (!string_is_C_identifier(transport_name)) {
  4436. log_warn(LD_CONFIG, "Transport name is not a C identifier (%s).",
  4437. transport_name);
  4438. goto err;
  4439. }
  4440. } SMARTLIST_FOREACH_END(transport_name);
  4441. type = smartlist_get(items, 1);
  4442. if (!strcmp(type, "exec")) {
  4443. is_managed=1;
  4444. } else if (!strcmp(type, "proxy")) {
  4445. is_managed=0;
  4446. } else {
  4447. log_warn(LD_CONFIG, "Strange ServerTransportPlugin type '%s'", type);
  4448. goto err;
  4449. }
  4450. if (is_managed) { /* managed */
  4451. if (!validate_only) {
  4452. proxy_argc = line_length-2;
  4453. tor_assert(proxy_argc > 0);
  4454. proxy_argv = tor_malloc_zero(sizeof(char*)*(proxy_argc+1));
  4455. tmp = proxy_argv;
  4456. for (i=0;i<proxy_argc;i++) { /* store arguments */
  4457. *tmp++ = smartlist_get(items, 2);
  4458. smartlist_del_keeporder(items, 2);
  4459. }
  4460. *tmp = NULL; /*terminated with NUL pointer, just like execve() likes it*/
  4461. /* kickstart the thing */
  4462. pt_kickstart_server_proxy(transport_list, proxy_argv);
  4463. }
  4464. } else { /* external */
  4465. if (smartlist_len(transport_list) != 1) {
  4466. log_warn(LD_CONFIG, "You can't have an external proxy with "
  4467. "more than one transports.");
  4468. goto err;
  4469. }
  4470. addrport = smartlist_get(items, 2);
  4471. if (tor_addr_port_lookup(addrport, &addr, &port)<0) {
  4472. log_warn(LD_CONFIG, "Error parsing transport "
  4473. "address '%s'", addrport);
  4474. goto err;
  4475. }
  4476. if (!port) {
  4477. log_warn(LD_CONFIG,
  4478. "Transport address '%s' has no port.", addrport);
  4479. goto err;
  4480. }
  4481. if (!validate_only) {
  4482. log_info(LD_DIR, "Server transport '%s' at %s:%d.",
  4483. transports, fmt_addr(&addr), (int)port);
  4484. }
  4485. }
  4486. r = 0;
  4487. goto done;
  4488. err:
  4489. r = -1;
  4490. done:
  4491. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  4492. smartlist_free(items);
  4493. SMARTLIST_FOREACH(transport_list, char*, s, tor_free(s));
  4494. smartlist_free(transport_list);
  4495. return r;
  4496. }
  4497. /** Read the contents of a DirServer line from <b>line</b>. If
  4498. * <b>validate_only</b> is 0, and the line is well-formed, and it
  4499. * shares any bits with <b>required_type</b> or <b>required_type</b>
  4500. * is 0, then add the dirserver described in the line (minus whatever
  4501. * bits it's missing) as a valid authority. Return 0 on success,
  4502. * or -1 if the line isn't well-formed or if we can't add it. */
  4503. static int
  4504. parse_dir_server_line(const char *line, dirinfo_type_t required_type,
  4505. int validate_only)
  4506. {
  4507. smartlist_t *items = NULL;
  4508. int r;
  4509. char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
  4510. uint16_t dir_port = 0, or_port = 0;
  4511. char digest[DIGEST_LEN];
  4512. char v3_digest[DIGEST_LEN];
  4513. dirinfo_type_t type = V2_DIRINFO;
  4514. int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
  4515. items = smartlist_create();
  4516. smartlist_split_string(items, line, NULL,
  4517. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  4518. if (smartlist_len(items) < 1) {
  4519. log_warn(LD_CONFIG, "No arguments on DirServer line.");
  4520. goto err;
  4521. }
  4522. if (is_legal_nickname(smartlist_get(items, 0))) {
  4523. nickname = smartlist_get(items, 0);
  4524. smartlist_del_keeporder(items, 0);
  4525. }
  4526. while (smartlist_len(items)) {
  4527. char *flag = smartlist_get(items, 0);
  4528. if (TOR_ISDIGIT(flag[0]))
  4529. break;
  4530. if (!strcasecmp(flag, "v1")) {
  4531. type |= (V1_DIRINFO | HIDSERV_DIRINFO);
  4532. } else if (!strcasecmp(flag, "hs")) {
  4533. type |= HIDSERV_DIRINFO;
  4534. } else if (!strcasecmp(flag, "no-hs")) {
  4535. is_not_hidserv_authority = 1;
  4536. } else if (!strcasecmp(flag, "bridge")) {
  4537. type |= BRIDGE_DIRINFO;
  4538. } else if (!strcasecmp(flag, "no-v2")) {
  4539. is_not_v2_authority = 1;
  4540. } else if (!strcasecmpstart(flag, "orport=")) {
  4541. int ok;
  4542. char *portstring = flag + strlen("orport=");
  4543. or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
  4544. if (!ok)
  4545. log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
  4546. portstring);
  4547. } else if (!strcasecmpstart(flag, "v3ident=")) {
  4548. char *idstr = flag + strlen("v3ident=");
  4549. if (strlen(idstr) != HEX_DIGEST_LEN ||
  4550. base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
  4551. log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
  4552. flag);
  4553. } else {
  4554. type |= V3_DIRINFO|EXTRAINFO_DIRINFO|MICRODESC_DIRINFO;
  4555. }
  4556. } else {
  4557. log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
  4558. flag);
  4559. }
  4560. tor_free(flag);
  4561. smartlist_del_keeporder(items, 0);
  4562. }
  4563. if (is_not_hidserv_authority)
  4564. type &= ~HIDSERV_DIRINFO;
  4565. if (is_not_v2_authority)
  4566. type &= ~V2_DIRINFO;
  4567. if (smartlist_len(items) < 2) {
  4568. log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
  4569. goto err;
  4570. }
  4571. addrport = smartlist_get(items, 0);
  4572. smartlist_del_keeporder(items, 0);
  4573. if (addr_port_lookup(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
  4574. log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
  4575. goto err;
  4576. }
  4577. if (!dir_port) {
  4578. log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
  4579. goto err;
  4580. }
  4581. fingerprint = smartlist_join_strings(items, "", 0, NULL);
  4582. if (strlen(fingerprint) != HEX_DIGEST_LEN) {
  4583. log_warn(LD_CONFIG, "Key digest for DirServer is wrong length %d.",
  4584. (int)strlen(fingerprint));
  4585. goto err;
  4586. }
  4587. if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
  4588. /* a known bad fingerprint. refuse to use it. We can remove this
  4589. * clause once Tor 0.1.2.17 is obsolete. */
  4590. log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
  4591. "torrc file (%s), or reinstall Tor and use the default torrc.",
  4592. get_torrc_fname());
  4593. goto err;
  4594. }
  4595. if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
  4596. log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
  4597. goto err;
  4598. }
  4599. if (!validate_only && (!required_type || required_type & type)) {
  4600. if (required_type)
  4601. type &= required_type; /* pare down what we think of them as an
  4602. * authority for. */
  4603. log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
  4604. address, (int)dir_port, (char*)smartlist_get(items,0));
  4605. if (!add_trusted_dir_server(nickname, address, dir_port, or_port,
  4606. digest, v3_digest, type))
  4607. goto err;
  4608. }
  4609. r = 0;
  4610. goto done;
  4611. err:
  4612. r = -1;
  4613. done:
  4614. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  4615. smartlist_free(items);
  4616. tor_free(addrport);
  4617. tor_free(address);
  4618. tor_free(nickname);
  4619. tor_free(fingerprint);
  4620. return r;
  4621. }
  4622. /** Free all storage held in <b>port</b> */
  4623. static void
  4624. port_cfg_free(port_cfg_t *port)
  4625. {
  4626. tor_free(port);
  4627. }
  4628. /** Warn for every port in <b>ports</b> that is on a publicly routable
  4629. * address. */
  4630. static void
  4631. warn_nonlocal_client_ports(const smartlist_t *ports, const char *portname)
  4632. {
  4633. SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
  4634. if (port->is_unix_addr) {
  4635. /* Unix sockets aren't accessible over a network. */
  4636. } else if (!tor_addr_is_internal(&port->addr, 1)) {
  4637. log_warn(LD_CONFIG, "You specified a public address for %sPort. "
  4638. "Other people on the Internet might find your computer and "
  4639. "use it as an open proxy. Please don't allow this unless you "
  4640. "have a good reason.", portname);
  4641. } else if (!tor_addr_is_loopback(&port->addr)) {
  4642. log_notice(LD_CONFIG, "You configured a non-loopback address for "
  4643. "%sPort. This allows everybody on your local network to use "
  4644. "your machine as a proxy. Make sure this is what you wanted.",
  4645. portname);
  4646. }
  4647. } SMARTLIST_FOREACH_END(port);
  4648. }
  4649. #define CL_PORT_NO_OPTIONS (1u<<0)
  4650. #define CL_PORT_WARN_NONLOCAL (1u<<1)
  4651. #define CL_PORT_ALLOW_EXTRA_LISTENADDR (1u<<2)
  4652. /**
  4653. * Parse port configuration for a single client port type.
  4654. *
  4655. * Read entries of the "FooPort" type from the list <b>ports</b>, and
  4656. * entries of the "FooListenAddress" type from the list
  4657. * <b>listenaddrs</b>. Two syntaxes are supported: a legacy syntax
  4658. * where FooPort is at most a single entry containing a port number and
  4659. * where FooListenAddress has any number of address:port combinations;
  4660. * and a new syntax where there are no FooListenAddress entries and
  4661. * where FooPort can have any number of entries of the format
  4662. * "[Address:][Port] IsolationOptions".
  4663. *
  4664. * In log messages, describe the port type as <b>portname</b>.
  4665. *
  4666. * If no address is specified, default to <b>defaultaddr</b>. If no
  4667. * FooPort is given, default to defaultport (if 0, there is no default).
  4668. *
  4669. * If CL_PORT_NO_OPTIONS is set in <b>flags</b>, do not allow stream
  4670. * isolation options in the FooPort entries.
  4671. *
  4672. * If CL_PORT_WARN_NONLOCAL is set in <b>flags</b>, warn if any of the
  4673. * ports are not on a local address.
  4674. *
  4675. * Unless CL_PORT_ALLOW_EXTRA_LISTENADDR is set in <b>flags</b>, warn
  4676. * if FooListenAddress is set but FooPort is 0.
  4677. *
  4678. * On success, if <b>out</b> is given, add a new port_cfg_t entry to
  4679. * <b>out</b> for every port that the client should listen on. Return 0
  4680. * on success, -1 on failure.
  4681. */
  4682. static int
  4683. parse_client_port_config(smartlist_t *out,
  4684. const config_line_t *ports,
  4685. const config_line_t *listenaddrs,
  4686. const char *portname,
  4687. int listener_type,
  4688. const char *defaultaddr,
  4689. int defaultport,
  4690. unsigned flags)
  4691. {
  4692. smartlist_t *elts;
  4693. int retval = -1;
  4694. const unsigned allow_client_options = !(flags & CL_PORT_NO_OPTIONS);
  4695. const unsigned warn_nonlocal = flags & CL_PORT_WARN_NONLOCAL;
  4696. const unsigned allow_spurious_listenaddr =
  4697. flags & CL_PORT_ALLOW_EXTRA_LISTENADDR;
  4698. /* FooListenAddress is deprecated; let's make it work like it used to work,
  4699. * though. */
  4700. if (listenaddrs) {
  4701. int mainport = defaultport;
  4702. if (ports && ports->next) {
  4703. log_warn(LD_CONFIG, "%sListenAddress can't be used when there are "
  4704. "multiple %sPort lines", portname, portname);
  4705. return -1;
  4706. } else if (ports) {
  4707. if (!strcmp(ports->value, "auto")) {
  4708. mainport = CFG_AUTO_PORT;
  4709. } else {
  4710. int ok;
  4711. mainport = (int)tor_parse_long(ports->value, 10, 0, 65535, &ok, NULL);
  4712. if (!ok) {
  4713. log_warn(LD_CONFIG, "%sListenAddress can only be used with a single "
  4714. "%sPort with value \"auto\" or 1-65535.",
  4715. portname, portname);
  4716. return -1;
  4717. }
  4718. }
  4719. }
  4720. if (mainport == 0) {
  4721. if (allow_spurious_listenaddr)
  4722. return 1;
  4723. log_warn(LD_CONFIG, "%sPort must be defined if %sListenAddress is used",
  4724. portname, portname);
  4725. return -1;
  4726. }
  4727. for (; listenaddrs; listenaddrs = listenaddrs->next) {
  4728. tor_addr_t addr;
  4729. uint16_t port = 0;
  4730. if (tor_addr_port_lookup(listenaddrs->value, &addr, &port) < 0) {
  4731. log_warn(LD_CONFIG, "Unable to parse %sListenAddress '%s'",
  4732. portname, listenaddrs->value);
  4733. return -1;
  4734. }
  4735. if (out) {
  4736. port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t));
  4737. cfg->type = listener_type;
  4738. cfg->port = port ? port : mainport;
  4739. tor_addr_copy(&cfg->addr, &addr);
  4740. cfg->session_group = SESSION_GROUP_UNSET;
  4741. cfg->isolation_flags = ISO_DEFAULT;
  4742. smartlist_add(out, cfg);
  4743. }
  4744. }
  4745. if (warn_nonlocal && out)
  4746. warn_nonlocal_client_ports(out, portname);
  4747. return 0;
  4748. } /* end if (listenaddrs) */
  4749. /* No ListenAddress lines. If there's no FooPort, then maybe make a default
  4750. * one. */
  4751. if (! ports) {
  4752. if (defaultport && out) {
  4753. port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t));
  4754. cfg->type = listener_type;
  4755. cfg->port = defaultport;
  4756. tor_addr_parse(&cfg->addr, defaultaddr);
  4757. cfg->session_group = SESSION_GROUP_UNSET;
  4758. cfg->isolation_flags = ISO_DEFAULT;
  4759. smartlist_add(out, cfg);
  4760. }
  4761. return 0;
  4762. }
  4763. /* At last we can actually parse the FooPort lines. The syntax is:
  4764. * [Addr:](Port|auto) [Options].*/
  4765. elts = smartlist_create();
  4766. for (; ports; ports = ports->next) {
  4767. tor_addr_t addr;
  4768. int port;
  4769. int sessiongroup = SESSION_GROUP_UNSET;
  4770. unsigned isolation = ISO_DEFAULT;
  4771. char *addrport;
  4772. uint16_t ptmp=0;
  4773. int ok;
  4774. smartlist_split_string(elts, ports->value, NULL,
  4775. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  4776. if (smartlist_len(elts) == 0) {
  4777. log_warn(LD_CONFIG, "Invalid %sPort line with no value", portname);
  4778. goto err;
  4779. }
  4780. if (!allow_client_options && smartlist_len(elts) > 1) {
  4781. log_warn(LD_CONFIG, "Too many options on %sPort line", portname);
  4782. goto err;
  4783. }
  4784. /* Now parse the addr/port value */
  4785. addrport = smartlist_get(elts, 0);
  4786. if (!strcmp(addrport, "auto")) {
  4787. port = CFG_AUTO_PORT;
  4788. tor_addr_parse(&addr, defaultaddr);
  4789. } else if (!strcasecmpend(addrport, ":auto")) {
  4790. char *addrtmp = tor_strndup(addrport, strlen(addrport)-5);
  4791. port = CFG_AUTO_PORT;
  4792. if (tor_addr_port_lookup(addrtmp, &addr, &ptmp)<0 || ptmp) {
  4793. log_warn(LD_CONFIG, "Invalid address '%s' for %sPort",
  4794. escaped(addrport), portname);
  4795. tor_free(addrtmp);
  4796. goto err;
  4797. }
  4798. } else {
  4799. /* Try parsing integer port before address, because, who knows?
  4800. "9050" might be a valid address. */
  4801. port = (int) tor_parse_long(addrport, 10, 0, 65535, &ok, NULL);
  4802. if (ok) {
  4803. tor_addr_parse(&addr, defaultaddr);
  4804. } else if (tor_addr_port_lookup(addrport, &addr, &ptmp) == 0) {
  4805. if (ptmp == 0) {
  4806. log_warn(LD_CONFIG, "%sPort line has address but no port", portname);
  4807. goto err;
  4808. }
  4809. port = ptmp;
  4810. } else {
  4811. log_warn(LD_CONFIG, "Couldn't parse address '%s' for %sPort",
  4812. escaped(addrport), portname);
  4813. goto err;
  4814. }
  4815. }
  4816. /* Now parse the rest of the options, if any. */
  4817. SMARTLIST_FOREACH_BEGIN(elts, char *, elt) {
  4818. int no = 0, isoflag = 0;
  4819. const char *elt_orig = elt;
  4820. if (elt_sl_idx == 0)
  4821. continue; /* Skip addr:port */
  4822. if (!strcasecmpstart(elt, "SessionGroup=")) {
  4823. int group = (int)tor_parse_long(elt+strlen("SessionGroup="),
  4824. 10, 0, INT_MAX, &ok, NULL);
  4825. if (!ok) {
  4826. log_warn(LD_CONFIG, "Invalid %sPort option '%s'",
  4827. portname, escaped(elt));
  4828. goto err;
  4829. }
  4830. if (sessiongroup >= 0) {
  4831. log_warn(LD_CONFIG, "Multiple SessionGroup options on %sPort",
  4832. portname);
  4833. goto err;
  4834. }
  4835. sessiongroup = group;
  4836. continue;
  4837. }
  4838. if (!strcasecmpstart(elt, "No")) {
  4839. no = 1;
  4840. elt += 2;
  4841. }
  4842. if (!strcasecmpend(elt, "s"))
  4843. elt[strlen(elt)-1] = '\0'; /* kill plurals. */
  4844. if (!strcasecmp(elt, "IsolateDestPort")) {
  4845. isoflag = ISO_DESTPORT;
  4846. } else if (!strcasecmp(elt, "IsolateDestAddr")) {
  4847. isoflag = ISO_DESTADDR;
  4848. } else if (!strcasecmp(elt, "IsolateSOCKSAuth")) {
  4849. isoflag = ISO_SOCKSAUTH;
  4850. } else if (!strcasecmp(elt, "IsolateClientProtocol")) {
  4851. isoflag = ISO_CLIENTPROTO;
  4852. } else if (!strcasecmp(elt, "IsolateClientAddr")) {
  4853. isoflag = ISO_CLIENTADDR;
  4854. } else {
  4855. log_warn(LD_CONFIG, "Unrecognized %sPort option '%s'",
  4856. portname, escaped(elt_orig));
  4857. }
  4858. if (no) {
  4859. isolation &= ~isoflag;
  4860. } else {
  4861. isolation |= isoflag;
  4862. }
  4863. } SMARTLIST_FOREACH_END(elt);
  4864. if (out && port) {
  4865. port_cfg_t *cfg = tor_malloc_zero(sizeof(port_cfg_t));
  4866. cfg->type = listener_type;
  4867. cfg->port = port;
  4868. tor_addr_copy(&cfg->addr, &addr);
  4869. cfg->session_group = sessiongroup;
  4870. cfg->isolation_flags = isolation;
  4871. smartlist_add(out, cfg);
  4872. }
  4873. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  4874. smartlist_clear(elts);
  4875. }
  4876. if (warn_nonlocal && out)
  4877. warn_nonlocal_client_ports(out, portname);
  4878. retval = 0;
  4879. err:
  4880. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  4881. smartlist_free(elts);
  4882. return retval;
  4883. }
  4884. /** Parse all client port types (Socks, DNS, Trans, NATD) from
  4885. * <b>options</b>. On success, set *<b>n_ports_out</b> to the number of
  4886. * ports that are listed and return 0. On failure, set *<b>msg</b> to a
  4887. * description of the problem and return -1.
  4888. *
  4889. * If <b>validate_only</b> is false, set configured_client_ports to the
  4890. * new list of ports parsed from <b>options</b>.
  4891. **/
  4892. static int
  4893. parse_client_ports(const or_options_t *options, int validate_only,
  4894. char **msg, int *n_ports_out)
  4895. {
  4896. smartlist_t *ports;
  4897. int retval = -1;
  4898. ports = smartlist_create();
  4899. *n_ports_out = 0;
  4900. if (parse_client_port_config(ports,
  4901. options->SocksPort, options->SocksListenAddress,
  4902. "Socks", CONN_TYPE_AP_LISTENER,
  4903. "127.0.0.1", 9050,
  4904. CL_PORT_WARN_NONLOCAL|CL_PORT_ALLOW_EXTRA_LISTENADDR) < 0) {
  4905. *msg = tor_strdup("Invalid SocksPort/SocksListenAddress configuration");
  4906. goto err;
  4907. }
  4908. if (parse_client_port_config(ports,
  4909. options->DNSPort, options->DNSListenAddress,
  4910. "DNS", CONN_TYPE_AP_DNS_LISTENER,
  4911. "127.0.0.1", 0,
  4912. CL_PORT_WARN_NONLOCAL) < 0) {
  4913. *msg = tor_strdup("Invalid DNSPort/DNSListenAddress configuration");
  4914. goto err;
  4915. }
  4916. if (parse_client_port_config(ports,
  4917. options->TransPort, options->TransListenAddress,
  4918. "Trans", CONN_TYPE_AP_TRANS_LISTENER,
  4919. "127.0.0.1", 0,
  4920. CL_PORT_WARN_NONLOCAL) < 0) {
  4921. *msg = tor_strdup("Invalid TransPort/TransListenAddress configuration");
  4922. goto err;
  4923. }
  4924. if (parse_client_port_config(ports,
  4925. options->NATDPort, options->NATDListenAddress,
  4926. "NATD", CONN_TYPE_AP_NATD_LISTENER,
  4927. "127.0.0.1", 0,
  4928. CL_PORT_WARN_NONLOCAL) < 0) {
  4929. *msg = tor_strdup("Invalid NatdPort/NatdListenAddress configuration");
  4930. goto err;
  4931. }
  4932. *n_ports_out = smartlist_len(ports);
  4933. if (!validate_only) {
  4934. if (configured_client_ports) {
  4935. SMARTLIST_FOREACH(configured_client_ports,
  4936. port_cfg_t *, p, port_cfg_free(p));
  4937. smartlist_free(configured_client_ports);
  4938. }
  4939. configured_client_ports = ports;
  4940. ports = NULL; /* prevent free below. */
  4941. }
  4942. retval = 0;
  4943. err:
  4944. if (ports) {
  4945. SMARTLIST_FOREACH(ports, port_cfg_t *, p, port_cfg_free(p));
  4946. smartlist_free(ports);
  4947. }
  4948. return retval;
  4949. }
  4950. /** Return a list of port_cfg_t for client ports parsed from the
  4951. * options. */
  4952. const smartlist_t *
  4953. get_configured_client_ports(void)
  4954. {
  4955. if (!configured_client_ports)
  4956. configured_client_ports = smartlist_create();
  4957. return configured_client_ports;
  4958. }
  4959. /** Adjust the value of options->DataDirectory, or fill it in if it's
  4960. * absent. Return 0 on success, -1 on failure. */
  4961. static int
  4962. normalize_data_directory(or_options_t *options)
  4963. {
  4964. #ifdef MS_WINDOWS
  4965. char *p;
  4966. if (options->DataDirectory)
  4967. return 0; /* all set */
  4968. p = tor_malloc(MAX_PATH);
  4969. strlcpy(p,get_windows_conf_root(),MAX_PATH);
  4970. options->DataDirectory = p;
  4971. return 0;
  4972. #else
  4973. const char *d = options->DataDirectory;
  4974. if (!d)
  4975. d = "~/.tor";
  4976. if (strncmp(d,"~/",2) == 0) {
  4977. char *fn = expand_filename(d);
  4978. if (!fn) {
  4979. log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
  4980. return -1;
  4981. }
  4982. if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
  4983. /* If our homedir is /, we probably don't want to use it. */
  4984. /* Default to LOCALSTATEDIR/tor which is probably closer to what we
  4985. * want. */
  4986. log_warn(LD_CONFIG,
  4987. "Default DataDirectory is \"~/.tor\". This expands to "
  4988. "\"%s\", which is probably not what you want. Using "
  4989. "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
  4990. tor_free(fn);
  4991. fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
  4992. }
  4993. tor_free(options->DataDirectory);
  4994. options->DataDirectory = fn;
  4995. }
  4996. return 0;
  4997. #endif
  4998. }
  4999. /** Check and normalize the value of options->DataDirectory; return 0 if it
  5000. * is sane, -1 otherwise. */
  5001. static int
  5002. validate_data_directory(or_options_t *options)
  5003. {
  5004. if (normalize_data_directory(options) < 0)
  5005. return -1;
  5006. tor_assert(options->DataDirectory);
  5007. if (strlen(options->DataDirectory) > (512-128)) {
  5008. log_warn(LD_CONFIG, "DataDirectory is too long.");
  5009. return -1;
  5010. }
  5011. return 0;
  5012. }
  5013. /** This string must remain the same forevermore. It is how we
  5014. * recognize that the torrc file doesn't need to be backed up. */
  5015. #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
  5016. "if you edit it, comments will not be preserved"
  5017. /** This string can change; it tries to give the reader an idea
  5018. * that editing this file by hand is not a good plan. */
  5019. #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
  5020. "to torrc.orig.1 or similar, and Tor will ignore it"
  5021. /** Save a configuration file for the configuration in <b>options</b>
  5022. * into the file <b>fname</b>. If the file already exists, and
  5023. * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
  5024. * replace it. Return 0 on success, -1 on failure. */
  5025. static int
  5026. write_configuration_file(const char *fname, const or_options_t *options)
  5027. {
  5028. char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
  5029. int rename_old = 0, r;
  5030. tor_assert(fname);
  5031. switch (file_status(fname)) {
  5032. case FN_FILE:
  5033. old_val = read_file_to_str(fname, 0, NULL);
  5034. if (!old_val || strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
  5035. rename_old = 1;
  5036. }
  5037. tor_free(old_val);
  5038. break;
  5039. case FN_NOENT:
  5040. break;
  5041. case FN_ERROR:
  5042. case FN_DIR:
  5043. default:
  5044. log_warn(LD_CONFIG,
  5045. "Config file \"%s\" is not a file? Failing.", fname);
  5046. return -1;
  5047. }
  5048. if (!(new_conf = options_dump(options, 1))) {
  5049. log_warn(LD_BUG, "Couldn't get configuration string");
  5050. goto err;
  5051. }
  5052. tor_asprintf(&new_val, "%s\n%s\n\n%s",
  5053. GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
  5054. if (rename_old) {
  5055. int i = 1;
  5056. size_t fn_tmp_len = strlen(fname)+32;
  5057. char *fn_tmp;
  5058. tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
  5059. fn_tmp = tor_malloc(fn_tmp_len);
  5060. while (1) {
  5061. if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
  5062. log_warn(LD_BUG, "tor_snprintf failed inexplicably");
  5063. tor_free(fn_tmp);
  5064. goto err;
  5065. }
  5066. if (file_status(fn_tmp) == FN_NOENT)
  5067. break;
  5068. ++i;
  5069. }
  5070. log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
  5071. if (rename(fname, fn_tmp) < 0) {
  5072. log_warn(LD_FS,
  5073. "Couldn't rename configuration file \"%s\" to \"%s\": %s",
  5074. fname, fn_tmp, strerror(errno));
  5075. tor_free(fn_tmp);
  5076. goto err;
  5077. }
  5078. tor_free(fn_tmp);
  5079. }
  5080. if (write_str_to_file(fname, new_val, 0) < 0)
  5081. goto err;
  5082. r = 0;
  5083. goto done;
  5084. err:
  5085. r = -1;
  5086. done:
  5087. tor_free(new_val);
  5088. tor_free(new_conf);
  5089. return r;
  5090. }
  5091. /**
  5092. * Save the current configuration file value to disk. Return 0 on
  5093. * success, -1 on failure.
  5094. **/
  5095. int
  5096. options_save_current(void)
  5097. {
  5098. /* This fails if we can't write to our configuration file.
  5099. *
  5100. * If we try falling back to datadirectory or something, we have a better
  5101. * chance of saving the configuration, but a better chance of doing
  5102. * something the user never expected. */
  5103. return write_configuration_file(get_torrc_fname(), get_options());
  5104. }
  5105. /** Mapping from a unit name to a multiplier for converting that unit into a
  5106. * base unit. Used by config_parse_unit. */
  5107. struct unit_table_t {
  5108. const char *unit; /**< The name of the unit */
  5109. uint64_t multiplier; /**< How many of the base unit appear in this unit */
  5110. };
  5111. /** Table to map the names of memory units to the number of bytes they
  5112. * contain. */
  5113. static struct unit_table_t memory_units[] = {
  5114. { "", 1 },
  5115. { "b", 1<< 0 },
  5116. { "byte", 1<< 0 },
  5117. { "bytes", 1<< 0 },
  5118. { "kb", 1<<10 },
  5119. { "kbyte", 1<<10 },
  5120. { "kbytes", 1<<10 },
  5121. { "kilobyte", 1<<10 },
  5122. { "kilobytes", 1<<10 },
  5123. { "m", 1<<20 },
  5124. { "mb", 1<<20 },
  5125. { "mbyte", 1<<20 },
  5126. { "mbytes", 1<<20 },
  5127. { "megabyte", 1<<20 },
  5128. { "megabytes", 1<<20 },
  5129. { "gb", 1<<30 },
  5130. { "gbyte", 1<<30 },
  5131. { "gbytes", 1<<30 },
  5132. { "gigabyte", 1<<30 },
  5133. { "gigabytes", 1<<30 },
  5134. { "tb", U64_LITERAL(1)<<40 },
  5135. { "terabyte", U64_LITERAL(1)<<40 },
  5136. { "terabytes", U64_LITERAL(1)<<40 },
  5137. { NULL, 0 },
  5138. };
  5139. /** Table to map the names of time units to the number of seconds they
  5140. * contain. */
  5141. static struct unit_table_t time_units[] = {
  5142. { "", 1 },
  5143. { "second", 1 },
  5144. { "seconds", 1 },
  5145. { "minute", 60 },
  5146. { "minutes", 60 },
  5147. { "hour", 60*60 },
  5148. { "hours", 60*60 },
  5149. { "day", 24*60*60 },
  5150. { "days", 24*60*60 },
  5151. { "week", 7*24*60*60 },
  5152. { "weeks", 7*24*60*60 },
  5153. { NULL, 0 },
  5154. };
  5155. /** Table to map the names of time units to the number of milliseconds
  5156. * they contain. */
  5157. static struct unit_table_t time_msec_units[] = {
  5158. { "", 1 },
  5159. { "msec", 1 },
  5160. { "millisecond", 1 },
  5161. { "milliseconds", 1 },
  5162. { "second", 1000 },
  5163. { "seconds", 1000 },
  5164. { "minute", 60*1000 },
  5165. { "minutes", 60*1000 },
  5166. { "hour", 60*60*1000 },
  5167. { "hours", 60*60*1000 },
  5168. { "day", 24*60*60*1000 },
  5169. { "days", 24*60*60*1000 },
  5170. { "week", 7*24*60*60*1000 },
  5171. { "weeks", 7*24*60*60*1000 },
  5172. { NULL, 0 },
  5173. };
  5174. /** Parse a string <b>val</b> containing a number, zero or more
  5175. * spaces, and an optional unit string. If the unit appears in the
  5176. * table <b>u</b>, then multiply the number by the unit multiplier.
  5177. * On success, set *<b>ok</b> to 1 and return this product.
  5178. * Otherwise, set *<b>ok</b> to 0.
  5179. */
  5180. static uint64_t
  5181. config_parse_units(const char *val, struct unit_table_t *u, int *ok)
  5182. {
  5183. uint64_t v = 0;
  5184. double d = 0;
  5185. int use_float = 0;
  5186. char *cp;
  5187. tor_assert(ok);
  5188. v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
  5189. if (!*ok || (cp && *cp == '.')) {
  5190. d = tor_parse_double(val, 0, UINT64_MAX, ok, &cp);
  5191. if (!*ok)
  5192. goto done;
  5193. use_float = 1;
  5194. }
  5195. if (!cp) {
  5196. *ok = 1;
  5197. v = use_float ? DBL_TO_U64(d) : v;
  5198. goto done;
  5199. }
  5200. cp = (char*) eat_whitespace(cp);
  5201. for ( ;u->unit;++u) {
  5202. if (!strcasecmp(u->unit, cp)) {
  5203. if (use_float)
  5204. v = u->multiplier * d;
  5205. else
  5206. v *= u->multiplier;
  5207. *ok = 1;
  5208. goto done;
  5209. }
  5210. }
  5211. log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
  5212. *ok = 0;
  5213. done:
  5214. if (*ok)
  5215. return v;
  5216. else
  5217. return 0;
  5218. }
  5219. /** Parse a string in the format "number unit", where unit is a unit of
  5220. * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
  5221. * and return the number of bytes specified. Otherwise, set
  5222. * *<b>ok</b> to false and return 0. */
  5223. static uint64_t
  5224. config_parse_memunit(const char *s, int *ok)
  5225. {
  5226. uint64_t u = config_parse_units(s, memory_units, ok);
  5227. return u;
  5228. }
  5229. /** Parse a string in the format "number unit", where unit is a unit of
  5230. * time in milliseconds. On success, set *<b>ok</b> to true and return
  5231. * the number of milliseconds in the provided interval. Otherwise, set
  5232. * *<b>ok</b> to 0 and return -1. */
  5233. static int
  5234. config_parse_msec_interval(const char *s, int *ok)
  5235. {
  5236. uint64_t r;
  5237. r = config_parse_units(s, time_msec_units, ok);
  5238. if (!ok)
  5239. return -1;
  5240. if (r > INT_MAX) {
  5241. log_warn(LD_CONFIG, "Msec interval '%s' is too long", s);
  5242. *ok = 0;
  5243. return -1;
  5244. }
  5245. return (int)r;
  5246. }
  5247. /** Parse a string in the format "number unit", where unit is a unit of time.
  5248. * On success, set *<b>ok</b> to true and return the number of seconds in
  5249. * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
  5250. */
  5251. static int
  5252. config_parse_interval(const char *s, int *ok)
  5253. {
  5254. uint64_t r;
  5255. r = config_parse_units(s, time_units, ok);
  5256. if (!ok)
  5257. return -1;
  5258. if (r > INT_MAX) {
  5259. log_warn(LD_CONFIG, "Interval '%s' is too long", s);
  5260. *ok = 0;
  5261. return -1;
  5262. }
  5263. return (int)r;
  5264. }
  5265. /** Return the number of cpus configured in <b>options</b>. If we are
  5266. * told to auto-detect the number of cpus, return the auto-detected number. */
  5267. int
  5268. get_num_cpus(const or_options_t *options)
  5269. {
  5270. if (options->NumCPUs == 0) {
  5271. int n = compute_num_cpus();
  5272. return (n >= 1) ? n : 1;
  5273. } else {
  5274. return options->NumCPUs;
  5275. }
  5276. }
  5277. /**
  5278. * Initialize the libevent library.
  5279. */
  5280. static void
  5281. init_libevent(const or_options_t *options)
  5282. {
  5283. const char *badness=NULL;
  5284. tor_libevent_cfg cfg;
  5285. tor_assert(options);
  5286. configure_libevent_logging();
  5287. /* If the kernel complains that some method (say, epoll) doesn't
  5288. * exist, we don't care about it, since libevent will cope.
  5289. */
  5290. suppress_libevent_log_msg("Function not implemented");
  5291. tor_check_libevent_header_compatibility();
  5292. memset(&cfg, 0, sizeof(cfg));
  5293. cfg.disable_iocp = options->DisableIOCP;
  5294. cfg.num_cpus = get_num_cpus(options);
  5295. cfg.msec_per_tick = options->TokenBucketRefillInterval;
  5296. tor_libevent_initialize(&cfg);
  5297. suppress_libevent_log_msg(NULL);
  5298. tor_check_libevent_version(tor_libevent_get_method(),
  5299. get_options()->ORPort != 0,
  5300. &badness);
  5301. if (badness) {
  5302. const char *v = tor_libevent_get_version_str();
  5303. const char *m = tor_libevent_get_method();
  5304. control_event_general_status(LOG_WARN,
  5305. "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
  5306. v, m, badness);
  5307. }
  5308. }
  5309. /** Return the persistent state struct for this Tor. */
  5310. or_state_t *
  5311. get_or_state(void)
  5312. {
  5313. tor_assert(global_state);
  5314. return global_state;
  5315. }
  5316. /** Return a newly allocated string holding a filename relative to the data
  5317. * directory. If <b>sub1</b> is present, it is the first path component after
  5318. * the data directory. If <b>sub2</b> is also present, it is the second path
  5319. * component after the data directory. If <b>suffix</b> is present, it
  5320. * is appended to the filename.
  5321. *
  5322. * Examples:
  5323. * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
  5324. * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
  5325. * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
  5326. * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
  5327. *
  5328. * Note: Consider using the get_datadir_fname* macros in or.h.
  5329. */
  5330. char *
  5331. options_get_datadir_fname2_suffix(const or_options_t *options,
  5332. const char *sub1, const char *sub2,
  5333. const char *suffix)
  5334. {
  5335. char *fname = NULL;
  5336. size_t len;
  5337. tor_assert(options);
  5338. tor_assert(options->DataDirectory);
  5339. tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
  5340. len = strlen(options->DataDirectory);
  5341. if (sub1) {
  5342. len += strlen(sub1)+1;
  5343. if (sub2)
  5344. len += strlen(sub2)+1;
  5345. }
  5346. if (suffix)
  5347. len += strlen(suffix);
  5348. len++;
  5349. fname = tor_malloc(len);
  5350. if (sub1) {
  5351. if (sub2) {
  5352. tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
  5353. options->DataDirectory, sub1, sub2);
  5354. } else {
  5355. tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
  5356. options->DataDirectory, sub1);
  5357. }
  5358. } else {
  5359. strlcpy(fname, options->DataDirectory, len);
  5360. }
  5361. if (suffix)
  5362. strlcat(fname, suffix, len);
  5363. return fname;
  5364. }
  5365. /** Return true if <b>line</b> is a valid state TransportProxy line.
  5366. * Return false otherwise. */
  5367. static int
  5368. state_transport_line_is_valid(const char *line)
  5369. {
  5370. smartlist_t *items = NULL;
  5371. char *addrport=NULL;
  5372. tor_addr_t addr;
  5373. uint16_t port = 0;
  5374. int r;
  5375. items = smartlist_create();
  5376. smartlist_split_string(items, line, NULL,
  5377. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  5378. if (smartlist_len(items) != 2) {
  5379. log_warn(LD_CONFIG, "state: Not enough arguments in TransportProxy line.");
  5380. goto err;
  5381. }
  5382. addrport = smartlist_get(items, 1);
  5383. if (tor_addr_port_lookup(addrport, &addr, &port) < 0) {
  5384. log_warn(LD_CONFIG, "state: Could not parse addrport.");
  5385. goto err;
  5386. }
  5387. if (!port) {
  5388. log_warn(LD_CONFIG, "state: Transport line did not contain port.");
  5389. goto err;
  5390. }
  5391. r = 1;
  5392. goto done;
  5393. err:
  5394. r = 0;
  5395. done:
  5396. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  5397. smartlist_free(items);
  5398. return r;
  5399. }
  5400. /** Return 0 if all TransportProxy lines in <b>state</b> are well
  5401. * formed. Otherwise, return -1. */
  5402. static int
  5403. validate_transports_in_state(or_state_t *state)
  5404. {
  5405. int broken = 0;
  5406. config_line_t *line;
  5407. for (line = state->TransportProxies ; line ; line = line->next) {
  5408. tor_assert(!strcmp(line->key, "TransportProxy"));
  5409. if (!state_transport_line_is_valid(line->value)<0)
  5410. broken = 1;
  5411. }
  5412. if (broken)
  5413. log_warn(LD_CONFIG, "state: State file seems to be broken.");
  5414. return 0;
  5415. }
  5416. /** Return 0 if every setting in <b>state</b> is reasonable, and a
  5417. * permissible transition from <b>old_state</b>. Else warn and return -1.
  5418. * Should have no side effects, except for normalizing the contents of
  5419. * <b>state</b>.
  5420. */
  5421. /* XXX from_setconf is here because of bug 238 */
  5422. static int
  5423. or_state_validate(or_state_t *old_state, or_state_t *state,
  5424. int from_setconf, char **msg)
  5425. {
  5426. /* We don't use these; only options do. Still, we need to match that
  5427. * signature. */
  5428. (void) from_setconf;
  5429. (void) old_state;
  5430. if (entry_guards_parse_state(state, 0, msg)<0)
  5431. return -1;
  5432. if (validate_transports_in_state(state)<0)
  5433. return -1;
  5434. return 0;
  5435. }
  5436. /** Replace the current persistent state with <b>new_state</b> */
  5437. static int
  5438. or_state_set(or_state_t *new_state)
  5439. {
  5440. char *err = NULL;
  5441. int ret = 0;
  5442. tor_assert(new_state);
  5443. config_free(&state_format, global_state);
  5444. global_state = new_state;
  5445. if (entry_guards_parse_state(global_state, 1, &err)<0) {
  5446. log_warn(LD_GENERAL,"%s",err);
  5447. tor_free(err);
  5448. ret = -1;
  5449. }
  5450. if (rep_hist_load_state(global_state, &err)<0) {
  5451. log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
  5452. tor_free(err);
  5453. ret = -1;
  5454. }
  5455. if (circuit_build_times_parse_state(&circ_times, global_state) < 0) {
  5456. ret = -1;
  5457. }
  5458. return ret;
  5459. }
  5460. /**
  5461. * Save a broken state file to a backup location.
  5462. */
  5463. static void
  5464. or_state_save_broken(char *fname)
  5465. {
  5466. int i;
  5467. file_status_t status;
  5468. size_t len = strlen(fname)+16;
  5469. char *fname2 = tor_malloc(len);
  5470. for (i = 0; i < 100; ++i) {
  5471. tor_snprintf(fname2, len, "%s.%d", fname, i);
  5472. status = file_status(fname2);
  5473. if (status == FN_NOENT)
  5474. break;
  5475. }
  5476. if (i == 100) {
  5477. log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
  5478. "state files to move aside. Discarding the old state file.",
  5479. fname);
  5480. unlink(fname);
  5481. } else {
  5482. log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
  5483. "to \"%s\". This could be a bug in Tor; please tell "
  5484. "the developers.", fname, fname2);
  5485. if (rename(fname, fname2) < 0) {
  5486. log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
  5487. "OS gave an error of %s", strerror(errno));
  5488. }
  5489. }
  5490. tor_free(fname2);
  5491. }
  5492. /** Reload the persistent state from disk, generating a new state as needed.
  5493. * Return 0 on success, less than 0 on failure.
  5494. */
  5495. static int
  5496. or_state_load(void)
  5497. {
  5498. or_state_t *new_state = NULL;
  5499. char *contents = NULL, *fname;
  5500. char *errmsg = NULL;
  5501. int r = -1, badstate = 0;
  5502. fname = get_datadir_fname("state");
  5503. switch (file_status(fname)) {
  5504. case FN_FILE:
  5505. if (!(contents = read_file_to_str(fname, 0, NULL))) {
  5506. log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
  5507. goto done;
  5508. }
  5509. break;
  5510. case FN_NOENT:
  5511. break;
  5512. case FN_ERROR:
  5513. case FN_DIR:
  5514. default:
  5515. log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
  5516. goto done;
  5517. }
  5518. new_state = tor_malloc_zero(sizeof(or_state_t));
  5519. new_state->_magic = OR_STATE_MAGIC;
  5520. config_init(&state_format, new_state);
  5521. if (contents) {
  5522. config_line_t *lines=NULL;
  5523. int assign_retval;
  5524. if (config_get_lines(contents, &lines)<0)
  5525. goto done;
  5526. assign_retval = config_assign(&state_format, new_state,
  5527. lines, 0, 0, &errmsg);
  5528. config_free_lines(lines);
  5529. if (assign_retval<0)
  5530. badstate = 1;
  5531. if (errmsg) {
  5532. log_warn(LD_GENERAL, "%s", errmsg);
  5533. tor_free(errmsg);
  5534. }
  5535. }
  5536. if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
  5537. badstate = 1;
  5538. if (errmsg) {
  5539. log_warn(LD_GENERAL, "%s", errmsg);
  5540. tor_free(errmsg);
  5541. }
  5542. if (badstate && !contents) {
  5543. log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
  5544. " This is a bug in Tor.");
  5545. goto done;
  5546. } else if (badstate && contents) {
  5547. or_state_save_broken(fname);
  5548. tor_free(contents);
  5549. config_free(&state_format, new_state);
  5550. new_state = tor_malloc_zero(sizeof(or_state_t));
  5551. new_state->_magic = OR_STATE_MAGIC;
  5552. config_init(&state_format, new_state);
  5553. } else if (contents) {
  5554. log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
  5555. } else {
  5556. log_info(LD_GENERAL, "Initialized state");
  5557. }
  5558. if (or_state_set(new_state) == -1) {
  5559. or_state_save_broken(fname);
  5560. }
  5561. new_state = NULL;
  5562. if (!contents) {
  5563. global_state->next_write = 0;
  5564. or_state_save(time(NULL));
  5565. }
  5566. r = 0;
  5567. done:
  5568. tor_free(fname);
  5569. tor_free(contents);
  5570. if (new_state)
  5571. config_free(&state_format, new_state);
  5572. return r;
  5573. }
  5574. /** Did the last time we tried to write the state file fail? If so, we
  5575. * should consider disabling such features as preemptive circuit generation
  5576. * to compute circuit-build-time. */
  5577. static int last_state_file_write_failed = 0;
  5578. /** Return whether the state file failed to write last time we tried. */
  5579. int
  5580. did_last_state_file_write_fail(void)
  5581. {
  5582. return last_state_file_write_failed;
  5583. }
  5584. /** If writing the state to disk fails, try again after this many seconds. */
  5585. #define STATE_WRITE_RETRY_INTERVAL 3600
  5586. /** If we're a relay, how often should we checkpoint our state file even
  5587. * if nothing else dirties it? This will checkpoint ongoing stats like
  5588. * bandwidth used, per-country user stats, etc. */
  5589. #define STATE_RELAY_CHECKPOINT_INTERVAL (12*60*60)
  5590. /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
  5591. int
  5592. or_state_save(time_t now)
  5593. {
  5594. char *state, *contents;
  5595. char tbuf[ISO_TIME_LEN+1];
  5596. char *fname;
  5597. tor_assert(global_state);
  5598. if (global_state->next_write > now)
  5599. return 0;
  5600. /* Call everything else that might dirty the state even more, in order
  5601. * to avoid redundant writes. */
  5602. entry_guards_update_state(global_state);
  5603. rep_hist_update_state(global_state);
  5604. circuit_build_times_update_state(&circ_times, global_state);
  5605. if (accounting_is_enabled(get_options()))
  5606. accounting_run_housekeeping(now);
  5607. global_state->LastWritten = now;
  5608. tor_free(global_state->TorVersion);
  5609. tor_asprintf(&global_state->TorVersion, "Tor %s", get_version());
  5610. state = config_dump(&state_format, global_state, 1, 0);
  5611. format_local_iso_time(tbuf, now);
  5612. tor_asprintf(&contents,
  5613. "# Tor state file last generated on %s local time\n"
  5614. "# Other times below are in GMT\n"
  5615. "# You *do not* need to edit this file.\n\n%s",
  5616. tbuf, state);
  5617. tor_free(state);
  5618. fname = get_datadir_fname("state");
  5619. if (write_str_to_file(fname, contents, 0)<0) {
  5620. log_warn(LD_FS, "Unable to write state to file \"%s\"; "
  5621. "will try again later", fname);
  5622. last_state_file_write_failed = 1;
  5623. tor_free(fname);
  5624. tor_free(contents);
  5625. /* Try again after STATE_WRITE_RETRY_INTERVAL (or sooner, if the state
  5626. * changes sooner). */
  5627. global_state->next_write = now + STATE_WRITE_RETRY_INTERVAL;
  5628. return -1;
  5629. }
  5630. last_state_file_write_failed = 0;
  5631. log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
  5632. tor_free(fname);
  5633. tor_free(contents);
  5634. if (server_mode(get_options()))
  5635. global_state->next_write = now + STATE_RELAY_CHECKPOINT_INTERVAL;
  5636. else
  5637. global_state->next_write = TIME_MAX;
  5638. return 0;
  5639. }
  5640. /** Return the config line for transport <b>transport</b> in the current state.
  5641. * Return NULL if there is no config line for <b>transport</b>. */
  5642. static config_line_t *
  5643. get_transport_in_state_by_name(const char *transport)
  5644. {
  5645. or_state_t *or_state = get_or_state();
  5646. config_line_t *line;
  5647. config_line_t *ret = NULL;
  5648. smartlist_t *items = NULL;
  5649. for (line = or_state->TransportProxies ; line ; line = line->next) {
  5650. tor_assert(!strcmp(line->key, "TransportProxy"));
  5651. items = smartlist_create();
  5652. smartlist_split_string(items, line->value, NULL,
  5653. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  5654. if (smartlist_len(items) != 2) /* broken state */
  5655. goto done;
  5656. if (!strcmp(smartlist_get(items, 0), transport)) {
  5657. ret = line;
  5658. goto done;
  5659. }
  5660. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  5661. smartlist_free(items);
  5662. items = NULL;
  5663. }
  5664. done:
  5665. if (items) {
  5666. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  5667. smartlist_free(items);
  5668. }
  5669. return ret;
  5670. }
  5671. /** Return string containing the address:port part of the
  5672. * TransportProxy <b>line</b> for transport <b>transport</b>.
  5673. * If the line is corrupted, return NULL. */
  5674. static const char *
  5675. get_transport_bindaddr(const char *line, const char *transport)
  5676. {
  5677. char *line_tmp = NULL;
  5678. if (strlen(line) < strlen(transport) + 2) {
  5679. goto broken_state;
  5680. } else {
  5681. /* line should start with the name of the transport and a space.
  5682. (for example, "obfs2 127.0.0.1:47245") */
  5683. tor_asprintf(&line_tmp, "%s ", transport);
  5684. if (strcmpstart(line, line_tmp))
  5685. goto broken_state;
  5686. tor_free(line_tmp);
  5687. return (line+strlen(transport)+1);
  5688. }
  5689. broken_state:
  5690. tor_free(line_tmp);
  5691. return NULL;
  5692. }
  5693. /** Return a static string containing the address:port a proxy
  5694. * transport should bind on. */
  5695. const char *
  5696. get_bindaddr_for_transport(const char *transport)
  5697. {
  5698. static const char default_addrport[] = "127.0.0.1:0";
  5699. const char *bindaddr = NULL;
  5700. config_line_t *line = get_transport_in_state_by_name(transport);
  5701. if (!line)
  5702. return default_addrport;
  5703. bindaddr = get_transport_bindaddr(line->value, transport);
  5704. return bindaddr ? bindaddr : default_addrport;
  5705. }
  5706. /** Save <b>transport</b> listening on <b>addr</b>:<b>port</b> to
  5707. state */
  5708. void
  5709. save_transport_to_state(const char *transport,
  5710. const tor_addr_t *addr, uint16_t port)
  5711. {
  5712. or_state_t *state = get_or_state();
  5713. char *transport_addrport=NULL;
  5714. /** find where to write on the state */
  5715. config_line_t **next, *line;
  5716. /* see if this transport is already stored in state */
  5717. config_line_t *transport_line =
  5718. get_transport_in_state_by_name(transport);
  5719. if (transport_line) { /* if transport already exists in state... */
  5720. const char *prev_bindaddr = /* get its addrport... */
  5721. get_transport_bindaddr(transport_line->value, transport);
  5722. tor_asprintf(&transport_addrport, "%s:%d", fmt_addr(addr), (int)port);
  5723. /* if transport in state has the same address as this one, life is good */
  5724. if (!strcmp(prev_bindaddr, transport_addrport)) {
  5725. log_info(LD_CONFIG, "Transport seems to have spawned on its usual "
  5726. "address:port.");
  5727. goto done;
  5728. } else { /* if addrport in state is different than the one we got */
  5729. log_info(LD_CONFIG, "Transport seems to have spawned on different "
  5730. "address:port. Let's update the state file with the new "
  5731. "address:port");
  5732. tor_free(transport_line->value); /* free the old line */
  5733. tor_asprintf(&transport_line->value, "%s %s:%d", transport,
  5734. fmt_addr(addr),
  5735. (int) port); /* replace old addrport line with new line */
  5736. }
  5737. } else { /* never seen this one before; save it in state for next time */
  5738. log_info(LD_CONFIG, "It's the first time we see this transport. "
  5739. "Let's save its address:port");
  5740. next = &state->TransportProxies;
  5741. /* find the last TransportProxy line in the state and point 'next'
  5742. right after it */
  5743. line = state->TransportProxies;
  5744. while (line) {
  5745. next = &(line->next);
  5746. line = line->next;
  5747. }
  5748. /* allocate space for the new line and fill it in */
  5749. *next = line = tor_malloc_zero(sizeof(config_line_t));
  5750. line->key = tor_strdup("TransportProxy");
  5751. tor_asprintf(&line->value, "%s %s:%d", transport,
  5752. fmt_addr(addr), (int) port);
  5753. next = &(line->next);
  5754. }
  5755. if (!get_options()->AvoidDiskWrites)
  5756. or_state_mark_dirty(state, 0);
  5757. done:
  5758. tor_free(transport_addrport);
  5759. }
  5760. /** Given a file name check to see whether the file exists but has not been
  5761. * modified for a very long time. If so, remove it. */
  5762. void
  5763. remove_file_if_very_old(const char *fname, time_t now)
  5764. {
  5765. #define VERY_OLD_FILE_AGE (28*24*60*60)
  5766. struct stat st;
  5767. if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
  5768. char buf[ISO_TIME_LEN+1];
  5769. format_local_iso_time(buf, st.st_mtime);
  5770. log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
  5771. "Removing it.", fname, buf);
  5772. unlink(fname);
  5773. }
  5774. }
  5775. /** Helper to implement GETINFO functions about configuration variables (not
  5776. * their values). Given a "config/names" question, set *<b>answer</b> to a
  5777. * new string describing the supported configuration variables and their
  5778. * types. */
  5779. int
  5780. getinfo_helper_config(control_connection_t *conn,
  5781. const char *question, char **answer,
  5782. const char **errmsg)
  5783. {
  5784. (void) conn;
  5785. (void) errmsg;
  5786. if (!strcmp(question, "config/names")) {
  5787. smartlist_t *sl = smartlist_create();
  5788. int i;
  5789. for (i = 0; _option_vars[i].name; ++i) {
  5790. const config_var_t *var = &_option_vars[i];
  5791. const char *type;
  5792. char *line;
  5793. switch (var->type) {
  5794. case CONFIG_TYPE_STRING: type = "String"; break;
  5795. case CONFIG_TYPE_FILENAME: type = "Filename"; break;
  5796. case CONFIG_TYPE_UINT: type = "Integer"; break;
  5797. case CONFIG_TYPE_PORT: type = "Port"; break;
  5798. case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
  5799. case CONFIG_TYPE_MSEC_INTERVAL: type = "TimeMsecInterval"; break;
  5800. case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
  5801. case CONFIG_TYPE_DOUBLE: type = "Float"; break;
  5802. case CONFIG_TYPE_BOOL: type = "Boolean"; break;
  5803. case CONFIG_TYPE_AUTOBOOL: type = "Boolean+Auto"; break;
  5804. case CONFIG_TYPE_ISOTIME: type = "Time"; break;
  5805. case CONFIG_TYPE_ROUTERSET: type = "RouterList"; break;
  5806. case CONFIG_TYPE_CSV: type = "CommaList"; break;
  5807. case CONFIG_TYPE_LINELIST: type = "LineList"; break;
  5808. case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
  5809. case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
  5810. default:
  5811. case CONFIG_TYPE_OBSOLETE:
  5812. type = NULL; break;
  5813. }
  5814. if (!type)
  5815. continue;
  5816. tor_asprintf(&line, "%s %s\n",var->name,type);
  5817. smartlist_add(sl, line);
  5818. }
  5819. *answer = smartlist_join_strings(sl, "", 0, NULL);
  5820. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  5821. smartlist_free(sl);
  5822. }
  5823. return 0;
  5824. }