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