File: rate_engine.c

package info (click to toggle)
rate-engine 0.5.4-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 176 kB
  • ctags: 188
  • sloc: ansic: 1,486; makefile: 84; sql: 81
file content (2126 lines) | stat: -rw-r--r-- 53,846 bytes parent folder | download
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
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
/*
 * Do rate lookups and set destination route and maximum call length based on that
 * 
 * Copyright (C) 2003 by Troll Phone Networks AS
 *
 * This program is distributed under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2, or (at your
 * option) any later version.
 *
 *	$Id: rate_engine.c,v 1.26 2004/08/26 16:50:18 tholo Exp $
 */

#ifdef __linux__
#define _GNU_SOURCE
#endif

#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <pthread.h>

#include <mysql/mysql.h>

#include <pcre.h>
#include "pcre_subst.h"

#include <asterisk/file.h>
#include <asterisk/config.h>
#include <asterisk/logger.h>
#include <asterisk/channel.h>
#include <asterisk/pbx.h>
#include <asterisk/module.h>
#include <asterisk/options.h>
#include <asterisk/cli.h>
#include <asterisk/manager.h>
#include <asterisk/utils.h>

static char *tdesc = "Call Routing and Rating Application";
static char *cdr_name = "ratecall";
static char *routecall_app = "RouteCall";
static char *routecall_synopsis = "Do cost based routing of a call and set call time limit";
static char *routecall_descrip =
"  RouteCall(extension[|flags]): Does Least Cost Routing of a call, and\n"
"sets  an  absolute timeout  on  call length  based on customers credit\n"
"worthiness.  If there exists a priority n + 101, and no route could be\n"
"found,  then the  channel  will be set up to continue at that priority\n"
"level.\n"
"  If a route  is  found, a dialstring suitable  for  use with the Dial\n"
"application is created in the variable ${DESTINATIONnn}, to be used as\n"
"Dial(${DESTINATIONnn}) where 'nn' is a number  from 1 and up, with the\n"
"route in ${DESTINATION1} being the lowest-cost route found,  the route\n"
"in  ${DESTINATION2} being  the  next  lowest rate found and so on.  An\n"
"AbsoluteTimeout limit may also be set for the call.\n"
"  Always returns 0.\n";

STANDARD_LOCAL_USER;

LOCAL_USER_DECL;

AST_MUTEX_DEFINE_STATIC(ratelock);

static MYSQL mysql;
static char *systemname;

static pthread_t poster_thread;
static int cancel_poster = 0;
static pthread_mutex_t poster_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t poster_cond = PTHREAD_COND_INITIALIZER;

static int warn_threshold = 500;	/* Start giving warnings if CDR queue is this long */
static int drop_threshold = 1000;	/* Start dropping entries if CDR queue is this long */
static int warn_freq = 25;		/* Warn every this many entries only */
static int queuelen = 0;

typedef struct cdr_queue_t {
	struct cdr_queue_t *next;
	char *cdrquery;
	size_t cdrlen;
} cdr_queue_t;

static cdr_queue_t *queue_head = NULL, *queue_tail = NULL;

static char *dbhost = NULL, *dbuser = NULL, *dbpass = NULL, *dbname = NULL, *dbsock = NULL;
static char *table_cdr = NULL, *table_error = NULL, *table_egress = NULL, *table_cost = NULL;
static int dbport = 0, connected = 0, avg_call_length = 0;
static int reloadevery = 0;
static time_t lastreload = 0;
static int num_egress = 0, num_rate = 0;

typedef struct egress_t {
    int route_id;
    char *technology;
    char *peer;
    pcre *pcre;
    pcre_extra *extra;
    char *substitute;
    char *description;
} egress_t;

static egress_t *new_egress(void);
static void free_egress(egress_t *);

typedef struct rate_t {
    int rate_id;
    int route_id;
    egress_t *egress;
    char iso[3];
    char type[4];
    char *country;
    char *extra;
    char prefix[11];
    time_t active_date;
    time_t expires_date;
    int firstperiod;
    int periods;
    int startcost;
    int periodcost;
    int trialcost;
} rate_t;

static rate_t *new_rate(void);
static void free_rate(rate_t *);

typedef struct splayval_t {
    struct splayval_t *next;
    egress_t *egress;
    rate_t *rate;
} splayval_t;

typedef struct splay_t {
    char *key;
    void *value;
    int sentinel;
    struct splay_t *left;
    struct splay_t *right;
    struct splay_t *forward;
    struct splay_t *back;
    struct splay_t *parent;
} splay_t;

static splay_t *rates = NULL;
static splay_t *egresses = NULL;

static splay_t *new_splay(void);
static void free_splay(splay_t *);
static splay_t *insert_splay(splay_t *tree, const char *skey, void *value);
static splay_t *search_splay(splay_t *tree, const char *skey);
static splay_t *splay_root(splay_t *tree);
static splay_t *splay_first(splay_t *tree);
#if 0
static splay_t *splay_last(splay_t *tree);
#endif
static splay_t *splay_next(splay_t *node);
static splay_t *splay_prev(splay_t *node);
static splay_t *splay_null(splay_t *tree);
static void splay_delete(splay_t *node);
static splay_t *splay_find_nearest(splay_t *tree, const char *skey, int *cmpval);
static void splay(splay_t *node);

static void clear_egresses(void);
static void inject_egress(egress_t *);
static void clear_rates(void);
static void inject_rate(rate_t *);
static int load_rates(int);

/*
 * Find the Least Cost Route for a given number, and construct
 * a dial string suitable for use with the Dial application to
 * call using that route.  Also make available any other routes
 * sorted by least expensive to most expensive
 *
 * The dial strings are put in channel variables DESTINATIONxx
 * where "xx" is a number from 1 to N.  Also the cost values
 * are put in a matching FIRSTLEN, RESTLEN, STARTCOST and
 * PERIODCOST variables to be picked up by the CDR part to
 * calculate actual call cost.
 */
