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