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