Misc core external attended transfer fixes.
[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
2024         if (ast_channel_move(chan_target, chan_bridged)) {
2025                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
2026         }
2027 }
2028
2029 static void after_bridge_move_channel_fail(enum ast_after_bridge_cb_reason reason, void *data)
2030 {
2031         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
2032
2033         ast_log(LOG_WARNING, "Unable to complete transfer: %s\n",
2034                 ast_after_bridge_cb_reason_string(reason));
2035         ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
2036 }
2037
2038 static void bridge_channel_attended_transfer(struct ast_bridge_channel *bridge_channel,
2039                 const char *target_chan_name)
2040 {
2041         RAII_VAR(struct ast_channel *, chan_target, NULL, ao2_cleanup);
2042         RAII_VAR(struct ast_channel *, chan_bridged, NULL, ao2_cleanup);
2043
2044         chan_target = ast_channel_get_by_name(target_chan_name);
2045         if (!chan_target) {
2046                 /* Dang, it disappeared somehow */
2047                 bridge_handle_hangup(bridge_channel);
2048                 return;
2049         }
2050
2051         ast_bridge_channel_lock(bridge_channel);
2052         chan_bridged = bridge_channel->chan;
2053         ast_assert(chan_bridged != NULL);
2054         ao2_ref(chan_bridged, +1);
2055         ast_bridge_channel_unlock(bridge_channel);
2056
2057         if (ast_after_bridge_callback_set(chan_bridged, after_bridge_move_channel,
2058                 after_bridge_move_channel_fail, ast_channel_ref(chan_target))) {
2059                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
2060
2061                 /* Release the ref we tried to pass to ast_after_bridge_callback_set(). */
2062                 ast_channel_unref(chan_target);
2063         }
2064         bridge_handle_hangup(bridge_channel);
2065 }
2066
2067 /*!
2068  * \internal
2069  * \brief Handle bridge channel bridge action frame.
2070  * \since 12.0.0
2071  *
2072  * \param bridge_channel Channel to execute the action on.
2073  * \param action What to do.
2074  *
2075  * \return Nothing
2076  */
2077 static void bridge_channel_handle_action(struct ast_bridge_channel *bridge_channel, struct ast_frame *action)
2078 {
2079         switch (action->subclass.integer) {
2080         case AST_BRIDGE_ACTION_INTERVAL:
2081                 bridge_channel_suspend(bridge_channel);
2082                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2083                 bridge_channel_interval(bridge_channel);
2084                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2085                 bridge_channel_unsuspend(bridge_channel);
2086                 break;
2087         case AST_BRIDGE_ACTION_FEATURE:
2088                 bridge_channel_suspend(bridge_channel);
2089                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2090                 bridge_channel_feature(bridge_channel);
2091                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2092                 bridge_channel_unsuspend(bridge_channel);
2093                 break;
2094         case AST_BRIDGE_ACTION_DTMF_STREAM:
2095                 bridge_channel_suspend(bridge_channel);
2096                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2097                 bridge_channel_dtmf_stream(bridge_channel, action->data.ptr);
2098                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2099                 bridge_channel_unsuspend(bridge_channel);
2100                 break;
2101         case AST_BRIDGE_ACTION_TALKING_START:
2102         case AST_BRIDGE_ACTION_TALKING_STOP:
2103                 bridge_channel_talking(bridge_channel,
2104                         action->subclass.integer == AST_BRIDGE_ACTION_TALKING_START);
2105                 break;
2106         case AST_BRIDGE_ACTION_PLAY_FILE:
2107                 bridge_channel_suspend(bridge_channel);
2108                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2109                 bridge_channel_playfile(bridge_channel, action->data.ptr);
2110                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2111                 bridge_channel_unsuspend(bridge_channel);
2112                 break;
2113         case AST_BRIDGE_ACTION_PARK:
2114                 bridge_channel_suspend(bridge_channel);
2115                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2116                 bridge_channel_park(bridge_channel, action->data.ptr);
2117                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2118                 bridge_channel_unsuspend(bridge_channel);
2119                 break;
2120         case AST_BRIDGE_ACTION_RUN_APP:
2121                 bridge_channel_suspend(bridge_channel);
2122                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2123                 bridge_channel_run_app(bridge_channel, action->data.ptr);
2124                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2125                 bridge_channel_unsuspend(bridge_channel);
2126                 break;
2127         case AST_BRIDGE_ACTION_BLIND_TRANSFER:
2128                 bridge_channel_blind_transfer(bridge_channel, action->data.ptr);
2129                 break;
2130         case AST_BRIDGE_ACTION_ATTENDED_TRANSFER:
2131                 bridge_channel_attended_transfer(bridge_channel, action->data.ptr);
2132                 break;
2133         default:
2134                 break;
2135         }
2136 }
2137
2138 /*!
2139  * \internal
2140  * \brief Handle bridge channel control frame action.
2141  * \since 12.0.0
2142  *
2143  * \param bridge_channel Channel to execute the control frame action on.
2144  * \param fr Control frame to handle.
2145  *
2146  * \return Nothing
2147  */
2148 static void bridge_channel_handle_control(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
2149 {
2150         struct ast_channel *chan;
2151         struct ast_option_header *aoh;
2152         int is_caller;
2153         int intercept_failed;
2154
2155         chan = bridge_channel->chan;
2156         switch (fr->subclass.integer) {
2157         case AST_CONTROL_REDIRECTING:
2158                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
2159                 bridge_channel_suspend(bridge_channel);
2160                 intercept_failed = ast_channel_redirecting_sub(NULL, chan, fr, 1)
2161                         && ast_channel_redirecting_macro(NULL, chan, fr, is_caller, 1);
2162                 bridge_channel_unsuspend(bridge_channel);
2163                 if (intercept_failed) {
2164                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2165                 }
2166                 break;
2167         case AST_CONTROL_CONNECTED_LINE:
2168                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
2169                 bridge_channel_suspend(bridge_channel);
2170                 intercept_failed = ast_channel_connected_line_sub(NULL, chan, fr, 1)
2171                         && ast_channel_connected_line_macro(NULL, chan, fr, is_caller, 1);
2172                 bridge_channel_unsuspend(bridge_channel);
2173                 if (intercept_failed) {
2174                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2175                 }
2176                 break;
2177         case AST_CONTROL_HOLD:
2178         case AST_CONTROL_UNHOLD:
2179 /*
2180  * BUGBUG bridge_channels should remember sending/receiving an outstanding HOLD to/from the bridge
2181  *
2182  * When the sending channel is pulled from the bridge it needs to write into the bridge an UNHOLD before being pulled.
2183  * When the receiving channel is pulled from the bridge it needs to generate its own UNHOLD.
2184  * Something similar needs to be done for DTMF begin/end.
2185  */
2186         case AST_CONTROL_VIDUPDATE:
2187         case AST_CONTROL_SRCUPDATE:
2188         case AST_CONTROL_SRCCHANGE:
2189         case AST_CONTROL_T38_PARAMETERS:
2190 /* BUGBUG may have to do something with a jitter buffer for these. */
2191                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2192                 break;
2193         case AST_CONTROL_OPTION:
2194                 /*
2195                  * Forward option Requests, but only ones we know are safe These
2196                  * are ONLY sent by chan_iax2 and I'm not convinced that they
2197                  * are useful. I haven't deleted them entirely because I just am
2198                  * not sure of the ramifications of removing them.
2199                  */
2200                 aoh = fr->data.ptr;
2201                 if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
2202                         switch (ntohs(aoh->option)) {
2203                         case AST_OPTION_TONE_VERIFY:
2204                         case AST_OPTION_TDD:
2205                         case AST_OPTION_RELAXDTMF:
2206                         case AST_OPTION_AUDIO_MODE:
2207                         case AST_OPTION_DIGIT_DETECT:
2208                         case AST_OPTION_FAX_DETECT:
2209                                 ast_channel_setoption(chan, ntohs(aoh->option), aoh->data,
2210                                         fr->datalen - sizeof(*aoh), 0);
2211                                 break;
2212                         default:
2213                                 break;
2214                         }
2215                 }
2216                 break;
2217         case AST_CONTROL_ANSWER:
2218                 if (ast_channel_state(chan) != AST_STATE_UP) {
2219                         ast_answer(chan);
2220                 } else {
2221                         ast_indicate(chan, -1);
2222                 }
2223                 break;
2224         default:
2225                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2226                 break;
2227         }
2228 }
2229
2230 /*!
2231  * \internal
2232  * \brief Handle bridge channel write frame to channel.
2233  * \since 12.0.0
2234  *
2235  * \param bridge_channel Channel to write outgoing frame.
2236  *
2237  * \return Nothing
2238  */
2239 static void bridge_channel_handle_write(struct ast_bridge_channel *bridge_channel)
2240 {
2241         struct ast_frame *fr;
2242         char nudge;
2243
2244         ast_bridge_channel_lock(bridge_channel);
2245         if (read(bridge_channel->alert_pipe[0], &nudge, sizeof(nudge)) < 0) {
2246                 if (errno != EINTR && errno != EAGAIN) {
2247                         ast_log(LOG_WARNING, "read() failed for alert pipe on %p(%s): %s\n",
2248                                 bridge_channel, ast_channel_name(bridge_channel->chan), strerror(errno));
2249                 }
2250         }
2251         fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list);
2252         ast_bridge_channel_unlock(bridge_channel);
2253         if (!fr) {
2254                 return;
2255         }
2256         switch (fr->frametype) {
2257         case AST_FRAME_BRIDGE_ACTION:
2258                 bridge_channel_handle_action(bridge_channel, fr);
2259                 break;
2260         case AST_FRAME_CONTROL:
2261                 bridge_channel_handle_control(bridge_channel, fr);
2262                 break;
2263         case AST_FRAME_NULL:
2264                 break;
2265         default:
2266                 /* Write the frame to the channel. */
2267                 bridge_channel->activity = AST_BRIDGE_CHANNEL_THREAD_SIMPLE;
2268                 ast_write(bridge_channel->chan, fr);
2269                 break;
2270         }
2271         ast_frfree(fr);
2272 }
2273
2274 /*!
2275  * \internal
2276  * \brief Handle bridge channel interval expiration.
2277  * \since 12.0.0
2278  *
2279  * \param bridge_channel Channel to check interval on.
2280  *
2281  * \return Nothing
2282  */
2283 static void bridge_channel_handle_interval(struct ast_bridge_channel *bridge_channel)
2284 {
2285         struct ast_timer *interval_timer;
2286
2287         interval_timer = bridge_channel->features->interval_timer;
2288         if (interval_timer) {
2289                 if (ast_wait_for_input(ast_timer_fd(interval_timer), 0) == 1) {
2290                         ast_timer_ack(interval_timer, 1);
2291                         if (bridge_channel_interval_ready(bridge_channel)) {
2292 /* 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(). */
2293                                 struct ast_frame interval_action = {
2294                                         .frametype = AST_FRAME_BRIDGE_ACTION,
2295                                         .subclass.integer = AST_BRIDGE_ACTION_INTERVAL,
2296                                 };
2297
2298                                 ast_bridge_channel_queue_frame(bridge_channel, &interval_action);
2299                         }
2300                 }
2301         }
2302 }
2303
2304 /*!
2305  * \internal
2306  * \brief Wait for something to happen on the bridge channel and handle it.
2307  * \since 12.0.0
2308  *
2309  * \param bridge_channel Channel to wait.
2310  *
2311  * \note Each channel does writing/reading in their own thread.
2312  *
2313  * \return Nothing
2314  */
2315 static void bridge_channel_wait(struct ast_bridge_channel *bridge_channel)
2316 {
2317         int ms = -1;
2318         int outfd;
2319         struct ast_channel *chan;
2320
2321         /* Wait for data to either come from the channel or us to be signaled */
2322         ast_bridge_channel_lock(bridge_channel);
2323         if (bridge_channel->state != AST_BRIDGE_CHANNEL_STATE_WAIT) {
2324         } else if (bridge_channel->suspended) {
2325 /* BUGBUG the external party use of suspended will go away as will these references because this is the bridge channel thread */
2326                 ast_debug(1, "Bridge %s: %p(%s) is going into a signal wait\n",
2327                         bridge_channel->bridge->uniqueid, bridge_channel,
2328                         ast_channel_name(bridge_channel->chan));
2329                 ast_cond_wait(&bridge_channel->cond, ao2_object_get_lockaddr(bridge_channel));
2330         } else {
2331                 ast_debug(10, "Bridge %s: %p(%s) is going into a waitfor\n",
2332                         bridge_channel->bridge->uniqueid, bridge_channel,
2333                         ast_channel_name(bridge_channel->chan));
2334                 bridge_channel->waiting = 1;
2335                 ast_bridge_channel_unlock(bridge_channel);
2336                 outfd = -1;
2337 /* BUGBUG need to make the next expiring active interval setup ms timeout rather than holding up the chan reads. */
2338                 chan = ast_waitfor_nandfds(&bridge_channel->chan, 1,
2339                         &bridge_channel->alert_pipe[0], 1, NULL, &outfd, &ms);
2340                 bridge_channel->waiting = 0;
2341                 if (ast_channel_softhangup_internal_flag(bridge_channel->chan) & AST_SOFTHANGUP_UNBRIDGE) {
2342                         ast_channel_clear_softhangup(bridge_channel->chan, AST_SOFTHANGUP_UNBRIDGE);
2343                         ast_bridge_channel_lock_bridge(bridge_channel);
2344                         bridge_channel->bridge->reconfigured = 1;
2345                         bridge_reconfigured(bridge_channel->bridge);
2346                         ast_bridge_unlock(bridge_channel->bridge);
2347                 }
2348                 ast_bridge_channel_lock(bridge_channel);
2349                 bridge_channel->activity = AST_BRIDGE_CHANNEL_THREAD_FRAME;
2350                 ast_bridge_channel_unlock(bridge_channel);
2351                 if (!bridge_channel->suspended
2352                         && bridge_channel->state == AST_BRIDGE_CHANNEL_STATE_WAIT) {
2353                         if (chan) {
2354                                 bridge_channel_handle_interval(bridge_channel);
2355                                 bridge_handle_trip(bridge_channel);
2356                         } else if (-1 < outfd) {
2357                                 bridge_channel_handle_write(bridge_channel);
2358                         }
2359                 }
2360                 bridge_channel->activity = AST_BRIDGE_CHANNEL_THREAD_IDLE;
2361                 return;
2362         }
2363         ast_bridge_channel_unlock(bridge_channel);
2364 }
2365
2366 /*!
2367  * \internal
2368  * \brief Handle bridge channel join event.
2369  * \since 12.0.0
2370  *
2371  * \param bridge_channel Which channel is joining.
2372  *
2373  * \return Nothing
2374  */
2375 static void bridge_channel_handle_join(struct ast_bridge_channel *bridge_channel)
2376 {
2377         struct ast_bridge_features *features = bridge_channel->features;
2378         struct ast_bridge_hook *hook;
2379         struct ao2_iterator iter;
2380
2381         /* Run any join hooks. */
2382         iter = ao2_iterator_init(features->join_hooks, AO2_ITERATOR_UNLINK);
2383         hook = ao2_iterator_next(&iter);
2384         if (hook) {
2385                 bridge_channel_suspend(bridge_channel);
2386                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2387                 do {
2388                         hook->callback(bridge_channel->bridge, bridge_channel, hook->hook_pvt);
2389                         ao2_ref(hook, -1);
2390                 } while ((hook = ao2_iterator_next(&iter)));
2391                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2392                 bridge_channel_unsuspend(bridge_channel);
2393         }
2394         ao2_iterator_destroy(&iter);
2395 }
2396
2397 /*!
2398  * \internal
2399  * \brief Handle bridge channel leave event.
2400  * \since 12.0.0
2401  *
2402  * \param bridge_channel Which channel is leaving.
2403  *
2404  * \return Nothing
2405  */
2406 static void bridge_channel_handle_leave(struct ast_bridge_channel *bridge_channel)
2407 {
2408         struct ast_bridge_features *features = bridge_channel->features;
2409         struct ast_bridge_hook *hook;
2410         struct ao2_iterator iter;
2411
2412         /* Run any leave hooks. */
2413         iter = ao2_iterator_init(features->leave_hooks, AO2_ITERATOR_UNLINK);
2414         hook = ao2_iterator_next(&iter);
2415         if (hook) {
2416                 bridge_channel_suspend(bridge_channel);
2417                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2418                 do {
2419                         hook->callback(bridge_channel->bridge, bridge_channel, hook->hook_pvt);
2420                         ao2_ref(hook, -1);
2421                 } while ((hook = ao2_iterator_next(&iter)));
2422                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2423                 bridge_channel_unsuspend(bridge_channel);
2424         }
2425         ao2_iterator_destroy(&iter);
2426 }
2427
2428 /*! \brief Join a channel to a bridge and handle anything the bridge may want us to do */
2429 static void bridge_channel_join(struct ast_bridge_channel *bridge_channel)
2430 {
2431         ast_format_copy(&bridge_channel->read_format, ast_channel_readformat(bridge_channel->chan));
2432         ast_format_copy(&bridge_channel->write_format, ast_channel_writeformat(bridge_channel->chan));
2433
2434         ast_debug(1, "Bridge %s: %p(%s) is joining\n",
2435                 bridge_channel->bridge->uniqueid,
2436                 bridge_channel, ast_channel_name(bridge_channel->chan));
2437
2438         /*
2439          * Get "in the bridge" before pushing the channel for any
2440          * masquerades on the channel to happen before bridging.
2441          */
2442         ast_channel_lock(bridge_channel->chan);
2443         ast_channel_internal_bridge_set(bridge_channel->chan, bridge_channel->bridge);
2444         ast_channel_unlock(bridge_channel->chan);
2445
2446         /* Add the jitterbuffer if the channel requires it */
2447         ast_jb_enable_for_channel(bridge_channel->chan);
2448
2449         /*
2450          * Directly locking the bridge is safe here because nobody else
2451          * knows about this bridge_channel yet.
2452          */
2453         ast_bridge_lock(bridge_channel->bridge);
2454
2455         if (!bridge_channel->bridge->callid) {
2456                 bridge_channel->bridge->callid = ast_read_threadstorage_callid();
2457         }
2458
2459         if (bridge_channel_push(bridge_channel)) {
2460                 ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_HANGUP);
2461         }
2462         bridge_reconfigured(bridge_channel->bridge);
2463
2464         if (bridge_channel->state == AST_BRIDGE_CHANNEL_STATE_WAIT) {
2465                 /*
2466                  * Indicate a source change since this channel is entering the
2467                  * bridge system only if the bridge technology is not MULTIMIX
2468                  * capable.  The MULTIMIX technology has already done it.
2469                  */
2470                 if (!(bridge_channel->bridge->technology->capabilities
2471                         & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
2472                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2473                 }
2474
2475                 ast_bridge_unlock(bridge_channel->bridge);
2476                 bridge_channel_handle_join(bridge_channel);
2477                 while (bridge_channel->state == AST_BRIDGE_CHANNEL_STATE_WAIT) {
2478                         /* Wait for something to do. */
2479                         bridge_channel_wait(bridge_channel);
2480                 }
2481                 bridge_channel_handle_leave(bridge_channel);
2482                 ast_bridge_channel_lock_bridge(bridge_channel);
2483         }
2484
2485         bridge_channel_pull(bridge_channel);
2486         bridge_reconfigured(bridge_channel->bridge);
2487
2488         ast_bridge_unlock(bridge_channel->bridge);
2489
2490         /* Indicate a source change since this channel is leaving the bridge system. */
2491         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2492
2493 /* BUGBUG Revisit in regards to moving channels between bridges and local channel optimization. */
2494 /* BUGBUG This is where outgoing HOLD/UNHOLD memory should write UNHOLD to channel. */
2495         /* Complete any partial DTMF digit before exiting the bridge. */
2496         if (ast_channel_sending_dtmf_digit(bridge_channel->chan)) {
2497                 ast_bridge_end_dtmf(bridge_channel->chan,
2498                         ast_channel_sending_dtmf_digit(bridge_channel->chan),
2499                         ast_channel_sending_dtmf_tv(bridge_channel->chan), "bridge end");
2500         }
2501
2502         /*
2503          * Wait for any dual redirect to complete.
2504          *
2505          * Must be done while "still in the bridge" for ast_async_goto()
2506          * to work right.
2507          */
2508         while (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT)) {
2509                 sched_yield();
2510         }
2511         ast_channel_lock(bridge_channel->chan);
2512         ast_channel_internal_bridge_set(bridge_channel->chan, NULL);
2513         ast_channel_unlock(bridge_channel->chan);
2514
2515         ast_bridge_channel_restore_formats(bridge_channel);
2516 }
2517
2518 /*!
2519  * \internal
2520  * \brief Close a pipe.
2521  * \since 12.0.0
2522  *
2523  * \param my_pipe What to close.
2524  *
2525  * \return Nothing
2526  */
2527 static void pipe_close(int *my_pipe)
2528 {
2529         if (my_pipe[0] > -1) {
2530                 close(my_pipe[0]);
2531                 my_pipe[0] = -1;
2532         }
2533         if (my_pipe[1] > -1) {
2534                 close(my_pipe[1]);
2535                 my_pipe[1] = -1;
2536         }
2537 }
2538
2539 /*!
2540  * \internal
2541  * \brief Initialize a pipe as non-blocking.
2542  * \since 12.0.0
2543  *
2544  * \param my_pipe What to initialize.
2545  *
2546  * \retval 0 on success.
2547  * \retval -1 on error.
2548  */
2549 static int pipe_init_nonblock(int *my_pipe)
2550 {
2551         int flags;
2552
2553         my_pipe[0] = -1;
2554         my_pipe[1] = -1;
2555         if (pipe(my_pipe)) {
2556                 ast_log(LOG_WARNING, "Can't create pipe! Try increasing max file descriptors with ulimit -n\n");
2557                 return -1;
2558         }
2559         flags = fcntl(my_pipe[0], F_GETFL);
2560         if (fcntl(my_pipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
2561                 ast_log(LOG_WARNING, "Unable to set read pipe nonblocking! (%d: %s)\n",
2562                         errno, strerror(errno));
2563                 return -1;
2564         }
2565         flags = fcntl(my_pipe[1], F_GETFL);
2566         if (fcntl(my_pipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
2567                 ast_log(LOG_WARNING, "Unable to set write pipe nonblocking! (%d: %s)\n",
2568                         errno, strerror(errno));
2569                 return -1;
2570         }
2571         return 0;
2572 }
2573
2574 /* Destroy elements of the bridge channel structure and the bridge channel structure itself */
2575 static void bridge_channel_destroy(void *obj)
2576 {
2577         struct ast_bridge_channel *bridge_channel = obj;
2578         struct ast_frame *fr;
2579
2580         if (bridge_channel->callid) {
2581                 bridge_channel->callid = ast_callid_unref(bridge_channel->callid);
2582         }
2583
2584         if (bridge_channel->bridge) {
2585                 ao2_ref(bridge_channel->bridge, -1);
2586                 bridge_channel->bridge = NULL;
2587         }
2588
2589         /* Flush any unhandled wr_queue frames. */
2590         while ((fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list))) {
2591                 ast_frfree(fr);
2592         }
2593         pipe_close(bridge_channel->alert_pipe);
2594
2595         ast_cond_destroy(&bridge_channel->cond);
2596 }
2597
2598 static struct ast_bridge_channel *bridge_channel_alloc(struct ast_bridge *bridge)
2599 {
2600         struct ast_bridge_channel *bridge_channel;
2601
2602         bridge_channel = ao2_alloc(sizeof(struct ast_bridge_channel), bridge_channel_destroy);
2603         if (!bridge_channel) {
2604                 return NULL;
2605         }
2606         ast_cond_init(&bridge_channel->cond, NULL);
2607         if (pipe_init_nonblock(bridge_channel->alert_pipe)) {
2608                 ao2_ref(bridge_channel, -1);
2609                 return NULL;
2610         }
2611         if (bridge) {
2612                 bridge_channel->bridge = bridge;
2613                 ao2_ref(bridge_channel->bridge, +1);
2614         }
2615
2616         return bridge_channel;
2617 }
2618
2619 struct after_bridge_cb_ds {
2620         /*! Desired callback function. */
2621         ast_after_bridge_cb callback;
2622         /*! After bridge callback will not be called and destroy any resources data may contain. */
2623         ast_after_bridge_cb_failed failed;
2624         /*! Extra data to pass to the callback. */
2625         void *data;
2626 };
2627
2628 /*!
2629  * \internal
2630  * \brief Destroy the after bridge callback datastore.
2631  * \since 12.0.0
2632  *
2633  * \param data After bridge callback data to destroy.
2634  *
2635  * \return Nothing
2636  */
2637 static void after_bridge_cb_destroy(void *data)
2638 {
2639         struct after_bridge_cb_ds *after_bridge = data;
2640
2641         if (after_bridge->failed) {
2642                 after_bridge->failed(AST_AFTER_BRIDGE_CB_REASON_DESTROY, after_bridge->data);
2643                 after_bridge->failed = NULL;
2644         }
2645 }
2646
2647 /*!
2648  * \internal
2649  * \brief Fixup the after bridge callback datastore.
2650  * \since 12.0.0
2651  *
2652  * \param data After bridge callback data to fixup.
2653  * \param old_chan The datastore is moving from this channel.
2654  * \param new_chan The datastore is moving to this channel.
2655  *
2656  * \return Nothing
2657  */
2658 static void after_bridge_cb_fixup(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan)
2659 {
2660         /* There can be only one.  Discard any already on the new channel. */
2661         ast_after_bridge_callback_discard(new_chan, AST_AFTER_BRIDGE_CB_REASON_MASQUERADE);
2662 }
2663
2664 static const struct ast_datastore_info after_bridge_cb_info = {
2665         .type = "after-bridge-cb",
2666         .destroy = after_bridge_cb_destroy,
2667         .chan_fixup = after_bridge_cb_fixup,
2668 };
2669
2670 /*!
2671  * \internal
2672  * \brief Remove channel after the bridge callback and return it.
2673  * \since 12.0.0
2674  *
2675  * \param chan Channel to remove after bridge callback.
2676  *
2677  * \retval datastore on success.
2678  * \retval NULL on error or not found.
2679  */
2680 static struct ast_datastore *after_bridge_cb_remove(struct ast_channel *chan)
2681 {
2682         struct ast_datastore *datastore;
2683
2684         ast_channel_lock(chan);
2685         datastore = ast_channel_datastore_find(chan, &after_bridge_cb_info, NULL);
2686         if (datastore && ast_channel_datastore_remove(chan, datastore)) {
2687                 datastore = NULL;
2688         }
2689         ast_channel_unlock(chan);
2690
2691         return datastore;
2692 }
2693
2694 void ast_after_bridge_callback_discard(struct ast_channel *chan, enum ast_after_bridge_cb_reason reason)
2695 {
2696         struct ast_datastore *datastore;
2697
2698         datastore = after_bridge_cb_remove(chan);
2699         if (datastore) {
2700                 struct after_bridge_cb_ds *after_bridge = datastore->data;
2701
2702                 if (after_bridge && after_bridge->failed) {
2703                         after_bridge->failed(reason, after_bridge->data);
2704                         after_bridge->failed = NULL;
2705                 }
2706                 ast_datastore_free(datastore);
2707         }
2708 }
2709
2710 /*!
2711  * \internal
2712  * \brief Run any after bridge callback if possible.
2713  * \since 12.0.0
2714  *
2715  * \param chan Channel to run after bridge callback.
2716  *
2717  * \return Nothing
2718  */
2719 static void after_bridge_callback_run(struct ast_channel *chan)
2720 {
2721         struct ast_datastore *datastore;
2722         struct after_bridge_cb_ds *after_bridge;
2723
2724         if (ast_check_hangup(chan)) {
2725                 return;
2726         }
2727
2728         /* Get after bridge goto datastore. */
2729         datastore = after_bridge_cb_remove(chan);
2730         if (!datastore) {
2731                 return;
2732         }
2733
2734         after_bridge = datastore->data;
2735         if (after_bridge) {
2736                 after_bridge->failed = NULL;
2737                 after_bridge->callback(chan, after_bridge->data);
2738         }
2739
2740         /* Discard after bridge callback datastore. */
2741         ast_datastore_free(datastore);
2742 }
2743
2744 int ast_after_bridge_callback_set(struct ast_channel *chan, ast_after_bridge_cb callback, ast_after_bridge_cb_failed failed, void *data)
2745 {
2746         struct ast_datastore *datastore;
2747         struct after_bridge_cb_ds *after_bridge;
2748
2749         /* Sanity checks. */
2750         ast_assert(chan != NULL);
2751         if (!chan || !callback) {
2752                 return -1;
2753         }
2754
2755         /* Create a new datastore. */
2756         datastore = ast_datastore_alloc(&after_bridge_cb_info, NULL);
2757         if (!datastore) {
2758                 return -1;
2759         }
2760         after_bridge = ast_calloc(1, sizeof(*after_bridge));
2761         if (!after_bridge) {
2762                 ast_datastore_free(datastore);
2763                 return -1;
2764         }
2765
2766         /* Initialize it. */
2767         after_bridge->callback = callback;
2768         after_bridge->failed = failed;
2769         after_bridge->data = data;
2770         datastore->data = after_bridge;
2771
2772         /* Put it on the channel replacing any existing one. */
2773         ast_channel_lock(chan);
2774         ast_after_bridge_callback_discard(chan, AST_AFTER_BRIDGE_CB_REASON_REPLACED);
2775         ast_channel_datastore_add(chan, datastore);
2776         ast_channel_unlock(chan);
2777
2778         return 0;
2779 }
2780
2781 const char *reason_strings[] = {
2782         [AST_AFTER_BRIDGE_CB_REASON_DESTROY] = "Bridge Destroyed",
2783         [AST_AFTER_BRIDGE_CB_REASON_REPLACED] = "Channel replaced",
2784         [AST_AFTER_BRIDGE_CB_REASON_MASQUERADE] = "Channel masqueraded",
2785         [AST_AFTER_BRIDGE_CB_REASON_DEPART] = "Channel departed",
2786         [AST_AFTER_BRIDGE_CB_REASON_REMOVED] = "Channel removed",
2787 };
2788
2789 const char *ast_after_bridge_cb_reason_string(enum ast_after_bridge_cb_reason reason)
2790 {
2791         if (reason < AST_AFTER_BRIDGE_CB_REASON_DESTROY || reason > AST_AFTER_BRIDGE_CB_REASON_REMOVED) {
2792                 return "Unknown";
2793         }
2794
2795         return reason_strings[reason];
2796 }
2797
2798 struct after_bridge_goto_ds {
2799         /*! Goto string that can be parsed by ast_parseable_goto(). */
2800         const char *parseable_goto;
2801         /*! Specific goto context or default context for parseable_goto. */
2802         const char *context;
2803         /*! Specific goto exten or default exten for parseable_goto. */
2804         const char *exten;
2805         /*! Specific goto priority or default priority for parseable_goto. */
2806         int priority;
2807         /*! TRUE if the peer should run the h exten. */
2808         unsigned int run_h_exten:1;
2809         /*! Specific goto location */
2810         unsigned int specific:1;
2811 };
2812
2813 /*!
2814  * \internal
2815  * \brief Destroy the after bridge goto datastore.
2816  * \since 12.0.0
2817  *
2818  * \param data After bridge goto data to destroy.
2819  *
2820  * \return Nothing
2821  */
2822 static void after_bridge_goto_destroy(void *data)
2823 {
2824         struct after_bridge_goto_ds *after_bridge = data;
2825
2826         ast_free((char *) after_bridge->parseable_goto);
2827         ast_free((char *) after_bridge->context);
2828         ast_free((char *) after_bridge->exten);
2829 }
2830
2831 /*!
2832  * \internal
2833  * \brief Fixup the after bridge goto datastore.
2834  * \since 12.0.0
2835  *
2836  * \param data After bridge goto data to fixup.
2837  * \param old_chan The datastore is moving from this channel.
2838  * \param new_chan The datastore is moving to this channel.
2839  *
2840  * \return Nothing
2841  */
2842 static void after_bridge_goto_fixup(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan)
2843 {
2844         /* There can be only one.  Discard any already on the new channel. */
2845         ast_after_bridge_goto_discard(new_chan);
2846 }
2847
2848 static const struct ast_datastore_info after_bridge_goto_info = {
2849         .type = "after-bridge-goto",
2850         .destroy = after_bridge_goto_destroy,
2851         .chan_fixup = after_bridge_goto_fixup,
2852 };
2853
2854 /*!
2855  * \internal
2856  * \brief Remove channel goto location after the bridge and return it.
2857  * \since 12.0.0
2858  *
2859  * \param chan Channel to remove after bridge goto location.
2860  *
2861  * \retval datastore on success.
2862  * \retval NULL on error or not found.
2863  */
2864 static struct ast_datastore *after_bridge_goto_remove(struct ast_channel *chan)
2865 {
2866         struct ast_datastore *datastore;
2867
2868         ast_channel_lock(chan);
2869         datastore = ast_channel_datastore_find(chan, &after_bridge_goto_info, NULL);
2870         if (datastore && ast_channel_datastore_remove(chan, datastore)) {
2871                 datastore = NULL;
2872         }
2873         ast_channel_unlock(chan);
2874
2875         return datastore;
2876 }
2877
2878 void ast_after_bridge_goto_discard(struct ast_channel *chan)
2879 {
2880         struct ast_datastore *datastore;
2881
2882         datastore = after_bridge_goto_remove(chan);
2883         if (datastore) {
2884                 ast_datastore_free(datastore);
2885         }
2886 }
2887
2888 int ast_after_bridge_goto_setup(struct ast_channel *chan)
2889 {
2890         struct ast_datastore *datastore;
2891         struct after_bridge_goto_ds *after_bridge;
2892         int goto_failed = -1;
2893
2894         /* Determine if we are going to setup a dialplan location and where. */
2895         if (ast_channel_softhangup_internal_flag(chan) & AST_SOFTHANGUP_ASYNCGOTO) {
2896                 /* An async goto has already setup a location. */
2897                 ast_channel_clear_softhangup(chan, AST_SOFTHANGUP_ASYNCGOTO);
2898                 if (!ast_check_hangup(chan)) {
2899                         goto_failed = 0;
2900                 }
2901                 return goto_failed;
2902         }
2903
2904         /* Get after bridge goto datastore. */
2905         datastore = after_bridge_goto_remove(chan);
2906         if (!datastore) {
2907                 return goto_failed;
2908         }
2909
2910         after_bridge = datastore->data;
2911         if (after_bridge->run_h_exten) {
2912                 if (ast_exists_extension(chan, after_bridge->context, "h", 1,
2913                         S_COR(ast_channel_caller(chan)->id.number.valid,
2914                                 ast_channel_caller(chan)->id.number.str, NULL))) {
2915                         ast_debug(1, "Running after bridge goto h exten %s,h,1\n",
2916                                 ast_channel_context(chan));
2917                         ast_pbx_h_exten_run(chan, after_bridge->context);
2918                 }
2919         } else if (!ast_check_hangup(chan)) {
2920                 if (after_bridge->specific) {
2921                         goto_failed = ast_explicit_goto(chan, after_bridge->context,
2922                                 after_bridge->exten, after_bridge->priority);
2923                 } else if (!ast_strlen_zero(after_bridge->parseable_goto)) {
2924                         char *context;
2925                         char *exten;
2926                         int priority;
2927
2928                         /* Option F(x) for Bridge(), Dial(), and Queue() */
2929
2930                         /* Save current dialplan location in case of failure. */
2931                         context = ast_strdupa(ast_channel_context(chan));
2932                         exten = ast_strdupa(ast_channel_exten(chan));
2933                         priority = ast_channel_priority(chan);
2934
2935                         /* Set current dialplan position to default dialplan position */
2936                         ast_explicit_goto(chan, after_bridge->context, after_bridge->exten,
2937                                 after_bridge->priority);
2938
2939                         /* Then perform the goto */
2940                         goto_failed = ast_parseable_goto(chan, after_bridge->parseable_goto);
2941                         if (goto_failed) {
2942                                 /* Restore original dialplan location. */
2943                                 ast_channel_context_set(chan, context);
2944                                 ast_channel_exten_set(chan, exten);
2945                                 ast_channel_priority_set(chan, priority);
2946                         }
2947                 } else {
2948                         /* Option F() for Bridge(), Dial(), and Queue() */
2949                         goto_failed = ast_goto_if_exists(chan, after_bridge->context,
2950                                 after_bridge->exten, after_bridge->priority + 1);
2951                 }
2952                 if (!goto_failed) {
2953                         ast_debug(1, "Setup after bridge goto location to %s,%s,%d.\n",
2954                                 ast_channel_context(chan),
2955                                 ast_channel_exten(chan),
2956                                 ast_channel_priority(chan));
2957                 }
2958         }
2959
2960         /* Discard after bridge goto datastore. */
2961         ast_datastore_free(datastore);
2962
2963         return goto_failed;
2964 }
2965
2966 void ast_after_bridge_goto_run(struct ast_channel *chan)
2967 {
2968         int goto_failed;
2969
2970         goto_failed = ast_after_bridge_goto_setup(chan);
2971         if (goto_failed || ast_pbx_run(chan)) {
2972                 ast_hangup(chan);
2973         }
2974 }
2975
2976 /*!
2977  * \internal
2978  * \brief Set after bridge goto location of channel.
2979  * \since 12.0.0
2980  *
2981  * \param chan Channel to setup after bridge goto location.
2982  * \param run_h_exten TRUE if the h exten should be run.
2983  * \param specific TRUE if the context/exten/priority is exactly specified.
2984  * \param context Context to goto after bridge.
2985  * \param exten Exten to goto after bridge. (Could be NULL if run_h_exten)
2986  * \param priority Priority to goto after bridge.
2987  * \param parseable_goto User specified goto string. (Could be NULL)
2988  *
2989  * \details Add a channel datastore to setup the goto location
2990  * when the channel leaves the bridge and run a PBX from there.
2991  *
2992  * If run_h_exten then execute the h exten found in the given context.
2993  * Else if specific then goto the given context/exten/priority.
2994  * Else if parseable_goto then use the given context/exten/priority
2995  *   as the relative position for the parseable_goto.
2996  * Else goto the given context/exten/priority+1.
2997  *
2998  * \return Nothing
2999  */
3000 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)
3001 {
3002         struct ast_datastore *datastore;
3003         struct after_bridge_goto_ds *after_bridge;
3004
3005         /* Sanity checks. */
3006         ast_assert(chan != NULL);
3007         if (!chan) {
3008                 return;
3009         }
3010         if (run_h_exten) {
3011                 ast_assert(run_h_exten && context);
3012                 if (!context) {
3013                         return;
3014                 }
3015         } else {
3016                 ast_assert(context && exten && 0 < priority);
3017                 if (!context || !exten || priority < 1) {
3018                         return;
3019                 }
3020         }
3021
3022         /* Create a new datastore. */
3023         datastore = ast_datastore_alloc(&after_bridge_goto_info, NULL);
3024         if (!datastore) {
3025                 return;
3026         }
3027         after_bridge = ast_calloc(1, sizeof(*after_bridge));
3028         if (!after_bridge) {
3029                 ast_datastore_free(datastore);
3030                 return;
3031         }
3032
3033         /* Initialize it. */
3034         after_bridge->parseable_goto = ast_strdup(parseable_goto);
3035         after_bridge->context = ast_strdup(context);
3036         after_bridge->exten = ast_strdup(exten);
3037         after_bridge->priority = priority;
3038         after_bridge->run_h_exten = run_h_exten ? 1 : 0;
3039         after_bridge->specific = specific ? 1 : 0;
3040         datastore->data = after_bridge;
3041         if ((parseable_goto && !after_bridge->parseable_goto)
3042                 || (context && !after_bridge->context)
3043                 || (exten && !after_bridge->exten)) {
3044                 ast_datastore_free(datastore);
3045                 return;
3046         }
3047
3048         /* Put it on the channel replacing any existing one. */
3049         ast_channel_lock(chan);
3050         ast_after_bridge_goto_discard(chan);
3051         ast_channel_datastore_add(chan, datastore);
3052         ast_channel_unlock(chan);
3053 }
3054
3055 void ast_after_bridge_set_goto(struct ast_channel *chan, const char *context, const char *exten, int priority)
3056 {
3057         __after_bridge_set_goto(chan, 0, 1, context, exten, priority, NULL);
3058 }
3059
3060 void ast_after_bridge_set_h(struct ast_channel *chan, const char *context)
3061 {
3062         __after_bridge_set_goto(chan, 1, 0, context, NULL, 1, NULL);
3063 }
3064
3065 void ast_after_bridge_set_go_on(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *parseable_goto)
3066 {
3067         char *p_goto;
3068
3069         if (!ast_strlen_zero(parseable_goto)) {
3070                 p_goto = ast_strdupa(parseable_goto);
3071                 ast_replace_subargument_delimiter(p_goto);
3072         } else {
3073                 p_goto = NULL;
3074         }
3075         __after_bridge_set_goto(chan, 0, 0, context, exten, priority, p_goto);
3076 }
3077
3078 void ast_bridge_notify_masquerade(struct ast_channel *chan)
3079 {
3080         struct ast_bridge_channel *bridge_channel;
3081         struct ast_bridge *bridge;
3082
3083         /* Safely get the bridge_channel pointer for the chan. */
3084         ast_channel_lock(chan);
3085         bridge_channel = ast_channel_get_bridge_channel(chan);
3086         ast_channel_unlock(chan);
3087         if (!bridge_channel) {
3088                 /* Not in a bridge */
3089                 return;
3090         }
3091
3092         ast_bridge_channel_lock_bridge(bridge_channel);
3093         bridge = bridge_channel->bridge;
3094         if (bridge_channel == find_bridge_channel(bridge, chan)) {
3095 /* 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. */
3096                 /* The channel we want to notify is still in a bridge. */
3097                 bridge->v_table->notify_masquerade(bridge, bridge_channel);
3098                 bridge_reconfigured(bridge);
3099         }
3100         ast_bridge_unlock(bridge);
3101         ao2_ref(bridge_channel, -1);
3102 }
3103
3104 /*
3105  * BUGBUG make ast_bridge_join() require features to be allocated just like ast_bridge_impart() and not expect the struct back.
3106  *
3107  * This change is really going to break ConfBridge.  All other
3108  * users are easily changed.  However, it is needed so the
3109  * bridging code can manipulate features on all channels
3110  * consistently no matter how they joined.
3111  *
3112  * Need to update the features parameter doxygen when this
3113  * change is made to be like ast_bridge_impart().
3114  */
3115 enum ast_bridge_channel_state ast_bridge_join(struct ast_bridge *bridge,
3116         struct ast_channel *chan,
3117         struct ast_channel *swap,
3118         struct ast_bridge_features *features,
3119         struct ast_bridge_tech_optimizations *tech_args,
3120         int pass_reference)
3121 {
3122         struct ast_bridge_channel *bridge_channel;
3123         enum ast_bridge_channel_state state;
3124
3125         bridge_channel = bridge_channel_alloc(bridge);
3126         if (pass_reference) {
3127                 ao2_ref(bridge, -1);
3128         }
3129         if (!bridge_channel) {
3130                 state = AST_BRIDGE_CHANNEL_STATE_HANGUP;
3131                 goto join_exit;
3132         }
3133 /* BUGBUG features cannot be NULL when passed in. When it is changed to allocated we can do like ast_bridge_impart() and allocate one. */
3134         ast_assert(features != NULL);
3135         if (!features) {
3136                 ao2_ref(bridge_channel, -1);
3137                 state = AST_BRIDGE_CHANNEL_STATE_HANGUP;
3138                 goto join_exit;
3139         }
3140         if (tech_args) {
3141                 bridge_channel->tech_args = *tech_args;
3142         }
3143
3144         /* Initialize various other elements of the bridge channel structure that we can't do above */
3145         ast_channel_lock(chan);
3146         ast_channel_internal_bridge_channel_set(chan, bridge_channel);
3147         ast_channel_unlock(chan);
3148         bridge_channel->thread = pthread_self();
3149         bridge_channel->chan = chan;
3150         bridge_channel->swap = swap;
3151         bridge_channel->features = features;
3152
3153         bridge_channel_join(bridge_channel);
3154         state = bridge_channel->state;
3155
3156         /* Cleanup all the data in the bridge channel after it leaves the bridge. */
3157         ast_channel_lock(chan);
3158         ast_channel_internal_bridge_channel_set(chan, NULL);
3159         ast_channel_unlock(chan);
3160         bridge_channel->chan = NULL;
3161         bridge_channel->swap = NULL;
3162         bridge_channel->features = NULL;
3163
3164         ao2_ref(bridge_channel, -1);
3165
3166 join_exit:;
3167 /* 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. */
3168         after_bridge_callback_run(chan);
3169         if (!(ast_channel_softhangup_internal_flag(chan) & AST_SOFTHANGUP_ASYNCGOTO)
3170                 && !ast_after_bridge_goto_setup(chan)) {
3171                 /* Claim the after bridge goto is an async goto destination. */
3172                 ast_channel_lock(chan);
3173                 ast_softhangup_nolock(chan, AST_SOFTHANGUP_ASYNCGOTO);
3174                 ast_channel_unlock(chan);
3175         }
3176         return state;
3177 }
3178
3179 /*! \brief Thread responsible for imparted bridged channels to be departed */
3180 static void *bridge_channel_depart_thread(void *data)
3181 {
3182         struct ast_bridge_channel *bridge_channel = data;
3183
3184         if (bridge_channel->callid) {
3185                 ast_callid_threadassoc_add(bridge_channel->callid);
3186         }
3187
3188         bridge_channel_join(bridge_channel);
3189
3190         /* cleanup */
3191         bridge_channel->swap = NULL;
3192         ast_bridge_features_destroy(bridge_channel->features);
3193         bridge_channel->features = NULL;
3194
3195         ast_after_bridge_callback_discard(bridge_channel->chan, AST_AFTER_BRIDGE_CB_REASON_DEPART);
3196         ast_after_bridge_goto_discard(bridge_channel->chan);
3197
3198         return NULL;
3199 }
3200
3201 /*! \brief Thread responsible for independent imparted bridged channels */
3202 static void *bridge_channel_ind_thread(void *data)
3203 {
3204         struct ast_bridge_channel *bridge_channel = data;
3205         struct ast_channel *chan;
3206
3207         if (bridge_channel->callid) {
3208                 ast_callid_threadassoc_add(bridge_channel->callid);
3209         }
3210
3211         bridge_channel_join(bridge_channel);
3212         chan = bridge_channel->chan;
3213
3214         /* cleanup */
3215         ast_channel_lock(chan);
3216         ast_channel_internal_bridge_channel_set(chan, NULL);
3217         ast_channel_unlock(chan);
3218         bridge_channel->chan = NULL;
3219         bridge_channel->swap = NULL;
3220         ast_bridge_features_destroy(bridge_channel->features);
3221         bridge_channel->features = NULL;
3222
3223         ao2_ref(bridge_channel, -1);
3224
3225         after_bridge_callback_run(chan);
3226         ast_after_bridge_goto_run(chan);
3227         return NULL;
3228 }
3229
3230 int ast_bridge_impart(struct ast_bridge *bridge, struct ast_channel *chan, struct ast_channel *swap, struct ast_bridge_features *features, int independent)
3231 {
3232         int res;
3233         struct ast_bridge_channel *bridge_channel;
3234
3235         /* Supply an empty features structure if the caller did not. */
3236         if (!features) {
3237                 features = ast_bridge_features_new();
3238                 if (!features) {
3239                         return -1;
3240                 }
3241         }
3242
3243         /* Try to allocate a structure for the bridge channel */
3244         bridge_channel = bridge_channel_alloc(bridge);
3245         if (!bridge_channel) {
3246                 ast_bridge_features_destroy(features);
3247                 return -1;
3248         }
3249
3250         /* Setup various parameters */
3251         ast_channel_lock(chan);
3252         ast_channel_internal_bridge_channel_set(chan, bridge_channel);
3253         ast_channel_unlock(chan);
3254         bridge_channel->chan = chan;
3255         bridge_channel->swap = swap;
3256         bridge_channel->features = features;
3257         bridge_channel->depart_wait = independent ? 0 : 1;
3258         bridge_channel->callid = ast_read_threadstorage_callid();
3259
3260         /* Actually create the thread that will handle the channel */
3261         if (independent) {
3262                 /* Independently imparted channels cannot have a PBX. */
3263                 ast_assert(!ast_channel_pbx(chan));
3264
3265                 res = ast_pthread_create_detached(&bridge_channel->thread, NULL,
3266                         bridge_channel_ind_thread, bridge_channel);
3267         } else {
3268                 /* Imparted channels to be departed should not have a PBX either. */
3269                 ast_assert(!ast_channel_pbx(chan));
3270
3271                 res = ast_pthread_create(&bridge_channel->thread, NULL,
3272                         bridge_channel_depart_thread, bridge_channel);
3273         }
3274
3275         if (res) {
3276                 /* cleanup */
3277                 ast_channel_lock(chan);
3278                 ast_channel_internal_bridge_channel_set(chan, NULL);
3279                 ast_channel_unlock(chan);
3280                 bridge_channel->chan = NULL;
3281                 bridge_channel->swap = NULL;
3282                 ast_bridge_features_destroy(bridge_channel->features);
3283                 bridge_channel->features = NULL;
3284
3285                 ao2_ref(bridge_channel, -1);
3286                 return -1;
3287         }
3288
3289         return 0;
3290 }
3291
3292 int ast_bridge_depart(struct ast_channel *chan)
3293 {
3294         struct ast_bridge_channel *bridge_channel;
3295         int departable;
3296
3297         ast_channel_lock(chan);
3298         bridge_channel = ast_channel_internal_bridge_channel(chan);
3299         departable = bridge_channel && bridge_channel->depart_wait;
3300         ast_channel_unlock(chan);
3301         if (!departable) {
3302                 ast_log(LOG_ERROR, "Channel %s cannot be departed.\n",
3303                         ast_channel_name(chan));
3304                 /*
3305                  * Should never happen.  It likely means that
3306                  * ast_bridge_depart() is called by two threads for the same
3307                  * channel, the channel was never imparted to be departed, or it
3308                  * has already been departed.
3309                  */
3310                 ast_assert(0);
3311                 return -1;
3312         }
3313
3314         /*
3315          * We are claiming the reference held by the depart bridge
3316          * channel thread.
3317          */
3318
3319         ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_HANGUP);
3320
3321         /* Wait for the depart thread to die */
3322         ast_debug(1, "Waiting for %p(%s) bridge thread to die.\n",
3323                 bridge_channel, ast_channel_name(bridge_channel->chan));
3324         pthread_join(bridge_channel->thread, NULL);
3325
3326         ast_channel_lock(chan);
3327         ast_channel_internal_bridge_channel_set(chan, NULL);
3328         ast_channel_unlock(chan);
3329
3330         /* We can get rid of the bridge_channel after the depart thread has died. */
3331         ao2_ref(bridge_channel, -1);
3332         return 0;
3333 }
3334
3335 int ast_bridge_remove(struct ast_bridge *bridge, struct ast_channel *chan)
3336 {
3337         struct ast_bridge_channel *bridge_channel;
3338
3339         ast_bridge_lock(bridge);
3340
3341         /* Try to find the channel that we want to remove */
3342         if (!(bridge_channel = find_bridge_channel(bridge, chan))) {
3343                 ast_bridge_unlock(bridge);
3344                 return -1;
3345         }
3346
3347         ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_HANGUP);
3348
3349         ast_bridge_unlock(bridge);
3350
3351         return 0;
3352 }
3353
3354 /*!
3355  * \internal
3356  * \brief Point the bridge_channel to a new bridge.
3357  * \since 12.0.0
3358  *
3359  * \param bridge_channel What is to point to a new bridge.
3360  * \param new_bridge Where the bridge channel should point.
3361  *
3362  * \return Nothing
3363  */
3364 static void bridge_channel_change_bridge(struct ast_bridge_channel *bridge_channel, struct ast_bridge *new_bridge)
3365 {
3366         struct ast_bridge *old_bridge;
3367
3368         ao2_ref(new_bridge, +1);
3369         ast_bridge_channel_lock(bridge_channel);
3370         ast_channel_lock(bridge_channel->chan);
3371         old_bridge = bridge_channel->bridge;
3372         bridge_channel->bridge = new_bridge;
3373         ast_channel_internal_bridge_set(bridge_channel->chan, new_bridge);
3374         ast_channel_unlock(bridge_channel->chan);
3375         ast_bridge_channel_unlock(bridge_channel);
3376         ao2_ref(old_bridge, -1);
3377 }
3378
3379 /*!
3380  * \internal
3381  * \brief Do the merge of two bridges.
3382  * \since 12.0.0
3383  *
3384  * \param dst_bridge Destination bridge of merge.
3385  * \param src_bridge Source bridge of merge.
3386  * \param kick_me Array of channels to kick from the bridges.
3387  * \param num_kick Number of channels in the kick_me array.
3388  *