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