aboutsummaryrefslogtreecommitdiffstats
path: root/res/res_features.c
blob: 691969781e6afd565378de6539b694f8dbb832b3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
/*
 * Asterisk -- A telephony toolkit for Linux.
 *
 * Routines implementing call parking
 * 
 * Copyright (C) 1999-2004, Digium, Inc.
 *
 * Mark Spencer <markster@digium.com>
 *
 * This program is free software, distributed under the terms of
 * the GNU General Public License
 */

#include <asterisk/lock.h>
#include <asterisk/file.h>
#include <asterisk/logger.h>
#include <asterisk/channel.h>
#include <asterisk/pbx.h>
#include <asterisk/options.h>
#include <asterisk/module.h>
#include <asterisk/translate.h>
#include <asterisk/app.h>
#include <asterisk/say.h>
#include <asterisk/channel_pvt.h>
#include <asterisk/features.h>
#include <asterisk/musiconhold.h>
#include <asterisk/config.h>
#include <asterisk/cli.h>
#include <asterisk/manager.h>
#include <asterisk/utils.h>
#include <asterisk/adsi.h>
#include <pthread.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <sys/signal.h>
#include <netinet/in.h>

#define DEFAULT_PARK_TIME 45000
#define DEFAULT_TRANSFER_DIGIT_TIMEOUT 3000
#define DEFAULT_FEATURE_DIGIT_TIMEOUT 500

static char *parkedcall = "ParkedCall";

/* No more than 45 seconds parked before you do something with them */
static int parkingtime = DEFAULT_PARK_TIME;

/* Context for which parking is made accessible */
static char parking_con[AST_MAX_EXTENSION] = "parkedcalls";

/* Context for dialback for parking (KLUDGE) */
static char parking_con_dial[AST_MAX_EXTENSION] = "park-dial";

/* Extension you type to park the call */
static char parking_ext[AST_MAX_EXTENSION] = "700";

static char pickup_ext[AST_MAX_EXTENSION] = "*8";

/* Default sounds */
static char courtesytone[256] = "";
static char xfersound[256] = "beep";
static char xferfailsound[256] = "pbx-invalid";

/* First available extension for parking */
static int parking_start = 701;

/* Last available extension for parking */
static int parking_stop = 750;

static int adsipark = 0;

static int transferdigittimeout = DEFAULT_TRANSFER_DIGIT_TIMEOUT;
static int featuredigittimeout = DEFAULT_FEATURE_DIGIT_TIMEOUT;

/* Default courtesy tone played when party joins conference */

/* Registrar for operations */
static char *registrar = "res_features";

static char *synopsis = "Answer a parked call";

static char *descrip = "ParkedCall(exten):"
"Used to connect to a parked call.  This application is always\n"
"registered internally and does not need to be explicitly added\n"
"into the dialplan, although you should include the 'parkedcalls'\n"
"context.\n";

static char *parkcall = "Park";

static char *synopsis2 = "Park yourself";

static char *descrip2 = "Park(exten):"
"Used to park yourself (typically in combination with a supervised\n"
"transfer to know the parking space). This application is always\n"
"registered internally and does not need to be explicitly added\n"
"into the dialplan, although you should include the 'parkedcalls'\n"
"context.\n";

static struct ast_app *monitor_app=NULL;
static int monitor_ok=1;

struct parkeduser {
	struct ast_channel *chan;
	struct timeval start;
	int parkingnum;
	/* Where to go if our parking time expires */
	char context[AST_MAX_EXTENSION];
	char exten[AST_MAX_EXTENSION];
	int priority;
	int parkingtime;
	int notquiteyet;
	char peername[1024];
	struct parkeduser *next;
};

static struct parkeduser *parkinglot;

AST_MUTEX_DEFINE_STATIC(parking_lock);

static pthread_t parking_thread;

STANDARD_LOCAL_USER;

LOCAL_USER_DECL;

char *ast_parking_ext(void)
{
	return parking_ext;
}

char *ast_pickup_ext(void)
{
	return pickup_ext;
}

struct ast_bridge_thread_obj 
{
	struct ast_bridge_config bconfig;
	struct ast_channel *chan;
	struct ast_channel *peer;
};

static void *ast_bridge_call_thread(void *data) 
{
	struct ast_bridge_thread_obj *tobj = data;
	tobj->chan->appl = "Transferred Call";
	tobj->chan->data = tobj->peer->name;
	tobj->peer->appl = "Transferred Call";
	tobj->peer->data = tobj->chan->name;
	if (tobj->chan->cdr) {
		ast_cdr_reset(tobj->chan->cdr,0);
		ast_cdr_setdestchan(tobj->chan->cdr, tobj->peer->name);
	}
	if (tobj->peer->cdr) {
		ast_cdr_reset(tobj->peer->cdr,0);
		ast_cdr_setdestchan(tobj->peer->cdr, tobj->chan->name);
	}


	ast_bridge_call(tobj->peer, tobj->chan, &tobj->bconfig);
	ast_hangup(tobj->chan);
	ast_hangup(tobj->peer);
	tobj->chan = tobj->peer = NULL;
	free(tobj);
	tobj=NULL;
	return NULL;
}

static void ast_bridge_call_thread_launch(void *data) 
{
	pthread_t thread;
	pthread_attr_t attr;
	int result;

	result = pthread_attr_init(&attr);
	pthread_attr_setschedpolicy(&attr, SCHED_RR);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
	result = ast_pthread_create(&thread, &attr,ast_bridge_call_thread, data);
	result = pthread_attr_destroy(&attr);
}



static int adsi_announce_park(struct ast_channel *chan, int parkingnum)
{
	int res;
	int justify[5] = {ADSI_JUST_CENT, ADSI_JUST_CENT, ADSI_JUST_CENT, ADSI_JUST_CENT};
	char tmp[256] = "";
	char *message[5] = {NULL, NULL, NULL, NULL, NULL};

	snprintf(tmp, sizeof(tmp), "Parked on %d", parkingnum);
	message[0] = tmp;
	res = adsi_load_session(chan, NULL, 0, 1);
	if (res == -1) {
		return res;
	}
	return adsi_print(chan, message, justify, 1);
}

