core: Fix unused variable error in handle_show_sysinfo.
[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
26 /*! \li \ref cel.c uses the configuration file \ref cel.conf
27  * \addtogroup configuration_file Configuration Files
28  */
29
30 /*!
31  * \page cel.conf cel.conf
32  * \verbinclude cel.conf.sample
33  */
34
35 /*** MODULEINFO
36         <support_level>core</support_level>
37  ***/
38
39 #include "asterisk.h"
40
41 #include "asterisk/_private.h"
42
43 #include "asterisk/channel.h"
44 #include "asterisk/pbx.h"
45 #include "asterisk/cel.h"
46 #include "asterisk/logger.h"
47 #include "asterisk/linkedlists.h"
48 #include "asterisk/utils.h"
49 #include "asterisk/config.h"
50 #include "asterisk/config_options.h"
51 #include "asterisk/cli.h"
52 #include "asterisk/astobj2.h"
53 #include "asterisk/stasis_message_router.h"
54 #include "asterisk/stasis_channels.h"
55 #include "asterisk/stasis_bridges.h"
56 #include "asterisk/bridge.h"
57 #include "asterisk/parking.h"
58 #include "asterisk/pickup.h"
59 #include "asterisk/core_local.h"
60 #include "asterisk/taskprocessor.h"
61
62 /*** DOCUMENTATION
63         <configInfo name="cel" language="en_US">
64                 <configFile name="cel.conf">
65                         <configObject name="general">
66                                 <synopsis>Options that apply globally to Channel Event Logging (CEL)</synopsis>
67                                 <configOption name="enable">
68                                         <synopsis>Determines whether CEL is enabled</synopsis>
69                                 </configOption>
70                                 <configOption name="dateformat">
71                                         <synopsis>The format to be used for dates when logging</synopsis>
72                                 </configOption>
73                                 <configOption name="apps">
74                                         <synopsis>List of apps for CEL to track</synopsis>
75                                         <description><para>A case-insensitive, comma-separated list of applications
76                                         to track when one or both of APP_START and APP_END events are flagged for
77                                         tracking</para></description>
78                                 </configOption>
79                                 <configOption name="events">
80                                         <synopsis>List of events for CEL to track</synopsis>
81                                         <description><para>A case-sensitive, comma-separated list of event names
82                                         to track. These event names do not include the leading <literal>AST_CEL</literal>.
83                                         </para>
84                                         <enumlist>
85                                                 <enum name="ALL">
86                                                         <para>Special value which tracks all events.</para>
87                                                 </enum>
88                                                 <enum name="CHAN_START"/>
89                                                 <enum name="CHAN_END"/>
90                                                 <enum name="ANSWER"/>
91                                                 <enum name="HANGUP"/>
92                                                 <enum name="APP_START"/>
93                                                 <enum name="APP_END"/>
94                                                 <enum name="PARK_START"/>
95                                                 <enum name="PARK_END"/>
96                                                 <enum name="USER_DEFINED"/>
97                                                 <enum name="BRIDGE_ENTER"/>
98                                                 <enum name="BRIDGE_EXIT"/>
99                                                 <enum name="BLINDTRANSFER"/>
100                                                 <enum name="ATTENDEDTRANSFER"/>
101                                                 <enum name="PICKUP"/>
102                                                 <enum name="FORWARD"/>
103                                                 <enum name="LINKEDID_END"/>
104                                                 <enum name="LOCAL_OPTIMIZE"/>
105                                         </enumlist>
106                                         </description>
107                                 </configOption>
108                         </configObject>
109                 </configFile>
110         </configInfo>
111  ***/
112
113 /*! Message router for state that CEL needs to know about */
114 static struct stasis_message_router *cel_state_router;
115
116 /*! Topic for CEL-specific messages */
117 static struct stasis_topic *cel_topic;
118
119 /*! Aggregation topic for all topics CEL needs to know about */
120 static struct stasis_topic *cel_aggregation_topic;
121
122 /*! Subscription for forwarding the channel caching topic */
123 static struct stasis_forward *cel_channel_forwarder;
124
125 /*! Subscription for forwarding the channel caching topic */
126 static struct stasis_forward *cel_bridge_forwarder;
127
128 /*! Subscription for forwarding the parking topic */
129 static struct stasis_forward *cel_parking_forwarder;
130
131 /*! Subscription for forwarding the CEL-specific topic */
132 static struct stasis_forward *cel_cel_forwarder;
133
134 struct stasis_message_type *cel_generic_type(void);
135 STASIS_MESSAGE_TYPE_DEFN(cel_generic_type);
136
137 /*! Container for CEL backend information */
138 static AO2_GLOBAL_OBJ_STATIC(cel_backends);
139
140 /*! The number of buckets into which backend names will be hashed */
141 #define BACKEND_BUCKETS 13
142
143 /*! Container for dial end multichannel blobs for holding on to dial statuses */
144 static AO2_GLOBAL_OBJ_STATIC(cel_dialstatus_store);
145
146 /*!
147  * \brief Maximum possible CEL event IDs
148  * \note This limit is currently imposed by the eventset definition
149  */
150 #define CEL_MAX_EVENT_IDS 64
151
152 /*!
153  * \brief Number of buckets for the appset container
154  */
155 #define NUM_APP_BUCKETS         97
156
157 /*!
158  * \brief Number of buckets for the dialstatus container
159  */
160 #define NUM_DIALSTATUS_BUCKETS  251
161
162 struct cel_linkedid {
163         /*! Number of channels with this linkedid. */
164         unsigned int count;
165         /*! Linkedid stored at end of struct. */
166         char id[0];
167 };
168
169 /*! Container of channel references to a linkedid for CEL purposes. */
170 static AO2_GLOBAL_OBJ_STATIC(cel_linkedids);
171
172 struct cel_dialstatus {
173         /*! Uniqueid of the channel */
174         char uniqueid[AST_MAX_UNIQUEID];
175         /*! The dial status */
176         char dialstatus[0];
177 };
178
179 /*! \brief Destructor for cel_config */
180 static void cel_general_config_dtor(void *obj)
181 {
182         struct ast_cel_general_config *cfg = obj;
183         ast_string_field_free_memory(cfg);
184         ao2_cleanup(cfg->apps);
185         cfg->apps = NULL;
186 }
187
188 void *ast_cel_general_config_alloc(void)
189 {
190         RAII_VAR(struct ast_cel_general_config *, cfg, NULL, ao2_cleanup);
191
192         if (!(cfg = ao2_alloc(sizeof(*cfg), cel_general_config_dtor))) {
193                 return NULL;
194         }
195
196         if (ast_string_field_init(cfg, 64)) {
197                 return NULL;
198         }
199
200         if (!(cfg->apps = ast_str_container_alloc(NUM_APP_BUCKETS))) {
201                 return NULL;
202         }
203
204         ao2_ref(cfg, +1);
205         return cfg;
206 }
207
208 /*! \brief A container that holds all config-related information */
209 struct cel_config {
210         struct ast_cel_general_config *general;
211 };
212
213
214 static AO2_GLOBAL_OBJ_STATIC(cel_configs);
215
216 /*! \brief Destructor for cel_config */
217 static void cel_config_dtor(void *obj)
218 {
219         struct cel_config *cfg = obj;
220         ao2_cleanup(cfg->general);
221         cfg->general = NULL;
222 }
223
224 static void *cel_config_alloc(void)
225 {
226         RAII_VAR(struct cel_config *, cfg, NULL, ao2_cleanup);
227
228         if (!(cfg = ao2_alloc(sizeof(*cfg), cel_config_dtor))) {
229                 return NULL;
230         }
231
232         if (!(cfg->general = ast_cel_general_config_alloc())) {
233                 return NULL;
234         }
235
236         ao2_ref(cfg, +1);
237         return cfg;
238 }
239
240 /*! \brief An aco_type structure to link the "general" category to the ast_cel_general_config type */
241 static struct aco_type general_option = {
242         .type = ACO_GLOBAL,
243         .name = "general",
244         .item_offset = offsetof(struct cel_config, general),
245         .category_match = ACO_WHITELIST_EXACT,
246         .category = "general",
247 };
248
249 /*! Config sections used by existing modules. Do not add to this list. */
250 static const char *ignore_categories[] = {
251         "manager",
252         "radius",
253         NULL,
254 };
255
256 static struct aco_type ignore_option = {
257         .type = ACO_IGNORE,
258         .name = "modules",
259         .category = (const char*)ignore_categories,
260         .category_match = ACO_WHITELIST_ARRAY,
261 };
262
263 /*! \brief The config file to be processed for the module. */
264 static struct aco_file cel_conf = {
265         .filename = "cel.conf",                  /*!< The name of the config file */
266         .types = ACO_TYPES(&general_option, &ignore_option),     /*!< The mapping object types to be processed */
267 };
268
269 static int cel_pre_apply_config(void);
270
271 CONFIG_INFO_CORE("cel", cel_cfg_info, cel_configs, cel_config_alloc,
272         .files = ACO_FILES(&cel_conf),
273         .pre_apply_config = cel_pre_apply_config,
274 );
275
276 static int cel_pre_apply_config(void)
277 {
278         struct cel_config *cfg = aco_pending_config(&cel_cfg_info);
279
280         if (!cfg->general) {
281                 return -1;
282         }
283
284         if (!ao2_container_count(cfg->general->apps)) {
285                 return 0;
286         }
287
288         if (cfg->general->events & ((int64_t) 1 << AST_CEL_APP_START)) {
289                 return 0;
290         }
291
292         if (cfg->general->events & ((int64_t) 1 << AST_CEL_APP_END)) {
293                 return 0;
294         }
295
296         ast_log(LOG_ERROR, "Applications are listed to be tracked, but APP events are not tracked\n");
297         return -1;
298 }
299
300 static struct aco_type *general_options[] = ACO_TYPES(&general_option);
301
302 /*!
303  * \brief Map of ast_cel_event_type to strings
304  */
305 static const char * const cel_event_types[CEL_MAX_EVENT_IDS] = {
306         [AST_CEL_ALL]              = "ALL",
307         [AST_CEL_CHANNEL_START]    = "CHAN_START",
308         [AST_CEL_CHANNEL_END]      = "CHAN_END",
309         [AST_CEL_ANSWER]           = "ANSWER",
310         [AST_CEL_HANGUP]           = "HANGUP",
311         [AST_CEL_APP_START]        = "APP_START",
312         [AST_CEL_APP_END]          = "APP_END",
313         [AST_CEL_PARK_START]       = "PARK_START",
314         [AST_CEL_PARK_END]         = "PARK_END",
315         [AST_CEL_USER_DEFINED]     = "USER_DEFINED",
316         [AST_CEL_BRIDGE_ENTER]     = "BRIDGE_ENTER",
317         [AST_CEL_BRIDGE_EXIT]      = "BRIDGE_EXIT",
318         [AST_CEL_BLINDTRANSFER]    = "BLINDTRANSFER",
319         [AST_CEL_ATTENDEDTRANSFER] = "ATTENDEDTRANSFER",
320         [AST_CEL_PICKUP]           = "PICKUP",
321         [AST_CEL_FORWARD]          = "FORWARD",
322         [AST_CEL_LINKEDID_END]     = "LINKEDID_END",
323         [AST_CEL_LOCAL_OPTIMIZE]   = "LOCAL_OPTIMIZE",
324 };
325
326 struct cel_backend {
327         ast_cel_backend_cb callback; /*!< Callback for this backend */
328         char name[0];                /*!< Name of this backend */
329 };
330
331 /*! \brief Hashing function for cel_backend */
332 static int cel_backend_hash(const void *obj, int flags)
333 {
334         const struct cel_backend *backend;
335         const char *name;
336
337         switch (flags & OBJ_SEARCH_MASK) {
338         case OBJ_SEARCH_OBJECT:
339                 backend = obj;
340                 name = backend->name;
341                 break;
342         case OBJ_SEARCH_KEY:
343                 name = obj;
344                 break;
345         default:
346                 /* Hash can only work on something with a full key. */
347                 ast_assert(0);
348                 return 0;
349         }
350
351         return ast_str_hash(name);
352 }
353
354 /*! \brief Comparator function for cel_backend */
355 static int cel_backend_cmp(void *obj, void *arg, int flags)
356 {
357         const struct cel_backend *object_left = obj;
358         const struct cel_backend *object_right = arg;
359         const char *right_key = arg;
360         int cmp;
361
362         switch (flags & OBJ_SEARCH_MASK) {
363         case OBJ_SEARCH_OBJECT:
364                 right_key = object_right->name;
365                 /* Fall through */
366         case OBJ_SEARCH_KEY:
367                 cmp = strcmp(object_left->name, right_key);
368                 break;
369         case OBJ_SEARCH_PARTIAL_KEY:
370                 /*
371                  * We could also use a partial key struct containing a length
372                  * so strlen() does not get called for every comparison instead.
373                  */
374                 cmp = strncmp(object_left->name, right_key, strlen(right_key));
375                 break;
376         default:
377                 /*
378                  * What arg points to is specific to this traversal callback
379                  * and has no special meaning to astobj2.
380                  */
381                 cmp = 0;
382                 break;
383         }
384         if (cmp) {
385                 return 0;
386         }
387         /*
388          * At this point the traversal callback is identical to a sorted
389          * container.
390          */
391         return CMP_MATCH;
392 }
393
394 /*! \brief Hashing function for dialstatus container */
395 static int dialstatus_hash(const void *obj, int flags)
396 {
397         const struct cel_dialstatus *dialstatus;
398         const char *key;
399
400         switch (flags & OBJ_SEARCH_MASK) {
401         case OBJ_SEARCH_KEY:
402                 key = obj;
403                 break;
404         case OBJ_SEARCH_OBJECT:
405                 dialstatus = obj;
406                 key = dialstatus->uniqueid;
407                 break;
408         default:
409                 /* Hash can only work on something with a full key. */
410                 ast_assert(0);
411                 return 0;
412         }
413         return ast_str_hash(key);
414 }
415
416 /*! \brief Comparator function for dialstatus container */
417 static int dialstatus_cmp(void *obj, void *arg, int flags)
418 {
419         struct cel_dialstatus *object_left = obj;
420         struct cel_dialstatus *object_right = arg;
421         const char *right_key = arg;
422         int cmp;
423
424         switch (flags & OBJ_SEARCH_MASK) {
425         case OBJ_SEARCH_OBJECT:
426                 right_key = object_right->uniqueid;
427                 /* Fall through */
428         case OBJ_SEARCH_KEY:
429                 cmp = strcmp(object_left->uniqueid, right_key);
430                 break;
431         case OBJ_SEARCH_PARTIAL_KEY:
432                 /*
433                  * We could also use a partial key struct containing a length
434                  * so strlen() does not get called for every comparison instead.
435                  */
436                 cmp = strncmp(object_left->uniqueid, right_key, strlen(right_key));
437                 break;
438         default:
439                 /*
440                  * What arg points to is specific to this traversal callback
441                  * and has no special meaning to astobj2.
442                  */
443                 cmp = 0;
444                 break;
445         }
446         if (cmp) {
447                 return 0;
448         }
449         /*
450          * At this point the traversal callback is identical to a sorted
451          * container.
452          */
453         return CMP_MATCH;
454 }
455
456 unsigned int ast_cel_check_enabled(void)
457 {
458         unsigned int enabled;
459         struct cel_config *cfg = ao2_global_obj_ref(cel_configs);
460
461         enabled = (!cfg || !cfg->general) ? 0 : cfg->general->enable;
462         ao2_cleanup(cfg);
463         return enabled;
464 }
465
466 static char *handle_cli_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
467 {
468         unsigned int i;
469         RAII_VAR(struct cel_config *, cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
470         RAII_VAR(struct ao2_container *, backends, ao2_global_obj_ref(cel_backends), ao2_cleanup);
471         struct ao2_iterator iter;
472         char *app;
473
474         switch (cmd) {
475         case CLI_INIT:
476                 e->command = "cel show status";
477                 e->usage =
478                         "Usage: cel show status\n"
479                         "       Displays the Channel Event Logging system status.\n";
480                 return NULL;
481         case CLI_GENERATE:
482                 return NULL;
483         case CLI_HANDLER:
484                 break;
485         }
486
487         if (a->argc > 3) {
488                 return CLI_SHOWUSAGE;
489         }
490
491         ast_cli(a->fd, "CEL Logging: %s\n", ast_cel_check_enabled() ? "Enabled" : "Disabled");
492
493         if (!cfg || !cfg->general || !cfg->general->enable) {
494                 return CLI_SUCCESS;
495         }
496
497         for (i = 0; i < (sizeof(cfg->general->events) * 8); i++) {
498                 const char *name;
499
500                 if (!(cfg->general->events & ((int64_t) 1 << i))) {
501                         continue;
502                 }
503
504                 name = ast_cel_get_type_name(i);
505                 if (strcasecmp(name, "Unknown")) {
506                         ast_cli(a->fd, "CEL Tracking Event: %s\n", name);
507                 }
508         }
509
510         iter = ao2_iterator_init(cfg->general->apps, 0);
511         for (; (app = ao2_iterator_next(&iter)); ao2_ref(app, -1)) {
512                 ast_cli(a->fd, "CEL Tracking Application: %s\n", app);
513         }
514         ao2_iterator_destroy(&iter);
515
516         if (backends) {
517                 struct cel_backend *backend;
518
519                 iter = ao2_iterator_init(backends, 0);
520                 for (; (backend = ao2_iterator_next(&iter)); ao2_ref(backend, -1)) {
521                         ast_cli(a->fd, "CEL Event Subscriber: %s\n", backend->name);
522                 }
523                 ao2_iterator_destroy(&iter);
524         }
525
526         return CLI_SUCCESS;
527 }
528
529 static struct ast_cli_entry cli_status = AST_CLI_DEFINE(handle_cli_status, "Display the CEL status");
530
531 enum ast_cel_event_type ast_cel_str_to_event_type(const char *name)
532 {
533         unsigned int i;
534
535         for (i = 0; i < ARRAY_LEN(cel_event_types); i++) {
536                 if (cel_event_types[i] && !strcasecmp(name, cel_event_types[i])) {
537                         return i;
538                 }
539         }
540
541         ast_log(LOG_ERROR, "Unknown event name '%s'\n", name);
542         return AST_CEL_INVALID_VALUE;
543 }
544
545 static int ast_cel_track_event(enum ast_cel_event_type et)
546 {
547         RAII_VAR(struct cel_config *, cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
548
549         if (!cfg || !cfg->general) {
550                 return 0;
551         }
552
553         return (cfg->general->events & ((int64_t) 1 << et)) ? 1 : 0;
554 }
555
556 static int events_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
557 {
558         struct ast_cel_general_config *cfg = obj;
559         char *events = ast_strdupa(var->value);
560         char *cur_event;
561
562         while ((cur_event = strsep(&events, ","))) {
563                 enum ast_cel_event_type event_type;
564
565                 cur_event = ast_strip(cur_event);
566                 if (ast_strlen_zero(cur_event)) {
567                         continue;
568                 }
569
570                 event_type = ast_cel_str_to_event_type(cur_event);
571
572                 if (event_type == AST_CEL_ALL) {
573                         /* All events */
574                         cfg->events = (int64_t) -1;
575                 } else if (event_type == AST_CEL_INVALID_VALUE) {
576                         return -1;
577                 } else {
578                         cfg->events |= ((int64_t) 1 << event_type);
579                 }
580         }
581
582         return 0;
583 }
584
585 static int apps_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
586 {
587         struct ast_cel_general_config *cfg = obj;
588         char *apps = ast_strdupa(var->value);
589         char *cur_app;
590
591         while ((cur_app = strsep(&apps, ","))) {
592                 cur_app = ast_strip(cur_app);
593                 if (ast_strlen_zero(cur_app)) {
594                         continue;
595                 }
596
597                 cur_app = ast_str_to_lower(cur_app);
598                 ast_str_container_add(cfg->apps, cur_app);
599         }
600
601         return 0;
602 }
603
604 const char *ast_cel_get_type_name(enum ast_cel_event_type type)
605 {
606         return S_OR(cel_event_types[type], "Unknown");
607 }
608
609 static int cel_track_app(const char *const_app)
610 {
611         RAII_VAR(struct cel_config *, cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
612         RAII_VAR(char *, app, NULL, ao2_cleanup);
613         char *app_lower;
614
615         if (!cfg || !cfg->general) {
616                 return 0;
617         }
618
619         app_lower = ast_str_to_lower(ast_strdupa(const_app));
620         app = ao2_find(cfg->general->apps, app_lower, OBJ_SEARCH_KEY);
621         if (!app) {
622                 return 0;
623         }
624
625         return 1;
626 }
627
628 static int cel_linkedid_ref(const char *linkedid);
629
630 struct ast_event *ast_cel_create_event(struct ast_channel_snapshot *snapshot,
631                 enum ast_cel_event_type event_type, const char *userdefevname,
632                 struct ast_json *extra, const char *peer)
633 {
634         struct timeval eventtime = ast_tvnow();
635         RAII_VAR(char *, extra_txt, NULL, ast_json_free);
636         if (extra) {
637                 extra_txt = ast_json_dump_string(extra);
638         }
639         return ast_event_new(AST_EVENT_CEL,
640                 AST_EVENT_IE_CEL_EVENT_TYPE, AST_EVENT_IE_PLTYPE_UINT, event_type,
641                 AST_EVENT_IE_CEL_EVENT_TIME, AST_EVENT_IE_PLTYPE_UINT, eventtime.tv_sec,
642                 AST_EVENT_IE_CEL_EVENT_TIME_USEC, AST_EVENT_IE_PLTYPE_UINT, eventtime.tv_usec,
643                 AST_EVENT_IE_CEL_USEREVENT_NAME, AST_EVENT_IE_PLTYPE_STR, S_OR(userdefevname, ""),
644                 AST_EVENT_IE_CEL_CIDNAME, AST_EVENT_IE_PLTYPE_STR, snapshot->caller_name,
645                 AST_EVENT_IE_CEL_CIDNUM, AST_EVENT_IE_PLTYPE_STR, snapshot->caller_number,
646                 AST_EVENT_IE_CEL_CIDANI, AST_EVENT_IE_PLTYPE_STR, snapshot->caller_ani,
647                 AST_EVENT_IE_CEL_CIDRDNIS, AST_EVENT_IE_PLTYPE_STR, snapshot->caller_rdnis,
648                 AST_EVENT_IE_CEL_CIDDNID, AST_EVENT_IE_PLTYPE_STR, snapshot->caller_dnid,
649                 AST_EVENT_IE_CEL_EXTEN, AST_EVENT_IE_PLTYPE_STR, snapshot->exten,
650                 AST_EVENT_IE_CEL_CONTEXT, AST_EVENT_IE_PLTYPE_STR, snapshot->context,
651                 AST_EVENT_IE_CEL_CHANNAME, AST_EVENT_IE_PLTYPE_STR, snapshot->name,
652                 AST_EVENT_IE_CEL_APPNAME, AST_EVENT_IE_PLTYPE_STR, snapshot->appl,
653                 AST_EVENT_IE_CEL_APPDATA, AST_EVENT_IE_PLTYPE_STR, snapshot->data,
654                 AST_EVENT_IE_CEL_AMAFLAGS, AST_EVENT_IE_PLTYPE_UINT, snapshot->amaflags,
655                 AST_EVENT_IE_CEL_ACCTCODE, AST_EVENT_IE_PLTYPE_STR, snapshot->accountcode,
656                 AST_EVENT_IE_CEL_PEERACCT, AST_EVENT_IE_PLTYPE_STR, snapshot->peeraccount,
657                 AST_EVENT_IE_CEL_UNIQUEID, AST_EVENT_IE_PLTYPE_STR, snapshot->uniqueid,
658                 AST_EVENT_IE_CEL_LINKEDID, AST_EVENT_IE_PLTYPE_STR, snapshot->linkedid,
659                 AST_EVENT_IE_CEL_USERFIELD, AST_EVENT_IE_PLTYPE_STR, snapshot->userfield,
660                 AST_EVENT_IE_CEL_EXTRA, AST_EVENT_IE_PLTYPE_STR, S_OR(extra_txt, ""),
661                 AST_EVENT_IE_CEL_PEER, AST_EVENT_IE_PLTYPE_STR, S_OR(peer, ""),
662                 AST_EVENT_IE_END);
663 }
664
665 static int cel_backend_send_cb(void *obj, void *arg, int flags)
666 {
667         struct cel_backend *backend = obj;
668
669         backend->callback(arg);
670         return 0;
671 }
672
673 static int cel_report_event(struct ast_channel_snapshot *snapshot,
674                 enum ast_cel_event_type event_type, const char *userdefevname,
675                 struct ast_json *extra, const char *peer_str)
676 {
677         struct ast_event *ev;
678         RAII_VAR(struct cel_config *, cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
679         RAII_VAR(struct ao2_container *, backends, ao2_global_obj_ref(cel_backends), ao2_cleanup);
680
681         if (!cfg || !cfg->general || !cfg->general->enable || !backends) {
682                 return 0;
683         }
684
685         /* Record the linkedid of new channels if we are tracking LINKEDID_END even if we aren't
686          * reporting on CHANNEL_START so we can track when to send LINKEDID_END */
687         if (event_type == AST_CEL_CHANNEL_START
688                 && ast_cel_track_event(AST_CEL_LINKEDID_END)) {
689                 if (cel_linkedid_ref(snapshot->linkedid)) {
690                         return -1;
691                 }
692         }
693
694         if (!ast_cel_track_event(event_type)) {
695                 return 0;
696         }
697
698         if ((event_type == AST_CEL_APP_START || event_type == AST_CEL_APP_END)
699                 && !cel_track_app(snapshot->appl)) {
700                 return 0;
701         }
702
703         ev = ast_cel_create_event(snapshot, event_type, userdefevname, extra, peer_str);
704         if (!ev) {
705                 return -1;
706         }
707
708         /* Distribute event to backends */
709         ao2_callback(backends, OBJ_MULTIPLE | OBJ_NODATA, cel_backend_send_cb, ev);
710         ast_event_destroy(ev);
711
712         return 0;
713 }
714
715 /* called whenever a channel is destroyed or a linkedid is changed to
716  * potentially emit a CEL_LINKEDID_END event */
717 static void check_retire_linkedid(struct ast_channel_snapshot *snapshot)
718 {
719         RAII_VAR(struct ao2_container *, linkedids, ao2_global_obj_ref(cel_linkedids), ao2_cleanup);
720         struct cel_linkedid *lid;
721
722         if (!linkedids || ast_strlen_zero(snapshot->linkedid)) {
723                 /* The CEL module is shutdown.  Abort. */
724                 return;
725         }
726
727         ao2_lock(linkedids);
728
729         lid = ao2_find(linkedids, (void *) snapshot->linkedid, OBJ_SEARCH_KEY);
730         if (!lid) {
731                 ao2_unlock(linkedids);
732
733                 /*
734                  * The user may have done a reload to start tracking linkedids
735                  * when a call was already in progress.  This is an unusual kind
736                  * of change to make after starting Asterisk.
737                  */
738                 ast_log(LOG_ERROR, "Something weird happened, couldn't find linkedid %s\n",
739                         snapshot->linkedid);
740                 return;
741         }
742
743         if (!--lid->count) {
744                 /* No channels use this linkedid anymore. */
745                 ao2_unlink(linkedids, lid);
746                 ao2_unlock(linkedids);
747
748                 cel_report_event(snapshot, AST_CEL_LINKEDID_END, NULL, NULL, NULL);
749         } else {
750                 ao2_unlock(linkedids);
751         }
752         ao2_ref(lid, -1);
753 }
754
755 /* Note that no 'chan_fixup' function is provided for this datastore type,
756  * because the channels that will use it will never be involved in masquerades.
757  */
758 static const struct ast_datastore_info fabricated_channel_datastore = {
759         .type = "CEL fabricated channel",
760         .destroy = ast_free_ptr,
761 };
762
763 struct ast_channel *ast_cel_fabricate_channel_from_event(const struct ast_event *event)
764 {
765         struct varshead *headp;
766         struct ast_var_t *newvariable;
767         const char *mixed_name;
768         char timebuf[30];
769         struct ast_channel *tchan;
770         struct ast_cel_event_record record = {
771                 .version = AST_CEL_EVENT_RECORD_VERSION,
772         };
773         struct ast_datastore *datastore;
774         char *app_data;
775         RAII_VAR(struct cel_config *, cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
776
777         if (!cfg || !cfg->general) {
778                 return NULL;
779         }
780
781         /* do not call ast_channel_alloc because this is not really a real channel */
782         if (!(tchan = ast_dummy_channel_alloc())) {
783                 return NULL;
784         }
785
786         headp = ast_channel_varshead(tchan);
787
788         /* first, get the variables from the event */
789         if (ast_cel_fill_record(event, &record)) {
790                 ast_channel_unref(tchan);
791                 return NULL;
792         }
793
794         /* next, fill the channel with their data */
795         mixed_name = (record.event_type == AST_CEL_USER_DEFINED)
796                 ? record.user_defined_name : record.event_name;
797         if ((newvariable = ast_var_assign("eventtype", mixed_name))) {
798                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
799         }
800
801         if (ast_strlen_zero(cfg->general->date_format)) {
802                 snprintf(timebuf, sizeof(timebuf), "%ld.%06ld", (long) record.event_time.tv_sec,
803                                 (long) record.event_time.tv_usec);
804         } else {
805                 struct ast_tm tm;
806                 ast_localtime(&record.event_time, &tm, NULL);
807                 ast_strftime(timebuf, sizeof(timebuf), cfg->general->date_format, &tm);
808         }
809
810         if ((newvariable = ast_var_assign("eventtime", timebuf))) {
811                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
812         }
813
814         if ((newvariable = ast_var_assign("eventenum", record.event_name))) {
815                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
816         }
817         if ((newvariable = ast_var_assign("userdeftype", record.user_defined_name))) {
818                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
819         }
820         if ((newvariable = ast_var_assign("eventextra", record.extra))) {
821                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
822         }
823
824         ast_channel_caller(tchan)->id.name.valid = 1;
825         ast_channel_caller(tchan)->id.name.str = ast_strdup(record.caller_id_name);
826         ast_channel_caller(tchan)->id.number.valid = 1;
827         ast_channel_caller(tchan)->id.number.str = ast_strdup(record.caller_id_num);
828         ast_channel_caller(tchan)->ani.number.valid = 1;
829         ast_channel_caller(tchan)->ani.number.str = ast_strdup(record.caller_id_ani);
830         ast_channel_redirecting(tchan)->from.number.valid = 1;
831         ast_channel_redirecting(tchan)->from.number.str = ast_strdup(record.caller_id_rdnis);
832         ast_channel_dialed(tchan)->number.str = ast_strdup(record.caller_id_dnid);
833
834         ast_channel_exten_set(tchan, record.extension);
835         ast_channel_context_set(tchan, record.context);
836         ast_channel_name_set(tchan, record.channel_name);
837         ast_channel_internal_set_fake_ids(tchan, record.unique_id, record.linked_id);
838         ast_channel_accountcode_set(tchan, record.account_code);
839         ast_channel_peeraccount_set(tchan, record.peer_account);
840         ast_channel_userfield_set(tchan, record.user_field);
841
842         if ((newvariable = ast_var_assign("BRIDGEPEER", record.peer))) {
843                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
844         }
845
846         ast_channel_amaflags_set(tchan, record.amaflag);
847
848         /* We need to store an 'application name' and 'application
849          * data' on the channel for logging purposes, but the channel
850          * structure only provides a place to store pointers, and it
851          * expects these pointers to be pointing to data that does not
852          * need to be freed. This means that the channel's destructor
853          * does not attempt to free any storage that these pointers
854          * point to. However, we can't provide data in that form directly for
855          * these structure members. In order to ensure that these data
856          * elements have a lifetime that matches the channel's
857          * lifetime, we'll put them in a datastore attached to the
858          * channel, and set's the channel's pointers to point into the
859          * datastore.  The datastore will then be automatically destroyed
860          * when the channel is destroyed.
861          */
862
863         if (!(datastore = ast_datastore_alloc(&fabricated_channel_datastore, NULL))) {
864                 ast_channel_unref(tchan);
865                 return NULL;
866         }
867
868         if (!(app_data = ast_malloc(strlen(record.application_name) + strlen(record.application_data) + 2))) {
869                 ast_datastore_free(datastore);
870                 ast_channel_unref(tchan);
871                 return NULL;
872         }
873
874         ast_channel_appl_set(tchan, strcpy(app_data, record.application_name));
875         ast_channel_data_set(tchan, strcpy(app_data + strlen(record.application_name) + 1,
876                 record.application_data));
877
878         datastore->data = app_data;
879         ast_channel_datastore_add(tchan, datastore);
880
881         return tchan;
882 }
883
884 static int cel_linkedid_ref(const char *linkedid)
885 {
886         RAII_VAR(struct ao2_container *, linkedids, ao2_global_obj_ref(cel_linkedids), ao2_cleanup);
887         struct cel_linkedid *lid;
888
889         if (ast_strlen_zero(linkedid)) {
890                 ast_log(LOG_ERROR, "The linkedid should never be empty\n");
891                 return -1;
892         }
893         if (!linkedids) {
894                 /* The CEL module is shutdown.  Abort. */
895                 return -1;
896         }
897
898         ao2_lock(linkedids);
899         lid = ao2_find(linkedids, (void *) linkedid, OBJ_SEARCH_KEY);
900         if (!lid) {
901                 /*
902                  * Changes to the lid->count member are protected by the
903                  * container lock so the lid object does not need its own lock.
904                  */
905                 lid = ao2_alloc_options(sizeof(*lid) + strlen(linkedid) + 1, NULL,
906                         AO2_ALLOC_OPT_LOCK_NOLOCK);
907                 if (!lid) {
908                         ao2_unlock(linkedids);
909                         return -1;
910                 }
911                 strcpy(lid->id, linkedid);/* Safe */
912
913                 ao2_link(linkedids, lid);
914         }
915         ++lid->count;
916         ao2_unlock(linkedids);
917         ao2_ref(lid, -1);
918
919         return 0;
920 }
921
922 int ast_cel_fill_record(const struct ast_event *e, struct ast_cel_event_record *r)
923 {
924         if (r->version != AST_CEL_EVENT_RECORD_VERSION) {
925                 ast_log(LOG_ERROR, "Module ABI mismatch for ast_cel_event_record.  "
926                                 "Please ensure all modules were compiled for "
927                                 "this version of Asterisk.\n");
928                 return -1;
929         }
930
931         r->event_type = ast_event_get_ie_uint(e, AST_EVENT_IE_CEL_EVENT_TYPE);
932
933         r->event_time.tv_sec = ast_event_get_ie_uint(e, AST_EVENT_IE_CEL_EVENT_TIME);
934         r->event_time.tv_usec = ast_event_get_ie_uint(e, AST_EVENT_IE_CEL_EVENT_TIME_USEC);
935
936         r->event_name = ast_cel_get_type_name(r->event_type);
937         if (r->event_type == AST_CEL_USER_DEFINED) {
938                 r->user_defined_name = ast_event_get_ie_str(e, AST_EVENT_IE_CEL_USEREVENT_NAME);
939         } else {
940                 r->user_defined_name = "";
941         }
942
943         r->caller_id_name   = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CIDNAME), "");
944         r->caller_id_num    = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CIDNUM), "");
945         r->caller_id_ani    = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CIDANI), "");
946         r->caller_id_rdnis  = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CIDRDNIS), "");
947         r->caller_id_dnid   = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CIDDNID), "");
948         r->extension        = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_EXTEN), "");
949         r->context          = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CONTEXT), "");
950         r->channel_name     = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CHANNAME), "");
951         r->application_name = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_APPNAME), "");
952         r->application_data = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_APPDATA), "");
953         r->account_code     = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_ACCTCODE), "");
954         r->peer_account     = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_PEERACCT), "");
955         r->unique_id        = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_UNIQUEID), "");
956         r->linked_id        = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_LINKEDID), "");
957         r->amaflag          = ast_event_get_ie_uint(e, AST_EVENT_IE_CEL_AMAFLAGS);
958         r->user_field       = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_USERFIELD), "");
959         r->peer             = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_PEER), "");
960         r->extra            = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_EXTRA), "");
961
962         return 0;
963 }
964
965 /*! \brief Typedef for callbacks that get called on channel snapshot updates */
966 typedef void (*cel_channel_snapshot_monitor)(
967         struct ast_channel_snapshot *old_snapshot,
968         struct ast_channel_snapshot *new_snapshot);
969
970 static struct cel_dialstatus *get_dialstatus(const char *uniqueid)
971 {
972         struct ao2_container *dial_statuses = ao2_global_obj_ref(cel_dialstatus_store);
973         struct cel_dialstatus *dialstatus = NULL;
974
975         if (dial_statuses) {
976                 dialstatus = ao2_find(dial_statuses, uniqueid, OBJ_SEARCH_KEY | OBJ_UNLINK);
977                 ao2_ref(dial_statuses, -1);
978         }
979         return dialstatus;
980 }
981
982 static const char *get_blob_variable(struct ast_multi_channel_blob *blob, const char *varname)
983 {
984         struct ast_json *json = ast_multi_channel_blob_get_json(blob);
985         if (!json) {
986                 return NULL;
987         }
988
989         json = ast_json_object_get(json, varname);
990         if (!json) {
991                 return NULL;
992         }
993
994         return ast_json_string_get(json);
995 }
996
997 /*! \brief Handle channel state changes */
998 static void cel_channel_state_change(
999         struct ast_channel_snapshot *old_snapshot,
1000         struct ast_channel_snapshot *new_snapshot)
1001 {
1002         int is_hungup, was_hungup;
1003
1004         if (!new_snapshot) {
1005                 cel_report_event(old_snapshot, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
1006                 if (ast_cel_track_event(AST_CEL_LINKEDID_END)) {
1007                         check_retire_linkedid(old_snapshot);
1008                 }
1009                 return;
1010         }
1011
1012         if (!old_snapshot) {
1013                 cel_report_event(new_snapshot, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
1014                 return;
1015         }
1016
1017         was_hungup = ast_test_flag(&old_snapshot->flags, AST_FLAG_DEAD) ? 1 : 0;
1018         is_hungup = ast_test_flag(&new_snapshot->flags, AST_FLAG_DEAD) ? 1 : 0;
1019
1020         if (!was_hungup && is_hungup) {
1021                 struct ast_json *extra;
1022                 struct cel_dialstatus *dialstatus = get_dialstatus(new_snapshot->uniqueid);
1023
1024                 extra = ast_json_pack("{s: i, s: s, s: s}",
1025                         "hangupcause", new_snapshot->hangupcause,
1026                         "hangupsource", new_snapshot->hangupsource,
1027                         "dialstatus", dialstatus ? dialstatus->dialstatus : "");
1028                 cel_report_event(new_snapshot, AST_CEL_HANGUP, NULL, extra, NULL);
1029                 ast_json_unref(extra);
1030                 ao2_cleanup(dialstatus);
1031                 return;
1032         }
1033
1034         if (old_snapshot->state != new_snapshot->state && new_snapshot->state == AST_STATE_UP) {
1035                 cel_report_event(new_snapshot, AST_CEL_ANSWER, NULL, NULL, NULL);
1036                 return;
1037         }
1038 }
1039
1040 static void cel_channel_linkedid_change(
1041         struct ast_channel_snapshot *old_snapshot,
1042         struct ast_channel_snapshot *new_snapshot)
1043 {
1044         if (!old_snapshot || !new_snapshot) {
1045                 return;
1046         }
1047
1048         ast_assert(!ast_strlen_zero(new_snapshot->linkedid));
1049         ast_assert(!ast_strlen_zero(old_snapshot->linkedid));
1050
1051         if (ast_cel_track_event(AST_CEL_LINKEDID_END)
1052                 && strcmp(old_snapshot->linkedid, new_snapshot->linkedid)) {
1053                 cel_linkedid_ref(new_snapshot->linkedid);
1054                 check_retire_linkedid(old_snapshot);
1055         }
1056 }
1057
1058 static void cel_channel_app_change(
1059         struct ast_channel_snapshot *old_snapshot,
1060         struct ast_channel_snapshot *new_snapshot)
1061 {
1062         if (new_snapshot && old_snapshot
1063                 && !strcmp(old_snapshot->appl, new_snapshot->appl)) {
1064                 return;
1065         }
1066
1067         /* old snapshot has an application, end it */
1068         if (old_snapshot && !ast_strlen_zero(old_snapshot->appl)) {
1069                 cel_report_event(old_snapshot, AST_CEL_APP_END, NULL, NULL, NULL);
1070         }
1071
1072         /* new snapshot has an application, start it */
1073         if (new_snapshot && !ast_strlen_zero(new_snapshot->appl)) {
1074                 cel_report_event(new_snapshot, AST_CEL_APP_START, NULL, NULL, NULL);
1075         }
1076 }
1077
1078 /* \brief Handlers for channel snapshot changes.
1079  * \note Order of the handlers matters. Application changes must come before state
1080  * changes to ensure that hangup notifications occur after application changes.
1081  * Linkedid checking should always come last.
1082  */
1083 cel_channel_snapshot_monitor cel_channel_monitors[] = {
1084         cel_channel_app_change,
1085         cel_channel_state_change,
1086         cel_channel_linkedid_change,
1087 };
1088
1089 static int cel_filter_channel_snapshot(struct ast_channel_snapshot *snapshot)
1090 {
1091         if (!snapshot) {
1092                 return 0;
1093         }
1094         return snapshot->tech_properties & AST_CHAN_TP_INTERNAL;
1095 }
1096
1097 static void cel_snapshot_update_cb(void *data, struct stasis_subscription *sub,
1098         struct stasis_message *message)
1099 {
1100         struct stasis_cache_update *update = stasis_message_data(message);
1101         if (ast_channel_snapshot_type() == update->type) {
1102                 struct ast_channel_snapshot *old_snapshot;
1103                 struct ast_channel_snapshot *new_snapshot;
1104                 size_t i;
1105
1106                 old_snapshot = stasis_message_data(update->old_snapshot);
1107                 new_snapshot = stasis_message_data(update->new_snapshot);
1108
1109                 if (cel_filter_channel_snapshot(old_snapshot) || cel_filter_channel_snapshot(new_snapshot)) {
1110                         return;
1111                 }
1112
1113                 for (i = 0; i < ARRAY_LEN(cel_channel_monitors); ++i) {
1114                         cel_channel_monitors[i](old_snapshot, new_snapshot);
1115                 }
1116         }
1117 }
1118
1119 static struct ast_str *cel_generate_peer_str(
1120         struct ast_bridge_snapshot *bridge,
1121         struct ast_channel_snapshot *chan)
1122 {
1123         struct ast_str *peer_str = ast_str_create(32);
1124         struct ao2_iterator i;
1125         char *current_chan = NULL;
1126
1127         if (!peer_str) {
1128                 return NULL;
1129         }
1130
1131         for (i = ao2_iterator_init(bridge->channels, 0);
1132                 (current_chan = ao2_iterator_next(&i));
1133                 ao2_cleanup(current_chan)) {
1134                 struct ast_channel_snapshot *current_snapshot;
1135
1136                 /* Don't add the channel for which this message is being generated */
1137                 if (!strcmp(current_chan, chan->uniqueid)) {
1138                         continue;
1139                 }
1140
1141                 current_snapshot = ast_channel_snapshot_get_latest(current_chan);
1142                 if (!current_snapshot) {
1143                         continue;
1144                 }
1145
1146                 ast_str_append(&peer_str, 0, "%s,", current_snapshot->name);
1147                 ao2_cleanup(current_snapshot);
1148         }
1149         ao2_iterator_destroy(&i);
1150
1151         /* Rip off the trailing comma */
1152         ast_str_truncate(peer_str, -1);
1153
1154         return peer_str;
1155 }
1156
1157 static void cel_bridge_enter_cb(
1158         void *data, struct stasis_subscription *sub,
1159         struct stasis_message *message)
1160 {
1161         struct ast_bridge_blob *blob = stasis_message_data(message);
1162         struct ast_bridge_snapshot *snapshot = blob->bridge;
1163         struct ast_channel_snapshot *chan_snapshot = blob->channel;
1164         RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1165         RAII_VAR(struct ast_str *, peer_str, NULL, ast_free);
1166
1167         if (cel_filter_channel_snapshot(chan_snapshot)) {
1168                 return;
1169         }
1170
1171         extra = ast_json_pack("{s: s, s: s}",
1172                 "bridge_id", snapshot->uniqueid,
1173                 "bridge_technology", snapshot->technology);
1174         if (!extra) {
1175                 return;
1176         }
1177
1178         peer_str = cel_generate_peer_str(snapshot, chan_snapshot);
1179         if (!peer_str) {
1180                 return;
1181         }
1182
1183         cel_report_event(chan_snapshot, AST_CEL_BRIDGE_ENTER, NULL, extra, ast_str_buffer(peer_str));
1184 }
1185
1186 static void cel_bridge_leave_cb(
1187         void *data, struct stasis_subscription *sub,
1188         struct stasis_message *message)
1189 {
1190         struct ast_bridge_blob *blob = stasis_message_data(message);
1191         struct ast_bridge_snapshot *snapshot = blob->bridge;
1192         struct ast_channel_snapshot *chan_snapshot = blob->channel;
1193         RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1194         RAII_VAR(struct ast_str *, peer_str, NULL, ast_free);
1195
1196         if (cel_filter_channel_snapshot(chan_snapshot)) {
1197                 return;
1198         }
1199
1200         extra = ast_json_pack("{s: s, s: s}",
1201                 "bridge_id", snapshot->uniqueid,
1202                 "bridge_technology", snapshot->technology);
1203         if (!extra) {
1204                 return;
1205         }
1206
1207         peer_str = cel_generate_peer_str(snapshot, chan_snapshot);
1208         if (!peer_str) {
1209                 return;
1210         }
1211
1212         cel_report_event(chan_snapshot, AST_CEL_BRIDGE_EXIT, NULL, extra, ast_str_buffer(peer_str));
1213 }
1214
1215 static void cel_parking_cb(
1216         void *data, struct stasis_subscription *sub,
1217         struct stasis_message *message)
1218 {
1219         struct ast_parked_call_payload *parked_payload = stasis_message_data(message);
1220         RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1221         const char *reason = NULL;
1222
1223         switch (parked_payload->event_type) {
1224         case PARKED_CALL:
1225                 extra = ast_json_pack("{s: s, s: s}",
1226                         "parker_dial_string", parked_payload->parker_dial_string,
1227                         "parking_lot", parked_payload->parkinglot);
1228                 if (extra) {
1229                         cel_report_event(parked_payload->parkee, AST_CEL_PARK_START, NULL, extra, NULL);
1230                 }
1231                 return;
1232         case PARKED_CALL_TIMEOUT:
1233                 reason = "ParkedCallTimeOut";
1234                 break;
1235         case PARKED_CALL_GIVEUP:
1236                 reason = "ParkedCallGiveUp";
1237                 break;
1238         case PARKED_CALL_UNPARKED:
1239                 reason = "ParkedCallUnparked";
1240                 break;
1241         case PARKED_CALL_FAILED:
1242                 reason = "ParkedCallFailed";
1243                 break;
1244         case PARKED_CALL_SWAP:
1245                 reason = "ParkedCallSwap";
1246                 break;
1247         }
1248
1249         if (parked_payload->retriever) {
1250                 extra = ast_json_pack("{s: s, s: s}",
1251                         "reason", reason ?: "",
1252                         "retriever", parked_payload->retriever->name);
1253         } else {
1254                 extra = ast_json_pack("{s: s}", "reason", reason ?: "");
1255         }
1256
1257         if (extra) {
1258                 cel_report_event(parked_payload->parkee, AST_CEL_PARK_END, NULL, extra, NULL);
1259         }
1260 }
1261
1262 static void save_dialstatus(struct ast_multi_channel_blob *blob, struct ast_channel_snapshot *snapshot)
1263 {
1264         struct ao2_container *dial_statuses = ao2_global_obj_ref(cel_dialstatus_store);
1265         const char *dialstatus_string = get_blob_variable(blob, "dialstatus");
1266         struct cel_dialstatus *dialstatus;
1267         size_t dialstatus_string_len;
1268
1269         if (!dial_statuses || ast_strlen_zero(dialstatus_string)) {
1270                 ao2_cleanup(dial_statuses);
1271                 return;
1272         }
1273
1274         dialstatus = ao2_find(dial_statuses, snapshot->uniqueid, OBJ_SEARCH_KEY);
1275         if (dialstatus) {
1276                 if (!strcasecmp(dialstatus_string, "ANSWER") && strcasecmp(dialstatus->dialstatus, "ANSWER")) {
1277                         /* In the case of an answer after we already have a dial status we give
1278                          * priority to the answer since the call was, well, answered. In the case of
1279                          * failure dial status results we simply let the first failure be the status.
1280                          */
1281                         ao2_unlink(dial_statuses, dialstatus);
1282                         ao2_ref(dialstatus, -1);
1283                 } else {
1284                         ao2_ref(dialstatus, -1);
1285                         ao2_ref(dial_statuses, -1);
1286                         return;
1287                 }
1288         }
1289
1290         dialstatus_string_len = strlen(dialstatus_string) + 1;
1291         dialstatus = ao2_alloc_options(sizeof(*dialstatus) + dialstatus_string_len, NULL,
1292                 AO2_ALLOC_OPT_LOCK_NOLOCK);
1293         if (!dialstatus) {
1294                 ao2_ref(dial_statuses, -1);
1295                 return;
1296         }
1297
1298         ast_copy_string(dialstatus->uniqueid, snapshot->uniqueid, sizeof(dialstatus->uniqueid));
1299         ast_copy_string(dialstatus->dialstatus, dialstatus_string, dialstatus_string_len);
1300
1301         ao2_link(dial_statuses, dialstatus);
1302         ao2_ref(dialstatus, -1);
1303         ao2_ref(dial_statuses, -1);
1304 }
1305
1306 static int is_valid_dialstatus(struct ast_multi_channel_blob *blob)
1307 {
1308         const char *dialstatus = get_blob_variable(blob, "dialstatus");
1309         int res = 0;
1310
1311         if (ast_strlen_zero(dialstatus)) {
1312                 res = 0;
1313         } else if (!strcasecmp(dialstatus, "CHANUNAVAIL")) {
1314                 res = 1;
1315         } else if (!strcasecmp(dialstatus, "CONGESTION")) {
1316                 res = 1;
1317         } else if (!strcasecmp(dialstatus, "NOANSWER")) {
1318                 res = 1;
1319         } else if (!strcasecmp(dialstatus, "BUSY")) {
1320                 res = 1;
1321         } else if (!strcasecmp(dialstatus, "ANSWER")) {
1322                 res = 1;
1323         } else if (!strcasecmp(dialstatus, "CANCEL")) {
1324                 res = 1;
1325         } else if (!strcasecmp(dialstatus, "DONTCALL")) {
1326                 res = 1;
1327         } else if (!strcasecmp(dialstatus, "TORTURE")) {
1328                 res = 1;
1329         } else if (!strcasecmp(dialstatus, "INVALIDARGS")) {
1330                 res = 1;
1331         }
1332         return res;
1333 }
1334
1335 static void cel_dial_cb(void *data, struct stasis_subscription *sub,
1336         struct stasis_message *message)
1337 {
1338         struct ast_multi_channel_blob *blob = stasis_message_data(message);
1339         struct ast_channel_snapshot *snapshot;
1340
1341         snapshot = ast_multi_channel_blob_get_channel(blob, "caller");
1342         if (!snapshot || cel_filter_channel_snapshot(snapshot)) {
1343                 return;
1344         }
1345
1346         if (!ast_strlen_zero(get_blob_variable(blob, "forward"))) {
1347                 struct ast_json *extra;
1348
1349                 extra = ast_json_pack("{s: s}", "forward", get_blob_variable(blob, "forward"));
1350                 if (extra) {
1351                         cel_report_event(snapshot, AST_CEL_FORWARD, NULL, extra, NULL);
1352                         ast_json_unref(extra);
1353                 }
1354         }
1355
1356         if (is_valid_dialstatus(blob)) {
1357                 save_dialstatus(blob, snapshot);
1358         }
1359 }
1360
1361 static void cel_generic_cb(
1362         void *data, struct stasis_subscription *sub,
1363         struct stasis_message *message)
1364 {
1365         struct ast_channel_blob *obj = stasis_message_data(message);
1366         int event_type = ast_json_integer_get(ast_json_object_get(obj->blob, "event_type"));
1367         struct ast_json *event_details = ast_json_object_get(obj->blob, "event_details");
1368
1369         switch (event_type) {
1370         case AST_CEL_USER_DEFINED:
1371                 {
1372                         const char *event = ast_json_string_get(ast_json_object_get(event_details, "event"));
1373                         struct ast_json *extra = ast_json_object_get(event_details, "extra");
1374                         cel_report_event(obj->snapshot, event_type, event, extra, NULL);
1375                         break;
1376                 }
1377         default:
1378                 ast_log(LOG_ERROR, "Unhandled %s event blob\n", ast_cel_get_type_name(event_type));
1379                 break;
1380         }
1381 }
1382
1383 static void cel_blind_transfer_cb(
1384         void *data, struct stasis_subscription *sub,
1385         struct stasis_message *message)
1386 {
1387         struct ast_blind_transfer_message *transfer_msg = stasis_message_data(message);
1388         struct ast_channel_snapshot *chan_snapshot = transfer_msg->transferer;
1389         struct ast_bridge_snapshot *bridge_snapshot = transfer_msg->bridge;
1390         struct ast_json *extra;
1391
1392         if (transfer_msg->result != AST_BRIDGE_TRANSFER_SUCCESS) {
1393                 return;
1394         }
1395
1396         extra = ast_json_pack("{s: s, s: s, s: s, s: s, s: s}",
1397                 "extension", transfer_msg->exten,
1398                 "context", transfer_msg->context,
1399                 "bridge_id", bridge_snapshot->uniqueid,
1400                 "transferee_channel_name", transfer_msg->transferee ? transfer_msg->transferee->name : "N/A",
1401                 "transferee_channel_uniqueid", transfer_msg->transferee ? transfer_msg->transferee->uniqueid  : "N/A");
1402         if (extra) {
1403                 cel_report_event(chan_snapshot, AST_CEL_BLINDTRANSFER, NULL, extra, NULL);
1404                 ast_json_unref(extra);
1405         }
1406 }
1407
1408 static void cel_attended_transfer_cb(
1409         void *data, struct stasis_subscription *sub,
1410         struct stasis_message *message)
1411 {
1412         struct ast_attended_transfer_message *xfer = stasis_message_data(message);
1413         struct ast_json *extra = NULL;
1414         struct ast_bridge_snapshot *bridge1, *bridge2;
1415         struct ast_channel_snapshot *channel1, *channel2;
1416
1417         /* Make sure bridge1 is always non-NULL */
1418         if (!xfer->to_transferee.bridge_snapshot) {
1419                 bridge1 = xfer->to_transfer_target.bridge_snapshot;
1420                 bridge2 = xfer->to_transferee.bridge_snapshot;
1421                 channel1 = xfer->to_transfer_target.channel_snapshot;
1422                 channel2 = xfer->to_transferee.channel_snapshot;
1423         } else {
1424                 bridge1 = xfer->to_transferee.bridge_snapshot;
1425                 bridge2 = xfer->to_transfer_target.bridge_snapshot;
1426                 channel1 = xfer->to_transferee.channel_snapshot;
1427                 channel2 = xfer->to_transfer_target.channel_snapshot;
1428         }
1429
1430         switch (xfer->dest_type) {
1431         case AST_ATTENDED_TRANSFER_DEST_FAIL:
1432                 return;
1433                 /* handle these three the same */
1434         case AST_ATTENDED_TRANSFER_DEST_BRIDGE_MERGE:
1435         case AST_ATTENDED_TRANSFER_DEST_LINK:
1436         case AST_ATTENDED_TRANSFER_DEST_THREEWAY:
1437                 extra = ast_json_pack("{s: s, s: s, s: s, s: s, s: s, s: s, s: s, s: s}",
1438                         "bridge1_id", bridge1->uniqueid,
1439                         "channel2_name", channel2->name,
1440                         "channel2_uniqueid", channel2->uniqueid,
1441                         "bridge2_id", bridge2->uniqueid,
1442                         "transferee_channel_name", xfer->transferee ? xfer->transferee->name : "N/A",
1443                         "transferee_channel_uniqueid", xfer->transferee ? xfer->transferee->uniqueid : "N/A",
1444                         "transfer_target_channel_name", xfer->target ? xfer->target->name : "N/A",
1445                         "transfer_target_channel_uniqueid", xfer->target ? xfer->target->uniqueid : "N/A");
1446                 if (!extra) {
1447                         return;
1448                 }
1449                 break;
1450         case AST_ATTENDED_TRANSFER_DEST_APP:
1451         case AST_ATTENDED_TRANSFER_DEST_LOCAL_APP:
1452                 extra = ast_json_pack("{s: s, s: s, s: s, s: s, s: s, s: s, s: s, s: s}",
1453                         "bridge1_id", bridge1->uniqueid,
1454                         "channel2_name", channel2->name,
1455                         "channel2_uniqueid", channel2->uniqueid,
1456                         "app", xfer->dest.app,
1457                         "transferee_channel_name", xfer->transferee ? xfer->transferee->name : "N/A",
1458                         "transferee_channel_uniqueid", xfer->transferee ? xfer->transferee->uniqueid : "N/A",
1459                         "transfer_target_channel_name", xfer->target ? xfer->target->name : "N/A",
1460                         "transfer_target_channel_uniqueid", xfer->target ? xfer->target->uniqueid : "N/A");
1461                 if (!extra) {
1462                         return;
1463                 }
1464                 break;
1465         }
1466         cel_report_event(channel1, AST_CEL_ATTENDEDTRANSFER, NULL, extra, NULL);
1467         ast_json_unref(extra);
1468 }
1469
1470 static void cel_pickup_cb(
1471         void *data, struct stasis_subscription *sub,
1472         struct stasis_message *message)
1473 {
1474         struct ast_multi_channel_blob *obj = stasis_message_data(message);
1475         struct ast_channel_snapshot *channel = ast_multi_channel_blob_get_channel(obj, "channel");
1476         struct ast_channel_snapshot *target = ast_multi_channel_blob_get_channel(obj, "target");
1477         struct ast_json *extra;
1478
1479         if (!channel || !target) {
1480                 return;
1481         }
1482
1483         extra = ast_json_pack("{s: s, s: s}",
1484                 "pickup_channel", channel->name,
1485                 "pickup_channel_uniqueid", channel->uniqueid);
1486         if (!extra) {
1487                 return;
1488         }
1489
1490         cel_report_event(target, AST_CEL_PICKUP, NULL, extra, NULL);
1491         ast_json_unref(extra);
1492 }
1493
1494 static void cel_local_cb(
1495         void *data, struct stasis_subscription *sub,
1496         struct stasis_message *message)
1497 {
1498         struct ast_multi_channel_blob *obj = stasis_message_data(message);
1499         struct ast_channel_snapshot *localone = ast_multi_channel_blob_get_channel(obj, "1");
1500         struct ast_channel_snapshot *localtwo = ast_multi_channel_blob_get_channel(obj, "2");
1501         struct ast_json *extra;
1502
1503         if (!localone || !localtwo) {
1504                 return;
1505         }
1506
1507         extra = ast_json_pack("{s: s, s: s}",
1508                 "local_two", localtwo->name,
1509                 "local_two_uniqueid", localtwo->uniqueid);
1510         if (!extra) {
1511                 return;
1512         }
1513
1514         cel_report_event(localone, AST_CEL_LOCAL_OPTIMIZE, NULL, extra, NULL);
1515         ast_json_unref(extra);
1516 }
1517
1518 static void destroy_routes(void)
1519 {
1520         stasis_message_router_unsubscribe_and_join(cel_state_router);
1521         cel_state_router = NULL;
1522 }
1523
1524 static void destroy_subscriptions(void)
1525 {
1526         ao2_cleanup(cel_aggregation_topic);
1527         cel_aggregation_topic = NULL;
1528         ao2_cleanup(cel_topic);
1529         cel_topic = NULL;
1530
1531         cel_channel_forwarder = stasis_forward_cancel(cel_channel_forwarder);
1532         cel_bridge_forwarder = stasis_forward_cancel(cel_bridge_forwarder);
1533         cel_parking_forwarder = stasis_forward_cancel(cel_parking_forwarder);
1534         cel_cel_forwarder = stasis_forward_cancel(cel_cel_forwarder);
1535 }
1536
1537 static void cel_engine_cleanup(void)
1538 {
1539         destroy_routes();
1540         destroy_subscriptions();
1541         STASIS_MESSAGE_TYPE_CLEANUP(cel_generic_type);
1542
1543         ast_cli_unregister(&cli_status);
1544         aco_info_destroy(&cel_cfg_info);
1545         ao2_global_obj_release(cel_configs);
1546         ao2_global_obj_release(cel_dialstatus_store);
1547         ao2_global_obj_release(cel_linkedids);
1548         ao2_global_obj_release(cel_backends);
1549 }
1550
1551 /*!
1552  * \brief Create the Stasis subscriptions for CEL
1553  */
1554 static int create_subscriptions(void)
1555 {
1556         cel_aggregation_topic = stasis_topic_create("cel_aggregation_topic");
1557         if (!cel_aggregation_topic) {
1558                 return -1;
1559         }
1560
1561         cel_topic = stasis_topic_create("cel_topic");
1562         if (!cel_topic) {
1563                 return -1;
1564         }
1565
1566         cel_channel_forwarder = stasis_forward_all(
1567                 ast_channel_topic_all_cached(),
1568                 cel_aggregation_topic);
1569         if (!cel_channel_forwarder) {
1570                 return -1;
1571         }
1572
1573         cel_bridge_forwarder = stasis_forward_all(
1574                 ast_bridge_topic_all_cached(),
1575                 cel_aggregation_topic);
1576         if (!cel_bridge_forwarder) {
1577                 return -1;
1578         }
1579
1580         cel_parking_forwarder = stasis_forward_all(
1581                 ast_parking_topic(),
1582                 cel_aggregation_topic);
1583         if (!cel_parking_forwarder) {
1584                 return -1;
1585         }
1586
1587         cel_cel_forwarder = stasis_forward_all(
1588                 ast_cel_topic(),
1589                 cel_aggregation_topic);
1590         if (!cel_cel_forwarder) {
1591                 return -1;
1592         }
1593
1594         return 0;
1595 }
1596
1597 /*!
1598  * \brief Create the Stasis message router and routes for CEL
1599  */
1600 static int create_routes(void)
1601 {
1602         int ret = 0;
1603
1604         cel_state_router = stasis_message_router_create(cel_aggregation_topic);
1605         if (!cel_state_router) {
1606                 return -1;
1607         }
1608         stasis_message_router_set_congestion_limits(cel_state_router, -1,
1609                 6 * AST_TASKPROCESSOR_HIGH_WATER_LEVEL);
1610
1611         ret |= stasis_message_router_add(cel_state_router,
1612                 stasis_cache_update_type(),
1613                 cel_snapshot_update_cb,
1614                 NULL);
1615
1616         ret |= stasis_message_router_add(cel_state_router,
1617                 ast_channel_dial_type(),
1618                 cel_dial_cb,
1619                 NULL);
1620
1621         ret |= stasis_message_router_add(cel_state_router,
1622                 ast_channel_entered_bridge_type(),
1623                 cel_bridge_enter_cb,
1624                 NULL);
1625
1626         ret |= stasis_message_router_add(cel_state_router,
1627                 ast_channel_left_bridge_type(),
1628                 cel_bridge_leave_cb,
1629                 NULL);
1630
1631         ret |= stasis_message_router_add(cel_state_router,
1632                 ast_parked_call_type(),
1633                 cel_parking_cb,
1634                 NULL);
1635
1636         ret |= stasis_message_router_add(cel_state_router,
1637                 cel_generic_type(),
1638                 cel_generic_cb,
1639                 NULL);
1640
1641         ret |= stasis_message_router_add(cel_state_router,
1642                 ast_blind_transfer_type(),
1643                 cel_blind_transfer_cb,
1644                 NULL);
1645
1646         ret |= stasis_message_router_add(cel_state_router,
1647                 ast_attended_transfer_type(),
1648                 cel_attended_transfer_cb,
1649                 NULL);
1650
1651         ret |= stasis_message_router_add(cel_state_router,
1652                 ast_call_pickup_type(),
1653                 cel_pickup_cb,
1654                 NULL);
1655
1656         ret |= stasis_message_router_add(cel_state_router,
1657                 ast_local_optimization_end_type(),
1658                 cel_local_cb,
1659                 NULL);
1660
1661         if (ret) {
1662                 ast_log(AST_LOG_ERROR, "Failed to register for Stasis messages\n");
1663         }
1664
1665         return ret;
1666 }
1667
1668 static int lid_hash(const void *obj, const int flags)
1669 {
1670         const struct cel_linkedid *lid;
1671         const char *key;
1672
1673         switch (flags & OBJ_SEARCH_MASK) {
1674         case OBJ_SEARCH_KEY:
1675                 key = obj;
1676                 break;
1677         case OBJ_SEARCH_OBJECT:
1678                 lid = obj;
1679                 key = lid->id;
1680                 break;
1681         default:
1682                 /* Hash can only work on something with a full key. */
1683                 ast_assert(0);
1684                 return 0;
1685         }
1686         return ast_str_hash(key);
1687 }
1688
1689 static int lid_cmp(void *obj, void *arg, int flags)
1690 {
1691         const struct cel_linkedid *object_left = obj;
1692         const struct cel_linkedid *object_right = arg;
1693         const char *right_key = arg;
1694         int cmp;
1695
1696         switch (flags & OBJ_SEARCH_MASK) {
1697         case OBJ_SEARCH_OBJECT:
1698                 right_key = object_right->id;
1699                 /* Fall through */
1700         case OBJ_SEARCH_KEY:
1701                 cmp = strcmp(object_left->id, right_key);
1702                 break;
1703         case OBJ_SEARCH_PARTIAL_KEY:
1704                 /*
1705                  * We could also use a partial key struct containing a length
1706                  * so strlen() does not get called for every comparison instead.
1707                  */
1708                 cmp = strncmp(object_left->id, right_key, strlen(right_key));
1709                 break;
1710         default:
1711                 /*
1712                  * What arg points to is specific to this traversal callback
1713                  * and has no special meaning to astobj2.
1714                  */
1715                 cmp = 0;
1716                 break;
1717         }
1718         if (cmp) {
1719                 return 0;
1720         }
1721         /*
1722          * At this point the traversal callback is identical to a sorted
1723          * container.
1724          */
1725         return CMP_MATCH;
1726 }
1727
1728 int ast_cel_engine_init(void)
1729 {
1730         struct ao2_container *container;
1731
1732         container = ao2_container_alloc(NUM_APP_BUCKETS, lid_hash, lid_cmp);
1733         ao2_global_obj_replace_unref(cel_linkedids, container);
1734         ao2_cleanup(container);
1735         if (!container) {
1736                 cel_engine_cleanup();
1737                 return -1;
1738         }
1739
1740         container = ao2_container_alloc(NUM_DIALSTATUS_BUCKETS,
1741                 dialstatus_hash, dialstatus_cmp);
1742         ao2_global_obj_replace_unref(cel_dialstatus_store, container);
1743         ao2_cleanup(container);
1744         if (!container) {
1745                 cel_engine_cleanup();
1746                 return -1;
1747         }
1748
1749         if (STASIS_MESSAGE_TYPE_INIT(cel_generic_type)) {
1750                 cel_engine_cleanup();
1751                 return -1;
1752         }
1753
1754         if (ast_cli_register(&cli_status)) {
1755                 cel_engine_cleanup();
1756                 return -1;
1757         }
1758
1759         container = ao2_container_alloc(BACKEND_BUCKETS, cel_backend_hash, cel_backend_cmp);
1760         ao2_global_obj_replace_unref(cel_backends, container);
1761         ao2_cleanup(container);
1762         if (!container) {
1763                 cel_engine_cleanup();
1764                 return -1;
1765         }
1766
1767         if (aco_info_init(&cel_cfg_info)) {
1768                 cel_engine_cleanup();
1769                 return -1;
1770         }
1771
1772         aco_option_register(&cel_cfg_info, "enable", ACO_EXACT, general_options, "no", OPT_BOOL_T, 1, FLDSET(struct ast_cel_general_config, enable));
1773         aco_option_register(&cel_cfg_info, "dateformat", ACO_EXACT, general_options, "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_cel_general_config, date_format));
1774         aco_option_register_custom(&cel_cfg_info, "apps", ACO_EXACT, general_options, "", apps_handler, 0);
1775         aco_option_register_custom(&cel_cfg_info, "events", ACO_EXACT, general_options, "", events_handler, 0);
1776
1777         if (aco_process_config(&cel_cfg_info, 0)) {
1778                 struct cel_config *cel_cfg = cel_config_alloc();
1779
1780                 if (!cel_cfg) {
1781                         cel_engine_cleanup();
1782                         return -1;
1783                 }
1784
1785                 /* We couldn't process the configuration so create a default config. */
1786                 if (!aco_set_defaults(&general_option, "general", cel_cfg->general)) {
1787                         ast_log(LOG_NOTICE, "Failed to process CEL configuration; using defaults\n");
1788                         ao2_global_obj_replace_unref(cel_configs, cel_cfg);
1789                 }
1790                 ao2_ref(cel_cfg, -1);
1791         }
1792
1793         if (create_subscriptions()) {
1794                 cel_engine_cleanup();
1795                 return -1;
1796         }
1797
1798         if (ast_cel_check_enabled() && create_routes()) {
1799                 cel_engine_cleanup();
1800                 return -1;
1801         }
1802
1803         ast_register_cleanup(cel_engine_cleanup);
1804         return 0;
1805 }
1806
1807 int ast_cel_engine_reload(void)
1808 {
1809         unsigned int was_enabled = ast_cel_check_enabled();
1810         unsigned int is_enabled;
1811
1812         if (aco_process_config(&cel_cfg_info, 1) == ACO_PROCESS_ERROR) {
1813                 return -1;
1814         }
1815
1816         is_enabled = ast_cel_check_enabled();
1817
1818         if (!was_enabled && is_enabled) {
1819                 if (create_routes()) {
1820                         return -1;
1821                 }
1822         } else if (was_enabled && !is_enabled) {
1823                 destroy_routes();
1824         }
1825
1826         ast_verb(3, "CEL logging %sabled.\n", is_enabled ? "en" : "dis");
1827
1828         return 0;
1829 }
1830
1831 void ast_cel_publish_event(struct ast_channel *chan,
1832         enum ast_cel_event_type event_type,
1833         struct ast_json *blob)
1834 {
1835         struct ast_json *cel_blob;
1836         struct stasis_message *message;
1837
1838         cel_blob = ast_json_pack("{s: i, s: o}",
1839                 "event_type", event_type,
1840                 "event_details", ast_json_ref(blob));
1841
1842         message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan), cel_generic_type(), cel_blob);
1843         if (message) {
1844                 stasis_publish(ast_cel_topic(), message);
1845         }
1846         ao2_cleanup(message);
1847         ast_json_unref(cel_blob);
1848 }
1849
1850 struct stasis_topic *ast_cel_topic(void)
1851 {
1852         return cel_topic;
1853 }
1854
1855 struct ast_cel_general_config *ast_cel_get_config(void)
1856 {
1857         RAII_VAR(struct cel_config *, mod_cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
1858
1859         if (!mod_cfg || !mod_cfg->general) {
1860                 return NULL;
1861         }
1862
1863         ao2_ref(mod_cfg->general, +1);
1864         return mod_cfg->general;
1865 }
1866
1867 void ast_cel_set_config(struct ast_cel_general_config *config)
1868 {
1869         int was_enabled;
1870         int is_enabled;
1871         struct ast_cel_general_config *cleanup_config;
1872         struct cel_config *mod_cfg = ao2_global_obj_ref(cel_configs);
1873
1874         if (mod_cfg) {
1875                 was_enabled = ast_cel_check_enabled();
1876
1877                 cleanup_config = mod_cfg->general;
1878                 ao2_bump(config);
1879                 mod_cfg->general = config;
1880                 ao2_cleanup(cleanup_config);
1881
1882                 is_enabled = ast_cel_check_enabled();
1883                 if (!was_enabled && is_enabled) {
1884                         create_routes();
1885                 } else if (was_enabled && !is_enabled) {
1886                         destroy_routes();
1887                 }
1888
1889                 ao2_ref(mod_cfg, -1);
1890         }
1891 }
1892
1893 int ast_cel_backend_unregister(const char *name)
1894 {
1895         struct ao2_container *backends = ao2_global_obj_ref(cel_backends);
1896
1897         if (backends) {
1898                 ao2_find(backends, name, OBJ_SEARCH_KEY | OBJ_NODATA | OBJ_UNLINK);
1899                 ao2_ref(backends, -1);
1900         }
1901
1902         return 0;
1903 }
1904
1905 int ast_cel_backend_register(const char *name, ast_cel_backend_cb backend_callback)
1906 {
1907         RAII_VAR(struct ao2_container *, backends, ao2_global_obj_ref(cel_backends), ao2_cleanup);
1908         struct cel_backend *backend;
1909
1910         if (!backends || ast_strlen_zero(name) || !backend_callback) {
1911                 return -1;
1912         }
1913
1914         /* The backend object is immutable so it doesn't need a lock of its own. */
1915         backend = ao2_alloc_options(sizeof(*backend) + 1 + strlen(name), NULL,
1916                 AO2_ALLOC_OPT_LOCK_NOLOCK);
1917         if (!backend) {
1918                 return -1;
1919         }
1920         strcpy(backend->name, name);/* Safe */
1921         backend->callback = backend_callback;
1922
1923         ao2_link(backends, backend);
1924         ao2_ref(backend, -1);
1925         return 0;
1926 }