config.c 149 KB

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