Merge "rtp_engine: rtcp_report_to_json can overflow the ssrc integer value"
[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->exten,
537                 AST_EVENT_IE_CEL_CONTEXT, AST_EVENT_IE_PLTYPE_STR, snapshot->context,
538                 AST_EVENT_IE_CEL_CHANNAME, AST_EVENT_IE_PLTYPE_STR, snapshot->name,
539                 AST_EVENT_IE_CEL_APPNAME, AST_EVENT_IE_PLTYPE_STR, snapshot->appl,
540                 AST_EVENT_IE_CEL_APPDATA, AST_EVENT_IE_PLTYPE_STR, snapshot->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->accountcode,
543                 AST_EVENT_IE_CEL_PEERACCT, AST_EVENT_IE_PLTYPE_STR, snapshot->peeraccount,
544                 AST_EVENT_IE_CEL_UNIQUEID, AST_EVENT_IE_PLTYPE_STR, snapshot->uniqueid,
545                 AST_EVENT_IE_CEL_LINKEDID, AST_EVENT_IE_PLTYPE_STR, snapshot->linkedid,
546                 AST_EVENT_IE_CEL_USERFIELD, AST_EVENT_IE_PLTYPE_STR, snapshot->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->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->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->linkedid)) {
610                 /* The CEL module is shutdown.  Abort. */
611                 return;
612         }
613
614         ao2_lock(linkedids);
615
616         lid = ao2_find(linkedids, (void *) snapshot->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->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 (!new_snapshot) {
892                 cel_report_event(old_snapshot, AST_CEL_CHANNEL_END, NULL, NULL, NULL);
893                 if (ast_cel_track_event(AST_CEL_LINKEDID_END)) {
894                         check_retire_linkedid(old_snapshot);
895                 }
896                 return;
897         }
898
899         if (!old_snapshot) {
900                 cel_report_event(new_snapshot, AST_CEL_CHANNEL_START, NULL, NULL, NULL);
901                 return;
902         }
903
904         was_hungup = ast_test_flag(&old_snapshot->flags, AST_FLAG_DEAD) ? 1 : 0;
905         is_hungup = ast_test_flag(&new_snapshot->flags, AST_FLAG_DEAD) ? 1 : 0;
906
907         if (!was_hungup && is_hungup) {
908                 struct ast_json *extra;
909                 struct cel_dialstatus *dialstatus = get_dialstatus(new_snapshot->uniqueid);
910
911                 extra = ast_json_pack("{s: i, s: s, s: s}",
912                         "hangupcause", new_snapshot->hangupcause,
913                         "hangupsource", new_snapshot->hangupsource,
914                         "dialstatus", dialstatus ? dialstatus->dialstatus : "");
915                 cel_report_event(new_snapshot, AST_CEL_HANGUP, NULL, extra, NULL);
916                 ast_json_unref(extra);
917                 ao2_cleanup(dialstatus);
918                 return;
919         }
920
921         if (old_snapshot->state != new_snapshot->state && new_snapshot->state == AST_STATE_UP) {
922                 cel_report_event(new_snapshot, AST_CEL_ANSWER, NULL, NULL, NULL);
923                 return;
924         }
925 }
926
927 static void cel_channel_linkedid_change(
928         struct ast_channel_snapshot *old_snapshot,
929         struct ast_channel_snapshot *new_snapshot)
930 {
931         if (!old_snapshot || !new_snapshot) {
932                 return;
933         }
934
935         ast_assert(!ast_strlen_zero(new_snapshot->linkedid));
936         ast_assert(!ast_strlen_zero(old_snapshot->linkedid));
937
938         if (ast_cel_track_event(AST_CEL_LINKEDID_END)
939                 && strcmp(old_snapshot->linkedid, new_snapshot->linkedid)) {
940                 cel_linkedid_ref(new_snapshot->linkedid);
941                 check_retire_linkedid(old_snapshot);
942         }
943 }
944
945 static void cel_channel_app_change(
946         struct ast_channel_snapshot *old_snapshot,
947         struct ast_channel_snapshot *new_snapshot)
948 {
949         if (new_snapshot && old_snapshot
950                 && !strcmp(old_snapshot->appl, new_snapshot->appl)) {
951                 return;
952         }
953
954         /* old snapshot has an application, end it */
955         if (old_snapshot && !ast_strlen_zero(old_snapshot->appl)) {
956                 cel_report_event(old_snapshot, AST_CEL_APP_END, NULL, NULL, NULL);
957         }
958
959         /* new snapshot has an application, start it */
960         if (new_snapshot && !ast_strlen_zero(new_snapshot->appl)) {
961                 cel_report_event(new_snapshot, AST_CEL_APP_START, NULL, NULL, NULL);
962         }
963 }
964
965 /* \brief Handlers for channel snapshot changes.
966  * \note Order of the handlers matters. Application changes must come before state
967  * changes to ensure that hangup notifications occur after application changes.
968  * Linkedid checking should always come last.
969  */
970 cel_channel_snapshot_monitor cel_channel_monitors[] = {
971         cel_channel_app_change,
972         cel_channel_state_change,
973         cel_channel_linkedid_change,
974 };
975
976 static int cel_filter_channel_snapshot(struct ast_channel_snapshot *snapshot)
977 {
978         if (!snapshot) {
979                 return 0;
980         }
981         return snapshot->tech_properties & AST_CHAN_TP_INTERNAL;
982 }
983
984 static void cel_snapshot_update_cb(void *data, struct stasis_subscription *sub,
985         struct stasis_message *message)
986 {
987         struct stasis_cache_update *update = stasis_message_data(message);
988         if (ast_channel_snapshot_type() == update->type) {
989                 struct ast_channel_snapshot *old_snapshot;
990                 struct ast_channel_snapshot *new_snapshot;
991                 size_t i;
992
993                 old_snapshot = stasis_message_data(update->old_snapshot);
994                 new_snapshot = stasis_message_data(update->new_snapshot);
995
996                 if (cel_filter_channel_snapshot(old_snapshot) || cel_filter_channel_snapshot(new_snapshot)) {
997                         return;
998                 }
999
1000                 for (i = 0; i < ARRAY_LEN(cel_channel_monitors); ++i) {
1001                         cel_channel_monitors[i](old_snapshot, new_snapshot);
1002                 }
1003         }
1004 }
1005
1006 static struct ast_str *cel_generate_peer_str(
1007         struct ast_bridge_snapshot *bridge,
1008         struct ast_channel_snapshot *chan)
1009 {
1010         struct ast_str *peer_str = ast_str_create(32);
1011         struct ao2_iterator i;
1012         char *current_chan = NULL;
1013
1014         if (!peer_str) {
1015                 return NULL;
1016         }
1017
1018         for (i = ao2_iterator_init(bridge->channels, 0);
1019                 (current_chan = ao2_iterator_next(&i));
1020                 ao2_cleanup(current_chan)) {
1021                 struct ast_channel_snapshot *current_snapshot;
1022
1023                 /* Don't add the channel for which this message is being generated */
1024                 if (!strcmp(current_chan, chan->uniqueid)) {
1025                         continue;
1026                 }
1027
1028                 current_snapshot = ast_channel_snapshot_get_latest(current_chan);
1029                 if (!current_snapshot) {
1030                         continue;
1031                 }
1032
1033                 ast_str_append(&peer_str, 0, "%s,", current_snapshot->name);
1034                 ao2_cleanup(current_snapshot);
1035         }
1036         ao2_iterator_destroy(&i);
1037
1038         /* Rip off the trailing comma */
1039         ast_str_truncate(peer_str, -1);
1040
1041         return peer_str;
1042 }
1043
1044 static void cel_bridge_enter_cb(
1045         void *data, struct stasis_subscription *sub,
1046         struct stasis_message *message)
1047 {
1048         struct ast_bridge_blob *blob = stasis_message_data(message);
1049         struct ast_bridge_snapshot *snapshot = blob->bridge;
1050         struct ast_channel_snapshot *chan_snapshot = blob->channel;
1051         RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1052         RAII_VAR(struct ast_str *, peer_str, NULL, ast_free);
1053
1054         if (cel_filter_channel_snapshot(chan_snapshot)) {
1055                 return;
1056         }
1057
1058         extra = ast_json_pack("{s: s, s: s}",
1059                 "bridge_id", snapshot->uniqueid,
1060                 "bridge_technology", snapshot->technology);
1061         if (!extra) {
1062                 return;
1063         }
1064
1065         peer_str = cel_generate_peer_str(snapshot, chan_snapshot);
1066         if (!peer_str) {
1067                 return;
1068         }
1069
1070         cel_report_event(chan_snapshot, AST_CEL_BRIDGE_ENTER, NULL, extra, ast_str_buffer(peer_str));
1071 }
1072
1073 static void cel_bridge_leave_cb(
1074         void *data, struct stasis_subscription *sub,
1075         struct stasis_message *message)
1076 {
1077         struct ast_bridge_blob *blob = stasis_message_data(message);
1078         struct ast_bridge_snapshot *snapshot = blob->bridge;
1079         struct ast_channel_snapshot *chan_snapshot = blob->channel;
1080         RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1081         RAII_VAR(struct ast_str *, peer_str, NULL, ast_free);
1082
1083         if (cel_filter_channel_snapshot(chan_snapshot)) {
1084                 return;
1085         }
1086
1087         extra = ast_json_pack("{s: s, s: s}",
1088                 "bridge_id", snapshot->uniqueid,
1089                 "bridge_technology", snapshot->technology);
1090         if (!extra) {
1091                 return;
1092         }
1093
1094         peer_str = cel_generate_peer_str(snapshot, chan_snapshot);
1095         if (!peer_str) {
1096                 return;
1097         }
1098
1099         cel_report_event(chan_snapshot, AST_CEL_BRIDGE_EXIT, NULL, extra, ast_str_buffer(peer_str));
1100 }
1101
1102 static void cel_parking_cb(
1103         void *data, struct stasis_subscription *sub,
1104         struct stasis_message *message)
1105 {
1106         struct ast_parked_call_payload *parked_payload = stasis_message_data(message);
1107         RAII_VAR(struct ast_json *, extra, NULL, ast_json_unref);
1108         const char *reason = NULL;
1109
1110         switch (parked_payload->event_type) {
1111         case PARKED_CALL:
1112                 extra = ast_json_pack("{s: s, s: s}",
1113                         "parker_dial_string", parked_payload->parker_dial_string,
1114                         "parking_lot", parked_payload->parkinglot);
1115                 if (extra) {
1116                         cel_report_event(parked_payload->parkee, AST_CEL_PARK_START, NULL, extra, NULL);
1117                 }
1118                 return;
1119         case PARKED_CALL_TIMEOUT:
1120                 reason = "ParkedCallTimeOut";
1121                 break;
1122         case PARKED_CALL_GIVEUP:
1123                 reason = "ParkedCallGiveUp";
1124                 break;
1125         case PARKED_CALL_UNPARKED:
1126                 reason = "ParkedCallUnparked";
1127                 break;
1128         case PARKED_CALL_FAILED:
1129                 reason = "ParkedCallFailed";
1130                 break;
1131         case PARKED_CALL_SWAP:
1132                 reason = "ParkedCallSwap";
1133                 break;
1134         }
1135
1136         if (parked_payload->retriever) {
1137                 extra = ast_json_pack("{s: s, s: s}",
1138                         "reason", reason ?: "",
1139                         "retriever", parked_payload->retriever->name);
1140         } else {
1141                 extra = ast_json_pack("{s: s}", "reason", reason ?: "");
1142         }
1143
1144         if (extra) {
1145                 cel_report_event(parked_payload->parkee, AST_CEL_PARK_END, NULL, extra, NULL);
1146         }
1147 }
1148
1149 static void save_dialstatus(struct ast_multi_channel_blob *blob, struct ast_channel_snapshot *snapshot)
1150 {
1151         struct ao2_container *dial_statuses = ao2_global_obj_ref(cel_dialstatus_store);
1152         const char *dialstatus_string = get_blob_variable(blob, "dialstatus");
1153         struct cel_dialstatus *dialstatus;
1154         size_t dialstatus_string_len;
1155
1156         if (!dial_statuses || ast_strlen_zero(dialstatus_string)) {
1157                 ao2_cleanup(dial_statuses);
1158                 return;
1159         }
1160
1161         dialstatus = ao2_find(dial_statuses, snapshot->uniqueid, OBJ_SEARCH_KEY);
1162         if (dialstatus) {
1163                 if (!strcasecmp(dialstatus_string, "ANSWER") && strcasecmp(dialstatus->dialstatus, "ANSWER")) {
1164                         /* In the case of an answer after we already have a dial status we give
1165                          * priority to the answer since the call was, well, answered. In the case of
1166                          * failure dial status results we simply let the first failure be the status.
1167                          */
1168                         ao2_unlink(dial_statuses, dialstatus);
1169                         ao2_ref(dialstatus, -1);
1170                 } else {
1171                         ao2_ref(dialstatus, -1);
1172                         ao2_ref(dial_statuses, -1);
1173                         return;
1174                 }
1175         }
1176
1177         dialstatus_string_len = strlen(dialstatus_string) + 1;
1178         dialstatus = ao2_alloc_options(sizeof(*dialstatus) + dialstatus_string_len, NULL,
1179                 AO2_ALLOC_OPT_LOCK_NOLOCK);
1180         if (!dialstatus) {
1181                 ao2_ref(dial_statuses, -1);
1182                 return;
1183         }
1184
1185         ast_copy_string(dialstatus->uniqueid, snapshot->uniqueid, sizeof(dialstatus->uniqueid));
1186         ast_copy_string(dialstatus->dialstatus, dialstatus_string, dialstatus_string_len);
1187
1188         ao2_link(dial_statuses, dialstatus);
1189         ao2_ref(dialstatus, -1);
1190         ao2_ref(dial_statuses, -1);
1191 }
1192
1193 static int is_valid_dialstatus(struct ast_multi_channel_blob *blob)
1194 {
1195         const char *dialstatus = get_blob_variable(blob, "dialstatus");
1196         int res = 0;
1197
1198         if (ast_strlen_zero(dialstatus)) {
1199                 res = 0;
1200         } else if (!strcasecmp(dialstatus, "CHANUNAVAIL")) {
1201                 res = 1;
1202         } else if (!strcasecmp(dialstatus, "CONGESTION")) {
1203                 res = 1;
1204         } else if (!strcasecmp(dialstatus, "NOANSWER")) {
1205                 res = 1;
1206         } else if (!strcasecmp(dialstatus, "BUSY")) {
1207                 res = 1;
1208         } else if (!strcasecmp(dialstatus, "ANSWER")) {
1209                 res = 1;
1210         } else if (!strcasecmp(dialstatus, "CANCEL")) {
1211                 res = 1;
1212         } else if (!strcasecmp(dialstatus, "DONTCALL")) {
1213                 res = 1;
1214         } else if (!strcasecmp(dialstatus, "TORTURE")) {
1215                 res = 1;
1216         } else if (!strcasecmp(dialstatus, "INVALIDARGS")) {
1217                 res = 1;
1218         }
1219         return res;
1220 }
1221
1222 static void cel_dial_cb(void *data, struct stasis_subscription *sub,
1223         struct stasis_message *message)
1224 {
1225         struct ast_multi_channel_blob *blob = stasis_message_data(message);
1226         struct ast_channel_snapshot *snapshot;
1227
1228         snapshot = ast_multi_channel_blob_get_channel(blob, "caller");
1229         if (!snapshot || cel_filter_channel_snapshot(snapshot)) {
1230                 return;
1231         }
1232
1233         if (!ast_strlen_zero(get_blob_variable(blob, "forward"))) {
1234                 struct ast_json *extra;
1235
1236                 extra = ast_json_pack("{s: s}", "forward", get_blob_variable(blob, "forward"));
1237                 if (extra) {
1238                         cel_report_event(snapshot, AST_CEL_FORWARD, NULL, extra, NULL);
1239                         ast_json_unref(extra);
1240                 }
1241         }
1242
1243         if (is_valid_dialstatus(blob)) {
1244                 save_dialstatus(blob, snapshot);
1245         }
1246 }
1247
1248 static void cel_generic_cb(
1249         void *data, struct stasis_subscription *sub,
1250         struct stasis_message *message)
1251 {
1252         struct ast_channel_blob *obj = stasis_message_data(message);
1253         int event_type = ast_json_integer_get(ast_json_object_get(obj->blob, "event_type"));
1254         struct ast_json *event_details = ast_json_object_get(obj->blob, "event_details");
1255
1256         switch (event_type) {
1257         case AST_CEL_USER_DEFINED:
1258                 {
1259                         const char *event = ast_json_string_get(ast_json_object_get(event_details, "event"));
1260                         struct ast_json *extra = ast_json_object_get(event_details, "extra");
1261                         cel_report_event(obj->snapshot, event_type, event, extra, NULL);
1262                         break;
1263                 }
1264         default:
1265                 ast_log(LOG_ERROR, "Unhandled %s event blob\n", ast_cel_get_type_name(event_type));
1266                 break;
1267         }
1268 }
1269
1270 static void cel_blind_transfer_cb(
1271         void *data, struct stasis_subscription *sub,
1272         struct stasis_message *message)
1273 {
1274         struct ast_blind_transfer_message *transfer_msg = stasis_message_data(message);
1275         struct ast_channel_snapshot *chan_snapshot = transfer_msg->transferer;
1276         struct ast_bridge_snapshot *bridge_snapshot = transfer_msg->bridge;
1277         struct ast_json *extra;
1278
1279         if (transfer_msg->result != AST_BRIDGE_TRANSFER_SUCCESS) {
1280                 return;
1281         }
1282
1283         extra = ast_json_pack("{s: s, s: s, s: s, s: s, s: s}",
1284                 "extension", transfer_msg->exten,
1285                 "context", transfer_msg->context,
1286                 "bridge_id", bridge_snapshot->uniqueid,
1287                 "transferee_channel_name", transfer_msg->transferee ? transfer_msg->transferee->name : "N/A",
1288                 "transferee_channel_uniqueid", transfer_msg->transferee ? transfer_msg->transferee->uniqueid  : "N/A");
1289         if (extra) {
1290                 cel_report_event(chan_snapshot, AST_CEL_BLINDTRANSFER, NULL, extra, NULL);
1291                 ast_json_unref(extra);
1292         }
1293 }
1294
1295 static void cel_attended_transfer_cb(
1296         void *data, struct stasis_subscription *sub,
1297         struct stasis_message *message)
1298 {
1299         struct ast_attended_transfer_message *xfer = stasis_message_data(message);
1300         struct ast_json *extra = NULL;
1301         struct ast_bridge_snapshot *bridge1, *bridge2;
1302         struct ast_channel_snapshot *channel1, *channel2;
1303
1304         /* Make sure bridge1 is always non-NULL */
1305         if (!xfer->to_transferee.bridge_snapshot) {
1306                 bridge1 = xfer->to_transfer_target.bridge_snapshot;
1307                 bridge2 = xfer->to_transferee.bridge_snapshot;
1308                 channel1 = xfer->to_transfer_target.channel_snapshot;
1309                 channel2 = xfer->to_transferee.channel_snapshot;
1310         } else {
1311                 bridge1 = xfer->to_transferee.bridge_snapshot;
1312                 bridge2 = xfer->to_transfer_target.bridge_snapshot;
1313                 channel1 = xfer->to_transferee.channel_snapshot;
1314                 channel2 = xfer->to_transfer_target.channel_snapshot;
1315         }
1316
1317         switch (xfer->dest_type) {
1318         case AST_ATTENDED_TRANSFER_DEST_FAIL:
1319                 return;
1320                 /* handle these three the same */
1321         case AST_ATTENDED_TRANSFER_DEST_BRIDGE_MERGE:
1322         case AST_ATTENDED_TRANSFER_DEST_LINK:
1323         case AST_ATTENDED_TRANSFER_DEST_THREEWAY:
1324                 extra = ast_json_pack("{s: s, s: s, s: s, s: s, s: s, s: s, s: s, s: s}",
1325                         "bridge1_id", bridge1->uniqueid,
1326                         "channel2_name", channel2->name,
1327                         "channel2_uniqueid", channel2->uniqueid,
1328                         "bridge2_id", bridge2->uniqueid,
1329                         "transferee_channel_name", xfer->transferee ? xfer->transferee->name : "N/A",
1330                         "transferee_channel_uniqueid", xfer->transferee ? xfer->transferee->uniqueid : "N/A",
1331                         "transfer_target_channel_name", xfer->target ? xfer->target->name : "N/A",
1332                         "transfer_target_channel_uniqueid", xfer->target ? xfer->target->uniqueid : "N/A");
1333                 if (!extra) {
1334                         return;
1335                 }
1336                 break;
1337         case AST_ATTENDED_TRANSFER_DEST_APP:
1338         case AST_ATTENDED_TRANSFER_DEST_LOCAL_APP:
1339                 extra = ast_json_pack("{s: s, s: s, s: s, s: s, s: s, s: s, s: s, s: s}",
1340                         "bridge1_id", bridge1->uniqueid,
1341                         "channel2_name", channel2->name,
1342                         "channel2_uniqueid", channel2->uniqueid,
1343                         "app", xfer->dest.app,
1344                         "transferee_channel_name", xfer->transferee ? xfer->transferee->name : "N/A",
1345                         "transferee_channel_uniqueid", xfer->transferee ? xfer->transferee->uniqueid : "N/A",
1346                         "transfer_target_channel_name", xfer->target ? xfer->target->name : "N/A",
1347                         "transfer_target_channel_uniqueid", xfer->target ? xfer->target->uniqueid : "N/A");
1348                 if (!extra) {
1349                         return;
1350                 }
1351                 break;
1352         }
1353         cel_report_event(channel1, AST_CEL_ATTENDEDTRANSFER, NULL, extra, NULL);
1354         ast_json_unref(extra);
1355 }
1356
1357 static void cel_pickup_cb(
1358         void *data, struct stasis_subscription *sub,
1359         struct stasis_message *message)
1360 {
1361         struct ast_multi_channel_blob *obj = stasis_message_data(message);
1362         struct ast_channel_snapshot *channel = ast_multi_channel_blob_get_channel(obj, "channel");
1363         struct ast_channel_snapshot *target = ast_multi_channel_blob_get_channel(obj, "target");
1364         struct ast_json *extra;
1365
1366         if (!channel || !target) {
1367                 return;
1368         }
1369
1370         extra = ast_json_pack("{s: s, s: s}",
1371                 "pickup_channel", channel->name,
1372                 "pickup_channel_uniqueid", channel->uniqueid);
1373         if (!extra) {
1374                 return;
1375         }
1376
1377         cel_report_event(target, AST_CEL_PICKUP, NULL, extra, NULL);
1378         ast_json_unref(extra);
1379 }
1380
1381 static void cel_local_cb(
1382         void *data, struct stasis_subscription *sub,
1383         struct stasis_message *message)
1384 {
1385         struct ast_multi_channel_blob *obj = stasis_message_data(message);
1386         struct ast_channel_snapshot *localone = ast_multi_channel_blob_get_channel(obj, "1");
1387         struct ast_channel_snapshot *localtwo = ast_multi_channel_blob_get_channel(obj, "2");
1388         struct ast_json *extra;
1389
1390         if (!localone || !localtwo) {
1391                 return;
1392         }
1393
1394         extra = ast_json_pack("{s: s, s: s}",
1395                 "local_two", localtwo->name,
1396                 "local_two_uniqueid", localtwo->uniqueid);
1397         if (!extra) {
1398                 return;
1399         }
1400
1401         cel_report_event(localone, AST_CEL_LOCAL_OPTIMIZE, NULL, extra, NULL);
1402         ast_json_unref(extra);
1403 }
1404
1405 static void destroy_routes(void)
1406 {
1407         stasis_message_router_unsubscribe_and_join(cel_state_router);
1408         cel_state_router = NULL;
1409 }
1410
1411 static void destroy_subscriptions(void)
1412 {
1413         ao2_cleanup(cel_aggregation_topic);
1414         cel_aggregation_topic = NULL;
1415         ao2_cleanup(cel_topic);
1416         cel_topic = NULL;
1417
1418         cel_channel_forwarder = stasis_forward_cancel(cel_channel_forwarder);
1419         cel_bridge_forwarder = stasis_forward_cancel(cel_bridge_forwarder);
1420         cel_parking_forwarder = stasis_forward_cancel(cel_parking_forwarder);
1421         cel_cel_forwarder = stasis_forward_cancel(cel_cel_forwarder);
1422 }
1423
1424 static int unload_module(void)
1425 {
1426         destroy_routes();
1427         destroy_subscriptions();
1428         STASIS_MESSAGE_TYPE_CLEANUP(cel_generic_type);
1429
1430         ast_cli_unregister(&cli_status);
1431         aco_info_destroy(&cel_cfg_info);
1432         ao2_global_obj_release(cel_configs);
1433         ao2_global_obj_release(cel_dialstatus_store);
1434         ao2_global_obj_release(cel_linkedids);
1435         ao2_global_obj_release(cel_backends);
1436
1437         return 0;
1438 }
1439
1440 /*!
1441  * \brief Create the Stasis subscriptions for CEL
1442  */
1443 static int create_subscriptions(void)
1444 {
1445         cel_aggregation_topic = stasis_topic_create("cel_aggregation_topic");
1446         if (!cel_aggregation_topic) {
1447                 return -1;
1448         }
1449
1450         cel_topic = stasis_topic_create("cel_topic");
1451         if (!cel_topic) {
1452                 return -1;
1453         }
1454
1455         cel_channel_forwarder = stasis_forward_all(
1456                 ast_channel_topic_all_cached(),
1457                 cel_aggregation_topic);
1458         if (!cel_channel_forwarder) {
1459                 return -1;
1460         }
1461
1462         cel_bridge_forwarder = stasis_forward_all(
1463                 ast_bridge_topic_all_cached(),
1464                 cel_aggregation_topic);
1465         if (!cel_bridge_forwarder) {
1466                 return -1;
1467         }
1468
1469         cel_parking_forwarder = stasis_forward_all(
1470                 ast_parking_topic(),
1471                 cel_aggregation_topic);
1472         if (!cel_parking_forwarder) {
1473                 return -1;
1474         }
1475
1476         cel_cel_forwarder = stasis_forward_all(
1477                 ast_cel_topic(),
1478                 cel_aggregation_topic);
1479         if (!cel_cel_forwarder) {
1480                 return -1;
1481         }
1482
1483         return 0;
1484 }
1485
1486 /*!
1487  * \brief Create the Stasis message router and routes for CEL
1488  */
1489 static int create_routes(void)
1490 {
1491         int ret = 0;
1492
1493         cel_state_router = stasis_message_router_create(cel_aggregation_topic);
1494         if (!cel_state_router) {
1495                 return -1;
1496         }
1497         stasis_message_router_set_congestion_limits(cel_state_router, -1,
1498                 6 * AST_TASKPROCESSOR_HIGH_WATER_LEVEL);
1499
1500         ret |= stasis_message_router_add(cel_state_router,
1501                 stasis_cache_update_type(),
1502                 cel_snapshot_update_cb,
1503                 NULL);
1504
1505         ret |= stasis_message_router_add(cel_state_router,
1506                 ast_channel_dial_type(),
1507                 cel_dial_cb,
1508                 NULL);
1509
1510         ret |= stasis_message_router_add(cel_state_router,
1511                 ast_channel_entered_bridge_type(),
1512                 cel_bridge_enter_cb,
1513                 NULL);
1514
1515         ret |= stasis_message_router_add(cel_state_router,
1516                 ast_channel_left_bridge_type(),
1517                 cel_bridge_leave_cb,
1518                 NULL);
1519
1520         ret |= stasis_message_router_add(cel_state_router,
1521                 ast_parked_call_type(),
1522                 cel_parking_cb,
1523                 NULL);
1524
1525         ret |= stasis_message_router_add(cel_state_router,
1526                 cel_generic_type(),
1527                 cel_generic_cb,
1528                 NULL);
1529
1530         ret |= stasis_message_router_add(cel_state_router,
1531                 ast_blind_transfer_type(),
1532                 cel_blind_transfer_cb,
1533                 NULL);
1534
1535         ret |= stasis_message_router_add(cel_state_router,
1536                 ast_attended_transfer_type(),
1537                 cel_attended_transfer_cb,
1538                 NULL);
1539
1540         ret |= stasis_message_router_add(cel_state_router,
1541                 ast_call_pickup_type(),
1542                 cel_pickup_cb,
1543                 NULL);
1544
1545         ret |= stasis_message_router_add(cel_state_router,
1546                 ast_local_optimization_end_type(),
1547                 cel_local_cb,
1548                 NULL);
1549
1550         if (ret) {
1551                 ast_log(AST_LOG_ERROR, "Failed to register for Stasis messages\n");
1552         }
1553
1554         return ret;
1555 }
1556
1557 AO2_STRING_FIELD_HASH_FN(cel_linkedid, id)
1558 AO2_STRING_FIELD_CMP_FN(cel_linkedid, id)
1559
1560 static int load_module(void)
1561 {
1562         struct ao2_container *container;
1563
1564         container = ao2_container_alloc(NUM_APP_BUCKETS, cel_linkedid_hash_fn, cel_linkedid_cmp_fn);
1565         ao2_global_obj_replace_unref(cel_linkedids, container);
1566         ao2_cleanup(container);
1567         if (!container) {
1568                 return AST_MODULE_LOAD_FAILURE;
1569         }
1570
1571         container = ao2_container_alloc(NUM_DIALSTATUS_BUCKETS,
1572                 cel_dialstatus_hash_fn, cel_dialstatus_cmp_fn);
1573         ao2_global_obj_replace_unref(cel_dialstatus_store, container);
1574         ao2_cleanup(container);
1575         if (!container) {
1576                 return AST_MODULE_LOAD_FAILURE;
1577         }
1578
1579         if (STASIS_MESSAGE_TYPE_INIT(cel_generic_type)) {
1580                 return AST_MODULE_LOAD_FAILURE;
1581         }
1582
1583         if (ast_cli_register(&cli_status)) {
1584                 return AST_MODULE_LOAD_FAILURE;
1585         }
1586
1587         container = ao2_container_alloc(BACKEND_BUCKETS, cel_backend_hash_fn, cel_backend_cmp_fn);
1588         ao2_global_obj_replace_unref(cel_backends, container);
1589         ao2_cleanup(container);
1590         if (!container) {
1591                 return AST_MODULE_LOAD_FAILURE;
1592         }
1593
1594         if (aco_info_init(&cel_cfg_info)) {
1595                 return AST_MODULE_LOAD_FAILURE;
1596         }
1597
1598         aco_option_register(&cel_cfg_info, "enable", ACO_EXACT, general_options, "no", OPT_BOOL_T, 1, FLDSET(struct ast_cel_general_config, enable));
1599         aco_option_register(&cel_cfg_info, "dateformat", ACO_EXACT, general_options, "", OPT_STRINGFIELD_T, 0, STRFLDSET(struct ast_cel_general_config, date_format));
1600         aco_option_register_custom(&cel_cfg_info, "apps", ACO_EXACT, general_options, "", apps_handler, 0);
1601         aco_option_register_custom(&cel_cfg_info, "events", ACO_EXACT, general_options, "", events_handler, 0);
1602
1603         if (aco_process_config(&cel_cfg_info, 0)) {
1604                 struct cel_config *cel_cfg = cel_config_alloc();
1605
1606                 if (!cel_cfg) {
1607                         return AST_MODULE_LOAD_FAILURE;
1608                 }
1609
1610                 /* We couldn't process the configuration so create a default config. */
1611                 if (!aco_set_defaults(&general_option, "general", cel_cfg->general)) {
1612                         ast_log(LOG_NOTICE, "Failed to process CEL configuration; using defaults\n");
1613                         ao2_global_obj_replace_unref(cel_configs, cel_cfg);
1614                 }
1615                 ao2_ref(cel_cfg, -1);
1616         }
1617
1618         if (create_subscriptions()) {
1619                 return AST_MODULE_LOAD_FAILURE;
1620         }
1621
1622         if (ast_cel_check_enabled() && create_routes()) {
1623                 return AST_MODULE_LOAD_FAILURE;
1624         }
1625
1626         return AST_MODULE_LOAD_SUCCESS;
1627 }
1628
1629 static int reload_module(void)
1630 {
1631         unsigned int was_enabled = ast_cel_check_enabled();
1632         unsigned int is_enabled;
1633
1634         if (aco_process_config(&cel_cfg_info, 1) == ACO_PROCESS_ERROR) {
1635                 return -1;
1636         }
1637
1638         is_enabled = ast_cel_check_enabled();
1639
1640         if (!was_enabled && is_enabled) {
1641                 if (create_routes()) {
1642                         return -1;
1643                 }
1644         } else if (was_enabled && !is_enabled) {
1645                 destroy_routes();
1646         }
1647
1648         ast_verb(3, "CEL logging %sabled.\n", is_enabled ? "en" : "dis");
1649
1650         return 0;
1651 }
1652
1653 void ast_cel_publish_event(struct ast_channel *chan,
1654         enum ast_cel_event_type event_type,
1655         struct ast_json *blob)
1656 {
1657         struct ast_json *cel_blob;
1658         struct stasis_message *message;
1659
1660         cel_blob = ast_json_pack("{s: i, s: o}",
1661                 "event_type", event_type,
1662                 "event_details", ast_json_ref(blob));
1663
1664         message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan), cel_generic_type(), cel_blob);
1665         if (message) {
1666                 stasis_publish(ast_cel_topic(), message);
1667         }
1668         ao2_cleanup(message);
1669         ast_json_unref(cel_blob);
1670 }
1671
1672 struct stasis_topic *ast_cel_topic(void)
1673 {
1674         return cel_topic;
1675 }
1676
1677 struct ast_cel_general_config *ast_cel_get_config(void)
1678 {
1679         RAII_VAR(struct cel_config *, mod_cfg, ao2_global_obj_ref(cel_configs), ao2_cleanup);
1680
1681         if (!mod_cfg || !mod_cfg->general) {
1682                 return NULL;
1683         }
1684
1685         ao2_ref(mod_cfg->general, +1);
1686         return mod_cfg->general;
1687 }
1688
1689 void ast_cel_set_config(struct ast_cel_general_config *config)
1690 {
1691         int was_enabled;
1692         int is_enabled;
1693         struct ast_cel_general_config *cleanup_config;
1694         struct cel_config *mod_cfg = ao2_global_obj_ref(cel_configs);
1695
1696         if (mod_cfg) {
1697                 was_enabled = ast_cel_check_enabled();
1698
1699                 cleanup_config = mod_cfg->general;
1700                 ao2_bump(config);
1701                 mod_cfg->general = config;
1702                 ao2_cleanup(cleanup_config);
1703
1704                 is_enabled = ast_cel_check_enabled();
1705                 if (!was_enabled && is_enabled) {
1706                         create_routes();
1707                 } else if (was_enabled && !is_enabled) {
1708                         destroy_routes();
1709                 }
1710
1711                 ao2_ref(mod_cfg, -1);
1712         }
1713 }
1714
1715 int ast_cel_backend_unregister(const char *name)
1716 {
1717         struct ao2_container *backends = ao2_global_obj_ref(cel_backends);
1718
1719         if (backends) {
1720                 ao2_find(backends, name, OBJ_SEARCH_KEY | OBJ_NODATA | OBJ_UNLINK);
1721                 ao2_ref(backends, -1);
1722         }
1723
1724         return 0;
1725 }
1726
1727 int ast_cel_backend_register(const char *name, ast_cel_backend_cb backend_callback)
1728 {
1729         RAII_VAR(struct ao2_container *, backends, ao2_global_obj_ref(cel_backends), ao2_cleanup);
1730         struct cel_backend *backend;
1731
1732         if (!backends || ast_strlen_zero(name) || !backend_callback) {
1733                 return -1;
1734         }
1735
1736         /* The backend object is immutable so it doesn't need a lock of its own. */
1737         backend = ao2_alloc_options(sizeof(*backend) + 1 + strlen(name), NULL,
1738                 AO2_ALLOC_OPT_LOCK_NOLOCK);
1739         if (!backend) {
1740                 return -1;
1741         }
1742         strcpy(backend->name, name);/* Safe */
1743         backend->callback = backend_callback;
1744
1745         ao2_link(backends, backend);
1746         ao2_ref(backend, -1);
1747         return 0;
1748 }
1749
1750 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "CEL Engine",
1751         .support_level = AST_MODULE_SUPPORT_CORE,
1752         .load = load_module,
1753         .unload = unload_module,
1754         .reload = reload_module,
1755         .load_pri = AST_MODPRI_CORE,
1756         .requires = "extconfig",
1757 );