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