control.c 143 KB

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