int ast_park_call(struct ast_channel *chan, struct ast_channel *peer, int timeout, int *extout)
{
	/* We put the user in the parking list, then wake up the parking thread to be sure it looks
	   after these channels too */
	struct parkeduser *pu, *cur;
	int x;
	char exten[AST_MAX_EXTENSION];
	struct ast_context *con;
	pu = malloc(sizeof(struct parkeduser));
	if (pu) {
		memset(pu,0,sizeof(struct parkeduser));
		ast_mutex_lock(&parking_lock);
		for (x=parking_start;x<=parking_stop;x++) {
			cur = parkinglot;
			while(cur) {
				if (cur->parkingnum == x) 
					break;
				cur = cur->next;
			}
			if (!cur)
				break;
		}
		if (x <= parking_stop) {
			chan->appl = "Parked Call";
			chan->data = NULL; 

			pu->chan = chan;
			/* Start music on hold */
			if (chan != peer) {
				ast_indicate(pu->chan, AST_CONTROL_HOLD);
				ast_moh_start(pu->chan, NULL);
			}
			gettimeofday(&pu->start, NULL);
			pu->parkingnum = x;
			if (timeout > 0)
				pu->parkingtime = timeout;
			else
				pu->parkingtime = parkingtime;
			if (extout)
				*extout = x;
			if (peer)
			{
				strncpy(pu->peername,peer->name,sizeof(pu->peername) - 1);
			}
			/* Remember what had been dialed, so that if the parking
			   expires, we try to come back to the same place */
			if (!ast_strlen_zero(chan->macrocontext))
				strncpy(pu->context, chan->macrocontext, sizeof(pu->context)-1);
			else
				strncpy(pu->context, chan->context, sizeof(pu->context)-1);
			if (!ast_strlen_zero(chan->macroexten))
				strncpy(pu->exten, chan->macroexten, sizeof(pu->exten)-1);
			else
				strncpy(pu->exten, chan->exten, sizeof(pu->exten)-1);
			if (chan->macropriority)
				pu->priority = chan->macropriority;
			else
				pu->priority = chan->priority;
			pu->next = parkinglot;
			parkinglot = pu;
			/* If parking a channel directly, don't quiet yet get parking running on it */
			if (peer == chan) 
				pu->notquiteyet = 1;
			ast_mutex_unlock(&parking_lock);
			/* Wake up the (presumably select()ing) thread */
			pthread_kill(parking_thread, SIGURG);
			if (option_verbose > 1) 
				ast_verbose(VERBOSE_PREFIX_2 "Parked %s on %d. Will timeout back to %s,%s,%d in %d seconds\n", pu->chan->name, pu->parkingnum, pu->context, pu->exten, pu->priority, (pu->parkingtime/1000));

			manager_event(EVENT_FLAG_CALL, "ParkedCall",
                                "Exten: %d\r\n"
                                "Channel: %s\r\n"
                                "From: %s\r\n"
                                "Timeout: %ld\r\n"
                                "CallerID: %s\r\n"
                                "CallerIDName: %s\r\n\r\n"
                                ,pu->parkingnum, pu->chan->name, peer->name
                                ,(long)pu->start.tv_sec + (long)(pu->parkingtime/1000) - (long)time(NULL)
                                ,(pu->chan->cid.cid_num ? pu->chan->cid.cid_num : "")
                                ,(pu->chan->cid.cid_name ? pu->chan->cid.cid_name : "")
                                );

			if (peer) {
				if (adsipark && adsi_available(peer)) {
					adsi_announce_park(peer, pu->parkingnum);
				}
				if (adsipark && adsi_available(peer)) {
					adsi_unload_session(peer);
				}
				if (pu->notquiteyet) {
					/* Wake up parking thread if we're really done */
					ast_moh_start(pu->chan, NULL);
					pu->notquiteyet = 0;
					pthread_kill(parking_thread, SIGURG);
				}
			}
			con = ast_context_find(parking_con);
			if (!con) {
				con = ast_context_create(NULL,parking_con, registrar);
				if (!con) {
					ast_log(LOG_ERROR, "Parking context '%s' does not exist and unable to create\n", parking_con);
				}
			}
			if (con) {
				snprintf(exten, sizeof(exten), "%d", x);
				ast_add_extension2(con, 1, exten, 1, NULL, NULL, parkedcall, strdup(exten), free, registrar);
			}
			if (peer) ast_say_digits(peer, pu->parkingnum, "", peer->language);
			return 0;
		} else {
			ast_log(LOG_WARNING, "No more parking spaces\n");
			free(pu);
			ast_mutex_unlock(&parking_lock);
			return -1;
		}
	} else {
		ast_log(LOG_WARNING, "Out of memory\n");
		return -1;
	}
	return 0;
}

int ast_masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, int timeout, int *extout)
{
	struct ast_channel *chan;
	struct ast_frame *f;
	/* Make a new, fake channel that we'll use to masquerade in the real one */
	chan = ast_channel_alloc(0);
	if (chan) {
		/* Let us keep track of the channel name */
		snprintf(chan->name, sizeof (chan->name), "Parked/%s",rchan->name);
		/* Make formats okay */
		chan->readformat = rchan->readformat;
		chan->writeformat = rchan->writeformat;
		ast_channel_masquerade(chan, rchan);
		/* Setup the extensions and such */
		strncpy(chan->context, rchan->context, sizeof(chan->context) - 1);
		strncpy(chan->exten, rchan->exten, sizeof(chan->exten) - 1);
		chan->priority = rchan->priority;
		/* Make the masq execute */
		f = ast_read(chan);
		if (f)
			ast_frfree(f);
		ast_park_call(chan, peer, timeout, extout);
	} else {
		ast_log(LOG_WARNING, "Unable to create parked channel\n");
		return -1;
	}
	return 0;
}


#define FEATURE_RETURN_HANGUP		-1
#define FEATURE_RETURN_SUCCESSBREAK	 0
#define FEATURE_RETURN_PBX_KEEPALIVE	AST_PBX_KEEPALIVE
#define FEATURE_RETURN_NO_HANGUP_PEER	AST_PBX_NO_HANGUP_PEER
#define FEATURE_RETURN_PASSDIGITS	 21
#define FEATURE_RETURN_STOREDIGITS	 22
#define FEATURE_RETURN_SUCCESS	 	 23

#define FEATURE_SENSE_CHAN	(1 << 0)
#define FEATURE_SENSE_PEER	(1 << 1)
#define FEATURE_MAX_LEN		11

static int builtin_automonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense)
{
	char *touch_monitor = NULL, *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL;
	int x = 0;
	size_t len;
	struct ast_channel *caller_chan = NULL, *callee_chan = NULL;


	if(sense == 2) {
		caller_chan = peer;
		callee_chan = chan;
	} else {
		callee_chan = peer;
		caller_chan = chan;
	}
	
	if (!monitor_ok) {
		ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
		return -1;
	}

	if (!monitor_app) { 
		if (!(monitor_app = pbx_findapp("Monitor"))) {
			monitor_ok=0;
			ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
			return -1;
		}
	}
	if (!ast_strlen_zero(courtesytone)) {
		if (ast_autoservice_start(callee_chan))
			return -1;
		if (!ast_streamfile(caller_chan, courtesytone, caller_chan->language)) {
			if (ast_waitstream(caller_chan, "") < 0) {
				ast_log(LOG_WARNING, "Failed to play courtesy tone!\n");
				ast_autoservice_stop(callee_chan);
				return -1;
			}
		}
		if (ast_autoservice_stop(callee_chan))
			return -1;
	}
	
	if (callee_chan->monitor) {
		if (option_verbose > 3)
			ast_verbose(VERBOSE_PREFIX_3 "User hit '%s' to stop recording call.\n", code);
		ast_monitor_stop(callee_chan, 1);
		return FEATURE_RETURN_SUCCESS;
	}

	if (caller_chan && callee_chan) {
		touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR");
		if (!touch_monitor)
			touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR");
		
		if (touch_monitor) {
			len = strlen(touch_monitor) + 50;
			args = alloca(len);
			snprintf(args, len, "WAV|auto-%ld-%s|m", time(NULL), touch_monitor);
		} else {
			caller_chan_id = ast_strdupa(caller_chan->cid.cid_num ? caller_chan->cid.cid_num : caller_chan->name);
			callee_chan_id = ast_strdupa(callee_chan->cid.cid_num ? callee_chan->cid.cid_num : callee_chan->name);
			len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
			args = alloca(len);
			snprintf(args, len, "WAV|auto-%ld-%s-%s|m", time(NULL), caller_chan_id, callee_chan_id);
		}

		for( x = 0; x < strlen(args); x++)
			if (args[x] == '/')
				args[x] = '-';
		
		if (option_verbose > 3)
			ast_verbose(VERBOSE_PREFIX_3 "User hit '%s' to record call. filename: %s\n", code, args);

		pbx_exec(callee_chan, monitor_app, args, 1);
		
		return FEATURE_RETURN_SUCCESS;
	}
	
	ast_log(LOG_NOTICE,"Cannot record the call. One or both channels have gone away.\n");	
	return -1;
}

