config.c 237 KB

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