config.c 159 KB

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