config.c 171 KB

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