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