config.c 158 KB

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