config.c 168 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053
  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.
  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. i += 1; /* command-line option. ignore it. */
  1243. continue;
  1244. } else if (!strcmp(argv[i],"--nt-service") ||
  1245. !strcmp(argv[i],"-nt-service")) {
  1246. i += 1;
  1247. continue;
  1248. }
  1249. if (i == argc-1) {
  1250. log_warn(LD_CONFIG,"Command-line option '%s' with no value. Failing.",
  1251. argv[i]);
  1252. config_free_lines(front);
  1253. return -1;
  1254. }
  1255. *new = tor_malloc_zero(sizeof(config_line_t));
  1256. s = argv[i];
  1257. while (*s == '-')
  1258. s++;
  1259. (*new)->key = tor_strdup(expand_abbrev(&options_format, s, 1, 1));
  1260. (*new)->value = tor_strdup(argv[i+1]);
  1261. (*new)->next = NULL;
  1262. log(LOG_DEBUG, LD_CONFIG, "Commandline: parsed keyword '%s', value '%s'",
  1263. (*new)->key, (*new)->value);
  1264. new = &((*new)->next);
  1265. i += 2;
  1266. }
  1267. *result = front;
  1268. return 0;
  1269. }
  1270. /** Helper: allocate a new configuration option mapping 'key' to 'val',
  1271. * append it to *<b>lst</b>. */
  1272. static void
  1273. config_line_append(config_line_t **lst,
  1274. const char *key,
  1275. const char *val)
  1276. {
  1277. config_line_t *newline;
  1278. newline = tor_malloc(sizeof(config_line_t));
  1279. newline->key = tor_strdup(key);
  1280. newline->value = tor_strdup(val);
  1281. newline->next = NULL;
  1282. while (*lst)
  1283. lst = &((*lst)->next);
  1284. (*lst) = newline;
  1285. }
  1286. /** Helper: parse the config string and strdup into key/value
  1287. * strings. Set *result to the list, or NULL if parsing the string
  1288. * failed. Return 0 on success, -1 on failure. Warn and ignore any
  1289. * misformatted lines. */
  1290. int
  1291. config_get_lines(const char *string, config_line_t **result)
  1292. {
  1293. config_line_t *list = NULL, **next;
  1294. char *k, *v;
  1295. next = &list;
  1296. do {
  1297. string = parse_config_line_from_str(string, &k, &v);
  1298. if (!string) {
  1299. config_free_lines(list);
  1300. return -1;
  1301. }
  1302. if (k && v) {
  1303. /* This list can get long, so we keep a pointer to the end of it
  1304. * rather than using config_line_append over and over and getting
  1305. * n^2 performance. */
  1306. *next = tor_malloc(sizeof(config_line_t));
  1307. (*next)->key = k;
  1308. (*next)->value = v;
  1309. (*next)->next = NULL;
  1310. next = &((*next)->next);
  1311. } else {
  1312. tor_free(k);
  1313. tor_free(v);
  1314. }
  1315. } while (*string);
  1316. *result = list;
  1317. return 0;
  1318. }
  1319. /**
  1320. * Free all the configuration lines on the linked list <b>front</b>.
  1321. */
  1322. void
  1323. config_free_lines(config_line_t *front)
  1324. {
  1325. config_line_t *tmp;
  1326. while (front) {
  1327. tmp = front;
  1328. front = tmp->next;
  1329. tor_free(tmp->key);
  1330. tor_free(tmp->value);
  1331. tor_free(tmp);
  1332. }
  1333. }
  1334. /** Return the description for a given configuration variable, or NULL if no
  1335. * description exists. */
  1336. static const char *
  1337. config_find_description(config_format_t *fmt, const char *name)
  1338. {
  1339. int i;
  1340. for (i=0; fmt->descriptions[i].name; ++i) {
  1341. if (!strcasecmp(name, fmt->descriptions[i].name))
  1342. return fmt->descriptions[i].description;
  1343. }
  1344. return NULL;
  1345. }
  1346. /** If <b>key</b> is a configuration option, return the corresponding
  1347. * config_var_t. Otherwise, if <b>key</b> is a non-standard abbreviation,
  1348. * warn, and return the corresponding config_var_t. Otherwise return NULL.
  1349. */
  1350. static config_var_t *
  1351. config_find_option(config_format_t *fmt, const char *key)
  1352. {
  1353. int i;
  1354. size_t keylen = strlen(key);
  1355. if (!keylen)
  1356. return NULL; /* if they say "--" on the commandline, it's not an option */
  1357. /* First, check for an exact (case-insensitive) match */
  1358. for (i=0; fmt->vars[i].name; ++i) {
  1359. if (!strcasecmp(key, fmt->vars[i].name)) {
  1360. return &fmt->vars[i];
  1361. }
  1362. }
  1363. /* If none, check for an abbreviated match */
  1364. for (i=0; fmt->vars[i].name; ++i) {
  1365. if (!strncasecmp(key, fmt->vars[i].name, keylen)) {
  1366. log_warn(LD_CONFIG, "The abbreviation '%s' is deprecated. "
  1367. "Please use '%s' instead",
  1368. key, fmt->vars[i].name);
  1369. return &fmt->vars[i];
  1370. }
  1371. }
  1372. /* Okay, unrecognized option */
  1373. return NULL;
  1374. }
  1375. /*
  1376. * Functions to assign config options.
  1377. */
  1378. /** <b>c</b>-\>key is known to be a real key. Update <b>options</b>
  1379. * with <b>c</b>-\>value and return 0, or return -1 if bad value.
  1380. *
  1381. * Called from config_assign_line() and option_reset().
  1382. */
  1383. static int
  1384. config_assign_value(config_format_t *fmt, or_options_t *options,
  1385. config_line_t *c, char **msg)
  1386. {
  1387. int i, r, ok;
  1388. char buf[1024];
  1389. config_var_t *var;
  1390. void *lvalue;
  1391. CHECK(fmt, options);
  1392. var = config_find_option(fmt, c->key);
  1393. tor_assert(var);
  1394. lvalue = STRUCT_VAR_P(options, var->var_offset);
  1395. switch (var->type) {
  1396. case CONFIG_TYPE_UINT:
  1397. i = (int)tor_parse_long(c->value, 10, 0, INT_MAX, &ok, NULL);
  1398. if (!ok) {
  1399. r = tor_snprintf(buf, sizeof(buf),
  1400. "Int keyword '%s %s' is malformed or out of bounds.",
  1401. c->key, c->value);
  1402. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  1403. return -1;
  1404. }
  1405. *(int *)lvalue = i;
  1406. break;
  1407. case CONFIG_TYPE_INTERVAL: {
  1408. i = config_parse_interval(c->value, &ok);
  1409. if (!ok) {
  1410. r = tor_snprintf(buf, sizeof(buf),
  1411. "Interval '%s %s' is malformed or out of bounds.",
  1412. c->key, c->value);
  1413. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  1414. return -1;
  1415. }
  1416. *(int *)lvalue = i;
  1417. break;
  1418. }
  1419. case CONFIG_TYPE_MEMUNIT: {
  1420. uint64_t u64 = config_parse_memunit(c->value, &ok);
  1421. if (!ok) {
  1422. r = tor_snprintf(buf, sizeof(buf),
  1423. "Value '%s %s' is malformed or out of bounds.",
  1424. c->key, c->value);
  1425. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  1426. return -1;
  1427. }
  1428. *(uint64_t *)lvalue = u64;
  1429. break;
  1430. }
  1431. case CONFIG_TYPE_BOOL:
  1432. i = (int)tor_parse_long(c->value, 10, 0, 1, &ok, NULL);
  1433. if (!ok) {
  1434. r = tor_snprintf(buf, sizeof(buf),
  1435. "Boolean '%s %s' expects 0 or 1.",
  1436. c->key, c->value);
  1437. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  1438. return -1;
  1439. }
  1440. *(int *)lvalue = i;
  1441. break;
  1442. case CONFIG_TYPE_STRING:
  1443. tor_free(*(char **)lvalue);
  1444. *(char **)lvalue = tor_strdup(c->value);
  1445. break;
  1446. case CONFIG_TYPE_DOUBLE:
  1447. *(double *)lvalue = atof(c->value);
  1448. break;
  1449. case CONFIG_TYPE_ISOTIME:
  1450. if (parse_iso_time(c->value, (time_t *)lvalue)) {
  1451. r = tor_snprintf(buf, sizeof(buf),
  1452. "Invalid time '%s' for keyword '%s'", c->value, c->key);
  1453. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  1454. return -1;
  1455. }
  1456. break;
  1457. case CONFIG_TYPE_CSV:
  1458. if (*(smartlist_t**)lvalue) {
  1459. SMARTLIST_FOREACH(*(smartlist_t**)lvalue, char *, cp, tor_free(cp));
  1460. smartlist_clear(*(smartlist_t**)lvalue);
  1461. } else {
  1462. *(smartlist_t**)lvalue = smartlist_create();
  1463. }
  1464. smartlist_split_string(*(smartlist_t**)lvalue, c->value, ",",
  1465. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1466. break;
  1467. case CONFIG_TYPE_LINELIST:
  1468. case CONFIG_TYPE_LINELIST_S:
  1469. config_line_append((config_line_t**)lvalue, c->key, c->value);
  1470. break;
  1471. case CONFIG_TYPE_OBSOLETE:
  1472. log_warn(LD_CONFIG, "Skipping obsolete configuration option '%s'", c->key);
  1473. break;
  1474. case CONFIG_TYPE_LINELIST_V:
  1475. r = tor_snprintf(buf, sizeof(buf),
  1476. "You may not provide a value for virtual option '%s'", c->key);
  1477. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  1478. return -1;
  1479. default:
  1480. tor_assert(0);
  1481. break;
  1482. }
  1483. return 0;
  1484. }
  1485. /** If <b>c</b> is a syntactically valid configuration line, update
  1486. * <b>options</b> with its value and return 0. Otherwise return -1 for bad
  1487. * key, -2 for bad value.
  1488. *
  1489. * If <b>clear_first</b> is set, clear the value first. Then if
  1490. * <b>use_defaults</b> is set, set the value to the default.
  1491. *
  1492. * Called from config_assign().
  1493. */
  1494. static int
  1495. config_assign_line(config_format_t *fmt, or_options_t *options,
  1496. config_line_t *c, int use_defaults,
  1497. int clear_first, char **msg)
  1498. {
  1499. config_var_t *var;
  1500. CHECK(fmt, options);
  1501. var = config_find_option(fmt, c->key);
  1502. if (!var) {
  1503. if (fmt->extra) {
  1504. void *lvalue = STRUCT_VAR_P(options, fmt->extra->var_offset);
  1505. log_info(LD_CONFIG,
  1506. "Found unrecognized option '%s'; saving it.", c->key);
  1507. config_line_append((config_line_t**)lvalue, c->key, c->value);
  1508. return 0;
  1509. } else {
  1510. char buf[1024];
  1511. int tmp = tor_snprintf(buf, sizeof(buf),
  1512. "Unknown option '%s'. Failing.", c->key);
  1513. *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
  1514. return -1;
  1515. }
  1516. }
  1517. /* Put keyword into canonical case. */
  1518. if (strcmp(var->name, c->key)) {
  1519. tor_free(c->key);
  1520. c->key = tor_strdup(var->name);
  1521. }
  1522. if (!strlen(c->value)) {
  1523. /* reset or clear it, then return */
  1524. if (!clear_first) {
  1525. if (var->type == CONFIG_TYPE_LINELIST ||
  1526. var->type == CONFIG_TYPE_LINELIST_S) {
  1527. /* We got an empty linelist from the torrc or commandline.
  1528. As a special case, call this an error. Warn and ignore. */
  1529. log_warn(LD_CONFIG,
  1530. "Linelist option '%s' has no value. Skipping.", c->key);
  1531. } else { /* not already cleared */
  1532. option_reset(fmt, options, var, use_defaults);
  1533. }
  1534. }
  1535. return 0;
  1536. }
  1537. if (config_assign_value(fmt, options, c, msg) < 0)
  1538. return -2;
  1539. return 0;
  1540. }
  1541. /** Restore the option named <b>key</b> in options to its default value.
  1542. * Called from config_assign(). */
  1543. static void
  1544. config_reset_line(config_format_t *fmt, or_options_t *options,
  1545. const char *key, int use_defaults)
  1546. {
  1547. config_var_t *var;
  1548. CHECK(fmt, options);
  1549. var = config_find_option(fmt, key);
  1550. if (!var)
  1551. return; /* give error on next pass. */
  1552. option_reset(fmt, options, var, use_defaults);
  1553. }
  1554. /** Return true iff key is a valid configuration option. */
  1555. int
  1556. option_is_recognized(const char *key)
  1557. {
  1558. config_var_t *var = config_find_option(&options_format, key);
  1559. return (var != NULL);
  1560. }
  1561. /** Return the canonical name of a configuration option, or NULL
  1562. * if no such option exists. */
  1563. const char *
  1564. option_get_canonical_name(const char *key)
  1565. {
  1566. config_var_t *var = config_find_option(&options_format, key);
  1567. return var ? var->name : NULL;
  1568. }
  1569. /** Return a canonicalized list of the options assigned for key.
  1570. */
  1571. config_line_t *
  1572. option_get_assignment(or_options_t *options, const char *key)
  1573. {
  1574. return get_assigned_option(&options_format, options, key, 1);
  1575. }
  1576. /** Return true iff value needs to be quoted and escaped to be used in
  1577. * a configuration file. */
  1578. static int
  1579. config_value_needs_escape(const char *value)
  1580. {
  1581. if (*value == '\"')
  1582. return 1;
  1583. while (*value) {
  1584. switch (*value)
  1585. {
  1586. case '\r':
  1587. case '\n':
  1588. case '#':
  1589. /* Note: quotes and backspaces need special handling when we are using
  1590. * quotes, not otherwise, so they don't trigger escaping on their
  1591. * own. */
  1592. return 1;
  1593. default:
  1594. if (!TOR_ISPRINT(*value))
  1595. return 1;
  1596. }
  1597. ++value;
  1598. }
  1599. return 0;
  1600. }
  1601. /** Return a newly allocated deep copy of the lines in <b>inp</b>. */
  1602. static config_line_t *
  1603. config_lines_dup(const config_line_t *inp)
  1604. {
  1605. config_line_t *result = NULL;
  1606. config_line_t **next_out = &result;
  1607. while (inp) {
  1608. *next_out = tor_malloc(sizeof(config_line_t));
  1609. (*next_out)->key = tor_strdup(inp->key);
  1610. (*next_out)->value = tor_strdup(inp->value);
  1611. inp = inp->next;
  1612. next_out = &((*next_out)->next);
  1613. }
  1614. (*next_out) = NULL;
  1615. return result;
  1616. }
  1617. /** Return newly allocated line or lines corresponding to <b>key</b> in the
  1618. * configuration <b>options</b>. If <b>escape_val</b> is true and a
  1619. * value needs to be quoted before it's put in a config file, quote and
  1620. * escape that value. Return NULL if no such key exists. */
  1621. static config_line_t *
  1622. get_assigned_option(config_format_t *fmt, or_options_t *options,
  1623. const char *key, int escape_val)
  1624. /* XXXX argument is options, but fmt is provided. Inconsistent. */
  1625. {
  1626. config_var_t *var;
  1627. const void *value;
  1628. char buf[32];
  1629. config_line_t *result;
  1630. tor_assert(options && key);
  1631. CHECK(fmt, options);
  1632. var = config_find_option(fmt, key);
  1633. if (!var) {
  1634. log_warn(LD_CONFIG, "Unknown option '%s'. Failing.", key);
  1635. return NULL;
  1636. }
  1637. value = STRUCT_VAR_P(options, var->var_offset);
  1638. result = tor_malloc_zero(sizeof(config_line_t));
  1639. result->key = tor_strdup(var->name);
  1640. switch (var->type)
  1641. {
  1642. case CONFIG_TYPE_STRING:
  1643. if (*(char**)value) {
  1644. result->value = tor_strdup(*(char**)value);
  1645. } else {
  1646. tor_free(result->key);
  1647. tor_free(result);
  1648. return NULL;
  1649. }
  1650. break;
  1651. case CONFIG_TYPE_ISOTIME:
  1652. if (*(time_t*)value) {
  1653. result->value = tor_malloc(ISO_TIME_LEN+1);
  1654. format_iso_time(result->value, *(time_t*)value);
  1655. } else {
  1656. tor_free(result->key);
  1657. tor_free(result);
  1658. }
  1659. escape_val = 0; /* Can't need escape. */
  1660. break;
  1661. case CONFIG_TYPE_INTERVAL:
  1662. case CONFIG_TYPE_UINT:
  1663. /* This means every or_options_t uint or bool element
  1664. * needs to be an int. Not, say, a uint16_t or char. */
  1665. tor_snprintf(buf, sizeof(buf), "%d", *(int*)value);
  1666. result->value = tor_strdup(buf);
  1667. escape_val = 0; /* Can't need escape. */
  1668. break;
  1669. case CONFIG_TYPE_MEMUNIT:
  1670. tor_snprintf(buf, sizeof(buf), U64_FORMAT,
  1671. U64_PRINTF_ARG(*(uint64_t*)value));
  1672. result->value = tor_strdup(buf);
  1673. escape_val = 0; /* Can't need escape. */
  1674. break;
  1675. case CONFIG_TYPE_DOUBLE:
  1676. tor_snprintf(buf, sizeof(buf), "%f", *(double*)value);
  1677. result->value = tor_strdup(buf);
  1678. escape_val = 0; /* Can't need escape. */
  1679. break;
  1680. case CONFIG_TYPE_BOOL:
  1681. result->value = tor_strdup(*(int*)value ? "1" : "0");
  1682. escape_val = 0; /* Can't need escape. */
  1683. break;
  1684. case CONFIG_TYPE_CSV:
  1685. if (*(smartlist_t**)value)
  1686. result->value =
  1687. smartlist_join_strings(*(smartlist_t**)value, ",", 0, NULL);
  1688. else
  1689. result->value = tor_strdup("");
  1690. break;
  1691. case CONFIG_TYPE_OBSOLETE:
  1692. log_warn(LD_CONFIG,
  1693. "You asked me for the value of an obsolete config option '%s'.",
  1694. key);
  1695. tor_free(result->key);
  1696. tor_free(result);
  1697. return NULL;
  1698. case CONFIG_TYPE_LINELIST_S:
  1699. log_warn(LD_CONFIG,
  1700. "Can't return context-sensitive '%s' on its own", key);
  1701. tor_free(result->key);
  1702. tor_free(result);
  1703. return NULL;
  1704. case CONFIG_TYPE_LINELIST:
  1705. case CONFIG_TYPE_LINELIST_V:
  1706. tor_free(result->key);
  1707. tor_free(result);
  1708. result = config_lines_dup(*(const config_line_t**)value);
  1709. break;
  1710. default:
  1711. tor_free(result->key);
  1712. tor_free(result);
  1713. log_warn(LD_BUG,"Unknown type %d for known key '%s'",
  1714. var->type, key);
  1715. return NULL;
  1716. }
  1717. if (escape_val) {
  1718. config_line_t *line;
  1719. for (line = result; line; line = line->next) {
  1720. if (line->value && config_value_needs_escape(line->value)) {
  1721. char *newval = esc_for_log(line->value);
  1722. tor_free(line->value);
  1723. line->value = newval;
  1724. }
  1725. }
  1726. }
  1727. return result;
  1728. }
  1729. /** Iterate through the linked list of requested options <b>list</b>.
  1730. * For each item, convert as appropriate and assign to <b>options</b>.
  1731. * If an item is unrecognized, set *msg and return -1 immediately,
  1732. * else return 0 for success.
  1733. *
  1734. * If <b>clear_first</b>, interpret config options as replacing (not
  1735. * extending) their previous values. If <b>clear_first</b> is set,
  1736. * then <b>use_defaults</b> to decide if you set to defaults after
  1737. * clearing, or make the value 0 or NULL.
  1738. *
  1739. * Here are the use cases:
  1740. * 1. A non-empty AllowInvalid line in your torrc. Appends to current
  1741. * if linelist, replaces current if csv.
  1742. * 2. An empty AllowInvalid line in your torrc. Should clear it.
  1743. * 3. "RESETCONF AllowInvalid" sets it to default.
  1744. * 4. "SETCONF AllowInvalid" makes it NULL.
  1745. * 5. "SETCONF AllowInvalid=foo" clears it and sets it to "foo".
  1746. *
  1747. * Use_defaults Clear_first
  1748. * 0 0 "append"
  1749. * 1 0 undefined, don't use
  1750. * 0 1 "set to null first"
  1751. * 1 1 "set to defaults first"
  1752. * Return 0 on success, -1 on bad key, -2 on bad value.
  1753. *
  1754. * As an additional special case, if a LINELIST config option has
  1755. * no value and clear_first is 0, then warn and ignore it.
  1756. */
  1757. /*
  1758. There are three call cases for config_assign() currently.
  1759. Case one: Torrc entry
  1760. options_init_from_torrc() calls config_assign(0, 0)
  1761. calls config_assign_line(0, 0).
  1762. if value is empty, calls option_reset(0) and returns.
  1763. calls config_assign_value(), appends.
  1764. Case two: setconf
  1765. options_trial_assign() calls config_assign(0, 1)
  1766. calls config_reset_line(0)
  1767. calls option_reset(0)
  1768. calls option_clear().
  1769. calls config_assign_line(0, 1).
  1770. if value is empty, returns.
  1771. calls config_assign_value(), appends.
  1772. Case three: resetconf
  1773. options_trial_assign() calls config_assign(1, 1)
  1774. calls config_reset_line(1)
  1775. calls option_reset(1)
  1776. calls option_clear().
  1777. calls config_assign_value(default)
  1778. calls config_assign_line(1, 1).
  1779. returns.
  1780. */
  1781. static int
  1782. config_assign(config_format_t *fmt, void *options, config_line_t *list,
  1783. int use_defaults, int clear_first, char **msg)
  1784. {
  1785. config_line_t *p;
  1786. CHECK(fmt, options);
  1787. /* pass 1: normalize keys */
  1788. for (p = list; p; p = p->next) {
  1789. const char *full = expand_abbrev(fmt, p->key, 0, 1);
  1790. if (strcmp(full,p->key)) {
  1791. tor_free(p->key);
  1792. p->key = tor_strdup(full);
  1793. }
  1794. }
  1795. /* pass 2: if we're reading from a resetting source, clear all
  1796. * mentioned config options, and maybe set to their defaults. */
  1797. if (clear_first) {
  1798. for (p = list; p; p = p->next)
  1799. config_reset_line(fmt, options, p->key, use_defaults);
  1800. }
  1801. /* pass 3: assign. */
  1802. while (list) {
  1803. int r;
  1804. if ((r=config_assign_line(fmt, options, list, use_defaults,
  1805. clear_first, msg)))
  1806. return r;
  1807. list = list->next;
  1808. }
  1809. return 0;
  1810. }
  1811. /** Try assigning <b>list</b> to the global options. You do this by duping
  1812. * options, assigning list to the new one, then validating it. If it's
  1813. * ok, then throw out the old one and stick with the new one. Else,
  1814. * revert to old and return failure. Return 0 on success, -1 on bad
  1815. * keys, -2 on bad values, -3 on bad transition, and -4 on failed-to-set.
  1816. *
  1817. * If not success, point *<b>msg</b> to a newly allocated string describing
  1818. * what went wrong.
  1819. */
  1820. int
  1821. options_trial_assign(config_line_t *list, int use_defaults,
  1822. int clear_first, char **msg)
  1823. {
  1824. int r;
  1825. or_options_t *trial_options = options_dup(&options_format, get_options());
  1826. if ((r=config_assign(&options_format, trial_options,
  1827. list, use_defaults, clear_first, msg)) < 0) {
  1828. config_free(&options_format, trial_options);
  1829. return r;
  1830. }
  1831. if (options_validate(get_options(), trial_options, 1, msg) < 0) {
  1832. config_free(&options_format, trial_options);
  1833. return -2;
  1834. }
  1835. if (options_transition_allowed(get_options(), trial_options, msg) < 0) {
  1836. config_free(&options_format, trial_options);
  1837. return -3;
  1838. }
  1839. if (set_options(trial_options, msg)<0) {
  1840. config_free(&options_format, trial_options);
  1841. return -4;
  1842. }
  1843. /* we liked it. put it in place. */
  1844. return 0;
  1845. }
  1846. /** Reset config option <b>var</b> to 0, 0.0, NULL, or the equivalent.
  1847. * Called from option_reset() and config_free(). */
  1848. static void
  1849. option_clear(config_format_t *fmt, or_options_t *options, config_var_t *var)
  1850. {
  1851. void *lvalue = STRUCT_VAR_P(options, var->var_offset);
  1852. (void)fmt; /* unused */
  1853. switch (var->type) {
  1854. case CONFIG_TYPE_STRING:
  1855. tor_free(*(char**)lvalue);
  1856. break;
  1857. case CONFIG_TYPE_DOUBLE:
  1858. *(double*)lvalue = 0.0;
  1859. break;
  1860. case CONFIG_TYPE_ISOTIME:
  1861. *(time_t*)lvalue = 0;
  1862. case CONFIG_TYPE_INTERVAL:
  1863. case CONFIG_TYPE_UINT:
  1864. case CONFIG_TYPE_BOOL:
  1865. *(int*)lvalue = 0;
  1866. break;
  1867. case CONFIG_TYPE_MEMUNIT:
  1868. *(uint64_t*)lvalue = 0;
  1869. break;
  1870. case CONFIG_TYPE_CSV:
  1871. if (*(smartlist_t**)lvalue) {
  1872. SMARTLIST_FOREACH(*(smartlist_t **)lvalue, char *, cp, tor_free(cp));
  1873. smartlist_free(*(smartlist_t **)lvalue);
  1874. *(smartlist_t **)lvalue = NULL;
  1875. }
  1876. break;
  1877. case CONFIG_TYPE_LINELIST:
  1878. case CONFIG_TYPE_LINELIST_S:
  1879. config_free_lines(*(config_line_t **)lvalue);
  1880. *(config_line_t **)lvalue = NULL;
  1881. break;
  1882. case CONFIG_TYPE_LINELIST_V:
  1883. /* handled by linelist_s. */
  1884. break;
  1885. case CONFIG_TYPE_OBSOLETE:
  1886. break;
  1887. }
  1888. }
  1889. /** Clear the option indexed by <b>var</b> in <b>options</b>. Then if
  1890. * <b>use_defaults</b>, set it to its default value.
  1891. * Called by config_init() and option_reset_line() and option_assign_line(). */
  1892. static void
  1893. option_reset(config_format_t *fmt, or_options_t *options,
  1894. config_var_t *var, int use_defaults)
  1895. {
  1896. config_line_t *c;
  1897. char *msg = NULL;
  1898. CHECK(fmt, options);
  1899. option_clear(fmt, options, var); /* clear it first */
  1900. if (!use_defaults)
  1901. return; /* all done */
  1902. if (var->initvalue) {
  1903. c = tor_malloc_zero(sizeof(config_line_t));
  1904. c->key = tor_strdup(var->name);
  1905. c->value = tor_strdup(var->initvalue);
  1906. if (config_assign_value(fmt, options, c, &msg) < 0) {
  1907. log_warn(LD_BUG, "Failed to assign default: %s", msg);
  1908. tor_free(msg); /* if this happens it's a bug */
  1909. }
  1910. config_free_lines(c);
  1911. }
  1912. }
  1913. /** Print a usage message for tor. */
  1914. static void
  1915. print_usage(void)
  1916. {
  1917. printf(
  1918. "Copyright (c) 2001-2004, Roger Dingledine\n"
  1919. "Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson\n"
  1920. "Copyright (c) 2007-2008, The Tor Project, Inc.\n\n"
  1921. "tor -f <torrc> [args]\n"
  1922. "See man page for options, or https://www.torproject.org/ for "
  1923. "documentation.\n");
  1924. }
  1925. /** Print all non-obsolete torrc options. */
  1926. static void
  1927. list_torrc_options(void)
  1928. {
  1929. int i;
  1930. smartlist_t *lines = smartlist_create();
  1931. for (i = 0; _option_vars[i].name; ++i) {
  1932. config_var_t *var = &_option_vars[i];
  1933. const char *desc;
  1934. if (var->type == CONFIG_TYPE_OBSOLETE ||
  1935. var->type == CONFIG_TYPE_LINELIST_V)
  1936. continue;
  1937. desc = config_find_description(&options_format, var->name);
  1938. printf("%s\n", var->name);
  1939. if (desc) {
  1940. wrap_string(lines, desc, 76, " ", " ");
  1941. SMARTLIST_FOREACH(lines, char *, cp, {
  1942. printf("%s", cp);
  1943. tor_free(cp);
  1944. });
  1945. smartlist_clear(lines);
  1946. }
  1947. }
  1948. smartlist_free(lines);
  1949. }
  1950. /** Last value actually set by resolve_my_address. */
  1951. static uint32_t last_resolved_addr = 0;
  1952. /**
  1953. * Based on <b>options-\>Address</b>, guess our public IP address and put it
  1954. * (in host order) into *<b>addr_out</b>. If <b>hostname_out</b> is provided,
  1955. * set *<b>hostname_out</b> to a new string holding the hostname we used to
  1956. * get the address. Return 0 if all is well, or -1 if we can't find a suitable
  1957. * public IP address.
  1958. */
  1959. int
  1960. resolve_my_address(int warn_severity, or_options_t *options,
  1961. uint32_t *addr_out, char **hostname_out)
  1962. {
  1963. struct in_addr in;
  1964. struct hostent *rent;
  1965. char hostname[256];
  1966. int explicit_ip=1;
  1967. int explicit_hostname=1;
  1968. int from_interface=0;
  1969. char tmpbuf[INET_NTOA_BUF_LEN];
  1970. const char *address = options->Address;
  1971. int notice_severity = warn_severity <= LOG_NOTICE ?
  1972. LOG_NOTICE : warn_severity;
  1973. tor_assert(addr_out);
  1974. if (address && *address) {
  1975. strlcpy(hostname, address, sizeof(hostname));
  1976. } else { /* then we need to guess our address */
  1977. explicit_ip = 0; /* it's implicit */
  1978. explicit_hostname = 0; /* it's implicit */
  1979. if (gethostname(hostname, sizeof(hostname)) < 0) {
  1980. log_fn(warn_severity, LD_NET,"Error obtaining local hostname");
  1981. return -1;
  1982. }
  1983. log_debug(LD_CONFIG,"Guessed local host name as '%s'",hostname);
  1984. }
  1985. /* now we know hostname. resolve it and keep only the IP address */
  1986. if (tor_inet_aton(hostname, &in) == 0) {
  1987. /* then we have to resolve it */
  1988. explicit_ip = 0;
  1989. rent = (struct hostent *)gethostbyname(hostname);
  1990. if (!rent) {
  1991. uint32_t interface_ip;
  1992. if (explicit_hostname) {
  1993. log_fn(warn_severity, LD_CONFIG,
  1994. "Could not resolve local Address '%s'. Failing.", hostname);
  1995. return -1;
  1996. }
  1997. log_fn(notice_severity, LD_CONFIG,
  1998. "Could not resolve guessed local hostname '%s'. "
  1999. "Trying something else.", hostname);
  2000. if (get_interface_address(warn_severity, &interface_ip)) {
  2001. log_fn(warn_severity, LD_CONFIG,
  2002. "Could not get local interface IP address. Failing.");
  2003. return -1;
  2004. }
  2005. from_interface = 1;
  2006. in.s_addr = htonl(interface_ip);
  2007. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  2008. log_fn(notice_severity, LD_CONFIG, "Learned IP address '%s' for "
  2009. "local interface. Using that.", tmpbuf);
  2010. strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
  2011. } else {
  2012. tor_assert(rent->h_length == 4);
  2013. memcpy(&in.s_addr, rent->h_addr, rent->h_length);
  2014. if (!explicit_hostname &&
  2015. is_internal_IP(ntohl(in.s_addr), 0)) {
  2016. uint32_t interface_ip;
  2017. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  2018. log_fn(notice_severity, LD_CONFIG, "Guessed local hostname '%s' "
  2019. "resolves to a private IP address (%s). Trying something "
  2020. "else.", hostname, tmpbuf);
  2021. if (get_interface_address(warn_severity, &interface_ip)) {
  2022. log_fn(warn_severity, LD_CONFIG,
  2023. "Could not get local interface IP address. Too bad.");
  2024. } else if (is_internal_IP(interface_ip, 0)) {
  2025. struct in_addr in2;
  2026. in2.s_addr = htonl(interface_ip);
  2027. tor_inet_ntoa(&in2,tmpbuf,sizeof(tmpbuf));
  2028. log_fn(notice_severity, LD_CONFIG,
  2029. "Interface IP address '%s' is a private address too. "
  2030. "Ignoring.", tmpbuf);
  2031. } else {
  2032. from_interface = 1;
  2033. in.s_addr = htonl(interface_ip);
  2034. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  2035. log_fn(notice_severity, LD_CONFIG,
  2036. "Learned IP address '%s' for local interface."
  2037. " Using that.", tmpbuf);
  2038. strlcpy(hostname, "<guessed from interfaces>", sizeof(hostname));
  2039. }
  2040. }
  2041. }
  2042. }
  2043. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  2044. if (is_internal_IP(ntohl(in.s_addr), 0) &&
  2045. options->_PublishServerDescriptor) {
  2046. /* make sure we're ok with publishing an internal IP */
  2047. if (!options->DirServers && !options->AlternateDirAuthority) {
  2048. /* if they are using the default dirservers, disallow internal IPs
  2049. * always. */
  2050. log_fn(warn_severity, LD_CONFIG,
  2051. "Address '%s' resolves to private IP address '%s'. "
  2052. "Tor servers that use the default DirServers must have public "
  2053. "IP addresses.", hostname, tmpbuf);
  2054. return -1;
  2055. }
  2056. if (!explicit_ip) {
  2057. /* even if they've set their own dirservers, require an explicit IP if
  2058. * they're using an internal address. */
  2059. log_fn(warn_severity, LD_CONFIG, "Address '%s' resolves to private "
  2060. "IP address '%s'. Please set the Address config option to be "
  2061. "the IP address you want to use.", hostname, tmpbuf);
  2062. return -1;
  2063. }
  2064. }
  2065. log_debug(LD_CONFIG, "Resolved Address to '%s'.", tmpbuf);
  2066. *addr_out = ntohl(in.s_addr);
  2067. if (last_resolved_addr && last_resolved_addr != *addr_out) {
  2068. /* Leave this as a notice, regardless of the requested severity,
  2069. * at least until dynamic IP address support becomes bulletproof. */
  2070. log_notice(LD_NET,
  2071. "Your IP address seems to have changed to %s. Updating.",
  2072. tmpbuf);
  2073. ip_address_changed(0);
  2074. }
  2075. if (last_resolved_addr != *addr_out) {
  2076. const char *method;
  2077. const char *h = hostname;
  2078. if (explicit_ip) {
  2079. method = "CONFIGURED";
  2080. h = NULL;
  2081. } else if (explicit_hostname) {
  2082. method = "RESOLVED";
  2083. } else if (from_interface) {
  2084. method = "INTERFACE";
  2085. h = NULL;
  2086. } else {
  2087. method = "GETHOSTNAME";
  2088. }
  2089. control_event_server_status(LOG_NOTICE,
  2090. "EXTERNAL_ADDRESS ADDRESS=%s METHOD=%s %s%s",
  2091. tmpbuf, method, h?"HOSTNAME=":"", h);
  2092. }
  2093. last_resolved_addr = *addr_out;
  2094. if (hostname_out)
  2095. *hostname_out = tor_strdup(hostname);
  2096. return 0;
  2097. }
  2098. /** Return true iff <b>ip</b> (in host order) is judged to be on the
  2099. * same network as us, or on a private network.
  2100. */
  2101. int
  2102. is_local_IP(uint32_t ip)
  2103. {
  2104. if (is_internal_IP(ip, 0))
  2105. return 1;
  2106. /* Check whether ip is on the same /24 as we are. */
  2107. if (get_options()->EnforceDistinctSubnets == 0)
  2108. return 0;
  2109. /* It's possible that this next check will hit before the first time
  2110. * resolve_my_address actually succeeds. (For clients, it is likely that
  2111. * resolve_my_address will never be called at all). In those cases,
  2112. * last_resolved_addr will be 0, and so checking to see whether ip is on the
  2113. * same /24 as last_resolved_addr will be the same as checking whether it
  2114. * was on net 0, which is already done by is_internal_IP.
  2115. */
  2116. if ((last_resolved_addr & 0xffffff00ul) == (ip & 0xffffff00ul))
  2117. return 1;
  2118. return 0;
  2119. }
  2120. /** Called when we don't have a nickname set. Try to guess a good nickname
  2121. * based on the hostname, and return it in a newly allocated string. If we
  2122. * can't, return NULL and let the caller warn if it wants to. */
  2123. static char *
  2124. get_default_nickname(void)
  2125. {
  2126. static const char * const bad_default_nicknames[] = {
  2127. "localhost",
  2128. NULL,
  2129. };
  2130. char localhostname[256];
  2131. char *cp, *out, *outp;
  2132. int i;
  2133. if (gethostname(localhostname, sizeof(localhostname)) < 0)
  2134. return NULL;
  2135. /* Put it in lowercase; stop at the first dot. */
  2136. if ((cp = strchr(localhostname, '.')))
  2137. *cp = '\0';
  2138. tor_strlower(localhostname);
  2139. /* Strip invalid characters. */
  2140. cp = localhostname;
  2141. out = outp = tor_malloc(strlen(localhostname) + 1);
  2142. while (*cp) {
  2143. if (strchr(LEGAL_NICKNAME_CHARACTERS, *cp))
  2144. *outp++ = *cp++;
  2145. else
  2146. cp++;
  2147. }
  2148. *outp = '\0';
  2149. /* Enforce length. */
  2150. if (strlen(out) > MAX_NICKNAME_LEN)
  2151. out[MAX_NICKNAME_LEN]='\0';
  2152. /* Check for dumb names. */
  2153. for (i = 0; bad_default_nicknames[i]; ++i) {
  2154. if (!strcmp(out, bad_default_nicknames[i])) {
  2155. tor_free(out);
  2156. return NULL;
  2157. }
  2158. }
  2159. return out;
  2160. }
  2161. /** Release storage held by <b>options</b>. */
  2162. static void
  2163. config_free(config_format_t *fmt, void *options)
  2164. {
  2165. int i;
  2166. tor_assert(options);
  2167. for (i=0; fmt->vars[i].name; ++i)
  2168. option_clear(fmt, options, &(fmt->vars[i]));
  2169. if (fmt->extra) {
  2170. config_line_t **linep = STRUCT_VAR_P(options, fmt->extra->var_offset);
  2171. config_free_lines(*linep);
  2172. *linep = NULL;
  2173. }
  2174. tor_free(options);
  2175. }
  2176. /** Return true iff a and b contain identical keys and values in identical
  2177. * order. */
  2178. static int
  2179. config_lines_eq(config_line_t *a, config_line_t *b)
  2180. {
  2181. while (a && b) {
  2182. if (strcasecmp(a->key, b->key) || strcmp(a->value, b->value))
  2183. return 0;
  2184. a = a->next;
  2185. b = b->next;
  2186. }
  2187. if (a || b)
  2188. return 0;
  2189. return 1;
  2190. }
  2191. /** Return true iff the option <b>name</b> has the same value in <b>o1</b>
  2192. * and <b>o2</b>. Must not be called for LINELIST_S or OBSOLETE options.
  2193. */
  2194. static int
  2195. option_is_same(config_format_t *fmt,
  2196. or_options_t *o1, or_options_t *o2, const char *name)
  2197. {
  2198. config_line_t *c1, *c2;
  2199. int r = 1;
  2200. CHECK(fmt, o1);
  2201. CHECK(fmt, o2);
  2202. c1 = get_assigned_option(fmt, o1, name, 0);
  2203. c2 = get_assigned_option(fmt, o2, name, 0);
  2204. r = config_lines_eq(c1, c2);
  2205. config_free_lines(c1);
  2206. config_free_lines(c2);
  2207. return r;
  2208. }
  2209. /** Copy storage held by <b>old</b> into a new or_options_t and return it. */
  2210. static or_options_t *
  2211. options_dup(config_format_t *fmt, or_options_t *old)
  2212. {
  2213. or_options_t *newopts;
  2214. int i;
  2215. config_line_t *line;
  2216. newopts = config_alloc(fmt);
  2217. for (i=0; fmt->vars[i].name; ++i) {
  2218. if (fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
  2219. continue;
  2220. if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE)
  2221. continue;
  2222. line = get_assigned_option(fmt, old, fmt->vars[i].name, 0);
  2223. if (line) {
  2224. char *msg = NULL;
  2225. if (config_assign(fmt, newopts, line, 0, 0, &msg) < 0) {
  2226. log_err(LD_BUG, "Config_get_assigned_option() generated "
  2227. "something we couldn't config_assign(): %s", msg);
  2228. tor_free(msg);
  2229. tor_assert(0);
  2230. }
  2231. }
  2232. config_free_lines(line);
  2233. }
  2234. return newopts;
  2235. }
  2236. /** Return a new empty or_options_t. Used for testing. */
  2237. or_options_t *
  2238. options_new(void)
  2239. {
  2240. return config_alloc(&options_format);
  2241. }
  2242. /** Set <b>options</b> to hold reasonable defaults for most options.
  2243. * Each option defaults to zero. */
  2244. void
  2245. options_init(or_options_t *options)
  2246. {
  2247. config_init(&options_format, options);
  2248. }
  2249. /** Set all vars in the configuration object <b>options</b> to their default
  2250. * values. */
  2251. static void
  2252. config_init(config_format_t *fmt, void *options)
  2253. {
  2254. int i;
  2255. config_var_t *var;
  2256. CHECK(fmt, options);
  2257. for (i=0; fmt->vars[i].name; ++i) {
  2258. var = &fmt->vars[i];
  2259. if (!var->initvalue)
  2260. continue; /* defaults to NULL or 0 */
  2261. option_reset(fmt, options, var, 1);
  2262. }
  2263. }
  2264. /** Allocate and return a new string holding the written-out values of the vars
  2265. * in 'options'. If 'minimal', do not write out any default-valued vars.
  2266. * Else, if comment_defaults, write default values as comments.
  2267. */
  2268. static char *
  2269. config_dump(config_format_t *fmt, void *options, int minimal,
  2270. int comment_defaults)
  2271. {
  2272. smartlist_t *elements;
  2273. or_options_t *defaults;
  2274. config_line_t *line, *assigned;
  2275. char *result;
  2276. int i;
  2277. const char *desc;
  2278. char *msg = NULL;
  2279. defaults = config_alloc(fmt);
  2280. config_init(fmt, defaults);
  2281. /* XXX use a 1 here so we don't add a new log line while dumping */
  2282. if (fmt->validate_fn(NULL,defaults, 1, &msg) < 0) {
  2283. log_err(LD_BUG, "Failed to validate default config.");
  2284. tor_free(msg);
  2285. tor_assert(0);
  2286. }
  2287. elements = smartlist_create();
  2288. for (i=0; fmt->vars[i].name; ++i) {
  2289. int comment_option = 0;
  2290. if (fmt->vars[i].type == CONFIG_TYPE_OBSOLETE ||
  2291. fmt->vars[i].type == CONFIG_TYPE_LINELIST_S)
  2292. continue;
  2293. /* Don't save 'hidden' control variables. */
  2294. if (!strcmpstart(fmt->vars[i].name, "__"))
  2295. continue;
  2296. if (minimal && option_is_same(fmt, options, defaults, fmt->vars[i].name))
  2297. continue;
  2298. else if (comment_defaults &&
  2299. option_is_same(fmt, options, defaults, fmt->vars[i].name))
  2300. comment_option = 1;
  2301. desc = config_find_description(fmt, fmt->vars[i].name);
  2302. line = assigned = get_assigned_option(fmt, options, fmt->vars[i].name, 1);
  2303. if (line && desc) {
  2304. /* Only dump the description if there's something to describe. */
  2305. wrap_string(elements, desc, 78, "# ", "# ");
  2306. }
  2307. for (; line; line = line->next) {
  2308. size_t len = strlen(line->key) + strlen(line->value) + 5;
  2309. char *tmp;
  2310. tmp = tor_malloc(len);
  2311. if (tor_snprintf(tmp, len, "%s%s %s\n",
  2312. comment_option ? "# " : "",
  2313. line->key, line->value)<0) {
  2314. log_err(LD_BUG,"Internal error writing option value");
  2315. tor_assert(0);
  2316. }
  2317. smartlist_add(elements, tmp);
  2318. }
  2319. config_free_lines(assigned);
  2320. }
  2321. if (fmt->extra) {
  2322. line = *(config_line_t**)STRUCT_VAR_P(options, fmt->extra->var_offset);
  2323. for (; line; line = line->next) {
  2324. size_t len = strlen(line->key) + strlen(line->value) + 3;
  2325. char *tmp;
  2326. tmp = tor_malloc(len);
  2327. if (tor_snprintf(tmp, len, "%s %s\n", line->key, line->value)<0) {
  2328. log_err(LD_BUG,"Internal error writing option value");
  2329. tor_assert(0);
  2330. }
  2331. smartlist_add(elements, tmp);
  2332. }
  2333. }
  2334. result = smartlist_join_strings(elements, "", 0, NULL);
  2335. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  2336. smartlist_free(elements);
  2337. config_free(fmt, defaults);
  2338. return result;
  2339. }
  2340. /** Return a string containing a possible configuration file that would give
  2341. * the configuration in <b>options</b>. If <b>minimal</b> is true, do not
  2342. * include options that are the same as Tor's defaults.
  2343. */
  2344. static char *
  2345. options_dump(or_options_t *options, int minimal)
  2346. {
  2347. return config_dump(&options_format, options, minimal, 0);
  2348. }
  2349. /** Return 0 if every element of sl is a string holding a decimal
  2350. * representation of a port number, or if sl is NULL.
  2351. * Otherwise set *msg and return -1. */
  2352. static int
  2353. validate_ports_csv(smartlist_t *sl, const char *name, char **msg)
  2354. {
  2355. int i;
  2356. char buf[1024];
  2357. tor_assert(name);
  2358. if (!sl)
  2359. return 0;
  2360. SMARTLIST_FOREACH(sl, const char *, cp,
  2361. {
  2362. i = atoi(cp);
  2363. if (i < 1 || i > 65535) {
  2364. int r = tor_snprintf(buf, sizeof(buf),
  2365. "Port '%s' out of range in %s", cp, name);
  2366. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  2367. return -1;
  2368. }
  2369. });
  2370. return 0;
  2371. }
  2372. /** If <b>value</b> exceeds ROUTER_MAX_DECLARED_BANDWIDTH, write
  2373. * a complaint into *<b>msg</b> using string <b>desc</b>, and return -1.
  2374. * Else return 0.
  2375. */
  2376. static int
  2377. ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
  2378. {
  2379. int r;
  2380. char buf[1024];
  2381. if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
  2382. /* This handles an understandable special case where somebody says "2gb"
  2383. * whereas our actual maximum is 2gb-1 (INT_MAX) */
  2384. --*value;
  2385. }
  2386. if (*value > ROUTER_MAX_DECLARED_BANDWIDTH) {
  2387. r = tor_snprintf(buf, sizeof(buf), "%s ("U64_FORMAT") must be at most %d",
  2388. desc, U64_PRINTF_ARG(*value),
  2389. ROUTER_MAX_DECLARED_BANDWIDTH);
  2390. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  2391. return -1;
  2392. }
  2393. return 0;
  2394. }
  2395. /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
  2396. * and write it to <b>options</b>-\>_PublishServerDescriptor. Treat "1"
  2397. * as "v2,v3" unless BridgeRelay is 1, in which case treat it as "bridge".
  2398. * Treat "0" as "".
  2399. * Return 0 on success or -1 if not a recognized authority type (in which
  2400. * case the value of _PublishServerDescriptor is undefined). */
  2401. static int
  2402. compute_publishserverdescriptor(or_options_t *options)
  2403. {
  2404. smartlist_t *list = options->PublishServerDescriptor;
  2405. authority_type_t *auth = &options->_PublishServerDescriptor;
  2406. *auth = NO_AUTHORITY;
  2407. if (!list) /* empty list, answer is none */
  2408. return 0;
  2409. SMARTLIST_FOREACH(list, const char *, string, {
  2410. if (!strcasecmp(string, "v1"))
  2411. *auth |= V1_AUTHORITY;
  2412. else if (!strcmp(string, "1"))
  2413. if (options->BridgeRelay)
  2414. *auth |= BRIDGE_AUTHORITY;
  2415. else
  2416. *auth |= V2_AUTHORITY | V3_AUTHORITY;
  2417. else if (!strcasecmp(string, "v2"))
  2418. *auth |= V2_AUTHORITY;
  2419. else if (!strcasecmp(string, "v3"))
  2420. *auth |= V3_AUTHORITY;
  2421. else if (!strcasecmp(string, "bridge"))
  2422. *auth |= BRIDGE_AUTHORITY;
  2423. else if (!strcasecmp(string, "hidserv"))
  2424. *auth |= HIDSERV_AUTHORITY;
  2425. else if (!strcasecmp(string, "") || !strcmp(string, "0"))
  2426. /* no authority */;
  2427. else
  2428. return -1;
  2429. });
  2430. return 0;
  2431. }
  2432. /** Lowest allowable value for RendPostPeriod; if this is too low, hidden
  2433. * services can overload the directory system. */
  2434. #define MIN_REND_POST_PERIOD (10*60)
  2435. /** Highest allowable value for RendPostPeriod. */
  2436. #define MAX_DIR_PERIOD (MIN_ONION_KEY_LIFETIME/2)
  2437. /** Return 0 if every setting in <b>options</b> is reasonable, and a
  2438. * permissible transition from <b>old_options</b>. Else return -1.
  2439. * Should have no side effects, except for normalizing the contents of
  2440. * <b>options</b>.
  2441. *
  2442. * On error, tor_strdup an error explanation into *<b>msg</b>.
  2443. *
  2444. * XXX
  2445. * If <b>from_setconf</b>, we were called by the controller, and our
  2446. * Log line should stay empty. If it's 0, then give us a default log
  2447. * if there are no logs defined.
  2448. */
  2449. static int
  2450. options_validate(or_options_t *old_options, or_options_t *options,
  2451. int from_setconf, char **msg)
  2452. {
  2453. int i, r;
  2454. config_line_t *cl;
  2455. const char *uname = get_uname();
  2456. char buf[1024];
  2457. #define REJECT(arg) \
  2458. STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
  2459. #define COMPLAIN(arg) STMT_BEGIN log(LOG_WARN, LD_CONFIG, arg); STMT_END
  2460. tor_assert(msg);
  2461. *msg = NULL;
  2462. if (options->ORPort < 0 || options->ORPort > 65535)
  2463. REJECT("ORPort option out of bounds.");
  2464. if (server_mode(options) &&
  2465. (!strcmpstart(uname, "Windows 95") ||
  2466. !strcmpstart(uname, "Windows 98") ||
  2467. !strcmpstart(uname, "Windows Me"))) {
  2468. log(LOG_WARN, LD_CONFIG, "Tor is running as a server, but you are "
  2469. "running %s; this probably won't work. See "
  2470. "http://wiki.noreply.org/noreply/TheOnionRouter/TorFAQ#ServerOS "
  2471. "for details.", uname);
  2472. }
  2473. if (options->ORPort == 0 && options->ORListenAddress != NULL)
  2474. REJECT("ORPort must be defined if ORListenAddress is defined.");
  2475. if (options->DirPort == 0 && options->DirListenAddress != NULL)
  2476. REJECT("DirPort must be defined if DirListenAddress is defined.");
  2477. if (options->DNSPort == 0 && options->DNSListenAddress != NULL)
  2478. REJECT("DNSPort must be defined if DNSListenAddress is defined.");
  2479. if (options->ControlPort == 0 && options->ControlListenAddress != NULL)
  2480. REJECT("ControlPort must be defined if ControlListenAddress is defined.");
  2481. if (options->TransPort == 0 && options->TransListenAddress != NULL)
  2482. REJECT("TransPort must be defined if TransListenAddress is defined.");
  2483. if (options->NatdPort == 0 && options->NatdListenAddress != NULL)
  2484. REJECT("NatdPort must be defined if NatdListenAddress is defined.");
  2485. /* Don't gripe about SocksPort 0 with SocksListenAddress set; a standard
  2486. * configuration does this. */
  2487. for (i = 0; i < 3; ++i) {
  2488. int is_socks = i==0;
  2489. int is_trans = i==1;
  2490. config_line_t *line, *opt, *old;
  2491. const char *tp;
  2492. if (is_socks) {
  2493. opt = options->SocksListenAddress;
  2494. old = old_options ? old_options->SocksListenAddress : NULL;
  2495. tp = "SOCKS proxy";
  2496. } else if (is_trans) {
  2497. opt = options->TransListenAddress;
  2498. old = old_options ? old_options->TransListenAddress : NULL;
  2499. tp = "transparent proxy";
  2500. } else {
  2501. opt = options->NatdListenAddress;
  2502. old = old_options ? old_options->NatdListenAddress : NULL;
  2503. tp = "natd proxy";
  2504. }
  2505. for (line = opt; line; line = line->next) {
  2506. char *address = NULL;
  2507. uint16_t port;
  2508. uint32_t addr;
  2509. if (parse_addr_port(LOG_WARN, line->value, &address, &addr, &port)<0)
  2510. continue; /* We'll warn about this later. */
  2511. if (!is_internal_IP(addr, 1) &&
  2512. (!old_options || !config_lines_eq(old, opt))) {
  2513. log_warn(LD_CONFIG,
  2514. "You specified a public address '%s' for a %s. Other "
  2515. "people on the Internet might find your computer and use it as "
  2516. "an open %s. Please don't allow this unless you have "
  2517. "a good reason.", address, tp, tp);
  2518. }
  2519. tor_free(address);
  2520. }
  2521. }
  2522. if (validate_data_directory(options)<0)
  2523. REJECT("Invalid DataDirectory");
  2524. if (options->Nickname == NULL) {
  2525. if (server_mode(options)) {
  2526. if (!(options->Nickname = get_default_nickname())) {
  2527. log_notice(LD_CONFIG, "Couldn't pick a nickname based on "
  2528. "our hostname; using %s instead.", UNNAMED_ROUTER_NICKNAME);
  2529. options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
  2530. } else {
  2531. log_notice(LD_CONFIG, "Choosing default nickname '%s'",
  2532. options->Nickname);
  2533. }
  2534. }
  2535. } else {
  2536. if (!is_legal_nickname(options->Nickname)) {
  2537. r = tor_snprintf(buf, sizeof(buf),
  2538. "Nickname '%s' is wrong length or contains illegal characters.",
  2539. options->Nickname);
  2540. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  2541. return -1;
  2542. }
  2543. }
  2544. if (server_mode(options) && !options->ContactInfo)
  2545. log(LOG_NOTICE, LD_CONFIG, "Your ContactInfo config option is not set. "
  2546. "Please consider setting it, so we can contact you if your server is "
  2547. "misconfigured or something else goes wrong.");
  2548. /* Special case on first boot if no Log options are given. */
  2549. if (!options->Logs && !options->RunAsDaemon && !from_setconf)
  2550. config_line_append(&options->Logs, "Log", "notice stdout");
  2551. if (options_init_logs(options, 1)<0) /* Validate the log(s) */
  2552. REJECT("Failed to validate Log options. See logs for details.");
  2553. if (options->NoPublish) {
  2554. log(LOG_WARN, LD_CONFIG,
  2555. "NoPublish is obsolete. Use PublishServerDescriptor instead.");
  2556. SMARTLIST_FOREACH(options->PublishServerDescriptor, char *, s,
  2557. tor_free(s));
  2558. smartlist_clear(options->PublishServerDescriptor);
  2559. }
  2560. if (authdir_mode(options)) {
  2561. /* confirm that our address isn't broken, so we can complain now */
  2562. uint32_t tmp;
  2563. if (resolve_my_address(LOG_WARN, options, &tmp, NULL) < 0)
  2564. REJECT("Failed to resolve/guess local address. See logs for details.");
  2565. }
  2566. #ifndef MS_WINDOWS
  2567. if (options->RunAsDaemon && torrc_fname && path_is_relative(torrc_fname))
  2568. REJECT("Can't use a relative path to torrc when RunAsDaemon is set.");
  2569. #endif
  2570. if (options->SocksPort < 0 || options->SocksPort > 65535)
  2571. REJECT("SocksPort option out of bounds.");
  2572. if (options->DNSPort < 0 || options->DNSPort > 65535)
  2573. REJECT("DNSPort option out of bounds.");
  2574. if (options->TransPort < 0 || options->TransPort > 65535)
  2575. REJECT("TransPort option out of bounds.");
  2576. if (options->NatdPort < 0 || options->NatdPort > 65535)
  2577. REJECT("NatdPort option out of bounds.");
  2578. if (options->SocksPort == 0 && options->TransPort == 0 &&
  2579. options->NatdPort == 0 && options->ORPort == 0 &&
  2580. options->DNSPort == 0 && !options->RendConfigLines)
  2581. log(LOG_WARN, LD_CONFIG,
  2582. "SocksPort, TransPort, NatdPort, DNSPort, and ORPort are all "
  2583. "undefined, and there aren't any hidden services configured. "
  2584. "Tor will still run, but probably won't do anything.");
  2585. if (options->ControlPort < 0 || options->ControlPort > 65535)
  2586. REJECT("ControlPort option out of bounds.");
  2587. if (options->DirPort < 0 || options->DirPort > 65535)
  2588. REJECT("DirPort option out of bounds.");
  2589. #ifndef USE_TRANSPARENT
  2590. if (options->TransPort || options->TransListenAddress)
  2591. REJECT("TransPort and TransListenAddress are disabled in this build.");
  2592. #endif
  2593. if (options->StrictExitNodes &&
  2594. (!options->ExitNodes || !strlen(options->ExitNodes)) &&
  2595. (!old_options ||
  2596. (old_options->StrictExitNodes != options->StrictExitNodes) ||
  2597. (!opt_streq(old_options->ExitNodes, options->ExitNodes))))
  2598. COMPLAIN("StrictExitNodes set, but no ExitNodes listed.");
  2599. if (options->StrictEntryNodes &&
  2600. (!options->EntryNodes || !strlen(options->EntryNodes)) &&
  2601. (!old_options ||
  2602. (old_options->StrictEntryNodes != options->StrictEntryNodes) ||
  2603. (!opt_streq(old_options->EntryNodes, options->EntryNodes))))
  2604. COMPLAIN("StrictEntryNodes set, but no EntryNodes listed.");
  2605. if (options->AuthoritativeDir) {
  2606. if (!options->ContactInfo)
  2607. REJECT("Authoritative directory servers must set ContactInfo");
  2608. if (options->V1AuthoritativeDir && !options->RecommendedVersions)
  2609. REJECT("V1 auth dir servers must set RecommendedVersions.");
  2610. if (!options->RecommendedClientVersions)
  2611. options->RecommendedClientVersions =
  2612. config_lines_dup(options->RecommendedVersions);
  2613. if (!options->RecommendedServerVersions)
  2614. options->RecommendedServerVersions =
  2615. config_lines_dup(options->RecommendedVersions);
  2616. if (options->VersioningAuthoritativeDir &&
  2617. (!options->RecommendedClientVersions ||
  2618. !options->RecommendedServerVersions))
  2619. REJECT("Versioning auth dir servers must set Recommended*Versions.");
  2620. if (options->UseEntryGuards) {
  2621. log_info(LD_CONFIG, "Authoritative directory servers can't set "
  2622. "UseEntryGuards. Disabling.");
  2623. options->UseEntryGuards = 0;
  2624. }
  2625. if (!options->DownloadExtraInfo && authdir_mode_any_main(options)) {
  2626. log_info(LD_CONFIG, "Authoritative directories always try to download "
  2627. "extra-info documents. Setting DownloadExtraInfo.");
  2628. options->DownloadExtraInfo = 1;
  2629. }
  2630. if (!(options->BridgeAuthoritativeDir || options->HSAuthoritativeDir ||
  2631. options->V1AuthoritativeDir || options->V2AuthoritativeDir ||
  2632. options->V3AuthoritativeDir))
  2633. REJECT("AuthoritativeDir is set, but none of "
  2634. "(Bridge/HS/V1/V2/V3)AuthoritativeDir is set.");
  2635. }
  2636. if (options->AuthoritativeDir && !options->DirPort)
  2637. REJECT("Running as authoritative directory, but no DirPort set.");
  2638. if (options->AuthoritativeDir && !options->ORPort)
  2639. REJECT("Running as authoritative directory, but no ORPort set.");
  2640. if (options->AuthoritativeDir && options->ClientOnly)
  2641. REJECT("Running as authoritative directory, but ClientOnly also set.");
  2642. if (options->HSAuthorityRecordStats && !options->HSAuthoritativeDir)
  2643. REJECT("HSAuthorityRecordStats is set but we're not running as "
  2644. "a hidden service authority.");
  2645. if (options->HidServDirectoryV2 && !options->DirPort)
  2646. REJECT("Running as hidden service directory, but no DirPort set.");
  2647. if (options->ConnLimit <= 0) {
  2648. r = tor_snprintf(buf, sizeof(buf),
  2649. "ConnLimit must be greater than 0, but was set to %d",
  2650. options->ConnLimit);
  2651. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  2652. return -1;
  2653. }
  2654. if (validate_ports_csv(options->FirewallPorts, "FirewallPorts", msg) < 0)
  2655. return -1;
  2656. if (validate_ports_csv(options->LongLivedPorts, "LongLivedPorts", msg) < 0)
  2657. return -1;
  2658. if (validate_ports_csv(options->RejectPlaintextPorts,
  2659. "RejectPlaintextPorts", msg) < 0)
  2660. return -1;
  2661. if (validate_ports_csv(options->WarnPlaintextPorts,
  2662. "WarnPlaintextPorts", msg) < 0)
  2663. return -1;
  2664. if (options->FascistFirewall && !options->ReachableAddresses) {
  2665. if (options->FirewallPorts && smartlist_len(options->FirewallPorts)) {
  2666. /* We already have firewall ports set, so migrate them to
  2667. * ReachableAddresses, which will set ReachableORAddresses and
  2668. * ReachableDirAddresses if they aren't set explicitly. */
  2669. smartlist_t *instead = smartlist_create();
  2670. config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
  2671. new_line->key = tor_strdup("ReachableAddresses");
  2672. /* If we're configured with the old format, we need to prepend some
  2673. * open ports. */
  2674. SMARTLIST_FOREACH(options->FirewallPorts, const char *, portno,
  2675. {
  2676. int p = atoi(portno);
  2677. char *s;
  2678. if (p<0) continue;
  2679. s = tor_malloc(16);
  2680. tor_snprintf(s, 16, "*:%d", p);
  2681. smartlist_add(instead, s);
  2682. });
  2683. new_line->value = smartlist_join_strings(instead,",",0,NULL);
  2684. /* These have been deprecated since 0.1.1.5-alpha-cvs */
  2685. log(LOG_NOTICE, LD_CONFIG,
  2686. "Converting FascistFirewall and FirewallPorts "
  2687. "config options to new format: \"ReachableAddresses %s\"",
  2688. new_line->value);
  2689. options->ReachableAddresses = new_line;
  2690. SMARTLIST_FOREACH(instead, char *, cp, tor_free(cp));
  2691. smartlist_free(instead);
  2692. } else {
  2693. /* We do not have FirewallPorts set, so add 80 to
  2694. * ReachableDirAddresses, and 443 to ReachableORAddresses. */
  2695. if (!options->ReachableDirAddresses) {
  2696. config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
  2697. new_line->key = tor_strdup("ReachableDirAddresses");
  2698. new_line->value = tor_strdup("*:80");
  2699. options->ReachableDirAddresses = new_line;
  2700. log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
  2701. "to new format: \"ReachableDirAddresses *:80\"");
  2702. }
  2703. if (!options->ReachableORAddresses) {
  2704. config_line_t *new_line = tor_malloc_zero(sizeof(config_line_t));
  2705. new_line->key = tor_strdup("ReachableORAddresses");
  2706. new_line->value = tor_strdup("*:443");
  2707. options->ReachableORAddresses = new_line;
  2708. log(LOG_NOTICE, LD_CONFIG, "Converting FascistFirewall config option "
  2709. "to new format: \"ReachableORAddresses *:443\"");
  2710. }
  2711. }
  2712. }
  2713. for (i=0; i<3; i++) {
  2714. config_line_t **linep =
  2715. (i==0) ? &options->ReachableAddresses :
  2716. (i==1) ? &options->ReachableORAddresses :
  2717. &options->ReachableDirAddresses;
  2718. if (!*linep)
  2719. continue;
  2720. /* We need to end with a reject *:*, not an implicit accept *:* */
  2721. for (;;) {
  2722. if (!strcmp((*linep)->value, "reject *:*")) /* already there */
  2723. break;
  2724. linep = &((*linep)->next);
  2725. if (!*linep) {
  2726. *linep = tor_malloc_zero(sizeof(config_line_t));
  2727. (*linep)->key = tor_strdup(
  2728. (i==0) ? "ReachableAddresses" :
  2729. (i==1) ? "ReachableORAddresses" :
  2730. "ReachableDirAddresses");
  2731. (*linep)->value = tor_strdup("reject *:*");
  2732. break;
  2733. }
  2734. }
  2735. }
  2736. if ((options->ReachableAddresses ||
  2737. options->ReachableORAddresses ||
  2738. options->ReachableDirAddresses) &&
  2739. server_mode(options))
  2740. REJECT("Servers must be able to freely connect to the rest "
  2741. "of the Internet, so they must not set Reachable*Addresses "
  2742. "or FascistFirewall.");
  2743. if (options->UseBridges &&
  2744. server_mode(options))
  2745. REJECT("Servers must be able to freely connect to the rest "
  2746. "of the Internet, so they must not set UseBridges.");
  2747. options->_AllowInvalid = 0;
  2748. if (options->AllowInvalidNodes) {
  2749. SMARTLIST_FOREACH(options->AllowInvalidNodes, const char *, cp, {
  2750. if (!strcasecmp(cp, "entry"))
  2751. options->_AllowInvalid |= ALLOW_INVALID_ENTRY;
  2752. else if (!strcasecmp(cp, "exit"))
  2753. options->_AllowInvalid |= ALLOW_INVALID_EXIT;
  2754. else if (!strcasecmp(cp, "middle"))
  2755. options->_AllowInvalid |= ALLOW_INVALID_MIDDLE;
  2756. else if (!strcasecmp(cp, "introduction"))
  2757. options->_AllowInvalid |= ALLOW_INVALID_INTRODUCTION;
  2758. else if (!strcasecmp(cp, "rendezvous"))
  2759. options->_AllowInvalid |= ALLOW_INVALID_RENDEZVOUS;
  2760. else {
  2761. r = tor_snprintf(buf, sizeof(buf),
  2762. "Unrecognized value '%s' in AllowInvalidNodes", cp);
  2763. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  2764. return -1;
  2765. }
  2766. });
  2767. }
  2768. if (compute_publishserverdescriptor(options) < 0) {
  2769. r = tor_snprintf(buf, sizeof(buf),
  2770. "Unrecognized value in PublishServerDescriptor");
  2771. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  2772. return -1;
  2773. }
  2774. if (options->MinUptimeHidServDirectoryV2 < 0) {
  2775. log_warn(LD_CONFIG, "MinUptimeHidServDirectoryV2 option must be at "
  2776. "least 0 seconds. Changing to 0.");
  2777. options->MinUptimeHidServDirectoryV2 = 0;
  2778. }
  2779. if (options->RendPostPeriod < MIN_REND_POST_PERIOD) {
  2780. log(LOG_WARN,LD_CONFIG,"RendPostPeriod option must be at least %d seconds."
  2781. " Clipping.", MIN_REND_POST_PERIOD);
  2782. options->RendPostPeriod = MIN_REND_POST_PERIOD;
  2783. }
  2784. if (options->RendPostPeriod > MAX_DIR_PERIOD) {
  2785. log(LOG_WARN, LD_CONFIG, "RendPostPeriod is too large; clipping to %ds.",
  2786. MAX_DIR_PERIOD);
  2787. options->RendPostPeriod = MAX_DIR_PERIOD;
  2788. }
  2789. if (options->KeepalivePeriod < 1)
  2790. REJECT("KeepalivePeriod option must be positive.");
  2791. if (ensure_bandwidth_cap(&options->BandwidthRate,
  2792. "BandwidthRate", msg) < 0)
  2793. return -1;
  2794. if (ensure_bandwidth_cap(&options->BandwidthBurst,
  2795. "BandwidthBurst", msg) < 0)
  2796. return -1;
  2797. if (ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
  2798. "MaxAdvertisedBandwidth", msg) < 0)
  2799. return -1;
  2800. if (ensure_bandwidth_cap(&options->RelayBandwidthRate,
  2801. "RelayBandwidthRate", msg) < 0)
  2802. return -1;
  2803. if (ensure_bandwidth_cap(&options->RelayBandwidthBurst,
  2804. "RelayBandwidthBurst", msg) < 0)
  2805. return -1;
  2806. if (server_mode(options)) {
  2807. if (options->BandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH*2) {
  2808. r = tor_snprintf(buf, sizeof(buf),
  2809. "BandwidthRate is set to %d bytes/second. "
  2810. "For servers, it must be at least %d.",
  2811. (int)options->BandwidthRate,
  2812. ROUTER_REQUIRED_MIN_BANDWIDTH*2);
  2813. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  2814. return -1;
  2815. } else if (options->MaxAdvertisedBandwidth <
  2816. ROUTER_REQUIRED_MIN_BANDWIDTH) {
  2817. r = tor_snprintf(buf, sizeof(buf),
  2818. "MaxAdvertisedBandwidth is set to %d bytes/second. "
  2819. "For servers, it must be at least %d.",
  2820. (int)options->MaxAdvertisedBandwidth,
  2821. ROUTER_REQUIRED_MIN_BANDWIDTH);
  2822. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  2823. return -1;
  2824. }
  2825. if (options->RelayBandwidthRate &&
  2826. options->RelayBandwidthRate < ROUTER_REQUIRED_MIN_BANDWIDTH) {
  2827. r = tor_snprintf(buf, sizeof(buf),
  2828. "RelayBandwidthRate is set to %d bytes/second. "
  2829. "For servers, it must be at least %d.",
  2830. (int)options->RelayBandwidthRate,
  2831. ROUTER_REQUIRED_MIN_BANDWIDTH);
  2832. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  2833. return -1;
  2834. }
  2835. }
  2836. if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
  2837. options->RelayBandwidthBurst = options->RelayBandwidthRate;
  2838. if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
  2839. REJECT("RelayBandwidthBurst must be at least equal "
  2840. "to RelayBandwidthRate.");
  2841. if (options->BandwidthRate > options->BandwidthBurst)
  2842. REJECT("BandwidthBurst must be at least equal to BandwidthRate.");
  2843. /* if they set relaybandwidth* really high but left bandwidth*
  2844. * at the default, raise the defaults. */
  2845. if (options->RelayBandwidthRate > options->BandwidthRate)
  2846. options->BandwidthRate = options->RelayBandwidthRate;
  2847. if (options->RelayBandwidthBurst > options->BandwidthBurst)
  2848. options->BandwidthBurst = options->RelayBandwidthBurst;
  2849. if (accounting_parse_options(options, 1)<0)
  2850. REJECT("Failed to parse accounting options. See logs for details.");
  2851. if (options->HttpProxy) { /* parse it now */
  2852. if (parse_addr_port(LOG_WARN, options->HttpProxy, NULL,
  2853. &options->HttpProxyAddr, &options->HttpProxyPort) < 0)
  2854. REJECT("HttpProxy failed to parse or resolve. Please fix.");
  2855. if (options->HttpProxyPort == 0) { /* give it a default */
  2856. options->HttpProxyPort = 80;
  2857. }
  2858. }
  2859. if (options->HttpProxyAuthenticator) {
  2860. if (strlen(options->HttpProxyAuthenticator) >= 48)
  2861. REJECT("HttpProxyAuthenticator is too long (>= 48 chars).");
  2862. }
  2863. if (options->HttpsProxy) { /* parse it now */
  2864. if (parse_addr_port(LOG_WARN, options->HttpsProxy, NULL,
  2865. &options->HttpsProxyAddr, &options->HttpsProxyPort) <0)
  2866. REJECT("HttpsProxy failed to parse or resolve. Please fix.");
  2867. if (options->HttpsProxyPort == 0) { /* give it a default */
  2868. options->HttpsProxyPort = 443;
  2869. }
  2870. }
  2871. if (options->HttpsProxyAuthenticator) {
  2872. if (strlen(options->HttpsProxyAuthenticator) >= 48)
  2873. REJECT("HttpsProxyAuthenticator is too long (>= 48 chars).");
  2874. }
  2875. if (options->HashedControlPassword) {
  2876. smartlist_t *sl = decode_hashed_passwords(options->HashedControlPassword);
  2877. if (!sl) {
  2878. REJECT("Bad HashedControlPassword: wrong length or bad encoding");
  2879. } else {
  2880. SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
  2881. smartlist_free(sl);
  2882. }
  2883. }
  2884. if (options->HashedControlSessionPassword) {
  2885. smartlist_t *sl = decode_hashed_passwords(
  2886. options->HashedControlSessionPassword);
  2887. if (!sl) {
  2888. REJECT("Bad HashedControlSessionPassword: wrong length or bad encoding");
  2889. } else {
  2890. SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
  2891. smartlist_free(sl);
  2892. }
  2893. }
  2894. if (options->ControlListenAddress) {
  2895. int all_are_local = 1;
  2896. config_line_t *ln;
  2897. for (ln = options->ControlListenAddress; ln; ln = ln->next) {
  2898. if (strcmpstart(ln->value, "127."))
  2899. all_are_local = 0;
  2900. }
  2901. if (!all_are_local) {
  2902. if (!options->HashedControlPassword &&
  2903. !options->HashedControlSessionPassword &&
  2904. !options->CookieAuthentication) {
  2905. log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
  2906. "connections from a non-local address. This means that "
  2907. "any program on the internet can reconfigure your Tor. "
  2908. "That's so bad that I'm closing your ControlPort for you.");
  2909. options->ControlPort = 0;
  2910. } else {
  2911. log_warn(LD_CONFIG, "You have a ControlListenAddress set to accept "
  2912. "connections from a non-local address. This means that "
  2913. "programs not running on your computer can reconfigure your "
  2914. "Tor. That's pretty bad!");
  2915. }
  2916. }
  2917. }
  2918. if (options->ControlPort && !options->HashedControlPassword &&
  2919. !options->HashedControlSessionPassword &&
  2920. !options->CookieAuthentication) {
  2921. log_warn(LD_CONFIG, "ControlPort is open, but no authentication method "
  2922. "has been configured. This means that any program on your "
  2923. "computer can reconfigure your Tor. That's bad! You should "
  2924. "upgrade your Tor controller as soon as possible.");
  2925. }
  2926. if (options->UseEntryGuards && ! options->NumEntryGuards)
  2927. REJECT("Cannot enable UseEntryGuards with NumEntryGuards set to 0");
  2928. if (check_nickname_list(options->ExitNodes, "ExitNodes", msg))
  2929. return -1;
  2930. if (check_nickname_list(options->EntryNodes, "EntryNodes", msg))
  2931. return -1;
  2932. if (check_nickname_list(options->ExcludeNodes, "ExcludeNodes", msg))
  2933. return -1;
  2934. if (check_nickname_list(options->RendNodes, "RendNodes", msg))
  2935. return -1;
  2936. if (check_nickname_list(options->RendNodes, "RendExcludeNodes", msg))
  2937. return -1;
  2938. if (check_nickname_list(options->TestVia, "TestVia", msg))
  2939. return -1;
  2940. if (check_nickname_list(options->MyFamily, "MyFamily", msg))
  2941. return -1;
  2942. for (cl = options->NodeFamilies; cl; cl = cl->next) {
  2943. if (check_nickname_list(cl->value, "NodeFamily", msg))
  2944. return -1;
  2945. }
  2946. if (validate_addr_policies(options, msg) < 0)
  2947. return -1;
  2948. for (cl = options->RedirectExit; cl; cl = cl->next) {
  2949. if (parse_redirect_line(NULL, cl, msg)<0)
  2950. return -1;
  2951. }
  2952. if (validate_dir_authorities(options, old_options) < 0)
  2953. REJECT("Directory authority line did not parse. See logs for details.");
  2954. if (options->UseBridges && !options->Bridges)
  2955. REJECT("If you set UseBridges, you must specify at least one bridge.");
  2956. if (options->UseBridges && !options->TunnelDirConns)
  2957. REJECT("If you set UseBridges, you must set TunnelDirConns.");
  2958. if (options->Bridges) {
  2959. for (cl = options->Bridges; cl; cl = cl->next) {
  2960. if (parse_bridge_line(cl->value, 1)<0)
  2961. REJECT("Bridge line did not parse. See logs for details.");
  2962. }
  2963. }
  2964. if (options->ConstrainedSockets) {
  2965. /* If the user wants to constrain socket buffer use, make sure the desired
  2966. * limit is between MIN|MAX_TCPSOCK_BUFFER in k increments. */
  2967. if (options->ConstrainedSockSize < MIN_CONSTRAINED_TCP_BUFFER ||
  2968. options->ConstrainedSockSize > MAX_CONSTRAINED_TCP_BUFFER ||
  2969. options->ConstrainedSockSize % 1024) {
  2970. r = tor_snprintf(buf, sizeof(buf),
  2971. "ConstrainedSockSize is invalid. Must be a value between %d and %d "
  2972. "in 1024 byte increments.",
  2973. MIN_CONSTRAINED_TCP_BUFFER, MAX_CONSTRAINED_TCP_BUFFER);
  2974. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  2975. return -1;
  2976. }
  2977. if (options->DirPort) {
  2978. /* Providing cached directory entries while system TCP buffers are scarce
  2979. * will exacerbate the socket errors. Suggest that this be disabled. */
  2980. COMPLAIN("You have requested constrained socket buffers while also "
  2981. "serving directory entries via DirPort. It is strongly "
  2982. "suggested that you disable serving directory requests when "
  2983. "system TCP buffer resources are scarce.");
  2984. }
  2985. }
  2986. if (options->V3AuthVoteDelay + options->V3AuthDistDelay >=
  2987. options->V3AuthVotingInterval/2) {
  2988. REJECT("V3AuthVoteDelay plus V3AuthDistDelay must be less than half "
  2989. "V3AuthVotingInterval");
  2990. }
  2991. if (options->V3AuthVoteDelay < MIN_VOTE_SECONDS)
  2992. REJECT("V3AuthVoteDelay is way too low.");
  2993. if (options->V3AuthDistDelay < MIN_DIST_SECONDS)
  2994. REJECT("V3AuthDistDelay is way too low.");
  2995. if (options->V3AuthNIntervalsValid < 2)
  2996. REJECT("V3AuthNIntervalsValid must be at least 2.");
  2997. if (options->V3AuthVotingInterval < MIN_VOTE_INTERVAL) {
  2998. REJECT("V3AuthVotingInterval is insanely low.");
  2999. } else if (options->V3AuthVotingInterval > 24*60*60) {
  3000. REJECT("V3AuthVotingInterval is insanely high.");
  3001. } else if (((24*60*60) % options->V3AuthVotingInterval) != 0) {
  3002. COMPLAIN("V3AuthVotingInterval does not divide evenly into 24 hours.");
  3003. }
  3004. if (rend_config_services(options, 1) < 0)
  3005. REJECT("Failed to configure rendezvous options. See logs for details.");
  3006. if (parse_virtual_addr_network(options->VirtualAddrNetwork, 1, NULL)<0)
  3007. return -1;
  3008. if (options->PreferTunneledDirConns && !options->TunnelDirConns)
  3009. REJECT("Must set TunnelDirConns if PreferTunneledDirConns is set.");
  3010. if (options->AutomapHostsSuffixes) {
  3011. SMARTLIST_FOREACH(options->AutomapHostsSuffixes, char *, suf,
  3012. {
  3013. size_t len = strlen(suf);
  3014. if (len && suf[len-1] == '.')
  3015. suf[len-1] = '\0';
  3016. });
  3017. }
  3018. return 0;
  3019. #undef REJECT
  3020. #undef COMPLAIN
  3021. }
  3022. /** Helper: return true iff s1 and s2 are both NULL, or both non-NULL
  3023. * equal strings. */
  3024. static int
  3025. opt_streq(const char *s1, const char *s2)
  3026. {
  3027. if (!s1 && !s2)
  3028. return 1;
  3029. else if (s1 && s2 && !strcmp(s1,s2))
  3030. return 1;
  3031. else
  3032. return 0;
  3033. }
  3034. /** Check if any of the previous options have changed but aren't allowed to. */
  3035. static int
  3036. options_transition_allowed(or_options_t *old, or_options_t *new_val,
  3037. char **msg)
  3038. {
  3039. if (!old)
  3040. return 0;
  3041. if (!opt_streq(old->PidFile, new_val->PidFile)) {
  3042. *msg = tor_strdup("PidFile is not allowed to change.");
  3043. return -1;
  3044. }
  3045. if (old->RunAsDaemon != new_val->RunAsDaemon) {
  3046. *msg = tor_strdup("While Tor is running, changing RunAsDaemon "
  3047. "is not allowed.");
  3048. return -1;
  3049. }
  3050. if (strcmp(old->DataDirectory,new_val->DataDirectory)!=0) {
  3051. char buf[1024];
  3052. int r = tor_snprintf(buf, sizeof(buf),
  3053. "While Tor is running, changing DataDirectory "
  3054. "(\"%s\"->\"%s\") is not allowed.",
  3055. old->DataDirectory, new_val->DataDirectory);
  3056. *msg = tor_strdup(r >= 0 ? buf : "internal error");
  3057. return -1;
  3058. }
  3059. if (!opt_streq(old->User, new_val->User)) {
  3060. *msg = tor_strdup("While Tor is running, changing User is not allowed.");
  3061. return -1;
  3062. }
  3063. if (!opt_streq(old->Group, new_val->Group)) {
  3064. *msg = tor_strdup("While Tor is running, changing Group is not allowed.");
  3065. return -1;
  3066. }
  3067. if (old->HardwareAccel != new_val->HardwareAccel) {
  3068. *msg = tor_strdup("While Tor is running, changing HardwareAccel is "
  3069. "not allowed.");
  3070. return -1;
  3071. }
  3072. return 0;
  3073. }
  3074. /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
  3075. * will require us to rotate the cpu and dns workers; else return 0. */
  3076. static int
  3077. options_transition_affects_workers(or_options_t *old_options,
  3078. or_options_t *new_options)
  3079. {
  3080. if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
  3081. old_options->NumCpus != new_options->NumCpus ||
  3082. old_options->ORPort != new_options->ORPort ||
  3083. old_options->ServerDNSSearchDomains !=
  3084. new_options->ServerDNSSearchDomains ||
  3085. old_options->SafeLogging != new_options->SafeLogging ||
  3086. old_options->ClientOnly != new_options->ClientOnly ||
  3087. !config_lines_eq(old_options->Logs, new_options->Logs))
  3088. return 1;
  3089. /* Check whether log options match. */
  3090. /* Nothing that changed matters. */
  3091. return 0;
  3092. }
  3093. /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
  3094. * will require us to generate a new descriptor; else return 0. */
  3095. static int
  3096. options_transition_affects_descriptor(or_options_t *old_options,
  3097. or_options_t *new_options)
  3098. {
  3099. if (!opt_streq(old_options->DataDirectory, new_options->DataDirectory) ||
  3100. !opt_streq(old_options->Nickname,new_options->Nickname) ||
  3101. !opt_streq(old_options->Address,new_options->Address) ||
  3102. !config_lines_eq(old_options->ExitPolicy,new_options->ExitPolicy) ||
  3103. old_options->ExitPolicyRejectPrivate !=
  3104. new_options->ExitPolicyRejectPrivate ||
  3105. old_options->ORPort != new_options->ORPort ||
  3106. old_options->DirPort != new_options->DirPort ||
  3107. old_options->ClientOnly != new_options->ClientOnly ||
  3108. old_options->NoPublish != new_options->NoPublish ||
  3109. old_options->_PublishServerDescriptor !=
  3110. new_options->_PublishServerDescriptor ||
  3111. old_options->BandwidthRate != new_options->BandwidthRate ||
  3112. old_options->BandwidthBurst != new_options->BandwidthBurst ||
  3113. !opt_streq(old_options->ContactInfo, new_options->ContactInfo) ||
  3114. !opt_streq(old_options->MyFamily, new_options->MyFamily) ||
  3115. !opt_streq(old_options->AccountingStart, new_options->AccountingStart) ||
  3116. old_options->AccountingMax != new_options->AccountingMax)
  3117. return 1;
  3118. return 0;
  3119. }
  3120. #ifdef MS_WINDOWS
  3121. /** Return the directory on windows where we expect to find our application
  3122. * data. */
  3123. static char *
  3124. get_windows_conf_root(void)
  3125. {
  3126. static int is_set = 0;
  3127. static char path[MAX_PATH+1];
  3128. LPITEMIDLIST idl;
  3129. IMalloc *m;
  3130. HRESULT result;
  3131. if (is_set)
  3132. return path;
  3133. /* Find X:\documents and settings\username\application data\ .
  3134. * We would use SHGetSpecialFolder path, but that wasn't added until IE4.
  3135. */
  3136. if (!SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_APPDATA,
  3137. &idl))) {
  3138. GetCurrentDirectory(MAX_PATH, path);
  3139. is_set = 1;
  3140. log_warn(LD_CONFIG,
  3141. "I couldn't find your application data folder: are you "
  3142. "running an ancient version of Windows 95? Defaulting to \"%s\"",
  3143. path);
  3144. return path;
  3145. }
  3146. /* Convert the path from an "ID List" (whatever that is!) to a path. */
  3147. result = SHGetPathFromIDList(idl, path);
  3148. /* Now we need to free the */
  3149. SHGetMalloc(&m);
  3150. if (m) {
  3151. m->lpVtbl->Free(m, idl);
  3152. m->lpVtbl->Release(m);
  3153. }
  3154. if (!SUCCEEDED(result)) {
  3155. return NULL;
  3156. }
  3157. strlcat(path,"\\tor",MAX_PATH);
  3158. is_set = 1;
  3159. return path;
  3160. }
  3161. #endif
  3162. /** Return the default location for our torrc file. */
  3163. static const char *
  3164. get_default_conf_file(void)
  3165. {
  3166. #ifdef MS_WINDOWS
  3167. static char path[MAX_PATH+1];
  3168. strlcpy(path, get_windows_conf_root(), MAX_PATH);
  3169. strlcat(path,"\\torrc",MAX_PATH);
  3170. return path;
  3171. #else
  3172. return (CONFDIR "/torrc");
  3173. #endif
  3174. }
  3175. /** Verify whether lst is a string containing valid-looking space-separated
  3176. * nicknames, or NULL. Return 0 on success. Warn and return -1 on failure.
  3177. */
  3178. static int
  3179. check_nickname_list(const char *lst, const char *name, char **msg)
  3180. {
  3181. int r = 0;
  3182. smartlist_t *sl;
  3183. if (!lst)
  3184. return 0;
  3185. sl = smartlist_create();
  3186. smartlist_split_string(sl, lst, ",", SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3187. SMARTLIST_FOREACH(sl, const char *, s,
  3188. {
  3189. if (!is_legal_nickname_or_hexdigest(s)) {
  3190. char buf[1024];
  3191. int tmp = tor_snprintf(buf, sizeof(buf),
  3192. "Invalid nickname '%s' in %s line", s, name);
  3193. *msg = tor_strdup(tmp >= 0 ? buf : "internal error");
  3194. r = -1;
  3195. break;
  3196. }
  3197. });
  3198. SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
  3199. smartlist_free(sl);
  3200. return r;
  3201. }
  3202. /** Learn config file name from command line arguments, or use the default */
  3203. static char *
  3204. find_torrc_filename(int argc, char **argv,
  3205. int *using_default_torrc, int *ignore_missing_torrc)
  3206. {
  3207. char *fname=NULL;
  3208. int i;
  3209. for (i = 1; i < argc; ++i) {
  3210. if (i < argc-1 && !strcmp(argv[i],"-f")) {
  3211. if (fname) {
  3212. log(LOG_WARN, LD_CONFIG, "Duplicate -f options on command line.");
  3213. tor_free(fname);
  3214. }
  3215. #ifdef MS_WINDOWS
  3216. /* XXX one day we might want to extend expand_filename to work
  3217. * under Windows as well. */
  3218. fname = tor_strdup(argv[i+1]);
  3219. #else
  3220. fname = expand_filename(argv[i+1]);
  3221. #endif
  3222. *using_default_torrc = 0;
  3223. ++i;
  3224. } else if (!strcmp(argv[i],"--ignore-missing-torrc")) {
  3225. *ignore_missing_torrc = 1;
  3226. }
  3227. }
  3228. if (*using_default_torrc) {
  3229. /* didn't find one, try CONFDIR */
  3230. const char *dflt = get_default_conf_file();
  3231. if (dflt && file_status(dflt) == FN_FILE) {
  3232. fname = tor_strdup(dflt);
  3233. } else {
  3234. #ifndef MS_WINDOWS
  3235. char *fn;
  3236. fn = expand_filename("~/.torrc");
  3237. if (fn && file_status(fn) == FN_FILE) {
  3238. fname = fn;
  3239. } else {
  3240. tor_free(fn);
  3241. fname = tor_strdup(dflt);
  3242. }
  3243. #else
  3244. fname = tor_strdup(dflt);
  3245. #endif
  3246. }
  3247. }
  3248. return fname;
  3249. }
  3250. /** Load torrc from disk, setting torrc_fname if successful */
  3251. static char *
  3252. load_torrc_from_disk(int argc, char **argv)
  3253. {
  3254. char *fname=NULL;
  3255. char *cf = NULL;
  3256. int using_default_torrc = 1;
  3257. int ignore_missing_torrc = 0;
  3258. fname = find_torrc_filename(argc, argv,
  3259. &using_default_torrc, &ignore_missing_torrc);
  3260. tor_assert(fname);
  3261. log(LOG_DEBUG, LD_CONFIG, "Opening config file \"%s\"", fname);
  3262. tor_free(torrc_fname);
  3263. torrc_fname = fname;
  3264. /* Open config file */
  3265. if (file_status(fname) != FN_FILE ||
  3266. !(cf = read_file_to_str(fname,0,NULL))) {
  3267. if (using_default_torrc == 1 || ignore_missing_torrc ) {
  3268. log(LOG_NOTICE, LD_CONFIG, "Configuration file \"%s\" not present, "
  3269. "using reasonable defaults.", fname);
  3270. tor_free(fname); /* sets fname to NULL */
  3271. torrc_fname = NULL;
  3272. cf = tor_strdup("");
  3273. } else {
  3274. log(LOG_WARN, LD_CONFIG,
  3275. "Unable to open configuration file \"%s\".", fname);
  3276. goto err;
  3277. }
  3278. }
  3279. return cf;
  3280. err:
  3281. tor_free(fname);
  3282. torrc_fname = NULL;
  3283. return NULL;
  3284. }
  3285. /** Read a configuration file into <b>options</b>, finding the configuration
  3286. * file location based on the command line. After loading the file
  3287. * call options_init_from_string() to load the config.
  3288. * Return 0 if success, -1 if failure. */
  3289. int
  3290. options_init_from_torrc(int argc, char **argv)
  3291. {
  3292. char *cf=NULL;
  3293. int i, retval, command;
  3294. static char **backup_argv;
  3295. static int backup_argc;
  3296. char *command_arg = NULL;
  3297. char *errmsg=NULL;
  3298. if (argv) { /* first time we're called. save commandline args */
  3299. backup_argv = argv;
  3300. backup_argc = argc;
  3301. } else { /* we're reloading. need to clean up old options first. */
  3302. argv = backup_argv;
  3303. argc = backup_argc;
  3304. }
  3305. if (argc > 1 && (!strcmp(argv[1], "-h") || !strcmp(argv[1],"--help"))) {
  3306. print_usage();
  3307. exit(0);
  3308. }
  3309. if (argc > 1 && !strcmp(argv[1], "--list-torrc-options")) {
  3310. /* For documenting validating whether we've documented everything. */
  3311. list_torrc_options();
  3312. exit(0);
  3313. }
  3314. if (argc > 1 && (!strcmp(argv[1],"--version"))) {
  3315. printf("Tor version %s.\n",get_version());
  3316. if (argc > 2 && (!strcmp(argv[2],"--version"))) {
  3317. print_svn_version();
  3318. }
  3319. exit(0);
  3320. }
  3321. /* Go through command-line variables */
  3322. if (!global_cmdline_options) {
  3323. /* Or we could redo the list every time we pass this place.
  3324. * It does not really matter */
  3325. if (config_get_commandlines(argc, argv, &global_cmdline_options) < 0) {
  3326. goto err;
  3327. }
  3328. }
  3329. command = CMD_RUN_TOR;
  3330. for (i = 1; i < argc; ++i) {
  3331. if (!strcmp(argv[i],"--list-fingerprint")) {
  3332. command = CMD_LIST_FINGERPRINT;
  3333. } else if (!strcmp(argv[i],"--hash-password")) {
  3334. command = CMD_HASH_PASSWORD;
  3335. command_arg = tor_strdup( (i < argc-1) ? argv[i+1] : "");
  3336. ++i;
  3337. } else if (!strcmp(argv[i],"--verify-config")) {
  3338. command = CMD_VERIFY_CONFIG;
  3339. }
  3340. }
  3341. cf = load_torrc_from_disk(argc, argv);
  3342. if (!cf)
  3343. goto err;
  3344. retval = options_init_from_string(cf, command, command_arg, &errmsg);
  3345. tor_free(cf);
  3346. if (retval < 0)
  3347. goto err;
  3348. return 0;
  3349. err:
  3350. if (errmsg) {
  3351. log(LOG_WARN,LD_CONFIG,"%s", errmsg);
  3352. tor_free(errmsg);
  3353. }
  3354. return -1;
  3355. }
  3356. /** Load the options from the configuration in <b>cf</b>, validate
  3357. * them for consistency and take actions based on them.
  3358. *
  3359. * Return 0 if success, negative on error:
  3360. * * -1 for general errors.
  3361. * * -2 for failure to parse/validate,
  3362. * * -3 for transition not allowed
  3363. * * -4 for error while setting the new options
  3364. */
  3365. int
  3366. options_init_from_string(const char *cf,
  3367. int command, const char *command_arg,
  3368. char **msg)
  3369. {
  3370. or_options_t *oldoptions, *newoptions;
  3371. config_line_t *cl;
  3372. int retval;
  3373. int err = -1;
  3374. assert(msg);
  3375. oldoptions = global_options; /* get_options unfortunately asserts if
  3376. this is the first time we run*/
  3377. newoptions = tor_malloc_zero(sizeof(or_options_t));
  3378. newoptions->_magic = OR_OPTIONS_MAGIC;
  3379. options_init(newoptions);
  3380. newoptions->command = command;
  3381. newoptions->command_arg = command_arg;
  3382. /* get config lines, assign them */
  3383. retval = config_get_lines(cf, &cl);
  3384. if (retval < 0) {
  3385. err = -2;
  3386. goto err;
  3387. }
  3388. retval = config_assign(&options_format, newoptions, cl, 0, 0, msg);
  3389. config_free_lines(cl);
  3390. if (retval < 0) {
  3391. err = -2;
  3392. goto err;
  3393. }
  3394. /* Go through command-line variables too */
  3395. retval = config_assign(&options_format, newoptions,
  3396. global_cmdline_options, 0, 0, msg);
  3397. if (retval < 0) {
  3398. err = -2;
  3399. goto err;
  3400. }
  3401. /* Validate newoptions */
  3402. if (options_validate(oldoptions, newoptions, 0, msg) < 0) {
  3403. err = -2;
  3404. goto err;
  3405. }
  3406. if (options_transition_allowed(oldoptions, newoptions, msg) < 0) {
  3407. err = -3;
  3408. goto err;
  3409. }
  3410. if (set_options(newoptions, msg)) {
  3411. err = -4;
  3412. goto err; /* frees and replaces old options */
  3413. }
  3414. return 0;
  3415. err:
  3416. config_free(&options_format, newoptions);
  3417. if (*msg) {
  3418. int len = strlen(*msg)+256;
  3419. char *newmsg = tor_malloc(len);
  3420. tor_snprintf(newmsg, len, "Failed to parse/validate config: %s", *msg);
  3421. tor_free(*msg);
  3422. *msg = newmsg;
  3423. }
  3424. return err;
  3425. }
  3426. /** Return the location for our configuration file.
  3427. */
  3428. const char *
  3429. get_torrc_fname(void)
  3430. {
  3431. if (torrc_fname)
  3432. return torrc_fname;
  3433. else
  3434. return get_default_conf_file();
  3435. }
  3436. /** Adjust the address map mased on the MapAddress elements in the
  3437. * configuration <b>options</b>
  3438. */
  3439. static void
  3440. config_register_addressmaps(or_options_t *options)
  3441. {
  3442. smartlist_t *elts;
  3443. config_line_t *opt;
  3444. char *from, *to;
  3445. addressmap_clear_configured();
  3446. elts = smartlist_create();
  3447. for (opt = options->AddressMap; opt; opt = opt->next) {
  3448. smartlist_split_string(elts, opt->value, NULL,
  3449. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  3450. if (smartlist_len(elts) >= 2) {
  3451. from = smartlist_get(elts,0);
  3452. to = smartlist_get(elts,1);
  3453. if (address_is_invalid_destination(to, 1)) {
  3454. log_warn(LD_CONFIG,
  3455. "Skipping invalid argument '%s' to MapAddress", to);
  3456. } else {
  3457. addressmap_register(from, tor_strdup(to), 0, ADDRMAPSRC_TORRC);
  3458. if (smartlist_len(elts)>2) {
  3459. log_warn(LD_CONFIG,"Ignoring extra arguments to MapAddress.");
  3460. }
  3461. }
  3462. } else {
  3463. log_warn(LD_CONFIG,"MapAddress '%s' has too few arguments. Ignoring.",
  3464. opt->value);
  3465. }
  3466. SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
  3467. smartlist_clear(elts);
  3468. }
  3469. smartlist_free(elts);
  3470. }
  3471. /**
  3472. * Initialize the logs based on the configuration file.
  3473. */
  3474. static int
  3475. options_init_logs(or_options_t *options, int validate_only)
  3476. {
  3477. config_line_t *opt;
  3478. int ok;
  3479. smartlist_t *elts;
  3480. int daemon =
  3481. #ifdef MS_WINDOWS
  3482. 0;
  3483. #else
  3484. options->RunAsDaemon;
  3485. #endif
  3486. ok = 1;
  3487. elts = smartlist_create();
  3488. for (opt = options->Logs; opt; opt = opt->next) {
  3489. log_severity_list_t *severity;
  3490. const char *cfg = opt->value;
  3491. severity = tor_malloc_zero(sizeof(log_severity_list_t));
  3492. if (parse_log_severity_config(&cfg, severity) < 0) {
  3493. log_warn(LD_CONFIG, "Couldn't parse log levels in Log option 'Log %s'",
  3494. opt->value);
  3495. ok = 0; goto cleanup;
  3496. }
  3497. smartlist_split_string(elts, cfg, NULL,
  3498. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  3499. if (smartlist_len(elts) == 0)
  3500. smartlist_add(elts, tor_strdup("stdout"));
  3501. if (smartlist_len(elts) == 1 &&
  3502. (!strcasecmp(smartlist_get(elts,0), "stdout") ||
  3503. !strcasecmp(smartlist_get(elts,0), "stderr"))) {
  3504. int err = smartlist_len(elts) &&
  3505. !strcasecmp(smartlist_get(elts,0), "stderr");
  3506. if (!validate_only) {
  3507. if (daemon) {
  3508. log_warn(LD_CONFIG,
  3509. "Can't log to %s with RunAsDaemon set; skipping stdout",
  3510. err?"stderr":"stdout");
  3511. } else {
  3512. add_stream_log(severity, err?"<stderr>":"<stdout>",
  3513. err?stderr:stdout);
  3514. }
  3515. }
  3516. goto cleanup;
  3517. }
  3518. if (smartlist_len(elts) == 1 &&
  3519. !strcasecmp(smartlist_get(elts,0), "syslog")) {
  3520. #ifdef HAVE_SYSLOG_H
  3521. if (!validate_only) {
  3522. add_syslog_log(severity);
  3523. }
  3524. #else
  3525. log_warn(LD_CONFIG, "Syslog is not supported on this system. Sorry.");
  3526. #endif
  3527. goto cleanup;
  3528. }
  3529. if (smartlist_len(elts) == 2 &&
  3530. !strcasecmp(smartlist_get(elts,0), "file")) {
  3531. if (!validate_only) {
  3532. if (add_file_log(severity, smartlist_get(elts, 1)) < 0) {
  3533. log_warn(LD_CONFIG, "Couldn't open file for 'Log %s'", opt->value);
  3534. ok = 0;
  3535. }
  3536. }
  3537. goto cleanup;
  3538. }
  3539. log_warn(LD_CONFIG, "Bad syntax on file Log option 'Log %s'",
  3540. opt->value);
  3541. ok = 0; goto cleanup;
  3542. cleanup:
  3543. SMARTLIST_FOREACH(elts, char*, cp, tor_free(cp));
  3544. smartlist_clear(elts);
  3545. tor_free(severity);
  3546. }
  3547. smartlist_free(elts);
  3548. return ok?0:-1;
  3549. }
  3550. /** Parse a single RedirectExit line's contents from <b>line</b>. If
  3551. * they are valid, and <b>result</b> is not NULL, add an element to
  3552. * <b>result</b> and return 0. Else if they are valid, return 0.
  3553. * Else set *msg and return -1. */
  3554. static int
  3555. parse_redirect_line(smartlist_t *result, config_line_t *line, char **msg)
  3556. {
  3557. smartlist_t *elements = NULL;
  3558. exit_redirect_t *r;
  3559. tor_assert(line);
  3560. r = tor_malloc_zero(sizeof(exit_redirect_t));
  3561. elements = smartlist_create();
  3562. smartlist_split_string(elements, line->value, NULL,
  3563. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3564. if (smartlist_len(elements) != 2) {
  3565. *msg = tor_strdup("Wrong number of elements in RedirectExit line");
  3566. goto err;
  3567. }
  3568. if (parse_addr_and_port_range(smartlist_get(elements,0),&r->addr,
  3569. &r->maskbits,&r->port_min,&r->port_max)) {
  3570. *msg = tor_strdup("Error parsing source address in RedirectExit line");
  3571. goto err;
  3572. }
  3573. if (0==strcasecmp(smartlist_get(elements,1), "pass")) {
  3574. r->is_redirect = 0;
  3575. } else {
  3576. if (parse_addr_port(LOG_WARN, smartlist_get(elements,1),NULL,
  3577. &r->addr_dest, &r->port_dest)) {
  3578. *msg = tor_strdup("Error parsing dest address in RedirectExit line");
  3579. goto err;
  3580. }
  3581. r->is_redirect = 1;
  3582. }
  3583. goto done;
  3584. err:
  3585. tor_free(r);
  3586. done:
  3587. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  3588. smartlist_free(elements);
  3589. if (r) {
  3590. if (result)
  3591. smartlist_add(result, r);
  3592. else
  3593. tor_free(r);
  3594. return 0;
  3595. } else {
  3596. tor_assert(*msg);
  3597. return -1;
  3598. }
  3599. }
  3600. /** Read the contents of a Bridge line from <b>line</b>. Return 0
  3601. * if the line is well-formed, and -1 if it isn't. If
  3602. * <b>validate_only</b> is 0, and the line is well-formed, then add
  3603. * the bridge described in the line to our internal bridge list. */
  3604. static int
  3605. parse_bridge_line(const char *line, int validate_only)
  3606. {
  3607. smartlist_t *items = NULL;
  3608. int r;
  3609. char *addrport=NULL, *address=NULL, *fingerprint=NULL;
  3610. uint32_t addr = 0;
  3611. uint16_t port = 0;
  3612. char digest[DIGEST_LEN];
  3613. items = smartlist_create();
  3614. smartlist_split_string(items, line, NULL,
  3615. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  3616. if (smartlist_len(items) < 1) {
  3617. log_warn(LD_CONFIG, "Too few arguments to Bridge line.");
  3618. goto err;
  3619. }
  3620. addrport = smartlist_get(items, 0);
  3621. smartlist_del_keeporder(items, 0);
  3622. if (parse_addr_port(LOG_WARN, addrport, &address, &addr, &port)<0) {
  3623. log_warn(LD_CONFIG, "Error parsing Bridge address '%s'", addrport);
  3624. goto err;
  3625. }
  3626. if (!port) {
  3627. log_warn(LD_CONFIG, "Missing port in Bridge address '%s'",addrport);
  3628. goto err;
  3629. }
  3630. if (smartlist_len(items)) {
  3631. fingerprint = smartlist_join_strings(items, "", 0, NULL);
  3632. if (strlen(fingerprint) != HEX_DIGEST_LEN) {
  3633. log_warn(LD_CONFIG, "Key digest for Bridge is wrong length.");
  3634. goto err;
  3635. }
  3636. if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
  3637. log_warn(LD_CONFIG, "Unable to decode Bridge key digest.");
  3638. goto err;
  3639. }
  3640. }
  3641. if (!validate_only) {
  3642. log_debug(LD_DIR, "Bridge at %s:%d (%s)", address,
  3643. (int)port,
  3644. fingerprint ? fingerprint : "no key listed");
  3645. bridge_add_from_config(addr, port, fingerprint ? digest : NULL);
  3646. }
  3647. r = 0;
  3648. goto done;
  3649. err:
  3650. r = -1;
  3651. done:
  3652. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  3653. smartlist_free(items);
  3654. tor_free(addrport);
  3655. tor_free(address);
  3656. tor_free(fingerprint);
  3657. return r;
  3658. }
  3659. /** Read the contents of a DirServer line from <b>line</b>. If
  3660. * <b>validate_only</b> is 0, and the line is well-formed, and it
  3661. * shares any bits with <b>required_type</b> or <b>required_type</b>
  3662. * is 0, then add the dirserver described in the line (minus whatever
  3663. * bits it's missing) as a valid authority. Return 0 on success,
  3664. * or -1 if the line isn't well-formed or if we can't add it. */
  3665. static int
  3666. parse_dir_server_line(const char *line, authority_type_t required_type,
  3667. int validate_only)
  3668. {
  3669. smartlist_t *items = NULL;
  3670. int r;
  3671. char *addrport=NULL, *address=NULL, *nickname=NULL, *fingerprint=NULL;
  3672. uint16_t dir_port = 0, or_port = 0;
  3673. char digest[DIGEST_LEN];
  3674. char v3_digest[DIGEST_LEN];
  3675. authority_type_t type = V2_AUTHORITY;
  3676. int is_not_hidserv_authority = 0, is_not_v2_authority = 0;
  3677. items = smartlist_create();
  3678. smartlist_split_string(items, line, NULL,
  3679. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, -1);
  3680. if (smartlist_len(items) < 1) {
  3681. log_warn(LD_CONFIG, "No arguments on DirServer line.");
  3682. goto err;
  3683. }
  3684. if (is_legal_nickname(smartlist_get(items, 0))) {
  3685. nickname = smartlist_get(items, 0);
  3686. smartlist_del_keeporder(items, 0);
  3687. }
  3688. while (smartlist_len(items)) {
  3689. char *flag = smartlist_get(items, 0);
  3690. if (TOR_ISDIGIT(flag[0]))
  3691. break;
  3692. if (!strcasecmp(flag, "v1")) {
  3693. type |= (V1_AUTHORITY | HIDSERV_AUTHORITY);
  3694. } else if (!strcasecmp(flag, "hs")) {
  3695. type |= HIDSERV_AUTHORITY;
  3696. } else if (!strcasecmp(flag, "no-hs")) {
  3697. is_not_hidserv_authority = 1;
  3698. } else if (!strcasecmp(flag, "bridge")) {
  3699. type |= BRIDGE_AUTHORITY;
  3700. } else if (!strcasecmp(flag, "no-v2")) {
  3701. is_not_v2_authority = 1;
  3702. } else if (!strcasecmpstart(flag, "orport=")) {
  3703. int ok;
  3704. char *portstring = flag + strlen("orport=");
  3705. or_port = (uint16_t) tor_parse_long(portstring, 10, 1, 65535, &ok, NULL);
  3706. if (!ok)
  3707. log_warn(LD_CONFIG, "Invalid orport '%s' on DirServer line.",
  3708. portstring);
  3709. } else if (!strcasecmpstart(flag, "v3ident=")) {
  3710. char *idstr = flag + strlen("v3ident=");
  3711. if (strlen(idstr) != HEX_DIGEST_LEN ||
  3712. base16_decode(v3_digest, DIGEST_LEN, idstr, HEX_DIGEST_LEN)<0) {
  3713. log_warn(LD_CONFIG, "Bad v3 identity digest '%s' on DirServer line",
  3714. flag);
  3715. } else {
  3716. type |= V3_AUTHORITY;
  3717. }
  3718. } else {
  3719. log_warn(LD_CONFIG, "Unrecognized flag '%s' on DirServer line",
  3720. flag);
  3721. }
  3722. tor_free(flag);
  3723. smartlist_del_keeporder(items, 0);
  3724. }
  3725. if (is_not_hidserv_authority)
  3726. type &= ~HIDSERV_AUTHORITY;
  3727. if (is_not_v2_authority)
  3728. type &= ~V2_AUTHORITY;
  3729. if (smartlist_len(items) < 2) {
  3730. log_warn(LD_CONFIG, "Too few arguments to DirServer line.");
  3731. goto err;
  3732. }
  3733. addrport = smartlist_get(items, 0);
  3734. smartlist_del_keeporder(items, 0);
  3735. if (parse_addr_port(LOG_WARN, addrport, &address, NULL, &dir_port)<0) {
  3736. log_warn(LD_CONFIG, "Error parsing DirServer address '%s'", addrport);
  3737. goto err;
  3738. }
  3739. if (!dir_port) {
  3740. log_warn(LD_CONFIG, "Missing port in DirServer address '%s'",addrport);
  3741. goto err;
  3742. }
  3743. fingerprint = smartlist_join_strings(items, "", 0, NULL);
  3744. if (strlen(fingerprint) != HEX_DIGEST_LEN) {
  3745. log_warn(LD_CONFIG, "Key digest for DirServer is wrong length %d.",
  3746. (int)strlen(fingerprint));
  3747. goto err;
  3748. }
  3749. if (!strcmp(fingerprint, "E623F7625FBE0C87820F11EC5F6D5377ED816294")) {
  3750. /* a known bad fingerprint. refuse to use it. We can remove this
  3751. * clause once Tor 0.1.2.17 is obsolete. */
  3752. log_warn(LD_CONFIG, "Dangerous dirserver line. To correct, erase your "
  3753. "torrc file (%s), or reinstall Tor and use the default torrc.",
  3754. get_torrc_fname());
  3755. goto err;
  3756. }
  3757. if (base16_decode(digest, DIGEST_LEN, fingerprint, HEX_DIGEST_LEN)<0) {
  3758. log_warn(LD_CONFIG, "Unable to decode DirServer key digest.");
  3759. goto err;
  3760. }
  3761. if (!validate_only && (!required_type || required_type & type)) {
  3762. if (required_type)
  3763. type &= required_type; /* pare down what we think of them as an
  3764. * authority for. */
  3765. log_debug(LD_DIR, "Trusted %d dirserver at %s:%d (%s)", (int)type,
  3766. address, (int)dir_port, (char*)smartlist_get(items,0));
  3767. if (!add_trusted_dir_server(nickname, address, dir_port, or_port,
  3768. digest, v3_digest, type))
  3769. goto err;
  3770. }
  3771. r = 0;
  3772. goto done;
  3773. err:
  3774. r = -1;
  3775. done:
  3776. SMARTLIST_FOREACH(items, char*, s, tor_free(s));
  3777. smartlist_free(items);
  3778. tor_free(addrport);
  3779. tor_free(address);
  3780. tor_free(nickname);
  3781. tor_free(fingerprint);
  3782. return r;
  3783. }
  3784. /** Adjust the value of options->DataDirectory, or fill it in if it's
  3785. * absent. Return 0 on success, -1 on failure. */
  3786. static int
  3787. normalize_data_directory(or_options_t *options)
  3788. {
  3789. #ifdef MS_WINDOWS
  3790. char *p;
  3791. if (options->DataDirectory)
  3792. return 0; /* all set */
  3793. p = tor_malloc(MAX_PATH);
  3794. strlcpy(p,get_windows_conf_root(),MAX_PATH);
  3795. options->DataDirectory = p;
  3796. return 0;
  3797. #else
  3798. const char *d = options->DataDirectory;
  3799. if (!d)
  3800. d = "~/.tor";
  3801. if (strncmp(d,"~/",2) == 0) {
  3802. char *fn = expand_filename(d);
  3803. if (!fn) {
  3804. log_warn(LD_CONFIG,"Failed to expand filename \"%s\".", d);
  3805. return -1;
  3806. }
  3807. if (!options->DataDirectory && !strcmp(fn,"/.tor")) {
  3808. /* If our homedir is /, we probably don't want to use it. */
  3809. /* Default to LOCALSTATEDIR/tor which is probably closer to what we
  3810. * want. */
  3811. log_warn(LD_CONFIG,
  3812. "Default DataDirectory is \"~/.tor\". This expands to "
  3813. "\"%s\", which is probably not what you want. Using "
  3814. "\"%s"PATH_SEPARATOR"tor\" instead", fn, LOCALSTATEDIR);
  3815. tor_free(fn);
  3816. fn = tor_strdup(LOCALSTATEDIR PATH_SEPARATOR "tor");
  3817. }
  3818. tor_free(options->DataDirectory);
  3819. options->DataDirectory = fn;
  3820. }
  3821. return 0;
  3822. #endif
  3823. }
  3824. /** Check and normalize the value of options->DataDirectory; return 0 if it
  3825. * sane, -1 otherwise. */
  3826. static int
  3827. validate_data_directory(or_options_t *options)
  3828. {
  3829. if (normalize_data_directory(options) < 0)
  3830. return -1;
  3831. tor_assert(options->DataDirectory);
  3832. if (strlen(options->DataDirectory) > (512-128)) {
  3833. log_warn(LD_CONFIG, "DataDirectory is too long.");
  3834. return -1;
  3835. }
  3836. return 0;
  3837. }
  3838. /** This string must remain the same forevermore. It is how we
  3839. * recognize that the torrc file doesn't need to be backed up. */
  3840. #define GENERATED_FILE_PREFIX "# This file was generated by Tor; " \
  3841. "if you edit it, comments will not be preserved"
  3842. /** This string can change; it tries to give the reader an idea
  3843. * that editing this file by hand is not a good plan. */
  3844. #define GENERATED_FILE_COMMENT "# The old torrc file was renamed " \
  3845. "to torrc.orig.1 or similar, and Tor will ignore it"
  3846. /** Save a configuration file for the configuration in <b>options</b>
  3847. * into the file <b>fname</b>. If the file already exists, and
  3848. * doesn't begin with GENERATED_FILE_PREFIX, rename it. Otherwise
  3849. * replace it. Return 0 on success, -1 on failure. */
  3850. static int
  3851. write_configuration_file(const char *fname, or_options_t *options)
  3852. {
  3853. char *old_val=NULL, *new_val=NULL, *new_conf=NULL;
  3854. int rename_old = 0, r;
  3855. size_t len;
  3856. if (fname) {
  3857. switch (file_status(fname)) {
  3858. case FN_FILE:
  3859. old_val = read_file_to_str(fname, 0, NULL);
  3860. if (strcmpstart(old_val, GENERATED_FILE_PREFIX)) {
  3861. rename_old = 1;
  3862. }
  3863. tor_free(old_val);
  3864. break;
  3865. case FN_NOENT:
  3866. break;
  3867. case FN_ERROR:
  3868. case FN_DIR:
  3869. default:
  3870. log_warn(LD_CONFIG,
  3871. "Config file \"%s\" is not a file? Failing.", fname);
  3872. return -1;
  3873. }
  3874. }
  3875. if (!(new_conf = options_dump(options, 1))) {
  3876. log_warn(LD_BUG, "Couldn't get configuration string");
  3877. goto err;
  3878. }
  3879. len = strlen(new_conf)+256;
  3880. new_val = tor_malloc(len);
  3881. tor_snprintf(new_val, len, "%s\n%s\n\n%s",
  3882. GENERATED_FILE_PREFIX, GENERATED_FILE_COMMENT, new_conf);
  3883. if (rename_old) {
  3884. int i = 1;
  3885. size_t fn_tmp_len = strlen(fname)+32;
  3886. char *fn_tmp;
  3887. tor_assert(fn_tmp_len > strlen(fname)); /*check for overflow*/
  3888. fn_tmp = tor_malloc(fn_tmp_len);
  3889. while (1) {
  3890. if (tor_snprintf(fn_tmp, fn_tmp_len, "%s.orig.%d", fname, i)<0) {
  3891. log_warn(LD_BUG, "tor_snprintf failed inexplicably");
  3892. tor_free(fn_tmp);
  3893. goto err;
  3894. }
  3895. if (file_status(fn_tmp) == FN_NOENT)
  3896. break;
  3897. ++i;
  3898. }
  3899. log_notice(LD_CONFIG, "Renaming old configuration file to \"%s\"", fn_tmp);
  3900. if (rename(fname, fn_tmp) < 0) {
  3901. log_warn(LD_FS,
  3902. "Couldn't rename configuration file \"%s\" to \"%s\": %s",
  3903. fname, fn_tmp, strerror(errno));
  3904. tor_free(fn_tmp);
  3905. goto err;
  3906. }
  3907. tor_free(fn_tmp);
  3908. }
  3909. if (write_str_to_file(fname, new_val, 0) < 0)
  3910. goto err;
  3911. r = 0;
  3912. goto done;
  3913. err:
  3914. r = -1;
  3915. done:
  3916. tor_free(new_val);
  3917. tor_free(new_conf);
  3918. return r;
  3919. }
  3920. /**
  3921. * Save the current configuration file value to disk. Return 0 on
  3922. * success, -1 on failure.
  3923. **/
  3924. int
  3925. options_save_current(void)
  3926. {
  3927. if (torrc_fname) {
  3928. /* This fails if we can't write to our configuration file.
  3929. *
  3930. * If we try falling back to datadirectory or something, we have a better
  3931. * chance of saving the configuration, but a better chance of doing
  3932. * something the user never expected. Let's just warn instead. */
  3933. return write_configuration_file(torrc_fname, get_options());
  3934. }
  3935. return write_configuration_file(get_default_conf_file(), get_options());
  3936. }
  3937. /** Mapping from a unit name to a multiplier for converting that unit into a
  3938. * base unit. */
  3939. struct unit_table_t {
  3940. const char *unit;
  3941. uint64_t multiplier;
  3942. };
  3943. static struct unit_table_t memory_units[] = {
  3944. { "", 1 },
  3945. { "b", 1<< 0 },
  3946. { "byte", 1<< 0 },
  3947. { "bytes", 1<< 0 },
  3948. { "kb", 1<<10 },
  3949. { "kbyte", 1<<10 },
  3950. { "kbytes", 1<<10 },
  3951. { "kilobyte", 1<<10 },
  3952. { "kilobytes", 1<<10 },
  3953. { "m", 1<<20 },
  3954. { "mb", 1<<20 },
  3955. { "mbyte", 1<<20 },
  3956. { "mbytes", 1<<20 },
  3957. { "megabyte", 1<<20 },
  3958. { "megabytes", 1<<20 },
  3959. { "gb", 1<<30 },
  3960. { "gbyte", 1<<30 },
  3961. { "gbytes", 1<<30 },
  3962. { "gigabyte", 1<<30 },
  3963. { "gigabytes", 1<<30 },
  3964. { "tb", U64_LITERAL(1)<<40 },
  3965. { "terabyte", U64_LITERAL(1)<<40 },
  3966. { "terabytes", U64_LITERAL(1)<<40 },
  3967. { NULL, 0 },
  3968. };
  3969. static struct unit_table_t time_units[] = {
  3970. { "", 1 },
  3971. { "second", 1 },
  3972. { "seconds", 1 },
  3973. { "minute", 60 },
  3974. { "minutes", 60 },
  3975. { "hour", 60*60 },
  3976. { "hours", 60*60 },
  3977. { "day", 24*60*60 },
  3978. { "days", 24*60*60 },
  3979. { "week", 7*24*60*60 },
  3980. { "weeks", 7*24*60*60 },
  3981. { NULL, 0 },
  3982. };
  3983. /** Parse a string <b>val</b> containing a number, zero or more
  3984. * spaces, and an optional unit string. If the unit appears in the
  3985. * table <b>u</b>, then multiply the number by the unit multiplier.
  3986. * On success, set *<b>ok</b> to 1 and return this product.
  3987. * Otherwise, set *<b>ok</b> to 0.
  3988. */
  3989. static uint64_t
  3990. config_parse_units(const char *val, struct unit_table_t *u, int *ok)
  3991. {
  3992. uint64_t v;
  3993. char *cp;
  3994. tor_assert(ok);
  3995. v = tor_parse_uint64(val, 10, 0, UINT64_MAX, ok, &cp);
  3996. if (!*ok)
  3997. return 0;
  3998. if (!cp) {
  3999. *ok = 1;
  4000. return v;
  4001. }
  4002. while (TOR_ISSPACE(*cp))
  4003. ++cp;
  4004. for ( ;u->unit;++u) {
  4005. if (!strcasecmp(u->unit, cp)) {
  4006. v *= u->multiplier;
  4007. *ok = 1;
  4008. return v;
  4009. }
  4010. }
  4011. log_warn(LD_CONFIG, "Unknown unit '%s'.", cp);
  4012. *ok = 0;
  4013. return 0;
  4014. }
  4015. /** Parse a string in the format "number unit", where unit is a unit of
  4016. * information (byte, KB, M, etc). On success, set *<b>ok</b> to true
  4017. * and return the number of bytes specified. Otherwise, set
  4018. * *<b>ok</b> to false and return 0. */
  4019. static uint64_t
  4020. config_parse_memunit(const char *s, int *ok)
  4021. {
  4022. return config_parse_units(s, memory_units, ok);
  4023. }
  4024. /** Parse a string in the format "number unit", where unit is a unit of time.
  4025. * On success, set *<b>ok</b> to true and return the number of seconds in
  4026. * the provided interval. Otherwise, set *<b>ok</b> to 0 and return -1.
  4027. */
  4028. static int
  4029. config_parse_interval(const char *s, int *ok)
  4030. {
  4031. uint64_t r;
  4032. r = config_parse_units(s, time_units, ok);
  4033. if (!ok)
  4034. return -1;
  4035. if (r > INT_MAX) {
  4036. log_warn(LD_CONFIG, "Interval '%s' is too long", s);
  4037. *ok = 0;
  4038. return -1;
  4039. }
  4040. return (int)r;
  4041. }
  4042. /**
  4043. * Initialize the libevent library.
  4044. */
  4045. static void
  4046. init_libevent(void)
  4047. {
  4048. configure_libevent_logging();
  4049. /* If the kernel complains that some method (say, epoll) doesn't
  4050. * exist, we don't care about it, since libevent will cope.
  4051. */
  4052. suppress_libevent_log_msg("Function not implemented");
  4053. #ifdef __APPLE__
  4054. if (decode_libevent_version() < LE_11B) {
  4055. setenv("EVENT_NOKQUEUE","1",1);
  4056. }
  4057. #endif
  4058. event_init();
  4059. suppress_libevent_log_msg(NULL);
  4060. #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
  4061. /* Making this a NOTICE for now so we can link bugs to a libevent versions
  4062. * or methods better. */
  4063. log(LOG_NOTICE, LD_GENERAL,
  4064. "Initialized libevent version %s using method %s. Good.",
  4065. event_get_version(), event_get_method());
  4066. check_libevent_version(event_get_method(), get_options()->ORPort != 0);
  4067. #else
  4068. log(LOG_NOTICE, LD_GENERAL,
  4069. "Initialized old libevent (version 1.0b or earlier).");
  4070. log(LOG_WARN, LD_GENERAL,
  4071. "You have a *VERY* old version of libevent. It is likely to be buggy; "
  4072. "please build Tor with a more recent version.");
  4073. #endif
  4074. }
  4075. #if defined(HAVE_EVENT_GET_VERSION) && defined(HAVE_EVENT_GET_METHOD)
  4076. /** Table mapping return value of event_get_version() to le_version_t. */
  4077. static const struct {
  4078. const char *name; le_version_t version;
  4079. } le_version_table[] = {
  4080. /* earlier versions don't have get_version. */
  4081. { "1.0c", LE_10C },
  4082. { "1.0d", LE_10D },
  4083. { "1.0e", LE_10E },
  4084. { "1.1", LE_11 },
  4085. { "1.1a", LE_11A },
  4086. { "1.1b", LE_11B },
  4087. { "1.2", LE_12 },
  4088. { "1.2a", LE_12A },
  4089. { "1.3", LE_13 },
  4090. { "1.3a", LE_13A },
  4091. { "1.3b", LE_13B },
  4092. { "1.3c", LE_13C },
  4093. { "1.3d", LE_13D },
  4094. { NULL, LE_OTHER }
  4095. };
  4096. /** Return the le_version_t for the current version of libevent. If the
  4097. * version is very new, return LE_OTHER. If the version is so old that it
  4098. * doesn't support event_get_version(), return LE_OLD. */
  4099. static le_version_t
  4100. decode_libevent_version(void)
  4101. {
  4102. const char *v = event_get_version();
  4103. int i;
  4104. for (i=0; le_version_table[i].name; ++i) {
  4105. if (!strcmp(le_version_table[i].name, v)) {
  4106. return le_version_table[i].version;
  4107. }
  4108. }
  4109. return LE_OTHER;
  4110. }
  4111. /**
  4112. * Compare the given libevent method and version to a list of versions
  4113. * which are known not to work. Warn the user as appropriate.
  4114. */
  4115. static void
  4116. check_libevent_version(const char *m, int server)
  4117. {
  4118. int buggy = 0, iffy = 0, slow = 0, thread_unsafe = 0;
  4119. le_version_t version;
  4120. const char *v = event_get_version();
  4121. const char *badness = NULL;
  4122. const char *sad_os = "";
  4123. version = decode_libevent_version();
  4124. /* XXX Would it be worthwhile disabling the methods that we know
  4125. * are buggy, rather than just warning about them and then proceeding
  4126. * to use them? If so, we should probably not wrap this whole thing
  4127. * in HAVE_EVENT_GET_VERSION and HAVE_EVENT_GET_METHOD. -RD */
  4128. /* XXXX The problem is that it's not trivial to get libevent to change it's
  4129. * method once it's initialized, and it's not trivial to tell what method it
  4130. * will use without initializing it. I guess we could preemptively disable
  4131. * buggy libevent modes based on the version _before_ initializing it,
  4132. * though, but then there's no good way (afaict) to warn "I would have used
  4133. * kqueue, but instead I'm using select." -NM */
  4134. if (!strcmp(m, "kqueue")) {
  4135. if (version < LE_11B)
  4136. buggy = 1;
  4137. } else if (!strcmp(m, "epoll")) {
  4138. if (version < LE_11)
  4139. iffy = 1;
  4140. } else if (!strcmp(m, "poll")) {
  4141. if (version < LE_10E)
  4142. buggy = 1;
  4143. else if (version < LE_11)
  4144. slow = 1;
  4145. } else if (!strcmp(m, "select")) {
  4146. if (version < LE_11)
  4147. slow = 1;
  4148. } else if (!strcmp(m, "win32")) {
  4149. if (version < LE_11B)
  4150. buggy = 1;
  4151. }
  4152. /* Libevent versions before 1.3b do very badly on operating systems with
  4153. * user-space threading implementations. */
  4154. #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
  4155. if (server && version < LE_13B) {
  4156. thread_unsafe = 1;
  4157. sad_os = "BSD variants";
  4158. }
  4159. #elif defined(__APPLE__) || defined(__darwin__)
  4160. if (server && version < LE_13B) {
  4161. thread_unsafe = 1;
  4162. sad_os = "Mac OS X";
  4163. }
  4164. #endif
  4165. if (thread_unsafe) {
  4166. log(LOG_WARN, LD_GENERAL,
  4167. "Libevent version %s often crashes when running a Tor server with %s. "
  4168. "Please use the latest version of libevent (1.3b or later)",v,sad_os);
  4169. badness = "BROKEN";
  4170. } else if (buggy) {
  4171. log(LOG_WARN, LD_GENERAL,
  4172. "There are serious bugs in using %s with libevent %s. "
  4173. "Please use the latest version of libevent.", m, v);
  4174. badness = "BROKEN";
  4175. } else if (iffy) {
  4176. log(LOG_WARN, LD_GENERAL,
  4177. "There are minor bugs in using %s with libevent %s. "
  4178. "You may want to use the latest version of libevent.", m, v);
  4179. badness = "BUGGY";
  4180. } else if (slow && server) {
  4181. log(LOG_WARN, LD_GENERAL,
  4182. "libevent %s can be very slow with %s. "
  4183. "When running a server, please use the latest version of libevent.",
  4184. v,m);
  4185. badness = "SLOW";
  4186. }
  4187. if (badness) {
  4188. control_event_general_status(LOG_WARN,
  4189. "BAD_LIBEVENT VERSION=%s METHOD=%s BADNESS=%s RECOVERED=NO",
  4190. v, m, badness);
  4191. }
  4192. }
  4193. #else
  4194. static le_version_t
  4195. decode_libevent_version(void)
  4196. {
  4197. return LE_OLD;
  4198. }
  4199. #endif
  4200. /** Return the persistent state struct for this Tor. */
  4201. or_state_t *
  4202. get_or_state(void)
  4203. {
  4204. tor_assert(global_state);
  4205. return global_state;
  4206. }
  4207. /** Return a newly allocated string holding a filename relative to the data
  4208. * directory. If <b>sub1</b> is present, it is the first path component after
  4209. * the data directory. If <b>sub2</b> is also present, it is the second path
  4210. * component after the data directory. If <b>suffix</b> is present, it
  4211. * is appended to the filename.
  4212. *
  4213. * Examples:
  4214. * get_datadir_fname2_suffix("a", NULL, NULL) -> $DATADIR/a
  4215. * get_datadir_fname2_suffix("a", NULL, ".tmp") -> $DATADIR/a.tmp
  4216. * get_datadir_fname2_suffix("a", "b", ".tmp") -> $DATADIR/a/b/.tmp
  4217. * get_datadir_fname2_suffix("a", "b", NULL) -> $DATADIR/a/b
  4218. *
  4219. * Note: Consider using the get_datadir_fname* macros in or.h.
  4220. */
  4221. char *
  4222. get_datadir_fname2_suffix(const char *sub1, const char *sub2,
  4223. const char *suffix)
  4224. {
  4225. or_options_t *options = get_options();
  4226. char *fname = NULL;
  4227. size_t len;
  4228. tor_assert(options);
  4229. tor_assert(options->DataDirectory);
  4230. tor_assert(sub1 || !sub2); /* If sub2 is present, sub1 must be present. */
  4231. len = strlen(options->DataDirectory);
  4232. if (sub1) {
  4233. len += strlen(sub1)+1;
  4234. if (sub2)
  4235. len += strlen(sub2)+1;
  4236. }
  4237. if (suffix)
  4238. len += strlen(suffix);
  4239. len++;
  4240. fname = tor_malloc(len);
  4241. if (sub1) {
  4242. if (sub2) {
  4243. tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s"PATH_SEPARATOR"%s",
  4244. options->DataDirectory, sub1, sub2);
  4245. } else {
  4246. tor_snprintf(fname, len, "%s"PATH_SEPARATOR"%s",
  4247. options->DataDirectory, sub1);
  4248. }
  4249. } else {
  4250. strlcpy(fname, options->DataDirectory, len);
  4251. }
  4252. if (suffix)
  4253. strlcat(fname, suffix, len);
  4254. return fname;
  4255. }
  4256. /** Return 0 if every setting in <b>state</b> is reasonable, and a
  4257. * permissible transition from <b>old_state</b>. Else warn and return -1.
  4258. * Should have no side effects, except for normalizing the contents of
  4259. * <b>state</b>.
  4260. */
  4261. /* XXX from_setconf is here because of bug 238 */
  4262. static int
  4263. or_state_validate(or_state_t *old_state, or_state_t *state,
  4264. int from_setconf, char **msg)
  4265. {
  4266. /* We don't use these; only options do. Still, we need to match that
  4267. * signature. */
  4268. (void) from_setconf;
  4269. (void) old_state;
  4270. if (entry_guards_parse_state(state, 0, msg)<0)
  4271. return -1;
  4272. return 0;
  4273. }
  4274. /** Replace the current persistent state with <b>new_state</b> */
  4275. static void
  4276. or_state_set(or_state_t *new_state)
  4277. {
  4278. char *err = NULL;
  4279. tor_assert(new_state);
  4280. if (global_state)
  4281. config_free(&state_format, global_state);
  4282. global_state = new_state;
  4283. if (entry_guards_parse_state(global_state, 1, &err)<0) {
  4284. log_warn(LD_GENERAL,"%s",err);
  4285. tor_free(err);
  4286. }
  4287. if (rep_hist_load_state(global_state, &err)<0) {
  4288. log_warn(LD_GENERAL,"Unparseable bandwidth history state: %s",err);
  4289. tor_free(err);
  4290. }
  4291. }
  4292. /** Reload the persistent state from disk, generating a new state as needed.
  4293. * Return 0 on success, less than 0 on failure.
  4294. */
  4295. static int
  4296. or_state_load(void)
  4297. {
  4298. or_state_t *new_state = NULL;
  4299. char *contents = NULL, *fname;
  4300. char *errmsg = NULL;
  4301. int r = -1, badstate = 0;
  4302. fname = get_datadir_fname("state");
  4303. switch (file_status(fname)) {
  4304. case FN_FILE:
  4305. if (!(contents = read_file_to_str(fname, 0, NULL))) {
  4306. log_warn(LD_FS, "Unable to read state file \"%s\"", fname);
  4307. goto done;
  4308. }
  4309. break;
  4310. case FN_NOENT:
  4311. break;
  4312. case FN_ERROR:
  4313. case FN_DIR:
  4314. default:
  4315. log_warn(LD_GENERAL,"State file \"%s\" is not a file? Failing.", fname);
  4316. goto done;
  4317. }
  4318. new_state = tor_malloc_zero(sizeof(or_state_t));
  4319. new_state->_magic = OR_STATE_MAGIC;
  4320. config_init(&state_format, new_state);
  4321. if (contents) {
  4322. config_line_t *lines=NULL;
  4323. int assign_retval;
  4324. if (config_get_lines(contents, &lines)<0)
  4325. goto done;
  4326. assign_retval = config_assign(&state_format, new_state,
  4327. lines, 0, 0, &errmsg);
  4328. config_free_lines(lines);
  4329. if (assign_retval<0)
  4330. badstate = 1;
  4331. if (errmsg) {
  4332. log_warn(LD_GENERAL, "%s", errmsg);
  4333. tor_free(errmsg);
  4334. }
  4335. }
  4336. if (!badstate && or_state_validate(NULL, new_state, 1, &errmsg) < 0)
  4337. badstate = 1;
  4338. if (errmsg) {
  4339. log_warn(LD_GENERAL, "%s", errmsg);
  4340. tor_free(errmsg);
  4341. }
  4342. if (badstate && !contents) {
  4343. log_warn(LD_BUG, "Uh oh. We couldn't even validate our own default state."
  4344. " This is a bug in Tor.");
  4345. goto done;
  4346. } else if (badstate && contents) {
  4347. int i;
  4348. file_status_t status;
  4349. size_t len = strlen(fname)+16;
  4350. char *fname2 = tor_malloc(len);
  4351. for (i = 0; i < 100; ++i) {
  4352. tor_snprintf(fname2, len, "%s.%d", fname, i);
  4353. status = file_status(fname2);
  4354. if (status == FN_NOENT)
  4355. break;
  4356. }
  4357. if (i == 100) {
  4358. log_warn(LD_BUG, "Unable to parse state in \"%s\"; too many saved bad "
  4359. "state files to move aside. Discarding the old state file.",
  4360. fname);
  4361. unlink(fname);
  4362. } else {
  4363. log_warn(LD_BUG, "Unable to parse state in \"%s\". Moving it aside "
  4364. "to \"%s\". This could be a bug in Tor; please tell "
  4365. "the developers.", fname, fname2);
  4366. if (rename(fname, fname2) < 0) {
  4367. log_warn(LD_BUG, "Weirdly, I couldn't even move the state aside. The "
  4368. "OS gave an error of %s", strerror(errno));
  4369. }
  4370. }
  4371. tor_free(fname2);
  4372. tor_free(contents);
  4373. config_free(&state_format, new_state);
  4374. new_state = tor_malloc_zero(sizeof(or_state_t));
  4375. new_state->_magic = OR_STATE_MAGIC;
  4376. config_init(&state_format, new_state);
  4377. } else if (contents) {
  4378. log_info(LD_GENERAL, "Loaded state from \"%s\"", fname);
  4379. } else {
  4380. log_info(LD_GENERAL, "Initialized state");
  4381. }
  4382. or_state_set(new_state);
  4383. new_state = NULL;
  4384. if (!contents) {
  4385. global_state->next_write = 0;
  4386. or_state_save(time(NULL));
  4387. }
  4388. r = 0;
  4389. done:
  4390. tor_free(fname);
  4391. tor_free(contents);
  4392. if (new_state)
  4393. config_free(&state_format, new_state);
  4394. return r;
  4395. }
  4396. /** Write the persistent state to disk. Return 0 for success, <0 on failure. */
  4397. int
  4398. or_state_save(time_t now)
  4399. {
  4400. char *state, *contents;
  4401. char tbuf[ISO_TIME_LEN+1];
  4402. size_t len;
  4403. char *fname;
  4404. tor_assert(global_state);
  4405. if (global_state->next_write > now)
  4406. return 0;
  4407. /* Call everything else that might dirty the state even more, in order
  4408. * to avoid redundant writes. */
  4409. entry_guards_update_state(global_state);
  4410. rep_hist_update_state(global_state);
  4411. if (accounting_is_enabled(get_options()))
  4412. accounting_run_housekeeping(now);
  4413. global_state->LastWritten = time(NULL);
  4414. tor_free(global_state->TorVersion);
  4415. len = strlen(get_version())+8;
  4416. global_state->TorVersion = tor_malloc(len);
  4417. tor_snprintf(global_state->TorVersion, len, "Tor %s", get_version());
  4418. state = config_dump(&state_format, global_state, 1, 0);
  4419. len = strlen(state)+256;
  4420. contents = tor_malloc(len);
  4421. format_local_iso_time(tbuf, time(NULL));
  4422. tor_snprintf(contents, len,
  4423. "# Tor state file last generated on %s local time\n"
  4424. "# Other times below are in GMT\n"
  4425. "# You *do not* need to edit this file.\n\n%s",
  4426. tbuf, state);
  4427. tor_free(state);
  4428. fname = get_datadir_fname("state");
  4429. if (write_str_to_file(fname, contents, 0)<0) {
  4430. log_warn(LD_FS, "Unable to write state to file \"%s\"", fname);
  4431. tor_free(fname);
  4432. tor_free(contents);
  4433. return -1;
  4434. }
  4435. log_info(LD_GENERAL, "Saved state to \"%s\"", fname);
  4436. tor_free(fname);
  4437. tor_free(contents);
  4438. global_state->next_write = TIME_MAX;
  4439. return 0;
  4440. }
  4441. /** Given a file name check to see whether the file exists but has not been
  4442. * modified for a very long time. If so, remove it. */
  4443. void
  4444. remove_file_if_very_old(const char *fname, time_t now)
  4445. {
  4446. #define VERY_OLD_FILE_AGE (28*24*60*60)
  4447. struct stat st;
  4448. if (stat(fname, &st)==0 && st.st_mtime < now-VERY_OLD_FILE_AGE) {
  4449. char buf[ISO_TIME_LEN+1];
  4450. format_local_iso_time(buf, st.st_mtime);
  4451. log_notice(LD_GENERAL, "Obsolete file %s hasn't been modified since %s. "
  4452. "Removing it.", fname, buf);
  4453. unlink(fname);
  4454. }
  4455. }
  4456. /** Helper to implement GETINFO functions about configuration variables (not
  4457. * their values). Given a "config/names" question, set *<b>answer</b> to a
  4458. * new string describing the supported configuration variables and their
  4459. * types. */
  4460. int
  4461. getinfo_helper_config(control_connection_t *conn,
  4462. const char *question, char **answer)
  4463. {
  4464. (void) conn;
  4465. if (!strcmp(question, "config/names")) {
  4466. smartlist_t *sl = smartlist_create();
  4467. int i;
  4468. for (i = 0; _option_vars[i].name; ++i) {
  4469. config_var_t *var = &_option_vars[i];
  4470. const char *type, *desc;
  4471. char *line;
  4472. size_t len;
  4473. desc = config_find_description(&options_format, var->name);
  4474. switch (var->type) {
  4475. case CONFIG_TYPE_STRING: type = "String"; break;
  4476. case CONFIG_TYPE_UINT: type = "Integer"; break;
  4477. case CONFIG_TYPE_INTERVAL: type = "TimeInterval"; break;
  4478. case CONFIG_TYPE_MEMUNIT: type = "DataSize"; break;
  4479. case CONFIG_TYPE_DOUBLE: type = "Float"; break;
  4480. case CONFIG_TYPE_BOOL: type = "Boolean"; break;
  4481. case CONFIG_TYPE_ISOTIME: type = "Time"; break;
  4482. case CONFIG_TYPE_CSV: type = "CommaList"; break;
  4483. case CONFIG_TYPE_LINELIST: type = "LineList"; break;
  4484. case CONFIG_TYPE_LINELIST_S: type = "Dependant"; break;
  4485. case CONFIG_TYPE_LINELIST_V: type = "Virtual"; break;
  4486. default:
  4487. case CONFIG_TYPE_OBSOLETE:
  4488. type = NULL; break;
  4489. }
  4490. if (!type)
  4491. continue;
  4492. len = strlen(var->name)+strlen(type)+16;
  4493. if (desc)
  4494. len += strlen(desc);
  4495. line = tor_malloc(len);
  4496. if (desc)
  4497. tor_snprintf(line, len, "%s %s %s\n",var->name,type,desc);
  4498. else
  4499. tor_snprintf(line, len, "%s %s\n",var->name,type);
  4500. smartlist_add(sl, line);
  4501. }
  4502. *answer = smartlist_join_strings(sl, "", 0, NULL);
  4503. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  4504. smartlist_free(sl);
  4505. }
  4506. return 0;
  4507. }
  4508. #include "aes.h"
  4509. #include "ht.h"
  4510. #include "test.h"
  4511. extern const char aes_c_id[];
  4512. extern const char compat_c_id[];
  4513. extern const char container_c_id[];
  4514. extern const char crypto_c_id[];
  4515. extern const char log_c_id[];
  4516. extern const char torgzip_c_id[];
  4517. extern const char tortls_c_id[];
  4518. extern const char util_c_id[];
  4519. extern const char buffers_c_id[];
  4520. extern const char circuitbuild_c_id[];
  4521. extern const char circuitlist_c_id[];
  4522. extern const char circuituse_c_id[];
  4523. extern const char command_c_id[];
  4524. // extern const char config_c_id[];
  4525. extern const char connection_c_id[];
  4526. extern const char connection_edge_c_id[];
  4527. extern const char connection_or_c_id[];
  4528. extern const char control_c_id[];
  4529. extern const char cpuworker_c_id[];
  4530. extern const char directory_c_id[];
  4531. extern const char dirserv_c_id[];
  4532. extern const char dns_c_id[];
  4533. extern const char hibernate_c_id[];
  4534. extern const char main_c_id[];
  4535. #ifdef NT_SERVICE
  4536. extern const char ntmain_c_id[];
  4537. #endif
  4538. extern const char onion_c_id[];
  4539. extern const char policies_c_id[];
  4540. extern const char relay_c_id[];
  4541. extern const char rendclient_c_id[];
  4542. extern const char rendcommon_c_id[];
  4543. extern const char rendmid_c_id[];
  4544. extern const char rendservice_c_id[];
  4545. extern const char rephist_c_id[];
  4546. extern const char router_c_id[];
  4547. extern const char routerlist_c_id[];
  4548. extern const char routerparse_c_id[];
  4549. /** Dump the version of every file to the log. */
  4550. static void
  4551. print_svn_version(void)
  4552. {
  4553. puts(AES_H_ID);
  4554. puts(COMPAT_H_ID);
  4555. puts(CONTAINER_H_ID);
  4556. puts(CRYPTO_H_ID);
  4557. puts(HT_H_ID);
  4558. puts(TEST_H_ID);
  4559. puts(LOG_H_ID);
  4560. puts(TORGZIP_H_ID);
  4561. puts(TORINT_H_ID);
  4562. puts(TORTLS_H_ID);
  4563. puts(UTIL_H_ID);
  4564. puts(aes_c_id);
  4565. puts(compat_c_id);
  4566. puts(container_c_id);
  4567. puts(crypto_c_id);
  4568. puts(log_c_id);
  4569. puts(torgzip_c_id);
  4570. puts(tortls_c_id);
  4571. puts(util_c_id);
  4572. puts(OR_H_ID);
  4573. puts(buffers_c_id);
  4574. puts(circuitbuild_c_id);
  4575. puts(circuitlist_c_id);
  4576. puts(circuituse_c_id);
  4577. puts(command_c_id);
  4578. puts(config_c_id);
  4579. puts(connection_c_id);
  4580. puts(connection_edge_c_id);
  4581. puts(connection_or_c_id);
  4582. puts(control_c_id);
  4583. puts(cpuworker_c_id);
  4584. puts(directory_c_id);
  4585. puts(dirserv_c_id);
  4586. puts(dns_c_id);
  4587. puts(hibernate_c_id);
  4588. puts(main_c_id);
  4589. #ifdef NT_SERVICE
  4590. puts(ntmain_c_id);
  4591. #endif
  4592. puts(onion_c_id);
  4593. puts(policies_c_id);
  4594. puts(relay_c_id);
  4595. puts(rendclient_c_id);
  4596. puts(rendcommon_c_id);
  4597. puts(rendmid_c_id);
  4598. puts(rendservice_c_id);
  4599. puts(rephist_c_id);
  4600. puts(router_c_id);
  4601. puts(routerlist_c_id);
  4602. puts(routerparse_c_id);
  4603. }