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