static int routecall_exec(struct ast_channel *chan, void *data)
{
    char destvar[20], firstvar[20], restvar[20], startcost[20], periodcost[20];
    char trialcost[20];
    char *args, *number, *flags, *destination, *sub;
    int res = 0, maxcall = 0, i, cmpval;
    struct localuser *u;
    char tempstr[16];
    splayval_t *val;
    splay_t *s;
    time_t now;

    /*
     * If we should load rates automatically, see if they have
     * expired, and if so, try to reload
     */
    if (reloadevery &&
	lastreload + reloadevery <= time(NULL)) {
	load_rates(0);
    }

    /*
     * Verify that arguments were supplied
     */
    if (data == NULL || *(char *)data == '\0') {
	ast_log(LOG_WARNING, "RouteCall requires an argument (number[|flags])\n");
	return -1;
    }

    LOCAL_USER_ADD(u);

    /*
     * Parse out arguments to number and (optional) flags
     */
    args = ast_strdupa((char *)data);
    number = strsep(&args, "|");
    flags = strsep(&args, "\0");

    /*
     * Make empty strings be NULL pointers instead
     */
    if (number && *number == '\0')
	number = NULL;
    if (flags && *flags == '\0')
	flags = NULL;

    /*
     * We can't do any routing if we don't have any rates or
     * egress routes loaded
     */
    if (rates == NULL || egresses == NULL) {
	ast_log(LOG_WARNING, "RouteCall requires that rates and egress routes exists\n");

	/*
	 * Jump to priority + 101, since we got an error
	 */
	if (ast_exists_extension(chan, chan->context, chan->exten, chan->priority + 101, chan->callerid))
	    chan->priority += 100;
	else
	    res = -1;

	LOCAL_USER_REMOVE(u);

	return res;
    }

    /*
     * Make sure only one thread access the database at a time
     */
    ast_mutex_lock(&ratelock);

    /*
     * If no phone number was supplied, error out
     */
    if (!number)
	goto errout;

    /*
     * Search the in-memory splay tree for a prefix match
     */
    s = splay_find_nearest(rates, number, &cmpval);

    /*
     * cmpval != 0 means inexact match, make sure it is a
     * prefix match if at all possible
     */
    if (cmpval && s) {
	/*
	 * We got a non-matchin key back -- if it is not a prefix,
	 * retrieve the next smaller until we run out of prefixes
	 * to try or we find a usable prefix (we are guaranteed
	 * that the returned key is larger than or equal to the
	 * one we searched for if such a key exist)
	 */
	while (s != splay_null(rates) &&
	       strncasecmp(number, s->key, strlen(s->key)) != 0)
	    s = splay_prev(s);
	if (s != splay_null(rates) &&
	    strncasecmp(number, s->key, strlen(s->key)) == 0) {
	    cmpval = 0;
	}
    }
    
    /*
     * If we could not find a match for the number, we should
     * log an entry to the error table so that there will be
     * a record of a non-matched number for future reference,
     * and then return failure
     */
    if (cmpval != 0) {
	ast_log(LOG_WARNING, "No match for phone number %s in rate tables\n", number);
	goto errout;
    }

    /*
     * Optimize by moving matched prefixes towards the top
     * of the splay tree
     */
    splay(s);

    /*
     * Get current time, so we can skip rate entries that
     * are expired or not yet valid
     */
    time(&now);

    /*
     * The in-memory rates are already sorted from least to
     * most expensive
     */
    for (i = 0, val = s->value; val; val = val->next) {
	/*
	 * If we do not have the actual egress route, skip the rate
	 */
	if (val->rate->egress == NULL) {
	    ast_log(LOG_WARNING, "Rate without egress route for prefix '%s'\n", s->key);
	    continue;
	}

	/*
	 * If the rate is not yet active, or if it has expired,
	 * skip it
	 */
	if ((val->rate->active_date &&
	     val->rate->active_date > now) ||
	    (val->rate->expires_date &&
	     val->rate->expires_date > now))
	    continue;

	snprintf(destvar, sizeof(destvar), "DESTINATION%d", i + 1);
	snprintf(firstvar, sizeof(firstvar), "FIRSTLEN%d", i + 1);
	snprintf(restvar, sizeof(restvar), "RESTLEN%d", i + 1);
	snprintf(startcost, sizeof(startcost), "STARTCOST%d", i + 1);
	snprintf(periodcost, sizeof(periodcost), "PERIODCOST%d", i + 1);
	snprintf(trialcost, sizeof(trialcost), "TRIALCOST%d", i + 1);

	sub = malloc(strlen(val->rate->egress->technology) +
		     strlen(val->rate->egress->peer) +
		     strlen(val->rate->egress->substitute) +
		     3);	/* Two /'s and a NUL */
	strcpy(sub, val->rate->egress->technology);
	strcat(sub, "/");
	strcat(sub, val->rate->egress->peer);
	strcat(sub, "/");
	strcat(sub, val->rate->egress->substitute);
	destination = pcre_subst(val->rate->egress->pcre, val->rate->egress->extra, number, strlen(number), 0, 0, sub);
	if (sub)
	    free(sub);

	res = 0;
	pbx_builtin_setvar_helper(chan, destvar, destination);
	snprintf(tempstr, sizeof(tempstr), "%d", val->rate->firstperiod);
	pbx_builtin_setvar_helper(chan, firstvar, tempstr);
	snprintf(tempstr, sizeof(tempstr), "%d", val->rate->periods);
	pbx_builtin_setvar_helper(chan, restvar, tempstr);
	snprintf(tempstr, sizeof(tempstr), "%d", val->rate->startcost);
	pbx_builtin_setvar_helper(chan, startcost, tempstr);
	snprintf(tempstr, sizeof(tempstr), "%d", val->rate->periodcost);
	pbx_builtin_setvar_helper(chan, periodcost, tempstr);
	snprintf(tempstr, sizeof(tempstr), "%d", val->rate->trialcost);
	pbx_builtin_setvar_helper(chan, trialcost, tempstr);
	if (option_verbose > 3) {
	    if (i)
		ast_verbose( VERBOSE_PREFIX_4 "Alternate route as %s\n", destination);
	    else
		ast_verbose( VERBOSE_PREFIX_4 "Route as %s\n", destination);
	}
	pcre_free(destination);
	i++;
    }

    /*
     * If no prefix rates actually had egress routes or were valid,
     * we need to error out here -- should be try a shorter prefix
     * for this case?
     */
    if (i == 0) {
	ast_log(LOG_WARNING, "No valid egress routes for prefix '%s'\n", s->key);
	goto errout;
    }

    /*
     * Release the lock
     */
    ast_mutex_unlock(&ratelock);

    /*
     * If we could not find a match for the number, we should
     * log an entry to the error table so that there will be
     * a record of a non-matched number for future reference,
     * and then return failure
     */
    if (res < 0) {
	res = 0;
	ast_log(LOG_WARNING, "No route could be made for phone number %s\n", number);
	goto errout;
    }

    /*
     * Set an AbsoluteTimeout on the call, based on customer
     * credit worthiness and call cost for the destination
     * we have found a route for
     */
    ast_channel_setwhentohangup(chan, maxcall);
    if (option_verbose > 3)
	ast_verbose( VERBOSE_PREFIX_4 "Set AbsoluteTimeout to %d\n", maxcall);

    goto out;
errout:
    /*
     * Release the lock
     */
    ast_mutex_unlock(&ratelock);

    /*
     * Jump to priority + 101, since we got an error
     */
    if (res == 0 && ast_exists_extension(chan, chan->context, chan->exten, chan->priority + 101, chan->callerid))
	chan->priority += 100;
    else
	res = -1;

out:
    LOCAL_USER_REMOVE(u);

    return res;
}

/*
 * Called when a call is completed, to log call details.  We
 * extend this to calculate actual call costs based on the
 * route used, by using saved rate information from the LCR
 * routine.
 *
 * We also pick up ANI from the channel structure, to get
 * slightly better CDR data.
 */
