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
|
/* <@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>
*/
/*
Compile with extra warnings -- gcc only, not suitable for use as default:
gcc -Wextra -Wdeclaration-after-statement -Wall -g -O2 spamc/spamc.c \
spamc/getopt.c spamc/libspamc.c spamc/utils.c -o spamc/spamc -ldl -lz
*/
#include "config.h"
#include "libspamc.h"
#include "utils.h"
#include <stdarg.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#ifdef _WIN32
#define snprintf _snprintf
#define vsnprintf _vsnprintf
#define strcasecmp stricmp
#define sleep Sleep
#include <io.h>
#else
#include <syslog.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#define closesocket(x) close(x)
#endif
#ifdef HAVE_SYSEXITS_H
#include <sysexits.h>
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_SYS_ERRNO_H
#include <sys/errno.h>
#endif
#ifdef HAVE_TIME_H
#include <time.h>
#endif
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_ZLIB_H
#include <zlib.h>
#endif
/* RedHat 5.2 doesn't define Shutdown 2nd Parameter Constants */
/* KAM 12-4-01 */
/* SJF 2003/04/25 - now test for macros directly */
#ifndef SHUT_RD
# define SHUT_RD 0 /* no more receptions */
#endif
#ifndef SHUT_WR
# define SHUT_WR 1 /* no more transmissions */
#endif
#ifndef SHUT_RDWR
# define SHUT_RDWR 2 /* no more receptions or transmissions */
#endif
#ifndef HAVE_H_ERRNO
#define h_errno errno
#endif
#ifdef _WIN32
#define spamc_get_errno() WSAGetLastError()
#else
#define spamc_get_errno() errno
#endif
#ifndef HAVE_OPTARG
extern char *optarg;
#endif
#ifndef HAVE_INADDR_NONE
#define INADDR_NONE ((in_addr_t) 0xffffffff)
#endif
/* jm: turned off for now, it should not be necessary. */
#undef USE_TCP_NODELAY
#ifndef HAVE_EX__MAX
/* jm: very conservative figure, should be well out of range on almost all NIXes */
#define EX__MAX 200
#endif
#undef DO_CONNECT_DEBUG_SYSLOGS
/*
#define DO_CONNECT_DEBUG_SYSLOGS 1
#define CONNECT_DEBUG_LEVEL LOG_DEBUG
*/
/* bug 4477 comment 14 */
#ifdef NI_MAXHOST
#define SPAMC_MAXHOST NI_MAXHOST
#else
#define SPAMC_MAXHOST 256
#endif
#ifdef NI_MAXSERV
#define SPAMC_MAXSERV NI_MAXSERV
#else
#define SPAMC_MAXSERV 256
#endif
/* static const int ESC_PASSTHROUGHRAW = EX__MAX + 666; No longer seems to be used */
/* set EXPANSION_ALLOWANCE to something more than might be
added to a message in X-headers and the report template */
static const int EXPANSION_ALLOWANCE = 16384;
/* set NUM_CHECK_BYTES to number of bytes that have to match at beginning and end
of the data streams before and after processing by spamd
Aug 7 2002 jm: no longer seems to be used
static const int NUM_CHECK_BYTES = 32;
*/
/* Set the protocol version that this spamc speaks */
static const char *PROTOCOL_VERSION = "SPAMC/1.5";
/* "private" part of struct message.
* we use this instead of the struct message directly, so that we
* can add new members without affecting the ABI.
*/
struct libspamc_private_message
{
int flags; /* copied from "flags" arg to message_read() */
int alloced_size; /* allocated space for the "out" buffer */
void (*spamc_header_callback)(struct message *m, int flags, char *buf, int len);
void (*spamd_header_callback)(struct message *m, int flags, const char *buf, int len);
};
void (*libspamc_log_callback)(int flags, int level, char *msg, va_list args) = NULL;
int libspamc_timeout = 0;
int libspamc_connect_timeout = 0; /* Sep 8, 2008 mrgus: separate connect timeout */
/*
* translate_connect_errno()
*
* Given a UNIX error number obtained (probably) from "connect(2)",
* translate this to a failure code. This module is shared by both
* transport modules - UNIX and TCP.
*
* This should ONLY be called when there is an error.
*/
static int _translate_connect_errno(int err)
{
switch (err) {
case EBADF:
case EFAULT:
case ENOTSOCK:
case EISCONN:
case EADDRINUSE:
case EINPROGRESS:
case EALREADY:
case EAFNOSUPPORT:
return EX_SOFTWARE;
case ECONNREFUSED:
case ETIMEDOUT:
case ENETUNREACH:
return EX_UNAVAILABLE;
case EACCES:
return EX_NOPERM;
default:
return EX_SOFTWARE;
}
}
/*
* opensocket()
*
* Given a socket type (PF_INET or PF_UNIX), try to create this socket
* and store the FD in the pointed-to place. If it's successful, do any
* other setup required to make the socket ready to use, such as setting
* TCP_NODELAY mode, and in any case we return EX_OK if all is well.
*
* Upon failure we return one of the other EX_??? error codes.
*/
#ifdef SPAMC_HAS_ADDRINFO
static int _opensocket(int flags, struct addrinfo *res, int *psock)
{
#else
static int _opensocket(int flags, int type, int *psock)
{
int proto = 0;
#endif
const char *typename;
int origerr;
#ifdef _WIN32
int socktout;
#endif
assert(psock != 0);
/*----------------------------------------------------------------
* Create a few induction variables that are implied by the socket
* type given by the user. The typename is strictly used for debug
* reporting.
*/
#ifdef SPAMC_HAS_ADDRINFO
switch(res->ai_family) {
case PF_UNIX:
typename = "PF_UNIX";
break;
case PF_INET:
typename = "PF_INET";
break;
case PF_INET6:
typename = "PF_INET6";
break;
default:
typename = "Unknown";
break;
}
#else
if (type == PF_UNIX) {
typename = "PF_UNIX";
}
else {
typename = "PF_INET";
proto = IPPROTO_TCP;
}
#endif
#ifdef DO_CONNECT_DEBUG_SYSLOGS
libspamc_log(flags, CONNECT_DEBUG_LEVEL, "dbg: create socket(%s)", typename);
#endif
#ifdef SPAMC_HAS_ADDRINFO
if ((*psock = socket(res->ai_family, res->ai_socktype, res->ai_protocol))
#else
if ((*psock = socket(type, SOCK_STREAM, proto))
#endif
#ifndef _WIN32
< 0
#else
== INVALID_SOCKET
#endif
) {
/*--------------------------------------------------------
* At this point we had a failure creating the socket, and
* this is pretty much fatal. Translate the error reason
* into something the user can understand.
*/
origerr = spamc_get_errno();
#ifndef _WIN32
libspamc_log(flags, LOG_ERR, "socket(%s) to spamd failed: %s", typename, strerror(origerr));
#else
libspamc_log(flags, LOG_ERR, "socket(%s) to spamd failed: %d", typename, origerr);
#endif
switch (origerr) {
case EPROTONOSUPPORT:
case EINVAL:
return EX_SOFTWARE;
case EACCES:
return EX_NOPERM;
case ENFILE:
case EMFILE:
case ENOBUFS:
case ENOMEM:
return EX_OSERR;
default:
return EX_SOFTWARE;
}
}
#ifdef _WIN32
/* bug 4344: makes timeout functional on Win32 */
socktout = libspamc_timeout * 1000;
if (type == PF_INET
&& setsockopt(*psock, SOL_SOCKET, SO_RCVTIMEO, (char *)&socktout, sizeof(socktout)) != 0)
{
origerr = spamc_get_errno();
switch (origerr)
{
case EBADF:
case ENOTSOCK:
case ENOPROTOOPT:
case EFAULT:
libspamc_log(flags, LOG_ERR, "setsockopt(SO_RCVTIMEO) failed: %d", origerr);
closesocket(*psock);
return EX_SOFTWARE;
default:
break; /* ignored */
}
}
#endif
/*----------------------------------------------------------------
* Do a bit of setup on the TCP socket if required. Notes above
* suggest this is probably not set
*/
#ifdef USE_TCP_NODELAY
{
int one = 1;
if (type == PF_INET
&& setsockopt(*psock, 0, TCP_NODELAY, &one, sizeof one) != 0) {
origerr = spamc_get_errno();
switch (origerr) {
case EBADF:
case ENOTSOCK:
case ENOPROTOOPT:
case EFAULT:
libspamc_log(flags, LOG_ERR,
#ifndef _WIN32
"setsockopt(TCP_NODELAY) failed: %s", strerror(origerr));
#else
"setsockopt(TCP_NODELAY) failed: %d", origerr);
#endif
closesocket(*psock);
return EX_SOFTWARE;
default:
break; /* ignored */
}
}
}
#endif /* USE_TCP_NODELAY */
return EX_OK; /* all is well */
}
/*
* try_to_connect_unix()
*
* Given a transport handle that implies using a UNIX domain
* socket, try to make a connection to it and store the resulting
* file descriptor in *sockptr. Return is EX_OK if we did it,
* and some other error code otherwise.
*/
static int _try_to_connect_unix(struct transport *tp, int *sockptr)
{
#ifndef _WIN32
int mysock, status, origerr;
struct sockaddr_un addrbuf;
#ifdef SPAMC_HAS_ADDRINFO
struct addrinfo hints, *res;
#else
int res = PF_UNIX;
#endif
int ret;
assert(tp != 0);
assert(sockptr != 0);
assert(tp->socketpath != 0);
#ifdef SPAMC_HAS_ADDRINFO
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNIX;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = 0;
res = &hints;
#endif
/*----------------------------------------------------------------
* If the socket itself can't be created, this is a fatal error.
*/
if ((ret = _opensocket(tp->flags, res, &mysock)) != EX_OK)
return ret;
/* set up the UNIX domain socket */
memset(&addrbuf, 0, sizeof addrbuf);
addrbuf.sun_family = AF_UNIX;
strncpy(addrbuf.sun_path, tp->socketpath, sizeof addrbuf.sun_path - 1);
addrbuf.sun_path[sizeof addrbuf.sun_path - 1] = '\0';
#ifdef DO_CONNECT_DEBUG_SYSLOGS
libspamc_log(tp->flags, CONNECT_DEBUG_LEVEL, "dbg: connect(AF_UNIX) to spamd at %s",
addrbuf.sun_path);
#endif
status = timeout_connect(mysock, (struct sockaddr *) &addrbuf, sizeof(addrbuf));
origerr = errno;
if (status >= 0) {
#ifdef DO_CONNECT_DEBUG_SYSLOGS
libspamc_log(tp->flags, CONNECT_DEBUG_LEVEL, "dbg: connect(AF_UNIX) ok");
#endif
*sockptr = mysock;
return EX_OK;
}
libspamc_log(tp->flags, LOG_ERR, "connect(AF_UNIX) to spamd %s failed: %s",
addrbuf.sun_path, strerror(origerr));
closesocket(mysock);
return _translate_connect_errno(origerr);
#else
(void) tp; /* not used. suppress compiler warning */
(void) sockptr; /* not used. suppress compiler warning */
return EX_OSERR;
#endif
}
/*
* try_to_connect_tcp()
*
* Given a transport that implies a TCP connection, either to
* localhost or a list of IP addresses, attempt to connect. The
* list of IP addresses has already been randomized (if requested)
* and limited to just one if fallback has been enabled.
*/
static int _try_to_connect_tcp(const struct transport *tp, int *sockptr)
{
int numloops;
int origerr = 0;
int ret;
#ifdef SPAMC_HAS_ADDRINFO
struct addrinfo *res = NULL;
char port[SPAMC_MAXSERV-1]; /* port, for logging */
#else
int res = PF_INET;
#endif
char host[SPAMC_MAXHOST-1]; /* hostname, for logging */
int connect_retries, retry_sleep;
assert(tp != 0);
assert(sockptr != 0);
assert(tp->nhosts > 0);
/* default values */
retry_sleep = tp->retry_sleep;
connect_retries = tp->connect_retries;
if (connect_retries == 0) {
connect_retries = 3;
}
if (retry_sleep < 0) {
retry_sleep = 1;
}
for (numloops = 0; numloops < connect_retries; numloops++) {
const int hostix = numloops % tp->nhosts;
int status, mysock;
/*--------------------------------------------------------
* We always start by creating the socket, as we get only
* one attempt to connect() on each one. If this fails,
* we're done.
*/
#ifdef SPAMC_HAS_ADDRINFO
res = tp->hosts[hostix];
while(res) {
char *family = NULL;
switch(res->ai_family) {
case AF_INET:
family = "AF_INET";
break;
case AF_INET6:
family = "AF_INET6";
break;
default:
family = "Unknown";
break;
}
if ((ret = _opensocket(tp->flags, res, &mysock)) != EX_OK) {
res = res->ai_next;
continue;
}
getnameinfo(res->ai_addr, res->ai_addrlen,
host, sizeof(host),
port, sizeof(port),
NI_NUMERICHOST|NI_NUMERICSERV);
#ifdef DO_CONNECT_DEBUG_SYSLOGS
libspamc_log(tp->flags, CONNECT_DEBUG_LEVEL,
"dbg: connect(%s) to spamd (host %s, port %s) (try #%d of %d)",
family, host, port, numloops + 1, connect_retries);
#endif
/* this is special-cased so that we have an address we can
* safely use as an "always fail" test case */
if (!strcmp(host, "255.255.255.255")) {
libspamc_log(tp->flags, LOG_ERR,
"connect to spamd on %s failed, broadcast addr",
host);
status = -1;
}
else {
status = timeout_connect(mysock, res->ai_addr, res->ai_addrlen);
}
#else
struct sockaddr_in addrbuf;
const char *ipaddr;
const char* family="AF_INET";
if ((ret = _opensocket(tp->flags, PF_INET, &mysock)) != EX_OK)
return ret;
memset(&addrbuf, 0, sizeof(addrbuf));
addrbuf.sin_family = AF_INET;
addrbuf.sin_port = htons(tp->port);
addrbuf.sin_addr = tp->hosts[hostix];
ipaddr = inet_ntoa(addrbuf.sin_addr);
/* make a copy in host, for logging (bug 5577) */
strncpy (host, ipaddr, sizeof(host) - 1);
#ifdef DO_CONNECT_DEBUG_SYSLOGS
libspamc_log(tp->flags, LOG_DEBUG,
"dbg: connect(AF_INET) to spamd at %s (try #%d of %d)",
ipaddr, numloops + 1, connect_retries);
#endif
/* this is special-cased so that we have an address we can
* safely use as an "always fail" test case */
if (!strcmp(ipaddr, "255.255.255.255")) {
libspamc_log(tp->flags, LOG_ERR,
"connect to spamd on %s failed, broadcast addr",
ipaddr);
status = -1;
}
else {
status = timeout_connect(mysock, (struct sockaddr *) &addrbuf,
sizeof(addrbuf));
}
#endif
if (status != 0) {
origerr = spamc_get_errno();
closesocket(mysock);
#ifndef _WIN32
libspamc_log(tp->flags, LOG_ERR,
"connect to spamd on %s failed, retrying (#%d of %d): %s",
host, numloops+1, connect_retries, strerror(origerr));
#else
libspamc_log(tp->flags, LOG_ERR,
"connect to spamd on %s failed, retrying (#%d of %d): %d",
host, numloops+1, connect_retries, origerr);
#endif
} else {
#ifdef DO_CONNECT_DEBUG_SYSLOGS
libspamc_log(tp->flags, CONNECT_DEBUG_LEVEL,
"dbg: connect(%s) to spamd done",family);
#endif
*sockptr = mysock;
return EX_OK;
}
#ifdef SPAMC_HAS_ADDRINFO
res = res->ai_next;
}
#endif
sleep(retry_sleep);
} /* for(numloops...) */
libspamc_log(tp->flags, LOG_ERR,
"connection attempt to spamd aborted after %d retries",
connect_retries);
return _translate_connect_errno(origerr);
}
/* Aug 14, 2002 bj: Reworked things. Now we have message_read, message_write,
* message_dump, lookup_host, message_filter, and message_process, and a bunch
* of helper functions.
*/
static void _clear_message(struct message *m)
{
m->type = MESSAGE_NONE;
m->raw = NULL;
m->raw_len = 0;
m->pre = NULL;
m->pre_len = 0;
m->msg = NULL;
m->msg_len = 0;
m->post = NULL;
m->post_len = 0;
m->is_spam = EX_TOOBIG;
m->score = 0.0;
m->threshold = 0.0;
m->outbuf = NULL;
m->out = NULL;
m->out_len = 0;
m->content_length = -1;
}
static void _free_zlib_buffer(unsigned char **zlib_buf, int *zlib_bufsiz)
{
if(*zlib_buf) {
free(*zlib_buf);
*zlib_buf=NULL;
}
*zlib_bufsiz=0;
}
static void _use_msg_for_out(struct message *m)
{
if (m->outbuf)
free(m->outbuf);
m->outbuf = NULL;
m->out = m->msg;
m->out_len = m->msg_len;
}
static int _message_read_raw(int fd, struct message *m)
{
_clear_message(m);
if ((m->raw = malloc(m->max_len + 1)) == NULL)
return EX_OSERR;
m->raw_len = full_read(fd, 1, m->raw, m->max_len + 1, m->max_len + 1);
if (m->raw_len <= 0) {
free(m->raw);
m->raw = NULL;
m->raw_len = 0;
return EX_IOERR;
}
m->type = MESSAGE_ERROR;
if (m->raw_len > (int) m->max_len)
{
libspamc_log(m->priv->flags, LOG_NOTICE,
"skipped message, greater than max message size (%d bytes)",
m->max_len);
return EX_TOOBIG;
}
m->type = MESSAGE_RAW;
m->msg = m->raw;
m->msg_len = m->raw_len;
m->out = m->msg;
m->out_len = m->msg_len;
return EX_OK;
}
static int _message_read_bsmtp(int fd, struct message *m)
{
unsigned int i, j, p_len;
char prev;
char* p;
_clear_message(m);
if ((m->raw = malloc(m->max_len + 1)) == NULL)
return EX_OSERR;
/* Find the DATA line */
m->raw_len = full_read(fd, 1, m->raw, m->max_len + 1, m->max_len + 1);
if (m->raw_len <= 0) {
free(m->raw);
m->raw = NULL;
m->raw_len = 0;
return EX_IOERR;
}
m->type = MESSAGE_ERROR;
if (m->raw_len > (int) m->max_len)
return EX_TOOBIG;
p = m->pre = m->raw;
/* Search for \nDATA\n which marks start of actual message */
while ((p_len = (m->raw_len - (p - m->raw))) > 8) { /* leave room for at least \nDATA\n.\n */
char* q = memchr(p, '\n', p_len - 8); /* find next \n then see if start of \nDATA\n */
if (q == NULL) break;
q++;
if (((q[0]|0x20) == 'd') && /* case-insensitive ASCII comparison */
((q[1]|0x20) == 'a') &&
((q[2]|0x20) == 't') &&
((q[3]|0x20) == 'a')) {
q+=4;
if (q[0] == '\r') ++q;
if (*(q++) == '\n') { /* leave q at start of message if we found it */
m->msg = q;
m->pre_len = q - m->raw;
m->msg_len = m->raw_len - m->pre_len;
break;
}
}
p = q; /* the above code ensures no other '\n' comes before q */
}
if (m->msg == NULL)
return EX_DATAERR;
/* ensure this is >= 0 */
if (m->msg_len < 0) {
return EX_SOFTWARE;
}
/* Find the end-of-DATA line */
prev = '\n';
for (i = j = 0; i < (unsigned int) m->msg_len; i++) {
if (prev == '\n' && m->msg[i] == '.') {
/* Dot at the beginning of a line */
if (((int) (i+1) == m->msg_len)
|| ((int) (i+1) < m->msg_len && m->msg[i + 1] == '\n')
|| ((int) (i+2) < m->msg_len && m->msg[i + 1] == '\r' && m->msg[i + 2] == '\n')) {
/* Lone dot! That's all, folks */
m->post = m->msg + i;
m->post_len = m->msg_len - i;
m->msg_len = j;
break;
}
else if ((int) (i+1) < m->msg_len && m->msg[i + 1] == '.') {
/* Escaping dot, eliminate. */
prev = '.';
continue;
} /* Else an ordinary dot, drop down to ordinary char handler */
}
prev = m->msg[i];
m->msg[j++] = m->msg[i];
}
/* if bad format with no end "\n.\n", error out */
if (m->post == NULL)
return EX_DATAERR;
m->type = MESSAGE_BSMTP;
m->out = m->msg;
m->out_len = m->msg_len;
return EX_OK;
}
int message_read(int fd, int flags, struct message *m)
{
assert(m != NULL);
libspamc_timeout = 0;
/* create the "private" part of the struct message */
m->priv = malloc(sizeof(struct libspamc_private_message));
if (m->priv == NULL) {
libspamc_log(flags, LOG_ERR, "message_read: malloc failed");
return EX_OSERR;
}
m->priv->flags = flags;
m->priv->alloced_size = 0;
m->priv->spamc_header_callback = 0;
m->priv->spamd_header_callback = 0;
if (flags & SPAMC_PING) {
_clear_message(m);
return EX_OK;
}
switch (flags & SPAMC_MODE_MASK) {
case SPAMC_RAW_MODE:
return _message_read_raw(fd, m);
case SPAMC_BSMTP_MODE:
return _message_read_bsmtp(fd, m);
default:
libspamc_log(flags, LOG_ERR, "message_read: Unknown mode %d",
flags & SPAMC_MODE_MASK);
return EX_USAGE;
}
}
long message_write(int fd, struct message *m)
{
long total = 0;
off_t i, j;
off_t jlimit;
char buffer[1024];
assert(m != NULL);
if (m->priv->flags & (SPAMC_CHECK_ONLY|SPAMC_PING)) {
if (m->is_spam == EX_ISSPAM || m->is_spam == EX_NOTSPAM) {
return full_write(fd, 1, m->out, m->out_len);
}
else {
libspamc_log(m->priv->flags, LOG_ERR, "oops! SPAMC_CHECK_ONLY is_spam: %d",
m->is_spam);
return -1;
}
}
/* else we're not in CHECK_ONLY mode */
switch (m->type) {
case MESSAGE_NONE:
libspamc_log(m->priv->flags, LOG_ERR, "Cannot write this message, it's MESSAGE_NONE!");
return -1;
case MESSAGE_ERROR:
return full_write(fd, 1, m->raw, m->raw_len);
case MESSAGE_RAW:
return full_write(fd, 1, m->out, m->out_len);
case MESSAGE_BSMTP:
total = full_write(fd, 1, m->pre, m->pre_len);
for (i = 0; i < m->out_len;) {
jlimit = (off_t) (sizeof(buffer) / sizeof(*buffer) - 4);
for (j = 0; i < (off_t) m->out_len && j < jlimit;) {
if (i + 1 < m->out_len && m->out[i] == '\n'
&& m->out[i + 1] == '.') {
if (j > jlimit - 4) {
break; /* avoid overflow */
}
buffer[j++] = m->out[i++];
buffer[j++] = m->out[i++];
buffer[j++] = '.';
}
else {
buffer[j++] = m->out[i++];
}
}
total += full_write(fd, 1, buffer, j);
}
return total + full_write(fd, 1, m->post, m->post_len);
default:
libspamc_log(m->priv->flags, LOG_ERR, "Unknown message type %d", m->type);
return -1;
}
}
void message_dump(int in_fd, int out_fd, struct message *m)
{
char buf[8196];
int bytes;
if (m == NULL) {
return; /* Bug 6562 reported by Frederik Deweerdt <frederik.deweerdt@xprog.eu> */
}
if (m != NULL && m->type != MESSAGE_NONE) {
message_write(out_fd, m);
}
while ((bytes = full_read(in_fd, 1, buf, 8192, 8192)) > 0) {
if (bytes != full_write(out_fd, 1, buf, bytes)) {
libspamc_log(m->priv->flags, LOG_ERR, "oops! message_dump of %d returned different",
bytes);
}
}
}
static int
_spamc_read_full_line(struct message *m, int flags, SSL * ssl, int sock,
char *buf, size_t *lenp, size_t bufsiz)
{
int failureval;
int bytesread = 0;
size_t len;
UNUSED_VARIABLE(m);
*lenp = 0;
/* Now, read from spamd */
for (len = 0; len < bufsiz - 1; len++) {
if (flags & SPAMC_USE_SSL) {
bytesread = ssl_timeout_read(ssl, buf + len, 1);
}
else {
bytesread = fd_timeout_read(sock, 0, buf + len, 1);
}
if (bytesread <= 0) {
failureval = EX_IOERR;
goto failure;
}
if (buf[len] == '\n') {
buf[len] = '\0';
if (len > 0 && buf[len - 1] == '\r') {
len--;
buf[len] = '\0';
}
*lenp = len;
return EX_OK;
}
}
libspamc_log(flags, LOG_ERR, "spamd responded with line of %d bytes, dying", len);
failureval = EX_TOOBIG;
failure:
return failureval;
}
/*
* May 7 2003 jm: using %f is bad where LC_NUMERIC is "," in the locale.
* work around using our own locale-independent float-parser code.
*/
static float _locale_safe_string_to_float(char *buf, int siz)
{
int is_neg;
char *cp, *dot;
int divider;
float ret, postdot;
buf[siz - 1] = '\0'; /* ensure termination */
/* ok, let's illustrate using "100.033" as an example... */
is_neg = 0;
if (*buf == '-') {
is_neg = 1;
}
ret = (float) (strtol(buf, &dot, 10));
if (dot == NULL) {
return 0.0;
}
if (dot != NULL && *dot != '.') {
return ret;
}
/* ex: ret == 100.0 */
cp = (dot + 1);
postdot = (float) (strtol(cp, NULL, 10));
/* note: don't compare floats == 0.0, it's unsafe. use a range */
if (postdot >= -0.00001 && postdot <= 0.00001) {
return ret;
}
/* ex: postdot == 33.0, cp="033" */
/* now count the number of decimal places and figure out what power of 10 to use */
divider = 1;
while (*cp != '\0') {
divider *= 10;
cp++;
}
/* ex:
* cp="033", divider=1
* cp="33", divider=10
* cp="3", divider=100
* cp="", divider=1000
*/
if (is_neg) {
ret -= (postdot / ((float) divider));
}
else {
ret += (postdot / ((float) divider));
}
/* ex: ret == 100.033, tada! ... hopefully */
return ret;
}
static int
_handle_spamd_header(struct message *m, int flags, char *buf, int len,
unsigned int *didtellflags)
{
char is_spam[6];
char s_str[21], t_str[21];
char didset_ret[15];
char didremove_ret[15];
UNUSED_VARIABLE(len);
/* Feb 12 2003 jm: actually, I think sccanf is working fine here ;)
* let's stick with it for this parser.
* May 7 2003 jm: using %f is bad where LC_NUMERIC is "," in the locale.
* work around using our own locale-independent float-parser code.
*/
if (sscanf(buf, "Spam: %5s ; %20s / %20s", is_spam, s_str, t_str) == 3) {
m->score = _locale_safe_string_to_float(s_str, 20);
m->threshold = _locale_safe_string_to_float(t_str, 20);
/* set bounds on these to ensure no buffer overflow in the sprintf */
if (m->score > 1e10)
m->score = 1e10;
else if (m->score < -1e10)
m->score = -1e10;
if (m->threshold > 1e10)
m->threshold = 1e10;
else if (m->threshold < -1e10)
m->threshold = -1e10;
/* Format is "Spam: x; y / x" */
m->is_spam =
strcasecmp("true", is_spam) == 0 ? EX_ISSPAM : EX_NOTSPAM;
if (flags & SPAMC_CHECK_ONLY) {
m->out_len = sprintf(m->out,
"%.1f/%.1f\n", m->score, m->threshold);
}
else if ((flags & SPAMC_REPORT_IFSPAM && m->is_spam == EX_ISSPAM)
|| (flags & SPAMC_REPORT)) {
m->out_len = sprintf(m->out,
"%.1f/%.1f\n", m->score, m->threshold);
}
return EX_OK;
}
else if (sscanf(buf, "Content-length: %d", &m->content_length) == 1) {
if (m->content_length < 0) {
libspamc_log(flags, LOG_ERR, "spamd responded with bad Content-length '%s'",
buf);
return EX_PROTOCOL;
}
return EX_OK;
}
else if (sscanf(buf, "DidSet: %14s", didset_ret) == 1) {
if (strstr(didset_ret, "local")) {
*didtellflags |= SPAMC_SET_LOCAL;
}
if (strstr(didset_ret, "remote")) {
*didtellflags |= SPAMC_SET_REMOTE;
}
}
else if (sscanf(buf, "DidRemove: %14s", didremove_ret) == 1) {
if (strstr(didremove_ret, "local")) {
*didtellflags |= SPAMC_REMOVE_LOCAL;
}
if (strstr(didremove_ret, "remote")) {
*didtellflags |= SPAMC_REMOVE_REMOTE;
}
}
else if (m->priv->spamd_header_callback != NULL)
m->priv->spamd_header_callback(m, flags, buf, len);
return EX_OK;
}
static int
_zlib_compress (char *m_msg, int m_msg_len,
unsigned char **zlib_buf, int *zlib_bufsiz, int flags)
{
int rc;
int len, totallen;
#ifndef HAVE_LIBZ
UNUSED_VARIABLE(m_msg);
UNUSED_VARIABLE(m_msg_len);
UNUSED_VARIABLE(zlib_buf);
UNUSED_VARIABLE(zlib_bufsiz);
UNUSED_VARIABLE(rc);
UNUSED_VARIABLE(len);
UNUSED_VARIABLE(totallen);
libspamc_log(flags, LOG_ERR, "spamc not built with zlib support");
return EX_SOFTWARE;
#else
z_stream strm;
UNUSED_VARIABLE(flags);
/* worst-case, according to http://www.zlib.org/zlib_tech.html ;
* same as input, plus 5 bytes per 16k, plus 6 bytes. this should
* be plenty */
*zlib_bufsiz = (int) (m_msg_len * 1.0005) + 1024;
*zlib_buf = (unsigned char *) malloc (*zlib_bufsiz);
if (*zlib_buf == NULL) {
return EX_OSERR;
}
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
rc = deflateInit(&strm, 3);
if (rc != Z_OK) {
return EX_OSERR;
}
strm.avail_in = m_msg_len;
strm.next_in = (unsigned char *) m_msg;
strm.avail_out = *zlib_bufsiz;
strm.next_out = (unsigned char *) *zlib_buf;
totallen = 0;
do {
rc = deflate(&strm, Z_FINISH);
assert(rc != Z_STREAM_ERROR);
len = (size_t) (*zlib_bufsiz - strm.avail_out);
strm.next_out += len;
totallen += len;
} while (strm.avail_out == 0);
*zlib_bufsiz = totallen;
return EX_OK;
#endif
}
int
_append_original_body (struct message *m, int flags)
{
char *cp, *cpend, *bodystart;
int bodylen, outspaceleft, towrite;
/* at this stage, m->out now contains the rewritten headers.
* find and append the raw message's body, up to m->priv->alloced_size
* bytes.
*/
#define CRNLCRNL "\r\n\r\n"
#define CRNLCRNL_LEN 4
#define NLNL "\n\n"
#define NLNL_LEN 2
cpend = m->raw + m->raw_len;
bodystart = NULL;
for (cp = m->raw; cp < cpend; cp++) {
if (*cp == '\r' && cpend - cp >= CRNLCRNL_LEN &&
!strncmp(cp, CRNLCRNL, CRNLCRNL_LEN))
{
bodystart = cp + CRNLCRNL_LEN;
break;
}
else if (*cp == '\n' && cpend - cp >= NLNL_LEN &&
!strncmp(cp, NLNL, NLNL_LEN))
{
bodystart = cp + NLNL_LEN;
break;
}
}
if (bodystart == NULL) {
libspamc_log(flags, LOG_ERR, "failed to find end-of-headers");
return EX_SOFTWARE;
}
bodylen = cpend - bodystart;
outspaceleft = (m->priv->alloced_size-1) - m->out_len;
towrite = (bodylen < outspaceleft ? bodylen : outspaceleft);
/* copy in the body; careful not to overflow */
strncpy (m->out + m->out_len, bodystart, towrite);
m->out_len += towrite;
return EX_OK;
}
int message_filter(struct transport *tp, const char *username,
int flags, struct message *m)
{
char buf[8192];
size_t bufsiz = (sizeof(buf) / sizeof(*buf)) - 4; /* bit of breathing room */
size_t len;
int sock = -1;
int rc;
char versbuf[20];
float version;
int response;
int failureval = EX_SOFTWARE;
unsigned int throwaway;
SSL_CTX *ctx = NULL;
SSL *ssl = NULL;
SSL_METHOD *meth;
char zlib_on = 0;
unsigned char *zlib_buf = NULL;
int zlib_bufsiz = 0;
unsigned char *towrite_buf;
int towrite_len;
int filter_retry_count;
int filter_retry_sleep;
int filter_retries;
#ifdef SPAMC_HAS_ADDRINFO
struct addrinfo *tmphost;
#else
struct in_addr tmphost;
#endif
int nhost_counter;
assert(tp != NULL);
assert(m != NULL);
if ((flags & SPAMC_USE_ZLIB) != 0) {
zlib_on = 1;
}
if (flags & SPAMC_USE_SSL) {
#ifdef SPAMC_SSL
SSLeay_add_ssl_algorithms();
if (flags & SPAMC_TLSV1) {
meth = TLSv1_client_method();
} else {
meth = SSLv3_client_method(); /* default */
}
SSL_load_error_strings();
ctx = SSL_CTX_new(meth);
#else
UNUSED_VARIABLE(ssl);
UNUSED_VARIABLE(meth);
UNUSED_VARIABLE(ctx);
libspamc_log(flags, LOG_ERR, "spamc not built with SSL support");
return EX_SOFTWARE;
#endif
}
m->is_spam = EX_TOOBIG;
if (m->outbuf != NULL)
free(m->outbuf);
m->priv->alloced_size = m->max_len + EXPANSION_ALLOWANCE + 1;
if ((m->outbuf = malloc(m->priv->alloced_size)) == NULL) {
failureval = EX_OSERR;
goto failure;
}
m->out = m->outbuf;
m->out_len = 0;
/* If the spamd filter takes too long and we timeout, then
* retry again. This gets us around a hung child thread
* in spamd or a problem on a spamd host in a multi-host
* setup. If there is more than one destination host
* we move to the next host on each attempt.
*/
/* default values */
filter_retry_sleep = tp->filter_retry_sleep;
filter_retries = tp->filter_retries;
if (filter_retries == 0) {
filter_retries = 1;
}
if (filter_retry_sleep < 0) {
filter_retry_sleep = 1;
}
/* filterloop - Ensure that we run through this at least
* once, and again if there are errors
*/
filter_retry_count = 0;
while ((filter_retry_count==0) ||
((filter_retry_count<tp->filter_retries) && (failureval == EX_IOERR)))
{
if (filter_retry_count != 0){
/* Ensure that the old socket gets closed */
if (sock != -1) {
closesocket(sock);
sock=-1;
}
/* Move to the next host in the list, if nhosts>1 */
if (tp->nhosts > 1) {
tmphost = tp->hosts[0];
/* TODO: free using freeaddrinfo() */
for (nhost_counter = 1; nhost_counter < tp->nhosts; nhost_counter++) {
tp->hosts[nhost_counter - 1] = tp->hosts[nhost_counter];
}
tp->hosts[nhost_counter - 1] = tmphost;
}
/* Now sleep the requested amount */
sleep(filter_retry_sleep);
}
filter_retry_count++;
/* Build spamd protocol header */
if (flags & SPAMC_CHECK_ONLY)
strcpy(buf, "CHECK ");
else if (flags & SPAMC_REPORT_IFSPAM)
strcpy(buf, "REPORT_IFSPAM ");
else if (flags & SPAMC_REPORT)
strcpy(buf, "REPORT ");
else if (flags & SPAMC_SYMBOLS)
strcpy(buf, "SYMBOLS ");
else if (flags & SPAMC_PING)
strcpy(buf, "PING ");
else if (flags & SPAMC_HEADERS)
strcpy(buf, "HEADERS ");
else
strcpy(buf, "PROCESS ");
len = strlen(buf);
if (len + strlen(PROTOCOL_VERSION) + 2 >= bufsiz) {
_use_msg_for_out(m);
return EX_OSERR;
}
strcat(buf, PROTOCOL_VERSION);
strcat(buf, "\r\n");
len = strlen(buf);
towrite_buf = (unsigned char *) m->msg;
towrite_len = (int) m->msg_len;
if (zlib_on) {
if (_zlib_compress(m->msg, m->msg_len, &zlib_buf, &zlib_bufsiz, flags) != EX_OK)
{
_free_zlib_buffer(&zlib_buf, &zlib_bufsiz);
return EX_OSERR;
}
towrite_buf = zlib_buf;
towrite_len = zlib_bufsiz;
}
if (!(flags & SPAMC_PING)) {
if (username != NULL) {
if (strlen(username) + 8 >= (bufsiz - len)) {
_use_msg_for_out(m);
if (zlib_on) {
_free_zlib_buffer(&zlib_buf, &zlib_bufsiz);
}
return EX_OSERR;
}
strcpy(buf + len, "User: ");
strcat(buf + len, username);
strcat(buf + len, "\r\n");
len += strlen(buf + len);
}
if (zlib_on) {
len += snprintf(buf + len, 8192-len, "Compress: zlib\r\n");
}
if ((m->msg_len > SPAMC_MAX_MESSAGE_LEN) || ((len + 27) >= (bufsiz - len))) {
_use_msg_for_out(m);
if (zlib_on) {
_free_zlib_buffer(&zlib_buf, &zlib_bufsiz);
}
return EX_DATAERR;
}
len += snprintf(buf + len, 8192-len, "Content-length: %d\r\n", (int) towrite_len);
}
/* bug 6187, PING needs empty line too, bumps protocol version to 1.5 */
len += snprintf(buf + len, 8192-len, "\r\n");
libspamc_timeout = m->timeout;
libspamc_connect_timeout = m->connect_timeout; /* Sep 8, 2008 mrgus: separate connect timeout */
if (tp->socketpath)
rc = _try_to_connect_unix(tp, &sock);
else
rc = _try_to_connect_tcp(tp, &sock);
if (rc != EX_OK) {
_use_msg_for_out(m);
if (zlib_on) {
_free_zlib_buffer(&zlib_buf, &zlib_bufsiz);
}
return rc; /* use the error code try_to_connect_*() gave us. */
}
if (flags & SPAMC_USE_SSL) {
#ifdef SPAMC_SSL
ssl = SSL_new(ctx);
SSL_set_fd(ssl, sock);
SSL_connect(ssl);
#endif
}
/* Send to spamd */
if (flags & SPAMC_USE_SSL) {
#ifdef SPAMC_SSL
SSL_write(ssl, buf, len);
SSL_write(ssl, towrite_buf, towrite_len);
#endif
}
else {
full_write(sock, 0, buf, len);
full_write(sock, 0, towrite_buf, towrite_len);
shutdown(sock, SHUT_WR);
}
/* free zlib buffer
* bug 6025: zlib buffer not freed if compression is used
*/
if (zlib_on) {
_free_zlib_buffer(&zlib_buf, &zlib_bufsiz);
}
/* ok, now read and parse it. SPAMD/1.2 line first... */
failureval =
_spamc_read_full_line(m, flags, ssl, sock, buf, &len, bufsiz);
} /* end of filterloop */
if (failureval != EX_OK) {
goto failure;
}
if (sscanf(buf, "SPAMD/%18s %d %*s", versbuf, &response) != 2) {
libspamc_log(flags, LOG_ERR, "spamd responded with bad string '%s'", buf);
failureval = EX_PROTOCOL;
goto failure;
}
versbuf[19] = '\0';
version = _locale_safe_string_to_float(versbuf, 20);
if (version < 1.0) {
libspamc_log(flags, LOG_ERR, "spamd responded with bad version string '%s'",
versbuf);
failureval = EX_PROTOCOL;
goto failure;
}
if (flags & SPAMC_PING) {
closesocket(sock);
sock = -1;
m->out_len = sprintf(m->out, "SPAMD/%s %d\n", versbuf, response);
m->is_spam = EX_NOTSPAM;
return EX_OK;
}
m->score = 0;
m->threshold = 0;
m->is_spam = EX_TOOBIG;
while (1) {
failureval =
_spamc_read_full_line(m, flags, ssl, sock, buf, &len, bufsiz);
if (failureval != EX_OK) {
goto failure;
}
if (len == 0 && buf[0] == '\0') {
break; /* end of headers */
}
if (_handle_spamd_header(m, flags, buf, len, &throwaway) < 0) {
failureval = EX_PROTOCOL;
goto failure;
}
}
len = 0; /* overwrite those headers */
if (flags & SPAMC_CHECK_ONLY) {
closesocket(sock);
sock = -1;
if (m->is_spam == EX_TOOBIG) {
/* We should have gotten headers back... Damnit. */
failureval = EX_PROTOCOL;
goto failure;
}
return EX_OK;
}
else {
if (m->content_length < 0) {
/* should have got a length too. */
failureval = EX_PROTOCOL;
goto failure;
}
/* have we already got something in the buffer (e.g. REPORT and
* REPORT_IFSPAM both create a line from the "Spam:" hdr)? If
* so, add the size of that so our sanity check passes.
*/
if (m->out_len > 0) {
m->content_length += m->out_len;
}
if (flags & SPAMC_USE_SSL) {
len = full_read_ssl(ssl, (unsigned char *) m->out + m->out_len,
m->priv->alloced_size - m->out_len,
m->priv->alloced_size - m->out_len);
}
else {
len = full_read(sock, 0, m->out + m->out_len,
m->priv->alloced_size - m->out_len,
m->priv->alloced_size - m->out_len);
}
if ((int) len + (int) m->out_len > (m->priv->alloced_size - 1)) {
failureval = EX_TOOBIG;
goto failure;
}
m->out_len += len;
shutdown(sock, SHUT_RD);
closesocket(sock);
sock = -1;
}
libspamc_timeout = 0;
if (m->out_len != m->content_length) {
libspamc_log(flags, LOG_ERR,
"failed sanity check, %d bytes claimed, %d bytes seen",
m->content_length, m->out_len);
failureval = EX_PROTOCOL;
goto failure;
}
if (flags & SPAMC_HEADERS) {
if (_append_original_body(m, flags) != EX_OK) {
goto failure;
}
}
return EX_OK;
failure:
_use_msg_for_out(m);
if (sock != -1) {
closesocket(sock);
}
libspamc_timeout = 0;
if (flags & SPAMC_USE_SSL) {
#ifdef SPAMC_SSL
SSL_free(ssl);
SSL_CTX_free(ctx);
#endif
}
return failureval;
}
int message_process(struct transport *trans, char *username, int max_size,
int in_fd, int out_fd, const int flags)
{
int ret;
struct message m;
assert(trans != NULL);
m.type = MESSAGE_NONE;
/* enforce max_size being unsigned, therefore >= 0 */
if (max_size < 0) {
ret = EX_SOFTWARE;
goto FAIL;
}
m.max_len = (unsigned int) max_size;
ret = message_read(in_fd, flags, &m);
if (ret != EX_OK)
goto FAIL;
ret = message_filter(trans, username, flags, &m);
if (ret != EX_OK)
goto FAIL;
if (message_write(out_fd, &m) < 0)
goto FAIL;
if (m.is_spam != EX_TOOBIG) {
message_cleanup(&m);
return m.is_spam;
}
message_cleanup(&m);
return ret;
FAIL:
if (flags & SPAMC_CHECK_ONLY) {
full_write(out_fd, 1, "0/0\n", 4);
message_cleanup(&m);
return EX_NOTSPAM;
}
else {
message_dump(in_fd, out_fd, &m);
message_cleanup(&m);
return ret;
}
}
int message_tell(struct transport *tp, const char *username, int flags,
struct message *m, int msg_class,
unsigned int tellflags, unsigned int *didtellflags)
{
char buf[8192];
size_t bufsiz = (sizeof(buf) / sizeof(*buf)) - 4; /* bit of breathing room */
size_t len;
int sock = -1;
int rc;
char versbuf[20];
float version;
int response;
int failureval;
SSL_CTX *ctx = NULL;
SSL *ssl = NULL;
SSL_METHOD *meth;
assert(tp != NULL);
assert(m != NULL);
if (flags & SPAMC_USE_SSL) {
#ifdef SPAMC_SSL
SSLeay_add_ssl_algorithms();
meth = SSLv3_client_method();
SSL_load_error_strings();
ctx = SSL_CTX_new(meth);
#else
UNUSED_VARIABLE(ssl);
UNUSED_VARIABLE(meth);
UNUSED_VARIABLE(ctx);
libspamc_log(flags, LOG_ERR, "spamc not built with SSL support");
return EX_SOFTWARE;
#endif
}
m->is_spam = EX_TOOBIG;
if (m->outbuf != NULL)
free(m->outbuf);
m->priv->alloced_size = m->max_len + EXPANSION_ALLOWANCE + 1;
if ((m->outbuf = malloc(m->priv->alloced_size)) == NULL) {
failureval = EX_OSERR;
goto failure;
}
m->out = m->outbuf;
m->out_len = 0;
/* Build spamd protocol header */
strcpy(buf, "TELL ");
len = strlen(buf);
if (len + strlen(PROTOCOL_VERSION) + 2 >= bufsiz) {
_use_msg_for_out(m);
return EX_OSERR;
}
strcat(buf, PROTOCOL_VERSION);
strcat(buf, "\r\n");
len = strlen(buf);
if (msg_class != 0) {
strcpy(buf + len, "Message-class: ");
if (msg_class == SPAMC_MESSAGE_CLASS_SPAM) {
strcat(buf + len, "spam\r\n");
}
else {
strcat(buf + len, "ham\r\n");
}
len += strlen(buf + len);
}
if ((tellflags & SPAMC_SET_LOCAL) || (tellflags & SPAMC_SET_REMOTE)) {
int needs_comma_p = 0;
strcat(buf + len, "Set: ");
if (tellflags & SPAMC_SET_LOCAL) {
strcat(buf + len, "local");
needs_comma_p = 1;
}
if (tellflags & SPAMC_SET_REMOTE) {
if (needs_comma_p == 1) {
strcat(buf + len, ",");
}
strcat(buf + len, "remote");
}
strcat(buf + len, "\r\n");
len += strlen(buf + len);
}
if ((tellflags & SPAMC_REMOVE_LOCAL) || (tellflags & SPAMC_REMOVE_REMOTE)) {
int needs_comma_p = 0;
strcat(buf + len, "Remove: ");
if (tellflags & SPAMC_REMOVE_LOCAL) {
strcat(buf + len, "local");
needs_comma_p = 1;
}
if (tellflags & SPAMC_REMOVE_REMOTE) {
if (needs_comma_p == 1) {
strcat(buf + len, ",");
}
strcat(buf + len, "remote");
}
strcat(buf + len, "\r\n");
len += strlen(buf + len);
}
if (username != NULL) {
if (strlen(username) + 8 >= (bufsiz - len)) {
_use_msg_for_out(m);
return EX_OSERR;
}
strcpy(buf + len, "User: ");
strcat(buf + len, username);
strcat(buf + len, "\r\n");
len += strlen(buf + len);
}
if ((m->msg_len > SPAMC_MAX_MESSAGE_LEN) || ((len + 27) >= (bufsiz - len))) {
_use_msg_for_out(m);
return EX_DATAERR;
}
len += sprintf(buf + len, "Content-length: %d\r\n\r\n", (int) m->msg_len);
if (m->priv->spamc_header_callback != NULL) {
char buf2[1024];
m->priv->spamc_header_callback(m, flags, buf2, 1024);
strncat(buf, buf2, bufsiz - len);
}
libspamc_timeout = m->timeout;
libspamc_connect_timeout = m->connect_timeout; /* Sep 8, 2008 mrgus: separate connect timeout */
if (tp->socketpath)
rc = _try_to_connect_unix(tp, &sock);
else
rc = _try_to_connect_tcp(tp, &sock);
if (rc != EX_OK) {
_use_msg_for_out(m);
return rc; /* use the error code try_to_connect_*() gave us. */
}
if (flags & SPAMC_USE_SSL) {
#ifdef SPAMC_SSL
ssl = SSL_new(ctx);
SSL_set_fd(ssl, sock);
SSL_connect(ssl);
#endif
}
/* Send to spamd */
if (flags & SPAMC_USE_SSL) {
#ifdef SPAMC_SSL
SSL_write(ssl, buf, len);
SSL_write(ssl, m->msg, m->msg_len);
#endif
}
else {
full_write(sock, 0, buf, len);
full_write(sock, 0, m->msg, m->msg_len);
shutdown(sock, SHUT_WR);
}
/* ok, now read and parse it. SPAMD/1.2 line first... */
failureval =
_spamc_read_full_line(m, flags, ssl, sock, buf, &len, bufsiz);
if (failureval != EX_OK) {
goto failure;
}
if (sscanf(buf, "SPAMD/%18s %d %*s", versbuf, &response) != 2) {
libspamc_log(flags, LOG_ERR, "spamd responded with bad string '%s'", buf);
failureval = EX_PROTOCOL;
goto failure;
}
versbuf[19] = '\0';
version = _locale_safe_string_to_float(versbuf, 20);
if (version < 1.0) {
libspamc_log(flags, LOG_ERR, "spamd responded with bad version string '%s'",
versbuf);
failureval = EX_PROTOCOL;
goto failure;
}
m->score = 0;
m->threshold = 0;
m->is_spam = EX_TOOBIG;
while (1) {
failureval =
_spamc_read_full_line(m, flags, ssl, sock, buf, &len, bufsiz);
if (failureval != EX_OK) {
goto failure;
}
if (len == 0 && buf[0] == '\0') {
break; /* end of headers */
}
if (_handle_spamd_header(m, flags, buf, len, didtellflags) < 0) {
failureval = EX_PROTOCOL;
goto failure;
}
}
len = 0; /* overwrite those headers */
shutdown(sock, SHUT_RD);
closesocket(sock);
sock = -1;
libspamc_timeout = 0;
return EX_OK;
failure:
_use_msg_for_out(m);
if (sock != -1) {
closesocket(sock);
}
libspamc_timeout = 0;
if (flags & SPAMC_USE_SSL) {
#ifdef SPAMC_SSL
SSL_free(ssl);
SSL_CTX_free(ctx);
#endif
}
return failureval;
}
void message_cleanup(struct message *m)
{
assert(m != NULL);
if (m->outbuf != NULL)
free(m->outbuf);
if (m->raw != NULL)
free(m->raw);
if (m->priv != NULL)
free(m->priv);
_clear_message(m);
}
/* Aug 14, 2002 bj: Obsolete! */
int process_message(struct transport *tp, char *username, int max_size,
int in_fd, int out_fd, const int my_check_only,
const int my_safe_fallback)
{
int flags;
flags = SPAMC_RAW_MODE;
if (my_check_only)
flags |= SPAMC_CHECK_ONLY;
if (my_safe_fallback)
flags |= SPAMC_SAFE_FALLBACK;
return message_process(tp, username, max_size, in_fd, out_fd, flags);
}
/*
* init_transport()
*
* Given a pointer to a transport structure, set it to "all empty".
* The default is a localhost connection.
*/
void transport_init(struct transport *tp)
{
assert(tp != 0);
memset(tp, 0, sizeof *tp);
tp->type = TRANSPORT_LOCALHOST;
tp->port = 783;
tp->flags = 0;
tp->retry_sleep = -1;
}
/*
* randomize_hosts()
*
* Given the transport object that contains one or more IP addresses
* in this "hosts" list, rotate it by a random number of shifts to
* randomize them - this is a kind of load balancing. It's possible
* that the random number will be 0, which says not to touch. We don't
* do anything unless
*/
static void _randomize_hosts(struct transport *tp)
{
#ifdef SPAMC_HAS_ADDRINFO
struct addrinfo *tmp;
#else
struct in_addr tmp;
#endif
int i;
int rnum;
assert(tp != 0);
if (tp->nhosts <= 1)
return;
rnum = rand() % tp->nhosts;
while (rnum-- > 0) {
tmp = tp->hosts[0];
for (i = 1; i < tp->nhosts; i++)
tp->hosts[i - 1] = tp->hosts[i];
tp->hosts[i - 1] = tmp;
}
}
/*
* transport_setup()
*
* Given a "transport" object that says how we're to connect to the
* spam daemon, perform all the initial setup required to make the
* connection process a smooth one. The main work is to do the host
* name lookup and copy over all the IP addresses to make a local copy
* so they're not kept in the resolver's static state.
*
* Here we also manage quasi-load balancing and failover: if we're
* doing load balancing, we randomly "rotate" the list to put it in
* a different order, and then if we're not doing failover we limit
* the hosts to just one. This way *all* connections are done with
* the intention of failover - makes the code a bit more clear.
*/
int transport_setup(struct transport *tp, int flags)
{
#ifdef SPAMC_HAS_ADDRINFO
struct addrinfo hints, *res, *addrp;
char port[6];
int origerr;
#else
struct hostent *hp;
char **addrp;
#endif
char *hostlist, *hostname;
int errbits;
#ifdef _WIN32
/* Start Winsock up */
WSADATA wsaData;
int nCode;
if ((nCode = WSAStartup(MAKEWORD(1, 1), &wsaData)) != 0) {
printf("WSAStartup() returned error code %d\n", nCode);
return EX_OSERR;
}
#endif
assert(tp != NULL);
tp->flags = flags;
#ifdef SPAMC_HAS_ADDRINFO
snprintf(port, 6, "%d", tp->port);
memset(&hints, 0, sizeof(hints));
hints.ai_flags = 0;
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
#endif
switch (tp->type) {
#ifndef _WIN32
case TRANSPORT_UNIX:
assert(tp->socketpath != 0);
return EX_OK;
#endif
case TRANSPORT_LOCALHOST:
#ifdef SPAMC_HAS_ADDRINFO
/* getaddrinfo(NULL) will look up the loopback address.
* bug 5057: unfortunately, it's the IPv6 loopback address on
* linux! Be explicit, and force IPv4 using "127.0.0.1".
*/
if ((origerr = getaddrinfo("127.0.0.1", port, &hints, &res)) != 0) {
libspamc_log(flags, LOG_ERR,
"getaddrinfo(127.0.0.1) failed: %s",
gai_strerror(origerr));
return EX_OSERR;
}
tp->hosts[0] = res;
#else
tp->hosts[0].s_addr = inet_addr("127.0.0.1");
#endif
tp->nhosts = 1;
return EX_OK;
case TRANSPORT_TCP:
if ((hostlist = strdup(tp->hostname)) == NULL)
return EX_OSERR;
/* We want to return the least permanent error, in this bitmask we
* record the errors seen with:
* 0: no error
* 1: EX_TEMPFAIL
* 2: EX_NOHOST
* EX_OSERR will return immediately.
* Bits aren't reset so a check against nhosts is needed to determine
* if something went wrong.
*/
errbits = 0;
tp->nhosts = 0;
/* Start with char offset in front of the string because we'll add
* one in the loop
*/
hostname = hostlist - 1;
do {
char *hostend;
hostname += 1;
hostend = strchr(hostname, ',');
if (hostend != NULL) {
*hostend = '\0';
}
#ifdef SPAMC_HAS_ADDRINFO
if ((origerr = getaddrinfo(hostname, port, &hints, &res))) {
libspamc_log(flags, LOG_DEBUG,
"getaddrinfo(%s) failed: %s",
hostname, gai_strerror(origerr));
switch (origerr) {
case EAI_AGAIN:
errbits |= 1;
break;
case EAI_FAMILY: /*address family not supported*/
case EAI_SOCKTYPE: /*socket type not supported*/
case EAI_BADFLAGS: /*ai_flags is invalid*/
case EAI_NONAME: /*node or service unknown*/
case EAI_SERVICE: /*service not available*/
/* work around Cygwin IPv6 patch - err codes not defined in Windows aren't in patch */
#ifdef HAVE_EAI_ADDRFAMILY
case EAI_ADDRFAMILY: /*no addresses in requested family*/
#endif
#ifdef HAVE_EAI_SYSTEM
case EAI_SYSTEM: /*system error, check errno*/
#endif
#ifdef HAVE_EAI_NODATA
case EAI_NODATA: /*address exists, but no data*/
#endif
case EAI_MEMORY: /*out of memory*/
case EAI_FAIL: /*name server returned permanent error*/
errbits |= 2;
break;
default:
/* should not happen, all errors are checked above */
free(hostlist);
return EX_OSERR;
}
goto nexthost; /* try next host in list */
}
#else
if ((hp = gethostbyname(hostname)) == NULL) {
int origerr = h_errno; /* take a copy before syslog() */
libspamc_log(flags, LOG_DEBUG, "gethostbyname(%s) failed: h_errno=%d",
hostname, origerr);
switch (origerr) {
case TRY_AGAIN:
errbits |= 1;
break;
case HOST_NOT_FOUND:
case NO_ADDRESS:
case NO_RECOVERY:
errbits |= 2;
break;
default:
/* should not happen, all errors are checked above */
free(hostlist);
return EX_OSERR;
}
goto nexthost; /* try next host in list */
}
#endif
/* If we have no hosts at all */
#ifdef SPAMC_HAS_ADDRINFO
if(res == NULL)
#else
if (hp->h_addr_list[0] == NULL
|| hp->h_length != sizeof tp->hosts[0]
|| hp->h_addrtype != AF_INET)
/* no hosts/bad size/wrong family */
#endif
{
errbits |= 1;
goto nexthost; /* try next host in list */
}
/* Copy all the IP addresses into our private structure.
* This gets them out of the resolver's static area and
* means we won't ever walk all over the list with other
* calls.
*/
#ifdef SPAMC_HAS_ADDRINFO
if(tp->nhosts == TRANSPORT_MAX_HOSTS) {
libspamc_log(flags, LOG_NOTICE,
"hit limit of %d hosts, ignoring remainder",
TRANSPORT_MAX_HOSTS);
break;
}
for (addrp = res; addrp != NULL; ) {
tp->hosts[tp->nhosts] = addrp;
addrp = addrp->ai_next; /* before NULLing ai_next */
tp->hosts[tp->nhosts]->ai_next = NULL;
tp->nhosts++;
}
#else
for (addrp = hp->h_addr_list; *addrp; addrp++) {
if (tp->nhosts == TRANSPORT_MAX_HOSTS) {
libspamc_log(flags, LOG_NOTICE, "hit limit of %d hosts, ignoring remainder",
TRANSPORT_MAX_HOSTS);
break;
}
memcpy(&tp->hosts[tp->nhosts], *addrp, hp->h_length);
tp->nhosts++;
}
#endif
nexthost:
hostname = hostend;
} while (hostname != NULL);
free(hostlist);
if (tp->nhosts == 0) {
if (errbits & 1) {
libspamc_log(flags, LOG_ERR, "could not resolve any hosts (%s): a temporary error occurred",
tp->hostname);
return EX_TEMPFAIL;
}
else {
libspamc_log(flags, LOG_ERR, "could not resolve any hosts (%s): no such host",
tp->hostname);
return EX_NOHOST;
}
}
/* QUASI-LOAD-BALANCING
*
* If the user wants to do quasi load balancing, "rotate"
* the list by a random amount based on the current time.
* This may later be truncated to a single item. This is
* meaningful only if we have more than one host.
*/
if ((flags & SPAMC_RANDOMIZE_HOSTS) && tp->nhosts > 1) {
_randomize_hosts(tp);
}
/* If the user wants no fallback, simply truncate the host
* list to just one - this pretends that this is the extent
* of our connection list - then it's not a special case.
*/
if (!(flags & SPAMC_SAFE_FALLBACK) && tp->nhosts > 1) {
/* truncating list */
tp->nhosts = 1;
}
return EX_OK;
}
/* oops, unknown transport type */
return EX_OSERR;
}
/*
* transport_cleanup()
*
* Given a "transport" object that says how we're to connect to the
* spam daemon, delete and free any buffers allocated so that it
* can be discarded without causing a memory leak.
*/
void transport_cleanup(struct transport *tp)
{
#ifdef SPAMC_HAS_ADDRINFO
int i;
for(i=0;i<tp->nhosts;i++) {
if (tp->hosts[i] != NULL) {
freeaddrinfo(tp->hosts[i]);
tp->hosts[i] = NULL;
}
}
#endif
}
/*
* register_libspamc_log_callback()
*
* Register a callback handler for libspamc_log to replace the default behaviour.
*/
void register_libspamc_log_callback(void (*function)(int flags, int level, char *msg, va_list args)) {
libspamc_log_callback = function;
}
/*
* register_spamc_header_callback()
*
* Register a callback handler to generate spamc headers for a given message
*/
void register_spamc_header_callback(const struct message *m, void (*func)(struct message *m, int flags, char *buf, int len)) {
m->priv->spamc_header_callback = func;
}
/*
* register_spamd_header_callback()
*
* Register a callback handler to generate spamd headers for a given message
*/
void register_spamd_header_callback(const struct message *m, void (*func)(struct message *m, int flags, const char *buf, int len)) {
m->priv->spamd_header_callback = func;
}
/* --------------------------------------------------------------------------- */
#define LOG_BUFSIZ 1023
void
libspamc_log (int flags, int level, char *msg, ...)
{
va_list ap;
char buf[LOG_BUFSIZ+1];
int len = 0;
va_start(ap, msg);
if ((flags & SPAMC_LOG_TO_CALLBACK) != 0 && libspamc_log_callback != NULL) {
libspamc_log_callback(flags, level, msg, ap);
}
else if ((flags & SPAMC_LOG_TO_STDERR) != 0) {
/* create a log-line buffer */
len = snprintf(buf, LOG_BUFSIZ, "spamc: ");
len += vsnprintf(buf+len, LOG_BUFSIZ-len, msg, ap);
/* avoid buffer overflow */
if (len > (LOG_BUFSIZ-2)) { len = (LOG_BUFSIZ-3); }
len += snprintf(buf+len, LOG_BUFSIZ-len, "\n");
buf[LOG_BUFSIZ] = '\0'; /* ensure termination */
(void) write (2, buf, len);
} else {
vsnprintf(buf, LOG_BUFSIZ, msg, ap);
buf[LOG_BUFSIZ] = '\0'; /* ensure termination */
#ifndef _WIN32
syslog (level, "%s", buf);
#else
(void) level; /* not used. suppress compiler warning */
fprintf (stderr, "%s\n", buf);
#endif
}
va_end(ap);
}
/* --------------------------------------------------------------------------- */
/*
* Unit tests. Must be built externally, e.g.:
*
* gcc -g -DLIBSPAMC_UNIT_TESTS spamd/spamc.c spamd/libspamc.c spamd/utils.c -o libspamctest
* ./libspamctest
*
*/
#ifdef LIBSPAMC_UNIT_TESTS
static void _test_locale_safe_string_to_float_val(float input)
{
char inputstr[99], cmpbuf1[99], cmpbuf2[99];
float output;
/* sprintf instead of snprintf is safe here because it is only a controlled test */
sprintf(inputstr, "%f", input);
output = _locale_safe_string_to_float(inputstr, 99);
if (input == output) {
return;
}
/* could be a rounding error. print as string and compare those */
sprintf(cmpbuf1, "%f", input);
sprintf(cmpbuf2, "%f", output);
if (!strcmp(cmpbuf1, cmpbuf2)) {
return;
}
printf("FAIL: input=%f != output=%f\n", input, output);
}
static void unit_test_locale_safe_string_to_float(void)
{
float statictestset[] = { /* will try both +ve and -ve */
0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001,
9.1, 9.91, 9.991, 9.9991, 9.99991, 9.999991,
0.0 /* end of set constant */
};
float num;
int i;
printf("starting unit_test_locale_safe_string_to_float\n");
/* tests of precision */
for (i = 0; statictestset[i] != 0.0; i++) {
_test_locale_safe_string_to_float_val(statictestset[i]);
_test_locale_safe_string_to_float_val(-statictestset[i]);
_test_locale_safe_string_to_float_val(1 - statictestset[i]);
_test_locale_safe_string_to_float_val(1 + statictestset[i]);
}
/* now exhaustive, in steps of 0.01 */
for (num = -1000.0; num < 1000.0; num += 0.01) {
_test_locale_safe_string_to_float_val(num);
}
printf("finished unit_test_locale_safe_string_to_float\n");
}
void do_libspamc_unit_tests(void)
{
unit_test_locale_safe_string_to_float();
exit(0);
}
#endif /* LIBSPAMC_UNIT_TESTS */
|