config.c 168 KB

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