static int cdr_ratecall(struct ast_cdr *cdr)
{
    char *ani, *src, *dst, *dcontext, *channel, *dstchannel, *lastapp, *lastdata;
    char starttime[32], answertime[32], endtime[32], destvar[32], firstvar[32];
    char trialvar[32];
    int len, i, first = 0, start = 0, each = 0, rest = 0, trial = 0;
    char *account, *uniqueid, *destination = "", *end;
    char restvar[32], startvar[32], periodvar[32];
    struct ast_channel *chan;
    long long cost = 0;
    cdr_queue_t *q;
    struct tm tm;
    time_t t;

    /*
     * If we should load rates automatically, see if they have
     * expired, and if so, try to reload
     */
    if (reloadevery &&
	lastreload + reloadevery <= time(NULL)) {
	load_rates(0);
    }

    /*
     * Find which channel this CDR entry was generated from -- this
     * will allow us to retrieve channel variables and other info
     * that is needed for accurate logging
     */
    chan = ast_channel_walk_locked(NULL);
    while (chan && chan->cdr != cdr) {
	ast_mutex_unlock(&chan->lock);
	chan = ast_channel_walk_locked(chan);
    }
    if (chan) {
	for (i = 1;; i++) {
	    snprintf(destvar, sizeof(destvar), "DESTINATION%d", i);
	    snprintf(firstvar, sizeof(firstvar), "FIRSTLEN%d", i);
	    snprintf(restvar, sizeof(restvar), "RESTLEN%d", i);
	    snprintf(startvar, sizeof(startvar), "STARTCOST%d", i);
	    snprintf(periodvar, sizeof(periodvar), "PERIODCOST%d", i);
	    snprintf(trialvar, sizeof(trialvar), "TRIALCOST%d", i);

	    dst = pbx_builtin_getvar_helper(chan, destvar);
	    if (dst == NULL)
		break;
	    if (strcmp(dst, cdr->lastdata) == 0) {
		dst = pbx_builtin_getvar_helper(chan, firstvar);
		first = strtoul(dst, &end, 10);
		dst = pbx_builtin_getvar_helper(chan, restvar);
		rest = strtoul(dst, &end, 10);
		dst = pbx_builtin_getvar_helper(chan, startvar);
		start = strtoul(dst, &end, 10);
		dst = pbx_builtin_getvar_helper(chan, periodvar);
		each = strtoul(dst, &end, 10);
		dst = pbx_builtin_getvar_helper(chan, trialvar);
		trial = strtoul(dst, &end, 10);
		break;
	    }
	}
	ast_mutex_unlock(&chan->lock);
    }

    /*
     * Make sure only one thread access the database at a time
     */
    ast_mutex_lock(&ratelock);

    /*
     * Make MySQL-safe copies of all strings
     */
    if ((src = alloca((len = strlen(cdr->src)) * 2 + 1)) != NULL)
	mysql_real_escape_string(&mysql, src, cdr->src, len);

    /*
     * Try to pick up real ANI if that exists
     */
    if (chan && chan->ani) {
	if ((ani = alloca((len = strlen(chan->ani)) * 2 + 1)) != NULL)
	    mysql_real_escape_string(&mysql, ani, chan->ani, len);
    }
    else
	ani = src;
    if ((dst = alloca((len = strlen(cdr->dst)) * 2 + 1)) != NULL)
	mysql_real_escape_string(&mysql, dst, cdr->dst, len);
    if ((dcontext = alloca((len = strlen(cdr->dcontext)) * 2 + 1)) != NULL)
	mysql_real_escape_string(&mysql, dcontext, cdr->dcontext, len);
    if ((channel = alloca((len = strlen(cdr->channel)) * 2 + 1)) != NULL)
	mysql_real_escape_string(&mysql, channel, cdr->channel, len);
    if ((dstchannel = alloca((len = strlen(cdr->dstchannel)) * 2 + 1)) != NULL)
	mysql_real_escape_string(&mysql, dstchannel, cdr->dstchannel, len);
    if ((lastapp = alloca((len = strlen(cdr->lastapp)) * 2 + 1)) != NULL)
	mysql_real_escape_string(&mysql, lastapp, cdr->lastapp, len);
    if ((lastdata = alloca((len = strlen(cdr->lastdata)) * 2 + 1)) != NULL)
	mysql_real_escape_string(&mysql, lastdata, cdr->lastdata, len);
    if ((account = alloca((len = strlen(cdr->accountcode)) * 2 + 1)) != NULL)
	mysql_real_escape_string(&mysql, account, cdr->accountcode, len);
    if ((uniqueid = alloca((len = strlen(cdr->uniqueid)) * 2 + 1)) != NULL)
	mysql_real_escape_string(&mysql, uniqueid, cdr->uniqueid, len);

    /*
     * Release database lock
     */
    ast_mutex_unlock(&ratelock);

    /*
     * If any allocations failed, bail with an error
     */
    if (ani == NULL || dcontext == NULL || channel == NULL || dstchannel == NULL ||
	lastapp == NULL || lastdata == NULL || uniqueid == NULL) {
	ast_log(LOG_ERROR, "Out of memory!\n");
	return -1;
    }

    t = cdr->start.tv_sec;
    localtime_r(&t,&tm);
    strftime(starttime, sizeof(starttime), "%Y-%m-%d %T", &tm);
    t = cdr->answer.tv_sec;
    localtime_r(&t,&tm);
    strftime(answertime, sizeof(answertime), "%Y-%m-%d %T", &tm);
    t = cdr->end.tv_sec;
    localtime_r(&t,&tm);
    strftime(endtime, sizeof(endtime), "%Y-%m-%d %T", &tm);

    /*
     * Charge for answered calls
     */
    if (cdr->disposition == AST_CDR_ANSWERED &&
	(first || rest) && (start || each)) {
	/*
	 * Billable seconds is really the number of whole
	 * periods, plus the length of the first period
	 * which often is a different length, and/or has
	 * a different price
	 */
	cdr->billsec = (cdr->billsec - first < 0 ? 0 : cdr->billsec - first + rest - 1) / rest * rest;

	/*
	 * Cost of the call is the starting cost (for the
	 * first period), plus the price for each full
	 * period thereafter
	 */
	cost = start + cdr->billsec / rest * each;

	/*
	 * Don't forget to actually add inn the length of
	 * that first period
	 */
	cdr->billsec += first;
    }
    /*
     * Charge for unanswered or busy calls
     */
    else if (cdr->disposition == AST_CDR_NOANSWER ||
	     cdr->disposition == AST_CDR_BUSY) {
	cost = trial;
    }

    /*
     * Allocate a CDR queue entry
     */
    if ((q = malloc(sizeof(cdr_queue_t))) == NULL) {
	ast_log(LOG_WARNING, "Out of memory\n");
	return -1;
    }
    q->next = NULL;

    q->cdrlen = asprintf(&q->cdrquery,
			 "INSERT INTO %s "
			 "(callDate,endDate,ANI,callerID,calledNumber,calledContext,"
			 "sourceChannel,destinationChannel,lastApplication,lastData,"
			 "callDuration,billableDuration,callDisposition,amaFlags,"
			 "accountCode,destinationDescription,callCost,uniqueID,"
			 "handlingSystem) VALUES "
			 "('%s','%s','%s','%s','%s','%s','%s','%s','%s',"
			 "'%s',%i,%i,'%s','%s','%s','%s',%lld,'%s','%s')",
			 table_cdr,
			 starttime, endtime, ani, src, dst, dcontext,
			 channel, dstchannel, lastapp, lastdata, cdr->duration,
			 cdr->billsec, ast_cdr_disp2str(cdr->disposition),
			 ast_cdr_flags2str(cdr->amaflags), account,
			 destination, cost, uniqueid, systemname);

    /*
     * Acquire shared data lock
     */
    pthread_mutex_lock(&poster_lock);

    /*
     * Only add to queue if we are below the maximum threshold
     */
    if (queuelen < drop_threshold) {
	/*
	 * Append CDR entry to queue
	 */
	if (queue_tail != NULL)
	    queue_tail-> next =q;
	queue_tail = q;
	if (queue_head == NULL)
	    queue_head = q;

	/*
	 * Warn if we are getting too long a queue (but only once every
	 * warn_freq entries)
	 */
	if (++queuelen > warn_threshold &&
	    warn_freq &&
	    ((queuelen - warn_threshold) % warn_freq) == 0)
	    ast_log(LOG_WARNING, "Rating Engine CDR Queue now at %d entries!\n", queuelen);
    }
    else {
	ast_log(LOG_ERROR, "Rating Engine CDR entry dropped!\n");
	free(q->cdrquery);
	free(q);
    }

    /*
     * Signal worker thread that there is data available
     */
    pthread_cond_signal(&poster_cond);

    /*
     * Release shared data lock
     */
    pthread_mutex_unlock(&poster_lock);

    return 0;
}

/*
 * Worker thread to actually post the CDR data to a
 * Rating Engine -- will not remove the entries from
 * queue if connecting to the Rating Engine fails,
 * or if sending the entries to it fails
 */
