config.c 166 KB

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