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