/usr/share/perl5/Mail/SpamAssassin/BayesStore/SQL.pm is in spamassassin 3.4.1-8build1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 | # <@LICENSE>
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to you under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# </@LICENSE>
=head1 NAME
Mail::SpamAssassin::BayesStore::SQL - SQL Bayesian Storage Module Implementation
=head1 SYNOPSIS
=head1 DESCRIPTION
This module implementes a SQL based bayesian storage module.
=cut
package Mail::SpamAssassin::BayesStore::SQL;
use strict;
use warnings;
use bytes;
use re 'taint';
use Errno qw(EBADF);
BEGIN {
eval { require Digest::SHA; import Digest::SHA qw(sha1); 1 }
or do { require Digest::SHA1; import Digest::SHA1 qw(sha1) }
}
use Mail::SpamAssassin::BayesStore;
use Mail::SpamAssassin::Logger;
use vars qw( @ISA );
@ISA = qw( Mail::SpamAssassin::BayesStore );
use constant HAS_DBI => eval { require DBI; };
=head1 METHODS
=head2 new
public class (Mail::SpamAssassin::BayesStore::SQL) new (Mail::Spamassassin::Plugin::Bayes $bayes)
Description:
This methods creates a new instance of the Mail::SpamAssassin::BayesStore::SQL
object. It expects to be passed an instance of the Mail::SpamAssassin:Bayes
object which is passed into the Mail::SpamAssassin::BayesStore parent object.
This method sets up the database connection and determines the username to
use in queries.
=cut
sub new {
my $class = shift;
$class = ref($class) || $class;
my $self = $class->SUPER::new(@_);
$self->{supported_db_version} = 3;
$self->{db_writable_p} = 0;
if (!$self->{bayes}->{conf}->{bayes_sql_dsn}) {
dbg("bayes: invalid config, must set bayes_sql_dsn config variable\n");
return;
}
$self->{_dsn} = $self->{bayes}->{conf}->{bayes_sql_dsn};
$self->{_dbuser} = $self->{bayes}->{conf}->{bayes_sql_username};
$self->{_dbpass} = $self->{bayes}->{conf}->{bayes_sql_password};
$self->{_dbh} = undef;
unless (HAS_DBI) {
dbg("bayes: unable to connect to database: DBI module not available: $!");
}
if ($self->{bayes}->{conf}->{bayes_sql_override_username}) {
$self->{_username} = $self->{bayes}->{conf}->{bayes_sql_override_username};
}
else {
$self->{_username} = $self->{bayes}->{main}->{username};
# Need to make sure that a username is set, so just in case there is
# no username set in main, set one here.
if (!defined $self->{_username} || $self->{_username} eq '') {
$self->{_username} = "GLOBALBAYES";
}
}
dbg("bayes: using username: ".$self->{_username});
return $self;
}
=head2 tie_db_readonly
public instance (Boolean) tie_db_readonly ();
Description:
This method ensures that the database connection is properly setup
and working. If necessary it will initialize a user's bayes variables
so that they can begin using the database immediately.
=cut
sub tie_db_readonly {
my ($self) = @_;
return 0 unless (HAS_DBI);
if ($self->{_dbh}) {
# already connected, but connection has now become readonly
$self->{db_writable_p} = 0;
return 1;
}
my $main = $self->{bayes}->{main};
my $timer_tie_ro = $main->time_method('b_tie_ro');
$self->read_db_configs();
return 0 unless ($self->_connect_db());
my $db_ver = $self->_get_db_version();
$self->{db_version} = $db_ver;
dbg("bayes: found bayes db version ".$self->{db_version});
if ( $db_ver != $self->DB_VERSION ) {
warn("bayes: database version $db_ver is different than we understand (".$self->DB_VERSION."), aborting!");
$self->untie_db();
return 0;
}
unless ($self->_initialize_db(0)) {
dbg("bayes: unable to initialize database for ".$self->{_username}." user, aborting!");
$self->untie_db();
return 0;
}
return 1;
}
=head2 tie_db_writable
public instance (Boolean) tie_db_writable ()
Description:
This method ensures that the database connection is properly setup
and working. If necessary it will initialize a users bayes variables
so that they can begin using the database immediately.
=cut
sub tie_db_writable {
my ($self) = @_;
return 0 unless (HAS_DBI);
if ($self->{_dbh}) {
# already connected, but now it will be writable
$self->{db_writable_p} = 1;
return 1;
}
my $main = $self->{bayes}->{main};
my $timer_tie_rw = $main->time_method('b_tie_rw');
$self->read_db_configs();
return 0 unless ($self->_connect_db());
my $db_ver = $self->_get_db_version();
$self->{db_version} = $db_ver;
dbg("bayes: found bayes db version ".$self->{db_version});
if ( $db_ver != $self->DB_VERSION ) {
warn("bayes: database version $db_ver is different than we understand (".$self->DB_VERSION."), aborting!");
$self->untie_db();
return 0;
}
unless ($self->_initialize_db(1)) {
dbg("bayes: unable to initialize database for ".$self->{_username}." user, aborting!");
$self->untie_db();
return 0;
}
$self->{db_writable_p} = 1;
return 1;
}
=head2 untie_db
public instance () untie_db ()
Description:
Disconnects from an SQL server.
=cut
sub untie_db {
my ($self) = @_;
return unless (defined($self->{_dbh}));
$self->{db_writable_p} = 0;
$self->{_dbh}->disconnect();
$self->{_dbh} = undef;
}
=head2 calculate_expire_delta
public instance (%) calculate_expire_delta (Integer $newest_atime,
Integer $start,
Integer $max_expire_mult)
Description:
This method performs a calculation on the data to determine the optimum
atime for token expiration.
=cut
sub calculate_expire_delta {
my ($self, $newest_atime, $start, $max_expire_mult) = @_;
my %delta; # use a hash since an array is going to be very sparse
return %delta unless (defined($self->{_dbh}));
my $sql = "SELECT count(*)
FROM bayes_token
WHERE id = ?
AND atime < ?";
my $sth = $self->{_dbh}->prepare_cached($sql);
unless (defined($sth)) {
dbg("bayes: calculate_expire_delta: SQL Error: ".$self->{_dbh}->errstr());
return %delta;
}
for (my $i = 1; $i <= $max_expire_mult; $i<<=1) {
my $rc = $sth->execute($self->{_userid}, $newest_atime - $start * $i);
unless ($rc) {
dbg("bayes: calculate_expire_delta: SQL error: ".$self->{_dbh}->errstr());
return;
}
my ($count) = $sth->fetchrow_array();
$delta{$i} = $count;
}
$sth->finish();
return %delta;
}
=head2 token_expiration
public instance (Integer, Integer,
Integer, Integer) token_expiration(\% $opts,
Integer $newdelta,
@ @vars)
Description:
This method performs the database specific expiration of tokens based on
the passed in C<$newdelta> and C<@vars>.
=cut
sub token_expiration {
my ($self, $opts, $newdelta, @vars) = @_;
my $num_hapaxes;
my $num_lowfreq;
my $deleted;
# Figure out how old is too old...
my $too_old = $vars[10] - $newdelta; # tooold = newest - delta
# if token atime > newest, reset to newest ...
my $sql = "UPDATE bayes_token SET atime = ?
WHERE id = ?
AND atime > ?";
my $rows = $self->{_dbh}->do($sql, undef, $vars[10], $self->{_userid}, $vars[10]);
unless (defined($rows)) {
dbg("bayes: token_expiration: SQL error: ".$self->{_dbh}->errstr());
$deleted = 0;
goto token_expiration_final;
}
# Check to make sure the expire won't remove too many tokens
$sql = "SELECT count(token) FROM bayes_token
WHERE id = ?
AND atime < ?";
my $sth = $self->{_dbh}->prepare_cached($sql);
unless (defined($sth)) {
dbg("bayes: token_expiration: SQL error: ".$self->{_dbh}->errstr());
$deleted = 0;
goto token_expiration_final;
}
my $rc = $sth->execute($self->{_userid}, $too_old);
unless ($rc) {
dbg("bayes: token_expiration: SQL error: ".$self->{_dbh}->errstr());
$deleted = 0;
goto token_expiration_final;
}
my ($count) = $sth->fetchrow_array();
$sth->finish();
# Sanity check: if we expired too many tokens, abort!
if ($vars[3] - $count < 100000) {
dbg("bayes: token expiration would expire too many tokens, aborting");
# set these appropriately so the next expire pass does the first pass
$deleted = 0;
$newdelta = 0;
}
else {
# Do the expire
$sql = "DELETE from bayes_token
WHERE id = ?
AND atime < ?";
$rows = $self->{_dbh}->do($sql, undef, $self->{_userid}, $too_old);
unless (defined($rows)) {
dbg("bayes: token_expiration: SQL error: ".$self->{_dbh}->errstr());
$deleted = 0;
goto token_expiration_final;
}
$deleted = ($rows eq '0E0') ? 0 : $rows;
}
# Update the magic tokens as appropriate
$sql = "UPDATE bayes_vars SET token_count = token_count - ?,
last_expire = ?,
last_atime_delta = ?,
last_expire_reduce = ?
WHERE id = ?";
$rows = $self->{_dbh}->do($sql, undef, $deleted, time(), $newdelta, $deleted, $self->{_userid});
unless (defined($rows)) {
# Very bad, we actually deleted the tokens, but were unable to update
# bayes_vars with the new data.
dbg("bayes: token_expiration: SQL error: ".$self->{_dbh}->errstr());
dbg("bayes: bayes database now in inconsistent state, suggest a backup/restore");
goto token_expiration_final;
}
# If we didn't remove any tokens, the oldest token age wouldn't have changed
if ($deleted) {
# Now let's update the oldest_token_age value, shouldn't need to worry
# about newest_token_age. There is a slight race condition here, but the
# chance is small that we'll insert a new token with such an old atime
my $oldest_token_age = $self->_get_oldest_token_age();
$sql = "UPDATE bayes_vars SET oldest_token_age = ? WHERE id = ?";
$rows = $self->{_dbh}->do($sql, undef, $oldest_token_age, $self->{_userid});
unless (defined($rows)) {
# not much more we can do here, so just warn the user and bail out
dbg("bayes: token_expiration: SQL error: ".$self->{_dbh}->errstr());
# yeah I know it's the next thing anyway, but here in case someone adds
# additional code below this block
goto token_expiration_final;
}
}
token_expiration_final:
my $kept = $vars[3] - $deleted;
$num_hapaxes = $self->_get_num_hapaxes() if ($opts->{verbose});
$num_lowfreq = $self->_get_num_lowfreq() if ($opts->{verbose});
# Call untie_db() first so we unlock correctly etc. first
$self->untie_db();
return ($kept, $deleted, $num_hapaxes, $num_lowfreq);
}
=head2 sync_due
public instance (Boolean) sync_due ()
Description:
This method determines if a database sync is currently required.
Unused for SQL based implementation.
=cut
sub sync_due {
my ($self) = @_;
return 0;
}
=head2 seen_get
public instance (String) seen_get (string $msgid)
Description:
This method retrieves the stored value, if any, for C<$msgid>. The return value
is the stored string ('s' for spam and 'h' for ham) or undef if C<$msgid> is not
found.
=cut
sub seen_get {
my ($self, $msgid) = @_;
return unless defined($self->{_dbh});
my $sql = "SELECT flag FROM bayes_seen
WHERE id = ?
AND msgid = ?";
my $sth = $self->{_dbh}->prepare_cached($sql);
unless (defined($sth)) {
dbg("bayes: seen_get: SQL Error: ".$self->{_dbh}->errstr());
return;
}
my $rc = $sth->execute($self->{_userid}, $msgid);
unless ($rc) {
dbg("bayes: seen_get: SQL error: ".$self->{_dbh}->errstr());
return;
}
my ($flag) = $sth->fetchrow_array();
$sth->finish();
return $flag;
}
=head2 seen_put
public (Boolean) seen_put (string $msgid, char $flag)
Description:
This method records C<$msgid> as the type given by C<$flag>. C<$flag> is one of
two values 's' for spam and 'h' for ham.
=cut
sub seen_put {
my ($self, $msgid, $flag) = @_;
return 0 if (!$msgid);
return 0 if (!$flag);
return 0 unless (defined($self->{_dbh}));
my $sql = "INSERT INTO bayes_seen (id, msgid, flag)
VALUES (?,?,?)";
my $rows = $self->{_dbh}->do($sql,
undef,
$self->{_userid}, $msgid, $flag);
unless (defined($rows)) {
dbg("bayes: seen_put: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
dbg("bayes: seen ($msgid) put");
return 1;
}
=head2 seen_delete
public instance (Boolean) seen_delete (string $msgid)
Description:
This method removes C<$msgid> from the database.
=cut
sub seen_delete {
my ($self, $msgid) = @_;
return 0 if (!$msgid);
return 0 unless (defined($self->{_dbh}));
my $sql = "DELETE FROM bayes_seen
WHERE id = ?
AND msgid = ?";
my $rows = $self->{_dbh}->do($sql,
undef,
$self->{_userid}, $msgid);
unless (defined($rows)) {
dbg("bayes: seen_delete: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
return 1;
}
=head2 get_storage_variables
public instance (@) get_storage_variables ()
Description:
This method retrieves the various administrative variables used by
the Bayes process and database.
The values returned in the array are in the following order:
0: scan count base
1: number of spam
2: number of ham
3: number of tokens in db
4: last expire atime
5: oldest token in db atime
6: db version value
7: last journal sync
8: last atime delta
9: last expire reduction count
10: newest token in db atime
=cut
sub get_storage_variables {
my ($self) = @_;
my @values;
return (0,0,0,0,0,0,0,0,0,0,0) unless (defined($self->{_dbh}));
my $sql = "SELECT spam_count, ham_count, token_count, last_expire,
last_atime_delta, last_expire_reduce, oldest_token_age,
newest_token_age
FROM bayes_vars
WHERE id = ?";
my $sth = $self->{_dbh}->prepare_cached($sql);
unless (defined($sth)) {
dbg("bayes: get_storage_variables: SQL error: ".$self->{_dbh}->errstr());
return (0,0,0,0,0,0,0,0,0,0,0);
}
my $rc = $sth->execute($self->{_userid});
unless ($rc) {
dbg("bayes: get_storage_variables: SQL error: ".$self->{_dbh}->errstr());
return (0,0,0,0,0,0,0,0,0,0,0);
}
my ($spam_count, $ham_count, $token_count,
$last_expire, $last_atime_delta, $last_expire_reduce,
$oldest_token_age, $newest_token_age) = $sth->fetchrow_array();
$sth->finish();
my $db_ver = $self->DB_VERSION;
@values = (
0,
$spam_count,
$ham_count,
$token_count,
$last_expire,
$oldest_token_age,
$db_ver,
0, # we do not do journal syncs
$last_atime_delta,
$last_expire_reduce,
$newest_token_age
);
return @values;
}
=head2 dump_db_toks
public instance () dump_db_toks (String $template, String $regex, Array @vars)
Description:
This method loops over all tokens, computing the probability for the token and then
printing it out according to the passed in token.
=cut
sub dump_db_toks {
my ($self, $template, $regex, @vars) = @_;
return unless (defined($self->{_dbh}));
# 0/0 tokens don't count, but in theory we shouldn't have any
my $token_select = $self->_token_select_string();
my $sql = "SELECT $token_select, spam_count, ham_count, atime
FROM bayes_token
WHERE id = ?
AND (spam_count > 0 OR ham_count > 0)";
my $sth = $self->{_dbh}->prepare($sql);
unless (defined($sth)) {
dbg("bayes: dump_db_toks: SQL error: ".$self->{_dbh}->errstr());
return;
}
my $rc = $sth->execute($self->{_userid});
unless ($rc) {
dbg("bayes: dump_db_toks: SQL error: ".$self->{_dbh}->errstr());
return;
}
while (my ($token, $spam_count, $ham_count, $atime) = $sth->fetchrow_array()) {
my $prob = $self->{bayes}->_compute_prob_for_token($token, $vars[1], $vars[2],
$spam_count, $ham_count);
$prob ||= 0.5;
my $encoded_token = unpack("H*", $token);
printf $template,$prob,$spam_count,$ham_count,$atime,$encoded_token
or die "Error writing tokens: $!";
}
$sth->finish();
return;
}
=head2 set_last_expire
public instance (Boolean) set_last_expire (Integer $time)
Description:
This method sets the last expire time.
=cut
sub set_last_expire {
my ($self, $time) = @_;
return 0 unless (defined($time));
return 0 unless (defined($self->{_dbh}));
my $sql = "UPDATE bayes_vars SET last_expire = ? WHERE id = ?";
my $rows = $self->{_dbh}->do($sql,
undef,
$time,
$self->{_userid});
unless (defined($rows)) {
dbg("bayes: set_last_expire: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
return 1;
}
=head2 get_running_expire_tok
public instance (String $time) get_running_expire_tok ()
Description:
This method determines if an expire is currently running and returns
the last time set.
There can be multiple times, so we just pull the greatest (most recent)
value.
=cut
sub get_running_expire_tok {
my ($self) = @_;
return 0 unless (defined($self->{_dbh}));
my $sql = "SELECT max(runtime) from bayes_expire WHERE id = ?";
my $sth = $self->{_dbh}->prepare_cached($sql);
unless (defined($sth)) {
dbg("bayes: get_running_expire_tok: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
my $rc = $sth->execute($self->{_userid});
unless ($rc) {
dbg("bayes: get_running_expire_tok: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
my ($runtime) = $sth->fetchrow_array();
$sth->finish();
return $runtime;
}
=head2 set_running_expire_tok
public instance (String $time) set_running_expire_tok ()
Description:
This method sets the time that an expire starts running.
=cut
sub set_running_expire_tok {
my ($self) = @_;
return 0 unless (defined($self->{_dbh}));
my $sql = "INSERT INTO bayes_expire (id,runtime) VALUES (?,?)";
my $time = time();
my $rows = $self->{_dbh}->do($sql,
undef,
$self->{_userid}, $time);
unless (defined($rows)) {
dbg("bayes: set_running_expire_tok: SQL error: ".$self->{_dbh}->errstr());
return;
}
return $time;
}
=head2 remove_running_expire_tok
public instance (Boolean) remove_running_expire_tok ()
Description:
This method removes the row in the database that indicates that
and expire is currently running.
=cut
sub remove_running_expire_tok {
my ($self) = @_;
return 0 unless (defined($self->{_dbh}));
my $sql = "DELETE from bayes_expire
WHERE id = ?";
my $rows = $self->{_dbh}->do($sql, undef, $self->{_userid});
unless (defined($rows)) {
dbg("bayes: remove_running_expire_tok: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
return 1;
}
=head2 tok_get
public instance (Integer, Integer, Integer) tok_get (String $token)
Description:
This method retrieves a specificed token (C<$token>) from the database
and returns it's spam_count, ham_count and last access time.
=cut
sub tok_get {
my ($self, $token) = @_;
return (0,0,0) unless (defined($self->{_dbh}));
my $sql = "SELECT spam_count, ham_count, atime
FROM bayes_token
WHERE id = ?
AND token = ?";
my $sth = $self->{_dbh}->prepare_cached($sql);
unless (defined($sth)) {
dbg("bayes: tok_get: SQL error: ".$self->{_dbh}->errstr());
return (0,0,0);
}
my $rc = $sth->execute($self->{_userid}, $token);
unless ($rc) {
dbg("bayes: tok_get: SQL error: ".$self->{_dbh}->errstr());
return (0,0,0);
}
my ($spam_count, $ham_count, $atime) = $sth->fetchrow_array();
$sth->finish();
$spam_count = 0 if (!$spam_count || $spam_count < 0);
$ham_count = 0 if (!$ham_count || $ham_count < 0);
$atime = 0 if (!$atime);
return ($spam_count, $ham_count, $atime)
}
=head2 tok_get_all
public instance (\@) tok_get (@ $tokens)
Description:
This method retrieves the specified tokens (C<$tokens>) from storage and returns
an array ref of arrays spam count, ham acount and last access time.
=cut
sub tok_get_all {
my ($self, @tokens) = @_;
return [] unless (defined($self->{_dbh}));
my $token_list_size = scalar(@tokens);
dbg("bayes: tok_get_all: token count: $token_list_size");
my @tok_results;
my $search_index = 0;
my $results_index = 0;
my $bunch_end;
my $token_select = $self->_token_select_string();
my $multi_sql = "SELECT $token_select, spam_count, ham_count, atime
FROM bayes_token
WHERE id = ?
AND token IN ";
# fetch tokens in bunches of 100 until there are <= 100 left, then just fetch the rest
while ($token_list_size > $search_index) {
my $bunch_size;
if ($token_list_size - $search_index > 100) {
$bunch_size = 100;
}
else {
$bunch_size = $token_list_size - $search_index;
}
while ($token_list_size - $search_index >= $bunch_size) {
my @bindings;
my $bindcount;
my $in_str = '(';
$bunch_end = $search_index + $bunch_size;
for ( ; $search_index < $bunch_end; $search_index++) {
$in_str .= '?,';
push(@bindings, $tokens[$search_index]);
}
chop $in_str;
$in_str .= ')';
my $dynamic_sql = $multi_sql . $in_str;
my $sth = $self->{_dbh}->prepare($dynamic_sql);
unless (defined($sth)) {
dbg("bayes: tok_get_all: SQL error: ".$self->{_dbh}->errstr());
return [];
}
my $rc = $sth->execute($self->{_userid}, @bindings);
unless ($rc) {
dbg("bayes: tok_get_all: SQL error: ".$self->{_dbh}->errstr());
return [];
}
my $results = $sth->fetchall_arrayref();
$sth->finish();
foreach my $result (@{$results}) {
# Make sure that spam_count and ham_count are not negative
$result->[1] = 0 if (!$result->[1] || $result->[1] < 0);
$result->[2] = 0 if (!$result->[2] || $result->[2] < 0);
# Make sure that atime has a value
$result->[3] = 0 if (!$result->[3]);
$tok_results[$results_index++] = $result;
}
}
}
return \@tok_results;
}
=head2 tok_count_change
public instance (Boolean) tok_count_change (Integer $spam_count,
Integer $ham_count,
String $token,
String $atime)
Description:
This method takes a C<$spam_count> and C<$ham_count> and adds it to
C<$tok> along with updating C<$tok>s atime with C<$atime>.
=cut
sub tok_count_change {
my ($self, $spam_count, $ham_count, $token, $atime) = @_;
$atime = 0 unless defined $atime;
$self->_put_token($token, $spam_count, $ham_count, $atime);
}
=head2 multi_tok_count_change
public instance (Boolean) multi_tok_count_change (Integer $spam_count,
Integer $ham_count,
\% $tokens,
String $atime)
Description:
This method takes a C<$spam_count> and C<$ham_count> and adds it to all
of the tokens in the C<$tokens> hash ref along with updating each token's
atime with C<$atime>.
=cut
sub multi_tok_count_change {
my ($self, $spam_count, $ham_count, $tokens, $atime) = @_;
$atime = 0 unless defined $atime;
$self->_put_tokens($tokens, $spam_count, $ham_count, $atime);
}
=head2 nspam_nham_get
public instance ($spam_count, $ham_count) nspam_nham_get ()
Description:
This method retrieves the total number of spam and the total number of
ham learned.
=cut
sub nspam_nham_get {
my ($self) = @_;
return (0,0) unless (defined($self->{_dbh}));
my @vars = $self->get_storage_variables();
return ($vars[1] || 0, $vars[2] || 0);
}
=head2 nspam_nham_change
public instance (Boolean) nspam_nham_change (Integer $num_spam,
Integer $num_ham)
Description:
This method updates the number of spam and the number of ham in the database.
=cut
sub nspam_nham_change {
my ($self, $num_spam, $num_ham) = @_;
return 0 unless (defined($self->{_dbh}));
my $sql;
my @bindings;
if ($num_spam != 0 && $num_ham != 0) {
$sql = "UPDATE bayes_vars
SET spam_count = spam_count + ?,
ham_count = ham_count + ?
WHERE id = ?";
@bindings = ($num_spam, $num_ham, $self->{_userid});
}
elsif ($num_spam != 0) {
$sql = "UPDATE bayes_vars
SET spam_count = spam_count + ?
WHERE id = ?";
@bindings = ($num_spam, $self->{_userid});
}
elsif ($num_ham != 0) {
$sql = "UPDATE bayes_vars
SET ham_count = ham_count + ?
WHERE id = ?";
@bindings = ($num_ham, $self->{_userid});
}
else {
# For some reason called with no delta, it's ok though so just return
dbg("bayes: nspam_nham_change: Called with no delta on spam or ham");
return 1;
}
my $rows = $self->{_dbh}->do($sql,
undef,
@bindings);
unless (defined($rows)) {
dbg("bayes: nspam_nham_change: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
return 1;
}
=head2 tok_touch
public instance (Boolean) tok_touch (String $token,
String $atime)
Description:
This method updates the given tokens (C<$token>) atime.
The assumption is that the token already exists in the database.
=cut
sub tok_touch {
my ($self, $token, $atime) = @_;
return 0 unless (defined($self->{_dbh}));
# shortcut, will only update atime for the token if the atime is less than
# what we are updating to
my $sql = "UPDATE bayes_token
SET atime = ?
WHERE id = ?
AND token = ?
AND atime < ?";
my $rows = $self->{_dbh}->do($sql, undef, $atime, $self->{_userid},
$token, $atime);
unless (defined($rows)) {
dbg("bayes: tok_touch: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
# if we didn't update a row then no need to update newest_token_age
return 1 if ($rows eq '0E0');
# need to check newest_token_age
# no need to check oldest_token_age since we would only update if the
# atime was newer than what is in the database
$sql = "UPDATE bayes_vars
SET newest_token_age = ?
WHERE id = ?
AND newest_token_age < ?";
$rows = $self->{_dbh}->do($sql, undef, $atime, $self->{_userid}, $atime);
unless (defined($rows)) {
dbg("bayes: tok_touch: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
return 1;
}
=head2 tok_touch_all
public instance (Boolean) tok_touch (\@ $tokens
String $atime)
Description:
This method does a mass update of the given list of tokens C<$tokens>, if the existing token
atime is < C<$atime>.
The assumption is that the tokens already exist in the database.
We should never be touching more than N_SIGNIFICANT_TOKENS, so we can make
some assumptions about how to handle the data (ie no need to batch like we
do in tok_get_all)
=cut
sub tok_touch_all {
my ($self, $tokens, $atime) = @_;
return 0 unless (defined($self->{_dbh}));
return 1 unless (scalar(@{$tokens}));
my $sql = "UPDATE bayes_token SET atime = ? WHERE id = ? AND token IN (";
my @bindings = ($atime, $self->{_userid});
foreach my $token (@{$tokens}) {
$sql .= "?,";
push(@bindings, $token);
}
chop($sql); # get rid of trailing ,
$sql .= ") AND atime < ?";
push(@bindings, $atime);
my $rows = $self->{_dbh}->do($sql, undef, @bindings);
unless (defined($rows)) {
dbg("bayes: tok_touch_all: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
# if we didn't update a row then no need to update newest_token_age
return 1 if ($rows eq '0E0');
# need to check newest_token_age
# no need to check oldest_token_age since we would only update if the
# atime was newer than what is in the database
$sql = "UPDATE bayes_vars
SET newest_token_age = ?
WHERE id = ?
AND newest_token_age < ?";
$rows = $self->{_dbh}->do($sql, undef, $atime, $self->{_userid}, $atime);
unless (defined($rows)) {
dbg("bayes: tok_touch_all: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
return 1;
}
=head2 cleanup
public instance (Boolean) cleanup ()
Description:
This method perfoms any cleanup necessary before moving onto the next
operation.
=cut
sub cleanup {
my ($self) = @_;
return 1 unless ($self->{needs_cleanup});
# cleanup was needed, go ahead and clear the cleanup flag
$self->{needs_cleanup} = 0;
my $sql = "DELETE from bayes_token
WHERE id = ?
AND spam_count = 0
AND ham_count = 0";
my $toks_deleted = $self->{_dbh}->do($sql, undef, $self->{_userid});
unless (defined($toks_deleted)) {
dbg("bayes: cleanup: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
# check to see if any tokens where deleted
return 1 if ($toks_deleted eq '0E0');
$sql = "UPDATE bayes_vars SET token_count = token_count - $toks_deleted
WHERE id = ?";
my $rows = $self->{_dbh}->do($sql, undef, $self->{_userid});
unless (defined($rows)) {
dbg("bayes: cleanup: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
return 1;
}
=head2 get_magic_re
public instance get_magic_re (String)
Description:
This method returns a regexp which indicates a magic token.
Unused in SQL implementation.
=cut
sub get_magic_re {
my ($self) = @_;
undef;
}
=head2 sync
public instance (Boolean) sync (\% $opts)
Description:
This method performs a sync of the database
=cut
sub sync {
my ($self, $opts) = @_;
# Not used for this implementation
return 1;
}
=head2 perform_upgrade
public instance (Boolean) perform_upgrade (\% $opts);
Description:
Performs an upgrade of the database from one version to another, not
currently used in this implementation.
=cut
sub perform_upgrade {
my ($self) = @_;
return 1;
}
=head2 clear_database
public instance (Boolean) clear_database ()
Description:
This method deletes all records for a particular user.
Callers should be aware that any errors returned by this method
could cause the database to be inconsistent for the given user.
=cut
sub clear_database {
my ($self) = @_;
# We want to open readonly first, because if they don't already have
# a db entry, we want to avoid creating one, just to delete it in a few secs
if ($self->tie_db_readonly()) {
# Ok, they must have had a db entry, so now make the connection writable
$self->tie_db_writable();
}
else {
# If we were unable to create a readonly connection then they must
# not have a db entry, so no need to clear.
# But it should be considered a success.
return 1;
}
return 0 unless (defined($self->{_dbh}));
my $rows = $self->{_dbh}->do("DELETE FROM bayes_vars WHERE id = ?",
undef,
$self->{_userid});
unless (defined($rows)) {
dbg("bayes: SQL error removing user (bayes_vars) data: ".$self->{_dbh}->errstr());
return 0;
}
$rows = $self->{_dbh}->do("DELETE FROM bayes_seen WHERE id = ?",
undef,
$self->{_userid});
unless (defined($rows)) {
dbg("bayes: SQL error removing seen data: ".$self->{_dbh}->errstr());
return 0;
}
$rows = $self->{_dbh}->do("DELETE FROM bayes_token WHERE id = ?",
undef,
$self->{_userid});
unless (defined($rows)) {
dbg("bayes: SQL error removing token data: ".$self->{_dbh}->errstr());
return 0;
}
return 1;
}
=head2 backup_database
public instance (Boolean) backup_database ()
Description:
This method will dump the users database in a machine readable format.
=cut
sub backup_database {
my ($self) = @_;
return 0 unless ($self->tie_db_readonly());
return 0 unless (defined($self->{_dbh}));
my @vars = $self->get_storage_variables();
my $num_spam = $vars[1] || 0;
my $num_ham = $vars[2] || 0;
print "v\t$vars[6]\tdb_version # this must be the first line!!!\n"
or die "Error writing: $!";
print "v\t$num_spam\tnum_spam\n" or die "Error writing: $!";
print "v\t$num_ham\tnum_nonspam\n" or die "Error writing: $!";
my $token_select = $self->_token_select_string();
my $token_sql = "SELECT spam_count, ham_count, atime, $token_select
FROM bayes_token
WHERE id = ?
AND (spam_count > 0 OR ham_count > 0)";
my $seen_sql = "SELECT flag, msgid
FROM bayes_seen
WHERE id = ?";
my $sth = $self->{_dbh}->prepare_cached($token_sql);
unless (defined ($sth)) {
dbg("bayes: backup_database: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
my $rc = $sth->execute($self->{_userid});
unless ($rc) {
dbg("bayes: backup_database: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
while (my @values = $sth->fetchrow_array()) {
$values[3] = unpack("H*", $values[3]);
print "t\t" . join("\t", @values) . "\n"
or die "Error writing: $!";
}
$sth->finish();
$sth = $self->{_dbh}->prepare_cached($seen_sql);
unless (defined ($sth)) {
dbg("bayes: backup_database: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
$rc = $sth->execute($self->{_userid});
unless ($rc) {
dbg("bayes: backup_database: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
while (my @values = $sth->fetchrow_array()) {
print "s\t" . join("\t",@values) . "\n" or die "Error writing: $!";
}
$sth->finish();
$self->untie_db();
return 1;
}
=head2 restore_database
public instance (Boolean) restore_database (String $filename, Boolean $showdots)
Description:
This method restores a database from the given filename, C<$filename>.
Callers should be aware that any errors returned by this method
could causes the database to be inconsistent for the given user.
=cut
sub restore_database {
my ($self, $filename, $showdots) = @_;
local *DUMPFILE;
if (!open(DUMPFILE, '<', $filename)) {
dbg("bayes: unable to open backup file $filename: $!");
return 0;
}
# This is the critical phase (moving sql around), so don't allow it
# to be interrupted.
local $SIG{'INT'} = 'IGNORE';
local $SIG{'HUP'} = 'IGNORE' if (!Mail::SpamAssassin::Util::am_running_on_windows());
local $SIG{'TERM'} = 'IGNORE';
unless ($self->clear_database()) {
return 0;
}
# we need to go ahead close the db connection so we can then open it up
# in a fresh state after clearing
$self->untie_db();
unless ($self->tie_db_writable()) {
return 0;
}
my $token_count = 0;
my $db_version;
my $num_spam;
my $num_ham;
my $error_p = 0;
my $line_count = 0;
my $line = <DUMPFILE>;
defined $line or die "Error reading dump file: $!";
$line_count++;
# We require the database version line to be the first in the file so we can
# figure out how to properly deal with the file. If it is not the first
# line then fail
if ($line =~ m/^v\s+(\d+)\s+db_version/) {
$db_version = $1;
}
else {
dbg("bayes: database version must be the first line in the backup file, correct and re-run");
return 0;
}
unless ($db_version == 2 || $db_version == 3) {
warn("bayes: database version $db_version is unsupported, must be version 2 or 3");
return 0;
}
my $token_error_count = 0;
my $seen_error_count = 0;
for ($!=0; defined($line=<DUMPFILE>); $!=0) {
chomp($line);
$line_count++;
if ($line_count % 1000 == 0) {
print STDERR "." if ($showdots);
}
if ($line =~ /^v\s+/) { # variable line
my @parsed_line = split(/\s+/, $line, 3);
my $value = $parsed_line[1] + 0;
if ($parsed_line[2] eq 'num_spam') {
$num_spam = $value;
}
elsif ($parsed_line[2] eq 'num_nonspam') {
$num_ham = $value;
}
else {
dbg("bayes: restore_database: skipping unknown line: $line");
}
}
elsif ($line =~ /^t\s+/) { # token line
my @parsed_line = split(/\s+/, $line, 5);
my $spam_count = $parsed_line[1] + 0;
my $ham_count = $parsed_line[2] + 0;
my $atime = $parsed_line[3] + 0;
my $token = $parsed_line[4];
my $token_warn_p = 0;
my @warnings;
if ($spam_count < 0) {
$spam_count = 0;
push(@warnings, 'spam count < 0, resetting');
$token_warn_p = 1;
}
if ($ham_count < 0) {
$ham_count = 0;
push(@warnings, 'ham count < 0, resetting');
$token_warn_p = 1;
}
if ($spam_count == 0 && $ham_count == 0) {
dbg("bayes: token has zero spam and ham count, skipping");
next;
}
if ($atime > time()) {
$atime = time();
push(@warnings, 'atime > current time, resetting');
$token_warn_p = 1;
}
if ($token_warn_p) {
dbg("bayes: token ($token) has the following warnings:\n".join("\n",@warnings));
}
if ($db_version < 3) {
# versions < 3 use plain text tokens, so we need to convert to hash
$token = substr(sha1($token), -5);
}
else {
# turn unpacked binary token back into binary value
$token = pack("H*",$token);
}
unless ($self->_put_token($token, $spam_count, $ham_count, $atime)) {
dbg("bayes: error inserting token for line: $line");
$token_error_count++;
}
$token_count++;
}
elsif ($line =~ /^s\s+/) { # seen line
my @parsed_line = split(/\s+/, $line, 3);
my $flag = $parsed_line[1];
my $msgid = $parsed_line[2];
unless ($flag eq 'h' || $flag eq 's') {
dbg("bayes: unknown seen flag ($flag) for line: $line, skipping");
next;
}
unless ($msgid) {
dbg("bayes: blank msgid for line: $line, skipping");
next;
}
unless ($self->seen_put($msgid, $flag)) {
dbg("bayes: error inserting msgid in seen table for line: $line");
$seen_error_count++;
}
}
else {
dbg("bayes: skipping unknown line: $line");
next;
}
if ($token_error_count >= 20) {
warn "bayes: encountered too many errors (20) while parsing token line, reverting to empty database and exiting\n";
$self->clear_database();
return 0;
}
if ($seen_error_count >= 20) {
warn "bayes: encountered too many errors (20) while parsing seen lines, reverting to empty database and exiting\n";
$self->clear_database();
return 0;
}
}
defined $line || $!==0 or
$!==EBADF ? dbg("bayes: error reading dump file: $!")
: die "error reading dump file: $!";
close(DUMPFILE) or die "Can't close dump file: $!";
print STDERR "\n" if ($showdots);
unless (defined($num_spam)) {
dbg("bayes: unable to find num spam, please check file");
$error_p = 1;
}
unless (defined($num_ham)) {
dbg("bayes: unable to find num ham, please check file");
$error_p = 1;
}
if ($error_p) {
dbg("bayes: error(s) while attempting to load $filename, clearing database, correct and re-run");
$self->clear_database();
return 0;
}
if ($num_spam || $num_ham) {
unless ($self->nspam_nham_change($num_spam, $num_ham)) {
dbg("bayes: error updating num spam and num ham, clearing database");
$self->clear_database();
return 0;
}
}
dbg("bayes: parsed $line_count lines");
dbg("bayes: created database with $token_count tokens based on $num_spam spam messages and $num_ham ham messages");
$self->untie_db();
return 1;
}
=head2 db_readable
public instance (Boolean) db_readable()
Description:
This method returns a boolean value indicating if the database is in a
readable state.
=cut
sub db_readable {
my ($self) = @_;
# if there's a database handle, we can read...
return defined $self->{_dbh};
}
=head2 db_writable
public instance (Boolean) db_writeable()
Description:
This method returns a boolean value indicating if the database is in a
writable state.
=cut
sub db_writable {
my ($self) = @_;
return (defined $self->{_dbh} && $self->{db_writable_p})
}
=head1 Private Methods
=head2 _connect_db
private instance (Boolean) _connect_db ()
Description:
This method connects to the SQL database.
=cut
sub _connect_db {
my ($self) = @_;
$self->{_dbh} = undef;
# Turn off PrintError and explicitly set AutoCommit to off
my $dbh = DBI->connect($self->{_dsn}, $self->{_dbuser}, $self->{_dbpass},
{'PrintError' => 0, 'AutoCommit' => 1});
if (!$dbh) {
dbg("bayes: unable to connect to database: ".DBI->errstr());
return 0;
}
else {
dbg("bayes: database connection established");
}
$self->{_dbh} = $dbh;
return 1;
}
=head2 _get_db_version
private instance (Integer) _get_db_version ()
Description:
Gets the current version of the database from the special global vars
tables.
=cut
sub _get_db_version {
my ($self) = @_;
return 0 unless (defined($self->{_dbh}));
return ($self->{_db_version_cache}) if (defined($self->{_db_version_cache}));
my $sql = "SELECT value FROM bayes_global_vars WHERE variable = 'VERSION'";
my $sth = $self->{_dbh}->prepare_cached($sql);
unless (defined($sth)) {
dbg("bayes: _get_db_version: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
my $rc = $sth->execute();
unless ($rc) {
dbg("bayes: _get_db_version: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
my ($version) = $sth->fetchrow_array();
$sth->finish();
$self->{_db_version_cache} = $version;
return $version;
}
=head2 _initialize_db
private instance (Boolean) _initialize_db ()
Description:
This method will check to see if a user has had their bayes variables
initialized. If not then it will perform this initialization.
=cut
sub _initialize_db {
my ($self, $create_entry_p) = @_;
return 0 if !defined $self->{_dbh};
return 0 if !defined $self->{_username} || $self->{_username} eq '';
# Check to see if we should call the services_authorized_for_username plugin
# hook to see if this user is allowed/able to use bayes. If not, do nothing
# and return 0.
if ($self->{bayes}->{conf}->{bayes_sql_username_authorized}) {
my $services = { 'bayessql' => 0 };
$self->{bayes}->{main}->call_plugins("services_allowed_for_username",
{ services => $services,
username => $self->{_username},
conf => $self->{bayes}->{conf},
});
unless ($services->{bayessql}) {
dbg("bayes: username not allowed by services_allowed_for_username plugin call");
return 0;
}
}
my $sqlselect = "SELECT id FROM bayes_vars WHERE username = ?";
my $sthselect = $self->{_dbh}->prepare_cached($sqlselect);
unless (defined($sthselect)) {
dbg("bayes: _initialize_db: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
my $rc = $sthselect->execute($self->{_username});
unless ($rc) {
dbg("bayes: _initialize_db: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
my ($id) = $sthselect->fetchrow_array();
if ($id) {
$self->{_userid} = $id;
dbg("bayes: Using userid: ".$self->{_userid});
$sthselect->finish();
return 1;
}
# Do not create an entry for this user unless we were specifically asked to
return 0 unless ($create_entry_p);
# For now let the database setup the other variables as defaults
my $sqlinsert = "INSERT INTO bayes_vars (username) VALUES (?)";
my $rows = $self->{_dbh}->do($sqlinsert,
undef,
$self->{_username});
unless (defined($rows)) {
dbg("bayes: _initialize_db: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
# Now we need to figure out what id we inserted them at, in a perfect
# world the database driver would handle this for us (ie mysql_insert_id)
# but this is far from a perfect world, however since in theory we only
# ever do this once it's ok to take the hit
$rc = $sthselect->execute($self->{_username});
unless ($rc) {
dbg("bayes: _initialize_db: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
($id) = $sthselect->fetchrow_array();
$sthselect->finish();
if ($id) {
$self->{_userid} = $id;
dbg("bayes: using userid: ".$self->{_userid});
return 1;
}
return 1;
}
=head2 _put_token
private instance (Boolean) _put_token (string $token,
integer $spam_count,
integer $ham_count,
string $atime)
Description:
This method performs the work of either inserting or updating a token in
the database.
=cut
sub _put_token {
my ($self, $token, $spam_count, $ham_count, $atime) = @_;
return 0 unless (defined($self->{_dbh}));
$spam_count ||= 0;
$ham_count ||= 0;
if ($spam_count == 0 && $ham_count == 0) {
return 1;
}
my ($existing_spam_count,
$existing_ham_count,
$existing_atime) = $self->tok_get($token);
if (!$existing_atime) {
# You can't create a new entry for a token with a negative count, so just return
# if we are unable to find an entry.
return 1 if ($spam_count < 0 || $ham_count < 0);
my $sql = "INSERT INTO bayes_token
(id, token, spam_count, ham_count, atime)
VALUES (?,?,?,?,?)";
my $sth = $self->{_dbh}->prepare_cached($sql);
unless (defined($sth)) {
dbg("bayes: _put_token: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
my $rc = $sth->execute($self->{_userid},
$token,
$spam_count,
$ham_count,
$atime);
unless ($rc) {
dbg("bayes: _put_token: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
$sth->finish();
$sql = "UPDATE bayes_vars SET token_count = token_count + 1
WHERE id = ?";
my $rows = $self->{_dbh}->do($sql, undef, $self->{_userid});
unless (defined($rows)) {
dbg("bayes: _put_token: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
$sql = "UPDATE bayes_vars SET newest_token_age = ?
WHERE id = ? AND newest_token_age < ?";
$rows = $self->{_dbh}->do($sql, undef, $atime, $self->{_userid}, $atime);
unless (defined($rows)) {
dbg("bayes: _put_token: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
if ($rows eq '0E0') {
# no need to update oldest_token_age if we updated newest_token_age
$sql = "UPDATE bayes_vars SET oldest_token_age = ?
WHERE id = ? AND oldest_token_age > ?";
$rows = $self->{_dbh}->do($sql, undef, $atime, $self->{_userid}, $atime);
unless (defined($rows)) {
dbg("bayes: _put_token: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
}
}
else {
if ($spam_count < 0 || $ham_count < 0) {
# we only need to cleanup when we subtract counts for a token and the
# counts may have both reached 0
# XXX - future optimization, since we have the existing spam/ham counts
# we can make an educated guess on if the count would reach 0, for
# instance, if we are decreasing spam_count but spam_count is currently
# > 1000, then there is no possible way this update or any others that
# might currently be happening could reduce that value to 0, so there
# would be no need to set the needs_cleanup flag
$self->{needs_cleanup} = 1;
}
my $update_atime_p = 1;
my $updated_atime_p = 0;
# if the existing atime is already >= the one we are going to set, then
# don't bother
$update_atime_p = 0 if ($existing_atime >= $atime);
# These SQL statements include as part of the WHERE clause something like
# "AND spam_count + ? >= 0" or "AND ham_count + ? >= 0". This is to keep
# the count from going negative.
if ($spam_count) {
my $sql;
my @args;
if ($update_atime_p) {
$sql = "UPDATE bayes_token
SET spam_count = spam_count + ?,
atime = ?
WHERE id = ?
AND token = ?
AND spam_count + ? >= 0";
@args = ($spam_count, $atime, $self->{_userid}, $token, $spam_count);
$updated_atime_p = 1; # note the fact that we did do it
}
else {
$sql = "UPDATE bayes_token
SET spam_count = spam_count + ?
WHERE id = ?
AND token = ?
AND spam_count + ? >= 0";
@args = ($spam_count, $self->{_userid}, $token, $spam_count);
}
my $rows = $self->{_dbh}->do($sql, undef, @args);
unless (defined($rows)) {
dbg("bayes: _put_token: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
}
if ($ham_count) {
my $sql;
my @args;
if ($update_atime_p && !$updated_atime_p) {
$sql = "UPDATE bayes_token
SET ham_count = ham_count + ?,
atime = ?
WHERE id = ?
AND token = ?
AND ham_count + ? >= 0";
@args = ($ham_count, $atime, $self->{_userid}, $token, $ham_count);
$updated_atime_p = 1; # note the fact that we did do it
}
else {
$sql = "UPDATE bayes_token
SET ham_count = ham_count + ?
WHERE id = ?
AND token = ?
AND ham_count + ? >= 0";
@args = ($ham_count, $self->{_userid}, $token, $ham_count);
}
my $rows = $self->{_dbh}->do($sql, undef, @args);
unless (defined($rows)) {
dbg("bayes: _put_token: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
}
if ($updated_atime_p) {
# we updated the atime, so we need to check and update bayes_vars
# we only need to worry about newest_token_age since we would have
# only updated the atime if it was > the previous value
my $sql = "UPDATE bayes_vars SET newest_token_age = ?
WHERE id = ? AND newest_token_age < ?";
my $rows = $self->{_dbh}->do($sql, undef, $atime, $self->{_userid}, $atime);
unless (defined($rows)) {
dbg("bayes: _put_token: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
}
}
return 1;
}
=head2 _put_tokens
private instance (Boolean) _put_tokens (\% $tokens,
integer $spam_count,
integer $ham_count,
string $atime)
Description:
This method performs the work of either inserting or updating tokens in
the database.
=cut
sub _put_tokens {
my ($self, $tokens, $spam_count, $ham_count, $atime) = @_;
return 0 unless (defined($self->{_dbh}));
$spam_count ||= 0;
$ham_count ||= 0;
if ($spam_count == 0 && $ham_count == 0) {
return 1;
}
my $atime_updated_p = 0;
my $atime_inserted_p = 0;
my $new_tokens = 0;
my $insertsql = "INSERT INTO bayes_token
(id, token, spam_count, ham_count, atime)
VALUES (?,?,?,?,?)";
my $insertsth = $self->{_dbh}->prepare_cached($insertsql);
unless (defined($insertsth)) {
dbg("bayes: _put_token: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
foreach my $token (keys %{$tokens}) {
my ($existing_spam_count,
$existing_ham_count,
$existing_atime) = $self->tok_get($token);
if (!$existing_atime) {
# You can't create a new entry for a token with a negative count, so
# just skip to the next one if we are unable to find an entry.
next if ($spam_count < 0 || $ham_count < 0);
my $rc = $insertsth->execute($self->{_userid},
$token,
$spam_count,
$ham_count,
$atime);
unless ($rc) {
dbg("bayes: _put_token: SQL error: ".$self->{_dbh}->errstr());
next;
}
$insertsth->finish();
$atime_inserted_p = 1;
$new_tokens++;
}
else {
if ($spam_count < 0 || $ham_count < 0) {
# we only need to cleanup when we subtract counts for a token and the
# counts may have both reached 0
# XXX - future optimization, since we have the existing spam/ham counts
# we can make an educated guess on if the count would reach 0, for
# instance, if we are decreasing spam_count but spam_count is currently
# > 1000, then there is no possible way this update or any others that
# might currently be happening could reduce that value to 0, so there
# would be no need to set the needs_cleanup flag
$self->{needs_cleanup} = 1;
}
my $update_atime_p = 1;
# if the existing atime is already >= the one we are going to set, then
# don't bother
$update_atime_p = 0 if ($existing_atime >= $atime);
# These SQL statements include as part of the WHERE clause something like
# "AND spam_count + ? >= 0" or "AND ham_count + ? >= 0". This is to keep
# the count from going negative.
if ($spam_count) {
my $sql;
my @args;
if ($update_atime_p) {
$sql = "UPDATE bayes_token
SET spam_count = spam_count + ?,
atime = ?
WHERE id = ?
AND token = ?
AND spam_count + ? >= 0";
@args = ($spam_count, $atime, $self->{_userid}, $token, $spam_count);
$atime_updated_p = 1;
}
else {
$sql = "UPDATE bayes_token
SET spam_count = spam_count + ?
WHERE id = ?
AND token = ?
AND spam_count + ? >= 0";
@args = ($spam_count, $self->{_userid}, $token, $spam_count);
}
my $rows = $self->{_dbh}->do($sql, undef, @args);
unless (defined($rows)) {
dbg("bayes: _put_token: SQL error: ".$self->{_dbh}->errstr());
}
}
if ($ham_count) {
my $sql;
my @args;
# if $spam_count then we already updated the atime
if ($update_atime_p && !$spam_count) {
$sql = "UPDATE bayes_token
SET ham_count = ham_count + ?,
atime = ?
WHERE id = ?
AND token = ?
AND ham_count + ? >= 0";
@args = ($ham_count, $atime, $self->{_userid}, $token, $ham_count);
$atime_updated_p = 1;
}
else {
$sql = "UPDATE bayes_token
SET ham_count = ham_count + ?
WHERE id = ?
AND token = ?
AND ham_count + ? >= 0";
@args = ($ham_count, $self->{_userid}, $token, $ham_count);
}
my $rows = $self->{_dbh}->do($sql, undef, @args);
unless (defined($rows)) {
dbg("bayes: _put_token: SQL error: ".$self->{_dbh}->errstr());
}
}
}
}
if ($new_tokens) {
my $sql = "UPDATE bayes_vars SET token_count = token_count + ?
WHERE id = ?";
my $rows = $self->{_dbh}->do($sql, undef, $new_tokens, $self->{_userid});
unless (defined($rows)) {
dbg("bayes: _put_token: SQL error: ".$self->{_dbh}->errstr());
}
}
if ($atime_updated_p || $atime_inserted_p) {
# we updated the atime, so we need to check and update bayes_vars
# we only need to worry about newest_token_age since we would have
# only updated the atime if it was > the previous value
my $sql = "UPDATE bayes_vars SET newest_token_age = ?
WHERE id = ? AND newest_token_age < ?";
my $rows = $self->{_dbh}->do($sql, undef, $atime, $self->{_userid}, $atime);
unless (defined($rows)) {
dbg("bayes: _put_token: SQL error: ".$self->{_dbh}->errstr());
}
}
# If we inserted then we might need to update oldest_token_age
# but if we already updated newest_token_age then there is no need
if ($atime_inserted_p) {
my $sql = "UPDATE bayes_vars SET oldest_token_age = ?
WHERE id = ? AND oldest_token_age > ?";
my $rows = $self->{_dbh}->do($sql, undef, $atime, $self->{_userid}, $atime);
unless (defined($rows)) {
dbg("bayes: _put_token: SQL error: ".$self->{_dbh}->errstr());
}
}
return 1;
}
=head2 _get_oldest_token_age
private instance (Integer) _get_oldest_token_age ()
Description:
This method finds the atime of the oldest token in the database.
The use of min(atime) in the SQL is ugly and but really the most efficient
way of getting the oldest_token_age after we've done a mass expire. It should
only be called at expire time.
=cut
sub _get_oldest_token_age {
my ($self) = @_;
return 0 unless (defined($self->{_dbh}));
my $sql = "SELECT min(atime) FROM bayes_token
WHERE id = ?";
my $sth = $self->{_dbh}->prepare_cached($sql);
unless (defined($sth)) {
dbg("bayes: _get_oldest_token_age: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
my $rc = $sth->execute($self->{_userid});
unless ($rc) {
dbg("bayes: _get_oldest_token_age: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
my ($atime) = $sth->fetchrow_array();
$sth->finish();
return $atime;
}
=head2 _get_num_hapaxes
private instance (Integer) _get_num_hapaxes ()
Description:
This method gets the total number of hapaxes (spam_count + ham_count == 1) in
the token database for a user.
=cut
sub _get_num_hapaxes {
my ($self) = @_;
return 0 unless (defined($self->{_dbh}));
my $sql = "SELECT count(*)
FROM bayes_token
WHERE id = ?
AND spam_count + ham_count = 1";
my $sth = $self->{_dbh}->prepare_cached($sql);
unless (defined($sth)) {
dbg("bayes: _get_num_hapaxes: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
my $rc = $sth->execute($self->{_userid});
unless ($rc) {
dbg("bayes: _get_num_hapaxes: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
my ($num_hapaxes) = $sth->fetchrow_array();
$sth->finish();
return $num_hapaxes;
}
=head2 _get_num_lowfreq
private instance (Integer) _get_num_lowfreq ()
Description:
This method gets the total number of lowfreq tokens (spam_count < 8 and
ham_count < 8) in the token database for a user
=cut
sub _get_num_lowfreq {
my ($self) = @_;
return 0 unless (defined($self->{_dbh}));
my $sql = "SELECT count(*)
FROM bayes_token
WHERE id = ?
AND (spam_count >= 0 AND spam_count < 8)
AND (ham_count >= 0 AND ham_count < 8)
AND spam_count + ham_count != 1";
my $sth = $self->{_dbh}->prepare_cached($sql);
unless (defined($sth)) {
dbg("bayes: _get_num_lowfreq: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
my $rc = $sth->execute($self->{_userid});
unless ($rc) {
dbg("bayes: _get_num_lowfreq: SQL error: ".$self->{_dbh}->errstr());
return 0;
}
my ($num_lowfreq) = $sth->fetchrow_array();
$sth->finish();
return $num_lowfreq;
}
=head2 _token_select_string
private instance (String) _token_select_string
Description:
This method returns the string to be used in SELECT statements to represent
the token column.
The default is to use the RPAD function to pad the token out to 5 characters.
=cut
sub _token_select_string {
return "RPAD(token, 5, ' ')";
}
sub sa_die { Mail::SpamAssassin::sa_die(@_); }
1;
|