bridge: avoid leaking channel during blond 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_FILE_VERSION(__FILE__, "$Revision$")
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/features.h"
49 #include "asterisk/format_cache.h"
50 #include "asterisk/test.h"
51
52 #define NORMAL_FLAGS    (AST_BRIDGE_FLAG_DISSOLVE_HANGUP | AST_BRIDGE_FLAG_DISSOLVE_EMPTY \
53                         | AST_BRIDGE_FLAG_SMART)
54
55 #define TRANSFER_FLAGS AST_BRIDGE_FLAG_SMART
56
57 struct attended_transfer_properties;
58
59 enum bridge_basic_personality_type {
60         /*! Index for "normal" basic bridge personality */
61         BRIDGE_BASIC_PERSONALITY_NORMAL,
62         /*! Index for attended transfer basic bridge personality */
63         BRIDGE_BASIC_PERSONALITY_ATXFER,
64         /*! Indicates end of enum. Must always remain the last element */
65         BRIDGE_BASIC_PERSONALITY_END,
66 };
67
68 /*!
69  * \brief Change basic bridge personality
70  *
71  * Changing personalities allows for the bridge to remain in use but have
72  * properties such as its v_table and its flags change.
73  *
74  * \param bridge The bridge
75  * \param type The personality to change the bridge to
76  * \user_data Private data to attach to the personality.
77  */
78 static void bridge_basic_change_personality(struct ast_bridge *bridge,
79                 enum bridge_basic_personality_type type, void *user_data);
80
81 /* ------------------------------------------------------------------- */
82
83 static const struct ast_datastore_info dtmf_features_info = {
84         .type = "bridge-dtmf-features",
85         .destroy = ast_free_ptr,
86 };
87
88 /*!
89  * \internal
90  * \since 12.0.0
91  * \brief read a feature code character and set it on for the give feature_flags struct
92  *
93  * \param feature_flags flags being modifed
94  * \param feature feature code provided - should be an uppercase letter
95  *
96  * \retval 0 if the feature was set successfully
97  * \retval -1 failure because the requested feature code isn't handled by this function
98  */
99 static int set_feature_flag_from_char(struct ast_flags *feature_flags, char feature)
100 {
101         switch (feature) {
102         case 'T':
103                 ast_set_flag(feature_flags, AST_FEATURE_REDIRECT);
104                 return 0;
105         case 'K':
106                 ast_set_flag(feature_flags, AST_FEATURE_PARKCALL);
107                 return 0;
108         case 'H':
109                 ast_set_flag(feature_flags, AST_FEATURE_DISCONNECT);
110                 return 0;
111         case 'W':
112                 ast_set_flag(feature_flags, AST_FEATURE_AUTOMON);
113                 return 0;
114         case 'X':
115                 ast_set_flag(feature_flags, AST_FEATURE_AUTOMIXMON);
116                 return 0;
117         default:
118                 return -1;
119         }
120 }
121
122 /*!
123  * \internal
124  * \since 12.0.0
125  * \brief Write a features string to a string buffer based on the feature flags provided
126  *
127  * \param feature_flags pointer to the feature flags to write from.
128  * \param buffer pointer to a string buffer to write the features
129  * \param buffer_size size of the buffer provided (should be able to fit all feature codes)
130  *
131  * \retval 0 on successful write
132  * \retval -1 failure due to running out of buffer space
133  */
134 static int dtmf_features_flags_to_string(struct ast_flags *feature_flags, char *buffer, size_t buffer_size)
135 {
136         size_t buffer_expended = 0;
137         unsigned int cur_feature;
138         static const struct {
139                 char letter;
140                 unsigned int flag;
141         } associations[] = {
142                 { 'T', AST_FEATURE_REDIRECT },
143                 { 'K', AST_FEATURE_PARKCALL },
144                 { 'H', AST_FEATURE_DISCONNECT },
145                 { 'W', AST_FEATURE_AUTOMON },
146                 { 'X', AST_FEATURE_AUTOMIXMON },
147         };
148
149         for (cur_feature = 0; cur_feature < ARRAY_LEN(associations); cur_feature++) {
150                 if (ast_test_flag(feature_flags, associations[cur_feature].flag)) {
151                         if (buffer_expended == buffer_size - 1) {
152                                 buffer[buffer_expended] = '\0';
153                                 return -1;
154                         }
155                         buffer[buffer_expended++] = associations[cur_feature].letter;
156                 }
157         }
158
159         buffer[buffer_expended] = '\0';
160         return 0;
161 }
162
163 static int build_dtmf_features(struct ast_flags *flags, const char *features)
164 {
165         const char *feature;
166
167         char missing_features[strlen(features) + 1];
168         size_t number_of_missing_features = 0;
169
170         for (feature = features; *feature; feature++) {
171                 if (!isupper(*feature)) {
172                         ast_log(LOG_ERROR, "Features string '%s' rejected because it contains non-uppercase feature.\n", features);
173                         return -1;
174                 }
175
176                 if (set_feature_flag_from_char(flags, *feature)) {
177                         missing_features[number_of_missing_features++] = *feature;
178                 }
179         }
180
181         missing_features[number_of_missing_features] = '\0';
182
183         if (number_of_missing_features) {
184                 ast_log(LOG_WARNING, "Features '%s' from features string '%s' can not be applied.\n", missing_features, features);
185         }
186
187         return 0;
188 }
189
190 int ast_bridge_features_ds_set_string(struct ast_channel *chan, const char *features)
191 {
192         struct ast_flags flags = {0};
193
194         if (build_dtmf_features(&flags, features)) {
195                 return -1;
196         }
197
198         ast_channel_lock(chan);
199         if (ast_bridge_features_ds_set(chan, &flags)) {
200                 ast_channel_unlock(chan);
201                 ast_log(LOG_ERROR, "Failed to apply features datastore for '%s' to channel '%s'\n", features, ast_channel_name(chan));
202                 return -1;
203         }
204         ast_channel_unlock(chan);
205
206         return 0;
207 }
208
209 int ast_bridge_features_ds_get_string(struct ast_channel *chan, char *buffer, size_t buf_size)
210 {
211         struct ast_flags *channel_flags;
212         struct ast_flags held_copy;
213
214         ast_channel_lock(chan);
215         if (!(channel_flags = ast_bridge_features_ds_get(chan))) {
216                 ast_channel_unlock(chan);
217                 return -1;
218         }
219         held_copy = *channel_flags;
220         ast_channel_unlock(chan);
221
222         return dtmf_features_flags_to_string(&held_copy, buffer, buf_size);
223 }
224
225 static int bridge_features_ds_set_full(struct ast_channel *chan, struct ast_flags *flags, int replace)
226 {
227         struct ast_datastore *datastore;
228         struct ast_flags *ds_flags;
229
230         datastore = ast_channel_datastore_find(chan, &dtmf_features_info, NULL);
231         if (datastore) {
232                 ds_flags = datastore->data;
233                 if (replace) {
234                         *ds_flags = *flags;
235                 } else {
236                         flags->flags = flags->flags | ds_flags->flags;
237                         *ds_flags = *flags;
238                 }
239                 return 0;
240         }
241
242         datastore = ast_datastore_alloc(&dtmf_features_info, NULL);
243         if (!datastore) {
244                 return -1;
245         }
246
247         ds_flags = ast_malloc(sizeof(*ds_flags));
248         if (!ds_flags) {
249                 ast_datastore_free(datastore);
250                 return -1;
251         }
252
253         *ds_flags = *flags;
254         datastore->data = ds_flags;
255         ast_channel_datastore_add(chan, datastore);
256         return 0;
257 }
258
259 int ast_bridge_features_ds_set(struct ast_channel *chan, struct ast_flags *flags)
260 {
261         return bridge_features_ds_set_full(chan, flags, 1);
262 }
263
264 int ast_bridge_features_ds_append(struct ast_channel *chan, struct ast_flags *flags)
265 {
266         return bridge_features_ds_set_full(chan, flags, 0);
267 }
268
269 struct ast_flags *ast_bridge_features_ds_get(struct ast_channel *chan)
270 {
271         struct ast_datastore *datastore;
272
273         datastore = ast_channel_datastore_find(chan, &dtmf_features_info, NULL);
274         if (!datastore) {
275                 return NULL;
276         }
277         return datastore->data;
278 }
279
280 /*!
281  * \internal
282  * \brief Determine if we should dissolve the bridge from a hangup.
283  * \since 12.0.0
284  *
285  * \param bridge_channel Channel executing the feature
286  * \param hook_pvt Private data passed in when the hook was created
287  *
288  * \retval 0 Keep the callback hook.
289  * \retval -1 Remove the callback hook.
290  */
291 static int basic_hangup_hook(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
292 {
293         int bridge_count = 0;
294         struct ast_bridge_channel *iter;
295
296         ast_bridge_channel_lock_bridge(bridge_channel);
297         AST_LIST_TRAVERSE(&bridge_channel->bridge->channels, iter, entry) {
298                 if (iter != bridge_channel && iter->state == BRIDGE_CHANNEL_STATE_WAIT) {
299                         ++bridge_count;
300                 }
301         }
302         if (2 <= bridge_count) {
303                 /* Just allow this channel to leave the multi-party bridge. */
304                 ast_bridge_channel_leave_bridge(bridge_channel,
305                         BRIDGE_CHANNEL_STATE_END_NO_DISSOLVE, 0);
306         }
307         ast_bridge_unlock(bridge_channel->bridge);
308         return 0;
309 }
310
311 /*!
312  * \brief Details for specific basic bridge personalities
313  */
314 struct personality_details {
315         /*! The v_table to use for this personality */
316         struct ast_bridge_methods *v_table;
317         /*! Flags to set on this type of bridge */
318         unsigned int bridge_flags;
319         /*! User data for this personality. If used, must be an ao2 object */
320         void *pvt;
321         /*! Callback to be called when changing to the personality */
322         void (*on_personality_change)(struct ast_bridge *bridge);
323 };
324
325 /*!
326  * \brief structure that organizes different personalities for basic bridges.
327  */
328 struct bridge_basic_personality {
329         /*! The current bridge personality in use */
330         enum bridge_basic_personality_type current;
331         /*! Array of details for the types of bridge personalities supported */
332         struct personality_details details[BRIDGE_BASIC_PERSONALITY_END];
333 };
334
335 /*
336  * \internal
337  * \brief Get the extension for a given builtin feature.
338  *
339  * \param chan Get the feature extension for this channel.
340  * \param feature_name features.conf name of feature.
341  * \param buf Where to put the extension.
342  * \param len Length of the given extension buffer.
343  *
344  * \retval 0 success
345  * \retval non-zero failiure
346  */
347 static int builtin_feature_get_exten(struct ast_channel *chan, const char *feature_name, char *buf, size_t len)
348 {
349         SCOPED_CHANNELLOCK(lock, chan);
350
351         return ast_get_builtin_feature(chan, feature_name, buf, len);
352 }
353
354 /*!
355  * \internal
356  * \brief Helper to add a builtin DTMF feature hook to the features struct.
357  * \since 12.0.0
358  *
359  * \param features Bridge features to setup.
360  * \param chan Get features from this channel.
361  * \param flags Feature flags on the channel.
362  * \param feature_flag Feature flag to test.
363  * \param feature_name features.conf name of feature.
364  * \param feature_bridge Bridge feature enum to get hook callback.
365  *
366  * \retval 0 on success.
367  * \retval -1 on error.
368  */
369 static int builtin_features_helper(struct ast_bridge_features *features, struct ast_channel *chan,
370         struct ast_flags *flags, unsigned int feature_flag, const char *feature_name, enum ast_bridge_builtin_feature feature_bridge)
371 {
372         char dtmf[AST_FEATURE_MAX_LEN];
373         int res;
374
375         res = 0;
376         if (ast_test_flag(flags, feature_flag)
377                 && !builtin_feature_get_exten(chan, feature_name, dtmf, sizeof(dtmf))
378                 && !ast_strlen_zero(dtmf)) {
379                 res = ast_bridge_features_enable(features, feature_bridge, dtmf, NULL, NULL,
380                         AST_BRIDGE_HOOK_REMOVE_ON_PULL | AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE);
381                 if (res) {
382                         ast_log(LOG_ERROR, "Channel %s: Requested DTMF feature %s not available.\n",
383                                 ast_channel_name(chan), feature_name);
384                 }
385         }
386
387         return res;
388 }
389
390 /*!
391  * \internal
392  * \brief Setup bridge builtin features.
393  * \since 12.0.0
394  *
395  * \param features Bridge features to setup.
396  * \param chan Get features from this channel.
397  *
398  * \retval 0 on success.
399  * \retval -1 on error.
400  */
401 static int setup_bridge_features_builtin(struct ast_bridge_features *features, struct ast_channel *chan)
402 {
403         struct ast_flags *flags;
404         int res;
405
406         ast_channel_lock(chan);
407         flags = ast_bridge_features_ds_get(chan);
408         ast_channel_unlock(chan);
409         if (!flags) {
410                 return 0;
411         }
412
413         res = 0;
414         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_REDIRECT, "blindxfer", AST_BRIDGE_BUILTIN_BLINDTRANSFER);
415         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_REDIRECT, "atxfer", AST_BRIDGE_BUILTIN_ATTENDEDTRANSFER);
416         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_DISCONNECT, "disconnect", AST_BRIDGE_BUILTIN_HANGUP);
417         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_PARKCALL, "parkcall", AST_BRIDGE_BUILTIN_PARKCALL);
418         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_AUTOMON, "automon", AST_BRIDGE_BUILTIN_AUTOMON);
419         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_AUTOMIXMON, "automixmon", AST_BRIDGE_BUILTIN_AUTOMIXMON);
420
421         return res ? -1 : 0;
422 }
423
424 struct dynamic_dtmf_hook_run {
425         /*! Offset into app_name[] where the channel name that activated the hook starts. */
426         int activated_offset;
427         /*! Offset into app_name[] where the dynamic feature name starts. */
428         int feature_offset;
429         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
430         int moh_offset;
431         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
432         int app_args_offset;
433         /*! Application name to run. */
434         char app_name[0];
435 };
436
437 static void dynamic_dtmf_hook_callback(struct ast_bridge_channel *bridge_channel,
438         const void *payload, size_t payload_size)
439 {
440         struct ast_channel *chan = bridge_channel->chan;
441         const struct dynamic_dtmf_hook_run *run_data = payload;
442
443         pbx_builtin_setvar_helper(chan, "DYNAMIC_FEATURENAME",
444                 &run_data->app_name[run_data->feature_offset]);
445         pbx_builtin_setvar_helper(chan, "DYNAMIC_WHO_ACTIVATED",
446                 &run_data->app_name[run_data->activated_offset]);
447
448         ast_bridge_channel_run_app(bridge_channel, run_data->app_name,
449                 run_data->app_args_offset ? &run_data->app_name[run_data->app_args_offset] : NULL,
450                 run_data->moh_offset ? &run_data->app_name[run_data->moh_offset] : NULL);
451 }
452
453 struct dynamic_dtmf_hook_data {
454         /*! Which side of bridge to run app (AST_FEATURE_FLAG_ONSELF/AST_FEATURE_FLAG_ONPEER) */
455         unsigned int flags;
456         /*! Offset into app_name[] where the dynamic feature name starts. */
457         int feature_offset;
458         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
459         int moh_offset;
460         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
461         int app_args_offset;
462         /*! Application name to run. */
463         char app_name[0];
464 };
465
466 /*!
467  * \internal
468  * \brief Activated dynamic DTMF feature hook.
469  * \since 12.0.0
470  *
471  * \param bridge_channel Channel executing the feature
472  * \param hook_pvt Private data passed in when the hook was created
473  *
474  * \retval 0 Keep the callback hook.
475  * \retval -1 Remove the callback hook.
476  */
477 static int dynamic_dtmf_hook_trip(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
478 {
479         struct dynamic_dtmf_hook_data *pvt = hook_pvt;
480         struct dynamic_dtmf_hook_run *run_data;
481         const char *activated_name;
482         size_t len_name;
483         size_t len_args;
484         size_t len_moh;
485         size_t len_feature;
486         size_t len_activated;
487         size_t len_data;
488
489         /* Determine lengths of things. */
490         len_name = strlen(pvt->app_name) + 1;
491         len_args = pvt->app_args_offset ? strlen(&pvt->app_name[pvt->app_args_offset]) + 1 : 0;
492         len_moh = pvt->moh_offset ? strlen(&pvt->app_name[pvt->moh_offset]) + 1 : 0;
493         len_feature = strlen(&pvt->app_name[pvt->feature_offset]) + 1;
494         ast_channel_lock(bridge_channel->chan);
495         activated_name = ast_strdupa(ast_channel_name(bridge_channel->chan));
496         ast_channel_unlock(bridge_channel->chan);
497         len_activated = strlen(activated_name) + 1;
498         len_data = sizeof(*run_data) + len_name + len_args + len_moh + len_feature + len_activated;
499
500         /* Fill in dynamic feature run hook data. */
501         run_data = ast_alloca(len_data);
502         run_data->app_args_offset = len_args ? len_name : 0;
503         run_data->moh_offset = len_moh ? len_name + len_args : 0;
504         run_data->feature_offset = len_name + len_args + len_moh;
505         run_data->activated_offset = len_name + len_args + len_moh + len_feature;
506         strcpy(run_data->app_name, pvt->app_name);/* Safe */
507         if (len_args) {
508                 strcpy(&run_data->app_name[run_data->app_args_offset],
509                         &pvt->app_name[pvt->app_args_offset]);/* Safe */
510         }
511         if (len_moh) {
512                 strcpy(&run_data->app_name[run_data->moh_offset],
513                         &pvt->app_name[pvt->moh_offset]);/* Safe */
514         }
515         strcpy(&run_data->app_name[run_data->feature_offset],
516                 &pvt->app_name[pvt->feature_offset]);/* Safe */
517         strcpy(&run_data->app_name[run_data->activated_offset], activated_name);/* Safe */
518
519         if (ast_test_flag(pvt, AST_FEATURE_FLAG_ONPEER)) {
520                 ast_bridge_channel_write_callback(bridge_channel,
521                         AST_BRIDGE_CHANNEL_CB_OPTION_MEDIA,
522                         dynamic_dtmf_hook_callback, run_data, len_data);
523         } else {
524                 dynamic_dtmf_hook_callback(bridge_channel, run_data, len_data);
525         }
526         return 0;
527 }
528
529 /*!
530  * \internal
531  * \brief Add a dynamic DTMF feature hook to the bridge features.
532  * \since 12.0.0
533  *
534  * \param features Bridge features to setup.
535  * \param flags Which side of bridge to run app (AST_FEATURE_FLAG_ONSELF/AST_FEATURE_FLAG_ONPEER).
536  * \param dtmf DTMF trigger sequence.
537  * \param feature_name Name of the dynamic feature.
538  * \param app_name Dialplan application name to run.
539  * \param app_args Dialplan application arguments. (Empty or NULL if no arguments)
540  * \param moh_class MOH class to play to peer. (Empty or NULL if no MOH played)
541  *
542  * \retval 0 on success.
543  * \retval -1 on error.
544  */
545 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)
546 {
547         struct dynamic_dtmf_hook_data *hook_data;
548         size_t len_name = strlen(app_name) + 1;
549         size_t len_args = ast_strlen_zero(app_args) ? 0 : strlen(app_args) + 1;
550         size_t len_moh = ast_strlen_zero(moh_class) ? 0 : strlen(moh_class) + 1;
551         size_t len_feature = strlen(feature_name) + 1;
552         size_t len_data = sizeof(*hook_data) + len_name + len_args + len_moh + len_feature;
553         int res;
554
555         /* Fill in application run hook data. */
556         hook_data = ast_malloc(len_data);
557         if (!hook_data) {
558                 return -1;
559         }
560         hook_data->flags = flags;
561         hook_data->app_args_offset = len_args ? len_name : 0;
562         hook_data->moh_offset = len_moh ? len_name + len_args : 0;
563         hook_data->feature_offset = len_name + len_args + len_moh;
564         strcpy(hook_data->app_name, app_name);/* Safe */
565         if (len_args) {
566                 strcpy(&hook_data->app_name[hook_data->app_args_offset], app_args);/* Safe */
567         }
568         if (len_moh) {
569                 strcpy(&hook_data->app_name[hook_data->moh_offset], moh_class);/* Safe */
570         }
571         strcpy(&hook_data->app_name[hook_data->feature_offset], feature_name);/* Safe */
572
573         res = ast_bridge_dtmf_hook(features, dtmf, dynamic_dtmf_hook_trip, hook_data,
574                 ast_free_ptr,
575                 AST_BRIDGE_HOOK_REMOVE_ON_PULL | AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE);
576         if (res) {
577                 ast_free(hook_data);
578         }
579         return res;
580 }
581
582 static int setup_dynamic_feature(void *obj, void *arg, void *data, int flags)
583 {
584         struct ast_applicationmap_item *item = obj;
585         struct ast_bridge_features *features = arg;
586         int *res = data;
587
588         *res |= dynamic_dtmf_hook_add(features,
589                 item->activate_on_self ? AST_FEATURE_FLAG_ONSELF : AST_FEATURE_FLAG_ONPEER,
590                 item->dtmf, item->name, item->app, item->app_data, item->moh_class);
591
592         return 0;
593 }
594
595 /*!
596  * \internal
597  * \brief Setup bridge dynamic features.
598  * \since 12.0.0
599  *
600  * \param features Bridge features to setup.
601  * \param chan Get features from this channel.
602  *
603  * \retval 0 on success.
604  * \retval -1 on error.
605  */
606 static int setup_bridge_features_dynamic(struct ast_bridge_features *features, struct ast_channel *chan)
607 {
608         RAII_VAR(struct ao2_container *, applicationmap, NULL, ao2_cleanup);
609         int res = 0;
610
611         ast_channel_lock(chan);
612         applicationmap = ast_get_chan_applicationmap(chan);
613         ast_channel_unlock(chan);
614         if (!applicationmap) {
615                 return 0;
616         }
617
618         ao2_callback_data(applicationmap, 0, setup_dynamic_feature, features, &res);
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
1325          */
1326         struct ast_channel *recall_target;
1327         /*! The absolute starting time for running timers */
1328         struct timeval start;
1329         AST_LIST_HEAD_NOLOCK(,stimulus_list) stimulus_queue;
1330         /*! The current state of the attended transfer */
1331         enum attended_transfer_state state;
1332         /*! The current superstate of the attended transfer */
1333         enum attended_transfer_superstate superstate;
1334         /*! Configured atxferdropcall from features.conf */
1335         int atxferdropcall;
1336         /*! Configured atxfercallbackretries from features.conf */
1337         int atxfercallbackretries;
1338         /*! Configured atxferloopdelay from features.conf */
1339         int atxferloopdelay;
1340         /*! Configured atxfernoanswertimeout from features.conf */
1341         int atxfernoanswertimeout;
1342         /*! Count of the number of times that recalls have been attempted */
1343         int retry_attempts;
1344         /*! Framehook ID for outbounc call to transfer target or recall target */
1345         int target_framehook_id;
1346         /*! Dial structure used when recalling transferer channel */
1347         struct ast_dial *dial;
1348         /*! The bridging features the transferer has available */
1349         struct ast_flags transferer_features;
1350 };
1351
1352 static void attended_transfer_properties_destructor(void *obj)
1353 {
1354         struct attended_transfer_properties *props = obj;
1355
1356         ast_debug(1, "Destroy attended transfer properties %p\n", props);
1357
1358         ao2_cleanup(props->target_bridge);
1359         ao2_cleanup(props->transferee_bridge);
1360         /* Use ast_channel_cleanup() instead of ast_channel_unref() for channels since they may be NULL */
1361         ast_channel_cleanup(props->transferer);
1362         ast_channel_cleanup(props->transfer_target);
1363         ast_channel_cleanup(props->recall_target);
1364         ast_string_field_free_memory(props);
1365         ast_cond_destroy(&props->cond);
1366 }
1367
1368 /*!
1369  * \internal
1370  * \brief Determine the transfer context to use.
1371  * \since 12.0.0
1372  *
1373  * \param transferer Channel initiating the transfer.
1374  * \param context User supplied context if available.  May be NULL.
1375  *
1376  * \return The context to use for the transfer.
1377  */
1378 static const char *get_transfer_context(struct ast_channel *transferer, const char *context)
1379 {
1380         if (!ast_strlen_zero(context)) {
1381                 return context;
1382         }
1383         context = pbx_builtin_getvar_helper(transferer, "TRANSFER_CONTEXT");
1384         if (!ast_strlen_zero(context)) {
1385                 return context;
1386         }
1387         context = ast_channel_macrocontext(transferer);
1388         if (!ast_strlen_zero(context)) {
1389                 return context;
1390         }
1391         context = ast_channel_context(transferer);
1392         if (!ast_strlen_zero(context)) {
1393                 return context;
1394         }
1395         return "default";
1396 }
1397
1398 /*!
1399  * \brief Allocate and initialize attended transfer properties
1400  *
1401  * \param transferer The channel performing the attended transfer
1402  * \param context Suggestion for what context the transfer target extension can be found in
1403  *
1404  * \retval NULL Failure to allocate or initialize
1405  * \retval non-NULL Newly allocated properties
1406  */
1407 static struct attended_transfer_properties *attended_transfer_properties_alloc(
1408         struct ast_channel *transferer, const char *context)
1409 {
1410         struct attended_transfer_properties *props;
1411         char *tech;
1412         char *addr;
1413         char *serial;
1414         RAII_VAR(struct ast_features_xfer_config *, xfer_cfg, NULL, ao2_cleanup);
1415         struct ast_flags *transferer_features;
1416
1417         props = ao2_alloc(sizeof(*props), attended_transfer_properties_destructor);
1418         if (!props || ast_string_field_init(props, 64)) {
1419                 return NULL;
1420         }
1421
1422         ast_cond_init(&props->cond, NULL);
1423
1424         props->target_framehook_id = -1;
1425         props->transferer = ast_channel_ref(transferer);
1426
1427         ast_channel_lock(props->transferer);
1428         xfer_cfg = ast_get_chan_features_xfer_config(props->transferer);
1429         if (!xfer_cfg) {
1430                 ast_log(LOG_ERROR, "Unable to get transfer configuration from channel %s\n", ast_channel_name(props->transferer));
1431                 ao2_ref(props, -1);
1432                 return NULL;
1433         }
1434         transferer_features = ast_bridge_features_ds_get(props->transferer);
1435         if (transferer_features) {
1436                 props->transferer_features = *transferer_features;
1437         }
1438         props->atxferdropcall = xfer_cfg->atxferdropcall;
1439         props->atxfercallbackretries = xfer_cfg->atxfercallbackretries;
1440         props->atxfernoanswertimeout = xfer_cfg->atxfernoanswertimeout;
1441         props->atxferloopdelay = xfer_cfg->atxferloopdelay;
1442         ast_string_field_set(props, context, get_transfer_context(transferer, context));
1443         ast_string_field_set(props, failsound, xfer_cfg->xferfailsound);
1444         ast_string_field_set(props, xfersound, xfer_cfg->xfersound);
1445
1446         tech = ast_strdupa(ast_channel_name(props->transferer));
1447         addr = strchr(tech, '/');
1448         if (!addr) {
1449                 ast_log(LOG_ERROR, "Transferer channel name does not follow typical channel naming format (tech/address)\n");
1450                 ast_channel_unref(props->transferer);
1451                 return NULL;
1452         }
1453         *addr++ = '\0';
1454         serial = strrchr(addr, '-');
1455         if (serial) {
1456                 *serial = '\0';
1457         }
1458         ast_string_field_set(props, transferer_type, tech);
1459         ast_string_field_set(props, transferer_addr, addr);
1460
1461         ast_channel_unlock(props->transferer);
1462
1463         ast_debug(1, "Allocated attended transfer properties %p for transfer from %s\n",
1464                         props, ast_channel_name(props->transferer));
1465         return props;
1466 }
1467
1468 /*!
1469  * \brief Free backlog of stimuli in the queue
1470  */
1471 static void clear_stimulus_queue(struct attended_transfer_properties *props)
1472 {
1473         struct stimulus_list *list;
1474         SCOPED_AO2LOCK(lock, props);
1475
1476         while ((list = AST_LIST_REMOVE_HEAD(&props->stimulus_queue, next))) {
1477                 ast_free(list);
1478         }
1479 }
1480
1481 /*!
1482  * \brief Initiate shutdown of attended transfer properties
1483  *
1484  * Calling this indicates that the attended transfer properties are no longer needed
1485  * because the transfer operation has concluded.
1486  */
1487 static void attended_transfer_properties_shutdown(struct attended_transfer_properties *props)
1488 {
1489         ast_debug(1, "Shutting down attended transfer %p\n", props);
1490
1491         if (props->transferee_bridge) {
1492                 bridge_basic_change_personality(props->transferee_bridge,
1493                                 BRIDGE_BASIC_PERSONALITY_NORMAL, NULL);
1494                 ast_bridge_merge_inhibit(props->transferee_bridge, -1);
1495         }
1496
1497         if (props->target_bridge) {
1498                 ast_bridge_destroy(props->target_bridge, 0);
1499                 props->target_bridge = NULL;
1500         }
1501
1502         if (props->transferer) {
1503                 ast_channel_remove_bridge_role(props->transferer, AST_TRANSFERER_ROLE_NAME);
1504         }
1505
1506         clear_stimulus_queue(props);
1507
1508         ao2_cleanup(props);
1509 }
1510
1511 static void stimulate_attended_transfer(struct attended_transfer_properties *props,
1512                 enum attended_transfer_stimulus stimulus)
1513 {
1514         struct stimulus_list *list;
1515
1516         list = ast_calloc(1, sizeof(*list));
1517         if (!list) {
1518                 ast_log(LOG_ERROR, "Unable to push event to attended transfer queue. Expect transfer to fail\n");
1519                 return;
1520         }
1521
1522         list->stimulus = stimulus;
1523         ao2_lock(props);
1524         AST_LIST_INSERT_TAIL(&props->stimulus_queue, list, next);
1525         ast_cond_signal(&props->cond);
1526         ao2_unlock(props);
1527 }
1528
1529 /*!
1530  * \brief Get a desired transfer party for a bridge the transferer is not in.
1531  *
1532  * \param bridge The bridge to get the party from. May be NULL.
1533  * \param[out] party The lone channel in the bridge. Will be set NULL if bridge is NULL or multiple parties are present.
1534  */
1535 static void get_transfer_party_non_transferer_bridge(struct ast_bridge *bridge,
1536                 struct ast_channel **party)
1537 {
1538         if (bridge && bridge->num_channels == 1) {
1539                 *party = ast_channel_ref(AST_LIST_FIRST(&bridge->channels)->chan);
1540         } else {
1541                 *party = NULL;
1542         }
1543 }
1544
1545 /*!
1546  * \brief Get the transferee and transfer target when the transferer is in a bridge with
1547  * one of the desired parties.
1548  *
1549  * \param transferer_bridge The bridge the transferer is in
1550  * \param other_bridge The bridge the transferer is not in. May be NULL.
1551  * \param transferer The transferer party
1552  * \param[out] transferer_peer The party that is in the bridge with the transferer
1553  * \param[out] other_party The party that is in the other_bridge
1554  */
1555 static void get_transfer_parties_transferer_bridge(struct ast_bridge *transferer_bridge,
1556                 struct ast_bridge *other_bridge, struct ast_channel *transferer,
1557                 struct ast_channel **transferer_peer, struct ast_channel **other_party)
1558 {
1559         *transferer_peer = ast_bridge_peer(transferer_bridge, transferer);
1560         get_transfer_party_non_transferer_bridge(other_bridge, other_party);
1561 }
1562
1563 /*!
1564  * \brief determine transferee and transfer target for an attended transfer
1565  *
1566  * In builtin attended transfers, there is a single transferer channel that jumps between
1567  * the two bridges involved. At the time the attended transfer occurs, the transferer could
1568  * be in either bridge, so determining the parties is a bit more complex than normal.
1569  *
1570  * The method used here is to determine which of the two bridges the transferer is in, and
1571  * grabbing the peer from that bridge. The other bridge, if it only has a single channel in it,
1572  * has the other desired channel.
1573  *
1574  * \param transferer The channel performing the transfer
1575  * \param transferee_bridge The bridge that the transferee is in
1576  * \param target_bridge The bridge that the transfer target is in
1577  * \param[out] transferee The transferee channel
1578  * \param[out] transfer_target The transfer target channel
1579  */
1580 static void get_transfer_parties(struct ast_channel *transferer, struct ast_bridge *transferee_bridge,
1581                 struct ast_bridge *target_bridge, struct ast_channel **transferee,
1582                 struct ast_channel **transfer_target)
1583 {
1584         struct ast_bridge *transferer_bridge;
1585
1586         ast_channel_lock(transferer);
1587         transferer_bridge = ast_channel_get_bridge(transferer);
1588         ast_channel_unlock(transferer);
1589
1590         if (transferer_bridge == transferee_bridge) {
1591                 get_transfer_parties_transferer_bridge(transferee_bridge, target_bridge,
1592                                 transferer, transferee, transfer_target);
1593         } else if (transferer_bridge == target_bridge) {
1594                 get_transfer_parties_transferer_bridge(target_bridge, transferee_bridge,
1595                                 transferer, transfer_target, transferee);
1596         } else {
1597                 get_transfer_party_non_transferer_bridge(transferee_bridge, transferee);
1598                 get_transfer_party_non_transferer_bridge(target_bridge, transfer_target);
1599         }
1600
1601         ao2_cleanup(transferer_bridge);
1602 }
1603
1604 /*!
1605  * \brief Send a stasis publication for a successful attended transfer
1606  */
1607 static void publish_transfer_success(struct attended_transfer_properties *props,
1608                 struct ast_channel *transferee_channel, struct ast_channel *target_channel)
1609 {
1610         struct ast_attended_transfer_message *transfer_msg;
1611
1612         transfer_msg = ast_attended_transfer_message_create(0, props->transferer,
1613                         props->transferee_bridge, props->transferer, props->target_bridge,
1614                         transferee_channel, target_channel);
1615
1616         if (!transfer_msg) {
1617                 ast_log(LOG_ERROR, "Unable to publish successful attended transfer from %s\n",
1618                                 ast_channel_name(props->transferer));
1619                 return;
1620         }
1621
1622         ast_attended_transfer_message_add_merge(transfer_msg, props->transferee_bridge);
1623         ast_bridge_publish_attended_transfer(transfer_msg);
1624         ao2_cleanup(transfer_msg);
1625 }
1626
1627 /*!
1628  * \brief Send a stasis publication for an attended transfer that ends in a threeway call
1629  */
1630 static void publish_transfer_threeway(struct attended_transfer_properties *props,
1631                 struct ast_channel *transferee_channel, struct ast_channel *target_channel)
1632 {
1633         struct ast_attended_transfer_message *transfer_msg;
1634
1635         transfer_msg = ast_attended_transfer_message_create(0, props->transferer,
1636                         props->transferee_bridge, props->transferer, props->target_bridge,
1637                         transferee_channel, target_channel);
1638
1639         if (!transfer_msg) {
1640                 ast_log(LOG_ERROR, "Unable to publish successful three-way transfer from %s\n",
1641                                 ast_channel_name(props->transferer));
1642                 return;
1643         }
1644
1645         ast_attended_transfer_message_add_threeway(transfer_msg, props->transferer,
1646                         props->transferee_bridge);
1647         ast_bridge_publish_attended_transfer(transfer_msg);
1648         ao2_cleanup(transfer_msg);
1649 }
1650
1651 /*!
1652  * \brief Send a stasis publication for a failed attended transfer
1653  */
1654 static void publish_transfer_fail(struct attended_transfer_properties *props)
1655 {
1656         struct ast_attended_transfer_message *transfer_msg;
1657
1658         transfer_msg = ast_attended_transfer_message_create(0, props->transferer,
1659                         props->transferee_bridge, props->transferer, props->target_bridge,
1660                         NULL, NULL);
1661
1662         if (!transfer_msg) {
1663                 ast_log(LOG_ERROR, "Unable to publish failed transfer from %s\n",
1664                                 ast_channel_name(props->transferer));
1665                 return;
1666         }
1667
1668         transfer_msg->result = AST_BRIDGE_TRANSFER_FAIL;
1669         ast_bridge_publish_attended_transfer(transfer_msg);
1670         ao2_cleanup(transfer_msg);
1671 }
1672
1673 /*!
1674  * \brief Helper method to play a sound on a channel in a bridge
1675  *
1676  * \param chan The channel to play the sound to
1677  * \param sound The sound to play
1678  */
1679 static void play_sound(struct ast_channel *chan, const char *sound)
1680 {
1681         RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
1682
1683         ast_channel_lock(chan);
1684         bridge_channel = ast_channel_get_bridge_channel(chan);
1685         ast_channel_unlock(chan);
1686
1687         if (!bridge_channel) {
1688                 return;
1689         }
1690
1691         ast_bridge_channel_queue_playfile(bridge_channel, NULL, sound, NULL);
1692 }
1693
1694 /*!
1695  * \brief Helper method to place a channel in a bridge on hold
1696  */
1697 static void hold(struct ast_channel *chan)
1698 {
1699         RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
1700
1701         if (chan) {
1702                 ast_channel_lock(chan);
1703                 bridge_channel = ast_channel_get_bridge_channel(chan);
1704                 ast_channel_unlock(chan);
1705
1706                 ast_assert(bridge_channel != NULL);
1707
1708                 ast_bridge_channel_write_hold(bridge_channel, NULL);
1709         }
1710 }
1711
1712 /*!
1713  * \brief Helper method to take a channel in a bridge off hold
1714  */
1715 static void unhold(struct ast_channel *chan)
1716 {
1717         RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
1718
1719         ast_channel_lock(chan);
1720         bridge_channel = ast_channel_get_bridge_channel(chan);
1721         ast_channel_unlock(chan);
1722
1723         ast_assert(bridge_channel != NULL);
1724
1725         ast_bridge_channel_write_unhold(bridge_channel);
1726 }
1727
1728 /*!
1729  * \brief Helper method to send a ringing indication to a channel in a bridge
1730  */
1731 static void ringing(struct ast_channel *chan)
1732 {
1733         RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
1734
1735         ast_channel_lock(chan);
1736         bridge_channel = ast_channel_get_bridge_channel(chan);
1737         ast_channel_unlock(chan);
1738
1739         ast_assert(bridge_channel != NULL);
1740
1741         ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_RINGING, NULL, 0);
1742 }
1743
1744 /*!
1745  * \brief Helper method to send a ringing indication to all channels in a bridge
1746  */
1747 static void bridge_ringing(struct ast_bridge *bridge)
1748 {
1749         struct ast_frame ringing = {
1750                 .frametype = AST_FRAME_CONTROL,
1751                 .subclass.integer = AST_CONTROL_RINGING,
1752         };
1753
1754         ast_bridge_queue_everyone_else(bridge, NULL, &ringing);
1755 }
1756
1757 /*!
1758  * \brief Helper method to send a hold frame to all channels in a bridge
1759  */
1760 static void bridge_hold(struct ast_bridge *bridge)
1761 {
1762         struct ast_frame hold = {
1763                 .frametype = AST_FRAME_CONTROL,
1764                 .subclass.integer = AST_CONTROL_HOLD,
1765         };
1766
1767         ast_bridge_queue_everyone_else(bridge, NULL, &hold);
1768 }
1769
1770 /*!
1771  * \brief Helper method to send an unhold frame to all channels in a bridge
1772  */
1773 static void bridge_unhold(struct ast_bridge *bridge)
1774 {
1775         struct ast_frame unhold = {
1776                 .frametype = AST_FRAME_CONTROL,
1777                 .subclass.integer = AST_CONTROL_UNHOLD,
1778         };
1779
1780         ast_bridge_queue_everyone_else(bridge, NULL, &unhold);
1781 }
1782
1783 /*!
1784  * \brief Wrapper for \ref bridge_do_move
1785  */
1786 static int bridge_move(struct ast_bridge *dest, struct ast_bridge *src, struct ast_channel *channel, struct ast_channel *swap)
1787 {
1788         int res;
1789         RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
1790
1791         ast_bridge_lock_both(src, dest);
1792
1793         ast_channel_lock(channel);
1794         bridge_channel = ast_channel_get_bridge_channel(channel);
1795         ast_channel_unlock(channel);
1796
1797         ast_assert(bridge_channel != NULL);
1798
1799         ao2_lock(bridge_channel);
1800         bridge_channel->swap = swap;
1801         ao2_unlock(bridge_channel);
1802
1803         res = bridge_do_move(dest, bridge_channel, 1, 0);
1804
1805         ast_bridge_unlock(dest);
1806         ast_bridge_unlock(src);
1807
1808         return res;
1809 }
1810
1811 /*!
1812  * \brief Wrapper for \ref bridge_do_merge
1813  */
1814 static void bridge_merge(struct ast_bridge *dest, struct ast_bridge *src, struct ast_channel **kick_channels, unsigned int num_channels)
1815 {
1816         struct ast_bridge_channel **kick_bridge_channels = num_channels ?
1817                 ast_alloca(num_channels * sizeof(*kick_bridge_channels)) : NULL;
1818         int i;
1819         int num_bridge_channels = 0;
1820
1821         ast_bridge_lock_both(dest, src);
1822
1823         for (i = 0; i < num_channels; ++i) {
1824                 struct ast_bridge_channel *kick_bridge_channel;
1825
1826                 kick_bridge_channel = bridge_find_channel(src, kick_channels[i]);
1827                 if (!kick_bridge_channel) {
1828                         kick_bridge_channel = bridge_find_channel(dest, kick_channels[i]);
1829                 }
1830
1831                 /* It's possible (and fine) for the bridge channel to be NULL at this point if the
1832                  * channel has hung up already. If that happens, we can just remove it from the list
1833                  * of bridge channels to kick from the bridge
1834                  */
1835                 if (!kick_bridge_channel) {
1836                         continue;
1837                 }
1838
1839                 kick_bridge_channels[num_bridge_channels++] = kick_bridge_channel;
1840         }
1841
1842         bridge_do_merge(dest, src, kick_bridge_channels, num_bridge_channels, 0);
1843         ast_bridge_unlock(dest);
1844         ast_bridge_unlock(src);
1845 }
1846
1847 /*!
1848  * \brief Flags that indicate properties of attended transfer states
1849  */
1850 enum attended_transfer_state_flags {
1851         /*! This state requires that the timer be reset when entering the state */
1852         TRANSFER_STATE_FLAG_TIMER_RESET = (1 << 0),
1853         /*! This state's timer uses atxferloopdelay */
1854         TRANSFER_STATE_FLAG_TIMER_LOOP_DELAY = (1 << 1),
1855         /*! This state's timer uses atxfernoanswertimeout */
1856         TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER = (1 << 2),
1857         /*! This state has a time limit associated with it */
1858         TRANSFER_STATE_FLAG_TIMED = (TRANSFER_STATE_FLAG_TIMER_RESET |
1859                         TRANSFER_STATE_FLAG_TIMER_LOOP_DELAY | TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER),
1860         /*! This state does not transition to any other states */
1861         TRANSFER_STATE_FLAG_TERMINAL = (1 << 3),
1862 };
1863
1864 static int calling_target_enter(struct attended_transfer_properties *props);
1865 static enum attended_transfer_state calling_target_exit(struct attended_transfer_properties *props,
1866                 enum attended_transfer_stimulus stimulus);
1867
1868 static int hesitant_enter(struct attended_transfer_properties *props);
1869 static enum attended_transfer_state hesitant_exit(struct attended_transfer_properties *props,
1870                 enum attended_transfer_stimulus stimulus);
1871
1872 static int rebridge_enter(struct attended_transfer_properties *props);
1873
1874 static int resume_enter(struct attended_transfer_properties *props);
1875
1876 static int threeway_enter(struct attended_transfer_properties *props);
1877
1878 static int consulting_enter(struct attended_transfer_properties *props);
1879 static enum attended_transfer_state consulting_exit(struct attended_transfer_properties *props,
1880                 enum attended_transfer_stimulus stimulus);
1881
1882 static int double_checking_enter(struct attended_transfer_properties *props);
1883 static enum attended_transfer_state double_checking_exit(struct attended_transfer_properties *props,
1884                 enum attended_transfer_stimulus stimulus);
1885
1886 static int complete_enter(struct attended_transfer_properties *props);
1887
1888 static int blond_enter(struct attended_transfer_properties *props);
1889
1890 static int blond_nonfinal_enter(struct attended_transfer_properties *props);
1891 static enum attended_transfer_state blond_nonfinal_exit(struct attended_transfer_properties *props,
1892                 enum attended_transfer_stimulus stimulus);
1893
1894 static int recalling_enter(struct attended_transfer_properties *props);
1895 static enum attended_transfer_state recalling_exit(struct attended_transfer_properties *props,
1896                 enum attended_transfer_stimulus stimulus);
1897
1898 static int wait_to_retransfer_enter(struct attended_transfer_properties *props);
1899 static enum attended_transfer_state wait_to_retransfer_exit(struct attended_transfer_properties *props,
1900                 enum attended_transfer_stimulus stimulus);
1901
1902 static int retransfer_enter(struct attended_transfer_properties *props);
1903 static enum attended_transfer_state retransfer_exit(struct attended_transfer_properties *props,
1904                 enum attended_transfer_stimulus stimulus);
1905
1906 static int wait_to_recall_enter(struct attended_transfer_properties *props);
1907 static enum attended_transfer_state wait_to_recall_exit(struct attended_transfer_properties *props,
1908                 enum attended_transfer_stimulus stimulus);
1909
1910 static int fail_enter(struct attended_transfer_properties *props);
1911
1912 /*!
1913  * \brief Properties of an attended transfer state
1914  */
1915 struct attended_transfer_state_properties {
1916         /*! The name of the state. Used for debugging */
1917         const char *state_name;
1918         /*! Function used to enter a state */
1919         int (*enter)(struct attended_transfer_properties *props);
1920         /*!
1921          * Function used to exit a state
1922          * This is used both to determine what the next state
1923          * to transition to will be and to perform any cleanup
1924          * necessary before exiting the current state.
1925          */
1926         enum attended_transfer_state (*exit)(struct attended_transfer_properties *props,
1927                         enum attended_transfer_stimulus stimulus);
1928         /*! Flags associated with this state */
1929         enum attended_transfer_state_flags flags;
1930 };
1931
1932 static const struct attended_transfer_state_properties state_properties[] = {
1933         [TRANSFER_CALLING_TARGET] = {
1934                 .state_name = "Calling Target",
1935                 .enter = calling_target_enter,
1936                 .exit = calling_target_exit,
1937                 .flags = TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER | TRANSFER_STATE_FLAG_TIMER_RESET,
1938         },
1939         [TRANSFER_HESITANT] = {
1940                 .state_name = "Hesitant",
1941                 .enter = hesitant_enter,
1942                 .exit = hesitant_exit,
1943                 .flags = TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER,
1944         },
1945         [TRANSFER_REBRIDGE] = {
1946                 .state_name = "Rebridge",
1947                 .enter = rebridge_enter,
1948                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
1949         },
1950         [TRANSFER_RESUME] = {
1951                 .state_name = "Resume",
1952                 .enter = resume_enter,
1953                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
1954         },
1955         [TRANSFER_THREEWAY] = {
1956                 .state_name = "Threeway",
1957                 .enter = threeway_enter,
1958                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
1959         },
1960         [TRANSFER_CONSULTING] = {
1961                 .state_name = "Consulting",
1962                 .enter = consulting_enter,
1963                 .exit = consulting_exit,
1964         },
1965         [TRANSFER_DOUBLECHECKING] = {
1966                 .state_name = "Double Checking",
1967                 .enter = double_checking_enter,
1968                 .exit = double_checking_exit,
1969         },
1970         [TRANSFER_COMPLETE] = {
1971                 .state_name = "Complete",
1972                 .enter = complete_enter,
1973                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
1974         },
1975         [TRANSFER_BLOND] = {
1976                 .state_name = "Blond",
1977                 .enter = blond_enter,
1978                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
1979         },
1980         [TRANSFER_BLOND_NONFINAL] = {
1981                 .state_name = "Blond Non-Final",
1982                 .enter = blond_nonfinal_enter,
1983                 .exit = blond_nonfinal_exit,
1984                 .flags = TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER,
1985         },
1986         [TRANSFER_RECALLING] = {
1987                 .state_name = "Recalling",
1988                 .enter = recalling_enter,
1989                 .exit = recalling_exit,
1990                 .flags = TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER | TRANSFER_STATE_FLAG_TIMER_RESET,
1991         },
1992         [TRANSFER_WAIT_TO_RETRANSFER] = {
1993                 .state_name = "Wait to Retransfer",
1994                 .enter = wait_to_retransfer_enter,
1995                 .exit = wait_to_retransfer_exit,
1996                 .flags = TRANSFER_STATE_FLAG_TIMER_RESET | TRANSFER_STATE_FLAG_TIMER_LOOP_DELAY,
1997         },
1998         [TRANSFER_RETRANSFER] = {
1999                 .state_name = "Retransfer",
2000                 .enter = retransfer_enter,
2001                 .exit = retransfer_exit,
2002                 .flags = TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER | TRANSFER_STATE_FLAG_TIMER_RESET,
2003         },
2004         [TRANSFER_WAIT_TO_RECALL] = {
2005                 .state_name = "Wait to Recall",
2006                 .enter = wait_to_recall_enter,
2007                 .exit = wait_to_recall_exit,
2008                 .flags = TRANSFER_STATE_FLAG_TIMER_RESET | TRANSFER_STATE_FLAG_TIMER_LOOP_DELAY,
2009         },
2010         [TRANSFER_FAIL] = {
2011                 .state_name = "Fail",
2012                 .enter = fail_enter,
2013                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
2014         },
2015 };
2016
2017 static int calling_target_enter(struct attended_transfer_properties *props)
2018 {
2019         return bridge_move(props->target_bridge, props->transferee_bridge, props->transferer, NULL);
2020 }
2021
2022 static enum attended_transfer_state calling_target_exit(struct attended_transfer_properties *props,
2023                 enum attended_transfer_stimulus stimulus)
2024 {
2025         switch (stimulus) {
2026         case STIMULUS_TRANSFEREE_HANGUP:
2027                 play_sound(props->transferer, props->failsound);
2028                 publish_transfer_fail(props);
2029                 return TRANSFER_FAIL;
2030         case STIMULUS_DTMF_ATXFER_COMPLETE:
2031         case STIMULUS_TRANSFERER_HANGUP:
2032                 bridge_unhold(props->transferee_bridge);
2033                 return props->atxferdropcall ? TRANSFER_BLOND : TRANSFER_BLOND_NONFINAL;
2034         case STIMULUS_TRANSFER_TARGET_ANSWER:
2035                 return TRANSFER_CONSULTING;
2036         case STIMULUS_TRANSFER_TARGET_HANGUP:
2037         case STIMULUS_TIMEOUT:
2038         case STIMULUS_DTMF_ATXFER_ABORT:
2039                 play_sound(props->transferer, props->failsound);
2040                 return TRANSFER_REBRIDGE;
2041         case STIMULUS_DTMF_ATXFER_THREEWAY:
2042                 bridge_unhold(props->transferee_bridge);
2043                 return TRANSFER_THREEWAY;
2044         case STIMULUS_DTMF_ATXFER_SWAP:
2045                 return TRANSFER_HESITANT;
2046         case STIMULUS_NONE:
2047         case STIMULUS_RECALL_TARGET_ANSWER:
2048         case STIMULUS_RECALL_TARGET_HANGUP:
2049         default:
2050                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2051                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2052                 return props->state;
2053         }
2054 }
2055
2056 static int hesitant_enter(struct attended_transfer_properties *props)
2057 {
2058         if (bridge_move(props->transferee_bridge, props->target_bridge, props->transferer, NULL)) {
2059                 return -1;
2060         }
2061
2062         unhold(props->transferer);
2063         return 0;
2064 }
2065
2066 static enum attended_transfer_state hesitant_exit(struct attended_transfer_properties *props,
2067                 enum attended_transfer_stimulus stimulus)
2068 {
2069         switch (stimulus) {
2070         case STIMULUS_TRANSFEREE_HANGUP:
2071                 play_sound(props->transferer, props->failsound);
2072                 publish_transfer_fail(props);
2073                 return TRANSFER_FAIL;
2074         case STIMULUS_DTMF_ATXFER_COMPLETE:
2075         case STIMULUS_TRANSFERER_HANGUP:
2076                 return props->atxferdropcall ? TRANSFER_BLOND : TRANSFER_BLOND_NONFINAL;
2077         case STIMULUS_TRANSFER_TARGET_ANSWER:
2078                 return TRANSFER_DOUBLECHECKING;
2079         case STIMULUS_TRANSFER_TARGET_HANGUP:
2080         case STIMULUS_TIMEOUT:
2081         case STIMULUS_DTMF_ATXFER_ABORT:
2082                 play_sound(props->transferer, props->failsound);
2083                 return TRANSFER_RESUME;
2084         case STIMULUS_DTMF_ATXFER_THREEWAY:
2085                 return TRANSFER_THREEWAY;
2086         case STIMULUS_DTMF_ATXFER_SWAP:
2087                 hold(props->transferer);
2088                 return TRANSFER_CALLING_TARGET;
2089         case STIMULUS_NONE:
2090         case STIMULUS_RECALL_TARGET_HANGUP:
2091         case STIMULUS_RECALL_TARGET_ANSWER:
2092         default:
2093                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2094                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2095                 return props->state;
2096         }
2097 }
2098
2099 static int rebridge_enter(struct attended_transfer_properties *props)
2100 {
2101         if (bridge_move(props->transferee_bridge, props->target_bridge,
2102                         props->transferer, NULL)) {
2103                 return -1;
2104         }
2105
2106         unhold(props->transferer);
2107         return 0;
2108 }
2109
2110 static int resume_enter(struct attended_transfer_properties *props)
2111 {
2112         return 0;
2113 }
2114
2115 static int threeway_enter(struct attended_transfer_properties *props)
2116 {
2117         struct ast_channel *transferee_channel;
2118         struct ast_channel *target_channel;
2119
2120         get_transfer_parties(props->transferer, props->transferee_bridge, props->target_bridge,
2121                         &transferee_channel, &target_channel);
2122         bridge_merge(props->transferee_bridge, props->target_bridge, NULL, 0);
2123         play_sound(props->transfer_target, props->xfersound);
2124         play_sound(props->transferer, props->xfersound);
2125         publish_transfer_threeway(props, transferee_channel, target_channel);
2126
2127         ast_channel_cleanup(transferee_channel);
2128         ast_channel_cleanup(target_channel);
2129         return 0;
2130 }
2131
2132 static int consulting_enter(struct attended_transfer_properties *props)
2133 {
2134         return 0;
2135 }
2136
2137 static enum attended_transfer_state consulting_exit(struct attended_transfer_properties *props,
2138                 enum attended_transfer_stimulus stimulus)
2139 {
2140         switch (stimulus) {
2141         case STIMULUS_TRANSFEREE_HANGUP:
2142                 /* This is a one-of-a-kind event. The transferer and transfer target are talking in
2143                  * one bridge, and the transferee has hung up in a separate bridge. In this case, we
2144                  * will change the personality of the transfer target bridge back to normal, and play
2145                  * a sound to the transferer to indicate the transferee is gone.
2146                  */
2147                 bridge_basic_change_personality(props->target_bridge, BRIDGE_BASIC_PERSONALITY_NORMAL, NULL);
2148                 play_sound(props->transferer, props->failsound);
2149                 ast_bridge_merge_inhibit(props->target_bridge, -1);
2150                 /* These next two lines are here to ensure that our reference to the target bridge
2151                  * is cleaned up properly and that the target bridge is not destroyed when the
2152                  * monitor thread exits
2153                  */
2154                 ao2_ref(props->target_bridge, -1);
2155                 props->target_bridge = NULL;
2156                 return TRANSFER_FAIL;
2157         case STIMULUS_TRANSFERER_HANGUP:
2158         case STIMULUS_DTMF_ATXFER_COMPLETE:
2159                 /* We know the transferer is in the target_bridge, so take the other bridge off hold */
2160                 bridge_unhold(props->transferee_bridge);
2161                 return TRANSFER_COMPLETE;
2162         case STIMULUS_TRANSFER_TARGET_HANGUP:
2163         case STIMULUS_DTMF_ATXFER_ABORT:
2164                 play_sound(props->transferer, props->failsound);
2165                 return TRANSFER_REBRIDGE;
2166         case STIMULUS_DTMF_ATXFER_THREEWAY:
2167                 bridge_unhold(props->transferee_bridge);
2168                 return TRANSFER_THREEWAY;
2169         case STIMULUS_DTMF_ATXFER_SWAP:
2170                 hold(props->transferer);
2171                 bridge_move(props->transferee_bridge, props->target_bridge, props->transferer, NULL);
2172                 unhold(props->transferer);
2173                 return TRANSFER_DOUBLECHECKING;
2174         case STIMULUS_NONE:
2175         case STIMULUS_TIMEOUT:
2176         case STIMULUS_TRANSFER_TARGET_ANSWER:
2177         case STIMULUS_RECALL_TARGET_HANGUP:
2178         case STIMULUS_RECALL_TARGET_ANSWER:
2179         default:
2180                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2181                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2182                 return props->state;
2183         }
2184 }
2185
2186 static int double_checking_enter(struct attended_transfer_properties *props)
2187 {
2188         return 0;
2189 }
2190
2191 static enum attended_transfer_state double_checking_exit(struct attended_transfer_properties *props,
2192                 enum attended_transfer_stimulus stimulus)
2193 {
2194         switch (stimulus) {
2195         case STIMULUS_TRANSFEREE_HANGUP:
2196                 play_sound(props->transferer, props->failsound);
2197                 publish_transfer_fail(props);
2198                 return TRANSFER_FAIL;
2199         case STIMULUS_TRANSFERER_HANGUP:
2200         case STIMULUS_DTMF_ATXFER_COMPLETE:
2201                 /* We know the transferer is in the transferee, so take the other bridge off hold */
2202                 bridge_unhold(props->target_bridge);
2203                 return TRANSFER_COMPLETE;
2204         case STIMULUS_TRANSFER_TARGET_HANGUP:
2205         case STIMULUS_DTMF_ATXFER_ABORT:
2206                 play_sound(props->transferer, props->failsound);
2207                 return TRANSFER_RESUME;
2208         case STIMULUS_DTMF_ATXFER_THREEWAY:
2209                 bridge_unhold(props->target_bridge);
2210                 return TRANSFER_THREEWAY;
2211         case STIMULUS_DTMF_ATXFER_SWAP:
2212                 hold(props->transferer);
2213                 bridge_move(props->target_bridge, props->transferee_bridge, props->transferer, NULL);
2214                 unhold(props->transferer);
2215                 return TRANSFER_CONSULTING;
2216         case STIMULUS_NONE:
2217         case STIMULUS_TIMEOUT:
2218         case STIMULUS_TRANSFER_TARGET_ANSWER:
2219         case STIMULUS_RECALL_TARGET_HANGUP:
2220         case STIMULUS_RECALL_TARGET_ANSWER:
2221         default:
2222                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2223                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2224                 return props->state;
2225         }
2226 }
2227
2228 static int complete_enter(struct attended_transfer_properties *props)
2229 {
2230         struct ast_channel *transferee_channel;
2231         struct ast_channel *target_channel;
2232
2233         get_transfer_parties(props->transferer, props->transferee_bridge, props->target_bridge,
2234                         &transferee_channel, &target_channel);
2235         bridge_merge(props->transferee_bridge, props->target_bridge, &props->transferer, 1);
2236         play_sound(props->transfer_target, props->xfersound);
2237         publish_transfer_success(props, transferee_channel, target_channel);
2238
2239         ast_channel_cleanup(transferee_channel);
2240         ast_channel_cleanup(target_channel);
2241         return 0;
2242 }
2243
2244 static int blond_enter(struct attended_transfer_properties *props)
2245 {
2246         struct ast_channel *transferee_channel;
2247         struct ast_channel *target_channel;
2248
2249         get_transfer_parties(props->transferer, props->transferee_bridge, props->target_bridge,
2250                         &transferee_channel, &target_channel);
2251         bridge_merge(props->transferee_bridge, props->target_bridge, &props->transferer, 1);
2252         ringing(props->transfer_target);
2253         publish_transfer_success(props, transferee_channel, target_channel);
2254
2255         ast_channel_cleanup(transferee_channel);
2256         ast_channel_cleanup(target_channel);
2257         return 0;
2258 }
2259
2260 static int blond_nonfinal_enter(struct attended_transfer_properties *props)
2261 {
2262         int res;
2263         props->superstate = SUPERSTATE_RECALL;
2264         props->recall_target = ast_channel_ref(props->transfer_target);
2265         res = blond_enter(props);
2266         /* transfer properties holds a separate reference to transfer_target, don't set it to NULL here */
2267         ast_channel_unref(props->transfer_target);
2268         return res;
2269 }
2270
2271 static enum attended_transfer_state blond_nonfinal_exit(struct attended_transfer_properties *props,
2272                 enum attended_transfer_stimulus stimulus)
2273 {
2274         switch (stimulus) {
2275         case STIMULUS_TRANSFEREE_HANGUP:
2276                 return TRANSFER_FAIL;
2277         case STIMULUS_RECALL_TARGET_ANSWER:
2278                 return TRANSFER_RESUME;
2279         case STIMULUS_TIMEOUT:
2280                 ast_softhangup(props->recall_target, AST_SOFTHANGUP_EXPLICIT);
2281                 props->recall_target = ast_channel_unref(props->recall_target);
2282         case STIMULUS_RECALL_TARGET_HANGUP:
2283                 return TRANSFER_RECALLING;
2284         case STIMULUS_NONE:
2285         case STIMULUS_DTMF_ATXFER_ABORT:
2286         case STIMULUS_DTMF_ATXFER_COMPLETE:
2287         case STIMULUS_DTMF_ATXFER_THREEWAY:
2288         case STIMULUS_DTMF_ATXFER_SWAP:
2289         case STIMULUS_TRANSFERER_HANGUP:
2290         case STIMULUS_TRANSFER_TARGET_HANGUP:
2291         case STIMULUS_TRANSFER_TARGET_ANSWER:
2292         default:
2293                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2294                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2295                 return props->state;
2296         }
2297 }
2298
2299 /*!
2300  * \brief Dial callback when attempting to recall the original transferer channel
2301  *
2302  * This is how we can monitor if the recall target has answered or has hung up.
2303  * If one of the two is detected, then an appropriate stimulus is sent to the
2304  * attended transfer monitor thread.
2305  */
2306 static void recall_callback(struct ast_dial *dial)
2307 {
2308         struct attended_transfer_properties *props = ast_dial_get_user_data(dial);
2309
2310         switch (ast_dial_state(dial)) {
2311         default:
2312         case AST_DIAL_RESULT_INVALID:
2313         case AST_DIAL_RESULT_FAILED:
2314         case AST_DIAL_RESULT_TIMEOUT:
2315         case AST_DIAL_RESULT_HANGUP:
2316         case AST_DIAL_RESULT_UNANSWERED:
2317                 /* Failure cases */
2318                 stimulate_attended_transfer(props, STIMULUS_RECALL_TARGET_HANGUP);
2319                 break;
2320         case AST_DIAL_RESULT_RINGING:
2321         case AST_DIAL_RESULT_PROGRESS:
2322         case AST_DIAL_RESULT_PROCEEDING:
2323         case AST_DIAL_RESULT_TRYING:
2324                 /* Don't care about these cases */
2325                 break;
2326         case AST_DIAL_RESULT_ANSWERED:
2327                 /* We struck gold! */
2328                 props->recall_target = ast_dial_answered_steal(dial);
2329                 stimulate_attended_transfer(props, STIMULUS_RECALL_TARGET_ANSWER);
2330                 break;
2331         }
2332 }
2333
2334
2335 static int recalling_enter(struct attended_transfer_properties *props)
2336 {
2337         RAII_VAR(struct ast_format_cap *, cap, ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT), ao2_cleanup);
2338
2339         if (!cap) {
2340                 return -1;
2341         }
2342
2343         ast_format_cap_append(cap, ast_format_slin, 0);
2344
2345         /* When we dial the transfer target, since we are communicating
2346          * with a local channel, we can place the local channel in a bridge
2347          * and then call out to it. When recalling the transferer, though, we
2348          * have to use the dialing API because the channel is not local.
2349          */
2350         props->dial = ast_dial_create();
2351         if (!props->dial) {
2352                 return -1;
2353         }
2354
2355         if (ast_dial_append(props->dial, props->transferer_type, props->transferer_addr, NULL)) {
2356                 return -1;
2357         }
2358
2359         if (ast_dial_prerun(props->dial, NULL, cap)) {
2360                 return -1;
2361         }
2362
2363         ast_dial_set_state_callback(props->dial, &recall_callback);
2364
2365         ao2_ref(props, +1);
2366         ast_dial_set_user_data(props->dial, props);
2367
2368         if (ast_dial_run(props->dial, NULL, 1) == AST_DIAL_RESULT_FAILED) {
2369                 ao2_ref(props, -1);
2370                 return -1;
2371         }
2372
2373         bridge_ringing(props->transferee_bridge);
2374         return 0;
2375 }
2376
2377 static enum attended_transfer_state recalling_exit(struct attended_transfer_properties *props,
2378                 enum attended_transfer_stimulus stimulus)
2379 {
2380         /* No matter what the outcome was, we need to kill off the dial */
2381         ast_dial_join(props->dial);
2382         ast_dial_destroy(props->dial);
2383         props->dial = NULL;
2384         /* This reference is the one we incremented for the dial state callback (recall_callback) to use */
2385         ao2_ref(props, -1);
2386
2387         switch (stimulus) {
2388         case STIMULUS_TRANSFEREE_HANGUP:
2389                 return TRANSFER_FAIL;
2390         case STIMULUS_TIMEOUT:
2391         case STIMULUS_RECALL_TARGET_HANGUP:
2392                 ++props->retry_attempts;
2393                 if (props->retry_attempts >= props->atxfercallbackretries) {
2394                         return TRANSFER_FAIL;
2395                 }
2396                 if (props->atxferloopdelay) {
2397                         return TRANSFER_WAIT_TO_RETRANSFER;
2398                 }
2399                 return TRANSFER_RETRANSFER;
2400         case STIMULUS_RECALL_TARGET_ANSWER:
2401                 /* Setting this datastore up will allow the transferer to have all of his
2402                  * call features set up automatically when the bridge changes back to a
2403                  * normal personality
2404                  */
2405                 ast_bridge_features_ds_set(props->recall_target, &props->transferer_features);
2406                 ast_channel_ref(props->recall_target);
2407                 if (ast_bridge_impart(props->transferee_bridge, props->recall_target, NULL, NULL,
2408                         AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
2409                         ast_hangup(props->recall_target);
2410                         return TRANSFER_FAIL;
2411                 }
2412                 return TRANSFER_RESUME;
2413         case STIMULUS_NONE:
2414         case STIMULUS_DTMF_ATXFER_ABORT:
2415         case STIMULUS_DTMF_ATXFER_COMPLETE:
2416         case STIMULUS_DTMF_ATXFER_THREEWAY:
2417         case STIMULUS_DTMF_ATXFER_SWAP:
2418         case STIMULUS_TRANSFER_TARGET_HANGUP:
2419         case STIMULUS_TRANSFER_TARGET_ANSWER:
2420         case STIMULUS_TRANSFERER_HANGUP:
2421         default:
2422                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2423                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2424                 return props->state;
2425         }
2426 }
2427
2428 static int wait_to_retransfer_enter(struct attended_transfer_properties *props)
2429 {
2430         bridge_hold(props->transferee_bridge);
2431         return 0;
2432 }
2433
2434 static enum attended_transfer_state wait_to_retransfer_exit(struct attended_transfer_properties *props,
2435                 enum attended_transfer_stimulus stimulus)
2436 {
2437         bridge_unhold(props->transferee_bridge);
2438         switch (stimulus) {
2439         case STIMULUS_TRANSFEREE_HANGUP:
2440                 return TRANSFER_FAIL;
2441         case STIMULUS_TIMEOUT:
2442                 return TRANSFER_RETRANSFER;
2443         case STIMULUS_NONE:
2444         case STIMULUS_DTMF_ATXFER_ABORT:
2445         case STIMULUS_DTMF_ATXFER_COMPLETE:
2446         case STIMULUS_DTMF_ATXFER_THREEWAY:
2447         case STIMULUS_DTMF_ATXFER_SWAP:
2448         case STIMULUS_TRANSFER_TARGET_HANGUP:
2449         case STIMULUS_TRANSFER_TARGET_ANSWER:
2450         case STIMULUS_TRANSFERER_HANGUP:
2451         case STIMULUS_RECALL_TARGET_HANGUP:
2452         case STIMULUS_RECALL_TARGET_ANSWER:
2453         default:
2454                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2455                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2456                 return props->state;
2457         }
2458 }
2459
2460 static int attach_framehook(struct attended_transfer_properties *props, struct ast_channel *channel);
2461
2462 static int retransfer_enter(struct attended_transfer_properties *props)
2463 {
2464         RAII_VAR(struct ast_format_cap *, cap, ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT), ao2_cleanup);
2465         char destination[AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2];
2466         int cause;
2467
2468         if (!cap) {
2469                 return -1;
2470         }
2471
2472         snprintf(destination, sizeof(destination), "%s@%s", props->exten, props->context);
2473
2474         ast_format_cap_append(cap, ast_format_slin, 0);
2475
2476         /* Get a channel that is the destination we wish to call */
2477         props->recall_target = ast_request("Local", cap, NULL, NULL, destination, &cause);
2478         if (!props->recall_target) {
2479                 ast_log(LOG_ERROR, "Unable to request outbound channel for recall target\n");
2480                 return -1;
2481         }
2482
2483         if (attach_framehook(props, props->recall_target)) {
2484                 ast_log(LOG_ERROR, "Unable to attach framehook to recall target\n");
2485                 ast_hangup(props->recall_target);
2486                 props->recall_target = NULL;
2487                 return -1;
2488         }
2489
2490         if (ast_call(props->recall_target, destination, 0)) {
2491                 ast_log(LOG_ERROR, "Unable to place outbound call to recall target\n");
2492                 ast_hangup(props->recall_target);
2493                 props->recall_target = NULL;
2494                 return -1;
2495         }
2496
2497         ast_channel_ref(props->recall_target);
2498         if (ast_bridge_impart(props->transferee_bridge, props->recall_target, NULL, NULL,
2499                 AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
2500                 ast_log(LOG_ERROR, "Unable to place recall target into bridge\n");
2501                 ast_hangup(props->recall_target);
2502                 return -1;
2503         }
2504
2505         return 0;
2506 }
2507
2508 static enum attended_transfer_state retransfer_exit(struct attended_transfer_properties *props,
2509                 enum attended_transfer_stimulus stimulus)
2510 {
2511         switch (stimulus) {
2512         case STIMULUS_TRANSFEREE_HANGUP:
2513                 return TRANSFER_FAIL;
2514         case STIMULUS_TIMEOUT:
2515                 ast_softhangup(props->recall_target, AST_SOFTHANGUP_EXPLICIT);
2516         case STIMULUS_RECALL_TARGET_HANGUP:
2517                 props->recall_target = ast_channel_unref(props->recall_target);
2518                 if (props->atxferloopdelay) {
2519                         return TRANSFER_WAIT_TO_RECALL;
2520                 }
2521                 return TRANSFER_RECALLING;
2522         case STIMULUS_RECALL_TARGET_ANSWER:
2523                 return TRANSFER_RESUME;
2524         case STIMULUS_NONE:
2525         case STIMULUS_DTMF_ATXFER_ABORT:
2526         case STIMULUS_DTMF_ATXFER_COMPLETE:
2527         case STIMULUS_DTMF_ATXFER_THREEWAY:
2528         case STIMULUS_DTMF_ATXFER_SWAP:
2529         case STIMULUS_TRANSFER_TARGET_HANGUP:
2530         case STIMULUS_TRANSFER_TARGET_ANSWER:
2531         case STIMULUS_TRANSFERER_HANGUP:
2532         default:
2533                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2534                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2535                 return props->state;
2536         }
2537 }
2538
2539 static int wait_to_recall_enter(struct attended_transfer_properties *props)
2540 {
2541         bridge_hold(props->transferee_bridge);
2542         return 0;
2543 }
2544
2545 static enum attended_transfer_state wait_to_recall_exit(struct attended_transfer_properties *props,
2546                 enum attended_transfer_stimulus stimulus)
2547 {
2548         bridge_unhold(props->transferee_bridge);
2549         switch (stimulus) {
2550         case STIMULUS_TRANSFEREE_HANGUP:
2551                 return TRANSFER_FAIL;
2552         case STIMULUS_TIMEOUT:
2553                 return TRANSFER_RECALLING;
2554         case STIMULUS_NONE:
2555         case STIMULUS_DTMF_ATXFER_ABORT:
2556         case STIMULUS_DTMF_ATXFER_COMPLETE:
2557         case STIMULUS_DTMF_ATXFER_THREEWAY:
2558         case STIMULUS_DTMF_ATXFER_SWAP:
2559         case STIMULUS_TRANSFER_TARGET_HANGUP:
2560         case STIMULUS_TRANSFER_TARGET_ANSWER:
2561         case STIMULUS_TRANSFERER_HANGUP:
2562         case STIMULUS_RECALL_TARGET_HANGUP:
2563         case STIMULUS_RECALL_TARGET_ANSWER:
2564         default:
2565                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2566                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2567                 return props->state;
2568         }
2569 }
2570
2571 static int fail_enter(struct attended_transfer_properties *props)
2572 {
2573         if (props->transferee_bridge) {
2574                 ast_bridge_destroy(props->transferee_bridge, 0);
2575                 props->transferee_bridge = NULL;
2576         }
2577         return 0;
2578 }
2579
2580 /*!
2581  * \brief DTMF hook when transferer presses abort sequence.
2582  *
2583  * Sends a stimulus to the attended transfer monitor thread that the abort sequence has been pressed
2584  */
2585 static int atxfer_abort(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2586 {
2587         struct attended_transfer_properties *props = hook_pvt;
2588
2589         ast_debug(1, "Transferer on attended transfer %p pressed abort sequence\n", props);
2590         stimulate_attended_transfer(props, STIMULUS_DTMF_ATXFER_ABORT);
2591         return 0;
2592 }
2593
2594 /*!
2595  * \brief DTMF hook when transferer presses complete sequence.
2596  *
2597  * Sends a stimulus to the attended transfer monitor thread that the complete sequence has been pressed
2598  */
2599 static int atxfer_complete(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2600 {
2601         struct attended_transfer_properties *props = hook_pvt;
2602
2603         ast_debug(1, "Transferer on attended transfer %p pressed complete sequence\n", props);
2604         stimulate_attended_transfer(props, STIMULUS_DTMF_ATXFER_COMPLETE);
2605         return 0;
2606 }
2607
2608 /*!
2609  * \brief DTMF hook when transferer presses threeway sequence.
2610  *
2611  * Sends a stimulus to the attended transfer monitor thread that the threeway sequence has been pressed
2612  */
2613 static int atxfer_threeway(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2614 {
2615         struct attended_transfer_properties *props = hook_pvt;
2616
2617         ast_debug(1, "Transferer on attended transfer %p pressed threeway sequence\n", props);
2618         stimulate_attended_transfer(props, STIMULUS_DTMF_ATXFER_THREEWAY);
2619         return 0;
2620 }
2621
2622 /*!
2623  * \brief DTMF hook when transferer presses swap sequence.
2624  *
2625  * Sends a stimulus to the attended transfer monitor thread that the swap sequence has been pressed
2626  */
2627 static int atxfer_swap(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2628 {
2629         struct attended_transfer_properties *props = hook_pvt;
2630
2631         ast_debug(1, "Transferer on attended transfer %p pressed swap sequence\n", props);
2632         stimulate_attended_transfer(props, STIMULUS_DTMF_ATXFER_SWAP);
2633         return 0;
2634 }
2635
2636 /*!
2637  * \brief Hangup hook for transferer channel.
2638  *
2639  * Sends a stimulus to the attended transfer monitor thread that the transferer has hung up.
2640  */
2641 static int atxfer_transferer_hangup(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2642 {
2643         struct attended_transfer_properties *props = hook_pvt;
2644
2645         ast_debug(1, "Transferer on attended transfer %p hung up\n", props);
2646         stimulate_attended_transfer(props, STIMULUS_TRANSFERER_HANGUP);
2647         return 0;
2648 }
2649
2650 /*!
2651  * \brief Frame hook for transfer target channel
2652  *
2653  * This is used to determine if the transfer target or recall target has answered
2654  * the outgoing call.
2655  *
2656  * When an answer is detected, a stimulus is sent to the attended transfer monitor
2657  * thread to indicate that the transfer target or recall target has answered.
2658  *
2659  * \param chan The channel the framehook is attached to.
2660  * \param frame The frame being read or written.
2661  * \param event What is being done with the frame.
2662  * \param data The attended transfer properties.
2663  */
2664 static struct ast_frame *transfer_target_framehook_cb(struct ast_channel *chan,
2665                 struct ast_frame *frame, enum ast_framehook_event event, void *data)
2666 {
2667         struct attended_transfer_properties *props = data;
2668
2669         if (event == AST_FRAMEHOOK_EVENT_READ &&
2670                         frame && frame->frametype == AST_FRAME_CONTROL &&
2671                         frame->subclass.integer == AST_CONTROL_ANSWER) {
2672
2673                 ast_debug(1, "Detected an answer for recall attempt on attended transfer %p\n", props);
2674                 if (props->superstate == SUPERSTATE_TRANSFER) {
2675                         stimulate_attended_transfer(props, STIMULUS_TRANSFER_TARGET_ANSWER);
2676                 } else {
2677                         stimulate_attended_transfer(props, STIMULUS_RECALL_TARGET_ANSWER);
2678                 }
2679                 ast_framehook_detach(chan, props->target_framehook_id);
2680                 props->target_framehook_id = -1;
2681         }
2682
2683         return frame;
2684 }
2685
2686 /*! \brief Callback function which informs upstream if we are consuming a frame of a specific type */
2687 static int transfer_target_framehook_consume(void *data, enum ast_frame_type type)
2688 {
2689         return (type == AST_FRAME_CONTROL ? 1 : 0);
2690 }
2691
2692 static void transfer_target_framehook_destroy_cb(void *data)
2693 {
2694         struct attended_transfer_properties *props = data;
2695         ao2_cleanup(props);
2696 }
2697
2698 static int bridge_personality_atxfer_push(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
2699 {
2700         const char *abort_dtmf;
2701         const char *complete_dtmf;
2702         const char *threeway_dtmf;
2703         const char *swap_dtmf;
2704         struct bridge_basic_personality *personality = self->personality;
2705
2706         if (!ast_channel_has_role(bridge_channel->chan, AST_TRANSFERER_ROLE_NAME)) {
2707                 return 0;
2708         }
2709
2710         abort_dtmf = ast_channel_get_role_option(bridge_channel->chan, AST_TRANSFERER_ROLE_NAME, "abort");
2711         complete_dtmf = ast_channel_get_role_option(bridge_channel->chan, AST_TRANSFERER_ROLE_NAME, "complete");
2712         threeway_dtmf = ast_channel_get_role_option(bridge_channel->chan, AST_TRANSFERER_ROLE_NAME, "threeway");
2713         swap_dtmf = ast_channel_get_role_option(bridge_channel->chan, AST_TRANSFERER_ROLE_NAME, "swap");
2714
2715         if (!ast_strlen_zero(abort_dtmf) && ast_bridge_dtmf_hook(bridge_channel->features,
2716                         abort_dtmf, atxfer_abort, personality->details[personality->current].pvt, NULL,
2717                         AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE | AST_BRIDGE_HOOK_REMOVE_ON_PULL)) {
2718                 return -1;
2719         }
2720         if (!ast_strlen_zero(complete_dtmf) && ast_bridge_dtmf_hook(bridge_channel->features,
2721                         complete_dtmf, atxfer_complete, personality->details[personality->current].pvt, NULL,
2722                         AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE | AST_BRIDGE_HOOK_REMOVE_ON_PULL)) {
2723                 return -1;
2724         }
2725         if (!ast_strlen_zero(threeway_dtmf) && ast_bridge_dtmf_hook(bridge_channel->features,
2726                         threeway_dtmf, atxfer_threeway, personality->details[personality->current].pvt, NULL,
2727                         AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE | AST_BRIDGE_HOOK_REMOVE_ON_PULL)) {
2728                 return -1;
2729         }
2730         if (!ast_strlen_zero(swap_dtmf) && ast_bridge_dtmf_hook(bridge_channel->features,
2731                         swap_dtmf, atxfer_swap, personality->details[personality->current].pvt, NULL,
2732                         AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE | AST_BRIDGE_HOOK_REMOVE_ON_PULL)) {
2733                 return -1;
2734         }
2735         if (ast_bridge_hangup_hook(bridge_channel->features, atxfer_transferer_hangup,
2736                         personality->details[personality->current].pvt, NULL,
2737                         AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE | AST_BRIDGE_HOOK_REMOVE_ON_PULL)) {
2738                 return -1;
2739         }
2740
2741         return 0;
2742 }
2743
2744 static void transfer_pull(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct attended_transfer_properties *props)
2745 {
2746         if (self->num_channels > 1 || bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2747                 return;
2748         }
2749
2750         if (self->num_channels == 1) {
2751                 RAII_VAR(struct ast_bridge_channel *, transferer_bridge_channel, NULL, ao2_cleanup);
2752
2753                 ast_channel_lock(props->transferer);
2754                 transferer_bridge_channel = ast_channel_get_bridge_channel(props->transferer);
2755                 ast_channel_unlock(props->transferer);
2756
2757                 if (!transferer_bridge_channel) {
2758                         return;
2759                 }
2760
2761                 if (AST_LIST_FIRST(&self->channels) != transferer_bridge_channel) {
2762                         return;
2763                 }
2764         }
2765
2766         /* Reaching this point means that either
2767          * 1) The bridge has no channels in it
2768          * 2) The bridge has one channel, and it's the transferer
2769          * In either case, it indicates that the non-transferer parties
2770          * are no longer in the bridge.
2771          */
2772         if (self == props->transferee_bridge) {
2773                 stimulate_attended_transfer(props, STIMULUS_TRANSFEREE_HANGUP);
2774         } else {
2775                 stimulate_attended_transfer(props, STIMULUS_TRANSFER_TARGET_HANGUP);
2776         }
2777 }
2778
2779 static void recall_pull(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct attended_transfer_properties *props)
2780 {
2781         if (self == props->target_bridge) {
2782                 /* Once we're in the recall superstate, we no longer care about this bridge */
2783                 return;
2784         }
2785
2786         if (bridge_channel->chan == props->recall_target) {
2787                 stimulate_attended_transfer(props, STIMULUS_RECALL_TARGET_HANGUP);
2788                 return;
2789         }
2790
2791         if (self->num_channels == 0) {
2792                 /* Empty bridge means all transferees are gone for sure */
2793                 stimulate_attended_transfer(props, STIMULUS_TRANSFEREE_HANGUP);
2794                 return;
2795         }
2796
2797         if (self->num_channels == 1) {
2798                 RAII_VAR(struct ast_bridge_channel *, target_bridge_channel, NULL, ao2_cleanup);
2799                 if (!props->recall_target) {
2800                         /* No recall target means that the pull happened on a transferee. If there's still
2801                          * a channel left in the bridge, we don't need to send a stimulus
2802                          */
2803                         return;
2804                 }
2805
2806                 ast_channel_lock(props->recall_target);
2807                 target_bridge_channel = ast_channel_get_bridge_channel(props->recall_target);
2808                 ast_channel_unlock(props->recall_target);
2809
2810                 if (!target_bridge_channel) {
2811                         return;
2812                 }
2813
2814                 if (AST_LIST_FIRST(&self->channels) == target_bridge_channel) {
2815                         stimulate_attended_transfer(props, STIMULUS_TRANSFEREE_HANGUP);
2816                 }
2817         }
2818 }
2819
2820 static void bridge_personality_atxfer_pull(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel)
2821 {
2822         struct bridge_basic_personality *personality = self->personality;
2823         struct attended_transfer_properties *props = personality->details[personality->current].pvt;
2824
2825         switch (props->superstate) {
2826         case SUPERSTATE_TRANSFER:
2827                 transfer_pull(self, bridge_channel, props);
2828                 break;
2829         case SUPERSTATE_RECALL:
2830                 recall_pull(self, bridge_channel, props);
2831                 break;
2832         }
2833 }
2834
2835 static enum attended_transfer_stimulus wait_for_stimulus(struct attended_transfer_properties *props)
2836 {
2837         RAII_VAR(struct stimulus_list *, list, NULL, ast_free_ptr);
2838         SCOPED_MUTEX(lock, ao2_object_get_lockaddr(props));
2839
2840         while (!(list = AST_LIST_REMOVE_HEAD(&props->stimulus_queue, next))) {
2841                 if (!(state_properties[props->state].flags & TRANSFER_STATE_FLAG_TIMED)) {
2842                         ast_cond_wait(&props->cond, lock);
2843                 } else {
2844                         struct timeval relative_timeout = { 0, };
2845                         struct timeval absolute_timeout;
2846                         struct timespec timeout_arg;
2847
2848                         if (state_properties[props->state].flags & TRANSFER_STATE_FLAG_TIMER_RESET) {
2849                                 props->start = ast_tvnow();
2850                         }
2851
2852                         if (state_properties[props->state].flags & TRANSFER_STATE_FLAG_TIMER_LOOP_DELAY) {
2853                                 relative_timeout.tv_sec = props->atxferloopdelay;
2854                         } else {
2855                                 /* Implied TRANSFER_STATE_FLAG_TIMER_ATXFER_NO_ANSWER */
2856                                 relative_timeout.tv_sec = props->atxfernoanswertimeout;
2857                         }
2858
2859                         absolute_timeout = ast_tvadd(props->start, relative_timeout);
2860                         timeout_arg.tv_sec = absolute_timeout.tv_sec;
2861                         timeout_arg.tv_nsec = absolute_timeout.tv_usec * 1000;
2862
2863                         if (ast_cond_timedwait(&props->cond, lock, &timeout_arg) == ETIMEDOUT) {
2864                                 return STIMULUS_TIMEOUT;
2865                         }
2866                 }
2867         }
2868         return list->stimulus;
2869 }
2870
2871 /*!
2872  * \brief The main loop for the attended transfer monitor thread.
2873  *
2874  * This loop runs continuously until the attended transfer reaches
2875  * a terminal state. Stimuli for changes in the attended transfer
2876  * state are handled in this thread so that all factors in an
2877  * attended transfer can be handled in an orderly fashion.
2878  *
2879  * \param data The attended transfer properties
2880  */
2881 static void *attended_transfer_monitor_thread(void *data)
2882 {
2883         struct attended_transfer_properties *props = data;
2884
2885         for (;;) {
2886                 enum attended_transfer_stimulus stimulus;
2887
2888                 ast_debug(1, "About to enter state %s for attended transfer %p\n", state_properties[props->state].state_name, props);
2889
2890                 if (state_properties[props->state].enter &&
2891                                 state_properties[props->state].enter(props)) {
2892                         ast_log(LOG_ERROR, "State %s enter function returned an error for attended transfer %p\n",
2893                                         state_properties[props->state].state_name, props);
2894                         break;
2895                 }
2896
2897                 if (state_properties[props->state].flags & TRANSFER_STATE_FLAG_TERMINAL) {
2898                         ast_debug(1, "State %s is a terminal state. Ending attended transfer %p\n",
2899                                         state_properties[props->state].state_name, props);
2900                         break;
2901                 }
2902
2903                 stimulus = wait_for_stimulus(props);
2904
2905                 ast_debug(1, "Received stimulus %s on attended transfer %p\n", stimulus_strs[stimulus], props);
2906
2907                 ast_assert(state_properties[props->state].exit != NULL);
2908
2909                 props->state = state_properties[props->state].exit(props, stimulus);
2910
2911                 ast_debug(1, "Told to enter state %s exit on attended transfer %p\n", state_properties[props->state].state_name, props);
2912         }
2913
2914         attended_transfer_properties_shutdown(props);
2915
2916         return NULL;
2917 }
2918
2919 static int attach_framehook(struct attended_transfer_properties *props, struct ast_channel *channel)
2920 {
2921         struct ast_framehook_interface target_interface = {
2922                 .version = AST_FRAMEHOOK_INTERFACE_VERSION,
2923                 .event_cb = transfer_target_framehook_cb,
2924                 .destroy_cb = transfer_target_framehook_destroy_cb,
2925                 .consume_cb = transfer_target_framehook_consume,
2926                 .disable_inheritance = 1,
2927         };
2928
2929         ao2_ref(props, +1);
2930         target_interface.data = props;
2931
2932         props->target_framehook_id = ast_framehook_attach(channel, &target_interface);
2933         if (props->target_framehook_id == -1) {
2934                 ao2_ref(props, -1);
2935                 return -1;
2936         }
2937         return 0;
2938 }
2939
2940 static int add_transferer_role(struct ast_channel *chan, struct ast_bridge_features_attended_transfer *attended_transfer)
2941 {
2942         const char *atxfer_abort;
2943         const char *atxfer_threeway;
2944         const char *atxfer_complete;
2945         const char *atxfer_swap;
2946         RAII_VAR(struct ast_features_xfer_config *, xfer_cfg, NULL, ao2_cleanup);
2947         SCOPED_CHANNELLOCK(lock, chan);
2948
2949         xfer_cfg = ast_get_chan_features_xfer_config(chan);
2950         if (!xfer_cfg) {
2951                 return -1;
2952         }
2953         if (attended_transfer) {
2954                 atxfer_abort = ast_strdupa(S_OR(attended_transfer->abort, xfer_cfg->atxferabort));
2955                 atxfer_threeway = ast_strdupa(S_OR(attended_transfer->threeway, xfer_cfg->atxferthreeway));
2956                 atxfer_complete = ast_strdupa(S_OR(attended_transfer->complete, xfer_cfg->atxfercomplete));
2957                 atxfer_swap = ast_strdupa(S_OR(attended_transfer->swap, xfer_cfg->atxferswap));
2958         } else {
2959                 atxfer_abort = ast_strdupa(xfer_cfg->atxferabort);
2960                 atxfer_threeway = ast_strdupa(xfer_cfg->atxferthreeway);
2961                 atxfer_complete = ast_strdupa(xfer_cfg->atxfercomplete);
2962                 atxfer_swap = ast_strdupa(xfer_cfg->atxferswap);
2963         }
2964
2965         return ast_channel_add_bridge_role(chan, AST_TRANSFERER_ROLE_NAME) ||
2966                 ast_channel_set_bridge_role_option(chan, AST_TRANSFERER_ROLE_NAME, "abort", atxfer_abort) ||
2967                 ast_channel_set_bridge_role_option(chan, AST_TRANSFERER_ROLE_NAME, "complete", atxfer_complete) ||
2968                 ast_channel_set_bridge_role_option(chan, AST_TRANSFERER_ROLE_NAME, "threeway", atxfer_threeway) ||
2969                 ast_channel_set_bridge_role_option(chan, AST_TRANSFERER_ROLE_NAME, "swap", atxfer_swap);
2970 }
2971
2972 /*!
2973  * \brief Helper function that presents dialtone and grabs extension
2974  *
2975  * \retval 0 on success
2976  * \retval -1 on failure
2977  */
2978 static int grab_transfer(struct ast_channel *chan, char *exten, size_t exten_len, const char *context)
2979 {
2980         int res;
2981         int digit_timeout;
2982         int attempts = 0;
2983         int max_attempts;
2984         RAII_VAR(struct ast_features_xfer_config *, xfer_cfg, NULL, ao2_cleanup);
2985         char *retry_sound;
2986         char *invalid_sound;
2987
2988         ast_channel_lock(chan);
2989         xfer_cfg = ast_get_chan_features_xfer_config(chan);
2990         if (!xfer_cfg) {
2991                 ast_log(LOG_ERROR, "Unable to get transfer configuration\n");
2992                 ast_channel_unlock(chan);
2993                 return -1;
2994         }
2995         digit_timeout = xfer_cfg->transferdigittimeout * 1000;
2996         max_attempts = xfer_cfg->transferdialattempts;
2997         retry_sound = ast_strdupa(xfer_cfg->transferretrysound);
2998         invalid_sound = ast_strdupa(xfer_cfg->transferinvalidsound);
2999         ast_channel_unlock(chan);
3000
3001         /* Play the simple "transfer" prompt out and wait */
3002         res = ast_stream_and_wait(chan, "pbx-transfer", AST_DIGIT_ANY);
3003         ast_stopstream(chan);
3004         if (res < 0) {
3005                 /* Hangup or error */
3006                 return -1;
3007         }
3008         if (res) {
3009                 /* Store the DTMF digit that interrupted playback of the file. */
3010                 exten[0] = res;
3011         }
3012
3013         /* Drop to dialtone so they can enter the extension they want to transfer to */
3014         do {
3015                 ++attempts;
3016
3017                 ast_test_suite_event_notify("TRANSFER_BEGIN_DIAL",
3018                                 "Channel: %s\r\n"
3019                                 "Attempt: %d",
3020                                 ast_channel_name(chan), attempts);
3021                 res = ast_app_dtget(chan, context, exten, exten_len, exten_len - 1, digit_timeout);
3022                 ast_test_suite_event_notify("TRANSFER_DIALLED",
3023                                 "Channel: %s\r\n"
3024                                 "Attempt: %d\r\n"
3025                                 "Dialled: %s\r\n"
3026                                 "Result: %s",
3027                                 ast_channel_name(chan), attempts, exten, res > 0 ? "Success" : "Failure");
3028                 if (res < 0) {
3029                         /* Hangup or error */
3030                         res = -1;
3031                 } else if (!res) {
3032                         /* 0 for invalid extension dialed. */
3033                         if (ast_strlen_zero(exten)) {
3034                                 ast_debug(1, "%s dialed no digits.\n", ast_channel_name(chan));
3035                         } else {
3036                                 ast_debug(1, "%s dialed '%s@%s' does not exist.\n",
3037                                         ast_channel_name(chan), exten, context);
3038                         }
3039                         if (attempts < max_attempts) {
3040                                 ast_stream_and_wait(chan, retry_sound, AST_DIGIT_NONE);
3041                         } else {
3042                                 ast_stream_and_wait(chan, invalid_sound, AST_DIGIT_NONE);
3043                         }
3044                         memset(exten, 0, exten_len);
3045                         res = 1;
3046                 } else {
3047                         /* Dialed extension is valid. */
3048                         res = 0;
3049                 }
3050         } while (res > 0 && attempts < max_attempts);
3051
3052         ast_test_suite_event_notify("TRANSFER_DIAL_FINAL",
3053                         "Channel: %s\r\n"
3054                         "Result: %s",
3055                         ast_channel_name(chan), res == 0 ? "Success" : "Failure");
3056
3057         return res ? -1 : 0;
3058 }
3059
3060 static void copy_caller_data(struct ast_channel *dest, struct ast_channel *caller)
3061 {
3062         ast_channel_lock_both(caller, dest);
3063         ast_connected_line_copy_from_caller(ast_channel_connected(dest), ast_channel_caller(caller));
3064         ast_channel_inherit_variables(caller, dest);
3065         ast_channel_datastore_inherit(caller, dest);
3066         ast_channel_unlock(dest);
3067         ast_channel_unlock(caller);
3068 }
3069
3070 /*! \brief Helper function that creates an outgoing channel and returns it immediately */
3071 static struct ast_channel *dial_transfer(struct ast_channel *caller, const char *destination)
3072 {
3073         struct ast_channel *chan;
3074         int cause;
3075
3076         /* Now we request a local channel to prepare to call the destination */
3077         chan = ast_request("Local", ast_channel_nativeformats(caller), NULL, caller, destination,
3078                 &cause);
3079         if (!chan) {
3080                 return NULL;
3081         }
3082
3083         ast_channel_lock_both(chan, caller);
3084
3085         ast_channel_req_accountcodes(chan, caller, AST_CHANNEL_REQUESTOR_BRIDGE_PEER);
3086
3087         /* Who is transferring the call. */
3088         pbx_builtin_setvar_helper(chan, "TRANSFERERNAME", ast_channel_name(caller));
3089
3090         ast_bridge_set_transfer_variables(chan, ast_channel_name(caller), 1);
3091
3092         ast_channel_unlock(chan);
3093         ast_channel_unlock(caller);
3094
3095         /* Before we actually dial out let's inherit appropriate information. */
3096         copy_caller_data(chan, caller);
3097
3098         return chan;
3099 }
3100
3101 /*!
3102  * \brief Internal built in feature for attended transfers
3103  *
3104  * This hook will set up a thread for monitoring the progress of
3105  * an attended transfer. For more information about attended transfer
3106  * progress, see documentation on the transfer state machine.
3107  *
3108  * \param bridge_channel The channel that pressed the attended transfer DTMF sequence
3109  * \param hook_pvt Structure with further information about the attended transfer
3110  */
3111 static int feature_attended_transfer(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
3112 {
3113         struct ast_bridge_features_attended_transfer *attended_transfer = hook_pvt;
3114         struct attended_transfer_properties *props;
3115         struct ast_bridge *bridge;
3116         char destination[AST_MAX_EXTENSION + AST_MAX_CONTEXT + 1];
3117         char exten[AST_MAX_EXTENSION] = "";
3118         pthread_t thread;
3119
3120         /* Inhibit the bridge before we do anything else. */
3121         bridge = ast_bridge_channel_merge_inhibit(bridge_channel, +1);
3122
3123         if (strcmp(bridge->v_table->name, "basic")) {
3124                 ast_log(LOG_ERROR, "Attended transfer attempted on unsupported bridge type '%s'.\n",
3125                         bridge->v_table->name);
3126                 ast_bridge_merge_inhibit(bridge, -1);
3127                 ao2_ref(bridge, -1);
3128                 return 0;
3129         }
3130
3131         /* Was the bridge inhibited before we inhibited it? */
3132         if (1 < bridge->inhibit_merge) {
3133                 /*
3134                  * The peer likely initiated attended transfer at the same time
3135                  * and we lost the race.
3136                  */
3137                 ast_verb(3, "Channel %s: Bridge '%s' does not permit merging at this time.\n",
3138                         ast_channel_name(bridge_channel->chan), bridge->uniqueid);
3139                 ast_bridge_merge_inhibit(bridge, -1);
3140                 ao2_ref(bridge, -1);
3141                 return 0;
3142         }
3143
3144         props = attended_transfer_properties_alloc(bridge_channel->chan,
3145                 attended_transfer ? attended_transfer->context : NULL);
3146         if (!props) {
3147                 ast_log(LOG_ERROR, "Unable to allocate control structure for performing attended transfer.\n");
3148                 ast_bridge_merge_inhibit(bridge, -1);
3149                 ao2_ref(bridge, -1);
3150                 return 0;
3151         }
3152
3153         props->transferee_bridge = bridge;
3154
3155         if (add_transferer_role(props->transferer, attended_transfer)) {
3156                 ast_log(LOG_ERROR, "Unable to set transferrer bridge role.\n");
3157                 attended_transfer_properties_shutdown(props);
3158                 return 0;
3159         }
3160
3161         ast_bridge_channel_write_hold(bridge_channel, NULL);
3162
3163         /* Grab the extension to transfer to */
3164         if (grab_transfer(bridge_channel->chan, exten, sizeof(exten), props->context)) {
3165                 ast_log(LOG_WARNING, "Unable to acquire target extension for attended transfer.\n");
3166                 ast_bridge_channel_write_unhold(bridge_channel);
3167                 attended_transfer_properties_shutdown(props);
3168                 return 0;
3169         }
3170
3171         ast_string_field_set(props, exten, exten);
3172
3173         /* Fill the variable with the extension and context we want to call */
3174         snprintf(destination, sizeof(destination), "%s@%s", props->exten, props->context);
3175
3176         ast_debug(1, "Attended transfer to '%s'\n", destination);
3177
3178         /* Get a channel that is the destination we wish to call */
3179         props->transfer_target = dial_transfer(bridge_channel->chan, destination);
3180         if (!props->transfer_target) {
3181                 ast_log(LOG_ERROR, "Unable to request outbound channel for attended transfer target.\n");
3182                 ast_stream_and_wait(props->transferer, props->failsound, AST_DIGIT_NONE);
3183                 ast_bridge_channel_write_unhold(bridge_channel);
3184                 attended_transfer_properties_shutdown(props);
3185                 return 0;
3186         }
3187
3188
3189         /* Create a bridge to use to talk to the person we are calling */
3190         props->target_bridge = ast_bridge_basic_new();
3191         if (!props->target_bridge) {
3192                 ast_log(LOG_ERROR, "Unable to create bridge for attended transfer target.\n");
3193                 ast_stream_and_wait(props->transferer, props->failsound, AST_DIGIT_NONE);
3194                 ast_bridge_channel_write_unhold(bridge_channel);
3195                 ast_hangup(props->transfer_target);
3196                 props->transfer_target = NULL;
3197                 attended_transfer_properties_shutdown(props);
3198                 return 0;
3199         }
3200         ast_bridge_merge_inhibit(props->target_bridge, +1);
3201
3202         if (attach_framehook(props, props->transfer_target)) {
3203                 ast_log(LOG_ERROR, "Unable to attach framehook to transfer target.\n");
3204                 ast_stream_and_wait(props->transferer, props->failsound, AST_DIGIT_NONE);
3205                 ast_bridge_channel_write_unhold(bridge_channel);
3206                 ast_hangup(props->transfer_target);
3207                 props->transfer_target = NULL;
3208                 attended_transfer_properties_shutdown(props);
3209                 return 0;
3210         }
3211
3212         bridge_basic_change_personality(props->target_bridge,
3213                         BRIDGE_BASIC_PERSONALITY_ATXFER, props);
3214         bridge_basic_change_personality(bridge,
3215                         BRIDGE_BASIC_PERSONALITY_ATXFER, props);
3216
3217         if (ast_call(props->transfer_target, destination, 0)) {
3218                 ast_log(LOG_ERROR, "Unable to place outbound call to transfer target.\n");
3219                 ast_stream_and_wait(bridge_channel->chan, props->failsound, AST_DIGIT_NONE);
3220                 ast_bridge_channel_write_unhold(bridge_channel);
3221                 ast_hangup(props->transfer_target);
3222                 props->transfer_target = NULL;
3223                 attended_transfer_properties_shutdown(props);
3224                 return 0;
3225         }
3226
3227         /* We increase the refcount of the transfer target because ast_bridge_impart() will
3228          * steal the reference we already have. We need to keep a reference, so the only
3229          * choice is to give it a bump
3230          */
3231         ast_channel_ref(props->transfer_target);
3232         if (ast_bridge_impart(props->target_bridge, props->transfer_target, NULL, NULL,
3233                 AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
3234                 ast_log(LOG_ERROR, "Unable to place transfer target into bridge.\n");
3235                 ast_stream_and_wait(bridge_channel->chan, props->failsound, AST_DIGIT_NONE);
3236                 ast_bridge_channel_write_unhold(bridge_channel);
3237                 ast_hangup(props->transfer_target);
3238                 props->transfer_target = NULL;
3239                 attended_transfer_properties_shutdown(props);
3240                 return 0;
3241         }
3242
3243         if (ast_pthread_create_detached(&thread, NULL, attended_transfer_monitor_thread, props)) {
3244                 ast_log(LOG_ERROR, "Unable to create monitoring thread for attended transfer.\n");
3245                 ast_stream_and_wait(bridge_channel->chan, props->failsound, AST_DIGIT_NONE);
3246                 ast_bridge_channel_write_unhold(bridge_channel);
3247                 attended_transfer_properties_shutdown(props);
3248                 return 0;
3249         }
3250
3251         /* Once the monitoring thread has been created, it is responsible for destroying all
3252          * of the necessary components.
3253          */
3254         return 0;
3255 }
3256
3257 static void blind_transfer_cb(struct ast_channel *new_channel, struct transfer_channel_data *user_data_wrapper,
3258                 enum ast_transfer_type transfer_type)
3259 {
3260         struct ast_channel *transferer_channel = user_data_wrapper->data;
3261
3262         if (transfer_type == AST_BRIDGE_TRANSFER_MULTI_PARTY) {
3263                 copy_caller_data(new_channel, transferer_channel);
3264         }
3265 }
3266
3267 /*! \brief Internal built in feature for blind transfers */
3268 static int feature_blind_transfer(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
3269 {
3270         char exten[AST_MAX_EXTENSION] = "";
3271         struct ast_bridge_features_blind_transfer *blind_transfer = hook_pvt;
3272         const char *context;
3273         char *goto_on_blindxfr;
3274
3275         ast_bridge_channel_write_hold(bridge_channel, NULL);
3276
3277         ast_channel_lock(bridge_channel->chan);
3278         context = ast_strdupa(get_transfer_context(bridge_channel->chan,
3279                 blind_transfer ? blind_transfer->context : NULL));
3280         goto_on_blindxfr = ast_strdupa(S_OR(pbx_builtin_getvar_helper(bridge_channel->chan,
3281                 "GOTO_ON_BLINDXFR"), ""));
3282         ast_channel_unlock(bridge_channel->chan);
3283
3284         /* Grab the extension to transfer to */
3285         if (grab_transfer(bridge_channel->chan, exten, sizeof(exten), context)) {
3286                 ast_bridge_channel_write_unhold(bridge_channel);
3287                 return 0;
3288         }
3289
3290         if (!ast_strlen_zero(goto_on_blindxfr)) {
3291                 ast_debug(1, "After transfer, transferer %s goes to %s\n",
3292                                 ast_channel_name(bridge_channel->chan), goto_on_blindxfr);
3293                 ast_bridge_set_after_go_on(bridge_channel->chan, NULL, NULL, 0, goto_on_blindxfr);
3294         }
3295
3296         if (ast_bridge_transfer_blind(0, bridge_channel->chan, exten, context, blind_transfer_cb,
3297                         bridge_channel->chan) != AST_BRIDGE_TRANSFER_SUCCESS &&
3298                         !ast_strlen_zero(goto_on_blindxfr)) {
3299                 ast_bridge_discard_after_goto(bridge_channel->chan);
3300         }
3301
3302         return 0;
3303 }
3304
3305 struct ast_bridge_methods ast_bridge_basic_v_table;
3306 struct ast_bridge_methods personality_normal_v_table;
3307 struct ast_bridge_methods personality_atxfer_v_table;
3308
3309 static void bridge_basic_change_personality(struct ast_bridge *bridge,
3310                 enum bridge_basic_personality_type type, void *user_data)
3311 {
3312         struct bridge_basic_personality *personality = bridge->personality;
3313         SCOPED_LOCK(lock, bridge, ast_bridge_lock, ast_bridge_unlock);
<