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