config.c 297 KB

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