config.c 155 KB

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