Restore Dial, Queue, and FollowMe 'I' option support.
[asterisk/asterisk.git] / main / bridge_channel.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2007 - 2009, Digium, Inc.
5  *
6  * Joshua Colp <jcolp@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 Bridging Channel API
22  *
23  * \author Joshua Colp <jcolp@digium.com>
24  * \author Richard Mudgett <rmudgett@digium.com>
25  * \author Matt Jordan <mjordan@digium.com>
26  *
27  */
28
29 /*** MODULEINFO
30         <support_level>core</support_level>
31  ***/
32
33 #include "asterisk.h"
34
35 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
36
37 #include <signal.h>
38
39 #include "asterisk/heap.h"
40 #include "asterisk/astobj2.h"
41 #include "asterisk/stringfields.h"
42 #include "asterisk/app.h"
43 #include "asterisk/pbx.h"
44 #include "asterisk/channel.h"
45 #include "asterisk/timing.h"
46 #include "asterisk/bridge.h"
47 #include "asterisk/bridge_channel.h"
48 #include "asterisk/bridge_after.h"
49 #include "asterisk/bridge_channel_internal.h"
50 #include "asterisk/bridge_internal.h"
51 #include "asterisk/stasis_bridges.h"
52 #include "asterisk/stasis_channels.h"
53 #include "asterisk/musiconhold.h"
54 #include "asterisk/features_config.h"
55 #include "asterisk/parking.h"
56 #include "asterisk/causes.h"
57 #include "asterisk/test.h"
58
59 /*!
60  * \brief Used to queue an action frame onto a bridge channel and write an action frame into a bridge.
61  * \since 12.0.0
62  *
63  * \param bridge_channel Which channel work with.
64  * \param action Type of bridge action frame.
65  * \param data Frame payload data to pass.
66  * \param datalen Frame payload data length to pass.
67  *
68  * \retval 0 on success.
69  * \retval -1 on error.
70  */
71 typedef int (*ast_bridge_channel_post_action_data)(struct ast_bridge_channel *bridge_channel, enum bridge_channel_action_type action, const void *data, size_t datalen);
72
73 void ast_bridge_channel_lock_bridge(struct ast_bridge_channel *bridge_channel)
74 {
75         struct ast_bridge *bridge;
76
77         for (;;) {
78                 /* Safely get the bridge pointer */
79                 ast_bridge_channel_lock(bridge_channel);
80                 bridge = bridge_channel->bridge;
81                 ao2_ref(bridge, +1);
82                 ast_bridge_channel_unlock(bridge_channel);
83
84                 /* Lock the bridge and see if it is still the bridge we need to lock. */
85                 ast_bridge_lock(bridge);
86                 if (bridge == bridge_channel->bridge) {
87                         ao2_ref(bridge, -1);
88                         return;
89                 }
90                 ast_bridge_unlock(bridge);
91                 ao2_ref(bridge, -1);
92         }
93 }
94
95 int ast_bridge_channel_notify_talking(struct ast_bridge_channel *bridge_channel, int started_talking)
96 {
97         struct ast_frame action = {
98                 .frametype = AST_FRAME_BRIDGE_ACTION,
99                 .subclass.integer = started_talking
100                         ? BRIDGE_CHANNEL_ACTION_TALKING_START : BRIDGE_CHANNEL_ACTION_TALKING_STOP,
101         };
102
103         return ast_bridge_channel_queue_frame(bridge_channel, &action);
104 }
105
106 /*!
107  * \internal
108  * \brief Poke the bridge_channel thread
109  */
110 static void bridge_channel_poke(struct ast_bridge_channel *bridge_channel)
111 {
112         if (!pthread_equal(pthread_self(), bridge_channel->thread)) {
113                 /* Wake up the bridge channel thread. */
114                 ast_queue_frame(bridge_channel->chan, &ast_null_frame);
115         }
116 }
117
118 /*!
119  * \internal
120  * \brief Set actual cause on channel.
121  * \since 12.0.0
122  *
123  * \param chan Channel to set cause.
124  * \param cause Cause to set on channel.
125  *   If cause <= 0 then use cause on channel if cause still <= 0 use AST_CAUSE_NORMAL_CLEARING.
126  *
127  * \return Actual cause set on channel.
128  */
129 static int channel_set_cause(struct ast_channel *chan, int cause)
130 {
131         ast_channel_lock(chan);
132         if (cause <= 0) {
133                 cause = ast_channel_hangupcause(chan);
134                 if (cause <= 0) {
135                         cause = AST_CAUSE_NORMAL_CLEARING;
136                 }
137         }
138         ast_channel_hangupcause_set(chan, cause);
139         ast_channel_unlock(chan);
140         return cause;
141 }
142
143 void ast_bridge_channel_leave_bridge_nolock(struct ast_bridge_channel *bridge_channel, enum bridge_channel_state new_state, int cause)
144 {
145         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
146                 return;
147         }
148
149         ast_debug(1, "Setting %p(%s) state from:%d to:%d\n",
150                 bridge_channel, ast_channel_name(bridge_channel->chan), bridge_channel->state,
151                 new_state);
152
153         channel_set_cause(bridge_channel->chan, cause);
154
155         /* Change the state on the bridge channel */
156         bridge_channel->state = new_state;
157
158         bridge_channel_poke(bridge_channel);
159 }
160
161 void ast_bridge_channel_leave_bridge(struct ast_bridge_channel *bridge_channel, enum bridge_channel_state new_state, int cause)
162 {
163         ast_bridge_channel_lock(bridge_channel);
164         ast_bridge_channel_leave_bridge_nolock(bridge_channel, new_state, cause);
165         ast_bridge_channel_unlock(bridge_channel);
166 }
167
168 struct ast_bridge_channel *ast_bridge_channel_peer(struct ast_bridge_channel *bridge_channel)
169 {
170         struct ast_bridge *bridge = bridge_channel->bridge;
171         struct ast_bridge_channel *other = NULL;
172
173         if (bridge_channel->in_bridge && bridge->num_channels == 2) {
174                 AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
175                         if (other != bridge_channel) {
176                                 break;
177                         }
178                 }
179         }
180
181         return other;
182 }
183
184 void ast_bridge_channel_restore_formats(struct ast_bridge_channel *bridge_channel)
185 {
186         /* Restore original formats of the channel as they came in */
187         if (ast_format_cmp(ast_channel_readformat(bridge_channel->chan), &bridge_channel->read_format) == AST_FORMAT_CMP_NOT_EQUAL) {
188                 ast_debug(1, "Bridge is returning %p(%s) to read format %s\n",
189                         bridge_channel, ast_channel_name(bridge_channel->chan),
190                         ast_getformatname(&bridge_channel->read_format));
191                 if (ast_set_read_format(bridge_channel->chan, &bridge_channel->read_format)) {
192                         ast_debug(1, "Bridge failed to return %p(%s) to read format %s\n",
193                                 bridge_channel, ast_channel_name(bridge_channel->chan),
194                                 ast_getformatname(&bridge_channel->read_format));
195                 }
196         }
197         if (ast_format_cmp(ast_channel_writeformat(bridge_channel->chan), &bridge_channel->write_format) == AST_FORMAT_CMP_NOT_EQUAL) {
198                 ast_debug(1, "Bridge is returning %p(%s) to write format %s\n",
199                         bridge_channel, ast_channel_name(bridge_channel->chan),
200                         ast_getformatname(&bridge_channel->write_format));
201                 if (ast_set_write_format(bridge_channel->chan, &bridge_channel->write_format)) {
202                         ast_debug(1, "Bridge failed to return %p(%s) to write format %s\n",
203                                 bridge_channel, ast_channel_name(bridge_channel->chan),
204                                 ast_getformatname(&bridge_channel->write_format));
205                 }
206         }
207 }
208
209 struct ast_bridge *ast_bridge_channel_merge_inhibit(struct ast_bridge_channel *bridge_channel, int request)
210 {
211         struct ast_bridge *bridge;
212
213         ast_bridge_channel_lock_bridge(bridge_channel);
214         bridge = bridge_channel->bridge;
215         ao2_ref(bridge, +1);
216         bridge_merge_inhibit_nolock(bridge, request);
217         ast_bridge_unlock(bridge);
218         return bridge;
219 }
220
221 void ast_bridge_channel_update_linkedids(struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
222 {
223         struct ast_bridge_channel *other = NULL;
224         struct ast_bridge *bridge = bridge_channel->bridge;
225         const char *oldest_linkedid = ast_channel_linkedid(bridge_channel->chan);
226
227         AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
228                 if (other == swap) {
229                         continue;
230                 }
231                 oldest_linkedid = ast_channel_oldest_linkedid(oldest_linkedid, ast_channel_linkedid(other->chan));
232         }
233
234         if (ast_strlen_zero(oldest_linkedid)) {
235                 return;
236         }
237
238         ast_channel_linkedid_set(bridge_channel->chan, oldest_linkedid);
239         AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
240                 if (other == swap) {
241                         continue;
242                 }
243                 ast_channel_linkedid_set(other->chan, oldest_linkedid);
244         }
245 }
246
247 void ast_bridge_channel_update_accountcodes(struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
248 {
249         struct ast_bridge *bridge = bridge_channel->bridge;
250         struct ast_bridge_channel *other = NULL;
251
252         AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
253                 if (other == swap) {
254                         continue;
255                 }
256
257                 if (!ast_strlen_zero(ast_channel_accountcode(bridge_channel->chan)) && ast_strlen_zero(ast_channel_peeraccount(other->chan))) {
258                         ast_debug(1, "Setting peeraccount to %s for %s from data on channel %s\n",
259                                         ast_channel_accountcode(bridge_channel->chan), ast_channel_name(other->chan), ast_channel_name(bridge_channel->chan));
260                         ast_channel_peeraccount_set(other->chan, ast_channel_accountcode(bridge_channel->chan));
261                 }
262                 if (!ast_strlen_zero(ast_channel_accountcode(other->chan)) && ast_strlen_zero(ast_channel_peeraccount(bridge_channel->chan))) {
263                         ast_debug(1, "Setting peeraccount to %s for %s from data on channel %s\n",
264                                         ast_channel_accountcode(other->chan), ast_channel_name(bridge_channel->chan), ast_channel_name(other->chan));
265                         ast_channel_peeraccount_set(bridge_channel->chan, ast_channel_accountcode(other->chan));
266                 }
267                 if (!ast_strlen_zero(ast_channel_peeraccount(bridge_channel->chan)) && ast_strlen_zero(ast_channel_accountcode(other->chan))) {
268                         ast_debug(1, "Setting accountcode to %s for %s from data on channel %s\n",
269                                         ast_channel_peeraccount(bridge_channel->chan), ast_channel_name(other->chan), ast_channel_name(bridge_channel->chan));
270                         ast_channel_accountcode_set(other->chan, ast_channel_peeraccount(bridge_channel->chan));
271                 }
272                 if (!ast_strlen_zero(ast_channel_peeraccount(other->chan)) && ast_strlen_zero(ast_channel_accountcode(bridge_channel->chan))) {
273                         ast_debug(1, "Setting accountcode to %s for %s from data on channel %s\n",
274                                         ast_channel_peeraccount(other->chan), ast_channel_name(bridge_channel->chan), ast_channel_name(other->chan));
275                         ast_channel_accountcode_set(bridge_channel->chan, ast_channel_peeraccount(other->chan));
276                 }
277                 if (bridge->num_channels == 2) {
278                         if (strcmp(ast_channel_accountcode(bridge_channel->chan), ast_channel_peeraccount(other->chan))) {
279                                 ast_debug(1, "Changing peeraccount from %s to %s on %s to match channel %s\n",
280                                                 ast_channel_peeraccount(other->chan), ast_channel_peeraccount(bridge_channel->chan), ast_channel_name(other->chan), ast_channel_name(bridge_channel->chan));
281                                 ast_channel_peeraccount_set(other->chan, ast_channel_accountcode(bridge_channel->chan));
282                         }
283                         if (strcmp(ast_channel_accountcode(other->chan), ast_channel_peeraccount(bridge_channel->chan))) {
284                                 ast_debug(1, "Changing peeraccount from %s to %s on %s to match channel %s\n",
285                                                 ast_channel_peeraccount(bridge_channel->chan), ast_channel_peeraccount(other->chan), ast_channel_name(bridge_channel->chan), ast_channel_name(other->chan));
286                                 ast_channel_peeraccount_set(bridge_channel->chan, ast_channel_accountcode(other->chan));
287                         }
288                 }
289         }
290 }
291
292 void ast_bridge_channel_kick(struct ast_bridge_channel *bridge_channel, int cause)
293 {
294         struct ast_bridge_features *features = bridge_channel->features;
295         struct ast_bridge_hook *hook;
296         struct ao2_iterator iter;
297
298         ast_bridge_channel_lock(bridge_channel);
299         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
300                 channel_set_cause(bridge_channel->chan, cause);
301                 cause = 0;
302         }
303         ast_bridge_channel_unlock(bridge_channel);
304
305         /* Run any hangup hooks. */
306         iter = ao2_iterator_init(features->other_hooks, 0);
307         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
308                 int remove_me;
309
310                 if (hook->type != AST_BRIDGE_HOOK_TYPE_HANGUP) {
311                         continue;
312                 }
313                 remove_me = hook->callback(bridge_channel, hook->hook_pvt);
314                 if (remove_me) {
315                         ast_debug(1, "Hangup hook %p is being removed from %p(%s)\n",
316                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
317                         ao2_unlink(features->other_hooks, hook);
318                 }
319         }
320         ao2_iterator_destroy(&iter);
321
322         /* Default hangup action. */
323         ast_bridge_channel_leave_bridge(bridge_channel, BRIDGE_CHANNEL_STATE_END, cause);
324 }
325
326 /*!
327  * \internal
328  * \brief Write an \ref ast_frame onto the bridge channel
329  * \since 12.0.0
330  *
331  * \param bridge_channel Which channel to queue the frame onto.
332  * \param frame The frame to write onto the bridge_channel
333  *
334  * \retval 0 on success.
335  * \retval -1 on error.
336  */
337 static int bridge_channel_write_frame(struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
338 {
339         ast_bridge_channel_lock_bridge(bridge_channel);
340 /*
341  * XXX need to implement a deferred write queue for when there
342  * is no peer channel in the bridge (yet or it was kicked).
343  *
344  * The tech decides if a frame needs to be pushed back for deferral.
345  * simple_bridge/native_bridge are likely the only techs that will do this.
346  */
347         bridge_channel->bridge->technology->write(bridge_channel->bridge, bridge_channel, frame);
348
349         /* Remember any owed events to the bridge. */
350         switch (frame->frametype) {
351         case AST_FRAME_DTMF_BEGIN:
352                 bridge_channel->owed.dtmf_tv = ast_tvnow();
353                 bridge_channel->owed.dtmf_digit = frame->subclass.integer;
354                 break;
355         case AST_FRAME_DTMF_END:
356                 bridge_channel->owed.dtmf_digit = '\0';
357                 break;
358         case AST_FRAME_CONTROL:
359                 /*
360                  * We explicitly will not remember HOLD/UNHOLD frames because
361                  * things like attended transfers will handle them.
362                  */
363         default:
364                 break;
365         }
366         ast_bridge_unlock(bridge_channel->bridge);
367
368         /*
369          * Claim successful write to bridge.  If deferred frame
370          * support is added, claim successfully deferred.
371          */
372         return 0;
373 }
374
375 void bridge_channel_settle_owed_events(struct ast_bridge *orig_bridge, struct ast_bridge_channel *bridge_channel)
376 {
377         if (bridge_channel->owed.dtmf_digit) {
378                 struct ast_frame frame = {
379                         .frametype = AST_FRAME_DTMF_END,
380                         .subclass.integer = bridge_channel->owed.dtmf_digit,
381                         .src = "Bridge channel owed DTMF",
382                 };
383
384                 frame.len = ast_tvdiff_ms(ast_tvnow(), bridge_channel->owed.dtmf_tv);
385                 if (frame.len < option_dtmfminduration) {
386                         frame.len = option_dtmfminduration;
387                 }
388                 ast_log(LOG_DTMF, "DTMF end '%c' simulated to bridge %s because %s left.  Duration %ld ms.\n",
389                         bridge_channel->owed.dtmf_digit, orig_bridge->uniqueid,
390                         ast_channel_name(bridge_channel->chan), frame.len);
391                 bridge_channel->owed.dtmf_digit = '\0';
392                 orig_bridge->technology->write(orig_bridge, NULL, &frame);
393         }
394 }
395
396 /*!
397  * \internal
398  * \brief Suspend a channel from a bridge.
399  *
400  * \param bridge_channel Channel to suspend.
401  *
402  * \note This function assumes bridge_channel->bridge is locked.
403  *
404  * \return Nothing
405  */
406 void bridge_channel_internal_suspend_nolock(struct ast_bridge_channel *bridge_channel)
407 {
408         bridge_channel->suspended = 1;
409         if (bridge_channel->in_bridge) {
410                 --bridge_channel->bridge->num_active;
411         }
412
413         /* Get technology bridge threads off of the channel. */
414         if (bridge_channel->bridge->technology->suspend) {
415                 bridge_channel->bridge->technology->suspend(bridge_channel->bridge, bridge_channel);
416         }
417 }
418
419 /*!
420  * \internal
421  * \brief Suspend a channel from a bridge.
422  *
423  * \param bridge_channel Channel to suspend.
424  *
425  * \return Nothing
426  */
427 static void bridge_channel_suspend(struct ast_bridge_channel *bridge_channel)
428 {
429         ast_bridge_channel_lock_bridge(bridge_channel);
430         bridge_channel_internal_suspend_nolock(bridge_channel);
431         ast_bridge_unlock(bridge_channel->bridge);
432 }
433
434 /*!
435  * \internal
436  * \brief Unsuspend a channel from a bridge.
437  *
438  * \param bridge_channel Channel to unsuspend.
439  *
440  * \note This function assumes bridge_channel->bridge is locked.
441  *
442  * \return Nothing
443  */
444 void bridge_channel_internal_unsuspend_nolock(struct ast_bridge_channel *bridge_channel)
445 {
446         bridge_channel->suspended = 0;
447         if (bridge_channel->in_bridge) {
448                 ++bridge_channel->bridge->num_active;
449         }
450
451         /* Wake technology bridge threads to take care of channel again. */
452         if (bridge_channel->bridge->technology->unsuspend) {
453                 bridge_channel->bridge->technology->unsuspend(bridge_channel->bridge, bridge_channel);
454         }
455
456         /* Wake suspended channel. */
457         ast_bridge_channel_lock(bridge_channel);
458         ast_cond_signal(&bridge_channel->cond);
459         ast_bridge_channel_unlock(bridge_channel);
460 }
461
462 /*!
463  * \internal
464  * \brief Unsuspend a channel from a bridge.
465  *
466  * \param bridge_channel Channel to unsuspend.
467  *
468  * \return Nothing
469  */
470 static void bridge_channel_unsuspend(struct ast_bridge_channel *bridge_channel)
471 {
472         ast_bridge_channel_lock_bridge(bridge_channel);
473         bridge_channel_internal_unsuspend_nolock(bridge_channel);
474         ast_bridge_unlock(bridge_channel->bridge);
475 }
476
477 /*!
478  * \internal
479  * \brief Queue an action frame onto the bridge channel with data.
480  * \since 12.0.0
481  *
482  * \param bridge_channel Which channel to queue the frame onto.
483  * \param action Type of bridge action frame.
484  * \param data Frame payload data to pass.
485  * \param datalen Frame payload data length to pass.
486  *
487  * \retval 0 on success.
488  * \retval -1 on error.
489  */
490 static int bridge_channel_queue_action_data(struct ast_bridge_channel *bridge_channel, enum bridge_channel_action_type action, const void *data, size_t datalen)
491 {
492         struct ast_frame frame = {
493                 .frametype = AST_FRAME_BRIDGE_ACTION,
494                 .subclass.integer = action,
495                 .datalen = datalen,
496                 .data.ptr = (void *) data,
497         };
498
499         return ast_bridge_channel_queue_frame(bridge_channel, &frame);
500 }
501
502 /*!
503  * \internal
504  * \brief Write an action frame onto the bridge channel with data.
505  * \since 12.0.0
506  *
507  * \param bridge_channel Which channel to queue the frame onto.
508  * \param action Type of bridge action frame.
509  * \param data Frame payload data to pass.
510  * \param datalen Frame payload data length to pass.
511  *
512  * \retval 0 on success.
513  * \retval -1 on error.
514  */
515 static int bridge_channel_write_action_data(struct ast_bridge_channel *bridge_channel, enum bridge_channel_action_type action, const void *data, size_t datalen)
516 {
517         struct ast_frame frame = {
518                 .frametype = AST_FRAME_BRIDGE_ACTION,
519                 .subclass.integer = action,
520                 .datalen = datalen,
521                 .data.ptr = (void *) data,
522         };
523
524         return bridge_channel_write_frame(bridge_channel, &frame);
525 }
526
527 int ast_bridge_channel_queue_frame(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
528 {
529         struct ast_frame *dup;
530         char nudge = 0;
531
532         if (bridge_channel->suspended
533                 /* Also defer DTMF frames. */
534                 && fr->frametype != AST_FRAME_DTMF_BEGIN
535                 && fr->frametype != AST_FRAME_DTMF_END
536                 && !ast_is_deferrable_frame(fr)) {
537                 /* Drop non-deferable frames when suspended. */
538                 return 0;
539         }
540         if (fr->frametype == AST_FRAME_NULL) {
541                 /* "Accept" the frame and discard it. */
542                 return 0;
543         }
544
545         dup = ast_frdup(fr);
546         if (!dup) {
547                 return -1;
548         }
549
550         ast_bridge_channel_lock(bridge_channel);
551         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
552                 /* Drop frames on channels leaving the bridge. */
553                 ast_bridge_channel_unlock(bridge_channel);
554                 ast_frfree(dup);
555                 return 0;
556         }
557
558         AST_LIST_INSERT_TAIL(&bridge_channel->wr_queue, dup, frame_list);
559         if (write(bridge_channel->alert_pipe[1], &nudge, sizeof(nudge)) != sizeof(nudge)) {
560                 ast_log(LOG_ERROR, "We couldn't write alert pipe for %p(%s)... something is VERY wrong\n",
561                         bridge_channel, ast_channel_name(bridge_channel->chan));
562         }
563         ast_bridge_channel_unlock(bridge_channel);
564         return 0;
565 }
566
567 int ast_bridge_queue_everyone_else(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
568 {
569         struct ast_bridge_channel *cur;
570         int not_written = -1;
571
572         if (frame->frametype == AST_FRAME_NULL) {
573                 /* "Accept" the frame and discard it. */
574                 return 0;
575         }
576
577         AST_LIST_TRAVERSE(&bridge->channels, cur, entry) {
578                 if (cur == bridge_channel) {
579                         continue;
580                 }
581                 if (!ast_bridge_channel_queue_frame(cur, frame)) {
582                         not_written = 0;
583                 }
584         }
585         return not_written;
586 }
587
588 int ast_bridge_channel_queue_control_data(struct ast_bridge_channel *bridge_channel, enum ast_control_frame_type control, const void *data, size_t datalen)
589 {
590         struct ast_frame frame = {
591                 .frametype = AST_FRAME_CONTROL,
592                 .subclass.integer = control,
593                 .datalen = datalen,
594                 .data.ptr = (void *) data,
595         };
596
597         return ast_bridge_channel_queue_frame(bridge_channel, &frame);
598 }
599
600 int ast_bridge_channel_write_control_data(struct ast_bridge_channel *bridge_channel, enum ast_control_frame_type control, const void *data, size_t datalen)
601 {
602         struct ast_frame frame = {
603                 .frametype = AST_FRAME_CONTROL,
604                 .subclass.integer = control,
605                 .datalen = datalen,
606                 .data.ptr = (void *) data,
607         };
608
609         return bridge_channel_write_frame(bridge_channel, &frame);
610 }
611
612 int ast_bridge_channel_write_hold(struct ast_bridge_channel *bridge_channel, const char *moh_class)
613 {
614         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
615         size_t datalen;
616
617         if (!ast_strlen_zero(moh_class)) {
618                 datalen = strlen(moh_class) + 1;
619
620                 blob = ast_json_pack("{s: s}",
621                         "musicclass", moh_class);
622         } else {
623                 moh_class = NULL;
624                 datalen = 0;
625         }
626
627         ast_channel_publish_blob(bridge_channel->chan, ast_channel_hold_type(), blob);
628         return ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_HOLD,
629                 moh_class, datalen);
630 }
631
632 int ast_bridge_channel_write_unhold(struct ast_bridge_channel *bridge_channel)
633 {
634         ast_channel_publish_blob(bridge_channel->chan, ast_channel_unhold_type(), NULL);
635         return ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_UNHOLD, NULL, 0);
636 }
637
638 /*!
639  * \internal
640  * \brief Helper function to kick off a PBX app on a bridge_channel
641  */
642 static int run_app_helper(struct ast_channel *chan, const char *app_name, const char *app_args)
643 {
644         int res = 0;
645
646         if (!strcasecmp("Gosub", app_name)) {
647                 ast_app_exec_sub(NULL, chan, app_args, 0);
648         } else if (!strcasecmp("Macro", app_name)) {
649                 ast_app_exec_macro(NULL, chan, app_args);
650         } else {
651                 struct ast_app *app;
652
653                 app = pbx_findapp(app_name);
654                 if (!app) {
655                         ast_log(LOG_WARNING, "Could not find application (%s)\n", app_name);
656                 } else {
657                         res = pbx_exec(chan, app, app_args);
658                 }
659         }
660         return res;
661 }
662
663 void ast_bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
664 {
665         if (moh_class) {
666                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
667         }
668         if (run_app_helper(bridge_channel->chan, app_name, S_OR(app_args, ""))) {
669                 /* Break the bridge if the app returns non-zero. */
670                 ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
671         }
672         if (moh_class) {
673                 ast_bridge_channel_write_unhold(bridge_channel);
674         }
675 }
676
677 struct bridge_run_app {
678         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
679         int moh_offset;
680         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
681         int app_args_offset;
682         /*! Application name to run. */
683         char app_name[0];
684 };
685
686 /*!
687  * \internal
688  * \brief Handle the run application bridge action.
689  * \since 12.0.0
690  *
691  * \param bridge_channel Which channel to run the application on.
692  * \param data Action frame data to run the application.
693  *
694  * \return Nothing
695  */
696 static void bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, struct bridge_run_app *data)
697 {
698         ast_bridge_channel_run_app(bridge_channel, data->app_name,
699                 data->app_args_offset ? &data->app_name[data->app_args_offset] : NULL,
700                 data->moh_offset ? &data->app_name[data->moh_offset] : NULL);
701 }
702
703 /*!
704  * \internal
705  * \brief Marshal an application to be executed on a bridge_channel
706  */
707 static int payload_helper_app(ast_bridge_channel_post_action_data post_it,
708         struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
709 {
710         struct bridge_run_app *app_data;
711         size_t len_name = strlen(app_name) + 1;
712         size_t len_args = ast_strlen_zero(app_args) ? 0 : strlen(app_args) + 1;
713         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
714         size_t len_data = sizeof(*app_data) + len_name + len_args + len_moh;
715
716         /* Fill in application run frame data. */
717         app_data = alloca(len_data);
718         app_data->app_args_offset = len_args ? len_name : 0;
719         app_data->moh_offset = len_moh ? len_name + len_args : 0;
720         strcpy(app_data->app_name, app_name);/* Safe */
721         if (len_args) {
722                 strcpy(&app_data->app_name[app_data->app_args_offset], app_args);/* Safe */
723         }
724         if (moh_class) {
725                 strcpy(&app_data->app_name[app_data->moh_offset], moh_class);/* Safe */
726         }
727
728         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_RUN_APP, app_data, len_data);
729 }
730
731 int ast_bridge_channel_write_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
732 {
733         return payload_helper_app(bridge_channel_write_action_data,
734                 bridge_channel, app_name, app_args, moh_class);
735 }
736
737 int ast_bridge_channel_queue_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
738 {
739         return payload_helper_app(bridge_channel_queue_action_data,
740                 bridge_channel, app_name, app_args, moh_class);
741 }
742
743 void ast_bridge_channel_playfile(struct ast_bridge_channel *bridge_channel, ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
744 {
745         if (moh_class) {
746                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
747         }
748         if (custom_play) {
749                 custom_play(bridge_channel, playfile);
750         } else {
751                 ast_stream_and_wait(bridge_channel->chan, playfile, AST_DIGIT_NONE);
752         }
753         if (moh_class) {
754                 ast_bridge_channel_write_unhold(bridge_channel);
755         }
756
757         /*
758          * It may be necessary to resume music on hold after we finish
759          * playing the announcment.
760          */
761         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_MOH)) {
762                 const char *latest_musicclass;
763
764                 ast_channel_lock(bridge_channel->chan);
765                 latest_musicclass = ast_strdupa(ast_channel_latest_musicclass(bridge_channel->chan));
766                 ast_channel_unlock(bridge_channel->chan);
767                 ast_moh_start(bridge_channel->chan, latest_musicclass, NULL);
768         }
769 }
770
771 struct bridge_playfile {
772         /*! Call this function to play the playfile. (NULL if normal sound file to play) */
773         ast_bridge_custom_play_fn custom_play;
774         /*! Offset into playfile[] where the MOH class name starts.  (zero if no MOH)*/
775         int moh_offset;
776         /*! Filename to play. */
777         char playfile[0];
778 };
779
780 /*!
781  * \internal
782  * \brief Handle the playfile bridge action.
783  * \since 12.0.0
784  *
785  * \param bridge_channel Which channel to play a file on.
786  * \param payload Action frame payload to play a file.
787  *
788  * \return Nothing
789  */
790 static void bridge_channel_playfile(struct ast_bridge_channel *bridge_channel, struct bridge_playfile *payload)
791 {
792         ast_bridge_channel_playfile(bridge_channel, payload->custom_play, payload->playfile,
793                 payload->moh_offset ? &payload->playfile[payload->moh_offset] : NULL);
794 }
795
796 /*!
797  * \internal
798  * \brief Marshal a file to be played on a bridge_channel
799  */
800 static int payload_helper_playfile(ast_bridge_channel_post_action_data post_it,
801         struct ast_bridge_channel *bridge_channel, ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
802 {
803         struct bridge_playfile *payload;
804         size_t len_name = strlen(playfile) + 1;
805         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
806         size_t len_payload = sizeof(*payload) + len_name + len_moh;
807
808         /* Fill in play file frame data. */
809         payload = alloca(len_payload);
810         payload->custom_play = custom_play;
811         payload->moh_offset = len_moh ? len_name : 0;
812         strcpy(payload->playfile, playfile);/* Safe */
813         if (moh_class) {
814                 strcpy(&payload->playfile[payload->moh_offset], moh_class);/* Safe */
815         }
816
817         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_PLAY_FILE, payload, len_payload);
818 }
819
820 int ast_bridge_channel_write_playfile(struct ast_bridge_channel *bridge_channel, ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
821 {
822         return payload_helper_playfile(bridge_channel_write_action_data,
823                 bridge_channel, custom_play, playfile, moh_class);
824 }
825
826 int ast_bridge_channel_queue_playfile(struct ast_bridge_channel *bridge_channel, ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
827 {
828         return payload_helper_playfile(bridge_channel_queue_action_data,
829                 bridge_channel, custom_play, playfile, moh_class);
830 }
831
832 struct bridge_custom_callback {
833         /*! Call this function on the bridge channel thread. */
834         ast_bridge_custom_callback_fn callback;
835         /*! Size of the payload if it exists.  A number otherwise. */
836         size_t payload_size;
837         /*! Option flags determining how callback is called. */
838         unsigned int flags;
839         /*! Nonzero if the payload exists. */
840         char payload_exists;
841         /*! Payload to give to callback. */
842         char payload[0];
843 };
844
845 /*!
846  * \internal
847  * \brief Handle the do custom callback bridge action.
848  * \since 12.0.0
849  *
850  * \param bridge_channel Which channel to call the callback on.
851  * \param data Action frame data to call the callback.
852  *
853  * \return Nothing
854  */
855 static void bridge_channel_do_callback(struct ast_bridge_channel *bridge_channel, struct bridge_custom_callback *data)
856 {
857         if (ast_test_flag(data, AST_BRIDGE_CHANNEL_CB_OPTION_MEDIA)) {
858                 bridge_channel_suspend(bridge_channel);
859                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
860         }
861         data->callback(bridge_channel, data->payload_exists ? data->payload : NULL, data->payload_size);
862         if (ast_test_flag(data, AST_BRIDGE_CHANNEL_CB_OPTION_MEDIA)) {
863                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
864                 bridge_channel_unsuspend(bridge_channel);
865         }
866 }
867
868 /*!
869  * \internal
870  * \brief Marshal a custom callback function to be called on a bridge_channel
871  */
872 static int payload_helper_cb(ast_bridge_channel_post_action_data post_it,
873         struct ast_bridge_channel *bridge_channel,
874         enum ast_bridge_channel_custom_callback_option flags,
875         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
876 {
877         struct bridge_custom_callback *cb_data;
878         size_t len_data = sizeof(*cb_data) + (payload ? payload_size : 0);
879
880         /* Sanity check. */
881         if (!callback) {
882                 ast_assert(0);
883                 return -1;
884         }
885
886         /* Fill in custom callback frame data. */
887         cb_data = alloca(len_data);
888         cb_data->callback = callback;
889         cb_data->payload_size = payload_size;
890         cb_data->flags = flags;
891         cb_data->payload_exists = payload && payload_size;
892         if (cb_data->payload_exists) {
893                 memcpy(cb_data->payload, payload, payload_size);/* Safe */
894         }
895
896         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_CALLBACK, cb_data, len_data);
897 }
898
899 int ast_bridge_channel_write_callback(struct ast_bridge_channel *bridge_channel,
900         enum ast_bridge_channel_custom_callback_option flags,
901         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
902 {
903         return payload_helper_cb(bridge_channel_write_action_data,
904                 bridge_channel, flags, callback, payload, payload_size);
905 }
906
907 int ast_bridge_channel_queue_callback(struct ast_bridge_channel *bridge_channel,
908         enum ast_bridge_channel_custom_callback_option flags,
909         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
910 {
911         return payload_helper_cb(bridge_channel_queue_action_data,
912                 bridge_channel, flags, callback, payload, payload_size);
913 }
914
915 struct bridge_park {
916         int parker_uuid_offset;
917         int app_data_offset;
918         /* buffer used for holding those strings */
919         char parkee_uuid[0];
920 };
921
922 /*!
923  * \internal
924  * \brief Park a bridge_cahnnel
925  */
926 static void bridge_channel_park(struct ast_bridge_channel *bridge_channel, struct bridge_park *payload)
927 {
928         if (!ast_parking_provider_registered()) {
929                 ast_log(AST_LOG_WARNING, "Unable to park %s: No parking provider loaded!\n",
930                         ast_channel_name(bridge_channel->chan));
931                 return;
932         }
933
934         if (ast_parking_park_bridge_channel(bridge_channel, payload->parkee_uuid,
935                 &payload->parkee_uuid[payload->parker_uuid_offset],
936                 payload->app_data_offset ? &payload->parkee_uuid[payload->app_data_offset] : NULL)) {
937                 ast_log(AST_LOG_WARNING, "Error occurred while parking %s\n",
938                         ast_channel_name(bridge_channel->chan));
939         }
940 }
941
942 /*!
943  * \internal
944  * \brief Marshal a park action onto a bridge_channel
945  */
946 static int payload_helper_park(ast_bridge_channel_post_action_data post_it,
947         struct ast_bridge_channel *bridge_channel,
948         const char *parkee_uuid,
949         const char *parker_uuid,
950         const char *app_data)
951 {
952         struct bridge_park *payload;
953         size_t len_parkee_uuid = strlen(parkee_uuid) + 1;
954         size_t len_parker_uuid = strlen(parker_uuid) + 1;
955         size_t len_app_data = !app_data ? 0 : strlen(app_data) + 1;
956         size_t len_payload = sizeof(*payload) + len_parker_uuid + len_parkee_uuid + len_app_data;
957
958         payload = alloca(len_payload);
959         payload->app_data_offset = len_app_data ? len_parkee_uuid + len_parker_uuid : 0;
960         payload->parker_uuid_offset = len_parkee_uuid;
961         strcpy(payload->parkee_uuid, parkee_uuid);
962         strcpy(&payload->parkee_uuid[payload->parker_uuid_offset], parker_uuid);
963         if (app_data) {
964                 strcpy(&payload->parkee_uuid[payload->app_data_offset], app_data);
965         }
966
967         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_PARK, payload, len_payload);
968 }
969
970 int ast_bridge_channel_write_park(struct ast_bridge_channel *bridge_channel, const char *parkee_uuid, const char *parker_uuid, const char *app_data)
971 {
972         return payload_helper_park(bridge_channel_write_action_data,
973                 bridge_channel, parkee_uuid, parker_uuid, app_data);
974 }
975
976 /*!
977  * \internal
978  * \brief Handle bridge channel interval expiration.
979  * \since 12.0.0
980  *
981  * \param bridge_channel Channel to run expired intervals on.
982  *
983  * \return Nothing
984  */
985 static void bridge_channel_handle_interval(struct ast_bridge_channel *bridge_channel)
986 {
987         struct ast_heap *interval_hooks;
988         struct ast_bridge_hook_timer *hook;
989         struct timeval start;
990         int chan_suspended = 0;
991
992         interval_hooks = bridge_channel->features->interval_hooks;
993         ast_heap_wrlock(interval_hooks);
994         start = ast_tvnow();
995         while ((hook = ast_heap_peek(interval_hooks, 1))) {
996                 int interval;
997                 unsigned int execution_time;
998
999                 if (ast_tvdiff_ms(hook->timer.trip_time, start) > 0) {
1000                         ast_debug(1, "Hook %p on %p(%s) wants to happen in the future, stopping our traversal\n",
1001                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1002                         break;
1003                 }
1004                 ao2_ref(hook, +1);
1005                 ast_heap_unlock(interval_hooks);
1006
1007                 if (!chan_suspended
1008                         && ast_test_flag(&hook->timer, AST_BRIDGE_HOOK_TIMER_OPTION_MEDIA)) {
1009                         chan_suspended = 1;
1010                         bridge_channel_suspend(bridge_channel);
1011                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1012                 }
1013
1014                 ast_debug(1, "Executing hook %p on %p(%s)\n",
1015                         hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1016                 interval = hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
1017
1018                 ast_heap_wrlock(interval_hooks);
1019                 if (ast_heap_peek(interval_hooks, hook->timer.heap_index) != hook
1020                         || !ast_heap_remove(interval_hooks, hook)) {
1021                         /* Interval hook is already removed from the bridge_channel. */
1022                         ao2_ref(hook, -1);
1023                         continue;
1024                 }
1025                 ao2_ref(hook, -1);
1026
1027                 if (interval < 0) {
1028                         ast_debug(1, "Removed interval hook %p from %p(%s)\n",
1029                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1030                         ao2_ref(hook, -1);
1031                         continue;
1032                 }
1033                 if (interval) {
1034                         /* Set new interval for the hook. */
1035                         hook->timer.interval = interval;
1036                 }
1037
1038                 ast_debug(1, "Updating interval hook %p with interval %u on %p(%s)\n",
1039                         hook, hook->timer.interval, bridge_channel,
1040                         ast_channel_name(bridge_channel->chan));
1041
1042                 /* resetting start */
1043                 start = ast_tvnow();
1044
1045                 /*
1046                  * Resetup the interval hook for the next interval.  We may need
1047                  * to skip over any missed intervals because the hook was
1048                  * delayed or took too long.
1049                  */
1050                 execution_time = ast_tvdiff_ms(start, hook->timer.trip_time);
1051                 while (hook->timer.interval < execution_time) {
1052                         execution_time -= hook->timer.interval;
1053                 }
1054                 hook->timer.trip_time = ast_tvadd(start, ast_samp2tv(hook->timer.interval - execution_time, 1000));
1055                 hook->timer.seqno = ast_atomic_fetchadd_int((int *) &bridge_channel->features->interval_sequence, +1);
1056
1057                 if (ast_heap_push(interval_hooks, hook)) {
1058                         /* Could not push the hook back onto the heap. */
1059                         ao2_ref(hook, -1);
1060                 }
1061         }
1062         ast_heap_unlock(interval_hooks);
1063
1064         if (chan_suspended) {
1065                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1066                 bridge_channel_unsuspend(bridge_channel);
1067         }
1068 }
1069
1070 /*!
1071  * \internal
1072  * \brief Write a DTMF stream out to a channel
1073  */
1074 static int bridge_channel_write_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
1075 {
1076         return bridge_channel_write_action_data(bridge_channel,
1077                 BRIDGE_CHANNEL_ACTION_DTMF_STREAM, dtmf, strlen(dtmf) + 1);
1078 }
1079
1080 /*!
1081  * \internal
1082  * \brief Indicate to the testsuite a feature was successfully detected.
1083  *
1084  * Currently, this function only will relay built-in features to the testsuite,
1085  * but it could be modified to detect applicationmap items should the need arise.
1086  *
1087  * \param chan The channel that activated the feature
1088  * \param dtmf The DTMF sequence entered to activate the feature
1089  */
1090 static void testsuite_notify_feature_success(struct ast_channel *chan, const char *dtmf)
1091 {
1092 #ifdef TEST_FRAMEWORK
1093         char *feature = "unknown";
1094         struct ast_featuremap_config *featuremap = ast_get_chan_featuremap_config(chan);
1095
1096         if (featuremap) {
1097                 if (!strcmp(dtmf, featuremap->blindxfer)) {
1098                         feature = "blindxfer";
1099                 } else if (!strcmp(dtmf, featuremap->atxfer)) {
1100                         feature = "atxfer";
1101                 } else if (!strcmp(dtmf, featuremap->disconnect)) {
1102                         feature = "disconnect";
1103                 } else if (!strcmp(dtmf, featuremap->automon)) {
1104                         feature = "automon";
1105                 } else if (!strcmp(dtmf, featuremap->automixmon)) {
1106                         feature = "automixmon";
1107                 } else if (!strcmp(dtmf, featuremap->parkcall)) {
1108                         feature = "parkcall";
1109                 }
1110         }
1111
1112         ast_test_suite_event_notify("FEATURE_DETECTION",
1113                         "Result: success\r\n"
1114                         "Feature: %s", feature);
1115 #endif /* TEST_FRAMEWORK */
1116 }
1117
1118 /*!
1119  * \internal
1120  * \brief Internal function that executes a feature on a bridge channel
1121  * \note Neither the bridge nor the bridge_channel locks should be held when entering
1122  * this function.
1123  */
1124 static void bridge_channel_feature(struct ast_bridge_channel *bridge_channel, const char *starting_dtmf)
1125 {
1126         struct ast_bridge_features *features = bridge_channel->features;
1127         struct ast_bridge_hook_dtmf *hook = NULL;
1128         char dtmf[MAXIMUM_DTMF_FEATURE_STRING];
1129         size_t dtmf_len;
1130         unsigned int digit_timeout;
1131         RAII_VAR(struct ast_features_general_config *, gen_cfg, NULL, ao2_cleanup);
1132
1133         ast_channel_lock(bridge_channel->chan);
1134         gen_cfg = ast_get_chan_features_general_config(bridge_channel->chan);
1135         if (!gen_cfg) {
1136                 ast_log(LOG_ERROR, "Unable to retrieve features configuration.\n");
1137                 ast_channel_unlock(bridge_channel->chan);
1138                 return;
1139         }
1140         digit_timeout = gen_cfg->featuredigittimeout;
1141         ast_channel_unlock(bridge_channel->chan);
1142
1143         if (ast_strlen_zero(starting_dtmf)) {
1144                 dtmf[0] = '\0';
1145                 dtmf_len = 0;
1146         } else {
1147                 ast_copy_string(dtmf, starting_dtmf, sizeof(dtmf));
1148                 dtmf_len = strlen(dtmf);
1149         }
1150
1151         /*
1152          * Check if any feature DTMF hooks match or could match and
1153          * try to collect more DTMF digits.
1154          */
1155         for (;;) {
1156                 int res;
1157
1158                 if (dtmf_len) {
1159                         ast_debug(1, "DTMF feature string on %p(%s) is now '%s'\n",
1160                                 bridge_channel, ast_channel_name(bridge_channel->chan), dtmf);
1161
1162                         /* See if a DTMF feature hook matches or can match */
1163                         hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_PARTIAL_KEY);
1164                         if (!hook) {
1165                                 ast_debug(1, "No DTMF feature hooks on %p(%s) match '%s'\n",
1166                                         bridge_channel, ast_channel_name(bridge_channel->chan), dtmf);
1167                                 break;
1168                         }
1169                         if (strlen(hook->dtmf.code) == dtmf_len) {
1170                                 ast_debug(1, "DTMF feature hook %p matched DTMF string '%s' on %p(%s)\n",
1171                                         hook, dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
1172                                 break;
1173                         }
1174                         ao2_ref(hook, -1);
1175                         hook = NULL;
1176
1177                         if (ARRAY_LEN(dtmf) - 1 <= dtmf_len) {
1178                                 /* We have reached the maximum length of a DTMF feature string. */
1179                                 break;
1180                         }
1181                 }
1182
1183                 res = ast_waitfordigit(bridge_channel->chan, digit_timeout);
1184                 if (!res) {
1185                         ast_debug(1, "DTMF feature string collection on %p(%s) timed out\n",
1186                                 bridge_channel, ast_channel_name(bridge_channel->chan));
1187                         break;
1188                 }
1189                 if (res < 0) {
1190                         ast_debug(1, "DTMF feature string collection failed on %p(%s) for some reason\n",
1191                                 bridge_channel, ast_channel_name(bridge_channel->chan));
1192                         break;
1193                 }
1194
1195                 /* Add the new DTMF into the DTMF string so we can do our matching */
1196                 dtmf[dtmf_len] = res;
1197                 dtmf[++dtmf_len] = '\0';
1198         }
1199
1200         if (hook) {
1201                 int remove_me;
1202
1203                 /* Execute the matched hook on this channel. */
1204                 remove_me = hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
1205                 if (remove_me) {
1206                         ast_debug(1, "DTMF hook %p is being removed from %p(%s)\n",
1207                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1208                         ao2_unlink(features->dtmf_hooks, hook);
1209                 }
1210                 testsuite_notify_feature_success(bridge_channel->chan, hook->dtmf.code);
1211                 ao2_ref(hook, -1);
1212
1213                 /*
1214                  * If we are handing the channel off to an external hook for
1215                  * ownership, we are not guaranteed what kind of state it will
1216                  * come back in.  If the channel hungup, we need to detect that
1217                  * here if the hook did not already change the state.
1218                  */
1219                 if (bridge_channel->chan && ast_check_hangup_locked(bridge_channel->chan)) {
1220                         ast_bridge_channel_kick(bridge_channel, 0);
1221                 }
1222         } else {
1223                 if (features->dtmf_passthrough) {
1224                         /* Stream any collected DTMF to the other channels. */
1225                         bridge_channel_write_dtmf_stream(bridge_channel, dtmf);
1226                 }
1227                 ast_test_suite_event_notify("FEATURE_DETECTION", "Result: fail");
1228         }
1229 }
1230
1231 /*!
1232  * \internal
1233  * \brief Indicate that a bridge_channel is talking
1234  */
1235 static void bridge_channel_talking(struct ast_bridge_channel *bridge_channel, int talking)
1236 {
1237         struct ast_bridge_features *features = bridge_channel->features;
1238         struct ast_bridge_hook *hook;
1239         struct ao2_iterator iter;
1240
1241         /* Run any talk detection hooks. */
1242         iter = ao2_iterator_init(features->other_hooks, 0);
1243         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
1244                 int remove_me;
1245                 ast_bridge_talking_indicate_callback talk_cb;
1246
1247                 if (hook->type != AST_BRIDGE_HOOK_TYPE_TALK) {
1248                         continue;
1249                 }
1250                 talk_cb = (ast_bridge_talking_indicate_callback) hook->callback;
1251                 remove_me = talk_cb(bridge_channel, hook->hook_pvt, talking);
1252                 if (remove_me) {
1253                         ast_debug(1, "Talk detection hook %p is being removed from %p(%s)\n",
1254                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1255                         ao2_unlink(features->other_hooks, hook);
1256                 }
1257         }
1258         ao2_iterator_destroy(&iter);
1259 }
1260
1261 /*! \brief Internal function that plays back DTMF on a bridge channel */
1262 static void bridge_channel_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
1263 {
1264         ast_debug(1, "Playing DTMF stream '%s' out to %p(%s)\n",
1265                 dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
1266         ast_dtmf_stream(bridge_channel->chan, NULL, dtmf, 0, 0);
1267 }
1268
1269 /*! \brief Data specifying where a blind transfer is going to */
1270 struct blind_transfer_data {
1271         char exten[AST_MAX_EXTENSION];
1272         char context[AST_MAX_CONTEXT];
1273 };
1274
1275 /*!
1276  * \internal
1277  * \brief Execute after bridge actions on a channel when it leaves a bridge
1278  */
1279 static void after_bridge_move_channel(struct ast_channel *chan_bridged, void *data)
1280 {
1281         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1282         struct ast_party_connected_line connected_target;
1283         unsigned char connected_line_data[1024];
1284         int payload_size;
1285
1286         ast_party_connected_line_init(&connected_target);
1287
1288         ast_channel_lock(chan_target);
1289         ast_party_connected_line_copy(&connected_target, ast_channel_connected(chan_target));
1290         ast_channel_unlock(chan_target);
1291         ast_party_id_reset(&connected_target.priv);
1292
1293         if (ast_channel_move(chan_target, chan_bridged)) {
1294                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1295                 ast_party_connected_line_free(&connected_target);
1296                 return;
1297         }
1298
1299         if ((payload_size = ast_connected_line_build_data(connected_line_data,
1300                 sizeof(connected_line_data), &connected_target, NULL)) != -1) {
1301                 struct ast_control_read_action_payload *frame_payload;
1302                 int frame_size;
1303
1304                 frame_size = payload_size + sizeof(*frame_payload);
1305                 frame_payload = ast_alloca(frame_size);
1306                 frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
1307                 frame_payload->payload_size = payload_size;
1308                 memcpy(frame_payload->payload, connected_line_data, payload_size);
1309                 ast_queue_control_data(chan_target, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
1310         }
1311
1312         ast_party_connected_line_free(&connected_target);
1313 }
1314
1315 /*!
1316  * \internal
1317  * \brief Execute logic to cleanup when after bridge fails
1318  */
1319 static void after_bridge_move_channel_fail(enum ast_bridge_after_cb_reason reason, void *data)
1320 {
1321         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1322
1323         ast_log(LOG_WARNING, "Unable to complete transfer: %s\n",
1324                 ast_bridge_after_cb_reason_string(reason));
1325         ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1326 }
1327
1328 /*!
1329  * \internal
1330  * \brief Perform a blind transfer on a channel in a bridge
1331  */
1332 static void bridge_channel_blind_transfer(struct ast_bridge_channel *bridge_channel,
1333                 struct blind_transfer_data *blind_data)
1334 {
1335         ast_async_goto(bridge_channel->chan, blind_data->context, blind_data->exten, 1);
1336         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1337 }
1338
1339 /*!
1340  * \internal
1341  * \brief Perform an attended transfer on a channel in a bridge
1342  */
1343 static void bridge_channel_attended_transfer(struct ast_bridge_channel *bridge_channel,
1344                 const char *target_chan_name)
1345 {
1346         RAII_VAR(struct ast_channel *, chan_target, NULL, ao2_cleanup);
1347         RAII_VAR(struct ast_channel *, chan_bridged, NULL, ao2_cleanup);
1348
1349         chan_target = ast_channel_get_by_name(target_chan_name);
1350         if (!chan_target) {
1351                 /* Dang, it disappeared somehow */
1352                 ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1353                 return;
1354         }
1355
1356         ast_bridge_channel_lock(bridge_channel);
1357         chan_bridged = bridge_channel->chan;
1358         ast_assert(chan_bridged != NULL);
1359         ao2_ref(chan_bridged, +1);
1360         ast_bridge_channel_unlock(bridge_channel);
1361
1362         if (ast_bridge_set_after_callback(chan_bridged, after_bridge_move_channel,
1363                 after_bridge_move_channel_fail, ast_channel_ref(chan_target))) {
1364                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1365
1366                 /* Release the ref we tried to pass to ast_bridge_set_after_callback(). */
1367                 ast_channel_unref(chan_target);
1368         }
1369         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1370 }
1371
1372 /*!
1373  * \internal
1374  * \brief Handle bridge channel bridge action frame.
1375  * \since 12.0.0
1376  *
1377  * \param bridge_channel Channel to execute the action on.
1378  * \param action What to do.
1379  *
1380  * \return Nothing
1381  */
1382 static void bridge_channel_handle_action(struct ast_bridge_channel *bridge_channel, struct ast_frame *action)
1383 {
1384         switch (action->subclass.integer) {
1385         case BRIDGE_CHANNEL_ACTION_DTMF_STREAM:
1386                 bridge_channel_suspend(bridge_channel);
1387                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1388                 bridge_channel_dtmf_stream(bridge_channel, action->data.ptr);
1389                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1390                 bridge_channel_unsuspend(bridge_channel);
1391                 break;
1392         case BRIDGE_CHANNEL_ACTION_TALKING_START:
1393         case BRIDGE_CHANNEL_ACTION_TALKING_STOP:
1394                 bridge_channel_talking(bridge_channel,
1395                         action->subclass.integer == BRIDGE_CHANNEL_ACTION_TALKING_START);
1396                 break;
1397         case BRIDGE_CHANNEL_ACTION_PLAY_FILE:
1398                 bridge_channel_suspend(bridge_channel);
1399                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1400                 bridge_channel_playfile(bridge_channel, action->data.ptr);
1401                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1402                 bridge_channel_unsuspend(bridge_channel);
1403                 break;
1404         case BRIDGE_CHANNEL_ACTION_RUN_APP:
1405                 bridge_channel_suspend(bridge_channel);
1406                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1407                 bridge_channel_run_app(bridge_channel, action->data.ptr);
1408                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1409                 bridge_channel_unsuspend(bridge_channel);
1410                 break;
1411         case BRIDGE_CHANNEL_ACTION_CALLBACK:
1412                 bridge_channel_do_callback(bridge_channel, action->data.ptr);
1413                 break;
1414         case BRIDGE_CHANNEL_ACTION_PARK:
1415                 bridge_channel_suspend(bridge_channel);
1416                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1417                 bridge_channel_park(bridge_channel, action->data.ptr);
1418                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1419                 bridge_channel_unsuspend(bridge_channel);
1420                 break;
1421         case BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER:
1422                 bridge_channel_blind_transfer(bridge_channel, action->data.ptr);
1423                 break;
1424         case BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER:
1425                 bridge_channel_attended_transfer(bridge_channel, action->data.ptr);
1426                 break;
1427         default:
1428                 break;
1429         }
1430 }
1431
1432 /*!
1433  * \internal
1434  * \brief Check if a bridge should dissolve and do it.
1435  * \since 12.0.0
1436  *
1437  * \param bridge_channel Channel causing the check.
1438  *
1439  * \note On entry, bridge_channel->bridge is already locked.
1440  *
1441  * \return Nothing
1442  */
1443 static void bridge_channel_dissolve_check(struct ast_bridge_channel *bridge_channel)
1444 {
1445         struct ast_bridge *bridge = bridge_channel->bridge;
1446
1447         if (bridge->dissolved) {
1448                 return;
1449         }
1450
1451         if (!bridge->num_channels
1452                 && ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY)) {
1453                 /* Last channel leaving the bridge turns off the lights. */
1454                 bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
1455                 return;
1456         }
1457
1458         switch (bridge_channel->state) {
1459         case BRIDGE_CHANNEL_STATE_END:
1460                 /* Do we need to dissolve the bridge because this channel hung up? */
1461                 if (ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_HANGUP)
1462                         || (bridge_channel->features->usable
1463                                 && ast_test_flag(&bridge_channel->features->feature_flags,
1464                                         AST_BRIDGE_CHANNEL_FLAG_DISSOLVE_HANGUP))) {
1465                         bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
1466                         return;
1467                 }
1468                 break;
1469         default:
1470                 break;
1471         }
1472
1473         if (bridge->num_lonely && bridge->num_lonely == bridge->num_channels) {
1474                 /*
1475                  * This will start a chain reaction where each channel leaving
1476                  * enters this function and causes the next to leave as long as
1477                  * there aren't non-lonely channels in the bridge.
1478                  */
1479                 ast_bridge_channel_leave_bridge(AST_LIST_FIRST(&bridge->channels),
1480                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE,
1481                         ast_channel_hangupcause(bridge_channel->chan));
1482         }
1483 }
1484
1485 void bridge_channel_internal_pull(struct ast_bridge_channel *bridge_channel)
1486 {
1487         struct ast_bridge *bridge = bridge_channel->bridge;
1488
1489         if (!bridge_channel->in_bridge) {
1490                 return;
1491         }
1492         bridge_channel->in_bridge = 0;
1493
1494         ast_debug(1, "Bridge %s: pulling %p(%s)\n",
1495                 bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1496
1497         ast_verb(3, "Channel %s left '%s' %s-bridge <%s>\n",
1498                 ast_channel_name(bridge_channel->chan),
1499                 bridge->technology->name,
1500                 bridge->v_table->name,
1501                 bridge->uniqueid);
1502
1503         if (!bridge_channel->just_joined) {
1504                 /* Tell the bridge technology we are leaving so they tear us down */
1505                 ast_debug(1, "Bridge %s: %p(%s) is leaving %s technology\n",
1506                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1507                         bridge->technology->name);
1508                 if (bridge->technology->leave) {
1509                         bridge->technology->leave(bridge, bridge_channel);
1510                 }
1511         }
1512
1513         /* Remove channel from the bridge */
1514         if (!bridge_channel->suspended) {
1515                 --bridge->num_active;
1516         }
1517         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
1518                 --bridge->num_lonely;
1519         }
1520         --bridge->num_channels;
1521         AST_LIST_REMOVE(&bridge->channels, bridge_channel, entry);
1522         bridge->v_table->pull(bridge, bridge_channel);
1523
1524         ast_bridge_channel_clear_roles(bridge_channel);
1525
1526         /* If we are not going to be hung up after leaving a bridge, and we were an
1527          * outgoing channel, clear the outgoing flag.
1528          */
1529         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING)
1530                         && (ast_channel_softhangup_internal_flag(bridge_channel->chan) & (AST_SOFTHANGUP_ASYNCGOTO | AST_SOFTHANGUP_UNBRIDGE)
1531                             || bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT)) {
1532                 ast_debug(2, "Channel %s will survive this bridge; clearing outgoing (dialed) flag\n", ast_channel_name(bridge_channel->chan));
1533                 ast_clear_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING);
1534         }
1535
1536         bridge_channel_dissolve_check(bridge_channel);
1537
1538         bridge->reconfigured = 1;
1539         ast_bridge_publish_leave(bridge, bridge_channel->chan);
1540 }
1541
1542 int bridge_channel_internal_push(struct ast_bridge_channel *bridge_channel)
1543 {
1544         struct ast_bridge *bridge = bridge_channel->bridge;
1545         struct ast_bridge_channel *swap;
1546
1547         ast_assert(!bridge_channel->in_bridge);
1548
1549         swap = bridge_find_channel(bridge, bridge_channel->swap);
1550         bridge_channel->swap = NULL;
1551
1552         if (swap) {
1553                 ast_debug(1, "Bridge %s: pushing %p(%s) by swapping with %p(%s)\n",
1554                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1555                         swap, ast_channel_name(swap->chan));
1556         } else {
1557                 ast_debug(1, "Bridge %s: pushing %p(%s)\n",
1558                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1559         }
1560
1561         /* Add channel to the bridge */
1562         if (bridge->dissolved
1563                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
1564                 || (swap && swap->state != BRIDGE_CHANNEL_STATE_WAIT)
1565                 || bridge->v_table->push(bridge, bridge_channel, swap)
1566                 || ast_bridge_channel_establish_roles(bridge_channel)) {
1567                 ast_debug(1, "Bridge %s: pushing %p(%s) into bridge failed\n",
1568                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1569                 ast_bridge_features_remove(bridge_channel->features, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
1570                 return -1;
1571         }
1572         bridge_channel->in_bridge = 1;
1573         bridge_channel->just_joined = 1;
1574         AST_LIST_INSERT_TAIL(&bridge->channels, bridge_channel, entry);
1575         ++bridge->num_channels;
1576         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
1577                 ++bridge->num_lonely;
1578         }
1579         if (!bridge_channel->suspended) {
1580                 ++bridge->num_active;
1581         }
1582
1583         ast_verb(3, "Channel %s %s%s%s '%s' %s-bridge <%s>\n",
1584                 ast_channel_name(bridge_channel->chan),
1585                 swap ? "swapped with " : "joined",
1586                 swap ? ast_channel_name(swap->chan) : "",
1587                 swap ? " into" : "",
1588                 bridge->technology->name,
1589                 bridge->v_table->name,
1590                 bridge->uniqueid);
1591
1592         ast_bridge_publish_enter(bridge, bridge_channel->chan, swap ? swap->chan : NULL);
1593         if (swap) {
1594                 ast_bridge_channel_leave_bridge(swap, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, 0);
1595                 bridge_channel_internal_pull(swap);
1596         }
1597
1598         /* Clear any BLINDTRANSFER and ATTENDEDTRANSFER since the transfer has completed. */
1599         pbx_builtin_setvar_helper(bridge_channel->chan, "BLINDTRANSFER", NULL);
1600         pbx_builtin_setvar_helper(bridge_channel->chan, "ATTENDEDTRANSFER", NULL);
1601
1602         /* Wake up the bridge channel thread to reevaluate any interval timers. */
1603         ast_queue_frame(bridge_channel->chan, &ast_null_frame);
1604
1605         bridge->reconfigured = 1;
1606         return 0;
1607 }
1608
1609 /*!
1610  * \internal
1611  * \brief Handle bridge channel control frame action.
1612  * \since 12.0.0
1613  *
1614  * \param bridge_channel Channel to execute the control frame action on.
1615  * \param fr Control frame to handle.
1616  *
1617  * \return Nothing
1618  */
1619 static void bridge_channel_handle_control(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
1620 {
1621         struct ast_channel *chan;
1622         struct ast_option_header *aoh;
1623         int is_caller;
1624
1625         chan = bridge_channel->chan;
1626         switch (fr->subclass.integer) {
1627         case AST_CONTROL_REDIRECTING:
1628                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
1629                 if (ast_channel_redirecting_sub(NULL, chan, fr, 1) &&
1630                         ast_channel_redirecting_macro(NULL, chan, fr, is_caller, 1)) {
1631                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1632                 }
1633                 break;
1634         case AST_CONTROL_CONNECTED_LINE:
1635                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
1636                 if (ast_channel_connected_line_sub(NULL, chan, fr, 1) &&
1637                         ast_channel_connected_line_macro(NULL, chan, fr, is_caller, 1)) {
1638                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1639                 }
1640                 break;
1641         case AST_CONTROL_OPTION:
1642                 /*
1643                  * Forward option Requests, but only ones we know are safe These
1644                  * are ONLY sent by chan_iax2 and I'm not convinced that they
1645                  * are useful. I haven't deleted them entirely because I just am
1646                  * not sure of the ramifications of removing them.
1647                  */
1648                 aoh = fr->data.ptr;
1649                 if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
1650                         switch (ntohs(aoh->option)) {
1651                         case AST_OPTION_TONE_VERIFY:
1652                         case AST_OPTION_TDD:
1653                         case AST_OPTION_RELAXDTMF:
1654                         case AST_OPTION_AUDIO_MODE:
1655                         case AST_OPTION_DIGIT_DETECT:
1656                         case AST_OPTION_FAX_DETECT:
1657                                 ast_channel_setoption(chan, ntohs(aoh->option), aoh->data,
1658                                         fr->datalen - sizeof(*aoh), 0);
1659                                 break;
1660                         default:
1661                                 break;
1662                         }
1663                 }
1664                 break;
1665         case AST_CONTROL_ANSWER:
1666                 if (ast_channel_state(chan) != AST_STATE_UP) {
1667                         ast_answer(chan);
1668                 } else {
1669                         ast_indicate(chan, -1);
1670                 }
1671                 break;
1672         default:
1673                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1674                 break;
1675         }
1676 }
1677
1678 /*!
1679  * \internal
1680  * \brief Handle bridge channel write frame to channel.
1681  * \since 12.0.0
1682  *
1683  * \param bridge_channel Channel to write outgoing frame.
1684  *
1685  * \return Nothing
1686  */
1687 static void bridge_channel_handle_write(struct ast_bridge_channel *bridge_channel)
1688 {
1689         struct ast_frame *fr;
1690         char nudge;
1691
1692         ast_bridge_channel_lock(bridge_channel);
1693         if (read(bridge_channel->alert_pipe[0], &nudge, sizeof(nudge)) < 0) {
1694                 if (errno != EINTR && errno != EAGAIN) {
1695                         ast_log(LOG_WARNING, "read() failed for alert pipe on %p(%s): %s\n",
1696                                 bridge_channel, ast_channel_name(bridge_channel->chan), strerror(errno));
1697                 }
1698         }
1699         fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list);
1700         ast_bridge_channel_unlock(bridge_channel);
1701         if (!fr) {
1702                 return;
1703         }
1704         switch (fr->frametype) {
1705         case AST_FRAME_BRIDGE_ACTION:
1706                 bridge_channel_handle_action(bridge_channel, fr);
1707                 break;
1708         case AST_FRAME_CONTROL:
1709                 bridge_channel_handle_control(bridge_channel, fr);
1710                 break;
1711         case AST_FRAME_NULL:
1712                 break;
1713         default:
1714                 /* Write the frame to the channel. */
1715                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_SIMPLE;
1716                 ast_write(bridge_channel->chan, fr);
1717                 break;
1718         }
1719         ast_frfree(fr);
1720 }
1721
1722 /*! \brief Internal function to handle DTMF from a channel */
1723 static struct ast_frame *bridge_handle_dtmf(struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
1724 {
1725         struct ast_bridge_features *features = bridge_channel->features;
1726         struct ast_bridge_hook_dtmf *hook;
1727         char dtmf[2];
1728
1729         /* See if this DTMF matches the beginning of any feature hooks. */
1730         dtmf[0] = frame->subclass.integer;
1731         dtmf[1] = '\0';
1732         hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_PARTIAL_KEY);
1733         if (hook) {
1734                 enum ast_frame_type frametype = frame->frametype;
1735
1736                 ast_frfree(frame);
1737                 frame = NULL;
1738
1739                 ao2_ref(hook, -1);
1740
1741                 /* Collect any more needed DTMF to execute a hook. */
1742                 bridge_channel_suspend(bridge_channel);
1743                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1744                 switch (frametype) {
1745                 case AST_FRAME_DTMF_BEGIN:
1746                         bridge_channel_feature(bridge_channel, NULL);
1747                         break;
1748                 case AST_FRAME_DTMF_END:
1749                         bridge_channel_feature(bridge_channel, dtmf);
1750                         break;
1751                 default:
1752                         /* Unexpected frame type. */
1753                         ast_assert(0);
1754                         break;
1755                 }
1756                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1757                 bridge_channel_unsuspend(bridge_channel);
1758 #ifdef TEST_FRAMEWORK
1759         } else if (frame->frametype == AST_FRAME_DTMF_END) {
1760                 /* Only transmit this event on DTMF end or else every DTMF
1761                  * press will result in the event being broadcast twice
1762                  */
1763                 ast_test_suite_event_notify("FEATURE_DETECTION", "Result: fail");
1764 #endif
1765         }
1766
1767         return frame;
1768 }
1769
1770
1771 /*!
1772  * \internal
1773  * \brief Feed notification that a frame is waiting on a channel into the bridging core
1774  *
1775  * \param bridge_channel Bridge channel the notification was received on
1776  */
1777 static void bridge_handle_trip(struct ast_bridge_channel *bridge_channel)
1778 {
1779         struct ast_frame *frame;
1780
1781         if (bridge_channel->features->mute) {
1782                 frame = ast_read_noaudio(bridge_channel->chan);
1783         } else {
1784                 frame = ast_read(bridge_channel->chan);
1785         }
1786
1787         if (!frame) {
1788                 ast_bridge_channel_kick(bridge_channel, 0);
1789                 return;
1790         }
1791         switch (frame->frametype) {
1792         case AST_FRAME_CONTROL:
1793                 switch (frame->subclass.integer) {
1794                 case AST_CONTROL_HANGUP:
1795                         ast_bridge_channel_kick(bridge_channel, 0);
1796                         ast_frfree(frame);
1797                         return;
1798                 default:
1799                         break;
1800                 }
1801                 break;
1802         case AST_FRAME_DTMF_BEGIN:
1803         case AST_FRAME_DTMF_END:
1804                 frame = bridge_handle_dtmf(bridge_channel, frame);
1805                 if (!frame) {
1806                         return;
1807                 }
1808                 if (!bridge_channel->features->dtmf_passthrough) {
1809                         ast_frfree(frame);
1810                         return;
1811                 }
1812                 break;
1813         default:
1814                 break;
1815         }
1816
1817         /* Simply write the frame out to the bridge technology. */
1818         bridge_channel_write_frame(bridge_channel, frame);
1819         ast_frfree(frame);
1820 }
1821
1822 /*!
1823  * \internal
1824  * \brief Determine how long till the next timer interval.
1825  * \since 12.0.0
1826  *
1827  * \param bridge_channel Channel to determine how long can wait.
1828  *
1829  * \retval ms Number of milliseconds to wait.
1830  * \retval -1 to wait forever.
1831  */
1832 static int bridge_channel_next_interval(struct ast_bridge_channel *bridge_channel)
1833 {
1834         struct ast_heap *interval_hooks = bridge_channel->features->interval_hooks;
1835         struct ast_bridge_hook_timer *hook;
1836         int ms;
1837
1838         ast_heap_wrlock(interval_hooks);
1839         hook = ast_heap_peek(interval_hooks, 1);
1840         if (hook) {
1841                 ms = ast_tvdiff_ms(hook->timer.trip_time, ast_tvnow());
1842                 if (ms < 0) {
1843                         /* Expire immediately.  An interval hook is ready to run. */
1844                         ms = 0;
1845                 }
1846         } else {
1847                 /* No hook so wait forever. */
1848                 ms = -1;
1849         }
1850         ast_heap_unlock(interval_hooks);
1851
1852         return ms;
1853 }
1854
1855 /*!
1856  * \internal
1857  * \brief Wait for something to happen on the bridge channel and handle it.
1858  * \since 12.0.0
1859  *
1860  * \param bridge_channel Channel to wait.
1861  *
1862  * \note Each channel does writing/reading in their own thread.
1863  *
1864  * \return Nothing
1865  */
1866 static void bridge_channel_wait(struct ast_bridge_channel *bridge_channel)
1867 {
1868         int ms;
1869         int outfd;
1870         struct ast_channel *chan;
1871
1872         /* Wait for data to either come from the channel or us to be signaled */
1873         ast_bridge_channel_lock(bridge_channel);
1874         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
1875         } else if (bridge_channel->suspended) {
1876 /* XXX ASTERISK-21271 the external party use of suspended will go away as will these references because this is the bridge channel thread */
1877                 ast_debug(1, "Bridge %s: %p(%s) is going into a signal wait\n",
1878                         bridge_channel->bridge->uniqueid, bridge_channel,
1879                         ast_channel_name(bridge_channel->chan));
1880                 ast_cond_wait(&bridge_channel->cond, ao2_object_get_lockaddr(bridge_channel));
1881         } else {
1882                 ast_debug(10, "Bridge %s: %p(%s) is going into a waitfor\n",
1883                         bridge_channel->bridge->uniqueid, bridge_channel,
1884                         ast_channel_name(bridge_channel->chan));
1885                 ast_bridge_channel_unlock(bridge_channel);
1886                 outfd = -1;
1887                 ms = bridge_channel_next_interval(bridge_channel);
1888                 chan = ast_waitfor_nandfds(&bridge_channel->chan, 1,
1889                         &bridge_channel->alert_pipe[0], 1, NULL, &outfd, &ms);
1890                 if (ast_channel_softhangup_internal_flag(bridge_channel->chan) & AST_SOFTHANGUP_UNBRIDGE) {
1891                         ast_channel_clear_softhangup(bridge_channel->chan, AST_SOFTHANGUP_UNBRIDGE);
1892                         ast_bridge_channel_lock_bridge(bridge_channel);
1893                         bridge_channel->bridge->reconfigured = 1;
1894                         bridge_reconfigured(bridge_channel->bridge, 0);
1895                         ast_bridge_unlock(bridge_channel->bridge);
1896                 }
1897                 ast_bridge_channel_lock(bridge_channel);
1898                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_FRAME;
1899                 ast_bridge_channel_unlock(bridge_channel);
1900                 if (!bridge_channel->suspended
1901                         && bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
1902                         if (chan) {
1903                                 bridge_handle_trip(bridge_channel);
1904                         } else if (-1 < outfd) {
1905                                 bridge_channel_handle_write(bridge_channel);
1906                         } else if (ms == 0) {
1907                                 /* An interval expired. */
1908                                 bridge_channel_handle_interval(bridge_channel);
1909                         }
1910                 }
1911                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_IDLE;
1912                 return;
1913         }
1914         ast_bridge_channel_unlock(bridge_channel);
1915 }
1916
1917 /*!
1918  * \internal
1919  * \brief Handle bridge channel join/leave event.
1920  * \since 12.0.0
1921  *
1922  * \param bridge_channel Which channel is involved.
1923  * \param type Specified join/leave event.
1924  *
1925  * \return Nothing
1926  */
1927 static void bridge_channel_event_join_leave(struct ast_bridge_channel *bridge_channel, enum ast_bridge_hook_type type)
1928 {
1929         struct ast_bridge_features *features = bridge_channel->features;
1930         struct ast_bridge_hook *hook;
1931         struct ao2_iterator iter;
1932
1933         /* Run the specified hooks. */
1934         iter = ao2_iterator_init(features->other_hooks, 0);
1935         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
1936                 if (hook->type == type) {
1937                         break;
1938                 }
1939         }
1940         if (hook) {
1941                 /* Found the first specified hook to run. */
1942                 bridge_channel_suspend(bridge_channel);
1943                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1944                 do {
1945                         if (hook->type == type) {
1946                                 hook->callback(bridge_channel, hook->hook_pvt);
1947                                 ao2_unlink(features->other_hooks, hook);
1948                         }
1949                         ao2_ref(hook, -1);
1950                 } while ((hook = ao2_iterator_next(&iter)));
1951                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1952                 bridge_channel_unsuspend(bridge_channel);
1953         }
1954         ao2_iterator_destroy(&iter);
1955 }
1956
1957 /*! \brief Join a channel to a bridge and handle anything the bridge may want us to do */
1958 int bridge_channel_internal_join(struct ast_bridge_channel *bridge_channel)
1959 {
1960         int res = 0;
1961
1962         ast_format_copy(&bridge_channel->read_format, ast_channel_readformat(bridge_channel->chan));
1963         ast_format_copy(&bridge_channel->write_format, ast_channel_writeformat(bridge_channel->chan));
1964
1965         ast_debug(1, "Bridge %s: %p(%s) is joining\n",
1966                 bridge_channel->bridge->uniqueid,
1967                 bridge_channel, ast_channel_name(bridge_channel->chan));
1968
1969         /*
1970          * Directly locking the bridge is safe here because nobody else
1971          * knows about this bridge_channel yet.
1972          */
1973         ast_bridge_lock(bridge_channel->bridge);
1974
1975         /* Make sure we're still good to be put into a bridge
1976          */
1977         ast_channel_lock(bridge_channel->chan);
1978         if (ast_channel_internal_bridge(bridge_channel->chan)
1979                 || ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_ZOMBIE)) {
1980                 ast_channel_unlock(bridge_channel->chan);
1981                 ast_bridge_unlock(bridge_channel->bridge);
1982                 ast_debug(1, "Bridge %s: %p(%s) failed to join Bridge\n",
1983                         bridge_channel->bridge->uniqueid,
1984                         bridge_channel,
1985                         ast_channel_name(bridge_channel->chan));
1986                 return -1;
1987         }
1988         ast_channel_internal_bridge_set(bridge_channel->chan, bridge_channel->bridge);
1989         ast_channel_unlock(bridge_channel->chan);
1990
1991         /* Add the jitterbuffer if the channel requires it */
1992         ast_jb_enable_for_channel(bridge_channel->chan);
1993
1994         if (!bridge_channel->bridge->callid) {
1995                 bridge_channel->bridge->callid = ast_read_threadstorage_callid();
1996         }
1997
1998         if (bridge_channel_internal_push(bridge_channel)) {
1999                 ast_bridge_channel_leave_bridge(bridge_channel,
2000                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, bridge_channel->bridge->cause);
2001                 res = -1;
2002         }
2003         bridge_reconfigured(bridge_channel->bridge, !bridge_channel->inhibit_colp);
2004
2005         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2006                 /*
2007                  * Indicate a source change since this channel is entering the
2008                  * bridge system only if the bridge technology is not MULTIMIX
2009                  * capable.  The MULTIMIX technology has already done it.
2010                  */
2011                 if (!(bridge_channel->bridge->technology->capabilities
2012                         & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
2013                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2014                 }
2015
2016                 ast_bridge_unlock(bridge_channel->bridge);
2017                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_JOIN);
2018                 while (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2019                         /* Wait for something to do. */
2020                         bridge_channel_wait(bridge_channel);
2021                 }
2022                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_LEAVE);
2023                 ast_bridge_channel_lock_bridge(bridge_channel);
2024         }
2025
2026         bridge_channel_internal_pull(bridge_channel);
2027         bridge_channel_settle_owed_events(bridge_channel->bridge, bridge_channel);
2028         bridge_reconfigured(bridge_channel->bridge, 1);
2029
2030         ast_bridge_unlock(bridge_channel->bridge);
2031
2032         /* Complete any active hold before exiting the bridge. */
2033         if (ast_channel_hold_state(bridge_channel->chan) == AST_CONTROL_HOLD) {
2034                 ast_debug(1, "Channel %s simulating UNHOLD for bridge end.\n",
2035                         ast_channel_name(bridge_channel->chan));
2036                 ast_indicate(bridge_channel->chan, AST_CONTROL_UNHOLD);
2037         }
2038
2039         /* Complete any partial DTMF digit before exiting the bridge. */
2040         if (ast_channel_sending_dtmf_digit(bridge_channel->chan)) {
2041                 ast_channel_end_dtmf(bridge_channel->chan,
2042                         ast_channel_sending_dtmf_digit(bridge_channel->chan),
2043                         ast_channel_sending_dtmf_tv(bridge_channel->chan), "bridge end");
2044         }
2045
2046         /* Indicate a source change since this channel is leaving the bridge system. */
2047         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2048
2049         /*
2050          * Wait for any dual redirect to complete.
2051          *
2052          * Must be done while "still in the bridge" for ast_async_goto()
2053          * to work right.
2054          */
2055         while (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT)) {
2056                 sched_yield();
2057         }
2058         ast_channel_lock(bridge_channel->chan);
2059         ast_channel_internal_bridge_set(bridge_channel->chan, NULL);
2060         ast_channel_unlock(bridge_channel->chan);
2061
2062         ast_bridge_channel_restore_formats(bridge_channel);
2063
2064         return res;
2065 }
2066
2067 int bridge_channel_internal_queue_blind_transfer(struct ast_channel *transferee,
2068                 const char *exten, const char *context,
2069                 transfer_channel_cb new_channel_cb, void *user_data)
2070 {
2071         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
2072         struct blind_transfer_data blind_data;
2073
2074         ast_channel_lock(transferee);
2075         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
2076         ast_channel_unlock(transferee);
2077
2078         if (!transferee_bridge_channel) {
2079                 return -1;
2080         }
2081
2082         if (new_channel_cb) {
2083                 new_channel_cb(transferee, user_data, AST_BRIDGE_TRANSFER_SINGLE_PARTY);
2084         }
2085
2086         ast_copy_string(blind_data.exten, exten, sizeof(blind_data.exten));
2087         ast_copy_string(blind_data.context, context, sizeof(blind_data.context));
2088
2089         return bridge_channel_queue_action_data(transferee_bridge_channel,
2090                 BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER, &blind_data, sizeof(blind_data));
2091 }
2092
2093 int bridge_channel_internal_queue_attended_transfer(struct ast_channel *transferee,
2094                 struct ast_channel *unbridged_chan)
2095 {
2096         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
2097         char unbridged_chan_name[AST_CHANNEL_NAME];
2098
2099         ast_channel_lock(transferee);
2100         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
2101         ast_channel_unlock(transferee);
2102
2103         if (!transferee_bridge_channel) {
2104                 return -1;
2105         }
2106
2107         ast_copy_string(unbridged_chan_name, ast_channel_name(unbridged_chan),
2108                 sizeof(unbridged_chan_name));
2109
2110         return bridge_channel_queue_action_data(transferee_bridge_channel,
2111                 BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER, unbridged_chan_name,
2112                 sizeof(unbridged_chan_name));
2113 }
2114
2115 int bridge_channel_internal_allows_optimization(struct ast_bridge_channel *bridge_channel)
2116 {
2117         return bridge_channel->in_bridge
2118                 && AST_LIST_EMPTY(&bridge_channel->wr_queue);
2119 }
2120
2121 /*!
2122  * \internal
2123  * \brief Close a pipe.
2124  * \since 12.0.0
2125  *
2126  * \param my_pipe What to close.
2127  *
2128  * \return Nothing
2129  */
2130 static void pipe_close(int *my_pipe)
2131 {
2132         if (my_pipe[0] > -1) {
2133                 close(my_pipe[0]);
2134                 my_pipe[0] = -1;
2135         }
2136         if (my_pipe[1] > -1) {
2137                 close(my_pipe[1]);
2138                 my_pipe[1] = -1;
2139         }
2140 }
2141
2142 /*!
2143  * \internal
2144  * \brief Initialize a pipe as non-blocking.
2145  * \since 12.0.0
2146  *
2147  * \param my_pipe What to initialize.
2148  *
2149  * \retval 0 on success.
2150  * \retval -1 on error.
2151  */
2152 static int pipe_init_nonblock(int *my_pipe)
2153 {
2154         int flags;
2155
2156         my_pipe[0] = -1;
2157         my_pipe[1] = -1;
2158         if (pipe(my_pipe)) {
2159                 ast_log(LOG_WARNING, "Can't create pipe! Try increasing max file descriptors with ulimit -n\n");
2160                 return -1;
2161         }
2162         flags = fcntl(my_pipe[0], F_GETFL);
2163         if (fcntl(my_pipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
2164                 ast_log(LOG_WARNING, "Unable to set read pipe nonblocking! (%d: %s)\n",
2165                         errno, strerror(errno));
2166                 return -1;
2167         }
2168         flags = fcntl(my_pipe[1], F_GETFL);
2169         if (fcntl(my_pipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
2170                 ast_log(LOG_WARNING, "Unable to set write pipe nonblocking! (%d: %s)\n",
2171                         errno, strerror(errno));
2172                 return -1;
2173         }
2174         return 0;
2175 }
2176
2177 /* Destroy elements of the bridge channel structure and the bridge channel structure itself */
2178 static void bridge_channel_destroy(void *obj)
2179 {
2180         struct ast_bridge_channel *bridge_channel = obj;
2181         struct ast_frame *fr;
2182
2183         if (bridge_channel->callid) {
2184                 bridge_channel->callid = ast_callid_unref(bridge_channel->callid);
2185         }
2186
2187         if (bridge_channel->bridge) {
2188                 ao2_ref(bridge_channel->bridge, -1);
2189                 bridge_channel->bridge = NULL;
2190         }
2191
2192         /* Flush any unhandled wr_queue frames. */
2193         while ((fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list))) {
2194                 ast_frfree(fr);
2195         }
2196         pipe_close(bridge_channel->alert_pipe);
2197
2198         ast_cond_destroy(&bridge_channel->cond);
2199 }
2200
2201 struct ast_bridge_channel *bridge_channel_internal_alloc(struct ast_bridge *bridge)
2202 {
2203         struct ast_bridge_channel *bridge_channel;
2204
2205         bridge_channel = ao2_alloc(sizeof(struct ast_bridge_channel), bridge_channel_destroy);
2206         if (!bridge_channel) {
2207                 return NULL;
2208         }
2209         ast_cond_init(&bridge_channel->cond, NULL);
2210         if (pipe_init_nonblock(bridge_channel->alert_pipe)) {
2211                 ao2_ref(bridge_channel, -1);
2212                 return NULL;
2213         }
2214         if (bridge) {
2215                 bridge_channel->bridge = bridge;
2216                 ao2_ref(bridge_channel->bridge, +1);
2217         }
2218
2219         return bridge_channel;
2220 }