config.c 146 KB

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