config.c 155 KB

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