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