config.c 192 KB

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