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