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