static int builtin_disconnect(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense)
{
	if (option_verbose > 3)
		ast_verbose(VERBOSE_PREFIX_3 "User hit '%s' to disconnect call.\n", code);
	return FEATURE_RETURN_HANGUP;
}

static int builtin_blindtransfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense)
{
	struct ast_channel *transferer;
	struct ast_channel *transferee;
	char *transferer_real_context;
	char newext[256], *ptr;
	int res;
	int len;

	if (sense == FEATURE_SENSE_PEER) {
		transferer = peer;
		transferee = chan;
	} else {
		transferer = chan;
		transferee = peer;
	}
	if (!(transferer_real_context=pbx_builtin_getvar_helper(transferee, "TRANSFER_CONTEXT")) &&
	   !(transferer_real_context=pbx_builtin_getvar_helper(transferer, "TRANSFER_CONTEXT"))) {
		/* Use the non-macro context to transfer the call */
		if (!ast_strlen_zero(transferer->macrocontext))
			transferer_real_context = transferer->macrocontext;
		else
			transferer_real_context = transferer->context;
	}
	/* Start autoservice on chan while we talk
	   to the originator */
	ast_indicate(transferee, AST_CONTROL_HOLD);
	ast_autoservice_start(transferee);
	ast_moh_start(transferee, NULL);

	memset(newext, 0, sizeof(newext));
	ptr = newext;

	/* Transfer */
	if ((res=ast_streamfile(transferer, "pbx-transfer", transferer->language))) {
		ast_moh_stop(transferee);
		ast_autoservice_stop(transferee);
		ast_indicate(transferee, AST_CONTROL_UNHOLD);
		return res;
	}
	if ((res=ast_waitstream(transferer, AST_DIGIT_ANY)) < 0) {
		ast_moh_stop(transferee);
		ast_autoservice_stop(transferee);
		ast_indicate(transferee, AST_CONTROL_UNHOLD);
		return res;
	}
	ast_stopstream(transferer);
	if (res > 0) {
		/* If they've typed a digit already, handle it */
		newext[0] = res;
		ptr++;
		len--;
	}

	res = ast_app_dtget(transferer, transferer_real_context, newext, sizeof(newext), 100, transferdigittimeout);
	if (res < 0) {
		ast_moh_stop(transferee);
		ast_autoservice_stop(transferee);
		ast_indicate(transferee, AST_CONTROL_UNHOLD);
		return res;
	}
	if (!strcmp(newext, ast_parking_ext())) {
		ast_moh_stop(transferee);

		res = ast_autoservice_stop(transferee);
		ast_indicate(transferee, AST_CONTROL_UNHOLD);
		if (res)
			res = -1;
		else if (!ast_park_call(transferee, transferer, 0, NULL)) {
			/* We return non-zero, but tell the PBX not to hang the channel when
			   the thread dies -- We have to be careful now though.  We are responsible for 
			   hanging up the channel, else it will never be hung up! */

			if (transferer==peer)
				res=AST_PBX_KEEPALIVE;
			else
				res=AST_PBX_NO_HANGUP_PEER;
			return res;
		} else {
			ast_log(LOG_WARNING, "Unable to park call %s\n", transferee->name);
		}
		/* XXX Maybe we should have another message here instead of invalid extension XXX */
	} else if (ast_exists_extension(transferee, transferer_real_context, newext, 1, transferer->cid.cid_num)) {
		pbx_builtin_setvar_helper(peer, "BLINDTRANSFER", chan->name);
		pbx_builtin_setvar_helper(chan, "BLINDTRANSFER", peer->name);
		ast_moh_stop(transferee);
		res=ast_autoservice_stop(transferee);
		ast_indicate(transferee, AST_CONTROL_UNHOLD);
		if (!transferee->pbx) {
			/* Doh!  Use our handy async_goto functions */
			if (option_verbose > 2) 
				ast_verbose(VERBOSE_PREFIX_3 "Transferring %s to '%s' (context %s) priority 1\n"
								,transferee->name, newext, transferer_real_context);
			if (ast_async_goto(transferee, transferer_real_context, newext, 1))
				ast_log(LOG_WARNING, "Async goto failed :-(\n");
			res = -1;
		} else {
			/* Set the channel's new extension, since it exists, using transferer context */
			strncpy(transferee->exten, newext, sizeof(transferee->exten)-1);
			strncpy(transferee->context, transferer_real_context, sizeof(transferee->context)-1);
			transferee->priority = 0;
		}
		return res;
	} else {
		if (option_verbose > 2)	
			ast_verbose(VERBOSE_PREFIX_3 "Unable to find extension '%s' in context '%s'\n", newext, transferer_real_context);
	}
	if (!ast_strlen_zero(xferfailsound))
		res = ast_streamfile(transferer, xferfailsound, transferee->language);
	else
		res = 0;
	if (res) {
		ast_moh_stop(transferee);
		ast_autoservice_stop(transferee);
		ast_indicate(transferee, AST_CONTROL_UNHOLD);
		return res;
	}
	res = ast_waitstream(transferer, AST_DIGIT_ANY);
	ast_stopstream(transferer);
	ast_moh_stop(transferee);
	res = ast_autoservice_stop(transferee);
	ast_indicate(transferee, AST_CONTROL_UNHOLD);
	if (res) {
		if (option_verbose > 1)
			ast_verbose(VERBOSE_PREFIX_2 "Hungup during autoservice stop on '%s'\n", transferee->name);
		return res;
	}
	return FEATURE_RETURN_SUCCESS;
}

