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