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