static int builtin_atxfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense)
{
	struct ast_channel *transferer;
	struct ast_channel *transferee;
	struct ast_channel *newchan, *xferchan=NULL;
	int outstate=0;
	struct ast_bridge_config bconfig;
	char *transferer_real_context;
	char xferto[256],dialstr[265];
	char *cid_num;
	char *cid_name;
	int res;
	struct ast_frame *f = NULL;
	struct ast_bridge_thread_obj *tobj;

	ast_log(LOG_DEBUG, "Executing Attended Transfer %s, %s (sense=%d) XXX\n", chan->name, peer->name, sense);
	if (sense == FEATURE_SENSE_PEER) {
		transferer = peer;
		transferee = chan;
	} else {
		transferer = chan;
		transferee = peer;
	}
	if (!(transferer_real_context=pbx_builtin_getvar_helper(transferee, "TRANSFER_CONTEXT")) &&
	   !(transferer_real_context=pbx_builtin_getvar_helper(transferer, "TRANSFER_CONTEXT"))) {
		/* Use the non-macro context to transfer the call */
		if (!ast_strlen_zero(transferer->macrocontext))
			transferer_real_context = transferer->macrocontext;
		else
			transferer_real_context = transferer->context;
	}
	/* Start autoservice on chan while we talk
	   to the originator */
	ast_indicate(transferee, AST_CONTROL_HOLD);
	ast_autoservice_start(transferee);
	ast_moh_start(transferee, NULL);

	/* Transfer */
	if ((res=ast_streamfile(transferer, "pbx-transfer", transferer->language))) {
		ast_moh_stop(transferee);
		ast_autoservice_stop(transferee);
		ast_indicate(transferee, AST_CONTROL_UNHOLD);
		return res;
	}
	if ((res=ast_waitstream(transferer, AST_DIGIT_ANY)) < 0) {
		ast_moh_stop(transferee);
		ast_autoservice_stop(transferee);
		ast_indicate(transferee, AST_CONTROL_UNHOLD);
		return res;
	}
	if ((ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout))) {
		cid_num = transferer->cid.cid_num;
		cid_name = transferer->cid.cid_name;
		if (ast_exists_extension(transferer, transferer_real_context,xferto, 1, cid_num)) {
			snprintf(dialstr, sizeof(dialstr), "%s@%s/n", xferto, transferer_real_context);
			if ((newchan = ast_request_and_dial("Local", ast_best_codec(transferer->nativeformats), dialstr,30000, &outstate, cid_num, cid_name))) {
				res = ast_channel_make_compatible(transferer, newchan);
				if (res < 0) {
					ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", transferer->name, newchan->name);
					ast_hangup(newchan);
					return -1;
				}
				memset(&bconfig,0,sizeof(struct ast_bridge_config));
				ast_set_flag(&(bconfig.features_caller), AST_FEATURE_DISCONNECT);
				ast_set_flag(&(bconfig.features_callee), AST_FEATURE_DISCONNECT);
				res = ast_bridge_call(transferer,newchan,&bconfig);
				if (newchan->_softhangup || newchan->_state != AST_STATE_UP) {
					ast_hangup(newchan);
					if (f) {
						ast_frfree(f);
						f = NULL;
					}
					if (!ast_strlen_zero(xfersound) && !ast_streamfile(transferer, xfersound, transferer->language)) {
						if (ast_waitstream(transferer, "") < 0) {
							ast_log(LOG_WARNING, "Failed to play courtesy tone!\n");
						}
					}
					ast_moh_stop(transferee);
					ast_autoservice_stop(transferee);
					ast_indicate(transferee, AST_CONTROL_UNHOLD);
					transferer->_softhangup = 0;
					return FEATURE_RETURN_SUCCESS;
				}
				
				res = ast_channel_make_compatible(transferee, newchan);
				if (res < 0) {
					ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n", transferee->name, newchan->name);
					ast_hangup(newchan);
					return -1;
				}
				
				
				ast_moh_stop(transferee);
				
				if ((ast_autoservice_stop(transferee) < 0)
				   ||(ast_waitfordigit(transferee,100) < 0)
				   || (ast_waitfordigit(newchan,100) < 0) 
				   || ast_check_hangup(transferee) 
				   || ast_check_hangup(newchan)) {
					ast_hangup(newchan);
					res = -1;
					return -1;
				}

				if ((xferchan = ast_channel_alloc(0))) {
					snprintf(xferchan->name, sizeof (xferchan->name), "Transfered/%s",transferee->name);
					/* Make formats okay */
					xferchan->readformat = transferee->readformat;
					xferchan->writeformat = transferee->writeformat;
					ast_channel_masquerade(xferchan, transferee);
					ast_explicit_goto(xferchan, transferee->context, transferee->exten, transferee->priority);
					xferchan->_state = AST_STATE_UP;
					ast_clear_flag(xferchan, AST_FLAGS_ALL);	
					xferchan->_softhangup = 0;

					if ((f = ast_read(xferchan))) {
						ast_frfree(f);
						f = NULL;
					}
					
				} else {
					ast_hangup(newchan);
					return -1;
				}

				newchan->_state = AST_STATE_UP;
				ast_clear_flag(newchan, AST_FLAGS_ALL);	
				newchan->_softhangup = 0;

				tobj = malloc(sizeof(struct ast_bridge_thread_obj));
				if (tobj) {
					memset(tobj,0,sizeof(struct ast_bridge_thread_obj));
					tobj->chan = xferchan;
					tobj->peer = newchan;
					tobj->bconfig = *config;
	
					if (!ast_strlen_zero(xfersound) && !ast_streamfile(newchan, xfersound, newchan->language)) {
						if (ast_waitstream(newchan, "") < 0) {
							ast_log(LOG_WARNING, "Failed to play courtesy tone!\n");
						}
					}
					ast_bridge_call_thread_launch(tobj);
				} else {
					ast_log(LOG_WARNING, "Out of memory!\n");
					ast_hangup(xferchan);
					ast_hangup(newchan);
				}
				return -1;
				
			} else {
				ast_log(LOG_WARNING, "Unable to create channel Local/%s do you have chan_local?\n",dialstr);
				ast_moh_stop(transferee);
				ast_autoservice_stop(transferee);
				ast_indicate(transferee, AST_CONTROL_UNHOLD);
				if (!ast_strlen_zero(xferfailsound)) {
					res = ast_streamfile(transferer, xferfailsound, transferer->language);
					if (!res && (ast_waitstream(transferer, "") < 0)) {
						return -1;
					}
				}
				return -1;
			}
		} else {
			ast_log(LOG_WARNING, "Extension %s does not exist in context %s\n",xferto,transferer_real_context);
			ast_moh_stop(transferee);
			ast_autoservice_stop(transferee);
			ast_indicate(transferee, AST_CONTROL_UNHOLD);
			res = ast_streamfile(transferer, "beeperr", transferer->language);
			if (!res && (ast_waitstream(transferer, "") < 0)) {
				return -1;
			}
		}
	}  else {
		ast_log(LOG_WARNING, "Did not read data.\n");
		res = ast_streamfile(transferer, "beeperr", transferer->language);
		if (ast_waitstream(transferer, "") < 0) {
			return -1;
		}
	}
	ast_moh_stop(transferee);
	ast_autoservice_stop(transferee);
	ast_indicate(transferee, AST_CONTROL_UNHOLD);

	return FEATURE_RETURN_SUCCESS;
}

struct ast_call_feature {
	int feature_mask;
	char *fname;
	char *sname;
	char exten[FEATURE_MAX_LEN];
	char default_exten[FEATURE_MAX_LEN];
	int (*operation)(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense);
	unsigned int flags;
};

/* add atxfer and automon as undefined so you can only use em if you configure them */
#define FEATURES_COUNT (sizeof(builtin_features) / sizeof(builtin_features[0]))
struct ast_call_feature builtin_features[] = 
{
	{ AST_FEATURE_REDIRECT, "Blind Transfer", "blindxfer", "#", "#", builtin_blindtransfer, AST_FEATURE_FLAG_NEEDSDTMF },
	{ AST_FEATURE_REDIRECT, "Attended Transfer", "atxfer", "", "", builtin_atxfer, AST_FEATURE_FLAG_NEEDSDTMF },
	{ AST_FEATURE_AUTOMON, "One Touch Monitor", "automon", "", "", builtin_automonitor, AST_FEATURE_FLAG_NEEDSDTMF },
	{ AST_FEATURE_DISCONNECT, "Disconnect Call", "disconnect", "*", "*", builtin_disconnect, AST_FEATURE_FLAG_NEEDSDTMF },
};

static void unmap_features(void)
{
	int x;
	for (x=0;x<FEATURES_COUNT;x++)
		strcpy(builtin_features[x].exten, builtin_features[x].default_exten);
}

static int remap_feature(const char *name, const char *value)
{
	int x;
	int res = -1;
	for (x=0;x<FEATURES_COUNT;x++) {
		if (!strcasecmp(name, builtin_features[x].sname)) {
			strncpy(builtin_features[x].exten, value, sizeof(builtin_features[x].exten) - 1);
			if (option_verbose > 1)
				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);
			res = 0;
		} else if (!strcmp(value, builtin_features[x].exten)) 
			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);
	}
	return res;
}

