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