static void *poster_worker(void *arg)
{
    int isconnected = 0, fail;
    struct timespec ts;
    MYSQL poster_mysql;
    cdr_queue_t *q;

    ast_log(LOG_DEBUG, "Rating Engine poster thread started\n");

    /*
     * Get lock on shared data
     */
    pthread_mutex_lock(&poster_lock);

    /*
     * We need a timeout if there is something on the queue
     */
    ts.tv_sec = time(NULL) + 30;
    ts.tv_nsec = 0;

    /*
     * Initialize MySQL
     */
    mysql_init(&poster_mysql);
    if (mysql_real_connect(&poster_mysql, dbhost, dbuser, dbpass, dbname, dbport, dbsock, 0))
	isconnected = 1;
    else {
	ast_log(LOG_ERROR, "Failed to connect to MySQL database '%s': %s\n", dbname, mysql_error(&poster_mysql));
	isconnected = 0;
    }

    /*
     * Wait for [more] data to be available
     */
    for (;; (queue_head ?
	     (ts.tv_sec = time(NULL) + 30, ts.tv_nsec = 0, pthread_cond_timedwait(&poster_cond, &poster_lock, &ts)) :
	     pthread_cond_wait(&poster_cond, &poster_lock))) {

	ast_log(LOG_DEBUG, "Rating Engine poster thread processing\n");

	/*
	 * Check if we should stop processing
	 */
	if (cancel_poster) {
	    cancel_poster = 0;
	    break;
	}

	/*
	 * If we have to (re-)connect to a database, that might
	 * take a little while, so release the lock while we do
	 * that
	 */
	pthread_mutex_unlock(&poster_lock);

	/*
	 * If we are not connected to a database, try to connect
	 */
	if (!isconnected) {
	    if (mysql_real_connect(&poster_mysql, dbhost, dbuser, dbpass, dbname, dbport, dbsock, 0))
		isconnected = 1;
	    else {
		ast_log(LOG_ERROR, "Failed to connect to MySQL database '%s': %s\n", dbname, mysql_error(&poster_mysql));

		/*
		 * Reacquire the lock before we restart loop
		 */
		pthread_mutex_lock(&poster_lock);

		continue;
	    }
	}

	/*
	 * Try to verify that our database connection is still alive
	 */
	if (mysql_ping(&poster_mysql)) {
	    ast_log(LOG_ERROR, "Cannot talk to MySQL database '%s': %s\n",
		    dbname, mysql_error(&poster_mysql));
	    isconnected = 0;

	    /*
	     * Reacquire the lock before we restart loop
	     */
	    pthread_mutex_lock(&poster_lock);

	    continue;
	}

	/*
	 * We do have to reacquire the lock before we can actually
	 * touch the queue, however...
	 */
	pthread_mutex_lock(&poster_lock);

	/*
	 * Process CDR records on queue
	 */
	for (q = queue_head; q; q = queue_head) {

	    ast_log(LOG_DEBUG, "Attempting to write queue entry to database\n");

	    /*
	     * Update the queue head and tail
	     */
	    queue_head = q->next;
	    if (queue_head == NULL)
		queue_tail = NULL;
	    queuelen--;

	    /*
	     * Release the lock before doing potentially long operation
	     */
	    pthread_mutex_unlock(&poster_lock);

	    /*
	     * Perform query
	     */
	    if (mysql_real_query(&poster_mysql, q->cdrquery, q->cdrlen)) {
		fail = 1;
		ast_log(LOG_ERROR,"Failed to insert into database: %s\n", mysql_error(&poster_mysql));
	    }
	    else
		fail = 0;

	    /*
	     * Re-acquire the lock
	     */
	    pthread_mutex_lock(&poster_lock);

	    /*
	     * If we errored out of sending the CDR entry, put it back
	     * on the head of the queue, updating the queue as needed;
	     * be careful -- if we emptied the queue above, we have a
	     * new queue_head, and if not we have to set the tail too
	     */
	    if (fail) {
		ast_log(LOG_DEBUG, "Prepending failed CDR entry to Rating Engine queue\n");
		q->next = queue_head;
		queue_head = q;
		if (queue_tail == NULL)
		    queue_tail = q;
		queuelen++;
		break;
	    }

	    /*
	     * Otherwise, we successfully sent a queue entry, and should
	     * free the memory it used
	     */
	    free(q->cdrquery);
	    free(q);
	}
    }

    ast_log(LOG_DEBUG, "Rating Engine poster thread exiting\n");

    /*
     * Release the lock before exiting thread
     */
    pthread_mutex_unlock(&poster_lock);

    /*
     * Close connection if it is open
     */
    mysql_close(&poster_mysql);

    /*
     * Exit thread
     */
    return NULL;
}

/*
 * Load configuration settings from configuration file,
 * and do some minimal sanity checks on the information
 * loaded
 */
