Remove incorrect comment about local channel optimization occurring when performing...
[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 a channel to the bridge.
1099  * \since 12.0.0
1100  *
1101  * \param bridge What to operate upon.
1102  * \param bridge_channel What is joining the bridge technology.
1103  *
1104  * \note On entry, bridge is already locked.
1105  *
1106  * \return Nothing
1107  */
1108 static void bridge_channel_complete_join(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
1109 {
1110         /* Make the channel compatible with the bridge */
1111         bridge_make_compatible(bridge, bridge_channel);
1112
1113         /* Tell the bridge technology we are joining so they set us up */
1114         ast_debug(1, "Bridge %s: %p(%s) is joining %s technology\n",
1115                 bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1116                 bridge->technology->name);
1117         if (bridge->technology->join
1118                 && bridge->technology->join(bridge, bridge_channel)) {
1119                 ast_debug(1, "Bridge %s: %p(%s) failed to join %s technology\n",
1120                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1121                         bridge->technology->name);
1122                 bridge_channel->just_joined = 1;
1123                 return;
1124         }
1125
1126         bridge_channel->just_joined = 0;
1127 }
1128
1129 /*!
1130  * \internal
1131  * \brief Complete joining new channels to the bridge.
1132  * \since 12.0.0
1133  *
1134  * \param bridge Check for new channels on this bridge.
1135  *
1136  * \note On entry, bridge is already locked.
1137  *
1138  * \return Nothing
1139  */
1140 static void bridge_complete_join(struct ast_bridge *bridge)
1141 {
1142         struct ast_bridge_channel *bridge_channel;
1143
1144         if (bridge->dissolved) {
1145                 /*
1146                  * No sense in completing the join on channels for a dissolved
1147                  * bridge.  They are just going to be removed soon anyway.
1148                  * However, we do have reason to abort here because the bridge
1149                  * technology may not be able to handle the number of channels
1150                  * still in the bridge.
1151                  */
1152                 return;
1153         }
1154
1155         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1156                 if (!bridge_channel->just_joined) {
1157                         continue;
1158                 }
1159                 bridge_channel_complete_join(bridge, bridge_channel);
1160         }
1161 }
1162
1163 /*! \brief Helper function used to find the "best" bridge technology given specified capabilities */
1164 static struct ast_bridge_technology *find_best_technology(uint32_t capabilities, struct ast_bridge *bridge)
1165 {
1166         struct ast_bridge_technology *current;
1167         struct ast_bridge_technology *best = NULL;
1168
1169         AST_RWLIST_RDLOCK(&bridge_technologies);
1170         AST_RWLIST_TRAVERSE(&bridge_technologies, current, entry) {
1171                 if (current->suspended) {
1172                         ast_debug(1, "Bridge technology %s is suspended. Skipping.\n",
1173                                 current->name);
1174                         continue;
1175                 }
1176                 if (!(current->capabilities & capabilities)) {
1177                         ast_debug(1, "Bridge technology %s does not have any capabilities we want.\n",
1178                                 current->name);
1179                         continue;
1180                 }
1181                 if (best && current->preference <= best->preference) {
1182                         ast_debug(1, "Bridge technology %s has less preference than %s (%d <= %d). Skipping.\n",
1183                                 current->name, best->name, current->preference, best->preference);
1184                         continue;
1185                 }
1186                 if (current->compatible && !current->compatible(bridge)) {
1187                         ast_debug(1, "Bridge technology %s is not compatible with properties of existing bridge.\n",
1188                                 current->name);
1189                         continue;
1190                 }
1191                 best = current;
1192         }
1193
1194         if (best) {
1195                 /* Increment it's module reference count if present so it does not get unloaded while in use */
1196                 ast_module_ref(best->mod);
1197                 ast_debug(1, "Chose bridge technology %s\n", best->name);
1198         }
1199
1200         AST_RWLIST_UNLOCK(&bridge_technologies);
1201
1202         return best;
1203 }
1204
1205 struct tech_deferred_destroy {
1206         struct ast_bridge_technology *tech;
1207         void *tech_pvt;
1208 };
1209
1210 /*!
1211  * \internal
1212  * \brief Deferred destruction of bridge tech private structure.
1213  * \since 12.0.0
1214  *
1215  * \param bridge What to execute the action on.
1216  * \param action Deferred bridge tech destruction.
1217  *
1218  * \note On entry, bridge must not be locked.
1219  *
1220  * \return Nothing
1221  */
1222 static void bridge_tech_deferred_destroy(struct ast_bridge *bridge, struct ast_frame *action)
1223 {
1224         struct tech_deferred_destroy *deferred = action->data.ptr;
1225         struct ast_bridge dummy_bridge = {
1226                 .technology = deferred->tech,
1227                 .tech_pvt = deferred->tech_pvt,
1228                 };
1229
1230         ast_copy_string(dummy_bridge.uniqueid, bridge->uniqueid, sizeof(dummy_bridge.uniqueid));
1231         ast_debug(1, "Bridge %s: calling %s technology destructor (deferred, dummy)\n",
1232                 dummy_bridge.uniqueid, dummy_bridge.technology->name);
1233         dummy_bridge.technology->destroy(&dummy_bridge);
1234         ast_module_unref(dummy_bridge.technology->mod);
1235 }
1236
1237 /*!
1238  * \internal
1239  * \brief Handle bridge action frame.
1240  * \since 12.0.0
1241  *
1242  * \param bridge What to execute the action on.
1243  * \param action What to do.
1244  *
1245  * \note On entry, bridge is already locked.
1246  * \note Can be called by the bridge destructor.
1247  *
1248  * \return Nothing
1249  */
1250 static void bridge_action_bridge(struct ast_bridge *bridge, struct ast_frame *action)
1251 {
1252 #if 0   /* In case we need to know when the destructor is calling us. */
1253         int in_destructor = !ao2_ref(bridge, 0);
1254 #endif
1255
1256         switch (action->subclass.integer) {
1257         case AST_BRIDGE_ACTION_DEFERRED_TECH_DESTROY:
1258                 ast_bridge_unlock(bridge);
1259                 bridge_tech_deferred_destroy(bridge, action);
1260                 ast_bridge_lock(bridge);
1261                 break;
1262         case AST_BRIDGE_ACTION_DEFERRED_DISSOLVING:
1263                 ast_bridge_unlock(bridge);
1264                 bridge->v_table->dissolving(bridge);
1265                 ast_bridge_lock(bridge);
1266                 break;
1267         default:
1268                 /* Unexpected deferred action type.  Should never happen. */
1269                 ast_assert(0);
1270                 break;
1271         }
1272 }
1273
1274 /*!
1275  * \internal
1276  * \brief Do any pending bridge actions.
1277  * \since 12.0.0
1278  *
1279  * \param bridge What to do actions on.
1280  *
1281  * \note On entry, bridge is already locked.
1282  * \note Can be called by the bridge destructor.
1283  *
1284  * \return Nothing
1285  */
1286 static void bridge_handle_actions(struct ast_bridge *bridge)
1287 {
1288         struct ast_frame *action;
1289
1290         while ((action = AST_LIST_REMOVE_HEAD(&bridge->action_queue, frame_list))) {
1291                 switch (action->frametype) {
1292                 case AST_FRAME_BRIDGE_ACTION:
1293                         bridge_action_bridge(bridge, action);
1294                         break;
1295                 default:
1296                         /* Unexpected deferred frame type.  Should never happen. */
1297                         ast_assert(0);
1298                         break;
1299                 }
1300                 ast_frfree(action);
1301         }
1302 }
1303
1304 static struct stasis_message *create_bridge_snapshot_message(struct ast_bridge *bridge)
1305 {
1306         RAII_VAR(struct ast_bridge_snapshot *, snapshot, NULL, ao2_cleanup);
1307         snapshot = ast_bridge_snapshot_create(bridge);
1308         if (!snapshot) {
1309                 return NULL;
1310         }
1311
1312         return stasis_message_create(ast_bridge_snapshot_type(), snapshot);
1313 }
1314
1315 static void destroy_bridge(void *obj)
1316 {
1317         struct ast_bridge *bridge = obj;
1318         RAII_VAR(struct stasis_message *, clear_msg, NULL, ao2_cleanup);
1319
1320         ast_debug(1, "Bridge %s: actually destroying %s bridge, nobody wants it anymore\n",
1321                 bridge->uniqueid, bridge->v_table->name);
1322
1323         clear_msg = create_bridge_snapshot_message(bridge);
1324         if (clear_msg) {
1325                 RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
1326                 msg = stasis_cache_clear_create(clear_msg);
1327                 if (msg) {
1328                         stasis_publish(ast_bridge_topic(bridge), msg);
1329                 }
1330         }
1331
1332         /* Do any pending actions in the context of destruction. */
1333         ast_bridge_lock(bridge);
1334         bridge_handle_actions(bridge);
1335         ast_bridge_unlock(bridge);
1336
1337         /* There should not be any channels left in the bridge. */
1338         ast_assert(AST_LIST_EMPTY(&bridge->channels));
1339
1340         ast_debug(1, "Bridge %s: calling %s bridge destructor\n",
1341                 bridge->uniqueid, bridge->v_table->name);
1342         bridge->v_table->destroy(bridge);
1343
1344         /* Pass off the bridge to the technology to destroy if needed */
1345         if (bridge->technology) {
1346                 ast_debug(1, "Bridge %s: calling %s technology stop\n",
1347                         bridge->uniqueid, bridge->technology->name);
1348                 if (bridge->technology->stop) {
1349                         ast_bridge_lock(bridge);
1350                         bridge->technology->stop(bridge);
1351                         ast_bridge_unlock(bridge);
1352                 }
1353                 ast_debug(1, "Bridge %s: calling %s technology destructor\n",
1354                         bridge->uniqueid, bridge->technology->name);
1355                 if (bridge->technology->destroy) {
1356                         bridge->technology->destroy(bridge);
1357                 }
1358                 ast_module_unref(bridge->technology->mod);
1359                 bridge->technology = NULL;
1360         }
1361
1362         if (bridge->callid) {
1363                 bridge->callid = ast_callid_unref(bridge->callid);
1364         }
1365
1366         cleanup_video_mode(bridge);
1367 }
1368
1369 struct ast_bridge *ast_bridge_register(struct ast_bridge *bridge)
1370 {
1371         if (bridge) {
1372                 ast_bridge_publish_state(bridge);
1373                 if (!ao2_link(bridges, bridge)) {
1374                         ast_bridge_destroy(bridge);
1375                         bridge = NULL;
1376                 }
1377         }
1378         return bridge;
1379 }
1380
1381 struct ast_bridge *ast_bridge_alloc(size_t size, const struct ast_bridge_methods *v_table)
1382 {
1383         struct ast_bridge *bridge;
1384
1385         /* Check v_table that all methods are present. */
1386         if (!v_table
1387                 || !v_table->name
1388                 || !v_table->destroy
1389                 || !v_table->dissolving
1390                 || !v_table->push
1391                 || !v_table->pull
1392                 || !v_table->notify_masquerade
1393                 || !v_table->get_merge_priority) {
1394                 ast_log(LOG_ERROR, "Virtual method table for bridge class %s not complete.\n",
1395                         v_table && v_table->name ? v_table->name : "<unknown>");
1396                 ast_assert(0);
1397                 return NULL;
1398         }
1399
1400         bridge = ao2_alloc(size, destroy_bridge);
1401         if (bridge) {
1402                 bridge->v_table = v_table;
1403         }
1404         return bridge;
1405 }
1406
1407 struct ast_bridge *ast_bridge_base_init(struct ast_bridge *self, uint32_t capabilities, unsigned int flags)
1408 {
1409         if (!self) {
1410                 return NULL;
1411         }
1412
1413         ast_uuid_generate_str(self->uniqueid, sizeof(self->uniqueid));
1414         ast_set_flag(&self->feature_flags, flags);
1415         self->allowed_capabilities = capabilities;
1416
1417         /* Use our helper function to find the "best" bridge technology. */
1418         self->technology = find_best_technology(capabilities, self);
1419         if (!self->technology) {
1420                 ast_debug(1, "Bridge %s: Could not create.  No technology available to support it.\n",
1421                         self->uniqueid);
1422                 ao2_ref(self, -1);
1423                 return NULL;
1424         }
1425
1426         /* Pass off the bridge to the technology to manipulate if needed */
1427         ast_debug(1, "Bridge %s: calling %s technology constructor\n",
1428                 self->uniqueid, self->technology->name);
1429         if (self->technology->create && self->technology->create(self)) {
1430                 ast_debug(1, "Bridge %s: failed to setup %s technology\n",
1431                         self->uniqueid, self->technology->name);
1432                 ao2_ref(self, -1);
1433                 return NULL;
1434         }
1435         ast_debug(1, "Bridge %s: calling %s technology start\n",
1436                 self->uniqueid, self->technology->name);
1437         if (self->technology->start && self->technology->start(self)) {
1438                 ast_debug(1, "Bridge %s: failed to start %s technology\n",
1439                         self->uniqueid, self->technology->name);
1440                 ao2_ref(self, -1);
1441                 return NULL;
1442         }
1443
1444         if (!ast_bridge_topic(self)) {
1445                 ao2_ref(self, -1);
1446                 return NULL;
1447         }
1448
1449         return self;
1450 }
1451
1452 /*!
1453  * \internal
1454  * \brief ast_bridge base class destructor.
1455  * \since 12.0.0
1456  *
1457  * \param self Bridge to operate upon.
1458  *
1459  * \note Stub because of nothing to do.
1460  *
1461  * \return Nothing
1462  */
1463 static void bridge_base_destroy(struct ast_bridge *self)
1464 {
1465 }
1466
1467 /*!
1468  * \internal
1469  * \brief The bridge is being dissolved.
1470  * \since 12.0.0
1471  *
1472  * \param self Bridge to operate upon.
1473  *
1474  * \return Nothing
1475  */
1476 static void bridge_base_dissolving(struct ast_bridge *self)
1477 {
1478         ao2_unlink(bridges, self);
1479 }
1480
1481 /*!
1482  * \internal
1483  * \brief ast_bridge base push method.
1484  * \since 12.0.0
1485  *
1486  * \param self Bridge to operate upon.
1487  * \param bridge_channel Bridge channel to push.
1488  * \param swap Bridge channel to swap places with if not NULL.
1489  *
1490  * \note On entry, self is already locked.
1491  * \note Stub because of nothing to do.
1492  *
1493  * \retval 0 on success
1494  * \retval -1 on failure
1495  */
1496 static int bridge_base_push(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
1497 {
1498         return 0;
1499 }
1500
1501 /*!
1502  * \internal
1503  * \brief ast_bridge base pull method.
1504  * \since 12.0.0
1505  *
1506  * \param self Bridge to operate upon.
1507  * \param bridge_channel Bridge channel to pull.
1508  *
1509  * \note On entry, self is already locked.
1510  *
1511  * \return Nothing
1512  */
1513 static void bridge_base_pull(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel)
1514 {
1515         bridge_features_remove(bridge_channel->features, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
1516 }
1517
1518 /*!
1519  * \internal
1520  * \brief ast_bridge base notify_masquerade method.
1521  * \since 12.0.0
1522  *
1523  * \param self Bridge to operate upon.
1524  * \param bridge_channel Bridge channel that was masqueraded.
1525  *
1526  * \note On entry, self is already locked.
1527  *
1528  * \return Nothing
1529  */
1530 static void bridge_base_notify_masquerade(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel)
1531 {
1532         self->reconfigured = 1;
1533 }
1534
1535 /*!
1536  * \internal
1537  * \brief Get the merge priority of this bridge.
1538  * \since 12.0.0
1539  *
1540  * \param self Bridge to operate upon.
1541  *
1542  * \note On entry, self is already locked.
1543  *
1544  * \return Merge priority
1545  */
1546 static int bridge_base_get_merge_priority(struct ast_bridge *self)
1547 {
1548         return 0;
1549 }
1550
1551 struct ast_bridge_methods ast_bridge_base_v_table = {
1552         .name = "base",
1553         .destroy = bridge_base_destroy,
1554         .dissolving = bridge_base_dissolving,
1555         .push = bridge_base_push,
1556         .pull = bridge_base_pull,
1557         .notify_masquerade = bridge_base_notify_masquerade,
1558         .get_merge_priority = bridge_base_get_merge_priority,
1559 };
1560
1561 struct ast_bridge *ast_bridge_base_new(uint32_t capabilities, unsigned int flags)
1562 {
1563         void *bridge;
1564
1565         bridge = ast_bridge_alloc(sizeof(struct ast_bridge), &ast_bridge_base_v_table);
1566         bridge = ast_bridge_base_init(bridge, capabilities, flags);
1567         bridge = ast_bridge_register(bridge);
1568         return bridge;
1569 }
1570
1571 int ast_bridge_destroy(struct ast_bridge *bridge)
1572 {
1573         ast_debug(1, "Bridge %s: telling all channels to leave the party\n", bridge->uniqueid);
1574         ast_bridge_lock(bridge);
1575         bridge_dissolve(bridge);
1576         ast_bridge_unlock(bridge);
1577
1578         ao2_ref(bridge, -1);
1579
1580         return 0;
1581 }
1582
1583 static int bridge_make_compatible(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
1584 {
1585         struct ast_format read_format;
1586         struct ast_format write_format;
1587         struct ast_format best_format;
1588         char codec_buf[512];
1589
1590         ast_format_copy(&read_format, ast_channel_readformat(bridge_channel->chan));
1591         ast_format_copy(&write_format, ast_channel_writeformat(bridge_channel->chan));
1592
1593         /* Are the formats currently in use something this bridge can handle? */
1594         if (!ast_format_cap_iscompatible(bridge->technology->format_capabilities, ast_channel_readformat(bridge_channel->chan))) {
1595                 ast_best_codec(bridge->technology->format_capabilities, &best_format);
1596
1597                 /* Read format is a no go... */
1598                 ast_debug(1, "Bridge technology %s wants to read any of formats %s but channel has %s\n",
1599                         bridge->technology->name,
1600                         ast_getformatname_multiple(codec_buf, sizeof(codec_buf), bridge->technology->format_capabilities),
1601                         ast_getformatname(&read_format));
1602
1603                 /* Switch read format to the best one chosen */
1604                 if (ast_set_read_format(bridge_channel->chan, &best_format)) {
1605                         ast_log(LOG_WARNING, "Failed to set channel %s to read format %s\n",
1606                                 ast_channel_name(bridge_channel->chan), ast_getformatname(&best_format));
1607                         return -1;
1608                 }
1609                 ast_debug(1, "Bridge %s put channel %s into read format %s\n",
1610                         bridge->uniqueid, ast_channel_name(bridge_channel->chan),
1611                         ast_getformatname(&best_format));
1612         } else {
1613                 ast_debug(1, "Bridge %s is happy that channel %s already has read format %s\n",
1614                         bridge->uniqueid, ast_channel_name(bridge_channel->chan),
1615                         ast_getformatname(&read_format));
1616         }
1617
1618         if (!ast_format_cap_iscompatible(bridge->technology->format_capabilities, &write_format)) {
1619                 ast_best_codec(bridge->technology->format_capabilities, &best_format);
1620
1621                 /* Write format is a no go... */
1622                 ast_debug(1, "Bridge technology %s wants to write any of formats %s but channel has %s\n",
1623                         bridge->technology->name,
1624                         ast_getformatname_multiple(codec_buf, sizeof(codec_buf), bridge->technology->format_capabilities),
1625                         ast_getformatname(&write_format));
1626
1627                 /* Switch write format to the best one chosen */
1628                 if (ast_set_write_format(bridge_channel->chan, &best_format)) {
1629                         ast_log(LOG_WARNING, "Failed to set channel %s to write format %s\n",
1630                                 ast_channel_name(bridge_channel->chan), ast_getformatname(&best_format));
1631                         return -1;
1632                 }
1633                 ast_debug(1, "Bridge %s put channel %s into write format %s\n",
1634                         bridge->uniqueid, ast_channel_name(bridge_channel->chan),
1635                         ast_getformatname(&best_format));
1636         } else {
1637                 ast_debug(1, "Bridge %s is happy that channel %s already has write format %s\n",
1638                         bridge->uniqueid, ast_channel_name(bridge_channel->chan),
1639                         ast_getformatname(&write_format));
1640         }
1641
1642         return 0;
1643 }
1644
1645 /*!
1646  * \internal
1647  * \brief Perform the smart bridge operation.
1648  * \since 12.0.0
1649  *
1650  * \param bridge Work on this bridge.
1651  *
1652  * \details
1653  * Basically see if a new bridge technology should be used instead
1654  * of the current one.
1655  *
1656  * \note On entry, bridge is already locked.
1657  *
1658  * \retval 0 on success.
1659  * \retval -1 on error.
1660  */
1661 static int smart_bridge_operation(struct ast_bridge *bridge)
1662 {
1663         uint32_t new_capabilities;
1664         struct ast_bridge_technology *new_technology;
1665         struct ast_bridge_technology *old_technology = bridge->technology;
1666         struct ast_bridge_channel *bridge_channel;
1667         struct ast_frame *deferred_action;
1668         struct ast_bridge dummy_bridge = {
1669                 .technology = bridge->technology,
1670                 .tech_pvt = bridge->tech_pvt,
1671         };
1672
1673         if (bridge->dissolved) {
1674                 ast_debug(1, "Bridge %s is dissolved, not performing smart bridge operation.\n",
1675                         bridge->uniqueid);
1676                 return 0;
1677         }
1678
1679         /* Determine new bridge technology capabilities needed. */
1680         if (2 < bridge->num_channels) {
1681                 new_capabilities = AST_BRIDGE_CAPABILITY_MULTIMIX;
1682                 new_capabilities &= bridge->allowed_capabilities;
1683         } else {
1684                 new_capabilities = AST_BRIDGE_CAPABILITY_NATIVE | AST_BRIDGE_CAPABILITY_1TO1MIX;
1685                 new_capabilities &= bridge->allowed_capabilities;
1686                 if (!new_capabilities
1687                         && (bridge->allowed_capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
1688                         /* Allow switching between different multimix bridge technologies. */
1689                         new_capabilities = AST_BRIDGE_CAPABILITY_MULTIMIX;
1690                 }
1691         }
1692
1693         /* Find a bridge technology to satisfy the new capabilities. */
1694         new_technology = find_best_technology(new_capabilities, bridge);
1695         if (!new_technology) {
1696                 int is_compatible = 0;
1697
1698                 if (old_technology->compatible) {
1699                         is_compatible = old_technology->compatible(bridge);
1700                 } else if (old_technology->capabilities & AST_BRIDGE_CAPABILITY_MULTIMIX) {
1701                         is_compatible = 1;
1702                 } else if (bridge->num_channels <= 2
1703                         && (old_technology->capabilities & AST_BRIDGE_CAPABILITY_1TO1MIX)) {
1704                         is_compatible = 1;
1705                 }
1706
1707                 if (is_compatible) {
1708                         ast_debug(1, "Bridge %s could not get a new technology, staying with old technology.\n",
1709                                 bridge->uniqueid);
1710                         return 0;
1711                 }
1712                 ast_log(LOG_WARNING, "Bridge %s has no technology available to support it.\n",
1713                         bridge->uniqueid);
1714                 return -1;
1715         }
1716         if (new_technology == old_technology) {
1717                 ast_debug(1, "Bridge %s is already using the new technology.\n",
1718                         bridge->uniqueid);
1719                 ast_module_unref(old_technology->mod);
1720                 return 0;
1721         }
1722
1723         ast_copy_string(dummy_bridge.uniqueid, bridge->uniqueid, sizeof(dummy_bridge.uniqueid));
1724
1725         if (old_technology->destroy) {
1726                 struct tech_deferred_destroy deferred_tech_destroy = {
1727                         .tech = dummy_bridge.technology,
1728                         .tech_pvt = dummy_bridge.tech_pvt,
1729                 };
1730                 struct ast_frame action = {
1731                         .frametype = AST_FRAME_BRIDGE_ACTION,
1732                         .subclass.integer = AST_BRIDGE_ACTION_DEFERRED_TECH_DESTROY,
1733                         .data.ptr = &deferred_tech_destroy,
1734                         .datalen = sizeof(deferred_tech_destroy),
1735                 };
1736
1737                 /*
1738                  * We need to defer the bridge technology destroy callback
1739                  * because we have the bridge locked.
1740                  */
1741                 deferred_action = ast_frdup(&action);
1742                 if (!deferred_action) {
1743                         ast_module_unref(new_technology->mod);
1744                         return -1;
1745                 }
1746         } else {
1747                 deferred_action = NULL;
1748         }
1749
1750         /*
1751          * We are now committed to changing the bridge technology.  We
1752          * must not release the bridge lock until we have installed the
1753          * new bridge technology.
1754          */
1755         ast_debug(1, "Bridge %s: switching %s technology to %s\n",
1756                 bridge->uniqueid, old_technology->name, new_technology->name);
1757
1758         /*
1759          * Since we are soon going to pass this bridge to a new
1760          * technology we need to NULL out the tech_pvt pointer but
1761          * don't worry as it still exists in dummy_bridge, ditto for the
1762          * old technology.
1763          */
1764         bridge->tech_pvt = NULL;
1765         bridge->technology = new_technology;
1766
1767         /* Setup the new bridge technology. */
1768         ast_debug(1, "Bridge %s: calling %s technology constructor\n",
1769                 bridge->uniqueid, new_technology->name);
1770         if (new_technology->create && new_technology->create(bridge)) {
1771                 ast_log(LOG_WARNING, "Bridge %s: failed to setup bridge technology %s\n",
1772                         bridge->uniqueid, new_technology->name);
1773                 bridge->tech_pvt = dummy_bridge.tech_pvt;
1774                 bridge->technology = dummy_bridge.technology;
1775                 ast_module_unref(new_technology->mod);
1776                 return -1;
1777         }
1778
1779         ast_debug(1, "Bridge %s: calling %s technology stop\n",
1780                 dummy_bridge.uniqueid, old_technology->name);
1781         if (old_technology->stop) {
1782                 old_technology->stop(&dummy_bridge);
1783         }
1784
1785         /*
1786          * Move existing channels over to the new technology and
1787          * complete joining any new channels to the bridge.
1788          */
1789         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1790                 if (!bridge_channel->just_joined) {
1791                         /* Take existing channel from the old technology. */
1792                         ast_debug(1, "Bridge %s: %p(%s) is leaving %s technology (dummy)\n",
1793                                 dummy_bridge.uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1794                                 old_technology->name);
1795                         if (old_technology->leave) {
1796                                 old_technology->leave(&dummy_bridge, bridge_channel);
1797                         }
1798                 }
1799
1800                 /* Add any new channels or re-add an existing channel to the bridge. */
1801                 bridge_channel_complete_join(bridge, bridge_channel);
1802         }
1803
1804         ast_debug(1, "Bridge %s: calling %s technology start\n",
1805                 bridge->uniqueid, new_technology->name);
1806         if (new_technology->start && new_technology->start(bridge)) {
1807                 ast_log(LOG_WARNING, "Bridge %s: failed to start bridge technology %s\n",
1808                         bridge->uniqueid, new_technology->name);
1809         }
1810
1811         /*
1812          * Now that all the channels have been moved over we need to get
1813          * rid of all the information the old technology may have left
1814          * around.
1815          */
1816         if (old_technology->destroy) {
1817                 ast_debug(1, "Bridge %s: deferring %s technology destructor\n",
1818                         dummy_bridge.uniqueid, old_technology->name);
1819                 bridge_queue_action_nodup(bridge, deferred_action);
1820         } else {
1821                 ast_debug(1, "Bridge %s: calling %s technology destructor\n",
1822                         dummy_bridge.uniqueid, old_technology->name);
1823                 ast_module_unref(old_technology->mod);
1824         }
1825
1826         return 0;
1827 }
1828
1829 /*!
1830  * \internal
1831  * \brief Bridge channel to check if a BRIDGE_PLAY_SOUND needs to be played.
1832  * \since 12.0.0
1833  *
1834  * \param bridge_channel What to check.
1835  *
1836  * \return Nothing
1837  */
1838 static void check_bridge_play_sound(struct ast_bridge_channel *bridge_channel)
1839 {
1840         const char *play_file;
1841
1842         ast_channel_lock(bridge_channel->chan);
1843         play_file = pbx_builtin_getvar_helper(bridge_channel->chan, "BRIDGE_PLAY_SOUND");
1844         if (!ast_strlen_zero(play_file)) {
1845                 play_file = ast_strdupa(play_file);
1846                 pbx_builtin_setvar_helper(bridge_channel->chan, "BRIDGE_PLAY_SOUND", NULL);
1847         } else {
1848                 play_file = NULL;
1849         }
1850         ast_channel_unlock(bridge_channel->chan);
1851
1852         if (play_file) {
1853                 ast_bridge_channel_queue_playfile(bridge_channel, NULL, play_file, NULL);
1854         }
1855 }
1856
1857 /*!
1858  * \internal
1859  * \brief Check for any BRIDGE_PLAY_SOUND channel variables in the bridge.
1860  * \since 12.0.0
1861  *
1862  * \param bridge What to operate on.
1863  *
1864  * \note On entry, the bridge is already locked.
1865  *
1866  * \return Nothing
1867  */
1868 static void check_bridge_play_sounds(struct ast_bridge *bridge)
1869 {
1870         struct ast_bridge_channel *bridge_channel;
1871
1872         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1873                 check_bridge_play_sound(bridge_channel);
1874         }
1875 }
1876
1877 static void update_bridge_vars_set(struct ast_channel *chan, const char *name, const char *pvtid)
1878 {
1879         pbx_builtin_setvar_helper(chan, "BRIDGEPEER", name);
1880         pbx_builtin_setvar_helper(chan, "BRIDGEPVTCALLID", pvtid);
1881 }
1882
1883 /*!
1884  * \internal
1885  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in a 2 party bridge.
1886  * \since 12.0.0
1887  *
1888  * \param c0 Party of the first part.
1889  * \param c1 Party of the second part.
1890  *
1891  * \note On entry, the bridge is already locked.
1892  * \note The bridge is expected to have exactly two parties.
1893  *
1894  * \return Nothing
1895  */
1896 static void set_bridge_peer_vars_2party(struct ast_channel *c0, struct ast_channel *c1)
1897 {
1898         const char *c0_name;
1899         const char *c1_name;
1900         const char *c0_pvtid = NULL;
1901         const char *c1_pvtid = NULL;
1902 #define UPDATE_BRIDGE_VARS_GET(chan, name, pvtid)                                                                       \
1903         do {                                                                                                                                                    \
1904                 name = ast_strdupa(ast_channel_name(chan));                                                                     \
1905                 if (ast_channel_tech(chan)->get_pvt_uniqueid) {                                                         \
1906                         pvtid = ast_strdupa(ast_channel_tech(chan)->get_pvt_uniqueid(chan));    \
1907                 }                                                                                                                                                       \
1908         } while (0)
1909
1910         ast_channel_lock(c1);
1911         UPDATE_BRIDGE_VARS_GET(c1, c1_name, c1_pvtid);
1912         ast_channel_unlock(c1);
1913
1914         ast_channel_lock(c0);
1915         update_bridge_vars_set(c0, c1_name, c1_pvtid);
1916         UPDATE_BRIDGE_VARS_GET(c0, c0_name, c0_pvtid);
1917         ast_channel_unlock(c0);
1918
1919         ast_channel_lock(c1);
1920         update_bridge_vars_set(c1, c0_name, c0_pvtid);
1921         ast_channel_unlock(c1);
1922 }
1923
1924 /*!
1925  * \internal
1926  * \brief Fill the BRIDGEPEER value buffer with a comma separated list of channel names.
1927  * \since 12.0.0
1928  *
1929  * \param buf Buffer to fill.  The caller must guarantee the buffer is large enough.
1930  * \param cur_idx Which index into names[] to skip.
1931  * \param names Channel names to put in the buffer.
1932  * \param num_names Number of names in the array.
1933  *
1934  * \return Nothing
1935  */
1936 static void fill_bridgepeer_buf(char *buf, unsigned int cur_idx, const char *names[], unsigned int num_names)
1937 {
1938         int need_separator = 0;
1939         unsigned int idx;
1940         const char *src;
1941         char *pos;
1942
1943         pos = buf;
1944         for (idx = 0; idx < num_names; ++idx) {
1945                 if (idx == cur_idx) {
1946                         continue;
1947                 }
1948
1949                 if (need_separator) {
1950                         *pos++ = ',';
1951                 }
1952                 need_separator = 1;
1953
1954                 /* Copy name into buffer. */
1955                 src = names[idx];
1956                 while (*src) {
1957                         *pos++ = *src++;
1958                 }
1959         }
1960         *pos = '\0';
1961 }
1962
1963 /*!
1964  * \internal
1965  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in a multi-party bridge.
1966  * \since 12.0.0
1967  *
1968  * \param bridge What to operate on.
1969  *
1970  * \note On entry, the bridge is already locked.
1971  * \note The bridge is expected to have more than two parties.
1972  *
1973  * \return Nothing
1974  */
1975 static void set_bridge_peer_vars_multiparty(struct ast_bridge *bridge)
1976 {
1977 /*
1978  * Set a maximum number of channel names for the BRIDGEPEER
1979  * list.  The plus one is for the current channel which is not
1980  * put in the list.
1981  */
1982 #define MAX_BRIDGEPEER_CHANS    (10 + 1)
1983
1984         unsigned int idx;
1985         unsigned int num_names;
1986         unsigned int len;
1987         const char **names;
1988         char *buf;
1989         struct ast_bridge_channel *bridge_channel;
1990
1991         /* Get first MAX_BRIDGEPEER_CHANS channel names. */
1992         num_names = MIN(bridge->num_channels, MAX_BRIDGEPEER_CHANS);
1993         names = ast_alloca(num_names * sizeof(*names));
1994         idx = 0;
1995         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
1996                 if (num_names <= idx) {
1997                         break;
1998                 }
1999                 ast_channel_lock(bridge_channel->chan);
2000                 names[idx++] = ast_strdupa(ast_channel_name(bridge_channel->chan));
2001                 ast_channel_unlock(bridge_channel->chan);
2002         }
2003
2004         /* Determine maximum buf size needed. */
2005         len = num_names;
2006         for (idx = 0; idx < num_names; ++idx) {
2007                 len += strlen(names[idx]);
2008         }
2009         buf = ast_alloca(len);
2010
2011         /* Set the bridge channel variables. */
2012         idx = 0;
2013         buf[0] = '\0';
2014         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
2015                 if (idx < num_names) {
2016                         fill_bridgepeer_buf(buf, idx, names, num_names);
2017                 }
2018                 ++idx;
2019
2020                 ast_channel_lock(bridge_channel->chan);
2021                 update_bridge_vars_set(bridge_channel->chan, buf, NULL);
2022                 ast_channel_unlock(bridge_channel->chan);
2023         }
2024 }
2025
2026 /*!
2027  * \internal
2028  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in a holding bridge.
2029  * \since 12.0.0
2030  *
2031  * \param bridge What to operate on.
2032  *
2033  * \note On entry, the bridge is already locked.
2034  *
2035  * \return Nothing
2036  */
2037 static void set_bridge_peer_vars_holding(struct ast_bridge *bridge)
2038 {
2039         struct ast_bridge_channel *bridge_channel;
2040
2041         AST_LIST_TRAVERSE(&bridge->channels, bridge_channel, entry) {
2042                 ast_channel_lock(bridge_channel->chan);
2043                 update_bridge_vars_set(bridge_channel->chan, NULL, NULL);
2044                 ast_channel_unlock(bridge_channel->chan);
2045         }
2046 }
2047
2048 /*!
2049  * \internal
2050  * \brief Set BRIDGEPEER and BRIDGEPVTCALLID channel variables in the bridge.
2051  * \since 12.0.0
2052  *
2053  * \param bridge What to operate on.
2054  *
2055  * \note On entry, the bridge is already locked.
2056  *
2057  * \return Nothing
2058  */
2059 static void set_bridge_peer_vars(struct ast_bridge *bridge)
2060 {
2061         if (bridge->technology->capabilities & AST_BRIDGE_CAPABILITY_HOLDING) {
2062                 set_bridge_peer_vars_holding(bridge);
2063                 return;
2064         }
2065         if (bridge->num_channels < 2) {
2066                 return;
2067         }
2068         if (bridge->num_channels == 2) {
2069                 set_bridge_peer_vars_2party(AST_LIST_FIRST(&bridge->channels)->chan,
2070                         AST_LIST_LAST(&bridge->channels)->chan);
2071         } else {
2072                 set_bridge_peer_vars_multiparty(bridge);
2073         }
2074 }
2075
2076 /*!
2077  * \internal
2078  * \brief Notify the bridge that it has been reconfigured.
2079  * \since 12.0.0
2080  *
2081  * \param bridge Reconfigured bridge.
2082  *
2083  * \details
2084  * After a series of bridge_channel_push and
2085  * bridge_channel_pull calls, you need to call this function
2086  * to cause the bridge to complete restruturing for the change
2087  * in the channel makeup of the bridge.
2088  *
2089  * \note On entry, the bridge is already locked.
2090  *
2091  * \return Nothing
2092  */
2093 static void bridge_reconfigured(struct ast_bridge *bridge)
2094 {
2095         if (!bridge->reconfigured) {
2096                 return;
2097         }
2098         bridge->reconfigured = 0;
2099         if (ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_SMART)
2100                 && smart_bridge_operation(bridge)) {
2101                 /* Smart bridge failed. */
2102                 bridge_dissolve(bridge);
2103                 return;
2104         }
2105         bridge_complete_join(bridge);
2106
2107         if (bridge->dissolved) {
2108                 return;
2109         }
2110         check_bridge_play_sounds(bridge);
2111         set_bridge_peer_vars(bridge);
2112 }
2113
2114 /*!
2115  * \internal
2116  * \brief Suspend a channel from a bridge.
2117  *
2118  * \param bridge_channel Channel to suspend.
2119  *
2120  * \note This function assumes bridge_channel->bridge is locked.
2121  *
2122  * \return Nothing
2123  */
2124 static void bridge_channel_suspend_nolock(struct ast_bridge_channel *bridge_channel)
2125 {
2126         bridge_channel->suspended = 1;
2127         if (bridge_channel->in_bridge) {
2128                 --bridge_channel->bridge->num_active;
2129         }
2130
2131         /* Get technology bridge threads off of the channel. */
2132         if (bridge_channel->bridge->technology->suspend) {
2133                 bridge_channel->bridge->technology->suspend(bridge_channel->bridge, bridge_channel);
2134         }
2135 }
2136
2137 /*!
2138  * \internal
2139  * \brief Suspend a channel from a bridge.
2140  *
2141  * \param bridge_channel Channel to suspend.
2142  *
2143  * \return Nothing
2144  */
2145 static void bridge_channel_suspend(struct ast_bridge_channel *bridge_channel)
2146 {
2147         ast_bridge_channel_lock_bridge(bridge_channel);
2148         bridge_channel_suspend_nolock(bridge_channel);
2149         ast_bridge_unlock(bridge_channel->bridge);
2150 }
2151
2152 /*!
2153  * \internal
2154  * \brief Unsuspend a channel from a bridge.
2155  *
2156  * \param bridge_channel Channel to unsuspend.
2157  *
2158  * \note This function assumes bridge_channel->bridge is locked.
2159  *
2160  * \return Nothing
2161  */
2162 static void bridge_channel_unsuspend_nolock(struct ast_bridge_channel *bridge_channel)
2163 {
2164         bridge_channel->suspended = 0;
2165         if (bridge_channel->in_bridge) {
2166                 ++bridge_channel->bridge->num_active;
2167         }
2168
2169         /* Wake technology bridge threads to take care of channel again. */
2170         if (bridge_channel->bridge->technology->unsuspend) {
2171                 bridge_channel->bridge->technology->unsuspend(bridge_channel->bridge, bridge_channel);
2172         }
2173
2174         /* Wake suspended channel. */
2175         ast_bridge_channel_lock(bridge_channel);
2176         ast_cond_signal(&bridge_channel->cond);
2177         ast_bridge_channel_unlock(bridge_channel);
2178 }
2179
2180 /*!
2181  * \internal
2182  * \brief Unsuspend a channel from a bridge.
2183  *
2184  * \param bridge_channel Channel to unsuspend.
2185  *
2186  * \return Nothing
2187  */
2188 static void bridge_channel_unsuspend(struct ast_bridge_channel *bridge_channel)
2189 {
2190         ast_bridge_channel_lock_bridge(bridge_channel);
2191         bridge_channel_unsuspend_nolock(bridge_channel);
2192         ast_bridge_unlock(bridge_channel->bridge);
2193 }
2194
2195 /*! \brief Internal function that activates interval hooks on a bridge channel */
2196 static void bridge_channel_interval(struct ast_bridge_channel *bridge_channel)
2197 {
2198         struct ast_bridge_hook *hook;
2199         struct timeval start;
2200
2201         ast_heap_wrlock(bridge_channel->features->interval_hooks);
2202         start = ast_tvnow();
2203         while ((hook = ast_heap_peek(bridge_channel->features->interval_hooks, 1))) {
2204                 int interval;
2205                 unsigned int execution_time;
2206
2207                 if (ast_tvdiff_ms(hook->parms.timer.trip_time, start) > 0) {
2208                         ast_debug(1, "Hook %p on %p(%s) wants to happen in the future, stopping our traversal\n",
2209                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
2210                         break;
2211                 }
2212                 ao2_ref(hook, +1);
2213                 ast_heap_unlock(bridge_channel->features->interval_hooks);
2214
2215                 ast_debug(1, "Executing hook %p on %p(%s)\n",
2216                         hook, bridge_channel, ast_channel_name(bridge_channel->chan));
2217                 interval = hook->callback(bridge_channel->bridge, bridge_channel, hook->hook_pvt);
2218
2219                 ast_heap_wrlock(bridge_channel->features->interval_hooks);
2220                 if (ast_heap_peek(bridge_channel->features->interval_hooks,
2221                         hook->parms.timer.heap_index) != hook
2222                         || !ast_heap_remove(bridge_channel->features->interval_hooks, hook)) {
2223                         /* Interval hook is already removed from the bridge_channel. */
2224                         ao2_ref(hook, -1);
2225                         continue;
2226                 }
2227                 ao2_ref(hook, -1);
2228
2229                 if (interval < 0) {
2230                         ast_debug(1, "Removed interval hook %p from %p(%s)\n",
2231                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
2232                         ao2_ref(hook, -1);
2233                         continue;
2234                 }
2235                 if (interval) {
2236                         /* Set new interval for the hook. */
2237                         hook->parms.timer.interval = interval;
2238                 }
2239
2240                 ast_debug(1, "Updating interval hook %p with interval %u on %p(%s)\n",
2241                         hook, hook->parms.timer.interval, bridge_channel,
2242                         ast_channel_name(bridge_channel->chan));
2243
2244                 /* resetting start */
2245                 start = ast_tvnow();
2246
2247                 /*
2248                  * Resetup the interval hook for the next interval.  We may need
2249                  * to skip over any missed intervals because the hook was
2250                  * delayed or took too long.
2251                  */
2252                 execution_time = ast_tvdiff_ms(start, hook->parms.timer.trip_time);
2253                 while (hook->parms.timer.interval < execution_time) {
2254                         execution_time -= hook->parms.timer.interval;
2255                 }
2256                 hook->parms.timer.trip_time = ast_tvadd(start, ast_samp2tv(hook->parms.timer.interval - execution_time, 1000));
2257                 hook->parms.timer.seqno = ast_atomic_fetchadd_int((int *) &bridge_channel->features->interval_sequence, +1);
2258
2259                 if (ast_heap_push(bridge_channel->features->interval_hooks, hook)) {
2260                         /* Could not push the hook back onto the heap. */
2261                         ao2_ref(hook, -1);
2262                 }
2263         }
2264         ast_heap_unlock(bridge_channel->features->interval_hooks);
2265 }
2266
2267 static void bridge_channel_write_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
2268 {
2269         ast_bridge_channel_write_action_data(bridge_channel,
2270                 AST_BRIDGE_ACTION_DTMF_STREAM, dtmf, strlen(dtmf) + 1);
2271 }
2272
2273 /*!
2274  * \brief Internal function that executes a feature on a bridge channel
2275  * \note Neither the bridge nor the bridge_channel locks should be held when entering
2276  * this function.
2277  */
2278 static void bridge_channel_feature(struct ast_bridge_channel *bridge_channel)
2279 {
2280         struct ast_bridge_features *features = bridge_channel->features;
2281         struct ast_bridge_hook *hook = NULL;
2282         char dtmf[MAXIMUM_DTMF_FEATURE_STRING] = "";
2283         size_t dtmf_len = 0;
2284         unsigned int digit_timeout;
2285         RAII_VAR(struct ast_features_general_config *, gen_cfg, NULL, ao2_cleanup);
2286
2287         ast_channel_lock(bridge_channel->chan);
2288         gen_cfg = ast_get_chan_features_general_config(bridge_channel->chan);
2289         if (!gen_cfg) {
2290                 ast_log(LOG_ERROR, "Unable to retrieve features configuration.\n");
2291                 ast_channel_unlock(bridge_channel->chan);
2292                 return;
2293         }
2294         digit_timeout = gen_cfg->featuredigittimeout;
2295         ast_channel_unlock(bridge_channel->chan);
2296
2297         /* 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 */
2298         ast_set_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_END_DTMF_ONLY);
2299
2300         /* Wait for DTMF on the channel and put it into a buffer. If the buffer matches any feature hook execute the hook. */
2301         do {
2302                 int res;
2303
2304                 /* If the above timed out simply exit */
2305                 res = ast_waitfordigit(bridge_channel->chan, digit_timeout);
2306                 if (!res) {
2307                         ast_debug(1, "DTMF feature string collection on %p(%s) timed out\n",
2308                                 bridge_channel, ast_channel_name(bridge_channel->chan));
2309                         break;
2310                 }
2311                 if (res < 0) {
2312                         ast_debug(1, "DTMF feature string collection failed on %p(%s) for some reason\n",
2313                                 bridge_channel, ast_channel_name(bridge_channel->chan));
2314                         break;
2315                 }
2316
2317 /* BUGBUG need to record the duration of DTMF digits so when the string is played back, they are reproduced. */
2318                 /* Add the above DTMF into the DTMF string so we can do our matching */
2319                 dtmf[dtmf_len++] = res;
2320                 ast_debug(1, "DTMF feature string on %p(%s) is now '%s'\n",
2321                         bridge_channel, ast_channel_name(bridge_channel->chan), dtmf);
2322
2323                 /* See if a DTMF feature hook matches or can match */
2324                 hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_PARTIAL_KEY);
2325                 if (!hook) {
2326                         ast_debug(1, "No DTMF feature hooks on %p(%s) match '%s'\n",
2327                                 bridge_channel, ast_channel_name(bridge_channel->chan), dtmf);
2328                         break;
2329                 }
2330                 if (strlen(hook->parms.dtmf.code) == dtmf_len) {
2331                         ast_debug(1, "DTMF feature hook %p matched DTMF string '%s' on %p(%s)\n",
2332                                 hook, dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
2333                         break;
2334                 }
2335                 ao2_ref(hook, -1);
2336                 hook = NULL;
2337
2338                 /* Stop if we have reached the maximum length of a DTMF feature string. */
2339         } while (dtmf_len < ARRAY_LEN(dtmf) - 1);
2340
2341         /* Since we are done bringing DTMF in return to using both begin and end frames */
2342         ast_clear_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_END_DTMF_ONLY);
2343
2344         /* If a hook was actually matched execute it on this channel, otherwise stream up the DTMF to the other channels */
2345         if (hook) {
2346                 int failed;
2347
2348                 failed = hook->callback(bridge_channel->bridge, bridge_channel, hook->hook_pvt);
2349                 if (failed) {
2350                         ast_debug(1, "DTMF hook %p is being removed from %p(%s)\n",
2351                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
2352                         ao2_unlink(features->dtmf_hooks, hook);
2353                 }
2354                 ao2_ref(hook, -1);
2355
2356                 /*
2357                  * If we are handing the channel off to an external hook for
2358                  * ownership, we are not guaranteed what kind of state it will
2359                  * come back in.  If the channel hungup, we need to detect that
2360                  * here if the hook did not already change the state.
2361                  */
2362                 if (bridge_channel->chan && ast_check_hangup_locked(bridge_channel->chan)) {
2363                         bridge_handle_hangup(bridge_channel);
2364                 }
2365         } else if (features->dtmf_passthrough) {
2366                 bridge_channel_write_dtmf_stream(bridge_channel, dtmf);
2367         }
2368 }
2369
2370 static void bridge_channel_talking(struct ast_bridge_channel *bridge_channel, int talking)
2371 {
2372         struct ast_bridge_features *features = bridge_channel->features;
2373
2374         if (features->talker_cb) {
2375                 features->talker_cb(bridge_channel, features->talker_pvt_data, talking);
2376         }
2377 }
2378
2379 /*! \brief Internal function that plays back DTMF on a bridge channel */
2380 static void bridge_channel_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
2381 {
2382         ast_debug(1, "Playing DTMF stream '%s' out to %p(%s)\n",
2383                 dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
2384         ast_dtmf_stream(bridge_channel->chan, NULL, dtmf, 0, 0);
2385 }
2386
2387 struct blind_transfer_data {
2388         char exten[AST_MAX_EXTENSION];
2389         char context[AST_MAX_CONTEXT];
2390 };
2391
2392 static void bridge_channel_blind_transfer(struct ast_bridge_channel *bridge_channel,
2393                 struct blind_transfer_data *blind_data)
2394 {
2395         ast_async_goto(bridge_channel->chan, blind_data->context, blind_data->exten, 1);
2396         bridge_handle_hangup(bridge_channel);
2397 }
2398
2399 static void after_bridge_move_channel(struct ast_channel *chan_bridged, void *data)
2400 {
2401         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
2402
2403         if (ast_channel_move(chan_target, chan_bridged)) {
2404                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
2405         }
2406 }
2407
2408 static void after_bridge_move_channel_fail(enum ast_after_bridge_cb_reason reason, void *data)
2409 {
2410         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
2411
2412         ast_log(LOG_WARNING, "Unable to complete transfer: %s\n",
2413                 ast_after_bridge_cb_reason_string(reason));
2414         ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
2415 }
2416
2417 static void bridge_channel_attended_transfer(struct ast_bridge_channel *bridge_channel,
2418                 const char *target_chan_name)
2419 {
2420         RAII_VAR(struct ast_channel *, chan_target, NULL, ao2_cleanup);
2421         RAII_VAR(struct ast_channel *, chan_bridged, NULL, ao2_cleanup);
2422
2423         chan_target = ast_channel_get_by_name(target_chan_name);
2424         if (!chan_target) {
2425                 /* Dang, it disappeared somehow */
2426                 bridge_handle_hangup(bridge_channel);
2427                 return;
2428         }
2429
2430         ast_bridge_channel_lock(bridge_channel);
2431         chan_bridged = bridge_channel->chan;
2432         ast_assert(chan_bridged != NULL);
2433         ao2_ref(chan_bridged, +1);
2434         ast_bridge_channel_unlock(bridge_channel);
2435
2436         if (ast_after_bridge_callback_set(chan_bridged, after_bridge_move_channel,
2437                 after_bridge_move_channel_fail, ast_channel_ref(chan_target))) {
2438                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
2439
2440                 /* Release the ref we tried to pass to ast_after_bridge_callback_set(). */
2441                 ast_channel_unref(chan_target);
2442         }
2443         bridge_handle_hangup(bridge_channel);
2444 }
2445
2446 /*!
2447  * \internal
2448  * \brief Handle bridge channel bridge action frame.
2449  * \since 12.0.0
2450  *
2451  * \param bridge_channel Channel to execute the action on.
2452  * \param action What to do.
2453  *
2454  * \return Nothing
2455  */
2456 static void bridge_channel_handle_action(struct ast_bridge_channel *bridge_channel, struct ast_frame *action)
2457 {
2458         switch (action->subclass.integer) {
2459         case AST_BRIDGE_ACTION_INTERVAL:
2460                 bridge_channel_suspend(bridge_channel);
2461                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2462                 bridge_channel_interval(bridge_channel);
2463                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2464                 bridge_channel_unsuspend(bridge_channel);
2465                 break;
2466         case AST_BRIDGE_ACTION_FEATURE:
2467                 bridge_channel_suspend(bridge_channel);
2468                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2469                 bridge_channel_feature(bridge_channel);
2470                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2471                 bridge_channel_unsuspend(bridge_channel);
2472                 break;
2473         case AST_BRIDGE_ACTION_DTMF_STREAM:
2474                 bridge_channel_suspend(bridge_channel);
2475                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2476                 bridge_channel_dtmf_stream(bridge_channel, action->data.ptr);
2477                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2478                 bridge_channel_unsuspend(bridge_channel);
2479                 break;
2480         case AST_BRIDGE_ACTION_TALKING_START:
2481         case AST_BRIDGE_ACTION_TALKING_STOP:
2482                 bridge_channel_talking(bridge_channel,
2483                         action->subclass.integer == AST_BRIDGE_ACTION_TALKING_START);
2484                 break;
2485         case AST_BRIDGE_ACTION_PLAY_FILE:
2486                 bridge_channel_suspend(bridge_channel);
2487                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2488                 bridge_channel_playfile(bridge_channel, action->data.ptr);
2489                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2490                 bridge_channel_unsuspend(bridge_channel);
2491                 break;
2492         case AST_BRIDGE_ACTION_RUN_APP:
2493                 bridge_channel_suspend(bridge_channel);
2494                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2495                 bridge_channel_run_app(bridge_channel, action->data.ptr);
2496                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2497                 bridge_channel_unsuspend(bridge_channel);
2498                 break;
2499         case AST_BRIDGE_ACTION_CALLBACK:
2500                 bridge_channel_suspend(bridge_channel);
2501                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2502                 bridge_channel_do_callback(bridge_channel, action->data.ptr);
2503                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2504                 bridge_channel_unsuspend(bridge_channel);
2505                 break;
2506         case AST_BRIDGE_ACTION_PARK:
2507                 bridge_channel_suspend(bridge_channel);
2508                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2509                 bridge_channel_park(bridge_channel, action->data.ptr);
2510                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2511                 bridge_channel_unsuspend(bridge_channel);
2512                 break;
2513         case AST_BRIDGE_ACTION_BLIND_TRANSFER:
2514                 bridge_channel_blind_transfer(bridge_channel, action->data.ptr);
2515                 break;
2516         case AST_BRIDGE_ACTION_ATTENDED_TRANSFER:
2517                 bridge_channel_attended_transfer(bridge_channel, action->data.ptr);
2518                 break;
2519         default:
2520                 break;
2521         }
2522 }
2523
2524 /*!
2525  * \internal
2526  * \brief Handle bridge channel control frame action.
2527  * \since 12.0.0
2528  *
2529  * \param bridge_channel Channel to execute the control frame action on.
2530  * \param fr Control frame to handle.
2531  *
2532  * \return Nothing
2533  */
2534 static void bridge_channel_handle_control(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
2535 {
2536         struct ast_channel *chan;
2537         struct ast_option_header *aoh;
2538         int is_caller;
2539         int intercept_failed;
2540
2541         chan = bridge_channel->chan;
2542         switch (fr->subclass.integer) {
2543         case AST_CONTROL_REDIRECTING:
2544                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
2545                 bridge_channel_suspend(bridge_channel);
2546                 intercept_failed = ast_channel_redirecting_sub(NULL, chan, fr, 1)
2547                         && ast_channel_redirecting_macro(NULL, chan, fr, is_caller, 1);
2548                 bridge_channel_unsuspend(bridge_channel);
2549                 if (intercept_failed) {
2550                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2551                 }
2552                 break;
2553         case AST_CONTROL_CONNECTED_LINE:
2554                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
2555                 bridge_channel_suspend(bridge_channel);
2556                 intercept_failed = ast_channel_connected_line_sub(NULL, chan, fr, 1)
2557                         && ast_channel_connected_line_macro(NULL, chan, fr, is_caller, 1);
2558                 bridge_channel_unsuspend(bridge_channel);
2559                 if (intercept_failed) {
2560                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2561                 }
2562                 break;
2563         case AST_CONTROL_HOLD:
2564         case AST_CONTROL_UNHOLD:
2565 /*
2566  * BUGBUG bridge_channels should remember sending/receiving an outstanding HOLD to/from the bridge
2567  *
2568  * When the sending channel is pulled from the bridge it needs to write into the bridge an UNHOLD before being pulled.
2569  * When the receiving channel is pulled from the bridge it needs to generate its own UNHOLD.
2570  * Something similar needs to be done for DTMF begin/end.
2571  */
2572         case AST_CONTROL_VIDUPDATE:
2573         case AST_CONTROL_SRCUPDATE:
2574         case AST_CONTROL_SRCCHANGE:
2575         case AST_CONTROL_T38_PARAMETERS:
2576 /* BUGBUG may have to do something with a jitter buffer for these. */
2577                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2578                 break;
2579         case AST_CONTROL_OPTION:
2580                 /*
2581                  * Forward option Requests, but only ones we know are safe These
2582                  * are ONLY sent by chan_iax2 and I'm not convinced that they
2583                  * are useful. I haven't deleted them entirely because I just am
2584                  * not sure of the ramifications of removing them.
2585                  */
2586                 aoh = fr->data.ptr;
2587                 if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
2588                         switch (ntohs(aoh->option)) {
2589                         case AST_OPTION_TONE_VERIFY:
2590                         case AST_OPTION_TDD:
2591                         case AST_OPTION_RELAXDTMF:
2592                         case AST_OPTION_AUDIO_MODE:
2593                         case AST_OPTION_DIGIT_DETECT:
2594                         case AST_OPTION_FAX_DETECT:
2595                                 ast_channel_setoption(chan, ntohs(aoh->option), aoh->data,
2596                                         fr->datalen - sizeof(*aoh), 0);
2597                                 break;
2598                         default:
2599                                 break;
2600                         }
2601                 }
2602                 break;
2603         case AST_CONTROL_ANSWER:
2604                 if (ast_channel_state(chan) != AST_STATE_UP) {
2605                         ast_answer(chan);
2606                 } else {
2607                         ast_indicate(chan, -1);
2608                 }
2609                 break;
2610         default:
2611                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
2612                 break;
2613         }
2614 }
2615
2616 /*!
2617  * \internal
2618  * \brief Handle bridge channel write frame to channel.
2619  * \since 12.0.0
2620  *
2621  * \param bridge_channel Channel to write outgoing frame.
2622  *
2623  * \return Nothing
2624  */
2625 static void bridge_channel_handle_write(struct ast_bridge_channel *bridge_channel)
2626 {
2627         struct ast_frame *fr;
2628         char nudge;
2629
2630         ast_bridge_channel_lock(bridge_channel);
2631         if (read(bridge_channel->alert_pipe[0], &nudge, sizeof(nudge)) < 0) {
2632                 if (errno != EINTR && errno != EAGAIN) {
2633                         ast_log(LOG_WARNING, "read() failed for alert pipe on %p(%s): %s\n",
2634                                 bridge_channel, ast_channel_name(bridge_channel->chan), strerror(errno));
2635                 }
2636         }
2637         fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list);
2638         ast_bridge_channel_unlock(bridge_channel);
2639         if (!fr) {
2640                 return;
2641         }
2642         switch (fr->frametype) {
2643         case AST_FRAME_BRIDGE_ACTION:
2644                 bridge_channel_handle_action(bridge_channel, fr);
2645                 break;
2646         case AST_FRAME_CONTROL:
2647                 bridge_channel_handle_control(bridge_channel, fr);
2648                 break;
2649         case AST_FRAME_NULL:
2650                 break;
2651         default:
2652                 /* Write the frame to the channel. */
2653                 bridge_channel->activity = AST_BRIDGE_CHANNEL_THREAD_SIMPLE;
2654                 ast_write(bridge_channel->chan, fr);
2655                 break;
2656         }
2657         ast_frfree(fr);
2658 }
2659
2660 /*!
2661  * \internal
2662  * \brief Handle bridge channel interval expiration.
2663  * \since 12.0.0
2664  *
2665  * \param bridge_channel Channel to check interval on.
2666  *
2667  * \return Nothing
2668  */
2669 static void bridge_channel_handle_interval(struct ast_bridge_channel *bridge_channel)
2670 {
2671         struct ast_timer *interval_timer;
2672
2673         interval_timer = bridge_channel->features->interval_timer;
2674         if (interval_timer) {
2675                 if (ast_wait_for_input(ast_timer_fd(interval_timer), 0) == 1) {
2676                         ast_timer_ack(interval_timer, 1);
2677                         if (bridge_channel_interval_ready(bridge_channel)) {
2678 /* 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(). */
2679                                 struct ast_frame interval_action = {
2680                                         .frametype = AST_FRAME_BRIDGE_ACTION,
2681                                         .subclass.integer = AST_BRIDGE_ACTION_INTERVAL,
2682                                 };
2683
2684                                 ast_bridge_channel_queue_frame(bridge_channel, &interval_action);
2685                         }
2686                 }
2687         }
2688 }
2689
2690 /*!
2691  * \internal
2692  * \brief Wait for something to happen on the bridge channel and handle it.
2693  * \since 12.0.0
2694  *
2695  * \param bridge_channel Channel to wait.
2696  *
2697  * \note Each channel does writing/reading in their own thread.
2698  *
2699  * \return Nothing
2700  */
2701 static void bridge_channel_wait(struct ast_bridge_channel *bridge_channel)
2702 {
2703         int ms = -1;
2704         int outfd;
2705         struct ast_channel *chan;
2706
2707         /* Wait for data to either come from the channel or us to be signaled */
2708         ast_bridge_channel_lock(bridge_channel);
2709         if (bridge_channel->state != AST_BRIDGE_CHANNEL_STATE_WAIT) {
2710         } else if (bridge_channel->suspended) {
2711 /* BUGBUG the external party use of suspended will go away as will these references because this is the bridge channel thread */
2712                 ast_debug(1, "Bridge %s: %p(%s) is going into a signal wait\n",
2713                         bridge_channel->bridge->uniqueid, bridge_channel,
2714                         ast_channel_name(bridge_channel->chan));
2715                 ast_cond_wait(&bridge_channel->cond, ao2_object_get_lockaddr(bridge_channel));
2716         } else {
2717                 ast_debug(10, "Bridge %s: %p(%s) is going into a waitfor\n",
2718                         bridge_channel->bridge->uniqueid, bridge_channel,
2719                         ast_channel_name(bridge_channel->chan));
2720                 bridge_channel->waiting = 1;
2721                 ast_bridge_channel_unlock(bridge_channel);
2722                 outfd = -1;
2723 /* BUGBUG need to make the next expiring active interval setup ms timeout rather than holding up the chan reads. */
2724                 chan = ast_waitfor_nandfds(&bridge_channel->chan, 1,
2725                         &bridge_channel->alert_pipe[0], 1, NULL, &outfd, &ms);
2726                 bridge_channel->waiting = 0;
2727                 if (ast_channel_softhangup_internal_flag(bridge_channel->chan) & AST_SOFTHANGUP_UNBRIDGE) {
2728                         ast_channel_clear_softhangup(bridge_channel->chan, AST_SOFTHANGUP_UNBRIDGE);
2729                         ast_bridge_channel_lock_bridge(bridge_channel);
2730                         bridge_channel->bridge->reconfigured = 1;
2731                         bridge_reconfigured(bridge_channel->bridge);
2732                         ast_bridge_unlock(bridge_channel->bridge);
2733                 }
2734                 ast_bridge_channel_lock(bridge_channel);
2735                 bridge_channel->activity = AST_BRIDGE_CHANNEL_THREAD_FRAME;
2736                 ast_bridge_channel_unlock(bridge_channel);
2737                 if (!bridge_channel->suspended
2738                         && bridge_channel->state == AST_BRIDGE_CHANNEL_STATE_WAIT) {
2739                         if (chan) {
2740                                 bridge_channel_handle_interval(bridge_channel);
2741                                 bridge_handle_trip(bridge_channel);
2742                         } else if (-1 < outfd) {
2743                                 bridge_channel_handle_write(bridge_channel);
2744                         }
2745                 }
2746                 bridge_channel->activity = AST_BRIDGE_CHANNEL_THREAD_IDLE;
2747                 return;
2748         }
2749         ast_bridge_channel_unlock(bridge_channel);
2750 }
2751
2752 /*!
2753  * \internal
2754  * \brief Handle bridge channel join event.
2755  * \since 12.0.0
2756  *
2757  * \param bridge_channel Which channel is joining.
2758  *
2759  * \return Nothing
2760  */
2761 static void bridge_channel_handle_join(struct ast_bridge_channel *bridge_channel)
2762 {
2763         struct ast_bridge_features *features = bridge_channel->features;
2764         struct ast_bridge_hook *hook;
2765         struct ao2_iterator iter;
2766
2767         /* Run any join hooks. */
2768         iter = ao2_iterator_init(features->join_hooks, AO2_ITERATOR_UNLINK);
2769         hook = ao2_iterator_next(&iter);
2770         if (hook) {
2771                 bridge_channel_suspend(bridge_channel);
2772                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2773                 do {
2774                         hook->callback(bridge_channel->bridge, bridge_channel, hook->hook_pvt);
2775                         ao2_ref(hook, -1);
2776                 } while ((hook = ao2_iterator_next(&iter)));
2777                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2778                 bridge_channel_unsuspend(bridge_channel);
2779         }
2780         ao2_iterator_destroy(&iter);
2781 }
2782
2783 /*!
2784  * \internal
2785  * \brief Handle bridge channel leave event.
2786  * \since 12.0.0
2787  *
2788  * \param bridge_channel Which channel is leaving.
2789  *
2790  * \return Nothing
2791  */
2792 static void bridge_channel_handle_leave(struct ast_bridge_channel *bridge_channel)
2793 {
2794         struct ast_bridge_features *features = bridge_channel->features;
2795         struct ast_bridge_hook *hook;
2796         struct ao2_iterator iter;
2797
2798         /* Run any leave hooks. */
2799         iter = ao2_iterator_init(features->leave_hooks, AO2_ITERATOR_UNLINK);
2800         hook = ao2_iterator_next(&iter);
2801         if (hook) {
2802                 bridge_channel_suspend(bridge_channel);
2803                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2804                 do {
2805                         hook->callback(bridge_channel->bridge, bridge_channel, hook->hook_pvt);
2806                         ao2_ref(hook, -1);
2807                 } while ((hook = ao2_iterator_next(&iter)));
2808                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
2809                 bridge_channel_unsuspend(bridge_channel);
2810         }
2811         ao2_iterator_destroy(&iter);
2812 }
2813
2814 /*! \brief Join a channel to a bridge and handle anything the bridge may want us to do */
2815 static void bridge_channel_join(struct ast_bridge_channel *bridge_channel)
2816 {
2817         ast_format_copy(&bridge_channel->read_format, ast_channel_readformat(bridge_channel->chan));
2818         ast_format_copy(&bridge_channel->write_format, ast_channel_writeformat(bridge_channel->chan));
2819
2820         ast_debug(1, "Bridge %s: %p(%s) is joining\n",
2821                 bridge_channel->bridge->uniqueid,
2822                 bridge_channel, ast_channel_name(bridge_channel->chan));
2823
2824         /*
2825          * Get "in the bridge" before pushing the channel for any
2826          * masquerades on the channel to happen before bridging.
2827          */
2828         ast_channel_lock(bridge_channel->chan);
2829         ast_channel_internal_bridge_set(bridge_channel->chan, bridge_channel->bridge);
2830         ast_channel_unlock(bridge_channel->chan);
2831
2832         /* Add the jitterbuffer if the channel requires it */
2833         ast_jb_enable_for_channel(bridge_channel->chan);
2834
2835         /*
2836          * Directly locking the bridge is safe here because nobody else
2837          * knows about this bridge_channel yet.
2838          */
2839         ast_bridge_lock(bridge_channel->bridge);
2840
2841         if (!bridge_channel->bridge->callid) {
2842                 bridge_channel->bridge->callid = ast_read_threadstorage_callid();
2843         }
2844
2845         if (bridge_channel_push(bridge_channel)) {
2846                 ast_bridge_change_state(bridge_channel, AST_BRIDGE_CHANNEL_STATE_HANGUP);
2847         }
2848         bridge_reconfigured(bridge_channel->bridge);
2849
2850         if (bridge_channel->state == AST_BRIDGE_CHANNEL_STATE_WAIT) {
2851                 /*
2852                  * Indicate a source change since this channel is entering the
2853                  * bridge system only if the bridge technology is not MULTIMIX
2854                  * capable.  The MULTIMIX technology has already done it.
2855                  */
2856                 if (!(bridge_channel->bridge->technology->capabilities
2857                         & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
2858                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2859                 }
2860
2861                 ast_bridge_unlock(bridge_channel->bridge);
2862                 bridge_channel_handle_join(bridge_channel);
2863                 while (bridge_channel->state == AST_BRIDGE_CHANNEL_STATE_WAIT) {
2864                         /* Wait for something to do. */
2865                         bridge_channel_wait(bridge_channel);
2866                 }
2867                 bridge_channel_handle_leave(bridge_channel);
2868                 ast_bridge_channel_lock_bridge(bridge_channel);
2869         }
2870
2871         bridge_channel_pull(bridge_channel);
2872         bridge_reconfigured(bridge_channel->bridge);
2873
2874         ast_bridge_unlock(bridge_channel->bridge);
2875
2876         /* Indicate a source change since this channel is leaving the bridge system. */
2877         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2878
2879 /* BUGBUG Revisit in regards to moving channels between bridges and local channel optimization. */
2880 /* BUGBUG This is where outgoing HOLD/UNHOLD memory should write UNHOLD to channel. */
2881         /* Complete any partial DTMF digit before exiting the bridge. */
2882         if (ast_channel_sending_dtmf_digit(bridge_channel->chan)) {
2883                 ast_bridge_end_dtmf(bridge_channel->chan,
2884                         ast_channel_sending_dtmf_digit(bridge_channel->chan),
2885                         ast_channel_sending_dtmf_tv(bridge_channel->chan), "bridge end");
2886         }
2887
2888         /*
2889          * Wait for any dual redirect to complete.
2890          *
2891          * Must be done while "still in the bridge" for ast_async_goto()
2892          * to work right.
2893          */
2894         while (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT)) {
2895                 sched_yield();
2896         }
2897         ast_channel_lock(bridge_channel->chan);
2898         ast_channel_internal_bridge_set(bridge_channel->chan, NULL);
2899         ast_channel_unlock(bridge_channel->chan);
2900
2901         ast_bridge_channel_restore_formats(bridge_channel);
2902 }
2903
2904 /*!
2905  * \internal
2906  * \brief Close a pipe.
2907  * \since 12.0.0
2908  *
2909  * \param my_pipe What to close.
2910  *
2911  * \return Nothing
2912  */
2913 static void pipe_close(int *my_pipe)
2914 {
2915         if (my_pipe[0] > -1) {
2916                 close(my_pipe[0]);
2917                 my_pipe[0] = -1;
2918         }
2919         if (my_pipe[1] > -1) {
2920                 close(my_pipe[1]);
2921                 my_pipe[1] = -1;
2922         }
2923 }
2924
2925 /*!
2926  * \internal
2927  * \brief Initialize a pipe as non-blocking.
2928  * \since 12.0.0
2929  *
2930  * \param my_pipe What to initialize.
2931  *
2932  * \retval 0 on success.
2933  * \retval -1 on error.
2934  */
2935 static int pipe_init_nonblock(int *my_pipe)
2936 {
2937         int flags;
2938
2939         my_pipe[0] = -1;
2940         my_pipe[1] = -1;
2941         if (pipe(my_pipe)) {
2942                 ast_log(LOG_WARNING, "Can't create pipe! Try increasing max file descriptors with ulimit -n\n");
2943                 return -1;
2944         }
2945         flags = fcntl(my_pipe[0], F_GETFL);
2946         if (fcntl(my_pipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
2947                 ast_log(LOG_WARNING, "Unable to set read pipe nonblocking! (%d: %s)\n",
2948                         errno, strerror(errno));
2949                 return -1;
2950         }
2951         flags = fcntl(my_pipe[1], F_GETFL);
2952         if (fcntl(my_pipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
2953                 ast_log(LOG_WARNING, "Unable to set write pipe nonblocking! (%d: %s)\n",
2954                         errno, strerror(errno));
2955                 return -1;
2956         }
2957         return 0;
2958 }
2959
2960 /* Destroy elements of the bridge channel structure and the bridge channel structure itself */
2961 static void bridge_channel_destroy(void *obj)
2962 {
2963         struct ast_bridge_channel *bridge_channel = obj;
2964         struct ast_frame *fr;
2965
2966         if (bridge_channel->callid) {
2967                 bridge_channel->callid = ast_callid_unref(bridge_channel->callid);
2968         }
2969
2970         if (bridge_channel->bridge) {
2971                 ao2_ref(bridge_channel->bridge, -1);
2972                 bridge_channel->bridge = NULL;
2973         }
2974
2975         /* Flush any unhandled wr_queue frames. */
2976         while ((fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list))) {
2977                 ast_frfree(fr);
2978         }
2979         pipe_close(bridge_channel->alert_pipe);
2980
2981         ast_cond_destroy(&bridge_channel->cond);
2982 }
2983
2984 static struct ast_bridge_channel *bridge_channel_alloc(struct ast_bridge *bridge)
2985 {
2986         struct ast_bridge_channel *bridge_channel;
2987
2988         bridge_channel = ao2_alloc(sizeof(struct ast_bridge_channel), bridge_channel_destroy);
2989         if (!bridge_channel) {
2990                 return NULL;
2991         }
2992         ast_cond_init(&bridge_channel->cond, NULL);
2993         if (pipe_init_nonblock(bridge_channel->alert_pipe)) {
2994                 ao2_ref(bridge_channel, -1);
2995                 return NULL;
2996         }
2997         if (bridge) {
2998                 bridge_channel->bridge = bridge;
2999                 ao2_ref(bridge_channel->bridge, +1);
3000         }
3001
3002         return bridge_channel;
3003 }
3004
3005 struct after_bridge_cb_ds {
3006         /*! Desired callback function. */
3007         ast_after_bridge_cb callback;
3008         /*! After bridge callback will not be called and destroy any resources data may contain. */
3009         ast_after_bridge_cb_failed failed;
3010         /*! Extra data to pass to the callback. */
3011         void *data;
3012 };
3013
3014 /*!
3015  * \internal
3016  * \brief Destroy the after bridge callback datastore.
3017  * \since 12.0.0
3018  *
3019  * \param data After bridge callback data to destroy.
3020  *
3021  * \return Nothing
3022  */
3023 static void after_bridge_cb_destroy(void *data)
3024 {
3025         struct after_bridge_cb_ds *after_bridge = data;
3026
3027         if (after_bridge->failed) {
3028                 after_bridge->failed(AST_AFTER_BRIDGE_CB_REASON_DESTROY, after_bridge->data);
3029                 after_bridge->failed = NULL;
3030         }
3031 }
3032
3033 /*!
3034  * \internal
3035  * \brief Fixup the after bridge callback datastore.
3036  * \since 12.0.0
3037  *
3038  * \param data After bridge callback data to fixup.
3039  * \param old_chan The datastore is moving from this channel.
3040  * \param new_chan The datastore is moving to this channel.
3041  *
3042  * \return Nothing
3043  */
3044 static void after_bridge_cb_fixup(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan)
3045 {
3046         /* There can be only one.  Discard any already on the new channel. */
3047         ast_after_bridge_callback_discard(new_chan, AST_AFTER_BRIDGE_CB_REASON_MASQUERADE);
3048 }
3049
3050 static const struct ast_datastore_info after_bridge_cb_info = {
3051         .type = "after-bridge-cb",
3052         .destroy = after_bridge_cb_destroy,
3053         .chan_fixup = after_bridge_cb_fixup,
3054 };
3055
3056 /*!
3057  * \internal
3058  * \brief Remove channel after the bridge callback and return it.
3059  * \since 12.0.0
3060  *
3061  * \param chan Channel to remove after bridge callback.
3062  *
3063  * \retval datastore on success.
3064  * \retval NULL on error or not found.
3065  */
3066 static struct ast_datastore *after_bridge_cb_remove(struct ast_channel *chan)
3067 {
3068         struct ast_datastore *datastore;
3069
3070         ast_channel_lock(chan);
3071         datastore = ast_channel_datastore_find(chan, &after_bridge_cb_info, NULL);
3072         if (datastore && ast_channel_datastore_remove(chan, datastore)) {
3073                 datastore = NULL;
3074         }
3075         ast_channel_unlock(chan);
3076
3077         return datastore;
3078 }
3079
3080 void ast_after_bridge_callback_discard(struct ast_channel *chan, enum ast_after_bridge_cb_reason reason)
3081 {
3082         struct ast_datastore *datastore;
3083
3084         datastore = after_bridge_cb_remove(chan);
3085         if (datastore) {
3086                 struct after_bridge_cb_ds *after_bridge = datastore->data;
3087
3088                 if (after_bridge && after_bridge->failed) {
3089                         after_bridge->failed(reason, after_bridge->data);
3090                         after_bridge->failed = NULL;
3091                 }
3092                 ast_datastore_free(datastore);
3093         }
3094 }
3095
3096 /*!
3097  * \internal
3098  * \brief Run any after bridge callback if possible.
3099  * \since 12.0.0
3100  *
3101  * \param chan Channel to run after bridge callback.
3102  *
3103  * \return Nothing
3104  */
3105 static void after_bridge_callback_run(struct ast_channel *chan)
3106 {
3107         struct ast_datastore *datastore;
3108         struct after_bridge_cb_ds *after_bridge;
3109
3110         if (ast_check_hangup(chan)) {
3111                 return;
3112         }
3113
3114         /* Get after bridge goto datastore. */
3115         datastore = after_bridge_cb_remove(chan);
3116         if (!datastore) {
3117                 return;
3118         }
3119
3120         after_bridge = datastore->data;
3121         if (after_bridge) {
3122                 after_bridge->failed = NULL;
3123                 after_bridge->callback(chan, after_bridge->data);
3124         }
3125
3126         /* Discard after bridge callback datastore. */
3127         ast_datastore_free(datastore);
3128 }
3129
3130 int ast_after_bridge_callback_set(struct ast_channel *chan, ast_after_bridge_cb callback, ast_after_bridge_cb_failed failed, void *data)
3131 {
3132         struct ast_datastore *datastore;
3133         struct after_bridge_cb_ds *after_bridge;
3134
3135         /* Sanity checks. */
3136         ast_assert(chan != NULL);
3137         if (!chan || !callback) {
3138                 return -1;
3139         }
3140
3141         /* Create a new datastore. */
3142         datastore = ast_datastore_alloc(&after_bridge_cb_info, NULL);
3143         if (!datastore) {
3144                 return -1;
3145         }
3146         after_bridge = ast_calloc(1, sizeof(*after_bridge));
3147         if (!after_bridge) {
3148                 ast_datastore_free(datastore);
3149                 return -1;
3150         }
3151
3152         /* Initialize it. */
3153         after_bridge->callback = callback;
3154         after_bridge->failed = failed;
3155         after_bridge->data = data;
3156         datastore->data = after_bridge;
3157
3158         /* Put it on the channel replacing any existing one. */
3159         ast_channel_lock(chan);
3160         ast_after_bridge_callback_discard(chan, AST_AFTER_BRIDGE_CB_REASON_REPLACED);
3161         ast_channel_datastore_add(chan, datastore);
3162         ast_channel_unlock(chan);
3163
3164         return 0;
3165 }
3166
3167 const char *reason_strings[] = {
3168         [AST_AFTER_BRIDGE_CB_REASON_DESTROY] = "Bridge Destroyed",
3169         [AST_AFTER_BRIDGE_CB_REASON_REPLACED] = "Channel replaced",
3170         [AST_AFTER_BRIDGE_CB_REASON_MASQUERADE] = "Channel masqueraded",
3171         [AST_AFTER_BRIDGE_CB_REASON_DEPART] = "Channel departed",
3172         [AST_AFTER_BRIDGE_CB_REASON_REMOVED] = "Channel removed",
3173 };
3174
3175 const char *ast_after_bridge_cb_reason_string(enum ast_after_bridge_cb_reason reason)
3176 {
3177         if (reason < AST_AFTER_BRIDGE_CB_REASON_DESTROY || reason > AST_AFTER_BRIDGE_CB_REASON_REMOVED) {
3178                 return "Unknown";
3179         }
3180
3181         return reason_strings[reason];
3182 }
3183
3184 struct after_bridge_goto_ds {
3185         /*! Goto string that can be parsed by ast_parseable_goto(). */
3186         const char *parseable_goto;
3187         /*! Specific goto context or default context for parseable_goto. */
3188         const char *context;
3189         /*! Specific goto exten or default exten for parseable_goto. */
3190         const char *exten;
3191         /*! Specific goto priority or default priority for parseable_goto. */
3192         int priority;
3193         /*! TRUE if the peer should run the h exten. */
3194         unsigned int run_h_exten:1;
3195         /*! Specific goto location */
3196         unsigned int specific:1;
3197 };
3198
3199 /*!
3200  * \internal
3201  * \brief Destroy the after bridge goto datastore.
3202  * \since 12.0.0
3203  *
3204  * \param data After bridge goto data to destroy.
3205  *
3206  * \return Nothing
3207  */
3208 static void after_bridge_goto_destroy(void *data)
3209 {
3210         struct after_bridge_goto_ds *after_bridge = data;
3211
3212         ast_free((char *) after_bridge->parseable_goto);
3213         ast_free((char *) after_bridge->context);
3214         ast_free((char *) after_bridge->exten);
3215 }
3216
3217 /*!
3218  * \internal
3219  * \brief Fixup the after bridge goto datastore.
3220  * \since 12.0.0
3221  *
3222  * \param data After bridge goto data to fixup.
3223  * \param old_chan The datastore is moving from this channel.
3224  * \param new_chan The datastore is moving to this channel.
3225  *
3226  * \return Nothing
3227  */
3228 static void after_bridge_goto_fixup(void *data, struct ast_channel *old_chan, struct ast_channel *new_chan)
3229 {
3230         /* There can be only one.  Discard any already on the new channel. */
3231         ast_after_bridge_goto_discard(new_chan);
3232 }
3233
3234 static const struct ast_datastore_info after_bridge_goto_info = {
3235         .type = "after-bridge-goto",
3236         .destroy = after_bridge_goto_destroy,
3237         .chan_fixup = after_bridge_goto_fixup,
3238 };
3239
3240 /*!
3241  * \internal
3242  * \brief Remove channel goto location after the bridge and return it.
3243  * \since 12.0.0
3244  *
3245  * \param chan Channel to remove after bridge goto location.
3246  *
3247  * \retval datastore on success.
3248  * \retval NULL on error or not found.
3249  */
3250 static struct ast_datastore *after_bridge_goto_remove(struct ast_channel *chan)
3251 {
3252         struct ast_datastore *datastore;
3253
3254         ast_channel_lock(chan);
3255         datastore = ast_channel_datastore_find(chan, &after_bridge_goto_info, NULL);
3256         if (datastore && ast_channel_datastore_remove(chan, datastore)) {
3257                 datastore = NULL;
3258         }
3259         ast_channel_unlock(chan);
3260
3261         return datastore;
3262 }
3263
3264 void ast_after_bridge_goto_discard(struct ast_channel *chan)
3265 {
3266         struct ast_datastore *datastore;
3267
3268         datastore = after_bridge_goto_remove(chan);
3269         if (datastore) {
3270                 ast_datastore_free(datastore);
3271         }
3272 }
3273
3274 int ast_after_bridge_goto_setup(struct ast_channel *chan)
3275 {
3276         struct ast_datastore *datastore;
3277         struct after_bridge_goto_ds *after_bridge;
3278         int goto_failed = -1;
3279
3280         /* Determine if we are going to setup a dialplan location and where. */
3281         if (ast_channel_softhangup_internal_flag(chan) & AST_SOFTHANGUP_ASYNCGOTO) {
3282                 /* An async goto has already setup a location. */
3283                 ast_channel_clear_softhangup(chan, AST_SOFTHANGUP_ASYNCGOTO);
3284                 if (!ast_check_hangup(chan)) {
3285                         goto_failed = 0;
3286                 }
3287                 return goto_failed;
3288         }
3289
3290         /* Get after bridge goto datastore. */
3291         datastore = after_bridge_goto_remove(chan);
3292         if (!datastore) {
3293                 return goto_failed;
3294         }
3295
3296         after_bridge = datastore->data;
3297         if (after_bridge->run_h_exten) {
3298                 if (ast_exists_extension(chan, after_bridge->context, "h", 1,
3299                         S_COR(ast_channel_caller(chan)->id.number.valid,
3300                                 ast_channel_caller(chan)->id.number.str, NULL))) {
3301                         ast_debug(1, "Running after bridge goto h exten %s,h,1\n",
3302                                 ast_channel_context(chan));
3303                         ast_pbx_h_exten_run(chan, after_bridge->context);
3304                 }
3305         } else if (!ast_check_hangup(chan)) {
3306                 if (after_bridge->specific) {
3307                         goto_failed = ast_explicit_goto(chan, after_bridge->context,
3308                                 after_bridge->exten, after_bridge->priority);
3309                 } else if (!ast_strlen_zero(after_bridge->parseable_goto)) {
3310                         char *context;
3311                         char *exten;
3312                         int priority;
3313
3314                         /* Option F(x) for Bridge(), Dial(), and Queue() */
3315
3316                         /* Save current dialplan location in case of failure. */
3317                         context = ast_strdupa(ast_channel_context(chan));
3318                         exten = ast_strdupa(ast_channel_exten(chan));
3319                         priority = ast_channel_priority(chan);
3320
3321                         /* Set current dialplan position to default dialplan position */
3322                         ast_explicit_goto(chan, after_bridge->context, after_bridge->exten,
3323                                 after_bridge->priority);
3324
3325                         /* Then perform the goto */
3326                         goto_failed = ast_parseable_goto(chan, after_bridge->parseable_goto);
3327                         if (goto_failed) {
3328                                 /* Restore original dialplan location. */
3329                                 ast_channel_context_set(chan, context);
3330                                 ast_channel_exten_set(chan, exten);
3331                                 ast_channel_priority_set(chan, priority);
3332                         }
3333                 } else {
3334                         /* Option F() for Bridge(), Dial(), and Queue() */
3335                         goto_failed = ast_goto_if_exists(chan, after_bridge->context,
3336                                 after_bridge->exten, after_bridge->priority + 1);
3337                 }
3338                 if (!goto_failed) {
3339                         ast_debug(1, "Setup after bridge goto location to %s,%s,%d.\n",
3340                                 ast_channel_context(chan),
3341                                 ast_channel_exten(chan),
3342                                 ast_channel_priority(chan));
3343                 }
3344         }
3345
3346         /* Discard after bridge goto datastore. */
3347         ast_datastore_free(datastore);
3348
3349         return goto_failed;
3350 }
3351
3352 void ast_after_bridge_goto_run(struct ast_channel *chan)
3353 {
3354         int goto_failed;
3355
3356         goto_failed = ast_after_bridge_goto_setup(chan);
3357         if (goto_failed || ast_pbx_run(chan)) {
3358                 ast_hangup(chan);
3359         }
3360 }
3361
3362 /*!
3363  * \internal
3364  * \brief Set after bridge goto location of channel.
3365  * \since 12.0.0
3366  *
3367  * \param chan Channel to setup after bridge goto location.
3368  * \param run_h_exten TRUE if the h exten should be run.
3369  * \param specific TRUE if the context/exten/priority is exactly specified.
3370  * \param context Context to goto after bridge.
3371  * \param exten Exten to goto after bridge. (Could be NULL if run_h_exten)
3372  * \param priority Priority to goto after bridge.
3373  * \param parseable_goto User specified goto string. (Could be NULL)
3374  *
3375  * \details Add a channel datastore to setup the goto location
3376  * when the channel leaves the bridge and run a PBX from there.
3377  *
3378  * If run_h_exten then execute the h exten found in the given context.
3379  * Else if specific then goto the given context/exten/priority.
3380  * Else if parseable_goto then use the given context/exten/priority
3381  *   as the relative position for the parseable_goto.
3382  * Else goto the given context/exten/priority+1.
3383  *
3384  * \return Nothing
3385  */
3386 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)
3387 {
3388         struct ast_datastore *datastore;
3389         struct after_bridge_goto_ds *after_bridge;
3390
3391         /* Sanity checks. */