config.c 181 KB

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