control_events.c 74 KB

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