static int ast_feature_interpret(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense)
{
	int x;
	struct ast_flags features;
	int res = FEATURE_RETURN_PASSDIGITS;

	if (sense == FEATURE_SENSE_CHAN)
		ast_copy_flags(&features, &(config->features_caller), AST_FLAGS_ALL);	
	else
		ast_copy_flags(&features, &(config->features_callee), AST_FLAGS_ALL);	
	ast_log(LOG_DEBUG, "Feature interpret: chan=%s, peer=%s, sense=%d, features=%d\n", chan->name, peer->name, sense, features.flags);
	for (x=0;x<FEATURES_COUNT;x++) {
		if ((ast_test_flag(&features, builtin_features[x].feature_mask)) &&
		    !ast_strlen_zero(builtin_features[x].exten)) {
			/* Feature is up for consideration */
			if (!strcmp(builtin_features[x].exten, code)) {
				res = builtin_features[x].operation(chan, peer, config, code, sense);
				break;
			} else if (!strncmp(builtin_features[x].exten, code, strlen(code))) {
				if (res == FEATURE_RETURN_PASSDIGITS)
					res = FEATURE_RETURN_STOREDIGITS;
			}
		}
	}
	return res;
}

static void set_config_flags(struct ast_bridge_config *config)
{
	int x;
	ast_clear_flag(config, AST_FLAGS_ALL);	
	for (x=0;x<FEATURES_COUNT;x++) {
		if (ast_test_flag(&(config->features_caller), builtin_features[x].feature_mask)) {
			if (ast_test_flag(builtin_features + x, AST_FEATURE_FLAG_NEEDSDTMF))
				ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
		}
		if (ast_test_flag(&(config->features_callee), builtin_features[x].feature_mask)) {
			if (ast_test_flag(builtin_features + x, AST_FEATURE_FLAG_NEEDSDTMF))
				ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
		}
	}
}

int ast_bridge_call(struct ast_channel *chan,struct ast_channel *peer,struct ast_bridge_config *config)
{
	/* Copy voice back and forth between the two channels.  Give the peer
	   the ability to transfer calls with '#<extension' syntax. */
	struct ast_frame *f;
	struct ast_channel *who;
	char chan_featurecode[FEATURE_MAX_LEN + 1]="";
	char peer_featurecode[FEATURE_MAX_LEN + 1]="";
	int res;
	int diff;
	int hasfeatures=0;
	int hadfeatures=0;
	struct ast_option_header *aoh;
	struct timeval start, end;
	struct ast_bridge_config backup_config;
	int allowdisconnect_in,allowdisconnect_out,allowredirect_in,allowredirect_out;
	char *monitor_exec;

	memset(&backup_config, 0, sizeof(backup_config));

	if (chan && peer) {
		pbx_builtin_setvar_helper(chan, "BRIDGEPEER", peer->name);
		pbx_builtin_setvar_helper(peer, "BRIDGEPEER", chan->name);
	} else if (chan)
		pbx_builtin_setvar_helper(chan, "BLINDTRANSFER", NULL);

	if (monitor_ok) {
		if (!monitor_app) { 
			if (!(monitor_app = pbx_findapp("Monitor")))
				monitor_ok=0;
		}
		if ((monitor_exec = pbx_builtin_getvar_helper(chan, "AUTO_MONITOR"))) 
			pbx_exec(chan, monitor_app, monitor_exec, 1);
		else if ((monitor_exec = pbx_builtin_getvar_helper(peer, "AUTO_MONITOR")))
			pbx_exec(peer, monitor_app, monitor_exec, 1);
	}
	
	allowdisconnect_in = ast_test_flag(&(config->features_callee), AST_FEATURE_DISCONNECT);
	allowdisconnect_out = ast_test_flag(&(config->features_caller), AST_FEATURE_DISCONNECT);
	allowredirect_in = ast_test_flag(&(config->features_callee), AST_FEATURE_REDIRECT);
	allowredirect_out = ast_test_flag(&(config->features_caller), AST_FEATURE_REDIRECT);
	set_config_flags(config);
	config->firstpass = 1;

	/* Answer if need be */
	if (ast_answer(chan))
		return -1;
	peer->appl = "Bridged Call";
	peer->data = chan->name;
	/* copy the userfield from the B-leg to A-leg if applicable */
	if (chan->cdr && peer->cdr && !ast_strlen_zero(peer->cdr->userfield)) {
		char tmp[256];
		if (!ast_strlen_zero(chan->cdr->userfield)) {
			snprintf(tmp, sizeof(tmp), "%s;%s",chan->cdr->userfield, peer->cdr->userfield);
			ast_cdr_appenduserfield(chan, tmp);
		} else
			ast_cdr_setuserfield(chan, peer->cdr->userfield);
		/* free the peer's cdr without ast_cdr_free complaining */
		free(peer->cdr);
		peer->cdr = NULL;
	}
	for (;;) {
		if (config->timelimit)
			gettimeofday(&start, NULL);
		res = ast_channel_bridge(chan,peer,config,&f, &who);
		if (config->timelimit) {
			/* Update time limit for next pass */
			gettimeofday(&end, NULL);
			diff = (end.tv_sec - start.tv_sec) * 1000;
			diff += (end.tv_usec - start.tv_usec) / 1000;
			config->timelimit -= diff;
			if (hasfeatures) {
				/* Running on backup config, meaning a feature might be being
				   activated, but that's no excuse to keep things going 
				   indefinitely! */
				if (backup_config.timelimit && ((backup_config.timelimit -= diff) <= 0)) {
					ast_log(LOG_DEBUG, "Timed out, realtime this time!\n");
					config->timelimit = 0;
					who = chan;
					if (f)
						ast_frfree(f);
					f = NULL;
					res = 0;
				} else if (config->timelimit <= 0) {
					/* Not *really* out of time, just out of time for
					   digits to come in for features. */
					ast_log(LOG_DEBUG, "Timed out for feature!\n");
					if (!ast_strlen_zero(peer_featurecode)) {
						ast_dtmf_stream(chan, peer, peer_featurecode, 0);
						memset(peer_featurecode, 0, sizeof(peer_featurecode));
					}
					if (!ast_strlen_zero(chan_featurecode)) {
						ast_dtmf_stream(peer, chan, chan_featurecode, 0);
						memset(chan_featurecode, 0, sizeof(chan_featurecode));
					}
					if (f)
						ast_frfree(f);
					hasfeatures = !ast_strlen_zero(chan_featurecode) || !ast_strlen_zero(peer_featurecode);
					if (!hasfeatures) {
						/* Restore original (possibly time modified) bridge config */
						memcpy(config, &backup_config, sizeof(struct ast_bridge_config));
						memset(&backup_config, 0, sizeof(backup_config));
					}
					hadfeatures = hasfeatures;
					/* Continue as we were */
					continue;
				}
			} else {
				if (config->timelimit <=0) {
					/* We ran out of time */
					config->timelimit = 0;
					who = chan;
					if (f)
						ast_frfree(f);
					f = NULL;
					res = 0;
				}
			}
		}
		if (res < 0) {
			ast_log(LOG_WARNING, "Bridge failed on channels %s and %s\n", chan->name, peer->name);
			return -1;
		}
		
		if (!f || ((f->frametype == AST_FRAME_CONTROL) && ((f->subclass == AST_CONTROL_HANGUP) || (f->subclass == AST_CONTROL_BUSY) || 
			(f->subclass == AST_CONTROL_CONGESTION)))) {
				res = -1;
				break;
		}
		if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_RINGING)) {
			if (who == chan)
				ast_indicate(peer, AST_CONTROL_RINGING);
			else
				ast_indicate(chan, AST_CONTROL_RINGING);
		}
		if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == -1)) {
			if (who == chan)
				ast_indicate(peer, -1);
			else
				ast_indicate(chan, -1);
		}
		if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_FLASH)) {
			if (who == chan)
				ast_indicate(peer, AST_CONTROL_FLASH);
			else
				ast_indicate(chan, AST_CONTROL_FLASH);
		}
		if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_OPTION)) {
			aoh = f->data;
			/* Forward option Requests */
			if (aoh && (aoh->flag == AST_OPTION_FLAG_REQUEST)) {
				if (who == chan)
					ast_channel_setoption(peer, ntohs(aoh->option), aoh->data, f->datalen - sizeof(struct ast_option_header), 0);
				else
					ast_channel_setoption(chan, ntohs(aoh->option), aoh->data, f->datalen - sizeof(struct ast_option_header), 0);
			}
		}
		/* check for '*', if we find it it's time to disconnect */
		if (f && (f->frametype == AST_FRAME_DTMF)) {
			char *featurecode;
			int sense;
			struct ast_channel *other;
			hadfeatures = hasfeatures;
			/* This cannot overrun because the longest feature is one shorter than our buffer */
			if (who == chan) {
				other = peer;
				sense = FEATURE_SENSE_CHAN;
				featurecode = chan_featurecode;
			} else  {
				other = chan;
				sense = FEATURE_SENSE_PEER;
				featurecode = peer_featurecode;
			}
			featurecode[strlen(featurecode)] = f->subclass;
			config->timelimit = backup_config.timelimit;
			res = ast_feature_interpret(chan, peer, config, featurecode, sense);
			switch(res) {
			case FEATURE_RETURN_PASSDIGITS:
				ast_dtmf_stream(other, who, featurecode, 0);
				/* Fall through */
			case FEATURE_RETURN_SUCCESS:
				memset(featurecode, 0, sizeof(chan_featurecode));
				break;
			}
			if (res >= FEATURE_RETURN_PASSDIGITS) {
				res = 0;
			} else {
				ast_frfree(f);
				break;
			}
			hasfeatures = !ast_strlen_zero(chan_featurecode) || !ast_strlen_zero(peer_featurecode);
			if (hadfeatures && !hasfeatures) {
				/* Restore backup */
				memcpy(config, &backup_config, sizeof(struct ast_bridge_config));
				memset(&backup_config, 0, sizeof(struct ast_bridge_config));
			} else if (hasfeatures) {
				if (!hadfeatures) {
					/* Backup configuration */
					memcpy(&backup_config, config, sizeof(struct ast_bridge_config));
					/* Setup temporary config options */
					config->play_warning = 0;
					ast_clear_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING);
					ast_clear_flag(&(config->features_callee),AST_FEATURE_PLAY_WARNING);
					config->warning_freq = 0;
					config->warning_sound = NULL;
					config->end_sound = NULL;
					config->start_sound = NULL;
					config->firstpass = 0;
				}
				config->timelimit = featuredigittimeout;
				ast_log(LOG_DEBUG, "Set time limit to %ld\n", config->timelimit);
			}
		}
		if (f)
			ast_frfree(f);
	}
	return res;
}

