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