Add support for a realtime sorcery module.
[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 const struct ast_datastore_info dial_features_info = {
883         .type = "dial-features",
884         .destroy = ast_free_ptr,
885         .duplicate = dial_features_duplicate,
886 };
887
888 /*!
889  * \internal
890  * \brief Set the features datastore if it doesn't exist.
891  *
892  * \param chan Channel to add features datastore
893  * \param my_features The channel's feature flags
894  * \param peer_features The channel's bridge peer feature flags
895  *
896  * \retval TRUE if features datastore already existed.
897  */
898 static int add_features_datastore(struct ast_channel *chan, const struct ast_flags *my_features, const struct ast_flags *peer_features)
899 {
900         struct ast_datastore *datastore;
901         struct ast_dial_features *dialfeatures;
902
903         ast_channel_lock(chan);
904         datastore = ast_channel_datastore_find(chan, &dial_features_info, NULL);
905         ast_channel_unlock(chan);
906         if (datastore) {
907                 /* Already exists. */
908                 return 1;
909         }
910
911         /* Create a new datastore with specified feature flags. */
912         datastore = ast_datastore_alloc(&dial_features_info, NULL);
913         if (!datastore) {
914                 ast_log(LOG_WARNING, "Unable to create channel features datastore.\n");
915                 return 0;
916         }
917         dialfeatures = ast_calloc(1, sizeof(*dialfeatures));
918         if (!dialfeatures) {
919                 ast_log(LOG_WARNING, "Unable to allocate memory for feature flags.\n");
920                 ast_datastore_free(datastore);
921                 return 0;
922         }
923         ast_copy_flags(&dialfeatures->my_features, my_features, AST_FLAGS_ALL);
924         ast_copy_flags(&dialfeatures->peer_features, peer_features, AST_FLAGS_ALL);
925         datastore->inheritance = DATASTORE_INHERIT_FOREVER;
926         datastore->data = dialfeatures;
927         ast_channel_lock(chan);
928         ast_channel_datastore_add(chan, datastore);
929         ast_channel_unlock(chan);
930         return 0;
931 }
932
933 /* Forward declarations */
934 static struct ast_parkinglot *parkinglot_addref(struct ast_parkinglot *parkinglot);
935 static void parkinglot_unref(struct ast_parkinglot *parkinglot);
936 static struct ast_parkinglot *find_parkinglot(const char *name);
937 static struct ast_parkinglot *create_parkinglot(const char *name);
938 static struct ast_parkinglot *copy_parkinglot(const char *name, const struct ast_parkinglot *parkinglot);
939 static int parkinglot_activate(struct ast_parkinglot *parkinglot);
940 static int play_message_on_chan(struct ast_channel *play_to, struct ast_channel *other, const char *msg, const char *audiofile);
941
942 /*!
943  * \internal
944  * \brief Get the parking extension if it exists.
945  *
946  * \param exten_str Parking extension to see if exists.
947  * \param chan Channel to autoservice while looking for exten.  (Could be NULL)
948  * \param context Parking context to look in for exten.
949  *
950  * \retval exten on success.
951  * \retval NULL on error or exten does not exist.
952  */
953 static struct ast_exten *get_parking_exten(const char *exten_str, struct ast_channel *chan, const char *context)
954 {
955         struct ast_exten *exten;
956         struct pbx_find_info q = { .stacklen = 0 }; /* the rest is reset in pbx_find_extension */
957         const char *app_at_exten;
958
959         ast_debug(4, "Checking if %s@%s is a parking exten\n", exten_str, context);
960         exten = pbx_find_extension(chan, NULL, &q, context, exten_str, 1, NULL, NULL,
961                 E_MATCH);
962         if (!exten) {
963                 return NULL;
964         }
965
966         app_at_exten = ast_get_extension_app(exten);
967         if (!app_at_exten || strcasecmp(parkcall, app_at_exten)) {
968                 return NULL;
969         }
970
971         return exten;
972 }
973
974 int ast_parking_ext_valid(const char *exten_str, struct ast_channel *chan, const char *context)
975 {
976         return get_parking_exten(exten_str, chan, context) ? 1 : 0;
977 }
978
979 const char *ast_pickup_ext(void)
980 {
981         return pickup_ext;
982 }
983
984 struct ast_bridge_thread_obj
985 {
986         struct ast_bridge_config bconfig;
987         struct ast_channel *chan;
988         struct ast_channel *peer;
989         struct ast_callid *callid;                             /*<! callid pointer (Only used to bind thread) */
990         unsigned int return_to_pbx:1;
991 };
992
993 static int parkinglot_hash_cb(const void *obj, const int flags)
994 {
995         const struct ast_parkinglot *parkinglot = obj;
996
997         return ast_str_case_hash(parkinglot->name);
998 }
999
1000 static int parkinglot_cmp_cb(void *obj, void *arg, int flags)
1001 {
1002         struct ast_parkinglot *parkinglot = obj;
1003         struct ast_parkinglot *parkinglot2 = arg;
1004
1005         return !strcasecmp(parkinglot->name, parkinglot2->name) ? CMP_MATCH | CMP_STOP : 0;
1006 }
1007
1008 /*!
1009  * \brief store context, extension and priority
1010  * \param chan, context, ext, pri
1011  */
1012 static void set_c_e_p(struct ast_channel *chan, const char *context, const char *ext, int pri)
1013 {
1014         ast_channel_context_set(chan, context);
1015         ast_channel_exten_set(chan, ext);
1016         ast_channel_priority_set(chan, pri);
1017 }
1018
1019 /*!
1020  * \brief Check goto on transfer
1021  * \param chan
1022  *
1023  * Check if channel has 'GOTO_ON_BLINDXFR' set, if not exit.
1024  * When found make sure the types are compatible. Check if channel is valid
1025  * if so start the new channel else hangup the call.
1026  */
1027 static void check_goto_on_transfer(struct ast_channel *chan)
1028 {
1029         struct ast_channel *xferchan;
1030         const char *val;
1031         char *goto_on_transfer;
1032         char *x;
1033
1034         ast_channel_lock(chan);
1035         val = pbx_builtin_getvar_helper(chan, "GOTO_ON_BLINDXFR");
1036         if (ast_strlen_zero(val)) {
1037                 ast_channel_unlock(chan);
1038                 return;
1039         }
1040         goto_on_transfer = ast_strdupa(val);
1041         ast_channel_unlock(chan);
1042
1043         ast_debug(1, "Attempting GOTO_ON_BLINDXFR=%s for %s.\n", val, ast_channel_name(chan));
1044
1045         xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", ast_channel_linkedid(chan), 0,
1046                 "%s", ast_channel_name(chan));
1047         if (!xferchan) {
1048                 return;
1049         }
1050
1051         /* Make formats okay */
1052         ast_format_copy(ast_channel_readformat(xferchan), ast_channel_readformat(chan));
1053         ast_format_copy(ast_channel_writeformat(xferchan), ast_channel_writeformat(chan));
1054
1055         if (ast_channel_masquerade(xferchan, chan)) {
1056                 /* Failed to setup masquerade. */
1057                 ast_hangup(xferchan);
1058                 return;
1059         }
1060
1061         for (x = goto_on_transfer; *x; ++x) {
1062                 if (*x == '^') {
1063                         *x = ',';
1064                 }
1065         }
1066         ast_parseable_goto(xferchan, goto_on_transfer);
1067         ast_channel_state_set(xferchan, AST_STATE_UP);
1068         ast_clear_flag(ast_channel_flags(xferchan), AST_FLAGS_ALL);
1069         ast_channel_clear_softhangup(xferchan, AST_SOFTHANGUP_ALL);
1070
1071         ast_do_masquerade(xferchan);
1072         if (ast_pbx_start(xferchan)) {
1073                 /* Failed to start PBX. */
1074                 ast_hangup(xferchan);
1075         }
1076 }
1077
1078 static struct ast_channel *feature_request_and_dial(struct ast_channel *caller,
1079         const char *caller_name, struct ast_channel *requestor,
1080         struct ast_channel *transferee, const char *type, struct ast_format_cap *cap, const char *addr,
1081         int timeout, int *outstate, const char *language);
1082
1083 static const struct ast_datastore_info channel_app_data_datastore = {
1084         .type = "Channel appdata datastore",
1085         .destroy = ast_free_ptr,
1086 };
1087
1088 static int set_chan_app_data(struct ast_channel *chan, const char *src_app_data)
1089 {
1090         struct ast_datastore *datastore;
1091         char *dst_app_data;
1092
1093         datastore = ast_datastore_alloc(&channel_app_data_datastore, NULL);
1094         if (!datastore) {
1095                 return -1;
1096         }
1097
1098         dst_app_data = ast_malloc(strlen(src_app_data) + 1);
1099         if (!dst_app_data) {
1100                 ast_datastore_free(datastore);
1101                 return -1;
1102         }
1103
1104         ast_channel_data_set(chan, strcpy(dst_app_data, src_app_data));
1105         datastore->data = dst_app_data;
1106         ast_channel_datastore_add(chan, datastore);
1107         return 0;
1108 }
1109
1110 /*!
1111  * \brief bridge the call
1112  * \param data thread bridge.
1113  *
1114  * Set Last Data for respective channels, reset cdr for channels
1115  * bridge call, check if we're going back to dialplan
1116  * if not hangup both legs of the call
1117  */
1118 static void *bridge_call_thread(void *data)
1119 {
1120         struct ast_bridge_thread_obj *tobj = data;
1121
1122         if (tobj->callid) {
1123                 ast_callid_threadassoc_add(tobj->callid);
1124                 /* Need to deref and set to null since ast_bridge_thread_obj has no common destructor */
1125                 tobj->callid = ast_callid_unref(tobj->callid);
1126         }
1127
1128         ast_channel_appl_set(tobj->chan, !tobj->return_to_pbx ? "Transferred Call" : "ManagerBridge");
1129         if (set_chan_app_data(tobj->chan, ast_channel_name(tobj->peer))) {
1130                 ast_channel_data_set(tobj->chan, "(Empty)");
1131         }
1132         ast_channel_appl_set(tobj->peer, !tobj->return_to_pbx ? "Transferred Call" : "ManagerBridge");
1133         if (set_chan_app_data(tobj->peer, ast_channel_name(tobj->chan))) {
1134                 ast_channel_data_set(tobj->peer, "(Empty)");
1135         }
1136
1137         ast_bridge_call(tobj->peer, tobj->chan, &tobj->bconfig);
1138
1139         if (tobj->return_to_pbx) {
1140                 if (!ast_check_hangup(tobj->peer)) {
1141                         ast_log(LOG_VERBOSE, "putting peer %s into PBX again\n", ast_channel_name(tobj->peer));
1142                         if (ast_pbx_start(tobj->peer)) {
1143                                 ast_log(LOG_WARNING, "FAILED continuing PBX on peer %s\n", ast_channel_name(tobj->peer));
1144                                 ast_autoservice_chan_hangup_peer(tobj->chan, tobj->peer);
1145                         }
1146                 } else {
1147                         ast_autoservice_chan_hangup_peer(tobj->chan, tobj->peer);
1148                 }
1149                 if (!ast_check_hangup(tobj->chan)) {
1150                         ast_log(LOG_VERBOSE, "putting chan %s into PBX again\n", ast_channel_name(tobj->chan));
1151                         if (ast_pbx_start(tobj->chan)) {
1152                                 ast_log(LOG_WARNING, "FAILED continuing PBX on chan %s\n", ast_channel_name(tobj->chan));
1153                                 ast_hangup(tobj->chan);
1154                         }
1155                 } else {
1156                         ast_hangup(tobj->chan);
1157                 }
1158         } else {
1159                 ast_hangup(tobj->chan);
1160                 ast_hangup(tobj->peer);
1161         }
1162
1163         ast_free(tobj);
1164
1165         return NULL;
1166 }
1167
1168 /*!
1169  * \brief create thread for the parked call
1170  * \param data
1171  *
1172  * Create thread and attributes, call bridge_call_thread
1173  */
1174 static void bridge_call_thread_launch(struct ast_bridge_thread_obj *data)
1175 {
1176         pthread_t thread;
1177         pthread_attr_t attr;
1178         struct sched_param sched;
1179
1180         /* This needs to be unreffed once it has been associated with the new thread. */
1181         data->callid = ast_read_threadstorage_callid();
1182
1183         pthread_attr_init(&attr);
1184         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1185         if (ast_pthread_create(&thread, &attr, bridge_call_thread, data)) {
1186                 /* Failed to create thread. Ditch the reference to callid. */
1187                 ast_callid_unref(data->callid);
1188                 ast_hangup(data->chan);
1189                 ast_hangup(data->peer);
1190                 ast_log(LOG_ERROR, "Failed to create bridge_call_thread.\n");
1191                 return;
1192         }
1193         pthread_attr_destroy(&attr);
1194         memset(&sched, 0, sizeof(sched));
1195         pthread_setschedparam(thread, SCHED_RR, &sched);
1196 }
1197
1198 /*!
1199  * \brief Announce call parking by ADSI
1200  * \param chan .
1201  * \param parkingexten .
1202  * Create message to show for ADSI, display message.
1203  * \retval 0 on success.
1204  * \retval -1 on failure.
1205  */
1206 static int adsi_announce_park(struct ast_channel *chan, char *parkingexten)
1207 {
1208         int res;
1209         int justify[5] = {ADSI_JUST_CENT, ADSI_JUST_CENT, ADSI_JUST_CENT, ADSI_JUST_CENT};
1210         char tmp[256];
1211         char *message[5] = {NULL, NULL, NULL, NULL, NULL};
1212
1213         snprintf(tmp, sizeof(tmp), "Parked on %s", parkingexten);
1214         message[0] = tmp;
1215         res = ast_adsi_load_session(chan, NULL, 0, 1);
1216         if (res == -1)
1217                 return res;
1218         return ast_adsi_print(chan, message, justify, 1);
1219 }
1220
1221 /*!
1222  * \brief Find parking lot name from channel
1223  * \note Channel needs to be locked while the returned string is in use.
1224  */
1225 static const char *findparkinglotname(struct ast_channel *chan)
1226 {
1227         const char *name;
1228
1229         /* The channel variable overrides everything */
1230         name = pbx_builtin_getvar_helper(chan, "PARKINGLOT");
1231         if (!name && !ast_strlen_zero(ast_channel_parkinglot(chan))) {
1232                 /* Use the channel's parking lot. */
1233                 name = ast_channel_parkinglot(chan);
1234         }
1235         return name;
1236 }
1237
1238 /*! \brief Notify metermaids that we've changed an extension */
1239 static void notify_metermaids(const char *exten, char *context, enum ast_device_state state)
1240 {
1241         ast_debug(4, "Notification of state change to metermaids %s@%s\n to state '%s'",
1242                 exten, context, ast_devstate2str(state));
1243
1244         ast_devstate_changed(state, AST_DEVSTATE_CACHABLE, "park:%s@%s", exten, context);
1245 }
1246
1247 /*! \brief metermaids callback from devicestate.c */
1248 static enum ast_device_state metermaidstate(const char *data)
1249 {
1250         char *context;
1251         char *exten;
1252
1253         context = ast_strdupa(data);
1254
1255         exten = strsep(&context, "@");
1256         if (!context)
1257                 return AST_DEVICE_INVALID;
1258
1259         ast_debug(4, "Checking state of exten %s in context %s\n", exten, context);
1260
1261         if (!ast_exists_extension(NULL, context, exten, 1, NULL))
1262                 return AST_DEVICE_NOT_INUSE;
1263
1264         return AST_DEVICE_INUSE;
1265 }
1266
1267 /*! Options to pass to park_call_full */
1268 enum ast_park_call_options {
1269         /*! Provide ringing to the parked caller instead of music on hold */
1270         AST_PARK_OPT_RINGING =   (1 << 0),
1271         /*! Randomly choose a parking spot for the caller instead of choosing
1272          *  the first one that is available. */
1273         AST_PARK_OPT_RANDOMIZE = (1 << 1),
1274         /*! Do not announce the parking number */
1275         AST_PARK_OPT_SILENCE = (1 << 2),
1276 };
1277
1278 /*! Optional additional parking options when parking a call. */
1279 struct ast_park_call_args {
1280         /*! How long to wait in the parking lot before the call gets sent back
1281          *  to the specified return extension (or a best guess at where it came
1282          *  from if not explicitly specified). */
1283         int timeout;
1284         /*! An output parameter to store the parking space where the parked caller
1285          *  was placed. */
1286         int *extout;
1287         const char *orig_chan_name;
1288         const char *return_con;
1289         const char *return_ext;
1290         int return_pri;
1291         uint32_t flags;
1292         /*! Parked user that has already obtained a parking space */
1293         struct parkeduser *pu;
1294         /*! \brief Parkinglot to be parked in */
1295         struct ast_parkinglot *parkinglot;
1296 };
1297
1298 /*!
1299  * \internal
1300  * \brief Create a dynamic parking lot.
1301  *
1302  * \param name Dynamic parking lot name to create.
1303  * \param chan Channel to get dynamic parking lot parameters.
1304  *
1305  * \retval parkinglot on success.
1306  * \retval NULL on error.
1307  */
1308 static struct ast_parkinglot *create_dynamic_parkinglot(const char *name, struct ast_channel *chan)
1309 {
1310         const char *dyn_context;
1311         const char *dyn_exten;
1312         const char *dyn_range;
1313         const char *template_name;
1314         struct ast_parkinglot *template_parkinglot = NULL;
1315         struct ast_parkinglot *parkinglot;
1316         int dyn_start;
1317         int dyn_end;
1318
1319         ast_channel_lock(chan);
1320         template_name = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNAMIC"), ""));
1321         dyn_context = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNCONTEXT"), ""));
1322         dyn_exten = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNEXTEN"), ""));
1323         dyn_range = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNPOS"), ""));
1324         ast_channel_unlock(chan);
1325
1326         if (!ast_strlen_zero(template_name)) {
1327                 template_parkinglot = find_parkinglot(template_name);
1328                 if (!template_parkinglot) {
1329                         ast_debug(1, "PARKINGDYNAMIC lot %s does not exist.\n",
1330                                 template_name);
1331                 } else if (template_parkinglot->cfg.is_invalid) {
1332                         ast_debug(1, "PARKINGDYNAMIC lot %s has invalid config.\n",
1333                                 template_name);
1334                         parkinglot_unref(template_parkinglot);
1335                         template_parkinglot = NULL;
1336                 }
1337         }
1338         if (!template_parkinglot) {
1339                 template_parkinglot = parkinglot_addref(default_parkinglot);
1340                 ast_debug(1, "Using default parking lot for template\n");
1341         }
1342
1343         parkinglot = copy_parkinglot(name, template_parkinglot);
1344         if (!parkinglot) {
1345                 ast_log(LOG_ERROR, "Could not build dynamic parking lot!\n");
1346         } else {
1347                 /* Configure the dynamic parking lot. */
1348                 if (!ast_strlen_zero(dyn_context)) {
1349                         ast_copy_string(parkinglot->cfg.parking_con, dyn_context,
1350                                 sizeof(parkinglot->cfg.parking_con));
1351                 }
1352                 if (!ast_strlen_zero(dyn_exten)) {
1353                         ast_copy_string(parkinglot->cfg.parkext, dyn_exten,
1354                                 sizeof(parkinglot->cfg.parkext));
1355                 }
1356                 if (!ast_strlen_zero(dyn_range)) {
1357                         if (sscanf(dyn_range, "%30d-%30d", &dyn_start, &dyn_end) != 2) {
1358                                 ast_log(LOG_WARNING,
1359                                         "Format for parking positions is a-b, where a and b are numbers\n");
1360                         } else if (dyn_end < dyn_start || dyn_start <= 0 || dyn_end <= 0) {
1361                                 ast_log(LOG_WARNING,
1362                                         "Format for parking positions is a-b, where a <= b\n");
1363                         } else {
1364                                 parkinglot->cfg.parking_start = dyn_start;
1365                                 parkinglot->cfg.parking_stop = dyn_end;
1366                         }
1367                 }
1368
1369                 /*
1370                  * Sanity check for dynamic parking lot configuration.
1371                  *
1372                  * XXX It may be desirable to instead check if the dynamic
1373                  * parking lot overlaps any existing lots like what is done for
1374                  * a reload.
1375                  */
1376                 if (!strcmp(parkinglot->cfg.parking_con, template_parkinglot->cfg.parking_con)) {
1377                         if (!strcmp(parkinglot->cfg.parkext, template_parkinglot->cfg.parkext)
1378                                 && parkinglot->cfg.parkext_exclusive) {
1379                                 ast_log(LOG_WARNING,
1380                                         "Parking lot '%s' conflicts with template parking lot '%s'!\n"
1381                                         "Change either PARKINGDYNCONTEXT or PARKINGDYNEXTEN.\n",
1382                                         parkinglot->name, template_parkinglot->name);
1383                         }
1384                         if ((template_parkinglot->cfg.parking_start <= parkinglot->cfg.parking_start
1385                                         && parkinglot->cfg.parking_start <= template_parkinglot->cfg.parking_stop)
1386                                 || (template_parkinglot->cfg.parking_start <= parkinglot->cfg.parking_stop
1387                                         && parkinglot->cfg.parking_stop <= template_parkinglot->cfg.parking_stop)
1388                                 || (parkinglot->cfg.parking_start < template_parkinglot->cfg.parking_start
1389                                         && template_parkinglot->cfg.parking_stop < parkinglot->cfg.parking_stop)) {
1390                                 ast_log(LOG_WARNING,
1391                                         "Parking lot '%s' parking spaces overlap template parking lot '%s'!\n"
1392                                         "Change PARKINGDYNPOS.\n",
1393                                         parkinglot->name, template_parkinglot->name);
1394                         }
1395                 }
1396
1397                 parkinglot_activate(parkinglot);
1398                 ao2_link(parkinglots, parkinglot);
1399         }
1400         parkinglot_unref(template_parkinglot);
1401
1402         return parkinglot;
1403 }
1404
1405 /*!
1406  * \internal
1407  * \brief Abort parking a call that has not completed parking yet.
1408  *
1409  * \param pu Parked user item to clean up.
1410  *
1411  * \note The parking lot parkings list is locked on entry.
1412  *
1413  * \return Nothing
1414  */
1415 static void park_space_abort(struct parkeduser *pu)
1416 {
1417         struct ast_parkinglot *parkinglot;
1418
1419         parkinglot = pu->parkinglot;
1420
1421         /* Put back the parking space just allocated. */
1422         --parkinglot->next_parking_space;
1423
1424         AST_LIST_REMOVE(&parkinglot->parkings, pu, list);
1425
1426         AST_LIST_UNLOCK(&parkinglot->parkings);
1427         parkinglot_unref(parkinglot);
1428         ast_free(pu);
1429 }
1430
1431 /*!
1432  * \internal
1433  * \brief Reserve a parking space in a parking lot for a call being parked.
1434  *
1435  * \param park_me Channel being parked.
1436  * \param parker Channel parking the call.
1437  * \param args Optional additional parking options when parking a call.
1438  *
1439  * \return Parked call descriptor or NULL if failed.
1440  * \note The parking lot list is locked if successful.
1441  */
1442 static struct parkeduser *park_space_reserve(struct ast_channel *park_me, struct ast_channel *parker, struct ast_park_call_args *args)
1443 {
1444         struct parkeduser *pu;
1445         int i;
1446         int parking_space = -1;
1447         const char *parkinglotname;
1448         const char *parkingexten;
1449         struct parkeduser *cur;
1450         struct ast_parkinglot *parkinglot = NULL;
1451
1452         if (args->parkinglot) {
1453                 parkinglot = parkinglot_addref(args->parkinglot);
1454                 parkinglotname = parkinglot->name;
1455         } else {
1456                 if (parker) {
1457                         parkinglotname = findparkinglotname(parker);
1458                 } else { /* parker was NULL, check park_me (ParkAndAnnounce / res_agi) */
1459                         parkinglotname = findparkinglotname(park_me);
1460                 }
1461                 if (!ast_strlen_zero(parkinglotname)) {
1462                         parkinglot = find_parkinglot(parkinglotname);
1463                 } else {
1464                         /* Parking lot is not specified, so use the default parking lot. */
1465                         ast_debug(4, "This could be an indication channel driver needs updating, using default lot.\n");
1466                         parkinglot = parkinglot_addref(default_parkinglot);
1467                 }
1468         }
1469
1470         /* Dynamically create parkinglot */
1471         if (!parkinglot && parkeddynamic && !ast_strlen_zero(parkinglotname)) {
1472                 parkinglot = create_dynamic_parkinglot(parkinglotname, park_me);
1473         }
1474
1475         if (!parkinglot) {
1476                 ast_log(LOG_WARNING, "Parking lot not available to park %s.\n", ast_channel_name(park_me));
1477                 return NULL;
1478         }
1479
1480         ast_debug(1, "Parking lot: %s\n", parkinglot->name);
1481         if (parkinglot->disabled || parkinglot->cfg.is_invalid) {
1482                 ast_log(LOG_WARNING, "Parking lot %s is not in a useable state.\n",
1483                         parkinglot->name);
1484                 parkinglot_unref(parkinglot);
1485                 return NULL;
1486         }
1487
1488         /* Allocate memory for parking data */
1489         if (!(pu = ast_calloc(1, sizeof(*pu)))) {
1490                 parkinglot_unref(parkinglot);
1491                 return NULL;
1492         }
1493
1494         /* Lock parking list */
1495         AST_LIST_LOCK(&parkinglot->parkings);
1496
1497         /* Check for channel variable PARKINGEXTEN */
1498         parkingexten = ast_strdupa(S_OR(pbx_builtin_getvar_helper(park_me, "PARKINGEXTEN"), ""));
1499         if (!ast_strlen_zero(parkingexten)) {
1500                 /*!
1501                  * \note The API forces us to specify a numeric parking slot, even
1502                  * though the architecture would tend to support non-numeric extensions
1503                  * (as are possible with SIP, for example).  Hence, we enforce that
1504                  * limitation here.  If extout was not numeric, we could permit
1505                  * arbitrary non-numeric extensions.
1506                  */
1507                 if (sscanf(parkingexten, "%30d", &parking_space) != 1 || parking_space <= 0) {
1508                         ast_log(LOG_WARNING, "PARKINGEXTEN='%s' is not a valid parking space.\n",
1509                                 parkingexten);
1510                         AST_LIST_UNLOCK(&parkinglot->parkings);
1511                         parkinglot_unref(parkinglot);
1512                         ast_free(pu);
1513                         return NULL;
1514                 }
1515
1516                 if (parking_space < parkinglot->cfg.parking_start
1517                         || parkinglot->cfg.parking_stop < parking_space) {
1518                         /*
1519                          * Cannot allow park because parking lots are not setup for
1520                          * spaces outside of the lot.  (Things like dialplan hints don't
1521                          * exist for outside lot space.)
1522                          */
1523                         ast_log(LOG_WARNING, "PARKINGEXTEN=%d is not in %s (%d-%d).\n",
1524                                 parking_space, parkinglot->name, parkinglot->cfg.parking_start,
1525                                 parkinglot->cfg.parking_stop);
1526                         AST_LIST_UNLOCK(&parkinglot->parkings);
1527                         parkinglot_unref(parkinglot);
1528                         ast_free(pu);
1529                         return NULL;
1530                 }
1531
1532                 /* Check if requested parking space is in use. */
1533                 AST_LIST_TRAVERSE(&parkinglot->parkings, cur, list) {
1534                         if (cur->parkingnum == parking_space) {
1535                                 ast_log(LOG_WARNING, "PARKINGEXTEN=%d is already in use in %s\n",
1536                                         parking_space, parkinglot->name);
1537                                 AST_LIST_UNLOCK(&parkinglot->parkings);
1538                                 parkinglot_unref(parkinglot);
1539                                 ast_free(pu);
1540                                 return NULL;
1541                         }
1542                 }
1543         } else {
1544                 /* PARKINGEXTEN is empty, so find a usable extension in the lot to park the call */
1545                 int start; /* The first slot we look in the parkinglot. It can be randomized. */
1546                 int start_checked = 0; /* flag raised once the first slot is checked */
1547
1548                 /* If using randomize mode, set start to random position on parking range */
1549                 if (ast_test_flag(args, AST_PARK_OPT_RANDOMIZE)) {
1550                         start = ast_random() % (parkinglot->cfg.parking_stop - parkinglot->cfg.parking_start + 1);
1551                         start += parkinglot->cfg.parking_start;
1552                 } else if (parkinglot->cfg.parkfindnext
1553                         && parkinglot->cfg.parking_start <= parkinglot->next_parking_space
1554                         && parkinglot->next_parking_space <= parkinglot->cfg.parking_stop) {
1555                         /* Start looking with the next parking space in the lot. */
1556                         start = parkinglot->next_parking_space;
1557                 } else {
1558                         /* Otherwise, just set it to the start position. */
1559                         start = parkinglot->cfg.parking_start;
1560                 }
1561
1562                 /* free parking extension linear search: O(n^2) */
1563                 for (i = start; ; i++) {
1564                         /* If we are past the end, wrap around to the first parking slot*/
1565                         if (i == parkinglot->cfg.parking_stop + 1) {
1566                                 i = parkinglot->cfg.parking_start;
1567                         }
1568
1569                         if (i == start) {
1570                                 /* At this point, if start_checked, we've exhausted all the possible slots. */
1571                                 if (start_checked) {
1572                                         break;
1573                                 } else {
1574                                         start_checked = 1;
1575                                 }
1576                         }
1577
1578                         /* Search the list of parked calls already in use for i. If we find it, it's in use. */
1579                         AST_LIST_TRAVERSE(&parkinglot->parkings, cur, list) {
1580                                 if (cur->parkingnum == i) {
1581                                         break;
1582                                 }
1583                         }
1584                         if (!cur) {
1585                                 /* We found a parking space. */
1586                                 parking_space = i;
1587                                 break;
1588                         }
1589                 }
1590                 if (parking_space == -1) {
1591                         /* We did not find a parking space.  Lot is full. */
1592                         ast_log(LOG_WARNING, "No more parking spaces in %s\n", parkinglot->name);
1593                         AST_LIST_UNLOCK(&parkinglot->parkings);
1594                         parkinglot_unref(parkinglot);
1595                         ast_free(pu);
1596                         return NULL;
1597                 }
1598         }
1599
1600         /* Prepare for next parking space search. */
1601         parkinglot->next_parking_space = parking_space + 1;
1602
1603         snprintf(pu->parkingexten, sizeof(pu->parkingexten), "%d", parking_space);
1604         pu->notquiteyet = 1;
1605         pu->parkingnum = parking_space;
1606         pu->parkinglot = parkinglot;
1607         AST_LIST_INSERT_TAIL(&parkinglot->parkings, pu, list);
1608
1609         return pu;
1610 }
1611
1612 static unsigned int get_parkingtime(struct ast_channel *chan, struct ast_parkinglot *parkinglot);
1613
1614 /* Park a call */
1615 static int park_call_full(struct ast_channel *chan, struct ast_channel *peer, struct ast_park_call_args *args)
1616 {
1617         struct parkeduser *pu = args->pu;
1618         const char *event_from;         /*!< Channel name that is parking the call. */
1619         char app_data[AST_MAX_EXTENSION + AST_MAX_CONTEXT];
1620
1621         if (pu == NULL) {
1622                 args->pu = pu = park_space_reserve(chan, peer, args);
1623                 if (pu == NULL) {
1624                         return -1;
1625                 }
1626         }
1627
1628         ast_channel_appl_set(chan, "Parked Call");
1629         ast_channel_data_set(chan, NULL);
1630
1631         pu->chan = chan;
1632
1633         /* Put the parked channel on hold if we have two different channels */
1634         if (chan != peer) {
1635                 if (ast_test_flag(args, AST_PARK_OPT_RINGING)) {
1636                         pu->hold_method = AST_CONTROL_RINGING;
1637                         ast_indicate(chan, AST_CONTROL_RINGING);
1638                 } else {
1639                         pu->hold_method = AST_CONTROL_HOLD;
1640                         ast_indicate_data(chan, AST_CONTROL_HOLD,
1641                                 S_OR(pu->parkinglot->cfg.mohclass, NULL),
1642                                 !ast_strlen_zero(pu->parkinglot->cfg.mohclass) ? strlen(pu->parkinglot->cfg.mohclass) + 1 : 0);
1643                 }
1644         }
1645
1646         pu->start = ast_tvnow();
1647         pu->parkingtime = (args->timeout > 0) ? args->timeout : get_parkingtime(chan, pu->parkinglot);
1648         if (args->extout)
1649                 *(args->extout) = pu->parkingnum;
1650
1651         if (peer) {
1652                 event_from = S_OR(args->orig_chan_name, ast_channel_name(peer));
1653
1654                 /*
1655                  * This is so ugly that it hurts, but implementing
1656                  * get_base_channel() on local channels could have ugly side
1657                  * effects.  We could have
1658                  * transferer<->local;1<->local;2<->parking and we need the
1659                  * callback name to be that of transferer.  Since local;1/2 have
1660                  * the same name we can be tricky and just grab the bridged
1661                  * channel from the other side of the local.
1662                  */
1663                 if (!strcasecmp(ast_channel_tech(peer)->type, "Local")) {
1664                         struct ast_channel *tmpchan, *base_peer;
1665                         char other_side[AST_CHANNEL_NAME];
1666                         char *c;
1667
1668                         ast_copy_string(other_side, event_from, sizeof(other_side));
1669                         if ((c = strrchr(other_side, ';'))) {
1670                                 *++c = '1';
1671                         }
1672                         if ((tmpchan = ast_channel_get_by_name(other_side))) {
1673                                 ast_channel_lock(tmpchan);
1674                                 if ((base_peer = ast_bridged_channel(tmpchan))) {
1675                                         ast_copy_string(pu->peername, ast_channel_name(base_peer), sizeof(pu->peername));
1676                                 }
1677                                 ast_channel_unlock(tmpchan);
1678                                 tmpchan = ast_channel_unref(tmpchan);
1679                         }
1680                 } else {
1681                         ast_copy_string(pu->peername, event_from, sizeof(pu->peername));
1682                 }
1683         } else {
1684                 event_from = S_OR(pbx_builtin_getvar_helper(chan, "BLINDTRANSFER"),
1685                         ast_channel_name(chan));
1686         }
1687
1688         /*
1689          * Remember what had been dialed, so that if the parking
1690          * expires, we try to come back to the same place
1691          */
1692         pu->options_specified = (!ast_strlen_zero(args->return_con) || !ast_strlen_zero(args->return_ext) || args->return_pri);
1693
1694         /*
1695          * If extension has options specified, they override all other
1696          * possibilities such as the returntoorigin flag and transferred
1697          * context.  Information on extension options is lost here, so
1698          * we set a flag
1699          */
1700         ast_copy_string(pu->context,
1701                 S_OR(args->return_con, S_OR(ast_channel_macrocontext(chan), ast_channel_context(chan))),
1702                 sizeof(pu->context));
1703         ast_copy_string(pu->exten,
1704                 S_OR(args->return_ext, S_OR(ast_channel_macroexten(chan), ast_channel_exten(chan))),
1705                 sizeof(pu->exten));
1706         pu->priority = args->return_pri ? args->return_pri :
1707                 (ast_channel_macropriority(chan) ? ast_channel_macropriority(chan) : ast_channel_priority(chan));
1708
1709         /*
1710          * If parking a channel directly, don't quite yet get parking
1711          * running on it.  All parking lot entries are put into the
1712          * parking lot with notquiteyet on.
1713          */
1714         if (peer != chan) {
1715                 pu->notquiteyet = 0;
1716         }
1717
1718         /* Wake up the (presumably select()ing) thread */
1719         pthread_kill(parking_thread, SIGURG);
1720         ast_verb(2, "Parked %s on %d (lot %s). Will timeout back to extension [%s] %s, %d in %u seconds\n",
1721                 ast_channel_name(chan), pu->parkingnum, pu->parkinglot->name,
1722                 pu->context, pu->exten, pu->priority, (pu->parkingtime / 1000));
1723
1724         ast_cel_report_event(chan, AST_CEL_PARK_START, NULL, pu->parkinglot->name, peer);
1725         /*** DOCUMENTATION
1726                 <managerEventInstance>
1727                         <synopsis>Raised when a call has been parked.</synopsis>
1728                         <syntax>
1729                                 <parameter name="Exten">
1730                                         <para>The parking lot extension.</para>
1731                                 </parameter>
1732                                 <parameter name="Parkinglot">
1733                                         <para>The name of the parking lot.</para>
1734                                 </parameter>
1735                                 <parameter name="From">
1736                                         <para>The name of the channel that parked the call.</para>
1737                                 </parameter>
1738                         </syntax>
1739                         <see-also>
1740                                 <ref type="application">Park</ref>
1741                                 <ref type="manager">Park</ref>
1742                                 <ref type="managerEvent">ParkedCallTimeOut</ref>
1743                                 <ref type="managerEvent">ParkedCallGiveUp</ref>
1744                         </see-also>
1745                 </managerEventInstance>
1746         ***/
1747         ast_manager_event(chan, EVENT_FLAG_CALL, "ParkedCall",
1748                 "Exten: %s\r\n"
1749                 "Channel: %s\r\n"
1750                 "Parkinglot: %s\r\n"
1751                 "From: %s\r\n"
1752                 "Timeout: %ld\r\n"
1753                 "CallerIDNum: %s\r\n"
1754                 "CallerIDName: %s\r\n"
1755                 "ConnectedLineNum: %s\r\n"
1756                 "ConnectedLineName: %s\r\n"
1757                 "Uniqueid: %s\r\n",
1758                 pu->parkingexten, ast_channel_name(chan), pu->parkinglot->name, event_from,
1759                 (long)pu->start.tv_sec + (long)(pu->parkingtime/1000) - (long)time(NULL),
1760                 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, "<unknown>"),
1761                 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, "<unknown>"),
1762                 S_COR(ast_channel_connected(chan)->id.number.valid, ast_channel_connected(chan)->id.number.str, "<unknown>"),
1763                 S_COR(ast_channel_connected(chan)->id.name.valid, ast_channel_connected(chan)->id.name.str, "<unknown>"),
1764                 ast_channel_uniqueid(chan)
1765                 );
1766         ast_debug(4, "peer: %s\n", peer ? ast_channel_name(peer) : "-No peer-");
1767         ast_debug(4, "args->orig_chan_name: %s\n", args->orig_chan_name ? args->orig_chan_name : "-none-");
1768         ast_debug(4, "pu->peername: %s\n", pu->peername);
1769         ast_debug(4, "AMI ParkedCall Channel: %s\n", ast_channel_name(chan));
1770         ast_debug(4, "AMI ParkedCall From: %s\n", event_from);
1771
1772         if (peer && adsipark && ast_adsi_available(peer)) {
1773                 adsi_announce_park(peer, pu->parkingexten);     /* Only supports parking numbers */
1774                 ast_adsi_unload_session(peer);
1775         }
1776
1777         snprintf(app_data, sizeof(app_data), "%s,%s", pu->parkingexten,
1778                 pu->parkinglot->name);
1779         if (ast_add_extension(pu->parkinglot->cfg.parking_con, 1, pu->parkingexten, 1,
1780                 NULL, NULL, parkedcall, ast_strdup(app_data), ast_free_ptr, registrar)) {
1781                 ast_log(LOG_ERROR, "Could not create parked call exten: %s@%s\n",
1782                         pu->parkingexten, pu->parkinglot->cfg.parking_con);
1783         } else {
1784                 notify_metermaids(pu->parkingexten, pu->parkinglot->cfg.parking_con, AST_DEVICE_INUSE);
1785         }
1786
1787         AST_LIST_UNLOCK(&pu->parkinglot->parkings);
1788
1789         /* Only say number if it's a number and the channel hasn't been masqueraded away */
1790         if (peer && !ast_test_flag(args, AST_PARK_OPT_SILENCE)
1791                 && (ast_strlen_zero(args->orig_chan_name) || !strcasecmp(ast_channel_name(peer), args->orig_chan_name))) {
1792                 /*
1793                  * If a channel is masqueraded into peer while playing back the
1794                  * parking space number do not continue playing it back.  This
1795                  * is the case if an attended transfer occurs.
1796                  */
1797                 ast_set_flag(ast_channel_flags(peer), AST_FLAG_MASQ_NOSTREAM);
1798                 /* Tell the peer channel the number of the parking space */
1799                 ast_say_digits(peer, pu->parkingnum, "", ast_channel_language(peer));
1800                 ast_clear_flag(ast_channel_flags(peer), AST_FLAG_MASQ_NOSTREAM);
1801         }
1802         if (peer == chan) { /* pu->notquiteyet = 1 */
1803                 /* Wake up parking thread if we're really done */
1804                 if (ast_test_flag(args, AST_PARK_OPT_RINGING)) {
1805                         pu->hold_method = AST_CONTROL_RINGING;
1806                         ast_indicate(chan, AST_CONTROL_RINGING);
1807                 } else {
1808                         pu->hold_method = AST_CONTROL_HOLD;
1809                         ast_indicate_data(chan, AST_CONTROL_HOLD,
1810                                 S_OR(pu->parkinglot->cfg.mohclass, NULL),
1811                                 !ast_strlen_zero(pu->parkinglot->cfg.mohclass) ? strlen(pu->parkinglot->cfg.mohclass) + 1 : 0);
1812                 }
1813                 pu->notquiteyet = 0;
1814                 pthread_kill(parking_thread, SIGURG);
1815         }
1816         return 0;
1817 }
1818
1819 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)
1820 {
1821         int res;
1822         char *parse;
1823         const char *app_data;
1824         struct ast_exten *exten;
1825         struct park_app_args app_args;
1826         struct ast_park_call_args args = {
1827                 .timeout = timeout,
1828                 .extout = extout,
1829         };
1830
1831         if (!park_exten || !park_context) {
1832                 return park_call_full(park_me, parker, &args);
1833         }
1834
1835         /*
1836          * Determiine if the specified park extension has an exclusive
1837          * parking lot to use.
1838          */
1839         if (parker && parker != park_me) {
1840                 ast_autoservice_start(park_me);
1841         }
1842         exten = get_parking_exten(park_exten, parker, park_context);
1843         if (exten) {
1844                 app_data = ast_get_extension_app_data(exten);
1845                 if (!app_data) {
1846                         app_data = "";
1847                 }
1848                 parse = ast_strdupa(app_data);
1849                 AST_STANDARD_APP_ARGS(app_args, parse);
1850
1851                 if (!ast_strlen_zero(app_args.pl_name)) {
1852                         /* Find the specified exclusive parking lot */
1853                         args.parkinglot = find_parkinglot(app_args.pl_name);
1854                         if (!args.parkinglot && parkeddynamic) {
1855                                 args.parkinglot = create_dynamic_parkinglot(app_args.pl_name, park_me);
1856                         }
1857                 }
1858         }
1859         if (parker && parker != park_me) {
1860                 ast_autoservice_stop(park_me);
1861         }
1862
1863         res = park_call_full(park_me, parker, &args);
1864         if (args.parkinglot) {
1865                 parkinglot_unref(args.parkinglot);
1866         }
1867         return res;
1868 }
1869
1870 int ast_park_call(struct ast_channel *park_me, struct ast_channel *parker, int timeout, const char *park_exten, int *extout)
1871 {
1872         struct ast_park_call_args args = {
1873                 .timeout = timeout,
1874                 .extout = extout,
1875         };
1876
1877         return park_call_full(park_me, parker, &args);
1878 }
1879
1880 /*!
1881  * \brief Park call via masqueraded channel and announce parking spot on peer channel.
1882  *
1883  * \param rchan the real channel to be parked
1884  * \param peer the channel to have the parking read to.
1885  * \param args Additional parking options when parking a call.
1886  *
1887  * \retval 0 on success.
1888  * \retval -1 on failure.
1889  */
1890 static int masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, struct ast_park_call_args *args)
1891 {
1892         struct ast_channel *chan;
1893
1894         /* Make a new, channel that we'll use to masquerade in the real one */
1895         chan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, ast_channel_accountcode(rchan), ast_channel_exten(rchan),
1896                 ast_channel_context(rchan), ast_channel_linkedid(rchan), ast_channel_amaflags(rchan), "Parked/%s", ast_channel_name(rchan));
1897         if (!chan) {
1898                 ast_log(LOG_WARNING, "Unable to create parked channel\n");
1899                 if (!ast_test_flag(args, AST_PARK_OPT_SILENCE)) {
1900                         if (peer == rchan) {
1901                                 /* Only have one channel to worry about. */
1902                                 ast_stream_and_wait(peer, "pbx-parkingfailed", "");
1903                         } else if (peer) {
1904                                 /* Have two different channels to worry about. */
1905                                 play_message_on_chan(peer, rchan, "failure message", "pbx-parkingfailed");
1906                         }
1907                 }
1908                 return -1;
1909         }
1910
1911         args->pu = park_space_reserve(rchan, peer, args);
1912         if (!args->pu) {
1913                 ast_hangup(chan);
1914                 if (!ast_test_flag(args, AST_PARK_OPT_SILENCE)) {
1915                         if (peer == rchan) {
1916                                 /* Only have one channel to worry about. */
1917                                 ast_stream_and_wait(peer, "pbx-parkingfailed", "");
1918                         } else if (peer) {
1919                                 /* Have two different channels to worry about. */
1920                                 play_message_on_chan(peer, rchan, "failure message", "pbx-parkingfailed");
1921                         }
1922                 }
1923                 return -1;
1924         }
1925
1926         /* Make formats okay */
1927         ast_format_copy(ast_channel_readformat(chan), ast_channel_readformat(rchan));
1928         ast_format_copy(ast_channel_writeformat(chan), ast_channel_writeformat(rchan));
1929
1930         if (ast_channel_masquerade(chan, rchan)) {
1931                 park_space_abort(args->pu);
1932                 args->pu = NULL;
1933                 ast_hangup(chan);
1934                 if (!ast_test_flag(args, AST_PARK_OPT_SILENCE)) {
1935                         if (peer == rchan) {
1936                                 /* Only have one channel to worry about. */
1937                                 ast_stream_and_wait(peer, "pbx-parkingfailed", "");
1938                         } else if (peer) {
1939                                 /* Have two different channels to worry about. */
1940                                 play_message_on_chan(peer, rchan, "failure message", "pbx-parkingfailed");
1941                         }
1942                 }
1943                 return -1;
1944         }
1945
1946         /* Setup the extensions and such */
1947         set_c_e_p(chan, ast_channel_context(rchan), ast_channel_exten(rchan), ast_channel_priority(rchan));
1948
1949         /* Setup the macro extension and such */
1950         ast_channel_macrocontext_set(chan, ast_channel_macrocontext(rchan));
1951         ast_channel_macroexten_set(chan, ast_channel_macroexten(rchan));
1952         ast_channel_macropriority_set(chan, ast_channel_macropriority(rchan));
1953
1954         /* Manually do the masquerade to make sure it is complete. */
1955         ast_do_masquerade(chan);
1956
1957         if (peer == rchan) {
1958                 peer = chan;
1959         }
1960
1961         /* parking space reserved, return code check unnecessary */
1962         park_call_full(chan, peer, args);
1963
1964         return 0;
1965 }
1966
1967 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)
1968 {
1969         int res;
1970         char *parse;
1971         const char *app_data;
1972         struct ast_exten *exten;
1973         struct park_app_args app_args;
1974         struct ast_park_call_args args = {
1975                 .timeout = timeout,
1976                 .extout = extout,
1977         };
1978
1979         if (parker) {
1980                 args.orig_chan_name = ast_strdupa(ast_channel_name(parker));
1981         }
1982         if (!park_exten || !park_context) {
1983                 return masq_park_call(park_me, parker, &args);
1984         }
1985
1986         /*
1987          * Determiine if the specified park extension has an exclusive
1988          * parking lot to use.
1989          */
1990         if (parker && parker != park_me) {
1991                 ast_autoservice_start(park_me);
1992         }
1993         exten = get_parking_exten(park_exten, parker, park_context);
1994         if (exten) {
1995                 app_data = ast_get_extension_app_data(exten);
1996                 if (!app_data) {
1997                         app_data = "";
1998                 }
1999                 parse = ast_strdupa(app_data);
2000                 AST_STANDARD_APP_ARGS(app_args, parse);
2001
2002                 if (!ast_strlen_zero(app_args.pl_name)) {
2003                         /* Find the specified exclusive parking lot */
2004                         args.parkinglot = find_parkinglot(app_args.pl_name);
2005                         if (!args.parkinglot && parkeddynamic) {
2006                                 args.parkinglot = create_dynamic_parkinglot(app_args.pl_name, park_me);
2007                         }
2008                 }
2009         }
2010         if (parker && parker != park_me) {
2011                 ast_autoservice_stop(park_me);
2012         }
2013
2014         res = masq_park_call(park_me, parker, &args);
2015         if (args.parkinglot) {
2016                 parkinglot_unref(args.parkinglot);
2017         }
2018         return res;
2019 }
2020
2021 int ast_masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, int timeout, int *extout)
2022 {
2023         struct ast_park_call_args args = {
2024                 .timeout = timeout,
2025                 .extout = extout,
2026         };
2027
2028         if (peer) {
2029                 args.orig_chan_name = ast_strdupa(ast_channel_name(peer));
2030         }
2031         return masq_park_call(rchan, peer, &args);
2032 }
2033
2034 static int finishup(struct ast_channel *chan)
2035 {
2036         ast_indicate(chan, AST_CONTROL_UNHOLD);
2037
2038         return ast_autoservice_stop(chan);
2039 }
2040
2041 /*!
2042  * \internal
2043  * \brief Builtin transfer park call helper.
2044  *
2045  * \param park_me Channel to be parked.
2046  * \param parker Channel parking the call.
2047  * \param park_exten Parking lot dialplan access ramp extension.
2048  *
2049  * \note Assumes park_me is on hold and in autoservice.
2050  *
2051  * \retval -1 on successful park.
2052  * \retval -1 on park_me hangup.
2053  * \retval AST_FEATURE_RETURN_SUCCESS on error to keep the bridge connected.
2054  */
2055 static int xfer_park_call_helper(struct ast_channel *park_me, struct ast_channel *parker, struct ast_exten *park_exten)
2056 {
2057         char *parse;
2058         const char *app_data;
2059         const char *pl_name;
2060         struct ast_park_call_args args = { 0, };
2061         struct park_app_args app_args;
2062         int res;
2063
2064         app_data = ast_get_extension_app_data(park_exten);
2065         if (!app_data) {
2066                 app_data = "";
2067         }
2068         parse = ast_strdupa(app_data);
2069         AST_STANDARD_APP_ARGS(app_args, parse);
2070
2071         /* Find the parking lot */
2072         if (!ast_strlen_zero(app_args.pl_name)) {
2073                 pl_name = app_args.pl_name;
2074         } else {
2075                 pl_name = findparkinglotname(parker);
2076         }
2077         if (ast_strlen_zero(pl_name)) {
2078                 /* Parking lot is not specified, so use the default parking lot. */
2079                 args.parkinglot = parkinglot_addref(default_parkinglot);
2080         } else {
2081                 args.parkinglot = find_parkinglot(pl_name);
2082                 if (!args.parkinglot && parkeddynamic) {
2083                         args.parkinglot = create_dynamic_parkinglot(pl_name, park_me);
2084                 }
2085         }
2086
2087         if (args.parkinglot) {
2088                 /* Park the call */
2089                 res = finishup(park_me);
2090                 if (res) {
2091                         /* park_me hungup on us. */
2092                         parkinglot_unref(args.parkinglot);
2093                         return -1;
2094                 }
2095                 res = masq_park_call(park_me, parker, &args);
2096                 parkinglot_unref(args.parkinglot);
2097         } else {
2098                 /* Parking failed because parking lot does not exist. */
2099                 if (!ast_test_flag(&args, AST_PARK_OPT_SILENCE)) {
2100                         ast_stream_and_wait(parker, "pbx-parkingfailed", "");
2101                 }
2102                 finishup(park_me);
2103                 res = -1;
2104         }
2105
2106         return res ? AST_FEATURE_RETURN_SUCCESS : -1;
2107 }
2108
2109 /*!
2110  * \brief set caller and callee according to the direction
2111  * \param caller, callee, peer, chan, sense
2112  *
2113  * Detect who triggered feature and set callee/caller variables accordingly
2114  */
2115 static void set_peers(struct ast_channel **caller, struct ast_channel **callee,
2116         struct ast_channel *peer, struct ast_channel *chan, int sense)
2117 {
2118         if (sense == FEATURE_SENSE_PEER) {
2119                 *caller = peer;
2120                 *callee = chan;
2121         } else {
2122                 *callee = peer;
2123                 *caller = chan;
2124         }
2125 }
2126
2127 /*!
2128  * \brief support routing for one touch call parking
2129  * \param chan channel parking call
2130  * \param peer channel to be parked
2131  * \param config unsed
2132  * \param code unused
2133  * \param sense feature options
2134  * \param data unused
2135  *
2136  * \retval -1 on successful park.
2137  * \retval -1 on chan hangup.
2138  * \retval AST_FEATURE_RETURN_SUCCESS on error to keep the bridge connected.
2139  */
2140 static int builtin_parkcall(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2141 {
2142         struct ast_channel *parker;
2143         struct ast_channel *parkee;
2144         struct ast_park_call_args args = { 0, };
2145
2146         /*
2147          * We used to set chan's exten and priority to "s" and 1 here,
2148          * but this generates (in some cases) an invalid extension, and
2149          * if "s" exists, could errantly cause execution of extensions
2150          * you don't expect.  It makes more sense to let nature take its
2151          * course when chan finishes, and let the pbx do its thing and
2152          * hang up when the park is over.
2153          */
2154
2155         /* Answer if call is not up */
2156         if (ast_channel_state(chan) != AST_STATE_UP) {
2157                 /*
2158                  * XXX Why are we doing this?  Both of the channels should be up
2159                  * since you cannot do DTMF features unless you are bridged.
2160                  */
2161                 if (ast_answer(chan)) {
2162                         return -1;
2163                 }
2164
2165                 /* Sleep to allow VoIP streams to settle down */
2166                 if (ast_safe_sleep(chan, 1000)) {
2167                         return -1;
2168                 }
2169         }
2170
2171         /* one direction used to call park_call.... */
2172         set_peers(&parker, &parkee, peer, chan, sense);
2173         return masq_park_call(parkee, parker, &args) ? AST_FEATURE_RETURN_SUCCESS : -1;
2174 }
2175
2176 /*!
2177  * \internal
2178  * \brief Play file to specified channel.
2179  *
2180  * \param play_to Channel to play audiofile to.
2181  * \param other Channel to put in autoservice while playing file.
2182  * \param msg Descriptive name of message type being played.
2183  * \param audiofile Audio file to play.
2184  *
2185  * \retval 0 on success.
2186  * \retval -1 on error. (Couldn't play file, a channel hung up,...)
2187  */
2188 static int play_message_on_chan(struct ast_channel *play_to, struct ast_channel *other, const char *msg, const char *audiofile)
2189 {
2190         /* Put other channel in autoservice. */
2191         if (ast_autoservice_start(other)) {
2192                 return -1;
2193         }
2194         ast_autoservice_ignore(other, AST_FRAME_DTMF_BEGIN);
2195         ast_autoservice_ignore(other, AST_FRAME_DTMF_END);
2196         if (ast_stream_and_wait(play_to, audiofile, "")) {
2197                 ast_log(LOG_WARNING, "Failed to play %s '%s'!\n", msg, audiofile);
2198                 ast_autoservice_stop(other);
2199                 return -1;
2200         }
2201         if (ast_autoservice_stop(other)) {
2202                 return -1;
2203         }
2204         return 0;
2205 }
2206
2207 /*!
2208  * \internal
2209  * \brief Play file to specified channels.
2210  *
2211  * \param left Channel on left to play file.
2212  * \param right Channel on right to play file.
2213  * \param which Play file on indicated channels: which < 0 play left, which == 0 play both, which > 0 play right
2214  * \param msg Descriptive name of message type being played.
2215  * \param audiofile Audio file to play to channels.
2216  *
2217  * \note Plays file to the indicated channels in turn so please
2218  * don't use this for very long messages.
2219  *
2220  * \retval 0 on success.
2221  * \retval -1 on error. (Couldn't play file, channel hung up,...)
2222  */
2223 static int play_message_to_chans(struct ast_channel *left, struct ast_channel *right, int which, const char *msg, const char *audiofile)
2224 {
2225         /* First play the file to the left channel if requested. */
2226         if (which <= 0 && play_message_on_chan(left, right, msg, audiofile)) {
2227                 return -1;
2228         }
2229
2230         /* Then play the file to the right channel if requested. */
2231         if (which >= 0 && play_message_on_chan(right, left, msg, audiofile)) {
2232                 return -1;
2233         }
2234
2235         return 0;
2236 }
2237
2238 /*!
2239  * \brief Play message to both caller and callee in bridged call, plays synchronously, autoservicing the
2240  * other channel during the message, so please don't use this for very long messages
2241  */
2242 static int play_message_in_bridged_call(struct ast_channel *caller_chan, struct ast_channel *callee_chan, const char *audiofile)
2243 {
2244         return play_message_to_chans(caller_chan, callee_chan, 0, "automon message",
2245                 audiofile);
2246 }
2247
2248 /*!
2249  * \brief Monitor a channel by DTMF
2250  * \param chan channel requesting monitor
2251  * \param peer channel to be monitored
2252  * \param config
2253  * \param code
2254  * \param sense feature options
2255  *
2256  * \param data
2257  * Check monitor app enabled, setup channels, both caller/callee chans not null
2258  * get TOUCH_MONITOR variable for filename if exists, exec monitor app.
2259  * \retval AST_FEATURE_RETURN_SUCCESS on success.
2260  * \retval -1 on error.
2261  */
2262 static int builtin_automonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2263 {
2264         char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
2265         int x = 0;
2266         size_t len;
2267         struct ast_channel *caller_chan, *callee_chan;
2268         const char *automon_message_start = NULL;
2269         const char *automon_message_stop = NULL;
2270         const char *touch_format = NULL;
2271         const char *touch_monitor = NULL;
2272         const char *touch_monitor_prefix = NULL;
2273         struct ast_app *monitor_app;
2274
2275         monitor_app = pbx_findapp("Monitor");
2276         if (!monitor_app) {
2277                 ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
2278                 return -1;
2279         }
2280
2281         set_peers(&caller_chan, &callee_chan, peer, chan, sense);
2282
2283         /* Find extra messages */
2284         automon_message_start = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_START");
2285         automon_message_stop = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_STOP");
2286
2287         if (!ast_strlen_zero(courtesytone)) {   /* Play courtesy tone if configured */
2288                 if(play_message_in_bridged_call(caller_chan, callee_chan, courtesytone) == -1) {
2289                         return -1;
2290                 }
2291         }
2292
2293         if (ast_channel_monitor(callee_chan)) {
2294                 ast_verb(4, "User hit '%s' to stop recording call.\n", code);
2295                 if (!ast_strlen_zero(automon_message_stop)) {
2296                         play_message_in_bridged_call(caller_chan, callee_chan, automon_message_stop);
2297                 }
2298                 ast_channel_monitor(callee_chan)->stop(callee_chan, 1);
2299                 return AST_FEATURE_RETURN_SUCCESS;
2300         }
2301
2302         touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_FORMAT");
2303         touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR");
2304         touch_monitor_prefix = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_PREFIX");
2305
2306         if (!touch_format)
2307                 touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_FORMAT");
2308
2309         if (!touch_monitor)
2310                 touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR");
2311
2312         if (!touch_monitor_prefix)
2313                 touch_monitor_prefix = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_PREFIX");
2314
2315         if (touch_monitor) {
2316                 len = strlen(touch_monitor) + 50;
2317                 args = ast_alloca(len);
2318                 touch_filename = ast_alloca(len);
2319                 snprintf(touch_filename, len, "%s-%ld-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), touch_monitor);
2320                 snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
2321         } else {
2322                 caller_chan_id = ast_strdupa(S_COR(ast_channel_caller(caller_chan)->id.number.valid,
2323                         ast_channel_caller(caller_chan)->id.number.str, ast_channel_name(caller_chan)));
2324                 callee_chan_id = ast_strdupa(S_COR(ast_channel_caller(callee_chan)->id.number.valid,
2325                         ast_channel_caller(callee_chan)->id.number.str, ast_channel_name(callee_chan)));
2326                 len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
2327                 args = ast_alloca(len);
2328                 touch_filename = ast_alloca(len);
2329                 snprintf(touch_filename, len, "%s-%ld-%s-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), caller_chan_id, callee_chan_id);
2330                 snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
2331         }
2332
2333         for(x = 0; x < strlen(args); x++) {
2334                 if (args[x] == '/')
2335                         args[x] = '-';
2336         }
2337
2338         ast_verb(4, "User hit '%s' to record call. filename: %s\n", code, args);
2339
2340         pbx_exec(callee_chan, monitor_app, args);
2341         pbx_builtin_setvar_helper(callee_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
2342         pbx_builtin_setvar_helper(caller_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
2343
2344         if (!ast_strlen_zero(automon_message_start)) {  /* Play start message for both channels */
2345                 play_message_in_bridged_call(caller_chan, callee_chan, automon_message_start);
2346         }
2347
2348         return AST_FEATURE_RETURN_SUCCESS;
2349 }
2350
2351 static int builtin_automixmonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2352 {
2353         char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
2354         int x = 0;
2355         size_t len;
2356         struct ast_channel *caller_chan, *callee_chan;
2357         const char *mixmonitor_spy_type = "MixMonitor";
2358         const char *touch_format;
2359         const char *touch_monitor;
2360         struct ast_app *mixmonitor_app;
2361         int count = 0;
2362
2363         mixmonitor_app = pbx_findapp("MixMonitor");
2364         if (!mixmonitor_app) {
2365                 ast_log(LOG_ERROR,"Cannot record the call. The mixmonitor application is disabled.\n");
2366                 return -1;
2367         }
2368
2369         set_peers(&caller_chan, &callee_chan, peer, chan, sense);
2370
2371         if (!ast_strlen_zero(courtesytone)) {
2372                 if (ast_autoservice_start(callee_chan))
2373                         return -1;
2374                 ast_autoservice_ignore(callee_chan, AST_FRAME_DTMF_END);
2375                 if (ast_stream_and_wait(caller_chan, courtesytone, "")) {
2376                         ast_log(LOG_WARNING, "Failed to play courtesy tone!\n");
2377                         ast_autoservice_stop(callee_chan);
2378                         return -1;
2379                 }
2380                 if (ast_autoservice_stop(callee_chan))
2381                         return -1;
2382         }
2383
2384         ast_channel_lock(callee_chan);
2385         count = ast_channel_audiohook_count_by_source(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
2386         ast_channel_unlock(callee_chan);
2387
2388         /* This means a mixmonitor is attached to the channel, running or not is unknown. */
2389         if (count > 0) {
2390                 ast_verb(3, "User hit '%s' to stop recording call.\n", code);
2391
2392                 /* Make sure they are running */
2393                 ast_channel_lock(callee_chan);
2394                 count = ast_channel_audiohook_count_by_source_running(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
2395                 ast_channel_unlock(callee_chan);
2396                 if (count > 0) {
2397                         struct ast_app *stopmixmonitor_app;
2398
2399                         stopmixmonitor_app = pbx_findapp("StopMixMonitor");
2400                         if (!stopmixmonitor_app) {
2401                                 ast_log(LOG_ERROR,"Cannot stop recording the call. The stopmixmonitor application is disabled.\n");
2402                                 return -1;
2403                         }
2404                         pbx_exec(callee_chan, stopmixmonitor_app, "");
2405                         return AST_FEATURE_RETURN_SUCCESS;
2406                 }
2407
2408                 ast_log(LOG_WARNING,"Stopped MixMonitors are attached to the channel.\n");
2409         }
2410
2411         touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR_FORMAT");
2412         touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR");
2413
2414         if (!touch_format)
2415                 touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR_FORMAT");
2416
2417         if (!touch_monitor)
2418                 touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR");
2419
2420         if (touch_monitor) {
2421                 len = strlen(touch_monitor) + 50;
2422                 args = ast_alloca(len);
2423                 touch_filename = ast_alloca(len);
2424                 snprintf(touch_filename, len, "auto-%ld-%s", (long)time(NULL), touch_monitor);
2425                 snprintf(args, len, "%s.%s,b", touch_filename, (touch_format) ? touch_format : "wav");
2426         } else {
2427                 caller_chan_id = ast_strdupa(S_COR(ast_channel_caller(caller_chan)->id.number.valid,
2428                         ast_channel_caller(caller_chan)->id.number.str, ast_channel_name(caller_chan)));
2429                 callee_chan_id = ast_strdupa(S_COR(ast_channel_caller(callee_chan)->id.number.valid,
2430                         ast_channel_caller(callee_chan)->id.number.str, ast_channel_name(callee_chan)));
2431                 len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
2432                 args = ast_alloca(len);
2433                 touch_filename = ast_alloca(len);
2434                 snprintf(touch_filename, len, "auto-%ld-%s-%s", (long)time(NULL), caller_chan_id, callee_chan_id);
2435                 snprintf(args, len, "%s.%s,b", touch_filename, S_OR(touch_format, "wav"));
2436         }
2437
2438         for( x = 0; x < strlen(args); x++) {
2439                 if (args[x] == '/')
2440                         args[x] = '-';
2441         }
2442
2443         ast_verb(3, "User hit '%s' to record call. filename: %s\n", code, touch_filename);
2444
2445         pbx_exec(callee_chan, mixmonitor_app, args);
2446         pbx_builtin_setvar_helper(callee_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
2447         pbx_builtin_setvar_helper(caller_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
2448         return AST_FEATURE_RETURN_SUCCESS;
2449 }
2450
2451 static int builtin_disconnect(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2452 {
2453         ast_verb(4, "User hit '%s' to disconnect call.\n", code);
2454         return AST_FEATURE_RETURN_HANGUP;
2455 }
2456
2457 /*!
2458  * \brief Find the context for the transfer
2459  * \param transferer
2460  * \param transferee
2461  *
2462  * Grab the TRANSFER_CONTEXT, if fails try grabbing macrocontext.
2463  * \return a context string
2464  */
2465 static const char *real_ctx(struct ast_channel *transferer, struct ast_channel *transferee)
2466 {
2467         const char *s = pbx_builtin_getvar_helper(transferer, "TRANSFER_CONTEXT");
2468         if (ast_strlen_zero(s)) {
2469                 s = pbx_builtin_getvar_helper(transferee, "TRANSFER_CONTEXT");
2470         }
2471         if (ast_strlen_zero(s)) { /* Use the non-macro context to transfer the call XXX ? */
2472                 s = ast_channel_macrocontext(transferer);
2473         }
2474         if (ast_strlen_zero(s)) {
2475                 s = ast_channel_context(transferer);
2476         }
2477         return s;
2478 }
2479
2480 /*!
2481  * \brief Blind transfer user to another extension
2482  * \param chan channel to be transfered
2483  * \param peer channel initiated blind transfer
2484  * \param config
2485  * \param code
2486  * \param data
2487  * \param sense  feature options
2488  *
2489  * Place chan on hold, check if transferred to parkinglot extension,
2490  * otherwise check extension exists and transfer caller.
2491  * \retval AST_FEATURE_RETURN_SUCCESS.
2492  * \retval -1 on failure.
2493  */
2494 static int builtin_blindtransfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2495 {
2496         struct ast_channel *transferer;
2497         struct ast_channel *transferee;
2498         struct ast_exten *park_exten;
2499         const char *transferer_real_context;
2500         char xferto[256] = "";
2501         int res;
2502
2503         ast_debug(1, "Executing Blind Transfer %s, %s (sense=%d) \n", ast_channel_name(chan), ast_channel_name(peer), sense);
2504         set_peers(&transferer, &transferee, peer, chan, sense);
2505         transferer_real_context = ast_strdupa(real_ctx(transferer, transferee));
2506
2507         /* Start autoservice on transferee while we talk to the transferer */
2508         ast_autoservice_start(transferee);
2509         ast_indicate(transferee, AST_CONTROL_HOLD);
2510
2511         /* Transfer */
2512         res = ast_stream_and_wait(transferer, "pbx-transfer", AST_DIGIT_ANY);
2513         if (res < 0) {
2514                 finishup(transferee);
2515                 return -1; /* error ? */
2516         }
2517         if (res > 0) { /* If they've typed a digit already, handle it */
2518                 xferto[0] = (char) res;
2519         }
2520
2521         res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
2522         if (res < 0) {  /* hangup or error, (would be 0 for invalid and 1 for valid) */
2523                 finishup(transferee);
2524                 return -1;
2525         }
2526         if (res == 0) {
2527                 if (xferto[0]) {
2528                         ast_log(LOG_WARNING, "Extension '%s' does not exist in context '%s'\n",
2529                                 xferto, transferer_real_context);
2530                 } else {
2531                         /* Does anyone care about this case? */
2532                         ast_log(LOG_WARNING, "No digits dialed.\n");
2533                 }
2534                 ast_stream_and_wait(transferer, "pbx-invalid", "");
2535                 finishup(transferee);
2536                 return AST_FEATURE_RETURN_SUCCESS;
2537         }
2538
2539         park_exten = get_parking_exten(xferto, transferer, transferer_real_context);
2540         if (park_exten) {
2541                 /* We are transfering the transferee to a parking lot. */
2542                 return xfer_park_call_helper(transferee, transferer, park_exten);
2543         }
2544
2545         /* Do blind transfer. */
2546         ast_verb(3, "Blind transferring %s to '%s' (context %s) priority 1\n",
2547                 ast_channel_name(transferee), xferto, transferer_real_context);
2548         ast_cel_report_event(transferer, AST_CEL_BLINDTRANSFER, NULL, xferto, transferee);
2549         pbx_builtin_setvar_helper(transferer, "BLINDTRANSFER", ast_channel_name(transferee));
2550         pbx_builtin_setvar_helper(transferee, "BLINDTRANSFER", ast_channel_name(transferer));
2551         finishup(transferee);
2552         ast_channel_lock(transferer);
2553         if (!ast_channel_cdr(transferer)) {
2554                 /* this code should never get called (in a perfect world) */
2555                 ast_channel_cdr_set(transferer, ast_cdr_alloc());
2556                 if (ast_channel_cdr(transferer)) {
2557                         ast_cdr_init(ast_channel_cdr(transferer), transferer); /* initialize our channel's cdr */
2558                         ast_cdr_start(ast_channel_cdr(transferer));
2559                 }
2560         }
2561         ast_channel_unlock(transferer);
2562         if (ast_channel_cdr(transferer)) {
2563                 struct ast_cdr *swap = ast_channel_cdr(transferer);
2564
2565                 ast_debug(1,
2566                         "transferer=%s; transferee=%s; lastapp=%s; lastdata=%s; chan=%s; dstchan=%s\n",
2567                         ast_channel_name(transferer), ast_channel_name(transferee), ast_channel_cdr(transferer)->lastapp,
2568                         ast_channel_cdr(transferer)->lastdata, ast_channel_cdr(transferer)->channel,
2569                         ast_channel_cdr(transferer)->dstchannel);
2570                 ast_debug(1, "TRANSFEREE; lastapp=%s; lastdata=%s, chan=%s; dstchan=%s\n",
2571                         ast_channel_cdr(transferee)->lastapp, ast_channel_cdr(transferee)->lastdata, ast_channel_cdr(transferee)->channel,
2572                         ast_channel_cdr(transferee)->dstchannel);
2573                 ast_debug(1, "transferer_real_context=%s; xferto=%s\n",
2574                         transferer_real_context, xferto);
2575                 /* swap cdrs-- it will save us some time & work */
2576                 ast_channel_cdr_set(transferer, ast_channel_cdr(transferee));
2577                 ast_channel_cdr_set(transferee, swap);
2578         }
2579
2580         res = ast_channel_pbx(transferee) ? AST_FEATURE_RETURN_SUCCESSBREAK : -1;
2581
2582         /* Doh!  Use our handy async_goto functions */
2583         if (ast_async_goto(transferee, transferer_real_context, xferto, 1)) {
2584                 ast_log(LOG_WARNING, "Async goto failed :-(\n");
2585                 res = -1;
2586         } else if (res == AST_FEATURE_RETURN_SUCCESSBREAK) {
2587                 /* Don't let the after-bridge code run the h-exten */
2588                 ast_channel_lock(transferee);
2589                 ast_set_flag(ast_channel_flags(transferee), AST_FLAG_BRIDGE_HANGUP_DONT);
2590                 ast_channel_unlock(transferee);
2591         }
2592         check_goto_on_transfer(transferer);
2593         return res;
2594 }
2595
2596 /*!
2597  * \brief make channels compatible
2598  * \param c
2599  * \param newchan
2600  * \retval 0 on success.
2601  * \retval -1 on failure.
2602  */
2603 static int check_compat(struct ast_channel *c, struct ast_channel *newchan)
2604 {
2605         if (ast_channel_make_compatible(c, newchan) < 0) {
2606                 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n",
2607                         ast_channel_name(c), ast_channel_name(newchan));
2608                 ast_autoservice_chan_hangup_peer(c, newchan);
2609                 return -1;
2610         }
2611         return 0;
2612 }
2613
2614 /*!
2615  * \internal
2616  * \brief Builtin attended transfer failed cleanup.
2617  * \since 10.0
2618  *
2619  * \param transferee Party A in the transfer.
2620  * \param transferer Party B in the transfer.
2621  * \param connected_line Saved connected line info about party A.
2622  *
2623  * \note The connected_line data is freed.
2624  *
2625  * \return Nothing
2626  */
2627 static void atxfer_fail_cleanup(struct ast_channel *transferee, struct ast_channel *transferer, struct ast_party_connected_line *connected_line)
2628 {
2629         finishup(transferee);
2630
2631         /*
2632          * Restore party B connected line info about party A.
2633          *
2634          * Party B was the caller to party C and is the last known mode
2635          * for party B.
2636          */
2637         if (ast_channel_connected_line_sub(transferee, transferer, connected_line, 0) &&
2638                 ast_channel_connected_line_macro(transferee, transferer, connected_line, 1, 0)) {
2639                 ast_channel_update_connected_line(transferer, connected_line, NULL);
2640         }
2641         ast_party_connected_line_free(connected_line);
2642 }
2643
2644 /*!
2645  * \brief Attended transfer
2646  * \param chan transfered user
2647  * \param peer person transfering call
2648  * \param config
2649  * \param code
2650  * \param sense feature options
2651  *
2652  * \param data
2653  * Get extension to transfer to, if you cannot generate channel (or find extension)
2654  * return to host channel. After called channel answered wait for hangup of transferer,
2655  * bridge call between transfer peer (taking them off hold) to attended transfer channel.
2656  *
2657  * \return -1 on failure
2658  */
2659 static int builtin_atxfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2660 {
2661         struct ast_channel *transferer;/* Party B */
2662         struct ast_channel *transferee;/* Party A */
2663         struct ast_exten *park_exten;
2664         const char *chan1_attended_sound;
2665         const char *chan2_attended_sound;
2666         const char *transferer_real_context;
2667         char xferto[256] = "";
2668         int res;
2669         int outstate=0;
2670         struct ast_channel *newchan;
2671         struct ast_channel *xferchan;
2672         struct ast_bridge_thread_obj *tobj;
2673         struct ast_bridge_config bconfig;
2674         int l;
2675         struct ast_party_connected_line connected_line;
2676         struct ast_datastore *features_datastore;
2677         struct ast_dial_features *dialfeatures;
2678         char *transferer_tech;
2679         char *transferer_name;
2680         char *transferer_name_orig;
2681         char *dash;
2682
2683         ast_debug(1, "Executing Attended Transfer %s, %s (sense=%d) \n", ast_channel_name(chan), ast_channel_name(peer), sense);
2684         set_peers(&transferer, &transferee, peer, chan, sense);
2685         transferer_real_context = real_ctx(transferer, transferee);
2686
2687         /* Start autoservice on transferee while we talk to the transferer */
2688         ast_autoservice_start(transferee);
2689         ast_indicate(transferee, AST_CONTROL_HOLD);
2690
2691         /* Transfer */
2692         res = ast_stream_and_wait(transferer, "pbx-transfer", AST_DIGIT_ANY);
2693         if (res < 0) {
2694                 finishup(transferee);
2695                 return -1;
2696         }
2697         if (res > 0) { /* If they've typed a digit already, handle it */
2698                 xferto[0] = (char) res;
2699         }
2700
2701         /* this is specific of atxfer */
2702         res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
2703         if (res < 0) {  /* hangup or error, (would be 0 for invalid and 1 for valid) */
2704                 finishup(transferee);
2705                 return -1;
2706         }
2707         l = strlen(xferto);
2708         if (res == 0) {
2709                 if (l) {
2710                         ast_log(LOG_WARNING, "Extension '%s' does not exist in context '%s'\n",
2711                                 xferto, transferer_real_context);
2712                 } else {
2713                         /* Does anyone care about this case? */
2714                         ast_log(LOG_WARNING, "No digits dialed for atxfer.\n");
2715                 }
2716                 ast_stream_and_wait(transferer, "pbx-invalid", "");
2717                 finishup(transferee);
2718                 return AST_FEATURE_RETURN_SUCCESS;
2719         }
2720
2721         park_exten = get_parking_exten(xferto, transferer, transferer_real_context);
2722         if (park_exten) {
2723                 /* We are transfering the transferee to a parking lot. */
2724                 return xfer_park_call_helper(transferee, transferer, park_exten);
2725         }
2726
2727         /*
2728          * Append context to dialed transfer number.
2729          *
2730          * NOTE: The local channel needs the /n flag so party C will use
2731          * the feature flags set by the dialplan when calling that
2732          * party.
2733          */
2734         snprintf(xferto + l, sizeof(xferto) - l, "@%s/n", transferer_real_context);
2735
2736         /* If we are performing an attended transfer and we have two channels involved then
2737            copy sound file information to play upon attended transfer completion */
2738         chan1_attended_sound = pbx_builtin_getvar_helper(transferer, "ATTENDED_TRANSFER_COMPLETE_SOUND");
2739         chan2_attended_sound = pbx_builtin_getvar_helper(transferee, "ATTENDED_TRANSFER_COMPLETE_SOUND");
2740         if (!ast_strlen_zero(chan1_attended_sound)) {
2741                 pbx_builtin_setvar_helper(transferer, "BRIDGE_PLAY_SOUND", chan1_attended_sound);
2742         }
2743         if (!ast_strlen_zero(chan2_attended_sound)) {
2744                 pbx_builtin_setvar_helper(transferee, "BRIDGE_PLAY_SOUND", chan2_attended_sound);
2745         }
2746
2747         /* Extract redial transferer information from the channel name. */
2748         transferer_name_orig = ast_strdupa(ast_channel_name(transferer));
2749         transferer_name = ast_strdupa(transferer_name_orig);
2750         transferer_tech = strsep(&transferer_name, "/");
2751         dash = strrchr(transferer_name, '-');
2752         if (dash) {
2753                 /* Trim off channel name sequence/serial number. */
2754                 *dash = '\0';
2755         }
2756
2757         /* Stop autoservice so we can monitor all parties involved in the transfer. */
2758         if (ast_autoservice_stop(transferee) < 0) {
2759                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2760                 return -1;
2761         }
2762
2763         /* Save connected line info for party B about party A in case transfer fails. */
2764         ast_party_connected_line_init(&connected_line);
2765         ast_channel_lock(transferer);
2766         ast_party_connected_line_copy(&connected_line, ast_channel_connected(transferer));
2767         ast_channel_unlock(transferer);
2768         connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
2769
2770         /* Dial party C */
2771         newchan = feature_request_and_dial(transferer, transferer_name_orig, transferer,
2772                 transferee, "Local", ast_channel_nativeformats(transferer), xferto,
2773                 atxfernoanswertimeout, &outstate, ast_channel_language(transferer));
2774         ast_debug(2, "Dial party C result: newchan:%d, outstate:%d\n", !!newchan, outstate);
2775
2776         if (!ast_check_hangup(transferer)) {
2777                 int hangup_dont = 0;
2778
2779                 /* Transferer (party B) is up */
2780                 ast_debug(1, "Actually doing an attended transfer.\n");
2781
2782                 /* Start autoservice on transferee while the transferer deals with party C. */
2783                 ast_autoservice_start(transferee);
2784
2785                 ast_indicate(transferer, -1);
2786                 if (!newchan) {
2787                         /* any reason besides user requested cancel and busy triggers the failed sound */
2788                         switch (outstate) {
2789                         case AST_CONTROL_UNHOLD:/* Caller requested cancel or party C answer timeout. */
2790                         case AST_CONTROL_BUSY:
2791                         case AST_CONTROL_CONGESTION:
2792                                 if (ast_stream_and_wait(transferer, xfersound, "")) {
2793                                         ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
2794                                 }
2795                                 break;
2796                         default:
2797                                 if (ast_stream_and_wait(transferer, xferfailsound, "")) {
2798                                         ast_log(LOG_WARNING, "Failed to play transfer failed sound!\n");
2799                                 }
2800                                 break;
2801                         }
2802                         atxfer_fail_cleanup(transferee, transferer, &connected_line);
2803                         return AST_FEATURE_RETURN_SUCCESS;
2804                 }
2805
2806                 if (check_compat(transferer, newchan)) {
2807                         if (ast_stream_and_wait(transferer, xferfailsound, "")) {
2808                                 ast_log(LOG_WARNING, "Failed to play transfer failed sound!\n");
2809                         }
2810                         atxfer_fail_cleanup(transferee, transferer, &connected_line);
2811                         return AST_FEATURE_RETURN_SUCCESS;
2812                 }
2813                 memset(&bconfig,0,sizeof(struct ast_bridge_config));
2814                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_DISCONNECT);
2815                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_DISCONNECT);
2816
2817                 /*
2818                  * ast_bridge_call clears AST_FLAG_BRIDGE_HANGUP_DONT, but we
2819                  * don't want that to happen here because the transferer is in
2820                  * another bridge already.
2821                  */
2822                 if (ast_test_flag(ast_channel_flags(transferer), AST_FLAG_BRIDGE_HANGUP_DONT)) {
2823                         hangup_dont = 1;
2824                 }
2825
2826                 /*
2827                  * Don't let the after-bridge code run the h-exten.  It is the
2828                  * wrong bridge to run the h-exten after.
2829                  */
2830                 ast_set_flag(ast_channel_flags(transferer), AST_FLAG_BRIDGE_HANGUP_DONT);
2831
2832                 /*
2833                  * Let party B and C talk as long as they want while party A
2834                  * languishes in autoservice listening to MOH.
2835                  */
2836                 ast_bridge_call(transferer, newchan, &bconfig);
2837
2838                 if (hangup_dont) {
2839                         /* Restore the AST_FLAG_BRIDGE_HANGUP_DONT flag */
2840                         ast_set_flag(ast_channel_flags(transferer), AST_FLAG_BRIDGE_HANGUP_DONT);
2841                 }
2842
2843                 if (ast_check_hangup(newchan) || !ast_check_hangup(transferer)) {
2844                         ast_autoservice_chan_hangup_peer(transferer, newchan);
2845                         if (ast_stream_and_wait(transferer, xfersound, "")) {
2846                                 ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
2847                         }
2848                         atxfer_fail_cleanup(transferee, transferer, &connected_line);
2849                         return AST_FEATURE_RETURN_SUCCESS;
2850                 }
2851
2852                 /* Transferer (party B) is confirmed hung up at this point. */
2853                 if (check_compat(transferee, newchan)) {
2854                         finishup(transferee);
2855                         ast_party_connected_line_free(&connected_line);
2856                         return -1;
2857                 }
2858
2859                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2860                 if ((ast_autoservice_stop(transferee) < 0)
2861                         || (ast_waitfordigit(transferee, 100) < 0)
2862                         || (ast_waitfordigit(newchan, 100) < 0)
2863                         || ast_check_hangup(transferee)
2864                         || ast_check_hangup(newchan)) {
2865                         ast_hangup(newchan);
2866                         ast_party_connected_line_free(&connected_line);
2867                         return -1;
2868                 }
2869         } else if (!ast_check_hangup(transferee)) {
2870                 /* Transferer (party B) has hung up at this point.  Doing blonde transfer. */
2871                 ast_debug(1, "Actually doing a blonde transfer.\n");
2872
2873                 if (!newchan && !atxferdropcall) {
2874                         /* Party C is not available, try to call party B back. */
2875                         unsigned int tries = 0;
2876
2877                         if (ast_strlen_zero(transferer_name) || ast_strlen_zero(transferer_tech)) {
2878                                 ast_log(LOG_WARNING,
2879                                         "Transferer channel name: '%s' cannot be used for callback.\n",
2880                                         transferer_name_orig);
2881                                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2882                                 ast_party_connected_line_free(&connected_line);
2883                                 return -1;
2884                         }
2885
2886                         tries = 0;
2887                         for (;;) {
2888                                 /* Try to get party B back. */
2889                                 ast_debug(1, "We're trying to callback %s/%s\n",
2890                                         transferer_tech, transferer_name);
2891                                 newchan = feature_request_and_dial(transferer, transferer_name_orig,
2892                                         transferee, transferee, transferer_tech,
2893                                         ast_channel_nativeformats(transferee), transferer_name,
2894                                         atxfernoanswertimeout, &outstate, ast_channel_language(transferer));
2895                                 ast_debug(2, "Dial party B result: newchan:%d, outstate:%d\n",
2896                                         !!newchan, outstate);
2897                                 if (newchan) {
2898                                         /*
2899                                          * We have recalled party B (newchan).  We need to give this
2900                                          * call leg the same feature flags as the original party B call
2901                                          * leg.
2902                                          */
2903                                         ast_channel_lock(transferer);
2904                                         features_datastore = ast_channel_datastore_find(transferer,
2905                                                 &dial_features_info, NULL);
2906                                         if (features_datastore && (dialfeatures = features_datastore->data)) {
2907                                                 struct ast_flags my_features = { 0 };
2908                                                 struct ast_flags peer_features = { 0 };
2909
2910                                                 ast_copy_flags(&my_features, &dialfeatures->my_features,
2911                                                         AST_FLAGS_ALL);
2912                                                 ast_copy_flags(&peer_features, &dialfeatures->peer_features,
2913                                                         AST_FLAGS_ALL);
2914                                                 ast_channel_unlock(transferer);
2915                                                 add_features_datastore(newchan, &my_features, &peer_features);
2916                                         } else {
2917                                                 ast_channel_unlock(transferer);
2918                                         }
2919                                         break;
2920                                 }
2921                                 if (ast_check_hangup(transferee)) {
2922                                         break;
2923                                 }
2924
2925                                 ++tries;
2926                                 if (atxfercallbackretries <= tries) {
2927                                         /* No more callback tries remaining. */
2928                                         break;
2929                                 }
2930
2931                                 if (atxferloopdelay) {
2932                                         /* Transfer failed, sleeping */
2933                                         ast_debug(1, "Sleeping for %d ms before retrying atxfer.\n",
2934                                                 atxferloopdelay);
2935                                         ast_safe_sleep(transferee, atxferloopdelay);
2936                                         if (ast_check_hangup(transferee)) {
2937                                                 ast_party_connected_line_free(&connected_line);
2938                                                 return -1;
2939                                         }
2940                                 }
2941
2942                                 /* Retry dialing party C. */
2943                                 ast_debug(1, "We're retrying to call %s/%s\n", "Local", xferto);
2944                                 newchan = feature_request_and_dial(transferer, transferer_name_orig,
2945                                         transferer, transferee, "Local",
2946                                         ast_channel_nativeformats(transferee), xferto,
2947                                         atxfernoanswertimeout, &outstate, ast_channel_language(transferer));
2948                                 ast_debug(2, "Redial party C result: newchan:%d, outstate:%d\n",
2949                                         !!newchan, outstate);
2950                                 if (newchan || ast_check_hangup(transferee)) {
2951                                         break;
2952                                 }
2953                         }
2954                 }
2955                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2956                 if (!newchan) {
2957                         /* No party C or could not callback party B. */
2958                         ast_party_connected_line_free(&connected_line);
2959                         return -1;
2960                 }
2961
2962                 /* newchan is up, we should prepare transferee and bridge them */
2963                 if (ast_check_hangup(newchan)) {
2964                         ast_autoservice_chan_hangup_peer(transferee, newchan);
2965                         ast_party_connected_line_free(&connected_line);
2966                         return -1;
2967                 }
2968                 if (check_compat(transferee, newchan)) {
2969                         ast_party_connected_line_free(&connected_line);
2970                         return -1;
2971                 }
2972         } else {
2973                 /*
2974                  * Both the transferer and transferee have hungup.  If newchan
2975                  * is up, hang it up as it has no one to talk to.
2976                  */
2977                 ast_debug(1, "Everyone is hungup.\n");
2978                 if (newchan) {
2979                         ast_hangup(newchan);
2980                 }
2981                 ast_party_connected_line_free(&connected_line);
2982                 return -1;
2983         }
2984
2985         /* Initiate the channel transfer of party A to party C (or recalled party B). */
2986         ast_cel_report_event(transferee, AST_CEL_ATTENDEDTRANSFER, NULL, NULL, newchan);
2987
2988         xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", ast_channel_linkedid(transferee), 0, "Transfered/%s", ast_channel_name(transferee));
2989         if (!xferchan) {
2990                 ast_autoservice_chan_hangup_peer(transferee, newchan);
2991                 ast_party_connected_line_free(&connected_line);
2992                 return -1;
2993         }
2994
2995         /* Give party A a momentary ringback tone during transfer. */
2996         ast_channel_visible_indication_set(xferchan, AST_CONTROL_RINGING);
2997
2998         /* Make formats okay */
2999         ast_format_copy(ast_channel_readformat(xferchan), ast_channel_readformat(transferee));
3000         ast_format_copy(ast_channel_writeformat(xferchan), ast_channel_writeformat(transferee));
3001
3002         if (ast_channel_masquerade(xferchan, transferee)) {
3003                 ast_hangup(xferchan);
3004                 ast_autoservice_chan_hangup_peer(transferee, newchan);
3005                 ast_party_connected_line_free(&connected_line);
3006                 return -1;
3007         }
3008
3009         dash = strrchr(xferto, '@');
3010         if (dash) {
3011                 /* Trim off the context. */
3012                 *dash = '\0';
3013         }
3014         ast_explicit_goto(xferchan, transferer_real_context, xferto, 1);
3015         ast_channel_state_set(xferchan, AST_STATE_UP);
3016         ast_clear_flag(ast_channel_flags(xferchan), AST_FLAGS_ALL);
3017
3018         /* Do the masquerade manually to make sure that is is completed. */
3019         ast_do_masquerade(xferchan);
3020
3021         ast_channel_state_set(newchan, AST_STATE_UP);
3022         ast_clear_flag(ast_channel_flags(newchan), AST_FLAGS_ALL);
3023         tobj = ast_calloc(1, sizeof(*tobj));
3024         if (!tobj) {
3025   &nbs