config.c 288 KB

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