control.c 170 KB

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