features: Fix crash when transferee hangs up during DTMF attended transfer.
[asterisk/asterisk.git] / main / bridge_basic.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013 Digium, Inc.
5  *
6  * Richard Mudgett <rmudgett@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 /*!
20  * \file
21  * \brief Basic bridge class.  It is a subclass of struct ast_bridge.
22  *
23  * \author Richard Mudgett <rmudgett@digium.com>
24  *
25  * See Also:
26  * \arg \ref AstCREDITS
27  */
28
29
30 #include "asterisk.h"
31
32 ASTERISK_REGISTER_FILE()
33
34 #include "asterisk/channel.h"
35 #include "asterisk/utils.h"
36 #include "asterisk/linkedlists.h"
37 #include "asterisk/bridge.h"
38 #include "asterisk/bridge_internal.h"
39 #include "asterisk/bridge_basic.h"
40 #include "asterisk/bridge_after.h"
41 #include "asterisk/astobj2.h"
42 #include "asterisk/features_config.h"
43 #include "asterisk/pbx.h"
44 #include "asterisk/file.h"
45 #include "asterisk/app.h"
46 #include "asterisk/dial.h"
47 #include "asterisk/stasis_bridges.h"
48 #include "asterisk/stasis_channels.h"
49 #include "asterisk/features.h"
50 #include "asterisk/format_cache.h"
51 #include "asterisk/test.h"
52
53 #define NORMAL_FLAGS    (AST_BRIDGE_FLAG_DISSOLVE_HANGUP | AST_BRIDGE_FLAG_DISSOLVE_EMPTY \
54                         | AST_BRIDGE_FLAG_SMART)
55
56 #define TRANSFER_FLAGS AST_BRIDGE_FLAG_SMART
57
58 struct attended_transfer_properties;
59
60 enum bridge_basic_personality_type {
61         /*! Index for "normal" basic bridge personality */
62         BRIDGE_BASIC_PERSONALITY_NORMAL,
63         /*! Index for attended transfer basic bridge personality */
64         BRIDGE_BASIC_PERSONALITY_ATXFER,
65         /*! Indicates end of enum. Must always remain the last element */
66         BRIDGE_BASIC_PERSONALITY_END,
67 };
68
69 /*!
70  * \brief Change basic bridge personality
71  *
72  * Changing personalities allows for the bridge to remain in use but have
73  * properties such as its v_table and its flags change.
74  *
75  * \param bridge The bridge
76  * \param type The personality to change the bridge to
77  * \user_data Private data to attach to the personality.
78  */
79 static void bridge_basic_change_personality(struct ast_bridge *bridge,
80                 enum bridge_basic_personality_type type, void *user_data);
81
82 /* ------------------------------------------------------------------- */
83
84 static const struct ast_datastore_info dtmf_features_info = {
85         .type = "bridge-dtmf-features",
86         .destroy = ast_free_ptr,
87 };
88
89 /*!
90  * \internal
91  * \since 12.0.0
92  * \brief read a feature code character and set it on for the give feature_flags struct
93  *
94  * \param feature_flags flags being modifed
95  * \param feature feature code provided - should be an uppercase letter
96  *
97  * \retval 0 if the feature was set successfully
98  * \retval -1 failure because the requested feature code isn't handled by this function
99  */
100 static int set_feature_flag_from_char(struct ast_flags *feature_flags, char feature)
101 {
102         switch (feature) {
103         case 'T':
104                 ast_set_flag(feature_flags, AST_FEATURE_REDIRECT);
105                 return 0;
106         case 'K':
107                 ast_set_flag(feature_flags, AST_FEATURE_PARKCALL);
108                 return 0;
109         case 'H':
110                 ast_set_flag(feature_flags, AST_FEATURE_DISCONNECT);
111                 return 0;
112         case 'W':
113                 ast_set_flag(feature_flags, AST_FEATURE_AUTOMON);
114                 return 0;
115         case 'X':
116                 ast_set_flag(feature_flags, AST_FEATURE_AUTOMIXMON);
117                 return 0;
118         default:
119                 return -1;
120         }
121 }
122
123 /*!
124  * \internal
125  * \since 12.0.0
126  * \brief Write a features string to a string buffer based on the feature flags provided
127  *
128  * \param feature_flags pointer to the feature flags to write from.
129  * \param buffer pointer to a string buffer to write the features
130  * \param buffer_size size of the buffer provided (should be able to fit all feature codes)
131  *
132  * \retval 0 on successful write
133  * \retval -1 failure due to running out of buffer space
134  */
135 static int dtmf_features_flags_to_string(struct ast_flags *feature_flags, char *buffer, size_t buffer_size)
136 {
137         size_t buffer_expended = 0;
138         unsigned int cur_feature;
139         static const struct {
140                 char letter;
141                 unsigned int flag;
142         } associations[] = {
143                 { 'T', AST_FEATURE_REDIRECT },
144                 { 'K', AST_FEATURE_PARKCALL },
145                 { 'H', AST_FEATURE_DISCONNECT },
146                 { 'W', AST_FEATURE_AUTOMON },
147                 { 'X', AST_FEATURE_AUTOMIXMON },
148         };
149
150         for (cur_feature = 0; cur_feature < ARRAY_LEN(associations); cur_feature++) {
151                 if (ast_test_flag(feature_flags, associations[cur_feature].flag)) {
152                         if (buffer_expended == buffer_size - 1) {
153                                 buffer[buffer_expended] = '\0';
154                                 return -1;
155                         }
156                         buffer[buffer_expended++] = associations[cur_feature].letter;
157                 }
158         }
159
160         buffer[buffer_expended] = '\0';
161         return 0;
162 }
163
164 static int build_dtmf_features(struct ast_flags *flags, const char *features)
165 {
166         const char *feature;
167
168         char missing_features[strlen(features) + 1];
169         size_t number_of_missing_features = 0;
170
171         for (feature = features; *feature; feature++) {
172                 if (!isupper(*feature)) {
173                         ast_log(LOG_ERROR, "Features string '%s' rejected because it contains non-uppercase feature.\n", features);
174                         return -1;
175                 }
176
177                 if (set_feature_flag_from_char(flags, *feature)) {
178                         missing_features[number_of_missing_features++] = *feature;
179                 }
180         }
181
182         missing_features[number_of_missing_features] = '\0';
183
184         if (number_of_missing_features) {
185                 ast_log(LOG_WARNING, "Features '%s' from features string '%s' can not be applied.\n", missing_features, features);
186         }
187
188         return 0;
189 }
190
191 int ast_bridge_features_ds_set_string(struct ast_channel *chan, const char *features)
192 {
193         struct ast_flags flags = {0};
194
195         if (build_dtmf_features(&flags, features)) {
196                 return -1;
197         }
198
199         ast_channel_lock(chan);
200         if (ast_bridge_features_ds_set(chan, &flags)) {
201                 ast_channel_unlock(chan);
202                 ast_log(LOG_ERROR, "Failed to apply features datastore for '%s' to channel '%s'\n", features, ast_channel_name(chan));
203                 return -1;
204         }
205         ast_channel_unlock(chan);
206
207         return 0;
208 }
209
210 int ast_bridge_features_ds_get_string(struct ast_channel *chan, char *buffer, size_t buf_size)
211 {
212         struct ast_flags *channel_flags;
213         struct ast_flags held_copy;
214
215         ast_channel_lock(chan);
216         if (!(channel_flags = ast_bridge_features_ds_get(chan))) {
217                 ast_channel_unlock(chan);
218                 return -1;
219         }
220         held_copy = *channel_flags;
221         ast_channel_unlock(chan);
222
223         return dtmf_features_flags_to_string(&held_copy, buffer, buf_size);
224 }
225
226 static int bridge_features_ds_set_full(struct ast_channel *chan, struct ast_flags *flags, int replace)
227 {
228         struct ast_datastore *datastore;
229         struct ast_flags *ds_flags;
230
231         datastore = ast_channel_datastore_find(chan, &dtmf_features_info, NULL);
232         if (datastore) {
233                 ds_flags = datastore->data;
234                 if (replace) {
235                         *ds_flags = *flags;
236                 } else {
237                         flags->flags = flags->flags | ds_flags->flags;
238                         *ds_flags = *flags;
239                 }
240                 return 0;
241         }
242
243         datastore = ast_datastore_alloc(&dtmf_features_info, NULL);
244         if (!datastore) {
245                 return -1;
246         }
247
248         ds_flags = ast_malloc(sizeof(*ds_flags));
249         if (!ds_flags) {
250                 ast_datastore_free(datastore);
251                 return -1;
252         }
253
254         *ds_flags = *flags;
255         datastore->data = ds_flags;
256         ast_channel_datastore_add(chan, datastore);
257         return 0;
258 }
259
260 int ast_bridge_features_ds_set(struct ast_channel *chan, struct ast_flags *flags)
261 {
262         return bridge_features_ds_set_full(chan, flags, 1);
263 }
264
265 int ast_bridge_features_ds_append(struct ast_channel *chan, struct ast_flags *flags)
266 {
267         return bridge_features_ds_set_full(chan, flags, 0);
268 }
269
270 struct ast_flags *ast_bridge_features_ds_get(struct ast_channel *chan)
271 {
272         struct ast_datastore *datastore;
273
274         datastore = ast_channel_datastore_find(chan, &dtmf_features_info, NULL);
275         if (!datastore) {
276                 return NULL;
277         }
278         return datastore->data;
279 }
280
281 /*!
282  * \internal
283  * \brief Determine if we should dissolve the bridge from a hangup.
284  * \since 12.0.0
285  *
286  * \param bridge_channel Channel executing the feature
287  * \param hook_pvt Private data passed in when the hook was created
288  *
289  * \retval 0 Keep the callback hook.
290  * \retval -1 Remove the callback hook.
291  */
292 static int basic_hangup_hook(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
293 {
294         int bridge_count = 0;
295         struct ast_bridge_channel *iter;
296
297         ast_bridge_channel_lock_bridge(bridge_channel);
298         AST_LIST_TRAVERSE(&bridge_channel->bridge->channels, iter, entry) {
299                 if (iter != bridge_channel && iter->state == BRIDGE_CHANNEL_STATE_WAIT) {
300                         ++bridge_count;
301                 }
302         }
303         if (2 <= bridge_count) {
304                 /* Just allow this channel to leave the multi-party bridge. */
305                 ast_bridge_channel_leave_bridge(bridge_channel,
306                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, 0);
307         }
308         ast_bridge_unlock(bridge_channel->bridge);
309         return 0;
310 }
311
312 /*!
313  * \brief Details for specific basic bridge personalities
314  */
315 struct personality_details {
316         /*! The v_table to use for this personality */
317         struct ast_bridge_methods *v_table;
318         /*! Flags to set on this type of bridge */
319         unsigned int bridge_flags;
320         /*! User data for this personality. If used, must be an ao2 object */
321         void *pvt;
322         /*! Callback to be called when changing to the personality */
323         void (*on_personality_change)(struct ast_bridge *bridge);
324 };
325
326 /*!
327  * \brief structure that organizes different personalities for basic bridges.
328  */
329 struct bridge_basic_personality {
330         /*! The current bridge personality in use */
331         enum bridge_basic_personality_type current;
332         /*! Array of details for the types of bridge personalities supported */
333         struct personality_details details[BRIDGE_BASIC_PERSONALITY_END];
334 };
335
336 /*
337  * \internal
338  * \brief Get the extension for a given builtin feature.
339  *
340  * \param chan Get the feature extension for this channel.
341  * \param feature_name features.conf name of feature.
342  * \param buf Where to put the extension.
343  * \param len Length of the given extension buffer.
344  *
345  * \retval 0 success
346  * \retval non-zero failiure
347  */
348 static int builtin_feature_get_exten(struct ast_channel *chan, const char *feature_name, char *buf, size_t len)
349 {
350         SCOPED_CHANNELLOCK(lock, chan);
351
352         return ast_get_builtin_feature(chan, feature_name, buf, len);
353 }
354
355 /*!
356  * \internal
357  * \brief Helper to add a builtin DTMF feature hook to the features struct.
358  * \since 12.0.0
359  *
360  * \param features Bridge features to setup.
361  * \param chan Get features from this channel.
362  * \param flags Feature flags on the channel.
363  * \param feature_flag Feature flag to test.
364  * \param feature_name features.conf name of feature.
365  * \param feature_bridge Bridge feature enum to get hook callback.
366  *
367  * \retval 0 on success.
368  * \retval -1 on error.
369  */
370 static int builtin_features_helper(struct ast_bridge_features *features, struct ast_channel *chan,
371         struct ast_flags *flags, unsigned int feature_flag, const char *feature_name, enum ast_bridge_builtin_feature feature_bridge)
372 {
373         char dtmf[AST_FEATURE_MAX_LEN];
374         int res;
375
376         res = 0;
377         if (ast_test_flag(flags, feature_flag)
378                 && !builtin_feature_get_exten(chan, feature_name, dtmf, sizeof(dtmf))
379                 && !ast_strlen_zero(dtmf)) {
380                 res = ast_bridge_features_enable(features, feature_bridge, dtmf, NULL, NULL,
381                         AST_BRIDGE_HOOK_REMOVE_ON_PULL | AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE);
382                 if (res) {
383                         ast_log(LOG_ERROR, "Channel %s: Requested DTMF feature %s not available.\n",
384                                 ast_channel_name(chan), feature_name);
385                 }
386         }
387
388         return res;
389 }
390
391 /*!
392  * \internal
393  * \brief Setup bridge builtin features.
394  * \since 12.0.0
395  *
396  * \param features Bridge features to setup.
397  * \param chan Get features from this channel.
398  *
399  * \retval 0 on success.
400  * \retval -1 on error.
401  */
402 static int setup_bridge_features_builtin(struct ast_bridge_features *features, struct ast_channel *chan)
403 {
404         struct ast_flags *flags;
405         int res;
406
407         ast_channel_lock(chan);
408         flags = ast_bridge_features_ds_get(chan);
409         ast_channel_unlock(chan);
410         if (!flags) {
411                 return 0;
412         }
413
414         res = 0;
415         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_REDIRECT, "blindxfer", AST_BRIDGE_BUILTIN_BLINDTRANSFER);
416         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_REDIRECT, "atxfer", AST_BRIDGE_BUILTIN_ATTENDEDTRANSFER);
417         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_DISCONNECT, "disconnect", AST_BRIDGE_BUILTIN_HANGUP);
418         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_PARKCALL, "parkcall", AST_BRIDGE_BUILTIN_PARKCALL);
419         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_AUTOMON, "automon", AST_BRIDGE_BUILTIN_AUTOMON);
420         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_AUTOMIXMON, "automixmon", AST_BRIDGE_BUILTIN_AUTOMIXMON);
421
422         return res ? -1 : 0;
423 }
424
425 struct dynamic_dtmf_hook_run {
426         /*! Offset into app_name[] where the channel name that activated the hook starts. */
427         int activated_offset;
428         /*! Offset into app_name[] where the dynamic feature name starts. */
429         int feature_offset;
430         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
431         int moh_offset;
432         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
433         int app_args_offset;
434         /*! Application name to run. */
435         char app_name[0];
436 };
437
438 static void dynamic_dtmf_hook_callback(struct ast_bridge_channel *bridge_channel,
439         const void *payload, size_t payload_size)
440 {
441         struct ast_channel *chan = bridge_channel->chan;
442         const struct dynamic_dtmf_hook_run *run_data = payload;
443
444         pbx_builtin_setvar_helper(chan, "DYNAMIC_FEATURENAME",
445                 &run_data->app_name[run_data->feature_offset]);
446         pbx_builtin_setvar_helper(chan, "DYNAMIC_WHO_ACTIVATED",
447                 &run_data->app_name[run_data->activated_offset]);
448
449         ast_bridge_channel_run_app(bridge_channel, run_data->app_name,
450                 run_data->app_args_offset ? &run_data->app_name[run_data->app_args_offset] : NULL,
451                 run_data->moh_offset ? &run_data->app_name[run_data->moh_offset] : NULL);
452 }
453
454 struct dynamic_dtmf_hook_data {
455         /*! Which side of bridge to run app (AST_FEATURE_FLAG_ONSELF/AST_FEATURE_FLAG_ONPEER) */
456         unsigned int flags;
457         /*! Offset into app_name[] where the dynamic feature name starts. */
458         int feature_offset;
459         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
460         int moh_offset;
461         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
462         int app_args_offset;
463         /*! Application name to run. */
464         char app_name[0];
465 };
466
467 /*!
468  * \internal
469  * \brief Activated dynamic DTMF feature hook.
470  * \since 12.0.0
471  *
472  * \param bridge_channel Channel executing the feature
473  * \param hook_pvt Private data passed in when the hook was created
474  *
475  * \retval 0 Keep the callback hook.
476  * \retval -1 Remove the callback hook.
477  */
478 static int dynamic_dtmf_hook_trip(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
479 {
480         struct dynamic_dtmf_hook_data *pvt = hook_pvt;
481         struct dynamic_dtmf_hook_run *run_data;
482         const char *activated_name;
483         size_t len_name;
484         size_t len_args;
485         size_t len_moh;
486         size_t len_feature;
487         size_t len_activated;
488         size_t len_data;
489
490         /* Determine lengths of things. */
491         len_name = strlen(pvt->app_name) + 1;
492         len_args = pvt->app_args_offset ? strlen(&pvt->app_name[pvt->app_args_offset]) + 1 : 0;
493         len_moh = pvt->moh_offset ? strlen(&pvt->app_name[pvt->moh_offset]) + 1 : 0;
494         len_feature = strlen(&pvt->app_name[pvt->feature_offset]) + 1;
495         ast_channel_lock(bridge_channel->chan);
496         activated_name = ast_strdupa(ast_channel_name(bridge_channel->chan));
497         ast_channel_unlock(bridge_channel->chan);
498         len_activated = strlen(activated_name) + 1;
499         len_data = sizeof(*run_data) + len_name + len_args + len_moh + len_feature + len_activated;
500
501         /* Fill in dynamic feature run hook data. */
502         run_data = ast_alloca(len_data);
503         run_data->app_args_offset = len_args ? len_name : 0;
504         run_data->moh_offset = len_moh ? len_name + len_args : 0;
505         run_data->feature_offset = len_name + len_args + len_moh;
506         run_data->activated_offset = len_name + len_args + len_moh + len_feature;
507         strcpy(run_data->app_name, pvt->app_name);/* Safe */
508         if (len_args) {
509                 strcpy(&run_data->app_name[run_data->app_args_offset],
510                         &pvt->app_name[pvt->app_args_offset]);/* Safe */
511         }
512         if (len_moh) {
513                 strcpy(&run_data->app_name[run_data->moh_offset],
514                         &pvt->app_name[pvt->moh_offset]);/* Safe */
515         }
516         strcpy(&run_data->app_name[run_data->feature_offset],
517                 &pvt->app_name[pvt->feature_offset]);/* Safe */
518         strcpy(&run_data->app_name[run_data->activated_offset], activated_name);/* Safe */
519
520         if (ast_test_flag(pvt, AST_FEATURE_FLAG_ONPEER)) {
521                 ast_bridge_channel_write_callback(bridge_channel,
522                         AST_BRIDGE_CHANNEL_CB_OPTION_MEDIA,
523                         dynamic_dtmf_hook_callback, run_data, len_data);
524         } else {
525                 dynamic_dtmf_hook_callback(bridge_channel, run_data, len_data);
526         }
527         return 0;
528 }
529
530 /*!
531  * \internal
532  * \brief Add a dynamic DTMF feature hook to the bridge features.
533  * \since 12.0.0
534  *
535  * \param features Bridge features to setup.
536  * \param flags Which side of bridge to run app (AST_FEATURE_FLAG_ONSELF/AST_FEATURE_FLAG_ONPEER).
537  * \param dtmf DTMF trigger sequence.
538  * \param feature_name Name of the dynamic feature.
539  * \param app_name Dialplan application name to run.
540  * \param app_args Dialplan application arguments. (Empty or NULL if no arguments)
541  * \param moh_class MOH class to play to peer. (Empty or NULL if no MOH played)
542  *
543  * \retval 0 on success.
544  * \retval -1 on error.
545  */
546 static int dynamic_dtmf_hook_add(struct ast_bridge_features *features, unsigned int flags, const char *dtmf, const char *feature_name, const char *app_name, const char *app_args, const char *moh_class)
547 {
548         struct dynamic_dtmf_hook_data *hook_data;
549         size_t len_name = strlen(app_name) + 1;
550         size_t len_args = ast_strlen_zero(app_args) ? 0 : strlen(app_args) + 1;
551         size_t len_moh = ast_strlen_zero(moh_class) ? 0 : strlen(moh_class) + 1;
552         size_t len_feature = strlen(feature_name) + 1;
553         size_t len_data = sizeof(*hook_data) + len_name + len_args + len_moh + len_feature;
554         int res;
555
556         /* Fill in application run hook data. */
557         hook_data = ast_malloc(len_data);
558         if (!hook_data) {
559                 return -1;
560         }
561         hook_data->flags = flags;
562         hook_data->app_args_offset = len_args ? len_name : 0;
563         hook_data->moh_offset = len_moh ? len_name + len_args : 0;
564         hook_data->feature_offset = len_name + len_args + len_moh;
565         strcpy(hook_data->app_name, app_name);/* Safe */
566         if (len_args) {
567                 strcpy(&hook_data->app_name[hook_data->app_args_offset], app_args);/* Safe */
568         }
569         if (len_moh) {
570                 strcpy(&hook_data->app_name[hook_data->moh_offset], moh_class);/* Safe */
571         }
572         strcpy(&hook_data->app_name[hook_data->feature_offset], feature_name);/* Safe */
573
574         res = ast_bridge_dtmf_hook(features, dtmf, dynamic_dtmf_hook_trip, hook_data,
575                 ast_free_ptr,
576                 AST_BRIDGE_HOOK_REMOVE_ON_PULL | AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE);
577         if (res) {
578                 ast_free(hook_data);
579         }
580         return res;
581 }
582
583 static int setup_dynamic_feature(void *obj, void *arg, void *data, int flags)
584 {
585         struct ast_applicationmap_item *item = obj;
586         struct ast_bridge_features *features = arg;
587         int *res = data;
588
589         *res |= dynamic_dtmf_hook_add(features,
590                 item->activate_on_self ? AST_FEATURE_FLAG_ONSELF : AST_FEATURE_FLAG_ONPEER,
591                 item->dtmf, item->name, item->app, item->app_data, item->moh_class);
592
593         return 0;
594 }
595
596 /*!
597  * \internal
598  * \brief Setup bridge dynamic features.
599  * \since 12.0.0
600  *
601  * \param features Bridge features to setup.
602  * \param chan Get features from this channel.
603  *
604  * \retval 0 on success.
605  * \retval -1 on error.
606  */
607 static int setup_bridge_features_dynamic(struct ast_bridge_features *features, struct ast_channel *chan)
608 {
609         struct ao2_container *applicationmap;
610         int res = 0;
611
612         ast_channel_lock(chan);
613         applicationmap = ast_get_chan_applicationmap(chan);
614         ast_channel_unlock(chan);
615         if (applicationmap) {
616                 ao2_callback_data(applicationmap, 0, setup_dynamic_feature, features, &res);
617                 ao2_ref(applicationmap, -1);
618         }
619
620         return res;
621 }
622
623 /*!
624  * \internal
625  * \brief Setup DTMF feature hooks using the channel features datastore property.
626  * \since 12.0.0
627  *
628  * \param bridge_channel What to setup DTMF features on.
629  *
630  * \retval 0 on success.
631  * \retval -1 on error.
632  */
633 static int bridge_basic_setup_features(struct ast_bridge_channel *bridge_channel)
634 {
635         int res = 0;
636
637         res |= setup_bridge_features_builtin(bridge_channel->features, bridge_channel->chan);
638         res |= setup_bridge_features_dynamic(bridge_channel->features, bridge_channel->chan);
639
640         return res;
641 }
642
643 static int add_normal_hooks(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
644 {
645         return ast_bridge_hangup_hook(bridge_channel->features, basic_hangup_hook,
646                         NULL, NULL, AST_BRIDGE_HOOK_REMOVE_ON_PULL)
647                 || bridge_basic_setup_features(bridge_channel);
648 }
649
650 /*!
651  * \internal
652  * \brief ast_bridge basic push method.
653  * \since 12.0.0
654  *
655  * \param self Bridge to operate upon.
656  * \param bridge_channel Bridge channel to push.
657  * \param swap Bridge channel to swap places with if not NULL.
658  *
659  * \note On entry, self is already locked.
660  *
661  * \retval 0 on success
662  * \retval -1 on failure
663  */
664 static int bridge_personality_normal_push(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
665 {
666         if (add_normal_hooks(self, bridge_channel)) {
667                 return -1;
668         }
669
670         return 0;
671 }
672
673 static int bridge_basic_push(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
674 {
675         struct bridge_basic_personality *personality = self->personality;
676
677         ast_assert(personality != NULL);
678
679         if (personality->details[personality->current].v_table->push
680                 && personality->details[personality->current].v_table->push(self, bridge_channel, swap)) {
681                 return -1;
682         }
683
684         ast_bridge_channel_update_linkedids(bridge_channel, swap);
685         ast_bridge_channel_update_accountcodes(bridge_channel, swap);
686
687         return ast_bridge_base_v_table.push(self, bridge_channel, swap);
688 }
689
690 static void bridge_basic_pull(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel)
691 {
692         struct bridge_basic_personality *personality = self->personality;
693
694         ast_assert(personality != NULL);
695
696         if (personality->details[personality->current].v_table->pull) {
697                 personality->details[personality->current].v_table->pull(self, bridge_channel);
698         }
699
700         ast_bridge_channel_update_accountcodes(NULL, bridge_channel);
701
702         ast_bridge_base_v_table.pull(self, bridge_channel);
703 }
704
705 static void bridge_basic_destroy(struct ast_bridge *self)
706 {
707         struct bridge_basic_personality *personality = self->personality;
708
709         ao2_cleanup(personality);
710
711         ast_bridge_base_v_table.destroy(self);
712 }
713
714 /*!
715  * \brief Remove appropriate hooks when basic bridge personality changes
716  *
717  * Hooks that have the AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE flag
718  * set will be removed from all bridge channels in the bridge.
719  *
720  * \param bridge Basic bridge undergoing personality change
721  */
722 static void remove_hooks_on_personality_change(struct ast_bridge *bridge)
723 {
724         struct ast_bridge_channel *iter;
725
726         AST_LIST_TRAVERSE(&bridge->channels, iter, entry) {
727                 SCOPED_LOCK(lock, iter, ast_bridge_channel_lock, ast_bridge_channel_unlock);
728                 ast_bridge_features_remove(iter->features, AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE);
729         }
730 }
731
732 /*!
733  * \brief Attended transfer superstates.
734  *
735  * An attended transfer's progress is facilitated by a state machine.
736  * The individual states of the state machine fall into the realm of
737  * one of two superstates.
738  */
739 enum attended_transfer_superstate {
740         /*!
741          * \brief Transfer superstate
742          *
743          * The attended transfer state machine begins in this superstate. The
744          * goal of this state is for a transferer channel to facilitate a
745          * transfer from a transferee to a transfer target.
746          *
747          * There are two bridges used in this superstate. The transferee bridge is
748          * the bridge that the transferer and transferee channels originally
749          * communicate in, and the target bridge is the bridge where the transfer
750          * target is being dialed.
751          *
752          * The transferer channel is capable of moving between the bridges using
753          * the DTMF swap sequence.
754          */
755         SUPERSTATE_TRANSFER,
756         /*!
757          * \brief Recall superstate
758          *
759          * The attended transfer state machine moves to this superstate if
760          * atxferdropcall is set to "no" and the transferer channel hangs up
761          * during a transfer. The goal in this superstate is to call back either
762          * the transfer target or transferer and rebridge with the transferee
763          * channel(s).
764          *
765          * In this superstate, there is only a single bridge used, the original
766          * transferee bridge. Rather than distinguishing between a transferer
767          * and transfer target, all outbound calls are toward a "recall_target"
768          * channel.
769          */
770         SUPERSTATE_RECALL,
771 };
772
773 /*!
774  * The states in the attended transfer state machine.
775  */
776 enum attended_transfer_state {
777         /*!
778          * \brief Calling Target state
779          *
780          * This state describes the initial state of a transfer. The transferer
781          * waits in the transfer target's bridge for the transfer target to answer.
782          *
783          * Superstate: Transfer
784          *
785          * Preconditions:
786          * 1) Transfer target is RINGING
787          * 2) Transferer is in transferee bridge
788          * 3) Transferee is on hold
789          *
790          * Transitions to TRANSFER_CALLING_TARGET:
791          * 1) This is the initial state for an attended transfer.
792          * 2) TRANSFER_HESITANT: Transferer presses DTMF swap sequence
793          *
794          * State operation:
795          * The transferer is moved from the transferee bridge into the transfer
796          * target bridge.
797          *
798          * Transitions from TRANSFER_CALLING_TARGET:
799          * 1) TRANSFER_FAIL: Transferee hangs up.
800          * 2) TRANSFER_BLOND: Transferer hangs up or presses DTMF swap sequence
801          * and configured atxferdropcall setting is yes.
802          * 3) TRANSFER_BLOND_NONFINAL: Transferer hangs up or presses DTMF swap
803          * sequence and configured atxferdroppcall setting is no.
804          * 4) TRANSFER_CONSULTING: Transfer target answers the call.
805          * 5) TRANSFER_REBRIDGE: Transfer target hangs up, call to transfer target
806          * times out, or transferer presses DTMF abort sequence.
807          * 6) TRANSFER_THREEWAY: Transferer presses DTMF threeway sequence.
808          * 7) TRANSFER_HESITANT: Transferer presses DTMF swap sequence.
809          */
810         TRANSFER_CALLING_TARGET,
811         /*!
812          * \brief Hesitant state
813          *
814          * This state only arises if when waiting for the transfer target to
815          * answer, the transferer presses the DTMF swap sequence. This will
816          * cause the transferer to be rebridged with the transferee temporarily.
817          *
818          * Superstate: Transfer
819          *
820          * Preconditions:
821          * 1) Transfer target is in ringing state
822          * 2) Transferer is in transfer target bridge
823          * 3) Transferee is on hold
824          *
825          * Transitions to TRANSFER_HESITANT:
826          * 1) TRANSFER_CALLING_TARGET: Transferer presses DTMF swap sequence.
827          *
828          * State operation:
829          * The transferer is moved from the transfer target bridge into the
830          * transferee bridge, and the transferee is taken off hold.
831          *
832          * Transitions from TRANSFER_HESITANT:
833          * 1) TRANSFER_FAIL: Transferee hangs up
834          * 2) TRANSFER_BLOND: Transferer hangs up or presses DTMF swap sequence
835          * and configured atxferdropcall setting is yes.
836          * 3) TRANSFER_BLOND_NONFINAL: Transferer hangs up or presses DTMF swap
837          * sequence and configured atxferdroppcall setting is no.
838          * 4) TRANSFER_DOUBLECHECKING: Transfer target answers the call
839          * 5) TRANSFER_RESUME: Transfer target hangs up, call to transfer target
840          * times out, or transferer presses DTMF abort sequence.
841          * 6) TRANSFER_THREEWAY: Transferer presses DTMF threeway sequence.
842          * 7) TRANSFER_CALLING_TARGET: Transferer presses DTMF swap sequence.
843          */
844         TRANSFER_HESITANT,
845         /*!
846          * \brief Rebridge state
847          *
848          * This is a terminal state that indicates that the transferer needs
849          * to move back to the transferee's bridge. This is a failed attended
850          * transfer result.
851          *
852          * Superstate: Transfer
853          *
854          * Preconditions:
855          * 1) Transferer is in transfer target bridge
856          * 2) Transferee is on hold
857          *
858          * Transitions to TRANSFER_REBRIDGE:
859          * 1) TRANSFER_CALLING_TARGET: Transfer target hangs up, call to transfer target
860          * times out, or transferer presses DTMF abort sequence.
861          * 2) TRANSFER_STATE_CONSULTING: Transfer target hangs up, or transferer presses
862          * DTMF abort sequence.
863          *
864          * State operation:
865          * The transferer channel is moved from the transfer target bridge to the
866          * transferee bridge. The transferee is taken off hold. A stasis transfer
867          * message is published indicating a failed attended transfer.
868          *
869          * Transitions from TRANSFER_REBRIDGE:
870          * None
871          */
872         TRANSFER_REBRIDGE,
873         /*!
874          * \brief Resume state
875          *
876          * This is a terminal state that indicates that the party bridged with the
877          * transferee is the final party to be bridged with that transferee. This state
878          * may come about due to a successful recall or due to a failed transfer.
879          *
880          * Superstate: Transfer or Recall
881          *
882          * Preconditions:
883          * In Transfer Superstate:
884          * 1) Transferer is in transferee bridge
885          * 2) Transferee is not on hold
886          * In Recall Superstate:
887          * 1) The recall target is in the transferee bridge
888          * 2) Transferee is not on hold
889          *
890          * Transitions to TRANSFER_RESUME:
891          * TRANSFER_HESITANT: Transfer target hangs up, call to transfer target times out,
892          * or transferer presses DTMF abort sequence.
893          * TRANSFER_DOUBLECHECKING: Transfer target hangs up or transferer presses DTMF
894          * abort sequence.
895          * TRANSFER_BLOND_NONFINAL: Recall target answers
896          * TRANSFER_RECALLING: Recall target answers
897          * TRANSFER_RETRANSFER: Recall target answers
898          *
899          * State operations:
900          * None
901          *
902          * Transitions from TRANSFER_RESUME:
903          * None
904          */
905         TRANSFER_RESUME,
906         /*!
907          * \brief Threeway state
908          *
909          * This state results when the transferer wishes to have all parties involved
910          * in a transfer to be in the same bridge together.
911          *
912          * Superstate: Transfer
913          *
914          * Preconditions:
915          * 1) Transfer target state is either RINGING or UP
916          * 2) Transferer is in either bridge
917          * 3) Transferee is not on hold
918          *
919          * Transitions to TRANSFER_THREEWAY:
920          * 1) TRANSFER_CALLING_TARGET: Transferer presses DTMF threeway sequence.
921          * 2) TRANSFER_HESITANT: Transferer presses DTMF threeway sequence.
922          * 3) TRANSFER_CONSULTING: Transferer presses DTMF threeway sequence.
923          * 4) TRANSFER_DOUBLECHECKING: Transferer presses DTMF threeway sequence.
924          *
925          * State operation:
926          * The transfer target bridge is merged into the transferee bridge.
927          *
928          * Transitions from TRANSFER_THREEWAY:
929          * None.
930          */
931         TRANSFER_THREEWAY,
932         /*!
933          * \brief Consulting state
934          *
935          * This state describes the case where the transferer and transfer target
936          * are able to converse in the transfer target's bridge prior to completing
937          * the transfer.
938          *
939          * Superstate: Transfer
940          *
941          * Preconditions:
942          * 1) Transfer target is UP
943          * 2) Transferer is in target bridge
944          * 3) Transferee is on hold
945          *
946          * Transitions to TRANSFER_CONSULTING:
947          * 1) TRANSFER_CALLING_TARGET: Transfer target answers.
948          * 2) TRANSFER_DOUBLECHECKING: Transferer presses DTMF swap sequence.
949          *
950          * State operations:
951          * None.
952          *
953          * Transitions from TRANSFER_CONSULTING:
954          * TRANSFER_COMPLETE: Transferer hangs up or transferer presses DTMF complete sequence.
955          * TRANSFER_REBRIDGE: Transfer target hangs up or transferer presses DTMF abort sequence.
956          * TRANSFER_THREEWAY: Transferer presses DTMF threeway sequence.
957          * TRANSFER_DOUBLECHECKING: Transferer presses DTMF swap sequence.
958          */
959         TRANSFER_CONSULTING,
960         /*!
961          * \brief Double-checking state
962          *
963          * This state describes the case where the transferer and transferee are
964          * able to converse in the transferee's bridge prior to completing the transfer. The
965          * difference between this and TRANSFER_HESITANT is that the transfer target is
966          * UP in this case.
967          *
968          * Superstate: Transfer
969          *
970          * Preconditions:
971          * 1) Transfer target is UP and on hold
972          * 2) Transferer is in transferee bridge
973          * 3) Transferee is off hold
974          *
975          * Transitions to TRANSFER_DOUBLECHECKING:
976          * 1) TRANSFER_HESITANT: Transfer target answers.
977          * 2) TRANSFER_CONSULTING: Transferer presses DTMF swap sequence.
978          *
979          * State operations:
980          * None.
981          *
982          * Transitions from TRANSFER_DOUBLECHECKING:
983          * 1) TRANSFER_FAIL: Transferee hangs up.
984          * 2) TRANSFER_COMPLETE: Transferer hangs up or presses DTMF complete sequence.
985          * 3) TRANSFER_RESUME: Transfer target hangs up or transferer presses DTMF abort sequence.
986          * 4) TRANSFER_THREEWAY: Transferer presses DTMF threeway sequence.
987          * 5) TRANSFER_CONSULTING: Transferer presses the DTMF swap sequence.
988          */
989         TRANSFER_DOUBLECHECKING,
990         /*!
991          * \brief Complete state
992          *
993          * This is a terminal state where a transferer has successfully completed an attended
994          * transfer. This state's goal is to get the transfer target and transferee into
995          * the same bridge and the transferer off the call.
996          *
997          * Superstate: Transfer
998          *
999          * Preconditions:
1000          * 1) Transfer target is UP and off hold.
1001          * 2) Transferer is in either bridge.
1002          * 3) Transferee is off hold.
1003          *
1004          * Transitions to TRANSFER_COMPLETE:
1005          * 1) TRANSFER_CONSULTING: transferer hangs up or presses the DTMF complete sequence.
1006          * 2) TRANSFER_DOUBLECHECKING: transferer hangs up or presses the DTMF complete sequence.
1007          *
1008          * State operation:
1009          * The transfer target bridge is merged into the transferee bridge. The transferer
1010          * channel is kicked out of the bridges as part of the merge.
1011          *
1012          * State operations:
1013          * 1) Merge the transfer target bridge into the transferee bridge,
1014          * excluding the transferer channel from the merge.
1015          * 2) Publish a stasis transfer message.
1016          *
1017          * Exit operations:
1018          * This is a terminal state, so there are no exit operations.
1019          */
1020         TRANSFER_COMPLETE,
1021         /*!
1022          * \brief Blond state
1023          *
1024          * This is a terminal state where a transferer has completed an attended transfer prior
1025          * to the transfer target answering. This state is only entered if atxferdropcall
1026          * is set to 'yes'. This is considered to be a successful attended transfer.
1027          *
1028          * Superstate: Transfer
1029          *
1030          * Preconditions:
1031          * 1) Transfer target is RINGING.
1032          * 2) Transferer is in either bridge.
1033          * 3) Transferee is off hold.
1034          *
1035          * Transitions to TRANSFER_BLOND:
1036          * 1) TRANSFER_CALLING_TARGET: Transferer hangs up or presses the DTMF complete sequence.
1037          *    atxferdropcall is set to 'yes'.
1038          * 2) TRANSFER_HESITANT: Transferer hangs up or presses the DTMF complete sequence.
1039          *    atxferdropcall is set to 'yes'.
1040          *
1041          * State operations:
1042          * The transfer target bridge is merged into the transferee bridge. The transferer
1043          * channel is kicked out of the bridges as part of the merge. A stasis transfer
1044          * publication is sent indicating a successful transfer.
1045          *
1046          * Transitions from TRANSFER_BLOND:
1047          * None
1048          */
1049         TRANSFER_BLOND,
1050         /*!
1051          * \brief Blond non-final state
1052          *
1053          * This state is very similar to the TRANSFER_BLOND state, except that
1054          * this state is entered when atxferdropcall is set to 'no'. This is the
1055          * initial state of the Recall superstate, so state operations mainly involve
1056          * moving to the Recall superstate. This means that the transfer target, that
1057          * is currently ringing is now known as the recall target.
1058          *
1059          * Superstate: Recall
1060          *
1061          * Preconditions:
1062          * 1) Recall target is RINGING.
1063          * 2) Transferee is off hold.
1064          *
1065          * Transitions to TRANSFER_BLOND_NONFINAL:
1066          * 1) TRANSFER_CALLING_TARGET: Transferer hangs up or presses the DTMF complete sequence.
1067          *    atxferdropcall is set to 'no'.
1068          * 2) TRANSFER_HESITANT: Transferer hangs up or presses the DTMF complete sequence.
1069          *    atxferdropcall is set to 'no'.
1070          *
1071          * State operation:
1072          * The superstate of the attended transfer is changed from Transfer to Recall.
1073          * The transfer target bridge is merged into the transferee bridge. The transferer
1074          * channel is kicked out of the bridges as part of the merge.
1075          *
1076          * Transitions from TRANSFER_BLOND_NONFINAL:
1077          * 1) TRANSFER_FAIL: Transferee hangs up
1078          * 2) TRANSFER_RESUME: Recall target answers
1079          * 3) TRANSFER_RECALLING: Recall target hangs up or time expires.
1080          */
1081         TRANSFER_BLOND_NONFINAL,
1082         /*!
1083          * \brief Recalling state
1084          *
1085          * This state is entered if the recall target from the TRANSFER_BLOND_NONFINAL
1086          * or TRANSFER_RETRANSFER states hangs up or does not answer. The goal of this
1087          * state is to call back the original transferer in an attempt to recover the
1088          * original call.
1089          *
1090          * Superstate: Recall
1091          *
1092          * Preconditions:
1093          * 1) Recall target is down.
1094          * 2) Transferee is off hold.
1095          *
1096          * Transitions to TRANSFER_RECALLING:
1097          * 1) TRANSFER_BLOND_NONFINAL: Recall target hangs up or time expires.
1098          * 2) TRANSFER_RETRANSFER: Recall target hangs up or time expires.
1099          *    atxferloopdelay is non-zero.
1100          * 3) TRANSFER_WAIT_TO_RECALL: Time expires.
1101          *
1102          * State operation:
1103          * The original transferer becomes the recall target and is called using the Dialing API.
1104          * Ringing is indicated to the transferee.
1105          *
1106          * Transitions from TRANSFER_RECALLING:
1107          * 1) TRANSFER_FAIL:
1108          *    a) Transferee hangs up.
1109          *    b) Recall target hangs up or time expires, and number of recall attempts exceeds atxfercallbackretries
1110          * 2) TRANSFER_WAIT_TO_RETRANSFER: Recall target hangs up or time expires.
1111          *    atxferloopdelay is non-zero.
1112          * 3) TRANSFER_RETRANSFER: Recall target hangs up or time expires.
1113          *    atxferloopdelay is zero.
1114          * 4) TRANSFER_RESUME: Recall target answers.
1115          */
1116         TRANSFER_RECALLING,
1117         /*!
1118          * \brief Wait to Retransfer state
1119          *
1120          * This state is used simply to give a bit of breathing room between attempting
1121          * to call back the original transferer and attempting to call back the original
1122          * transfer target. The transferee hears music on hold during this state as an
1123          * auditory clue that no one is currently being dialed.
1124          *
1125          * Superstate: Recall
1126          *
1127          * Preconditions:
1128          * 1) Recall target is down.
1129          * 2) Transferee is off hold.
1130          *
1131          * Transitions to TRANSFER_WAIT_TO_RETRANSFER:
1132          * 1) TRANSFER_RECALLING: Recall target hangs up or time expires.
1133          *    atxferloopdelay is non-zero.
1134          *
1135          * State operation:
1136          * The transferee is placed on hold.
1137          *
1138          * Transitions from TRANSFER_WAIT_TO_RETRANSFER:
1139          * 1) TRANSFER_FAIL: Transferee hangs up.
1140          * 2) TRANSFER_RETRANSFER: Time expires.
1141          */
1142         TRANSFER_WAIT_TO_RETRANSFER,
1143         /*!
1144          * \brief Retransfer state
1145          *
1146          * This state is used in order to attempt to call back the original
1147          * transfer target channel from the transfer. The transferee hears
1148          * ringing during this state as an auditory cue that a party is being
1149          * dialed.
1150          *
1151          * Superstate: Recall
1152          *
1153          * Preconditions:
1154          * 1) Recall target is down.
1155          * 2) Transferee is off hold.
1156          *
1157          * Transitions to TRANSFER_RETRANSFER:
1158          * 1) TRANSFER_RECALLING: Recall target hangs up or time expires.
1159          *    atxferloopdelay is zero.
1160          * 2) TRANSFER_WAIT_TO_RETRANSFER: Time expires.
1161          *
1162          * State operation:
1163          * The original transfer target is requested and is set as the recall target.
1164          * The recall target is called and placed into the transferee bridge.
1165          *
1166          * Transitions from TRANSFER_RETRANSFER:
1167          * 1) TRANSFER_FAIL: Transferee hangs up.
1168          * 2) TRANSFER_WAIT_TO_RECALL: Recall target hangs up or time expires.
1169          *    atxferloopdelay is non-zero.
1170          * 3) TRANSFER_RECALLING: Recall target hangs up or time expires.
1171          *    atxferloopdelay is zero.
1172          */
1173         TRANSFER_RETRANSFER,
1174         /*!
1175          * \brief Wait to recall state
1176          *
1177          * This state is used simply to give a bit of breathing room between attempting
1178          * to call back the original transfer target and attempting to call back the
1179          * original transferer. The transferee hears music on hold during this state as an
1180          * auditory clue that no one is currently being dialed.
1181          *
1182          * Superstate: Recall
1183          *
1184          * Preconditions:
1185          * 1) Recall target is down.
1186          * 2) Transferee is off hold.
1187          *
1188          * Transitions to TRANSFER_WAIT_TO_RECALL:
1189          * 1) TRANSFER_RETRANSFER: Recall target hangs up or time expires.
1190          *    atxferloopdelay is non-zero.
1191          *
1192          * State operation:
1193          * Transferee is placed on hold.
1194          *
1195          * Transitions from TRANSFER_WAIT_TO_RECALL:
1196          * 1) TRANSFER_FAIL: Transferee hangs up
1197          * 2) TRANSFER_RECALLING: Time expires
1198          */
1199         TRANSFER_WAIT_TO_RECALL,
1200         /*!
1201          * \brief Fail state
1202          *
1203          * This state indicates that something occurred during the transfer that
1204          * makes a graceful completion impossible. The most common stimulus for this
1205          * state is when the transferee hangs up.
1206          *
1207          * Superstate: Transfer and Recall
1208          *
1209          * Preconditions:
1210          * None
1211          *
1212          * Transitions to TRANSFER_FAIL:
1213          * 1) TRANSFER_CALLING_TARGET: Transferee hangs up.
1214          * 2) TRANSFER_HESITANT: Transferee hangs up.
1215          * 3) TRANSFER_DOUBLECHECKING: Transferee hangs up.
1216          * 4) TRANSFER_BLOND_NONFINAL: Transferee hangs up.
1217          * 5) TRANSFER_RECALLING:
1218          *    a) Transferee hangs up.
1219          *    b) Recall target hangs up or time expires, and number of
1220          *       recall attempts exceeds atxfercallbackretries.
1221          * 6) TRANSFER_WAIT_TO_RETRANSFER: Transferee hangs up.
1222          * 7) TRANSFER_RETRANSFER: Transferee hangs up.
1223          * 8) TRANSFER_WAIT_TO_RECALL: Transferee hangs up.
1224          *
1225          * State operation:
1226          * A transfer stasis publication is made indicating a failed transfer.
1227          * The transferee bridge is destroyed.
1228          *
1229          * Transitions from TRANSFER_FAIL:
1230          * None.
1231          */
1232         TRANSFER_FAIL,
1233 };
1234
1235 /*!
1236  * \brief Stimuli that can cause transfer state changes
1237  */
1238 enum attended_transfer_stimulus {
1239         /*! No stimulus. This literally can never happen. */
1240         STIMULUS_NONE,
1241         /*! All of the transferee channels have been hung up. */
1242         STIMULUS_TRANSFEREE_HANGUP,
1243         /*! The transferer has hung up. */
1244         STIMULUS_TRANSFERER_HANGUP,
1245         /*! The transfer target channel has hung up. */
1246         STIMULUS_TRANSFER_TARGET_HANGUP,
1247         /*! The transfer target channel has answered. */
1248         STIMULUS_TRANSFER_TARGET_ANSWER,
1249         /*! The recall target channel has hung up. */
1250         STIMULUS_RECALL_TARGET_HANGUP,
1251         /*! The recall target channel has answered. */
1252         STIMULUS_RECALL_TARGET_ANSWER,
1253         /*! The current state's timer has expired. */
1254         STIMULUS_TIMEOUT,
1255         /*! The transferer pressed the abort DTMF sequence. */
1256         STIMULUS_DTMF_ATXFER_ABORT,
1257         /*! The transferer pressed the complete DTMF sequence. */
1258         STIMULUS_DTMF_ATXFER_COMPLETE,
1259         /*! The transferer pressed the three-way DTMF sequence. */
1260         STIMULUS_DTMF_ATXFER_THREEWAY,
1261         /*! The transferer pressed the swap DTMF sequence. */
1262         STIMULUS_DTMF_ATXFER_SWAP,
1263 };
1264
1265 /*!
1266  * \brief String representations of the various stimuli
1267  *
1268  * Used for debugging purposes
1269  */
1270 const char *stimulus_strs[] = {
1271         [STIMULUS_NONE] = "None",
1272         [STIMULUS_TRANSFEREE_HANGUP] = "Transferee Hangup",
1273         [STIMULUS_TRANSFERER_HANGUP] = "Transferer Hangup",
1274         [STIMULUS_TRANSFER_TARGET_HANGUP] = "Transfer Target Hangup",
1275         [STIMULUS_TRANSFER_TARGET_ANSWER] = "Transfer Target Answer",
1276         [STIMULUS_RECALL_TARGET_HANGUP] = "Recall Target Hangup",
1277         [STIMULUS_RECALL_TARGET_ANSWER] = "Recall Target Answer",
1278         [STIMULUS_TIMEOUT] = "Timeout",
1279         [STIMULUS_DTMF_ATXFER_ABORT] = "DTMF Abort",
1280         [STIMULUS_DTMF_ATXFER_COMPLETE] = "DTMF Complete",
1281         [STIMULUS_DTMF_ATXFER_THREEWAY] = "DTMF Threeway",
1282         [STIMULUS_DTMF_ATXFER_SWAP] = "DTMF Swap",
1283 };
1284
1285 struct stimulus_list {
1286         enum attended_transfer_stimulus stimulus;
1287         AST_LIST_ENTRY(stimulus_list) next;
1288 };
1289
1290 /*!
1291  * \brief Collection of data related to an attended transfer attempt
1292  */
1293 struct attended_transfer_properties {
1294         AST_DECLARE_STRING_FIELDS (
1295                 /*! Extension of transfer target */
1296                 AST_STRING_FIELD(exten);
1297                 /*! Context of transfer target */
1298                 AST_STRING_FIELD(context);
1299                 /*! Sound to play on failure */
1300                 AST_STRING_FIELD(failsound);
1301                 /*! Sound to play when transfer completes */
1302                 AST_STRING_FIELD(xfersound);
1303                 /*! The channel technology of the transferer channel */
1304                 AST_STRING_FIELD(transferer_type);
1305                 /*! The transferer channel address */
1306                 AST_STRING_FIELD(transferer_addr);
1307         );
1308         /*! Condition used to synchronize when stimuli are reported to the monitor thread */
1309         ast_cond_t cond;
1310         /*! The bridge where the transferee resides. This bridge is also the bridge that
1311          * survives a successful attended transfer.
1312          */
1313         struct ast_bridge *transferee_bridge;
1314         /*! The bridge used to place an outbound call to the transfer target. This
1315          * bridge is merged with the transferee_bridge on a successful transfer.
1316          */
1317         struct ast_bridge *target_bridge;
1318         /*! The party that performs the attended transfer. */
1319         struct ast_channel *transferer;
1320         /*! The local channel dialed to reach the transfer target. */
1321         struct ast_channel *transfer_target;
1322         /*! The party that is currently being recalled. Depending on
1323          * the current state, this may be either the party that originally
1324          * was the transferer or the original transfer target.  This is
1325          * set with reference when entering the BLOND_NONFINAL, RECALLING,
1326          * and RETRANSFER states, and the reference released on state exit
1327          * if continuing with recall or retransfer to avoid leak.
1328          */
1329         struct ast_channel *recall_target;
1330         /*! The absolute starting time for running timers */
1331         struct timeval start;
1332         AST_LIST_HEAD_NOLOCK(,stimulus_list) stimulus_queue;
1333         /*! The current state of the attended transfer */
1334         enum attended_transfer_state state;
1335         /*! The current superstate of the attended transfer */
1336         enum attended_transfer_superstate superstate;
1337         /*! Configured atxferdropcall from features.conf */
1338         int atxferdropcall;
1339         /*! Configured atxfercallbackretries from features.conf */
1340         int atxfercallbackretries;
1341         /*! Configured atxferloopdelay from features.conf */
1342         int atxferloopdelay;
1343         /*! Configured atxfernoanswertimeout from features.conf */
1344         int atxfernoanswertimeout;
1345         /*! Count of the number of times that recalls have been attempted */
1346         int retry_attempts;
1347         /*! Framehook ID for outbounc call to transfer target or recall target */
1348         int target_framehook_id;
1349         /*! Dial structure used when recalling transferer channel */
1350         struct ast_dial *dial;
1351         /*! The bridging features the transferer has available */
1352         struct ast_flags transferer_features;
1353         /*! Saved transferer connected line data for recalling the transferer. */
1354         struct ast_party_connected_line original_transferer_colp;
1355 };
1356
1357 static void attended_transfer_properties_destructor(void *obj)
1358 {
1359         struct attended_transfer_properties *props = obj;
1360
1361         ast_debug(1, "Destroy attended transfer properties %p\n", props);
1362
1363         ao2_cleanup(props->target_bridge);
1364         ao2_cleanup(props->transferee_bridge);
1365         /* Use ast_channel_cleanup() instead of ast_channel_unref() for channels since they may be NULL */
1366         ast_channel_cleanup(props->transferer);
1367         ast_channel_cleanup(props->transfer_target);
1368         ast_channel_cleanup(props->recall_target);
1369         ast_party_connected_line_free(&props->original_transferer_colp);
1370         ast_string_field_free_memory(props);
1371         ast_cond_destroy(&props->cond);
1372 }
1373
1374 /*!
1375  * \internal
1376  * \brief Determine the transfer context to use.
1377  * \since 12.0.0
1378  *
1379  * \param transferer Channel initiating the transfer.
1380  * \param context User supplied context if available.  May be NULL.
1381  *
1382  * \return The context to use for the transfer.
1383  */
1384 static const char *get_transfer_context(struct ast_channel *transferer, const char *context)
1385 {
1386         if (!ast_strlen_zero(context)) {
1387                 return context;
1388         }
1389         context = pbx_builtin_getvar_helper(transferer, "TRANSFER_CONTEXT");
1390         if (!ast_strlen_zero(context)) {
1391                 return context;
1392         }
1393         context = ast_channel_macrocontext(transferer);
1394         if (!ast_strlen_zero(context)) {
1395                 return context;
1396         }
1397         context = ast_channel_context(transferer);
1398         if (!ast_strlen_zero(context)) {
1399                 return context;
1400         }
1401         return "default";
1402 }
1403
1404 /*!
1405  * \brief Allocate and initialize attended transfer properties
1406  *
1407  * \param transferer The channel performing the attended transfer
1408  * \param context Suggestion for what context the transfer target extension can be found in
1409  *
1410  * \retval NULL Failure to allocate or initialize
1411  * \retval non-NULL Newly allocated properties
1412  */
1413 static struct attended_transfer_properties *attended_transfer_properties_alloc(
1414         struct ast_channel *transferer, const char *context)
1415 {
1416         struct attended_transfer_properties *props;
1417         char *tech;
1418         char *addr;
1419         char *serial;
1420         struct ast_features_xfer_config *xfer_cfg;
1421         struct ast_flags *transferer_features;
1422
1423         props = ao2_alloc(sizeof(*props), attended_transfer_properties_destructor);
1424         if (!props || ast_string_field_init(props, 64)) {
1425                 return NULL;
1426         }
1427
1428         ast_cond_init(&props->cond, NULL);
1429
1430         props->target_framehook_id = -1;
1431         props->transferer = ast_channel_ref(transferer);
1432
1433         ast_channel_lock(props->transferer);
1434         xfer_cfg = ast_get_chan_features_xfer_config(props->transferer);
1435         if (!xfer_cfg) {
1436                 ast_log(LOG_ERROR, "Unable to get transfer configuration from channel %s\n", ast_channel_name(props->transferer));
1437                 ast_channel_unlock(props->transferer);
1438                 ao2_ref(props, -1);
1439                 return NULL;
1440         }
1441         transferer_features = ast_bridge_features_ds_get(props->transferer);
1442         if (transferer_features) {
1443                 props->transferer_features = *transferer_features;
1444         }
1445         props->atxferdropcall = xfer_cfg->atxferdropcall;
1446         props->atxfercallbackretries = xfer_cfg->atxfercallbackretries;
1447         props->atxfernoanswertimeout = xfer_cfg->atxfernoanswertimeout;
1448         props->atxferloopdelay = xfer_cfg->atxferloopdelay;
1449         ast_string_field_set(props, context, get_transfer_context(transferer, context));
1450         ast_string_field_set(props, failsound, xfer_cfg->xferfailsound);
1451         ast_string_field_set(props, xfersound, xfer_cfg->xfersound);
1452         ao2_ref(xfer_cfg, -1);
1453
1454         /*
1455          * Save the transferee's party information for any recall calls.
1456          * This is the only piece of information needed that gets overwritten
1457          * on the transferer channel by the inital call to the transfer target.
1458          */
1459         ast_party_connected_line_copy(&props->original_transferer_colp,
1460                 ast_channel_connected(props->transferer));
1461
1462         tech = ast_strdupa(ast_channel_name(props->transferer));
1463         addr = strchr(tech, '/');
1464         if (!addr) {
1465                 ast_log(LOG_ERROR, "Transferer channel name does not follow typical channel naming format (tech/address)\n");
1466                 ast_channel_unlock(props->transferer);
1467                 ao2_ref(props, -1);
1468                 return NULL;
1469         }
1470         *addr++ = '\0';
1471         serial = strrchr(addr, '-');
1472         if (serial) {
1473                 *serial = '\0';
1474         }
1475         ast_string_field_set(props, transferer_type, tech);
1476         ast_string_field_set(props, transferer_addr, addr);
1477
1478         ast_channel_unlock(props->transferer);
1479
1480         ast_debug(1, "Allocated attended transfer properties %p for transfer from %s\n",
1481                         props, ast_channel_name(props->transferer));
1482         return props;
1483 }
1484
1485 /*!
1486  * \brief Free backlog of stimuli in the queue
1487  */
1488 static void clear_stimulus_queue(struct attended_transfer_properties *props)
1489 {
1490         struct stimulus_list *list;
1491         SCOPED_AO2LOCK(lock, props);
1492
1493         while ((list = AST_LIST_REMOVE_HEAD(&props->stimulus_queue, next))) {
1494                 ast_free(list);
1495         }
1496 }
1497
1498 /*!
1499  * \brief Initiate shutdown of attended transfer properties
1500  *
1501  * Calling this indicates that the attended transfer properties are no longer needed
1502  * because the transfer operation has concluded.
1503  */
1504 static void attended_transfer_properties_shutdown(struct attended_transfer_properties *props)
1505 {
1506         ast_debug(1, "Shutting down attended transfer %p\n", props);
1507
1508         if (props->transferee_bridge) {
1509                 bridge_basic_change_personality(props->transferee_bridge,
1510                                 BRIDGE_BASIC_PERSONALITY_NORMAL, NULL);
1511                 ast_bridge_merge_inhibit(props->transferee_bridge, -1);
1512         }
1513
1514         if (props->target_bridge) {
1515                 ast_bridge_destroy(props->target_bridge, 0);
1516                 props->target_bridge = NULL;
1517         }
1518
1519         if (props->transferer) {
1520                 ast_channel_remove_bridge_role(props->transferer, AST_TRANSFERER_ROLE_NAME);
1521         }
1522
1523         clear_stimulus_queue(props);
1524
1525         ao2_cleanup(props);
1526 }
1527
1528 static void stimulate_attended_transfer(struct attended_transfer_properties *props,
1529                 enum attended_transfer_stimulus stimulus)
1530 {
1531         struct stimulus_list *list;
1532
1533         list = ast_calloc(1, sizeof(*list));
1534         if (!list) {
1535                 ast_log(LOG_ERROR, "Unable to push event to attended transfer queue. Expect transfer to fail\n");
1536                 return;
1537         }
1538
1539         list->stimulus = stimulus;
1540         ao2_lock(props);
1541         AST_LIST_INSERT_TAIL(&props->stimulus_queue, list, next);
1542         ast_cond_signal(&props->cond);
1543         ao2_unlock(props);
1544 }
1545
1546 /*!
1547  * \brief Get a desired transfer party for a bridge the transferer is not in.
1548  *
1549  * \param bridge The bridge to get the party from. May be NULL.
1550  * \param[out] party The lone channel in the bridge. Will be set NULL if bridge is NULL or multiple parties are present.
1551  */
1552 static void get_transfer_party_non_transferer_bridge(struct ast_bridge *bridge,
1553                 struct ast_channel **party)
1554 {
1555         if (bridge && bridge->num_channels == 1) {
1556                 *party = ast_channel_ref(AST_LIST_FIRST(&bridge->channels)->chan);
1557         } else {
1558                 *party = NULL;
1559         }
1560 }
1561
1562 /*!
1563  * \brief Get the transferee and transfer target when the transferer is in a bridge with
1564  * one of the desired parties.
1565  *
1566  * \param transferer_bridge The bridge the transferer is in
1567  * \param other_bridge The bridge the transferer is not in. May be NULL.
1568  * \param transferer The transferer party
1569  * \param[out] transferer_peer The party that is in the bridge with the transferer
1570  * \param[out] other_party The party that is in the other_bridge
1571  */
1572 static void get_transfer_parties_transferer_bridge(struct ast_bridge *transferer_bridge,
1573                 struct ast_bridge *other_bridge, struct ast_channel *transferer,
1574                 struct ast_channel **transferer_peer, struct ast_channel **other_party)
1575 {
1576         *transferer_peer = ast_bridge_peer(transferer_bridge, transferer);
1577         get_transfer_party_non_transferer_bridge(other_bridge, other_party);
1578 }
1579
1580 /*!
1581  * \brief determine transferee and transfer target for an attended transfer
1582  *
1583  * In builtin attended transfers, there is a single transferer channel that jumps between
1584  * the two bridges involved. At the time the attended transfer occurs, the transferer could
1585  * be in either bridge, so determining the parties is a bit more complex than normal.
1586  *
1587  * The method used here is to determine which of the two bridges the transferer is in, and
1588  * grabbing the peer from that bridge. The other bridge, if it only has a single channel in it,
1589  * has the other desired channel.
1590  *
1591  * \param transferer The channel performing the transfer
1592  * \param transferee_bridge The bridge that the transferee is in
1593  * \param target_bridge The bridge that the transfer target is in
1594  * \param[out] transferee The transferee channel
1595  * \param[out] transfer_target The transfer target channel
1596  */
1597 static void get_transfer_parties(struct ast_channel *transferer, struct ast_bridge *transferee_bridge,
1598                 struct ast_bridge *target_bridge, struct ast_channel **transferee,
1599                 struct ast_channel **transfer_target)
1600 {
1601         struct ast_bridge *transferer_bridge;
1602
1603         ast_channel_lock(transferer);
1604         transferer_bridge = ast_channel_get_bridge(transferer);
1605         ast_channel_unlock(transferer);
1606
1607         if (transferer_bridge == transferee_bridge) {
1608                 get_transfer_parties_transferer_bridge(transferee_bridge, target_bridge,
1609                                 transferer, transferee, transfer_target);
1610         } else if (transferer_bridge == target_bridge) {
1611                 get_transfer_parties_transferer_bridge(target_bridge, transferee_bridge,
1612                                 transferer, transfer_target, transferee);
1613         } else {
1614                 get_transfer_party_non_transferer_bridge(transferee_bridge, transferee);
1615                 get_transfer_party_non_transferer_bridge(target_bridge, transfer_target);
1616         }
1617
1618         ao2_cleanup(transferer_bridge);
1619 }
1620
1621 /*!
1622  * \brief Send a stasis publication for a successful attended transfer
1623  */
1624 static void publish_transfer_success(struct attended_transfer_properties *props,
1625                 struct ast_channel *transferee_channel, struct ast_channel *target_channel)
1626 {
1627         struct ast_attended_transfer_message *transfer_msg;
1628
1629         transfer_msg = ast_attended_transfer_message_create(0, props->transferer,
1630                         props->transferee_bridge, props->transferer, props->target_bridge,
1631                         transferee_channel, target_channel);
1632
1633         if (!transfer_msg) {
1634                 ast_log(LOG_ERROR, "Unable to publish successful attended transfer from %s\n",
1635                                 ast_channel_name(props->transferer));
1636                 return;
1637         }
1638
1639         ast_attended_transfer_message_add_merge(transfer_msg, props->transferee_bridge);
1640         ast_bridge_publish_attended_transfer(transfer_msg);
1641         ao2_cleanup(transfer_msg);
1642 }
1643
1644 /*!
1645  * \brief Send a stasis publication for an attended transfer that ends in a threeway call
1646  */
1647 static void publish_transfer_threeway(struct attended_transfer_properties *props,
1648                 struct ast_channel *transferee_channel, struct ast_channel *target_channel)
1649 {
1650         struct ast_attended_transfer_message *transfer_msg;
1651
1652         transfer_msg = ast_attended_transfer_message_create(0, props->transferer,
1653                         props->transferee_bridge, props->transferer, props->target_bridge,
1654                         transferee_channel, target_channel);
1655
1656         if (!transfer_msg) {
1657                 ast_log(LOG_ERROR, "Unable to publish successful three-way transfer from %s\n",
1658                                 ast_channel_name(props->transferer));
1659                 return;
1660         }
1661
1662         ast_attended_transfer_message_add_threeway(transfer_msg, props->transferer,
1663                         props->transferee_bridge);
1664         ast_bridge_publish_attended_transfer(transfer_msg);
1665         ao2_cleanup(transfer_msg);
1666 }
1667
1668 /*!
1669  * \brief Send a stasis publication for a failed attended transfer
1670  */
1671 static void publish_transfer_fail(struct attended_transfer_properties *props)
1672 {
1673         struct ast_attended_transfer_message *transfer_msg;
1674
1675         transfer_msg = ast_attended_transfer_message_create(0, props->transferer,
1676                         props->transferee_bridge, props->transferer, props->target_bridge,
1677                         NULL, NULL);
1678
1679         if (!transfer_msg) {
1680                 ast_log(LOG_ERROR, "Unable to publish failed transfer from %s\n",
1681                                 ast_channel_name(props->transferer));
1682                 return;
1683         }
1684
1685         transfer_msg->result = AST_BRIDGE_TRANSFER_FAIL;
1686         ast_bridge_publish_attended_transfer(transfer_msg);
1687         ao2_cleanup(transfer_msg);
1688 }
1689
1690 /*!
1691  * \brief Helper method to play a sound on a channel in a bridge
1692  *
1693  * \param chan The channel to play the sound to
1694  * \param sound The sound to play
1695  */
1696 static void play_sound(struct ast_channel *chan, const char *sound)
1697 {
1698         struct ast_bridge_channel *bridge_channel;
1699
1700         ast_channel_lock(chan);
1701         bridge_channel = ast_channel_get_bridge_channel(chan);
1702         ast_channel_unlock(chan);
1703
1704         if (bridge_channel) {
1705                 ast_bridge_channel_queue_playfile(bridge_channel, NULL, sound, NULL);
1706                 ao2_ref(bridge_channel, -1);
1707         }
1708 }
1709
1710 /*!
1711  * \brief Helper method to place a channel in a bridge on hold
1712  */
1713 static void hold(struct ast_channel *chan)
1714 {
1715         struct ast_bridge_channel *bridge_channel;
1716
1717         if (!chan) {
1718                 return;
1719         }
1720
1721         ast_channel_lock(chan);
1722         bridge_channel = ast_channel_get_bridge_channel(chan);
1723         ast_channel_unlock(chan);
1724
1725         if (bridge_channel) {
1726                 ast_bridge_channel_write_hold(bridge_channel, NULL);
1727                 ao2_ref(bridge_channel, -1);
1728         }
1729 }
1730
1731 /*!
1732  * \brief Helper method to take a channel in a bridge off hold
1733  */
1734 static void unhold(struct ast_channel *chan)
1735 {
1736         struct ast_bridge_channel *bridge_channel;
1737
1738         if (!chan) {
1739                 return;
1740         }
1741
1742         ast_channel_lock(chan);
1743         bridge_channel = ast_channel_get_bridge_channel(chan);
1744         ast_channel_unlock(chan);
1745
1746         if (bridge_channel) {
1747                 ast_bridge_channel_write_unhold(bridge_channel);
1748                 ao2_ref(bridge_channel, -1);
1749         }
1750 }
1751
1752 /*!
1753  * \brief Helper method to send a ringing indication to a channel in a bridge
1754  */
1755 static void ringing(struct ast_channel *chan)
1756 {
1757         struct ast_bridge_channel *bridge_channel;
1758
1759         ast_channel_lock(chan);
1760         bridge_channel = ast_channel_get_bridge_channel(chan);
1761         ast_channel_unlock(chan);
1762
1763         if (bridge_channel) {
1764                 ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_RINGING, NULL, 0);
1765                 ao2_ref(bridge_channel, -1);
1766         }
1767 }
1768
1769 /*!
1770  * \brief Helper method to send a ringing indication to all channels in a bridge
1771  */
1772 static void bridge_ringing(struct ast_bridge *bridge)
1773 {
1774         struct ast_frame ringing = {
1775                 .frametype = AST_FRAME_CONTROL,
1776                 .subclass.integer = AST_CONTROL_RINGING,
1777         };
1778
1779         ast_bridge_queue_everyone_else(bridge, NULL, &ringing);
1780 }
1781
1782 /*!
1783  * \brief Helper method to send a hold frame to all channels in a bridge
1784  */
1785 static void bridge_hold(struct ast_bridge *bridge)
1786 {
1787         struct ast_frame hold = {
1788                 .frametype = AST_FRAME_CONTROL,
1789                 .subclass.integer = AST_CONTROL_HOLD,
1790         };
1791
1792         ast_bridge_queue_everyone_else(bridge, NULL, &hold);
1793 }
1794
1795 /*!
1796  * \brief Helper method to send an unhold frame to all channels in a bridge
1797  */
1798 static void bridge_unhold(struct ast_bridge *bridge)
1799 {
1800         struct ast_frame unhold = {
1801                 .frametype = AST_FRAME_CONTROL,
1802                 .subclass.integer = AST_CONTROL_UNHOLD,
1803         };
1804
1805         ast_bridge_queue_everyone_else(bridge, NULL, &unhold);
1806 }
1807
1808 /*!
1809  * \brief Wrapper for \ref bridge_do_move
1810  */
1811 static void bridge_move(struct ast_bridge *dest, struct ast_bridge *src, struct ast_channel *channel, struct ast_channel *swap)
1812 {
1813         struct ast_bridge_channel *bridge_channel;
1814
1815         ast_bridge_lock_both(src, dest);
1816
1817         ast_channel_lock(channel);
1818         bridge_channel = ast_channel_get_bridge_channel(channel);
1819         ast_channel_unlock(channel);
1820
1821         if (bridge_channel) {
1822                 ao2_lock(bridge_channel);
1823                 bridge_channel->swap = swap;
1824                 ao2_unlock(bridge_channel);
1825
1826                 bridge_do_move(dest, bridge_channel, 1, 0);
1827         }
1828
1829         ast_bridge_unlock(dest);
1830         ast_bridge_unlock(src);
1831
1832         ao2_cleanup(bridge_channel);
1833 }
1834
1835 /*!
1836  * \brief Wrapper for \ref bridge_do_merge
1837  */
1838 static void bridge_merge(struct ast_bridge *dest, struct ast_bridge *src, struct ast_channel **kick_channels, unsigned int num_channels)
1839 {
1840         struct ast_bridge_channel **kick_bridge_channels = num_channels ?
1841                 ast_alloca(num_channels * sizeof(*kick_bridge_channels)) : NULL;
1842         int i;
1843         int num_bridge_channels = 0;
1844
1845         ast_bridge_lock_both(dest, src);
1846
1847         for (i = 0; i < num_channels; ++i) {
1848                 struct ast_bridge_channel *kick_bridge_channel;
1849
1850                 kick_bridge_channel = bridge_find_channel(src, kick_channels[i]);
1851                 if (!kick_bridge_channel) {
1852                         kick_bridge_channel = bridge_find_channel(dest, kick_channels[i]);
1853                 }
1854
1855                 /* It's possible (and fine) for the bridge channel to be NULL at this point if the
1856                  * channel has hung up already. If that happens, we can just remove it from the list
1857                  * of bridge channels to kick from the bridge
1858                  */
1859                 if (!kick_bridge_channel) {
1860                         continue;
1861                 }
1862
1863                 kick_bridge_channels[num_bridge_channels++] = kick_bridge_channel;
1864         }
1865
1866         bridge_do_merge(dest, src, kick_bridge_channels, num_bridge_channels, 0);
1867         ast_bridge_unlock(dest);
1868         ast_bridge_unlock(src);
1869 }
1870
1871 /*!
1872  * \brief Flags that indicate properties of attended transfer states
1873  */
1874 enum attended_transfer_state_flags {
1875         /*! This state requires that the timer be reset when entering the state */
1876         TRANSFER_STATE_FLAG_TIMER_RESET = (1 << 0),
1877         /*! This state's timer uses atxferloopdelay */
1878         TRANSFER_STATE_FLAG_TIMER_LOOP_DELAY = (1 << 1),
1879         /*! This state's timer uses atxfernoanswertimeout */
1880         TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER = (1 << 2),
1881         /*! This state has a time limit associated with it */
1882         TRANSFER_STATE_FLAG_TIMED = (TRANSFER_STATE_FLAG_TIMER_RESET |
1883                         TRANSFER_STATE_FLAG_TIMER_LOOP_DELAY | TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER),
1884         /*! This state does not transition to any other states */
1885         TRANSFER_STATE_FLAG_TERMINAL = (1 << 3),
1886 };
1887
1888 static int calling_target_enter(struct attended_transfer_properties *props);
1889 static enum attended_transfer_state calling_target_exit(struct attended_transfer_properties *props,
1890                 enum attended_transfer_stimulus stimulus);
1891
1892 static int hesitant_enter(struct attended_transfer_properties *props);
1893 static enum attended_transfer_state hesitant_exit(struct attended_transfer_properties *props,
1894                 enum attended_transfer_stimulus stimulus);
1895
1896 static int rebridge_enter(struct attended_transfer_properties *props);
1897
1898 static int resume_enter(struct attended_transfer_properties *props);
1899
1900 static int threeway_enter(struct attended_transfer_properties *props);
1901
1902 static int consulting_enter(struct attended_transfer_properties *props);
1903 static enum attended_transfer_state consulting_exit(struct attended_transfer_properties *props,
1904                 enum attended_transfer_stimulus stimulus);
1905
1906 static int double_checking_enter(struct attended_transfer_properties *props);
1907 static enum attended_transfer_state double_checking_exit(struct attended_transfer_properties *props,
1908                 enum attended_transfer_stimulus stimulus);
1909
1910 static int complete_enter(struct attended_transfer_properties *props);
1911
1912 static int blond_enter(struct attended_transfer_properties *props);
1913
1914 static int blond_nonfinal_enter(struct attended_transfer_properties *props);
1915 static enum attended_transfer_state blond_nonfinal_exit(struct attended_transfer_properties *props,
1916                 enum attended_transfer_stimulus stimulus);
1917
1918 static int recalling_enter(struct attended_transfer_properties *props);
1919 static enum attended_transfer_state recalling_exit(struct attended_transfer_properties *props,
1920                 enum attended_transfer_stimulus stimulus);
1921
1922 static int wait_to_retransfer_enter(struct attended_transfer_properties *props);
1923 static enum attended_transfer_state wait_to_retransfer_exit(struct attended_transfer_properties *props,
1924                 enum attended_transfer_stimulus stimulus);
1925
1926 static int retransfer_enter(struct attended_transfer_properties *props);
1927 static enum attended_transfer_state retransfer_exit(struct attended_transfer_properties *props,
1928                 enum attended_transfer_stimulus stimulus);
1929
1930 static int wait_to_recall_enter(struct attended_transfer_properties *props);
1931 static enum attended_transfer_state wait_to_recall_exit(struct attended_transfer_properties *props,
1932                 enum attended_transfer_stimulus stimulus);
1933
1934 static int fail_enter(struct attended_transfer_properties *props);
1935
1936 /*!
1937  * \brief Properties of an attended transfer state
1938  */
1939 struct attended_transfer_state_properties {
1940         /*! The name of the state. Used for debugging */
1941         const char *state_name;
1942         /*! Function used to enter a state */
1943         int (*enter)(struct attended_transfer_properties *props);
1944         /*!
1945          * Function used to exit a state
1946          * This is used both to determine what the next state
1947          * to transition to will be and to perform any cleanup
1948          * necessary before exiting the current state.
1949          */
1950         enum attended_transfer_state (*exit)(struct attended_transfer_properties *props,
1951                         enum attended_transfer_stimulus stimulus);
1952         /*! Flags associated with this state */
1953         enum attended_transfer_state_flags flags;
1954 };
1955
1956 static const struct attended_transfer_state_properties state_properties[] = {
1957         [TRANSFER_CALLING_TARGET] = {
1958                 .state_name = "Calling Target",
1959                 .enter = calling_target_enter,
1960                 .exit = calling_target_exit,
1961                 .flags = TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER | TRANSFER_STATE_FLAG_TIMER_RESET,
1962         },
1963         [TRANSFER_HESITANT] = {
1964                 .state_name = "Hesitant",
1965                 .enter = hesitant_enter,
1966                 .exit = hesitant_exit,
1967                 .flags = TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER,
1968         },
1969         [TRANSFER_REBRIDGE] = {
1970                 .state_name = "Rebridge",
1971                 .enter = rebridge_enter,
1972                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
1973         },
1974         [TRANSFER_RESUME] = {
1975                 .state_name = "Resume",
1976                 .enter = resume_enter,
1977                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
1978         },
1979         [TRANSFER_THREEWAY] = {
1980                 .state_name = "Threeway",
1981                 .enter = threeway_enter,
1982                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
1983         },
1984         [TRANSFER_CONSULTING] = {
1985                 .state_name = "Consulting",
1986                 .enter = consulting_enter,
1987                 .exit = consulting_exit,
1988         },
1989         [TRANSFER_DOUBLECHECKING] = {
1990                 .state_name = "Double Checking",
1991                 .enter = double_checking_enter,
1992                 .exit = double_checking_exit,
1993         },
1994         [TRANSFER_COMPLETE] = {
1995                 .state_name = "Complete",
1996                 .enter = complete_enter,
1997                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
1998         },
1999         [TRANSFER_BLOND] = {
2000                 .state_name = "Blond",
2001                 .enter = blond_enter,
2002                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
2003         },
2004         [TRANSFER_BLOND_NONFINAL] = {
2005                 .state_name = "Blond Non-Final",
2006                 .enter = blond_nonfinal_enter,
2007                 .exit = blond_nonfinal_exit,
2008                 .flags = TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER,
2009         },
2010         [TRANSFER_RECALLING] = {
2011                 .state_name = "Recalling",
2012                 .enter = recalling_enter,
2013                 .exit = recalling_exit,
2014                 .flags = TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER | TRANSFER_STATE_FLAG_TIMER_RESET,
2015         },
2016         [TRANSFER_WAIT_TO_RETRANSFER] = {
2017                 .state_name = "Wait to Retransfer",
2018                 .enter = wait_to_retransfer_enter,
2019                 .exit = wait_to_retransfer_exit,
2020                 .flags = TRANSFER_STATE_FLAG_TIMER_RESET | TRANSFER_STATE_FLAG_TIMER_LOOP_DELAY,
2021         },
2022         [TRANSFER_RETRANSFER] = {
2023                 .state_name = "Retransfer",
2024                 .enter = retransfer_enter,
2025                 .exit = retransfer_exit,
2026                 .flags = TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER | TRANSFER_STATE_FLAG_TIMER_RESET,
2027         },
2028         [TRANSFER_WAIT_TO_RECALL] = {
2029                 .state_name = "Wait to Recall",
2030                 .enter = wait_to_recall_enter,
2031                 .exit = wait_to_recall_exit,
2032                 .flags = TRANSFER_STATE_FLAG_TIMER_RESET | TRANSFER_STATE_FLAG_TIMER_LOOP_DELAY,
2033         },
2034         [TRANSFER_FAIL] = {
2035                 .state_name = "Fail",
2036                 .enter = fail_enter,
2037                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
2038         },
2039 };
2040
2041 static int calling_target_enter(struct attended_transfer_properties *props)
2042 {
2043         bridge_move(props->target_bridge, props->transferee_bridge, props->transferer, NULL);
2044         return 0;
2045 }
2046
2047 static enum attended_transfer_state calling_target_exit(struct attended_transfer_properties *props,
2048                 enum attended_transfer_stimulus stimulus)
2049 {
2050         switch (stimulus) {
2051         case STIMULUS_TRANSFEREE_HANGUP:
2052                 play_sound(props->transferer, props->failsound);
2053                 publish_transfer_fail(props);
2054                 return TRANSFER_FAIL;
2055         case STIMULUS_DTMF_ATXFER_COMPLETE:
2056         case STIMULUS_TRANSFERER_HANGUP:
2057                 bridge_unhold(props->transferee_bridge);
2058                 return props->atxferdropcall ? TRANSFER_BLOND : TRANSFER_BLOND_NONFINAL;
2059         case STIMULUS_TRANSFER_TARGET_ANSWER:
2060                 return TRANSFER_CONSULTING;
2061         case STIMULUS_TRANSFER_TARGET_HANGUP:
2062         case STIMULUS_TIMEOUT:
2063         case STIMULUS_DTMF_ATXFER_ABORT:
2064                 play_sound(props->transferer, props->failsound);
2065                 return TRANSFER_REBRIDGE;
2066         case STIMULUS_DTMF_ATXFER_THREEWAY:
2067                 bridge_unhold(props->transferee_bridge);
2068                 return TRANSFER_THREEWAY;
2069         case STIMULUS_DTMF_ATXFER_SWAP:
2070                 return TRANSFER_HESITANT;
2071         case STIMULUS_NONE:
2072         case STIMULUS_RECALL_TARGET_ANSWER:
2073         case STIMULUS_RECALL_TARGET_HANGUP:
2074         default:
2075                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2076                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2077                 return props->state;
2078         }
2079 }
2080
2081 static int hesitant_enter(struct attended_transfer_properties *props)
2082 {
2083         bridge_move(props->transferee_bridge, props->target_bridge, props->transferer, NULL);
2084         unhold(props->transferer);
2085         return 0;
2086 }
2087
2088 static enum attended_transfer_state hesitant_exit(struct attended_transfer_properties *props,
2089                 enum attended_transfer_stimulus stimulus)
2090 {
2091         switch (stimulus) {
2092         case STIMULUS_TRANSFEREE_HANGUP:
2093                 play_sound(props->transferer, props->failsound);
2094                 publish_transfer_fail(props);
2095                 return TRANSFER_FAIL;
2096         case STIMULUS_DTMF_ATXFER_COMPLETE:
2097         case STIMULUS_TRANSFERER_HANGUP:
2098                 return props->atxferdropcall ? TRANSFER_BLOND : TRANSFER_BLOND_NONFINAL;
2099         case STIMULUS_TRANSFER_TARGET_ANSWER:
2100                 return TRANSFER_DOUBLECHECKING;
2101         case STIMULUS_TRANSFER_TARGET_HANGUP:
2102         case STIMULUS_TIMEOUT:
2103         case STIMULUS_DTMF_ATXFER_ABORT:
2104                 play_sound(props->transferer, props->failsound);
2105                 return TRANSFER_RESUME;
2106         case STIMULUS_DTMF_ATXFER_THREEWAY:
2107                 return TRANSFER_THREEWAY;
2108         case STIMULUS_DTMF_ATXFER_SWAP:
2109                 hold(props->transferer);
2110                 return TRANSFER_CALLING_TARGET;
2111         case STIMULUS_NONE:
2112         case STIMULUS_RECALL_TARGET_HANGUP:
2113         case STIMULUS_RECALL_TARGET_ANSWER:
2114         default:
2115                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2116                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2117                 return props->state;
2118         }
2119 }
2120
2121 static int rebridge_enter(struct attended_transfer_properties *props)
2122 {
2123         bridge_move(props->transferee_bridge, props->target_bridge, props->transferer, NULL);
2124         unhold(props->transferer);
2125         return 0;
2126 }
2127
2128 static int resume_enter(struct attended_transfer_properties *props)
2129 {
2130         return 0;
2131 }
2132
2133 static int threeway_enter(struct attended_transfer_properties *props)
2134 {
2135         struct ast_channel *transferee_channel;
2136         struct ast_channel *target_channel;
2137
2138         get_transfer_parties(props->transferer, props->transferee_bridge, props->target_bridge,
2139                         &transferee_channel, &target_channel);
2140         bridge_merge(props->transferee_bridge, props->target_bridge, NULL, 0);
2141         play_sound(props->transfer_target, props->xfersound);
2142         play_sound(props->transferer, props->xfersound);
2143         publish_transfer_threeway(props, transferee_channel, target_channel);
2144
2145         ast_channel_cleanup(transferee_channel);
2146         ast_channel_cleanup(target_channel);
2147         return 0;
2148 }
2149
2150 static int consulting_enter(struct attended_transfer_properties *props)
2151 {
2152         return 0;
2153 }
2154
2155 static enum attended_transfer_state consulting_exit(struct attended_transfer_properties *props,
2156                 enum attended_transfer_stimulus stimulus)
2157 {
2158         switch (stimulus) {
2159         case STIMULUS_TRANSFEREE_HANGUP:
2160                 /* This is a one-of-a-kind event. The transferer and transfer target are talking in
2161                  * one bridge, and the transferee has hung up in a separate bridge. In this case, we
2162                  * will change the personality of the transfer target bridge back to normal, and play
2163                  * a sound to the transferer to indicate the transferee is gone.
2164                  */
2165                 bridge_basic_change_personality(props->target_bridge, BRIDGE_BASIC_PERSONALITY_NORMAL, NULL);
2166                 play_sound(props->transferer, props->failsound);
2167                 ast_bridge_merge_inhibit(props->target_bridge, -1);
2168                 /* These next two lines are here to ensure that our reference to the target bridge
2169                  * is cleaned up properly and that the target bridge is not destroyed when the
2170                  * monitor thread exits
2171                  */
2172                 ao2_ref(props->target_bridge, -1);
2173                 props->target_bridge = NULL;
2174                 return TRANSFER_FAIL;
2175         case STIMULUS_TRANSFERER_HANGUP:
2176         case STIMULUS_DTMF_ATXFER_COMPLETE:
2177                 /* We know the transferer is in the target_bridge, so take the other bridge off hold */
2178                 bridge_unhold(props->transferee_bridge);
2179                 return TRANSFER_COMPLETE;
2180         case STIMULUS_TRANSFER_TARGET_HANGUP:
2181         case STIMULUS_DTMF_ATXFER_ABORT:
2182                 play_sound(props->transferer, props->failsound);
2183                 return TRANSFER_REBRIDGE;
2184         case STIMULUS_DTMF_ATXFER_THREEWAY:
2185                 bridge_unhold(props->transferee_bridge);
2186                 return TRANSFER_THREEWAY;
2187         case STIMULUS_DTMF_ATXFER_SWAP:
2188                 hold(props->transferer);
2189                 bridge_move(props->transferee_bridge, props->target_bridge, props->transferer, NULL);
2190                 unhold(props->transferer);
2191                 return TRANSFER_DOUBLECHECKING;
2192         case STIMULUS_NONE:
2193         case STIMULUS_TIMEOUT:
2194         case STIMULUS_TRANSFER_TARGET_ANSWER:
2195         case STIMULUS_RECALL_TARGET_HANGUP:
2196         case STIMULUS_RECALL_TARGET_ANSWER:
2197         default:
2198                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2199                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2200                 return props->state;
2201         }
2202 }
2203
2204 static int double_checking_enter(struct attended_transfer_properties *props)
2205 {
2206         return 0;
2207 }
2208
2209 static enum attended_transfer_state double_checking_exit(struct attended_transfer_properties *props,
2210                 enum attended_transfer_stimulus stimulus)
2211 {
2212         switch (stimulus) {
2213         case STIMULUS_TRANSFEREE_HANGUP:
2214                 play_sound(props->transferer, props->failsound);
2215                 publish_transfer_fail(props);
2216                 return TRANSFER_FAIL;
2217         case STIMULUS_TRANSFERER_HANGUP:
2218         case STIMULUS_DTMF_ATXFER_COMPLETE:
2219                 /* We know the transferer is in the transferee, so take the other bridge off hold */
2220                 bridge_unhold(props->target_bridge);
2221                 return TRANSFER_COMPLETE;
2222         case STIMULUS_TRANSFER_TARGET_HANGUP:
2223         case STIMULUS_DTMF_ATXFER_ABORT:
2224                 play_sound(props->transferer, props->failsound);
2225                 return TRANSFER_RESUME;
2226         case STIMULUS_DTMF_ATXFER_THREEWAY:
2227                 bridge_unhold(props->target_bridge);
2228                 return TRANSFER_THREEWAY;
2229         case STIMULUS_DTMF_ATXFER_SWAP:
2230                 hold(props->transferer);
2231                 bridge_move(props->target_bridge, props->transferee_bridge, props->transferer, NULL);
2232                 unhold(props->transferer);
2233                 return TRANSFER_CONSULTING;
2234         case STIMULUS_NONE:
2235         case STIMULUS_TIMEOUT:
2236         case STIMULUS_TRANSFER_TARGET_ANSWER:
2237         case STIMULUS_RECALL_TARGET_HANGUP:
2238         case STIMULUS_RECALL_TARGET_ANSWER:
2239         default:
2240                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2241                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2242                 return props->state;
2243         }
2244 }
2245
2246 static int complete_enter(struct attended_transfer_properties *props)
2247 {
2248         struct ast_channel *transferee_channel;
2249         struct ast_channel *target_channel;
2250
2251         get_transfer_parties(props->transferer, props->transferee_bridge, props->target_bridge,
2252                         &transferee_channel, &target_channel);
2253         bridge_merge(props->transferee_bridge, props->target_bridge, &props->transferer, 1);
2254         play_sound(props->transfer_target, props->xfersound);
2255         publish_transfer_success(props, transferee_channel, target_channel);
2256
2257         ast_channel_cleanup(transferee_channel);
2258         ast_channel_cleanup(target_channel);
2259         return 0;
2260 }
2261
2262 static int blond_enter(struct attended_transfer_properties *props)
2263 {
2264         struct ast_channel *transferee_channel;
2265         struct ast_channel *target_channel;
2266
2267         get_transfer_parties(props->transferer, props->transferee_bridge, props->target_bridge,
2268                         &transferee_channel, &target_channel);
2269         bridge_merge(props->transferee_bridge, props->target_bridge, &props->transferer, 1);
2270         ringing(props->transfer_target);
2271         publish_transfer_success(props, transferee_channel, target_channel);
2272
2273         ast_channel_cleanup(transferee_channel);
2274         ast_channel_cleanup(target_channel);
2275         return 0;
2276 }
2277
2278 static int blond_nonfinal_enter(struct attended_transfer_properties *props)
2279 {
2280         int res;
2281         props->superstate = SUPERSTATE_RECALL;
2282         /* move the transfer target to the recall target along with its reference */
2283         props->recall_target = ast_channel_ref(props->transfer_target);
2284         res = blond_enter(props);
2285         props->transfer_target = ast_channel_unref(props->transfer_target);
2286         return res;
2287 }
2288
2289 static enum attended_transfer_state blond_nonfinal_exit(struct attended_transfer_properties *props,
2290                 enum attended_transfer_stimulus stimulus)
2291 {
2292         switch (stimulus) {
2293         case STIMULUS_TRANSFEREE_HANGUP:
2294                 return TRANSFER_FAIL;
2295         case STIMULUS_RECALL_TARGET_ANSWER:
2296                 return TRANSFER_RESUME;
2297         case STIMULUS_TIMEOUT:
2298                 ast_softhangup(props->recall_target, AST_SOFTHANGUP_EXPLICIT);
2299         case STIMULUS_RECALL_TARGET_HANGUP:
2300                 props->recall_target = ast_channel_unref(props->recall_target);
2301                 return TRANSFER_RECALLING;
2302         case STIMULUS_NONE:
2303         case STIMULUS_DTMF_ATXFER_ABORT:
2304         case STIMULUS_DTMF_ATXFER_COMPLETE:
2305         case STIMULUS_DTMF_ATXFER_THREEWAY:
2306         case STIMULUS_DTMF_ATXFER_SWAP:
2307         case STIMULUS_TRANSFERER_HANGUP:
2308         case STIMULUS_TRANSFER_TARGET_HANGUP:
2309         case STIMULUS_TRANSFER_TARGET_ANSWER:
2310         default:
2311                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2312                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2313                 return props->state;
2314         }
2315 }
2316
2317 /*!
2318  * \brief Dial callback when attempting to recall the original transferer channel
2319  *
2320  * This is how we can monitor if the recall target has answered or has hung up.
2321  * If one of the two is detected, then an appropriate stimulus is sent to the
2322  * attended transfer monitor thread.
2323  */
2324 static void recall_callback(struct ast_dial *dial)
2325 {
2326         struct attended_transfer_properties *props = ast_dial_get_user_data(dial);
2327
2328         switch (ast_dial_state(dial)) {
2329         default:
2330         case AST_DIAL_RESULT_INVALID:
2331         case AST_DIAL_RESULT_FAILED:
2332         case AST_DIAL_RESULT_TIMEOUT:
2333         case AST_DIAL_RESULT_HANGUP:
2334         case AST_DIAL_RESULT_UNANSWERED:
2335                 /* Failure cases */
2336                 stimulate_attended_transfer(props, STIMULUS_RECALL_TARGET_HANGUP);
2337                 break;
2338         case AST_DIAL_RESULT_RINGING:
2339         case AST_DIAL_RESULT_PROGRESS:
2340         case AST_DIAL_RESULT_PROCEEDING:
2341         case AST_DIAL_RESULT_TRYING:
2342                 /* Don't care about these cases */
2343                 break;
2344         case AST_DIAL_RESULT_ANSWERED:
2345                 /* We struck gold! */
2346                 props->recall_target = ast_dial_answered_steal(dial);
2347                 stimulate_attended_transfer(props, STIMULUS_RECALL_TARGET_ANSWER);
2348                 break;
2349         }
2350 }
2351
2352 /*!
2353  * \internal
2354  * \brief Setup common things to transferrer and transfer_target recall channels.
2355  *
2356  * \param recall Channel for recalling a party.
2357  * \param transferer Channel supplying recall information.
2358  *
2359  * \details
2360  * Setup callid, variables, datastores, accountcode, and peeraccount.
2361  *
2362  * \pre Both channels are locked on entry.
2363  *
2364  * \pre COLP and CLID on the recall channel are setup by the caller but not
2365  * explicitly published yet.
2366  *
2367  * \return Nothing
2368  */
2369 static void common_recall_channel_setup(struct ast_channel *recall, struct ast_channel *transferer)
2370 {
2371         ast_callid callid;
2372
2373         callid = ast_read_threadstorage_callid();
2374         if (callid) {
2375                 ast_channel_callid_set(recall, callid);
2376         }
2377
2378         ast_channel_inherit_variables(transferer, recall);
2379         ast_channel_datastore_inherit(transferer, recall);
2380
2381         /*
2382          * Stage a snapshot to ensure that a snapshot is always done
2383          * on the recall channel so earler COLP and CLID setup will
2384          * get published.
2385          */
2386         ast_channel_stage_snapshot(recall);
2387         ast_channel_req_accountcodes(recall, transferer, AST_CHANNEL_REQUESTOR_REPLACEMENT);
2388         ast_channel_stage_snapshot_done(recall);
2389 }
2390
2391 static int recalling_enter(struct attended_transfer_properties *props)
2392 {
2393         RAII_VAR(struct ast_format_cap *, cap, ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT), ao2_cleanup);
2394         struct ast_channel *recall;
2395
2396         if (!cap) {
2397                 return -1;
2398         }
2399
2400         ast_format_cap_append(cap, ast_format_slin, 0);
2401
2402         /* When we dial the transfer target, since we are communicating
2403          * with a local channel, we can place the local channel in a bridge
2404          * and then call out to it. When recalling the transferer, though, we
2405          * have to use the dialing API because the channel is not local.
2406          */
2407         props->dial = ast_dial_create();
2408         if (!props->dial) {
2409                 return -1;
2410         }
2411
2412         if (ast_dial_append(props->dial, props->transferer_type, props->transferer_addr, NULL)) {
2413                 return -1;
2414         }
2415
2416         if (ast_dial_prerun(props->dial, NULL, cap)) {
2417                 return -1;
2418         }
2419
2420         /*
2421          * Setup callid, variables, datastores, accountcode, peeraccount,
2422          * COLP, and CLID on the recalled transferrer.
2423          */
2424         recall = ast_dial_get_channel(props->dial, 0);
2425         if (!recall) {
2426                 return -1;
2427         }
2428         ast_channel_lock_both(recall, props->transferer);
2429
2430         ast_party_caller_copy(ast_channel_caller(recall),
2431                 ast_channel_caller(props->transferer));
2432         ast_party_connected_line_copy(ast_channel_connected(recall),
2433                 &props->original_transferer_colp);
2434
2435         common_recall_channel_setup(recall, props->transferer);
2436         ast_channel_unlock(recall);
2437         ast_channel_unlock(props->transferer);
2438
2439         ast_dial_set_state_callback(props->dial, recall_callback);
2440
2441         ao2_ref(props, +1);
2442         ast_dial_set_user_data(props->dial, props);
2443
2444         if (ast_dial_run(props->dial, NULL, 1) == AST_DIAL_RESULT_FAILED) {
2445                 ao2_ref(props, -1);
2446                 return -1;
2447         }
2448
2449         bridge_ringing(props->transferee_bridge);
2450         return 0;
2451 }
2452
2453 static enum attended_transfer_state recalling_exit(struct attended_transfer_properties *props,
2454                 enum attended_transfer_stimulus stimulus)
2455 {
2456         /* No matter what the outcome was, we need to kill off the dial */
2457         ast_dial_join(props->dial);
2458         ast_dial_destroy(props->dial);
2459         props->dial = NULL;
2460         /* This reference is the one we incremented for the dial state callback (recall_callback) to use */
2461         ao2_ref(props, -1);
2462
2463         switch (stimulus) {
2464         case STIMULUS_TRANSFEREE_HANGUP:
2465                 return TRANSFER_FAIL;
2466         case STIMULUS_TIMEOUT:
2467         case STIMULUS_RECALL_TARGET_HANGUP:
2468                 ++props->retry_attempts;
2469                 if (props->retry_attempts >= props->atxfercallbackretries) {
2470                         return TRANSFER_FAIL;
2471                 }
2472                 if (props->atxferloopdelay) {
2473                         return TRANSFER_WAIT_TO_RETRANSFER;
2474                 }
2475                 return TRANSFER_RETRANSFER;
2476         case STIMULUS_RECALL_TARGET_ANSWER:
2477                 /* Setting this datastore up will allow the transferer to have all of his
2478                  * call features set up automatically when the bridge changes back to a
2479                  * normal personality
2480                  */
2481                 ast_bridge_features_ds_set(props->recall_target, &props->transferer_features);
2482                 ast_channel_ref(props->recall_target);
2483                 if (ast_bridge_impart(props->transferee_bridge, props->recall_target, NULL, NULL,
2484                         AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
2485                         ast_hangup(props->recall_target);
2486                         ast_channel_unref(props->recall_target);
2487                         return TRANSFER_FAIL;
2488                 }
2489                 return TRANSFER_RESUME;
2490         case STIMULUS_NONE:
2491         case STIMULUS_DTMF_ATXFER_ABORT:
2492         case STIMULUS_DTMF_ATXFER_COMPLETE:
2493         case STIMULUS_DTMF_ATXFER_THREEWAY:
2494         case STIMULUS_DTMF_ATXFER_SWAP:
2495         case STIMULUS_TRANSFER_TARGET_HANGUP:
2496         case STIMULUS_TRANSFER_TARGET_ANSWER:
2497         case STIMULUS_TRANSFERER_HANGUP:
2498         default:
2499                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2500                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2501                 return props->state;
2502         }
2503 }
2504
2505 static int wait_to_retransfer_enter(struct attended_transfer_properties *props)
2506 {
2507         bridge_hold(props->transferee_bridge);
2508         return 0;
2509 }
2510
2511 static enum attended_transfer_state wait_to_retransfer_exit(struct attended_transfer_properties *props,
2512                 enum attended_transfer_stimulus stimulus)
2513 {
2514         bridge_unhold(props->transferee_bridge);
2515         switch (stimulus) {
2516         case STIMULUS_TRANSFEREE_HANGUP:
2517                 return TRANSFER_FAIL;
2518         case STIMULUS_TIMEOUT:
2519                 return TRANSFER_RETRANSFER;
2520         case STIMULUS_NONE:
2521         case STIMULUS_DTMF_ATXFER_ABORT:
2522         case STIMULUS_DTMF_ATXFER_COMPLETE:
2523         case STIMULUS_DTMF_ATXFER_THREEWAY:
2524         case STIMULUS_DTMF_ATXFER_SWAP:
2525         case STIMULUS_TRANSFER_TARGET_HANGUP:
2526         case STIMULUS_TRANSFER_TARGET_ANSWER:
2527         case STIMULUS_TRANSFERER_HANGUP:
2528         case STIMULUS_RECALL_TARGET_HANGUP:
2529         case STIMULUS_RECALL_TARGET_ANSWER:
2530         default:
2531                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2532                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2533                 return props->state;
2534         }
2535 }
2536
2537 static int attach_framehook(struct attended_transfer_properties *props, struct ast_channel *channel);
2538
2539 static int retransfer_enter(struct attended_transfer_properties *props)
2540 {
2541         RAII_VAR(struct ast_format_cap *, cap, ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT), ao2_cleanup);
2542         char destination[AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2];
2543         int cause;
2544
2545         if (!cap) {
2546                 return -1;
2547         }
2548
2549         snprintf(destination, sizeof(destination), "%s@%s", props->exten, props->context);
2550
2551         ast_format_cap_append(cap, ast_format_slin, 0);
2552
2553         /* Get a channel that is the destination we wish to call */
2554         props->recall_target = ast_request("Local", cap, NULL, NULL, destination, &cause);
2555         if (!props->recall_target) {
2556                 ast_log(LOG_ERROR, "Unable to request outbound channel for recall target\n");
2557                 return -1;
2558         }
2559
2560         if (attach_framehook(props, props->recall_target)) {
2561                 ast_log(LOG_ERROR, "Unable to attach framehook to recall target\n");
2562                 ast_hangup(props->recall_target);
2563                 props->recall_target = NULL;
2564                 return -1;
2565         }
2566
2567         /*
2568          * Setup callid, variables, datastores, accountcode, peeraccount,
2569          * and COLP on the recalled transfer target.
2570          */
2571         ast_channel_lock_both(props->recall_target, props->transferer);
2572
2573         ast_party_connected_line_copy(ast_channel_connected(props->recall_target),
2574                 &props->original_transferer_colp);
2575         ast_party_id_reset(&ast_channel_connected(props->recall_target)->priv);
2576
2577         common_recall_channel_setup(props->recall_target, props->recall_target);
2578         ast_channel_unlock(props->recall_target);
2579         ast_channel_unlock(props->transferer);
2580
2581         if (ast_call(props->recall_target, destination, 0)) {
2582                 ast_log(LOG_ERROR, "Unable to place outbound call to recall target\n");
2583                 ast_hangup(props->recall_target);
2584                 props->recall_target = NULL;
2585                 return -1;
2586         }
2587
2588         ast_channel_ref(props->recall_target);
2589         if (ast_bridge_impart(props->transferee_bridge, props->recall_target, NULL, NULL,
2590                 AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
2591                 ast_log(LOG_ERROR, "Unable to place recall target into bridge\n");
2592                 ast_hangup(props->recall_target);
2593                 ast_channel_unref(props->recall_target);
2594                 return -1;
2595         }
2596
2597         return 0;
2598 }
2599
2600 static enum attended_transfer_state retransfer_exit(struct attended_transfer_properties *props,
2601                 enum attended_transfer_stimulus stimulus)
2602 {
2603         switch (stimulus) {
2604         case STIMULUS_TRANSFEREE_HANGUP:
2605                 return TRANSFER_FAIL;
2606         case STIMULUS_TIMEOUT:
2607                 ast_softhangup(props->recall_target, AST_SOFTHANGUP_EXPLICIT);
2608         case STIMULUS_RECALL_TARGET_HANGUP:
2609                 props->recall_target = ast_channel_unref(props->recall_target);
2610                 if (props->atxferloopdelay) {
2611                         return TRANSFER_WAIT_TO_RECALL;
2612                 }
2613                 return TRANSFER_RECALLING;
2614         case STIMULUS_RECALL_TARGET_ANSWER:
2615                 return TRANSFER_RESUME;
2616         case STIMULUS_NONE:
2617         case STIMULUS_DTMF_ATXFER_ABORT:
2618         case STIMULUS_DTMF_ATXFER_COMPLETE:
2619         case STIMULUS_DTMF_ATXFER_THREEWAY:
2620         case STIMULUS_DTMF_ATXFER_SWAP:
2621         case STIMULUS_TRANSFER_TARGET_HANGUP:
2622         case STIMULUS_TRANSFER_TARGET_ANSWER:
2623         case STIMULUS_TRANSFERER_HANGUP:
2624         default:
2625                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2626                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2627                 return props->state;
2628         }
2629 }
2630
2631 static int wait_to_recall_enter(struct attended_transfer_properties *props)
2632 {
2633         bridge_hold(props->transferee_bridge);
2634         return 0;
2635 }
2636
2637 static enum attended_transfer_state wait_to_recall_exit(struct attended_transfer_properties *props,
2638                 enum attended_transfer_stimulus stimulus)
2639 {
2640         bridge_unhold(props->transferee_bridge);
2641         switch (stimulus) {
2642         case STIMULUS_TRANSFEREE_HANGUP:
2643                 return TRANSFER_FAIL;
2644         case STIMULUS_TIMEOUT:
2645                 return TRANSFER_RECALLING;
2646         case STIMULUS_NONE:
2647         case STIMULUS_DTMF_ATXFER_ABORT:
2648         case STIMULUS_DTMF_ATXFER_COMPLETE:
2649         case STIMULUS_DTMF_ATXFER_THREEWAY:
2650         case STIMULUS_DTMF_ATXFER_SWAP:
2651         case STIMULUS_TRANSFER_TARGET_HANGUP:
2652         case STIMULUS_TRANSFER_TARGET_ANSWER:
2653         case STIMULUS_TRANSFERER_HANGUP:
2654         case STIMULUS_RECALL_TARGET_HANGUP:
2655         case STIMULUS_RECALL_TARGET_ANSWER:
2656         default:
2657                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2658                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2659                 return props->state;
2660         }
2661 }
2662
2663 static int fail_enter(struct attended_transfer_properties *props)
2664 {
2665         if (props->transferee_bridge) {
2666                 ast_bridge_destroy(props->transferee_bridge, 0);
2667                 props->transferee_bridge = NULL;
2668         }
2669         return 0;
2670 }
2671
2672 /*!
2673  * \brief DTMF hook when transferer presses abort sequence.
2674  *
2675  * Sends a stimulus to the attended transfer monitor thread that the abort sequence has been pressed
2676  */
2677 static int atxfer_abort(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2678 {
2679         struct attended_transfer_properties *props = hook_pvt;
2680
2681         ast_debug(1, "Transferer on attended transfer %p pressed abort sequence\n", props);
2682         stimulate_attended_transfer(props, STIMULUS_DTMF_ATXFER_ABORT);
2683         return 0;
2684 }
2685
2686 /*!
2687  * \brief DTMF hook when transferer presses complete sequence.
2688  *
2689  * Sends a stimulus to the attended transfer monitor thread that the complete sequence has been pressed
2690  */
2691 static int atxfer_complete(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2692 {
2693         struct attended_transfer_properties *props = hook_pvt;
2694
2695         ast_debug(1, "Transferer on attended transfer %p pressed complete sequence\n", props);
2696         stimulate_attended_transfer(props, STIMULUS_DTMF_ATXFER_COMPLETE);
2697         return 0;
2698 }
2699
2700 /*!
2701  * \brief DTMF hook when transferer presses threeway sequence.
2702  *
2703  * Sends a stimulus to the attended transfer monitor thread that the threeway sequence has been pressed
2704  */
2705 static int atxfer_threeway(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2706 {
2707         struct attended_transfer_properties *props = hook_pvt;
2708
2709         ast_debug(1, "Transferer on attended transfer %p pressed threeway sequence\n", props);
2710         stimulate_attended_transfer(props, STIMULUS_DTMF_ATXFER_THREEWAY);
2711         return 0;
2712 }
2713
2714 /*!
2715  * \brief DTMF hook when transferer presses swap sequence.
2716  *
2717  * Sends a stimulus to the attended transfer monitor thread that the swap sequence has been pressed
2718  */
2719 static int atxfer_swap(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2720 {
2721         struct attended_transfer_properties *props = hook_pvt;
2722
2723         ast_debug(1, "Transferer on attended transfer %p pressed swap sequence\n", props);
2724         stimulate_attended_transfer(props, STIMULUS_DTMF_ATXFER_SWAP);
2725         return 0;
2726 }
2727
2728 /*!
2729  * \brief Hangup hook for transferer channel.
2730  *
2731  * Sends a stimulus to the attended transfer monitor thread that the transferer has hung up.
2732  */
2733 static int atxfer_transferer_hangup(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2734 {
2735         struct attended_transfer_properties *props = hook_pvt;
2736
2737         ast_debug(1, "Transferer on attended transfer %p hung up\n", props);
2738         stimulate_attended_transfer(props, STIMULUS_TRANSFERER_HANGUP);
2739         return 0;
2740 }
2741
2742 /*!
2743  * \brief Frame hook for transfer target channel
2744  *
2745  * This is used to determine if the transfer target or recall target has answered
2746  * the outgoing call.
2747  *
2748  * When an answer is detected, a stimulus is sent to the attended transfer monitor
2749  * thread to indicate that the transfer target or recall target has answered.
2750  *
2751  * \param chan The channel the framehook is attached to.
2752  * \param frame The frame being read or written.
2753  * \param event What is being done with the frame.
2754  * \param data The attended transfer properties.
2755  */
2756 static struct ast_frame *transfer_target_framehook_cb(struct ast_channel *chan,
2757                 struct ast_frame *frame, enum ast_framehook_event event, void *data)
2758 {
2759         struct attended_transfer_properties *props = data;
2760
2761         if (event == AST_FRAMEHOOK_EVENT_READ &&
2762                         frame && frame->frametype == AST_FRAME_CONTROL &&
2763                         frame->subclass.integer == AST_CONTROL_ANSWER) {
2764
2765                 ast_debug(1, "Detected an answer for recall attempt on attended transfer %p\n", props);
2766                 if (props->superstate == SUPERSTATE_TRANSFER) {
2767                         stimulate_attended_transfer(props, STIMULUS_TRANSFER_TARGET_ANSWER);
2768                 } else {
2769                         stimulate_attended_transfer(props, STIMULUS_RECALL_TARGET_ANSWER);
2770                 }
2771                 ast_framehook_detach(chan, props->target_framehook_id);
2772                 props->target_framehook_id = -1;
2773         }
2774
2775         return frame;
2776 }
2777
2778 /*! \brief Callback function which informs upstream if we are consuming a frame of a specific type */
2779 static int transfer_target_framehook_consume(void *data, enum ast_frame_type type)
2780 {
2781         return (type == AST_FRAME_CONTROL ? 1 : 0);
2782 }
2783
2784 static void transfer_target_framehook_destroy_cb(void *data)
2785 {
2786         struct attended_transfer_properties *props = data;
2787         ao2_cleanup(props);
2788 }
2789
2790 static int bridge_personality_atxfer_push(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
2791 {
2792         const char *abort_dtmf;
2793         const char *complete_dtmf;
2794         const char *threeway_dtmf;
2795         const char *swap_dtmf;
2796         struct bridge_basic_personality *personality = self->personality;
2797
2798         if (!ast_channel_has_role(bridge_channel->chan, AST_TRANSFERER_ROLE_NAME)) {
2799                 return 0;
2800         }
2801
2802         abort_dtmf = ast_channel_get_role_option(bridge_channel->chan, AST_TRANSFERER_ROLE_NAME, "abort");
2803         complete_dtmf = ast_channel_get_role_option(bridge_channel->chan, AST_TRANSFERER_ROLE_NAME, "complete");
2804         threeway_dtmf = ast_channel_get_role_option(bridge_channel->chan, AST_TRANSFERER_ROLE_NAME, "threeway");
2805         swap_dtmf = ast_channel_get_role_option(bridge_channel->chan, AST_TRANSFERER_ROLE_NAME, "swap");
2806
2807         if (!ast_strlen_zero(abort_dtmf) && ast_bridge_dtmf_hook(bridge_channel->features,
2808                         abort_dtmf, atxfer_abort, personality->details[personality->current].pvt, NULL,
2809                         AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE | AST_BRIDGE_HOOK_REMOVE_ON_PULL)) {
2810                 return -1;
2811         }
2812         if (!ast_strlen_zero(complete_dtmf) && ast_bridge_dtmf_hook(bridge_channel->features,
2813                         complete_dtmf, atxfer_complete, personality->details[personality->current].pvt, NULL,
2814                         AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE | AST_BRIDGE_HOOK_REMOVE_ON_PULL)) {
2815                 return -1;
2816         }
2817         if (!ast_strlen_zero(threeway_dtmf) && ast_bridge_dtmf_hook(bridge_channel->features,
2818                         threeway_dtmf, atxfer_threeway, personality->details[personality->current].pvt, NULL,
2819                         AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE | AST_BRIDGE_HOOK_REMOVE_ON_PULL)) {
2820                 return -1;
2821         }
2822         if (!ast_strlen_zero(swap_dtmf) && ast_bridge_dtmf_hook(bridge_channel->features,
2823                         swap_dtmf, atxfer_swap, personality->details[personality->current].pvt, NULL,
2824                         AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE | AST_BRIDGE_HOOK_REMOVE_ON_PULL)) {
2825                 return -1;
2826         }
2827         if (ast_bridge_hangup_hook(bridge_channel->features, atxfer_transferer_hangup,
2828                         personality->details[personality->current].pvt, NULL,
2829                         AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE | AST_BRIDGE_HOOK_REMOVE_ON_PULL)) {
2830                 return -1;
2831         }
2832
2833         return 0;
2834 }
2835
2836 static void transfer_pull(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct attended_transfer_properties *props)
2837 {
2838         if (self->num_channels > 1 || bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2839                 return;
2840         }
2841
2842         if (self->num_channels == 1) {
2843                 struct ast_bridge_channel *transferer_bridge_channel;
2844                 int not_transferer;
2845
2846                 ast_channel_lock(props->transferer);
2847                 transferer_bridge_channel = ast_channel_get_bridge_channel(props->transferer);
2848                 ast_channel_unlock(props->transferer);
2849
2850                 if (!transferer_bridge_channel) {
2851                         return;
2852                 }
2853
2854                 not_transferer = AST_LIST_FIRST(&self->channels) != transferer_bridge_channel;
2855                 ao2_ref(transferer_bridge_channel, -1);
2856                 if (not_transferer) {
2857                         return;
2858                 }
2859         }
2860
2861         /* Reaching this point means that either
2862          * 1) The bridge has no channels in it
2863          * 2) The bridge has one channel, and it's the transferer
2864          * In either case, it indicates that the non-transferer parties
2865          * are no longer in the bridge.
2866          */
2867         if (self == props->transferee_bridge) {
2868                 stimulate_attended_transfer(props, STIMULUS_TRANSFEREE_HANGUP);
2869         } else {
2870                 stimulate_attended_transfer(props, STIMULUS_TRANSFER_TARGET_HANGUP);
2871         }
2872 }
2873
2874 static void recall_pull(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct attended_transfer_properties *props)
2875 {
2876         if (self == props->target_bridge) {
2877                 /* Once we're in the recall superstate, we no longer care about this bridge */
2878                 return;
2879         }
2880
2881         if (bridge_channel->chan == props->recall_target) {
2882                 stimulate_attended_transfer(props, STIMULUS_RECALL_TARGET_HANGUP);
2883                 return;
2884         }
2885
2886         if (self->num_channels == 0) {
2887                 /* Empty bridge means all transferees are gone for sure */
2888                 stimulate_attended_transfer(props, STIMULUS_TRANSFEREE_HANGUP);
2889                 return;
2890         }
2891
2892         if (self->num_channels == 1) {
2893                 struct ast_bridge_channel *target_bridge_channel;
2894
2895                 if (!props->recall_target) {
2896                         /* No recall target means that the pull happened on a transferee. If there's still
2897                          * a channel left in the bridge, we don't need to send a stimulus
2898                          */
2899                         return;
2900                 }
2901
2902                 ast_channel_lock(props->recall_target);
2903                 target_bridge_channel = ast_channel_get_bridge_channel(props->recall_target);
2904                 ast_channel_unlock(props->recall_target);
2905
2906                 if (target_bridge_channel) {
2907                         if (AST_LIST_FIRST(&self->channels) == target_bridge_channel) {
2908                                 stimulate_attended_transfer(props, STIMULUS_TRANSFEREE_HANGUP);
2909                         }
2910                         ao2_ref(target_bridge_channel, -1);
2911                 }
2912         }
2913 }
2914
2915 static void bridge_personality_atxfer_pull(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel)
2916 {
2917         struct bridge_basic_personality *personality = self->personality;
2918         struct attended_transfer_properties *props = personality->details[personality->current].pvt;
2919
2920         switch (props->superstate) {
2921         case SUPERSTATE_TRANSFER:
2922                 transfer_pull(self, bridge_channel, props);
2923                 break;
2924         case SUPERSTATE_RECALL:
2925                 recall_pull(self, bridge_channel, props);
2926                 break;
2927         }
2928 }
2929
2930 static enum attended_transfer_stimulus wait_for_stimulus(struct attended_transfer_properties *props)
2931 {
2932         enum attended_transfer_stimulus stimulus;
2933         struct stimulus_list *list;
2934         SCOPED_MUTEX(lock, ao2_object_get_lockaddr(props));
2935
2936         while (!(list = AST_LIST_REMOVE_HEAD(&props->stimulus_queue, next))) {
2937                 if (!(state_properties[props->state].flags & TRANSFER_STATE_FLAG_TIMED)) {
2938                         ast_cond_wait(&props->cond, lock);
2939                 } else {
2940                         struct timeval relative_timeout = { 0, };
2941                         struct timeval absolute_timeout;
2942                         struct timespec timeout_arg;
2943
2944                         if (state_properties[props->state].flags & TRANSFER_STATE_FLAG_TIMER_RESET) {
2945                                 props->start = ast_tvnow();
2946                         }
2947
2948                         if (state_properties[props->state].flags & TRANSFER_STATE_FLAG_TIMER_LOOP_DELAY) {
2949                                 relative_timeout.tv_sec = props->atxferloopdelay;
2950                         } else {
2951                                 /* Implied TRANSFER_STATE_FLAG_TIMER_ATXFER_NO_ANSWER */
2952                                 relative_timeout.tv_sec = props->atxfernoanswertimeout;
2953                         }
2954
2955                         absolute_timeout = ast_tvadd(props->start, relative_timeout);
2956                         timeout_arg.tv_sec = absolute_timeout.tv_sec;
2957                         timeout_arg.tv_nsec = absolute_timeout.tv_usec * 1000;
2958
2959                         if (ast_cond_timedwait(&props->cond, lock, &timeout_arg) == ETIMEDOUT) {
2960                                 return STIMULUS_TIMEOUT;
2961                         }
2962                 }
2963         }
2964         stimulus = list->stimulus;
2965         ast_free(list);
2966         return stimulus;
2967 }
2968
2969 /*!
2970  * \brief The main loop for the attended transfer monitor thread.
2971  *
2972  * This loop runs continuously until the attended transfer reaches
2973  * a terminal state. Stimuli for changes in the attended transfer
2974  * state are handled in this thread so that all factors in an
2975  * attended transfer can be handled in an orderly fashion.
2976  *
2977  * \param data The attended transfer properties
2978  */
2979 static void *attended_transfer_monitor_thread(void *data)
2980 {
2981         struct attended_transfer_properties *props = data;
2982         ast_callid callid;
2983
2984         /*
2985          * Set thread callid to the transferer's callid because we
2986          * are doing all this on that channel's behalf.
2987          */
2988         ast_channel_lock(props->transferer);
2989         callid = ast_channel_callid(props->transferer);
2990         ast_channel_unlock(props->transferer);
2991         if (callid) {
2992                 ast_callid_threadassoc_add(callid);
2993         }
2994
2995         for (;;) {
2996                 enum attended_transfer_stimulus stimulus;
2997
2998                 ast_debug(1, "About to enter state %s for attended transfer %p\n", state_properties[props->state].state_name, props);
2999
3000                 if (state_properties[props->state].enter &&
3001                                 state_properties[props->state].enter(props)) {
3002                         ast_log(LOG_ERROR, "State %s enter function returned an error for attended transfer %p\n",
3003                                         state_properties[props->state].state_name, props);
3004                         break;
3005                 }
3006
3007                 if (state_properties[props->state].flags & TRANSFER_STATE_FLAG_TERMINAL) {
3008                         ast_debug(1, "State %s is a terminal state. Ending attended transfer %p\n",
3009                                         state_properties[props->state].state_name, props);
3010                         break;
3011                 }
3012
3013                 stimulus = wait_for_stimulus(props);
3014
3015                 ast_debug(1, "Received stimulus %s on attended transfer %p\n", stimulus_strs[stimulus], props);
3016
3017                 ast_assert(state_properties[props->state].exit != NULL);
3018
3019                 props->state = state_properties[props->state].exit(props, stimulus);
3020
3021                 ast_debug(1, "Told to enter state %s exit on attended transfer %p\n", state_properties[props->state].state_name, props);
3022         }
3023
3024         attended_transfer_properties_shutdown(props);
3025
3026         if (callid) {
3027                 ast_callid_threadassoc_remove();
3028         }
3029
3030         return NULL;
3031 }
3032
3033 static int attach_framehook(struct attended_transfer_properties *props, struct ast_channel *channel)
3034 {
3035         struct ast_framehook_interface target_interface = {
3036                 .version = AST_FRAMEHOOK_INTERFACE_VERSION,
3037                 .event_cb = transfer_target_framehook_cb,
3038                 .destroy_cb = transfer_target_framehook_destroy_cb,
3039                 .consume_cb = transfer_target_framehook_consume,
3040                 .disable_inheritance = 1,
3041         };
3042
3043         ao2_ref(props, +1);
3044         target_interface.data = props;
3045
3046         props->target_framehook_id = ast_framehook_attach(channel, &target_interface);
3047         if (props->target_framehook_id == -1) {
3048                 ao2_ref(props, -1);
3049                 return -1;
3050         }
3051         return 0;
3052 }
3053
3054 static int add_transferer_role(struct ast_channel *chan, struct ast_bridge_features_attended_transfer *attended_transfer)
3055 {
3056         const char *atxfer_abort;
3057         const char *atxfer_threeway;
3058         const char *atxfer_complete;
3059         const char *atxfer_swap;
3060         struct ast_features_xfer_config *xfer_cfg;
3061         SCOPED_CHANNELLOCK(lock, chan);
3062
3063         xfer_cfg = ast_get_chan_features_xfer_config(chan);
3064         if (!xfer_cfg) {
3065                 return -1;
3066         }
3067         if (attended_transfer) {
3068                 atxfer_abort = ast_strdupa(S_OR(attended_transfer->abort, xfer_cfg->atxferabort));
3069                 atxfer_threeway = ast_strdupa(S_OR(attended_transfer->threeway, xfer_cfg->atxferthreeway));
3070                 atxfer_complete = ast_strdupa(S_OR(attended_transfer->complete, xfer_cfg->atxfercomplete));
3071                 atxfer_swap = ast_strdupa(S_OR(attended_transfer->swap, xfer_cfg->atxferswap));
3072         } else {
3073                 atxfer_abort = ast_strdupa(xfer_cfg->atxferabort);
3074                 atxfer_threeway = ast_strdupa(xfer_cfg->atxferthreeway);
3075                 atxfer_complete = ast_strdupa(xfer_cfg->atxfercomplete);
3076                 atxfer_swap = ast_strdupa(xfer_cfg->atxferswap);
3077         }
3078         ao2_ref(xfer_cfg, -1);
3079
3080         return ast_channel_add_bridge_role(chan, AST_TRANSFERER_ROLE_NAME) ||
3081                 ast_channel_set_bridge_role_option(chan, AST_TRANSFERER_ROLE_NAME, "abort", atxfer_abort) ||
3082                 ast_channel_set_bridge_role_option(chan, AST_TRANSFERER_ROLE_NAME, "complete", atxfer_complete) ||
3083                 ast_channel_set_bridge_role_option(chan, AST_TRANSFERER_ROLE_NAME, "threeway", atxfer_threeway) ||
3084                 ast_channel_set_bridge_role_option(chan, AST_TRANSFERER_ROLE_NAME, "swap", atxfer_swap);
3085 }
3086
3087 /*!
3088  * \brief Helper function that presents dialtone and grabs extension
3089  *
3090  * \retval 0 on success
3091  * \retval -1 on failure
3092  */
3093 static int grab_transfer(struct ast_channel *chan, char *exten, size_t exten_len, const char *context)
3094 {
3095         int res;
3096         int digit_timeout;
3097         int attempts = 0;
3098         int max_attempts;
3099         struct ast_features_xfer_config *xfer_cfg;
3100         char *retry_sound;
3101         char *invalid_sound;
3102
3103         ast_channel_lock(chan);
3104         xfer_cfg = ast_get_chan_features_xfer_config(chan);
3105         if (!xfer_cfg) {
3106                 ast_log(LOG_ERROR, "Unable to get transfer configuration\n");
3107                 ast_channel_unlock(chan);
3108                 return -1;
3109         }
3110         digit_timeout = xfer_cfg->transferdigittimeout * 1000;
3111         max_attempts = xfer_cfg->transferdialattempts;
3112         retry_sound = ast_strdupa(xfer_cfg->transferretrysound);
3113         invalid_sound = ast_strdupa(xfer_cfg->transferinvalidsound);
3114         ao2_ref(xfer_cfg, -1);
3115         ast_channel_unlock(chan);
3116
3117         /* Play the simple "transfer" prompt out and wait */
3118         res = ast_stream_and_wait(chan, "pbx-transfer", AST_DIGIT_ANY);
3119         ast_stopstream(chan);
3120         if (res < 0) {
3121                 /* Hangup or error */
3122                 return -1;
3123         }
3124         if (res) {
3125                 /* Store the DTMF digit that interrupted playback of the file. */
3126                 exten[0] = res;
3127         }
3128
3129         /* Drop to dialtone so they can enter the extension they want to transfer to */
3130         do {
3131                 ++attempts;
3132
3133                 ast_test_suite_event_notify("TRANSFER_BEGIN_DIAL",
3134                                 "Channel: %s\r\n"
3135                                 "Attempt: %d",
3136                                 ast_channel_name(chan), attempts);
3137                 res = ast_app_dtget(chan, context, exten, exten_len, exten_len - 1, digit_timeout);
3138                 ast_test_suite_event_notify("TRANSFER_DIALLED",
3139                                 "Channel: %s\r\n"
3140                                 "Attempt: %d\r\n"
3141                                 "Dialled: %s\r\n"
3142                                 "Result: %s",
3143                                 ast_channel_name(chan), attempts, exten, res > 0 ? "Success" : "Failure");
3144                 if (res < 0) {
3145                         /* Hangup or error */
3146                         res = -1;
3147                 } else if (!res) {
3148                         /* 0 for invalid extension dialed. */
3149                         if (ast_strlen_zero(exten)) {
3150                                 ast_debug(1, "%s dialed no digits.\n", ast_channel_name(chan));
3151                         } else {
3152                                 ast_debug(1, "%s dialed '%s@%s' does not exist.\n",
3153                                         ast_channel_name(chan), exten, context);
3154                         }
3155                         if (attempts < max_attempts) {
3156                                 ast_stream_and_wait(chan, retry_sound, AST_DIGIT_NONE);
3157                         } else {
3158                                 ast_stream_and_wait(chan, invalid_sound, AST_DIGIT_NONE);
3159                         }
3160                         memset(exten, 0, exten_len);
3161                         res = 1;
3162                 } else {
3163                         /* Dialed extension is valid. */
3164                         res = 0;
3165                 }
3166         } while (res > 0 && attempts < max_attempts);
3167
3168         ast_test_suite_event_notify("TRANSFER_DIAL_FINAL",
3169                         "Channel: %s\r\n"
3170                         "Result: %s",
3171                         ast_channel_name(chan), res == 0 ? "Success" : "Failure");
3172
3173         return res ? -1 : 0;
3174 }
3175
3176 static void copy_caller_data(struct ast_channel *dest, struct ast_channel *caller)
3177 {
3178         ast_channel_lock_both(caller, dest);
3179         ast_connected_line_copy_from_caller(ast_channel_connected(dest), ast_channel_caller(caller));
3180         ast_channel_inherit_variables(caller, dest);
3181         ast_channel_datastore_inherit(caller, dest);
3182         ast_channel_unlock(dest);
3183         ast_channel_unlock(caller);
3184 }
3185
3186 /*! \brief Helper function that creates an outgoing channel and returns it immediately */
3187 static struct ast_channel *dial_transfer(struct ast_channel *caller, const char *destination)
3188 {
3189         struct ast_channel *chan;
3190         int cause;
3191
3192         /* Now we request a local channel to prepare to call the destination */
3193         chan = ast_request("Local", ast_channel_nativeformats(caller), NULL, caller, destination,
3194                 &cause);
3195         if (!chan) {
3196                 return NULL;
3197         }
3198
3199         ast_channel_lock_both(chan, caller);
3200
3201         ast_channel_req_accountcodes(chan, caller, AST_CHANNEL_REQUESTOR_BRIDGE_PEER);
3202
3203         /* Who is transferring the call. */
3204         pbx_builtin_setvar_helper(chan, "TRANSFERERNAME", ast_channel_name(caller));
3205
3206         ast_bridge_set_transfer_variables(chan, ast_channel_name(caller), 1);
3207
3208         ast_channel_unlock(chan);
3209         ast_channel_unlock(caller);
3210
3211         /* Before we actually dial out let's inherit appropriate information. */
3212         copy_caller_data(chan, caller);
3213
3214         return chan;
3215 }
3216
3217 /*!
3218  * \brief Internal built in feature for attended transfers
3219  *
3220  * This hook will set up a thread for monitoring the progress of
3221  * an attended transfer. For more information about attended transfer
3222  * progress, see documentation on the transfer state machine.
3223  *
3224  * \param bridge_channel The channel that pressed the attended transfer DTMF sequence
3225  * \param hook_pvt Structure with further information about the attended transfer
3226  */
3227 static int feature_attended_transfer(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
3228 {
3229         struct ast_bridge_features_attended_transfer *attended_transfer = hook_pvt;
3230         struct attended_transfer_properties *props;
3231         struct ast_bridge *bridge;
3232         char destination[AST_MAX_EXTENSION + AST_MAX_CONTEXT + 1];
3233         char exten[AST_MAX_EXTENSION] = "";
3234         pthread_t thread;
3235
3236         /* Inhibit the bridge before we do anything else. */
3237         bridge = ast_bridge_channel_merge_inhibit(bridge_channel, +1);
3238
3239         if (strcmp(bridge->v_table->name, "basic")) {
3240                 ast_log(LOG_ERROR, "Attended transfer attempted on unsupported bridge type '%s'.\n",
3241                         bridge->v_table->name);
3242                 ast_bridge_merge_inhibit(bridge, -1);
3243                 ao2_ref(bridge, -1);
3244                 return 0;
3245         }
3246
3247         /* Was the bridge inhibited before we inhibited it? */
3248         if (1 < bridge->inhibit_merge) {
3249                 /*
3250                  * The peer likely initiated attended transfer at the same time
3251                  * and we lost the race.
3252                  */
3253                 ast_verb(3, "Channel %s: Bridge '%s' does not permit merging at this time.\n",
3254                         ast_channel_name(bridge_channel->chan), bridge->uniqueid);
3255                 ast_bridge_merge_inhibit(bridge, -1);
3256                 ao2_ref(bridge, -1);
3257                 return 0;
3258         }
3259
3260         props = attended_transfer_properties_alloc(bridge_channel->chan,
3261                 attended_transfer ? attended_transfer->context : NULL);
3262         if (!props) {
3263                 ast_log(LOG_ERROR, "Unable to allocate control structure for performing attended transfer.\n");
3264                 ast_bridge_merge_inhibit(bridge, -1);
3265                 ao2_ref(bridge, -1);
3266                 return 0;
3267         }
3268
3269         props->transferee_bridge = bridge;
3270
3271         if (add_transferer_role(props->transferer, attended_transfer)) {
3272                 ast_log(LOG_ERROR, "Unable to set transferrer bridge role.\n");
3273                 attended_transfer_properties_shutdown(props);
3274                 return 0;
3275         }
3276
3277         ast_bridge_channel_write_hold(bridge_channel, NULL);
3278
3279         /* Grab the extension to transfer to */
3280         if (grab_transfer(bridge_channel->chan, exten, sizeof(exten), props->context)) {
3281                 ast_log(LOG_WARNING, "Unable to acquire target extension for attended transfer.\n");
3282                 ast_bridge_channel_write_unhold(bridge_channel);
3283                 attended_transfer_properties_shutdown(props);
3284                 return 0;
3285         }
3286
3287         ast_string_field_set(props, exten, exten);
3288
3289         /* Fill the variable with the extension and context we want to call */
3290         snprintf(destination, sizeof(destination), "%s@%s", props->exten, props->context);
3291
3292         ast_debug(1, "Attended transfer to '%s'\n", destination);
3293
3294         /* Get a channel that is the destination we wish to call */
3295         props->transfer_target = dial_transfer(bridge_channel->chan, destination);
3296         if (!props->transfer_target) {
3297                 ast_log(LOG_ERROR, "Unable to request outbound channel for attended transfer target.\n");
3298                 ast_stream_and_wait(props->transferer, props->failsound, AST_DIGIT_NONE);
3299                 ast_bridge_channel_write_unhold(bridge_channel);
3300                 attended_transfer_properties_shutdown(props);
3301                 return 0;
3302         }
3303
3304
3305         /* Create a bridge to use to talk to the person we are calling */
3306         props->target_bridge = ast_bridge_basic_new();
3307         if (!props->target_bridge) {
3308                 ast_log(LOG_ERROR, "Unable to create bridge for attended transfer target.\n");
3309                 ast_stream_and_wait(props->transferer, props->failsound, AST_DIGIT_NONE);
3310                 ast_bridge_channel_write_unhold(bridge_channel);
3311                 ast_hangup(props->transfer_target);
3312                 props->transfer_target = NULL;
3313                 attended_transfer_properties_shutdown(props);
3314                 return 0;
3315         }
3316         ast_bridge_merge_inhibit(props->target_bridge, +1);
3317
3318         if (attach_framehook(props, props->transfer_target)) {
3319                 ast_log(LOG_ERROR, "Unable to attach framehook to transfer target.\n");</