Sound confirmation of call pickup success.
[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 2000
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 *ast_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 *ast_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 ast_bridge_call_thread
450 */
451 static void ast_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,ast_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 ast_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 ast_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 ast_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 = ast_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 = ast_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                 ast_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 = ast_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 = ast_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 = ast_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                 ast_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 ast_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 *dynamic_features;
1987         char *tmp, *tok;
1988         int res = AST_FEATURE_RETURN_PASSDIGITS;
1989         int feature_detected = 0;
1990
1991         if (sense == FEATURE_SENSE_CHAN) {
1992                 ast_copy_flags(&features, &(config->features_caller), AST_FLAGS_ALL);
1993                 dynamic_features = pbx_builtin_getvar_helper(chan, "DYNAMIC_FEATURES");
1994         }
1995         else {
1996                 ast_copy_flags(&features, &(config->features_callee), AST_FLAGS_ALL);
1997                 dynamic_features = pbx_builtin_getvar_helper(peer, "DYNAMIC_FEATURES");
1998         }
1999         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);
2000
2001         ast_rwlock_rdlock(&features_lock);
2002         for (x = 0; x < FEATURES_COUNT; x++) {
2003                 if ((ast_test_flag(&features, builtin_features[x].feature_mask)) &&
2004                     !ast_strlen_zero(builtin_features[x].exten)) {
2005                         /* Feature is up for consideration */
2006                         if (!strcmp(builtin_features[x].exten, code)) {
2007                                 ast_debug(3, "Feature detected: fname=%s sname=%s exten=%s\n", builtin_features[x].fname, builtin_features[x].sname, builtin_features[x].exten);
2008                                 res = builtin_features[x].operation(chan, peer, config, code, sense, NULL);
2009                                 feature_detected = 1;
2010                                 break;
2011                         } else if (!strncmp(builtin_features[x].exten, code, strlen(code))) {
2012                                 if (res == AST_FEATURE_RETURN_PASSDIGITS)
2013                                         res = AST_FEATURE_RETURN_STOREDIGITS;
2014                         }
2015                 }
2016         }
2017         ast_rwlock_unlock(&features_lock);
2018
2019         if (ast_strlen_zero(dynamic_features) || feature_detected)
2020                 return res;
2021
2022         tmp = ast_strdupa(dynamic_features);
2023
2024         while ((tok = strsep(&tmp, "#"))) {
2025                 AST_RWLIST_RDLOCK(&feature_groups);
2026
2027                 fg = find_group(tok);
2028
2029                 if (fg) {
2030                         AST_LIST_TRAVERSE(&fg->features, fge, entry) {
2031                                 if (strcasecmp(fge->exten, code))
2032                                         continue;
2033
2034                                 res = fge->feature->operation(chan, peer, config, code, sense, fge->feature);
2035                                 if (res != AST_FEATURE_RETURN_KEEPTRYING) {
2036                                         AST_RWLIST_UNLOCK(&feature_groups);
2037                                         break;
2038                                 }
2039                                 res = AST_FEATURE_RETURN_PASSDIGITS;
2040                         }
2041                         if (fge)
2042                                 break;
2043                 }
2044
2045                 AST_RWLIST_UNLOCK(&feature_groups);
2046
2047                 AST_RWLIST_RDLOCK(&feature_list);
2048
2049                 if (!(feature = find_dynamic_feature(tok))) {
2050                         AST_RWLIST_UNLOCK(&feature_list);
2051                         continue;
2052                 }
2053                         
2054                 /* Feature is up for consideration */
2055                 if (!strcmp(feature->exten, code)) {
2056                         ast_verb(3, " Feature Found: %s exten: %s\n",feature->sname, tok);
2057                         res = feature->operation(chan, peer, config, code, sense, feature);
2058                         if (res != AST_FEATURE_RETURN_KEEPTRYING) {
2059                                 AST_RWLIST_UNLOCK(&feature_list);
2060                                 break;
2061                         }
2062                         res = AST_FEATURE_RETURN_PASSDIGITS;
2063                 } else if (!strncmp(feature->exten, code, strlen(code)))
2064                         res = AST_FEATURE_RETURN_STOREDIGITS;
2065
2066                 AST_RWLIST_UNLOCK(&feature_list);
2067         }
2068         
2069         return res;
2070 }
2071
2072 static void set_config_flags(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config)
2073 {
2074         int x;
2075         
2076         ast_clear_flag(config, AST_FLAGS_ALL);
2077
2078         ast_rwlock_rdlock(&features_lock);
2079         for (x = 0; x < FEATURES_COUNT; x++) {
2080                 if (!ast_test_flag(builtin_features + x, AST_FEATURE_FLAG_NEEDSDTMF))
2081                         continue;
2082
2083                 if (ast_test_flag(&(config->features_caller), builtin_features[x].feature_mask))
2084                         ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
2085
2086                 if (ast_test_flag(&(config->features_callee), builtin_features[x].feature_mask))
2087                         ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
2088         }
2089         ast_rwlock_unlock(&features_lock);
2090         
2091         if (chan && peer && !(ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_0) && ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_1))) {
2092                 const char *dynamic_features = pbx_builtin_getvar_helper(chan, "DYNAMIC_FEATURES");
2093
2094                 if (dynamic_features) {
2095                         char *tmp = ast_strdupa(dynamic_features);
2096                         char *tok;
2097                         struct ast_call_feature *feature;
2098
2099                         /* while we have a feature */
2100                         while ((tok = strsep(&tmp, "#"))) {
2101                                 AST_RWLIST_RDLOCK(&feature_list);
2102                                 if ((feature = find_dynamic_feature(tok)) && ast_test_flag(feature, AST_FEATURE_FLAG_NEEDSDTMF)) {
2103                                         if (ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLER))
2104                                                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
2105                                         if (ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLEE))
2106                                                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
2107                                 }
2108                                 AST_RWLIST_UNLOCK(&feature_list);
2109                         }
2110                 }
2111         }
2112 }
2113
2114 /*! 
2115  * \brief Get feature and dial
2116  * \param caller,transferee,type,format,data,timeout,outstate,cid_num,cid_name,igncallerstate
2117  *
2118  * Request channel, set channel variables, initiate call,check if they want to disconnect
2119  * go into loop, check if timeout has elapsed, check if person to be transfered hung up,
2120  * check for answer break loop, set cdr return channel.
2121  *
2122  * \todo XXX Check - this is very similar to the code in channel.c 
2123  * \return always a channel
2124 */
2125 static struct ast_channel *ast_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)
2126 {
2127         int state = 0;
2128         int cause = 0;
2129         int to;
2130         struct ast_channel *chan;
2131         struct ast_channel *monitor_chans[2];
2132         struct ast_channel *active_channel;
2133         int res = 0, ready = 0;
2134         struct timeval started;
2135         int x, len = 0;
2136         char *disconnect_code = NULL, *dialed_code = NULL;
2137
2138         if (!(chan = ast_request(type, format, data, &cause))) {
2139                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2140                 switch(cause) {
2141                 case AST_CAUSE_BUSY:
2142                         state = AST_CONTROL_BUSY;
2143                         break;
2144                 case AST_CAUSE_CONGESTION:
2145                         state = AST_CONTROL_CONGESTION;
2146                         break;
2147                 }
2148                 goto done;
2149         }
2150
2151         ast_set_callerid(chan, cid_num, cid_name, cid_num);
2152         ast_string_field_set(chan, language, language);
2153         ast_channel_inherit_variables(caller, chan);    
2154         pbx_builtin_setvar_helper(chan, "TRANSFERERNAME", caller->name);
2155                 
2156         if (ast_call(chan, data, timeout)) {
2157                 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2158                 goto done;
2159         }
2160         
2161         ast_indicate(caller, AST_CONTROL_RINGING);
2162         /* support dialing of the featuremap disconnect code while performing an attended tranfer */
2163         ast_rwlock_rdlock(&features_lock);
2164         for (x = 0; x < FEATURES_COUNT; x++) {
2165                 if (strcasecmp(builtin_features[x].sname, "disconnect"))
2166                         continue;
2167
2168                 disconnect_code = builtin_features[x].exten;
2169                 len = strlen(disconnect_code) + 1;
2170                 dialed_code = alloca(len);
2171                 memset(dialed_code, 0, len);
2172                 break;
2173         }
2174         ast_rwlock_unlock(&features_lock);
2175         x = 0;
2176         started = ast_tvnow();
2177         to = timeout;
2178
2179         ast_poll_channel_add(caller, chan);
2180
2181         while (!((transferee && ast_check_hangup(transferee)) && (!igncallerstate && ast_check_hangup(caller))) && timeout && (chan->_state != AST_STATE_UP)) {
2182                 struct ast_frame *f = NULL;
2183
2184                 monitor_chans[0] = caller;
2185                 monitor_chans[1] = chan;
2186                 active_channel = ast_waitfor_n(monitor_chans, 2, &to);
2187
2188                 /* see if the timeout has been violated */
2189                 if(ast_tvdiff_ms(ast_tvnow(), started) > timeout) {
2190                         state = AST_CONTROL_UNHOLD;
2191                         ast_log(LOG_NOTICE, "We exceeded our AT-timeout\n");
2192                         break; /*doh! timeout*/
2193                 }
2194
2195                 if (!active_channel)
2196                         continue;
2197
2198                 if (chan && (chan == active_channel)){
2199                         f = ast_read(chan);
2200                         if (f == NULL) { /*doh! where'd he go?*/
2201                                 state = AST_CONTROL_HANGUP;
2202                                 res = 0;
2203                                 break;
2204                         }
2205                         
2206                         if (f->frametype == AST_FRAME_CONTROL || f->frametype == AST_FRAME_DTMF || f->frametype == AST_FRAME_TEXT) {
2207                                 if (f->subclass == AST_CONTROL_RINGING) {
2208                                         state = f->subclass;
2209                                         ast_verb(3, "%s is ringing\n", chan->name);
2210                                         ast_indicate(caller, AST_CONTROL_RINGING);
2211                                 } else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
2212                                         state = f->subclass;
2213                                         ast_verb(3, "%s is busy\n", chan->name);
2214                                         ast_indicate(caller, AST_CONTROL_BUSY);
2215                                         ast_frfree(f);
2216                                         f = NULL;
2217                                         break;
2218                                 } else if (f->subclass == AST_CONTROL_ANSWER) {
2219                                         /* This is what we are hoping for */
2220                                         state = f->subclass;
2221                                         ast_frfree(f);
2222                                         f = NULL;
2223                                         ready=1;
2224                                         break;
2225                                 } else if (f->subclass != -1) {
2226                                         ast_log(LOG_NOTICE, "Don't know what to do about control frame: %d\n", f->subclass);
2227                                 }
2228                                 /* else who cares */
2229                         }
2230
2231                 } else if (caller && (active_channel == caller)) {
2232                         f = ast_read(caller);
2233                         if (f == NULL) { /*doh! where'd he go?*/
2234                                 if (!igncallerstate) {
2235                                         if (ast_check_hangup(caller) && !ast_check_hangup(chan)) {
2236                                                 /* make this a blind transfer */
2237                                                 ready = 1;
2238                                                 break;
2239                                         }
2240                                         state = AST_CONTROL_HANGUP;
2241                                         res = 0;
2242                                         break;
2243                                 }
2244                         } else {
2245                         
2246                                 if (f->frametype == AST_FRAME_DTMF) {
2247                                         dialed_code[x++] = f->subclass;
2248                                         dialed_code[x] = '\0';
2249                                         if (strlen(dialed_code) == len) {
2250                                                 x = 0;
2251                                         } else if (x && strncmp(dialed_code, disconnect_code, x)) {
2252                                                 x = 0;
2253                                                 dialed_code[x] = '\0';
2254                                         }
2255                                         if (*dialed_code && !strcmp(dialed_code, disconnect_code)) {
2256                                                 /* Caller Canceled the call */
2257                                                 state = AST_CONTROL_UNHOLD;
2258                                                 ast_frfree(f);
2259                                                 f = NULL;
2260                                                 break;
2261                                         }
2262                                 }
2263                         }
2264                 }
2265                 if (f)
2266                         ast_frfree(f);
2267         } /* end while */
2268
2269         ast_poll_channel_del(caller, chan);
2270                 
2271 done:
2272         ast_indicate(caller, -1);
2273         if (chan && ready) {
2274                 if (chan->_state == AST_STATE_UP) 
2275                         state = AST_CONTROL_ANSWER;
2276                 res = 0;
2277         } else if (chan) {
2278                 res = -1;
2279                 ast_hangup(chan);
2280                 chan = NULL;
2281         } else {
2282                 res = -1;
2283         }
2284         
2285         if (outstate)
2286                 *outstate = state;
2287
2288         return chan;
2289 }
2290
2291 /*!
2292  * \brief return the first unlocked cdr in a possible chain
2293 */
2294 static struct ast_cdr *pick_unlocked_cdr(struct ast_cdr *cdr)
2295 {
2296         struct ast_cdr *cdr_orig = cdr;
2297         while (cdr) {
2298                 if (!ast_test_flag(cdr,AST_CDR_FLAG_LOCKED))
2299                         return cdr;
2300                 cdr = cdr->next;
2301         }
2302         return cdr_orig; /* everybody LOCKED or some other weirdness, like a NULL */
2303 }
2304
2305 static void set_bridge_features_on_config(struct ast_bridge_config *config, const char *features)
2306 {
2307         const char *feature;
2308
2309         if (ast_strlen_zero(features)) {
2310                 return;
2311         }
2312
2313         for (feature = features; *feature; feature++) {
2314                 switch (*feature) {
2315                 case 'T' :
2316                 case 't' :
2317                         ast_set_flag(&(config->features_caller), AST_FEATURE_REDIRECT);
2318                         break;
2319                 case 'K' :
2320                 case 'k' :
2321                         ast_set_flag(&(config->features_caller), AST_FEATURE_PARKCALL);
2322                         break;
2323                 case 'H' :
2324                 case 'h' :
2325                         ast_set_flag(&(config->features_caller), AST_FEATURE_DISCONNECT);
2326                         break;
2327                 case 'W' :
2328                 case 'w' :
2329                         ast_set_flag(&(config->features_caller), AST_FEATURE_AUTOMON);
2330                         break;
2331                 default :
2332                         ast_log(LOG_WARNING, "Skipping unknown feature code '%c'\n", *feature);
2333                 }
2334         }
2335 }
2336
2337 static void add_features_datastores(struct ast_channel *caller, struct ast_channel *callee, struct ast_bridge_config *config)
2338 {
2339         struct ast_datastore *ds_callee_features = NULL, *ds_caller_features = NULL;
2340         struct ast_dial_features *callee_features = NULL, *caller_features = NULL;
2341
2342         ast_channel_lock(caller);
2343         ds_caller_features = ast_channel_datastore_find(caller, &dial_features_info, NULL);
2344         ast_channel_unlock(caller);
2345         if (!ds_caller_features) {
2346                 if (!(ds_caller_features = ast_datastore_alloc(&dial_features_info, NULL))) {
2347                         ast_log(LOG_WARNING, "Unable to create channel datastore for caller features. Aborting!\n");
2348                         return;
2349                 }
2350                 if (!(caller_features = ast_calloc(1, sizeof(*caller_features)))) {
2351                         ast_log(LOG_WARNING, "Unable to allocate memory for callee feature flags. Aborting!\n");
2352                         ast_datastore_free(ds_caller_features);
2353                         return;
2354                 }
2355                 ds_caller_features->inheritance = DATASTORE_INHERIT_FOREVER;
2356                 caller_features->is_caller = 1;
2357                 ast_copy_flags(&(caller_features->features_callee), &(config->features_callee), AST_FLAGS_ALL);
2358                 ast_copy_flags(&(caller_features->features_caller), &(config->features_caller), AST_FLAGS_ALL);
2359                 ds_caller_features->data = caller_features;
2360                 ast_channel_lock(caller);
2361                 ast_channel_datastore_add(caller, ds_caller_features);
2362                 ast_channel_unlock(caller);
2363         } else {
2364                 /* If we don't return here, then when we do a builtin_atxfer we will copy the disconnect
2365                  * flags over from the atxfer to the caller */
2366                 return;
2367         }
2368
2369         ast_channel_lock(callee);
2370         ds_callee_features = ast_channel_datastore_find(callee, &dial_features_info, NULL);
2371         ast_channel_unlock(callee);
2372         if (!ds_callee_features) {
2373                 if (!(ds_callee_features = ast_datastore_alloc(&dial_features_info, NULL))) {
2374                         ast_log(LOG_WARNING, "Unable to create channel datastore for callee features. Aborting!\n");
2375                         return;
2376                 }
2377                 if (!(callee_features = ast_calloc(1, sizeof(*callee_features)))) {
2378                         ast_log(LOG_WARNING, "Unable to allocate memory for callee feature flags. Aborting!\n");
2379                         ast_datastore_free(ds_callee_features);
2380                         return;
2381                 }
2382                 ds_callee_features->inheritance = DATASTORE_INHERIT_FOREVER;
2383                 callee_features->is_caller = 0;
2384                 ast_copy_flags(&(callee_features->features_callee), &(config->features_caller), AST_FLAGS_ALL);
2385                 ast_copy_flags(&(callee_features->features_caller), &(config->features_callee), AST_FLAGS_ALL);
2386                 ds_callee_features->data = callee_features;
2387                 ast_channel_lock(callee);
2388                 ast_channel_datastore_add(callee, ds_callee_features);
2389                 ast_channel_unlock(callee);
2390         }
2391
2392         return;
2393 }
2394
2395 /*!
2396  * \brief bridge the call and set CDR
2397  * \param chan,peer,config
2398  * 
2399  * Set start time, check for two channels,check if monitor on
2400  * check for feature activation, create new CDR
2401  * \retval res on success.
2402  * \retval -1 on failure to bridge.
2403 */
2404 int ast_bridge_call(struct ast_channel *chan,struct ast_channel *peer,struct ast_bridge_config *config)
2405 {
2406         /* Copy voice back and forth between the two channels.  Give the peer
2407            the ability to transfer calls with '#<extension' syntax. */
2408         struct ast_frame *f;
2409         struct ast_channel *who;
2410         char chan_featurecode[FEATURE_MAX_LEN + 1]="";
2411         char peer_featurecode[FEATURE_MAX_LEN + 1]="";
2412         char orig_channame[AST_MAX_EXTENSION];
2413         char orig_peername[AST_MAX_EXTENSION];
2414         int res;
2415         int diff;
2416         int hasfeatures=0;
2417         int hadfeatures=0;
2418         int autoloopflag;
2419         struct ast_option_header *aoh;
2420         struct ast_bridge_config backup_config;
2421         struct ast_cdr *bridge_cdr = NULL;
2422         struct ast_cdr *orig_peer_cdr = NULL;
2423         struct ast_cdr *chan_cdr = pick_unlocked_cdr(chan->cdr); /* the proper chan cdr, if there are forked cdrs */
2424         struct ast_cdr *peer_cdr = pick_unlocked_cdr(peer->cdr); /* the proper chan cdr, if there are forked cdrs */
2425         struct ast_cdr *new_chan_cdr = NULL; /* the proper chan cdr, if there are forked cdrs */
2426         struct ast_cdr *new_peer_cdr = NULL; /* the proper chan cdr, if there are forked cdrs */
2427
2428         memset(&backup_config, 0, sizeof(backup_config));
2429
2430         config->start_time = ast_tvnow();
2431
2432         if (chan && peer) {
2433                 pbx_builtin_setvar_helper(chan, "BRIDGEPEER", peer->name);
2434                 pbx_builtin_setvar_helper(peer, "BRIDGEPEER", chan->name);
2435         } else if (chan) {
2436                 pbx_builtin_setvar_helper(chan, "BLINDTRANSFER", NULL);
2437         }
2438
2439         set_bridge_features_on_config(config, pbx_builtin_getvar_helper(chan, "BRIDGE_FEATURES"));
2440         add_features_datastores(chan, peer, config);
2441
2442         /* This is an interesting case.  One example is if a ringing channel gets redirected to
2443          * an extension that picks up a parked call.  This will make sure that the call taken
2444          * out of parking gets told that the channel it just got bridged to is still ringing. */
2445         if (chan->_state == AST_STATE_RINGING && peer->visible_indication != AST_CONTROL_RINGING) {
2446                 ast_indicate(peer, AST_CONTROL_RINGING);
2447         }
2448
2449         if (monitor_ok) {
2450                 const char *monitor_exec;
2451                 struct ast_channel *src = NULL;
2452                 if (!monitor_app) { 
2453                         if (!(monitor_app = pbx_findapp("Monitor")))
2454                                 monitor_ok=0;
2455                 }
2456                 if ((monitor_exec = pbx_builtin_getvar_helper(chan, "AUTO_MONITOR"))) 
2457                         src = chan;
2458                 else if ((monitor_exec = pbx_builtin_getvar_helper(peer, "AUTO_MONITOR")))
2459                         src = peer;
2460                 if (monitor_app && src) {
2461                         char *tmp = ast_strdupa(monitor_exec);
2462                         pbx_exec(src, monitor_app, tmp);
2463                 }
2464         }
2465
2466         set_config_flags(chan, peer, config);
2467         config->firstpass = 1;
2468
2469         /* Answer if need be */
2470         if (ast_answer(chan))
2471                 return -1;
2472
2473         ast_copy_string(orig_channame,chan->name,sizeof(orig_channame));
2474         ast_copy_string(orig_peername,peer->name,sizeof(orig_peername));
2475         orig_peer_cdr = peer_cdr;
2476         
2477         if (!chan_cdr || (chan_cdr && !ast_test_flag(chan_cdr, AST_CDR_FLAG_POST_DISABLED))) {
2478                 
2479                 if (chan_cdr) {
2480                         ast_set_flag(chan_cdr, AST_CDR_FLAG_MAIN);
2481                         ast_cdr_update(chan);
2482                         bridge_cdr = ast_cdr_dup(chan_cdr);
2483                         ast_copy_string(bridge_cdr->lastapp, chan->appl, sizeof(bridge_cdr->lastapp));
2484                         ast_copy_string(bridge_cdr->lastdata, chan->data, sizeof(bridge_cdr->lastdata));
2485                 } else {
2486                         /* better yet, in a xfer situation, find out why the chan cdr got zapped (pun unintentional) */
2487                         bridge_cdr = ast_cdr_alloc(); /* this should be really, really rare/impossible? */
2488                         ast_copy_string(bridge_cdr->channel, chan->name, sizeof(bridge_cdr->channel));
2489                         ast_copy_string(bridge_cdr->dstchannel, peer->name, sizeof(bridge_cdr->dstchannel));
2490                         ast_copy_string(bridge_cdr->uniqueid, chan->uniqueid, sizeof(bridge_cdr->uniqueid));
2491                         ast_copy_string(bridge_cdr->lastapp, chan->appl, sizeof(bridge_cdr->lastapp));
2492                         ast_copy_string(bridge_cdr->lastdata, chan->data, sizeof(bridge_cdr->lastdata));
2493                         ast_cdr_setcid(bridge_cdr, chan);
2494                         bridge_cdr->disposition = (chan->_state == AST_STATE_UP) ?  AST_CDR_ANSWERED : AST_CDR_NULL;
2495                         bridge_cdr->amaflags = chan->amaflags ? chan->amaflags :  ast_default_amaflags;
2496                         ast_copy_string(bridge_cdr->accountcode, chan->accountcode, sizeof(bridge_cdr->accountcode));
2497                         /* Destination information */
2498                         ast_copy_string(bridge_cdr->dst, chan->exten, sizeof(bridge_cdr->dst));
2499                         ast_copy_string(bridge_cdr->dcontext, chan->context, sizeof(bridge_cdr->dcontext));
2500                         if (peer_cdr) {
2501                                 bridge_cdr->start = peer_cdr->start;
2502                                 ast_copy_string(bridge_cdr->userfield, peer_cdr->userfield, sizeof(bridge_cdr->userfield));
2503                         } else {
2504                                 ast_cdr_start(bridge_cdr);
2505                         }
2506                 }
2507                 ast_debug(4,"bridge answer set, chan answer set\n");
2508                 /* peer_cdr->answer will be set when a macro runs on the peer;
2509                    in that case, the bridge answer will be delayed while the
2510                    macro plays on the peer channel. The peer answered the call
2511                    before the macro started playing. To the phone system,
2512                    this is billable time for the call, even tho the caller
2513                    hears nothing but ringing while the macro does its thing. */
2514                 if (peer_cdr && !ast_tvzero(peer_cdr->answer)) {
2515                         bridge_cdr->answer = peer_cdr->answer;
2516                         chan_cdr->answer = peer_cdr->answer;
2517                         bridge_cdr->disposition = peer_cdr->disposition;
2518                         chan_cdr->disposition = peer_cdr->disposition;
2519                 } else {
2520                         ast_cdr_answer(bridge_cdr);
2521                         ast_cdr_answer(chan_cdr); /* for the sake of cli status checks */
2522                 }
2523                 if (ast_test_flag(chan,AST_FLAG_BRIDGE_HANGUP_DONT)) {
2524                         ast_set_flag(chan_cdr, AST_CDR_FLAG_BRIDGED);
2525                         if (peer_cdr) {
2526                                 ast_set_flag(peer_cdr, AST_CDR_FLAG_BRIDGED);
2527                         }
2528                 }
2529         }
2530         for (;;) {
2531                 struct ast_channel *other;      /* used later */
2532         
2533                 res = ast_channel_bridge(chan, peer, config, &f, &who);
2534                 
2535                 /* When frame is not set, we are probably involved in a situation
2536                    where we've timed out.
2537                    When frame is set, we'll come this code twice; once for DTMF_BEGIN
2538                    and also for DTMF_END. If we flow into the following 'if' for both, then 
2539                    our wait times are cut in half, as both will subtract from the
2540                    feature_timer. Not good!
2541                 */
2542                 if (config->feature_timer && (!f || f->frametype == AST_FRAME_DTMF_END)) {
2543                         /* Update time limit for next pass */
2544                         diff = ast_tvdiff_ms(ast_tvnow(), config->start_time);
2545                         if (res == AST_BRIDGE_RETRY) {
2546                                 /* The feature fully timed out but has not been updated. Skip
2547                                  * the potential round error from the diff calculation and
2548                                  * explicitly set to expired. */
2549                                 config->feature_timer = -1;
2550                         } else {
2551                                 config->feature_timer -= diff;
2552                         }
2553
2554                         if (hasfeatures) {
2555                                 /* Running on backup config, meaning a feature might be being
2556                                    activated, but that's no excuse to keep things going 
2557                                    indefinitely! */
2558                                 if (backup_config.feature_timer && ((backup_config.feature_timer -= diff) <= 0)) {
2559                                         ast_debug(1, "Timed out, realtime this time!\n");
2560                                         config->feature_timer = 0;
2561                                         who = chan;
2562                                         if (f)
2563                                                 ast_frfree(f);
2564                                         f = NULL;
2565                                         res = 0;
2566                                 } else if (config->feature_timer <= 0) {
2567                                         /* Not *really* out of time, just out of time for
2568                                            digits to come in for features. */
2569                                         ast_debug(1, "Timed out for feature!\n");
2570                                         if (!ast_strlen_zero(peer_featurecode)) {
2571                                                 ast_dtmf_stream(chan, peer, peer_featurecode, 0, 0);
2572                                                 memset(peer_featurecode, 0, sizeof(peer_featurecode));
2573                                         }
2574                                         if (!ast_strlen_zero(chan_featurecode)) {
2575                                                 ast_dtmf_stream(peer, chan, chan_featurecode, 0, 0);
2576                                                 memset(chan_featurecode, 0, sizeof(chan_featurecode));
2577                                         }
2578                                         if (f)
2579                                                 ast_frfree(f);
2580                                         hasfeatures = !ast_strlen_zero(chan_featurecode) || !ast_strlen_zero(peer_featurecode);
2581                                         if (!hasfeatures) {
2582                                                 /* Restore original (possibly time modified) bridge config */
2583                                                 memcpy(config, &backup_config, sizeof(struct ast_bridge_config));
2584                                                 memset(&backup_config, 0, sizeof(backup_config));
2585                                         }
2586                                         hadfeatures = hasfeatures;
2587                                         /* Continue as we were */
2588                                         continue;
2589                                 } else if (!f) {
2590                                         /* The bridge returned without a frame and there is a feature in progress.
2591                                          * However, we don't think the feature has quite yet timed out, so just
2592                                          * go back into the bridge. */
2593                                         continue;
2594                                 }
2595                         } else {
2596                                 if (config->feature_timer <=0) {
2597                                         /* We ran out of time */
2598                                         config->feature_timer = 0;
2599                                         who = chan;
2600                                         if (f)
2601                                                 ast_frfree(f);
2602                                         f = NULL;
2603                                         res = 0;
2604                                 }
2605                         }
2606                 }
2607                 if (res < 0) {
2608                         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_test_flag(peer, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan) && !ast_check_hangup(peer))
2609                                 ast_log(LOG_WARNING, "Bridge failed on channels %s and %s\n", chan->name, peer->name);
2610                         goto before_you_go;
2611                 }
2612                 
2613                 if (!f || (f->frametype == AST_FRAME_CONTROL &&
2614                                 (f->subclass == AST_CONTROL_HANGUP || f->subclass == AST_CONTROL_BUSY || 
2615                                         f->subclass == AST_CONTROL_CONGESTION))) {
2616                         res = -1;
2617                         break;
2618                 }
2619                 /* many things should be sent to the 'other' channel */
2620                 other = (who == chan) ? peer : chan;
2621                 if (f->frametype == AST_FRAME_CONTROL) {
2622                         switch (f->subclass) {
2623                         case AST_CONTROL_RINGING:
2624                         case AST_CONTROL_FLASH:
2625                         case -1:
2626                                 ast_indicate(other, f->subclass);
2627                                 break;
2628                         case AST_CONTROL_HOLD:
2629                         case AST_CONTROL_UNHOLD:
2630                                 ast_indicate_data(other, f->subclass, f->data.ptr, f->datalen);
2631                                 break;
2632                         case AST_CONTROL_OPTION:
2633                                 aoh = f->data.ptr;
2634                                 /* Forward option Requests */
2635                                 if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
2636                                         ast_channel_setoption(other, ntohs(aoh->option), aoh->data, 
2637                                                 f->datalen - sizeof(struct ast_option_header), 0);
2638                                 }
2639                                 break;
2640                         }
2641                 } else if (f->frametype == AST_FRAME_DTMF_BEGIN) {
2642                         /* eat it */
2643                 } else if (f->frametype == AST_FRAME_DTMF) {
2644                         char *featurecode;
2645                         int sense;
2646
2647                         hadfeatures = hasfeatures;
2648                         /* This cannot overrun because the longest feature is one shorter than our buffer */
2649                         if (who == chan) {
2650                                 sense = FEATURE_SENSE_CHAN;
2651                                 featurecode = chan_featurecode;
2652                         } else  {
2653                                 sense = FEATURE_SENSE_PEER;
2654                                 featurecode = peer_featurecode;
2655                         }
2656                         /*! append the event to featurecode. we rely on the string being zero-filled, and
2657                          * not overflowing it. 
2658                          * \todo XXX how do we guarantee the latter ?
2659                          */
2660                         featurecode[strlen(featurecode)] = f->subclass;
2661                         /* Get rid of the frame before we start doing "stuff" with the channels */
2662                         ast_frfree(f);
2663                         f = NULL;
2664                         config->feature_timer = backup_config.feature_timer;
2665                         res = ast_feature_interpret(chan, peer, config, featurecode, sense);
2666                         switch(res) {
2667                         case AST_FEATURE_RETURN_PASSDIGITS:
2668                                 ast_dtmf_stream(other, who, featurecode, 0, 0);
2669                                 /* Fall through */
2670                         case AST_FEATURE_RETURN_SUCCESS:
2671                                 memset(featurecode, 0, sizeof(chan_featurecode));
2672                                 break;
2673                         }
2674                         if (res >= AST_FEATURE_RETURN_PASSDIGITS) {
2675                                 res = 0;
2676                         } else 
2677                                 break;
2678                         hasfeatures = !ast_strlen_zero(chan_featurecode) || !ast_strlen_zero(peer_featurecode);
2679                         if (hadfeatures && !hasfeatures) {
2680                                 /* Restore backup */
2681                                 memcpy(config, &backup_config, sizeof(struct ast_bridge_config));
2682                                 memset(&backup_config, 0, sizeof(struct ast_bridge_config));
2683                         } else if (hasfeatures) {
2684                                 if (!hadfeatures) {
2685                                         /* Backup configuration */
2686                                         memcpy(&backup_config, config, sizeof(struct ast_bridge_config));
2687                                         /* Setup temporary config options */
2688                                         config->play_warning = 0;
2689                                         ast_clear_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING);
2690                                         ast_clear_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING);
2691                                         config->warning_freq = 0;
2692                                         config->warning_sound = NULL;
2693                                         config->end_sound = NULL;
2694                                         config->start_sound = NULL;
2695                                         config->firstpass = 0;
2696                                 }
2697                                 config->start_time = ast_tvnow();
2698                                 config->feature_timer = featuredigittimeout;
2699                                 ast_debug(1, "Set time limit to %ld\n", config->feature_timer);
2700                         }
2701                 }
2702                 if (f)
2703                         ast_frfree(f);
2704
2705         }
2706    before_you_go:
2707
2708         if (ast_test_flag(chan,AST_FLAG_BRIDGE_HANGUP_DONT)) {
2709                 ast_clear_flag(chan,AST_FLAG_BRIDGE_HANGUP_DONT); /* its job is done */
2710                 if (bridge_cdr) {
2711                         ast_cdr_discard(bridge_cdr);
2712                         /* QUESTION: should we copy bridge_cdr fields to the peer before we throw it away? */
2713                 }
2714                 return res; /* if we shouldn't do the h-exten, we shouldn't do the bridge cdr, either! */
2715         }
2716
2717         if (config->end_bridge_callback) {
2718                 config->end_bridge_callback(config->end_bridge_callback_data);
2719         }
2720
2721         /* run the hangup exten on the chan object IFF it was NOT involved in a parking situation 
2722          * if it were, then chan belongs to a different thread now, and might have been hung up long
2723      * ago.
2724          */
2725         if (!ast_test_flag(&(config->features_caller),AST_FEATURE_NO_H_EXTEN) &&
2726                 ast_exists_extension(chan, chan->context, "h", 1, chan->cid.cid_num)) {
2727                 struct ast_cdr *swapper = NULL;
2728                 char savelastapp[AST_MAX_EXTENSION];
2729                 char savelastdata[AST_MAX_EXTENSION];
2730                 char save_exten[AST_MAX_EXTENSION];
2731                 int  save_prio;
2732                 int  found = 0; /* set if we find at least one match */
2733                 int  spawn_error = 0;
2734                 
2735                 autoloopflag = ast_test_flag(chan, AST_FLAG_IN_AUTOLOOP);
2736                 ast_set_flag(chan, AST_FLAG_IN_AUTOLOOP);
2737                 if (bridge_cdr && ast_opt_end_cdr_before_h_exten) {
2738                         ast_cdr_end(bridge_cdr);
2739                 }
2740                 /* swap the bridge cdr and the chan cdr for a moment, and let the endbridge
2741                    dialplan code operate on it */
2742                 ast_channel_lock(chan);
2743                 if (bridge_cdr) {
2744                         swapper = chan->cdr;
2745                         ast_copy_string(savelastapp, bridge_cdr->lastapp, sizeof(bridge_cdr->lastapp));
2746                         ast_copy_string(savelastdata, bridge_cdr->lastdata, sizeof(bridge_cdr->lastdata));
2747                         chan->cdr = bridge_cdr;
2748                 }
2749                 ast_copy_string(save_exten, chan->exten, sizeof(save_exten));
2750                 save_prio = chan->priority;
2751                 ast_copy_string(chan->exten, "h", sizeof(chan->exten));
2752                 chan->priority = 1;
2753                 ast_channel_unlock(chan);
2754                 while ((spawn_error = ast_spawn_extension(chan, chan->context, chan->exten, chan->priority, chan->cid.cid_num, &found, 1)) == 0) {
2755                         chan->priority++;
2756                 }
2757                 if (found && spawn_error) {
2758                         /* Something bad happened, or a hangup has been requested. */
2759                         ast_debug(1, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", chan->context, chan->exten, chan->priority, chan->name);
2760                         ast_verb(2, "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", chan->context, chan->exten, chan->priority, chan->name);
2761                 }
2762                 /* swap it back */
2763                 ast_channel_lock(chan);
2764                 ast_copy_string(chan->exten, save_exten, sizeof(chan->exten));
2765                 chan->priority = save_prio;
2766                 if (bridge_cdr)
2767                         chan->cdr = swapper;
2768                 ast_set_flag(chan, AST_FLAG_BRIDGE_HANGUP_RUN);
2769                 ast_channel_unlock(chan);
2770                 /* protect the lastapp/lastdata against the effects of the hangup/dialplan code */
2771                 if (bridge_cdr) {
2772                         ast_copy_string(bridge_cdr->lastapp, savelastapp, sizeof(bridge_cdr->lastapp));
2773                         ast_copy_string(bridge_cdr->lastdata, savelastdata, sizeof(bridge_cdr->lastdata));
2774                 }
2775                 ast_set2_flag(chan, autoloopflag, AST_FLAG_IN_AUTOLOOP);
2776         }
2777         
2778         /* obey the NoCDR() wishes. -- move the DISABLED flag to the bridge CDR if it was set on the channel during the bridge... */
2779         new_chan_cdr = pick_unlocked_cdr(chan->cdr); /* the proper chan cdr, if there are forked cdrs */
2780         if (bridge_cdr && new_chan_cdr && ast_test_flag(new_chan_cdr, AST_CDR_FLAG_POST_DISABLED))
2781                 ast_set_flag(bridge_cdr, AST_CDR_FLAG_POST_DISABLED);
2782
2783         /* we can post the bridge CDR at this point */
2784         if (bridge_cdr) {
2785                 ast_cdr_end(bridge_cdr);
2786                 ast_cdr_detach(bridge_cdr);
2787         }
2788         
2789         /* do a specialized reset on the beginning channel
2790            CDR's, if they still exist, so as not to mess up
2791            issues in future bridges;
2792            
2793            Here are the rules of the game:
2794            1. The chan and peer channel pointers will not change
2795               during the life of the bridge.
2796            2. But, in transfers, the channel names will change.
2797               between the time the bridge is started, and the
2798               time the channel ends. 
2799               Usually, when a channel changes names, it will
2800               also change CDR pointers.
2801            3. Usually, only one of the two channels (chan or peer)
2802               will change names.
2803            4. Usually, if a channel changes names during a bridge,
2804               it is because of a transfer. Usually, in these situations,
2805               it is normal to see 2 bridges running simultaneously, and
2806               it is not unusual to see the two channels that change
2807               swapped between bridges.
2808            5. After a bridge occurs, we have 2 or 3 channels' CDRs
2809               to attend to; if the chan or peer changed names,
2810               we have the before and after attached CDR's.
2811         */
2812         
2813         if (new_chan_cdr) {
2814                 struct ast_channel *chan_ptr = NULL;
2815  
2816                 if (strcasecmp(orig_channame, chan->name) != 0) { 
2817                         /* old channel */
2818                         chan_ptr = ast_get_channel_by_name_locked(orig_channame);
2819                         if (chan_ptr) {
2820                                 if (!ast_bridged_channel(chan_ptr)) {
2821                                         struct ast_cdr *cur;
2822                                         for (cur = chan_ptr->cdr; cur; cur = cur->next) {
2823                                                 if (cur == chan_cdr) {
2824                                                         break;
2825                                                 }
2826                                         }
2827                                         if (cur)
2828                                                 ast_cdr_specialized_reset(chan_cdr,0);
2829                                 }
2830                                 ast_channel_unlock(chan_ptr);
2831                         }
2832                         /* new channel */
2833                         ast_cdr_specialized_reset(new_chan_cdr,0);
2834                 } else {
2835                         ast_cdr_specialized_reset(chan_cdr,0); /* nothing changed, reset the chan_cdr  */
2836                 }
2837         }
2838         
2839         {
2840                 struct ast_channel *chan_ptr = NULL;
2841                 new_peer_cdr = pick_unlocked_cdr(peer->cdr); /* the proper chan cdr, if there are forked cdrs */
2842                 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))
2843                         ast_set_flag(new_peer_cdr, AST_CDR_FLAG_POST_DISABLED); /* DISABLED is viral-- it will propagate across a bridge */
2844                 if (strcasecmp(orig_peername, peer->name) != 0) { 
2845                         /* old channel */
2846                         chan_ptr = ast_get_channel_by_name_locked(orig_peername);
2847                         if (chan_ptr) {
2848                                 if (!ast_bridged_channel(chan_ptr)) {
2849                                         struct ast_cdr *cur;
2850                                         for (cur = chan_ptr->cdr; cur; cur = cur->next) {
2851                                                 if (cur == peer_cdr) {
2852                                                         break;
2853                                                 }
2854                                         }
2855                                         if (cur)
2856                                                 ast_cdr_specialized_reset(peer_cdr,0);
2857                                 }
2858                                 ast_channel_unlock(chan_ptr);
2859                         }
2860                         /* new channel */
2861                         ast_cdr_specialized_reset(new_peer_cdr,0);
2862                 } else {
2863                         ast_cdr_specialized_reset(peer_cdr,0); /* nothing changed, reset the peer_cdr  */
2864                 }
2865         }
2866         
2867         return res;
2868 }
2869
2870 /*! \brief Output parking event to manager */
2871 static void post_manager_event(const char *s, struct parkeduser *pu)
2872 {
2873         manager_event(EVENT_FLAG_CALL, s,
2874                 "Exten: %s\r\n"
2875                 "Channel: %s\r\n"
2876                 "Parkinglot: %s\r\n"
2877                 "CallerIDNum: %s\r\n"
2878                 "CallerIDName: %s\r\n"
2879                 "UniqueID: %s\r\n\r\n",
2880                 pu->parkingexten, 
2881                 pu->chan->name,
2882                 pu->parkinglot->name,
2883                 S_OR(pu->chan->cid.cid_num, "<unknown>"),
2884                 S_OR(pu->chan->cid.cid_name, "<unknown>"),
2885                 pu->chan->uniqueid
2886                 );
2887 }
2888
2889 static char *callback_dialoptions(struct ast_flags *features_callee, struct ast_flags *features_caller, char *options, size_t len)
2890 {
2891         int i = 0;
2892         enum {
2893                 OPT_CALLEE_REDIRECT   = 't',
2894                 OPT_CALLER_REDIRECT   = 'T',
2895                 OPT_CALLEE_AUTOMON    = 'w',
2896                 OPT_CALLER_AUTOMON    = 'W',
2897                 OPT_CALLEE_DISCONNECT = 'h',
2898                 OPT_CALLER_DISCONNECT = 'H',
2899                 OPT_CALLEE_PARKCALL   = 'k',
2900                 OPT_CALLER_PARKCALL   = 'K',
2901         };
2902
2903         memset(options, 0, len);
2904         if (ast_test_flag(features_caller, AST_FEATURE_REDIRECT) && i < len) {
2905                 options[i++] = OPT_CALLER_REDIRECT;
2906         }
2907         if (ast_test_flag(features_caller, AST_FEATURE_AUTOMON) && i < len) {
2908                 options[i++] = OPT_CALLER_AUTOMON;
2909         }
2910         if (ast_test_flag(features_caller, AST_FEATURE_DISCONNECT) && i < len) {
2911                 options[i++] = OPT_CALLER_DISCONNECT;
2912         }
2913         if (ast_test_flag(features_caller, AST_FEATURE_PARKCALL) && i < len) {
2914                 options[i++] = OPT_CALLER_PARKCALL;
2915         }
2916
2917         if (ast_test_flag(features_callee, AST_FEATURE_REDIRECT) && i < len) {
2918                 options[i++] = OPT_CALLEE_REDIRECT;
2919         }
2920         if (ast_test_flag(features_callee, AST_FEATURE_AUTOMON) && i < len) {
2921                 options[i++] = OPT_CALLEE_AUTOMON;
2922         }
2923         if (ast_test_flag(features_callee, AST_FEATURE_DISCONNECT) && i < len) {
2924                 options[i++] = OPT_CALLEE_DISCONNECT;
2925         }
2926         if (ast_test_flag(features_callee, AST_FEATURE_PARKCALL) && i < len) {
2927                 options[i++] = OPT_CALLEE_PARKCALL;
2928         }
2929
2930         return options;
2931 }
2932
2933 /*! \brief Run management on parkinglots, called once per parkinglot */
2934 int manage_parkinglot(struct ast_parkinglot *curlot, fd_set *rfds, fd_set *efds, fd_set *nrfds, fd_set *nefds, int *ms, int *max)
2935 {
2936
2937         struct parkeduser *pu;
2938         int res = 0;
2939         char parkingslot[AST_MAX_EXTENSION];
2940
2941         /* Lock parking list */
2942         AST_LIST_LOCK(&curlot->parkings);
2943         AST_LIST_TRAVERSE_SAFE_BEGIN(&curlot->parkings, pu, list) {
2944                 struct ast_channel *chan = pu->chan;    /* shorthand */
2945                 int tms;        /* timeout for this item */
2946                 int x;          /* fd index in channel */
2947                 struct ast_context *con;
2948
2949                 if (pu->notquiteyet) { /* Pretend this one isn't here yet */
2950                         continue;
2951                 }
2952                 tms = ast_tvdiff_ms(ast_tvnow(), pu->start);
2953                 if (tms > pu->parkingtime) {
2954                         /* Stop music on hold */
2955                         ast_indicate(pu->chan, AST_CONTROL_UNHOLD);
2956                         /* Get chan, exten from derived kludge */
2957                         if (pu->peername[0]) {
2958                                 char *peername = ast_strdupa(pu->peername);
2959                                 char *cp = strrchr(peername, '-');
2960                                 char peername_flat[AST_MAX_EXTENSION]; /* using something like DAHDI/52 for an extension name is NOT a good idea */
2961                                 int i;
2962
2963                                 if (cp) 
2964                                         *cp = 0;
2965                                 ast_copy_string(peername_flat,peername,sizeof(peername_flat));
2966                                 for(i=0; peername_flat[i] && i < AST_MAX_EXTENSION; i++) {
2967                                         if (peername_flat[i] == '/') 
2968                                                 peername_flat[i]= '0';
2969                                 }
2970                                 con = ast_context_find_or_create(NULL, NULL, pu->parkinglot->parking_con_dial, registrar);
2971                                 if (!con) {
2972                                         ast_log(LOG_ERROR, "Parking dial context '%s' does not exist and unable to create\n", pu->parkinglot->parking_con_dial);
2973                                 }
2974                                 if (con) {
2975                                         char returnexten[AST_MAX_EXTENSION];
2976                                         struct ast_datastore *features_datastore;
2977                                         struct ast_dial_features *dialfeatures = NULL;
2978
2979                                         ast_channel_lock(chan);
2980
2981                                         if ((features_datastore = ast_channel_datastore_find(chan, &dial_features_info, NULL)))
2982                                                 dialfeatures = features_datastore->data;
2983
2984                                         ast_channel_unlock(chan);
2985
2986                                         if (!strncmp(peername, "Parked/", 7)) {
2987                                                 peername += 7;
2988                                         }
2989
2990                                         if (dialfeatures) {
2991                                                 char buf[MAX_DIAL_FEATURE_OPTIONS] = {0,};
2992                                                 snprintf(returnexten, sizeof(returnexten), "%s|30|%s", peername, callback_dialoptions(&(dialfeatures->features_callee), &(dialfeatures->features_caller), buf, sizeof(buf)));
2993                                         } else { /* Existing default */
2994                                                 ast_log(LOG_WARNING, "Dialfeatures not found on %s, using default!\n", chan->name);
2995                                                 snprintf(returnexten, sizeof(returnexten), "%s|30|t", peername);
2996                                         }
2997
2998                                         ast_add_extension2(con, 1, peername_flat, 1, NULL, NULL, "Dial", ast_strdup(returnexten), ast_free_ptr, registrar);
2999                                 }
3000                                 if (comebacktoorigin) {
3001                                         set_c_e_p(chan, pu->parkinglot->parking_con_dial, peername_flat, 1);
3002                                 } else {
3003                                         ast_log(LOG_WARNING, "now going to parkedcallstimeout,s,1 | ps is %d\n",pu->parkingnum);
3004                                         snprintf(parkingslot, sizeof(parkingslot), "%d", pu->parkingnum);
3005                                         pbx_builtin_setvar_helper(chan, "PARKINGSLOT", parkingslot);
3006                                         set_c_e_p(chan, "parkedcallstimeout", peername_flat, 1);