static int load_config(void)
{
    struct ast_variable *var;
    struct ast_config *cfg;
    char *cat, *e;

    /*
     * Lock the configuration, since we are about to change it
     */
    ast_mutex_lock(&ratelock);

    cfg = ast_load("rate_engine.conf");
    if (cfg) {
	cat = ast_category_browse(cfg, NULL);
	while (cat) {
	    var = ast_variable_browse(cfg, cat);

	    /*
	     * Global settings
	     */
	    if (strcasecmp(cat, "general") == 0) {
		while (var) {
		    /*
		     * Our system name -- used only for logging
		     */
		    if (strcasecmp(var->name, "system") == 0) {
			if (systemname)
			    free(systemname);
			systemname = strdup(var->value);
			if (option_verbose > 2)
			    ast_verbose(VERBOSE_PREFIX_3 "System Name: %s\n", var->value);
		    }
		    /*
		     * Host where our database is
		     */
		    else if (strcasecmp(var->name, "host") == 0) {
			if (dbhost)
			    free(dbhost);
			dbhost = strdup(var->value);
			if (option_verbose > 3)
			    ast_verbose(VERBOSE_PREFIX_4 "DB Host: %s\n", var->value);
		    }
		    /*
		     * Port for the database -- used only when
		     * host is set, and is not "localhost"
		     */
		    else if (strcasecmp(var->name, "port") == 0) {
			dbport = strtol(var->value, &e, 10);
			if (option_verbose > 3)
			    ast_verbose(VERBOSE_PREFIX_4 "DB Port: %s\n", var->value);
		    }
		    /*
		     * Unix domain socket -- used only when
		     * host is not set, or is set to "localhost"
		     */
		    else if (strcasecmp(var->name, "socket") == 0) {
			if (dbsock)
			    free(dbsock);
			dbsock = strdup(var->value);
			if (option_verbose > 3)
			    ast_verbose(VERBOSE_PREFIX_4 "DB Socket: %s\n", var->value);
		    }
		    /*
		     * Username to authenticate to the database
		     */
		    else if (strcasecmp(var->name, "username") == 0) {
			if (dbuser)
			    free(dbuser);
			dbuser = strdup(var->value);
			if (option_verbose > 3)
			    ast_verbose(VERBOSE_PREFIX_4 "DB Username: %s\n", var->value);
		    }
		    /*
		     * Password to authenticate to the database
		     */
		    else if (strcasecmp(var->name, "password") == 0) {
			if (dbpass)
			    free(dbpass);
			dbpass = strdup(var->value);
			if (option_verbose > 3)
			    ast_verbose(VERBOSE_PREFIX_4 "DB Password: [set]\n");
		    }
		    /*
		     * Name of database to be used
		     */
		    else if (strcasecmp(var->name, "database") == 0) {
			if (dbname)
			    free(dbname);
			dbname = strdup(var->value);
			if (option_verbose > 2)
			    ast_verbose(VERBOSE_PREFIX_3 "Database: %s\n", var->value);
		    }
		    /*
		     * How often to reload rate and egress information
		     */
		    else if (strcasecmp(var->name, "reloadevery") == 0) {
			reloadevery = strtol(var->value, &e, 10) * 60;
			if (option_verbose > 3) {
			    if (reloadevery)
				ast_verbose(VERBOSE_PREFIX_4 "Reload Rates: every %ss\n", var->value);
			    else
				ast_verbose(VERBOSE_PREFIX_4 "Reload Rates: manually\n");
			}
		    }
		    else {
			ast_log(LOG_WARNING, "Unrecognized variable '%s' in category '%s'\n",
				var->name, cat);
		    }
		    var = var->next;
		}
	    }

	    /*
	     * Settings for logging CDR data
	     */
	    else if (strcasecmp(cat, "cdr") == 0) {
		while (var) {
		    /*
		     * Table to log CDR entries to
		     */
		    if (strcasecmp(var->name, "table") == 0) {
			if (table_cdr)
			    free(table_cdr);
			table_cdr = strdup(var->value);
			if (option_verbose > 3)
			    ast_verbose(VERBOSE_PREFIX_4 "CDR Table: %s\n", var->value);
		    }
		    /*
		     * Backlog threshold before we start dropping
		     * CDR entries (if database unavailable)
		     */
		    else if (strcasecmp(var->name, "dropthres") == 0) {
			drop_threshold = strtol(var->value, &e, 10);
			if (option_verbose > 3)
			    ast_verbose(VERBOSE_PREFIX_4 "Drop Threshold: %s entries\n", var->value);
		    }
		    /*
		     * Backlog threshold before we start warning
		     * about database being backed up or unavailable
		     */
		    else if (strcasecmp(var->name, "warnthres") == 0) {
			warn_threshold = strtol(var->value, &e, 10);
			if (option_verbose > 3)
			    ast_verbose(VERBOSE_PREFIX_4 "Warning Threshold: %s entries\n", var->value);
		    }
		    /*
		     * Frequency of warnings once we are at or above
		     * the warning threshold
		     */
		    else if (strcasecmp(var->name, "warnfreq") == 0) {
			warn_freq = strtol(var->value, &e, 10);
			if (option_verbose > 3)
			    ast_verbose(VERBOSE_PREFIX_4 "Warning Frequency: every %s entries\n", var->value);
		    }
		    else {
			ast_log(LOG_WARNING, "Unrecognized variable '%s' in category '%s'\n",
				var->name, cat);
		    }
		    var = var->next;
		}
	    }

	    /*
	     * Configuration information for Least Cost Routing
	     */
	    else if (strcasecmp(cat, "route") == 0) {
		while (var) {
		    /*
		     * Table for logging when rate information
		     * for a prefix could not be found
		     */
		    if (strcasecmp(var->name, "errors") == 0) {
			if (table_error)
			    free(table_error);
			table_error = strdup(var->value);
			if (option_verbose > 3)
			    ast_verbose(VERBOSE_PREFIX_4 "Error Table: %s\n", var->value);
		    }
		    /*
		     * Table holding egress routes
		     */
		    else if (strcasecmp(var->name, "egress") == 0) {
			if (table_egress)
			    free(table_egress);
			table_egress = strdup(var->value);
			if (option_verbose > 3)
			    ast_verbose(VERBOSE_PREFIX_4 "Egress Table: %s\n", var->value);
		    }
		    /*
		     * Table holding rate information for prefixes
		     */
		    else if (strcasecmp(var->name, "cost") == 0) {
			if (table_cost)
			    free(table_cost);
			table_cost = strdup(var->value);
			if (option_verbose > 3)
			    ast_verbose(VERBOSE_PREFIX_4 "Cost Table: %s\n", var->value);
		    }
		    /*
		     * Average length of a phone call -- used to calculate
		     * lowest rates, due to imbalances with starting cost
		     * and cost per time unit on a call
		     */
		    else if (strcasecmp(var->name, "avglen") == 0) {
			avg_call_length = strtol(var->value, NULL, 10);
			if (option_verbose > 3)
			    ast_verbose(VERBOSE_PREFIX_4 "Average Call Length: %ss\n", var->value);
		    }
		    else {
			ast_log(LOG_WARNING, "Unrecognized variable '%s' in category '%s'\n",
				var->name, cat);
		    }
		    var = var->next;
		}
	    }
	    else {
		ast_log(LOG_WARNING, "Unrecognized category '%s'\n", cat);
	    }
	    cat = ast_category_browse(cfg, cat);
	}
    }
    ast_destroy(cfg);

    /*
     * Do some quick sanity checks
     */
    if (dbhost == NULL)
	ast_log(LOG_WARNING, "MySQL host not specified -- assuming localhost\n");
    if (dbname == NULL) {
	ast_log(LOG_WARNING, "MySQL database not specified -- assuming rating\n");
	dbname = strdup("rating");
    }
    if (dbuser == NULL) {
	ast_log(LOG_WARNING, "MySQL username not specified -- assuming root\n");
	dbuser = strdup("root");
    }
    if (table_egress == NULL) {
	ast_log(LOG_WARNING, "egress table not specified -- assuming 'egress'\n");
	table_egress = strdup("egress");
    }
    if (table_cost == NULL) {
	ast_log(LOG_WARNING, "cost table not specified -- assuming 'rate'\n");
	table_cost = strdup("rate");
    }
    if (table_cdr == NULL) {
	ast_log(LOG_WARNING, "cdr table not specified -- assuming 'cdr'\n");
	table_cdr = strdup("cdr");
    }
    if (avg_call_length == 0) {
	ast_log(LOG_WARNING, "Average Call Length not specified -- assuming 180s\n");
	avg_call_length = 180;
    }
    if (drop_threshold <= warn_threshold) {
	ast_log(LOG_WARNING, "Drop threshold must be larger than warning threshold, adjusting...\n");
	drop_threshold = warn_threshold * 2;
    }

    /*
     * Configuration has been loaded -- it is now safe to use
     */
    ast_mutex_unlock(&ratelock);

    return 0;
}

static void splay_rotate(splay_t *node)
{
    splay_t *parent, *grandparent;

    parent = node->parent;

    if (parent->sentinel)
	return;
  
    grandparent = parent->parent;

    if (parent->left == node) {
	parent->left = node->right;
	if (parent->left)
	    parent->left->parent = parent;
	node->right = parent;
    }
    else if (parent->right == node) {
	parent->right = node->left;
	if (parent->right)
	    parent->right->parent = parent;
	node->left = parent;
    }
    else {
	fprintf(stderr, "rotate: error: parent's children are not right\n");
	exit(1);
    }

    parent->parent = node;
    node->parent = grandparent;

    if (grandparent->sentinel) {
	grandparent->parent = node;
    }
    else if (grandparent->left == parent) {
	grandparent->left = node;
    }
    else if (grandparent->right == parent) {
	grandparent->right = node;
    }
    else {
	fprintf(stderr, "rotate: error: grandparent's children are not right\n");
	exit(1);
    }
}

static void splay(splay_t *node)
{
    splay_t *parent, *grandparent;
  
    if (node->sentinel)
	return;

    for (;;) {
	parent = node->parent;

	if (parent->sentinel)
	    return;
  
	grandparent = parent->parent;

	/*
	 * If the node's parent is the root of the tree, do one rotation
	 */
	if (grandparent->sentinel)
	    splay_rotate(node);
	/*
	 * If we have a zig-zig, then rotate my parent, then rotate me
	 */
	else if ((parent->left  == node && grandparent->left  == parent) ||
		 (parent->right == node && grandparent->right == parent)) {
	    splay_rotate(parent);
	    splay_rotate(node);
	}
	/*
	 * If we have a zig-zag, then rotate me twice
	 */
	else {
	    splay_rotate(node);
	    splay_rotate(node);
	}
    }
}

