json: Add conditionals to avoid locking if Jansson is thread safe.
[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 #include "asterisk/astobj2.h"
34 #include "asterisk/json.h"
35 #include "asterisk/pbx.h"
36 #include "asterisk/bridge.h"
37 #include "asterisk/translate.h"
38 #include "asterisk/stasis.h"
39 #include "asterisk/stasis_cache_pattern.h"
40 #include "asterisk/stasis_channels.h"
41 #include "asterisk/dial.h"
42 #include "asterisk/linkedlists.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         <managerEvent language="en_US" name="ChannelTalkingStart">
89                 <managerEventInstance class="EVENT_FLAG_CLASS">
90                         <synopsis>Raised when talking is detected on a channel.</synopsis>
91                         <syntax>
92                                 <channel_snapshot/>
93                         </syntax>
94                         <see-also>
95                                 <ref type="function">TALK_DETECT</ref>
96                                 <ref type="managerEvent">ChannelTalkingStop</ref>
97                         </see-also>
98                 </managerEventInstance>
99         </managerEvent>
100         <managerEvent language="en_US" name="ChannelTalkingStop">
101                 <managerEventInstance class="EVENT_FLAG_CLASS">
102                         <synopsis>Raised when talking is no longer detected on a channel.</synopsis>
103                         <syntax>
104                                 <channel_snapshot/>
105                                 <parameter name="Duration">
106                                         <para>The length in time, in milliseconds, that talking was
107                                         detected on the channel.</para>
108                                 </parameter>
109                         </syntax>
110                         <see-also>
111                                 <ref type="function">TALK_DETECT</ref>
112                                 <ref type="managerEvent">ChannelTalkingStart</ref>
113                         </see-also>
114                 </managerEventInstance>
115         </managerEvent>
116 ***/
117
118 #define NUM_MULTI_CHANNEL_BLOB_BUCKETS 7
119
120 static struct stasis_cp_all *channel_cache_all;
121 static struct stasis_cache *channel_cache_by_name;
122 static struct stasis_caching_topic *channel_by_name_topic;
123
124 struct stasis_cp_all *ast_channel_cache_all(void)
125 {
126         return channel_cache_all;
127 }
128
129 struct stasis_cache *ast_channel_cache(void)
130 {
131         return stasis_cp_all_cache(channel_cache_all);
132 }
133
134 struct stasis_topic *ast_channel_topic_all(void)
135 {
136         return stasis_cp_all_topic(channel_cache_all);
137 }
138
139 struct stasis_topic *ast_channel_topic_all_cached(void)
140 {
141         return stasis_cp_all_topic_cached(channel_cache_all);
142 }
143
144 struct stasis_cache *ast_channel_cache_by_name(void)
145 {
146         return channel_cache_by_name;
147 }
148
149 static const char *channel_snapshot_get_id(struct stasis_message *message)
150 {
151         struct ast_channel_snapshot *snapshot;
152         if (ast_channel_snapshot_type() != stasis_message_type(message)) {
153                 return NULL;
154         }
155         snapshot = stasis_message_data(message);
156         return snapshot->uniqueid;
157 }
158
159 static const char *channel_snapshot_get_name(struct stasis_message *message)
160 {
161         struct ast_channel_snapshot *snapshot;
162         if (ast_channel_snapshot_type() != stasis_message_type(message)) {
163                 return NULL;
164         }
165         snapshot = stasis_message_data(message);
166         return snapshot->name;
167 }
168
169 /*!
170  * \internal
171  * \brief Hash function for \ref ast_channel_snapshot objects
172  */
173 static int channel_snapshot_hash_cb(const void *obj, const int flags)
174 {
175         const struct ast_channel_snapshot *object = obj;
176         const char *key;
177
178         switch (flags & OBJ_SEARCH_MASK) {
179         case OBJ_SEARCH_KEY:
180                 key = obj;
181                 break;
182         case OBJ_SEARCH_OBJECT:
183                 key = object->name;
184                 break;
185         default:
186                 ast_assert(0);
187                 return 0;
188         }
189         return ast_str_case_hash(key);
190 }
191
192 /*!
193  * \internal
194  * \brief Comparison function for \ref ast_channel_snapshot objects
195  */
196 static int channel_snapshot_cmp_cb(void *obj, void *arg, int flags)
197 {
198         const struct ast_channel_snapshot *object_left = obj;
199         const struct ast_channel_snapshot *object_right = arg;
200         const char *right_key = arg;
201         int cmp;
202
203         switch (flags & OBJ_SEARCH_MASK) {
204         case OBJ_SEARCH_OBJECT:
205                 right_key = object_right->name;
206         case OBJ_SEARCH_KEY:
207                 cmp = strcasecmp(object_left->name, right_key);
208                 break;
209         case OBJ_SEARCH_PARTIAL_KEY:
210                 cmp = strncasecmp(object_left->name, right_key, strlen(right_key));
211                 break;
212         default:
213                 cmp = 0;
214                 break;
215         }
216         if (cmp) {
217                 return 0;
218         }
219         return CMP_MATCH;
220 }
221
222 static void channel_snapshot_dtor(void *obj)
223 {
224         struct ast_channel_snapshot *snapshot = obj;
225
226         ast_string_field_free_memory(snapshot);
227         ao2_cleanup(snapshot->manager_vars);
228         ao2_cleanup(snapshot->ari_vars);
229 }
230
231 struct ast_channel_snapshot *ast_channel_snapshot_create(struct ast_channel *chan)
232 {
233         struct ast_channel_snapshot *snapshot;
234         struct ast_bridge *bridge;
235
236         /* no snapshots for dummy channels */
237         if (!ast_channel_tech(chan)) {
238                 return NULL;
239         }
240
241         snapshot = ao2_alloc_options(sizeof(*snapshot), channel_snapshot_dtor,
242                 AO2_ALLOC_OPT_LOCK_NOLOCK);
243         if (!snapshot || ast_string_field_init(snapshot, 1024)) {
244                 ao2_cleanup(snapshot);
245                 return NULL;
246         }
247
248         ast_string_field_set(snapshot, name, ast_channel_name(chan));
249         ast_string_field_set(snapshot, type, ast_channel_tech(chan)->type);
250         ast_string_field_set(snapshot, accountcode, ast_channel_accountcode(chan));
251         ast_string_field_set(snapshot, peeraccount, ast_channel_peeraccount(chan));
252         ast_string_field_set(snapshot, userfield, ast_channel_userfield(chan));
253         ast_string_field_set(snapshot, uniqueid, ast_channel_uniqueid(chan));
254         ast_string_field_set(snapshot, linkedid, ast_channel_linkedid(chan));
255         ast_string_field_set(snapshot, hangupsource, ast_channel_hangupsource(chan));
256         if (ast_channel_appl(chan)) {
257                 ast_string_field_set(snapshot, appl, ast_channel_appl(chan));
258         }
259         if (ast_channel_data(chan)) {
260                 ast_string_field_set(snapshot, data, ast_channel_data(chan));
261         }
262         ast_string_field_set(snapshot, context, ast_channel_context(chan));
263         ast_string_field_set(snapshot, exten, ast_channel_exten(chan));
264
265         ast_string_field_set(snapshot, caller_name,
266                 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, ""));
267         ast_string_field_set(snapshot, caller_number,
268                 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, ""));
269         ast_string_field_set(snapshot, caller_subaddr,
270                 S_COR(ast_channel_caller(chan)->id.subaddress.valid, ast_channel_caller(chan)->id.subaddress.str, ""));
271         ast_string_field_set(snapshot, caller_ani,
272                 S_COR(ast_channel_caller(chan)->ani.number.valid, ast_channel_caller(chan)->ani.number.str, ""));
273
274         ast_string_field_set(snapshot, caller_rdnis,
275                 S_COR(ast_channel_redirecting(chan)->from.number.valid, ast_channel_redirecting(chan)->from.number.str, ""));
276
277         ast_string_field_set(snapshot, caller_dnid,
278                 S_OR(ast_channel_dialed(chan)->number.str, ""));
279         ast_string_field_set(snapshot, dialed_subaddr,
280                 S_COR(ast_channel_dialed(chan)->subaddress.valid, ast_channel_dialed(chan)->subaddress.str, ""));
281
282         ast_string_field_set(snapshot, connected_name,
283                 S_COR(ast_channel_connected(chan)->id.name.valid, ast_channel_connected(chan)->id.name.str, ""));
284         ast_string_field_set(snapshot, connected_number,
285                 S_COR(ast_channel_connected(chan)->id.number.valid, ast_channel_connected(chan)->id.number.str, ""));
286
287         ast_string_field_set(snapshot, language, ast_channel_language(chan));
288
289         if ((bridge = ast_channel_get_bridge(chan))) {
290                 if (!ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_INVISIBLE)) {
291                         ast_string_field_set(snapshot, bridgeid, bridge->uniqueid);
292                 }
293                 ao2_cleanup(bridge);
294         }
295
296         snapshot->creationtime = ast_channel_creationtime(chan);
297         snapshot->state = ast_channel_state(chan);
298         snapshot->priority = ast_channel_priority(chan);
299         snapshot->amaflags = ast_channel_amaflags(chan);
300         snapshot->hangupcause = ast_channel_hangupcause(chan);
301         ast_copy_flags(&snapshot->flags, ast_channel_flags(chan), 0xFFFFFFFF);
302         snapshot->caller_pres = ast_party_id_presentation(&ast_channel_caller(chan)->id);
303         ast_set_flag(&snapshot->softhangup_flags, ast_channel_softhangup_internal_flag(chan));
304
305         snapshot->manager_vars = ast_channel_get_manager_vars(chan);
306         snapshot->ari_vars = ast_channel_get_ari_vars(chan);
307         snapshot->tech_properties = ast_channel_tech(chan)->properties;
308
309         return snapshot;
310 }
311
312 static void publish_message_for_channel_topics(struct stasis_message *message, struct ast_channel *chan)
313 {
314         if (chan) {
315                 stasis_publish(ast_channel_topic(chan), message);
316         } else {
317                 stasis_publish(ast_channel_topic_all(), message);
318         }
319 }
320
321 static void channel_blob_dtor(void *obj)
322 {
323         struct ast_channel_blob *event = obj;
324         ao2_cleanup(event->snapshot);
325         ast_json_unref(event->blob);
326 }
327
328 static void ast_channel_publish_dial_internal(struct ast_channel *caller,
329         struct ast_channel *peer, struct ast_channel *forwarded, const char *dialstring,
330         const char *dialstatus, const char *forward)
331 {
332         struct ast_multi_channel_blob *payload;
333         struct stasis_message *msg;
334         struct ast_json *blob;
335         struct ast_channel_snapshot *peer_snapshot;
336
337         if (!ast_channel_dial_type()) {
338                 return;
339         }
340
341         ast_assert(peer != NULL);
342
343         blob = ast_json_pack("{s: s, s: s, s: s}",
344                 "dialstatus", S_OR(dialstatus, ""),
345                 "forward", S_OR(forward, ""),
346                 "dialstring", S_OR(dialstring, ""));
347         if (!blob) {
348                 return;
349         }
350         payload = ast_multi_channel_blob_create(blob);
351         ast_json_unref(blob);
352         if (!payload) {
353                 return;
354         }
355
356         if (caller) {
357                 struct ast_channel_snapshot *caller_snapshot;
358
359                 ast_channel_lock(caller);
360                 if (ast_strlen_zero(dialstatus)) {
361                         caller_snapshot = ast_channel_snapshot_get_latest(ast_channel_uniqueid(caller));
362                 } else {
363                         caller_snapshot = ast_channel_snapshot_create(caller);
364                 }
365                 ast_channel_unlock(caller);
366                 if (!caller_snapshot) {
367                         ao2_ref(payload, -1);
368                         return;
369                 }
370                 ast_multi_channel_blob_add_channel(payload, "caller", caller_snapshot);
371                 ao2_ref(caller_snapshot, -1);
372         }
373
374         ast_channel_lock(peer);
375         if (ast_strlen_zero(dialstatus)) {
376                 peer_snapshot = ast_channel_snapshot_get_latest(ast_channel_uniqueid(peer));
377         } else {
378                 peer_snapshot = ast_channel_snapshot_create(peer);
379         }
380         ast_channel_unlock(peer);
381         if (!peer_snapshot) {
382                 ao2_ref(payload, -1);
383                 return;
384         }
385         ast_multi_channel_blob_add_channel(payload, "peer", peer_snapshot);
386         ao2_ref(peer_snapshot, -1);
387
388         if (forwarded) {
389                 struct ast_channel_snapshot *forwarded_snapshot;
390
391                 ast_channel_lock(forwarded);
392                 forwarded_snapshot = ast_channel_snapshot_create(forwarded);
393                 ast_channel_unlock(forwarded);
394                 if (!forwarded_snapshot) {
395                         ao2_ref(payload, -1);
396                         return;
397                 }
398                 ast_multi_channel_blob_add_channel(payload, "forwarded", forwarded_snapshot);
399                 ao2_ref(forwarded_snapshot, -1);
400         }
401
402         msg = stasis_message_create(ast_channel_dial_type(), payload);
403         ao2_ref(payload, -1);
404         if (msg) {
405                 publish_message_for_channel_topics(msg, caller ?: peer);
406                 ao2_ref(msg, -1);
407         }
408 }
409
410 static void remove_dial_masquerade(struct ast_channel *peer);
411 static void remove_dial_masquerade_caller(struct ast_channel *caller);
412 static int set_dial_masquerade(struct ast_channel *caller,
413         struct ast_channel *peer, const char *dialstring);
414
415 void ast_channel_publish_dial_forward(struct ast_channel *caller, struct ast_channel *peer,
416         struct ast_channel *forwarded, const char *dialstring, const char *dialstatus,
417         const char *forward)
418 {
419         ast_assert(peer != NULL);
420
421         /* XXX With an early bridge the below dial masquerade datastore code could, theoretically,
422          * go away as the act of changing the channel during dialing would be done using the bridge
423          * API itself and not a masquerade.
424          */
425
426         if (caller) {
427                 /*
428                  * Lock two or three channels.
429                  *
430                  * We need to hold the locks to hold off a potential masquerade
431                  * messing up the stasis dial event ordering.
432                  */
433                 for (;; ast_channel_unlock(caller), sched_yield()) {
434                         ast_channel_lock(caller);
435                         if (ast_channel_trylock(peer)) {
436                                 continue;
437                         }
438                         if (forwarded && ast_channel_trylock(forwarded)) {
439                                 ast_channel_unlock(peer);
440                                 continue;
441                         }
442                         break;
443                 }
444
445                 if (ast_strlen_zero(dialstatus)) {
446                         set_dial_masquerade(caller, peer, dialstring);
447                 } else {
448                         remove_dial_masquerade(peer);
449                 }
450         }
451
452         ast_channel_publish_dial_internal(caller, peer, forwarded, dialstring, dialstatus,
453                 forward);
454
455         if (caller) {
456                 if (forwarded) {
457                         ast_channel_unlock(forwarded);
458                 }
459                 ast_channel_unlock(peer);
460                 remove_dial_masquerade_caller(caller);
461                 ast_channel_unlock(caller);
462         }
463 }
464
465 void ast_channel_publish_dial(struct ast_channel *caller, struct ast_channel *peer,
466         const char *dialstring, const char *dialstatus)
467 {
468         ast_channel_publish_dial_forward(caller, peer, NULL, dialstring, dialstatus, NULL);
469 }
470
471 static struct stasis_message *create_channel_blob_message(struct ast_channel_snapshot *snapshot,
472                 struct stasis_message_type *type,
473                 struct ast_json *blob)
474 {
475         struct stasis_message *msg;
476         struct ast_channel_blob *obj;
477
478         obj = ao2_alloc(sizeof(*obj), channel_blob_dtor);
479         if (!obj) {
480                 return NULL;
481         }
482
483         if (snapshot) {
484                 obj->snapshot = snapshot;
485                 ao2_ref(obj->snapshot, +1);
486         }
487         if (!blob) {
488                 blob = ast_json_null();
489         }
490         obj->blob = ast_json_ref(blob);
491
492         msg = stasis_message_create(type, obj);
493         ao2_cleanup(obj);
494         return msg;
495 }
496
497 struct stasis_message *ast_channel_blob_create_from_cache(const char *channel_id,
498                                                struct stasis_message_type *type,
499                                                struct ast_json *blob)
500 {
501         struct ast_channel_snapshot *snapshot;
502         struct stasis_message *msg;
503
504         if (!type) {
505                 return NULL;
506         }
507
508         snapshot = ast_channel_snapshot_get_latest(channel_id);
509         msg = create_channel_blob_message(snapshot, type, blob);
510         ao2_cleanup(snapshot);
511         return msg;
512 }
513
514 struct stasis_message *ast_channel_blob_create(struct ast_channel *chan,
515         struct stasis_message_type *type, struct ast_json *blob)
516 {
517         struct ast_channel_snapshot *snapshot;
518         struct stasis_message *msg;
519
520         if (!type) {
521                 return NULL;
522         }
523
524         snapshot = chan ? ast_channel_snapshot_create(chan) : NULL;
525         msg = create_channel_blob_message(snapshot, type, blob);
526         ao2_cleanup(snapshot);
527         return msg;
528 }
529
530 /*! \brief A channel snapshot wrapper object used in \ref ast_multi_channel_blob objects */
531 struct channel_role_snapshot {
532         struct ast_channel_snapshot *snapshot;  /*!< A channel snapshot */
533         char role[0];                                                   /*!< The role assigned to the channel */
534 };
535
536 /*! \brief A multi channel blob data structure for multi_channel_blob stasis messages */
537 struct ast_multi_channel_blob {
538         struct ao2_container *channel_snapshots;        /*!< A container holding the snapshots */
539         struct ast_json *blob;                                          /*!< A blob of JSON data */
540 };
541
542 /*!
543  * \internal
544  * \brief Comparison function for \ref channel_role_snapshot objects
545  */
546 static int channel_role_cmp_cb(void *obj, void *arg, int flags)
547 {
548         const struct channel_role_snapshot *object_left = obj;
549         const struct channel_role_snapshot *object_right = arg;
550         const char *right_key = arg;
551         int cmp;
552
553         switch (flags & OBJ_SEARCH_MASK) {
554         case OBJ_SEARCH_OBJECT:
555                 right_key = object_right->role;
556         case OBJ_SEARCH_KEY:
557                 cmp = strcasecmp(object_left->role, right_key);
558                 break;
559         case OBJ_SEARCH_PARTIAL_KEY:
560                 cmp = strncasecmp(object_left->role, right_key, strlen(right_key));
561                 break;
562         default:
563                 cmp = 0;
564                 break;
565         }
566         if (cmp) {
567                 return 0;
568         }
569         return CMP_MATCH;
570 }
571
572 /*!
573  * \internal
574  * \brief Hash function for \ref channel_role_snapshot objects
575  */
576 static int channel_role_hash_cb(const void *obj, const int flags)
577 {
578         const struct channel_role_snapshot *object = obj;
579         const char *key;
580
581         switch (flags & OBJ_SEARCH_MASK) {
582         case OBJ_SEARCH_KEY:
583                 key = obj;
584                 break;
585         case OBJ_SEARCH_OBJECT:
586                 key = object->role;
587                 break;
588         default:
589                 ast_assert(0);
590                 return 0;
591         }
592         return ast_str_case_hash(key);
593 }
594
595 /*!
596  * \internal
597  * \brief Destructor for \ref ast_multi_channel_blob objects
598  */
599 static void multi_channel_blob_dtor(void *obj)
600 {
601         struct ast_multi_channel_blob *multi_blob = obj;
602
603         ao2_cleanup(multi_blob->channel_snapshots);
604         ast_json_unref(multi_blob->blob);
605 }
606
607 struct ast_multi_channel_blob *ast_multi_channel_blob_create(struct ast_json *blob)
608 {
609         struct ast_multi_channel_blob *obj;
610
611         ast_assert(blob != NULL);
612
613         obj = ao2_alloc(sizeof(*obj), multi_channel_blob_dtor);
614         if (!obj) {
615                 return NULL;
616         }
617
618         obj->channel_snapshots = ao2_container_alloc(NUM_MULTI_CHANNEL_BLOB_BUCKETS,
619                 channel_role_hash_cb, channel_role_cmp_cb);
620         if (!obj->channel_snapshots) {
621                 ao2_ref(obj, -1);
622                 return NULL;
623         }
624
625         obj->blob = ast_json_ref(blob);
626         return obj;
627 }
628
629 struct ast_channel_snapshot *ast_channel_snapshot_get_latest(const char *uniqueid)
630 {
631         struct stasis_message *message;
632         struct ast_channel_snapshot *snapshot;
633
634         ast_assert(!ast_strlen_zero(uniqueid));
635
636         message = stasis_cache_get(ast_channel_cache(), ast_channel_snapshot_type(),
637                 uniqueid);
638         if (!message) {
639                 return NULL;
640         }
641
642         snapshot = ao2_bump(stasis_message_data(message));
643         ao2_ref(message, -1);
644         return snapshot;
645 }
646
647 struct ast_channel_snapshot *ast_channel_snapshot_get_latest_by_name(const char *name)
648 {
649         struct stasis_message *message;
650         struct ast_channel_snapshot *snapshot;
651
652         ast_assert(!ast_strlen_zero(name));
653
654         message = stasis_cache_get(ast_channel_cache_by_name(), ast_channel_snapshot_type(),
655                 name);
656         if (!message) {
657                 return NULL;
658         }
659
660         snapshot = ao2_bump(stasis_message_data(message));
661         ao2_ref(message, -1);
662         return snapshot;
663 }
664
665 static void channel_role_snapshot_dtor(void *obj)
666 {
667         struct channel_role_snapshot *role_snapshot = obj;
668
669         ao2_cleanup(role_snapshot->snapshot);
670 }
671
672 void ast_multi_channel_blob_add_channel(struct ast_multi_channel_blob *obj, const char *role, struct ast_channel_snapshot *snapshot)
673 {
674         struct channel_role_snapshot *role_snapshot;
675         int role_len = strlen(role) + 1;
676
677         if (!obj || ast_strlen_zero(role) || !snapshot) {
678                 return;
679         }
680
681         role_snapshot = ao2_alloc_options(sizeof(*role_snapshot) + role_len,
682                 channel_role_snapshot_dtor, AO2_ALLOC_OPT_LOCK_NOLOCK);
683         if (!role_snapshot) {
684                 return;
685         }
686         ast_copy_string(role_snapshot->role, role, role_len);
687         role_snapshot->snapshot = snapshot;
688         ao2_ref(role_snapshot->snapshot, +1);
689         ao2_link(obj->channel_snapshots, role_snapshot);
690         ao2_ref(role_snapshot, -1);
691 }
692
693 struct ast_channel_snapshot *ast_multi_channel_blob_get_channel(struct ast_multi_channel_blob *obj, const char *role)
694 {
695         struct channel_role_snapshot *role_snapshot;
696         struct ast_channel_snapshot *snapshot;
697
698         if (!obj || ast_strlen_zero(role)) {
699                 return NULL;
700         }
701         role_snapshot = ao2_find(obj->channel_snapshots, role, OBJ_SEARCH_KEY);
702         /* Note that this function does not increase the ref count on snapshot */
703         if (!role_snapshot) {
704                 return NULL;
705         }
706         snapshot = role_snapshot->snapshot;
707         ao2_ref(role_snapshot, -1);
708         return snapshot;
709 }
710
711 struct ao2_container *ast_multi_channel_blob_get_channels(struct ast_multi_channel_blob *obj, const char *role)
712 {
713         struct ao2_container *ret_container;
714         struct ao2_iterator *it_role_snapshots;
715         struct channel_role_snapshot *role_snapshot;
716         char *arg;
717
718         if (!obj || ast_strlen_zero(role)) {
719                 return NULL;
720         }
721
722         ret_container = ao2_container_alloc(NUM_MULTI_CHANNEL_BLOB_BUCKETS,
723                 channel_snapshot_hash_cb, channel_snapshot_cmp_cb);
724         if (!ret_container) {
725                 return NULL;
726         }
727
728         arg = ast_strdupa(role);
729         it_role_snapshots = ao2_callback(obj->channel_snapshots,
730                 OBJ_MULTIPLE | OBJ_SEARCH_KEY, channel_role_cmp_cb, arg);
731         if (!it_role_snapshots) {
732                 ao2_ref(ret_container, -1);
733                 return NULL;
734         }
735
736         while ((role_snapshot = ao2_iterator_next(it_role_snapshots))) {
737                 ao2_link(ret_container, role_snapshot->snapshot);
738                 ao2_ref(role_snapshot, -1);
739         }
740         ao2_iterator_destroy(it_role_snapshots);
741
742         return ret_container;
743 }
744
745 struct ast_json *ast_multi_channel_blob_get_json(struct ast_multi_channel_blob *obj)
746 {
747         if (!obj) {
748                 return NULL;
749         }
750         return obj->blob;
751 }
752
753 void ast_channel_stage_snapshot(struct ast_channel *chan)
754 {
755         ast_set_flag(ast_channel_flags(chan), AST_FLAG_SNAPSHOT_STAGE);
756 }
757
758 void ast_channel_stage_snapshot_done(struct ast_channel *chan)
759 {
760         ast_clear_flag(ast_channel_flags(chan), AST_FLAG_SNAPSHOT_STAGE);
761         ast_channel_publish_snapshot(chan);
762 }
763
764 void ast_channel_publish_snapshot(struct ast_channel *chan)
765 {
766         struct ast_channel_snapshot *snapshot;
767         struct stasis_message *message;
768
769         if (!ast_channel_snapshot_type()) {
770                 return;
771         }
772
773         if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_SNAPSHOT_STAGE)) {
774                 return;
775         }
776
777         snapshot = ast_channel_snapshot_create(chan);
778         if (!snapshot) {
779                 return;
780         }
781
782         message = stasis_message_create(ast_channel_snapshot_type(), snapshot);
783         ao2_ref(snapshot, -1);
784         if (!message) {
785                 return;
786         }
787
788         ast_assert(ast_channel_topic(chan) != NULL);
789         stasis_publish(ast_channel_topic(chan), message);
790         ao2_ref(message, -1);
791 }
792
793 void ast_channel_publish_cached_blob(struct ast_channel *chan, struct stasis_message_type *type, struct ast_json *blob)
794 {
795         struct stasis_message *message;
796
797         if (!blob) {
798                 blob = ast_json_null();
799         }
800
801         message = ast_channel_blob_create_from_cache(ast_channel_uniqueid(chan), type, blob);
802         if (message) {
803                 stasis_publish(ast_channel_topic(chan), message);
804                 ao2_ref(message, -1);
805         }
806 }
807
808 void ast_channel_publish_blob(struct ast_channel *chan, struct stasis_message_type *type, struct ast_json *blob)
809 {
810         struct stasis_message *message;
811
812         if (!blob) {
813                 blob = ast_json_null();
814         }
815
816         message = ast_channel_blob_create(chan, type, blob);
817         if (message) {
818                 stasis_publish(ast_channel_topic(chan), message);
819                 ao2_ref(message, -1);
820         }
821 }
822
823 void ast_channel_publish_varset(struct ast_channel *chan, const char *name, const char *value)
824 {
825         struct ast_json *blob;
826
827         ast_assert(name != NULL);
828         ast_assert(value != NULL);
829
830         blob = ast_json_pack("{s: s, s: s}",
831                              "variable", name,
832                              "value", value);
833         if (!blob) {
834                 ast_log(LOG_ERROR, "Error creating message\n");
835                 return;
836         }
837
838         /*! If there are manager variables, force a cache update */
839         if (chan && ast_channel_has_manager_vars()) {
840                 ast_channel_publish_snapshot(chan);
841         }
842
843         if (chan) {
844                 ast_channel_publish_cached_blob(chan, ast_channel_varset_type(), blob);
845         } else {
846                 /* This function is NULL safe for global variables */
847                 ast_channel_publish_blob(NULL, ast_channel_varset_type(), blob);
848         }
849
850         ast_json_unref(blob);
851 }
852
853 static struct ast_manager_event_blob *varset_to_ami(struct stasis_message *msg)
854 {
855         struct ast_str *channel_event_string;
856         struct ast_channel_blob *obj = stasis_message_data(msg);
857         const char *variable =
858                 ast_json_string_get(ast_json_object_get(obj->blob, "variable"));
859         char *value;
860         struct ast_manager_event_blob *ev;
861
862         value = ast_escape_c_alloc(ast_json_string_get(ast_json_object_get(obj->blob,
863                 "value")));
864         if (!value) {
865                 return NULL;
866         }
867
868         if (obj->snapshot) {
869                 channel_event_string = ast_manager_build_channel_state_string(obj->snapshot);
870         } else {
871                 channel_event_string = ast_str_create(35);
872                 ast_str_set(&channel_event_string, 0,
873                         "Channel: none\r\n"
874                         "Uniqueid: none\r\n");
875         }
876         if (!channel_event_string) {
877                 ast_free(value);
878                 return NULL;
879         }
880
881         ev = ast_manager_event_blob_create(EVENT_FLAG_DIALPLAN, "VarSet",
882                 "%s"
883                 "Variable: %s\r\n"
884                 "Value: %s\r\n",
885                 ast_str_buffer(channel_event_string), variable, value);
886         ast_free(channel_event_string);
887         ast_free(value);
888         return ev;
889 }
890
891 static struct ast_manager_event_blob *agent_login_to_ami(struct stasis_message *msg)
892 {
893         struct ast_str *channel_string;
894         struct ast_channel_blob *obj = stasis_message_data(msg);
895         const char *agent = ast_json_string_get(ast_json_object_get(obj->blob, "agent"));
896         struct ast_manager_event_blob *ev;
897
898         channel_string = ast_manager_build_channel_state_string(obj->snapshot);
899         if (!channel_string) {
900                 return NULL;
901         }
902
903         ev = ast_manager_event_blob_create(EVENT_FLAG_AGENT, "AgentLogin",
904                 "%s"
905                 "Agent: %s\r\n",
906                 ast_str_buffer(channel_string), agent);
907         ast_free(channel_string);
908         return ev;
909 }
910
911 static struct ast_manager_event_blob *agent_logoff_to_ami(struct stasis_message *msg)
912 {
913         struct ast_str *channel_string;
914         struct ast_channel_blob *obj = stasis_message_data(msg);
915         const char *agent = ast_json_string_get(ast_json_object_get(obj->blob, "agent"));
916         long logintime = ast_json_integer_get(ast_json_object_get(obj->blob, "logintime"));
917         struct ast_manager_event_blob *ev;
918
919         channel_string = ast_manager_build_channel_state_string(obj->snapshot);
920         if (!channel_string) {
921                 return NULL;
922         }
923
924         ev = ast_manager_event_blob_create(EVENT_FLAG_AGENT, "AgentLogoff",
925                 "%s"
926                 "Agent: %s\r\n"
927                 "Logintime: %ld\r\n",
928                 ast_str_buffer(channel_string), agent, logintime);
929         ast_free(channel_string);
930         return ev;
931 }
932
933 void ast_publish_channel_state(struct ast_channel *chan)
934 {
935         struct ast_channel_snapshot *snapshot;
936         struct stasis_message *message;
937
938         if (!ast_channel_snapshot_type()) {
939                 return;
940         }
941
942         ast_assert(chan != NULL);
943         if (!chan) {
944                 return;
945         }
946
947         snapshot = ast_channel_snapshot_create(chan);
948         if (!snapshot) {
949                 return;
950         }
951
952         message = stasis_message_create(ast_channel_snapshot_type(), snapshot);
953         ao2_ref(snapshot, -1);
954         if (!message) {
955                 return;
956         }
957
958         ast_assert(ast_channel_topic(chan) != NULL);
959         stasis_publish(ast_channel_topic(chan), message);
960         ao2_ref(message, -1);
961 }
962
963 struct ast_json *ast_channel_snapshot_to_json(
964         const struct ast_channel_snapshot *snapshot,
965         const struct stasis_message_sanitizer *sanitize)
966 {
967         struct ast_json *json_chan;
968
969         if (snapshot == NULL
970                 || (sanitize
971                         && sanitize->channel_snapshot
972                         && sanitize->channel_snapshot(snapshot))) {
973                 return NULL;
974         }
975
976         json_chan = ast_json_pack(
977                 /* Broken up into groups of three for readability */
978                 "{ s: s, s: s, s: s,"
979                 "  s: o, s: o, s: s,"
980                 "  s: o, s: o, s: s }",
981                 /* First line */
982                 "id", snapshot->uniqueid,
983                 "name", snapshot->name,
984                 "state", ast_state2str(snapshot->state),
985                 /* Second line */
986                 "caller", ast_json_name_number(
987                         snapshot->caller_name, snapshot->caller_number),
988                 "connected", ast_json_name_number(
989                         snapshot->connected_name, snapshot->connected_number),
990                 "accountcode", snapshot->accountcode,
991                 /* Third line */
992                 "dialplan", ast_json_dialplan_cep(
993                         snapshot->context, snapshot->exten, snapshot->priority),
994                 "creationtime", ast_json_timeval(snapshot->creationtime, NULL),
995                 "language", snapshot->language);
996
997         if (snapshot->ari_vars && !AST_LIST_EMPTY(snapshot->ari_vars)) {
998                 ast_json_object_set(json_chan, "channelvars", ast_json_channel_vars(snapshot->ari_vars));
999         }
1000
1001         return json_chan;
1002 }
1003
1004 int ast_channel_snapshot_cep_equal(
1005         const struct ast_channel_snapshot *old_snapshot,
1006         const struct ast_channel_snapshot *new_snapshot)
1007 {
1008         ast_assert(old_snapshot != NULL);
1009         ast_assert(new_snapshot != NULL);
1010
1011         /* We actually get some snapshots with CEP set, but before the
1012          * application is set. Since empty application is invalid, we treat
1013          * setting the application from nothing as a CEP change.
1014          */
1015         if (ast_strlen_zero(old_snapshot->appl) &&
1016             !ast_strlen_zero(new_snapshot->appl)) {
1017                 return 0;
1018         }
1019
1020         return old_snapshot->priority == new_snapshot->priority &&
1021                 strcmp(old_snapshot->context, new_snapshot->context) == 0 &&
1022                 strcmp(old_snapshot->exten, new_snapshot->exten) == 0;
1023 }
1024
1025 int ast_channel_snapshot_caller_id_equal(
1026         const struct ast_channel_snapshot *old_snapshot,
1027         const struct ast_channel_snapshot *new_snapshot)
1028 {
1029         ast_assert(old_snapshot != NULL);
1030         ast_assert(new_snapshot != NULL);
1031         return strcmp(old_snapshot->caller_number, new_snapshot->caller_number) == 0 &&
1032                 strcmp(old_snapshot->caller_name, new_snapshot->caller_name) == 0;
1033 }
1034
1035 int ast_channel_snapshot_connected_line_equal(
1036         const struct ast_channel_snapshot *old_snapshot,
1037         const struct ast_channel_snapshot *new_snapshot)
1038 {
1039         ast_assert(old_snapshot != NULL);
1040         ast_assert(new_snapshot != NULL);
1041         return strcmp(old_snapshot->connected_number, new_snapshot->connected_number) == 0 &&
1042                 strcmp(old_snapshot->connected_name, new_snapshot->connected_name) == 0;
1043 }
1044
1045 static struct ast_json *channel_blob_to_json(
1046         struct stasis_message *message,
1047         const char *type,
1048         const struct stasis_message_sanitizer *sanitize)
1049 {
1050         struct ast_json *to_json;
1051         struct ast_channel_blob *channel_blob = stasis_message_data(message);
1052         struct ast_json *blob = channel_blob->blob;
1053         struct ast_channel_snapshot *snapshot = channel_blob->snapshot;
1054         const struct timeval *tv = stasis_message_timestamp(message);
1055         int res = 0;
1056
1057         if (blob == NULL || ast_json_is_null(blob)) {
1058                 to_json = ast_json_object_create();
1059         } else {
1060                 /* blobs are immutable, so shallow copies are fine */
1061                 to_json = ast_json_copy(blob);
1062         }
1063         if (!to_json) {
1064                 return NULL;
1065         }
1066
1067         res |= ast_json_object_set(to_json, "type", ast_json_string_create(type));
1068         res |= ast_json_object_set(to_json, "timestamp",
1069                 ast_json_timeval(*tv, NULL));
1070
1071         /* For global channel messages, the snapshot is optional */
1072         if (snapshot) {
1073                 struct ast_json *json_channel;
1074
1075                 json_channel = ast_channel_snapshot_to_json(snapshot, sanitize);
1076                 if (!json_channel) {
1077                         ast_json_unref(to_json);
1078                         return NULL;
1079                 }
1080
1081                 res |= ast_json_object_set(to_json, "channel", json_channel);
1082         }
1083
1084         if (res != 0) {
1085                 ast_json_unref(to_json);
1086                 return NULL;
1087         }
1088
1089         return to_json;
1090 }
1091
1092 static struct ast_json *dtmf_end_to_json(
1093         struct stasis_message *message,
1094         const struct stasis_message_sanitizer *sanitize)
1095 {
1096         struct ast_channel_blob *channel_blob = stasis_message_data(message);
1097         struct ast_json *blob = channel_blob->blob;
1098         struct ast_channel_snapshot *snapshot = channel_blob->snapshot;
1099         const char *direction =
1100                 ast_json_string_get(ast_json_object_get(blob, "direction"));
1101         const char *digit =
1102                 ast_json_string_get(ast_json_object_get(blob, "digit"));
1103         long duration_ms =
1104                 ast_json_integer_get(ast_json_object_get(blob, "duration_ms"));
1105         const struct timeval *tv = stasis_message_timestamp(message);
1106         struct ast_json *json_channel;
1107
1108         /* Only present received DTMF end events as JSON */
1109         if (strcasecmp("Received", direction) != 0) {
1110                 return NULL;
1111         }
1112
1113         json_channel = ast_channel_snapshot_to_json(snapshot, sanitize);
1114         if (!json_channel) {
1115                 return NULL;
1116         }
1117
1118         return ast_json_pack("{s: s, s: o, s: s, s: i, s: o}",
1119                 "type", "ChannelDtmfReceived",
1120                 "timestamp", ast_json_timeval(*tv, NULL),
1121                 "digit", digit,
1122                 "duration_ms", duration_ms,
1123                 "channel", json_channel);
1124 }
1125
1126 static struct ast_json *varset_to_json(
1127         struct stasis_message *message,
1128         const struct stasis_message_sanitizer *sanitize)
1129 {
1130         return channel_blob_to_json(message, "ChannelVarset", sanitize);
1131 }
1132
1133 static struct ast_json *hangup_request_to_json(
1134         struct stasis_message *message,
1135         const struct stasis_message_sanitizer *sanitize)
1136 {
1137         return channel_blob_to_json(message, "ChannelHangupRequest", sanitize);
1138 }
1139
1140 static struct ast_json *dial_to_json(
1141         struct stasis_message *message,
1142         const struct stasis_message_sanitizer *sanitize)
1143 {
1144         struct ast_multi_channel_blob *payload = stasis_message_data(message);
1145         struct ast_json *blob = ast_multi_channel_blob_get_json(payload);
1146         const char *dialstatus =
1147                 ast_json_string_get(ast_json_object_get(blob, "dialstatus"));
1148         const char *forward =
1149                 ast_json_string_get(ast_json_object_get(blob, "forward"));
1150         const char *dialstring =
1151                 ast_json_string_get(ast_json_object_get(blob, "dialstring"));
1152         struct ast_json *caller_json = ast_channel_snapshot_to_json(ast_multi_channel_blob_get_channel(payload, "caller"), sanitize);
1153         struct ast_json *peer_json = ast_channel_snapshot_to_json(ast_multi_channel_blob_get_channel(payload, "peer"), sanitize);
1154         struct ast_json *forwarded_json = ast_channel_snapshot_to_json(ast_multi_channel_blob_get_channel(payload, "forwarded"), sanitize);
1155         struct ast_json *json;
1156         const struct timeval *tv = stasis_message_timestamp(message);
1157         int res = 0;
1158
1159         json = ast_json_pack("{s: s, s: o, s: s, s: s, s: s}",
1160                 "type", "Dial",
1161                 "timestamp", ast_json_timeval(*tv, NULL),
1162                 "dialstatus", dialstatus,
1163                 "forward", forward,
1164                 "dialstring", dialstring);
1165         if (!json) {
1166                 ast_json_unref(caller_json);
1167                 ast_json_unref(peer_json);
1168                 ast_json_unref(forwarded_json);
1169                 return NULL;
1170         }
1171
1172         if (caller_json) {
1173                 res |= ast_json_object_set(json, "caller", caller_json);
1174         }
1175         if (peer_json) {
1176                 res |= ast_json_object_set(json, "peer", peer_json);
1177         }
1178         if (forwarded_json) {
1179                 res |= ast_json_object_set(json, "forwarded", forwarded_json);
1180         }
1181
1182         if (res) {
1183                 ast_json_unref(json);
1184                 return NULL;
1185         }
1186
1187         return json;
1188 }
1189
1190 static struct ast_manager_event_blob *talking_start_to_ami(struct stasis_message *msg)
1191 {
1192         struct ast_str *channel_string;
1193         struct ast_channel_blob *obj = stasis_message_data(msg);
1194         struct ast_manager_event_blob *blob;
1195
1196         channel_string = ast_manager_build_channel_state_string(obj->snapshot);
1197         if (!channel_string) {
1198                 return NULL;
1199         }
1200
1201         blob = ast_manager_event_blob_create(EVENT_FLAG_CALL, "ChannelTalkingStart",
1202                                              "%s", ast_str_buffer(channel_string));
1203         ast_free(channel_string);
1204
1205         return blob;
1206 }
1207
1208 static struct ast_json *talking_start_to_json(struct stasis_message *message,
1209         const struct stasis_message_sanitizer *sanitize)
1210 {
1211         return channel_blob_to_json(message, "ChannelTalkingStarted", sanitize);
1212 }
1213
1214 static struct ast_manager_event_blob *talking_stop_to_ami(struct stasis_message *msg)
1215 {
1216         struct ast_str *channel_string;
1217         struct ast_channel_blob *obj = stasis_message_data(msg);
1218         int duration = ast_json_integer_get(ast_json_object_get(obj->blob, "duration"));
1219         struct ast_manager_event_blob *blob;
1220
1221         channel_string = ast_manager_build_channel_state_string(obj->snapshot);
1222         if (!channel_string) {
1223                 return NULL;
1224         }
1225
1226         blob = ast_manager_event_blob_create(EVENT_FLAG_CALL, "ChannelTalkingStop",
1227                                              "%s"
1228                                              "Duration: %d\r\n",
1229                                              ast_str_buffer(channel_string),
1230                                              duration);
1231         ast_free(channel_string);
1232
1233         return blob;
1234 }
1235
1236 static struct ast_json *talking_stop_to_json(struct stasis_message *message,
1237         const struct stasis_message_sanitizer *sanitize)
1238 {
1239         return channel_blob_to_json(message, "ChannelTalkingFinished", sanitize);
1240 }
1241
1242 static struct ast_json *hold_to_json(struct stasis_message *message,
1243         const struct stasis_message_sanitizer *sanitize)
1244 {
1245         struct ast_channel_blob *channel_blob = stasis_message_data(message);
1246         struct ast_json *blob = channel_blob->blob;
1247         struct ast_channel_snapshot *snapshot = channel_blob->snapshot;
1248         const char *musicclass = ast_json_string_get(ast_json_object_get(blob, "musicclass"));
1249         const struct timeval *tv = stasis_message_timestamp(message);
1250         struct ast_json *json_channel;
1251
1252         json_channel = ast_channel_snapshot_to_json(snapshot, sanitize);
1253         if (!json_channel) {
1254                 return NULL;
1255         }
1256
1257         return ast_json_pack("{s: s, s: o, s: s, s: o}",
1258                 "type", "ChannelHold",
1259                 "timestamp", ast_json_timeval(*tv, NULL),
1260                 "musicclass", S_OR(musicclass, "N/A"),
1261                 "channel", json_channel);
1262 }
1263
1264 static struct ast_json *unhold_to_json(struct stasis_message *message,
1265         const struct stasis_message_sanitizer *sanitize)
1266 {
1267         struct ast_channel_blob *channel_blob = stasis_message_data(message);
1268         struct ast_channel_snapshot *snapshot = channel_blob->snapshot;
1269         const struct timeval *tv = stasis_message_timestamp(message);
1270         struct ast_json *json_channel;
1271
1272         json_channel = ast_channel_snapshot_to_json(snapshot, sanitize);
1273         if (!json_channel) {
1274                 return NULL;
1275         }
1276
1277         return ast_json_pack("{s: s, s: o, s: o}",
1278                 "type", "ChannelUnhold",
1279                 "timestamp", ast_json_timeval(*tv, NULL),
1280                 "channel", json_channel);
1281 }
1282
1283 /*!
1284  * @{ \brief Define channel message types.
1285  */
1286 STASIS_MESSAGE_TYPE_DEFN(ast_channel_snapshot_type);
1287 STASIS_MESSAGE_TYPE_DEFN(ast_channel_dial_type,
1288         .to_json = dial_to_json,
1289         );
1290 STASIS_MESSAGE_TYPE_DEFN(ast_channel_varset_type,
1291         .to_ami = varset_to_ami,
1292         .to_json = varset_to_json,
1293         );
1294 STASIS_MESSAGE_TYPE_DEFN(ast_channel_hangup_request_type,
1295         .to_json = hangup_request_to_json,
1296         );
1297 STASIS_MESSAGE_TYPE_DEFN(ast_channel_dtmf_begin_type);
1298 STASIS_MESSAGE_TYPE_DEFN(ast_channel_dtmf_end_type,
1299         .to_json = dtmf_end_to_json,
1300         );
1301 STASIS_MESSAGE_TYPE_DEFN(ast_channel_hold_type,
1302         .to_json = hold_to_json,
1303         );
1304 STASIS_MESSAGE_TYPE_DEFN(ast_channel_unhold_type,
1305         .to_json = unhold_to_json,
1306         );
1307 STASIS_MESSAGE_TYPE_DEFN(ast_channel_chanspy_start_type);
1308 STASIS_MESSAGE_TYPE_DEFN(ast_channel_chanspy_stop_type);
1309 STASIS_MESSAGE_TYPE_DEFN(ast_channel_fax_type);
1310 STASIS_MESSAGE_TYPE_DEFN(ast_channel_hangup_handler_type);
1311 STASIS_MESSAGE_TYPE_DEFN(ast_channel_moh_start_type);
1312 STASIS_MESSAGE_TYPE_DEFN(ast_channel_moh_stop_type);
1313 STASIS_MESSAGE_TYPE_DEFN(ast_channel_monitor_start_type);
1314 STASIS_MESSAGE_TYPE_DEFN(ast_channel_monitor_stop_type);
1315 STASIS_MESSAGE_TYPE_DEFN(ast_channel_agent_login_type,
1316         .to_ami = agent_login_to_ami,
1317         );
1318 STASIS_MESSAGE_TYPE_DEFN(ast_channel_agent_logoff_type,
1319         .to_ami = agent_logoff_to_ami,
1320         );
1321 STASIS_MESSAGE_TYPE_DEFN(ast_channel_talking_start,
1322         .to_ami = talking_start_to_ami,
1323         .to_json = talking_start_to_json,
1324         );
1325 STASIS_MESSAGE_TYPE_DEFN(ast_channel_talking_stop,
1326         .to_ami = talking_stop_to_ami,
1327         .to_json = talking_stop_to_json,
1328         );
1329
1330 /*! @} */
1331
1332 static void stasis_channels_cleanup(void)
1333 {
1334         stasis_caching_unsubscribe_and_join(channel_by_name_topic);
1335         channel_by_name_topic = NULL;
1336         ao2_cleanup(channel_cache_by_name);
1337         channel_cache_by_name = NULL;
1338         ao2_cleanup(channel_cache_all);
1339         channel_cache_all = NULL;
1340
1341         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_snapshot_type);
1342         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_dial_type);
1343         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_varset_type);
1344         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_hangup_request_type);
1345         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_dtmf_begin_type);
1346         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_dtmf_end_type);
1347         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_hold_type);
1348         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_unhold_type);
1349         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_chanspy_start_type);
1350         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_chanspy_stop_type);
1351         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_fax_type);
1352         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_hangup_handler_type);
1353         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_moh_start_type);
1354         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_moh_stop_type);
1355         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_monitor_start_type);
1356         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_monitor_stop_type);
1357         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_agent_login_type);
1358         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_agent_logoff_type);
1359         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_talking_start);
1360         STASIS_MESSAGE_TYPE_CLEANUP(ast_channel_talking_stop);
1361 }
1362
1363 int ast_stasis_channels_init(void)
1364 {
1365         int res = 0;
1366
1367         ast_register_cleanup(stasis_channels_cleanup);
1368
1369         channel_cache_all = stasis_cp_all_create("ast_channel_topic_all",
1370                 channel_snapshot_get_id);
1371         if (!channel_cache_all) {
1372                 return -1;
1373         }
1374         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_agent_login_type);
1375         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_agent_logoff_type);
1376
1377         channel_cache_by_name = stasis_cache_create(channel_snapshot_get_name);
1378         if (!channel_cache_by_name) {
1379                 return -1;
1380         }
1381
1382         /* This should be initialized before the caching topic */
1383         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_snapshot_type);
1384
1385         channel_by_name_topic = stasis_caching_topic_create(
1386                 stasis_cp_all_topic(channel_cache_all),
1387                 channel_cache_by_name);
1388         if (!channel_by_name_topic) {
1389                 return -1;
1390         }
1391
1392         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_dial_type);
1393         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_varset_type);
1394         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_hangup_request_type);
1395         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_dtmf_begin_type);
1396         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_dtmf_end_type);
1397         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_hold_type);
1398         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_unhold_type);
1399         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_chanspy_start_type);
1400         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_chanspy_stop_type);
1401         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_fax_type);
1402         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_hangup_handler_type);
1403         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_moh_start_type);
1404         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_moh_stop_type);
1405         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_monitor_start_type);
1406         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_monitor_stop_type);
1407         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_talking_start);
1408         res |= STASIS_MESSAGE_TYPE_INIT(ast_channel_talking_stop);
1409
1410         return res;
1411 }
1412
1413 /*!
1414  * \internal
1415  * \brief A list element for the dial_masquerade_datastore -- stores data about a dialed peer
1416  */
1417 struct dial_target {
1418         /*! Called party channel. */
1419         struct ast_channel *peer;
1420         /*! Dialstring used to call the peer. */
1421         char *dialstring;
1422         /*! Next entry in the list. */
1423         AST_LIST_ENTRY(dial_target) list;
1424 };
1425
1426 static void dial_target_free(struct dial_target *doomed)
1427 {
1428         if (!doomed) {
1429                 return;
1430         }
1431         ast_free(doomed->dialstring);
1432         ast_channel_cleanup(doomed->peer);
1433         ast_free(doomed);
1434 }
1435
1436 /*!
1437  * \internal
1438  * \brief Datastore used for advancing dial state in the case of a masquerade
1439  *        against a channel in the process of dialing.
1440  */
1441 struct dial_masquerade_datastore {
1442         /*! Calling party channel. */
1443         struct ast_channel *caller;
1444         /*! List of called peers. */
1445         AST_LIST_HEAD_NOLOCK(, dial_target) dialed_peers;
1446 };
1447
1448 static void dial_masquerade_datastore_cleanup(struct dial_masquerade_datastore *masq_data)
1449 {
1450         struct dial_target *cur;
1451
1452         while ((cur = AST_LIST_REMOVE_HEAD(&masq_data->dialed_peers, list))) {
1453                 dial_target_free(cur);
1454         }
1455 }
1456
1457 static void dial_masquerade_datastore_remove_chan(struct dial_masquerade_datastore *masq_data, struct ast_channel *chan)
1458 {
1459         struct dial_target *cur;
1460
1461         ao2_lock(masq_data);
1462         if (masq_data->caller == chan) {
1463                 dial_masquerade_datastore_cleanup(masq_data);
1464         } else {
1465                 AST_LIST_TRAVERSE_SAFE_BEGIN(&masq_data->dialed_peers, cur, list) {
1466                         if (cur->peer == chan) {
1467                                 AST_LIST_REMOVE_CURRENT(list);
1468                                 dial_target_free(cur);
1469                                 break;
1470                         }
1471                 }
1472                 AST_LIST_TRAVERSE_SAFE_END;
1473         }
1474         ao2_unlock(masq_data);
1475 }
1476
1477 static void dial_masquerade_datastore_dtor(void *vdoomed)
1478 {
1479         dial_masquerade_datastore_cleanup(vdoomed);
1480 }
1481
1482 static struct dial_masquerade_datastore *dial_masquerade_datastore_alloc(void)
1483 {
1484         struct dial_masquerade_datastore *masq_data;
1485
1486         masq_data = ao2_alloc(sizeof(struct dial_masquerade_datastore),
1487                 dial_masquerade_datastore_dtor);
1488         if (!masq_data) {
1489                 return NULL;
1490         }
1491         AST_LIST_HEAD_INIT_NOLOCK(&masq_data->dialed_peers);
1492         return masq_data;
1493 }
1494
1495 /*!
1496  * \internal
1497  * \brief Datastore destructor for dial_masquerade_datastore
1498  */
1499 static void dial_masquerade_datastore_destroy(void *data)
1500 {
1501         ao2_ref(data, -1);
1502 }
1503
1504 /*!
1505  * \internal
1506  * \brief Datastore destructor for dial_masquerade_datastore
1507  */
1508 static void dial_masquerade_caller_datastore_destroy(void *data)
1509 {
1510         dial_masquerade_datastore_cleanup(data);
1511         ao2_ref(data, -1);
1512 }
1513
1514 static struct ast_datastore *dial_masquerade_datastore_find(struct ast_channel *chan);
1515
1516 static void dial_masquerade_fixup(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan)
1517 {
1518         struct dial_masquerade_datastore *masq_data = data;
1519         struct dial_target *cur;
1520         struct ast_datastore *datastore;
1521
1522         ao2_lock(masq_data);
1523         if (!masq_data->caller) {
1524                 /* Nothing to do but remove the datastore */
1525         } else if (masq_data->caller == old_chan) {
1526                 /* The caller channel is being masqueraded out. */
1527                 ast_debug(1, "Caller channel %s being masqueraded out to %s (is_empty:%d)\n",
1528                         ast_channel_name(new_chan), ast_channel_name(old_chan),
1529                         AST_LIST_EMPTY(&masq_data->dialed_peers));
1530                 AST_LIST_TRAVERSE(&masq_data->dialed_peers, cur, list) {
1531                         ast_channel_publish_dial_internal(new_chan, cur->peer, NULL,
1532                                 cur->dialstring, "NOANSWER", NULL);
1533                         ast_channel_publish_dial_internal(old_chan, cur->peer, NULL,
1534                                 cur->dialstring, NULL, NULL);
1535                 }
1536                 dial_masquerade_datastore_cleanup(masq_data);
1537         } else {
1538                 /* One of the peer channels is being masqueraded out. */
1539                 AST_LIST_TRAVERSE_SAFE_BEGIN(&masq_data->dialed_peers, cur, list) {
1540                         if (cur->peer == old_chan) {
1541                                 ast_debug(1, "Peer channel %s being masqueraded out to %s\n",
1542                                         ast_channel_name(new_chan), ast_channel_name(old_chan));
1543                                 ast_channel_publish_dial_internal(masq_data->caller, new_chan, NULL,
1544                                         cur->dialstring, "CANCEL", NULL);
1545                                 ast_channel_publish_dial_internal(masq_data->caller, old_chan, NULL,
1546                                         cur->dialstring, NULL, NULL);
1547
1548                                 AST_LIST_REMOVE_CURRENT(list);
1549                                 dial_target_free(cur);
1550                                 break;
1551                         }
1552                 }
1553                 AST_LIST_TRAVERSE_SAFE_END;
1554         }
1555         ao2_unlock(masq_data);
1556
1557         /* Remove the datastore from the channel. */
1558         datastore = dial_masquerade_datastore_find(old_chan);
1559         if (!datastore) {
1560                 return;
1561         }
1562         ast_channel_datastore_remove(old_chan, datastore);
1563         ast_datastore_free(datastore);
1564 }
1565
1566 /*!
1567  * \internal
1568  * \brief Primary purpose for dial_masquerade_datastore, publishes
1569  *        the channel dial event needed to set the incoming channel into the
1570  *        dial state during a masquerade.
1571  * \param data pointer to the dial_masquerade_datastore
1572  * \param old_chan Channel being replaced
1573  * \param new_chan Channel being pushed to dial mode
1574  */
1575 static void dial_masquerade_breakdown(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan)
1576 {
1577         struct dial_masquerade_datastore *masq_data = data;
1578         struct dial_target *cur;
1579
1580         ao2_lock(masq_data);
1581
1582         if (!masq_data->caller) {
1583                 ao2_unlock(masq_data);
1584                 return;
1585         }
1586
1587         if (masq_data->caller == new_chan) {
1588                 /*
1589                  * The caller channel is being masqueraded into.
1590                  * The masquerade is likely because of a blonde transfer.
1591                  */
1592                 ast_debug(1, "Caller channel %s being masqueraded into by %s (is_empty:%d)\n",
1593                         ast_channel_name(old_chan), ast_channel_name(new_chan),
1594                         AST_LIST_EMPTY(&masq_data->dialed_peers));
1595                 AST_LIST_TRAVERSE(&masq_data->dialed_peers, cur, list) {
1596                         ast_channel_publish_dial_internal(old_chan, cur->peer, NULL,
1597                                 cur->dialstring, "NOANSWER", NULL);
1598                         ast_channel_publish_dial_internal(new_chan, cur->peer, NULL,
1599                                 cur->dialstring, NULL, NULL);
1600                 }
1601
1602                 ao2_unlock(masq_data);
1603                 return;
1604         }
1605
1606         /*
1607          * One of the peer channels is being masqueraded into.
1608          * The masquerade is likely because of a call pickup.
1609          */
1610         AST_LIST_TRAVERSE(&masq_data->dialed_peers, cur, list) {
1611                 if (cur->peer == new_chan) {
1612                         ast_debug(1, "Peer channel %s being masqueraded into by %s\n",
1613                                 ast_channel_name(old_chan), ast_channel_name(new_chan));
1614                         ast_channel_publish_dial_internal(masq_data->caller, old_chan, NULL,
1615                                 cur->dialstring, "CANCEL", NULL);
1616                         ast_channel_publish_dial_internal(masq_data->caller, new_chan, NULL,
1617                                 cur->dialstring, NULL, NULL);
1618                         break;
1619                 }
1620         }
1621
1622         ao2_unlock(masq_data);
1623 }
1624
1625 static const struct ast_datastore_info dial_masquerade_info = {
1626         .type = "stasis-chan-dial-masq",
1627         .destroy = dial_masquerade_datastore_destroy,
1628         .chan_fixup = dial_masquerade_fixup,
1629         .chan_breakdown = dial_masquerade_breakdown,
1630 };
1631
1632 static const struct ast_datastore_info dial_masquerade_caller_info = {
1633         .type = "stasis-chan-dial-masq",
1634         .destroy = dial_masquerade_caller_datastore_destroy,
1635         .chan_fixup = dial_masquerade_fixup,
1636         .chan_breakdown = dial_masquerade_breakdown,
1637 };
1638
1639 /*!
1640  * \internal
1641  * \brief Find the dial masquerade datastore on the given channel.
1642  *
1643  * \param chan Channel a datastore data is wanted from
1644  *
1645  * \return A pointer to the datastore if it exists.
1646  */
1647 static struct ast_datastore *dial_masquerade_datastore_find(struct ast_channel *chan)
1648 {
1649         struct ast_datastore *datastore;
1650
1651         datastore = ast_channel_datastore_find(chan, &dial_masquerade_info, NULL);
1652         if (!datastore) {
1653                 datastore = ast_channel_datastore_find(chan, &dial_masquerade_caller_info, NULL);
1654         }
1655
1656         return datastore;
1657 }
1658
1659 /*!
1660  * \internal
1661  * \brief Add the dial masquerade datastore to a channel.
1662  *
1663  * \param chan Channel to setup dial masquerade datastore on.
1664  * \param masq_data NULL to setup caller datastore otherwise steals the ref on success.
1665  *
1666  * \retval masq_data given or created on success.
1667  *         (A ref is not returned but can be obtained before chan is unlocked.)
1668  * \retval NULL on error.  masq_data ref is not stolen.
1669  */
1670 static struct dial_masquerade_datastore *dial_masquerade_datastore_add(
1671         struct ast_channel *chan, struct dial_masquerade_datastore *masq_data)
1672 {
1673         struct ast_datastore *datastore;
1674
1675         datastore = ast_datastore_alloc(!masq_data ? &dial_masquerade_caller_info : &dial_masquerade_info, NULL);
1676         if (!datastore) {
1677                 return NULL;
1678         }
1679
1680         if (!masq_data) {
1681                 masq_data = dial_masquerade_datastore_alloc();
1682                 if (!masq_data) {
1683                         ast_datastore_free(datastore);
1684                         return NULL;
1685                 }
1686                 masq_data->caller = chan;
1687         }
1688
1689         datastore->data = masq_data;
1690         ast_channel_datastore_add(chan, datastore);
1691
1692         return masq_data;
1693 }
1694
1695 static int set_dial_masquerade(struct ast_channel *caller, struct ast_channel *peer, const char *dialstring)
1696 {
1697         struct ast_datastore *datastore;
1698         struct dial_masquerade_datastore *masq_data;
1699         struct dial_target *target;
1700
1701         /* Find or create caller datastore */
1702         datastore = dial_masquerade_datastore_find(caller);
1703         if (!datastore) {
1704                 masq_data = dial_masquerade_datastore_add(caller, NULL);
1705         } else {
1706                 masq_data = datastore->data;
1707         }
1708         if (!masq_data) {
1709                 return -1;
1710         }
1711         ao2_ref(masq_data, +1);
1712
1713         /*
1714          * Someone likely forgot to do an ast_channel_publish_dial()
1715          * or ast_channel_publish_dial_forward() with a final dial
1716          * status on the channel.
1717          */
1718         ast_assert(masq_data->caller == caller);
1719
1720         /* Create peer target to put into datastore */
1721         target = ast_calloc(1, sizeof(*target));
1722         if (!target) {
1723                 ao2_ref(masq_data, -1);
1724                 return -1;
1725         }
1726         if (dialstring) {
1727                 target->dialstring = ast_strdup(dialstring);
1728                 if (!target->dialstring) {
1729                         ast_free(target);
1730                         ao2_ref(masq_data, -1);
1731                         return -1;
1732                 }
1733         }
1734         target->peer = ast_channel_ref(peer);
1735
1736         /* Put peer target into datastore */
1737         ao2_lock(masq_data);
1738         dial_masquerade_datastore_remove_chan(masq_data, peer);
1739         AST_LIST_INSERT_HEAD(&masq_data->dialed_peers, target, list);
1740         ao2_unlock(masq_data);
1741
1742         datastore = dial_masquerade_datastore_find(peer);
1743         if (datastore) {
1744                 if (datastore->data == masq_data) {
1745                         /*
1746                          * Peer already had the datastore for this dial masquerade.
1747                          * This was a redundant peer dial masquerade setup.
1748                          */
1749                         ao2_ref(masq_data, -1);
1750                         return 0;
1751                 }
1752
1753                 /* Something is wrong.  Try to fix if the assert doesn't abort. */
1754                 ast_assert(0);
1755
1756                 /* Remove the stale dial masquerade datastore */
1757                 dial_masquerade_datastore_remove_chan(datastore->data, peer);
1758                 ast_channel_datastore_remove(peer, datastore);
1759                 ast_datastore_free(datastore);
1760         }
1761
1762         /* Create the peer dial masquerade datastore */
1763         if (dial_masquerade_datastore_add(peer, masq_data)) {
1764                 /* Success */
1765                 return 0;
1766         }
1767
1768         /* Failed to create the peer datastore */
1769         dial_masquerade_datastore_remove_chan(masq_data, peer);
1770         ao2_ref(masq_data, -1);
1771         return -1;
1772 }
1773
1774 static void remove_dial_masquerade(struct ast_channel *peer)
1775 {
1776         struct ast_datastore *datastore;
1777         struct dial_masquerade_datastore *masq_data;
1778
1779         datastore = dial_masquerade_datastore_find(peer);
1780         if (!datastore) {
1781                 return;
1782         }
1783
1784         masq_data = datastore->data;
1785         if (masq_data) {
1786                 dial_masquerade_datastore_remove_chan(masq_data, peer);
1787         }
1788
1789         ast_channel_datastore_remove(peer, datastore);
1790         ast_datastore_free(datastore);
1791 }
1792
1793 static void remove_dial_masquerade_caller(struct ast_channel *caller)
1794 {
1795         struct ast_datastore *datastore;
1796         struct dial_masquerade_datastore *masq_data;
1797
1798         datastore = dial_masquerade_datastore_find(caller);
1799         if (!datastore) {
1800                 return;
1801         }
1802
1803         masq_data = datastore->data;
1804         if (!masq_data || !AST_LIST_EMPTY(&masq_data->dialed_peers)) {
1805                 return;
1806         }
1807
1808         dial_masquerade_datastore_remove_chan(masq_data, caller);
1809
1810         ast_channel_datastore_remove(caller, datastore);
1811         ast_datastore_free(datastore);
1812 }