config.c 168 KB

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