bb0f75051960180ab21782b5c40aab3f51c0ae47
[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}",
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         if (extra) {
1376                 cel_report_event(chan_snapshot, AST_CEL_BLINDTRANSFER, NULL, extra, NULL);
1377                 ast_json_unref(extra);
1378         }
1379 }
1380
1381 static void cel_attended_transfer_cb(
1382         void *data, struct stasis_subscription *sub,
1383         struct stasis_message *message)
1384 {
1385         struct ast_attended_transfer_message *xfer = stasis_message_data(message);
1386         struct ast_json *extra = NULL;
1387         struct ast_bridge_snapshot *bridge1, *bridge2;
1388         struct ast_channel_snapshot *channel1, *channel2;
1389
1390         /* Make sure bridge1 is always non-NULL */
1391         if (!xfer->to_transferee.bridge_snapshot) {
1392                 bridge1 = xfer->to_transfer_target.bridge_snapshot;
1393                 bridge2 = xfer->to_transferee.bridge_snapshot;
1394                 channel1 = xfer->to_transfer_target.channel_snapshot;
1395                 channel2 = xfer->to_transferee.channel_snapshot;
1396         } else {
1397                 bridge1 = xfer->to_transferee.bridge_snapshot;
1398                 bridge2 = xfer->to_transfer_target.bridge_snapshot;
1399                 channel1 = xfer->to_transferee.channel_snapshot;
1400                 channel2 = xfer->to_transfer_target.channel_snapshot;
1401         }
1402
1403         switch (xfer->dest_type) {
1404         case AST_ATTENDED_TRANSFER_DEST_FAIL:
1405                 return;
1406                 /* handle these three the same */
1407         case AST_ATTENDED_TRANSFER_DEST_BRIDGE_MERGE:
1408         case AST_ATTENDED_TRANSFER_DEST_LINK:
1409         case AST_ATTENDED_TRANSFER_DEST_THREEWAY:
1410                 extra = ast_json_pack("{s: s, s: s, s: s, s: s, s: s}",
1411                         "bridge1_id", bridge1->uniqueid,
1412                         "channel2_name", channel2->name,
1413                         "bridge2_id", bridge2->uniqueid,
1414                         "transferee_channel_name", xfer->transferee ? xfer->transferee->name : "N/A",
1415                         "transfer_target_channel_name", xfer->target ? xfer->target->name : "N/A");
1416                 if (!extra) {
1417                         return;
1418                 }
1419                 break;
1420         case AST_ATTENDED_TRANSFER_DEST_APP:
1421         case AST_ATTENDED_TRANSFER_DEST_LOCAL_APP:
1422                 extra = ast_json_pack("{s: s, s: s, s: s, s: s, s: s}",
1423                         "bridge1_id", bridge1->uniqueid,
1424                         "channel2_name", channel2->name,
1425                         "app", xfer->dest.app,
1426                         "transferee_channel_name", xfer->transferee ? xfer->transferee->name : "N/A",
1427                         "transfer_target_channel_name", xfer->target ? xfer->target->name : "N/A");
1428                 if (!extra) {
1429                         return;
1430                 }
1431                 break;
1432         }
1433         cel_report_event(channel1, AST_CEL_ATTENDEDTRANSFER, NULL, extra, NULL);
1434         ast_json_unref(extra);
1435 }
1436
1437 static void cel_pickup_cb(
1438         void *data, struct stasis_subscription *sub,
1439         struct stasis_message *message)
1440 {
1441         struct ast_multi_channel_blob *obj = stasis_message_data(message);
1442         struct ast_channel_snapshot *channel = ast_multi_channel_blob_get_channel(obj, "channel");
1443         struct ast_channel_snapshot *target = ast_multi_channel_blob_get_channel(obj, "target");
1444         struct ast_json *extra;
1445
1446         if (!channel || !target) {
1447                 return;
1448         }
1449
1450         extra = ast_json_pack("{s: s}", "pickup_channel", channel->name);
1451         if (!extra) {
1452                 return;
1453         }
1454
1455         cel_report_event(target, AST_CEL_PICKUP, NULL, extra, NULL);
1456         ast_json_unref(extra);
1457 }
1458
1459 static void cel_local_cb(
1460         void *data, struct stasis_subscription *sub,
1461         struct stasis_message *message)
1462 {
1463         struct ast_multi_channel_blob *obj = stasis_message_data(message);
1464         struct ast_channel_snapshot *localone = ast_multi_channel_blob_get_channel(obj, "1");
1465         struct ast_channel_snapshot *localtwo = ast_multi_channel_blob_get_channel(obj, "2");
1466         struct ast_json *extra;
1467
1468         if (!localone || !localtwo) {
1469                 return;
1470         }
1471
1472         extra = ast_json_pack("{s: s}", "local_two", localtwo->name);
1473         if (!extra) {
1474                 return;
1475         }
1476
1477         cel_report_event(localone, AST_CEL_LOCAL_OPTIMIZE, NULL, extra, NULL);
1478         ast_json_unref(extra);
1479 }
1480
1481 static void destroy_routes(void)
1482 {
1483         stasis_message_router_unsubscribe_and_join(cel_state_router);
1484         cel_state_router = NULL;
1485 }
1486
1487 static void destroy_subscriptions(void)
1488 {
1489         ao2_cleanup(cel_aggregation_topic);
1490         cel_aggregation_topic = NULL;
1491         ao2_cleanup(cel_topic);
1492         cel_topic = NULL;
1493
1494         cel_channel_forwarder = stasis_forward_cancel(cel_channel_forwarder);
1495         cel_bridge_forwarder = stasis_forward_cancel(cel_bridge_forwarder);
1496         cel_parking_forwarder = stasis_forward_cancel(cel_parking_forwarder);
1497         cel_cel_forwarder = stasis_forward_cancel(cel_cel_forwarder);
1498 }
1499
1500 static void cel_engine_cleanup(void)
1501 {
1502         destroy_routes();
1503         destroy_subscriptions();
1504         STASIS_MESSAGE_TYPE_CLEANUP(cel_generic_type);
1505 }
1506
1507 static void cel_engine_atexit(void)
1508 {
1509         ast_cli_unregister(&cli_status);
1510         aco_info_destroy(&cel_cfg_info);
1511         ao2_global_obj_release(cel_configs);
1512         ao2_global_obj_release(cel_dialstatus_store);
1513         ao2_global_obj_release(cel_linkedids);
1514         ao2_global_obj_release(cel_backends);
1515 }
1516
1517 static void cel_engine_abort(void)
1518 {
1519         cel_engine_cleanup();
1520         cel_engine_atexit();
1521 }
1522
1523 /*!
1524  * \brief Create the Stasis subscriptions for CEL
1525  */
1526 static int create_subscriptions(void)
1527 {
1528         cel_aggregation_topic = stasis_topic_create("cel_aggregation_topic");
1529         if (!cel_aggregation_topic) {
1530                 return -1;
1531         }
1532
1533         cel_topic = stasis_topic_create("cel_topic");
1534         if (!cel_topic) {
1535                 return -1;
1536         }
1537
1538         cel_channel_forwarder = stasis_forward_all(
1539                 ast_channel_topic_all_cached(),
1540                 cel_aggregation_topic);
1541         if (!cel_channel_forwarder) {
1542                 return -1;
1543         }
1544
1545         cel_bridge_forwarder = stasis_forward_all(
1546                 ast_bridge_topic_all_cached(),
1547                 cel_aggregation_topic);
1548         if (!cel_bridge_forwarder) {
1549                 return -1;
1550         }
1551
1552         cel_parking_forwarder = stasis_forward_all(
1553                 ast_parking_topic(),
1554                 cel_aggregation_topic);
1555         if (!cel_parking_forwarder) {
1556                 return -1;
1557         }
1558
1559         cel_cel_forwarder = stasis_forward_all(
1560                 ast_cel_topic(),
1561                 cel_aggregation_topic);
1562         if (!cel_cel_forwarder) {
1563                 return -1;
1564         }
1565
1566         return 0;
1567 }
1568
1569 /*!
1570  * \brief Create the Stasis message router and routes for CEL
1571  */
1572 static int create_routes(void)
1573 {
1574         int ret = 0;
1575
1576         cel_state_router = stasis_message_router_create(cel_aggregation_topic);
1577         if (!cel_state_router) {
1578                 return -1;
1579         }
1580
1581         ret |= stasis_message_router_add(cel_state_router,
1582                 stasis_cache_update_type(),
1583                 cel_snapshot_update_cb,
1584                 NULL);
1585
1586         ret |= stasis_message_router_add(cel_state_router,
1587                 ast_channel_dial_type(),
1588                 cel_dial_cb,
1589                 NULL);
1590
1591         ret |= stasis_message_router_add(cel_state_router,
1592                 ast_channel_entered_bridge_type(),
1593                 cel_bridge_enter_cb,
1594                 NULL);
1595
1596         ret |= stasis_message_router_add(cel_state_router,
1597                 ast_channel_left_bridge_type(),
1598                 cel_bridge_leave_cb,
1599                 NULL);
1600
1601         ret |= stasis_message_router_add(cel_state_router,
1602                 ast_parked_call_type(),
1603                 cel_parking_cb,
1604                 NULL);
1605
1606         ret |= stasis_message_router_add(cel_state_router,
1607                 cel_generic_type(),
1608                 cel_generic_cb,
1609                 NULL);
1610
1611         ret |= stasis_message_router_add(cel_state_router,
1612                 ast_blind_transfer_type(),
1613                 cel_blind_transfer_cb,
1614                 NULL);
1615
1616         ret |= stasis_message_router_add(cel_state_router,
1617                 ast_attended_transfer_type(),
1618                 cel_attended_transfer_cb,
1619                 NULL);
1620
1621         ret |= stasis_message_router_add(cel_state_router,
1622                 ast_call_pickup_type(),
1623                 cel_pickup_cb,
1624                 NULL);
1625
1626         ret |= stasis_message_router_add(cel_state_router,
1627                 ast_local_optimization_end_type(),
1628                 cel_local_cb,
1629                 NULL);
1630
1631         if (ret) {
1632                 ast_log(AST_LOG_ERROR, "Failed to register for Stasis messages\n");
1633         }
1634
1635         return ret;
1636 }
1637
1638 static int lid_hash(const void *obj, const int flags)
1639 {
1640         const struct cel_linkedid *lid;
1641         const char *key;
1642
1643         switch (flags & OBJ_SEARCH_MASK) {
1644         case OBJ_SEARCH_KEY:
1645                 key = obj;
1646                 break;
1647         case OBJ_SEARCH_OBJECT:
1648                 lid = obj;
1649                 key = lid->id;
1650                 break;
1651         default:
1652                 /* Hash can only work on something with a full key. */
1653                 ast_assert(0);
1654                 return 0;
1655         }
1656         return ast_str_hash(key);
1657 }
1658
1659 static int lid_cmp(void *obj, void *arg, int flags)
1660 {
1661         const struct cel_linkedid *object_left = obj;
1662         const struct cel_linkedid *object_right = arg;
1663         const char *right_key = arg;
1664         int cmp;
1665
1666         switch (flags & OBJ_SEARCH_MASK) {
1667         case OBJ_SEARCH_OBJECT:
1668                 right_key = object_right->id;
1669                 /* Fall through */
1670         case OBJ_SEARCH_KEY:
1671                 cmp = strcmp(object_left->id, right_key);
1672                 break;
1673         case OBJ_SEARCH_PARTIAL_KEY:
1674                 /*
1675                  * We could also use a partial key struct containing a length
1676                  * so strlen() does not get called for every comparison instead.
1677                  */
1678                 cmp = strncmp(object_left->id, right_key, strlen(right_key));
1679                 break;
1680         default:
1681                 /*
1682                  * What arg points to is specific to this traversal callback
1683                  * and has no special meaning to astobj2.
1684                  */
1685                 cmp = 0;
1686                 break;
1687         }
1688         if (cmp) {
1689                 return 0;
1690         }
1691         /*
1692          * At this point the traversal callback is identical to a sorted
1693          * container.
1694          */
1695         return CMP_MATCH;
1696 }
1697
1698 int ast_cel_engine_init(void)
1699 {
1700         struct ao2_container *container;
1701
1702         container = ao2_container_alloc(NUM_APP_BUCKETS, lid_hash, lid_cmp);
1703         ao2_global_obj_replace_unref(cel_linkedids, container);
1704         ao2_cleanup(container);
1705         if (!container) {
1706                 cel_engine_abort();
1707                 return -1;
1708         }
1709
1710         container = ao2_container_alloc(NUM_DIALSTATUS_BUCKETS,
1711                 dialstatus_hash, dialstatus_cmp);
1712         ao2_global_obj_replace_unref(cel_dialstatus_store, container);
1713         ao2_cleanup(container);
1714         if (!container) {
1715                 cel_engine_abort();
1716                 return -1;
1717         }
1718
1719         if (STASIS_MESSAGE_TYPE_INIT(cel_generic_type)) {
1720                 cel_engine_abort();
1721                 return -1;
1722         }
1723
1724         if (ast_cli_register(&cli_status)) {
1725                 cel_engine_abort();
1726                 return -1;
1727         }
1728
1729         container = ao2_container_alloc(BACKEND_BUCKETS, cel_backend_hash, cel_backend_cmp);
1730         ao2_global_obj_replace_unref(cel_backends, container);
1731         ao2_cleanup(container);
1732         if (!container) {
1733                 cel_engine_abort();
1734                 return -1;
1735         }
1736
1737         if (aco_info_init(&cel_cfg_info)) {
1738                 cel_engine_abort();
1739                 return -1;
1740         }
1741
1742         aco_option_register(&cel_cfg_info, "enable", ACO_EXACT, general_options, "no", OPT_BOOL_T, 1, FLDSET(struct ast_cel_general_config, enable));
1743         aco_option_register(&cel_cfg_info, "dateformat", ACO_EXACT, general_options, "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_cel_general_config, date_format));
1744         aco_option_register_custom(&cel_cfg_info, "apps", ACO_EXACT, general_options, "", apps_handler, 0);
1745         aco_option_register_custom(&cel_cfg_info, "events", ACO_EXACT, general_options, "", events_handler, 0);
1746
1747         if (aco_process_config(&cel_cfg_info, 0)) {
1748                 struct cel_config *cel_cfg = cel_config_alloc();
1749
1750                 if (!cel_cfg) {
1751                         cel_engine_abort();
1752                         return -1;
1753                 }
1754
1755                 /* We couldn't process the configuration so create a default config. */
1756                 if (!aco_set_defaults(&general_option, "general", cel_cfg->general)) {
1757                         ast_log(LOG_NOTICE, "Failed to process CEL configuration; using defaults\n");
1758                         ao2_global_obj_replace_unref(cel_configs, cel_cfg);
1759                 }
1760                 ao2_ref(cel_cfg, -1);
1761         }
1762
1763         if (create_subscriptions()) {
1764                 cel_engine_abort();
1765                 return -1;
1766         }
1767
1768         if (ast_cel_check_enabled() && create_routes()) {
1769                 cel_engine_abort();
1770                 return -1;
1771         }
1772
1773         ast_register_atexit(cel_engine_atexit);
1774         ast_register_cleanup(cel_engine_cleanup);
1775         return 0;
1776 }
1777
1778 int ast_cel_engine_reload(void)
1779 {
1780         unsigned int was_enabled = ast_cel_check_enabled();
1781         unsigned int is_enabled;
1782
1783         if (aco_process_config(&cel_cfg_info, 1) == ACO_PROCESS_ERROR) {
1784                 return -1;
1785         }
1786
1787         is_enabled = ast_cel_check_enabled();
1788
1789         if (!was_enabled && is_enabled) {
1790                 if (create_routes()) {
1791                         return -1;
1792                 }
1793         } else if (was_enabled && !is_enabled) {
1794                 destroy_routes();
1795         }
1796
1797         ast_verb(3, "CEL logging %sabled.\n", is_enabled ? "en" : "dis");
1798
1799         return 0;
1800 }
1801
1802 void ast_cel_publish_event(struct ast_channel *chan,
1803         enum ast_cel_event_type event_type,
1804         struct ast_json *blob)
1805 {
1806         struct ast_json *cel_blob;
1807         struct stasis_message *message;
1808
1809         cel_blob = ast_json_pack("{s: i, s: O}",
1810                 "event_type", event_type,
1811                 "event_details", blob);
1812
1813         message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan), cel_generic_type(), cel_blob);
1814         if (message) {
1815                 stasis_publish(ast_cel_topic(), message);
1816         }
1817         ao2_cleanup(message);
1818         ast_json_unref(cel_blob);
1819 }
1820
1821 struct stasis_topic *ast_cel_topic(void)
1822 {
1823         return cel_topic;
1824 }
1825
1826 struct ast_cel_general_config *ast_cel_get_config(void)
1827 {
1828         RAII_VAR(struct cel_config *, mod_cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
1829
1830         if (!mod_cfg || !mod_cfg->general) {
1831                 return NULL;
1832         }
1833
1834         ao2_ref(mod_cfg->general, +1);
1835         return mod_cfg->general;
1836 }
1837
1838 void ast_cel_set_config(struct ast_cel_general_config *config)
1839 {
1840         int was_enabled;
1841         int is_enabled;
1842         struct ast_cel_general_config *cleanup_config;
1843         struct cel_config *mod_cfg = ao2_global_obj_ref(cel_configs);
1844
1845         if (mod_cfg) {
1846                 was_enabled = ast_cel_check_enabled();
1847
1848                 cleanup_config = mod_cfg->general;
1849                 ao2_bump(config);
1850                 mod_cfg->general = config;
1851                 ao2_cleanup(cleanup_config);
1852
1853                 is_enabled = ast_cel_check_enabled();
1854                 if (!was_enabled && is_enabled) {
1855                         create_routes();
1856                 } else if (was_enabled && !is_enabled) {
1857                         destroy_routes();
1858                 }
1859
1860                 ao2_ref(mod_cfg, -1);
1861         }
1862 }
1863
1864 int ast_cel_backend_unregister(const char *name)
1865 {
1866         struct ao2_container *backends = ao2_global_obj_ref(cel_backends);
1867
1868         if (backends) {
1869                 ao2_find(backends, name, OBJ_SEARCH_KEY | OBJ_NODATA | OBJ_UNLINK);
1870                 ao2_ref(backends, -1);
1871         }
1872
1873         return 0;
1874 }
1875
1876 int ast_cel_backend_register(const char *name, ast_cel_backend_cb backend_callback)
1877 {
1878         RAII_VAR(struct ao2_container *, backends, ao2_global_obj_ref(cel_backends), ao2_cleanup);
1879         struct cel_backend *backend;
1880
1881         if (!backends || ast_strlen_zero(name) || !backend_callback) {
1882                 return -1;
1883         }
1884
1885         /* The backend object is immutable so it doesn't need a lock of its own. */
1886         backend = ao2_alloc_options(sizeof(*backend) + 1 + strlen(name), NULL,
1887                 AO2_ALLOC_OPT_LOCK_NOLOCK);
1888         if (!backend) {
1889                 return -1;
1890         }
1891         strcpy(backend->name, name);/* Safe */
1892         backend->callback = backend_callback;
1893
1894         ao2_link(backends, backend);
1895         ao2_ref(backend, -1);
1896         return 0;
1897 }