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