static splay_t *new_splay(void)
{
    splay_t *tree;

    tree = (splay_t *) malloc(sizeof(splay_t));

    tree->key = NULL;
    tree->value = NULL;
    tree->sentinel = 1;
    tree->forward = tree;
    tree->back = tree;
    tree->left = NULL;
    tree->right = NULL;
    tree->parent = NULL;

    return tree;
}

static splay_t *splay_root(splay_t *tree)
{
    return tree->parent;
}

static splay_t *splay_first(splay_t *tree)
{
    return tree->forward;
}

#if 0
static splay_t *splay_last(splay_t *tree)
{
    return tree->back;
}
#endif

static splay_t *splay_next(splay_t *node)
{
    return node->forward;
}

static splay_t *splay_prev(splay_t *node)
{
    return node->back;
}

static splay_t *splay_null(splay_t *tree)
{
    return tree;
}

static void free_splay(splay_t *tree)
{
    splay_t *ptr;

    for (;;) {
	ptr = splay_first(tree);
	if (!ptr->sentinel)
	    splay_delete(ptr);
	else {
	    free(ptr);
	    return;
	}
    }
}

static splay_t *splay_find_nearest(splay_t *tree, const char *skey, int *cmpval) 
{
    splay_t *s, *last;
    int cmp;

    last = tree;
    s = splay_root(tree);
    cmp = 1;

    while (s) {
	last = s;
	cmp = strcmp(skey, s->key);
	if (cmp == 0) {
	    *cmpval = 0;
	    return s;
	}
	else if (cmp < 0)
	    s = s->left;
	else
	    s = s->right;
    }

    *cmpval = cmp;
    return last;
}
 
static splay_t *search_splay(splay_t *tree, const char *skey)
{
    int cmpval;
    splay_t *s;

    s = splay_find_nearest(tree, skey, &cmpval);
    splay(s);
    if (cmpval == 0)
	return s;
    else
	return NULL;
}

static splay_t *splay_insert(const char *skey, void *val, splay_t *parent, int cmpval)
{
    splay_t *s;

    s = (splay_t *) malloc(sizeof(splay_t));
    s->sentinel = 0;
    s->parent = parent;
    s->left = NULL;
    s->right = NULL;
    s->key = strdup(skey);
    s->value = val;

    /*
     * Set the parent's correct child pointer.  The only
     * subtle case here is when the key is already in 
     * the tree -- then we need to find a leaf node 
     * to use as a parent
     *
     * When we're done here, parent should point to the
     * new node's successor in the linked list
     */
    if (parent->sentinel)
	parent->parent = s;
    else {
	if (cmpval == 0) {   /* If the key is already in the
			      * tree, try to insert a new one as the
			      * node's right child.  If the node already
			      * has a right child, then try to insert the
			      * new one as a left child.  If there is already
			      * a left child, then go to parent-flink and 
			      * insert the node as its left child.
			      */
	    if (parent->right == NULL)
		cmpval = 1;
	    else if (parent->left == NULL)
		cmpval = -1;
	    else {
		parent = parent->forward;
		s->parent = parent;
		cmpval = -1;
	    }
	}
	if (cmpval > 0) {   /* Insert as right child */
	    if (parent->right != NULL) {
		fprintf(stderr, "splay_insert error: parent->right != NULL");
		exit(1);
	    }
	    parent->right = s;
	    parent = parent->forward;
	}
	else {
	    if (parent->left != NULL) {
		fprintf(stderr, "splay_insert error: parent->left != NULL");
		exit(1);
	    }
	    parent->left = s;
	}
    }

    s->forward = parent;
    s->back = parent->back;
    s->forward->back = s;
    s->back->forward = s;
    splay(s);
    return s;
}

static splay_t *insert_splay(splay_t *tree, const char *skey, void *val)
{
    splay_t *parent;
    int cmpval;

    parent = splay_find_nearest(tree, skey, &cmpval);
    return splay_insert(skey, val, parent, cmpval);
}

static void splay_delete(splay_t *node)
{
    splay_t *left, *right, *tree, *newroot;
    splayval_t *val;

    splay(node);

    tree = node->parent;

    left = node->left;
    right = node->right;
    newroot = node->forward;

    node->forward->back = node->back;
    node->back->forward = node->forward;

    if (node->key)
	free(node->key);
    val = node->value;
    while (val) {
	if (val->rate)
	    free_rate(val->rate);
	if (val->egress)
	    free_egress(val->egress);
	node->value = val->next;
	free(val);
	val = node->value;
    }
    free(node);

    if (right == NULL && left == NULL) {
	tree->parent = NULL;
    }
    else if (right == NULL) {
	tree->parent = left;
	left->parent = tree;
    }
    else if (left == NULL) {
	tree->parent = right;
	right->parent = tree;
    }
    else {
	tree->parent = right;
	right->parent = tree;
	splay(newroot);
	newroot->left = left;
	left->parent = newroot;
    }
}

/*
 * Clear in-memory egress table completely
 */
static void clear_egresses(void)
{
    splayval_t *val;
    splay_t *s;

    if (egresses) {
	free_splay(egresses);
	egresses = NULL;

	/*
	 * Make sure to clear egress pointers when egress routes are removed
	 */
	for (s = splay_first(rates); s != splay_null(rates); s = splay_next(s))
	    for (val = s->value; val; val = val->next)
		if (val->rate)
		    val->rate->egress = NULL;
	ast_log(LOG_DEBUG, "Cleared egress route from all rates\n");
    }
}

/*
 * Inject an egress route into the in-memory table
 */
static void inject_egress(egress_t *egress)
{
    splayval_t *val;
    char id[12];
    splay_t *s;

    if (egresses == NULL)
	egresses = new_splay();

    snprintf(id, sizeof(id), "%d", egress->route_id);

    val = malloc(sizeof(splayval_t));
    val->egress = egress;
    val->rate = NULL;

    s = search_splay(egresses, id);
    if (s) {
	ast_log(LOG_ERROR, "Duplicate egress route for %s[%s]\n", egress->technology, egress->peer);
	free_egress(egress);
	free(val);
    }
    else {
	val->next = NULL;
	s = insert_splay(egresses, id, val);

	/*
	 * If rate information is loaded, attempt to populate egress pointer
	 */
	if (rates) {
	    for (s = splay_first(rates); s != splay_null(rates); s = splay_next(s))
		for (val = s->value; val; val = val->next)
		    if (val->rate->route_id == egress->route_id)
			val->rate->egress = egress;
	    ast_log(LOG_DEBUG, "Added egress route to applicable rates\n");
	}
    }
}

/*
 * Clear in-memory rate table completely
 */
static void clear_rates(void)
{
    if (rates)
	free_splay(rates);
    rates = NULL;
}

/*
 * Inject a rate entry into the in-memory table -- when adding
 * a rate to an existing prefix, we should have a linked list
 * with least expensive first and most expensive last
 */
static void inject_rate(rate_t *rate)
{
    splayval_t *val;
    char id[12];
    splay_t *s;

    if (rates == NULL)
	rates = new_splay();

    snprintf(id, sizeof(id), "%d", rate->route_id);
    s = search_splay(egresses, id);
    if (s) {
	val = s->value;
	rate->egress = val->egress;
    }

    val = malloc(sizeof(splayval_t));
    val->egress = NULL;
    val->rate = rate;

    s = search_splay(rates, rate->prefix);
    if (s) {
	val->next = s->value;
	s->value = val;
    }
    else {
	val->next = NULL;
	insert_splay(rates, rate->prefix, val);
    }
}