static void *do_parking_thread(void *ignore)
{
	int ms, tms, max;
	struct parkeduser *pu, *pl, *pt = NULL;
	struct timeval tv;
	struct ast_frame *f;
	char exten[AST_MAX_EXTENSION];
	char *peername,*cp;
	struct ast_context *con;
	int x;
	int gc=0;
	fd_set rfds, efds;
	fd_set nrfds, nefds;
	FD_ZERO(&rfds);
	FD_ZERO(&efds);

	for (;;) {
		ms = -1;
		max = -1;
		ast_mutex_lock(&parking_lock);
		pl = NULL;
		pu = parkinglot;
		FD_ZERO(&nrfds);
		FD_ZERO(&nefds);
		while(pu) {
			if (pu->notquiteyet) {
				/* Pretend this one isn't here yet */
				pl = pu;
				pu = pu->next;
				continue;
			}
			if (gc < 5 && !pu->chan->generator) {
				gc++;
				ast_moh_start(pu->chan,NULL);
			}
			gettimeofday(&tv, NULL);
			tms = (tv.tv_sec - pu->start.tv_sec) * 1000 + (tv.tv_usec - pu->start.tv_usec) / 1000;
			if (tms > pu->parkingtime) {
				/* Stop music on hold */
				ast_moh_stop(pu->chan);
				ast_indicate(pu->chan, AST_CONTROL_UNHOLD);
				/* Get chan, exten from derived kludge */
				if (pu->peername[0]) {
					peername = ast_strdupa(pu->peername);
					cp = strrchr(peername, '-');
					if (cp) 
						*cp = 0;
					con = ast_context_find(parking_con_dial);
					if (!con) {
						con = ast_context_create(NULL, parking_con_dial, registrar);
						if (!con) {
							ast_log(LOG_ERROR, "Parking dial context '%s' does not exist and unable to create\n", parking_con_dial);
						}
					}
					if (con) {
						ast_add_extension2(con, 1, peername, 1, NULL, NULL, "Dial", strdup(peername), free, registrar);
					}
					strncpy(pu->chan->exten, peername, sizeof(pu->chan->exten) - 1);
					strncpy(pu->chan->context, parking_con_dial, sizeof(pu->chan->context) - 1);
					pu->chan->priority = 1;

				} else {
					/* They've been waiting too long, send them back to where they came.  Theoretically they
					   should have their original extensions and such, but we copy to be on the safe side */
					strncpy(pu->chan->exten, pu->exten, sizeof(pu->chan->exten)-1);
					strncpy(pu->chan->context, pu->context, sizeof(pu->chan->context)-1);
					pu->chan->priority = pu->priority;
				}
				if (option_verbose > 1) 
					ast_verbose(VERBOSE_PREFIX_2 "Timeout for %s parked on %d. Returning to %s,%s,%d\n", pu->chan->name, pu->parkingnum, pu->chan->context, pu->chan->exten, pu->chan->priority);
				/* Start up the PBX, or hang them up */
				if (ast_pbx_start(pu->chan))  {
					ast_log(LOG_WARNING, "Unable to restart the PBX for user on '%s', hanging them up...\n", pu->chan->name);
					ast_hangup(pu->chan);
				}
				/* And take them out of the parking lot */
				if (pl) 
					pl->next = pu->next;
				else
					parkinglot = pu->next;
				pt = pu;
				pu = pu->next;
				con = ast_context_find(parking_con);
				if (con) {
					snprintf(exten, sizeof(exten), "%d", pt->parkingnum);
					if (ast_context_remove_extension2(con, exten, 1, NULL))
						ast_log(LOG_WARNING, "Whoa, failed to remove the extension!\n");
				} else
					ast_log(LOG_WARNING, "Whoa, no parking context?\n");
				free(pt);
			} else {
				for (x=0; x<AST_MAX_FDS; x++) {
					if ((pu->chan->fds[x] > -1) && (FD_ISSET(pu->chan->fds[x], &rfds) || FD_ISSET(pu->chan->fds[x], &efds))) {
						if (FD_ISSET(pu->chan->fds[x], &efds))
							ast_set_flag(pu->chan, AST_FLAG_EXCEPTION);
						else
							ast_clear_flag(pu->chan, AST_FLAG_EXCEPTION);
						pu->chan->fdno = x;
						/* See if they need servicing */
						f = ast_read(pu->chan);
						if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass ==  AST_CONTROL_HANGUP))) {
							/* There's a problem, hang them up*/
							if (option_verbose > 1) 
								ast_verbose(VERBOSE_PREFIX_2 "%s got tired of being parked\n", pu->chan->name);
							ast_hangup(pu->chan);
							/* And take them out of the parking lot */
							if (pl) 
								pl->next = pu->next;
							else
								parkinglot = pu->next;
							pt = pu;
							pu = pu->next;
							con = ast_context_find(parking_con);
							if (con) {
								snprintf(exten, sizeof(exten), "%d", pt->parkingnum);
								if (ast_context_remove_extension2(con, exten, 1, NULL))
									ast_log(LOG_WARNING, "Whoa, failed to remove the extension!\n");
							} else
								ast_log(LOG_WARNING, "Whoa, no parking context?\n");
							free(pt);
							break;
						} else {
							/* XXX Maybe we could do something with packets, like dial "0" for operator or something XXX */
							ast_frfree(f);
							goto std;	/* XXX Ick: jumping into an else statement??? XXX */
						}
					}
				}
				if (x >= AST_MAX_FDS) {
std:					for (x=0; x<AST_MAX_FDS; x++) {
						/* Keep this one for next one */
						if (pu->chan->fds[x] > -1) {
							FD_SET(pu->chan->fds[x], &nrfds);
							FD_SET(pu->chan->fds[x], &nefds);
							if (pu->chan->fds[x] > max)
								max = pu->chan->fds[x];
						}
					}
					/* Keep track of our longest wait */
					if ((tms < ms) || (ms < 0))
						ms = tms;
					pl = pu;
					pu = pu->next;
				}
			}
		}
		ast_mutex_unlock(&parking_lock);
		rfds = nrfds;
		efds = nefds;
		tv.tv_sec = ms / 1000;
		tv.tv_usec = (ms % 1000) * 1000;
		/* Wait for something to happen */
		ast_select(max + 1, &rfds, NULL, &efds, (ms > -1) ? &tv : NULL);
		pthread_testcancel();
	}
	return NULL;	/* Never reached */
}

