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