config.c 163 KB

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