media formats: re-architect handling of media for performance improvements
[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 Send a stasis publication for a successful attended transfer
1530  */
1531 static void publish_transfer_success(struct attended_transfer_properties *props)
1532 {
1533         struct ast_bridge_channel_pair transferee = {
1534                 .channel = props->transferer,
1535                 .bridge = props->transferee_bridge,
1536         };
1537         struct ast_bridge_channel_pair transfer_target = {
1538                 .channel = props->transferer,
1539                 .bridge = props->target_bridge,
1540         };
1541
1542         if (transferee.bridge && transfer_target.bridge) {
1543                 ast_bridge_lock_both(transferee.bridge, transfer_target.bridge);
1544         } else if (transferee.bridge) {
1545                 ast_bridge_lock(transferee.bridge);
1546         } else if (transfer_target.bridge) {
1547                 ast_bridge_lock(transfer_target.bridge);
1548         }
1549
1550         ast_bridge_publish_attended_transfer_bridge_merge(0, AST_BRIDGE_TRANSFER_SUCCESS,
1551                         &transferee, &transfer_target, props->transferee_bridge);
1552
1553         if (transferee.bridge) {
1554                 ast_bridge_unlock(transferee.bridge);
1555         }
1556         if (transfer_target.bridge) {
1557                 ast_bridge_unlock(transfer_target.bridge);
1558         }
1559 }
1560
1561 /*!
1562  * \brief Send a stasis publication for an attended transfer that ends in a threeway call
1563  */
1564 static void publish_transfer_threeway(struct attended_transfer_properties *props)
1565 {
1566         struct ast_bridge_channel_pair transferee = {
1567                 .channel = props->transferer,
1568                 .bridge = props->transferee_bridge,
1569         };
1570         struct ast_bridge_channel_pair transfer_target = {
1571                 .channel = props->transferer,
1572                 .bridge = props->target_bridge,
1573         };
1574         struct ast_bridge_channel_pair threeway = {
1575                 .channel = props->transferer,
1576                 .bridge = props->transferee_bridge,
1577         };
1578
1579         if (transferee.bridge && transfer_target.bridge) {
1580                 ast_bridge_lock_both(transferee.bridge, transfer_target.bridge);
1581         } else if (transferee.bridge) {
1582                 ast_bridge_lock(transferee.bridge);
1583         } else if (transfer_target.bridge) {
1584                 ast_bridge_lock(transfer_target.bridge);
1585         }
1586
1587         ast_bridge_publish_attended_transfer_threeway(0, AST_BRIDGE_TRANSFER_SUCCESS,
1588                         &transferee, &transfer_target, &threeway);
1589
1590         if (transferee.bridge) {
1591                 ast_bridge_unlock(transferee.bridge);
1592         }
1593         if (transfer_target.bridge) {
1594                 ast_bridge_unlock(transfer_target.bridge);
1595         }
1596 }
1597
1598 /*!
1599  * \brief Send a stasis publication for a failed attended transfer
1600  */
1601 static void publish_transfer_fail(struct attended_transfer_properties *props)
1602 {
1603         struct ast_bridge_channel_pair transferee = {
1604                 .channel = props->transferer,
1605                 .bridge = props->transferee_bridge,
1606         };
1607         struct ast_bridge_channel_pair transfer_target = {
1608                 .channel = props->transferer,
1609                 .bridge = props->target_bridge,
1610         };
1611
1612         if (transferee.bridge && transfer_target.bridge) {
1613                 ast_bridge_lock_both(transferee.bridge, transfer_target.bridge);
1614         } else if (transferee.bridge) {
1615                 ast_bridge_lock(transferee.bridge);
1616         } else if (transfer_target.bridge) {
1617                 ast_bridge_lock(transfer_target.bridge);
1618         }
1619
1620         ast_bridge_publish_attended_transfer_fail(0, AST_BRIDGE_TRANSFER_FAIL,
1621                         &transferee, &transfer_target);
1622
1623         if (transferee.bridge) {
1624                 ast_bridge_unlock(transferee.bridge);
1625         }
1626         if (transfer_target.bridge) {
1627                 ast_bridge_unlock(transfer_target.bridge);
1628         }
1629 }
1630
1631 /*!
1632  * \brief Helper method to play a sound on a channel in a bridge
1633  *
1634  * \param chan The channel to play the sound to
1635  * \param sound The sound to play
1636  */
1637 static void play_sound(struct ast_channel *chan, const char *sound)
1638 {
1639         RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
1640
1641         ast_channel_lock(chan);
1642         bridge_channel = ast_channel_get_bridge_channel(chan);
1643         ast_channel_unlock(chan);
1644
1645         if (!bridge_channel) {
1646                 return;
1647         }
1648
1649         ast_bridge_channel_queue_playfile(bridge_channel, NULL, sound, NULL);
1650 }
1651
1652 /*!
1653  * \brief Helper method to place a channel in a bridge on hold
1654  */
1655 static void hold(struct ast_channel *chan)
1656 {
1657         RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
1658
1659         if (chan) {
1660                 ast_channel_lock(chan);
1661                 bridge_channel = ast_channel_get_bridge_channel(chan);
1662                 ast_channel_unlock(chan);
1663
1664                 ast_assert(bridge_channel != NULL);
1665
1666                 ast_bridge_channel_write_hold(bridge_channel, NULL);
1667         }
1668 }
1669
1670 /*!
1671  * \brief Helper method to take a channel in a bridge off hold
1672  */
1673 static void unhold(struct ast_channel *chan)
1674 {
1675         RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
1676
1677         ast_channel_lock(chan);
1678         bridge_channel = ast_channel_get_bridge_channel(chan);
1679         ast_channel_unlock(chan);
1680
1681         ast_assert(bridge_channel != NULL);
1682
1683         ast_bridge_channel_write_unhold(bridge_channel);
1684 }
1685
1686 /*!
1687  * \brief Helper method to send a ringing indication to a channel in a bridge
1688  */
1689 static void ringing(struct ast_channel *chan)
1690 {
1691         RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
1692
1693         ast_channel_lock(chan);
1694         bridge_channel = ast_channel_get_bridge_channel(chan);
1695         ast_channel_unlock(chan);
1696
1697         ast_assert(bridge_channel != NULL);
1698
1699         ast_bridge_channel_write_control_data(bridge_channel, AST_CONTROL_RINGING, NULL, 0);
1700 }
1701
1702 /*!
1703  * \brief Helper method to send a ringing indication to all channels in a bridge
1704  */
1705 static void bridge_ringing(struct ast_bridge *bridge)
1706 {
1707         struct ast_frame ringing = {
1708                 .frametype = AST_FRAME_CONTROL,
1709                 .subclass.integer = AST_CONTROL_RINGING,
1710         };
1711
1712         ast_bridge_queue_everyone_else(bridge, NULL, &ringing);
1713 }
1714
1715 /*!
1716  * \brief Helper method to send a hold frame to all channels in a bridge
1717  */
1718 static void bridge_hold(struct ast_bridge *bridge)
1719 {
1720         struct ast_frame hold = {
1721                 .frametype = AST_FRAME_CONTROL,
1722                 .subclass.integer = AST_CONTROL_HOLD,
1723         };
1724
1725         ast_bridge_queue_everyone_else(bridge, NULL, &hold);
1726 }
1727
1728 /*!
1729  * \brief Helper method to send an unhold frame to all channels in a bridge
1730  */
1731 static void bridge_unhold(struct ast_bridge *bridge)
1732 {
1733         struct ast_frame unhold = {
1734                 .frametype = AST_FRAME_CONTROL,
1735                 .subclass.integer = AST_CONTROL_UNHOLD,
1736         };
1737
1738         ast_bridge_queue_everyone_else(bridge, NULL, &unhold);
1739 }
1740
1741 /*!
1742  * \brief Wrapper for \ref bridge_do_move
1743  */
1744 static int bridge_move(struct ast_bridge *dest, struct ast_bridge *src, struct ast_channel *channel, struct ast_channel *swap)
1745 {
1746         int res;
1747         RAII_VAR(struct ast_bridge_channel *, bridge_channel, NULL, ao2_cleanup);
1748
1749         ast_bridge_lock_both(src, dest);
1750
1751         ast_channel_lock(channel);
1752         bridge_channel = ast_channel_get_bridge_channel(channel);
1753         ast_channel_unlock(channel);
1754
1755         ast_assert(bridge_channel != NULL);
1756
1757         ao2_lock(bridge_channel);
1758         bridge_channel->swap = swap;
1759         ao2_unlock(bridge_channel);
1760
1761         res = bridge_do_move(dest, bridge_channel, 1, 0);
1762
1763         ast_bridge_unlock(dest);
1764         ast_bridge_unlock(src);
1765
1766         return res;
1767 }
1768
1769 /*!
1770  * \brief Wrapper for \ref bridge_do_merge
1771  */
1772 static void bridge_merge(struct ast_bridge *dest, struct ast_bridge *src, struct ast_channel **kick_channels, unsigned int num_channels)
1773 {
1774         struct ast_bridge_channel **kick_bridge_channels = num_channels ?
1775                 ast_alloca(num_channels * sizeof(*kick_bridge_channels)) : NULL;
1776         int i;
1777         int num_bridge_channels = 0;
1778
1779         ast_bridge_lock_both(dest, src);
1780
1781         for (i = 0; i < num_channels; ++i) {
1782                 struct ast_bridge_channel *kick_bridge_channel;
1783
1784                 kick_bridge_channel = bridge_find_channel(src, kick_channels[i]);
1785                 if (!kick_bridge_channel) {
1786                         kick_bridge_channel = bridge_find_channel(dest, kick_channels[i]);
1787                 }
1788
1789                 /* It's possible (and fine) for the bridge channel to be NULL at this point if the
1790                  * channel has hung up already. If that happens, we can just remove it from the list
1791                  * of bridge channels to kick from the bridge
1792                  */
1793                 if (!kick_bridge_channel) {
1794                         continue;
1795                 }
1796
1797                 kick_bridge_channels[num_bridge_channels++] = kick_bridge_channel;
1798         }
1799
1800         bridge_do_merge(dest, src, kick_bridge_channels, num_bridge_channels, 0);
1801         ast_bridge_unlock(dest);
1802         ast_bridge_unlock(src);
1803 }
1804
1805 /*!
1806  * \brief Flags that indicate properties of attended transfer states
1807  */
1808 enum attended_transfer_state_flags {
1809         /*! This state requires that the timer be reset when entering the state */
1810         TRANSFER_STATE_FLAG_TIMER_RESET = (1 << 0),
1811         /*! This state's timer uses atxferloopdelay */
1812         TRANSFER_STATE_FLAG_TIMER_LOOP_DELAY = (1 << 1),
1813         /*! This state's timer uses atxfernoanswertimeout */
1814         TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER = (1 << 2),
1815         /*! This state has a time limit associated with it */
1816         TRANSFER_STATE_FLAG_TIMED = (TRANSFER_STATE_FLAG_TIMER_RESET |
1817                         TRANSFER_STATE_FLAG_TIMER_LOOP_DELAY | TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER),
1818         /*! This state does not transition to any other states */
1819         TRANSFER_STATE_FLAG_TERMINAL = (1 << 3),
1820 };
1821
1822 static int calling_target_enter(struct attended_transfer_properties *props);
1823 static enum attended_transfer_state calling_target_exit(struct attended_transfer_properties *props,
1824                 enum attended_transfer_stimulus stimulus);
1825
1826 static int hesitant_enter(struct attended_transfer_properties *props);
1827 static enum attended_transfer_state hesitant_exit(struct attended_transfer_properties *props,
1828                 enum attended_transfer_stimulus stimulus);
1829
1830 static int rebridge_enter(struct attended_transfer_properties *props);
1831
1832 static int resume_enter(struct attended_transfer_properties *props);
1833
1834 static int threeway_enter(struct attended_transfer_properties *props);
1835
1836 static int consulting_enter(struct attended_transfer_properties *props);
1837 static enum attended_transfer_state consulting_exit(struct attended_transfer_properties *props,
1838                 enum attended_transfer_stimulus stimulus);
1839
1840 static int double_checking_enter(struct attended_transfer_properties *props);
1841 static enum attended_transfer_state double_checking_exit(struct attended_transfer_properties *props,
1842                 enum attended_transfer_stimulus stimulus);
1843
1844 static int complete_enter(struct attended_transfer_properties *props);
1845
1846 static int blond_enter(struct attended_transfer_properties *props);
1847
1848 static int blond_nonfinal_enter(struct attended_transfer_properties *props);
1849 static enum attended_transfer_state blond_nonfinal_exit(struct attended_transfer_properties *props,
1850                 enum attended_transfer_stimulus stimulus);
1851
1852 static int recalling_enter(struct attended_transfer_properties *props);
1853 static enum attended_transfer_state recalling_exit(struct attended_transfer_properties *props,
1854                 enum attended_transfer_stimulus stimulus);
1855
1856 static int wait_to_retransfer_enter(struct attended_transfer_properties *props);
1857 static enum attended_transfer_state wait_to_retransfer_exit(struct attended_transfer_properties *props,
1858                 enum attended_transfer_stimulus stimulus);
1859
1860 static int retransfer_enter(struct attended_transfer_properties *props);
1861 static enum attended_transfer_state retransfer_exit(struct attended_transfer_properties *props,
1862                 enum attended_transfer_stimulus stimulus);
1863
1864 static int wait_to_recall_enter(struct attended_transfer_properties *props);
1865 static enum attended_transfer_state wait_to_recall_exit(struct attended_transfer_properties *props,
1866                 enum attended_transfer_stimulus stimulus);
1867
1868 static int fail_enter(struct attended_transfer_properties *props);
1869
1870 /*!
1871  * \brief Properties of an attended transfer state
1872  */
1873 struct attended_transfer_state_properties {
1874         /*! The name of the state. Used for debugging */
1875         const char *state_name;
1876         /*! Function used to enter a state */
1877         int (*enter)(struct attended_transfer_properties *props);
1878         /*!
1879          * Function used to exit a state
1880          * This is used both to determine what the next state
1881          * to transition to will be and to perform any cleanup
1882          * necessary before exiting the current state.
1883          */
1884         enum attended_transfer_state (*exit)(struct attended_transfer_properties *props,
1885                         enum attended_transfer_stimulus stimulus);
1886         /*! Flags associated with this state */
1887         enum attended_transfer_state_flags flags;
1888 };
1889
1890 static const struct attended_transfer_state_properties state_properties[] = {
1891         [TRANSFER_CALLING_TARGET] = {
1892                 .state_name = "Calling Target",
1893                 .enter = calling_target_enter,
1894                 .exit = calling_target_exit,
1895                 .flags = TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER | TRANSFER_STATE_FLAG_TIMER_RESET,
1896         },
1897         [TRANSFER_HESITANT] = {
1898                 .state_name = "Hesitant",
1899                 .enter = hesitant_enter,
1900                 .exit = hesitant_exit,
1901                 .flags = TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER,
1902         },
1903         [TRANSFER_REBRIDGE] = {
1904                 .state_name = "Rebridge",
1905                 .enter = rebridge_enter,
1906                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
1907         },
1908         [TRANSFER_RESUME] = {
1909                 .state_name = "Resume",
1910                 .enter = resume_enter,
1911                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
1912         },
1913         [TRANSFER_THREEWAY] = {
1914                 .state_name = "Threeway",
1915                 .enter = threeway_enter,
1916                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
1917         },
1918         [TRANSFER_CONSULTING] = {
1919                 .state_name = "Consulting",
1920                 .enter = consulting_enter,
1921                 .exit = consulting_exit,
1922         },
1923         [TRANSFER_DOUBLECHECKING] = {
1924                 .state_name = "Double Checking",
1925                 .enter = double_checking_enter,
1926                 .exit = double_checking_exit,
1927         },
1928         [TRANSFER_COMPLETE] = {
1929                 .state_name = "Complete",
1930                 .enter = complete_enter,
1931                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
1932         },
1933         [TRANSFER_BLOND] = {
1934                 .state_name = "Blond",
1935                 .enter = blond_enter,
1936                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
1937         },
1938         [TRANSFER_BLOND_NONFINAL] = {
1939                 .state_name = "Blond Non-Final",
1940                 .enter = blond_nonfinal_enter,
1941                 .exit = blond_nonfinal_exit,
1942                 .flags = TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER,
1943         },
1944         [TRANSFER_RECALLING] = {
1945                 .state_name = "Recalling",
1946                 .enter = recalling_enter,
1947                 .exit = recalling_exit,
1948                 .flags = TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER | TRANSFER_STATE_FLAG_TIMER_RESET,
1949         },
1950         [TRANSFER_WAIT_TO_RETRANSFER] = {
1951                 .state_name = "Wait to Retransfer",
1952                 .enter = wait_to_retransfer_enter,
1953                 .exit = wait_to_retransfer_exit,
1954                 .flags = TRANSFER_STATE_FLAG_TIMER_RESET | TRANSFER_STATE_FLAG_TIMER_LOOP_DELAY,
1955         },
1956         [TRANSFER_RETRANSFER] = {
1957                 .state_name = "Retransfer",
1958                 .enter = retransfer_enter,
1959                 .exit = retransfer_exit,
1960                 .flags = TRANSFER_STATE_FLAG_ATXFER_NO_ANSWER | TRANSFER_STATE_FLAG_TIMER_RESET,
1961         },
1962         [TRANSFER_WAIT_TO_RECALL] = {
1963                 .state_name = "Wait to Recall",
1964                 .enter = wait_to_recall_enter,
1965                 .exit = wait_to_recall_exit,
1966                 .flags = TRANSFER_STATE_FLAG_TIMER_RESET | TRANSFER_STATE_FLAG_TIMER_LOOP_DELAY,
1967         },
1968         [TRANSFER_FAIL] = {
1969                 .state_name = "Fail",
1970                 .enter = fail_enter,
1971                 .flags = TRANSFER_STATE_FLAG_TERMINAL,
1972         },
1973 };
1974
1975 static int calling_target_enter(struct attended_transfer_properties *props)
1976 {
1977         return bridge_move(props->target_bridge, props->transferee_bridge, props->transferer, NULL);
1978 }
1979
1980 static enum attended_transfer_state calling_target_exit(struct attended_transfer_properties *props,
1981                 enum attended_transfer_stimulus stimulus)
1982 {
1983         switch (stimulus) {
1984         case STIMULUS_TRANSFEREE_HANGUP:
1985                 play_sound(props->transferer, props->failsound);
1986                 publish_transfer_fail(props);
1987                 return TRANSFER_FAIL;
1988         case STIMULUS_DTMF_ATXFER_COMPLETE:
1989         case STIMULUS_TRANSFERER_HANGUP:
1990                 bridge_unhold(props->transferee_bridge);
1991                 return props->atxferdropcall ? TRANSFER_BLOND : TRANSFER_BLOND_NONFINAL;
1992         case STIMULUS_TRANSFER_TARGET_ANSWER:
1993                 return TRANSFER_CONSULTING;
1994         case STIMULUS_TRANSFER_TARGET_HANGUP:
1995         case STIMULUS_TIMEOUT:
1996         case STIMULUS_DTMF_ATXFER_ABORT:
1997                 play_sound(props->transferer, props->failsound);
1998                 return TRANSFER_REBRIDGE;
1999         case STIMULUS_DTMF_ATXFER_THREEWAY:
2000                 bridge_unhold(props->transferee_bridge);
2001                 return TRANSFER_THREEWAY;
2002         case STIMULUS_DTMF_ATXFER_SWAP:
2003                 return TRANSFER_HESITANT;
2004         case STIMULUS_NONE:
2005         case STIMULUS_RECALL_TARGET_ANSWER:
2006         case STIMULUS_RECALL_TARGET_HANGUP:
2007         default:
2008                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2009                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2010                 return props->state;
2011         }
2012 }
2013
2014 static int hesitant_enter(struct attended_transfer_properties *props)
2015 {
2016         if (bridge_move(props->transferee_bridge, props->target_bridge, props->transferer, NULL)) {
2017                 return -1;
2018         }
2019
2020         unhold(props->transferer);
2021         return 0;
2022 }
2023
2024 static enum attended_transfer_state hesitant_exit(struct attended_transfer_properties *props,
2025                 enum attended_transfer_stimulus stimulus)
2026 {
2027         switch (stimulus) {
2028         case STIMULUS_TRANSFEREE_HANGUP:
2029                 play_sound(props->transferer, props->failsound);
2030                 publish_transfer_fail(props);
2031                 return TRANSFER_FAIL;
2032         case STIMULUS_DTMF_ATXFER_COMPLETE:
2033         case STIMULUS_TRANSFERER_HANGUP:
2034                 return props->atxferdropcall ? TRANSFER_BLOND : TRANSFER_BLOND_NONFINAL;
2035         case STIMULUS_TRANSFER_TARGET_ANSWER:
2036                 return TRANSFER_DOUBLECHECKING;
2037         case STIMULUS_TRANSFER_TARGET_HANGUP:
2038         case STIMULUS_TIMEOUT:
2039         case STIMULUS_DTMF_ATXFER_ABORT:
2040                 play_sound(props->transferer, props->failsound);
2041                 return TRANSFER_RESUME;
2042         case STIMULUS_DTMF_ATXFER_THREEWAY:
2043                 return TRANSFER_THREEWAY;
2044         case STIMULUS_DTMF_ATXFER_SWAP:
2045                 hold(props->transferer);
2046                 return TRANSFER_CALLING_TARGET;
2047         case STIMULUS_NONE:
2048         case STIMULUS_RECALL_TARGET_HANGUP:
2049         case STIMULUS_RECALL_TARGET_ANSWER:
2050         default:
2051                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2052                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2053                 return props->state;
2054         }
2055 }
2056
2057 static int rebridge_enter(struct attended_transfer_properties *props)
2058 {
2059         if (bridge_move(props->transferee_bridge, props->target_bridge,
2060                         props->transferer, NULL)) {
2061                 return -1;
2062         }
2063
2064         unhold(props->transferer);
2065         return 0;
2066 }
2067
2068 static int resume_enter(struct attended_transfer_properties *props)
2069 {
2070         return 0;
2071 }
2072
2073 static int threeway_enter(struct attended_transfer_properties *props)
2074 {
2075         bridge_merge(props->transferee_bridge, props->target_bridge, NULL, 0);
2076         play_sound(props->transfer_target, props->xfersound);
2077         play_sound(props->transferer, props->xfersound);
2078         publish_transfer_threeway(props);
2079
2080         return 0;
2081 }
2082
2083 static int consulting_enter(struct attended_transfer_properties *props)
2084 {
2085         return 0;
2086 }
2087
2088 static enum attended_transfer_state consulting_exit(struct attended_transfer_properties *props,
2089                 enum attended_transfer_stimulus stimulus)
2090 {
2091         switch (stimulus) {
2092         case STIMULUS_TRANSFEREE_HANGUP:
2093                 /* This is a one-of-a-kind event. The transferer and transfer target are talking in
2094                  * one bridge, and the transferee has hung up in a separate bridge. In this case, we
2095                  * will change the personality of the transfer target bridge back to normal, and play
2096                  * a sound to the transferer to indicate the transferee is gone.
2097                  */
2098                 bridge_basic_change_personality(props->target_bridge, BRIDGE_BASIC_PERSONALITY_NORMAL, NULL);
2099                 play_sound(props->transferer, props->failsound);
2100                 ast_bridge_merge_inhibit(props->target_bridge, -1);
2101                 /* These next two lines are here to ensure that our reference to the target bridge
2102                  * is cleaned up properly and that the target bridge is not destroyed when the
2103                  * monitor thread exits
2104                  */
2105                 ao2_ref(props->target_bridge, -1);
2106                 props->target_bridge = NULL;
2107                 return TRANSFER_FAIL;
2108         case STIMULUS_TRANSFERER_HANGUP:
2109         case STIMULUS_DTMF_ATXFER_COMPLETE:
2110                 /* We know the transferer is in the target_bridge, so take the other bridge off hold */
2111                 bridge_unhold(props->transferee_bridge);
2112                 return TRANSFER_COMPLETE;
2113         case STIMULUS_TRANSFER_TARGET_HANGUP:
2114         case STIMULUS_DTMF_ATXFER_ABORT:
2115                 play_sound(props->transferer, props->failsound);
2116                 return TRANSFER_REBRIDGE;
2117         case STIMULUS_DTMF_ATXFER_THREEWAY:
2118                 bridge_unhold(props->transferee_bridge);
2119                 return TRANSFER_THREEWAY;
2120         case STIMULUS_DTMF_ATXFER_SWAP:
2121                 hold(props->transferer);
2122                 bridge_move(props->transferee_bridge, props->target_bridge, props->transferer, NULL);
2123                 unhold(props->transferer);
2124                 return TRANSFER_DOUBLECHECKING;
2125         case STIMULUS_NONE:
2126         case STIMULUS_TIMEOUT:
2127         case STIMULUS_TRANSFER_TARGET_ANSWER:
2128         case STIMULUS_RECALL_TARGET_HANGUP:
2129         case STIMULUS_RECALL_TARGET_ANSWER:
2130         default:
2131                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2132                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2133                 return props->state;
2134         }
2135 }
2136
2137 static int double_checking_enter(struct attended_transfer_properties *props)
2138 {
2139         return 0;
2140 }
2141
2142 static enum attended_transfer_state double_checking_exit(struct attended_transfer_properties *props,
2143                 enum attended_transfer_stimulus stimulus)
2144 {
2145         switch (stimulus) {
2146         case STIMULUS_TRANSFEREE_HANGUP:
2147                 play_sound(props->transferer, props->failsound);
2148                 publish_transfer_fail(props);
2149                 return TRANSFER_FAIL;
2150         case STIMULUS_TRANSFERER_HANGUP:
2151         case STIMULUS_DTMF_ATXFER_COMPLETE:
2152                 /* We know the transferer is in the transferee, so take the other bridge off hold */
2153                 bridge_unhold(props->target_bridge);
2154                 return TRANSFER_COMPLETE;
2155         case STIMULUS_TRANSFER_TARGET_HANGUP:
2156         case STIMULUS_DTMF_ATXFER_ABORT:
2157                 play_sound(props->transferer, props->failsound);
2158                 return TRANSFER_RESUME;
2159         case STIMULUS_DTMF_ATXFER_THREEWAY:
2160                 bridge_unhold(props->target_bridge);
2161                 return TRANSFER_THREEWAY;
2162         case STIMULUS_DTMF_ATXFER_SWAP:
2163                 hold(props->transferer);
2164                 bridge_move(props->target_bridge, props->transferee_bridge, props->transferer, NULL);
2165                 unhold(props->transferer);
2166                 return TRANSFER_CONSULTING;
2167         case STIMULUS_NONE:
2168         case STIMULUS_TIMEOUT:
2169         case STIMULUS_TRANSFER_TARGET_ANSWER:
2170         case STIMULUS_RECALL_TARGET_HANGUP:
2171         case STIMULUS_RECALL_TARGET_ANSWER:
2172         default:
2173                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2174                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2175                 return props->state;
2176         }
2177 }
2178
2179 static int complete_enter(struct attended_transfer_properties *props)
2180 {
2181         bridge_merge(props->transferee_bridge, props->target_bridge, &props->transferer, 1);
2182         play_sound(props->transfer_target, props->xfersound);
2183         publish_transfer_success(props);
2184         return 0;
2185 }
2186
2187 static int blond_enter(struct attended_transfer_properties *props)
2188 {
2189         bridge_merge(props->transferee_bridge, props->target_bridge, &props->transferer, 1);
2190         ringing(props->transfer_target);
2191         publish_transfer_success(props);
2192         return 0;
2193 }
2194
2195 static int blond_nonfinal_enter(struct attended_transfer_properties *props)
2196 {
2197         int res;
2198         props->superstate = SUPERSTATE_RECALL;
2199         props->recall_target = ast_channel_ref(props->transfer_target);
2200         res = blond_enter(props);
2201         props->transfer_target = ast_channel_unref(props->transfer_target);
2202         return res;
2203 }
2204
2205 static enum attended_transfer_state blond_nonfinal_exit(struct attended_transfer_properties *props,
2206                 enum attended_transfer_stimulus stimulus)
2207 {
2208         switch (stimulus) {
2209         case STIMULUS_TRANSFEREE_HANGUP:
2210                 return TRANSFER_FAIL;
2211         case STIMULUS_RECALL_TARGET_ANSWER:
2212                 return TRANSFER_RESUME;
2213         case STIMULUS_TIMEOUT:
2214                 ast_softhangup(props->recall_target, AST_SOFTHANGUP_EXPLICIT);
2215                 props->recall_target = ast_channel_unref(props->recall_target);
2216         case STIMULUS_RECALL_TARGET_HANGUP:
2217                 return TRANSFER_RECALLING;
2218         case STIMULUS_NONE:
2219         case STIMULUS_DTMF_ATXFER_ABORT:
2220         case STIMULUS_DTMF_ATXFER_COMPLETE:
2221         case STIMULUS_DTMF_ATXFER_THREEWAY:
2222         case STIMULUS_DTMF_ATXFER_SWAP:
2223         case STIMULUS_TRANSFERER_HANGUP:
2224         case STIMULUS_TRANSFER_TARGET_HANGUP:
2225         case STIMULUS_TRANSFER_TARGET_ANSWER:
2226         default:
2227                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2228                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2229                 return props->state;
2230         }
2231 }
2232
2233 /*!
2234  * \brief Dial callback when attempting to recall the original transferer channel
2235  *
2236  * This is how we can monitor if the recall target has answered or has hung up.
2237  * If one of the two is detected, then an appropriate stimulus is sent to the
2238  * attended transfer monitor thread.
2239  */
2240 static void recall_callback(struct ast_dial *dial)
2241 {
2242         struct attended_transfer_properties *props = ast_dial_get_user_data(dial);
2243
2244         switch (ast_dial_state(dial)) {
2245         default:
2246         case AST_DIAL_RESULT_INVALID:
2247         case AST_DIAL_RESULT_FAILED:
2248         case AST_DIAL_RESULT_TIMEOUT:
2249         case AST_DIAL_RESULT_HANGUP:
2250         case AST_DIAL_RESULT_UNANSWERED:
2251                 /* Failure cases */
2252                 stimulate_attended_transfer(props, STIMULUS_RECALL_TARGET_HANGUP);
2253                 break;
2254         case AST_DIAL_RESULT_RINGING:
2255         case AST_DIAL_RESULT_PROGRESS:
2256         case AST_DIAL_RESULT_PROCEEDING:
2257         case AST_DIAL_RESULT_TRYING:
2258                 /* Don't care about these cases */
2259                 break;
2260         case AST_DIAL_RESULT_ANSWERED:
2261                 /* We struck gold! */
2262                 props->recall_target = ast_dial_answered_steal(dial);
2263                 stimulate_attended_transfer(props, STIMULUS_RECALL_TARGET_ANSWER);
2264                 break;
2265         }
2266 }
2267
2268
2269 static int recalling_enter(struct attended_transfer_properties *props)
2270 {
2271         RAII_VAR(struct ast_format_cap *, cap, ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT), ao2_cleanup);
2272
2273         if (!cap) {
2274                 return -1;
2275         }
2276
2277         ast_format_cap_append(cap, ast_format_slin, 0);
2278
2279         /* When we dial the transfer target, since we are communicating
2280          * with a local channel, we can place the local channel in a bridge
2281          * and then call out to it. When recalling the transferer, though, we
2282          * have to use the dialing API because the channel is not local.
2283          */
2284         props->dial = ast_dial_create();
2285         if (!props->dial) {
2286                 return -1;
2287         }
2288
2289         if (ast_dial_append(props->dial, props->transferer_type, props->transferer_addr, NULL)) {
2290                 return -1;
2291         }
2292
2293         if (ast_dial_prerun(props->dial, NULL, cap)) {
2294                 return -1;
2295         }
2296
2297         ast_dial_set_state_callback(props->dial, &recall_callback);
2298
2299         ao2_ref(props, +1);
2300         ast_dial_set_user_data(props->dial, props);
2301
2302         if (ast_dial_run(props->dial, NULL, 1) == AST_DIAL_RESULT_FAILED) {
2303                 ao2_ref(props, -1);
2304                 return -1;
2305         }
2306
2307         bridge_ringing(props->transferee_bridge);
2308         return 0;
2309 }
2310
2311 static enum attended_transfer_state recalling_exit(struct attended_transfer_properties *props,
2312                 enum attended_transfer_stimulus stimulus)
2313 {
2314         /* No matter what the outcome was, we need to kill off the dial */
2315         ast_dial_join(props->dial);
2316         ast_dial_destroy(props->dial);
2317         props->dial = NULL;
2318         /* This reference is the one we incremented for the dial state callback (recall_callback) to use */
2319         ao2_ref(props, -1);
2320
2321         switch (stimulus) {
2322         case STIMULUS_TRANSFEREE_HANGUP:
2323                 return TRANSFER_FAIL;
2324         case STIMULUS_TIMEOUT:
2325         case STIMULUS_RECALL_TARGET_HANGUP:
2326                 ++props->retry_attempts;
2327                 if (props->retry_attempts >= props->atxfercallbackretries) {
2328                         return TRANSFER_FAIL;
2329                 }
2330                 if (props->atxferloopdelay) {
2331                         return TRANSFER_WAIT_TO_RETRANSFER;
2332                 }
2333                 return TRANSFER_RETRANSFER;
2334         case STIMULUS_RECALL_TARGET_ANSWER:
2335                 /* Setting this datastore up will allow the transferer to have all of his
2336                  * call features set up automatically when the bridge changes back to a
2337                  * normal personality
2338                  */
2339                 ast_bridge_features_ds_set(props->recall_target, &props->transferer_features);
2340                 ast_channel_ref(props->recall_target);
2341                 if (ast_bridge_impart(props->transferee_bridge, props->recall_target, NULL, NULL,
2342                         AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
2343                         ast_hangup(props->recall_target);
2344                         return TRANSFER_FAIL;
2345                 }
2346                 return TRANSFER_RESUME;
2347         case STIMULUS_NONE:
2348         case STIMULUS_DTMF_ATXFER_ABORT:
2349         case STIMULUS_DTMF_ATXFER_COMPLETE:
2350         case STIMULUS_DTMF_ATXFER_THREEWAY:
2351         case STIMULUS_DTMF_ATXFER_SWAP:
2352         case STIMULUS_TRANSFER_TARGET_HANGUP:
2353         case STIMULUS_TRANSFER_TARGET_ANSWER:
2354         case STIMULUS_TRANSFERER_HANGUP:
2355         default:
2356                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2357                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2358                 return props->state;
2359         }
2360 }
2361
2362 static int wait_to_retransfer_enter(struct attended_transfer_properties *props)
2363 {
2364         bridge_hold(props->transferee_bridge);
2365         return 0;
2366 }
2367
2368 static enum attended_transfer_state wait_to_retransfer_exit(struct attended_transfer_properties *props,
2369                 enum attended_transfer_stimulus stimulus)
2370 {
2371         bridge_unhold(props->transferee_bridge);
2372         switch (stimulus) {
2373         case STIMULUS_TRANSFEREE_HANGUP:
2374                 return TRANSFER_FAIL;
2375         case STIMULUS_TIMEOUT:
2376                 return TRANSFER_RETRANSFER;
2377         case STIMULUS_NONE:
2378         case STIMULUS_DTMF_ATXFER_ABORT:
2379         case STIMULUS_DTMF_ATXFER_COMPLETE:
2380         case STIMULUS_DTMF_ATXFER_THREEWAY:
2381         case STIMULUS_DTMF_ATXFER_SWAP:
2382         case STIMULUS_TRANSFER_TARGET_HANGUP:
2383         case STIMULUS_TRANSFER_TARGET_ANSWER:
2384         case STIMULUS_TRANSFERER_HANGUP:
2385         case STIMULUS_RECALL_TARGET_HANGUP:
2386         case STIMULUS_RECALL_TARGET_ANSWER:
2387         default:
2388                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2389                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2390                 return props->state;
2391         }
2392 }
2393
2394 static int attach_framehook(struct attended_transfer_properties *props, struct ast_channel *channel);
2395
2396 static int retransfer_enter(struct attended_transfer_properties *props)
2397 {
2398         RAII_VAR(struct ast_format_cap *, cap, ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT), ao2_cleanup);
2399         char destination[AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2];
2400         int cause;
2401
2402         if (!cap) {
2403                 return -1;
2404         }
2405
2406         snprintf(destination, sizeof(destination), "%s@%s", props->exten, props->context);
2407
2408         ast_format_cap_append(cap, ast_format_slin, 0);
2409
2410         /* Get a channel that is the destination we wish to call */
2411         props->recall_target = ast_request("Local", cap, NULL, NULL, destination, &cause);
2412         if (!props->recall_target) {
2413                 ast_log(LOG_ERROR, "Unable to request outbound channel for recall target\n");
2414                 return -1;
2415         }
2416
2417         if (attach_framehook(props, props->recall_target)) {
2418                 ast_log(LOG_ERROR, "Unable to attach framehook to recall target\n");
2419                 ast_hangup(props->recall_target);
2420                 props->recall_target = NULL;
2421                 return -1;
2422         }
2423
2424         if (ast_call(props->recall_target, destination, 0)) {
2425                 ast_log(LOG_ERROR, "Unable to place outbound call to recall target\n");
2426                 ast_hangup(props->recall_target);
2427                 props->recall_target = NULL;
2428                 return -1;
2429         }
2430
2431         ast_channel_ref(props->recall_target);
2432         if (ast_bridge_impart(props->transferee_bridge, props->recall_target, NULL, NULL,
2433                 AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
2434                 ast_log(LOG_ERROR, "Unable to place recall target into bridge\n");
2435                 ast_hangup(props->recall_target);
2436                 return -1;
2437         }
2438
2439         return 0;
2440 }
2441
2442 static enum attended_transfer_state retransfer_exit(struct attended_transfer_properties *props,
2443                 enum attended_transfer_stimulus stimulus)
2444 {
2445         switch (stimulus) {
2446         case STIMULUS_TRANSFEREE_HANGUP:
2447                 return TRANSFER_FAIL;
2448         case STIMULUS_TIMEOUT:
2449                 ast_softhangup(props->recall_target, AST_SOFTHANGUP_EXPLICIT);
2450         case STIMULUS_RECALL_TARGET_HANGUP:
2451                 props->recall_target = ast_channel_unref(props->recall_target);
2452                 if (props->atxferloopdelay) {
2453                         return TRANSFER_WAIT_TO_RECALL;
2454                 }
2455                 return TRANSFER_RECALLING;
2456         case STIMULUS_RECALL_TARGET_ANSWER:
2457                 return TRANSFER_RESUME;
2458         case STIMULUS_NONE:
2459         case STIMULUS_DTMF_ATXFER_ABORT:
2460         case STIMULUS_DTMF_ATXFER_COMPLETE:
2461         case STIMULUS_DTMF_ATXFER_THREEWAY:
2462         case STIMULUS_DTMF_ATXFER_SWAP:
2463         case STIMULUS_TRANSFER_TARGET_HANGUP:
2464         case STIMULUS_TRANSFER_TARGET_ANSWER:
2465         case STIMULUS_TRANSFERER_HANGUP:
2466         default:
2467                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2468                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2469                 return props->state;
2470         }
2471 }
2472
2473 static int wait_to_recall_enter(struct attended_transfer_properties *props)
2474 {
2475         bridge_hold(props->transferee_bridge);
2476         return 0;
2477 }
2478
2479 static enum attended_transfer_state wait_to_recall_exit(struct attended_transfer_properties *props,
2480                 enum attended_transfer_stimulus stimulus)
2481 {
2482         bridge_unhold(props->transferee_bridge);
2483         switch (stimulus) {
2484         case STIMULUS_TRANSFEREE_HANGUP:
2485                 return TRANSFER_FAIL;
2486         case STIMULUS_TIMEOUT:
2487                 return TRANSFER_RECALLING;
2488         case STIMULUS_NONE:
2489         case STIMULUS_DTMF_ATXFER_ABORT:
2490         case STIMULUS_DTMF_ATXFER_COMPLETE:
2491         case STIMULUS_DTMF_ATXFER_THREEWAY:
2492         case STIMULUS_DTMF_ATXFER_SWAP:
2493         case STIMULUS_TRANSFER_TARGET_HANGUP:
2494         case STIMULUS_TRANSFER_TARGET_ANSWER:
2495         case STIMULUS_TRANSFERER_HANGUP:
2496         case STIMULUS_RECALL_TARGET_HANGUP:
2497         case STIMULUS_RECALL_TARGET_ANSWER:
2498         default:
2499                 ast_log(LOG_WARNING, "Unexpected stimulus '%s' received in attended transfer state '%s'\n",
2500                                 stimulus_strs[stimulus], state_properties[props->state].state_name);
2501                 return props->state;
2502         }
2503 }
2504
2505 static int fail_enter(struct attended_transfer_properties *props)
2506 {
2507         if (props->transferee_bridge) {
2508                 ast_bridge_destroy(props->transferee_bridge, 0);
2509                 props->transferee_bridge = NULL;
2510         }
2511         return 0;
2512 }
2513
2514 /*!
2515  * \brief DTMF hook when transferer presses abort sequence.
2516  *
2517  * Sends a stimulus to the attended transfer monitor thread that the abort sequence has been pressed
2518  */
2519 static int atxfer_abort(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2520 {
2521         struct attended_transfer_properties *props = hook_pvt;
2522
2523         ast_debug(1, "Transferer on attended transfer %p pressed abort sequence\n", props);
2524         stimulate_attended_transfer(props, STIMULUS_DTMF_ATXFER_ABORT);
2525         return 0;
2526 }
2527
2528 /*!
2529  * \brief DTMF hook when transferer presses complete sequence.
2530  *
2531  * Sends a stimulus to the attended transfer monitor thread that the complete sequence has been pressed
2532  */
2533 static int atxfer_complete(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2534 {
2535         struct attended_transfer_properties *props = hook_pvt;
2536
2537         ast_debug(1, "Transferer on attended transfer %p pressed complete sequence\n", props);
2538         stimulate_attended_transfer(props, STIMULUS_DTMF_ATXFER_COMPLETE);
2539         return 0;
2540 }
2541
2542 /*!
2543  * \brief DTMF hook when transferer presses threeway sequence.
2544  *
2545  * Sends a stimulus to the attended transfer monitor thread that the threeway sequence has been pressed
2546  */
2547 static int atxfer_threeway(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2548 {
2549         struct attended_transfer_properties *props = hook_pvt;
2550
2551         ast_debug(1, "Transferer on attended transfer %p pressed threeway sequence\n", props);
2552         stimulate_attended_transfer(props, STIMULUS_DTMF_ATXFER_THREEWAY);
2553         return 0;
2554 }
2555
2556 /*!
2557  * \brief DTMF hook when transferer presses swap sequence.
2558  *
2559  * Sends a stimulus to the attended transfer monitor thread that the swap sequence has been pressed
2560  */
2561 static int atxfer_swap(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2562 {
2563         struct attended_transfer_properties *props = hook_pvt;
2564
2565         ast_debug(1, "Transferer on attended transfer %p pressed swap sequence\n", props);
2566         stimulate_attended_transfer(props, STIMULUS_DTMF_ATXFER_SWAP);
2567         return 0;
2568 }
2569
2570 /*!
2571  * \brief Hangup hook for transferer channel.
2572  *
2573  * Sends a stimulus to the attended transfer monitor thread that the transferer has hung up.
2574  */
2575 static int atxfer_transferer_hangup(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
2576 {
2577         struct attended_transfer_properties *props = hook_pvt;
2578
2579         ast_debug(1, "Transferer on attended transfer %p hung up\n", props);
2580         stimulate_attended_transfer(props, STIMULUS_TRANSFERER_HANGUP);
2581         return 0;
2582 }
2583
2584 /*!
2585  * \brief Frame hook for transfer target channel
2586  *
2587  * This is used to determine if the transfer target or recall target has answered
2588  * the outgoing call.
2589  *
2590  * When an answer is detected, a stimulus is sent to the attended transfer monitor
2591  * thread to indicate that the transfer target or recall target has answered.
2592  *
2593  * \param chan The channel the framehook is attached to.
2594  * \param frame The frame being read or written.
2595  * \param event What is being done with the frame.
2596  * \param data The attended transfer properties.
2597  */
2598 static struct ast_frame *transfer_target_framehook_cb(struct ast_channel *chan,
2599                 struct ast_frame *frame, enum ast_framehook_event event, void *data)
2600 {
2601         struct attended_transfer_properties *props = data;
2602
2603         if (event == AST_FRAMEHOOK_EVENT_READ &&
2604                         frame && frame->frametype == AST_FRAME_CONTROL &&
2605                         frame->subclass.integer == AST_CONTROL_ANSWER) {
2606
2607                 ast_debug(1, "Detected an answer for recall attempt on attended transfer %p\n", props);
2608                 if (props->superstate == SUPERSTATE_TRANSFER) {
2609                         stimulate_attended_transfer(props, STIMULUS_TRANSFER_TARGET_ANSWER);
2610                 } else {
2611                         stimulate_attended_transfer(props, STIMULUS_RECALL_TARGET_ANSWER);
2612                 }
2613                 ast_framehook_detach(chan, props->target_framehook_id);
2614                 props->target_framehook_id = -1;
2615         }
2616
2617         return frame;
2618 }
2619
2620 /*! \brief Callback function which informs upstream if we are consuming a frame of a specific type */
2621 static int transfer_target_framehook_consume(void *data, enum ast_frame_type type)
2622 {
2623         return (type == AST_FRAME_CONTROL ? 1 : 0);
2624 }
2625
2626 static void transfer_target_framehook_destroy_cb(void *data)
2627 {
2628         struct attended_transfer_properties *props = data;
2629         ao2_cleanup(props);
2630 }
2631
2632 static int bridge_personality_atxfer_push(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct ast_bridge_channel *swap)
2633 {
2634         const char *abort_dtmf;
2635         const char *complete_dtmf;
2636         const char *threeway_dtmf;
2637         const char *swap_dtmf;
2638         struct bridge_basic_personality *personality = self->personality;
2639
2640         if (!ast_channel_has_role(bridge_channel->chan, AST_TRANSFERER_ROLE_NAME)) {
2641                 return 0;
2642         }
2643
2644         abort_dtmf = ast_channel_get_role_option(bridge_channel->chan, AST_TRANSFERER_ROLE_NAME, "abort");
2645         complete_dtmf = ast_channel_get_role_option(bridge_channel->chan, AST_TRANSFERER_ROLE_NAME, "complete");
2646         threeway_dtmf = ast_channel_get_role_option(bridge_channel->chan, AST_TRANSFERER_ROLE_NAME, "threeway");
2647         swap_dtmf = ast_channel_get_role_option(bridge_channel->chan, AST_TRANSFERER_ROLE_NAME, "swap");
2648
2649         if (!ast_strlen_zero(abort_dtmf) && ast_bridge_dtmf_hook(bridge_channel->features,
2650                         abort_dtmf, atxfer_abort, personality->details[personality->current].pvt, NULL,
2651                         AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE | AST_BRIDGE_HOOK_REMOVE_ON_PULL)) {
2652                 return -1;
2653         }
2654         if (!ast_strlen_zero(complete_dtmf) && ast_bridge_dtmf_hook(bridge_channel->features,
2655                         complete_dtmf, atxfer_complete, personality->details[personality->current].pvt, NULL,
2656                         AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE | AST_BRIDGE_HOOK_REMOVE_ON_PULL)) {
2657                 return -1;
2658         }
2659         if (!ast_strlen_zero(threeway_dtmf) && ast_bridge_dtmf_hook(bridge_channel->features,
2660                         threeway_dtmf, atxfer_threeway, personality->details[personality->current].pvt, NULL,
2661                         AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE | AST_BRIDGE_HOOK_REMOVE_ON_PULL)) {
2662                 return -1;
2663         }
2664         if (!ast_strlen_zero(swap_dtmf) && ast_bridge_dtmf_hook(bridge_channel->features,
2665                         swap_dtmf, atxfer_swap, personality->details[personality->current].pvt, NULL,
2666                         AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE | AST_BRIDGE_HOOK_REMOVE_ON_PULL)) {
2667                 return -1;
2668         }
2669         if (ast_bridge_hangup_hook(bridge_channel->features, atxfer_transferer_hangup,
2670                         personality->details[personality->current].pvt, NULL,
2671                         AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE | AST_BRIDGE_HOOK_REMOVE_ON_PULL)) {
2672                 return -1;
2673         }
2674
2675         return 0;
2676 }
2677
2678 static void transfer_pull(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct attended_transfer_properties *props)
2679 {
2680         if (self->num_channels > 1 || bridge_channel->state == BRIDGE_CHANNEL_STATE_WAIT) {
2681                 return;
2682         }
2683
2684         if (self->num_channels == 1) {
2685                 RAII_VAR(struct ast_bridge_channel *, transferer_bridge_channel, NULL, ao2_cleanup);
2686
2687                 ast_channel_lock(props->transferer);
2688                 transferer_bridge_channel = ast_channel_get_bridge_channel(props->transferer);
2689                 ast_channel_unlock(props->transferer);
2690
2691                 if (!transferer_bridge_channel) {
2692                         return;
2693                 }
2694
2695                 if (AST_LIST_FIRST(&self->channels) != transferer_bridge_channel) {
2696                         return;
2697                 }
2698         }
2699
2700         /* Reaching this point means that either
2701          * 1) The bridge has no channels in it
2702          * 2) The bridge has one channel, and it's the transferer
2703          * In either case, it indicates that the non-transferer parties
2704          * are no longer in the bridge.
2705          */
2706         if (self == props->transferee_bridge) {
2707                 stimulate_attended_transfer(props, STIMULUS_TRANSFEREE_HANGUP);
2708         } else {
2709                 stimulate_attended_transfer(props, STIMULUS_TRANSFER_TARGET_HANGUP);
2710         }
2711 }
2712
2713 static void recall_pull(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel, struct attended_transfer_properties *props)
2714 {
2715         if (self == props->target_bridge) {
2716                 /* Once we're in the recall superstate, we no longer care about this bridge */
2717                 return;
2718         }
2719
2720         if (bridge_channel->chan == props->recall_target) {
2721                 stimulate_attended_transfer(props, STIMULUS_RECALL_TARGET_HANGUP);
2722                 return;
2723         }
2724
2725         if (self->num_channels == 0) {
2726                 /* Empty bridge means all transferees are gone for sure */
2727                 stimulate_attended_transfer(props, STIMULUS_TRANSFEREE_HANGUP);
2728                 return;
2729         }
2730
2731         if (self->num_channels == 1) {
2732                 RAII_VAR(struct ast_bridge_channel *, target_bridge_channel, NULL, ao2_cleanup);
2733                 if (!props->recall_target) {
2734                         /* No recall target means that the pull happened on a transferee. If there's still
2735                          * a channel left in the bridge, we don't need to send a stimulus
2736                          */
2737                         return;
2738                 }
2739
2740                 ast_channel_lock(props->recall_target);
2741                 target_bridge_channel = ast_channel_get_bridge_channel(props->recall_target);
2742                 ast_channel_unlock(props->recall_target);
2743
2744                 if (!target_bridge_channel) {
2745                         return;
2746                 }
2747
2748                 if (AST_LIST_FIRST(&self->channels) == target_bridge_channel) {
2749                         stimulate_attended_transfer(props, STIMULUS_TRANSFEREE_HANGUP);
2750                 }
2751         }
2752 }
2753
2754 static void bridge_personality_atxfer_pull(struct ast_bridge *self, struct ast_bridge_channel *bridge_channel)
2755 {
2756         struct bridge_basic_personality *personality = self->personality;
2757         struct attended_transfer_properties *props = personality->details[personality->current].pvt;
2758
2759         switch (props->superstate) {
2760         case SUPERSTATE_TRANSFER:
2761                 transfer_pull(self, bridge_channel, props);
2762                 break;
2763         case SUPERSTATE_RECALL:
2764                 recall_pull(self, bridge_channel, props);
2765                 break;
2766         }
2767 }
2768
2769 static enum attended_transfer_stimulus wait_for_stimulus(struct attended_transfer_properties *props)
2770 {
2771         RAII_VAR(struct stimulus_list *, list, NULL, ast_free_ptr);
2772         SCOPED_MUTEX(lock, ao2_object_get_lockaddr(props));
2773
2774         while (!(list = AST_LIST_REMOVE_HEAD(&props->stimulus_queue, next))) {
2775                 if (!(state_properties[props->state].flags & TRANSFER_STATE_FLAG_TIMED)) {
2776                         ast_cond_wait(&props->cond, lock);
2777                 } else {
2778                         struct timeval relative_timeout = { 0, };
2779                         struct timeval absolute_timeout;
2780                         struct timespec timeout_arg;
2781
2782                         if (state_properties[props->state].flags & TRANSFER_STATE_FLAG_TIMER_RESET) {
2783                                 props->start = ast_tvnow();
2784                         }
2785
2786                         if (state_properties[props->state].flags & TRANSFER_STATE_FLAG_TIMER_LOOP_DELAY) {
2787                                 relative_timeout.tv_sec = props->atxferloopdelay;
2788                         } else {
2789                                 /* Implied TRANSFER_STATE_FLAG_TIMER_ATXFER_NO_ANSWER */
2790                                 relative_timeout.tv_sec = props->atxfernoanswertimeout;
2791                         }
2792
2793                         absolute_timeout = ast_tvadd(props->start, relative_timeout);
2794                         timeout_arg.tv_sec = absolute_timeout.tv_sec;
2795                         timeout_arg.tv_nsec = absolute_timeout.tv_usec * 1000;
2796
2797                         if (ast_cond_timedwait(&props->cond, lock, &timeout_arg) == ETIMEDOUT) {
2798                                 return STIMULUS_TIMEOUT;
2799                         }
2800                 }
2801         }
2802         return list->stimulus;
2803 }
2804
2805 /*!
2806  * \brief The main loop for the attended transfer monitor thread.
2807  *
2808  * This loop runs continuously until the attended transfer reaches
2809  * a terminal state. Stimuli for changes in the attended transfer
2810  * state are handled in this thread so that all factors in an
2811  * attended transfer can be handled in an orderly fashion.
2812  *
2813  * \param data The attended transfer properties
2814  */
2815 static void *attended_transfer_monitor_thread(void *data)
2816 {
2817         struct attended_transfer_properties *props = data;
2818
2819         for (;;) {
2820                 enum attended_transfer_stimulus stimulus;
2821
2822                 ast_debug(1, "About to enter state %s for attended transfer %p\n", state_properties[props->state].state_name, props);
2823
2824                 if (state_properties[props->state].enter &&
2825                                 state_properties[props->state].enter(props)) {
2826                         ast_log(LOG_ERROR, "State %s enter function returned an error for attended transfer %p\n",
2827                                         state_properties[props->state].state_name, props);
2828                         break;
2829                 }
2830
2831                 if (state_properties[props->state].flags & TRANSFER_STATE_FLAG_TERMINAL) {
2832                         ast_debug(1, "State %s is a terminal state. Ending attended transfer %p\n",
2833                                         state_properties[props->state].state_name, props);
2834                         break;
2835                 }
2836
2837                 stimulus = wait_for_stimulus(props);
2838
2839                 ast_debug(1, "Received stimulus %s on attended transfer %p\n", stimulus_strs[stimulus], props);
2840
2841                 ast_assert(state_properties[props->state].exit != NULL);
2842
2843                 props->state = state_properties[props->state].exit(props, stimulus);
2844
2845                 ast_debug(1, "Told to enter state %s exit on attended transfer %p\n", state_properties[props->state].state_name, props);
2846         }
2847
2848         attended_transfer_properties_shutdown(props);
2849
2850         return NULL;
2851 }
2852
2853 static int attach_framehook(struct attended_transfer_properties *props, struct ast_channel *channel)
2854 {
2855         struct ast_framehook_interface target_interface = {
2856                 .version = AST_FRAMEHOOK_INTERFACE_VERSION,
2857                 .event_cb = transfer_target_framehook_cb,
2858                 .destroy_cb = transfer_target_framehook_destroy_cb,
2859                 .consume_cb = transfer_target_framehook_consume,
2860                 .disable_inheritance = 1,
2861         };
2862
2863         ao2_ref(props, +1);
2864         target_interface.data = props;
2865
2866         props->target_framehook_id = ast_framehook_attach(channel, &target_interface);
2867         if (props->target_framehook_id == -1) {
2868                 ao2_ref(props, -1);
2869                 return -1;
2870         }
2871         return 0;
2872 }
2873
2874 static int add_transferer_role(struct ast_channel *chan, struct ast_bridge_features_attended_transfer *attended_transfer)
2875 {
2876         const char *atxfer_abort;
2877         const char *atxfer_threeway;
2878         const char *atxfer_complete;
2879         const char *atxfer_swap;
2880         RAII_VAR(struct ast_features_xfer_config *, xfer_cfg, NULL, ao2_cleanup);
2881         SCOPED_CHANNELLOCK(lock, chan);
2882
2883         xfer_cfg = ast_get_chan_features_xfer_config(chan);
2884         if (!xfer_cfg) {
2885                 return -1;
2886         }
2887         if (attended_transfer) {
2888                 atxfer_abort = ast_strdupa(S_OR(attended_transfer->abort, xfer_cfg->atxferabort));
2889                 atxfer_threeway = ast_strdupa(S_OR(attended_transfer->threeway, xfer_cfg->atxferthreeway));
2890                 atxfer_complete = ast_strdupa(S_OR(attended_transfer->complete, xfer_cfg->atxfercomplete));
2891                 atxfer_swap = ast_strdupa(S_OR(attended_transfer->swap, xfer_cfg->atxferswap));
2892         } else {
2893                 atxfer_abort = ast_strdupa(xfer_cfg->atxferabort);
2894                 atxfer_threeway = ast_strdupa(xfer_cfg->atxferthreeway);
2895                 atxfer_complete = ast_strdupa(xfer_cfg->atxfercomplete);
2896                 atxfer_swap = ast_strdupa(xfer_cfg->atxferswap);
2897         }
2898
2899         return ast_channel_add_bridge_role(chan, AST_TRANSFERER_ROLE_NAME) ||
2900                 ast_channel_set_bridge_role_option(chan, AST_TRANSFERER_ROLE_NAME, "abort", atxfer_abort) ||
2901                 ast_channel_set_bridge_role_option(chan, AST_TRANSFERER_ROLE_NAME, "complete", atxfer_complete) ||
2902                 ast_channel_set_bridge_role_option(chan, AST_TRANSFERER_ROLE_NAME, "threeway", atxfer_threeway) ||
2903                 ast_channel_set_bridge_role_option(chan, AST_TRANSFERER_ROLE_NAME, "swap", atxfer_swap);
2904 }
2905
2906 /*!
2907  * \brief Helper function that presents dialtone and grabs extension
2908  *
2909  * \retval 0 on success
2910  * \retval -1 on failure
2911  */
2912 static int grab_transfer(struct ast_channel *chan, char *exten, size_t exten_len, const char *context)
2913 {
2914         int res;
2915         int digit_timeout;
2916         RAII_VAR(struct ast_features_xfer_config *, xfer_cfg, NULL, ao2_cleanup);
2917
2918         ast_channel_lock(chan);
2919         xfer_cfg = ast_get_chan_features_xfer_config(chan);
2920         if (!xfer_cfg) {
2921                 ast_log(LOG_ERROR, "Unable to get transfer configuration\n");
2922                 ast_channel_unlock(chan);
2923                 return -1;
2924         }
2925         digit_timeout = xfer_cfg->transferdigittimeout * 1000;
2926         ast_channel_unlock(chan);
2927
2928         /* Play the simple "transfer" prompt out and wait */
2929         res = ast_stream_and_wait(chan, "pbx-transfer", AST_DIGIT_ANY);
2930         ast_stopstream(chan);
2931         if (res < 0) {
2932                 /* Hangup or error */
2933                 return -1;
2934         }
2935         if (res) {
2936                 /* Store the DTMF digit that interrupted playback of the file. */
2937                 exten[0] = res;
2938         }
2939
2940         /* Drop to dialtone so they can enter the extension they want to transfer to */
2941         res = ast_app_dtget(chan, context, exten, exten_len, exten_len - 1, digit_timeout);
2942         if (res < 0) {
2943                 /* Hangup or error */
2944                 res = -1;
2945         } else if (!res) {
2946                 /* 0 for invalid extension dialed. */
2947                 if (ast_strlen_zero(exten)) {
2948                         ast_debug(1, "%s dialed no digits.\n", ast_channel_name(chan));
2949                 } else {
2950                         ast_debug(1, "%s dialed '%s@%s' does not exist.\n",
2951                                 ast_channel_name(chan), exten, context);
2952                 }
2953                 ast_stream_and_wait(chan, "pbx-invalid", AST_DIGIT_NONE);
2954                 res = -1;
2955         } else {
2956                 /* Dialed extension is valid. */
2957                 res = 0;
2958         }
2959         return res;
2960 }
2961
2962 static void copy_caller_data(struct ast_channel *dest, struct ast_channel *caller)
2963 {
2964         ast_channel_lock_both(caller, dest);
2965         ast_connected_line_copy_from_caller(ast_channel_connected(dest), ast_channel_caller(caller));
2966         ast_channel_inherit_variables(caller, dest);
2967         ast_channel_datastore_inherit(caller, dest);
2968         ast_channel_unlock(dest);
2969         ast_channel_unlock(caller);
2970 }
2971
2972 /*! \brief Helper function that creates an outgoing channel and returns it immediately */
2973 static struct ast_channel *dial_transfer(struct ast_channel *caller, const char *destination)
2974 {
2975         struct ast_channel *chan;
2976         int cause;
2977
2978         /* Now we request a local channel to prepare to call the destination */
2979         chan = ast_request("Local", ast_channel_nativeformats(caller), NULL, caller, destination,
2980                 &cause);
2981         if (!chan) {
2982                 return NULL;
2983         }
2984
2985         /* Who is transferring the call. */
2986         pbx_builtin_setvar_helper(chan, "TRANSFERERNAME", ast_channel_name(caller));
2987
2988         ast_bridge_set_transfer_variables(chan, ast_channel_name(caller), 1);
2989
2990         /* Before we actually dial out let's inherit appropriate information. */
2991         copy_caller_data(chan, caller);
2992
2993         return chan;
2994 }
2995
2996 /*!
2997  * \brief Internal built in feature for attended transfers
2998  *
2999  * This hook will set up a thread for monitoring the progress of
3000  * an attended transfer. For more information about attended transfer
3001  * progress, see documentation on the transfer state machine.
3002  *
3003  * \param bridge_channel The channel that pressed the attended transfer DTMF sequence
3004  * \param hook_pvt Structure with further information about the attended transfer
3005  */
3006 static int feature_attended_transfer(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
3007 {
3008         struct ast_bridge_features_attended_transfer *attended_transfer = hook_pvt;
3009         struct attended_transfer_properties *props;
3010         struct ast_bridge *bridge;
3011         char destination[AST_MAX_EXTENSION + AST_MAX_CONTEXT + 1];
3012         char exten[AST_MAX_EXTENSION] = "";
3013         pthread_t thread;
3014
3015         /* Inhibit the bridge before we do anything else. */
3016         bridge = ast_bridge_channel_merge_inhibit(bridge_channel, +1);
3017
3018         if (strcmp(bridge->v_table->name, "basic")) {
3019                 ast_log(LOG_ERROR, "Attended transfer attempted on unsupported bridge type '%s'.\n",
3020                         bridge->v_table->name);
3021                 ast_bridge_merge_inhibit(bridge, -1);
3022                 ao2_ref(bridge, -1);
3023                 return 0;
3024         }
3025
3026         /* Was the bridge inhibited before we inhibited it? */
3027         if (1 < bridge->inhibit_merge) {
3028                 /*
3029                  * The peer likely initiated attended transfer at the same time
3030                  * and we lost the race.
3031                  */
3032                 ast_verb(3, "Channel %s: Bridge '%s' does not permit merging at this time.\n",
3033                         ast_channel_name(bridge_channel->chan), bridge->uniqueid);
3034                 ast_bridge_merge_inhibit(bridge, -1);
3035                 ao2_ref(bridge, -1);
3036                 return 0;
3037         }
3038
3039         props = attended_transfer_properties_alloc(bridge_channel->chan,
3040                 attended_transfer ? attended_transfer->context : NULL);
3041         if (!props) {
3042                 ast_log(LOG_ERROR, "Unable to allocate control structure for performing attended transfer.\n");
3043                 ast_bridge_merge_inhibit(bridge, -1);
3044                 ao2_ref(bridge, -1);
3045                 return 0;
3046         }
3047
3048         props->transferee_bridge = bridge;
3049
3050         if (add_transferer_role(props->transferer, attended_transfer)) {
3051                 ast_log(LOG_ERROR, "Unable to set transferrer bridge role.\n");
3052                 attended_transfer_properties_shutdown(props);
3053                 return 0;
3054         }
3055
3056         ast_bridge_channel_write_hold(bridge_channel, NULL);
3057
3058         /* Grab the extension to transfer to */
3059         if (grab_transfer(bridge_channel->chan, exten, sizeof(exten), props->context)) {
3060                 ast_log(LOG_WARNING, "Unable to acquire target extension for attended transfer.\n");
3061                 ast_bridge_channel_write_unhold(bridge_channel);
3062                 attended_transfer_properties_shutdown(props);
3063                 return 0;
3064         }
3065
3066         ast_string_field_set(props, exten, exten);
3067
3068         /* Fill the variable with the extension and context we want to call */
3069         snprintf(destination, sizeof(destination), "%s@%s", props->exten, props->context);
3070
3071         ast_debug(1, "Attended transfer to '%s'\n", destination);
3072
3073         /* Get a channel that is the destination we wish to call */
3074         props->transfer_target = dial_transfer(bridge_channel->chan, destination);
3075         if (!props->transfer_target) {
3076                 ast_log(LOG_ERROR, "Unable to request outbound channel for attended transfer target.\n");
3077                 ast_stream_and_wait(props->transferer, props->failsound, AST_DIGIT_NONE);
3078                 ast_bridge_channel_write_unhold(bridge_channel);
3079                 attended_transfer_properties_shutdown(props);
3080                 return 0;
3081         }
3082
3083
3084         /* Create a bridge to use to talk to the person we are calling */
3085         props->target_bridge = ast_bridge_basic_new();
3086         if (!props->target_bridge) {
3087                 ast_log(LOG_ERROR, "Unable to create bridge for attended transfer target.\n");
3088                 ast_stream_and_wait(props->transferer, props->failsound, AST_DIGIT_NONE);
3089                 ast_bridge_channel_write_unhold(bridge_channel);
3090                 ast_hangup(props->transfer_target);
3091                 props->transfer_target = NULL;
3092                 attended_transfer_properties_shutdown(props);
3093                 return 0;
3094         }
3095         ast_bridge_merge_inhibit(props->target_bridge, +1);
3096
3097         if (attach_framehook(props, props->transfer_target)) {
3098                 ast_log(LOG_ERROR, "Unable to attach framehook to transfer target.\n");
3099                 ast_stream_and_wait(props->transferer, props->failsound, AST_DIGIT_NONE);
3100                 ast_bridge_channel_write_unhold(bridge_channel);
3101                 ast_hangup(props->transfer_target);
3102                 props->transfer_target = NULL;
3103                 attended_transfer_properties_shutdown(props);
3104                 return 0;
3105         }
3106
3107         bridge_basic_change_personality(props->target_bridge,
3108                         BRIDGE_BASIC_PERSONALITY_ATXFER, props);
3109         bridge_basic_change_personality(bridge,
3110                         BRIDGE_BASIC_PERSONALITY_ATXFER, props);
3111
3112         if (ast_call(props->transfer_target, destination, 0)) {
3113                 ast_log(LOG_ERROR, "Unable to place outbound call to transfer target.\n");
3114                 ast_stream_and_wait(bridge_channel->chan, props->failsound, AST_DIGIT_NONE);
3115                 ast_bridge_channel_write_unhold(bridge_channel);
3116                 ast_hangup(props->transfer_target);
3117                 props->transfer_target = NULL;
3118                 attended_transfer_properties_shutdown(props);
3119                 return 0;
3120         }
3121
3122         /* We increase the refcount of the transfer target because ast_bridge_impart() will
3123          * steal the reference we already have. We need to keep a reference, so the only
3124          * choice is to give it a bump
3125          */
3126         ast_channel_ref(props->transfer_target);
3127         if (ast_bridge_impart(props->target_bridge, props->transfer_target, NULL, NULL,
3128                 AST_BRIDGE_IMPART_CHAN_INDEPENDENT)) {
3129                 ast_log(LOG_ERROR, "Unable to place transfer target into bridge.\n");
3130                 ast_stream_and_wait(bridge_channel->chan, props->failsound, AST_DIGIT_NONE);
3131                 ast_bridge_channel_write_unhold(bridge_channel);
3132                 ast_hangup(props->transfer_target);
3133                 props->transfer_target = NULL;
3134                 attended_transfer_properties_shutdown(props);
3135                 return 0;
3136         }
3137
3138         if (ast_pthread_create_detached(&thread, NULL, attended_transfer_monitor_thread, props)) {
3139                 ast_log(LOG_ERROR, "Unable to create monitoring thread for attended transfer.\n");
3140                 ast_stream_and_wait(bridge_channel->chan, props->failsound, AST_DIGIT_NONE);
3141                 ast_bridge_channel_write_unhold(bridge_channel);
3142                 attended_transfer_properties_shutdown(props);
3143                 return 0;
3144         }
3145
3146         /* Once the monitoring thread has been created, it is responsible for destroying all
3147          * of the necessary components.
3148          */
3149         return 0;
3150 }
3151
3152 static void blind_transfer_cb(struct ast_channel *new_channel, struct transfer_channel_data *user_data_wrapper,
3153                 enum ast_transfer_type transfer_type)
3154 {
3155         struct ast_channel *transferer_channel = user_data_wrapper->data;
3156
3157         if (transfer_type == AST_BRIDGE_TRANSFER_MULTI_PARTY) {
3158                 copy_caller_data(new_channel, transferer_channel);
3159         }
3160 }
3161
3162 /*! \brief Internal built in feature for blind transfers */
3163 static int feature_blind_transfer(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
3164 {
3165         char exten[AST_MAX_EXTENSION] = "";
3166         struct ast_bridge_features_blind_transfer *blind_transfer = hook_pvt;
3167         const char *context;
3168         char *goto_on_blindxfr;
3169
3170         ast_bridge_channel_write_hold(bridge_channel, NULL);
3171
3172         ast_channel_lock(bridge_channel->chan);
3173         context = ast_strdupa(get_transfer_context(bridge_channel->chan,
3174                 blind_transfer ? blind_transfer->context : NULL));
3175         goto_on_blindxfr = ast_strdupa(S_OR(pbx_builtin_getvar_helper(bridge_channel->chan,
3176                 "GOTO_ON_BLINDXFR"), ""));
3177         ast_channel_unlock(bridge_channel->chan);
3178
3179         /* Grab the extension to transfer to */
3180         if (grab_transfer(bridge_channel->chan, exten, sizeof(exten), context)) {
3181                 ast_bridge_channel_write_unhold(bridge_channel);
3182                 return 0;
3183         }
3184
3185         if (!ast_strlen_zero(goto_on_blindxfr)) {
3186                 ast_debug(1, "After transfer, transferer %s goes to %s\n",
3187                                 ast_channel_name(bridge_channel->chan), goto_on_blindxfr);
3188                 ast_bridge_set_after_go_on(bridge_channel->chan, NULL, NULL, 0, goto_on_blindxfr);
3189         }
3190
3191         if (ast_bridge_transfer_blind(0, bridge_channel->chan, exten, context, blind_transfer_cb,
3192                         bridge_channel->chan) != AST_BRIDGE_TRANSFER_SUCCESS &&
3193                         !ast_strlen_zero(goto_on_blindxfr)) {
3194                 ast_bridge_discard_after_goto(bridge_channel->chan);
3195         }
3196
3197         return 0;
3198 }
3199
3200 struct ast_bridge_methods ast_bridge_basic_v_table;
3201 struct ast_bridge_methods personality_normal_v_table;
3202 struct ast_bridge_methods personality_atxfer_v_table;
3203
3204 static void bridge_basic_change_personality(struct ast_bridge *bridge,
3205                 enum bridge_basic_personality_type type, void *user_data)
3206 {
3207         struct bridge_basic_personality *personality = bridge->personality;
3208         SCOPED_LOCK(lock, bridge, ast_bridge_lock, ast_bridge_unlock);
3209
3210         remove_hooks_on_personality_change(bridge);
3211
3212         ao2_cleanup(personality->details[personality->current].pvt);
3213         personality->details[personality->current].pvt = NULL;
3214         ast_clear_flag(&bridge->feature_flags, AST_FLAGS_ALL);
3215
3216         personality->current = type;
3217         if (user_data) {
3218                 ao2_ref(user_data, +1);
3219         }
3220         personality->details[personality->current].pvt = user_data;
3221         ast_set_flag(&bridge->feature_flags, personality->details[personality->current].bridge_flags);
3222         if (personality->details[personality->current].on_personality_change) {
3223                 personality->details[personality->current].on_personality_change(bridge);
3224         }
3225 }
3226
3227 static void personality_destructor(void *obj)
3228 {
3229         struct bridge_basic_personality *personality = obj;
3230         int i;
3231
3232         for (i = 0; i < BRIDGE_BASIC_PERSONALITY_END; ++i) {
3233                 ao2_cleanup(personality->details[i].pvt);
3234         }
3235 }
3236
3237 static void on_personality_change_normal(struct ast_bridge *bridge)
3238 {
3239         struct ast_bridge_channel *iter;
3240
3241         AST_LIST_TRAVERSE(&bridge->channels, iter, entry) {
3242                 if (add_normal_hooks(bridge, iter)) {
3243                         ast_log(LOG_WARNING, "Unable to set up bridge hooks for channel %s. Features may not work properly\n",
3244                                         ast_channel_name(iter->chan));
3245                 }
3246         }
3247 }
3248
3249 static void init_details(struct personality_details *details,
3250                 enum bridge_basic_personality_type type)
3251 {
3252         switch (type) {
3253         case BRIDGE_BASIC_PERSONALITY_NORMAL:
3254                 details->v_table = &personality_normal_v_table;
3255                 details->bridge_flags = NORMAL_FLAGS;
3256                 details->on_personality_change = on_personality_change_normal;
3257                 break;
3258         case BRIDGE_BASIC_PERSONALITY_ATXFER:
3259                 details->v_table = &personality_atxfer_v_table;
3260                 details->bridge_flags = TRANSFER_FLAGS;
3261                 break;
3262         default:
3263                 ast_log(LOG_WARNING, "Asked to initialize unexpected basic bridge personality type.\n");
3264                 break;
3265         }
3266 }
3267
3268 static struct ast_bridge *bridge_basic_personality_alloc(struct ast_bridge *bridge)
3269 {
3270         struct bridge_basic_personality *personality;
3271         int i;
3272
3273         if (!bridge) {
3274                 return NULL;
3275         }
3276
3277         personality = ao2_alloc(sizeof(*personality), personality_destructor);
3278         if (!personality) {
3279                 ao2_ref(bridge, -1);
3280                 return NULL;
3281         }
3282         for (i = 0; i < BRIDGE_BASIC_PERSONALITY_END; ++i) {
3283                 init_details(&personality->details[i], i);
3284         }
3285         personality->current = BRIDGE_BASIC_PERSONALITY_NORMAL;
3286         bridge->personality = personality;
3287
3288         return bridge;
3289 }
3290
3291 struct ast_bridge *ast_bridge_basic_new(void)
3292 {
3293         struct ast_bridge *bridge;
3294
3295         bridge = bridge_alloc(sizeof(struct ast_bridge), &ast_bridge_basic_v_table);
3296         bridge = bridge_base_init(bridge,
3297                 AST_BRIDGE_CAPABILITY_NATIVE | AST_BRIDGE_CAPABILITY_1TO1MIX
3298                         | AST_BRIDGE_CAPABILITY_MULTIMIX, NORMAL_FLAGS, NULL, NULL, NULL);
3299         bridge = bridge_basic_personality_alloc(bridge);
3300         bridge = bridge_register(bridge);
3301         return bridge;
3302 }
3303
3304 void ast_bridge_basic_set_flags(struct ast_bridge *bridge, unsigned int flags)
3305 {
3306         SCOPED_LOCK(lock, bridge, ast_bridge_lock, ast_bridge_unlock);
3307         struct bridge_basic_personality *personality = bridge->personality;
3308
3309         personality->details[personality->current].bridge_flags |= flags;
3310         ast_set_flag(&bridge->feature_flags, flags);
3311 }
3312
3313 void ast_bridging_init_basic(void)
3314 {
3315         /* Setup bridge basic subclass v_table. */
3316         ast_bridge_basic_v_table = ast_bridge_base_v_table;
3317         ast_bridge_basic_v_table.name = "basic";
3318         ast_bridge_basic_v_table.push = bridge_basic_push;
3319         ast_bridge_basic_v_table.pull = bridge_basic_pull;
3320         ast_bridge_basic_v_table.destroy = bridge_basic_destroy;
3321
3322         /*
3323          * Personality vtables don't have the same rules as
3324          * normal bridge vtables.  These vtable functions are
3325          * used as alterations to the ast_bridge_basic_v_table
3326          * method functionality and are checked for NULL before
3327          * calling.
3328          */
3329         personality_normal_v_table.name = "normal";
3330         personality_normal_v_table.push = bridge_personality_normal_push;
3331
3332         personality_atxfer_v_table.name = "attended transfer";
3333         personality_atxfer_v_table.push = bridge_personality_atxfer_push;
3334         personality_atxfer_v_table.pull = bridge_personality_atxfer_pull;
3335
3336         ast_bridge_features_register(AST_BRIDGE_BUILTIN_ATTENDEDTRANSFER, feature_attended_transfer, NULL);
3337         ast_bridge_features_register(AST_BRIDGE_BUILTIN_BLINDTRANSFER, feature_blind_transfer, NULL);
3338 }
3339