config.c 171 KB

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