control.c 157 KB

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