static int park_call_exec(struct ast_channel *chan, void *data)
{
	/* Data is unused at the moment but could contain a parking
	   lot context eventually */
	int res=0;
	struct localuser *u;
	LOCAL_USER_ADD(u);
	/* Setup the exten/priority to be s/1 since we don't know
	   where this call should return */
	strcpy(chan->exten, "s");
	chan->priority = 1;
	if (chan->_state != AST_STATE_UP)
		res = ast_answer(chan);
	if (!res)
		res = ast_safe_sleep(chan, 1000);
	if (!res)
		res = ast_park_call(chan, chan, 0, NULL);
	LOCAL_USER_REMOVE(u);
	if (!res)
		res = AST_PBX_KEEPALIVE;
	return res;
}

static int park_exec(struct ast_channel *chan, void *data)
{
	int res=0;
	struct localuser *u;
	struct ast_channel *peer=NULL;
	struct parkeduser *pu, *pl=NULL;
	char exten[AST_MAX_EXTENSION];
	struct ast_context *con;
	int park;
	int dres;
	struct ast_bridge_config config;

	if (!data) {
		ast_log(LOG_WARNING, "Park requires an argument (extension number)\n");
		return -1;
	}
	LOCAL_USER_ADD(u);
	park = atoi((char *)data);
	ast_mutex_lock(&parking_lock);
	pu = parkinglot;
	while(pu) {
		if (pu->parkingnum == park) {
			if (pl)
				pl->next = pu->next;
			else
				parkinglot = pu->next;
			break;
		}
		pl = pu;
		pu = pu->next;
	}
	ast_mutex_unlock(&parking_lock);
	if (pu) {
		peer = pu->chan;
		con = ast_context_find(parking_con);
		if (con) {
			snprintf(exten, sizeof(exten), "%d", pu->parkingnum);
			if (ast_context_remove_extension2(con, exten, 1, NULL))
				ast_log(LOG_WARNING, "Whoa, failed to remove the extension!\n");
		} else
			ast_log(LOG_WARNING, "Whoa, no parking context?\n");
		free(pu);
	}
	/* JK02: it helps to answer the channel if not already up */
	if (chan->_state != AST_STATE_UP) {
		ast_answer(chan);
	}

	if (peer) {
		/* Play a courtesy beep in the calling channel to prefix the bridge connecting */	
		if (!ast_strlen_zero(courtesytone)) {
			if (!ast_streamfile(chan, courtesytone, chan->language)) {
				if (ast_waitstream(chan, "") < 0) {
					ast_log(LOG_WARNING, "Failed to play courtesy tone!\n");
					ast_hangup(peer);
					return -1;
				}
			}
		}
 
		ast_moh_stop(peer);
		ast_indicate(peer, AST_CONTROL_UNHOLD);
		res = ast_channel_make_compatible(chan, peer);
		if (res < 0) {
			ast_log(LOG_WARNING, "Could not make channels %s and %s compatible for bridge\n", chan->name, peer->name);
			ast_hangup(peer);
			return -1;
		}
		/* This runs sorta backwards, since we give the incoming channel control, as if it
		   were the person called. */
		if (option_verbose > 2) 
			ast_verbose(VERBOSE_PREFIX_3 "Channel %s connected to parked call %d\n", chan->name, park);

		memset(&config,0,sizeof(struct ast_bridge_config));
		ast_set_flag(&(config.features_callee), AST_FEATURE_REDIRECT);
		ast_set_flag(&(config.features_caller), AST_FEATURE_REDIRECT);
		config.timelimit = 0;
		config.play_warning = 0;
		config.warning_freq = 0;
		config.warning_sound=NULL;
		res = ast_bridge_call(chan,peer,&config);

		/* Simulate the PBX hanging up */
		if (res != AST_PBX_NO_HANGUP_PEER)
			ast_hangup(peer);
		return res;
	} else {
		/* XXX Play a message XXX */
		dres = ast_streamfile(chan, "pbx-invalidpark", chan->language);
		if (!dres)
	    		dres = ast_waitstream(chan, "");
		 else {
			ast_log(LOG_WARNING, "ast_streamfile of %s failed on %s\n", "pbx-invalidpark", chan->name);
			dres = 0;
		}
		if (option_verbose > 2) 
			ast_verbose(VERBOSE_PREFIX_3 "Channel %s tried to talk to non-existant parked call %d\n", chan->name, park);
		res = -1;
	}
	LOCAL_USER_REMOVE(u);
	return res;
}

static int handle_parkedcalls(int fd, int argc, char *argv[])
{
	struct parkeduser *cur;

	ast_cli(fd, "%4s %25s (%-15s %-12s %-4s) %-6s \n", "Num", "Channel"
		, "Context", "Extension", "Pri", "Timeout");

	ast_mutex_lock(&parking_lock);

	cur = parkinglot;
	while(cur) {
		ast_cli(fd, "%4d %25s (%-15s %-12s %-4d) %6lds\n"
			,cur->parkingnum, cur->chan->name, cur->context, cur->exten
			,cur->priority, cur->start.tv_sec + (cur->parkingtime/1000) - time(NULL));

		cur = cur->next;
	}

	ast_mutex_unlock(&parking_lock);

	return RESULT_SUCCESS;
}

static char showparked_help[] =
"Usage: show parkedcalls\n"
"       Lists currently parked calls.\n";

