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