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