config.c 141 KB

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