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