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