config.c 285 KB

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