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