Doxygen Updates - Title update
[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                 pu->hold_method = AST_CONTROL_HOLD;
1821                 ast_indicate_data(chan, AST_CONTROL_HOLD,
1822                         S_OR(pu->parkinglot->cfg.mohclass, NULL),
1823                         !ast_strlen_zero(pu->parkinglot->cfg.mohclass) ? strlen(pu->parkinglot->cfg.mohclass) + 1 : 0);
1824                 pu->notquiteyet = 0;
1825                 pthread_kill(parking_thread, SIGURG);
1826         }
1827         return 0;
1828 }
1829
1830 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)
1831 {
1832         int res;
1833         char *parse;
1834         const char *app_data;
1835         struct ast_exten *exten;
1836         struct park_app_args app_args;
1837         struct ast_park_call_args args = {
1838                 .timeout = timeout,
1839                 .extout = extout,
1840         };
1841
1842         if (!park_exten || !park_context) {
1843                 return park_call_full(park_me, parker, &args);
1844         }
1845
1846         /*
1847          * Determiine if the specified park extension has an exclusive
1848          * parking lot to use.
1849          */
1850         if (parker && parker != park_me) {
1851                 ast_autoservice_start(park_me);
1852         }
1853         exten = get_parking_exten(park_exten, parker, park_context);
1854         if (exten) {
1855                 app_data = ast_get_extension_app_data(exten);
1856                 if (!app_data) {
1857                         app_data = "";
1858                 }
1859                 parse = ast_strdupa(app_data);
1860                 AST_STANDARD_APP_ARGS(app_args, parse);
1861
1862                 if (!ast_strlen_zero(app_args.pl_name)) {
1863                         /* Find the specified exclusive parking lot */
1864                         args.parkinglot = find_parkinglot(app_args.pl_name);
1865                         if (!args.parkinglot && parkeddynamic) {
1866                                 args.parkinglot = create_dynamic_parkinglot(app_args.pl_name, park_me);
1867                         }
1868                 }
1869         }
1870         if (parker && parker != park_me) {
1871                 ast_autoservice_stop(park_me);
1872         }
1873
1874         res = park_call_full(park_me, parker, &args);
1875         if (args.parkinglot) {
1876                 parkinglot_unref(args.parkinglot);
1877         }
1878         return res;
1879 }
1880
1881 int ast_park_call(struct ast_channel *park_me, struct ast_channel *parker, int timeout, const char *park_exten, int *extout)
1882 {
1883         struct ast_park_call_args args = {
1884                 .timeout = timeout,
1885                 .extout = extout,
1886         };
1887
1888         return park_call_full(park_me, parker, &args);
1889 }
1890
1891 /*!
1892  * \brief Park call via masqueraded channel and announce parking spot on peer channel.
1893  *
1894  * \param rchan the real channel to be parked
1895  * \param peer the channel to have the parking read to.
1896  * \param args Additional parking options when parking a call.
1897  *
1898  * \retval 0 on success.
1899  * \retval -1 on failure.
1900  */
1901 static int masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, struct ast_park_call_args *args)
1902 {
1903         struct ast_channel *chan;
1904
1905         /* Make a new, channel that we'll use to masquerade in the real one */
1906         chan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, ast_channel_accountcode(rchan), ast_channel_exten(rchan),
1907                 ast_channel_context(rchan), ast_channel_linkedid(rchan), ast_channel_amaflags(rchan), "Parked/%s", ast_channel_name(rchan));
1908         if (!chan) {
1909                 ast_log(LOG_WARNING, "Unable to create parked channel\n");
1910                 if (!ast_test_flag(args, AST_PARK_OPT_SILENCE)) {
1911                         if (peer == rchan) {
1912                                 /* Only have one channel to worry about. */
1913                                 ast_stream_and_wait(peer, "pbx-parkingfailed", "");
1914                         } else if (peer) {
1915                                 /* Have two different channels to worry about. */
1916                                 play_message_on_chan(peer, rchan, "failure message", "pbx-parkingfailed");
1917                         }
1918                 }
1919                 return -1;
1920         }
1921
1922         args->pu = park_space_reserve(rchan, peer, args);
1923         if (!args->pu) {
1924                 ast_hangup(chan);
1925                 if (!ast_test_flag(args, AST_PARK_OPT_SILENCE)) {
1926                         if (peer == rchan) {
1927                                 /* Only have one channel to worry about. */
1928                                 ast_stream_and_wait(peer, "pbx-parkingfailed", "");
1929                         } else if (peer) {
1930                                 /* Have two different channels to worry about. */
1931                                 play_message_on_chan(peer, rchan, "failure message", "pbx-parkingfailed");
1932                         }
1933                 }
1934                 return -1;
1935         }
1936
1937         /* Make formats okay */
1938         ast_format_copy(ast_channel_readformat(chan), ast_channel_readformat(rchan));
1939         ast_format_copy(ast_channel_writeformat(chan), ast_channel_writeformat(rchan));
1940
1941         if (ast_channel_masquerade(chan, rchan)) {
1942                 park_space_abort(args->pu);
1943                 args->pu = NULL;
1944                 ast_hangup(chan);
1945                 if (!ast_test_flag(args, AST_PARK_OPT_SILENCE)) {
1946                         if (peer == rchan) {
1947                                 /* Only have one channel to worry about. */
1948                                 ast_stream_and_wait(peer, "pbx-parkingfailed", "");
1949                         } else if (peer) {
1950                                 /* Have two different channels to worry about. */
1951                                 play_message_on_chan(peer, rchan, "failure message", "pbx-parkingfailed");
1952                         }
1953                 }
1954                 return -1;
1955         }
1956
1957         /* Setup the extensions and such */
1958         set_c_e_p(chan, ast_channel_context(rchan), ast_channel_exten(rchan), ast_channel_priority(rchan));
1959
1960         /* Setup the macro extension and such */
1961         ast_channel_macrocontext_set(chan, ast_channel_macrocontext(rchan));
1962         ast_channel_macroexten_set(chan, ast_channel_macroexten(rchan));
1963         ast_channel_macropriority_set(chan, ast_channel_macropriority(rchan));
1964
1965         /* Manually do the masquerade to make sure it is complete. */
1966         ast_do_masquerade(chan);
1967
1968         if (peer == rchan) {
1969                 peer = chan;
1970         }
1971
1972         /* parking space reserved, return code check unnecessary */
1973         park_call_full(chan, peer, args);
1974
1975         return 0;
1976 }
1977
1978 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)
1979 {
1980         int res;
1981         char *parse;
1982         const char *app_data;
1983         struct ast_exten *exten;
1984         struct park_app_args app_args;
1985         struct ast_park_call_args args = {
1986                 .timeout = timeout,
1987                 .extout = extout,
1988         };
1989
1990         if (parker) {
1991                 args.orig_chan_name = ast_strdupa(ast_channel_name(parker));
1992         }
1993         if (!park_exten || !park_context) {
1994                 return masq_park_call(park_me, parker, &args);
1995         }
1996
1997         /*
1998          * Determiine if the specified park extension has an exclusive
1999          * parking lot to use.
2000          */
2001         if (parker && parker != park_me) {
2002                 ast_autoservice_start(park_me);
2003         }
2004         exten = get_parking_exten(park_exten, parker, park_context);
2005         if (exten) {
2006                 app_data = ast_get_extension_app_data(exten);
2007                 if (!app_data) {
2008                         app_data = "";
2009                 }
2010                 parse = ast_strdupa(app_data);
2011                 AST_STANDARD_APP_ARGS(app_args, parse);
2012
2013                 if (!ast_strlen_zero(app_args.pl_name)) {
2014                         /* Find the specified exclusive parking lot */
2015                         args.parkinglot = find_parkinglot(app_args.pl_name);
2016                         if (!args.parkinglot && parkeddynamic) {
2017                                 args.parkinglot = create_dynamic_parkinglot(app_args.pl_name, park_me);
2018                         }
2019                 }
2020         }
2021         if (parker && parker != park_me) {
2022                 ast_autoservice_stop(park_me);
2023         }
2024
2025         res = masq_park_call(park_me, parker, &args);
2026         if (args.parkinglot) {
2027                 parkinglot_unref(args.parkinglot);
2028         }
2029         return res;
2030 }
2031
2032 int ast_masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, int timeout, int *extout)
2033 {
2034         struct ast_park_call_args args = {
2035                 .timeout = timeout,
2036                 .extout = extout,
2037         };
2038
2039         if (peer) {
2040                 args.orig_chan_name = ast_strdupa(ast_channel_name(peer));
2041         }
2042         return masq_park_call(rchan, peer, &args);
2043 }
2044
2045 static int finishup(struct ast_channel *chan)
2046 {
2047         ast_indicate(chan, AST_CONTROL_UNHOLD);
2048
2049         return ast_autoservice_stop(chan);
2050 }
2051
2052 /*!
2053  * \internal
2054  * \brief Builtin transfer park call helper.
2055  *
2056  * \param park_me Channel to be parked.
2057  * \param parker Channel parking the call.
2058  * \param park_exten Parking lot dialplan access ramp extension.
2059  *
2060  * \note Assumes park_me is on hold and in autoservice.
2061  *
2062  * \retval -1 on successful park.
2063  * \retval -1 on park_me hangup.
2064  * \retval AST_FEATURE_RETURN_SUCCESS on error to keep the bridge connected.
2065  */
2066 static int xfer_park_call_helper(struct ast_channel *park_me, struct ast_channel *parker, struct ast_exten *park_exten)
2067 {
2068         char *parse;
2069         const char *app_data;
2070         const char *pl_name;
2071         struct ast_park_call_args args = { 0, };
2072         struct park_app_args app_args;
2073         int res;
2074
2075         app_data = ast_get_extension_app_data(park_exten);
2076         if (!app_data) {
2077                 app_data = "";
2078         }
2079         parse = ast_strdupa(app_data);
2080         AST_STANDARD_APP_ARGS(app_args, parse);
2081
2082         /* Find the parking lot */
2083         if (!ast_strlen_zero(app_args.pl_name)) {
2084                 pl_name = app_args.pl_name;
2085         } else {
2086                 pl_name = findparkinglotname(parker);
2087         }
2088         if (ast_strlen_zero(pl_name)) {
2089                 /* Parking lot is not specified, so use the default parking lot. */
2090                 args.parkinglot = parkinglot_addref(default_parkinglot);
2091         } else {
2092                 args.parkinglot = find_parkinglot(pl_name);
2093                 if (!args.parkinglot && parkeddynamic) {
2094                         args.parkinglot = create_dynamic_parkinglot(pl_name, park_me);
2095                 }
2096         }
2097
2098         if (args.parkinglot) {
2099                 /* Park the call */
2100                 res = finishup(park_me);
2101                 if (res) {
2102                         /* park_me hungup on us. */
2103                         parkinglot_unref(args.parkinglot);
2104                         return -1;
2105                 }
2106                 res = masq_park_call(park_me, parker, &args);
2107                 parkinglot_unref(args.parkinglot);
2108         } else {
2109                 /* Parking failed because parking lot does not exist. */
2110                 if (!ast_test_flag(&args, AST_PARK_OPT_SILENCE)) {
2111                         ast_stream_and_wait(parker, "pbx-parkingfailed", "");
2112                 }
2113                 finishup(park_me);
2114                 res = -1;
2115         }
2116
2117         return res ? AST_FEATURE_RETURN_SUCCESS : -1;
2118 }
2119
2120 /*!
2121  * \brief set caller and callee according to the direction
2122  * \param caller, callee, peer, chan, sense
2123  *
2124  * Detect who triggered feature and set callee/caller variables accordingly
2125  */
2126 static void set_peers(struct ast_channel **caller, struct ast_channel **callee,
2127         struct ast_channel *peer, struct ast_channel *chan, int sense)
2128 {
2129         if (sense == FEATURE_SENSE_PEER) {
2130                 *caller = peer;
2131                 *callee = chan;
2132         } else {
2133                 *callee = peer;
2134                 *caller = chan;
2135         }
2136 }
2137
2138 /*!
2139  * \brief support routing for one touch call parking
2140  * \param chan channel parking call
2141  * \param peer channel to be parked
2142  * \param config unsed
2143  * \param code unused
2144  * \param sense feature options
2145  * \param data unused
2146  *
2147  * \retval -1 on successful park.
2148  * \retval -1 on chan hangup.
2149  * \retval AST_FEATURE_RETURN_SUCCESS on error to keep the bridge connected.
2150  */
2151 static int builtin_parkcall(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2152 {
2153         struct ast_channel *parker;
2154         struct ast_channel *parkee;
2155         struct ast_park_call_args args = { 0, };
2156
2157         /*
2158          * We used to set chan's exten and priority to "s" and 1 here,
2159          * but this generates (in some cases) an invalid extension, and
2160          * if "s" exists, could errantly cause execution of extensions
2161          * you don't expect.  It makes more sense to let nature take its
2162          * course when chan finishes, and let the pbx do its thing and
2163          * hang up when the park is over.
2164          */
2165
2166         /* Answer if call is not up */
2167         if (ast_channel_state(chan) != AST_STATE_UP) {
2168                 /*
2169                  * XXX Why are we doing this?  Both of the channels should be up
2170                  * since you cannot do DTMF features unless you are bridged.
2171                  */
2172                 if (ast_answer(chan)) {
2173                         return -1;
2174                 }
2175
2176                 /* Sleep to allow VoIP streams to settle down */
2177                 if (ast_safe_sleep(chan, 1000)) {
2178                         return -1;
2179                 }
2180         }
2181
2182         /* one direction used to call park_call.... */
2183         set_peers(&parker, &parkee, peer, chan, sense);
2184         return masq_park_call(parkee, parker, &args) ? AST_FEATURE_RETURN_SUCCESS : -1;
2185 }
2186
2187 /*!
2188  * \internal
2189  * \brief Play file to specified channel.
2190  *
2191  * \param play_to Channel to play audiofile to.
2192  * \param other Channel to put in autoservice while playing file.
2193  * \param msg Descriptive name of message type being played.
2194  * \param audiofile Audio file to play.
2195  *
2196  * \retval 0 on success.
2197  * \retval -1 on error. (Couldn't play file, a channel hung up,...)
2198  */
2199 static int play_message_on_chan(struct ast_channel *play_to, struct ast_channel *other, const char *msg, const char *audiofile)
2200 {
2201         /* Put other channel in autoservice. */
2202         if (ast_autoservice_start(other)) {
2203                 return -1;
2204         }
2205         ast_autoservice_ignore(other, AST_FRAME_DTMF_BEGIN);
2206         ast_autoservice_ignore(other, AST_FRAME_DTMF_END);
2207         if (ast_stream_and_wait(play_to, audiofile, "")) {
2208                 ast_log(LOG_WARNING, "Failed to play %s '%s'!\n", msg, audiofile);
2209                 ast_autoservice_stop(other);
2210                 return -1;
2211         }
2212         if (ast_autoservice_stop(other)) {
2213                 return -1;
2214         }
2215         return 0;
2216 }
2217
2218 /*!
2219  * \internal
2220  * \brief Play file to specified channels.
2221  *
2222  * \param left Channel on left to play file.
2223  * \param right Channel on right to play file.
2224  * \param which Play file on indicated channels: which < 0 play left, which == 0 play both, which > 0 play right
2225  * \param msg Descriptive name of message type being played.
2226  * \param audiofile Audio file to play to channels.
2227  *
2228  * \note Plays file to the indicated channels in turn so please
2229  * don't use this for very long messages.
2230  *
2231  * \retval 0 on success.
2232  * \retval -1 on error. (Couldn't play file, channel hung up,...)
2233  */
2234 static int play_message_to_chans(struct ast_channel *left, struct ast_channel *right, int which, const char *msg, const char *audiofile)
2235 {
2236         /* First play the file to the left channel if requested. */
2237         if (which <= 0 && play_message_on_chan(left, right, msg, audiofile)) {
2238                 return -1;
2239         }
2240
2241         /* Then play the file to the right channel if requested. */
2242         if (which >= 0 && play_message_on_chan(right, left, msg, audiofile)) {
2243                 return -1;
2244         }
2245
2246         return 0;
2247 }
2248
2249 /*!
2250  * \brief Play message to both caller and callee in bridged call, plays synchronously, autoservicing the
2251  * other channel during the message, so please don't use this for very long messages
2252  */
2253 static int play_message_in_bridged_call(struct ast_channel *caller_chan, struct ast_channel *callee_chan, const char *audiofile)
2254 {
2255         return play_message_to_chans(caller_chan, callee_chan, 0, "automon message",
2256                 audiofile);
2257 }
2258
2259 /*!
2260  * \brief Monitor a channel by DTMF
2261  * \param chan channel requesting monitor
2262  * \param peer channel to be monitored
2263  * \param config
2264  * \param code
2265  * \param sense feature options
2266  *
2267  * \param data
2268  * Check monitor app enabled, setup channels, both caller/callee chans not null
2269  * get TOUCH_MONITOR variable for filename if exists, exec monitor app.
2270  * \retval AST_FEATURE_RETURN_SUCCESS on success.
2271  * \retval -1 on error.
2272  */
2273 static int builtin_automonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2274 {
2275         char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
2276         int x = 0;
2277         size_t len;
2278         struct ast_channel *caller_chan, *callee_chan;
2279         const char *automon_message_start = NULL;
2280         const char *automon_message_stop = NULL;
2281         const char *touch_format = NULL;
2282         const char *touch_monitor = NULL;
2283         const char *touch_monitor_prefix = NULL;
2284
2285         if (!monitor_ok) {
2286                 ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
2287                 return -1;
2288         }
2289
2290         if (!monitor_app && !(monitor_app = pbx_findapp("Monitor"))) {
2291                 monitor_ok = 0;
2292                 ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
2293                 return -1;
2294         }
2295
2296         set_peers(&caller_chan, &callee_chan, peer, chan, sense);
2297
2298         /* Find extra messages */
2299         automon_message_start = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_START");
2300         automon_message_stop = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_STOP");
2301
2302         if (!ast_strlen_zero(courtesytone)) {   /* Play courtesy tone if configured */
2303                 if(play_message_in_bridged_call(caller_chan, callee_chan, courtesytone) == -1) {
2304                         return -1;
2305                 }
2306         }
2307
2308         if (ast_channel_monitor(callee_chan)) {
2309                 ast_verb(4, "User hit '%s' to stop recording call.\n", code);
2310                 if (!ast_strlen_zero(automon_message_stop)) {
2311                         play_message_in_bridged_call(caller_chan, callee_chan, automon_message_stop);
2312                 }
2313                 ast_channel_monitor(callee_chan)->stop(callee_chan, 1);
2314                 return AST_FEATURE_RETURN_SUCCESS;
2315         }
2316
2317         touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_FORMAT");
2318         touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR");
2319         touch_monitor_prefix = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_PREFIX");
2320
2321         if (!touch_format)
2322                 touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_FORMAT");
2323
2324         if (!touch_monitor)
2325                 touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR");
2326
2327         if (!touch_monitor_prefix)
2328                 touch_monitor_prefix = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_PREFIX");
2329
2330         if (touch_monitor) {
2331                 len = strlen(touch_monitor) + 50;
2332                 args = ast_alloca(len);
2333                 touch_filename = ast_alloca(len);
2334                 snprintf(touch_filename, len, "%s-%ld-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), touch_monitor);
2335                 snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
2336         } else {
2337                 caller_chan_id = ast_strdupa(S_COR(ast_channel_caller(caller_chan)->id.number.valid,
2338                         ast_channel_caller(caller_chan)->id.number.str, ast_channel_name(caller_chan)));
2339                 callee_chan_id = ast_strdupa(S_COR(ast_channel_caller(callee_chan)->id.number.valid,
2340                         ast_channel_caller(callee_chan)->id.number.str, ast_channel_name(callee_chan)));
2341                 len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
2342                 args = ast_alloca(len);
2343                 touch_filename = ast_alloca(len);
2344                 snprintf(touch_filename, len, "%s-%ld-%s-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), caller_chan_id, callee_chan_id);
2345                 snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
2346         }
2347
2348         for(x = 0; x < strlen(args); x++) {
2349                 if (args[x] == '/')
2350                         args[x] = '-';
2351         }
2352
2353         ast_verb(4, "User hit '%s' to record call. filename: %s\n", code, args);
2354
2355         pbx_exec(callee_chan, monitor_app, args);
2356         pbx_builtin_setvar_helper(callee_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
2357         pbx_builtin_setvar_helper(caller_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
2358
2359         if (!ast_strlen_zero(automon_message_start)) {  /* Play start message for both channels */
2360                 play_message_in_bridged_call(caller_chan, callee_chan, automon_message_start);
2361         }
2362
2363         return AST_FEATURE_RETURN_SUCCESS;
2364 }
2365
2366 static int builtin_automixmonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2367 {
2368         char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
2369         int x = 0;
2370         size_t len;
2371         struct ast_channel *caller_chan, *callee_chan;
2372         const char *mixmonitor_spy_type = "MixMonitor";
2373         const char *touch_format;
2374         const char *touch_monitor;
2375         int count = 0;
2376
2377         if (!mixmonitor_ok) {
2378                 ast_log(LOG_ERROR,"Cannot record the call. The mixmonitor application is disabled.\n");
2379                 return -1;
2380         }
2381
2382         if (!(mixmonitor_app = pbx_findapp("MixMonitor"))) {
2383                 mixmonitor_ok = 0;
2384                 ast_log(LOG_ERROR,"Cannot record the call. The mixmonitor application is disabled.\n");
2385                 return -1;
2386         }
2387
2388         set_peers(&caller_chan, &callee_chan, peer, chan, sense);
2389
2390         if (!ast_strlen_zero(courtesytone)) {
2391                 if (ast_autoservice_start(callee_chan))
2392                         return -1;
2393                 ast_autoservice_ignore(callee_chan, AST_FRAME_DTMF_END);
2394                 if (ast_stream_and_wait(caller_chan, courtesytone, "")) {
2395                         ast_log(LOG_WARNING, "Failed to play courtesy tone!\n");
2396                         ast_autoservice_stop(callee_chan);
2397                         return -1;
2398                 }
2399                 if (ast_autoservice_stop(callee_chan))
2400                         return -1;
2401         }
2402
2403         ast_channel_lock(callee_chan);
2404         count = ast_channel_audiohook_count_by_source(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
2405         ast_channel_unlock(callee_chan);
2406
2407         /* This means a mixmonitor is attached to the channel, running or not is unknown. */
2408         if (count > 0) {
2409                 ast_verb(3, "User hit '%s' to stop recording call.\n", code);
2410
2411                 /* Make sure they are running */
2412                 ast_channel_lock(callee_chan);
2413                 count = ast_channel_audiohook_count_by_source_running(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
2414                 ast_channel_unlock(callee_chan);
2415                 if (count > 0) {
2416                         if (!stopmixmonitor_ok) {
2417                                 ast_log(LOG_ERROR,"Cannot stop recording the call. The stopmixmonitor application is disabled.\n");
2418                                 return -1;
2419                         }
2420                         if (!(stopmixmonitor_app = pbx_findapp("StopMixMonitor"))) {
2421                                 stopmixmonitor_ok = 0;
2422                                 ast_log(LOG_ERROR,"Cannot stop recording the call. The stopmixmonitor application is disabled.\n");
2423                                 return -1;
2424                         } else {
2425                                 pbx_exec(callee_chan, stopmixmonitor_app, "");
2426                                 return AST_FEATURE_RETURN_SUCCESS;
2427                         }
2428                 }
2429
2430                 ast_log(LOG_WARNING,"Stopped MixMonitors are attached to the channel.\n");
2431         }
2432
2433         touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR_FORMAT");
2434         touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR");
2435
2436         if (!touch_format)
2437                 touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR_FORMAT");
2438
2439         if (!touch_monitor)
2440                 touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR");
2441
2442         if (touch_monitor) {
2443                 len = strlen(touch_monitor) + 50;
2444                 args = ast_alloca(len);
2445                 touch_filename = ast_alloca(len);
2446                 snprintf(touch_filename, len, "auto-%ld-%s", (long)time(NULL), touch_monitor);
2447                 snprintf(args, len, "%s.%s,b", touch_filename, (touch_format) ? touch_format : "wav");
2448         } else {
2449                 caller_chan_id = ast_strdupa(S_COR(ast_channel_caller(caller_chan)->id.number.valid,
2450                         ast_channel_caller(caller_chan)->id.number.str, ast_channel_name(caller_chan)));
2451                 callee_chan_id = ast_strdupa(S_COR(ast_channel_caller(callee_chan)->id.number.valid,
2452                         ast_channel_caller(callee_chan)->id.number.str, ast_channel_name(callee_chan)));
2453                 len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
2454                 args = ast_alloca(len);
2455                 touch_filename = ast_alloca(len);
2456                 snprintf(touch_filename, len, "auto-%ld-%s-%s", (long)time(NULL), caller_chan_id, callee_chan_id);
2457                 snprintf(args, len, "%s.%s,b", touch_filename, S_OR(touch_format, "wav"));
2458         }
2459
2460         for( x = 0; x < strlen(args); x++) {
2461                 if (args[x] == '/')
2462                         args[x] = '-';
2463         }
2464
2465         ast_verb(3, "User hit '%s' to record call. filename: %s\n", code, touch_filename);
2466
2467         pbx_exec(callee_chan, mixmonitor_app, args);
2468         pbx_builtin_setvar_helper(callee_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
2469         pbx_builtin_setvar_helper(caller_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
2470         return AST_FEATURE_RETURN_SUCCESS;
2471 }
2472
2473 static int builtin_disconnect(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2474 {
2475         ast_verb(4, "User hit '%s' to disconnect call.\n", code);
2476         return AST_FEATURE_RETURN_HANGUP;
2477 }
2478
2479 /*!
2480  * \brief Find the context for the transfer
2481  * \param transferer
2482  * \param transferee
2483  *
2484  * Grab the TRANSFER_CONTEXT, if fails try grabbing macrocontext.
2485  * \return a context string
2486  */
2487 static const char *real_ctx(struct ast_channel *transferer, struct ast_channel *transferee)
2488 {
2489         const char *s = pbx_builtin_getvar_helper(transferer, "TRANSFER_CONTEXT");
2490         if (ast_strlen_zero(s)) {
2491                 s = pbx_builtin_getvar_helper(transferee, "TRANSFER_CONTEXT");
2492         }
2493         if (ast_strlen_zero(s)) { /* Use the non-macro context to transfer the call XXX ? */
2494                 s = ast_channel_macrocontext(transferer);
2495         }
2496         if (ast_strlen_zero(s)) {
2497                 s = ast_channel_context(transferer);
2498         }
2499         return s;
2500 }
2501
2502 /*!
2503  * \brief Blind transfer user to another extension
2504  * \param chan channel to be transfered
2505  * \param peer channel initiated blind transfer
2506  * \param config
2507  * \param code
2508  * \param data
2509  * \param sense  feature options
2510  *
2511  * Place chan on hold, check if transferred to parkinglot extension,
2512  * otherwise check extension exists and transfer caller.
2513  * \retval AST_FEATURE_RETURN_SUCCESS.
2514  * \retval -1 on failure.
2515  */
2516 static int builtin_blindtransfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2517 {
2518         struct ast_channel *transferer;
2519         struct ast_channel *transferee;
2520         struct ast_exten *park_exten;
2521         const char *transferer_real_context;
2522         char xferto[256] = "";
2523         int res;
2524
2525         ast_debug(1, "Executing Blind Transfer %s, %s (sense=%d) \n", ast_channel_name(chan), ast_channel_name(peer), sense);
2526         set_peers(&transferer, &transferee, peer, chan, sense);
2527         transferer_real_context = ast_strdupa(real_ctx(transferer, transferee));
2528
2529         /* Start autoservice on transferee while we talk to the transferer */
2530         ast_autoservice_start(transferee);
2531         ast_indicate(transferee, AST_CONTROL_HOLD);
2532
2533         /* Transfer */
2534         res = ast_stream_and_wait(transferer, "pbx-transfer", AST_DIGIT_ANY);
2535         if (res < 0) {
2536                 finishup(transferee);
2537                 return -1; /* error ? */
2538         }
2539         if (res > 0) { /* If they've typed a digit already, handle it */
2540                 xferto[0] = (char) res;
2541         }
2542
2543         res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
2544         if (res < 0) {  /* hangup or error, (would be 0 for invalid and 1 for valid) */
2545                 finishup(transferee);
2546                 return -1;
2547         }
2548         if (res == 0) {
2549                 if (xferto[0]) {
2550                         ast_log(LOG_WARNING, "Extension '%s' does not exist in context '%s'\n",
2551                                 xferto, transferer_real_context);
2552                 } else {
2553                         /* Does anyone care about this case? */
2554                         ast_log(LOG_WARNING, "No digits dialed.\n");
2555                 }
2556                 ast_stream_and_wait(transferer, "pbx-invalid", "");
2557                 finishup(transferee);
2558                 return AST_FEATURE_RETURN_SUCCESS;
2559         }
2560
2561         park_exten = get_parking_exten(xferto, transferer, transferer_real_context);
2562         if (park_exten) {
2563                 /* We are transfering the transferee to a parking lot. */
2564                 return xfer_park_call_helper(transferee, transferer, park_exten);
2565         }
2566
2567         /* Do blind transfer. */
2568         ast_verb(3, "Blind transferring %s to '%s' (context %s) priority 1\n",
2569                 ast_channel_name(transferee), xferto, transferer_real_context);
2570         ast_cel_report_event(transferer, AST_CEL_BLINDTRANSFER, NULL, xferto, transferee);
2571         pbx_builtin_setvar_helper(transferer, "BLINDTRANSFER", ast_channel_name(transferee));
2572         pbx_builtin_setvar_helper(transferee, "BLINDTRANSFER", ast_channel_name(transferer));
2573         finishup(transferee);
2574         ast_channel_lock(transferer);
2575         if (!ast_channel_cdr(transferer)) {
2576                 /* this code should never get called (in a perfect world) */
2577                 ast_channel_cdr_set(transferer, ast_cdr_alloc());
2578                 if (ast_channel_cdr(transferer)) {
2579                         ast_cdr_init(ast_channel_cdr(transferer), transferer); /* initialize our channel's cdr */
2580                         ast_cdr_start(ast_channel_cdr(transferer));
2581                 }
2582         }
2583         ast_channel_unlock(transferer);
2584         if (ast_channel_cdr(transferer)) {
2585                 struct ast_cdr *swap = ast_channel_cdr(transferer);
2586
2587                 ast_debug(1,
2588                         "transferer=%s; transferee=%s; lastapp=%s; lastdata=%s; chan=%s; dstchan=%s\n",
2589                         ast_channel_name(transferer), ast_channel_name(transferee), ast_channel_cdr(transferer)->lastapp,
2590                         ast_channel_cdr(transferer)->lastdata, ast_channel_cdr(transferer)->channel,
2591                         ast_channel_cdr(transferer)->dstchannel);
2592                 ast_debug(1, "TRANSFEREE; lastapp=%s; lastdata=%s, chan=%s; dstchan=%s\n",
2593                         ast_channel_cdr(transferee)->lastapp, ast_channel_cdr(transferee)->lastdata, ast_channel_cdr(transferee)->channel,
2594                         ast_channel_cdr(transferee)->dstchannel);
2595                 ast_debug(1, "transferer_real_context=%s; xferto=%s\n",
2596                         transferer_real_context, xferto);
2597                 /* swap cdrs-- it will save us some time & work */
2598                 ast_channel_cdr_set(transferer, ast_channel_cdr(transferee));
2599                 ast_channel_cdr_set(transferee, swap);
2600         }
2601
2602         res = ast_channel_pbx(transferee) ? AST_FEATURE_RETURN_SUCCESSBREAK : -1;
2603
2604         /* Doh!  Use our handy async_goto functions */
2605         if (ast_async_goto(transferee, transferer_real_context, xferto, 1)) {
2606                 ast_log(LOG_WARNING, "Async goto failed :-(\n");
2607                 res = -1;
2608         } else if (res == AST_FEATURE_RETURN_SUCCESSBREAK) {
2609                 /* Don't let the after-bridge code run the h-exten */
2610                 ast_channel_lock(transferee);
2611                 ast_set_flag(ast_channel_flags(transferee), AST_FLAG_BRIDGE_HANGUP_DONT);
2612                 ast_channel_unlock(transferee);
2613         }
2614         check_goto_on_transfer(transferer);
2615         return res;
2616 }
2617
2618 /*!
2619  * \brief make channels compatible
2620  * \param c
2621  * \param newchan
2622  * \retval 0 on success.
2623  * \retval -1 on failure.
2624  */
2625 static int check_compat(struct ast_channel *c, struct ast_channel *newchan)
2626 {
2627         if (ast_channel_make_compatible(c, newchan) < 0) {
2628                 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n",
2629                         ast_channel_name(c), ast_channel_name(newchan));
2630                 ast_autoservice_chan_hangup_peer(c, newchan);
2631                 return -1;
2632         }
2633         return 0;
2634 }
2635
2636 /*!
2637  * \internal
2638  * \brief Builtin attended transfer failed cleanup.
2639  * \since 10.0
2640  *
2641  * \param transferee Party A in the transfer.
2642  * \param transferer Party B in the transfer.
2643  * \param connected_line Saved connected line info about party A.
2644  *
2645  * \note The connected_line data is freed.
2646  *
2647  * \return Nothing
2648  */
2649 static void atxfer_fail_cleanup(struct ast_channel *transferee, struct ast_channel *transferer, struct ast_party_connected_line *connected_line)
2650 {
2651         finishup(transferee);
2652
2653         /*
2654          * Restore party B connected line info about party A.
2655          *
2656          * Party B was the caller to party C and is the last known mode
2657          * for party B.
2658          */
2659         if (ast_channel_connected_line_sub(transferee, transferer, connected_line, 0) &&
2660                 ast_channel_connected_line_macro(transferee, transferer, connected_line, 1, 0)) {
2661                 ast_channel_update_connected_line(transferer, connected_line, NULL);
2662         }
2663         ast_party_connected_line_free(connected_line);
2664 }
2665
2666 /*!
2667  * \brief Attended transfer
2668  * \param chan transfered user
2669  * \param peer person transfering call
2670  * \param config
2671  * \param code
2672  * \param sense feature options
2673  *
2674  * \param data
2675  * Get extension to transfer to, if you cannot generate channel (or find extension)
2676  * return to host channel. After called channel answered wait for hangup of transferer,
2677  * bridge call between transfer peer (taking them off hold) to attended transfer channel.
2678  *
2679  * \return -1 on failure
2680  */
2681 static int builtin_atxfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2682 {
2683         struct ast_channel *transferer;/* Party B */
2684         struct ast_channel *transferee;/* Party A */
2685         struct ast_exten *park_exten;
2686         const char *chan1_attended_sound;
2687         const char *chan2_attended_sound;
2688         const char *transferer_real_context;
2689         char xferto[256] = "";
2690         int res;
2691         int outstate=0;
2692         struct ast_channel *newchan;
2693         struct ast_channel *xferchan;
2694         struct ast_bridge_thread_obj *tobj;
2695         struct ast_bridge_config bconfig;
2696         int l;
2697         struct ast_party_connected_line connected_line;
2698         struct ast_datastore *features_datastore;
2699         struct ast_dial_features *dialfeatures;
2700         char *transferer_tech;
2701         char *transferer_name;
2702         char *transferer_name_orig;
2703         char *dash;
2704
2705         ast_debug(1, "Executing Attended Transfer %s, %s (sense=%d) \n", ast_channel_name(chan), ast_channel_name(peer), sense);
2706         set_peers(&transferer, &transferee, peer, chan, sense);
2707         transferer_real_context = real_ctx(transferer, transferee);
2708
2709         /* Start autoservice on transferee while we talk to the transferer */
2710         ast_autoservice_start(transferee);
2711         ast_indicate(transferee, AST_CONTROL_HOLD);
2712
2713         /* Transfer */
2714         res = ast_stream_and_wait(transferer, "pbx-transfer", AST_DIGIT_ANY);
2715         if (res < 0) {
2716                 finishup(transferee);
2717                 return -1;
2718         }
2719         if (res > 0) { /* If they've typed a digit already, handle it */
2720                 xferto[0] = (char) res;
2721         }
2722
2723         /* this is specific of atxfer */
2724         res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
2725         if (res < 0) {  /* hangup or error, (would be 0 for invalid and 1 for valid) */
2726                 finishup(transferee);
2727                 return -1;
2728         }
2729         l = strlen(xferto);
2730         if (res == 0) {
2731                 if (l) {
2732                         ast_log(LOG_WARNING, "Extension '%s' does not exist in context '%s'\n",
2733                                 xferto, transferer_real_context);
2734                 } else {
2735                         /* Does anyone care about this case? */
2736                         ast_log(LOG_WARNING, "No digits dialed for atxfer.\n");
2737                 }
2738                 ast_stream_and_wait(transferer, "pbx-invalid", "");
2739                 finishup(transferee);
2740                 return AST_FEATURE_RETURN_SUCCESS;
2741         }
2742
2743         park_exten = get_parking_exten(xferto, transferer, transferer_real_context);
2744         if (park_exten) {
2745                 /* We are transfering the transferee to a parking lot. */
2746                 return xfer_park_call_helper(transferee, transferer, park_exten);
2747         }
2748
2749         /*
2750          * Append context to dialed transfer number.
2751          *
2752          * NOTE: The local channel needs the /n flag so party C will use
2753          * the feature flags set by the dialplan when calling that
2754          * party.
2755          */
2756         snprintf(xferto + l, sizeof(xferto) - l, "@%s/n", transferer_real_context);
2757
2758         /* If we are performing an attended transfer and we have two channels involved then
2759            copy sound file information to play upon attended transfer completion */
2760         chan1_attended_sound = pbx_builtin_getvar_helper(transferer, "ATTENDED_TRANSFER_COMPLETE_SOUND");
2761         chan2_attended_sound = pbx_builtin_getvar_helper(transferee, "ATTENDED_TRANSFER_COMPLETE_SOUND");
2762         if (!ast_strlen_zero(chan1_attended_sound)) {
2763                 pbx_builtin_setvar_helper(transferer, "BRIDGE_PLAY_SOUND", chan1_attended_sound);
2764         }
2765         if (!ast_strlen_zero(chan2_attended_sound)) {
2766                 pbx_builtin_setvar_helper(transferee, "BRIDGE_PLAY_SOUND", chan2_attended_sound);
2767         }
2768
2769         /* Extract redial transferer information from the channel name. */
2770         transferer_name_orig = ast_strdupa(ast_channel_name(transferer));
2771         transferer_name = ast_strdupa(transferer_name_orig);
2772         transferer_tech = strsep(&transferer_name, "/");
2773         dash = strrchr(transferer_name, '-');
2774         if (dash) {
2775                 /* Trim off channel name sequence/serial number. */
2776                 *dash = '\0';
2777         }
2778
2779         /* Stop autoservice so we can monitor all parties involved in the transfer. */
2780         if (ast_autoservice_stop(transferee) < 0) {
2781                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2782                 return -1;
2783         }
2784
2785         /* Save connected line info for party B about party A in case transfer fails. */
2786         ast_party_connected_line_init(&connected_line);
2787         ast_channel_lock(transferer);
2788         ast_party_connected_line_copy(&connected_line, ast_channel_connected(transferer));
2789         ast_channel_unlock(transferer);
2790         connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
2791
2792         /* Dial party C */
2793         newchan = feature_request_and_dial(transferer, transferer_name_orig, transferer,
2794                 transferee, "Local", ast_channel_nativeformats(transferer), xferto,
2795                 atxfernoanswertimeout, &outstate, ast_channel_language(transferer));
2796         ast_debug(2, "Dial party C result: newchan:%d, outstate:%d\n", !!newchan, outstate);
2797
2798         if (!ast_check_hangup(transferer)) {
2799                 int hangup_dont = 0;
2800
2801                 /* Transferer (party B) is up */
2802                 ast_debug(1, "Actually doing an attended transfer.\n");
2803
2804                 /* Start autoservice on transferee while the transferer deals with party C. */
2805                 ast_autoservice_start(transferee);
2806
2807                 ast_indicate(transferer, -1);
2808                 if (!newchan) {
2809                         /* any reason besides user requested cancel and busy triggers the failed sound */
2810                         switch (outstate) {
2811                         case AST_CONTROL_UNHOLD:/* Caller requested cancel or party C answer timeout. */
2812                         case AST_CONTROL_BUSY:
2813                         case AST_CONTROL_CONGESTION:
2814                                 if (ast_stream_and_wait(transferer, xfersound, "")) {
2815                                         ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
2816                                 }
2817                                 break;
2818                         default:
2819                                 if (ast_stream_and_wait(transferer, xferfailsound, "")) {
2820                                         ast_log(LOG_WARNING, "Failed to play transfer failed sound!\n");
2821                                 }
2822                                 break;
2823                         }
2824                         atxfer_fail_cleanup(transferee, transferer, &connected_line);
2825                         return AST_FEATURE_RETURN_SUCCESS;
2826                 }
2827
2828                 if (check_compat(transferer, newchan)) {
2829                         if (ast_stream_and_wait(transferer, xferfailsound, "")) {
2830                                 ast_log(LOG_WARNING, "Failed to play transfer failed sound!\n");
2831                         }
2832                         atxfer_fail_cleanup(transferee, transferer, &connected_line);
2833                         return AST_FEATURE_RETURN_SUCCESS;
2834                 }
2835                 memset(&bconfig,0,sizeof(struct ast_bridge_config));
2836                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_DISCONNECT);
2837                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_DISCONNECT);
2838
2839                 /*
2840                  * ast_bridge_call clears AST_FLAG_BRIDGE_HANGUP_DONT, but we
2841                  * don't want that to happen here because the transferer is in
2842                  * another bridge already.
2843                  */
2844                 if (ast_test_flag(ast_channel_flags(transferer), AST_FLAG_BRIDGE_HANGUP_DONT)) {
2845                         hangup_dont = 1;
2846                 }
2847
2848                 /*
2849                  * Don't let the after-bridge code run the h-exten.  It is the
2850                  * wrong bridge to run the h-exten after.
2851                  */
2852                 ast_set_flag(ast_channel_flags(transferer), AST_FLAG_BRIDGE_HANGUP_DONT);
2853
2854                 /*
2855                  * Let party B and C talk as long as they want while party A
2856                  * languishes in autoservice listening to MOH.
2857                  */
2858                 ast_bridge_call(transferer, newchan, &bconfig);
2859
2860                 if (hangup_dont) {
2861                         /* Restore the AST_FLAG_BRIDGE_HANGUP_DONT flag */
2862                         ast_set_flag(ast_channel_flags(transferer), AST_FLAG_BRIDGE_HANGUP_DONT);
2863                 }
2864
2865                 if (ast_check_hangup(newchan) || !ast_check_hangup(transferer)) {
2866                         ast_autoservice_chan_hangup_peer(transferer, newchan);
2867                         if (ast_stream_and_wait(transferer, xfersound, "")) {
2868                                 ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
2869                         }
2870                         atxfer_fail_cleanup(transferee, transferer, &connected_line);
2871                         return AST_FEATURE_RETURN_SUCCESS;
2872                 }
2873
2874                 /* Transferer (party B) is confirmed hung up at this point. */
2875                 if (check_compat(transferee, newchan)) {
2876                         finishup(transferee);
2877                         ast_party_connected_line_free(&connected_line);
2878                         return -1;
2879                 }
2880
2881                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2882                 if ((ast_autoservice_stop(transferee) < 0)
2883                         || (ast_waitfordigit(transferee, 100) < 0)
2884                         || (ast_waitfordigit(newchan, 100) < 0)
2885                         || ast_check_hangup(transferee)
2886                         || ast_check_hangup(newchan)) {
2887                         ast_hangup(newchan);
2888                         ast_party_connected_line_free(&connected_line);
2889                         return -1;
2890                 }
2891         } else if (!ast_check_hangup(transferee)) {
2892                 /* Transferer (party B) has hung up at this point.  Doing blonde transfer. */
2893                 ast_debug(1, "Actually doing a blonde transfer.\n");
2894
2895                 if (!newchan && !atxferdropcall) {
2896                         /* Party C is not available, try to call party B back. */
2897                         unsigned int tries = 0;
2898
2899                         if (ast_strlen_zero(transferer_name) || ast_strlen_zero(transferer_tech)) {
2900                                 ast_log(LOG_WARNING,
2901                                         "Transferer channel name: '%s' cannot be used for callback.\n",
2902                                         transferer_name_orig);
2903                                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2904                                 ast_party_connected_line_free(&connected_line);
2905                                 return -1;
2906                         }
2907
2908                         tries = 0;
2909                         for (;;) {
2910                                 /* Try to get party B back. */
2911                                 ast_debug(1, "We're trying to callback %s/%s\n",
2912                                         transferer_tech, transferer_name);
2913                                 newchan = feature_request_and_dial(transferer, transferer_name_orig,
2914                                         transferee, transferee, transferer_tech,
2915                                         ast_channel_nativeformats(transferee), transferer_name,
2916                                         atxfernoanswertimeout, &outstate, ast_channel_language(transferer));
2917                                 ast_debug(2, "Dial party B result: newchan:%d, outstate:%d\n",
2918                                         !!newchan, outstate);
2919                                 if (newchan) {
2920                                         /*
2921                                          * We have recalled party B (newchan).  We need to give this
2922                                          * call leg the same feature flags as the original party B call
2923                                          * leg.
2924                                          */
2925                                         ast_channel_lock(transferer);
2926                                         features_datastore = ast_channel_datastore_find(transferer,
2927                                                 &dial_features_info, NULL);
2928                                         if (features_datastore && (dialfeatures = features_datastore->data)) {
2929                                                 struct ast_flags my_features = { 0 };
2930                                                 struct ast_flags peer_features = { 0 };
2931
2932                                                 ast_copy_flags(&my_features, &dialfeatures->my_features,
2933                                                         AST_FLAGS_ALL);
2934                                                 ast_copy_flags(&peer_features, &dialfeatures->peer_features,
2935                                                         AST_FLAGS_ALL);
2936                                                 ast_channel_unlock(transferer);
2937                                                 add_features_datastore(newchan, &my_features, &peer_features);
2938                                         } else {
2939                                                 ast_channel_unlock(transferer);
2940                                         }
2941                                         break;
2942                                 }
2943                                 if (ast_check_hangup(transferee)) {
2944                                         break;
2945                                 }
2946
2947                                 ++tries;
2948                                 if (atxfercallbackretries <= tries) {
2949                                         /* No more callback tries remaining. */
2950                                         break;
2951                                 }
2952
2953                                 if (atxferloopdelay) {
2954                                         /* Transfer failed, sleeping */
2955                                         ast_debug(1, "Sleeping for %d ms before retrying atxfer.\n",
2956                                                 atxferloopdelay);
2957                                         ast_safe_sleep(transferee, atxferloopdelay);
2958                                         if (ast_check_hangup(transferee)) {
2959                                                 ast_party_connected_line_free(&connected_line);
2960                                                 return -1;
2961                                         }
2962                                 }
2963
2964                                 /* Retry dialing party C. */
2965                                 ast_debug(1, "We're retrying to call %s/%s\n", "Local", xferto);
2966                                 newchan = feature_request_and_dial(transferer, transferer_name_orig,
2967                                         transferer, transferee, "Local",
2968                                         ast_channel_nativeformats(transferee), xferto,
2969                                         atxfernoanswertimeout, &outstate, ast_channel_language(transferer));
2970                                 ast_debug(2, "Redial party C result: newchan:%d, outstate:%d\n",
2971                                         !!newchan, outstate);
2972                                 if (newchan || ast_check_hangup(transferee)) {
2973                                         break;
2974                                 }
2975                         }
2976                 }
2977                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2978                 if (!newchan) {
2979                         /* No party C or could not callback party B. */
2980                         ast_party_connected_line_free(&connected_line);
2981                         return -1;
2982                 }
2983
2984                 /* newchan is up, we should prepare transferee and bridge them */
2985                 if (ast_check_hangup(newchan)) {
2986                         ast_autoservice_chan_hangup_peer(transferee, newchan);
2987                         ast_party_connected_line_free(&connected_line);
2988                         return -1;
2989                 }
2990                 if (check_compat(transferee, newchan)) {
2991                         ast_party_connected_line_free(&connected_line);
2992                         return -1;
2993                 }
2994         } else {
2995                 /*
2996                  * Both the transferer and transferee have hungup.  If newchan
2997                  * is up, hang it up as it has no one to talk to.
2998                  */
2999                 ast_debug(1, "Everyone is hungup.\n");
3000                 if (newchan) {
3001                         ast_hangup(newchan);
3002                 }
3003                 ast_party_connected_line_free(&connected_line);
3004                 return -1;
3005         }
3006
3007         /* Initiate the channel transfer of party A to party C (or recalled party B). */
3008         ast_cel_report_event(transferee, AST_CEL_ATTENDEDTRANSFER, NULL, NULL, newchan);
3009
3010         xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", ast_channel_linkedid(transferee), 0, "Transfered/%s", ast_channel_name(transferee));
3011         if (!xferchan) {
3012                 ast_autoservice_chan_hangup_peer(transferee, newchan);
3013                 ast_party_connected_line_free(&connected_line);
3014                 return -1;
3015         }
3016
3017         /* Give party A a momentary ringback tone during transfer. */
3018         ast_channel_visible_indication_set(xferchan, AST_CONTROL_RINGING);
3019
3020         /* Make formats okay */
3021         ast_format_copy(ast_channel_readformat(xferchan), ast_channel_readformat(transferee));
3022         ast_format_copy(ast_channel_writeformat(xferchan), ast_channel_writeformat(transferee));
3023
3024         if (ast_channel_masquerade(xferchan, transferee)) {
3025                 ast_hangup(xferchan);
3026                 ast_autoservice_chan_hangup_peer(transferee, newchan);
3027           &nbs