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