config.c 182 KB

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