ARI: Add ability to raise arbitrary User Events
[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_ACCTCODE), "");
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}", "bridge_id", snapshot->uniqueid);
1171         if (!extra) {
1172                 return;
1173         }
1174
1175         peer_str = cel_generate_peer_str(snapshot, chan_snapshot);
1176         if (!peer_str) {
1177                 return;
1178         }
1179
1180         cel_report_event(chan_snapshot, AST_CEL_BRIDGE_ENTER, NULL, extra, ast_str_buffer(peer_str));
1181 }
1182
1183 static void cel_bridge_leave_cb(
1184         void *data, struct stasis_subscription *sub,
1185         struct stasis_message *message)
1186 {
1187         struct ast_bridge_blob *blob = stasis_message_data(message);
1188         struct ast_bridge_snapshot *snapshot = blob->bridge;
1189         struct ast_channel_snapshot *chan_snapshot = blob->channel;
1190         RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1191         RAII_VAR(struct ast_str *, peer_str, NULL, ast_free);
1192
1193         if (cel_filter_channel_snapshot(chan_snapshot)) {
1194                 return;
1195         }
1196
1197         extra = ast_json_pack("{s: s}", "bridge_id", snapshot->uniqueid);
1198         if (!extra) {
1199                 return;
1200         }
1201
1202         peer_str = cel_generate_peer_str(snapshot, chan_snapshot);
1203         if (!peer_str) {
1204                 return;
1205         }
1206
1207         cel_report_event(chan_snapshot, AST_CEL_BRIDGE_EXIT, NULL, extra, ast_str_buffer(peer_str));
1208 }
1209
1210 static void cel_parking_cb(
1211         void *data, struct stasis_subscription *sub,
1212         struct stasis_message *message)
1213 {
1214         struct ast_parked_call_payload *parked_payload = stasis_message_data(message);
1215         RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1216         const char *reason = NULL;
1217
1218         switch (parked_payload->event_type) {
1219         case PARKED_CALL:
1220                 extra = ast_json_pack("{s: s, s: s}",
1221                         "parker_dial_string", parked_payload->parker_dial_string,
1222                         "parking_lot", parked_payload->parkinglot);
1223                 if (extra) {
1224                         cel_report_event(parked_payload->parkee, AST_CEL_PARK_START, NULL, extra, NULL);
1225                 }
1226                 return;
1227         case PARKED_CALL_TIMEOUT:
1228                 reason = "ParkedCallTimeOut";
1229                 break;
1230         case PARKED_CALL_GIVEUP:
1231                 reason = "ParkedCallGiveUp";
1232                 break;
1233         case PARKED_CALL_UNPARKED:
1234                 reason = "ParkedCallUnparked";
1235                 break;
1236         case PARKED_CALL_FAILED:
1237                 reason = "ParkedCallFailed";
1238                 break;
1239         case PARKED_CALL_SWAP:
1240                 reason = "ParkedCallSwap";
1241                 break;
1242         }
1243
1244         extra = ast_json_pack("{s: s}", "reason", reason);
1245         if (extra) {
1246                 cel_report_event(parked_payload->parkee, AST_CEL_PARK_END, NULL, extra, NULL);
1247         }
1248 }
1249
1250 static void save_dialstatus(struct ast_multi_channel_blob *blob)
1251 {
1252         struct ao2_container *dial_statuses = ao2_global_obj_ref(cel_dialstatus_store);
1253
1254         ast_assert(blob != NULL);
1255
1256         if (dial_statuses) {
1257                 ao2_link(dial_statuses, blob);
1258                 ao2_ref(dial_statuses, -1);
1259         }
1260 }
1261
1262 static void cel_dial_cb(void *data, struct stasis_subscription *sub,
1263         struct stasis_message *message)
1264 {
1265         struct ast_multi_channel_blob *blob = stasis_message_data(message);
1266
1267         if (cel_filter_channel_snapshot(ast_multi_channel_blob_get_channel(blob, "caller"))) {
1268                 return;
1269         }
1270
1271         if (!get_caller_uniqueid(blob)) {
1272                 return;
1273         }
1274
1275         if (!ast_strlen_zero(get_blob_variable(blob, "forward"))) {
1276                 struct ast_channel_snapshot *caller = ast_multi_channel_blob_get_channel(blob, "caller");
1277                 struct ast_json *extra;
1278
1279                 if (!caller) {
1280                         return;
1281                 }
1282
1283                 extra = ast_json_pack("{s: s}", "forward", get_blob_variable(blob, "forward"));
1284                 if (extra) {
1285                         cel_report_event(caller, AST_CEL_FORWARD, NULL, extra, NULL);
1286                         ast_json_unref(extra);
1287                 }
1288         }
1289
1290         if (ast_strlen_zero(get_blob_variable(blob, "dialstatus"))) {
1291                 return;
1292         }
1293
1294         save_dialstatus(blob);
1295 }
1296
1297 static void cel_generic_cb(
1298         void *data, struct stasis_subscription *sub,
1299         struct stasis_message *message)
1300 {
1301         struct ast_channel_blob *obj = stasis_message_data(message);
1302         int event_type = ast_json_integer_get(ast_json_object_get(obj->blob, "event_type"));
1303         struct ast_json *event_details = ast_json_object_get(obj->blob, "event_details");
1304
1305         switch (event_type) {
1306         case AST_CEL_USER_DEFINED:
1307                 {
1308                         const char *event = ast_json_string_get(ast_json_object_get(event_details, "event"));
1309                         struct ast_json *extra = ast_json_object_get(event_details, "extra");
1310                         cel_report_event(obj->snapshot, event_type, event, extra, NULL);
1311                         break;
1312                 }
1313         default:
1314                 ast_log(LOG_ERROR, "Unhandled %s event blob\n", ast_cel_get_type_name(event_type));
1315                 break;
1316         }
1317 }
1318
1319 static void cel_blind_transfer_cb(
1320         void *data, struct stasis_subscription *sub,
1321         struct stasis_message *message)
1322 {
1323         struct ast_bridge_blob *obj = stasis_message_data(message);
1324         struct ast_channel_snapshot *chan_snapshot = obj->channel;
1325         struct ast_bridge_snapshot *bridge_snapshot = obj->bridge;
1326         struct ast_json *blob = obj->blob;
1327         struct ast_json *json_result = ast_json_object_get(blob, "result");
1328         struct ast_json *json_exten;
1329         struct ast_json *json_context;
1330         struct ast_json *extra;
1331         const char *exten;
1332         const char *context;
1333         enum ast_transfer_result result;
1334
1335         if (!json_result) {
1336                 return;
1337         }
1338
1339         result = ast_json_integer_get(json_result);
1340         if (result != AST_BRIDGE_TRANSFER_SUCCESS) {
1341                 return;
1342         }
1343
1344         json_exten = ast_json_object_get(blob, "exten");
1345         json_context = ast_json_object_get(blob, "context");
1346
1347         if (!json_exten || !json_context) {
1348                 return;
1349         }
1350
1351         exten = ast_json_string_get(json_exten);
1352         context = ast_json_string_get(json_context);
1353         if (!exten || !context) {
1354                 return;
1355         }
1356
1357         extra = ast_json_pack("{s: s, s: s, s: s}",
1358                 "extension", exten,
1359                 "context", context,
1360                 "bridge_id", bridge_snapshot->uniqueid);
1361         if (extra) {
1362                 cel_report_event(chan_snapshot, AST_CEL_BLINDTRANSFER, NULL, extra, NULL);
1363                 ast_json_unref(extra);
1364         }
1365 }
1366
1367 static void cel_attended_transfer_cb(
1368         void *data, struct stasis_subscription *sub,
1369         struct stasis_message *message)
1370 {
1371         struct ast_attended_transfer_message *xfer = stasis_message_data(message);
1372         struct ast_json *extra = NULL;
1373         struct ast_bridge_snapshot *bridge1, *bridge2;
1374         struct ast_channel_snapshot *channel1, *channel2;
1375
1376         /* Make sure bridge1 is always non-NULL */
1377         if (!xfer->to_transferee.bridge_snapshot) {
1378                 bridge1 = xfer->to_transfer_target.bridge_snapshot;
1379                 bridge2 = xfer->to_transferee.bridge_snapshot;
1380                 channel1 = xfer->to_transfer_target.channel_snapshot;
1381                 channel2 = xfer->to_transferee.channel_snapshot;
1382         } else {
1383                 bridge1 = xfer->to_transferee.bridge_snapshot;
1384                 bridge2 = xfer->to_transfer_target.bridge_snapshot;
1385                 channel1 = xfer->to_transferee.channel_snapshot;
1386                 channel2 = xfer->to_transfer_target.channel_snapshot;
1387         }
1388
1389         switch (xfer->dest_type) {
1390         case AST_ATTENDED_TRANSFER_DEST_FAIL:
1391                 return;
1392                 /* handle these three the same */
1393         case AST_ATTENDED_TRANSFER_DEST_BRIDGE_MERGE:
1394         case AST_ATTENDED_TRANSFER_DEST_LINK:
1395         case AST_ATTENDED_TRANSFER_DEST_THREEWAY:
1396                 extra = ast_json_pack("{s: s, s: s, s: s}",
1397                         "bridge1_id", bridge1->uniqueid,
1398                         "channel2_name", channel2->name,
1399                         "bridge2_id", bridge2->uniqueid);
1400                 if (!extra) {
1401                         return;
1402                 }
1403                 break;
1404         case AST_ATTENDED_TRANSFER_DEST_APP:
1405                 extra = ast_json_pack("{s: s, s: s, s: s}",
1406                         "bridge1_id", bridge1->uniqueid,
1407                         "channel2_name", channel2->name,
1408                         "app", xfer->dest.app);
1409                 if (!extra) {
1410                         return;
1411                 }
1412                 break;
1413         }
1414         cel_report_event(channel1, AST_CEL_ATTENDEDTRANSFER, NULL, extra, NULL);
1415         ast_json_unref(extra);
1416 }
1417
1418 static void cel_pickup_cb(
1419         void *data, struct stasis_subscription *sub,
1420         struct stasis_message *message)
1421 {
1422         struct ast_multi_channel_blob *obj = stasis_message_data(message);
1423         struct ast_channel_snapshot *channel = ast_multi_channel_blob_get_channel(obj, "channel");
1424         struct ast_channel_snapshot *target = ast_multi_channel_blob_get_channel(obj, "target");
1425         struct ast_json *extra;
1426
1427         if (!channel || !target) {
1428                 return;
1429         }
1430
1431         extra = ast_json_pack("{s: s}", "pickup_channel", channel->name);
1432         if (!extra) {
1433                 return;
1434         }
1435
1436         cel_report_event(target, AST_CEL_PICKUP, NULL, extra, NULL);
1437         ast_json_unref(extra);
1438 }
1439
1440 static void cel_local_cb(
1441         void *data, struct stasis_subscription *sub,
1442         struct stasis_message *message)
1443 {
1444         struct ast_multi_channel_blob *obj = stasis_message_data(message);
1445         struct ast_channel_snapshot *localone = ast_multi_channel_blob_get_channel(obj, "1");
1446         struct ast_channel_snapshot *localtwo = ast_multi_channel_blob_get_channel(obj, "2");
1447         struct ast_json *extra;
1448
1449         if (!localone || !localtwo) {
1450                 return;
1451         }
1452
1453         extra = ast_json_pack("{s: s}", "local_two", localtwo->name);
1454         if (!extra) {
1455                 return;
1456         }
1457
1458         cel_report_event(localone, AST_CEL_LOCAL_OPTIMIZE, NULL, extra, NULL);
1459         ast_json_unref(extra);
1460 }
1461
1462 static void destroy_routes(void)
1463 {
1464         stasis_message_router_unsubscribe_and_join(cel_state_router);
1465         cel_state_router = NULL;
1466 }
1467
1468 static void destroy_subscriptions(void)
1469 {
1470         ao2_cleanup(cel_aggregation_topic);
1471         cel_aggregation_topic = NULL;
1472         ao2_cleanup(cel_topic);
1473         cel_topic = NULL;
1474
1475         cel_channel_forwarder = stasis_forward_cancel(cel_channel_forwarder);
1476         cel_bridge_forwarder = stasis_forward_cancel(cel_bridge_forwarder);
1477         cel_parking_forwarder = stasis_forward_cancel(cel_parking_forwarder);
1478         cel_cel_forwarder = stasis_forward_cancel(cel_cel_forwarder);
1479 }
1480
1481 static void cel_engine_cleanup(void)
1482 {
1483         destroy_routes();
1484         destroy_subscriptions();
1485         STASIS_MESSAGE_TYPE_CLEANUP(cel_generic_type);
1486 }
1487
1488 static void cel_engine_atexit(void)
1489 {
1490         ast_cli_unregister(&cli_status);
1491         aco_info_destroy(&cel_cfg_info);
1492         ao2_global_obj_release(cel_configs);
1493         ao2_global_obj_release(cel_dialstatus_store);
1494         ao2_global_obj_release(cel_linkedids);
1495         ao2_global_obj_release(cel_backends);
1496 }
1497
1498 static void cel_engine_abort(void)
1499 {
1500         cel_engine_cleanup();
1501         cel_engine_atexit();
1502 }
1503
1504 /*!
1505  * \brief Create the Stasis subscriptions for CEL
1506  */
1507 static int create_subscriptions(void)
1508 {
1509         cel_aggregation_topic = stasis_topic_create("cel_aggregation_topic");
1510         if (!cel_aggregation_topic) {
1511                 return -1;
1512         }
1513
1514         cel_topic = stasis_topic_create("cel_topic");
1515         if (!cel_topic) {
1516                 return -1;
1517         }
1518
1519         cel_channel_forwarder = stasis_forward_all(
1520                 ast_channel_topic_all_cached(),
1521                 cel_aggregation_topic);
1522         if (!cel_channel_forwarder) {
1523                 return -1;
1524         }
1525
1526         cel_bridge_forwarder = stasis_forward_all(
1527                 ast_bridge_topic_all_cached(),
1528                 cel_aggregation_topic);
1529         if (!cel_bridge_forwarder) {
1530                 return -1;
1531         }
1532
1533         cel_parking_forwarder = stasis_forward_all(
1534                 ast_parking_topic(),
1535                 cel_aggregation_topic);
1536         if (!cel_parking_forwarder) {
1537                 return -1;
1538         }
1539
1540         cel_cel_forwarder = stasis_forward_all(
1541                 ast_cel_topic(),
1542                 cel_aggregation_topic);
1543         if (!cel_cel_forwarder) {
1544                 return -1;
1545         }
1546
1547         return 0;
1548 }
1549
1550 /*!
1551  * \brief Create the Stasis message router and routes for CEL
1552  */
1553 static int create_routes(void)
1554 {
1555         int ret = 0;
1556
1557         cel_state_router = stasis_message_router_create(cel_aggregation_topic);
1558         if (!cel_state_router) {
1559                 return -1;
1560         }
1561
1562         ret |= stasis_message_router_add(cel_state_router,
1563                 stasis_cache_update_type(),
1564                 cel_snapshot_update_cb,
1565                 NULL);
1566
1567         ret |= stasis_message_router_add(cel_state_router,
1568                 ast_channel_dial_type(),
1569                 cel_dial_cb,
1570                 NULL);
1571
1572         ret |= stasis_message_router_add(cel_state_router,
1573                 ast_channel_entered_bridge_type(),
1574                 cel_bridge_enter_cb,
1575                 NULL);
1576
1577         ret |= stasis_message_router_add(cel_state_router,
1578                 ast_channel_left_bridge_type(),
1579                 cel_bridge_leave_cb,
1580                 NULL);
1581
1582         ret |= stasis_message_router_add(cel_state_router,
1583                 ast_parked_call_type(),
1584                 cel_parking_cb,
1585                 NULL);
1586
1587         ret |= stasis_message_router_add(cel_state_router,
1588                 cel_generic_type(),
1589                 cel_generic_cb,
1590                 NULL);
1591
1592         ret |= stasis_message_router_add(cel_state_router,
1593                 ast_blind_transfer_type(),
1594                 cel_blind_transfer_cb,
1595                 NULL);
1596
1597         ret |= stasis_message_router_add(cel_state_router,
1598                 ast_attended_transfer_type(),
1599                 cel_attended_transfer_cb,
1600                 NULL);
1601
1602         ret |= stasis_message_router_add(cel_state_router,
1603                 ast_call_pickup_type(),
1604                 cel_pickup_cb,
1605                 NULL);
1606
1607         ret |= stasis_message_router_add(cel_state_router,
1608                 ast_local_optimization_end_type(),
1609                 cel_local_cb,
1610                 NULL);
1611
1612         if (ret) {
1613                 ast_log(AST_LOG_ERROR, "Failed to register for Stasis messages\n");
1614         }
1615
1616         return ret;
1617 }
1618
1619 static int lid_hash(const void *obj, const int flags)
1620 {
1621         const struct cel_linkedid *lid;
1622         const char *key;
1623
1624         switch (flags & OBJ_SEARCH_MASK) {
1625         case OBJ_SEARCH_KEY:
1626                 key = obj;
1627                 break;
1628         case OBJ_SEARCH_OBJECT:
1629                 lid = obj;
1630                 key = lid->id;
1631                 break;
1632         default:
1633                 /* Hash can only work on something with a full key. */
1634                 ast_assert(0);
1635                 return 0;
1636         }
1637         return ast_str_hash(key);
1638 }
1639
1640 static int lid_cmp(void *obj, void *arg, int flags)
1641 {
1642         const struct cel_linkedid *object_left = obj;
1643         const struct cel_linkedid *object_right = arg;
1644         const char *right_key = arg;
1645         int cmp;
1646
1647         switch (flags & OBJ_SEARCH_MASK) {
1648         case OBJ_SEARCH_OBJECT:
1649                 right_key = object_right->id;
1650                 /* Fall through */
1651         case OBJ_SEARCH_KEY:
1652                 cmp = strcmp(object_left->id, right_key);
1653                 break;
1654         case OBJ_SEARCH_PARTIAL_KEY:
1655                 /*
1656                  * We could also use a partial key struct containing a length
1657                  * so strlen() does not get called for every comparison instead.
1658                  */
1659                 cmp = strncmp(object_left->id, right_key, strlen(right_key));
1660                 break;
1661         default:
1662                 /*
1663                  * What arg points to is specific to this traversal callback
1664                  * and has no special meaning to astobj2.
1665                  */
1666                 cmp = 0;
1667                 break;
1668         }
1669         if (cmp) {
1670                 return 0;
1671         }
1672         /*
1673          * At this point the traversal callback is identical to a sorted
1674          * container.
1675          */
1676         return CMP_MATCH;
1677 }
1678
1679 int ast_cel_engine_init(void)
1680 {
1681         struct ao2_container *container;
1682
1683         container = ao2_container_alloc(NUM_APP_BUCKETS, lid_hash, lid_cmp);
1684         ao2_global_obj_replace_unref(cel_linkedids, container);
1685         ao2_cleanup(container);
1686         if (!container) {
1687                 cel_engine_abort();
1688                 return -1;
1689         }
1690
1691         container = ao2_container_alloc(NUM_DIALSTATUS_BUCKETS,
1692                 dialstatus_hash, dialstatus_cmp);
1693         ao2_global_obj_replace_unref(cel_dialstatus_store, container);
1694         ao2_cleanup(container);
1695         if (!container) {
1696                 cel_engine_abort();
1697                 return -1;
1698         }
1699
1700         if (STASIS_MESSAGE_TYPE_INIT(cel_generic_type)) {
1701                 cel_engine_abort();
1702                 return -1;
1703         }
1704
1705         if (ast_cli_register(&cli_status)) {
1706                 cel_engine_abort();
1707                 return -1;
1708         }
1709
1710         container = ao2_container_alloc(BACKEND_BUCKETS, cel_backend_hash, cel_backend_cmp);
1711         ao2_global_obj_replace_unref(cel_backends, container);
1712         ao2_cleanup(container);
1713         if (!container) {
1714                 cel_engine_abort();
1715                 return -1;
1716         }
1717
1718         if (aco_info_init(&cel_cfg_info)) {
1719                 cel_engine_abort();
1720                 return -1;
1721         }
1722
1723         aco_option_register(&cel_cfg_info, "enable", ACO_EXACT, general_options, "no", OPT_BOOL_T, 1, FLDSET(struct ast_cel_general_config, enable));
1724         aco_option_register(&cel_cfg_info, "dateformat", ACO_EXACT, general_options, "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_cel_general_config, date_format));
1725         aco_option_register_custom(&cel_cfg_info, "apps", ACO_EXACT, general_options, "", apps_handler, 0);
1726         aco_option_register_custom(&cel_cfg_info, "events", ACO_EXACT, general_options, "", events_handler, 0);
1727
1728         if (aco_process_config(&cel_cfg_info, 0)) {
1729                 struct cel_config *cel_cfg = cel_config_alloc();
1730
1731                 if (!cel_cfg) {
1732                         cel_engine_abort();
1733                         return -1;
1734                 }
1735
1736                 /* We couldn't process the configuration so create a default config. */
1737                 if (!aco_set_defaults(&general_option, "general", cel_cfg->general)) {
1738                         ast_log(LOG_NOTICE, "Failed to process CEL configuration; using defaults\n");
1739                         ao2_global_obj_replace_unref(cel_configs, cel_cfg);
1740                 }
1741                 ao2_ref(cel_cfg, -1);
1742         }
1743
1744         if (create_subscriptions()) {
1745                 cel_engine_abort();
1746                 return -1;
1747         }
1748
1749         if (ast_cel_check_enabled() && create_routes()) {
1750                 cel_engine_abort();
1751                 return -1;
1752         }
1753
1754         ast_register_atexit(cel_engine_atexit);
1755         ast_register_cleanup(cel_engine_cleanup);
1756         return 0;
1757 }
1758
1759 int ast_cel_engine_reload(void)
1760 {
1761         unsigned int was_enabled = ast_cel_check_enabled();
1762         unsigned int is_enabled;
1763
1764         if (aco_process_config(&cel_cfg_info, 1) == ACO_PROCESS_ERROR) {
1765                 return -1;
1766         }
1767
1768         is_enabled = ast_cel_check_enabled();
1769
1770         if (!was_enabled && is_enabled) {
1771                 if (create_routes()) {
1772                         return -1;
1773                 }
1774         } else if (was_enabled && !is_enabled) {
1775                 destroy_routes();
1776         }
1777
1778         ast_verb(3, "CEL logging %sabled.\n", is_enabled ? "en" : "dis");
1779
1780         return 0;
1781 }
1782
1783 void ast_cel_publish_event(struct ast_channel *chan,
1784         enum ast_cel_event_type event_type,
1785         struct ast_json *blob)
1786 {
1787         struct ast_json *cel_blob;
1788         struct stasis_message *message;
1789
1790         cel_blob = ast_json_pack("{s: i, s: O}",
1791                 "event_type", event_type,
1792                 "event_details", blob);
1793
1794         ast_channel_lock(chan);
1795         message = ast_channel_blob_create(chan, cel_generic_type(), cel_blob);
1796         ast_channel_unlock(chan);
1797         if (message) {
1798                 stasis_publish(ast_cel_topic(), message);
1799         }
1800         ao2_cleanup(message);
1801         ast_json_unref(cel_blob);
1802 }
1803
1804 struct stasis_topic *ast_cel_topic(void)
1805 {
1806         return cel_topic;
1807 }
1808
1809 struct ast_cel_general_config *ast_cel_get_config(void)
1810 {
1811         RAII_VAR(struct cel_config *, mod_cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
1812
1813         if (!mod_cfg || !mod_cfg->general) {
1814                 return NULL;
1815         }
1816
1817         ao2_ref(mod_cfg->general, +1);
1818         return mod_cfg->general;
1819 }
1820
1821 void ast_cel_set_config(struct ast_cel_general_config *config)
1822 {
1823         int was_enabled;
1824         int is_enabled;
1825         struct ast_cel_general_config *cleanup_config;
1826         struct cel_config *mod_cfg = ao2_global_obj_ref(cel_configs);
1827
1828         if (mod_cfg) {
1829                 was_enabled = ast_cel_check_enabled();
1830
1831                 cleanup_config = mod_cfg->general;
1832                 ao2_bump(config);
1833                 mod_cfg->general = config;
1834                 ao2_cleanup(cleanup_config);
1835
1836                 is_enabled = ast_cel_check_enabled();
1837                 if (!was_enabled && is_enabled) {
1838                         create_routes();
1839                 } else if (was_enabled && !is_enabled) {
1840                         destroy_routes();
1841                 }
1842
1843                 ao2_ref(mod_cfg, -1);
1844         }
1845 }
1846
1847 int ast_cel_backend_unregister(const char *name)
1848 {
1849         struct ao2_container *backends = ao2_global_obj_ref(cel_backends);
1850
1851         if (backends) {
1852                 ao2_find(backends, name, OBJ_SEARCH_KEY | OBJ_NODATA | OBJ_UNLINK);
1853                 ao2_ref(backends, -1);
1854         }
1855
1856         return 0;
1857 }
1858
1859 int ast_cel_backend_register(const char *name, ast_cel_backend_cb backend_callback)
1860 {
1861         RAII_VAR(struct ao2_container *, backends, ao2_global_obj_ref(cel_backends), ao2_cleanup);
1862         struct cel_backend *backend;
1863
1864         if (!backends || ast_strlen_zero(name) || !backend_callback) {
1865                 return -1;
1866         }
1867
1868         /* The backend object is immutable so it doesn't need a lock of its own. */
1869         backend = ao2_alloc_options(sizeof(*backend) + 1 + strlen(name), NULL,
1870                 AO2_ALLOC_OPT_LOCK_NOLOCK);
1871         if (!backend) {
1872                 return -1;
1873         }
1874         strcpy(backend->name, name);/* Safe */
1875         backend->callback = backend_callback;
1876
1877         ao2_link(backends, backend);
1878         ao2_ref(backend, -1);
1879         return 0;
1880 }