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