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