- Doxygen and some formatting fixes in res_features
[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/monitor.h"
60
61 #ifdef __AST_DEBUG_MALLOC
62 static void FREE(void *ptr)
63 {
64         free(ptr);
65 }
66 #else
67 #define FREE free
68 #endif
69
70 #define DEFAULT_PARK_TIME 45000
71 #define DEFAULT_TRANSFER_DIGIT_TIMEOUT 3000
72 #define DEFAULT_FEATURE_DIGIT_TIMEOUT 500
73 #define DEFAULT_NOANSWER_TIMEOUT_ATTENDED_TRANSFER 15000
74
75 #define AST_MAX_WATCHERS 256
76
77 static char *parkedcall = "ParkedCall";
78
79 static int parkingtime = DEFAULT_PARK_TIME;                /*!< No more than 45 seconds parked before you do something with them */
80 static char parking_con[AST_MAX_EXTENSION];                /*!< Context for which parking is made accessible */
81 static char parking_con_dial[AST_MAX_EXTENSION];           /*!< Context for dialback for parking (KLUDGE) */
82 static char parking_ext[AST_MAX_EXTENSION];                /*!< Extension you type to park the call */
83 static char pickup_ext[AST_MAX_EXTENSION];                 /*!< Call pickup extension */
84 static int parking_start;                                  /*!< First available extension for parking */
85 static int parking_stop;                                   /*!< Last available extension for parking */
86
87 static char courtesytone[256];                             /*!< Courtesy tone */
88 static int parkedplay = 0;                                 /*!< Who to play the courtesy tone to */
89 static char xfersound[256];                                /*!< Call transfer sound */
90 static char xferfailsound[256];                            /*!< Call transfer failure sound */
91
92 static int parking_offset;
93 static int parkfindnext;
94
95 static int adsipark;
96
97 static int transferdigittimeout;
98 static int featuredigittimeout;
99
100 static int atxfernoanswertimeout;
101
102 static char *registrar = "res_features";                   /*!< Registrar for operations */
103
104 /* module and CLI command definitions */
105 static char *synopsis = "Answer a parked call";
106
107 static char *descrip = "ParkedCall(exten):"
108 "Used to connect to a parked call.  This application is always\n"
109 "registered internally and does not need to be explicitly added\n"
110 "into the dialplan, although you should include the 'parkedcalls'\n"
111 "context.\n";
112
113 static char *parkcall = "Park";
114
115 static char *synopsis2 = "Park yourself";
116
117 static char *descrip2 = "Park():"
118 "Used to park yourself (typically in combination with a supervised\n"
119 "transfer to know the parking space). This application is always\n"
120 "registered internally and does not need to be explicitly added\n"
121 "into the dialplan, although you should include the 'parkedcalls'\n"
122 "context.\n";
123
124 static struct ast_app *monitor_app = NULL;
125 static int monitor_ok = 1;
126
127 struct parkeduser {
128         struct ast_channel *chan;                   /*!< Parking channel */
129         struct timeval start;                       /*!< Time the parking started */
130         int parkingnum;                             /*!< Parking lot */
131         char context[AST_MAX_CONTEXT];              /*!< Where to go if our parking time expires */
132         char exten[AST_MAX_EXTENSION];
133         int priority;
134         int parkingtime;                            /*!< Maximum length in parking lot before return */
135         int notquiteyet;
136         char peername[1024];
137         unsigned char moh_trys;
138         struct parkeduser *next;
139 };
140
141 static struct parkeduser *parkinglot;
142
143 AST_MUTEX_DEFINE_STATIC(parking_lock);  /*!< protects all static variables above */
144
145 static pthread_t parking_thread;
146
147 char *ast_parking_ext(void)
148 {
149         return parking_ext;
150 }
151
152 char *ast_pickup_ext(void)
153 {
154         return pickup_ext;
155 }
156
157 struct ast_bridge_thread_obj 
158 {
159         struct ast_bridge_config bconfig;
160         struct ast_channel *chan;
161         struct ast_channel *peer;
162 };
163
164 /*! \brief store context, priority and extension */
165 static void set_c_e_p(struct ast_channel *chan, const char *context, const char *ext, int pri)
166 {
167         ast_copy_string(chan->context, context, sizeof(chan->context));
168         ast_copy_string(chan->exten, ext, sizeof(chan->exten));
169         chan->priority = pri;
170 }
171
172 static void check_goto_on_transfer(struct ast_channel *chan) 
173 {
174         struct ast_channel *xferchan;
175         const char *val = pbx_builtin_getvar_helper(chan, "GOTO_ON_BLINDXFR");
176         char *x, *goto_on_transfer;
177         struct ast_frame *f;
178
179         if (ast_strlen_zero(val))
180                 return;
181
182         goto_on_transfer = ast_strdupa(val);
183
184         if (!(xferchan = ast_channel_alloc(0)))
185                 return;
186
187         for (x = goto_on_transfer; x && *x; x++) {
188                 if (*x == '^')
189                         *x = '|';
190         }
191         ast_string_field_set(xferchan, name, chan->name);
192         /* Make formats okay */
193         xferchan->readformat = chan->readformat;
194         xferchan->writeformat = chan->writeformat;
195         ast_channel_masquerade(xferchan, chan);
196         ast_parseable_goto(xferchan, goto_on_transfer);
197         xferchan->_state = AST_STATE_UP;
198         ast_clear_flag(xferchan, AST_FLAGS_ALL);        
199         xferchan->_softhangup = 0;
200         if ((f = ast_read(xferchan))) {
201                 ast_frfree(f);
202                 f = NULL;
203                 ast_pbx_start(xferchan);
204         } else {
205                 ast_hangup(xferchan);
206         }
207 }
208
209 static struct ast_channel *ast_feature_request_and_dial(struct ast_channel *caller, const char *type, int format, void *data, int timeout, int *outstate, const char *cid_num, const char *cid_name);
210
211
212 static void *ast_bridge_call_thread(void *data) 
213 {
214         struct ast_bridge_thread_obj *tobj = data;
215
216         tobj->chan->appl = "Transferred Call";
217         tobj->chan->data = tobj->peer->name;
218         tobj->peer->appl = "Transferred Call";
219         tobj->peer->data = tobj->chan->name;
220         if (tobj->chan->cdr) {
221                 ast_cdr_reset(tobj->chan->cdr, NULL);
222                 ast_cdr_setdestchan(tobj->chan->cdr, tobj->peer->name);
223         }
224         if (tobj->peer->cdr) {
225                 ast_cdr_reset(tobj->peer->cdr, NULL);
226                 ast_cdr_setdestchan(tobj->peer->cdr, tobj->chan->name);
227         }
228
229         ast_bridge_call(tobj->peer, tobj->chan, &tobj->bconfig);
230         ast_hangup(tobj->chan);
231         ast_hangup(tobj->peer);
232         bzero(tobj, sizeof(*tobj)); /*! \todo XXX for safety */
233         free(tobj);
234         return NULL;
235 }
236
237 static void ast_bridge_call_thread_launch(void *data) 
238 {
239         pthread_t thread;
240         pthread_attr_t attr;
241         struct sched_param sched;
242
243         pthread_attr_init(&attr);
244         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
245         ast_pthread_create(&thread, &attr,ast_bridge_call_thread, data);
246         pthread_attr_destroy(&attr);
247         memset(&sched, 0, sizeof(sched));
248         pthread_setschedparam(thread, SCHED_RR, &sched);
249 }
250
251 static int adsi_announce_park(struct ast_channel *chan, int parkingnum)
252 {
253         int res;
254         int justify[5] = {ADSI_JUST_CENT, ADSI_JUST_CENT, ADSI_JUST_CENT, ADSI_JUST_CENT};
255         char tmp[256];
256         char *message[5] = {NULL, NULL, NULL, NULL, NULL};
257
258         snprintf(tmp, sizeof(tmp), "Parked on %d", parkingnum);
259         message[0] = tmp;
260         res = adsi_load_session(chan, NULL, 0, 1);
261         if (res == -1)
262                 return res;
263         return adsi_print(chan, message, justify, 1);
264 }
265
266 /*! \brief Park a call 
267         \note We put the user in the parking list, then wake up the parking thread to be sure it looks
268         after these channels too */
269 int ast_park_call(struct ast_channel *chan, struct ast_channel *peer, int timeout, int *extout)
270 {
271         struct parkeduser *pu, *cur;
272         int i,x,parking_range;
273         char exten[AST_MAX_EXTENSION];
274         struct ast_context *con;
275         
276         if (!(pu = ast_calloc(1, sizeof(*pu)))) 
277                 return -1;
278
279         ast_mutex_lock(&parking_lock);
280         parking_range = parking_stop - parking_start+1;
281         for (i = 0; i < parking_range; i++) {
282                 x = (i + parking_offset) % parking_range + parking_start;
283                 cur = parkinglot;
284                 while(cur) {
285                         if (cur->parkingnum == x) 
286                                 break;
287                         cur = cur->next;
288                 }
289                 if (!cur)
290                         break;
291         }
292
293         if (!(i < parking_range)) {
294                 ast_log(LOG_WARNING, "No more parking spaces\n");
295                 free(pu);
296                 ast_mutex_unlock(&parking_lock);
297                 return -1;
298         }
299         if (parkfindnext) 
300                 parking_offset = x - parking_start + 1;
301         chan->appl = "Parked Call";
302         chan->data = NULL; 
303
304         pu->chan = chan;
305         /* Start music on hold */
306         if (chan != peer) {
307                 ast_indicate(pu->chan, AST_CONTROL_HOLD);       /* Indicate to peer that we're on hold */
308                 ast_moh_start(pu->chan, NULL);
309         }
310         pu->start = ast_tvnow();
311         pu->parkingnum = x;
312         pu->parkingtime = (timeout > 0) ? timeout : parkingtime;
313         if (extout)
314                 *extout = x;
315         if (peer) 
316                 ast_copy_string(pu->peername, peer->name, sizeof(pu->peername));
317
318         /* Remember what had been dialed, so that if the parking
319            expires, we try to come back to the same place */
320         ast_copy_string(pu->context, S_OR(chan->macrocontext, chan->context), sizeof(pu->context));
321         ast_copy_string(pu->exten, S_OR(chan->macroexten, chan->exten), sizeof(pu->exten));
322         pu->priority = chan->macropriority ? chan->macropriority : chan->priority;
323         pu->next = parkinglot;
324         parkinglot = pu;
325         /* If parking a channel directly, don't quiet yet get parking running on it */
326         if (peer == chan) 
327                 pu->notquiteyet = 1;
328         ast_mutex_unlock(&parking_lock);
329         /* Wake up the (presumably select()ing) thread */
330         pthread_kill(parking_thread, SIGURG);
331         if (option_verbose > 1) 
332                 ast_verbose(VERBOSE_PREFIX_2 "Parked %s on %d. Will timeout back to extension [%s] %s, %d in %d seconds\n", pu->chan->name, pu->parkingnum, pu->context, pu->exten, pu->priority, (pu->parkingtime/1000));
333
334         manager_event(EVENT_FLAG_CALL, "ParkedCall",
335                 "Exten: %d\r\n"
336                 "Channel: %s\r\n"
337                 "From: %s\r\n"
338                 "Timeout: %ld\r\n"
339                 "CallerID: %s\r\n"
340                 "CallerIDName: %s\r\n",
341                 pu->parkingnum, pu->chan->name, peer ? peer->name : "",
342                 (long)pu->start.tv_sec + (long)(pu->parkingtime/1000) - (long)time(NULL),
343                 S_OR(pu->chan->cid.cid_num, "<unknown>"),
344                 S_OR(pu->chan->cid.cid_name, "<unknown>")
345                 );
346
347         if (peer && adsipark && adsi_available(peer)) {
348                 adsi_announce_park(peer, pu->parkingnum);
349                 adsi_unload_session(peer);
350         }
351
352         con = ast_context_find(parking_con);
353         if (!con) 
354                 con = ast_context_create(NULL, parking_con, registrar);
355         if (!con)       /* Still no context? Bad */
356                 ast_log(LOG_ERROR, "Parking context '%s' does not exist and unable to create\n", parking_con);
357         else {          /* Add extension to context */
358                 snprintf(exten, sizeof(exten), "%d", x);
359                 ast_add_extension2(con, 1, exten, 1, NULL, NULL, parkedcall, strdup(exten), FREE, registrar);
360         }
361         /* Tell the peer channel the number of the parking space */
362         if (peer) 
363                 ast_say_digits(peer, pu->parkingnum, "", peer->language);
364         if (pu->notquiteyet) {
365                 /* Wake up parking thread if we're really done */
366                 ast_moh_start(pu->chan, NULL);
367                 pu->notquiteyet = 0;
368                 pthread_kill(parking_thread, SIGURG);
369         }
370         return 0;
371 }
372
373 int ast_masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, int timeout, int *extout)
374 {
375         struct ast_channel *chan;
376         struct ast_frame *f;
377
378         /* Make a new, fake channel that we'll use to masquerade in the real one */
379         if (!(chan = ast_channel_alloc(0))) {
380                 ast_log(LOG_WARNING, "Unable to create parked channel\n");
381                 return -1;
382         }
383         /* Let us keep track of the channel name */
384         ast_string_field_build(chan, name, "Parked/%s",rchan->name);
385
386         /* Make formats okay */
387         chan->readformat = rchan->readformat;
388         chan->writeformat = rchan->writeformat;
389         ast_channel_masquerade(chan, rchan);
390
391         /* Setup the extensions and such */
392         set_c_e_p(chan, rchan->context, rchan->exten, rchan->priority);
393
394         /* Make the masq execute */
395         f = ast_read(chan);
396         if (f)
397                 ast_frfree(f);
398
399         ast_park_call(chan, peer, timeout, extout);
400         return 0;
401 }
402
403
404 #define FEATURE_RETURN_HANGUP           -1
405 #define FEATURE_RETURN_SUCCESSBREAK      0
406 #define FEATURE_RETURN_PBX_KEEPALIVE    AST_PBX_KEEPALIVE
407 #define FEATURE_RETURN_NO_HANGUP_PEER   AST_PBX_NO_HANGUP_PEER
408 #define FEATURE_RETURN_PASSDIGITS        21
409 #define FEATURE_RETURN_STOREDIGITS       22
410 #define FEATURE_RETURN_SUCCESS           23
411
412 #define FEATURE_SENSE_CHAN      (1 << 0)
413 #define FEATURE_SENSE_PEER      (1 << 1)
414
415 /*
416  * set caller and callee according to the direction
417  */
418 static void set_peers(struct ast_channel **caller, struct ast_channel **callee,
419         struct ast_channel *peer, struct ast_channel *chan, int sense)
420 {
421         if (sense == FEATURE_SENSE_PEER) {
422                 *caller = peer;
423                 *callee = chan;
424         } else {
425                 *callee = peer;
426                 *caller = chan;
427         }
428 }
429
430 static int builtin_parkcall(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense)
431 {
432         struct ast_channel *parker;
433         struct ast_channel *parkee;
434
435         int res=0;
436         struct localuser *u;
437         LOCAL_USER_ADD(u);
438
439         set_peers(&parker, &parkee, peer, chan, sense);
440         /* Setup the exten/priority to be s/1 since we don't know
441            where this call should return */
442         strcpy(chan->exten, "s");
443         chan->priority = 1;
444         if (chan->_state != AST_STATE_UP)
445                 res = ast_answer(chan);
446         if (!res)
447                 res = ast_safe_sleep(chan, 1000);
448         if (!res)
449                 res = ast_park_call(parkee, parker, 0, NULL);
450         LOCAL_USER_REMOVE(u);
451         if (!res) {
452                 if (sense == FEATURE_SENSE_CHAN)
453                         res = AST_PBX_NO_HANGUP_PEER;
454                 else
455                         res = AST_PBX_KEEPALIVE;
456         }
457         return res;
458
459 }
460
461 static int builtin_automonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense)
462 {
463         char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
464         int x = 0;
465         size_t len;
466         struct ast_channel *caller_chan, *callee_chan;
467
468         if (!monitor_ok) {
469                 ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
470                 return -1;
471         }
472
473         if (!monitor_app && !(monitor_app = pbx_findapp("Monitor"))) {
474                 monitor_ok=0;
475                 ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
476                 return -1;
477         }
478
479         set_peers(&caller_chan, &callee_chan, peer, chan, sense);
480
481         if (!ast_strlen_zero(courtesytone)) {
482                 if (ast_autoservice_start(callee_chan))
483                         return -1;
484                 if (ast_stream_and_wait(caller_chan, courtesytone, caller_chan->language, "")) {
485                         ast_log(LOG_WARNING, "Failed to play courtesy tone!\n");
486                         ast_autoservice_stop(callee_chan);
487                         return -1;
488                 }
489                 if (ast_autoservice_stop(callee_chan))
490                         return -1;
491         }
492         
493         if (callee_chan->monitor) {
494                 if (option_verbose > 3)
495                         ast_verbose(VERBOSE_PREFIX_3 "User hit '%s' to stop recording call.\n", code);
496                 ast_monitor_stop(callee_chan, 1);
497                 return FEATURE_RETURN_SUCCESS;
498         }
499
500         if (caller_chan && callee_chan) {
501                 const char *touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_FORMAT");
502                 const char *touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR");
503
504                 if (!touch_format)
505                         touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_FORMAT");
506
507                 if (!touch_monitor)
508                         touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR");
509         
510                 if (touch_monitor) {
511                         len = strlen(touch_monitor) + 50;
512                         args = alloca(len);
513                         touch_filename = alloca(len);
514                         snprintf(touch_filename, len, "auto-%ld-%s", (long)time(NULL), touch_monitor);
515                         snprintf(args, len, "%s|%s|m", (touch_format) ? touch_format : "wav", touch_filename);
516                 } else {
517                         caller_chan_id = ast_strdupa(S_OR(caller_chan->cid.cid_num, caller_chan->name));
518                         callee_chan_id = ast_strdupa(S_OR(callee_chan->cid.cid_num, callee_chan->name));
519                         len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
520                         args = alloca(len);
521                         touch_filename = alloca(len);
522                         snprintf(touch_filename, len, "auto-%ld-%s-%s", (long)time(NULL), caller_chan_id, callee_chan_id);
523                         snprintf(args, len, "%s|%s|m", S_OR(touch_format, "wav"), touch_filename);
524                 }
525
526                 for( x = 0; x < strlen(args); x++) {
527                         if (args[x] == '/')
528                                 args[x] = '-';
529                 }
530                 
531                 if (option_verbose > 3)
532                         ast_verbose(VERBOSE_PREFIX_3 "User hit '%s' to record call. filename: %s\n", code, args);
533
534                 pbx_exec(callee_chan, monitor_app, args);
535                 pbx_builtin_setvar_helper(callee_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
536                 pbx_builtin_setvar_helper(caller_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
537         
538                 return FEATURE_RETURN_SUCCESS;
539         }
540         
541         ast_log(LOG_NOTICE,"Cannot record the call. One or both channels have gone away.\n");   
542         return -1;
543 }
544
545 static int builtin_disconnect(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense)
546 {
547         if (option_verbose > 3)
548                 ast_verbose(VERBOSE_PREFIX_3 "User hit '%s' to disconnect call.\n", code);
549         return FEATURE_RETURN_HANGUP;
550 }
551
552 static int finishup(struct ast_channel *chan)
553 {
554         int res;
555   
556         ast_moh_stop(chan);
557         res = ast_autoservice_stop(chan);
558         ast_indicate(chan, AST_CONTROL_UNHOLD);
559         return res;
560 }
561
562 static const char *real_ctx(struct ast_channel *transferer, struct ast_channel *transferee)
563 {
564         const char *s = pbx_builtin_getvar_helper(transferer, "TRANSFER_CONTEXT");
565         if (ast_strlen_zero(s))
566                 s = pbx_builtin_getvar_helper(transferee, "TRANSFER_CONTEXT");
567         if (ast_strlen_zero(s)) /* Use the non-macro context to transfer the call XXX ? */
568                 s = transferer->macrocontext;
569         if (ast_strlen_zero(s))
570                 s = transferer->context;
571         return s;  
572 }
573
574 static int builtin_blindtransfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense)
575 {
576         struct ast_channel *transferer;
577         struct ast_channel *transferee;
578         const char *transferer_real_context;
579         char xferto[256];
580         int res;
581
582         set_peers(&transferer, &transferee, peer, chan, sense);
583         transferer_real_context = real_ctx(transferer, transferee);
584         /* Start autoservice on chan while we talk to the originator */
585         ast_indicate(transferee, AST_CONTROL_HOLD);
586         ast_autoservice_start(transferee);
587         ast_moh_start(transferee, NULL);
588
589         memset(xferto, 0, sizeof(xferto));
590         
591         /* Transfer */
592         res = ast_stream_and_wait(transferer, "pbx-transfer", transferer->language, AST_DIGIT_ANY);
593         if (res < 0) {
594                 finishup(transferee);
595                 return -1; /* error ? */
596         }
597         if (res > 0)    /* If they've typed a digit already, handle it */
598                 xferto[0] = (char) res;
599
600         ast_stopstream(transferer);
601         res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
602         if (res < 0) {  /* hangup, would be 0 for invalid and 1 for valid */
603                 finishup(transferee);
604                 return res;
605         }
606         if (!strcmp(xferto, ast_parking_ext())) {
607                 res = finishup(transferee);
608                 if (res)
609                         res = -1;
610                 else if (!ast_park_call(transferee, transferer, 0, NULL)) {     /* success */
611                         /* We return non-zero, but tell the PBX not to hang the channel when
612                            the thread dies -- We have to be careful now though.  We are responsible for 
613                            hanging up the channel, else it will never be hung up! */
614
615                         return (transferer == peer) ? AST_PBX_KEEPALIVE : AST_PBX_NO_HANGUP_PEER;
616                 } else {
617                         ast_log(LOG_WARNING, "Unable to park call %s\n", transferee->name);
618                 }
619                 /*! \todo XXX Maybe we should have another message here instead of invalid extension XXX */
620         } else if (ast_exists_extension(transferee, transferer_real_context, xferto, 1, transferer->cid.cid_num)) {
621                 pbx_builtin_setvar_helper(peer, "BLINDTRANSFER", chan->name);
622                 pbx_builtin_setvar_helper(chan, "BLINDTRANSFER", peer->name);
623                 res=finishup(transferee);
624                 if (!transferee->pbx) {
625                         /* Doh!  Use our handy async_goto functions */
626                         if (option_verbose > 2) 
627                                 ast_verbose(VERBOSE_PREFIX_3 "Transferring %s to '%s' (context %s) priority 1\n"
628                                                                 ,transferee->name, xferto, transferer_real_context);
629                         if (ast_async_goto(transferee, transferer_real_context, xferto, 1))
630                                 ast_log(LOG_WARNING, "Async goto failed :-(\n");
631                         res = -1;
632                 } else {
633                         /* Set the channel's new extension, since it exists, using transferer context */
634                         set_c_e_p(transferee, transferer_real_context, xferto, 0);
635                 }
636                 check_goto_on_transfer(transferer);
637                 return res;
638         } else {
639                 if (option_verbose > 2) 
640                         ast_verbose(VERBOSE_PREFIX_3 "Unable to find extension '%s' in context '%s'\n", xferto, transferer_real_context);
641         }
642         if (ast_stream_and_wait(transferer, xferfailsound, transferer->language, AST_DIGIT_ANY) < 0 ) {
643                 finishup(transferee);
644                 return -1;
645         }
646         ast_stopstream(transferer);
647         res = finishup(transferee);
648         if (res) {
649                 if (option_verbose > 1)
650                         ast_verbose(VERBOSE_PREFIX_2 "Hungup during autoservice stop on '%s'\n", transferee->name);
651                 return res;
652         }
653         return FEATURE_RETURN_SUCCESS;
654 }
655
656 static int check_compat(struct ast_channel *c, struct ast_channel *newchan)
657 {
658         if (ast_channel_make_compatible(c, newchan) < 0) {
659                 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n",
660                         c->name, newchan->name);
661                 ast_hangup(newchan);
662                 return -1;
663         }
664         return 0;
665 }
666
667 static int builtin_atxfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense)
668 {
669         struct ast_channel *transferer;
670         struct ast_channel *transferee;
671         const char *transferer_real_context;
672         char xferto[256];
673         int res;
674         int outstate=0;
675         struct ast_channel *newchan;
676         struct ast_channel *xferchan;
677         struct ast_bridge_thread_obj *tobj;
678         struct ast_bridge_config bconfig;
679         struct ast_frame *f;
680         int l;
681
682         if (option_debug)
683                 ast_log(LOG_DEBUG, "Executing Attended Transfer %s, %s (sense=%d) \n", chan->name, peer->name, sense);
684         set_peers(&transferer, &transferee, peer, chan, sense);
685         transferer_real_context = real_ctx(transferer, transferee);
686         /* Start autoservice on chan while we talk to the originator */
687         ast_indicate(transferee, AST_CONTROL_HOLD);
688         ast_autoservice_start(transferee);
689         ast_moh_start(transferee, NULL);
690         memset(xferto, 0, sizeof(xferto));
691         /* Transfer */
692         res = ast_stream_and_wait(transferer, "pbx-transfer", transferer->language, AST_DIGIT_ANY);
693         if (res < 0) {
694                 finishup(transferee);
695                 return res;
696         }
697         if (res > 0) /* If they've typed a digit already, handle it */
698                 xferto[0] = (char) res;
699
700         /* this is specific of atxfer */
701         res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
702         if (res < 0) {  /* hangup, would be 0 for invalid and 1 for valid */
703                 finishup(transferee);
704                 return res;
705         }
706         if (res == 0) {
707                 ast_log(LOG_WARNING, "Did not read data.\n");
708                 finishup(transferee);
709                 if (ast_stream_and_wait(transferer, "beeperr", transferer->language, ""))
710                         return -1;
711                 return FEATURE_RETURN_SUCCESS;
712         }
713
714         /* valid extension, res == 1 */
715         if (!ast_exists_extension(transferer, transferer_real_context, xferto, 1, transferer->cid.cid_num)) {
716                 ast_log(LOG_WARNING, "Extension %s does not exist in context %s\n",xferto,transferer_real_context);
717                 finishup(transferee);
718                 if (ast_stream_and_wait(transferer, "beeperr", transferer->language, ""))
719                         return -1;
720                 return FEATURE_RETURN_SUCCESS;
721         }
722
723         l = strlen(xferto);
724         snprintf(xferto + l, sizeof(xferto) - l, "@%s/n", transferer_real_context);     /* append context */
725         newchan = ast_feature_request_and_dial(transferer, "Local", ast_best_codec(transferer->nativeformats),
726                 xferto, atxfernoanswertimeout, &outstate, transferer->cid.cid_num, transferer->cid.cid_name);
727         ast_indicate(transferer, -1);
728         if (!newchan) {
729                 finishup(transferee);
730                 /* any reason besides user requested cancel and busy triggers the failed sound */
731                 if (outstate != AST_CONTROL_UNHOLD && outstate != AST_CONTROL_BUSY &&
732                                 ast_stream_and_wait(transferer, xferfailsound, transferer->language, ""))
733                         return -1;
734                 return FEATURE_RETURN_SUCCESS;
735         }
736
737         if (check_compat(transferer, newchan))
738                 return -1;
739         memset(&bconfig,0,sizeof(struct ast_bridge_config));
740         ast_set_flag(&(bconfig.features_caller), AST_FEATURE_DISCONNECT);
741         ast_set_flag(&(bconfig.features_callee), AST_FEATURE_DISCONNECT);
742         res = ast_bridge_call(transferer, newchan, &bconfig);
743         if (newchan->_softhangup || newchan->_state != AST_STATE_UP || !transferer->_softhangup) {
744                 ast_hangup(newchan);
745                 if (ast_stream_and_wait(transferer, xfersound, transferer->language, ""))
746                         ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
747                 finishup(transferee);
748                 transferer->_softhangup = 0;
749                 return FEATURE_RETURN_SUCCESS;
750         }
751         
752         if (check_compat(transferee, newchan))
753                 return -1;
754
755         ast_moh_stop(transferee);
756         
757         if ((ast_autoservice_stop(transferee) < 0)
758            || (ast_waitfordigit(transferee, 100) < 0)
759            || (ast_waitfordigit(newchan, 100) < 0) 
760            || ast_check_hangup(transferee) 
761            || ast_check_hangup(newchan)) {
762                 ast_hangup(newchan);
763                 return -1;
764         }
765
766         xferchan = ast_channel_alloc(0);
767         if (!xferchan) {
768                 ast_hangup(newchan);
769                 return -1;
770         }
771         ast_string_field_build(xferchan, name, "Transfered/%s", transferee->name);
772         /* Make formats okay */
773         xferchan->readformat = transferee->readformat;
774         xferchan->writeformat = transferee->writeformat;
775         ast_channel_masquerade(xferchan, transferee);
776         ast_explicit_goto(xferchan, transferee->context, transferee->exten, transferee->priority);
777         xferchan->_state = AST_STATE_UP;
778         ast_clear_flag(xferchan, AST_FLAGS_ALL);        
779         xferchan->_softhangup = 0;
780
781         if ((f = ast_read(xferchan)))
782                 ast_frfree(f);
783
784         newchan->_state = AST_STATE_UP;
785         ast_clear_flag(newchan, AST_FLAGS_ALL); 
786         newchan->_softhangup = 0;
787
788         tobj = ast_calloc(1, sizeof(struct ast_bridge_thread_obj));
789         if (!tobj) {
790                 ast_hangup(xferchan);
791                 ast_hangup(newchan);
792                 return -1;
793         }
794         tobj->chan = xferchan;
795         tobj->peer = newchan;
796         tobj->bconfig = *config;
797
798         if (ast_stream_and_wait(newchan, xfersound, newchan->language, ""))
799                 ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
800         ast_bridge_call_thread_launch(tobj);
801         return -1;      /* XXX meaning the channel is bridged ? */
802 }
803
804
805 /* add atxfer and automon as undefined so you can only use em if you configure them */
806 #define FEATURES_COUNT (sizeof(builtin_features) / sizeof(builtin_features[0]))
807
808 struct ast_call_feature builtin_features[] = 
809  {
810         { AST_FEATURE_REDIRECT, "Blind Transfer", "blindxfer", "#", "#", builtin_blindtransfer, AST_FEATURE_FLAG_NEEDSDTMF },
811         { AST_FEATURE_REDIRECT, "Attended Transfer", "atxfer", "", "", builtin_atxfer, AST_FEATURE_FLAG_NEEDSDTMF },
812         { AST_FEATURE_AUTOMON, "One Touch Monitor", "automon", "", "", builtin_automonitor, AST_FEATURE_FLAG_NEEDSDTMF },
813         { AST_FEATURE_DISCONNECT, "Disconnect Call", "disconnect", "*", "*", builtin_disconnect, AST_FEATURE_FLAG_NEEDSDTMF },
814         { AST_FEATURE_PARKCALL, "Park Call", "parkcall", "", "", builtin_parkcall, AST_FEATURE_FLAG_NEEDSDTMF },
815 };
816
817
818 static AST_LIST_HEAD_STATIC(feature_list,ast_call_feature);
819
820 /*! \brief register new feature into feature_list*/
821 void ast_register_feature(struct ast_call_feature *feature)
822 {
823         if (!feature) {
824                 ast_log(LOG_NOTICE,"You didn't pass a feature!\n");
825                 return;
826         }
827   
828         AST_LIST_LOCK(&feature_list);
829         AST_LIST_INSERT_HEAD(&feature_list,feature,feature_entry);
830         AST_LIST_UNLOCK(&feature_list);
831
832         if (option_verbose >= 2) 
833                 ast_verbose(VERBOSE_PREFIX_2 "Registered Feature '%s'\n",feature->sname);
834 }
835
836 /*! \brief unregister feature from feature_list */
837 void ast_unregister_feature(struct ast_call_feature *feature)
838 {
839         if (!feature)
840                 return;
841
842         AST_LIST_LOCK(&feature_list);
843         AST_LIST_REMOVE(&feature_list,feature,feature_entry);
844         AST_LIST_UNLOCK(&feature_list);
845         free(feature);
846 }
847
848 static void ast_unregister_features(void)
849 {
850         struct ast_call_feature *feature;
851
852         AST_LIST_LOCK(&feature_list);
853         while ((feature = AST_LIST_REMOVE_HEAD(&feature_list,feature_entry)))
854                 free(feature);
855         AST_LIST_UNLOCK(&feature_list);
856 }
857
858 /*! \brief find a feature by name */
859 static struct ast_call_feature *find_feature(char *name)
860 {
861         struct ast_call_feature *tmp;
862
863         AST_LIST_LOCK(&feature_list);
864         AST_LIST_TRAVERSE(&feature_list, tmp, feature_entry) {
865                 if (!strcasecmp(tmp->sname, name))
866                         break;
867         }
868         AST_LIST_UNLOCK(&feature_list);
869
870         return tmp;
871 }
872
873 /*! \brief exec an app by feature */
874 static int feature_exec_app(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense)
875 {
876         struct ast_app *app;
877         struct ast_call_feature *feature;
878         int res;
879
880         AST_LIST_LOCK(&feature_list);
881         AST_LIST_TRAVERSE(&feature_list,feature,feature_entry) {
882                 if (!strcasecmp(feature->exten,code))
883                         break;
884         }
885         AST_LIST_UNLOCK(&feature_list);
886
887         if (!feature) { /* shouldn't ever happen! */
888                 ast_log(LOG_NOTICE, "Found feature before, but at execing we've lost it??\n");
889                 return -1; 
890         }
891         
892         app = pbx_findapp(feature->app);
893         if (app) {
894                 struct ast_channel *work = ast_test_flag(feature,AST_FEATURE_FLAG_CALLEE) ? peer : chan;
895                 res = pbx_exec(work, app, feature->app_args);
896                 if (res == AST_PBX_KEEPALIVE)
897                         return FEATURE_RETURN_PBX_KEEPALIVE;
898                 else if (res == AST_PBX_NO_HANGUP_PEER)
899                         return FEATURE_RETURN_NO_HANGUP_PEER;
900                 else if (res)
901                         return FEATURE_RETURN_SUCCESSBREAK;
902         } else {
903                 ast_log(LOG_WARNING, "Could not find application (%s)\n", feature->app);
904                 return -2;
905         }
906         
907         return FEATURE_RETURN_SUCCESS;  /*! \todo XXX should probably return res */
908 }
909
910 static void unmap_features(void)
911 {
912         int x;
913         for (x = 0; x < FEATURES_COUNT; x++)
914                 strcpy(builtin_features[x].exten, builtin_features[x].default_exten);
915 }
916
917 static int remap_feature(const char *name, const char *value)
918 {
919         int x;
920         int res = -1;
921         for (x = 0; x < FEATURES_COUNT; x++) {
922                 if (!strcasecmp(name, builtin_features[x].sname)) {
923                         ast_copy_string(builtin_features[x].exten, value, sizeof(builtin_features[x].exten));
924                         if (option_verbose > 1)
925                                 ast_verbose(VERBOSE_PREFIX_2 "Remapping feature %s (%s) to sequence '%s'\n", builtin_features[x].fname, builtin_features[x].sname, builtin_features[x].exten);
926                         res = 0;
927                 } else if (!strcmp(value, builtin_features[x].exten)) 
928                         ast_log(LOG_WARNING, "Sequence '%s' already mapped to function %s (%s) while assigning to %s\n", value, builtin_features[x].fname, builtin_features[x].sname, name);
929         }
930         return res;
931 }
932
933 static int ast_feature_interpret(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense)
934 {
935         int x;
936         struct ast_flags features;
937         int res = FEATURE_RETURN_PASSDIGITS;
938         struct ast_call_feature *feature;
939         const char *dynamic_features=pbx_builtin_getvar_helper(chan,"DYNAMIC_FEATURES");
940
941         if (sense == FEATURE_SENSE_CHAN)
942                 ast_copy_flags(&features, &(config->features_caller), AST_FLAGS_ALL);   
943         else
944                 ast_copy_flags(&features, &(config->features_callee), AST_FLAGS_ALL);   
945         if (option_debug > 2)
946                 ast_log(LOG_DEBUG, "Feature interpret: chan=%s, peer=%s, sense=%d, features=%d\n", chan->name, peer->name, sense, features.flags);
947
948         for (x=0; x < FEATURES_COUNT; x++) {
949                 if ((ast_test_flag(&features, builtin_features[x].feature_mask)) &&
950                     !ast_strlen_zero(builtin_features[x].exten)) {
951                         /* Feature is up for consideration */
952                         if (!strcmp(builtin_features[x].exten, code)) {
953                                 res = builtin_features[x].operation(chan, peer, config, code, sense);
954                                 break;
955                         } else if (!strncmp(builtin_features[x].exten, code, strlen(code))) {
956                                 if (res == FEATURE_RETURN_PASSDIGITS)
957                                         res = FEATURE_RETURN_STOREDIGITS;
958                         }
959                 }
960         }
961
962
963         if (!ast_strlen_zero(dynamic_features)) {
964                 char *tmp = ast_strdupa(dynamic_features);
965                 char *tok;
966
967                 while ((tok = strsep(&tmp, "#")) != NULL) {
968                         feature = find_feature(tok);
969                         
970                         if (feature) {
971                                 /* Feature is up for consideration */
972                                 if (!strcmp(feature->exten, code)) {
973                                         if (option_verbose > 2)
974                                                 ast_verbose(VERBOSE_PREFIX_3 " Feature Found: %s exten: %s\n",feature->sname, tok);
975                                         if (sense == FEATURE_SENSE_CHAN)
976                                                 res = feature->operation(chan, peer, config, code, sense);
977                                         else
978                                                 res = feature->operation(peer, chan, config, code, sense);
979                                         break;
980                                 } else if (!strncmp(feature->exten, code, strlen(code))) {
981                                         res = FEATURE_RETURN_STOREDIGITS;
982                                 }
983                         }
984                 }
985         }
986         
987         return res;
988 }
989
990 static void set_config_flags(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config)
991 {
992         int x;
993         
994         ast_clear_flag(config, AST_FLAGS_ALL);  
995         for (x = 0; x < FEATURES_COUNT; x++) {
996                 if (ast_test_flag(builtin_features + x, AST_FEATURE_FLAG_NEEDSDTMF)) {
997                         if (ast_test_flag(&(config->features_caller), builtin_features[x].feature_mask))
998                                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
999
1000                         if (ast_test_flag(&(config->features_callee), builtin_features[x].feature_mask))
1001                                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
1002                 }
1003         }
1004         
1005         if (chan && peer && !(ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_0) && ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_1))) {
1006                 const char *dynamic_features = pbx_builtin_getvar_helper(chan, "DYNAMIC_FEATURES");
1007
1008                 if (dynamic_features) {
1009                         char *tmp = ast_strdupa(dynamic_features);
1010                         char *tok;
1011                         struct ast_call_feature *feature;
1012
1013                         /* while we have a feature */
1014                         while ((tok = strsep(&tmp, "#"))) {
1015                                 if ((feature = find_feature(tok)) && ast_test_flag(feature, AST_FEATURE_FLAG_NEEDSDTMF)) {
1016                                         if (ast_test_flag(feature, AST_FEATURE_FLAG_CALLER))
1017                                                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
1018                                         if (ast_test_flag(feature, AST_FEATURE_FLAG_CALLEE))
1019                                                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
1020                                 }
1021                         }
1022                 }
1023         }
1024 }
1025
1026 /*! \todo XXX Check - this is very similar to the code in channel.c */
1027 static struct ast_channel *ast_feature_request_and_dial(struct ast_channel *caller, const char *type, int format, void *data, int timeout, int *outstate, const char *cid_num, const char *cid_name)
1028 {
1029         int state = 0;
1030         int cause = 0;
1031         int to;
1032         struct ast_channel *chan;
1033         struct ast_channel *monitor_chans[2];
1034         struct ast_channel *active_channel;
1035         int res = 0, ready = 0;
1036         
1037         if ((chan = ast_request(type, format, data, &cause))) {
1038                 ast_set_callerid(chan, cid_num, cid_name, cid_num);
1039                 ast_channel_inherit_variables(caller, chan);    
1040                 pbx_builtin_setvar_helper(chan, "TRANSFERERNAME", caller->name);
1041                 if (!ast_call(chan, data, timeout)) {
1042                         struct timeval started;
1043                         int x, len = 0;
1044                         char *disconnect_code = NULL, *dialed_code = NULL;
1045
1046                         ast_indicate(caller, AST_CONTROL_RINGING);
1047                         /* support dialing of the featuremap disconnect code while performing an attended tranfer */
1048                         for (x=0; x < FEATURES_COUNT; x++) {
1049                                 if (strcasecmp(builtin_features[x].sname, "disconnect"))
1050                                         continue;
1051
1052                                 disconnect_code = builtin_features[x].exten;
1053                                 len = strlen(disconnect_code) + 1;
1054                                 dialed_code = alloca(len);
1055                                 memset(dialed_code, 0, len);
1056                                 break;
1057                         }
1058                         x = 0;
1059                         started = ast_tvnow();
1060                         to = timeout;
1061                         while (!ast_check_hangup(caller) && timeout && (chan->_state != AST_STATE_UP)) {
1062                                 struct ast_frame *f = NULL;
1063
1064                                 monitor_chans[0] = caller;
1065                                 monitor_chans[1] = chan;
1066                                 active_channel = ast_waitfor_n(monitor_chans, 2, &to);
1067
1068                                 /* see if the timeout has been violated */
1069                                 if(ast_tvdiff_ms(ast_tvnow(), started) > timeout) {
1070                                         state = AST_CONTROL_UNHOLD;
1071                                         ast_log(LOG_NOTICE, "We exceeded our AT-timeout\n");
1072                                         break; /*doh! timeout*/
1073                                 }
1074
1075                                 if (!active_channel)
1076                                         continue;
1077
1078                                 if (chan && (chan == active_channel)){
1079                                         f = ast_read(chan);
1080                                         if (f == NULL) { /*doh! where'd he go?*/
1081                                                 state = AST_CONTROL_HANGUP;
1082                                                 res = 0;
1083                                                 break;
1084                                         }
1085                                         
1086                                         if (f->frametype == AST_FRAME_CONTROL || f->frametype == AST_FRAME_DTMF || f->frametype == AST_FRAME_TEXT) {
1087                                                 if (f->subclass == AST_CONTROL_RINGING) {
1088                                                         state = f->subclass;
1089                                                         if (option_verbose > 2)
1090                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is ringing\n", chan->name);
1091                                                         ast_indicate(caller, AST_CONTROL_RINGING);
1092                                                 } else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
1093                                                         state = f->subclass;
1094                                                         if (option_verbose > 2)
1095                                                                 ast_verbose( VERBOSE_PREFIX_3 "%s is busy\n", chan->name);
1096                                                         ast_indicate(caller, AST_CONTROL_BUSY);
1097                                                         ast_frfree(f);
1098                                                         f = NULL;
1099                                                         break;
1100                                                 } else if (f->subclass == AST_CONTROL_ANSWER) {
1101                                                         /* This is what we are hoping for */
1102                                                         state = f->subclass;
1103                                                         ast_frfree(f);
1104                                                         f = NULL;
1105                                                         ready=1;
1106                                                         break;
1107                                                 } else {
1108                                                         ast_log(LOG_NOTICE, "Don't know what to do about control frame: %d\n", f->subclass);
1109                                                 }
1110                                                 /* else who cares */
1111                                         }
1112
1113                                 } else if (caller && (active_channel == caller)) {
1114                                         f = ast_read(caller);
1115                                         if (f == NULL) { /*doh! where'd he go?*/
1116                                                 if (caller->_softhangup && !chan->_softhangup) {
1117                                                         /* make this a blind transfer */
1118                                                         ready = 1;
1119                                                         break;
1120                                                 }
1121                                                 state = AST_CONTROL_HANGUP;
1122                                                 res = 0;
1123                                                 break;
1124                                         }
1125                                         
1126                                         if (f->frametype == AST_FRAME_DTMF) {
1127                                                 dialed_code[x++] = f->subclass;
1128                                                 dialed_code[x] = '\0';
1129                                                 if (strlen(dialed_code) == len) {
1130                                                         x = 0;
1131                                                 } else if (x && strncmp(dialed_code, disconnect_code, x)) {
1132                                                         x = 0;
1133                                                         dialed_code[x] = '\0';
1134                                                 }
1135                                                 if (*dialed_code && !strcmp(dialed_code, disconnect_code)) {
1136                                                         /* Caller Canceled the call */
1137                                                         state = AST_CONTROL_UNHOLD;
1138                                                         ast_frfree(f);
1139                                                         f = NULL;
1140                                                         break;
1141                                                 }
1142                                         }
1143                                 }
1144                                 if (f)
1145                                         ast_frfree(f);
1146                         } /* end while */
1147                 } else
1148                         ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
1149         } else {
1150                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1151                 switch(cause) {
1152                 case AST_CAUSE_BUSY:
1153                         state = AST_CONTROL_BUSY;
1154                         break;
1155                 case AST_CAUSE_CONGESTION:
1156                         state = AST_CONTROL_CONGESTION;
1157                         break;
1158                 }
1159         }
1160         
1161         ast_indicate(caller, -1);
1162         if (chan && ready) {
1163                 if (chan->_state == AST_STATE_UP) 
1164                         state = AST_CONTROL_ANSWER;
1165                 res = 0;
1166         } else if(chan) {
1167                 res = -1;
1168                 ast_hangup(chan);
1169                 chan = NULL;
1170         } else {
1171                 res = -1;
1172         }
1173         
1174         if (outstate)
1175                 *outstate = state;
1176
1177         if (chan && res <= 0) {
1178                 if (chan->cdr || (chan->cdr = ast_cdr_alloc())) {
1179                         char tmp[256];
1180                         ast_cdr_init(chan->cdr, chan);
1181                         snprintf(tmp, 256, "%s/%s", type, (char *)data);
1182                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
1183                         ast_cdr_update(chan);
1184                         ast_cdr_start(chan->cdr);
1185                         ast_cdr_end(chan->cdr);
1186                         /* If the cause wasn't handled properly */
1187                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
1188                                 ast_cdr_failed(chan->cdr);
1189                 } else {
1190                         ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
1191                 }
1192         }
1193         
1194         return chan;
1195 }
1196
1197 int ast_bridge_call(struct ast_channel *chan,struct ast_channel *peer,struct ast_bridge_config *config)
1198 {
1199         /* Copy voice back and forth between the two channels.  Give the peer
1200            the ability to transfer calls with '#<extension' syntax. */
1201         struct ast_frame *f;
1202         struct ast_channel *who;
1203         char chan_featurecode[FEATURE_MAX_LEN + 1]="";
1204         char peer_featurecode[FEATURE_MAX_LEN + 1]="";
1205         int res;
1206         int diff;
1207         int hasfeatures=0;
1208         int hadfeatures=0;
1209         struct ast_option_header *aoh;
1210         struct timeval start = { 0 , 0 };
1211         struct ast_bridge_config backup_config;
1212
1213         memset(&backup_config, 0, sizeof(backup_config));
1214
1215         config->start_time = ast_tvnow();
1216
1217         if (chan && peer) {
1218                 pbx_builtin_setvar_helper(chan, "BRIDGEPEER", peer->name);
1219                 pbx_builtin_setvar_helper(peer, "BRIDGEPEER", chan->name);
1220         } else if (chan)
1221                 pbx_builtin_setvar_helper(chan, "BLINDTRANSFER", NULL);
1222
1223         if (monitor_ok) {
1224                 const char *monitor_exec;
1225                 struct ast_channel *src = NULL;
1226                 if (!monitor_app) { 
1227                         if (!(monitor_app = pbx_findapp("Monitor")))
1228                                 monitor_ok=0;
1229                 }
1230                 if ((monitor_exec = pbx_builtin_getvar_helper(chan, "AUTO_MONITOR"))) 
1231                         src = chan;
1232                 else if ((monitor_exec = pbx_builtin_getvar_helper(peer, "AUTO_MONITOR")))
1233                         src = peer;
1234                 if (monitor_app && src) {
1235                         char *tmp = ast_strdupa(monitor_exec);
1236                         pbx_exec(src, monitor_app, tmp);
1237                 }
1238         }
1239         
1240         set_config_flags(chan, peer, config);
1241         config->firstpass = 1;
1242
1243         /* Answer if need be */
1244         if (ast_answer(chan))
1245                 return -1;
1246         peer->appl = "Bridged Call";
1247         peer->data = chan->name;
1248
1249         /* copy the userfield from the B-leg to A-leg if applicable */
1250         if (chan->cdr && peer->cdr && !ast_strlen_zero(peer->cdr->userfield)) {
1251                 char tmp[256];
1252                 if (!ast_strlen_zero(chan->cdr->userfield)) {
1253                         snprintf(tmp, sizeof(tmp), "%s;%s", chan->cdr->userfield, peer->cdr->userfield);
1254                         ast_cdr_appenduserfield(chan, tmp);
1255                 } else
1256                         ast_cdr_setuserfield(chan, peer->cdr->userfield);
1257                 /* free the peer's cdr without ast_cdr_free complaining */
1258                 free(peer->cdr);
1259                 peer->cdr = NULL;
1260         }
1261         for (;;) {
1262                 struct ast_channel *other;      /* used later */
1263                 if (config->feature_timer)
1264                         start = ast_tvnow();
1265
1266                 res = ast_channel_bridge(chan, peer, config, &f, &who);
1267
1268                 if (config->feature_timer) {
1269                         /* Update time limit for next pass */
1270                         diff = ast_tvdiff_ms(ast_tvnow(), start);
1271                         config->feature_timer -= diff;
1272                         if (hasfeatures) {
1273                                 /* Running on backup config, meaning a feature might be being
1274                                    activated, but that's no excuse to keep things going 
1275                                    indefinitely! */
1276                                 if (backup_config.feature_timer && ((backup_config.feature_timer -= diff) <= 0)) {
1277                                         if (option_debug)
1278                                                 ast_log(LOG_DEBUG, "Timed out, realtime this time!\n");
1279                                         config->feature_timer = 0;
1280                                         who = chan;
1281                                         if (f)
1282                                                 ast_frfree(f);
1283                                         f = NULL;
1284                                         res = 0;
1285                                 } else if (config->feature_timer <= 0) {
1286                                         /* Not *really* out of time, just out of time for
1287                                            digits to come in for features. */
1288                                         if (option_debug)
1289                                                 ast_log(LOG_DEBUG, "Timed out for feature!\n");
1290                                         if (!ast_strlen_zero(peer_featurecode)) {
1291                                                 ast_dtmf_stream(chan, peer, peer_featurecode, 0);
1292                                                 memset(peer_featurecode, 0, sizeof(peer_featurecode));
1293                                         }
1294                                         if (!ast_strlen_zero(chan_featurecode)) {
1295                                                 ast_dtmf_stream(peer, chan, chan_featurecode, 0);
1296                                                 memset(chan_featurecode, 0, sizeof(chan_featurecode));
1297                                         }
1298                                         if (f)
1299                                                 ast_frfree(f);
1300                                         hasfeatures = !ast_strlen_zero(chan_featurecode) || !ast_strlen_zero(peer_featurecode);
1301                                         if (!hasfeatures) {
1302                                                 /* Restore original (possibly time modified) bridge config */
1303                                                 memcpy(config, &backup_config, sizeof(struct ast_bridge_config));
1304                                                 memset(&backup_config, 0, sizeof(backup_config));
1305                                         }
1306                                         hadfeatures = hasfeatures;
1307                                         /* Continue as we were */
1308                                         continue;
1309                                 }
1310                         } else {
1311                                 if (config->feature_timer <=0) {
1312                                         /* We ran out of time */
1313                                         config->feature_timer = 0;
1314                                         who = chan;
1315                                         if (f)
1316                                                 ast_frfree(f);
1317                                         f = NULL;
1318                                         res = 0;
1319                                 }
1320                         }
1321                 }
1322                 if (res < 0) {
1323                         ast_log(LOG_WARNING, "Bridge failed on channels %s and %s\n", chan->name, peer->name);
1324                         return -1;
1325                 }
1326                 
1327                 if (!f || (f->frametype == AST_FRAME_CONTROL &&
1328                                 (f->subclass == AST_CONTROL_HANGUP || f->subclass == AST_CONTROL_BUSY || 
1329                                         f->subclass == AST_CONTROL_CONGESTION ) ) ) {
1330                         res = -1;
1331                         break;
1332                 }
1333                 /* many things should be sent to the 'other' channel */
1334                 other = (who == chan) ? peer : chan;
1335                 if (f->frametype == AST_FRAME_CONTROL) {
1336                         if (f->subclass == AST_CONTROL_RINGING)
1337                                 ast_indicate(other, AST_CONTROL_RINGING);
1338                         else if (f->subclass == -1)
1339                                 ast_indicate(other, -1);
1340                         else if (f->subclass == AST_CONTROL_FLASH)
1341                                 ast_indicate(other, AST_CONTROL_FLASH);
1342                         else if (f->subclass == AST_CONTROL_OPTION) {
1343                                 aoh = f->data;
1344                                 /* Forward option Requests */
1345                                 if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST)
1346                                         ast_channel_setoption(other, ntohs(aoh->option), aoh->data, f->datalen - sizeof(struct ast_option_header), 0);
1347                         }
1348                 }
1349                 /* check for '*', if we find it it's time to disconnect */
1350                 if (f->frametype == AST_FRAME_DTMF) {
1351                         char *featurecode;
1352                         int sense;
1353
1354                         hadfeatures = hasfeatures;
1355                         /* This cannot overrun because the longest feature is one shorter than our buffer */
1356                         if (who == chan) {
1357                                 sense = FEATURE_SENSE_CHAN;
1358                                 featurecode = chan_featurecode;
1359                         } else  {
1360                                 sense = FEATURE_SENSE_PEER;
1361                                 featurecode = peer_featurecode;
1362                         }
1363                         /*! append the event to featurecode. we rely on the string being zero-filled, and
1364                          * not overflowing it. 
1365                          * \todo XXX how do we guarantee the latter ?
1366                          */
1367                         featurecode[strlen(featurecode)] = f->subclass;
1368                         /* Get rid of the frame before we start doing "stuff" with the channels */
1369                         ast_frfree(f);
1370                         f = NULL;
1371                         config->feature_timer = backup_config.feature_timer;
1372                         res = ast_feature_interpret(chan, peer, config, featurecode, sense);
1373                         switch(res) {
1374                         case FEATURE_RETURN_PASSDIGITS:
1375                                 ast_dtmf_stream(other, who, featurecode, 0);
1376                                 /* Fall through */
1377                         case FEATURE_RETURN_SUCCESS:
1378                                 memset(featurecode, 0, sizeof(chan_featurecode));
1379                                 break;
1380                         }
1381                         if (res >= FEATURE_RETURN_PASSDIGITS) {
1382                                 res = 0;
1383                         } else 
1384                                 break;
1385                         hasfeatures = !ast_strlen_zero(chan_featurecode) || !ast_strlen_zero(peer_featurecode);
1386                         if (hadfeatures && !hasfeatures) {
1387                                 /* Restore backup */
1388                                 memcpy(config, &backup_config, sizeof(struct ast_bridge_config));
1389                                 memset(&backup_config, 0, sizeof(struct ast_bridge_config));
1390                         } else if (hasfeatures) {
1391                                 if (!hadfeatures) {
1392                                         /* Backup configuration */
1393                                         memcpy(&backup_config, config, sizeof(struct ast_bridge_config));
1394                                         /* Setup temporary config options */
1395                                         config->play_warning = 0;
1396                                         ast_clear_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING);
1397                                         ast_clear_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING);
1398                                         config->warning_freq = 0;
1399                                         config->warning_sound = NULL;
1400                                         config->end_sound = NULL;
1401                                         config->start_sound = NULL;
1402                                         config->firstpass = 0;
1403                                 }
1404                                 config->feature_timer = featuredigittimeout;
1405                                 if (option_debug)
1406                                         ast_log(LOG_DEBUG, "Set time limit to %ld\n", config->feature_timer);
1407                         }
1408                 }
1409                 if (f)
1410                         ast_frfree(f);
1411         }
1412         return res;
1413 }
1414
1415 static void post_manager_event(const char *s, int num, struct ast_channel *chan)
1416 {
1417         manager_event(EVENT_FLAG_CALL, s,
1418                 "Exten: %d\r\n"
1419                 "Channel: %s\r\n"
1420                 "CallerID: %s\r\n"
1421                 "CallerIDName: %s\r\n\r\n",
1422                 num, chan->name,
1423                 S_OR(chan->cid.cid_num, "<unknown>"),
1424                 S_OR(chan->cid.cid_name, "<unknown>")
1425                 );
1426 }
1427
1428 /*! \brief Take care of parked calls and unpark them if needed */
1429 static void *do_parking_thread(void *ignore)
1430 {
1431         fd_set rfds, efds;      /* results from previous select, to be preserved across loops. */
1432         FD_ZERO(&rfds);
1433         FD_ZERO(&efds);
1434
1435         for (;;) {
1436                 struct parkeduser *pu, *pl, *pt = NULL;
1437                 int ms = -1;    /* select timeout, uninitialized */
1438                 int max = -1;   /* max fd, none there yet */
1439                 fd_set nrfds, nefds;    /* args for the next select */
1440                 FD_ZERO(&nrfds);
1441                 FD_ZERO(&nefds);
1442
1443                 ast_mutex_lock(&parking_lock);
1444                 pl = NULL;
1445                 pu = parkinglot;
1446                 /* navigate the list with prev-cur pointers to support removals */
1447                 while(pu) {
1448                         struct ast_channel *chan = pu->chan;    /* shorthand */
1449                         int tms;        /* timeout for this item */
1450                         int x;          /* fd index in channel */
1451                         struct ast_context *con;
1452
1453                         if (pu->notquiteyet) { /* Pretend this one isn't here yet */
1454                                 pl = pu;
1455                                 pu = pu->next;
1456                                 continue;
1457                         }
1458                         tms = ast_tvdiff_ms(ast_tvnow(), pu->start);
1459                         if (tms > pu->parkingtime) {
1460                                 /* Stop music on hold */
1461                                 ast_moh_stop(chan);
1462                                 ast_indicate(chan, AST_CONTROL_UNHOLD);
1463                                 /* Get chan, exten from derived kludge */
1464                                 if (pu->peername[0]) {
1465                                         char *peername = ast_strdupa(pu->peername);
1466                                         char *cp = strrchr(peername, '-');
1467                                         if (cp) 
1468                                                 *cp = 0;
1469                                         con = ast_context_find(parking_con_dial);
1470                                         if (!con) {
1471                                                 con = ast_context_create(NULL, parking_con_dial, registrar);
1472                                                 if (!con) {
1473                                                         ast_log(LOG_ERROR, "Parking dial context '%s' does not exist and unable to create\n", parking_con_dial);
1474                                                 }
1475                                         }
1476                                         if (con) {
1477                                                 char returnexten[AST_MAX_EXTENSION];
1478                                                 snprintf(returnexten, sizeof(returnexten), "%s||t", peername);
1479                                                 ast_add_extension2(con, 1, peername, 1, NULL, NULL, "Dial", strdup(returnexten), FREE, registrar);
1480                                         }
1481                                         set_c_e_p(chan, parking_con_dial, peername, 1);
1482                                 } else {
1483                                         /* They've been waiting too long, send them back to where they came.  Theoretically they
1484                                            should have their original extensions and such, but we copy to be on the safe side */
1485                                         set_c_e_p(chan, pu->context, pu->exten, pu->priority);
1486                                 }
1487
1488                                 post_manager_event("ParkedCallTimeOut", pu->parkingnum, chan);
1489
1490                                 if (option_verbose > 1) 
1491                                         ast_verbose(VERBOSE_PREFIX_2 "Timeout for %s parked on %d. Returning to %s,%s,%d\n", chan->name, pu->parkingnum, chan->context, chan->exten, chan->priority);
1492                                 /* Start up the PBX, or hang them up */
1493                                 if (ast_pbx_start(chan))  {
1494                                         ast_log(LOG_WARNING, "Unable to restart the PBX for user on '%s', hanging them up...\n", chan->name);
1495                                         ast_hangup(chan);
1496                                 }
1497                                 /* And take them out of the parking lot */
1498                                 if (pl) 
1499                                         pl->next = pu->next;
1500                                 else
1501                                         parkinglot = pu->next;
1502                                 pt = pu;
1503                                 pu = pu->next;
1504                                 con = ast_context_find(parking_con);
1505                                 if (con) {
1506                                         char exten[AST_MAX_EXTENSION];
1507                                         snprintf(exten, sizeof(exten), "%d", pt->parkingnum);
1508                                         if (ast_context_remove_extension2(con, exten, 1, NULL))
1509                                                 ast_log(LOG_WARNING, "Whoa, failed to remove the extension!\n");
1510                                 } else
1511                                         ast_log(LOG_WARNING, "Whoa, no parking context?\n");
1512                                 free(pt);
1513                         } else {        /* still within parking time, process descriptors */
1514                                 for (x = 0; x < AST_MAX_FDS; x++) {
1515                                         struct ast_frame *f;
1516
1517                                         if (chan->fds[x] == -1 || (!FD_ISSET(chan->fds[x], &rfds) && !FD_ISSET(chan->fds[x], &efds)))
1518                                                 continue;       /* nothing on this descriptor */
1519
1520                                         if (FD_ISSET(chan->fds[x], &efds))
1521                                                 ast_set_flag(chan, AST_FLAG_EXCEPTION);
1522                                         else
1523                                                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1524                                         chan->fdno = x;
1525                                         /* See if they need servicing */
1526                                         f = ast_read(chan);
1527                                         if (!f || (f->frametype == AST_FRAME_CONTROL && f->subclass ==  AST_CONTROL_HANGUP)) {
1528                                                 if (f)
1529                                                         ast_frfree(f);
1530                                                 post_manager_event("ParkedCallGiveUp", pu->parkingnum, chan);
1531
1532                                                 /* There's a problem, hang them up*/
1533                                                 if (option_verbose > 1) 
1534                                                         ast_verbose(VERBOSE_PREFIX_2 "%s got tired of being parked\n", chan->name);
1535                                                 ast_hangup(chan);
1536                                                 /* And take them out of the parking lot */
1537                                                 if (pl) 
1538                                                         pl->next = pu->next;
1539                                                 else
1540                                                         parkinglot = pu->next;
1541                                                 pt = pu;
1542                                                 pu = pu->next;
1543                                                 con = ast_context_find(parking_con);
1544                                                 if (con) {
1545                                                         char exten[AST_MAX_EXTENSION];
1546                                                         snprintf(exten, sizeof(exten), "%d", pt->parkingnum);
1547                                                         if (ast_context_remove_extension2(con, exten, 1, NULL))
1548                                                                 ast_log(LOG_WARNING, "Whoa, failed to remove the extension!\n");
1549                                                 } else
1550                                                         ast_log(LOG_WARNING, "Whoa, no parking context?\n");
1551                                                 free(pt);
1552                                                 break;
1553                                         } else {
1554                                                 /*! \todo XXX Maybe we could do something with packets, like dial "0" for operator or something XXX */
1555                                                 ast_frfree(f);
1556                                                 if (pu->moh_trys < 3 && !chan->generatordata) {
1557                                                         if (option_debug)
1558                                                                 ast_log(LOG_DEBUG, "MOH on parked call stopped by outside source.  Restarting.\n");
1559                                                         ast_moh_start(chan, NULL);
1560                                                         pu->moh_trys++;
1561                                                 }
1562                                                 goto std;       /*! \todo XXX Ick: jumping into an else statement??? XXX */
1563                                         }
1564
1565                                 } /* end for */
1566                                 if (x >= AST_MAX_FDS) {
1567 std:                                    for (x=0; x<AST_MAX_FDS; x++) { /* mark fds for next round */
1568                                                 if (chan->fds[x] > -1) {
1569                                                         FD_SET(chan->fds[x], &nrfds);
1570                                                         FD_SET(chan->fds[x], &nefds);
1571                                                         if (chan->fds[x] > max)
1572                                                                 max = chan->fds[x];
1573                                                 }
1574                                         }
1575                                         /* Keep track of our shortest wait */
1576                                         if (tms < ms || ms < 0)
1577                                                 ms = tms;
1578                                         pl = pu;
1579                                         pu = pu->next;
1580                                 }
1581                         }
1582                 } /* end while */
1583                 ast_mutex_unlock(&parking_lock);
1584                 rfds = nrfds;
1585                 efds = nefds;
1586                 {
1587                         struct timeval tv = ast_samp2tv(ms, 1000);
1588                         /* Wait for something to happen */
1589                         ast_select(max + 1, &rfds, NULL, &efds, (ms > -1) ? &tv : NULL);
1590                 }
1591                 pthread_testcancel();
1592         }
1593         return NULL;    /* Never reached */
1594 }
1595
1596 static int park_call_exec(struct ast_channel *chan, void *data)
1597 {
1598         /* Data is unused at the moment but could contain a parking
1599            lot context eventually */
1600         int res=0;
1601         struct localuser *u;
1602         LOCAL_USER_ADD(u);
1603         /* Setup the exten/priority to be s/1 since we don't know
1604            where this call should return */
1605         strcpy(chan->exten, "s");
1606         chan->priority = 1;
1607         if (chan->_state != AST_STATE_UP)
1608                 res = ast_answer(chan);
1609         if (!res)
1610                 res = ast_safe_sleep(chan, 1000);
1611         if (!res)
1612                 res = ast_park_call(chan, chan, 0, NULL);
1613         LOCAL_USER_REMOVE(u);
1614         if (!res)
1615                 res = AST_PBX_KEEPALIVE;
1616         return res;
1617 }
1618
1619 static int park_exec(struct ast_channel *chan, void *data)
1620 {
1621         int res=0;
1622         struct localuser *u;
1623         struct ast_channel *peer=NULL;
1624         struct parkeduser *pu, *pl=NULL;
1625         struct ast_context *con;
1626         int park;
1627         struct ast_bridge_config config;
1628
1629         if (!data) {
1630                 ast_log(LOG_WARNING, "Park requires an argument (extension number)\n");
1631                 return -1;
1632         }
1633         LOCAL_USER_ADD(u);
1634         park = atoi((char *)data);
1635         ast_mutex_lock(&parking_lock);
1636         pu = parkinglot;
1637         while(pu) {
1638                 if (pu->parkingnum == park) {
1639                         if (pl)
1640                                 pl->next = pu->next;
1641                         else
1642                                 parkinglot = pu->next;
1643                         break;
1644                 }
1645                 pl = pu;
1646                 pu = pu->next;
1647         }
1648         ast_mutex_unlock(&parking_lock);
1649         if (pu) {
1650                 peer = pu->chan;
1651                 con = ast_context_find(parking_con);
1652                 if (con) {
1653                         char exten[AST_MAX_EXTENSION];
1654                         snprintf(exten, sizeof(exten), "%d", pu->parkingnum);
1655                         if (ast_context_remove_extension2(con, exten, 1, NULL))
1656                                 ast_log(LOG_WARNING, "Whoa, failed to remove the extension!\n");
1657                 } else
1658                         ast_log(LOG_WARNING, "Whoa, no parking context?\n");
1659
1660                 manager_event(EVENT_FLAG_CALL, "UnParkedCall",
1661                         "Exten: %d\r\n"
1662                         "Channel: %s\r\n"
1663                         "From: %s\r\n"
1664                         "CallerID: %s\r\n"
1665                         "CallerIDName: %s\r\n",
1666                         pu->parkingnum, pu->chan->name, chan->name,
1667                         S_OR(pu->chan->cid.cid_num, "<unknown>"),
1668                         S_OR(pu->chan->cid.cid_name, "<unknown>")
1669                         );
1670
1671                 free(pu);
1672         }
1673         /* JK02: it helps to answer the channel if not already up */
1674         if (chan->_state != AST_STATE_UP)
1675                 ast_answer(chan);
1676
1677         if (peer) {
1678                 /* Play a courtesy to the source(s) configured to prefix the bridge connecting */
1679                 
1680                 if (!ast_strlen_zero(courtesytone)) {
1681                         int error = 0;
1682                         ast_moh_stop(peer);
1683                         ast_indicate(peer, AST_CONTROL_UNHOLD);
1684                         if (parkedplay == 0) {
1685                                 error = ast_stream_and_wait(chan, courtesytone, chan->language, "");
1686                         } else if (parkedplay == 1) {
1687                                 error = ast_stream_and_wait(peer, courtesytone, chan->language, "");
1688                         } else if (parkedplay == 2) {
1689                                 if (!ast_streamfile(chan, courtesytone, chan->language) &&
1690                                                 !ast_streamfile(peer, courtesytone, chan->language)) {
1691                                         /*! \todo XXX we would like to wait on both! */
1692                                         res = ast_waitstream(chan, "");
1693                                         if (res >= 0)
1694                                                 res = ast_waitstream(peer, "");
1695                                         if (res < 0)
1696                                                 error = 1;
1697                                 }
1698                         }
1699                         if (error) {
1700                                 ast_log(LOG_WARNING, "Failed to play courtesy tone!\n");
1701                                 ast_hangup(peer);
1702                                 return -1;
1703                         }
1704                 } else {
1705                         ast_moh_stop(peer);
1706                         ast_indicate(peer, AST_CONTROL_UNHOLD); 
1707                 }
1708
1709                 res = ast_channel_make_compatible(chan, peer);
1710                 if (res < 0) {
1711                         ast_log(LOG_WARNING, "Could not make channels %s and %s compatible for bridge\n", chan->name, peer->name);
1712                         ast_hangup(peer);
1713                         return -1;
1714                 }
1715                 /* This runs sorta backwards, since we give the incoming channel control, as if it
1716                    were the person called. */
1717                 if (option_verbose > 2) 
1718                         ast_verbose(VERBOSE_PREFIX_3 "Channel %s connected to parked call %d\n", chan->name, park);
1719
1720                 memset(&config, 0, sizeof(struct ast_bridge_config));
1721                 ast_set_flag(&(config.features_callee), AST_FEATURE_REDIRECT);
1722                 ast_set_flag(&(config.features_caller), AST_FEATURE_REDIRECT);
1723                 config.timelimit = 0;
1724                 config.play_warning = 0;
1725                 config.warning_freq = 0;
1726                 config.warning_sound=NULL;
1727                 res = ast_bridge_call(chan, peer, &config);
1728
1729                 /* Simulate the PBX hanging up */
1730                 if (res != AST_PBX_NO_HANGUP_PEER)
1731                         ast_hangup(peer);
1732                 return res;
1733         } else {
1734                 /*! \todo XXX Play a message XXX */
1735                 if (ast_stream_and_wait(chan, "pbx-invalidpark", chan->language, ""))
1736                         ast_log(LOG_WARNING, "ast_streamfile of %s failed on %s\n", "pbx-invalidpark", chan->name);
1737                 if (option_verbose > 2) 
1738                         ast_verbose(VERBOSE_PREFIX_3 "Channel %s tried to talk to nonexistent parked call %d\n", chan->name, park);
1739                 res = -1;
1740         }
1741         LOCAL_USER_REMOVE(u);
1742         return res;
1743 }
1744
1745 static int handle_showfeatures(int fd, int argc, char *argv[])
1746 {
1747         int i;
1748         int fcount;
1749         struct ast_call_feature *feature;
1750         char format[] = "%-25s %-7s %-7s\n";
1751
1752         ast_cli(fd, format, "Builtin Feature", "Default", "Current");
1753         ast_cli(fd, format, "---------------", "-------", "-------");
1754
1755         ast_cli(fd, format, "Pickup", "*8", ast_pickup_ext());          /* default hardcoded above, so we'll hardcode it here */
1756
1757         fcount = sizeof(builtin_features) / sizeof(builtin_features[0]);
1758
1759         for (i = 0; i < fcount; i++)
1760         {
1761                 ast_cli(fd, format, builtin_features[i].fname, builtin_features[i].default_exten, builtin_features[i].exten);
1762         }
1763         ast_cli(fd, "\n");
1764         ast_cli(fd, format, "Dynamic Feature", "Default", "Current");
1765         ast_cli(fd, format, "---------------", "-------", "-------");
1766         if (AST_LIST_EMPTY(&feature_list)) {
1767                 ast_cli(fd, "(none)\n");
1768         }
1769         else {
1770                 AST_LIST_LOCK(&feature_list);
1771                 AST_LIST_TRAVERSE(&feature_list, feature, feature_entry) {
1772                         ast_cli(fd, format, feature->sname, "no def", feature->exten);  
1773                 }
1774                 AST_LIST_UNLOCK(&feature_list);
1775         }
1776         ast_cli(fd, "\nCall parking\n");
1777         ast_cli(fd, "------------\n");
1778         ast_cli(fd,"%-20s:      %s\n", "Parking extension", parking_ext);
1779         ast_cli(fd,"%-20s:      %s\n", "Parking context", parking_con);
1780         ast_cli(fd,"%-20s:      %d-%d\n", "Parked call extensions", parking_start, parking_stop);
1781         ast_cli(fd,"\n");
1782         
1783         return RESULT_SUCCESS;
1784 }
1785
1786 static char showfeatures_help[] =
1787 "Usage: show features\n"
1788 "       Lists currently configured features.\n";
1789
1790 static struct ast_cli_entry showfeatures =
1791 { { "show", "features", NULL }, handle_showfeatures, "Lists configured features", showfeatures_help };
1792
1793 static int handle_parkedcalls(int fd, int argc, char *argv[])
1794 {
1795         struct parkeduser *cur;
1796         int numparked = 0;
1797
1798         ast_cli(fd, "%4s %25s (%-15s %-12s %-4s) %-6s \n", "Num", "Channel"
1799                 , "Context", "Extension", "Pri", "Timeout");
1800
1801         ast_mutex_lock(&parking_lock);
1802
1803         for (cur = parkinglot; cur; cur = cur->next) {
1804                 ast_cli(fd, "%4d %25s (%-15s %-12s %-4d) %6lds\n"
1805                         ,cur->parkingnum, cur->chan->name, cur->context, cur->exten
1806                         ,cur->priority, cur->start.tv_sec + (cur->parkingtime/1000) - time(NULL));
1807
1808                 numparked++;
1809         }
1810         ast_mutex_unlock(&parking_lock);
1811         ast_cli(fd, "%d parked call%s.\n", numparked, (numparked != 1) ? "s" : "");
1812
1813
1814         return RESULT_SUCCESS;
1815 }
1816
1817 static char showparked_help[] =
1818 "Usage: show parkedcalls\n"
1819 "       Lists currently parked calls.\n";
1820
1821 static struct ast_cli_entry showparked =
1822 { { "show", "parkedcalls", NULL }, handle_parkedcalls, "Lists parked calls", showparked_help };
1823
1824 /*! \brief Dump lot status */
1825 static int manager_parking_status( struct mansession *s, struct message *m )
1826 {
1827         struct parkeduser *cur;
1828         char *id = astman_get_header(m,"ActionID");
1829         char idText[256] = "";
1830
1831         if (!ast_strlen_zero(id))
1832                 snprintf(idText,256,"ActionID: %s\r\n",id);
1833
1834         astman_send_ack(s, m, "Parked calls will follow");
1835
1836         ast_mutex_lock(&parking_lock);
1837
1838         for (cur=parkinglot; cur; cur = cur->next) {
1839                 astman_append(s, "Event: ParkedCall\r\n"
1840                         "Exten: %d\r\n"
1841                         "Channel: %s\r\n"
1842                         "From: %s\r\n"
1843                         "Timeout: %ld\r\n"
1844                         "CallerID: %s\r\n"
1845                         "CallerIDName: %s\r\n"
1846                         "%s"
1847                         "\r\n",
1848                         cur->parkingnum, cur->chan->name, cur->peername,
1849                         (long)cur->start.tv_sec + (long)(cur->parkingtime/1000) - (long)time(NULL),
1850                         S_OR(cur->chan->cid.cid_num, ""),       /* XXX in other places it is <unknown> */
1851                         S_OR(cur->chan->cid.cid_name, ""),
1852                         idText);
1853         }
1854
1855         astman_append(s,
1856                 "Event: ParkedCallsComplete\r\n"
1857                 "%s"
1858                 "\r\n",idText);
1859
1860         ast_mutex_unlock(&parking_lock);
1861
1862         return RESULT_SUCCESS;
1863 }
1864
1865 static char mandescr_park[] =
1866 "Description: Park a channel.\n"
1867 "Variables: (Names marked with * are required)\n"
1868 "       *Channel: Channel name to park\n"
1869 "       *Channel2: Channel to announce park info to (and return to if timeout)\n"
1870 "       Timeout: Number of milliseconds to wait before callback.\n";  
1871
1872 static int manager_park(struct mansession *s, struct message *m)
1873 {
1874         char *channel = astman_get_header(m, "Channel");
1875         char *channel2 = astman_get_header(m, "Channel2");
1876         char *timeout = astman_get_header(m, "Timeout");
1877         char buf[BUFSIZ];
1878         int to = 0;
1879         int res = 0;
1880         int parkExt = 0;
1881         struct ast_channel *ch1, *ch2;
1882
1883         if (ast_strlen_zero(channel)) {
1884                 astman_send_error(s, m, "Channel not specified");
1885                 return 0;
1886         }
1887
1888         if (ast_strlen_zero(channel2)) {
1889                 astman_send_error(s, m, "Channel2 not specified");
1890                 return 0;
1891         }
1892
1893         ch1 = ast_get_channel_by_name_locked(channel);
1894         if (!ch1) {
1895                 snprintf(buf, sizeof(buf), "Channel does not exist: %s", channel);
1896                 astman_send_error(s, m, buf);
1897                 return 0;
1898         }
1899
1900         ch2 = ast_get_channel_by_name_locked(channel2);
1901         if (!ch2) {
1902                 snprintf(buf, sizeof(buf), "Channel does not exist: %s", channel2);
1903                 astman_send_error(s, m, buf);
1904                 ast_channel_unlock(ch1);
1905                 return 0;
1906         }
1907
1908         if (!ast_strlen_zero(timeout)) {
1909                 sscanf(timeout, "%d", &to);
1910         }
1911
1912         res = ast_masq_park_call(ch1, ch2, to, &parkExt);
1913         if (!res) {
1914                 ast_softhangup(ch2, AST_SOFTHANGUP_EXPLICIT);
1915                 astman_send_ack(s, m, "Park successful");
1916         } else {
1917                 astman_send_error(s, m, "Park failure");
1918         }
1919
1920         ast_channel_unlock(ch1);
1921         ast_channel_unlock(ch2);
1922
1923         return 0;
1924 }
1925
1926
1927 int ast_pickup_call(struct ast_channel *chan)
1928 {
1929         struct ast_channel *cur = NULL;
1930         int res = -1;
1931
1932         while ( (cur = ast_channel_walk_locked(cur)) != NULL) {
1933                 if (!cur->pbx && 
1934                         (cur != chan) &&
1935                         (chan->pickupgroup & cur->callgroup) &&
1936                         ((cur->_state == AST_STATE_RINGING) ||
1937                          (cur->_state == AST_STATE_RING))) {
1938                                 break;
1939                 }
1940                 ast_channel_unlock(cur);
1941         }
1942         if (cur) {
1943                 if (option_debug)
1944                         ast_log(LOG_DEBUG, "Call pickup on chan '%s' by '%s'\n",cur->name, chan->name);
1945                 res = ast_answer(chan);
1946                 if (res)
1947                         ast_log(LOG_WARNING, "Unable to answer '%s'\n", chan->name);
1948                 res = ast_queue_control(chan, AST_CONTROL_ANSWER);
1949                 if (res)
1950                         ast_log(LOG_WARNING, "Unable to queue answer on '%s'\n", chan->name);
1951                 res = ast_channel_masquerade(cur, chan);
1952                 if (res)
1953                         ast_log(LOG_WARNING, "Unable to masquerade '%s' into '%s'\n", chan->name, cur->name);           /* Done */
1954                 ast_channel_unlock(cur);
1955         } else  {
1956                 if (option_debug)
1957                         ast_log(LOG_DEBUG, "No call pickup possible...\n");
1958         }
1959         return res;
1960 }
1961
1962 static int load_config(void) 
1963 {
1964         int start = 0, end = 0;
1965         struct ast_context *con = NULL;
1966         struct ast_config *cfg = NULL;
1967         struct ast_variable *var = NULL;
1968         char old_parking_ext[AST_MAX_EXTENSION];
1969         char old_parking_con[AST_MAX_EXTENSION] = "";
1970
1971         if (!ast_strlen_zero(parking_con)) {
1972                 strcpy(old_parking_ext, parking_ext);
1973                 strcpy(old_parking_con, parking_con);
1974         } 
1975
1976         /* Reset to defaults */
1977         strcpy(parking_con, "parkedcalls");
1978         strcpy(parking_con_dial, "park-dial");
1979         strcpy(parking_ext, "700");
1980         strcpy(pickup_ext, "*8");
1981         courtesytone[0] = '\0';
1982         strcpy(xfersound, "beep");
1983         strcpy(xferfailsound, "pbx-invalid");
1984         parking_start = 701;
1985         parking_stop = 750;
1986         parkfindnext = 0;
1987         adsipark = 0;
1988
1989         transferdigittimeout = DEFAULT_TRANSFER_DIGIT_TIMEOUT;
1990         featuredigittimeout = DEFAULT_FEATURE_DIGIT_TIMEOUT;
1991         atxfernoanswertimeout = DEFAULT_NOANSWER_TIMEOUT_ATTENDED_TRANSFER;
1992
1993         cfg = ast_config_load("features.conf");
1994         if (cfg) {
1995                 for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
1996                         if (!strcasecmp(var->name, "parkext")) {
1997                                 ast_copy_string(parking_ext, var->value, sizeof(parking_ext));
1998                         } else if (!strcasecmp(var->name, "context")) {
1999                                 ast_copy_string(parking_con, var->value, sizeof(parking_con));
2000                         } else if (!strcasecmp(var->name, "parkingtime")) {
2001                                 if ((sscanf(var->value, "%d", &parkingtime) != 1) || (parkingtime < 1)) {
2002                                         ast_log(LOG_WARNING, "%s is not a valid parkingtime\n", var->value);
2003                                         parkingtime = DEFAULT_PARK_TIME;
2004                                 } else
2005                                         parkingtime = parkingtime * 1000;
2006                         } else if (!strcasecmp(var->name, "parkpos")) {
2007                                 if (sscanf(var->value, "%d-%d", &start, &end) != 2) {
2008                                         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);
2009                                 } else {
2010                                         parking_start = start;
2011                                         parking_stop = end;
2012                                 }
2013                         } else if (!strcasecmp(var->name, "findslot")) {
2014                                 parkfindnext = (!strcasecmp(var->value, "next"));
2015                         } else if (!strcasecmp(var->name, "adsipark")) {
2016                                 adsipark = ast_true(var->value);
2017                         } else if (!strcasecmp(var->name, "transferdigittimeout")) {
2018                                 if ((sscanf(var->value, "%d", &transferdigittimeout) != 1) || (transferdigittimeout < 1)) {
2019                                         ast_log(LOG_WARNING, "%s is not a valid transferdigittimeout\n", var->value);
2020                                         transferdigittimeout = DEFAULT_TRANSFER_DIGIT_TIMEOUT;
2021                                 } else
2022                                         transferdigittimeout = transferdigittimeout * 1000;
2023                         } else if (!strcasecmp(var->name, "featuredigittimeout")) {
2024                                 if ((sscanf(var->value, "%d", &featuredigittimeout) != 1) || (featuredigittimeout < 1)) {
2025                                         ast_log(LOG_WARNING, "%s is not a valid featuredigittimeout\n", var->value);
2026                                         featuredigittimeout = DEFAULT_FEATURE_DIGIT_TIMEOUT;
2027                                 }
2028                         } else if (!strcasecmp(var->name, "atxfernoanswertimeout")) {
2029                                 if ((sscanf(var->value, "%d", &atxfernoanswertimeout) != 1) || (atxfernoanswertimeout < 1)) {
2030                                         ast_log(LOG_WARNING, "%s is not a valid atxfernoanswertimeout\n", var->value);
2031                                         atxfernoanswertimeout = DEFAULT_NOANSWER_TIMEOUT_ATTENDED_TRANSFER;
2032                                 } else
2033                                         atxfernoanswertimeout = atxfernoanswertimeout * 1000;
2034                         } else if (!strcasecmp(var->name, "courtesytone")) {
2035                                 ast_copy_string(courtesytone, var->value, sizeof(courtesytone));
2036                         }  else if (!strcasecmp(var->name, "parkedplay")) {
2037                                 if (!strcasecmp(var->value, "both"))
2038                                         parkedplay = 2;
2039                                 else if (!strcasecmp(var->value, "parked"))
2040                                         parkedplay = 1;
2041                                 else
2042                                         parkedplay = 0;
2043                         } else if (!strcasecmp(var->name, "xfersound")) {
2044                                 ast_copy_string(xfersound, var->value, sizeof(xfersound));
2045                         } else if (!strcasecmp(var->name, "xferfailsound")) {
2046                                 ast_copy_string(xferfailsound, var->value, sizeof(xferfailsound));
2047                         } else if (!strcasecmp(var->name, "pickupexten")) {
2048                                 ast_copy_string(pickup_ext, var->value, sizeof(pickup_ext));
2049                         }
2050                 }
2051
2052                 unmap_features();
2053                 for (var = ast_variable_browse(cfg, "featuremap"); var; var = var->next) {
2054                         if (remap_feature(var->name, var->value))
2055                                 ast_log(LOG_NOTICE, "Unknown feature '%s'\n", var->name);
2056                 }
2057
2058                 /* Map a key combination to an application*/
2059                 ast_unregister_features();
2060                 for (var = ast_variable_browse(cfg, "applicationmap"); var; var = var->next) {
2061                         char *tmp_val = ast_strdup(var->value);
2062                         char *exten, *party=NULL, *app=NULL, *app_args=NULL; 
2063
2064                         if (!tmp_val) { 
2065                                 /*! \todo XXX No memory. We should probably break, but at least we do not
2066                                  * insist on this entry or we could be stuck in an
2067                                  * infinite loop.
2068                                  */
2069                                 continue;
2070                         }
2071
2072                         /* strsep() sets the argument to NULL if match not found, and it
2073                          * is safe to use it with a NULL argument, so we don't check
2074                          * between calls.
2075                          */
2076                         exten = strsep(&tmp_val,",");
2077                         party = strsep(&tmp_val,",");
2078                         app = strsep(&tmp_val,",");
2079                         app_args = strsep(&tmp_val,",");
2080
2081                         /*! \todo XXX var_name or app_args ? */
2082                         if (ast_strlen_zero(app) || ast_strlen_zero(exten) || ast_strlen_zero(party) || ast_strlen_zero(var->name)) {
2083                                 ast_log(LOG_NOTICE, "Please check the feature Mapping Syntax, either extension, name, or app aren't provided %s %s %s %s\n",app,exten,party,var->name);
2084                                 free(tmp_val);
2085                                 continue;
2086                         }
2087
2088                         {
2089                                 struct ast_call_feature *feature;
2090                                 int mallocd = 0;
2091                                 
2092                                 if (!(feature = find_feature(var->name))) {
2093                                         mallocd = 1;
2094                                         
2095                                         if (!(feature = ast_calloc(1, sizeof(*feature)))) {
2096                                                 free(tmp_val);
2097                                                 continue;                                       
2098                                         }
2099                                 }
2100
2101                                 ast_copy_string(feature->sname,var->name,FEATURE_SNAME_LEN);
2102                                 ast_copy_string(feature->app,app,FEATURE_APP_LEN);
2103                                 ast_copy_string(feature->exten, exten,FEATURE_EXTEN_LEN);
2104                                 free(tmp_val);
2105                                 
2106                                 if (app_args) 
2107                                         ast_copy_string(feature->app_args,app_args,FEATURE_APP_ARGS_LEN);
2108                                 
2109                                 ast_copy_string(feature->exten, exten,sizeof(feature->exten));
2110                                 feature->operation=feature_exec_app;
2111                                 ast_set_flag(feature,AST_FEATURE_FLAG_NEEDSDTMF);
2112                                 
2113                                 if (!strcasecmp(party,"caller"))
2114                                         ast_set_flag(feature,AST_FEATURE_FLAG_CALLER);
2115                                 else if (!strcasecmp(party, "callee"))
2116                                         ast_set_flag(feature,AST_FEATURE_FLAG_CALLEE);
2117                                 else {
2118                                         ast_log(LOG_NOTICE, "Invalid party specification for feature '%s', must be caller, or callee\n", var->name);
2119                                         continue;
2120                                 }
2121
2122                                 ast_register_feature(feature);
2123                                 /* XXX do we need to free it if mallocd ? */
2124                                 
2125                                 if (option_verbose >=1)
2126                                         ast_verbose(VERBOSE_PREFIX_2 "Mapping Feature '%s' to app '%s' with code '%s'\n", var->name, app, exten);  
2127                         }
2128                 }        
2129         }
2130         ast_config_destroy(cfg);
2131
2132         /* Remove the old parking extension */
2133         if (!ast_strlen_zero(old_parking_con) && (con = ast_context_find(old_parking_con)))     {
2134                 ast_context_remove_extension2(con, old_parking_ext, 1, registrar);
2135                 if (option_debug)
2136                         ast_log(LOG_DEBUG, "Removed old parking extension %s@%s\n", old_parking_ext, old_parking_con);
2137         }
2138         
2139         if (!(con = ast_context_find(parking_con)) && !(con = ast_context_create(NULL, parking_con, registrar))) {
2140                 ast_log(LOG_ERROR, "Parking context '%s' does not exist and unable to create\n", parking_con);
2141                 return -1;
2142         }
2143         return ast_add_extension2(con, 1, ast_parking_ext(), 1, NULL, NULL, parkcall, strdup(""), FREE, registrar);
2144 }
2145
2146 static int reload(void *mod)
2147 {
2148         return load_config();
2149 }
2150
2151 static int load_module(void *mod)
2152 {
2153         int res;
2154         
2155         __mod_desc = mod;
2156         memset(parking_ext, 0, sizeof(parking_ext));
2157         memset(parking_con, 0, sizeof(parking_con));
2158
2159         if ((res = load_config()))
2160                 return res;
2161         ast_cli_register(&showparked);
2162         ast_cli_register(&showfeatures);
2163         ast_pthread_create(&parking_thread, NULL, do_parking_thread, NULL);
2164         res = ast_register_application(parkedcall, park_exec, synopsis, descrip);
2165         if (!res)
2166                 res = ast_register_application(parkcall, park_call_exec, synopsis2, descrip2);
2167         if (!res) {
2168                 ast_manager_register("ParkedCalls", 0, manager_parking_status, "List parked calls" );
2169                 ast_manager_register2("Park", EVENT_FLAG_CALL, manager_park,
2170                         "Park a channel", mandescr_park); 
2171         }
2172         return res;
2173 }
2174
2175
2176 static int unload_module(void *mod)
2177 {
2178         STANDARD_HANGUP_LOCALUSERS;
2179
2180         ast_manager_unregister("ParkedCalls");
2181         ast_manager_unregister("Park");
2182         ast_cli_unregister(&showfeatures);
2183         ast_cli_unregister(&showparked);
2184         ast_unregister_application(parkcall);
2185         return ast_unregister_application(parkedcall);
2186 }
2187
2188 static const char *description(void)
2189 {
2190         return "Call Features Resource";
2191 }
2192
2193 static const char *key(void)
2194 {
2195         return ASTERISK_GPL_KEY;
2196 }
2197
2198 STD_MOD(MOD_0 | NO_UNLOAD, reload, NULL, NULL);