Fix Bridge API DTMF hook matching for begin and end DTMF events.
[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
995  * \brief Internal function that executes a feature on a bridge channel
996  * \note Neither the bridge nor the bridge_channel locks should be held when entering
997  * this function.
998  */
999 static void bridge_channel_feature(struct ast_bridge_channel *bridge_channel, const char *starting_dtmf)
1000 {
1001         struct ast_bridge_features *features = bridge_channel->features;
1002         struct ast_bridge_hook_dtmf *hook = NULL;
1003         char dtmf[MAXIMUM_DTMF_FEATURE_STRING];
1004         size_t dtmf_len;
1005         unsigned int digit_timeout;
1006         RAII_VAR(struct ast_features_general_config *, gen_cfg, NULL, ao2_cleanup);
1007
1008         ast_channel_lock(bridge_channel->chan);
1009         gen_cfg = ast_get_chan_features_general_config(bridge_channel->chan);
1010         if (!gen_cfg) {
1011                 ast_log(LOG_ERROR, "Unable to retrieve features configuration.\n");
1012                 ast_channel_unlock(bridge_channel->chan);
1013                 return;
1014         }
1015         digit_timeout = gen_cfg->featuredigittimeout;
1016         ast_channel_unlock(bridge_channel->chan);
1017
1018         if (ast_strlen_zero(starting_dtmf)) {
1019                 dtmf[0] = '\0';
1020                 dtmf_len = 0;
1021         } else {
1022                 ast_copy_string(dtmf, starting_dtmf, sizeof(dtmf));
1023                 dtmf_len = strlen(dtmf);
1024         }
1025
1026         /*
1027          * Check if any feature DTMF hooks match or could match and
1028          * try to collect more DTMF digits.
1029          */
1030         for (;;) {
1031                 int res;
1032
1033                 if (dtmf_len) {
1034                         ast_debug(1, "DTMF feature string on %p(%s) is now '%s'\n",
1035                                 bridge_channel, ast_channel_name(bridge_channel->chan), dtmf);
1036
1037                         /* See if a DTMF feature hook matches or can match */
1038                         hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_PARTIAL_KEY);
1039                         if (!hook) {
1040                                 ast_debug(1, "No DTMF feature hooks on %p(%s) match '%s'\n",
1041                                         bridge_channel, ast_channel_name(bridge_channel->chan), dtmf);
1042                                 break;
1043                         }
1044                         if (strlen(hook->dtmf.code) == dtmf_len) {
1045                                 ast_debug(1, "DTMF feature hook %p matched DTMF string '%s' on %p(%s)\n",
1046                                         hook, dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
1047                                 break;
1048                         }
1049                         ao2_ref(hook, -1);
1050                         hook = NULL;
1051
1052                         if (ARRAY_LEN(dtmf) - 1 <= dtmf_len) {
1053                                 /* We have reached the maximum length of a DTMF feature string. */
1054                                 break;
1055                         }
1056                 }
1057
1058                 res = ast_waitfordigit(bridge_channel->chan, digit_timeout);
1059                 if (!res) {
1060                         ast_debug(1, "DTMF feature string collection on %p(%s) timed out\n",
1061                                 bridge_channel, ast_channel_name(bridge_channel->chan));
1062                         break;
1063                 }
1064                 if (res < 0) {
1065                         ast_debug(1, "DTMF feature string collection failed on %p(%s) for some reason\n",
1066                                 bridge_channel, ast_channel_name(bridge_channel->chan));
1067                         break;
1068                 }
1069
1070                 /* Add the new DTMF into the DTMF string so we can do our matching */
1071                 dtmf[dtmf_len] = res;
1072                 dtmf[++dtmf_len] = '\0';
1073         }
1074
1075         if (hook) {
1076                 int remove_me;
1077
1078                 /* Execute the matched hook on this channel. */
1079                 remove_me = hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
1080                 if (remove_me) {
1081                         ast_debug(1, "DTMF hook %p is being removed from %p(%s)\n",
1082                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1083                         ao2_unlink(features->dtmf_hooks, hook);
1084                 }
1085                 ao2_ref(hook, -1);
1086
1087                 /*
1088                  * If we are handing the channel off to an external hook for
1089                  * ownership, we are not guaranteed what kind of state it will
1090                  * come back in.  If the channel hungup, we need to detect that
1091                  * here if the hook did not already change the state.
1092                  */
1093                 if (bridge_channel->chan && ast_check_hangup_locked(bridge_channel->chan)) {
1094                         bridge_channel_handle_hangup(bridge_channel);
1095                 }
1096         } else if (features->dtmf_passthrough) {
1097                 /* Stream any collected DTMF to the other channels. */
1098                 bridge_channel_write_dtmf_stream(bridge_channel, dtmf);
1099         }
1100 }
1101
1102 /*! \internal \brief Indicate that a bridge_channel is talking */
1103 static void bridge_channel_talking(struct ast_bridge_channel *bridge_channel, int talking)
1104 {
1105         struct ast_bridge_features *features = bridge_channel->features;
1106         struct ast_bridge_hook *hook;
1107         struct ao2_iterator iter;
1108
1109         /* Run any talk detection hooks. */
1110         iter = ao2_iterator_init(features->other_hooks, 0);
1111         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
1112                 int remove_me;
1113                 ast_bridge_talking_indicate_callback talk_cb;
1114
1115                 if (hook->type != AST_BRIDGE_HOOK_TYPE_TALK) {
1116                         continue;
1117                 }
1118                 talk_cb = (ast_bridge_talking_indicate_callback) hook->callback;
1119                 remove_me = talk_cb(bridge_channel, hook->hook_pvt, talking);
1120                 if (remove_me) {
1121                         ast_debug(1, "Talk detection hook %p is being removed from %p(%s)\n",
1122                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1123                         ao2_unlink(features->other_hooks, hook);
1124                 }
1125         }
1126         ao2_iterator_destroy(&iter);
1127 }
1128
1129 /*! \brief Internal function that plays back DTMF on a bridge channel */
1130 static void bridge_channel_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
1131 {
1132         ast_debug(1, "Playing DTMF stream '%s' out to %p(%s)\n",
1133                 dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
1134         ast_dtmf_stream(bridge_channel->chan, NULL, dtmf, 0, 0);
1135 }
1136
1137 /*! \brief Data specifying where a blind transfer is going to */
1138 struct blind_transfer_data {
1139         char exten[AST_MAX_EXTENSION];
1140         char context[AST_MAX_CONTEXT];
1141 };
1142
1143 /*! \internal \brief Execute after bridge actions on a channel when it leaves a bridge */
1144 static void after_bridge_move_channel(struct ast_channel *chan_bridged, void *data)
1145 {
1146         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1147         struct ast_party_connected_line connected_target;
1148         unsigned char connected_line_data[1024];
1149         int payload_size;
1150
1151         ast_party_connected_line_init(&connected_target);
1152
1153         ast_channel_lock(chan_target);
1154         ast_party_connected_line_copy(&connected_target, ast_channel_connected(chan_target));
1155         ast_channel_unlock(chan_target);
1156         ast_party_id_reset(&connected_target.priv);
1157
1158         if (ast_channel_move(chan_target, chan_bridged)) {
1159                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1160                 ast_party_connected_line_free(&connected_target);
1161                 return;
1162         }
1163
1164         if ((payload_size = ast_connected_line_build_data(connected_line_data,
1165                 sizeof(connected_line_data), &connected_target, NULL)) != -1) {
1166                 struct ast_control_read_action_payload *frame_payload;
1167                 int frame_size;
1168
1169                 frame_size = payload_size + sizeof(*frame_payload);
1170                 frame_payload = ast_alloca(frame_size);
1171                 frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
1172                 frame_payload->payload_size = payload_size;
1173                 memcpy(frame_payload->payload, connected_line_data, payload_size);
1174                 ast_queue_control_data(chan_target, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
1175         }
1176
1177         ast_party_connected_line_free(&connected_target);
1178 }
1179
1180 /*! \internal \brief Execute logic to cleanup when after bridge fails */
1181 static void after_bridge_move_channel_fail(enum ast_bridge_after_cb_reason reason, void *data)
1182 {
1183         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1184
1185         ast_log(LOG_WARNING, "Unable to complete transfer: %s\n",
1186                 ast_bridge_after_cb_reason_string(reason));
1187         ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1188 }
1189
1190 /*! \internal \brief Perform a blind transfer on a channel in a bridge */
1191 static void bridge_channel_blind_transfer(struct ast_bridge_channel *bridge_channel,
1192                 struct blind_transfer_data *blind_data)
1193 {
1194         ast_async_goto(bridge_channel->chan, blind_data->context, blind_data->exten, 1);
1195         bridge_channel_handle_hangup(bridge_channel);
1196 }
1197
1198 /*! \internal \brief Perform an attended transfer on a channel in a bridge */
1199 static void bridge_channel_attended_transfer(struct ast_bridge_channel *bridge_channel,
1200                 const char *target_chan_name)
1201 {
1202         RAII_VAR(struct ast_channel *, chan_target, NULL, ao2_cleanup);
1203         RAII_VAR(struct ast_channel *, chan_bridged, NULL, ao2_cleanup);
1204
1205         chan_target = ast_channel_get_by_name(target_chan_name);
1206         if (!chan_target) {
1207                 /* Dang, it disappeared somehow */
1208                 bridge_channel_handle_hangup(bridge_channel);
1209                 return;
1210         }
1211
1212         ast_bridge_channel_lock(bridge_channel);
1213         chan_bridged = bridge_channel->chan;
1214         ast_assert(chan_bridged != NULL);
1215         ao2_ref(chan_bridged, +1);
1216         ast_bridge_channel_unlock(bridge_channel);
1217
1218         if (ast_bridge_set_after_callback(chan_bridged, after_bridge_move_channel,
1219                 after_bridge_move_channel_fail, ast_channel_ref(chan_target))) {
1220                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1221
1222                 /* Release the ref we tried to pass to ast_bridge_set_after_callback(). */
1223                 ast_channel_unref(chan_target);
1224         }
1225         bridge_channel_handle_hangup(bridge_channel);
1226 }
1227
1228 /*!
1229  * \internal
1230  * \brief Handle bridge channel bridge action frame.
1231  * \since 12.0.0
1232  *
1233  * \param bridge_channel Channel to execute the action on.
1234  * \param action What to do.
1235  *
1236  * \return Nothing
1237  */
1238 static void bridge_channel_handle_action(struct ast_bridge_channel *bridge_channel, struct ast_frame *action)
1239 {
1240         switch (action->subclass.integer) {
1241         case BRIDGE_CHANNEL_ACTION_DTMF_STREAM:
1242                 bridge_channel_suspend(bridge_channel);
1243                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1244                 bridge_channel_dtmf_stream(bridge_channel, action->data.ptr);
1245                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1246                 bridge_channel_unsuspend(bridge_channel);
1247                 break;
1248         case BRIDGE_CHANNEL_ACTION_TALKING_START:
1249         case BRIDGE_CHANNEL_ACTION_TALKING_STOP:
1250                 bridge_channel_talking(bridge_channel,
1251                         action->subclass.integer == BRIDGE_CHANNEL_ACTION_TALKING_START);
1252                 break;
1253         case BRIDGE_CHANNEL_ACTION_PLAY_FILE:
1254                 bridge_channel_suspend(bridge_channel);
1255                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1256                 bridge_channel_playfile(bridge_channel, action->data.ptr);
1257                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1258                 bridge_channel_unsuspend(bridge_channel);
1259                 break;
1260         case BRIDGE_CHANNEL_ACTION_RUN_APP:
1261                 bridge_channel_suspend(bridge_channel);
1262                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1263                 bridge_channel_run_app(bridge_channel, action->data.ptr);
1264                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1265                 bridge_channel_unsuspend(bridge_channel);
1266                 break;
1267         case BRIDGE_CHANNEL_ACTION_CALLBACK:
1268                 bridge_channel_suspend(bridge_channel);
1269                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1270                 bridge_channel_do_callback(bridge_channel, action->data.ptr);
1271                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1272                 bridge_channel_unsuspend(bridge_channel);
1273                 break;
1274         case BRIDGE_CHANNEL_ACTION_PARK:
1275                 bridge_channel_suspend(bridge_channel);
1276                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1277                 bridge_channel_park(bridge_channel, action->data.ptr);
1278                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1279                 bridge_channel_unsuspend(bridge_channel);
1280                 break;
1281         case BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER:
1282                 bridge_channel_blind_transfer(bridge_channel, action->data.ptr);
1283                 break;
1284         case BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER:
1285                 bridge_channel_attended_transfer(bridge_channel, action->data.ptr);
1286                 break;
1287         default:
1288                 break;
1289         }
1290 }
1291
1292 /*!
1293  * \internal
1294  * \brief Check if a bridge should dissolve and do it.
1295  * \since 12.0.0
1296  *
1297  * \param bridge_channel Channel causing the check.
1298  *
1299  * \note On entry, bridge_channel->bridge is already locked.
1300  *
1301  * \return Nothing
1302  */
1303 static void bridge_channel_dissolve_check(struct ast_bridge_channel *bridge_channel)
1304 {
1305         struct ast_bridge *bridge = bridge_channel->bridge;
1306
1307         if (bridge->dissolved) {
1308                 return;
1309         }
1310
1311         if (!bridge->num_channels
1312                 && ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY)) {
1313                 /* Last channel leaving the bridge turns off the lights. */
1314                 bridge_dissolve(bridge);
1315                 return;
1316         }
1317
1318         switch (bridge_channel->state) {
1319         case BRIDGE_CHANNEL_STATE_END:
1320                 /* Do we need to dissolve the bridge because this channel hung up? */
1321                 if (ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_HANGUP)
1322                         || (bridge_channel->features->usable
1323                                 && ast_test_flag(&bridge_channel->features->feature_flags,
1324                                         AST_BRIDGE_CHANNEL_FLAG_DISSOLVE_HANGUP))) {
1325                         bridge_dissolve(bridge);
1326                         return;
1327                 }
1328                 break;
1329         default:
1330                 break;
1331         }
1332
1333         if (bridge->num_lonely && bridge->num_lonely == bridge->num_channels) {
1334                 /* This will start a chain reaction where each channel leaving enters this function and causes
1335                  * the next to leave as long as there aren't non-lonely channels in the bridge. */
1336                 ast_bridge_channel_leave_bridge(AST_LIST_FIRST(&bridge->channels), BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE);
1337         }
1338 }
1339
1340 void bridge_channel_internal_pull(struct ast_bridge_channel *bridge_channel)
1341 {
1342         struct ast_bridge *bridge = bridge_channel->bridge;
1343
1344         if (!bridge_channel->in_bridge) {
1345                 return;
1346         }
1347         bridge_channel->in_bridge = 0;
1348
1349         ast_debug(1, "Bridge %s: pulling %p(%s)\n",
1350                 bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1351
1352         ast_verb(3, "Channel %s left '%s' %s-bridge <%s>\n",
1353                 ast_channel_name(bridge_channel->chan),
1354                 bridge->technology->name,
1355                 bridge->v_table->name,
1356                 bridge->uniqueid);
1357
1358 /* BUGBUG This is where incoming HOLD/UNHOLD memory should write UNHOLD into bridge. (if not local optimizing) */
1359 /* BUGBUG This is where incoming DTMF begin/end memory should write DTMF end into bridge. (if not local optimizing) */
1360         if (!bridge_channel->just_joined) {
1361                 /* Tell the bridge technology we are leaving so they tear us down */
1362                 ast_debug(1, "Bridge %s: %p(%s) is leaving %s technology\n",
1363                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1364                         bridge->technology->name);
1365                 if (bridge->technology->leave) {
1366                         bridge->technology->leave(bridge, bridge_channel);
1367                 }
1368         }
1369
1370         /* Remove channel from the bridge */
1371         if (!bridge_channel->suspended) {
1372                 --bridge->num_active;
1373         }
1374         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
1375                 --bridge->num_lonely;
1376         }
1377         --bridge->num_channels;
1378         AST_LIST_REMOVE(&bridge->channels, bridge_channel, entry);
1379         bridge->v_table->pull(bridge, bridge_channel);
1380
1381         ast_bridge_channel_clear_roles(bridge_channel);
1382
1383         /* If we are not going to be hung up after leaving a bridge, and we were an
1384          * outgoing channel, clear the outgoing flag.
1385          */
1386         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING)
1387                         && (ast_channel_softhangup_internal_flag(bridge_channel->chan) &
1388                                 (AST_SOFTHANGUP_ASYNCGOTO | AST_SOFTHANGUP_UNBRIDGE))) {
1389                 ast_clear_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING);
1390         }
1391
1392         bridge_channel_dissolve_check(bridge_channel);
1393
1394         bridge->reconfigured = 1;
1395         ast_bridge_publish_leave(bridge, bridge_channel->chan);
1396 }
1397
1398 int bridge_channel_internal_push(struct ast_bridge_channel *bridge_channel)
1399 {
1400         struct ast_bridge *bridge = bridge_channel->bridge;
1401         struct ast_bridge_channel *swap;
1402
1403         ast_assert(!bridge_channel->in_bridge);
1404
1405         swap = bridge_find_channel(bridge, bridge_channel->swap);
1406         bridge_channel->swap = NULL;
1407
1408         if (swap) {
1409                 ast_debug(1, "Bridge %s: pushing %p(%s) by swapping with %p(%s)\n",
1410                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1411                         swap, ast_channel_name(swap->chan));
1412         } else {
1413                 ast_debug(1, "Bridge %s: pushing %p(%s)\n",
1414                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1415         }
1416
1417         /* Add channel to the bridge */
1418         if (bridge->dissolved
1419                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
1420                 || (swap && swap->state != BRIDGE_CHANNEL_STATE_WAIT)
1421                 || bridge->v_table->push(bridge, bridge_channel, swap)
1422                 || ast_bridge_channel_establish_roles(bridge_channel)) {
1423                 ast_debug(1, "Bridge %s: pushing %p(%s) into bridge failed\n",
1424                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1425                 ast_bridge_features_remove(bridge_channel->features, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
1426                 return -1;
1427         }
1428         bridge_channel->in_bridge = 1;
1429         bridge_channel->just_joined = 1;
1430         AST_LIST_INSERT_TAIL(&bridge->channels, bridge_channel, entry);
1431         ++bridge->num_channels;
1432         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
1433                 ++bridge->num_lonely;
1434         }
1435         if (!bridge_channel->suspended) {
1436                 ++bridge->num_active;
1437         }
1438
1439         ast_verb(3, "Channel %s %s%s%s '%s' %s-bridge <%s>\n",
1440                 ast_channel_name(bridge_channel->chan),
1441                 swap ? "swapped with " : "joined",
1442                 swap ? ast_channel_name(swap->chan) : "",
1443                 swap ? " into" : "",
1444                 bridge->technology->name,
1445                 bridge->v_table->name,
1446                 bridge->uniqueid);
1447
1448         ast_bridge_publish_enter(bridge, bridge_channel->chan, swap ? swap->chan : NULL);
1449         if (swap) {
1450                 ast_bridge_channel_leave_bridge(swap, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE);
1451                 bridge_channel_internal_pull(swap);
1452         }
1453
1454         /* Clear any BLINDTRANSFER and ATTENDEDTRANSFER since the transfer has completed. */
1455         pbx_builtin_setvar_helper(bridge_channel->chan, "BLINDTRANSFER", NULL);
1456         pbx_builtin_setvar_helper(bridge_channel->chan, "ATTENDEDTRANSFER", NULL);
1457
1458         /* Wake up the bridge channel thread to reevaluate any interval timers. */
1459         ast_queue_frame(bridge_channel->chan, &ast_null_frame);
1460
1461         bridge->reconfigured = 1;
1462         return 0;
1463 }
1464
1465 /*!
1466  * \internal
1467  * \brief Handle bridge channel control frame action.
1468  * \since 12.0.0
1469  *
1470  * \param bridge_channel Channel to execute the control frame action on.
1471  * \param fr Control frame to handle.
1472  *
1473  * \return Nothing
1474  */
1475 static void bridge_channel_handle_control(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
1476 {
1477         struct ast_channel *chan;
1478         struct ast_option_header *aoh;
1479         int is_caller;
1480         int intercept_failed;
1481
1482         chan = bridge_channel->chan;
1483         switch (fr->subclass.integer) {
1484         case AST_CONTROL_REDIRECTING:
1485                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
1486                 bridge_channel_suspend(bridge_channel);
1487                 intercept_failed = ast_channel_redirecting_sub(NULL, chan, fr, 1)
1488                         && ast_channel_redirecting_macro(NULL, chan, fr, is_caller, 1);
1489                 bridge_channel_unsuspend(bridge_channel);
1490                 if (intercept_failed) {
1491                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1492                 }
1493                 break;
1494         case AST_CONTROL_CONNECTED_LINE:
1495                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
1496                 bridge_channel_suspend(bridge_channel);
1497                 intercept_failed = ast_channel_connected_line_sub(NULL, chan, fr, 1)
1498                         && ast_channel_connected_line_macro(NULL, chan, fr, is_caller, 1);
1499                 bridge_channel_unsuspend(bridge_channel);
1500                 if (intercept_failed) {
1501                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1502                 }
1503                 break;
1504         case AST_CONTROL_HOLD:
1505         case AST_CONTROL_UNHOLD:
1506 /*
1507  * BUGBUG bridge_channels should remember sending/receiving an outstanding HOLD to/from the bridge
1508  *
1509  * When the sending channel is pulled from the bridge it needs to write into the bridge an UNHOLD before being pulled.
1510  * When the receiving channel is pulled from the bridge it needs to generate its own UNHOLD.
1511  * Something similar needs to be done for DTMF begin/end.
1512  */
1513         case AST_CONTROL_VIDUPDATE:
1514         case AST_CONTROL_SRCUPDATE:
1515         case AST_CONTROL_SRCCHANGE:
1516         case AST_CONTROL_T38_PARAMETERS:
1517 /* BUGBUG may have to do something with a jitter buffer for these. */
1518                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1519                 break;
1520         case AST_CONTROL_OPTION:
1521                 /*
1522                  * Forward option Requests, but only ones we know are safe These
1523                  * are ONLY sent by chan_iax2 and I'm not convinced that they
1524                  * are useful. I haven't deleted them entirely because I just am
1525                  * not sure of the ramifications of removing them.
1526                  */
1527                 aoh = fr->data.ptr;
1528                 if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
1529                         switch (ntohs(aoh->option)) {
1530                         case AST_OPTION_TONE_VERIFY:
1531                         case AST_OPTION_TDD:
1532                         case AST_OPTION_RELAXDTMF:
1533                         case AST_OPTION_AUDIO_MODE:
1534                         case AST_OPTION_DIGIT_DETECT:
1535                         case AST_OPTION_FAX_DETECT:
1536                                 ast_channel_setoption(chan, ntohs(aoh->option), aoh->data,
1537                                         fr->datalen - sizeof(*aoh), 0);
1538                                 break;
1539                         default:
1540                                 break;
1541                         }
1542                 }
1543                 break;
1544         case AST_CONTROL_ANSWER:
1545                 if (ast_channel_state(chan) != AST_STATE_UP) {
1546                         ast_answer(chan);
1547                 } else {
1548                         ast_indicate(chan, -1);
1549                 }
1550                 break;
1551         default:
1552                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1553                 break;
1554         }
1555 }
1556
1557 /*!
1558  * \internal
1559  * \brief Handle bridge channel write frame to channel.
1560  * \since 12.0.0
1561  *
1562  * \param bridge_channel Channel to write outgoing frame.
1563  *
1564  * \return Nothing
1565  */
1566 static void bridge_channel_handle_write(struct ast_bridge_channel *bridge_channel)
1567 {
1568         struct ast_frame *fr;
1569         char nudge;
1570
1571         ast_bridge_channel_lock(bridge_channel);
1572         if (read(bridge_channel->alert_pipe[0], &nudge, sizeof(nudge)) < 0) {
1573                 if (errno != EINTR && errno != EAGAIN) {
1574                         ast_log(LOG_WARNING, "read() failed for alert pipe on %p(%s): %s\n",
1575                                 bridge_channel, ast_channel_name(bridge_channel->chan), strerror(errno));
1576                 }
1577         }
1578         fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list);
1579         ast_bridge_channel_unlock(bridge_channel);
1580         if (!fr) {
1581                 return;
1582         }
1583         switch (fr->frametype) {
1584         case AST_FRAME_BRIDGE_ACTION:
1585                 bridge_channel_handle_action(bridge_channel, fr);
1586                 break;
1587         case AST_FRAME_CONTROL:
1588                 bridge_channel_handle_control(bridge_channel, fr);
1589                 break;
1590         case AST_FRAME_NULL:
1591                 break;
1592         default:
1593                 /* Write the frame to the channel. */
1594                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_SIMPLE;
1595                 ast_write(bridge_channel->chan, fr);
1596                 break;
1597         }
1598         ast_frfree(fr);
1599 }
1600
1601 /*! \brief Internal function to handle DTMF from a channel */
1602 static struct ast_frame *bridge_handle_dtmf(struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
1603 {
1604         struct ast_bridge_features *features = bridge_channel->features;
1605         struct ast_bridge_hook_dtmf *hook;
1606         char dtmf[2];
1607
1608         /* See if this DTMF matches the beginning of any feature hooks. */
1609         dtmf[0] = frame->subclass.integer;
1610         dtmf[1] = '\0';
1611         hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_PARTIAL_KEY);
1612         if (hook) {
1613                 enum ast_frame_type frametype = frame->frametype;
1614
1615                 ast_frfree(frame);
1616                 frame = NULL;
1617
1618                 ao2_ref(hook, -1);
1619
1620                 /* Collect any more needed DTMF to execute a hook. */
1621                 bridge_channel_suspend(bridge_channel);
1622                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1623                 switch (frametype) {
1624                 case AST_FRAME_DTMF_BEGIN:
1625                         bridge_channel_feature(bridge_channel, NULL);
1626                         break;
1627                 case AST_FRAME_DTMF_END:
1628                         bridge_channel_feature(bridge_channel, dtmf);
1629                         break;
1630                 default:
1631                         /* Unexpected frame type. */
1632                         ast_assert(0);
1633                         break;
1634                 }
1635                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1636                 bridge_channel_unsuspend(bridge_channel);
1637         }
1638
1639         return frame;
1640 }
1641
1642
1643 /*!
1644  * \internal
1645  * \brief Feed notification that a frame is waiting on a channel into the bridging core
1646  *
1647  * \param bridge_channel Bridge channel the notification was received on
1648  */
1649 static void bridge_handle_trip(struct ast_bridge_channel *bridge_channel)
1650 {
1651         struct ast_frame *frame;
1652
1653         if (bridge_channel->features->mute) {
1654                 frame = ast_read_noaudio(bridge_channel->chan);
1655         } else {
1656                 frame = ast_read(bridge_channel->chan);
1657         }
1658
1659         if (!frame) {
1660                 bridge_channel_handle_hangup(bridge_channel);
1661                 return;
1662         }
1663         switch (frame->frametype) {
1664         case AST_FRAME_CONTROL:
1665                 switch (frame->subclass.integer) {
1666                 case AST_CONTROL_HANGUP:
1667                         bridge_channel_handle_hangup(bridge_channel);
1668                         ast_frfree(frame);
1669                         return;
1670 /* BUGBUG This is where incoming HOLD/UNHOLD memory should register.  Write UNHOLD into bridge when this channel is pulled. */
1671                 default:
1672                         break;
1673                 }
1674                 break;
1675         case AST_FRAME_DTMF_BEGIN:
1676         case AST_FRAME_DTMF_END:
1677                 frame = bridge_handle_dtmf(bridge_channel, frame);
1678                 if (!frame) {
1679                         return;
1680                 }
1681                 if (!bridge_channel->features->dtmf_passthrough) {
1682                         ast_frfree(frame);
1683                         return;
1684                 }
1685 /* BUGBUG This is where incoming DTMF begin/end memory should register.  Write DTMF end into bridge when this channel is pulled. */
1686                 break;
1687         default:
1688                 break;
1689         }
1690
1691         /* Simply write the frame out to the bridge technology. */
1692 /* BUGBUG The tech is where AST_CONTROL_ANSWER hook should go. (early bridge) */
1693 /* BUGBUG The tech is where incoming BUSY/CONGESTION hangup should happen? (early bridge) */
1694         bridge_channel_write_frame(bridge_channel, frame);
1695         ast_frfree(frame);
1696 }
1697
1698 /*!
1699  * \internal
1700  * \brief Determine how long till the next timer interval.
1701  * \since 12.0.0
1702  *
1703  * \param bridge_channel Channel to determine how long can wait.
1704  *
1705  * \retval ms Number of milliseconds to wait.
1706  * \retval -1 to wait forever.
1707  */
1708 static int bridge_channel_next_interval(struct ast_bridge_channel *bridge_channel)
1709 {
1710         struct ast_heap *interval_hooks = bridge_channel->features->interval_hooks;
1711         struct ast_bridge_hook_timer *hook;
1712         int ms;
1713
1714         ast_heap_wrlock(interval_hooks);
1715         hook = ast_heap_peek(interval_hooks, 1);
1716         if (hook) {
1717                 ms = ast_tvdiff_ms(hook->timer.trip_time, ast_tvnow());
1718                 if (ms < 0) {
1719                         /* Expire immediately.  An interval hook is ready to run. */
1720                         ms = 0;
1721                 }
1722         } else {
1723                 /* No hook so wait forever. */
1724                 ms = -1;
1725         }
1726         ast_heap_unlock(interval_hooks);
1727
1728         return ms;
1729 }
1730
1731 /*!
1732  * \internal
1733  * \brief Wait for something to happen on the bridge channel and handle it.
1734  * \since 12.0.0
1735  *
1736  * \param bridge_channel Channel to wait.
1737  *
1738  * \note Each channel does writing/reading in their own thread.
1739  *
1740  * \return Nothing
1741  */
1742 static void bridge_channel_wait(struct ast_bridge_channel *bridge_channel)
1743 {
1744         int ms;
1745         int outfd;
1746         struct ast_channel *chan;
1747
1748         /* Wait for data to either come from the channel or us to be signaled */
1749         ast_bridge_channel_lock(bridge_channel);
1750         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
1751         } else if (bridge_channel->suspended) {
1752 /* BUGBUG the external party use of suspended will go away as will these references because this is the bridge channel thread */
1753                 ast_debug(1, "Bridge %s: %p(%s) is going into a signal wait\n",
1754                         bridge_channel->bridge->uniqueid, bridge_channel,
1755                         ast_channel_name(bridge_channel->chan));
1756                 ast_cond_wait(&bridge_channel->cond, ao2_object_get_lockaddr(bridge_channel));
1757         } else {
1758                 ast_debug(10, "Bridge %s: %p(%s) is going into a waitfor\n",
1759                         bridge_channel->bridge->uniqueid, bridge_channel,
1760                         ast_channel_name(bridge_channel->chan));
1761                 bridge_channel->waiting = 1;
1762                 ast_bridge_channel_unlock(bridge_channel);
1763                 outfd = -1;
1764                 ms = bridge_channel_next_interval(bridge_channel);
1765                 chan = ast_waitfor_nandfds(&bridge_channel->chan, 1,
1766                         &bridge_channel->alert_pipe[0], 1, NULL, &outfd, &ms);
1767                 bridge_channel->waiting = 0;
1768                 if (ast_channel_softhangup_internal_flag(bridge_channel->chan) & AST_SOFTHANGUP_UNBRIDGE) {
1769                         ast_channel_clear_softhangup(bridge_channel->chan, AST_SOFTHANGUP_UNBRIDGE);
1770                         ast_bridge_channel_lock_bridge(bridge_channel);
1771                         bridge_channel->bridge->reconfigured = 1;
1772                         bridge_reconfigured(bridge_channel->bridge, 0);
1773                         ast_bridge_unlock(bridge_channel->bridge);
1774                 }
1775                 ast_bridge_channel_lock(bridge_channel);
1776                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_FRAME;
1777                 ast_bridge_channel_unlock(bridge_channel);
1778                 if (!bridge_channel->suspended
1779                         && bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
1780                         if (chan) {
1781                                 bridge_handle_trip(bridge_channel);
1782                         } else if (-1 < outfd) {
1783                                 bridge_channel_handle_write(bridge_channel);
1784                         } else if (ms == 0) {
1785                                 /* An interval expired. */
1786                                 bridge_channel_handle_interval(bridge_channel);
1787                         }
1788                 }
1789                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_IDLE;
1790                 return;
1791         }
1792         ast_bridge_channel_unlock(bridge_channel);
1793 }
1794
1795 /*!
1796  * \internal
1797  * \brief Handle bridge channel join/leave event.
1798  * \since 12.0.0
1799  *
1800  * \param bridge_channel Which channel is involved.
1801  * \param type Specified join/leave event.
1802  *
1803  * \return Nothing
1804  */
1805 static void bridge_channel_event_join_leave(struct ast_bridge_channel *bridge_channel, enum ast_bridge_hook_type type)
1806 {
1807         struct ast_bridge_features *features = bridge_channel->features;
1808         struct ast_bridge_hook *hook;
1809         struct ao2_iterator iter;
1810
1811         /* Run the specified hooks. */
1812         iter = ao2_iterator_init(features->other_hooks, 0);
1813         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
1814                 if (hook->type == type) {
1815                         break;
1816                 }
1817         }
1818         if (hook) {
1819                 /* Found the first specified hook to run. */
1820                 bridge_channel_suspend(bridge_channel);
1821                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1822                 do {
1823                         if (hook->type == type) {
1824                                 hook->callback(bridge_channel, hook->hook_pvt);
1825                                 ao2_unlink(features->other_hooks, hook);
1826                         }
1827                         ao2_ref(hook, -1);
1828                 } while ((hook = ao2_iterator_next(&iter)));
1829                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1830                 bridge_channel_unsuspend(bridge_channel);
1831         }
1832         ao2_iterator_destroy(&iter);
1833 }
1834
1835 /*! \brief Join a channel to a bridge and handle anything the bridge may want us to do */
1836 int bridge_channel_internal_join(struct ast_bridge_channel *bridge_channel)
1837 {
1838         int res = 0;
1839         ast_format_copy(&bridge_channel->read_format, ast_channel_readformat(bridge_channel->chan));
1840         ast_format_copy(&bridge_channel->write_format, ast_channel_writeformat(bridge_channel->chan));
1841
1842         ast_debug(1, "Bridge %s: %p(%s) is joining\n",
1843                 bridge_channel->bridge->uniqueid,
1844                 bridge_channel, ast_channel_name(bridge_channel->chan));
1845
1846         /*
1847          * Directly locking the bridge is safe here because nobody else
1848          * knows about this bridge_channel yet.
1849          */
1850         ast_bridge_lock(bridge_channel->bridge);
1851
1852         /* Make sure we're still good to be put into a bridge
1853          */
1854         ast_channel_lock(bridge_channel->chan);
1855         if (ast_channel_internal_bridge(bridge_channel->chan)
1856                 || ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_ZOMBIE)) {
1857                 ast_channel_unlock(bridge_channel->chan);
1858                 ast_bridge_unlock(bridge_channel->bridge);
1859                 ast_debug(1, "Bridge %s: %p(%s) failed to join Bridge\n",
1860                         bridge_channel->bridge->uniqueid,
1861                         bridge_channel,
1862                         ast_channel_name(bridge_channel->chan));
1863                 return -1;
1864         }
1865         ast_channel_internal_bridge_set(bridge_channel->chan, bridge_channel->bridge);
1866         ast_channel_unlock(bridge_channel->chan);
1867
1868         /* Add the jitterbuffer if the channel requires it */
1869         ast_jb_enable_for_channel(bridge_channel->chan);
1870
1871         if (!bridge_channel->bridge->callid) {
1872                 bridge_channel->bridge->callid = ast_read_threadstorage_callid();
1873         }
1874
1875         if (bridge_channel_internal_push(bridge_channel)) {
1876                 ast_bridge_channel_leave_bridge(bridge_channel, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE);
1877                 res = -1;
1878         }
1879         bridge_reconfigured(bridge_channel->bridge, 1);
1880
1881         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
1882                 /*
1883                  * Indicate a source change since this channel is entering the
1884                  * bridge system only if the bridge technology is not MULTIMIX
1885                  * capable.  The MULTIMIX technology has already done it.
1886                  */
1887                 if (!(bridge_channel->bridge->technology->capabilities
1888                         & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
1889                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
1890                 }
1891
1892                 ast_bridge_unlock(bridge_channel->bridge);
1893                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_JOIN);
1894                 while (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
1895                         /* Wait for something to do. */
1896                         bridge_channel_wait(bridge_channel);
1897                 }
1898                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_LEAVE);
1899                 ast_bridge_channel_lock_bridge(bridge_channel);
1900         }
1901
1902         bridge_channel_internal_pull(bridge_channel);
1903         bridge_reconfigured(bridge_channel->bridge, 1);
1904
1905         ast_bridge_unlock(bridge_channel->bridge);
1906
1907         /* Indicate a source change since this channel is leaving the bridge system. */
1908         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
1909
1910 /* BUGBUG Revisit in regards to moving channels between bridges and local channel optimization. */
1911 /* BUGBUG This is where outgoing HOLD/UNHOLD memory should write UNHOLD to channel. */
1912         /* Complete any partial DTMF digit before exiting the bridge. */
1913         if (ast_channel_sending_dtmf_digit(bridge_channel->chan)) {
1914                 ast_channel_end_dtmf(bridge_channel->chan,
1915                         ast_channel_sending_dtmf_digit(bridge_channel->chan),
1916                         ast_channel_sending_dtmf_tv(bridge_channel->chan), "bridge end");
1917         }
1918
1919         /*
1920          * Wait for any dual redirect to complete.
1921          *
1922          * Must be done while "still in the bridge" for ast_async_goto()
1923          * to work right.
1924          */
1925         while (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT)) {
1926                 sched_yield();
1927         }
1928         ast_channel_lock(bridge_channel->chan);
1929         ast_channel_internal_bridge_set(bridge_channel->chan, NULL);
1930         ast_channel_unlock(bridge_channel->chan);
1931
1932         ast_bridge_channel_restore_formats(bridge_channel);
1933
1934         return res;
1935 }
1936
1937 int bridge_channel_internal_queue_blind_transfer(struct ast_channel *transferee,
1938                 const char *exten, const char *context,
1939                 transfer_channel_cb new_channel_cb, void *user_data)
1940 {
1941         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
1942         struct blind_transfer_data blind_data;
1943
1944         ast_channel_lock(transferee);
1945         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
1946         ast_channel_unlock(transferee);
1947
1948         if (!transferee_bridge_channel) {
1949                 return -1;
1950         }
1951
1952         if (new_channel_cb) {
1953                 new_channel_cb(transferee, user_data, AST_BRIDGE_TRANSFER_SINGLE_PARTY);
1954         }
1955
1956         ast_copy_string(blind_data.exten, exten, sizeof(blind_data.exten));
1957         ast_copy_string(blind_data.context, context, sizeof(blind_data.context));
1958
1959         return bridge_channel_queue_action_data(transferee_bridge_channel,
1960                 BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER, &blind_data, sizeof(blind_data));
1961 }
1962
1963 int bridge_channel_internal_queue_attended_transfer(struct ast_channel *transferee,
1964                 struct ast_channel *unbridged_chan)
1965 {
1966         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
1967         char unbridged_chan_name[AST_CHANNEL_NAME];
1968
1969         ast_channel_lock(transferee);
1970         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
1971         ast_channel_unlock(transferee);
1972
1973         if (!transferee_bridge_channel) {
1974                 return -1;
1975         }
1976
1977         ast_copy_string(unbridged_chan_name, ast_channel_name(unbridged_chan),
1978                 sizeof(unbridged_chan_name));
1979
1980         return bridge_channel_queue_action_data(transferee_bridge_channel,
1981                 BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER, unbridged_chan_name,
1982                 sizeof(unbridged_chan_name));
1983 }
1984
1985 int bridge_channel_internal_allows_optimization(struct ast_bridge_channel *bridge_channel)
1986 {
1987         return bridge_channel->in_bridge
1988                 && AST_LIST_EMPTY(&bridge_channel->wr_queue);
1989 }
1990
1991 /*!
1992  * \internal
1993  * \brief Close a pipe.
1994  * \since 12.0.0
1995  *
1996  * \param my_pipe What to close.
1997  *
1998  * \return Nothing
1999  */
2000 static void pipe_close(int *my_pipe)
2001 {
2002         if (my_pipe[0] > -1) {
2003                 close(my_pipe[0]);
2004                 my_pipe[0] = -1;
2005         }
2006         if (my_pipe[1] > -1) {
2007                 close(my_pipe[1]);
2008                 my_pipe[1] = -1;
2009         }
2010 }
2011
2012 /*!
2013  * \internal
2014  * \brief Initialize a pipe as non-blocking.
2015  * \since 12.0.0
2016  *
2017  * \param my_pipe What to initialize.
2018  *
2019  * \retval 0 on success.
2020  * \retval -1 on error.
2021  */
2022 static int pipe_init_nonblock(int *my_pipe)
2023 {
2024         int flags;
2025
2026         my_pipe[0] = -1;
2027         my_pipe[1] = -1;
2028         if (pipe(my_pipe)) {
2029                 ast_log(LOG_WARNING, "Can't create pipe! Try increasing max file descriptors with ulimit -n\n");
2030                 return -1;
2031         }
2032         flags = fcntl(my_pipe[0], F_GETFL);
2033         if (fcntl(my_pipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
2034                 ast_log(LOG_WARNING, "Unable to set read pipe nonblocking! (%d: %s)\n",
2035                         errno, strerror(errno));
2036                 return -1;
2037         }
2038         flags = fcntl(my_pipe[1], F_GETFL);
2039         if (fcntl(my_pipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
2040                 ast_log(LOG_WARNING, "Unable to set write pipe nonblocking! (%d: %s)\n",
2041                         errno, strerror(errno));
2042                 return -1;
2043         }
2044         return 0;
2045 }
2046
2047 /* Destroy elements of the bridge channel structure and the bridge channel structure itself */
2048 static void bridge_channel_destroy(void *obj)
2049 {
2050         struct ast_bridge_channel *bridge_channel = obj;
2051         struct ast_frame *fr;
2052
2053         if (bridge_channel->callid) {
2054                 bridge_channel->callid = ast_callid_unref(bridge_channel->callid);
2055         }
2056
2057         if (bridge_channel->bridge) {
2058                 ao2_ref(bridge_channel->bridge, -1);
2059                 bridge_channel->bridge = NULL;
2060         }
2061
2062         /* Flush any unhandled wr_queue frames. */
2063         while ((fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list))) {
2064                 ast_frfree(fr);
2065         }
2066         pipe_close(bridge_channel->alert_pipe);
2067
2068         ast_cond_destroy(&bridge_channel->cond);
2069 }
2070
2071 struct ast_bridge_channel *bridge_channel_internal_alloc(struct ast_bridge *bridge)
2072 {
2073         struct ast_bridge_channel *bridge_channel;
2074
2075         bridge_channel = ao2_alloc(sizeof(struct ast_bridge_channel), bridge_channel_destroy);
2076         if (!bridge_channel) {
2077                 return NULL;
2078         }
2079         ast_cond_init(&bridge_channel->cond, NULL);
2080         if (pipe_init_nonblock(bridge_channel->alert_pipe)) {
2081                 ao2_ref(bridge_channel, -1);
2082                 return NULL;
2083         }
2084         if (bridge) {
2085                 bridge_channel->bridge = bridge;
2086                 ao2_ref(bridge_channel->bridge, +1);
2087         }
2088
2089         return bridge_channel;
2090 }