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