config.c 159 KB

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