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