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