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