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