control.c 181 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2015, The Tor Project, Inc. */
  3. /* See LICENSE for licensing information */
  4. /**
  5. * \file control.c
  6. * \brief Implementation for Tor's control-socket interface.
  7. * See doc/spec/control-spec.txt for full details on protocol.
  8. **/
  9. #define CONTROL_PRIVATE
  10. #include "or.h"
  11. #include "addressmap.h"
  12. #include "buffers.h"
  13. #include "channel.h"
  14. #include "channeltls.h"
  15. #include "circuitbuild.h"
  16. #include "circuitlist.h"
  17. #include "circuitstats.h"
  18. #include "circuituse.h"
  19. #include "command.h"
  20. #include "config.h"
  21. #include "confparse.h"
  22. #include "connection.h"
  23. #include "connection_edge.h"
  24. #include "connection_or.h"
  25. #include "control.h"
  26. #include "directory.h"
  27. #include "dirserv.h"
  28. #include "dnsserv.h"
  29. #include "entrynodes.h"
  30. #include "geoip.h"
  31. #include "hibernate.h"
  32. #include "main.h"
  33. #include "networkstatus.h"
  34. #include "nodelist.h"
  35. #include "policies.h"
  36. #include "reasons.h"
  37. #include "rephist.h"
  38. #include "router.h"
  39. #include "routerlist.h"
  40. #include "routerparse.h"
  41. #ifndef _WIN32
  42. #include <pwd.h>
  43. #include <sys/resource.h>
  44. #endif
  45. #include "crypto_s2k.h"
  46. #include "procmon.h"
  47. /** Yield true iff <b>s</b> is the state of a control_connection_t that has
  48. * finished authentication and is accepting commands. */
  49. #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
  50. /** Bitfield: The bit 1&lt;&lt;e is set if <b>any</b> open control
  51. * connection is interested in events of type <b>e</b>. We use this
  52. * so that we can decide to skip generating event messages that nobody
  53. * has interest in without having to walk over the global connection
  54. * list to find out.
  55. **/
  56. typedef uint64_t event_mask_t;
  57. /** An event mask of all the events that any controller is interested in
  58. * receiving. */
  59. static event_mask_t global_event_mask = 0;
  60. /** True iff we have disabled log messages from being sent to the controller */
  61. static int disable_log_messages = 0;
  62. /** Macro: true if any control connection is interested in events of type
  63. * <b>e</b>. */
  64. #define EVENT_IS_INTERESTING(e) \
  65. (!! (global_event_mask & EVENT_MASK_(e)))
  66. /** If we're using cookie-type authentication, how long should our cookies be?
  67. */
  68. #define AUTHENTICATION_COOKIE_LEN 32
  69. /** If true, we've set authentication_cookie to a secret code and
  70. * stored it to disk. */
  71. static int authentication_cookie_is_set = 0;
  72. /** If authentication_cookie_is_set, a secret cookie that we've stored to disk
  73. * and which we're using to authenticate controllers. (If the controller can
  74. * read it off disk, it has permission to connect.) */
  75. static uint8_t *authentication_cookie = NULL;
  76. #define SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT \
  77. "Tor safe cookie authentication server-to-controller hash"
  78. #define SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT \
  79. "Tor safe cookie authentication controller-to-server hash"
  80. #define SAFECOOKIE_SERVER_NONCE_LEN DIGEST256_LEN
  81. /** A sufficiently large size to record the last bootstrap phase string. */
  82. #define BOOTSTRAP_MSG_LEN 1024
  83. /** What was the last bootstrap phase message we sent? We keep track
  84. * of this so we can respond to getinfo status/bootstrap-phase queries. */
  85. static char last_sent_bootstrap_message[BOOTSTRAP_MSG_LEN];
  86. static void connection_printf_to_buf(control_connection_t *conn,
  87. const char *format, ...)
  88. CHECK_PRINTF(2,3);
  89. static void send_control_event_impl(uint16_t event, event_format_t which,
  90. const char *format, va_list ap)
  91. CHECK_PRINTF(3,0);
  92. static int control_event_status(int type, int severity, const char *format,
  93. va_list args)
  94. CHECK_PRINTF(3,0);
  95. static void send_control_done(control_connection_t *conn);
  96. static void send_control_event(uint16_t event, event_format_t which,
  97. const char *format, ...)
  98. CHECK_PRINTF(3,4);
  99. static int handle_control_setconf(control_connection_t *conn, uint32_t len,
  100. char *body);
  101. static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
  102. char *body);
  103. static int handle_control_getconf(control_connection_t *conn, uint32_t len,
  104. const char *body);
  105. static int handle_control_loadconf(control_connection_t *conn, uint32_t len,
  106. const char *body);
  107. static int handle_control_setevents(control_connection_t *conn, uint32_t len,
  108. const char *body);
  109. static int handle_control_authenticate(control_connection_t *conn,
  110. uint32_t len,
  111. const char *body);
  112. static int handle_control_signal(control_connection_t *conn, uint32_t len,
  113. const char *body);
  114. static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  115. const char *body);
  116. static char *list_getinfo_options(void);
  117. static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
  118. const char *body);
  119. static int handle_control_extendcircuit(control_connection_t *conn,
  120. uint32_t len,
  121. const char *body);
  122. static int handle_control_setcircuitpurpose(control_connection_t *conn,
  123. uint32_t len, const char *body);
  124. static int handle_control_attachstream(control_connection_t *conn,
  125. uint32_t len,
  126. const char *body);
  127. static int handle_control_postdescriptor(control_connection_t *conn,
  128. uint32_t len,
  129. const char *body);
  130. static int handle_control_redirectstream(control_connection_t *conn,
  131. uint32_t len,
  132. const char *body);
  133. static int handle_control_closestream(control_connection_t *conn, uint32_t len,
  134. const char *body);
  135. static int handle_control_closecircuit(control_connection_t *conn,
  136. uint32_t len,
  137. const char *body);
  138. static int handle_control_resolve(control_connection_t *conn, uint32_t len,
  139. const char *body);
  140. static int handle_control_usefeature(control_connection_t *conn,
  141. uint32_t len,
  142. const char *body);
  143. static int handle_control_hsfetch(control_connection_t *conn, uint32_t len,
  144. const char *body);
  145. static int write_stream_target_to_buf(entry_connection_t *conn, char *buf,
  146. size_t len);
  147. static void orconn_target_get_name(char *buf, size_t len,
  148. or_connection_t *conn);
  149. /** Given a control event code for a message event, return the corresponding
  150. * log severity. */
  151. static INLINE int
  152. event_to_log_severity(int event)
  153. {
  154. switch (event) {
  155. case EVENT_DEBUG_MSG: return LOG_DEBUG;
  156. case EVENT_INFO_MSG: return LOG_INFO;
  157. case EVENT_NOTICE_MSG: return LOG_NOTICE;
  158. case EVENT_WARN_MSG: return LOG_WARN;
  159. case EVENT_ERR_MSG: return LOG_ERR;
  160. default: return -1;
  161. }
  162. }
  163. /** Given a log severity, return the corresponding control event code. */
  164. static INLINE int
  165. log_severity_to_event(int severity)
  166. {
  167. switch (severity) {
  168. case LOG_DEBUG: return EVENT_DEBUG_MSG;
  169. case LOG_INFO: return EVENT_INFO_MSG;
  170. case LOG_NOTICE: return EVENT_NOTICE_MSG;
  171. case LOG_WARN: return EVENT_WARN_MSG;
  172. case LOG_ERR: return EVENT_ERR_MSG;
  173. default: return -1;
  174. }
  175. }
  176. /** Helper: clear bandwidth counters of all origin circuits. */
  177. static void
  178. clear_circ_bw_fields(void)
  179. {
  180. origin_circuit_t *ocirc;
  181. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  182. if (!CIRCUIT_IS_ORIGIN(circ))
  183. continue;
  184. ocirc = TO_ORIGIN_CIRCUIT(circ);
  185. ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
  186. }
  187. SMARTLIST_FOREACH_END(circ);
  188. }
  189. /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
  190. * connection's event_mask field. */
  191. void
  192. control_update_global_event_mask(void)
  193. {
  194. smartlist_t *conns = get_connection_array();
  195. event_mask_t old_mask, new_mask;
  196. old_mask = global_event_mask;
  197. global_event_mask = 0;
  198. SMARTLIST_FOREACH(conns, connection_t *, _conn,
  199. {
  200. if (_conn->type == CONN_TYPE_CONTROL &&
  201. STATE_IS_OPEN(_conn->state)) {
  202. control_connection_t *conn = TO_CONTROL_CONN(_conn);
  203. global_event_mask |= conn->event_mask;
  204. }
  205. });
  206. new_mask = global_event_mask;
  207. /* Handle the aftermath. Set up the log callback to tell us only what
  208. * we want to hear...*/
  209. control_adjust_event_log_severity();
  210. /* ...then, if we've started logging stream or circ bw, clear the
  211. * appropriate fields. */
  212. if (! (old_mask & EVENT_STREAM_BANDWIDTH_USED) &&
  213. (new_mask & EVENT_STREAM_BANDWIDTH_USED)) {
  214. SMARTLIST_FOREACH(conns, connection_t *, conn,
  215. {
  216. if (conn->type == CONN_TYPE_AP) {
  217. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  218. edge_conn->n_written = edge_conn->n_read = 0;
  219. }
  220. });
  221. }
  222. if (! (old_mask & EVENT_CIRC_BANDWIDTH_USED) &&
  223. (new_mask & EVENT_CIRC_BANDWIDTH_USED)) {
  224. clear_circ_bw_fields();
  225. }
  226. }
  227. /** Adjust the log severities that result in control_event_logmsg being called
  228. * to match the severity of log messages that any controllers are interested
  229. * in. */
  230. void
  231. control_adjust_event_log_severity(void)
  232. {
  233. int i;
  234. int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
  235. for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
  236. if (EVENT_IS_INTERESTING(i)) {
  237. min_log_event = i;
  238. break;
  239. }
  240. }
  241. for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
  242. if (EVENT_IS_INTERESTING(i)) {
  243. max_log_event = i;
  244. break;
  245. }
  246. }
  247. if (EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
  248. if (min_log_event > EVENT_NOTICE_MSG)
  249. min_log_event = EVENT_NOTICE_MSG;
  250. if (max_log_event < EVENT_ERR_MSG)
  251. max_log_event = EVENT_ERR_MSG;
  252. }
  253. if (min_log_event <= max_log_event)
  254. change_callback_log_severity(event_to_log_severity(min_log_event),
  255. event_to_log_severity(max_log_event),
  256. control_event_logmsg);
  257. else
  258. change_callback_log_severity(LOG_ERR, LOG_ERR,
  259. control_event_logmsg);
  260. }
  261. /** Return true iff the event with code <b>c</b> is being sent to any current
  262. * control connection. This is useful if the amount of work needed to prepare
  263. * to call the appropriate control_event_...() function is high.
  264. */
  265. int
  266. control_event_is_interesting(int event)
  267. {
  268. return EVENT_IS_INTERESTING(event);
  269. }
  270. /** Append a NUL-terminated string <b>s</b> to the end of
  271. * <b>conn</b>-\>outbuf.
  272. */
  273. static INLINE void
  274. connection_write_str_to_buf(const char *s, control_connection_t *conn)
  275. {
  276. size_t len = strlen(s);
  277. connection_write_to_buf(s, len, TO_CONN(conn));
  278. }
  279. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  280. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy the
  281. * contents of <b>data</b> into *<b>out</b>, adding a period before any period
  282. * that appears at the start of a line, and adding a period-CRLF line at
  283. * the end. Replace all LF characters sequences with CRLF. Return the number
  284. * of bytes in *<b>out</b>.
  285. */
  286. STATIC size_t
  287. write_escaped_data(const char *data, size_t len, char **out)
  288. {
  289. size_t sz_out = len+8;
  290. char *outp;
  291. const char *start = data, *end;
  292. int i;
  293. int start_of_line;
  294. for (i=0; i<(int)len; ++i) {
  295. if (data[i]== '\n')
  296. sz_out += 2; /* Maybe add a CR; maybe add a dot. */
  297. }
  298. *out = outp = tor_malloc(sz_out+1);
  299. end = data+len;
  300. start_of_line = 1;
  301. while (data < end) {
  302. if (*data == '\n') {
  303. if (data > start && data[-1] != '\r')
  304. *outp++ = '\r';
  305. start_of_line = 1;
  306. } else if (*data == '.') {
  307. if (start_of_line) {
  308. start_of_line = 0;
  309. *outp++ = '.';
  310. }
  311. } else {
  312. start_of_line = 0;
  313. }
  314. *outp++ = *data++;
  315. }
  316. if (outp < *out+2 || fast_memcmp(outp-2, "\r\n", 2)) {
  317. *outp++ = '\r';
  318. *outp++ = '\n';
  319. }
  320. *outp++ = '.';
  321. *outp++ = '\r';
  322. *outp++ = '\n';
  323. *outp = '\0'; /* NUL-terminate just in case. */
  324. tor_assert((outp - *out) <= (int)sz_out);
  325. return outp - *out;
  326. }
  327. /** Given a <b>len</b>-character string in <b>data</b>, made of lines
  328. * terminated by CRLF, allocate a new string in *<b>out</b>, and copy
  329. * the contents of <b>data</b> into *<b>out</b>, removing any period
  330. * that appears at the start of a line, and replacing all CRLF sequences
  331. * with LF. Return the number of
  332. * bytes in *<b>out</b>. */
  333. STATIC size_t
  334. read_escaped_data(const char *data, size_t len, char **out)
  335. {
  336. char *outp;
  337. const char *next;
  338. const char *end;
  339. *out = outp = tor_malloc(len+1);
  340. end = data+len;
  341. while (data < end) {
  342. /* we're at the start of a line. */
  343. if (*data == '.')
  344. ++data;
  345. next = memchr(data, '\n', end-data);
  346. if (next) {
  347. size_t n_to_copy = next-data;
  348. /* Don't copy a CR that precedes this LF. */
  349. if (n_to_copy && *(next-1) == '\r')
  350. --n_to_copy;
  351. memcpy(outp, data, n_to_copy);
  352. outp += n_to_copy;
  353. data = next+1; /* This will point at the start of the next line,
  354. * or the end of the string, or a period. */
  355. } else {
  356. memcpy(outp, data, end-data);
  357. outp += (end-data);
  358. *outp = '\0';
  359. return outp - *out;
  360. }
  361. *outp++ = '\n';
  362. }
  363. *outp = '\0';
  364. return outp - *out;
  365. }
  366. /** If the first <b>in_len_max</b> characters in <b>start</b> contain a
  367. * double-quoted string with escaped characters, return the length of that
  368. * string (as encoded, including quotes). Otherwise return -1. */
  369. static INLINE int
  370. get_escaped_string_length(const char *start, size_t in_len_max,
  371. int *chars_out)
  372. {
  373. const char *cp, *end;
  374. int chars = 0;
  375. if (*start != '\"')
  376. return -1;
  377. cp = start+1;
  378. end = start+in_len_max;
  379. /* Calculate length. */
  380. while (1) {
  381. if (cp >= end) {
  382. return -1; /* Too long. */
  383. } else if (*cp == '\\') {
  384. if (++cp == end)
  385. return -1; /* Can't escape EOS. */
  386. ++cp;
  387. ++chars;
  388. } else if (*cp == '\"') {
  389. break;
  390. } else {
  391. ++cp;
  392. ++chars;
  393. }
  394. }
  395. if (chars_out)
  396. *chars_out = chars;
  397. return (int)(cp - start+1);
  398. }
  399. /** As decode_escaped_string, but does not decode the string: copies the
  400. * entire thing, including quotation marks. */
  401. static const char *
  402. extract_escaped_string(const char *start, size_t in_len_max,
  403. char **out, size_t *out_len)
  404. {
  405. int length = get_escaped_string_length(start, in_len_max, NULL);
  406. if (length<0)
  407. return NULL;
  408. *out_len = length;
  409. *out = tor_strndup(start, *out_len);
  410. return start+length;
  411. }
  412. /** Given a pointer to a string starting at <b>start</b> containing
  413. * <b>in_len_max</b> characters, decode a string beginning with one double
  414. * quote, containing any number of non-quote characters or characters escaped
  415. * with a backslash, and ending with a final double quote. Place the resulting
  416. * string (unquoted, unescaped) into a newly allocated string in *<b>out</b>;
  417. * store its length in <b>out_len</b>. On success, return a pointer to the
  418. * character immediately following the escaped string. On failure, return
  419. * NULL. */
  420. static const char *
  421. decode_escaped_string(const char *start, size_t in_len_max,
  422. char **out, size_t *out_len)
  423. {
  424. const char *cp, *end;
  425. char *outp;
  426. int len, n_chars = 0;
  427. len = get_escaped_string_length(start, in_len_max, &n_chars);
  428. if (len<0)
  429. return NULL;
  430. end = start+len-1; /* Index of last quote. */
  431. tor_assert(*end == '\"');
  432. outp = *out = tor_malloc(len+1);
  433. *out_len = n_chars;
  434. cp = start+1;
  435. while (cp < end) {
  436. if (*cp == '\\')
  437. ++cp;
  438. *outp++ = *cp++;
  439. }
  440. *outp = '\0';
  441. tor_assert((outp - *out) == (int)*out_len);
  442. return end+1;
  443. }
  444. /** Acts like sprintf, but writes its formatted string to the end of
  445. * <b>conn</b>-\>outbuf. */
  446. static void
  447. connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
  448. {
  449. va_list ap;
  450. char *buf = NULL;
  451. int len;
  452. va_start(ap,format);
  453. len = tor_vasprintf(&buf, format, ap);
  454. va_end(ap);
  455. if (len < 0) {
  456. log_err(LD_BUG, "Unable to format string for controller.");
  457. tor_assert(0);
  458. }
  459. connection_write_to_buf(buf, (size_t)len, TO_CONN(conn));
  460. tor_free(buf);
  461. }
  462. /** Write all of the open control ports to ControlPortWriteToFile */
  463. void
  464. control_ports_write_to_file(void)
  465. {
  466. smartlist_t *lines;
  467. char *joined = NULL;
  468. const or_options_t *options = get_options();
  469. if (!options->ControlPortWriteToFile)
  470. return;
  471. lines = smartlist_new();
  472. SMARTLIST_FOREACH_BEGIN(get_connection_array(), const connection_t *, conn) {
  473. if (conn->type != CONN_TYPE_CONTROL_LISTENER || conn->marked_for_close)
  474. continue;
  475. #ifdef AF_UNIX
  476. if (conn->socket_family == AF_UNIX) {
  477. smartlist_add_asprintf(lines, "UNIX_PORT=%s\n", conn->address);
  478. continue;
  479. }
  480. #endif
  481. smartlist_add_asprintf(lines, "PORT=%s:%d\n", conn->address, conn->port);
  482. } SMARTLIST_FOREACH_END(conn);
  483. joined = smartlist_join_strings(lines, "", 0, NULL);
  484. if (write_str_to_file(options->ControlPortWriteToFile, joined, 0) < 0) {
  485. log_warn(LD_CONTROL, "Writing %s failed: %s",
  486. options->ControlPortWriteToFile, strerror(errno));
  487. }
  488. #ifndef _WIN32
  489. if (options->ControlPortFileGroupReadable) {
  490. if (chmod(options->ControlPortWriteToFile, 0640)) {
  491. log_warn(LD_FS,"Unable to make %s group-readable.",
  492. options->ControlPortWriteToFile);
  493. }
  494. }
  495. #endif
  496. tor_free(joined);
  497. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  498. smartlist_free(lines);
  499. }
  500. /** Send a "DONE" message down the control connection <b>conn</b>. */
  501. static void
  502. send_control_done(control_connection_t *conn)
  503. {
  504. connection_write_str_to_buf("250 OK\r\n", conn);
  505. }
  506. /** Send an event to all v1 controllers that are listening for code
  507. * <b>event</b>. The event's body is given by <b>msg</b>.
  508. *
  509. * If <b>which</b> & SHORT_NAMES, the event contains short-format names: send
  510. * it to controllers that haven't enabled the VERBOSE_NAMES feature. If
  511. * <b>which</b> & LONG_NAMES, the event contains long-format names: send it
  512. * to controllers that <em>have</em> enabled VERBOSE_NAMES.
  513. *
  514. * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
  515. * respect to the EXTENDED_EVENTS feature. */
  516. MOCK_IMPL(STATIC void,
  517. send_control_event_string,(uint16_t event, event_format_t which,
  518. const char *msg))
  519. {
  520. smartlist_t *conns = get_connection_array();
  521. (void)which;
  522. tor_assert(event >= EVENT_MIN_ && event <= EVENT_MAX_);
  523. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  524. if (conn->type == CONN_TYPE_CONTROL &&
  525. !conn->marked_for_close &&
  526. conn->state == CONTROL_CONN_STATE_OPEN) {
  527. control_connection_t *control_conn = TO_CONTROL_CONN(conn);
  528. if (control_conn->event_mask & (((event_mask_t)1)<<event)) {
  529. int is_err = 0;
  530. connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
  531. if (event == EVENT_ERR_MSG)
  532. is_err = 1;
  533. else if (event == EVENT_STATUS_GENERAL)
  534. is_err = !strcmpstart(msg, "STATUS_GENERAL ERR ");
  535. else if (event == EVENT_STATUS_CLIENT)
  536. is_err = !strcmpstart(msg, "STATUS_CLIENT ERR ");
  537. else if (event == EVENT_STATUS_SERVER)
  538. is_err = !strcmpstart(msg, "STATUS_SERVER ERR ");
  539. if (is_err)
  540. connection_flush(TO_CONN(control_conn));
  541. }
  542. }
  543. } SMARTLIST_FOREACH_END(conn);
  544. }
  545. /** Helper for send_control_event and control_event_status:
  546. * Send an event to all v1 controllers that are listening for code
  547. * <b>event</b>. The event's body is created by the printf-style format in
  548. * <b>format</b>, and other arguments as provided. */
  549. static void
  550. send_control_event_impl(uint16_t event, event_format_t which,
  551. const char *format, va_list ap)
  552. {
  553. char *buf = NULL;
  554. int len;
  555. len = tor_vasprintf(&buf, format, ap);
  556. if (len < 0) {
  557. log_warn(LD_BUG, "Unable to format event for controller.");
  558. return;
  559. }
  560. send_control_event_string(event, which|ALL_FORMATS, buf);
  561. tor_free(buf);
  562. }
  563. /** Send an event to all v1 controllers that are listening for code
  564. * <b>event</b>. The event's body is created by the printf-style format in
  565. * <b>format</b>, and other arguments as provided. */
  566. static void
  567. send_control_event(uint16_t event, event_format_t which,
  568. const char *format, ...)
  569. {
  570. va_list ap;
  571. va_start(ap, format);
  572. send_control_event_impl(event, which, format, ap);
  573. va_end(ap);
  574. }
  575. /** Given a text circuit <b>id</b>, return the corresponding circuit. */
  576. static origin_circuit_t *
  577. get_circ(const char *id)
  578. {
  579. uint32_t n_id;
  580. int ok;
  581. n_id = (uint32_t) tor_parse_ulong(id, 10, 0, UINT32_MAX, &ok, NULL);
  582. if (!ok)
  583. return NULL;
  584. return circuit_get_by_global_id(n_id);
  585. }
  586. /** Given a text stream <b>id</b>, return the corresponding AP connection. */
  587. static entry_connection_t *
  588. get_stream(const char *id)
  589. {
  590. uint64_t n_id;
  591. int ok;
  592. connection_t *conn;
  593. n_id = tor_parse_uint64(id, 10, 0, UINT64_MAX, &ok, NULL);
  594. if (!ok)
  595. return NULL;
  596. conn = connection_get_by_global_id(n_id);
  597. if (!conn || conn->type != CONN_TYPE_AP || conn->marked_for_close)
  598. return NULL;
  599. return TO_ENTRY_CONN(conn);
  600. }
  601. /** Helper for setconf and resetconf. Acts like setconf, except
  602. * it passes <b>use_defaults</b> on to options_trial_assign(). Modifies the
  603. * contents of body.
  604. */
  605. static int
  606. control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
  607. int use_defaults)
  608. {
  609. setopt_err_t opt_err;
  610. config_line_t *lines=NULL;
  611. char *start = body;
  612. char *errstring = NULL;
  613. const int clear_first = 1;
  614. char *config;
  615. smartlist_t *entries = smartlist_new();
  616. /* We have a string, "body", of the format '(key(=val|="val")?)' entries
  617. * separated by space. break it into a list of configuration entries. */
  618. while (*body) {
  619. char *eq = body;
  620. char *key;
  621. char *entry;
  622. while (!TOR_ISSPACE(*eq) && *eq != '=')
  623. ++eq;
  624. key = tor_strndup(body, eq-body);
  625. body = eq+1;
  626. if (*eq == '=') {
  627. char *val=NULL;
  628. size_t val_len=0;
  629. if (*body != '\"') {
  630. char *val_start = body;
  631. while (!TOR_ISSPACE(*body))
  632. body++;
  633. val = tor_strndup(val_start, body-val_start);
  634. val_len = strlen(val);
  635. } else {
  636. body = (char*)extract_escaped_string(body, (len - (body-start)),
  637. &val, &val_len);
  638. if (!body) {
  639. connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
  640. SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  641. smartlist_free(entries);
  642. tor_free(key);
  643. return 0;
  644. }
  645. }
  646. tor_asprintf(&entry, "%s %s", key, val);
  647. tor_free(key);
  648. tor_free(val);
  649. } else {
  650. entry = key;
  651. }
  652. smartlist_add(entries, entry);
  653. while (TOR_ISSPACE(*body))
  654. ++body;
  655. }
  656. smartlist_add(entries, tor_strdup(""));
  657. config = smartlist_join_strings(entries, "\n", 0, NULL);
  658. SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
  659. smartlist_free(entries);
  660. if (config_get_lines(config, &lines, 0) < 0) {
  661. log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
  662. connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
  663. conn);
  664. tor_free(config);
  665. return 0;
  666. }
  667. tor_free(config);
  668. opt_err = options_trial_assign(lines, use_defaults, clear_first, &errstring);
  669. {
  670. const char *msg;
  671. switch (opt_err) {
  672. case SETOPT_ERR_MISC:
  673. msg = "552 Unrecognized option";
  674. break;
  675. case SETOPT_ERR_PARSE:
  676. msg = "513 Unacceptable option value";
  677. break;
  678. case SETOPT_ERR_TRANSITION:
  679. msg = "553 Transition not allowed";
  680. break;
  681. case SETOPT_ERR_SETTING:
  682. default:
  683. msg = "553 Unable to set option";
  684. break;
  685. case SETOPT_OK:
  686. config_free_lines(lines);
  687. send_control_done(conn);
  688. return 0;
  689. }
  690. log_warn(LD_CONTROL,
  691. "Controller gave us config lines that didn't validate: %s",
  692. errstring);
  693. connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
  694. config_free_lines(lines);
  695. tor_free(errstring);
  696. return 0;
  697. }
  698. }
  699. /** Called when we receive a SETCONF message: parse the body and try
  700. * to update our configuration. Reply with a DONE or ERROR message.
  701. * Modifies the contents of body.*/
  702. static int
  703. handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
  704. {
  705. return control_setconf_helper(conn, len, body, 0);
  706. }
  707. /** Called when we receive a RESETCONF message: parse the body and try
  708. * to update our configuration. Reply with a DONE or ERROR message.
  709. * Modifies the contents of body. */
  710. static int
  711. handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
  712. {
  713. return control_setconf_helper(conn, len, body, 1);
  714. }
  715. /** Called when we receive a GETCONF message. Parse the request, and
  716. * reply with a CONFVALUE or an ERROR message */
  717. static int
  718. handle_control_getconf(control_connection_t *conn, uint32_t body_len,
  719. const char *body)
  720. {
  721. smartlist_t *questions = smartlist_new();
  722. smartlist_t *answers = smartlist_new();
  723. smartlist_t *unrecognized = smartlist_new();
  724. char *msg = NULL;
  725. size_t msg_len;
  726. const or_options_t *options = get_options();
  727. int i, len;
  728. (void) body_len; /* body is NUL-terminated; so we can ignore len. */
  729. smartlist_split_string(questions, body, " ",
  730. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  731. SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
  732. if (!option_is_recognized(q)) {
  733. smartlist_add(unrecognized, (char*) q);
  734. } else {
  735. config_line_t *answer = option_get_assignment(options,q);
  736. if (!answer) {
  737. const char *name = option_get_canonical_name(q);
  738. smartlist_add_asprintf(answers, "250-%s\r\n", name);
  739. }
  740. while (answer) {
  741. config_line_t *next;
  742. smartlist_add_asprintf(answers, "250-%s=%s\r\n",
  743. answer->key, answer->value);
  744. next = answer->next;
  745. tor_free(answer->key);
  746. tor_free(answer->value);
  747. tor_free(answer);
  748. answer = next;
  749. }
  750. }
  751. } SMARTLIST_FOREACH_END(q);
  752. if ((len = smartlist_len(unrecognized))) {
  753. for (i=0; i < len-1; ++i)
  754. connection_printf_to_buf(conn,
  755. "552-Unrecognized configuration key \"%s\"\r\n",
  756. (char*)smartlist_get(unrecognized, i));
  757. connection_printf_to_buf(conn,
  758. "552 Unrecognized configuration key \"%s\"\r\n",
  759. (char*)smartlist_get(unrecognized, len-1));
  760. } else if ((len = smartlist_len(answers))) {
  761. char *tmp = smartlist_get(answers, len-1);
  762. tor_assert(strlen(tmp)>4);
  763. tmp[3] = ' ';
  764. msg = smartlist_join_strings(answers, "", 0, &msg_len);
  765. connection_write_to_buf(msg, msg_len, TO_CONN(conn));
  766. } else {
  767. connection_write_str_to_buf("250 OK\r\n", conn);
  768. }
  769. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  770. smartlist_free(answers);
  771. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  772. smartlist_free(questions);
  773. smartlist_free(unrecognized);
  774. tor_free(msg);
  775. return 0;
  776. }
  777. /** Called when we get a +LOADCONF message. */
  778. static int
  779. handle_control_loadconf(control_connection_t *conn, uint32_t len,
  780. const char *body)
  781. {
  782. setopt_err_t retval;
  783. char *errstring = NULL;
  784. const char *msg = NULL;
  785. (void) len;
  786. retval = options_init_from_string(NULL, body, CMD_RUN_TOR, NULL, &errstring);
  787. if (retval != SETOPT_OK)
  788. log_warn(LD_CONTROL,
  789. "Controller gave us config file that didn't validate: %s",
  790. errstring);
  791. switch (retval) {
  792. case SETOPT_ERR_PARSE:
  793. msg = "552 Invalid config file";
  794. break;
  795. case SETOPT_ERR_TRANSITION:
  796. msg = "553 Transition not allowed";
  797. break;
  798. case SETOPT_ERR_SETTING:
  799. msg = "553 Unable to set option";
  800. break;
  801. case SETOPT_ERR_MISC:
  802. default:
  803. msg = "550 Unable to load config";
  804. break;
  805. case SETOPT_OK:
  806. break;
  807. }
  808. if (msg) {
  809. if (errstring)
  810. connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
  811. else
  812. connection_printf_to_buf(conn, "%s\r\n", msg);
  813. } else {
  814. send_control_done(conn);
  815. }
  816. tor_free(errstring);
  817. return 0;
  818. }
  819. /** Helper structure: maps event values to their names. */
  820. struct control_event_t {
  821. uint16_t event_code;
  822. const char *event_name;
  823. };
  824. /** Table mapping event values to their names. Used to implement SETEVENTS
  825. * and GETINFO events/names, and to keep they in sync. */
  826. static const struct control_event_t control_event_table[] = {
  827. { EVENT_CIRCUIT_STATUS, "CIRC" },
  828. { EVENT_CIRCUIT_STATUS_MINOR, "CIRC_MINOR" },
  829. { EVENT_STREAM_STATUS, "STREAM" },
  830. { EVENT_OR_CONN_STATUS, "ORCONN" },
  831. { EVENT_BANDWIDTH_USED, "BW" },
  832. { EVENT_DEBUG_MSG, "DEBUG" },
  833. { EVENT_INFO_MSG, "INFO" },
  834. { EVENT_NOTICE_MSG, "NOTICE" },
  835. { EVENT_WARN_MSG, "WARN" },
  836. { EVENT_ERR_MSG, "ERR" },
  837. { EVENT_NEW_DESC, "NEWDESC" },
  838. { EVENT_ADDRMAP, "ADDRMAP" },
  839. { EVENT_AUTHDIR_NEWDESCS, "AUTHDIR_NEWDESCS" },
  840. { EVENT_DESCCHANGED, "DESCCHANGED" },
  841. { EVENT_NS, "NS" },
  842. { EVENT_STATUS_GENERAL, "STATUS_GENERAL" },
  843. { EVENT_STATUS_CLIENT, "STATUS_CLIENT" },
  844. { EVENT_STATUS_SERVER, "STATUS_SERVER" },
  845. { EVENT_GUARD, "GUARD" },
  846. { EVENT_STREAM_BANDWIDTH_USED, "STREAM_BW" },
  847. { EVENT_CLIENTS_SEEN, "CLIENTS_SEEN" },
  848. { EVENT_NEWCONSENSUS, "NEWCONSENSUS" },
  849. { EVENT_BUILDTIMEOUT_SET, "BUILDTIMEOUT_SET" },
  850. { EVENT_SIGNAL, "SIGNAL" },
  851. { EVENT_CONF_CHANGED, "CONF_CHANGED"},
  852. { EVENT_CONN_BW, "CONN_BW" },
  853. { EVENT_CELL_STATS, "CELL_STATS" },
  854. { EVENT_TB_EMPTY, "TB_EMPTY" },
  855. { EVENT_CIRC_BANDWIDTH_USED, "CIRC_BW" },
  856. { EVENT_TRANSPORT_LAUNCHED, "TRANSPORT_LAUNCHED" },
  857. { EVENT_HS_DESC, "HS_DESC" },
  858. { 0, NULL },
  859. };
  860. /** Called when we get a SETEVENTS message: update conn->event_mask,
  861. * and reply with DONE or ERROR. */
  862. static int
  863. handle_control_setevents(control_connection_t *conn, uint32_t len,
  864. const char *body)
  865. {
  866. int event_code;
  867. event_mask_t event_mask = 0;
  868. smartlist_t *events = smartlist_new();
  869. (void) len;
  870. smartlist_split_string(events, body, " ",
  871. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  872. SMARTLIST_FOREACH_BEGIN(events, const char *, ev)
  873. {
  874. if (!strcasecmp(ev, "EXTENDED")) {
  875. continue;
  876. } else {
  877. int i;
  878. event_code = -1;
  879. for (i = 0; control_event_table[i].event_name != NULL; ++i) {
  880. if (!strcasecmp(ev, control_event_table[i].event_name)) {
  881. event_code = control_event_table[i].event_code;
  882. break;
  883. }
  884. }
  885. if (event_code == -1) {
  886. connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
  887. ev);
  888. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  889. smartlist_free(events);
  890. return 0;
  891. }
  892. }
  893. event_mask |= (((event_mask_t)1) << event_code);
  894. }
  895. SMARTLIST_FOREACH_END(ev);
  896. SMARTLIST_FOREACH(events, char *, e, tor_free(e));
  897. smartlist_free(events);
  898. conn->event_mask = event_mask;
  899. control_update_global_event_mask();
  900. send_control_done(conn);
  901. return 0;
  902. }
  903. /** Decode the hashed, base64'd passwords stored in <b>passwords</b>.
  904. * Return a smartlist of acceptable passwords (unterminated strings of
  905. * length S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN) on success, or NULL on
  906. * failure.
  907. */
  908. smartlist_t *
  909. decode_hashed_passwords(config_line_t *passwords)
  910. {
  911. char decoded[64];
  912. config_line_t *cl;
  913. smartlist_t *sl = smartlist_new();
  914. tor_assert(passwords);
  915. for (cl = passwords; cl; cl = cl->next) {
  916. const char *hashed = cl->value;
  917. if (!strcmpstart(hashed, "16:")) {
  918. if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
  919. || strlen(hashed+3) != (S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN)*2) {
  920. goto err;
  921. }
  922. } else {
  923. if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
  924. != S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN) {
  925. goto err;
  926. }
  927. }
  928. smartlist_add(sl,
  929. tor_memdup(decoded, S2K_RFC2440_SPECIFIER_LEN+DIGEST_LEN));
  930. }
  931. return sl;
  932. err:
  933. SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
  934. smartlist_free(sl);
  935. return NULL;
  936. }
  937. /** Called when we get an AUTHENTICATE message. Check whether the
  938. * authentication is valid, and if so, update the connection's state to
  939. * OPEN. Reply with DONE or ERROR.
  940. */
  941. static int
  942. handle_control_authenticate(control_connection_t *conn, uint32_t len,
  943. const char *body)
  944. {
  945. int used_quoted_string = 0;
  946. const or_options_t *options = get_options();
  947. const char *errstr = "Unknown error";
  948. char *password;
  949. size_t password_len;
  950. const char *cp;
  951. int i;
  952. int bad_cookie=0, bad_password=0;
  953. smartlist_t *sl = NULL;
  954. if (!len) {
  955. password = tor_strdup("");
  956. password_len = 0;
  957. } else if (TOR_ISXDIGIT(body[0])) {
  958. cp = body;
  959. while (TOR_ISXDIGIT(*cp))
  960. ++cp;
  961. i = (int)(cp - body);
  962. tor_assert(i>0);
  963. password_len = i/2;
  964. password = tor_malloc(password_len + 1);
  965. if (base16_decode(password, password_len+1, body, i)<0) {
  966. connection_write_str_to_buf(
  967. "551 Invalid hexadecimal encoding. Maybe you tried a plain text "
  968. "password? If so, the standard requires that you put it in "
  969. "double quotes.\r\n", conn);
  970. connection_mark_for_close(TO_CONN(conn));
  971. tor_free(password);
  972. return 0;
  973. }
  974. } else {
  975. if (!decode_escaped_string(body, len, &password, &password_len)) {
  976. connection_write_str_to_buf("551 Invalid quoted string. You need "
  977. "to put the password in double quotes.\r\n", conn);
  978. connection_mark_for_close(TO_CONN(conn));
  979. return 0;
  980. }
  981. used_quoted_string = 1;
  982. }
  983. if (conn->safecookie_client_hash != NULL) {
  984. /* The controller has chosen safe cookie authentication; the only
  985. * acceptable authentication value is the controller-to-server
  986. * response. */
  987. tor_assert(authentication_cookie_is_set);
  988. if (password_len != DIGEST256_LEN) {
  989. log_warn(LD_CONTROL,
  990. "Got safe cookie authentication response with wrong length "
  991. "(%d)", (int)password_len);
  992. errstr = "Wrong length for safe cookie response.";
  993. goto err;
  994. }
  995. if (tor_memneq(conn->safecookie_client_hash, password, DIGEST256_LEN)) {
  996. log_warn(LD_CONTROL,
  997. "Got incorrect safe cookie authentication response");
  998. errstr = "Safe cookie response did not match expected value.";
  999. goto err;
  1000. }
  1001. tor_free(conn->safecookie_client_hash);
  1002. goto ok;
  1003. }
  1004. if (!options->CookieAuthentication && !options->HashedControlPassword &&
  1005. !options->HashedControlSessionPassword) {
  1006. /* if Tor doesn't demand any stronger authentication, then
  1007. * the controller can get in with anything. */
  1008. goto ok;
  1009. }
  1010. if (options->CookieAuthentication) {
  1011. int also_password = options->HashedControlPassword != NULL ||
  1012. options->HashedControlSessionPassword != NULL;
  1013. if (password_len != AUTHENTICATION_COOKIE_LEN) {
  1014. if (!also_password) {
  1015. log_warn(LD_CONTROL, "Got authentication cookie with wrong length "
  1016. "(%d)", (int)password_len);
  1017. errstr = "Wrong length on authentication cookie.";
  1018. goto err;
  1019. }
  1020. bad_cookie = 1;
  1021. } else if (tor_memneq(authentication_cookie, password, password_len)) {
  1022. if (!also_password) {
  1023. log_warn(LD_CONTROL, "Got mismatched authentication cookie");
  1024. errstr = "Authentication cookie did not match expected value.";
  1025. goto err;
  1026. }
  1027. bad_cookie = 1;
  1028. } else {
  1029. goto ok;
  1030. }
  1031. }
  1032. if (options->HashedControlPassword ||
  1033. options->HashedControlSessionPassword) {
  1034. int bad = 0;
  1035. smartlist_t *sl_tmp;
  1036. char received[DIGEST_LEN];
  1037. int also_cookie = options->CookieAuthentication;
  1038. sl = smartlist_new();
  1039. if (options->HashedControlPassword) {
  1040. sl_tmp = decode_hashed_passwords(options->HashedControlPassword);
  1041. if (!sl_tmp)
  1042. bad = 1;
  1043. else {
  1044. smartlist_add_all(sl, sl_tmp);
  1045. smartlist_free(sl_tmp);
  1046. }
  1047. }
  1048. if (options->HashedControlSessionPassword) {
  1049. sl_tmp = decode_hashed_passwords(options->HashedControlSessionPassword);
  1050. if (!sl_tmp)
  1051. bad = 1;
  1052. else {
  1053. smartlist_add_all(sl, sl_tmp);
  1054. smartlist_free(sl_tmp);
  1055. }
  1056. }
  1057. if (bad) {
  1058. if (!also_cookie) {
  1059. log_warn(LD_BUG,
  1060. "Couldn't decode HashedControlPassword: invalid base16");
  1061. errstr="Couldn't decode HashedControlPassword value in configuration.";
  1062. goto err;
  1063. }
  1064. bad_password = 1;
  1065. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1066. smartlist_free(sl);
  1067. sl = NULL;
  1068. } else {
  1069. SMARTLIST_FOREACH(sl, char *, expected,
  1070. {
  1071. secret_to_key_rfc2440(received,DIGEST_LEN,
  1072. password,password_len,expected);
  1073. if (tor_memeq(expected + S2K_RFC2440_SPECIFIER_LEN,
  1074. received, DIGEST_LEN))
  1075. goto ok;
  1076. });
  1077. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1078. smartlist_free(sl);
  1079. sl = NULL;
  1080. if (used_quoted_string)
  1081. errstr = "Password did not match HashedControlPassword value from "
  1082. "configuration";
  1083. else
  1084. errstr = "Password did not match HashedControlPassword value from "
  1085. "configuration. Maybe you tried a plain text password? "
  1086. "If so, the standard requires that you put it in double quotes.";
  1087. bad_password = 1;
  1088. if (!also_cookie)
  1089. goto err;
  1090. }
  1091. }
  1092. /** We only get here if both kinds of authentication failed. */
  1093. tor_assert(bad_password && bad_cookie);
  1094. log_warn(LD_CONTROL, "Bad password or authentication cookie on controller.");
  1095. errstr = "Password did not match HashedControlPassword *or* authentication "
  1096. "cookie.";
  1097. err:
  1098. tor_free(password);
  1099. connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n", errstr);
  1100. connection_mark_for_close(TO_CONN(conn));
  1101. if (sl) { /* clean up */
  1102. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1103. smartlist_free(sl);
  1104. }
  1105. return 0;
  1106. ok:
  1107. log_info(LD_CONTROL, "Authenticated control connection ("TOR_SOCKET_T_FORMAT
  1108. ")", conn->base_.s);
  1109. send_control_done(conn);
  1110. conn->base_.state = CONTROL_CONN_STATE_OPEN;
  1111. tor_free(password);
  1112. if (sl) { /* clean up */
  1113. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1114. smartlist_free(sl);
  1115. }
  1116. return 0;
  1117. }
  1118. /** Called when we get a SAVECONF command. Try to flush the current options to
  1119. * disk, and report success or failure. */
  1120. static int
  1121. handle_control_saveconf(control_connection_t *conn, uint32_t len,
  1122. const char *body)
  1123. {
  1124. (void) len;
  1125. (void) body;
  1126. if (options_save_current()<0) {
  1127. connection_write_str_to_buf(
  1128. "551 Unable to write configuration to disk.\r\n", conn);
  1129. } else {
  1130. send_control_done(conn);
  1131. }
  1132. return 0;
  1133. }
  1134. struct signal_t {
  1135. int sig;
  1136. const char *signal_name;
  1137. };
  1138. static const struct signal_t signal_table[] = {
  1139. { SIGHUP, "RELOAD" },
  1140. { SIGHUP, "HUP" },
  1141. { SIGINT, "SHUTDOWN" },
  1142. { SIGUSR1, "DUMP" },
  1143. { SIGUSR1, "USR1" },
  1144. { SIGUSR2, "DEBUG" },
  1145. { SIGUSR2, "USR2" },
  1146. { SIGTERM, "HALT" },
  1147. { SIGTERM, "TERM" },
  1148. { SIGTERM, "INT" },
  1149. { SIGNEWNYM, "NEWNYM" },
  1150. { SIGCLEARDNSCACHE, "CLEARDNSCACHE"},
  1151. { SIGHEARTBEAT, "HEARTBEAT"},
  1152. { 0, NULL },
  1153. };
  1154. /** Called when we get a SIGNAL command. React to the provided signal, and
  1155. * report success or failure. (If the signal results in a shutdown, success
  1156. * may not be reported.) */
  1157. static int
  1158. handle_control_signal(control_connection_t *conn, uint32_t len,
  1159. const char *body)
  1160. {
  1161. int sig = -1;
  1162. int i;
  1163. int n = 0;
  1164. char *s;
  1165. (void) len;
  1166. while (body[n] && ! TOR_ISSPACE(body[n]))
  1167. ++n;
  1168. s = tor_strndup(body, n);
  1169. for (i = 0; signal_table[i].signal_name != NULL; ++i) {
  1170. if (!strcasecmp(s, signal_table[i].signal_name)) {
  1171. sig = signal_table[i].sig;
  1172. break;
  1173. }
  1174. }
  1175. if (sig < 0)
  1176. connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
  1177. s);
  1178. tor_free(s);
  1179. if (sig < 0)
  1180. return 0;
  1181. send_control_done(conn);
  1182. /* Flush the "done" first if the signal might make us shut down. */
  1183. if (sig == SIGTERM || sig == SIGINT)
  1184. connection_flush(TO_CONN(conn));
  1185. process_signal(sig);
  1186. return 0;
  1187. }
  1188. /** Called when we get a TAKEOWNERSHIP command. Mark this connection
  1189. * as an owning connection, so that we will exit if the connection
  1190. * closes. */
  1191. static int
  1192. handle_control_takeownership(control_connection_t *conn, uint32_t len,
  1193. const char *body)
  1194. {
  1195. (void)len;
  1196. (void)body;
  1197. conn->is_owning_control_connection = 1;
  1198. log_info(LD_CONTROL, "Control connection %d has taken ownership of this "
  1199. "Tor instance.",
  1200. (int)(conn->base_.s));
  1201. send_control_done(conn);
  1202. return 0;
  1203. }
  1204. /** Return true iff <b>addr</b> is unusable as a mapaddress target because of
  1205. * containing funny characters. */
  1206. static int
  1207. address_is_invalid_mapaddress_target(const char *addr)
  1208. {
  1209. if (!strcmpstart(addr, "*."))
  1210. return address_is_invalid_destination(addr+2, 1);
  1211. else
  1212. return address_is_invalid_destination(addr, 1);
  1213. }
  1214. /** Called when we get a MAPADDRESS command; try to bind all listed addresses,
  1215. * and report success or failure. */
  1216. static int
  1217. handle_control_mapaddress(control_connection_t *conn, uint32_t len,
  1218. const char *body)
  1219. {
  1220. smartlist_t *elts;
  1221. smartlist_t *lines;
  1222. smartlist_t *reply;
  1223. char *r;
  1224. size_t sz;
  1225. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  1226. lines = smartlist_new();
  1227. elts = smartlist_new();
  1228. reply = smartlist_new();
  1229. smartlist_split_string(lines, body, " ",
  1230. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1231. SMARTLIST_FOREACH_BEGIN(lines, char *, line) {
  1232. tor_strlower(line);
  1233. smartlist_split_string(elts, line, "=", 0, 2);
  1234. if (smartlist_len(elts) == 2) {
  1235. const char *from = smartlist_get(elts,0);
  1236. const char *to = smartlist_get(elts,1);
  1237. if (address_is_invalid_mapaddress_target(to)) {
  1238. smartlist_add_asprintf(reply,
  1239. "512-syntax error: invalid address '%s'", to);
  1240. log_warn(LD_CONTROL,
  1241. "Skipping invalid argument '%s' in MapAddress msg", to);
  1242. } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0") ||
  1243. !strcmp(from, "::")) {
  1244. const char type =
  1245. !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME :
  1246. (!strcmp(from, "0.0.0.0") ? RESOLVED_TYPE_IPV4 : RESOLVED_TYPE_IPV6);
  1247. const char *address = addressmap_register_virtual_address(
  1248. type, tor_strdup(to));
  1249. if (!address) {
  1250. smartlist_add_asprintf(reply,
  1251. "451-resource exhausted: skipping '%s'", line);
  1252. log_warn(LD_CONTROL,
  1253. "Unable to allocate address for '%s' in MapAddress msg",
  1254. safe_str_client(line));
  1255. } else {
  1256. smartlist_add_asprintf(reply, "250-%s=%s", address, to);
  1257. }
  1258. } else {
  1259. const char *msg;
  1260. if (addressmap_register_auto(from, to, 1,
  1261. ADDRMAPSRC_CONTROLLER, &msg) < 0) {
  1262. smartlist_add_asprintf(reply,
  1263. "512-syntax error: invalid address mapping "
  1264. " '%s': %s", line, msg);
  1265. log_warn(LD_CONTROL,
  1266. "Skipping invalid argument '%s' in MapAddress msg: %s",
  1267. line, msg);
  1268. } else {
  1269. smartlist_add_asprintf(reply, "250-%s", line);
  1270. }
  1271. }
  1272. } else {
  1273. smartlist_add_asprintf(reply, "512-syntax error: mapping '%s' is "
  1274. "not of expected form 'foo=bar'.", line);
  1275. log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
  1276. "number of items.",
  1277. safe_str_client(line));
  1278. }
  1279. SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
  1280. smartlist_clear(elts);
  1281. } SMARTLIST_FOREACH_END(line);
  1282. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1283. smartlist_free(lines);
  1284. smartlist_free(elts);
  1285. if (smartlist_len(reply)) {
  1286. ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
  1287. r = smartlist_join_strings(reply, "\r\n", 1, &sz);
  1288. connection_write_to_buf(r, sz, TO_CONN(conn));
  1289. tor_free(r);
  1290. } else {
  1291. const char *response =
  1292. "512 syntax error: not enough arguments to mapaddress.\r\n";
  1293. connection_write_to_buf(response, strlen(response), TO_CONN(conn));
  1294. }
  1295. SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
  1296. smartlist_free(reply);
  1297. return 0;
  1298. }
  1299. /** Implementation helper for GETINFO: knows the answers for various
  1300. * trivial-to-implement questions. */
  1301. static int
  1302. getinfo_helper_misc(control_connection_t *conn, const char *question,
  1303. char **answer, const char **errmsg)
  1304. {
  1305. (void) conn;
  1306. if (!strcmp(question, "version")) {
  1307. *answer = tor_strdup(get_version());
  1308. } else if (!strcmp(question, "bw-event-cache")) {
  1309. *answer = get_bw_samples();
  1310. } else if (!strcmp(question, "config-file")) {
  1311. const char *a = get_torrc_fname(0);
  1312. if (a)
  1313. *answer = tor_strdup(a);
  1314. } else if (!strcmp(question, "config-defaults-file")) {
  1315. const char *a = get_torrc_fname(1);
  1316. if (a)
  1317. *answer = tor_strdup(a);
  1318. } else if (!strcmp(question, "config-text")) {
  1319. *answer = options_dump(get_options(), OPTIONS_DUMP_MINIMAL);
  1320. } else if (!strcmp(question, "info/names")) {
  1321. *answer = list_getinfo_options();
  1322. } else if (!strcmp(question, "dormant")) {
  1323. int dormant = rep_hist_circbuilding_dormant(time(NULL));
  1324. *answer = tor_strdup(dormant ? "1" : "0");
  1325. } else if (!strcmp(question, "events/names")) {
  1326. int i;
  1327. smartlist_t *event_names = smartlist_new();
  1328. for (i = 0; control_event_table[i].event_name != NULL; ++i) {
  1329. smartlist_add(event_names, (char *)control_event_table[i].event_name);
  1330. }
  1331. *answer = smartlist_join_strings(event_names, " ", 0, NULL);
  1332. smartlist_free(event_names);
  1333. } else if (!strcmp(question, "signal/names")) {
  1334. smartlist_t *signal_names = smartlist_new();
  1335. int j;
  1336. for (j = 0; signal_table[j].signal_name != NULL; ++j) {
  1337. smartlist_add(signal_names, (char*)signal_table[j].signal_name);
  1338. }
  1339. *answer = smartlist_join_strings(signal_names, " ", 0, NULL);
  1340. smartlist_free(signal_names);
  1341. } else if (!strcmp(question, "features/names")) {
  1342. *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
  1343. } else if (!strcmp(question, "address")) {
  1344. uint32_t addr;
  1345. if (router_pick_published_address(get_options(), &addr) < 0) {
  1346. *errmsg = "Address unknown";
  1347. return -1;
  1348. }
  1349. *answer = tor_dup_ip(addr);
  1350. } else if (!strcmp(question, "traffic/read")) {
  1351. tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_read()));
  1352. } else if (!strcmp(question, "traffic/written")) {
  1353. tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_written()));
  1354. } else if (!strcmp(question, "process/pid")) {
  1355. int myPid = -1;
  1356. #ifdef _WIN32
  1357. myPid = _getpid();
  1358. #else
  1359. myPid = getpid();
  1360. #endif
  1361. tor_asprintf(answer, "%d", myPid);
  1362. } else if (!strcmp(question, "process/uid")) {
  1363. #ifdef _WIN32
  1364. *answer = tor_strdup("-1");
  1365. #else
  1366. int myUid = geteuid();
  1367. tor_asprintf(answer, "%d", myUid);
  1368. #endif
  1369. } else if (!strcmp(question, "process/user")) {
  1370. #ifdef _WIN32
  1371. *answer = tor_strdup("");
  1372. #else
  1373. int myUid = geteuid();
  1374. const struct passwd *myPwEntry = tor_getpwuid(myUid);
  1375. if (myPwEntry) {
  1376. *answer = tor_strdup(myPwEntry->pw_name);
  1377. } else {
  1378. *answer = tor_strdup("");
  1379. }
  1380. #endif
  1381. } else if (!strcmp(question, "process/descriptor-limit")) {
  1382. int max_fds=-1;
  1383. set_max_file_descriptors(0, &max_fds);
  1384. tor_asprintf(answer, "%d", max_fds);
  1385. } else if (!strcmp(question, "limits/max-mem-in-queues")) {
  1386. tor_asprintf(answer, U64_FORMAT,
  1387. U64_PRINTF_ARG(get_options()->MaxMemInQueues));
  1388. } else if (!strcmp(question, "dir-usage")) {
  1389. *answer = directory_dump_request_log();
  1390. } else if (!strcmp(question, "fingerprint")) {
  1391. crypto_pk_t *server_key;
  1392. if (!server_mode(get_options())) {
  1393. *errmsg = "Not running in server mode";
  1394. return -1;
  1395. }
  1396. server_key = get_server_identity_key();
  1397. *answer = tor_malloc(HEX_DIGEST_LEN+1);
  1398. crypto_pk_get_fingerprint(server_key, *answer, 0);
  1399. }
  1400. return 0;
  1401. }
  1402. /** Awful hack: return a newly allocated string based on a routerinfo and
  1403. * (possibly) an extrainfo, sticking the read-history and write-history from
  1404. * <b>ei</b> into the resulting string. The thing you get back won't
  1405. * necessarily have a valid signature.
  1406. *
  1407. * New code should never use this; it's for backward compatibility.
  1408. *
  1409. * NOTE: <b>ri_body</b> is as returned by signed_descriptor_get_body: it might
  1410. * not be NUL-terminated. */
  1411. static char *
  1412. munge_extrainfo_into_routerinfo(const char *ri_body,
  1413. const signed_descriptor_t *ri,
  1414. const signed_descriptor_t *ei)
  1415. {
  1416. char *out = NULL, *outp;
  1417. int i;
  1418. const char *router_sig;
  1419. const char *ei_body = signed_descriptor_get_body(ei);
  1420. size_t ri_len = ri->signed_descriptor_len;
  1421. size_t ei_len = ei->signed_descriptor_len;
  1422. if (!ei_body)
  1423. goto bail;
  1424. outp = out = tor_malloc(ri_len+ei_len+1);
  1425. if (!(router_sig = tor_memstr(ri_body, ri_len, "\nrouter-signature")))
  1426. goto bail;
  1427. ++router_sig;
  1428. memcpy(out, ri_body, router_sig-ri_body);
  1429. outp += router_sig-ri_body;
  1430. for (i=0; i < 2; ++i) {
  1431. const char *kwd = i ? "\nwrite-history " : "\nread-history ";
  1432. const char *cp, *eol;
  1433. if (!(cp = tor_memstr(ei_body, ei_len, kwd)))
  1434. continue;
  1435. ++cp;
  1436. if (!(eol = memchr(cp, '\n', ei_len - (cp-ei_body))))
  1437. continue;
  1438. memcpy(outp, cp, eol-cp+1);
  1439. outp += eol-cp+1;
  1440. }
  1441. memcpy(outp, router_sig, ri_len - (router_sig-ri_body));
  1442. *outp++ = '\0';
  1443. tor_assert(outp-out < (int)(ri_len+ei_len+1));
  1444. return out;
  1445. bail:
  1446. tor_free(out);
  1447. return tor_strndup(ri_body, ri->signed_descriptor_len);
  1448. }
  1449. /** Implementation helper for GETINFO: answers requests for information about
  1450. * which ports are bound. */
  1451. static int
  1452. getinfo_helper_listeners(control_connection_t *control_conn,
  1453. const char *question,
  1454. char **answer, const char **errmsg)
  1455. {
  1456. int type;
  1457. smartlist_t *res;
  1458. (void)control_conn;
  1459. (void)errmsg;
  1460. if (!strcmp(question, "net/listeners/or"))
  1461. type = CONN_TYPE_OR_LISTENER;
  1462. else if (!strcmp(question, "net/listeners/dir"))
  1463. type = CONN_TYPE_DIR_LISTENER;
  1464. else if (!strcmp(question, "net/listeners/socks"))
  1465. type = CONN_TYPE_AP_LISTENER;
  1466. else if (!strcmp(question, "net/listeners/trans"))
  1467. type = CONN_TYPE_AP_TRANS_LISTENER;
  1468. else if (!strcmp(question, "net/listeners/natd"))
  1469. type = CONN_TYPE_AP_NATD_LISTENER;
  1470. else if (!strcmp(question, "net/listeners/dns"))
  1471. type = CONN_TYPE_AP_DNS_LISTENER;
  1472. else if (!strcmp(question, "net/listeners/control"))
  1473. type = CONN_TYPE_CONTROL_LISTENER;
  1474. else
  1475. return 0; /* unknown key */
  1476. res = smartlist_new();
  1477. SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
  1478. struct sockaddr_storage ss;
  1479. socklen_t ss_len = sizeof(ss);
  1480. if (conn->type != type || conn->marked_for_close || !SOCKET_OK(conn->s))
  1481. continue;
  1482. if (getsockname(conn->s, (struct sockaddr *)&ss, &ss_len) < 0) {
  1483. smartlist_add_asprintf(res, "%s:%d", conn->address, (int)conn->port);
  1484. } else {
  1485. char *tmp = tor_sockaddr_to_str((struct sockaddr *)&ss);
  1486. smartlist_add(res, esc_for_log(tmp));
  1487. tor_free(tmp);
  1488. }
  1489. } SMARTLIST_FOREACH_END(conn);
  1490. *answer = smartlist_join_strings(res, " ", 0, NULL);
  1491. SMARTLIST_FOREACH(res, char *, cp, tor_free(cp));
  1492. smartlist_free(res);
  1493. return 0;
  1494. }
  1495. /** Implementation helper for GETINFO: knows the answers for questions about
  1496. * directory information. */
  1497. static int
  1498. getinfo_helper_dir(control_connection_t *control_conn,
  1499. const char *question, char **answer,
  1500. const char **errmsg)
  1501. {
  1502. const node_t *node;
  1503. const routerinfo_t *ri = NULL;
  1504. (void) control_conn;
  1505. if (!strcmpstart(question, "desc/id/")) {
  1506. node = node_get_by_hex_id(question+strlen("desc/id/"));
  1507. if (node)
  1508. ri = node->ri;
  1509. if (ri) {
  1510. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1511. if (body)
  1512. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1513. }
  1514. } else if (!strcmpstart(question, "desc/name/")) {
  1515. /* XXX023 Setting 'warn_if_unnamed' here is a bit silly -- the
  1516. * warning goes to the user, not to the controller. */
  1517. node = node_get_by_nickname(question+strlen("desc/name/"), 1);
  1518. if (node)
  1519. ri = node->ri;
  1520. if (ri) {
  1521. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1522. if (body)
  1523. *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
  1524. }
  1525. } else if (!strcmp(question, "desc/all-recent")) {
  1526. routerlist_t *routerlist = router_get_routerlist();
  1527. smartlist_t *sl = smartlist_new();
  1528. if (routerlist && routerlist->routers) {
  1529. SMARTLIST_FOREACH(routerlist->routers, const routerinfo_t *, ri,
  1530. {
  1531. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1532. if (body)
  1533. smartlist_add(sl,
  1534. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1535. });
  1536. }
  1537. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1538. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1539. smartlist_free(sl);
  1540. } else if (!strcmp(question, "desc/all-recent-extrainfo-hack")) {
  1541. /* XXXX Remove this once Torstat asks for extrainfos. */
  1542. routerlist_t *routerlist = router_get_routerlist();
  1543. smartlist_t *sl = smartlist_new();
  1544. if (routerlist && routerlist->routers) {
  1545. SMARTLIST_FOREACH_BEGIN(routerlist->routers, const routerinfo_t *, ri) {
  1546. const char *body = signed_descriptor_get_body(&ri->cache_info);
  1547. signed_descriptor_t *ei = extrainfo_get_by_descriptor_digest(
  1548. ri->cache_info.extra_info_digest);
  1549. if (ei && body) {
  1550. smartlist_add(sl, munge_extrainfo_into_routerinfo(body,
  1551. &ri->cache_info, ei));
  1552. } else if (body) {
  1553. smartlist_add(sl,
  1554. tor_strndup(body, ri->cache_info.signed_descriptor_len));
  1555. }
  1556. } SMARTLIST_FOREACH_END(ri);
  1557. }
  1558. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1559. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1560. smartlist_free(sl);
  1561. } else if (!strcmpstart(question, "md/id/")) {
  1562. const node_t *node = node_get_by_hex_id(question+strlen("md/id/"));
  1563. const microdesc_t *md = NULL;
  1564. if (node) md = node->md;
  1565. if (md && md->body) {
  1566. *answer = tor_strndup(md->body, md->bodylen);
  1567. }
  1568. } else if (!strcmpstart(question, "md/name/")) {
  1569. /* XXX023 Setting 'warn_if_unnamed' here is a bit silly -- the
  1570. * warning goes to the user, not to the controller. */
  1571. const node_t *node = node_get_by_nickname(question+strlen("md/name/"), 1);
  1572. /* XXXX duplicated code */
  1573. const microdesc_t *md = NULL;
  1574. if (node) md = node->md;
  1575. if (md && md->body) {
  1576. *answer = tor_strndup(md->body, md->bodylen);
  1577. }
  1578. } else if (!strcmpstart(question, "desc-annotations/id/")) {
  1579. node = node_get_by_hex_id(question+strlen("desc-annotations/id/"));
  1580. if (node)
  1581. ri = node->ri;
  1582. if (ri) {
  1583. const char *annotations =
  1584. signed_descriptor_get_annotations(&ri->cache_info);
  1585. if (annotations)
  1586. *answer = tor_strndup(annotations,
  1587. ri->cache_info.annotations_len);
  1588. }
  1589. } else if (!strcmpstart(question, "dir/server/")) {
  1590. size_t answer_len = 0;
  1591. char *url = NULL;
  1592. smartlist_t *descs = smartlist_new();
  1593. const char *msg;
  1594. int res;
  1595. char *cp;
  1596. tor_asprintf(&url, "/tor/%s", question+4);
  1597. res = dirserv_get_routerdescs(descs, url, &msg);
  1598. if (res) {
  1599. log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
  1600. smartlist_free(descs);
  1601. tor_free(url);
  1602. *errmsg = msg;
  1603. return -1;
  1604. }
  1605. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1606. answer_len += sd->signed_descriptor_len);
  1607. cp = *answer = tor_malloc(answer_len+1);
  1608. SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
  1609. {
  1610. memcpy(cp, signed_descriptor_get_body(sd),
  1611. sd->signed_descriptor_len);
  1612. cp += sd->signed_descriptor_len;
  1613. });
  1614. *cp = '\0';
  1615. tor_free(url);
  1616. smartlist_free(descs);
  1617. } else if (!strcmpstart(question, "dir/status/")) {
  1618. *answer = tor_strdup("");
  1619. } else if (!strcmp(question, "dir/status-vote/current/consensus")) { /* v3 */
  1620. if (directory_caches_dir_info(get_options())) {
  1621. const cached_dir_t *consensus = dirserv_get_consensus("ns");
  1622. if (consensus)
  1623. *answer = tor_strdup(consensus->dir);
  1624. }
  1625. if (!*answer) { /* try loading it from disk */
  1626. char *filename = get_datadir_fname("cached-consensus");
  1627. *answer = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
  1628. tor_free(filename);
  1629. }
  1630. } else if (!strcmp(question, "network-status")) { /* v1 */
  1631. routerlist_t *routerlist = router_get_routerlist();
  1632. if (!routerlist || !routerlist->routers ||
  1633. list_server_status_v1(routerlist->routers, answer, 1) < 0) {
  1634. return -1;
  1635. }
  1636. } else if (!strcmpstart(question, "extra-info/digest/")) {
  1637. question += strlen("extra-info/digest/");
  1638. if (strlen(question) == HEX_DIGEST_LEN) {
  1639. char d[DIGEST_LEN];
  1640. signed_descriptor_t *sd = NULL;
  1641. if (base16_decode(d, sizeof(d), question, strlen(question))==0) {
  1642. /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
  1643. * but I don't want to risk affecting other parts of the code,
  1644. * especially since the rules for using our own extrainfo (including
  1645. * when it might be freed) are different from those for using one
  1646. * we have downloaded. */
  1647. if (router_extrainfo_digest_is_me(d))
  1648. sd = &(router_get_my_extrainfo()->cache_info);
  1649. else
  1650. sd = extrainfo_get_by_descriptor_digest(d);
  1651. }
  1652. if (sd) {
  1653. const char *body = signed_descriptor_get_body(sd);
  1654. if (body)
  1655. *answer = tor_strndup(body, sd->signed_descriptor_len);
  1656. }
  1657. }
  1658. }
  1659. return 0;
  1660. }
  1661. /** Allocate and return a description of <b>circ</b>'s current status,
  1662. * including its path (if any). */
  1663. static char *
  1664. circuit_describe_status_for_controller(origin_circuit_t *circ)
  1665. {
  1666. char *rv;
  1667. smartlist_t *descparts = smartlist_new();
  1668. {
  1669. char *vpath = circuit_list_path_for_controller(circ);
  1670. if (*vpath) {
  1671. smartlist_add(descparts, vpath);
  1672. } else {
  1673. tor_free(vpath); /* empty path; don't put an extra space in the result */
  1674. }
  1675. }
  1676. {
  1677. cpath_build_state_t *build_state = circ->build_state;
  1678. smartlist_t *flaglist = smartlist_new();
  1679. char *flaglist_joined;
  1680. if (build_state->onehop_tunnel)
  1681. smartlist_add(flaglist, (void *)"ONEHOP_TUNNEL");
  1682. if (build_state->is_internal)
  1683. smartlist_add(flaglist, (void *)"IS_INTERNAL");
  1684. if (build_state->need_capacity)
  1685. smartlist_add(flaglist, (void *)"NEED_CAPACITY");
  1686. if (build_state->need_uptime)
  1687. smartlist_add(flaglist, (void *)"NEED_UPTIME");
  1688. /* Only emit a BUILD_FLAGS argument if it will have a non-empty value. */
  1689. if (smartlist_len(flaglist)) {
  1690. flaglist_joined = smartlist_join_strings(flaglist, ",", 0, NULL);
  1691. smartlist_add_asprintf(descparts, "BUILD_FLAGS=%s", flaglist_joined);
  1692. tor_free(flaglist_joined);
  1693. }
  1694. smartlist_free(flaglist);
  1695. }
  1696. smartlist_add_asprintf(descparts, "PURPOSE=%s",
  1697. circuit_purpose_to_controller_string(circ->base_.purpose));
  1698. {
  1699. const char *hs_state =
  1700. circuit_purpose_to_controller_hs_state_string(circ->base_.purpose);
  1701. if (hs_state != NULL) {
  1702. smartlist_add_asprintf(descparts, "HS_STATE=%s", hs_state);
  1703. }
  1704. }
  1705. if (circ->rend_data != NULL) {
  1706. smartlist_add_asprintf(descparts, "REND_QUERY=%s",
  1707. circ->rend_data->onion_address);
  1708. }
  1709. {
  1710. char tbuf[ISO_TIME_USEC_LEN+1];
  1711. format_iso_time_nospace_usec(tbuf, &circ->base_.timestamp_created);
  1712. smartlist_add_asprintf(descparts, "TIME_CREATED=%s", tbuf);
  1713. }
  1714. // Show username and/or password if available.
  1715. if (circ->socks_username_len > 0) {
  1716. char* socks_username_escaped = esc_for_log_len(circ->socks_username,
  1717. (size_t) circ->socks_username_len);
  1718. smartlist_add_asprintf(descparts, "SOCKS_USERNAME=%s",
  1719. socks_username_escaped);
  1720. tor_free(socks_username_escaped);
  1721. }
  1722. if (circ->socks_password_len > 0) {
  1723. char* socks_password_escaped = esc_for_log_len(circ->socks_password,
  1724. (size_t) circ->socks_password_len);
  1725. smartlist_add_asprintf(descparts, "SOCKS_PASSWORD=%s",
  1726. socks_password_escaped);
  1727. tor_free(socks_password_escaped);
  1728. }
  1729. rv = smartlist_join_strings(descparts, " ", 0, NULL);
  1730. SMARTLIST_FOREACH(descparts, char *, cp, tor_free(cp));
  1731. smartlist_free(descparts);
  1732. return rv;
  1733. }
  1734. /** Implementation helper for GETINFO: knows how to generate summaries of the
  1735. * current states of things we send events about. */
  1736. static int
  1737. getinfo_helper_events(control_connection_t *control_conn,
  1738. const char *question, char **answer,
  1739. const char **errmsg)
  1740. {
  1741. (void) control_conn;
  1742. if (!strcmp(question, "circuit-status")) {
  1743. smartlist_t *status = smartlist_new();
  1744. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ_) {
  1745. origin_circuit_t *circ;
  1746. char *circdesc;
  1747. const char *state;
  1748. if (! CIRCUIT_IS_ORIGIN(circ_) || circ_->marked_for_close)
  1749. continue;
  1750. circ = TO_ORIGIN_CIRCUIT(circ_);
  1751. if (circ->base_.state == CIRCUIT_STATE_OPEN)
  1752. state = "BUILT";
  1753. else if (circ->cpath)
  1754. state = "EXTENDED";
  1755. else
  1756. state = "LAUNCHED";
  1757. circdesc = circuit_describe_status_for_controller(circ);
  1758. smartlist_add_asprintf(status, "%lu %s%s%s",
  1759. (unsigned long)circ->global_identifier,
  1760. state, *circdesc ? " " : "", circdesc);
  1761. tor_free(circdesc);
  1762. }
  1763. SMARTLIST_FOREACH_END(circ_);
  1764. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1765. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1766. smartlist_free(status);
  1767. } else if (!strcmp(question, "stream-status")) {
  1768. smartlist_t *conns = get_connection_array();
  1769. smartlist_t *status = smartlist_new();
  1770. char buf[256];
  1771. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  1772. const char *state;
  1773. entry_connection_t *conn;
  1774. circuit_t *circ;
  1775. origin_circuit_t *origin_circ = NULL;
  1776. if (base_conn->type != CONN_TYPE_AP ||
  1777. base_conn->marked_for_close ||
  1778. base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
  1779. base_conn->state == AP_CONN_STATE_NATD_WAIT)
  1780. continue;
  1781. conn = TO_ENTRY_CONN(base_conn);
  1782. switch (base_conn->state)
  1783. {
  1784. case AP_CONN_STATE_CONTROLLER_WAIT:
  1785. case AP_CONN_STATE_CIRCUIT_WAIT:
  1786. if (conn->socks_request &&
  1787. SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
  1788. state = "NEWRESOLVE";
  1789. else
  1790. state = "NEW";
  1791. break;
  1792. case AP_CONN_STATE_RENDDESC_WAIT:
  1793. case AP_CONN_STATE_CONNECT_WAIT:
  1794. state = "SENTCONNECT"; break;
  1795. case AP_CONN_STATE_RESOLVE_WAIT:
  1796. state = "SENTRESOLVE"; break;
  1797. case AP_CONN_STATE_OPEN:
  1798. state = "SUCCEEDED"; break;
  1799. default:
  1800. log_warn(LD_BUG, "Asked for stream in unknown state %d",
  1801. base_conn->state);
  1802. continue;
  1803. }
  1804. circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
  1805. if (circ && CIRCUIT_IS_ORIGIN(circ))
  1806. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1807. write_stream_target_to_buf(conn, buf, sizeof(buf));
  1808. smartlist_add_asprintf(status, "%lu %s %lu %s",
  1809. (unsigned long) base_conn->global_identifier,state,
  1810. origin_circ?
  1811. (unsigned long)origin_circ->global_identifier : 0ul,
  1812. buf);
  1813. } SMARTLIST_FOREACH_END(base_conn);
  1814. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1815. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1816. smartlist_free(status);
  1817. } else if (!strcmp(question, "orconn-status")) {
  1818. smartlist_t *conns = get_connection_array();
  1819. smartlist_t *status = smartlist_new();
  1820. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  1821. const char *state;
  1822. char name[128];
  1823. or_connection_t *conn;
  1824. if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
  1825. continue;
  1826. conn = TO_OR_CONN(base_conn);
  1827. if (conn->base_.state == OR_CONN_STATE_OPEN)
  1828. state = "CONNECTED";
  1829. else if (conn->nickname)
  1830. state = "LAUNCHED";
  1831. else
  1832. state = "NEW";
  1833. orconn_target_get_name(name, sizeof(name), conn);
  1834. smartlist_add_asprintf(status, "%s %s", name, state);
  1835. } SMARTLIST_FOREACH_END(base_conn);
  1836. *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
  1837. SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
  1838. smartlist_free(status);
  1839. } else if (!strcmpstart(question, "address-mappings/")) {
  1840. time_t min_e, max_e;
  1841. smartlist_t *mappings;
  1842. question += strlen("address-mappings/");
  1843. if (!strcmp(question, "all")) {
  1844. min_e = 0; max_e = TIME_MAX;
  1845. } else if (!strcmp(question, "cache")) {
  1846. min_e = 2; max_e = TIME_MAX;
  1847. } else if (!strcmp(question, "config")) {
  1848. min_e = 0; max_e = 0;
  1849. } else if (!strcmp(question, "control")) {
  1850. min_e = 1; max_e = 1;
  1851. } else {
  1852. return 0;
  1853. }
  1854. mappings = smartlist_new();
  1855. addressmap_get_mappings(mappings, min_e, max_e, 1);
  1856. *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
  1857. SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
  1858. smartlist_free(mappings);
  1859. } else if (!strcmpstart(question, "status/")) {
  1860. /* Note that status/ is not a catch-all for events; there's only supposed
  1861. * to be a status GETINFO if there's a corresponding STATUS event. */
  1862. if (!strcmp(question, "status/circuit-established")) {
  1863. *answer = tor_strdup(have_completed_a_circuit() ? "1" : "0");
  1864. } else if (!strcmp(question, "status/enough-dir-info")) {
  1865. *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
  1866. } else if (!strcmp(question, "status/good-server-descriptor") ||
  1867. !strcmp(question, "status/accepted-server-descriptor")) {
  1868. /* They're equivalent for now, until we can figure out how to make
  1869. * good-server-descriptor be what we want. See comment in
  1870. * control-spec.txt. */
  1871. *answer = tor_strdup(directories_have_accepted_server_descriptor()
  1872. ? "1" : "0");
  1873. } else if (!strcmp(question, "status/reachability-succeeded/or")) {
  1874. *answer = tor_strdup(check_whether_orport_reachable() ? "1" : "0");
  1875. } else if (!strcmp(question, "status/reachability-succeeded/dir")) {
  1876. *answer = tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
  1877. } else if (!strcmp(question, "status/reachability-succeeded")) {
  1878. tor_asprintf(answer, "OR=%d DIR=%d",
  1879. check_whether_orport_reachable() ? 1 : 0,
  1880. check_whether_dirport_reachable() ? 1 : 0);
  1881. } else if (!strcmp(question, "status/bootstrap-phase")) {
  1882. *answer = tor_strdup(last_sent_bootstrap_message);
  1883. } else if (!strcmpstart(question, "status/version/")) {
  1884. int is_server = server_mode(get_options());
  1885. networkstatus_t *c = networkstatus_get_latest_consensus();
  1886. version_status_t status;
  1887. const char *recommended;
  1888. if (c) {
  1889. recommended = is_server ? c->server_versions : c->client_versions;
  1890. status = tor_version_is_obsolete(VERSION, recommended);
  1891. } else {
  1892. recommended = "?";
  1893. status = VS_UNKNOWN;
  1894. }
  1895. if (!strcmp(question, "status/version/recommended")) {
  1896. *answer = tor_strdup(recommended);
  1897. return 0;
  1898. }
  1899. if (!strcmp(question, "status/version/current")) {
  1900. switch (status)
  1901. {
  1902. case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
  1903. case VS_OLD: *answer = tor_strdup("obsolete"); break;
  1904. case VS_NEW: *answer = tor_strdup("new"); break;
  1905. case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
  1906. case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
  1907. case VS_EMPTY: *answer = tor_strdup("none recommended"); break;
  1908. case VS_UNKNOWN: *answer = tor_strdup("unknown"); break;
  1909. default: tor_fragile_assert();
  1910. }
  1911. } else if (!strcmp(question, "status/version/num-versioning") ||
  1912. !strcmp(question, "status/version/num-concurring")) {
  1913. tor_asprintf(answer, "%d", get_n_authorities(V3_DIRINFO));
  1914. log_warn(LD_GENERAL, "%s is deprecated; it no longer gives useful "
  1915. "information", question);
  1916. }
  1917. } else if (!strcmp(question, "status/clients-seen")) {
  1918. char *bridge_stats = geoip_get_bridge_stats_controller(time(NULL));
  1919. if (!bridge_stats) {
  1920. *errmsg = "No bridge-client stats available";
  1921. return -1;
  1922. }
  1923. *answer = bridge_stats;
  1924. } else if (!strcmp(question, "status/fresh-relay-descs")) {
  1925. if (!server_mode(get_options())) {
  1926. *errmsg = "Only relays have descriptors";
  1927. return -1;
  1928. }
  1929. routerinfo_t *r;
  1930. extrainfo_t *e;
  1931. if (router_build_fresh_descriptor(&r, &e) < 0) {
  1932. *errmsg = "Error generating descriptor";
  1933. return -1;
  1934. }
  1935. size_t size = r->cache_info.signed_descriptor_len + 1;
  1936. if (e) {
  1937. size += e->cache_info.signed_descriptor_len + 1;
  1938. }
  1939. tor_assert(r->cache_info.signed_descriptor_len);
  1940. char *descs = tor_malloc(size);
  1941. char *cp = descs;
  1942. memcpy(cp, signed_descriptor_get_body(&r->cache_info),
  1943. r->cache_info.signed_descriptor_len);
  1944. cp += r->cache_info.signed_descriptor_len - 1;
  1945. if (e) {
  1946. if (cp[0] == '\0') {
  1947. cp[0] = '\n';
  1948. } else if (cp[0] != '\n') {
  1949. cp[1] = '\n';
  1950. cp++;
  1951. }
  1952. memcpy(cp, signed_descriptor_get_body(&e->cache_info),
  1953. e->cache_info.signed_descriptor_len);
  1954. cp += e->cache_info.signed_descriptor_len - 1;
  1955. }
  1956. if (cp[0] == '\n') {
  1957. cp[0] = '\0';
  1958. } else if (cp[0] != '\0') {
  1959. cp[1] = '\0';
  1960. }
  1961. *answer = descs;
  1962. routerinfo_free(r);
  1963. extrainfo_free(e);
  1964. } else {
  1965. return 0;
  1966. }
  1967. }
  1968. return 0;
  1969. }
  1970. /** Callback function for GETINFO: on a given control connection, try to
  1971. * answer the question <b>q</b> and store the newly-allocated answer in
  1972. * *<b>a</b>. If an internal error occurs, return -1 and optionally set
  1973. * *<b>error_out</b> to point to an error message to be delivered to the
  1974. * controller. On success, _or if the key is not recognized_, return 0. Do not
  1975. * set <b>a</b> if the key is not recognized.
  1976. */
  1977. typedef int (*getinfo_helper_t)(control_connection_t *,
  1978. const char *q, char **a,
  1979. const char **error_out);
  1980. /** A single item for the GETINFO question-to-answer-function table. */
  1981. typedef struct getinfo_item_t {
  1982. const char *varname; /**< The value (or prefix) of the question. */
  1983. getinfo_helper_t fn; /**< The function that knows the answer: NULL if
  1984. * this entry is documentation-only. */
  1985. const char *desc; /**< Description of the variable. */
  1986. int is_prefix; /** Must varname match exactly, or must it be a prefix? */
  1987. } getinfo_item_t;
  1988. #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
  1989. #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
  1990. #define DOC(name, desc) { name, NULL, desc, 0 }
  1991. /** Table mapping questions accepted by GETINFO to the functions that know how
  1992. * to answer them. */
  1993. static const getinfo_item_t getinfo_items[] = {
  1994. ITEM("version", misc, "The current version of Tor."),
  1995. ITEM("bw-event-cache", misc, "Cached BW events for a short interval."),
  1996. ITEM("config-file", misc, "Current location of the \"torrc\" file."),
  1997. ITEM("config-defaults-file", misc, "Current location of the defaults file."),
  1998. ITEM("config-text", misc,
  1999. "Return the string that would be written by a saveconf command."),
  2000. ITEM("accounting/bytes", accounting,
  2001. "Number of bytes read/written so far in the accounting interval."),
  2002. ITEM("accounting/bytes-left", accounting,
  2003. "Number of bytes left to write/read so far in the accounting interval."),
  2004. ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
  2005. ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
  2006. ITEM("accounting/interval-start", accounting,
  2007. "Time when the accounting period starts."),
  2008. ITEM("accounting/interval-end", accounting,
  2009. "Time when the accounting period ends."),
  2010. ITEM("accounting/interval-wake", accounting,
  2011. "Time to wake up in this accounting period."),
  2012. ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
  2013. ITEM("entry-guards", entry_guards,
  2014. "Which nodes are we using as entry guards?"),
  2015. ITEM("fingerprint", misc, NULL),
  2016. PREFIX("config/", config, "Current configuration values."),
  2017. DOC("config/names",
  2018. "List of configuration options, types, and documentation."),
  2019. DOC("config/defaults",
  2020. "List of default values for configuration options. "
  2021. "See also config/names"),
  2022. ITEM("info/names", misc,
  2023. "List of GETINFO options, types, and documentation."),
  2024. ITEM("events/names", misc,
  2025. "Events that the controller can ask for with SETEVENTS."),
  2026. ITEM("signal/names", misc, "Signal names recognized by the SIGNAL command"),
  2027. ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
  2028. PREFIX("desc/id/", dir, "Router descriptors by ID."),
  2029. PREFIX("desc/name/", dir, "Router descriptors by nickname."),
  2030. ITEM("desc/all-recent", dir,
  2031. "All non-expired, non-superseded router descriptors."),
  2032. ITEM("desc/all-recent-extrainfo-hack", dir, NULL), /* Hack. */
  2033. PREFIX("md/id/", dir, "Microdescriptors by ID"),
  2034. PREFIX("md/name/", dir, "Microdescriptors by name"),
  2035. PREFIX("extra-info/digest/", dir, "Extra-info documents by digest."),
  2036. PREFIX("net/listeners/", listeners, "Bound addresses by type"),
  2037. ITEM("ns/all", networkstatus,
  2038. "Brief summary of router status (v2 directory format)"),
  2039. PREFIX("ns/id/", networkstatus,
  2040. "Brief summary of router status by ID (v2 directory format)."),
  2041. PREFIX("ns/name/", networkstatus,
  2042. "Brief summary of router status by nickname (v2 directory format)."),
  2043. PREFIX("ns/purpose/", networkstatus,
  2044. "Brief summary of router status by purpose (v2 directory format)."),
  2045. PREFIX("consensus/", networkstatus,
  2046. "Information about and from the ns consensus."),
  2047. ITEM("network-status", dir,
  2048. "Brief summary of router status (v1 directory format)"),
  2049. ITEM("circuit-status", events, "List of current circuits originating here."),
  2050. ITEM("stream-status", events,"List of current streams."),
  2051. ITEM("orconn-status", events, "A list of current OR connections."),
  2052. ITEM("dormant", misc,
  2053. "Is Tor dormant (not building circuits because it's idle)?"),
  2054. PREFIX("address-mappings/", events, NULL),
  2055. DOC("address-mappings/all", "Current address mappings."),
  2056. DOC("address-mappings/cache", "Current cached DNS replies."),
  2057. DOC("address-mappings/config",
  2058. "Current address mappings from configuration."),
  2059. DOC("address-mappings/control", "Current address mappings from controller."),
  2060. PREFIX("status/", events, NULL),
  2061. DOC("status/circuit-established",
  2062. "Whether we think client functionality is working."),
  2063. DOC("status/enough-dir-info",
  2064. "Whether we have enough up-to-date directory information to build "
  2065. "circuits."),
  2066. DOC("status/bootstrap-phase",
  2067. "The last bootstrap phase status event that Tor sent."),
  2068. DOC("status/clients-seen",
  2069. "Breakdown of client countries seen by a bridge."),
  2070. DOC("status/fresh-relay-descs",
  2071. "A fresh relay/ei descriptor pair for Tor's current state. Not stored."),
  2072. DOC("status/version/recommended", "List of currently recommended versions."),
  2073. DOC("status/version/current", "Status of the current version."),
  2074. DOC("status/version/num-versioning", "Number of versioning authorities."),
  2075. DOC("status/version/num-concurring",
  2076. "Number of versioning authorities agreeing on the status of the "
  2077. "current version"),
  2078. ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
  2079. ITEM("traffic/read", misc,"Bytes read since the process was started."),
  2080. ITEM("traffic/written", misc,
  2081. "Bytes written since the process was started."),
  2082. ITEM("process/pid", misc, "Process id belonging to the main tor process."),
  2083. ITEM("process/uid", misc, "User id running the tor process."),
  2084. ITEM("process/user", misc,
  2085. "Username under which the tor process is running."),
  2086. ITEM("process/descriptor-limit", misc, "File descriptor limit."),
  2087. ITEM("limits/max-mem-in-queues", misc, "Actual limit on memory in queues"),
  2088. ITEM("dir-usage", misc, "Breakdown of bytes transferred over DirPort."),
  2089. PREFIX("desc-annotations/id/", dir, "Router annotations by hexdigest."),
  2090. PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
  2091. PREFIX("dir/status/", dir,
  2092. "v2 networkstatus docs as retrieved from a DirPort."),
  2093. ITEM("dir/status-vote/current/consensus", dir,
  2094. "v3 Networkstatus consensus as retrieved from a DirPort."),
  2095. ITEM("exit-policy/default", policies,
  2096. "The default value appended to the configured exit policy."),
  2097. ITEM("exit-policy/full", policies, "The entire exit policy of onion router"),
  2098. ITEM("exit-policy/ipv4", policies, "IPv4 parts of exit policy"),
  2099. ITEM("exit-policy/ipv6", policies, "IPv6 parts of exit policy"),
  2100. PREFIX("ip-to-country/", geoip, "Perform a GEOIP lookup"),
  2101. { NULL, NULL, NULL, 0 }
  2102. };
  2103. /** Allocate and return a list of recognized GETINFO options. */
  2104. static char *
  2105. list_getinfo_options(void)
  2106. {
  2107. int i;
  2108. smartlist_t *lines = smartlist_new();
  2109. char *ans;
  2110. for (i = 0; getinfo_items[i].varname; ++i) {
  2111. if (!getinfo_items[i].desc)
  2112. continue;
  2113. smartlist_add_asprintf(lines, "%s%s -- %s\n",
  2114. getinfo_items[i].varname,
  2115. getinfo_items[i].is_prefix ? "*" : "",
  2116. getinfo_items[i].desc);
  2117. }
  2118. smartlist_sort_strings(lines);
  2119. ans = smartlist_join_strings(lines, "", 0, NULL);
  2120. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  2121. smartlist_free(lines);
  2122. return ans;
  2123. }
  2124. /** Lookup the 'getinfo' entry <b>question</b>, and return
  2125. * the answer in <b>*answer</b> (or NULL if key not recognized).
  2126. * Return 0 if success or unrecognized, or -1 if recognized but
  2127. * internal error. */
  2128. static int
  2129. handle_getinfo_helper(control_connection_t *control_conn,
  2130. const char *question, char **answer,
  2131. const char **err_out)
  2132. {
  2133. int i;
  2134. *answer = NULL; /* unrecognized key by default */
  2135. for (i = 0; getinfo_items[i].varname; ++i) {
  2136. int match;
  2137. if (getinfo_items[i].is_prefix)
  2138. match = !strcmpstart(question, getinfo_items[i].varname);
  2139. else
  2140. match = !strcmp(question, getinfo_items[i].varname);
  2141. if (match) {
  2142. tor_assert(getinfo_items[i].fn);
  2143. return getinfo_items[i].fn(control_conn, question, answer, err_out);
  2144. }
  2145. }
  2146. return 0; /* unrecognized */
  2147. }
  2148. /** Called when we receive a GETINFO command. Try to fetch all requested
  2149. * information, and reply with information or error message. */
  2150. static int
  2151. handle_control_getinfo(control_connection_t *conn, uint32_t len,
  2152. const char *body)
  2153. {
  2154. smartlist_t *questions = smartlist_new();
  2155. smartlist_t *answers = smartlist_new();
  2156. smartlist_t *unrecognized = smartlist_new();
  2157. char *msg = NULL, *ans = NULL;
  2158. int i;
  2159. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  2160. smartlist_split_string(questions, body, " ",
  2161. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2162. SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
  2163. const char *errmsg = NULL;
  2164. if (handle_getinfo_helper(conn, q, &ans, &errmsg) < 0) {
  2165. if (!errmsg)
  2166. errmsg = "Internal error";
  2167. connection_printf_to_buf(conn, "551 %s\r\n", errmsg);
  2168. goto done;
  2169. }
  2170. if (!ans) {
  2171. smartlist_add(unrecognized, (char*)q);
  2172. } else {
  2173. smartlist_add(answers, tor_strdup(q));
  2174. smartlist_add(answers, ans);
  2175. }
  2176. } SMARTLIST_FOREACH_END(q);
  2177. if (smartlist_len(unrecognized)) {
  2178. for (i=0; i < smartlist_len(unrecognized)-1; ++i)
  2179. connection_printf_to_buf(conn,
  2180. "552-Unrecognized key \"%s\"\r\n",
  2181. (char*)smartlist_get(unrecognized, i));
  2182. connection_printf_to_buf(conn,
  2183. "552 Unrecognized key \"%s\"\r\n",
  2184. (char*)smartlist_get(unrecognized, i));
  2185. goto done;
  2186. }
  2187. for (i = 0; i < smartlist_len(answers); i += 2) {
  2188. char *k = smartlist_get(answers, i);
  2189. char *v = smartlist_get(answers, i+1);
  2190. if (!strchr(v, '\n') && !strchr(v, '\r')) {
  2191. connection_printf_to_buf(conn, "250-%s=", k);
  2192. connection_write_str_to_buf(v, conn);
  2193. connection_write_str_to_buf("\r\n", conn);
  2194. } else {
  2195. char *esc = NULL;
  2196. size_t esc_len;
  2197. esc_len = write_escaped_data(v, strlen(v), &esc);
  2198. connection_printf_to_buf(conn, "250+%s=\r\n", k);
  2199. connection_write_to_buf(esc, esc_len, TO_CONN(conn));
  2200. tor_free(esc);
  2201. }
  2202. }
  2203. connection_write_str_to_buf("250 OK\r\n", conn);
  2204. done:
  2205. SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
  2206. smartlist_free(answers);
  2207. SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
  2208. smartlist_free(questions);
  2209. smartlist_free(unrecognized);
  2210. tor_free(msg);
  2211. return 0;
  2212. }
  2213. /** Given a string, convert it to a circuit purpose. */
  2214. static uint8_t
  2215. circuit_purpose_from_string(const char *string)
  2216. {
  2217. if (!strcasecmpstart(string, "purpose="))
  2218. string += strlen("purpose=");
  2219. if (!strcasecmp(string, "general"))
  2220. return CIRCUIT_PURPOSE_C_GENERAL;
  2221. else if (!strcasecmp(string, "controller"))
  2222. return CIRCUIT_PURPOSE_CONTROLLER;
  2223. else
  2224. return CIRCUIT_PURPOSE_UNKNOWN;
  2225. }
  2226. /** Return a newly allocated smartlist containing the arguments to the command
  2227. * waiting in <b>body</b>. If there are fewer than <b>min_args</b> arguments,
  2228. * or if <b>max_args</b> is nonnegative and there are more than
  2229. * <b>max_args</b> arguments, send a 512 error to the controller, using
  2230. * <b>command</b> as the command name in the error message. */
  2231. static smartlist_t *
  2232. getargs_helper(const char *command, control_connection_t *conn,
  2233. const char *body, int min_args, int max_args)
  2234. {
  2235. smartlist_t *args = smartlist_new();
  2236. smartlist_split_string(args, body, " ",
  2237. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2238. if (smartlist_len(args) < min_args) {
  2239. connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
  2240. goto err;
  2241. } else if (max_args >= 0 && smartlist_len(args) > max_args) {
  2242. connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
  2243. goto err;
  2244. }
  2245. return args;
  2246. err:
  2247. SMARTLIST_FOREACH(args, char *, s, tor_free(s));
  2248. smartlist_free(args);
  2249. return NULL;
  2250. }
  2251. /** Helper. Return the first element of <b>sl</b> at index <b>start_at</b> or
  2252. * higher that starts with <b>prefix</b>, case-insensitive. Return NULL if no
  2253. * such element exists. */
  2254. static const char *
  2255. find_element_starting_with(smartlist_t *sl, int start_at, const char *prefix)
  2256. {
  2257. int i;
  2258. for (i = start_at; i < smartlist_len(sl); ++i) {
  2259. const char *elt = smartlist_get(sl, i);
  2260. if (!strcasecmpstart(elt, prefix))
  2261. return elt;
  2262. }
  2263. return NULL;
  2264. }
  2265. /** Helper. Return true iff s is an argument that we should treat as a
  2266. * key-value pair. */
  2267. static int
  2268. is_keyval_pair(const char *s)
  2269. {
  2270. /* An argument is a key-value pair if it has an =, and it isn't of the form
  2271. * $fingeprint=name */
  2272. return strchr(s, '=') && s[0] != '$';
  2273. }
  2274. /** Called when we get an EXTENDCIRCUIT message. Try to extend the listed
  2275. * circuit, and report success or failure. */
  2276. static int
  2277. handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
  2278. const char *body)
  2279. {
  2280. smartlist_t *router_nicknames=NULL, *nodes=NULL;
  2281. origin_circuit_t *circ = NULL;
  2282. int zero_circ;
  2283. uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
  2284. smartlist_t *args;
  2285. (void) len;
  2286. router_nicknames = smartlist_new();
  2287. args = getargs_helper("EXTENDCIRCUIT", conn, body, 1, -1);
  2288. if (!args)
  2289. goto done;
  2290. zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
  2291. if (zero_circ) {
  2292. const char *purp = find_element_starting_with(args, 1, "PURPOSE=");
  2293. if (purp) {
  2294. intended_purpose = circuit_purpose_from_string(purp);
  2295. if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  2296. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  2297. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2298. smartlist_free(args);
  2299. goto done;
  2300. }
  2301. }
  2302. if ((smartlist_len(args) == 1) ||
  2303. (smartlist_len(args) >= 2 && is_keyval_pair(smartlist_get(args, 1)))) {
  2304. // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
  2305. circ = circuit_launch(intended_purpose, CIRCLAUNCH_NEED_CAPACITY);
  2306. if (!circ) {
  2307. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  2308. } else {
  2309. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  2310. (unsigned long)circ->global_identifier);
  2311. }
  2312. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2313. smartlist_free(args);
  2314. goto done;
  2315. }
  2316. // "EXTENDCIRCUIT 0 router1,router2" ||
  2317. // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
  2318. }
  2319. if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
  2320. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2321. (char*)smartlist_get(args, 0));
  2322. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2323. smartlist_free(args);
  2324. goto done;
  2325. }
  2326. if (smartlist_len(args) < 2) {
  2327. connection_printf_to_buf(conn,
  2328. "512 syntax error: not enough arguments.\r\n");
  2329. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2330. smartlist_free(args);
  2331. goto done;
  2332. }
  2333. smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
  2334. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2335. smartlist_free(args);
  2336. nodes = smartlist_new();
  2337. SMARTLIST_FOREACH_BEGIN(router_nicknames, const char *, n) {
  2338. const node_t *node = node_get_by_nickname(n, 1);
  2339. if (!node) {
  2340. connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
  2341. goto done;
  2342. }
  2343. if (!node_has_descriptor(node)) {
  2344. connection_printf_to_buf(conn, "552 No descriptor for \"%s\"\r\n", n);
  2345. goto done;
  2346. }
  2347. smartlist_add(nodes, (void*)node);
  2348. } SMARTLIST_FOREACH_END(n);
  2349. if (!smartlist_len(nodes)) {
  2350. connection_write_str_to_buf("512 No router names provided\r\n", conn);
  2351. goto done;
  2352. }
  2353. if (zero_circ) {
  2354. /* start a new circuit */
  2355. circ = origin_circuit_init(intended_purpose, 0);
  2356. }
  2357. /* now circ refers to something that is ready to be extended */
  2358. SMARTLIST_FOREACH(nodes, const node_t *, node,
  2359. {
  2360. extend_info_t *info = extend_info_from_node(node, 0);
  2361. tor_assert(info); /* True, since node_has_descriptor(node) == true */
  2362. circuit_append_new_exit(circ, info);
  2363. extend_info_free(info);
  2364. });
  2365. /* now that we've populated the cpath, start extending */
  2366. if (zero_circ) {
  2367. int err_reason = 0;
  2368. if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
  2369. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2370. connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
  2371. goto done;
  2372. }
  2373. } else {
  2374. if (circ->base_.state == CIRCUIT_STATE_OPEN) {
  2375. int err_reason = 0;
  2376. circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  2377. if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
  2378. log_info(LD_CONTROL,
  2379. "send_next_onion_skin failed; circuit marked for closing.");
  2380. circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
  2381. connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
  2382. goto done;
  2383. }
  2384. }
  2385. }
  2386. connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
  2387. (unsigned long)circ->global_identifier);
  2388. if (zero_circ) /* send a 'launched' event, for completeness */
  2389. control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
  2390. done:
  2391. SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
  2392. smartlist_free(router_nicknames);
  2393. smartlist_free(nodes);
  2394. return 0;
  2395. }
  2396. /** Called when we get a SETCIRCUITPURPOSE message. If we can find the
  2397. * circuit and it's a valid purpose, change it. */
  2398. static int
  2399. handle_control_setcircuitpurpose(control_connection_t *conn,
  2400. uint32_t len, const char *body)
  2401. {
  2402. origin_circuit_t *circ = NULL;
  2403. uint8_t new_purpose;
  2404. smartlist_t *args;
  2405. (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
  2406. args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
  2407. if (!args)
  2408. goto done;
  2409. if (!(circ = get_circ(smartlist_get(args,0)))) {
  2410. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2411. (char*)smartlist_get(args, 0));
  2412. goto done;
  2413. }
  2414. {
  2415. const char *purp = find_element_starting_with(args,1,"PURPOSE=");
  2416. if (!purp) {
  2417. connection_write_str_to_buf("552 No purpose given\r\n", conn);
  2418. goto done;
  2419. }
  2420. new_purpose = circuit_purpose_from_string(purp);
  2421. if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
  2422. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
  2423. goto done;
  2424. }
  2425. }
  2426. circuit_change_purpose(TO_CIRCUIT(circ), new_purpose);
  2427. connection_write_str_to_buf("250 OK\r\n", conn);
  2428. done:
  2429. if (args) {
  2430. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2431. smartlist_free(args);
  2432. }
  2433. return 0;
  2434. }
  2435. /** Called when we get an ATTACHSTREAM message. Try to attach the requested
  2436. * stream, and report success or failure. */
  2437. static int
  2438. handle_control_attachstream(control_connection_t *conn, uint32_t len,
  2439. const char *body)
  2440. {
  2441. entry_connection_t *ap_conn = NULL;
  2442. origin_circuit_t *circ = NULL;
  2443. int zero_circ;
  2444. smartlist_t *args;
  2445. crypt_path_t *cpath=NULL;
  2446. int hop=0, hop_line_ok=1;
  2447. (void) len;
  2448. args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
  2449. if (!args)
  2450. return 0;
  2451. zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
  2452. if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
  2453. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2454. (char*)smartlist_get(args, 0));
  2455. } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
  2456. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2457. (char*)smartlist_get(args, 1));
  2458. } else if (circ) {
  2459. const char *hopstring = find_element_starting_with(args,2,"HOP=");
  2460. if (hopstring) {
  2461. hopstring += strlen("HOP=");
  2462. hop = (int) tor_parse_ulong(hopstring, 10, 0, INT_MAX,
  2463. &hop_line_ok, NULL);
  2464. if (!hop_line_ok) { /* broken hop line */
  2465. connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
  2466. }
  2467. }
  2468. }
  2469. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2470. smartlist_free(args);
  2471. if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
  2472. return 0;
  2473. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT &&
  2474. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONNECT_WAIT &&
  2475. ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_RESOLVE_WAIT) {
  2476. connection_write_str_to_buf(
  2477. "555 Connection is not managed by controller.\r\n",
  2478. conn);
  2479. return 0;
  2480. }
  2481. /* Do we need to detach it first? */
  2482. if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT) {
  2483. edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
  2484. circuit_t *tmpcirc = circuit_get_by_edge_conn(edge_conn);
  2485. connection_edge_end(edge_conn, END_STREAM_REASON_TIMEOUT);
  2486. /* Un-mark it as ending, since we're going to reuse it. */
  2487. edge_conn->edge_has_sent_end = 0;
  2488. edge_conn->end_reason = 0;
  2489. if (tmpcirc)
  2490. circuit_detach_stream(tmpcirc, edge_conn);
  2491. TO_CONN(edge_conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
  2492. }
  2493. if (circ && (circ->base_.state != CIRCUIT_STATE_OPEN)) {
  2494. connection_write_str_to_buf(
  2495. "551 Can't attach stream to non-open origin circuit\r\n",
  2496. conn);
  2497. return 0;
  2498. }
  2499. /* Is this a single hop circuit? */
  2500. if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
  2501. const node_t *node = NULL;
  2502. char *exit_digest = NULL;
  2503. if (circ->build_state &&
  2504. circ->build_state->chosen_exit &&
  2505. !tor_digest_is_zero(circ->build_state->chosen_exit->identity_digest)) {
  2506. exit_digest = circ->build_state->chosen_exit->identity_digest;
  2507. node = node_get_by_id(exit_digest);
  2508. }
  2509. /* Do both the client and relay allow one-hop exit circuits? */
  2510. if (!node ||
  2511. !node_allows_single_hop_exits(node) ||
  2512. !get_options()->AllowSingleHopCircuits) {
  2513. connection_write_str_to_buf(
  2514. "551 Can't attach stream to this one-hop circuit.\r\n", conn);
  2515. return 0;
  2516. }
  2517. tor_assert(exit_digest);
  2518. ap_conn->chosen_exit_name = tor_strdup(hex_str(exit_digest, DIGEST_LEN));
  2519. }
  2520. if (circ && hop>0) {
  2521. /* find this hop in the circuit, and set cpath */
  2522. cpath = circuit_get_cpath_hop(circ, hop);
  2523. if (!cpath) {
  2524. connection_printf_to_buf(conn,
  2525. "551 Circuit doesn't have %d hops.\r\n", hop);
  2526. return 0;
  2527. }
  2528. }
  2529. if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
  2530. connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
  2531. return 0;
  2532. }
  2533. send_control_done(conn);
  2534. return 0;
  2535. }
  2536. /** Called when we get a POSTDESCRIPTOR message. Try to learn the provided
  2537. * descriptor, and report success or failure. */
  2538. static int
  2539. handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
  2540. const char *body)
  2541. {
  2542. char *desc;
  2543. const char *msg=NULL;
  2544. uint8_t purpose = ROUTER_PURPOSE_GENERAL;
  2545. int cache = 0; /* eventually, we may switch this to 1 */
  2546. char *cp = memchr(body, '\n', len);
  2547. smartlist_t *args = smartlist_new();
  2548. tor_assert(cp);
  2549. *cp++ = '\0';
  2550. smartlist_split_string(args, body, " ",
  2551. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2552. SMARTLIST_FOREACH_BEGIN(args, char *, option) {
  2553. if (!strcasecmpstart(option, "purpose=")) {
  2554. option += strlen("purpose=");
  2555. purpose = router_purpose_from_string(option);
  2556. if (purpose == ROUTER_PURPOSE_UNKNOWN) {
  2557. connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
  2558. option);
  2559. goto done;
  2560. }
  2561. } else if (!strcasecmpstart(option, "cache=")) {
  2562. option += strlen("cache=");
  2563. if (!strcasecmp(option, "no"))
  2564. cache = 0;
  2565. else if (!strcasecmp(option, "yes"))
  2566. cache = 1;
  2567. else {
  2568. connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
  2569. option);
  2570. goto done;
  2571. }
  2572. } else { /* unrecognized argument? */
  2573. connection_printf_to_buf(conn,
  2574. "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
  2575. goto done;
  2576. }
  2577. } SMARTLIST_FOREACH_END(option);
  2578. read_escaped_data(cp, len-(cp-body), &desc);
  2579. switch (router_load_single_router(desc, purpose, cache, &msg)) {
  2580. case -1:
  2581. if (!msg) msg = "Could not parse descriptor";
  2582. connection_printf_to_buf(conn, "554 %s\r\n", msg);
  2583. break;
  2584. case 0:
  2585. if (!msg) msg = "Descriptor not added";
  2586. connection_printf_to_buf(conn, "251 %s\r\n",msg);
  2587. break;
  2588. case 1:
  2589. send_control_done(conn);
  2590. break;
  2591. }
  2592. tor_free(desc);
  2593. done:
  2594. SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
  2595. smartlist_free(args);
  2596. return 0;
  2597. }
  2598. /** Called when we receive a REDIRECTSTERAM command. Try to change the target
  2599. * address of the named AP stream, and report success or failure. */
  2600. static int
  2601. handle_control_redirectstream(control_connection_t *conn, uint32_t len,
  2602. const char *body)
  2603. {
  2604. entry_connection_t *ap_conn = NULL;
  2605. char *new_addr = NULL;
  2606. uint16_t new_port = 0;
  2607. smartlist_t *args;
  2608. (void) len;
  2609. args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
  2610. if (!args)
  2611. return 0;
  2612. if (!(ap_conn = get_stream(smartlist_get(args, 0)))
  2613. || !ap_conn->socks_request) {
  2614. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2615. (char*)smartlist_get(args, 0));
  2616. } else {
  2617. int ok = 1;
  2618. if (smartlist_len(args) > 2) { /* they included a port too */
  2619. new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
  2620. 10, 1, 65535, &ok, NULL);
  2621. }
  2622. if (!ok) {
  2623. connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
  2624. (char*)smartlist_get(args, 2));
  2625. } else {
  2626. new_addr = tor_strdup(smartlist_get(args, 1));
  2627. }
  2628. }
  2629. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2630. smartlist_free(args);
  2631. if (!new_addr)
  2632. return 0;
  2633. strlcpy(ap_conn->socks_request->address, new_addr,
  2634. sizeof(ap_conn->socks_request->address));
  2635. if (new_port)
  2636. ap_conn->socks_request->port = new_port;
  2637. tor_free(new_addr);
  2638. send_control_done(conn);
  2639. return 0;
  2640. }
  2641. /** Called when we get a CLOSESTREAM command; try to close the named stream
  2642. * and report success or failure. */
  2643. static int
  2644. handle_control_closestream(control_connection_t *conn, uint32_t len,
  2645. const char *body)
  2646. {
  2647. entry_connection_t *ap_conn=NULL;
  2648. uint8_t reason=0;
  2649. smartlist_t *args;
  2650. int ok;
  2651. (void) len;
  2652. args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
  2653. if (!args)
  2654. return 0;
  2655. else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
  2656. connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
  2657. (char*)smartlist_get(args, 0));
  2658. else {
  2659. reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
  2660. &ok, NULL);
  2661. if (!ok) {
  2662. connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
  2663. (char*)smartlist_get(args, 1));
  2664. ap_conn = NULL;
  2665. }
  2666. }
  2667. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2668. smartlist_free(args);
  2669. if (!ap_conn)
  2670. return 0;
  2671. connection_mark_unattached_ap(ap_conn, reason);
  2672. send_control_done(conn);
  2673. return 0;
  2674. }
  2675. /** Called when we get a CLOSECIRCUIT command; try to close the named circuit
  2676. * and report success or failure. */
  2677. static int
  2678. handle_control_closecircuit(control_connection_t *conn, uint32_t len,
  2679. const char *body)
  2680. {
  2681. origin_circuit_t *circ = NULL;
  2682. int safe = 0;
  2683. smartlist_t *args;
  2684. (void) len;
  2685. args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
  2686. if (!args)
  2687. return 0;
  2688. if (!(circ=get_circ(smartlist_get(args, 0))))
  2689. connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
  2690. (char*)smartlist_get(args, 0));
  2691. else {
  2692. int i;
  2693. for (i=1; i < smartlist_len(args); ++i) {
  2694. if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
  2695. safe = 1;
  2696. else
  2697. log_info(LD_CONTROL, "Skipping unknown option %s",
  2698. (char*)smartlist_get(args,i));
  2699. }
  2700. }
  2701. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2702. smartlist_free(args);
  2703. if (!circ)
  2704. return 0;
  2705. if (!safe || !circ->p_streams) {
  2706. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
  2707. }
  2708. send_control_done(conn);
  2709. return 0;
  2710. }
  2711. /** Called when we get a RESOLVE command: start trying to resolve
  2712. * the listed addresses. */
  2713. static int
  2714. handle_control_resolve(control_connection_t *conn, uint32_t len,
  2715. const char *body)
  2716. {
  2717. smartlist_t *args, *failed;
  2718. int is_reverse = 0;
  2719. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2720. if (!(conn->event_mask & (((event_mask_t)1)<<EVENT_ADDRMAP))) {
  2721. log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
  2722. "isn't listening for ADDRMAP events. It probably won't see "
  2723. "the answer.");
  2724. }
  2725. args = smartlist_new();
  2726. smartlist_split_string(args, body, " ",
  2727. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2728. {
  2729. const char *modearg = find_element_starting_with(args, 0, "mode=");
  2730. if (modearg && !strcasecmp(modearg, "mode=reverse"))
  2731. is_reverse = 1;
  2732. }
  2733. failed = smartlist_new();
  2734. SMARTLIST_FOREACH(args, const char *, arg, {
  2735. if (!is_keyval_pair(arg)) {
  2736. if (dnsserv_launch_request(arg, is_reverse, conn)<0)
  2737. smartlist_add(failed, (char*)arg);
  2738. }
  2739. });
  2740. send_control_done(conn);
  2741. SMARTLIST_FOREACH(failed, const char *, arg, {
  2742. control_event_address_mapped(arg, arg, time(NULL),
  2743. "internal", 0);
  2744. });
  2745. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2746. smartlist_free(args);
  2747. smartlist_free(failed);
  2748. return 0;
  2749. }
  2750. /** Called when we get a PROTOCOLINFO command: send back a reply. */
  2751. static int
  2752. handle_control_protocolinfo(control_connection_t *conn, uint32_t len,
  2753. const char *body)
  2754. {
  2755. const char *bad_arg = NULL;
  2756. smartlist_t *args;
  2757. (void)len;
  2758. conn->have_sent_protocolinfo = 1;
  2759. args = smartlist_new();
  2760. smartlist_split_string(args, body, " ",
  2761. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2762. SMARTLIST_FOREACH(args, const char *, arg, {
  2763. int ok;
  2764. tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
  2765. if (!ok) {
  2766. bad_arg = arg;
  2767. break;
  2768. }
  2769. });
  2770. if (bad_arg) {
  2771. connection_printf_to_buf(conn, "513 No such version %s\r\n",
  2772. escaped(bad_arg));
  2773. /* Don't tolerate bad arguments when not authenticated. */
  2774. if (!STATE_IS_OPEN(TO_CONN(conn)->state))
  2775. connection_mark_for_close(TO_CONN(conn));
  2776. goto done;
  2777. } else {
  2778. const or_options_t *options = get_options();
  2779. int cookies = options->CookieAuthentication;
  2780. char *cfile = get_controller_cookie_file_name();
  2781. char *abs_cfile;
  2782. char *esc_cfile;
  2783. char *methods;
  2784. abs_cfile = make_path_absolute(cfile);
  2785. esc_cfile = esc_for_log(abs_cfile);
  2786. {
  2787. int passwd = (options->HashedControlPassword != NULL ||
  2788. options->HashedControlSessionPassword != NULL);
  2789. smartlist_t *mlist = smartlist_new();
  2790. if (cookies) {
  2791. smartlist_add(mlist, (char*)"COOKIE");
  2792. smartlist_add(mlist, (char*)"SAFECOOKIE");
  2793. }
  2794. if (passwd)
  2795. smartlist_add(mlist, (char*)"HASHEDPASSWORD");
  2796. if (!cookies && !passwd)
  2797. smartlist_add(mlist, (char*)"NULL");
  2798. methods = smartlist_join_strings(mlist, ",", 0, NULL);
  2799. smartlist_free(mlist);
  2800. }
  2801. connection_printf_to_buf(conn,
  2802. "250-PROTOCOLINFO 1\r\n"
  2803. "250-AUTH METHODS=%s%s%s\r\n"
  2804. "250-VERSION Tor=%s\r\n"
  2805. "250 OK\r\n",
  2806. methods,
  2807. cookies?" COOKIEFILE=":"",
  2808. cookies?esc_cfile:"",
  2809. escaped(VERSION));
  2810. tor_free(methods);
  2811. tor_free(cfile);
  2812. tor_free(abs_cfile);
  2813. tor_free(esc_cfile);
  2814. }
  2815. done:
  2816. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2817. smartlist_free(args);
  2818. return 0;
  2819. }
  2820. /** Called when we get an AUTHCHALLENGE command. */
  2821. static int
  2822. handle_control_authchallenge(control_connection_t *conn, uint32_t len,
  2823. const char *body)
  2824. {
  2825. const char *cp = body;
  2826. char *client_nonce;
  2827. size_t client_nonce_len;
  2828. char server_hash[DIGEST256_LEN];
  2829. char server_hash_encoded[HEX_DIGEST256_LEN+1];
  2830. char server_nonce[SAFECOOKIE_SERVER_NONCE_LEN];
  2831. char server_nonce_encoded[(2*SAFECOOKIE_SERVER_NONCE_LEN) + 1];
  2832. cp += strspn(cp, " \t\n\r");
  2833. if (!strcasecmpstart(cp, "SAFECOOKIE")) {
  2834. cp += strlen("SAFECOOKIE");
  2835. } else {
  2836. connection_write_str_to_buf("513 AUTHCHALLENGE only supports SAFECOOKIE "
  2837. "authentication\r\n", conn);
  2838. connection_mark_for_close(TO_CONN(conn));
  2839. return -1;
  2840. }
  2841. if (!authentication_cookie_is_set) {
  2842. connection_write_str_to_buf("515 Cookie authentication is disabled\r\n",
  2843. conn);
  2844. connection_mark_for_close(TO_CONN(conn));
  2845. return -1;
  2846. }
  2847. cp += strspn(cp, " \t\n\r");
  2848. if (*cp == '"') {
  2849. const char *newcp =
  2850. decode_escaped_string(cp, len - (cp - body),
  2851. &client_nonce, &client_nonce_len);
  2852. if (newcp == NULL) {
  2853. connection_write_str_to_buf("513 Invalid quoted client nonce\r\n",
  2854. conn);
  2855. connection_mark_for_close(TO_CONN(conn));
  2856. return -1;
  2857. }
  2858. cp = newcp;
  2859. } else {
  2860. size_t client_nonce_encoded_len = strspn(cp, "0123456789ABCDEFabcdef");
  2861. client_nonce_len = client_nonce_encoded_len / 2;
  2862. client_nonce = tor_malloc_zero(client_nonce_len);
  2863. if (base16_decode(client_nonce, client_nonce_len,
  2864. cp, client_nonce_encoded_len) < 0) {
  2865. connection_write_str_to_buf("513 Invalid base16 client nonce\r\n",
  2866. conn);
  2867. connection_mark_for_close(TO_CONN(conn));
  2868. tor_free(client_nonce);
  2869. return -1;
  2870. }
  2871. cp += client_nonce_encoded_len;
  2872. }
  2873. cp += strspn(cp, " \t\n\r");
  2874. if (*cp != '\0' ||
  2875. cp != body + len) {
  2876. connection_write_str_to_buf("513 Junk at end of AUTHCHALLENGE command\r\n",
  2877. conn);
  2878. connection_mark_for_close(TO_CONN(conn));
  2879. tor_free(client_nonce);
  2880. return -1;
  2881. }
  2882. const int fail = crypto_rand(server_nonce, SAFECOOKIE_SERVER_NONCE_LEN);
  2883. tor_assert(!fail);
  2884. /* Now compute and send the server-to-controller response, and the
  2885. * server's nonce. */
  2886. tor_assert(authentication_cookie != NULL);
  2887. {
  2888. size_t tmp_len = (AUTHENTICATION_COOKIE_LEN +
  2889. client_nonce_len +
  2890. SAFECOOKIE_SERVER_NONCE_LEN);
  2891. char *tmp = tor_malloc_zero(tmp_len);
  2892. char *client_hash = tor_malloc_zero(DIGEST256_LEN);
  2893. memcpy(tmp, authentication_cookie, AUTHENTICATION_COOKIE_LEN);
  2894. memcpy(tmp + AUTHENTICATION_COOKIE_LEN, client_nonce, client_nonce_len);
  2895. memcpy(tmp + AUTHENTICATION_COOKIE_LEN + client_nonce_len,
  2896. server_nonce, SAFECOOKIE_SERVER_NONCE_LEN);
  2897. crypto_hmac_sha256(server_hash,
  2898. SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT,
  2899. strlen(SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT),
  2900. tmp,
  2901. tmp_len);
  2902. crypto_hmac_sha256(client_hash,
  2903. SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT,
  2904. strlen(SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT),
  2905. tmp,
  2906. tmp_len);
  2907. conn->safecookie_client_hash = client_hash;
  2908. tor_free(tmp);
  2909. }
  2910. base16_encode(server_hash_encoded, sizeof(server_hash_encoded),
  2911. server_hash, sizeof(server_hash));
  2912. base16_encode(server_nonce_encoded, sizeof(server_nonce_encoded),
  2913. server_nonce, sizeof(server_nonce));
  2914. connection_printf_to_buf(conn,
  2915. "250 AUTHCHALLENGE SERVERHASH=%s "
  2916. "SERVERNONCE=%s\r\n",
  2917. server_hash_encoded,
  2918. server_nonce_encoded);
  2919. tor_free(client_nonce);
  2920. return 0;
  2921. }
  2922. /** Called when we get a USEFEATURE command: parse the feature list, and
  2923. * set up the control_connection's options properly. */
  2924. static int
  2925. handle_control_usefeature(control_connection_t *conn,
  2926. uint32_t len,
  2927. const char *body)
  2928. {
  2929. smartlist_t *args;
  2930. int bad = 0;
  2931. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2932. args = smartlist_new();
  2933. smartlist_split_string(args, body, " ",
  2934. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2935. SMARTLIST_FOREACH_BEGIN(args, const char *, arg) {
  2936. if (!strcasecmp(arg, "VERBOSE_NAMES"))
  2937. ;
  2938. else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
  2939. ;
  2940. else {
  2941. connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
  2942. arg);
  2943. bad = 1;
  2944. break;
  2945. }
  2946. } SMARTLIST_FOREACH_END(arg);
  2947. if (!bad) {
  2948. send_control_done(conn);
  2949. }
  2950. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2951. smartlist_free(args);
  2952. return 0;
  2953. }
  2954. /** Implementation for the DROPGUARDS command. */
  2955. static int
  2956. handle_control_dropguards(control_connection_t *conn,
  2957. uint32_t len,
  2958. const char *body)
  2959. {
  2960. smartlist_t *args;
  2961. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2962. args = smartlist_new();
  2963. smartlist_split_string(args, body, " ",
  2964. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2965. if (smartlist_len(args)) {
  2966. connection_printf_to_buf(conn, "512 Too many arguments to DROPGUARDS\r\n");
  2967. } else {
  2968. remove_all_entry_guards();
  2969. send_control_done(conn);
  2970. }
  2971. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  2972. smartlist_free(args);
  2973. return 0;
  2974. }
  2975. /** Implementation for the HSFETCH command. */
  2976. static int
  2977. handle_control_hsfetch(control_connection_t *conn, uint32_t len,
  2978. const char *body)
  2979. {
  2980. char digest[DIGEST_LEN], *hsaddress = NULL, *arg1 = NULL, *desc_id = NULL;
  2981. smartlist_t *args = NULL, *hsdirs = NULL;
  2982. (void) len; /* body is nul-terminated; it's safe to ignore the length */
  2983. static const char *v2_str = "v2-";
  2984. const size_t v2_str_len = strlen(v2_str);
  2985. /* Make sure we have at least one argument, the HSAddress. */
  2986. args = getargs_helper("HSFETCH", conn, body, 1, -1);
  2987. if (!args) {
  2988. goto done;
  2989. }
  2990. /* Extract the HS address that should NOT contain the .onion part. */
  2991. arg1 = smartlist_get(args, 0);
  2992. /* Remove the HS address from the argument list so we can safely iterate
  2993. * on all the rest to find optional argument(s). */
  2994. smartlist_del(args, 0);
  2995. /* Test if it's an HS address without the .onion part. */
  2996. if (strlen(arg1) == REND_SERVICE_ID_LEN_BASE32 &&
  2997. base32_decode(digest, sizeof(digest), arg1,
  2998. REND_SERVICE_ID_LEN_BASE32) == 0) {
  2999. hsaddress = arg1;
  3000. } else if (strstr(arg1, v2_str) &&
  3001. strlen(arg1 + v2_str_len) == REND_DESC_ID_V2_LEN_BASE32 &&
  3002. base32_decode(digest, sizeof(digest), arg1 + v2_str_len,
  3003. REND_DESC_ID_V2_LEN_BASE32) == 0) {
  3004. /* We have a well formed version 2 descriptor ID. */
  3005. desc_id = arg1 + v2_str_len;
  3006. } else {
  3007. connection_printf_to_buf(conn, "552 Unrecognized \"%s\"\r\n",
  3008. arg1);
  3009. goto done;
  3010. }
  3011. /* Stores routerstatus_t object for each specified server. */
  3012. hsdirs = smartlist_new();
  3013. /* Skip first argument because it's the HSAddress. */
  3014. SMARTLIST_FOREACH_BEGIN(args, char *, arg) {
  3015. const node_t *node;
  3016. static const char *opt_server = "SERVER=";
  3017. if (!strcasecmpstart(arg, opt_server)) {
  3018. const char *server;
  3019. memset(digest, 0, sizeof(digest));
  3020. server = arg + strlen(opt_server);
  3021. /* Is the server fingerprint valid?. */
  3022. if (!string_is_hex(server) || strlen(server) != HEX_DIGEST_LEN ||
  3023. base16_decode(digest, sizeof(digest), server, HEX_DIGEST_LEN)) {
  3024. connection_printf_to_buf(conn, "552 Invalid fingerprint \"%s\"\r\n",
  3025. server);
  3026. goto done;
  3027. }
  3028. node = node_get_by_id(digest);
  3029. if (!node) {
  3030. connection_printf_to_buf(conn, "552 Server \"%s\" not found\r\n",
  3031. server);
  3032. goto done;
  3033. }
  3034. /* Valid server, add it to our local list. */
  3035. smartlist_add(hsdirs, node->rs);
  3036. } else {
  3037. connection_printf_to_buf(conn, "552 Unexpected argument \"%s\"\r\n",
  3038. arg);
  3039. goto done;
  3040. }
  3041. } SMARTLIST_FOREACH_END(arg);
  3042. /* XXX: Actually trigger the fetch(es). */
  3043. (void) hsaddress;
  3044. (void) desc_id;
  3045. (void) hsdirs;
  3046. /* All good, thanks and come again! */
  3047. send_control_done(conn);
  3048. done:
  3049. if (args) {
  3050. SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
  3051. smartlist_free(args);
  3052. }
  3053. tor_free(arg1);
  3054. smartlist_free(hsdirs);
  3055. return 0;
  3056. }
  3057. /** Called when <b>conn</b> has no more bytes left on its outbuf. */
  3058. int
  3059. connection_control_finished_flushing(control_connection_t *conn)
  3060. {
  3061. tor_assert(conn);
  3062. return 0;
  3063. }
  3064. /** Called when <b>conn</b> has gotten its socket closed. */
  3065. int
  3066. connection_control_reached_eof(control_connection_t *conn)
  3067. {
  3068. tor_assert(conn);
  3069. log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
  3070. connection_mark_for_close(TO_CONN(conn));
  3071. return 0;
  3072. }
  3073. static void lost_owning_controller(const char *owner_type,
  3074. const char *loss_manner)
  3075. ATTR_NORETURN;
  3076. /** Shut down this Tor instance in the same way that SIGINT would, but
  3077. * with a log message appropriate for the loss of an owning controller. */
  3078. static void
  3079. lost_owning_controller(const char *owner_type, const char *loss_manner)
  3080. {
  3081. log_notice(LD_CONTROL, "Owning controller %s has %s -- exiting now.",
  3082. owner_type, loss_manner);
  3083. /* XXXX Perhaps this chunk of code should be a separate function,
  3084. * called here and by process_signal(SIGINT). */
  3085. tor_cleanup();
  3086. exit(0);
  3087. }
  3088. /** Called when <b>conn</b> is being freed. */
  3089. void
  3090. connection_control_closed(control_connection_t *conn)
  3091. {
  3092. tor_assert(conn);
  3093. conn->event_mask = 0;
  3094. control_update_global_event_mask();
  3095. if (conn->is_owning_control_connection) {
  3096. lost_owning_controller("connection", "closed");
  3097. }
  3098. }
  3099. /** Return true iff <b>cmd</b> is allowable (or at least forgivable) at this
  3100. * stage of the protocol. */
  3101. static int
  3102. is_valid_initial_command(control_connection_t *conn, const char *cmd)
  3103. {
  3104. if (conn->base_.state == CONTROL_CONN_STATE_OPEN)
  3105. return 1;
  3106. if (!strcasecmp(cmd, "PROTOCOLINFO"))
  3107. return (!conn->have_sent_protocolinfo &&
  3108. conn->safecookie_client_hash == NULL);
  3109. if (!strcasecmp(cmd, "AUTHCHALLENGE"))
  3110. return (conn->safecookie_client_hash == NULL);
  3111. if (!strcasecmp(cmd, "AUTHENTICATE") ||
  3112. !strcasecmp(cmd, "QUIT"))
  3113. return 1;
  3114. return 0;
  3115. }
  3116. /** Do not accept any control command of more than 1MB in length. Anything
  3117. * that needs to be anywhere near this long probably means that one of our
  3118. * interfaces is broken. */
  3119. #define MAX_COMMAND_LINE_LENGTH (1024*1024)
  3120. /** Wrapper around peek_(evbuffer|buf)_has_control0 command: presents the same
  3121. * interface as those underlying functions, but takes a connection_t intead of
  3122. * an evbuffer or a buf_t.
  3123. */
  3124. static int
  3125. peek_connection_has_control0_command(connection_t *conn)
  3126. {
  3127. IF_HAS_BUFFEREVENT(conn, {
  3128. struct evbuffer *input = bufferevent_get_input(conn->bufev);
  3129. return peek_evbuffer_has_control0_command(input);
  3130. }) ELSE_IF_NO_BUFFEREVENT {
  3131. return peek_buf_has_control0_command(conn->inbuf);
  3132. }
  3133. }
  3134. /** Called when data has arrived on a v1 control connection: Try to fetch
  3135. * commands from conn->inbuf, and execute them.
  3136. */
  3137. int
  3138. connection_control_process_inbuf(control_connection_t *conn)
  3139. {
  3140. size_t data_len;
  3141. uint32_t cmd_data_len;
  3142. int cmd_len;
  3143. char *args;
  3144. tor_assert(conn);
  3145. tor_assert(conn->base_.state == CONTROL_CONN_STATE_OPEN ||
  3146. conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH);
  3147. if (!conn->incoming_cmd) {
  3148. conn->incoming_cmd = tor_malloc(1024);
  3149. conn->incoming_cmd_len = 1024;
  3150. conn->incoming_cmd_cur_len = 0;
  3151. }
  3152. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  3153. peek_connection_has_control0_command(TO_CONN(conn))) {
  3154. /* Detect v0 commands and send a "no more v0" message. */
  3155. size_t body_len;
  3156. char buf[128];
  3157. set_uint16(buf+2, htons(0x0000)); /* type == error */
  3158. set_uint16(buf+4, htons(0x0001)); /* code == internal error */
  3159. strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
  3160. "and later; upgrade your controller.",
  3161. sizeof(buf)-6);
  3162. body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
  3163. set_uint16(buf+0, htons(body_len));
  3164. connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
  3165. connection_mark_and_flush(TO_CONN(conn));
  3166. return 0;
  3167. }
  3168. again:
  3169. while (1) {
  3170. size_t last_idx;
  3171. int r;
  3172. /* First, fetch a line. */
  3173. do {
  3174. data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
  3175. r = connection_fetch_from_buf_line(TO_CONN(conn),
  3176. conn->incoming_cmd+conn->incoming_cmd_cur_len,
  3177. &data_len);
  3178. if (r == 0)
  3179. /* Line not all here yet. Wait. */
  3180. return 0;
  3181. else if (r == -1) {
  3182. if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
  3183. connection_write_str_to_buf("500 Line too long.\r\n", conn);
  3184. connection_stop_reading(TO_CONN(conn));
  3185. connection_mark_and_flush(TO_CONN(conn));
  3186. }
  3187. while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
  3188. conn->incoming_cmd_len *= 2;
  3189. conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
  3190. conn->incoming_cmd_len);
  3191. }
  3192. } while (r != 1);
  3193. tor_assert(data_len);
  3194. last_idx = conn->incoming_cmd_cur_len;
  3195. conn->incoming_cmd_cur_len += (int)data_len;
  3196. /* We have appended a line to incoming_cmd. Is the command done? */
  3197. if (last_idx == 0 && *conn->incoming_cmd != '+')
  3198. /* One line command, didn't start with '+'. */
  3199. break;
  3200. /* XXXX this code duplication is kind of dumb. */
  3201. if (last_idx+3 == conn->incoming_cmd_cur_len &&
  3202. tor_memeq(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
  3203. /* Just appended ".\r\n"; we're done. Remove it. */
  3204. conn->incoming_cmd[last_idx] = '\0';
  3205. conn->incoming_cmd_cur_len -= 3;
  3206. break;
  3207. } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
  3208. tor_memeq(conn->incoming_cmd + last_idx, ".\n", 2)) {
  3209. /* Just appended ".\n"; we're done. Remove it. */
  3210. conn->incoming_cmd[last_idx] = '\0';
  3211. conn->incoming_cmd_cur_len -= 2;
  3212. break;
  3213. }
  3214. /* Otherwise, read another line. */
  3215. }
  3216. data_len = conn->incoming_cmd_cur_len;
  3217. /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
  3218. * recognize it.
  3219. */
  3220. cmd_len = 0;
  3221. while ((size_t)cmd_len < data_len
  3222. && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
  3223. ++cmd_len;
  3224. conn->incoming_cmd[cmd_len]='\0';
  3225. args = conn->incoming_cmd+cmd_len+1;
  3226. tor_assert(data_len>(size_t)cmd_len);
  3227. data_len -= (cmd_len+1); /* skip the command and NUL we added after it */
  3228. while (TOR_ISSPACE(*args)) {
  3229. ++args;
  3230. --data_len;
  3231. }
  3232. /* If the connection is already closing, ignore further commands */
  3233. if (TO_CONN(conn)->marked_for_close) {
  3234. return 0;
  3235. }
  3236. /* Otherwise, Quit is always valid. */
  3237. if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
  3238. connection_write_str_to_buf("250 closing connection\r\n", conn);
  3239. connection_mark_and_flush(TO_CONN(conn));
  3240. return 0;
  3241. }
  3242. if (conn->base_.state == CONTROL_CONN_STATE_NEEDAUTH &&
  3243. !is_valid_initial_command(conn, conn->incoming_cmd)) {
  3244. connection_write_str_to_buf("514 Authentication required.\r\n", conn);
  3245. connection_mark_for_close(TO_CONN(conn));
  3246. return 0;
  3247. }
  3248. if (data_len >= UINT32_MAX) {
  3249. connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn);
  3250. connection_mark_for_close(TO_CONN(conn));
  3251. return 0;
  3252. }
  3253. /* XXXX Why is this not implemented as a table like the GETINFO
  3254. * items are? Even handling the plus signs at the beginnings of
  3255. * commands wouldn't be very hard with proper macros. */
  3256. cmd_data_len = (uint32_t)data_len;
  3257. if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
  3258. if (handle_control_setconf(conn, cmd_data_len, args))
  3259. return -1;
  3260. } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
  3261. if (handle_control_resetconf(conn, cmd_data_len, args))
  3262. return -1;
  3263. } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
  3264. if (handle_control_getconf(conn, cmd_data_len, args))
  3265. return -1;
  3266. } else if (!strcasecmp(conn->incoming_cmd, "+LOADCONF")) {
  3267. if (handle_control_loadconf(conn, cmd_data_len, args))
  3268. return -1;
  3269. } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
  3270. if (handle_control_setevents(conn, cmd_data_len, args))
  3271. return -1;
  3272. } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
  3273. if (handle_control_authenticate(conn, cmd_data_len, args))
  3274. return -1;
  3275. } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
  3276. if (handle_control_saveconf(conn, cmd_data_len, args))
  3277. return -1;
  3278. } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
  3279. if (handle_control_signal(conn, cmd_data_len, args))
  3280. return -1;
  3281. } else if (!strcasecmp(conn->incoming_cmd, "TAKEOWNERSHIP")) {
  3282. if (handle_control_takeownership(conn, cmd_data_len, args))
  3283. return -1;
  3284. } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
  3285. if (handle_control_mapaddress(conn, cmd_data_len, args))
  3286. return -1;
  3287. } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
  3288. if (handle_control_getinfo(conn, cmd_data_len, args))
  3289. return -1;
  3290. } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
  3291. if (handle_control_extendcircuit(conn, cmd_data_len, args))
  3292. return -1;
  3293. } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
  3294. if (handle_control_setcircuitpurpose(conn, cmd_data_len, args))
  3295. return -1;
  3296. } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
  3297. connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
  3298. } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
  3299. if (handle_control_attachstream(conn, cmd_data_len, args))
  3300. return -1;
  3301. } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
  3302. if (handle_control_postdescriptor(conn, cmd_data_len, args))
  3303. return -1;
  3304. } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
  3305. if (handle_control_redirectstream(conn, cmd_data_len, args))
  3306. return -1;
  3307. } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
  3308. if (handle_control_closestream(conn, cmd_data_len, args))
  3309. return -1;
  3310. } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
  3311. if (handle_control_closecircuit(conn, cmd_data_len, args))
  3312. return -1;
  3313. } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
  3314. if (handle_control_usefeature(conn, cmd_data_len, args))
  3315. return -1;
  3316. } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
  3317. if (handle_control_resolve(conn, cmd_data_len, args))
  3318. return -1;
  3319. } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
  3320. if (handle_control_protocolinfo(conn, cmd_data_len, args))
  3321. return -1;
  3322. } else if (!strcasecmp(conn->incoming_cmd, "AUTHCHALLENGE")) {
  3323. if (handle_control_authchallenge(conn, cmd_data_len, args))
  3324. return -1;
  3325. } else if (!strcasecmp(conn->incoming_cmd, "DROPGUARDS")) {
  3326. if (handle_control_dropguards(conn, cmd_data_len, args))
  3327. return -1;
  3328. } else if (!strcasecmp(conn->incoming_cmd, "HSFETCH")) {
  3329. if (handle_control_hsfetch(conn, cmd_data_len, args))
  3330. return -1;
  3331. } else {
  3332. connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
  3333. conn->incoming_cmd);
  3334. }
  3335. conn->incoming_cmd_cur_len = 0;
  3336. goto again;
  3337. }
  3338. /** Something major has happened to circuit <b>circ</b>: tell any
  3339. * interested control connections. */
  3340. int
  3341. control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
  3342. int reason_code)
  3343. {
  3344. const char *status;
  3345. char reasons[64] = "";
  3346. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  3347. return 0;
  3348. tor_assert(circ);
  3349. switch (tp)
  3350. {
  3351. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  3352. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  3353. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  3354. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  3355. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  3356. default:
  3357. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  3358. tor_fragile_assert();
  3359. return 0;
  3360. }
  3361. if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
  3362. const char *reason_str = circuit_end_reason_to_control_string(reason_code);
  3363. char unk_reason_buf[16];
  3364. if (!reason_str) {
  3365. tor_snprintf(unk_reason_buf, 16, "UNKNOWN_%d", reason_code);
  3366. reason_str = unk_reason_buf;
  3367. }
  3368. if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
  3369. tor_snprintf(reasons, sizeof(reasons),
  3370. " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
  3371. } else {
  3372. tor_snprintf(reasons, sizeof(reasons),
  3373. " REASON=%s", reason_str);
  3374. }
  3375. }
  3376. {
  3377. char *circdesc = circuit_describe_status_for_controller(circ);
  3378. const char *sp = strlen(circdesc) ? " " : "";
  3379. send_control_event(EVENT_CIRCUIT_STATUS, ALL_FORMATS,
  3380. "650 CIRC %lu %s%s%s%s\r\n",
  3381. (unsigned long)circ->global_identifier,
  3382. status, sp,
  3383. circdesc,
  3384. reasons);
  3385. tor_free(circdesc);
  3386. }
  3387. return 0;
  3388. }
  3389. /** Something minor has happened to circuit <b>circ</b>: tell any
  3390. * interested control connections. */
  3391. static int
  3392. control_event_circuit_status_minor(origin_circuit_t *circ,
  3393. circuit_status_minor_event_t e,
  3394. int purpose, const struct timeval *tv)
  3395. {
  3396. const char *event_desc;
  3397. char event_tail[160] = "";
  3398. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR))
  3399. return 0;
  3400. tor_assert(circ);
  3401. switch (e)
  3402. {
  3403. case CIRC_MINOR_EVENT_PURPOSE_CHANGED:
  3404. event_desc = "PURPOSE_CHANGED";
  3405. {
  3406. /* event_tail can currently be up to 68 chars long */
  3407. const char *hs_state_str =
  3408. circuit_purpose_to_controller_hs_state_string(purpose);
  3409. tor_snprintf(event_tail, sizeof(event_tail),
  3410. " OLD_PURPOSE=%s%s%s",
  3411. circuit_purpose_to_controller_string(purpose),
  3412. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  3413. (hs_state_str != NULL) ? hs_state_str : "");
  3414. }
  3415. break;
  3416. case CIRC_MINOR_EVENT_CANNIBALIZED:
  3417. event_desc = "CANNIBALIZED";
  3418. {
  3419. /* event_tail can currently be up to 130 chars long */
  3420. const char *hs_state_str =
  3421. circuit_purpose_to_controller_hs_state_string(purpose);
  3422. const struct timeval *old_timestamp_began = tv;
  3423. char tbuf[ISO_TIME_USEC_LEN+1];
  3424. format_iso_time_nospace_usec(tbuf, old_timestamp_began);
  3425. tor_snprintf(event_tail, sizeof(event_tail),
  3426. " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
  3427. circuit_purpose_to_controller_string(purpose),
  3428. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  3429. (hs_state_str != NULL) ? hs_state_str : "",
  3430. tbuf);
  3431. }
  3432. break;
  3433. default:
  3434. log_warn(LD_BUG, "Unrecognized status code %d", (int)e);
  3435. tor_fragile_assert();
  3436. return 0;
  3437. }
  3438. {
  3439. char *circdesc = circuit_describe_status_for_controller(circ);
  3440. const char *sp = strlen(circdesc) ? " " : "";
  3441. send_control_event(EVENT_CIRCUIT_STATUS_MINOR, ALL_FORMATS,
  3442. "650 CIRC_MINOR %lu %s%s%s%s\r\n",
  3443. (unsigned long)circ->global_identifier,
  3444. event_desc, sp,
  3445. circdesc,
  3446. event_tail);
  3447. tor_free(circdesc);
  3448. }
  3449. return 0;
  3450. }
  3451. /**
  3452. * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
  3453. * interested controllers.
  3454. */
  3455. int
  3456. control_event_circuit_purpose_changed(origin_circuit_t *circ,
  3457. int old_purpose)
  3458. {
  3459. return control_event_circuit_status_minor(circ,
  3460. CIRC_MINOR_EVENT_PURPOSE_CHANGED,
  3461. old_purpose,
  3462. NULL);
  3463. }
  3464. /**
  3465. * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
  3466. * created-time from <b>old_tv_created</b>: tell any interested controllers.
  3467. */
  3468. int
  3469. control_event_circuit_cannibalized(origin_circuit_t *circ,
  3470. int old_purpose,
  3471. const struct timeval *old_tv_created)
  3472. {
  3473. return control_event_circuit_status_minor(circ,
  3474. CIRC_MINOR_EVENT_CANNIBALIZED,
  3475. old_purpose,
  3476. old_tv_created);
  3477. }
  3478. /** Given an AP connection <b>conn</b> and a <b>len</b>-character buffer
  3479. * <b>buf</b>, determine the address:port combination requested on
  3480. * <b>conn</b>, and write it to <b>buf</b>. Return 0 on success, -1 on
  3481. * failure. */
  3482. static int
  3483. write_stream_target_to_buf(entry_connection_t *conn, char *buf, size_t len)
  3484. {
  3485. char buf2[256];
  3486. if (conn->chosen_exit_name)
  3487. if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
  3488. return -1;
  3489. if (!conn->socks_request)
  3490. return -1;
  3491. if (tor_snprintf(buf, len, "%s%s%s:%d",
  3492. conn->socks_request->address,
  3493. conn->chosen_exit_name ? buf2 : "",
  3494. !conn->chosen_exit_name && connection_edge_is_rendezvous_stream(
  3495. ENTRY_TO_EDGE_CONN(conn)) ? ".onion" : "",
  3496. conn->socks_request->port)<0)
  3497. return -1;
  3498. return 0;
  3499. }
  3500. /** Something has happened to the stream associated with AP connection
  3501. * <b>conn</b>: tell any interested control connections. */
  3502. int
  3503. control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp,
  3504. int reason_code)
  3505. {
  3506. char reason_buf[64];
  3507. char addrport_buf[64];
  3508. const char *status;
  3509. circuit_t *circ;
  3510. origin_circuit_t *origin_circ = NULL;
  3511. char buf[256];
  3512. const char *purpose = "";
  3513. tor_assert(conn->socks_request);
  3514. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  3515. return 0;
  3516. if (tp == STREAM_EVENT_CLOSED &&
  3517. (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
  3518. return 0;
  3519. write_stream_target_to_buf(conn, buf, sizeof(buf));
  3520. reason_buf[0] = '\0';
  3521. switch (tp)
  3522. {
  3523. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  3524. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  3525. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  3526. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  3527. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  3528. case STREAM_EVENT_NEW: status = "NEW"; break;
  3529. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  3530. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  3531. case STREAM_EVENT_REMAP: status = "REMAP"; break;
  3532. default:
  3533. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  3534. return 0;
  3535. }
  3536. if (reason_code && (tp == STREAM_EVENT_FAILED ||
  3537. tp == STREAM_EVENT_CLOSED ||
  3538. tp == STREAM_EVENT_FAILED_RETRIABLE)) {
  3539. const char *reason_str = stream_end_reason_to_control_string(reason_code);
  3540. char *r = NULL;
  3541. if (!reason_str) {
  3542. tor_asprintf(&r, " UNKNOWN_%d", reason_code);
  3543. reason_str = r;
  3544. }
  3545. if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
  3546. tor_snprintf(reason_buf, sizeof(reason_buf),
  3547. " REASON=END REMOTE_REASON=%s", reason_str);
  3548. else
  3549. tor_snprintf(reason_buf, sizeof(reason_buf),
  3550. " REASON=%s", reason_str);
  3551. tor_free(r);
  3552. } else if (reason_code && tp == STREAM_EVENT_REMAP) {
  3553. switch (reason_code) {
  3554. case REMAP_STREAM_SOURCE_CACHE:
  3555. strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
  3556. break;
  3557. case REMAP_STREAM_SOURCE_EXIT:
  3558. strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
  3559. break;
  3560. default:
  3561. tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
  3562. reason_code);
  3563. /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
  3564. break;
  3565. }
  3566. }
  3567. if (tp == STREAM_EVENT_NEW || tp == STREAM_EVENT_NEW_RESOLVE) {
  3568. /*
  3569. * When the control conn is an AF_UNIX socket and we have no address,
  3570. * it gets set to "(Tor_internal)"; see dnsserv_launch_request() in
  3571. * dnsserv.c.
  3572. */
  3573. if (strcmp(ENTRY_TO_CONN(conn)->address, "(Tor_internal)") != 0) {
  3574. tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
  3575. ENTRY_TO_CONN(conn)->address, ENTRY_TO_CONN(conn)->port);
  3576. } else {
  3577. /*
  3578. * else leave it blank so control on AF_UNIX doesn't need to make
  3579. * something up.
  3580. */
  3581. addrport_buf[0] = '\0';
  3582. }
  3583. } else {
  3584. addrport_buf[0] = '\0';
  3585. }
  3586. if (tp == STREAM_EVENT_NEW_RESOLVE) {
  3587. purpose = " PURPOSE=DNS_REQUEST";
  3588. } else if (tp == STREAM_EVENT_NEW) {
  3589. if (conn->use_begindir) {
  3590. connection_t *linked = ENTRY_TO_CONN(conn)->linked_conn;
  3591. int linked_dir_purpose = -1;
  3592. if (linked && linked->type == CONN_TYPE_DIR)
  3593. linked_dir_purpose = linked->purpose;
  3594. if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
  3595. purpose = " PURPOSE=DIR_UPLOAD";
  3596. else
  3597. purpose = " PURPOSE=DIR_FETCH";
  3598. } else
  3599. purpose = " PURPOSE=USER";
  3600. }
  3601. circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
  3602. if (circ && CIRCUIT_IS_ORIGIN(circ))
  3603. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  3604. send_control_event(EVENT_STREAM_STATUS, ALL_FORMATS,
  3605. "650 STREAM "U64_FORMAT" %s %lu %s%s%s%s\r\n",
  3606. U64_PRINTF_ARG(ENTRY_TO_CONN(conn)->global_identifier),
  3607. status,
  3608. origin_circ?
  3609. (unsigned long)origin_circ->global_identifier : 0ul,
  3610. buf, reason_buf, addrport_buf, purpose);
  3611. /* XXX need to specify its intended exit, etc? */
  3612. return 0;
  3613. }
  3614. /** Figure out the best name for the target router of an OR connection
  3615. * <b>conn</b>, and write it into the <b>len</b>-character buffer
  3616. * <b>name</b>. */
  3617. static void
  3618. orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
  3619. {
  3620. const node_t *node = node_get_by_id(conn->identity_digest);
  3621. if (node) {
  3622. tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
  3623. node_get_verbose_nickname(node, name);
  3624. } else if (! tor_digest_is_zero(conn->identity_digest)) {
  3625. name[0] = '$';
  3626. base16_encode(name+1, len-1, conn->identity_digest,
  3627. DIGEST_LEN);
  3628. } else {
  3629. tor_snprintf(name, len, "%s:%d",
  3630. conn->base_.address, conn->base_.port);
  3631. }
  3632. }
  3633. /** Called when the status of an OR connection <b>conn</b> changes: tell any
  3634. * interested control connections. <b>tp</b> is the new status for the
  3635. * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
  3636. * may be the reason why.
  3637. */
  3638. int
  3639. control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
  3640. int reason)
  3641. {
  3642. int ncircs = 0;
  3643. const char *status;
  3644. char name[128];
  3645. char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
  3646. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  3647. return 0;
  3648. switch (tp)
  3649. {
  3650. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  3651. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  3652. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  3653. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  3654. case OR_CONN_EVENT_NEW: status = "NEW"; break;
  3655. default:
  3656. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  3657. return 0;
  3658. }
  3659. if (conn->chan) {
  3660. ncircs = circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn->chan));
  3661. } else {
  3662. ncircs = 0;
  3663. }
  3664. ncircs += connection_or_get_num_circuits(conn);
  3665. if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
  3666. tor_snprintf(ncircs_buf, sizeof(ncircs_buf), " NCIRCS=%d", ncircs);
  3667. }
  3668. orconn_target_get_name(name, sizeof(name), conn);
  3669. send_control_event(EVENT_OR_CONN_STATUS, ALL_FORMATS,
  3670. "650 ORCONN %s %s%s%s%s ID="U64_FORMAT"\r\n",
  3671. name, status,
  3672. reason ? " REASON=" : "",
  3673. orconn_end_reason_to_control_string(reason),
  3674. ncircs_buf,
  3675. U64_PRINTF_ARG(conn->base_.global_identifier));
  3676. return 0;
  3677. }
  3678. /**
  3679. * Print out STREAM_BW event for a single conn
  3680. */
  3681. int
  3682. control_event_stream_bandwidth(edge_connection_t *edge_conn)
  3683. {
  3684. circuit_t *circ;
  3685. origin_circuit_t *ocirc;
  3686. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  3687. if (!edge_conn->n_read && !edge_conn->n_written)
  3688. return 0;
  3689. send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
  3690. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  3691. U64_PRINTF_ARG(edge_conn->base_.global_identifier),
  3692. (unsigned long)edge_conn->n_read,
  3693. (unsigned long)edge_conn->n_written);
  3694. circ = circuit_get_by_edge_conn(edge_conn);
  3695. if (circ && CIRCUIT_IS_ORIGIN(circ)) {
  3696. ocirc = TO_ORIGIN_CIRCUIT(circ);
  3697. ocirc->n_read_circ_bw += edge_conn->n_read;
  3698. ocirc->n_written_circ_bw += edge_conn->n_written;
  3699. }
  3700. edge_conn->n_written = edge_conn->n_read = 0;
  3701. }
  3702. return 0;
  3703. }
  3704. /** A second or more has elapsed: tell any interested control
  3705. * connections how much bandwidth streams have used. */
  3706. int
  3707. control_event_stream_bandwidth_used(void)
  3708. {
  3709. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  3710. smartlist_t *conns = get_connection_array();
  3711. edge_connection_t *edge_conn;
  3712. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
  3713. {
  3714. if (conn->type != CONN_TYPE_AP)
  3715. continue;
  3716. edge_conn = TO_EDGE_CONN(conn);
  3717. if (!edge_conn->n_read && !edge_conn->n_written)
  3718. continue;
  3719. send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
  3720. "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
  3721. U64_PRINTF_ARG(edge_conn->base_.global_identifier),
  3722. (unsigned long)edge_conn->n_read,
  3723. (unsigned long)edge_conn->n_written);
  3724. edge_conn->n_written = edge_conn->n_read = 0;
  3725. }
  3726. SMARTLIST_FOREACH_END(conn);
  3727. }
  3728. return 0;
  3729. }
  3730. /** A second or more has elapsed: tell any interested control connections
  3731. * how much bandwidth origin circuits have used. */
  3732. int
  3733. control_event_circ_bandwidth_used(void)
  3734. {
  3735. origin_circuit_t *ocirc;
  3736. if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
  3737. return 0;
  3738. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  3739. if (!CIRCUIT_IS_ORIGIN(circ))
  3740. continue;
  3741. ocirc = TO_ORIGIN_CIRCUIT(circ);
  3742. if (!ocirc->n_read_circ_bw && !ocirc->n_written_circ_bw)
  3743. continue;
  3744. send_control_event(EVENT_CIRC_BANDWIDTH_USED, ALL_FORMATS,
  3745. "650 CIRC_BW ID=%d READ=%lu WRITTEN=%lu\r\n",
  3746. ocirc->global_identifier,
  3747. (unsigned long)ocirc->n_read_circ_bw,
  3748. (unsigned long)ocirc->n_written_circ_bw);
  3749. ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
  3750. }
  3751. SMARTLIST_FOREACH_END(circ);
  3752. return 0;
  3753. }
  3754. /** Print out CONN_BW event for a single OR/DIR/EXIT <b>conn</b> and reset
  3755. * bandwidth counters. */
  3756. int
  3757. control_event_conn_bandwidth(connection_t *conn)
  3758. {
  3759. const char *conn_type_str;
  3760. if (!get_options()->TestingEnableConnBwEvent ||
  3761. !EVENT_IS_INTERESTING(EVENT_CONN_BW))
  3762. return 0;
  3763. if (!conn->n_read_conn_bw && !conn->n_written_conn_bw)
  3764. return 0;
  3765. switch (conn->type) {
  3766. case CONN_TYPE_OR:
  3767. conn_type_str = "OR";
  3768. break;
  3769. case CONN_TYPE_DIR:
  3770. conn_type_str = "DIR";
  3771. break;
  3772. case CONN_TYPE_EXIT:
  3773. conn_type_str = "EXIT";
  3774. break;
  3775. default:
  3776. return 0;
  3777. }
  3778. send_control_event(EVENT_CONN_BW, ALL_FORMATS,
  3779. "650 CONN_BW ID="U64_FORMAT" TYPE=%s "
  3780. "READ=%lu WRITTEN=%lu\r\n",
  3781. U64_PRINTF_ARG(conn->global_identifier),
  3782. conn_type_str,
  3783. (unsigned long)conn->n_read_conn_bw,
  3784. (unsigned long)conn->n_written_conn_bw);
  3785. conn->n_written_conn_bw = conn->n_read_conn_bw = 0;
  3786. return 0;
  3787. }
  3788. /** A second or more has elapsed: tell any interested control
  3789. * connections how much bandwidth connections have used. */
  3790. int
  3791. control_event_conn_bandwidth_used(void)
  3792. {
  3793. if (get_options()->TestingEnableConnBwEvent &&
  3794. EVENT_IS_INTERESTING(EVENT_CONN_BW)) {
  3795. SMARTLIST_FOREACH(get_connection_array(), connection_t *, conn,
  3796. control_event_conn_bandwidth(conn));
  3797. }
  3798. return 0;
  3799. }
  3800. /** Helper: iterate over cell statistics of <b>circ</b> and sum up added
  3801. * cells, removed cells, and waiting times by cell command and direction.
  3802. * Store results in <b>cell_stats</b>. Free cell statistics of the
  3803. * circuit afterwards. */
  3804. void
  3805. sum_up_cell_stats_by_command(circuit_t *circ, cell_stats_t *cell_stats)
  3806. {
  3807. memset(cell_stats, 0, sizeof(cell_stats_t));
  3808. SMARTLIST_FOREACH_BEGIN(circ->testing_cell_stats,
  3809. testing_cell_stats_entry_t *, ent) {
  3810. tor_assert(ent->command <= CELL_COMMAND_MAX_);
  3811. if (!ent->removed && !ent->exitward) {
  3812. cell_stats->added_cells_appward[ent->command] += 1;
  3813. } else if (!ent->removed && ent->exitward) {
  3814. cell_stats->added_cells_exitward[ent->command] += 1;
  3815. } else if (!ent->exitward) {
  3816. cell_stats->removed_cells_appward[ent->command] += 1;
  3817. cell_stats->total_time_appward[ent->command] += ent->waiting_time * 10;
  3818. } else {
  3819. cell_stats->removed_cells_exitward[ent->command] += 1;
  3820. cell_stats->total_time_exitward[ent->command] += ent->waiting_time * 10;
  3821. }
  3822. tor_free(ent);
  3823. } SMARTLIST_FOREACH_END(ent);
  3824. smartlist_free(circ->testing_cell_stats);
  3825. circ->testing_cell_stats = NULL;
  3826. }
  3827. /** Helper: append a cell statistics string to <code>event_parts</code>,
  3828. * prefixed with <code>key</code>=. Statistics consist of comma-separated
  3829. * key:value pairs with lower-case command strings as keys and cell
  3830. * numbers or total waiting times as values. A key:value pair is included
  3831. * if the entry in <code>include_if_non_zero</code> is not zero, but with
  3832. * the (possibly zero) entry from <code>number_to_include</code>. Both
  3833. * arrays are expected to have a length of CELL_COMMAND_MAX_ + 1. If no
  3834. * entry in <code>include_if_non_zero</code> is positive, no string will
  3835. * be added to <code>event_parts</code>. */
  3836. void
  3837. append_cell_stats_by_command(smartlist_t *event_parts, const char *key,
  3838. const uint64_t *include_if_non_zero,
  3839. const uint64_t *number_to_include)
  3840. {
  3841. smartlist_t *key_value_strings = smartlist_new();
  3842. int i;
  3843. for (i = 0; i <= CELL_COMMAND_MAX_; i++) {
  3844. if (include_if_non_zero[i] > 0) {
  3845. smartlist_add_asprintf(key_value_strings, "%s:"U64_FORMAT,
  3846. cell_command_to_string(i),
  3847. U64_PRINTF_ARG(number_to_include[i]));
  3848. }
  3849. }
  3850. if (smartlist_len(key_value_strings) > 0) {
  3851. char *joined = smartlist_join_strings(key_value_strings, ",", 0, NULL);
  3852. smartlist_add_asprintf(event_parts, "%s=%s", key, joined);
  3853. SMARTLIST_FOREACH(key_value_strings, char *, cp, tor_free(cp));
  3854. tor_free(joined);
  3855. }
  3856. smartlist_free(key_value_strings);
  3857. }
  3858. /** Helper: format <b>cell_stats</b> for <b>circ</b> for inclusion in a
  3859. * CELL_STATS event and write result string to <b>event_string</b>. */
  3860. void
  3861. format_cell_stats(char **event_string, circuit_t *circ,
  3862. cell_stats_t *cell_stats)
  3863. {
  3864. smartlist_t *event_parts = smartlist_new();
  3865. if (CIRCUIT_IS_ORIGIN(circ)) {
  3866. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  3867. smartlist_add_asprintf(event_parts, "ID=%lu",
  3868. (unsigned long)ocirc->global_identifier);
  3869. } else if (TO_OR_CIRCUIT(circ)->p_chan) {
  3870. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  3871. smartlist_add_asprintf(event_parts, "InboundQueue=%lu",
  3872. (unsigned long)or_circ->p_circ_id);
  3873. smartlist_add_asprintf(event_parts, "InboundConn="U64_FORMAT,
  3874. U64_PRINTF_ARG(or_circ->p_chan->global_identifier));
  3875. append_cell_stats_by_command(event_parts, "InboundAdded",
  3876. cell_stats->added_cells_appward,
  3877. cell_stats->added_cells_appward);
  3878. append_cell_stats_by_command(event_parts, "InboundRemoved",
  3879. cell_stats->removed_cells_appward,
  3880. cell_stats->removed_cells_appward);
  3881. append_cell_stats_by_command(event_parts, "InboundTime",
  3882. cell_stats->removed_cells_appward,
  3883. cell_stats->total_time_appward);
  3884. }
  3885. if (circ->n_chan) {
  3886. smartlist_add_asprintf(event_parts, "OutboundQueue=%lu",
  3887. (unsigned long)circ->n_circ_id);
  3888. smartlist_add_asprintf(event_parts, "OutboundConn="U64_FORMAT,
  3889. U64_PRINTF_ARG(circ->n_chan->global_identifier));
  3890. append_cell_stats_by_command(event_parts, "OutboundAdded",
  3891. cell_stats->added_cells_exitward,
  3892. cell_stats->added_cells_exitward);
  3893. append_cell_stats_by_command(event_parts, "OutboundRemoved",
  3894. cell_stats->removed_cells_exitward,
  3895. cell_stats->removed_cells_exitward);
  3896. append_cell_stats_by_command(event_parts, "OutboundTime",
  3897. cell_stats->removed_cells_exitward,
  3898. cell_stats->total_time_exitward);
  3899. }
  3900. *event_string = smartlist_join_strings(event_parts, " ", 0, NULL);
  3901. SMARTLIST_FOREACH(event_parts, char *, cp, tor_free(cp));
  3902. smartlist_free(event_parts);
  3903. }
  3904. /** A second or more has elapsed: tell any interested control connection
  3905. * how many cells have been processed for a given circuit. */
  3906. int
  3907. control_event_circuit_cell_stats(void)
  3908. {
  3909. cell_stats_t *cell_stats;
  3910. char *event_string;
  3911. if (!get_options()->TestingEnableCellStatsEvent ||
  3912. !EVENT_IS_INTERESTING(EVENT_CELL_STATS))
  3913. return 0;
  3914. cell_stats = tor_malloc(sizeof(cell_stats_t));;
  3915. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  3916. if (!circ->testing_cell_stats)
  3917. continue;
  3918. sum_up_cell_stats_by_command(circ, cell_stats);
  3919. format_cell_stats(&event_string, circ, cell_stats);
  3920. send_control_event(EVENT_CELL_STATS, ALL_FORMATS,
  3921. "650 CELL_STATS %s\r\n", event_string);
  3922. tor_free(event_string);
  3923. }
  3924. SMARTLIST_FOREACH_END(circ);
  3925. tor_free(cell_stats);
  3926. return 0;
  3927. }
  3928. /** Tokens in <b>bucket</b> have been refilled: the read bucket was empty
  3929. * for <b>read_empty_time</b> millis, the write bucket was empty for
  3930. * <b>write_empty_time</b> millis, and buckets were last refilled
  3931. * <b>milliseconds_elapsed</b> millis ago. Only emit TB_EMPTY event if
  3932. * either read or write bucket have been empty before. */
  3933. int
  3934. control_event_tb_empty(const char *bucket, uint32_t read_empty_time,
  3935. uint32_t write_empty_time,
  3936. int milliseconds_elapsed)
  3937. {
  3938. if (get_options()->TestingEnableTbEmptyEvent &&
  3939. EVENT_IS_INTERESTING(EVENT_TB_EMPTY) &&
  3940. (read_empty_time > 0 || write_empty_time > 0)) {
  3941. send_control_event(EVENT_TB_EMPTY, ALL_FORMATS,
  3942. "650 TB_EMPTY %s READ=%d WRITTEN=%d "
  3943. "LAST=%d\r\n",
  3944. bucket, read_empty_time, write_empty_time,
  3945. milliseconds_elapsed);
  3946. }
  3947. return 0;
  3948. }
  3949. /* about 5 minutes worth. */
  3950. #define N_BW_EVENTS_TO_CACHE 300
  3951. /* Index into cached_bw_events to next write. */
  3952. static int next_measurement_idx = 0;
  3953. /* number of entries set in n_measurements */
  3954. static int n_measurements = 0;
  3955. static struct cached_bw_event_s {
  3956. uint32_t n_read;
  3957. uint32_t n_written;
  3958. } cached_bw_events[N_BW_EVENTS_TO_CACHE];
  3959. /** A second or more has elapsed: tell any interested control
  3960. * connections how much bandwidth we used. */
  3961. int
  3962. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  3963. {
  3964. cached_bw_events[next_measurement_idx].n_read = n_read;
  3965. cached_bw_events[next_measurement_idx].n_written = n_written;
  3966. if (++next_measurement_idx == N_BW_EVENTS_TO_CACHE)
  3967. next_measurement_idx = 0;
  3968. if (n_measurements < N_BW_EVENTS_TO_CACHE)
  3969. ++n_measurements;
  3970. if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
  3971. send_control_event(EVENT_BANDWIDTH_USED, ALL_FORMATS,
  3972. "650 BW %lu %lu\r\n",
  3973. (unsigned long)n_read,
  3974. (unsigned long)n_written);
  3975. }
  3976. return 0;
  3977. }
  3978. STATIC char *
  3979. get_bw_samples(void)
  3980. {
  3981. int i;
  3982. int idx = (next_measurement_idx + N_BW_EVENTS_TO_CACHE - n_measurements)
  3983. % N_BW_EVENTS_TO_CACHE;
  3984. tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
  3985. smartlist_t *elements = smartlist_new();
  3986. for (i = 0; i < n_measurements; ++i) {
  3987. tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
  3988. const struct cached_bw_event_s *bwe = &cached_bw_events[idx];
  3989. smartlist_add_asprintf(elements, "%u,%u",
  3990. (unsigned)bwe->n_read,
  3991. (unsigned)bwe->n_written);
  3992. idx = (idx + 1) % N_BW_EVENTS_TO_CACHE;
  3993. }
  3994. char *result = smartlist_join_strings(elements, " ", 0, NULL);
  3995. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  3996. smartlist_free(elements);
  3997. return result;
  3998. }
  3999. /** Called when we are sending a log message to the controllers: suspend
  4000. * sending further log messages to the controllers until we're done. Used by
  4001. * CONN_LOG_PROTECT. */
  4002. void
  4003. disable_control_logging(void)
  4004. {
  4005. ++disable_log_messages;
  4006. }
  4007. /** We're done sending a log message to the controllers: re-enable controller
  4008. * logging. Used by CONN_LOG_PROTECT. */
  4009. void
  4010. enable_control_logging(void)
  4011. {
  4012. if (--disable_log_messages < 0)
  4013. tor_assert(0);
  4014. }
  4015. /** We got a log message: tell any interested control connections. */
  4016. void
  4017. control_event_logmsg(int severity, uint32_t domain, const char *msg)
  4018. {
  4019. int event;
  4020. /* Don't even think of trying to add stuff to a buffer from a cpuworker
  4021. * thread. */
  4022. if (! in_main_thread())
  4023. return;
  4024. if (disable_log_messages)
  4025. return;
  4026. if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
  4027. severity <= LOG_NOTICE) {
  4028. char *esc = esc_for_log(msg);
  4029. ++disable_log_messages;
  4030. control_event_general_status(severity, "BUG REASON=%s", esc);
  4031. --disable_log_messages;
  4032. tor_free(esc);
  4033. }
  4034. event = log_severity_to_event(severity);
  4035. if (event >= 0 && EVENT_IS_INTERESTING(event)) {
  4036. char *b = NULL;
  4037. const char *s;
  4038. if (strchr(msg, '\n')) {
  4039. char *cp;
  4040. b = tor_strdup(msg);
  4041. for (cp = b; *cp; ++cp)
  4042. if (*cp == '\r' || *cp == '\n')
  4043. *cp = ' ';
  4044. }
  4045. switch (severity) {
  4046. case LOG_DEBUG: s = "DEBUG"; break;
  4047. case LOG_INFO: s = "INFO"; break;
  4048. case LOG_NOTICE: s = "NOTICE"; break;
  4049. case LOG_WARN: s = "WARN"; break;
  4050. case LOG_ERR: s = "ERR"; break;
  4051. default: s = "UnknownLogSeverity"; break;
  4052. }
  4053. ++disable_log_messages;
  4054. send_control_event(event, ALL_FORMATS, "650 %s %s\r\n", s, b?b:msg);
  4055. --disable_log_messages;
  4056. tor_free(b);
  4057. }
  4058. }
  4059. /** Called whenever we receive new router descriptors: tell any
  4060. * interested control connections. <b>routers</b> is a list of
  4061. * routerinfo_t's.
  4062. */
  4063. int
  4064. control_event_descriptors_changed(smartlist_t *routers)
  4065. {
  4066. char *msg;
  4067. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  4068. return 0;
  4069. {
  4070. smartlist_t *names = smartlist_new();
  4071. char *ids;
  4072. SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
  4073. char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  4074. router_get_verbose_nickname(b, ri);
  4075. smartlist_add(names, b);
  4076. });
  4077. ids = smartlist_join_strings(names, " ", 0, NULL);
  4078. tor_asprintf(&msg, "650 NEWDESC %s\r\n", ids);
  4079. send_control_event_string(EVENT_NEW_DESC, ALL_FORMATS, msg);
  4080. tor_free(ids);
  4081. tor_free(msg);
  4082. SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
  4083. smartlist_free(names);
  4084. }
  4085. return 0;
  4086. }
  4087. /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
  4088. * <b>expires</b> values less than 3 are special; see connection_edge.c. If
  4089. * <b>error</b> is non-NULL, it is an error code describing the failure
  4090. * mode of the mapping.
  4091. */
  4092. int
  4093. control_event_address_mapped(const char *from, const char *to, time_t expires,
  4094. const char *error, const int cached)
  4095. {
  4096. if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
  4097. return 0;
  4098. if (expires < 3 || expires == TIME_MAX)
  4099. send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
  4100. "650 ADDRMAP %s %s NEVER %s%s"
  4101. "CACHED=\"%s\"\r\n",
  4102. from, to, error?error:"", error?" ":"",
  4103. cached?"YES":"NO");
  4104. else {
  4105. char buf[ISO_TIME_LEN+1];
  4106. char buf2[ISO_TIME_LEN+1];
  4107. format_local_iso_time(buf,expires);
  4108. format_iso_time(buf2,expires);
  4109. send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
  4110. "650 ADDRMAP %s %s \"%s\""
  4111. " %s%sEXPIRES=\"%s\" CACHED=\"%s\"\r\n",
  4112. from, to, buf,
  4113. error?error:"", error?" ":"",
  4114. buf2, cached?"YES":"NO");
  4115. }
  4116. return 0;
  4117. }
  4118. /** The authoritative dirserver has received a new descriptor that
  4119. * has passed basic syntax checks and is properly self-signed.
  4120. *
  4121. * Notify any interested party of the new descriptor and what has
  4122. * been done with it, and also optionally give an explanation/reason. */
  4123. int
  4124. control_event_or_authdir_new_descriptor(const char *action,
  4125. const char *desc, size_t desclen,
  4126. const char *msg)
  4127. {
  4128. char firstline[1024];
  4129. char *buf;
  4130. size_t totallen;
  4131. char *esc = NULL;
  4132. size_t esclen;
  4133. if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
  4134. return 0;
  4135. tor_snprintf(firstline, sizeof(firstline),
  4136. "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
  4137. action,
  4138. msg ? msg : "");
  4139. /* Escape the server descriptor properly */
  4140. esclen = write_escaped_data(desc, desclen, &esc);
  4141. totallen = strlen(firstline) + esclen + 1;
  4142. buf = tor_malloc(totallen);
  4143. strlcpy(buf, firstline, totallen);
  4144. strlcpy(buf+strlen(firstline), esc, totallen);
  4145. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
  4146. buf);
  4147. send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
  4148. "650 OK\r\n");
  4149. tor_free(esc);
  4150. tor_free(buf);
  4151. return 0;
  4152. }
  4153. /** Helper function for NS-style events. Constructs and sends an event
  4154. * of type <b>event</b> with string <b>event_string</b> out of the set of
  4155. * networkstatuses <b>statuses</b>. Currently it is used for NS events
  4156. * and NEWCONSENSUS events. */
  4157. static int
  4158. control_event_networkstatus_changed_helper(smartlist_t *statuses,
  4159. uint16_t event,
  4160. const char *event_string)
  4161. {
  4162. smartlist_t *strs;
  4163. char *s, *esc = NULL;
  4164. if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
  4165. return 0;
  4166. strs = smartlist_new();
  4167. smartlist_add(strs, tor_strdup("650+"));
  4168. smartlist_add(strs, tor_strdup(event_string));
  4169. smartlist_add(strs, tor_strdup("\r\n"));
  4170. SMARTLIST_FOREACH(statuses, const routerstatus_t *, rs,
  4171. {
  4172. s = networkstatus_getinfo_helper_single(rs);
  4173. if (!s) continue;
  4174. smartlist_add(strs, s);
  4175. });
  4176. s = smartlist_join_strings(strs, "", 0, NULL);
  4177. write_escaped_data(s, strlen(s), &esc);
  4178. SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
  4179. smartlist_free(strs);
  4180. tor_free(s);
  4181. send_control_event_string(event, ALL_FORMATS, esc);
  4182. send_control_event_string(event, ALL_FORMATS,
  4183. "650 OK\r\n");
  4184. tor_free(esc);
  4185. return 0;
  4186. }
  4187. /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
  4188. * an NS event to any controller that cares. */
  4189. int
  4190. control_event_networkstatus_changed(smartlist_t *statuses)
  4191. {
  4192. return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
  4193. }
  4194. /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
  4195. * event consisting of an NS-style line for each relay in the consensus. */
  4196. int
  4197. control_event_newconsensus(const networkstatus_t *consensus)
  4198. {
  4199. if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
  4200. return 0;
  4201. return control_event_networkstatus_changed_helper(
  4202. consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
  4203. }
  4204. /** Called when we compute a new circuitbuildtimeout */
  4205. int
  4206. control_event_buildtimeout_set(buildtimeout_set_event_t type,
  4207. const char *args)
  4208. {
  4209. const char *type_string = NULL;
  4210. if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
  4211. return 0;
  4212. switch (type) {
  4213. case BUILDTIMEOUT_SET_EVENT_COMPUTED:
  4214. type_string = "COMPUTED";
  4215. break;
  4216. case BUILDTIMEOUT_SET_EVENT_RESET:
  4217. type_string = "RESET";
  4218. break;
  4219. case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
  4220. type_string = "SUSPENDED";
  4221. break;
  4222. case BUILDTIMEOUT_SET_EVENT_DISCARD:
  4223. type_string = "DISCARD";
  4224. break;
  4225. case BUILDTIMEOUT_SET_EVENT_RESUME:
  4226. type_string = "RESUME";
  4227. break;
  4228. default:
  4229. type_string = "UNKNOWN";
  4230. break;
  4231. }
  4232. send_control_event(EVENT_BUILDTIMEOUT_SET, ALL_FORMATS,
  4233. "650 BUILDTIMEOUT_SET %s %s\r\n",
  4234. type_string, args);
  4235. return 0;
  4236. }
  4237. /** Called when a signal has been processed from signal_callback */
  4238. int
  4239. control_event_signal(uintptr_t signal)
  4240. {
  4241. const char *signal_string = NULL;
  4242. if (!control_event_is_interesting(EVENT_SIGNAL))
  4243. return 0;
  4244. switch (signal) {
  4245. case SIGHUP:
  4246. signal_string = "RELOAD";
  4247. break;
  4248. case SIGUSR1:
  4249. signal_string = "DUMP";
  4250. break;
  4251. case SIGUSR2:
  4252. signal_string = "DEBUG";
  4253. break;
  4254. case SIGNEWNYM:
  4255. signal_string = "NEWNYM";
  4256. break;
  4257. case SIGCLEARDNSCACHE:
  4258. signal_string = "CLEARDNSCACHE";
  4259. break;
  4260. case SIGHEARTBEAT:
  4261. signal_string = "HEARTBEAT";
  4262. break;
  4263. default:
  4264. log_warn(LD_BUG, "Unrecognized signal %lu in control_event_signal",
  4265. (unsigned long)signal);
  4266. return -1;
  4267. }
  4268. send_control_event(EVENT_SIGNAL, ALL_FORMATS, "650 SIGNAL %s\r\n",
  4269. signal_string);
  4270. return 0;
  4271. }
  4272. /** Called when a single local_routerstatus_t has changed: Sends an NS event
  4273. * to any controller that cares. */
  4274. int
  4275. control_event_networkstatus_changed_single(const routerstatus_t *rs)
  4276. {
  4277. smartlist_t *statuses;
  4278. int r;
  4279. if (!EVENT_IS_INTERESTING(EVENT_NS))
  4280. return 0;
  4281. statuses = smartlist_new();
  4282. smartlist_add(statuses, (void*)rs);
  4283. r = control_event_networkstatus_changed(statuses);
  4284. smartlist_free(statuses);
  4285. return r;
  4286. }
  4287. /** Our own router descriptor has changed; tell any controllers that care.
  4288. */
  4289. int
  4290. control_event_my_descriptor_changed(void)
  4291. {
  4292. send_control_event(EVENT_DESCCHANGED, ALL_FORMATS, "650 DESCCHANGED\r\n");
  4293. return 0;
  4294. }
  4295. /** Helper: sends a status event where <b>type</b> is one of
  4296. * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
  4297. * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
  4298. * string corresponding to <b>args</b>. */
  4299. static int
  4300. control_event_status(int type, int severity, const char *format, va_list args)
  4301. {
  4302. char *user_buf = NULL;
  4303. char format_buf[160];
  4304. const char *status, *sev;
  4305. switch (type) {
  4306. case EVENT_STATUS_GENERAL:
  4307. status = "STATUS_GENERAL";
  4308. break;
  4309. case EVENT_STATUS_CLIENT:
  4310. status = "STATUS_CLIENT";
  4311. break;
  4312. case EVENT_STATUS_SERVER:
  4313. status = "STATUS_SERVER";
  4314. break;
  4315. default:
  4316. log_warn(LD_BUG, "Unrecognized status type %d", type);
  4317. return -1;
  4318. }
  4319. switch (severity) {
  4320. case LOG_NOTICE:
  4321. sev = "NOTICE";
  4322. break;
  4323. case LOG_WARN:
  4324. sev = "WARN";
  4325. break;
  4326. case LOG_ERR:
  4327. sev = "ERR";
  4328. break;
  4329. default:
  4330. log_warn(LD_BUG, "Unrecognized status severity %d", severity);
  4331. return -1;
  4332. }
  4333. if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s",
  4334. status, sev)<0) {
  4335. log_warn(LD_BUG, "Format string too long.");
  4336. return -1;
  4337. }
  4338. tor_vasprintf(&user_buf, format, args);
  4339. send_control_event(type, ALL_FORMATS, "%s %s\r\n", format_buf, user_buf);
  4340. tor_free(user_buf);
  4341. return 0;
  4342. }
  4343. /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
  4344. * by formatting the arguments using the printf-style <b>format</b>. */
  4345. int
  4346. control_event_general_status(int severity, const char *format, ...)
  4347. {
  4348. va_list ap;
  4349. int r;
  4350. if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL))
  4351. return 0;
  4352. va_start(ap, format);
  4353. r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
  4354. va_end(ap);
  4355. return r;
  4356. }
  4357. /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
  4358. * by formatting the arguments using the printf-style <b>format</b>. */
  4359. int
  4360. control_event_client_status(int severity, const char *format, ...)
  4361. {
  4362. va_list ap;
  4363. int r;
  4364. if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT))
  4365. return 0;
  4366. va_start(ap, format);
  4367. r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
  4368. va_end(ap);
  4369. return r;
  4370. }
  4371. /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
  4372. * by formatting the arguments using the printf-style <b>format</b>. */
  4373. int
  4374. control_event_server_status(int severity, const char *format, ...)
  4375. {
  4376. va_list ap;
  4377. int r;
  4378. if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER))
  4379. return 0;
  4380. va_start(ap, format);
  4381. r = control_event_status(EVENT_STATUS_SERVER, severity, format, ap);
  4382. va_end(ap);
  4383. return r;
  4384. }
  4385. /** Called when the status of an entry guard with the given <b>nickname</b>
  4386. * and identity <b>digest</b> has changed to <b>status</b>: tells any
  4387. * controllers that care. */
  4388. int
  4389. control_event_guard(const char *nickname, const char *digest,
  4390. const char *status)
  4391. {
  4392. char hbuf[HEX_DIGEST_LEN+1];
  4393. base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
  4394. if (!EVENT_IS_INTERESTING(EVENT_GUARD))
  4395. return 0;
  4396. {
  4397. char buf[MAX_VERBOSE_NICKNAME_LEN+1];
  4398. const node_t *node = node_get_by_id(digest);
  4399. if (node) {
  4400. node_get_verbose_nickname(node, buf);
  4401. } else {
  4402. tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
  4403. }
  4404. send_control_event(EVENT_GUARD, ALL_FORMATS,
  4405. "650 GUARD ENTRY %s %s\r\n", buf, status);
  4406. }
  4407. return 0;
  4408. }
  4409. /** Called when a configuration option changes. This is generally triggered
  4410. * by SETCONF requests and RELOAD/SIGHUP signals. The <b>elements</b> is
  4411. * a smartlist_t containing (key, value, ...) pairs in sequence.
  4412. * <b>value</b> can be NULL. */
  4413. int
  4414. control_event_conf_changed(const smartlist_t *elements)
  4415. {
  4416. int i;
  4417. char *result;
  4418. smartlist_t *lines;
  4419. if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED) ||
  4420. smartlist_len(elements) == 0) {
  4421. return 0;
  4422. }
  4423. lines = smartlist_new();
  4424. for (i = 0; i < smartlist_len(elements); i += 2) {
  4425. char *k = smartlist_get(elements, i);
  4426. char *v = smartlist_get(elements, i+1);
  4427. if (v == NULL) {
  4428. smartlist_add_asprintf(lines, "650-%s", k);
  4429. } else {
  4430. smartlist_add_asprintf(lines, "650-%s=%s", k, v);
  4431. }
  4432. }
  4433. result = smartlist_join_strings(lines, "\r\n", 0, NULL);
  4434. send_control_event(EVENT_CONF_CHANGED, 0,
  4435. "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result);
  4436. tor_free(result);
  4437. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  4438. smartlist_free(lines);
  4439. return 0;
  4440. }
  4441. /** Helper: Return a newly allocated string containing a path to the
  4442. * file where we store our authentication cookie. */
  4443. char *
  4444. get_controller_cookie_file_name(void)
  4445. {
  4446. const or_options_t *options = get_options();
  4447. if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
  4448. return tor_strdup(options->CookieAuthFile);
  4449. } else {
  4450. return get_datadir_fname("control_auth_cookie");
  4451. }
  4452. }
  4453. /* Initialize the cookie-based authentication system of the
  4454. * ControlPort. If <b>enabled</b> is 0, then disable the cookie
  4455. * authentication system. */
  4456. int
  4457. init_control_cookie_authentication(int enabled)
  4458. {
  4459. char *fname = NULL;
  4460. int retval;
  4461. if (!enabled) {
  4462. authentication_cookie_is_set = 0;
  4463. return 0;
  4464. }
  4465. fname = get_controller_cookie_file_name();
  4466. retval = init_cookie_authentication(fname, "", /* no header */
  4467. AUTHENTICATION_COOKIE_LEN,
  4468. get_options()->CookieAuthFileGroupReadable,
  4469. &authentication_cookie,
  4470. &authentication_cookie_is_set);
  4471. tor_free(fname);
  4472. return retval;
  4473. }
  4474. /** A copy of the process specifier of Tor's owning controller, or
  4475. * NULL if this Tor instance is not currently owned by a process. */
  4476. static char *owning_controller_process_spec = NULL;
  4477. /** A process-termination monitor for Tor's owning controller, or NULL
  4478. * if this Tor instance is not currently owned by a process. */
  4479. static tor_process_monitor_t *owning_controller_process_monitor = NULL;
  4480. static void owning_controller_procmon_cb(void *unused) ATTR_NORETURN;
  4481. /** Process-termination monitor callback for Tor's owning controller
  4482. * process. */
  4483. static void
  4484. owning_controller_procmon_cb(void *unused)
  4485. {
  4486. (void)unused;
  4487. lost_owning_controller("process", "vanished");
  4488. }
  4489. /** Set <b>process_spec</b> as Tor's owning controller process.
  4490. * Exit on failure. */
  4491. void
  4492. monitor_owning_controller_process(const char *process_spec)
  4493. {
  4494. const char *msg;
  4495. tor_assert((owning_controller_process_spec == NULL) ==
  4496. (owning_controller_process_monitor == NULL));
  4497. if (owning_controller_process_spec != NULL) {
  4498. if ((process_spec != NULL) && !strcmp(process_spec,
  4499. owning_controller_process_spec)) {
  4500. /* Same process -- return now, instead of disposing of and
  4501. * recreating the process-termination monitor. */
  4502. return;
  4503. }
  4504. /* We are currently owned by a process, and we should no longer be
  4505. * owned by it. Free the process-termination monitor. */
  4506. tor_process_monitor_free(owning_controller_process_monitor);
  4507. owning_controller_process_monitor = NULL;
  4508. tor_free(owning_controller_process_spec);
  4509. owning_controller_process_spec = NULL;
  4510. }
  4511. tor_assert((owning_controller_process_spec == NULL) &&
  4512. (owning_controller_process_monitor == NULL));
  4513. if (process_spec == NULL)
  4514. return;
  4515. owning_controller_process_spec = tor_strdup(process_spec);
  4516. owning_controller_process_monitor =
  4517. tor_process_monitor_new(tor_libevent_get_base(),
  4518. owning_controller_process_spec,
  4519. LD_CONTROL,
  4520. owning_controller_procmon_cb, NULL,
  4521. &msg);
  4522. if (owning_controller_process_monitor == NULL) {
  4523. log_err(LD_BUG, "Couldn't create process-termination monitor for "
  4524. "owning controller: %s. Exiting.",
  4525. msg);
  4526. owning_controller_process_spec = NULL;
  4527. tor_cleanup();
  4528. exit(0);
  4529. }
  4530. }
  4531. /** Convert the name of a bootstrapping phase <b>s</b> into strings
  4532. * <b>tag</b> and <b>summary</b> suitable for display by the controller. */
  4533. static int
  4534. bootstrap_status_to_string(bootstrap_status_t s, const char **tag,
  4535. const char **summary)
  4536. {
  4537. switch (s) {
  4538. case BOOTSTRAP_STATUS_UNDEF:
  4539. *tag = "undef";
  4540. *summary = "Undefined";
  4541. break;
  4542. case BOOTSTRAP_STATUS_STARTING:
  4543. *tag = "starting";
  4544. *summary = "Starting";
  4545. break;
  4546. case BOOTSTRAP_STATUS_CONN_DIR:
  4547. *tag = "conn_dir";
  4548. *summary = "Connecting to directory server";
  4549. break;
  4550. case BOOTSTRAP_STATUS_HANDSHAKE:
  4551. *tag = "status_handshake";
  4552. *summary = "Finishing handshake";
  4553. break;
  4554. case BOOTSTRAP_STATUS_HANDSHAKE_DIR:
  4555. *tag = "handshake_dir";
  4556. *summary = "Finishing handshake with directory server";
  4557. break;
  4558. case BOOTSTRAP_STATUS_ONEHOP_CREATE:
  4559. *tag = "onehop_create";
  4560. *summary = "Establishing an encrypted directory connection";
  4561. break;
  4562. case BOOTSTRAP_STATUS_REQUESTING_STATUS:
  4563. *tag = "requesting_status";
  4564. *summary = "Asking for networkstatus consensus";
  4565. break;
  4566. case BOOTSTRAP_STATUS_LOADING_STATUS:
  4567. *tag = "loading_status";
  4568. *summary = "Loading networkstatus consensus";
  4569. break;
  4570. case BOOTSTRAP_STATUS_LOADING_KEYS:
  4571. *tag = "loading_keys";
  4572. *summary = "Loading authority key certs";
  4573. break;
  4574. case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS:
  4575. *tag = "requesting_descriptors";
  4576. /* XXXX this appears to incorrectly report internal on most loads */
  4577. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  4578. "Asking for relay descriptors for internal paths" :
  4579. "Asking for relay descriptors";
  4580. break;
  4581. /* If we're sure there are no exits in the consensus,
  4582. * inform the controller by adding "internal"
  4583. * to the status summaries.
  4584. * (We only check this while loading descriptors,
  4585. * so we may not know in the earlier stages.)
  4586. * But if there are exits, we can't be sure whether
  4587. * we're creating internal or exit paths/circuits.
  4588. * XXXX Or should be use different tags or statuses
  4589. * for internal and exit/all? */
  4590. case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS:
  4591. *tag = "loading_descriptors";
  4592. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  4593. "Loading relay descriptors for internal paths" :
  4594. "Loading relay descriptors";
  4595. break;
  4596. case BOOTSTRAP_STATUS_CONN_OR:
  4597. *tag = "conn_or";
  4598. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  4599. "Connecting to the Tor network internally" :
  4600. "Connecting to the Tor network";
  4601. break;
  4602. case BOOTSTRAP_STATUS_HANDSHAKE_OR:
  4603. *tag = "handshake_or";
  4604. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  4605. "Finishing handshake with first hop of internal circuit" :
  4606. "Finishing handshake with first hop";
  4607. break;
  4608. case BOOTSTRAP_STATUS_CIRCUIT_CREATE:
  4609. *tag = "circuit_create";
  4610. *summary = router_have_consensus_path() == CONSENSUS_PATH_INTERNAL ?
  4611. "Establishing an internal Tor circuit" :
  4612. "Establishing a Tor circuit";
  4613. break;
  4614. case BOOTSTRAP_STATUS_DONE:
  4615. *tag = "done";
  4616. *summary = "Done";
  4617. break;
  4618. default:
  4619. // log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
  4620. *tag = *summary = "unknown";
  4621. return -1;
  4622. }
  4623. return 0;
  4624. }
  4625. /** What percentage through the bootstrap process are we? We remember
  4626. * this so we can avoid sending redundant bootstrap status events, and
  4627. * so we can guess context for the bootstrap messages which are
  4628. * ambiguous. It starts at 'undef', but gets set to 'starting' while
  4629. * Tor initializes. */
  4630. static int bootstrap_percent = BOOTSTRAP_STATUS_UNDEF;
  4631. /** As bootstrap_percent, but holds the bootstrapping level at which we last
  4632. * logged a NOTICE-level message. We use this, plus BOOTSTRAP_PCT_INCREMENT,
  4633. * to avoid flooding the log with a new message every time we get a few more
  4634. * microdescriptors */
  4635. static int notice_bootstrap_percent = 0;
  4636. /** How many problems have we had getting to the next bootstrapping phase?
  4637. * These include failure to establish a connection to a Tor relay,
  4638. * failures to finish the TLS handshake, failures to validate the
  4639. * consensus document, etc. */
  4640. static int bootstrap_problems = 0;
  4641. /** We only tell the controller once we've hit a threshold of problems
  4642. * for the current phase. */
  4643. #define BOOTSTRAP_PROBLEM_THRESHOLD 10
  4644. /** When our bootstrapping progress level changes, but our bootstrapping
  4645. * status has not advanced, we only log at NOTICE when we have made at least
  4646. * this much progress.
  4647. */
  4648. #define BOOTSTRAP_PCT_INCREMENT 5
  4649. /** Called when Tor has made progress at bootstrapping its directory
  4650. * information and initial circuits.
  4651. *
  4652. * <b>status</b> is the new status, that is, what task we will be doing
  4653. * next. <b>progress</b> is zero if we just started this task, else it
  4654. * represents progress on the task.
  4655. *
  4656. * Return true if we logged a message at level NOTICE, and false otherwise.
  4657. */
  4658. int
  4659. control_event_bootstrap(bootstrap_status_t status, int progress)
  4660. {
  4661. const char *tag, *summary;
  4662. char buf[BOOTSTRAP_MSG_LEN];
  4663. if (bootstrap_percent == BOOTSTRAP_STATUS_DONE)
  4664. return 0; /* already bootstrapped; nothing to be done here. */
  4665. /* special case for handshaking status, since our TLS handshaking code
  4666. * can't distinguish what the connection is going to be for. */
  4667. if (status == BOOTSTRAP_STATUS_HANDSHAKE) {
  4668. if (bootstrap_percent < BOOTSTRAP_STATUS_CONN_OR) {
  4669. status = BOOTSTRAP_STATUS_HANDSHAKE_DIR;
  4670. } else {
  4671. status = BOOTSTRAP_STATUS_HANDSHAKE_OR;
  4672. }
  4673. }
  4674. if (status > bootstrap_percent ||
  4675. (progress && progress > bootstrap_percent)) {
  4676. int loglevel = LOG_NOTICE;
  4677. bootstrap_status_to_string(status, &tag, &summary);
  4678. if (status <= bootstrap_percent &&
  4679. (progress < notice_bootstrap_percent + BOOTSTRAP_PCT_INCREMENT)) {
  4680. /* We log the message at info if the status hasn't advanced, and if less
  4681. * than BOOTSTRAP_PCT_INCREMENT progress has been made.
  4682. */
  4683. loglevel = LOG_INFO;
  4684. }
  4685. tor_log(loglevel, LD_CONTROL,
  4686. "Bootstrapped %d%%: %s", progress ? progress : status, summary);
  4687. tor_snprintf(buf, sizeof(buf),
  4688. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
  4689. progress ? progress : status, tag, summary);
  4690. tor_snprintf(last_sent_bootstrap_message,
  4691. sizeof(last_sent_bootstrap_message),
  4692. "NOTICE %s", buf);
  4693. control_event_client_status(LOG_NOTICE, "%s", buf);
  4694. if (status > bootstrap_percent) {
  4695. bootstrap_percent = status; /* new milestone reached */
  4696. }
  4697. if (progress > bootstrap_percent) {
  4698. /* incremental progress within a milestone */
  4699. bootstrap_percent = progress;
  4700. bootstrap_problems = 0; /* Progress! Reset our problem counter. */
  4701. }
  4702. if (loglevel == LOG_NOTICE &&
  4703. bootstrap_percent > notice_bootstrap_percent) {
  4704. /* Remember that we gave a notice at this level. */
  4705. notice_bootstrap_percent = bootstrap_percent;
  4706. }
  4707. return loglevel == LOG_NOTICE;
  4708. }
  4709. return 0;
  4710. }
  4711. /** Called when Tor has failed to make bootstrapping progress in a way
  4712. * that indicates a problem. <b>warn</b> gives a hint as to why, and
  4713. * <b>reason</b> provides an "or_conn_end_reason" tag. <b>or_conn</b>
  4714. * is the connection that caused this problem.
  4715. */
  4716. MOCK_IMPL(void,
  4717. control_event_bootstrap_problem, (const char *warn, int reason,
  4718. or_connection_t *or_conn))
  4719. {
  4720. int status = bootstrap_percent;
  4721. const char *tag = "", *summary = "";
  4722. char buf[BOOTSTRAP_MSG_LEN];
  4723. const char *recommendation = "ignore";
  4724. int severity;
  4725. /* bootstrap_percent must not be in "undefined" state here. */
  4726. tor_assert(status >= 0);
  4727. if (or_conn->have_noted_bootstrap_problem)
  4728. return;
  4729. or_conn->have_noted_bootstrap_problem = 1;
  4730. if (bootstrap_percent == 100)
  4731. return; /* already bootstrapped; nothing to be done here. */
  4732. bootstrap_problems++;
  4733. if (bootstrap_problems >= BOOTSTRAP_PROBLEM_THRESHOLD)
  4734. recommendation = "warn";
  4735. if (reason == END_OR_CONN_REASON_NO_ROUTE)
  4736. recommendation = "warn";
  4737. /* If we are using bridges and all our OR connections are now
  4738. closed, it means that we totally failed to connect to our
  4739. bridges. Throw a warning. */
  4740. if (get_options()->UseBridges && !any_other_active_or_conns(or_conn))
  4741. recommendation = "warn";
  4742. if (we_are_hibernating())
  4743. recommendation = "ignore";
  4744. while (status>=0 && bootstrap_status_to_string(status, &tag, &summary) < 0)
  4745. status--; /* find a recognized status string based on current progress */
  4746. status = bootstrap_percent; /* set status back to the actual number */
  4747. severity = !strcmp(recommendation, "warn") ? LOG_WARN : LOG_INFO;
  4748. log_fn(severity,
  4749. LD_CONTROL, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
  4750. "count %d; recommendation %s; host %s at %s:%d)",
  4751. status, summary, warn,
  4752. orconn_end_reason_to_control_string(reason),
  4753. bootstrap_problems, recommendation,
  4754. hex_str(or_conn->identity_digest, DIGEST_LEN),
  4755. or_conn->base_.address,
  4756. or_conn->base_.port);
  4757. connection_or_report_broken_states(severity, LD_HANDSHAKE);
  4758. tor_snprintf(buf, sizeof(buf),
  4759. "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
  4760. "COUNT=%d RECOMMENDATION=%s HOSTID=\"%s\" HOSTADDR=\"%s:%d\"",
  4761. bootstrap_percent, tag, summary, warn,
  4762. orconn_end_reason_to_control_string(reason), bootstrap_problems,
  4763. recommendation,
  4764. hex_str(or_conn->identity_digest, DIGEST_LEN),
  4765. or_conn->base_.address,
  4766. (int)or_conn->base_.port);
  4767. tor_snprintf(last_sent_bootstrap_message,
  4768. sizeof(last_sent_bootstrap_message),
  4769. "WARN %s", buf);
  4770. control_event_client_status(LOG_WARN, "%s", buf);
  4771. }
  4772. /** We just generated a new summary of which countries we've seen clients
  4773. * from recently. Send a copy to the controller in case it wants to
  4774. * display it for the user. */
  4775. void
  4776. control_event_clients_seen(const char *controller_str)
  4777. {
  4778. send_control_event(EVENT_CLIENTS_SEEN, 0,
  4779. "650 CLIENTS_SEEN %s\r\n", controller_str);
  4780. }
  4781. /** A new pluggable transport called <b>transport_name</b> was
  4782. * launched on <b>addr</b>:<b>port</b>. <b>mode</b> is either
  4783. * "server" or "client" depending on the mode of the pluggable
  4784. * transport.
  4785. * "650" SP "TRANSPORT_LAUNCHED" SP Mode SP Name SP Address SP Port
  4786. */
  4787. void
  4788. control_event_transport_launched(const char *mode, const char *transport_name,
  4789. tor_addr_t *addr, uint16_t port)
  4790. {
  4791. send_control_event(EVENT_TRANSPORT_LAUNCHED, ALL_FORMATS,
  4792. "650 TRANSPORT_LAUNCHED %s %s %s %u\r\n",
  4793. mode, transport_name, fmt_addr(addr), port);
  4794. }
  4795. /** Convert rendezvous auth type to string for HS_DESC control events
  4796. */
  4797. const char *
  4798. rend_auth_type_to_string(rend_auth_type_t auth_type)
  4799. {
  4800. const char *str;
  4801. switch (auth_type) {
  4802. case REND_NO_AUTH:
  4803. str = "NO_AUTH";
  4804. break;
  4805. case REND_BASIC_AUTH:
  4806. str = "BASIC_AUTH";
  4807. break;
  4808. case REND_STEALTH_AUTH:
  4809. str = "STEALTH_AUTH";
  4810. break;
  4811. default:
  4812. str = "UNKNOWN";
  4813. }
  4814. return str;
  4815. }
  4816. /** Return a longname the node whose identity is <b>id_digest</b>. If
  4817. * node_get_by_id() returns NULL, base 16 encoding of <b>id_digest</b> is
  4818. * returned instead.
  4819. *
  4820. * This function is not thread-safe. Each call to this function invalidates
  4821. * previous values returned by this function.
  4822. */
  4823. MOCK_IMPL(const char *,
  4824. node_describe_longname_by_id,(const char *id_digest))
  4825. {
  4826. static char longname[MAX_VERBOSE_NICKNAME_LEN+1];
  4827. node_get_verbose_nickname_by_id(id_digest, longname);
  4828. return longname;
  4829. }
  4830. /** send HS_DESC requested event.
  4831. *
  4832. * <b>rend_query</b> is used to fetch requested onion address and auth type.
  4833. * <b>hs_dir</b> is the description of contacting hs directory.
  4834. * <b>desc_id_base32</b> is the ID of requested hs descriptor.
  4835. */
  4836. void
  4837. control_event_hs_descriptor_requested(const rend_data_t *rend_query,
  4838. const char *id_digest,
  4839. const char *desc_id_base32)
  4840. {
  4841. if (!id_digest || !rend_query || !desc_id_base32) {
  4842. log_warn(LD_BUG, "Called with rend_query==%p, "
  4843. "id_digest==%p, desc_id_base32==%p",
  4844. rend_query, id_digest, desc_id_base32);
  4845. return;
  4846. }
  4847. send_control_event(EVENT_HS_DESC, ALL_FORMATS,
  4848. "650 HS_DESC REQUESTED %s %s %s %s\r\n",
  4849. rend_query->onion_address,
  4850. rend_auth_type_to_string(rend_query->auth_type),
  4851. node_describe_longname_by_id(id_digest),
  4852. desc_id_base32);
  4853. }
  4854. /** send HS_DESC event after got response from hs directory.
  4855. *
  4856. * NOTE: this is an internal function used by following functions:
  4857. * control_event_hs_descriptor_received
  4858. * control_event_hs_descriptor_failed
  4859. *
  4860. * So do not call this function directly.
  4861. */
  4862. void
  4863. control_event_hs_descriptor_receive_end(const char *action,
  4864. const rend_data_t *rend_query,
  4865. const char *id_digest,
  4866. const char *reason)
  4867. {
  4868. char *reason_field = NULL;
  4869. if (!action || !rend_query || !id_digest) {
  4870. log_warn(LD_BUG, "Called with action==%p, rend_query==%p, "
  4871. "id_digest==%p", action, rend_query, id_digest);
  4872. return;
  4873. }
  4874. if (reason) {
  4875. tor_asprintf(&reason_field, " REASON=%s", reason);
  4876. }
  4877. send_control_event(EVENT_HS_DESC, ALL_FORMATS,
  4878. "650 HS_DESC %s %s %s %s%s\r\n",
  4879. action,
  4880. rend_query->onion_address,
  4881. rend_auth_type_to_string(rend_query->auth_type),
  4882. node_describe_longname_by_id(id_digest),
  4883. reason_field ? reason_field : "");
  4884. tor_free(reason_field);
  4885. }
  4886. /** send HS_DESC RECEIVED event
  4887. *
  4888. * called when a we successfully received a hidden service descriptor.
  4889. */
  4890. void
  4891. control_event_hs_descriptor_received(const rend_data_t *rend_query,
  4892. const char *id_digest)
  4893. {
  4894. if (!rend_query || !id_digest) {
  4895. log_warn(LD_BUG, "Called with rend_query==%p, id_digest==%p",
  4896. rend_query, id_digest);
  4897. return;
  4898. }
  4899. control_event_hs_descriptor_receive_end("RECEIVED", rend_query,
  4900. id_digest, NULL);
  4901. }
  4902. /** Send HS_DESC event to inform controller that query <b>rend_query</b>
  4903. * failed to retrieve hidden service descriptor identified by
  4904. * <b>id_digest</b>. If <b>reason</b> is not NULL, add it to REASON=
  4905. * field.
  4906. */
  4907. void
  4908. control_event_hs_descriptor_failed(const rend_data_t *rend_query,
  4909. const char *id_digest,
  4910. const char *reason)
  4911. {
  4912. if (!rend_query || !id_digest) {
  4913. log_warn(LD_BUG, "Called with rend_query==%p, id_digest==%p",
  4914. rend_query, id_digest);
  4915. return;
  4916. }
  4917. control_event_hs_descriptor_receive_end("FAILED", rend_query,
  4918. id_digest, reason);
  4919. }
  4920. /** Free any leftover allocated memory of the control.c subsystem. */
  4921. void
  4922. control_free_all(void)
  4923. {
  4924. if (authentication_cookie) /* Free the auth cookie */
  4925. tor_free(authentication_cookie);
  4926. }
  4927. #ifdef TOR_UNIT_TESTS
  4928. /* For testing: change the value of global_event_mask */
  4929. void
  4930. control_testing_set_global_event_mask(uint64_t mask)
  4931. {
  4932. global_event_mask = mask;
  4933. }
  4934. #endif