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