config.c 193 KB

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