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