config.c 158 KB

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