config.c 179 KB

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