config.c 165 KB

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