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