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