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