/*
 * Allocate and initialize a new egress entry
 */
static egress_t *new_egress(void)
{
    egress_t *egress = malloc(sizeof(egress_t));

    egress->route_id = -1;
    egress->technology = NULL;
    egress->peer = NULL;
    egress->pcre = NULL;
    egress->extra = NULL;
    egress->substitute = NULL;
    egress->description = NULL;

    return egress;
}

/*
 * Free the resources used by an egress entry
 */
static void free_egress(egress_t *egress)
{
    if (egress->technology)
	free(egress->technology);
    if (egress->peer)
	free(egress->peer);
    if (egress->extra)
	pcre_free(egress->extra);
    if (egress->pcre)
	pcre_free(egress->pcre);
    if (egress->substitute)
	free(egress->substitute);
    if (egress->description)
	free(egress->description);
    free(egress);
}

/*
 * Allocate and initialize a new rate entry
 */
static rate_t *new_rate(void)
{
    rate_t *rate = malloc(sizeof(rate_t));

    rate->rate_id = -1;
    rate->route_id = -1;
    memset(rate->iso, '\0', sizeof(rate->iso));
    memset(rate->type, '\0', sizeof(rate->type));
    rate->country = NULL;
    rate->extra = NULL;
    memset(rate->prefix, '\0', sizeof(rate->prefix));
    rate->active_date = 0;
    rate->expires_date = 0;
    rate->firstperiod = 0;
    rate->periods = 0;
    rate->startcost = 0;
    rate->periodcost = 0;
    rate->trialcost = 0;

    return rate;
}

/*
 * Free the resources used by a rate entry
 */
static void free_rate(rate_t *rate)
{
    if (rate->country)
	free(rate->country);
    if (rate->extra)
	free(rate->extra);
    free(rate);
}

/*
 * Load egress and rate information from file into memory
 */
static int load_rates(int cli)
{
    char *query, *end;
    MYSQL_RES *result;
    egress_t *egress;
    int len, erroff;
    const char *err;
    MYSQL_ROW row;
    rate_t *rate;

    /*
     * Make sure we have exclusive access to MySQL and to the
     * in-memory rate / egress information
     */
    ast_mutex_lock(&ratelock);

    /*
     * Re-connect to MySQL if we are not currently connected
     */
    if (connected == 0) {
	if (mysql_real_connect(&mysql, dbhost, dbuser, dbpass, dbname, dbport, dbsock, 0)) {
	    if (option_verbose > 2)
		ast_verbose(VERBOSE_PREFIX_3 "Connected to database: %s\n", dbname);
	    connected = 1;
	}
	else {
	    connected = 0;
	    ast_mutex_unlock(&ratelock);
	    ast_log(LOG_ERROR, "Failed to connect to MySQL database '%s': %s\n", dbname, mysql_error(&mysql));
	    return -1;
	}
    }
    /*
     * Verify that our connection to MySQL is still alive,
     * reconnecting as needed
     */
    else if (mysql_ping(&mysql)) {
	connected = 0;
	ast_mutex_unlock(&ratelock);
	ast_log(LOG_ERROR, "Cannot talk to MySQL database '%s': %s\n", dbname, mysql_error(&mysql));
	return -1;
    }

    /*
     * Log an event so everyone knows what happened
     */
    ast_log(LOG_EVENT, "Reloading rates\n");

    /*
     * Load all egress routes into memory
     */
    len = asprintf(&query,
		   "SELECT route_id, technology, peer, pattern, substitute, description "
		   "FROM %s",
		   table_egress);
    if (mysql_real_query(&mysql, query, len)) {
	ast_mutex_unlock(&ratelock);
	ast_log(LOG_ERROR, "MySQL query failed: %s\n", mysql_error(&mysql));
	free(query);
	return -1;
    }
    else if ((result = mysql_store_result(&mysql)) == NULL) {
	ast_mutex_unlock(&ratelock);
	ast_log(LOG_ERROR, "Failed to retrieve MySQL result: %s\n", mysql_error(&mysql));
	free(query);
	return -1;
    }
    else {
	/*
	 * Now that we know the query succeeded, clear existing
	 * egress routes from memory and set the count to zero
	 */
	clear_egresses();
	num_egress = 0;

	/*
	 * Load each egress route into memory, increasing the
	 * count for each route successfully loaded
	 */
	while ((row = mysql_fetch_row(result)) != NULL) {
	    egress = new_egress();
	    egress->route_id = strtol(row[0], &end, 10);
	    egress->technology = strdup(row[1]);
	    egress->peer = strdup(row[2]);

	    /*
	     * Compile the matching pattern since we will use
	     * this quite a bit for active egress routes
	     */
	    if ((egress->pcre = pcre_compile(row[3], 0, &err, &erroff, NULL)) == NULL) {
		ast_log(LOG_WARNING, "Bad search pattern for egress route %d: %s\n", egress->route_id, err);
		free_egress(egress);
		continue;
	    }

	    /*
	     * We need the additional information for the
	     * substitute operation that we will be doing
	     * on egress route usage, too
	     */
	    egress->extra = pcre_study(egress->pcre, 0, &err);
	    if (err) {
		ast_log(LOG_WARNING, "Search pattern problem for egress route %d: %s\n", egress->route_id, err);
		free_egress(egress);
		continue;
	    }

	    egress->substitute = strdup(row[4]);
	    if (row[5])
		egress->description = strdup(row[5]);

	    /*
	     * Log egress routes on the console, but only when
	     * called during startup or from the CLI handler
	     */
	    if (cli && option_verbose > 3)
		ast_verbose(VERBOSE_PREFIX_4 "Egress route exists to %s[%s] (%s)\n",
			    egress->technology, egress->peer, egress->description);

	    num_egress++;
	    inject_egress(egress);
	}
	mysql_free_result(result);
    }
    free(query);

    /*
     * Load all rates into memory
     */
    len = asprintf(&query,
		   "SELECT rate_id, route_id, iso, type, country, extra, prefix, "
			  "UNIX_TIMESTAMP(active_date), UNIX_TIMESTAMP(expires_date), "
			  "firstperiod, periods, startcost, periodcost, trialcost "
		   "FROM %s",
		   table_cost);
    if (mysql_real_query(&mysql, query, len)) {
	ast_mutex_unlock(&ratelock);
	ast_log(LOG_ERROR, "MySQL query failed: %s\n", mysql_error(&mysql));
	free(query);
	return -1;
    }
    else if ((result = mysql_store_result(&mysql)) == NULL) {
	ast_mutex_unlock(&ratelock);
	ast_log(LOG_ERROR, "Failed to retrieve MySQL result: %s\n", mysql_error(&mysql));
	free(query);
	return -1;
    }
    else {
	/*
	 * Now that we know the query succeeded, clear existing
	 * egress routes from memory and set the count to zero
	 */
	clear_rates();
	num_rate = 0;

	/*
	 * Load each rate entry into memory, increasing the
	 * count for each rate successfully loaded
	 */
	while ((row = mysql_fetch_row(result)) != NULL) {
	    rate = new_rate();
	    rate->rate_id = strtol(row[0], &end, 10);
	    rate->route_id = strtol(row[1], &end, 10);
	    strncpy(rate->iso, row[2], sizeof(rate->iso) - 1);
	    if (row[3])
		strncpy(rate->type, row[3], sizeof(rate->type) - 1);
	    rate->country = strdup(row[4]);
	    if (row[5])
		rate->extra = strdup(row[5]);
	    strncpy(rate->prefix, row[6], sizeof(rate->prefix) - 1);
	    if (row[7])
		rate->active_date = strtol(row[7], &end, 10);
	    if (row[8])
		rate->expires_date = strtol(row[8], &end, 10);
	    rate->firstperiod = strtol(row[9], &end, 10);
	    rate->periods = strtol(row[10], &end, 10);
	    rate->startcost = strtol(row[11], &end, 10);
	    rate->periodcost = strtol(row[12], &end, 10);
	    rate->trialcost = strtol(row[13], &end, 10);

	    num_rate++;
	    inject_rate(rate);
	}
	mysql_free_result(result);
    }
    free(query);

    /*
     * Note when we last reloaded rate information
     */
    time(&lastreload);

    /*
     * And release lock, now that we are done updating the
     * in-memory tables and are no longer using MySQL
     */
    ast_mutex_unlock(&ratelock);

    return 0;
}

