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