config.c 239 KB

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