config.c 297 KB

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