config.c 157 KB

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