Add transfer support to CEL
[asterisk/asterisk.git] / main / cel.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2007 - 2009, Digium, Inc.
5  *
6  * See http://www.asterisk.org for more information about
7  * the Asterisk project. Please do not directly contact
8  * any of the maintainers of this project for assistance;
9  * the project provides a web site, mailing lists and IRC
10  * channels for your use.
11  *
12  * This program is free software, distributed under the terms of
13  * the GNU General Public License Version 2. See the LICENSE file
14  * at the top of the source tree.
15  */
16
17 /*!
18  * \file
19  *
20  * \brief Channel Event Logging API
21  *
22  * \author Steve Murphy <murf@digium.com>
23  * \author Russell Bryant <russell@digium.com>
24  *
25  * \todo Do thorough testing of all transfer methods to ensure that BLINDTRANSFER,
26  *       ATTENDEDTRANSFER, BRIDGE_START, and BRIDGE_END events are all reported
27  *       as expected.
28  */
29
30 /*! \li \ref cel.c uses the configuration file \ref cel.conf
31  * \addtogroup configuration_file Configuration Files
32  */
33
34 /*!
35  * \page cel.conf cel.conf
36  * \verbinclude cel.conf.sample
37  */
38
39 /*** MODULEINFO
40         <support_level>core</support_level>
41  ***/
42
43 #include "asterisk.h"
44
45 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
46
47 #include "asterisk/_private.h"
48
49 #include "asterisk/channel.h"
50 #include "asterisk/pbx.h"
51 #include "asterisk/cel.h"
52 #include "asterisk/logger.h"
53 #include "asterisk/linkedlists.h"
54 #include "asterisk/utils.h"
55 #include "asterisk/config.h"
56 #include "asterisk/config_options.h"
57 #include "asterisk/cli.h"
58 #include "asterisk/astobj2.h"
59 #include "asterisk/stasis_message_router.h"
60 #include "asterisk/stasis_channels.h"
61 #include "asterisk/stasis_bridging.h"
62 #include "asterisk/bridging.h"
63 #include "asterisk/parking.h"
64 #include "asterisk/features.h"
65
66 /*** DOCUMENTATION
67         <configInfo name="cel" language="en_US">
68                 <configFile name="cel.conf">
69                         <configObject name="general">
70                                 <synopsis>Options that apply globally to Channel Event Logging (CEL)</synopsis>
71                                 <configOption name="enable">
72                                         <synopsis>Determines whether CEL is enabled</synopsis>
73                                 </configOption>
74                                 <configOption name="dateformat">
75                                         <synopsis>The format to be used for dates when logging</synopsis>
76                                 </configOption>
77                                 <configOption name="apps">
78                                         <synopsis>List of apps for CEL to track</synopsis>
79                                         <description><para>A case-insensitive, comma-separated list of applications
80                                         to track when one or both of APP_START and APP_END events are flagged for
81                                         tracking</para></description>
82                                 </configOption>
83                                 <configOption name="events">
84                                         <synopsis>List of events for CEL to track</synopsis>
85                                         <description><para>A case-sensitive, comma-separated list of event names
86                                         to track. These event names do not include the leading <literal>AST_CEL</literal>.
87                                         </para>
88                                         <enumlist>
89                                                 <enum name="ALL">
90                                                         <para>Special value which tracks all events.</para>
91                                                 </enum>
92                                                 <enum name="CHAN_START"/>
93                                                 <enum name="CHAN_END"/>
94                                                 <enum name="ANSWER"/>
95                                                 <enum name="HANGUP"/>
96                                                 <enum name="APP_START"/>
97                                                 <enum name="APP_END"/>
98                                                 <enum name="BRIDGE_START"/>
99                                                 <enum name="BRIDGE_END"/>
100                                                 <enum name="BRIDGE_TO_CONF"/>
101                                                 <enum name="CONF_START"/>
102                                                 <enum name="CONF_END"/>
103                                                 <enum name="PARK_START"/>
104                                                 <enum name="PARK_END"/>
105                                                 <enum name="USER_DEFINED"/>
106                                                 <enum name="CONF_ENTER"/>
107                                                 <enum name="CONF_EXIT"/>
108                                                 <enum name="BLINDTRANSFER"/>
109                                                 <enum name="ATTENDEDTRANSFER"/>
110                                                 <enum name="PICKUP"/>
111                                                 <enum name="FORWARD"/>
112                                                 <enum name="3WAY_START"/>
113                                                 <enum name="3WAY_END"/>
114                                                 <enum name="HOOKFLASH"/>
115                                                 <enum name="LINKEDID_END"/>
116
117                                         </enumlist>
118                                         </description>
119                                 </configOption>
120                         </configObject>
121                 </configFile>
122         </configInfo>
123  ***/
124
125 /*! Message router for state that CEL needs to know about */
126 static struct stasis_message_router *cel_state_router;
127
128 /*! Topic for CEL-specific messages */
129 static struct stasis_topic *cel_topic;
130
131 /*! Aggregation topic for all topics CEL needs to know about */
132 static struct stasis_topic *cel_aggregation_topic;
133
134 /*! Subscription for forwarding the channel caching topic */
135 static struct stasis_subscription *cel_channel_forwarder;
136
137 /*! Subscription for forwarding the channel caching topic */
138 static struct stasis_subscription *cel_bridge_forwarder;
139
140 /*! Subscription for forwarding the parking topic */
141 static struct stasis_subscription *cel_parking_forwarder;
142
143 /*! Subscription for forwarding the CEL-specific topic */
144 static struct stasis_subscription *cel_cel_forwarder;
145
146 /*! Container for primary channel/bridge ID listing for 2 party bridges */
147 static struct ao2_container *bridge_primaries;
148
149 struct stasis_message_type *cel_generic_type(void);
150 STASIS_MESSAGE_TYPE_DEFN(cel_generic_type);
151
152 /*! The number of buckets into which primary channel uniqueids will be hashed */
153 #define BRIDGE_PRIMARY_BUCKETS 251
154
155 /*! Container for dial end multichannel blobs for holding on to dial statuses */
156 static struct ao2_container *cel_dialstatus_store;
157
158 /*!
159  * \brief Maximum possible CEL event IDs
160  * \note This limit is currently imposed by the eventset definition
161  */
162 #define CEL_MAX_EVENT_IDS 64
163
164 /*!
165  * \brief Number of buckets for the appset container
166  */
167 #define NUM_APP_BUCKETS         97
168
169 /*!
170  * \brief Number of buckets for the dialstatus container
171  */
172 #define NUM_DIALSTATUS_BUCKETS  251
173
174 /*!
175  * \brief Container of Asterisk application names
176  *
177  * The apps in this container are the applications that were specified
178  * in the configuration as applications that CEL events should be generated
179  * for when they start and end on a channel.
180  */
181 static struct ao2_container *linkedids;
182
183 /*! \brief Destructor for cel_config */
184 static void cel_general_config_dtor(void *obj)
185 {
186         struct ast_cel_general_config *cfg = obj;
187         ast_string_field_free_memory(cfg);
188         ao2_cleanup(cfg->apps);
189         cfg->apps = NULL;
190 }
191
192 void *ast_cel_general_config_alloc(void)
193 {
194         RAII_VAR(struct ast_cel_general_config *, cfg, NULL, ao2_cleanup);
195
196         if (!(cfg = ao2_alloc(sizeof(*cfg), cel_general_config_dtor))) {
197                 return NULL;
198         }
199
200         if (ast_string_field_init(cfg, 64)) {
201                 return NULL;
202         }
203
204         if (!(cfg->apps = ast_str_container_alloc(NUM_APP_BUCKETS))) {
205                 return NULL;
206         }
207
208         ao2_ref(cfg, +1);
209         return cfg;
210 }
211
212 /*! \brief A container that holds all config-related information */
213 struct cel_config {
214         struct ast_cel_general_config *general;
215 };
216
217
218 static AO2_GLOBAL_OBJ_STATIC(cel_configs);
219
220 /*! \brief Destructor for cel_config */
221 static void cel_config_dtor(void *obj)
222 {
223         struct cel_config *cfg = obj;
224         ao2_cleanup(cfg->general);
225         cfg->general = NULL;
226 }
227
228 static void *cel_config_alloc(void)
229 {
230         RAII_VAR(struct cel_config *, cfg, NULL, ao2_cleanup);
231
232         if (!(cfg = ao2_alloc(sizeof(*cfg), cel_config_dtor))) {
233                 return NULL;
234         }
235
236         if (!(cfg->general = ast_cel_general_config_alloc())) {
237                 return NULL;
238         }
239
240         ao2_ref(cfg, +1);
241         return cfg;
242 }
243
244 /*! \brief An aco_type structure to link the "general" category to the ast_cel_general_config type */
245 static struct aco_type general_option = {
246         .type = ACO_GLOBAL,
247         .name = "general",
248         .item_offset = offsetof(struct cel_config, general),
249         .category_match = ACO_WHITELIST,
250         .category = "^general$",
251 };
252
253 /*! \brief The config file to be processed for the module. */
254 static struct aco_file cel_conf = {
255         .filename = "cel.conf",                  /*!< The name of the config file */
256         .types = ACO_TYPES(&general_option),     /*!< The mapping object types to be processed */
257         .skip_category = "(^manager$|^radius$)", /*!< Config sections used by existing modules. Do not add to this list. */
258 };
259
260 static int cel_pre_apply_config(void);
261
262 CONFIG_INFO_CORE("cel", cel_cfg_info, cel_configs, cel_config_alloc,
263         .files = ACO_FILES(&cel_conf),
264         .pre_apply_config = cel_pre_apply_config,
265 );
266
267 static int cel_pre_apply_config(void)
268 {
269         struct cel_config *cfg = aco_pending_config(&cel_cfg_info);
270
271         if (!cfg->general) {
272                 return -1;
273         }
274
275         if (!ao2_container_count(cfg->general->apps)) {
276                 return 0;
277         }
278
279         if (cfg->general->events & ((int64_t) 1 << AST_CEL_APP_START)) {
280                 return 0;
281         }
282
283         if (cfg->general->events & ((int64_t) 1 << AST_CEL_APP_END)) {
284                 return 0;
285         }
286
287         ast_log(LOG_ERROR, "Applications are listed to be tracked, but APP events are not tracked\n");
288         return -1;
289 }
290
291 static struct aco_type *general_options[] = ACO_TYPES(&general_option);
292
293 /*!
294  * \brief Map of ast_cel_event_type to strings
295  */
296 static const char * const cel_event_types[CEL_MAX_EVENT_IDS] = {
297         [0]                        = "ALL",
298         [AST_CEL_CHANNEL_START]    = "CHAN_START",
299         [AST_CEL_CHANNEL_END]      = "CHAN_END",
300         [AST_CEL_ANSWER]           = "ANSWER",
301         [AST_CEL_HANGUP]           = "HANGUP",
302         [AST_CEL_APP_START]        = "APP_START",
303         [AST_CEL_APP_END]          = "APP_END",
304         [AST_CEL_BRIDGE_START]     = "BRIDGE_START",
305         [AST_CEL_BRIDGE_END]       = "BRIDGE_END",
306         [AST_CEL_BRIDGE_TO_CONF]   = "BRIDGE_TO_CONF",
307         [AST_CEL_CONF_START]       = "CONF_START",
308         [AST_CEL_CONF_END]         = "CONF_END",
309         [AST_CEL_PARK_START]       = "PARK_START",
310         [AST_CEL_PARK_END]         = "PARK_END",
311         [AST_CEL_USER_DEFINED]     = "USER_DEFINED",
312         [AST_CEL_CONF_ENTER]       = "CONF_ENTER",
313         [AST_CEL_CONF_EXIT]        = "CONF_EXIT",
314         [AST_CEL_BLINDTRANSFER]    = "BLINDTRANSFER",
315         [AST_CEL_ATTENDEDTRANSFER] = "ATTENDEDTRANSFER",
316         [AST_CEL_PICKUP]           = "PICKUP",
317         [AST_CEL_FORWARD]          = "FORWARD",
318         [AST_CEL_3WAY_START]       = "3WAY_START",
319         [AST_CEL_3WAY_END]         = "3WAY_END",
320         [AST_CEL_HOOKFLASH]        = "HOOKFLASH",
321         [AST_CEL_LINKEDID_END]     = "LINKEDID_END",
322 };
323
324 struct bridge_assoc {
325         AST_DECLARE_STRING_FIELDS(
326                 AST_STRING_FIELD(bridge_id);           /*!< UniqueID of the bridge */
327                 AST_STRING_FIELD(secondary_name);      /*!< UniqueID of the secondary/dialed channel */
328         );
329         struct ast_channel_snapshot *primary_snapshot; /*!< The snapshot for the initiating channel in the bridge */
330         int track_as_conf;                             /*!< Whether this bridge will be treated like a conference in CEL terms */
331 };
332
333 static void bridge_assoc_dtor(void *obj)
334 {
335         struct bridge_assoc *assoc = obj;
336         ast_string_field_free_memory(assoc);
337         ao2_cleanup(assoc->primary_snapshot);
338         assoc->primary_snapshot = NULL;
339 }
340
341 static struct bridge_assoc *bridge_assoc_alloc(struct ast_channel_snapshot *primary, const char *bridge_id, const char *secondary_name)
342 {
343         RAII_VAR(struct bridge_assoc *, assoc, ao2_alloc(sizeof(*assoc), bridge_assoc_dtor), ao2_cleanup);
344         if (!primary || !assoc || ast_string_field_init(assoc, 64)) {
345                 return NULL;
346         }
347
348         ast_string_field_set(assoc, bridge_id, bridge_id);
349         ast_string_field_set(assoc, secondary_name, secondary_name);
350
351         assoc->primary_snapshot = primary;
352         ao2_ref(primary, +1);
353
354         ao2_ref(assoc, +1);
355         return assoc;
356 }
357
358 static int add_bridge_primary(struct ast_channel_snapshot *primary, const char *bridge_id, const char *secondary_name)
359 {
360         RAII_VAR(struct bridge_assoc *, assoc, bridge_assoc_alloc(primary, bridge_id, secondary_name), ao2_cleanup);
361         if (!assoc) {
362                 return -1;
363         }
364
365         ao2_link(bridge_primaries, assoc);
366         return 0;
367 }
368
369 static void remove_bridge_primary(const char *channel_id)
370 {
371         ao2_find(bridge_primaries, channel_id, OBJ_NODATA | OBJ_MULTIPLE | OBJ_UNLINK | OBJ_KEY);
372 }
373
374 /*! \brief Hashing function for bridge_assoc */
375 static int bridge_assoc_hash(const void *obj, int flags)
376 {
377         const struct bridge_assoc *assoc = obj;
378         const char *uniqueid = obj;
379         if (!(flags & OBJ_KEY)) {
380                 uniqueid = assoc->primary_snapshot->uniqueid;
381         }
382
383         return ast_str_hash(uniqueid);
384 }
385
386 /*! \brief Comparator function for bridge_assoc */
387 static int bridge_assoc_cmp(void *obj, void *arg, int flags)
388 {
389         struct bridge_assoc *assoc1 = obj, *assoc2 = arg;
390         const char *assoc2_id = arg, *assoc1_id = assoc1->primary_snapshot->uniqueid;
391         if (!(flags & OBJ_KEY)) {
392                 assoc2_id = assoc2->primary_snapshot->uniqueid;
393         }
394
395         return !strcmp(assoc1_id, assoc2_id) ? CMP_MATCH | CMP_STOP : 0;
396 }
397
398 static const char *get_caller_uniqueid(struct ast_multi_channel_blob *blob)
399 {
400         struct ast_channel_snapshot *caller = ast_multi_channel_blob_get_channel(blob, "caller");
401         if (!caller) {
402                 return NULL;
403         }
404
405         return caller->uniqueid;
406 }
407
408 /*! \brief Hashing function for dialstatus container */
409 static int dialstatus_hash(const void *obj, int flags)
410 {
411         struct ast_multi_channel_blob *blob = (void *) obj;
412         const char *uniqueid = obj;
413         if (!(flags & OBJ_KEY)) {
414                 uniqueid = get_caller_uniqueid(blob);
415         }
416
417         return ast_str_hash(uniqueid);
418 }
419
420 /*! \brief Comparator function for dialstatus container */
421 static int dialstatus_cmp(void *obj, void *arg, int flags)
422 {
423         struct ast_multi_channel_blob *blob1 = obj, *blob2 = arg;
424         const char *blob2_id = arg, *blob1_id = get_caller_uniqueid(blob1);
425         if (!(flags & OBJ_KEY)) {
426                 blob2_id = get_caller_uniqueid(blob2);
427         }
428
429         return !strcmp(blob1_id, blob2_id) ? CMP_MATCH | CMP_STOP : 0;
430 }
431
432 unsigned int ast_cel_check_enabled(void)
433 {
434         RAII_VAR(struct cel_config *, cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
435
436         if (!cfg || !cfg->general) {
437                 return 0;
438         }
439
440         return cfg->general->enable;
441 }
442
443 static int print_app(void *obj, void *arg, int flags)
444 {
445         struct ast_cli_args *a = arg;
446
447         ast_cli(a->fd, "CEL Tracking Application: %s\n", (const char *) obj);
448
449         return 0;
450 }
451
452 static void print_cel_sub(const struct ast_event *event, void *data)
453 {
454         struct ast_cli_args *a = data;
455
456         ast_cli(a->fd, "CEL Event Subscriber: %s\n",
457                         ast_event_get_ie_str(event, AST_EVENT_IE_DESCRIPTION));
458 }
459
460 static char *handle_cli_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
461 {
462         unsigned int i;
463         struct ast_event_sub *sub;
464         RAII_VAR(struct cel_config *, cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
465
466         switch (cmd) {
467         case CLI_INIT:
468                 e->command = "cel show status";
469                 e->usage =
470                         "Usage: cel show status\n"
471                         "       Displays the Channel Event Logging system status.\n";
472                 return NULL;
473         case CLI_GENERATE:
474                 return NULL;
475         case CLI_HANDLER:
476                 break;
477         }
478
479         if (a->argc > 3) {
480                 return CLI_SHOWUSAGE;
481         }
482
483         ast_cli(a->fd, "CEL Logging: %s\n", ast_cel_check_enabled() ? "Enabled" : "Disabled");
484
485         if (!cfg || !cfg->general) {
486                 return CLI_SUCCESS;
487         }
488
489         if (!cfg->general->enable) {
490                 return CLI_SUCCESS;
491         }
492
493         for (i = 0; i < (sizeof(cfg->general->events) * 8); i++) {
494                 const char *name;
495
496                 if (!(cfg->general->events & ((int64_t) 1 << i))) {
497                         continue;
498                 }
499
500                 name = ast_cel_get_type_name(i);
501                 if (strcasecmp(name, "Unknown")) {
502                         ast_cli(a->fd, "CEL Tracking Event: %s\n", name);
503                 }
504         }
505
506         ao2_callback(cfg->general->apps, OBJ_NODATA, print_app, a);
507
508         if (!(sub = ast_event_subscribe_new(AST_EVENT_SUB, print_cel_sub, a))) {
509                 return CLI_FAILURE;
510         }
511         ast_event_sub_append_ie_uint(sub, AST_EVENT_IE_EVENTTYPE, AST_EVENT_CEL);
512         ast_event_report_subs(sub);
513         ast_event_sub_destroy(sub);
514         sub = NULL;
515
516         return CLI_SUCCESS;
517 }
518
519 static struct ast_cli_entry cli_status = AST_CLI_DEFINE(handle_cli_status, "Display the CEL status");
520
521 enum ast_cel_event_type ast_cel_str_to_event_type(const char *name)
522 {
523         unsigned int i;
524
525         for (i = 0; i < ARRAY_LEN(cel_event_types); i++) {
526                 if (!cel_event_types[i]) {
527                         continue;
528                 }
529
530                 if (!strcasecmp(name, cel_event_types[i])) {
531                         return i;
532                 }
533         }
534
535         return -1;
536 }
537
538 static int ast_cel_track_event(enum ast_cel_event_type et)
539 {
540         RAII_VAR(struct cel_config *, cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
541
542         if (!cfg || !cfg->general) {
543                 return 0;
544         }
545
546         return (cfg->general->events & ((int64_t) 1 << et));
547 }
548
549 static int events_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
550 {
551         struct ast_cel_general_config *cfg = obj;
552         char *events = ast_strdupa(var->value);
553         char *cur_event;
554
555         while ((cur_event = strsep(&events, ","))) {
556                 enum ast_cel_event_type event_type;
557
558                 cur_event = ast_strip(cur_event);
559                 if (ast_strlen_zero(cur_event)) {
560                         continue;
561                 }
562
563                 event_type = ast_cel_str_to_event_type(cur_event);
564
565                 if (event_type == 0) {
566                         /* All events */
567                         cfg->events = (int64_t) -1;
568                 } else if (event_type == -1) {
569                         ast_log(LOG_ERROR, "Unknown event name '%s'\n", cur_event);
570                         return -1;
571                 } else {
572                         cfg->events |= ((int64_t) 1 << event_type);
573                 }
574         }
575
576         return 0;
577 }
578
579 static int apps_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
580 {
581         struct ast_cel_general_config *cfg = obj;
582         char *apps = ast_strdupa(var->value);
583         char *cur_app;
584
585         while ((cur_app = strsep(&apps, ","))) {
586                 cur_app = ast_strip(cur_app);
587                 if (ast_strlen_zero(cur_app)) {
588                         continue;
589                 }
590
591                 cur_app = ast_str_to_lower(cur_app);
592                 ast_str_container_add(cfg->apps, cur_app);
593         }
594
595         return 0;
596 }
597
598 static int do_reload(void)
599 {
600         if (aco_process_config(&cel_cfg_info, 1) == ACO_PROCESS_ERROR) {
601                 return -1;
602         }
603
604         ast_verb(3, "CEL logging %sabled.\n", ast_cel_check_enabled() ? "en" : "dis");
605
606         return 0;
607 }
608
609 const char *ast_cel_get_type_name(enum ast_cel_event_type type)
610 {
611         return S_OR(cel_event_types[type], "Unknown");
612 }
613
614 static int cel_track_app(const char *const_app)
615 {
616         RAII_VAR(struct cel_config *, cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
617         RAII_VAR(char *, app, NULL, ao2_cleanup);
618         char *app_lower;
619
620         if (!cfg || !cfg->general) {
621                 return 0;
622         }
623
624         app_lower = ast_str_to_lower(ast_strdupa(const_app));
625         app = ao2_find(cfg->general->apps, app_lower, OBJ_KEY);
626         if (!app) {
627                 return 0;
628         }
629
630         return 1;
631 }
632
633 static int cel_linkedid_ref(const char *linkedid);
634 struct ast_event *ast_cel_create_event(struct ast_channel_snapshot *snapshot,
635                 enum ast_cel_event_type event_type, const char *userdefevname,
636                 struct ast_json *extra, const char *peer_name)
637 {
638         struct timeval eventtime = ast_tvnow();
639         RAII_VAR(char *, extra_txt, NULL, ast_free);
640         if (extra) {
641                 extra_txt = ast_json_dump_string(extra);
642         }
643         return ast_event_new(AST_EVENT_CEL,
644                 AST_EVENT_IE_CEL_EVENT_TYPE, AST_EVENT_IE_PLTYPE_UINT, event_type,
645                 AST_EVENT_IE_CEL_EVENT_TIME, AST_EVENT_IE_PLTYPE_UINT, eventtime.tv_sec,
646                 AST_EVENT_IE_CEL_EVENT_TIME_USEC, AST_EVENT_IE_PLTYPE_UINT, eventtime.tv_usec,
647                 AST_EVENT_IE_CEL_USEREVENT_NAME, AST_EVENT_IE_PLTYPE_STR, S_OR(userdefevname, ""),
648                 AST_EVENT_IE_CEL_CIDNAME, AST_EVENT_IE_PLTYPE_STR, snapshot->caller_name,
649                 AST_EVENT_IE_CEL_CIDNUM, AST_EVENT_IE_PLTYPE_STR, snapshot->caller_number,
650                 AST_EVENT_IE_CEL_CIDANI, AST_EVENT_IE_PLTYPE_STR, snapshot->caller_ani,
651                 AST_EVENT_IE_CEL_CIDRDNIS, AST_EVENT_IE_PLTYPE_STR, snapshot->caller_rdnis,
652                 AST_EVENT_IE_CEL_CIDDNID, AST_EVENT_IE_PLTYPE_STR, snapshot->caller_dnid,
653                 AST_EVENT_IE_CEL_EXTEN, AST_EVENT_IE_PLTYPE_STR, snapshot->exten,
654                 AST_EVENT_IE_CEL_CONTEXT, AST_EVENT_IE_PLTYPE_STR, snapshot->context,
655                 AST_EVENT_IE_CEL_CHANNAME, AST_EVENT_IE_PLTYPE_STR, snapshot->name,
656                 AST_EVENT_IE_CEL_APPNAME, AST_EVENT_IE_PLTYPE_STR, snapshot->appl,
657                 AST_EVENT_IE_CEL_APPDATA, AST_EVENT_IE_PLTYPE_STR, snapshot->data,
658                 AST_EVENT_IE_CEL_AMAFLAGS, AST_EVENT_IE_PLTYPE_UINT, snapshot->amaflags,
659                 AST_EVENT_IE_CEL_ACCTCODE, AST_EVENT_IE_PLTYPE_STR, snapshot->accountcode,
660                 AST_EVENT_IE_CEL_PEERACCT, AST_EVENT_IE_PLTYPE_STR, snapshot->peeraccount,
661                 AST_EVENT_IE_CEL_UNIQUEID, AST_EVENT_IE_PLTYPE_STR, snapshot->uniqueid,
662                 AST_EVENT_IE_CEL_LINKEDID, AST_EVENT_IE_PLTYPE_STR, snapshot->linkedid,
663                 AST_EVENT_IE_CEL_USERFIELD, AST_EVENT_IE_PLTYPE_STR, snapshot->userfield,
664                 AST_EVENT_IE_CEL_EXTRA, AST_EVENT_IE_PLTYPE_STR, S_OR(extra_txt, ""),
665                 AST_EVENT_IE_CEL_PEER, AST_EVENT_IE_PLTYPE_STR, S_OR(peer_name, ""),
666                 AST_EVENT_IE_END);
667 }
668
669 static int cel_report_event(struct ast_channel_snapshot *snapshot,
670                 enum ast_cel_event_type event_type, const char *userdefevname,
671                 struct ast_json *extra, const char *peer2_name)
672 {
673         struct ast_event *ev;
674         char *linkedid = ast_strdupa(snapshot->linkedid);
675         const char *peer_name = peer2_name;
676         RAII_VAR(struct bridge_assoc *, assoc, NULL, ao2_cleanup);
677         RAII_VAR(struct cel_config *, cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
678
679         if (!cfg || !cfg->general) {
680                 return 0;
681         }
682
683         if (!cfg->general->enable) {
684                 return 0;
685         }
686
687         if (ast_strlen_zero(peer_name)) {
688                 assoc = ao2_find(bridge_primaries, snapshot->uniqueid, OBJ_KEY);
689                 if (assoc) {
690                         peer_name = assoc->secondary_name;
691                 }
692         }
693
694         /* Record the linkedid of new channels if we are tracking LINKEDID_END even if we aren't
695          * reporting on CHANNEL_START so we can track when to send LINKEDID_END */
696         if (ast_cel_track_event(AST_CEL_LINKEDID_END) && event_type == AST_CEL_CHANNEL_START && linkedid) {
697                 if (cel_linkedid_ref(linkedid)) {
698                         return -1;
699                 }
700         }
701
702         if (!ast_cel_track_event(event_type)) {
703                 return 0;
704         }
705
706         if ((event_type == AST_CEL_APP_START || event_type == AST_CEL_APP_END)
707                 && !cel_track_app(snapshot->appl)) {
708                 return 0;
709         }
710
711         ev = ast_cel_create_event(snapshot, event_type, userdefevname, extra, peer_name);
712         if (ev && ast_event_queue(ev)) {
713                 ast_event_destroy(ev);
714                 return -1;
715         }
716
717         return 0;
718 }
719
720 /* called whenever a channel is destroyed or a linkedid is changed to
721  * potentially emit a CEL_LINKEDID_END event */
722 static void check_retire_linkedid(struct ast_channel_snapshot *snapshot)
723 {
724         char *lid;
725
726         /* make sure we need to do all this work */
727
728         if (ast_strlen_zero(snapshot->linkedid) || !ast_cel_track_event(AST_CEL_LINKEDID_END)) {
729                 return;
730         }
731
732         if (!(lid = ao2_find(linkedids, (void *) snapshot->linkedid, OBJ_POINTER))) {
733                 ast_log(LOG_ERROR, "Something weird happened, couldn't find linkedid %s\n", snapshot->linkedid);
734                 return;
735         }
736
737         /* We have a ref for each channel with this linkedid, the link and the above find, so if
738          * before unreffing the channel we have a refcount of 3, we're done. Unlink and report. */
739         if (ao2_ref(lid, -1) == 3) {
740                 ast_str_container_remove(linkedids, lid);
741                 cel_report_event(snapshot, AST_CEL_LINKEDID_END, NULL, NULL, NULL);
742         }
743         ao2_ref(lid, -1);
744 }
745
746 /* Note that no 'chan_fixup' function is provided for this datastore type,
747  * because the channels that will use it will never be involved in masquerades.
748  */
749 static const struct ast_datastore_info fabricated_channel_datastore = {
750         .type = "CEL fabricated channel",
751         .destroy = ast_free_ptr,
752 };
753
754 struct ast_channel *ast_cel_fabricate_channel_from_event(const struct ast_event *event)
755 {
756         struct varshead *headp;
757         struct ast_var_t *newvariable;
758         const char *mixed_name;
759         char timebuf[30];
760         struct ast_channel *tchan;
761         struct ast_cel_event_record record = {
762                 .version = AST_CEL_EVENT_RECORD_VERSION,
763         };
764         struct ast_datastore *datastore;
765         char *app_data;
766         RAII_VAR(struct cel_config *, cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
767
768         if (!cfg || !cfg->general) {
769                 return NULL;
770         }
771
772         /* do not call ast_channel_alloc because this is not really a real channel */
773         if (!(tchan = ast_dummy_channel_alloc())) {
774                 return NULL;
775         }
776
777         headp = ast_channel_varshead(tchan);
778
779         /* first, get the variables from the event */
780         if (ast_cel_fill_record(event, &record)) {
781                 ast_channel_unref(tchan);
782                 return NULL;
783         }
784
785         /* next, fill the channel with their data */
786         mixed_name = (record.event_type == AST_CEL_USER_DEFINED)
787                 ? record.user_defined_name : record.event_name;
788         if ((newvariable = ast_var_assign("eventtype", mixed_name))) {
789                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
790         }
791
792         if (ast_strlen_zero(cfg->general->date_format)) {
793                 snprintf(timebuf, sizeof(timebuf), "%ld.%06ld", (long) record.event_time.tv_sec,
794                                 (long) record.event_time.tv_usec);
795         } else {
796                 struct ast_tm tm;
797                 ast_localtime(&record.event_time, &tm, NULL);
798                 ast_strftime(timebuf, sizeof(timebuf), cfg->general->date_format, &tm);
799         }
800
801         if ((newvariable = ast_var_assign("eventtime", timebuf))) {
802                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
803         }
804
805         if ((newvariable = ast_var_assign("eventenum", record.event_name))) {
806                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
807         }
808         if ((newvariable = ast_var_assign("userdeftype", record.user_defined_name))) {
809                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
810         }
811         if ((newvariable = ast_var_assign("eventextra", record.extra))) {
812                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
813         }
814
815         ast_channel_caller(tchan)->id.name.valid = 1;
816         ast_channel_caller(tchan)->id.name.str = ast_strdup(record.caller_id_name);
817         ast_channel_caller(tchan)->id.number.valid = 1;
818         ast_channel_caller(tchan)->id.number.str = ast_strdup(record.caller_id_num);
819         ast_channel_caller(tchan)->ani.number.valid = 1;
820         ast_channel_caller(tchan)->ani.number.str = ast_strdup(record.caller_id_ani);
821         ast_channel_redirecting(tchan)->from.number.valid = 1;
822         ast_channel_redirecting(tchan)->from.number.str = ast_strdup(record.caller_id_rdnis);
823         ast_channel_dialed(tchan)->number.str = ast_strdup(record.caller_id_dnid);
824
825         ast_channel_exten_set(tchan, record.extension);
826         ast_channel_context_set(tchan, record.context);
827         ast_channel_name_set(tchan, record.channel_name);
828         ast_channel_uniqueid_set(tchan, record.unique_id);
829         ast_channel_linkedid_set(tchan, record.linked_id);
830         ast_channel_accountcode_set(tchan, record.account_code);
831         ast_channel_peeraccount_set(tchan, record.peer_account);
832         ast_channel_userfield_set(tchan, record.user_field);
833
834         if ((newvariable = ast_var_assign("BRIDGEPEER", record.peer))) {
835                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
836         }
837
838         ast_channel_amaflags_set(tchan, record.amaflag);
839
840         /* We need to store an 'application name' and 'application
841          * data' on the channel for logging purposes, but the channel
842          * structure only provides a place to store pointers, and it
843          * expects these pointers to be pointing to data that does not
844          * need to be freed. This means that the channel's destructor
845          * does not attempt to free any storage that these pointers
846          * point to. However, we can't provide data in that form directly for
847          * these structure members. In order to ensure that these data
848          * elements have a lifetime that matches the channel's
849          * lifetime, we'll put them in a datastore attached to the
850          * channel, and set's the channel's pointers to point into the
851          * datastore.  The datastore will then be automatically destroyed
852          * when the channel is destroyed.
853          */
854
855         if (!(datastore = ast_datastore_alloc(&fabricated_channel_datastore, NULL))) {
856                 ast_channel_unref(tchan);
857                 return NULL;
858         }
859
860         if (!(app_data = ast_malloc(strlen(record.application_name) + strlen(record.application_data) + 2))) {
861                 ast_datastore_free(datastore);
862                 ast_channel_unref(tchan);
863                 return NULL;
864         }
865
866         ast_channel_appl_set(tchan, strcpy(app_data, record.application_name));
867         ast_channel_data_set(tchan, strcpy(app_data + strlen(record.application_name) + 1,
868                 record.application_data));
869
870         datastore->data = app_data;
871         ast_channel_datastore_add(tchan, datastore);
872
873         return tchan;
874 }
875
876 static int cel_linkedid_ref(const char *linkedid)
877 {
878         char *lid;
879
880         if (ast_strlen_zero(linkedid)) {
881                 ast_log(LOG_ERROR, "The linkedid should never be empty\n");
882                 return -1;
883         }
884
885         if (!(lid = ao2_find(linkedids, (void *) linkedid, OBJ_POINTER))) {
886                 if (!(lid = ao2_alloc(strlen(linkedid) + 1, NULL))) {
887                         return -1;
888                 }
889                 strcpy(lid, linkedid);
890                 if (!ao2_link(linkedids, lid)) {
891                         ao2_ref(lid, -1);
892                         return -1;
893                 }
894                 /* Leave both the link and the alloc refs to show a count of 1 + the link */
895         }
896         /* If we've found, go ahead and keep the ref to increment count of how many channels
897          * have this linkedid. We'll clean it up in check_retire */
898         return 0;
899 }
900
901 int ast_cel_fill_record(const struct ast_event *e, struct ast_cel_event_record *r)
902 {
903         if (r->version != AST_CEL_EVENT_RECORD_VERSION) {
904                 ast_log(LOG_ERROR, "Module ABI mismatch for ast_cel_event_record.  "
905                                 "Please ensure all modules were compiled for "
906                                 "this version of Asterisk.\n");
907                 return -1;
908         }
909
910         r->event_type = ast_event_get_ie_uint(e, AST_EVENT_IE_CEL_EVENT_TYPE);
911
912         r->event_time.tv_sec = ast_event_get_ie_uint(e, AST_EVENT_IE_CEL_EVENT_TIME);
913         r->event_time.tv_usec = ast_event_get_ie_uint(e, AST_EVENT_IE_CEL_EVENT_TIME_USEC);
914
915         r->event_name = ast_cel_get_type_name(r->event_type);
916         if (r->event_type == AST_CEL_USER_DEFINED) {
917                 r->user_defined_name = ast_event_get_ie_str(e, AST_EVENT_IE_CEL_USEREVENT_NAME);
918         } else {
919                 r->user_defined_name = "";
920         }
921
922         r->caller_id_name   = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CIDNAME), "");
923         r->caller_id_num    = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CIDNUM), "");
924         r->caller_id_ani    = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CIDANI), "");
925         r->caller_id_rdnis  = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CIDRDNIS), "");
926         r->caller_id_dnid   = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CIDDNID), "");
927         r->extension        = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_EXTEN), "");
928         r->context          = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CONTEXT), "");
929         r->channel_name     = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CHANNAME), "");
930         r->application_name = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_APPNAME), "");
931         r->application_data = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_APPDATA), "");
932         r->account_code     = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_ACCTCODE), "");
933         r->peer_account     = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_ACCTCODE), "");
934         r->unique_id        = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_UNIQUEID), "");
935         r->linked_id        = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_LINKEDID), "");
936         r->amaflag          = ast_event_get_ie_uint(e, AST_EVENT_IE_CEL_AMAFLAGS);
937         r->user_field       = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_USERFIELD), "");
938         r->peer             = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_PEER), "");
939         r->extra            = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_EXTRA), "");
940
941         return 0;
942 }
943
944 /*! \brief Typedef for callbacks that get called on channel snapshot updates */
945 typedef void (*cel_channel_snapshot_monitor)(
946         struct ast_channel_snapshot *old_snapshot,
947         struct ast_channel_snapshot *new_snapshot);
948
949 static struct ast_multi_channel_blob *get_dialstatus_blob(const char *uniqueid)
950 {
951         return ao2_find(cel_dialstatus_store, uniqueid, OBJ_KEY | OBJ_UNLINK);
952 }
953
954 static const char *get_blob_variable(struct ast_multi_channel_blob *blob, const char *varname)
955 {
956         struct ast_json *json = ast_multi_channel_blob_get_json(blob);
957         if (!json) {
958                 return NULL;
959         }
960
961         json = ast_json_object_get(json, varname);
962         if (!json) {
963                 return NULL;
964         }
965
966         return ast_json_string_get(json);
967 }
968
969 /*! \brief Handle channel state changes */
970 static void cel_channel_state_change(
971         struct ast_channel_snapshot *old_snapshot,
972         struct ast_channel_snapshot *new_snapshot)
973 {
974         int is_hungup, was_hungup;
975
976         if (!new_snapshot) {
977                 cel_report_event(old_snapshot, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
978                 check_retire_linkedid(old_snapshot);
979                 return;
980         }
981
982         if (!old_snapshot) {
983                 cel_report_event(new_snapshot, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
984                 return;
985         }
986
987         was_hungup = ast_test_flag(&old_snapshot->flags, AST_FLAG_DEAD) ? 1 : 0;
988         is_hungup = ast_test_flag(&new_snapshot->flags, AST_FLAG_DEAD) ? 1 : 0;
989
990         if (!was_hungup && is_hungup) {
991                 RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
992                 RAII_VAR(struct ast_multi_channel_blob *, blob, get_dialstatus_blob(new_snapshot->uniqueid), ao2_cleanup);
993                 const char *dialstatus = "";
994                 if (blob && !ast_strlen_zero(get_blob_variable(blob, "dialstatus"))) {
995                         dialstatus = get_blob_variable(blob, "dialstatus");
996                 }
997                 extra = ast_json_pack("{s: i, s: s, s: s}",
998                         "hangupcause", new_snapshot->hangupcause,
999                         "hangupsource", new_snapshot->hangupsource,
1000                         "dialstatus", dialstatus);
1001                 cel_report_event(new_snapshot, AST_CEL_HANGUP, NULL, extra, NULL);
1002                 return;
1003         }
1004
1005         if (old_snapshot->state != new_snapshot->state && new_snapshot->state == AST_STATE_UP) {
1006                 cel_report_event(new_snapshot, AST_CEL_ANSWER, NULL, NULL, NULL);
1007                 return;
1008         }
1009 }
1010
1011 static void cel_channel_linkedid_change(
1012         struct ast_channel_snapshot *old_snapshot,
1013         struct ast_channel_snapshot *new_snapshot)
1014 {
1015         if (!old_snapshot || !new_snapshot) {
1016                 return;
1017         }
1018
1019         ast_assert(!ast_strlen_zero(new_snapshot->linkedid));
1020         ast_assert(!ast_strlen_zero(old_snapshot->linkedid));
1021
1022         if (strcmp(old_snapshot->linkedid, new_snapshot->linkedid)) {
1023                 cel_linkedid_ref(new_snapshot->linkedid);
1024                 check_retire_linkedid(old_snapshot);
1025         }
1026 }
1027
1028 static void cel_channel_app_change(
1029         struct ast_channel_snapshot *old_snapshot,
1030         struct ast_channel_snapshot *new_snapshot)
1031 {
1032         if (new_snapshot && old_snapshot
1033                 && !strcmp(old_snapshot->appl, new_snapshot->appl)) {
1034                 return;
1035         }
1036
1037         /* old snapshot has an application, end it */
1038         if (old_snapshot && !ast_strlen_zero(old_snapshot->appl)) {
1039                 cel_report_event(old_snapshot, AST_CEL_APP_END, NULL, NULL, NULL);
1040         }
1041
1042         /* new snapshot has an application, start it */
1043         if (new_snapshot && !ast_strlen_zero(new_snapshot->appl)) {
1044                 cel_report_event(new_snapshot, AST_CEL_APP_START, NULL, NULL, NULL);
1045         }
1046 }
1047
1048 /* \brief Handlers for channel snapshot changes.
1049  * \note Order of the handlers matters. Application changes must come before state
1050  * changes to ensure that hangup notifications occur after application changes.
1051  * Linkedid checking should always come last.
1052  */
1053 cel_channel_snapshot_monitor cel_channel_monitors[] = {
1054         cel_channel_app_change,
1055         cel_channel_state_change,
1056         cel_channel_linkedid_change,
1057 };
1058
1059 static void update_bridge_primary(struct ast_channel_snapshot *snapshot)
1060 {
1061         RAII_VAR(struct bridge_assoc *, assoc, NULL, ao2_cleanup);
1062
1063         if (!snapshot) {
1064                 return;
1065         }
1066
1067         assoc = ao2_find(bridge_primaries, snapshot->uniqueid, OBJ_KEY);
1068         if (!assoc) {
1069                 return;
1070         }
1071
1072         ao2_cleanup(assoc->primary_snapshot);
1073         ao2_ref(snapshot, +1);
1074         assoc->primary_snapshot = snapshot;
1075 }
1076
1077 static int bridge_match_cb(void *obj, void *arg, int flags)
1078 {
1079         struct bridge_assoc *assoc = obj;
1080         char *bridge_id = arg;
1081         if (!strcmp(bridge_id, assoc->bridge_id)) {
1082                 return CMP_MATCH;
1083         }
1084         return 0;
1085 }
1086
1087 static struct bridge_assoc *find_bridge_primary_by_bridge_id(const char *bridge_id)
1088 {
1089         char *dup_id = ast_strdupa(bridge_id);
1090         return ao2_callback(bridge_primaries, 0, bridge_match_cb, dup_id);
1091 }
1092
1093 static void clear_bridge_primary(const char *bridge_id)
1094 {
1095         char *dup_id = ast_strdupa(bridge_id);
1096         ao2_callback(bridge_primaries, OBJ_KEY | OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, bridge_match_cb, dup_id);
1097 }
1098
1099 static int cel_filter_channel_snapshot(struct ast_channel_snapshot *snapshot)
1100 {
1101         if (!snapshot) {
1102                 return 0;
1103         }
1104         return snapshot->tech_properties & (AST_CHAN_TP_ANNOUNCER | AST_CHAN_TP_RECORDER);
1105 }
1106
1107 static void cel_snapshot_update_cb(void *data, struct stasis_subscription *sub,
1108         struct stasis_topic *topic,
1109         struct stasis_message *message)
1110 {
1111         struct stasis_cache_update *update = stasis_message_data(message);
1112         if (ast_channel_snapshot_type() == update->type) {
1113                 struct ast_channel_snapshot *old_snapshot;
1114                 struct ast_channel_snapshot *new_snapshot;
1115                 size_t i;
1116
1117                 old_snapshot = stasis_message_data(update->old_snapshot);
1118                 new_snapshot = stasis_message_data(update->new_snapshot);
1119
1120                 if (cel_filter_channel_snapshot(old_snapshot) || cel_filter_channel_snapshot(new_snapshot)) {
1121                         return;
1122                 }
1123
1124                 update_bridge_primary(new_snapshot);
1125
1126                 for (i = 0; i < ARRAY_LEN(cel_channel_monitors); ++i) {
1127                         cel_channel_monitors[i](old_snapshot, new_snapshot);
1128                 }
1129         } else if (ast_bridge_snapshot_type() == update->type) {
1130                 struct ast_bridge_snapshot *old_snapshot;
1131                 struct ast_bridge_snapshot *new_snapshot;
1132
1133                 old_snapshot = stasis_message_data(update->old_snapshot);
1134                 new_snapshot = stasis_message_data(update->new_snapshot);
1135
1136                 if (!old_snapshot) {
1137                         return;
1138                 }
1139
1140                 if (!new_snapshot) {
1141                         clear_bridge_primary(old_snapshot->uniqueid);
1142                         return;
1143                 }
1144         }
1145 }
1146
1147 static void cel_bridge_enter_cb(
1148         void *data, struct stasis_subscription *sub,
1149         struct stasis_topic *topic,
1150         struct stasis_message *message)
1151 {
1152         struct ast_bridge_blob *blob = stasis_message_data(message);
1153         struct ast_bridge_snapshot *snapshot = blob->bridge;
1154         struct ast_channel_snapshot *chan_snapshot = blob->channel;
1155         RAII_VAR(struct bridge_assoc *, assoc, find_bridge_primary_by_bridge_id(snapshot->uniqueid), ao2_cleanup);
1156
1157         if (cel_filter_channel_snapshot(chan_snapshot)) {
1158                 return;
1159         }
1160
1161         if (snapshot->capabilities & (AST_BRIDGE_CAPABILITY_1TO1MIX | AST_BRIDGE_CAPABILITY_NATIVE)) {
1162                 if (assoc && assoc->track_as_conf) {
1163                         RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1164                         extra = ast_json_pack("{s: s}", "bridge_id", snapshot->uniqueid);
1165                         if (extra) {
1166                                 cel_report_event(chan_snapshot, AST_CEL_CONF_ENTER, NULL, extra, NULL);
1167                         }
1168                         return;
1169                 }
1170
1171                 if (ao2_container_count(snapshot->channels) == 2) {
1172                         struct ao2_iterator i;
1173                         RAII_VAR(char *, channel_id, NULL, ao2_cleanup);
1174                         RAII_VAR(struct ast_channel_snapshot *, latest_primary, NULL, ao2_cleanup);
1175
1176                         /* get the name of the channel in the container we don't already know the name of */
1177                         i = ao2_iterator_init(snapshot->channels, 0);
1178                         while ((channel_id = ao2_iterator_next(&i))) {
1179                                 if (strcmp(channel_id, chan_snapshot->uniqueid)) {
1180                                         break;
1181                                 }
1182                                 ao2_cleanup(channel_id);
1183                                 channel_id = NULL;
1184                         }
1185                         ao2_iterator_destroy(&i);
1186
1187                         latest_primary = ast_channel_snapshot_get_latest(channel_id);
1188                         if (!latest_primary) {
1189                                 return;
1190                         }
1191
1192                         add_bridge_primary(latest_primary, snapshot->uniqueid, chan_snapshot->name);
1193                         cel_report_event(latest_primary, AST_CEL_BRIDGE_START, NULL, NULL, chan_snapshot->name);
1194                 } else if (ao2_container_count(snapshot->channels) > 2) {
1195                         if (!assoc) {
1196                                 ast_log(LOG_ERROR, "No association found for bridge %s\n", snapshot->uniqueid);
1197                                 return;
1198                         }
1199
1200                         /* this bridge will no longer be treated like a bridge, so mark the bridge_assoc as such */
1201                         if (!assoc->track_as_conf) {
1202                                 RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1203                                 assoc->track_as_conf = 1;
1204
1205                                 extra = ast_json_pack("{s: s, s: s}",
1206                                         "channel_name", chan_snapshot->name,
1207                                         "bridge_id", snapshot->uniqueid);
1208
1209                                 if (extra) {
1210                                         cel_report_event(assoc->primary_snapshot, AST_CEL_BRIDGE_TO_CONF, NULL,
1211                                                 extra, assoc->secondary_name);
1212                                 }
1213
1214                                 ast_string_field_set(assoc, secondary_name, "");
1215                         }
1216                 }
1217         } else if (snapshot->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX) {
1218                 RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1219                 if (!assoc) {
1220                         add_bridge_primary(chan_snapshot, snapshot->uniqueid, "");
1221                         return;
1222                 }
1223                 extra = ast_json_pack("{s: s}", "bridge_id", snapshot->uniqueid);
1224                 if (extra) {
1225                         cel_report_event(chan_snapshot, AST_CEL_CONF_ENTER, NULL, extra, NULL);
1226                 }
1227         }
1228 }
1229
1230 static void cel_bridge_leave_cb(
1231         void *data, struct stasis_subscription *sub,
1232         struct stasis_topic *topic,
1233         struct stasis_message *message)
1234 {
1235         struct ast_bridge_blob *blob = stasis_message_data(message);
1236         struct ast_bridge_snapshot *snapshot = blob->bridge;
1237         struct ast_channel_snapshot *chan_snapshot = blob->channel;
1238
1239         if (cel_filter_channel_snapshot(chan_snapshot)) {
1240                 return;
1241         }
1242
1243         if (snapshot->capabilities & (AST_BRIDGE_CAPABILITY_1TO1MIX | AST_BRIDGE_CAPABILITY_NATIVE)) {
1244                 RAII_VAR(struct bridge_assoc *, assoc,
1245                         find_bridge_primary_by_bridge_id(snapshot->uniqueid),
1246                         ao2_cleanup);
1247
1248                 if (!assoc) {
1249                         return;
1250                 }
1251
1252                 if (assoc->track_as_conf) {
1253                         RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1254                         extra = ast_json_pack("{s: s}", "bridge_id", snapshot->uniqueid);
1255                         if (extra) {
1256                                 cel_report_event(chan_snapshot, AST_CEL_CONF_EXIT, NULL, extra, NULL);
1257                         }
1258                         return;
1259                 }
1260
1261                 if (ao2_container_count(snapshot->channels) == 1) {
1262                         cel_report_event(assoc->primary_snapshot, AST_CEL_BRIDGE_END, NULL, NULL, assoc->secondary_name);
1263                         remove_bridge_primary(assoc->primary_snapshot->uniqueid);
1264                         return;
1265                 }
1266         } else if (snapshot->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX) {
1267                 RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1268                 extra = ast_json_pack("{s: s}", "bridge_id", snapshot->uniqueid);
1269                 if (extra) {
1270                         cel_report_event(chan_snapshot, AST_CEL_CONF_EXIT, NULL, extra, NULL);
1271                 }
1272         }
1273 }
1274
1275 static void cel_parking_cb(
1276         void *data, struct stasis_subscription *sub,
1277         struct stasis_topic *topic,
1278         struct stasis_message *message)
1279 {
1280         struct ast_parked_call_payload *parked_payload = stasis_message_data(message);
1281         RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1282         const char *reason = NULL;
1283
1284         switch (parked_payload->event_type) {
1285         case PARKED_CALL:
1286                 extra = ast_json_pack("{s: s, s: s}",
1287                         "parker_dial_string", parked_payload->parker_dial_string,
1288                         "parking_lot", parked_payload->parkinglot);
1289                 if (extra) {
1290                         cel_report_event(parked_payload->parkee, AST_CEL_PARK_START, NULL, extra, NULL);
1291                 }
1292                 return;
1293         case PARKED_CALL_TIMEOUT:
1294                 reason = "ParkedCallTimeOut";
1295                 break;
1296         case PARKED_CALL_GIVEUP:
1297                 reason = "ParkedCallGiveUp";
1298                 break;
1299         case PARKED_CALL_UNPARKED:
1300                 reason = "ParkedCallUnparked";
1301                 break;
1302         case PARKED_CALL_FAILED:
1303                 reason = "ParkedCallFailed";
1304                 break;
1305         }
1306
1307         extra = ast_json_pack("{s: s}", "reason", reason);
1308         if (extra) {
1309                 cel_report_event(parked_payload->parkee, AST_CEL_PARK_END, NULL, extra, NULL);
1310         }
1311 }
1312
1313 static void save_dialstatus(struct ast_multi_channel_blob *blob)
1314 {
1315         ao2_link(cel_dialstatus_store, blob);
1316 }
1317
1318 static void cel_dial_cb(void *data, struct stasis_subscription *sub,
1319         struct stasis_topic *topic,
1320         struct stasis_message *message)
1321 {
1322         struct ast_multi_channel_blob *blob = stasis_message_data(message);
1323
1324         if (cel_filter_channel_snapshot(ast_multi_channel_blob_get_channel(blob, "caller"))) {
1325                 return;
1326         }
1327
1328         if (!get_caller_uniqueid(blob)) {
1329                 return;
1330         }
1331
1332         if (!ast_strlen_zero(get_blob_variable(blob, "forward"))) {
1333                 struct ast_channel_snapshot *caller = ast_multi_channel_blob_get_channel(blob, "caller");
1334                 RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1335                 if (!caller) {
1336                         return;
1337                 }
1338
1339                 extra = ast_json_pack("{s: s}", "forward", get_blob_variable(blob, "forward"));
1340                 if (extra) {
1341                         cel_report_event(caller, AST_CEL_FORWARD, NULL, extra, NULL);
1342                 }
1343         }
1344
1345         if (ast_strlen_zero(get_blob_variable(blob, "dialstatus"))) {
1346                 return;
1347         }
1348
1349         save_dialstatus(blob);
1350 }
1351
1352 static void cel_generic_cb(
1353         void *data, struct stasis_subscription *sub,
1354         struct stasis_topic *topic,
1355         struct stasis_message *message)
1356 {
1357         struct ast_channel_blob *obj = stasis_message_data(message);
1358         int event_type = ast_json_integer_get(ast_json_object_get(obj->blob, "event_type"));
1359         struct ast_json *event_details = ast_json_object_get(obj->blob, "event_details");
1360
1361         switch (event_type) {
1362         case AST_CEL_USER_DEFINED:
1363                 {
1364                         const char *event = ast_json_string_get(ast_json_object_get(event_details, "event"));
1365                         struct ast_json *extra = ast_json_object_get(event_details, "extra");
1366                         cel_report_event(obj->snapshot, event_type, event, extra, NULL);
1367                         break;
1368                 }
1369         default:
1370                 ast_log(LOG_ERROR, "Unhandled %s event blob\n", ast_cel_get_type_name(event_type));
1371                 break;
1372         }
1373 }
1374
1375 static void cel_blind_transfer_cb(
1376         void *data, struct stasis_subscription *sub,
1377         struct stasis_topic *topic,
1378         struct stasis_message *message)
1379 {
1380         struct ast_bridge_blob *obj = stasis_message_data(message);
1381         struct ast_channel_snapshot *chan_snapshot = obj->channel;
1382         struct ast_bridge_snapshot *bridge_snapshot = obj->bridge;
1383         struct ast_json *blob = obj->blob;
1384         struct ast_json *json_exten = ast_json_object_get(blob, "exten");
1385         struct ast_json *json_context = ast_json_object_get(blob, "context");
1386         RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1387         const char *exten, *context;
1388
1389         if (!json_exten || !json_context) {
1390                 return;
1391         }
1392
1393         exten = ast_json_string_get(json_exten);
1394         context = ast_json_string_get(json_context);
1395         if (!exten || !context) {
1396                 return;
1397         }
1398         extra = ast_json_pack("{s: s, s: s, s: s}",
1399                 "extension", exten,
1400                 "context", context,
1401                 "bridge_id", bridge_snapshot->uniqueid);
1402
1403         if (extra) {
1404                 cel_report_event(chan_snapshot, AST_CEL_BLINDTRANSFER, NULL, extra, NULL);
1405         }
1406 }
1407
1408 static void cel_attended_transfer_cb(
1409         void *data, struct stasis_subscription *sub,
1410         struct stasis_topic *topic,
1411         struct stasis_message *message)
1412 {
1413         struct ast_attended_transfer_message *xfer = stasis_message_data(message);
1414         RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1415         struct ast_bridge_snapshot *bridge1, *bridge2;
1416         struct ast_channel_snapshot *channel1, *channel2;
1417
1418         /* Make sure bridge1 is always non-NULL */
1419         if (!xfer->to_transferee.bridge_snapshot) {
1420                 bridge1 = xfer->to_transfer_target.bridge_snapshot;
1421                 bridge2 = xfer->to_transferee.bridge_snapshot;
1422                 channel1 = xfer->to_transfer_target.channel_snapshot;
1423                 channel2 = xfer->to_transferee.channel_snapshot;
1424         } else {
1425                 bridge1 = xfer->to_transferee.bridge_snapshot;
1426                 bridge2 = xfer->to_transfer_target.bridge_snapshot;
1427                 channel1 = xfer->to_transferee.channel_snapshot;
1428                 channel2 = xfer->to_transfer_target.channel_snapshot;
1429         }
1430
1431         switch (xfer->dest_type) {
1432         case AST_ATTENDED_TRANSFER_DEST_FAIL:
1433                 return;
1434                 /* handle these two the same */
1435         case AST_ATTENDED_TRANSFER_DEST_BRIDGE_MERGE:
1436         case AST_ATTENDED_TRANSFER_DEST_LINK:
1437                 extra = ast_json_pack("{s: s, s: s, s: s}",
1438                         "bridge1_id", bridge1->uniqueid,
1439                         "channel2_name", channel2->name,
1440                         "bridge2_id", bridge2->uniqueid);
1441
1442                 if (!extra) {
1443                         return;
1444                 }
1445                 break;
1446         case AST_ATTENDED_TRANSFER_DEST_APP:
1447                 extra = ast_json_pack("{s: s, s: s, s: s}",
1448                         "bridge1_id", bridge1->uniqueid,
1449                         "channel2_name", channel2->name,
1450                         "app", xfer->dest.app);
1451
1452                 if (!extra) {
1453                         return;
1454                 }
1455                 break;
1456         }
1457         cel_report_event(channel1, AST_CEL_ATTENDEDTRANSFER, NULL, extra, NULL);
1458 }
1459
1460 static void cel_pickup_cb(
1461         void *data, struct stasis_subscription *sub,
1462         struct stasis_topic *topic,
1463         struct stasis_message *message)
1464 {
1465         struct ast_multi_channel_blob *obj = stasis_message_data(message);
1466         struct ast_channel_snapshot *channel = ast_multi_channel_blob_get_channel(obj, "channel");
1467         struct ast_channel_snapshot *target = ast_multi_channel_blob_get_channel(obj, "target");
1468
1469         if (!channel || !target) {
1470                 return;
1471         }
1472
1473         cel_report_event(target, AST_CEL_PICKUP, NULL, NULL, channel->name);
1474 }
1475
1476 static void ast_cel_engine_term(void)
1477 {
1478         aco_info_destroy(&cel_cfg_info);
1479         ao2_global_obj_release(cel_configs);
1480         stasis_message_router_unsubscribe_and_join(cel_state_router);
1481         cel_state_router = NULL;
1482         ao2_cleanup(cel_aggregation_topic);
1483         cel_aggregation_topic = NULL;
1484         ao2_cleanup(cel_topic);
1485         cel_topic = NULL;
1486         cel_channel_forwarder = stasis_unsubscribe_and_join(cel_channel_forwarder);
1487         cel_bridge_forwarder = stasis_unsubscribe_and_join(cel_bridge_forwarder);
1488         cel_parking_forwarder = stasis_unsubscribe_and_join(cel_parking_forwarder);
1489         cel_cel_forwarder = stasis_unsubscribe_and_join(cel_cel_forwarder);
1490         ao2_cleanup(bridge_primaries);
1491         bridge_primaries = NULL;
1492         ast_cli_unregister(&cli_status);
1493         ao2_cleanup(cel_dialstatus_store);
1494         cel_dialstatus_store = NULL;
1495         ao2_cleanup(linkedids);
1496         linkedids = NULL;
1497         STASIS_MESSAGE_TYPE_CLEANUP(cel_generic_type);
1498 }
1499
1500 int ast_cel_engine_init(void)
1501 {
1502         int ret = 0;
1503         if (!(linkedids = ast_str_container_alloc(NUM_APP_BUCKETS))) {
1504                 return -1;
1505         }
1506
1507         if (!(cel_dialstatus_store = ao2_container_alloc(NUM_DIALSTATUS_BUCKETS, dialstatus_hash, dialstatus_cmp))) {
1508                 return -1;
1509         }
1510
1511         if (STASIS_MESSAGE_TYPE_INIT(cel_generic_type)) {
1512                 return -1;
1513         }
1514
1515         if (ast_cli_register(&cli_status)) {
1516                 return -1;
1517         }
1518
1519         bridge_primaries = ao2_container_alloc(BRIDGE_PRIMARY_BUCKETS, bridge_assoc_hash, bridge_assoc_cmp);
1520         if (!bridge_primaries) {
1521                 return -1;
1522         }
1523
1524         cel_aggregation_topic = stasis_topic_create("cel_aggregation_topic");
1525         if (!cel_aggregation_topic) {
1526                 return -1;
1527         }
1528
1529         cel_topic = stasis_topic_create("cel_topic");
1530         if (!cel_topic) {
1531                 return -1;
1532         }
1533
1534         cel_channel_forwarder = stasis_forward_all(
1535                 stasis_caching_get_topic(ast_channel_topic_all_cached()),
1536                 cel_aggregation_topic);
1537         if (!cel_channel_forwarder) {
1538                 return -1;
1539         }
1540
1541         cel_bridge_forwarder = stasis_forward_all(
1542                 stasis_caching_get_topic(ast_bridge_topic_all_cached()),
1543                 cel_aggregation_topic);
1544         if (!cel_bridge_forwarder) {
1545                 return -1;
1546         }
1547
1548         cel_parking_forwarder = stasis_forward_all(
1549                 ast_parking_topic(),
1550                 cel_aggregation_topic);
1551         if (!cel_parking_forwarder) {
1552                 return -1;
1553         }
1554
1555         cel_cel_forwarder = stasis_forward_all(
1556                 ast_cel_topic(),
1557                 cel_aggregation_topic);
1558         if (!cel_cel_forwarder) {
1559                 return -1;
1560         }
1561
1562         cel_state_router = stasis_message_router_create(cel_aggregation_topic);
1563         if (!cel_state_router) {
1564                 return -1;
1565         }
1566
1567         ret |= stasis_message_router_add(cel_state_router,
1568                 stasis_cache_update_type(),
1569                 cel_snapshot_update_cb,
1570                 NULL);
1571
1572         ret |= stasis_message_router_add(cel_state_router,
1573                 ast_channel_dial_type(),
1574                 cel_dial_cb,
1575                 NULL);
1576
1577         ret |= stasis_message_router_add(cel_state_router,
1578                 ast_channel_entered_bridge_type(),
1579                 cel_bridge_enter_cb,
1580                 NULL);
1581
1582         ret |= stasis_message_router_add(cel_state_router,
1583                 ast_channel_left_bridge_type(),
1584                 cel_bridge_leave_cb,
1585                 NULL);
1586
1587         ret |= stasis_message_router_add(cel_state_router,
1588                 ast_parked_call_type(),
1589                 cel_parking_cb,
1590                 NULL);
1591
1592         ret |= stasis_message_router_add(cel_state_router,
1593                 cel_generic_type(),
1594                 cel_generic_cb,
1595                 NULL);
1596
1597         ret |= stasis_message_router_add(cel_state_router,
1598                 ast_blind_transfer_type(),
1599                 cel_blind_transfer_cb,
1600                 NULL);
1601
1602         ret |= stasis_message_router_add(cel_state_router,
1603                 ast_attended_transfer_type(),
1604                 cel_attended_transfer_cb,
1605                 NULL);
1606
1607         ret |= stasis_message_router_add(cel_state_router,
1608                 ast_call_pickup_type(),
1609                 cel_pickup_cb,
1610                 NULL);
1611
1612         /* If somehow we failed to add any routes, just shut down the whole
1613          * thing and fail it.
1614          */
1615         if (ret) {
1616                 ast_cel_engine_term();
1617                 return -1;
1618         }
1619
1620         if (aco_info_init(&cel_cfg_info)) {
1621                 return -1;
1622         }
1623
1624         aco_option_register(&cel_cfg_info, "enable", ACO_EXACT, general_options, "no", OPT_BOOL_T, 1, FLDSET(struct ast_cel_general_config, enable));
1625         aco_option_register(&cel_cfg_info, "dateformat", ACO_EXACT, general_options, "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_cel_general_config, date_format));
1626         aco_option_register_custom(&cel_cfg_info, "apps", ACO_EXACT, general_options, "", apps_handler, 0);
1627         aco_option_register_custom(&cel_cfg_info, "events", ACO_EXACT, general_options, "", events_handler, 0);
1628
1629         aco_process_config(&cel_cfg_info, 0);
1630
1631         ast_register_cleanup(ast_cel_engine_term);
1632
1633         return 0;
1634 }
1635
1636 int ast_cel_engine_reload(void)
1637 {
1638         return do_reload();
1639 }
1640
1641 void ast_cel_publish_event(struct ast_channel *chan,
1642         enum ast_cel_event_type event_type,
1643         struct ast_json *blob)
1644 {
1645         RAII_VAR(struct ast_channel_blob *, obj, NULL, ao2_cleanup);
1646         RAII_VAR(struct ast_json *, cel_blob, NULL, ast_json_unref);
1647         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1648         cel_blob = ast_json_pack("{s: i, s: O}",
1649                 "event_type", event_type,
1650                 "event_details", blob);
1651
1652         message = ast_channel_blob_create(chan, cel_generic_type(), cel_blob);
1653         if (message) {
1654                 stasis_publish(ast_cel_topic(), message);
1655         }
1656 }
1657
1658 struct stasis_topic *ast_cel_topic(void)
1659 {
1660         return cel_topic;
1661 }
1662
1663 struct ast_cel_general_config *ast_cel_get_config(void)
1664 {
1665         RAII_VAR(struct cel_config *, mod_cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
1666         ao2_ref(mod_cfg->general, +1);
1667         return mod_cfg->general;
1668 }
1669
1670 void ast_cel_set_config(struct ast_cel_general_config *config)
1671 {
1672         RAII_VAR(struct cel_config *, mod_cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
1673         ao2_cleanup(mod_cfg->general);
1674         mod_cfg->general = config;
1675         ao2_ref(mod_cfg->general, +1);
1676 }
1677