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