Eliminate some more unnecessary RAII_VAR() uses.
[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                 forwarded_snapshot = ast_channel_snapshot_create(forwarded);
340                 if (!forwarded_snapshot) {
341                         return;
342                 }
343                 ast_multi_channel_blob_add_channel(payload, "forwarded", forwarded_snapshot);
344         }
345
346         msg = stasis_message_create(ast_channel_dial_type(), payload);
347         if (!msg) {
348                 return;
349         }
350
351         if (forwarded) {
352                 struct stasis_subscription *subscription = stasis_subscribe(ast_channel_topic(peer), dummy_event_cb, NULL);
353
354                 stasis_publish(ast_channel_topic(peer), msg);
355                 stasis_unsubscribe_and_join(subscription);
356         } else {
357                 publish_message_for_channel_topics(msg, caller);
358         }
359 }
360
361 void ast_channel_publish_dial(struct ast_channel *caller, struct ast_channel *peer,
362         const char *dialstring, const char *dialstatus)
363 {
364         ast_channel_publish_dial_forward(caller, peer, NULL, dialstring, dialstatus, NULL);
365 }
366
367 static struct stasis_message *create_channel_blob_message(struct ast_channel_snapshot *snapshot,
368                 struct stasis_message_type *type,
369                 struct ast_json *blob)
370 {
371         struct stasis_message *msg;
372         struct ast_channel_blob *obj;
373
374         obj = ao2_alloc(sizeof(*obj), channel_blob_dtor);
375         if (!obj) {
376                 return NULL;
377         }
378
379         if (snapshot) {
380                 obj->snapshot = snapshot;
381                 ao2_ref(obj->snapshot, +1);
382         }
383         if (!blob) {
384                 blob = ast_json_null();
385         }
386         obj->blob = ast_json_ref(blob);
387
388         msg = stasis_message_create(type, obj);
389         ao2_cleanup(obj);
390         return msg;
391 }
392
393 struct stasis_message *ast_channel_blob_create_from_cache(const char *channel_id,
394                                                struct stasis_message_type *type,
395                                                struct ast_json *blob)
396 {
397         RAII_VAR(struct ast_channel_snapshot *, snapshot,
398                         ast_channel_snapshot_get_latest(channel_id),
399                         ao2_cleanup);
400
401         return create_channel_blob_message(snapshot, type, blob);
402 }
403
404 struct stasis_message *ast_channel_blob_create(struct ast_channel *chan,
405         struct stasis_message_type *type, struct ast_json *blob)
406 {
407         RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
408
409         if (chan) {
410                 snapshot = ast_channel_snapshot_create(chan);
411         }
412
413         return create_channel_blob_message(snapshot, type, blob);
414 }
415
416 /*! \brief A channel snapshot wrapper object used in \ref ast_multi_channel_blob objects */
417 struct channel_role_snapshot {
418         struct ast_channel_snapshot *snapshot;  /*!< A channel snapshot */
419         char role[0];                                                   /*!< The role assigned to the channel */
420 };
421
422 /*! \brief A multi channel blob data structure for multi_channel_blob stasis messages */
423 struct ast_multi_channel_blob {
424         struct ao2_container *channel_snapshots;        /*!< A container holding the snapshots */
425         struct ast_json *blob;                                          /*< A blob of JSON data */
426 };
427
428 /*!
429  * \internal
430  * \brief Standard comparison function for \ref channel_role_snapshot objects
431  */
432 static int channel_role_single_cmp_cb(void *obj, void *arg, int flags)
433 {
434         struct channel_role_snapshot *left = obj;
435         struct channel_role_snapshot *right = arg;
436         const char *match = (flags & OBJ_KEY) ? arg : right->role;
437         return strcasecmp(left->role, match) ? 0 : (CMP_MATCH | CMP_STOP);
438 }
439
440 /*!
441  * \internal
442  * \brief Multi comparison function for \ref channel_role_snapshot objects
443  */
444 static int channel_role_multi_cmp_cb(void *obj, void *arg, int flags)
445 {
446         struct channel_role_snapshot *left = obj;
447         struct channel_role_snapshot *right = arg;
448         const char *match = (flags & OBJ_KEY) ? arg : right->role;
449         return strcasecmp(left->role, match) ? 0 : (CMP_MATCH);
450 }
451
452 /*!
453  * \internal
454  * \brief Hash function for \ref channel_role_snapshot objects
455  */
456 static int channel_role_hash_cb(const void *obj, const int flags)
457 {
458         const struct channel_role_snapshot *snapshot = obj;
459         const char *name = (flags & OBJ_KEY) ? obj : snapshot->role;
460         return ast_str_case_hash(name);
461 }
462
463 /*!
464  * \internal
465  * \brief Destructor for \ref ast_multi_channel_blob objects
466  */
467 static void multi_channel_blob_dtor(void *obj)
468 {
469         struct ast_multi_channel_blob *multi_blob = obj;
470
471         ao2_cleanup(multi_blob->channel_snapshots);
472         ast_json_unref(multi_blob->blob);
473 }
474
475 struct ast_multi_channel_blob *ast_multi_channel_blob_create(struct ast_json *blob)
476 {
477         RAII_VAR(struct ast_multi_channel_blob *, obj,
478                         ao2_alloc(sizeof(*obj), multi_channel_blob_dtor),
479                         ao2_cleanup);
480
481         ast_assert(blob != NULL);
482
483         if (!obj) {
484                 return NULL;
485         }
486
487         obj->channel_snapshots = ao2_container_alloc(NUM_MULTI_CHANNEL_BLOB_BUCKETS,
488                         channel_role_hash_cb, channel_role_single_cmp_cb);
489         if (!obj->channel_snapshots) {
490                 return NULL;
491         }
492
493         obj->blob = ast_json_ref(blob);
494
495         ao2_ref(obj, +1);
496         return obj;
497 }
498
499 struct ast_channel_snapshot *ast_channel_snapshot_get_latest(const char *uniqueid)
500 {
501         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
502         struct ast_channel_snapshot *snapshot;
503
504         ast_assert(!ast_strlen_zero(uniqueid));
505
506         message = stasis_cache_get(ast_channel_cache(),
507                         ast_channel_snapshot_type(),
508                         uniqueid);
509         if (!message) {
510                 return NULL;
511         }
512
513         snapshot = stasis_message_data(message);
514         if (!snapshot) {
515                 return NULL;
516         }
517         ao2_ref(snapshot, +1);
518         return snapshot;
519 }
520
521 struct ast_channel_snapshot *ast_channel_snapshot_get_latest_by_name(const char *name)
522 {
523         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
524         struct ast_channel_snapshot *snapshot;
525
526         ast_assert(!ast_strlen_zero(name));
527
528         message = stasis_cache_get(ast_channel_cache_by_name(),
529                         ast_channel_snapshot_type(),
530                         name);
531         if (!message) {
532                 return NULL;
533         }
534
535         snapshot = stasis_message_data(message);
536         if (!snapshot) {
537                 return NULL;
538         }
539         ao2_ref(snapshot, +1);
540         return snapshot;
541 }
542
543 static void channel_role_snapshot_dtor(void *obj)
544 {
545         struct channel_role_snapshot *role_snapshot = obj;
546         ao2_cleanup(role_snapshot->snapshot);
547 }
548
549 void ast_multi_channel_blob_add_channel(struct ast_multi_channel_blob *obj, const char *role, struct ast_channel_snapshot *snapshot)
550 {
551         RAII_VAR(struct channel_role_snapshot *, role_snapshot, NULL, ao2_cleanup);
552         int role_len = strlen(role) + 1;
553
554         if (!obj || ast_strlen_zero(role) || !snapshot) {
555                 return;
556         }
557
558         role_snapshot = ao2_alloc(sizeof(*role_snapshot) + role_len, channel_role_snapshot_dtor);
559         if (!role_snapshot) {
560                 return;
561         }
562         ast_copy_string(role_snapshot->role, role, role_len);
563         role_snapshot->snapshot = snapshot;
564         ao2_ref(role_snapshot->snapshot, +1);
565         ao2_link(obj->channel_snapshots, role_snapshot);
566 }
567
568 struct ast_channel_snapshot *ast_multi_channel_blob_get_channel(struct ast_multi_channel_blob *obj, const char *role)
569 {
570         struct channel_role_snapshot *role_snapshot;
571
572         if (!obj || ast_strlen_zero(role)) {
573                 return NULL;
574         }
575         role_snapshot = ao2_find(obj->channel_snapshots, role, OBJ_KEY);
576         /* Note that this function does not increase the ref count on snapshot */
577         if (!role_snapshot) {
578                 return NULL;
579         }
580         ao2_ref(role_snapshot, -1);
581         return role_snapshot->snapshot;
582 }
583
584 struct ao2_container *ast_multi_channel_blob_get_channels(struct ast_multi_channel_blob *obj, const char *role)
585 {
586         RAII_VAR(struct ao2_container *, ret_container,
587                 ao2_container_alloc(NUM_MULTI_CHANNEL_BLOB_BUCKETS, channel_snapshot_hash_cb, channel_snapshot_cmp_cb),
588                 ao2_cleanup);
589         struct ao2_iterator *it_role_snapshots;
590         struct channel_role_snapshot *role_snapshot;
591         char *arg;
592
593         if (!obj || ast_strlen_zero(role) || !ret_container) {
594                 return NULL;
595         }
596         arg = ast_strdupa(role);
597
598         it_role_snapshots = ao2_callback(obj->channel_snapshots, OBJ_MULTIPLE | OBJ_KEY, channel_role_multi_cmp_cb, arg);
599         if (!it_role_snapshots) {
600                 return NULL;
601         }
602
603         while ((role_snapshot = ao2_iterator_next(it_role_snapshots))) {
604                 ao2_link(ret_container, role_snapshot->snapshot);
605                 ao2_ref(role_snapshot, -1);
606         }
607         ao2_iterator_destroy(it_role_snapshots);
608
609         ao2_ref(ret_container, +1);
610         return ret_container;
611 }
612
613 struct ast_json *ast_multi_channel_blob_get_json(struct ast_multi_channel_blob *obj)
614 {
615         if (!obj) {
616                 return NULL;
617         }
618         return obj->blob;
619 }
620
621 void ast_channel_stage_snapshot(struct ast_channel *chan)
622 {
623         ast_set_flag(ast_channel_flags(chan), AST_FLAG_SNAPSHOT_STAGE);
624 }
625
626 void ast_channel_stage_snapshot_done(struct ast_channel *chan)
627 {
628         ast_clear_flag(ast_channel_flags(chan), AST_FLAG_SNAPSHOT_STAGE);
629         ast_channel_publish_snapshot(chan);
630 }
631
632 void ast_channel_publish_snapshot(struct ast_channel *chan)
633 {
634         RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
635         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
636
637         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_SNAPSHOT_STAGE)) {
638                 return;
639         }
640
641         snapshot = ast_channel_snapshot_create(chan);
642         if (!snapshot) {
643                 return;
644         }
645
646         message = stasis_message_create(ast_channel_snapshot_type(), snapshot);
647         if (!message) {
648                 return;
649         }
650
651         ast_assert(ast_channel_topic(chan) != NULL);
652         stasis_publish(ast_channel_topic(chan), message);
653 }
654
655 void ast_channel_publish_blob(struct ast_channel *chan, struct stasis_message_type *type, struct ast_json *blob)
656 {
657         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
658
659         if (!blob) {
660                 blob = ast_json_null();
661         }
662
663         message = ast_channel_blob_create(chan, type, blob);
664         if (message) {
665                 stasis_publish(ast_channel_topic(chan), message);
666         }
667 }
668
669 void ast_channel_publish_varset(struct ast_channel *chan, const char *name, const char *value)
670 {
671         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
672
673         ast_assert(name != NULL);
674         ast_assert(value != NULL);
675
676         blob = ast_json_pack("{s: s, s: s}",
677                              "variable", name,
678                              "value", value);
679         if (!blob) {
680                 ast_log(LOG_ERROR, "Error creating message\n");
681                 return;
682         }
683
684         ast_channel_publish_blob(chan, ast_channel_varset_type(), blob);
685 }
686
687 static struct ast_manager_event_blob *varset_to_ami(struct stasis_message *msg)
688 {
689         RAII_VAR(struct ast_str *, channel_event_string, NULL, ast_free);
690         struct ast_channel_blob *obj = stasis_message_data(msg);
691         const char *variable =
692                 ast_json_string_get(ast_json_object_get(obj->blob, "variable"));
693         const char *value =
694                 ast_json_string_get(ast_json_object_get(obj->blob, "value"));
695
696         if (obj->snapshot) {
697                 channel_event_string =
698                         ast_manager_build_channel_state_string(obj->snapshot);
699         } else {
700                 channel_event_string = ast_str_create(35);
701                 ast_str_set(&channel_event_string, 0,
702                             "Channel: none\r\n"
703                             "Uniqueid: none\r\n");
704         }
705
706         if (!channel_event_string) {
707                 return NULL;
708         }
709
710         return ast_manager_event_blob_create(EVENT_FLAG_DIALPLAN, "VarSet",
711                 "%s"
712                 "Variable: %s\r\n"
713                 "Value: %s\r\n",
714                 ast_str_buffer(channel_event_string), variable, value);
715 }
716
717 static struct ast_manager_event_blob *agent_login_to_ami(struct stasis_message *msg)
718 {
719         RAII_VAR(struct ast_str *, channel_string, NULL, ast_free);
720         struct ast_channel_blob *obj = stasis_message_data(msg);
721         const char *agent = ast_json_string_get(ast_json_object_get(obj->blob, "agent"));
722
723         channel_string = ast_manager_build_channel_state_string(obj->snapshot);
724         if (!channel_string) {
725                 return NULL;
726         }
727
728         return ast_manager_event_blob_create(EVENT_FLAG_AGENT, "AgentLogin",
729                 "%s"
730                 "Agent: %s\r\n",
731                 ast_str_buffer(channel_string), agent);
732 }
733
734 static struct ast_manager_event_blob *agent_logoff_to_ami(struct stasis_message *msg)
735 {
736         RAII_VAR(struct ast_str *, channel_string, NULL, ast_free);
737         struct ast_channel_blob *obj = stasis_message_data(msg);
738         const char *agent = ast_json_string_get(ast_json_object_get(obj->blob, "agent"));
739         long logintime = ast_json_integer_get(ast_json_object_get(obj->blob, "logintime"));
740
741         channel_string = ast_manager_build_channel_state_string(obj->snapshot);
742         if (!channel_string) {
743                 return NULL;
744         }
745
746         return ast_manager_event_blob_create(EVENT_FLAG_AGENT, "AgentLogoff",
747                 "%s"
748                 "Agent: %s\r\n"
749                 "Logintime: %ld\r\n",
750                 ast_str_buffer(channel_string), agent, logintime);
751 }
752
753 void ast_publish_channel_state(struct ast_channel *chan)
754 {
755         RAII_VAR(struct ast_channel_snapshot *, snapshot, NULL, ao2_cleanup);
756         RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
757
758         ast_assert(chan != NULL);
759         if (!chan) {
760                 return;
761         }
762
763         snapshot = ast_channel_snapshot_create(chan);
764         if (!snapshot) {
765                 return;
766         }
767
768         message = stasis_message_create(ast_channel_snapshot_type(), snapshot);
769         if (!message) {
770                 return;
771         }
772
773         ast_assert(ast_channel_topic(chan) != NULL);
774         stasis_publish(ast_channel_topic(chan), message);
775 }
776
777 struct ast_json *ast_channel_snapshot_to_json(
778         const struct ast_channel_snapshot *snapshot,
779         const struct stasis_message_sanitizer *sanitize)
780 {
781         RAII_VAR(struct ast_json *, json_chan, NULL, ast_json_unref);
782
783         if (snapshot == NULL
784                 || (sanitize && sanitize->channel_snapshot
785                 && sanitize->channel_snapshot(snapshot))) {
786                 return NULL;
787         }
788
789         json_chan = ast_json_pack(
790                 /* Broken up into groups of three for readability */
791                 "{ s: s, s: s, s: s,"
792                 "  s: o, s: o, s: s,"
793                 "  s: o, s: o }",
794                 /* First line */
795                 "id", snapshot->uniqueid,
796                 "name", snapshot->name,
797                 "state", ast_state2str(snapshot->state),
798                 /* Second line */
799                 "caller", ast_json_name_number(
800                         snapshot->caller_name, snapshot->caller_number),
801                 "connected", ast_json_name_number(
802                         snapshot->connected_name, snapshot->connected_number),
803                 "accountcode", snapshot->accountcode,
804                 /* Third line */
805                 "dialplan", ast_json_dialplan_cep(
806                         snapshot->context, snapshot->exten, snapshot->priority),
807                 "creationtime", ast_json_timeval(snapshot->creationtime, NULL));
808
809         return ast_json_ref(json_chan);
810 }
811
812 int ast_channel_snapshot_cep_equal(
813         const struct ast_channel_snapshot *old_snapshot,
814         const struct ast_channel_snapshot *new_snapshot)
815 {
816         ast_assert(old_snapshot != NULL);
817         ast_assert(new_snapshot != NULL);
818
819         /* We actually get some snapshots with CEP set, but before the
820          * application is set. Since empty application is invalid, we treat
821          * setting the application from nothing as a CEP change.
822          */
823         if (ast_strlen_zero(old_snapshot->appl) &&
824             !ast_strlen_zero(new_snapshot->appl)) {
825                 return 0;
826         }
827
828         return old_snapshot->priority == new_snapshot->priority &&
829                 strcmp(old_snapshot->context, new_snapshot->context) == 0 &&
830                 strcmp(old_snapshot->exten, new_snapshot->exten) == 0;
831 }
832
833 int ast_channel_snapshot_caller_id_equal(
834         const struct ast_channel_snapshot *old_snapshot,
835         const struct ast_channel_snapshot *new_snapshot)
836 {
837         ast_assert(old_snapshot != NULL);
838         ast_assert(new_snapshot != NULL);
839         return strcmp(old_snapshot->caller_number, new_snapshot->caller_number) == 0 &&
840                 strcmp(old_snapshot->caller_name, new_snapshot->caller_name) == 0;
841 }
842
843 static struct ast_json *channel_blob_to_json(
844         struct stasis_message *message,
845         const char *type,
846         const struct stasis_message_sanitizer *sanitize)
847 {
848         RAII_VAR(struct ast_json *, out, NULL, ast_json_unref);
849         struct ast_channel_blob *channel_blob = stasis_message_data(message);
850         struct ast_json *blob = channel_blob->blob;
851         struct ast_channel_snapshot *snapshot = channel_blob->snapshot;
852         const struct timeval *tv = stasis_message_timestamp(message);
853         int res = 0;
854
855         if (blob == NULL || ast_json_is_null(blob)) {
856                 out = ast_json_object_create();
857         } else {
858                 /* blobs are immutable, so shallow copies are fine */
859                 out = ast_json_copy(blob);
860         }
861
862         if (!out) {
863                 return NULL;
864         }
865
866         res |= ast_json_object_set(out, "type", ast_json_string_create(type));
867         res |= ast_json_object_set(out, "timestamp",
868                 ast_json_timeval(*tv, NULL));
869
870         /* For global channel messages, the snapshot is optional */
871         if (snapshot) {
872                 struct ast_json *json_channel = ast_channel_snapshot_to_json(snapshot, sanitize);
873
874                 if (!json_channel) {
875                         return NULL;
876                 }
877
878                 res |= ast_json_object_set(out, "channel", json_channel);
879         }
880
881         if (res != 0) {
882                 return NULL;
883         }
884
885         return ast_json_ref(out);
886 }
887
888 static struct ast_json *dtmf_end_to_json(
889         struct stasis_message *message,
890         const struct stasis_message_sanitizer *sanitize)
891 {
892         struct ast_channel_blob *channel_blob = stasis_message_data(message);
893         struct ast_json *blob = channel_blob->blob;
894         struct ast_channel_snapshot *snapshot = channel_blob->snapshot;
895         const char *direction =
896                 ast_json_string_get(ast_json_object_get(blob, "direction"));
897         const struct timeval *tv = stasis_message_timestamp(message);
898         struct ast_json *json_channel = ast_channel_snapshot_to_json(snapshot, sanitize);
899
900         /* Only present received DTMF end events as JSON */
901         if (strcasecmp("Received", direction) != 0) {
902                 return NULL;
903         }
904
905         if (!json_channel) {
906                 return NULL;
907         }
908
909         return ast_json_pack("{s: s, s: o, s: O, s: O, s: o}",
910                 "type", "ChannelDtmfReceived",
911                 "timestamp", ast_json_timeval(*tv, NULL),
912                 "digit", ast_json_object_get(blob, "digit"),
913                 "duration_ms", ast_json_object_get(blob, "duration_ms"),
914                 "channel", json_channel);
915 }
916
917 static struct ast_json *user_event_to_json(
918         struct stasis_message *message,
919         const struct stasis_message_sanitizer *sanitize)
920 {
921         struct ast_channel_blob *channel_blob = stasis_message_data(message);
922         struct ast_json *blob = channel_blob->blob;
923         struct ast_channel_snapshot *snapshot = channel_blob->snapshot;
924         const struct timeval *tv = stasis_message_timestamp(message);
925         struct ast_json *json_channel = ast_channel_snapshot_to_json(snapshot, sanitize);
926
927         if (!json_channel) {
928                 return NULL;
929         }
930
931         return ast_json_pack("{s: s, s: o, s: O, s: O, s: o}",
932                 "type", "ChannelUserevent",
933                 "timestamp", ast_json_timeval(*tv, NULL),
934                 "eventname", ast_json_object_get(blob, "eventname"),
935                 "userevent", blob,
936                 "channel", json_channel);
937 }
938
939 static struct ast_json *varset_to_json(
940         struct stasis_message *message,
941         const struct stasis_message_sanitizer *sanitize)
942 {
943         return channel_blob_to_json(message, "ChannelVarset", sanitize);
944 }
945
946 static struct ast_json *hangup_request_to_json(
947         struct stasis_message *message,
948         const struct stasis_message_sanitizer *sanitize)
949 {
950         return channel_blob_to_json(message, "ChannelHangupRequest", sanitize);
951 }
952
953 static struct ast_json *dial_to_json(
954         struct stasis_message *message,
955         const struct stasis_message_sanitizer *sanitize)
956 {
957         struct ast_multi_channel_blob *payload = stasis_message_data(message);
958         struct ast_json *blob = ast_multi_channel_blob_get_json(payload);
959         struct ast_json *caller_json = ast_channel_snapshot_to_json(ast_multi_channel_blob_get_channel(payload, "caller"), sanitize);
960         struct ast_json *peer_json = ast_channel_snapshot_to_json(ast_multi_channel_blob_get_channel(payload, "peer"), sanitize);
961         struct ast_json *forwarded_json = ast_channel_snapshot_to_json(ast_multi_channel_blob_get_channel(payload, "forwarded"), sanitize);
962         struct ast_json *json;
963         const struct timeval *tv = stasis_message_timestamp(message);
964         int res = 0;
965
966         json = ast_json_pack("{s: s, s: o, s: O, s: O, s: O}",
967                 "type", "Dial",
968                 "timestamp", ast_json_timeval(*tv, NULL),
969                 "dialstatus", ast_json_object_get(blob, "dialstatus"),
970                 "forward", ast_json_object_get(blob, "forward"),
971                 "dialstring", ast_json_object_get(blob, "dialstring"));
972         if (!json) {
973                 ast_json_unref(caller_json);
974                 ast_json_unref(peer_json);
975                 ast_json_unref(forwarded_json);
976                 return NULL;
977         }
978
979         if (caller_json) {
980                 res |= ast_json_object_set(json, "caller", caller_json);
981         }
982         if (peer_json) {
983                 res |= ast_json_object_set(json, "peer", peer_json);
984         }
985         if (forwarded_json) {
986                 res |= ast_json_object_set(json, "forwarded", forwarded_json);
987         }
988
989         if (res) {
990                 ast_json_unref(json);
991                 return NULL;
992         }
993
994         return json;
995 }
996
997 /*!
998  * @{ \brief Define channel message types.
999  */
1000 STASIS_MESSAGE_TYPE_DEFN(ast_channel_snapshot_type);
1001 STASIS_MESSAGE_TYPE_DEFN(ast_channel_dial_type,
1002         .to_json = dial_to_json,
1003         );
1004 STASIS_MESSAGE_TYPE_DEFN(ast_channel_varset_type,
1005         .to_ami = varset_to_ami,
1006         .to_json = varset_to_json,
1007         );
1008 STASIS_MESSAGE_TYPE_DEFN(ast_channel_user_event_type,
1009         .to_json = user_event_to_json,
1010         );
1011 STASIS_MESSAGE_TYPE_DEFN(ast_channel_hangup_request_type,
1012         .to_json = hangup_request_to_json,
1013         );
1014 STASIS_MESSAGE_TYPE_DEFN(ast_channel_dtmf_begin_type);
1015 STASIS_MESSAGE_TYPE_DEFN(ast_channel_dtmf_end_type,
1016         .to_json = dtmf_end_to_json,
1017         );
1018 STASIS_MESSAGE_TYPE_DEFN(ast_channel_hold_type);
1019 STASIS_MESSAGE_TYPE_DEFN(ast_channel_unhold_type);
1020 STASIS_MESSAGE_TYPE_DEFN(ast_channel_chanspy_start_type);
1021 STASIS_MESSAGE_TYPE_DEFN(ast_channel_chanspy_stop_type);
1022 STASIS_MESSAGE_TYPE_DEFN(ast_channel_fax_type);
1023 STASIS_MESSAGE_TYPE_DEFN(ast_channel_hangup_handler_type);
1024 STASIS_MESSAGE_TYPE_DEFN(ast_channel_moh_start_type);
1025 STASIS_MESSAGE_TYPE_DEFN(ast_channel_moh_stop_type);
1026 STASIS_MESSAGE_TYPE_DEFN(ast_channel_monitor_start_type);
1027 STASIS_MESSAGE_TYPE_DEFN(ast_channel_monitor_stop_type);
1028 STASIS_MESSAGE_TYPE_DEFN(ast_channel_agent_login_type,
1029         .to_ami = agent_login_to_ami,
1030         );
1031 STASIS_MESSAGE_TYPE_DEFN(ast_channel_agent_logoff_type,
1032         .to_ami = agent_logoff_to_ami,
1033         );
1034
1035 /*! @} */
1036
1037 static void stasis_channels_cleanup(void)
1038 {
1039         stasis_caching_unsubscribe_and_join(channel_by_name_topic);
1040         channel_by_name_topic = NULL;
1041         ao2_cleanup(channel_cache_by_name);
1042         channel_cache_by_name = NULL;
1043         ao2_cleanup(channel_cache_all);
1044         channel_cache_all = NULL;
1045
1046         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_snapshot_type);
1047         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_dial_type);
1048         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_varset_type);
1049         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_user_event_type);
1050         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_hangup_request_type);
1051         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_dtmf_begin_type);
1052         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_dtmf_end_type);
1053         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_hold_type);
1054         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_unhold_type);
1055         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_chanspy_start_type);
1056         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_chanspy_stop_type);
1057         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_fax_type);
1058         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_hangup_handler_type);
1059         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_moh_start_type);
1060         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_moh_stop_type);
1061         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_monitor_start_type);
1062         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_monitor_stop_type);
1063         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_agent_login_type);
1064         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_agent_logoff_type);
1065 }
1066
1067 int ast_stasis_channels_init(void)
1068 {
1069         int res = 0;
1070
1071         ast_register_cleanup(stasis_channels_cleanup);
1072
1073         channel_cache_all = stasis_cp_all_create("ast_channel_topic_all",
1074                 channel_snapshot_get_id);
1075         if (!channel_cache_all) {
1076                 return -1;
1077         }
1078         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_agent_login_type);
1079         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_agent_logoff_type);
1080
1081         channel_cache_by_name = stasis_cache_create(channel_snapshot_get_name);
1082         if (!channel_cache_by_name) {
1083                 return -1;
1084         }
1085
1086         /* This should be initialized before the caching topic */
1087         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_snapshot_type);
1088
1089         channel_by_name_topic = stasis_caching_topic_create(
1090                 stasis_cp_all_topic(channel_cache_all),
1091                 channel_cache_by_name);
1092         if (!channel_by_name_topic) {
1093                 return -1;
1094         }
1095
1096         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_dial_type);
1097         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_varset_type);
1098         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_user_event_type);
1099         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_hangup_request_type);
1100         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_dtmf_begin_type);
1101         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_dtmf_end_type);
1102         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_hold_type);
1103         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_unhold_type);
1104         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_chanspy_start_type);
1105         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_chanspy_stop_type);
1106         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_fax_type);
1107         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_hangup_handler_type);
1108         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_moh_start_type);
1109         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_moh_stop_type);
1110         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_monitor_start_type);
1111         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_monitor_stop_type);
1112
1113         return res;
1114 }