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