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