config.c 152 KB

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