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