control.c 172 KB

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