ffe21611661bb7d936fa95e75e2d4d3bed290ac2
[asterisk/asterisk.git] / main / bridging.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 Channel Bridging API
22  *
23  * \author Joshua Colp <jcolp@digium.com>
24  */
25
26 /*** MODULEINFO
27         <support_level>core</support_level>
28  ***/
29
30 #include "asterisk.h"
31
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
33
34 #include <signal.h>
35
36 #include "asterisk/logger.h"
37 #include "asterisk/channel.h"
38 #include "asterisk/options.h"
39 #include "asterisk/utils.h"
40 #include "asterisk/lock.h"
41 #include "asterisk/linkedlists.h"
42 #include "asterisk/bridging.h"
43 #include "asterisk/bridging_basic.h"
44 #include "asterisk/bridging_technology.h"
45 #include "asterisk/stasis_bridging.h"
46 #include "asterisk/stasis_channels.h"
47 #include "asterisk/app.h"
48 #include "asterisk/file.h"
49 #include "asterisk/module.h"
50 #include "asterisk/astobj2.h"
51 #include "asterisk/pbx.h"
52 #include "asterisk/test.h"
53 #include "asterisk/_private.h"
54
55 #include "asterisk/heap.h"
56 #include "asterisk/say.h"
57 #include "asterisk/timing.h"
58 #include "asterisk/stringfields.h"
59 #include "asterisk/musiconhold.h"
60 #include "asterisk/features.h"
61 #include "asterisk/cli.h"
62 #include "asterisk/parking.h"
63 #include "asterisk/core_local.h"
64 #include "asterisk/features_config.h"
65
66 /*! All bridges container. */
67 static struct ao2_container *bridges;
68
69 static AST_RWLIST_HEAD_STATIC(bridge_technologies, ast_bridge_technology);
70
71 /* Initial starting point for the bridge array of channels */
72 #define BRIDGE_ARRAY_START 128
73
74 /* Grow rate of bridge array of channels */
75 #define BRIDGE_ARRAY_GROW 32
76
77 static void cleanup_video_mode(struct ast_bridge *bridge);
78 static int bridge_make_compatible(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel);
79 static void bridge_features_remove(struct ast_bridge_features *features, enum ast_bridge_hook_remove_flags remove_flags);
80
81 /*! Default DTMF keys for built in features */
82 static char builtin_features_dtmf[AST_BRIDGE_BUILTIN_END][MAXIMUM_DTMF_FEATURE_STRING];
83
84 /*! Function handlers for the built in features */
85 static void *builtin_features_handlers[AST_BRIDGE_BUILTIN_END];
86
87 /*! Function handlers for built in interval features */
88 static ast_bridge_builtin_set_limits_fn builtin_interval_handlers[AST_BRIDGE_BUILTIN_INTERVAL_END];
89
90 /*! Bridge manager service request */
91 struct bridge_manager_request {
92         /*! List of bridge service requests. */
93         AST_LIST_ENTRY(bridge_manager_request) node;
94         /*! Refed bridge requesting service. */
95         struct ast_bridge *bridge;
96 };
97
98 struct bridge_manager_controller {
99         /*! Condition, used to wake up the bridge manager thread. */
100         ast_cond_t cond;
101         /*! Queue of bridge service requests. */
102         AST_LIST_HEAD_NOLOCK(, bridge_manager_request) service_requests;
103         /*! Manager thread */
104         pthread_t thread;
105         /*! TRUE if the manager needs to stop. */
106         unsigned int stop:1;
107 };
108
109 /*! Bridge manager controller. */
110 static struct bridge_manager_controller *bridge_manager;
111
112 /*!
113  * \internal
114  * \brief Request service for a bridge from the bridge manager.
115  * \since 12.0.0
116  *
117  * \param bridge Requesting service.
118  *
119  * \return Nothing
120  */
121 static void bridge_manager_service_req(struct ast_bridge *bridge)
122 {
123         struct bridge_manager_request *request;
124
125         ao2_lock(bridge_manager);
126         if (bridge_manager->stop) {
127                 ao2_unlock(bridge_manager);
128                 return;
129         }
130
131         /* Create the service request. */
132         request = ast_calloc(1, sizeof(*request));
133         if (!request) {
134                 /* Well. This isn't good. */
135                 ao2_unlock(bridge_manager);
136                 return;
137         }
138         ao2_ref(bridge, +1);
139         request->bridge = bridge;
140
141         /* Put request into the queue and wake the bridge manager. */
142         AST_LIST_INSERT_TAIL(&bridge_manager->service_requests, request, node);
143         ast_cond_signal(&bridge_manager->cond);
144         ao2_unlock(bridge_manager);
145 }
146
147 int __ast_bridge_technology_register(struct ast_bridge_technology *technology, struct ast_module *module)
148 {
149         struct ast_bridge_technology *current;
150
151         /* Perform a sanity check to make sure the bridge technology conforms to our needed requirements */
152         if (ast_strlen_zero(technology->name)
153                 || !technology->capabilities
154                 || !technology->write) {
155                 ast_log(LOG_WARNING, "Bridge technology %s failed registration sanity check.\n",
156                         technology->name);
157                 return -1;
158         }
159
160         AST_RWLIST_WRLOCK(&bridge_technologies);
161
162         /* Look for duplicate bridge technology already using this name, or already registered */
163         AST_RWLIST_TRAVERSE(&bridge_technologies, current, entry) {
164                 if ((!strcasecmp(current->name, technology->name)) || (current == technology)) {
165                         ast_log(LOG_WARNING, "A bridge technology of %s already claims to exist in our world.\n",
166                                 technology->name);
167                         AST_RWLIST_UNLOCK(&bridge_technologies);
168                         return -1;
169                 }
170         }
171
172         /* Copy module pointer so reference counting can keep the module from unloading */
173         technology->mod = module;
174
175         /* Insert our new bridge technology into the list and print out a pretty message */
176         AST_RWLIST_INSERT_TAIL(&bridge_technologies, technology, entry);
177
178         AST_RWLIST_UNLOCK(&bridge_technologies);
179
180         ast_verb(2, "Registered bridge technology %s\n", technology->name);
181
182         return 0;
183 }
184
185 int ast_bridge_technology_unregister(struct ast_bridge_technology *technology)
186 {
187         struct ast_bridge_technology *current;
188
189         AST_RWLIST_WRLOCK(&bridge_technologies);
190
191         /* Ensure the bridge technology is registered before removing it */
192         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&bridge_technologies, current, entry) {
193                 if (current == technology) {
194                         AST_RWLIST_REMOVE_CURRENT(entry);
195                         ast_verb(2, "Unregistered bridge technology %s\n", technology->name);
196                         break;
197                 }
198         }
199         AST_RWLIST_TRAVERSE_SAFE_END;
200
201         AST_RWLIST_UNLOCK(&bridge_technologies);
202
203         return current ? 0 : -1;
204 }
205
206 void ast_bridge_channel_lock_bridge(struct ast_bridge_channel *bridge_channel)
207 {
208         struct ast_bridge *bridge;
209
210         for (;;) {
211                 /* Safely get the bridge pointer */
212                 ast_bridge_channel_lock(bridge_channel);
213                 bridge = bridge_channel->bridge;
214                 ao2_ref(bridge, +1);
215                 ast_bridge_channel_unlock(bridge_channel);
216
217                 /* Lock the bridge and see if it is still the bridge we need to lock. */
218                 ast_bridge_lock(bridge);
219                 if (bridge == bridge_channel->bridge) {
220                         ao2_ref(bridge, -1);
221                         return;
222                 }
223                 ast_bridge_unlock(bridge);
224                 ao2_ref(bridge, -1);
225         }
226 }
227
228 static void bridge_channel_poke(struct ast_bridge_channel *bridge_channel)
229 {
230         if (!pthread_equal(pthread_self(), bridge_channel->thread)) {
231                 while (bridge_channel->waiting) {
232                         pthread_kill(bridge_channel->thread, SIGURG);
233                         sched_yield();
234                 }
235         }
236 }
237
238 void ast_bridge_change_state_nolock(struct ast_bridge_channel *bridge_channel, enum ast_bridge_channel_state new_state)
239 {
240 /* BUGBUG need cause code for the bridge_channel leaving the bridge. */
241         if (bridge_channel->state != AST_BRIDGE_CHANNEL_STATE_WAIT) {
242                 return;
243         }
244
245         ast_debug(1, "Setting %p(%s) state from:%d to:%d\n",
246                 bridge_channel, ast_channel_name(bridge_channel->chan), bridge_channel->state,
247                 new_state);
248
249         /* Change the state on the bridge channel */
250         bridge_channel->state = new_state;
251
252         bridge_channel_poke(bridge_channel);
253 }
254
255 void ast_bridge_change_state(struct ast_bridge_channel *bridge_channel, enum ast_bridge_channel_state new_state)
256 {
257         ast_bridge_channel_lock(bridge_channel);
258         ast_bridge_change_state_nolock(bridge_channel, new_state);
259         ast_bridge_channel_unlock(bridge_channel);
260 }
261
262 /*!
263  * \internal
264  * \brief Put an action onto the specified bridge. Don't dup the action frame.
265  * \since 12.0.0
266  *
267  * \param bridge What to queue the action on.
268  * \param action What to do.
269  *
270  * \return Nothing
271  */
272 static void bridge_queue_action_nodup(struct ast_bridge *bridge, struct ast_frame *action)
273 {
274         ast_debug(1, "Bridge %s: queueing action type:%d sub:%d\n",
275                 bridge->uniqueid, action->frametype, action->subclass.integer);
276
277         ast_bridge_lock(bridge);
278         AST_LIST_INSERT_TAIL(&bridge->action_queue, action, frame_list);
279         ast_bridge_unlock(bridge);
280         bridge_manager_service_req(bridge);
281 }
282
283 int ast_bridge_queue_action(struct ast_bridge *bridge, struct ast_frame *action)
284 {
285         struct ast_frame *dup;
286
287         dup = ast_frdup(action);
288         if (!dup) {
289                 return -1;
290         }
291         bridge_queue_action_nodup(bridge, dup);
292         return 0;
293 }
294
295 void ast_bridge_update_accountcodes(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
296 {
297         struct ast_bridge_channel *other = NULL;
298
299         AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
300                 if (other == swap) {
301                         continue;
302                 }
303
304                 if (!ast_strlen_zero(ast_channel_accountcode(bridge_channel->chan)) && ast_strlen_zero(ast_channel_peeraccount(other->chan))) {
305                         ast_debug(1, "Setting peeraccount to %s for %s from data on channel %s\n",
306                                         ast_channel_accountcode(bridge_channel->chan), ast_channel_name(other->chan), ast_channel_name(bridge_channel->chan));
307                         ast_channel_peeraccount_set(other->chan, ast_channel_accountcode(bridge_channel->chan));
308                 }
309                 if (!ast_strlen_zero(ast_channel_accountcode(other->chan)) && ast_strlen_zero(ast_channel_peeraccount(bridge_channel->chan))) {
310                         ast_debug(1, "Setting peeraccount to %s for %s from data on channel %s\n",
311                                         ast_channel_accountcode(other->chan), ast_channel_name(bridge_channel->chan), ast_channel_name(other->chan));
312                         ast_channel_peeraccount_set(bridge_channel->chan, ast_channel_accountcode(other->chan));
313                 }
314                 if (!ast_strlen_zero(ast_channel_peeraccount(bridge_channel->chan)) && ast_strlen_zero(ast_channel_accountcode(other->chan))) {
315                         ast_debug(1, "Setting accountcode to %s for %s from data on channel %s\n",
316                                         ast_channel_peeraccount(bridge_channel->chan), ast_channel_name(other->chan), ast_channel_name(bridge_channel->chan));
317                         ast_channel_accountcode_set(other->chan, ast_channel_peeraccount(bridge_channel->chan));
318                 }
319                 if (!ast_strlen_zero(ast_channel_peeraccount(other->chan)) && ast_strlen_zero(ast_channel_accountcode(bridge_channel->chan))) {
320                         ast_debug(1, "Setting accountcode to %s for %s from data on channel %s\n",
321                                         ast_channel_peeraccount(other->chan), ast_channel_name(bridge_channel->chan), ast_channel_name(other->chan));
322                         ast_channel_accountcode_set(bridge_channel->chan, ast_channel_peeraccount(other->chan));
323                 }
324                 if (bridge->num_channels == 2) {
325                         if (strcmp(ast_channel_accountcode(bridge_channel->chan), ast_channel_peeraccount(other->chan))) {
326                                 ast_debug(1, "Changing peeraccount from %s to %s on %s to match channel %s\n",
327                                                 ast_channel_peeraccount(other->chan), ast_channel_peeraccount(bridge_channel->chan), ast_channel_name(other->chan), ast_channel_name(bridge_channel->chan));
328                                 ast_channel_peeraccount_set(other->chan, ast_channel_accountcode(bridge_channel->chan));
329                         }
330                         if (strcmp(ast_channel_accountcode(other->chan), ast_channel_peeraccount(bridge_channel->chan))) {
331                                 ast_debug(1, "Changing peeraccount from %s to %s on %s to match channel %s\n",
332                                                 ast_channel_peeraccount(bridge_channel->chan), ast_channel_peeraccount(other->chan), ast_channel_name(bridge_channel->chan), ast_channel_name(other->chan));
333                                 ast_channel_peeraccount_set(bridge_channel->chan, ast_channel_accountcode(other->chan));
334                         }
335                 }
336         }
337 }
338
339 void ast_bridge_update_linkedids(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
340 {
341         struct ast_bridge_channel *other = NULL;
342         const char *oldest_linkedid = ast_channel_linkedid(bridge_channel->chan);
343
344         AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
345                 if (other == swap) {
346                         continue;
347                 }
348                 oldest_linkedid = ast_channel_oldest_linkedid(oldest_linkedid, ast_channel_linkedid(other->chan));
349         }
350
351         if (ast_strlen_zero(oldest_linkedid)) {
352                 return;
353         }
354
355         ast_channel_linkedid_set(bridge_channel->chan, oldest_linkedid);
356         AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
357                 if (other == swap) {
358                         continue;
359                 }
360                 ast_channel_linkedid_set(other->chan, oldest_linkedid);
361         }
362 }
363
364 int ast_bridge_channel_queue_frame(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
365 {
366         struct ast_frame *dup;
367         char nudge = 0;
368
369         if (bridge_channel->suspended
370                 /* Also defer DTMF frames. */
371                 && fr->frametype != AST_FRAME_DTMF_BEGIN
372                 && fr->frametype != AST_FRAME_DTMF_END
373                 && !ast_is_deferrable_frame(fr)) {
374                 /* Drop non-deferable frames when suspended. */
375                 return 0;
376         }
377
378         dup = ast_frdup(fr);
379         if (!dup) {
380                 return -1;
381         }
382
383         ast_bridge_channel_lock(bridge_channel);
384         if (bridge_channel->state != AST_BRIDGE_CHANNEL_STATE_WAIT) {
385                 /* Drop frames on channels leaving the bridge. */
386                 ast_bridge_channel_unlock(bridge_channel);
387                 ast_frfree(dup);
388                 return 0;
389         }
390
391         AST_LIST_INSERT_TAIL(&bridge_channel->wr_queue, dup, frame_list);
392         if (write(bridge_channel->alert_pipe[1], &nudge, sizeof(nudge)) != sizeof(nudge)) {
393                 ast_log(LOG_ERROR, "We couldn't write alert pipe for %p(%s)... something is VERY wrong\n",
394                         bridge_channel, ast_channel_name(bridge_channel->chan));
395         }
396         ast_bridge_channel_unlock(bridge_channel);
397         return 0;
398 }
399
400 void ast_bridge_channel_queue_action_data(struct ast_bridge_channel *bridge_channel, enum ast_bridge_action_type action, const void *data, size_t datalen)
401 {
402         struct ast_frame frame = {
403                 .frametype = AST_FRAME_BRIDGE_ACTION,
404                 .subclass.integer = action,
405                 .datalen = datalen,
406                 .data.ptr = (void *) data,
407         };
408
409         ast_bridge_channel_queue_frame(bridge_channel, &frame);
410 }
411
412 void ast_bridge_channel_queue_control_data(struct ast_bridge_channel *bridge_channel, enum ast_control_frame_type control, const void *data, size_t datalen)
413 {
414         struct ast_frame frame = {
415                 .frametype = AST_FRAME_CONTROL,
416                 .subclass.integer = control,
417                 .datalen = datalen,
418                 .data.ptr = (void *) data,
419         };
420
421         ast_bridge_channel_queue_frame(bridge_channel, &frame);
422 }
423
424 void ast_bridge_channel_restore_formats(struct ast_bridge_channel *bridge_channel)
425 {
426         /* Restore original formats of the channel as they came in */
427         if (ast_format_cmp(ast_channel_readformat(bridge_channel->chan), &bridge_channel->read_format) == AST_FORMAT_CMP_NOT_EQUAL) {
428                 ast_debug(1, "Bridge is returning %p(%s) to read format %s\n",
429                         bridge_channel, ast_channel_name(bridge_channel->chan),
430                         ast_getformatname(&bridge_channel->read_format));
431                 if (ast_set_read_format(bridge_channel->chan, &bridge_channel->read_format)) {
432                         ast_debug(1, "Bridge failed to return %p(%s) to read format %s\n",
433                                 bridge_channel, ast_channel_name(bridge_channel->chan),
434                                 ast_getformatname(&bridge_channel->read_format));
435                 }
436         }
437         if (ast_format_cmp(ast_channel_writeformat(bridge_channel->chan), &bridge_channel->write_format) == AST_FORMAT_CMP_NOT_EQUAL) {
438                 ast_debug(1, "Bridge is returning %p(%s) to write format %s\n",
439                         bridge_channel, ast_channel_name(bridge_channel->chan),
440                         ast_getformatname(&bridge_channel->write_format));
441                 if (ast_set_write_format(bridge_channel->chan, &bridge_channel->write_format)) {
442                         ast_debug(1, "Bridge failed to return %p(%s) to write format %s\n",
443                                 bridge_channel, ast_channel_name(bridge_channel->chan),
444                                 ast_getformatname(&bridge_channel->write_format));
445                 }
446         }
447 }
448
449 /*!
450  * \internal
451  * \brief Helper function to find a bridge channel given a channel.
452  *
453  * \param bridge What to search
454  * \param chan What to search for.
455  *
456  * \note On entry, bridge is already locked.
457  *
458  * \retval bridge_channel if channel is in the bridge.
459  * \retval NULL if not in bridge.
460  */
461 static struct ast_bridge_channel *find_bridge_channel(struct ast_bridge *bridge, struct ast_channel *chan)
462 {
463         struct ast_bridge_channel *bridge_channel;
464
465         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
466                 if (bridge_channel->chan == chan) {
467                         break;
468                 }
469         }
470
471         return bridge_channel;
472 }
473
474 /*!
475  * \internal
476  * \brief Dissolve the bridge.
477  * \since 12.0.0
478  *
479  * \param bridge Bridge to eject all channels
480  *
481  * \details
482  * Force out all channels that are not already going out of the
483  * bridge.  Any new channels joining will leave immediately.
484  *
485  * \note On entry, bridge is already locked.
486  *
487  * \return Nothing
488  */
489 static void bridge_dissolve(struct ast_bridge *bridge)
490 {
491         struct ast_bridge_channel *bridge_channel;
492         struct ast_frame action = {
493                 .frametype = AST_FRAME_BRIDGE_ACTION,
494                 .subclass.integer = AST_BRIDGE_ACTION_DEFERRED_DISSOLVING,
495         };
496
497         if (bridge->dissolved) {
498                 return;
499         }
500         bridge->dissolved = 1;
501
502         ast_debug(1, "Bridge %s: dissolving bridge\n", bridge->uniqueid);
503
504 /* BUGBUG need a cause code on the bridge for the later ejected channels. */
505         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
506                 ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_HANGUP);
507         }
508
509         /* Must defer dissolving bridge because it is already locked. */
510         ast_bridge_queue_action(bridge, &action);
511 }
512
513 /*!
514  * \internal
515  * \brief Check if a bridge should dissolve and do it.
516  * \since 12.0.0
517  *
518  * \param bridge_channel Channel causing the check.
519  *
520  * \note On entry, bridge_channel->bridge is already locked.
521  *
522  * \return Nothing
523  */
524 static void bridge_dissolve_check(struct ast_bridge_channel *bridge_channel)
525 {
526         struct ast_bridge *bridge = bridge_channel->bridge;
527
528         if (bridge->dissolved) {
529                 return;
530         }
531
532         if (!bridge->num_channels
533                 && ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY)) {
534                 /* Last channel leaving the bridge turns off the lights. */
535                 bridge_dissolve(bridge);
536                 return;
537         }
538
539         switch (bridge_channel->state) {
540         case AST_BRIDGE_CHANNEL_STATE_END:
541                 /* Do we need to dissolve the bridge because this channel hung up? */
542                 if (ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_HANGUP)
543                         || (bridge_channel->features->usable
544                                 && ast_test_flag(&bridge_channel->features->feature_flags,
545                                         AST_BRIDGE_CHANNEL_FLAG_DISSOLVE_HANGUP))) {
546                         bridge_dissolve(bridge);
547                         return;
548                 }
549                 break;
550         default:
551                 break;
552         }
553 /* BUGBUG need to implement AST_BRIDGE_CHANNEL_FLAG_LONELY support here */
554 }
555
556 /*!
557  * \internal
558  * \brief Pull the bridge channel out of its current bridge.
559  * \since 12.0.0
560  *
561  * \param bridge_channel Channel to pull.
562  *
563  * \note On entry, bridge_channel->bridge is already locked.
564  *
565  * \return Nothing
566  */
567 static void bridge_channel_pull(struct ast_bridge_channel *bridge_channel)
568 {
569         struct ast_bridge *bridge = bridge_channel->bridge;
570
571         if (!bridge_channel->in_bridge) {
572                 return;
573         }
574         bridge_channel->in_bridge = 0;
575
576         ast_debug(1, "Bridge %s: pulling %p(%s)\n",
577                 bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
578
579 /* BUGBUG This is where incoming HOLD/UNHOLD memory should write UNHOLD into bridge. (if not local optimizing) */
580 /* BUGBUG This is where incoming DTMF begin/end memory should write DTMF end into bridge. (if not local optimizing) */
581         if (!bridge_channel->just_joined) {
582                 /* Tell the bridge technology we are leaving so they tear us down */
583                 ast_debug(1, "Bridge %s: %p(%s) is leaving %s technology\n",
584                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
585                         bridge->technology->name);
586                 if (bridge->technology->leave) {
587                         bridge->technology->leave(bridge, bridge_channel);
588                 }
589         }
590
591         /* Remove channel from the bridge */
592         if (!bridge_channel->suspended) {
593                 --bridge->num_active;
594         }
595         --bridge->num_channels;
596         AST_LIST_REMOVE(&bridge->channels, bridge_channel, entry);
597         bridge->v_table->pull(bridge, bridge_channel);
598
599         ast_bridge_channel_clear_roles(bridge_channel);
600
601         /* If we are not going to be hung up after leaving a bridge, and we were an
602          * outgoing channel, clear the outgoing flag.
603          */
604         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING)
605                         && (ast_channel_softhangup_internal_flag(bridge_channel->chan) & (AST_SOFTHANGUP_ASYNCGOTO | AST_SOFTHANGUP_UNBRIDGE))) {
606                 ast_clear_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING);
607         }
608
609         bridge_dissolve_check(bridge_channel);
610
611         bridge->reconfigured = 1;
612         ast_bridge_publish_leave(bridge, bridge_channel->chan);
613 }
614
615 /*!
616  * \internal
617  * \brief Push the bridge channel into its specified bridge.
618  * \since 12.0.0
619  *
620  * \param bridge_channel Channel to push.
621  *
622  * \note On entry, bridge_channel->bridge is already locked.
623  *
624  * \retval 0 on success.
625  * \retval -1 on failure.  The channel did not get pushed.
626  */
627 static int bridge_channel_push(struct ast_bridge_channel *bridge_channel)
628 {
629         struct ast_bridge *bridge = bridge_channel->bridge;
630         struct ast_bridge_channel *swap;
631
632         ast_assert(!bridge_channel->in_bridge);
633
634         swap = find_bridge_channel(bridge, bridge_channel->swap);
635         bridge_channel->swap = NULL;
636
637         if (swap) {
638                 ast_debug(1, "Bridge %s: pushing %p(%s) by swapping with %p(%s)\n",
639                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
640                         swap, ast_channel_name(swap->chan));
641         } else {
642                 ast_debug(1, "Bridge %s: pushing %p(%s)\n",
643                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
644         }
645
646         /* Add channel to the bridge */
647         if (bridge->dissolved
648                 || bridge_channel->state != AST_BRIDGE_CHANNEL_STATE_WAIT
649                 || (swap && swap->state != AST_BRIDGE_CHANNEL_STATE_WAIT)
650                 || bridge->v_table->push(bridge, bridge_channel, swap)
651                 || ast_bridge_channel_establish_roles(bridge_channel)) {
652                 ast_debug(1, "Bridge %s: pushing %p(%s) into bridge failed\n",
653                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
654                 bridge_features_remove(bridge_channel->features, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
655                 return -1;
656         }
657         bridge_channel->in_bridge = 1;
658         bridge_channel->just_joined = 1;
659         AST_LIST_INSERT_TAIL(&bridge->channels, bridge_channel, entry);
660         ++bridge->num_channels;
661         if (!bridge_channel->suspended) {
662                 ++bridge->num_active;
663         }
664         if (swap) {
665                 ast_bridge_change_state(swap, AST_BRIDGE_CHANNEL_STATE_HANGUP);
666                 bridge_channel_pull(swap);
667         }
668
669         /* Clear any BLINDTRANSFER since the transfer has completed. */
670         pbx_builtin_setvar_helper(bridge_channel->chan, "BLINDTRANSFER", NULL);
671
672         bridge->reconfigured = 1;
673         ast_bridge_publish_enter(bridge, bridge_channel->chan);
674         return 0;
675 }
676
677 /*! \brief Internal function to handle DTMF from a channel */
678 static struct ast_frame *bridge_handle_dtmf(struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
679 {
680         struct ast_bridge_features *features = bridge_channel->features;
681         struct ast_bridge_hook *hook;
682         char dtmf[2];
683
684 /* BUGBUG the feature hook matching needs to be done here.  Any matching feature hook needs to be queued onto the bridge_channel.  Also the feature hook digit timeout needs to be handled. */
685 /* BUGBUG the AMI atxfer action just sends DTMF end events to initiate DTMF atxfer and dial the extension.  Another reason the DTMF hook matching needs rework. */
686         /* See if this DTMF matches the beginnings of any feature hooks, if so we switch to the feature state to either execute the feature or collect more DTMF */
687         dtmf[0] = frame->subclass.integer;
688         dtmf[1] = '\0';
689         hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_PARTIAL_KEY);
690         if (hook) {
691                 struct ast_frame action = {
692                         .frametype = AST_FRAME_BRIDGE_ACTION,
693                         .subclass.integer = AST_BRIDGE_ACTION_FEATURE,
694                 };
695
696                 ast_frfree(frame);
697                 frame = NULL;
698                 ast_bridge_channel_queue_frame(bridge_channel, &action);
699                 ao2_ref(hook, -1);
700         }
701
702         return frame;
703 }
704
705 /*!
706  * \internal
707  * \brief Handle bridge hangup event.
708  * \since 12.0.0
709  *
710  * \param bridge_channel Which channel is hanging up.
711  *
712  * \return Nothing
713  */
714 static void bridge_handle_hangup(struct ast_bridge_channel *bridge_channel)
715 {
716         struct ast_bridge_features *features = bridge_channel->features;
717         struct ast_bridge_hook *hook;
718         struct ao2_iterator iter;
719
720         /* Run any hangup hooks. */
721         iter = ao2_iterator_init(features->hangup_hooks, 0);
722         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
723                 int failed;
724
725                 failed = hook->callback(bridge_channel->bridge, bridge_channel, hook->hook_pvt);
726                 if (failed) {
727                         ast_debug(1, "Hangup hook %p is being removed from %p(%s)\n",
728                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
729                         ao2_unlink(features->hangup_hooks, hook);
730                 }
731         }
732         ao2_iterator_destroy(&iter);
733
734         /* Default hangup action. */
735         ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_END);
736 }
737
738 static int bridge_channel_interval_ready(struct ast_bridge_channel *bridge_channel)
739 {
740         struct ast_bridge_features *features = bridge_channel->features;
741         struct ast_bridge_hook *hook;
742         int ready;
743
744         ast_heap_wrlock(features->interval_hooks);
745         hook = ast_heap_peek(features->interval_hooks, 1);
746         ready = hook && ast_tvdiff_ms(hook->parms.timer.trip_time, ast_tvnow()) <= 0;
747         ast_heap_unlock(features->interval_hooks);
748
749         return ready;
750 }
751
752 void ast_bridge_notify_talking(struct ast_bridge_channel *bridge_channel, int started_talking)
753 {
754         struct ast_frame action = {
755                 .frametype = AST_FRAME_BRIDGE_ACTION,
756                 .subclass.integer = started_talking
757                         ? AST_BRIDGE_ACTION_TALKING_START : AST_BRIDGE_ACTION_TALKING_STOP,
758         };
759
760         ast_bridge_channel_queue_frame(bridge_channel, &action);
761 }
762
763 static void bridge_channel_write_frame(struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
764 {
765         ast_bridge_channel_lock_bridge(bridge_channel);
766 /*
767  * BUGBUG need to implement a deferred write queue for when there is no peer channel in the bridge (yet or it was kicked).
768  *
769  * The tech decides if a frame needs to be pushed back for deferral.
770  * simple_bridge/native_bridge are likely the only techs that will do this.
771  */
772         bridge_channel->bridge->technology->write(bridge_channel->bridge, bridge_channel, frame);
773         ast_bridge_unlock(bridge_channel->bridge);
774 }
775
776 void ast_bridge_channel_write_action_data(struct ast_bridge_channel *bridge_channel, enum ast_bridge_action_type action, const void *data, size_t datalen)
777 {
778         struct ast_frame frame = {
779                 .frametype = AST_FRAME_BRIDGE_ACTION,
780                 .subclass.integer = action,
781                 .datalen = datalen,
782                 .data.ptr = (void *) data,
783         };
784
785         bridge_channel_write_frame(bridge_channel, &frame);
786 }
787
788 void ast_bridge_channel_write_control_data(struct ast_bridge_channel *bridge_channel, enum ast_control_frame_type control, const void *data, size_t datalen)
789 {
790         struct ast_frame frame = {
791                 .frametype = AST_FRAME_CONTROL,
792                 .subclass.integer = control,
793                 .datalen = datalen,
794                 .data.ptr = (void *) data,
795         };
796
797         bridge_channel_write_frame(bridge_channel, &frame);
798 }
799
800 void ast_bridge_channel_write_hold(struct ast_bridge_channel *bridge_channel, const char *moh_class)
801 {
802         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
803         size_t datalen;
804
805         if (!ast_strlen_zero(moh_class)) {
806                 datalen = strlen(moh_class) + 1;
807
808                 blob = ast_json_pack("{s: s}",
809                         "musicclass", moh_class);
810         } else {
811                 moh_class = NULL;
812                 datalen = 0;
813         }
814
815         ast_channel_publish_blob(bridge_channel->chan, ast_channel_hold_type(), blob);
816         ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_HOLD, moh_class,
817                 datalen);
818 }
819
820 void ast_bridge_channel_write_unhold(struct ast_bridge_channel *bridge_channel)
821 {
822         ast_channel_publish_blob(bridge_channel->chan, ast_channel_unhold_type(), NULL);
823         ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_UNHOLD, NULL, 0);
824 }
825
826 static int run_app_helper(struct ast_channel *chan, const char *app_name, const char *app_args)
827 {
828         int res = 0;
829
830         if (!strcasecmp("Gosub", app_name)) {
831                 ast_app_exec_sub(NULL, chan, app_args, 0);
832         } else if (!strcasecmp("Macro", app_name)) {
833                 ast_app_exec_macro(NULL, chan, app_args);
834         } else {
835                 struct ast_app *app;
836
837                 app = pbx_findapp(app_name);
838                 if (!app) {
839                         ast_log(LOG_WARNING, "Could not find application (%s)\n", app_name);
840                 } else {
841                         res = pbx_exec(chan, app, app_args);
842                 }
843         }
844         return res;
845 }
846
847 void ast_bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
848 {
849         if (moh_class) {
850                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
851         }
852         if (run_app_helper(bridge_channel->chan, app_name, S_OR(app_args, ""))) {
853                 /* Break the bridge if the app returns non-zero. */
854                 bridge_handle_hangup(bridge_channel);
855         }
856         if (moh_class) {
857                 ast_bridge_channel_write_unhold(bridge_channel);
858         }
859 }
860
861 struct bridge_run_app {
862         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
863         int moh_offset;
864         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
865         int app_args_offset;
866         /*! Application name to run. */
867         char app_name[0];
868 };
869
870 /*!
871  * \internal
872  * \brief Handle the run application bridge action.
873  * \since 12.0.0
874  *
875  * \param bridge_channel Which channel to run the application on.
876  * \param data Action frame data to run the application.
877  *
878  * \return Nothing
879  */
880 static void bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, struct bridge_run_app *data)
881 {
882         ast_bridge_channel_run_app(bridge_channel, data->app_name,
883                 data->app_args_offset ? &data->app_name[data->app_args_offset] : NULL,
884                 data->moh_offset ? &data->app_name[data->moh_offset] : NULL);
885 }
886
887 static void payload_helper_app(ast_bridge_channel_post_action_data post_it,
888         struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
889 {
890         struct bridge_run_app *app_data;
891         size_t len_name = strlen(app_name) + 1;
892         size_t len_args = ast_strlen_zero(app_args) ? 0 : strlen(app_args) + 1;
893         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
894         size_t len_data = sizeof(*app_data) + len_name + len_args + len_moh;
895
896         /* Fill in application run frame data. */
897         app_data = alloca(len_data);
898         app_data->app_args_offset = len_args ? len_name : 0;
899         app_data->moh_offset = len_moh ? len_name + len_args : 0;
900         strcpy(app_data->app_name, app_name);/* Safe */
901         if (len_args) {
902                 strcpy(&app_data->app_name[app_data->app_args_offset], app_args);/* Safe */
903         }
904         if (moh_class) {
905                 strcpy(&app_data->app_name[app_data->moh_offset], moh_class);/* Safe */
906         }
907
908         post_it(bridge_channel, AST_BRIDGE_ACTION_RUN_APP, app_data, len_data);
909 }
910
911 void ast_bridge_channel_write_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
912 {
913         payload_helper_app(ast_bridge_channel_write_action_data,
914                 bridge_channel, app_name, app_args, moh_class);
915 }
916
917 void ast_bridge_channel_queue_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
918 {
919         payload_helper_app(ast_bridge_channel_queue_action_data,
920                 bridge_channel, app_name, app_args, moh_class);
921 }
922
923 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)
924 {
925         if (moh_class) {
926                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
927         }
928         if (custom_play) {
929                 custom_play(bridge_channel, playfile);
930         } else {
931                 ast_stream_and_wait(bridge_channel->chan, playfile, AST_DIGIT_NONE);
932         }
933         if (moh_class) {
934                 ast_bridge_channel_write_unhold(bridge_channel);
935         }
936
937         /*
938          * It may be necessary to resume music on hold after we finish
939          * playing the announcment.
940          *
941          * XXX We have no idea what MOH class was in use before playing
942          * the file.
943          */
944         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_MOH)) {
945                 ast_moh_start(bridge_channel->chan, NULL, NULL);
946         }
947 }
948
949 struct bridge_playfile {
950         /*! Call this function to play the playfile. (NULL if normal sound file to play) */
951         ast_bridge_custom_play_fn custom_play;
952         /*! Offset into playfile[] where the MOH class name starts.  (zero if no MOH)*/
953         int moh_offset;
954         /*! Filename to play. */
955         char playfile[0];
956 };
957
958 /*!
959  * \internal
960  * \brief Handle the playfile bridge action.
961  * \since 12.0.0
962  *
963  * \param bridge_channel Which channel to play a file on.
964  * \param payload Action frame payload to play a file.
965  *
966  * \return Nothing
967  */
968 static void bridge_channel_playfile(struct ast_bridge_channel *bridge_channel, struct bridge_playfile *payload)
969 {
970         ast_bridge_channel_playfile(bridge_channel, payload->custom_play, payload->playfile,
971                 payload->moh_offset ? &payload->playfile[payload->moh_offset] : NULL);
972 }
973
974 static void payload_helper_playfile(ast_bridge_channel_post_action_data post_it,
975         struct ast_bridge_channel *bridge_channel, ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
976 {
977         struct bridge_playfile *payload;
978         size_t len_name = strlen(playfile) + 1;
979         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
980         size_t len_payload = sizeof(*payload) + len_name + len_moh;
981
982         /* Fill in play file frame data. */
983         payload = alloca(len_payload);
984         payload->custom_play = custom_play;
985         payload->moh_offset = len_moh ? len_name : 0;
986         strcpy(payload->playfile, playfile);/* Safe */
987         if (moh_class) {
988                 strcpy(&payload->playfile[payload->moh_offset], moh_class);/* Safe */
989         }
990
991         post_it(bridge_channel, AST_BRIDGE_ACTION_PLAY_FILE, payload, len_payload);
992 }
993
994 void 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)
995 {
996         payload_helper_playfile(ast_bridge_channel_write_action_data,
997                 bridge_channel, custom_play, playfile, moh_class);
998 }
999
1000 void 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)
1001 {
1002         payload_helper_playfile(ast_bridge_channel_queue_action_data,
1003                 bridge_channel, custom_play, playfile, moh_class);
1004 }
1005
1006 struct bridge_custom_callback {
1007         /*! Call this function on the bridge channel thread. */
1008         ast_bridge_custom_callback_fn callback;
1009         /*! Size of the payload if it exists.  A number otherwise. */
1010         size_t payload_size;
1011         /*! Nonzero if the payload exists. */
1012         char payload_exists;
1013         /*! Payload to give to callback. */
1014         char payload[0];
1015 };
1016
1017 /*!
1018  * \internal
1019  * \brief Handle the do custom callback bridge action.
1020  * \since 12.0.0
1021  *
1022  * \param bridge_channel Which channel to run the application on.
1023  * \param data Action frame data to run the application.
1024  *
1025  * \return Nothing
1026  */
1027 static void bridge_channel_do_callback(struct ast_bridge_channel *bridge_channel, struct bridge_custom_callback *data)
1028 {
1029         data->callback(bridge_channel, data->payload_exists ? data->payload : NULL, data->payload_size);
1030 }
1031
1032 static void payload_helper_cb(ast_bridge_channel_post_action_data post_it,
1033         struct ast_bridge_channel *bridge_channel, ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
1034 {
1035         struct bridge_custom_callback *cb_data;
1036         size_t len_data = sizeof(*cb_data) + (payload ? payload_size : 0);
1037
1038         /* Sanity check. */
1039         if (!callback) {
1040                 ast_assert(0);
1041                 return;
1042         }
1043
1044         /* Fill in custom callback frame data. */
1045         cb_data = alloca(len_data);
1046         cb_data->callback = callback;
1047         cb_data->payload_size = payload_size;
1048         cb_data->payload_exists = payload && payload_size;
1049         if (cb_data->payload_exists) {
1050                 memcpy(cb_data->payload, payload, payload_size);/* Safe */
1051         }
1052
1053         post_it(bridge_channel, AST_BRIDGE_ACTION_CALLBACK, cb_data, len_data);
1054 }
1055
1056 void ast_bridge_channel_write_callback(struct ast_bridge_channel *bridge_channel, ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
1057 {
1058         payload_helper_cb(ast_bridge_channel_write_action_data,
1059                 bridge_channel, callback, payload, payload_size);
1060 }
1061
1062 void ast_bridge_channel_queue_callback(struct ast_bridge_channel *bridge_channel, ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
1063 {
1064         payload_helper_cb(ast_bridge_channel_queue_action_data,
1065                 bridge_channel, callback, payload, payload_size);
1066 }
1067
1068 struct bridge_park {
1069         int parker_uuid_offset;
1070         int app_data_offset;
1071         /* buffer used for holding those strings */
1072         char parkee_uuid[0];
1073 };
1074
1075 static void bridge_channel_park(struct ast_bridge_channel *bridge_channel, struct bridge_park *payload)
1076 {
1077         ast_bridge_channel_park(bridge_channel, payload->parkee_uuid,
1078                 &payload->parkee_uuid[payload->parker_uuid_offset],
1079                 payload->app_data_offset ? &payload->parkee_uuid[payload->app_data_offset] : NULL);
1080 }
1081
1082 static void payload_helper_park(ast_bridge_channel_post_action_data post_it,
1083         struct ast_bridge_channel *bridge_channel,
1084         const char *parkee_uuid,
1085         const char *parker_uuid,
1086         const char *app_data)
1087 {
1088         struct bridge_park *payload;
1089         size_t len_parkee_uuid = strlen(parkee_uuid) + 1;
1090         size_t len_parker_uuid = strlen(parker_uuid) + 1;
1091         size_t len_app_data = !app_data ? 0 : strlen(app_data) + 1;
1092         size_t len_payload = sizeof(*payload) + len_parker_uuid + len_parkee_uuid + len_app_data;
1093
1094         payload = alloca(len_payload);
1095         payload->app_data_offset = len_app_data ? len_parkee_uuid + len_parker_uuid : 0;
1096         payload->parker_uuid_offset = len_parkee_uuid;
1097         strcpy(payload->parkee_uuid, parkee_uuid);
1098         strcpy(&payload->parkee_uuid[payload->parker_uuid_offset], parker_uuid);
1099         if (app_data) {
1100                 strcpy(&payload->parkee_uuid[payload->app_data_offset], app_data);
1101         }
1102
1103         post_it(bridge_channel, AST_BRIDGE_ACTION_PARK, payload, len_payload);
1104 }
1105
1106 void ast_bridge_channel_write_park(struct ast_bridge_channel *bridge_channel, const char *parkee_uuid, const char *parker_uuid, const char *app_data)
1107 {
1108         payload_helper_park(ast_bridge_channel_write_action_data,
1109                 bridge_channel, parkee_uuid, parker_uuid, app_data);
1110 }
1111
1112 /*!
1113  * \internal
1114  * \brief Feed notification that a frame is waiting on a channel into the bridging core
1115  *
1116  * \param bridge_channel Bridge channel the notification was received on
1117  */
1118 static void bridge_handle_trip(struct ast_bridge_channel *bridge_channel)
1119 {
1120         struct ast_frame *frame;
1121
1122         if (bridge_channel->features->mute) {
1123                 frame = ast_read_noaudio(bridge_channel->chan);
1124         } else {
1125                 frame = ast_read(bridge_channel->chan);
1126         }
1127
1128         if (!frame) {
1129                 bridge_handle_hangup(bridge_channel);
1130                 return;
1131         }
1132         switch (frame->frametype) {
1133         case AST_FRAME_NULL:
1134                 /* Just discard it. */
1135                 ast_frfree(frame);
1136                 return;
1137         case AST_FRAME_CONTROL:
1138                 switch (frame->subclass.integer) {
1139                 case AST_CONTROL_HANGUP:
1140                         bridge_handle_hangup(bridge_channel);
1141                         ast_frfree(frame);
1142                         return;
1143 /* BUGBUG This is where incoming HOLD/UNHOLD memory should register.  Write UNHOLD into bridge when this channel is pulled. */
1144                 default:
1145                         break;
1146                 }
1147                 break;
1148         case AST_FRAME_DTMF_BEGIN:
1149                 frame = bridge_handle_dtmf(bridge_channel, frame);
1150                 if (!frame) {
1151                         return;
1152                 }
1153                 /* Fall through */
1154         case AST_FRAME_DTMF_END:
1155                 if (!bridge_channel->features->dtmf_passthrough) {
1156                         ast_frfree(frame);
1157                         return;
1158                 }
1159 /* BUGBUG This is where incoming DTMF begin/end memory should register.  Write DTMF end into bridge when this channel is pulled. */
1160                 break;
1161         default:
1162                 break;
1163         }
1164
1165 /* BUGBUG bridge join or impart needs to do CONNECTED_LINE updates if the channels are being swapped and it is a 1-1 bridge. */
1166
1167         /* Simply write the frame out to the bridge technology. */
1168 /* BUGBUG The tech is where AST_CONTROL_ANSWER hook should go. (early bridge) */
1169 /* BUGBUG The tech is where incoming BUSY/CONGESTION hangup should happen? (early bridge) */
1170         bridge_channel_write_frame(bridge_channel, frame);
1171         ast_frfree(frame);
1172 }
1173
1174 /*!
1175  * \internal
1176  * \brief Complete joining a channel to the bridge.
1177  * \since 12.0.0
1178  *
1179  * \param bridge What to operate upon.
1180  * \param bridge_channel What is joining the bridge technology.
1181  *
1182  * \note On entry, bridge is already locked.
1183  *
1184  * \return Nothing
1185  */
1186 static void bridge_channel_complete_join(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
1187 {
1188         /* Make the channel compatible with the bridge */
1189         bridge_make_compatible(bridge, bridge_channel);
1190
1191         /* Tell the bridge technology we are joining so they set us up */
1192         ast_debug(1, "Bridge %s: %p(%s) is joining %s technology\n",
1193                 bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1194                 bridge->technology->name);
1195         if (bridge->technology->join
1196                 && bridge->technology->join(bridge, bridge_channel)) {
1197                 ast_debug(1, "Bridge %s: %p(%s) failed to join %s technology\n",
1198                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1199                         bridge->technology->name);
1200                 bridge_channel->just_joined = 1;
1201                 return;
1202         }
1203
1204         bridge_channel->just_joined = 0;
1205 }
1206
1207 /*!
1208  * \internal
1209  * \brief Complete joining new channels to the bridge.
1210  * \since 12.0.0
1211  *
1212  * \param bridge Check for new channels on this bridge.
1213  *
1214  * \note On entry, bridge is already locked.
1215  *
1216  * \return Nothing
1217  */
1218 static void bridge_complete_join(struct ast_bridge *bridge)
1219 {
1220         struct ast_bridge_channel *bridge_channel;
1221
1222         if (bridge->dissolved) {
1223                 /*
1224                  * No sense in completing the join on channels for a dissolved
1225                  * bridge.  They are just going to be removed soon anyway.
1226                  * However, we do have reason to abort here because the bridge
1227                  * technology may not be able to handle the number of channels
1228                  * still in the bridge.
1229                  */
1230                 return;
1231         }
1232
1233         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1234                 if (!bridge_channel->just_joined) {
1235                         continue;
1236                 }
1237                 bridge_channel_complete_join(bridge, bridge_channel);
1238         }
1239 }
1240
1241 /*! \brief Helper function used to find the "best" bridge technology given specified capabilities */
1242 static struct ast_bridge_technology *find_best_technology(uint32_t capabilities, struct ast_bridge *bridge)
1243 {
1244         struct ast_bridge_technology *current;
1245         struct ast_bridge_technology *best = NULL;
1246
1247         AST_RWLIST_RDLOCK(&bridge_technologies);
1248         AST_RWLIST_TRAVERSE(&bridge_technologies, current, entry) {
1249                 if (current->suspended) {
1250                         ast_debug(1, "Bridge technology %s is suspended. Skipping.\n",
1251                                 current->name);
1252                         continue;
1253                 }
1254                 if (!(current->capabilities & capabilities)) {
1255                         ast_debug(1, "Bridge technology %s does not have any capabilities we want.\n",
1256                                 current->name);
1257                         continue;
1258                 }
1259                 if (best && current->preference <= best->preference) {
1260                         ast_debug(1, "Bridge technology %s has less preference than %s (%d <= %d). Skipping.\n",
1261                                 current->name, best->name, current->preference, best->preference);
1262                         continue;
1263                 }
1264                 if (current->compatible && !current->compatible(bridge)) {
1265                         ast_debug(1, "Bridge technology %s is not compatible with properties of existing bridge.\n",
1266                                 current->name);
1267                         continue;
1268                 }
1269                 best = current;
1270         }
1271
1272         if (best) {
1273                 /* Increment it's module reference count if present so it does not get unloaded while in use */
1274                 ast_module_ref(best->mod);
1275                 ast_debug(1, "Chose bridge technology %s\n", best->name);
1276         }
1277
1278         AST_RWLIST_UNLOCK(&bridge_technologies);
1279
1280         return best;
1281 }
1282
1283 struct tech_deferred_destroy {
1284         struct ast_bridge_technology *tech;
1285         void *tech_pvt;
1286 };
1287
1288 /*!
1289  * \internal
1290  * \brief Deferred destruction of bridge tech private structure.
1291  * \since 12.0.0
1292  *
1293  * \param bridge What to execute the action on.
1294  * \param action Deferred bridge tech destruction.
1295  *
1296  * \note On entry, bridge must not be locked.
1297  *
1298  * \return Nothing
1299  */
1300 static void bridge_tech_deferred_destroy(struct ast_bridge *bridge, struct ast_frame *action)
1301 {
1302         struct tech_deferred_destroy *deferred = action->data.ptr;
1303         struct ast_bridge dummy_bridge = {
1304                 .technology = deferred->tech,
1305                 .tech_pvt = deferred->tech_pvt,
1306                 };
1307
1308         ast_copy_string(dummy_bridge.uniqueid, bridge->uniqueid, sizeof(dummy_bridge.uniqueid));
1309         ast_debug(1, "Bridge %s: calling %s technology destructor (deferred, dummy)\n",
1310                 dummy_bridge.uniqueid, dummy_bridge.technology->name);
1311         dummy_bridge.technology->destroy(&dummy_bridge);
1312         ast_module_unref(dummy_bridge.technology->mod);
1313 }
1314
1315 /*!
1316  * \internal
1317  * \brief Handle bridge action frame.
1318  * \since 12.0.0
1319  *
1320  * \param bridge What to execute the action on.
1321  * \param action What to do.
1322  *
1323  * \note On entry, bridge is already locked.
1324  * \note Can be called by the bridge destructor.
1325  *
1326  * \return Nothing
1327  */
1328 static void bridge_action_bridge(struct ast_bridge *bridge, struct ast_frame *action)
1329 {
1330 #if 0   /* In case we need to know when the destructor is calling us. */
1331         int in_destructor = !ao2_ref(bridge, 0);
1332 #endif
1333
1334         switch (action->subclass.integer) {
1335         case AST_BRIDGE_ACTION_DEFERRED_TECH_DESTROY:
1336                 ast_bridge_unlock(bridge);
1337                 bridge_tech_deferred_destroy(bridge, action);
1338                 ast_bridge_lock(bridge);
1339                 break;
1340         case AST_BRIDGE_ACTION_DEFERRED_DISSOLVING:
1341                 ast_bridge_unlock(bridge);
1342                 bridge->v_table->dissolving(bridge);
1343                 ast_bridge_lock(bridge);
1344                 break;
1345         default:
1346                 /* Unexpected deferred action type.  Should never happen. */
1347                 ast_assert(0);
1348                 break;
1349         }
1350 }
1351
1352 /*!
1353  * \internal
1354  * \brief Do any pending bridge actions.
1355  * \since 12.0.0
1356  *
1357  * \param bridge What to do actions on.
1358  *
1359  * \note On entry, bridge is already locked.
1360  * \note Can be called by the bridge destructor.
1361  *
1362  * \return Nothing
1363  */
1364 static void bridge_handle_actions(struct ast_bridge *bridge)
1365 {
1366         struct ast_frame *action;
1367
1368         while ((action = AST_LIST_REMOVE_HEAD(&bridge->action_queue, frame_list))) {
1369                 switch (action->frametype) {
1370                 case AST_FRAME_BRIDGE_ACTION:
1371                         bridge_action_bridge(bridge, action);
1372                         break;
1373                 default:
1374                         /* Unexpected deferred frame type.  Should never happen. */
1375                         ast_assert(0);
1376                         break;
1377                 }
1378                 ast_frfree(action);
1379         }
1380 }
1381
1382 static struct stasis_message *create_bridge_snapshot_message(struct ast_bridge *bridge)
1383 {
1384         RAII_VAR(struct ast_bridge_snapshot *, snapshot, NULL, ao2_cleanup);
1385         snapshot = ast_bridge_snapshot_create(bridge);
1386         if (!snapshot) {
1387                 return NULL;
1388         }
1389
1390         return stasis_message_create(ast_bridge_snapshot_type(), snapshot);
1391 }
1392
1393 static void destroy_bridge(void *obj)
1394 {
1395         struct ast_bridge *bridge = obj;
1396         RAII_VAR(struct stasis_message *, clear_msg, NULL, ao2_cleanup);
1397
1398         ast_debug(1, "Bridge %s: actually destroying %s bridge, nobody wants it anymore\n",
1399                 bridge->uniqueid, bridge->v_table->name);
1400
1401         clear_msg = create_bridge_snapshot_message(bridge);
1402         if (clear_msg) {
1403                 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
1404                 msg = stasis_cache_clear_create(clear_msg);
1405                 if (msg) {
1406                         stasis_publish(ast_bridge_topic(bridge), msg);
1407                 }
1408         }
1409
1410         /* Do any pending actions in the context of destruction. */
1411         ast_bridge_lock(bridge);
1412         bridge_handle_actions(bridge);
1413         ast_bridge_unlock(bridge);
1414
1415         /* There should not be any channels left in the bridge. */
1416         ast_assert(AST_LIST_EMPTY(&bridge->channels));
1417
1418         ast_debug(1, "Bridge %s: calling %s bridge destructor\n",
1419                 bridge->uniqueid, bridge->v_table->name);
1420         bridge->v_table->destroy(bridge);
1421
1422         /* Pass off the bridge to the technology to destroy if needed */
1423         if (bridge->technology) {
1424                 ast_debug(1, "Bridge %s: calling %s technology stop\n",
1425                         bridge->uniqueid, bridge->technology->name);
1426                 if (bridge->technology->stop) {
1427                         ast_bridge_lock(bridge);
1428                         bridge->technology->stop(bridge);
1429                         ast_bridge_unlock(bridge);
1430                 }
1431                 ast_debug(1, "Bridge %s: calling %s technology destructor\n",
1432                         bridge->uniqueid, bridge->technology->name);
1433                 if (bridge->technology->destroy) {
1434                         bridge->technology->destroy(bridge);
1435                 }
1436                 ast_module_unref(bridge->technology->mod);
1437                 bridge->technology = NULL;
1438         }
1439
1440         if (bridge->callid) {
1441                 bridge->callid = ast_callid_unref(bridge->callid);
1442         }
1443
1444         cleanup_video_mode(bridge);
1445 }
1446
1447 struct ast_bridge *ast_bridge_register(struct ast_bridge *bridge)
1448 {
1449         if (bridge) {
1450                 ast_bridge_publish_state(bridge);
1451                 if (!ao2_link(bridges, bridge)) {
1452                         ast_bridge_destroy(bridge);
1453                         bridge = NULL;
1454                 }
1455         }
1456         return bridge;
1457 }
1458
1459 struct ast_bridge *ast_bridge_alloc(size_t size, const struct ast_bridge_methods *v_table)
1460 {
1461         struct ast_bridge *bridge;
1462
1463         /* Check v_table that all methods are present. */
1464         if (!v_table
1465                 || !v_table->name
1466                 || !v_table->destroy
1467                 || !v_table->dissolving
1468                 || !v_table->push
1469                 || !v_table->pull
1470                 || !v_table->notify_masquerade
1471                 || !v_table->get_merge_priority) {
1472                 ast_log(LOG_ERROR, "Virtual method table for bridge class %s not complete.\n",
1473                         v_table && v_table->name ? v_table->name : "<unknown>");
1474                 ast_assert(0);
1475                 return NULL;
1476         }
1477
1478         bridge = ao2_alloc(size, destroy_bridge);
1479         if (bridge) {
1480                 bridge->v_table = v_table;
1481         }
1482         return bridge;
1483 }
1484
1485 struct ast_bridge *ast_bridge_base_init(struct ast_bridge *self, uint32_t capabilities, unsigned int flags)
1486 {
1487         if (!self) {
1488                 return NULL;
1489         }
1490
1491         ast_uuid_generate_str(self->uniqueid, sizeof(self->uniqueid));
1492         ast_set_flag(&self->feature_flags, flags);
1493         self->allowed_capabilities = capabilities;
1494
1495         /* Use our helper function to find the "best" bridge technology. */
1496         self->technology = find_best_technology(capabilities, self);
1497         if (!self->technology) {
1498                 ast_debug(1, "Bridge %s: Could not create.  No technology available to support it.\n",
1499                         self->uniqueid);
1500                 ao2_ref(self, -1);
1501                 return NULL;
1502         }
1503
1504         /* Pass off the bridge to the technology to manipulate if needed */
1505         ast_debug(1, "Bridge %s: calling %s technology constructor\n",
1506                 self->uniqueid, self->technology->name);
1507         if (self->technology->create && self->technology->create(self)) {
1508                 ast_debug(1, "Bridge %s: failed to setup %s technology\n",
1509                         self->uniqueid, self->technology->name);
1510                 ao2_ref(self, -1);
1511                 return NULL;
1512         }
1513         ast_debug(1, "Bridge %s: calling %s technology start\n",
1514                 self->uniqueid, self->technology->name);
1515         if (self->technology->start && self->technology->start(self)) {
1516                 ast_debug(1, "Bridge %s: failed to start %s technology\n",
1517                         self->uniqueid, self->technology->name);
1518                 ao2_ref(self, -1);
1519                 return NULL;
1520         }
1521
1522         if (!ast_bridge_topic(self)) {
1523                 ao2_ref(self, -1);
1524                 return NULL;
1525         }
1526
1527         return self;
1528 }
1529
1530 /*!
1531  * \internal
1532  * \brief ast_bridge base class destructor.
1533  * \since 12.0.0
1534  *
1535  * \param self Bridge to operate upon.
1536  *
1537  * \note Stub because of nothing to do.
1538  *
1539  * \return Nothing
1540  */
1541 static void bridge_base_destroy(struct ast_bridge *self)
1542 {
1543 }
1544
1545 /*!
1546  * \internal
1547  * \brief The bridge is being dissolved.
1548  * \since 12.0.0
1549  *
1550  * \param self Bridge to operate upon.
1551  *
1552  * \return Nothing
1553  */
1554 static void bridge_base_dissolving(struct ast_bridge *self)
1555 {
1556         ao2_unlink(bridges, self);
1557 }
1558
1559 /*!
1560  * \internal
1561  * \brief ast_bridge base push method.
1562  * \since 12.0.0
1563  *
1564  * \param self Bridge to operate upon.
1565  * \param bridge_channel Bridge channel to push.
1566  * \param swap Bridge channel to swap places with if not NULL.
1567  *
1568  * \note On entry, self is already locked.
1569  * \note Stub because of nothing to do.
1570  *
1571  * \retval 0 on success
1572  * \retval -1 on failure
1573  */
1574 static int bridge_base_push(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
1575 {
1576         return 0;
1577 }
1578
1579 /*!
1580  * \internal
1581  * \brief ast_bridge base pull method.
1582  * \since 12.0.0
1583  *
1584  * \param self Bridge to operate upon.
1585  * \param bridge_channel Bridge channel to pull.
1586  *
1587  * \note On entry, self is already locked.
1588  *
1589  * \return Nothing
1590  */
1591 static void bridge_base_pull(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel)
1592 {
1593         bridge_features_remove(bridge_channel->features, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
1594 }
1595
1596 /*!
1597  * \internal
1598  * \brief ast_bridge base notify_masquerade method.
1599  * \since 12.0.0
1600  *
1601  * \param self Bridge to operate upon.
1602  * \param bridge_channel Bridge channel that was masqueraded.
1603  *
1604  * \note On entry, self is already locked.
1605  *
1606  * \return Nothing
1607  */
1608 static void bridge_base_notify_masquerade(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel)
1609 {
1610         self->reconfigured = 1;
1611 }
1612
1613 /*!
1614  * \internal
1615  * \brief Get the merge priority of this bridge.
1616  * \since 12.0.0
1617  *
1618  * \param self Bridge to operate upon.
1619  *
1620  * \note On entry, self is already locked.
1621  *
1622  * \return Merge priority
1623  */
1624 static int bridge_base_get_merge_priority(struct ast_bridge *self)
1625 {
1626         return 0;
1627 }
1628
1629 struct ast_bridge_methods ast_bridge_base_v_table = {
1630         .name = "base",
1631         .destroy = bridge_base_destroy,
1632         .dissolving = bridge_base_dissolving,
1633         .push = bridge_base_push,
1634         .pull = bridge_base_pull,
1635         .notify_masquerade = bridge_base_notify_masquerade,
1636         .get_merge_priority = bridge_base_get_merge_priority,
1637 };
1638
1639 struct ast_bridge *ast_bridge_base_new(uint32_t capabilities, unsigned int flags)
1640 {
1641         void *bridge;
1642
1643         bridge = ast_bridge_alloc(sizeof(struct ast_bridge), &ast_bridge_base_v_table);
1644         bridge = ast_bridge_base_init(bridge, capabilities, flags);
1645         bridge = ast_bridge_register(bridge);
1646         return bridge;
1647 }
1648
1649 int ast_bridge_destroy(struct ast_bridge *bridge)
1650 {
1651         ast_debug(1, "Bridge %s: telling all channels to leave the party\n", bridge->uniqueid);
1652         ast_bridge_lock(bridge);
1653         bridge_dissolve(bridge);
1654         ast_bridge_unlock(bridge);
1655
1656         ao2_ref(bridge, -1);
1657
1658         return 0;
1659 }
1660
1661 static int bridge_make_compatible(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
1662 {
1663         struct ast_format read_format;
1664         struct ast_format write_format;
1665         struct ast_format best_format;
1666         char codec_buf[512];
1667
1668         ast_format_copy(&read_format, ast_channel_readformat(bridge_channel->chan));
1669         ast_format_copy(&write_format, ast_channel_writeformat(bridge_channel->chan));
1670
1671         /* Are the formats currently in use something this bridge can handle? */
1672         if (!ast_format_cap_iscompatible(bridge->technology->format_capabilities, ast_channel_readformat(bridge_channel->chan))) {
1673                 ast_best_codec(bridge->technology->format_capabilities, &best_format);
1674
1675                 /* Read format is a no go... */
1676                 ast_debug(1, "Bridge technology %s wants to read any of formats %s but channel has %s\n",
1677                         bridge->technology->name,
1678                         ast_getformatname_multiple(codec_buf, sizeof(codec_buf), bridge->technology->format_capabilities),
1679                         ast_getformatname(&read_format));
1680
1681                 /* Switch read format to the best one chosen */
1682                 if (ast_set_read_format(bridge_channel->chan, &best_format)) {
1683                         ast_log(LOG_WARNING, "Failed to set channel %s to read format %s\n",
1684                                 ast_channel_name(bridge_channel->chan), ast_getformatname(&best_format));
1685                         return -1;
1686                 }
1687                 ast_debug(1, "Bridge %s put channel %s into read format %s\n",
1688                         bridge->uniqueid, ast_channel_name(bridge_channel->chan),
1689                         ast_getformatname(&best_format));
1690         } else {
1691                 ast_debug(1, "Bridge %s is happy that channel %s already has read format %s\n",
1692                         bridge->uniqueid, ast_channel_name(bridge_channel->chan),
1693                         ast_getformatname(&read_format));
1694         }
1695
1696         if (!ast_format_cap_iscompatible(bridge->technology->format_capabilities, &write_format)) {
1697                 ast_best_codec(bridge->technology->format_capabilities, &best_format);
1698
1699                 /* Write format is a no go... */
1700                 ast_debug(1, "Bridge technology %s wants to write any of formats %s but channel has %s\n",
1701                         bridge->technology->name,
1702                         ast_getformatname_multiple(codec_buf, sizeof(codec_buf), bridge->technology->format_capabilities),
1703                         ast_getformatname(&write_format));
1704
1705                 /* Switch write format to the best one chosen */
1706                 if (ast_set_write_format(bridge_channel->chan, &best_format)) {
1707                         ast_log(LOG_WARNING, "Failed to set channel %s to write format %s\n",
1708                                 ast_channel_name(bridge_channel->chan), ast_getformatname(&best_format));
1709                         return -1;
1710                 }
1711                 ast_debug(1, "Bridge %s put channel %s into write format %s\n",
1712                         bridge->uniqueid, ast_channel_name(bridge_channel->chan),
1713                         ast_getformatname(&best_format));
1714         } else {
1715                 ast_debug(1, "Bridge %s is happy that channel %s already has write format %s\n",
1716                         bridge->uniqueid, ast_channel_name(bridge_channel->chan),
1717                         ast_getformatname(&write_format));
1718         }
1719
1720         return 0;
1721 }
1722
1723 /*!
1724  * \internal
1725  * \brief Perform the smart bridge operation.
1726  * \since 12.0.0
1727  *
1728  * \param bridge Work on this bridge.
1729  *
1730  * \details
1731  * Basically see if a new bridge technology should be used instead
1732  * of the current one.
1733  *
1734  * \note On entry, bridge is already locked.
1735  *
1736  * \retval 0 on success.
1737  * \retval -1 on error.
1738  */
1739 static int smart_bridge_operation(struct ast_bridge *bridge)
1740 {
1741         uint32_t new_capabilities;
1742         struct ast_bridge_technology *new_technology;
1743         struct ast_bridge_technology *old_technology = bridge->technology;
1744         struct ast_bridge_channel *bridge_channel;
1745         struct ast_frame *deferred_action;
1746         struct ast_bridge dummy_bridge = {
1747                 .technology = bridge->technology,
1748                 .tech_pvt = bridge->tech_pvt,
1749         };
1750
1751         if (bridge->dissolved) {
1752                 ast_debug(1, "Bridge %s is dissolved, not performing smart bridge operation.\n",
1753                         bridge->uniqueid);
1754                 return 0;
1755         }
1756
1757         /* Determine new bridge technology capabilities needed. */
1758         if (2 < bridge->num_channels) {
1759                 new_capabilities = AST_BRIDGE_CAPABILITY_MULTIMIX;
1760                 new_capabilities &= bridge->allowed_capabilities;
1761         } else {
1762                 new_capabilities = AST_BRIDGE_CAPABILITY_NATIVE | AST_BRIDGE_CAPABILITY_1TO1MIX;
1763                 new_capabilities &= bridge->allowed_capabilities;
1764                 if (!new_capabilities
1765                         && (bridge->allowed_capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
1766                         /* Allow switching between different multimix bridge technologies. */
1767                         new_capabilities = AST_BRIDGE_CAPABILITY_MULTIMIX;
1768                 }
1769         }
1770
1771         /* Find a bridge technology to satisfy the new capabilities. */
1772         new_technology = find_best_technology(new_capabilities, bridge);
1773         if (!new_technology) {
1774                 int is_compatible = 0;
1775
1776                 if (old_technology->compatible) {
1777                         is_compatible = old_technology->compatible(bridge);
1778                 } else if (old_technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX) {
1779                         is_compatible = 1;
1780                 } else if (bridge->num_channels <= 2
1781                         && (old_technology->capabilities & AST_BRIDGE_CAPABILITY_1TO1MIX)) {
1782                         is_compatible = 1;
1783                 }
1784
1785                 if (is_compatible) {
1786                         ast_debug(1, "Bridge %s could not get a new technology, staying with old technology.\n",
1787                                 bridge->uniqueid);
1788                         return 0;
1789                 }
1790                 ast_log(LOG_WARNING, "Bridge %s has no technology available to support it.\n",
1791                         bridge->uniqueid);
1792                 return -1;
1793         }
1794         if (new_technology == old_technology) {
1795                 ast_debug(1, "Bridge %s is already using the new technology.\n",
1796                         bridge->uniqueid);
1797                 ast_module_unref(old_technology->mod);
1798                 return 0;
1799         }
1800
1801         ast_copy_string(dummy_bridge.uniqueid, bridge->uniqueid, sizeof(dummy_bridge.uniqueid));
1802
1803         if (old_technology->destroy) {
1804                 struct tech_deferred_destroy deferred_tech_destroy = {
1805                         .tech = dummy_bridge.technology,
1806                         .tech_pvt = dummy_bridge.tech_pvt,
1807                 };
1808                 struct ast_frame action = {
1809                         .frametype = AST_FRAME_BRIDGE_ACTION,
1810                         .subclass.integer = AST_BRIDGE_ACTION_DEFERRED_TECH_DESTROY,
1811                         .data.ptr = &deferred_tech_destroy,
1812                         .datalen = sizeof(deferred_tech_destroy),
1813                 };
1814
1815                 /*
1816                  * We need to defer the bridge technology destroy callback
1817                  * because we have the bridge locked.
1818                  */
1819                 deferred_action = ast_frdup(&action);
1820                 if (!deferred_action) {
1821                         ast_module_unref(new_technology->mod);
1822                         return -1;
1823                 }
1824         } else {
1825                 deferred_action = NULL;
1826         }
1827
1828         /*
1829          * We are now committed to changing the bridge technology.  We
1830          * must not release the bridge lock until we have installed the
1831          * new bridge technology.
1832          */
1833         ast_debug(1, "Bridge %s: switching %s technology to %s\n",
1834                 bridge->uniqueid, old_technology->name, new_technology->name);
1835
1836         /*
1837          * Since we are soon going to pass this bridge to a new
1838          * technology we need to NULL out the tech_pvt pointer but
1839          * don't worry as it still exists in dummy_bridge, ditto for the
1840          * old technology.
1841          */
1842         bridge->tech_pvt = NULL;
1843         bridge->technology = new_technology;
1844
1845         /* Setup the new bridge technology. */
1846         ast_debug(1, "Bridge %s: calling %s technology constructor\n",
1847                 bridge->uniqueid, new_technology->name);
1848         if (new_technology->create && new_technology->create(bridge)) {
1849                 ast_log(LOG_WARNING, "Bridge %s: failed to setup bridge technology %s\n",
1850                         bridge->uniqueid, new_technology->name);
1851                 bridge->tech_pvt = dummy_bridge.tech_pvt;
1852                 bridge->technology = dummy_bridge.technology;
1853                 ast_module_unref(new_technology->mod);
1854                 return -1;
1855         }
1856
1857         ast_debug(1, "Bridge %s: calling %s technology stop\n",
1858                 dummy_bridge.uniqueid, old_technology->name);
1859         if (old_technology->stop) {
1860                 old_technology->stop(&dummy_bridge);
1861         }
1862
1863         /*
1864          * Move existing channels over to the new technology and
1865          * complete joining any new channels to the bridge.
1866          */
1867         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1868                 if (!bridge_channel->just_joined) {
1869                         /* Take existing channel from the old technology. */
1870                         ast_debug(1, "Bridge %s: %p(%s) is leaving %s technology (dummy)\n",
1871                                 dummy_bridge.uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1872                                 old_technology->name);
1873                         if (old_technology->leave) {
1874                                 old_technology->leave(&dummy_bridge, bridge_channel);
1875                         }
1876                 }
1877
1878                 /* Add any new channels or re-add an existing channel to the bridge. */
1879                 bridge_channel_complete_join(bridge, bridge_channel);
1880         }
1881
1882         ast_debug(1, "Bridge %s: calling %s technology start\n",
1883                 bridge->uniqueid, new_technology->name);
1884         if (new_technology->start && new_technology->start(bridge)) {
1885                 ast_log(LOG_WARNING, "Bridge %s: failed to start bridge technology %s\n",
1886                         bridge->uniqueid, new_technology->name);
1887         }
1888
1889         /*
1890          * Now that all the channels have been moved over we need to get
1891          * rid of all the information the old technology may have left
1892          * around.
1893          */
1894         if (old_technology->destroy) {
1895                 ast_debug(1, "Bridge %s: deferring %s technology destructor\n",
1896                         dummy_bridge.uniqueid, old_technology->name);
1897                 bridge_queue_action_nodup(bridge, deferred_action);
1898         } else {
1899                 ast_debug(1, "Bridge %s: calling %s technology destructor\n",
1900                         dummy_bridge.uniqueid, old_technology->name);
1901                 ast_module_unref(old_technology->mod);
1902         }
1903
1904         return 0;
1905 }
1906
1907 /*!
1908  * \internal
1909  * \brief Bridge channel to check if a BRIDGE_PLAY_SOUND needs to be played.
1910  * \since 12.0.0
1911  *
1912  * \param bridge_channel What to check.
1913  *
1914  * \return Nothing
1915  */
1916 static void check_bridge_play_sound(struct ast_bridge_channel *bridge_channel)
1917 {
1918         const char *play_file;
1919
1920         ast_channel_lock(bridge_channel->chan);
1921         play_file = pbx_builtin_getvar_helper(bridge_channel->chan, "BRIDGE_PLAY_SOUND");
1922         if (!ast_strlen_zero(play_file)) {
1923                 play_file = ast_strdupa(play_file);
1924                 pbx_builtin_setvar_helper(bridge_channel->chan, "BRIDGE_PLAY_SOUND", NULL);
1925         } else {
1926                 play_file = NULL;
1927         }
1928         ast_channel_unlock(bridge_channel->chan);
1929
1930         if (play_file) {
1931                 ast_bridge_channel_queue_playfile(bridge_channel, NULL, play_file, NULL);
1932         }
1933 }
1934
1935 /*!
1936  * \internal
1937  * \brief Check for any BRIDGE_PLAY_SOUND channel variables in the bridge.
1938  * \since 12.0.0
1939  *
1940  * \param bridge What to operate on.
1941  *
1942  * \note On entry, the bridge is already locked.
1943  *
1944  * \return Nothing
1945  */
1946 static void check_bridge_play_sounds(struct ast_bridge *bridge)
1947 {
1948         struct ast_bridge_channel *bridge_channel;
1949
1950         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1951                 check_bridge_play_sound(bridge_channel);
1952         }
1953 }
1954
1955 static void update_bridge_vars_set(struct ast_channel *chan, const char *name, const char *pvtid)
1956 {
1957         pbx_builtin_setvar_helper(chan, "BRIDGEPEER", name);
1958         pbx_builtin_setvar_helper(chan, "BRIDGEPVTCALLID", pvtid);
1959 }
1960
1961 /*!
1962  * \internal
1963  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in a 2 party bridge.
1964  * \since 12.0.0
1965  *
1966  * \param c0 Party of the first part.
1967  * \param c1 Party of the second part.
1968  *
1969  * \note On entry, the bridge is already locked.
1970  * \note The bridge is expected to have exactly two parties.
1971  *
1972  * \return Nothing
1973  */
1974 static void set_bridge_peer_vars_2party(struct ast_channel *c0, struct ast_channel *c1)
1975 {
1976         const char *c0_name;
1977         const char *c1_name;
1978         const char *c0_pvtid = NULL;
1979         const char *c1_pvtid = NULL;
1980 #define UPDATE_BRIDGE_VARS_GET(chan, name, pvtid)                                                                       \
1981         do {                                                                                                                                                    \
1982                 name = ast_strdupa(ast_channel_name(chan));                                                                     \
1983                 if (ast_channel_tech(chan)->get_pvt_uniqueid) {                                                         \
1984                         pvtid = ast_strdupa(ast_channel_tech(chan)->get_pvt_uniqueid(chan));    \
1985                 }                                                                                                                                                       \
1986         } while (0)
1987
1988         ast_channel_lock(c1);
1989         UPDATE_BRIDGE_VARS_GET(c1, c1_name, c1_pvtid);
1990         ast_channel_unlock(c1);
1991
1992         ast_channel_lock(c0);
1993         update_bridge_vars_set(c0, c1_name, c1_pvtid);
1994         UPDATE_BRIDGE_VARS_GET(c0, c0_name, c0_pvtid);
1995         ast_channel_unlock(c0);
1996
1997         ast_channel_lock(c1);
1998         update_bridge_vars_set(c1, c0_name, c0_pvtid);
1999         ast_channel_unlock(c1);
2000 }
2001
2002 /*!
2003  * \internal
2004  * \brief Fill the BRIDGEPEER value buffer with a comma separated list of channel names.
2005  * \since 12.0.0
2006  *
2007  * \param buf Buffer to fill.  The caller must guarantee the buffer is large enough.
2008  * \param cur_idx Which index into names[] to skip.
2009  * \param names Channel names to put in the buffer.
2010  * \param num_names Number of names in the array.
2011  *
2012  * \return Nothing
2013  */
2014 static void fill_bridgepeer_buf(char *buf, unsigned int cur_idx, const char *names[], unsigned int num_names)
2015 {
2016         int need_separator = 0;
2017         unsigned int idx;
2018         const char *src;
2019         char *pos;
2020
2021         pos = buf;
2022         for (idx = 0; idx < num_names; ++idx) {
2023                 if (idx == cur_idx) {
2024                         continue;
2025                 }
2026
2027                 if (need_separator) {
2028                         *pos++ = ',';
2029                 }
2030                 need_separator = 1;
2031
2032                 /* Copy name into buffer. */
2033                 src = names[idx];
2034                 while (*src) {
2035                         *pos++ = *src++;
2036                 }
2037         }
2038         *pos = '\0';
2039 }
2040
2041 /*!
2042  * \internal
2043  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in a multi-party bridge.
2044  * \since 12.0.0
2045  *
2046  * \param bridge What to operate on.
2047  *
2048  * \note On entry, the bridge is already locked.
2049  * \note The bridge is expected to have more than two parties.
2050  *
2051  * \return Nothing
2052  */
2053 static void set_bridge_peer_vars_multiparty(struct ast_bridge *bridge)
2054 {
2055 /*
2056  * Set a maximum number of channel names for the BRIDGEPEER
2057  * list.  The plus one is for the current channel which is not
2058  * put in the list.
2059  */
2060 #define MAX_BRIDGEPEER_CHANS    (10 + 1)
2061
2062         unsigned int idx;
2063         unsigned int num_names;
2064         unsigned int len;
2065         const char **names;
2066         char *buf;
2067         struct ast_bridge_channel *bridge_channel;
2068
2069         /* Get first MAX_BRIDGEPEER_CHANS channel names. */
2070         num_names = MIN(bridge->num_channels, MAX_BRIDGEPEER_CHANS);
2071         names = ast_alloca(num_names * sizeof(*names));
2072         idx = 0;
2073         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
2074                 if (num_names <= idx) {
2075                         break;
2076                 }
2077                 ast_channel_lock(bridge_channel->chan);
2078                 names[idx++] = ast_strdupa(ast_channel_name(bridge_channel->chan));
2079                 ast_channel_unlock(bridge_channel->chan);
2080         }
2081
2082         /* Determine maximum buf size needed. */
2083         len = num_names;
2084         for (idx = 0; idx < num_names; ++idx) {
2085                 len += strlen(names[idx]);
2086         }
2087         buf = ast_alloca(len);
2088
2089         /* Set the bridge channel variables. */
2090         idx = 0;
2091         buf[0] = '\0';
2092         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
2093                 if (idx < num_names) {
2094                         fill_bridgepeer_buf(buf, idx, names, num_names);
2095                 }
2096                 ++idx;
2097
2098                 ast_channel_lock(bridge_channel->chan);
2099                 update_bridge_vars_set(bridge_channel->chan, buf, NULL);
2100                 ast_channel_unlock(bridge_channel->chan);
2101         }
2102 }
2103
2104 /*!
2105  * \internal
2106  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in a holding bridge.
2107  * \since 12.0.0
2108  *
2109  * \param bridge What to operate on.
2110  *
2111  * \note On entry, the bridge is already locked.
2112  *
2113  * \return Nothing
2114  */
2115 static void set_bridge_peer_vars_holding(struct ast_bridge *bridge)
2116 {
2117         struct ast_bridge_channel *bridge_channel;
2118
2119         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
2120                 ast_channel_lock(bridge_channel->chan);
2121                 update_bridge_vars_set(bridge_channel->chan, NULL, NULL);
2122                 ast_channel_unlock(bridge_channel->chan);
2123         }
2124 }
2125
2126 /*!
2127  * \internal
2128  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in the bridge.
2129  * \since 12.0.0
2130  *
2131  * \param bridge What to operate on.
2132  *
2133  * \note On entry, the bridge is already locked.
2134  *
2135  * \return Nothing
2136  */
2137 static void set_bridge_peer_vars(struct ast_bridge *bridge)
2138 {
2139         if (bridge->technology->capabilities & AST_BRIDGE_CAPABILITY_HOLDING) {
2140                 set_bridge_peer_vars_holding(bridge);
2141                 return;
2142         }
2143         if (bridge->num_channels < 2) {
2144                 return;
2145         }
2146         if (bridge->num_channels == 2) {
2147                 set_bridge_peer_vars_2party(AST_LIST_FIRST(&bridge->channels)->chan,
2148                         AST_LIST_LAST(&bridge->channels)->chan);
2149         } else {
2150                 set_bridge_peer_vars_multiparty(bridge);
2151         }
2152 }
2153
2154 /*!
2155  * \internal
2156  * \brief Notify the bridge that it has been reconfigured.
2157  * \since 12.0.0
2158  *
2159  * \param bridge Reconfigured bridge.
2160  *
2161  * \details
2162  * After a series of bridge_channel_push and
2163  * bridge_channel_pull calls, you need to call this function
2164  * to cause the bridge to complete restructuring for the change
2165  * in the channel makeup of the bridge.
2166  *
2167  * \note On entry, the bridge is already locked.
2168  *
2169  * \return Nothing
2170  */
2171 static void bridge_reconfigured(struct ast_bridge *bridge)
2172 {
2173         if (!bridge->reconfigured) {
2174                 return;
2175         }
2176         bridge->reconfigured = 0;
2177         if (ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_SMART)
2178                 && smart_bridge_operation(bridge)) {
2179                 /* Smart bridge failed. */
2180                 bridge_dissolve(bridge);
2181                 return;
2182         }
2183         bridge_complete_join(bridge);
2184
2185         if (bridge->dissolved) {
2186                 return;
2187         }
2188         check_bridge_play_sounds(bridge);
2189         set_bridge_peer_vars(bridge);
2190         ast_bridge_publish_state(bridge);
2191 }
2192
2193 /*!
2194  * \internal
2195  * \brief Suspend a channel from a bridge.
2196  *
2197  * \param bridge_channel Channel to suspend.
2198  *
2199  * \note This function assumes bridge_channel->bridge is locked.
2200  *
2201  * \return Nothing
2202  */
2203 static void bridge_channel_suspend_nolock(struct ast_bridge_channel *bridge_channel)
2204 {
2205         bridge_channel->suspended = 1;
2206         if (bridge_channel->in_bridge) {
2207                 --bridge_channel->bridge->num_active;
2208         }
2209
2210         /* Get technology bridge threads off of the channel. */
2211         if (bridge_channel->bridge->technology->suspend) {
2212                 bridge_channel->bridge->technology->suspend(bridge_channel->bridge, bridge_channel);
2213         }
2214 }
2215
2216 /*!
2217  * \internal
2218  * \brief Suspend a channel from a bridge.
2219  *
2220  * \param bridge_channel Channel to suspend.
2221  *
2222  * \return Nothing
2223  */
2224 static void bridge_channel_suspend(struct ast_bridge_channel *bridge_channel)
2225 {
2226         ast_bridge_channel_lock_bridge(bridge_channel);
2227         bridge_channel_suspend_nolock(bridge_channel);
2228         ast_bridge_unlock(bridge_channel->bridge);
2229 }
2230
2231 /*!
2232  * \internal
2233  * \brief Unsuspend a channel from a bridge.
2234  *
2235  * \param bridge_channel Channel to unsuspend.
2236  *
2237  * \note This function assumes bridge_channel->bridge is locked.
2238  *
2239  * \return Nothing
2240  */
2241 static void bridge_channel_unsuspend_nolock(struct ast_bridge_channel *bridge_channel)
2242 {
2243         bridge_channel->suspended = 0;
2244         if (bridge_channel->in_bridge) {
2245                 ++bridge_channel->bridge->num_active;
2246         }
2247
2248         /* Wake technology bridge threads to take care of channel again. */
2249         if (bridge_channel->bridge->technology->unsuspend) {
2250                 bridge_channel->bridge->technology->unsuspend(bridge_channel->bridge, bridge_channel);
2251         }
2252
2253         /* Wake suspended channel. */
2254         ast_bridge_channel_lock(bridge_channel);
2255         ast_cond_signal(&bridge_channel->cond);
2256         ast_bridge_channel_unlock(bridge_channel);
2257 }
2258
2259 /*!
2260  * \internal
2261  * \brief Unsuspend a channel from a bridge.
2262  *
2263  * \param bridge_channel Channel to unsuspend.
2264  *
2265  * \return Nothing
2266  */
2267 static void bridge_channel_unsuspend(struct ast_bridge_channel *bridge_channel)
2268 {
2269         ast_bridge_channel_lock_bridge(bridge_channel);
2270         bridge_channel_unsuspend_nolock(bridge_channel);
2271         ast_bridge_unlock(bridge_channel->bridge);
2272 }
2273
2274 /*! \brief Internal function that activates interval hooks on a bridge channel */
2275 static void bridge_channel_interval(struct ast_bridge_channel *bridge_channel)
2276 {
2277         struct ast_bridge_hook *hook;
2278         struct timeval start;
2279
2280         ast_heap_wrlock(bridge_channel->features->interval_hooks);
2281         start = ast_tvnow();
2282         while ((hook = ast_heap_peek(bridge_channel->features->interval_hooks, 1))) {
2283                 int interval;
2284                 unsigned int execution_time;
2285
2286                 if (ast_tvdiff_ms(hook->parms.timer.trip_time, start) > 0) {
2287                         ast_debug(1, "Hook %p on %p(%s) wants to happen in the future, stopping our traversal\n",
2288                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
2289                         break;
2290                 }
2291                 ao2_ref(hook, +1);
2292                 ast_heap_unlock(bridge_channel->features->interval_hooks);
2293
2294                 ast_debug(1, "Executing hook %p on %p(%s)\n",
2295                         hook, bridge_channel, ast_channel_name(bridge_channel->chan));
2296                 interval = hook->callback(bridge_channel->bridge, bridge_channel, hook->hook_pvt);
2297
2298                 ast_heap_wrlock(bridge_channel->features->interval_hooks);
2299                 if (ast_heap_peek(bridge_channel->features->interval_hooks,
2300                         hook->parms.timer.heap_index) != hook
2301                         || !ast_heap_remove(bridge_channel->features->interval_hooks, hook)) {
2302                         /* Interval hook is already removed from the bridge_channel. */
2303                         ao2_ref(hook, -1);
2304                         continue;
2305                 }
2306                 ao2_ref(hook, -1);
2307
2308                 if (interval < 0) {
2309                         ast_debug(1, "Removed interval hook %p from %p(%s)\n",
2310                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
2311                         ao2_ref(hook, -1);
2312                         continue;
2313                 }
2314                 if (interval) {
2315                         /* Set new interval for the hook. */
2316                         hook->parms.timer.interval = interval;
2317                 }
2318
2319                 ast_debug(1, "Updating interval hook %p with interval %u on %p(%s)\n",
2320                         hook, hook->parms.timer.interval, bridge_channel,
2321                         ast_channel_name(bridge_channel->chan));
2322
2323                 /* resetting start */
2324                 start = ast_tvnow();
2325
2326                 /*
2327                  * Resetup the interval hook for the next interval.  We may need
2328                  * to skip over any missed intervals because the hook was
2329                  * delayed or took too long.
2330                  */
2331                 execution_time = ast_tvdiff_ms(start, hook->parms.timer.trip_time);
2332                 while (hook->parms.timer.interval < execution_time) {
2333                         execution_time -= hook->parms.timer.interval;
2334                 }
2335                 hook->parms.timer.trip_time = ast_tvadd(start, ast_samp2tv(hook->parms.timer.interval - execution_time, 1000));
2336                 hook->parms.timer.seqno = ast_atomic_fetchadd_int((int *) &bridge_channel->features->interval_sequence, +1);
2337
2338                 if (ast_heap_push(bridge_channel->features->interval_hooks, hook)) {
2339                         /* Could not push the hook back onto the heap. */
2340                         ao2_ref(hook, -1);
2341                 }
2342         }
2343         ast_heap_unlock(bridge_channel->features->interval_hooks);
2344 }
2345
2346 static void bridge_channel_write_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
2347 {
2348         ast_bridge_channel_write_action_data(bridge_channel,
2349                 AST_BRIDGE_ACTION_DTMF_STREAM, dtmf, strlen(dtmf) + 1);
2350 }
2351
2352 /*!
2353  * \brief Internal function that executes a feature on a bridge channel
2354  * \note Neither the bridge nor the bridge_channel locks should be held when entering
2355  * this function.
2356  */
2357 static void bridge_channel_feature(struct ast_bridge_channel *bridge_channel)
2358 {
2359         struct ast_bridge_features *features = bridge_channel->features;
2360         struct ast_bridge_hook *hook = NULL;
2361         char dtmf[MAXIMUM_DTMF_FEATURE_STRING] = "";
2362         size_t dtmf_len = 0;
2363         unsigned int digit_timeout;
2364         RAII_VAR(struct ast_features_general_config *, gen_cfg, NULL, ao2_cleanup);
2365
2366         ast_channel_lock(bridge_channel->chan);
2367         gen_cfg = ast_get_chan_features_general_config(bridge_channel->chan);
2368         if (!gen_cfg) {
2369                 ast_log(LOG_ERROR, "Unable to retrieve features configuration.\n");
2370                 ast_channel_unlock(bridge_channel->chan);
2371                 return;
2372         }
2373         digit_timeout = gen_cfg->featuredigittimeout;
2374         ast_channel_unlock(bridge_channel->chan);
2375
2376         /* The channel is now under our control and we don't really want any begin frames to do our DTMF matching so disable 'em at the core level */
2377         ast_set_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_END_DTMF_ONLY);
2378
2379         /* Wait for DTMF on the channel and put it into a buffer. If the buffer matches any feature hook execute the hook. */
2380         do {
2381                 int res;
2382
2383                 /* If the above timed out simply exit */
2384                 res = ast_waitfordigit(bridge_channel->chan, digit_timeout);
2385                 if (!res) {
2386                         ast_debug(1, "DTMF feature string collection on %p(%s) timed out\n",
2387                                 bridge_channel, ast_channel_name(bridge_channel->chan));
2388                         break;
2389                 }
2390                 if (res < 0) {
2391                         ast_debug(1, "DTMF feature string collection failed on %p(%s) for some reason\n",
2392                                 bridge_channel, ast_channel_name(bridge_channel->chan));
2393                         break;
2394                 }
2395
2396 /* BUGBUG need to record the duration of DTMF digits so when the string is played back, they are reproduced. */
2397                 /* Add the above DTMF into the DTMF string so we can do our matching */
2398                 dtmf[dtmf_len++] = res;
2399                 ast_debug(1, "DTMF feature string on %p(%s) is now '%s'\n",
2400                         bridge_channel, ast_channel_name(bridge_channel->chan), dtmf);
2401
2402                 /* See if a DTMF feature hook matches or can match */
2403                 hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_PARTIAL_KEY);
2404                 if (!hook) {
2405                         ast_debug(1, "No DTMF feature hooks on %p(%s) match '%s'\n",
2406                                 bridge_channel, ast_channel_name(bridge_channel->chan), dtmf);
2407                         break;
2408                 }
2409                 if (strlen(hook->parms.dtmf.code) == dtmf_len) {
2410                         ast_debug(1, "DTMF feature hook %p matched DTMF string '%s' on %p(%s)\n",
2411                                 hook, dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
2412                         break;
2413                 }
2414                 ao2_ref(hook, -1);
2415                 hook = NULL;
2416
2417                 /* Stop if we have reached the maximum length of a DTMF feature string. */
2418         } while (dtmf_len < ARRAY_LEN(dtmf) - 1);
2419
2420         /* Since we are done bringing DTMF in return to using both begin and end frames */
2421         ast_clear_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_END_DTMF_ONLY);
2422
2423         /* If a hook was actually matched execute it on this channel, otherwise stream up the DTMF to the other channels */
2424         if (hook) {
2425                 int failed;
2426
2427                 failed = hook->callback(bridge_channel->bridge, bridge_channel, hook->hook_pvt);
2428                 if (failed) {
2429                         ast_debug(1, "DTMF hook %p is being removed from %p(%s)\n",
2430                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
2431                         ao2_unlink(features->dtmf_hooks, hook);
2432                 }
2433                 ao2_ref(hook, -1);
2434
2435                 /*
2436                  * If we are handing the channel off to an external hook for
2437                  * ownership, we are not guaranteed what kind of state it will
2438                  * come back in.  If the channel hungup, we need to detect that
2439                  * here if the hook did not already change the state.
2440                  */
2441                 if (bridge_channel->chan && ast_check_hangup_locked(bridge_channel->chan)) {
2442                         bridge_handle_hangup(bridge_channel);
2443                 }
2444         } else if (features->dtmf_passthrough) {
2445                 bridge_channel_write_dtmf_stream(bridge_channel, dtmf);
2446         }
2447 }
2448
2449 static void bridge_channel_talking(struct ast_bridge_channel *bridge_channel, int talking)
2450 {
2451         struct ast_bridge_features *features = bridge_channel->features;
2452
2453         if (features->talker_cb) {
2454                 features->talker_cb(bridge_channel, features->talker_pvt_data, talking);
2455         }
2456 }
2457
2458 /*! \brief Internal function that plays back DTMF on a bridge channel */
2459 static void bridge_channel_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
2460 {
2461         ast_debug(1, "Playing DTMF stream '%s' out to %p(%s)\n",
2462                 dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
2463         ast_dtmf_stream(bridge_channel->chan, NULL, dtmf, 0, 0);
2464 }
2465
2466 struct blind_transfer_data {
2467         char exten[AST_MAX_EXTENSION];
2468         char context[AST_MAX_CONTEXT];
2469 };
2470
2471 static void bridge_channel_blind_transfer(struct ast_bridge_channel *bridge_channel,
2472                 struct blind_transfer_data *blind_data)
2473 {
2474         ast_async_goto(bridge_channel->chan, blind_data->context, blind_data->exten, 1);
2475         bridge_handle_hangup(bridge_channel);
2476 }
2477
2478 static void after_bridge_move_channel(struct ast_channel *chan_bridged, void *data)
2479 {
2480         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
2481
2482         if (ast_channel_move(chan_target, chan_bridged)) {
2483                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
2484         }
2485 }
2486
2487 static void after_bridge_move_channel_fail(enum ast_after_bridge_cb_reason reason, void *data)
2488 {
2489         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
2490
2491         ast_log(LOG_WARNING, "Unable to complete transfer: %s\n",
2492                 ast_after_bridge_cb_reason_string(reason));
2493         ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
2494 }
2495
2496 static void bridge_channel_attended_transfer(struct ast_bridge_channel *bridge_channel,
2497                 const char *target_chan_name)
2498 {
2499         RAII_VAR(struct ast_channel *, chan_target, NULL, ao2_cleanup);
2500         RAII_VAR(struct ast_channel *, chan_bridged, NULL, ao2_cleanup);
2501
2502         chan_target = ast_channel_get_by_name(target_chan_name);
2503         if (!chan_target) {
2504                 /* Dang, it disappeared somehow */
2505                 bridge_handle_hangup(bridge_channel);
2506                 return;
2507         }
2508
2509         ast_bridge_channel_lock(bridge_channel);
2510         chan_bridged = bridge_channel->chan;
2511         ast_assert(chan_bridged != NULL);
2512         ao2_ref(chan_bridged, +1);
2513         ast_bridge_channel_unlock(bridge_channel);
2514
2515         if (ast_after_bridge_callback_set(chan_bridged, after_bridge_move_channel,
2516                 after_bridge_move_channel_fail, ast_channel_ref(chan_target))) {
2517                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
2518
2519                 /* Release the ref we tried to pass to ast_after_bridge_callback_set(). */
2520                 ast_channel_unref(chan_target);
2521         }
2522         bridge_handle_hangup(bridge_channel);
2523 }
2524
2525 /*!
2526  * \internal
2527  * \brief Handle bridge channel bridge action frame.
2528  * \since 12.0.0
2529  *
2530  * \param bridge_channel Channel to execute the action on.
2531  * \param action What to do.
2532  *
2533  * \return Nothing
2534  */
2535 static void bridge_channel_handle_action(struct ast_bridge_channel *bridge_channel, struct ast_frame *action)
2536 {
2537         switch (action->subclass.integer) {
2538         case AST_BRIDGE_ACTION_INTERVAL:
2539                 bridge_channel_suspend(bridge_channel);
2540                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2541                 bridge_channel_interval(bridge_channel);
2542                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2543                 bridge_channel_unsuspend(bridge_channel);
2544                 break;
2545         case AST_BRIDGE_ACTION_FEATURE:
2546                 bridge_channel_suspend(bridge_channel);
2547                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2548                 bridge_channel_feature(bridge_channel);
2549                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2550                 bridge_channel_unsuspend(bridge_channel);
2551                 break;
2552         case AST_BRIDGE_ACTION_DTMF_STREAM:
2553                 bridge_channel_suspend(bridge_channel);
2554                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2555                 bridge_channel_dtmf_stream(bridge_channel, action->data.ptr);
2556                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2557                 bridge_channel_unsuspend(bridge_channel);
2558                 break;
2559         case AST_BRIDGE_ACTION_TALKING_START:
2560         case AST_BRIDGE_ACTION_TALKING_STOP:
2561                 bridge_channel_talking(bridge_channel,
2562                         action->subclass.integer == AST_BRIDGE_ACTION_TALKING_START);
2563                 break;
2564         case AST_BRIDGE_ACTION_PLAY_FILE:
2565                 bridge_channel_suspend(bridge_channel);
2566                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2567                 bridge_channel_playfile(bridge_channel, action->data.ptr);
2568                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2569                 bridge_channel_unsuspend(bridge_channel);
2570                 break;
2571         case AST_BRIDGE_ACTION_RUN_APP:
2572                 bridge_channel_suspend(bridge_channel);
2573                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2574                 bridge_channel_run_app(bridge_channel, action->data.ptr);
2575                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2576                 bridge_channel_unsuspend(bridge_channel);
2577                 break;
2578         case AST_BRIDGE_ACTION_CALLBACK:
2579                 bridge_channel_suspend(bridge_channel);
2580                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2581                 bridge_channel_do_callback(bridge_channel, action->data.ptr);
2582                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2583                 bridge_channel_unsuspend(bridge_channel);
2584                 break;
2585         case AST_BRIDGE_ACTION_PARK:
2586                 bridge_channel_suspend(bridge_channel);
2587                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2588                 bridge_channel_park(bridge_channel, action->data.ptr);
2589                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2590                 bridge_channel_unsuspend(bridge_channel);
2591                 break;
2592         case AST_BRIDGE_ACTION_BLIND_TRANSFER:
2593                 bridge_channel_blind_transfer(bridge_channel, action->data.ptr);
2594                 break;
2595         case AST_BRIDGE_ACTION_ATTENDED_TRANSFER:
2596                 bridge_channel_attended_transfer(bridge_channel, action->data.ptr);
2597                 break;
2598         default:
2599                 break;
2600         }
2601 }
2602
2603 /*!
2604  * \internal
2605  * \brief Handle bridge channel control frame action.
2606  * \since 12.0.0
2607  *
2608  * \param bridge_channel Channel to execute the control frame action on.
2609  * \param fr Control frame to handle.
2610  *
2611  * \return Nothing
2612  */
2613 static void bridge_channel_handle_control(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
2614 {
2615         struct ast_channel *chan;
2616         struct ast_option_header *aoh;
2617         int is_caller;
2618         int intercept_failed;
2619
2620         chan = bridge_channel->chan;
2621         switch (fr->subclass.integer) {
2622         case AST_CONTROL_REDIRECTING:
2623                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
2624                 bridge_channel_suspend(bridge_channel);
2625                 intercept_failed = ast_channel_redirecting_sub(NULL, chan, fr, 1)
2626                         && ast_channel_redirecting_macro(NULL, chan, fr, is_caller, 1);
2627                 bridge_channel_unsuspend(bridge_channel);
2628                 if (intercept_failed) {
2629                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2630                 }
2631                 break;
2632         case AST_CONTROL_CONNECTED_LINE:
2633                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
2634                 bridge_channel_suspend(bridge_channel);
2635                 intercept_failed = ast_channel_connected_line_sub(NULL, chan, fr, 1)
2636                         && ast_channel_connected_line_macro(NULL, chan, fr, is_caller, 1);
2637                 bridge_channel_unsuspend(bridge_channel);
2638                 if (intercept_failed) {
2639                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2640                 }
2641                 break;
2642         case AST_CONTROL_HOLD:
2643         case AST_CONTROL_UNHOLD:
2644 /*
2645  * BUGBUG bridge_channels should remember sending/receiving an outstanding HOLD to/from the bridge
2646  *
2647  * When the sending channel is pulled from the bridge it needs to write into the bridge an UNHOLD before being pulled.
2648  * When the receiving channel is pulled from the bridge it needs to generate its own UNHOLD.
2649  * Something similar needs to be done for DTMF begin/end.
2650  */
2651         case AST_CONTROL_VIDUPDATE:
2652         case AST_CONTROL_SRCUPDATE:
2653         case AST_CONTROL_SRCCHANGE:
2654         case AST_CONTROL_T38_PARAMETERS:
2655 /* BUGBUG may have to do something with a jitter buffer for these. */
2656                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2657                 break;
2658         case AST_CONTROL_OPTION:
2659                 /*
2660                  * Forward option Requests, but only ones we know are safe These
2661                  * are ONLY sent by chan_iax2 and I'm not convinced that they
2662                  * are useful. I haven't deleted them entirely because I just am
2663                  * not sure of the ramifications of removing them.
2664                  */
2665                 aoh = fr->data.ptr;
2666                 if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
2667                         switch (ntohs(aoh->option)) {
2668                         case AST_OPTION_TONE_VERIFY:
2669                         case AST_OPTION_TDD:
2670                         case AST_OPTION_RELAXDTMF:
2671                         case AST_OPTION_AUDIO_MODE:
2672                         case AST_OPTION_DIGIT_DETECT:
2673                         case AST_OPTION_FAX_DETECT:
2674                                 ast_channel_setoption(chan, ntohs(aoh->option), aoh->data,
2675                                         fr->datalen - sizeof(*aoh), 0);
2676                                 break;
2677                         default:
2678                                 break;
2679                         }
2680                 }
2681                 break;
2682         case AST_CONTROL_ANSWER:
2683                 if (ast_channel_state(chan) != AST_STATE_UP) {
2684                         ast_answer(chan);
2685                 } else {
2686                         ast_indicate(chan, -1);
2687                 }
2688                 break;
2689         default:
2690                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2691                 break;
2692         }
2693 }
2694
2695 /*!
2696  * \internal
2697  * \brief Handle bridge channel write frame to channel.
2698  * \since 12.0.0
2699  *
2700  * \param bridge_channel Channel to write outgoing frame.
2701  *
2702  * \return Nothing
2703  */
2704 static void bridge_channel_handle_write(struct ast_bridge_channel *bridge_channel)
2705 {
2706         struct ast_frame *fr;
2707         char nudge;
2708
2709         ast_bridge_channel_lock(bridge_channel);
2710         if (read(bridge_channel->alert_pipe[0], &nudge, sizeof(nudge)) < 0) {
2711                 if (errno != EINTR && errno != EAGAIN) {
2712                         ast_log(LOG_WARNING, "read() failed for alert pipe on %p(%s): %s\n",
2713                                 bridge_channel, ast_channel_name(bridge_channel->chan), strerror(errno));
2714                 }
2715         }
2716         fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list);
2717         ast_bridge_channel_unlock(bridge_channel);
2718         if (!fr) {
2719                 return;
2720         }
2721         switch (fr->frametype) {
2722         case AST_FRAME_BRIDGE_ACTION:
2723                 bridge_channel_handle_action(bridge_channel, fr);
2724                 break;
2725         case AST_FRAME_CONTROL:
2726                 bridge_channel_handle_control(bridge_channel, fr);
2727                 break;
2728         case AST_FRAME_NULL:
2729                 break;
2730         default:
2731                 /* Write the frame to the channel. */
2732                 bridge_channel->activity = AST_BRIDGE_CHANNEL_THREAD_SIMPLE;
2733                 ast_write(bridge_channel->chan, fr);
2734                 break;
2735         }
2736         ast_frfree(fr);
2737 }
2738
2739 /*!
2740  * \internal
2741  * \brief Handle bridge channel interval expiration.
2742  * \since 12.0.0
2743  *
2744  * \param bridge_channel Channel to check interval on.
2745  *
2746  * \return Nothing
2747  */
2748 static void bridge_channel_handle_interval(struct ast_bridge_channel *bridge_channel)
2749 {
2750         struct ast_timer *interval_timer;
2751
2752         interval_timer = bridge_channel->features->interval_timer;
2753         if (interval_timer) {
2754                 if (ast_wait_for_input(ast_timer_fd(interval_timer), 0) == 1) {
2755                         ast_timer_ack(interval_timer, 1);
2756                         if (bridge_channel_interval_ready(bridge_channel)) {
2757 /* BUGBUG since this is now only run by the channel thread, there is no need to queue the action once this intervals become a first class wait item in bridge_channel_wait(). */
2758                                 struct ast_frame interval_action = {
2759                                         .frametype = AST_FRAME_BRIDGE_ACTION,
2760                                         .subclass.integer = AST_BRIDGE_ACTION_INTERVAL,
2761                                 };
2762
2763                                 ast_bridge_channel_queue_frame(bridge_channel, &interval_action);
2764                         }
2765                 }
2766         }
2767 }
2768
2769 /*!
2770  * \internal
2771  * \brief Wait for something to happen on the bridge channel and handle it.
2772  * \since 12.0.0
2773  *
2774  * \param bridge_channel Channel to wait.
2775  *
2776  * \note Each channel does writing/reading in their own thread.
2777  *
2778  * \return Nothing
2779  */
2780 static void bridge_channel_wait(struct ast_bridge_channel *bridge_channel)
2781 {
2782         int ms = -1;
2783         int outfd;
2784         struct ast_channel *chan;
2785
2786         /* Wait for data to either come from the channel or us to be signaled */
2787         ast_bridge_channel_lock(bridge_channel);
2788         if (bridge_channel->state != AST_BRIDGE_CHANNEL_STATE_WAIT) {
2789         } else if (bridge_channel->suspended) {
2790 /* BUGBUG the external party use of suspended will go away as will these references because this is the bridge channel thread */
2791                 ast_debug(1, "Bridge %s: %p(%s) is going into a signal wait\n",
2792                         bridge_channel->bridge->uniqueid, bridge_channel,
2793                         ast_channel_name(bridge_channel->chan));
2794                 ast_cond_wait(&bridge_channel->cond, ao2_object_get_lockaddr(bridge_channel));
2795         } else {
2796                 ast_debug(10, "Bridge %s: %p(%s) is going into a waitfor\n",
2797                         bridge_channel->bridge->uniqueid, bridge_channel,
2798                         ast_channel_name(bridge_channel->chan));
2799                 bridge_channel->waiting = 1;
2800                 ast_bridge_channel_unlock(bridge_channel);
2801                 outfd = -1;
2802 /* BUGBUG need to make the next expiring active interval setup ms timeout rather than holding up the chan reads. */
2803                 chan = ast_waitfor_nandfds(&bridge_channel->chan, 1,
2804                         &bridge_channel->alert_pipe[0], 1, NULL, &outfd, &ms);
2805                 bridge_channel->waiting = 0;
2806                 if (ast_channel_softhangup_internal_flag(bridge_channel->chan) & AST_SOFTHANGUP_UNBRIDGE) {
2807                         ast_channel_clear_softhangup(bridge_channel->chan, AST_SOFTHANGUP_UNBRIDGE);
2808                         ast_bridge_channel_lock_bridge(bridge_channel);
2809                         bridge_channel->bridge->reconfigured = 1;
2810                         bridge_reconfigured(bridge_channel->bridge);
2811                         ast_bridge_unlock(bridge_channel->bridge);
2812                 }
2813                 ast_bridge_channel_lock(bridge_channel);
2814                 bridge_channel->activity = AST_BRIDGE_CHANNEL_THREAD_FRAME;
2815                 ast_bridge_channel_unlock(bridge_channel);
2816                 if (!bridge_channel->suspended
2817                         && bridge_channel->state == AST_BRIDGE_CHANNEL_STATE_WAIT) {
2818                         if (chan) {
2819                                 bridge_channel_handle_interval(bridge_channel);
2820                                 bridge_handle_trip(bridge_channel);
2821                         } else if (-1 < outfd) {
2822                                 bridge_channel_handle_write(bridge_channel);
2823                         }
2824                 }
2825                 bridge_channel->activity = AST_BRIDGE_CHANNEL_THREAD_IDLE;
2826                 return;
2827         }
2828         ast_bridge_channel_unlock(bridge_channel);
2829 }
2830
2831 /*!
2832  * \internal
2833  * \brief Handle bridge channel join event.
2834  * \since 12.0.0
2835  *
2836  * \param bridge_channel Which channel is joining.
2837  *
2838  * \return Nothing
2839  */
2840 static void bridge_channel_handle_join(struct ast_bridge_channel *bridge_channel)
2841 {
2842         struct ast_bridge_features *features = bridge_channel->features;
2843         struct ast_bridge_hook *hook;
2844         struct ao2_iterator iter;
2845
2846         /* Run any join hooks. */
2847         iter = ao2_iterator_init(features->join_hooks, AO2_ITERATOR_UNLINK);
2848         hook = ao2_iterator_next(&iter);
2849         if (hook) {
2850                 bridge_channel_suspend(bridge_channel);
2851                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2852                 do {
2853                         hook->callback(bridge_channel->bridge, bridge_channel, hook->hook_pvt);
2854                         ao2_ref(hook, -1);
2855                 } while ((hook = ao2_iterator_next(&iter)));
2856                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2857                 bridge_channel_unsuspend(bridge_channel);
2858         }
2859         ao2_iterator_destroy(&iter);
2860 }
2861
2862 /*!
2863  * \internal
2864  * \brief Handle bridge channel leave event.
2865  * \since 12.0.0
2866  *
2867  * \param bridge_channel Which channel is leaving.
2868  *
2869  * \return Nothing
2870  */
2871 static void bridge_channel_handle_leave(struct ast_bridge_channel *bridge_channel)
2872 {
2873         struct ast_bridge_features *features = bridge_channel->features;
2874         struct ast_bridge_hook *hook;
2875         struct ao2_iterator iter;
2876
2877         /* Run any leave hooks. */
2878         iter = ao2_iterator_init(features->leave_hooks, AO2_ITERATOR_UNLINK);
2879         hook = ao2_iterator_next(&iter);
2880         if (hook) {
2881                 bridge_channel_suspend(bridge_channel);
2882                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2883                 do {
2884                         hook->callback(bridge_channel->bridge, bridge_channel, hook->hook_pvt);
2885                         ao2_ref(hook, -1);
2886                 } while ((hook = ao2_iterator_next(&iter)));
2887                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2888                 bridge_channel_unsuspend(bridge_channel);
2889         }
2890         ao2_iterator_destroy(&iter);
2891 }
2892
2893 /*! \brief Join a channel to a bridge and handle anything the bridge may want us to do */
2894 static void bridge_channel_join(struct ast_bridge_channel *bridge_channel)
2895 {
2896         ast_format_copy(&bridge_channel->read_format, ast_channel_readformat(bridge_channel->chan));
2897         ast_format_copy(&bridge_channel->write_format, ast_channel_writeformat(bridge_channel->chan));
2898
2899         ast_debug(1, "Bridge %s: %p(%s) is joining\n",
2900                 bridge_channel->bridge->uniqueid,
2901                 bridge_channel, ast_channel_name(bridge_channel->chan));
2902
2903         /*
2904          * Get "in the bridge" before pushing the channel for any
2905          * masquerades on the channel to happen before bridging.
2906          */
2907         ast_channel_lock(bridge_channel->chan);
2908         ast_channel_internal_bridge_set(bridge_channel->chan, bridge_channel->bridge);
2909         ast_channel_unlock(bridge_channel->chan);
2910
2911         /* Add the jitterbuffer if the channel requires it */
2912         ast_jb_enable_for_channel(bridge_channel->chan);
2913
2914         /*
2915          * Directly locking the bridge is safe here because nobody else
2916          * knows about this bridge_channel yet.
2917          */
2918         ast_bridge_lock(bridge_channel->bridge);
2919
2920         if (!bridge_channel->bridge->callid) {
2921                 bridge_channel->bridge->callid = ast_read_threadstorage_callid();
2922         }
2923
2924         if (bridge_channel_push(bridge_channel)) {
2925                 ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_HANGUP);
2926         }
2927         bridge_reconfigured(bridge_channel->bridge);
2928
2929         if (bridge_channel->state == AST_BRIDGE_CHANNEL_STATE_WAIT) {
2930                 /*
2931                  * Indicate a source change since this channel is entering the
2932                  * bridge system only if the bridge technology is not MULTIMIX
2933                  * capable.  The MULTIMIX technology has already done it.
2934                  */
2935                 if (!(bridge_channel->bridge->technology->capabilities
2936                         & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
2937                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2938                 }
2939
2940                 ast_bridge_unlock(bridge_channel->bridge);
2941                 bridge_channel_handle_join(bridge_channel);
2942                 while (bridge_channel->state == AST_BRIDGE_CHANNEL_STATE_WAIT) {
2943                         /* Wait for something to do. */
2944                         bridge_channel_wait(bridge_channel);
2945                 }
2946                 bridge_channel_handle_leave(bridge_channel);
2947                 ast_bridge_channel_lock_bridge(bridge_channel);
2948         }
2949
2950         bridge_channel_pull(bridge_channel);
2951         bridge_reconfigured(bridge_channel->bridge);
2952
2953         ast_bridge_unlock(bridge_channel->bridge);
2954
2955         /* Indicate a source change since this channel is leaving the bridge system. */
2956         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2957
2958 /* BUGBUG Revisit in regards to moving channels between bridges and local channel optimization. */
2959 /* BUGBUG This is where outgoing HOLD/UNHOLD memory should write UNHOLD to channel. */
2960         /* Complete any partial DTMF digit before exiting the bridge. */
2961         if (ast_channel_sending_dtmf_digit(bridge_channel->chan)) {
2962                 ast_bridge_end_dtmf(bridge_channel->chan,
2963                         ast_channel_sending_dtmf_digit(bridge_channel->chan),
2964                         ast_channel_sending_dtmf_tv(bridge_channel->chan), "bridge end");
2965         }
2966
2967         /*
2968          * Wait for any dual redirect to complete.
2969          *
2970          * Must be done while "still in the bridge" for ast_async_goto()
2971          * to work right.
2972          */
2973         while (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT)) {
2974                 sched_yield();
2975         }
2976         ast_channel_lock(bridge_channel->chan);
2977         ast_channel_internal_bridge_set(bridge_channel->chan, NULL);
2978         ast_channel_unlock(bridge_channel->chan);
2979
2980         ast_bridge_channel_restore_formats(bridge_channel);
2981 }
2982
2983 /*!
2984  * \internal
2985  * \brief Close a pipe.
2986  * \since 12.0.0
2987  *
2988  * \param my_pipe What to close.
2989  *
2990  * \return Nothing
2991  */
2992 static void pipe_close(int *my_pipe)
2993 {
2994         if (my_pipe[0] > -1) {
2995                 close(my_pipe[0]);
2996                 my_pipe[0] = -1;
2997         }
2998         if (my_pipe[1] > -1) {
2999                 close(my_pipe[1]);
3000                 my_pipe[1] = -1;
3001         }
3002 }
3003
3004 /*!
3005  * \internal
3006  * \brief Initialize a pipe as non-blocking.
3007  * \since 12.0.0
3008  *
3009  * \param my_pipe What to initialize.
3010  *
3011  * \retval 0 on success.
3012  * \retval -1 on error.
3013  */
3014 static int pipe_init_nonblock(int *my_pipe)
3015 {
3016         int flags;
3017
3018         my_pipe[0] = -1;
3019         my_pipe[1] = -1;
3020         if (pipe(my_pipe)) {
3021                 ast_log(LOG_WARNING, "Can't create pipe! Try increasing max file descriptors with ulimit -n\n");
3022                 return -1;
3023         }
3024         flags = fcntl(my_pipe[0], F_GETFL);
3025         if (fcntl(my_pipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
3026                 ast_log(LOG_WARNING, "Unable to set read pipe nonblocking! (%d: %s)\n",
3027                         errno, strerror(errno));
3028                 return -1;
3029         }
3030         flags = fcntl(my_pipe[1], F_GETFL);
3031         if (fcntl(my_pipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
3032                 ast_log(LOG_WARNING, "Unable to set write pipe nonblocking! (%d: %s)\n",
3033                         errno, strerror(errno));
3034                 return -1;
3035         }
3036         return 0;
3037 }
3038
3039 /* Destroy elements of the bridge channel structure and the bridge channel structure itself */
3040 static void bridge_channel_destroy(void *obj)
3041 {
3042         struct ast_bridge_channel *bridge_channel = obj;
3043         struct ast_frame *fr;
3044
3045         if (bridge_channel->callid) {
3046                 bridge_channel->callid = ast_callid_unref(bridge_channel->callid);
3047         }
3048
3049         if (bridge_channel->bridge) {
3050                 ao2_ref(bridge_channel->bridge, -1);
3051                 bridge_channel->bridge = NULL;
3052         }
3053
3054         /* Flush any unhandled wr_queue frames. */
3055         while ((fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list))) {
3056                 ast_frfree(fr);
3057         }
3058         pipe_close(bridge_channel->alert_pipe);
3059
3060         ast_cond_destroy(&bridge_channel->cond);
3061 }
3062
3063 static struct ast_bridge_channel *bridge_channel_alloc(struct ast_bridge *bridge)
3064 {
3065         struct ast_bridge_channel *bridge_channel;
3066
3067         bridge_channel = ao2_alloc(sizeof(struct ast_bridge_channel), bridge_channel_destroy);
3068         if (!bridge_channel) {
3069                 return NULL;
3070         }
3071         ast_cond_init(&bridge_channel->cond, NULL);
3072         if (pipe_init_nonblock(bridge_channel->alert_pipe)) {
3073                 ao2_ref(bridge_channel, -1);
3074                 return NULL;
3075         }
3076         if (bridge) {
3077                 bridge_channel->bridge = bridge;
3078                 ao2_ref(bridge_channel->bridge, +1);
3079         }
3080
3081         return bridge_channel;
3082 }
3083
3084 struct after_bridge_cb_ds {
3085         /*! Desired callback function. */
3086         ast_after_bridge_cb callback;
3087         /*! After bridge callback will not be called and destroy any resources data may contain. */
3088         ast_after_bridge_cb_failed failed;
3089         /*! Extra data to pass to the callback. */
3090         void *data;
3091 };
3092
3093 /*!
3094  * \internal
3095  * \brief Destroy the after bridge callback datastore.
3096  * \since 12.0.0
3097  *
3098  * \param data After bridge callback data to destroy.
3099  *
3100  * \return Nothing
3101  */
3102 static void after_bridge_cb_destroy(void *data)
3103 {
3104         struct after_bridge_cb_ds *after_bridge = data;
3105
3106         if (after_bridge->failed) {
3107                 after_bridge->failed(AST_AFTER_BRIDGE_CB_REASON_DESTROY, after_bridge->data);
3108                 after_bridge->failed = NULL;
3109         }
3110 }
3111
3112 /*!
3113  * \internal
3114  * \brief Fixup the after bridge callback datastore.
3115  * \since 12.0.0
3116  *
3117  * \param data After bridge callback data to fixup.
3118  * \param old_chan The datastore is moving from this channel.
3119  * \param new_chan The datastore is moving to this channel.
3120  *
3121  * \return Nothing
3122  */
3123 static void after_bridge_cb_fixup(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan)
3124 {
3125         /* There can be only one.  Discard any already on the new channel. */
3126         ast_after_bridge_callback_discard(new_chan, AST_AFTER_BRIDGE_CB_REASON_MASQUERADE);
3127 }
3128
3129 static const struct ast_datastore_info after_bridge_cb_info = {
3130         .type = "after-bridge-cb",
3131         .destroy = after_bridge_cb_destroy,
3132         .chan_fixup = after_bridge_cb_fixup,
3133 };
3134
3135 /*!
3136  * \internal
3137  * \brief Remove channel after the bridge callback and return it.
3138  * \since 12.0.0
3139  *
3140  * \param chan Channel to remove after bridge callback.
3141  *
3142  * \retval datastore on success.
3143  * \retval NULL on error or not found.
3144  */
3145 static struct ast_datastore *after_bridge_cb_remove(struct ast_channel *chan)
3146 {
3147         struct ast_datastore *datastore;
3148
3149         ast_channel_lock(chan);
3150         datastore = ast_channel_datastore_find(chan, &after_bridge_cb_info, NULL);
3151         if (datastore && ast_channel_datastore_remove(chan, datastore)) {
3152                 datastore = NULL;
3153         }
3154         ast_channel_unlock(chan);
3155
3156         return datastore;
3157 }
3158
3159 void ast_after_bridge_callback_discard(struct ast_channel *chan, enum ast_after_bridge_cb_reason reason)
3160 {
3161         struct ast_datastore *datastore;
3162
3163         datastore = after_bridge_cb_remove(chan);
3164         if (datastore) {
3165                 struct after_bridge_cb_ds *after_bridge = datastore->data;
3166
3167                 if (after_bridge && after_bridge->failed) {
3168                         after_bridge->failed(reason, after_bridge->data);
3169                         after_bridge->failed = NULL;
3170                 }
3171                 ast_datastore_free(datastore);
3172         }
3173 }
3174
3175 /*!
3176  * \internal
3177  * \brief Run any after bridge callback if possible.
3178  * \since 12.0.0
3179  *
3180  * \param chan Channel to run after bridge callback.
3181  *
3182  * \return Nothing
3183  */
3184 static void after_bridge_callback_run(struct ast_channel *chan)
3185 {
3186         struct ast_datastore *datastore;
3187         struct after_bridge_cb_ds *after_bridge;
3188
3189         if (ast_check_hangup(chan)) {
3190                 return;
3191         }
3192
3193         /* Get after bridge goto datastore. */
3194         datastore = after_bridge_cb_remove(chan);
3195         if (!datastore) {
3196                 return;
3197         }
3198
3199         after_bridge = datastore->data;
3200         if (after_bridge) {
3201                 after_bridge->failed = NULL;
3202                 after_bridge->callback(chan, after_bridge->data);
3203         }
3204
3205         /* Discard after bridge callback datastore. */
3206         ast_datastore_free(datastore);
3207 }
3208
3209 int ast_after_bridge_callback_set(struct ast_channel *chan, ast_after_bridge_cb callback, ast_after_bridge_cb_failed failed, void *data)
3210 {
3211         struct ast_datastore *datastore;
3212         struct after_bridge_cb_ds *after_bridge;
3213
3214         /* Sanity checks. */
3215         ast_assert(chan != NULL);
3216         if (!chan || !callback) {
3217                 return -1;
3218         }
3219
3220         /* Create a new datastore. */
3221         datastore = ast_datastore_alloc(&after_bridge_cb_info, NULL);
3222         if (!datastore) {
3223                 return -1;
3224         }
3225         after_bridge = ast_calloc(1, sizeof(*after_bridge));
3226         if (!after_bridge) {
3227                 ast_datastore_free(datastore);
3228                 return -1;
3229         }
3230
3231         /* Initialize it. */
3232         after_bridge->callback = callback;
3233         after_bridge->failed = failed;
3234         after_bridge->data = data;
3235         datastore->data = after_bridge;
3236
3237         /* Put it on the channel replacing any existing one. */
3238         ast_channel_lock(chan);
3239         ast_after_bridge_callback_discard(chan, AST_AFTER_BRIDGE_CB_REASON_REPLACED);
3240         ast_channel_datastore_add(chan, datastore);
3241         ast_channel_unlock(chan);
3242
3243         return 0;
3244 }
3245
3246 const char *reason_strings[] = {
3247         [AST_AFTER_BRIDGE_CB_REASON_DESTROY] = "Bridge Destroyed",
3248         [AST_AFTER_BRIDGE_CB_REASON_REPLACED] = "Channel replaced",
3249         [AST_AFTER_BRIDGE_CB_REASON_MASQUERADE] = "Channel masqueraded",
3250         [AST_AFTER_BRIDGE_CB_REASON_DEPART] = "Channel departed",
3251         [AST_AFTER_BRIDGE_CB_REASON_REMOVED] = "Channel removed",
3252 };
3253
3254 const char *ast_after_bridge_cb_reason_string(enum ast_after_bridge_cb_reason reason)
3255 {
3256         if (reason < AST_AFTER_BRIDGE_CB_REASON_DESTROY || reason > AST_AFTER_BRIDGE_CB_REASON_REMOVED) {
3257                 return "Unknown";
3258         }
3259
3260         return reason_strings[reason];
3261 }
3262
3263 struct after_bridge_goto_ds {
3264         /*! Goto string that can be parsed by ast_parseable_goto(). */
3265         const char *parseable_goto;
3266         /*! Specific goto context or default context for parseable_goto. */
3267         const char *context;
3268         /*! Specific goto exten or default exten for parseable_goto. */
3269         const char *exten;
3270         /*! Specific goto priority or default priority for parseable_goto. */
3271         int priority;
3272         /*! TRUE if the peer should run the h exten. */
3273         unsigned int run_h_exten:1;
3274         /*! Specific goto location */
3275         unsigned int specific:1;
3276 };
3277
3278 /*!
3279  * \internal
3280  * \brief Destroy the after bridge goto datastore.
3281  * \since 12.0.0
3282  *
3283  * \param data After bridge goto data to destroy.
3284  *
3285  * \return Nothing
3286  */
3287 static void after_bridge_goto_destroy(void *data)
3288 {
3289         struct after_bridge_goto_ds *after_bridge = data;
3290
3291         ast_free((char *) after_bridge->parseable_goto);
3292         ast_free((char *) after_bridge->context);
3293         ast_free((char *) after_bridge->exten);
3294 }
3295
3296 /*!
3297  * \internal
3298  * \brief Fixup the after bridge goto datastore.
3299  * \since 12.0.0
3300  *
3301  * \param data After bridge goto data to fixup.
3302  * \param old_chan The datastore is moving from this channel.
3303  * \param new_chan The datastore is moving to this channel.
3304  *
3305  * \return Nothing
3306  */
3307 static void after_bridge_goto_fixup(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan)
3308 {
3309         /* There can be only one.  Discard any already on the new channel. */
3310         ast_after_bridge_goto_discard(new_chan);
3311 }
3312
3313 static const struct ast_datastore_info after_bridge_goto_info = {
3314         .type = "after-bridge-goto",
3315         .destroy = after_bridge_goto_destroy,
3316         .chan_fixup = after_bridge_goto_fixup,
3317 };
3318
3319 /*!
3320  * \internal
3321  * \brief Remove channel goto location after the bridge and return it.
3322  * \since 12.0.0
3323  *
3324  * \param chan Channel to remove after bridge goto location.
3325  *
3326  * \retval datastore on success.
3327  * \retval NULL on error or not found.
3328  */
3329 static struct ast_datastore *after_bridge_goto_remove(struct ast_channel *chan)
3330 {
3331         struct ast_datastore *datastore;
3332
3333         ast_channel_lock(chan);
3334         datastore = ast_channel_datastore_find(chan, &after_bridge_goto_info, NULL);
3335         if (datastore && ast_channel_datastore_remove(chan, datastore)) {
3336                 datastore = NULL;
3337         }
3338         ast_channel_unlock(chan);
3339
3340         return datastore;
3341 }
3342
3343 void ast_after_bridge_goto_discard(struct ast_channel *chan)
3344 {
3345         struct ast_datastore *datastore;
3346
3347         datastore = after_bridge_goto_remove(chan);
3348         if (datastore) {
3349                 ast_datastore_free(datastore);
3350         }
3351 }
3352
3353 int ast_after_bridge_goto_setup(struct ast_channel *chan)
3354 {
3355         struct ast_datastore *datastore;
3356         struct after_bridge_goto_ds *after_bridge;
3357         int goto_failed = -1;
3358
3359         /* Determine if we are going to setup a dialplan location and where. */
3360         if (ast_channel_softhangup_internal_flag(chan) & AST_SOFTHANGUP_ASYNCGOTO) {
3361                 /* An async goto has already setup a location. */
3362                 ast_channel_clear_softhangup(chan, AST_SOFTHANGUP_ASYNCGOTO);
3363                 if (!ast_check_hangup(chan)) {
3364                         goto_failed = 0;
3365                 }
3366                 return goto_failed;
3367         }
3368
3369         /* Get after bridge goto datastore. */
3370         datastore = after_bridge_goto_remove(chan);
3371         if (!datastore) {
3372                 return goto_failed;
3373         }
3374
3375         after_bridge = datastore->data;
3376         if (after_bridge->run_h_exten) {
3377                 if (ast_exists_extension(chan, after_bridge->context, "h", 1,
3378                         S_COR(ast_channel_caller(chan)->id.number.valid,
3379                                 ast_channel_caller(chan)->id.number.str, NULL))) {
3380                         ast_debug(1, "Running after bridge goto h exten %s,h,1\n",
3381                                 ast_channel_context(chan));
3382                         ast_pbx_h_exten_run(chan, after_bridge->context);
3383                 }
3384         } else if (!ast_check_hangup(chan)) {
3385                 if (after_bridge->specific) {
3386                         goto_failed = ast_explicit_goto(chan, after_bridge->context,
3387                                 after_bridge->exten, after_bridge->priority);
3388                 } else if (!ast_strlen_zero(after_bridge->parseable_goto)) {
3389                         char *context;
3390                         char *exten;
3391                         int priority;
3392
3393                         /* Option F(x) for Bridge(), Dial(), and Queue() */
3394
3395                         /* Save current dialplan location in case of failure. */
3396                         context = ast_strdupa(ast_channel_context(chan));
3397                         exten = ast_strdupa(ast_channel_exten(chan));
3398                         priority = ast_channel_priority(chan);
3399
3400                         /* Set current dialplan position to default dialplan position */
3401                         ast_explicit_goto(chan, after_bridge->context, after_bridge->exten,
3402                                 after_bridge->priority);
3403
3404                         /* Then perform the goto */
3405                         goto_failed = ast_parseable_goto(chan, after_bridge->parseable_goto);
3406                         if (goto_failed) {
3407                                 /* Restore original dialplan location. */
3408                                 ast_channel_context_set(chan, context);
3409                                 ast_channel_exten_set(chan, exten);
3410                                 ast_channel_priority_set(chan, priority);
3411                         }
3412                 } else {
3413                         /* Option F() for Bridge(), Dial(), and Queue() */
3414                         goto_failed = ast_goto_if_exists(chan, after_bridge->context,
3415                                 after_bridge->exten, after_bridge->priority + 1);
3416                 }
3417                 if (!goto_failed) {
3418                         ast_debug(1, "Setup after bridge goto location to %s,%s,%d.\n",
3419                                 ast_channel_context(chan),
3420                                 ast_channel_exten(chan),
3421                                 ast_channel_priority(chan));
3422                 }
3423         }
3424
3425         /* Discard after bridge goto datastore. */
3426         ast_datastore_free(datastore);
3427
3428         return goto_failed;
3429 }
3430
3431 void ast_after_bridge_goto_run(struct ast_channel *chan)
3432 {
3433         int goto_failed;
3434
3435         goto_failed = ast_after_bridge_goto_setup(chan);
3436         if (goto_failed || ast_pbx_run(chan)) {
3437                 ast_hangup(chan);
3438         }
3439 }
3440
3441 /*!
3442  * \internal
3443  * \brief Set after bridge goto location of channel.
3444  * \since 12.0.0
3445  *
3446  * \param chan Channel to setup after bridge goto location.
3447  * \param run_h_exten TRUE if the h exten should be run.
3448  * \param specific TRUE if the context/exten/priority is exactly specified.
3449  * \param context Context to goto after bridge.
3450  * \param exten Exten to goto after bridge. (Could be NULL if run_h_exten)
3451  * \param priority Priority to goto after bridge.
3452  * \param parseable_goto User specified goto string. (Could be NULL)
3453  *
3454  * \details Add a channel datastore to setup the goto location
3455  * when the channel leaves the bridge and run a PBX from there.
3456  *
3457  * If run_h_exten then execute the h exten found in the given context.
3458  * Else if specific then goto the given context/exten/priority.
3459  * Else if parseable_goto then use the given context/exten/priority
3460  *   as the relative position for the parseable_goto.
3461  * Else goto the given context/exten/priority+1.
3462  *
3463  * \return Nothing
3464  */
3465 static void __after_bridge_set_goto(struct ast_channel *chan, int run_h_exten, int specific, const char *context, const char *exten, int priority, const char *parseable_goto)
3466 {
3467         struct ast_datastore *datastore;
3468         struct after_bridge_goto_ds *after_bridge;
3469
3470         /* Sanity checks. */
3471         ast_assert(chan != NULL);
3472         if (!chan) {
3473                 return;
3474         }
3475         if (run_h_exten) {
3476                 ast_assert(run_h_exten && context);
3477                 if (!context) {
3478                         return;
3479                 }
3480         } else {
3481                 ast_assert(context && exten && 0 < priority);
3482                 if (!context || !exten || priority < 1) {
3483                         return;
3484                 }
3485         }
3486
3487         /* Create a new datastore. */
3488         datastore = ast_datastore_alloc(&after_bridge_goto_info, NULL);
3489         if (!datastore) {
3490                 return;
3491         }
3492         after_bridge = ast_calloc(1, sizeof(*after_bridge));
3493         if (!after_bridge) {
3494                 ast_datastore_free(datastore);
3495                 return;
3496         }
3497
3498         /* Initialize it. */
3499         after_bridge->parseable_goto = ast_strdup(parseable_goto);
3500         after_bridge->context = ast_strdup(context);
3501         after_bridge->exten = ast_strdup(exten);
3502         after_bridge->priority = priority;
3503         after_bridge->run_h_exten = run_h_exten ? 1 : 0;
3504         after_bridge->specific = specific ? 1 : 0;
3505         datastore->data = after_bridge;
3506         if ((parseable_goto && !after_bridge->parseable_goto)
3507                 || (context && !after_bridge->context)
3508                 || (exten && !after_bridge->exten)) {
3509                 ast_datastore_free(datastore);
3510                 return;
3511         }
3512
3513         /* Put it on the channel replacing any existing one. */
3514         ast_channel_lock(chan);
3515         ast_after_bridge_goto_discard(chan);
3516         ast_channel_datastore_add(chan, datastore);
3517         ast_channel_unlock(chan);
3518 }
3519
3520 void ast_after_bridge_set_goto(struct ast_channel *chan, const char *context, const char *exten, int priority)
3521 {
3522         __after_bridge_set_goto(chan, 0, 1, context, exten, priority, NULL);
3523 }
3524
3525 void ast_after_bridge_set_h(struct ast_channel *chan, const char *context)
3526 {
3527         __after_bridge_set_goto(chan, 1, 0, context, NULL, 1, NULL);
3528 }
3529
3530 void ast_after_bridge_set_go_on(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *parseable_goto)
3531 {
3532         char *p_goto;
3533
3534         if (!ast_strlen_zero(parseable_goto)) {
3535                 p_goto = ast_strdupa(parseable_goto);
3536                 ast_replace_subargument_delimiter(p_goto);
3537         } else {
3538                 p_goto = NULL;
3539         }
3540         __after_bridge_set_goto(chan, 0, 0, context, exten, priority, p_goto);
3541 }
3542
3543 void ast_bridge_notify_masquerade(struct ast_channel *chan)
3544 {
3545         struct ast_bridge_channel *bridge_channel;
3546         struct ast_bridge *bridge;
3547
3548         /* Safely get the bridge_channel pointer for the chan. */
3549         ast_channel_lock(chan);
3550         bridge_channel = ast_channel_get_bridge_channel(chan);
3551         ast_channel_unlock(chan);
3552         if (!bridge_channel) {
3553                 /* Not in a bridge */
3554                 return;
3555         }
3556
3557         ast_bridge_channel_lock_bridge(bridge_channel);
3558         bridge = bridge_channel->bridge;
3559         if (bridge_channel == find_bridge_channel(bridge, chan)) {
3560 /* BUGBUG this needs more work.  The channels need to be made compatible again if the formats change. The bridge_channel thread needs to monitor for this case. */
3561                 /* The channel we want to notify is still in a bridge. */
3562                 bridge->v_table->notify_masquerade(bridge, bridge_channel);
3563                 bridge_reconfigured(bridge);
3564         }
3565         ast_bridge_unlock(bridge);
3566         ao2_ref(bridge_channel, -1);
3567 }
3568
3569 /*
3570  * BUGBUG make ast_bridge_join() require features to be allocated just like ast_bridge_impart() and not expect the struct back.
3571  *
3572  * This change is really going to break ConfBridge.  All other
3573  * users are easily changed.  However, it is needed so the
3574  * bridging code can manipulate features on all channels
3575  * consistently no matter how they joined.
3576  *
3577  * Need to update the features parameter doxygen when this
3578  * change is made to be like ast_bridge_impart().
3579  */
3580 enum ast_bridge_channel_state ast_bridge_join(struct ast_bridge *bridge,
3581         struct ast_channel *chan,
3582         struct ast_channel *swap,
3583         struct ast_bridge_features *features,
3584         struct ast_bridge_tech_optimizations *tech_args,
3585         int pass_reference)
3586 {
3587         struct ast_bridge_channel *bridge_channel;
3588         enum ast_bridge_channel_state state;
3589
3590         bridge_channel = bridge_channel_alloc(bridge);
3591         if (pass_reference) {
3592                 ao2_ref(bridge, -1);
3593         }
3594         if (!bridge_channel) {
3595                 state = AST_BRIDGE_CHANNEL_STATE_HANGUP;
3596                 goto join_exit;
3597         }
3598 /* BUGBUG features cannot be NULL when passed in. When it is changed to allocated we can do like ast_bridge_impart() and allocate one. */
3599         ast_assert(features != NULL);
3600         if (!features) {
3601                 ao2_ref(bridge_channel, -1);
3602                 state = AST_BRIDGE_CHANNEL_STATE_HANGUP;
3603                 goto join_exit;
3604         }
3605         if (tech_args) {
3606                 bridge_channel->tech_args = *tech_args;
3607         }
3608
3609         /* Initialize various other elements of the bridge channel structure that we can't do above */
3610         ast_channel_lock(chan);
3611         ast_channel_internal_bridge_channel_set(chan, bridge_channel);
3612         ast_channel_unlock(chan);
3613         bridge_channel->thread = pthread_self();
3614         bridge_channel->chan = chan;
3615         bridge_channel->swap = swap;
3616         bridge_channel->features = features;
3617
3618         bridge_channel_join(bridge_channel);
3619         state = bridge_channel->state;
3620
3621         /* Cleanup all the data in the bridge channel after it leaves the bridge. */
3622         ast_channel_lock(chan);
3623         ast_channel_internal_bridge_channel_set(chan, NULL);
3624         ast_channel_unlock(chan);
3625         bridge_channel->chan = NULL;
3626         bridge_channel->swap = NULL;
3627         bridge_channel->features = NULL;
3628
3629         ao2_ref(bridge_channel, -1);
3630
3631 join_exit:;
3632 /* BUGBUG this is going to cause problems for DTMF atxfer attended bridge between B & C.  Maybe an ast_bridge_join_internal() that does not do the after bridge goto for this case. */
3633         after_bridge_callback_run(chan);
3634         if (!(ast_channel_softhangup_internal_flag(chan) & AST_SOFTHANGUP_ASYNCGOTO)
3635                 && !ast_after_bridge_goto_setup(chan)) {
3636                 /* Claim the after bridge goto is an async goto destination. */
3637                 ast_channel_lock(chan);
3638                 ast_softhangup_nolock(chan, AST_SOFTHANGUP_ASYNCGOTO);
3639                 ast_channel_unlock(chan);
3640         }
3641         return state;
3642 }
3643
3644 /*! \brief Thread responsible for imparted bridged channels to be departed */
3645 static void *bridge_channel_depart_thread(void *data)
3646 {
3647         struct ast_bridge_channel *bridge_channel = data;
3648
3649         if (bridge_channel->callid) {
3650                 ast_callid_threadassoc_add(bridge_channel->callid);
3651         }
3652
3653         bridge_channel_join(bridge_channel);
3654
3655         /* cleanup */
3656         bridge_channel->swap = NULL;
3657         ast_bridge_features_destroy(bridge_channel->features);
3658         bridge_channel->features = NULL;
3659
3660         ast_after_bridge_callback_discard(bridge_channel->chan, AST_AFTER_BRIDGE_CB_REASON_DEPART);
3661         ast_after_bridge_goto_discard(bridge_channel->chan);
3662
3663         return NULL;
3664 }
3665
3666 /*! \brief Thread responsible for independent imparted bridged channels */
3667 static void *bridge_channel_ind_thread(void *data)
3668 {
3669         struct ast_bridge_channel *bridge_channel = data;
3670         struct ast_channel *chan;
3671
3672         if (bridge_channel->callid) {
3673                 ast_callid_threadassoc_add(bridge_channel->callid);
3674         }
3675
3676         bridge_channel_join(bridge_channel);
3677         chan = bridge_channel->chan;
3678
3679         /* cleanup */
3680         ast_channel_lock(chan);
3681         ast_channel_internal_bridge_channel_set(chan, NULL);
3682         ast_channel_unlock(chan);
3683         bridge_channel->chan = NULL;
3684         bridge_channel->swap = NULL;
3685         ast_bridge_features_destroy(bridge_channel->features);
3686         bridge_channel->features = NULL;
3687
3688         ao2_ref(bridge_channel, -1);
3689
3690         after_bridge_callback_run(chan);
3691         ast_after_bridge_goto_run(chan);
3692         return NULL;
3693 }
3694
3695 int ast_bridge_impart(struct ast_bridge *bridge, struct ast_channel *chan, struct ast_channel *swap, struct ast_bridge_features *features, int independent)
3696 {
3697         int res;
3698         struct ast_bridge_channel *bridge_channel;
3699
3700         /* Supply an empty features structure if the caller did not. */
3701         if (!features) {
3702                 features = ast_bridge_features_new();
3703                 if (!features) {
3704                         return -1;
3705                 }
3706         }
3707
3708         /* Try to allocate a structure for the bridge channel */
3709         bridge_channel = bridge_channel_alloc(bridge);
3710         if (!bridge_channel) {
3711                 ast_bridge_features_destroy(features);
3712                 return -1;
3713         }
3714
3715         /* Setup various parameters */
3716         ast_channel_lock(chan);
3717         ast_channel_internal_bridge_channel_set(chan, bridge_channel);
3718         ast_channel_unlock(chan);
3719         bridge_channel->chan = chan;
3720         bridge_channel->swap = swap;
3721         bridge_channel->features = features;
3722         bridge_channel->depart_wait = independent ? 0 : 1;
3723         bridge_channel->callid = ast_read_threadstorage_callid();
3724
3725         /* Actually create the thread that will handle the channel */
3726         if (independent) {
3727                 /* Independently imparted channels cannot have a PBX. */
3728                 ast_assert(!ast_channel_pbx(chan));
3729
3730                 res = ast_pthread_create_detached(&bridge_channel->thread, NULL,
3731                         bridge_channel_ind_thread, bridge_channel);
3732         } else {
3733                 /* Imparted channels to be departed should not have a PBX either. */
3734                 ast_assert(!ast_channel_pbx(chan));
3735
3736                 res = ast_pthread_create(&bridge_channel->thread, NULL,
3737                         bridge_channel_depart_thread, bridge_channel);
3738         }
3739
3740         if (res) {
3741                 /* cleanup */
3742                 ast_channel_lock(chan);
3743                 ast_channel_internal_bridge_channel_set(chan, NULL);
3744                 ast_channel_unlock(chan);
3745                 bridge_channel->chan = NULL;
3746                 bridge_channel->swap = NULL;
3747                 ast_bridge_features_destroy(bridge_channel->features);
3748                 bridge_channel->features = NULL;
3749
3750                 ao2_ref(bridge_channel, -1);
3751                 return -1;
3752         }
3753
3754         return 0;
3755 }
3756
3757 int ast_bridge_depart(struct ast_channel *chan)
3758 {
3759         struct ast_bridge_channel *bridge_channel;
3760         int departable;
3761
3762         ast_channel_lock(chan);
3763         bridge_channel = ast_channel_internal_bridge_channel(chan);
3764         departable = bridge_channel && bridge_channel->depart_wait;
3765         ast_channel_unlock(chan);
3766         if (!departable) {
3767                 ast_log(LOG_ERROR, "Channel %s cannot be departed.\n",
3768                         ast_channel_name(chan));
3769                 /*
3770                  * Should never happen.  It likely means that
3771                  * ast_bridge_depart() is called by two threads for the same
3772                  * channel, the channel was never imparted to be departed, or it
3773                  * has already been departed.
3774                  */
3775                 ast_assert(0);
3776                 return -1;
3777         }
3778
3779         /*
3780          * We are claiming the reference held by the depart bridge
3781          * channel thread.
3782          */
3783
3784         ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_HANGUP);
3785
3786         /* Wait for the depart thread to die */
3787         ast_debug(1, "Waiting for %p(%s) bridge thread to die.\n",
3788                 bridge_channel, ast_channel_name(bridge_channel->chan));
3789         pthread_join(bridge_channel->thread, NULL);
3790
3791         ast_channel_lock(chan);
3792         ast_channel_internal_bridge_channel_set(chan, NULL);
3793         ast_channel_unlock(chan);
3794
3795         /* We can get rid of the bridge_channel after the depart thread has died. */
3796         ao2_ref(bridge_channel, -1);
3797         return 0;
3798 }
3799
3800 int ast_bridge_remove(struct ast_bridge *bridge, struct ast_channel *chan)
3801 {
3802         struct ast_bridge_channel *bridge_channel;
3803
3804         ast_bridge_lock(bridge);
3805
3806         /* Try to find the channel that we want to remove */
3807         if (!(bridge_channel = find_bridge_channel(bridge, chan))) {
3808                 ast_bridge_unlock(bridge);
3809                 return -1;
3810         }
3811
3812         ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_HANGUP);
3813
3814         ast_bridge_unlock(bridge);
3815
3816         return 0;
3817 }
3818
3819 /*!
3820  * \internal
3821  * \brief Point the bridge_channel to a new bridge.
3822  * \since 12.0.0
3823  *
3824  * \param bridge_channel What is to point to a new bridge.
3825  * \param new_bridge Where the bridge channel should point.
3826  *
3827  * \return Nothing
3828  */
3829 static void bridge_channel_change_bridge(struct ast_bridge_channel *bridge_channel, struct ast_bridge *new_bridge)
3830 {
3831         struct ast_bridge *old_bridge;
3832
3833         ao2_ref(new_bridge, +1);
3834         ast_bridge_channel_lock(bridge_channel);
3835         ast_channel_lock(bridge_channel->chan);
3836         old_bridge = bridge_channel->bridge;
3837         bridge_channel->bridge = new_bridge;
3838         ast_channel_internal_bridge_set(bridge_channel->chan, new_bridge);
3839         ast_channel_unlock(bridge_channel->chan);
3840         ast_bridge_channel_unlock(bridge_channel);
3841         ao2_ref(old_bridge, -1);
3842 }
3843
3844 /*!
3845  * \internal
3846  * \brief Do the merge of two bridges.
3847  * \since 12.0.0
3848  *
3849  * \param dst_bridge Destination bridge of merge.
3850  * \param src_bridge Source bridge of merge.
3851  * \param kick_me Array of channels to kick from the bridges.
3852  * \param num_kick Number of channels in the kick_me array.
3853  *
3854  * \return Nothing
3855  *
3856  * \note The two bridges are assumed already locked.
3857  *
3858  * This moves the channels in src_bridge into the bridge pointed
3859  * to by dst_bridge.
3860  */
3861 static void bridge_merge_do(struct ast_bridge *dst_bridge, struct ast_bridge *src_bridge, struct ast_bridge_channel **kick_me, unsigned int num_kick)
3862 {
3863         struct ast_bridge_channel *bridge_channel;
3864         unsigned int idx;
3865
3866         ast_debug(1, "Merging bridge %s into bridge %s\n",
3867                 src_bridge->uniqueid, dst_bridge->uniqueid);
3868
3869         ast_bridge_publish_merge(dst_bridge, src_bridge);
3870
3871         /*
3872          * Move channels from src_bridge over to dst_bridge.
3873          *
3874          * We must use AST_LIST_TRAVERSE_SAFE_BEGIN() because
3875          * bridge_channel_pull() alters the list we are traversing.
3876          */
3877         AST_LIST_TRAVERSE_SAFE_BEGIN(&src_bridge->channels, bridge_channel, entry) {
3878                 if (bridge_channel->state != AST_BRIDGE_CHANNEL_STATE_WAIT) {
3879                         /*
3880                          * The channel is already leaving let it leave normally because
3881                          * pulling it may delete hooks that should run for this channel.
3882                          */
3883                         continue;
3884                 }
3885                 if (ast_test_flag(&bridge_channel->features->feature_flags,
3886                         AST_BRIDGE_CHANNEL_FLAG_IMMOVABLE)) {
3887                         continue;
3888                 }
3889
3890                 if (kick_me) {
3891                         for (idx = 0; idx < num_kick; ++idx) {
3892                                 if (bridge_channel == kick_me[idx]) {
3893                                         ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_HANGUP);
3894                                         break;
3895                                 }
3896                         }
3897                 }
3898                 bridge_channel_pull(bridge_channel);
3899                 if (bridge_channel->state != AST_BRIDGE_CHANNEL_STATE_WAIT) {
3900                         /*
3901                          * The channel died as a result of being pulled or it was
3902                          * kicked.  Leave it pointing to the original bridge.
3903                          */
3904                         continue;
3905                 }
3906
3907                 /* Point to new bridge.*/
3908                 bridge_channel_change_bridge(bridge_channel, dst_bridge);
3909
3910                 if (bridge_channel_push(bridge_channel)) {
3911                         ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_HANGUP);
3912                 }
3913         }
3914         AST_LIST_TRAVERSE_SAFE_END;
3915
3916         if (kick_me) {
3917                 /*
3918                  * Now we can kick any channels in the dst_bridge without
3919                  * potentially dissolving the bridge.
3920                  */
3921                 for (idx = 0; idx < num_kick; ++idx) {
3922                         bridge_channel = kick_me[idx];
3923                         ast_bridge_channel_lock(bridge_channel);
3924                         if (bridge_channel->state == AST_BRIDGE_CHANNEL_STATE_WAIT) {
3925                                 ast_bridge_change_state_nolock(bridge_channel, AST_BRIDGE_CHANNEL_STATE_HANGUP);
3926                                 bridge_channel_pull(bridge_channel);
3927                         }
3928                         ast_bridge_channel_unlock(bridge_channel);
3929                 }
3930         }
3931
3932         bridge_reconfigured(dst_bridge);
3933         bridge_reconfigured(src_bridge);
3934
3935         ast_debug(1, "Merged bridge %s into bridge %s\n",
3936                 src_bridge->uniqueid, dst_bridge->uniqueid);