config.c 181 KB

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