Minor change to 318141 to improve parsing behavior.
[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 {
1051                 int start;
1052                 struct parkeduser *cur = NULL;
1053
1054                 if (ast_test_flag(args, AST_PARK_OPT_RANDOMIZE)) {
1055                         start = ast_random() % (parkinglot->parking_stop - parkinglot->parking_start + 1);
1056                 } else {
1057                         start = parkinglot->parking_start;
1058                 }
1059
1060                 for (i = start; 1; i++) {
1061                         if (i == parkinglot->parking_stop + 1) {
1062                                 i = parkinglot->parking_start - 1;
1063                                 break;
1064                         }
1065
1066                         AST_LIST_TRAVERSE(&parkinglot->parkings, cur, list) {
1067                                 if (cur->parkingnum == i) {
1068                                         break;
1069                                 }
1070                         }
1071                         if (!cur) {
1072                                 parking_space = i;
1073                                 break;
1074                         }
1075                 }
1076
1077                 if (i == start - 1 && cur) {
1078                         ast_log(LOG_WARNING, "No more parking spaces\n");
1079                         ast_free(pu);
1080                         AST_LIST_UNLOCK(&parkinglot->parkings);
1081                         parkinglot_unref(parkinglot);
1082                         return NULL;
1083                 }
1084                 /* Set pointer for next parking */
1085                 if (parkinglot->parkfindnext) 
1086                         parkinglot->parking_offset = parking_space - parkinglot->parking_start + 1;
1087                 snprintf(pu->parkingexten, sizeof(pu->parkingexten), "%d", parking_space);
1088         }
1089
1090         pu->notquiteyet = 1;
1091         pu->parkingnum = parking_space;
1092         pu->parkinglot = parkinglot;
1093         AST_LIST_INSERT_TAIL(&parkinglot->parkings, pu, list);
1094
1095         return pu;
1096 }
1097
1098 /* Park a call */
1099 static int park_call_full(struct ast_channel *chan, struct ast_channel *peer, struct ast_park_call_args *args)
1100 {
1101         struct ast_context *con;
1102         struct parkeduser *pu = args->pu;
1103         const char *event_from;
1104
1105         if (pu == NULL)
1106                 args->pu = pu = park_space_reserve(chan, peer, args);
1107         if (pu == NULL)
1108                 return 1; /* Continue execution if possible */
1109
1110         snprintf(pu->parkingexten, sizeof(pu->parkingexten), "%d", pu->parkingnum);
1111
1112         chan->appl = "Parked Call";
1113         chan->data = NULL;
1114
1115         pu->chan = chan;
1116
1117         /* Put the parked channel on hold if we have two different channels */
1118         if (chan != peer) {
1119                 if (ast_test_flag(args, AST_PARK_OPT_RINGING)) {
1120                         ast_indicate(pu->chan, AST_CONTROL_RINGING);
1121                 } else {
1122                         ast_indicate_data(pu->chan, AST_CONTROL_HOLD, 
1123                                 S_OR(pu->parkinglot->mohclass, NULL),
1124                                 !ast_strlen_zero(pu->parkinglot->mohclass) ? strlen(pu->parkinglot->mohclass) + 1 : 0);
1125                 }
1126         }
1127         
1128         pu->start = ast_tvnow();
1129         pu->parkingtime = (args->timeout > 0) ? args->timeout : pu->parkinglot->parkingtime;
1130         if (args->extout)
1131                 *(args->extout) = pu->parkingnum;
1132
1133         if (peer) { 
1134                 /* This is so ugly that it hurts, but implementing get_base_channel() on local channels
1135                         could have ugly side effects.  We could have transferer<->local,1<->local,2<->parking
1136                         and we need the callback name to be that of transferer.  Since local,1/2 have the same
1137                         name we can be tricky and just grab the bridged channel from the other side of the local
1138                 */
1139                 if (!strcasecmp(peer->tech->type, "Local")) {
1140                         struct ast_channel *tmpchan, *base_peer;
1141                         char other_side[AST_CHANNEL_NAME];
1142                         char *c;
1143                         ast_copy_string(other_side, S_OR(args->orig_chan_name, peer->name), sizeof(other_side));
1144                         if ((c = strrchr(other_side, ';'))) {
1145                                 *++c = '1';
1146                         }
1147                         if ((tmpchan = ast_channel_get_by_name(other_side))) {
1148                                 ast_channel_lock(tmpchan);
1149                                 if ((base_peer = ast_bridged_channel(tmpchan))) {
1150                                         ast_copy_string(pu->peername, base_peer->name, sizeof(pu->peername));
1151                                 }
1152                                 ast_channel_unlock(tmpchan);
1153                                 tmpchan = ast_channel_unref(tmpchan);
1154                         }
1155                 } else {
1156                         ast_copy_string(pu->peername, S_OR(args->orig_chan_name, peer->name), sizeof(pu->peername));
1157                 }
1158         }
1159
1160         /* Remember what had been dialed, so that if the parking
1161            expires, we try to come back to the same place */
1162
1163         pu->options_specified = (!ast_strlen_zero(args->return_con) || !ast_strlen_zero(args->return_ext) || args->return_pri);
1164
1165         /* If extension has options specified, they override all other possibilities
1166         such as the returntoorigin flag and transferred context. Information on
1167         extension options is lost here, so we set a flag */
1168
1169         ast_copy_string(pu->context, 
1170                 S_OR(args->return_con, S_OR(chan->macrocontext, chan->context)), 
1171                 sizeof(pu->context));
1172         ast_copy_string(pu->exten, 
1173                 S_OR(args->return_ext, S_OR(chan->macroexten, chan->exten)), 
1174                 sizeof(pu->exten));
1175         pu->priority = args->return_pri ? args->return_pri : 
1176                 (chan->macropriority ? chan->macropriority : chan->priority);
1177
1178         /* If parking a channel directly, don't quiet yet get parking running on it.
1179          * All parking lot entries are put into the parking lot with notquiteyet on. */
1180         if (peer != chan) 
1181                 pu->notquiteyet = 0;
1182
1183         /* Wake up the (presumably select()ing) thread */
1184         pthread_kill(parking_thread, SIGURG);
1185         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));
1186
1187         ast_cel_report_event(pu->chan, AST_CEL_PARK_START, NULL, pu->parkinglot->name, peer);
1188
1189         if (peer) {
1190                 event_from = peer->name;
1191         } else {
1192                 event_from = pbx_builtin_getvar_helper(chan, "BLINDTRANSFER");
1193         }
1194
1195         ast_manager_event(pu->chan, EVENT_FLAG_CALL, "ParkedCall",
1196                 "Exten: %s\r\n"
1197                 "Channel: %s\r\n"
1198                 "Parkinglot: %s\r\n"
1199                 "From: %s\r\n"
1200                 "Timeout: %ld\r\n"
1201                 "CallerIDNum: %s\r\n"
1202                 "CallerIDName: %s\r\n"
1203                 "Uniqueid: %s\r\n",
1204                 pu->parkingexten, pu->chan->name, pu->parkinglot->name, event_from ? event_from : "",
1205                 (long)pu->start.tv_sec + (long)(pu->parkingtime/1000) - (long)time(NULL),
1206                 S_COR(pu->chan->caller.id.number.valid, pu->chan->caller.id.number.str, "<unknown>"),
1207                 S_COR(pu->chan->caller.id.name.valid, pu->chan->caller.id.name.str, "<unknown>"),
1208                 pu->chan->uniqueid
1209                 );
1210
1211         if (peer && adsipark && ast_adsi_available(peer)) {
1212                 adsi_announce_park(peer, pu->parkingexten);     /* Only supports parking numbers */
1213                 ast_adsi_unload_session(peer);
1214         }
1215
1216         con = ast_context_find_or_create(NULL, NULL, pu->parkinglot->parking_con, registrar);
1217         if (!con)       /* Still no context? Bad */
1218                 ast_log(LOG_ERROR, "Parking context '%s' does not exist and unable to create\n", pu->parkinglot->parking_con);
1219         if (con) {
1220                 if (!ast_add_extension2(con, 1, pu->parkingexten, 1, NULL, NULL, parkedcall, ast_strdup(pu->parkingexten), ast_free_ptr, registrar))
1221                         notify_metermaids(pu->parkingexten, pu->parkinglot->parking_con, AST_DEVICE_INUSE);
1222         }
1223
1224         AST_LIST_UNLOCK(&pu->parkinglot->parkings);
1225
1226         /* Only say number if it's a number and the channel hasn't been masqueraded away */
1227         if (peer && !ast_test_flag(args, AST_PARK_OPT_SILENCE) && (ast_strlen_zero(args->orig_chan_name) || !strcasecmp(peer->name, args->orig_chan_name))) {
1228                 /* 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. */
1229                 ast_set_flag(peer, AST_FLAG_MASQ_NOSTREAM);
1230                 /* Tell the peer channel the number of the parking space */
1231                 ast_say_digits(peer, pu->parkingnum, "", peer->language);
1232                 ast_clear_flag(peer, AST_FLAG_MASQ_NOSTREAM);
1233         }
1234         if (peer == chan) { /* pu->notquiteyet = 1 */
1235                 /* Wake up parking thread if we're really done */
1236                 ast_indicate_data(pu->chan, AST_CONTROL_HOLD, 
1237                         S_OR(pu->parkinglot->mohclass, NULL),
1238                         !ast_strlen_zero(pu->parkinglot->mohclass) ? strlen(pu->parkinglot->mohclass) + 1 : 0);
1239                 pu->notquiteyet = 0;
1240                 pthread_kill(parking_thread, SIGURG);
1241         }
1242         return 0;
1243 }
1244
1245 /*! \brief Park a call */
1246 int ast_park_call(struct ast_channel *chan, struct ast_channel *peer, int timeout, const char *parkexten, int *extout)
1247 {
1248         struct ast_parkinglot *found_lot = ao2_callback(parkinglots, 0, find_parkinglot_by_exten_cb, (void *) parkexten);
1249
1250         struct ast_park_call_args args = {
1251                 .timeout = timeout,
1252                 .extout = extout,
1253                 .parkinglot = found_lot,
1254         };
1255
1256         return park_call_full(chan, peer, &args);
1257 }
1258
1259 /*!
1260  * \param rchan is the transferee
1261  * \param peer is the transferer
1262  */
1263 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)
1264 {
1265         struct ast_channel *chan;
1266         struct ast_frame *f;
1267         struct ast_park_call_args park_args = {0,};
1268
1269         if (!args) {
1270                 args = &park_args;
1271                 args->timeout = timeout;
1272                 args->extout = extout;
1273         }
1274
1275         if ((args->pu = park_space_reserve(rchan, peer, args)) == NULL) {
1276                 if (peer) {
1277                         ast_stream_and_wait(peer, "pbx-parkingfailed", "");
1278                 }
1279                 return AST_FEATURE_RETURN_PARKFAILED;
1280         }
1281
1282         /* Make a new, fake channel that we'll use to masquerade in the real one */
1283         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))) {
1284                 ast_log(LOG_WARNING, "Unable to create parked channel\n");
1285                 return -1;
1286         }
1287
1288         /* Make formats okay */
1289         chan->readformat = rchan->readformat;
1290         chan->writeformat = rchan->writeformat;
1291         ast_channel_masquerade(chan, rchan);
1292
1293         /* Setup the extensions and such */
1294         set_c_e_p(chan, rchan->context, rchan->exten, rchan->priority);
1295
1296         /* Setup the macro extension and such */
1297         ast_copy_string(chan->macrocontext,rchan->macrocontext,sizeof(chan->macrocontext));
1298         ast_copy_string(chan->macroexten,rchan->macroexten,sizeof(chan->macroexten));
1299         chan->macropriority = rchan->macropriority;
1300
1301         /* Make the masq execute */
1302         if ((f = ast_read(chan)))
1303                 ast_frfree(f);
1304
1305         if (peer == rchan) {
1306                 peer = chan;
1307         }
1308
1309         if (peer && (!play_announcement && args == &park_args)) {
1310                 args->orig_chan_name = ast_strdupa(peer->name);
1311         }
1312
1313         /* parking space reserved, return code check unnecessary */
1314         park_call_full(chan, peer, args);
1315
1316         return 0;
1317 }
1318
1319 /* Park call via masqueraded channel */
1320 int ast_masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, int timeout, int *extout)
1321 {
1322         return masq_park_call(rchan, peer, timeout, extout, 0, NULL);
1323 }
1324
1325 static int masq_park_call_announce(struct ast_channel *rchan, struct ast_channel *peer, struct ast_park_call_args *args)
1326 {
1327         return masq_park_call(rchan, peer, 0, NULL, 1, args);
1328 }
1329
1330 #ifdef TEST_FRAMEWORK
1331 static int fake_fixup(struct ast_channel *clonechan, struct ast_channel *original)
1332 {
1333         return 0;
1334 }
1335
1336 static struct ast_channel *create_test_channel(const struct ast_channel_tech *fake_tech)
1337 {
1338         struct ast_channel *test_channel1;
1339         struct ast_format tmp_fmt;
1340         if (!(test_channel1 = ast_channel_alloc(0, AST_STATE_DOWN, NULL, NULL, NULL,
1341         NULL, NULL, 0, 0, "TestChannel1"))) {
1342                 return NULL;
1343         }
1344
1345         /* normally this is done in the channel driver */
1346         ast_format_cap_add(test_channel1->nativeformats, ast_format_set(&tmp_fmt, AST_FORMAT_GSM, 0));
1347
1348         ast_format_set(&test_channel1->writeformat, AST_FORMAT_GSM, 0);
1349         ast_format_set(&test_channel1->rawwriteformat, AST_FORMAT_GSM, 0);
1350         ast_format_set(&test_channel1->readformat, AST_FORMAT_GSM, 0);
1351         ast_format_set(&test_channel1->rawreadformat, AST_FORMAT_GSM, 0);
1352
1353         test_channel1->tech = fake_tech;
1354
1355         return test_channel1;
1356 }
1357
1358 static int unpark_test_channel(struct ast_channel *toremove, struct ast_park_call_args *args)
1359 {
1360         struct ast_context *con;
1361         struct parkeduser *pu_toremove;
1362         args->pu->notquiteyet = 1; /* go ahead and stop processing the test parking */
1363         AST_LIST_LOCK(&args->pu->parkinglot->parkings);
1364         AST_LIST_TRAVERSE_SAFE_BEGIN(&args->pu->parkinglot->parkings, pu_toremove, list) {
1365                 con = ast_context_find(args->pu->parkinglot->parking_con);
1366                 if (con) {
1367                         if (ast_context_remove_extension2(con, args->pu->parkingexten, 1, NULL, 0)) {
1368                                 ast_log(LOG_WARNING, "Whoa, failed to remove the parking extension!\n");
1369                                 return -1;
1370                         } else {
1371                                 notify_metermaids(args->pu->parkingexten, pu_toremove->parkinglot->parking_con, AST_DEVICE_NOT_INUSE);
1372                         }
1373                 } else {
1374                         ast_log(LOG_WARNING, "Whoa, no parking context?\n");
1375                         return -1;
1376                 }
1377                 if (pu_toremove == args->pu) {
1378                         AST_LIST_REMOVE_CURRENT(list);
1379                         break;
1380                 }
1381         }
1382         AST_LIST_TRAVERSE_SAFE_END;
1383         AST_LIST_UNLOCK(&args->pu->parkinglot->parkings);
1384
1385         /* the only way this would be unsafe is if a timeout occurred, which is set at 45 sec */
1386         ast_free(args->pu);
1387         args->pu = NULL;
1388
1389         ast_hangup(toremove);
1390         return 0;
1391 }
1392
1393 AST_TEST_DEFINE(features_test)
1394 {
1395         int saved_parkeddynamic;
1396         struct ast_channel *test_channel1 = NULL;
1397         struct ast_channel *parked_chan = NULL;
1398         struct ast_parkinglot *dynlot = NULL;
1399         struct ast_park_call_args args = {
1400                 .timeout = DEFAULT_PARK_TIME,
1401         };
1402
1403         int res = -1;
1404
1405         static const struct ast_channel_tech fake_tech = {
1406                 .fixup = fake_fixup, /* silence warning from masquerade */
1407         };
1408
1409         static const char unique_parkinglot[] = "myuniquetestparkinglot3141592654";
1410         static const char parkinglot_range[] = "750-760";
1411
1412         switch (cmd) {
1413         case TEST_INIT:
1414                 info->name = "features_test";
1415                 info->category = "/main/features/";
1416                 info->summary = "Features unit test";
1417                 info->description =
1418                         "Tests whether parking respects PARKINGLOT settings";
1419                 return AST_TEST_NOT_RUN;
1420         case TEST_EXECUTE:
1421                 break;
1422         }
1423
1424         /* changing a config option is a bad practice, but must be done in this case */
1425         saved_parkeddynamic = parkeddynamic;
1426         parkeddynamic = 1;
1427
1428         if (!(test_channel1 = create_test_channel(&fake_tech))) {
1429                 goto exit_features_test;
1430         }
1431
1432         ast_test_status_update(test, "Test parking functionality with defaults\n");
1433         if (park_call_full(test_channel1, NULL, &args)) {
1434                 goto exit_features_test;
1435         }
1436         if (unpark_test_channel(test_channel1, &args)) {
1437                 goto exit_features_test;
1438         }
1439
1440         ast_test_status_update(test, "Check that certain parking options are respected\n");
1441         if (!(test_channel1 = create_test_channel(&fake_tech))) {
1442                 goto exit_features_test;
1443         }
1444         pbx_builtin_setvar_helper(test_channel1, "PARKINGLOT", unique_parkinglot);
1445         pbx_builtin_setvar_helper(test_channel1, "PARKINGDYNPOS", parkinglot_range);
1446         if (park_call_full(test_channel1, NULL, &args)) {
1447                 goto exit_features_test;
1448         }
1449         /* grab newly created parking lot for destruction in the end */
1450         dynlot = args.pu->parkinglot;
1451         if (!args.pu->parkingnum == 750 || strcasecmp(args.pu->parkinglot->name, unique_parkinglot)) {
1452                 ast_test_status_update(test, "Parking settings were not respected\n");
1453                 goto exit_features_test;
1454         } else {
1455                 ast_test_status_update(test, "Parking settings for non-masquerading park verified\n");
1456         }
1457         if (unpark_test_channel(test_channel1, &args)) {
1458                 goto exit_features_test;
1459         }
1460
1461         ast_test_status_update(test, "Check #2 that certain parking options are respected\n");
1462         if (!(test_channel1 = create_test_channel(&fake_tech))) {
1463                 goto exit_features_test;
1464         }
1465         pbx_builtin_setvar_helper(test_channel1, "PARKINGLOT", unique_parkinglot);
1466         pbx_builtin_setvar_helper(test_channel1, "PARKINGDYNPOS", parkinglot_range);
1467         if (masq_park_call(test_channel1, NULL, 0, NULL, 0, &args) == AST_FEATURE_RETURN_PARKFAILED) {
1468                 goto exit_features_test;
1469         }
1470         /* hangup zombie channel */
1471         ast_hangup(test_channel1);
1472         test_channel1 = NULL;
1473         if (!args.pu->parkingnum == 750 || strcasecmp(args.pu->parkinglot->name, unique_parkinglot)) {
1474                 ast_test_status_update(test, "Parking settings were not respected\n");
1475                 goto exit_features_test;
1476         } else {
1477                 ast_test_status_update(test, "Parking settings for masquerading park verified\n");
1478         }
1479         /* find the real channel */
1480         parked_chan = ast_channel_get_by_name("TestChannel1");
1481         if (unpark_test_channel(parked_chan, &args)) {
1482                 goto exit_features_test;
1483         }
1484
1485         res = 0;
1486
1487 exit_features_test:
1488
1489         if (test_channel1) {
1490                 ast_hangup(test_channel1);
1491         }
1492
1493         /* careful, if PARKINGDYNCONTEXT is tested, need to delete context */
1494         ao2_unlink(parkinglots, dynlot);
1495         parkeddynamic = saved_parkeddynamic;
1496         return res ? AST_TEST_FAIL : AST_TEST_PASS;
1497 }
1498 #endif
1499
1500
1501 /*!
1502  * \brief set caller and callee according to the direction
1503  * \param caller, callee, peer, chan, sense
1504  *
1505  * Detect who triggered feature and set callee/caller variables accordingly
1506 */
1507 static void set_peers(struct ast_channel **caller, struct ast_channel **callee,
1508         struct ast_channel *peer, struct ast_channel *chan, int sense)
1509 {
1510         if (sense == FEATURE_SENSE_PEER) {
1511                 *caller = peer;
1512                 *callee = chan;
1513         } else {
1514                 *callee = peer;
1515                 *caller = chan;
1516         }
1517 }
1518
1519 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)
1520 {
1521         int res = 0;
1522
1523         if (args) {
1524                 ast_debug(1, "Parkinglot specified for builtin_parkcall: %s\n", args->parkinglot->name);
1525         }
1526
1527         /* we used to set chan's exten and priority to "s" and 1
1528            here, but this generates (in some cases) an invalid
1529            extension, and if "s" exists, could errantly
1530            cause execution of extensions you don't expect. It
1531            makes more sense to let nature take its course
1532            when chan finishes, and let the pbx do its thing
1533            and hang up when the park is over.
1534         */
1535         if (chan->_state != AST_STATE_UP)
1536                 res = ast_answer(chan);
1537         if (!res)
1538                 res = ast_safe_sleep(chan, 1000);
1539
1540         if (!res) { /* one direction used to call park_call.... */
1541                 struct ast_channel *parker;
1542                 struct ast_channel *parkee;
1543                 set_peers(&parker, &parkee, peer, chan, sense);
1544                 res = masq_park_call_announce(parkee, parker, args);
1545                 /* PBX should hangup zombie channel if a masquerade actually occurred (res=0) */
1546         }
1547
1548         return res;
1549 }
1550
1551 /*! 
1552  * \brief support routing for one touch call parking
1553  * \param chan channel parking call
1554  * \param peer channel to be parked
1555  * \param config unsed
1556  * \param code unused
1557  * \param sense feature options
1558  *
1559  * \param data
1560  * Setup channel, set return exten,priority to 's,1'
1561  * answer chan, sleep chan, park call
1562 */
1563 static int builtin_parkcall(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
1564 {
1565         return parkcall_helper(chan, peer, config, code, sense, NULL);
1566 }
1567
1568 /*! \brief Play message to both caller and callee in bridged call, plays synchronously, autoservicing the
1569         other channel during the message, so please don't use this for very long messages
1570  */
1571 static int play_message_in_bridged_call(struct ast_channel *caller_chan, struct ast_channel *callee_chan, const char *audiofile)
1572 {
1573         /* First play for caller, put other channel on auto service */
1574         if (ast_autoservice_start(callee_chan))
1575                 return -1;
1576         ast_autoservice_ignore(callee_chan, AST_FRAME_DTMF_END);
1577         if (ast_stream_and_wait(caller_chan, audiofile, "")) {
1578                 ast_log(LOG_WARNING, "Failed to play automon message!\n");
1579                 ast_autoservice_stop(callee_chan);
1580                 return -1;
1581         }
1582         if (ast_autoservice_stop(callee_chan))
1583                 return -1;
1584         /* Then play for callee, put other channel on auto service */
1585         if (ast_autoservice_start(caller_chan))
1586                 return -1;
1587         ast_autoservice_ignore(caller_chan, AST_FRAME_DTMF_END);
1588         if (ast_stream_and_wait(callee_chan, audiofile, "")) {
1589                 ast_log(LOG_WARNING, "Failed to play automon message !\n");
1590                 ast_autoservice_stop(caller_chan);
1591                 return -1;
1592         }
1593         if (ast_autoservice_stop(caller_chan))
1594                 return -1;
1595         return(0);
1596 }
1597
1598 /*!
1599  * \brief Monitor a channel by DTMF
1600  * \param chan channel requesting monitor
1601  * \param peer channel to be monitored
1602  * \param config
1603  * \param code
1604  * \param sense feature options
1605  *
1606  * \param data
1607  * Check monitor app enabled, setup channels, both caller/callee chans not null
1608  * get TOUCH_MONITOR variable for filename if exists, exec monitor app.
1609  * \retval AST_FEATURE_RETURN_SUCCESS on success.
1610  * \retval -1 on error.
1611 */
1612 static int builtin_automonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
1613 {
1614         char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
1615         int x = 0;
1616         size_t len;
1617         struct ast_channel *caller_chan, *callee_chan;
1618         const char *automon_message_start = NULL;
1619         const char *automon_message_stop = NULL;
1620
1621         if (!monitor_ok) {
1622                 ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
1623                 return -1;
1624         }
1625
1626         if (!monitor_app && !(monitor_app = pbx_findapp("Monitor"))) {
1627                 monitor_ok = 0;
1628                 ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
1629                 return -1;
1630         }
1631
1632         set_peers(&caller_chan, &callee_chan, peer, chan, sense);
1633         if (caller_chan) {      /* Find extra messages */
1634                 automon_message_start = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_START");
1635                 automon_message_stop = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_STOP");
1636         }
1637
1638         if (!ast_strlen_zero(courtesytone)) {   /* Play courtesy tone if configured */
1639                 if(play_message_in_bridged_call(caller_chan, callee_chan, courtesytone) == -1) {
1640                         return -1;
1641                 }
1642         }
1643         
1644         if (callee_chan->monitor) {
1645                 ast_verb(4, "User hit '%s' to stop recording call.\n", code);
1646                 if (!ast_strlen_zero(automon_message_stop)) {
1647                         play_message_in_bridged_call(caller_chan, callee_chan, automon_message_stop);
1648                 }
1649                 callee_chan->monitor->stop(callee_chan, 1);
1650                 return AST_FEATURE_RETURN_SUCCESS;
1651         }
1652
1653         if (caller_chan && callee_chan) {
1654                 const char *touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_FORMAT");
1655                 const char *touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR");
1656                 const char *touch_monitor_prefix = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_PREFIX");
1657
1658                 if (!touch_format)
1659                         touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_FORMAT");
1660
1661                 if (!touch_monitor)
1662                         touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR");
1663         
1664                 if (!touch_monitor_prefix)
1665                         touch_monitor_prefix = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_PREFIX");
1666         
1667                 if (touch_monitor) {
1668                         len = strlen(touch_monitor) + 50;
1669                         args = alloca(len);
1670                         touch_filename = alloca(len);
1671                         snprintf(touch_filename, len, "%s-%ld-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), touch_monitor);
1672                         snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
1673                 } else {
1674                         caller_chan_id = ast_strdupa(S_COR(caller_chan->caller.id.number.valid,
1675                                 caller_chan->caller.id.number.str, caller_chan->name));
1676                         callee_chan_id = ast_strdupa(S_COR(callee_chan->caller.id.number.valid,
1677                                 callee_chan->caller.id.number.str, callee_chan->name));
1678                         len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
1679                         args = alloca(len);
1680                         touch_filename = alloca(len);
1681                         snprintf(touch_filename, len, "%s-%ld-%s-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), caller_chan_id, callee_chan_id);
1682                         snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
1683                 }
1684
1685                 for(x = 0; x < strlen(args); x++) {
1686                         if (args[x] == '/')
1687                                 args[x] = '-';
1688                 }
1689                 
1690                 ast_verb(4, "User hit '%s' to record call. filename: %s\n", code, args);
1691
1692                 pbx_exec(callee_chan, monitor_app, args);
1693                 pbx_builtin_setvar_helper(callee_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
1694                 pbx_builtin_setvar_helper(caller_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
1695
1696                 if (!ast_strlen_zero(automon_message_start)) {  /* Play start message for both channels */
1697                         play_message_in_bridged_call(caller_chan, callee_chan, automon_message_start);
1698                 }
1699         
1700                 return AST_FEATURE_RETURN_SUCCESS;
1701         }
1702         
1703         ast_log(LOG_NOTICE,"Cannot record the call. One or both channels have gone away.\n");   
1704         return -1;
1705 }
1706
1707 static int builtin_automixmonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
1708 {
1709         char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
1710         int x = 0;
1711         size_t len;
1712         struct ast_channel *caller_chan, *callee_chan;
1713         const char *mixmonitor_spy_type = "MixMonitor";
1714         int count = 0;
1715
1716         if (!mixmonitor_ok) {
1717                 ast_log(LOG_ERROR,"Cannot record the call. The mixmonitor application is disabled.\n");
1718                 return -1;
1719         }
1720
1721         if (!(mixmonitor_app = pbx_findapp("MixMonitor"))) {
1722                 mixmonitor_ok = 0;
1723                 ast_log(LOG_ERROR,"Cannot record the call. The mixmonitor application is disabled.\n");
1724                 return -1;
1725         }
1726
1727         set_peers(&caller_chan, &callee_chan, peer, chan, sense);
1728
1729         if (!ast_strlen_zero(courtesytone)) {
1730                 if (ast_autoservice_start(callee_chan))
1731                         return -1;
1732                 ast_autoservice_ignore(callee_chan, AST_FRAME_DTMF_END);
1733                 if (ast_stream_and_wait(caller_chan, courtesytone, "")) {
1734                         ast_log(LOG_WARNING, "Failed to play courtesy tone!\n");
1735                         ast_autoservice_stop(callee_chan);
1736                         return -1;
1737                 }
1738                 if (ast_autoservice_stop(callee_chan))
1739                         return -1;
1740         }
1741
1742         ast_channel_lock(callee_chan);
1743         count = ast_channel_audiohook_count_by_source(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
1744         ast_channel_unlock(callee_chan);
1745
1746         /* This means a mixmonitor is attached to the channel, running or not is unknown. */
1747         if (count > 0) {
1748                 
1749                 ast_verb(3, "User hit '%s' to stop recording call.\n", code);
1750
1751                 /* Make sure they are running */
1752                 ast_channel_lock(callee_chan);
1753                 count = ast_channel_audiohook_count_by_source_running(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
1754                 ast_channel_unlock(callee_chan);
1755                 if (count > 0) {
1756                         if (!stopmixmonitor_ok) {
1757                                 ast_log(LOG_ERROR,"Cannot stop recording the call. The stopmixmonitor application is disabled.\n");
1758                                 return -1;
1759                         }
1760                         if (!(stopmixmonitor_app = pbx_findapp("StopMixMonitor"))) {
1761                                 stopmixmonitor_ok = 0;
1762                                 ast_log(LOG_ERROR,"Cannot stop recording the call. The stopmixmonitor application is disabled.\n");
1763                                 return -1;
1764                         } else {
1765                                 pbx_exec(callee_chan, stopmixmonitor_app, "");
1766                                 return AST_FEATURE_RETURN_SUCCESS;
1767                         }
1768                 }
1769                 
1770                 ast_log(LOG_WARNING,"Stopped MixMonitors are attached to the channel.\n");      
1771         }                       
1772
1773         if (caller_chan && callee_chan) {
1774                 const char *touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR_FORMAT");
1775                 const char *touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR");
1776
1777                 if (!touch_format)
1778                         touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR_FORMAT");
1779
1780                 if (!touch_monitor)
1781                         touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR");
1782
1783                 if (touch_monitor) {
1784                         len = strlen(touch_monitor) + 50;
1785                         args = alloca(len);
1786                         touch_filename = alloca(len);
1787                         snprintf(touch_filename, len, "auto-%ld-%s", (long)time(NULL), touch_monitor);
1788                         snprintf(args, len, "%s.%s,b", touch_filename, (touch_format) ? touch_format : "wav");
1789                 } else {
1790                         caller_chan_id = ast_strdupa(S_COR(caller_chan->caller.id.number.valid,
1791                                 caller_chan->caller.id.number.str, caller_chan->name));
1792                         callee_chan_id = ast_strdupa(S_COR(callee_chan->caller.id.number.valid,
1793                                 callee_chan->caller.id.number.str, callee_chan->name));
1794                         len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
1795                         args = alloca(len);
1796                         touch_filename = alloca(len);
1797                         snprintf(touch_filename, len, "auto-%ld-%s-%s", (long)time(NULL), caller_chan_id, callee_chan_id);
1798                         snprintf(args, len, "%s.%s,b", touch_filename, S_OR(touch_format, "wav"));
1799                 }
1800
1801                 for( x = 0; x < strlen(args); x++) {
1802                         if (args[x] == '/')
1803                                 args[x] = '-';
1804                 }
1805
1806                 ast_verb(3, "User hit '%s' to record call. filename: %s\n", code, touch_filename);
1807
1808                 pbx_exec(callee_chan, mixmonitor_app, args);
1809                 pbx_builtin_setvar_helper(callee_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
1810                 pbx_builtin_setvar_helper(caller_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
1811                 return AST_FEATURE_RETURN_SUCCESS;
1812         
1813         }
1814
1815         ast_log(LOG_NOTICE,"Cannot record the call. One or both channels have gone away.\n");
1816         return -1;
1817
1818 }
1819
1820 static int builtin_disconnect(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
1821 {
1822         ast_verb(4, "User hit '%s' to disconnect call.\n", code);
1823         return AST_FEATURE_RETURN_HANGUP;
1824 }
1825
1826 static int finishup(struct ast_channel *chan)
1827 {
1828         ast_indicate(chan, AST_CONTROL_UNHOLD);
1829
1830         return ast_autoservice_stop(chan);
1831 }
1832
1833 /*!
1834  * \brief Find the context for the transfer
1835  * \param transferer
1836  * \param transferee
1837  * 
1838  * Grab the TRANSFER_CONTEXT, if fails try grabbing macrocontext.
1839  * \return a context string
1840 */
1841 static const char *real_ctx(struct ast_channel *transferer, struct ast_channel *transferee)
1842 {
1843         const char *s = pbx_builtin_getvar_helper(transferer, "TRANSFER_CONTEXT");
1844         if (ast_strlen_zero(s)) {
1845                 s = pbx_builtin_getvar_helper(transferee, "TRANSFER_CONTEXT");
1846         }
1847         if (ast_strlen_zero(s)) { /* Use the non-macro context to transfer the call XXX ? */
1848                 s = transferer->macrocontext;
1849         }
1850         if (ast_strlen_zero(s)) {
1851                 s = transferer->context;
1852         }
1853         return s;  
1854 }
1855
1856 /*!
1857  * \brief Blind transfer user to another extension
1858  * \param chan channel to be transfered
1859  * \param peer channel initiated blind transfer
1860  * \param config
1861  * \param code
1862  * \param data
1863  * \param sense  feature options
1864  * 
1865  * Place chan on hold, check if transferred to parkinglot extension,
1866  * otherwise check extension exists and transfer caller.
1867  * \retval AST_FEATURE_RETURN_SUCCESS.
1868  * \retval -1 on failure.
1869 */
1870 static int builtin_blindtransfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
1871 {
1872         struct ast_channel *transferer;
1873         struct ast_channel *transferee;
1874         const char *transferer_real_context;
1875         struct ast_parkinglot *found_lot = NULL;
1876         char xferto[256];
1877         int res, parkstatus = 0;
1878
1879         set_peers(&transferer, &transferee, peer, chan, sense);
1880         transferer_real_context = real_ctx(transferer, transferee);
1881         /* Start autoservice on chan while we talk to the originator */
1882         ast_autoservice_start(transferee);
1883         ast_autoservice_ignore(transferee, AST_FRAME_DTMF_END);
1884         ast_indicate(transferee, AST_CONTROL_HOLD);
1885
1886         memset(xferto, 0, sizeof(xferto));
1887
1888         /* Transfer */
1889         res = ast_stream_and_wait(transferer, "pbx-transfer", AST_DIGIT_ANY);
1890         if (res < 0) {
1891                 finishup(transferee);
1892                 return -1; /* error ? */
1893         }
1894         if (res > 0)    /* If they've typed a digit already, handle it */
1895                 xferto[0] = (char) res;
1896
1897         ast_stopstream(transferer);
1898         res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
1899         if (res < 0) {  /* hangup or error, (would be 0 for invalid and 1 for valid) */
1900                 finishup(transferee);
1901                 return -1;
1902         }
1903         if (res == 0) {
1904                 if (xferto[0]) {
1905                         ast_log(LOG_WARNING, "Extension '%s' does not exist in context '%s'\n",
1906                                 xferto, transferer_real_context);
1907                 } else {
1908                         /* Does anyone care about this case? */
1909                         ast_log(LOG_WARNING, "No digits dialed.\n");
1910                 }
1911                 ast_stream_and_wait(transferer, "pbx-invalid", "");
1912                 finishup(transferee);
1913                 return AST_FEATURE_RETURN_SUCCESS;
1914         }
1915
1916         found_lot = ao2_callback(parkinglots, 0, find_parkinglot_by_exten_cb, &xferto);
1917         if (found_lot) {
1918                 struct ast_park_call_args args = {
1919                         .parkinglot = found_lot,
1920                 };
1921                 res = finishup(transferee);
1922                 if (res) {
1923                 } else if (!(parkstatus = masq_park_call_announce(transferee, transferer, &args))) {    /* success */
1924                         /* We return non-zero, but tell the PBX not to hang the channel when
1925                            the thread dies -- We have to be careful now though.  We are responsible for 
1926                            hanging up the channel, else it will never be hung up! */
1927
1928                         return 0;
1929                 } else {
1930                         ast_log(LOG_WARNING, "Unable to park call %s, parkstatus = %d\n", transferee->name, parkstatus);
1931                 }
1932                 ast_autoservice_start(transferee);
1933         } else {
1934                 ast_cel_report_event(transferer, AST_CEL_BLINDTRANSFER, NULL, xferto, transferee);
1935                 pbx_builtin_setvar_helper(transferer, "BLINDTRANSFER", transferee->name);
1936                 pbx_builtin_setvar_helper(transferee, "BLINDTRANSFER", transferer->name);
1937                 res=finishup(transferee);
1938                 if (!transferer->cdr) { /* this code should never get called (in a perfect world) */
1939                         transferer->cdr=ast_cdr_alloc();
1940                         if (transferer->cdr) {
1941                                 ast_cdr_init(transferer->cdr, transferer); /* initialize our channel's cdr */
1942                                 ast_cdr_start(transferer->cdr);
1943                         }
1944                 }
1945                 if (transferer->cdr) {
1946                         struct ast_cdr *swap = transferer->cdr;
1947                         ast_debug(1, "transferer=%s; transferee=%s; lastapp=%s; lastdata=%s; chan=%s; dstchan=%s\n",
1948                                         transferer->name, transferee->name, transferer->cdr->lastapp, transferer->cdr->lastdata, 
1949                                         transferer->cdr->channel, transferer->cdr->dstchannel);
1950                         ast_debug(1, "TRANSFEREE; lastapp=%s; lastdata=%s, chan=%s; dstchan=%s\n",
1951                                         transferee->cdr->lastapp, transferee->cdr->lastdata, transferee->cdr->channel, transferee->cdr->dstchannel);
1952                         ast_debug(1, "transferer_real_context=%s; xferto=%s\n", transferer_real_context, xferto);
1953                         /* swap cdrs-- it will save us some time & work */
1954                         transferer->cdr = transferee->cdr;
1955                         transferee->cdr = swap;
1956                 }
1957                 if (!transferee->pbx) {
1958                         /* Doh!  Use our handy async_goto functions */
1959                         ast_verb(3, "Transferring %s to '%s' (context %s) priority 1\n"
1960                                                                 ,transferee->name, xferto, transferer_real_context);
1961                         if (ast_async_goto(transferee, transferer_real_context, xferto, 1))
1962                                 ast_log(LOG_WARNING, "Async goto failed :-(\n");
1963                 } else {
1964                         /* Set the channel's new extension, since it exists, using transferer context */
1965                         ast_set_flag(transferee, AST_FLAG_BRIDGE_HANGUP_DONT); /* don't let the after-bridge code run the h-exten */
1966                         ast_debug(1, "ABOUT TO AST_ASYNC_GOTO, have a pbx... set HANGUP_DONT on chan=%s\n", transferee->name);
1967                         if (ast_channel_connected_line_macro(transferee, transferer, &transferer->connected, 1, 0)) {
1968                                 ast_channel_update_connected_line(transferer, &transferer->connected, NULL);
1969                         }
1970                         set_c_e_p(transferee, transferer_real_context, xferto, 0);
1971                 }
1972                 check_goto_on_transfer(transferer);
1973                 return res;
1974         }
1975         if (parkstatus != AST_FEATURE_RETURN_PARKFAILED
1976                 && ast_stream_and_wait(transferer, xferfailsound, "")) {
1977                 finishup(transferee);
1978                 return -1;
1979         }
1980         ast_stopstream(transferer);
1981         res = finishup(transferee);
1982         if (res) {
1983                 ast_verb(2, "Hungup during autoservice stop on '%s'\n", transferee->name);
1984                 return res;
1985         }
1986         return AST_FEATURE_RETURN_SUCCESS;
1987 }
1988
1989 /*!
1990  * \brief make channels compatible
1991  * \param c
1992  * \param newchan
1993  * \retval 0 on success.
1994  * \retval -1 on failure.
1995 */
1996 static int check_compat(struct ast_channel *c, struct ast_channel *newchan)
1997 {
1998         if (ast_channel_make_compatible(c, newchan) < 0) {
1999                 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n",
2000                         c->name, newchan->name);
2001                 ast_hangup(newchan);
2002                 return -1;
2003         }
2004         return 0;
2005 }
2006
2007 /*!
2008  * \internal
2009  * \brief Builtin attended transfer failed cleanup.
2010  * \since 1.10
2011  *
2012  * \param transferee Party A in the transfer.
2013  * \param transferer Party B in the transfer.
2014  * \param connected_line Saved connected line info about party A.
2015  *
2016  * \note The connected_line data is freed.
2017  *
2018  * \return Nothing
2019  */
2020 static void atxfer_fail_cleanup(struct ast_channel *transferee, struct ast_channel *transferer, struct ast_party_connected_line *connected_line)
2021 {
2022         finishup(transferee);
2023
2024         /*
2025          * Restore party B connected line info about party A.
2026          *
2027          * Party B was the caller to party C and is the last known mode
2028          * for party B.
2029          */
2030         if (ast_channel_connected_line_macro(transferee, transferer, connected_line, 1, 0)) {
2031                 ast_channel_update_connected_line(transferer, connected_line, NULL);
2032         }
2033         ast_party_connected_line_free(connected_line);
2034 }
2035
2036 /*!
2037  * \brief Attended transfer
2038  * \param chan transfered user
2039  * \param peer person transfering call
2040  * \param config
2041  * \param code
2042  * \param sense feature options
2043  *
2044  * \param data
2045  * Get extension to transfer to, if you cannot generate channel (or find extension)
2046  * return to host channel. After called channel answered wait for hangup of transferer,
2047  * bridge call between transfer peer (taking them off hold) to attended transfer channel.
2048  *
2049  * \return -1 on failure
2050 */
2051 static int builtin_atxfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2052 {
2053         struct ast_channel *transferer;/* Party B */
2054         struct ast_channel *transferee;/* Party A */
2055         const char *transferer_real_context;
2056         char xferto[256] = "";
2057         int res;
2058         int outstate=0;
2059         struct ast_channel *newchan;
2060         struct ast_channel *xferchan;
2061         struct ast_bridge_thread_obj *tobj;
2062         struct ast_bridge_config bconfig;
2063         int l;
2064         struct ast_party_connected_line connected_line;
2065         struct ast_datastore *features_datastore;
2066         struct ast_dial_features *dialfeatures = NULL;
2067         struct ast_parkinglot *parkinglot;
2068         char *transferer_tech;
2069         char *transferer_name;
2070         char *transferer_name_orig;
2071         char *dash;
2072
2073         ast_debug(1, "Executing Attended Transfer %s, %s (sense=%d) \n", chan->name, peer->name, sense);
2074         set_peers(&transferer, &transferee, peer, chan, sense);
2075         transferer_real_context = real_ctx(transferer, transferee);
2076
2077         /* Start autoservice on transferee while we talk to the transferer */
2078         ast_autoservice_start(transferee);
2079         ast_indicate(transferee, AST_CONTROL_HOLD);
2080
2081         /* Transfer */
2082         res = ast_stream_and_wait(transferer, "pbx-transfer", AST_DIGIT_ANY);
2083         if (res < 0) {
2084                 finishup(transferee);
2085                 return -1;
2086         }
2087         if (res > 0) /* If they've typed a digit already, handle it */
2088                 xferto[0] = (char) res;
2089
2090         /* this is specific of atxfer */
2091         res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
2092         if (res < 0) {  /* hangup or error, (would be 0 for invalid and 1 for valid) */
2093                 finishup(transferee);
2094                 return -1;
2095         }
2096         l = strlen(xferto);
2097         if (res == 0) {
2098                 if (l) {
2099                         ast_log(LOG_WARNING, "Extension '%s' does not exist in context '%s'\n",
2100                                 xferto, transferer_real_context);
2101                 } else {
2102                         /* Does anyone care about this case? */
2103                         ast_log(LOG_WARNING, "No digits dialed for atxfer.\n");
2104                 }
2105                 ast_stream_and_wait(transferer, "pbx-invalid", "");
2106                 finishup(transferee);
2107                 return AST_FEATURE_RETURN_SUCCESS;
2108         }
2109
2110         /* If we are attended transfering to parking, just use parkcall_helper instead of trying to track all of
2111          * the different variables for handling this properly with a builtin_atxfer */
2112         parkinglot = ao2_callback(parkinglots, 0, find_parkinglot_by_exten_cb, &xferto);
2113         if (parkinglot) {
2114                 struct ast_park_call_args args = {
2115                         .parkinglot = parkinglot,
2116                 };
2117                 finishup(transferee);
2118                 return parkcall_helper(chan, peer, config, code, sense, &args);
2119         }
2120
2121         /* Append context to dialed transfer number. */
2122         snprintf(xferto + l, sizeof(xferto) - l, "@%s/n", transferer_real_context);
2123
2124         /* If we are performing an attended transfer and we have two channels involved then
2125            copy sound file information to play upon attended transfer completion */
2126         if (transferee) {
2127                 const char *chan1_attended_sound = pbx_builtin_getvar_helper(transferer, "ATTENDED_TRANSFER_COMPLETE_SOUND");
2128                 const char *chan2_attended_sound = pbx_builtin_getvar_helper(transferee, "ATTENDED_TRANSFER_COMPLETE_SOUND");
2129
2130                 if (!ast_strlen_zero(chan1_attended_sound)) {
2131                         pbx_builtin_setvar_helper(transferer, "BRIDGE_PLAY_SOUND", chan1_attended_sound);
2132                 }
2133                 if (!ast_strlen_zero(chan2_attended_sound)) {
2134                         pbx_builtin_setvar_helper(transferee, "BRIDGE_PLAY_SOUND", chan2_attended_sound);
2135                 }
2136         }
2137
2138         /* Extract redial transferer information from the channel name. */
2139         transferer_name_orig = ast_strdupa(transferer->name);
2140         transferer_name = ast_strdupa(transferer_name_orig);
2141         transferer_tech = strsep(&transferer_name, "/");
2142         dash = strrchr(transferer_name, '-');
2143         if (dash) {
2144                 /* Trim off channel name sequence/serial number. */
2145                 *dash = '\0';
2146         }
2147
2148         /* Stop autoservice so we can monitor all parties involved in the transfer. */
2149         if (ast_autoservice_stop(transferee) < 0) {
2150                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2151                 return -1;
2152         }
2153
2154         /* Save connected line info for party B about party A in case transfer fails. */
2155         ast_party_connected_line_init(&connected_line);
2156         ast_channel_lock(transferer);
2157         ast_party_connected_line_copy(&connected_line, &transferer->connected);
2158         ast_channel_unlock(transferer);
2159         connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
2160
2161         /* Dial party C */
2162         newchan = feature_request_and_dial(transferer, transferer_name_orig, transferer,
2163                 transferee, "Local", transferer->nativeformats, xferto,
2164                 atxfernoanswertimeout, &outstate, transferer->language);
2165         ast_debug(2, "Dial party C result: newchan:%d, outstate:%d\n", !!newchan, outstate);
2166
2167         if (!ast_check_hangup(transferer)) {
2168                 int hangup_dont = 0;
2169
2170                 /* Transferer (party B) is up */
2171                 ast_debug(1, "Actually doing an attended transfer.\n");
2172
2173                 /* Start autoservice on transferee while the transferer deals with party C. */
2174                 ast_autoservice_start(transferee);
2175
2176                 ast_indicate(transferer, -1);
2177                 if (!newchan) {
2178                         /* any reason besides user requested cancel and busy triggers the failed sound */
2179                         switch (outstate) {
2180                         case AST_CONTROL_UNHOLD:/* Caller requested cancel or party C answer timeout. */
2181                         case AST_CONTROL_BUSY:
2182                         case AST_CONTROL_CONGESTION:
2183                                 if (ast_stream_and_wait(transferer, xfersound, "")) {
2184                                         ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
2185                                 }
2186                                 break;
2187                         default:
2188                                 if (ast_stream_and_wait(transferer, xferfailsound, "")) {
2189                                         ast_log(LOG_WARNING, "Failed to play transfer failed sound!\n");
2190                                 }
2191                                 break;
2192                         }
2193                         atxfer_fail_cleanup(transferee, transferer, &connected_line);
2194                         return AST_FEATURE_RETURN_SUCCESS;
2195                 }
2196
2197                 if (check_compat(transferer, newchan)) {
2198                         if (ast_stream_and_wait(transferer, xferfailsound, "")) {
2199                                 ast_log(LOG_WARNING, "Failed to play transfer failed sound!\n");
2200                         }
2201                         atxfer_fail_cleanup(transferee, transferer, &connected_line);
2202                         return AST_FEATURE_RETURN_SUCCESS;
2203                 }
2204                 memset(&bconfig,0,sizeof(struct ast_bridge_config));
2205                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_DISCONNECT);
2206                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_DISCONNECT);
2207
2208                 /* ast_bridge_call clears AST_FLAG_BRIDGE_HANGUP_DONT, but we don't
2209                    want that to happen here because we're also in another bridge already
2210                  */
2211                 if (ast_test_flag(chan, AST_FLAG_BRIDGE_HANGUP_DONT)) {
2212                         hangup_dont = 1;
2213                 }
2214                 /* Let party B and party C talk as long as they want. */
2215                 ast_bridge_call(transferer, newchan, &bconfig);
2216                 if (hangup_dont) {
2217                         ast_set_flag(chan, AST_FLAG_BRIDGE_HANGUP_DONT);
2218                 }
2219
2220                 if (ast_check_hangup(newchan) || !ast_check_hangup(transferer)) {
2221                         ast_hangup(newchan);
2222                         if (ast_stream_and_wait(transferer, xfersound, "")) {
2223                                 ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
2224                         }
2225                         atxfer_fail_cleanup(transferee, transferer, &connected_line);
2226                         return AST_FEATURE_RETURN_SUCCESS;
2227                 }
2228
2229                 /* Transferer (party B) is confirmed hung up at this point. */
2230                 if (check_compat(transferee, newchan)) {
2231                         finishup(transferee);
2232                         ast_party_connected_line_free(&connected_line);
2233                         return -1;
2234                 }
2235
2236                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2237                 if ((ast_autoservice_stop(transferee) < 0)
2238                         || (ast_waitfordigit(transferee, 100) < 0)
2239                         || (ast_waitfordigit(newchan, 100) < 0)
2240                         || ast_check_hangup(transferee)
2241                         || ast_check_hangup(newchan)) {
2242                         ast_hangup(newchan);
2243                         ast_party_connected_line_free(&connected_line);
2244                         return -1;
2245                 }
2246         } else if (!ast_check_hangup(transferee)) {
2247                 /* Transferer (party B) has hung up at this point.  Doing blonde transfer. */
2248                 ast_debug(1, "Actually doing a blonde transfer.\n");
2249
2250                 if (!newchan && !atxferdropcall) {
2251                         /* Party C is not available, try to call party B back. */
2252                         unsigned int tries = 0;
2253
2254                         if (ast_strlen_zero(transferer_name) || ast_strlen_zero(transferer_tech)) {
2255                                 ast_log(LOG_WARNING,
2256                                         "Transferer channel name: '%s' cannot be used for callback.\n",
2257                                         transferer_name_orig);
2258                                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2259                                 ast_party_connected_line_free(&connected_line);
2260                                 return -1;
2261                         }
2262
2263                         tries = 0;
2264                         for (;;) {
2265                                 /* Try to get party B back. */
2266                                 ast_debug(1, "We're trying to callback %s/%s\n",
2267                                         transferer_tech, transferer_name);
2268                                 newchan = feature_request_and_dial(transferer, transferer_name_orig,
2269                                         transferee, transferee, transferer_tech,
2270                                         transferee->nativeformats, transferer_name,
2271                                         atxfernoanswertimeout, &outstate, transferer->language);
2272                                 ast_debug(2, "Dial party B result: newchan:%d, outstate:%d\n",
2273                                         !!newchan, outstate);
2274                                 if (newchan || ast_check_hangup(transferee)) {
2275                                         break;
2276                                 }
2277                                 ++tries;
2278                                 if (atxfercallbackretries <= tries) {
2279                                         /* No more callback tries remaining. */
2280                                         break;
2281                                 }
2282
2283                                 if (atxferloopdelay) {
2284                                         /* Transfer failed, sleeping */
2285                                         ast_debug(1, "Sleeping for %d ms before retrying atxfer.\n",
2286                                                 atxferloopdelay);
2287                                         ast_safe_sleep(transferee, atxferloopdelay);
2288                                         if (ast_check_hangup(transferee)) {
2289                                                 ast_party_connected_line_free(&connected_line);
2290                                                 return -1;
2291                                         }
2292                                 }
2293
2294                                 /* Retry dialing party C. */
2295                                 ast_debug(1, "We're retrying to call %s/%s\n", "Local", xferto);
2296                                 newchan = feature_request_and_dial(transferer, transferer_name_orig,
2297                                         transferer, transferee, "Local",
2298                                         transferee->nativeformats, xferto,
2299                                         atxfernoanswertimeout, &outstate, transferer->language);
2300                                 ast_debug(2, "Redial party C result: newchan:%d, outstate:%d\n",
2301                                         !!newchan, outstate);
2302                                 if (newchan || ast_check_hangup(transferee)) {
2303                                         break;
2304                                 }
2305                         }
2306                 }
2307                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2308                 if (!newchan) {
2309                         /* No party C or could not callback party B. */
2310                         ast_party_connected_line_free(&connected_line);
2311                         return -1;
2312                 }
2313
2314                 /* newchan is up, we should prepare transferee and bridge them */
2315                 if (ast_check_hangup(newchan)) {
2316                         ast_hangup(newchan);
2317                         ast_party_connected_line_free(&connected_line);
2318                         return -1;
2319                 }
2320                 if (check_compat(transferee, newchan)) {
2321                         ast_party_connected_line_free(&connected_line);
2322                         return -1;
2323                 }
2324         } else {
2325                 /*
2326                  * Both the transferer and transferee have hungup.  If newchan
2327                  * is up, hang it up as it has no one to talk to.
2328                  */
2329                 ast_debug(1, "Everyone is hungup.\n");
2330                 if (newchan) {
2331                         ast_hangup(newchan);
2332                 }
2333                 ast_party_connected_line_free(&connected_line);
2334                 return -1;
2335         }
2336
2337         /* Initiate the channel transfer of party A to party C (or recalled party B). */
2338         ast_cel_report_event(transferee, AST_CEL_ATTENDEDTRANSFER, NULL, NULL, newchan);
2339
2340         xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", transferee->linkedid, 0, "Transfered/%s", transferee->name);
2341         if (!xferchan) {
2342                 ast_hangup(newchan);
2343                 ast_party_connected_line_free(&connected_line);
2344                 return -1;
2345         }
2346
2347         /* Give party A a momentary ringback tone during transfer. */
2348         xferchan->visible_indication = AST_CONTROL_RINGING;
2349
2350         /* Make formats okay */
2351         xferchan->readformat = transferee->readformat;
2352         xferchan->writeformat = transferee->writeformat;
2353
2354         ast_channel_masquerade(xferchan, transferee);
2355         ast_explicit_goto(xferchan, transferee->context, transferee->exten, transferee->priority);
2356         xferchan->_state = AST_STATE_UP;
2357         ast_clear_flag(xferchan, AST_FLAGS_ALL);
2358
2359         /* Do the masquerade manually to make sure that is is completed. */
2360         ast_do_masquerade(xferchan);
2361
2362         newchan->_state = AST_STATE_UP;
2363         ast_clear_flag(newchan, AST_FLAGS_ALL);
2364         tobj = ast_calloc(1, sizeof(*tobj));
2365         if (!tobj) {
2366                 ast_hangup(xferchan);
2367                 ast_hangup(newchan);
2368                 ast_party_connected_line_free(&connected_line);
2369                 return -1;
2370         }
2371
2372         ast_channel_lock(newchan);
2373         if ((features_datastore = ast_channel_datastore_find(newchan, &dial_features_info, NULL))) {
2374                 dialfeatures = features_datastore->data;
2375         }
2376         ast_channel_unlock(newchan);
2377
2378         if (dialfeatures) {
2379                 /* newchan should always be the callee and shows up as callee in dialfeatures, but for some reason
2380                    I don't currently understand, the abilities of newchan seem to be stored on the caller side */
2381                 ast_copy_flags(&(config->features_callee), &(dialfeatures->features_caller), AST_FLAGS_ALL);
2382                 dialfeatures = NULL;
2383         }
2384
2385         ast_channel_lock(xferchan);
2386         if ((features_datastore = ast_channel_datastore_find(xferchan, &dial_features_info, NULL))) {
2387                 dialfeatures = features_datastore->data;
2388         }
2389         ast_channel_unlock(xferchan);
2390
2391         if (dialfeatures) {
2392                 ast_copy_flags(&(config->features_caller), &(dialfeatures->features_caller), AST_FLAGS_ALL);
2393         }
2394
2395         tobj->chan = newchan;
2396         tobj->peer = xferchan;
2397         tobj->bconfig = *config;
2398
2399         if (tobj->bconfig.end_bridge_callback_data_fixup) {
2400                 tobj->bconfig.end_bridge_callback_data_fixup(&tobj->bconfig, tobj->peer, tobj->chan);
2401         }
2402
2403         /*
2404          * xferchan is transferee, and newchan is the transfer target
2405          * So...in a transfer, who is the caller and who is the callee?
2406          *
2407          * When the call is originally made, it is clear who is caller and callee.
2408          * When a transfer occurs, it is my humble opinion that the transferee becomes
2409          * the caller, and the transfer target is the callee.
2410          *
2411          * The problem is that these macros were set with the intention of the original
2412          * caller and callee taking those roles.  A transfer can totally mess things up,
2413          * to be technical.  What sucks even more is that you can't effectively change
2414          * the macros in the dialplan during the call from the transferer to the transfer
2415          * target because the transferee is stuck with whatever role he originally had.
2416          *
2417          * I think the answer here is just to make sure that it is well documented that
2418          * during a transfer, the transferee is the "caller" and the transfer target
2419          * is the "callee."
2420          *
2421          * This means that if party B calls party A, and party B transfers party A to
2422          * party C, then A has switched roles for the call.  Now party A will have the
2423          * caller macro called on his channel instead of the callee macro.
2424          *
2425          * Luckily, the method by which the party B to party C bridge is
2426          * launched above ensures that the transferee is the "chan" on
2427          * the bridge and the transfer target is the "peer," so my idea
2428          * for the roles post-transfer does not require extensive code
2429          * changes.
2430          */
2431
2432         /* Transfer party C connected line to party A */
2433         ast_channel_lock(transferer);
2434         /*
2435          * Due to a limitation regarding when callerID is set on a Local channel,
2436          * we use the transferer's connected line information here.
2437          */
2438         ast_party_connected_line_copy(&connected_line, &transferer->connected);
2439         ast_channel_unlock(transferer);
2440         connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
2441         if (ast_channel_connected_line_macro(newchan, xferchan, &connected_line, 1, 0)) {
2442                 ast_channel_update_connected_line(xferchan, &connected_line, NULL);
2443         }
2444
2445         /* Transfer party A connected line to party C */
2446         ast_channel_lock(xferchan);
2447         ast_connected_line_copy_from_caller(&connected_line, &xferchan->caller);
2448         ast_channel_unlock(xferchan);
2449         connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
2450         if (ast_channel_connected_line_macro(xferchan, newchan, &connected_line, 0, 0)) {
2451                 ast_channel_update_connected_line(newchan, &connected_line, NULL);
2452         }
2453
2454         if (ast_stream_and_wait(newchan, xfersound, ""))
2455                 ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
2456         bridge_call_thread_launch(tobj);
2457
2458         ast_party_connected_line_free(&connected_line);
2459         return -1;/* The transferee is masqueraded and the original bridged channels can be hungup. */
2460 }
2461
2462 /* add atxfer and automon as undefined so you can only use em if you configure them */
2463 #define FEATURES_COUNT ARRAY_LEN(builtin_features)
2464
2465 AST_RWLOCK_DEFINE_STATIC(features_lock);
2466
2467 static struct ast_call_feature builtin_features[] = {
2468         { AST_FEATURE_REDIRECT, "Blind Transfer", "blindxfer", "#", "#", builtin_blindtransfer, AST_FEATURE_FLAG_NEEDSDTMF, "" },
2469         { AST_FEATURE_REDIRECT, "Attended Transfer", "atxfer", "", "", builtin_atxfer, AST_FEATURE_FLAG_NEEDSDTMF, "" },
2470         { AST_FEATURE_AUTOMON, "One Touch Monitor", "automon", "", "", builtin_automonitor, AST_FEATURE_FLAG_NEEDSDTMF, "" },
2471         { AST_FEATURE_DISCONNECT, "Disconnect Call", "disconnect", "*", "*", builtin_disconnect, AST_FEATURE_FLAG_NEEDSDTMF, "" },
2472         { AST_FEATURE_PARKCALL, "Park Call", "parkcall", "", "", builtin_parkcall, AST_FEATURE_FLAG_NEEDSDTMF, "" },
2473         { AST_FEATURE_AUTOMIXMON, "One Touch MixMonitor", "automixmon", "", "", builtin_automixmonitor, AST_FEATURE_FLAG_NEEDSDTMF, "" },
2474 };
2475
2476
2477 static AST_RWLIST_HEAD_STATIC(feature_list, ast_call_feature);
2478
2479 /*! \brief register new feature into feature_list*/
2480 void ast_register_feature(struct ast_call_feature *feature)
2481 {
2482         if (!feature) {
2483                 ast_log(LOG_NOTICE,"You didn't pass a feature!\n");
2484                 return;
2485         }
2486   
2487         AST_RWLIST_WRLOCK(&feature_list);
2488         AST_RWLIST_INSERT_HEAD(&feature_list,feature,feature_entry);
2489         AST_RWLIST_UNLOCK(&feature_list);
2490
2491         ast_verb(2, "Registered Feature '%s'\n",feature->sname);
2492 }
2493
2494 /*! 
2495  * \brief Add new feature group
2496  * \param fgname feature group name.
2497  *
2498  * Add new feature group to the feature group list insert at head of list.
2499  * \note This function MUST be called while feature_groups is locked.
2500 */
2501 static struct feature_group *register_group(const char *fgname)
2502 {
2503         struct feature_group *fg;
2504
2505         if (!fgname) {
2506                 ast_log(LOG_NOTICE, "You didn't pass a new group name!\n");
2507                 return NULL;
2508         }
2509
2510         if (!(fg = ast_calloc_with_stringfields(1, struct feature_group, 128))) {
2511                 return NULL;
2512         }
2513
2514         ast_string_field_set(fg, gname, fgname);
2515
2516         AST_LIST_INSERT_HEAD(&feature_groups, fg, entry);
2517
2518         ast_verb(2, "Registered group '%s'\n", fg->gname);
2519
2520         return fg;
2521 }
2522
2523 /*! 
2524  * \brief Add feature to group
2525  * \param fg feature group
2526  * \param exten
2527  * \param feature feature to add.
2528  *
2529  * Check fg and feature specified, add feature to list
2530  * \note This function MUST be called while feature_groups is locked. 
2531 */
2532 static void register_group_feature(struct feature_group *fg, const char *exten, struct ast_call_feature *feature)
2533 {
2534         struct feature_group_exten *fge;
2535
2536         if (!fg) {
2537                 ast_log(LOG_NOTICE, "You didn't pass a group!\n");
2538                 return;
2539         }
2540
2541         if (!feature) {
2542                 ast_log(LOG_NOTICE, "You didn't pass a feature!\n");
2543                 return;
2544         }
2545
2546         if (!(fge = ast_calloc_with_stringfields(1, struct feature_group_exten, 128))) {
2547                 return;
2548         }
2549
2550         ast_string_field_set(fge, exten, S_OR(exten, feature->exten));
2551
2552         fge->feature = feature;
2553
2554         AST_LIST_INSERT_HEAD(&fg->features, fge, entry);
2555
2556         ast_verb(2, "Registered feature '%s' for group '%s' at exten '%s'\n",
2557                                         feature->sname, fg->gname, fge->exten);
2558 }
2559
2560 void ast_unregister_feature(struct ast_call_feature *feature)
2561 {
2562         if (!feature) {
2563                 return;
2564         }
2565
2566         AST_RWLIST_WRLOCK(&feature_list);
2567         AST_RWLIST_REMOVE(&feature_list, feature, feature_entry);
2568         AST_RWLIST_UNLOCK(&feature_list);
2569
2570         ast_free(feature);
2571 }
2572
2573 /*! \brief Remove all features in the list */
2574 static void ast_unregister_features(void)
2575 {
2576         struct ast_call_feature *feature;
2577
2578         AST_RWLIST_WRLOCK(&feature_list);
2579         while ((feature = AST_RWLIST_REMOVE_HEAD(&feature_list, feature_entry))) {
2580                 ast_free(feature);
2581         }
2582         AST_RWLIST_UNLOCK(&feature_list);
2583 }
2584
2585 /*! \brief find a call feature by name */
2586 static struct ast_call_feature *find_dynamic_feature(const char *name)
2587 {
2588         struct ast_call_feature *tmp;
2589
2590         AST_RWLIST_TRAVERSE(&feature_list, tmp, feature_entry) {
2591                 if (!strcasecmp(tmp->sname, name)) {
2592                         break;
2593                 }
2594         }
2595
2596         return tmp;
2597 }
2598
2599 /*! \brief Remove all feature groups in the list */
2600 static void ast_unregister_groups(void)
2601 {
2602         struct feature_group *fg;
2603         struct feature_group_exten *fge;
2604
2605         AST_RWLIST_WRLOCK(&feature_groups);
2606         while ((fg = AST_LIST_REMOVE_HEAD(&feature_groups, entry))) {
2607                 while ((fge = AST_LIST_REMOVE_HEAD(&fg->features, entry))) {
2608                         ast_string_field_free_memory(fge);
2609                         ast_free(fge);
2610                 }
2611
2612                 ast_string_field_free_memory(fg);
2613                 ast_free(fg);
2614         }
2615         AST_RWLIST_UNLOCK(&feature_groups);
2616 }
2617
2618 /*! 
2619  * \brief Find a group by name 
2620  * \param name feature name
2621  * \retval feature group on success.
2622  * \retval NULL on failure.
2623 */
2624 static struct feature_group *find_group(const char *name)
2625 {
2626         struct feature_group *fg = NULL;
2627
2628         AST_LIST_TRAVERSE(&feature_groups, fg, entry) {
2629                 if (!strcasecmp(fg->gname, name))
2630                         break;
2631         }
2632
2633         return fg;
2634 }
2635
2636 void ast_rdlock_call_features(void)
2637 {
2638         ast_rwlock_rdlock(&features_lock);
2639 }
2640
2641 void ast_unlock_call_features(void)
2642 {
2643         ast_rwlock_unlock(&features_lock);
2644 }
2645
2646 struct ast_call_feature *ast_find_call_feature(const char *name)
2647 {
2648         int x;
2649         for (x = 0; x < FEATURES_COUNT; x++) {
2650                 if (!strcasecmp(name, builtin_features[x].sname))
2651                         return &builtin_features[x];
2652         }
2653         return NULL;
2654 }
2655
2656 /*!
2657  * \brief exec an app by feature 
2658  * \param chan,peer,config,code,sense,data
2659  *
2660  * Find a feature, determine which channel activated
2661  * \retval AST_FEATURE_RETURN_NO_HANGUP_PEER
2662  * \retval -1 error.
2663  * \retval -2 when an application cannot be found.
2664 */
2665 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)
2666 {
2667         struct ast_app *app;
2668         struct ast_call_feature *feature = data;
2669         struct ast_channel *work, *idle;
2670         int res;
2671
2672         if (!feature) { /* shouldn't ever happen! */
2673                 ast_log(LOG_NOTICE, "Found feature before, but at execing we've lost it??\n");
2674                 return -1; 
2675         }
2676
2677         if (sense == FEATURE_SENSE_CHAN) {
2678                 if (!ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLER))
2679                         return AST_FEATURE_RETURN_KEEPTRYING;
2680                 if (ast_test_flag(feature, AST_FEATURE_FLAG_ONSELF)) {
2681                         work = chan;
2682                         idle = peer;
2683                 } else {
2684                         work = peer;
2685                         idle = chan;
2686                 }
2687         } else {
2688                 if (!ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLEE))
2689                         return AST_FEATURE_RETURN_KEEPTRYING;
2690                 if (ast_test_flag(feature, AST_FEATURE_FLAG_ONSELF)) {
2691                         work = peer;
2692                         idle = chan;
2693                 } else {
2694                         work = chan;
2695                         idle = peer;
2696                 }
2697         }
2698
2699         if (!(app = pbx_findapp(feature->app))) {
2700                 ast_log(LOG_WARNING, "Could not find application (%s)\n", feature->app);
2701                 return -2;
2702         }
2703
2704         ast_autoservice_start(idle);
2705         ast_autoservice_ignore(idle, AST_FRAME_DTMF_END);
2706         
2707         if(work && idle) {
2708                 pbx_builtin_setvar_helper(work, "DYNAMIC_PEERNAME", idle->name);
2709                 pbx_builtin_setvar_helper(idle, "DYNAMIC_PEERNAME", work->name);
2710                 pbx_builtin_setvar_helper(work, "DYNAMIC_FEATURENAME", feature->sname);
2711                 pbx_builtin_setvar_helper(idle, "DYNAMIC_FEATURENAME", feature->sname);
2712         }
2713
2714         if (!ast_strlen_zero(feature->moh_class))
2715                 ast_moh_start(idle, feature->moh_class, NULL);
2716
2717         res = pbx_exec(work, app, feature->app_args);
2718
2719         if (!ast_strlen_zero(feature->moh_class))
2720                 ast_moh_stop(idle);
2721
2722         ast_autoservice_stop(idle);
2723
2724         if (res) {
2725                 return AST_FEATURE_RETURN_SUCCESSBREAK;
2726         }
2727         return AST_FEATURE_RETURN_SUCCESS;      /*! \todo XXX should probably return res */
2728 }
2729
2730 static void unmap_features(void)
2731 {
2732         int x;
2733
2734         ast_rwlock_wrlock(&features_lock);
2735         for (x = 0; x < FEATURES_COUNT; x++)
2736                 strcpy(builtin_features[x].exten, builtin_features[x].default_exten);
2737         ast_rwlock_unlock(&features_lock);
2738 }
2739
2740 static int remap_feature(const char *name, const char *value)
2741 {
2742         int x, res = -1;
2743
2744         ast_rwlock_wrlock(&features_lock);
2745         for (x = 0; x < FEATURES_COUNT; x++) {
2746                 if (strcasecmp(builtin_features[x].sname, name))
2747                         continue;
2748
2749                 ast_copy_string(builtin_features[x].exten, value, sizeof(builtin_features[x].exten));
2750                 res = 0;
2751                 break;
2752         }
2753         ast_rwlock_unlock(&features_lock);
2754
2755         return res;
2756 }
2757
2758 /*!
2759  * \brief Helper function for feature_interpret and ast_feature_detect
2760  * \param chan,peer,config,code,sense,dynamic_features_buf,features,operation,feature
2761  *
2762  * Lock features list, browse for code, unlock list
2763  * If a feature is found and the operation variable is set, that feature's
2764  * operation is executed.  The first feature found is copied to the feature parameter.
2765  * \retval res on success.
2766  * \retval -1 on failure.
2767 */
2768 static int feature_interpret_helper(struct ast_channel *chan, struct ast_channel *peer,
2769         struct ast_bridge_config *config, const char *code, int sense, char *dynamic_features_buf,
2770         struct ast_flags *features, feature_interpret_op operation, struct ast_call_feature *feature)
2771 {
2772         int x;
2773         struct feature_group *fg = NULL;
2774         struct feature_group_exten *fge;
2775         struct ast_call_feature *tmpfeature;
2776         char *tmp, *tok;
2777         int res = AST_FEATURE_RETURN_PASSDIGITS;
2778         int feature_detected = 0;
2779
2780         if (!(peer && chan && config) && operation == FEATURE_INTERPRET_DO) {
2781                 return -1; /* can not run feature operation */
2782         }
2783
2784         ast_rwlock_rdlock(&features_lock);
2785         for (x = 0; x < FEATURES_COUNT; x++) {
2786                 if ((ast_test_flag(features, builtin_features[x].feature_mask)) &&
2787                     !ast_strlen_zero(builtin_features[x].exten)) {
2788                         /* Feature is up for consideration */
2789                         if (!strcmp(builtin_features[x].exten, code)) {
2790                                 ast_debug(3, "Feature detected: fname=%s sname=%s exten=%s\n", builtin_features[x].fname, builtin_features[x].sname, builtin_features[x].exten);
2791                                 if (operation == FEATURE_INTERPRET_CHECK) {
2792                                         res = AST_FEATURE_RETURN_SUCCESS; /* We found something */
2793                                 } else if (operation == FEATURE_INTERPRET_DO) {
2794                                         res = builtin_features[x].operation(chan, peer, config, code, sense, NULL);
2795                                 }
2796                                 if (feature) {
2797                                         memcpy(feature, &builtin_features[x], sizeof(feature));
2798                                 }
2799                                 feature_detected = 1;
2800                                 break;
2801                         } else if (!strncmp(builtin_features[x].exten, code, strlen(code))) {
2802                                 if (res == AST_FEATURE_RETURN_PASSDIGITS) {
2803                                         res = AST_FEATURE_RETURN_STOREDIGITS;
2804                                 }
2805                         }
2806                 }
2807         }
2808         ast_rwlock_unlock(&features_lock);
2809
2810         if (ast_strlen_zero(dynamic_features_buf) || feature_detected) {
2811                 return res;
2812         }
2813
2814         tmp = dynamic_features_buf;
2815
2816         while ((tok = strsep(&tmp, "#"))) {
2817                 AST_RWLIST_RDLOCK(&feature_groups);
2818
2819                 fg = find_group(tok);
2820
2821                 if (fg) {
2822                         AST_LIST_TRAVERSE(&fg->features, fge, entry) {
2823                                 if (!strcmp(fge->exten, code)) {
2824                                         if (operation) {
2825                                                 res = fge->feature->operation(chan, peer, config, code, sense, fge->feature);
2826                                         }
2827                                         memcpy(feature, fge->feature, sizeof(feature));
2828                                         if (res != AST_FEATURE_RETURN_KEEPTRYING) {
2829                                                 AST_RWLIST_UNLOCK(&feature_groups);
2830                                                 break;
2831                                         }
2832                                         res = AST_FEATURE_RETURN_PASSDIGITS;
2833                                 } else if (!strncmp(fge->exten, code, strlen(code))) {
2834                                         res = AST_FEATURE_RETURN_STOREDIGITS;
2835                                 }
2836                         }
2837                         if (fge) {
2838                                 break;
2839                         }
2840                 }
2841
2842                 AST_RWLIST_UNLOCK(&feature_groups);
2843
2844                 AST_RWLIST_RDLOCK(&feature_list);
2845
2846                 if (!(tmpfeature = find_dynamic_feature(tok))) {
2847                         AST_RWLIST_UNLOCK(&feature_list);
2848                         continue;
2849                 }
2850
2851                 /* Feature is up for consideration */
2852                 if (!strcmp(tmpfeature->exten, code)) {
2853                         ast_verb(3, " Feature Found: %s exten: %s\n",tmpfeature->sname, tok);
2854                         if (operation == FEATURE_INTERPRET_CHECK) {
2855                                 res = AST_FEATURE_RETURN_SUCCESS; /* We found something */
2856                         } else if (operation == FEATURE_INTERPRET_DO) {
2857                                 res = tmpfeature->operation(chan, peer, config, code, sense, tmpfeature);
2858                         }
2859                         if (feature) {
2860                                 memcpy(feature, tmpfeature, sizeof(feature));
2861                         }
2862                         if (res != AST_FEATURE_RETURN_KEEPTRYING) {
2863                                 AST_RWLIST_UNLOCK(&feature_list);
2864                                 break;
2865                         }
2866                         res = AST_FEATURE_RETURN_PASSDIGITS;
2867                 } else if (!strncmp(tmpfeature->exten, code, strlen(code)))
2868                         res = AST_FEATURE_RETURN_STOREDIGITS;
2869
2870                 AST_RWLIST_UNLOCK(&feature_list);
2871         }
2872
2873         return res;
2874 }
2875
2876 /*!
2877  * \brief Check the dynamic features
2878  * \param chan,peer,config,code,sense
2879  *
2880  * \retval res on success.
2881  * \retval -1 on failure.
2882 */
2883
2884 static int feature_interpret(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense) {
2885
2886         char dynamic_features_buf[128];
2887         const char *peer_dynamic_features, *chan_dynamic_features;
2888         struct ast_flags features;
2889         struct ast_call_feature feature;
2890         if (sense == FEATURE_SENSE_CHAN) {
2891                 ast_copy_flags(&features, &(config->features_caller), AST_FLAGS_ALL);
2892         }
2893         else {
2894                 ast_copy_flags(&features, &(config->features_callee), AST_FLAGS_ALL);
2895         }
2896
2897         ast_channel_lock(peer);
2898         peer_dynamic_features = ast_strdupa(S_OR(pbx_builtin_getvar_helper(peer, "DYNAMIC_FEATURES"),""));
2899         ast_channel_unlock(peer);
2900
2901         ast_channel_lock(chan);
2902         chan_dynamic_features = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "DYNAMIC_FEATURES"),""));
2903         ast_channel_unlock(chan);
2904
2905         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,""));
2906
2907         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);
2908
2909         return feature_interpret_helper(chan, peer, config, code, sense, dynamic_features_buf, &features, FEATURE_INTERPRET_DO, &feature);
2910 }
2911
2912
2913 int ast_feature_detect(struct ast_channel *chan, struct ast_flags *features, const char *code, struct ast_call_feature *feature) {
2914
2915         return feature_interpret_helper(chan, NULL, NULL, code, 0, NULL, features, FEATURE_INTERPRET_DETECT, feature);
2916 }
2917
2918 /*! \brief Check if a feature exists */
2919 static int feature_check(struct ast_channel *chan, struct ast_flags *features, char *code) {
2920
2921         return feature_interpret_helper(chan, NULL, NULL, code, 0, NULL, features, FEATURE_INTERPRET_CHECK, NULL);
2922 }
2923
2924 static void set_config_flags(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config)
2925 {
2926         int x;
2927
2928         ast_clear_flag(config, AST_FLAGS_ALL);
2929
2930         ast_rwlock_rdlock(&features_lock);
2931         for (x = 0; x < FEATURES_COUNT; x++) {
2932                 if (!ast_test_flag(builtin_features + x, AST_FEATURE_FLAG_NEEDSDTMF))
2933                         continue;
2934
2935                 if (ast_test_flag(&(config->features_caller), builtin_features[x].feature_mask))
2936                         ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
2937
2938                 if (ast_test_flag(&(config->features_callee), builtin_features[x].feature_mask))
2939                         ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
2940         }
2941         ast_rwlock_unlock(&features_lock);
2942
2943         if (chan && peer && !(ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_0) && ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_1))) {
2944                 const char *dynamic_features = pbx_builtin_getvar_helper(chan, "DYNAMIC_FEATURES");
2945
2946                 if (dynamic_features) {
2947                         char *tmp = ast_strdupa(dynamic_features);
2948                         char *tok;
2949                         struct ast_call_feature *feature;
2950
2951                         /* while we have a feature */
2952                         while ((tok = strsep(&tmp, "#"))) {
2953                                 struct feature_group *fg;
2954
2955                                 AST_RWLIST_RDLOCK(&feature_groups);
2956                                 AST_RWLIST_TRAVERSE(&feature_groups, fg, entry) {
2957                                         struct feature_group_exten *fge;
2958
2959                                         AST_LIST_TRAVERSE(&fg->features, fge, entry) {
2960                                                 if (ast_test_flag(fge->feature, AST_FEATURE_FLAG_BYCALLER)) {
2961                                                         ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
2962                                                 }
2963                                                 if (ast_test_flag(fge->feature, AST_FEATURE_FLAG_BYCALLEE)) {
2964                                                         ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
2965                                                 }
2966                                         }
2967                                 }
2968                                 AST_RWLIST_UNLOCK(&feature_groups);
2969
2970                                 AST_RWLIST_RDLOCK(&feature_list);
2971                                 if ((feature = find_dynamic_feature(tok)) && ast_test_flag(feature, AST_FEATURE_FLAG_NEEDSDTMF)) {
2972                                         if (ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLER)) {
2973                                                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
2974                                         }
2975                                         if (ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLEE)) {
2976                                                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
2977                                         }
2978                                 }
2979                                 AST_RWLIST_UNLOCK(&feature_list);
2980                         }
2981                 }
2982         }
2983 }
2984
2985 /*!
2986  * \internal
2987  * \brief Get feature and dial.
2988  *
2989  * \param caller Channel to represent as the calling channel for the dialed channel.
2990  * \param caller_name Original caller channel name.
2991  * \param requestor Channel to say is requesting the dial (usually the caller).
2992  * \param transferee Channel that the dialed channel will be transferred to.
2993  * \param type Channel technology type to dial.
2994  * \param format Codec formats for dialed channel.
2995  * \param data Dialed channel extra parameters for ast_request() and ast_call().
2996  * \param timeout Time limit for dialed channel to answer in ms. Must be greater than zero.
2997  * \param outstate Status of dialed channel if unsuccessful.
2998  * \param language Language of the caller.
2999  *
3000  * \note
3001  * outstate can be:
3002  * 0, AST_CONTROL_BUSY, AST_CONTROL_CONGESTION,
3003  * AST_CONTROL_ANSWER, or AST_CONTROL_UNHOLD.  If
3004  * AST_CONTROL_UNHOLD then the caller channel cancelled the
3005  * transfer or the dialed channel did not answer before the
3006  * timeout.
3007  *
3008  * \details
3009  * Request channel, set channel variables, initiate call,
3010  * check if they want to disconnect, go into loop, check if timeout has elapsed,
3011  * check if person to be transfered hung up, check for answer break loop,
3012  * set cdr return channel.
3013  *
3014  * \retval Channel Connected channel for transfer.
3015  * \retval NULL on failure to get third party connected.
3016  *
3017  * \note This is similar to __ast_request_and_dial() in channel.c
3018  */
3019 static struct ast_channel *feature_request_and_dial(struct ast_channel *caller,
3020         const char *caller_name, struct ast_channel *requestor,
3021         struct ast_channel *transferee, const char *type, struct ast_format_cap *cap, void *data,
3022         int timeout, int *outstate, const char *language)
3023 {
3024         int state = 0;
3025         int cause = 0;
3026         int to;
3027         int caller_hungup;
3028         int transferee_hungup;
3029         struct ast_channel *chan;
3030         struct ast_channel *monitor_chans[3];
3031         struct ast_channel *active_channel;
3032         int res;
3033         int ready = 0;
3034         struct timeval started;
3035         int x, len = 0;
3036         char *disconnect_code = NULL, *dialed_code = NULL;
3037         struct ast_format_cap *tmp_cap;
3038         struct ast_format best_audio_fmt;
3039         struct ast_frame *f;
3040         AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
3041
3042         tmp_cap = ast_format_cap_alloc_nolock();
3043         if (!tmp_cap) {
3044                 return NULL;
3045         }
3046         ast_best_codec(cap, &best_audio_fmt);
3047         ast_format_cap_add(tmp_cap, &best_audio_fmt);
3048
3049         caller_hungup = ast_check_hangup(caller);
3050
3051         if (!(chan = ast_request(type, tmp_cap, requestor, data, &cause))) {
3052                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
3053                 switch (cause) {
3054                 case AST_CAUSE_BUSY:
3055                         state = AST_CONTROL_BUSY;
3056                         break;
3057                 case AST_CAUSE_CONGESTION:
3058                         state = AST_CONTROL_CONGESTION;
3059                         break;
3060                 default:
3061                         state = 0;
3062                         break;
3063                 }
3064                 goto done;
3065         }
3066
3067         ast_string_field_set(chan, language, language);
3068         ast_channel_inherit_variables(caller, chan);
3069         pbx_builtin_setvar_helper(chan, "TRANSFERERNAME", caller_name);
3070
3071         ast_channel_lock(chan);
3072         ast_connected_line_copy_from_caller(&chan->connected, &requestor->caller);
3073         ast_channel_unlock(chan);
3074
3075         if (ast_call(chan, data, timeout)) {
3076                 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
3077                 switch (chan->hangupcause) {
3078                 case AST_CAUSE_BUSY:
3079                         state = AST_CONTROL_BUSY;
3080                         break;
3081                 case AST_CAUSE_CONGESTION:
3082                         state = AST_CONTROL_CONGESTION;
3083                         break;
3084                 default:
3085                         state = 0;
3086                         break;
3087                 }
3088                 goto done;
3089         }
3090
3091         /* support dialing of the featuremap disconnect code while performing an attended tranfer */
3092         ast_rwlock_rdlock(&features_lock);
3093         for (x = 0; x < FEATURES_COUNT; x++) {
3094                 if (strcasecmp(builtin_features[x].sname, "disconnect"))
3095                         continue;
3096
3097                 disconnect_code = builtin_features[x].exten;
3098                 len = strlen(disconnect_code) + 1;
3099                 dialed_code = alloca(len);
3100                 memset(dialed_code, 0, len);
3101                 break;
3102  &n