config.c 152 KB

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