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