config.c 149 KB

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