config.c 185 KB

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