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