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