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