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 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505
|
/*
* 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.
*/
package org.apache.tomcat.util.net;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.jni.Address;
import org.apache.tomcat.jni.Error;
import org.apache.tomcat.jni.File;
import org.apache.tomcat.jni.Library;
import org.apache.tomcat.jni.OS;
import org.apache.tomcat.jni.Poll;
import org.apache.tomcat.jni.Pool;
import org.apache.tomcat.jni.SSL;
import org.apache.tomcat.jni.SSLContext;
import org.apache.tomcat.jni.SSLSocket;
import org.apache.tomcat.jni.Sockaddr;
import org.apache.tomcat.jni.Socket;
import org.apache.tomcat.jni.Status;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.net.AbstractEndpoint.Acceptor.AcceptorState;
import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState;
import org.apache.tomcat.util.security.PrivilegedSetTccl;
/**
* APR tailored thread pool, providing the following services:
* <ul>
* <li>Socket acceptor thread</li>
* <li>Socket poller thread</li>
* <li>Sendfile thread</li>
* <li>Worker threads pool</li>
* </ul>
*
* When switching to Java 5, there's an opportunity to use the virtual
* machine's thread pool.
*
* @author Mladen Turk
* @author Remy Maucherat
*/
public class AprEndpoint extends AbstractEndpoint<Long> {
// -------------------------------------------------------------- Constants
private static final Log log = LogFactory.getLog(AprEndpoint.class);
// ----------------------------------------------------------------- Fields
/**
* Root APR memory pool.
*/
protected long rootPool = 0;
/**
* Server socket "pointer".
*/
protected long serverSock = 0;
/**
* APR memory pool for the server socket.
*/
protected long serverSockPool = 0;
/**
* SSL context.
*/
protected long sslContext = 0;
protected ConcurrentLinkedQueue<SocketWrapper<Long>> waitingRequests =
new ConcurrentLinkedQueue<SocketWrapper<Long>>();
private final Map<Long,AprSocketWrapper> connections =
new ConcurrentHashMap<Long, AprSocketWrapper>();
// ------------------------------------------------------------ Constructor
public AprEndpoint() {
// Need to override the default for maxConnections to align it with what
// was pollerSize (before the two were merged)
setMaxConnections(8 * 1024);
}
// ------------------------------------------------------------- Properties
/**
* Defer accept.
*/
protected boolean deferAccept = true;
public void setDeferAccept(boolean deferAccept) { this.deferAccept = deferAccept; }
@Override
public boolean getDeferAccept() { return deferAccept; }
/**
* Size of the sendfile (= concurrent files which can be served).
*/
protected int sendfileSize = 1 * 1024;
public void setSendfileSize(int sendfileSize) { this.sendfileSize = sendfileSize; }
public int getSendfileSize() { return sendfileSize; }
/**
* Handling of accepted sockets.
*/
protected Handler handler = null;
public void setHandler(Handler handler ) { this.handler = handler; }
public Handler getHandler() { return handler; }
/**
* Poll interval, in microseconds. The smaller the value, the more CPU the poller
* will use, but the more responsive to activity it will be.
*/
protected int pollTime = 2000;
public int getPollTime() { return pollTime; }
public void setPollTime(int pollTime) { if (pollTime > 0) { this.pollTime = pollTime; } }
/**
* Use sendfile for sending static files.
*/
protected boolean useSendfile = Library.APR_HAS_SENDFILE;
public void setUseSendfile(boolean useSendfile) { this.useSendfile = useSendfile; }
@Override
public boolean getUseSendfile() { return useSendfile; }
/**
* Allow comet request handling.
*/
protected boolean useComet = true;
public void setUseComet(boolean useComet) { this.useComet = useComet; }
@Override
public boolean getUseComet() { return useComet; }
@Override
public boolean getUseCometTimeout() { return false; } // Not supported
@Override
public boolean getUsePolling() { return true; } // Always supported
/**
* Sendfile thread count.
*/
protected int sendfileThreadCount = 0;
public void setSendfileThreadCount(int sendfileThreadCount) { this.sendfileThreadCount = sendfileThreadCount; }
public int getSendfileThreadCount() { return sendfileThreadCount; }
/**
* The socket poller.
*/
protected Poller poller = null;
public Poller getPoller() {
return poller;
}
/**
* The socket poller.
*/
protected AsyncTimeout asyncTimeout = null;
public AsyncTimeout getAsyncTimeout() {
return asyncTimeout;
}
/**
* The static file sender.
*/
protected Sendfile sendfile = null;
public Sendfile getSendfile() {
return sendfile;
}
/**
* SSL protocols.
*/
protected String SSLProtocol = "all";
public String getSSLProtocol() { return SSLProtocol; }
public void setSSLProtocol(String SSLProtocol) { this.SSLProtocol = SSLProtocol; }
/**
* SSL password (if a cert is encrypted, and no password has been provided, a callback
* will ask for a password).
*/
protected String SSLPassword = null;
public String getSSLPassword() { return SSLPassword; }
public void setSSLPassword(String SSLPassword) { this.SSLPassword = SSLPassword; }
/**
* SSL cipher suite.
*/
protected String SSLCipherSuite = "ALL";
public String getSSLCipherSuite() { return SSLCipherSuite; }
public void setSSLCipherSuite(String SSLCipherSuite) { this.SSLCipherSuite = SSLCipherSuite; }
/**
* SSL certificate file.
*/
protected String SSLCertificateFile = null;
public String getSSLCertificateFile() { return SSLCertificateFile; }
public void setSSLCertificateFile(String SSLCertificateFile) { this.SSLCertificateFile = SSLCertificateFile; }
/**
* SSL certificate key file.
*/
protected String SSLCertificateKeyFile = null;
public String getSSLCertificateKeyFile() { return SSLCertificateKeyFile; }
public void setSSLCertificateKeyFile(String SSLCertificateKeyFile) { this.SSLCertificateKeyFile = SSLCertificateKeyFile; }
/**
* SSL certificate chain file.
*/
protected String SSLCertificateChainFile = null;
public String getSSLCertificateChainFile() { return SSLCertificateChainFile; }
public void setSSLCertificateChainFile(String SSLCertificateChainFile) { this.SSLCertificateChainFile = SSLCertificateChainFile; }
/**
* SSL CA certificate path.
*/
protected String SSLCACertificatePath = null;
public String getSSLCACertificatePath() { return SSLCACertificatePath; }
public void setSSLCACertificatePath(String SSLCACertificatePath) { this.SSLCACertificatePath = SSLCACertificatePath; }
/**
* SSL CA certificate file.
*/
protected String SSLCACertificateFile = null;
public String getSSLCACertificateFile() { return SSLCACertificateFile; }
public void setSSLCACertificateFile(String SSLCACertificateFile) { this.SSLCACertificateFile = SSLCACertificateFile; }
/**
* SSL CA revocation path.
*/
protected String SSLCARevocationPath = null;
public String getSSLCARevocationPath() { return SSLCARevocationPath; }
public void setSSLCARevocationPath(String SSLCARevocationPath) { this.SSLCARevocationPath = SSLCARevocationPath; }
/**
* SSL CA revocation file.
*/
protected String SSLCARevocationFile = null;
public String getSSLCARevocationFile() { return SSLCARevocationFile; }
public void setSSLCARevocationFile(String SSLCARevocationFile) { this.SSLCARevocationFile = SSLCARevocationFile; }
/**
* SSL verify client.
*/
protected String SSLVerifyClient = "none";
public String getSSLVerifyClient() { return SSLVerifyClient; }
public void setSSLVerifyClient(String SSLVerifyClient) { this.SSLVerifyClient = SSLVerifyClient; }
/**
* SSL verify depth.
*/
protected int SSLVerifyDepth = 10;
public int getSSLVerifyDepth() { return SSLVerifyDepth; }
public void setSSLVerifyDepth(int SSLVerifyDepth) { this.SSLVerifyDepth = SSLVerifyDepth; }
/**
* SSL allow insecure renegotiation for the the client that does not
* support the secure renegotiation.
*/
protected boolean SSLInsecureRenegotiation = false;
public void setSSLInsecureRenegotiation(boolean SSLInsecureRenegotiation) { this.SSLInsecureRenegotiation = SSLInsecureRenegotiation; }
public boolean getSSLInsecureRenegotiation() { return SSLInsecureRenegotiation; }
protected boolean SSLHonorCipherOrder = false;
/**
* Set to <code>true</code> to enforce the <i>server's</i> cipher order
* instead of the default which is to allow the client to choose a
* preferred cipher.
*/
public void setSSLHonorCipherOrder(boolean SSLHonorCipherOrder) { this.SSLHonorCipherOrder = SSLHonorCipherOrder; }
public boolean getSSLHonorCipherOrder() { return SSLHonorCipherOrder; }
/**
* Disables compression of the SSL stream. This thwarts CRIME attack
* and possibly improves performance by not compressing uncompressible
* content such as JPEG, etc.
*/
protected boolean SSLDisableCompression = false;
/**
* Set to <code>true</code> to disable SSL compression. This thwarts CRIME
* attack.
*/
public void setSSLDisableCompression(boolean SSLDisableCompression) { this.SSLDisableCompression = SSLDisableCompression; }
public boolean getSSLDisableCompression() { return SSLDisableCompression; }
/**
* Port in use.
*/
@Override
public int getLocalPort() {
long s = serverSock;
if (s == 0) {
return -1;
} else {
long sa;
try {
sa = Address.get(Socket.APR_LOCAL, s);
Sockaddr addr = Address.getInfo(sa);
return addr.port;
} catch (Exception e) {
return -1;
}
}
}
/**
* This endpoint does not support <code>-1</code> for unlimited connections,
* nor does it support setting this attribute while the endpoint is running.
*
* {@inheritDoc}
*/
@Override
public void setMaxConnections(int maxConnections) {
if (maxConnections == -1) {
log.warn(sm.getString("endpoint.apr.maxConnections.unlimited",
Integer.valueOf(getMaxConnections())));
return;
}
if (running) {
log.warn(sm.getString("endpoint.apr.maxConnections.running",
Integer.valueOf(getMaxConnections())));
return;
}
super.setMaxConnections(maxConnections);
}
// --------------------------------------------------------- Public Methods
/**
* Number of keepalive sockets.
*/
public int getKeepAliveCount() {
if (poller == null) {
return 0;
}
return poller.getConnectionCount();
}
/**
* Number of sendfile sockets.
*/
public int getSendfileCount() {
if (sendfile == null) {
return 0;
}
return sendfile.getSendfileCount();
}
// ----------------------------------------------- Public Lifecycle Methods
/**
* Initialize the endpoint.
*/
@Override
public void bind() throws Exception {
// Create the root APR memory pool
try {
rootPool = Pool.create(0);
} catch (UnsatisfiedLinkError e) {
throw new Exception(sm.getString("endpoint.init.notavail"));
}
// Create the pool for the server socket
serverSockPool = Pool.create(rootPool);
// Create the APR address that will be bound
String addressStr = null;
if (getAddress() != null) {
addressStr = getAddress().getHostAddress();
}
int family = Socket.APR_INET;
if (Library.APR_HAVE_IPV6) {
if (addressStr == null) {
if (!OS.IS_BSD && !OS.IS_WIN32 && !OS.IS_WIN64)
family = Socket.APR_UNSPEC;
} else if (addressStr.indexOf(':') >= 0) {
family = Socket.APR_UNSPEC;
}
}
long inetAddress = Address.info(addressStr, family,
getPort(), 0, rootPool);
// Create the APR server socket
serverSock = Socket.create(Address.getInfo(inetAddress).family,
Socket.SOCK_STREAM,
Socket.APR_PROTO_TCP, rootPool);
if (OS.IS_UNIX) {
Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1);
}
// Deal with the firewalls that tend to drop the inactive sockets
Socket.optSet(serverSock, Socket.APR_SO_KEEPALIVE, 1);
// Bind the server socket
int ret = Socket.bind(serverSock, inetAddress);
if (ret != 0) {
throw new Exception(sm.getString("endpoint.init.bind", "" + ret, Error.strerror(ret)));
}
// Start listening on the server socket
ret = Socket.listen(serverSock, getBacklog());
if (ret != 0) {
throw new Exception(sm.getString("endpoint.init.listen", "" + ret, Error.strerror(ret)));
}
if (OS.IS_WIN32 || OS.IS_WIN64) {
// On Windows set the reuseaddr flag after the bind/listen
Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1);
}
// Sendfile usage on systems which don't support it cause major problems
if (useSendfile && !Library.APR_HAS_SENDFILE) {
useSendfile = false;
}
// Initialize thread count default for acceptor
if (acceptorThreadCount == 0) {
// FIXME: Doesn't seem to work that well with multiple accept threads
acceptorThreadCount = 1;
}
// Delay accepting of new connections until data is available
// Only Linux kernels 2.4 + have that implemented
// on other platforms this call is noop and will return APR_ENOTIMPL.
if (deferAccept) {
if (Socket.optSet(serverSock, Socket.APR_TCP_DEFER_ACCEPT, 1) == Status.APR_ENOTIMPL) {
deferAccept = false;
}
}
// Initialize SSL if needed
if (isSSLEnabled()) {
if (SSLCertificateFile == null) {
// This is required
throw new Exception(sm.getString("endpoint.apr.noSslCertFile"));
}
// SSL protocol
int value = SSL.SSL_PROTOCOL_NONE;
if (SSLProtocol == null || SSLProtocol.length() == 0) {
value = SSL.SSL_PROTOCOL_ALL;
} else {
for (String protocol : SSLProtocol.split("\\+")) {
protocol = protocol.trim();
if ("SSLv2".equalsIgnoreCase(protocol)) {
value |= SSL.SSL_PROTOCOL_SSLV2;
} else if ("SSLv3".equalsIgnoreCase(protocol)) {
value |= SSL.SSL_PROTOCOL_SSLV3;
} else if ("TLSv1".equalsIgnoreCase(protocol)) {
value |= SSL.SSL_PROTOCOL_TLSV1;
} else if ("all".equalsIgnoreCase(protocol)) {
value |= SSL.SSL_PROTOCOL_ALL;
} else {
// Protocol not recognized, fail to start as it is safer than
// continuing with the default which might enable more than the
// is required
throw new Exception(sm.getString(
"endpoint.apr.invalidSslProtocol", SSLProtocol));
}
}
}
// Create SSL Context
try {
sslContext = SSLContext.make(rootPool, value, SSL.SSL_MODE_SERVER);
} catch (Exception e) {
// If the sslEngine is disabled on the AprLifecycleListener
// there will be an Exception here but there is no way to check
// the AprLifecycleListener settings from here
throw new Exception(
sm.getString("endpoint.apr.failSslContextMake"), e);
}
if (SSLInsecureRenegotiation) {
boolean legacyRenegSupported = false;
try {
legacyRenegSupported = SSL.hasOp(SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
if (legacyRenegSupported)
SSLContext.setOptions(sslContext, SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
} catch (UnsatisfiedLinkError e) {
// Ignore
}
if (!legacyRenegSupported) {
// OpenSSL does not support unsafe legacy renegotiation.
log.warn(sm.getString("endpoint.warn.noInsecureReneg",
SSL.versionString()));
}
}
// Set cipher order: client (default) or server
if (SSLHonorCipherOrder) {
boolean orderCiphersSupported = false;
try {
orderCiphersSupported = SSL.hasOp(SSL.SSL_OP_CIPHER_SERVER_PREFERENCE);
if (orderCiphersSupported)
SSLContext.setOptions(sslContext, SSL.SSL_OP_CIPHER_SERVER_PREFERENCE);
} catch (UnsatisfiedLinkError e) {
// Ignore
}
if (!orderCiphersSupported) {
// OpenSSL does not support ciphers ordering.
log.warn(sm.getString("endpoint.warn.noHonorCipherOrder",
SSL.versionString()));
}
}
// Disable compression if requested
if (SSLDisableCompression) {
boolean disableCompressionSupported = false;
try {
disableCompressionSupported = SSL.hasOp(SSL.SSL_OP_NO_COMPRESSION);
if (disableCompressionSupported)
SSLContext.setOptions(sslContext, SSL.SSL_OP_NO_COMPRESSION);
} catch (UnsatisfiedLinkError e) {
// Ignore
}
if (!disableCompressionSupported) {
// OpenSSL does not support ciphers ordering.
log.warn(sm.getString("endpoint.warn.noDisableCompression",
SSL.versionString()));
}
}
// List the ciphers that the client is permitted to negotiate
SSLContext.setCipherSuite(sslContext, SSLCipherSuite);
// Load Server key and certificate
SSLContext.setCertificate(sslContext, SSLCertificateFile, SSLCertificateKeyFile, SSLPassword, SSL.SSL_AIDX_RSA);
// Set certificate chain file
SSLContext.setCertificateChainFile(sslContext, SSLCertificateChainFile, false);
// Support Client Certificates
SSLContext.setCACertificate(sslContext, SSLCACertificateFile, SSLCACertificatePath);
// Set revocation
SSLContext.setCARevocation(sslContext, SSLCARevocationFile, SSLCARevocationPath);
// Client certificate verification
value = SSL.SSL_CVERIFY_NONE;
if ("optional".equalsIgnoreCase(SSLVerifyClient)) {
value = SSL.SSL_CVERIFY_OPTIONAL;
} else if ("require".equalsIgnoreCase(SSLVerifyClient)) {
value = SSL.SSL_CVERIFY_REQUIRE;
} else if ("optionalNoCA".equalsIgnoreCase(SSLVerifyClient)) {
value = SSL.SSL_CVERIFY_OPTIONAL_NO_CA;
}
SSLContext.setVerify(sslContext, value, SSLVerifyDepth);
// For now, sendfile is not supported with SSL
useSendfile = false;
}
}
/**
* Start the APR endpoint, creating acceptor, poller and sendfile threads.
*/
@Override
public void startInternal() throws Exception {
if (!running) {
running = true;
paused = false;
// Create worker collection
if (getExecutor() == null) {
createExecutor();
}
initializeConnectionLatch();
// Start poller thread
poller = new Poller();
poller.init();
Thread pollerThread = new Thread(poller, getName() + "-Poller");
pollerThread.setPriority(threadPriority);
pollerThread.setDaemon(true);
pollerThread.start();
// Start sendfile thread
if (useSendfile) {
sendfile = new Sendfile();
sendfile.init();
Thread sendfileThread =
new Thread(sendfile, getName() + "-Sendfile");
sendfileThread.setPriority(threadPriority);
sendfileThread.setDaemon(true);
sendfileThread.start();
}
startAcceptorThreads();
// Start async timeout thread
asyncTimeout = new AsyncTimeout();
Thread timeoutThread = new Thread(asyncTimeout,
getName() + "-AsyncTimeout");
timeoutThread.setPriority(threadPriority);
timeoutThread.setDaemon(true);
timeoutThread.start();
}
}
/**
* Stop the endpoint. This will cause all processing threads to stop.
*/
@Override
public void stopInternal() {
releaseConnectionLatch();
if (!paused) {
pause();
}
if (running) {
running = false;
poller.stop();
asyncTimeout.stop();
unlockAccept();
for (AbstractEndpoint.Acceptor acceptor : acceptors) {
long waitLeft = 10000;
while (waitLeft > 0 &&
acceptor.getState() != AcceptorState.ENDED &&
serverSock != 0) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// Ignore
}
waitLeft -= 50;
}
if (waitLeft == 0) {
log.warn(sm.getString("endpoint.warn.unlockAcceptorFailed",
acceptor.getThreadName()));
// If the Acceptor is still running force
// the hard socket close.
if (serverSock != 0) {
Socket.shutdown(serverSock, Socket.APR_SHUTDOWN_READ);
serverSock = 0;
}
}
}
try {
poller.destroy();
} catch (Exception e) {
// Ignore
}
poller = null;
connections.clear();
if (useSendfile) {
try {
sendfile.destroy();
} catch (Exception e) {
// Ignore
}
sendfile = null;
}
}
shutdownExecutor();
}
/**
* Deallocate APR memory pools, and close server socket.
*/
@Override
public void unbind() throws Exception {
if (running) {
stop();
}
// Destroy pool if it was initialised
if (serverSockPool != 0) {
Pool.destroy(serverSockPool);
serverSockPool = 0;
}
// Close server socket if it was initialised
if (serverSock != 0) {
Socket.close(serverSock);
serverSock = 0;
}
sslContext = 0;
// Close all APR memory pools and resources if initialised
if (rootPool != 0) {
Pool.destroy(rootPool);
rootPool = 0;
}
handler.recycle();
}
// ------------------------------------------------------ Protected Methods
@Override
protected AbstractEndpoint.Acceptor createAcceptor() {
return new Acceptor();
}
/**
* Process the specified connection.
*/
protected boolean setSocketOptions(long socket) {
// Process the connection
int step = 1;
try {
// 1: Set socket options: timeout, linger, etc
if (socketProperties.getSoLingerOn() && socketProperties.getSoLingerTime() >= 0)
Socket.optSet(socket, Socket.APR_SO_LINGER, socketProperties.getSoLingerTime());
if (socketProperties.getTcpNoDelay())
Socket.optSet(socket, Socket.APR_TCP_NODELAY, (socketProperties.getTcpNoDelay() ? 1 : 0));
Socket.timeoutSet(socket, socketProperties.getSoTimeout() * 1000);
// 2: SSL handshake
step = 2;
if (sslContext != 0) {
SSLSocket.attach(sslContext, socket);
if (SSLSocket.handshake(socket) != 0) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("endpoint.err.handshake") + ": " + SSL.getLastError());
}
return false;
}
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
if (log.isDebugEnabled()) {
if (step == 2) {
log.debug(sm.getString("endpoint.err.handshake"), t);
} else {
log.debug(sm.getString("endpoint.err.unexpected"), t);
}
}
// Tell to close the socket
return false;
}
return true;
}
/**
* Allocate a new poller of the specified size.
*/
protected long allocatePoller(int size, long pool, int timeout) {
try {
return Poll.create(size, pool, 0, timeout * 1000);
} catch (Error e) {
if (Status.APR_STATUS_IS_EINVAL(e.getError())) {
log.info(sm.getString("endpoint.poll.limitedpollsize", "" + size));
return 0;
} else {
log.error(sm.getString("endpoint.poll.initfail"), e);
return -1;
}
}
}
/**
* Process given socket. This is called when the socket has been
* accepted.
*/
protected boolean processSocketWithOptions(long socket) {
try {
// During shutdown, executor may be null - avoid NPE
if (running) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("endpoint.debug.socket",
Long.valueOf(socket)));
}
AprSocketWrapper wrapper =
new AprSocketWrapper(Long.valueOf(socket));
wrapper.setKeepAliveLeft(getMaxKeepAliveRequests());
wrapper.setSecure(isSSLEnabled());
connections.put(Long.valueOf(socket), wrapper);
getExecutor().execute(new SocketWithOptionsProcessor(wrapper));
}
} catch (RejectedExecutionException x) {
log.warn("Socket processing request was rejected for:"+socket,x);
return false;
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
// This means we got an OOM or similar creating a thread, or that
// the pool and its queue are full
log.error(sm.getString("endpoint.process.fail"), t);
return false;
}
return true;
}
/**
* Process given socket. Called in non-comet mode, typically keep alive
* or upgraded protocol.
*/
public boolean processSocket(long socket, SocketStatus status) {
try {
Executor executor = getExecutor();
if (executor == null) {
log.warn(sm.getString("endpoint.warn.noExector",
Long.valueOf(socket), null));
} else {
SocketWrapper<Long> wrapper =
connections.get(Long.valueOf(socket));
// Make sure connection hasn't been closed
if (wrapper != null) {
executor.execute(new SocketProcessor(wrapper, status));
}
}
} catch (RejectedExecutionException x) {
log.warn("Socket processing request was rejected for:"+socket,x);
return false;
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
// This means we got an OOM or similar creating a thread, or that
// the pool and its queue are full
log.error(sm.getString("endpoint.process.fail"), t);
return false;
}
return true;
}
@Override
public void processSocketAsync(SocketWrapper<Long> socket,
SocketStatus status) {
try {
synchronized (socket) {
if (waitingRequests.remove(socket)) {
SocketProcessor proc = new SocketProcessor(socket, status);
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try {
//threads should not be created by the webapp classloader
if (Constants.IS_SECURITY_ENABLED) {
PrivilegedAction<Void> pa = new PrivilegedSetTccl(
getClass().getClassLoader());
AccessController.doPrivileged(pa);
} else {
Thread.currentThread().setContextClassLoader(
getClass().getClassLoader());
}
Executor executor = getExecutor();
if (executor == null) {
log.warn(sm.getString("endpoint.warn.noExector",
socket, status));
return;
} else {
executor.execute(proc);
}
} finally {
if (Constants.IS_SECURITY_ENABLED) {
PrivilegedAction<Void> pa = new PrivilegedSetTccl(loader);
AccessController.doPrivileged(pa);
} else {
Thread.currentThread().setContextClassLoader(loader);
}
}
}
}
} catch (RejectedExecutionException x) {
log.warn("Socket processing request was rejected for: "+socket, x);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
// This means we got an OOM or similar creating a thread, or that
// the pool and its queue are full
log.error(sm.getString("endpoint.process.fail"), t);
}
}
private void closeSocket(long socket) {
// If not running the socket will be destroyed by
// parent pool or acceptor socket.
// In any case disable double free which would cause JVM core.
connections.remove(Long.valueOf(socket));
// While the connector is running, destroySocket() will call
// countDownConnection(). Once the connector is stopped, the latch is
// removed so it does not matter that destroySocket() does not call
// countDownConnection() in that case
Poller poller = this.poller;
if (poller != null) {
if (!poller.close(socket)) {
destroySocket(socket);
}
}
}
/*
* This method should only be called if there is no chance that the socket
* is currently being used by the Poller. It is generally a bad idea to call
* this directly from a known error condition.
*/
private void destroySocket(long socket) {
connections.remove(Long.valueOf(socket));
if (log.isDebugEnabled()) {
String msg = sm.getString("endpoint.debug.destroySocket",
Long.valueOf(socket));
if (log.isTraceEnabled()) {
log.trace(msg, new Exception());
} else {
log.debug(msg);
}
}
// Be VERY careful if you call this method directly. If it is called
// twice for the same socket the JVM will core. Currently this is only
// called from Poller.closePollset() to ensure kept alive connections
// are closed when calling stop() followed by start().
if (socket != 0) {
Socket.destroy(socket);
countDownConnection();
}
}
@Override
protected Log getLog() {
return log;
}
// --------------------------------------------------- Acceptor Inner Class
/**
* The background thread that listens for incoming TCP/IP connections and
* hands them off to an appropriate processor.
*/
protected class Acceptor extends AbstractEndpoint.Acceptor {
private final Log log = LogFactory.getLog(AprEndpoint.Acceptor.class);
@Override
public void run() {
int errorDelay = 0;
// Loop until we receive a shutdown command
while (running) {
// Loop if endpoint is paused
while (paused && running) {
state = AcceptorState.PAUSED;
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// Ignore
}
}
if (!running) {
break;
}
state = AcceptorState.RUNNING;
try {
//if we have reached max connections, wait
countUpOrAwaitConnection();
long socket = 0;
try {
// Accept the next incoming connection from the server
// socket
socket = Socket.accept(serverSock);
if (log.isDebugEnabled()) {
long sa = Address.get(Socket.APR_REMOTE, socket);
Sockaddr addr = Address.getInfo(sa);
log.debug(sm.getString("endpoint.apr.remoteport",
Long.valueOf(socket),
Long.valueOf(addr.port)));
}
} catch (Exception e) {
//we didn't get a socket
countDownConnection();
// Introduce delay if necessary
errorDelay = handleExceptionWithDelay(errorDelay);
// re-throw
throw e;
}
// Successful accept, reset the error delay
errorDelay = 0;
if (running && !paused) {
// Hand this socket off to an appropriate processor
if (!processSocketWithOptions(socket)) {
// Close socket right away
closeSocket(socket);
}
} else {
// Close socket right away
// No code path could have added the socket to the
// Poller so use destroySocket()
destroySocket(socket);
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
if (running) {
String msg = sm.getString("endpoint.accept.fail");
if (t instanceof Error) {
Error e = (Error) t;
if (e.getError() == 233) {
// Not an error on HP-UX so log as a warning
// so it can be filtered out on that platform
// See bug 50273
log.warn(msg, t);
} else {
log.error(msg, t);
}
} else {
log.error(msg, t);
}
}
}
// The processor will recycle itself when it finishes
}
state = AcceptorState.ENDED;
}
}
/**
* Async timeout thread
*/
protected class AsyncTimeout implements Runnable {
private volatile boolean asyncTimeoutRunning = true;
/**
* The background thread that checks async requests and fires the
* timeout if there has been no activity.
*/
@Override
public void run() {
// Loop until we receive a shutdown command
while (asyncTimeoutRunning) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Ignore
}
long now = System.currentTimeMillis();
Iterator<SocketWrapper<Long>> sockets =
waitingRequests.iterator();
while (sockets.hasNext()) {
SocketWrapper<Long> socket = sockets.next();
if (socket.async) {
long access = socket.getLastAccess();
if (socket.getTimeout() > 0 &&
(now-access)>socket.getTimeout()) {
processSocketAsync(socket,SocketStatus.TIMEOUT);
}
}
}
// Loop if endpoint is paused
while (paused && asyncTimeoutRunning) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Ignore
}
}
}
}
protected void stop() {
asyncTimeoutRunning = false;
}
}
// -------------------------------------------------- SocketInfo Inner Class
public static class SocketInfo {
public long socket;
public int timeout;
public int flags;
public boolean read() {
return (flags & Poll.APR_POLLIN) == Poll.APR_POLLIN;
}
public boolean write() {
return (flags & Poll.APR_POLLOUT) == Poll.APR_POLLOUT;
}
public static int merge(int flag1, int flag2) {
return ((flag1 & Poll.APR_POLLIN) | (flag2 & Poll.APR_POLLIN))
| ((flag1 & Poll.APR_POLLOUT) | (flag2 & Poll.APR_POLLOUT));
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Socket: [");
sb.append(socket);
sb.append("], timeout: [");
sb.append(timeout);
sb.append("], flags: [");
sb.append(flags);
return sb.toString();
}
}
// ---------------------------------------------- SocketTimeouts Inner Class
public class SocketTimeouts {
protected int size;
protected long[] sockets;
protected long[] timeouts;
protected int pos = 0;
public SocketTimeouts(int size) {
this.size = 0;
sockets = new long[size];
timeouts = new long[size];
}
public void add(long socket, long timeout) {
sockets[size] = socket;
timeouts[size] = timeout;
size++;
}
/**
* Removes the specified socket from the poller.
*
* @return The configured timeout for the socket or zero if the socket
* was not in the list of socket timeouts
*/
public long remove(long socket) {
long result = 0;
for (int i = 0; i < size; i++) {
if (sockets[i] == socket) {
result = timeouts[i];
sockets[i] = sockets[size - 1];
timeouts[i] = timeouts[size - 1];
size--;
break;
}
}
return result;
}
public long check(long date) {
while (pos < size) {
if (date >= timeouts[pos]) {
long result = sockets[pos];
sockets[pos] = sockets[size - 1];
timeouts[pos] = timeouts[size - 1];
size--;
return result;
}
pos++;
}
pos = 0;
return 0;
}
}
// -------------------------------------------------- SocketList Inner Class
public class SocketList {
protected int size;
protected int pos;
protected long[] sockets;
protected int[] timeouts;
protected int[] flags;
protected SocketInfo info = new SocketInfo();
public SocketList(int size) {
this.size = 0;
pos = 0;
sockets = new long[size];
timeouts = new int[size];
flags = new int[size];
}
public int size() {
return this.size;
}
public SocketInfo get() {
if (pos == size) {
return null;
} else {
info.socket = sockets[pos];
info.timeout = timeouts[pos];
info.flags = flags[pos];
pos++;
return info;
}
}
public void clear() {
size = 0;
pos = 0;
}
public boolean add(long socket, int timeout, int flag) {
if (size == sockets.length) {
return false;
} else {
for (int i = 0; i < size; i++) {
if (sockets[i] == socket) {
flags[i] = SocketInfo.merge(flags[i], flag);
return true;
}
}
sockets[size] = socket;
timeouts[size] = timeout;
flags[size] = flag;
size++;
return true;
}
}
public boolean remove(long socket) {
for (int i = 0; i < size; i++) {
if (sockets[i] == socket) {
sockets[i] = sockets[size - 1];
timeouts[i] = timeouts[size - 1];
flags[size] = flags[size -1];
size--;
return true;
}
}
return false;
}
public void duplicate(SocketList copy) {
copy.size = size;
copy.pos = pos;
System.arraycopy(sockets, 0, copy.sockets, 0, size);
System.arraycopy(timeouts, 0, copy.timeouts, 0, size);
System.arraycopy(flags, 0, copy.flags, 0, size);
}
}
// ------------------------------------------------------ Poller Inner Class
public class Poller implements Runnable {
/**
* Pointers to the pollers.
*/
protected long[] pollers = null;
/**
* Actual poller size.
*/
protected int actualPollerSize = 0;
/**
* Amount of spots left in the poller.
*/
protected int[] pollerSpace = null;
/**
* Amount of low level pollers in use by this poller.
*/
protected int pollerCount;
/**
* Timeout value for the poll call.
*/
protected int pollerTime;
/**
* Variable poller timeout that adjusts depending on how many poll sets
* are in use so that the total poll time across all poll sets remains
* equal to pollTime.
*/
private int nextPollerTime;
/**
* Root pool.
*/
protected long pool = 0;
/**
* Socket descriptors.
*/
protected long[] desc;
/**
* List of sockets to be added to the poller.
*/
protected SocketList addList = null;
/**
* List of sockets to be closed.
*/
private SocketList closeList = null;
/**
* Structure used for storing timeouts.
*/
protected SocketTimeouts timeouts = null;
/**
* Last run of maintain. Maintain will run usually every 5s.
*/
protected long lastMaintain = System.currentTimeMillis();
/**
* The number of connections currently inside this Poller. The correct
* operation of the Poller depends on this figure being correct. If it
* is not, it is possible that the Poller will enter a wait loop where
* it waits for the next connection to be added to the Poller before it
* calls poll when it should still be polling existing connections.
* Although not necessary at the time of writing this comment, it has
* been implemented as an AtomicInteger to ensure that it remains
* thread-safe.
*/
private AtomicInteger connectionCount = new AtomicInteger(0);
public int getConnectionCount() { return connectionCount.get(); }
private volatile boolean pollerRunning = true;
/**
* Create the poller. With some versions of APR, the maximum poller size
* will be 62 (recompiling APR is necessary to remove this limitation).
*/
protected void init() {
pool = Pool.create(serverSockPool);
// Single poller by default
int defaultPollerSize = getMaxConnections();
if ((OS.IS_WIN32 || OS.IS_WIN64) && (defaultPollerSize > 1024)) {
// The maximum per poller to get reasonable performance is 1024
// Adjust poller size so that it won't reach the limit. This is
// a limitation of XP / Server 2003 that has been fixed in
// Vista / Server 2008 onwards.
actualPollerSize = 1024;
} else {
actualPollerSize = defaultPollerSize;
}
timeouts = new SocketTimeouts(defaultPollerSize);
// At the moment, setting the timeout is useless, but it could get
// used again as the normal poller could be faster using maintain.
// It might not be worth bothering though.
long pollset = allocatePoller(actualPollerSize, pool, -1);
if (pollset == 0 && actualPollerSize > 1024) {
actualPollerSize = 1024;
pollset = allocatePoller(actualPollerSize, pool, -1);
}
if (pollset == 0) {
actualPollerSize = 62;
pollset = allocatePoller(actualPollerSize, pool, -1);
}
pollerCount = defaultPollerSize / actualPollerSize;
pollerTime = pollTime / pollerCount;
nextPollerTime = pollerTime;
pollers = new long[pollerCount];
pollers[0] = pollset;
for (int i = 1; i < pollerCount; i++) {
pollers[i] = allocatePoller(actualPollerSize, pool, -1);
}
pollerSpace = new int[pollerCount];
for (int i = 0; i < pollerCount; i++) {
pollerSpace[i] = actualPollerSize;
}
desc = new long[actualPollerSize * 2];
connectionCount.set(0);
addList = new SocketList(defaultPollerSize);
closeList = new SocketList(defaultPollerSize);
}
/*
* This method is synchronized so that it is not possible for a socket
* to be added to the Poller's addList once this method has completed.
*/
protected synchronized void stop() {
pollerRunning = false;
}
/**
* Destroy the poller.
*/
protected void destroy() {
// Wait for pollerTime before doing anything, so that the poller
// threads exit, otherwise parallel destruction of sockets which are
// still in the poller can cause problems
try {
synchronized (this) {
this.notify();
this.wait(pollTime / 1000);
}
} catch (InterruptedException e) {
// Ignore
}
// Close all sockets in the add queue
SocketInfo info = addList.get();
while (info != null) {
boolean comet =
connections.get(Long.valueOf(info.socket)).isComet();
if (!comet || (comet && !processSocket(
info.socket, SocketStatus.STOP))) {
// Poller isn't running at this point so use destroySocket()
// directly
destroySocket(info.socket);
}
info = addList.get();
}
addList.clear();
// Close all sockets still in the poller
for (int i = 0; i < pollerCount; i++) {
int rv = Poll.pollset(pollers[i], desc);
if (rv > 0) {
for (int n = 0; n < rv; n++) {
boolean comet = connections.get(
Long.valueOf(desc[n*2+1])).isComet();
if (!comet || (comet && !processSocket(
desc[n*2+1], SocketStatus.STOP))) {
destroySocket(desc[n*2+1]);
}
}
}
}
Pool.destroy(pool);
connectionCount.set(0);
}
/**
* Add specified socket and associated pool to the poller. The socket
* will be added to a temporary array, and polled first after a maximum
* amount of time equal to pollTime (in most cases, latency will be much
* lower, however). Note: If both read and write are false, the socket
* will only be checked for timeout; if the socket was already present
* in the poller, a callback event will be generated and the socket will
* be removed from the poller.
*
* @param socket to add to the poller
* @param timeout to use for this connection
* @param read to do read polling
* @param write to do write polling
*/
public void add(long socket, int timeout, boolean read, boolean write) {
add(socket, timeout,
(read ? Poll.APR_POLLIN : 0) |
(write ? Poll.APR_POLLOUT : 0));
}
private void add(long socket, int timeout, int flags) {
if (log.isDebugEnabled()) {
String msg = sm.getString("endpoint.debug.pollerAdd",
Long.valueOf(socket), Integer.valueOf(timeout),
Integer.valueOf(flags));
if (log.isTraceEnabled()) {
log.trace(msg, new Exception());
} else {
log.debug(msg);
}
}
if (timeout <= 0) {
// Always put a timeout in
timeout = Integer.MAX_VALUE;
}
boolean ok = false;
synchronized (this) {
// Add socket to the list. Newly added sockets will wait
// at most for pollTime before being polled. Don't add the
// socket once the poller has stopped but destroy it straight
// away
if (pollerRunning && addList.add(socket, timeout, flags)) {
ok = true;
this.notify();
}
}
if (!ok) {
// Can't do anything: close the socket right away
boolean comet = connections.get(
Long.valueOf(socket)).isComet();
if (!comet || (comet && !processSocket(
socket, SocketStatus.ERROR))) {
closeSocket(socket);
}
}
}
/**
* Add specified socket to one of the pollers. Must only be called from
* {@link Poller#run()}.
*/
protected boolean addToPoller(long socket, int events) {
int rv = -1;
for (int i = 0; i < pollers.length; i++) {
if (pollerSpace[i] > 0) {
rv = Poll.add(pollers[i], socket, events);
if (rv == Status.APR_SUCCESS) {
pollerSpace[i]--;
connectionCount.incrementAndGet();
return true;
}
}
}
return false;
}
protected boolean close(long socket) {
if (!pollerRunning) {
return false;
}
synchronized (this) {
if (!pollerRunning) {
return false;
}
closeList.add(socket, 0, 0);
this.notify();
return true;
}
}
/**
* Remove specified socket from the pollers. Must only be called from
* {@link Poller#run()}.
*/
private boolean removeFromPoller(long socket) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("endpoint.debug.pollerRemove",
Long.valueOf(socket)));
}
int rv = -1;
for (int i = 0; i < pollers.length; i++) {
if (pollerSpace[i] < actualPollerSize) {
rv = Poll.remove(pollers[i], socket);
if (rv != Status.APR_NOTFOUND) {
pollerSpace[i]++;
connectionCount.decrementAndGet();
if (log.isDebugEnabled()) {
log.debug(sm.getString("endpoint.debug.pollerRemoved",
Long.valueOf(socket)));
}
break;
}
}
}
timeouts.remove(socket);
return (rv == Status.APR_SUCCESS);
}
/**
* Timeout checks.
*/
protected void maintain() {
long date = System.currentTimeMillis();
// Maintain runs at most once every 5s, although it will likely get
// called more
if ((date - lastMaintain) < 5000L) {
return;
} else {
lastMaintain = date;
}
long socket = timeouts.check(date);
while (socket != 0) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("endpoint.debug.socketTimeout",
Long.valueOf(socket)));
}
removeFromPoller(socket);
boolean comet = connections.get(
Long.valueOf(socket)).isComet();
if (!comet || (comet && !processSocket(
socket, SocketStatus.TIMEOUT))) {
destroySocket(socket);
}
socket = timeouts.check(date);
}
}
/**
* Displays the list of sockets in the pollers.
*/
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("Poller");
long[] res = new long[actualPollerSize * 2];
for (int i = 0; i < pollers.length; i++) {
int count = Poll.pollset(pollers[i], res);
buf.append(" [ ");
for (int j = 0; j < count; j++) {
buf.append(desc[2*j+1]).append(" ");
}
buf.append("]");
}
return buf.toString();
}
/**
* The background thread that listens for incoming TCP/IP connections
* and hands them off to an appropriate processor.
*/
@Override
public void run() {
int maintain = 0;
SocketList localAddList = new SocketList(getMaxConnections());
SocketList localCloseList = new SocketList(getMaxConnections());
// Loop until we receive a shutdown command
while (pollerRunning) {
// Loop if endpoint is paused
while (pollerRunning && paused) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Ignore
}
}
// Check timeouts if the poller is empty
while (pollerRunning && connectionCount.get() < 1 &&
addList.size() < 1 && closeList.size() < 1) {
// Reset maintain time.
try {
if (getSoTimeout() > 0 && pollerRunning) {
maintain();
}
synchronized (this) {
this.wait(10000);
}
} catch (InterruptedException e) {
// Ignore
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
getLog().warn(sm.getString("endpoint.timeout.err"));
}
}
// Don't add or poll if the poller has been stopped
if (!pollerRunning) {
break;
}
try {
// Duplicate the add and remove lists so that the syncs are
// minimised
if (closeList.size() > 0) {
synchronized (this) {
// Duplicate to another list, so that the syncing is
// minimal
closeList.duplicate(localCloseList);
closeList.clear();
}
} else {
localCloseList.clear();
}
if (addList.size() > 0) {
synchronized (this) {
// Duplicate to another list, so that the syncing is
// minimal
addList.duplicate(localAddList);
addList.clear();
}
} else {
localAddList.clear();
}
// Remove sockets
if (localCloseList.size() > 0) {
SocketInfo info = localCloseList.get();
while (info != null) {
localAddList.remove(info.socket);
removeFromPoller(info.socket);
destroySocket(info.socket);
info = localCloseList.get();
}
}
// Add sockets which are waiting to the poller
if (localAddList.size() > 0) {
SocketInfo info = localAddList.get();
while (info != null) {
if (log.isDebugEnabled()) {
log.debug(sm.getString(
"endpoint.debug.pollerAddDo",
Long.valueOf(info.socket)));
}
timeouts.remove(info.socket);
AprSocketWrapper wrapper = connections.get(
Long.valueOf(info.socket));
if (wrapper == null) {
continue;
}
if (info.read() || info.write()) {
boolean comet = wrapper.isComet();
if (comet || wrapper.pollerFlags != 0) {
removeFromPoller(info.socket);
}
wrapper.pollerFlags = wrapper.pollerFlags |
(info.read() ? Poll.APR_POLLIN : 0) |
(info.write() ? Poll.APR_POLLOUT : 0);
if (!addToPoller(info.socket, wrapper.pollerFlags)) {
// Can't do anything: close the socket right
// away
if (!comet || (comet && !processSocket(
info.socket, SocketStatus.ERROR))) {
closeSocket(info.socket);
}
} else {
timeouts.add(info.socket,
System.currentTimeMillis() +
info.timeout);
}
} else {
// Should never happen.
closeSocket(info.socket);
getLog().warn(sm.getString(
"endpoint.apr.pollAddInvalid", info));
}
info = localAddList.get();
}
}
// Poll for the specified interval
for (int i = 0; i < pollers.length; i++) {
// Flags to ask to reallocate the pool
boolean reset = false;
//ArrayList<Long> skip = null;
int rv = 0;
// Iterate on each pollers, but no need to poll empty pollers
if (pollerSpace[i] < actualPollerSize) {
rv = Poll.poll(pollers[i], nextPollerTime, desc, true);
// Reset the nextPollerTime
nextPollerTime = pollerTime;
} else {
// Skipping an empty poll set means skipping a wait
// time of pollerTime microseconds. If most of the
// poll sets are skipped then this loop will be
// tighter than expected which could lead to higher
// than expected CPU usage. Extending the
// nextPollerTime ensures that this loop always
// takes about the same time to execute.
nextPollerTime += pollerTime;
}
if (rv > 0) {
pollerSpace[i] += rv;
connectionCount.addAndGet(-rv);
for (int n = 0; n < rv; n++) {
long timeout = timeouts.remove(desc[n*2+1]);
AprSocketWrapper wrapper = connections.get(
Long.valueOf(desc[n*2+1]));
if (getLog().isDebugEnabled()) {
log.debug(sm.getString(
"endpoint.debug.pollerProcess",
Long.valueOf(desc[n*2+1]),
Long.valueOf(desc[n*2])));
}
wrapper.pollerFlags = wrapper.pollerFlags & ~((int) desc[n*2]);
// Check for failed sockets and hand this socket off to a worker
if (wrapper.isComet()) {
// Event processes either a read or a write depending on what the poller returns
if (((desc[n*2] & Poll.APR_POLLHUP) == Poll.APR_POLLHUP)
|| ((desc[n*2] & Poll.APR_POLLERR) == Poll.APR_POLLERR)
|| ((desc[n*2] & Poll.APR_POLLNVAL) == Poll.APR_POLLNVAL)) {
if (!processSocket(desc[n*2+1], SocketStatus.ERROR)) {
// Close socket and clear pool
closeSocket(desc[n*2+1]);
}
} else if ((desc[n*2] & Poll.APR_POLLIN) == Poll.APR_POLLIN) {
if (wrapper.pollerFlags != 0) {
add(desc[n*2+1], 1, wrapper.pollerFlags);
}
if (!processSocket(desc[n*2+1], SocketStatus.OPEN_READ)) {
// Close socket and clear pool
closeSocket(desc[n*2+1]);
}
} else if ((desc[n*2] & Poll.APR_POLLOUT) == Poll.APR_POLLOUT) {
if (wrapper.pollerFlags != 0) {
add(desc[n*2+1], 1, wrapper.pollerFlags);
}
if (!processSocket(desc[n*2+1], SocketStatus.OPEN_WRITE)) {
// Close socket and clear pool
closeSocket(desc[n*2+1]);
}
} else {
// Unknown event
getLog().warn(sm.getString(
"endpoint.apr.pollUnknownEvent",
Long.valueOf(desc[n*2])));
if (!processSocket(desc[n*2+1], SocketStatus.ERROR)) {
// Close socket and clear pool
closeSocket(desc[n*2+1]);
}
}
} else if (((desc[n*2] & Poll.APR_POLLHUP) == Poll.APR_POLLHUP)
|| ((desc[n*2] & Poll.APR_POLLERR) == Poll.APR_POLLERR)
|| ((desc[n*2] & Poll.APR_POLLNVAL) == Poll.APR_POLLNVAL)) {
if (wrapper.isUpgraded()) {
// Using non-blocking IO. Need to trigger error handling.
// Poller may return error codes plus the flags it was
// waiting for or it may just return an error code. By
// signalling read/write is possible, a read/write will be
// attempted, fail and that will trigger an exception the
// application will see.
// Check the return flags first, followed by what the socket
// was registered for
if ((desc[n*2] & Poll.APR_POLLIN) == Poll.APR_POLLIN) {
// Error probably occurred during a non-blocking read
if (!processSocket(desc[n*2+1], SocketStatus.OPEN_READ)) {
// Close socket and clear pool
closeSocket(desc[n*2+1]);
}
} else if ((desc[n*2] & Poll.APR_POLLOUT) == Poll.APR_POLLOUT) {
// Error probably occurred during a non-blocking write
if (!processSocket(desc[n*2+1], SocketStatus.OPEN_WRITE)) {
// Close socket and clear pool
closeSocket(desc[n*2+1]);
}
} else if ((wrapper.pollerFlags & Poll.APR_POLLIN) == Poll.APR_POLLIN) {
// Can't tell what was happening when the error occurred but the
// socket is registered for non-blocking read so use that
if (!processSocket(desc[n*2+1], SocketStatus.OPEN_READ)) {
// Close socket and clear pool
closeSocket(desc[n*2+1]);
}
} else if ((wrapper.pollerFlags & Poll.APR_POLLOUT) == Poll.APR_POLLOUT) {
// Can't tell what was happening when the error occurred but the
// socket is registered for non-blocking write so use that
if (!processSocket(desc[n*2+1], SocketStatus.OPEN_WRITE)) {
// Close socket and clear pool
closeSocket(desc[n*2+1]);
}
} else {
// Close socket and clear pool
closeSocket(desc[n*2+1]);
}
} else {
// Close socket and clear pool
closeSocket(desc[n*2+1]);
}
} else if (((desc[n*2] & Poll.APR_POLLIN) == Poll.APR_POLLIN)
|| ((desc[n*2] & Poll.APR_POLLOUT) == Poll.APR_POLLOUT)) {
boolean error = false;
if (((desc[n*2] & Poll.APR_POLLIN) == Poll.APR_POLLIN) &&
!processSocket(desc[n*2+1], SocketStatus.OPEN_READ)) {
error = true;
// Close socket and clear pool
closeSocket(desc[n*2+1]);
}
if (!error &&
((desc[n*2] & Poll.APR_POLLOUT) == Poll.APR_POLLOUT) &&
!processSocket(desc[n*2+1], SocketStatus.OPEN_WRITE)) {
// Close socket and clear pool
error = true;
closeSocket(desc[n*2+1]);
}
if (!error && wrapper.pollerFlags != 0) {
// If socket was registered for multiple events but
// only some of the occurred, re-register for the
// remaining events.
// timeout is the value of System.currentTimeMillis() that
// was set as the point that the socket will timeout. When
// adding to the poller, the timeout from now in
// milliseconds is required.
// So first, subtract the current timestamp
if (timeout > 0) {
timeout = timeout - System.currentTimeMillis();
}
// If the socket should have already expired by now,
// re-add it with a very short timeout
if (timeout <= 0) {
timeout = 1;
}
// Should be impossible but just in case since timeout will
// be cast to an int.
if (timeout > Integer.MAX_VALUE) {
timeout = Integer.MAX_VALUE;
}
add(desc[n*2+1], (int) timeout, wrapper.pollerFlags);
}
} else {
// Unknown event
getLog().warn(sm.getString(
"endpoint.apr.pollUnknownEvent",
Long.valueOf(desc[n*2])));
// Close socket and clear pool
closeSocket(desc[n*2+1]);
}
}
} else if (rv < 0) {
int errn = -rv;
// Any non timeup or interrupted error is critical
if ((errn != Status.TIMEUP) && (errn != Status.EINTR)) {
if (errn > Status.APR_OS_START_USERERR) {
errn -= Status.APR_OS_START_USERERR;
}
getLog().error(sm.getString(
"endpoint.apr.pollError",
Integer.valueOf(errn),
Error.strerror(errn)));
// Destroy and reallocate the poller
reset = true;
}
}
if (reset) {
// Reallocate the current poller
int count = Poll.pollset(pollers[i], desc);
long newPoller = allocatePoller(actualPollerSize, pool, -1);
// Don't restore connections for now, since I have not tested it
pollerSpace[i] = actualPollerSize;
connectionCount.addAndGet(-count);
Poll.destroy(pollers[i]);
pollers[i] = newPoller;
}
}
// Process socket timeouts
if (getSoTimeout() > 0 && maintain++ > 1000 && pollerRunning) {
// This works and uses only one timeout mechanism for everything, but the
// non event poller might be a bit faster by using the old maintain.
maintain = 0;
maintain();
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
if (maintain == 0) {
getLog().warn(sm.getString("endpoint.timeout.error"), t);
} else {
getLog().warn(sm.getString("endpoint.poll.error"), t);
}
}
}
synchronized (this) {
this.notifyAll();
}
}
}
// ----------------------------------------------- SendfileData Inner Class
/**
* SendfileData class.
*/
public static class SendfileData {
// File
public String fileName;
public long fd;
public long fdpool;
// Range information
public long start;
public long end;
// Socket and socket pool
public long socket;
// Position
public long pos;
// KeepAlive flag
public SendfileKeepAliveState keepAliveState = SendfileKeepAliveState.NONE;
}
// --------------------------------------------------- Sendfile Inner Class
public class Sendfile implements Runnable {
protected long sendfilePollset = 0;
protected long pool = 0;
protected long[] desc;
protected HashMap<Long, SendfileData> sendfileData;
protected int sendfileCount;
public int getSendfileCount() { return sendfileCount; }
protected ArrayList<SendfileData> addS;
private volatile boolean sendfileRunning = true;
/**
* Create the sendfile poller. With some versions of APR, the maximum
* poller size will be 62 (recompiling APR is necessary to remove this
* limitation).
*/
protected void init() {
pool = Pool.create(serverSockPool);
int size = sendfileSize;
if (size <= 0) {
size = (OS.IS_WIN32 || OS.IS_WIN64) ? (1 * 1024) : (16 * 1024);
}
sendfilePollset = allocatePoller(size, pool, getSoTimeout());
if (sendfilePollset == 0 && size > 1024) {
size = 1024;
sendfilePollset = allocatePoller(size, pool, getSoTimeout());
}
if (sendfilePollset == 0) {
size = 62;
sendfilePollset = allocatePoller(size, pool, getSoTimeout());
}
desc = new long[size * 2];
sendfileData = new HashMap<Long, SendfileData>(size);
addS = new ArrayList<SendfileData>();
}
/**
* Destroy the poller.
*/
protected void destroy() {
sendfileRunning = false;
// Wait for polltime before doing anything, so that the poller threads
// exit, otherwise parallel destruction of sockets which are still
// in the poller can cause problems
try {
synchronized (this) {
this.notify();
this.wait(pollTime / 1000);
}
} catch (InterruptedException e) {
// Ignore
}
// Close any socket remaining in the add queue
for (int i = (addS.size() - 1); i >= 0; i--) {
SendfileData data = addS.get(i);
closeSocket(data.socket);
}
// Close all sockets still in the poller
int rv = Poll.pollset(sendfilePollset, desc);
if (rv > 0) {
for (int n = 0; n < rv; n++) {
closeSocket(desc[n*2+1]);
}
}
Pool.destroy(pool);
sendfileData.clear();
}
/**
* Add the sendfile data to the sendfile poller. Note that in most cases,
* the initial non blocking calls to sendfile will return right away, and
* will be handled asynchronously inside the kernel. As a result,
* the poller will never be used.
*
* @param data containing the reference to the data which should be snet
* @return true if all the data has been sent right away, and false
* otherwise
*/
public SendfileState add(SendfileData data) {
// Initialize fd from data given
try {
data.fdpool = Socket.pool(data.socket);
data.fd = File.open
(data.fileName, File.APR_FOPEN_READ
| File.APR_FOPEN_SENDFILE_ENABLED | File.APR_FOPEN_BINARY,
0, data.fdpool);
data.pos = data.start;
// Set the socket to nonblocking mode
Socket.timeoutSet(data.socket, 0);
while (true) {
long nw = Socket.sendfilen(data.socket, data.fd,
data.pos, data.end - data.pos, 0);
if (nw < 0) {
if (!(-nw == Status.EAGAIN)) {
Pool.destroy(data.fdpool);
data.socket = 0;
return SendfileState.ERROR;
} else {
// Break the loop and add the socket to poller.
break;
}
} else {
data.pos = data.pos + nw;
if (data.pos >= data.end) {
// Entire file has been sent
Pool.destroy(data.fdpool);
// Set back socket to blocking mode
Socket.timeoutSet(
data.socket, getSoTimeout() * 1000);
return SendfileState.DONE;
}
}
}
} catch (Exception e) {
log.warn(sm.getString("endpoint.sendfile.error"), e);
return SendfileState.ERROR;
}
// Add socket to the list. Newly added sockets will wait
// at most for pollTime before being polled
synchronized (this) {
addS.add(data);
this.notify();
}
return SendfileState.PENDING;
}
/**
* Remove socket from the poller.
*
* @param data the sendfile data which should be removed
*/
protected void remove(SendfileData data) {
int rv = Poll.remove(sendfilePollset, data.socket);
if (rv == Status.APR_SUCCESS) {
sendfileCount--;
}
sendfileData.remove(new Long(data.socket));
}
/**
* The background thread that listens for incoming TCP/IP connections
* and hands them off to an appropriate processor.
*/
@Override
public void run() {
long maintainTime = 0;
// Loop until we receive a shutdown command
while (sendfileRunning) {
// Loop if endpoint is paused
while (sendfileRunning && paused) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Ignore
}
}
// Loop if poller is empty
while (sendfileRunning && sendfileCount < 1 && addS.size() < 1) {
// Reset maintain time.
maintainTime = 0;
try {
synchronized (this) {
this.wait();
}
} catch (InterruptedException e) {
// Ignore
}
}
// Don't add or poll if the poller has been stopped
if (!sendfileRunning) {
break;
}
try {
// Add socket to the poller
if (addS.size() > 0) {
synchronized (this) {
for (int i = (addS.size() - 1); i >= 0; i--) {
SendfileData data = addS.get(i);
int rv = Poll.add(sendfilePollset, data.socket, Poll.APR_POLLOUT);
if (rv == Status.APR_SUCCESS) {
sendfileData.put(new Long(data.socket), data);
sendfileCount++;
} else {
getLog().warn(sm.getString(
"endpoint.sendfile.addfail",
Integer.valueOf(rv),
Error.strerror(rv)));
// Can't do anything: close the socket right away
closeSocket(data.socket);
}
}
addS.clear();
}
}
maintainTime += pollTime;
// Pool for the specified interval
int rv = Poll.poll(sendfilePollset, pollTime, desc, false);
if (rv > 0) {
for (int n = 0; n < rv; n++) {
// Get the sendfile state
SendfileData state =
sendfileData.get(new Long(desc[n*2+1]));
// Problem events
if (((desc[n*2] & Poll.APR_POLLHUP) == Poll.APR_POLLHUP)
|| ((desc[n*2] & Poll.APR_POLLERR) == Poll.APR_POLLERR)) {
// Close socket and clear pool
remove(state);
// Destroy file descriptor pool, which should close the file
// Close the socket, as the response would be incomplete
closeSocket(state.socket);
continue;
}
// Write some data using sendfile
long nw = Socket.sendfilen(state.socket, state.fd,
state.pos,
state.end - state.pos, 0);
if (nw < 0) {
// Close socket and clear pool
remove(state);
// Close the socket, as the response would be incomplete
// This will close the file too.
closeSocket(state.socket);
continue;
}
state.pos = state.pos + nw;
if (state.pos >= state.end) {
remove(state);
switch (state.keepAliveState) {
case NONE: {
// Close the socket since this is
// the end of the not keep-alive request.
closeSocket(state.socket);
break;
}
case PIPELINED: {
// Destroy file descriptor pool, which should close the file
Pool.destroy(state.fdpool);
Socket.timeoutSet(state.socket, getSoTimeout() * 1000);
// Process the pipelined request data
if (!processSocket(state.socket, SocketStatus.OPEN_READ)) {
closeSocket(state.socket);
}
break;
}
case OPEN: {
// Destroy file descriptor pool, which should close the file
Pool.destroy(state.fdpool);
Socket.timeoutSet(state.socket, getSoTimeout() * 1000);
// Put the socket back in the poller for
// processing of further requests
getPoller().add(state.socket, getKeepAliveTimeout(),
true, false);
break;
}
}
}
}
} else if (rv < 0) {
int errn = -rv;
/* Any non timeup or interrupted error is critical */
if ((errn != Status.TIMEUP) && (errn != Status.EINTR)) {
if (errn > Status.APR_OS_START_USERERR) {
errn -= Status.APR_OS_START_USERERR;
}
getLog().error(sm.getString(
"Unexpected poller error",
Integer.valueOf(errn),
Error.strerror(errn)));
// Handle poll critical failure
synchronized (this) {
destroy();
init();
}
continue;
}
}
// Call maintain for the sendfile poller
if (getSoTimeout() > 0 &&
maintainTime > 1000000L && sendfileRunning) {
rv = Poll.maintain(sendfilePollset, desc, false);
maintainTime = 0;
if (rv > 0) {
for (int n = 0; n < rv; n++) {
// Get the sendfile state
SendfileData state = sendfileData.get(new Long(desc[n]));
// Close socket and clear pool
remove(state);
// Destroy file descriptor pool, which should close the file
// Close the socket, as the response would be incomplete
closeSocket(state.socket);
}
}
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
getLog().error(sm.getString("endpoint.poll.error"), t);
}
}
synchronized (this) {
this.notifyAll();
}
}
}
// ------------------------------------------------ Handler Inner Interface
/**
* Bare bones interface used for socket processing. Per thread data is to be
* stored in the ThreadWithAttributes extra folders, or alternately in
* thread local fields.
*/
public interface Handler extends AbstractEndpoint.Handler {
public SocketState process(SocketWrapper<Long> socket,
SocketStatus status);
}
// --------------------------------- SocketWithOptionsProcessor Inner Class
/**
* This class is the equivalent of the Worker, but will simply use in an
* external Executor thread pool. This will also set the socket options
* and do the handshake.
*
* This is called after an accept().
*/
protected class SocketWithOptionsProcessor implements Runnable {
protected SocketWrapper<Long> socket = null;
public SocketWithOptionsProcessor(SocketWrapper<Long> socket) {
this.socket = socket;
}
@Override
public void run() {
synchronized (socket) {
if (!deferAccept) {
if (setSocketOptions(socket.getSocket().longValue())) {
getPoller().add(socket.getSocket().longValue(),
getSoTimeout(), true, false);
} else {
// Close socket and pool
closeSocket(socket.getSocket().longValue());
socket = null;
}
} else {
// Process the request from this socket
if (!setSocketOptions(socket.getSocket().longValue())) {
// Close socket and pool
closeSocket(socket.getSocket().longValue());
socket = null;
return;
}
// Process the request from this socket
Handler.SocketState state = handler.process(socket,
SocketStatus.OPEN_READ);
if (state == Handler.SocketState.CLOSED) {
// Close socket and pool
closeSocket(socket.getSocket().longValue());
socket = null;
} else if (state == Handler.SocketState.LONG) {
socket.access();
if (socket.async) {
waitingRequests.add(socket);
}
}
}
}
}
}
// -------------------------------------------- SocketProcessor Inner Class
/**
* This class is the equivalent of the Worker, but will simply use in an
* external Executor thread pool.
*/
protected class SocketProcessor implements Runnable {
private final SocketWrapper<Long> socket;
private final SocketStatus status;
public SocketProcessor(SocketWrapper<Long> socket,
SocketStatus status) {
this.socket = socket;
if (status == null) {
// Should never happen
throw new NullPointerException();
}
this.status = status;
}
@Override
public void run() {
// Upgraded connections need to allow multiple threads to access the
// connection at the same time to enable blocking IO to be used when
// Servlet 3.1 NIO has been configured
if (socket.isUpgraded() && SocketStatus.OPEN_WRITE == status) {
synchronized (socket.getWriteThreadLock()) {
doRun();
}
} else {
synchronized (socket) {
doRun();
}
}
}
private void doRun() {
// Process the request from this socket
if (socket.getSocket() == null) {
// Closed in another thread
return;
}
SocketState state = handler.process(socket, status);
if (state == Handler.SocketState.CLOSED) {
// Close socket and pool
closeSocket(socket.getSocket().longValue());
socket.socket = null;
} else if (state == Handler.SocketState.LONG) {
socket.access();
if (socket.async) {
waitingRequests.add(socket);
}
} else if (state == Handler.SocketState.ASYNC_END) {
socket.access();
SocketProcessor proc = new SocketProcessor(socket,
SocketStatus.OPEN_READ);
getExecutor().execute(proc);
}
}
}
private static class AprSocketWrapper extends SocketWrapper<Long> {
// This field should only be used by Poller#run()
private int pollerFlags = 0;
public AprSocketWrapper(Long socket) {
super(socket);
}
}
}
|