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