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