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