channel locking: Add locking for channel snapshot creation
[asterisk/asterisk.git] / main / bridge_channel.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 Bridging Channel API
22  *
23  * \author Joshua Colp <jcolp@digium.com>
24  * \author Richard Mudgett <rmudgett@digium.com>
25  * \author Matt Jordan <mjordan@digium.com>
26  *
27  */
28
29 /*** MODULEINFO
30         <support_level>core</support_level>
31  ***/
32
33 #include "asterisk.h"
34
35 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
36
37 #include <signal.h>
38
39 #include "asterisk/heap.h"
40 #include "asterisk/astobj2.h"
41 #include "asterisk/stringfields.h"
42 #include "asterisk/app.h"
43 #include "asterisk/pbx.h"
44 #include "asterisk/channel.h"
45 #include "asterisk/timing.h"
46 #include "asterisk/bridge.h"
47 #include "asterisk/bridge_channel.h"
48 #include "asterisk/bridge_after.h"
49 #include "asterisk/bridge_channel_internal.h"
50 #include "asterisk/bridge_internal.h"
51 #include "asterisk/stasis_bridges.h"
52 #include "asterisk/stasis_channels.h"
53 #include "asterisk/musiconhold.h"
54 #include "asterisk/features_config.h"
55 #include "asterisk/parking.h"
56 #include "asterisk/causes.h"
57 #include "asterisk/test.h"
58
59 /*!
60  * \brief Used to queue an action frame onto a bridge channel and write an action frame into a bridge.
61  * \since 12.0.0
62  *
63  * \param bridge_channel Which channel work with.
64  * \param action Type of bridge action frame.
65  * \param data Frame payload data to pass.
66  * \param datalen Frame payload data length to pass.
67  *
68  * \retval 0 on success.
69  * \retval -1 on error.
70  */
71 typedef int (*ast_bridge_channel_post_action_data)(struct ast_bridge_channel *bridge_channel, enum bridge_channel_action_type action, const void *data, size_t datalen);
72
73 void ast_bridge_channel_lock_bridge(struct ast_bridge_channel *bridge_channel)
74 {
75         struct ast_bridge *bridge;
76
77         for (;;) {
78                 /* Safely get the bridge pointer */
79                 ast_bridge_channel_lock(bridge_channel);
80                 bridge = bridge_channel->bridge;
81                 ao2_ref(bridge, +1);
82                 ast_bridge_channel_unlock(bridge_channel);
83
84                 /* Lock the bridge and see if it is still the bridge we need to lock. */
85                 ast_bridge_lock(bridge);
86                 if (bridge == bridge_channel->bridge) {
87                         ao2_ref(bridge, -1);
88                         return;
89                 }
90                 ast_bridge_unlock(bridge);
91                 ao2_ref(bridge, -1);
92         }
93 }
94
95 int ast_bridge_channel_notify_talking(struct ast_bridge_channel *bridge_channel, int started_talking)
96 {
97         struct ast_frame action = {
98                 .frametype = AST_FRAME_BRIDGE_ACTION,
99                 .subclass.integer = started_talking
100                         ? BRIDGE_CHANNEL_ACTION_TALKING_START : BRIDGE_CHANNEL_ACTION_TALKING_STOP,
101         };
102
103         return ast_bridge_channel_queue_frame(bridge_channel, &action);
104 }
105
106 /*!
107  * \internal
108  * \brief Poke the bridge_channel thread
109  */
110 static void bridge_channel_poke(struct ast_bridge_channel *bridge_channel)
111 {
112         if (!pthread_equal(pthread_self(), bridge_channel->thread)) {
113                 /* Wake up the bridge channel thread. */
114                 ast_queue_frame(bridge_channel->chan, &ast_null_frame);
115         }
116 }
117
118 /*!
119  * \internal
120  * \brief Set actual cause on channel.
121  * \since 12.0.0
122  *
123  * \param chan Channel to set cause.
124  * \param cause Cause to set on channel.
125  *   If cause <= 0 then use cause on channel if cause still <= 0 use AST_CAUSE_NORMAL_CLEARING.
126  *
127  * \return Actual cause set on channel.
128  */
129 static int channel_set_cause(struct ast_channel *chan, int cause)
130 {
131         ast_channel_lock(chan);
132         if (cause <= 0) {
133                 cause = ast_channel_hangupcause(chan);
134                 if (cause <= 0) {
135                         cause = AST_CAUSE_NORMAL_CLEARING;
136                 }
137         }
138         ast_channel_hangupcause_set(chan, cause);
139         ast_channel_unlock(chan);
140         return cause;
141 }
142
143 void ast_bridge_channel_leave_bridge_nolock(struct ast_bridge_channel *bridge_channel, enum bridge_channel_state new_state, int cause)
144 {
145         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
146                 return;
147         }
148
149         ast_debug(1, "Setting %p(%s) state from:%d to:%d\n",
150                 bridge_channel, ast_channel_name(bridge_channel->chan), bridge_channel->state,
151                 new_state);
152
153         channel_set_cause(bridge_channel->chan, cause);
154
155         /* Change the state on the bridge channel */
156         bridge_channel->state = new_state;
157
158         bridge_channel_poke(bridge_channel);
159 }
160
161 void ast_bridge_channel_leave_bridge(struct ast_bridge_channel *bridge_channel, enum bridge_channel_state new_state, int cause)
162 {
163         ast_bridge_channel_lock(bridge_channel);
164         ast_bridge_channel_leave_bridge_nolock(bridge_channel, new_state, cause);
165         ast_bridge_channel_unlock(bridge_channel);
166 }
167
168 struct ast_bridge_channel *ast_bridge_channel_peer(struct ast_bridge_channel *bridge_channel)
169 {
170         struct ast_bridge *bridge = bridge_channel->bridge;
171         struct ast_bridge_channel *other = NULL;
172
173         if (bridge_channel->in_bridge && bridge->num_channels == 2) {
174                 AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
175                         if (other != bridge_channel) {
176                                 break;
177                         }
178                 }
179         }
180
181         return other;
182 }
183
184 void ast_bridge_channel_restore_formats(struct ast_bridge_channel *bridge_channel)
185 {
186         /* Restore original formats of the channel as they came in */
187         if (ast_format_cmp(ast_channel_readformat(bridge_channel->chan), &bridge_channel->read_format) == AST_FORMAT_CMP_NOT_EQUAL) {
188                 ast_debug(1, "Bridge is returning %p(%s) to read format %s\n",
189                         bridge_channel, ast_channel_name(bridge_channel->chan),
190                         ast_getformatname(&bridge_channel->read_format));
191                 if (ast_set_read_format(bridge_channel->chan, &bridge_channel->read_format)) {
192                         ast_debug(1, "Bridge failed to return %p(%s) to read format %s\n",
193                                 bridge_channel, ast_channel_name(bridge_channel->chan),
194                                 ast_getformatname(&bridge_channel->read_format));
195                 }
196         }
197         if (ast_format_cmp(ast_channel_writeformat(bridge_channel->chan), &bridge_channel->write_format) == AST_FORMAT_CMP_NOT_EQUAL) {
198                 ast_debug(1, "Bridge is returning %p(%s) to write format %s\n",
199                         bridge_channel, ast_channel_name(bridge_channel->chan),
200                         ast_getformatname(&bridge_channel->write_format));
201                 if (ast_set_write_format(bridge_channel->chan, &bridge_channel->write_format)) {
202                         ast_debug(1, "Bridge failed to return %p(%s) to write format %s\n",
203                                 bridge_channel, ast_channel_name(bridge_channel->chan),
204                                 ast_getformatname(&bridge_channel->write_format));
205                 }
206         }
207 }
208
209 struct ast_bridge *ast_bridge_channel_merge_inhibit(struct ast_bridge_channel *bridge_channel, int request)
210 {
211         struct ast_bridge *bridge;
212
213         ast_bridge_channel_lock_bridge(bridge_channel);
214         bridge = bridge_channel->bridge;
215         ao2_ref(bridge, +1);
216         bridge_merge_inhibit_nolock(bridge, request);
217         ast_bridge_unlock(bridge);
218         return bridge;
219 }
220
221 void ast_bridge_channel_update_linkedids(struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
222 {
223         struct ast_bridge_channel *other = NULL;
224         struct ast_bridge *bridge = bridge_channel->bridge;
225         const char *oldest_linkedid = ast_channel_linkedid(bridge_channel->chan);
226
227         AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
228                 if (other == swap) {
229                         continue;
230                 }
231                 oldest_linkedid = ast_channel_oldest_linkedid(oldest_linkedid, ast_channel_linkedid(other->chan));
232         }
233
234         if (ast_strlen_zero(oldest_linkedid)) {
235                 return;
236         }
237
238         ast_channel_lock(bridge_channel->chan);
239         ast_channel_linkedid_set(bridge_channel->chan, oldest_linkedid);
240         ast_channel_unlock(bridge_channel->chan);
241         AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
242                 if (other == swap) {
243                         continue;
244                 }
245                 ast_channel_lock(other->chan);
246                 ast_channel_linkedid_set(other->chan, oldest_linkedid);
247                 ast_channel_unlock(other->chan);
248         }
249 }
250
251 void ast_bridge_channel_update_accountcodes(struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
252 {
253         struct ast_bridge *bridge = bridge_channel->bridge;
254         struct ast_bridge_channel *other = NULL;
255
256         AST_LIST_TRAVERSE(&bridge->channels, other, entry) {
257                 if (other == swap) {
258                         continue;
259                 }
260                 ast_channel_lock_both(bridge_channel->chan, other->chan);
261
262                 if (!ast_strlen_zero(ast_channel_accountcode(bridge_channel->chan)) && ast_strlen_zero(ast_channel_peeraccount(other->chan))) {
263                         ast_debug(1, "Setting peeraccount to %s for %s from data on channel %s\n",
264                                         ast_channel_accountcode(bridge_channel->chan), ast_channel_name(other->chan), ast_channel_name(bridge_channel->chan));
265                         ast_channel_peeraccount_set(other->chan, ast_channel_accountcode(bridge_channel->chan));
266                 }
267                 if (!ast_strlen_zero(ast_channel_accountcode(other->chan)) && ast_strlen_zero(ast_channel_peeraccount(bridge_channel->chan))) {
268                         ast_debug(1, "Setting peeraccount to %s for %s from data on channel %s\n",
269                                         ast_channel_accountcode(other->chan), ast_channel_name(bridge_channel->chan), ast_channel_name(other->chan));
270                         ast_channel_peeraccount_set(bridge_channel->chan, ast_channel_accountcode(other->chan));
271                 }
272                 if (!ast_strlen_zero(ast_channel_peeraccount(bridge_channel->chan)) && ast_strlen_zero(ast_channel_accountcode(other->chan))) {
273                         ast_debug(1, "Setting accountcode to %s for %s from data on channel %s\n",
274                                         ast_channel_peeraccount(bridge_channel->chan), ast_channel_name(other->chan), ast_channel_name(bridge_channel->chan));
275                         ast_channel_accountcode_set(other->chan, ast_channel_peeraccount(bridge_channel->chan));
276                 }
277                 if (!ast_strlen_zero(ast_channel_peeraccount(other->chan)) && ast_strlen_zero(ast_channel_accountcode(bridge_channel->chan))) {
278                         ast_debug(1, "Setting accountcode to %s for %s from data on channel %s\n",
279                                         ast_channel_peeraccount(other->chan), ast_channel_name(bridge_channel->chan), ast_channel_name(other->chan));
280                         ast_channel_accountcode_set(bridge_channel->chan, ast_channel_peeraccount(other->chan));
281                 }
282                 if (bridge->num_channels == 2) {
283                         if (strcmp(ast_channel_accountcode(bridge_channel->chan), ast_channel_peeraccount(other->chan))) {
284                                 ast_debug(1, "Changing peeraccount from %s to %s on %s to match channel %s\n",
285                                                 ast_channel_peeraccount(other->chan), ast_channel_peeraccount(bridge_channel->chan), ast_channel_name(other->chan), ast_channel_name(bridge_channel->chan));
286                                 ast_channel_peeraccount_set(other->chan, ast_channel_accountcode(bridge_channel->chan));
287                         }
288                         if (strcmp(ast_channel_accountcode(other->chan), ast_channel_peeraccount(bridge_channel->chan))) {
289                                 ast_debug(1, "Changing peeraccount from %s to %s on %s to match channel %s\n",
290                                                 ast_channel_peeraccount(bridge_channel->chan), ast_channel_peeraccount(other->chan), ast_channel_name(bridge_channel->chan), ast_channel_name(other->chan));
291                                 ast_channel_peeraccount_set(bridge_channel->chan, ast_channel_accountcode(other->chan));
292                         }
293                 }
294                 ast_channel_unlock(bridge_channel->chan);
295                 ast_channel_unlock(other->chan);
296         }
297 }
298
299 void ast_bridge_channel_kick(struct ast_bridge_channel *bridge_channel, int cause)
300 {
301         struct ast_bridge_features *features = bridge_channel->features;
302         struct ast_bridge_hook *hook;
303         struct ao2_iterator iter;
304
305         ast_bridge_channel_lock(bridge_channel);
306         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
307                 channel_set_cause(bridge_channel->chan, cause);
308                 cause = 0;
309         }
310         ast_bridge_channel_unlock(bridge_channel);
311
312         /* Run any hangup hooks. */
313         iter = ao2_iterator_init(features->other_hooks, 0);
314         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
315                 int remove_me;
316
317                 if (hook->type != AST_BRIDGE_HOOK_TYPE_HANGUP) {
318                         continue;
319                 }
320                 remove_me = hook->callback(bridge_channel, hook->hook_pvt);
321                 if (remove_me) {
322                         ast_debug(1, "Hangup hook %p is being removed from %p(%s)\n",
323                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
324                         ao2_unlink(features->other_hooks, hook);
325                 }
326         }
327         ao2_iterator_destroy(&iter);
328
329         /* Default hangup action. */
330         ast_bridge_channel_leave_bridge(bridge_channel, BRIDGE_CHANNEL_STATE_END, cause);
331 }
332
333 /*!
334  * \internal
335  * \brief Write an \ref ast_frame onto the bridge channel
336  * \since 12.0.0
337  *
338  * \param bridge_channel Which channel to queue the frame onto.
339  * \param frame The frame to write onto the bridge_channel
340  *
341  * \retval 0 on success.
342  * \retval -1 on error.
343  */
344 static int bridge_channel_write_frame(struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
345 {
346         ast_bridge_channel_lock_bridge(bridge_channel);
347 /*
348  * XXX need to implement a deferred write queue for when there
349  * is no peer channel in the bridge (yet or it was kicked).
350  *
351  * The tech decides if a frame needs to be pushed back for deferral.
352  * simple_bridge/native_bridge are likely the only techs that will do this.
353  */
354         bridge_channel->bridge->technology->write(bridge_channel->bridge, bridge_channel, frame);
355
356         /* Remember any owed events to the bridge. */
357         switch (frame->frametype) {
358         case AST_FRAME_DTMF_BEGIN:
359                 bridge_channel->owed.dtmf_tv = ast_tvnow();
360                 bridge_channel->owed.dtmf_digit = frame->subclass.integer;
361                 break;
362         case AST_FRAME_DTMF_END:
363                 bridge_channel->owed.dtmf_digit = '\0';
364                 break;
365         case AST_FRAME_CONTROL:
366                 /*
367                  * We explicitly will not remember HOLD/UNHOLD frames because
368                  * things like attended transfers will handle them.
369                  */
370         default:
371                 break;
372         }
373         ast_bridge_unlock(bridge_channel->bridge);
374
375         /*
376          * Claim successful write to bridge.  If deferred frame
377          * support is added, claim successfully deferred.
378          */
379         return 0;
380 }
381
382 void bridge_channel_settle_owed_events(struct ast_bridge *orig_bridge, struct ast_bridge_channel *bridge_channel)
383 {
384         if (bridge_channel->owed.dtmf_digit) {
385                 struct ast_frame frame = {
386                         .frametype = AST_FRAME_DTMF_END,
387                         .subclass.integer = bridge_channel->owed.dtmf_digit,
388                         .src = "Bridge channel owed DTMF",
389                 };
390
391                 frame.len = ast_tvdiff_ms(ast_tvnow(), bridge_channel->owed.dtmf_tv);
392                 if (frame.len < option_dtmfminduration) {
393                         frame.len = option_dtmfminduration;
394                 }
395                 ast_log(LOG_DTMF, "DTMF end '%c' simulated to bridge %s because %s left.  Duration %ld ms.\n",
396                         bridge_channel->owed.dtmf_digit, orig_bridge->uniqueid,
397                         ast_channel_name(bridge_channel->chan), frame.len);
398                 bridge_channel->owed.dtmf_digit = '\0';
399                 orig_bridge->technology->write(orig_bridge, NULL, &frame);
400         }
401 }
402
403 /*!
404  * \internal
405  * \brief Suspend a channel from a bridge.
406  *
407  * \param bridge_channel Channel to suspend.
408  *
409  * \note This function assumes bridge_channel->bridge is locked.
410  *
411  * \return Nothing
412  */
413 void bridge_channel_internal_suspend_nolock(struct ast_bridge_channel *bridge_channel)
414 {
415         bridge_channel->suspended = 1;
416         if (bridge_channel->in_bridge) {
417                 --bridge_channel->bridge->num_active;
418         }
419
420         /* Get technology bridge threads off of the channel. */
421         if (bridge_channel->bridge->technology->suspend) {
422                 bridge_channel->bridge->technology->suspend(bridge_channel->bridge, bridge_channel);
423         }
424 }
425
426 /*!
427  * \internal
428  * \brief Suspend a channel from a bridge.
429  *
430  * \param bridge_channel Channel to suspend.
431  *
432  * \return Nothing
433  */
434 static void bridge_channel_suspend(struct ast_bridge_channel *bridge_channel)
435 {
436         ast_bridge_channel_lock_bridge(bridge_channel);
437         bridge_channel_internal_suspend_nolock(bridge_channel);
438         ast_bridge_unlock(bridge_channel->bridge);
439 }
440
441 /*!
442  * \internal
443  * \brief Unsuspend a channel from a bridge.
444  *
445  * \param bridge_channel Channel to unsuspend.
446  *
447  * \note This function assumes bridge_channel->bridge is locked.
448  *
449  * \return Nothing
450  */
451 void bridge_channel_internal_unsuspend_nolock(struct ast_bridge_channel *bridge_channel)
452 {
453         bridge_channel->suspended = 0;
454         if (bridge_channel->in_bridge) {
455                 ++bridge_channel->bridge->num_active;
456         }
457
458         /* Wake technology bridge threads to take care of channel again. */
459         if (bridge_channel->bridge->technology->unsuspend) {
460                 bridge_channel->bridge->technology->unsuspend(bridge_channel->bridge, bridge_channel);
461         }
462
463         /* Wake suspended channel. */
464         ast_bridge_channel_lock(bridge_channel);
465         ast_cond_signal(&bridge_channel->cond);
466         ast_bridge_channel_unlock(bridge_channel);
467 }
468
469 /*!
470  * \internal
471  * \brief Unsuspend a channel from a bridge.
472  *
473  * \param bridge_channel Channel to unsuspend.
474  *
475  * \return Nothing
476  */
477 static void bridge_channel_unsuspend(struct ast_bridge_channel *bridge_channel)
478 {
479         ast_bridge_channel_lock_bridge(bridge_channel);
480         bridge_channel_internal_unsuspend_nolock(bridge_channel);
481         ast_bridge_unlock(bridge_channel->bridge);
482 }
483
484 /*!
485  * \internal
486  * \brief Queue an action frame onto the bridge channel with data.
487  * \since 12.0.0
488  *
489  * \param bridge_channel Which channel to queue the frame onto.
490  * \param action Type of bridge action frame.
491  * \param data Frame payload data to pass.
492  * \param datalen Frame payload data length to pass.
493  *
494  * \retval 0 on success.
495  * \retval -1 on error.
496  */
497 static int bridge_channel_queue_action_data(struct ast_bridge_channel *bridge_channel, enum bridge_channel_action_type action, const void *data, size_t datalen)
498 {
499         struct ast_frame frame = {
500                 .frametype = AST_FRAME_BRIDGE_ACTION,
501                 .subclass.integer = action,
502                 .datalen = datalen,
503                 .data.ptr = (void *) data,
504         };
505
506         return ast_bridge_channel_queue_frame(bridge_channel, &frame);
507 }
508
509 /*!
510  * \internal
511  * \brief Write an action frame onto the bridge channel with data.
512  * \since 12.0.0
513  *
514  * \param bridge_channel Which channel to queue the frame onto.
515  * \param action Type of bridge action frame.
516  * \param data Frame payload data to pass.
517  * \param datalen Frame payload data length to pass.
518  *
519  * \retval 0 on success.
520  * \retval -1 on error.
521  */
522 static int bridge_channel_write_action_data(struct ast_bridge_channel *bridge_channel, enum bridge_channel_action_type action, const void *data, size_t datalen)
523 {
524         struct ast_frame frame = {
525                 .frametype = AST_FRAME_BRIDGE_ACTION,
526                 .subclass.integer = action,
527                 .datalen = datalen,
528                 .data.ptr = (void *) data,
529         };
530
531         return bridge_channel_write_frame(bridge_channel, &frame);
532 }
533
534 int ast_bridge_channel_queue_frame(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
535 {
536         struct ast_frame *dup;
537         char nudge = 0;
538
539         if (bridge_channel->suspended
540                 /* Also defer DTMF frames. */
541                 && fr->frametype != AST_FRAME_DTMF_BEGIN
542                 && fr->frametype != AST_FRAME_DTMF_END
543                 && !ast_is_deferrable_frame(fr)) {
544                 /* Drop non-deferable frames when suspended. */
545                 return 0;
546         }
547         if (fr->frametype == AST_FRAME_NULL) {
548                 /* "Accept" the frame and discard it. */
549                 return 0;
550         }
551
552         dup = ast_frdup(fr);
553         if (!dup) {
554                 return -1;
555         }
556
557         ast_bridge_channel_lock(bridge_channel);
558         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
559                 /* Drop frames on channels leaving the bridge. */
560                 ast_bridge_channel_unlock(bridge_channel);
561                 ast_frfree(dup);
562                 return 0;
563         }
564
565         AST_LIST_INSERT_TAIL(&bridge_channel->wr_queue, dup, frame_list);
566         if (write(bridge_channel->alert_pipe[1], &nudge, sizeof(nudge)) != sizeof(nudge)) {
567                 ast_log(LOG_ERROR, "We couldn't write alert pipe for %p(%s)... something is VERY wrong\n",
568                         bridge_channel, ast_channel_name(bridge_channel->chan));
569         }
570         ast_bridge_channel_unlock(bridge_channel);
571         return 0;
572 }
573
574 int ast_bridge_queue_everyone_else(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
575 {
576         struct ast_bridge_channel *cur;
577         int not_written = -1;
578
579         if (frame->frametype == AST_FRAME_NULL) {
580                 /* "Accept" the frame and discard it. */
581                 return 0;
582         }
583
584         AST_LIST_TRAVERSE(&bridge->channels, cur, entry) {
585                 if (cur == bridge_channel) {
586                         continue;
587                 }
588                 if (!ast_bridge_channel_queue_frame(cur, frame)) {
589                         not_written = 0;
590                 }
591         }
592         return not_written;
593 }
594
595 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)
596 {
597         struct ast_frame frame = {
598                 .frametype = AST_FRAME_CONTROL,
599                 .subclass.integer = control,
600                 .datalen = datalen,
601                 .data.ptr = (void *) data,
602         };
603
604         return ast_bridge_channel_queue_frame(bridge_channel, &frame);
605 }
606
607 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)
608 {
609         struct ast_frame frame = {
610                 .frametype = AST_FRAME_CONTROL,
611                 .subclass.integer = control,
612                 .datalen = datalen,
613                 .data.ptr = (void *) data,
614         };
615
616         return bridge_channel_write_frame(bridge_channel, &frame);
617 }
618
619 int ast_bridge_channel_write_hold(struct ast_bridge_channel *bridge_channel, const char *moh_class)
620 {
621         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
622         size_t datalen;
623
624         if (!ast_strlen_zero(moh_class)) {
625                 datalen = strlen(moh_class) + 1;
626
627                 blob = ast_json_pack("{s: s}",
628                         "musicclass", moh_class);
629         } else {
630                 moh_class = NULL;
631                 datalen = 0;
632         }
633
634         ast_channel_lock(bridge_channel->chan);
635         ast_channel_publish_blob(bridge_channel->chan, ast_channel_hold_type(), blob);
636         ast_channel_unlock(bridge_channel->chan);
637         return ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_HOLD,
638                 moh_class, datalen);
639 }
640
641 int ast_bridge_channel_write_unhold(struct ast_bridge_channel *bridge_channel)
642 {
643         ast_channel_lock(bridge_channel->chan);
644         ast_channel_publish_blob(bridge_channel->chan, ast_channel_unhold_type(), NULL);
645         ast_channel_unlock(bridge_channel->chan);
646         return ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_UNHOLD, NULL, 0);
647 }
648
649 /*!
650  * \internal
651  * \brief Helper function to kick off a PBX app on a bridge_channel
652  */
653 static int run_app_helper(struct ast_channel *chan, const char *app_name, const char *app_args)
654 {
655         int res = 0;
656
657         if (!strcasecmp("Gosub", app_name)) {
658                 ast_app_exec_sub(NULL, chan, app_args, 0);
659         } else if (!strcasecmp("Macro", app_name)) {
660                 ast_app_exec_macro(NULL, chan, app_args);
661         } else {
662                 struct ast_app *app;
663
664                 app = pbx_findapp(app_name);
665                 if (!app) {
666                         ast_log(LOG_WARNING, "Could not find application (%s)\n", app_name);
667                 } else {
668                         res = pbx_exec(chan, app, app_args);
669                 }
670         }
671         return res;
672 }
673
674 void ast_bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
675 {
676         if (moh_class) {
677                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
678         }
679         if (run_app_helper(bridge_channel->chan, app_name, S_OR(app_args, ""))) {
680                 /* Break the bridge if the app returns non-zero. */
681                 ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
682         }
683         if (moh_class) {
684                 ast_bridge_channel_write_unhold(bridge_channel);
685         }
686 }
687
688 struct bridge_run_app {
689         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
690         int moh_offset;
691         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
692         int app_args_offset;
693         /*! Application name to run. */
694         char app_name[0];
695 };
696
697 /*!
698  * \internal
699  * \brief Handle the run application bridge action.
700  * \since 12.0.0
701  *
702  * \param bridge_channel Which channel to run the application on.
703  * \param data Action frame data to run the application.
704  *
705  * \return Nothing
706  */
707 static void bridge_channel_run_app(struct ast_bridge_channel *bridge_channel, struct bridge_run_app *data)
708 {
709         ast_bridge_channel_run_app(bridge_channel, data->app_name,
710                 data->app_args_offset ? &data->app_name[data->app_args_offset] : NULL,
711                 data->moh_offset ? &data->app_name[data->moh_offset] : NULL);
712 }
713
714 /*!
715  * \internal
716  * \brief Marshal an application to be executed on a bridge_channel
717  */
718 static int payload_helper_app(ast_bridge_channel_post_action_data post_it,
719         struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
720 {
721         struct bridge_run_app *app_data;
722         size_t len_name = strlen(app_name) + 1;
723         size_t len_args = ast_strlen_zero(app_args) ? 0 : strlen(app_args) + 1;
724         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
725         size_t len_data = sizeof(*app_data) + len_name + len_args + len_moh;
726
727         /* Fill in application run frame data. */
728         app_data = alloca(len_data);
729         app_data->app_args_offset = len_args ? len_name : 0;
730         app_data->moh_offset = len_moh ? len_name + len_args : 0;
731         strcpy(app_data->app_name, app_name);/* Safe */
732         if (len_args) {
733                 strcpy(&app_data->app_name[app_data->app_args_offset], app_args);/* Safe */
734         }
735         if (moh_class) {
736                 strcpy(&app_data->app_name[app_data->moh_offset], moh_class);/* Safe */
737         }
738
739         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_RUN_APP, app_data, len_data);
740 }
741
742 int ast_bridge_channel_write_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
743 {
744         return payload_helper_app(bridge_channel_write_action_data,
745                 bridge_channel, app_name, app_args, moh_class);
746 }
747
748 int ast_bridge_channel_queue_app(struct ast_bridge_channel *bridge_channel, const char *app_name, const char *app_args, const char *moh_class)
749 {
750         return payload_helper_app(bridge_channel_queue_action_data,
751                 bridge_channel, app_name, app_args, moh_class);
752 }
753
754 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)
755 {
756         if (moh_class) {
757                 ast_bridge_channel_write_hold(bridge_channel, moh_class);
758         }
759         if (custom_play) {
760                 custom_play(bridge_channel, playfile);
761         } else {
762                 ast_stream_and_wait(bridge_channel->chan, playfile, AST_DIGIT_NONE);
763         }
764         if (moh_class) {
765                 ast_bridge_channel_write_unhold(bridge_channel);
766         }
767
768         /*
769          * It may be necessary to resume music on hold after we finish
770          * playing the announcment.
771          */
772         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_MOH)) {
773                 const char *latest_musicclass;
774
775                 ast_channel_lock(bridge_channel->chan);
776                 latest_musicclass = ast_strdupa(ast_channel_latest_musicclass(bridge_channel->chan));
777                 ast_channel_unlock(bridge_channel->chan);
778                 ast_moh_start(bridge_channel->chan, latest_musicclass, NULL);
779         }
780 }
781
782 struct bridge_playfile {
783         /*! Call this function to play the playfile. (NULL if normal sound file to play) */
784         ast_bridge_custom_play_fn custom_play;
785         /*! Offset into playfile[] where the MOH class name starts.  (zero if no MOH)*/
786         int moh_offset;
787         /*! Filename to play. */
788         char playfile[0];
789 };
790
791 /*!
792  * \internal
793  * \brief Handle the playfile bridge action.
794  * \since 12.0.0
795  *
796  * \param bridge_channel Which channel to play a file on.
797  * \param payload Action frame payload to play a file.
798  *
799  * \return Nothing
800  */
801 static void bridge_channel_playfile(struct ast_bridge_channel *bridge_channel, struct bridge_playfile *payload)
802 {
803         ast_bridge_channel_playfile(bridge_channel, payload->custom_play, payload->playfile,
804                 payload->moh_offset ? &payload->playfile[payload->moh_offset] : NULL);
805 }
806
807 /*!
808  * \internal
809  * \brief Marshal a file to be played on a bridge_channel
810  */
811 static int payload_helper_playfile(ast_bridge_channel_post_action_data post_it,
812         struct ast_bridge_channel *bridge_channel, ast_bridge_custom_play_fn custom_play, const char *playfile, const char *moh_class)
813 {
814         struct bridge_playfile *payload;
815         size_t len_name = strlen(playfile) + 1;
816         size_t len_moh = !moh_class ? 0 : strlen(moh_class) + 1;
817         size_t len_payload = sizeof(*payload) + len_name + len_moh;
818
819         /* Fill in play file frame data. */
820         payload = alloca(len_payload);
821         payload->custom_play = custom_play;
822         payload->moh_offset = len_moh ? len_name : 0;
823         strcpy(payload->playfile, playfile);/* Safe */
824         if (moh_class) {
825                 strcpy(&payload->playfile[payload->moh_offset], moh_class);/* Safe */
826         }
827
828         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_PLAY_FILE, payload, len_payload);
829 }
830
831 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)
832 {
833         return payload_helper_playfile(bridge_channel_write_action_data,
834                 bridge_channel, custom_play, playfile, moh_class);
835 }
836
837 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)
838 {
839         return payload_helper_playfile(bridge_channel_queue_action_data,
840                 bridge_channel, custom_play, playfile, moh_class);
841 }
842
843 struct bridge_custom_callback {
844         /*! Call this function on the bridge channel thread. */
845         ast_bridge_custom_callback_fn callback;
846         /*! Size of the payload if it exists.  A number otherwise. */
847         size_t payload_size;
848         /*! Option flags determining how callback is called. */
849         unsigned int flags;
850         /*! Nonzero if the payload exists. */
851         char payload_exists;
852         /*! Payload to give to callback. */
853         char payload[0];
854 };
855
856 /*!
857  * \internal
858  * \brief Handle the do custom callback bridge action.
859  * \since 12.0.0
860  *
861  * \param bridge_channel Which channel to call the callback on.
862  * \param data Action frame data to call the callback.
863  *
864  * \return Nothing
865  */
866 static void bridge_channel_do_callback(struct ast_bridge_channel *bridge_channel, struct bridge_custom_callback *data)
867 {
868         if (ast_test_flag(data, AST_BRIDGE_CHANNEL_CB_OPTION_MEDIA)) {
869                 bridge_channel_suspend(bridge_channel);
870                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
871         }
872         data->callback(bridge_channel, data->payload_exists ? data->payload : NULL, data->payload_size);
873         if (ast_test_flag(data, AST_BRIDGE_CHANNEL_CB_OPTION_MEDIA)) {
874                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
875                 bridge_channel_unsuspend(bridge_channel);
876         }
877 }
878
879 /*!
880  * \internal
881  * \brief Marshal a custom callback function to be called on a bridge_channel
882  */
883 static int payload_helper_cb(ast_bridge_channel_post_action_data post_it,
884         struct ast_bridge_channel *bridge_channel,
885         enum ast_bridge_channel_custom_callback_option flags,
886         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
887 {
888         struct bridge_custom_callback *cb_data;
889         size_t len_data = sizeof(*cb_data) + (payload ? payload_size : 0);
890
891         /* Sanity check. */
892         if (!callback) {
893                 ast_assert(0);
894                 return -1;
895         }
896
897         /* Fill in custom callback frame data. */
898         cb_data = alloca(len_data);
899         cb_data->callback = callback;
900         cb_data->payload_size = payload_size;
901         cb_data->flags = flags;
902         cb_data->payload_exists = payload && payload_size;
903         if (cb_data->payload_exists) {
904                 memcpy(cb_data->payload, payload, payload_size);/* Safe */
905         }
906
907         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_CALLBACK, cb_data, len_data);
908 }
909
910 int ast_bridge_channel_write_callback(struct ast_bridge_channel *bridge_channel,
911         enum ast_bridge_channel_custom_callback_option flags,
912         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
913 {
914         return payload_helper_cb(bridge_channel_write_action_data,
915                 bridge_channel, flags, callback, payload, payload_size);
916 }
917
918 int ast_bridge_channel_queue_callback(struct ast_bridge_channel *bridge_channel,
919         enum ast_bridge_channel_custom_callback_option flags,
920         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
921 {
922         return payload_helper_cb(bridge_channel_queue_action_data,
923                 bridge_channel, flags, callback, payload, payload_size);
924 }
925
926 struct bridge_park {
927         int parker_uuid_offset;
928         int app_data_offset;
929         /* buffer used for holding those strings */
930         char parkee_uuid[0];
931 };
932
933 /*!
934  * \internal
935  * \brief Park a bridge_cahnnel
936  */
937 static void bridge_channel_park(struct ast_bridge_channel *bridge_channel, struct bridge_park *payload)
938 {
939         if (!ast_parking_provider_registered()) {
940                 ast_log(AST_LOG_WARNING, "Unable to park %s: No parking provider loaded!\n",
941                         ast_channel_name(bridge_channel->chan));
942                 return;
943         }
944
945         if (ast_parking_park_bridge_channel(bridge_channel, payload->parkee_uuid,
946                 &payload->parkee_uuid[payload->parker_uuid_offset],
947                 payload->app_data_offset ? &payload->parkee_uuid[payload->app_data_offset] : NULL)) {
948                 ast_log(AST_LOG_WARNING, "Error occurred while parking %s\n",
949                         ast_channel_name(bridge_channel->chan));
950         }
951 }
952
953 /*!
954  * \internal
955  * \brief Marshal a park action onto a bridge_channel
956  */
957 static int payload_helper_park(ast_bridge_channel_post_action_data post_it,
958         struct ast_bridge_channel *bridge_channel,
959         const char *parkee_uuid,
960         const char *parker_uuid,
961         const char *app_data)
962 {
963         struct bridge_park *payload;
964         size_t len_parkee_uuid = strlen(parkee_uuid) + 1;
965         size_t len_parker_uuid = strlen(parker_uuid) + 1;
966         size_t len_app_data = !app_data ? 0 : strlen(app_data) + 1;
967         size_t len_payload = sizeof(*payload) + len_parker_uuid + len_parkee_uuid + len_app_data;
968
969         payload = alloca(len_payload);
970         payload->app_data_offset = len_app_data ? len_parkee_uuid + len_parker_uuid : 0;
971         payload->parker_uuid_offset = len_parkee_uuid;
972         strcpy(payload->parkee_uuid, parkee_uuid);
973         strcpy(&payload->parkee_uuid[payload->parker_uuid_offset], parker_uuid);
974         if (app_data) {
975                 strcpy(&payload->parkee_uuid[payload->app_data_offset], app_data);
976         }
977
978         return post_it(bridge_channel, BRIDGE_CHANNEL_ACTION_PARK, payload, len_payload);
979 }
980
981 int ast_bridge_channel_write_park(struct ast_bridge_channel *bridge_channel, const char *parkee_uuid, const char *parker_uuid, const char *app_data)
982 {
983         return payload_helper_park(bridge_channel_write_action_data,
984                 bridge_channel, parkee_uuid, parker_uuid, app_data);
985 }
986
987 /*!
988  * \internal
989  * \brief Handle bridge channel interval expiration.
990  * \since 12.0.0
991  *
992  * \param bridge_channel Channel to run expired intervals on.
993  *
994  * \return Nothing
995  */
996 static void bridge_channel_handle_interval(struct ast_bridge_channel *bridge_channel)
997 {
998         struct ast_heap *interval_hooks;
999         struct ast_bridge_hook_timer *hook;
1000         struct timeval start;
1001         int chan_suspended = 0;
1002
1003         interval_hooks = bridge_channel->features->interval_hooks;
1004         ast_heap_wrlock(interval_hooks);
1005         start = ast_tvnow();
1006         while ((hook = ast_heap_peek(interval_hooks, 1))) {
1007                 int interval;
1008                 unsigned int execution_time;
1009
1010                 if (ast_tvdiff_ms(hook->timer.trip_time, start) > 0) {
1011                         ast_debug(1, "Hook %p on %p(%s) wants to happen in the future, stopping our traversal\n",
1012                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1013                         break;
1014                 }
1015                 ao2_ref(hook, +1);
1016                 ast_heap_unlock(interval_hooks);
1017
1018                 if (!chan_suspended
1019                         && ast_test_flag(&hook->timer, AST_BRIDGE_HOOK_TIMER_OPTION_MEDIA)) {
1020                         chan_suspended = 1;
1021                         bridge_channel_suspend(bridge_channel);
1022                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1023                 }
1024
1025                 ast_debug(1, "Executing hook %p on %p(%s)\n",
1026                         hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1027                 interval = hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
1028
1029                 ast_heap_wrlock(interval_hooks);
1030                 if (ast_heap_peek(interval_hooks, hook->timer.heap_index) != hook
1031                         || !ast_heap_remove(interval_hooks, hook)) {
1032                         /* Interval hook is already removed from the bridge_channel. */
1033                         ao2_ref(hook, -1);
1034                         continue;
1035                 }
1036                 ao2_ref(hook, -1);
1037
1038                 if (interval < 0) {
1039                         ast_debug(1, "Removed interval hook %p from %p(%s)\n",
1040                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1041                         ao2_ref(hook, -1);
1042                         continue;
1043                 }
1044                 if (interval) {
1045                         /* Set new interval for the hook. */
1046                         hook->timer.interval = interval;
1047                 }
1048
1049                 ast_debug(1, "Updating interval hook %p with interval %u on %p(%s)\n",
1050                         hook, hook->timer.interval, bridge_channel,
1051                         ast_channel_name(bridge_channel->chan));
1052
1053                 /* resetting start */
1054                 start = ast_tvnow();
1055
1056                 /*
1057                  * Resetup the interval hook for the next interval.  We may need
1058                  * to skip over any missed intervals because the hook was
1059                  * delayed or took too long.
1060                  */
1061                 execution_time = ast_tvdiff_ms(start, hook->timer.trip_time);
1062                 while (hook->timer.interval < execution_time) {
1063                         execution_time -= hook->timer.interval;
1064                 }
1065                 hook->timer.trip_time = ast_tvadd(start, ast_samp2tv(hook->timer.interval - execution_time, 1000));
1066                 hook->timer.seqno = ast_atomic_fetchadd_int((int *) &bridge_channel->features->interval_sequence, +1);
1067
1068                 if (ast_heap_push(interval_hooks, hook)) {
1069                         /* Could not push the hook back onto the heap. */
1070                         ao2_ref(hook, -1);
1071                 }
1072         }
1073         ast_heap_unlock(interval_hooks);
1074
1075         if (chan_suspended) {
1076                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1077                 bridge_channel_unsuspend(bridge_channel);
1078         }
1079 }
1080
1081 /*!
1082  * \internal
1083  * \brief Write a DTMF stream out to a channel
1084  */
1085 static int bridge_channel_write_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
1086 {
1087         return bridge_channel_write_action_data(bridge_channel,
1088                 BRIDGE_CHANNEL_ACTION_DTMF_STREAM, dtmf, strlen(dtmf) + 1);
1089 }
1090
1091 /*!
1092  * \internal
1093  * \brief Indicate to the testsuite a feature was successfully detected.
1094  *
1095  * Currently, this function only will relay built-in features to the testsuite,
1096  * but it could be modified to detect applicationmap items should the need arise.
1097  *
1098  * \param chan The channel that activated the feature
1099  * \param dtmf The DTMF sequence entered to activate the feature
1100  */
1101 static void testsuite_notify_feature_success(struct ast_channel *chan, const char *dtmf)
1102 {
1103 #ifdef TEST_FRAMEWORK
1104         char *feature = "unknown";
1105         struct ast_featuremap_config *featuremap = ast_get_chan_featuremap_config(chan);
1106         struct ast_features_xfer_config *xfer = ast_get_chan_features_xfer_config(chan);
1107
1108         if (featuremap) {
1109                 if (!strcmp(dtmf, featuremap->blindxfer)) {
1110                         feature = "blindxfer";
1111                 } else if (!strcmp(dtmf, featuremap->atxfer)) {
1112                         feature = "atxfer";
1113                 } else if (!strcmp(dtmf, featuremap->disconnect)) {
1114                         feature = "disconnect";
1115                 } else if (!strcmp(dtmf, featuremap->automon)) {
1116                         feature = "automon";
1117                 } else if (!strcmp(dtmf, featuremap->automixmon)) {
1118                         feature = "automixmon";
1119                 } else if (!strcmp(dtmf, featuremap->parkcall)) {
1120                         feature = "parkcall";
1121                 } else if (!strcmp(dtmf, xfer->atxferthreeway)) {
1122                         feature = "atxferthreeway";
1123                 }
1124         }
1125
1126         ast_test_suite_event_notify("FEATURE_DETECTION",
1127                         "Result: success\r\n"
1128                         "Feature: %s", feature);
1129 #endif /* TEST_FRAMEWORK */
1130 }
1131
1132 /*!
1133  * \internal
1134  * \brief Internal function that executes a feature on a bridge channel
1135  * \note Neither the bridge nor the bridge_channel locks should be held when entering
1136  * this function.
1137  */
1138 static void bridge_channel_feature(struct ast_bridge_channel *bridge_channel, const char *starting_dtmf)
1139 {
1140         struct ast_bridge_features *features = bridge_channel->features;
1141         struct ast_bridge_hook_dtmf *hook = NULL;
1142         char dtmf[MAXIMUM_DTMF_FEATURE_STRING];
1143         size_t dtmf_len;
1144         unsigned int digit_timeout;
1145         RAII_VAR(struct ast_features_general_config *, gen_cfg, NULL, ao2_cleanup);
1146
1147         ast_channel_lock(bridge_channel->chan);
1148         gen_cfg = ast_get_chan_features_general_config(bridge_channel->chan);
1149         if (!gen_cfg) {
1150                 ast_log(LOG_ERROR, "Unable to retrieve features configuration.\n");
1151                 ast_channel_unlock(bridge_channel->chan);
1152                 return;
1153         }
1154         digit_timeout = gen_cfg->featuredigittimeout;
1155         ast_channel_unlock(bridge_channel->chan);
1156
1157         if (ast_strlen_zero(starting_dtmf)) {
1158                 dtmf[0] = '\0';
1159                 dtmf_len = 0;
1160         } else {
1161                 ast_copy_string(dtmf, starting_dtmf, sizeof(dtmf));
1162                 dtmf_len = strlen(dtmf);
1163         }
1164
1165         /*
1166          * Check if any feature DTMF hooks match or could match and
1167          * try to collect more DTMF digits.
1168          */
1169         for (;;) {
1170                 int res;
1171
1172                 if (dtmf_len) {
1173                         ast_debug(1, "DTMF feature string on %p(%s) is now '%s'\n",
1174                                 bridge_channel, ast_channel_name(bridge_channel->chan), dtmf);
1175
1176                         /* See if a DTMF feature hook matches or can match */
1177                         hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_PARTIAL_KEY);
1178                         if (!hook) {
1179                                 ast_debug(1, "No DTMF feature hooks on %p(%s) match '%s'\n",
1180                                         bridge_channel, ast_channel_name(bridge_channel->chan), dtmf);
1181                                 break;
1182                         }
1183                         if (strlen(hook->dtmf.code) == dtmf_len) {
1184                                 ast_debug(1, "DTMF feature hook %p matched DTMF string '%s' on %p(%s)\n",
1185                                         hook, dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
1186                                 break;
1187                         }
1188                         ao2_ref(hook, -1);
1189                         hook = NULL;
1190
1191                         if (ARRAY_LEN(dtmf) - 1 <= dtmf_len) {
1192                                 /* We have reached the maximum length of a DTMF feature string. */
1193                                 break;
1194                         }
1195                 }
1196
1197                 res = ast_waitfordigit(bridge_channel->chan, digit_timeout);
1198                 if (!res) {
1199                         ast_debug(1, "DTMF feature string collection on %p(%s) timed out\n",
1200                                 bridge_channel, ast_channel_name(bridge_channel->chan));
1201                         break;
1202                 }
1203                 if (res < 0) {
1204                         ast_debug(1, "DTMF feature string collection failed on %p(%s) for some reason\n",
1205                                 bridge_channel, ast_channel_name(bridge_channel->chan));
1206                         break;
1207                 }
1208
1209                 /* Add the new DTMF into the DTMF string so we can do our matching */
1210                 dtmf[dtmf_len] = res;
1211                 dtmf[++dtmf_len] = '\0';
1212         }
1213
1214         if (hook) {
1215                 int remove_me;
1216
1217                 /* Execute the matched hook on this channel. */
1218                 remove_me = hook->generic.callback(bridge_channel, hook->generic.hook_pvt);
1219                 if (remove_me) {
1220                         ast_debug(1, "DTMF hook %p is being removed from %p(%s)\n",
1221                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1222                         ao2_unlink(features->dtmf_hooks, hook);
1223                 }
1224                 testsuite_notify_feature_success(bridge_channel->chan, hook->dtmf.code);
1225                 ao2_ref(hook, -1);
1226
1227                 /*
1228                  * If we are handing the channel off to an external hook for
1229                  * ownership, we are not guaranteed what kind of state it will
1230                  * come back in.  If the channel hungup, we need to detect that
1231                  * here if the hook did not already change the state.
1232                  */
1233                 if (bridge_channel->chan && ast_check_hangup_locked(bridge_channel->chan)) {
1234                         ast_bridge_channel_kick(bridge_channel, 0);
1235                 }
1236         } else {
1237                 if (features->dtmf_passthrough) {
1238                         /* Stream any collected DTMF to the other channels. */
1239                         bridge_channel_write_dtmf_stream(bridge_channel, dtmf);
1240                 }
1241                 ast_test_suite_event_notify("FEATURE_DETECTION", "Result: fail");
1242         }
1243 }
1244
1245 /*!
1246  * \internal
1247  * \brief Indicate that a bridge_channel is talking
1248  */
1249 static void bridge_channel_talking(struct ast_bridge_channel *bridge_channel, int talking)
1250 {
1251         struct ast_bridge_features *features = bridge_channel->features;
1252         struct ast_bridge_hook *hook;
1253         struct ao2_iterator iter;
1254
1255         /* Run any talk detection hooks. */
1256         iter = ao2_iterator_init(features->other_hooks, 0);
1257         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
1258                 int remove_me;
1259                 ast_bridge_talking_indicate_callback talk_cb;
1260
1261                 if (hook->type != AST_BRIDGE_HOOK_TYPE_TALK) {
1262                         continue;
1263                 }
1264                 talk_cb = (ast_bridge_talking_indicate_callback) hook->callback;
1265                 remove_me = talk_cb(bridge_channel, hook->hook_pvt, talking);
1266                 if (remove_me) {
1267                         ast_debug(1, "Talk detection hook %p is being removed from %p(%s)\n",
1268                                 hook, bridge_channel, ast_channel_name(bridge_channel->chan));
1269                         ao2_unlink(features->other_hooks, hook);
1270                 }
1271         }
1272         ao2_iterator_destroy(&iter);
1273 }
1274
1275 /*! \brief Internal function that plays back DTMF on a bridge channel */
1276 static void bridge_channel_dtmf_stream(struct ast_bridge_channel *bridge_channel, const char *dtmf)
1277 {
1278         ast_debug(1, "Playing DTMF stream '%s' out to %p(%s)\n",
1279                 dtmf, bridge_channel, ast_channel_name(bridge_channel->chan));
1280         ast_dtmf_stream(bridge_channel->chan, NULL, dtmf, 0, 0);
1281 }
1282
1283 /*! \brief Data specifying where a blind transfer is going to */
1284 struct blind_transfer_data {
1285         char exten[AST_MAX_EXTENSION];
1286         char context[AST_MAX_CONTEXT];
1287 };
1288
1289 /*!
1290  * \internal
1291  * \brief Execute after bridge actions on a channel when it leaves a bridge
1292  */
1293 static void after_bridge_move_channel(struct ast_channel *chan_bridged, void *data)
1294 {
1295         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1296         struct ast_party_connected_line connected_target;
1297         unsigned char connected_line_data[1024];
1298         int payload_size;
1299
1300         ast_party_connected_line_init(&connected_target);
1301
1302         ast_channel_lock(chan_target);
1303         ast_party_connected_line_copy(&connected_target, ast_channel_connected(chan_target));
1304         ast_channel_unlock(chan_target);
1305         ast_party_id_reset(&connected_target.priv);
1306
1307         if (ast_channel_move(chan_target, chan_bridged)) {
1308                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1309                 ast_party_connected_line_free(&connected_target);
1310                 return;
1311         }
1312
1313         if ((payload_size = ast_connected_line_build_data(connected_line_data,
1314                 sizeof(connected_line_data), &connected_target, NULL)) != -1) {
1315                 struct ast_control_read_action_payload *frame_payload;
1316                 int frame_size;
1317
1318                 frame_size = payload_size + sizeof(*frame_payload);
1319                 frame_payload = ast_alloca(frame_size);
1320                 frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
1321                 frame_payload->payload_size = payload_size;
1322                 memcpy(frame_payload->payload, connected_line_data, payload_size);
1323                 ast_queue_control_data(chan_target, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
1324         }
1325
1326         ast_party_connected_line_free(&connected_target);
1327 }
1328
1329 /*!
1330  * \internal
1331  * \brief Execute logic to cleanup when after bridge fails
1332  */
1333 static void after_bridge_move_channel_fail(enum ast_bridge_after_cb_reason reason, void *data)
1334 {
1335         RAII_VAR(struct ast_channel *, chan_target, data, ao2_cleanup);
1336
1337         ast_log(LOG_WARNING, "Unable to complete transfer: %s\n",
1338                 ast_bridge_after_cb_reason_string(reason));
1339         ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1340 }
1341
1342 /*!
1343  * \internal
1344  * \brief Perform a blind transfer on a channel in a bridge
1345  */
1346 static void bridge_channel_blind_transfer(struct ast_bridge_channel *bridge_channel,
1347                 struct blind_transfer_data *blind_data)
1348 {
1349         ast_async_goto(bridge_channel->chan, blind_data->context, blind_data->exten, 1);
1350         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1351 }
1352
1353 /*!
1354  * \internal
1355  * \brief Perform an attended transfer on a channel in a bridge
1356  */
1357 static void bridge_channel_attended_transfer(struct ast_bridge_channel *bridge_channel,
1358                 const char *target_chan_name)
1359 {
1360         RAII_VAR(struct ast_channel *, chan_target, NULL, ao2_cleanup);
1361         RAII_VAR(struct ast_channel *, chan_bridged, NULL, ao2_cleanup);
1362
1363         chan_target = ast_channel_get_by_name(target_chan_name);
1364         if (!chan_target) {
1365                 /* Dang, it disappeared somehow */
1366                 ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1367                 return;
1368         }
1369
1370         ast_bridge_channel_lock(bridge_channel);
1371         chan_bridged = bridge_channel->chan;
1372         ast_assert(chan_bridged != NULL);
1373         ao2_ref(chan_bridged, +1);
1374         ast_bridge_channel_unlock(bridge_channel);
1375
1376         if (ast_bridge_set_after_callback(chan_bridged, after_bridge_move_channel,
1377                 after_bridge_move_channel_fail, ast_channel_ref(chan_target))) {
1378                 ast_softhangup(chan_target, AST_SOFTHANGUP_DEV);
1379
1380                 /* Release the ref we tried to pass to ast_bridge_set_after_callback(). */
1381                 ast_channel_unref(chan_target);
1382         }
1383         ast_bridge_channel_kick(bridge_channel, AST_CAUSE_NORMAL_CLEARING);
1384 }
1385
1386 /*!
1387  * \internal
1388  * \brief Handle bridge channel bridge action frame.
1389  * \since 12.0.0
1390  *
1391  * \param bridge_channel Channel to execute the action on.
1392  * \param action What to do.
1393  *
1394  * \return Nothing
1395  */
1396 static void bridge_channel_handle_action(struct ast_bridge_channel *bridge_channel, struct ast_frame *action)
1397 {
1398         switch (action->subclass.integer) {
1399         case BRIDGE_CHANNEL_ACTION_DTMF_STREAM:
1400                 bridge_channel_suspend(bridge_channel);
1401                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1402                 bridge_channel_dtmf_stream(bridge_channel, action->data.ptr);
1403                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1404                 bridge_channel_unsuspend(bridge_channel);
1405                 break;
1406         case BRIDGE_CHANNEL_ACTION_TALKING_START:
1407         case BRIDGE_CHANNEL_ACTION_TALKING_STOP:
1408                 bridge_channel_talking(bridge_channel,
1409                         action->subclass.integer == BRIDGE_CHANNEL_ACTION_TALKING_START);
1410                 break;
1411         case BRIDGE_CHANNEL_ACTION_PLAY_FILE:
1412                 bridge_channel_suspend(bridge_channel);
1413                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1414                 bridge_channel_playfile(bridge_channel, action->data.ptr);
1415                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1416                 bridge_channel_unsuspend(bridge_channel);
1417                 break;
1418         case BRIDGE_CHANNEL_ACTION_RUN_APP:
1419                 bridge_channel_suspend(bridge_channel);
1420                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1421                 bridge_channel_run_app(bridge_channel, action->data.ptr);
1422                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1423                 bridge_channel_unsuspend(bridge_channel);
1424                 break;
1425         case BRIDGE_CHANNEL_ACTION_CALLBACK:
1426                 bridge_channel_do_callback(bridge_channel, action->data.ptr);
1427                 break;
1428         case BRIDGE_CHANNEL_ACTION_PARK:
1429                 bridge_channel_suspend(bridge_channel);
1430                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1431                 bridge_channel_park(bridge_channel, action->data.ptr);
1432                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1433                 bridge_channel_unsuspend(bridge_channel);
1434                 break;
1435         case BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER:
1436                 bridge_channel_blind_transfer(bridge_channel, action->data.ptr);
1437                 break;
1438         case BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER:
1439                 bridge_channel_attended_transfer(bridge_channel, action->data.ptr);
1440                 break;
1441         default:
1442                 break;
1443         }
1444 }
1445
1446 /*!
1447  * \internal
1448  * \brief Check if a bridge should dissolve and do it.
1449  * \since 12.0.0
1450  *
1451  * \param bridge_channel Channel causing the check.
1452  *
1453  * \note On entry, bridge_channel->bridge is already locked.
1454  *
1455  * \return Nothing
1456  */
1457 static void bridge_channel_dissolve_check(struct ast_bridge_channel *bridge_channel)
1458 {
1459         struct ast_bridge *bridge = bridge_channel->bridge;
1460
1461         if (bridge->dissolved) {
1462                 return;
1463         }
1464
1465         if (!bridge->num_channels
1466                 && ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_EMPTY)) {
1467                 /* Last channel leaving the bridge turns off the lights. */
1468                 bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
1469                 return;
1470         }
1471
1472         switch (bridge_channel->state) {
1473         case BRIDGE_CHANNEL_STATE_END:
1474                 /* Do we need to dissolve the bridge because this channel hung up? */
1475                 if (ast_test_flag(&bridge->feature_flags, AST_BRIDGE_FLAG_DISSOLVE_HANGUP)
1476                         || (bridge_channel->features->usable
1477                                 && ast_test_flag(&bridge_channel->features->feature_flags,
1478                                         AST_BRIDGE_CHANNEL_FLAG_DISSOLVE_HANGUP))) {
1479                         bridge_dissolve(bridge, ast_channel_hangupcause(bridge_channel->chan));
1480                         return;
1481                 }
1482                 break;
1483         default:
1484                 break;
1485         }
1486
1487         if (bridge->num_lonely && bridge->num_lonely == bridge->num_channels) {
1488                 /*
1489                  * This will start a chain reaction where each channel leaving
1490                  * enters this function and causes the next to leave as long as
1491                  * there aren't non-lonely channels in the bridge.
1492                  */
1493                 ast_bridge_channel_leave_bridge(AST_LIST_FIRST(&bridge->channels),
1494                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE,
1495                         ast_channel_hangupcause(bridge_channel->chan));
1496         }
1497 }
1498
1499 void bridge_channel_internal_pull(struct ast_bridge_channel *bridge_channel)
1500 {
1501         struct ast_bridge *bridge = bridge_channel->bridge;
1502
1503         if (!bridge_channel->in_bridge) {
1504                 return;
1505         }
1506         bridge_channel->in_bridge = 0;
1507
1508         ast_debug(1, "Bridge %s: pulling %p(%s)\n",
1509                 bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1510
1511         ast_verb(3, "Channel %s left '%s' %s-bridge <%s>\n",
1512                 ast_channel_name(bridge_channel->chan),
1513                 bridge->technology->name,
1514                 bridge->v_table->name,
1515                 bridge->uniqueid);
1516
1517         if (!bridge_channel->just_joined) {
1518                 /* Tell the bridge technology we are leaving so they tear us down */
1519                 ast_debug(1, "Bridge %s: %p(%s) is leaving %s technology\n",
1520                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1521                         bridge->technology->name);
1522                 if (bridge->technology->leave) {
1523                         bridge->technology->leave(bridge, bridge_channel);
1524                 }
1525         }
1526
1527         /* Remove channel from the bridge */
1528         if (!bridge_channel->suspended) {
1529                 --bridge->num_active;
1530         }
1531         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
1532                 --bridge->num_lonely;
1533         }
1534         --bridge->num_channels;
1535         AST_LIST_REMOVE(&bridge->channels, bridge_channel, entry);
1536         bridge->v_table->pull(bridge, bridge_channel);
1537
1538         ast_bridge_channel_clear_roles(bridge_channel);
1539
1540         /* If we are not going to be hung up after leaving a bridge, and we were an
1541          * outgoing channel, clear the outgoing flag.
1542          */
1543         if (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING)
1544                         && (ast_channel_softhangup_internal_flag(bridge_channel->chan) & (AST_SOFTHANGUP_ASYNCGOTO | AST_SOFTHANGUP_UNBRIDGE)
1545                             || bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT)) {
1546                 ast_debug(2, "Channel %s will survive this bridge; clearing outgoing (dialed) flag\n", ast_channel_name(bridge_channel->chan));
1547                 ast_clear_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_OUTGOING);
1548         }
1549
1550         bridge_channel_dissolve_check(bridge_channel);
1551
1552         bridge->reconfigured = 1;
1553         ast_bridge_publish_leave(bridge, bridge_channel->chan);
1554 }
1555
1556 int bridge_channel_internal_push(struct ast_bridge_channel *bridge_channel)
1557 {
1558         struct ast_bridge *bridge = bridge_channel->bridge;
1559         struct ast_bridge_channel *swap;
1560
1561         ast_assert(!bridge_channel->in_bridge);
1562
1563         swap = bridge_find_channel(bridge, bridge_channel->swap);
1564         bridge_channel->swap = NULL;
1565
1566         if (swap) {
1567                 ast_debug(1, "Bridge %s: pushing %p(%s) by swapping with %p(%s)\n",
1568                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan),
1569                         swap, ast_channel_name(swap->chan));
1570         } else {
1571                 ast_debug(1, "Bridge %s: pushing %p(%s)\n",
1572                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1573         }
1574
1575         /* Add channel to the bridge */
1576         if (bridge->dissolved
1577                 || bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT
1578                 || (swap && swap->state != BRIDGE_CHANNEL_STATE_WAIT)
1579                 || bridge->v_table->push(bridge, bridge_channel, swap)
1580                 || ast_bridge_channel_establish_roles(bridge_channel)) {
1581                 ast_debug(1, "Bridge %s: pushing %p(%s) into bridge failed\n",
1582                         bridge->uniqueid, bridge_channel, ast_channel_name(bridge_channel->chan));
1583                 return -1;
1584         }
1585         bridge_channel->in_bridge = 1;
1586         bridge_channel->just_joined = 1;
1587         AST_LIST_INSERT_TAIL(&bridge->channels, bridge_channel, entry);
1588         ++bridge->num_channels;
1589         if (ast_test_flag(&bridge_channel->features->feature_flags, AST_BRIDGE_CHANNEL_FLAG_LONELY)) {
1590                 ++bridge->num_lonely;
1591         }
1592         if (!bridge_channel->suspended) {
1593                 ++bridge->num_active;
1594         }
1595
1596         ast_verb(3, "Channel %s %s%s%s '%s' %s-bridge <%s>\n",
1597                 ast_channel_name(bridge_channel->chan),
1598                 swap ? "swapped with " : "joined",
1599                 swap ? ast_channel_name(swap->chan) : "",
1600                 swap ? " into" : "",
1601                 bridge->technology->name,
1602                 bridge->v_table->name,
1603                 bridge->uniqueid);
1604
1605         ast_bridge_publish_enter(bridge, bridge_channel->chan, swap ? swap->chan : NULL);
1606         if (swap) {
1607                 ast_bridge_channel_leave_bridge(swap, BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, 0);
1608                 bridge_channel_internal_pull(swap);
1609         }
1610
1611         /* Clear any BLINDTRANSFER and ATTENDEDTRANSFER since the transfer has completed. */
1612         pbx_builtin_setvar_helper(bridge_channel->chan, "BLINDTRANSFER", NULL);
1613         pbx_builtin_setvar_helper(bridge_channel->chan, "ATTENDEDTRANSFER", NULL);
1614
1615         /* Wake up the bridge channel thread to reevaluate any interval timers. */
1616         ast_queue_frame(bridge_channel->chan, &ast_null_frame);
1617
1618         bridge->reconfigured = 1;
1619         return 0;
1620 }
1621
1622 /*!
1623  * \internal
1624  * \brief Handle bridge channel control frame action.
1625  * \since 12.0.0
1626  *
1627  * \param bridge_channel Channel to execute the control frame action on.
1628  * \param fr Control frame to handle.
1629  *
1630  * \return Nothing
1631  */
1632 static void bridge_channel_handle_control(struct ast_bridge_channel *bridge_channel, struct ast_frame *fr)
1633 {
1634         struct ast_channel *chan;
1635         struct ast_option_header *aoh;
1636         int is_caller;
1637
1638         chan = bridge_channel->chan;
1639         switch (fr->subclass.integer) {
1640         case AST_CONTROL_REDIRECTING:
1641                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
1642                 if (ast_channel_redirecting_sub(NULL, chan, fr, 1) &&
1643                         ast_channel_redirecting_macro(NULL, chan, fr, is_caller, 1)) {
1644                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1645                 }
1646                 break;
1647         case AST_CONTROL_CONNECTED_LINE:
1648                 is_caller = !ast_test_flag(ast_channel_flags(chan), AST_FLAG_OUTGOING);
1649                 if (ast_channel_connected_line_sub(NULL, chan, fr, 1) &&
1650                         ast_channel_connected_line_macro(NULL, chan, fr, is_caller, 1)) {
1651                         ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1652                 }
1653                 break;
1654         case AST_CONTROL_OPTION:
1655                 /*
1656                  * Forward option Requests, but only ones we know are safe These
1657                  * are ONLY sent by chan_iax2 and I'm not convinced that they
1658                  * are useful. I haven't deleted them entirely because I just am
1659                  * not sure of the ramifications of removing them.
1660                  */
1661                 aoh = fr->data.ptr;
1662                 if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
1663                         switch (ntohs(aoh->option)) {
1664                         case AST_OPTION_TONE_VERIFY:
1665                         case AST_OPTION_TDD:
1666                         case AST_OPTION_RELAXDTMF:
1667                         case AST_OPTION_AUDIO_MODE:
1668                         case AST_OPTION_DIGIT_DETECT:
1669                         case AST_OPTION_FAX_DETECT:
1670                                 ast_channel_setoption(chan, ntohs(aoh->option), aoh->data,
1671                                         fr->datalen - sizeof(*aoh), 0);
1672                                 break;
1673                         default:
1674                                 break;
1675                         }
1676                 }
1677                 break;
1678         case AST_CONTROL_ANSWER:
1679                 if (ast_channel_state(chan) != AST_STATE_UP) {
1680                         ast_answer(chan);
1681                 } else {
1682                         ast_indicate(chan, -1);
1683                 }
1684                 break;
1685         default:
1686                 ast_indicate_data(chan, fr->subclass.integer, fr->data.ptr, fr->datalen);
1687                 break;
1688         }
1689 }
1690
1691 /*!
1692  * \internal
1693  * \brief Handle bridge channel write frame to channel.
1694  * \since 12.0.0
1695  *
1696  * \param bridge_channel Channel to write outgoing frame.
1697  *
1698  * \return Nothing
1699  */
1700 static void bridge_channel_handle_write(struct ast_bridge_channel *bridge_channel)
1701 {
1702         struct ast_frame *fr;
1703         char nudge;
1704
1705         ast_bridge_channel_lock(bridge_channel);
1706         if (read(bridge_channel->alert_pipe[0], &nudge, sizeof(nudge)) < 0) {
1707                 if (errno != EINTR && errno != EAGAIN) {
1708                         ast_log(LOG_WARNING, "read() failed for alert pipe on %p(%s): %s\n",
1709                                 bridge_channel, ast_channel_name(bridge_channel->chan), strerror(errno));
1710                 }
1711         }
1712         fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list);
1713         ast_bridge_channel_unlock(bridge_channel);
1714         if (!fr) {
1715                 return;
1716         }
1717         switch (fr->frametype) {
1718         case AST_FRAME_BRIDGE_ACTION:
1719                 bridge_channel_handle_action(bridge_channel, fr);
1720                 break;
1721         case AST_FRAME_CONTROL:
1722                 bridge_channel_handle_control(bridge_channel, fr);
1723                 break;
1724         case AST_FRAME_NULL:
1725                 break;
1726         default:
1727                 /* Write the frame to the channel. */
1728                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_SIMPLE;
1729                 ast_write(bridge_channel->chan, fr);
1730                 break;
1731         }
1732         ast_frfree(fr);
1733 }
1734
1735 /*! \brief Internal function to handle DTMF from a channel */
1736 static struct ast_frame *bridge_handle_dtmf(struct ast_bridge_channel *bridge_channel, struct ast_frame *frame)
1737 {
1738         struct ast_bridge_features *features = bridge_channel->features;
1739         struct ast_bridge_hook_dtmf *hook;
1740         char dtmf[2];
1741
1742         /* See if this DTMF matches the beginning of any feature hooks. */
1743         dtmf[0] = frame->subclass.integer;
1744         dtmf[1] = '\0';
1745         hook = ao2_find(features->dtmf_hooks, dtmf, OBJ_PARTIAL_KEY);
1746         if (hook) {
1747                 enum ast_frame_type frametype = frame->frametype;
1748
1749                 ast_frfree(frame);
1750                 frame = NULL;
1751
1752                 ao2_ref(hook, -1);
1753
1754                 /* Collect any more needed DTMF to execute a hook. */
1755                 bridge_channel_suspend(bridge_channel);
1756                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1757                 switch (frametype) {
1758                 case AST_FRAME_DTMF_BEGIN:
1759                         bridge_channel_feature(bridge_channel, NULL);
1760                         break;
1761                 case AST_FRAME_DTMF_END:
1762                         bridge_channel_feature(bridge_channel, dtmf);
1763                         break;
1764                 default:
1765                         /* Unexpected frame type. */
1766                         ast_assert(0);
1767                         break;
1768                 }
1769                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1770                 bridge_channel_unsuspend(bridge_channel);
1771 #ifdef TEST_FRAMEWORK
1772         } else if (frame->frametype == AST_FRAME_DTMF_END) {
1773                 /* Only transmit this event on DTMF end or else every DTMF
1774                  * press will result in the event being broadcast twice
1775                  */
1776                 ast_test_suite_event_notify("FEATURE_DETECTION", "Result: fail");
1777 #endif
1778         }
1779
1780         return frame;
1781 }
1782
1783
1784 /*!
1785  * \internal
1786  * \brief Feed notification that a frame is waiting on a channel into the bridging core
1787  *
1788  * \param bridge_channel Bridge channel the notification was received on
1789  */
1790 static void bridge_handle_trip(struct ast_bridge_channel *bridge_channel)
1791 {
1792         struct ast_frame *frame;
1793
1794         if (bridge_channel->features->mute) {
1795                 frame = ast_read_noaudio(bridge_channel->chan);
1796         } else {
1797                 frame = ast_read(bridge_channel->chan);
1798         }
1799
1800         if (!frame) {
1801                 ast_bridge_channel_kick(bridge_channel, 0);
1802                 return;
1803         }
1804         switch (frame->frametype) {
1805         case AST_FRAME_CONTROL:
1806                 switch (frame->subclass.integer) {
1807                 case AST_CONTROL_HANGUP:
1808                         ast_bridge_channel_kick(bridge_channel, 0);
1809                         ast_frfree(frame);
1810                         return;
1811                 default:
1812                         break;
1813                 }
1814                 break;
1815         case AST_FRAME_DTMF_BEGIN:
1816         case AST_FRAME_DTMF_END:
1817                 frame = bridge_handle_dtmf(bridge_channel, frame);
1818                 if (!frame) {
1819                         return;
1820                 }
1821                 if (!bridge_channel->features->dtmf_passthrough) {
1822                         ast_frfree(frame);
1823                         return;
1824                 }
1825                 break;
1826         default:
1827                 break;
1828         }
1829
1830         /* Simply write the frame out to the bridge technology. */
1831         bridge_channel_write_frame(bridge_channel, frame);
1832         ast_frfree(frame);
1833 }
1834
1835 /*!
1836  * \internal
1837  * \brief Determine how long till the next timer interval.
1838  * \since 12.0.0
1839  *
1840  * \param bridge_channel Channel to determine how long can wait.
1841  *
1842  * \retval ms Number of milliseconds to wait.
1843  * \retval -1 to wait forever.
1844  */
1845 static int bridge_channel_next_interval(struct ast_bridge_channel *bridge_channel)
1846 {
1847         struct ast_heap *interval_hooks = bridge_channel->features->interval_hooks;
1848         struct ast_bridge_hook_timer *hook;
1849         int ms;
1850
1851         ast_heap_wrlock(interval_hooks);
1852         hook = ast_heap_peek(interval_hooks, 1);
1853         if (hook) {
1854                 ms = ast_tvdiff_ms(hook->timer.trip_time, ast_tvnow());
1855                 if (ms < 0) {
1856                         /* Expire immediately.  An interval hook is ready to run. */
1857                         ms = 0;
1858                 }
1859         } else {
1860                 /* No hook so wait forever. */
1861                 ms = -1;
1862         }
1863         ast_heap_unlock(interval_hooks);
1864
1865         return ms;
1866 }
1867
1868 /*!
1869  * \internal
1870  * \brief Wait for something to happen on the bridge channel and handle it.
1871  * \since 12.0.0
1872  *
1873  * \param bridge_channel Channel to wait.
1874  *
1875  * \note Each channel does writing/reading in their own thread.
1876  *
1877  * \return Nothing
1878  */
1879 static void bridge_channel_wait(struct ast_bridge_channel *bridge_channel)
1880 {
1881         int ms;
1882         int outfd;
1883         struct ast_channel *chan;
1884
1885         /* Wait for data to either come from the channel or us to be signaled */
1886         ast_bridge_channel_lock(bridge_channel);
1887         if (bridge_channel->state != BRIDGE_CHANNEL_STATE_WAIT) {
1888         } else if (bridge_channel->suspended) {
1889 /* XXX ASTERISK-21271 the external party use of suspended will go away as will these references because this is the bridge channel thread */
1890                 ast_debug(1, "Bridge %s: %p(%s) is going into a signal wait\n",
1891                         bridge_channel->bridge->uniqueid, bridge_channel,
1892                         ast_channel_name(bridge_channel->chan));
1893                 ast_cond_wait(&bridge_channel->cond, ao2_object_get_lockaddr(bridge_channel));
1894         } else {
1895                 ast_bridge_channel_unlock(bridge_channel);
1896                 outfd = -1;
1897                 ms = bridge_channel_next_interval(bridge_channel);
1898                 chan = ast_waitfor_nandfds(&bridge_channel->chan, 1,
1899                         &bridge_channel->alert_pipe[0], 1, NULL, &outfd, &ms);
1900                 if (ast_channel_softhangup_internal_flag(bridge_channel->chan) & AST_SOFTHANGUP_UNBRIDGE) {
1901                         ast_channel_clear_softhangup(bridge_channel->chan, AST_SOFTHANGUP_UNBRIDGE);
1902                         ast_bridge_channel_lock_bridge(bridge_channel);
1903                         bridge_channel->bridge->reconfigured = 1;
1904                         bridge_reconfigured(bridge_channel->bridge, 0);
1905                         ast_bridge_unlock(bridge_channel->bridge);
1906                 }
1907                 ast_bridge_channel_lock(bridge_channel);
1908                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_FRAME;
1909                 ast_bridge_channel_unlock(bridge_channel);
1910                 if (!bridge_channel->suspended
1911                         && bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
1912                         if (chan) {
1913                                 bridge_handle_trip(bridge_channel);
1914                         } else if (-1 < outfd) {
1915                                 bridge_channel_handle_write(bridge_channel);
1916                         } else if (ms == 0) {
1917                                 /* An interval expired. */
1918                                 bridge_channel_handle_interval(bridge_channel);
1919                         }
1920                 }
1921                 bridge_channel->activity = BRIDGE_CHANNEL_THREAD_IDLE;
1922                 return;
1923         }
1924         ast_bridge_channel_unlock(bridge_channel);
1925 }
1926
1927 /*!
1928  * \internal
1929  * \brief Handle bridge channel join/leave event.
1930  * \since 12.0.0
1931  *
1932  * \param bridge_channel Which channel is involved.
1933  * \param type Specified join/leave event.
1934  *
1935  * \return Nothing
1936  */
1937 static void bridge_channel_event_join_leave(struct ast_bridge_channel *bridge_channel, enum ast_bridge_hook_type type)
1938 {
1939         struct ast_bridge_features *features = bridge_channel->features;
1940         struct ast_bridge_hook *hook;
1941         struct ao2_iterator iter;
1942
1943         /* Run the specified hooks. */
1944         iter = ao2_iterator_init(features->other_hooks, 0);
1945         for (; (hook = ao2_iterator_next(&iter)); ao2_ref(hook, -1)) {
1946                 if (hook->type == type) {
1947                         break;
1948                 }
1949         }
1950         if (hook) {
1951                 /* Found the first specified hook to run. */
1952                 bridge_channel_suspend(bridge_channel);
1953                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1954                 do {
1955                         if (hook->type == type) {
1956                                 hook->callback(bridge_channel, hook->hook_pvt);
1957                                 ao2_unlink(features->other_hooks, hook);
1958                         }
1959                         ao2_ref(hook, -1);
1960                 } while ((hook = ao2_iterator_next(&iter)));
1961                 ast_indicate(bridge_channel->chan, AST_CONTROL_SRCUPDATE);
1962                 bridge_channel_unsuspend(bridge_channel);
1963         }
1964         ao2_iterator_destroy(&iter);
1965 }
1966
1967 /*! \brief Join a channel to a bridge and handle anything the bridge may want us to do */
1968 int bridge_channel_internal_join(struct ast_bridge_channel *bridge_channel)
1969 {
1970         int res = 0;
1971
1972         ast_format_copy(&bridge_channel->read_format, ast_channel_readformat(bridge_channel->chan));
1973         ast_format_copy(&bridge_channel->write_format, ast_channel_writeformat(bridge_channel->chan));
1974
1975         ast_debug(1, "Bridge %s: %p(%s) is joining\n",
1976                 bridge_channel->bridge->uniqueid,
1977                 bridge_channel, ast_channel_name(bridge_channel->chan));
1978
1979         /*
1980          * Directly locking the bridge is safe here because nobody else
1981          * knows about this bridge_channel yet.
1982          */
1983         ast_bridge_lock(bridge_channel->bridge);
1984
1985         /* Make sure we're still good to be put into a bridge */
1986         ast_channel_lock(bridge_channel->chan);
1987         if (ast_channel_internal_bridge(bridge_channel->chan)
1988                 || ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_ZOMBIE)) {
1989                 ast_channel_unlock(bridge_channel->chan);
1990                 ast_bridge_unlock(bridge_channel->bridge);
1991                 ast_debug(1, "Bridge %s: %p(%s) failed to join Bridge\n",
1992                         bridge_channel->bridge->uniqueid,
1993                         bridge_channel,
1994                         ast_channel_name(bridge_channel->chan));
1995                 return -1;
1996         }
1997         ast_channel_internal_bridge_set(bridge_channel->chan, bridge_channel->bridge);
1998         ast_channel_unlock(bridge_channel->chan);
1999
2000         /* Add the jitterbuffer if the channel requires it */
2001         ast_jb_enable_for_channel(bridge_channel->chan);
2002
2003         if (!bridge_channel->bridge->callid) {
2004                 bridge_channel->bridge->callid = ast_read_threadstorage_callid();
2005         }
2006
2007         if (bridge_channel_internal_push(bridge_channel)) {
2008                 int cause = bridge_channel->bridge->cause;
2009
2010                 ast_bridge_unlock(bridge_channel->bridge);
2011                 ast_bridge_channel_kick(bridge_channel, cause);
2012                 ast_bridge_channel_lock_bridge(bridge_channel);
2013                 ast_bridge_features_remove(bridge_channel->features,
2014                         AST_BRIDGE_HOOK_REMOVE_ON_PULL);
2015                 bridge_channel_dissolve_check(bridge_channel);
2016                 res = -1;
2017         }
2018         bridge_reconfigured(bridge_channel->bridge, !bridge_channel->inhibit_colp);
2019
2020         if (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2021                 /*
2022                  * Indicate a source change since this channel is entering the
2023                  * bridge system only if the bridge technology is not MULTIMIX
2024                  * capable.  The MULTIMIX technology has already done it.
2025                  */
2026                 if (!(bridge_channel->bridge->technology->capabilities
2027                         & AST_BRIDGE_CAPABILITY_MULTIMIX)) {
2028                         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2029                 }
2030
2031                 ast_bridge_unlock(bridge_channel->bridge);
2032                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_JOIN);
2033                 while (bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2034                         /* Wait for something to do. */
2035                         bridge_channel_wait(bridge_channel);
2036                 }
2037                 bridge_channel_event_join_leave(bridge_channel, AST_BRIDGE_HOOK_TYPE_LEAVE);
2038                 ast_bridge_channel_lock_bridge(bridge_channel);
2039         }
2040
2041         bridge_channel_internal_pull(bridge_channel);
2042         bridge_channel_settle_owed_events(bridge_channel->bridge, bridge_channel);
2043         bridge_reconfigured(bridge_channel->bridge, 1);
2044
2045         ast_bridge_unlock(bridge_channel->bridge);
2046
2047         /* Complete any active hold before exiting the bridge. */
2048         if (ast_channel_hold_state(bridge_channel->chan) == AST_CONTROL_HOLD) {
2049                 ast_debug(1, "Channel %s simulating UNHOLD for bridge end.\n",
2050                         ast_channel_name(bridge_channel->chan));
2051                 ast_indicate(bridge_channel->chan, AST_CONTROL_UNHOLD);
2052         }
2053
2054         /* Complete any partial DTMF digit before exiting the bridge. */
2055         if (ast_channel_sending_dtmf_digit(bridge_channel->chan)) {
2056                 ast_channel_end_dtmf(bridge_channel->chan,
2057                         ast_channel_sending_dtmf_digit(bridge_channel->chan),
2058                         ast_channel_sending_dtmf_tv(bridge_channel->chan), "bridge end");
2059         }
2060
2061         /* Indicate a source change since this channel is leaving the bridge system. */
2062         ast_indicate(bridge_channel->chan, AST_CONTROL_SRCCHANGE);
2063
2064         /*
2065          * Wait for any dual redirect to complete.
2066          *
2067          * Must be done while "still in the bridge" for ast_async_goto()
2068          * to work right.
2069          */
2070         while (ast_test_flag(ast_channel_flags(bridge_channel->chan), AST_FLAG_BRIDGE_DUAL_REDIRECT_WAIT)) {
2071                 sched_yield();
2072         }
2073         ast_channel_lock(bridge_channel->chan);
2074         ast_channel_internal_bridge_set(bridge_channel->chan, NULL);
2075         ast_channel_unlock(bridge_channel->chan);
2076
2077         ast_bridge_channel_restore_formats(bridge_channel);
2078
2079         return res;
2080 }
2081
2082 int bridge_channel_internal_queue_blind_transfer(struct ast_channel *transferee,
2083                 const char *exten, const char *context,
2084                 transfer_channel_cb new_channel_cb, void *user_data)
2085 {
2086         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
2087         struct blind_transfer_data blind_data;
2088
2089         ast_channel_lock(transferee);
2090         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
2091         ast_channel_unlock(transferee);
2092
2093         if (!transferee_bridge_channel) {
2094                 return -1;
2095         }
2096
2097         if (new_channel_cb) {
2098                 new_channel_cb(transferee, user_data, AST_BRIDGE_TRANSFER_SINGLE_PARTY);
2099         }
2100
2101         ast_copy_string(blind_data.exten, exten, sizeof(blind_data.exten));
2102         ast_copy_string(blind_data.context, context, sizeof(blind_data.context));
2103
2104         return bridge_channel_queue_action_data(transferee_bridge_channel,
2105                 BRIDGE_CHANNEL_ACTION_BLIND_TRANSFER, &blind_data, sizeof(blind_data));
2106 }
2107
2108 int bridge_channel_internal_queue_attended_transfer(struct ast_channel *transferee,
2109                 struct ast_channel *unbridged_chan)
2110 {
2111         RAII_VAR(struct ast_bridge_channel *, transferee_bridge_channel, NULL, ao2_cleanup);
2112         char unbridged_chan_name[AST_CHANNEL_NAME];
2113
2114         ast_channel_lock(transferee);
2115         transferee_bridge_channel = ast_channel_get_bridge_channel(transferee);
2116         ast_channel_unlock(transferee);
2117
2118         if (!transferee_bridge_channel) {
2119                 return -1;
2120         }
2121
2122         ast_copy_string(unbridged_chan_name, ast_channel_name(unbridged_chan),
2123                 sizeof(unbridged_chan_name));
2124
2125         return bridge_channel_queue_action_data(transferee_bridge_channel,
2126                 BRIDGE_CHANNEL_ACTION_ATTENDED_TRANSFER, unbridged_chan_name,
2127                 sizeof(unbridged_chan_name));
2128 }
2129
2130 int bridge_channel_internal_allows_optimization(struct ast_bridge_channel *bridge_channel)
2131 {
2132         return bridge_channel->in_bridge
2133                 && AST_LIST_EMPTY(&bridge_channel->wr_queue);
2134 }
2135
2136 /*!
2137  * \internal
2138  * \brief Close a pipe.
2139  * \since 12.0.0
2140  *
2141  * \param my_pipe What to close.
2142  *
2143  * \return Nothing
2144  */
2145 static void pipe_close(int *my_pipe)
2146 {
2147         if (my_pipe[0] > -1) {
2148                 close(my_pipe[0]);
2149                 my_pipe[0] = -1;
2150         }
2151         if (my_pipe[1] > -1) {
2152                 close(my_pipe[1]);
2153                 my_pipe[1] = -1;
2154         }
2155 }
2156
2157 /*!
2158  * \internal
2159  * \brief Initialize a pipe as non-blocking.
2160  * \since 12.0.0
2161  *
2162  * \param my_pipe What to initialize.
2163  *
2164  * \retval 0 on success.
2165  * \retval -1 on error.
2166  */
2167 static int pipe_init_nonblock(int *my_pipe)
2168 {
2169         int flags;
2170
2171         my_pipe[0] = -1;
2172         my_pipe[1] = -1;
2173         if (pipe(my_pipe)) {
2174                 ast_log(LOG_WARNING, "Can't create pipe! Try increasing max file descriptors with ulimit -n\n");
2175                 return -1;
2176         }
2177         flags = fcntl(my_pipe[0], F_GETFL);
2178         if (fcntl(my_pipe[0], F_SETFL, flags | O_NONBLOCK) < 0) {
2179                 ast_log(LOG_WARNING, "Unable to set read pipe nonblocking! (%d: %s)\n",
2180                         errno, strerror(errno));
2181                 return -1;
2182         }
2183         flags = fcntl(my_pipe[1], F_GETFL);
2184         if (fcntl(my_pipe[1], F_SETFL, flags | O_NONBLOCK) < 0) {
2185                 ast_log(LOG_WARNING, "Unable to set write pipe nonblocking! (%d: %s)\n",
2186                         errno, strerror(errno));
2187                 return -1;
2188         }
2189         return 0;
2190 }
2191
2192 /* Destroy elements of the bridge channel structure and the bridge channel structure itself */
2193 static void bridge_channel_destroy(void *obj)
2194 {
2195         struct ast_bridge_channel *bridge_channel = obj;
2196         struct ast_frame *fr;
2197
2198         if (bridge_channel->callid) {
2199                 bridge_channel->callid = ast_callid_unref(bridge_channel->callid);
2200         }
2201
2202         if (bridge_channel->bridge) {
2203                 ao2_ref(bridge_channel->bridge, -1);
2204                 bridge_channel->bridge = NULL;
2205         }
2206
2207         /* Flush any unhandled wr_queue frames. */
2208         while ((fr = AST_LIST_REMOVE_HEAD(&bridge_channel->wr_queue, frame_list))) {
2209                 ast_frfree(fr);
2210         }
2211         pipe_close(bridge_channel->alert_pipe);
2212
2213         ast_cond_destroy(&bridge_channel->cond);
2214 }
2215
2216 struct ast_bridge_channel *bridge_channel_internal_alloc(struct ast_bridge *bridge)
2217 {
2218         struct ast_bridge_channel *bridge_channel;
2219
2220         bridge_channel = ao2_alloc(sizeof(struct ast_bridge_channel), bridge_channel_destroy);
2221         if (!bridge_channel) {
2222                 return NULL;
2223         }
2224         ast_cond_init(&bridge_channel->cond, NULL);
2225         if (pipe_init_nonblock(bridge_channel->alert_pipe)) {
2226                 ao2_ref(bridge_channel, -1);
2227                 return NULL;
2228         }
2229         if (bridge) {
2230                 bridge_channel->bridge = bridge;
2231                 ao2_ref(bridge_channel->bridge, +1);
2232         }
2233
2234         return bridge_channel;
2235 }