Coverity Report: Fix issues for error type UNINIT in Core supported modules
[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
2170         if (!monitor_ok) {
2171                 ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
2172                 return -1;
2173         }
2174
2175         if (!monitor_app && !(monitor_app = pbx_findapp("Monitor"))) {
2176                 monitor_ok = 0;
2177                 ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
2178                 return -1;
2179         }
2180
2181         set_peers(&caller_chan, &callee_chan, peer, chan, sense);
2182         if (caller_chan) {      /* Find extra messages */
2183                 automon_message_start = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_START");
2184                 automon_message_stop = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_STOP");
2185         }
2186
2187         if (!ast_strlen_zero(courtesytone)) {   /* Play courtesy tone if configured */
2188                 if(play_message_in_bridged_call(caller_chan, callee_chan, courtesytone) == -1) {
2189                         return -1;
2190                 }
2191         }
2192
2193         if (ast_channel_monitor(callee_chan)) {
2194                 ast_verb(4, "User hit '%s' to stop recording call.\n", code);
2195                 if (!ast_strlen_zero(automon_message_stop)) {
2196                         play_message_in_bridged_call(caller_chan, callee_chan, automon_message_stop);
2197                 }
2198                 ast_channel_monitor(callee_chan)->stop(callee_chan, 1);
2199                 return AST_FEATURE_RETURN_SUCCESS;
2200         }
2201
2202         if (caller_chan && callee_chan) {
2203                 const char *touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_FORMAT");
2204                 const char *touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR");
2205                 const char *touch_monitor_prefix = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_PREFIX");
2206
2207                 if (!touch_format)
2208                         touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_FORMAT");
2209
2210                 if (!touch_monitor)
2211                         touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR");
2212
2213                 if (!touch_monitor_prefix)
2214                         touch_monitor_prefix = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_PREFIX");
2215
2216                 if (touch_monitor) {
2217                         len = strlen(touch_monitor) + 50;
2218                         args = alloca(len);
2219                         touch_filename = alloca(len);
2220                         snprintf(touch_filename, len, "%s-%ld-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), touch_monitor);
2221                         snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
2222                 } else {
2223                         caller_chan_id = ast_strdupa(S_COR(ast_channel_caller(caller_chan)->id.number.valid,
2224                                 ast_channel_caller(caller_chan)->id.number.str, ast_channel_name(caller_chan)));
2225                         callee_chan_id = ast_strdupa(S_COR(ast_channel_caller(callee_chan)->id.number.valid,
2226                                 ast_channel_caller(callee_chan)->id.number.str, ast_channel_name(callee_chan)));
2227                         len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
2228                         args = alloca(len);
2229                         touch_filename = alloca(len);
2230                         snprintf(touch_filename, len, "%s-%ld-%s-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), caller_chan_id, callee_chan_id);
2231                         snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
2232                 }
2233
2234                 for(x = 0; x < strlen(args); x++) {
2235                         if (args[x] == '/')
2236                                 args[x] = '-';
2237                 }
2238
2239                 ast_verb(4, "User hit '%s' to record call. filename: %s\n", code, args);
2240
2241                 pbx_exec(callee_chan, monitor_app, args);
2242                 pbx_builtin_setvar_helper(callee_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
2243                 pbx_builtin_setvar_helper(caller_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
2244
2245                 if (!ast_strlen_zero(automon_message_start)) {  /* Play start message for both channels */
2246                         play_message_in_bridged_call(caller_chan, callee_chan, automon_message_start);
2247                 }
2248
2249                 return AST_FEATURE_RETURN_SUCCESS;
2250         }
2251
2252         ast_log(LOG_NOTICE,"Cannot record the call. One or both channels have gone away.\n");
2253         return -1;
2254 }
2255
2256 static int builtin_automixmonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2257 {
2258         char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
2259         int x = 0;
2260         size_t len;
2261         struct ast_channel *caller_chan, *callee_chan;
2262         const char *mixmonitor_spy_type = "MixMonitor";
2263         int count = 0;
2264
2265         if (!mixmonitor_ok) {
2266                 ast_log(LOG_ERROR,"Cannot record the call. The mixmonitor application is disabled.\n");
2267                 return -1;
2268         }
2269
2270         if (!(mixmonitor_app = pbx_findapp("MixMonitor"))) {
2271                 mixmonitor_ok = 0;
2272                 ast_log(LOG_ERROR,"Cannot record the call. The mixmonitor application is disabled.\n");
2273                 return -1;
2274         }
2275
2276         set_peers(&caller_chan, &callee_chan, peer, chan, sense);
2277
2278         if (!ast_strlen_zero(courtesytone)) {
2279                 if (ast_autoservice_start(callee_chan))
2280                         return -1;
2281                 ast_autoservice_ignore(callee_chan, AST_FRAME_DTMF_END);
2282                 if (ast_stream_and_wait(caller_chan, courtesytone, "")) {
2283                         ast_log(LOG_WARNING, "Failed to play courtesy tone!\n");
2284                         ast_autoservice_stop(callee_chan);
2285                         return -1;
2286                 }
2287                 if (ast_autoservice_stop(callee_chan))
2288                         return -1;
2289         }
2290
2291         ast_channel_lock(callee_chan);
2292         count = ast_channel_audiohook_count_by_source(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
2293         ast_channel_unlock(callee_chan);
2294
2295         /* This means a mixmonitor is attached to the channel, running or not is unknown. */
2296         if (count > 0) {
2297
2298                 ast_verb(3, "User hit '%s' to stop recording call.\n", code);
2299
2300                 /* Make sure they are running */
2301                 ast_channel_lock(callee_chan);
2302                 count = ast_channel_audiohook_count_by_source_running(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
2303                 ast_channel_unlock(callee_chan);
2304                 if (count > 0) {
2305                         if (!stopmixmonitor_ok) {
2306                                 ast_log(LOG_ERROR,"Cannot stop recording the call. The stopmixmonitor application is disabled.\n");
2307                                 return -1;
2308                         }
2309                         if (!(stopmixmonitor_app = pbx_findapp("StopMixMonitor"))) {
2310                                 stopmixmonitor_ok = 0;
2311                                 ast_log(LOG_ERROR,"Cannot stop recording the call. The stopmixmonitor application is disabled.\n");
2312                                 return -1;
2313                         } else {
2314                                 pbx_exec(callee_chan, stopmixmonitor_app, "");
2315                                 return AST_FEATURE_RETURN_SUCCESS;
2316                         }
2317                 }
2318
2319                 ast_log(LOG_WARNING,"Stopped MixMonitors are attached to the channel.\n");
2320         }
2321
2322         if (caller_chan && callee_chan) {
2323                 const char *touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR_FORMAT");
2324                 const char *touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR");
2325
2326                 if (!touch_format)
2327                         touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR_FORMAT");
2328
2329                 if (!touch_monitor)
2330                         touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR");
2331
2332                 if (touch_monitor) {
2333                         len = strlen(touch_monitor) + 50;
2334                         args = alloca(len);
2335                         touch_filename = alloca(len);
2336                         snprintf(touch_filename, len, "auto-%ld-%s", (long)time(NULL), touch_monitor);
2337                         snprintf(args, len, "%s.%s,b", touch_filename, (touch_format) ? touch_format : "wav");
2338                 } else {
2339                         caller_chan_id = ast_strdupa(S_COR(ast_channel_caller(caller_chan)->id.number.valid,
2340                                 ast_channel_caller(caller_chan)->id.number.str, ast_channel_name(caller_chan)));
2341                         callee_chan_id = ast_strdupa(S_COR(ast_channel_caller(callee_chan)->id.number.valid,
2342                                 ast_channel_caller(callee_chan)->id.number.str, ast_channel_name(callee_chan)));
2343                         len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
2344                         args = alloca(len);
2345                         touch_filename = alloca(len);
2346                         snprintf(touch_filename, len, "auto-%ld-%s-%s", (long)time(NULL), caller_chan_id, callee_chan_id);
2347                         snprintf(args, len, "%s.%s,b", touch_filename, S_OR(touch_format, "wav"));
2348                 }
2349
2350                 for( x = 0; x < strlen(args); x++) {
2351                         if (args[x] == '/')
2352                                 args[x] = '-';
2353                 }
2354
2355                 ast_verb(3, "User hit '%s' to record call. filename: %s\n", code, touch_filename);
2356
2357                 pbx_exec(callee_chan, mixmonitor_app, args);
2358                 pbx_builtin_setvar_helper(callee_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
2359                 pbx_builtin_setvar_helper(caller_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
2360                 return AST_FEATURE_RETURN_SUCCESS;
2361
2362         }
2363
2364         ast_log(LOG_NOTICE,"Cannot record the call. One or both channels have gone away.\n");
2365         return -1;
2366
2367 }
2368
2369 static int builtin_disconnect(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2370 {
2371         ast_verb(4, "User hit '%s' to disconnect call.\n", code);
2372         return AST_FEATURE_RETURN_HANGUP;
2373 }
2374
2375 /*!
2376  * \brief Find the context for the transfer
2377  * \param transferer
2378  * \param transferee
2379  *
2380  * Grab the TRANSFER_CONTEXT, if fails try grabbing macrocontext.
2381  * \return a context string
2382  */
2383 static const char *real_ctx(struct ast_channel *transferer, struct ast_channel *transferee)
2384 {
2385         const char *s = pbx_builtin_getvar_helper(transferer, "TRANSFER_CONTEXT");
2386         if (ast_strlen_zero(s)) {
2387                 s = pbx_builtin_getvar_helper(transferee, "TRANSFER_CONTEXT");
2388         }
2389         if (ast_strlen_zero(s)) { /* Use the non-macro context to transfer the call XXX ? */
2390                 s = ast_channel_macrocontext(transferer);
2391         }
2392         if (ast_strlen_zero(s)) {
2393                 s = ast_channel_context(transferer);
2394         }
2395         return s;
2396 }
2397
2398 /*!
2399  * \brief Blind transfer user to another extension
2400  * \param chan channel to be transfered
2401  * \param peer channel initiated blind transfer
2402  * \param config
2403  * \param code
2404  * \param data
2405  * \param sense  feature options
2406  *
2407  * Place chan on hold, check if transferred to parkinglot extension,
2408  * otherwise check extension exists and transfer caller.
2409  * \retval AST_FEATURE_RETURN_SUCCESS.
2410  * \retval -1 on failure.
2411  */
2412 static int builtin_blindtransfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2413 {
2414         struct ast_channel *transferer;
2415         struct ast_channel *transferee;
2416         struct ast_exten *park_exten;
2417         const char *transferer_real_context;
2418         char xferto[256] = "";
2419         int res;
2420
2421         ast_debug(1, "Executing Blind Transfer %s, %s (sense=%d) \n", ast_channel_name(chan), ast_channel_name(peer), sense);
2422         set_peers(&transferer, &transferee, peer, chan, sense);
2423         transferer_real_context = real_ctx(transferer, transferee);
2424
2425         /* Start autoservice on transferee while we talk to the transferer */
2426         ast_autoservice_start(transferee);
2427         ast_indicate(transferee, AST_CONTROL_HOLD);
2428
2429         /* Transfer */
2430         res = ast_stream_and_wait(transferer, "pbx-transfer", AST_DIGIT_ANY);
2431         if (res < 0) {
2432                 finishup(transferee);
2433                 return -1; /* error ? */
2434         }
2435         if (res > 0) { /* If they've typed a digit already, handle it */
2436                 xferto[0] = (char) res;
2437         }
2438
2439         res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
2440         if (res < 0) {  /* hangup or error, (would be 0 for invalid and 1 for valid) */
2441                 finishup(transferee);
2442                 return -1;
2443         }
2444         if (res == 0) {
2445                 if (xferto[0]) {
2446                         ast_log(LOG_WARNING, "Extension '%s' does not exist in context '%s'\n",
2447                                 xferto, transferer_real_context);
2448                 } else {
2449                         /* Does anyone care about this case? */
2450                         ast_log(LOG_WARNING, "No digits dialed.\n");
2451                 }
2452                 ast_stream_and_wait(transferer, "pbx-invalid", "");
2453                 finishup(transferee);
2454                 return AST_FEATURE_RETURN_SUCCESS;
2455         }
2456
2457         park_exten = get_parking_exten(xferto, transferer, transferer_real_context);
2458         if (park_exten) {
2459                 /* We are transfering the transferee to a parking lot. */
2460                 return xfer_park_call_helper(transferee, transferer, park_exten);
2461         }
2462
2463         /* Do blind transfer. */
2464         ast_verb(3, "Blind transferring %s to '%s' (context %s) priority 1\n",
2465                 ast_channel_name(transferee), xferto, transferer_real_context);
2466         ast_cel_report_event(transferer, AST_CEL_BLINDTRANSFER, NULL, xferto, transferee);
2467         pbx_builtin_setvar_helper(transferer, "BLINDTRANSFER", ast_channel_name(transferee));
2468         pbx_builtin_setvar_helper(transferee, "BLINDTRANSFER", ast_channel_name(transferer));
2469         finishup(transferee);
2470         ast_channel_lock(transferer);
2471         if (!ast_channel_cdr(transferer)) { /* this code should never get called (in a perfect world) */
2472                 ast_channel_cdr_set(transferer, ast_cdr_alloc());
2473                 if (ast_channel_cdr(transferer)) {
2474                         ast_cdr_init(ast_channel_cdr(transferer), transferer); /* initialize our channel's cdr */
2475                         ast_cdr_start(ast_channel_cdr(transferer));
2476                 }
2477         }
2478         ast_channel_unlock(transferer);
2479         if (ast_channel_cdr(transferer)) {
2480                 struct ast_cdr *swap = ast_channel_cdr(transferer);
2481
2482                 ast_debug(1,
2483                         "transferer=%s; transferee=%s; lastapp=%s; lastdata=%s; chan=%s; dstchan=%s\n",
2484                         ast_channel_name(transferer), ast_channel_name(transferee), ast_channel_cdr(transferer)->lastapp,
2485                         ast_channel_cdr(transferer)->lastdata, ast_channel_cdr(transferer)->channel,
2486                         ast_channel_cdr(transferer)->dstchannel);
2487                 ast_debug(1, "TRANSFEREE; lastapp=%s; lastdata=%s, chan=%s; dstchan=%s\n",
2488                         ast_channel_cdr(transferee)->lastapp, ast_channel_cdr(transferee)->lastdata, ast_channel_cdr(transferee)->channel,
2489                         ast_channel_cdr(transferee)->dstchannel);
2490                 ast_debug(1, "transferer_real_context=%s; xferto=%s\n",
2491                         transferer_real_context, xferto);
2492                 /* swap cdrs-- it will save us some time & work */
2493                 ast_channel_cdr_set(transferer, ast_channel_cdr(transferee));
2494                 ast_channel_cdr_set(transferee, swap);
2495         }
2496         if (!ast_channel_pbx(transferee)) {
2497                 /* Doh!  Use our handy async_goto functions */
2498                 ast_debug(1, "About to ast_async_goto %s.\n", ast_channel_name(transferee));
2499                 if (ast_async_goto(transferee, transferer_real_context, xferto, 1)) {
2500                         ast_log(LOG_WARNING, "Async goto failed :-(\n");
2501                 }
2502
2503                 /* The transferee is masqueraded and the original bridged channels can be hungup. */
2504                 res = -1;
2505         } else {
2506                 /* Set the transferee's new extension, since it exists, using transferer context */
2507                 ast_debug(1, "About to explicit goto %s, it has a PBX.\n", ast_channel_name(transferee));
2508                 ast_set_flag(ast_channel_flags(transferee), AST_FLAG_BRIDGE_HANGUP_DONT); /* don't let the after-bridge code run the h-exten */
2509                 set_c_e_p(transferee, transferer_real_context, xferto, 0);
2510
2511                 /*
2512                  * Break the bridge.  The transferee needs to resume executing
2513                  * dialplan at the xferto location.
2514                  */
2515                 res = AST_FEATURE_RETURN_SUCCESSBREAK;
2516         }
2517         check_goto_on_transfer(transferer);
2518         return res;
2519 }
2520
2521 /*!
2522  * \brief make channels compatible
2523  * \param c
2524  * \param newchan
2525  * \retval 0 on success.
2526  * \retval -1 on failure.
2527  */
2528 static int check_compat(struct ast_channel *c, struct ast_channel *newchan)
2529 {
2530         if (ast_channel_make_compatible(c, newchan) < 0) {
2531                 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n",
2532                         ast_channel_name(c), ast_channel_name(newchan));
2533                 ast_hangup(newchan);
2534                 return -1;
2535         }
2536         return 0;
2537 }
2538
2539 /*!
2540  * \internal
2541  * \brief Builtin attended transfer failed cleanup.
2542  * \since 10.0
2543  *
2544  * \param transferee Party A in the transfer.
2545  * \param transferer Party B in the transfer.
2546  * \param connected_line Saved connected line info about party A.
2547  *
2548  * \note The connected_line data is freed.
2549  *
2550  * \return Nothing
2551  */
2552 static void atxfer_fail_cleanup(struct ast_channel *transferee, struct ast_channel *transferer, struct ast_party_connected_line *connected_line)
2553 {
2554         finishup(transferee);
2555
2556         /*
2557          * Restore party B connected line info about party A.
2558          *
2559          * Party B was the caller to party C and is the last known mode
2560          * for party B.
2561          */
2562         if (ast_channel_connected_line_sub(transferee, transferer, connected_line, 0) &&
2563                 ast_channel_connected_line_macro(transferee, transferer, connected_line, 1, 0)) {
2564                 ast_channel_update_connected_line(transferer, connected_line, NULL);
2565         }
2566         ast_party_connected_line_free(connected_line);
2567 }
2568
2569 /*!
2570  * \brief Attended transfer
2571  * \param chan transfered user
2572  * \param peer person transfering call
2573  * \param config
2574  * \param code
2575  * \param sense feature options
2576  *
2577  * \param data
2578  * Get extension to transfer to, if you cannot generate channel (or find extension)
2579  * return to host channel. After called channel answered wait for hangup of transferer,
2580  * bridge call between transfer peer (taking them off hold) to attended transfer channel.
2581  *
2582  * \return -1 on failure
2583  */
2584 static int builtin_atxfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2585 {
2586         struct ast_channel *transferer;/* Party B */
2587         struct ast_channel *transferee;/* Party A */
2588         struct ast_exten *park_exten;
2589         const char *transferer_real_context;
2590         char xferto[256] = "";
2591         int res;
2592         int outstate=0;
2593         struct ast_channel *newchan;
2594         struct ast_channel *xferchan;
2595         struct ast_bridge_thread_obj *tobj;
2596         struct ast_bridge_config bconfig;
2597         int l;
2598         struct ast_party_connected_line connected_line;
2599         struct ast_datastore *features_datastore;
2600         struct ast_dial_features *dialfeatures;
2601         char *transferer_tech;
2602         char *transferer_name;
2603         char *transferer_name_orig;
2604         char *dash;
2605
2606         ast_debug(1, "Executing Attended Transfer %s, %s (sense=%d) \n", ast_channel_name(chan), ast_channel_name(peer), sense);
2607         set_peers(&transferer, &transferee, peer, chan, sense);
2608         transferer_real_context = real_ctx(transferer, transferee);
2609
2610         /* Start autoservice on transferee while we talk to the transferer */
2611         ast_autoservice_start(transferee);
2612         ast_indicate(transferee, AST_CONTROL_HOLD);
2613
2614         /* Transfer */
2615         res = ast_stream_and_wait(transferer, "pbx-transfer", AST_DIGIT_ANY);
2616         if (res < 0) {
2617                 finishup(transferee);
2618                 return -1;
2619         }
2620         if (res > 0) { /* If they've typed a digit already, handle it */
2621                 xferto[0] = (char) res;
2622         }
2623
2624         /* this is specific of atxfer */
2625         res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
2626         if (res < 0) {  /* hangup or error, (would be 0 for invalid and 1 for valid) */
2627                 finishup(transferee);
2628                 return -1;
2629         }
2630         l = strlen(xferto);
2631         if (res == 0) {
2632                 if (l) {
2633                         ast_log(LOG_WARNING, "Extension '%s' does not exist in context '%s'\n",
2634                                 xferto, transferer_real_context);
2635                 } else {
2636                         /* Does anyone care about this case? */
2637                         ast_log(LOG_WARNING, "No digits dialed for atxfer.\n");
2638                 }
2639                 ast_stream_and_wait(transferer, "pbx-invalid", "");
2640                 finishup(transferee);
2641                 return AST_FEATURE_RETURN_SUCCESS;
2642         }
2643
2644         park_exten = get_parking_exten(xferto, transferer, transferer_real_context);
2645         if (park_exten) {
2646                 /* We are transfering the transferee to a parking lot. */
2647                 return xfer_park_call_helper(transferee, transferer, park_exten);
2648         }
2649
2650         /*
2651          * Append context to dialed transfer number.
2652          *
2653          * NOTE: The local channel needs the /n flag so party C will use
2654          * the feature flags set by the dialplan when calling that
2655          * party.
2656          */
2657         snprintf(xferto + l, sizeof(xferto) - l, "@%s/n", transferer_real_context);
2658
2659         /* If we are performing an attended transfer and we have two channels involved then
2660            copy sound file information to play upon attended transfer completion */
2661         if (transferee) {
2662                 const char *chan1_attended_sound = pbx_builtin_getvar_helper(transferer, "ATTENDED_TRANSFER_COMPLETE_SOUND");
2663                 const char *chan2_attended_sound = pbx_builtin_getvar_helper(transferee, "ATTENDED_TRANSFER_COMPLETE_SOUND");
2664
2665                 if (!ast_strlen_zero(chan1_attended_sound)) {
2666                         pbx_builtin_setvar_helper(transferer, "BRIDGE_PLAY_SOUND", chan1_attended_sound);
2667                 }
2668                 if (!ast_strlen_zero(chan2_attended_sound)) {
2669                         pbx_builtin_setvar_helper(transferee, "BRIDGE_PLAY_SOUND", chan2_attended_sound);
2670                 }
2671         }
2672
2673         /* Extract redial transferer information from the channel name. */
2674         transferer_name_orig = ast_strdupa(ast_channel_name(transferer));
2675         transferer_name = ast_strdupa(transferer_name_orig);
2676         transferer_tech = strsep(&transferer_name, "/");
2677         dash = strrchr(transferer_name, '-');
2678         if (dash) {
2679                 /* Trim off channel name sequence/serial number. */
2680                 *dash = '\0';
2681         }
2682
2683         /* Stop autoservice so we can monitor all parties involved in the transfer. */
2684         if (ast_autoservice_stop(transferee) < 0) {
2685                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2686                 return -1;
2687         }
2688
2689         /* Save connected line info for party B about party A in case transfer fails. */
2690         ast_party_connected_line_init(&connected_line);
2691         ast_channel_lock(transferer);
2692         ast_party_connected_line_copy(&connected_line, ast_channel_connected(transferer));
2693         ast_channel_unlock(transferer);
2694         connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
2695
2696         /* Dial party C */
2697         newchan = feature_request_and_dial(transferer, transferer_name_orig, transferer,
2698                 transferee, "Local", ast_channel_nativeformats(transferer), xferto,
2699                 atxfernoanswertimeout, &outstate, ast_channel_language(transferer));
2700         ast_debug(2, "Dial party C result: newchan:%d, outstate:%d\n", !!newchan, outstate);
2701
2702         if (!ast_check_hangup(transferer)) {
2703                 int hangup_dont = 0;
2704
2705                 /* Transferer (party B) is up */
2706                 ast_debug(1, "Actually doing an attended transfer.\n");
2707
2708                 /* Start autoservice on transferee while the transferer deals with party C. */
2709                 ast_autoservice_start(transferee);
2710
2711                 ast_indicate(transferer, -1);
2712                 if (!newchan) {
2713                         /* any reason besides user requested cancel and busy triggers the failed sound */
2714                         switch (outstate) {
2715                         case AST_CONTROL_UNHOLD:/* Caller requested cancel or party C answer timeout. */
2716                         case AST_CONTROL_BUSY:
2717                         case AST_CONTROL_CONGESTION:
2718                                 if (ast_stream_and_wait(transferer, xfersound, "")) {
2719                                         ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
2720                                 }
2721                                 break;
2722                         default:
2723                                 if (ast_stream_and_wait(transferer, xferfailsound, "")) {
2724                                         ast_log(LOG_WARNING, "Failed to play transfer failed sound!\n");
2725                                 }
2726                                 break;
2727                         }
2728                         atxfer_fail_cleanup(transferee, transferer, &connected_line);
2729                         return AST_FEATURE_RETURN_SUCCESS;
2730                 }
2731
2732                 if (check_compat(transferer, newchan)) {
2733                         if (ast_stream_and_wait(transferer, xferfailsound, "")) {
2734                                 ast_log(LOG_WARNING, "Failed to play transfer failed sound!\n");
2735                         }
2736                         atxfer_fail_cleanup(transferee, transferer, &connected_line);
2737                         return AST_FEATURE_RETURN_SUCCESS;
2738                 }
2739                 memset(&bconfig,0,sizeof(struct ast_bridge_config));
2740                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_DISCONNECT);
2741                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_DISCONNECT);
2742
2743                 /*
2744                  * ast_bridge_call clears AST_FLAG_BRIDGE_HANGUP_DONT, but we
2745                  * don't want that to happen here because the transferer is in
2746                  * another bridge already.
2747                  */
2748                 if (ast_test_flag(ast_channel_flags(transferer), AST_FLAG_BRIDGE_HANGUP_DONT)) {
2749                         hangup_dont = 1;
2750                 }
2751
2752                 /*
2753                  * Don't let the after-bridge code run the h-exten.  It is the
2754                  * wrong bridge to run the h-exten after.
2755                  */
2756                 ast_set_flag(ast_channel_flags(transferer), AST_FLAG_BRIDGE_HANGUP_DONT);
2757
2758                 /*
2759                  * Let party B and C talk as long as they want while party A
2760                  * languishes in autoservice listening to MOH.
2761                  */
2762                 ast_bridge_call(transferer, newchan, &bconfig);
2763
2764                 if (hangup_dont) {
2765                         /* Restore the AST_FLAG_BRIDGE_HANGUP_DONT flag */
2766                         ast_set_flag(ast_channel_flags(transferer), AST_FLAG_BRIDGE_HANGUP_DONT);
2767                 }
2768
2769                 if (ast_check_hangup(newchan) || !ast_check_hangup(transferer)) {
2770                         ast_hangup(newchan);
2771                         if (ast_stream_and_wait(transferer, xfersound, "")) {
2772                                 ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
2773                         }
2774                         atxfer_fail_cleanup(transferee, transferer, &connected_line);
2775                         return AST_FEATURE_RETURN_SUCCESS;
2776                 }
2777
2778                 /* Transferer (party B) is confirmed hung up at this point. */
2779                 if (check_compat(transferee, newchan)) {
2780                         finishup(transferee);
2781                         ast_party_connected_line_free(&connected_line);
2782                         return -1;
2783                 }
2784
2785                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2786                 if ((ast_autoservice_stop(transferee) < 0)
2787                         || (ast_waitfordigit(transferee, 100) < 0)
2788                         || (ast_waitfordigit(newchan, 100) < 0)
2789                         || ast_check_hangup(transferee)
2790                         || ast_check_hangup(newchan)) {
2791                         ast_hangup(newchan);
2792                         ast_party_connected_line_free(&connected_line);
2793                         return -1;
2794                 }
2795         } else if (!ast_check_hangup(transferee)) {
2796                 /* Transferer (party B) has hung up at this point.  Doing blonde transfer. */
2797                 ast_debug(1, "Actually doing a blonde transfer.\n");
2798
2799                 if (!newchan && !atxferdropcall) {
2800                         /* Party C is not available, try to call party B back. */
2801                         unsigned int tries = 0;
2802
2803                         if (ast_strlen_zero(transferer_name) || ast_strlen_zero(transferer_tech)) {
2804                                 ast_log(LOG_WARNING,
2805                                         "Transferer channel name: '%s' cannot be used for callback.\n",
2806                                         transferer_name_orig);
2807                                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2808                                 ast_party_connected_line_free(&connected_line);
2809                                 return -1;
2810                         }
2811
2812                         tries = 0;
2813                         for (;;) {
2814                                 /* Try to get party B back. */
2815                                 ast_debug(1, "We're trying to callback %s/%s\n",
2816                                         transferer_tech, transferer_name);
2817                                 newchan = feature_request_and_dial(transferer, transferer_name_orig,
2818                                         transferee, transferee, transferer_tech,
2819                                         ast_channel_nativeformats(transferee), transferer_name,
2820                                         atxfernoanswertimeout, &outstate, ast_channel_language(transferer));
2821                                 ast_debug(2, "Dial party B result: newchan:%d, outstate:%d\n",
2822                                         !!newchan, outstate);
2823                                 if (newchan) {
2824                                         /*
2825                                          * We have recalled party B (newchan).  We need to give this
2826                                          * call leg the same feature flags as the original party B call
2827                                          * leg.
2828                                          */
2829                                         ast_channel_lock(transferer);
2830                                         features_datastore = ast_channel_datastore_find(transferer,
2831                                                 &dial_features_info, NULL);
2832                                         if (features_datastore && (dialfeatures = features_datastore->data)) {
2833                                                 struct ast_flags my_features = { 0 };
2834                                                 struct ast_flags peer_features = { 0 };
2835
2836                                                 ast_copy_flags(&my_features, &dialfeatures->my_features,
2837                                                         AST_FLAGS_ALL);
2838                                                 ast_copy_flags(&peer_features, &dialfeatures->peer_features,
2839                                                         AST_FLAGS_ALL);
2840                                                 ast_channel_unlock(transferer);
2841                                                 add_features_datastore(newchan, &my_features, &peer_features);
2842                                         } else {
2843                                                 ast_channel_unlock(transferer);
2844                                         }
2845                                         break;
2846                                 }
2847                                 if (ast_check_hangup(transferee)) {
2848                                         break;
2849                                 }
2850
2851                                 ++tries;
2852                                 if (atxfercallbackretries <= tries) {
2853                                         /* No more callback tries remaining. */
2854                                         break;
2855                                 }
2856
2857                                 if (atxferloopdelay) {
2858                                         /* Transfer failed, sleeping */
2859                                         ast_debug(1, "Sleeping for %d ms before retrying atxfer.\n",
2860                                                 atxferloopdelay);
2861                                         ast_safe_sleep(transferee, atxferloopdelay);
2862                                         if (ast_check_hangup(transferee)) {
2863                                                 ast_party_connected_line_free(&connected_line);
2864                                                 return -1;
2865                                         }
2866                                 }
2867
2868                                 /* Retry dialing party C. */
2869                                 ast_debug(1, "We're retrying to call %s/%s\n", "Local", xferto);
2870                                 newchan = feature_request_and_dial(transferer, transferer_name_orig,
2871                                         transferer, transferee, "Local",
2872                                         ast_channel_nativeformats(transferee), xferto,
2873                                         atxfernoanswertimeout, &outstate, ast_channel_language(transferer));
2874                                 ast_debug(2, "Redial party C result: newchan:%d, outstate:%d\n",
2875                                         !!newchan, outstate);
2876                                 if (newchan || ast_check_hangup(transferee)) {
2877                                         break;
2878                                 }
2879                         }
2880                 }
2881                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2882                 if (!newchan) {
2883                         /* No party C or could not callback party B. */
2884                         ast_party_connected_line_free(&connected_line);
2885                         return -1;
2886                 }
2887
2888                 /* newchan is up, we should prepare transferee and bridge them */
2889                 if (ast_check_hangup(newchan)) {
2890                         ast_hangup(newchan);
2891                         ast_party_connected_line_free(&connected_line);
2892                         return -1;
2893                 }
2894                 if (check_compat(transferee, newchan)) {
2895                         ast_party_connected_line_free(&connected_line);
2896                         return -1;
2897                 }
2898         } else {
2899                 /*
2900                  * Both the transferer and transferee have hungup.  If newchan
2901                  * is up, hang it up as it has no one to talk to.
2902                  */
2903                 ast_debug(1, "Everyone is hungup.\n");
2904                 if (newchan) {
2905                         ast_hangup(newchan);
2906                 }
2907                 ast_party_connected_line_free(&connected_line);
2908                 return -1;
2909         }
2910
2911         /* Initiate the channel transfer of party A to party C (or recalled party B). */
2912         ast_cel_report_event(transferee, AST_CEL_ATTENDEDTRANSFER, NULL, NULL, newchan);
2913
2914         xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", ast_channel_linkedid(transferee), 0, "Transfered/%s", ast_channel_name(transferee));
2915         if (!xferchan) {
2916                 ast_hangup(newchan);
2917                 ast_party_connected_line_free(&connected_line);
2918                 return -1;
2919         }
2920
2921         /* Give party A a momentary ringback tone during transfer. */
2922         ast_channel_visible_indication_set(xferchan, AST_CONTROL_RINGING);
2923
2924         /* Make formats okay */
2925         ast_format_copy(ast_channel_readformat(xferchan), ast_channel_readformat(transferee));
2926         ast_format_copy(ast_channel_writeformat(xferchan), ast_channel_writeformat(transferee));
2927
2928         ast_channel_masquerade(xferchan, transferee);
2929         ast_explicit_goto(xferchan, ast_channel_context(transferee), ast_channel_exten(transferee), ast_channel_priority(transferee));
2930         ast_channel_state_set(xferchan, AST_STATE_UP);
2931         ast_clear_flag(ast_channel_flags(xferchan), AST_FLAGS_ALL);
2932
2933         /* Do the masquerade manually to make sure that is is completed. */
2934         ast_do_masquerade(xferchan);
2935
2936         ast_channel_state_set(newchan, AST_STATE_UP);
2937         ast_clear_flag(ast_channel_flags(newchan), AST_FLAGS_ALL);
2938         tobj = ast_calloc(1, sizeof(*tobj));
2939         if (!tobj) {
2940                 ast_hangup(xferchan);
2941                 ast_hangup(newchan);
2942                 ast_party_connected_line_free(&connected_line);
2943                 return -1;
2944         }
2945
2946         tobj->chan = newchan;
2947         tobj->peer = xferchan;
2948         tobj->bconfig = *config;
2949
2950         ast_channel_lock(newchan);
2951         features_datastore = ast_channel_datastore_find(newchan, &dial_features_info, NULL);
2952         if (features_datastore && (dialfeatures = features_datastore->data)) {
2953                 ast_copy_flags(&tobj->bconfig.features_callee, &dialfeatures->my_features,
2954                         AST_FLAGS_ALL);
2955         }
2956         ast_channel_unlock(newchan);
2957
2958         ast_channel_lock(xferchan);
2959         features_datastore = ast_channel_datastore_find(xferchan, &dial_features_info, NULL);
2960         if (features_datastore && (dialfeatures = features_datastore->data)) {
2961                 ast_copy_flags(&tobj->bconfig.features_caller, &dialfeatures->my_features,
2962                         AST_FLAGS_ALL);
2963         }
2964         ast_channel_unlock(xferchan);
2965
2966         if (tobj->bconfig.end_bridge_callback_data_fixup) {
2967                 tobj->bconfig.end_bridge_callback_data_fixup(&tobj->bconfig, tobj->peer, tobj->chan);
2968         }
2969
2970         /*
2971          * xferchan is transferee, and newchan is the transfer target
2972          * So...in a transfer, who is the caller and who is the callee?
2973          *
2974          * When the call is originally made, it is clear who is caller and callee.
2975          * When a transfer occurs, it is my humble opinion that the transferee becomes
2976          * the caller, and the transfer target is the callee.
2977          *
2978          * The problem is that these macros were set with the intention of the original
2979          * caller and callee taking those roles.  A transfer can totally mess things up,
2980          * to be technical.  What sucks even more is that you can't effectively change
2981          * the macros in the dialplan during the call from the transferer to the transfer
2982          * target because the transferee is stuck with whatever role he originally had.
2983          *
2984          * I think the answer here is just to make sure that it is well documented that
2985          * during a transfer, the transferee is the "caller" and the transfer target
2986          * is the "callee."
2987          *
2988          * This means that if party B calls party A, and party B transfers party A to
2989          * party C, then A has switched roles for the call.  Now party A will have the
2990          * caller macro called on his channel instead of the callee macro.
2991          *
2992          * Luckily, the method by which the party B to party C bridge is
2993          * launched above ensures that the transferee is the "chan" on
2994          * the bridge and the transfer target is the "peer," so my idea
2995          * for the roles post-transfer does not require extensive code
2996          * changes.
2997          */
2998
2999         /* Transfer party C connected line to party A */
3000         ast_channel_lock(transferer);
3001         /*
3002          * Due to a limitation regarding when callerID is set on a Local channel,
3003          * we use the transferer's connected line information here.
3004          */
3005         ast_party_connected_line_copy(&connected_line, ast_channel_connected(transferer));
3006         ast_channel_unlock(transferer);
3007         connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
3008         if (ast_channel_connected_line_sub(newchan, xferchan, &connected_line, 0) &&
3009                 ast_channel_connected_line_macro(newchan, xferchan, &connected_line, 1, 0)) {
3010                 ast_channel_update_connected_line(xferchan, &connected_line, NULL);
3011         }
3012
3013         /* Transfer party A connected line to party C */
3014         ast_channel_lock(xferchan);
3015         ast_connected_line_copy_from_caller(&connected_line, ast_channel_caller(xferchan));
3016         ast_channel_unlock(xferchan);
3017         connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
3018         if (ast_channel_connected_line_sub(xferchan, newchan, &connected_line, 0) &&
3019                 ast_channel_connected_line_macro(xferchan, newchan, &connected_line, 0, 0)) {
3020                 ast_channel_update_connected_line(newchan, &connected_line, NULL);
3021         }
3022
3023         if (ast_stream_and_wait(newchan, xfersound, ""))
3024                 ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
3025         bridge_call_thread_launch(tobj);
3026
3027         ast_party_connected_line_free(&connected_line);
3028         return -1;/* The transferee is masqueraded and the original bridged channels can be hung