config.c 239 KB

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