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