Add transfer support to CEL
[asterisk/asterisk.git] / main / features.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2012, Digium, Inc.
5  * Copyright (C) 2012, Russell Bryant
6  *
7  * Mark Spencer <markster@digium.com>
8  *
9  * See http://www.asterisk.org for more information about
10  * the Asterisk project. Please do not directly contact
11  * any of the maintainers of this project for assistance;
12  * the project provides a web site, mailing lists and IRC
13  * channels for your use.
14  *
15  * This program is free software, distributed under the terms of
16  * the GNU General Public License Version 2. See the LICENSE file
17  * at the top of the source tree.
18  */
19
20 /*! \file
21  *
22  * \brief Routines implementing call features as call pickup, parking and transfer
23  *
24  * \author Mark Spencer <markster@digium.com>
25  */
26
27 /*! \li \ref features.c uses the configuration file \ref features.conf
28  * \addtogroup configuration_file Configuration Files
29  */
30
31 /*!
32  * \page features.conf features.conf
33  * \verbinclude features.conf.sample
34  */
35
36 /*** MODULEINFO
37         <support_level>core</support_level>
38  ***/
39
40 #include "asterisk.h"
41
42 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
43
44 #include "asterisk/_private.h"
45
46 #include <pthread.h>
47 #include <signal.h>
48 #include <sys/time.h>
49 #include <sys/signal.h>
50 #include <netinet/in.h>
51
52 #include "asterisk/lock.h"
53 #include "asterisk/file.h"
54 #include "asterisk/channel.h"
55 #include "asterisk/pbx.h"
56 #include "asterisk/causes.h"
57 #include "asterisk/module.h"
58 #include "asterisk/translate.h"
59 #include "asterisk/app.h"
60 #include "asterisk/say.h"
61 #include "asterisk/features.h"
62 #include "asterisk/musiconhold.h"
63 #include "asterisk/config.h"
64 #include "asterisk/cli.h"
65 #include "asterisk/manager.h"
66 #include "asterisk/utils.h"
67 #include "asterisk/adsi.h"
68 #include "asterisk/devicestate.h"
69 #include "asterisk/monitor.h"
70 #include "asterisk/audiohook.h"
71 #include "asterisk/global_datastores.h"
72 #include "asterisk/astobj2.h"
73 #include "asterisk/test.h"
74 #include "asterisk/bridging.h"
75 #include "asterisk/bridging_basic.h"
76 #include "asterisk/stasis.h"
77 #include "asterisk/stasis_channels.h"
78 #include "asterisk/features_config.h"
79
80 /* BUGBUG TEST_FRAMEWORK is disabled because parking tests no longer work. */
81 #undef TEST_FRAMEWORK
82
83 /*
84  * Party A - transferee
85  * Party B - transferer
86  * Party C - target of transfer
87  *
88  * DTMF attended transfer works within the channel bridge.
89  * Unfortunately, when either party A or B in the channel bridge
90  * hangs up, that channel is not completely hung up until the
91  * transfer completes.  This is a real problem depending upon
92  * the channel technology involved.
93  *
94  * For chan_dahdi, the channel is crippled until the hangup is
95  * complete.  Either the channel is not useable (analog) or the
96  * protocol disconnect messages are held up (PRI/BRI/SS7) and
97  * the media is not released.
98  *
99  * For chan_sip, a call limit of one is going to block that
100  * endpoint from any further calls until the hangup is complete.
101  *
102  * For party A this is a minor problem.  The party A channel
103  * will only be in this condition while party B is dialing and
104  * when party B and C are conferring.  The conversation between
105  * party B and C is expected to be a short one.  Party B is
106  * either asking a question of party C or announcing party A.
107  * Also party A does not have much incentive to hangup at this
108  * point.
109  *
110  * For party B this can be a major problem during a blonde
111  * transfer.  (A blonde transfer is our term for an attended
112  * transfer that is converted into a blind transfer. :))  Party
113  * B could be the operator.  When party B hangs up, he assumes
114  * that he is out of the original call entirely.  The party B
115  * channel will be in this condition while party C is ringing,
116  * while attempting to recall party B, and while waiting between
117  * call attempts.
118  *
119  * WARNING:
120  * The ATXFER_NULL_TECH conditional is a hack to fix the
121  * problem.  It will replace the party B channel technology with
122  * a NULL channel driver.  The consequences of this code is that
123  * the 'h' extension will not be able to access any channel
124  * technology specific information like SIP statistics for the
125  * call.
126  *
127  * Uncomment the ATXFER_NULL_TECH define below to replace the
128  * party B channel technology in the channel bridge to complete
129  * hanging up the channel technology.
130  */
131 //#define ATXFER_NULL_TECH      1
132
133 /*** DOCUMENTATION
134         <application name="Bridge" language="en_US">
135                 <synopsis>
136                         Bridge two channels.
137                 </synopsis>
138                 <syntax>
139                         <parameter name="channel" required="true">
140                                 <para>The current channel is bridged to the specified <replaceable>channel</replaceable>.</para>
141                         </parameter>
142                         <parameter name="options">
143                                 <optionlist>
144                                         <option name="p">
145                                                 <para>Play a courtesy tone to <replaceable>channel</replaceable>.</para>
146                                         </option>
147                                         <option name="F" argsep="^">
148                                                 <argument name="context" required="false" />
149                                                 <argument name="exten" required="false" />
150                                                 <argument name="priority" required="true" />
151                                                 <para>When the bridger hangs up, transfer the <emphasis>bridged</emphasis> party
152                                                 to the specified destination and <emphasis>start</emphasis> execution at that location.</para>
153                                                 <note>
154                                                         <para>Any channel variables you want the called channel to inherit from the caller channel must be
155                                                         prefixed with one or two underbars ('_').</para>
156                                                 </note>
157                                                 <note>
158                                                         <para>This option will override the 'x' option</para>
159                                                 </note>
160                                         </option>
161                                         <option name="F">
162                                                 <para>When the bridger hangs up, transfer the <emphasis>bridged</emphasis> party
163                                                 to the next priority of the current extension and <emphasis>start</emphasis> execution
164                                                 at that location.</para>
165                                                 <note>
166                                                         <para>Any channel variables you want the called channel to inherit from the caller channel must be
167                                                         prefixed with one or two underbars ('_').</para>
168                                                 </note>
169                                                 <note>
170                                                         <para>Using this option from a Macro() or GoSub() might not make sense as there would be no return points.</para>
171                                                 </note>
172                                                 <note>
173                                                         <para>This option will override the 'x' option</para>
174                                                 </note>
175                                         </option>
176
177                                         <option name="h">
178                                                 <para>Allow the called party to hang up by sending the
179                                                 <replaceable>*</replaceable> DTMF digit.</para>
180                                         </option>
181                                         <option name="H">
182                                                 <para>Allow the calling party to hang up by pressing the
183                                                 <replaceable>*</replaceable> DTMF digit.</para>
184                                         </option>
185                                         <option name="k">
186                                                 <para>Allow the called party to enable parking of the call by sending
187                                                 the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
188                                         </option>
189                                         <option name="K">
190                                                 <para>Allow the calling party to enable parking of the call by sending
191                                                  the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
192                                         </option>
193                                         <option name="L(x[:y][:z])">
194                                                 <para>Limit the call to <replaceable>x</replaceable> ms. Play a warning
195                                                 when <replaceable>y</replaceable> ms are left. Repeat the warning every
196                                                 <replaceable>z</replaceable> ms. The following special variables can be
197                                                 used with this option:</para>
198                                                 <variablelist>
199                                                         <variable name="LIMIT_PLAYAUDIO_CALLER">
200                                                                 <para>Play sounds to the caller. yes|no (default yes)</para>
201                                                         </variable>
202                                                         <variable name="LIMIT_PLAYAUDIO_CALLEE">
203                                                                 <para>Play sounds to the callee. yes|no</para>
204                                                         </variable>
205                                                         <variable name="LIMIT_TIMEOUT_FILE">
206                                                                 <para>File to play when time is up.</para>
207                                                         </variable>
208                                                         <variable name="LIMIT_CONNECT_FILE">
209                                                                 <para>File to play when call begins.</para>
210                                                         </variable>
211                                                         <variable name="LIMIT_WARNING_FILE">
212                                                                 <para>File to play as warning if <replaceable>y</replaceable> is
213                                                                 defined. The default is to say the time remaining.</para>
214                                                         </variable>
215                                                 </variablelist>
216                                         </option>
217                                         <option name="S(x)">
218                                                 <para>Hang up the call after <replaceable>x</replaceable> seconds *after* the called party has answered the call.</para>
219                                         </option>
220                                         <option name="t">
221                                                 <para>Allow the called party to transfer the calling party by sending the
222                                                 DTMF sequence defined in <filename>features.conf</filename>.</para>
223                                         </option>
224                                         <option name="T">
225                                                 <para>Allow the calling party to transfer the called party by sending the
226                                                 DTMF sequence defined in <filename>features.conf</filename>.</para>
227                                         </option>
228                                         <option name="w">
229                                                 <para>Allow the called party to enable recording of the call by sending
230                                                 the DTMF sequence defined for one-touch recording in <filename>features.conf</filename>.</para>
231                                         </option>
232                                         <option name="W">
233                                                 <para>Allow the calling party to enable recording of the call by sending
234                                                 the DTMF sequence defined for one-touch recording in <filename>features.conf</filename>.</para>
235                                         </option>
236                                         <option name="x">
237                                                 <para>Cause the called party to be hung up after the bridge, instead of being
238                                                 restarted in the dialplan.</para>
239                                         </option>
240                                 </optionlist>
241                         </parameter>
242                 </syntax>
243                 <description>
244                         <para>Allows the ability to bridge two channels via the dialplan.</para>
245                         <para>This application sets the following channel variable upon completion:</para>
246                         <variablelist>
247                                 <variable name="BRIDGERESULT">
248                                         <para>The result of the bridge attempt as a text string.</para>
249                                         <value name="SUCCESS" />
250                                         <value name="FAILURE" />
251                                         <value name="LOOP" />
252                                         <value name="NONEXISTENT" />
253                                         <value name="INCOMPATIBLE" />
254                                 </variable>
255                         </variablelist>
256                 </description>
257         </application>
258         <manager name="Bridge" language="en_US">
259                 <synopsis>
260                         Bridge two channels already in the PBX.
261                 </synopsis>
262                 <syntax>
263                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
264                         <parameter name="Channel1" required="true">
265                                 <para>Channel to Bridge to Channel2.</para>
266                         </parameter>
267                         <parameter name="Channel2" required="true">
268                                 <para>Channel to Bridge to Channel1.</para>
269                         </parameter>
270                         <parameter name="Tone">
271                                 <para>Play courtesy tone to Channel 2.</para>
272                                 <enumlist>
273                                         <enum name="no" />
274                                         <enum name="Channel1" />
275                                         <enum name="Channel2" />
276                                         <enum name="Both" />
277                                 </enumlist>
278                         </parameter>
279                 </syntax>
280                 <description>
281                         <para>Bridge together two channels already in the PBX.</para>
282                 </description>
283         </manager>
284         <managerEvent language="en_US" name="Pickup">
285                 <managerEventInstance class="EVENT_FLAG_CALL">
286                         <synopsis>Raised when a call pickup occurs.</synopsis>
287                         <syntax>
288                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='Newchannel']/managerEventInstance/syntax/parameter)" />
289                                 <parameter name="TargetChannel"/>
290                                 <parameter name="TargetChannelState"><para>A numeric code for the channel's current state, related to TargetChannelStateDesc</para></parameter>
291                                 <parameter name="TargetChannelStateDesc">
292                                         <enumlist>
293                                                 <enum name="Down"/>
294                                                 <enum name="Rsrvd"/>
295                                                 <enum name="OffHook"/>
296                                                 <enum name="Dialing"/>
297                                                 <enum name="Ring"/>
298                                                 <enum name="Ringing"/>
299                                                 <enum name="Up"/>
300                                                 <enum name="Busy"/>
301                                                 <enum name="Dialing Offhook"/>
302                                                 <enum name="Pre-ring"/>
303                                                 <enum name="Unknown"/>
304                                         </enumlist>
305                                 </parameter>
306                                 <parameter name="TargetCallerIDNum"/>
307                                 <parameter name="TargetCallerIDName"/>
308                                 <parameter name="TargetConnectedLineNum"/>
309                                 <parameter name="TargetConnectedLineName"/>
310                                 <parameter name="TargetAccountCode"/>
311                                 <parameter name="TargetContext"/>
312                                 <parameter name="TargetExten"/>
313                                 <parameter name="TargetPriority"/>
314                                 <parameter name="TargetUniqueid"/>
315                         </syntax>
316                 </managerEventInstance>
317         </managerEvent>
318  ***/
319
320 #define DEFAULT_PARK_TIME                                                       45000   /*!< ms */
321 #define DEFAULT_PARK_EXTENSION                                          "700"
322 #define DEFAULT_COMEBACK_CONTEXT                                        "parkedcallstimeout"
323 #define DEFAULT_COMEBACK_TO_ORIGIN                                      1
324 #define DEFAULT_COMEBACK_DIAL_TIME                                      30
325
326 #define AST_MAX_WATCHERS 256
327 #define MAX_DIAL_FEATURE_OPTIONS 30
328
329 /* TODO Scrape all of the parking stuff out of features.c */
330
331 typedef enum {
332         FEATURE_INTERPRET_DETECT, /* Used by ast_feature_detect */
333         FEATURE_INTERPRET_DO,     /* Used by feature_interpret */
334         FEATURE_INTERPRET_CHECK,  /* Used by feature_check */
335 } feature_interpret_op;
336
337 /*! Parking lot access ramp dialplan usage entry. */
338 struct parking_dp_ramp {
339         /*! Next node in the parking lot spaces dialplan list. */
340         AST_LIST_ENTRY(parking_dp_ramp) node;
341         /*! TRUE if the parking lot access extension is exclusive. */
342         unsigned int exclusive:1;
343         /*! Parking lot access extension */
344         char exten[1];
345 };
346
347 /*! Parking lot dialplan access ramp map */
348 AST_LIST_HEAD_NOLOCK(parking_dp_ramp_map, parking_dp_ramp);
349
350 /*! Parking lot spaces dialplan usage entry. */
351 struct parking_dp_spaces {
352         /*! Next node in the parking lot spaces dialplan list. */
353         AST_LIST_ENTRY(parking_dp_spaces) node;
354         /*! First parking space */
355         int start;
356         /*! Last parking space */
357         int stop;
358 };
359
360 /*! Parking lot dialplan context space map */
361 AST_LIST_HEAD_NOLOCK(parking_dp_space_map, parking_dp_spaces);
362
363 /*! Parking lot context dialplan usage entry. */
364 struct parking_dp_context {
365         /*! Next node in the parking lot contexts dialplan list. */
366         AST_LIST_ENTRY(parking_dp_context) node;
367         /*! Parking access extensions defined in this context. */
368         struct parking_dp_ramp_map access_extens;
369         /*! Parking spaces defined in this context. */
370         struct parking_dp_space_map spaces;
371         /*! Parking hints defined in this context. */
372         struct parking_dp_space_map hints;
373         /*! Parking lot context name */
374         char context[1];
375 };
376
377 /*! Parking lot dialplan usage map. */
378 AST_LIST_HEAD_NOLOCK(parking_dp_map, parking_dp_context);
379
380 /*!
381  * \brief Description of one parked call, added to a list while active, then removed.
382  * The list belongs to a parkinglot.
383  */
384 struct parkeduser {
385         struct ast_channel *chan;                   /*!< Parked channel */
386         struct timeval start;                       /*!< Time the park started */
387         int parkingnum;                             /*!< Parking lot space used */
388         char parkingexten[AST_MAX_EXTENSION];       /*!< If set beforehand, parking extension used for this call */
389         char context[AST_MAX_CONTEXT];              /*!< Where to go if our parking time expires */
390         char exten[AST_MAX_EXTENSION];
391         int priority;
392         unsigned int parkingtime;                   /*!< Maximum length in parking lot before return */
393         /*! Method to entertain the caller when parked: AST_CONTROL_RINGING, AST_CONTROL_HOLD, or 0(none) */
394         enum ast_control_frame_type hold_method;
395         unsigned int notquiteyet:1;
396         unsigned int options_specified:1;
397         char peername[AST_CHANNEL_NAME];
398         unsigned char moh_trys;
399         /*! Parking lot this entry belongs to.  Holds a parking lot reference. */
400         struct ast_parkinglot *parkinglot;
401         AST_LIST_ENTRY(parkeduser) list;
402 };
403
404 /*! Parking lot configuration options. */
405 struct parkinglot_cfg {
406         /*! Music class used for parking */
407         char mohclass[MAX_MUSICCLASS];
408         /*! Extension to park calls in this parking lot. */
409         char parkext[AST_MAX_EXTENSION];
410         /*! Context for which parking is made accessible */
411         char parking_con[AST_MAX_CONTEXT];
412         /*! Context that timed-out parked calls are called back on when comebacktoorigin=no */
413         char comebackcontext[AST_MAX_CONTEXT];
414         /*! First available extension for parking */
415         int parking_start;
416         /*! Last available extension for parking */
417         int parking_stop;
418         /*! Default parking time in ms. */
419         unsigned int parkingtime;
420         /*!
421          * \brief Enable DTMF based transfers on bridge when picking up parked calls.
422          *
423          * \details
424          * none(0)
425          * AST_FEATURE_FLAG_BYCALLEE
426          * AST_FEATURE_FLAG_BYCALLER
427          * AST_FEATURE_FLAG_BYBOTH
428          */
429         int parkedcalltransfers;
430         /*!
431          * \brief Enable DTMF based parking on bridge when picking up parked calls.
432          *
433          * \details
434          * none(0)
435          * AST_FEATURE_FLAG_BYCALLEE
436          * AST_FEATURE_FLAG_BYCALLER
437          * AST_FEATURE_FLAG_BYBOTH
438          */
439         int parkedcallreparking;
440         /*!
441          * \brief Enable DTMF based hangup on a bridge when pickup up parked calls.
442          *
443          * \details
444          * none(0)
445          * AST_FEATURE_FLAG_BYCALLEE
446          * AST_FEATURE_FLAG_BYCALLER
447          * AST_FEATURE_FLAG_BYBOTH
448          */
449         int parkedcallhangup;
450         /*!
451          * \brief Enable DTMF based recording on a bridge when picking up parked calls.
452          *
453          * \details
454          * none(0)
455          * AST_FEATURE_FLAG_BYCALLEE
456          * AST_FEATURE_FLAG_BYCALLER
457          * AST_FEATURE_FLAG_BYBOTH
458          */
459         int parkedcallrecording;
460
461         /*! Time in seconds to dial the device that parked a timedout parked call */
462         unsigned int comebackdialtime;
463         /*! TRUE if findslot is set to next */
464         unsigned int parkfindnext:1;
465         /*! TRUE if the parking lot is exclusively accessed by parkext */
466         unsigned int parkext_exclusive:1;
467         /*! Add parking hints automatically */
468         unsigned int parkaddhints:1;
469         /*! TRUE if configuration is invalid and the parking lot should not be used. */
470         unsigned int is_invalid:1;
471         /*! TRUE if a timed out parked call goes back to the parker */
472         unsigned int comebacktoorigin:1;
473 };
474
475 /*! \brief Structure for parking lots which are put in a container. */
476 struct ast_parkinglot {
477         /*! Name of the parking lot. */
478         char name[AST_MAX_CONTEXT];
479         /*! Parking lot user configuration. */
480         struct parkinglot_cfg cfg;
481
482         /*! Parking space to start next park search. */
483         int next_parking_space;
484
485         /*! That which bears the_mark shall be deleted if parking lot empty! (Used during reloads.) */
486         unsigned int the_mark:1;
487         /*! TRUE if the parking lot is disabled. */
488         unsigned int disabled:1;
489
490         /*! List of active parkings in this parkinglot */
491         AST_LIST_HEAD(parkinglot_parklist, parkeduser) parkings;
492 };
493
494 /*! \brief The configured parking lots container. Always at least one  - the default parking lot */
495 static struct ao2_container *parkinglots;
496
497 /*!
498  * \brief Default parking lot.
499  * \note Holds a parkinglot reference.
500  * \note Will not be NULL while running.
501  */
502 static struct ast_parkinglot *default_parkinglot;
503
504 /*! Force a config reload to reload regardless of config file timestamp. */
505 #ifdef TEST_FRAMEWORK
506 static int force_reload_load;
507 #endif
508
509 static int parkeddynamic = 0;                              /*!< Enable creation of parkinglots dynamically */
510
511 /*!
512  * \brief Context for parking dialback to parker.
513  * \note The need for the context is a KLUDGE.
514  *
515  * \todo Might be able to eliminate the parking_con_dial context
516  * kludge by running app_dial directly in its own thread to
517  * simulate a PBX.
518  */
519 static char parking_con_dial[] = "park-dial";
520
521 /*! Ensure that features.conf reloads on one thread at a time. */
522 AST_MUTEX_DEFINE_STATIC(features_reload_lock);
523
524 static int adsipark;
525
526 static char *registrar = "features";               /*!< Registrar for operations */
527
528 /*! PARK_APP_NAME application arguments */
529 AST_DEFINE_APP_ARGS_TYPE(park_app_args,
530         AST_APP_ARG(timeout);           /*!< Time in ms to remain in the parking lot. */
531         AST_APP_ARG(return_con);        /*!< Context to return parked call if timeout. */
532         AST_APP_ARG(return_ext);        /*!< Exten to return parked call if timeout. */
533         AST_APP_ARG(return_pri);        /*!< Priority to return parked call if timeout. */
534         AST_APP_ARG(options);           /*!< Parking option flags. */
535         AST_APP_ARG(pl_name);           /*!< Parking lot name to use if present. */
536         AST_APP_ARG(dummy);                     /*!< Place to put any remaining args string. */
537         );
538
539 /* module and CLI command definitions */
540 static const char *parkcall = "Park";
541
542 static pthread_t parking_thread;
543 struct ast_dial_features {
544         /*! Channel's feature flags. */
545         struct ast_flags my_features;
546         /*! Bridge peer's feature flags. */
547         struct ast_flags peer_features;
548 };
549
550 static struct ast_manager_event_blob *call_pickup_to_ami(struct stasis_message *message);
551
552 STASIS_MESSAGE_TYPE_DEFN(
553         ast_call_pickup_type,
554         .to_ami = call_pickup_to_ami);
555
556
557 #if defined(ATXFER_NULL_TECH)
558 /*!
559  * \internal
560  * \brief Set the channel technology to the kill technology.
561  *
562  * \param chan Channel to change technology.
563  *
564  * \return Nothing
565  */
566 static void set_kill_chan_tech(struct ast_channel *chan)
567 {
568         int idx;
569
570         ast_channel_lock(chan);
571
572         /* Hangup the channel's physical side */
573         if (ast_channel_tech(chan)->hangup) {
574                 ast_channel_tech(chan)->hangup(chan);
575         }
576         if (ast_channel_tech_pvt(chan)) {
577                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n",
578                         ast_channel_name(chan));
579                 ast_free(ast_channel_tech_pvt(chan));
580                 ast_channel_tech_pvt_set(chan, NULL);
581         }
582
583         /* Install the kill technology and wake up anyone waiting on it. */
584         ast_channel_tech_set(chan, &ast_kill_tech);
585         for (idx = 0; idx < AST_MAX_FDS; ++idx) {
586                 switch (idx) {
587                 case AST_ALERT_FD:
588                 case AST_TIMING_FD:
589                 case AST_GENERATOR_FD:
590                         /* Don't clear these fd's. */
591                         break;
592                 default:
593                         ast_channel_set_fd(chan, idx, -1);
594                         break;
595                 }
596         }
597         ast_queue_frame(chan, &ast_null_frame);
598
599         ast_channel_unlock(chan);
600 }
601 #endif  /* defined(ATXFER_NULL_TECH) */
602
603 #if defined(ATXFER_NULL_TECH)
604 /*!
605  * \internal
606  * \brief Set the channel name to something unique.
607  *
608  * \param chan Channel to change name.
609  *
610  * \return Nothing
611  */
612 static void set_new_chan_name(struct ast_channel *chan)
613 {
614         static int seq_num_last;
615         int seq_num;
616         int len;
617         char *chan_name;
618         char dummy[1];
619
620         /* Create the new channel name string. */
621         ast_channel_lock(chan);
622         seq_num = ast_atomic_fetchadd_int(&seq_num_last, +1);
623         len = snprintf(dummy, sizeof(dummy), "%s<XFER_%x>", ast_channel_name(chan), seq_num) + 1;
624         chan_name = ast_alloca(len);
625         snprintf(chan_name, len, "%s<XFER_%x>", ast_channel_name(chan), seq_num);
626         ast_channel_unlock(chan);
627
628         ast_change_name(chan, chan_name);
629 }
630 #endif  /* defined(ATXFER_NULL_TECH) */
631
632 static void *dial_features_duplicate(void *data)
633 {
634         struct ast_dial_features *df = data, *df_copy;
635
636         if (!(df_copy = ast_calloc(1, sizeof(*df)))) {
637                 return NULL;
638         }
639
640         memcpy(df_copy, df, sizeof(*df));
641
642         return df_copy;
643 }
644
645 static const struct ast_datastore_info dial_features_info = {
646         .type = "dial-features",
647         .destroy = ast_free_ptr,
648         .duplicate = dial_features_duplicate,
649 };
650
651 /*!
652  * \internal
653  * \brief Set the features datastore if it doesn't exist.
654  *
655  * \param chan Channel to add features datastore
656  * \param my_features The channel's feature flags
657  * \param peer_features The channel's bridge peer feature flags
658  *
659  * \retval TRUE if features datastore already existed.
660  */
661 static int add_features_datastore(struct ast_channel *chan, const struct ast_flags *my_features, const struct ast_flags *peer_features)
662 {
663         struct ast_datastore *datastore;
664         struct ast_dial_features *dialfeatures;
665
666         ast_channel_lock(chan);
667         datastore = ast_channel_datastore_find(chan, &dial_features_info, NULL);
668         ast_channel_unlock(chan);
669         if (datastore) {
670                 /* Already exists. */
671                 return 1;
672         }
673
674         /* Create a new datastore with specified feature flags. */
675         datastore = ast_datastore_alloc(&dial_features_info, NULL);
676         if (!datastore) {
677                 ast_log(LOG_WARNING, "Unable to create channel features datastore.\n");
678                 return 0;
679         }
680         dialfeatures = ast_calloc(1, sizeof(*dialfeatures));
681         if (!dialfeatures) {
682                 ast_log(LOG_WARNING, "Unable to allocate memory for feature flags.\n");
683                 ast_datastore_free(datastore);
684                 return 0;
685         }
686         ast_copy_flags(&dialfeatures->my_features, my_features, AST_FLAGS_ALL);
687         ast_copy_flags(&dialfeatures->peer_features, peer_features, AST_FLAGS_ALL);
688         datastore->inheritance = DATASTORE_INHERIT_FOREVER;
689         datastore->data = dialfeatures;
690         ast_channel_lock(chan);
691         ast_channel_datastore_add(chan, datastore);
692         ast_channel_unlock(chan);
693         return 0;
694 }
695
696 /* Forward declarations */
697 static struct ast_parkinglot *parkinglot_addref(struct ast_parkinglot *parkinglot);
698 static void parkinglot_unref(struct ast_parkinglot *parkinglot);
699 static struct ast_parkinglot *find_parkinglot(const char *name);
700 static struct ast_parkinglot *create_parkinglot(const char *name);
701 static struct ast_parkinglot *copy_parkinglot(const char *name, const struct ast_parkinglot *parkinglot);
702 static int parkinglot_activate(struct ast_parkinglot *parkinglot);
703 static int play_message_on_chan(struct ast_channel *play_to, struct ast_channel *other, const char *msg, const char *audiofile);
704
705 /*!
706  * \internal
707  * \brief Get the parking extension if it exists.
708  *
709  * \param exten_str Parking extension to see if exists.
710  * \param chan Channel to autoservice while looking for exten.  (Could be NULL)
711  * \param context Parking context to look in for exten.
712  *
713  * \retval exten on success.
714  * \retval NULL on error or exten does not exist.
715  */
716 static struct ast_exten *get_parking_exten(const char *exten_str, struct ast_channel *chan, const char *context)
717 {
718         struct ast_exten *exten;
719         struct pbx_find_info q = { .stacklen = 0 }; /* the rest is reset in pbx_find_extension */
720         const char *app_at_exten;
721
722         ast_debug(4, "Checking if %s@%s is a parking exten\n", exten_str, context);
723         exten = pbx_find_extension(chan, NULL, &q, context, exten_str, 1, NULL, NULL,
724                 E_MATCH);
725         if (!exten) {
726                 return NULL;
727         }
728
729         app_at_exten = ast_get_extension_app(exten);
730         if (!app_at_exten || strcasecmp(parkcall, app_at_exten)) {
731                 return NULL;
732         }
733
734         return exten;
735 }
736
737 int ast_parking_ext_valid(const char *exten_str, struct ast_channel *chan, const char *context)
738 {
739         return get_parking_exten(exten_str, chan, context) ? 1 : 0;
740 }
741
742 struct ast_bridge_thread_obj
743 {
744         struct ast_bridge_config bconfig;
745         struct ast_channel *chan;
746         struct ast_channel *peer;
747         struct ast_callid *callid;                             /*<! callid pointer (Only used to bind thread) */
748         unsigned int return_to_pbx:1;
749 };
750
751 static int parkinglot_hash_cb(const void *obj, const int flags)
752 {
753         const struct ast_parkinglot *parkinglot = obj;
754
755         return ast_str_case_hash(parkinglot->name);
756 }
757
758 static int parkinglot_cmp_cb(void *obj, void *arg, int flags)
759 {
760         struct ast_parkinglot *parkinglot = obj;
761         struct ast_parkinglot *parkinglot2 = arg;
762
763         return !strcasecmp(parkinglot->name, parkinglot2->name) ? CMP_MATCH | CMP_STOP : 0;
764 }
765
766 /*!
767  * \brief store context, extension and priority
768  * \param chan, context, ext, pri
769  */
770 static void set_c_e_p(struct ast_channel *chan, const char *context, const char *ext, int pri)
771 {
772         ast_channel_context_set(chan, context);
773         ast_channel_exten_set(chan, ext);
774         ast_channel_priority_set(chan, pri);
775 }
776
777 #if 0
778 static struct ast_channel *feature_request_and_dial(struct ast_channel *caller,
779         const char *caller_name, struct ast_channel *requestor,
780         struct ast_channel *transferee, const char *type, struct ast_format_cap *cap, const char *addr,
781         int timeout, int *outstate, const char *language);
782 #endif
783
784 static const struct ast_datastore_info channel_app_data_datastore = {
785         .type = "Channel appdata datastore",
786         .destroy = ast_free_ptr,
787 };
788
789 #if 0
790 static int set_chan_app_data(struct ast_channel *chan, const char *src_app_data)
791 {
792         struct ast_datastore *datastore;
793         char *dst_app_data;
794
795         datastore = ast_datastore_alloc(&channel_app_data_datastore, NULL);
796         if (!datastore) {
797                 return -1;
798         }
799
800         dst_app_data = ast_malloc(strlen(src_app_data) + 1);
801         if (!dst_app_data) {
802                 ast_datastore_free(datastore);
803                 return -1;
804         }
805
806         ast_channel_data_set(chan, strcpy(dst_app_data, src_app_data));
807         datastore->data = dst_app_data;
808         ast_channel_datastore_add(chan, datastore);
809         return 0;
810 }
811 #endif
812
813 #if 0
814 /*!
815  * \brief bridge the call
816  * \param data thread bridge.
817  *
818  * Set Last Data for respective channels, reset cdr for channels
819  * bridge call, check if we're going back to dialplan
820  * if not hangup both legs of the call
821  */
822 static void *bridge_call_thread(void *data)
823 {
824         struct ast_bridge_thread_obj *tobj = data;
825
826         if (tobj->callid) {
827                 ast_callid_threadassoc_add(tobj->callid);
828                 /* Need to deref and set to null since ast_bridge_thread_obj has no common destructor */
829                 tobj->callid = ast_callid_unref(tobj->callid);
830         }
831
832         ast_channel_appl_set(tobj->chan, !tobj->return_to_pbx ? "Transferred Call" : "ManagerBridge");
833         if (set_chan_app_data(tobj->chan, ast_channel_name(tobj->peer))) {
834                 ast_channel_data_set(tobj->chan, "(Empty)");
835         }
836         ast_channel_appl_set(tobj->peer, !tobj->return_to_pbx ? "Transferred Call" : "ManagerBridge");
837         if (set_chan_app_data(tobj->peer, ast_channel_name(tobj->chan))) {
838                 ast_channel_data_set(tobj->peer, "(Empty)");
839         }
840
841         if (tobj->return_to_pbx) {
842                 ast_after_bridge_set_goto(tobj->chan, ast_channel_context(tobj->chan),
843                         ast_channel_exten(tobj->chan), ast_channel_priority(tobj->chan));
844                 ast_after_bridge_set_goto(tobj->peer, ast_channel_context(tobj->peer),
845                         ast_channel_exten(tobj->peer), ast_channel_priority(tobj->peer));
846         }
847
848         ast_bridge_call(tobj->chan, tobj->peer, &tobj->bconfig);
849
850         ast_after_bridge_goto_run(tobj->chan);
851
852         ast_free(tobj);
853
854         return NULL;
855 }
856 #endif
857
858 #if 0
859 /*!
860  * \brief create thread for the bridging call
861  * \param tobj
862  */
863 static void bridge_call_thread_launch(struct ast_bridge_thread_obj *tobj)
864 {
865         pthread_t thread;
866
867         /* This needs to be unreffed once it has been associated with the new thread. */
868         tobj->callid = ast_read_threadstorage_callid();
869
870         if (ast_pthread_create_detached(&thread, NULL, bridge_call_thread, tobj)) {
871                 ast_log(LOG_ERROR, "Failed to create bridge_call_thread.\n");
872                 ast_callid_unref(tobj->callid);
873                 ast_hangup(tobj->chan);
874                 ast_hangup(tobj->peer);
875                 ast_free(tobj);
876         }
877 }
878 #endif
879
880 /*!
881  * \brief Announce call parking by ADSI
882  * \param chan .
883  * \param parkingexten .
884  * Create message to show for ADSI, display message.
885  * \retval 0 on success.
886  * \retval -1 on failure.
887  */
888 static int adsi_announce_park(struct ast_channel *chan, char *parkingexten)
889 {
890         int res;
891         int justify[5] = {ADSI_JUST_CENT, ADSI_JUST_CENT, ADSI_JUST_CENT, ADSI_JUST_CENT};
892         char tmp[256];
893         char *message[5] = {NULL, NULL, NULL, NULL, NULL};
894
895         snprintf(tmp, sizeof(tmp), "Parked on %s", parkingexten);
896         message[0] = tmp;
897         res = ast_adsi_load_session(chan, NULL, 0, 1);
898         if (res == -1)
899                 return res;
900         return ast_adsi_print(chan, message, justify, 1);
901 }
902
903 /*!
904  * \brief Find parking lot name from channel
905  * \note Channel needs to be locked while the returned string is in use.
906  */
907 static const char *findparkinglotname(struct ast_channel *chan)
908 {
909         const char *name;
910
911         /* The channel variable overrides everything */
912         name = pbx_builtin_getvar_helper(chan, "PARKINGLOT");
913         if (!name && !ast_strlen_zero(ast_channel_parkinglot(chan))) {
914                 /* Use the channel's parking lot. */
915                 name = ast_channel_parkinglot(chan);
916         }
917         return name;
918 }
919
920 /*! \brief Notify metermaids that we've changed an extension */
921 static void notify_metermaids(const char *exten, char *context, enum ast_device_state state)
922 {
923         ast_debug(4, "Notification of state change to metermaids %s@%s\n to state '%s'",
924                 exten, context, ast_devstate2str(state));
925
926         ast_devstate_changed(state, AST_DEVSTATE_CACHABLE, "park:%s@%s", exten, context);
927 }
928
929 /*! \brief metermaids callback from devicestate.c */
930 static enum ast_device_state metermaidstate(const char *data)
931 {
932         char *context;
933         char *exten;
934
935         context = ast_strdupa(data);
936
937         exten = strsep(&context, "@");
938         if (!context)
939                 return AST_DEVICE_INVALID;
940
941         ast_debug(4, "Checking state of exten %s in context %s\n", exten, context);
942
943         if (!ast_exists_extension(NULL, context, exten, 1, NULL))
944                 return AST_DEVICE_NOT_INUSE;
945
946         return AST_DEVICE_INUSE;
947 }
948
949 /*! Options to pass to park_call_full */
950 enum ast_park_call_options {
951         /*! Provide ringing to the parked caller instead of music on hold */
952         AST_PARK_OPT_RINGING =   (1 << 0),
953         /*! Randomly choose a parking spot for the caller instead of choosing
954          *  the first one that is available. */
955         AST_PARK_OPT_RANDOMIZE = (1 << 1),
956         /*! Do not announce the parking number */
957         AST_PARK_OPT_SILENCE = (1 << 2),
958 };
959
960 /*! Optional additional parking options when parking a call. */
961 struct ast_park_call_args {
962         /*! How long to wait in the parking lot before the call gets sent back
963          *  to the specified return extension (or a best guess at where it came
964          *  from if not explicitly specified). */
965         int timeout;
966         /*! An output parameter to store the parking space where the parked caller
967          *  was placed. */
968         int *extout;
969         const char *orig_chan_name;
970         const char *return_con;
971         const char *return_ext;
972         int return_pri;
973         uint32_t flags;
974         /*! Parked user that has already obtained a parking space */
975         struct parkeduser *pu;
976         /*! \brief Parkinglot to be parked in */
977         struct ast_parkinglot *parkinglot;
978 };
979
980 /*!
981  * \internal
982  * \brief Create a dynamic parking lot.
983  *
984  * \param name Dynamic parking lot name to create.
985  * \param chan Channel to get dynamic parking lot parameters.
986  *
987  * \retval parkinglot on success.
988  * \retval NULL on error.
989  */
990 static struct ast_parkinglot *create_dynamic_parkinglot(const char *name, struct ast_channel *chan)
991 {
992         const char *dyn_context;
993         const char *dyn_exten;
994         const char *dyn_range;
995         const char *template_name;
996         struct ast_parkinglot *template_parkinglot = NULL;
997         struct ast_parkinglot *parkinglot;
998         int dyn_start;
999         int dyn_end;
1000
1001         ast_channel_lock(chan);
1002         template_name = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNAMIC"), ""));
1003         dyn_context = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNCONTEXT"), ""));
1004         dyn_exten = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNEXTEN"), ""));
1005         dyn_range = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNPOS"), ""));
1006         ast_channel_unlock(chan);
1007
1008         if (!ast_strlen_zero(template_name)) {
1009                 template_parkinglot = find_parkinglot(template_name);
1010                 if (!template_parkinglot) {
1011                         ast_debug(1, "PARKINGDYNAMIC lot %s does not exist.\n",
1012                                 template_name);
1013                 } else if (template_parkinglot->cfg.is_invalid) {
1014                         ast_debug(1, "PARKINGDYNAMIC lot %s has invalid config.\n",
1015                                 template_name);
1016                         parkinglot_unref(template_parkinglot);
1017                         template_parkinglot = NULL;
1018                 }
1019         }
1020         if (!template_parkinglot) {
1021                 template_parkinglot = parkinglot_addref(default_parkinglot);
1022                 ast_debug(1, "Using default parking lot for template\n");
1023         }
1024
1025         parkinglot = copy_parkinglot(name, template_parkinglot);
1026         if (!parkinglot) {
1027                 ast_log(LOG_ERROR, "Could not build dynamic parking lot!\n");
1028         } else {
1029                 /* Configure the dynamic parking lot. */
1030                 if (!ast_strlen_zero(dyn_context)) {
1031                         ast_copy_string(parkinglot->cfg.parking_con, dyn_context,
1032                                 sizeof(parkinglot->cfg.parking_con));
1033                 }
1034                 if (!ast_strlen_zero(dyn_exten)) {
1035                         ast_copy_string(parkinglot->cfg.parkext, dyn_exten,
1036                                 sizeof(parkinglot->cfg.parkext));
1037                 }
1038                 if (!ast_strlen_zero(dyn_range)) {
1039                         if (sscanf(dyn_range, "%30d-%30d", &dyn_start, &dyn_end) != 2) {
1040                                 ast_log(LOG_WARNING,
1041                                         "Format for parking positions is a-b, where a and b are numbers\n");
1042                         } else if (dyn_end < dyn_start || dyn_start <= 0 || dyn_end <= 0) {
1043                                 ast_log(LOG_WARNING,
1044                                         "Format for parking positions is a-b, where a <= b\n");
1045                         } else {
1046                                 parkinglot->cfg.parking_start = dyn_start;
1047                                 parkinglot->cfg.parking_stop = dyn_end;
1048                         }
1049                 }
1050
1051                 /*
1052                  * Sanity check for dynamic parking lot configuration.
1053                  *
1054                  * XXX It may be desirable to instead check if the dynamic
1055                  * parking lot overlaps any existing lots like what is done for
1056                  * a reload.
1057                  */
1058                 if (!strcmp(parkinglot->cfg.parking_con, template_parkinglot->cfg.parking_con)) {
1059                         if (!strcmp(parkinglot->cfg.parkext, template_parkinglot->cfg.parkext)
1060                                 && parkinglot->cfg.parkext_exclusive) {
1061                                 ast_log(LOG_WARNING,
1062                                         "Parking lot '%s' conflicts with template parking lot '%s'!\n"
1063                                         "Change either PARKINGDYNCONTEXT or PARKINGDYNEXTEN.\n",
1064                                         parkinglot->name, template_parkinglot->name);
1065                         }
1066                         if ((template_parkinglot->cfg.parking_start <= parkinglot->cfg.parking_start
1067                                         && parkinglot->cfg.parking_start <= template_parkinglot->cfg.parking_stop)
1068                                 || (template_parkinglot->cfg.parking_start <= parkinglot->cfg.parking_stop
1069                                         && parkinglot->cfg.parking_stop <= template_parkinglot->cfg.parking_stop)
1070                                 || (parkinglot->cfg.parking_start < template_parkinglot->cfg.parking_start
1071                                         && template_parkinglot->cfg.parking_stop < parkinglot->cfg.parking_stop)) {
1072                                 ast_log(LOG_WARNING,
1073                                         "Parking lot '%s' parking spaces overlap template parking lot '%s'!\n"
1074                                         "Change PARKINGDYNPOS.\n",
1075                                         parkinglot->name, template_parkinglot->name);
1076                         }
1077                 }
1078
1079                 parkinglot_activate(parkinglot);
1080                 ao2_link(parkinglots, parkinglot);
1081         }
1082         parkinglot_unref(template_parkinglot);
1083
1084         return parkinglot;
1085 }
1086
1087 /*!
1088  * \internal
1089  * \brief Abort parking a call that has not completed parking yet.
1090  *
1091  * \param pu Parked user item to clean up.
1092  *
1093  * \note The parking lot parkings list is locked on entry.
1094  *
1095  * \return Nothing
1096  */
1097 static void park_space_abort(struct parkeduser *pu)
1098 {
1099         struct ast_parkinglot *parkinglot;
1100
1101         parkinglot = pu->parkinglot;
1102
1103         /* Put back the parking space just allocated. */
1104         --parkinglot->next_parking_space;
1105
1106         AST_LIST_REMOVE(&parkinglot->parkings, pu, list);
1107
1108         AST_LIST_UNLOCK(&parkinglot->parkings);
1109         parkinglot_unref(parkinglot);
1110         ast_free(pu);
1111 }
1112
1113 /*!
1114  * \internal
1115  * \brief Reserve a parking space in a parking lot for a call being parked.
1116  *
1117  * \param park_me Channel being parked.
1118  * \param parker Channel parking the call.
1119  * \param args Optional additional parking options when parking a call.
1120  *
1121  * \return Parked call descriptor or NULL if failed.
1122  * \note The parking lot list is locked if successful.
1123  */
1124 static struct parkeduser *park_space_reserve(struct ast_channel *park_me, struct ast_channel *parker, struct ast_park_call_args *args)
1125 {
1126         struct parkeduser *pu;
1127         int i;
1128         int parking_space = -1;
1129         const char *parkinglotname;
1130         const char *parkingexten;
1131         struct parkeduser *cur;
1132         struct ast_parkinglot *parkinglot = NULL;
1133
1134         if (args->parkinglot) {
1135                 parkinglot = parkinglot_addref(args->parkinglot);
1136                 parkinglotname = parkinglot->name;
1137         } else {
1138                 if (parker) {
1139                         parkinglotname = findparkinglotname(parker);
1140                 } else { /* parker was NULL, check park_me (ParkAndAnnounce / res_agi) */
1141                         parkinglotname = findparkinglotname(park_me);
1142                 }
1143                 if (!ast_strlen_zero(parkinglotname)) {
1144                         parkinglot = find_parkinglot(parkinglotname);
1145                 } else {
1146                         /* Parking lot is not specified, so use the default parking lot. */
1147                         ast_debug(4, "This could be an indication channel driver needs updating, using default lot.\n");
1148                         parkinglot = parkinglot_addref(default_parkinglot);
1149                 }
1150         }
1151
1152         /* Dynamically create parkinglot */
1153         if (!parkinglot && parkeddynamic && !ast_strlen_zero(parkinglotname)) {
1154                 parkinglot = create_dynamic_parkinglot(parkinglotname, park_me);
1155         }
1156
1157         if (!parkinglot) {
1158                 ast_log(LOG_WARNING, "Parking lot not available to park %s.\n", ast_channel_name(park_me));
1159                 return NULL;
1160         }
1161
1162         ast_debug(1, "Parking lot: %s\n", parkinglot->name);
1163         if (parkinglot->disabled || parkinglot->cfg.is_invalid) {
1164                 ast_log(LOG_WARNING, "Parking lot %s is not in a useable state.\n",
1165                         parkinglot->name);
1166                 parkinglot_unref(parkinglot);
1167                 return NULL;
1168         }
1169
1170         /* Allocate memory for parking data */
1171         if (!(pu = ast_calloc(1, sizeof(*pu)))) {
1172                 parkinglot_unref(parkinglot);
1173                 return NULL;
1174         }
1175
1176         /* Lock parking list */
1177         AST_LIST_LOCK(&parkinglot->parkings);
1178
1179         /* Check for channel variable PARKINGEXTEN */
1180         parkingexten = ast_strdupa(S_OR(pbx_builtin_getvar_helper(park_me, "PARKINGEXTEN"), ""));
1181         if (!ast_strlen_zero(parkingexten)) {
1182                 /*!
1183                  * \note The API forces us to specify a numeric parking slot, even
1184                  * though the architecture would tend to support non-numeric extensions
1185                  * (as are possible with SIP, for example).  Hence, we enforce that
1186                  * limitation here.  If extout was not numeric, we could permit
1187                  * arbitrary non-numeric extensions.
1188                  */
1189                 if (sscanf(parkingexten, "%30d", &parking_space) != 1 || parking_space <= 0) {
1190                         ast_log(LOG_WARNING, "PARKINGEXTEN='%s' is not a valid parking space.\n",
1191                                 parkingexten);
1192                         AST_LIST_UNLOCK(&parkinglot->parkings);
1193                         parkinglot_unref(parkinglot);
1194                         ast_free(pu);
1195                         return NULL;
1196                 }
1197
1198                 if (parking_space < parkinglot->cfg.parking_start
1199                         || parkinglot->cfg.parking_stop < parking_space) {
1200                         /*
1201                          * Cannot allow park because parking lots are not setup for
1202                          * spaces outside of the lot.  (Things like dialplan hints don't
1203                          * exist for outside lot space.)
1204                          */
1205                         ast_log(LOG_WARNING, "PARKINGEXTEN=%d is not in %s (%d-%d).\n",
1206                                 parking_space, parkinglot->name, parkinglot->cfg.parking_start,
1207                                 parkinglot->cfg.parking_stop);
1208                         AST_LIST_UNLOCK(&parkinglot->parkings);
1209                         parkinglot_unref(parkinglot);
1210                         ast_free(pu);
1211                         return NULL;
1212                 }
1213
1214                 /* Check if requested parking space is in use. */
1215                 AST_LIST_TRAVERSE(&parkinglot->parkings, cur, list) {
1216                         if (cur->parkingnum == parking_space) {
1217                                 ast_log(LOG_WARNING, "PARKINGEXTEN=%d is already in use in %s\n",
1218                                         parking_space, parkinglot->name);
1219                                 AST_LIST_UNLOCK(&parkinglot->parkings);
1220                                 parkinglot_unref(parkinglot);
1221                                 ast_free(pu);
1222                                 return NULL;
1223                         }
1224                 }
1225         } else {
1226                 /* PARKINGEXTEN is empty, so find a usable extension in the lot to park the call */
1227                 int start; /* The first slot we look in the parkinglot. It can be randomized. */
1228                 int start_checked = 0; /* flag raised once the first slot is checked */
1229
1230                 /* If using randomize mode, set start to random position on parking range */
1231                 if (ast_test_flag(args, AST_PARK_OPT_RANDOMIZE)) {
1232                         start = ast_random() % (parkinglot->cfg.parking_stop - parkinglot->cfg.parking_start + 1);
1233                         start += parkinglot->cfg.parking_start;
1234                 } else if (parkinglot->cfg.parkfindnext
1235                         && parkinglot->cfg.parking_start <= parkinglot->next_parking_space
1236                         && parkinglot->next_parking_space <= parkinglot->cfg.parking_stop) {
1237                         /* Start looking with the next parking space in the lot. */
1238                         start = parkinglot->next_parking_space;
1239                 } else {
1240                         /* Otherwise, just set it to the start position. */
1241                         start = parkinglot->cfg.parking_start;
1242                 }
1243
1244                 /* free parking extension linear search: O(n^2) */
1245                 for (i = start; ; i++) {
1246                         /* If we are past the end, wrap around to the first parking slot*/
1247                         if (i == parkinglot->cfg.parking_stop + 1) {
1248                                 i = parkinglot->cfg.parking_start;
1249                         }
1250
1251                         if (i == start) {
1252                                 /* At this point, if start_checked, we've exhausted all the possible slots. */
1253                                 if (start_checked) {
1254                                         break;
1255                                 } else {
1256                                         start_checked = 1;
1257                                 }
1258                         }
1259
1260                         /* Search the list of parked calls already in use for i. If we find it, it's in use. */
1261                         AST_LIST_TRAVERSE(&parkinglot->parkings, cur, list) {
1262                                 if (cur->parkingnum == i) {
1263                                         break;
1264                                 }
1265                         }
1266                         if (!cur) {
1267                                 /* We found a parking space. */
1268                                 parking_space = i;
1269                                 break;
1270                         }
1271                 }
1272                 if (parking_space == -1) {
1273                         /* We did not find a parking space.  Lot is full. */
1274                         ast_log(LOG_WARNING, "No more parking spaces in %s\n", parkinglot->name);
1275                         AST_LIST_UNLOCK(&parkinglot->parkings);
1276                         parkinglot_unref(parkinglot);
1277                         ast_free(pu);
1278                         return NULL;
1279                 }
1280         }
1281
1282         /* Prepare for next parking space search. */
1283         parkinglot->next_parking_space = parking_space + 1;
1284
1285         snprintf(pu->parkingexten, sizeof(pu->parkingexten), "%d", parking_space);
1286         pu->notquiteyet = 1;
1287         pu->parkingnum = parking_space;
1288         pu->parkinglot = parkinglot;
1289         AST_LIST_INSERT_TAIL(&parkinglot->parkings, pu, list);
1290
1291         return pu;
1292 }
1293
1294 /* Park a call */
1295 static int park_call_full(struct ast_channel *chan, struct ast_channel *peer, struct ast_park_call_args *args)
1296 {
1297         struct parkeduser *pu = args->pu;
1298         const char *event_from;         /*!< Channel name that is parking the call. */
1299         char app_data[AST_MAX_EXTENSION + AST_MAX_CONTEXT];
1300
1301         if (pu == NULL) {
1302                 args->pu = pu = park_space_reserve(chan, peer, args);
1303                 if (pu == NULL) {
1304                         return -1;
1305                 }
1306         }
1307
1308         ast_channel_appl_set(chan, "Parked Call");
1309         ast_channel_data_set(chan, NULL);
1310
1311         pu->chan = chan;
1312
1313         /* Put the parked channel on hold if we have two different channels */
1314         if (chan != peer) {
1315                 if (ast_test_flag(args, AST_PARK_OPT_RINGING)) {
1316                         pu->hold_method = AST_CONTROL_RINGING;
1317                         ast_indicate(chan, AST_CONTROL_RINGING);
1318                 } else {
1319                         pu->hold_method = AST_CONTROL_HOLD;
1320                         ast_indicate_data(chan, AST_CONTROL_HOLD,
1321                                 S_OR(pu->parkinglot->cfg.mohclass, NULL),
1322                                 !ast_strlen_zero(pu->parkinglot->cfg.mohclass) ? strlen(pu->parkinglot->cfg.mohclass) + 1 : 0);
1323                 }
1324         }
1325
1326         pu->start = ast_tvnow();
1327         /* XXX This line was changed to not use get_parkingtime. This is just a placeholder message, because
1328          * likely this entire function is going away.
1329          */
1330         pu->parkingtime = args->timeout;
1331         if (args->extout)
1332                 *(args->extout) = pu->parkingnum;
1333
1334         if (peer) {
1335                 event_from = S_OR(args->orig_chan_name, ast_channel_name(peer));
1336
1337                 /*
1338                  * This is so ugly that it hurts, but implementing
1339                  * get_base_channel() on local channels could have ugly side
1340                  * effects.  We could have
1341                  * transferer<->local;1<->local;2<->parking and we need the
1342                  * callback name to be that of transferer.  Since local;1/2 have
1343                  * the same name we can be tricky and just grab the bridged
1344                  * channel from the other side of the local.
1345                  */
1346                 if (!strcasecmp(ast_channel_tech(peer)->type, "Local")) {
1347                         struct ast_channel *tmpchan, *base_peer;
1348                         char other_side[AST_CHANNEL_NAME];
1349                         char *c;
1350
1351                         ast_copy_string(other_side, event_from, sizeof(other_side));
1352                         if ((c = strrchr(other_side, ';'))) {
1353                                 *++c = '1';
1354                         }
1355                         if ((tmpchan = ast_channel_get_by_name(other_side))) {
1356                                 ast_channel_lock(tmpchan);
1357                                 if ((base_peer = ast_bridged_channel(tmpchan))) {
1358                                         ast_copy_string(pu->peername, ast_channel_name(base_peer), sizeof(pu->peername));
1359                                 }
1360                                 ast_channel_unlock(tmpchan);
1361                                 tmpchan = ast_channel_unref(tmpchan);
1362                         }
1363                 } else {
1364                         ast_copy_string(pu->peername, event_from, sizeof(pu->peername));
1365                 }
1366         } else {
1367                 event_from = S_OR(pbx_builtin_getvar_helper(chan, "BLINDTRANSFER"),
1368                         ast_channel_name(chan));
1369         }
1370
1371         /*
1372          * Remember what had been dialed, so that if the parking
1373          * expires, we try to come back to the same place
1374          */
1375         pu->options_specified = (!ast_strlen_zero(args->return_con) || !ast_strlen_zero(args->return_ext) || args->return_pri);
1376
1377         /*
1378          * If extension has options specified, they override all other
1379          * possibilities such as the returntoorigin flag and transferred
1380          * context.  Information on extension options is lost here, so
1381          * we set a flag
1382          */
1383         ast_copy_string(pu->context,
1384                 S_OR(args->return_con, S_OR(ast_channel_macrocontext(chan), ast_channel_context(chan))),
1385                 sizeof(pu->context));
1386         ast_copy_string(pu->exten,
1387                 S_OR(args->return_ext, S_OR(ast_channel_macroexten(chan), ast_channel_exten(chan))),
1388                 sizeof(pu->exten));
1389         pu->priority = args->return_pri ? args->return_pri :
1390                 (ast_channel_macropriority(chan) ? ast_channel_macropriority(chan) : ast_channel_priority(chan));
1391
1392         /*
1393          * If parking a channel directly, don't quite yet get parking
1394          * running on it.  All parking lot entries are put into the
1395          * parking lot with notquiteyet on.
1396          */
1397         if (peer != chan) {
1398                 pu->notquiteyet = 0;
1399         }
1400
1401         /* Wake up the (presumably select()ing) thread */
1402         pthread_kill(parking_thread, SIGURG);
1403         ast_verb(2, "Parked %s on %d (lot %s). Will timeout back to extension [%s] %s, %d in %u seconds\n",
1404                 ast_channel_name(chan), pu->parkingnum, pu->parkinglot->name,
1405                 pu->context, pu->exten, pu->priority, (pu->parkingtime / 1000));
1406
1407         /*** DOCUMENTATION
1408                 <managerEventInstance>
1409                         <synopsis>Raised when a call has been parked.</synopsis>
1410                         <syntax>
1411                                 <parameter name="Exten">
1412                                         <para>The parking lot extension.</para>
1413                                 </parameter>
1414                                 <parameter name="Parkinglot">
1415                                         <para>The name of the parking lot.</para>
1416                                 </parameter>
1417                                 <parameter name="From">
1418                                         <para>The name of the channel that parked the call.</para>
1419                                 </parameter>
1420                         </syntax>
1421                         <see-also>
1422                                 <ref type="application">Park</ref>
1423                                 <ref type="manager">Park</ref>
1424                                 <ref type="managerEvent">ParkedCallTimeOut</ref>
1425                                 <ref type="managerEvent">ParkedCallGiveUp</ref>
1426                         </see-also>
1427                 </managerEventInstance>
1428         ***/
1429         ast_manager_event(chan, EVENT_FLAG_CALL, "ParkedCall",
1430                 "Exten: %s\r\n"
1431                 "Channel: %s\r\n"
1432                 "Parkinglot: %s\r\n"
1433                 "From: %s\r\n"
1434                 "Timeout: %ld\r\n"
1435                 "CallerIDNum: %s\r\n"
1436                 "CallerIDName: %s\r\n"
1437                 "ConnectedLineNum: %s\r\n"
1438                 "ConnectedLineName: %s\r\n"
1439                 "Uniqueid: %s\r\n",
1440                 pu->parkingexten, ast_channel_name(chan), pu->parkinglot->name, event_from,
1441                 (long)pu->start.tv_sec + (long)(pu->parkingtime/1000) - (long)time(NULL),
1442                 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, "<unknown>"),
1443                 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, "<unknown>"),
1444                 S_COR(ast_channel_connected(chan)->id.number.valid, ast_channel_connected(chan)->id.number.str, "<unknown>"),
1445                 S_COR(ast_channel_connected(chan)->id.name.valid, ast_channel_connected(chan)->id.name.str, "<unknown>"),
1446                 ast_channel_uniqueid(chan)
1447                 );
1448         ast_debug(4, "peer: %s\n", peer ? ast_channel_name(peer) : "-No peer-");
1449         ast_debug(4, "args->orig_chan_name: %s\n", args->orig_chan_name ? args->orig_chan_name : "-none-");
1450         ast_debug(4, "pu->peername: %s\n", pu->peername);
1451         ast_debug(4, "AMI ParkedCall Channel: %s\n", ast_channel_name(chan));
1452         ast_debug(4, "AMI ParkedCall From: %s\n", event_from);
1453
1454         if (peer && adsipark && ast_adsi_available(peer)) {
1455                 adsi_announce_park(peer, pu->parkingexten);     /* Only supports parking numbers */
1456                 ast_adsi_unload_session(peer);
1457         }
1458
1459         snprintf(app_data, sizeof(app_data), "%s,%s", pu->parkingexten,
1460                 pu->parkinglot->name);
1461
1462         AST_LIST_UNLOCK(&pu->parkinglot->parkings);
1463
1464         /* Only say number if it's a number and the channel hasn't been masqueraded away */
1465         if (peer && !ast_test_flag(args, AST_PARK_OPT_SILENCE)
1466                 && (ast_strlen_zero(args->orig_chan_name) || !strcasecmp(ast_channel_name(peer), args->orig_chan_name))) {
1467                 /*
1468                  * If a channel is masqueraded into peer while playing back the
1469                  * parking space number do not continue playing it back.  This
1470                  * is the case if an attended transfer occurs.
1471                  */
1472                 ast_set_flag(ast_channel_flags(peer), AST_FLAG_MASQ_NOSTREAM);
1473                 /* Tell the peer channel the number of the parking space */
1474                 ast_say_digits(peer, pu->parkingnum, "", ast_channel_language(peer));
1475                 ast_clear_flag(ast_channel_flags(peer), AST_FLAG_MASQ_NOSTREAM);
1476         }
1477         if (peer == chan) { /* pu->notquiteyet = 1 */
1478                 /* Wake up parking thread if we're really done */
1479                 if (ast_test_flag(args, AST_PARK_OPT_RINGING)) {
1480                         pu->hold_method = AST_CONTROL_RINGING;
1481                         ast_indicate(chan, AST_CONTROL_RINGING);
1482                 } else {
1483                         pu->hold_method = AST_CONTROL_HOLD;
1484                         ast_indicate_data(chan, AST_CONTROL_HOLD,
1485                                 S_OR(pu->parkinglot->cfg.mohclass, NULL),
1486                                 !ast_strlen_zero(pu->parkinglot->cfg.mohclass) ? strlen(pu->parkinglot->cfg.mohclass) + 1 : 0);
1487                 }
1488                 pu->notquiteyet = 0;
1489                 pthread_kill(parking_thread, SIGURG);
1490         }
1491         return 0;
1492 }
1493
1494 int ast_park_call_exten(struct ast_channel *park_me, struct ast_channel *parker, const char *park_exten, const char *park_context, int timeout, int *extout)
1495 {
1496         int res;
1497         char *parse;
1498         const char *app_data;
1499         struct ast_exten *exten;
1500         struct park_app_args app_args;
1501         struct ast_park_call_args args = {
1502                 .timeout = timeout,
1503                 .extout = extout,
1504         };
1505
1506         if (!park_exten || !park_context) {
1507                 return park_call_full(park_me, parker, &args);
1508         }
1509
1510         /*
1511          * Determiine if the specified park extension has an exclusive
1512          * parking lot to use.
1513          */
1514         if (parker && parker != park_me) {
1515                 ast_autoservice_start(park_me);
1516         }
1517         exten = get_parking_exten(park_exten, parker, park_context);
1518         if (exten) {
1519                 app_data = ast_get_extension_app_data(exten);
1520                 if (!app_data) {
1521                         app_data = "";
1522                 }
1523                 parse = ast_strdupa(app_data);
1524                 AST_STANDARD_APP_ARGS(app_args, parse);
1525
1526                 if (!ast_strlen_zero(app_args.pl_name)) {
1527                         /* Find the specified exclusive parking lot */
1528                         args.parkinglot = find_parkinglot(app_args.pl_name);
1529                         if (!args.parkinglot && parkeddynamic) {
1530                                 args.parkinglot = create_dynamic_parkinglot(app_args.pl_name, park_me);
1531                         }
1532                 }
1533         }
1534         if (parker && parker != park_me) {
1535                 ast_autoservice_stop(park_me);
1536         }
1537
1538         res = park_call_full(park_me, parker, &args);
1539         if (args.parkinglot) {
1540                 parkinglot_unref(args.parkinglot);
1541         }
1542         return res;
1543 }
1544
1545 int ast_park_call(struct ast_channel *park_me, struct ast_channel *parker, int timeout, const char *park_exten, int *extout)
1546 {
1547         struct ast_park_call_args args = {
1548                 .timeout = timeout,
1549                 .extout = extout,
1550         };
1551
1552         return park_call_full(park_me, parker, &args);
1553 }
1554
1555 /*!
1556  * \brief Park call via masqueraded channel and announce parking spot on peer channel.
1557  *
1558  * \param rchan the real channel to be parked
1559  * \param peer the channel to have the parking read to.
1560  * \param args Additional parking options when parking a call.
1561  *
1562  * \retval 0 on success.
1563  * \retval -1 on failure.
1564  */
1565 static int masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, struct ast_park_call_args *args)
1566 {
1567         struct ast_channel *chan;
1568
1569         /* Make a new, channel that we'll use to masquerade in the real one */
1570         chan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, ast_channel_accountcode(rchan), ast_channel_exten(rchan),
1571                 ast_channel_context(rchan), ast_channel_linkedid(rchan), ast_channel_amaflags(rchan), "Parked/%s", ast_channel_name(rchan));
1572         if (!chan) {
1573                 ast_log(LOG_WARNING, "Unable to create parked channel\n");
1574                 if (!ast_test_flag(args, AST_PARK_OPT_SILENCE)) {
1575                         if (peer == rchan) {
1576                                 /* Only have one channel to worry about. */
1577                                 ast_stream_and_wait(peer, "pbx-parkingfailed", "");
1578                         } else if (peer) {
1579                                 /* Have two different channels to worry about. */
1580                                 play_message_on_chan(peer, rchan, "failure message", "pbx-parkingfailed");
1581                         }
1582                 }
1583                 return -1;
1584         }
1585
1586         args->pu = park_space_reserve(rchan, peer, args);
1587         if (!args->pu) {
1588                 ast_hangup(chan);
1589                 if (!ast_test_flag(args, AST_PARK_OPT_SILENCE)) {
1590                         if (peer == rchan) {
1591                                 /* Only have one channel to worry about. */
1592                                 ast_stream_and_wait(peer, "pbx-parkingfailed", "");
1593                         } else if (peer) {
1594                                 /* Have two different channels to worry about. */
1595                                 play_message_on_chan(peer, rchan, "failure message", "pbx-parkingfailed");
1596                         }
1597                 }
1598                 return -1;
1599         }
1600
1601         /* Make formats okay */
1602         ast_format_copy(ast_channel_readformat(chan), ast_channel_readformat(rchan));
1603         ast_format_copy(ast_channel_writeformat(chan), ast_channel_writeformat(rchan));
1604
1605         if (ast_channel_masquerade(chan, rchan)) {
1606                 park_space_abort(args->pu);
1607                 args->pu = NULL;
1608                 ast_hangup(chan);
1609                 if (!ast_test_flag(args, AST_PARK_OPT_SILENCE)) {
1610                         if (peer == rchan) {
1611                                 /* Only have one channel to worry about. */
1612                                 ast_stream_and_wait(peer, "pbx-parkingfailed", "");
1613                         } else if (peer) {
1614                                 /* Have two different channels to worry about. */
1615                                 play_message_on_chan(peer, rchan, "failure message", "pbx-parkingfailed");
1616                         }
1617                 }
1618                 return -1;
1619         }
1620
1621         /* Setup the extensions and such */
1622         set_c_e_p(chan, ast_channel_context(rchan), ast_channel_exten(rchan), ast_channel_priority(rchan));
1623
1624         /* Setup the macro extension and such */
1625         ast_channel_macrocontext_set(chan, ast_channel_macrocontext(rchan));
1626         ast_channel_macroexten_set(chan, ast_channel_macroexten(rchan));
1627         ast_channel_macropriority_set(chan, ast_channel_macropriority(rchan));
1628
1629         /* Manually do the masquerade to make sure it is complete. */
1630         ast_do_masquerade(chan);
1631
1632         if (peer == rchan) {
1633                 peer = chan;
1634         }
1635
1636         /* parking space reserved, return code check unnecessary */
1637         park_call_full(chan, peer, args);
1638
1639         return 0;
1640 }
1641
1642 int ast_masq_park_call_exten(struct ast_channel *park_me, struct ast_channel *parker, const char *park_exten, const char *park_context, int timeout, int *extout)
1643 {
1644         int res;
1645         char *parse;
1646         const char *app_data;
1647         struct ast_exten *exten;
1648         struct park_app_args app_args;
1649         struct ast_park_call_args args = {
1650                 .timeout = timeout,
1651                 .extout = extout,
1652         };
1653
1654         if (parker) {
1655                 args.orig_chan_name = ast_strdupa(ast_channel_name(parker));
1656         }
1657         if (!park_exten || !park_context) {
1658                 return masq_park_call(park_me, parker, &args);
1659         }
1660
1661         /*
1662          * Determiine if the specified park extension has an exclusive
1663          * parking lot to use.
1664          */
1665         if (parker && parker != park_me) {
1666                 ast_autoservice_start(park_me);
1667         }
1668         exten = get_parking_exten(park_exten, parker, park_context);
1669         if (exten) {
1670                 app_data = ast_get_extension_app_data(exten);
1671                 if (!app_data) {
1672                         app_data = "";
1673                 }
1674                 parse = ast_strdupa(app_data);
1675                 AST_STANDARD_APP_ARGS(app_args, parse);
1676
1677                 if (!ast_strlen_zero(app_args.pl_name)) {
1678                         /* Find the specified exclusive parking lot */
1679                         args.parkinglot = find_parkinglot(app_args.pl_name);
1680                         if (!args.parkinglot && parkeddynamic) {
1681                                 args.parkinglot = create_dynamic_parkinglot(app_args.pl_name, park_me);
1682                         }
1683                 }
1684         }
1685         if (parker && parker != park_me) {
1686                 ast_autoservice_stop(park_me);
1687         }
1688
1689         res = masq_park_call(park_me, parker, &args);
1690         if (args.parkinglot) {
1691                 parkinglot_unref(args.parkinglot);
1692         }
1693         return res;
1694 }
1695
1696 int ast_masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, int timeout, int *extout)
1697 {
1698         struct ast_park_call_args args = {
1699                 .timeout = timeout,
1700                 .extout = extout,
1701         };
1702
1703         if (peer) {
1704                 args.orig_chan_name = ast_strdupa(ast_channel_name(peer));
1705         }
1706         return masq_park_call(rchan, peer, &args);
1707 }
1708
1709 #if 0
1710 static int finishup(struct ast_channel *chan)
1711 {
1712         ast_indicate(chan, AST_CONTROL_UNHOLD);
1713
1714         return ast_autoservice_stop(chan);
1715 }
1716 #endif
1717
1718 #if 0
1719 /*!
1720  * \internal
1721  * \brief Builtin transfer park call helper.
1722  *
1723  * \param park_me Channel to be parked.
1724  * \param parker Channel parking the call.
1725  * \param park_exten Parking lot dialplan access ramp extension.
1726  *
1727  * \note Assumes park_me is on hold and in autoservice.
1728  *
1729  * \retval -1 on successful park.
1730  * \retval -1 on park_me hangup.
1731  * \retval AST_FEATURE_RETURN_SUCCESS on error to keep the bridge connected.
1732  */
1733 static int xfer_park_call_helper(struct ast_channel *park_me, struct ast_channel *parker, struct ast_exten *park_exten)
1734 {
1735         char *parse;
1736         const char *app_data;
1737         const char *pl_name;
1738         struct ast_park_call_args args = { 0, };
1739         struct park_app_args app_args;
1740         int res;
1741
1742         app_data = ast_get_extension_app_data(park_exten);
1743         if (!app_data) {
1744                 app_data = "";
1745         }
1746         parse = ast_strdupa(app_data);
1747         AST_STANDARD_APP_ARGS(app_args, parse);
1748
1749         /* Find the parking lot */
1750         if (!ast_strlen_zero(app_args.pl_name)) {
1751                 pl_name = app_args.pl_name;
1752         } else {
1753                 pl_name = findparkinglotname(parker);
1754         }
1755         if (ast_strlen_zero(pl_name)) {
1756                 /* Parking lot is not specified, so use the default parking lot. */
1757                 args.parkinglot = parkinglot_addref(default_parkinglot);
1758         } else {
1759                 args.parkinglot = find_parkinglot(pl_name);
1760                 if (!args.parkinglot && parkeddynamic) {
1761                         args.parkinglot = create_dynamic_parkinglot(pl_name, park_me);
1762                 }
1763         }
1764
1765         if (args.parkinglot) {
1766                 /* Park the call */
1767                 res = finishup(park_me);
1768                 if (res) {
1769                         /* park_me hungup on us. */
1770                         parkinglot_unref(args.parkinglot);
1771                         return -1;
1772                 }
1773                 res = masq_park_call(park_me, parker, &args);
1774                 parkinglot_unref(args.parkinglot);
1775         } else {
1776                 /* Parking failed because parking lot does not exist. */
1777                 if (!ast_test_flag(&args, AST_PARK_OPT_SILENCE)) {
1778                         ast_stream_and_wait(parker, "pbx-parkingfailed", "");
1779                 }
1780                 finishup(park_me);
1781                 res = -1;
1782         }
1783
1784         return res ? AST_FEATURE_RETURN_SUCCESS : -1;
1785 }
1786 #endif
1787
1788 #if 0
1789 /*!
1790  * \brief set caller and callee according to the direction
1791  * \param caller, callee, peer, chan, sense
1792  *
1793  * Detect who triggered feature and set callee/caller variables accordingly
1794  */
1795 static void set_peers(struct ast_channel **caller, struct ast_channel **callee,
1796         struct ast_channel *peer, struct ast_channel *chan, int sense)
1797 {
1798         if (sense == FEATURE_SENSE_PEER) {
1799                 *caller = peer;
1800                 *callee = chan;
1801         } else {
1802                 *callee = peer;
1803                 *caller = chan;
1804         }
1805 }
1806 #endif
1807
1808 #if 0
1809 /*!
1810  * \brief support routing for one touch call parking
1811  * \param chan channel parking call
1812  * \param peer channel to be parked
1813  * \param config unsed
1814  * \param code unused
1815  * \param sense feature options
1816  * \param data unused
1817  *
1818  * \retval -1 on successful park.
1819  * \retval -1 on chan hangup.
1820  * \retval AST_FEATURE_RETURN_SUCCESS on error to keep the bridge connected.
1821  */
1822 static int builtin_parkcall(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
1823 {
1824         struct ast_channel *parker;
1825         struct ast_channel *parkee;
1826         struct ast_park_call_args args = { 0, };
1827
1828         /*
1829          * We used to set chan's exten and priority to "s" and 1 here,
1830          * but this generates (in some cases) an invalid extension, and
1831          * if "s" exists, could errantly cause execution of extensions
1832          * you don't expect.  It makes more sense to let nature take its
1833          * course when chan finishes, and let the pbx do its thing and
1834          * hang up when the park is over.
1835          */
1836
1837         /* Answer if call is not up */
1838         if (ast_channel_state(chan) != AST_STATE_UP) {
1839                 /*
1840                  * XXX Why are we doing this?  Both of the channels should be up
1841                  * since you cannot do DTMF features unless you are bridged.
1842                  */
1843                 if (ast_answer(chan)) {
1844                         return -1;
1845                 }
1846
1847                 /* Sleep to allow VoIP streams to settle down */
1848                 if (ast_safe_sleep(chan, 1000)) {
1849                         return -1;
1850                 }
1851         }
1852
1853         /* one direction used to call park_call.... */
1854         set_peers(&parker, &parkee, peer, chan, sense);
1855         return masq_park_call(parkee, parker, &args) ? AST_FEATURE_RETURN_SUCCESS : -1;
1856 }
1857 #endif
1858
1859 /*!
1860  * \internal
1861  * \brief Play file to specified channel.
1862  *
1863  * \param play_to Channel to play audiofile to.
1864  * \param other Channel to put in autoservice while playing file.
1865  * \param msg Descriptive name of message type being played.
1866  * \param audiofile Audio file to play.
1867  *
1868  * \retval 0 on success.
1869  * \retval -1 on error. (Couldn't play file, a channel hung up,...)
1870  */
1871 static int play_message_on_chan(struct ast_channel *play_to, struct ast_channel *other, const char *msg, const char *audiofile)
1872 {
1873         /* Put other channel in autoservice. */
1874         if (ast_autoservice_start(other)) {
1875                 return -1;
1876         }
1877         ast_autoservice_ignore(other, AST_FRAME_DTMF_BEGIN);
1878         ast_autoservice_ignore(other, AST_FRAME_DTMF_END);
1879         if (ast_stream_and_wait(play_to, audiofile, "")) {
1880                 ast_log(LOG_WARNING, "Failed to play %s '%s'!\n", msg, audiofile);
1881                 ast_autoservice_stop(other);
1882                 return -1;
1883         }
1884         if (ast_autoservice_stop(other)) {
1885                 return -1;
1886         }
1887         return 0;
1888 }
1889
1890 #if 0
1891 /*!
1892  * \internal
1893  * \brief Play file to specified channels.
1894  *
1895  * \param left Channel on left to play file.
1896  * \param right Channel on right to play file.
1897  * \param which Play file on indicated channels: which < 0 play left, which == 0 play both, which > 0 play right
1898  * \param msg Descriptive name of message type being played.
1899  * \param audiofile Audio file to play to channels.
1900  *
1901  * \note Plays file to the indicated channels in turn so please
1902  * don't use this for very long messages.
1903  *
1904  * \retval 0 on success.
1905  * \retval -1 on error. (Couldn't play file, channel hung up,...)
1906  */
1907 static int play_message_to_chans(struct ast_channel *left, struct ast_channel *right, int which, const char *msg, const char *audiofile)
1908 {
1909         /* First play the file to the left channel if requested. */
1910         if (which <= 0 && play_message_on_chan(left, right, msg, audiofile)) {
1911                 return -1;
1912         }
1913
1914         /* Then play the file to the right channel if requested. */
1915         if (which >= 0 && play_message_on_chan(right, left, msg, audiofile)) {
1916                 return -1;
1917         }
1918
1919         return 0;
1920 }
1921 #endif
1922
1923 #if 0
1924 /*!
1925  * \brief Play message to both caller and callee in bridged call, plays synchronously, autoservicing the
1926  * other channel during the message, so please don't use this for very long messages
1927  */
1928 static int play_message_in_bridged_call(struct ast_channel *caller_chan, struct ast_channel *callee_chan, const char *audiofile)
1929 {
1930         return play_message_to_chans(caller_chan, callee_chan, 0, "automon message",
1931                 audiofile);
1932 }
1933 #endif
1934
1935 #if 0
1936 /*!
1937  * \brief Monitor a channel by DTMF
1938  * \param chan channel requesting monitor
1939  * \param peer channel to be monitored
1940  * \param config
1941  * \param code
1942  * \param sense feature options
1943  *
1944  * \param data
1945  * Check monitor app enabled, setup channels, both caller/callee chans not null
1946  * get TOUCH_MONITOR variable for filename if exists, exec monitor app.
1947  * \retval AST_FEATURE_RETURN_SUCCESS on success.
1948  * \retval -1 on error.
1949  */
1950 static int builtin_automonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
1951 {
1952         char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
1953         int x = 0;
1954         size_t len;
1955         struct ast_channel *caller_chan, *callee_chan;
1956         const char *automon_message_start = NULL;
1957         const char *automon_message_stop = NULL;
1958         const char *touch_format = NULL;
1959         const char *touch_monitor = NULL;
1960         const char *touch_monitor_prefix = NULL;
1961         struct ast_app *monitor_app;
1962
1963         monitor_app = pbx_findapp("Monitor");
1964         if (!monitor_app) {
1965                 ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
1966                 return -1;
1967         }
1968
1969         set_peers(&caller_chan, &callee_chan, peer, chan, sense);
1970
1971         /* Find extra messages */
1972         automon_message_start = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_START");
1973         automon_message_stop = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_STOP");
1974
1975         if (!ast_strlen_zero(courtesytone)) {   /* Play courtesy tone if configured */
1976                 if(play_message_in_bridged_call(caller_chan, callee_chan, courtesytone) == -1) {
1977                         return -1;
1978                 }
1979         }
1980
1981         if (ast_channel_monitor(callee_chan)) {
1982                 ast_verb(4, "User hit '%s' to stop recording call.\n", code);
1983                 if (!ast_strlen_zero(automon_message_stop)) {
1984                         play_message_in_bridged_call(caller_chan, callee_chan, automon_message_stop);
1985                 }
1986                 ast_channel_monitor(callee_chan)->stop(callee_chan, 1);
1987                 return AST_FEATURE_RETURN_SUCCESS;
1988         }
1989
1990         touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_FORMAT");
1991         touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR");
1992         touch_monitor_prefix = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_PREFIX");
1993
1994         if (!touch_format)
1995                 touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_FORMAT");
1996
1997         if (!touch_monitor)
1998                 touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR");
1999
2000         if (!touch_monitor_prefix)
2001                 touch_monitor_prefix = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_PREFIX");
2002
2003         if (touch_monitor) {
2004                 len = strlen(touch_monitor) + 50;
2005                 args = ast_alloca(len);
2006                 touch_filename = ast_alloca(len);
2007                 snprintf(touch_filename, len, "%s-%ld-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), touch_monitor);
2008                 snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
2009         } else {
2010                 caller_chan_id = ast_strdupa(S_COR(ast_channel_caller(caller_chan)->id.number.valid,
2011                         ast_channel_caller(caller_chan)->id.number.str, ast_channel_name(caller_chan)));
2012                 callee_chan_id = ast_strdupa(S_COR(ast_channel_caller(callee_chan)->id.number.valid,
2013                         ast_channel_caller(callee_chan)->id.number.str, ast_channel_name(callee_chan)));
2014                 len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
2015                 args = ast_alloca(len);
2016                 touch_filename = ast_alloca(len);
2017                 snprintf(touch_filename, len, "%s-%ld-%s-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), caller_chan_id, callee_chan_id);
2018                 snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
2019         }
2020
2021         for(x = 0; x < strlen(args); x++) {
2022                 if (args[x] == '/')
2023                         args[x] = '-';
2024         }
2025
2026         ast_verb(4, "User hit '%s' to record call. filename: %s\n", code, args);
2027
2028         pbx_exec(callee_chan, monitor_app, args);
2029         pbx_builtin_setvar_helper(callee_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
2030         pbx_builtin_setvar_helper(caller_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
2031
2032         if (!ast_strlen_zero(automon_message_start)) {  /* Play start message for both channels */
2033                 play_message_in_bridged_call(caller_chan, callee_chan, automon_message_start);
2034         }
2035
2036         return AST_FEATURE_RETURN_SUCCESS;
2037 }
2038 #endif
2039
2040 #if 0
2041 static int builtin_automixmonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2042 {
2043         char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
2044         int x = 0;
2045         size_t len;
2046         struct ast_channel *caller_chan, *callee_chan;
2047         const char *mixmonitor_spy_type = "MixMonitor";
2048         const char *touch_format;
2049         const char *touch_monitor;
2050         struct ast_app *mixmonitor_app;
2051         int count = 0;
2052
2053         mixmonitor_app = pbx_findapp("MixMonitor");
2054         if (!mixmonitor_app) {
2055                 ast_log(LOG_ERROR,"Cannot record the call. The mixmonitor application is disabled.\n");
2056                 return -1;
2057         }
2058
2059         set_peers(&caller_chan, &callee_chan, peer, chan, sense);
2060
2061         if (!ast_strlen_zero(courtesytone)) {
2062                 if (ast_autoservice_start(callee_chan))
2063                         return -1;
2064                 ast_autoservice_ignore(callee_chan, AST_FRAME_DTMF_END);
2065                 if (ast_stream_and_wait(caller_chan, courtesytone, "")) {
2066                         ast_log(LOG_WARNING, "Failed to play courtesy tone!\n");
2067                         ast_autoservice_stop(callee_chan);
2068                         return -1;
2069                 }
2070                 if (ast_autoservice_stop(callee_chan))
2071                         return -1;
2072         }
2073
2074         ast_channel_lock(callee_chan);
2075         count = ast_channel_audiohook_count_by_source(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
2076         ast_channel_unlock(callee_chan);
2077
2078         /* This means a mixmonitor is attached to the channel, running or not is unknown. */
2079         if (count > 0) {
2080                 ast_verb(3, "User hit '%s' to stop recording call.\n", code);
2081
2082                 /* Make sure they are running */
2083                 ast_channel_lock(callee_chan);
2084                 count = ast_channel_audiohook_count_by_source_running(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
2085                 ast_channel_unlock(callee_chan);
2086                 if (count > 0) {
2087                         struct ast_app *stopmixmonitor_app;
2088
2089                         stopmixmonitor_app = pbx_findapp("StopMixMonitor");
2090                         if (!stopmixmonitor_app) {
2091                                 ast_log(LOG_ERROR,"Cannot stop recording the call. The stopmixmonitor application is disabled.\n");
2092                                 return -1;
2093                         }
2094                         pbx_exec(callee_chan, stopmixmonitor_app, "");
2095                         return AST_FEATURE_RETURN_SUCCESS;
2096                 }
2097
2098                 ast_log(LOG_WARNING,"Stopped MixMonitors are attached to the channel.\n");
2099         }
2100
2101         touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR_FORMAT");
2102         touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR");
2103
2104         if (!touch_format)
2105                 touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR_FORMAT");
2106
2107         if (!touch_monitor)
2108                 touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR");
2109
2110         if (touch_monitor) {
2111                 len = strlen(touch_monitor) + 50;
2112                 args = ast_alloca(len);
2113                 touch_filename = ast_alloca(len);
2114                 snprintf(touch_filename, len, "auto-%ld-%s", (long)time(NULL), touch_monitor);
2115                 snprintf(args, len, "%s.%s,b", touch_filename, (touch_format) ? touch_format : "wav");
2116         } else {
2117                 caller_chan_id = ast_strdupa(S_COR(ast_channel_caller(caller_chan)->id.number.valid,
2118                         ast_channel_caller(caller_chan)->id.number.str, ast_channel_name(caller_chan)));
2119                 callee_chan_id = ast_strdupa(S_COR(ast_channel_caller(callee_chan)->id.number.valid,
2120                         ast_channel_caller(callee_chan)->id.number.str, ast_channel_name(callee_chan)));
2121                 len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
2122                 args = ast_alloca(len);
2123                 touch_filename = ast_alloca(len);
2124                 snprintf(touch_filename, len, "auto-%ld-%s-%s", (long)time(NULL), caller_chan_id, callee_chan_id);
2125                 snprintf(args, len, "%s.%s,b", touch_filename, S_OR(touch_format, "wav"));
2126         }
2127
2128         for( x = 0; x < strlen(args); x++) {
2129                 if (args[x] == '/')
2130                         args[x] = '-';
2131         }
2132
2133         ast_verb(3, "User hit '%s' to record call. filename: %s\n", code, touch_filename);
2134
2135         pbx_exec(callee_chan, mixmonitor_app, args);
2136         pbx_builtin_setvar_helper(callee_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
2137         pbx_builtin_setvar_helper(caller_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
2138         return AST_FEATURE_RETURN_SUCCESS;
2139 }
2140 #endif
2141
2142 #if 0
2143 static int builtin_disconnect(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2144 {
2145         ast_verb(4, "User hit '%s' to disconnect call.\n", code);
2146         return AST_FEATURE_RETURN_HANGUP;
2147 }
2148 #endif
2149
2150 #if 0
2151 /*!
2152  * \brief Find the context for the transfer
2153  * \param transferer
2154  * \param transferee
2155  *
2156  * Grab the TRANSFER_CONTEXT, if fails try grabbing macrocontext.
2157  * \return a context string
2158  */
2159 static const char *real_ctx(struct ast_channel *transferer, struct ast_channel *transferee)
2160 {
2161         const char *s = pbx_builtin_getvar_helper(transferer, "TRANSFER_CONTEXT");
2162         if (ast_strlen_zero(s)) {
2163                 s = pbx_builtin_getvar_helper(transferee, "TRANSFER_CONTEXT");
2164         }
2165         if (ast_strlen_zero(s)) { /* Use the non-macro context to transfer the call XXX ? */
2166                 s = ast_channel_macrocontext(transferer);
2167         }
2168         if (ast_strlen_zero(s)) {
2169                 s = ast_channel_context(transferer);
2170         }
2171         return s;
2172 }
2173 #endif
2174
2175 #if 0
2176 /*!
2177  * \brief make channels compatible
2178  * \param c
2179  * \param newchan
2180  * \retval 0 on success.
2181  * \retval -1 on failure.
2182  */
2183 static int check_compat(struct ast_channel *c, struct ast_channel *newchan)
2184 {
2185         if (ast_channel_make_compatible(c, newchan) < 0) {
2186                 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n",
2187                         ast_channel_name(c), ast_channel_name(newchan));
2188                 ast_autoservice_chan_hangup_peer(c, newchan);
2189                 return -1;
2190         }
2191         return 0;
2192 }
2193 #endif
2194
2195 #if 0
2196 /*!
2197  * \internal
2198  * \brief Builtin attended transfer failed cleanup.
2199  * \since 10.0
2200  *
2201  * \param transferee Party A in the transfer.
2202  * \param transferer Party B in the transfer.
2203  * \param connected_line Saved connected line info about party A.
2204  *
2205  * \note The connected_line data is freed.
2206  *
2207  * \return Nothing
2208  */
2209 static void atxfer_fail_cleanup(struct ast_channel *transferee, struct ast_channel *transferer, struct ast_party_connected_line *connected_line)
2210 {
2211         finishup(transferee);
2212
2213         /*
2214          * Restore party B connected line info about party A.
2215          *
2216          * Party B was the caller to party C and is the last known mode
2217          * for party B.
2218          */
2219         if (ast_channel_connected_line_sub(transferee, transferer, connected_line, 0) &&
2220                 ast_channel_connected_line_macro(transferee, transferer, connected_line, 1, 0)) {
2221                 ast_channel_update_connected_line(transferer, connected_line, NULL);
2222         }
2223         ast_party_connected_line_free(connected_line);
2224 }
2225 #endif
2226
2227 #if 0
2228 /*!
2229  * \brief Attended transfer
2230  * \param chan transfered user
2231  * \param peer person transfering call
2232  * \param config
2233  * \param code
2234  * \param sense feature options
2235  *
2236  * \param data
2237  * Get extension to transfer to, if you cannot generate channel (or find extension)
2238  * return to host channel. After called channel answered wait for hangup of transferer,
2239  * bridge call between transfer peer (taking them off hold) to attended transfer channel.
2240  *
2241  * \return -1 on failure
2242  */
2243 static int builtin_atxfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2244 {
2245         struct ast_channel *transferer;/* Party B */
2246         struct ast_channel *transferee;/* Party A */
2247         struct ast_exten *park_exten;
2248         const char *chan1_attended_sound;
2249         const char *chan2_attended_sound;
2250         const char *transferer_real_context;
2251         char xferto[256] = "";
2252         int res;
2253         int outstate=0;
2254         struct ast_channel *newchan;
2255         struct ast_channel *xferchan;
2256         struct ast_bridge_thread_obj *tobj;
2257         struct ast_bridge_config bconfig;
2258         int l;
2259         struct ast_party_connected_line connected_line;
2260         struct ast_datastore *features_datastore;
2261         struct ast_dial_features *dialfeatures;
2262         char *transferer_tech;
2263         char *transferer_name;
2264         char *transferer_name_orig;
2265         char *dash;
2266         RAII_VAR(struct ast_features_xfer_config *, xfer_cfg, NULL, ao2_cleanup);
2267
2268         ast_debug(1, "Executing Attended Transfer %s, %s (sense=%d) \n", ast_channel_name(chan), ast_channel_name(peer), sense);
2269         set_peers(&transferer, &transferee, peer, chan, sense);
2270         transferer_real_context = real_ctx(transferer, transferee);
2271
2272         /* Start autoservice on transferee while we talk to the transferer */
2273         ast_autoservice_start(transferee);
2274         ast_indicate(transferee, AST_CONTROL_HOLD);
2275
2276         /* Transfer */
2277         res = ast_stream_and_wait(transferer, "pbx-transfer", AST_DIGIT_ANY);
2278         if (res < 0) {
2279                 finishup(transferee);
2280                 return -1;
2281         }
2282         if (res > 0) { /* If they've typed a digit already, handle it */
2283                 xferto[0] = (char) res;
2284         }
2285
2286         ast_channel_lock(transferer);
2287         xfer_cfg = ast_get_chan_features_xfer_config(transferer);
2288         ast_channel_unlock(transferer);
2289
2290         /* XXX All accesses to the xfer_cfg structure after this point are not thread-safe,
2291          * but I don't care because this is dead code.
2292          */
2293
2294         /* this is specific of atxfer */
2295         res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, xfer_cfg->transferdigittimeout);
2296         if (res < 0) {  /* hangup or error, (would be 0 for invalid and 1 for valid) */
2297                 finishup(transferee);
2298                 return -1;
2299         }
2300         l = strlen(xferto);
2301         if (res == 0) {
2302                 if (l) {
2303                         ast_log(LOG_WARNING, "Extension '%s' does not exist in context '%s'\n",
2304                                 xferto, transferer_real_context);
2305                 } else {
2306                         /* Does anyone care about this case? */
2307                         ast_log(LOG_WARNING, "No digits dialed for atxfer.\n");
2308                 }
2309                 ast_stream_and_wait(transferer, "pbx-invalid", "");
2310                 finishup(transferee);
2311                 return AST_FEATURE_RETURN_SUCCESS;
2312         }
2313
2314         park_exten = get_parking_exten(xferto, transferer, transferer_real_context);
2315         if (park_exten) {
2316                 /* We are transfering the transferee to a parking lot. */
2317                 return xfer_park_call_helper(transferee, transferer, park_exten);
2318         }
2319
2320         /*
2321          * Append context to dialed transfer number.
2322          *
2323          * NOTE: The local channel needs the /n flag so party C will use
2324          * the feature flags set by the dialplan when calling that
2325          * party.
2326          */
2327         snprintf(xferto + l, sizeof(xferto) - l, "@%s/n", transferer_real_context);
2328
2329         /* If we are performing an attended transfer and we have two channels involved then
2330            copy sound file information to play upon attended transfer completion */
2331         chan1_attended_sound = pbx_builtin_getvar_helper(transferer, "ATTENDED_TRANSFER_COMPLETE_SOUND");
2332         chan2_attended_sound = pbx_builtin_getvar_helper(transferee, "ATTENDED_TRANSFER_COMPLETE_SOUND");
2333         if (!ast_strlen_zero(chan1_attended_sound)) {
2334                 pbx_builtin_setvar_helper(transferer, "BRIDGE_PLAY_SOUND", chan1_attended_sound);
2335         }
2336         if (!ast_strlen_zero(chan2_attended_sound)) {
2337                 pbx_builtin_setvar_helper(transferee, "BRIDGE_PLAY_SOUND", chan2_attended_sound);
2338         }
2339
2340         /* Extract redial transferer information from the channel name. */
2341         transferer_name_orig = ast_strdupa(ast_channel_name(transferer));
2342         transferer_name = ast_strdupa(transferer_name_orig);
2343         transferer_tech = strsep(&transferer_name, "/");
2344         dash = strrchr(transferer_name, '-');
2345         if (dash) {
2346                 /* Trim off channel name sequence/serial number. */
2347                 *dash = '\0';
2348         }
2349
2350         /* Stop autoservice so we can monitor all parties involved in the transfer. */
2351         if (ast_autoservice_stop(transferee) < 0) {
2352                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2353                 return -1;
2354         }
2355
2356         /* Save connected line info for party B about party A in case transfer fails. */
2357         ast_party_connected_line_init(&connected_line);
2358         ast_channel_lock(transferer);
2359         ast_party_connected_line_copy(&connected_line, ast_channel_connected(transferer));
2360         ast_channel_unlock(transferer);
2361         connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
2362
2363         /* Dial party C */
2364         newchan = feature_request_and_dial(transferer, transferer_name_orig, transferer,
2365                 transferee, "Local", ast_channel_nativeformats(transferer), xferto,
2366                 xfer_cfg->atxfernoanswertimeout, &outstate, ast_channel_language(transferer));
2367         ast_debug(2, "Dial party C result: newchan:%d, outstate:%d\n", !!newchan, outstate);
2368
2369         if (!ast_check_hangup(transferer)) {
2370                 /* Transferer (party B) is up */
2371                 ast_debug(1, "Actually doing an attended transfer.\n");
2372
2373                 /* Start autoservice on transferee while the transferer deals with party C. */
2374                 ast_autoservice_start(transferee);
2375
2376                 ast_indicate(transferer, -1);
2377                 if (!newchan) {
2378                         /* any reason besides user requested cancel and busy triggers the failed sound */
2379                         switch (outstate) {
2380                         case AST_CONTROL_UNHOLD:/* Caller requested cancel or party C answer timeout. */
2381                         case AST_CONTROL_BUSY:
2382                         case AST_CONTROL_CONGESTION:
2383                                 if (ast_stream_and_wait(transferer, xfer_cfg->xfersound, "")) {
2384                                         ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
2385                                 }
2386                                 break;
2387                         default:
2388                                 if (ast_stream_and_wait(transferer, xfer_cfg->xferfailsound, "")) {
2389                                         ast_log(LOG_WARNING, "Failed to play transfer failed sound!\n");
2390                                 }
2391                                 break;
2392                         }
2393                         atxfer_fail_cleanup(transferee, transferer, &connected_line);
2394                         return AST_FEATURE_RETURN_SUCCESS;
2395                 }
2396
2397                 if (check_compat(transferer, newchan)) {
2398                         if (ast_stream_and_wait(transferer, xfer_cfg->xferfailsound, "")) {
2399                                 ast_log(LOG_WARNING, "Failed to play transfer failed sound!\n");
2400                         }
2401                         atxfer_fail_cleanup(transferee, transferer, &connected_line);
2402                         return AST_FEATURE_RETURN_SUCCESS;
2403                 }
2404                 memset(&bconfig,0,sizeof(struct ast_bridge_config));
2405                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_DISCONNECT);
2406                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_DISCONNECT);
2407
2408                 /*
2409                  * Let party B and C talk as long as they want while party A
2410                  * languishes in autoservice listening to MOH.
2411                  */
2412                 ast_bridge_call(transferer, newchan, &bconfig);
2413
2414                 if (ast_check_hangup(newchan) || !ast_check_hangup(transferer)) {
2415                         ast_autoservice_chan_hangup_peer(transferer, newchan);
2416                         if (ast_stream_and_wait(transferer, xfer_cfg->xfersound, "")) {
2417                                 ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
2418                         }
2419                         atxfer_fail_cleanup(transferee, transferer, &connected_line);
2420                         return AST_FEATURE_RETURN_SUCCESS;
2421                 }
2422
2423                 /* Transferer (party B) is confirmed hung up at this point. */
2424                 if (check_compat(transferee, newchan)) {
2425                         finishup(transferee);
2426                         ast_party_connected_line_free(&connected_line);
2427                         return -1;
2428                 }
2429
2430                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2431                 if ((ast_autoservice_stop(transferee) < 0)
2432                         || (ast_waitfordigit(transferee, 100) < 0)
2433                         || (ast_waitfordigit(newchan, 100) < 0)
2434                         || ast_check_hangup(transferee)
2435                         || ast_check_hangup(newchan)) {
2436                         ast_hangup(newchan);
2437                         ast_party_connected_line_free(&connected_line);
2438                         return -1;
2439                 }
2440         } else if (!ast_check_hangup(transferee)) {
2441                 /* Transferer (party B) has hung up at this point.  Doing blonde transfer. */
2442                 ast_debug(1, "Actually doing a blonde transfer.\n");
2443
2444                 if (!newchan && !xfer_cfg->atxferdropcall) {
2445                         /* Party C is not available, try to call party B back. */
2446                         unsigned int tries = 0;
2447
2448                         if (ast_strlen_zero(transferer_name) || ast_strlen_zero(transferer_tech)) {
2449                                 ast_log(LOG_WARNING,
2450                                         "Transferer channel name: '%s' cannot be used for callback.\n",
2451                                         transferer_name_orig);
2452                                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2453                                 ast_party_connected_line_free(&connected_line);
2454                                 return -1;
2455                         }
2456
2457                         tries = 0;
2458                         for (;;) {
2459                                 /* Try to get party B back. */
2460                                 ast_debug(1, "We're trying to callback %s/%s\n",
2461                                         transferer_tech, transferer_name);
2462                                 newchan = feature_request_and_dial(transferer, transferer_name_orig,
2463                                         transferee, transferee, transferer_tech,
2464                                         ast_channel_nativeformats(transferee), transferer_name,
2465                                         xfer_cfg->atxfernoanswertimeout, &outstate, ast_channel_language(transferer));
2466                                 ast_debug(2, "Dial party B result: newchan:%d, outstate:%d\n",
2467                                         !!newchan, outstate);
2468                                 if (newchan) {
2469                                         /*
2470                                          * We have recalled party B (newchan).  We need to give this
2471                                          * call leg the same feature flags as the original party B call
2472                                          * leg.
2473                                          */
2474                                         ast_channel_lock(transferer);
2475                                         features_datastore = ast_channel_datastore_find(transferer,
2476                                                 &dial_features_info, NULL);
2477                                         if (features_datastore && (dialfeatures = features_datastore->data)) {
2478                                                 struct ast_flags my_features = { 0 };
2479                                                 struct ast_flags peer_features = { 0 };
2480
2481                                                 ast_copy_flags(&my_features, &dialfeatures->my_features,
2482                                                         AST_FLAGS_ALL);
2483                                                 ast_copy_flags(&peer_features, &dialfeatures->peer_features,
2484                                                         AST_FLAGS_ALL);
2485                                                 ast_channel_unlock(transferer);
2486                                                 add_features_datastore(newchan, &my_features, &peer_features);
2487                                         } else {
2488                                                 ast_channel_unlock(transferer);
2489                                         }
2490                                         break;
2491                                 }
2492                                 if (ast_check_hangup(transferee)) {
2493                                         break;
2494                                 }
2495
2496                                 ++tries;
2497                                 if (xfer_cfg->atxfercallbackretries <= tries) {
2498                                         /* No more callback tries remaining. */
2499                                         break;
2500                                 }
2501
2502                                 if (xfer_cfg->atxferloopdelay) {
2503                                         /* Transfer failed, sleeping */
2504                                         ast_debug(1, "Sleeping for %d ms before retrying atxfer.\n",
2505                                                 xfer_cfg->atxferloopdelay);
2506                                         ast_safe_sleep(transferee, xfer_cfg->atxferloopdelay);
2507                                         if (ast_check_hangup(transferee)) {
2508                                                 ast_party_connected_line_free(&connected_line);
2509                                                 return -1;
2510                                         }
2511                                 }
2512
2513                                 /* Retry dialing party C. */
2514                                 ast_debug(1, "We're retrying to call %s/%s\n", "Local", xferto);
2515                                 newchan = feature_request_and_dial(transferer, transferer_name_orig,
2516                                         transferer, transferee, "Local",
2517                                         ast_channel_nativeformats(transferee), xferto,
2518                                         xfer_cfg->atxfernoanswertimeout, &outstate, ast_channel_language(transferer));
2519                                 ast_debug(2, "Redial party C result: newchan:%d, outstate:%d\n",
2520                                         !!newchan, outstate);
2521                                 if (newchan || ast_check_hangup(transferee)) {
2522                                         break;
2523                                 }
2524                         }
2525                 }
2526                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2527                 if (!newchan) {
2528                         /* No party C or could not callback party B. */
2529                         ast_party_connected_line_free(&connected_line);
2530                         return -1;
2531                 }
2532
2533                 /* newchan is up, we should prepare transferee and bridge them */
2534                 if (ast_check_hangup(newchan)) {
2535                         ast_autoservice_chan_hangup_peer(transferee, newchan);
2536                         ast_party_connected_line_free(&connected_line);
2537                         return -1;
2538                 }
2539                 if (check_compat(transferee, newchan)) {
2540                         ast_party_connected_line_free(&connected_line);
2541                         return -1;
2542                 }
2543         } else {
2544                 /*
2545                  * Both the transferer and transferee have hungup.  If newchan
2546                  * is up, hang it up as it has no one to talk to.
2547                  */
2548                 ast_debug(1, "Everyone is hungup.\n");
2549                 ast_hangup(newchan);
2550                 ast_party_connected_line_free(&connected_line);
2551                 return -1;
2552         }
2553
2554         /* Initiate the channel transfer of party A to party C (or recalled party B). */
2555         xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", ast_channel_linkedid(transferee), 0, "Transfered/%s", ast_channel_name(transferee));
2556         if (!xferchan) {
2557                 ast_autoservice_chan_hangup_peer(transferee, newchan);
2558                 ast_party_connected_line_free(&connected_line);
2559                 return -1;
2560         }
2561
2562         /* Give party A a momentary ringback tone during transfer. */
2563         ast_channel_visible_indication_set(xferchan, AST_CONTROL_RINGING);
2564
2565         /* Make formats okay */
2566         ast_format_copy(ast_channel_readformat(xferchan), ast_channel_readformat(transferee));
2567         ast_format_copy(ast_channel_writeformat(xferchan), ast_channel_writeformat(transferee));
2568
2569         if (ast_channel_masquerade(xferchan, transferee)) {
2570                 ast_hangup(xferchan);
2571                 ast_autoservice_chan_hangup_peer(transferee, newchan);
2572                 ast_party_connected_line_free(&connected_line);
2573                 return -1;
2574         }
2575
2576         dash = strrchr(xferto, '@');
2577         if (dash) {
2578                 /* Trim off the context. */
2579                 *dash = '\0';
2580         }
2581         ast_explicit_goto(xferchan, transferer_real_context, xferto, 1);
2582         ast_channel_state_set(xferchan, AST_STATE_UP);
2583         ast_clear_flag(ast_channel_flags(xferchan), AST_FLAGS_ALL);
2584
2585         /* Do the masquerade manually to make sure that is is completed. */
2586         ast_do_masquerade(xferchan);
2587
2588         ast_channel_state_set(newchan, AST_STATE_UP);
2589         ast_clear_flag(ast_channel_flags(newchan), AST_FLAGS_ALL);
2590         tobj = ast_calloc(1, sizeof(*tobj));
2591         if (!tobj) {
2592                 ast_hangup(xferchan);
2593                 ast_hangup(newchan);
2594                 ast_party_connected_line_free(&connected_line);
2595                 return -1;
2596         }
2597
2598         tobj->chan = newchan;
2599         tobj->peer = xferchan;
2600         tobj->bconfig = *config;
2601
2602         ast_channel_lock(newchan);
2603         features_datastore = ast_channel_datastore_find(newchan, &dial_features_info, NULL);
2604         if (features_datastore && (dialfeatures = features_datastore->data)) {
2605                 ast_copy_flags(&tobj->bconfig.features_callee, &dialfeatures->my_features,
2606                         AST_FLAGS_ALL);
2607         }
2608         ast_channel_unlock(newchan);
2609
2610         ast_channel_lock(xferchan);
2611         features_datastore = ast_channel_datastore_find(xferchan, &dial_features_info, NULL);
2612         if (features_datastore && (dialfeatures = features_datastore->data)) {
2613                 ast_copy_flags(&tobj->bconfig.features_caller, &dialfeatures->my_features,
2614                         AST_FLAGS_ALL);
2615         }
2616         ast_channel_unlock(xferchan);
2617
2618         if (tobj->bconfig.end_bridge_callback_data_fixup) {
2619                 tobj->bconfig.end_bridge_callback_data_fixup(&tobj->bconfig, tobj->peer, tobj->chan);
2620         }
2621
2622         /*
2623          * xferchan is transferee, and newchan is the transfer target
2624          * So...in a transfer, who is the caller and who is the callee?
2625          *
2626          * When the call is originally made, it is clear who is caller and callee.
2627          * When a transfer occurs, it is my humble opinion that the transferee becomes
2628          * the caller, and the transfer target is the callee.
2629          *
2630          * The problem is that these macros were set with the intention of the original
2631          * caller and callee taking those roles.  A transfer can totally mess things up,
2632          * to be technical.  What sucks even more is that you can't effectively change
2633          * the macros in the dialplan during the call from the transferer to the transfer
2634          * target because the transferee is stuck with whatever role he originally had.
2635          *
2636          * I think the answer here is just to make sure that it is well documented that
2637          * during a transfer, the transferee is the "caller" and the transfer target
2638          * is the "callee."
2639          *
2640          * This means that if party B calls party A, and party B transfers party A to
2641          * party C, then A has switched roles for the call.  Now party A will have the
2642          * caller macro called on his channel instead of the callee macro.
2643          *
2644          * Luckily, the method by which the party B to party C bridge is
2645          * launched above ensures that the transferee is the "chan" on
2646          * the bridge and the transfer target is the "peer," so my idea
2647          * for the roles post-transfer does not require extensive code
2648          * changes.
2649          */
2650
2651         /* Transfer party C connected line to party A */
2652         ast_channel_lock(transferer);
2653         /*
2654          * Due to a limitation regarding when callerID is set on a Local channel,
2655          * we use the transferer's connected line information here.
2656          */
2657         ast_party_connected_line_copy(&connected_line, ast_channel_connected(transferer));
2658         ast_channel_unlock(transferer);
2659         connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
2660         if (ast_channel_connected_line_sub(newchan, xferchan, &connected_line, 0) &&
2661                 ast_channel_connected_line_macro(newchan, xferchan, &connected_line, 1, 0)) {
2662                 ast_channel_update_connected_line(xferchan, &connected_line, NULL);
2663         }
2664
2665         /* Transfer party A connected line to party C */
2666         ast_channel_lock(xferchan);
2667         ast_connected_line_copy_from_caller(&connected_line, ast_channel_caller(xferchan));
2668         ast_channel_unlock(xferchan);
2669         connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
2670         if (ast_channel_connected_line_sub(xferchan, newchan, &connected_line, 0) &&
2671                 ast_channel_connected_line_macro(xferchan, newchan, &connected_line, 0, 0)) {
2672                 ast_channel_update_connected_line(newchan, &connected_line, NULL);
2673         }
2674
2675         if (ast_stream_and_wait(newchan, xfer_cfg->xfersound, ""))
2676                 ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
2677         bridge_call_thread_launch(tobj);
2678
2679         ast_party_connected_line_free(&connected_line);
2680         return -1;/* The transferee is masqueraded and the original bridged channels can be hungup. */
2681 }
2682 #endif
2683
2684 /*!
2685  * \internal
2686  * \brief Get the extension for a given builtin feature
2687  *
2688  * \pre expects features_lock to be readlocked
2689  *
2690  * \retval 0 success
2691  * \retval non-zero failiure
2692  */
2693 static int builtin_feature_get_exten(struct ast_channel *chan, const char *feature_name,
2694                 char *buf, size_t len)
2695 {
2696         SCOPED_CHANNELLOCK(lock, chan);
2697
2698         return ast_get_builtin_feature(chan, feature_name, buf, len);
2699 }
2700
2701 static void set_config_flags(struct ast_channel *chan, struct ast_bridge_config *config)
2702 {
2703 /* BUGBUG there is code that checks AST_BRIDGE_IGNORE_SIGS but no code to set it. */
2704 /* BUGBUG there is code that checks AST_BRIDGE_REC_CHANNEL_0 but no code to set it. */
2705 /* BUGBUG there is code that checks AST_BRIDGE_REC_CHANNEL_1 but no code to set it. */
2706         ast_clear_flag(config, AST_FLAGS_ALL);
2707
2708         if (ast_test_flag(&config->features_caller, AST_FEATURE_DTMF_MASK)) {
2709                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
2710         }
2711         if (ast_test_flag(&config->features_callee, AST_FEATURE_DTMF_MASK)) {
2712                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
2713         }
2714
2715         if (!(ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_0) && ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_1))) {
2716                 RAII_VAR(struct ao2_container *, applicationmap, NULL, ao2_cleanup);
2717
2718                 ast_channel_lock(chan);
2719                 applicationmap = ast_get_chan_applicationmap(chan);
2720                 ast_channel_unlock(chan);
2721
2722                 if (!applicationmap) {
2723                         return;
2724                 }
2725
2726                 /* If an applicationmap exists for this channel at all, then the channel needs the DTMF flag set */
2727                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
2728         }
2729 }
2730
2731 #if 0
2732 /*!
2733  * \internal
2734  * \brief Get feature and dial.
2735  *
2736  * \param caller Channel to represent as the calling channel for the dialed channel.
2737  * \param caller_name Original caller channel name.
2738  * \param requestor Channel to say is requesting the dial (usually the caller).
2739  * \param transferee Channel that the dialed channel will be transferred to.
2740  * \param type Channel technology type to dial.
2741  * \param format Codec formats for dialed channel.
2742  * \param addr destination of the call
2743  * \param timeout Time limit for dialed channel to answer in ms. Must be greater than zero.
2744  * \param outstate Status of dialed channel if unsuccessful.
2745  * \param language Language of the caller.
2746  *
2747  * \note
2748  * outstate can be:
2749  * 0, AST_CONTROL_BUSY, AST_CONTROL_CONGESTION,
2750  * AST_CONTROL_ANSWER, or AST_CONTROL_UNHOLD.  If
2751  * AST_CONTROL_UNHOLD then the caller channel cancelled the
2752  * transfer or the dialed channel did not answer before the
2753  * timeout.
2754  *
2755  * \details
2756  * Request channel, set channel variables, initiate call,
2757  * check if they want to disconnect, go into loop, check if timeout has elapsed,
2758  * check if person to be transfered hung up, check for answer break loop,
2759  * set cdr return channel.
2760  *
2761  * \retval Channel Connected channel for transfer.
2762  * \retval NULL on failure to get third party connected.
2763  *
2764  * \note This is similar to __ast_request_and_dial() in channel.c
2765  */
2766 static struct ast_channel *feature_request_and_dial(struct ast_channel *caller,
2767         const char *caller_name, struct ast_channel *requestor,
2768         struct ast_channel *transferee, const char *type, struct ast_format_cap *cap, const char *addr,
2769         int timeout, int *outstate, const char *language)
2770 {
2771         int state = 0;
2772         int cause = 0;
2773         int to;
2774         int caller_hungup;
2775         int transferee_hungup;
2776         struct ast_channel *chan;
2777         struct ast_channel *monitor_chans[3];
2778         struct ast_channel *active_channel;
2779         int res;
2780         int ready = 0;
2781         struct timeval started;
2782         int x, len = 0;
2783         char disconnect_code[AST_FEATURE_MAX_LEN];
2784         char *dialed_code = NULL;
2785         struct ast_format_cap *tmp_cap;
2786         struct ast_format best_audio_fmt;
2787         struct ast_frame *f;
2788         int disconnect_res;
2789         AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
2790
2791         tmp_cap = ast_format_cap_alloc_nolock();
2792         if (!tmp_cap) {
2793                 if (outstate) {
2794                         *outstate = 0;
2795                 }
2796                 return NULL;
2797         }
2798         ast_best_codec(cap, &best_audio_fmt);
2799         ast_format_cap_add(tmp_cap, &best_audio_fmt);
2800
2801         caller_hungup = ast_check_hangup(caller);
2802
2803         if (!(chan = ast_request(type, tmp_cap, requestor, addr, &cause))) {
2804                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, addr);
2805                 switch (cause) {
2806                 case AST_CAUSE_BUSY:
2807                         state = AST_CONTROL_BUSY;
2808                         break;
2809                 case AST_CAUSE_CONGESTION:
2810                         state = AST_CONTROL_CONGESTION;
2811                         break;
2812                 default:
2813                         state = 0;
2814                         break;
2815                 }
2816                 goto done;
2817         }
2818
2819         ast_channel_language_set(chan, language);
2820         ast_channel_inherit_variables(caller, chan);
2821         pbx_builtin_setvar_helper(chan, "TRANSFERERNAME", caller_name);
2822
2823         ast_channel_lock(chan);
2824         ast_connected_line_copy_from_caller(ast_channel_connected(chan), ast_channel_caller(requestor));
2825         ast_channel_unlock(chan);
2826
2827         if (ast_call(chan, addr, timeout)) {
2828                 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, addr);
2829                 switch (ast_channel_hangupcause(chan)) {
2830                 case AST_CAUSE_BUSY:
2831                         state = AST_CONTROL_BUSY;
2832                         break;
2833                 case AST_CAUSE_CONGESTION:
2834                         state = AST_CONTROL_CONGESTION;
2835                         break;
2836                 default:
2837                         state = 0;
2838                         break;
2839                 }
2840                 goto done;
2841         }
2842
2843         /* support dialing of the featuremap disconnect code while performing an attended tranfer */
2844         ast_channel_lock(chan);
2845         disconnect_res = ast_get_builtin_feature(chan, "disconnect",
2846                         disconnect_code, sizeof(disconnect_code));
2847         ast_channel_unlock(chan);
2848
2849         if (!disconnect_res) {
2850                 len = strlen(disconnect_code) + 1;
2851                 dialed_code = ast_alloca(len);
2852                 memset(dialed_code, 0, len);
2853         }
2854
2855         x = 0;
2856         started = ast_tvnow();
2857         to = timeout;
2858         AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
2859
2860         ast_poll_channel_add(caller, chan);
2861
2862         transferee_hungup = 0;
2863         while (!ast_check_hangup(transferee) && (ast_channel_state(chan) != AST_STATE_UP)) {
2864                 int num_chans = 0;
2865
2866                 monitor_chans[num_chans++] = transferee;
2867                 monitor_chans[num_chans++] = chan;
2868                 if (!caller_hungup) {
2869                         if (ast_check_hangup(caller)) {
2870                                 caller_hungup = 1;
2871
2872 #if defined(ATXFER_NULL_TECH)
2873                                 /* Change caller's name to ensure that it will remain unique. */
2874                                 set_new_chan_name(caller);
2875
2876                                 /*
2877                                  * Get rid of caller's physical technology so it is free for
2878                                  * other calls.
2879                                  */
2880                                 set_kill_chan_tech(caller);
2881 #endif  /* defined(ATXFER_NULL_TECH) */
2882                         } else {
2883                                 /* caller is not hungup so monitor it. */
2884                                 monitor_chans[num_chans++] = caller;
2885                         }
2886                 }
2887
2888                 /* see if the timeout has been violated */
2889                 if (ast_tvdiff_ms(ast_tvnow(), started) > timeout) {
2890                         state = AST_CONTROL_UNHOLD;
2891                         ast_log(LOG_NOTICE, "We exceeded our AT-timeout for %s\n", ast_channel_name(chan));
2892                         break; /*doh! timeout*/
2893                 }
2894
2895                 active_channel = ast_waitfor_n(monitor_chans, num_chans, &to);
2896                 if (!active_channel)
2897                         continue;
2898
2899                 f = NULL;
2900                 if (transferee == active_channel) {
2901                         struct ast_frame *dup_f;
2902
2903                         f = ast_read(transferee);
2904                         if (f == NULL) { /*doh! where'd he go?*/
2905                                 transferee_hungup = 1;
2906                                 state = 0;
2907                                 break;
2908                         }
2909                         if (ast_is_deferrable_frame(f)) {
2910                                 dup_f = ast_frisolate(f);
2911                                 if (dup_f) {
2912                                         if (dup_f == f) {
2913                                                 f = NULL;
2914                                         }
2915                                         AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
2916                                 }
2917                         }
2918                 } else if (chan == active_channel) {
2919                         if (!ast_strlen_zero(ast_channel_call_forward(chan))) {
2920                                 state = 0;
2921                                 ast_autoservice_start(transferee);
2922                                 chan = ast_call_forward(caller, chan, NULL, tmp_cap, NULL, &state);
2923                                 ast_autoservice_stop(transferee);
2924                                 if (!chan) {
2925                                         break;
2926                                 }
2927                                 continue;
2928                         }
2929                         f = ast_read(chan);
2930                         if (f == NULL) { /*doh! where'd he go?*/
2931                                 switch (ast_channel_hangupcause(chan)) {
2932                                 case AST_CAUSE_BUSY:
2933                                         state = AST_CONTROL_BUSY;
2934                                         break;
2935                                 case AST_CAUSE_CONGESTION:
2936                                         state = AST_CONTROL_CONGESTION;
2937                                         break;
2938                                 default:
2939                                         state = 0;
2940                                         break;
2941                                 }
2942                                 break;
2943                         }
2944
2945                         if (f->frametype == AST_FRAME_CONTROL) {
2946                                 if (f->subclass.integer == AST_CONTROL_RINGING) {
2947                                         ast_verb(3, "%s is ringing\n", ast_channel_name(chan));
2948                                         ast_indicate(caller, AST_CONTROL_RINGING);
2949                                 } else if (f->subclass.integer == AST_CONTROL_BUSY) {
2950                                         state = f->subclass.integer;
2951                                         ast_verb(3, "%s is busy\n", ast_channel_name(chan));
2952                                         ast_indicate(caller, AST_CONTROL_BUSY);
2953                                         ast_frfree(f);
2954                                         break;
2955                                 } else if (f->subclass.integer == AST_CONTROL_INCOMPLETE) {
2956                                         ast_verb(3, "%s dialed incomplete extension %s; ignoring\n", ast_channel_name(chan), ast_channel_exten(chan));
2957                                 } else if (f->subclass.integer == AST_CONTROL_CONGESTION) {
2958                                         state = f->subclass.integer;
2959                                         ast_verb(3, "%s is congested\n", ast_channel_name(chan));
2960                                         ast_indicate(caller, AST_CONTROL_CONGESTION);
2961                                         ast_frfree(f);
2962                                         break;
2963                                 } else if (f->subclass.integer == AST_CONTROL_ANSWER) {
2964                                         /* This is what we are hoping for */
2965                                         state = f->subclass.integer;
2966                                         ast_frfree(f);
2967                                         ready=1;
2968                                         break;
2969                                 } else if (f->subclass.integer == AST_CONTROL_PVT_CAUSE_CODE) {
2970                                         ast_indicate_data(caller, AST_CONTROL_PVT_CAUSE_CODE, f->data.ptr, f->datalen);
2971                                 } else if (f->subclass.integer == AST_CONTROL_CONNECTED_LINE) {
2972                                         if (caller_hungup) {
2973                                                 struct ast_party_connected_line connected;
2974
2975                                                 /* Just save it for the transfer. */
2976                                                 ast_party_connected_line_set_init(&connected, ast_channel_connected(caller));
2977                                                 res = ast_connected_line_parse_data(f->data.ptr, f->datalen,
2978                                                         &connected);
2979                                                 if (!res) {
2980                                                         ast_channel_set_connected_line(caller, &connected, NULL);
2981                                                 }
2982                                                 ast_party_connected_line_free(&connected);
2983                                         } else {
2984                                                 ast_autoservice_start(transferee);
2985                                                 if (ast_channel_connected_line_sub(chan, caller, f, 1) &&
2986                                                         ast_channel_connected_line_macro(chan, caller, f, 1, 1)) {
2987                                                         ast_indicate_data(caller, AST_CONTROL_CONNECTED_LINE,
2988                                                                 f->data.ptr, f->datalen);
2989                                                 }
2990                                                 ast_autoservice_stop(transferee);
2991                                         }
2992                                 } else if (f->subclass.integer == AST_CONTROL_REDIRECTING) {
2993                                         if (!caller_hungup) {
2994                                                 ast_autoservice_start(transferee);
2995                                                 if (ast_channel_redirecting_sub(chan, caller, f, 1) &&
2996                                                         ast_channel_redirecting_macro(chan, caller, f, 1, 1)) {
2997                                                         ast_indicate_data(caller, AST_CONTROL_REDIRECTING,
2998                                                                 f->data.ptr, f->datalen);
2999                                                 }
3000                                                 ast_autoservice_stop(transferee);
3001                                         }
3002                                 } else if (f->subclass.integer != -1
3003                                         && f->subclass.integer != AST_CONTROL_PROGRESS
3004                                         && f->subclass.integer != AST_CONTROL_PROCEEDING) {
3005                                         ast_log(LOG_NOTICE, "Don't know what to do about control frame: %d\n", f->subclass.integer);
3006                                 }
3007                                 /* else who cares */
3008                         } else if (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO) {
3009                                 ast_write(caller, f);
3010                         }
3011                 } else if (caller == active_channel) {
3012                         f = ast_read(caller);
3013                         if (f) {
3014                                 if (f->frametype == AST_FRAME_DTMF && dialed_code) {
3015                                         dialed_code[x++] = f->subclass.integer;
3016                                         dialed_code[x] = '\0';
3017                                         if (strlen(dialed_code) == len) {
3018                                                 x = 0;
3019                                         } else if (x && strncmp(dialed_code, disconnect_code, x)) {
3020                                                 x = 0;
3021                                                 dialed_code[x] = '\0';
3022                                         }
3023                                         if (*dialed_code && !strcmp(dialed_code, disconnect_code)) {
3024                                                 /* Caller Canceled the call */
3025                                                 state = AST_CONTROL_UNHOLD;
3026                                                 ast_frfree(f);
3027                                                 break;
3028                                         }
3029                                 } else if (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO) {
3030                                         ast_write(chan, f);
3031                                 }
3032                         }
3033                 }
3034                 if (f)
3035                         ast_frfree(f);
3036         } /* end while */
3037
3038         ast_poll_channel_del(caller, chan);
3039
3040         /*
3041          * We need to free all the deferred frames, but we only need to
3042          * queue the deferred frames if no hangup was received.