config.c 184 KB

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