config.c 155 KB

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