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