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