/*
 * CLI routine called to reload our rate and egress information
 */
static int rates_reload(int fd, int argc, char *argv[])
{
    if (load_rates(1))
	ast_cli(fd, "Error loading rates.\n");
    else
	ast_cli(fd, "Rates and egress routes reloaded.\n");
    return 0;
}

/*
 * CLI routine called to get rate and egress statistics
 */
static int rates_status(int fd, int argc, char *argv[])
{
    ast_cli(fd, "There are a total of %d rates, with %d egress routes.\n", num_rate, num_egress);
    return 0;
}

/*
 * Manager routine called to reload our rate and egress information
 */
static int manager_rates_reload(struct mansession *s, struct message *m)
{
    char *id = astman_get_header(m,"ActionID");
    char *idText = "";
    int res;

    if (id)
	asprintf(&idText, "ActionID: %s\r\n", id);
    else
	idText = NULL;

    res = load_rates(0);

    ast_cli(s->fd,
	    "Event: RatesReload\r\n"
	    "Reloaded: %s\r\n"
	    "Rates: %d\r\n"
	    "Routes: %d\r\n"
	    "%s"
	    "\r\n",
	    res ? "no" : "yes",
	    num_rate,
	    num_egress,
	    idText);
    if (id)
	free(idText);
    return 0;
}

/*
 * Manager routine called to get rate and egress statistics
 */
static int manager_rates_status(struct mansession *s, struct message *m)
{
    char *id = astman_get_header(m,"ActionID");
    char *idText = "";

    if (id)
	asprintf(&idText, "ActionID: %s\r\n", id);
    else
	idText = NULL;

    ast_cli(s->fd,
	    "Event: RatesStatus\r\n"
	    "Rates: %d\r\n"
	    "Routes: %d\r\n"
	    "%s"
	    "\r\n",
	    num_rate,
	    num_egress,
	    idText);
    if (id)
	free(idText);
    return 0;
}

static char rates_reload_usage[] =
"Usage: rates reload\n"
"       Reloads all rates from storage\n";

static char rates_status_usage[] =
"Usage: rates status\n"
"       Display statistics on rates in memory\n";

static struct ast_cli_entry cli_rates_reload = 
{ { "rates", "reload", NULL }, rates_reload, "Reloads all rates from storage", rates_reload_usage, NULL, NULL, 0 };

static struct ast_cli_entry cli_rates_status = 
{ { "rates", "status", NULL }, rates_status, "Display statistics on rates in memory", rates_status_usage, NULL, NULL, 0 };

/*
 * Called to reload configuration, rate and egress information
 */
int reload(void)
{
    int res;

    /*
     * Reload our configuration
     */
    res = load_config();

    /*
     * If successful, reload rates
     */
    if (res == 0)
	res = load_rates(1);

    return res;
}

int unload_module(void)
{
    int res;

    /*
     * Hang up on any channel that is connected to us
     */
    STANDARD_HANGUP_LOCALUSERS;

    /*
     * Unregister CDR handler
     */
    ast_cdr_unregister(cdr_name);

    /*
     * Unregister application entry point
     */
    res = ast_unregister_application(routecall_app);

    /*
     * Unregister manager entry points
     */
    ast_manager_unregister("RatesStatus");
    ast_manager_unregister("RatesReload");

    /*
     * Unregister CLI entry points
     */
    ast_cli_unregister(&cli_rates_reload);
    ast_cli_unregister(&cli_rates_status);

    /*
     * If we have a worker thread, cancel it
     */
    if (!pthread_equal(poster_thread, (pthread_t) -1)) {

	/*
	 * Get lock on shared data
	 */
	pthread_mutex_lock(&poster_lock);

	/*
	 * Tell posting thread to exit and signal a change
	 */
	cancel_poster = 1;
	pthread_cond_signal(&poster_cond);

	/*
	 * Release lock on shared data
	 */
	pthread_mutex_unlock(&poster_lock);

	/*
	 * Wait for posting thread to exit
	 */
	pthread_join(poster_thread, NULL);
	poster_thread = (pthread_t) -1;
    }

    /*
     * Close database connection
     */
    mysql_close(&mysql);
    connected = 0;

    /*
     * Free resources
     */
    if (dbhost) {
	free(dbhost);
	dbhost = NULL;
    }
    if (dbuser) {
	free(dbuser);
	dbuser = NULL;
    }
    if (dbpass) {
	free(dbpass);
	dbpass = NULL;
    }
    if (dbname) {
	free(dbname);
	dbname = NULL;
    }
    if (dbsock) {
	free(dbsock);
	dbsock = NULL;
    }
    if (table_cdr) {
	free(table_cdr);
	table_cdr = NULL;
    }
    if (table_error) {
	free(table_error);
	table_error = NULL;
    }
    if (table_egress) {
	free(table_egress);
	table_egress = NULL;
    }
    if (table_cost) {
	free(table_cost);
	table_cost = NULL;
    }
    clear_rates();
    clear_egresses();

    return res;
}

int load_module(void)
{
    int res;

    /*
     * Load configuration settings
     */
    res = load_config();
    if (res)
	return res;

    /*
     * Initialize database connection
     */
    mysql_init(&mysql);

    /*
     * Load route and rate information into memory
     */
    load_rates(1);

    /*
     * Register CLI entry points
     */
    ast_cli_register(&cli_rates_reload);
    ast_cli_register(&cli_rates_status);

    /*
     * Register manager entry points
     */
    ast_manager_register("RatesReload", 0, manager_rates_reload, "Rates Reload");
    ast_manager_register("RatesStatus", 0, manager_rates_status, "Rates Status");

    /*
     * Register application entry point
     */
    res = ast_register_application(routecall_app, routecall_exec, routecall_synopsis, routecall_descrip);
    if (res) {
	ast_log(LOG_ERROR, "Unable to register RouteCall application\n");
	return res;
    }

    /*
     * Create worker thread to post CDR data to the Rating Engine
     */
    if (ast_pthread_create(&poster_thread, NULL, poster_worker, NULL)) {
	ast_log(LOG_ERROR, "Unable to create CDR Rating Engine Poster thread.\n");
	return -1;
    }

    /*
     * Register us as a CDR consumer
     */
    res = ast_cdr_register(cdr_name, tdesc, cdr_ratecall);
    if (res) {
	ast_log(LOG_ERROR, "Unable to register CDR handling\n");
	return res;
    }

    return res;
}

char *description(void)
{
    /*
     * Return a terse description of the module
     */
    return tdesc;
}

int usecount(void)
{
    int res;

    /*
     * Return the number of current users of this module --
     * count our worker thread as a user in this context
     */
    STANDARD_USECOUNT(res);
    return res + pthread_equal(poster_thread, (pthread_t) -1) ? 0 : 1;
}

char *key()
{
    return ASTERISK_GPL_KEY;
}