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