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