7b856e132d65461f37d36b5ede6f5c60e031f829
[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         ast_channel_clear_softhangup(xferchan, AST_SOFTHANGUP_ALL);
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, struct ast_format_cap *cap, 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         struct ast_format tmp_fmt;
1319         if (!(test_channel1 = ast_channel_alloc(0, AST_STATE_DOWN, NULL, NULL, NULL,
1320         NULL, NULL, 0, 0, "TestChannel1"))) {
1321                 return NULL;
1322         }
1323
1324         /* normally this is done in the channel driver */
1325         ast_format_cap_add(test_channel1->nativeformats, ast_format_set(&tmp_fmt, AST_FORMAT_GSM, 0));
1326
1327         ast_format_set(&test_channel1->writeformat, AST_FORMAT_GSM, 0);
1328         ast_format_set(&test_channel1->rawwriteformat, AST_FORMAT_GSM, 0);
1329         ast_format_set(&test_channel1->readformat, AST_FORMAT_GSM, 0);
1330         ast_format_set(&test_channel1->rawreadformat, AST_FORMAT_GSM, 0);
1331
1332         test_channel1->tech = fake_tech;
1333
1334         return test_channel1;
1335 }
1336
1337 static int unpark_test_channel(struct ast_channel *toremove, struct ast_park_call_args *args)
1338 {
1339         struct ast_context *con;
1340         struct parkeduser *pu_toremove;
1341         args->pu->notquiteyet = 1; /* go ahead and stop processing the test parking */
1342         AST_LIST_LOCK(&args->pu->parkinglot->parkings);
1343         AST_LIST_TRAVERSE_SAFE_BEGIN(&args->pu->parkinglot->parkings, pu_toremove, list) {
1344                 con = ast_context_find(args->pu->parkinglot->parking_con);
1345                 if (con) {
1346                         if (ast_context_remove_extension2(con, args->pu->parkingexten, 1, NULL, 0)) {
1347                                 ast_log(LOG_WARNING, "Whoa, failed to remove the parking extension!\n");
1348                                 return -1;
1349                         } else {
1350                                 notify_metermaids(args->pu->parkingexten, pu_toremove->parkinglot->parking_con, AST_DEVICE_NOT_INUSE);
1351                         }
1352                 } else {
1353                         ast_log(LOG_WARNING, "Whoa, no parking context?\n");
1354                         return -1;
1355                 }
1356                 if (pu_toremove == args->pu) {
1357                         AST_LIST_REMOVE_CURRENT(list);
1358                         break;
1359                 }
1360         }
1361         AST_LIST_TRAVERSE_SAFE_END;
1362         AST_LIST_UNLOCK(&args->pu->parkinglot->parkings);
1363
1364         /* the only way this would be unsafe is if a timeout occurred, which is set at 45 sec */
1365         ast_free(args->pu);
1366         args->pu = NULL;
1367
1368         ast_hangup(toremove);
1369         return 0;
1370 }
1371
1372 AST_TEST_DEFINE(features_test)
1373 {
1374         int saved_parkeddynamic;
1375         struct ast_channel *test_channel1 = NULL;
1376         struct ast_channel *parked_chan = NULL;
1377         struct ast_parkinglot *dynlot = NULL;
1378         struct ast_park_call_args args = {
1379                 .timeout = DEFAULT_PARK_TIME,
1380         };
1381
1382         int res = -1;
1383
1384         static const struct ast_channel_tech fake_tech = {
1385                 .fixup = fake_fixup, /* silence warning from masquerade */
1386         };
1387
1388         static const char unique_parkinglot[] = "myuniquetestparkinglot3141592654";
1389         static const char parkinglot_range[] = "750-760";
1390
1391         switch (cmd) {
1392         case TEST_INIT:
1393                 info->name = "features_test";
1394                 info->category = "/main/features/";
1395                 info->summary = "Features unit test";
1396                 info->description =
1397                         "Tests whether parking respects PARKINGLOT settings";
1398                 return AST_TEST_NOT_RUN;
1399         case TEST_EXECUTE:
1400                 break;
1401         }
1402
1403         /* changing a config option is a bad practice, but must be done in this case */
1404         saved_parkeddynamic = parkeddynamic;
1405         parkeddynamic = 1;
1406
1407         if (!(test_channel1 = create_test_channel(&fake_tech))) {
1408                 goto exit_features_test;
1409         }
1410
1411         ast_test_status_update(test, "Test parking functionality with defaults\n");
1412         if (park_call_full(test_channel1, NULL, &args)) {
1413                 goto exit_features_test;
1414         }
1415         if (unpark_test_channel(test_channel1, &args)) {
1416                 goto exit_features_test;
1417         }
1418
1419         ast_test_status_update(test, "Check that certain parking options are respected\n");
1420         if (!(test_channel1 = create_test_channel(&fake_tech))) {
1421                 goto exit_features_test;
1422         }
1423         pbx_builtin_setvar_helper(test_channel1, "PARKINGLOT", unique_parkinglot);
1424         pbx_builtin_setvar_helper(test_channel1, "PARKINGDYNPOS", parkinglot_range);
1425         if (park_call_full(test_channel1, NULL, &args)) {
1426                 goto exit_features_test;
1427         }
1428         /* grab newly created parking lot for destruction in the end */
1429         dynlot = args.pu->parkinglot;
1430         if (!args.pu->parkingnum == 750 || strcasecmp(args.pu->parkinglot->name, unique_parkinglot)) {
1431                 ast_test_status_update(test, "Parking settings were not respected\n");
1432                 goto exit_features_test;
1433         } else {
1434                 ast_test_status_update(test, "Parking settings for non-masquerading park verified\n");
1435         }
1436         if (unpark_test_channel(test_channel1, &args)) {
1437                 goto exit_features_test;
1438         }
1439
1440         ast_test_status_update(test, "Check #2 that certain parking options are respected\n");
1441         if (!(test_channel1 = create_test_channel(&fake_tech))) {
1442                 goto exit_features_test;
1443         }
1444         pbx_builtin_setvar_helper(test_channel1, "PARKINGLOT", unique_parkinglot);
1445         pbx_builtin_setvar_helper(test_channel1, "PARKINGDYNPOS", parkinglot_range);
1446         if (masq_park_call(test_channel1, NULL, 0, NULL, 0, &args) == AST_FEATURE_RETURN_PARKFAILED) {
1447                 goto exit_features_test;
1448         }
1449         /* hangup zombie channel */
1450         ast_hangup(test_channel1);
1451         test_channel1 = NULL;
1452         if (!args.pu->parkingnum == 750 || strcasecmp(args.pu->parkinglot->name, unique_parkinglot)) {
1453                 ast_test_status_update(test, "Parking settings were not respected\n");
1454                 goto exit_features_test;
1455         } else {
1456                 ast_test_status_update(test, "Parking settings for masquerading park verified\n");
1457         }
1458         /* find the real channel */
1459         parked_chan = ast_channel_get_by_name("TestChannel1");
1460         if (unpark_test_channel(parked_chan, &args)) {
1461                 goto exit_features_test;
1462         }
1463
1464         res = 0;
1465
1466 exit_features_test:
1467
1468         if (test_channel1) {
1469                 ast_hangup(test_channel1);
1470         }
1471
1472         /* careful, if PARKINGDYNCONTEXT is tested, need to delete context */
1473         ao2_unlink(parkinglots, dynlot);
1474         parkeddynamic = saved_parkeddynamic;
1475         return res ? AST_TEST_FAIL : AST_TEST_PASS;
1476 }
1477 #endif
1478
1479
1480 /*!
1481  * \brief set caller and callee according to the direction
1482  * \param caller, callee, peer, chan, sense
1483  *
1484  * Detect who triggered feature and set callee/caller variables accordingly
1485 */
1486 static void set_peers(struct ast_channel **caller, struct ast_channel **callee,
1487         struct ast_channel *peer, struct ast_channel *chan, int sense)
1488 {
1489         if (sense == FEATURE_SENSE_PEER) {
1490                 *caller = peer;
1491                 *callee = chan;
1492         } else {
1493                 *callee = peer;
1494                 *caller = chan;
1495         }
1496 }
1497
1498 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)
1499 {
1500         int res = 0;
1501
1502         if (args) {
1503                 ast_debug(1, "Parkinglot specified for builtin_parkcall: %s\n", args->parkinglot->name);
1504         }
1505
1506         /* we used to set chan's exten and priority to "s" and 1
1507            here, but this generates (in some cases) an invalid
1508            extension, and if "s" exists, could errantly
1509            cause execution of extensions you don't expect. It
1510            makes more sense to let nature take its course
1511            when chan finishes, and let the pbx do its thing
1512            and hang up when the park is over.
1513         */
1514         if (chan->_state != AST_STATE_UP)
1515                 res = ast_answer(chan);
1516         if (!res)
1517                 res = ast_safe_sleep(chan, 1000);
1518
1519         if (!res) { /* one direction used to call park_call.... */
1520                 struct ast_channel *parker;
1521                 struct ast_channel *parkee;
1522                 set_peers(&parker, &parkee, peer, chan, sense);
1523                 res = masq_park_call_announce(parkee, parker, args);
1524                 /* PBX should hangup zombie channel if a masquerade actually occurred (res=0) */
1525         }
1526
1527         return res;
1528 }
1529
1530 /*! 
1531  * \brief support routing for one touch call parking
1532  * \param chan channel parking call
1533  * \param peer channel to be parked
1534  * \param config unsed
1535  * \param code unused
1536  * \param sense feature options
1537  *
1538  * \param data
1539  * Setup channel, set return exten,priority to 's,1'
1540  * answer chan, sleep chan, park call
1541 */
1542 static int builtin_parkcall(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
1543 {
1544         return parkcall_helper(chan, peer, config, code, sense, NULL);
1545 }
1546
1547 /*! \brief Play message to both caller and callee in bridged call, plays synchronously, autoservicing the
1548         other channel during the message, so please don't use this for very long messages
1549  */
1550 static int play_message_in_bridged_call(struct ast_channel *caller_chan, struct ast_channel *callee_chan, const char *audiofile)
1551 {
1552         /* First play for caller, put other channel on auto service */
1553         if (ast_autoservice_start(callee_chan))
1554                 return -1;
1555         ast_autoservice_ignore(callee_chan, AST_FRAME_DTMF_END);
1556         if (ast_stream_and_wait(caller_chan, audiofile, "")) {
1557                 ast_log(LOG_WARNING, "Failed to play automon message!\n");
1558                 ast_autoservice_stop(callee_chan);
1559                 return -1;
1560         }
1561         if (ast_autoservice_stop(callee_chan))
1562                 return -1;
1563         /* Then play for callee, put other channel on auto service */
1564         if (ast_autoservice_start(caller_chan))
1565                 return -1;
1566         ast_autoservice_ignore(caller_chan, AST_FRAME_DTMF_END);
1567         if (ast_stream_and_wait(callee_chan, audiofile, "")) {
1568                 ast_log(LOG_WARNING, "Failed to play automon message !\n");
1569                 ast_autoservice_stop(caller_chan);
1570                 return -1;
1571         }
1572         if (ast_autoservice_stop(caller_chan))
1573                 return -1;
1574         return(0);
1575 }
1576
1577 /*!
1578  * \brief Monitor a channel by DTMF
1579  * \param chan channel requesting monitor
1580  * \param peer channel to be monitored
1581  * \param config
1582  * \param code
1583  * \param sense feature options
1584  *
1585  * \param data
1586  * Check monitor app enabled, setup channels, both caller/callee chans not null
1587  * get TOUCH_MONITOR variable for filename if exists, exec monitor app.
1588  * \retval AST_FEATURE_RETURN_SUCCESS on success.
1589  * \retval -1 on error.
1590 */
1591 static int builtin_automonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
1592 {
1593         char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
1594         int x = 0;
1595         size_t len;
1596         struct ast_channel *caller_chan, *callee_chan;
1597         const char *automon_message_start = NULL;
1598         const char *automon_message_stop = NULL;
1599
1600         if (!monitor_ok) {
1601                 ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
1602                 return -1;
1603         }
1604
1605         if (!monitor_app && !(monitor_app = pbx_findapp("Monitor"))) {
1606                 monitor_ok = 0;
1607                 ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
1608                 return -1;
1609         }
1610
1611         set_peers(&caller_chan, &callee_chan, peer, chan, sense);
1612         if (caller_chan) {      /* Find extra messages */
1613                 automon_message_start = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_START");
1614                 automon_message_stop = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_STOP");
1615         }
1616
1617         if (!ast_strlen_zero(courtesytone)) {   /* Play courtesy tone if configured */
1618                 if(play_message_in_bridged_call(caller_chan, callee_chan, courtesytone) == -1) {
1619                         return -1;
1620                 }
1621         }
1622         
1623         if (callee_chan->monitor) {
1624                 ast_verb(4, "User hit '%s' to stop recording call.\n", code);
1625                 if (!ast_strlen_zero(automon_message_stop)) {
1626                         play_message_in_bridged_call(caller_chan, callee_chan, automon_message_stop);
1627                 }
1628                 callee_chan->monitor->stop(callee_chan, 1);
1629                 return AST_FEATURE_RETURN_SUCCESS;
1630         }
1631
1632         if (caller_chan && callee_chan) {
1633                 const char *touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_FORMAT");
1634                 const char *touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR");
1635                 const char *touch_monitor_prefix = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_PREFIX");
1636
1637                 if (!touch_format)
1638                         touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_FORMAT");
1639
1640                 if (!touch_monitor)
1641                         touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR");
1642         
1643                 if (!touch_monitor_prefix)
1644                         touch_monitor_prefix = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_PREFIX");
1645         
1646                 if (touch_monitor) {
1647                         len = strlen(touch_monitor) + 50;
1648                         args = alloca(len);
1649                         touch_filename = alloca(len);
1650                         snprintf(touch_filename, len, "%s-%ld-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), touch_monitor);
1651                         snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
1652                 } else {
1653                         caller_chan_id = ast_strdupa(S_COR(caller_chan->caller.id.number.valid,
1654                                 caller_chan->caller.id.number.str, caller_chan->name));
1655                         callee_chan_id = ast_strdupa(S_COR(callee_chan->caller.id.number.valid,
1656                                 callee_chan->caller.id.number.str, callee_chan->name));
1657                         len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
1658                         args = alloca(len);
1659                         touch_filename = alloca(len);
1660                         snprintf(touch_filename, len, "%s-%ld-%s-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), caller_chan_id, callee_chan_id);
1661                         snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
1662                 }
1663
1664                 for(x = 0; x < strlen(args); x++) {
1665                         if (args[x] == '/')
1666                                 args[x] = '-';
1667                 }
1668                 
1669                 ast_verb(4, "User hit '%s' to record call. filename: %s\n", code, args);
1670
1671                 pbx_exec(callee_chan, monitor_app, args);
1672                 pbx_builtin_setvar_helper(callee_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
1673                 pbx_builtin_setvar_helper(caller_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
1674
1675                 if (!ast_strlen_zero(automon_message_start)) {  /* Play start message for both channels */
1676                         play_message_in_bridged_call(caller_chan, callee_chan, automon_message_start);
1677                 }
1678         
1679                 return AST_FEATURE_RETURN_SUCCESS;
1680         }
1681         
1682         ast_log(LOG_NOTICE,"Cannot record the call. One or both channels have gone away.\n");   
1683         return -1;
1684 }
1685
1686 static int builtin_automixmonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
1687 {
1688         char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
1689         int x = 0;
1690         size_t len;
1691         struct ast_channel *caller_chan, *callee_chan;
1692         const char *mixmonitor_spy_type = "MixMonitor";
1693         int count = 0;
1694
1695         if (!mixmonitor_ok) {
1696                 ast_log(LOG_ERROR,"Cannot record the call. The mixmonitor application is disabled.\n");
1697                 return -1;
1698         }
1699
1700         if (!(mixmonitor_app = pbx_findapp("MixMonitor"))) {
1701                 mixmonitor_ok = 0;
1702                 ast_log(LOG_ERROR,"Cannot record the call. The mixmonitor application is disabled.\n");
1703                 return -1;
1704         }
1705
1706         set_peers(&caller_chan, &callee_chan, peer, chan, sense);
1707
1708         if (!ast_strlen_zero(courtesytone)) {
1709                 if (ast_autoservice_start(callee_chan))
1710                         return -1;
1711                 ast_autoservice_ignore(callee_chan, AST_FRAME_DTMF_END);
1712                 if (ast_stream_and_wait(caller_chan, courtesytone, "")) {
1713                         ast_log(LOG_WARNING, "Failed to play courtesy tone!\n");
1714                         ast_autoservice_stop(callee_chan);
1715                         return -1;
1716                 }
1717                 if (ast_autoservice_stop(callee_chan))
1718                         return -1;
1719         }
1720
1721         ast_channel_lock(callee_chan);
1722         count = ast_channel_audiohook_count_by_source(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
1723         ast_channel_unlock(callee_chan);
1724
1725         /* This means a mixmonitor is attached to the channel, running or not is unknown. */
1726         if (count > 0) {
1727                 
1728                 ast_verb(3, "User hit '%s' to stop recording call.\n", code);
1729
1730                 /* Make sure they are running */
1731                 ast_channel_lock(callee_chan);
1732                 count = ast_channel_audiohook_count_by_source_running(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
1733                 ast_channel_unlock(callee_chan);
1734                 if (count > 0) {
1735                         if (!stopmixmonitor_ok) {
1736                                 ast_log(LOG_ERROR,"Cannot stop recording the call. The stopmixmonitor application is disabled.\n");
1737                                 return -1;
1738                         }
1739                         if (!(stopmixmonitor_app = pbx_findapp("StopMixMonitor"))) {
1740                                 stopmixmonitor_ok = 0;
1741                                 ast_log(LOG_ERROR,"Cannot stop recording the call. The stopmixmonitor application is disabled.\n");
1742                                 return -1;
1743                         } else {
1744                                 pbx_exec(callee_chan, stopmixmonitor_app, "");
1745                                 return AST_FEATURE_RETURN_SUCCESS;
1746                         }
1747                 }
1748                 
1749                 ast_log(LOG_WARNING,"Stopped MixMonitors are attached to the channel.\n");      
1750         }                       
1751
1752         if (caller_chan && callee_chan) {
1753                 const char *touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR_FORMAT");
1754                 const char *touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR");
1755
1756                 if (!touch_format)
1757                         touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR_FORMAT");
1758
1759                 if (!touch_monitor)
1760                         touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR");
1761
1762                 if (touch_monitor) {
1763                         len = strlen(touch_monitor) + 50;
1764                         args = alloca(len);
1765                         touch_filename = alloca(len);
1766                         snprintf(touch_filename, len, "auto-%ld-%s", (long)time(NULL), touch_monitor);
1767                         snprintf(args, len, "%s.%s,b", touch_filename, (touch_format) ? touch_format : "wav");
1768                 } else {
1769                         caller_chan_id = ast_strdupa(S_COR(caller_chan->caller.id.number.valid,
1770                                 caller_chan->caller.id.number.str, caller_chan->name));
1771                         callee_chan_id = ast_strdupa(S_COR(callee_chan->caller.id.number.valid,
1772                                 callee_chan->caller.id.number.str, callee_chan->name));
1773                         len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
1774                         args = alloca(len);
1775                         touch_filename = alloca(len);
1776                         snprintf(touch_filename, len, "auto-%ld-%s-%s", (long)time(NULL), caller_chan_id, callee_chan_id);
1777                         snprintf(args, len, "%s.%s,b", touch_filename, S_OR(touch_format, "wav"));
1778                 }
1779
1780                 for( x = 0; x < strlen(args); x++) {
1781                         if (args[x] == '/')
1782                                 args[x] = '-';
1783                 }
1784
1785                 ast_verb(3, "User hit '%s' to record call. filename: %s\n", code, touch_filename);
1786
1787                 pbx_exec(callee_chan, mixmonitor_app, args);
1788                 pbx_builtin_setvar_helper(callee_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
1789                 pbx_builtin_setvar_helper(caller_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
1790                 return AST_FEATURE_RETURN_SUCCESS;
1791         
1792         }
1793
1794         ast_log(LOG_NOTICE,"Cannot record the call. One or both channels have gone away.\n");
1795         return -1;
1796
1797 }
1798
1799 static int builtin_disconnect(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
1800 {
1801         ast_verb(4, "User hit '%s' to disconnect call.\n", code);
1802         return AST_FEATURE_RETURN_HANGUP;
1803 }
1804
1805 static int finishup(struct ast_channel *chan)
1806 {
1807         ast_indicate(chan, AST_CONTROL_UNHOLD);
1808
1809         return ast_autoservice_stop(chan);
1810 }
1811
1812 /*!
1813  * \brief Find the context for the transfer
1814  * \param transferer
1815  * \param transferee
1816  * 
1817  * Grab the TRANSFER_CONTEXT, if fails try grabbing macrocontext.
1818  * \return a context string
1819 */
1820 static const char *real_ctx(struct ast_channel *transferer, struct ast_channel *transferee)
1821 {
1822         const char *s = pbx_builtin_getvar_helper(transferer, "TRANSFER_CONTEXT");
1823         if (ast_strlen_zero(s)) {
1824                 s = pbx_builtin_getvar_helper(transferee, "TRANSFER_CONTEXT");
1825         }
1826         if (ast_strlen_zero(s)) { /* Use the non-macro context to transfer the call XXX ? */
1827                 s = transferer->macrocontext;
1828         }
1829         if (ast_strlen_zero(s)) {
1830                 s = transferer->context;
1831         }
1832         return s;  
1833 }
1834
1835 /*!
1836  * \brief Blind transfer user to another extension
1837  * \param chan channel to be transfered
1838  * \param peer channel initiated blind transfer
1839  * \param config
1840  * \param code
1841  * \param data
1842  * \param sense  feature options
1843  * 
1844  * Place chan on hold, check if transferred to parkinglot extension,
1845  * otherwise check extension exists and transfer caller.
1846  * \retval AST_FEATURE_RETURN_SUCCESS.
1847  * \retval -1 on failure.
1848 */
1849 static int builtin_blindtransfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
1850 {
1851         struct ast_channel *transferer;
1852         struct ast_channel *transferee;
1853         const char *transferer_real_context;
1854         struct ast_parkinglot *found_lot = NULL;
1855         char xferto[256];
1856         int res, parkstatus = 0;
1857
1858         set_peers(&transferer, &transferee, peer, chan, sense);
1859         transferer_real_context = real_ctx(transferer, transferee);
1860         /* Start autoservice on chan while we talk to the originator */
1861         ast_autoservice_start(transferee);
1862         ast_autoservice_ignore(transferee, AST_FRAME_DTMF_END);
1863         ast_indicate(transferee, AST_CONTROL_HOLD);
1864
1865         memset(xferto, 0, sizeof(xferto));
1866
1867         /* Transfer */
1868         res = ast_stream_and_wait(transferer, "pbx-transfer", AST_DIGIT_ANY);
1869         if (res < 0) {
1870                 finishup(transferee);
1871                 return -1; /* error ? */
1872         }
1873         if (res > 0)    /* If they've typed a digit already, handle it */
1874                 xferto[0] = (char) res;
1875
1876         ast_stopstream(transferer);
1877         res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
1878         if (res < 0) {  /* hangup or error, (would be 0 for invalid and 1 for valid) */
1879                 finishup(transferee);
1880                 return -1;
1881         }
1882         if (res == 0) {
1883                 if (xferto[0]) {
1884                         ast_log(LOG_WARNING, "Extension '%s' does not exist in context '%s'\n",
1885                                 xferto, transferer_real_context);
1886                 } else {
1887                         /* Does anyone care about this case? */
1888                         ast_log(LOG_WARNING, "No digits dialed.\n");
1889                 }
1890                 ast_stream_and_wait(transferer, "pbx-invalid", "");
1891                 finishup(transferee);
1892                 return AST_FEATURE_RETURN_SUCCESS;
1893         }
1894
1895         found_lot = ao2_callback(parkinglots, 0, find_parkinglot_by_exten_cb, &xferto);
1896         if (found_lot) {
1897                 struct ast_park_call_args args = {
1898                         .parkinglot = found_lot,
1899                 };
1900                 res = finishup(transferee);
1901                 if (res) {
1902                 } else if (!(parkstatus = masq_park_call_announce(transferee, transferer, &args))) {    /* success */
1903                         /* We return non-zero, but tell the PBX not to hang the channel when
1904                            the thread dies -- We have to be careful now though.  We are responsible for 
1905                            hanging up the channel, else it will never be hung up! */
1906
1907                         return 0;
1908                 } else {
1909                         ast_log(LOG_WARNING, "Unable to park call %s, parkstatus = %d\n", transferee->name, parkstatus);
1910                 }
1911                 ast_autoservice_start(transferee);
1912         } else {
1913                 ast_cel_report_event(transferer, AST_CEL_BLINDTRANSFER, NULL, xferto, transferee);
1914                 pbx_builtin_setvar_helper(transferer, "BLINDTRANSFER", transferee->name);
1915                 pbx_builtin_setvar_helper(transferee, "BLINDTRANSFER", transferer->name);
1916                 res=finishup(transferee);
1917                 if (!transferer->cdr) { /* this code should never get called (in a perfect world) */
1918                         transferer->cdr=ast_cdr_alloc();
1919                         if (transferer->cdr) {
1920                                 ast_cdr_init(transferer->cdr, transferer); /* initialize our channel's cdr */
1921                                 ast_cdr_start(transferer->cdr);
1922                         }
1923                 }
1924                 if (transferer->cdr) {
1925                         struct ast_cdr *swap = transferer->cdr;
1926                         ast_debug(1, "transferer=%s; transferee=%s; lastapp=%s; lastdata=%s; chan=%s; dstchan=%s\n",
1927                                         transferer->name, transferee->name, transferer->cdr->lastapp, transferer->cdr->lastdata, 
1928                                         transferer->cdr->channel, transferer->cdr->dstchannel);
1929                         ast_debug(1, "TRANSFEREE; lastapp=%s; lastdata=%s, chan=%s; dstchan=%s\n",
1930                                         transferee->cdr->lastapp, transferee->cdr->lastdata, transferee->cdr->channel, transferee->cdr->dstchannel);
1931                         ast_debug(1, "transferer_real_context=%s; xferto=%s\n", transferer_real_context, xferto);
1932                         /* swap cdrs-- it will save us some time & work */
1933                         transferer->cdr = transferee->cdr;
1934                         transferee->cdr = swap;
1935                 }
1936                 if (!transferee->pbx) {
1937                         /* Doh!  Use our handy async_goto functions */
1938                         ast_verb(3, "Transferring %s to '%s' (context %s) priority 1\n"
1939                                                                 ,transferee->name, xferto, transferer_real_context);
1940                         if (ast_async_goto(transferee, transferer_real_context, xferto, 1))
1941                                 ast_log(LOG_WARNING, "Async goto failed :-(\n");
1942                 } else {
1943                         /* Set the channel's new extension, since it exists, using transferer context */
1944                         ast_set_flag(transferee, AST_FLAG_BRIDGE_HANGUP_DONT); /* don't let the after-bridge code run the h-exten */
1945                         ast_debug(1, "ABOUT TO AST_ASYNC_GOTO, have a pbx... set HANGUP_DONT on chan=%s\n", transferee->name);
1946                         if (ast_channel_connected_line_macro(transferee, transferer, &transferer->connected, 1, 0)) {
1947                                 ast_channel_update_connected_line(transferer, &transferer->connected, NULL);
1948                         }
1949                         set_c_e_p(transferee, transferer_real_context, xferto, 0);
1950                 }
1951                 check_goto_on_transfer(transferer);
1952                 return res;
1953         }
1954         if (parkstatus != AST_FEATURE_RETURN_PARKFAILED
1955                 && ast_stream_and_wait(transferer, xferfailsound, "")) {
1956                 finishup(transferee);
1957                 return -1;
1958         }
1959         ast_stopstream(transferer);
1960         res = finishup(transferee);
1961         if (res) {
1962                 ast_verb(2, "Hungup during autoservice stop on '%s'\n", transferee->name);
1963                 return res;
1964         }
1965         return AST_FEATURE_RETURN_SUCCESS;
1966 }
1967
1968 /*!
1969  * \brief make channels compatible
1970  * \param c
1971  * \param newchan
1972  * \retval 0 on success.
1973  * \retval -1 on failure.
1974 */
1975 static int check_compat(struct ast_channel *c, struct ast_channel *newchan)
1976 {
1977         if (ast_channel_make_compatible(c, newchan) < 0) {
1978                 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n",
1979                         c->name, newchan->name);
1980                 ast_hangup(newchan);
1981                 return -1;
1982         }
1983         return 0;
1984 }
1985
1986 /*!
1987  * \internal
1988  * \brief Builtin attended transfer failed cleanup.
1989  * \since 1.10
1990  *
1991  * \param transferee Party A in the transfer.
1992  * \param transferer Party B in the transfer.
1993  * \param connected_line Saved connected line info about party A.
1994  *
1995  * \note The connected_line data is freed.
1996  *
1997  * \return Nothing
1998  */
1999 static void atxfer_fail_cleanup(struct ast_channel *transferee, struct ast_channel *transferer, struct ast_party_connected_line *connected_line)
2000 {
2001         finishup(transferee);
2002
2003         /*
2004          * Restore party B connected line info about party A.
2005          *
2006          * Party B was the caller to party C and is the last known mode
2007          * for party B.
2008          */
2009         if (ast_channel_connected_line_macro(transferee, transferer, connected_line, 1, 0)) {
2010                 ast_channel_update_connected_line(transferer, connected_line, NULL);
2011         }
2012         ast_party_connected_line_free(connected_line);
2013 }
2014
2015 /*!
2016  * \brief Attended transfer
2017  * \param chan transfered user
2018  * \param peer person transfering call
2019  * \param config
2020  * \param code
2021  * \param sense feature options
2022  *
2023  * \param data
2024  * Get extension to transfer to, if you cannot generate channel (or find extension)
2025  * return to host channel. After called channel answered wait for hangup of transferer,
2026  * bridge call between transfer peer (taking them off hold) to attended transfer channel.
2027  *
2028  * \return -1 on failure
2029 */
2030 static int builtin_atxfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2031 {
2032         struct ast_channel *transferer;/* Party B */
2033         struct ast_channel *transferee;/* Party A */
2034         const char *transferer_real_context;
2035         char xferto[256] = "";
2036         int res;
2037         int outstate=0;
2038         struct ast_channel *newchan;
2039         struct ast_channel *xferchan;
2040         struct ast_bridge_thread_obj *tobj;
2041         struct ast_bridge_config bconfig;
2042         int l;
2043         struct ast_party_connected_line connected_line;
2044         struct ast_datastore *features_datastore;
2045         struct ast_dial_features *dialfeatures = NULL;
2046         struct ast_parkinglot *parkinglot;
2047         char *transferer_tech;
2048         char *transferer_name;
2049         char *transferer_name_orig;
2050         char *dash;
2051
2052         ast_debug(1, "Executing Attended Transfer %s, %s (sense=%d) \n", chan->name, peer->name, sense);
2053         set_peers(&transferer, &transferee, peer, chan, sense);
2054         transferer_real_context = real_ctx(transferer, transferee);
2055
2056         /* Start autoservice on transferee while we talk to the transferer */
2057         ast_autoservice_start(transferee);
2058         ast_indicate(transferee, AST_CONTROL_HOLD);
2059
2060         /* Transfer */
2061         res = ast_stream_and_wait(transferer, "pbx-transfer", AST_DIGIT_ANY);
2062         if (res < 0) {
2063                 finishup(transferee);
2064                 return -1;
2065         }
2066         if (res > 0) /* If they've typed a digit already, handle it */
2067                 xferto[0] = (char) res;
2068
2069         /* this is specific of atxfer */
2070         res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
2071         if (res < 0) {  /* hangup or error, (would be 0 for invalid and 1 for valid) */
2072                 finishup(transferee);
2073                 return -1;
2074         }
2075         l = strlen(xferto);
2076         if (res == 0) {
2077                 if (l) {
2078                         ast_log(LOG_WARNING, "Extension '%s' does not exist in context '%s'\n",
2079                                 xferto, transferer_real_context);
2080                 } else {
2081                         /* Does anyone care about this case? */
2082                         ast_log(LOG_WARNING, "No digits dialed for atxfer.\n");
2083                 }
2084                 ast_stream_and_wait(transferer, "pbx-invalid", "");
2085                 finishup(transferee);
2086                 return AST_FEATURE_RETURN_SUCCESS;
2087         }
2088
2089         /* If we are attended transfering to parking, just use parkcall_helper instead of trying to track all of
2090          * the different variables for handling this properly with a builtin_atxfer */
2091         parkinglot = ao2_callback(parkinglots, 0, find_parkinglot_by_exten_cb, &xferto);
2092         if (parkinglot) {
2093                 struct ast_park_call_args args = {
2094                         .parkinglot = parkinglot,
2095                 };
2096                 finishup(transferee);
2097                 return parkcall_helper(chan, peer, config, code, sense, &args);
2098         }
2099
2100         /* Append context to dialed transfer number. */
2101         snprintf(xferto + l, sizeof(xferto) - l, "@%s/n", transferer_real_context);
2102
2103         /* If we are performing an attended transfer and we have two channels involved then
2104            copy sound file information to play upon attended transfer completion */
2105         if (transferee) {
2106                 const char *chan1_attended_sound = pbx_builtin_getvar_helper(transferer, "ATTENDED_TRANSFER_COMPLETE_SOUND");
2107                 const char *chan2_attended_sound = pbx_builtin_getvar_helper(transferee, "ATTENDED_TRANSFER_COMPLETE_SOUND");
2108
2109                 if (!ast_strlen_zero(chan1_attended_sound)) {
2110                         pbx_builtin_setvar_helper(transferer, "BRIDGE_PLAY_SOUND", chan1_attended_sound);
2111                 }
2112                 if (!ast_strlen_zero(chan2_attended_sound)) {
2113                         pbx_builtin_setvar_helper(transferee, "BRIDGE_PLAY_SOUND", chan2_attended_sound);
2114                 }
2115         }
2116
2117         /* Extract redial transferer information from the channel name. */
2118         transferer_name_orig = ast_strdupa(transferer->name);
2119         transferer_name = ast_strdupa(transferer_name_orig);
2120         transferer_tech = strsep(&transferer_name, "/");
2121         dash = strrchr(transferer_name, '-');
2122         if (dash) {
2123                 /* Trim off channel name sequence/serial number. */
2124                 *dash = '\0';
2125         }
2126
2127         /* Stop autoservice so we can monitor all parties involved in the transfer. */
2128         if (ast_autoservice_stop(transferee) < 0) {
2129                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2130                 return -1;
2131         }
2132
2133         /* Save connected line info for party B about party A in case transfer fails. */
2134         ast_party_connected_line_init(&connected_line);
2135         ast_channel_lock(transferer);
2136         ast_party_connected_line_copy(&connected_line, &transferer->connected);
2137         ast_channel_unlock(transferer);
2138         connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
2139
2140         /* Dial party C */
2141         newchan = feature_request_and_dial(transferer, transferer_name_orig, transferer,
2142                 transferee, "Local", transferer->nativeformats, xferto,
2143                 atxfernoanswertimeout, &outstate, transferer->language);
2144         ast_debug(2, "Dial party C result: newchan:%d, outstate:%d\n", !!newchan, outstate);
2145
2146         if (!ast_check_hangup(transferer)) {
2147                 int hangup_dont = 0;
2148
2149                 /* Transferer (party B) is up */
2150                 ast_debug(1, "Actually doing an attended transfer.\n");
2151
2152                 /* Start autoservice on transferee while the transferer deals with party C. */
2153                 ast_autoservice_start(transferee);
2154
2155                 ast_indicate(transferer, -1);
2156                 if (!newchan) {
2157                         /* any reason besides user requested cancel and busy triggers the failed sound */
2158                         switch (outstate) {
2159                         case AST_CONTROL_UNHOLD:/* Caller requested cancel or party C answer timeout. */
2160                         case AST_CONTROL_BUSY:
2161                         case AST_CONTROL_CONGESTION:
2162                                 if (ast_stream_and_wait(transferer, xfersound, "")) {
2163                                         ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
2164                                 }
2165                                 break;
2166                         default:
2167                                 if (ast_stream_and_wait(transferer, xferfailsound, "")) {
2168                                         ast_log(LOG_WARNING, "Failed to play transfer failed sound!\n");
2169                                 }
2170                                 break;
2171                         }
2172                         atxfer_fail_cleanup(transferee, transferer, &connected_line);
2173                         return AST_FEATURE_RETURN_SUCCESS;
2174                 }
2175
2176                 if (check_compat(transferer, newchan)) {
2177                         if (ast_stream_and_wait(transferer, xferfailsound, "")) {
2178                                 ast_log(LOG_WARNING, "Failed to play transfer failed sound!\n");
2179                         }
2180                         atxfer_fail_cleanup(transferee, transferer, &connected_line);
2181                         return AST_FEATURE_RETURN_SUCCESS;
2182                 }
2183                 memset(&bconfig,0,sizeof(struct ast_bridge_config));
2184                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_DISCONNECT);
2185                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_DISCONNECT);
2186
2187                 /* ast_bridge_call clears AST_FLAG_BRIDGE_HANGUP_DONT, but we don't
2188                    want that to happen here because we're also in another bridge already
2189                  */
2190                 if (ast_test_flag(chan, AST_FLAG_BRIDGE_HANGUP_DONT)) {
2191                         hangup_dont = 1;
2192                 }
2193                 /* Let party B and party C talk as long as they want. */
2194                 ast_bridge_call(transferer, newchan, &bconfig);
2195                 if (hangup_dont) {
2196                         ast_set_flag(chan, AST_FLAG_BRIDGE_HANGUP_DONT);
2197                 }
2198
2199                 if (ast_check_hangup(newchan) || !ast_check_hangup(transferer)) {
2200                         ast_hangup(newchan);
2201                         if (ast_stream_and_wait(transferer, xfersound, "")) {
2202                                 ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
2203                         }
2204                         atxfer_fail_cleanup(transferee, transferer, &connected_line);
2205                         return AST_FEATURE_RETURN_SUCCESS;
2206                 }
2207
2208                 /* Transferer (party B) is confirmed hung up at this point. */
2209                 if (check_compat(transferee, newchan)) {
2210                         finishup(transferee);
2211                         ast_party_connected_line_free(&connected_line);
2212                         return -1;
2213                 }
2214
2215                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2216                 if ((ast_autoservice_stop(transferee) < 0)
2217                         || (ast_waitfordigit(transferee, 100) < 0)
2218                         || (ast_waitfordigit(newchan, 100) < 0)
2219                         || ast_check_hangup(transferee)
2220                         || ast_check_hangup(newchan)) {
2221                         ast_hangup(newchan);
2222                         ast_party_connected_line_free(&connected_line);
2223                         return -1;
2224                 }
2225         } else if (!ast_check_hangup(transferee)) {
2226                 /* Transferer (party B) has hung up at this point.  Doing blonde transfer. */
2227                 ast_debug(1, "Actually doing a blonde transfer.\n");
2228
2229                 if (!newchan && !atxferdropcall) {
2230                         /* Party C is not available, try to call party B back. */
2231                         unsigned int tries = 0;
2232
2233                         if (ast_strlen_zero(transferer_name) || ast_strlen_zero(transferer_tech)) {
2234                                 ast_log(LOG_WARNING,
2235                                         "Transferer channel name: '%s' cannot be used for callback.\n",
2236                                         transferer_name_orig);
2237                                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2238                                 ast_party_connected_line_free(&connected_line);
2239                                 return -1;
2240                         }
2241
2242                         tries = 0;
2243                         for (;;) {
2244                                 /* Try to get party B back. */
2245                                 ast_debug(1, "We're trying to callback %s/%s\n",
2246                                         transferer_tech, transferer_name);
2247                                 newchan = feature_request_and_dial(transferer, transferer_name_orig,
2248                                         transferee, transferee, transferer_tech,
2249                                         transferee->nativeformats, transferer_name,
2250                                         atxfernoanswertimeout, &outstate, transferer->language);
2251                                 ast_debug(2, "Dial party B result: newchan:%d, outstate:%d\n",
2252                                         !!newchan, outstate);
2253                                 if (newchan || ast_check_hangup(transferee)) {
2254                                         break;
2255                                 }
2256                                 ++tries;
2257                                 if (atxfercallbackretries <= tries) {
2258                                         /* No more callback tries remaining. */
2259                                         break;
2260                                 }
2261
2262                                 if (atxferloopdelay) {
2263                                         /* Transfer failed, sleeping */
2264                                         ast_debug(1, "Sleeping for %d ms before retrying atxfer.\n",
2265                                                 atxferloopdelay);
2266                                         ast_safe_sleep(transferee, atxferloopdelay);
2267                                         if (ast_check_hangup(transferee)) {
2268                                                 ast_party_connected_line_free(&connected_line);
2269                                                 return -1;
2270                                         }
2271                                 }
2272
2273                                 /* Retry dialing party C. */
2274                                 ast_debug(1, "We're retrying to call %s/%s\n", "Local", xferto);
2275                                 newchan = feature_request_and_dial(transferer, transferer_name_orig,
2276                                         transferer, transferee, "Local",
2277                                         transferee->nativeformats, xferto,
2278                                         atxfernoanswertimeout, &outstate, transferer->language);
2279                                 ast_debug(2, "Redial party C result: newchan:%d, outstate:%d\n",
2280                                         !!newchan, outstate);
2281                                 if (newchan || ast_check_hangup(transferee)) {
2282                                         break;
2283                                 }
2284                         }
2285                 }
2286                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2287                 if (!newchan) {
2288                         /* No party C or could not callback party B. */
2289                         ast_party_connected_line_free(&connected_line);
2290                         return -1;
2291                 }
2292
2293                 /* newchan is up, we should prepare transferee and bridge them */
2294                 if (ast_check_hangup(newchan)) {
2295                         ast_hangup(newchan);
2296                         ast_party_connected_line_free(&connected_line);
2297                         return -1;
2298                 }
2299                 if (check_compat(transferee, newchan)) {
2300                         ast_party_connected_line_free(&connected_line);
2301                         return -1;
2302                 }
2303         } else {
2304                 /*
2305                  * Both the transferer and transferee have hungup.  If newchan
2306                  * is up, hang it up as it has no one to talk to.
2307                  */
2308                 ast_debug(1, "Everyone is hungup.\n");
2309                 if (newchan) {
2310                         ast_hangup(newchan);
2311                 }
2312                 ast_party_connected_line_free(&connected_line);
2313                 return -1;
2314         }
2315
2316         /* Initiate the channel transfer of party A to party C (or recalled party B). */
2317         ast_cel_report_event(transferee, AST_CEL_ATTENDEDTRANSFER, NULL, NULL, newchan);
2318
2319         xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", transferee->linkedid, 0, "Transfered/%s", transferee->name);
2320         if (!xferchan) {
2321                 ast_hangup(newchan);
2322                 ast_party_connected_line_free(&connected_line);
2323                 return -1;
2324         }
2325
2326         /* Give party A a momentary ringback tone during transfer. */
2327         xferchan->visible_indication = AST_CONTROL_RINGING;
2328
2329         /* Make formats okay */
2330         xferchan->readformat = transferee->readformat;
2331         xferchan->writeformat = transferee->writeformat;
2332
2333         ast_channel_masquerade(xferchan, transferee);
2334         ast_explicit_goto(xferchan, transferee->context, transferee->exten, transferee->priority);
2335         xferchan->_state = AST_STATE_UP;
2336         ast_clear_flag(xferchan, AST_FLAGS_ALL);
2337
2338         /* Do the masquerade manually to make sure that is is completed. */
2339         ast_do_masquerade(xferchan);
2340
2341         newchan->_state = AST_STATE_UP;
2342         ast_clear_flag(newchan, AST_FLAGS_ALL);
2343         tobj = ast_calloc(1, sizeof(*tobj));
2344         if (!tobj) {
2345                 ast_hangup(xferchan);
2346                 ast_hangup(newchan);
2347                 ast_party_connected_line_free(&connected_line);
2348                 return -1;
2349         }
2350
2351         ast_channel_lock(newchan);
2352         if ((features_datastore = ast_channel_datastore_find(newchan, &dial_features_info, NULL))) {
2353                 dialfeatures = features_datastore->data;
2354         }
2355         ast_channel_unlock(newchan);
2356
2357         if (dialfeatures) {
2358                 /* newchan should always be the callee and shows up as callee in dialfeatures, but for some reason
2359                    I don't currently understand, the abilities of newchan seem to be stored on the caller side */
2360                 ast_copy_flags(&(config->features_callee), &(dialfeatures->features_caller), AST_FLAGS_ALL);
2361                 dialfeatures = NULL;
2362         }
2363
2364         ast_channel_lock(xferchan);
2365         if ((features_datastore = ast_channel_datastore_find(xferchan, &dial_features_info, NULL))) {
2366                 dialfeatures = features_datastore->data;
2367         }
2368         ast_channel_unlock(xferchan);
2369
2370         if (dialfeatures) {
2371                 ast_copy_flags(&(config->features_caller), &(dialfeatures->features_caller), AST_FLAGS_ALL);
2372         }
2373
2374         tobj->chan = newchan;
2375         tobj->peer = xferchan;
2376         tobj->bconfig = *config;
2377
2378         if (tobj->bconfig.end_bridge_callback_data_fixup) {
2379                 tobj->bconfig.end_bridge_callback_data_fixup(&tobj->bconfig, tobj->peer, tobj->chan);
2380         }
2381
2382         /*
2383          * xferchan is transferee, and newchan is the transfer target
2384          * So...in a transfer, who is the caller and who is the callee?
2385          *
2386          * When the call is originally made, it is clear who is caller and callee.
2387          * When a transfer occurs, it is my humble opinion that the transferee becomes
2388          * the caller, and the transfer target is the callee.
2389          *
2390          * The problem is that these macros were set with the intention of the original
2391          * caller and callee taking those roles.  A transfer can totally mess things up,
2392          * to be technical.  What sucks even more is that you can't effectively change
2393          * the macros in the dialplan during the call from the transferer to the transfer
2394          * target because the transferee is stuck with whatever role he originally had.
2395          *
2396          * I think the answer here is just to make sure that it is well documented that
2397          * during a transfer, the transferee is the "caller" and the transfer target
2398          * is the "callee."
2399          *
2400          * This means that if party B calls party A, and party B transfers party A to
2401          * party C, then A has switched roles for the call.  Now party A will have the
2402          * caller macro called on his channel instead of the callee macro.
2403          *
2404          * Luckily, the method by which the party B to party C bridge is
2405          * launched above ensures that the transferee is the "chan" on
2406          * the bridge and the transfer target is the "peer," so my idea
2407          * for the roles post-transfer does not require extensive code
2408          * changes.
2409          */
2410
2411         /* Transfer party C connected line to party A */
2412         ast_channel_lock(transferer);
2413         /*
2414          * Due to a limitation regarding when callerID is set on a Local channel,
2415          * we use the transferer's connected line information here.
2416          */
2417         ast_party_connected_line_copy(&connected_line, &transferer->connected);
2418         ast_channel_unlock(transferer);
2419         connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
2420         if (ast_channel_connected_line_macro(newchan, xferchan, &connected_line, 1, 0)) {
2421                 ast_channel_update_connected_line(xferchan, &connected_line, NULL);
2422         }
2423
2424         /* Transfer party A connected line to party C */
2425         ast_channel_lock(xferchan);
2426         ast_connected_line_copy_from_caller(&connected_line, &xferchan->caller);
2427         ast_channel_unlock(xferchan);
2428         connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
2429         if (ast_channel_connected_line_macro(xferchan, newchan, &connected_line, 0, 0)) {
2430                 ast_channel_update_connected_line(newchan, &connected_line, NULL);
2431         }
2432
2433         if (ast_stream_and_wait(newchan, xfersound, ""))
2434                 ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
2435         bridge_call_thread_launch(tobj);
2436
2437         ast_party_connected_line_free(&connected_line);
2438         return -1;/* The transferee is masqueraded and the original bridged channels can be hungup. */
2439 }
2440
2441 /* add atxfer and automon as undefined so you can only use em if you configure them */
2442 #define FEATURES_COUNT ARRAY_LEN(builtin_features)
2443
2444 AST_RWLOCK_DEFINE_STATIC(features_lock);
2445
2446 static struct ast_call_feature builtin_features[] = {
2447         { AST_FEATURE_REDIRECT, "Blind Transfer", "blindxfer", "#", "#", builtin_blindtransfer, AST_FEATURE_FLAG_NEEDSDTMF, "" },
2448         { AST_FEATURE_REDIRECT, "Attended Transfer", "atxfer", "", "", builtin_atxfer, AST_FEATURE_FLAG_NEEDSDTMF, "" },
2449         { AST_FEATURE_AUTOMON, "One Touch Monitor", "automon", "", "", builtin_automonitor, AST_FEATURE_FLAG_NEEDSDTMF, "" },
2450         { AST_FEATURE_DISCONNECT, "Disconnect Call", "disconnect", "*", "*", builtin_disconnect, AST_FEATURE_FLAG_NEEDSDTMF, "" },
2451         { AST_FEATURE_PARKCALL, "Park Call", "parkcall", "", "", builtin_parkcall, AST_FEATURE_FLAG_NEEDSDTMF, "" },
2452         { AST_FEATURE_AUTOMIXMON, "One Touch MixMonitor", "automixmon", "", "", builtin_automixmonitor, AST_FEATURE_FLAG_NEEDSDTMF, "" },
2453 };
2454
2455
2456 static AST_RWLIST_HEAD_STATIC(feature_list, ast_call_feature);
2457
2458 /*! \brief register new feature into feature_list*/
2459 void ast_register_feature(struct ast_call_feature *feature)
2460 {
2461         if (!feature) {
2462                 ast_log(LOG_NOTICE,"You didn't pass a feature!\n");
2463                 return;
2464         }
2465   
2466         AST_RWLIST_WRLOCK(&feature_list);
2467         AST_RWLIST_INSERT_HEAD(&feature_list,feature,feature_entry);
2468         AST_RWLIST_UNLOCK(&feature_list);
2469
2470         ast_verb(2, "Registered Feature '%s'\n",feature->sname);
2471 }
2472
2473 /*! 
2474  * \brief Add new feature group
2475  * \param fgname feature group name.
2476  *
2477  * Add new feature group to the feature group list insert at head of list.
2478  * \note This function MUST be called while feature_groups is locked.
2479 */
2480 static struct feature_group *register_group(const char *fgname)
2481 {
2482         struct feature_group *fg;
2483
2484         if (!fgname) {
2485                 ast_log(LOG_NOTICE, "You didn't pass a new group name!\n");
2486                 return NULL;
2487         }
2488
2489         if (!(fg = ast_calloc_with_stringfields(1, struct feature_group, 128))) {
2490                 return NULL;
2491         }
2492
2493         ast_string_field_set(fg, gname, fgname);
2494
2495         AST_LIST_INSERT_HEAD(&feature_groups, fg, entry);
2496
2497         ast_verb(2, "Registered group '%s'\n", fg->gname);
2498
2499         return fg;
2500 }
2501
2502 /*! 
2503  * \brief Add feature to group
2504  * \param fg feature group
2505  * \param exten
2506  * \param feature feature to add.
2507  *
2508  * Check fg and feature specified, add feature to list
2509  * \note This function MUST be called while feature_groups is locked. 
2510 */
2511 static void register_group_feature(struct feature_group *fg, const char *exten, struct ast_call_feature *feature)
2512 {
2513         struct feature_group_exten *fge;
2514
2515         if (!fg) {
2516                 ast_log(LOG_NOTICE, "You didn't pass a group!\n");
2517                 return;
2518         }
2519
2520         if (!feature) {
2521                 ast_log(LOG_NOTICE, "You didn't pass a feature!\n");
2522                 return;
2523         }
2524
2525         if (!(fge = ast_calloc_with_stringfields(1, struct feature_group_exten, 128))) {
2526                 return;
2527         }
2528
2529         ast_string_field_set(fge, exten, S_OR(exten, feature->exten));
2530
2531         fge->feature = feature;
2532
2533         AST_LIST_INSERT_HEAD(&fg->features, fge, entry);
2534
2535         ast_verb(2, "Registered feature '%s' for group '%s' at exten '%s'\n",
2536                                         feature->sname, fg->gname, fge->exten);
2537 }
2538
2539 void ast_unregister_feature(struct ast_call_feature *feature)
2540 {
2541         if (!feature) {
2542                 return;
2543         }
2544
2545         AST_RWLIST_WRLOCK(&feature_list);
2546         AST_RWLIST_REMOVE(&feature_list, feature, feature_entry);
2547         AST_RWLIST_UNLOCK(&feature_list);
2548
2549         ast_free(feature);
2550 }
2551
2552 /*! \brief Remove all features in the list */
2553 static void ast_unregister_features(void)
2554 {
2555         struct ast_call_feature *feature;
2556
2557         AST_RWLIST_WRLOCK(&feature_list);
2558         while ((feature = AST_RWLIST_REMOVE_HEAD(&feature_list, feature_entry))) {
2559                 ast_free(feature);
2560         }
2561         AST_RWLIST_UNLOCK(&feature_list);
2562 }
2563
2564 /*! \brief find a call feature by name */
2565 static struct ast_call_feature *find_dynamic_feature(const char *name)
2566 {
2567         struct ast_call_feature *tmp;
2568
2569         AST_RWLIST_TRAVERSE(&feature_list, tmp, feature_entry) {
2570                 if (!strcasecmp(tmp->sname, name)) {
2571                         break;
2572                 }
2573         }
2574
2575         return tmp;
2576 }
2577
2578 /*! \brief Remove all feature groups in the list */
2579 static void ast_unregister_groups(void)
2580 {
2581         struct feature_group *fg;
2582         struct feature_group_exten *fge;
2583
2584         AST_RWLIST_WRLOCK(&feature_groups);
2585         while ((fg = AST_LIST_REMOVE_HEAD(&feature_groups, entry))) {
2586                 while ((fge = AST_LIST_REMOVE_HEAD(&fg->features, entry))) {
2587                         ast_string_field_free_memory(fge);
2588                         ast_free(fge);
2589                 }
2590
2591                 ast_string_field_free_memory(fg);
2592                 ast_free(fg);
2593         }
2594         AST_RWLIST_UNLOCK(&feature_groups);
2595 }
2596
2597 /*! 
2598  * \brief Find a group by name 
2599  * \param name feature name
2600  * \retval feature group on success.
2601  * \retval NULL on failure.
2602 */
2603 static struct feature_group *find_group(const char *name)
2604 {
2605         struct feature_group *fg = NULL;
2606
2607         AST_LIST_TRAVERSE(&feature_groups, fg, entry) {
2608                 if (!strcasecmp(fg->gname, name))
2609                         break;
2610         }
2611
2612         return fg;
2613 }
2614
2615 void ast_rdlock_call_features(void)
2616 {
2617         ast_rwlock_rdlock(&features_lock);
2618 }
2619
2620 void ast_unlock_call_features(void)
2621 {
2622         ast_rwlock_unlock(&features_lock);
2623 }
2624
2625 struct ast_call_feature *ast_find_call_feature(const char *name)
2626 {
2627         int x;
2628         for (x = 0; x < FEATURES_COUNT; x++) {
2629                 if (!strcasecmp(name, builtin_features[x].sname))
2630                         return &builtin_features[x];
2631         }
2632         return NULL;
2633 }
2634
2635 /*!
2636  * \brief exec an app by feature 
2637  * \param chan,peer,config,code,sense,data
2638  *
2639  * Find a feature, determine which channel activated
2640  * \retval AST_FEATURE_RETURN_NO_HANGUP_PEER
2641  * \retval -1 error.
2642  * \retval -2 when an application cannot be found.
2643 */
2644 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)
2645 {
2646         struct ast_app *app;
2647         struct ast_call_feature *feature = data;
2648         struct ast_channel *work, *idle;
2649         int res;
2650
2651         if (!feature) { /* shouldn't ever happen! */
2652                 ast_log(LOG_NOTICE, "Found feature before, but at execing we've lost it??\n");
2653                 return -1; 
2654         }
2655
2656         if (sense == FEATURE_SENSE_CHAN) {
2657                 if (!ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLER))
2658                         return AST_FEATURE_RETURN_KEEPTRYING;
2659                 if (ast_test_flag(feature, AST_FEATURE_FLAG_ONSELF)) {
2660                         work = chan;
2661                         idle = peer;
2662                 } else {
2663                         work = peer;
2664                         idle = chan;
2665                 }
2666         } else {
2667                 if (!ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLEE))
2668                         return AST_FEATURE_RETURN_KEEPTRYING;
2669                 if (ast_test_flag(feature, AST_FEATURE_FLAG_ONSELF)) {
2670                         work = peer;
2671                         idle = chan;
2672                 } else {
2673                         work = chan;
2674                         idle = peer;
2675                 }
2676         }
2677
2678         if (!(app = pbx_findapp(feature->app))) {
2679                 ast_log(LOG_WARNING, "Could not find application (%s)\n", feature->app);
2680                 return -2;
2681         }
2682
2683         ast_autoservice_start(idle);
2684         ast_autoservice_ignore(idle, AST_FRAME_DTMF_END);
2685         
2686         if(work && idle) {
2687                 pbx_builtin_setvar_helper(work, "DYNAMIC_PEERNAME", idle->name);
2688                 pbx_builtin_setvar_helper(idle, "DYNAMIC_PEERNAME", work->name);
2689                 pbx_builtin_setvar_helper(work, "DYNAMIC_FEATURENAME", feature->sname);
2690                 pbx_builtin_setvar_helper(idle, "DYNAMIC_FEATURENAME", feature->sname);
2691         }
2692
2693         if (!ast_strlen_zero(feature->moh_class))
2694                 ast_moh_start(idle, feature->moh_class, NULL);
2695
2696         res = pbx_exec(work, app, feature->app_args);
2697
2698         if (!ast_strlen_zero(feature->moh_class))
2699                 ast_moh_stop(idle);
2700
2701         ast_autoservice_stop(idle);
2702
2703         if (res) {
2704                 return AST_FEATURE_RETURN_SUCCESSBREAK;
2705         }
2706         return AST_FEATURE_RETURN_SUCCESS;      /*! \todo XXX should probably return res */
2707 }
2708
2709 static void unmap_features(void)
2710 {
2711         int x;
2712
2713         ast_rwlock_wrlock(&features_lock);
2714         for (x = 0; x < FEATURES_COUNT; x++)
2715                 strcpy(builtin_features[x].exten, builtin_features[x].default_exten);
2716         ast_rwlock_unlock(&features_lock);
2717 }
2718
2719 static int remap_feature(const char *name, const char *value)
2720 {
2721         int x, res = -1;
2722
2723         ast_rwlock_wrlock(&features_lock);
2724         for (x = 0; x < FEATURES_COUNT; x++) {
2725                 if (strcasecmp(builtin_features[x].sname, name))
2726                         continue;
2727
2728                 ast_copy_string(builtin_features[x].exten, value, sizeof(builtin_features[x].exten));
2729                 res = 0;
2730                 break;
2731         }
2732         ast_rwlock_unlock(&features_lock);
2733
2734         return res;
2735 }
2736
2737 /*!
2738  * \brief Helper function for feature_interpret and ast_feature_detect
2739  * \param chan,peer,config,code,sense,dynamic_features_buf,features,operation,feature
2740  *
2741  * Lock features list, browse for code, unlock list
2742  * If a feature is found and the operation variable is set, that feature's
2743  * operation is executed.  The first feature found is copied to the feature parameter.
2744  * \retval res on success.
2745  * \retval -1 on failure.
2746 */
2747 static int feature_interpret_helper(struct ast_channel *chan, struct ast_channel *peer,
2748         struct ast_bridge_config *config, const char *code, int sense, char *dynamic_features_buf,
2749         struct ast_flags *features, int operation, struct ast_call_feature *feature)
2750 {
2751         int x;
2752         struct feature_group *fg = NULL;
2753         struct feature_group_exten *fge;
2754         struct ast_call_feature *tmpfeature;
2755         char *tmp, *tok;
2756         int res = AST_FEATURE_RETURN_PASSDIGITS;
2757         int feature_detected = 0;
2758
2759         if (!(peer && chan && config) && operation) {
2760                 return -1; /* can not run feature operation */
2761         }
2762
2763         ast_rwlock_rdlock(&features_lock);
2764         for (x = 0; x < FEATURES_COUNT; x++) {
2765                 if ((ast_test_flag(features, builtin_features[x].feature_mask)) &&
2766                     !ast_strlen_zero(builtin_features[x].exten)) {
2767                         /* Feature is up for consideration */
2768                         if (!strcmp(builtin_features[x].exten, code)) {
2769                                 ast_debug(3, "Feature detected: fname=%s sname=%s exten=%s\n", builtin_features[x].fname, builtin_features[x].sname, builtin_features[x].exten);
2770                                 if (operation) {
2771                                         res = builtin_features[x].operation(chan, peer, config, code, sense, NULL);
2772                                 }
2773                                 memcpy(feature, &builtin_features[x], sizeof(feature));
2774                                 feature_detected = 1;
2775                                 break;
2776                         } else if (!strncmp(builtin_features[x].exten, code, strlen(code))) {
2777                                 if (res == AST_FEATURE_RETURN_PASSDIGITS)
2778                                         res = AST_FEATURE_RETURN_STOREDIGITS;
2779                         }
2780                 }
2781         }
2782         ast_rwlock_unlock(&features_lock);
2783
2784         if (ast_strlen_zero(dynamic_features_buf) || feature_detected) {
2785                 return res;
2786         }
2787
2788         tmp = dynamic_features_buf;
2789
2790         while ((tok = strsep(&tmp, "#"))) {
2791                 AST_RWLIST_RDLOCK(&feature_groups);
2792
2793                 fg = find_group(tok);
2794
2795                 if (fg) {
2796                         AST_LIST_TRAVERSE(&fg->features, fge, entry) {
2797                                 if (!strcmp(fge->exten, code)) {
2798                                         if (operation) {
2799                                                 res = fge->feature->operation(chan, peer, config, code, sense, fge->feature);
2800                                         }
2801                                         memcpy(feature, fge->feature, sizeof(feature));
2802                                         if (res != AST_FEATURE_RETURN_KEEPTRYING) {
2803                                                 AST_RWLIST_UNLOCK(&feature_groups);
2804                                                 break;
2805                                         }
2806                                         res = AST_FEATURE_RETURN_PASSDIGITS;
2807                                 } else if (!strncmp(fge->exten, code, strlen(code))) {
2808                                         res = AST_FEATURE_RETURN_STOREDIGITS;
2809                                 }
2810                         }
2811                         if (fge) {
2812                                 break;
2813                         }
2814                 }
2815
2816                 AST_RWLIST_UNLOCK(&feature_groups);
2817
2818                 AST_RWLIST_RDLOCK(&feature_list);
2819
2820                 if (!(tmpfeature = find_dynamic_feature(tok))) {
2821                         AST_RWLIST_UNLOCK(&feature_list);
2822                         continue;
2823                 }
2824
2825                 /* Feature is up for consideration */
2826                 if (!strcmp(tmpfeature->exten, code)) {
2827                         ast_verb(3, " Feature Found: %s exten: %s\n",tmpfeature->sname, tok);
2828                         if (operation) {
2829                                 res = tmpfeature->operation(chan, peer, config, code, sense, tmpfeature);
2830                         }
2831                         memcpy(feature, tmpfeature, sizeof(feature));
2832                         if (res != AST_FEATURE_RETURN_KEEPTRYING) {
2833                                 AST_RWLIST_UNLOCK(&feature_list);
2834                                 break;
2835                         }
2836                         res = AST_FEATURE_RETURN_PASSDIGITS;
2837                 } else if (!strncmp(tmpfeature->exten, code, strlen(code)))
2838                         res = AST_FEATURE_RETURN_STOREDIGITS;
2839
2840                 AST_RWLIST_UNLOCK(&feature_list);
2841         }
2842
2843         return res;
2844 }
2845
2846 /*!
2847  * \brief Check the dynamic features
2848  * \param chan,peer,config,code,sense
2849  *
2850  * \retval res on success.
2851  * \retval -1 on failure.
2852 */
2853
2854 static int feature_interpret(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense) {
2855
2856         char dynamic_features_buf[128];
2857         const char *peer_dynamic_features, *chan_dynamic_features;
2858         struct ast_flags features;
2859         struct ast_call_feature feature;
2860         if (sense == FEATURE_SENSE_CHAN) {
2861                 ast_copy_flags(&features, &(config->features_caller), AST_FLAGS_ALL);
2862         }
2863         else {
2864                 ast_copy_flags(&features, &(config->features_callee), AST_FLAGS_ALL);
2865         }
2866
2867         ast_channel_lock(peer);
2868         peer_dynamic_features = ast_strdupa(S_OR(pbx_builtin_getvar_helper(peer, "DYNAMIC_FEATURES"),""));
2869         ast_channel_unlock(peer);
2870
2871         ast_channel_lock(chan);
2872         chan_dynamic_features = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "DYNAMIC_FEATURES"),""));
2873         ast_channel_unlock(chan);
2874
2875         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,""));
2876
2877         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);
2878
2879         return feature_interpret_helper(chan, peer, config, code, sense, dynamic_features_buf, &features, 1, &feature);
2880 }
2881
2882
2883 int ast_feature_detect(struct ast_channel *chan, struct ast_flags *features, const char *code, struct ast_call_feature *feature) {
2884
2885         return feature_interpret_helper(chan, NULL, NULL, code, 0, NULL, features, 0, feature);
2886 }
2887
2888 static void set_config_flags(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config)
2889 {
2890         int x;
2891
2892         ast_clear_flag(config, AST_FLAGS_ALL);
2893
2894         ast_rwlock_rdlock(&features_lock);
2895         for (x = 0; x < FEATURES_COUNT; x++) {
2896                 if (!ast_test_flag(builtin_features + x, AST_FEATURE_FLAG_NEEDSDTMF))
2897                         continue;
2898
2899                 if (ast_test_flag(&(config->features_caller), builtin_features[x].feature_mask))
2900                         ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
2901
2902                 if (ast_test_flag(&(config->features_callee), builtin_features[x].feature_mask))
2903                         ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
2904         }
2905         ast_rwlock_unlock(&features_lock);
2906
2907         if (chan && peer && !(ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_0) && ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_1))) {
2908                 const char *dynamic_features = pbx_builtin_getvar_helper(chan, "DYNAMIC_FEATURES");
2909
2910                 if (dynamic_features) {
2911                         char *tmp = ast_strdupa(dynamic_features);
2912                         char *tok;
2913                         struct ast_call_feature *feature;
2914
2915                         /* while we have a feature */
2916                         while ((tok = strsep(&tmp, "#"))) {
2917                                 struct feature_group *fg;
2918
2919                                 AST_RWLIST_RDLOCK(&feature_groups);
2920                                 AST_RWLIST_TRAVERSE(&feature_groups, fg, entry) {
2921                                         struct feature_group_exten *fge;
2922
2923                                         AST_LIST_TRAVERSE(&fg->features, fge, entry) {
2924                                                 if (ast_test_flag(fge->feature, AST_FEATURE_FLAG_BYCALLER)) {
2925                                                         ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
2926                                                 }
2927                                                 if (ast_test_flag(fge->feature, AST_FEATURE_FLAG_BYCALLEE)) {
2928                                                         ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
2929                                                 }
2930                                         }
2931                                 }
2932                                 AST_RWLIST_UNLOCK(&feature_groups);
2933
2934                                 AST_RWLIST_RDLOCK(&feature_list);
2935                                 if ((feature = find_dynamic_feature(tok)) && ast_test_flag(feature, AST_FEATURE_FLAG_NEEDSDTMF)) {
2936                                         if (ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLER)) {
2937                                                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
2938                                         }
2939                                         if (ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLEE)) {
2940                                                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
2941                                         }
2942                                 }
2943                                 AST_RWLIST_UNLOCK(&feature_list);
2944                         }
2945                 }
2946         }
2947 }
2948
2949 /*!
2950  * \internal
2951  * \brief Get feature and dial.
2952  *
2953  * \param caller Channel to represent as the calling channel for the dialed channel.
2954  * \param caller_name Original caller channel name.
2955  * \param requestor Channel to say is requesting the dial (usually the caller).
2956  * \param transferee Channel that the dialed channel will be transferred to.
2957  * \param type Channel technology type to dial.
2958  * \param format Codec formats for dialed channel.
2959  * \param data Dialed channel extra parameters for ast_request() and ast_call().
2960  * \param timeout Time limit for dialed channel to answer in ms. Must be greater than zero.
2961  * \param outstate Status of dialed channel if unsuccessful.
2962  * \param language Language of the caller.
2963  *
2964  * \note
2965  * outstate can be:
2966  * 0, AST_CONTROL_BUSY, AST_CONTROL_CONGESTION,
2967  * AST_CONTROL_ANSWER, or AST_CONTROL_UNHOLD.  If
2968  * AST_CONTROL_UNHOLD then the caller channel cancelled the
2969  * transfer or the dialed channel did not answer before the
2970  * timeout.
2971  *
2972  * \details
2973  * Request channel, set channel variables, initiate call,
2974  * check if they want to disconnect, go into loop, check if timeout has elapsed,
2975  * check if person to be transfered hung up, check for answer break loop,
2976  * set cdr return channel.
2977  *
2978  * \retval Channel Connected channel for transfer.
2979  * \retval NULL on failure to get third party connected.
2980  *
2981  * \note This is similar to __ast_request_and_dial() in channel.c
2982  */
2983 static struct ast_channel *feature_request_and_dial(struct ast_channel *caller,
2984         const char *caller_name, struct ast_channel *requestor,
2985         struct ast_channel *transferee, const char *type, struct ast_format_cap *cap, void *data,
2986         int timeout, int *outstate, const char *language)
2987 {
2988         int state = 0;
2989         int cause = 0;
2990         int to;
2991         int caller_hungup;
2992         int transferee_hungup;
2993         struct ast_channel *chan;
2994         struct ast_channel *monitor_chans[3];
2995         struct ast_channel *active_channel;
2996         int res;
2997         int ready = 0;
2998         struct timeval started;
2999         int x, len = 0;
3000         char *disconnect_code = NULL, *dialed_code = NULL;
3001         struct ast_format_cap *tmp_cap;
3002         struct ast_format best_audio_fmt;
3003         struct ast_frame *f;
3004         AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
3005
3006         tmp_cap = ast_format_cap_alloc_nolock();
3007         if (!tmp_cap) {
3008                 return NULL;
3009         }
3010         ast_best_codec(cap, &best_audio_fmt);
3011         ast_format_cap_add(tmp_cap, &best_audio_fmt);
3012
3013         caller_hungup = ast_check_hangup(caller);
3014
3015         if (!(chan = ast_request(type, tmp_cap, requestor, data, &cause))) {
3016                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
3017                 switch (cause) {
3018                 case AST_CAUSE_BUSY:
3019                         state = AST_CONTROL_BUSY;
3020                         break;
3021                 case AST_CAUSE_CONGESTION:
3022                         state = AST_CONTROL_CONGESTION;
3023                         break;
3024                 default:
3025                         state = 0;
3026                         break;
3027                 }
3028                 goto done;
3029         }
3030
3031         ast_string_field_set(chan, language, language);
3032         ast_channel_inherit_variables(caller, chan);
3033         pbx_builtin_setvar_helper(chan, "TRANSFERERNAME", caller_name);
3034
3035         ast_channel_lock(chan);
3036         ast_connected_line_copy_from_caller(&chan->connected, &requestor->caller);
3037         ast_channel_unlock(chan);
3038
3039         if (ast_call(chan, data, timeout)) {
3040                 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
3041                 switch (chan->hangupcause) {
3042                 case AST_CAUSE_BUSY:
3043                         state = AST_CONTROL_BUSY;
3044                         break;
3045                 case AST_CAUSE_CONGESTION:
3046                         state = AST_CONTROL_CONGESTION;
3047                         break;
3048                 default:
3049                         state = 0;
3050                         break;
3051                 }
3052                 goto done;
3053         }
3054
3055         /* support dialing of the featuremap disconnect code while performing an attended tranfer */
3056         ast_rwlock_rdlock(&features_lock);
3057         for (x = 0; x < FEATURES_COUNT; x++) {
3058                 if (strcasecmp(builtin_features[x].sname, "disconnect"))
3059                         continue;
3060
3061                 disconnect_code = builtin_features[x].exten;
3062                 len = strlen(disconnect_code) + 1;
3063                 dialed_code = alloca(len);
3064                 memset(dialed_code, 0, len);
3065                 break;
3066         }
3067         ast_rwlock_unlock(&features_lock);
3068         x = 0;
3069         started = ast_tvnow();
3070         to = timeout;
3071         AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
3072
3073         ast_poll_channel_add(caller, chan);
3074
3075         transferee_hungup = 0;
3076         while (!ast_check_hangup(transferee) && (chan->_state != AST_STATE_UP)) {
3077                 int num_chans = 0;
3078
3079                 monitor_chans[num_chans++] = transferee;
3080                 monitor_chans[num_chans++] = chan;
3081                 if (!caller_hungup) {
3082                         if (ast_check_hangup(caller)) {
3083                                 caller_hungup = 1;
3084
3085 #if defined(ATXFER_NULL_TECH)
3086                                 /* Change caller's name to ensure that it will remain unique. */
3087                                 set_new_chan_name(caller);
3088
3089                                 /*
3090                                  * Get rid of caller's physical technology so it is free for
3091                                  * other calls.
3092                                  */
3093                                 set_null_chan_tech(caller);
3094 #endif  /* defined(ATXFER_NULL_TECH) */
3095                         } else {
3096                                 /* caller is not hungup so monitor it. */
3097                                 monitor_chans[num_chans++] = caller;
3098                         }
3099                 }
3100
3101                 /* see if the timeout has been violated */
3102                 if (ast_tvdiff_ms(ast_tvnow(), started) > timeout) {
3103                         state = AST_CONTROL_UNHOLD;
3104                         ast_log(LOG_NOTICE, "We exceeded our AT-timeout for %s\n", chan->name);
3105                         break; /*doh! timeout*/
3106                 }
3107
3108                 active_channel = ast_waitfor_n(monitor_chans, num_chans, &to);
3109                 if (!active_channel)
3110                         continue;
3111
3112                 f = NULL;
3113                 if (transferee == active_channel) {
3114                         struct ast_frame *dup_f;
3115
3116                         f = ast_read(transferee);
3117                         if (f == NULL) { /*doh! where'd he go?*/
3118                                 transferee_hungup = 1;
3119                                 state = 0;
3120                                 break;
3121                         }
3122                         if (ast_is_deferrable_frame(f)) {
3123                                 dup_f = ast_frisolate(f);
3124                                 if (dup_f) {
3125                                         if (dup_f == f) {
3126                                                 f = NULL;
3127                                         }
3128                                         AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
3129                                 }
3130                         }
3131                 } else if (chan == active_channel) {
3132                         if (!ast_strlen_zero(chan->call_forward)) {
3133                                 chan = ast_call_forward(caller, chan, NULL, tmp_cap, NULL, &state);
3134                                 if (!chan) {
3135                                         break;
3136                                 }
3137                                 continue;
3138                         }
3139                         f = ast_read(chan);
3140                         if (f == NULL) { /*doh! where'd he go?*/
3141                                 switch (chan->hangupcause) {
3142                                 case AST_CAUSE_BUSY:
3143                                         state = AST_CONTROL_BUSY;
3144                                         break;
3145                                 case AST_CAUSE_CONGESTION:
3146                                         state = AST_CONTROL_CONGESTION;
3147                                         break;
3148                                 default:
3149                                         state = 0;
3150                                         break;
3151                                 }
3152                                 break;
3153                         }
3154
3155                         if (f->frametype == AST_FRAME_CONTROL) {
3156                                 if (f->subclass.integer == AST_CONTROL_RINGING) {
3157                                         ast_verb(3, "%s is ringing\n", chan->name);
3158                                         ast_indicate(caller, AST_CONTROL_RINGING);
3159                                 } else if (f->subclass.integer == AST_CONTROL_BUSY) {
3160                                         state = f->subclass.integer;
3161                                         ast_verb(3, "%s is busy\n", chan->name);
3162                                         ast_indicate(caller, AST_CONTROL_BUSY);
3163                                         ast_frfree(f);
3164                                         break;
3165                                 } else if (f->subclass.integer == AST_CONTROL_CONGESTION) {
3166                                         state = f->subclass.integer;
3167                                         ast_verb(3, "%s is congested\n", chan->name);
3168                                         ast_indicate(caller, AST_CONTROL_CONGESTION);
3169                                         ast_frfree(f);
3170                                         break;
3171                                 } else if (f->subclass.integer == AST_CONTROL_ANSWER) {
3172                                         /* This is what we are hoping for */
3173                                         state = f->subclass.integer;
3174                                         ast_frfree(f);
3175                                         ready=1;
3176                                         break;
3177                                 } else if (f->subclass.integer == AST_CONTROL_CONNECTED_LINE) {
3178                                         if (caller_hungup) {
3179                                                 struct ast_party_connected_line connected;
3180
3181                                                 /* Just save it for the transfer. */
3182                                                 ast_party_connected_line_set_init(&connected, &caller->connected);
3183                                                 res = ast_connected_line_parse_data(f->data.ptr, f->datalen,
3184                                                         &connected);
3185                                                 if (!res) {
3186                                                         ast_channel_set_connected_line(caller, &connected, NULL);
3187                                                 }
3188                                                 ast_party_connected_line_free(&connected);
3189                                         } else {
3190                                                 ast_autoservice_start(transferee);
3191                                                 if (ast_channel_connected_line_macro(chan, caller, f, 1, 1)) {
3192                                                         ast_indicate_data(caller, AST_CONTROL_CONNECTED_LINE,
3193                                                                 f->data.ptr, f->datalen);
3194                                                 }
3195                                                 ast_autoservice_stop(transferee);
3196                                         }
3197                                 } else if (f->subclass.integer == AST_CONTROL_REDIRECTING) {
3198                                         if (!caller_hungup) {
3199                                                 ast_autoservice_start(transferee);
3200                                                 if (ast_channel_redirecting_macro(chan, caller, f, 1, 1)) {
3201                                                         ast_indicate_data(caller, AST_CONTROL_REDIRECTING,
3202                                                                 f->data.ptr, f->datalen);
3203                                                 }
3204                                                 ast_autoservice_stop(transferee);
3205                                         }
3206                                 } else if (f->subclass.integer != -1 && f->subclass.integer != AST_CONTROL_PROGRESS) {
3207                                         ast_log(LOG_NOTICE, "Don't know what to do about control frame: %d\n", f->subclass.integer);
3208                                 }
3209                                 /* else who cares */
3210                         } else if (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO) {
3211                                 ast_write(caller, f);
3212                         }
3213                 } else if (caller == active_channel) {
3214                         f = ast_read(caller);
3215                         if (f) {
3216                                 if (f->frametype == AST_FRAME_DTMF) {
3217                                         dialed_code[x++] = f->subclass.integer;
3218                                         dialed_code[x] = '\0';
3219                                         if (strlen(dialed_code) == len) {
3220                                                 x = 0;
3221                                         } else if (x && strncmp(dialed_code, disconnect_code, x)) {
3222                                                 x = 0;
3223                                                 dialed_code[x] = '\0';
3224                                         }
3225                                         if (*dialed_code && !strcmp(dialed_code, disconnect_code)) {
3226                                                 /* Caller Canceled the call */
3227                                                 state = AST_CONTROL_UNHOLD;
3228                                                 ast_frfree(f);
3229                                                 break;
3230                                         }
3231                                 } else if (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO) {
3232                                         ast_write(chan, f);
3233                                 }
3234                         }
3235                 }
3236                 if (f)
3237                         ast_frfree(f);
3238         } /* end while */
3239
3240         ast_poll_channel_del(caller, chan);
3241
3242         /*
3243          * We need to free all the deferred frames, but we only need to
3244          * queue the deferred frames if no hangup was received.
3245          */
3246         ast_channel_lock(transferee);
3247         transferee_hungup = (transferee_hungup || ast_check_hangup(transferee));
3248         while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
3249                 if (!transferee_hungup) {
3250                         ast_queue_frame_head(transferee, f);
3251                 }
3252                 ast_frfree(f);
3253         }
3254         ast_channel_unlock(transferee);
3255
3256 done:
3257         ast_indicate(caller, -1);
3258         if (chan && (ready || chan->_state == AST_STATE_UP)) {
3259                 state = AST_CONTROL_ANSWER;
3260         } else if (chan) {
3261                 ast_hangup(chan);
3262                 chan = NULL;
3263         }
3264
3265         tmp_cap = ast_format_cap_destroy(tmp_cap);
3266
3267         if (outstate)
3268                 *outstate = state;
3269
3270         return chan;
3271 }
3272
3273 void ast_channel_log(char *title, struct ast_channel *chan);
3274
3275 void ast_channel_log(char *title, struct ast_channel *chan) /* for debug, this is handy enough to justify keeping it in the source */
3276 {
3277        ast_log(LOG_NOTICE, "______ %s (%lx)______\n", title, (unsigned long)chan);
3278        ast_log(LOG_NOTICE, "CHAN: name: %s;  appl: %s; data: %s; contxt: %s;  exten: %s; pri: %d;\n",
3279                        chan->name, chan->appl, chan->data, chan->context, chan->exten, chan->priority);
3280        ast_log(LOG_NOTICE, "CHAN: acctcode: %s;  dialcontext: %s; amaflags: %x; maccontxt: %s;  macexten: %s; macpri: %d;\n",
3281                        chan->accountcode, chan->dialcontext, chan->amaflags, chan->macrocontext, chan->macroexten, chan->macropriority);
3282        ast_log(LOG_NOTICE, "CHAN: masq: %p;  masqr: %p; _bridge: %p; uniqueID: %s; linkedID:%s\n",
3283                        chan->masq, chan->masqr,
3284                        chan->_bridge, chan->uniqueid, chan->linkedid);
3285        if (chan->masqr)
3286                ast_log(LOG_NOTICE, "CHAN: masquerading as: %s;  cdr: %p;\n",
3287                                chan->masqr->name, chan->masqr->cdr);
3288        if (chan->_bridge)
3289                ast_log(LOG_NOTICE, "CHAN: Bridged to %s\n", chan->_bridge->name);
3290
3291         ast_log(LOG_NOTICE, "===== done ====\n");
3292 }
3293
3294 /*!
3295  * \brief return the first unlocked cdr in a possible chain
3296 */
3297 static struct ast_cdr *pick_unlocked_cdr(struct ast_cdr *cdr)
3298 {
3299         struct ast_cdr *cdr_orig = cdr;
3300         while (cdr) {
3301                 if (!ast_test_flag(cdr,AST_CDR_FLAG_LOCKED))
3302                         return cdr;
3303                 cdr = cdr->next;
3304         }
3305         return cdr_orig; /* everybody LOCKED or some other weirdness, like a NULL */
3306 }
3307
3308 static void set_bridge_features_on_config(struct ast_bridge_config *config, const char *features)
3309 {
3310         const char *feature;
3311
3312         if (ast_strlen_zero(features)) {
3313                 return;
3314         }
3315
3316         for (feature = features; *feature; feature++) {
3317                 switch (*feature) {
3318                 case 'T' :
3319                 case 't' :
3320                         ast_set_flag(&(config->features_caller), AST_FEATURE_REDIRECT);
3321                         break;
3322                 case 'K' :
3323                 case 'k' :
3324                         ast_set_flag(&(config->features_caller), AST_FEATURE_PARKCALL);
3325                         break;
3326                 case 'H' :
3327                 case 'h' :
3328                         ast_set_flag(&(config->features_caller), AST_FEATURE_DISCONNECT);
3329                         break;
3330                 case 'W' :
3331                 case 'w' :
3332                         ast_set_flag(&(config->features_caller), AST_FEATURE_AUTOMON);
3333                         break;
3334                 default :
3335                         ast_log(LOG_WARNING, "Skipping unknown feature code '%c'\n", *feature);
3336                 }
3337         }
3338 }
3339
3340 static void add_features_datastores(struct ast_channel *caller, struct ast_channel *callee, struct ast_bridge_config *config)
3341 {
3342         struct ast_datastore *ds_callee_features = NULL, *ds_caller_features = NULL;
3343         struct ast_dial_features *callee_features = NULL, *caller_features = NULL;
3344
3345         ast_channel_lock(caller);
3346         ds_caller_features = ast_channel_datastore_find(caller, &dial_features_info, NULL);
3347         ast_channel_unlock(caller);
3348         if (!ds_caller_features) {
3349                 if (!(ds_caller_features = ast_datastore_alloc(&dial_features_info, NULL))) {
3350                         ast_log(LOG_WARNING, "Unable to create channel datastore for caller features. Aborting!\n");
3351                         return;
3352                 }
3353                 if (!(caller_features = ast_calloc(1, sizeof(*caller_features)))) {
3354                         ast_log(LOG_WARNING, "Unable to allocate memory for callee feature flags. Aborting!\n");
3355                         ast_datastore_free(ds_caller_features);
3356                         return;
3357                 }
3358                 ds_caller_features->inheritance = DATASTORE_INHERIT_FOREVER;
3359                 caller_features->is_caller = 1;
3360                 ast_copy_flags(&(caller_features->features_callee), &(config->features_callee), AST_FLAGS_ALL);
3361                 ast_copy_flags(&(caller_features->features_caller), &(config->features_caller), AST_FLAGS_ALL);
3362                 ds_caller_features->data = caller_features;
3363                 ast_channel_lock(caller);
3364                 ast_channel_datastore_add(caller, ds_caller_features);
3365                 ast_channel_unlock(caller);
3366         } else {
3367                 /* If we don't return here, then when we do a builtin_atxfer we will copy the disconnect
3368                  * flags over from the atxfer to the caller */
3369                 return;
3370         }
3371
3372         ast_channel_lock(callee);
3373         ds_callee_features = ast_channel_datastore_find(callee, &dial_features_info, NULL);
3374         ast_channel_unlock(callee);
3375         if (!ds_callee_features) {
3376                 if (!(ds_callee_features = ast_datastore_alloc(&dial_features_info, NULL))) {
3377                         ast_log(LOG_WARNING, "Unable to create channel datastore for callee features. Aborting!\n");
3378                         return;
3379                 }
3380                 if (!(callee_features = ast_calloc(1, sizeof(*callee_features)))) {
3381                         ast_log(LOG_WARNING, "Unable to allocate memory for callee feature flags. Aborting!\n");
3382                         ast_datastore_free(ds_callee_features);
3383                         return;
3384                 }
3385                 ds_callee_features->inheritance = DATASTORE_INHERIT_FOREVER;
3386                 callee_features->is_caller = 0;
3387                 ast_copy_flags(&(callee_features->features_callee), &(config->features_caller), AST_FLAGS_ALL);
3388                 ast_copy_flags(&(callee_features->features_caller), &(config->features_callee), AST_FLAGS_ALL);
3389                 ds_callee_features->data = callee_features;
3390                 ast_channel_lock(callee);
3391                 ast_channel_datastore_add(callee, ds_callee_features);
3392                 ast_channel_unlock(callee);
3393         }
3394
3395         return;
3396 }
3397
3398 /*!
3399  * \brief bridge the call and set CDR
3400  * \param chan,peer,config
3401  * 
3402  * Set start time, check for two channels,check if monitor on
3403  * check for feature activation, create new CDR
3404  * \retval res on success.
3405  * \retval -1 on failure to bridge.
3406 */
3407 int ast_bridge_call(struct ast_channel *chan,struct ast_channel *peer,struct ast_bridge_config *config)
3408 {
3409         /* Copy voice back and forth between the two channels.  Give the peer
3410            the ability to transfer calls with '#<extension' syntax. */
3411         struct ast_frame *f;
3412         struct ast_channel *who;
3413         char chan_featurecode[FEATURE_MAX_LEN + 1]="";
3414         char peer_featurecode[FEATURE_MAX_LEN + 1]="";
3415         char orig_channame[AST_MAX_EXTENSION];
3416         char orig_peername[AST_MAX_EXTENSION];
3417         int res;
3418         int diff;
3419         int hasfeatures=0;
3420         int hadfeatures=0;
3421         int autoloopflag;
3422         int we_disabled_peer_cdr = 0;
3423         struct ast_option_header *aoh;
3424         struct ast_cdr *bridge_cdr = NULL;
3425         struct ast_cdr *orig_peer_cdr = NULL;
3426         struct ast_cdr *chan_cdr = chan->cdr; /* the proper chan cdr, if there are forked cdrs */
3427         struct ast_cdr *peer_cdr = peer->cdr; /* the proper chan cdr, if there are forked cdrs */
3428         struct ast_cdr *new_chan_cdr = NULL; /* the proper chan cdr, if there are forked cdrs */
3429         struct ast_cdr *new_peer_cdr = NULL; /* the proper chan cdr, if there are forked cdrs */
3430
3431         if (chan && peer) {
3432                 pbx_builtin_setvar_helper(chan, "BRIDGEPEER", peer->name);
3433                 pbx_builtin_setvar_helper(peer, "BRIDGEPEER", chan->name);
3434         } else if (chan) {
3435                 pbx_builtin_setvar_helper(chan, "BLINDTRANSFER", NULL);
3436         }
3437
3438         set_bridge_features_on_config(config, pbx_builtin_getvar_helper(chan, "BRIDGE_FEATURES"));
3439         add_features_datastores(chan, peer, config);
3440
3441         /* This is an interesting case.  One example is if a ringing channel gets redirected to
3442          * an extension that picks up a parked call.  This will make sure that the call taken
3443          * out of parking gets told that the channel it just got bridged to is still ringing. */
3444         if (chan->_state == AST_STATE_RINGING && peer->visible_indication != AST_CONTROL_RINGING) {
3445                 ast_indicate(peer, AST_CONTROL_RINGING);
3446         }
3447
3448         if (monitor_ok) {
3449                 const char *monitor_exec;
3450                 struct ast_channel *src = NULL;
3451                 if (!monitor_app) {
3452                         if (!(monitor_app = pbx_findapp("Monitor")))
3453                                 monitor_ok=0;
3454                 }
3455                 if ((monitor_exec = pbx_builtin_getvar_helper(chan, "AUTO_MONITOR"))) 
3456                         src = chan;
3457                 else if ((monitor_exec = pbx_builtin_getvar_helper(peer, "AUTO_MONITOR")))
3458                         src = peer;
3459                 if (monitor_app && src) {
3460                         char *tmp = ast_strdupa(monitor_exec);
3461                         pbx_exec(src, monitor_app, tmp);
3462                 }
3463         }
3464
3465         set_config_flags(chan, peer, config);
3466
3467         /* Answer if need be */
3468         if (chan->_state != AST_STATE_UP) {
3469                 if (ast_raw_answer(chan, 1)) {
3470                         return -1;
3471                 }
3472         }
3473
3474 #ifdef FOR_DEBUG
3475         /* show the two channels and cdrs involved in the bridge for debug & devel purposes */
3476         ast_channel_log("Pre-bridge CHAN Channel info", chan);
3477         ast_channel_log("Pre-bridge PEER Channel info", peer);
3478 #endif
3479         /* two channels are being marked as linked here */
3480         ast_channel_set_linkgroup(chan,peer);
3481
3482         /* copy the userfield from the B-leg to A-leg if applicable */
3483         if (chan->cdr && peer->cdr && !ast_strlen_zero(peer->cdr->userfield)) {
3484                 char tmp[256];
3485                 if (!ast_strlen_zero(chan->cdr->userfield)) {
3486                         snprintf(tmp, sizeof(tmp), "%s;%s", chan->cdr->userfield, peer->cdr->userfield);
3487                         ast_cdr_appenduserfield(chan, tmp);
3488                 } else
3489                         ast_cdr_setuserfield(chan, peer->cdr->userfield);
3490                 /* Don't delete the CDR; just disable it. */
3491                 ast_set_flag(peer->cdr, AST_CDR_FLAG_POST_DISABLED);
3492                 we_disabled_peer_cdr = 1;
3493         }
3494         ast_copy_string(orig_channame,chan->name,sizeof(orig_channame));
3495         ast_copy_string(orig_peername,peer->name,sizeof(orig_peername));
3496         orig_peer_cdr = peer_cdr;
3497         
3498         if (!chan_cdr || (chan_cdr && !ast_test_flag(chan_cdr, AST_CDR_FLAG_POST_DISABLED))) {
3499                 
3500                 if (chan_cdr) {
3501                         ast_set_flag(chan_cdr, AST_CDR_FLAG_MAIN);
3502                         ast_cdr_update(chan);
3503                         bridge_cdr = ast_cdr_dup_unique_swap(chan_cdr);
3504                         /* rip any forked CDR's off of the chan_cdr and attach
3505                          * them to the bridge_cdr instead */
3506                         bridge_cdr->next = chan_cdr->next;
3507                         chan_cdr->next = NULL;
3508                         ast_copy_string(bridge_cdr->lastapp, S_OR(chan->appl, ""), sizeof(bridge_cdr->lastapp));
3509                         ast_copy_string(bridge_cdr->lastdata, S_OR(chan->data, ""), sizeof(bridge_cdr->lastdata));
3510                         if (peer_cdr && !ast_strlen_zero(peer_cdr->userfield)) {
3511                                 ast_copy_string(bridge_cdr->userfield, peer_cdr->userfield, sizeof(bridge_cdr->userfield));
3512                         }
3513                         ast_cdr_setaccount(peer, chan->accountcode);