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