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