static struct ast_cli_entry showparked =
{ { "show", "parkedcalls", NULL }, handle_parkedcalls, "Lists parked calls", showparked_help };
/* Dump lot status */
static int manager_parking_status( struct mansession *s, struct message *m )
{
	struct parkeduser *cur;
	char *id = astman_get_header(m,"ActionID");
	char idText[256] = "";

	if (id && !ast_strlen_zero(id))
		snprintf(idText,256,"ActionID: %s\r\n",id);

	astman_send_ack(s, m, "Parked calls will follow");

        ast_mutex_lock(&parking_lock);

        cur=parkinglot;
        while(cur) {
			ast_mutex_lock(&s->lock);
                ast_cli(s->fd, "Event: ParkedCall\r\n"
			"Exten: %d\r\n"
			"Channel: %s\r\n"
			"Timeout: %ld\r\n"
			"CallerID: %s\r\n"
			"CallerIDName: %s\r\n"
			"%s"
			"\r\n"
                        ,cur->parkingnum, cur->chan->name
                        ,(long)cur->start.tv_sec + (long)(cur->parkingtime/1000) - (long)time(NULL)
			,(cur->chan->cid.cid_num ? cur->chan->cid.cid_num : "")
			,(cur->chan->cid.cid_name ? cur->chan->cid.cid_name : "")
			,idText);
			ast_mutex_unlock(&s->lock);

            cur = cur->next;
        }

	ast_cli(s->fd,
	"Event: ParkedCallsComplete\r\n"
	"%s"
	"\r\n",idText);

        ast_mutex_unlock(&parking_lock);

        return RESULT_SUCCESS;
}


static int load_config(void) 
{
	int start = 0, end = 0;
	struct ast_context *con = NULL;
	struct ast_config *cfg = NULL;
	struct ast_variable *var = NULL;
	
	transferdigittimeout = DEFAULT_TRANSFER_DIGIT_TIMEOUT;
	featuredigittimeout = DEFAULT_FEATURE_DIGIT_TIMEOUT;

	cfg = ast_load("features.conf");
	if (!cfg) {
		cfg = ast_load("parking.conf");
		if (cfg)
			ast_log(LOG_NOTICE, "parking.conf is deprecated in favor of 'features.conf'.  Please rename it.\n");
	}
	if (cfg) {
		var = ast_variable_browse(cfg, "general");
		while(var) {
			if (!strcasecmp(var->name, "parkext")) {
				strncpy(parking_ext, var->value, sizeof(parking_ext) - 1);
			} else if (!strcasecmp(var->name, "context")) {
				strncpy(parking_con, var->value, sizeof(parking_con) - 1);
			} else if (!strcasecmp(var->name, "parkingtime")) {
				if ((sscanf(var->value, "%d", &parkingtime) != 1) || (parkingtime < 1)) {
					ast_log(LOG_WARNING, "%s is not a valid parkingtime\n", var->value);
					parkingtime = DEFAULT_PARK_TIME;
				} else
					parkingtime = parkingtime * 1000;
			} else if (!strcasecmp(var->name, "parkpos")) {
				if (sscanf(var->value, "%i-%i", &start, &end) != 2) {
					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);
				} else {
					parking_start = start;
					parking_stop = end;
				}
			} else if (!strcasecmp(var->name, "adsipark")) {
				adsipark = ast_true(var->value);
			} else if (!strcasecmp(var->name, "transferdigittimeout")) {
				if ((sscanf(var->value, "%d", &transferdigittimeout) != 1) || (transferdigittimeout < 1)) {
					ast_log(LOG_WARNING, "%s is not a valid transferdigittimeout\n", var->value);
					transferdigittimeout = DEFAULT_TRANSFER_DIGIT_TIMEOUT;
				} else
					transferdigittimeout = transferdigittimeout * 1000;
			} else if (!strcasecmp(var->name, "featuredigittimeout")) {
				if ((sscanf(var->value, "%d", &featuredigittimeout) != 1) || (transferdigittimeout < 1)) {
					ast_log(LOG_WARNING, "%s is not a valid featuredigittimeout\n", var->value);
					featuredigittimeout = DEFAULT_FEATURE_DIGIT_TIMEOUT;
				}
			} else if (!strcasecmp(var->name, "courtesytone")) {
				strncpy(courtesytone, var->value, sizeof(courtesytone) - 1);
			} else if (!strcasecmp(var->name, "xfersound")) {
				strncpy(xfersound, var->value, sizeof(xfersound) - 1);
			} else if (!strcasecmp(var->name, "xferfailsound")) {
				strncpy(xferfailsound, var->value, sizeof(xferfailsound) - 1);
			} else if (!strcasecmp(var->name, "pickupexten")) {
				strncpy(pickup_ext, var->value, sizeof(pickup_ext) - 1);
			}
			var = var->next;
		}
		unmap_features();
		var = ast_variable_browse(cfg, "featuremap");
		while(var) {
			if (remap_feature(var->name, var->value))
				ast_log(LOG_NOTICE, "Unknown feature '%s'\n", var->name);
			var = var->next;
		}
		ast_destroy(cfg);
	}
	
	if (con)
		ast_context_remove_extension2(con, ast_parking_ext(), 1, registrar);
	
	if (!(con = ast_context_find(parking_con))) {
		if (!(con = ast_context_create(NULL, parking_con, registrar))) {
			ast_log(LOG_ERROR, "Parking context '%s' does not exist and unable to create\n", parking_con);
			return -1;
		}
	}
	return ast_add_extension2(con, 1, ast_parking_ext(), 1, NULL, NULL, parkcall, strdup(""),free, registrar);
}

int reload(void) {
	return load_config();
}

int load_module(void)
{
	int res;
	if ((res = load_config()))
		return res;
	ast_cli_register(&showparked);
	ast_pthread_create(&parking_thread, NULL, do_parking_thread, NULL);
	res = ast_register_application(parkedcall, park_exec, synopsis, descrip);
	if (!res)
		res = ast_register_application(parkcall, park_call_exec, synopsis2, descrip2);
	if (!res) {
		ast_manager_register( "ParkedCalls", 0, manager_parking_status, "List parked calls" );
	}
	return res;
}

int ast_pickup_call(struct ast_channel *chan)
{
	struct ast_channel *cur;
	int res = -1;
	cur = ast_channel_walk_locked(NULL);
	while(cur) {
		if (!cur->pbx && 
			(cur != chan) &&
			(chan->pickupgroup & cur->callgroup) &&
			((cur->_state == AST_STATE_RINGING) ||
			 (cur->_state == AST_STATE_RING))) {
			 	break;
		}
		ast_mutex_unlock(&cur->lock);
		cur = ast_channel_walk_locked(cur);
	}
	if (cur) {
		if (option_debug)
			ast_log(LOG_DEBUG, "Call pickup on chan '%s' by '%s'\n",cur->name, chan->name);
		res = ast_answer(chan);
		if (res)
			ast_log(LOG_WARNING, "Unable to answer '%s'\n", chan->name);
		res = ast_queue_control(chan, AST_CONTROL_ANSWER);
		if (res)
			ast_log(LOG_WARNING, "Unable to queue answer on '%s'\n", chan->name);
		res = ast_channel_masquerade(cur, chan);
		if (res)
			ast_log(LOG_WARNING, "Unable to masquerade '%s' into '%s'\n", chan->name, cur->name);		/* Done */
		ast_mutex_unlock(&cur->lock);
	} else	{
		if (option_debug)
			ast_log(LOG_DEBUG, "No call pickup possible...\n");
	}
	return res;
}

int unload_module(void)
{
	STANDARD_HANGUP_LOCALUSERS;

	ast_manager_unregister( "ParkedCalls" );
	ast_cli_unregister(&showparked);
	ast_unregister_application(parkcall);
	return ast_unregister_application(parkedcall);
}

char *description(void)
{
	return "Call Parking Resource";
}

int usecount(void)
{
	/* Never allow parking to be unloaded because it will
	   unresolve needed symbols in the dialer */
#if 0
	int res;
	STANDARD_USECOUNT(res);
	return res;
#else
	return 1;
#endif
}

char *key()
{
	return ASTERISK_GPL_KEY;
}