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