control_events.c 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2019, The Tor Project, Inc. */
  3. /* See LICENSE for licensing information */
  4. /**
  5. * \file control_events.c
  6. * \brief Implement the event-reporting part of the controller API.
  7. **/
  8. #define CONTROL_MODULE_PRIVATE
  9. #define CONTROL_EVENTS_PRIVATE
  10. #define OCIRC_EVENT_PRIVATE
  11. #include "core/or/or.h"
  12. #include "app/config/config.h"
  13. #include "core/mainloop/connection.h"
  14. #include "core/mainloop/mainloop.h"
  15. #include "core/or/channeltls.h"
  16. #include "core/or/circuitlist.h"
  17. #include "core/or/command.h"
  18. #include "core/or/connection_edge.h"
  19. #include "core/or/connection_or.h"
  20. #include "core/or/reasons.h"
  21. #include "feature/control/control.h"
  22. #include "feature/control/control_events.h"
  23. #include "feature/control/control_fmt.h"
  24. #include "feature/dircommon/directory.h"
  25. #include "feature/nodelist/networkstatus.h"
  26. #include "feature/nodelist/nodelist.h"
  27. #include "feature/nodelist/routerinfo.h"
  28. #include "feature/control/control_connection_st.h"
  29. #include "core/or/entry_connection_st.h"
  30. #include "feature/nodelist/networkstatus_st.h"
  31. #include "core/or/or_connection_st.h"
  32. #include "core/or/or_circuit_st.h"
  33. #include "core/or/origin_circuit_st.h"
  34. #include "lib/evloop/compat_libevent.h"
  35. static void flush_queued_events_cb(mainloop_event_t *event, void *arg);
  36. static void control_get_bytes_rw_last_sec(uint64_t *r, uint64_t *w);
  37. /** Yield true iff <b>s</b> is the state of a control_connection_t that has
  38. * finished authentication and is accepting commands. */
  39. #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
  40. /** An event mask of all the events that any controller is interested in
  41. * receiving. */
  42. static event_mask_t global_event_mask = 0;
  43. /** True iff we have disabled log messages from being sent to the controller */
  44. static int disable_log_messages = 0;
  45. /** Macro: true if any control connection is interested in events of type
  46. * <b>e</b>. */
  47. #define EVENT_IS_INTERESTING(e) \
  48. (!! (global_event_mask & EVENT_MASK_(e)))
  49. /** Macro: true if any event from the bitfield 'e' is interesting. */
  50. #define ANY_EVENT_IS_INTERESTING(e) \
  51. (!! (global_event_mask & (e)))
  52. static void send_control_event_impl(uint16_t event,
  53. const char *format, va_list ap)
  54. CHECK_PRINTF(2,0);
  55. static int control_event_status(int type, int severity, const char *format,
  56. va_list args)
  57. CHECK_PRINTF(3,0);
  58. static void send_control_event(uint16_t event,
  59. const char *format, ...)
  60. CHECK_PRINTF(2,3);
  61. /** Given a log severity, return the corresponding control event code. */
  62. static inline int
  63. log_severity_to_event(int severity)
  64. {
  65. switch (severity) {
  66. case LOG_DEBUG: return EVENT_DEBUG_MSG;
  67. case LOG_INFO: return EVENT_INFO_MSG;
  68. case LOG_NOTICE: return EVENT_NOTICE_MSG;
  69. case LOG_WARN: return EVENT_WARN_MSG;
  70. case LOG_ERR: return EVENT_ERR_MSG;
  71. default: return -1;
  72. }
  73. }
  74. /** Helper: clear bandwidth counters of all origin circuits. */
  75. static void
  76. clear_circ_bw_fields(void)
  77. {
  78. origin_circuit_t *ocirc;
  79. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  80. if (!CIRCUIT_IS_ORIGIN(circ))
  81. continue;
  82. ocirc = TO_ORIGIN_CIRCUIT(circ);
  83. ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
  84. ocirc->n_overhead_written_circ_bw = ocirc->n_overhead_read_circ_bw = 0;
  85. ocirc->n_delivered_written_circ_bw = ocirc->n_delivered_read_circ_bw = 0;
  86. }
  87. SMARTLIST_FOREACH_END(circ);
  88. }
  89. /** Set <b>global_event_mask*</b> to the bitwise OR of each live control
  90. * connection's event_mask field. */
  91. void
  92. control_update_global_event_mask(void)
  93. {
  94. smartlist_t *conns = get_connection_array();
  95. event_mask_t old_mask, new_mask;
  96. old_mask = global_event_mask;
  97. int any_old_per_sec_events = control_any_per_second_event_enabled();
  98. global_event_mask = 0;
  99. SMARTLIST_FOREACH(conns, connection_t *, _conn,
  100. {
  101. if (_conn->type == CONN_TYPE_CONTROL &&
  102. STATE_IS_OPEN(_conn->state)) {
  103. control_connection_t *conn = TO_CONTROL_CONN(_conn);
  104. global_event_mask |= conn->event_mask;
  105. }
  106. });
  107. new_mask = global_event_mask;
  108. /* Handle the aftermath. Set up the log callback to tell us only what
  109. * we want to hear...*/
  110. control_adjust_event_log_severity();
  111. /* Macro: true if ev was false before and is true now. */
  112. #define NEWLY_ENABLED(ev) \
  113. (! (old_mask & (ev)) && (new_mask & (ev)))
  114. /* ...then, if we've started logging stream or circ bw, clear the
  115. * appropriate fields. */
  116. if (NEWLY_ENABLED(EVENT_STREAM_BANDWIDTH_USED)) {
  117. SMARTLIST_FOREACH(conns, connection_t *, conn,
  118. {
  119. if (conn->type == CONN_TYPE_AP) {
  120. edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
  121. edge_conn->n_written = edge_conn->n_read = 0;
  122. }
  123. });
  124. }
  125. if (NEWLY_ENABLED(EVENT_CIRC_BANDWIDTH_USED)) {
  126. clear_circ_bw_fields();
  127. }
  128. if (NEWLY_ENABLED(EVENT_BANDWIDTH_USED)) {
  129. uint64_t r, w;
  130. control_get_bytes_rw_last_sec(&r, &w);
  131. }
  132. if (any_old_per_sec_events != control_any_per_second_event_enabled()) {
  133. rescan_periodic_events(get_options());
  134. }
  135. #undef NEWLY_ENABLED
  136. }
  137. /** Given a control event code for a message event, return the corresponding
  138. * log severity. */
  139. static inline int
  140. event_to_log_severity(int event)
  141. {
  142. switch (event) {
  143. case EVENT_DEBUG_MSG: return LOG_DEBUG;
  144. case EVENT_INFO_MSG: return LOG_INFO;
  145. case EVENT_NOTICE_MSG: return LOG_NOTICE;
  146. case EVENT_WARN_MSG: return LOG_WARN;
  147. case EVENT_ERR_MSG: return LOG_ERR;
  148. default: return -1;
  149. }
  150. }
  151. /** Adjust the log severities that result in control_event_logmsg being called
  152. * to match the severity of log messages that any controllers are interested
  153. * in. */
  154. void
  155. control_adjust_event_log_severity(void)
  156. {
  157. int i;
  158. int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
  159. for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
  160. if (EVENT_IS_INTERESTING(i)) {
  161. min_log_event = i;
  162. break;
  163. }
  164. }
  165. for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
  166. if (EVENT_IS_INTERESTING(i)) {
  167. max_log_event = i;
  168. break;
  169. }
  170. }
  171. if (EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
  172. if (min_log_event > EVENT_NOTICE_MSG)
  173. min_log_event = EVENT_NOTICE_MSG;
  174. if (max_log_event < EVENT_ERR_MSG)
  175. max_log_event = EVENT_ERR_MSG;
  176. }
  177. if (min_log_event <= max_log_event)
  178. change_callback_log_severity(event_to_log_severity(min_log_event),
  179. event_to_log_severity(max_log_event),
  180. control_event_logmsg);
  181. else
  182. change_callback_log_severity(LOG_ERR, LOG_ERR,
  183. control_event_logmsg);
  184. }
  185. /** Return true iff the event with code <b>c</b> is being sent to any current
  186. * control connection. This is useful if the amount of work needed to prepare
  187. * to call the appropriate control_event_...() function is high.
  188. */
  189. int
  190. control_event_is_interesting(int event)
  191. {
  192. return EVENT_IS_INTERESTING(event);
  193. }
  194. /** Return true if any event that needs to fire once a second is enabled. */
  195. int
  196. control_any_per_second_event_enabled(void)
  197. {
  198. return ANY_EVENT_IS_INTERESTING(
  199. EVENT_MASK_(EVENT_BANDWIDTH_USED) |
  200. EVENT_MASK_(EVENT_CELL_STATS) |
  201. EVENT_MASK_(EVENT_CIRC_BANDWIDTH_USED) |
  202. EVENT_MASK_(EVENT_CONN_BW) |
  203. EVENT_MASK_(EVENT_STREAM_BANDWIDTH_USED)
  204. );
  205. }
  206. /* The value of 'get_bytes_read()' the previous time that
  207. * control_get_bytes_rw_last_sec() as called. */
  208. static uint64_t stats_prev_n_read = 0;
  209. /* The value of 'get_bytes_written()' the previous time that
  210. * control_get_bytes_rw_last_sec() as called. */
  211. static uint64_t stats_prev_n_written = 0;
  212. /**
  213. * Set <b>n_read</b> and <b>n_written</b> to the total number of bytes read
  214. * and written by Tor since the last call to this function.
  215. *
  216. * Call this only from the main thread.
  217. */
  218. static void
  219. control_get_bytes_rw_last_sec(uint64_t *n_read,
  220. uint64_t *n_written)
  221. {
  222. const uint64_t stats_n_bytes_read = get_bytes_read();
  223. const uint64_t stats_n_bytes_written = get_bytes_written();
  224. *n_read = stats_n_bytes_read - stats_prev_n_read;
  225. *n_written = stats_n_bytes_written - stats_prev_n_written;
  226. stats_prev_n_read = stats_n_bytes_read;
  227. stats_prev_n_written = stats_n_bytes_written;
  228. }
  229. /**
  230. * Run all the controller events (if any) that are scheduled to trigger once
  231. * per second.
  232. */
  233. void
  234. control_per_second_events(void)
  235. {
  236. if (!control_any_per_second_event_enabled())
  237. return;
  238. uint64_t bytes_read, bytes_written;
  239. control_get_bytes_rw_last_sec(&bytes_read, &bytes_written);
  240. control_event_bandwidth_used((uint32_t)bytes_read,(uint32_t)bytes_written);
  241. control_event_stream_bandwidth_used();
  242. control_event_conn_bandwidth_used();
  243. control_event_circ_bandwidth_used();
  244. control_event_circuit_cell_stats();
  245. }
  246. /** Represents an event that's queued to be sent to one or more
  247. * controllers. */
  248. typedef struct queued_event_s {
  249. uint16_t event;
  250. char *msg;
  251. } queued_event_t;
  252. /** Pointer to int. If this is greater than 0, we don't allow new events to be
  253. * queued. */
  254. static tor_threadlocal_t block_event_queue_flag;
  255. /** Holds a smartlist of queued_event_t objects that may need to be sent
  256. * to one or more controllers */
  257. static smartlist_t *queued_control_events = NULL;
  258. /** True if the flush_queued_events_event is pending. */
  259. static int flush_queued_event_pending = 0;
  260. /** Lock to protect the above fields. */
  261. static tor_mutex_t *queued_control_events_lock = NULL;
  262. /** An event that should fire in order to flush the contents of
  263. * queued_control_events. */
  264. static mainloop_event_t *flush_queued_events_event = NULL;
  265. void
  266. control_initialize_event_queue(void)
  267. {
  268. if (queued_control_events == NULL) {
  269. queued_control_events = smartlist_new();
  270. }
  271. if (flush_queued_events_event == NULL) {
  272. struct event_base *b = tor_libevent_get_base();
  273. if (b) {
  274. flush_queued_events_event =
  275. mainloop_event_new(flush_queued_events_cb, NULL);
  276. tor_assert(flush_queued_events_event);
  277. }
  278. }
  279. if (queued_control_events_lock == NULL) {
  280. queued_control_events_lock = tor_mutex_new();
  281. tor_threadlocal_init(&block_event_queue_flag);
  282. }
  283. }
  284. static int *
  285. get_block_event_queue(void)
  286. {
  287. int *val = tor_threadlocal_get(&block_event_queue_flag);
  288. if (PREDICT_UNLIKELY(val == NULL)) {
  289. val = tor_malloc_zero(sizeof(int));
  290. tor_threadlocal_set(&block_event_queue_flag, val);
  291. }
  292. return val;
  293. }
  294. /** Helper: inserts an event on the list of events queued to be sent to
  295. * one or more controllers, and schedules the events to be flushed if needed.
  296. *
  297. * This function takes ownership of <b>msg</b>, and may free it.
  298. *
  299. * We queue these events rather than send them immediately in order to break
  300. * the dependency in our callgraph from code that generates events for the
  301. * controller, and the network layer at large. Otherwise, nearly every
  302. * interesting part of Tor would potentially call every other interesting part
  303. * of Tor.
  304. */
  305. MOCK_IMPL(STATIC void,
  306. queue_control_event_string,(uint16_t event, char *msg))
  307. {
  308. /* This is redundant with checks done elsewhere, but it's a last-ditch
  309. * attempt to avoid queueing something we shouldn't have to queue. */
  310. if (PREDICT_UNLIKELY( ! EVENT_IS_INTERESTING(event) )) {
  311. tor_free(msg);
  312. return;
  313. }
  314. int *block_event_queue = get_block_event_queue();
  315. if (*block_event_queue) {
  316. tor_free(msg);
  317. return;
  318. }
  319. queued_event_t *ev = tor_malloc(sizeof(*ev));
  320. ev->event = event;
  321. ev->msg = msg;
  322. /* No queueing an event while queueing an event */
  323. ++*block_event_queue;
  324. tor_mutex_acquire(queued_control_events_lock);
  325. tor_assert(queued_control_events);
  326. smartlist_add(queued_control_events, ev);
  327. int activate_event = 0;
  328. if (! flush_queued_event_pending && in_main_thread()) {
  329. activate_event = 1;
  330. flush_queued_event_pending = 1;
  331. }
  332. tor_mutex_release(queued_control_events_lock);
  333. --*block_event_queue;
  334. /* We just put an event on the queue; mark the queue to be
  335. * flushed. We only do this from the main thread for now; otherwise,
  336. * we'd need to incur locking overhead in Libevent or use a socket.
  337. */
  338. if (activate_event) {
  339. tor_assert(flush_queued_events_event);
  340. mainloop_event_activate(flush_queued_events_event);
  341. }
  342. }
  343. #define queued_event_free(ev) \
  344. FREE_AND_NULL(queued_event_t, queued_event_free_, (ev))
  345. /** Release all storage held by <b>ev</b>. */
  346. static void
  347. queued_event_free_(queued_event_t *ev)
  348. {
  349. if (ev == NULL)
  350. return;
  351. tor_free(ev->msg);
  352. tor_free(ev);
  353. }
  354. /** Send every queued event to every controller that's interested in it,
  355. * and remove the events from the queue. If <b>force</b> is true,
  356. * then make all controllers send their data out immediately, since we
  357. * may be about to shut down. */
  358. static void
  359. queued_events_flush_all(int force)
  360. {
  361. /* Make sure that we get all the pending log events, if there are any. */
  362. flush_pending_log_callbacks();
  363. if (PREDICT_UNLIKELY(queued_control_events == NULL)) {
  364. return;
  365. }
  366. smartlist_t *all_conns = get_connection_array();
  367. smartlist_t *controllers = smartlist_new();
  368. smartlist_t *queued_events;
  369. int *block_event_queue = get_block_event_queue();
  370. ++*block_event_queue;
  371. tor_mutex_acquire(queued_control_events_lock);
  372. /* No queueing an event while flushing events. */
  373. flush_queued_event_pending = 0;
  374. queued_events = queued_control_events;
  375. queued_control_events = smartlist_new();
  376. tor_mutex_release(queued_control_events_lock);
  377. /* Gather all the controllers that will care... */
  378. SMARTLIST_FOREACH_BEGIN(all_conns, connection_t *, conn) {
  379. if (conn->type == CONN_TYPE_CONTROL &&
  380. !conn->marked_for_close &&
  381. conn->state == CONTROL_CONN_STATE_OPEN) {
  382. control_connection_t *control_conn = TO_CONTROL_CONN(conn);
  383. smartlist_add(controllers, control_conn);
  384. }
  385. } SMARTLIST_FOREACH_END(conn);
  386. SMARTLIST_FOREACH_BEGIN(queued_events, queued_event_t *, ev) {
  387. const event_mask_t bit = ((event_mask_t)1) << ev->event;
  388. const size_t msg_len = strlen(ev->msg);
  389. SMARTLIST_FOREACH_BEGIN(controllers, control_connection_t *,
  390. control_conn) {
  391. if (control_conn->event_mask & bit) {
  392. connection_buf_add(ev->msg, msg_len, TO_CONN(control_conn));
  393. }
  394. } SMARTLIST_FOREACH_END(control_conn);
  395. queued_event_free(ev);
  396. } SMARTLIST_FOREACH_END(ev);
  397. if (force) {
  398. SMARTLIST_FOREACH_BEGIN(controllers, control_connection_t *,
  399. control_conn) {
  400. connection_flush(TO_CONN(control_conn));
  401. } SMARTLIST_FOREACH_END(control_conn);
  402. }
  403. smartlist_free(queued_events);
  404. smartlist_free(controllers);
  405. --*block_event_queue;
  406. }
  407. /** Libevent callback: Flushes pending events to controllers that are
  408. * interested in them. */
  409. static void
  410. flush_queued_events_cb(mainloop_event_t *event, void *arg)
  411. {
  412. (void) event;
  413. (void) arg;
  414. queued_events_flush_all(0);
  415. }
  416. /** Send an event to all v1 controllers that are listening for code
  417. * <b>event</b>. The event's body is given by <b>msg</b>.
  418. *
  419. * The EXTENDED_FORMAT and NONEXTENDED_FORMAT flags behave similarly with
  420. * respect to the EXTENDED_EVENTS feature. */
  421. MOCK_IMPL(STATIC void,
  422. send_control_event_string,(uint16_t event,
  423. const char *msg))
  424. {
  425. tor_assert(event >= EVENT_MIN_ && event <= EVENT_MAX_);
  426. queue_control_event_string(event, tor_strdup(msg));
  427. }
  428. /** Helper for send_control_event and control_event_status:
  429. * Send an event to all v1 controllers that are listening for code
  430. * <b>event</b>. The event's body is created by the printf-style format in
  431. * <b>format</b>, and other arguments as provided. */
  432. static void
  433. send_control_event_impl(uint16_t event,
  434. const char *format, va_list ap)
  435. {
  436. char *buf = NULL;
  437. int len;
  438. len = tor_vasprintf(&buf, format, ap);
  439. if (len < 0) {
  440. log_warn(LD_BUG, "Unable to format event for controller.");
  441. return;
  442. }
  443. queue_control_event_string(event, buf);
  444. }
  445. /** Send an event to all v1 controllers that are listening for code
  446. * <b>event</b>. The event's body is created by the printf-style format in
  447. * <b>format</b>, and other arguments as provided. */
  448. static void
  449. send_control_event(uint16_t event,
  450. const char *format, ...)
  451. {
  452. va_list ap;
  453. va_start(ap, format);
  454. send_control_event_impl(event, format, ap);
  455. va_end(ap);
  456. }
  457. /** Something major has happened to circuit <b>circ</b>: tell any
  458. * interested control connections. */
  459. int
  460. control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
  461. int reason_code)
  462. {
  463. const char *status;
  464. char reasons[64] = "";
  465. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
  466. return 0;
  467. tor_assert(circ);
  468. switch (tp)
  469. {
  470. case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  471. case CIRC_EVENT_BUILT: status = "BUILT"; break;
  472. case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
  473. case CIRC_EVENT_FAILED: status = "FAILED"; break;
  474. case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
  475. default:
  476. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  477. tor_fragile_assert();
  478. return 0;
  479. }
  480. if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
  481. const char *reason_str = circuit_end_reason_to_control_string(reason_code);
  482. char unk_reason_buf[16];
  483. if (!reason_str) {
  484. tor_snprintf(unk_reason_buf, 16, "UNKNOWN_%d", reason_code);
  485. reason_str = unk_reason_buf;
  486. }
  487. if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
  488. tor_snprintf(reasons, sizeof(reasons),
  489. " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
  490. } else {
  491. tor_snprintf(reasons, sizeof(reasons),
  492. " REASON=%s", reason_str);
  493. }
  494. }
  495. {
  496. char *circdesc = circuit_describe_status_for_controller(circ);
  497. const char *sp = strlen(circdesc) ? " " : "";
  498. send_control_event(EVENT_CIRCUIT_STATUS,
  499. "650 CIRC %lu %s%s%s%s\r\n",
  500. (unsigned long)circ->global_identifier,
  501. status, sp,
  502. circdesc,
  503. reasons);
  504. tor_free(circdesc);
  505. }
  506. return 0;
  507. }
  508. /** Something minor has happened to circuit <b>circ</b>: tell any
  509. * interested control connections. */
  510. static int
  511. control_event_circuit_status_minor(origin_circuit_t *circ,
  512. circuit_status_minor_event_t e,
  513. int purpose, const struct timeval *tv)
  514. {
  515. const char *event_desc;
  516. char event_tail[160] = "";
  517. if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR))
  518. return 0;
  519. tor_assert(circ);
  520. switch (e)
  521. {
  522. case CIRC_MINOR_EVENT_PURPOSE_CHANGED:
  523. event_desc = "PURPOSE_CHANGED";
  524. {
  525. /* event_tail can currently be up to 68 chars long */
  526. const char *hs_state_str =
  527. circuit_purpose_to_controller_hs_state_string(purpose);
  528. tor_snprintf(event_tail, sizeof(event_tail),
  529. " OLD_PURPOSE=%s%s%s",
  530. circuit_purpose_to_controller_string(purpose),
  531. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  532. (hs_state_str != NULL) ? hs_state_str : "");
  533. }
  534. break;
  535. case CIRC_MINOR_EVENT_CANNIBALIZED:
  536. event_desc = "CANNIBALIZED";
  537. {
  538. /* event_tail can currently be up to 130 chars long */
  539. const char *hs_state_str =
  540. circuit_purpose_to_controller_hs_state_string(purpose);
  541. const struct timeval *old_timestamp_began = tv;
  542. char tbuf[ISO_TIME_USEC_LEN+1];
  543. format_iso_time_nospace_usec(tbuf, old_timestamp_began);
  544. tor_snprintf(event_tail, sizeof(event_tail),
  545. " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
  546. circuit_purpose_to_controller_string(purpose),
  547. (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
  548. (hs_state_str != NULL) ? hs_state_str : "",
  549. tbuf);
  550. }
  551. break;
  552. default:
  553. log_warn(LD_BUG, "Unrecognized status code %d", (int)e);
  554. tor_fragile_assert();
  555. return 0;
  556. }
  557. {
  558. char *circdesc = circuit_describe_status_for_controller(circ);
  559. const char *sp = strlen(circdesc) ? " " : "";
  560. send_control_event(EVENT_CIRCUIT_STATUS_MINOR,
  561. "650 CIRC_MINOR %lu %s%s%s%s\r\n",
  562. (unsigned long)circ->global_identifier,
  563. event_desc, sp,
  564. circdesc,
  565. event_tail);
  566. tor_free(circdesc);
  567. }
  568. return 0;
  569. }
  570. /**
  571. * <b>circ</b> has changed its purpose from <b>old_purpose</b>: tell any
  572. * interested controllers.
  573. */
  574. int
  575. control_event_circuit_purpose_changed(origin_circuit_t *circ,
  576. int old_purpose)
  577. {
  578. return control_event_circuit_status_minor(circ,
  579. CIRC_MINOR_EVENT_PURPOSE_CHANGED,
  580. old_purpose,
  581. NULL);
  582. }
  583. /**
  584. * <b>circ</b> has changed its purpose from <b>old_purpose</b>, and its
  585. * created-time from <b>old_tv_created</b>: tell any interested controllers.
  586. */
  587. int
  588. control_event_circuit_cannibalized(origin_circuit_t *circ,
  589. int old_purpose,
  590. const struct timeval *old_tv_created)
  591. {
  592. return control_event_circuit_status_minor(circ,
  593. CIRC_MINOR_EVENT_CANNIBALIZED,
  594. old_purpose,
  595. old_tv_created);
  596. }
  597. /** Something has happened to the stream associated with AP connection
  598. * <b>conn</b>: tell any interested control connections. */
  599. int
  600. control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp,
  601. int reason_code)
  602. {
  603. char reason_buf[64];
  604. char addrport_buf[64];
  605. const char *status;
  606. circuit_t *circ;
  607. origin_circuit_t *origin_circ = NULL;
  608. char buf[256];
  609. const char *purpose = "";
  610. tor_assert(conn->socks_request);
  611. if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
  612. return 0;
  613. if (tp == STREAM_EVENT_CLOSED &&
  614. (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
  615. return 0;
  616. write_stream_target_to_buf(conn, buf, sizeof(buf));
  617. reason_buf[0] = '\0';
  618. switch (tp)
  619. {
  620. case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
  621. case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
  622. case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
  623. case STREAM_EVENT_FAILED: status = "FAILED"; break;
  624. case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
  625. case STREAM_EVENT_NEW: status = "NEW"; break;
  626. case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
  627. case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
  628. case STREAM_EVENT_REMAP: status = "REMAP"; break;
  629. default:
  630. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  631. return 0;
  632. }
  633. if (reason_code && (tp == STREAM_EVENT_FAILED ||
  634. tp == STREAM_EVENT_CLOSED ||
  635. tp == STREAM_EVENT_FAILED_RETRIABLE)) {
  636. const char *reason_str = stream_end_reason_to_control_string(reason_code);
  637. char *r = NULL;
  638. if (!reason_str) {
  639. tor_asprintf(&r, " UNKNOWN_%d", reason_code);
  640. reason_str = r;
  641. }
  642. if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
  643. tor_snprintf(reason_buf, sizeof(reason_buf),
  644. " REASON=END REMOTE_REASON=%s", reason_str);
  645. else
  646. tor_snprintf(reason_buf, sizeof(reason_buf),
  647. " REASON=%s", reason_str);
  648. tor_free(r);
  649. } else if (reason_code && tp == STREAM_EVENT_REMAP) {
  650. switch (reason_code) {
  651. case REMAP_STREAM_SOURCE_CACHE:
  652. strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
  653. break;
  654. case REMAP_STREAM_SOURCE_EXIT:
  655. strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
  656. break;
  657. default:
  658. tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
  659. reason_code);
  660. /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
  661. break;
  662. }
  663. }
  664. if (tp == STREAM_EVENT_NEW || tp == STREAM_EVENT_NEW_RESOLVE) {
  665. /*
  666. * When the control conn is an AF_UNIX socket and we have no address,
  667. * it gets set to "(Tor_internal)"; see dnsserv_launch_request() in
  668. * dnsserv.c.
  669. */
  670. if (strcmp(ENTRY_TO_CONN(conn)->address, "(Tor_internal)") != 0) {
  671. tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
  672. ENTRY_TO_CONN(conn)->address, ENTRY_TO_CONN(conn)->port);
  673. } else {
  674. /*
  675. * else leave it blank so control on AF_UNIX doesn't need to make
  676. * something up.
  677. */
  678. addrport_buf[0] = '\0';
  679. }
  680. } else {
  681. addrport_buf[0] = '\0';
  682. }
  683. if (tp == STREAM_EVENT_NEW_RESOLVE) {
  684. purpose = " PURPOSE=DNS_REQUEST";
  685. } else if (tp == STREAM_EVENT_NEW) {
  686. if (conn->use_begindir) {
  687. connection_t *linked = ENTRY_TO_CONN(conn)->linked_conn;
  688. int linked_dir_purpose = -1;
  689. if (linked && linked->type == CONN_TYPE_DIR)
  690. linked_dir_purpose = linked->purpose;
  691. if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
  692. purpose = " PURPOSE=DIR_UPLOAD";
  693. else
  694. purpose = " PURPOSE=DIR_FETCH";
  695. } else
  696. purpose = " PURPOSE=USER";
  697. }
  698. circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
  699. if (circ && CIRCUIT_IS_ORIGIN(circ))
  700. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  701. send_control_event(EVENT_STREAM_STATUS,
  702. "650 STREAM %"PRIu64" %s %lu %s%s%s%s\r\n",
  703. (ENTRY_TO_CONN(conn)->global_identifier),
  704. status,
  705. origin_circ?
  706. (unsigned long)origin_circ->global_identifier : 0ul,
  707. buf, reason_buf, addrport_buf, purpose);
  708. /* XXX need to specify its intended exit, etc? */
  709. return 0;
  710. }
  711. /** Called when the status of an OR connection <b>conn</b> changes: tell any
  712. * interested control connections. <b>tp</b> is the new status for the
  713. * connection. If <b>conn</b> has just closed or failed, then <b>reason</b>
  714. * may be the reason why.
  715. */
  716. int
  717. control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
  718. int reason)
  719. {
  720. int ncircs = 0;
  721. const char *status;
  722. char name[128];
  723. char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
  724. if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
  725. return 0;
  726. switch (tp)
  727. {
  728. case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
  729. case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
  730. case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
  731. case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
  732. case OR_CONN_EVENT_NEW: status = "NEW"; break;
  733. default:
  734. log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
  735. return 0;
  736. }
  737. if (conn->chan) {
  738. ncircs = circuit_count_pending_on_channel(TLS_CHAN_TO_BASE(conn->chan));
  739. } else {
  740. ncircs = 0;
  741. }
  742. ncircs += connection_or_get_num_circuits(conn);
  743. if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
  744. tor_snprintf(ncircs_buf, sizeof(ncircs_buf), " NCIRCS=%d", ncircs);
  745. }
  746. orconn_target_get_name(name, sizeof(name), conn);
  747. send_control_event(EVENT_OR_CONN_STATUS,
  748. "650 ORCONN %s %s%s%s%s ID=%"PRIu64"\r\n",
  749. name, status,
  750. reason ? " REASON=" : "",
  751. orconn_end_reason_to_control_string(reason),
  752. ncircs_buf,
  753. (conn->base_.global_identifier));
  754. return 0;
  755. }
  756. /**
  757. * Print out STREAM_BW event for a single conn
  758. */
  759. int
  760. control_event_stream_bandwidth(edge_connection_t *edge_conn)
  761. {
  762. struct timeval now;
  763. char tbuf[ISO_TIME_USEC_LEN+1];
  764. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  765. if (!edge_conn->n_read && !edge_conn->n_written)
  766. return 0;
  767. tor_gettimeofday(&now);
  768. format_iso_time_nospace_usec(tbuf, &now);
  769. send_control_event(EVENT_STREAM_BANDWIDTH_USED,
  770. "650 STREAM_BW %"PRIu64" %lu %lu %s\r\n",
  771. (edge_conn->base_.global_identifier),
  772. (unsigned long)edge_conn->n_read,
  773. (unsigned long)edge_conn->n_written,
  774. tbuf);
  775. edge_conn->n_written = edge_conn->n_read = 0;
  776. }
  777. return 0;
  778. }
  779. /** A second or more has elapsed: tell any interested control
  780. * connections how much bandwidth streams have used. */
  781. int
  782. control_event_stream_bandwidth_used(void)
  783. {
  784. if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
  785. smartlist_t *conns = get_connection_array();
  786. edge_connection_t *edge_conn;
  787. struct timeval now;
  788. char tbuf[ISO_TIME_USEC_LEN+1];
  789. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
  790. {
  791. if (conn->type != CONN_TYPE_AP)
  792. continue;
  793. edge_conn = TO_EDGE_CONN(conn);
  794. if (!edge_conn->n_read && !edge_conn->n_written)
  795. continue;
  796. tor_gettimeofday(&now);
  797. format_iso_time_nospace_usec(tbuf, &now);
  798. send_control_event(EVENT_STREAM_BANDWIDTH_USED,
  799. "650 STREAM_BW %"PRIu64" %lu %lu %s\r\n",
  800. (edge_conn->base_.global_identifier),
  801. (unsigned long)edge_conn->n_read,
  802. (unsigned long)edge_conn->n_written,
  803. tbuf);
  804. edge_conn->n_written = edge_conn->n_read = 0;
  805. }
  806. SMARTLIST_FOREACH_END(conn);
  807. }
  808. return 0;
  809. }
  810. /** A second or more has elapsed: tell any interested control connections
  811. * how much bandwidth origin circuits have used. */
  812. int
  813. control_event_circ_bandwidth_used(void)
  814. {
  815. if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
  816. return 0;
  817. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  818. if (!CIRCUIT_IS_ORIGIN(circ))
  819. continue;
  820. control_event_circ_bandwidth_used_for_circ(TO_ORIGIN_CIRCUIT(circ));
  821. }
  822. SMARTLIST_FOREACH_END(circ);
  823. return 0;
  824. }
  825. /**
  826. * Emit a CIRC_BW event line for a specific circuit.
  827. *
  828. * This function sets the values it emits to 0, and does not emit
  829. * an event if there is no new data to report since the last call.
  830. *
  831. * Therefore, it may be called at any frequency.
  832. */
  833. int
  834. control_event_circ_bandwidth_used_for_circ(origin_circuit_t *ocirc)
  835. {
  836. struct timeval now;
  837. char tbuf[ISO_TIME_USEC_LEN+1];
  838. tor_assert(ocirc);
  839. if (!EVENT_IS_INTERESTING(EVENT_CIRC_BANDWIDTH_USED))
  840. return 0;
  841. /* n_read_circ_bw and n_written_circ_bw are always updated
  842. * when there is any new cell on a circuit, and set to 0 after
  843. * the event, below.
  844. *
  845. * Therefore, checking them is sufficient to determine if there
  846. * is new data to report. */
  847. if (!ocirc->n_read_circ_bw && !ocirc->n_written_circ_bw)
  848. return 0;
  849. tor_gettimeofday(&now);
  850. format_iso_time_nospace_usec(tbuf, &now);
  851. send_control_event(EVENT_CIRC_BANDWIDTH_USED,
  852. "650 CIRC_BW ID=%d READ=%lu WRITTEN=%lu TIME=%s "
  853. "DELIVERED_READ=%lu OVERHEAD_READ=%lu "
  854. "DELIVERED_WRITTEN=%lu OVERHEAD_WRITTEN=%lu\r\n",
  855. ocirc->global_identifier,
  856. (unsigned long)ocirc->n_read_circ_bw,
  857. (unsigned long)ocirc->n_written_circ_bw,
  858. tbuf,
  859. (unsigned long)ocirc->n_delivered_read_circ_bw,
  860. (unsigned long)ocirc->n_overhead_read_circ_bw,
  861. (unsigned long)ocirc->n_delivered_written_circ_bw,
  862. (unsigned long)ocirc->n_overhead_written_circ_bw);
  863. ocirc->n_written_circ_bw = ocirc->n_read_circ_bw = 0;
  864. ocirc->n_overhead_written_circ_bw = ocirc->n_overhead_read_circ_bw = 0;
  865. ocirc->n_delivered_written_circ_bw = ocirc->n_delivered_read_circ_bw = 0;
  866. return 0;
  867. }
  868. /** Print out CONN_BW event for a single OR/DIR/EXIT <b>conn</b> and reset
  869. * bandwidth counters. */
  870. int
  871. control_event_conn_bandwidth(connection_t *conn)
  872. {
  873. const char *conn_type_str;
  874. if (!get_options()->TestingEnableConnBwEvent ||
  875. !EVENT_IS_INTERESTING(EVENT_CONN_BW))
  876. return 0;
  877. if (!conn->n_read_conn_bw && !conn->n_written_conn_bw)
  878. return 0;
  879. switch (conn->type) {
  880. case CONN_TYPE_OR:
  881. conn_type_str = "OR";
  882. break;
  883. case CONN_TYPE_DIR:
  884. conn_type_str = "DIR";
  885. break;
  886. case CONN_TYPE_EXIT:
  887. conn_type_str = "EXIT";
  888. break;
  889. default:
  890. return 0;
  891. }
  892. send_control_event(EVENT_CONN_BW,
  893. "650 CONN_BW ID=%"PRIu64" TYPE=%s "
  894. "READ=%lu WRITTEN=%lu\r\n",
  895. (conn->global_identifier),
  896. conn_type_str,
  897. (unsigned long)conn->n_read_conn_bw,
  898. (unsigned long)conn->n_written_conn_bw);
  899. conn->n_written_conn_bw = conn->n_read_conn_bw = 0;
  900. return 0;
  901. }
  902. /** A second or more has elapsed: tell any interested control
  903. * connections how much bandwidth connections have used. */
  904. int
  905. control_event_conn_bandwidth_used(void)
  906. {
  907. if (get_options()->TestingEnableConnBwEvent &&
  908. EVENT_IS_INTERESTING(EVENT_CONN_BW)) {
  909. SMARTLIST_FOREACH(get_connection_array(), connection_t *, conn,
  910. control_event_conn_bandwidth(conn));
  911. }
  912. return 0;
  913. }
  914. /** Helper: iterate over cell statistics of <b>circ</b> and sum up added
  915. * cells, removed cells, and waiting times by cell command and direction.
  916. * Store results in <b>cell_stats</b>. Free cell statistics of the
  917. * circuit afterwards. */
  918. void
  919. sum_up_cell_stats_by_command(circuit_t *circ, cell_stats_t *cell_stats)
  920. {
  921. memset(cell_stats, 0, sizeof(cell_stats_t));
  922. SMARTLIST_FOREACH_BEGIN(circ->testing_cell_stats,
  923. const testing_cell_stats_entry_t *, ent) {
  924. tor_assert(ent->command <= CELL_COMMAND_MAX_);
  925. if (!ent->removed && !ent->exitward) {
  926. cell_stats->added_cells_appward[ent->command] += 1;
  927. } else if (!ent->removed && ent->exitward) {
  928. cell_stats->added_cells_exitward[ent->command] += 1;
  929. } else if (!ent->exitward) {
  930. cell_stats->removed_cells_appward[ent->command] += 1;
  931. cell_stats->total_time_appward[ent->command] += ent->waiting_time * 10;
  932. } else {
  933. cell_stats->removed_cells_exitward[ent->command] += 1;
  934. cell_stats->total_time_exitward[ent->command] += ent->waiting_time * 10;
  935. }
  936. } SMARTLIST_FOREACH_END(ent);
  937. circuit_clear_testing_cell_stats(circ);
  938. }
  939. /** Helper: append a cell statistics string to <code>event_parts</code>,
  940. * prefixed with <code>key</code>=. Statistics consist of comma-separated
  941. * key:value pairs with lower-case command strings as keys and cell
  942. * numbers or total waiting times as values. A key:value pair is included
  943. * if the entry in <code>include_if_non_zero</code> is not zero, but with
  944. * the (possibly zero) entry from <code>number_to_include</code>. Both
  945. * arrays are expected to have a length of CELL_COMMAND_MAX_ + 1. If no
  946. * entry in <code>include_if_non_zero</code> is positive, no string will
  947. * be added to <code>event_parts</code>. */
  948. void
  949. append_cell_stats_by_command(smartlist_t *event_parts, const char *key,
  950. const uint64_t *include_if_non_zero,
  951. const uint64_t *number_to_include)
  952. {
  953. smartlist_t *key_value_strings = smartlist_new();
  954. int i;
  955. for (i = 0; i <= CELL_COMMAND_MAX_; i++) {
  956. if (include_if_non_zero[i] > 0) {
  957. smartlist_add_asprintf(key_value_strings, "%s:%"PRIu64,
  958. cell_command_to_string(i),
  959. (number_to_include[i]));
  960. }
  961. }
  962. if (smartlist_len(key_value_strings) > 0) {
  963. char *joined = smartlist_join_strings(key_value_strings, ",", 0, NULL);
  964. smartlist_add_asprintf(event_parts, "%s=%s", key, joined);
  965. SMARTLIST_FOREACH(key_value_strings, char *, cp, tor_free(cp));
  966. tor_free(joined);
  967. }
  968. smartlist_free(key_value_strings);
  969. }
  970. /** Helper: format <b>cell_stats</b> for <b>circ</b> for inclusion in a
  971. * CELL_STATS event and write result string to <b>event_string</b>. */
  972. void
  973. format_cell_stats(char **event_string, circuit_t *circ,
  974. cell_stats_t *cell_stats)
  975. {
  976. smartlist_t *event_parts = smartlist_new();
  977. if (CIRCUIT_IS_ORIGIN(circ)) {
  978. origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  979. smartlist_add_asprintf(event_parts, "ID=%lu",
  980. (unsigned long)ocirc->global_identifier);
  981. } else if (TO_OR_CIRCUIT(circ)->p_chan) {
  982. or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  983. smartlist_add_asprintf(event_parts, "InboundQueue=%lu",
  984. (unsigned long)or_circ->p_circ_id);
  985. smartlist_add_asprintf(event_parts, "InboundConn=%"PRIu64,
  986. (or_circ->p_chan->global_identifier));
  987. append_cell_stats_by_command(event_parts, "InboundAdded",
  988. cell_stats->added_cells_appward,
  989. cell_stats->added_cells_appward);
  990. append_cell_stats_by_command(event_parts, "InboundRemoved",
  991. cell_stats->removed_cells_appward,
  992. cell_stats->removed_cells_appward);
  993. append_cell_stats_by_command(event_parts, "InboundTime",
  994. cell_stats->removed_cells_appward,
  995. cell_stats->total_time_appward);
  996. }
  997. if (circ->n_chan) {
  998. smartlist_add_asprintf(event_parts, "OutboundQueue=%lu",
  999. (unsigned long)circ->n_circ_id);
  1000. smartlist_add_asprintf(event_parts, "OutboundConn=%"PRIu64,
  1001. (circ->n_chan->global_identifier));
  1002. append_cell_stats_by_command(event_parts, "OutboundAdded",
  1003. cell_stats->added_cells_exitward,
  1004. cell_stats->added_cells_exitward);
  1005. append_cell_stats_by_command(event_parts, "OutboundRemoved",
  1006. cell_stats->removed_cells_exitward,
  1007. cell_stats->removed_cells_exitward);
  1008. append_cell_stats_by_command(event_parts, "OutboundTime",
  1009. cell_stats->removed_cells_exitward,
  1010. cell_stats->total_time_exitward);
  1011. }
  1012. *event_string = smartlist_join_strings(event_parts, " ", 0, NULL);
  1013. SMARTLIST_FOREACH(event_parts, char *, cp, tor_free(cp));
  1014. smartlist_free(event_parts);
  1015. }
  1016. /** A second or more has elapsed: tell any interested control connection
  1017. * how many cells have been processed for a given circuit. */
  1018. int
  1019. control_event_circuit_cell_stats(void)
  1020. {
  1021. cell_stats_t *cell_stats;
  1022. char *event_string;
  1023. if (!get_options()->TestingEnableCellStatsEvent ||
  1024. !EVENT_IS_INTERESTING(EVENT_CELL_STATS))
  1025. return 0;
  1026. cell_stats = tor_malloc(sizeof(cell_stats_t));
  1027. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, circ) {
  1028. if (!circ->testing_cell_stats)
  1029. continue;
  1030. sum_up_cell_stats_by_command(circ, cell_stats);
  1031. format_cell_stats(&event_string, circ, cell_stats);
  1032. send_control_event(EVENT_CELL_STATS,
  1033. "650 CELL_STATS %s\r\n", event_string);
  1034. tor_free(event_string);
  1035. }
  1036. SMARTLIST_FOREACH_END(circ);
  1037. tor_free(cell_stats);
  1038. return 0;
  1039. }
  1040. /* about 5 minutes worth. */
  1041. #define N_BW_EVENTS_TO_CACHE 300
  1042. /* Index into cached_bw_events to next write. */
  1043. static int next_measurement_idx = 0;
  1044. /* number of entries set in n_measurements */
  1045. static int n_measurements = 0;
  1046. static struct cached_bw_event_s {
  1047. uint32_t n_read;
  1048. uint32_t n_written;
  1049. } cached_bw_events[N_BW_EVENTS_TO_CACHE];
  1050. /** A second or more has elapsed: tell any interested control
  1051. * connections how much bandwidth we used. */
  1052. int
  1053. control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
  1054. {
  1055. cached_bw_events[next_measurement_idx].n_read = n_read;
  1056. cached_bw_events[next_measurement_idx].n_written = n_written;
  1057. if (++next_measurement_idx == N_BW_EVENTS_TO_CACHE)
  1058. next_measurement_idx = 0;
  1059. if (n_measurements < N_BW_EVENTS_TO_CACHE)
  1060. ++n_measurements;
  1061. if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
  1062. send_control_event(EVENT_BANDWIDTH_USED,
  1063. "650 BW %lu %lu\r\n",
  1064. (unsigned long)n_read,
  1065. (unsigned long)n_written);
  1066. }
  1067. return 0;
  1068. }
  1069. char *
  1070. get_bw_samples(void)
  1071. {
  1072. int i;
  1073. int idx = (next_measurement_idx + N_BW_EVENTS_TO_CACHE - n_measurements)
  1074. % N_BW_EVENTS_TO_CACHE;
  1075. tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
  1076. smartlist_t *elements = smartlist_new();
  1077. for (i = 0; i < n_measurements; ++i) {
  1078. tor_assert(0 <= idx && idx < N_BW_EVENTS_TO_CACHE);
  1079. const struct cached_bw_event_s *bwe = &cached_bw_events[idx];
  1080. smartlist_add_asprintf(elements, "%u,%u",
  1081. (unsigned)bwe->n_read,
  1082. (unsigned)bwe->n_written);
  1083. idx = (idx + 1) % N_BW_EVENTS_TO_CACHE;
  1084. }
  1085. char *result = smartlist_join_strings(elements, " ", 0, NULL);
  1086. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  1087. smartlist_free(elements);
  1088. return result;
  1089. }
  1090. /** Called when we are sending a log message to the controllers: suspend
  1091. * sending further log messages to the controllers until we're done. Used by
  1092. * CONN_LOG_PROTECT. */
  1093. void
  1094. disable_control_logging(void)
  1095. {
  1096. ++disable_log_messages;
  1097. }
  1098. /** We're done sending a log message to the controllers: re-enable controller
  1099. * logging. Used by CONN_LOG_PROTECT. */
  1100. void
  1101. enable_control_logging(void)
  1102. {
  1103. if (--disable_log_messages < 0)
  1104. tor_assert(0);
  1105. }
  1106. /** We got a log message: tell any interested control connections. */
  1107. void
  1108. control_event_logmsg(int severity, uint32_t domain, const char *msg)
  1109. {
  1110. int event;
  1111. /* Don't even think of trying to add stuff to a buffer from a cpuworker
  1112. * thread. (See #25987 for plan to fix.) */
  1113. if (! in_main_thread())
  1114. return;
  1115. if (disable_log_messages)
  1116. return;
  1117. if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
  1118. severity <= LOG_NOTICE) {
  1119. char *esc = esc_for_log(msg);
  1120. ++disable_log_messages;
  1121. control_event_general_status(severity, "BUG REASON=%s", esc);
  1122. --disable_log_messages;
  1123. tor_free(esc);
  1124. }
  1125. event = log_severity_to_event(severity);
  1126. if (event >= 0 && EVENT_IS_INTERESTING(event)) {
  1127. char *b = NULL;
  1128. const char *s;
  1129. if (strchr(msg, '\n')) {
  1130. char *cp;
  1131. b = tor_strdup(msg);
  1132. for (cp = b; *cp; ++cp)
  1133. if (*cp == '\r' || *cp == '\n')
  1134. *cp = ' ';
  1135. }
  1136. switch (severity) {
  1137. case LOG_DEBUG: s = "DEBUG"; break;
  1138. case LOG_INFO: s = "INFO"; break;
  1139. case LOG_NOTICE: s = "NOTICE"; break;
  1140. case LOG_WARN: s = "WARN"; break;
  1141. case LOG_ERR: s = "ERR"; break;
  1142. default: s = "UnknownLogSeverity"; break;
  1143. }
  1144. ++disable_log_messages;
  1145. send_control_event(event, "650 %s %s\r\n", s, b?b:msg);
  1146. if (severity == LOG_ERR) {
  1147. /* Force a flush, since we may be about to die horribly */
  1148. queued_events_flush_all(1);
  1149. }
  1150. --disable_log_messages;
  1151. tor_free(b);
  1152. }
  1153. }
  1154. /**
  1155. * Logging callback: called when there is a queued pending log callback.
  1156. */
  1157. void
  1158. control_event_logmsg_pending(void)
  1159. {
  1160. if (! in_main_thread()) {
  1161. /* We can't handle this case yet, since we're using a
  1162. * mainloop_event_t to invoke queued_events_flush_all. We ought to
  1163. * use a different mechanism instead: see #25987.
  1164. **/
  1165. return;
  1166. }
  1167. tor_assert(flush_queued_events_event);
  1168. mainloop_event_activate(flush_queued_events_event);
  1169. }
  1170. /** Called whenever we receive new router descriptors: tell any
  1171. * interested control connections. <b>routers</b> is a list of
  1172. * routerinfo_t's.
  1173. */
  1174. int
  1175. control_event_descriptors_changed(smartlist_t *routers)
  1176. {
  1177. char *msg;
  1178. if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
  1179. return 0;
  1180. {
  1181. smartlist_t *names = smartlist_new();
  1182. char *ids;
  1183. SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
  1184. char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
  1185. router_get_verbose_nickname(b, ri);
  1186. smartlist_add(names, b);
  1187. });
  1188. ids = smartlist_join_strings(names, " ", 0, NULL);
  1189. tor_asprintf(&msg, "650 NEWDESC %s\r\n", ids);
  1190. send_control_event_string(EVENT_NEW_DESC, msg);
  1191. tor_free(ids);
  1192. tor_free(msg);
  1193. SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
  1194. smartlist_free(names);
  1195. }
  1196. return 0;
  1197. }
  1198. /** Called when an address mapping on <b>from</b> from changes to <b>to</b>.
  1199. * <b>expires</b> values less than 3 are special; see connection_edge.c. If
  1200. * <b>error</b> is non-NULL, it is an error code describing the failure
  1201. * mode of the mapping.
  1202. */
  1203. int
  1204. control_event_address_mapped(const char *from, const char *to, time_t expires,
  1205. const char *error, const int cached)
  1206. {
  1207. if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
  1208. return 0;
  1209. if (expires < 3 || expires == TIME_MAX)
  1210. send_control_event(EVENT_ADDRMAP,
  1211. "650 ADDRMAP %s %s NEVER %s%s"
  1212. "CACHED=\"%s\"\r\n",
  1213. from, to, error?error:"", error?" ":"",
  1214. cached?"YES":"NO");
  1215. else {
  1216. char buf[ISO_TIME_LEN+1];
  1217. char buf2[ISO_TIME_LEN+1];
  1218. format_local_iso_time(buf,expires);
  1219. format_iso_time(buf2,expires);
  1220. send_control_event(EVENT_ADDRMAP,
  1221. "650 ADDRMAP %s %s \"%s\""
  1222. " %s%sEXPIRES=\"%s\" CACHED=\"%s\"\r\n",
  1223. from, to, buf,
  1224. error?error:"", error?" ":"",
  1225. buf2, cached?"YES":"NO");
  1226. }
  1227. return 0;
  1228. }
  1229. /** The network liveness has changed; this is called from circuitstats.c
  1230. * whenever we receive a cell, or when timeout expires and we assume the
  1231. * network is down. */
  1232. int
  1233. control_event_network_liveness_update(int liveness)
  1234. {
  1235. if (liveness > 0) {
  1236. if (get_cached_network_liveness() <= 0) {
  1237. /* Update cached liveness */
  1238. set_cached_network_liveness(1);
  1239. log_debug(LD_CONTROL, "Sending NETWORK_LIVENESS UP");
  1240. send_control_event_string(EVENT_NETWORK_LIVENESS,
  1241. "650 NETWORK_LIVENESS UP\r\n");
  1242. }
  1243. /* else was already live, no-op */
  1244. } else {
  1245. if (get_cached_network_liveness() > 0) {
  1246. /* Update cached liveness */
  1247. set_cached_network_liveness(0);
  1248. log_debug(LD_CONTROL, "Sending NETWORK_LIVENESS DOWN");
  1249. send_control_event_string(EVENT_NETWORK_LIVENESS,
  1250. "650 NETWORK_LIVENESS DOWN\r\n");
  1251. }
  1252. /* else was already dead, no-op */
  1253. }
  1254. return 0;
  1255. }
  1256. /** Helper function for NS-style events. Constructs and sends an event
  1257. * of type <b>event</b> with string <b>event_string</b> out of the set of
  1258. * networkstatuses <b>statuses</b>. Currently it is used for NS events
  1259. * and NEWCONSENSUS events. */
  1260. static int
  1261. control_event_networkstatus_changed_helper(smartlist_t *statuses,
  1262. uint16_t event,
  1263. const char *event_string)
  1264. {
  1265. smartlist_t *strs;
  1266. char *s, *esc = NULL;
  1267. if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
  1268. return 0;
  1269. strs = smartlist_new();
  1270. smartlist_add_strdup(strs, "650+");
  1271. smartlist_add_strdup(strs, event_string);
  1272. smartlist_add_strdup(strs, "\r\n");
  1273. SMARTLIST_FOREACH(statuses, const routerstatus_t *, rs,
  1274. {
  1275. s = networkstatus_getinfo_helper_single(rs);
  1276. if (!s) continue;
  1277. smartlist_add(strs, s);
  1278. });
  1279. s = smartlist_join_strings(strs, "", 0, NULL);
  1280. write_escaped_data(s, strlen(s), &esc);
  1281. SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
  1282. smartlist_free(strs);
  1283. tor_free(s);
  1284. send_control_event_string(event, esc);
  1285. send_control_event_string(event,
  1286. "650 OK\r\n");
  1287. tor_free(esc);
  1288. return 0;
  1289. }
  1290. /** Called when the routerstatus_ts <b>statuses</b> have changed: sends
  1291. * an NS event to any controller that cares. */
  1292. int
  1293. control_event_networkstatus_changed(smartlist_t *statuses)
  1294. {
  1295. return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
  1296. }
  1297. /** Called when we get a new consensus networkstatus. Sends a NEWCONSENSUS
  1298. * event consisting of an NS-style line for each relay in the consensus. */
  1299. int
  1300. control_event_newconsensus(const networkstatus_t *consensus)
  1301. {
  1302. if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
  1303. return 0;
  1304. return control_event_networkstatus_changed_helper(
  1305. consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
  1306. }
  1307. /** Called when we compute a new circuitbuildtimeout */
  1308. int
  1309. control_event_buildtimeout_set(buildtimeout_set_event_t type,
  1310. const char *args)
  1311. {
  1312. const char *type_string = NULL;
  1313. if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
  1314. return 0;
  1315. switch (type) {
  1316. case BUILDTIMEOUT_SET_EVENT_COMPUTED:
  1317. type_string = "COMPUTED";
  1318. break;
  1319. case BUILDTIMEOUT_SET_EVENT_RESET:
  1320. type_string = "RESET";
  1321. break;
  1322. case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
  1323. type_string = "SUSPENDED";
  1324. break;
  1325. case BUILDTIMEOUT_SET_EVENT_DISCARD:
  1326. type_string = "DISCARD";
  1327. break;
  1328. case BUILDTIMEOUT_SET_EVENT_RESUME:
  1329. type_string = "RESUME";
  1330. break;
  1331. default:
  1332. type_string = "UNKNOWN";
  1333. break;
  1334. }
  1335. send_control_event(EVENT_BUILDTIMEOUT_SET,
  1336. "650 BUILDTIMEOUT_SET %s %s\r\n",
  1337. type_string, args);
  1338. return 0;
  1339. }
  1340. /** Called when a signal has been processed from signal_callback */
  1341. int
  1342. control_event_signal(uintptr_t signal_num)
  1343. {
  1344. const char *signal_string = NULL;
  1345. if (!control_event_is_interesting(EVENT_GOT_SIGNAL))
  1346. return 0;
  1347. switch (signal_num) {
  1348. case SIGHUP:
  1349. signal_string = "RELOAD";
  1350. break;
  1351. case SIGUSR1:
  1352. signal_string = "DUMP";
  1353. break;
  1354. case SIGUSR2:
  1355. signal_string = "DEBUG";
  1356. break;
  1357. case SIGNEWNYM:
  1358. signal_string = "NEWNYM";
  1359. break;
  1360. case SIGCLEARDNSCACHE:
  1361. signal_string = "CLEARDNSCACHE";
  1362. break;
  1363. case SIGHEARTBEAT:
  1364. signal_string = "HEARTBEAT";
  1365. break;
  1366. default:
  1367. log_warn(LD_BUG, "Unrecognized signal %lu in control_event_signal",
  1368. (unsigned long)signal_num);
  1369. return -1;
  1370. }
  1371. send_control_event(EVENT_GOT_SIGNAL, "650 SIGNAL %s\r\n",
  1372. signal_string);
  1373. return 0;
  1374. }
  1375. /** Called when a single local_routerstatus_t has changed: Sends an NS event
  1376. * to any controller that cares. */
  1377. int
  1378. control_event_networkstatus_changed_single(const routerstatus_t *rs)
  1379. {
  1380. smartlist_t *statuses;
  1381. int r;
  1382. if (!EVENT_IS_INTERESTING(EVENT_NS))
  1383. return 0;
  1384. statuses = smartlist_new();
  1385. smartlist_add(statuses, (void*)rs);
  1386. r = control_event_networkstatus_changed(statuses);
  1387. smartlist_free(statuses);
  1388. return r;
  1389. }
  1390. /** Our own router descriptor has changed; tell any controllers that care.
  1391. */
  1392. int
  1393. control_event_my_descriptor_changed(void)
  1394. {
  1395. send_control_event(EVENT_DESCCHANGED, "650 DESCCHANGED\r\n");
  1396. return 0;
  1397. }
  1398. /** Helper: sends a status event where <b>type</b> is one of
  1399. * EVENT_STATUS_{GENERAL,CLIENT,SERVER}, where <b>severity</b> is one of
  1400. * LOG_{NOTICE,WARN,ERR}, and where <b>format</b> is a printf-style format
  1401. * string corresponding to <b>args</b>. */
  1402. static int
  1403. control_event_status(int type, int severity, const char *format, va_list args)
  1404. {
  1405. char *user_buf = NULL;
  1406. char format_buf[160];
  1407. const char *status, *sev;
  1408. switch (type) {
  1409. case EVENT_STATUS_GENERAL:
  1410. status = "STATUS_GENERAL";
  1411. break;
  1412. case EVENT_STATUS_CLIENT:
  1413. status = "STATUS_CLIENT";
  1414. break;
  1415. case EVENT_STATUS_SERVER:
  1416. status = "STATUS_SERVER";
  1417. break;
  1418. default:
  1419. log_warn(LD_BUG, "Unrecognized status type %d", type);
  1420. return -1;
  1421. }
  1422. switch (severity) {
  1423. case LOG_NOTICE:
  1424. sev = "NOTICE";
  1425. break;
  1426. case LOG_WARN:
  1427. sev = "WARN";
  1428. break;
  1429. case LOG_ERR:
  1430. sev = "ERR";
  1431. break;
  1432. default:
  1433. log_warn(LD_BUG, "Unrecognized status severity %d", severity);
  1434. return -1;
  1435. }
  1436. if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s",
  1437. status, sev)<0) {
  1438. log_warn(LD_BUG, "Format string too long.");
  1439. return -1;
  1440. }
  1441. tor_vasprintf(&user_buf, format, args);
  1442. send_control_event(type, "%s %s\r\n", format_buf, user_buf);
  1443. tor_free(user_buf);
  1444. return 0;
  1445. }
  1446. #define CONTROL_EVENT_STATUS_BODY(event, sev) \
  1447. int r; \
  1448. do { \
  1449. va_list ap; \
  1450. if (!EVENT_IS_INTERESTING(event)) \
  1451. return 0; \
  1452. \
  1453. va_start(ap, format); \
  1454. r = control_event_status((event), (sev), format, ap); \
  1455. va_end(ap); \
  1456. } while (0)
  1457. /** Format and send an EVENT_STATUS_GENERAL event whose main text is obtained
  1458. * by formatting the arguments using the printf-style <b>format</b>. */
  1459. int
  1460. control_event_general_status(int severity, const char *format, ...)
  1461. {
  1462. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL, severity);
  1463. return r;
  1464. }
  1465. /** Format and send an EVENT_STATUS_GENERAL LOG_ERR event, and flush it to the
  1466. * controller(s) immediately. */
  1467. int
  1468. control_event_general_error(const char *format, ...)
  1469. {
  1470. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_GENERAL, LOG_ERR);
  1471. /* Force a flush, since we may be about to die horribly */
  1472. queued_events_flush_all(1);
  1473. return r;
  1474. }
  1475. /** Format and send an EVENT_STATUS_CLIENT event whose main text is obtained
  1476. * by formatting the arguments using the printf-style <b>format</b>. */
  1477. int
  1478. control_event_client_status(int severity, const char *format, ...)
  1479. {
  1480. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT, severity);
  1481. return r;
  1482. }
  1483. /** Format and send an EVENT_STATUS_CLIENT LOG_ERR event, and flush it to the
  1484. * controller(s) immediately. */
  1485. int
  1486. control_event_client_error(const char *format, ...)
  1487. {
  1488. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_CLIENT, LOG_ERR);
  1489. /* Force a flush, since we may be about to die horribly */
  1490. queued_events_flush_all(1);
  1491. return r;
  1492. }
  1493. /** Format and send an EVENT_STATUS_SERVER event whose main text is obtained
  1494. * by formatting the arguments using the printf-style <b>format</b>. */
  1495. int
  1496. control_event_server_status(int severity, const char *format, ...)
  1497. {
  1498. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER, severity);
  1499. return r;
  1500. }
  1501. /** Format and send an EVENT_STATUS_SERVER LOG_ERR event, and flush it to the
  1502. * controller(s) immediately. */
  1503. int
  1504. control_event_server_error(const char *format, ...)
  1505. {
  1506. CONTROL_EVENT_STATUS_BODY(EVENT_STATUS_SERVER, LOG_ERR);
  1507. /* Force a flush, since we may be about to die horribly */
  1508. queued_events_flush_all(1);
  1509. return r;
  1510. }
  1511. /** Called when the status of an entry guard with the given <b>nickname</b>
  1512. * and identity <b>digest</b> has changed to <b>status</b>: tells any
  1513. * controllers that care. */
  1514. int
  1515. control_event_guard(const char *nickname, const char *digest,
  1516. const char *status)
  1517. {
  1518. char hbuf[HEX_DIGEST_LEN+1];
  1519. base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
  1520. if (!EVENT_IS_INTERESTING(EVENT_GUARD))
  1521. return 0;
  1522. {
  1523. char buf[MAX_VERBOSE_NICKNAME_LEN+1];
  1524. const node_t *node = node_get_by_id(digest);
  1525. if (node) {
  1526. node_get_verbose_nickname(node, buf);
  1527. } else {
  1528. tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
  1529. }
  1530. send_control_event(EVENT_GUARD,
  1531. "650 GUARD ENTRY %s %s\r\n", buf, status);
  1532. }
  1533. return 0;
  1534. }
  1535. /** Called when a configuration option changes. This is generally triggered
  1536. * by SETCONF requests and RELOAD/SIGHUP signals. The <b>elements</b> is
  1537. * a smartlist_t containing (key, value, ...) pairs in sequence.
  1538. * <b>value</b> can be NULL. */
  1539. int
  1540. control_event_conf_changed(const smartlist_t *elements)
  1541. {
  1542. int i;
  1543. char *result;
  1544. smartlist_t *lines;
  1545. if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED) ||
  1546. smartlist_len(elements) == 0) {
  1547. return 0;
  1548. }
  1549. lines = smartlist_new();
  1550. for (i = 0; i < smartlist_len(elements); i += 2) {
  1551. char *k = smartlist_get(elements, i);
  1552. char *v = smartlist_get(elements, i+1);
  1553. if (v == NULL) {
  1554. smartlist_add_asprintf(lines, "650-%s", k);
  1555. } else {
  1556. smartlist_add_asprintf(lines, "650-%s=%s", k, v);
  1557. }
  1558. }
  1559. result = smartlist_join_strings(lines, "\r\n", 0, NULL);
  1560. send_control_event(EVENT_CONF_CHANGED,
  1561. "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result);
  1562. tor_free(result);
  1563. SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
  1564. smartlist_free(lines);
  1565. return 0;
  1566. }
  1567. /** We just generated a new summary of which countries we've seen clients
  1568. * from recently. Send a copy to the controller in case it wants to
  1569. * display it for the user. */
  1570. void
  1571. control_event_clients_seen(const char *controller_str)
  1572. {
  1573. send_control_event(EVENT_CLIENTS_SEEN,
  1574. "650 CLIENTS_SEEN %s\r\n", controller_str);
  1575. }
  1576. /** A new pluggable transport called <b>transport_name</b> was
  1577. * launched on <b>addr</b>:<b>port</b>. <b>mode</b> is either
  1578. * "server" or "client" depending on the mode of the pluggable
  1579. * transport.
  1580. * "650" SP "TRANSPORT_LAUNCHED" SP Mode SP Name SP Address SP Port
  1581. */
  1582. void
  1583. control_event_transport_launched(const char *mode, const char *transport_name,
  1584. tor_addr_t *addr, uint16_t port)
  1585. {
  1586. send_control_event(EVENT_TRANSPORT_LAUNCHED,
  1587. "650 TRANSPORT_LAUNCHED %s %s %s %u\r\n",
  1588. mode, transport_name, fmt_addr(addr), port);
  1589. }
  1590. /** A pluggable transport called <b>pt_name</b> has emitted a log message
  1591. * found in <b>message</b> at <b>severity</b> log level. */
  1592. void
  1593. control_event_pt_log(const char *log)
  1594. {
  1595. send_control_event(EVENT_PT_LOG,
  1596. "650 PT_LOG %s\r\n",
  1597. log);
  1598. }
  1599. /** A pluggable transport has emitted a STATUS message found in
  1600. * <b>status</b>. */
  1601. void
  1602. control_event_pt_status(const char *status)
  1603. {
  1604. send_control_event(EVENT_PT_STATUS,
  1605. "650 PT_STATUS %s\r\n",
  1606. status);
  1607. }
  1608. /** Convert rendezvous auth type to string for HS_DESC control events
  1609. */
  1610. const char *
  1611. rend_auth_type_to_string(rend_auth_type_t auth_type)
  1612. {
  1613. const char *str;
  1614. switch (auth_type) {
  1615. case REND_NO_AUTH:
  1616. str = "NO_AUTH";
  1617. break;
  1618. case REND_BASIC_AUTH:
  1619. str = "BASIC_AUTH";
  1620. break;
  1621. case REND_STEALTH_AUTH:
  1622. str = "STEALTH_AUTH";
  1623. break;
  1624. default:
  1625. str = "UNKNOWN";
  1626. }
  1627. return str;
  1628. }
  1629. /** Return either the onion address if the given pointer is a non empty
  1630. * string else the unknown string. */
  1631. static const char *
  1632. rend_hsaddress_str_or_unknown(const char *onion_address)
  1633. {
  1634. static const char *str_unknown = "UNKNOWN";
  1635. const char *str_ret = str_unknown;
  1636. /* No valid pointer, unknown it is. */
  1637. if (!onion_address) {
  1638. goto end;
  1639. }
  1640. /* Empty onion address thus we don't know, unknown it is. */
  1641. if (onion_address[0] == '\0') {
  1642. goto end;
  1643. }
  1644. /* All checks are good so return the given onion address. */
  1645. str_ret = onion_address;
  1646. end:
  1647. return str_ret;
  1648. }
  1649. /** send HS_DESC requested event.
  1650. *
  1651. * <b>rend_query</b> is used to fetch requested onion address and auth type.
  1652. * <b>hs_dir</b> is the description of contacting hs directory.
  1653. * <b>desc_id_base32</b> is the ID of requested hs descriptor.
  1654. * <b>hsdir_index</b> is the HSDir fetch index value for v3, an hex string.
  1655. */
  1656. void
  1657. control_event_hs_descriptor_requested(const char *onion_address,
  1658. rend_auth_type_t auth_type,
  1659. const char *id_digest,
  1660. const char *desc_id,
  1661. const char *hsdir_index)
  1662. {
  1663. char *hsdir_index_field = NULL;
  1664. if (BUG(!id_digest || !desc_id)) {
  1665. return;
  1666. }
  1667. if (hsdir_index) {
  1668. tor_asprintf(&hsdir_index_field, " HSDIR_INDEX=%s", hsdir_index);
  1669. }
  1670. send_control_event(EVENT_HS_DESC,
  1671. "650 HS_DESC REQUESTED %s %s %s %s%s\r\n",
  1672. rend_hsaddress_str_or_unknown(onion_address),
  1673. rend_auth_type_to_string(auth_type),
  1674. node_describe_longname_by_id(id_digest),
  1675. desc_id,
  1676. hsdir_index_field ? hsdir_index_field : "");
  1677. tor_free(hsdir_index_field);
  1678. }
  1679. /** send HS_DESC CREATED event when a local service generates a descriptor.
  1680. *
  1681. * <b>onion_address</b> is service address.
  1682. * <b>desc_id</b> is the descriptor ID.
  1683. * <b>replica</b> is the the descriptor replica number. If it is negative, it
  1684. * is ignored.
  1685. */
  1686. void
  1687. control_event_hs_descriptor_created(const char *onion_address,
  1688. const char *desc_id,
  1689. int replica)
  1690. {
  1691. char *replica_field = NULL;
  1692. if (BUG(!onion_address || !desc_id)) {
  1693. return;
  1694. }
  1695. if (replica >= 0) {
  1696. tor_asprintf(&replica_field, " REPLICA=%d", replica);
  1697. }
  1698. send_control_event(EVENT_HS_DESC,
  1699. "650 HS_DESC CREATED %s UNKNOWN UNKNOWN %s%s\r\n",
  1700. onion_address, desc_id,
  1701. replica_field ? replica_field : "");
  1702. tor_free(replica_field);
  1703. }
  1704. /** send HS_DESC upload event.
  1705. *
  1706. * <b>onion_address</b> is service address.
  1707. * <b>hs_dir</b> is the description of contacting hs directory.
  1708. * <b>desc_id</b> is the ID of requested hs descriptor.
  1709. */
  1710. void
  1711. control_event_hs_descriptor_upload(const char *onion_address,
  1712. const char *id_digest,
  1713. const char *desc_id,
  1714. const char *hsdir_index)
  1715. {
  1716. char *hsdir_index_field = NULL;
  1717. if (BUG(!onion_address || !id_digest || !desc_id)) {
  1718. return;
  1719. }
  1720. if (hsdir_index) {
  1721. tor_asprintf(&hsdir_index_field, " HSDIR_INDEX=%s", hsdir_index);
  1722. }
  1723. send_control_event(EVENT_HS_DESC,
  1724. "650 HS_DESC UPLOAD %s UNKNOWN %s %s%s\r\n",
  1725. onion_address,
  1726. node_describe_longname_by_id(id_digest),
  1727. desc_id,
  1728. hsdir_index_field ? hsdir_index_field : "");
  1729. tor_free(hsdir_index_field);
  1730. }
  1731. /** send HS_DESC event after got response from hs directory.
  1732. *
  1733. * NOTE: this is an internal function used by following functions:
  1734. * control_event_hsv2_descriptor_received
  1735. * control_event_hsv2_descriptor_failed
  1736. * control_event_hsv3_descriptor_failed
  1737. *
  1738. * So do not call this function directly.
  1739. */
  1740. static void
  1741. event_hs_descriptor_receive_end(const char *action,
  1742. const char *onion_address,
  1743. const char *desc_id,
  1744. rend_auth_type_t auth_type,
  1745. const char *hsdir_id_digest,
  1746. const char *reason)
  1747. {
  1748. char *reason_field = NULL;
  1749. if (BUG(!action || !onion_address)) {
  1750. return;
  1751. }
  1752. if (reason) {
  1753. tor_asprintf(&reason_field, " REASON=%s", reason);
  1754. }
  1755. send_control_event(EVENT_HS_DESC,
  1756. "650 HS_DESC %s %s %s %s%s%s\r\n",
  1757. action,
  1758. rend_hsaddress_str_or_unknown(onion_address),
  1759. rend_auth_type_to_string(auth_type),
  1760. hsdir_id_digest ?
  1761. node_describe_longname_by_id(hsdir_id_digest) :
  1762. "UNKNOWN",
  1763. desc_id ? desc_id : "",
  1764. reason_field ? reason_field : "");
  1765. tor_free(reason_field);
  1766. }
  1767. /** send HS_DESC event after got response from hs directory.
  1768. *
  1769. * NOTE: this is an internal function used by following functions:
  1770. * control_event_hs_descriptor_uploaded
  1771. * control_event_hs_descriptor_upload_failed
  1772. *
  1773. * So do not call this function directly.
  1774. */
  1775. void
  1776. control_event_hs_descriptor_upload_end(const char *action,
  1777. const char *onion_address,
  1778. const char *id_digest,
  1779. const char *reason)
  1780. {
  1781. char *reason_field = NULL;
  1782. if (BUG(!action || !id_digest)) {
  1783. return;
  1784. }
  1785. if (reason) {
  1786. tor_asprintf(&reason_field, " REASON=%s", reason);
  1787. }
  1788. send_control_event(EVENT_HS_DESC,
  1789. "650 HS_DESC %s %s UNKNOWN %s%s\r\n",
  1790. action,
  1791. rend_hsaddress_str_or_unknown(onion_address),
  1792. node_describe_longname_by_id(id_digest),
  1793. reason_field ? reason_field : "");
  1794. tor_free(reason_field);
  1795. }
  1796. /** For an HS descriptor query <b>rend_data</b>, using the
  1797. * <b>onion_address</b> and HSDir fingerprint <b>hsdir_fp</b>, find out
  1798. * which descriptor ID in the query is the right one.
  1799. *
  1800. * Return a pointer of the binary descriptor ID found in the query's object
  1801. * or NULL if not found. */
  1802. static const char *
  1803. get_desc_id_from_query(const rend_data_t *rend_data, const char *hsdir_fp)
  1804. {
  1805. int replica;
  1806. const char *desc_id = NULL;
  1807. const rend_data_v2_t *rend_data_v2 = TO_REND_DATA_V2(rend_data);
  1808. /* Possible if the fetch was done using a descriptor ID. This means that
  1809. * the HSFETCH command was used. */
  1810. if (!tor_digest_is_zero(rend_data_v2->desc_id_fetch)) {
  1811. desc_id = rend_data_v2->desc_id_fetch;
  1812. goto end;
  1813. }
  1814. /* Without a directory fingerprint at this stage, we can't do much. */
  1815. if (hsdir_fp == NULL) {
  1816. goto end;
  1817. }
  1818. /* OK, we have an onion address so now let's find which descriptor ID
  1819. * is the one associated with the HSDir fingerprint. */
  1820. for (replica = 0; replica < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS;
  1821. replica++) {
  1822. const char *digest = rend_data_get_desc_id(rend_data, replica, NULL);
  1823. SMARTLIST_FOREACH_BEGIN(rend_data->hsdirs_fp, char *, fingerprint) {
  1824. if (tor_memcmp(fingerprint, hsdir_fp, DIGEST_LEN) == 0) {
  1825. /* Found it! This descriptor ID is the right one. */
  1826. desc_id = digest;
  1827. goto end;
  1828. }
  1829. } SMARTLIST_FOREACH_END(fingerprint);
  1830. }
  1831. end:
  1832. return desc_id;
  1833. }
  1834. /** send HS_DESC RECEIVED event
  1835. *
  1836. * called when we successfully received a hidden service descriptor.
  1837. */
  1838. void
  1839. control_event_hsv2_descriptor_received(const char *onion_address,
  1840. const rend_data_t *rend_data,
  1841. const char *hsdir_id_digest)
  1842. {
  1843. char *desc_id_field = NULL;
  1844. const char *desc_id;
  1845. if (BUG(!rend_data || !hsdir_id_digest || !onion_address)) {
  1846. return;
  1847. }
  1848. desc_id = get_desc_id_from_query(rend_data, hsdir_id_digest);
  1849. if (desc_id != NULL) {
  1850. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  1851. /* Set the descriptor ID digest to base32 so we can send it. */
  1852. base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_id,
  1853. DIGEST_LEN);
  1854. /* Extra whitespace is needed before the value. */
  1855. tor_asprintf(&desc_id_field, " %s", desc_id_base32);
  1856. }
  1857. event_hs_descriptor_receive_end("RECEIVED", onion_address, desc_id_field,
  1858. TO_REND_DATA_V2(rend_data)->auth_type,
  1859. hsdir_id_digest, NULL);
  1860. tor_free(desc_id_field);
  1861. }
  1862. /* Send HS_DESC RECEIVED event
  1863. *
  1864. * Called when we successfully received a hidden service descriptor. */
  1865. void
  1866. control_event_hsv3_descriptor_received(const char *onion_address,
  1867. const char *desc_id,
  1868. const char *hsdir_id_digest)
  1869. {
  1870. char *desc_id_field = NULL;
  1871. if (BUG(!onion_address || !desc_id || !hsdir_id_digest)) {
  1872. return;
  1873. }
  1874. /* Because DescriptorID is an optional positional value, we need to add a
  1875. * whitespace before in order to not be next to the HsDir value. */
  1876. tor_asprintf(&desc_id_field, " %s", desc_id);
  1877. event_hs_descriptor_receive_end("RECEIVED", onion_address, desc_id_field,
  1878. REND_NO_AUTH, hsdir_id_digest, NULL);
  1879. tor_free(desc_id_field);
  1880. }
  1881. /** send HS_DESC UPLOADED event
  1882. *
  1883. * called when we successfully uploaded a hidden service descriptor.
  1884. */
  1885. void
  1886. control_event_hs_descriptor_uploaded(const char *id_digest,
  1887. const char *onion_address)
  1888. {
  1889. if (BUG(!id_digest)) {
  1890. return;
  1891. }
  1892. control_event_hs_descriptor_upload_end("UPLOADED", onion_address,
  1893. id_digest, NULL);
  1894. }
  1895. /** Send HS_DESC event to inform controller that query <b>rend_data</b>
  1896. * failed to retrieve hidden service descriptor from directory identified by
  1897. * <b>id_digest</b>. If NULL, "UNKNOWN" is used. If <b>reason</b> is not NULL,
  1898. * add it to REASON= field.
  1899. */
  1900. void
  1901. control_event_hsv2_descriptor_failed(const rend_data_t *rend_data,
  1902. const char *hsdir_id_digest,
  1903. const char *reason)
  1904. {
  1905. char *desc_id_field = NULL;
  1906. const char *desc_id;
  1907. if (BUG(!rend_data)) {
  1908. return;
  1909. }
  1910. desc_id = get_desc_id_from_query(rend_data, hsdir_id_digest);
  1911. if (desc_id != NULL) {
  1912. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  1913. /* Set the descriptor ID digest to base32 so we can send it. */
  1914. base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_id,
  1915. DIGEST_LEN);
  1916. /* Extra whitespace is needed before the value. */
  1917. tor_asprintf(&desc_id_field, " %s", desc_id_base32);
  1918. }
  1919. event_hs_descriptor_receive_end("FAILED", rend_data_get_address(rend_data),
  1920. desc_id_field,
  1921. TO_REND_DATA_V2(rend_data)->auth_type,
  1922. hsdir_id_digest, reason);
  1923. tor_free(desc_id_field);
  1924. }
  1925. /** Send HS_DESC event to inform controller that the query to
  1926. * <b>onion_address</b> failed to retrieve hidden service descriptor
  1927. * <b>desc_id</b> from directory identified by <b>hsdir_id_digest</b>. If
  1928. * NULL, "UNKNOWN" is used. If <b>reason</b> is not NULL, add it to REASON=
  1929. * field. */
  1930. void
  1931. control_event_hsv3_descriptor_failed(const char *onion_address,
  1932. const char *desc_id,
  1933. const char *hsdir_id_digest,
  1934. const char *reason)
  1935. {
  1936. char *desc_id_field = NULL;
  1937. if (BUG(!onion_address || !desc_id || !reason)) {
  1938. return;
  1939. }
  1940. /* Because DescriptorID is an optional positional value, we need to add a
  1941. * whitespace before in order to not be next to the HsDir value. */
  1942. tor_asprintf(&desc_id_field, " %s", desc_id);
  1943. event_hs_descriptor_receive_end("FAILED", onion_address, desc_id_field,
  1944. REND_NO_AUTH, hsdir_id_digest, reason);
  1945. tor_free(desc_id_field);
  1946. }
  1947. /** Send HS_DESC_CONTENT event after completion of a successful fetch
  1948. * from hs directory. If <b>hsdir_id_digest</b> is NULL, it is replaced
  1949. * by "UNKNOWN". If <b>content</b> is NULL, it is replaced by an empty
  1950. * string. The <b>onion_address</b> or <b>desc_id</b> set to NULL will
  1951. * not trigger the control event. */
  1952. void
  1953. control_event_hs_descriptor_content(const char *onion_address,
  1954. const char *desc_id,
  1955. const char *hsdir_id_digest,
  1956. const char *content)
  1957. {
  1958. static const char *event_name = "HS_DESC_CONTENT";
  1959. char *esc_content = NULL;
  1960. if (!onion_address || !desc_id) {
  1961. log_warn(LD_BUG, "Called with onion_address==%p, desc_id==%p, ",
  1962. onion_address, desc_id);
  1963. return;
  1964. }
  1965. if (content == NULL) {
  1966. /* Point it to empty content so it can still be escaped. */
  1967. content = "";
  1968. }
  1969. write_escaped_data(content, strlen(content), &esc_content);
  1970. send_control_event(EVENT_HS_DESC_CONTENT,
  1971. "650+%s %s %s %s\r\n%s650 OK\r\n",
  1972. event_name,
  1973. rend_hsaddress_str_or_unknown(onion_address),
  1974. desc_id,
  1975. hsdir_id_digest ?
  1976. node_describe_longname_by_id(hsdir_id_digest) :
  1977. "UNKNOWN",
  1978. esc_content);
  1979. tor_free(esc_content);
  1980. }
  1981. /** Send HS_DESC event to inform controller upload of hidden service
  1982. * descriptor identified by <b>id_digest</b> failed. If <b>reason</b>
  1983. * is not NULL, add it to REASON= field.
  1984. */
  1985. void
  1986. control_event_hs_descriptor_upload_failed(const char *id_digest,
  1987. const char *onion_address,
  1988. const char *reason)
  1989. {
  1990. if (BUG(!id_digest)) {
  1991. return;
  1992. }
  1993. control_event_hs_descriptor_upload_end("FAILED", onion_address,
  1994. id_digest, reason);
  1995. }
  1996. void
  1997. control_events_free_all(void)
  1998. {
  1999. smartlist_t *queued_events = NULL;
  2000. stats_prev_n_read = stats_prev_n_written = 0;
  2001. if (queued_control_events_lock) {
  2002. tor_mutex_acquire(queued_control_events_lock);
  2003. flush_queued_event_pending = 0;
  2004. queued_events = queued_control_events;
  2005. queued_control_events = NULL;
  2006. tor_mutex_release(queued_control_events_lock);
  2007. }
  2008. if (queued_events) {
  2009. SMARTLIST_FOREACH(queued_events, queued_event_t *, ev,
  2010. queued_event_free(ev));
  2011. smartlist_free(queued_events);
  2012. }
  2013. if (flush_queued_events_event) {
  2014. mainloop_event_free(flush_queued_events_event);
  2015. flush_queued_events_event = NULL;
  2016. }
  2017. global_event_mask = 0;
  2018. disable_log_messages = 0;
  2019. }
  2020. #ifdef TOR_UNIT_TESTS
  2021. /* For testing: change the value of global_event_mask */
  2022. void
  2023. control_testing_set_global_event_mask(uint64_t mask)
  2024. {
  2025. global_event_mask = mask;
  2026. }
  2027. #endif /* defined(TOR_UNIT_TESTS) */