config.c 179 KB

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