config.c 164 KB

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