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