control.c 137 KB

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