config.c 158 KB

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