config.c 180 KB

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