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