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