config.c 158 KB

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