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