config.c 233 KB

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