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