Fix race condition that could result in ARI transfer messages not being sent.
[asterisk/asterisk.git] / main / bridge_basic.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013 Digium, Inc.
5  *
6  * Richard Mudgett <rmudgett@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*!
20  * \file
21  * \brief Basic bridge class.  It is a subclass of struct ast_bridge.
22  *
23  * \author Richard Mudgett <rmudgett@digium.com>
24  *
25  * See Also:
26  * \arg \ref AstCREDITS
27  */
28
29
30 #include "asterisk.h"
31
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
33
34 #include "asterisk/channel.h"
35 #include "asterisk/utils.h"
36 #include "asterisk/linkedlists.h"
37 #include "asterisk/bridge.h"
38 #include "asterisk/bridge_internal.h"
39 #include "asterisk/bridge_basic.h"
40 #include "asterisk/bridge_after.h"
41 #include "asterisk/astobj2.h"
42 #include "asterisk/features_config.h"
43 #include "asterisk/pbx.h"
44 #include "asterisk/file.h"
45 #include "asterisk/app.h"
46 #include "asterisk/dial.h"
47 #include "asterisk/stasis_bridges.h"
48 #include "asterisk/features.h"
49 #include "asterisk/format_cache.h"
50
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         RAII_VAR(struct ao2_container *, applicationmap, NULL, ao2_cleanup);
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                 return 0;
615         }
616
617         ao2_callback_data(applicationmap, 0, setup_dynamic_feature, features, &res);
618
619         return res;
620 }
621
622 /*!
623  * \internal
624  * \brief Setup DTMF feature hooks using the channel features datastore property.
625  * \since 12.0.0
626  *
627  * \param bridge_channel What to setup DTMF features on.
628  *
629  * \retval 0 on success.
630  * \retval -1 on error.
631  */
632 static int bridge_basic_setup_features(struct ast_bridge_channel *bridge_channel)
633 {
634         int res = 0;
635
636         res |= setup_bridge_features_builtin(bridge_channel->features, bridge_channel->chan);
637         res |= setup_bridge_features_dynamic(bridge_channel->features, bridge_channel->chan);
638
639         return res;
640 }
641
642 static int add_normal_hooks(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel)
643 {
644         return ast_bridge_hangup_hook(bridge_channel->features, basic_hangup_hook,
645                         NULL, NULL, AST_BRIDGE_HOOK_REMOVE_ON_PULL)
646                 || bridge_basic_setup_features(bridge_channel);
647 }
648
649 /*!
650  * \internal
651  * \brief ast_bridge basic push method.
652  * \since 12.0.0
653  *
654  * \param self Bridge to operate upon.
655  * \param bridge_channel Bridge channel to push.
656  * \param swap Bridge channel to swap places with if not NULL.
657  *
658  * \note On entry, self is already locked.
659  *
660  * \retval 0 on success
661  * \retval -1 on failure
662  */
663 static int bridge_personality_normal_push(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
664 {
665         if (add_normal_hooks(self, bridge_channel)) {
666                 return -1;
667         }
668
669         return 0;
670 }
671
672 static int bridge_basic_push(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
673 {
674         struct bridge_basic_personality *personality = self->personality;
675
676         ast_assert(personality != NULL);
677
678         if (personality->details[personality->current].v_table->push
679                 && personality->details[personality->current].v_table->push(self, bridge_channel, swap)) {
680                 return -1;
681         }
682
683         ast_bridge_channel_update_linkedids(bridge_channel, swap);
684         ast_bridge_channel_update_accountcodes(bridge_channel, swap);
685
686         return ast_bridge_base_v_table.push(self, bridge_channel, swap);
687 }
688
689 static void bridge_basic_pull(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel)
690 {
691         struct bridge_basic_personality *personality = self->personality;
692
693         ast_assert(personality != NULL);
694
695         if (personality->details[personality->current].v_table->pull) {
696                 personality->details[personality->current].v_table->pull(self, bridge_channel);
697         }
698
699         ast_bridge_channel_update_accountcodes(NULL, bridge_channel);
700
701         ast_bridge_base_v_table.pull(self, bridge_channel);
702 }
703
704 static void bridge_basic_destroy(struct ast_bridge *self)
705 {
706         struct bridge_basic_personality *personality = self->personality;
707
708         ao2_cleanup(personality);
709
710         ast_bridge_base_v_table.destroy(self);
711 }
712
713 /*!
714  * \brief Remove appropriate hooks when basic bridge personality changes
715  *
716  * Hooks that have the AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE flag
717  * set will be removed from all bridge channels in the bridge.
718  *
719  * \param bridge Basic bridge undergoing personality change
720  */
721 static void remove_hooks_on_personality_change(struct ast_bridge *bridge)
722 {
723         struct ast_bridge_channel *iter;
724
725         AST_LIST_TRAVERSE(&bridge->channels, iter, entry) {
726                 SCOPED_LOCK(lock, iter, ast_bridge_channel_lock, ast_bridge_channel_unlock);
727                 ast_bridge_features_remove(iter->features, AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE);
728         }
729 }
730
731 /*!
732  * \brief Attended transfer superstates.
733  *
734  * An attended transfer's progress is facilitated by a state machine.
735  * The individual states of the state machine fall into the realm of
736  * one of two superstates.
737  */
738 enum attended_transfer_superstate {
739         /*!
740          * \brief Transfer superstate
741          *
742          * The attended transfer state machine begins in this superstate. The
743          * goal of this state is for a transferer channel to facilitate a
744          * transfer from a transferee to a transfer target.
745          *
746          * There are two bridges used in this superstate. The transferee bridge is
747          * the bridge that the transferer and transferee channels originally
748          * communicate in, and the target bridge is the bridge where the transfer
749          * target is being dialed.
750          *
751          * The transferer channel is capable of moving between the bridges using
752          * the DTMF swap sequence.
753          */
754         SUPERSTATE_TRANSFER,
755         /*!
756          * \brief Recall superstate
757          *
758          * The attended transfer state machine moves to this superstate if
759          * atxferdropcall is set to "no" and the transferer channel hangs up
760          * during a transfer. The goal in this superstate is to call back either
761          * the transfer target or transferer and rebridge with the transferee
762          * channel(s).
763          *
764          * In this superstate, there is only a single bridge used, the original
765          * transferee bridge. Rather than distinguishing between a transferer
766          * and transfer target, all outbound calls are toward a "recall_target"
767          * channel.
768          */
769         SUPERSTATE_RECALL,
770 };
771
772 /*!
773  * The states in the attended transfer state machine.
774  */
775 enum attended_transfer_state {
776         /*!
777          * \brief Calling Target state
778          *
779          * This state describes the initial state of a transfer. The transferer
780          * waits in the transfer target's bridge for the transfer target to answer.
781          *
782          * Superstate: Transfer
783          *
784          * Preconditions:
785          * 1) Transfer target is RINGING
786          * 2) Transferer is in transferee bridge
787          * 3) Transferee is on hold
788          *
789          * Transitions to TRANSFER_CALLING_TARGET:
790          * 1) This is the initial state for an attended transfer.
791          * 2) TRANSFER_HESITANT: Transferer presses DTMF swap sequence
792          *
793          * State operation:
794          * The transferer is moved from the transferee bridge into the transfer
795          * target bridge.
796          *
797          * Transitions from TRANSFER_CALLING_TARGET:
798          * 1) TRANSFER_FAIL: Transferee hangs up.
799          * 2) TRANSFER_BLOND: Transferer hangs up or presses DTMF swap sequence
800          * and configured atxferdropcall setting is yes.
801          * 3) TRANSFER_BLOND_NONFINAL: Transferer hangs up or presses DTMF swap
802          * sequence and configured atxferdroppcall setting is no.
803          * 4) TRANSFER_CONSULTING: Transfer target answers the call.
804          * 5) TRANSFER_REBRIDGE: Transfer target hangs up, call to transfer target
805          * times out, or transferer presses DTMF abort sequence.
806          * 6) TRANSFER_THREEWAY: Transferer presses DTMF threeway sequence.
807          * 7) TRANSFER_HESITANT: Transferer presses DTMF swap sequence.
808          */
809         TRANSFER_CALLING_TARGET,
810         /*!
811          * \brief Hesitant state
812          *
813          * This state only arises if when waiting for the transfer target to
814          * answer, the transferer presses the DTMF swap sequence. This will
815          * cause the transferer to be rebridged with the transferee temporarily.
816          *
817          * Superstate: Transfer
818          *
819          * Preconditions:
820          * 1) Transfer target is in ringing state
821          * 2) Transferer is in transfer target bridge
822          * 3) Transferee is on hold
823          *
824          * Transitions to TRANSFER_HESITANT:
825          * 1) TRANSFER_CALLING_TARGET: Transferer presses DTMF swap sequence.
826          *
827          * State operation:
828          * The transferer is moved from the transfer target bridge into the
829          * transferee bridge, and the transferee is taken off hold.
830          *
831          * Transitions from TRANSFER_HESITANT:
832          * 1) TRANSFER_FAIL: Transferee hangs up
833          * 2) TRANSFER_BLOND: Transferer hangs up or presses DTMF swap sequence
834          * and configured atxferdropcall setting is yes.
835          * 3) TRANSFER_BLOND_NONFINAL: Transferer hangs up or presses DTMF swap
836          * sequence and configured atxferdroppcall setting is no.
837          * 4) TRANSFER_DOUBLECHECKING: Transfer target answers the call
838          * 5) TRANSFER_RESUME: Transfer target hangs up, call to transfer target
839          * times out, or transferer presses DTMF abort sequence.
840          * 6) TRANSFER_THREEWAY: Transferer presses DTMF threeway sequence.
841          * 7) TRANSFER_CALLING_TARGET: Transferer presses DTMF swap sequence.
842          */
843         TRANSFER_HESITANT,
844         /*!
845          * \brief Rebridge state
846          *
847          * This is a terminal state that indicates that the transferer needs
848          * to move back to the transferee's bridge. This is a failed attended
849          * transfer result.
850          *
851          * Superstate: Transfer
852          *
853          * Preconditions:
854          * 1) Transferer is in transfer target bridge
855          * 2) Transferee is on hold
856          *
857          * Transitions to TRANSFER_REBRIDGE:
858          * 1) TRANSFER_CALLING_TARGET: Transfer target hangs up, call to transfer target
859          * times out, or transferer presses DTMF abort sequence.
860          * 2) TRANSFER_STATE_CONSULTING: Transfer target hangs up, or transferer presses
861          * DTMF abort sequence.
862          *
863          * State operation:
864          * The transferer channel is moved from the transfer target bridge to the
865          * transferee bridge. The transferee is taken off hold. A stasis transfer
866          * message is published indicating a failed attended transfer.
867          *
868          * Transitions from TRANSFER_REBRIDGE:
869          * None
870          */
871         TRANSFER_REBRIDGE,
872         /*!
873          * \brief Resume state
874          *
875          * This is a terminal state that indicates that the party bridged with the
876          * transferee is the final party to be bridged with that transferee. This state
877          * may come about due to a successful recall or due to a failed transfer.
878          *
879          * Superstate: Transfer or Recall
880          *
881          * Preconditions:
882          * In Transfer Superstate:
883          * 1) Transferer is in transferee bridge
884          * 2) Transferee is not on hold
885          * In Recall Superstate:
886          * 1) The recall target is in the transferee bridge
887          * 2) Transferee is not on hold
888          *
889          * Transitions to TRANSFER_RESUME:
890          * TRANSFER_HESITANT: Transfer target hangs up, call to transfer target times out,
891          * or transferer presses DTMF abort sequence.
892          * TRANSFER_DOUBLECHECKING: Transfer target hangs up or transferer presses DTMF
893          * abort sequence.
894          * TRANSFER_BLOND_NONFINAL: Recall target answers
895          * TRANSFER_RECALLING: Recall target answers
896          * TRANSFER_RETRANSFER: Recall target answers
897          *
898          * State operations:
899          * None
900          *
901          * Transitions from TRANSFER_RESUME:
902          * None
903          */
904         TRANSFER_RESUME,
905         /*!
906          * \brief Threeway state
907          *
908          * This state results when the transferer wishes to have all parties involved
909          * in a transfer to be in the same bridge together.
910          *
911          * Superstate: Transfer
912          *
913          * Preconditions:
914          * 1) Transfer target state is either RINGING or UP
915          * 2) Transferer is in either bridge
916          * 3) Transferee is not on hold
917          *
918          * Transitions to TRANSFER_THREEWAY:
919          * 1) TRANSFER_CALLING_TARGET: Transferer presses DTMF threeway sequence.
920          * 2) TRANSFER_HESITANT: Transferer presses DTMF threeway sequence.
921          * 3) TRANSFER_CONSULTING: Transferer presses DTMF threeway sequence.
922          * 4) TRANSFER_DOUBLECHECKING: Transferer presses DTMF threeway sequence.
923          *
924          * State operation:
925          * The transfer target bridge is merged into the transferee bridge.
926          *
927          * Transitions from TRANSFER_THREEWAY:
928          * None.
929          */
930         TRANSFER_THREEWAY,
931         /*!
932          * \brief Consulting state
933          *
934          * This state describes the case where the transferer and transfer target
935          * are able to converse in the transfer target's bridge prior to completing
936          * the transfer.
937          *
938          * Superstate: Transfer
939          *
940          * Preconditions:
941          * 1) Transfer target is UP
942          * 2) Transferer is in target bridge
943          * 3) Transferee is on hold
944          *
945          * Transitions to TRANSFER_CONSULTING:
946          * 1) TRANSFER_CALLING_TARGET: Transfer target answers.
947          * 2) TRANSFER_DOUBLECHECKING: Transferer presses DTMF swap sequence.
948          *
949          * State operations:
950          * None.
951          *
952          * Transitions from TRANSFER_CONSULTING:
953          * TRANSFER_COMPLETE: Transferer hangs up or transferer presses DTMF complete sequence.
954          * TRANSFER_REBRIDGE: Transfer target hangs up or transferer presses DTMF abort sequence.
955          * TRANSFER_THREEWAY: Transferer presses DTMF threeway sequence.
956          * TRANSFER_DOUBLECHECKING: Transferer presses DTMF swap sequence.
957          */
958         TRANSFER_CONSULTING,
959         /*!
960          * \brief Double-checking state
961          *
962          * This state describes the case where the transferer and transferee are
963          * able to converse in the transferee's bridge prior to completing the transfer. The
964          * difference between this and TRANSFER_HESITANT is that the transfer target is
965          * UP in this case.
966          *
967          * Superstate: Transfer
968          *
969          * Preconditions:
970          * 1) Transfer target is UP and on hold
971          * 2) Transferer is in transferee bridge
972          * 3) Transferee is off hold
973          *
974          * Transitions to TRANSFER_DOUBLECHECKING:
975          * 1) TRANSFER_HESITANT: Transfer target answers.
976          * 2) TRANSFER_CONSULTING: Transferer presses DTMF swap sequence.
977          *
978          * State operations:
979          * None.
980          *
981          * Transitions from TRANSFER_DOUBLECHECKING:
982          * 1) TRANSFER_FAIL: Transferee hangs up.
983          * 2) TRANSFER_COMPLETE: Transferer hangs up or presses DTMF complete sequence.
984          * 3) TRANSFER_RESUME: Transfer target hangs up or transferer presses DTMF abort sequence.
985          * 4) TRANSFER_THREEWAY: Transferer presses DTMF threeway sequence.
986          * 5) TRANSFER_CONSULTING: Transferer presses the DTMF swap sequence.
987          */
988         TRANSFER_DOUBLECHECKING,
989         /*!
990          * \brief Complete state
991          *
992          * This is a terminal state where a transferer has successfully completed an attended
993          * transfer. This state's goal is to get the transfer target and transferee into
994          * the same bridge and the transferer off the call.
995          *
996          * Superstate: Transfer
997          *
998          * Preconditions:
999          * 1) Transfer target is UP and off hold.
1000          * 2) Transferer is in either bridge.
1001          * 3) Transferee is off hold.
1002          *
1003          * Transitions to TRANSFER_COMPLETE:
1004          * 1) TRANSFER_CONSULTING: transferer hangs up or presses the DTMF complete sequence.
1005          * 2) TRANSFER_DOUBLECHECKING: transferer hangs up or presses the DTMF complete sequence.
1006          *
1007          * State operation:
1008          * The transfer target bridge is merged into the transferee bridge. The transferer
1009          * channel is kicked out of the bridges as part of the merge.
1010          *
1011          * State operations:
1012          * 1) Merge the transfer target bridge into the transferee bridge,
1013          * excluding the transferer channel from the merge.
1014          * 2) Publish a stasis transfer message.
1015          *
1016          * Exit operations:
1017          * This is a terminal state, so there are no exit operations.
1018          */
1019         TRANSFER_COMPLETE,
1020         /*!
1021          * \brief Blond state
1022          *
1023          * This is a terminal state where a transferer has completed an attended transfer prior
1024          * to the transfer target answering. This state is only entered if atxferdropcall
1025          * is set to 'yes'. This is considered to be a successful attended transfer.
1026          *
1027          * Superstate: Transfer
1028          *
1029          * Preconditions:
1030          * 1) Transfer target is RINGING.
1031          * 2) Transferer is in either bridge.
1032          * 3) Transferee is off hold.
1033          *
1034          * Transitions to TRANSFER_BLOND:
1035          * 1) TRANSFER_CALLING_TARGET: Transferer hangs up or presses the DTMF complete sequence.
1036          *    atxferdropcall is set to 'yes'.
1037          * 2) TRANSFER_HESITANT: Transferer hangs up or presses the DTMF complete sequence.
1038          *    atxferdropcall is set to 'yes'.
1039          *
1040          * State operations:
1041          * The transfer target bridge is merged into the transferee bridge. The transferer
1042          * channel is kicked out of the bridges as part of the merge. A stasis transfer
1043          * publication is sent indicating a successful transfer.
1044          *
1045          * Transitions from TRANSFER_BLOND:
1046          * None
1047          */
1048         TRANSFER_BLOND,
1049         /*!
1050          * \brief Blond non-final state
1051          *
1052          * This state is very similar to the TRANSFER_BLOND state, except that
1053          * this state is entered when atxferdropcall is set to 'no'. This is the
1054          * initial state of the Recall superstate, so state operations mainly involve
1055          * moving to the Recall superstate. This means that the transfer target, that
1056          * is currently ringing is now known as the recall target.
1057          *
1058          * Superstate: Recall
1059          *
1060          * Preconditions:
1061          * 1) Recall target is RINGING.
1062          * 2) Transferee is off hold.
1063          *
1064          * Transitions to TRANSFER_BLOND_NONFINAL:
1065          * 1) TRANSFER_CALLING_TARGET: Transferer hangs up or presses the DTMF complete sequence.
1066          *    atxferdropcall is set to 'no'.
1067          * 2) TRANSFER_HESITANT: Transferer hangs up or presses the DTMF complete sequence.
1068          *    atxferdropcall is set to 'no'.
1069          *
1070          * State operation:
1071          * The superstate of the attended transfer is changed from Transfer to Recall.
1072          * The transfer target bridge is merged into the transferee bridge. The transferer
1073          * channel is kicked out of the bridges as part of the merge.
1074          *
1075          * Transitions from TRANSFER_BLOND_NONFINAL:
1076          * 1) TRANSFER_FAIL: Transferee hangs up
1077          * 2) TRANSFER_RESUME: Recall target answers
1078          * 3) TRANSFER_RECALLING: Recall target hangs up or time expires.
1079          */
1080         TRANSFER_BLOND_NONFINAL,
1081         /*!
1082          * \brief Recalling state
1083          *
1084          * This state is entered if the recall target from the TRANSFER_BLOND_NONFINAL
1085          * or TRANSFER_RETRANSFER states hangs up or does not answer. The goal of this
1086          * state is to call back the original transferer in an attempt to recover the
1087          * original call.
1088          *
1089          * Superstate: Recall
1090          *
1091          * Preconditions:
1092          * 1) Recall target is down.
1093          * 2) Transferee is off hold.
1094          *
1095          * Transitions to TRANSFER_RECALLING:
1096          * 1) TRANSFER_BLOND_NONFINAL: Recall target hangs up or time expires.
1097          * 2) TRANSFER_RETRANSFER: Recall target hangs up or time expires.
1098          *    atxferloopdelay is non-zero.
1099          * 3) TRANSFER_WAIT_TO_RECALL: Time expires.
1100          *
1101          * State operation:
1102          * The original transferer becomes the recall target and is called using the Dialing API.
1103          * Ringing is indicated to the transferee.
1104          *
1105          * Transitions from TRANSFER_RECALLING:
1106          * 1) TRANSFER_FAIL:
1107          *    a) Transferee hangs up.
1108          *    b) Recall target hangs up or time expires, and number of recall attempts exceeds atxfercallbackretries
1109          * 2) TRANSFER_WAIT_TO_RETRANSFER: Recall target hangs up or time expires.
1110          *    atxferloopdelay is non-zero.
1111          * 3) TRANSFER_RETRANSFER: Recall target hangs up or time expires.
1112          *    atxferloopdelay is zero.
1113          * 4) TRANSFER_RESUME: Recall target answers.
1114          */
1115         TRANSFER_RECALLING,
1116         /*!
1117          * \brief Wait to Retransfer state
1118          *
1119          * This state is used simply to give a bit of breathing room between attempting
1120          * to call back the original transferer and attempting to call back the original
1121          * transfer target. The transferee hears music on hold during this state as an
1122          * auditory clue that no one is currently being dialed.
1123          *
1124          * Superstate: Recall
1125          *
1126          * Preconditions:
1127          * 1) Recall target is down.
1128          * 2) Transferee is off hold.
1129          *
1130          * Transitions to TRANSFER_WAIT_TO_RETRANSFER:
1131          * 1) TRANSFER_RECALLING: Recall target hangs up or time expires.
1132          *    atxferloopdelay is non-zero.
1133          *
1134          * State operation:
1135          * The transferee is placed on hold.
1136          *
1137          * Transitions from TRANSFER_WAIT_TO_RETRANSFER:
1138          * 1) TRANSFER_FAIL: Transferee hangs up.
1139          * 2) TRANSFER_RETRANSFER: Time expires.
1140          */
1141         TRANSFER_WAIT_TO_RETRANSFER,
1142         /*!
1143          * \brief Retransfer state
1144          *
1145          * This state is used in order to attempt to call back the original
1146          * transfer target channel from the transfer. The transferee hears
1147          * ringing during this state as an auditory cue that a party is being
1148          * dialed.
1149          *
1150          * Superstate: Recall
1151          *
1152          * Preconditions:
1153          * 1) Recall target is down.
1154          * 2) Transferee is off hold.
1155          *
1156          * Transitions to TRANSFER_RETRANSFER:
1157          * 1) TRANSFER_RECALLING: Recall target hangs up or time expires.
1158          *    atxferloopdelay is zero.
1159          * 2) TRANSFER_WAIT_TO_RETRANSFER: Time expires.
1160          *
1161          * State operation:
1162          * The original transfer target is requested and is set as the recall target.
1163          * The recall target is called and placed into the transferee bridge.
1164          *
1165          * Transitions from TRANSFER_RETRANSFER:
1166          * 1) TRANSFER_FAIL: Transferee hangs up.
1167          * 2) TRANSFER_WAIT_TO_RECALL: Recall target hangs up or time expires.
1168          *    atxferloopdelay is non-zero.
1169          * 3) TRANSFER_RECALLING: Recall target hangs up or time expires.
1170          *    atxferloopdelay is zero.
1171          */
1172         TRANSFER_RETRANSFER,
1173         /*!
1174          * \brief Wait to recall state
1175          *
1176          * This state is used simply to give a bit of breathing room between attempting
1177          * to call back the original transfer target and attempting to call back the
1178          * original transferer. The transferee hears music on hold during this state as an
1179          * auditory clue that no one is currently being dialed.
1180          *
1181          * Superstate: Recall
1182          *
1183          * Preconditions:
1184          * 1) Recall target is down.
1185          * 2) Transferee is off hold.
1186          *
1187          * Transitions to TRANSFER_WAIT_TO_RECALL:
1188          * 1) TRANSFER_RETRANSFER: Recall target hangs up or time expires.
1189          *    atxferloopdelay is non-zero.
1190          *
1191          * State operation:
1192          * Transferee is placed on hold.
1193          *
1194          * Transitions from TRANSFER_WAIT_TO_RECALL:
1195          * 1) TRANSFER_FAIL: Transferee hangs up
1196          * 2) TRANSFER_RECALLING: Time expires
1197          */
1198         TRANSFER_WAIT_TO_RECALL,
1199         /*!
1200          * \brief Fail state
1201          *
1202          * This state indicates that something occurred during the transfer that
1203          * makes a graceful completion impossible. The most common stimulus for this
1204          * state is when the transferee hangs up.
1205          *
1206          * Superstate: Transfer and Recall
1207          *
1208          * Preconditions:
1209          * None
1210          *
1211          * Transitions to TRANSFER_FAIL:
1212          * 1) TRANSFER_CALLING_TARGET: Transferee hangs up.
1213          * 2) TRANSFER_HESITANT: Transferee hangs up.
1214          * 3) TRANSFER_DOUBLECHECKING: Transferee hangs up.
1215          * 4) TRANSFER_BLOND_NONFINAL: Transferee hangs up.
1216          * 5) TRANSFER_RECALLING:
1217          *    a) Transferee hangs up.
1218          *    b) Recall target hangs up or time expires, and number of
1219          *       recall attempts exceeds atxfercallbackretries.
1220          * 6) TRANSFER_WAIT_TO_RETRANSFER: Transferee hangs up.
1221          * 7) TRANSFER_RETRANSFER: Transferee hangs up.
1222          * 8) TRANSFER_WAIT_TO_RECALL: Transferee hangs up.
1223          *
1224          * State operation:
1225          * A transfer stasis publication is made indicating a failed transfer.
1226          * The transferee bridge is destroyed.
1227          *
1228          * Transitions from TRANSFER_FAIL:
1229          * None.
1230          */
1231         TRANSFER_FAIL,
1232 };
1233
1234 /*!
1235  * \brief Stimuli that can cause transfer state changes
1236  */
1237 enum attended_transfer_stimulus {
1238         /*! No stimulus. This literally can never happen. */
1239         STIMULUS_NONE,
1240         /*! All of the transferee channels have been hung up. */
1241         STIMULUS_TRANSFEREE_HANGUP,
1242         /*! The transferer has hung up. */
1243         STIMULUS_TRANSFERER_HANGUP,
1244         /*! The transfer target channel has hung up. */
1245         STIMULUS_TRANSFER_TARGET_HANGUP,
1246         /*! The transfer target channel has answered. */
1247         STIMULUS_TRANSFER_TARGET_ANSWER,
1248         /*! The recall target channel has hung up. */
1249         STIMULUS_RECALL_TARGET_HANGUP,
1250         /*! The recall target channel has answered. */
1251         STIMULUS_RECALL_TARGET_ANSWER,
1252         /*! The current state's timer has expired. */
1253         STIMULUS_TIMEOUT,
1254         /*! The transferer pressed the abort DTMF sequence. */
1255         STIMULUS_DTMF_ATXFER_ABORT,
1256         /*! The transferer pressed the complete DTMF sequence. */
1257         STIMULUS_DTMF_ATXFER_COMPLETE,
1258         /*! The transferer pressed the three-way DTMF sequence. */
1259         STIMULUS_DTMF_ATXFER_THREEWAY,
1260         /*! The transferer pressed the swap DTMF sequence. */
1261         STIMULUS_DTMF_ATXFER_SWAP,
1262 };
1263
1264 /*!
1265  * \brief String representations of the various stimuli
1266  *
1267  * Used for debugging purposes
1268  */
1269 const char *stimulus_strs[] = {
1270         [STIMULUS_NONE] = "None",
1271         [STIMULUS_TRANSFEREE_HANGUP] = "Transferee Hangup",
1272         [STIMULUS_TRANSFERER_HANGUP] = "Transferer Hangup",
1273         [STIMULUS_TRANSFER_TARGET_HANGUP] = "Transfer Target Hangup",
1274         [STIMULUS_TRANSFER_TARGET_ANSWER] = "Transfer Target Answer",
1275         [STIMULUS_RECALL_TARGET_HANGUP] = "Recall Target Hangup",
1276         [STIMULUS_RECALL_TARGET_ANSWER] = "Recall Target Answer",
1277         [STIMULUS_TIMEOUT] = "Timeout",
1278         [STIMULUS_DTMF_ATXFER_ABORT] = "DTMF Abort",
1279         [STIMULUS_DTMF_ATXFER_COMPLETE] = "DTMF Complete",
1280         [STIMULUS_DTMF_ATXFER_THREEWAY] = "DTMF Threeway",
1281         [STIMULUS_DTMF_ATXFER_SWAP] = "DTMF Swap",
1282 };
1283
1284 struct stimulus_list {
1285         enum attended_transfer_stimulus stimulus;
1286         AST_LIST_ENTRY(stimulus_list) next;
1287 };
1288
1289 /*!
1290  * \brief Collection of data related to an attended transfer attempt
1291  */
1292 struct attended_transfer_properties {
1293         AST_DECLARE_STRING_FIELDS (
1294                 /*! Extension of transfer target */
1295                 AST_STRING_FIELD(exten);
1296                 /*! Context of transfer target */
1297                 AST_STRING_FIELD(context);
1298                 /*! Sound to play on failure */
1299                 AST_STRING_FIELD(failsound);
1300                 /*! Sound to play when transfer completes */
1301                 AST_STRING_FIELD(xfersound);
1302                 /*! The channel technology of the transferer channel */
1303                 AST_STRING_FIELD(transferer_type);
1304                 /*! The transferer channel address */
1305                 AST_STRING_FIELD(transferer_addr);
1306         );
1307         /*! Condition used to synchronize when stimuli are reported to the monitor thread */
1308         ast_cond_t cond;
1309         /*! The bridge where the transferee resides. This bridge is also the bridge that
1310          * survives a successful attended transfer.
1311          */
1312         struct ast_bridge *transferee_bridge;
1313         /*! The bridge used to place an outbound call to the transfer target. This
1314          * bridge is merged with the transferee_bridge on a successful transfer.
1315          */
1316         struct ast_bridge *target_bridge;
1317         /*! The party that performs the attended transfer. */
1318         struct ast_channel *transferer;
1319         /*! The local channel dialed to reach the transfer target. */
1320         struct ast_channel *transfer_target;
1321         /*! The party that is currently being recalled. Depending on
1322          * the current state, this may be either the party that originally
1323          * was the transferer or the original transfer target
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 };
1350
1351 static void attended_transfer_properties_destructor(void *obj)
1352 {
1353         struct attended_transfer_properties *props = obj;
1354
1355         ast_debug(1, "Destroy attended transfer properties %p\n", props);
1356
1357         ao2_cleanup(props->target_bridge);
1358         ao2_cleanup(props->transferee_bridge);
1359         /* Use ast_channel_cleanup() instead of ast_channel_unref() for channels since they may be NULL */
1360         ast_channel_cleanup(props->transferer);
1361         ast_channel_cleanup(props->transfer_target);
1362         ast_channel_cleanup(props->recall_target);
1363         ast_string_field_free_memory(props);
1364         ast_cond_destroy(&props->cond);
1365 }
1366
1367 /*!
1368  * \internal
1369  * \brief Determine the transfer context to use.
1370  * \since 12.0.0
1371  *
1372  * \param transferer Channel initiating the transfer.
1373  * \param context User supplied context if available.  May be NULL.
1374  *
1375  * \return The context to use for the transfer.
1376  */
1377 static const char *get_transfer_context(struct ast_channel *transferer, const char *context)
1378 {
1379         if (!ast_strlen_zero(context)) {
1380                 return context;
1381         }
1382         context = pbx_builtin_getvar_helper(transferer, "TRANSFER_CONTEXT");
1383         if (!ast_strlen_zero(context)) {
1384                 return context;
1385         }
1386         context = ast_channel_macrocontext(transferer);
1387         if (!ast_strlen_zero(context)) {
1388                 return context;
1389         }
1390         context = ast_channel_context(transferer);
1391         if (!ast_strlen_zero(context)) {
1392                 return context;
1393         }
1394         return "default";
1395 }
1396
1397 /*!
1398  * \brief Allocate and initialize attended transfer properties
1399  *
1400  * \param transferer The channel performing the attended transfer
1401  * \param context Suggestion for what context the transfer target extension can be found in
1402  *
1403  * \retval NULL Failure to allocate or initialize
1404  * \retval non-NULL Newly allocated properties
1405  */
1406 static struct attended_transfer_properties *attended_transfer_properties_alloc(
1407         struct ast_channel *transferer, const char *context)
1408 {
1409         struct attended_transfer_properties *props;
1410         char *tech;
1411         char *addr;
1412         char *serial;
1413         RAII_VAR(struct ast_features_xfer_config *, xfer_cfg, NULL, ao2_cleanup);
1414         struct ast_flags *transferer_features;
1415
1416         props = ao2_alloc(sizeof(*props), attended_transfer_properties_destructor);
1417         if (!props || ast_string_field_init(props, 64)) {
1418                 return NULL;
1419         }
1420
1421         ast_cond_init(&props->cond, NULL);
1422
1423         props->target_framehook_id = -1;
1424         props->transferer = ast_channel_ref(transferer);
1425
1426         ast_channel_lock(props->transferer);
1427         xfer_cfg = ast_get_chan_features_xfer_config(props->transferer);
1428         if (!xfer_cfg) {
1429                 ast_log(LOG_ERROR, "Unable to get transfer configuration from channel %s\n", ast_channel_name(props->transferer));
1430                 ao2_ref(props, -1);
1431                 return NULL;
1432         }
1433         transferer_features = ast_bridge_features_ds_get(props->transferer);
1434         if (transferer_features) {
1435                 props->transferer_features = *transferer_features;
1436         }
1437         props->atxferdropcall = xfer_cfg->atxferdropcall;
1438         props->atxfercallbackretries = xfer_cfg->atxfercallbackretries;
1439         props->atxfernoanswertimeout = xfer_cfg->atxfernoanswertimeout;
1440         props->atxferloopdelay = xfer_cfg->atxferloopdelay;
1441         ast_string_field_set(props, context, get_transfer_context(transferer, context));
1442         ast_string_field_set(props, failsound, xfer_cfg->xferfailsound);
1443         ast_string_field_set(props, xfersound, xfer_cfg->xfersound);
1444
1445         tech = ast_strdupa(ast_channel_name(props->transferer));
1446         addr = strchr(tech, '/');
1447         if (!addr) {
1448                 ast_log(LOG_ERROR, "Transferer channel name does not follow typical channel naming format (tech/address)\n");
1449                 ast_channel_unref(props->transferer);
1450                 return NULL;
1451         }
1452         *addr++ = '\0';
1453         serial = strrchr(addr, '-');
1454         if (serial) {
1455                 *serial = '\0';
1456         }
1457         ast_string_field_set(props, transferer_type, tech);
1458         ast_string_field_set(props, transferer_addr, addr);
1459
1460         ast_channel_unlock(props->transferer);
1461
1462         ast_debug(1, "Allocated attended transfer properties %p for transfer from %s\n",
1463                         props, ast_channel_name(props->transferer));
1464         return props;
1465 }
1466
1467 /*!
1468  * \brief Free backlog of stimuli in the queue
1469  */
1470 static void clear_stimulus_queue(struct attended_transfer_properties *props)
1471 {
1472         struct stimulus_list *list;
1473         SCOPED_AO2LOCK(lock, props);
1474
1475         while ((list = AST_LIST_REMOVE_HEAD(&props->stimulus_queue, next))) {
1476                 ast_free(list);
1477         }
1478 }
1479
1480 /*!
1481  * \brief Initiate shutdown of attended transfer properties
1482  *
1483  * Calling this indicates that the attended transfer properties are no longer needed
1484  * because the transfer operation has concluded.
1485  */
1486 static void attended_transfer_properties_shutdown(struct attended_transfer_properties *props)
1487 {
1488         ast_debug(1, "Shutting down attended transfer %p\n", props);
1489
1490         if (props->transferee_bridge) {
1491                 bridge_basic_change_personality(props->transferee_bridge,
1492                                 BRIDGE_BASIC_PERSONALITY_NORMAL, NULL);
1493                 ast_bridge_merge_inhibit(props->transferee_bridge, -1);
1494         }
1495
1496         if (props->target_bridge) {
1497                 ast_bridge_destroy(props->target_bridge, 0);
1498                 props->target_bridge = NULL;
1499         }
1500
1501         if (props->transferer) {
1502                 ast_channel_remove_bridge_role(props->transferer, AST_TRANSFERER_ROLE_NAME);
1503         }
1504
1505         clear_stimulus_queue(props);
1506
1507         ao2_cleanup(props);
1508 }
1509
1510 static void stimulate_attended_transfer(struct attended_transfer_properties *props,
1511                 enum attended_transfer_stimulus stimulus)
1512 {
1513         struct stimulus_list *list;
1514
1515         list = ast_calloc(1, sizeof(*list));
1516         if (!list) {
1517                 ast_log(LOG_ERROR, "Unable to push event to attended transfer queue. Expect transfer to fail\n");
1518                 return;
1519         }
1520
1521         list->stimulus = stimulus;
1522         ao2_lock(props);
1523         AST_LIST_INSERT_TAIL(&props->stimulus_queue, list, next);
1524         ast_cond_signal(&props->cond);
1525         ao2_unlock(props);
1526 }
1527
1528 /*!
1529  * \brief Get a desired transfer party for a bridge the transferer is not in.
1530  *
1531  * \param bridge The bridge to get the party from. May be NULL.
1532  * \param[out] party The lone channel in the bridge. Will be set NULL if bridge is NULL or multiple parties are present.
1533  */
1534 static void get_transfer_party_non_transferer_bridge(struct ast_bridge *bridge,
1535                 struct ast_channel **party)
1536 {
1537         if (bridge && bridge->num_channels == 1) {
1538                 *party = ast_channel_ref(AST_LIST_FIRST(&bridge->channels)->chan);
1539         } else {
1540                 *party = NULL;
1541         }
1542 }
1543
1544 /*!
1545  * \brief Get the transferee and transfer target when the transferer is in a bridge with
1546  * one of the desired parties.
1547  *
1548  * \param transferer_bridge The bridge the transferer is in
1549  * \param other_bridge The bridge the transferer is not in. May be NULL.
1550  * \param transferer The transferer party
1551  * \param[out] transferer_peer The party that is in the bridge with the transferer
1552  * \param[out] other_party The party that is in the other_bridge
1553  */
1554 static void get_transfer_parties_transferer_bridge(struct ast_bridge *transferer_bridge,
1555                 struct ast_bridge *other_bridge, struct ast_channel *transferer,
1556                 struct ast_channel **transferer_peer, struct ast_channel **other_party)
1557 {
1558         *transferer_peer = ast_bridge_peer(transferer_bridge, transferer);
1559         get_transfer_party_non_transferer_bridge(other_bridge, other_party);
1560 }
1561
1562 /*!
1563  * \brief determine transferee and transfer target for an attended transfer
1564  *
1565  * In builtin attended transfers, there is a single transferer channel that jumps between
1566  * the two bridges involved. At the time the attended transfer occurs, the transferer could
1567  * be in either bridge, so determining the parties is a bit more complex than normal.
1568  *
1569  * The method used here is to determine which of the two bridges the transferer is in, and
1570  * grabbing the peer from that bridge. The other bridge, if it only has a single channel in it,
1571  * has the other desired channel.
1572  *
1573  * \param transferer The channel performing the transfer
1574  * \param transferee_bridge The bridge that the transferee is in
1575  * \param target_bridge The bridge that the transfer target is in
1576  * \param[out] transferee The transferee channel
1577  * \param[out] transfer_target The transfer target channel
1578  */
1579 static void get_transfer_parties(struct ast_channel *transferer, struct ast_bridge *transferee_bridge,
1580                 struct ast_bridge *target_bridge, struct ast_channel **transferee,
1581                 struct ast_channel **transfer_target)
1582 {
1583         struct ast_bridge *transferer_bridge;
1584
1585         ast_channel_lock(transferer);
1586         transferer_bridge = ast_channel_get_bridge(transferer);
1587         ast_channel_unlock(transferer);
1588
1589         if (transferer_bridge == transferee_bridge) {
1590                 get_transfer_parties_transferer_bridge(transferee_bridge, target_bridge,
1591                                 transferer, transferee, transfer_target);
1592         } else if (transferer_bridge == target_bridge) {
1593                 get_transfer_parties_transferer_bridge(target_bridge, transferee_bridge,
1594                                 transferer, transfer_target, transferee);
1595         } else {
1596                 get_transfer_party_non_transferer_bridge(transferee_bridge, transferee);
1597                 get_transfer_party_non_transferer_bridge(target_bridge, transfer_target);
1598         }
1599
1600         ao2_cleanup(transferer_bridge);
1601 }
1602
1603 /*!
1604  * \brief Send a stasis publication for a successful attended transfer
1605  */
1606 static void publish_transfer_success(struct attended_transfer_properties *props,
1607                 struct ast_channel *transferee_channel, struct ast_channel *target_channel)
1608 {
1609         struct ast_attended_transfer_message *transfer_msg;
1610
1611         transfer_msg = ast_attended_transfer_message_create(0, props->transferer,
1612                         props->transferee_bridge, props->transferer, props->target_bridge,
1613                         transferee_channel, target_channel);
1614
1615         if (!transfer_msg) {
1616                 ast_log(LOG_ERROR, "Unable to publish successful attended transfer from %s\n",
1617                                 ast_channel_name(props->transferer));
1618                 return;
1619         }
1620
1621         ast_attended_transfer_message_add_merge(transfer_msg, props->transferee_bridge);
1622         ast_bridge_publish_attended_transfer(transfer_msg);
1623         ao2_cleanup(transfer_msg);
1624 }
1625
1626 /*!
1627  * \brief Send a stasis publication for an attended transfer that ends in a threeway call
1628  */
1629 static void publish_transfer_threeway(struct attended_transfer_properties *props,
1630                 struct ast_channel *transferee_channel, struct ast_channel *target_channel)
1631 {
1632         struct ast_attended_transfer_message *transfer_msg;
1633
1634         transfer_msg = ast_attended_transfer_message_create(0, props->transferer,
1635                         props->transferee_bridge, props->transferer, props->target_bridge,
1636                         transferee_channel, target_channel);
1637
1638         if (!transfer_msg) {
1639                 ast_log(LOG_ERROR, "Unable to publish successful three-way transfer from %s\n",
1640                                 ast_channel_name(props->transferer));
1641                 return;
1642         }
1643
1644         ast_attended_transfer_message_add_threeway(transfer_msg, props->transferer,
1645                         props->transferee_bridge);
1646         ast_bridge_publish_attended_transfer(transfer_msg);
1647         ao2_cleanup(transfer_msg);
1648 }
1649
1650 /*!
1651  * \brief Send a stasis publication for a failed attended transfer
1652  */
1653 static void publish_transfer_fail(struct attended_transfer_properties *props)
1654 {
1655         struct ast_attended_transfer_message *transfer_msg;
1656
1657         transfer_msg = ast_attended_transfer_message_create(0, props->transferer,
1658                         props->transferee_bridge, props->transferer, props->target_bridge,
1659                         NULL, NULL);
1660
1661         if (!transfer_msg) {
1662                 ast_log(LOG_ERROR, "Unable to publish failed transfer from %s\n",
1663                                 ast_channel_name(props->transferer));
1664                 return;
1665         }
1666
1667         transfer_msg->result = AST_BRIDGE_TRANSFER_FAIL;
1668         ast_bridge_publish_attended_transfer(transfer_msg);
1669         ao2_cleanup(transfer_msg);
1670 }
1671
1672 /*!
1673  * \brief Helper method to play a sound on a channel in a bridge
1674  *
1675  * \param chan The channel to play the sound to
1676  * \param sound The sound to play
1677  */
1678 static void play_sound(struct ast_channel *chan, const char *sound)
1679 {
1680         RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
1681
1682         ast_channel_lock(chan);
1683         bridge_channel = ast_channel_get_bridge_channel(chan);
1684         ast_channel_unlock(chan);
1685
1686         if (!bridge_channel) {
1687                 return;
1688         }
1689
1690         ast_bridge_channel_queue_playfile(bridge_channel, NULL, sound, NULL);
1691 }
1692
1693 /*!
1694  * \brief Helper method to place a channel in a bridge on hold
1695  */
1696 static void hold(struct ast_channel *chan)
1697 {
1698         RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
1699
1700         if (chan) {
1701                 ast_channel_lock(chan);
1702                 bridge_channel = ast_channel_get_bridge_channel(chan);
1703                 ast_channel_unlock(chan);
1704
1705                 ast_assert(bridge_channel != NULL);
1706
1707                 ast_bridge_channel_write_hold(bridge_channel, NULL);
1708         }
1709 }
1710
1711 /*!
1712  * \brief Helper method to take a channel in a bridge off hold
1713  */
1714 static void unhold(struct ast_channel *chan)
1715 {
1716         RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
1717
1718         ast_channel_lock(chan);
1719         bridge_channel = ast_channel_get_bridge_channel(chan);
1720         ast_channel_unlock(chan);
1721
1722         ast_assert(bridge_channel != NULL);
1723
1724         ast_bridge_channel_write_unhold(bridge_channel);
1725 }
1726
1727 /*!
1728  * \brief Helper method to send a ringing indication to a channel in a bridge
1729  */
1730 static void ringing(struct ast_channel *chan)
1731 {
1732         RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
1733
1734         ast_channel_lock(chan);
1735         bridge_channel = ast_channel_get_bridge_channel(chan);
1736         ast_channel_unlock(chan);
1737
1738         ast_assert(bridge_channel != NULL);
1739
1740         ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_RINGING, NULL, 0);
1741 }
1742
1743 /*!
1744  * \brief Helper method to send a ringing indication to all channels in a bridge
1745  */
1746 static void bridge_ringing(struct ast_bridge *bridge)
1747 {
1748         struct ast_frame ringing = {
1749                 .frametype = AST_FRAME_CONTROL,
1750                 .subclass.integer = AST_CONTROL_RINGING,
1751         };
1752
1753         ast_bridge_queue_everyone_else(bridge, NULL, &ringing);
1754 }
1755
1756 /*!
1757  * \brief Helper method to send a hold frame to all channels in a bridge
1758  */
1759 static void bridge_hold(struct ast_bridge *bridge)
1760 {
1761         struct ast_frame hold = {
1762                 .frametype = AST_FRAME_CONTROL,
1763                 .subclass.integer = AST_CONTROL_HOLD,
1764         };
1765
1766         ast_bridge_queue_everyone_else(bridge, NULL, &hold);
1767 }
1768
1769 /*!
1770  * \brief Helper method to send an unhold frame to all channels in a bridge
1771  */
1772 static void bridge_unhold(struct ast_bridge *bridge)
1773 {
1774         struct ast_frame unhold = {
1775                 .frametype = AST_FRAME_CONTROL,
1776                 .subclass.integer = AST_CONTROL_UNHOLD,
1777         };
1778
1779         ast_bridge_queue_everyone_else(bridge, NULL, &unhold);
1780 }
1781
1782 /*!
1783  * \brief Wrapper for \ref bridge_do_move
1784  */
1785 static int bridge_move(struct ast_bridge *dest, struct ast_bridge *src, struct ast_channel *channel, struct ast_channel *swap)
1786 {
1787         int res;
1788         RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
1789
1790         ast_bridge_lock_both(src, dest);
1791
1792         ast_channel_lock(channel);
1793         bridge_channel = ast_channel_get_bridge_channel(channel);
1794         ast_channel_unlock(channel);
1795
1796         ast_assert(bridge_channel != NULL);
1797
1798         ao2_lock(bridge_channel);
1799         bridge_channel->swap = swap;
1800         ao2_unlock(bridge_channel);
1801
1802         res = bridge_do_move(dest, bridge_channel, 1, 0);
1803
1804         ast_bridge_unlock(dest);
1805         ast_bridge_unlock(src);
1806
1807         return res;
1808 }
1809
1810 /*!
1811  * \brief Wrapper for \ref bridge_do_merge
1812  */
1813 static void bridge_merge(struct ast_bridge *dest, struct ast_bridge *src, struct ast_channel **kick_channels, unsigned int num_channels)
1814 {
1815         struct ast_bridge_channel **kick_bridge_channels = num_channels ?
1816                 ast_alloca(num_channels * sizeof(*kick_bridge_channels)) : NULL;
1817         int i;
1818         int num_bridge_channels = 0;
1819
1820         ast_bridge_lock_both(dest, src);
1821
1822         for (i = 0; i < num_channels; ++i) {
1823                 struct ast_bridge_channel *kick_bridge_channel;
1824
1825                 kick_bridge_channel = bridge_find_channel(src, kick_channels[i]);
1826                 if (!kick_bridge_channel) {
1827                         kick_bridge_channel = bridge_find_channel(dest, kick_channels[i]);
1828                 }
1829
1830                 /* It's possible (and fine) for the bridge channel to be NULL at this point if the
1831                  * channel has hung up already. If that happens, we can just remove it from the list
1832                  * of bridge channels to kick from the bridge
1833                  */
1834                 if (!kick_bridge_channel) {
1835                         continue;
1836                 }
1837
1838                 kick_bridge_channels[num_bridge_channels++] = kick_bridge_channel;
1839         }
1840
1841         bridge_do_merge(dest, src, kick_bridge_channels, num_bridge_channels, 0);
1842         ast_bridge_unlock(dest);
1843         ast_bridge_unlock(src);
1844 }
1845
1846 /*!
1847  * \brief Flags that indicate properties of attended transfer states
1848  */
1849 enum attended_transfer_state_flags {
1850         /*! This state requires that the timer be reset when entering the state */
1851         TRANSFER_STATE_FLAG_TIMER_RESET = (1 << 0),
1852         /*! This state's timer uses atxferloopdelay */
1853         TRANSFER_STATE_FLAG_TIMER_LOOP_DELAY = (1 << 1),
1854         /*! This state's timer uses atxfernoanswertimeout */
1855         TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER = (1 << 2),
1856         /*! This state has a time limit associated with it */
1857         TRANSFER_STATE_FLAG_TIMED = (TRANSFER_STATE_FLAG_TIMER_RESET |
1858                         TRANSFER_STATE_FLAG_TIMER_LOOP_DELAY | TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER),
1859         /*! This state does not transition to any other states */
1860         TRANSFER_STATE_FLAG_TERMINAL = (1 << 3),
1861 };
1862
1863 static int calling_target_enter(struct attended_transfer_properties *props);
1864 static enum attended_transfer_state calling_target_exit(struct attended_transfer_properties *props,
1865                 enum attended_transfer_stimulus stimulus);
1866
1867 static int hesitant_enter(struct attended_transfer_properties *props);
1868 static enum attended_transfer_state hesitant_exit(struct attended_transfer_properties *props,
1869                 enum attended_transfer_stimulus stimulus);
1870
1871 static int rebridge_enter(struct attended_transfer_properties *props);
1872
1873 static int resume_enter(struct attended_transfer_properties *props);
1874
1875 static int threeway_enter(struct attended_transfer_properties *props);
1876
1877 static int consulting_enter(struct attended_transfer_properties *props);
1878 static enum attended_transfer_state consulting_exit(struct attended_transfer_properties *props,
1879                 enum attended_transfer_stimulus stimulus);
1880
1881 static int double_checking_enter(struct attended_transfer_properties *props);
1882 static enum attended_transfer_state double_checking_exit(struct attended_transfer_properties *props,
1883                 enum attended_transfer_stimulus stimulus);
1884
1885 static int complete_enter(struct attended_transfer_properties *props);
1886
1887 static int blond_enter(struct attended_transfer_properties *props);
1888
1889 static int blond_nonfinal_enter(struct attended_transfer_properties *props);
1890 static enum attended_transfer_state blond_nonfinal_exit(struct attended_transfer_properties *props,
1891                 enum attended_transfer_stimulus stimulus);
1892
1893 static int recalling_enter(struct attended_transfer_properties *props);
1894 static enum attended_transfer_state recalling_exit(struct attended_transfer_properties *props,
1895                 enum attended_transfer_stimulus stimulus);
1896
1897 static int wait_to_retransfer_enter(struct attended_transfer_properties *props);
1898 static enum attended_transfer_state wait_to_retransfer_exit(struct attended_transfer_properties *props,
1899                 enum attended_transfer_stimulus stimulus);
1900
1901 static int retransfer_enter(struct attended_transfer_properties *props);
1902 static enum attended_transfer_state retransfer_exit(struct attended_transfer_properties *props,
1903                 enum attended_transfer_stimulus stimulus);
1904
1905 static int wait_to_recall_enter(struct attended_transfer_properties *props);
1906 static enum attended_transfer_state wait_to_recall_exit(struct attended_transfer_properties *props,
1907                 enum attended_transfer_stimulus stimulus);
1908
1909 static int fail_enter(struct attended_transfer_properties *props);
1910
1911 /*!
1912  * \brief Properties of an attended transfer state
1913  */
1914 struct attended_transfer_state_properties {
1915         /*! The name of the state. Used for debugging */
1916         const char *state_name;
1917         /*! Function used to enter a state */
1918         int (*enter)(struct attended_transfer_properties *props);
1919         /*!
1920          * Function used to exit a state
1921          * This is used both to determine what the next state
1922          * to transition to will be and to perform any cleanup
1923          * necessary before exiting the current state.
1924          */
1925         enum attended_transfer_state (*exit)(struct attended_transfer_properties *props,
1926                         enum attended_transfer_stimulus stimulus);
1927         /*! Flags associated with this state */
1928         enum attended_transfer_state_flags flags;
1929 };
1930
1931 static const struct attended_transfer_state_properties state_properties[] = {
1932         [TRANSFER_CALLING_TARGET] = {
1933                 .state_name = "Calling Target",
1934                 .enter = calling_target_enter,
1935                 .exit = calling_target_exit,
1936                 .flags = TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER | TRANSFER_STATE_FLAG_TIMER_RESET,
1937         },
1938         [TRANSFER_HESITANT] = {
1939                 .state_name = "Hesitant",
1940                 .enter = hesitant_enter,
1941                 .exit = hesitant_exit,
1942                 .flags = TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER,
1943         },
1944         [TRANSFER_REBRIDGE] = {
1945                 .state_name = "Rebridge",
1946                 .enter = rebridge_enter,
1947                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
1948         },
1949         [TRANSFER_RESUME] = {
1950                 .state_name = "Resume",
1951                 .enter = resume_enter,
1952                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
1953         },
1954         [TRANSFER_THREEWAY] = {
1955                 .state_name = "Threeway",
1956                 .enter = threeway_enter,
1957                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
1958         },
1959         [TRANSFER_CONSULTING] = {
1960                 .state_name = "Consulting",
1961                 .enter = consulting_enter,
1962                 .exit = consulting_exit,
1963         },
1964         [TRANSFER_DOUBLECHECKING] = {
1965                 .state_name = "Double Checking",
1966                 .enter = double_checking_enter,
1967                 .exit = double_checking_exit,
1968         },
1969         [TRANSFER_COMPLETE] = {
1970                 .state_name = "Complete",
1971                 .enter = complete_enter,
1972                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
1973         },
1974         [TRANSFER_BLOND] = {
1975                 .state_name = "Blond",
1976                 .enter = blond_enter,
1977                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
1978         },
1979         [TRANSFER_BLOND_NONFINAL] = {
1980                 .state_name = "Blond Non-Final",
1981                 .enter = blond_nonfinal_enter,
1982                 .exit = blond_nonfinal_exit,
1983                 .flags = TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER,
1984         },
1985         [TRANSFER_RECALLING] = {
1986                 .state_name = "Recalling",
1987                 .enter = recalling_enter,
1988                 .exit = recalling_exit,
1989                 .flags = TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER | TRANSFER_STATE_FLAG_TIMER_RESET,
1990         },
1991         [TRANSFER_WAIT_TO_RETRANSFER] = {
1992                 .state_name = "Wait to Retransfer",
1993                 .enter = wait_to_retransfer_enter,
1994                 .exit = wait_to_retransfer_exit,
1995                 .flags = TRANSFER_STATE_FLAG_TIMER_RESET | TRANSFER_STATE_FLAG_TIMER_LOOP_DELAY,
1996         },
1997         [TRANSFER_RETRANSFER] = {
1998                 .state_name = "Retransfer",
1999                 .enter = retransfer_enter,
2000                 .exit = retransfer_exit,
2001                 .flags = TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER | TRANSFER_STATE_FLAG_TIMER_RESET,
2002         },
2003         [TRANSFER_WAIT_TO_RECALL] = {
2004                 .state_name = "Wait to Recall",
2005                 .enter = wait_to_recall_enter,
2006                 .exit = wait_to_recall_exit,
2007                 .flags = TRANSFER_STATE_FLAG_TIMER_RESET | TRANSFER_STATE_FLAG_TIMER_LOOP_DELAY,
2008         },
2009         [TRANSFER_FAIL] = {
2010                 .state_name = "Fail",
2011                 .enter = fail_enter,
2012                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
2013         },
2014 };
2015
2016 static int calling_target_enter(struct attended_transfer_properties *props)
2017 {
2018         return bridge_move(props->target_bridge, props->transferee_bridge, props->transferer, NULL);
2019 }
2020
2021 static enum attended_transfer_state calling_target_exit(struct attended_transfer_properties *props,
2022                 enum attended_transfer_stimulus stimulus)
2023 {
2024         switch (stimulus) {
2025         case STIMULUS_TRANSFEREE_HANGUP:
2026                 play_sound(props->transferer, props->failsound);
2027                 publish_transfer_fail(props);
2028                 return TRANSFER_FAIL;
2029         case STIMULUS_DTMF_ATXFER_COMPLETE:
2030         case STIMULUS_TRANSFERER_HANGUP:
2031                 bridge_unhold(props->transferee_bridge);
2032                 return props->atxferdropcall ? TRANSFER_BLOND : TRANSFER_BLOND_NONFINAL;
2033         case STIMULUS_TRANSFER_TARGET_ANSWER:
2034                 return TRANSFER_CONSULTING;
2035         case STIMULUS_TRANSFER_TARGET_HANGUP:
2036         case STIMULUS_TIMEOUT:
2037         case STIMULUS_DTMF_ATXFER_ABORT:
2038                 play_sound(props->transferer, props->failsound);
2039                 return TRANSFER_REBRIDGE;
2040         case STIMULUS_DTMF_ATXFER_THREEWAY:
2041                 bridge_unhold(props->transferee_bridge);
2042                 return TRANSFER_THREEWAY;
2043         case STIMULUS_DTMF_ATXFER_SWAP:
2044                 return TRANSFER_HESITANT;
2045         case STIMULUS_NONE:
2046         case STIMULUS_RECALL_TARGET_ANSWER:
2047         case STIMULUS_RECALL_TARGET_HANGUP:
2048         default:
2049                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2050                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2051                 return props->state;
2052         }
2053 }
2054
2055 static int hesitant_enter(struct attended_transfer_properties *props)
2056 {
2057         if (bridge_move(props->transferee_bridge, props->target_bridge, props->transferer, NULL)) {
2058                 return -1;
2059         }
2060
2061         unhold(props->transferer);
2062         return 0;
2063 }
2064
2065 static enum attended_transfer_state hesitant_exit(struct attended_transfer_properties *props,
2066                 enum attended_transfer_stimulus stimulus)
2067 {
2068         switch (stimulus) {
2069         case STIMULUS_TRANSFEREE_HANGUP:
2070                 play_sound(props->transferer, props->failsound);
2071                 publish_transfer_fail(props);
2072                 return TRANSFER_FAIL;
2073         case STIMULUS_DTMF_ATXFER_COMPLETE:
2074         case STIMULUS_TRANSFERER_HANGUP:
2075                 return props->atxferdropcall ? TRANSFER_BLOND : TRANSFER_BLOND_NONFINAL;
2076         case STIMULUS_TRANSFER_TARGET_ANSWER:
2077                 return TRANSFER_DOUBLECHECKING;
2078         case STIMULUS_TRANSFER_TARGET_HANGUP:
2079         case STIMULUS_TIMEOUT:
2080         case STIMULUS_DTMF_ATXFER_ABORT:
2081                 play_sound(props->transferer, props->failsound);
2082                 return TRANSFER_RESUME;
2083         case STIMULUS_DTMF_ATXFER_THREEWAY:
2084                 return TRANSFER_THREEWAY;
2085         case STIMULUS_DTMF_ATXFER_SWAP:
2086                 hold(props->transferer);
2087                 return TRANSFER_CALLING_TARGET;
2088         case STIMULUS_NONE:
2089         case STIMULUS_RECALL_TARGET_HANGUP:
2090         case STIMULUS_RECALL_TARGET_ANSWER:
2091         default:
2092                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2093                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2094                 return props->state;
2095         }
2096 }
2097
2098 static int rebridge_enter(struct attended_transfer_properties *props)
2099 {
2100         if (bridge_move(props->transferee_bridge, props->target_bridge,
2101                         props->transferer, NULL)) {
2102                 return -1;
2103         }
2104
2105         unhold(props->transferer);
2106         return 0;
2107 }
2108
2109 static int resume_enter(struct attended_transfer_properties *props)
2110 {
2111         return 0;
2112 }
2113
2114 static int threeway_enter(struct attended_transfer_properties *props)
2115 {
2116         struct ast_channel *transferee_channel;
2117         struct ast_channel *target_channel;
2118
2119         get_transfer_parties(props->transferer, props->transferee_bridge, props->target_bridge,
2120                         &transferee_channel, &target_channel);
2121         bridge_merge(props->transferee_bridge, props->target_bridge, NULL, 0);
2122         play_sound(props->transfer_target, props->xfersound);
2123         play_sound(props->transferer, props->xfersound);
2124         publish_transfer_threeway(props, transferee_channel, target_channel);
2125
2126         ast_channel_cleanup(transferee_channel);
2127         ast_channel_cleanup(target_channel);
2128         return 0;
2129 }
2130
2131 static int consulting_enter(struct attended_transfer_properties *props)
2132 {
2133         return 0;
2134 }
2135
2136 static enum attended_transfer_state consulting_exit(struct attended_transfer_properties *props,
2137                 enum attended_transfer_stimulus stimulus)
2138 {
2139         switch (stimulus) {
2140         case STIMULUS_TRANSFEREE_HANGUP:
2141                 /* This is a one-of-a-kind event. The transferer and transfer target are talking in
2142                  * one bridge, and the transferee has hung up in a separate bridge. In this case, we
2143                  * will change the personality of the transfer target bridge back to normal, and play
2144                  * a sound to the transferer to indicate the transferee is gone.
2145                  */
2146                 bridge_basic_change_personality(props->target_bridge, BRIDGE_BASIC_PERSONALITY_NORMAL, NULL);
2147                 play_sound(props->transferer, props->failsound);
2148                 ast_bridge_merge_inhibit(props->target_bridge, -1);
2149                 /* These next two lines are here to ensure that our reference to the target bridge
2150                  * is cleaned up properly and that the target bridge is not destroyed when the
2151                  * monitor thread exits
2152                  */
2153                 ao2_ref(props->target_bridge, -1);
2154                 props->target_bridge = NULL;
2155                 return TRANSFER_FAIL;
2156         case STIMULUS_TRANSFERER_HANGUP:
2157         case STIMULUS_DTMF_ATXFER_COMPLETE:
2158                 /* We know the transferer is in the target_bridge, so take the other bridge off hold */
2159                 bridge_unhold(props->transferee_bridge);
2160                 return TRANSFER_COMPLETE;
2161         case STIMULUS_TRANSFER_TARGET_HANGUP:
2162         case STIMULUS_DTMF_ATXFER_ABORT:
2163                 play_sound(props->transferer, props->failsound);
2164                 return TRANSFER_REBRIDGE;
2165         case STIMULUS_DTMF_ATXFER_THREEWAY:
2166                 bridge_unhold(props->transferee_bridge);
2167                 return TRANSFER_THREEWAY;
2168         case STIMULUS_DTMF_ATXFER_SWAP:
2169                 hold(props->transferer);
2170                 bridge_move(props->transferee_bridge, props->target_bridge, props->transferer, NULL);
2171                 unhold(props->transferer);
2172                 return TRANSFER_DOUBLECHECKING;
2173         case STIMULUS_NONE:
2174         case STIMULUS_TIMEOUT:
2175         case STIMULUS_TRANSFER_TARGET_ANSWER:
2176         case STIMULUS_RECALL_TARGET_HANGUP:
2177         case STIMULUS_RECALL_TARGET_ANSWER:
2178         default:
2179                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2180                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2181                 return props->state;
2182         }
2183 }
2184
2185 static int double_checking_enter(struct attended_transfer_properties *props)
2186 {
2187         return 0;
2188 }
2189
2190 static enum attended_transfer_state double_checking_exit(struct attended_transfer_properties *props,
2191                 enum attended_transfer_stimulus stimulus)
2192 {
2193         switch (stimulus) {
2194         case STIMULUS_TRANSFEREE_HANGUP:
2195                 play_sound(props->transferer, props->failsound);
2196                 publish_transfer_fail(props);
2197                 return TRANSFER_FAIL;
2198         case STIMULUS_TRANSFERER_HANGUP:
2199         case STIMULUS_DTMF_ATXFER_COMPLETE:
2200                 /* We know the transferer is in the transferee, so take the other bridge off hold */
2201                 bridge_unhold(props->target_bridge);
2202                 return TRANSFER_COMPLETE;
2203         case STIMULUS_TRANSFER_TARGET_HANGUP:
2204         case STIMULUS_DTMF_ATXFER_ABORT:
2205                 play_sound(props->transferer, props->failsound);
2206                 return TRANSFER_RESUME;
2207         case STIMULUS_DTMF_ATXFER_THREEWAY:
2208                 bridge_unhold(props->target_bridge);
2209                 return TRANSFER_THREEWAY;
2210         case STIMULUS_DTMF_ATXFER_SWAP:
2211                 hold(props->transferer);
2212                 bridge_move(props->target_bridge, props->transferee_bridge, props->transferer, NULL);
2213                 unhold(props->transferer);
2214                 return TRANSFER_CONSULTING;
2215         case STIMULUS_NONE:
2216         case STIMULUS_TIMEOUT:
2217         case STIMULUS_TRANSFER_TARGET_ANSWER:
2218         case STIMULUS_RECALL_TARGET_HANGUP:
2219         case STIMULUS_RECALL_TARGET_ANSWER:
2220         default:
2221                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2222                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2223                 return props->state;
2224         }
2225 }
2226
2227 static int complete_enter(struct attended_transfer_properties *props)
2228 {
2229         struct ast_channel *transferee_channel;
2230         struct ast_channel *target_channel;
2231
2232         get_transfer_parties(props->transferer, props->transferee_bridge, props->target_bridge,
2233                         &transferee_channel, &target_channel);
2234         bridge_merge(props->transferee_bridge, props->target_bridge, &props->transferer, 1);
2235         play_sound(props->transfer_target, props->xfersound);
2236         publish_transfer_success(props, transferee_channel, target_channel);
2237
2238         ast_channel_cleanup(transferee_channel);
2239         ast_channel_cleanup(target_channel);
2240         return 0;
2241 }
2242
2243 static int blond_enter(struct attended_transfer_properties *props)
2244 {
2245         struct ast_channel *transferee_channel;
2246         struct ast_channel *target_channel;
2247
2248         get_transfer_parties(props->transferer, props->transferee_bridge, props->target_bridge,
2249                         &transferee_channel, &target_channel);
2250         bridge_merge(props->transferee_bridge, props->target_bridge, &props->transferer, 1);
2251         ringing(props->transfer_target);
2252         publish_transfer_success(props, transferee_channel, target_channel);
2253
2254         ast_channel_cleanup(transferee_channel);
2255         ast_channel_cleanup(target_channel);
2256         return 0;
2257 }
2258
2259 static int blond_nonfinal_enter(struct attended_transfer_properties *props)
2260 {
2261         int res;
2262         props->superstate = SUPERSTATE_RECALL;
2263         props->recall_target = ast_channel_ref(props->transfer_target);
2264         res = blond_enter(props);
2265         props->transfer_target = ast_channel_unref(props->transfer_target);
2266         return res;
2267 }
2268
2269 static enum attended_transfer_state blond_nonfinal_exit(struct attended_transfer_properties *props,
2270                 enum attended_transfer_stimulus stimulus)
2271 {
2272         switch (stimulus) {
2273         case STIMULUS_TRANSFEREE_HANGUP:
2274                 return TRANSFER_FAIL;
2275         case STIMULUS_RECALL_TARGET_ANSWER:
2276                 return TRANSFER_RESUME;
2277         case STIMULUS_TIMEOUT:
2278                 ast_softhangup(props->recall_target, AST_SOFTHANGUP_EXPLICIT);
2279                 props->recall_target = ast_channel_unref(props->recall_target);
2280         case STIMULUS_RECALL_TARGET_HANGUP:
2281                 return TRANSFER_RECALLING;
2282         case STIMULUS_NONE:
2283         case STIMULUS_DTMF_ATXFER_ABORT:
2284         case STIMULUS_DTMF_ATXFER_COMPLETE:
2285         case STIMULUS_DTMF_ATXFER_THREEWAY:
2286         case STIMULUS_DTMF_ATXFER_SWAP:
2287         case STIMULUS_TRANSFERER_HANGUP:
2288         case STIMULUS_TRANSFER_TARGET_HANGUP:
2289         case STIMULUS_TRANSFER_TARGET_ANSWER:
2290         default:
2291                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2292                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2293                 return props->state;
2294         }
2295 }
2296
2297 /*!
2298  * \brief Dial callback when attempting to recall the original transferer channel
2299  *
2300  * This is how we can monitor if the recall target has answered or has hung up.
2301  * If one of the two is detected, then an appropriate stimulus is sent to the
2302  * attended transfer monitor thread.
2303  */
2304 static void recall_callback(struct ast_dial *dial)
2305 {
2306         struct attended_transfer_properties *props = ast_dial_get_user_data(dial);
2307
2308         switch (ast_dial_state(dial)) {
2309         default:
2310         case AST_DIAL_RESULT_INVALID:
2311         case AST_DIAL_RESULT_FAILED:
2312         case AST_DIAL_RESULT_TIMEOUT:
2313         case AST_DIAL_RESULT_HANGUP:
2314         case AST_DIAL_RESULT_UNANSWERED:
2315                 /* Failure cases */
2316                 stimulate_attended_transfer(props, STIMULUS_RECALL_TARGET_HANGUP);
2317                 break;
2318         case AST_DIAL_RESULT_RINGING:
2319         case AST_DIAL_RESULT_PROGRESS:
2320         case AST_DIAL_RESULT_PROCEEDING:
2321         case AST_DIAL_RESULT_TRYING:
2322                 /* Don't care about these cases */
2323                 break;
2324         case AST_DIAL_RESULT_ANSWERED:
2325                 /* We struck gold! */
2326                 props->recall_target = ast_dial_answered_steal(dial);
2327                 stimulate_attended_transfer(props, STIMULUS_RECALL_TARGET_ANSWER);
2328                 break;
2329         }
2330 }
2331
2332
2333 static int recalling_enter(struct attended_transfer_properties *props)
2334 {
2335         RAII_VAR(struct ast_format_cap *, cap, ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT), ao2_cleanup);
2336
2337         if (!cap) {
2338                 return -1;
2339         }
2340
2341         ast_format_cap_append(cap, ast_format_slin, 0);
2342
2343         /* When we dial the transfer target, since we are communicating
2344          * with a local channel, we can place the local channel in a bridge
2345          * and then call out to it. When recalling the transferer, though, we
2346          * have to use the dialing API because the channel is not local.
2347          */
2348         props->dial = ast_dial_create();
2349         if (!props->dial) {
2350                 return -1;
2351         }
2352
2353         if (ast_dial_append(props->dial, props->transferer_type, props->transferer_addr, NULL)) {
2354                 return -1;
2355         }
2356
2357         if (ast_dial_prerun(props->dial, NULL, cap)) {
2358                 return -1;
2359         }
2360
2361         ast_dial_set_state_callback(props->dial, &recall_callback);
2362
2363         ao2_ref(props, +1);
2364         ast_dial_set_user_data(props->dial, props);
2365
2366         if (ast_dial_run(props->dial, NULL, 1) == AST_DIAL_RESULT_FAILED) {
2367                 ao2_ref(props, -1);
2368                 return -1;
2369         }
2370
2371         bridge_ringing(props->transferee_bridge);
2372         return 0;
2373 }
2374
2375 static enum attended_transfer_state recalling_exit(struct attended_transfer_properties *props,
2376                 enum attended_transfer_stimulus stimulus)
2377 {
2378         /* No matter what the outcome was, we need to kill off the dial */
2379         ast_dial_join(props->dial);
2380         ast_dial_destroy(props->dial);
2381         props->dial = NULL;
2382         /* This reference is the one we incremented for the dial state callback (recall_callback) to use */
2383         ao2_ref(props, -1);
2384
2385         switch (stimulus) {
2386         case STIMULUS_TRANSFEREE_HANGUP:
2387                 return TRANSFER_FAIL;
2388         case STIMULUS_TIMEOUT:
2389         case STIMULUS_RECALL_TARGET_HANGUP:
2390                 ++props->retry_attempts;
2391                 if (props->retry_attempts >= props->atxfercallbackretries) {
2392                         return TRANSFER_FAIL;
2393                 }
2394                 if (props->atxferloopdelay) {
2395                         return TRANSFER_WAIT_TO_RETRANSFER;
2396                 }
2397                 return TRANSFER_RETRANSFER;
2398         case STIMULUS_RECALL_TARGET_ANSWER:
2399                 /* Setting this datastore up will allow the transferer to have all of his
2400                  * call features set up automatically when the bridge changes back to a
2401                  * normal personality
2402                  */
2403                 ast_bridge_features_ds_set(props->recall_target, &props->transferer_features);
2404                 ast_channel_ref(props->recall_target);
2405                 if (ast_bridge_impart(props->transferee_bridge, props->recall_target, NULL, NULL,
2406                         AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
2407                         ast_hangup(props->recall_target);
2408                         return TRANSFER_FAIL;
2409                 }
2410                 return TRANSFER_RESUME;
2411         case STIMULUS_NONE:
2412         case STIMULUS_DTMF_ATXFER_ABORT:
2413         case STIMULUS_DTMF_ATXFER_COMPLETE:
2414         case STIMULUS_DTMF_ATXFER_THREEWAY:
2415         case STIMULUS_DTMF_ATXFER_SWAP:
2416         case STIMULUS_TRANSFER_TARGET_HANGUP:
2417         case STIMULUS_TRANSFER_TARGET_ANSWER:
2418         case STIMULUS_TRANSFERER_HANGUP:
2419         default:
2420                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2421                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2422                 return props->state;
2423         }
2424 }
2425
2426 static int wait_to_retransfer_enter(struct attended_transfer_properties *props)
2427 {
2428         bridge_hold(props->transferee_bridge);
2429         return 0;
2430 }
2431
2432 static enum attended_transfer_state wait_to_retransfer_exit(struct attended_transfer_properties *props,
2433                 enum attended_transfer_stimulus stimulus)
2434 {
2435         bridge_unhold(props->transferee_bridge);
2436         switch (stimulus) {
2437         case STIMULUS_TRANSFEREE_HANGUP:
2438                 return TRANSFER_FAIL;
2439         case STIMULUS_TIMEOUT:
2440                 return TRANSFER_RETRANSFER;
2441         case STIMULUS_NONE:
2442         case STIMULUS_DTMF_ATXFER_ABORT:
2443         case STIMULUS_DTMF_ATXFER_COMPLETE:
2444         case STIMULUS_DTMF_ATXFER_THREEWAY:
2445         case STIMULUS_DTMF_ATXFER_SWAP:
2446         case STIMULUS_TRANSFER_TARGET_HANGUP:
2447         case STIMULUS_TRANSFER_TARGET_ANSWER:
2448         case STIMULUS_TRANSFERER_HANGUP:
2449         case STIMULUS_RECALL_TARGET_HANGUP:
2450         case STIMULUS_RECALL_TARGET_ANSWER:
2451         default:
2452                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2453                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2454                 return props->state;
2455         }
2456 }
2457
2458 static int attach_framehook(struct attended_transfer_properties *props, struct ast_channel *channel);
2459
2460 static int retransfer_enter(struct attended_transfer_properties *props)
2461 {
2462         RAII_VAR(struct ast_format_cap *, cap, ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT), ao2_cleanup);
2463         char destination[AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2];
2464         int cause;
2465
2466         if (!cap) {
2467                 return -1;
2468         }
2469
2470         snprintf(destination, sizeof(destination), "%s@%s", props->exten, props->context);
2471
2472         ast_format_cap_append(cap, ast_format_slin, 0);
2473
2474         /* Get a channel that is the destination we wish to call */
2475         props->recall_target = ast_request("Local", cap, NULL, NULL, destination, &cause);
2476         if (!props->recall_target) {
2477                 ast_log(LOG_ERROR, "Unable to request outbound channel for recall target\n");
2478                 return -1;
2479         }
2480
2481         if (attach_framehook(props, props->recall_target)) {
2482                 ast_log(LOG_ERROR, "Unable to attach framehook to recall target\n");
2483                 ast_hangup(props->recall_target);
2484                 props->recall_target = NULL;
2485                 return -1;
2486         }
2487
2488         if (ast_call(props->recall_target, destination, 0)) {
2489                 ast_log(LOG_ERROR, "Unable to place outbound call to recall target\n");
2490                 ast_hangup(props->recall_target);
2491                 props->recall_target = NULL;
2492                 return -1;
2493         }
2494
2495         ast_channel_ref(props->recall_target);
2496         if (ast_bridge_impart(props->transferee_bridge, props->recall_target, NULL, NULL,
2497                 AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
2498                 ast_log(LOG_ERROR, "Unable to place recall target into bridge\n");
2499                 ast_hangup(props->recall_target);
2500                 return -1;
2501         }
2502
2503         return 0;
2504 }
2505
2506 static enum attended_transfer_state retransfer_exit(struct attended_transfer_properties *props,
2507                 enum attended_transfer_stimulus stimulus)
2508 {
2509         switch (stimulus) {
2510         case STIMULUS_TRANSFEREE_HANGUP:
2511                 return TRANSFER_FAIL;
2512         case STIMULUS_TIMEOUT:
2513                 ast_softhangup(props->recall_target, AST_SOFTHANGUP_EXPLICIT);
2514         case STIMULUS_RECALL_TARGET_HANGUP:
2515                 props->recall_target = ast_channel_unref(props->recall_target);
2516                 if (props->atxferloopdelay) {
2517                         return TRANSFER_WAIT_TO_RECALL;
2518                 }
2519                 return TRANSFER_RECALLING;
2520         case STIMULUS_RECALL_TARGET_ANSWER:
2521                 return TRANSFER_RESUME;
2522         case STIMULUS_NONE:
2523         case STIMULUS_DTMF_ATXFER_ABORT:
2524         case STIMULUS_DTMF_ATXFER_COMPLETE:
2525         case STIMULUS_DTMF_ATXFER_THREEWAY:
2526         case STIMULUS_DTMF_ATXFER_SWAP:
2527         case STIMULUS_TRANSFER_TARGET_HANGUP:
2528         case STIMULUS_TRANSFER_TARGET_ANSWER:
2529         case STIMULUS_TRANSFERER_HANGUP:
2530         default:
2531                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2532                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2533                 return props->state;
2534         }
2535 }
2536
2537 static int wait_to_recall_enter(struct attended_transfer_properties *props)
2538 {
2539         bridge_hold(props->transferee_bridge);
2540         return 0;
2541 }
2542
2543 static enum attended_transfer_state wait_to_recall_exit(struct attended_transfer_properties *props,
2544                 enum attended_transfer_stimulus stimulus)
2545 {
2546         bridge_unhold(props->transferee_bridge);
2547         switch (stimulus) {
2548         case STIMULUS_TRANSFEREE_HANGUP:
2549                 return TRANSFER_FAIL;
2550         case STIMULUS_TIMEOUT:
2551                 return TRANSFER_RECALLING;
2552         case STIMULUS_NONE:
2553         case STIMULUS_DTMF_ATXFER_ABORT:
2554         case STIMULUS_DTMF_ATXFER_COMPLETE:
2555         case STIMULUS_DTMF_ATXFER_THREEWAY:
2556         case STIMULUS_DTMF_ATXFER_SWAP:
2557         case STIMULUS_TRANSFER_TARGET_HANGUP:
2558         case STIMULUS_TRANSFER_TARGET_ANSWER:
2559         case STIMULUS_TRANSFERER_HANGUP:
2560         case STIMULUS_RECALL_TARGET_HANGUP:
2561         case STIMULUS_RECALL_TARGET_ANSWER:
2562         default:
2563                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2564                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2565                 return props->state;
2566         }
2567 }
2568
2569 static int fail_enter(struct attended_transfer_properties *props)
2570 {
2571         if (props->transferee_bridge) {
2572                 ast_bridge_destroy(props->transferee_bridge, 0);
2573                 props->transferee_bridge = NULL;
2574         }
2575         return 0;
2576 }
2577
2578 /*!
2579  * \brief DTMF hook when transferer presses abort sequence.
2580  *
2581  * Sends a stimulus to the attended transfer monitor thread that the abort sequence has been pressed
2582  */
2583 static int atxfer_abort(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2584 {
2585         struct attended_transfer_properties *props = hook_pvt;
2586
2587         ast_debug(1, "Transferer on attended transfer %p pressed abort sequence\n", props);
2588         stimulate_attended_transfer(props, STIMULUS_DTMF_ATXFER_ABORT);
2589         return 0;
2590 }
2591
2592 /*!
2593  * \brief DTMF hook when transferer presses complete sequence.
2594  *
2595  * Sends a stimulus to the attended transfer monitor thread that the complete sequence has been pressed
2596  */
2597 static int atxfer_complete(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2598 {
2599         struct attended_transfer_properties *props = hook_pvt;
2600
2601         ast_debug(1, "Transferer on attended transfer %p pressed complete sequence\n", props);
2602         stimulate_attended_transfer(props, STIMULUS_DTMF_ATXFER_COMPLETE);
2603         return 0;
2604 }
2605
2606 /*!
2607  * \brief DTMF hook when transferer presses threeway sequence.
2608  *
2609  * Sends a stimulus to the attended transfer monitor thread that the threeway sequence has been pressed
2610  */
2611 static int atxfer_threeway(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2612 {
2613         struct attended_transfer_properties *props = hook_pvt;
2614
2615         ast_debug(1, "Transferer on attended transfer %p pressed threeway sequence\n", props);
2616         stimulate_attended_transfer(props, STIMULUS_DTMF_ATXFER_THREEWAY);
2617         return 0;
2618 }
2619
2620 /*!
2621  * \brief DTMF hook when transferer presses swap sequence.
2622  *
2623  * Sends a stimulus to the attended transfer monitor thread that the swap sequence has been pressed
2624  */
2625 static int atxfer_swap(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2626 {
2627         struct attended_transfer_properties *props = hook_pvt;
2628
2629         ast_debug(1, "Transferer on attended transfer %p pressed swap sequence\n", props);
2630         stimulate_attended_transfer(props, STIMULUS_DTMF_ATXFER_SWAP);
2631         return 0;
2632 }
2633
2634 /*!
2635  * \brief Hangup hook for transferer channel.
2636  *
2637  * Sends a stimulus to the attended transfer monitor thread that the transferer has hung up.
2638  */
2639 static int atxfer_transferer_hangup(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2640 {
2641         struct attended_transfer_properties *props = hook_pvt;
2642
2643         ast_debug(1, "Transferer on attended transfer %p hung up\n", props);
2644         stimulate_attended_transfer(props, STIMULUS_TRANSFERER_HANGUP);
2645         return 0;
2646 }
2647
2648 /*!
2649  * \brief Frame hook for transfer target channel
2650  *
2651  * This is used to determine if the transfer target or recall target has answered
2652  * the outgoing call.
2653  *
2654  * When an answer is detected, a stimulus is sent to the attended transfer monitor
2655  * thread to indicate that the transfer target or recall target has answered.
2656  *
2657  * \param chan The channel the framehook is attached to.
2658  * \param frame The frame being read or written.
2659  * \param event What is being done with the frame.
2660  * \param data The attended transfer properties.
2661  */
2662 static struct ast_frame *transfer_target_framehook_cb(struct ast_channel *chan,
2663                 struct ast_frame *frame, enum ast_framehook_event event, void *data)
2664 {
2665         struct attended_transfer_properties *props = data;
2666
2667         if (event == AST_FRAMEHOOK_EVENT_READ &&
2668                         frame && frame->frametype == AST_FRAME_CONTROL &&
2669                         frame->subclass.integer == AST_CONTROL_ANSWER) {
2670
2671                 ast_debug(1, "Detected an answer for recall attempt on attended transfer %p\n", props);
2672                 if (props->superstate == SUPERSTATE_TRANSFER) {
2673                         stimulate_attended_transfer(props, STIMULUS_TRANSFER_TARGET_ANSWER);
2674                 } else {
2675                         stimulate_attended_transfer(props, STIMULUS_RECALL_TARGET_ANSWER);
2676                 }
2677                 ast_framehook_detach(chan, props->target_framehook_id);
2678                 props->target_framehook_id = -1;
2679         }
2680
2681         return frame;
2682 }
2683
2684 /*! \brief Callback function which informs upstream if we are consuming a frame of a specific type */
2685 static int transfer_target_framehook_consume(void *data, enum ast_frame_type type)
2686 {
2687         return (type == AST_FRAME_CONTROL ? 1 : 0);
2688 }
2689
2690 static void transfer_target_framehook_destroy_cb(void *data)
2691 {
2692         struct attended_transfer_properties *props = data;
2693         ao2_cleanup(props);
2694 }
2695
2696 static int bridge_personality_atxfer_push(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
2697 {
2698         const char *abort_dtmf;
2699         const char *complete_dtmf;
2700         const char *threeway_dtmf;
2701         const char *swap_dtmf;
2702         struct bridge_basic_personality *personality = self->personality;
2703
2704         if (!ast_channel_has_role(bridge_channel->chan, AST_TRANSFERER_ROLE_NAME)) {
2705                 return 0;
2706         }
2707
2708         abort_dtmf = ast_channel_get_role_option(bridge_channel->chan, AST_TRANSFERER_ROLE_NAME, "abort");
2709         complete_dtmf = ast_channel_get_role_option(bridge_channel->chan, AST_TRANSFERER_ROLE_NAME, "complete");
2710         threeway_dtmf = ast_channel_get_role_option(bridge_channel->chan, AST_TRANSFERER_ROLE_NAME, "threeway");
2711         swap_dtmf = ast_channel_get_role_option(bridge_channel->chan, AST_TRANSFERER_ROLE_NAME, "swap");
2712
2713         if (!ast_strlen_zero(abort_dtmf) && ast_bridge_dtmf_hook(bridge_channel->features,
2714                         abort_dtmf, atxfer_abort, personality->details[personality->current].pvt, NULL,
2715                         AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE | AST_BRIDGE_HOOK_REMOVE_ON_PULL)) {
2716                 return -1;
2717         }
2718         if (!ast_strlen_zero(complete_dtmf) && ast_bridge_dtmf_hook(bridge_channel->features,
2719                         complete_dtmf, atxfer_complete, personality->details[personality->current].pvt, NULL,
2720                         AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE | AST_BRIDGE_HOOK_REMOVE_ON_PULL)) {
2721                 return -1;
2722         }
2723         if (!ast_strlen_zero(threeway_dtmf) && ast_bridge_dtmf_hook(bridge_channel->features,
2724                         threeway_dtmf, atxfer_threeway, personality->details[personality->current].pvt, NULL,
2725                         AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE | AST_BRIDGE_HOOK_REMOVE_ON_PULL)) {
2726                 return -1;
2727         }
2728         if (!ast_strlen_zero(swap_dtmf) && ast_bridge_dtmf_hook(bridge_channel->features,
2729                         swap_dtmf, atxfer_swap, personality->details[personality->current].pvt, NULL,
2730                         AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE | AST_BRIDGE_HOOK_REMOVE_ON_PULL)) {
2731                 return -1;
2732         }
2733         if (ast_bridge_hangup_hook(bridge_channel->features, atxfer_transferer_hangup,
2734                         personality->details[personality->current].pvt, NULL,
2735                         AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE | AST_BRIDGE_HOOK_REMOVE_ON_PULL)) {
2736                 return -1;
2737         }
2738
2739         return 0;
2740 }
2741
2742 static void transfer_pull(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct attended_transfer_properties *props)
2743 {
2744         if (self->num_channels > 1 || bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2745                 return;
2746         }
2747
2748         if (self->num_channels == 1) {
2749                 RAII_VAR(struct ast_bridge_channel *, transferer_bridge_channel, NULL, ao2_cleanup);
2750
2751                 ast_channel_lock(props->transferer);
2752                 transferer_bridge_channel = ast_channel_get_bridge_channel(props->transferer);
2753                 ast_channel_unlock(props->transferer);
2754
2755                 if (!transferer_bridge_channel) {
2756                         return;
2757                 }
2758
2759                 if (AST_LIST_FIRST(&self->channels) != transferer_bridge_channel) {
2760                         return;
2761                 }
2762         }
2763
2764         /* Reaching this point means that either
2765          * 1) The bridge has no channels in it
2766          * 2) The bridge has one channel, and it's the transferer
2767          * In either case, it indicates that the non-transferer parties
2768          * are no longer in the bridge.
2769          */
2770         if (self == props->transferee_bridge) {
2771                 stimulate_attended_transfer(props, STIMULUS_TRANSFEREE_HANGUP);
2772         } else {
2773                 stimulate_attended_transfer(props, STIMULUS_TRANSFER_TARGET_HANGUP);
2774         }
2775 }
2776
2777 static void recall_pull(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct attended_transfer_properties *props)
2778 {
2779         if (self == props->target_bridge) {
2780                 /* Once we're in the recall superstate, we no longer care about this bridge */
2781                 return;
2782         }
2783
2784         if (bridge_channel->chan == props->recall_target) {
2785                 stimulate_attended_transfer(props, STIMULUS_RECALL_TARGET_HANGUP);
2786                 return;
2787         }
2788
2789         if (self->num_channels == 0) {
2790                 /* Empty bridge means all transferees are gone for sure */
2791                 stimulate_attended_transfer(props, STIMULUS_TRANSFEREE_HANGUP);
2792                 return;
2793         }
2794
2795         if (self->num_channels == 1) {
2796                 RAII_VAR(struct ast_bridge_channel *, target_bridge_channel, NULL, ao2_cleanup);
2797                 if (!props->recall_target) {
2798                         /* No recall target means that the pull happened on a transferee. If there's still
2799                          * a channel left in the bridge, we don't need to send a stimulus
2800                          */
2801                         return;
2802                 }
2803
2804                 ast_channel_lock(props->recall_target);
2805                 target_bridge_channel = ast_channel_get_bridge_channel(props->recall_target);
2806                 ast_channel_unlock(props->recall_target);
2807
2808                 if (!target_bridge_channel) {
2809                         return;
2810                 }
2811
2812                 if (AST_LIST_FIRST(&self->channels) == target_bridge_channel) {
2813                         stimulate_attended_transfer(props, STIMULUS_TRANSFEREE_HANGUP);
2814                 }
2815         }
2816 }
2817
2818 static void bridge_personality_atxfer_pull(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel)
2819 {
2820         struct bridge_basic_personality *personality = self->personality;
2821         struct attended_transfer_properties *props = personality->details[personality->current].pvt;
2822
2823         switch (props->superstate) {
2824         case SUPERSTATE_TRANSFER:
2825                 transfer_pull(self, bridge_channel, props);
2826                 break;
2827         case SUPERSTATE_RECALL:
2828                 recall_pull(self, bridge_channel, props);
2829                 break;
2830         }
2831 }
2832
2833 static enum attended_transfer_stimulus wait_for_stimulus(struct attended_transfer_properties *props)
2834 {
2835         RAII_VAR(struct stimulus_list *, list, NULL, ast_free_ptr);
2836         SCOPED_MUTEX(lock, ao2_object_get_lockaddr(props));
2837
2838         while (!(list = AST_LIST_REMOVE_HEAD(&props->stimulus_queue, next))) {
2839                 if (!(state_properties[props->state].flags & TRANSFER_STATE_FLAG_TIMED)) {
2840                         ast_cond_wait(&props->cond, lock);
2841                 } else {
2842                         struct timeval relative_timeout = { 0, };
2843                         struct timeval absolute_timeout;
2844                         struct timespec timeout_arg;
2845
2846                         if (state_properties[props->state].flags & TRANSFER_STATE_FLAG_TIMER_RESET) {
2847                                 props->start = ast_tvnow();
2848                         }
2849
2850                         if (state_properties[props->state].flags & TRANSFER_STATE_FLAG_TIMER_LOOP_DELAY) {
2851                                 relative_timeout.tv_sec = props->atxferloopdelay;
2852                         } else {
2853                                 /* Implied TRANSFER_STATE_FLAG_TIMER_ATXFER_NO_ANSWER */
2854                                 relative_timeout.tv_sec = props->atxfernoanswertimeout;
2855                         }
2856
2857                         absolute_timeout = ast_tvadd(props->start, relative_timeout);
2858                         timeout_arg.tv_sec = absolute_timeout.tv_sec;
2859                         timeout_arg.tv_nsec = absolute_timeout.tv_usec * 1000;
2860
2861                         if (ast_cond_timedwait(&props->cond, lock, &timeout_arg) == ETIMEDOUT) {
2862                                 return STIMULUS_TIMEOUT;
2863                         }
2864                 }
2865         }
2866         return list->stimulus;
2867 }
2868
2869 /*!
2870  * \brief The main loop for the attended transfer monitor thread.
2871  *
2872  * This loop runs continuously until the attended transfer reaches
2873  * a terminal state. Stimuli for changes in the attended transfer
2874  * state are handled in this thread so that all factors in an
2875  * attended transfer can be handled in an orderly fashion.
2876  *
2877  * \param data The attended transfer properties
2878  */
2879 static void *attended_transfer_monitor_thread(void *data)
2880 {
2881         struct attended_transfer_properties *props = data;
2882
2883         for (;;) {
2884                 enum attended_transfer_stimulus stimulus;
2885
2886                 ast_debug(1, "About to enter state %s for attended transfer %p\n", state_properties[props->state].state_name, props);
2887
2888                 if (state_properties[props->state].enter &&
2889                                 state_properties[props->state].enter(props)) {
2890                         ast_log(LOG_ERROR, "State %s enter function returned an error for attended transfer %p\n",
2891                                         state_properties[props->state].state_name, props);
2892                         break;
2893                 }
2894
2895                 if (state_properties[props->state].flags & TRANSFER_STATE_FLAG_TERMINAL) {
2896                         ast_debug(1, "State %s is a terminal state. Ending attended transfer %p\n",
2897                                         state_properties[props->state].state_name, props);
2898                         break;
2899                 }
2900
2901                 stimulus = wait_for_stimulus(props);
2902
2903                 ast_debug(1, "Received stimulus %s on attended transfer %p\n", stimulus_strs[stimulus], props);
2904
2905                 ast_assert(state_properties[props->state].exit != NULL);
2906
2907                 props->state = state_properties[props->state].exit(props, stimulus);
2908
2909                 ast_debug(1, "Told to enter state %s exit on attended transfer %p\n", state_properties[props->state].state_name, props);
2910         }
2911
2912         attended_transfer_properties_shutdown(props);
2913
2914         return NULL;
2915 }
2916
2917 static int attach_framehook(struct attended_transfer_properties *props, struct ast_channel *channel)
2918 {
2919         struct ast_framehook_interface target_interface = {
2920                 .version = AST_FRAMEHOOK_INTERFACE_VERSION,
2921                 .event_cb = transfer_target_framehook_cb,
2922                 .destroy_cb = transfer_target_framehook_destroy_cb,
2923                 .consume_cb = transfer_target_framehook_consume,
2924                 .disable_inheritance = 1,
2925         };
2926
2927         ao2_ref(props, +1);
2928         target_interface.data = props;
2929
2930         props->target_framehook_id = ast_framehook_attach(channel, &target_interface);
2931         if (props->target_framehook_id == -1) {
2932                 ao2_ref(props, -1);
2933                 return -1;
2934         }
2935         return 0;
2936 }
2937
2938 static int add_transferer_role(struct ast_channel *chan, struct ast_bridge_features_attended_transfer *attended_transfer)
2939 {
2940         const char *atxfer_abort;
2941         const char *atxfer_threeway;
2942         const char *atxfer_complete;
2943         const char *atxfer_swap;
2944         RAII_VAR(struct ast_features_xfer_config *, xfer_cfg, NULL, ao2_cleanup);
2945         SCOPED_CHANNELLOCK(lock, chan);
2946
2947         xfer_cfg = ast_get_chan_features_xfer_config(chan);
2948         if (!xfer_cfg) {
2949                 return -1;
2950         }
2951         if (attended_transfer) {
2952                 atxfer_abort = ast_strdupa(S_OR(attended_transfer->abort, xfer_cfg->atxferabort));
2953                 atxfer_threeway = ast_strdupa(S_OR(attended_transfer->threeway, xfer_cfg->atxferthreeway));
2954                 atxfer_complete = ast_strdupa(S_OR(attended_transfer->complete, xfer_cfg->atxfercomplete));
2955                 atxfer_swap = ast_strdupa(S_OR(attended_transfer->swap, xfer_cfg->atxferswap));
2956         } else {
2957                 atxfer_abort = ast_strdupa(xfer_cfg->atxferabort);
2958                 atxfer_threeway = ast_strdupa(xfer_cfg->atxferthreeway);
2959                 atxfer_complete = ast_strdupa(xfer_cfg->atxfercomplete);
2960                 atxfer_swap = ast_strdupa(xfer_cfg->atxferswap);
2961         }
2962
2963         return ast_channel_add_bridge_role(chan, AST_TRANSFERER_ROLE_NAME) ||
2964                 ast_channel_set_bridge_role_option(chan, AST_TRANSFERER_ROLE_NAME, "abort", atxfer_abort) ||
2965                 ast_channel_set_bridge_role_option(chan, AST_TRANSFERER_ROLE_NAME, "complete", atxfer_complete) ||
2966                 ast_channel_set_bridge_role_option(chan, AST_TRANSFERER_ROLE_NAME, "threeway", atxfer_threeway) ||
2967                 ast_channel_set_bridge_role_option(chan, AST_TRANSFERER_ROLE_NAME, "swap", atxfer_swap);
2968 }
2969
2970 /*!
2971  * \brief Helper function that presents dialtone and grabs extension
2972  *
2973  * \retval 0 on success
2974  * \retval -1 on failure
2975  */
2976 static int grab_transfer(struct ast_channel *chan, char *exten, size_t exten_len, const char *context)
2977 {
2978         int res;
2979         int digit_timeout;
2980         RAII_VAR(struct ast_features_xfer_config *, xfer_cfg, NULL, ao2_cleanup);
2981
2982         ast_channel_lock(chan);
2983         xfer_cfg = ast_get_chan_features_xfer_config(chan);
2984         if (!xfer_cfg) {
2985                 ast_log(LOG_ERROR, "Unable to get transfer configuration\n");
2986                 ast_channel_unlock(chan);
2987                 return -1;
2988         }
2989         digit_timeout = xfer_cfg->transferdigittimeout * 1000;
2990         ast_channel_unlock(chan);
2991
2992         /* Play the simple "transfer" prompt out and wait */
2993         res = ast_stream_and_wait(chan, "pbx-transfer", AST_DIGIT_ANY);
2994         ast_stopstream(chan);
2995         if (res < 0) {
2996                 /* Hangup or error */
2997                 return -1;
2998         }
2999         if (res) {
3000                 /* Store the DTMF digit that interrupted playback of the file. */
3001                 exten[0] = res;
3002         }
3003
3004         /* Drop to dialtone so they can enter the extension they want to transfer to */
3005         res = ast_app_dtget(chan, context, exten, exten_len, exten_len - 1, digit_timeout);
3006         if (res < 0) {
3007                 /* Hangup or error */
3008                 res = -1;
3009         } else if (!res) {
3010                 /* 0 for invalid extension dialed. */
3011                 if (ast_strlen_zero(exten)) {
3012                         ast_debug(1, "%s dialed no digits.\n", ast_channel_name(chan));
3013                 } else {
3014                         ast_debug(1, "%s dialed '%s@%s' does not exist.\n",
3015                                 ast_channel_name(chan), exten, context);
3016                 }
3017                 ast_stream_and_wait(chan, "pbx-invalid", AST_DIGIT_NONE);
3018                 res = -1;
3019         } else {
3020                 /* Dialed extension is valid. */
3021                 res = 0;
3022         }
3023         return res;
3024 }
3025
3026 static void copy_caller_data(struct ast_channel *dest, struct ast_channel *caller)
3027 {
3028         ast_channel_lock_both(caller, dest);
3029         ast_connected_line_copy_from_caller(ast_channel_connected(dest), ast_channel_caller(caller));
3030         ast_channel_inherit_variables(caller, dest);
3031         ast_channel_datastore_inherit(caller, dest);
3032         ast_channel_unlock(dest);
3033         ast_channel_unlock(caller);
3034 }
3035
3036 /*! \brief Helper function that creates an outgoing channel and returns it immediately */
3037 static struct ast_channel *dial_transfer(struct ast_channel *caller, const char *destination)
3038 {
3039         struct ast_channel *chan;
3040         int cause;
3041
3042         /* Now we request a local channel to prepare to call the destination */
3043         chan = ast_request("Local", ast_channel_nativeformats(caller), NULL, caller, destination,
3044                 &cause);
3045         if (!chan) {
3046                 return NULL;
3047         }
3048
3049         ast_channel_lock_both(chan, caller);
3050
3051         ast_channel_req_accountcodes(chan, caller, AST_CHANNEL_REQUESTOR_BRIDGE_PEER);
3052
3053         /* Who is transferring the call. */
3054         pbx_builtin_setvar_helper(chan, "TRANSFERERNAME", ast_channel_name(caller));
3055
3056         ast_bridge_set_transfer_variables(chan, ast_channel_name(caller), 1);
3057
3058         ast_channel_unlock(chan);
3059         ast_channel_unlock(caller);
3060
3061         /* Before we actually dial out let's inherit appropriate information. */
3062         copy_caller_data(chan, caller);
3063
3064         return chan;
3065 }
3066
3067 /*!
3068  * \brief Internal built in feature for attended transfers
3069  *
3070  * This hook will set up a thread for monitoring the progress of
3071  * an attended transfer. For more information about attended transfer
3072  * progress, see documentation on the transfer state machine.
3073  *
3074  * \param bridge_channel The channel that pressed the attended transfer DTMF sequence
3075  * \param hook_pvt Structure with further information about the attended transfer
3076  */
3077 static int feature_attended_transfer(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
3078 {
3079         struct ast_bridge_features_attended_transfer *attended_transfer = hook_pvt;
3080         struct attended_transfer_properties *props;
3081         struct ast_bridge *bridge;
3082         char destination[AST_MAX_EXTENSION + AST_MAX_CONTEXT + 1];
3083         char exten[AST_MAX_EXTENSION] = "";
3084         pthread_t thread;
3085
3086         /* Inhibit the bridge before we do anything else. */
3087         bridge = ast_bridge_channel_merge_inhibit(bridge_channel, +1);
3088
3089         if (strcmp(bridge->v_table->name, "basic")) {
3090                 ast_log(LOG_ERROR, "Attended transfer attempted on unsupported bridge type '%s'.\n",
3091                         bridge->v_table->name);
3092                 ast_bridge_merge_inhibit(bridge, -1);
3093                 ao2_ref(bridge, -1);
3094                 return 0;
3095         }
3096
3097         /* Was the bridge inhibited before we inhibited it? */
3098         if (1 < bridge->inhibit_merge) {
3099                 /*
3100                  * The peer likely initiated attended transfer at the same time
3101                  * and we lost the race.
3102                  */
3103                 ast_verb(3, "Channel %s: Bridge '%s' does not permit merging at this time.\n",
3104                         ast_channel_name(bridge_channel->chan), bridge->uniqueid);
3105                 ast_bridge_merge_inhibit(bridge, -1);
3106                 ao2_ref(bridge, -1);
3107                 return 0;
3108         }
3109
3110         props = attended_transfer_properties_alloc(bridge_channel->chan,
3111                 attended_transfer ? attended_transfer->context : NULL);
3112         if (!props) {
3113                 ast_log(LOG_ERROR, "Unable to allocate control structure for performing attended transfer.\n");
3114                 ast_bridge_merge_inhibit(bridge, -1);
3115                 ao2_ref(bridge, -1);
3116                 return 0;
3117         }
3118
3119         props->transferee_bridge = bridge;
3120
3121         if (add_transferer_role(props->transferer, attended_transfer)) {
3122                 ast_log(LOG_ERROR, "Unable to set transferrer bridge role.\n");
3123                 attended_transfer_properties_shutdown(props);
3124                 return 0;
3125         }
3126
3127         ast_bridge_channel_write_hold(bridge_channel, NULL);
3128
3129         /* Grab the extension to transfer to */
3130         if (grab_transfer(bridge_channel->chan, exten, sizeof(exten), props->context)) {
3131                 ast_log(LOG_WARNING, "Unable to acquire target extension for attended transfer.\n");
3132                 ast_bridge_channel_write_unhold(bridge_channel);
3133                 attended_transfer_properties_shutdown(props);
3134                 return 0;
3135         }
3136
3137         ast_string_field_set(props, exten, exten);
3138
3139         /* Fill the variable with the extension and context we want to call */
3140         snprintf(destination, sizeof(destination), "%s@%s", props->exten, props->context);
3141
3142         ast_debug(1, "Attended transfer to '%s'\n", destination);
3143
3144         /* Get a channel that is the destination we wish to call */
3145         props->transfer_target = dial_transfer(bridge_channel->chan, destination);
3146         if (!props->transfer_target) {
3147                 ast_log(LOG_ERROR, "Unable to request outbound channel for attended transfer target.\n");
3148                 ast_stream_and_wait(props->transferer, props->failsound, AST_DIGIT_NONE);
3149                 ast_bridge_channel_write_unhold(bridge_channel);
3150                 attended_transfer_properties_shutdown(props);
3151                 return 0;
3152         }
3153
3154
3155         /* Create a bridge to use to talk to the person we are calling */
3156         props->target_bridge = ast_bridge_basic_new();
3157         if (!props->target_bridge) {
3158                 ast_log(LOG_ERROR, "Unable to create bridge for attended transfer target.\n");
3159                 ast_stream_and_wait(props->transferer, props->failsound, AST_DIGIT_NONE);
3160                 ast_bridge_channel_write_unhold(bridge_channel);
3161                 ast_hangup(props->transfer_target);
3162                 props->transfer_target = NULL;
3163                 attended_transfer_properties_shutdown(props);
3164                 return 0;
3165         }
3166         ast_bridge_merge_inhibit(props->target_bridge, +1);
3167
3168         if (attach_framehook(props, props->transfer_target)) {
3169                 ast_log(LOG_ERROR, "Unable to attach framehook to transfer target.\n");
3170                 ast_stream_and_wait(props->transferer, props->failsound, AST_DIGIT_NONE);
3171                 ast_bridge_channel_write_unhold(bridge_channel);
3172                 ast_hangup(props->transfer_target);
3173                 props->transfer_target = NULL;
3174                 attended_transfer_properties_shutdown(props);
3175                 return 0;
3176         }
3177
3178         bridge_basic_change_personality(props->target_bridge,
3179                         BRIDGE_BASIC_PERSONALITY_ATXFER, props);
3180         bridge_basic_change_personality(bridge,
3181                         BRIDGE_BASIC_PERSONALITY_ATXFER, props);
3182
3183         if (ast_call(props->transfer_target, destination, 0)) {
3184                 ast_log(LOG_ERROR, "Unable to place outbound call to transfer target.\n");
3185                 ast_stream_and_wait(bridge_channel->chan, props->failsound, AST_DIGIT_NONE);
3186                 ast_bridge_channel_write_unhold(bridge_channel);
3187                 ast_hangup(props->transfer_target);
3188                 props->transfer_target = NULL;
3189                 attended_transfer_properties_shutdown(props);
3190                 return 0;
3191         }
3192
3193         /* We increase the refcount of the transfer target because ast_bridge_impart() will
3194          * steal the reference we already have. We need to keep a reference, so the only
3195          * choice is to give it a bump
3196          */
3197         ast_channel_ref(props->transfer_target);
3198         if (ast_bridge_impart(props->target_bridge, props->transfer_target, NULL, NULL,
3199                 AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
3200                 ast_log(LOG_ERROR, "Unable to place transfer target into bridge.\n");
3201                 ast_stream_and_wait(bridge_channel->chan, props->failsound, AST_DIGIT_NONE);
3202                 ast_bridge_channel_write_unhold(bridge_channel);
3203                 ast_hangup(props->transfer_target);
3204                 props->transfer_target = NULL;
3205                 attended_transfer_properties_shutdown(props);
3206                 return 0;
3207         }
3208
3209         if (ast_pthread_create_detached(&thread, NULL, attended_transfer_monitor_thread, props)) {
3210                 ast_log(LOG_ERROR, "Unable to create monitoring thread for attended transfer.\n");
3211                 ast_stream_and_wait(bridge_channel->chan, props->failsound, AST_DIGIT_NONE);
3212                 ast_bridge_channel_write_unhold(bridge_channel);
3213                 attended_transfer_properties_shutdown(props);
3214                 return 0;
3215         }
3216
3217         /* Once the monitoring thread has been created, it is responsible for destroying all
3218          * of the necessary components.
3219          */
3220         return 0;
3221 }
3222
3223 static void blind_transfer_cb(struct ast_channel *new_channel, struct transfer_channel_data *user_data_wrapper,
3224                 enum ast_transfer_type transfer_type)
3225 {
3226         struct ast_channel *transferer_channel = user_data_wrapper->data;
3227
3228         if (transfer_type == AST_BRIDGE_TRANSFER_MULTI_PARTY) {
3229                 copy_caller_data(new_channel, transferer_channel);
3230         }
3231 }
3232
3233 /*! \brief Internal built in feature for blind transfers */
3234 static int feature_blind_transfer(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
3235 {
3236         char exten[AST_MAX_EXTENSION] = "";
3237         struct ast_bridge_features_blind_transfer *blind_transfer = hook_pvt;
3238         const char *context;
3239         char *goto_on_blindxfr;
3240
3241         ast_bridge_channel_write_hold(bridge_channel, NULL);
3242
3243         ast_channel_lock(bridge_channel->chan);
3244         context = ast_strdupa(get_transfer_context(bridge_channel->chan,
3245                 blind_transfer ? blind_transfer->context : NULL));
3246         goto_on_blindxfr = ast_strdupa(S_OR(pbx_builtin_getvar_helper(bridge_channel->chan,
3247                 "GOTO_ON_BLINDXFR"), ""));
3248         ast_channel_unlock(bridge_channel->chan);
3249
3250         /* Grab the extension to transfer to */
3251         if (grab_transfer(bridge_channel->chan, exten, sizeof(exten), context)) {
3252                 ast_bridge_channel_write_unhold(bridge_channel);
3253                 return 0;
3254         }
3255
3256         if (!ast_strlen_zero(goto_on_blindxfr)) {
3257                 ast_debug(1, "After transfer, transferer %s goes to %s\n",
3258                                 ast_channel_name(bridge_channel->chan), goto_on_blindxfr);
3259                 ast_bridge_set_after_go_on(bridge_channel->chan, NULL, NULL, 0, goto_on_blindxfr);
3260         }
3261
3262         if (ast_bridge_transfer_blind(0, bridge_channel->chan, exten, context, blind_transfer_cb,
3263                         bridge_channel->chan) != AST_BRIDGE_TRANSFER_SUCCESS &&
3264                         !ast_strlen_zero(goto_on_blindxfr)) {
3265                 ast_bridge_discard_after_goto(bridge_channel->chan);
3266         }
3267
3268         return 0;
3269 }
3270
3271 struct ast_bridge_methods ast_bridge_basic_v_table;
3272 struct ast_bridge_methods personality_normal_v_table;
3273 struct ast_bridge_methods personality_atxfer_v_table;
3274
3275 static void bridge_basic_change_personality(struct ast_bridge *bridge,
3276                 enum bridge_basic_personality_type type, void *user_data)
3277 {
3278         struct bridge_basic_personality *personality = bridge->personality;
3279         SCOPED_LOCK(lock, bridge, ast_bridge_lock, ast_bridge_unlock);
3280
3281         remove_hooks_on_personality_change(bridge);
3282
3283         ao2_cleanup(personality->details[personality->current].pvt);
3284         personality->details[personality->current].pvt = NULL;
3285         ast_clear_flag(&bridge->feature_flags, AST_FLAGS_ALL);
3286
3287         personality->current = type;
3288         if (user_data) {
3289                 ao2_ref(user_data, +1);
3290         }
3291         personality->details[personality->current].pvt = user_data;
3292         ast_set_flag(&bridge->feature_flags, personality->details[personality->current].bridge_flags);
3293         if (personality->details[personality->current].on_personality_change) {
3294                 personality->details[personality->current].on_personality_change(bridge);
3295         }
3296 }
3297
3298 static void personality_destructor(void *obj)
3299 {
3300         struct bridge_basic_personality *personality = obj;
3301         int i;
3302
3303         for (i = 0; i < BRIDGE_BASIC_PERSONALITY_END; ++i) {
3304                 ao2_cleanup(personality->details[i].pvt);
3305         }
3306 }
3307
3308 static void on_personality_change_normal(struct ast_bridge *bridge)
3309 {
3310         struct ast_bridge_channel *iter;
3311
3312         AST_LIST_TRAVERSE(&bridge->channels, iter, entry) {
3313                 if (add_normal_hooks(bridge, iter)) {
3314                         ast_log(LOG_WARNING, "Unable to set up bridge hooks for channel %s. Features may not work properly\n",
3315                                         ast_channel_name(iter->chan));
3316                 }
3317         }
3318 }
3319
3320 static void init_details(struct personality_details *details,
3321                 enum bridge_basic_personality_type type)
3322 {
3323         switch (type) {
3324  &