control.c 156 KB

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