config.c 269 KB

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