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