0e9519a1d0ed78731e84b6b5170e0092bb09dc4e
[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
65 /*** DOCUMENTATION
66         <configInfo name="cel" language="en_US">
67                 <configFile name="cel.conf">
68                         <configObject name="general">
69                                 <synopsis>Options that apply globally to Channel Event Logging (CEL)</synopsis>
70                                 <configOption name="enable">
71                                         <synopsis>Determines whether CEL is enabled</synopsis>
72                                 </configOption>
73                                 <configOption name="dateformat">
74                                         <synopsis>The format to be used for dates when logging</synopsis>
75                                 </configOption>
76                                 <configOption name="apps">
77                                         <synopsis>List of apps for CEL to track</synopsis>
78                                         <description><para>A case-insensitive, comma-separated list of applications
79                                         to track when one or both of APP_START and APP_END events are flagged for
80                                         tracking</para></description>
81                                 </configOption>
82                                 <configOption name="events">
83                                         <synopsis>List of events for CEL to track</synopsis>
84                                         <description><para>A case-sensitive, comma-separated list of event names
85                                         to track. These event names do not include the leading <literal>AST_CEL</literal>.
86                                         </para>
87                                         <enumlist>
88                                                 <enum name="ALL">
89                                                         <para>Special value which tracks all events.</para>
90                                                 </enum>
91                                                 <enum name="CHAN_START"/>
92                                                 <enum name="CHAN_END"/>
93                                                 <enum name="ANSWER"/>
94                                                 <enum name="HANGUP"/>
95                                                 <enum name="APP_START"/>
96                                                 <enum name="APP_END"/>
97                                                 <enum name="BRIDGE_START"/>
98                                                 <enum name="BRIDGE_END"/>
99                                                 <enum name="BRIDGE_TO_CONF"/>
100                                                 <enum name="CONF_START"/>
101                                                 <enum name="CONF_END"/>
102                                                 <enum name="PARK_START"/>
103                                                 <enum name="PARK_END"/>
104                                                 <enum name="TRANSFER"/>
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_TRANSFER]         = "TRANSFER",
312         [AST_CEL_USER_DEFINED]     = "USER_DEFINED",
313         [AST_CEL_CONF_ENTER]       = "CONF_ENTER",
314         [AST_CEL_CONF_EXIT]        = "CONF_EXIT",
315         [AST_CEL_BLINDTRANSFER]    = "BLINDTRANSFER",
316         [AST_CEL_ATTENDEDTRANSFER] = "ATTENDEDTRANSFER",
317         [AST_CEL_PICKUP]           = "PICKUP",
318         [AST_CEL_FORWARD]          = "FORWARD",
319         [AST_CEL_3WAY_START]       = "3WAY_START",
320         [AST_CEL_3WAY_END]         = "3WAY_END",
321         [AST_CEL_HOOKFLASH]        = "HOOKFLASH",
322         [AST_CEL_LINKEDID_END]     = "LINKEDID_END",
323 };
324
325 struct bridge_assoc {
326         AST_DECLARE_STRING_FIELDS(
327                 AST_STRING_FIELD(bridge_id);           /*!< UniqueID of the bridge */
328                 AST_STRING_FIELD(secondary_name);      /*!< UniqueID of the secondary/dialed channel */
329         );
330         struct ast_channel_snapshot *primary_snapshot; /*!< The snapshot for the initiating channel in the bridge */
331         int track_as_conf;                             /*!< Whether this bridge will be treated like a conference in CEL terms */
332 };
333
334 static void bridge_assoc_dtor(void *obj)
335 {
336         struct bridge_assoc *assoc = obj;
337         ast_string_field_free_memory(assoc);
338         ao2_cleanup(assoc->primary_snapshot);
339         assoc->primary_snapshot = NULL;
340 }
341
342 static struct bridge_assoc *bridge_assoc_alloc(struct ast_channel_snapshot *primary, const char *bridge_id, const char *secondary_name)
343 {
344         RAII_VAR(struct bridge_assoc *, assoc, ao2_alloc(sizeof(*assoc), bridge_assoc_dtor), ao2_cleanup);
345         if (!primary || !assoc || ast_string_field_init(assoc, 64)) {
346                 return NULL;
347         }
348
349         ast_string_field_set(assoc, bridge_id, bridge_id);
350         ast_string_field_set(assoc, secondary_name, secondary_name);
351
352         assoc->primary_snapshot = primary;
353         ao2_ref(primary, +1);
354
355         ao2_ref(assoc, +1);
356         return assoc;
357 }
358
359 static int add_bridge_primary(struct ast_channel_snapshot *primary, const char *bridge_id, const char *secondary_name)
360 {
361         RAII_VAR(struct bridge_assoc *, assoc, bridge_assoc_alloc(primary, bridge_id, secondary_name), ao2_cleanup);
362         if (!assoc) {
363                 return -1;
364         }
365
366         ao2_link(bridge_primaries, assoc);
367         return 0;
368 }
369
370 static void remove_bridge_primary(const char *channel_id)
371 {
372         ao2_find(bridge_primaries, channel_id, OBJ_NODATA | OBJ_MULTIPLE | OBJ_UNLINK | OBJ_KEY);
373 }
374
375 /*! \brief Hashing function for bridge_assoc */
376 static int bridge_assoc_hash(const void *obj, int flags)
377 {
378         const struct bridge_assoc *assoc = obj;
379         const char *uniqueid = obj;
380         if (!(flags & OBJ_KEY)) {
381                 uniqueid = assoc->primary_snapshot->uniqueid;
382         }
383
384         return ast_str_hash(uniqueid);
385 }
386
387 /*! \brief Comparator function for bridge_assoc */
388 static int bridge_assoc_cmp(void *obj, void *arg, int flags)
389 {
390         struct bridge_assoc *assoc1 = obj, *assoc2 = arg;
391         const char *assoc2_id = arg, *assoc1_id = assoc1->primary_snapshot->uniqueid;
392         if (!(flags & OBJ_KEY)) {
393                 assoc2_id = assoc2->primary_snapshot->uniqueid;
394         }
395
396         return !strcmp(assoc1_id, assoc2_id) ? CMP_MATCH | CMP_STOP : 0;
397 }
398
399 static const char *get_caller_uniqueid(struct ast_multi_channel_blob *blob)
400 {
401         struct ast_channel_snapshot *caller = ast_multi_channel_blob_get_channel(blob, "caller");
402         if (!caller) {
403                 return NULL;
404         }
405
406         return caller->uniqueid;
407 }
408
409 /*! \brief Hashing function for dialstatus container */
410 static int dialstatus_hash(const void *obj, int flags)
411 {
412         struct ast_multi_channel_blob *blob = (void *) obj;
413         const char *uniqueid = obj;
414         if (!(flags & OBJ_KEY)) {
415                 uniqueid = get_caller_uniqueid(blob);
416         }
417
418         return ast_str_hash(uniqueid);
419 }
420
421 /*! \brief Comparator function for dialstatus container */
422 static int dialstatus_cmp(void *obj, void *arg, int flags)
423 {
424         struct ast_multi_channel_blob *blob1 = obj, *blob2 = arg;
425         const char *blob2_id = arg, *blob1_id = get_caller_uniqueid(blob1);
426         if (!(flags & OBJ_KEY)) {
427                 blob2_id = get_caller_uniqueid(blob2);
428         }
429
430         return !strcmp(blob1_id, blob2_id) ? CMP_MATCH | CMP_STOP : 0;
431 }
432
433 unsigned int ast_cel_check_enabled(void)
434 {
435         RAII_VAR(struct cel_config *, cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
436
437         if (!cfg || !cfg->general) {
438                 return 0;
439         }
440
441         return cfg->general->enable;
442 }
443
444 static int print_app(void *obj, void *arg, int flags)
445 {
446         struct ast_cli_args *a = arg;
447
448         ast_cli(a->fd, "CEL Tracking Application: %s\n", (const char *) obj);
449
450         return 0;
451 }
452
453 static void print_cel_sub(const struct ast_event *event, void *data)
454 {
455         struct ast_cli_args *a = data;
456
457         ast_cli(a->fd, "CEL Event Subscriber: %s\n",
458                         ast_event_get_ie_str(event, AST_EVENT_IE_DESCRIPTION));
459 }
460
461 static char *handle_cli_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
462 {
463         unsigned int i;
464         struct ast_event_sub *sub;
465         RAII_VAR(struct cel_config *, cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
466
467         switch (cmd) {
468         case CLI_INIT:
469                 e->command = "cel show status";
470                 e->usage =
471                         "Usage: cel show status\n"
472                         "       Displays the Channel Event Logging system status.\n";
473                 return NULL;
474         case CLI_GENERATE:
475                 return NULL;
476         case CLI_HANDLER:
477                 break;
478         }
479
480         if (a->argc > 3) {
481                 return CLI_SHOWUSAGE;
482         }
483
484         ast_cli(a->fd, "CEL Logging: %s\n", ast_cel_check_enabled() ? "Enabled" : "Disabled");
485
486         if (!cfg || !cfg->general) {
487                 return CLI_SUCCESS;
488         }
489
490         if (!cfg->general->enable) {
491                 return CLI_SUCCESS;
492         }
493
494         for (i = 0; i < (sizeof(cfg->general->events) * 8); i++) {
495                 const char *name;
496
497                 if (!(cfg->general->events & ((int64_t) 1 << i))) {
498                         continue;
499                 }
500
501                 name = ast_cel_get_type_name(i);
502                 if (strcasecmp(name, "Unknown")) {
503                         ast_cli(a->fd, "CEL Tracking Event: %s\n", name);
504                 }
505         }
506
507         ao2_callback(cfg->general->apps, OBJ_NODATA, print_app, a);
508
509         if (!(sub = ast_event_subscribe_new(AST_EVENT_SUB, print_cel_sub, a))) {
510                 return CLI_FAILURE;
511         }
512         ast_event_sub_append_ie_uint(sub, AST_EVENT_IE_EVENTTYPE, AST_EVENT_CEL);
513         ast_event_report_subs(sub);
514         ast_event_sub_destroy(sub);
515         sub = NULL;
516
517         return CLI_SUCCESS;
518 }
519
520 static struct ast_cli_entry cli_status = AST_CLI_DEFINE(handle_cli_status, "Display the CEL status");
521
522 enum ast_cel_event_type ast_cel_str_to_event_type(const char *name)
523 {
524         unsigned int i;
525
526         for (i = 0; i < ARRAY_LEN(cel_event_types); i++) {
527                 if (!cel_event_types[i]) {
528                         continue;
529                 }
530
531                 if (!strcasecmp(name, cel_event_types[i])) {
532                         return i;
533                 }
534         }
535
536         return -1;
537 }
538
539 static int ast_cel_track_event(enum ast_cel_event_type et)
540 {
541         RAII_VAR(struct cel_config *, cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
542
543         if (!cfg || !cfg->general) {
544                 return 0;
545         }
546
547         return (cfg->general->events & ((int64_t) 1 << et));
548 }
549
550 static int events_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
551 {
552         struct ast_cel_general_config *cfg = obj;
553         char *events = ast_strdupa(var->value);
554         char *cur_event;
555
556         while ((cur_event = strsep(&events, ","))) {
557                 enum ast_cel_event_type event_type;
558
559                 cur_event = ast_strip(cur_event);
560                 if (ast_strlen_zero(cur_event)) {
561                         continue;
562                 }
563
564                 event_type = ast_cel_str_to_event_type(cur_event);
565
566                 if (event_type == 0) {
567                         /* All events */
568                         cfg->events = (int64_t) -1;
569                 } else if (event_type == -1) {
570                         ast_log(LOG_ERROR, "Unknown event name '%s'\n", cur_event);
571                         return -1;
572                 } else {
573                         cfg->events |= ((int64_t) 1 << event_type);
574                 }
575         }
576
577         return 0;
578 }
579
580 static int apps_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
581 {
582         struct ast_cel_general_config *cfg = obj;
583         char *apps = ast_strdupa(var->value);
584         char *cur_app;
585
586         while ((cur_app = strsep(&apps, ","))) {
587                 cur_app = ast_strip(cur_app);
588                 if (ast_strlen_zero(cur_app)) {
589                         continue;
590                 }
591
592                 cur_app = ast_str_to_lower(cur_app);
593                 ast_str_container_add(cfg->apps, cur_app);
594         }
595
596         return 0;
597 }
598
599 static int do_reload(void)
600 {
601         if (aco_process_config(&cel_cfg_info, 1) == ACO_PROCESS_ERROR) {
602                 return -1;
603         }
604
605         ast_verb(3, "CEL logging %sabled.\n", ast_cel_check_enabled() ? "en" : "dis");
606
607         return 0;
608 }
609
610 const char *ast_cel_get_type_name(enum ast_cel_event_type type)
611 {
612         return S_OR(cel_event_types[type], "Unknown");
613 }
614
615 static int cel_track_app(const char *const_app)
616 {
617         RAII_VAR(struct cel_config *, cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
618         RAII_VAR(char *, app, NULL, ao2_cleanup);
619         char *app_lower;
620
621         if (!cfg || !cfg->general) {
622                 return 0;
623         }
624
625         app_lower = ast_str_to_lower(ast_strdupa(const_app));
626         app = ao2_find(cfg->general->apps, app_lower, OBJ_KEY);
627         if (!app) {
628                 return 0;
629         }
630
631         return 1;
632 }
633
634 static int cel_linkedid_ref(const char *linkedid);
635 struct ast_event *ast_cel_create_event(struct ast_channel_snapshot *snapshot,
636                 enum ast_cel_event_type event_type, const char *userdefevname,
637                 const char *extra, const char *peer_name)
638 {
639         struct timeval eventtime = ast_tvnow();
640         return ast_event_new(AST_EVENT_CEL,
641                 AST_EVENT_IE_CEL_EVENT_TYPE, AST_EVENT_IE_PLTYPE_UINT, event_type,
642                 AST_EVENT_IE_CEL_EVENT_TIME, AST_EVENT_IE_PLTYPE_UINT, eventtime.tv_sec,
643                 AST_EVENT_IE_CEL_EVENT_TIME_USEC, AST_EVENT_IE_PLTYPE_UINT, eventtime.tv_usec,
644                 AST_EVENT_IE_CEL_USEREVENT_NAME, AST_EVENT_IE_PLTYPE_STR, S_OR(userdefevname, ""),
645                 AST_EVENT_IE_CEL_CIDNAME, AST_EVENT_IE_PLTYPE_STR, snapshot->caller_name,
646                 AST_EVENT_IE_CEL_CIDNUM, AST_EVENT_IE_PLTYPE_STR, snapshot->caller_number,
647                 AST_EVENT_IE_CEL_CIDANI, AST_EVENT_IE_PLTYPE_STR, snapshot->caller_ani,
648                 AST_EVENT_IE_CEL_CIDRDNIS, AST_EVENT_IE_PLTYPE_STR, snapshot->caller_rdnis,
649                 AST_EVENT_IE_CEL_CIDDNID, AST_EVENT_IE_PLTYPE_STR, snapshot->caller_dnid,
650                 AST_EVENT_IE_CEL_EXTEN, AST_EVENT_IE_PLTYPE_STR, snapshot->exten,
651                 AST_EVENT_IE_CEL_CONTEXT, AST_EVENT_IE_PLTYPE_STR, snapshot->context,
652                 AST_EVENT_IE_CEL_CHANNAME, AST_EVENT_IE_PLTYPE_STR, snapshot->name,
653                 AST_EVENT_IE_CEL_APPNAME, AST_EVENT_IE_PLTYPE_STR, snapshot->appl,
654                 AST_EVENT_IE_CEL_APPDATA, AST_EVENT_IE_PLTYPE_STR, snapshot->data,
655                 AST_EVENT_IE_CEL_AMAFLAGS, AST_EVENT_IE_PLTYPE_UINT, snapshot->amaflags,
656                 AST_EVENT_IE_CEL_ACCTCODE, AST_EVENT_IE_PLTYPE_STR, snapshot->accountcode,
657                 AST_EVENT_IE_CEL_PEERACCT, AST_EVENT_IE_PLTYPE_STR, snapshot->peeraccount,
658                 AST_EVENT_IE_CEL_UNIQUEID, AST_EVENT_IE_PLTYPE_STR, snapshot->uniqueid,
659                 AST_EVENT_IE_CEL_LINKEDID, AST_EVENT_IE_PLTYPE_STR, snapshot->linkedid,
660                 AST_EVENT_IE_CEL_USERFIELD, AST_EVENT_IE_PLTYPE_STR, snapshot->userfield,
661                 AST_EVENT_IE_CEL_EXTRA, AST_EVENT_IE_PLTYPE_STR, S_OR(extra, ""),
662                 AST_EVENT_IE_CEL_PEER, AST_EVENT_IE_PLTYPE_STR, S_OR(peer_name, ""),
663                 AST_EVENT_IE_END);
664 }
665
666 static int report_event_snapshot(struct ast_channel_snapshot *snapshot,
667                 enum ast_cel_event_type event_type, const char *userdefevname,
668                 const char *extra, const char *peer2_name)
669 {
670         struct ast_event *ev;
671         char *linkedid = ast_strdupa(snapshot->linkedid);
672         const char *peer_name = peer2_name;
673         RAII_VAR(struct bridge_assoc *, assoc, NULL, ao2_cleanup);
674         RAII_VAR(struct cel_config *, cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
675
676         if (!cfg || !cfg->general) {
677                 return 0;
678         }
679
680         if (!cfg->general->enable) {
681                 return 0;
682         }
683
684         if (ast_strlen_zero(peer_name)) {
685                 assoc = ao2_find(bridge_primaries, snapshot->uniqueid, OBJ_KEY);
686                 if (assoc) {
687                         peer_name = assoc->secondary_name;
688                 }
689         }
690
691         /* Record the linkedid of new channels if we are tracking LINKEDID_END even if we aren't
692          * reporting on CHANNEL_START so we can track when to send LINKEDID_END */
693         if (ast_cel_track_event(AST_CEL_LINKEDID_END) && event_type == AST_CEL_CHANNEL_START && linkedid) {
694                 if (cel_linkedid_ref(linkedid)) {
695                         return -1;
696                 }
697         }
698
699         if (!ast_cel_track_event(event_type)) {
700                 return 0;
701         }
702
703         if ((event_type == AST_CEL_APP_START || event_type == AST_CEL_APP_END)
704                 && !cel_track_app(snapshot->appl)) {
705                 return 0;
706         }
707
708         ev = ast_cel_create_event(snapshot, event_type, userdefevname, extra, peer_name);
709         if (ev && ast_event_queue(ev)) {
710                 ast_event_destroy(ev);
711                 return -1;
712         }
713
714         return 0;
715 }
716
717 /* called whenever a channel is destroyed or a linkedid is changed to
718  * potentially emit a CEL_LINKEDID_END event */
719 static void check_retire_linkedid(struct ast_channel_snapshot *snapshot)
720 {
721         char *lid;
722
723         /* make sure we need to do all this work */
724
725         if (ast_strlen_zero(snapshot->linkedid) || !ast_cel_track_event(AST_CEL_LINKEDID_END)) {
726                 return;
727         }
728
729         if (!(lid = ao2_find(linkedids, (void *) snapshot->linkedid, OBJ_POINTER))) {
730                 ast_log(LOG_ERROR, "Something weird happened, couldn't find linkedid %s\n", snapshot->linkedid);
731                 return;
732         }
733
734         /* We have a ref for each channel with this linkedid, the link and the above find, so if
735          * before unreffing the channel we have a refcount of 3, we're done. Unlink and report. */
736         if (ao2_ref(lid, -1) == 3) {
737                 ast_str_container_remove(linkedids, lid);
738                 report_event_snapshot(snapshot, AST_CEL_LINKEDID_END, NULL, NULL, NULL);
739         }
740         ao2_ref(lid, -1);
741 }
742
743 /* Note that no 'chan_fixup' function is provided for this datastore type,
744  * because the channels that will use it will never be involved in masquerades.
745  */
746 static const struct ast_datastore_info fabricated_channel_datastore = {
747         .type = "CEL fabricated channel",
748         .destroy = ast_free_ptr,
749 };
750
751 struct ast_channel *ast_cel_fabricate_channel_from_event(const struct ast_event *event)
752 {
753         struct varshead *headp;
754         struct ast_var_t *newvariable;
755         const char *mixed_name;
756         char timebuf[30];
757         struct ast_channel *tchan;
758         struct ast_cel_event_record record = {
759                 .version = AST_CEL_EVENT_RECORD_VERSION,
760         };
761         struct ast_datastore *datastore;
762         char *app_data;
763         RAII_VAR(struct cel_config *, cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
764
765         if (!cfg || !cfg->general) {
766                 return NULL;
767         }
768
769         /* do not call ast_channel_alloc because this is not really a real channel */
770         if (!(tchan = ast_dummy_channel_alloc())) {
771                 return NULL;
772         }
773
774         headp = ast_channel_varshead(tchan);
775
776         /* first, get the variables from the event */
777         if (ast_cel_fill_record(event, &record)) {
778                 ast_channel_unref(tchan);
779                 return NULL;
780         }
781
782         /* next, fill the channel with their data */
783         mixed_name = (record.event_type == AST_CEL_USER_DEFINED)
784                 ? record.user_defined_name : record.event_name;
785         if ((newvariable = ast_var_assign("eventtype", mixed_name))) {
786                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
787         }
788
789         if (ast_strlen_zero(cfg->general->date_format)) {
790                 snprintf(timebuf, sizeof(timebuf), "%ld.%06ld", (long) record.event_time.tv_sec,
791                                 (long) record.event_time.tv_usec);
792         } else {
793                 struct ast_tm tm;
794                 ast_localtime(&record.event_time, &tm, NULL);
795                 ast_strftime(timebuf, sizeof(timebuf), cfg->general->date_format, &tm);
796         }
797
798         if ((newvariable = ast_var_assign("eventtime", timebuf))) {
799                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
800         }
801
802         if ((newvariable = ast_var_assign("eventenum", record.event_name))) {
803                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
804         }
805         if ((newvariable = ast_var_assign("userdeftype", record.user_defined_name))) {
806                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
807         }
808         if ((newvariable = ast_var_assign("eventextra", record.extra))) {
809                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
810         }
811
812         ast_channel_caller(tchan)->id.name.valid = 1;
813         ast_channel_caller(tchan)->id.name.str = ast_strdup(record.caller_id_name);
814         ast_channel_caller(tchan)->id.number.valid = 1;
815         ast_channel_caller(tchan)->id.number.str = ast_strdup(record.caller_id_num);
816         ast_channel_caller(tchan)->ani.number.valid = 1;
817         ast_channel_caller(tchan)->ani.number.str = ast_strdup(record.caller_id_ani);
818         ast_channel_redirecting(tchan)->from.number.valid = 1;
819         ast_channel_redirecting(tchan)->from.number.str = ast_strdup(record.caller_id_rdnis);
820         ast_channel_dialed(tchan)->number.str = ast_strdup(record.caller_id_dnid);
821
822         ast_channel_exten_set(tchan, record.extension);
823         ast_channel_context_set(tchan, record.context);
824         ast_channel_name_set(tchan, record.channel_name);
825         ast_channel_uniqueid_set(tchan, record.unique_id);
826         ast_channel_linkedid_set(tchan, record.linked_id);
827         ast_channel_accountcode_set(tchan, record.account_code);
828         ast_channel_peeraccount_set(tchan, record.peer_account);
829         ast_channel_userfield_set(tchan, record.user_field);
830
831         if ((newvariable = ast_var_assign("BRIDGEPEER", record.peer))) {
832                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
833         }
834
835         ast_channel_amaflags_set(tchan, record.amaflag);
836
837         /* We need to store an 'application name' and 'application
838          * data' on the channel for logging purposes, but the channel
839          * structure only provides a place to store pointers, and it
840          * expects these pointers to be pointing to data that does not
841          * need to be freed. This means that the channel's destructor
842          * does not attempt to free any storage that these pointers
843          * point to. However, we can't provide data in that form directly for
844          * these structure members. In order to ensure that these data
845          * elements have a lifetime that matches the channel's
846          * lifetime, we'll put them in a datastore attached to the
847          * channel, and set's the channel's pointers to point into the
848          * datastore.  The datastore will then be automatically destroyed
849          * when the channel is destroyed.
850          */
851
852         if (!(datastore = ast_datastore_alloc(&fabricated_channel_datastore, NULL))) {
853                 ast_channel_unref(tchan);
854                 return NULL;
855         }
856
857         if (!(app_data = ast_malloc(strlen(record.application_name) + strlen(record.application_data) + 2))) {
858                 ast_datastore_free(datastore);
859                 ast_channel_unref(tchan);
860                 return NULL;
861         }
862
863         ast_channel_appl_set(tchan, strcpy(app_data, record.application_name));
864         ast_channel_data_set(tchan, strcpy(app_data + strlen(record.application_name) + 1,
865                 record.application_data));
866
867         datastore->data = app_data;
868         ast_channel_datastore_add(tchan, datastore);
869
870         return tchan;
871 }
872
873 static int cel_linkedid_ref(const char *linkedid)
874 {
875         char *lid;
876
877         if (ast_strlen_zero(linkedid)) {
878                 ast_log(LOG_ERROR, "The linkedid should never be empty\n");
879                 return -1;
880         }
881
882         if (!(lid = ao2_find(linkedids, (void *) linkedid, OBJ_POINTER))) {
883                 if (!(lid = ao2_alloc(strlen(linkedid) + 1, NULL))) {
884                         return -1;
885                 }
886                 strcpy(lid, linkedid);
887                 if (!ao2_link(linkedids, lid)) {
888                         ao2_ref(lid, -1);
889                         return -1;
890                 }
891                 /* Leave both the link and the alloc refs to show a count of 1 + the link */
892         }
893         /* If we've found, go ahead and keep the ref to increment count of how many channels
894          * have this linkedid. We'll clean it up in check_retire */
895         return 0;
896 }
897
898 int ast_cel_report_event(struct ast_channel *chan, enum ast_cel_event_type event_type,
899                 const char *userdefevname, const char *extra, struct ast_channel *peer2)
900 {
901         struct timeval eventtime;
902         struct ast_event *ev;
903         const char *peername = "";
904         struct ast_channel *peer;
905         char *linkedid = ast_strdupa(ast_channel_linkedid(chan));
906
907         if (!ast_cel_check_enabled()) {
908                 return 0;
909         }
910
911         /* Record the linkedid of new channels if we are tracking LINKEDID_END even if we aren't
912          * reporting on CHANNEL_START so we can track when to send LINKEDID_END */
913         if (ast_cel_track_event(AST_CEL_LINKEDID_END) && event_type == AST_CEL_CHANNEL_START && linkedid) {
914                 if (cel_linkedid_ref(linkedid)) {
915                         return -1;
916                 }
917         }
918
919         if (!ast_cel_track_event(event_type)) {
920                 return 0;
921         }
922
923         if ((event_type == AST_CEL_APP_START || event_type == AST_CEL_APP_END)
924                 && !cel_track_app(ast_channel_appl(chan))) {
925                 return 0;
926         }
927
928         ast_channel_lock(chan);
929         peer = ast_bridged_channel(chan);
930         if (peer) {
931                 ast_channel_ref(peer);
932         }
933         ast_channel_unlock(chan);
934
935         if (peer) {
936                 ast_channel_lock(peer);
937                 peername = ast_strdupa(ast_channel_name(peer));
938                 ast_channel_unlock(peer);
939         } else if (peer2) {
940                 ast_channel_lock(peer2);
941                 peername = ast_strdupa(ast_channel_name(peer2));
942                 ast_channel_unlock(peer2);
943         }
944
945         if (!userdefevname) {
946                 userdefevname = "";
947         }
948
949         if (!extra) {
950                 extra = "";
951         }
952
953         eventtime = ast_tvnow();
954
955         ast_channel_lock(chan);
956
957         ev = ast_event_new(AST_EVENT_CEL,
958                 AST_EVENT_IE_CEL_EVENT_TYPE, AST_EVENT_IE_PLTYPE_UINT, event_type,
959                 AST_EVENT_IE_CEL_EVENT_TIME, AST_EVENT_IE_PLTYPE_UINT, eventtime.tv_sec,
960                 AST_EVENT_IE_CEL_EVENT_TIME_USEC, AST_EVENT_IE_PLTYPE_UINT, eventtime.tv_usec,
961                 AST_EVENT_IE_CEL_USEREVENT_NAME, AST_EVENT_IE_PLTYPE_STR, userdefevname,
962                 AST_EVENT_IE_CEL_CIDNAME, AST_EVENT_IE_PLTYPE_STR,
963                         S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, ""),
964                 AST_EVENT_IE_CEL_CIDNUM, AST_EVENT_IE_PLTYPE_STR,
965                         S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, ""),
966                 AST_EVENT_IE_CEL_CIDANI, AST_EVENT_IE_PLTYPE_STR,
967                         S_COR(ast_channel_caller(chan)->ani.number.valid, ast_channel_caller(chan)->ani.number.str, ""),
968                 AST_EVENT_IE_CEL_CIDRDNIS, AST_EVENT_IE_PLTYPE_STR,
969                         S_COR(ast_channel_redirecting(chan)->from.number.valid, ast_channel_redirecting(chan)->from.number.str, ""),
970                 AST_EVENT_IE_CEL_CIDDNID, AST_EVENT_IE_PLTYPE_STR,
971                         S_OR(ast_channel_dialed(chan)->number.str, ""),
972                 AST_EVENT_IE_CEL_EXTEN, AST_EVENT_IE_PLTYPE_STR, ast_channel_exten(chan),
973                 AST_EVENT_IE_CEL_CONTEXT, AST_EVENT_IE_PLTYPE_STR, ast_channel_context(chan),
974                 AST_EVENT_IE_CEL_CHANNAME, AST_EVENT_IE_PLTYPE_STR, ast_channel_name(chan),
975                 AST_EVENT_IE_CEL_APPNAME, AST_EVENT_IE_PLTYPE_STR, S_OR(ast_channel_appl(chan), ""),
976                 AST_EVENT_IE_CEL_APPDATA, AST_EVENT_IE_PLTYPE_STR, S_OR(ast_channel_data(chan), ""),
977                 AST_EVENT_IE_CEL_AMAFLAGS, AST_EVENT_IE_PLTYPE_UINT, ast_channel_amaflags(chan),
978                 AST_EVENT_IE_CEL_ACCTCODE, AST_EVENT_IE_PLTYPE_STR, ast_channel_accountcode(chan),
979                 AST_EVENT_IE_CEL_PEERACCT, AST_EVENT_IE_PLTYPE_STR, ast_channel_peeraccount(chan),
980                 AST_EVENT_IE_CEL_UNIQUEID, AST_EVENT_IE_PLTYPE_STR, ast_channel_uniqueid(chan),
981                 AST_EVENT_IE_CEL_LINKEDID, AST_EVENT_IE_PLTYPE_STR, ast_channel_linkedid(chan),
982                 AST_EVENT_IE_CEL_USERFIELD, AST_EVENT_IE_PLTYPE_STR, ast_channel_userfield(chan),
983                 AST_EVENT_IE_CEL_EXTRA, AST_EVENT_IE_PLTYPE_STR, extra,
984                 AST_EVENT_IE_CEL_PEER, AST_EVENT_IE_PLTYPE_STR, peername,
985                 AST_EVENT_IE_END);
986
987         ast_channel_unlock(chan);
988
989         if (peer) {
990                 peer = ast_channel_unref(peer);
991         }
992
993         if (ev && ast_event_queue(ev)) {
994                 ast_event_destroy(ev);
995                 return -1;
996         }
997
998         return 0;
999 }
1000
1001 int ast_cel_fill_record(const struct ast_event *e, struct ast_cel_event_record *r)
1002 {
1003         if (r->version != AST_CEL_EVENT_RECORD_VERSION) {
1004                 ast_log(LOG_ERROR, "Module ABI mismatch for ast_cel_event_record.  "
1005                                 "Please ensure all modules were compiled for "
1006                                 "this version of Asterisk.\n");
1007                 return -1;
1008         }
1009
1010         r->event_type = ast_event_get_ie_uint(e, AST_EVENT_IE_CEL_EVENT_TYPE);
1011
1012         r->event_time.tv_sec = ast_event_get_ie_uint(e, AST_EVENT_IE_CEL_EVENT_TIME);
1013         r->event_time.tv_usec = ast_event_get_ie_uint(e, AST_EVENT_IE_CEL_EVENT_TIME_USEC);
1014
1015         r->event_name = ast_cel_get_type_name(r->event_type);
1016         if (r->event_type == AST_CEL_USER_DEFINED) {
1017                 r->user_defined_name = ast_event_get_ie_str(e, AST_EVENT_IE_CEL_USEREVENT_NAME);
1018         } else {
1019                 r->user_defined_name = "";
1020         }
1021
1022         r->caller_id_name   = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CIDNAME), "");
1023         r->caller_id_num    = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CIDNUM), "");
1024         r->caller_id_ani    = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CIDANI), "");
1025         r->caller_id_rdnis  = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CIDRDNIS), "");
1026         r->caller_id_dnid   = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CIDDNID), "");
1027         r->extension        = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_EXTEN), "");
1028         r->context          = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CONTEXT), "");
1029         r->channel_name     = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CHANNAME), "");
1030         r->application_name = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_APPNAME), "");
1031         r->application_data = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_APPDATA), "");
1032         r->account_code     = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_ACCTCODE), "");
1033         r->peer_account     = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_ACCTCODE), "");
1034         r->unique_id        = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_UNIQUEID), "");
1035         r->linked_id        = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_LINKEDID), "");
1036         r->amaflag          = ast_event_get_ie_uint(e, AST_EVENT_IE_CEL_AMAFLAGS);
1037         r->user_field       = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_USERFIELD), "");
1038         r->peer             = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_PEER), "");
1039         r->extra            = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_EXTRA), "");
1040
1041         return 0;
1042 }
1043
1044 /*! \brief Typedef for callbacks that get called on channel snapshot updates */
1045 typedef void (*cel_channel_snapshot_monitor)(
1046         struct ast_channel_snapshot *old_snapshot,
1047         struct ast_channel_snapshot *new_snapshot);
1048
1049 static struct ast_multi_channel_blob *get_dialstatus_blob(const char *uniqueid)
1050 {
1051         return ao2_find(cel_dialstatus_store, uniqueid, OBJ_KEY | OBJ_UNLINK);
1052 }
1053
1054 static const char *get_blob_variable(struct ast_multi_channel_blob *blob, const char *varname)
1055 {
1056         struct ast_json *json = ast_multi_channel_blob_get_json(blob);
1057         if (!json) {
1058                 return NULL;
1059         }
1060
1061         json = ast_json_object_get(json, varname);
1062         if (!json) {
1063                 return NULL;
1064         }
1065
1066         return ast_json_string_get(json);
1067 }
1068
1069 /*! \brief Handle channel state changes */
1070 static void cel_channel_state_change(
1071         struct ast_channel_snapshot *old_snapshot,
1072         struct ast_channel_snapshot *new_snapshot)
1073 {
1074         int is_hungup, was_hungup;
1075
1076         if (!new_snapshot) {
1077                 report_event_snapshot(old_snapshot, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
1078                 check_retire_linkedid(old_snapshot);
1079                 return;
1080         }
1081
1082         if (!old_snapshot) {
1083                 report_event_snapshot(new_snapshot, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
1084                 return;
1085         }
1086
1087         was_hungup = ast_test_flag(&old_snapshot->flags, AST_FLAG_DEAD) ? 1 : 0;
1088         is_hungup = ast_test_flag(&new_snapshot->flags, AST_FLAG_DEAD) ? 1 : 0;
1089
1090         if (!was_hungup && is_hungup) {
1091                 RAII_VAR(struct ast_str *, extra_str, ast_str_create(128), ast_free);
1092                 RAII_VAR(struct ast_multi_channel_blob *, blob, get_dialstatus_blob(new_snapshot->uniqueid), ao2_cleanup);
1093                 const char *dialstatus = "";
1094                 if (blob && !ast_strlen_zero(get_blob_variable(blob, "dialstatus"))) {
1095                         dialstatus = get_blob_variable(blob, "dialstatus");
1096                 }
1097                 ast_str_set(&extra_str, 0, "%d,%s,%s",
1098                         new_snapshot->hangupcause,
1099                         new_snapshot->hangupsource,
1100                         dialstatus);
1101                 report_event_snapshot(new_snapshot, AST_CEL_HANGUP, NULL, ast_str_buffer(extra_str), NULL);
1102                 return;
1103         }
1104
1105         if (old_snapshot->state != new_snapshot->state && new_snapshot->state == AST_STATE_UP) {
1106                 report_event_snapshot(new_snapshot, AST_CEL_ANSWER, NULL, NULL, NULL);
1107                 return;
1108         }
1109 }
1110
1111 static void cel_channel_linkedid_change(
1112         struct ast_channel_snapshot *old_snapshot,
1113         struct ast_channel_snapshot *new_snapshot)
1114 {
1115         if (!old_snapshot || !new_snapshot) {
1116                 return;
1117         }
1118
1119         ast_assert(!ast_strlen_zero(new_snapshot->linkedid));
1120         ast_assert(!ast_strlen_zero(old_snapshot->linkedid));
1121
1122         if (strcmp(old_snapshot->linkedid, new_snapshot->linkedid)) {
1123                 cel_linkedid_ref(new_snapshot->linkedid);
1124                 check_retire_linkedid(old_snapshot);
1125         }
1126 }
1127
1128 static void cel_channel_app_change(
1129         struct ast_channel_snapshot *old_snapshot,
1130         struct ast_channel_snapshot *new_snapshot)
1131 {
1132         if (new_snapshot && old_snapshot
1133                 && !strcmp(old_snapshot->appl, new_snapshot->appl)) {
1134                 return;
1135         }
1136
1137         /* old snapshot has an application, end it */
1138         if (old_snapshot && !ast_strlen_zero(old_snapshot->appl)) {
1139                 report_event_snapshot(old_snapshot, AST_CEL_APP_END, NULL, NULL, NULL);
1140         }
1141
1142         /* new snapshot has an application, start it */
1143         if (new_snapshot && !ast_strlen_zero(new_snapshot->appl)) {
1144                 report_event_snapshot(new_snapshot, AST_CEL_APP_START, NULL, NULL, NULL);
1145         }
1146 }
1147
1148 /* \brief Handlers for channel snapshot changes.
1149  * \note Order of the handlers matters. Application changes must come before state
1150  * changes to ensure that hangup notifications occur after application changes.
1151  * Linkedid checking should always come last.
1152  */
1153 cel_channel_snapshot_monitor cel_channel_monitors[] = {
1154         cel_channel_app_change,
1155         cel_channel_state_change,
1156         cel_channel_linkedid_change,
1157 };
1158
1159 static void update_bridge_primary(struct ast_channel_snapshot *snapshot)
1160 {
1161         RAII_VAR(struct bridge_assoc *, assoc, NULL, ao2_cleanup);
1162
1163         if (!snapshot) {
1164                 return;
1165         }
1166
1167         assoc = ao2_find(bridge_primaries, snapshot->uniqueid, OBJ_KEY);
1168         if (!assoc) {
1169                 return;
1170         }
1171
1172         ao2_cleanup(assoc->primary_snapshot);
1173         ao2_ref(snapshot, +1);
1174         assoc->primary_snapshot = snapshot;
1175 }
1176
1177 static int bridge_match_cb(void *obj, void *arg, int flags)
1178 {
1179         struct bridge_assoc *assoc = obj;
1180         char *bridge_id = arg;
1181         if (!strcmp(bridge_id, assoc->bridge_id)) {
1182                 return CMP_MATCH;
1183         }
1184         return 0;
1185 }
1186
1187 static struct bridge_assoc *find_bridge_primary_by_bridge_id(const char *bridge_id)
1188 {
1189         char *dup_id = ast_strdupa(bridge_id);
1190         return ao2_callback(bridge_primaries, 0, bridge_match_cb, dup_id);
1191 }
1192
1193 static void clear_bridge_primary(const char *bridge_id)
1194 {
1195         char *dup_id = ast_strdupa(bridge_id);
1196         ao2_callback(bridge_primaries, OBJ_KEY | OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, bridge_match_cb, dup_id);
1197 }
1198
1199 static int cel_filter_channel_snapshot(struct ast_channel_snapshot *snapshot)
1200 {
1201         if (!snapshot) {
1202                 return 0;
1203         }
1204         return snapshot->tech_properties & (AST_CHAN_TP_ANNOUNCER | AST_CHAN_TP_RECORDER);
1205 }
1206
1207 static void cel_snapshot_update_cb(void *data, struct stasis_subscription *sub,
1208         struct stasis_topic *topic,
1209         struct stasis_message *message)
1210 {
1211         struct stasis_cache_update *update = stasis_message_data(message);
1212         if (ast_channel_snapshot_type() == update->type) {
1213                 struct ast_channel_snapshot *old_snapshot;
1214                 struct ast_channel_snapshot *new_snapshot;
1215                 size_t i;
1216
1217                 old_snapshot = stasis_message_data(update->old_snapshot);
1218                 new_snapshot = stasis_message_data(update->new_snapshot);
1219
1220                 if (cel_filter_channel_snapshot(old_snapshot) || cel_filter_channel_snapshot(new_snapshot)) {
1221                         return;
1222                 }
1223
1224                 update_bridge_primary(new_snapshot);
1225
1226                 for (i = 0; i < ARRAY_LEN(cel_channel_monitors); ++i) {
1227                         cel_channel_monitors[i](old_snapshot, new_snapshot);
1228                 }
1229         } else if (ast_bridge_snapshot_type() == update->type) {
1230                 struct ast_bridge_snapshot *old_snapshot;
1231                 struct ast_bridge_snapshot *new_snapshot;
1232
1233                 old_snapshot = stasis_message_data(update->old_snapshot);
1234                 new_snapshot = stasis_message_data(update->new_snapshot);
1235
1236                 if (!old_snapshot) {
1237                         return;
1238                 }
1239
1240                 if (!new_snapshot) {
1241                         clear_bridge_primary(old_snapshot->uniqueid);
1242                         return;
1243                 }
1244         }
1245 }
1246
1247 static void cel_bridge_enter_cb(
1248         void *data, struct stasis_subscription *sub,
1249         struct stasis_topic *topic,
1250         struct stasis_message *message)
1251 {
1252         struct ast_bridge_blob *blob = stasis_message_data(message);
1253         struct ast_bridge_snapshot *snapshot = blob->bridge;
1254         struct ast_channel_snapshot *chan_snapshot = blob->channel;
1255         RAII_VAR(struct bridge_assoc *, assoc, find_bridge_primary_by_bridge_id(snapshot->uniqueid), ao2_cleanup);
1256
1257         if (cel_filter_channel_snapshot(chan_snapshot)) {
1258                 return;
1259         }
1260
1261         if (snapshot->capabilities & (AST_BRIDGE_CAPABILITY_1TO1MIX | AST_BRIDGE_CAPABILITY_NATIVE)) {
1262                 if (assoc && assoc->track_as_conf) {
1263                         report_event_snapshot(chan_snapshot, AST_CEL_CONF_ENTER, NULL, NULL, NULL);
1264                         return;
1265                 }
1266
1267                 if (ao2_container_count(snapshot->channels) == 2) {
1268                         struct ao2_iterator i;
1269                         RAII_VAR(char *, channel_id, NULL, ao2_cleanup);
1270                         RAII_VAR(struct ast_channel_snapshot *, latest_primary, NULL, ao2_cleanup);
1271
1272                         /* get the name of the channel in the container we don't already know the name of */
1273                         i = ao2_iterator_init(snapshot->channels, 0);
1274                         while ((channel_id = ao2_iterator_next(&i))) {
1275                                 if (strcmp(channel_id, chan_snapshot->uniqueid)) {
1276                                         break;
1277                                 }
1278                                 ao2_cleanup(channel_id);
1279                                 channel_id = NULL;
1280                         }
1281                         ao2_iterator_destroy(&i);
1282
1283                         latest_primary = ast_channel_snapshot_get_latest(channel_id);
1284                         if (!latest_primary) {
1285                                 return;
1286                         }
1287
1288                         add_bridge_primary(latest_primary, snapshot->uniqueid, chan_snapshot->name);
1289                         report_event_snapshot(latest_primary, AST_CEL_BRIDGE_START, NULL, NULL, chan_snapshot->name);
1290                 } else if (ao2_container_count(snapshot->channels) > 2) {
1291                         if (!assoc) {
1292                                 ast_log(LOG_ERROR, "No association found for bridge %s\n", snapshot->uniqueid);
1293                                 return;
1294                         }
1295
1296                         /* this bridge will no longer be treated like a bridge, so mark the bridge_assoc as such */
1297                         if (!assoc->track_as_conf) {
1298                                 assoc->track_as_conf = 1;
1299                                 report_event_snapshot(assoc->primary_snapshot, AST_CEL_BRIDGE_TO_CONF, NULL,
1300                                         chan_snapshot->name, assoc->secondary_name);
1301                                 ast_string_field_set(assoc, secondary_name, "");
1302                         }
1303                 }
1304         } else if (snapshot->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX) {
1305                 if (!assoc) {
1306                         add_bridge_primary(chan_snapshot, snapshot->uniqueid, "");
1307                         return;
1308                 }
1309                 report_event_snapshot(chan_snapshot, AST_CEL_CONF_ENTER, NULL, NULL, NULL);
1310         }
1311 }
1312
1313 static void cel_bridge_leave_cb(
1314         void *data, struct stasis_subscription *sub,
1315         struct stasis_topic *topic,
1316         struct stasis_message *message)
1317 {
1318         struct ast_bridge_blob *blob = stasis_message_data(message);
1319         struct ast_bridge_snapshot *snapshot = blob->bridge;
1320         struct ast_channel_snapshot *chan_snapshot = blob->channel;
1321
1322         if (cel_filter_channel_snapshot(chan_snapshot)) {
1323                 return;
1324         }
1325
1326         if (snapshot->capabilities & (AST_BRIDGE_CAPABILITY_1TO1MIX | AST_BRIDGE_CAPABILITY_NATIVE)) {
1327                 RAII_VAR(struct bridge_assoc *, assoc,
1328                         find_bridge_primary_by_bridge_id(snapshot->uniqueid),
1329                         ao2_cleanup);
1330
1331                 if (!assoc) {
1332                         return;
1333                 }
1334
1335                 if (assoc->track_as_conf) {
1336                         report_event_snapshot(chan_snapshot, AST_CEL_CONF_EXIT, NULL, NULL, NULL);
1337                         return;
1338                 }
1339
1340                 if (ao2_container_count(snapshot->channels) == 1) {
1341                         report_event_snapshot(assoc->primary_snapshot, AST_CEL_BRIDGE_END, NULL, NULL, assoc->secondary_name);
1342                         remove_bridge_primary(assoc->primary_snapshot->uniqueid);
1343                         return;
1344                 }
1345         } else if (snapshot->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX) {
1346                 report_event_snapshot(chan_snapshot, AST_CEL_CONF_EXIT, NULL, NULL, NULL);
1347         }
1348 }
1349
1350 static void cel_parking_cb(
1351         void *data, struct stasis_subscription *sub,
1352         struct stasis_topic *topic,
1353         struct stasis_message *message)
1354 {
1355         struct ast_parked_call_payload *parked_payload = stasis_message_data(message);
1356
1357         switch (parked_payload->event_type) {
1358         case PARKED_CALL:
1359                 report_event_snapshot(parked_payload->parkee, AST_CEL_PARK_START, NULL,
1360                         parked_payload->parkinglot,
1361                         parked_payload->parker_dial_string);
1362                 break;
1363         case PARKED_CALL_TIMEOUT:
1364                 report_event_snapshot(parked_payload->parkee, AST_CEL_PARK_END, NULL, "ParkedCallTimeOut", NULL);
1365                 break;
1366         case PARKED_CALL_GIVEUP:
1367                 report_event_snapshot(parked_payload->parkee, AST_CEL_PARK_END, NULL, "ParkedCallGiveUp", NULL);
1368                 break;
1369         case PARKED_CALL_UNPARKED:
1370                 report_event_snapshot(parked_payload->parkee, AST_CEL_PARK_END, NULL, "ParkedCallUnparked", NULL);
1371                 break;
1372         case PARKED_CALL_FAILED:
1373                 report_event_snapshot(parked_payload->parkee, AST_CEL_PARK_END, NULL, "ParkedCallFailed", NULL);
1374                 break;
1375         }
1376 }
1377
1378 static void save_dialstatus(struct ast_multi_channel_blob *blob)
1379 {
1380         ao2_link(cel_dialstatus_store, blob);
1381 }
1382
1383 static void cel_dial_cb(void *data, struct stasis_subscription *sub,
1384         struct stasis_topic *topic,
1385         struct stasis_message *message)
1386 {
1387         struct ast_multi_channel_blob *blob = stasis_message_data(message);
1388
1389         if (cel_filter_channel_snapshot(ast_multi_channel_blob_get_channel(blob, "caller"))) {
1390                 return;
1391         }
1392
1393         if (!get_caller_uniqueid(blob)) {
1394                 return;
1395         }
1396
1397         if (!ast_strlen_zero(get_blob_variable(blob, "forward"))) {
1398                 struct ast_channel_snapshot *caller = ast_multi_channel_blob_get_channel(blob, "caller");
1399                 if (!caller) {
1400                         return;
1401                 }
1402
1403                 report_event_snapshot(caller, AST_CEL_FORWARD, NULL, get_blob_variable(blob, "forward"), NULL);
1404         }
1405
1406         if (ast_strlen_zero(get_blob_variable(blob, "dialstatus"))) {
1407                 return;
1408         }
1409
1410         save_dialstatus(blob);
1411 }
1412
1413 static void cel_generic_cb(
1414         void *data, struct stasis_subscription *sub,
1415         struct stasis_topic *topic,
1416         struct stasis_message *message)
1417 {
1418         struct ast_channel_blob *obj = stasis_message_data(message);
1419         int event_type = ast_json_integer_get(ast_json_object_get(obj->blob, "event_type"));
1420         struct ast_json *event_details = ast_json_object_get(obj->blob, "event_details");
1421
1422         switch (event_type) {
1423         case AST_CEL_USER_DEFINED:
1424                 {
1425                         const char *event = ast_json_string_get(ast_json_object_get(event_details, "event"));
1426                         const char *extra = ast_json_string_get(ast_json_object_get(event_details, "extra"));
1427                         report_event_snapshot(obj->snapshot, event_type, event, extra, NULL);
1428                         break;
1429                 }
1430         default:
1431                 ast_log(LOG_ERROR, "Unhandled %s event blob\n", ast_cel_get_type_name(event_type));
1432                 break;
1433         }
1434 }
1435
1436 static void ast_cel_engine_term(void)
1437 {
1438         aco_info_destroy(&cel_cfg_info);
1439         ao2_global_obj_release(cel_configs);
1440         stasis_message_router_unsubscribe_and_join(cel_state_router);
1441         cel_state_router = NULL;
1442         ao2_cleanup(cel_aggregation_topic);
1443         cel_aggregation_topic = NULL;
1444         ao2_cleanup(cel_topic);
1445         cel_topic = NULL;
1446         cel_channel_forwarder = stasis_unsubscribe_and_join(cel_channel_forwarder);
1447         cel_bridge_forwarder = stasis_unsubscribe_and_join(cel_bridge_forwarder);
1448         cel_parking_forwarder = stasis_unsubscribe_and_join(cel_parking_forwarder);
1449         cel_cel_forwarder = stasis_unsubscribe_and_join(cel_cel_forwarder);
1450         ao2_cleanup(bridge_primaries);
1451         bridge_primaries = NULL;
1452         ast_cli_unregister(&cli_status);
1453         ao2_cleanup(cel_dialstatus_store);
1454         cel_dialstatus_store = NULL;
1455         ao2_cleanup(linkedids);
1456         linkedids = NULL;
1457         STASIS_MESSAGE_TYPE_CLEANUP(cel_generic_type);
1458 }
1459
1460 int ast_cel_engine_init(void)
1461 {
1462         int ret = 0;
1463         if (!(linkedids = ast_str_container_alloc(NUM_APP_BUCKETS))) {
1464                 return -1;
1465         }
1466
1467         if (!(cel_dialstatus_store = ao2_container_alloc(NUM_DIALSTATUS_BUCKETS, dialstatus_hash, dialstatus_cmp))) {
1468                 return -1;
1469         }
1470
1471         if (STASIS_MESSAGE_TYPE_INIT(cel_generic_type)) {
1472                 return -1;
1473         }
1474
1475         if (ast_cli_register(&cli_status)) {
1476                 return -1;
1477         }
1478
1479         bridge_primaries = ao2_container_alloc(BRIDGE_PRIMARY_BUCKETS, bridge_assoc_hash, bridge_assoc_cmp);
1480         if (!bridge_primaries) {
1481                 return -1;
1482         }
1483
1484         cel_aggregation_topic = stasis_topic_create("cel_aggregation_topic");
1485         if (!cel_aggregation_topic) {
1486                 return -1;
1487         }
1488
1489         cel_topic = stasis_topic_create("cel_topic");
1490         if (!cel_topic) {
1491                 return -1;
1492         }
1493
1494         cel_channel_forwarder = stasis_forward_all(
1495                 stasis_caching_get_topic(ast_channel_topic_all_cached()),
1496                 cel_aggregation_topic);
1497         if (!cel_channel_forwarder) {
1498                 return -1;
1499         }
1500
1501         cel_bridge_forwarder = stasis_forward_all(
1502                 stasis_caching_get_topic(ast_bridge_topic_all_cached()),
1503                 cel_aggregation_topic);
1504         if (!cel_bridge_forwarder) {
1505                 return -1;
1506         }
1507
1508         cel_parking_forwarder = stasis_forward_all(
1509                 ast_parking_topic(),
1510                 cel_aggregation_topic);
1511         if (!cel_parking_forwarder) {
1512                 return -1;
1513         }
1514
1515         cel_cel_forwarder = stasis_forward_all(
1516                 ast_cel_topic(),
1517                 cel_aggregation_topic);
1518         if (!cel_cel_forwarder) {
1519                 return -1;
1520         }
1521
1522         cel_state_router = stasis_message_router_create(cel_aggregation_topic);
1523         if (!cel_state_router) {
1524                 return -1;
1525         }
1526
1527         ret |= stasis_message_router_add(cel_state_router,
1528                 stasis_cache_update_type(),
1529                 cel_snapshot_update_cb,
1530                 NULL);
1531
1532         ret |= stasis_message_router_add(cel_state_router,
1533                 ast_channel_dial_type(),
1534                 cel_dial_cb,
1535                 NULL);
1536
1537         ret |= stasis_message_router_add(cel_state_router,
1538                 ast_channel_entered_bridge_type(),
1539                 cel_bridge_enter_cb,
1540                 NULL);
1541
1542         ret |= stasis_message_router_add(cel_state_router,
1543                 ast_channel_left_bridge_type(),
1544                 cel_bridge_leave_cb,
1545                 NULL);
1546
1547         ret |= stasis_message_router_add(cel_state_router,
1548                 ast_parked_call_type(),
1549                 cel_parking_cb,
1550                 NULL);
1551
1552         ret |= stasis_message_router_add(cel_state_router,
1553                 cel_generic_type(),
1554                 cel_generic_cb,
1555                 NULL);
1556
1557         /* If somehow we failed to add any routes, just shut down the whole
1558          * thing and fail it.
1559          */
1560         if (ret) {
1561                 ast_cel_engine_term();
1562                 return -1;
1563         }
1564
1565         if (aco_info_init(&cel_cfg_info)) {
1566                 return -1;
1567         }
1568
1569         aco_option_register(&cel_cfg_info, "enable", ACO_EXACT, general_options, "no", OPT_BOOL_T, 1, FLDSET(struct ast_cel_general_config, enable));
1570         aco_option_register(&cel_cfg_info, "dateformat", ACO_EXACT, general_options, "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_cel_general_config, date_format));
1571         aco_option_register_custom(&cel_cfg_info, "apps", ACO_EXACT, general_options, "", apps_handler, 0);
1572         aco_option_register_custom(&cel_cfg_info, "events", ACO_EXACT, general_options, "", events_handler, 0);
1573
1574         aco_process_config(&cel_cfg_info, 0);
1575
1576         ast_register_cleanup(ast_cel_engine_term);
1577
1578         return 0;
1579 }
1580
1581 int ast_cel_engine_reload(void)
1582 {
1583         return do_reload();
1584 }
1585
1586 void ast_cel_publish_event(struct ast_channel *chan,
1587         enum ast_cel_event_type event_type,
1588         struct ast_json *blob)
1589 {
1590         RAII_VAR(struct ast_channel_blob *, obj, NULL, ao2_cleanup);
1591         RAII_VAR(struct ast_json *, cel_blob, NULL, ast_json_unref);
1592         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1593         cel_blob = ast_json_pack("{s: i, s: O}",
1594                 "event_type", event_type,
1595                 "event_details", blob);
1596
1597         message = ast_channel_blob_create(chan, cel_generic_type(), cel_blob);
1598         if (message) {
1599                 stasis_publish(ast_cel_topic(), message);
1600         }
1601 }
1602
1603 struct stasis_topic *ast_cel_topic(void)
1604 {
1605         return cel_topic;
1606 }
1607
1608 struct ast_cel_general_config *ast_cel_get_config(void)
1609 {
1610         RAII_VAR(struct cel_config *, mod_cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
1611         ao2_ref(mod_cfg->general, +1);
1612         return mod_cfg->general;
1613 }
1614
1615 void ast_cel_set_config(struct ast_cel_general_config *config)
1616 {
1617         RAII_VAR(struct cel_config *, mod_cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
1618         ao2_cleanup(mod_cfg->general);
1619         mod_cfg->general = config;
1620         ao2_ref(mod_cfg->general, +1);
1621 }
1622