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