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