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