app_dial and app_queue: Make lock the forwarding channel while taking the channel...
[asterisk/asterisk.git] / main / stasis_channels.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013, Digium, Inc.
5  *
6  * Matt Jordan <mjordan@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Stasis Messages and Data Types for Channel Objects
22  *
23  * \author \verbatim Matt Jordan <mjordan@digium.com> \endverbatim
24  *
25  */
26
27 /*** MODULEINFO
28         <support_level>core</support_level>
29  ***/
30
31 #include "asterisk.h"
32
33 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
34
35 #include "asterisk/astobj2.h"
36 #include "asterisk/json.h"
37 #include "asterisk/pbx.h"
38 #include "asterisk/bridge.h"
39 #include "asterisk/translate.h"
40 #include "asterisk/stasis.h"
41 #include "asterisk/stasis_cache_pattern.h"
42 #include "asterisk/stasis_channels.h"
43
44 /*** DOCUMENTATION
45         <managerEvent language="en_US" name="VarSet">
46                 <managerEventInstance class="EVENT_FLAG_DIALPLAN">
47                         <synopsis>Raised when a variable is set to a particular value.</synopsis>
48                         <syntax>
49                                 <channel_snapshot/>
50                                 <parameter name="Variable">
51                                         <para>The variable being set.</para>
52                                 </parameter>
53                                 <parameter name="Value">
54                                         <para>The new value of the variable.</para>
55                                 </parameter>
56                         </syntax>
57                 </managerEventInstance>
58         </managerEvent>
59         <managerEvent language="en_US" name="AgentLogin">
60                 <managerEventInstance class="EVENT_FLAG_AGENT">
61                         <synopsis>Raised when an Agent has logged in.</synopsis>
62                         <syntax>
63                                 <channel_snapshot/>
64                                 <parameter name="Agent">
65                                         <para>Agent ID of the agent.</para>
66                                 </parameter>
67                         </syntax>
68                         <see-also>
69                                 <ref type="application">AgentLogin</ref>
70                                 <ref type="managerEvent">AgentLogoff</ref>
71                         </see-also>
72                 </managerEventInstance>
73         </managerEvent>
74         <managerEvent language="en_US" name="AgentLogoff">
75                 <managerEventInstance class="EVENT_FLAG_AGENT">
76                         <synopsis>Raised when an Agent has logged off.</synopsis>
77                         <syntax>
78                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='AgentLogin']/managerEventInstance/syntax/parameter)" />
79                                 <parameter name="Logintime">
80                                         <para>The number of seconds the agent was logged in.</para>
81                                 </parameter>
82                         </syntax>
83                         <see-also>
84                                 <ref type="managerEvent">AgentLogin</ref>
85                         </see-also>
86                 </managerEventInstance>
87         </managerEvent>
88 ***/
89
90 #define NUM_MULTI_CHANNEL_BLOB_BUCKETS 7
91
92 static struct stasis_cp_all *channel_cache_all;
93 static struct stasis_cache *channel_cache_by_name;
94 static struct stasis_caching_topic *channel_by_name_topic;
95
96 struct stasis_cp_all *ast_channel_cache_all(void)
97 {
98         return channel_cache_all;
99 }
100
101 struct stasis_cache *ast_channel_cache(void)
102 {
103         return stasis_cp_all_cache(channel_cache_all);
104 }
105
106 struct stasis_topic *ast_channel_topic_all(void)
107 {
108         return stasis_cp_all_topic(channel_cache_all);
109 }
110
111 struct stasis_topic *ast_channel_topic_all_cached(void)
112 {
113         return stasis_cp_all_topic_cached(channel_cache_all);
114 }
115
116 struct stasis_cache *ast_channel_cache_by_name(void)
117 {
118         return channel_cache_by_name;
119 }
120
121 static const char *channel_snapshot_get_id(struct stasis_message *message)
122 {
123         struct ast_channel_snapshot *snapshot;
124         if (ast_channel_snapshot_type() != stasis_message_type(message)) {
125                 return NULL;
126         }
127         snapshot = stasis_message_data(message);
128         return snapshot->uniqueid;
129 }
130
131 static const char *channel_snapshot_get_name(struct stasis_message *message)
132 {
133         struct ast_channel_snapshot *snapshot;
134         if (ast_channel_snapshot_type() != stasis_message_type(message)) {
135                 return NULL;
136         }
137         snapshot = stasis_message_data(message);
138         return snapshot->name;
139 }
140
141 /*!
142  * \internal
143  * \brief Hash function for \ref ast_channel_snapshot objects
144  */
145 static int channel_snapshot_hash_cb(const void *obj, const int flags)
146 {
147         const struct ast_channel_snapshot *snapshot = obj;
148         const char *name = (flags & OBJ_KEY) ? obj : snapshot->name;
149         return ast_str_case_hash(name);
150 }
151
152 /*!
153  * \internal
154  * \brief Comparison function for \ref ast_channel_snapshot objects
155  */
156 static int channel_snapshot_cmp_cb(void *obj, void *arg, int flags)
157 {
158         struct ast_channel_snapshot *left = obj;
159         struct ast_channel_snapshot *right = arg;
160         const char *match = (flags & OBJ_KEY) ? arg : right->name;
161         return strcasecmp(left->name, match) ? 0 : (CMP_MATCH | CMP_STOP);
162 }
163
164 static void channel_snapshot_dtor(void *obj)
165 {
166         struct ast_channel_snapshot *snapshot = obj;
167
168         ast_string_field_free_memory(snapshot);
169         ao2_cleanup(snapshot->manager_vars);
170         ao2_cleanup(snapshot->channel_vars);
171 }
172
173 struct ast_channel_snapshot *ast_channel_snapshot_create(struct ast_channel *chan)
174 {
175         struct ast_channel_snapshot *snapshot;
176         struct ast_bridge *bridge;
177         char nativeformats[256];
178         struct ast_str *write_transpath = ast_str_alloca(256);
179         struct ast_str *read_transpath = ast_str_alloca(256);
180         struct ast_party_id effective_connected_id;
181         struct ast_callid *callid;
182
183         /* no snapshots for dummy channels */
184         if (!ast_channel_tech(chan)) {
185                 return NULL;
186         }
187
188         snapshot = ao2_alloc(sizeof(*snapshot), channel_snapshot_dtor);
189         if (!snapshot || ast_string_field_init(snapshot, 1024)) {
190                 ao2_cleanup(snapshot);
191                 return NULL;
192         }
193
194         ast_string_field_set(snapshot, name, ast_channel_name(chan));
195         ast_string_field_set(snapshot, type, ast_channel_tech(chan)->type);
196         ast_string_field_set(snapshot, accountcode, ast_channel_accountcode(chan));
197         ast_string_field_set(snapshot, peeraccount, ast_channel_peeraccount(chan));
198         ast_string_field_set(snapshot, userfield, ast_channel_userfield(chan));
199         ast_string_field_set(snapshot, uniqueid, ast_channel_uniqueid(chan));
200         ast_string_field_set(snapshot, linkedid, ast_channel_linkedid(chan));
201         ast_string_field_set(snapshot, hangupsource, ast_channel_hangupsource(chan));
202         if (ast_channel_appl(chan)) {
203                 ast_string_field_set(snapshot, appl, ast_channel_appl(chan));
204         }
205         if (ast_channel_data(chan)) {
206                 ast_string_field_set(snapshot, data, ast_channel_data(chan));
207         }
208         ast_string_field_set(snapshot, context, ast_channel_context(chan));
209         ast_string_field_set(snapshot, exten, ast_channel_exten(chan));
210
211         ast_string_field_set(snapshot, caller_name,
212                 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, ""));
213         ast_string_field_set(snapshot, caller_number,
214                 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, ""));
215         ast_string_field_set(snapshot, caller_dnid, S_OR(ast_channel_dialed(chan)->number.str, ""));
216         ast_string_field_set(snapshot, caller_subaddr,
217                 S_COR(ast_channel_caller(chan)->id.subaddress.valid, ast_channel_caller(chan)->id.subaddress.str, ""));
218         ast_string_field_set(snapshot, dialed_subaddr,
219                 S_COR(ast_channel_dialed(chan)->subaddress.valid, ast_channel_dialed(chan)->subaddress.str, ""));
220         ast_string_field_set(snapshot, caller_ani,
221                 S_COR(ast_channel_caller(chan)->ani.number.valid, ast_channel_caller(chan)->ani.number.str, ""));
222         ast_string_field_set(snapshot, caller_rdnis,
223                 S_COR(ast_channel_redirecting(chan)->from.number.valid, ast_channel_redirecting(chan)->from.number.str, ""));
224         ast_string_field_set(snapshot, caller_dnid,
225                 S_OR(ast_channel_dialed(chan)->number.str, ""));
226
227         ast_string_field_set(snapshot, connected_name,
228                 S_COR(ast_channel_connected(chan)->id.name.valid, ast_channel_connected(chan)->id.name.str, ""));
229         ast_string_field_set(snapshot, connected_number,
230                 S_COR(ast_channel_connected(chan)->id.number.valid, ast_channel_connected(chan)->id.number.str, ""));
231         ast_string_field_set(snapshot, language, ast_channel_language(chan));
232
233         if ((bridge = ast_channel_get_bridge(chan))) {
234                 ast_string_field_set(snapshot, bridgeid, bridge->uniqueid);
235                 ao2_cleanup(bridge);
236         }
237
238         ast_string_field_set(snapshot, nativeformats, ast_getformatname_multiple(nativeformats, sizeof(nativeformats),
239                 ast_channel_nativeformats(chan)));
240         ast_string_field_set(snapshot, readformat, ast_getformatname(ast_channel_readformat(chan)));
241         ast_string_field_set(snapshot, writeformat, ast_getformatname(ast_channel_writeformat(chan)));
242         ast_string_field_set(snapshot, writetrans, ast_translate_path_to_str(ast_channel_writetrans(chan), &write_transpath));
243         ast_string_field_set(snapshot, readtrans, ast_translate_path_to_str(ast_channel_readtrans(chan), &read_transpath));
244
245         effective_connected_id = ast_channel_connected_effective_id(chan);
246         ast_string_field_set(snapshot, effective_name,
247                 S_COR(effective_connected_id.name.valid, effective_connected_id.name.str, ""));
248         ast_string_field_set(snapshot, effective_number,
249                 S_COR(effective_connected_id.number.valid, effective_connected_id.number.str, ""));
250
251         if ((callid = ast_channel_callid(chan))) {
252                 ast_callid_strnprint(snapshot->callid, sizeof(snapshot->callid), callid);
253                 ast_callid_unref(callid);
254         }
255
256         snapshot->creationtime = ast_channel_creationtime(chan);
257         snapshot->hanguptime = *(ast_channel_whentohangup(chan));
258         snapshot->state = ast_channel_state(chan);
259         snapshot->priority = ast_channel_priority(chan);
260         snapshot->amaflags = ast_channel_amaflags(chan);
261         snapshot->hangupcause = ast_channel_hangupcause(chan);
262         ast_copy_flags(&snapshot->flags, ast_channel_flags(chan), 0xFFFFFFFF);
263         snapshot->caller_pres = ast_party_id_presentation(&ast_channel_caller(chan)->id);
264         snapshot->callgroup = ast_channel_callgroup(chan);
265         snapshot->pickupgroup = ast_channel_pickupgroup(chan);
266         ast_set_flag(&snapshot->softhangup_flags, ast_channel_softhangup_internal_flag(chan));
267
268         snapshot->manager_vars = ast_channel_get_manager_vars(chan);
269         snapshot->channel_vars = ast_channel_get_vars(chan);
270         snapshot->tech_properties = ast_channel_tech(chan)->properties;
271
272         return snapshot;
273 }
274
275 static void publish_message_for_channel_topics(struct stasis_message *message, struct ast_channel *chan)
276 {
277         if (chan) {
278                 stasis_publish(ast_channel_topic(chan), message);
279         } else {
280                 stasis_publish(ast_channel_topic_all(), message);
281         }
282 }
283
284 static void channel_blob_dtor(void *obj)
285 {
286         struct ast_channel_blob *event = obj;
287         ao2_cleanup(event->snapshot);
288         ast_json_unref(event->blob);
289 }
290
291 /*! \brief Dummy callback for receiving events */
292 static void dummy_event_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message)
293 {
294 }
295
296 void ast_channel_publish_dial_forward(struct ast_channel *caller, struct ast_channel *peer,
297         struct ast_channel *forwarded, const char *dialstring, const char *dialstatus,
298         const char *forward)
299 {
300         RAII_VAR(struct ast_multi_channel_blob *, payload, NULL, ao2_cleanup);
301         RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
302         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
303         RAII_VAR(struct ast_channel_snapshot *, caller_snapshot, NULL, ao2_cleanup);
304         RAII_VAR(struct ast_channel_snapshot *, peer_snapshot, NULL, ao2_cleanup);
305         RAII_VAR(struct ast_channel_snapshot *, forwarded_snapshot, NULL, ao2_cleanup);
306
307         ast_assert(peer != NULL);
308         blob = ast_json_pack("{s: s, s: s, s: s}",
309                              "dialstatus", S_OR(dialstatus, ""),
310                              "forward", S_OR(forward, ""),
311                              "dialstring", S_OR(dialstring, ""));
312         if (!blob) {
313                 return;
314         }
315         payload = ast_multi_channel_blob_create(blob);
316         if (!payload) {
317                 return;
318         }
319
320         if (caller) {
321                 ast_channel_lock(caller);
322                 caller_snapshot = ast_channel_snapshot_create(caller);
323                 ast_channel_unlock(caller);
324                 if (!caller_snapshot) {
325                         return;
326                 }
327                 ast_multi_channel_blob_add_channel(payload, "caller", caller_snapshot);
328         }
329
330         ast_channel_lock(peer);
331         peer_snapshot = ast_channel_snapshot_create(peer);
332         ast_channel_unlock(peer);
333         if (!peer_snapshot) {
334                 return;
335         }
336         ast_multi_channel_blob_add_channel(payload, "peer", peer_snapshot);
337
338         if (forwarded) {
339                 ast_channel_lock(forwarded);
340                 forwarded_snapshot = ast_channel_snapshot_create(forwarded);
341                 ast_channel_unlock(forwarded);
342                 if (!forwarded_snapshot) {
343                         return;
344                 }
345                 ast_multi_channel_blob_add_channel(payload, "forwarded", forwarded_snapshot);
346         }
347
348         msg = stasis_message_create(ast_channel_dial_type(), payload);
349         if (!msg) {
350                 return;
351         }
352
353         if (forwarded) {
354                 struct stasis_subscription *subscription = stasis_subscribe(ast_channel_topic(peer), dummy_event_cb, NULL);
355
356                 stasis_publish(ast_channel_topic(peer), msg);
357                 stasis_unsubscribe_and_join(subscription);
358         } else {
359                 publish_message_for_channel_topics(msg, caller);
360         }
361 }
362
363 void ast_channel_publish_dial(struct ast_channel *caller, struct ast_channel *peer,
364         const char *dialstring, const char *dialstatus)
365 {
366         ast_channel_publish_dial_forward(caller, peer, NULL, dialstring, dialstatus, NULL);
367 }
368
369 static struct stasis_message *create_channel_blob_message(struct ast_channel_snapshot *snapshot,
370                 struct stasis_message_type *type,
371                 struct ast_json *blob)
372 {
373         struct stasis_message *msg;
374         struct ast_channel_blob *obj;
375
376         obj = ao2_alloc(sizeof(*obj), channel_blob_dtor);
377         if (!obj) {
378                 return NULL;
379         }
380
381         if (snapshot) {
382                 obj->snapshot = snapshot;
383                 ao2_ref(obj->snapshot, +1);
384         }
385         if (!blob) {
386                 blob = ast_json_null();
387         }
388         obj->blob = ast_json_ref(blob);
389
390         msg = stasis_message_create(type, obj);
391         ao2_cleanup(obj);
392         return msg;
393 }
394
395 struct stasis_message *ast_channel_blob_create_from_cache(const char *channel_id,
396                                                struct stasis_message_type *type,
397                                                struct ast_json *blob)
398 {
399         RAII_VAR(struct ast_channel_snapshot *, snapshot,
400                         ast_channel_snapshot_get_latest(channel_id),
401                         ao2_cleanup);
402
403         return create_channel_blob_message(snapshot, type, blob);
404 }
405
406 struct stasis_message *ast_channel_blob_create(struct ast_channel *chan,
407         struct stasis_message_type *type, struct ast_json *blob)
408 {
409         RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
410
411         if (chan) {
412                 snapshot = ast_channel_snapshot_create(chan);
413         }
414
415         return create_channel_blob_message(snapshot, type, blob);
416 }
417
418 /*! \brief A channel snapshot wrapper object used in \ref ast_multi_channel_blob objects */
419 struct channel_role_snapshot {
420         struct ast_channel_snapshot *snapshot;  /*!< A channel snapshot */
421         char role[0];                                                   /*!< The role assigned to the channel */
422 };
423
424 /*! \brief A multi channel blob data structure for multi_channel_blob stasis messages */
425 struct ast_multi_channel_blob {
426         struct ao2_container *channel_snapshots;        /*!< A container holding the snapshots */
427         struct ast_json *blob;                                          /*< A blob of JSON data */
428 };
429
430 /*!
431  * \internal
432  * \brief Standard comparison function for \ref channel_role_snapshot objects
433  */
434 static int channel_role_single_cmp_cb(void *obj, void *arg, int flags)
435 {
436         struct channel_role_snapshot *left = obj;
437         struct channel_role_snapshot *right = arg;
438         const char *match = (flags & OBJ_KEY) ? arg : right->role;
439         return strcasecmp(left->role, match) ? 0 : (CMP_MATCH | CMP_STOP);
440 }
441
442 /*!
443  * \internal
444  * \brief Multi comparison function for \ref channel_role_snapshot objects
445  */
446 static int channel_role_multi_cmp_cb(void *obj, void *arg, int flags)
447 {
448         struct channel_role_snapshot *left = obj;
449         struct channel_role_snapshot *right = arg;
450         const char *match = (flags & OBJ_KEY) ? arg : right->role;
451         return strcasecmp(left->role, match) ? 0 : (CMP_MATCH);
452 }
453
454 /*!
455  * \internal
456  * \brief Hash function for \ref channel_role_snapshot objects
457  */
458 static int channel_role_hash_cb(const void *obj, const int flags)
459 {
460         const struct channel_role_snapshot *snapshot = obj;
461         const char *name = (flags & OBJ_KEY) ? obj : snapshot->role;
462         return ast_str_case_hash(name);
463 }
464
465 /*!
466  * \internal
467  * \brief Destructor for \ref ast_multi_channel_blob objects
468  */
469 static void multi_channel_blob_dtor(void *obj)
470 {
471         struct ast_multi_channel_blob *multi_blob = obj;
472
473         ao2_cleanup(multi_blob->channel_snapshots);
474         ast_json_unref(multi_blob->blob);
475 }
476
477 struct ast_multi_channel_blob *ast_multi_channel_blob_create(struct ast_json *blob)
478 {
479         RAII_VAR(struct ast_multi_channel_blob *, obj,
480                         ao2_alloc(sizeof(*obj), multi_channel_blob_dtor),
481                         ao2_cleanup);
482
483         ast_assert(blob != NULL);
484
485         if (!obj) {
486                 return NULL;
487         }
488
489         obj->channel_snapshots = ao2_container_alloc(NUM_MULTI_CHANNEL_BLOB_BUCKETS,
490                         channel_role_hash_cb, channel_role_single_cmp_cb);
491         if (!obj->channel_snapshots) {
492                 return NULL;
493         }
494
495         obj->blob = ast_json_ref(blob);
496
497         ao2_ref(obj, +1);
498         return obj;
499 }
500
501 struct ast_channel_snapshot *ast_channel_snapshot_get_latest(const char *uniqueid)
502 {
503         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
504         struct ast_channel_snapshot *snapshot;
505
506         ast_assert(!ast_strlen_zero(uniqueid));
507
508         message = stasis_cache_get(ast_channel_cache(),
509                         ast_channel_snapshot_type(),
510                         uniqueid);
511         if (!message) {
512                 return NULL;
513         }
514
515         snapshot = stasis_message_data(message);
516         if (!snapshot) {
517                 return NULL;
518         }
519         ao2_ref(snapshot, +1);
520         return snapshot;
521 }
522
523 struct ast_channel_snapshot *ast_channel_snapshot_get_latest_by_name(const char *name)
524 {
525         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
526         struct ast_channel_snapshot *snapshot;
527
528         ast_assert(!ast_strlen_zero(name));
529
530         message = stasis_cache_get(ast_channel_cache_by_name(),
531                         ast_channel_snapshot_type(),
532                         name);
533         if (!message) {
534                 return NULL;
535         }
536
537         snapshot = stasis_message_data(message);
538         if (!snapshot) {
539                 return NULL;
540         }
541         ao2_ref(snapshot, +1);
542         return snapshot;
543 }
544
545 static void channel_role_snapshot_dtor(void *obj)
546 {
547         struct channel_role_snapshot *role_snapshot = obj;
548         ao2_cleanup(role_snapshot->snapshot);
549 }
550
551 void ast_multi_channel_blob_add_channel(struct ast_multi_channel_blob *obj, const char *role, struct ast_channel_snapshot *snapshot)
552 {
553         RAII_VAR(struct channel_role_snapshot *, role_snapshot, NULL, ao2_cleanup);
554         int role_len = strlen(role) + 1;
555
556         if (!obj || ast_strlen_zero(role) || !snapshot) {
557                 return;
558         }
559
560         role_snapshot = ao2_alloc(sizeof(*role_snapshot) + role_len, channel_role_snapshot_dtor);
561         if (!role_snapshot) {
562                 return;
563         }
564         ast_copy_string(role_snapshot->role, role, role_len);
565         role_snapshot->snapshot = snapshot;
566         ao2_ref(role_snapshot->snapshot, +1);
567         ao2_link(obj->channel_snapshots, role_snapshot);
568 }
569
570 struct ast_channel_snapshot *ast_multi_channel_blob_get_channel(struct ast_multi_channel_blob *obj, const char *role)
571 {
572         struct channel_role_snapshot *role_snapshot;
573
574         if (!obj || ast_strlen_zero(role)) {
575                 return NULL;
576         }
577         role_snapshot = ao2_find(obj->channel_snapshots, role, OBJ_KEY);
578         /* Note that this function does not increase the ref count on snapshot */
579         if (!role_snapshot) {
580                 return NULL;
581         }
582         ao2_ref(role_snapshot, -1);
583         return role_snapshot->snapshot;
584 }
585
586 struct ao2_container *ast_multi_channel_blob_get_channels(struct ast_multi_channel_blob *obj, const char *role)
587 {
588         RAII_VAR(struct ao2_container *, ret_container,
589                 ao2_container_alloc(NUM_MULTI_CHANNEL_BLOB_BUCKETS, channel_snapshot_hash_cb, channel_snapshot_cmp_cb),
590                 ao2_cleanup);
591         struct ao2_iterator *it_role_snapshots;
592         struct channel_role_snapshot *role_snapshot;
593         char *arg;
594
595         if (!obj || ast_strlen_zero(role) || !ret_container) {
596                 return NULL;
597         }
598         arg = ast_strdupa(role);
599
600         it_role_snapshots = ao2_callback(obj->channel_snapshots, OBJ_MULTIPLE | OBJ_KEY, channel_role_multi_cmp_cb, arg);
601         if (!it_role_snapshots) {
602                 return NULL;
603         }
604
605         while ((role_snapshot = ao2_iterator_next(it_role_snapshots))) {
606                 ao2_link(ret_container, role_snapshot->snapshot);
607                 ao2_ref(role_snapshot, -1);
608         }
609         ao2_iterator_destroy(it_role_snapshots);
610
611         ao2_ref(ret_container, +1);
612         return ret_container;
613 }
614
615 struct ast_json *ast_multi_channel_blob_get_json(struct ast_multi_channel_blob *obj)
616 {
617         if (!obj) {
618                 return NULL;
619         }
620         return obj->blob;
621 }
622
623 void ast_channel_stage_snapshot(struct ast_channel *chan)
624 {
625         ast_set_flag(ast_channel_flags(chan), AST_FLAG_SNAPSHOT_STAGE);
626 }
627
628 void ast_channel_stage_snapshot_done(struct ast_channel *chan)
629 {
630         ast_clear_flag(ast_channel_flags(chan), AST_FLAG_SNAPSHOT_STAGE);
631         ast_channel_publish_snapshot(chan);
632 }
633
634 void ast_channel_publish_snapshot(struct ast_channel *chan)
635 {
636         RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
637         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
638
639         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_SNAPSHOT_STAGE)) {
640                 return;
641         }
642
643         snapshot = ast_channel_snapshot_create(chan);
644         if (!snapshot) {
645                 return;
646         }
647
648         message = stasis_message_create(ast_channel_snapshot_type(), snapshot);
649         if (!message) {
650                 return;
651         }
652
653         ast_assert(ast_channel_topic(chan) != NULL);
654         stasis_publish(ast_channel_topic(chan), message);
655 }
656
657 void ast_channel_publish_blob(struct ast_channel *chan, struct stasis_message_type *type, struct ast_json *blob)
658 {
659         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
660
661         if (!blob) {
662                 blob = ast_json_null();
663         }
664
665         message = ast_channel_blob_create(chan, type, blob);
666         if (message) {
667                 stasis_publish(ast_channel_topic(chan), message);
668         }
669 }
670
671 void ast_channel_publish_varset(struct ast_channel *chan, const char *name, const char *value)
672 {
673         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
674
675         ast_assert(name != NULL);
676         ast_assert(value != NULL);
677
678         blob = ast_json_pack("{s: s, s: s}",
679                              "variable", name,
680                              "value", value);
681         if (!blob) {
682                 ast_log(LOG_ERROR, "Error creating message\n");
683                 return;
684         }
685
686         ast_channel_publish_blob(chan, ast_channel_varset_type(), blob);
687 }
688
689 static struct ast_manager_event_blob *varset_to_ami(struct stasis_message *msg)
690 {
691         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
692         struct ast_channel_blob *obj = stasis_message_data(msg);
693         const char *variable =
694                 ast_json_string_get(ast_json_object_get(obj->blob, "variable"));
695         const char *value =
696                 ast_json_string_get(ast_json_object_get(obj->blob, "value"));
697
698         if (obj->snapshot) {
699                 channel_event_string =
700                         ast_manager_build_channel_state_string(obj->snapshot);
701         } else {
702                 channel_event_string = ast_str_create(35);
703                 ast_str_set(&channel_event_string, 0,
704                             "Channel: none\r\n"
705                             "Uniqueid: none\r\n");
706         }
707
708         if (!channel_event_string) {
709                 return NULL;
710         }
711
712         return ast_manager_event_blob_create(EVENT_FLAG_DIALPLAN, "VarSet",
713                 "%s"
714                 "Variable: %s\r\n"
715                 "Value: %s\r\n",
716                 ast_str_buffer(channel_event_string), variable, value);
717 }
718
719 static struct ast_manager_event_blob *agent_login_to_ami(struct stasis_message *msg)
720 {
721         RAII_VAR(struct ast_str *, channel_string, NULL, ast_free);
722         struct ast_channel_blob *obj = stasis_message_data(msg);
723         const char *agent = ast_json_string_get(ast_json_object_get(obj->blob, "agent"));
724
725         channel_string = ast_manager_build_channel_state_string(obj->snapshot);
726         if (!channel_string) {
727                 return NULL;
728         }
729
730         return ast_manager_event_blob_create(EVENT_FLAG_AGENT, "AgentLogin",
731                 "%s"
732                 "Agent: %s\r\n",
733                 ast_str_buffer(channel_string), agent);
734 }
735
736 static struct ast_manager_event_blob *agent_logoff_to_ami(struct stasis_message *msg)
737 {
738         RAII_VAR(struct ast_str *, channel_string, NULL, ast_free);
739         struct ast_channel_blob *obj = stasis_message_data(msg);
740         const char *agent = ast_json_string_get(ast_json_object_get(obj->blob, "agent"));
741         long logintime = ast_json_integer_get(ast_json_object_get(obj->blob, "logintime"));
742
743         channel_string = ast_manager_build_channel_state_string(obj->snapshot);
744         if (!channel_string) {
745                 return NULL;
746         }
747
748         return ast_manager_event_blob_create(EVENT_FLAG_AGENT, "AgentLogoff",
749                 "%s"
750                 "Agent: %s\r\n"
751                 "Logintime: %ld\r\n",
752                 ast_str_buffer(channel_string), agent, logintime);
753 }
754
755 void ast_publish_channel_state(struct ast_channel *chan)
756 {
757         RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
758         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
759
760         ast_assert(chan != NULL);
761         if (!chan) {
762                 return;
763         }
764
765         snapshot = ast_channel_snapshot_create(chan);
766         if (!snapshot) {
767                 return;
768         }
769
770         message = stasis_message_create(ast_channel_snapshot_type(), snapshot);
771         if (!message) {
772                 return;
773         }
774
775         ast_assert(ast_channel_topic(chan) != NULL);
776         stasis_publish(ast_channel_topic(chan), message);
777 }
778
779 struct ast_json *ast_channel_snapshot_to_json(
780         const struct ast_channel_snapshot *snapshot,
781         const struct stasis_message_sanitizer *sanitize)
782 {
783         RAII_VAR(struct ast_json *, json_chan, NULL, ast_json_unref);
784
785         if (snapshot == NULL
786                 || (sanitize && sanitize->channel_snapshot
787                 && sanitize->channel_snapshot(snapshot))) {
788                 return NULL;
789         }
790
791         json_chan = ast_json_pack(
792                 /* Broken up into groups of three for readability */
793                 "{ s: s, s: s, s: s,"
794                 "  s: o, s: o, s: s,"
795                 "  s: o, s: o }",
796                 /* First line */
797                 "id", snapshot->uniqueid,
798                 "name", snapshot->name,
799                 "state", ast_state2str(snapshot->state),
800                 /* Second line */
801                 "caller", ast_json_name_number(
802                         snapshot->caller_name, snapshot->caller_number),
803                 "connected", ast_json_name_number(
804                         snapshot->connected_name, snapshot->connected_number),
805                 "accountcode", snapshot->accountcode,
806                 /* Third line */
807                 "dialplan", ast_json_dialplan_cep(
808                         snapshot->context, snapshot->exten, snapshot->priority),
809                 "creationtime", ast_json_timeval(snapshot->creationtime, NULL));
810
811         return ast_json_ref(json_chan);
812 }
813
814 int ast_channel_snapshot_cep_equal(
815         const struct ast_channel_snapshot *old_snapshot,
816         const struct ast_channel_snapshot *new_snapshot)
817 {
818         ast_assert(old_snapshot != NULL);
819         ast_assert(new_snapshot != NULL);
820
821         /* We actually get some snapshots with CEP set, but before the
822          * application is set. Since empty application is invalid, we treat
823          * setting the application from nothing as a CEP change.
824          */
825         if (ast_strlen_zero(old_snapshot->appl) &&
826             !ast_strlen_zero(new_snapshot->appl)) {
827                 return 0;
828         }
829
830         return old_snapshot->priority == new_snapshot->priority &&
831                 strcmp(old_snapshot->context, new_snapshot->context) == 0 &&
832                 strcmp(old_snapshot->exten, new_snapshot->exten) == 0;
833 }
834
835 int ast_channel_snapshot_caller_id_equal(
836         const struct ast_channel_snapshot *old_snapshot,
837         const struct ast_channel_snapshot *new_snapshot)
838 {
839         ast_assert(old_snapshot != NULL);
840         ast_assert(new_snapshot != NULL);
841         return strcmp(old_snapshot->caller_number, new_snapshot->caller_number) == 0 &&
842                 strcmp(old_snapshot->caller_name, new_snapshot->caller_name) == 0;
843 }
844
845 static struct ast_json *channel_blob_to_json(
846         struct stasis_message *message,
847         const char *type,
848         const struct stasis_message_sanitizer *sanitize)
849 {
850         RAII_VAR(struct ast_json *, out, NULL, ast_json_unref);
851         struct ast_channel_blob *channel_blob = stasis_message_data(message);
852         struct ast_json *blob = channel_blob->blob;
853         struct ast_channel_snapshot *snapshot = channel_blob->snapshot;
854         const struct timeval *tv = stasis_message_timestamp(message);
855         int res = 0;
856
857         if (blob == NULL || ast_json_is_null(blob)) {
858                 out = ast_json_object_create();
859         } else {
860                 /* blobs are immutable, so shallow copies are fine */
861                 out = ast_json_copy(blob);
862         }
863
864         if (!out) {
865                 return NULL;
866         }
867
868         res |= ast_json_object_set(out, "type", ast_json_string_create(type));
869         res |= ast_json_object_set(out, "timestamp",
870                 ast_json_timeval(*tv, NULL));
871
872         /* For global channel messages, the snapshot is optional */
873         if (snapshot) {
874                 struct ast_json *json_channel = ast_channel_snapshot_to_json(snapshot, sanitize);
875
876                 if (!json_channel) {
877                         return NULL;
878                 }
879
880                 res |= ast_json_object_set(out, "channel", json_channel);
881         }
882
883         if (res != 0) {
884                 return NULL;
885         }
886
887         return ast_json_ref(out);
888 }
889
890 static struct ast_json *dtmf_end_to_json(
891         struct stasis_message *message,
892         const struct stasis_message_sanitizer *sanitize)
893 {
894         struct ast_channel_blob *channel_blob = stasis_message_data(message);
895         struct ast_json *blob = channel_blob->blob;
896         struct ast_channel_snapshot *snapshot = channel_blob->snapshot;
897         const char *direction =
898                 ast_json_string_get(ast_json_object_get(blob, "direction"));
899         const struct timeval *tv = stasis_message_timestamp(message);
900         struct ast_json *json_channel = ast_channel_snapshot_to_json(snapshot, sanitize);
901
902         /* Only present received DTMF end events as JSON */
903         if (strcasecmp("Received", direction) != 0) {
904                 return NULL;
905         }
906
907         if (!json_channel) {
908                 return NULL;
909         }
910
911         return ast_json_pack("{s: s, s: o, s: O, s: O, s: o}",
912                 "type", "ChannelDtmfReceived",
913                 "timestamp", ast_json_timeval(*tv, NULL),
914                 "digit", ast_json_object_get(blob, "digit"),
915                 "duration_ms", ast_json_object_get(blob, "duration_ms"),
916                 "channel", json_channel);
917 }
918
919 static struct ast_json *user_event_to_json(
920         struct stasis_message *message,
921         const struct stasis_message_sanitizer *sanitize)
922 {
923         struct ast_channel_blob *channel_blob = stasis_message_data(message);
924         struct ast_json *blob = channel_blob->blob;
925         struct ast_channel_snapshot *snapshot = channel_blob->snapshot;
926         const struct timeval *tv = stasis_message_timestamp(message);
927         struct ast_json *json_channel = ast_channel_snapshot_to_json(snapshot, sanitize);
928
929         if (!json_channel) {
930                 return NULL;
931         }
932
933         return ast_json_pack("{s: s, s: o, s: O, s: O, s: o}",
934                 "type", "ChannelUserevent",
935                 "timestamp", ast_json_timeval(*tv, NULL),
936                 "eventname", ast_json_object_get(blob, "eventname"),
937                 "userevent", blob,
938                 "channel", json_channel);
939 }
940
941 static struct ast_json *varset_to_json(
942         struct stasis_message *message,
943         const struct stasis_message_sanitizer *sanitize)
944 {
945         return channel_blob_to_json(message, "ChannelVarset", sanitize);
946 }
947
948 static struct ast_json *hangup_request_to_json(
949         struct stasis_message *message,
950         const struct stasis_message_sanitizer *sanitize)
951 {
952         return channel_blob_to_json(message, "ChannelHangupRequest", sanitize);
953 }
954
955 static struct ast_json *dial_to_json(
956         struct stasis_message *message,
957         const struct stasis_message_sanitizer *sanitize)
958 {
959         struct ast_multi_channel_blob *payload = stasis_message_data(message);
960         struct ast_json *blob = ast_multi_channel_blob_get_json(payload);
961         struct ast_json *caller_json = ast_channel_snapshot_to_json(ast_multi_channel_blob_get_channel(payload, "caller"), sanitize);
962         struct ast_json *peer_json = ast_channel_snapshot_to_json(ast_multi_channel_blob_get_channel(payload, "peer"), sanitize);
963         struct ast_json *forwarded_json = ast_channel_snapshot_to_json(ast_multi_channel_blob_get_channel(payload, "forwarded"), sanitize);
964         struct ast_json *json;
965         const struct timeval *tv = stasis_message_timestamp(message);
966         int res = 0;
967
968         json = ast_json_pack("{s: s, s: o, s: O, s: O, s: O}",
969                 "type", "Dial",
970                 "timestamp", ast_json_timeval(*tv, NULL),
971                 "dialstatus", ast_json_object_get(blob, "dialstatus"),
972                 "forward", ast_json_object_get(blob, "forward"),
973                 "dialstring", ast_json_object_get(blob, "dialstring"));
974         if (!json) {
975                 ast_json_unref(caller_json);
976                 ast_json_unref(peer_json);
977                 ast_json_unref(forwarded_json);
978                 return NULL;
979         }
980
981         if (caller_json) {
982                 res |= ast_json_object_set(json, "caller", caller_json);
983         }
984         if (peer_json) {
985                 res |= ast_json_object_set(json, "peer", peer_json);
986         }
987         if (forwarded_json) {
988                 res |= ast_json_object_set(json, "forwarded", forwarded_json);
989         }
990
991         if (res) {
992                 ast_json_unref(json);
993                 return NULL;
994         }
995
996         return json;
997 }
998
999 /*!
1000  * @{ \brief Define channel message types.
1001  */
1002 STASIS_MESSAGE_TYPE_DEFN(ast_channel_snapshot_type);
1003 STASIS_MESSAGE_TYPE_DEFN(ast_channel_dial_type,
1004         .to_json = dial_to_json,
1005         );
1006 STASIS_MESSAGE_TYPE_DEFN(ast_channel_varset_type,
1007         .to_ami = varset_to_ami,
1008         .to_json = varset_to_json,
1009         );
1010 STASIS_MESSAGE_TYPE_DEFN(ast_channel_user_event_type,
1011         .to_json = user_event_to_json,
1012         );
1013 STASIS_MESSAGE_TYPE_DEFN(ast_channel_hangup_request_type,
1014         .to_json = hangup_request_to_json,
1015         );
1016 STASIS_MESSAGE_TYPE_DEFN(ast_channel_dtmf_begin_type);
1017 STASIS_MESSAGE_TYPE_DEFN(ast_channel_dtmf_end_type,
1018         .to_json = dtmf_end_to_json,
1019         );
1020 STASIS_MESSAGE_TYPE_DEFN(ast_channel_hold_type);
1021 STASIS_MESSAGE_TYPE_DEFN(ast_channel_unhold_type);
1022 STASIS_MESSAGE_TYPE_DEFN(ast_channel_chanspy_start_type);
1023 STASIS_MESSAGE_TYPE_DEFN(ast_channel_chanspy_stop_type);
1024 STASIS_MESSAGE_TYPE_DEFN(ast_channel_fax_type);
1025 STASIS_MESSAGE_TYPE_DEFN(ast_channel_hangup_handler_type);
1026 STASIS_MESSAGE_TYPE_DEFN(ast_channel_moh_start_type);
1027 STASIS_MESSAGE_TYPE_DEFN(ast_channel_moh_stop_type);
1028 STASIS_MESSAGE_TYPE_DEFN(ast_channel_monitor_start_type);
1029 STASIS_MESSAGE_TYPE_DEFN(ast_channel_monitor_stop_type);
1030 STASIS_MESSAGE_TYPE_DEFN(ast_channel_agent_login_type,
1031         .to_ami = agent_login_to_ami,
1032         );
1033 STASIS_MESSAGE_TYPE_DEFN(ast_channel_agent_logoff_type,
1034         .to_ami = agent_logoff_to_ami,
1035         );
1036
1037 /*! @} */
1038
1039 static void stasis_channels_cleanup(void)
1040 {
1041         stasis_caching_unsubscribe_and_join(channel_by_name_topic);
1042         channel_by_name_topic = NULL;
1043         ao2_cleanup(channel_cache_by_name);
1044         channel_cache_by_name = NULL;
1045         ao2_cleanup(channel_cache_all);
1046         channel_cache_all = NULL;
1047
1048         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_snapshot_type);
1049         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_dial_type);
1050         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_varset_type);
1051         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_user_event_type);
1052         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_hangup_request_type);
1053         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_dtmf_begin_type);
1054         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_dtmf_end_type);
1055         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_hold_type);
1056         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_unhold_type);
1057         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_chanspy_start_type);
1058         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_chanspy_stop_type);
1059         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_fax_type);
1060         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_hangup_handler_type);
1061         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_moh_start_type);
1062         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_moh_stop_type);
1063         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_monitor_start_type);
1064         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_monitor_stop_type);
1065         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_agent_login_type);
1066         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_agent_logoff_type);
1067 }
1068
1069 int ast_stasis_channels_init(void)
1070 {
1071         int res = 0;
1072
1073         ast_register_cleanup(stasis_channels_cleanup);
1074
1075         channel_cache_all = stasis_cp_all_create("ast_channel_topic_all",
1076                 channel_snapshot_get_id);
1077         if (!channel_cache_all) {
1078                 return -1;
1079         }
1080         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_agent_login_type);
1081         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_agent_logoff_type);
1082
1083         channel_cache_by_name = stasis_cache_create(channel_snapshot_get_name);
1084         if (!channel_cache_by_name) {
1085                 return -1;
1086         }
1087
1088         /* This should be initialized before the caching topic */
1089         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_snapshot_type);
1090
1091         channel_by_name_topic = stasis_caching_topic_create(
1092                 stasis_cp_all_topic(channel_cache_all),
1093                 channel_cache_by_name);
1094         if (!channel_by_name_topic) {
1095                 return -1;
1096         }
1097
1098         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_dial_type);
1099         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_varset_type);
1100         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_user_event_type);
1101         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_hangup_request_type);
1102         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_dtmf_begin_type);
1103         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_dtmf_end_type);
1104         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_hold_type);
1105         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_unhold_type);
1106         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_chanspy_start_type);
1107         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_chanspy_stop_type);
1108         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_fax_type);
1109         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_hangup_handler_type);
1110         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_moh_start_type);
1111         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_moh_stop_type);
1112         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_monitor_start_type);
1113         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_monitor_stop_type);
1114
1115         return res;
1116 }