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