Blank line tweaks.
[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                 testsuite_notify_feature_success(bridge_channel->chan, hook->dtmf.code);
1213                 ao2_ref(hook, -1);
1214
1215                 /*
1216                  * If we are handing the channel off to an external hook for
1217                  * ownership, we are not guaranteed what kind of state it will
1218                  * come back in.  If the channel hungup, we need to detect that
1219                  * here if the hook did not already change the state.
1220                  */
1221                 if (bridge_channel->chan && ast_check_hangup_locked(bridge_channel->chan)) {
1222                         ast_bridge_channel_kick(bridge_channel, 0);
1223                 }
1224         } else {
1225                 if (features->dtmf_passthrough) {
1226                         /* Stream any collected DTMF to the other channels. */
1227                         bridge_channel_write_dtmf_stream(bridge_channel, dtmf);
1228                 }
1229                 ast_test_suite_event_notify("FEATURE_DETECTION", "Result: fail");
1230         }
1231 }
1232
1233 /*!
1234  * \internal
1235  * \brief Indicate that a bridge_channel is talking
1236  */
1237 static void bridge_channel_talking(struct ast_bridge_channel *bridge_channel, int talking)
1238 {
1239         struct ast_bridge_features *features = bridge_channel->features;
1240         struct ast_bridge_hook *hook;
1241         struct ao2_iterator iter;
1242
1243         /* Run any talk detection hooks. */
1244         iter = ao2_iterator_init(features->other_hooks, 0);
1245         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
1246                 int remove_me;
1247                 ast_bridge_talking_indicate_callback talk_cb;
1248
1249                 if (hook->type != AST_BRIDGE_HOOK_TYPE_TALK) {
1250                         continue;
1251                 }
1252                 talk_cb = (ast_bridge_talking_indicate_callback) hook->callback;
1253                 remove_me = talk_cb(bridge_channel, hook->hook_pvt, talking);
1254                 if (remove_me) {
1255                         ast_debug(1, "Talk detection hook %p is being removed from %p(%s)\n",
1256                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1257                         ao2_unlink(features->other_hooks, hook);
1258                 }
1259         }
1260         ao2_iterator_destroy(&iter);
1261 }
1262
1263 /*! \brief Internal function that plays back DTMF on a bridge channel */
1264 static void bridge_channel_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
1265 {
1266         ast_debug(1, "Playing DTMF stream '%s' out to %p(%s)\n",
1267                 dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
1268         ast_dtmf_stream(bridge_channel->chan, NULL, dtmf, 0, 0);
1269 }
1270
1271 /*! \brief Data specifying where a blind transfer is going to */
1272 struct blind_transfer_data {
1273         char exten[AST_MAX_EXTENSION];
1274         char context[AST_MAX_CONTEXT];
1275 };
1276
1277 /*!
1278  * \internal
1279  * \brief Execute after bridge actions on a channel when it leaves a bridge
1280  */
1281 static void after_bridge_move_channel(struct ast_channel *chan_bridged, void *data)
1282 {
1283         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1284         struct ast_party_connected_line connected_target;
1285         unsigned char connected_line_data[1024];
1286         int payload_size;
1287
1288         ast_party_connected_line_init(&connected_target);
1289
1290         ast_channel_lock(chan_target);
1291         ast_party_connected_line_copy(&connected_target, ast_channel_connected(chan_target));
1292         ast_channel_unlock(chan_target);
1293         ast_party_id_reset(&connected_target.priv);
1294
1295         if (ast_channel_move(chan_target, chan_bridged)) {
1296                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1297                 ast_party_connected_line_free(&connected_target);
1298                 return;
1299         }
1300
1301         if ((payload_size = ast_connected_line_build_data(connected_line_data,
1302                 sizeof(connected_line_data), &connected_target, NULL)) != -1) {
1303                 struct ast_control_read_action_payload *frame_payload;
1304                 int frame_size;
1305
1306                 frame_size = payload_size + sizeof(*frame_payload);
1307                 frame_payload = ast_alloca(frame_size);
1308                 frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
1309                 frame_payload->payload_size = payload_size;
1310                 memcpy(frame_payload->payload, connected_line_data, payload_size);
1311                 ast_queue_control_data(chan_target, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
1312         }
1313
1314         ast_party_connected_line_free(&connected_target);
1315 }
1316
1317 /*!
1318  * \internal
1319  * \brief Execute logic to cleanup when after bridge fails
1320  */
1321 static void after_bridge_move_channel_fail(enum ast_bridge_after_cb_reason reason, void *data)
1322 {
1323         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1324
1325         ast_log(LOG_WARNING, "Unable to complete transfer: %s\n",
1326                 ast_bridge_after_cb_reason_string(reason));
1327         ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1328 }
1329
1330 /*!
1331  * \internal
1332  * \brief Perform a blind transfer on a channel in a bridge
1333  */
1334 static void bridge_channel_blind_transfer(struct ast_bridge_channel *bridge_channel,
1335                 struct blind_transfer_data *blind_data)
1336 {
1337         ast_async_goto(bridge_channel->chan, blind_data->context, blind_data->exten, 1);
1338         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1339 }
1340
1341 /*!
1342  * \internal
1343  * \brief Perform an attended transfer on a channel in a bridge
1344  */
1345 static void bridge_channel_attended_transfer(struct ast_bridge_channel *bridge_channel,
1346                 const char *target_chan_name)
1347 {
1348         RAII_VAR(struct ast_channel *, chan_target, NULL, ao2_cleanup);
1349         RAII_VAR(struct ast_channel *, chan_bridged, NULL, ao2_cleanup);
1350
1351         chan_target = ast_channel_get_by_name(target_chan_name);
1352         if (!chan_target) {
1353                 /* Dang, it disappeared somehow */
1354                 ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1355                 return;
1356         }
1357
1358         ast_bridge_channel_lock(bridge_channel);
1359         chan_bridged = bridge_channel->chan;
1360         ast_assert(chan_bridged != NULL);
1361         ao2_ref(chan_bridged, +1);
1362         ast_bridge_channel_unlock(bridge_channel);
1363
1364         if (ast_bridge_set_after_callback(chan_bridged, after_bridge_move_channel,
1365                 after_bridge_move_channel_fail, ast_channel_ref(chan_target))) {
1366                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1367
1368                 /* Release the ref we tried to pass to ast_bridge_set_after_callback(). */
1369                 ast_channel_unref(chan_target);
1370         }
1371         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1372 }
1373
1374 /*!
1375  * \internal
1376  * \brief Handle bridge channel bridge action frame.
1377  * \since 12.0.0
1378  *
1379  * \param bridge_channel Channel to execute the action on.
1380  * \param action What to do.
1381  *
1382  * \return Nothing
1383  */
1384 static void bridge_channel_handle_action(struct ast_bridge_channel *bridge_channel, struct ast_frame *action)
1385 {
1386         switch (action->subclass.integer) {
1387         case BRIDGE_CHANNEL_ACTION_DTMF_STREAM:
1388                 bridge_channel_suspend(bridge_channel);
1389                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1390                 bridge_channel_dtmf_stream(bridge_channel, action->data.ptr);
1391                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1392                 bridge_channel_unsuspend(bridge_channel);
1393                 break;
1394         case BRIDGE_CHANNEL_ACTION_TALKING_START:
1395         case BRIDGE_CHANNEL_ACTION_TALKING_STOP:
1396                 bridge_channel_talking(bridge_channel,
1397                         action->subclass.integer == BRIDGE_CHANNEL_ACTION_TALKING_START);
1398                 break;
1399         case BRIDGE_CHANNEL_ACTION_PLAY_FILE:
1400                 bridge_channel_suspend(bridge_channel);
1401                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1402                 bridge_channel_playfile(bridge_channel, action->data.ptr);
1403                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1404                 bridge_channel_unsuspend(bridge_channel);
1405                 break;
1406         case BRIDGE_CHANNEL_ACTION_RUN_APP:
1407                 bridge_channel_suspend(bridge_channel);
1408                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1409                 bridge_channel_run_app(bridge_channel, action->data.ptr);
1410                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1411                 bridge_channel_unsuspend(bridge_channel);
1412                 break;
1413         case BRIDGE_CHANNEL_ACTION_CALLBACK:
1414                 bridge_channel_do_callback(bridge_channel, action->data.ptr);
1415                 break;
1416         case BRIDGE_CHANNEL_ACTION_PARK:
1417                 bridge_channel_suspend(bridge_channel);
1418                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1419                 bridge_channel_park(bridge_channel, action->data.ptr);
1420                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1421                 bridge_channel_unsuspend(bridge_channel);
1422                 break;
1423         case BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER:
1424                 bridge_channel_blind_transfer(bridge_channel, action->data.ptr);
1425                 break;
1426         case BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER:
1427                 bridge_channel_attended_transfer(bridge_channel, action->data.ptr);
1428                 break;
1429         default:
1430                 break;
1431         }
1432 }
1433
1434 /*!
1435  * \internal
1436  * \brief Check if a bridge should dissolve and do it.
1437  * \since 12.0.0
1438  *
1439  * \param bridge_channel Channel causing the check.
1440  *
1441  * \note On entry, bridge_channel->bridge is already locked.
1442  *
1443  * \return Nothing
1444  */
1445 static void bridge_channel_dissolve_check(struct ast_bridge_channel *bridge_channel)
1446 {
1447         struct ast_bridge *bridge = bridge_channel->bridge;
1448
1449         if (bridge->dissolved) {
1450                 return;
1451         }
1452
1453         if (!bridge->num_channels
1454                 && ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY)) {
1455                 /* Last channel leaving the bridge turns off the lights. */
1456                 bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
1457                 return;
1458         }
1459
1460         switch (bridge_channel->state) {
1461         case BRIDGE_CHANNEL_STATE_END:
1462                 /* Do we need to dissolve the bridge because this channel hung up? */
1463                 if (ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_HANGUP)
1464                         || (bridge_channel->features->usable
1465                                 && ast_test_flag(&bridge_channel->features->feature_flags,
1466                                         AST_BRIDGE_CHANNEL_FLAG_DISSOLVE_HANGUP))) {
1467                         bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
1468                         return;
1469                 }
1470                 break;
1471         default:
1472                 break;
1473         }
1474
1475         if (bridge->num_lonely && bridge->num_lonely == bridge->num_channels) {
1476                 /*
1477                  * This will start a chain reaction where each channel leaving
1478                  * enters this function and causes the next to leave as long as
1479                  * there aren't non-lonely channels in the bridge.
1480                  */
1481                 ast_bridge_channel_leave_bridge(AST_LIST_FIRST(&bridge->channels),
1482                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE,
1483                         ast_channel_hangupcause(bridge_channel->chan));
1484         }
1485 }
1486
1487 void bridge_channel_internal_pull(struct ast_bridge_channel *bridge_channel)
1488 {
1489         struct ast_bridge *bridge = bridge_channel->bridge;
1490
1491         if (!bridge_channel->in_bridge) {
1492                 return;
1493         }
1494         bridge_channel->in_bridge = 0;
1495
1496         ast_debug(1, "Bridge %s: pulling %p(%s)\n",
1497                 bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1498
1499         ast_verb(3, "Channel %s left '%s' %s-bridge <%s>\n",
1500                 ast_channel_name(bridge_channel->chan),
1501                 bridge->technology->name,
1502                 bridge->v_table->name,
1503                 bridge->uniqueid);
1504
1505         if (!bridge_channel->just_joined) {
1506                 /* Tell the bridge technology we are leaving so they tear us down */
1507                 ast_debug(1, "Bridge %s: %p(%s) is leaving %s technology\n",
1508                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1509                         bridge->technology->name);
1510                 if (bridge->technology->leave) {
1511                         bridge->technology->leave(bridge, bridge_channel);
1512                 }
1513         }
1514
1515         /* Remove channel from the bridge */
1516         if (!bridge_channel->suspended) {
1517                 --bridge->num_active;
1518         }
1519         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
1520                 --bridge->num_lonely;
1521         }
1522         --bridge->num_channels;
1523         AST_LIST_REMOVE(&bridge->channels, bridge_channel, entry);
1524         bridge->v_table->pull(bridge, bridge_channel);
1525
1526         ast_bridge_channel_clear_roles(bridge_channel);
1527
1528         /* If we are not going to be hung up after leaving a bridge, and we were an
1529          * outgoing channel, clear the outgoing flag.
1530          */
1531         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING)
1532                         && (ast_channel_softhangup_internal_flag(bridge_channel->chan) &
1533                                 (AST_SOFTHANGUP_ASYNCGOTO | AST_SOFTHANGUP_UNBRIDGE))) {
1534                 ast_clear_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING);
1535         }
1536
1537         bridge_channel_dissolve_check(bridge_channel);
1538
1539         bridge->reconfigured = 1;
1540         ast_bridge_publish_leave(bridge, bridge_channel->chan);
1541 }
1542
1543 int bridge_channel_internal_push(struct ast_bridge_channel *bridge_channel)
1544 {
1545         struct ast_bridge *bridge = bridge_channel->bridge;
1546         struct ast_bridge_channel *swap;
1547
1548         ast_assert(!bridge_channel->in_bridge);
1549
1550         swap = bridge_find_channel(bridge, bridge_channel->swap);
1551         bridge_channel->swap = NULL;
1552
1553         if (swap) {
1554                 ast_debug(1, "Bridge %s: pushing %p(%s) by swapping with %p(%s)\n",
1555                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1556                         swap, ast_channel_name(swap->chan));
1557         } else {
1558                 ast_debug(1, "Bridge %s: pushing %p(%s)\n",
1559                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1560         }
1561
1562         /* Add channel to the bridge */
1563         if (bridge->dissolved
1564                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
1565                 || (swap && swap->state != BRIDGE_CHANNEL_STATE_WAIT)
1566                 || bridge->v_table->push(bridge, bridge_channel, swap)
1567                 || ast_bridge_channel_establish_roles(bridge_channel)) {
1568                 ast_debug(1, "Bridge %s: pushing %p(%s) into bridge failed\n",
1569                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1570                 ast_bridge_features_remove(bridge_channel->features, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
1571                 return -1;
1572         }
1573         bridge_channel->in_bridge = 1;
1574         bridge_channel->just_joined = 1;
1575         AST_LIST_INSERT_TAIL(&bridge->channels, bridge_channel, entry);
1576         ++bridge->num_channels;
1577         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
1578                 ++bridge->num_lonely;
1579         }
1580         if (!bridge_channel->suspended) {
1581                 ++bridge->num_active;
1582         }
1583
1584         ast_verb(3, "Channel %s %s%s%s '%s' %s-bridge <%s>\n",
1585                 ast_channel_name(bridge_channel->chan),
1586                 swap ? "swapped with " : "joined",
1587                 swap ? ast_channel_name(swap->chan) : "",
1588                 swap ? " into" : "",
1589                 bridge->technology->name,
1590                 bridge->v_table->name,
1591                 bridge->uniqueid);
1592
1593         ast_bridge_publish_enter(bridge, bridge_channel->chan, swap ? swap->chan : NULL);
1594         if (swap) {
1595                 ast_bridge_channel_leave_bridge(swap, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, 0);
1596                 bridge_channel_internal_pull(swap);
1597         }
1598
1599         /* Clear any BLINDTRANSFER and ATTENDEDTRANSFER since the transfer has completed. */
1600         pbx_builtin_setvar_helper(bridge_channel->chan, "BLINDTRANSFER", NULL);
1601         pbx_builtin_setvar_helper(bridge_channel->chan, "ATTENDEDTRANSFER", NULL);
1602
1603         /* Wake up the bridge channel thread to reevaluate any interval timers. */
1604         ast_queue_frame(bridge_channel->chan, &ast_null_frame);
1605
1606         bridge->reconfigured = 1;
1607         return 0;
1608 }
1609
1610 /*!
1611  * \internal
1612  * \brief Handle bridge channel control frame action.
1613  * \since 12.0.0
1614  *
1615  * \param bridge_channel Channel to execute the control frame action on.
1616  * \param fr Control frame to handle.
1617  *
1618  * \return Nothing
1619  */
1620 static void bridge_channel_handle_control(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
1621 {
1622         struct ast_channel *chan;
1623         struct ast_option_header *aoh;
1624         int is_caller;
1625
1626         chan = bridge_channel->chan;
1627         switch (fr->subclass.integer) {
1628         case AST_CONTROL_REDIRECTING:
1629                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
1630                 if (ast_channel_redirecting_sub(NULL, chan, fr, 1) &&
1631                         ast_channel_redirecting_macro(NULL, chan, fr, is_caller, 1)) {
1632                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1633                 }
1634                 break;
1635         case AST_CONTROL_CONNECTED_LINE:
1636                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
1637                 if (ast_channel_connected_line_sub(NULL, chan, fr, 1) &&
1638                         ast_channel_connected_line_macro(NULL, chan, fr, is_caller, 1)) {
1639                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1640                 }
1641                 break;
1642         case AST_CONTROL_OPTION:
1643                 /*
1644                  * Forward option Requests, but only ones we know are safe These
1645                  * are ONLY sent by chan_iax2 and I'm not convinced that they
1646                  * are useful. I haven't deleted them entirely because I just am
1647                  * not sure of the ramifications of removing them.
1648                  */
1649                 aoh = fr->data.ptr;
1650                 if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
1651                         switch (ntohs(aoh->option)) {
1652                         case AST_OPTION_TONE_VERIFY:
1653                         case AST_OPTION_TDD:
1654                         case AST_OPTION_RELAXDTMF:
1655                         case AST_OPTION_AUDIO_MODE:
1656                         case AST_OPTION_DIGIT_DETECT:
1657                         case AST_OPTION_FAX_DETECT:
1658                                 ast_channel_setoption(chan, ntohs(aoh->option), aoh->data,
1659                                         fr->datalen - sizeof(*aoh), 0);
1660                                 break;
1661                         default:
1662                                 break;
1663                         }
1664                 }
1665                 break;
1666         case AST_CONTROL_ANSWER:
1667                 if (ast_channel_state(chan) != AST_STATE_UP) {
1668                         ast_answer(chan);
1669                 } else {
1670                         ast_indicate(chan, -1);
1671                 }
1672                 break;
1673         default:
1674                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1675                 break;
1676         }
1677 }
1678
1679 /*!
1680  * \internal
1681  * \brief Handle bridge channel write frame to channel.
1682  * \since 12.0.0
1683  *
1684  * \param bridge_channel Channel to write outgoing frame.
1685  *
1686  * \return Nothing
1687  */
1688 static void bridge_channel_handle_write(struct ast_bridge_channel *bridge_channel)
1689 {
1690         struct ast_frame *fr;
1691         char nudge;
1692
1693         ast_bridge_channel_lock(bridge_channel);
1694         if (read(bridge_channel->alert_pipe[0], &nudge, sizeof(nudge)) < 0) {
1695                 if (errno != EINTR && errno != EAGAIN) {
1696                         ast_log(LOG_WARNING, "read() failed for alert pipe on %p(%s): %s\n",
1697                                 bridge_channel, ast_channel_name(bridge_channel->chan), strerror(errno));
1698                 }
1699         }
1700         fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list);
1701         ast_bridge_channel_unlock(bridge_channel);
1702         if (!fr) {
1703                 return;
1704         }
1705         switch (fr->frametype) {
1706         case AST_FRAME_BRIDGE_ACTION:
1707                 bridge_channel_handle_action(bridge_channel, fr);
1708                 break;
1709         case AST_FRAME_CONTROL:
1710                 bridge_channel_handle_control(bridge_channel, fr);
1711                 break;
1712         case AST_FRAME_NULL:
1713                 break;
1714         default:
1715                 /* Write the frame to the channel. */
1716                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_SIMPLE;
1717                 ast_write(bridge_channel->chan, fr);
1718                 break;
1719         }
1720         ast_frfree(fr);
1721 }
1722
1723 /*! \brief Internal function to handle DTMF from a channel */
1724 static struct ast_frame *bridge_handle_dtmf(struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
1725 {
1726         struct ast_bridge_features *features = bridge_channel->features;
1727         struct ast_bridge_hook_dtmf *hook;
1728         char dtmf[2];
1729
1730         /* See if this DTMF matches the beginning of any feature hooks. */
1731         dtmf[0] = frame->subclass.integer;
1732         dtmf[1] = '\0';
1733         hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_PARTIAL_KEY);
1734         if (hook) {
1735                 enum ast_frame_type frametype = frame->frametype;
1736
1737                 ast_frfree(frame);
1738                 frame = NULL;
1739
1740                 ao2_ref(hook, -1);
1741
1742                 /* Collect any more needed DTMF to execute a hook. */
1743                 bridge_channel_suspend(bridge_channel);
1744                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1745                 switch (frametype) {
1746                 case AST_FRAME_DTMF_BEGIN:
1747                         bridge_channel_feature(bridge_channel, NULL);
1748                         break;
1749                 case AST_FRAME_DTMF_END:
1750                         bridge_channel_feature(bridge_channel, dtmf);
1751                         break;
1752                 default:
1753                         /* Unexpected frame type. */
1754                         ast_assert(0);
1755                         break;
1756                 }
1757                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1758                 bridge_channel_unsuspend(bridge_channel);
1759 #ifdef TEST_FRAMEWORK
1760         } else if (frame->frametype == AST_FRAME_DTMF_END) {
1761                 /* Only transmit this event on DTMF end or else every DTMF
1762                  * press will result in the event being broadcast twice
1763                  */
1764                 ast_test_suite_event_notify("FEATURE_DETECTION", "Result: fail");
1765 #endif
1766         }
1767
1768         return frame;
1769 }
1770
1771
1772 /*!
1773  * \internal
1774  * \brief Feed notification that a frame is waiting on a channel into the bridging core
1775  *
1776  * \param bridge_channel Bridge channel the notification was received on
1777  */
1778 static void bridge_handle_trip(struct ast_bridge_channel *bridge_channel)
1779 {
1780         struct ast_frame *frame;
1781
1782         if (bridge_channel->features->mute) {
1783                 frame = ast_read_noaudio(bridge_channel->chan);
1784         } else {
1785                 frame = ast_read(bridge_channel->chan);
1786         }
1787
1788         if (!frame) {
1789                 ast_bridge_channel_kick(bridge_channel, 0);
1790                 return;
1791         }
1792         switch (frame->frametype) {
1793         case AST_FRAME_CONTROL:
1794                 switch (frame->subclass.integer) {
1795                 case AST_CONTROL_HANGUP:
1796                         ast_bridge_channel_kick(bridge_channel, 0);
1797                         ast_frfree(frame);
1798                         return;
1799                 default:
1800                         break;
1801                 }
1802                 break;
1803         case AST_FRAME_DTMF_BEGIN:
1804         case AST_FRAME_DTMF_END:
1805                 frame = bridge_handle_dtmf(bridge_channel, frame);
1806                 if (!frame) {
1807                         return;
1808                 }
1809                 if (!bridge_channel->features->dtmf_passthrough) {
1810                         ast_frfree(frame);
1811                         return;
1812                 }
1813                 break;
1814         default:
1815                 break;
1816         }
1817
1818         /* Simply write the frame out to the bridge technology. */
1819         bridge_channel_write_frame(bridge_channel, frame);
1820         ast_frfree(frame);
1821 }
1822
1823 /*!
1824  * \internal
1825  * \brief Determine how long till the next timer interval.
1826  * \since 12.0.0
1827  *
1828  * \param bridge_channel Channel to determine how long can wait.
1829  *
1830  * \retval ms Number of milliseconds to wait.
1831  * \retval -1 to wait forever.
1832  */
1833 static int bridge_channel_next_interval(struct ast_bridge_channel *bridge_channel)
1834 {
1835         struct ast_heap *interval_hooks = bridge_channel->features->interval_hooks;
1836         struct ast_bridge_hook_timer *hook;
1837         int ms;
1838
1839         ast_heap_wrlock(interval_hooks);
1840         hook = ast_heap_peek(interval_hooks, 1);
1841         if (hook) {
1842                 ms = ast_tvdiff_ms(hook->timer.trip_time, ast_tvnow());
1843                 if (ms < 0) {
1844                         /* Expire immediately.  An interval hook is ready to run. */
1845                         ms = 0;
1846                 }
1847         } else {
1848                 /* No hook so wait forever. */
1849                 ms = -1;
1850         }
1851         ast_heap_unlock(interval_hooks);
1852
1853         return ms;
1854 }
1855
1856 /*!
1857  * \internal
1858  * \brief Wait for something to happen on the bridge channel and handle it.
1859  * \since 12.0.0
1860  *
1861  * \param bridge_channel Channel to wait.
1862  *
1863  * \note Each channel does writing/reading in their own thread.
1864  *
1865  * \return Nothing
1866  */
1867 static void bridge_channel_wait(struct ast_bridge_channel *bridge_channel)
1868 {
1869         int ms;
1870         int outfd;
1871         struct ast_channel *chan;
1872
1873         /* Wait for data to either come from the channel or us to be signaled */
1874         ast_bridge_channel_lock(bridge_channel);
1875         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
1876         } else if (bridge_channel->suspended) {
1877 /* XXX ASTERISK-21271 the external party use of suspended will go away as will these references because this is the bridge channel thread */
1878                 ast_debug(1, "Bridge %s: %p(%s) is going into a signal wait\n",
1879                         bridge_channel->bridge->uniqueid, bridge_channel,
1880                         ast_channel_name(bridge_channel->chan));
1881                 ast_cond_wait(&bridge_channel->cond, ao2_object_get_lockaddr(bridge_channel));
1882         } else {
1883                 ast_debug(10, "Bridge %s: %p(%s) is going into a waitfor\n",
1884                         bridge_channel->bridge->uniqueid, bridge_channel,
1885                         ast_channel_name(bridge_channel->chan));
1886                 bridge_channel->waiting = 1;
1887                 ast_bridge_channel_unlock(bridge_channel);
1888                 outfd = -1;
1889                 ms = bridge_channel_next_interval(bridge_channel);
1890                 chan = ast_waitfor_nandfds(&bridge_channel->chan, 1,
1891                         &bridge_channel->alert_pipe[0], 1, NULL, &outfd, &ms);
1892                 bridge_channel->waiting = 0;
1893                 if (ast_channel_softhangup_internal_flag(bridge_channel->chan) & AST_SOFTHANGUP_UNBRIDGE) {
1894                         ast_channel_clear_softhangup(bridge_channel->chan, AST_SOFTHANGUP_UNBRIDGE);
1895                         ast_bridge_channel_lock_bridge(bridge_channel);
1896                         bridge_channel->bridge->reconfigured = 1;
1897                         bridge_reconfigured(bridge_channel->bridge, 0);
1898                         ast_bridge_unlock(bridge_channel->bridge);
1899                 }
1900                 ast_bridge_channel_lock(bridge_channel);
1901                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_FRAME;
1902                 ast_bridge_channel_unlock(bridge_channel);
1903                 if (!bridge_channel->suspended
1904                         && bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
1905                         if (chan) {
1906                                 bridge_handle_trip(bridge_channel);
1907                         } else if (-1 < outfd) {
1908                                 bridge_channel_handle_write(bridge_channel);
1909                         } else if (ms == 0) {
1910                                 /* An interval expired. */
1911                                 bridge_channel_handle_interval(bridge_channel);
1912                         }
1913                 }
1914                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_IDLE;
1915                 return;
1916         }
1917         ast_bridge_channel_unlock(bridge_channel);
1918 }
1919
1920 /*!
1921  * \internal
1922  * \brief Handle bridge channel join/leave event.
1923  * \since 12.0.0
1924  *
1925  * \param bridge_channel Which channel is involved.
1926  * \param type Specified join/leave event.
1927  *
1928  * \return Nothing
1929  */
1930 static void bridge_channel_event_join_leave(struct ast_bridge_channel *bridge_channel, enum ast_bridge_hook_type type)
1931 {
1932         struct ast_bridge_features *features = bridge_channel->features;
1933         struct ast_bridge_hook *hook;
1934         struct ao2_iterator iter;
1935
1936         /* Run the specified hooks. */
1937         iter = ao2_iterator_init(features->other_hooks, 0);
1938         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
1939                 if (hook->type == type) {
1940                         break;
1941                 }
1942         }
1943         if (hook) {
1944                 /* Found the first specified hook to run. */
1945                 bridge_channel_suspend(bridge_channel);
1946                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1947                 do {
1948                         if (hook->type == type) {
1949                                 hook->callback(bridge_channel, hook->hook_pvt);
1950                                 ao2_unlink(features->other_hooks, hook);
1951                         }
1952                         ao2_ref(hook, -1);
1953                 } while ((hook = ao2_iterator_next(&iter)));
1954                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1955                 bridge_channel_unsuspend(bridge_channel);
1956         }
1957         ao2_iterator_destroy(&iter);
1958 }
1959
1960 /*! \brief Join a channel to a bridge and handle anything the bridge may want us to do */
1961 int bridge_channel_internal_join(struct ast_bridge_channel *bridge_channel)
1962 {
1963         int res = 0;
1964
1965         ast_format_copy(&bridge_channel->read_format, ast_channel_readformat(bridge_channel->chan));
1966         ast_format_copy(&bridge_channel->write_format, ast_channel_writeformat(bridge_channel->chan));
1967
1968         ast_debug(1, "Bridge %s: %p(%s) is joining\n",
1969                 bridge_channel->bridge->uniqueid,
1970                 bridge_channel, ast_channel_name(bridge_channel->chan));
1971
1972         /*
1973          * Directly locking the bridge is safe here because nobody else
1974          * knows about this bridge_channel yet.
1975          */
1976         ast_bridge_lock(bridge_channel->bridge);
1977
1978         /* Make sure we're still good to be put into a bridge
1979          */
1980         ast_channel_lock(bridge_channel->chan);
1981         if (ast_channel_internal_bridge(bridge_channel->chan)
1982                 || ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_ZOMBIE)) {
1983                 ast_channel_unlock(bridge_channel->chan);
1984                 ast_bridge_unlock(bridge_channel->bridge);
1985                 ast_debug(1, "Bridge %s: %p(%s) failed to join Bridge\n",
1986                         bridge_channel->bridge->uniqueid,
1987                         bridge_channel,
1988                         ast_channel_name(bridge_channel->chan));
1989                 return -1;
1990         }
1991         ast_channel_internal_bridge_set(bridge_channel->chan, bridge_channel->bridge);
1992         ast_channel_unlock(bridge_channel->chan);
1993
1994         /* Add the jitterbuffer if the channel requires it */
1995         ast_jb_enable_for_channel(bridge_channel->chan);
1996
1997         if (!bridge_channel->bridge->callid) {
1998                 bridge_channel->bridge->callid = ast_read_threadstorage_callid();
1999         }
2000
2001         if (bridge_channel_internal_push(bridge_channel)) {
2002                 ast_bridge_channel_leave_bridge(bridge_channel,
2003                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, bridge_channel->bridge->cause);
2004                 res = -1;
2005         }
2006         bridge_reconfigured(bridge_channel->bridge, 1);
2007
2008         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2009                 /*
2010                  * Indicate a source change since this channel is entering the
2011                  * bridge system only if the bridge technology is not MULTIMIX
2012                  * capable.  The MULTIMIX technology has already done it.
2013                  */
2014                 if (!(bridge_channel->bridge->technology->capabilities
2015                         & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
2016                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2017                 }
2018
2019                 ast_bridge_unlock(bridge_channel->bridge);
2020                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_JOIN);
2021                 while (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2022                         /* Wait for something to do. */
2023                         bridge_channel_wait(bridge_channel);
2024                 }
2025                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_LEAVE);
2026                 ast_bridge_channel_lock_bridge(bridge_channel);
2027         }
2028
2029         bridge_channel_internal_pull(bridge_channel);
2030         bridge_channel_settle_owed_events(bridge_channel->bridge, bridge_channel);
2031         bridge_reconfigured(bridge_channel->bridge, 1);
2032
2033         ast_bridge_unlock(bridge_channel->bridge);
2034
2035         /* Complete any active hold before exiting the bridge. */
2036         if (ast_channel_hold_state(bridge_channel->chan) == AST_CONTROL_HOLD) {
2037                 ast_debug(1, "Channel %s simulating UNHOLD for bridge end.\n",
2038                         ast_channel_name(bridge_channel->chan));
2039                 ast_indicate(bridge_channel->chan, AST_CONTROL_UNHOLD);
2040         }
2041
2042         /* Complete any partial DTMF digit before exiting the bridge. */
2043         if (ast_channel_sending_dtmf_digit(bridge_channel->chan)) {
2044                 ast_channel_end_dtmf(bridge_channel->chan,
2045                         ast_channel_sending_dtmf_digit(bridge_channel->chan),
2046                         ast_channel_sending_dtmf_tv(bridge_channel->chan), "bridge end");
2047         }
2048
2049         /* Indicate a source change since this channel is leaving the bridge system. */
2050         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2051
2052         /*
2053          * Wait for any dual redirect to complete.
2054          *
2055          * Must be done while "still in the bridge" for ast_async_goto()
2056          * to work right.
2057          */
2058         while (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT)) {
2059                 sched_yield();
2060         }
2061         ast_channel_lock(bridge_channel->chan);
2062         ast_channel_internal_bridge_set(bridge_channel->chan, NULL);
2063         ast_channel_unlock(bridge_channel->chan);
2064
2065         ast_bridge_channel_restore_formats(bridge_channel);
2066
2067         return res;
2068 }
2069
2070 int bridge_channel_internal_queue_blind_transfer(struct ast_channel *transferee,
2071                 const char *exten, const char *context,
2072                 transfer_channel_cb new_channel_cb, void *user_data)
2073 {
2074         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
2075         struct blind_transfer_data blind_data;
2076
2077         ast_channel_lock(transferee);
2078         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
2079         ast_channel_unlock(transferee);
2080
2081         if (!transferee_bridge_channel) {
2082                 return -1;
2083         }
2084
2085         if (new_channel_cb) {
2086                 new_channel_cb(transferee, user_data, AST_BRIDGE_TRANSFER_SINGLE_PARTY);
2087         }
2088
2089         ast_copy_string(blind_data.exten, exten, sizeof(blind_data.exten));
2090         ast_copy_string(blind_data.context, context, sizeof(blind_data.context));
2091
2092         return bridge_channel_queue_action_data(transferee_bridge_channel,
2093                 BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER, &blind_data, sizeof(blind_data));
2094 }
2095
2096 int bridge_channel_internal_queue_attended_transfer(struct ast_channel *transferee,
2097                 struct ast_channel *unbridged_chan)
2098 {
2099         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
2100         char unbridged_chan_name[AST_CHANNEL_NAME];
2101
2102         ast_channel_lock(transferee);
2103         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
2104         ast_channel_unlock(transferee);
2105
2106         if (!transferee_bridge_channel) {
2107                 return -1;
2108         }
2109
2110         ast_copy_string(unbridged_chan_name, ast_channel_name(unbridged_chan),
2111                 sizeof(unbridged_chan_name));
2112
2113         return bridge_channel_queue_action_data(transferee_bridge_channel,
2114                 BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER, unbridged_chan_name,
2115                 sizeof(unbridged_chan_name));
2116 }
2117
2118 int bridge_channel_internal_allows_optimization(struct ast_bridge_channel *bridge_channel)
2119 {
2120         return bridge_channel->in_bridge
2121                 && AST_LIST_EMPTY(&bridge_channel->wr_queue);
2122 }
2123
2124 /*!
2125  * \internal
2126  * \brief Close a pipe.
2127  * \since 12.0.0
2128  *
2129  * \param my_pipe What to close.
2130  *
2131  * \return Nothing
2132  */
2133 static void pipe_close(int *my_pipe)
2134 {
2135         if (my_pipe[0] > -1) {
2136                 close(my_pipe[0]);
2137                 my_pipe[0] = -1;
2138         }
2139         if (my_pipe[1] > -1) {
2140                 close(my_pipe[1]);
2141                 my_pipe[1] = -1;
2142         }
2143 }
2144
2145 /*!
2146  * \internal
2147  * \brief Initialize a pipe as non-blocking.
2148  * \since 12.0.0
2149  *
2150  * \param my_pipe What to initialize.
2151  *
2152  * \retval 0 on success.
2153  * \retval -1 on error.
2154  */
2155 static int pipe_init_nonblock(int *my_pipe)
2156 {
2157         int flags;
2158
2159         my_pipe[0] = -1;
2160         my_pipe[1] = -1;
2161         if (pipe(my_pipe)) {
2162                 ast_log(LOG_WARNING, "Can't create pipe! Try increasing max file descriptors with ulimit -n\n");
2163                 return -1;
2164         }
2165         flags = fcntl(my_pipe[0], F_GETFL);
2166         if (fcntl(my_pipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
2167                 ast_log(LOG_WARNING, "Unable to set read pipe nonblocking! (%d: %s)\n",
2168                         errno, strerror(errno));
2169                 return -1;
2170         }
2171         flags = fcntl(my_pipe[1], F_GETFL);
2172         if (fcntl(my_pipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
2173                 ast_log(LOG_WARNING, "Unable to set write pipe nonblocking! (%d: %s)\n",
2174                         errno, strerror(errno));
2175                 return -1;
2176         }
2177         return 0;
2178 }
2179
2180 /* Destroy elements of the bridge channel structure and the bridge channel structure itself */
2181 static void bridge_channel_destroy(void *obj)
2182 {
2183         struct ast_bridge_channel *bridge_channel = obj;
2184         struct ast_frame *fr;
2185
2186         if (bridge_channel->callid) {
2187                 bridge_channel->callid = ast_callid_unref(bridge_channel->callid);
2188         }
2189
2190         if (bridge_channel->bridge) {
2191                 ao2_ref(bridge_channel->bridge, -1);
2192                 bridge_channel->bridge = NULL;
2193         }
2194
2195         /* Flush any unhandled wr_queue frames. */
2196         while ((fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list))) {
2197                 ast_frfree(fr);
2198         }
2199         pipe_close(bridge_channel->alert_pipe);
2200
2201         ast_cond_destroy(&bridge_channel->cond);
2202 }
2203
2204 struct ast_bridge_channel *bridge_channel_internal_alloc(struct ast_bridge *bridge)
2205 {
2206         struct ast_bridge_channel *bridge_channel;
2207
2208         bridge_channel = ao2_alloc(sizeof(struct ast_bridge_channel), bridge_channel_destroy);
2209         if (!bridge_channel) {
2210                 return NULL;
2211         }
2212         ast_cond_init(&bridge_channel->cond, NULL);
2213         if (pipe_init_nonblock(bridge_channel->alert_pipe)) {
2214                 ao2_ref(bridge_channel, -1);
2215                 return NULL;
2216         }
2217         if (bridge) {
2218                 bridge_channel->bridge = bridge;
2219                 ao2_ref(bridge_channel->bridge, +1);
2220         }
2221
2222         return bridge_channel;
2223 }