c4b80b5c1531546da4b9e0ae03291c0ac9d0e95b
[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_subscription *cel_channel_forwarder;
125
126 /*! Subscription for forwarding the channel caching topic */
127 static struct stasis_subscription *cel_bridge_forwarder;
128
129 /*! Subscription for forwarding the parking topic */
130 static struct stasis_subscription *cel_parking_forwarder;
131
132 /*! Subscription for forwarding the CEL-specific topic */
133 static struct stasis_subscription *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 static int do_reload(void)
551 {
552         if (aco_process_config(&cel_cfg_info, 1) == ACO_PROCESS_ERROR) {
553                 return -1;
554         }
555
556         ast_verb(3, "CEL logging %sabled.\n", ast_cel_check_enabled() ? "en" : "dis");
557
558         return 0;
559 }
560
561 const char *ast_cel_get_type_name(enum ast_cel_event_type type)
562 {
563         return S_OR(cel_event_types[type], "Unknown");
564 }
565
566 static int cel_track_app(const char *const_app)
567 {
568         RAII_VAR(struct cel_config *, cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
569         RAII_VAR(char *, app, NULL, ao2_cleanup);
570         char *app_lower;
571
572         if (!cfg || !cfg->general) {
573                 return 0;
574         }
575
576         app_lower = ast_str_to_lower(ast_strdupa(const_app));
577         app = ao2_find(cfg->general->apps, app_lower, OBJ_KEY);
578         if (!app) {
579                 return 0;
580         }
581
582         return 1;
583 }
584
585 static int cel_linkedid_ref(const char *linkedid);
586 struct ast_event *ast_cel_create_event(struct ast_channel_snapshot *snapshot,
587                 enum ast_cel_event_type event_type, const char *userdefevname,
588                 struct ast_json *extra)
589 {
590         struct timeval eventtime = ast_tvnow();
591         RAII_VAR(char *, extra_txt, NULL, ast_json_free);
592         if (extra) {
593                 extra_txt = ast_json_dump_string(extra);
594         }
595         return ast_event_new(AST_EVENT_CEL,
596                 AST_EVENT_IE_CEL_EVENT_TYPE, AST_EVENT_IE_PLTYPE_UINT, event_type,
597                 AST_EVENT_IE_CEL_EVENT_TIME, AST_EVENT_IE_PLTYPE_UINT, eventtime.tv_sec,
598                 AST_EVENT_IE_CEL_EVENT_TIME_USEC, AST_EVENT_IE_PLTYPE_UINT, eventtime.tv_usec,
599                 AST_EVENT_IE_CEL_USEREVENT_NAME, AST_EVENT_IE_PLTYPE_STR, S_OR(userdefevname, ""),
600                 AST_EVENT_IE_CEL_CIDNAME, AST_EVENT_IE_PLTYPE_STR, snapshot->caller_name,
601                 AST_EVENT_IE_CEL_CIDNUM, AST_EVENT_IE_PLTYPE_STR, snapshot->caller_number,
602                 AST_EVENT_IE_CEL_CIDANI, AST_EVENT_IE_PLTYPE_STR, snapshot->caller_ani,
603                 AST_EVENT_IE_CEL_CIDRDNIS, AST_EVENT_IE_PLTYPE_STR, snapshot->caller_rdnis,
604                 AST_EVENT_IE_CEL_CIDDNID, AST_EVENT_IE_PLTYPE_STR, snapshot->caller_dnid,
605                 AST_EVENT_IE_CEL_EXTEN, AST_EVENT_IE_PLTYPE_STR, snapshot->exten,
606                 AST_EVENT_IE_CEL_CONTEXT, AST_EVENT_IE_PLTYPE_STR, snapshot->context,
607                 AST_EVENT_IE_CEL_CHANNAME, AST_EVENT_IE_PLTYPE_STR, snapshot->name,
608                 AST_EVENT_IE_CEL_APPNAME, AST_EVENT_IE_PLTYPE_STR, snapshot->appl,
609                 AST_EVENT_IE_CEL_APPDATA, AST_EVENT_IE_PLTYPE_STR, snapshot->data,
610                 AST_EVENT_IE_CEL_AMAFLAGS, AST_EVENT_IE_PLTYPE_UINT, snapshot->amaflags,
611                 AST_EVENT_IE_CEL_ACCTCODE, AST_EVENT_IE_PLTYPE_STR, snapshot->accountcode,
612                 AST_EVENT_IE_CEL_PEERACCT, AST_EVENT_IE_PLTYPE_STR, snapshot->peeraccount,
613                 AST_EVENT_IE_CEL_UNIQUEID, AST_EVENT_IE_PLTYPE_STR, snapshot->uniqueid,
614                 AST_EVENT_IE_CEL_LINKEDID, AST_EVENT_IE_PLTYPE_STR, snapshot->linkedid,
615                 AST_EVENT_IE_CEL_USERFIELD, AST_EVENT_IE_PLTYPE_STR, snapshot->userfield,
616                 AST_EVENT_IE_CEL_EXTRA, AST_EVENT_IE_PLTYPE_STR, S_OR(extra_txt, ""),
617                 AST_EVENT_IE_CEL_PEER, AST_EVENT_IE_PLTYPE_STR, "",
618                 AST_EVENT_IE_END);
619 }
620
621 static int cel_backend_send_cb(void *obj, void *arg, int flags)
622 {
623         struct cel_backend *backend = obj;
624
625         backend->callback(arg);
626         return 0;
627 }
628
629 static int cel_report_event(struct ast_channel_snapshot *snapshot,
630                 enum ast_cel_event_type event_type, const char *userdefevname,
631                 struct ast_json *extra)
632 {
633         struct ast_event *ev;
634         char *linkedid = ast_strdupa(snapshot->linkedid);
635         RAII_VAR(struct cel_config *, cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
636
637         if (!cfg || !cfg->general) {
638                 return 0;
639         }
640
641         if (!cfg->general->enable) {
642                 return 0;
643         }
644
645         /* Record the linkedid of new channels if we are tracking LINKEDID_END even if we aren't
646          * reporting on CHANNEL_START so we can track when to send LINKEDID_END */
647         if (ast_cel_track_event(AST_CEL_LINKEDID_END) && event_type == AST_CEL_CHANNEL_START && linkedid) {
648                 if (cel_linkedid_ref(linkedid)) {
649                         return -1;
650                 }
651         }
652
653         if (!ast_cel_track_event(event_type)) {
654                 return 0;
655         }
656
657         if ((event_type == AST_CEL_APP_START || event_type == AST_CEL_APP_END)
658                 && !cel_track_app(snapshot->appl)) {
659                 return 0;
660         }
661
662         ev = ast_cel_create_event(snapshot, event_type, userdefevname, extra);
663         if (!ev) {
664                 return -1;
665         }
666
667         /* Distribute event to backends */
668         ao2_callback(cel_backends, OBJ_MULTIPLE | OBJ_NODATA, cel_backend_send_cb, ev);
669         ast_event_destroy(ev);
670
671         return 0;
672 }
673
674 /* called whenever a channel is destroyed or a linkedid is changed to
675  * potentially emit a CEL_LINKEDID_END event */
676 static void check_retire_linkedid(struct ast_channel_snapshot *snapshot)
677 {
678         char *lid;
679
680         /* make sure we need to do all this work */
681
682         if (ast_strlen_zero(snapshot->linkedid) || !ast_cel_track_event(AST_CEL_LINKEDID_END)) {
683                 return;
684         }
685
686         if (!(lid = ao2_find(linkedids, (void *) snapshot->linkedid, OBJ_POINTER))) {
687                 ast_log(LOG_ERROR, "Something weird happened, couldn't find linkedid %s\n", snapshot->linkedid);
688                 return;
689         }
690
691         /* We have a ref for each channel with this linkedid, the link and the above find, so if
692          * before unreffing the channel we have a refcount of 3, we're done. Unlink and report. */
693         if (ao2_ref(lid, -1) == 3) {
694                 ast_str_container_remove(linkedids, lid);
695                 cel_report_event(snapshot, AST_CEL_LINKEDID_END, NULL, NULL);
696         }
697         ao2_ref(lid, -1);
698 }
699
700 /* Note that no 'chan_fixup' function is provided for this datastore type,
701  * because the channels that will use it will never be involved in masquerades.
702  */
703 static const struct ast_datastore_info fabricated_channel_datastore = {
704         .type = "CEL fabricated channel",
705         .destroy = ast_free_ptr,
706 };
707
708 struct ast_channel *ast_cel_fabricate_channel_from_event(const struct ast_event *event)
709 {
710         struct varshead *headp;
711         struct ast_var_t *newvariable;
712         const char *mixed_name;
713         char timebuf[30];
714         struct ast_channel *tchan;
715         struct ast_cel_event_record record = {
716                 .version = AST_CEL_EVENT_RECORD_VERSION,
717         };
718         struct ast_datastore *datastore;
719         char *app_data;
720         RAII_VAR(struct cel_config *, cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
721
722         if (!cfg || !cfg->general) {
723                 return NULL;
724         }
725
726         /* do not call ast_channel_alloc because this is not really a real channel */
727         if (!(tchan = ast_dummy_channel_alloc())) {
728                 return NULL;
729         }
730
731         headp = ast_channel_varshead(tchan);
732
733         /* first, get the variables from the event */
734         if (ast_cel_fill_record(event, &record)) {
735                 ast_channel_unref(tchan);
736                 return NULL;
737         }
738
739         /* next, fill the channel with their data */
740         mixed_name = (record.event_type == AST_CEL_USER_DEFINED)
741                 ? record.user_defined_name : record.event_name;
742         if ((newvariable = ast_var_assign("eventtype", mixed_name))) {
743                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
744         }
745
746         if (ast_strlen_zero(cfg->general->date_format)) {
747                 snprintf(timebuf, sizeof(timebuf), "%ld.%06ld", (long) record.event_time.tv_sec,
748                                 (long) record.event_time.tv_usec);
749         } else {
750                 struct ast_tm tm;
751                 ast_localtime(&record.event_time, &tm, NULL);
752                 ast_strftime(timebuf, sizeof(timebuf), cfg->general->date_format, &tm);
753         }
754
755         if ((newvariable = ast_var_assign("eventtime", timebuf))) {
756                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
757         }
758
759         if ((newvariable = ast_var_assign("eventenum", record.event_name))) {
760                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
761         }
762         if ((newvariable = ast_var_assign("userdeftype", record.user_defined_name))) {
763                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
764         }
765         if ((newvariable = ast_var_assign("eventextra", record.extra))) {
766                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
767         }
768
769         ast_channel_caller(tchan)->id.name.valid = 1;
770         ast_channel_caller(tchan)->id.name.str = ast_strdup(record.caller_id_name);
771         ast_channel_caller(tchan)->id.number.valid = 1;
772         ast_channel_caller(tchan)->id.number.str = ast_strdup(record.caller_id_num);
773         ast_channel_caller(tchan)->ani.number.valid = 1;
774         ast_channel_caller(tchan)->ani.number.str = ast_strdup(record.caller_id_ani);
775         ast_channel_redirecting(tchan)->from.number.valid = 1;
776         ast_channel_redirecting(tchan)->from.number.str = ast_strdup(record.caller_id_rdnis);
777         ast_channel_dialed(tchan)->number.str = ast_strdup(record.caller_id_dnid);
778
779         ast_channel_exten_set(tchan, record.extension);
780         ast_channel_context_set(tchan, record.context);
781         ast_channel_name_set(tchan, record.channel_name);
782         ast_channel_uniqueid_set(tchan, record.unique_id);
783         ast_channel_linkedid_set(tchan, record.linked_id);
784         ast_channel_accountcode_set(tchan, record.account_code);
785         ast_channel_peeraccount_set(tchan, record.peer_account);
786         ast_channel_userfield_set(tchan, record.user_field);
787
788         if ((newvariable = ast_var_assign("BRIDGEPEER", record.peer))) {
789                 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
790         }
791
792         ast_channel_amaflags_set(tchan, record.amaflag);
793
794         /* We need to store an 'application name' and 'application
795          * data' on the channel for logging purposes, but the channel
796          * structure only provides a place to store pointers, and it
797          * expects these pointers to be pointing to data that does not
798          * need to be freed. This means that the channel's destructor
799          * does not attempt to free any storage that these pointers
800          * point to. However, we can't provide data in that form directly for
801          * these structure members. In order to ensure that these data
802          * elements have a lifetime that matches the channel's
803          * lifetime, we'll put them in a datastore attached to the
804          * channel, and set's the channel's pointers to point into the
805          * datastore.  The datastore will then be automatically destroyed
806          * when the channel is destroyed.
807          */
808
809         if (!(datastore = ast_datastore_alloc(&fabricated_channel_datastore, NULL))) {
810                 ast_channel_unref(tchan);
811                 return NULL;
812         }
813
814         if (!(app_data = ast_malloc(strlen(record.application_name) + strlen(record.application_data) + 2))) {
815                 ast_datastore_free(datastore);
816                 ast_channel_unref(tchan);
817                 return NULL;
818         }
819
820         ast_channel_appl_set(tchan, strcpy(app_data, record.application_name));
821         ast_channel_data_set(tchan, strcpy(app_data + strlen(record.application_name) + 1,
822                 record.application_data));
823
824         datastore->data = app_data;
825         ast_channel_datastore_add(tchan, datastore);
826
827         return tchan;
828 }
829
830 static int cel_linkedid_ref(const char *linkedid)
831 {
832         char *lid;
833
834         if (ast_strlen_zero(linkedid)) {
835                 ast_log(LOG_ERROR, "The linkedid should never be empty\n");
836                 return -1;
837         }
838
839         if (!(lid = ao2_find(linkedids, (void *) linkedid, OBJ_POINTER))) {
840                 if (!(lid = ao2_alloc(strlen(linkedid) + 1, NULL))) {
841                         return -1;
842                 }
843                 strcpy(lid, linkedid);
844                 if (!ao2_link(linkedids, lid)) {
845                         ao2_ref(lid, -1);
846                         return -1;
847                 }
848                 /* Leave both the link and the alloc refs to show a count of 1 + the link */
849         }
850         /* If we've found, go ahead and keep the ref to increment count of how many channels
851          * have this linkedid. We'll clean it up in check_retire */
852         return 0;
853 }
854
855 int ast_cel_fill_record(const struct ast_event *e, struct ast_cel_event_record *r)
856 {
857         if (r->version != AST_CEL_EVENT_RECORD_VERSION) {
858                 ast_log(LOG_ERROR, "Module ABI mismatch for ast_cel_event_record.  "
859                                 "Please ensure all modules were compiled for "
860                                 "this version of Asterisk.\n");
861                 return -1;
862         }
863
864         r->event_type = ast_event_get_ie_uint(e, AST_EVENT_IE_CEL_EVENT_TYPE);
865
866         r->event_time.tv_sec = ast_event_get_ie_uint(e, AST_EVENT_IE_CEL_EVENT_TIME);
867         r->event_time.tv_usec = ast_event_get_ie_uint(e, AST_EVENT_IE_CEL_EVENT_TIME_USEC);
868
869         r->event_name = ast_cel_get_type_name(r->event_type);
870         if (r->event_type == AST_CEL_USER_DEFINED) {
871                 r->user_defined_name = ast_event_get_ie_str(e, AST_EVENT_IE_CEL_USEREVENT_NAME);
872         } else {
873                 r->user_defined_name = "";
874         }
875
876         r->caller_id_name   = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CIDNAME), "");
877         r->caller_id_num    = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CIDNUM), "");
878         r->caller_id_ani    = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CIDANI), "");
879         r->caller_id_rdnis  = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CIDRDNIS), "");
880         r->caller_id_dnid   = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CIDDNID), "");
881         r->extension        = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_EXTEN), "");
882         r->context          = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CONTEXT), "");
883         r->channel_name     = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_CHANNAME), "");
884         r->application_name = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_APPNAME), "");
885         r->application_data = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_APPDATA), "");
886         r->account_code     = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_ACCTCODE), "");
887         r->peer_account     = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_ACCTCODE), "");
888         r->unique_id        = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_UNIQUEID), "");
889         r->linked_id        = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_LINKEDID), "");
890         r->amaflag          = ast_event_get_ie_uint(e, AST_EVENT_IE_CEL_AMAFLAGS);
891         r->user_field       = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_USERFIELD), "");
892         r->peer             = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_PEER), "");
893         r->extra            = S_OR(ast_event_get_ie_str(e, AST_EVENT_IE_CEL_EXTRA), "");
894
895         return 0;
896 }
897
898 /*! \brief Typedef for callbacks that get called on channel snapshot updates */
899 typedef void (*cel_channel_snapshot_monitor)(
900         struct ast_channel_snapshot *old_snapshot,
901         struct ast_channel_snapshot *new_snapshot);
902
903 static struct ast_multi_channel_blob *get_dialstatus_blob(const char *uniqueid)
904 {
905         return ao2_find(cel_dialstatus_store, uniqueid, OBJ_KEY | OBJ_UNLINK);
906 }
907
908 static const char *get_blob_variable(struct ast_multi_channel_blob *blob, const char *varname)
909 {
910         struct ast_json *json = ast_multi_channel_blob_get_json(blob);
911         if (!json) {
912                 return NULL;
913         }
914
915         json = ast_json_object_get(json, varname);
916         if (!json) {
917                 return NULL;
918         }
919
920         return ast_json_string_get(json);
921 }
922
923 /*! \brief Handle channel state changes */
924 static void cel_channel_state_change(
925         struct ast_channel_snapshot *old_snapshot,
926         struct ast_channel_snapshot *new_snapshot)
927 {
928         int is_hungup, was_hungup;
929
930         if (!new_snapshot) {
931                 cel_report_event(old_snapshot, AST_CEL_CHANNEL_END, NULL, NULL);
932                 check_retire_linkedid(old_snapshot);
933                 return;
934         }
935
936         if (!old_snapshot) {
937                 cel_report_event(new_snapshot, AST_CEL_CHANNEL_START, NULL, NULL);
938                 return;
939         }
940
941         was_hungup = ast_test_flag(&old_snapshot->flags, AST_FLAG_DEAD) ? 1 : 0;
942         is_hungup = ast_test_flag(&new_snapshot->flags, AST_FLAG_DEAD) ? 1 : 0;
943
944         if (!was_hungup && is_hungup) {
945                 RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
946                 RAII_VAR(struct ast_multi_channel_blob *, blob, get_dialstatus_blob(new_snapshot->uniqueid), ao2_cleanup);
947                 const char *dialstatus = "";
948                 if (blob && !ast_strlen_zero(get_blob_variable(blob, "dialstatus"))) {
949                         dialstatus = get_blob_variable(blob, "dialstatus");
950                 }
951                 extra = ast_json_pack("{s: i, s: s, s: s}",
952                         "hangupcause", new_snapshot->hangupcause,
953                         "hangupsource", new_snapshot->hangupsource,
954                         "dialstatus", dialstatus);
955                 cel_report_event(new_snapshot, AST_CEL_HANGUP, NULL, extra);
956                 return;
957         }
958
959         if (old_snapshot->state != new_snapshot->state && new_snapshot->state == AST_STATE_UP) {
960                 cel_report_event(new_snapshot, AST_CEL_ANSWER, NULL, NULL);
961                 return;
962         }
963 }
964
965 static void cel_channel_linkedid_change(
966         struct ast_channel_snapshot *old_snapshot,
967         struct ast_channel_snapshot *new_snapshot)
968 {
969         if (!old_snapshot || !new_snapshot) {
970                 return;
971         }
972
973         ast_assert(!ast_strlen_zero(new_snapshot->linkedid));
974         ast_assert(!ast_strlen_zero(old_snapshot->linkedid));
975
976         if (strcmp(old_snapshot->linkedid, new_snapshot->linkedid)) {
977                 cel_linkedid_ref(new_snapshot->linkedid);
978                 check_retire_linkedid(old_snapshot);
979         }
980 }
981
982 static void cel_channel_app_change(
983         struct ast_channel_snapshot *old_snapshot,
984         struct ast_channel_snapshot *new_snapshot)
985 {
986         if (new_snapshot && old_snapshot
987                 && !strcmp(old_snapshot->appl, new_snapshot->appl)) {
988                 return;
989         }
990
991         /* old snapshot has an application, end it */
992         if (old_snapshot && !ast_strlen_zero(old_snapshot->appl)) {
993                 cel_report_event(old_snapshot, AST_CEL_APP_END, NULL, NULL);
994         }
995
996         /* new snapshot has an application, start it */
997         if (new_snapshot && !ast_strlen_zero(new_snapshot->appl)) {
998                 cel_report_event(new_snapshot, AST_CEL_APP_START, NULL, NULL);
999         }
1000 }
1001
1002 /* \brief Handlers for channel snapshot changes.
1003  * \note Order of the handlers matters. Application changes must come before state
1004  * changes to ensure that hangup notifications occur after application changes.
1005  * Linkedid checking should always come last.
1006  */
1007 cel_channel_snapshot_monitor cel_channel_monitors[] = {
1008         cel_channel_app_change,
1009         cel_channel_state_change,
1010         cel_channel_linkedid_change,
1011 };
1012
1013 static int cel_filter_channel_snapshot(struct ast_channel_snapshot *snapshot)
1014 {
1015         if (!snapshot) {
1016                 return 0;
1017         }
1018         return snapshot->tech_properties & AST_CHAN_TP_INTERNAL;
1019 }
1020
1021 static void cel_snapshot_update_cb(void *data, struct stasis_subscription *sub,
1022         struct stasis_topic *topic,
1023         struct stasis_message *message)
1024 {
1025         struct stasis_cache_update *update = stasis_message_data(message);
1026         if (ast_channel_snapshot_type() == update->type) {
1027                 struct ast_channel_snapshot *old_snapshot;
1028                 struct ast_channel_snapshot *new_snapshot;
1029                 size_t i;
1030
1031                 old_snapshot = stasis_message_data(update->old_snapshot);
1032                 new_snapshot = stasis_message_data(update->new_snapshot);
1033
1034                 if (cel_filter_channel_snapshot(old_snapshot) || cel_filter_channel_snapshot(new_snapshot)) {
1035                         return;
1036                 }
1037
1038                 for (i = 0; i < ARRAY_LEN(cel_channel_monitors); ++i) {
1039                         cel_channel_monitors[i](old_snapshot, new_snapshot);
1040                 }
1041         }
1042 }
1043
1044 static void cel_bridge_enter_cb(
1045         void *data, struct stasis_subscription *sub,
1046         struct stasis_topic *topic,
1047         struct stasis_message *message)
1048 {
1049         struct ast_bridge_blob *blob = stasis_message_data(message);
1050         struct ast_bridge_snapshot *snapshot = blob->bridge;
1051         struct ast_channel_snapshot *chan_snapshot = blob->channel;
1052         RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1053
1054         if (cel_filter_channel_snapshot(chan_snapshot)) {
1055                 return;
1056         }
1057
1058         extra = ast_json_pack("{s: s}", "bridge_id", snapshot->uniqueid);
1059         if (!extra) {
1060                 return;
1061         }
1062
1063         cel_report_event(chan_snapshot, AST_CEL_BRIDGE_ENTER, NULL, extra);
1064 }
1065
1066 static void cel_bridge_leave_cb(
1067         void *data, struct stasis_subscription *sub,
1068         struct stasis_topic *topic,
1069         struct stasis_message *message)
1070 {
1071         struct ast_bridge_blob *blob = stasis_message_data(message);
1072         struct ast_bridge_snapshot *snapshot = blob->bridge;
1073         struct ast_channel_snapshot *chan_snapshot = blob->channel;
1074         RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1075
1076         if (cel_filter_channel_snapshot(chan_snapshot)) {
1077                 return;
1078         }
1079
1080         extra = ast_json_pack("{s: s}", "bridge_id", snapshot->uniqueid);
1081         if (!extra) {
1082                 return;
1083         }
1084
1085         cel_report_event(chan_snapshot, AST_CEL_BRIDGE_EXIT, NULL, extra);
1086 }
1087
1088 static void cel_parking_cb(
1089         void *data, struct stasis_subscription *sub,
1090         struct stasis_topic *topic,
1091         struct stasis_message *message)
1092 {
1093         struct ast_parked_call_payload *parked_payload = stasis_message_data(message);
1094         RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1095         const char *reason = NULL;
1096
1097         switch (parked_payload->event_type) {
1098         case PARKED_CALL:
1099                 extra = ast_json_pack("{s: s, s: s}",
1100                         "parker_dial_string", parked_payload->parker_dial_string,
1101                         "parking_lot", parked_payload->parkinglot);
1102                 if (extra) {
1103                         cel_report_event(parked_payload->parkee, AST_CEL_PARK_START, NULL, extra);
1104                 }
1105                 return;
1106         case PARKED_CALL_TIMEOUT:
1107                 reason = "ParkedCallTimeOut";
1108                 break;
1109         case PARKED_CALL_GIVEUP:
1110                 reason = "ParkedCallGiveUp";
1111                 break;
1112         case PARKED_CALL_UNPARKED:
1113                 reason = "ParkedCallUnparked";
1114                 break;
1115         case PARKED_CALL_FAILED:
1116                 reason = "ParkedCallFailed";
1117                 break;
1118         case PARKED_CALL_SWAP:
1119                 reason = "ParkedCallSwap";
1120                 break;
1121         }
1122
1123         extra = ast_json_pack("{s: s}", "reason", reason);
1124         if (extra) {
1125                 cel_report_event(parked_payload->parkee, AST_CEL_PARK_END, NULL, extra);
1126         }
1127 }
1128
1129 static void save_dialstatus(struct ast_multi_channel_blob *blob)
1130 {
1131         ao2_link(cel_dialstatus_store, blob);
1132 }
1133
1134 static void cel_dial_cb(void *data, struct stasis_subscription *sub,
1135         struct stasis_topic *topic,
1136         struct stasis_message *message)
1137 {
1138         struct ast_multi_channel_blob *blob = stasis_message_data(message);
1139
1140         if (cel_filter_channel_snapshot(ast_multi_channel_blob_get_channel(blob, "caller"))) {
1141                 return;
1142         }
1143
1144         if (!get_caller_uniqueid(blob)) {
1145                 return;
1146         }
1147
1148         if (!ast_strlen_zero(get_blob_variable(blob, "forward"))) {
1149                 struct ast_channel_snapshot *caller = ast_multi_channel_blob_get_channel(blob, "caller");
1150                 RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1151                 if (!caller) {
1152                         return;
1153                 }
1154
1155                 extra = ast_json_pack("{s: s}", "forward", get_blob_variable(blob, "forward"));
1156                 if (extra) {
1157                         cel_report_event(caller, AST_CEL_FORWARD, NULL, extra);
1158                 }
1159         }
1160
1161         if (ast_strlen_zero(get_blob_variable(blob, "dialstatus"))) {
1162                 return;
1163         }
1164
1165         save_dialstatus(blob);
1166 }
1167
1168 static void cel_generic_cb(
1169         void *data, struct stasis_subscription *sub,
1170         struct stasis_topic *topic,
1171         struct stasis_message *message)
1172 {
1173         struct ast_channel_blob *obj = stasis_message_data(message);
1174         int event_type = ast_json_integer_get(ast_json_object_get(obj->blob, "event_type"));
1175         struct ast_json *event_details = ast_json_object_get(obj->blob, "event_details");
1176
1177         switch (event_type) {
1178         case AST_CEL_USER_DEFINED:
1179                 {
1180                         const char *event = ast_json_string_get(ast_json_object_get(event_details, "event"));
1181                         struct ast_json *extra = ast_json_object_get(event_details, "extra");
1182                         cel_report_event(obj->snapshot, event_type, event, extra);
1183                         break;
1184                 }
1185         default:
1186                 ast_log(LOG_ERROR, "Unhandled %s event blob\n", ast_cel_get_type_name(event_type));
1187                 break;
1188         }
1189 }
1190
1191 static void cel_blind_transfer_cb(
1192         void *data, struct stasis_subscription *sub,
1193         struct stasis_topic *topic,
1194         struct stasis_message *message)
1195 {
1196         struct ast_bridge_blob *obj = stasis_message_data(message);
1197         struct ast_channel_snapshot *chan_snapshot = obj->channel;
1198         struct ast_bridge_snapshot *bridge_snapshot = obj->bridge;
1199         struct ast_json *blob = obj->blob;
1200         struct ast_json *json_result = ast_json_object_get(blob, "result");
1201         struct ast_json *json_exten;
1202         struct ast_json *json_context;
1203         RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1204         const char *exten, *context;
1205         enum ast_transfer_result result;
1206
1207         if (!json_result) {
1208                 return;
1209         }
1210
1211         result = ast_json_integer_get(json_result);
1212         if (result != AST_BRIDGE_TRANSFER_SUCCESS) {
1213                 return;
1214         }
1215
1216         json_exten = ast_json_object_get(blob, "exten");
1217         json_context = ast_json_object_get(blob, "context");
1218
1219         if (!json_exten || !json_context) {
1220                 return;
1221         }
1222
1223         exten = ast_json_string_get(json_exten);
1224         context = ast_json_string_get(json_context);
1225         if (!exten || !context) {
1226                 return;
1227         }
1228
1229         extra = ast_json_pack("{s: s, s: s, s: s}",
1230                 "extension", exten,
1231                 "context", context,
1232                 "bridge_id", bridge_snapshot->uniqueid);
1233
1234         if (extra) {
1235                 cel_report_event(chan_snapshot, AST_CEL_BLINDTRANSFER, NULL, extra);
1236         }
1237 }
1238
1239 static void cel_attended_transfer_cb(
1240         void *data, struct stasis_subscription *sub,
1241         struct stasis_topic *topic,
1242         struct stasis_message *message)
1243 {
1244         struct ast_attended_transfer_message *xfer = stasis_message_data(message);
1245         RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1246         struct ast_bridge_snapshot *bridge1, *bridge2;
1247         struct ast_channel_snapshot *channel1, *channel2;
1248
1249         /* Make sure bridge1 is always non-NULL */
1250         if (!xfer->to_transferee.bridge_snapshot) {
1251                 bridge1 = xfer->to_transfer_target.bridge_snapshot;
1252                 bridge2 = xfer->to_transferee.bridge_snapshot;
1253                 channel1 = xfer->to_transfer_target.channel_snapshot;
1254                 channel2 = xfer->to_transferee.channel_snapshot;
1255         } else {
1256                 bridge1 = xfer->to_transferee.bridge_snapshot;
1257                 bridge2 = xfer->to_transfer_target.bridge_snapshot;
1258                 channel1 = xfer->to_transferee.channel_snapshot;
1259                 channel2 = xfer->to_transfer_target.channel_snapshot;
1260         }
1261
1262         switch (xfer->dest_type) {
1263         case AST_ATTENDED_TRANSFER_DEST_FAIL:
1264                 return;
1265                 /* handle these three the same */
1266         case AST_ATTENDED_TRANSFER_DEST_BRIDGE_MERGE:
1267         case AST_ATTENDED_TRANSFER_DEST_LINK:
1268         case AST_ATTENDED_TRANSFER_DEST_THREEWAY:
1269                 extra = ast_json_pack("{s: s, s: s, s: s}",
1270                         "bridge1_id", bridge1->uniqueid,
1271                         "channel2_name", channel2->name,
1272                         "bridge2_id", bridge2->uniqueid);
1273
1274                 if (!extra) {
1275                         return;
1276                 }
1277                 break;
1278         case AST_ATTENDED_TRANSFER_DEST_APP:
1279                 extra = ast_json_pack("{s: s, s: s, s: s}",
1280                         "bridge1_id", bridge1->uniqueid,
1281                         "channel2_name", channel2->name,
1282                         "app", xfer->dest.app);
1283
1284                 if (!extra) {
1285                         return;
1286                 }
1287                 break;
1288         }
1289         cel_report_event(channel1, AST_CEL_ATTENDEDTRANSFER, NULL, extra);
1290 }
1291
1292 static void cel_pickup_cb(
1293         void *data, struct stasis_subscription *sub,
1294         struct stasis_topic *topic,
1295         struct stasis_message *message)
1296 {
1297         struct ast_multi_channel_blob *obj = stasis_message_data(message);
1298         struct ast_channel_snapshot *channel = ast_multi_channel_blob_get_channel(obj, "channel");
1299         struct ast_channel_snapshot *target = ast_multi_channel_blob_get_channel(obj, "target");
1300         RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1301
1302         if (!channel || !target) {
1303                 return;
1304         }
1305
1306         extra = ast_json_pack("{s: s}", "pickup_channel", channel->name);
1307         if (!extra) {
1308                 return;
1309         }
1310
1311         cel_report_event(target, AST_CEL_PICKUP, NULL, extra);
1312 }
1313
1314 static void cel_local_cb(
1315         void *data, struct stasis_subscription *sub,
1316         struct stasis_topic *topic,
1317         struct stasis_message *message)
1318 {
1319         struct ast_multi_channel_blob *obj = stasis_message_data(message);
1320         struct ast_channel_snapshot *localone = ast_multi_channel_blob_get_channel(obj, "1");
1321         struct ast_channel_snapshot *localtwo = ast_multi_channel_blob_get_channel(obj, "2");
1322         RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1323
1324         if (!localone || !localtwo) {
1325                 return;
1326         }
1327
1328         extra = ast_json_pack("{s: s}", "local_two", localtwo->name);
1329         if (!extra) {
1330                 return;
1331         }
1332
1333         cel_report_event(localone, AST_CEL_LOCAL_OPTIMIZE, NULL, extra);
1334 }
1335
1336 static void ast_cel_engine_term(void)
1337 {
1338         aco_info_destroy(&cel_cfg_info);
1339         ao2_global_obj_release(cel_configs);
1340         stasis_message_router_unsubscribe_and_join(cel_state_router);
1341         cel_state_router = NULL;
1342         ao2_cleanup(cel_aggregation_topic);
1343         cel_aggregation_topic = NULL;
1344         ao2_cleanup(cel_topic);
1345         cel_topic = NULL;
1346         cel_channel_forwarder = stasis_unsubscribe_and_join(cel_channel_forwarder);
1347         cel_bridge_forwarder = stasis_unsubscribe_and_join(cel_bridge_forwarder);
1348         cel_parking_forwarder = stasis_unsubscribe_and_join(cel_parking_forwarder);
1349         cel_cel_forwarder = stasis_unsubscribe_and_join(cel_cel_forwarder);
1350         ast_cli_unregister(&cli_status);
1351         ao2_cleanup(cel_dialstatus_store);
1352         cel_dialstatus_store = NULL;
1353         ao2_cleanup(linkedids);
1354         linkedids = NULL;
1355         STASIS_MESSAGE_TYPE_CLEANUP(cel_generic_type);
1356 }
1357
1358 int ast_cel_engine_init(void)
1359 {
1360         int ret = 0;
1361         if (!(linkedids = ast_str_container_alloc(NUM_APP_BUCKETS))) {
1362                 return -1;
1363         }
1364
1365         if (!(cel_dialstatus_store = ao2_container_alloc(NUM_DIALSTATUS_BUCKETS, dialstatus_hash, dialstatus_cmp))) {
1366                 return -1;
1367         }
1368
1369         if (STASIS_MESSAGE_TYPE_INIT(cel_generic_type)) {
1370                 return -1;
1371         }
1372
1373         if (ast_cli_register(&cli_status)) {
1374                 return -1;
1375         }
1376
1377         cel_backends = ao2_container_alloc(BACKEND_BUCKETS, cel_backend_hash, cel_backend_cmp);
1378         if (!cel_backends) {
1379                 return -1;
1380         }
1381
1382         cel_aggregation_topic = stasis_topic_create("cel_aggregation_topic");
1383         if (!cel_aggregation_topic) {
1384                 return -1;
1385         }
1386
1387         cel_topic = stasis_topic_create("cel_topic");
1388         if (!cel_topic) {
1389                 return -1;
1390         }
1391
1392         cel_channel_forwarder = stasis_forward_all(
1393                 ast_channel_topic_all_cached(),
1394                 cel_aggregation_topic);
1395         if (!cel_channel_forwarder) {
1396                 return -1;
1397         }
1398
1399         cel_bridge_forwarder = stasis_forward_all(
1400                 ast_bridge_topic_all_cached(),
1401                 cel_aggregation_topic);
1402         if (!cel_bridge_forwarder) {
1403                 return -1;
1404         }
1405
1406         cel_parking_forwarder = stasis_forward_all(
1407                 ast_parking_topic(),
1408                 cel_aggregation_topic);
1409         if (!cel_parking_forwarder) {
1410                 return -1;
1411         }
1412
1413         cel_cel_forwarder = stasis_forward_all(
1414                 ast_cel_topic(),
1415                 cel_aggregation_topic);
1416         if (!cel_cel_forwarder) {
1417                 return -1;
1418         }
1419
1420         cel_state_router = stasis_message_router_create(cel_aggregation_topic);
1421         if (!cel_state_router) {
1422                 return -1;
1423         }
1424
1425         ret |= stasis_message_router_add(cel_state_router,
1426                 stasis_cache_update_type(),
1427                 cel_snapshot_update_cb,
1428                 NULL);
1429
1430         ret |= stasis_message_router_add(cel_state_router,
1431                 ast_channel_dial_type(),
1432                 cel_dial_cb,
1433                 NULL);
1434
1435         ret |= stasis_message_router_add(cel_state_router,
1436                 ast_channel_entered_bridge_type(),
1437                 cel_bridge_enter_cb,
1438                 NULL);
1439
1440         ret |= stasis_message_router_add(cel_state_router,
1441                 ast_channel_left_bridge_type(),
1442                 cel_bridge_leave_cb,
1443                 NULL);
1444
1445         ret |= stasis_message_router_add(cel_state_router,
1446                 ast_parked_call_type(),
1447                 cel_parking_cb,
1448                 NULL);
1449
1450         ret |= stasis_message_router_add(cel_state_router,
1451                 cel_generic_type(),
1452                 cel_generic_cb,
1453                 NULL);
1454
1455         ret |= stasis_message_router_add(cel_state_router,
1456                 ast_blind_transfer_type(),
1457                 cel_blind_transfer_cb,
1458                 NULL);
1459
1460         ret |= stasis_message_router_add(cel_state_router,
1461                 ast_attended_transfer_type(),
1462                 cel_attended_transfer_cb,
1463                 NULL);
1464
1465         ret |= stasis_message_router_add(cel_state_router,
1466                 ast_call_pickup_type(),
1467                 cel_pickup_cb,
1468                 NULL);
1469
1470         ret |= stasis_message_router_add(cel_state_router,
1471                 ast_local_optimization_end_type(),
1472                 cel_local_cb,
1473                 NULL);
1474
1475         /* If somehow we failed to add any routes, just shut down the whole
1476          * thing and fail it.
1477          */
1478         if (ret) {
1479                 ast_cel_engine_term();
1480                 return -1;
1481         }
1482
1483         if (aco_info_init(&cel_cfg_info)) {
1484                 return -1;
1485         }
1486
1487         aco_option_register(&cel_cfg_info, "enable", ACO_EXACT, general_options, "no", OPT_BOOL_T, 1, FLDSET(struct ast_cel_general_config, enable));
1488         aco_option_register(&cel_cfg_info, "dateformat", ACO_EXACT, general_options, "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_cel_general_config, date_format));
1489         aco_option_register_custom(&cel_cfg_info, "apps", ACO_EXACT, general_options, "", apps_handler, 0);
1490         aco_option_register_custom(&cel_cfg_info, "events", ACO_EXACT, general_options, "", events_handler, 0);
1491
1492         if (aco_process_config(&cel_cfg_info, 0)) {
1493                 RAII_VAR(struct cel_config *, cel_cfg, cel_config_alloc(), ao2_cleanup);
1494
1495                 if (!cel_cfg) {
1496                         return -1;
1497                 }
1498
1499                 /* If we couldn't process the configuration and this wasn't a reload,
1500                  * create a default config
1501                  */
1502                 if (!aco_set_defaults(&general_option, "general", cel_cfg->general)) {
1503                         ast_log(LOG_NOTICE, "Failed to process CEL configuration; using defaults\n");
1504                         ao2_global_obj_replace(cel_configs, cel_cfg);
1505                 }
1506         }
1507
1508         ast_register_cleanup(ast_cel_engine_term);
1509
1510         return 0;
1511 }
1512
1513 int ast_cel_engine_reload(void)
1514 {
1515         return do_reload();
1516 }
1517
1518 void ast_cel_publish_event(struct ast_channel *chan,
1519         enum ast_cel_event_type event_type,
1520         struct ast_json *blob)
1521 {
1522         RAII_VAR(struct ast_channel_blob *, obj, NULL, ao2_cleanup);
1523         RAII_VAR(struct ast_json *, cel_blob, NULL, ast_json_unref);
1524         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
1525         cel_blob = ast_json_pack("{s: i, s: O}",
1526                 "event_type", event_type,
1527                 "event_details", blob);
1528
1529         message = ast_channel_blob_create(chan, cel_generic_type(), cel_blob);
1530         if (message) {
1531                 stasis_publish(ast_cel_topic(), message);
1532         }
1533 }
1534
1535 struct stasis_topic *ast_cel_topic(void)
1536 {
1537         return cel_topic;
1538 }
1539
1540 struct ast_cel_general_config *ast_cel_get_config(void)
1541 {
1542         RAII_VAR(struct cel_config *, mod_cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
1543
1544         if (!mod_cfg || !mod_cfg->general) {
1545                 return NULL;
1546         }
1547
1548         ao2_ref(mod_cfg->general, +1);
1549         return mod_cfg->general;
1550 }
1551
1552 void ast_cel_set_config(struct ast_cel_general_config *config)
1553 {
1554         RAII_VAR(struct cel_config *, mod_cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
1555         RAII_VAR(struct ast_cel_general_config *, cleanup_config, mod_cfg->general, ao2_cleanup);
1556
1557         if (mod_cfg) {
1558                 mod_cfg->general = config;
1559                 if (mod_cfg->general) {
1560                         ao2_ref(mod_cfg->general, +1);
1561                 }
1562         }
1563 }
1564
1565 int ast_cel_backend_unregister(const char *name)
1566 {
1567         RAII_VAR(struct cel_backend *, backend, NULL, ao2_cleanup);
1568
1569         backend = ao2_find(cel_backends, name, OBJ_KEY | OBJ_UNLINK);
1570         if (!backend) {
1571                 return -1;
1572         }
1573
1574         return 0;
1575 }
1576
1577 int ast_cel_backend_register(const char *name, ast_cel_backend_cb backend_callback)
1578 {
1579         RAII_VAR(struct cel_backend *, backend, NULL, ao2_cleanup);
1580
1581         if (ast_strlen_zero(name)) {
1582                 return -1;
1583         }
1584
1585         backend = ao2_alloc(sizeof(*backend) + 1 + strlen(name), NULL);
1586         if (!backend) {
1587                 return -1;
1588         }
1589
1590         /* safe strcpy */
1591         strcpy(backend->name, name);
1592         backend->callback = backend_callback;
1593         ao2_link(cel_backends, backend);
1594
1595         return 0;
1596 }