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