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 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033
|
/*
* util/netevent.c - event notification
*
* Copyright (c) 2007, NLnet Labs. All rights reserved.
*
* This software is open source.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the NLNET LABS nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* \file
*
* This file contains event notification functions.
*/
#include "config.h"
#include "util/netevent.h"
#include "util/ub_event.h"
#include "util/log.h"
#include "util/net_help.h"
#include "util/tcp_conn_limit.h"
#include "util/fptr_wlist.h"
#include "util/proxy_protocol.h"
#include "util/timeval_func.h"
#include "sldns/pkthdr.h"
#include "sldns/sbuffer.h"
#include "sldns/str2wire.h"
#include "dnstap/dnstap.h"
#include "dnscrypt/dnscrypt.h"
#include "services/listen_dnsport.h"
#include "util/random.h"
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_POLL_H
#include <poll.h>
#endif
#ifdef HAVE_OPENSSL_SSL_H
#include <openssl/ssl.h>
#endif
#ifdef HAVE_OPENSSL_ERR_H
#include <openssl/err.h>
#endif
#ifdef HAVE_NGTCP2
#include <ngtcp2/ngtcp2.h>
#include <ngtcp2/ngtcp2_crypto.h>
#endif
#ifdef HAVE_LINUX_NET_TSTAMP_H
#include <linux/net_tstamp.h>
#endif
/* -------- Start of local definitions -------- */
/** if CMSG_ALIGN is not defined on this platform, a workaround */
#ifndef CMSG_ALIGN
# ifdef __CMSG_ALIGN
# define CMSG_ALIGN(n) __CMSG_ALIGN(n)
# elif defined(CMSG_DATA_ALIGN)
# define CMSG_ALIGN _CMSG_DATA_ALIGN
# else
# define CMSG_ALIGN(len) (((len)+sizeof(long)-1) & ~(sizeof(long)-1))
# endif
#endif
/** if CMSG_LEN is not defined on this platform, a workaround */
#ifndef CMSG_LEN
# define CMSG_LEN(len) (CMSG_ALIGN(sizeof(struct cmsghdr))+(len))
#endif
/** if CMSG_SPACE is not defined on this platform, a workaround */
#ifndef CMSG_SPACE
# ifdef _CMSG_HDR_ALIGN
# define CMSG_SPACE(l) (CMSG_ALIGN(l)+_CMSG_HDR_ALIGN(sizeof(struct cmsghdr)))
# else
# define CMSG_SPACE(l) (CMSG_ALIGN(l)+CMSG_ALIGN(sizeof(struct cmsghdr)))
# endif
#endif
/** The TCP writing query timeout in milliseconds */
#define TCP_QUERY_TIMEOUT 120000
/** The minimum actual TCP timeout to use, regardless of what we advertise,
* in msec */
#define TCP_QUERY_TIMEOUT_MINIMUM 200
#ifndef NONBLOCKING_IS_BROKEN
/** number of UDP reads to perform per read indication from select */
#define NUM_UDP_PER_SELECT 100
#else
#define NUM_UDP_PER_SELECT 1
#endif
/** timeout in millisec to wait for write to unblock, packets dropped after.*/
#define SEND_BLOCKED_WAIT_TIMEOUT 200
/** max number of times to wait for write to unblock, packets dropped after.*/
#define SEND_BLOCKED_MAX_RETRY 5
/** Let's make timestamping code cleaner and redefine SO_TIMESTAMP* */
#ifndef SO_TIMESTAMP
#define SO_TIMESTAMP 29
#endif
#ifndef SO_TIMESTAMPNS
#define SO_TIMESTAMPNS 35
#endif
#ifndef SO_TIMESTAMPING
#define SO_TIMESTAMPING 37
#endif
/**
* The internal event structure for keeping ub_event info for the event.
* Possibly other structures (list, tree) this is part of.
*/
struct internal_event {
/** the comm base */
struct comm_base* base;
/** ub_event event type */
struct ub_event* ev;
};
/**
* Internal base structure, so that every thread has its own events.
*/
struct internal_base {
/** ub_event event_base type. */
struct ub_event_base* base;
/** seconds time pointer points here */
time_t secs;
/** timeval with current time */
struct timeval now;
/** the event used for slow_accept timeouts */
struct ub_event* slow_accept;
/** true if slow_accept is enabled */
int slow_accept_enabled;
/** last log time for slow logging of file descriptor errors */
time_t last_slow_log;
/** last log time for slow logging of write wait failures */
time_t last_writewait_log;
};
/**
* Internal timer structure, to store timer event in.
*/
struct internal_timer {
/** the super struct from which derived */
struct comm_timer super;
/** the comm base */
struct comm_base* base;
/** ub_event event type */
struct ub_event* ev;
/** is timer enabled */
uint8_t enabled;
};
/**
* Internal signal structure, to store signal event in.
*/
struct internal_signal {
/** ub_event event type */
struct ub_event* ev;
/** next in signal list */
struct internal_signal* next;
};
/** create a tcp handler with a parent */
static struct comm_point* comm_point_create_tcp_handler(
struct comm_base *base, struct comm_point* parent, size_t bufsize,
struct sldns_buffer* spoolbuf, comm_point_callback_type* callback,
void* callback_arg, struct unbound_socket* socket);
/* -------- End of local definitions -------- */
struct comm_base*
comm_base_create(int sigs)
{
struct comm_base* b = (struct comm_base*)calloc(1,
sizeof(struct comm_base));
const char *evnm="event", *evsys="", *evmethod="";
if(!b)
return NULL;
b->eb = (struct internal_base*)calloc(1, sizeof(struct internal_base));
if(!b->eb) {
free(b);
return NULL;
}
b->eb->base = ub_default_event_base(sigs, &b->eb->secs, &b->eb->now);
if(!b->eb->base) {
free(b->eb);
free(b);
return NULL;
}
ub_comm_base_now(b);
ub_get_event_sys(b->eb->base, &evnm, &evsys, &evmethod);
verbose(VERB_ALGO, "%s %s uses %s method.", evnm, evsys, evmethod);
return b;
}
struct comm_base*
comm_base_create_event(struct ub_event_base* base)
{
struct comm_base* b = (struct comm_base*)calloc(1,
sizeof(struct comm_base));
if(!b)
return NULL;
b->eb = (struct internal_base*)calloc(1, sizeof(struct internal_base));
if(!b->eb) {
free(b);
return NULL;
}
b->eb->base = base;
ub_comm_base_now(b);
return b;
}
void
comm_base_delete(struct comm_base* b)
{
if(!b)
return;
if(b->eb->slow_accept_enabled) {
if(ub_event_del(b->eb->slow_accept) != 0) {
log_err("could not event_del slow_accept");
}
ub_event_free(b->eb->slow_accept);
}
ub_event_base_free(b->eb->base);
b->eb->base = NULL;
free(b->eb);
free(b);
}
void
comm_base_delete_no_base(struct comm_base* b)
{
if(!b)
return;
if(b->eb->slow_accept_enabled) {
if(ub_event_del(b->eb->slow_accept) != 0) {
log_err("could not event_del slow_accept");
}
ub_event_free(b->eb->slow_accept);
}
b->eb->base = NULL;
free(b->eb);
free(b);
}
void
comm_base_timept(struct comm_base* b, time_t** tt, struct timeval** tv)
{
*tt = &b->eb->secs;
*tv = &b->eb->now;
}
void
comm_base_dispatch(struct comm_base* b)
{
int retval;
retval = ub_event_base_dispatch(b->eb->base);
if(retval < 0) {
fatal_exit("event_dispatch returned error %d, "
"errno is %s", retval, strerror(errno));
}
}
void comm_base_exit(struct comm_base* b)
{
if(ub_event_base_loopexit(b->eb->base) != 0) {
log_err("Could not loopexit");
}
}
void comm_base_set_slow_accept_handlers(struct comm_base* b,
void (*stop_acc)(void*), void (*start_acc)(void*), void* arg)
{
b->stop_accept = stop_acc;
b->start_accept = start_acc;
b->cb_arg = arg;
}
struct ub_event_base* comm_base_internal(struct comm_base* b)
{
return b->eb->base;
}
/** see if errno for udp has to be logged or not uses globals */
static int
udp_send_errno_needs_log(struct sockaddr* addr, socklen_t addrlen)
{
/* do not log transient errors (unless high verbosity) */
#if defined(ENETUNREACH) || defined(EHOSTDOWN) || defined(EHOSTUNREACH) || defined(ENETDOWN)
switch(errno) {
# ifdef ENETUNREACH
case ENETUNREACH:
# endif
# ifdef EHOSTDOWN
case EHOSTDOWN:
# endif
# ifdef EHOSTUNREACH
case EHOSTUNREACH:
# endif
# ifdef ENETDOWN
case ENETDOWN:
# endif
case EPERM:
case EACCES:
if(verbosity < VERB_ALGO)
return 0;
break;
default:
break;
}
#endif
/* permission denied is gotten for every send if the
* network is disconnected (on some OS), squelch it */
if( ((errno == EPERM)
# ifdef EADDRNOTAVAIL
/* 'Cannot assign requested address' also when disconnected */
|| (errno == EADDRNOTAVAIL)
# endif
) && verbosity < VERB_ALGO)
return 0;
# ifdef EADDRINUSE
/* If SO_REUSEADDR is set, we could try to connect to the same server
* from the same source port twice. */
if(errno == EADDRINUSE && verbosity < VERB_DETAIL)
return 0;
# endif
/* squelch errors where people deploy AAAA ::ffff:bla for
* authority servers, which we try for intranets. */
if(errno == EINVAL && addr_is_ip4mapped(
(struct sockaddr_storage*)addr, addrlen) &&
verbosity < VERB_DETAIL)
return 0;
/* SO_BROADCAST sockopt can give access to 255.255.255.255,
* but a dns cache does not need it. */
if(errno == EACCES && addr_is_broadcast(
(struct sockaddr_storage*)addr, addrlen) &&
verbosity < VERB_DETAIL)
return 0;
return 1;
}
int tcp_connect_errno_needs_log(struct sockaddr* addr, socklen_t addrlen)
{
return udp_send_errno_needs_log(addr, addrlen);
}
/* send a UDP reply */
int
comm_point_send_udp_msg(struct comm_point *c, sldns_buffer* packet,
struct sockaddr* addr, socklen_t addrlen, int is_connected)
{
ssize_t sent;
log_assert(c->fd != -1);
#ifdef UNBOUND_DEBUG
if(sldns_buffer_remaining(packet) == 0)
log_err("error: send empty UDP packet");
#endif
log_assert(addr && addrlen > 0);
if(!is_connected) {
sent = sendto(c->fd, (void*)sldns_buffer_begin(packet),
sldns_buffer_remaining(packet), 0,
addr, addrlen);
} else {
sent = send(c->fd, (void*)sldns_buffer_begin(packet),
sldns_buffer_remaining(packet), 0);
}
if(sent == -1) {
/* try again and block, waiting for IO to complete,
* we want to send the answer, and we will wait for
* the ethernet interface buffer to have space. */
#ifndef USE_WINSOCK
if(errno == EAGAIN || errno == EINTR ||
# ifdef EWOULDBLOCK
errno == EWOULDBLOCK ||
# endif
errno == ENOBUFS) {
#else
if(WSAGetLastError() == WSAEINPROGRESS ||
WSAGetLastError() == WSAEINTR ||
WSAGetLastError() == WSAENOBUFS ||
WSAGetLastError() == WSAEWOULDBLOCK) {
#endif
int retries = 0;
/* if we set the fd blocking, other threads suddenly
* have a blocking fd that they operate on */
while(sent == -1 && retries < SEND_BLOCKED_MAX_RETRY && (
#ifndef USE_WINSOCK
errno == EAGAIN || errno == EINTR ||
# ifdef EWOULDBLOCK
errno == EWOULDBLOCK ||
# endif
errno == ENOBUFS
#else
WSAGetLastError() == WSAEINPROGRESS ||
WSAGetLastError() == WSAEINTR ||
WSAGetLastError() == WSAENOBUFS ||
WSAGetLastError() == WSAEWOULDBLOCK
#endif
)) {
#if defined(HAVE_POLL) || defined(USE_WINSOCK)
int send_nobufs = (
#ifndef USE_WINSOCK
errno == ENOBUFS
#else
WSAGetLastError() == WSAENOBUFS
#endif
);
struct pollfd p;
int pret;
memset(&p, 0, sizeof(p));
p.fd = c->fd;
p.events = POLLOUT | POLLERR | POLLHUP;
# ifndef USE_WINSOCK
pret = poll(&p, 1, SEND_BLOCKED_WAIT_TIMEOUT);
# else
pret = WSAPoll(&p, 1,
SEND_BLOCKED_WAIT_TIMEOUT);
# endif
if(pret == 0) {
/* timer expired */
struct comm_base* b = c->ev->base;
if(b->eb->last_writewait_log+SLOW_LOG_TIME <=
b->eb->secs) {
b->eb->last_writewait_log = b->eb->secs;
verbose(VERB_OPS, "send udp blocked "
"for long, dropping packet.");
}
return 0;
} else if(pret < 0 &&
#ifndef USE_WINSOCK
errno != EAGAIN && errno != EINTR &&
# ifdef EWOULDBLOCK
errno != EWOULDBLOCK &&
# endif
errno != ENOBUFS
#else
WSAGetLastError() != WSAEINPROGRESS &&
WSAGetLastError() != WSAEINTR &&
WSAGetLastError() != WSAENOBUFS &&
WSAGetLastError() != WSAEWOULDBLOCK
#endif
) {
log_err("poll udp out failed: %s",
sock_strerror(errno));
return 0;
} else if((pret < 0 &&
#ifndef USE_WINSOCK
errno == ENOBUFS
#else
WSAGetLastError() == WSAENOBUFS
#endif
) || (send_nobufs && retries > 0)) {
/* ENOBUFS, and poll returned without
* a timeout. Or the retried send call
* returned ENOBUFS. It is good to
* wait a bit for the error to clear. */
/* The timeout is 20*(2^(retries+1)),
* it increases exponentially, starting
* at 40 msec. After 5 tries, 1240 msec
* have passed in total, when poll
* returned the error, and 1200 msec
* when send returned the errors. */
#ifndef USE_WINSOCK
pret = poll(NULL, 0, (SEND_BLOCKED_WAIT_TIMEOUT/10)<<(retries+1));
#else
pret = WSAPoll(NULL, 0, (SEND_BLOCKED_WAIT_TIMEOUT/10)<<(retries+1));
#endif
if(pret < 0 &&
#ifndef USE_WINSOCK
errno != EAGAIN && errno != EINTR &&
# ifdef EWOULDBLOCK
errno != EWOULDBLOCK &&
# endif
errno != ENOBUFS
#else
WSAGetLastError() != WSAEINPROGRESS &&
WSAGetLastError() != WSAEINTR &&
WSAGetLastError() != WSAENOBUFS &&
WSAGetLastError() != WSAEWOULDBLOCK
#endif
) {
log_err("poll udp out timer failed: %s",
sock_strerror(errno));
}
}
#endif /* defined(HAVE_POLL) || defined(USE_WINSOCK) */
retries++;
if (!is_connected) {
sent = sendto(c->fd, (void*)sldns_buffer_begin(packet),
sldns_buffer_remaining(packet), 0,
addr, addrlen);
} else {
sent = send(c->fd, (void*)sldns_buffer_begin(packet),
sldns_buffer_remaining(packet), 0);
}
}
}
}
if(sent == -1) {
if(!udp_send_errno_needs_log(addr, addrlen))
return 0;
if (!is_connected) {
verbose(VERB_OPS, "sendto failed: %s", sock_strerror(errno));
} else {
verbose(VERB_OPS, "send failed: %s", sock_strerror(errno));
}
if(addr)
log_addr(VERB_OPS, "remote address is",
(struct sockaddr_storage*)addr, addrlen);
return 0;
} else if((size_t)sent != sldns_buffer_remaining(packet)) {
log_err("sent %d in place of %d bytes",
(int)sent, (int)sldns_buffer_remaining(packet));
return 0;
}
return 1;
}
#if defined(AF_INET6) && defined(IPV6_PKTINFO) && (defined(HAVE_RECVMSG) || defined(HAVE_SENDMSG))
/** print debug ancillary info */
static void p_ancil(const char* str, struct comm_reply* r)
{
if(r->srctype != 4 && r->srctype != 6) {
log_info("%s: unknown srctype %d", str, r->srctype);
return;
}
if(r->srctype == 6) {
#ifdef IPV6_PKTINFO
char buf[1024];
if(inet_ntop(AF_INET6, &r->pktinfo.v6info.ipi6_addr,
buf, (socklen_t)sizeof(buf)) == 0) {
(void)strlcpy(buf, "(inet_ntop error)", sizeof(buf));
}
buf[sizeof(buf)-1]=0;
log_info("%s: %s %d", str, buf, r->pktinfo.v6info.ipi6_ifindex);
#endif
} else if(r->srctype == 4) {
#ifdef IP_PKTINFO
char buf1[1024], buf2[1024];
if(inet_ntop(AF_INET, &r->pktinfo.v4info.ipi_addr,
buf1, (socklen_t)sizeof(buf1)) == 0) {
(void)strlcpy(buf1, "(inet_ntop error)", sizeof(buf1));
}
buf1[sizeof(buf1)-1]=0;
#ifdef HAVE_STRUCT_IN_PKTINFO_IPI_SPEC_DST
if(inet_ntop(AF_INET, &r->pktinfo.v4info.ipi_spec_dst,
buf2, (socklen_t)sizeof(buf2)) == 0) {
(void)strlcpy(buf2, "(inet_ntop error)", sizeof(buf2));
}
buf2[sizeof(buf2)-1]=0;
#else
buf2[0]=0;
#endif
log_info("%s: %d %s %s", str, r->pktinfo.v4info.ipi_ifindex,
buf1, buf2);
#elif defined(IP_RECVDSTADDR)
char buf1[1024];
if(inet_ntop(AF_INET, &r->pktinfo.v4addr,
buf1, (socklen_t)sizeof(buf1)) == 0) {
(void)strlcpy(buf1, "(inet_ntop error)", sizeof(buf1));
}
buf1[sizeof(buf1)-1]=0;
log_info("%s: %s", str, buf1);
#endif /* IP_PKTINFO or PI_RECVDSTDADDR */
}
}
#endif /* AF_INET6 && IPV6_PKTINFO && HAVE_RECVMSG||HAVE_SENDMSG */
/** send a UDP reply over specified interface*/
static int
comm_point_send_udp_msg_if(struct comm_point *c, sldns_buffer* packet,
struct sockaddr* addr, socklen_t addrlen, struct comm_reply* r)
{
#if defined(AF_INET6) && defined(IPV6_PKTINFO) && defined(HAVE_SENDMSG)
ssize_t sent;
struct msghdr msg;
struct iovec iov[1];
union {
struct cmsghdr hdr;
char buf[256];
} control;
#ifndef S_SPLINT_S
struct cmsghdr *cmsg;
#endif /* S_SPLINT_S */
log_assert(c->fd != -1);
#ifdef UNBOUND_DEBUG
if(sldns_buffer_remaining(packet) == 0)
log_err("error: send empty UDP packet");
#endif
log_assert(addr && addrlen > 0);
msg.msg_name = addr;
msg.msg_namelen = addrlen;
iov[0].iov_base = sldns_buffer_begin(packet);
iov[0].iov_len = sldns_buffer_remaining(packet);
msg.msg_iov = iov;
msg.msg_iovlen = 1;
msg.msg_control = control.buf;
#ifndef S_SPLINT_S
msg.msg_controllen = sizeof(control.buf);
#endif /* S_SPLINT_S */
msg.msg_flags = 0;
#ifndef S_SPLINT_S
cmsg = CMSG_FIRSTHDR(&msg);
if(r->srctype == 4) {
#ifdef IP_PKTINFO
void* cmsg_data;
msg.msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo));
log_assert(msg.msg_controllen <= sizeof(control.buf));
cmsg->cmsg_level = IPPROTO_IP;
cmsg->cmsg_type = IP_PKTINFO;
memmove(CMSG_DATA(cmsg), &r->pktinfo.v4info,
sizeof(struct in_pktinfo));
/* unset the ifindex to not bypass the routing tables */
cmsg_data = CMSG_DATA(cmsg);
((struct in_pktinfo *) cmsg_data)->ipi_ifindex = 0;
cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
/* zero the padding bytes inserted by the CMSG_LEN */
if(sizeof(struct in_pktinfo) < cmsg->cmsg_len)
memset(((uint8_t*)(CMSG_DATA(cmsg))) +
sizeof(struct in_pktinfo), 0, cmsg->cmsg_len
- sizeof(struct in_pktinfo));
#elif defined(IP_SENDSRCADDR)
msg.msg_controllen = CMSG_SPACE(sizeof(struct in_addr));
log_assert(msg.msg_controllen <= sizeof(control.buf));
cmsg->cmsg_level = IPPROTO_IP;
cmsg->cmsg_type = IP_SENDSRCADDR;
memmove(CMSG_DATA(cmsg), &r->pktinfo.v4addr,
sizeof(struct in_addr));
cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
/* zero the padding bytes inserted by the CMSG_LEN */
if(sizeof(struct in_addr) < cmsg->cmsg_len)
memset(((uint8_t*)(CMSG_DATA(cmsg))) +
sizeof(struct in_addr), 0, cmsg->cmsg_len
- sizeof(struct in_addr));
#else
verbose(VERB_ALGO, "no IP_PKTINFO or IP_SENDSRCADDR");
msg.msg_control = NULL;
#endif /* IP_PKTINFO or IP_SENDSRCADDR */
} else if(r->srctype == 6) {
void* cmsg_data;
msg.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
log_assert(msg.msg_controllen <= sizeof(control.buf));
cmsg->cmsg_level = IPPROTO_IPV6;
cmsg->cmsg_type = IPV6_PKTINFO;
memmove(CMSG_DATA(cmsg), &r->pktinfo.v6info,
sizeof(struct in6_pktinfo));
/* unset the ifindex to not bypass the routing tables */
cmsg_data = CMSG_DATA(cmsg);
((struct in6_pktinfo *) cmsg_data)->ipi6_ifindex = 0;
cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
/* zero the padding bytes inserted by the CMSG_LEN */
if(sizeof(struct in6_pktinfo) < cmsg->cmsg_len)
memset(((uint8_t*)(CMSG_DATA(cmsg))) +
sizeof(struct in6_pktinfo), 0, cmsg->cmsg_len
- sizeof(struct in6_pktinfo));
} else {
/* try to pass all 0 to use default route */
msg.msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
log_assert(msg.msg_controllen <= sizeof(control.buf));
cmsg->cmsg_level = IPPROTO_IPV6;
cmsg->cmsg_type = IPV6_PKTINFO;
memset(CMSG_DATA(cmsg), 0, sizeof(struct in6_pktinfo));
cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
/* zero the padding bytes inserted by the CMSG_LEN */
if(sizeof(struct in6_pktinfo) < cmsg->cmsg_len)
memset(((uint8_t*)(CMSG_DATA(cmsg))) +
sizeof(struct in6_pktinfo), 0, cmsg->cmsg_len
- sizeof(struct in6_pktinfo));
}
#endif /* S_SPLINT_S */
if(verbosity >= VERB_ALGO && r->srctype != 0)
p_ancil("send_udp over interface", r);
sent = sendmsg(c->fd, &msg, 0);
if(sent == -1) {
/* try again and block, waiting for IO to complete,
* we want to send the answer, and we will wait for
* the ethernet interface buffer to have space. */
#ifndef USE_WINSOCK
if(errno == EAGAIN || errno == EINTR ||
# ifdef EWOULDBLOCK
errno == EWOULDBLOCK ||
# endif
errno == ENOBUFS) {
#else
if(WSAGetLastError() == WSAEINPROGRESS ||
WSAGetLastError() == WSAEINTR ||
WSAGetLastError() == WSAENOBUFS ||
WSAGetLastError() == WSAEWOULDBLOCK) {
#endif
int retries = 0;
while(sent == -1 && retries < SEND_BLOCKED_MAX_RETRY && (
#ifndef USE_WINSOCK
errno == EAGAIN || errno == EINTR ||
# ifdef EWOULDBLOCK
errno == EWOULDBLOCK ||
# endif
errno == ENOBUFS
#else
WSAGetLastError() == WSAEINPROGRESS ||
WSAGetLastError() == WSAEINTR ||
WSAGetLastError() == WSAENOBUFS ||
WSAGetLastError() == WSAEWOULDBLOCK
#endif
)) {
#if defined(HAVE_POLL) || defined(USE_WINSOCK)
int send_nobufs = (
#ifndef USE_WINSOCK
errno == ENOBUFS
#else
WSAGetLastError() == WSAENOBUFS
#endif
);
struct pollfd p;
int pret;
memset(&p, 0, sizeof(p));
p.fd = c->fd;
p.events = POLLOUT | POLLERR | POLLHUP;
# ifndef USE_WINSOCK
pret = poll(&p, 1, SEND_BLOCKED_WAIT_TIMEOUT);
# else
pret = WSAPoll(&p, 1,
SEND_BLOCKED_WAIT_TIMEOUT);
# endif
if(pret == 0) {
/* timer expired */
struct comm_base* b = c->ev->base;
if(b->eb->last_writewait_log+SLOW_LOG_TIME <=
b->eb->secs) {
b->eb->last_writewait_log = b->eb->secs;
verbose(VERB_OPS, "send udp blocked "
"for long, dropping packet.");
}
return 0;
} else if(pret < 0 &&
#ifndef USE_WINSOCK
errno != EAGAIN && errno != EINTR &&
# ifdef EWOULDBLOCK
errno != EWOULDBLOCK &&
# endif
errno != ENOBUFS
#else
WSAGetLastError() != WSAEINPROGRESS &&
WSAGetLastError() != WSAEINTR &&
WSAGetLastError() != WSAENOBUFS &&
WSAGetLastError() != WSAEWOULDBLOCK
#endif
) {
log_err("poll udp out failed: %s",
sock_strerror(errno));
return 0;
} else if((pret < 0 &&
#ifndef USE_WINSOCK
errno == ENOBUFS
#else
WSAGetLastError() == WSAENOBUFS
#endif
) || (send_nobufs && retries > 0)) {
/* ENOBUFS, and poll returned without
* a timeout. Or the retried send call
* returned ENOBUFS. It is good to
* wait a bit for the error to clear. */
/* The timeout is 20*(2^(retries+1)),
* it increases exponentially, starting
* at 40 msec. After 5 tries, 1240 msec
* have passed in total, when poll
* returned the error, and 1200 msec
* when send returned the errors. */
#ifndef USE_WINSOCK
pret = poll(NULL, 0, (SEND_BLOCKED_WAIT_TIMEOUT/10)<<(retries+1));
#else
pret = WSAPoll(NULL, 0, (SEND_BLOCKED_WAIT_TIMEOUT/10)<<(retries+1));
#endif
if(pret < 0 &&
#ifndef USE_WINSOCK
errno != EAGAIN && errno != EINTR &&
# ifdef EWOULDBLOCK
errno != EWOULDBLOCK &&
# endif
errno != ENOBUFS
#else
WSAGetLastError() != WSAEINPROGRESS &&
WSAGetLastError() != WSAEINTR &&
WSAGetLastError() != WSAENOBUFS &&
WSAGetLastError() != WSAEWOULDBLOCK
#endif
) {
log_err("poll udp out timer failed: %s",
sock_strerror(errno));
}
}
#endif /* defined(HAVE_POLL) || defined(USE_WINSOCK) */
retries++;
sent = sendmsg(c->fd, &msg, 0);
}
}
}
if(sent == -1) {
if(!udp_send_errno_needs_log(addr, addrlen))
return 0;
verbose(VERB_OPS, "sendmsg failed: %s", strerror(errno));
log_addr(VERB_OPS, "remote address is",
(struct sockaddr_storage*)addr, addrlen);
#ifdef __NetBSD__
/* netbsd 7 has IP_PKTINFO for recv but not send */
if(errno == EINVAL && r->srctype == 4)
log_err("sendmsg: No support for sendmsg(IP_PKTINFO). "
"Please disable interface-automatic");
#endif
return 0;
} else if((size_t)sent != sldns_buffer_remaining(packet)) {
log_err("sent %d in place of %d bytes",
(int)sent, (int)sldns_buffer_remaining(packet));
return 0;
}
return 1;
#else
(void)c;
(void)packet;
(void)addr;
(void)addrlen;
(void)r;
log_err("sendmsg: IPV6_PKTINFO not supported");
return 0;
#endif /* AF_INET6 && IPV6_PKTINFO && HAVE_SENDMSG */
}
/** return true is UDP receive error needs to be logged */
static int udp_recv_needs_log(int err)
{
switch(err) {
case EACCES: /* some hosts send ICMP 'Permission Denied' */
#ifndef USE_WINSOCK
case ECONNREFUSED:
# ifdef ENETUNREACH
case ENETUNREACH:
# endif
# ifdef EHOSTDOWN
case EHOSTDOWN:
# endif
# ifdef EHOSTUNREACH
case EHOSTUNREACH:
# endif
# ifdef ENETDOWN
case ENETDOWN:
# endif
#else /* USE_WINSOCK */
case WSAECONNREFUSED:
case WSAENETUNREACH:
case WSAEHOSTDOWN:
case WSAEHOSTUNREACH:
case WSAENETDOWN:
#endif
if(verbosity >= VERB_ALGO)
return 1;
return 0;
default:
break;
}
return 1;
}
/** Parses the PROXYv2 header from buf and updates the comm_reply struct.
* Returns 1 on success, 0 on failure. */
static int consume_pp2_header(struct sldns_buffer* buf, struct comm_reply* rep,
int stream) {
size_t size;
struct pp2_header *header;
int err = pp2_read_header(sldns_buffer_begin(buf),
sldns_buffer_remaining(buf));
if(err) return 0;
header = (struct pp2_header*)sldns_buffer_begin(buf);
size = PP2_HEADER_SIZE + ntohs(header->len);
if((header->ver_cmd & 0xF) == PP2_CMD_LOCAL) {
/* A connection from the proxy itself.
* No need to do anything with addresses. */
goto done;
}
if(header->fam_prot == PP2_UNSPEC_UNSPEC) {
/* Unspecified family and protocol. This could be used for
* health checks by proxies.
* No need to do anything with addresses. */
goto done;
}
/* Read the proxied address */
switch(header->fam_prot) {
case PP2_INET_STREAM:
case PP2_INET_DGRAM:
{
struct sockaddr_in* addr =
(struct sockaddr_in*)&rep->client_addr;
addr->sin_family = AF_INET;
addr->sin_addr.s_addr = header->addr.addr4.src_addr;
addr->sin_port = header->addr.addr4.src_port;
rep->client_addrlen = (socklen_t)sizeof(struct sockaddr_in);
}
/* Ignore the destination address; it should be us. */
break;
case PP2_INET6_STREAM:
case PP2_INET6_DGRAM:
{
struct sockaddr_in6* addr =
(struct sockaddr_in6*)&rep->client_addr;
memset(addr, 0, sizeof(*addr));
addr->sin6_family = AF_INET6;
memcpy(&addr->sin6_addr,
header->addr.addr6.src_addr, 16);
addr->sin6_port = header->addr.addr6.src_port;
rep->client_addrlen = (socklen_t)sizeof(struct sockaddr_in6);
}
/* Ignore the destination address; it should be us. */
break;
default:
log_err("proxy_protocol: unsupported family and "
"protocol 0x%x", (int)header->fam_prot);
return 0;
}
rep->is_proxied = 1;
done:
if(!stream) {
/* We are reading a whole packet;
* Move the rest of the data to overwrite the PROXYv2 header */
/* XXX can we do better to avoid memmove? */
memmove(header, ((char*)header)+size,
sldns_buffer_limit(buf)-size);
sldns_buffer_set_limit(buf, sldns_buffer_limit(buf)-size);
}
return 1;
}
#if defined(AF_INET6) && defined(IPV6_PKTINFO) && defined(HAVE_RECVMSG)
void
comm_point_udp_ancil_callback(int fd, short event, void* arg)
{
struct comm_reply rep;
struct msghdr msg;
struct iovec iov[1];
ssize_t rcv;
union {
struct cmsghdr hdr;
char buf[256];
} ancil;
int i;
#ifndef S_SPLINT_S
struct cmsghdr* cmsg;
#endif /* S_SPLINT_S */
#ifdef HAVE_LINUX_NET_TSTAMP_H
struct timespec *ts;
#endif /* HAVE_LINUX_NET_TSTAMP_H */
rep.c = (struct comm_point*)arg;
log_assert(rep.c->type == comm_udp);
if(!(event&UB_EV_READ))
return;
log_assert(rep.c && rep.c->buffer && rep.c->fd == fd);
ub_comm_base_now(rep.c->ev->base);
for(i=0; i<NUM_UDP_PER_SELECT; i++) {
sldns_buffer_clear(rep.c->buffer);
timeval_clear(&rep.c->recv_tv);
rep.remote_addrlen = (socklen_t)sizeof(rep.remote_addr);
log_assert(fd != -1);
log_assert(sldns_buffer_remaining(rep.c->buffer) > 0);
msg.msg_name = &rep.remote_addr;
msg.msg_namelen = (socklen_t)sizeof(rep.remote_addr);
iov[0].iov_base = sldns_buffer_begin(rep.c->buffer);
iov[0].iov_len = sldns_buffer_remaining(rep.c->buffer);
msg.msg_iov = iov;
msg.msg_iovlen = 1;
msg.msg_control = ancil.buf;
#ifndef S_SPLINT_S
msg.msg_controllen = sizeof(ancil.buf);
#endif /* S_SPLINT_S */
msg.msg_flags = 0;
rcv = recvmsg(fd, &msg, MSG_DONTWAIT);
if(rcv == -1) {
if(errno != EAGAIN && errno != EINTR
&& udp_recv_needs_log(errno)) {
log_err("recvmsg failed: %s", strerror(errno));
}
return;
}
rep.remote_addrlen = msg.msg_namelen;
sldns_buffer_skip(rep.c->buffer, rcv);
sldns_buffer_flip(rep.c->buffer);
rep.srctype = 0;
rep.is_proxied = 0;
#ifndef S_SPLINT_S
for(cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL;
cmsg = CMSG_NXTHDR(&msg, cmsg)) {
if( cmsg->cmsg_level == IPPROTO_IPV6 &&
cmsg->cmsg_type == IPV6_PKTINFO) {
rep.srctype = 6;
memmove(&rep.pktinfo.v6info, CMSG_DATA(cmsg),
sizeof(struct in6_pktinfo));
break;
#ifdef IP_PKTINFO
} else if( cmsg->cmsg_level == IPPROTO_IP &&
cmsg->cmsg_type == IP_PKTINFO) {
rep.srctype = 4;
memmove(&rep.pktinfo.v4info, CMSG_DATA(cmsg),
sizeof(struct in_pktinfo));
break;
#elif defined(IP_RECVDSTADDR)
} else if( cmsg->cmsg_level == IPPROTO_IP &&
cmsg->cmsg_type == IP_RECVDSTADDR) {
rep.srctype = 4;
memmove(&rep.pktinfo.v4addr, CMSG_DATA(cmsg),
sizeof(struct in_addr));
break;
#endif /* IP_PKTINFO or IP_RECVDSTADDR */
#ifdef HAVE_LINUX_NET_TSTAMP_H
} else if( cmsg->cmsg_level == SOL_SOCKET &&
cmsg->cmsg_type == SO_TIMESTAMPNS) {
ts = (struct timespec *)CMSG_DATA(cmsg);
TIMESPEC_TO_TIMEVAL(&rep.c->recv_tv, ts);
} else if( cmsg->cmsg_level == SOL_SOCKET &&
cmsg->cmsg_type == SO_TIMESTAMPING) {
ts = (struct timespec *)CMSG_DATA(cmsg);
TIMESPEC_TO_TIMEVAL(&rep.c->recv_tv, ts);
} else if( cmsg->cmsg_level == SOL_SOCKET &&
cmsg->cmsg_type == SO_TIMESTAMP) {
memmove(&rep.c->recv_tv, CMSG_DATA(cmsg), sizeof(struct timeval));
#endif /* HAVE_LINUX_NET_TSTAMP_H */
}
}
if(verbosity >= VERB_ALGO && rep.srctype != 0)
p_ancil("receive_udp on interface", &rep);
#endif /* S_SPLINT_S */
if(rep.c->pp2_enabled && !consume_pp2_header(rep.c->buffer,
&rep, 0)) {
log_err("proxy_protocol: could not consume PROXYv2 header");
return;
}
if(!rep.is_proxied) {
rep.client_addrlen = rep.remote_addrlen;
memmove(&rep.client_addr, &rep.remote_addr,
rep.remote_addrlen);
}
fptr_ok(fptr_whitelist_comm_point(rep.c->callback));
if((*rep.c->callback)(rep.c, rep.c->cb_arg, NETEVENT_NOERROR, &rep)) {
/* send back immediate reply */
struct sldns_buffer *buffer;
#ifdef USE_DNSCRYPT
buffer = rep.c->dnscrypt_buffer;
#else
buffer = rep.c->buffer;
#endif
(void)comm_point_send_udp_msg_if(rep.c, buffer,
(struct sockaddr*)&rep.remote_addr,
rep.remote_addrlen, &rep);
}
if(!rep.c || rep.c->fd == -1) /* commpoint closed */
break;
}
}
#endif /* AF_INET6 && IPV6_PKTINFO && HAVE_RECVMSG */
void
comm_point_udp_callback(int fd, short event, void* arg)
{
struct comm_reply rep;
ssize_t rcv;
int i;
struct sldns_buffer *buffer;
rep.c = (struct comm_point*)arg;
log_assert(rep.c->type == comm_udp);
if(!(event&UB_EV_READ))
return;
log_assert(rep.c && rep.c->buffer && rep.c->fd == fd);
ub_comm_base_now(rep.c->ev->base);
for(i=0; i<NUM_UDP_PER_SELECT; i++) {
sldns_buffer_clear(rep.c->buffer);
rep.remote_addrlen = (socklen_t)sizeof(rep.remote_addr);
log_assert(fd != -1);
log_assert(sldns_buffer_remaining(rep.c->buffer) > 0);
rcv = recvfrom(fd, (void*)sldns_buffer_begin(rep.c->buffer),
sldns_buffer_remaining(rep.c->buffer), MSG_DONTWAIT,
(struct sockaddr*)&rep.remote_addr, &rep.remote_addrlen);
if(rcv == -1) {
#ifndef USE_WINSOCK
if(errno != EAGAIN && errno != EINTR
&& udp_recv_needs_log(errno))
log_err("recvfrom %d failed: %s",
fd, strerror(errno));
#else
if(WSAGetLastError() != WSAEINPROGRESS &&
WSAGetLastError() != WSAECONNRESET &&
WSAGetLastError()!= WSAEWOULDBLOCK &&
udp_recv_needs_log(WSAGetLastError()))
log_err("recvfrom failed: %s",
wsa_strerror(WSAGetLastError()));
#endif
return;
}
sldns_buffer_skip(rep.c->buffer, rcv);
sldns_buffer_flip(rep.c->buffer);
rep.srctype = 0;
rep.is_proxied = 0;
if(rep.c->pp2_enabled && !consume_pp2_header(rep.c->buffer,
&rep, 0)) {
log_err("proxy_protocol: could not consume PROXYv2 header");
return;
}
if(!rep.is_proxied) {
rep.client_addrlen = rep.remote_addrlen;
memmove(&rep.client_addr, &rep.remote_addr,
rep.remote_addrlen);
}
fptr_ok(fptr_whitelist_comm_point(rep.c->callback));
if((*rep.c->callback)(rep.c, rep.c->cb_arg, NETEVENT_NOERROR, &rep)) {
/* send back immediate reply */
#ifdef USE_DNSCRYPT
buffer = rep.c->dnscrypt_buffer;
#else
buffer = rep.c->buffer;
#endif
(void)comm_point_send_udp_msg(rep.c, buffer,
(struct sockaddr*)&rep.remote_addr,
rep.remote_addrlen, 0);
}
if(!rep.c || rep.c->fd != fd) /* commpoint closed to -1 or reused for
another UDP port. Note rep.c cannot be reused with TCP fd. */
break;
}
}
#ifdef HAVE_NGTCP2
void
doq_pkt_addr_init(struct doq_pkt_addr* paddr)
{
paddr->addrlen = (socklen_t)sizeof(paddr->addr);
paddr->localaddrlen = (socklen_t)sizeof(paddr->localaddr);
paddr->ifindex = 0;
}
/** set the ecn on the transmission */
static void
doq_set_ecn(int fd, int family, uint32_t ecn)
{
unsigned int val = ecn;
if(family == AF_INET6) {
if(setsockopt(fd, IPPROTO_IPV6, IPV6_TCLASS, &val,
(socklen_t)sizeof(val)) == -1) {
log_err("setsockopt(.. IPV6_TCLASS ..): %s",
strerror(errno));
}
return;
}
if(setsockopt(fd, IPPROTO_IP, IP_TOS, &val,
(socklen_t)sizeof(val)) == -1) {
log_err("setsockopt(.. IP_TOS ..): %s",
strerror(errno));
}
}
/** set the local address in the control ancillary data */
static void
doq_set_localaddr_cmsg(struct msghdr* msg, size_t control_size,
struct doq_addr_storage* localaddr, socklen_t localaddrlen,
int ifindex)
{
#ifndef S_SPLINT_S
struct cmsghdr* cmsg;
#endif /* S_SPLINT_S */
#ifndef S_SPLINT_S
cmsg = CMSG_FIRSTHDR(msg);
if(localaddr->sockaddr.in.sin_family == AF_INET) {
#ifdef IP_PKTINFO
struct sockaddr_in* sa = (struct sockaddr_in*)localaddr;
struct in_pktinfo v4info;
log_assert(localaddrlen >= sizeof(struct sockaddr_in));
msg->msg_controllen = CMSG_SPACE(sizeof(struct in_pktinfo));
memset(msg->msg_control, 0, msg->msg_controllen);
log_assert(msg->msg_controllen <= control_size);
cmsg->cmsg_level = IPPROTO_IP;
cmsg->cmsg_type = IP_PKTINFO;
memset(&v4info, 0, sizeof(v4info));
# ifdef HAVE_STRUCT_IN_PKTINFO_IPI_SPEC_DST
memmove(&v4info.ipi_spec_dst, &sa->sin_addr,
sizeof(struct in_addr));
# else
memmove(&v4info.ipi_addr, &sa->sin_addr,
sizeof(struct in_addr));
# endif
v4info.ipi_ifindex = ifindex;
memmove(CMSG_DATA(cmsg), &v4info, sizeof(struct in_pktinfo));
cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
#elif defined(IP_SENDSRCADDR)
struct sockaddr_in* sa= (struct sockaddr_in*)localaddr;
log_assert(localaddrlen >= sizeof(struct sockaddr_in));
msg->msg_controllen = CMSG_SPACE(sizeof(struct in_addr));
memset(msg->msg_control, 0, msg->msg_controllen);
log_assert(msg->msg_controllen <= control_size);
cmsg->cmsg_level = IPPROTO_IP;
cmsg->cmsg_type = IP_SENDSRCADDR;
memmove(CMSG_DATA(cmsg), &sa->sin_addr,
sizeof(struct in_addr));
cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_addr));
#endif
} else {
struct sockaddr_in6* sa6 = (struct sockaddr_in6*)localaddr;
struct in6_pktinfo v6info;
log_assert(localaddrlen >= sizeof(struct sockaddr_in6));
msg->msg_controllen = CMSG_SPACE(sizeof(struct in6_pktinfo));
memset(msg->msg_control, 0, msg->msg_controllen);
log_assert(msg->msg_controllen <= control_size);
cmsg->cmsg_level = IPPROTO_IPV6;
cmsg->cmsg_type = IPV6_PKTINFO;
memset(&v6info, 0, sizeof(v6info));
memmove(&v6info.ipi6_addr, &sa6->sin6_addr,
sizeof(struct in6_addr));
v6info.ipi6_ifindex = ifindex;
memmove(CMSG_DATA(cmsg), &v6info, sizeof(struct in6_pktinfo));
cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo));
}
#endif /* S_SPLINT_S */
/* Ignore unused variables, if no assertions are compiled. */
(void)localaddrlen;
(void)control_size;
}
/** write address and port into strings */
static int
doq_print_addr_port(struct doq_addr_storage* addr, socklen_t addrlen,
char* host, size_t hostlen, char* port, size_t portlen)
{
if(addr->sockaddr.in.sin_family == AF_INET) {
struct sockaddr_in* sa = (struct sockaddr_in*)addr;
log_assert(addrlen >= sizeof(*sa));
if(inet_ntop(sa->sin_family, &sa->sin_addr, host,
(socklen_t)hostlen) == 0) {
log_hex("inet_ntop error: address", &sa->sin_addr,
sizeof(sa->sin_addr));
return 0;
}
snprintf(port, portlen, "%u", (unsigned)ntohs(sa->sin_port));
} else if(addr->sockaddr.in.sin_family == AF_INET6) {
struct sockaddr_in6* sa6 = (struct sockaddr_in6*)addr;
log_assert(addrlen >= sizeof(*sa6));
if(inet_ntop(sa6->sin6_family, &sa6->sin6_addr, host,
(socklen_t)hostlen) == 0) {
log_hex("inet_ntop error: address", &sa6->sin6_addr,
sizeof(sa6->sin6_addr));
return 0;
}
snprintf(port, portlen, "%u", (unsigned)ntohs(sa6->sin6_port));
}
return 1;
}
/** doq store the blocked packet when write has blocked */
static void
doq_store_blocked_pkt(struct comm_point* c, struct doq_pkt_addr* paddr,
uint32_t ecn)
{
if(c->doq_socket->have_blocked_pkt)
return; /* should not happen that we write when there is
already a blocked write, but if so, drop it. */
if(sldns_buffer_limit(c->doq_socket->pkt_buf) >
sldns_buffer_capacity(c->doq_socket->blocked_pkt))
return; /* impossibly large, drop packet. impossible because
pkt_buf and blocked_pkt are the same size. */
c->doq_socket->have_blocked_pkt = 1;
c->doq_socket->blocked_pkt_pi.ecn = ecn;
memcpy(c->doq_socket->blocked_paddr, paddr,
sizeof(*c->doq_socket->blocked_paddr));
sldns_buffer_clear(c->doq_socket->blocked_pkt);
sldns_buffer_write(c->doq_socket->blocked_pkt,
sldns_buffer_begin(c->doq_socket->pkt_buf),
sldns_buffer_limit(c->doq_socket->pkt_buf));
sldns_buffer_flip(c->doq_socket->blocked_pkt);
}
void
doq_send_pkt(struct comm_point* c, struct doq_pkt_addr* paddr, uint32_t ecn)
{
struct msghdr msg;
struct iovec iov[1];
union {
struct cmsghdr hdr;
char buf[256];
} control;
ssize_t ret;
iov[0].iov_base = sldns_buffer_begin(c->doq_socket->pkt_buf);
iov[0].iov_len = sldns_buffer_limit(c->doq_socket->pkt_buf);
memset(&msg, 0, sizeof(msg));
msg.msg_name = (void*)&paddr->addr;
msg.msg_namelen = paddr->addrlen;
msg.msg_iov = iov;
msg.msg_iovlen = 1;
msg.msg_control = control.buf;
#ifndef S_SPLINT_S
msg.msg_controllen = sizeof(control.buf);
#endif /* S_SPLINT_S */
msg.msg_flags = 0;
doq_set_localaddr_cmsg(&msg, sizeof(control.buf), &paddr->localaddr,
paddr->localaddrlen, paddr->ifindex);
doq_set_ecn(c->fd, paddr->addr.sockaddr.in.sin_family, ecn);
for(;;) {
ret = sendmsg(c->fd, &msg, MSG_DONTWAIT);
if(ret == -1 && errno == EINTR)
continue;
break;
}
if(ret == -1) {
#ifndef USE_WINSOCK
if(errno == EAGAIN ||
# ifdef EWOULDBLOCK
errno == EWOULDBLOCK ||
# endif
errno == ENOBUFS)
#else
if(WSAGetLastError() == WSAEINPROGRESS ||
WSAGetLastError() == WSAENOBUFS ||
WSAGetLastError() == WSAEWOULDBLOCK)
#endif
{
/* udp send has blocked */
doq_store_blocked_pkt(c, paddr, ecn);
return;
}
if(!udp_send_errno_needs_log((void*)&paddr->addr,
paddr->addrlen))
return;
if(verbosity >= VERB_OPS) {
char host[256], port[32];
if(doq_print_addr_port(&paddr->addr, paddr->addrlen,
host, sizeof(host), port, sizeof(port))) {
verbose(VERB_OPS, "doq sendmsg to %s %s "
"failed: %s", host, port,
strerror(errno));
} else {
verbose(VERB_OPS, "doq sendmsg failed: %s",
strerror(errno));
}
}
return;
} else if(ret != (ssize_t)sldns_buffer_limit(c->doq_socket->pkt_buf)) {
char host[256], port[32];
if(doq_print_addr_port(&paddr->addr, paddr->addrlen, host,
sizeof(host), port, sizeof(port))) {
log_err("doq sendmsg to %s %s failed: "
"sent %d in place of %d bytes",
host, port, (int)ret,
(int)sldns_buffer_limit(c->doq_socket->pkt_buf));
} else {
log_err("doq sendmsg failed: "
"sent %d in place of %d bytes",
(int)ret, (int)sldns_buffer_limit(c->doq_socket->pkt_buf));
}
return;
}
}
/** fetch port number */
static int
doq_sockaddr_get_port(struct doq_addr_storage* addr)
{
if(addr->sockaddr.in.sin_family == AF_INET) {
struct sockaddr_in* sa = (struct sockaddr_in*)addr;
return ntohs(sa->sin_port);
} else if(addr->sockaddr.in.sin_family == AF_INET6) {
struct sockaddr_in6* sa6 = (struct sockaddr_in6*)addr;
return ntohs(sa6->sin6_port);
}
return 0;
}
/** get local address from ancillary data headers */
static int
doq_get_localaddr_cmsg(struct comm_point* c, struct doq_pkt_addr* paddr,
int* pkt_continue, struct msghdr* msg)
{
#ifndef S_SPLINT_S
struct cmsghdr* cmsg;
#endif /* S_SPLINT_S */
memset(&paddr->localaddr, 0, sizeof(paddr->localaddr));
#ifndef S_SPLINT_S
for(cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL;
cmsg = CMSG_NXTHDR(msg, cmsg)) {
if( cmsg->cmsg_level == IPPROTO_IPV6 &&
cmsg->cmsg_type == IPV6_PKTINFO) {
struct in6_pktinfo* v6info =
(struct in6_pktinfo*)CMSG_DATA(cmsg);
struct sockaddr_in6* sa= (struct sockaddr_in6*)
&paddr->localaddr;
struct sockaddr_in6* rema = (struct sockaddr_in6*)
&paddr->addr;
if(rema->sin6_family != AF_INET6) {
log_err("doq cmsg family mismatch cmsg is ip6");
*pkt_continue = 1;
return 0;
}
sa->sin6_family = AF_INET6;
sa->sin6_port = htons(doq_sockaddr_get_port(
(void*)c->socket->addr));
paddr->ifindex = v6info->ipi6_ifindex;
memmove(&sa->sin6_addr, &v6info->ipi6_addr,
sizeof(struct in6_addr));
paddr->localaddrlen = sizeof(struct sockaddr_in6);
break;
#ifdef IP_PKTINFO
} else if( cmsg->cmsg_level == IPPROTO_IP &&
cmsg->cmsg_type == IP_PKTINFO) {
struct in_pktinfo* v4info =
(struct in_pktinfo*)CMSG_DATA(cmsg);
struct sockaddr_in* sa= (struct sockaddr_in*)
&paddr->localaddr;
struct sockaddr_in* rema = (struct sockaddr_in*)
&paddr->addr;
if(rema->sin_family != AF_INET) {
log_err("doq cmsg family mismatch cmsg is ip4");
*pkt_continue = 1;
return 0;
}
sa->sin_family = AF_INET;
sa->sin_port = htons(doq_sockaddr_get_port(
(void*)c->socket->addr));
paddr->ifindex = v4info->ipi_ifindex;
memmove(&sa->sin_addr, &v4info->ipi_addr,
sizeof(struct in_addr));
paddr->localaddrlen = sizeof(struct sockaddr_in);
break;
#elif defined(IP_RECVDSTADDR)
} else if( cmsg->cmsg_level == IPPROTO_IP &&
cmsg->cmsg_type == IP_RECVDSTADDR) {
struct sockaddr_in* sa= (struct sockaddr_in*)
&paddr->localaddr;
struct sockaddr_in* rema = (struct sockaddr_in*)
&paddr->addr;
if(rema->sin_family != AF_INET) {
log_err("doq cmsg family mismatch cmsg is ip4");
*pkt_continue = 1;
return 0;
}
sa->sin_family = AF_INET;
sa->sin_port = htons(doq_sockaddr_get_port(
(void*)c->socket->addr));
paddr->ifindex = 0;
memmove(&sa.sin_addr, CMSG_DATA(cmsg),
sizeof(struct in_addr));
paddr->localaddrlen = sizeof(struct sockaddr_in);
break;
#endif /* IP_PKTINFO or IP_RECVDSTADDR */
}
}
#endif /* S_SPLINT_S */
return 1;
}
/** get packet ecn information */
static uint32_t
msghdr_get_ecn(struct msghdr* msg, int family)
{
#ifndef S_SPLINT_S
struct cmsghdr* cmsg;
if(family == AF_INET6) {
for(cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL;
cmsg = CMSG_NXTHDR(msg, cmsg)) {
if(cmsg->cmsg_level == IPPROTO_IPV6 &&
cmsg->cmsg_type == IPV6_TCLASS &&
cmsg->cmsg_len != 0) {
uint8_t* ecn = (uint8_t*)CMSG_DATA(cmsg);
return *ecn;
}
}
return 0;
}
for(cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL;
cmsg = CMSG_NXTHDR(msg, cmsg)) {
if(cmsg->cmsg_level == IPPROTO_IP &&
cmsg->cmsg_type == IP_TOS &&
cmsg->cmsg_len != 0) {
uint8_t* ecn = (uint8_t*)CMSG_DATA(cmsg);
return *ecn;
}
}
#endif /* S_SPLINT_S */
return 0;
}
/** receive packet for DoQ on UDP. get ancillary data for addresses,
* return false if failed and the callback can stop receiving UDP packets
* if pkt_continue is false. */
static int
doq_recv(struct comm_point* c, struct doq_pkt_addr* paddr, int* pkt_continue,
struct ngtcp2_pkt_info* pi)
{
struct msghdr msg;
struct iovec iov[1];
ssize_t rcv;
union {
struct cmsghdr hdr;
char buf[256];
} ancil;
msg.msg_name = &paddr->addr;
msg.msg_namelen = (socklen_t)sizeof(paddr->addr);
iov[0].iov_base = sldns_buffer_begin(c->doq_socket->pkt_buf);
iov[0].iov_len = sldns_buffer_remaining(c->doq_socket->pkt_buf);
msg.msg_iov = iov;
msg.msg_iovlen = 1;
msg.msg_control = ancil.buf;
#ifndef S_SPLINT_S
msg.msg_controllen = sizeof(ancil.buf);
#endif /* S_SPLINT_S */
msg.msg_flags = 0;
rcv = recvmsg(c->fd, &msg, MSG_DONTWAIT);
if(rcv == -1) {
if(errno != EAGAIN && errno != EINTR
&& udp_recv_needs_log(errno)) {
log_err("recvmsg failed for doq: %s", strerror(errno));
}
*pkt_continue = 0;
return 0;
}
paddr->addrlen = msg.msg_namelen;
sldns_buffer_skip(c->doq_socket->pkt_buf, rcv);
sldns_buffer_flip(c->doq_socket->pkt_buf);
if(!doq_get_localaddr_cmsg(c, paddr, pkt_continue, &msg))
return 0;
pi->ecn = msghdr_get_ecn(&msg, paddr->addr.sockaddr.in.sin_family);
return 1;
}
/** send the version negotiation for doq. scid and dcid are flipped around
* to send back to the client. */
static void
doq_send_version_negotiation(struct comm_point* c, struct doq_pkt_addr* paddr,
const uint8_t* dcid, size_t dcidlen, const uint8_t* scid,
size_t scidlen)
{
uint32_t versions[2];
size_t versions_len = 0;
ngtcp2_ssize ret;
uint8_t unused_random;
/* fill the array with supported versions */
versions[0] = NGTCP2_PROTO_VER_V1;
versions_len = 1;
unused_random = ub_random_max(c->doq_socket->rnd, 256);
sldns_buffer_clear(c->doq_socket->pkt_buf);
ret = ngtcp2_pkt_write_version_negotiation(
sldns_buffer_begin(c->doq_socket->pkt_buf),
sldns_buffer_capacity(c->doq_socket->pkt_buf), unused_random,
dcid, dcidlen, scid, scidlen, versions, versions_len);
if(ret < 0) {
log_err("ngtcp2_pkt_write_version_negotiation failed: %s",
ngtcp2_strerror(ret));
return;
}
sldns_buffer_set_position(c->doq_socket->pkt_buf, ret);
sldns_buffer_flip(c->doq_socket->pkt_buf);
doq_send_pkt(c, paddr, 0);
}
/** Find the doq_conn object by remote address and dcid */
static struct doq_conn*
doq_conn_find(struct doq_table* table, struct doq_addr_storage* addr,
socklen_t addrlen, struct doq_addr_storage* localaddr,
socklen_t localaddrlen, int ifindex, const uint8_t* dcid,
size_t dcidlen)
{
struct rbnode_type* node;
struct doq_conn key;
memset(&key.node, 0, sizeof(key.node));
key.node.key = &key;
memmove(&key.key.paddr.addr, addr, addrlen);
key.key.paddr.addrlen = addrlen;
memmove(&key.key.paddr.localaddr, localaddr, localaddrlen);
key.key.paddr.localaddrlen = localaddrlen;
key.key.paddr.ifindex = ifindex;
key.key.dcid = (void*)dcid;
key.key.dcidlen = dcidlen;
node = rbtree_search(table->conn_tree, &key);
if(node)
return (struct doq_conn*)node->key;
return NULL;
}
/** find the doq_con by the connection id */
static struct doq_conn*
doq_conn_find_by_id(struct doq_table* table, const uint8_t* dcid,
size_t dcidlen)
{
struct doq_conid* conid;
lock_rw_rdlock(&table->conid_lock);
conid = doq_conid_find(table, dcid, dcidlen);
if(conid) {
/* make a copy of the key */
struct doq_conn* conn;
struct doq_conn_key key = conid->key;
uint8_t cid[NGTCP2_MAX_CIDLEN];
log_assert(conid->key.dcidlen <= NGTCP2_MAX_CIDLEN);
memcpy(cid, conid->key.dcid, conid->key.dcidlen);
key.dcid = cid;
lock_rw_unlock(&table->conid_lock);
/* now that the conid lock is released, look up the conn */
lock_rw_rdlock(&table->lock);
conn = doq_conn_find(table, &key.paddr.addr,
key.paddr.addrlen, &key.paddr.localaddr,
key.paddr.localaddrlen, key.paddr.ifindex, key.dcid,
key.dcidlen);
if(!conn) {
/* The connection got deleted between the conid lookup
* and the connection lock grab, it no longer exists,
* so return null. */
lock_rw_unlock(&table->lock);
return NULL;
}
lock_basic_lock(&conn->lock);
if(conn->is_deleted) {
lock_rw_unlock(&table->lock);
lock_basic_unlock(&conn->lock);
return NULL;
}
lock_rw_unlock(&table->lock);
return conn;
}
lock_rw_unlock(&table->conid_lock);
return NULL;
}
/** Find the doq_conn, by addr or by connection id */
static struct doq_conn*
doq_conn_find_by_addr_or_cid(struct doq_table* table,
struct doq_pkt_addr* paddr, const uint8_t* dcid, size_t dcidlen)
{
struct doq_conn* conn;
lock_rw_rdlock(&table->lock);
conn = doq_conn_find(table, &paddr->addr, paddr->addrlen,
&paddr->localaddr, paddr->localaddrlen, paddr->ifindex,
dcid, dcidlen);
if(conn && conn->is_deleted) {
conn = NULL;
}
if(conn) {
lock_basic_lock(&conn->lock);
lock_rw_unlock(&table->lock);
verbose(VERB_ALGO, "doq: found connection by address, dcid");
} else {
lock_rw_unlock(&table->lock);
conn = doq_conn_find_by_id(table, dcid, dcidlen);
if(conn) {
verbose(VERB_ALGO, "doq: found connection by dcid");
}
}
return conn;
}
/** decode doq packet header, false on handled or failure, true to continue
* to process the packet */
static int
doq_decode_pkt_header_negotiate(struct comm_point* c,
struct doq_pkt_addr* paddr, struct doq_conn** conn)
{
#ifdef HAVE_STRUCT_NGTCP2_VERSION_CID
struct ngtcp2_version_cid vc;
#else
uint32_t version;
const uint8_t *dcid, *scid;
size_t dcidlen, scidlen;
#endif
int rv;
#ifdef HAVE_STRUCT_NGTCP2_VERSION_CID
rv = ngtcp2_pkt_decode_version_cid(&vc,
sldns_buffer_begin(c->doq_socket->pkt_buf),
sldns_buffer_limit(c->doq_socket->pkt_buf),
c->doq_socket->sv_scidlen);
#else
rv = ngtcp2_pkt_decode_version_cid(&version, &dcid, &dcidlen,
&scid, &scidlen, sldns_buffer_begin(c->doq_socket->pkt_buf),
sldns_buffer_limit(c->doq_socket->pkt_buf), c->doq_socket->sv_scidlen);
#endif
if(rv != 0) {
if(rv == NGTCP2_ERR_VERSION_NEGOTIATION) {
/* send the version negotiation */
doq_send_version_negotiation(c, paddr,
#ifdef HAVE_STRUCT_NGTCP2_VERSION_CID
vc.scid, vc.scidlen, vc.dcid, vc.dcidlen
#else
scid, scidlen, dcid, dcidlen
#endif
);
return 0;
}
verbose(VERB_ALGO, "doq: could not decode version "
"and CID from QUIC packet header: %s",
ngtcp2_strerror(rv));
return 0;
}
if(verbosity >= VERB_ALGO) {
verbose(VERB_ALGO, "ngtcp2_pkt_decode_version_cid packet has "
"QUIC protocol version %u", (unsigned)
#ifdef HAVE_STRUCT_NGTCP2_VERSION_CID
vc.
#endif
version
);
log_hex("dcid",
#ifdef HAVE_STRUCT_NGTCP2_VERSION_CID
(void*)vc.dcid, vc.dcidlen
#else
(void*)dcid, dcidlen
#endif
);
log_hex("scid",
#ifdef HAVE_STRUCT_NGTCP2_VERSION_CID
(void*)vc.scid, vc.scidlen
#else
(void*)scid, scidlen
#endif
);
}
*conn = doq_conn_find_by_addr_or_cid(c->doq_socket->table, paddr,
#ifdef HAVE_STRUCT_NGTCP2_VERSION_CID
vc.dcid, vc.dcidlen
#else
dcid, dcidlen
#endif
);
if(*conn)
(*conn)->doq_socket = c->doq_socket;
return 1;
}
/** fill cid structure with random data */
static void doq_cid_randfill(struct ngtcp2_cid* cid, size_t datalen,
struct ub_randstate* rnd)
{
uint8_t buf[32];
if(datalen > sizeof(buf))
datalen = sizeof(buf);
doq_fill_rand(rnd, buf, datalen);
ngtcp2_cid_init(cid, buf, datalen);
}
/** send retry packet for doq connection. */
static void
doq_send_retry(struct comm_point* c, struct doq_pkt_addr* paddr,
struct ngtcp2_pkt_hd* hd)
{
char host[256], port[32];
struct ngtcp2_cid scid;
uint8_t token[NGTCP2_CRYPTO_MAX_RETRY_TOKENLEN];
ngtcp2_tstamp ts;
ngtcp2_ssize tokenlen, ret;
if(!doq_print_addr_port(&paddr->addr, paddr->addrlen, host,
sizeof(host), port, sizeof(port))) {
log_err("doq_send_retry failed");
return;
}
verbose(VERB_ALGO, "doq: sending retry packet to %s %s", host, port);
/* the server chosen source connection ID */
scid.datalen = c->doq_socket->sv_scidlen;
doq_cid_randfill(&scid, scid.datalen, c->doq_socket->rnd);
ts = doq_get_timestamp_nanosec();
tokenlen = ngtcp2_crypto_generate_retry_token(token,
c->doq_socket->static_secret, c->doq_socket->static_secret_len,
hd->version, (void*)&paddr->addr, paddr->addrlen, &scid,
&hd->dcid, ts);
if(tokenlen < 0) {
log_err("ngtcp2_crypto_generate_retry_token failed: %s",
ngtcp2_strerror(tokenlen));
return;
}
sldns_buffer_clear(c->doq_socket->pkt_buf);
ret = ngtcp2_crypto_write_retry(sldns_buffer_begin(c->doq_socket->pkt_buf),
sldns_buffer_capacity(c->doq_socket->pkt_buf), hd->version,
&hd->scid, &scid, &hd->dcid, token, tokenlen);
if(ret < 0) {
log_err("ngtcp2_crypto_write_retry failed: %s",
ngtcp2_strerror(ret));
return;
}
sldns_buffer_set_position(c->doq_socket->pkt_buf, ret);
sldns_buffer_flip(c->doq_socket->pkt_buf);
doq_send_pkt(c, paddr, 0);
}
/** doq send stateless connection close */
static void
doq_send_stateless_connection_close(struct comm_point* c,
struct doq_pkt_addr* paddr, struct ngtcp2_pkt_hd* hd,
uint64_t error_code)
{
ngtcp2_ssize ret;
sldns_buffer_clear(c->doq_socket->pkt_buf);
ret = ngtcp2_crypto_write_connection_close(
sldns_buffer_begin(c->doq_socket->pkt_buf),
sldns_buffer_capacity(c->doq_socket->pkt_buf), hd->version, &hd->scid,
&hd->dcid, error_code, NULL, 0);
if(ret < 0) {
log_err("ngtcp2_crypto_write_connection_close failed: %s",
ngtcp2_strerror(ret));
return;
}
sldns_buffer_set_position(c->doq_socket->pkt_buf, ret);
sldns_buffer_flip(c->doq_socket->pkt_buf);
doq_send_pkt(c, paddr, 0);
}
/** doq verify retry token, false on failure */
static int
doq_verify_retry_token(struct comm_point* c, struct doq_pkt_addr* paddr,
struct ngtcp2_cid* ocid, struct ngtcp2_pkt_hd* hd)
{
char host[256], port[32];
ngtcp2_tstamp ts;
if(!doq_print_addr_port(&paddr->addr, paddr->addrlen, host,
sizeof(host), port, sizeof(port))) {
log_err("doq_verify_retry_token failed");
return 0;
}
ts = doq_get_timestamp_nanosec();
verbose(VERB_ALGO, "doq: verifying retry token from %s %s", host,
port);
if(ngtcp2_crypto_verify_retry_token(ocid,
#ifdef HAVE_STRUCT_NGTCP2_PKT_HD_TOKENLEN
hd->token, hd->tokenlen,
#else
hd->token.base, hd->token.len,
#endif
c->doq_socket->static_secret,
c->doq_socket->static_secret_len, hd->version,
(void*)&paddr->addr, paddr->addrlen, &hd->dcid,
10*NGTCP2_SECONDS, ts) != 0) {
verbose(VERB_ALGO, "doq: could not verify retry token "
"from %s %s", host, port);
return 0;
}
verbose(VERB_ALGO, "doq: verified retry token from %s %s", host, port);
return 1;
}
/** doq verify token, false on failure */
static int
doq_verify_token(struct comm_point* c, struct doq_pkt_addr* paddr,
struct ngtcp2_pkt_hd* hd)
{
char host[256], port[32];
ngtcp2_tstamp ts;
if(!doq_print_addr_port(&paddr->addr, paddr->addrlen, host,
sizeof(host), port, sizeof(port))) {
log_err("doq_verify_token failed");
return 0;
}
ts = doq_get_timestamp_nanosec();
verbose(VERB_ALGO, "doq: verifying token from %s %s", host, port);
if(ngtcp2_crypto_verify_regular_token(
#ifdef HAVE_STRUCT_NGTCP2_PKT_HD_TOKENLEN
hd->token, hd->tokenlen,
#else
hd->token.base, hd->token.len,
#endif
c->doq_socket->static_secret, c->doq_socket->static_secret_len,
(void*)&paddr->addr, paddr->addrlen, 3600*NGTCP2_SECONDS,
ts) != 0) {
verbose(VERB_ALGO, "doq: could not verify token from %s %s",
host, port);
return 0;
}
verbose(VERB_ALGO, "doq: verified token from %s %s", host, port);
return 1;
}
/** delete and remove from the lookup tree the doq_conn connection */
static void
doq_delete_connection(struct comm_point* c, struct doq_conn* conn)
{
struct doq_conn copy;
uint8_t cid[NGTCP2_MAX_CIDLEN];
rbnode_type* node;
if(!conn)
return;
/* Copy the key and set it deleted. */
conn->is_deleted = 1;
doq_conn_write_disable(conn);
copy.key = conn->key;
log_assert(conn->key.dcidlen <= NGTCP2_MAX_CIDLEN);
memcpy(cid, conn->key.dcid, conn->key.dcidlen);
copy.key.dcid = cid;
copy.node.key = ©
lock_basic_unlock(&conn->lock);
/* Now get the table lock to delete it from the tree */
lock_rw_wrlock(&c->doq_socket->table->lock);
node = rbtree_delete(c->doq_socket->table->conn_tree, copy.node.key);
if(node) {
conn = (struct doq_conn*)node->key;
lock_basic_lock(&conn->lock);
doq_conn_write_list_remove(c->doq_socket->table, conn);
if(conn->timer.timer_in_list) {
/* Remove timer from list first, because finding the
* rbnode element of the setlist of same timeouts
* needs tree lookup. Edit the tree structure after
* that lookup. */
doq_timer_list_remove(c->doq_socket->table,
&conn->timer);
}
if(conn->timer.timer_in_tree)
doq_timer_tree_remove(c->doq_socket->table,
&conn->timer);
}
lock_rw_unlock(&c->doq_socket->table->lock);
if(node) {
lock_basic_unlock(&conn->lock);
doq_table_quic_size_subtract(c->doq_socket->table,
sizeof(*conn)+conn->key.dcidlen);
doq_conn_delete(conn, c->doq_socket->table);
}
}
/** create and setup a new doq connection, to a new destination, or with
* a new dcid. It has a new set of streams. It is inserted in the lookup tree.
* Returns NULL on failure. */
static struct doq_conn*
doq_setup_new_conn(struct comm_point* c, struct doq_pkt_addr* paddr,
struct ngtcp2_pkt_hd* hd, struct ngtcp2_cid* ocid)
{
struct doq_conn* conn;
if(!doq_table_quic_size_available(c->doq_socket->table,
c->doq_socket->cfg, sizeof(*conn)+hd->dcid.datalen
+ sizeof(struct doq_stream)
+ 100 /* estimated input query */
+ 1200 /* estimated output query */)) {
verbose(VERB_ALGO, "doq: no mem available for new connection");
doq_send_stateless_connection_close(c, paddr, hd,
NGTCP2_CONNECTION_REFUSED);
return NULL;
}
conn = doq_conn_create(c, paddr, hd->dcid.data, hd->dcid.datalen,
hd->version);
if(!conn) {
log_err("doq: could not allocate doq_conn");
return NULL;
}
lock_rw_wrlock(&c->doq_socket->table->lock);
lock_basic_lock(&conn->lock);
if(!rbtree_insert(c->doq_socket->table->conn_tree, &conn->node)) {
lock_rw_unlock(&c->doq_socket->table->lock);
log_err("doq: duplicate connection");
/* conn has no entry in writelist, and no timer yet. */
lock_basic_unlock(&conn->lock);
doq_conn_delete(conn, c->doq_socket->table);
return NULL;
}
lock_rw_unlock(&c->doq_socket->table->lock);
doq_table_quic_size_add(c->doq_socket->table,
sizeof(*conn)+conn->key.dcidlen);
verbose(VERB_ALGO, "doq: created new connection");
/* the scid and dcid switch meaning from the accepted client
* connection to the server connection. The 'source' and 'destination'
* meaning is reversed. */
if(!doq_conn_setup(conn, hd->scid.data, hd->scid.datalen,
(ocid?ocid->data:NULL), (ocid?ocid->datalen:0),
#ifdef HAVE_STRUCT_NGTCP2_PKT_HD_TOKENLEN
hd->token, hd->tokenlen
#else
hd->token.base, hd->token.len
#endif
)) {
log_err("doq: could not set up connection");
doq_delete_connection(c, conn);
return NULL;
}
return conn;
}
/** perform doq address validation */
static int
doq_address_validation(struct comm_point* c, struct doq_pkt_addr* paddr,
struct ngtcp2_pkt_hd* hd, struct ngtcp2_cid* ocid,
struct ngtcp2_cid** pocid)
{
#ifdef HAVE_STRUCT_NGTCP2_PKT_HD_TOKENLEN
const uint8_t* token = hd->token;
size_t tokenlen = hd->tokenlen;
#else
const uint8_t* token = hd->token.base;
size_t tokenlen = hd->token.len;
#endif
verbose(VERB_ALGO, "doq stateless address validation");
if(tokenlen == 0 || token == NULL) {
doq_send_retry(c, paddr, hd);
return 0;
}
if(token[0] != NGTCP2_CRYPTO_TOKEN_MAGIC_RETRY &&
hd->dcid.datalen < NGTCP2_MIN_INITIAL_DCIDLEN) {
doq_send_stateless_connection_close(c, paddr, hd,
NGTCP2_INVALID_TOKEN);
return 0;
}
if(token[0] == NGTCP2_CRYPTO_TOKEN_MAGIC_RETRY) {
if(!doq_verify_retry_token(c, paddr, ocid, hd)) {
doq_send_stateless_connection_close(c, paddr, hd,
NGTCP2_INVALID_TOKEN);
return 0;
}
*pocid = ocid;
} else if(token[0] == NGTCP2_CRYPTO_TOKEN_MAGIC_REGULAR) {
if(!doq_verify_token(c, paddr, hd)) {
doq_send_retry(c, paddr, hd);
return 0;
}
#ifdef HAVE_STRUCT_NGTCP2_PKT_HD_TOKENLEN
hd->token = NULL;
hd->tokenlen = 0;
#else
hd->token.base = NULL;
hd->token.len = 0;
#endif
} else {
verbose(VERB_ALGO, "doq address validation: unrecognised "
"token in hd.token.base with magic byte 0x%2.2x",
(int)token[0]);
if(c->doq_socket->validate_addr) {
doq_send_retry(c, paddr, hd);
return 0;
}
#ifdef HAVE_STRUCT_NGTCP2_PKT_HD_TOKENLEN
hd->token = NULL;
hd->tokenlen = 0;
#else
hd->token.base = NULL;
hd->token.len = 0;
#endif
}
return 1;
}
/** the doq accept, returns false if no further processing of content */
static int
doq_accept(struct comm_point* c, struct doq_pkt_addr* paddr,
struct doq_conn** conn, struct ngtcp2_pkt_info* pi)
{
int rv;
struct ngtcp2_pkt_hd hd;
struct ngtcp2_cid ocid, *pocid=NULL;
int err_retry;
memset(&hd, 0, sizeof(hd));
rv = ngtcp2_accept(&hd, sldns_buffer_begin(c->doq_socket->pkt_buf),
sldns_buffer_limit(c->doq_socket->pkt_buf));
if(rv != 0) {
if(rv == NGTCP2_ERR_RETRY) {
doq_send_retry(c, paddr, &hd);
return 0;
}
log_err("doq: initial packet failed, ngtcp2_accept failed: %s",
ngtcp2_strerror(rv));
return 0;
}
if(c->doq_socket->validate_addr ||
#ifdef HAVE_STRUCT_NGTCP2_PKT_HD_TOKENLEN
hd.tokenlen
#else
hd.token.len
#endif
) {
if(!doq_address_validation(c, paddr, &hd, &ocid, &pocid))
return 0;
}
*conn = doq_setup_new_conn(c, paddr, &hd, pocid);
if(!*conn)
return 0;
(*conn)->doq_socket = c->doq_socket;
if(!doq_conn_recv(c, paddr, *conn, pi, &err_retry, NULL)) {
if(err_retry)
doq_send_retry(c, paddr, &hd);
doq_delete_connection(c, *conn);
*conn = NULL;
return 0;
}
return 1;
}
/** doq pickup a timer to wait for for the worker. If any timer exists. */
static void
doq_pickup_timer(struct comm_point* c)
{
struct doq_timer* t;
struct timeval tv;
int have_time = 0;
memset(&tv, 0, sizeof(tv));
lock_rw_wrlock(&c->doq_socket->table->lock);
RBTREE_FOR(t, struct doq_timer*, c->doq_socket->table->timer_tree) {
if(t->worker_doq_socket == NULL ||
t->worker_doq_socket == c->doq_socket) {
/* pick up this element */
t->worker_doq_socket = c->doq_socket;
have_time = 1;
memcpy(&tv, &t->time, sizeof(tv));
break;
}
}
lock_rw_unlock(&c->doq_socket->table->lock);
if(have_time) {
struct timeval rel;
timeval_subtract(&rel, &tv, c->doq_socket->now_tv);
comm_timer_set(c->doq_socket->timer, &rel);
memcpy(&c->doq_socket->marked_time, &tv,
sizeof(c->doq_socket->marked_time));
verbose(VERB_ALGO, "doq pickup timer at %d.%6.6d in %d.%6.6d",
(int)tv.tv_sec, (int)tv.tv_usec, (int)rel.tv_sec,
(int)rel.tv_usec);
} else {
if(comm_timer_is_set(c->doq_socket->timer))
comm_timer_disable(c->doq_socket->timer);
memset(&c->doq_socket->marked_time, 0,
sizeof(c->doq_socket->marked_time));
verbose(VERB_ALGO, "doq timer disabled");
}
}
/** doq done with connection, release locks and setup timer and write */
static void
doq_done_setup_timer_and_write(struct comm_point* c, struct doq_conn* conn)
{
struct doq_conn copy;
uint8_t cid[NGTCP2_MAX_CIDLEN];
rbnode_type* node;
struct timeval new_tv;
int write_change = 0, timer_change = 0;
/* No longer in callbacks, so the pointer to doq_socket is back
* to NULL. */
conn->doq_socket = NULL;
if(doq_conn_check_timer(conn, &new_tv))
timer_change = 1;
if( (conn->write_interest && !conn->on_write_list) ||
(!conn->write_interest && conn->on_write_list))
write_change = 1;
if(!timer_change && !write_change) {
/* Nothing to do. */
lock_basic_unlock(&conn->lock);
return;
}
/* The table lock is needed to change the write list and timer tree.
* So the connection lock is release and then the connection is
* looked up again. */
copy.key = conn->key;
log_assert(conn->key.dcidlen <= NGTCP2_MAX_CIDLEN);
memcpy(cid, conn->key.dcid, conn->key.dcidlen);
copy.key.dcid = cid;
copy.node.key = ©
lock_basic_unlock(&conn->lock);
lock_rw_wrlock(&c->doq_socket->table->lock);
node = rbtree_search(c->doq_socket->table->conn_tree, copy.node.key);
if(!node) {
lock_rw_unlock(&c->doq_socket->table->lock);
/* Must have been deleted in the mean time. */
return;
}
conn = (struct doq_conn*)node->key;
lock_basic_lock(&conn->lock);
if(conn->is_deleted) {
/* It is deleted now. */
lock_rw_unlock(&c->doq_socket->table->lock);
lock_basic_unlock(&conn->lock);
return;
}
if(write_change) {
/* Edit the write lists, we are holding the table.lock and can
* edit the list first,last and also prev,next and on_list
* elements in the doq_conn structures. */
doq_conn_set_write_list(c->doq_socket->table, conn);
}
if(timer_change) {
doq_timer_set(c->doq_socket->table, &conn->timer,
c->doq_socket, &new_tv);
}
lock_rw_unlock(&c->doq_socket->table->lock);
lock_basic_unlock(&conn->lock);
}
/** doq done with connection callbacks, release locks and setup write */
static void
doq_done_with_conn_cb(struct comm_point* c, struct doq_conn* conn)
{
struct doq_conn copy;
uint8_t cid[NGTCP2_MAX_CIDLEN];
rbnode_type* node;
/* no longer in callbacks, so the pointer to doq_socket is back
* to NULL. */
conn->doq_socket = NULL;
if( (conn->write_interest && conn->on_write_list) ||
(!conn->write_interest && !conn->on_write_list)) {
/* The connection already has the required write list
* status. */
lock_basic_unlock(&conn->lock);
return;
}
/* To edit the write list of connections we have to hold the table
* lock, so we release the connection and then look it up again. */
copy.key = conn->key;
log_assert(conn->key.dcidlen <= NGTCP2_MAX_CIDLEN);
memcpy(cid, conn->key.dcid, conn->key.dcidlen);
copy.key.dcid = cid;
copy.node.key = ©
lock_basic_unlock(&conn->lock);
lock_rw_wrlock(&c->doq_socket->table->lock);
node = rbtree_search(c->doq_socket->table->conn_tree, copy.node.key);
if(!node) {
lock_rw_unlock(&c->doq_socket->table->lock);
/* must have been deleted in the mean time */
return;
}
conn = (struct doq_conn*)node->key;
lock_basic_lock(&conn->lock);
if(conn->is_deleted) {
/* it is deleted now. */
lock_rw_unlock(&c->doq_socket->table->lock);
lock_basic_unlock(&conn->lock);
return;
}
/* edit the write lists, we are holding the table.lock and can
* edit the list first,last and also prev,next and on_list elements
* in the doq_conn structures. */
doq_conn_set_write_list(c->doq_socket->table, conn);
lock_rw_unlock(&c->doq_socket->table->lock);
lock_basic_unlock(&conn->lock);
}
/** doq count the length of the write list */
static size_t
doq_write_list_length(struct comm_point* c)
{
size_t count = 0;
struct doq_conn* conn;
lock_rw_rdlock(&c->doq_socket->table->lock);
conn = c->doq_socket->table->write_list_first;
while(conn) {
count++;
conn = conn->write_next;
}
lock_rw_unlock(&c->doq_socket->table->lock);
return count;
}
/** doq pop the first element from the write list to have write events */
static struct doq_conn*
doq_pop_write_conn(struct comm_point* c)
{
struct doq_conn* conn;
lock_rw_wrlock(&c->doq_socket->table->lock);
conn = doq_table_pop_first(c->doq_socket->table);
while(conn && conn->is_deleted) {
lock_basic_unlock(&conn->lock);
conn = doq_table_pop_first(c->doq_socket->table);
}
lock_rw_unlock(&c->doq_socket->table->lock);
if(conn)
conn->doq_socket = c->doq_socket;
return conn;
}
/** doq the connection is done with write callbacks, release it. */
static void
doq_done_with_write_cb(struct comm_point* c, struct doq_conn* conn,
int delete_it)
{
if(delete_it) {
doq_delete_connection(c, conn);
return;
}
doq_done_setup_timer_and_write(c, conn);
}
/** see if the doq socket wants to write packets */
static int
doq_socket_want_write(struct comm_point* c)
{
int want_write = 0;
if(c->doq_socket->have_blocked_pkt)
return 1;
lock_rw_rdlock(&c->doq_socket->table->lock);
if(c->doq_socket->table->write_list_first)
want_write = 1;
lock_rw_unlock(&c->doq_socket->table->lock);
return want_write;
}
/** enable write event for the doq server socket fd */
static void
doq_socket_write_enable(struct comm_point* c)
{
verbose(VERB_ALGO, "doq socket want write");
if(c->doq_socket->event_has_write)
return;
comm_point_listen_for_rw(c, 1, 1);
c->doq_socket->event_has_write = 1;
}
/** disable write event for the doq server socket fd */
static void
doq_socket_write_disable(struct comm_point* c)
{
verbose(VERB_ALGO, "doq socket want no write");
if(!c->doq_socket->event_has_write)
return;
comm_point_listen_for_rw(c, 1, 0);
c->doq_socket->event_has_write = 0;
}
/** write blocked packet, if possible. returns false if failed, again. */
static int
doq_write_blocked_pkt(struct comm_point* c)
{
struct doq_pkt_addr paddr;
if(!c->doq_socket->have_blocked_pkt)
return 1;
c->doq_socket->have_blocked_pkt = 0;
if(sldns_buffer_limit(c->doq_socket->blocked_pkt) >
sldns_buffer_remaining(c->doq_socket->pkt_buf))
return 1; /* impossibly large, drop it.
impossible since pkt_buf is same size as blocked_pkt buf. */
sldns_buffer_clear(c->doq_socket->pkt_buf);
sldns_buffer_write(c->doq_socket->pkt_buf,
sldns_buffer_begin(c->doq_socket->blocked_pkt),
sldns_buffer_limit(c->doq_socket->blocked_pkt));
sldns_buffer_flip(c->doq_socket->pkt_buf);
memcpy(&paddr, c->doq_socket->blocked_paddr, sizeof(paddr));
doq_send_pkt(c, &paddr, c->doq_socket->blocked_pkt_pi.ecn);
if(c->doq_socket->have_blocked_pkt)
return 0;
return 1;
}
/** doq find a timer that timeouted and return the conn, locked. */
static struct doq_conn*
doq_timer_timeout_conn(struct doq_server_socket* doq_socket)
{
struct doq_conn* conn = NULL;
struct rbnode_type* node;
lock_rw_wrlock(&doq_socket->table->lock);
node = rbtree_first(doq_socket->table->timer_tree);
if(node && node != RBTREE_NULL) {
struct doq_timer* t = (struct doq_timer*)node;
conn = t->conn;
/* If now < timer then no further timeouts in tree. */
if(timeval_smaller(doq_socket->now_tv, &t->time)) {
lock_rw_unlock(&doq_socket->table->lock);
return NULL;
}
lock_basic_lock(&conn->lock);
conn->doq_socket = doq_socket;
/* Now that the timer is fired, remove it. */
doq_timer_unset(doq_socket->table, t);
lock_rw_unlock(&doq_socket->table->lock);
return conn;
}
lock_rw_unlock(&doq_socket->table->lock);
return NULL;
}
/** doq timer erase the marker that said which timer the worker uses. */
static void
doq_timer_erase_marker(struct doq_server_socket* doq_socket)
{
struct doq_timer* t;
lock_rw_wrlock(&doq_socket->table->lock);
t = doq_timer_find_time(doq_socket->table, &doq_socket->marked_time);
if(t && t->worker_doq_socket == doq_socket)
t->worker_doq_socket = NULL;
lock_rw_unlock(&doq_socket->table->lock);
memset(&doq_socket->marked_time, 0, sizeof(doq_socket->marked_time));
}
void
doq_timer_cb(void* arg)
{
struct doq_server_socket* doq_socket = (struct doq_server_socket*)arg;
struct doq_conn* conn;
verbose(VERB_ALGO, "doq timer callback");
doq_timer_erase_marker(doq_socket);
while((conn = doq_timer_timeout_conn(doq_socket)) != NULL) {
if(conn->is_deleted ||
#ifdef HAVE_NGTCP2_CONN_IN_CLOSING_PERIOD
ngtcp2_conn_in_closing_period(conn->conn) ||
#else
ngtcp2_conn_is_in_closing_period(conn->conn) ||
#endif
#ifdef HAVE_NGTCP2_CONN_IN_DRAINING_PERIOD
ngtcp2_conn_in_draining_period(conn->conn)
#else
ngtcp2_conn_is_in_draining_period(conn->conn)
#endif
) {
if(verbosity >= VERB_ALGO) {
char remotestr[256];
addr_to_str((void*)&conn->key.paddr.addr,
conn->key.paddr.addrlen, remotestr,
sizeof(remotestr));
verbose(VERB_ALGO, "doq conn %s is deleted "
"after timeout", remotestr);
}
doq_delete_connection(doq_socket->cp, conn);
continue;
}
if(!doq_conn_handle_timeout(conn))
doq_delete_connection(doq_socket->cp, conn);
else doq_done_setup_timer_and_write(doq_socket->cp, conn);
}
if(doq_socket_want_write(doq_socket->cp))
doq_socket_write_enable(doq_socket->cp);
else doq_socket_write_disable(doq_socket->cp);
doq_pickup_timer(doq_socket->cp);
}
void
comm_point_doq_callback(int fd, short event, void* arg)
{
struct comm_point* c;
struct doq_pkt_addr paddr;
int i, pkt_continue, err_drop;
struct doq_conn* conn;
struct ngtcp2_pkt_info pi;
size_t count, num_len;
c = (struct comm_point*)arg;
log_assert(c->type == comm_doq);
log_assert(c && c->doq_socket->pkt_buf && c->fd == fd);
ub_comm_base_now(c->ev->base);
/* see if there is a blocked packet, and send that if possible.
* do not attempt to read yet, even if possible, that would just
* push more answers in reply to those read packets onto the list
* of written replies. First attempt to clear the write content out.
* That keeps the memory usage from bloating up. */
if(c->doq_socket->have_blocked_pkt) {
if(!doq_write_blocked_pkt(c)) {
/* this write has also blocked, attempt to write
* later. Make sure the event listens to write
* events. */
if(!c->doq_socket->event_has_write)
doq_socket_write_enable(c);
doq_pickup_timer(c);
return;
}
}
/* see if there is write interest */
count = 0;
num_len = doq_write_list_length(c);
while((conn = doq_pop_write_conn(c)) != NULL) {
if(conn->is_deleted ||
#ifdef HAVE_NGTCP2_CONN_IN_CLOSING_PERIOD
ngtcp2_conn_in_closing_period(conn->conn) ||
#else
ngtcp2_conn_is_in_closing_period(conn->conn) ||
#endif
#ifdef HAVE_NGTCP2_CONN_IN_DRAINING_PERIOD
ngtcp2_conn_in_draining_period(conn->conn)
#else
ngtcp2_conn_is_in_draining_period(conn->conn)
#endif
) {
conn->doq_socket = NULL;
lock_basic_unlock(&conn->lock);
if(c->doq_socket->have_blocked_pkt) {
if(!c->doq_socket->event_has_write)
doq_socket_write_enable(c);
doq_pickup_timer(c);
return;
}
if(++count > num_len*2)
break;
continue;
}
if(verbosity >= VERB_ALGO) {
char remotestr[256];
addr_to_str((void*)&conn->key.paddr.addr,
conn->key.paddr.addrlen, remotestr,
sizeof(remotestr));
verbose(VERB_ALGO, "doq write connection %s %d",
remotestr, doq_sockaddr_get_port(
&conn->key.paddr.addr));
}
if(doq_conn_write_streams(c, conn, &err_drop))
err_drop = 0;
doq_done_with_write_cb(c, conn, err_drop);
if(c->doq_socket->have_blocked_pkt) {
if(!c->doq_socket->event_has_write)
doq_socket_write_enable(c);
doq_pickup_timer(c);
return;
}
/* Stop overly long write lists that are created
* while we are processing. Do those next time there
* is a write callback. Stops long loops, and keeps
* fair for other events. */
if(++count > num_len*2)
break;
}
/* check for data to read */
if((event&UB_EV_READ)!=0)
for(i=0; i<NUM_UDP_PER_SELECT; i++) {
/* there may be a blocked write packet and if so, stop
* reading because the reply cannot get written. The
* blocked packet could be written during the conn_recv
* handling of replies, or for a connection close. */
if(c->doq_socket->have_blocked_pkt) {
if(!c->doq_socket->event_has_write)
doq_socket_write_enable(c);
doq_pickup_timer(c);
return;
}
sldns_buffer_clear(c->doq_socket->pkt_buf);
doq_pkt_addr_init(&paddr);
log_assert(fd != -1);
log_assert(sldns_buffer_remaining(c->doq_socket->pkt_buf) > 0);
if(!doq_recv(c, &paddr, &pkt_continue, &pi)) {
if(pkt_continue)
continue;
break;
}
/* handle incoming packet from remote addr to localaddr */
if(verbosity >= VERB_ALGO) {
char remotestr[256], localstr[256];
addr_to_str((void*)&paddr.addr, paddr.addrlen,
remotestr, sizeof(remotestr));
addr_to_str((void*)&paddr.localaddr,
paddr.localaddrlen, localstr,
sizeof(localstr));
log_info("incoming doq packet from %s port %d on "
"%s port %d ifindex %d",
remotestr, doq_sockaddr_get_port(&paddr.addr),
localstr,
doq_sockaddr_get_port(&paddr.localaddr),
paddr.ifindex);
log_info("doq_recv length %d ecn 0x%x",
(int)sldns_buffer_limit(c->doq_socket->pkt_buf),
(int)pi.ecn);
}
if(sldns_buffer_limit(c->doq_socket->pkt_buf) == 0)
continue;
conn = NULL;
if(!doq_decode_pkt_header_negotiate(c, &paddr, &conn))
continue;
if(!conn) {
if(!doq_accept(c, &paddr, &conn, &pi))
continue;
if(!doq_conn_write_streams(c, conn, NULL)) {
doq_delete_connection(c, conn);
continue;
}
doq_done_setup_timer_and_write(c, conn);
continue;
}
if(
#ifdef HAVE_NGTCP2_CONN_IN_CLOSING_PERIOD
ngtcp2_conn_in_closing_period(conn->conn)
#else
ngtcp2_conn_is_in_closing_period(conn->conn)
#endif
) {
if(!doq_conn_send_close(c, conn)) {
doq_delete_connection(c, conn);
} else {
doq_done_setup_timer_and_write(c, conn);
}
continue;
}
if(
#ifdef HAVE_NGTCP2_CONN_IN_DRAINING_PERIOD
ngtcp2_conn_in_draining_period(conn->conn)
#else
ngtcp2_conn_is_in_draining_period(conn->conn)
#endif
) {
doq_done_setup_timer_and_write(c, conn);
continue;
}
if(!doq_conn_recv(c, &paddr, conn, &pi, NULL, &err_drop)) {
/* The receive failed, and if it also failed to send
* a close, drop the connection. That means it is not
* in the closing period. */
if(err_drop) {
doq_delete_connection(c, conn);
} else {
doq_done_setup_timer_and_write(c, conn);
}
continue;
}
if(!doq_conn_write_streams(c, conn, &err_drop)) {
if(err_drop) {
doq_delete_connection(c, conn);
} else {
doq_done_setup_timer_and_write(c, conn);
}
continue;
}
doq_done_setup_timer_and_write(c, conn);
}
/* see if we want to have more write events */
verbose(VERB_ALGO, "doq check write enable");
if(doq_socket_want_write(c))
doq_socket_write_enable(c);
else doq_socket_write_disable(c);
doq_pickup_timer(c);
}
/** create new doq server socket structure */
static struct doq_server_socket*
doq_server_socket_create(struct doq_table* table, struct ub_randstate* rnd,
const char* ssl_service_key, const char* ssl_service_pem,
struct comm_point* c, struct comm_base* base, struct config_file* cfg)
{
size_t doq_buffer_size = 4096; /* bytes buffer size, for one packet. */
struct doq_server_socket* doq_socket;
doq_socket = calloc(1, sizeof(*doq_socket));
if(!doq_socket) {
return NULL;
}
doq_socket->table = table;
doq_socket->rnd = rnd;
doq_socket->validate_addr = 1;
if(ssl_service_key == NULL || ssl_service_key[0]==0) {
log_err("doq server socket create: no tls-service-key");
free(doq_socket);
return NULL;
}
if(ssl_service_pem == NULL || ssl_service_pem[0]==0) {
log_err("doq server socket create: no tls-service-pem");
free(doq_socket);
return NULL;
}
doq_socket->ssl_service_key = strdup(ssl_service_key);
if(!doq_socket->ssl_service_key) {
free(doq_socket);
return NULL;
}
doq_socket->ssl_service_pem = strdup(ssl_service_pem);
if(!doq_socket->ssl_service_pem) {
free(doq_socket->ssl_service_key);
free(doq_socket);
return NULL;
}
doq_socket->ssl_verify_pem = NULL;
/* the doq_socket has its own copy of the static secret, as
* well as other config values, so that they do not need table.lock */
doq_socket->static_secret_len = table->static_secret_len;
doq_socket->static_secret = memdup(table->static_secret,
table->static_secret_len);
if(!doq_socket->static_secret) {
free(doq_socket->ssl_service_key);
free(doq_socket->ssl_service_pem);
free(doq_socket->ssl_verify_pem);
free(doq_socket);
return NULL;
}
if(!doq_socket_setup_ctx(doq_socket)) {
free(doq_socket->ssl_service_key);
free(doq_socket->ssl_service_pem);
free(doq_socket->ssl_verify_pem);
free(doq_socket->static_secret);
free(doq_socket);
return NULL;
}
doq_socket->idle_timeout = table->idle_timeout;
doq_socket->sv_scidlen = table->sv_scidlen;
doq_socket->cp = c;
doq_socket->pkt_buf = sldns_buffer_new(doq_buffer_size);
if(!doq_socket->pkt_buf) {
free(doq_socket->ssl_service_key);
free(doq_socket->ssl_service_pem);
free(doq_socket->ssl_verify_pem);
free(doq_socket->static_secret);
SSL_CTX_free(doq_socket->ctx);
free(doq_socket);
return NULL;
}
doq_socket->blocked_pkt = sldns_buffer_new(
sldns_buffer_capacity(doq_socket->pkt_buf));
if(!doq_socket->pkt_buf) {
free(doq_socket->ssl_service_key);
free(doq_socket->ssl_service_pem);
free(doq_socket->ssl_verify_pem);
free(doq_socket->static_secret);
SSL_CTX_free(doq_socket->ctx);
sldns_buffer_free(doq_socket->pkt_buf);
free(doq_socket);
return NULL;
}
doq_socket->blocked_paddr = calloc(1,
sizeof(*doq_socket->blocked_paddr));
if(!doq_socket->blocked_paddr) {
free(doq_socket->ssl_service_key);
free(doq_socket->ssl_service_pem);
free(doq_socket->ssl_verify_pem);
free(doq_socket->static_secret);
SSL_CTX_free(doq_socket->ctx);
sldns_buffer_free(doq_socket->pkt_buf);
sldns_buffer_free(doq_socket->blocked_pkt);
free(doq_socket);
return NULL;
}
doq_socket->timer = comm_timer_create(base, doq_timer_cb, doq_socket);
if(!doq_socket->timer) {
free(doq_socket->ssl_service_key);
free(doq_socket->ssl_service_pem);
free(doq_socket->ssl_verify_pem);
free(doq_socket->static_secret);
SSL_CTX_free(doq_socket->ctx);
sldns_buffer_free(doq_socket->pkt_buf);
sldns_buffer_free(doq_socket->blocked_pkt);
free(doq_socket->blocked_paddr);
free(doq_socket);
return NULL;
}
memset(&doq_socket->marked_time, 0, sizeof(doq_socket->marked_time));
comm_base_timept(base, &doq_socket->now_tt, &doq_socket->now_tv);
doq_socket->cfg = cfg;
return doq_socket;
}
/** delete doq server socket structure */
static void
doq_server_socket_delete(struct doq_server_socket* doq_socket)
{
if(!doq_socket)
return;
free(doq_socket->static_secret);
SSL_CTX_free(doq_socket->ctx);
#ifndef HAVE_NGTCP2_CRYPTO_QUICTLS_CONFIGURE_SERVER_CONTEXT
free(doq_socket->quic_method);
#endif
free(doq_socket->ssl_service_key);
free(doq_socket->ssl_service_pem);
free(doq_socket->ssl_verify_pem);
sldns_buffer_free(doq_socket->pkt_buf);
sldns_buffer_free(doq_socket->blocked_pkt);
free(doq_socket->blocked_paddr);
comm_timer_delete(doq_socket->timer);
free(doq_socket);
}
/** find repinfo in the doq table */
static struct doq_conn*
doq_lookup_repinfo(struct doq_table* table, struct comm_reply* repinfo)
{
struct doq_conn* conn;
struct doq_conn_key key;
doq_conn_key_from_repinfo(&key, repinfo);
lock_rw_rdlock(&table->lock);
conn = doq_conn_find(table, &key.paddr.addr,
key.paddr.addrlen, &key.paddr.localaddr,
key.paddr.localaddrlen, key.paddr.ifindex, key.dcid,
key.dcidlen);
if(conn) {
lock_basic_lock(&conn->lock);
lock_rw_unlock(&table->lock);
return conn;
}
lock_rw_unlock(&table->lock);
return NULL;
}
/** doq find connection and stream. From inside callbacks from worker. */
static int
doq_lookup_conn_stream(struct comm_reply* repinfo, struct comm_point* c,
struct doq_conn** conn, struct doq_stream** stream)
{
if(c->doq_socket->current_conn) {
*conn = c->doq_socket->current_conn;
} else {
*conn = doq_lookup_repinfo(c->doq_socket->table, repinfo);
if((*conn) && (*conn)->is_deleted) {
lock_basic_unlock(&(*conn)->lock);
*conn = NULL;
}
if(*conn) {
(*conn)->doq_socket = c->doq_socket;
}
}
if(!*conn) {
*stream = NULL;
return 0;
}
*stream = doq_stream_find(*conn, repinfo->doq_streamid);
if(!*stream) {
if(!c->doq_socket->current_conn) {
/* Not inside callbacks, we have our own lock on conn.
* Release it. */
lock_basic_unlock(&(*conn)->lock);
}
return 0;
}
if((*stream)->is_closed) {
/* stream is closed, ignore reply or drop */
if(!c->doq_socket->current_conn) {
/* Not inside callbacks, we have our own lock on conn.
* Release it. */
lock_basic_unlock(&(*conn)->lock);
}
return 0;
}
return 1;
}
/** doq send a reply from a comm reply */
static void
doq_socket_send_reply(struct comm_reply* repinfo)
{
struct doq_conn* conn;
struct doq_stream* stream;
log_assert(repinfo->c->type == comm_doq);
if(!doq_lookup_conn_stream(repinfo, repinfo->c, &conn, &stream)) {
verbose(VERB_ALGO, "doq: send_reply but %s is gone",
(conn?"stream":"connection"));
/* No stream, it may have been closed. */
/* Drop the reply, it cannot be sent. */
return;
}
if(!doq_stream_send_reply(conn, stream, repinfo->c->buffer))
doq_stream_close(conn, stream, 1);
if(!repinfo->c->doq_socket->current_conn) {
/* Not inside callbacks, we have our own lock on conn.
* Release it. */
doq_done_with_conn_cb(repinfo->c, conn);
/* since we sent a reply, or closed it, the assumption is
* that there is something to write, so enable write event.
* It waits until the write event happens to write the
* streams with answers, this allows some answers to be
* answered before the event loop reaches the doq fd, in
* repinfo->c->fd, and that collates answers. That would
* not happen if we write doq packets right now. */
doq_socket_write_enable(repinfo->c);
}
}
/** doq drop a reply from a comm reply */
static void
doq_socket_drop_reply(struct comm_reply* repinfo)
{
struct doq_conn* conn;
struct doq_stream* stream;
log_assert(repinfo->c->type == comm_doq);
if(!doq_lookup_conn_stream(repinfo, repinfo->c, &conn, &stream)) {
verbose(VERB_ALGO, "doq: drop_reply but %s is gone",
(conn?"stream":"connection"));
/* The connection or stream is already gone. */
return;
}
doq_stream_close(conn, stream, 1);
if(!repinfo->c->doq_socket->current_conn) {
/* Not inside callbacks, we have our own lock on conn.
* Release it. */
doq_done_with_conn_cb(repinfo->c, conn);
doq_socket_write_enable(repinfo->c);
}
}
#endif /* HAVE_NGTCP2 */
int adjusted_tcp_timeout(struct comm_point* c)
{
if(c->tcp_timeout_msec < TCP_QUERY_TIMEOUT_MINIMUM)
return TCP_QUERY_TIMEOUT_MINIMUM;
return c->tcp_timeout_msec;
}
/** Use a new tcp handler for new query fd, set to read query */
static void
setup_tcp_handler(struct comm_point* c, int fd, int cur, int max)
{
int handler_usage;
log_assert(c->type == comm_tcp || c->type == comm_http);
log_assert(c->fd == -1);
sldns_buffer_clear(c->buffer);
#ifdef USE_DNSCRYPT
if (c->dnscrypt)
sldns_buffer_clear(c->dnscrypt_buffer);
#endif
c->tcp_is_reading = 1;
c->tcp_byte_count = 0;
c->tcp_keepalive = 0;
/* if more than half the tcp handlers are in use, use a shorter
* timeout for this TCP connection, we need to make space for
* other connections to be able to get attention */
/* If > 50% TCP handler structures in use, set timeout to 1/100th
* configured value.
* If > 65%TCP handler structures in use, set to 1/500th configured
* value.
* If > 80% TCP handler structures in use, set to 0.
*
* If the timeout to use falls below 200 milliseconds, an actual
* timeout of 200ms is used.
*/
handler_usage = (cur * 100) / max;
if(handler_usage > 50 && handler_usage <= 65)
c->tcp_timeout_msec /= 100;
else if (handler_usage > 65 && handler_usage <= 80)
c->tcp_timeout_msec /= 500;
else if (handler_usage > 80)
c->tcp_timeout_msec = 0;
comm_point_start_listening(c, fd, adjusted_tcp_timeout(c));
}
void comm_base_handle_slow_accept(int ATTR_UNUSED(fd),
short ATTR_UNUSED(event), void* arg)
{
struct comm_base* b = (struct comm_base*)arg;
/* timeout for the slow accept, re-enable accepts again */
if(b->start_accept) {
verbose(VERB_ALGO, "wait is over, slow accept disabled");
fptr_ok(fptr_whitelist_start_accept(b->start_accept));
(*b->start_accept)(b->cb_arg);
b->eb->slow_accept_enabled = 0;
}
}
int comm_point_perform_accept(struct comm_point* c,
struct sockaddr_storage* addr, socklen_t* addrlen)
{
int new_fd;
*addrlen = (socklen_t)sizeof(*addr);
#ifndef HAVE_ACCEPT4
new_fd = accept(c->fd, (struct sockaddr*)addr, addrlen);
#else
/* SOCK_NONBLOCK saves extra calls to fcntl for the same result */
new_fd = accept4(c->fd, (struct sockaddr*)addr, addrlen, SOCK_NONBLOCK);
#endif
if(new_fd == -1) {
#ifndef USE_WINSOCK
/* EINTR is signal interrupt. others are closed connection. */
if( errno == EINTR || errno == EAGAIN
#ifdef EWOULDBLOCK
|| errno == EWOULDBLOCK
#endif
#ifdef ECONNABORTED
|| errno == ECONNABORTED
#endif
#ifdef EPROTO
|| errno == EPROTO
#endif /* EPROTO */
)
return -1;
#if defined(ENFILE) && defined(EMFILE)
if(errno == ENFILE || errno == EMFILE) {
/* out of file descriptors, likely outside of our
* control. stop accept() calls for some time */
if(c->ev->base->stop_accept) {
struct comm_base* b = c->ev->base;
struct timeval tv;
verbose(VERB_ALGO, "out of file descriptors: "
"slow accept");
ub_comm_base_now(b);
if(b->eb->last_slow_log+SLOW_LOG_TIME <=
b->eb->secs) {
b->eb->last_slow_log = b->eb->secs;
verbose(VERB_OPS, "accept failed, "
"slow down accept for %d "
"msec: %s",
NETEVENT_SLOW_ACCEPT_TIME,
sock_strerror(errno));
}
b->eb->slow_accept_enabled = 1;
fptr_ok(fptr_whitelist_stop_accept(
b->stop_accept));
(*b->stop_accept)(b->cb_arg);
/* set timeout, no mallocs */
tv.tv_sec = NETEVENT_SLOW_ACCEPT_TIME/1000;
tv.tv_usec = (NETEVENT_SLOW_ACCEPT_TIME%1000)*1000;
b->eb->slow_accept = ub_event_new(b->eb->base,
-1, UB_EV_TIMEOUT,
comm_base_handle_slow_accept, b);
if(b->eb->slow_accept == NULL) {
/* we do not want to log here, because
* that would spam the logfiles.
* error: "event_base_set failed." */
}
else if(ub_event_add(b->eb->slow_accept, &tv)
!= 0) {
/* we do not want to log here,
* error: "event_add failed." */
}
} else {
log_err("accept, with no slow down, "
"failed: %s", sock_strerror(errno));
}
return -1;
}
#endif
#else /* USE_WINSOCK */
if(WSAGetLastError() == WSAEINPROGRESS ||
WSAGetLastError() == WSAECONNRESET)
return -1;
if(WSAGetLastError() == WSAEWOULDBLOCK) {
ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
return -1;
}
#endif
log_err_addr("accept failed", sock_strerror(errno), addr,
*addrlen);
return -1;
}
if(c->tcp_conn_limit && c->type == comm_tcp_accept) {
c->tcl_addr = tcl_addr_lookup(c->tcp_conn_limit, addr, *addrlen);
if(!tcl_new_connection(c->tcl_addr)) {
if(verbosity >= 3)
log_err_addr("accept rejected",
"connection limit exceeded", addr, *addrlen);
close(new_fd);
return -1;
}
}
#ifndef HAVE_ACCEPT4
fd_set_nonblock(new_fd);
#endif
return new_fd;
}
#ifdef USE_WINSOCK
static long win_bio_cb(BIO *b, int oper, const char* ATTR_UNUSED(argp),
#ifdef HAVE_BIO_SET_CALLBACK_EX
size_t ATTR_UNUSED(len),
#endif
int ATTR_UNUSED(argi), long argl,
#ifndef HAVE_BIO_SET_CALLBACK_EX
long retvalue
#else
int retvalue, size_t* ATTR_UNUSED(processed)
#endif
)
{
int wsa_err = WSAGetLastError(); /* store errcode before it is gone */
verbose(VERB_ALGO, "bio_cb %d, %s %s %s", oper,
(oper&BIO_CB_RETURN)?"return":"before",
(oper&BIO_CB_READ)?"read":((oper&BIO_CB_WRITE)?"write":"other"),
wsa_err==WSAEWOULDBLOCK?"wsawb":"");
/* on windows, check if previous operation caused EWOULDBLOCK */
if( (oper == (BIO_CB_READ|BIO_CB_RETURN) && argl == 0) ||
(oper == (BIO_CB_GETS|BIO_CB_RETURN) && argl == 0)) {
if(wsa_err == WSAEWOULDBLOCK)
ub_winsock_tcp_wouldblock((struct ub_event*)
BIO_get_callback_arg(b), UB_EV_READ);
}
if( (oper == (BIO_CB_WRITE|BIO_CB_RETURN) && argl == 0) ||
(oper == (BIO_CB_PUTS|BIO_CB_RETURN) && argl == 0)) {
if(wsa_err == WSAEWOULDBLOCK)
ub_winsock_tcp_wouldblock((struct ub_event*)
BIO_get_callback_arg(b), UB_EV_WRITE);
}
/* return original return value */
return retvalue;
}
/** set win bio callbacks for nonblocking operations */
void
comm_point_tcp_win_bio_cb(struct comm_point* c, void* thessl)
{
SSL* ssl = (SSL*)thessl;
/* set them both just in case, but usually they are the same BIO */
#ifdef HAVE_BIO_SET_CALLBACK_EX
BIO_set_callback_ex(SSL_get_rbio(ssl), &win_bio_cb);
#else
BIO_set_callback(SSL_get_rbio(ssl), &win_bio_cb);
#endif
BIO_set_callback_arg(SSL_get_rbio(ssl), (char*)c->ev->ev);
#ifdef HAVE_BIO_SET_CALLBACK_EX
BIO_set_callback_ex(SSL_get_wbio(ssl), &win_bio_cb);
#else
BIO_set_callback(SSL_get_wbio(ssl), &win_bio_cb);
#endif
BIO_set_callback_arg(SSL_get_wbio(ssl), (char*)c->ev->ev);
}
#endif
#ifdef HAVE_NGHTTP2
/** Create http2 session server. Per connection, after TCP accepted.*/
static int http2_session_server_create(struct http2_session* h2_session)
{
log_assert(h2_session->callbacks);
h2_session->is_drop = 0;
if(nghttp2_session_server_new(&h2_session->session,
h2_session->callbacks,
h2_session) == NGHTTP2_ERR_NOMEM) {
log_err("failed to create nghttp2 session server");
return 0;
}
return 1;
}
/** Submit http2 setting to session. Once per session. */
static int http2_submit_settings(struct http2_session* h2_session)
{
int ret;
nghttp2_settings_entry settings[1] = {
{NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS,
h2_session->c->http2_max_streams}};
ret = nghttp2_submit_settings(h2_session->session, NGHTTP2_FLAG_NONE,
settings, 1);
if(ret) {
verbose(VERB_QUERY, "http2: submit_settings failed, "
"error: %s", nghttp2_strerror(ret));
return 0;
}
return 1;
}
#endif /* HAVE_NGHTTP2 */
void
comm_point_tcp_accept_callback(int fd, short event, void* arg)
{
struct comm_point* c = (struct comm_point*)arg, *c_hdl;
int new_fd;
log_assert(c->type == comm_tcp_accept);
if(!(event & UB_EV_READ)) {
log_info("ignoring tcp accept event %d", (int)event);
return;
}
ub_comm_base_now(c->ev->base);
/* find free tcp handler. */
if(!c->tcp_free) {
log_warn("accepted too many tcp, connections full");
return;
}
/* accept incoming connection. */
c_hdl = c->tcp_free;
/* clear leftover flags from previous use, and then set the
* correct event base for the event structure for libevent */
ub_event_free(c_hdl->ev->ev);
c_hdl->ev->ev = NULL;
if((c_hdl->type == comm_tcp && c_hdl->tcp_req_info) ||
c_hdl->type == comm_local || c_hdl->type == comm_raw)
c_hdl->tcp_do_toggle_rw = 0;
else c_hdl->tcp_do_toggle_rw = 1;
if(c_hdl->type == comm_http) {
#ifdef HAVE_NGHTTP2
if(!c_hdl->h2_session ||
!http2_session_server_create(c_hdl->h2_session)) {
log_warn("failed to create nghttp2");
return;
}
if(!c_hdl->h2_session ||
!http2_submit_settings(c_hdl->h2_session)) {
log_warn("failed to submit http2 settings");
return;
}
if(!c->ssl) {
c_hdl->tcp_do_toggle_rw = 0;
c_hdl->use_h2 = 1;
}
#endif
c_hdl->ev->ev = ub_event_new(c_hdl->ev->base->eb->base, -1,
UB_EV_PERSIST | UB_EV_READ | UB_EV_TIMEOUT,
comm_point_http_handle_callback, c_hdl);
} else {
c_hdl->ev->ev = ub_event_new(c_hdl->ev->base->eb->base, -1,
UB_EV_PERSIST | UB_EV_READ | UB_EV_TIMEOUT,
comm_point_tcp_handle_callback, c_hdl);
}
if(!c_hdl->ev->ev) {
log_warn("could not ub_event_new, dropped tcp");
return;
}
log_assert(fd != -1);
(void)fd;
new_fd = comm_point_perform_accept(c, &c_hdl->repinfo.remote_addr,
&c_hdl->repinfo.remote_addrlen);
if(new_fd == -1)
return;
/* Copy remote_address to client_address.
* Simplest way/time for streams to do that. */
c_hdl->repinfo.client_addrlen = c_hdl->repinfo.remote_addrlen;
memmove(&c_hdl->repinfo.client_addr,
&c_hdl->repinfo.remote_addr,
c_hdl->repinfo.remote_addrlen);
if(c->ssl) {
c_hdl->ssl = incoming_ssl_fd(c->ssl, new_fd);
if(!c_hdl->ssl) {
c_hdl->fd = new_fd;
comm_point_close(c_hdl);
return;
}
c_hdl->ssl_shake_state = comm_ssl_shake_read;
#ifdef USE_WINSOCK
comm_point_tcp_win_bio_cb(c_hdl, c_hdl->ssl);
#endif
}
/* grab the tcp handler buffers */
c->cur_tcp_count++;
c->tcp_free = c_hdl->tcp_free;
c_hdl->tcp_free = NULL;
if(!c->tcp_free) {
/* stop accepting incoming queries for now. */
comm_point_stop_listening(c);
}
setup_tcp_handler(c_hdl, new_fd, c->cur_tcp_count, c->max_tcp_count);
}
/** Make tcp handler free for next assignment */
static void
reclaim_tcp_handler(struct comm_point* c)
{
log_assert(c->type == comm_tcp);
if(c->ssl) {
#ifdef HAVE_SSL
SSL_shutdown(c->ssl);
SSL_free(c->ssl);
c->ssl = NULL;
#endif
}
comm_point_close(c);
if(c->tcp_parent) {
if(c != c->tcp_parent->tcp_free) {
c->tcp_parent->cur_tcp_count--;
c->tcp_free = c->tcp_parent->tcp_free;
c->tcp_parent->tcp_free = c;
}
if(!c->tcp_free) {
/* re-enable listening on accept socket */
comm_point_start_listening(c->tcp_parent, -1, -1);
}
}
c->tcp_more_read_again = NULL;
c->tcp_more_write_again = NULL;
c->tcp_byte_count = 0;
c->pp2_header_state = pp2_header_none;
sldns_buffer_clear(c->buffer);
}
/** do the callback when writing is done */
static void
tcp_callback_writer(struct comm_point* c)
{
log_assert(c->type == comm_tcp);
if(!c->tcp_write_and_read) {
sldns_buffer_clear(c->buffer);
c->tcp_byte_count = 0;
}
if(c->tcp_do_toggle_rw)
c->tcp_is_reading = 1;
/* switch from listening(write) to listening(read) */
if(c->tcp_req_info) {
tcp_req_info_handle_writedone(c->tcp_req_info);
} else {
comm_point_stop_listening(c);
if(c->tcp_write_and_read) {
fptr_ok(fptr_whitelist_comm_point(c->callback));
if( (*c->callback)(c, c->cb_arg, NETEVENT_PKT_WRITTEN,
&c->repinfo) ) {
comm_point_start_listening(c, -1,
adjusted_tcp_timeout(c));
}
} else {
comm_point_start_listening(c, -1,
adjusted_tcp_timeout(c));
}
}
}
/** do the callback when reading is done */
static void
tcp_callback_reader(struct comm_point* c)
{
log_assert(c->type == comm_tcp || c->type == comm_local);
sldns_buffer_flip(c->buffer);
if(c->tcp_do_toggle_rw)
c->tcp_is_reading = 0;
c->tcp_byte_count = 0;
if(c->tcp_req_info) {
tcp_req_info_handle_readdone(c->tcp_req_info);
} else {
if(c->type == comm_tcp)
comm_point_stop_listening(c);
fptr_ok(fptr_whitelist_comm_point(c->callback));
if( (*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, &c->repinfo) ) {
comm_point_start_listening(c, -1,
adjusted_tcp_timeout(c));
}
}
}
#ifdef HAVE_SSL
/** true if the ssl handshake error has to be squelched from the logs */
int
squelch_err_ssl_handshake(unsigned long err)
{
if(verbosity >= VERB_QUERY)
return 0; /* only squelch on low verbosity */
if(ERR_GET_LIB(err) == ERR_LIB_SSL &&
(ERR_GET_REASON(err) == SSL_R_HTTPS_PROXY_REQUEST ||
ERR_GET_REASON(err) == SSL_R_HTTP_REQUEST ||
ERR_GET_REASON(err) == SSL_R_WRONG_VERSION_NUMBER ||
ERR_GET_REASON(err) == SSL_R_SSLV3_ALERT_BAD_CERTIFICATE
#ifdef SSL_F_TLS_POST_PROCESS_CLIENT_HELLO
|| ERR_GET_REASON(err) == SSL_R_NO_SHARED_CIPHER
#endif
#ifdef SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO
|| ERR_GET_REASON(err) == SSL_R_UNKNOWN_PROTOCOL
|| ERR_GET_REASON(err) == SSL_R_UNSUPPORTED_PROTOCOL
# ifdef SSL_R_VERSION_TOO_LOW
|| ERR_GET_REASON(err) == SSL_R_VERSION_TOO_LOW
# endif
#endif
))
return 1;
return 0;
}
#endif /* HAVE_SSL */
/** continue ssl handshake */
#ifdef HAVE_SSL
static int
ssl_handshake(struct comm_point* c)
{
int r;
if(c->ssl_shake_state == comm_ssl_shake_hs_read) {
/* read condition satisfied back to writing */
comm_point_listen_for_rw(c, 0, 1);
c->ssl_shake_state = comm_ssl_shake_none;
return 1;
}
if(c->ssl_shake_state == comm_ssl_shake_hs_write) {
/* write condition satisfied, back to reading */
comm_point_listen_for_rw(c, 1, 0);
c->ssl_shake_state = comm_ssl_shake_none;
return 1;
}
ERR_clear_error();
r = SSL_do_handshake(c->ssl);
if(r != 1) {
int want = SSL_get_error(c->ssl, r);
if(want == SSL_ERROR_WANT_READ) {
if(c->ssl_shake_state == comm_ssl_shake_read)
return 1;
c->ssl_shake_state = comm_ssl_shake_read;
comm_point_listen_for_rw(c, 1, 0);
return 1;
} else if(want == SSL_ERROR_WANT_WRITE) {
if(c->ssl_shake_state == comm_ssl_shake_write)
return 1;
c->ssl_shake_state = comm_ssl_shake_write;
comm_point_listen_for_rw(c, 0, 1);
return 1;
} else if(r == 0) {
return 0; /* closed */
} else if(want == SSL_ERROR_SYSCALL) {
/* SYSCALL and errno==0 means closed uncleanly */
#ifdef EPIPE
if(errno == EPIPE && verbosity < 2)
return 0; /* silence 'broken pipe' */
#endif
#ifdef ECONNRESET
if(errno == ECONNRESET && verbosity < 2)
return 0; /* silence reset by peer */
#endif
if(!tcp_connect_errno_needs_log(
(struct sockaddr*)&c->repinfo.remote_addr,
c->repinfo.remote_addrlen))
return 0; /* silence connect failures that
show up because after connect this is the
first system call that accesses the socket */
if(errno != 0)
log_err("SSL_handshake syscall: %s",
strerror(errno));
return 0;
} else {
unsigned long err = ERR_get_error();
if(!squelch_err_ssl_handshake(err)) {
long vr;
log_crypto_err_io_code("ssl handshake failed",
want, err);
if((vr=SSL_get_verify_result(c->ssl)) != 0)
log_err("ssl handshake cert error: %s",
X509_verify_cert_error_string(
vr));
log_addr(VERB_OPS, "ssl handshake failed",
&c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
}
return 0;
}
}
/* this is where peer verification could take place */
if((SSL_get_verify_mode(c->ssl)&SSL_VERIFY_PEER)) {
/* verification */
if(SSL_get_verify_result(c->ssl) == X509_V_OK) {
#ifdef HAVE_SSL_GET1_PEER_CERTIFICATE
X509* x = SSL_get1_peer_certificate(c->ssl);
#else
X509* x = SSL_get_peer_certificate(c->ssl);
#endif
if(!x) {
log_addr(VERB_ALGO, "SSL connection failed: "
"no certificate",
&c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
return 0;
}
log_cert(VERB_ALGO, "peer certificate", x);
#ifdef HAVE_SSL_GET0_PEERNAME
if(SSL_get0_peername(c->ssl)) {
char buf[255];
snprintf(buf, sizeof(buf), "SSL connection "
"to %s authenticated",
SSL_get0_peername(c->ssl));
log_addr(VERB_ALGO, buf, &c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
} else {
#endif
log_addr(VERB_ALGO, "SSL connection "
"authenticated", &c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
#ifdef HAVE_SSL_GET0_PEERNAME
}
#endif
X509_free(x);
} else {
#ifdef HAVE_SSL_GET1_PEER_CERTIFICATE
X509* x = SSL_get1_peer_certificate(c->ssl);
#else
X509* x = SSL_get_peer_certificate(c->ssl);
#endif
if(x) {
log_cert(VERB_ALGO, "peer certificate", x);
X509_free(x);
}
log_addr(VERB_ALGO, "SSL connection failed: "
"failed to authenticate",
&c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
return 0;
}
} else {
/* unauthenticated, the verify peer flag was not set
* in c->ssl when the ssl object was created from ssl_ctx */
log_addr(VERB_ALGO, "SSL connection", &c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
}
#ifdef HAVE_SSL_GET0_ALPN_SELECTED
/* check if http2 use is negotiated */
if(c->type == comm_http && c->h2_session) {
const unsigned char *alpn;
unsigned int alpnlen = 0;
SSL_get0_alpn_selected(c->ssl, &alpn, &alpnlen);
if(alpnlen == 2 && memcmp("h2", alpn, 2) == 0) {
/* connection upgraded to HTTP2 */
c->tcp_do_toggle_rw = 0;
c->use_h2 = 1;
} else {
verbose(VERB_ALGO, "client doesn't support HTTP/2");
return 0;
}
}
#endif
/* setup listen rw correctly */
if(c->tcp_is_reading) {
if(c->ssl_shake_state != comm_ssl_shake_read)
comm_point_listen_for_rw(c, 1, 0);
} else {
comm_point_listen_for_rw(c, 0, 1);
}
c->ssl_shake_state = comm_ssl_shake_none;
return 1;
}
#endif /* HAVE_SSL */
/** ssl read callback on TCP */
static int
ssl_handle_read(struct comm_point* c)
{
#ifdef HAVE_SSL
int r;
if(c->ssl_shake_state != comm_ssl_shake_none) {
if(!ssl_handshake(c))
return 0;
if(c->ssl_shake_state != comm_ssl_shake_none)
return 1;
}
if(c->pp2_enabled && c->pp2_header_state != pp2_header_done) {
struct pp2_header* header = NULL;
size_t want_read_size = 0;
size_t current_read_size = 0;
if(c->pp2_header_state == pp2_header_none) {
want_read_size = PP2_HEADER_SIZE;
if(sldns_buffer_remaining(c->buffer)<want_read_size) {
log_err_addr("proxy_protocol: not enough "
"buffer size to read PROXYv2 header", "",
&c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
return 0;
}
verbose(VERB_ALGO, "proxy_protocol: reading fixed "
"part of PROXYv2 header (len %lu)",
(unsigned long)want_read_size);
current_read_size = want_read_size;
if(c->tcp_byte_count < current_read_size) {
ERR_clear_error();
if((r=SSL_read(c->ssl, (void*)sldns_buffer_at(
c->buffer, c->tcp_byte_count),
current_read_size -
c->tcp_byte_count)) <= 0) {
int want = SSL_get_error(c->ssl, r);
if(want == SSL_ERROR_ZERO_RETURN) {
if(c->tcp_req_info)
return tcp_req_info_handle_read_close(c->tcp_req_info);
return 0; /* shutdown, closed */
} else if(want == SSL_ERROR_WANT_READ) {
#ifdef USE_WINSOCK
ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
#endif
return 1; /* read more later */
} else if(want == SSL_ERROR_WANT_WRITE) {
c->ssl_shake_state = comm_ssl_shake_hs_write;
comm_point_listen_for_rw(c, 0, 1);
return 1;
} else if(want == SSL_ERROR_SYSCALL) {
#ifdef ECONNRESET
if(errno == ECONNRESET && verbosity < 2)
return 0; /* silence reset by peer */
#endif
if(errno != 0)
log_err("SSL_read syscall: %s",
strerror(errno));
return 0;
}
log_crypto_err_io("could not SSL_read",
want);
return 0;
}
c->tcp_byte_count += r;
sldns_buffer_skip(c->buffer, r);
if(c->tcp_byte_count != current_read_size) return 1;
c->pp2_header_state = pp2_header_init;
}
}
if(c->pp2_header_state == pp2_header_init) {
int err;
err = pp2_read_header(
sldns_buffer_begin(c->buffer),
sldns_buffer_limit(c->buffer));
if(err) {
log_err("proxy_protocol: could not parse "
"PROXYv2 header (%s)",
pp_lookup_error(err));
return 0;
}
header = (struct pp2_header*)sldns_buffer_begin(c->buffer);
want_read_size = ntohs(header->len);
if(sldns_buffer_limit(c->buffer) <
PP2_HEADER_SIZE + want_read_size) {
log_err_addr("proxy_protocol: not enough "
"buffer size to read PROXYv2 header", "",
&c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
return 0;
}
verbose(VERB_ALGO, "proxy_protocol: reading variable "
"part of PROXYv2 header (len %lu)",
(unsigned long)want_read_size);
current_read_size = PP2_HEADER_SIZE + want_read_size;
if(want_read_size == 0) {
/* nothing more to read; header is complete */
c->pp2_header_state = pp2_header_done;
} else if(c->tcp_byte_count < current_read_size) {
ERR_clear_error();
if((r=SSL_read(c->ssl, (void*)sldns_buffer_at(
c->buffer, c->tcp_byte_count),
current_read_size -
c->tcp_byte_count)) <= 0) {
int want = SSL_get_error(c->ssl, r);
if(want == SSL_ERROR_ZERO_RETURN) {
if(c->tcp_req_info)
return tcp_req_info_handle_read_close(c->tcp_req_info);
return 0; /* shutdown, closed */
} else if(want == SSL_ERROR_WANT_READ) {
#ifdef USE_WINSOCK
ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
#endif
return 1; /* read more later */
} else if(want == SSL_ERROR_WANT_WRITE) {
c->ssl_shake_state = comm_ssl_shake_hs_write;
comm_point_listen_for_rw(c, 0, 1);
return 1;
} else if(want == SSL_ERROR_SYSCALL) {
#ifdef ECONNRESET
if(errno == ECONNRESET && verbosity < 2)
return 0; /* silence reset by peer */
#endif
if(errno != 0)
log_err("SSL_read syscall: %s",
strerror(errno));
return 0;
}
log_crypto_err_io("could not SSL_read",
want);
return 0;
}
c->tcp_byte_count += r;
sldns_buffer_skip(c->buffer, r);
if(c->tcp_byte_count != current_read_size) return 1;
c->pp2_header_state = pp2_header_done;
}
}
if(c->pp2_header_state != pp2_header_done || !header) {
log_err_addr("proxy_protocol: wrong state for the "
"PROXYv2 header", "", &c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
return 0;
}
sldns_buffer_flip(c->buffer);
if(!consume_pp2_header(c->buffer, &c->repinfo, 1)) {
log_err_addr("proxy_protocol: could not consume "
"PROXYv2 header", "", &c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
return 0;
}
verbose(VERB_ALGO, "proxy_protocol: successful read of "
"PROXYv2 header");
/* Clear and reset the buffer to read the following
* DNS packet(s). */
sldns_buffer_clear(c->buffer);
c->tcp_byte_count = 0;
return 1;
}
if(c->tcp_byte_count < sizeof(uint16_t)) {
/* read length bytes */
ERR_clear_error();
if((r=SSL_read(c->ssl, (void*)sldns_buffer_at(c->buffer,
c->tcp_byte_count), (int)(sizeof(uint16_t) -
c->tcp_byte_count))) <= 0) {
int want = SSL_get_error(c->ssl, r);
if(want == SSL_ERROR_ZERO_RETURN) {
if(c->tcp_req_info)
return tcp_req_info_handle_read_close(c->tcp_req_info);
return 0; /* shutdown, closed */
} else if(want == SSL_ERROR_WANT_READ) {
#ifdef USE_WINSOCK
ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
#endif
return 1; /* read more later */
} else if(want == SSL_ERROR_WANT_WRITE) {
c->ssl_shake_state = comm_ssl_shake_hs_write;
comm_point_listen_for_rw(c, 0, 1);
return 1;
} else if(want == SSL_ERROR_SYSCALL) {
#ifdef ECONNRESET
if(errno == ECONNRESET && verbosity < 2)
return 0; /* silence reset by peer */
#endif
if(errno != 0)
log_err("SSL_read syscall: %s",
strerror(errno));
return 0;
}
log_crypto_err_io("could not SSL_read", want);
return 0;
}
c->tcp_byte_count += r;
if(c->tcp_byte_count < sizeof(uint16_t))
return 1;
if(sldns_buffer_read_u16_at(c->buffer, 0) >
sldns_buffer_capacity(c->buffer)) {
verbose(VERB_QUERY, "ssl: dropped larger than buffer");
return 0;
}
sldns_buffer_set_limit(c->buffer,
sldns_buffer_read_u16_at(c->buffer, 0));
if(sldns_buffer_limit(c->buffer) < LDNS_HEADER_SIZE) {
verbose(VERB_QUERY, "ssl: dropped bogus too short.");
return 0;
}
sldns_buffer_skip(c->buffer, (ssize_t)(c->tcp_byte_count-sizeof(uint16_t)));
verbose(VERB_ALGO, "Reading ssl tcp query of length %d",
(int)sldns_buffer_limit(c->buffer));
}
if(sldns_buffer_remaining(c->buffer) > 0) {
ERR_clear_error();
r = SSL_read(c->ssl, (void*)sldns_buffer_current(c->buffer),
(int)sldns_buffer_remaining(c->buffer));
if(r <= 0) {
int want = SSL_get_error(c->ssl, r);
if(want == SSL_ERROR_ZERO_RETURN) {
if(c->tcp_req_info)
return tcp_req_info_handle_read_close(c->tcp_req_info);
return 0; /* shutdown, closed */
} else if(want == SSL_ERROR_WANT_READ) {
#ifdef USE_WINSOCK
ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
#endif
return 1; /* read more later */
} else if(want == SSL_ERROR_WANT_WRITE) {
c->ssl_shake_state = comm_ssl_shake_hs_write;
comm_point_listen_for_rw(c, 0, 1);
return 1;
} else if(want == SSL_ERROR_SYSCALL) {
#ifdef ECONNRESET
if(errno == ECONNRESET && verbosity < 2)
return 0; /* silence reset by peer */
#endif
if(errno != 0)
log_err("SSL_read syscall: %s",
strerror(errno));
return 0;
}
log_crypto_err_io("could not SSL_read", want);
return 0;
}
sldns_buffer_skip(c->buffer, (ssize_t)r);
}
if(sldns_buffer_remaining(c->buffer) <= 0) {
tcp_callback_reader(c);
}
return 1;
#else
(void)c;
return 0;
#endif /* HAVE_SSL */
}
/** ssl write callback on TCP */
static int
ssl_handle_write(struct comm_point* c)
{
#ifdef HAVE_SSL
int r;
if(c->ssl_shake_state != comm_ssl_shake_none) {
if(!ssl_handshake(c))
return 0;
if(c->ssl_shake_state != comm_ssl_shake_none)
return 1;
}
/* ignore return, if fails we may simply block */
(void)SSL_set_mode(c->ssl, (long)SSL_MODE_ENABLE_PARTIAL_WRITE);
if((c->tcp_write_and_read?c->tcp_write_byte_count:c->tcp_byte_count) < sizeof(uint16_t)) {
uint16_t len = htons(c->tcp_write_and_read?c->tcp_write_pkt_len:sldns_buffer_limit(c->buffer));
ERR_clear_error();
if(c->tcp_write_and_read) {
if(c->tcp_write_pkt_len + 2 < LDNS_RR_BUF_SIZE) {
/* combine the tcp length and the query for
* write, this emulates writev */
uint8_t buf[LDNS_RR_BUF_SIZE];
memmove(buf, &len, sizeof(uint16_t));
memmove(buf+sizeof(uint16_t),
c->tcp_write_pkt,
c->tcp_write_pkt_len);
r = SSL_write(c->ssl,
(void*)(buf+c->tcp_write_byte_count),
c->tcp_write_pkt_len + 2 -
c->tcp_write_byte_count);
} else {
r = SSL_write(c->ssl,
(void*)(((uint8_t*)&len)+c->tcp_write_byte_count),
(int)(sizeof(uint16_t)-c->tcp_write_byte_count));
}
} else if(sizeof(uint16_t)+sldns_buffer_remaining(c->buffer) <
LDNS_RR_BUF_SIZE) {
/* combine the tcp length and the query for write,
* this emulates writev */
uint8_t buf[LDNS_RR_BUF_SIZE];
memmove(buf, &len, sizeof(uint16_t));
memmove(buf+sizeof(uint16_t),
sldns_buffer_current(c->buffer),
sldns_buffer_remaining(c->buffer));
r = SSL_write(c->ssl, (void*)(buf+c->tcp_byte_count),
(int)(sizeof(uint16_t)+
sldns_buffer_remaining(c->buffer)
- c->tcp_byte_count));
} else {
r = SSL_write(c->ssl,
(void*)(((uint8_t*)&len)+c->tcp_byte_count),
(int)(sizeof(uint16_t)-c->tcp_byte_count));
}
if(r <= 0) {
int want = SSL_get_error(c->ssl, r);
if(want == SSL_ERROR_ZERO_RETURN) {
return 0; /* closed */
} else if(want == SSL_ERROR_WANT_READ) {
c->ssl_shake_state = comm_ssl_shake_hs_read;
comm_point_listen_for_rw(c, 1, 0);
return 1; /* wait for read condition */
} else if(want == SSL_ERROR_WANT_WRITE) {
#ifdef USE_WINSOCK
ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
#endif
return 1; /* write more later */
} else if(want == SSL_ERROR_SYSCALL) {
#ifdef EPIPE
if(errno == EPIPE && verbosity < 2)
return 0; /* silence 'broken pipe' */
#endif
if(errno != 0)
log_err("SSL_write syscall: %s",
strerror(errno));
return 0;
}
log_crypto_err_io("could not SSL_write", want);
return 0;
}
if(c->tcp_write_and_read) {
c->tcp_write_byte_count += r;
if(c->tcp_write_byte_count < sizeof(uint16_t))
return 1;
} else {
c->tcp_byte_count += r;
if(c->tcp_byte_count < sizeof(uint16_t))
return 1;
sldns_buffer_set_position(c->buffer, c->tcp_byte_count -
sizeof(uint16_t));
}
if((!c->tcp_write_and_read && sldns_buffer_remaining(c->buffer) == 0) || (c->tcp_write_and_read && c->tcp_write_byte_count == c->tcp_write_pkt_len + 2)) {
tcp_callback_writer(c);
return 1;
}
}
log_assert(c->tcp_write_and_read || sldns_buffer_remaining(c->buffer) > 0);
log_assert(!c->tcp_write_and_read || c->tcp_write_byte_count < c->tcp_write_pkt_len + 2);
ERR_clear_error();
if(c->tcp_write_and_read) {
r = SSL_write(c->ssl, (void*)(c->tcp_write_pkt + c->tcp_write_byte_count - 2),
(int)(c->tcp_write_pkt_len + 2 - c->tcp_write_byte_count));
} else {
r = SSL_write(c->ssl, (void*)sldns_buffer_current(c->buffer),
(int)sldns_buffer_remaining(c->buffer));
}
if(r <= 0) {
int want = SSL_get_error(c->ssl, r);
if(want == SSL_ERROR_ZERO_RETURN) {
return 0; /* closed */
} else if(want == SSL_ERROR_WANT_READ) {
c->ssl_shake_state = comm_ssl_shake_hs_read;
comm_point_listen_for_rw(c, 1, 0);
return 1; /* wait for read condition */
} else if(want == SSL_ERROR_WANT_WRITE) {
#ifdef USE_WINSOCK
ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
#endif
return 1; /* write more later */
} else if(want == SSL_ERROR_SYSCALL) {
#ifdef EPIPE
if(errno == EPIPE && verbosity < 2)
return 0; /* silence 'broken pipe' */
#endif
if(errno != 0)
log_err("SSL_write syscall: %s",
strerror(errno));
return 0;
}
log_crypto_err_io("could not SSL_write", want);
return 0;
}
if(c->tcp_write_and_read) {
c->tcp_write_byte_count += r;
} else {
sldns_buffer_skip(c->buffer, (ssize_t)r);
}
if((!c->tcp_write_and_read && sldns_buffer_remaining(c->buffer) == 0) || (c->tcp_write_and_read && c->tcp_write_byte_count == c->tcp_write_pkt_len + 2)) {
tcp_callback_writer(c);
}
return 1;
#else
(void)c;
return 0;
#endif /* HAVE_SSL */
}
/** handle ssl tcp connection with dns contents */
static int
ssl_handle_it(struct comm_point* c, int is_write)
{
/* handle case where renegotiation wants read during write call
* or write during read calls */
if(is_write && c->ssl_shake_state == comm_ssl_shake_hs_write)
return ssl_handle_read(c);
else if(!is_write && c->ssl_shake_state == comm_ssl_shake_hs_read)
return ssl_handle_write(c);
/* handle read events for read operation and write events for a
* write operation */
else if(!is_write)
return ssl_handle_read(c);
return ssl_handle_write(c);
}
/**
* Handle tcp reading callback.
* @param fd: file descriptor of socket.
* @param c: comm point to read from into buffer.
* @param short_ok: if true, very short packets are OK (for comm_local).
* @return: 0 on error
*/
static int
comm_point_tcp_handle_read(int fd, struct comm_point* c, int short_ok)
{
ssize_t r;
int recv_initial = 0;
log_assert(c->type == comm_tcp || c->type == comm_local);
if(c->ssl)
return ssl_handle_it(c, 0);
if(!c->tcp_is_reading && !c->tcp_write_and_read)
return 0;
log_assert(fd != -1);
if(c->pp2_enabled && c->pp2_header_state != pp2_header_done) {
struct pp2_header* header = NULL;
size_t want_read_size = 0;
size_t current_read_size = 0;
if(c->pp2_header_state == pp2_header_none) {
want_read_size = PP2_HEADER_SIZE;
if(sldns_buffer_remaining(c->buffer)<want_read_size) {
log_err_addr("proxy_protocol: not enough "
"buffer size to read PROXYv2 header", "",
&c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
return 0;
}
verbose(VERB_ALGO, "proxy_protocol: reading fixed "
"part of PROXYv2 header (len %lu)",
(unsigned long)want_read_size);
current_read_size = want_read_size;
if(c->tcp_byte_count < current_read_size) {
r = recv(fd, (void*)sldns_buffer_at(c->buffer,
c->tcp_byte_count),
current_read_size-c->tcp_byte_count, MSG_DONTWAIT);
if(r == 0) {
if(c->tcp_req_info)
return tcp_req_info_handle_read_close(c->tcp_req_info);
return 0;
} else if(r == -1) {
goto recv_error_initial;
}
c->tcp_byte_count += r;
sldns_buffer_skip(c->buffer, r);
if(c->tcp_byte_count != current_read_size) return 1;
c->pp2_header_state = pp2_header_init;
}
}
if(c->pp2_header_state == pp2_header_init) {
int err;
err = pp2_read_header(
sldns_buffer_begin(c->buffer),
sldns_buffer_limit(c->buffer));
if(err) {
log_err("proxy_protocol: could not parse "
"PROXYv2 header (%s)",
pp_lookup_error(err));
return 0;
}
header = (struct pp2_header*)sldns_buffer_begin(c->buffer);
want_read_size = ntohs(header->len);
if(sldns_buffer_limit(c->buffer) <
PP2_HEADER_SIZE + want_read_size) {
log_err_addr("proxy_protocol: not enough "
"buffer size to read PROXYv2 header", "",
&c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
return 0;
}
verbose(VERB_ALGO, "proxy_protocol: reading variable "
"part of PROXYv2 header (len %lu)",
(unsigned long)want_read_size);
current_read_size = PP2_HEADER_SIZE + want_read_size;
if(want_read_size == 0) {
/* nothing more to read; header is complete */
c->pp2_header_state = pp2_header_done;
} else if(c->tcp_byte_count < current_read_size) {
r = recv(fd, (void*)sldns_buffer_at(c->buffer,
c->tcp_byte_count),
current_read_size-c->tcp_byte_count, MSG_DONTWAIT);
if(r == 0) {
if(c->tcp_req_info)
return tcp_req_info_handle_read_close(c->tcp_req_info);
return 0;
} else if(r == -1) {
goto recv_error;
}
c->tcp_byte_count += r;
sldns_buffer_skip(c->buffer, r);
if(c->tcp_byte_count != current_read_size) return 1;
c->pp2_header_state = pp2_header_done;
}
}
if(c->pp2_header_state != pp2_header_done || !header) {
log_err_addr("proxy_protocol: wrong state for the "
"PROXYv2 header", "", &c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
return 0;
}
sldns_buffer_flip(c->buffer);
if(!consume_pp2_header(c->buffer, &c->repinfo, 1)) {
log_err_addr("proxy_protocol: could not consume "
"PROXYv2 header", "", &c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
return 0;
}
verbose(VERB_ALGO, "proxy_protocol: successful read of "
"PROXYv2 header");
/* Clear and reset the buffer to read the following
* DNS packet(s). */
sldns_buffer_clear(c->buffer);
c->tcp_byte_count = 0;
return 1;
}
if(c->tcp_byte_count < sizeof(uint16_t)) {
/* read length bytes */
r = recv(fd,(void*)sldns_buffer_at(c->buffer,c->tcp_byte_count),
sizeof(uint16_t)-c->tcp_byte_count, MSG_DONTWAIT);
if(r == 0) {
if(c->tcp_req_info)
return tcp_req_info_handle_read_close(c->tcp_req_info);
return 0;
} else if(r == -1) {
if(c->pp2_enabled) goto recv_error;
goto recv_error_initial;
}
c->tcp_byte_count += r;
if(c->tcp_byte_count != sizeof(uint16_t))
return 1;
if(sldns_buffer_read_u16_at(c->buffer, 0) >
sldns_buffer_capacity(c->buffer)) {
verbose(VERB_QUERY, "tcp: dropped larger than buffer");
return 0;
}
sldns_buffer_set_limit(c->buffer,
sldns_buffer_read_u16_at(c->buffer, 0));
if(!short_ok &&
sldns_buffer_limit(c->buffer) < LDNS_HEADER_SIZE) {
verbose(VERB_QUERY, "tcp: dropped bogus too short.");
return 0;
}
verbose(VERB_ALGO, "Reading tcp query of length %d",
(int)sldns_buffer_limit(c->buffer));
}
if(sldns_buffer_remaining(c->buffer) == 0)
log_err("in comm_point_tcp_handle_read buffer_remaining is "
"not > 0 as expected, continuing with (harmless) 0 "
"length recv");
r = recv(fd, (void*)sldns_buffer_current(c->buffer),
sldns_buffer_remaining(c->buffer), MSG_DONTWAIT);
if(r == 0) {
if(c->tcp_req_info)
return tcp_req_info_handle_read_close(c->tcp_req_info);
return 0;
} else if(r == -1) {
goto recv_error;
}
sldns_buffer_skip(c->buffer, r);
if(sldns_buffer_remaining(c->buffer) <= 0) {
tcp_callback_reader(c);
}
return 1;
recv_error_initial:
recv_initial = 1;
recv_error:
#ifndef USE_WINSOCK
if(errno == EINTR || errno == EAGAIN)
return 1;
#ifdef ECONNRESET
if(errno == ECONNRESET && verbosity < 2)
return 0; /* silence reset by peer */
#endif
if(recv_initial) {
#ifdef ECONNREFUSED
if(errno == ECONNREFUSED && verbosity < 2)
return 0; /* silence reset by peer */
#endif
#ifdef ENETUNREACH
if(errno == ENETUNREACH && verbosity < 2)
return 0; /* silence it */
#endif
#ifdef EHOSTDOWN
if(errno == EHOSTDOWN && verbosity < 2)
return 0; /* silence it */
#endif
#ifdef EHOSTUNREACH
if(errno == EHOSTUNREACH && verbosity < 2)
return 0; /* silence it */
#endif
#ifdef ENETDOWN
if(errno == ENETDOWN && verbosity < 2)
return 0; /* silence it */
#endif
#ifdef EACCES
if(errno == EACCES && verbosity < 2)
return 0; /* silence it */
#endif
#ifdef ENOTCONN
if(errno == ENOTCONN) {
log_err_addr("read (in tcp initial) failed and this "
"could be because TCP Fast Open is "
"enabled [--disable-tfo-client "
"--disable-tfo-server] but does not "
"work", sock_strerror(errno),
&c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
return 0;
}
#endif
}
#else /* USE_WINSOCK */
if(recv_initial) {
if(WSAGetLastError() == WSAECONNREFUSED && verbosity < 2)
return 0;
if(WSAGetLastError() == WSAEHOSTDOWN && verbosity < 2)
return 0;
if(WSAGetLastError() == WSAEHOSTUNREACH && verbosity < 2)
return 0;
if(WSAGetLastError() == WSAENETDOWN && verbosity < 2)
return 0;
if(WSAGetLastError() == WSAENETUNREACH && verbosity < 2)
return 0;
}
if(WSAGetLastError() == WSAECONNRESET)
return 0;
if(WSAGetLastError() == WSAEINPROGRESS)
return 1;
if(WSAGetLastError() == WSAEWOULDBLOCK) {
ub_winsock_tcp_wouldblock(c->ev->ev,
UB_EV_READ);
return 1;
}
#endif
log_err_addr((recv_initial?"read (in tcp initial)":"read (in tcp)"),
sock_strerror(errno), &c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
return 0;
}
/**
* Handle tcp writing callback.
* @param fd: file descriptor of socket.
* @param c: comm point to write buffer out of.
* @return: 0 on error
*/
static int
comm_point_tcp_handle_write(int fd, struct comm_point* c)
{
ssize_t r;
struct sldns_buffer *buffer;
log_assert(c->type == comm_tcp);
#ifdef USE_DNSCRYPT
buffer = c->dnscrypt_buffer;
#else
buffer = c->buffer;
#endif
if(c->tcp_is_reading && !c->ssl && !c->tcp_write_and_read)
return 0;
log_assert(fd != -1);
if(((!c->tcp_write_and_read && c->tcp_byte_count == 0) || (c->tcp_write_and_read && c->tcp_write_byte_count == 0)) && c->tcp_check_nb_connect) {
/* check for pending error from nonblocking connect */
/* from Stevens, unix network programming, vol1, 3rd ed, p450*/
int error = 0;
socklen_t len = (socklen_t)sizeof(error);
if(getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&error,
&len) < 0){
#ifndef USE_WINSOCK
error = errno; /* on solaris errno is error */
#else /* USE_WINSOCK */
error = WSAGetLastError();
#endif
}
#ifndef USE_WINSOCK
#if defined(EINPROGRESS) && defined(EWOULDBLOCK)
if(error == EINPROGRESS || error == EWOULDBLOCK)
return 1; /* try again later */
else
#endif
if(error != 0 && verbosity < 2)
return 0; /* silence lots of chatter in the logs */
else if(error != 0) {
log_err_addr("tcp connect", strerror(error),
&c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
#else /* USE_WINSOCK */
/* examine error */
if(error == WSAEINPROGRESS)
return 1;
else if(error == WSAEWOULDBLOCK) {
ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
return 1;
} else if(error != 0 && verbosity < 2)
return 0;
else if(error != 0) {
log_err_addr("tcp connect", wsa_strerror(error),
&c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
#endif /* USE_WINSOCK */
return 0;
}
}
if(c->ssl)
return ssl_handle_it(c, 1);
#ifdef USE_MSG_FASTOPEN
/* Only try this on first use of a connection that uses tfo,
otherwise fall through to normal write */
/* Also, TFO support on WINDOWS not implemented at the moment */
if(c->tcp_do_fastopen == 1) {
/* this form of sendmsg() does both a connect() and send() so need to
look for various flavours of error*/
uint16_t len = htons(c->tcp_write_and_read?c->tcp_write_pkt_len:sldns_buffer_limit(buffer));
struct msghdr msg;
struct iovec iov[2];
c->tcp_do_fastopen = 0;
memset(&msg, 0, sizeof(msg));
if(c->tcp_write_and_read) {
iov[0].iov_base = (uint8_t*)&len + c->tcp_write_byte_count;
iov[0].iov_len = sizeof(uint16_t) - c->tcp_write_byte_count;
iov[1].iov_base = c->tcp_write_pkt;
iov[1].iov_len = c->tcp_write_pkt_len;
} else {
iov[0].iov_base = (uint8_t*)&len + c->tcp_byte_count;
iov[0].iov_len = sizeof(uint16_t) - c->tcp_byte_count;
iov[1].iov_base = sldns_buffer_begin(buffer);
iov[1].iov_len = sldns_buffer_limit(buffer);
}
log_assert(iov[0].iov_len > 0);
msg.msg_name = &c->repinfo.remote_addr;
msg.msg_namelen = c->repinfo.remote_addrlen;
msg.msg_iov = iov;
msg.msg_iovlen = 2;
r = sendmsg(fd, &msg, MSG_FASTOPEN);
if (r == -1) {
#if defined(EINPROGRESS) && defined(EWOULDBLOCK)
/* Handshake is underway, maybe because no TFO cookie available.
Come back to write the message*/
if(errno == EINPROGRESS || errno == EWOULDBLOCK)
return 1;
#endif
if(errno == EINTR || errno == EAGAIN)
return 1;
/* Not handling EISCONN here as shouldn't ever hit that case.*/
if(errno != EPIPE
#ifdef EOPNOTSUPP
/* if /proc/sys/net/ipv4/tcp_fastopen is
* disabled on Linux, sendmsg may return
* 'Operation not supported', if so
* fallthrough to ordinary connect. */
&& errno != EOPNOTSUPP
#endif
&& errno != 0) {
if(verbosity < 2)
return 0; /* silence lots of chatter in the logs */
log_err_addr("tcp sendmsg", strerror(errno),
&c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
return 0;
}
verbose(VERB_ALGO, "tcp sendmsg for fastopen failed (with %s), try normal connect", strerror(errno));
/* fallthrough to nonFASTOPEN
* (MSG_FASTOPEN on Linux 3 produces EPIPE)
* we need to perform connect() */
if(connect(fd, (struct sockaddr *)&c->repinfo.remote_addr,
c->repinfo.remote_addrlen) == -1) {
#ifdef EINPROGRESS
if(errno == EINPROGRESS)
return 1; /* wait until connect done*/
#endif
#ifdef USE_WINSOCK
if(WSAGetLastError() == WSAEINPROGRESS ||
WSAGetLastError() == WSAEWOULDBLOCK)
return 1; /* wait until connect done*/
#endif
if(tcp_connect_errno_needs_log(
(struct sockaddr *)&c->repinfo.remote_addr,
c->repinfo.remote_addrlen)) {
log_err_addr("outgoing tcp: connect after EPIPE for fastopen",
strerror(errno),
&c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
}
return 0;
}
} else {
if(c->tcp_write_and_read) {
c->tcp_write_byte_count += r;
if(c->tcp_write_byte_count < sizeof(uint16_t))
return 1;
} else {
c->tcp_byte_count += r;
if(c->tcp_byte_count < sizeof(uint16_t))
return 1;
sldns_buffer_set_position(buffer, c->tcp_byte_count -
sizeof(uint16_t));
}
if((!c->tcp_write_and_read && sldns_buffer_remaining(buffer) == 0) || (c->tcp_write_and_read && c->tcp_write_byte_count == c->tcp_write_pkt_len + 2)) {
tcp_callback_writer(c);
return 1;
}
}
}
#endif /* USE_MSG_FASTOPEN */
if((c->tcp_write_and_read?c->tcp_write_byte_count:c->tcp_byte_count) < sizeof(uint16_t)) {
uint16_t len = htons(c->tcp_write_and_read?c->tcp_write_pkt_len:sldns_buffer_limit(buffer));
#ifdef HAVE_WRITEV
struct iovec iov[2];
if(c->tcp_write_and_read) {
iov[0].iov_base = (uint8_t*)&len + c->tcp_write_byte_count;
iov[0].iov_len = sizeof(uint16_t) - c->tcp_write_byte_count;
iov[1].iov_base = c->tcp_write_pkt;
iov[1].iov_len = c->tcp_write_pkt_len;
} else {
iov[0].iov_base = (uint8_t*)&len + c->tcp_byte_count;
iov[0].iov_len = sizeof(uint16_t) - c->tcp_byte_count;
iov[1].iov_base = sldns_buffer_begin(buffer);
iov[1].iov_len = sldns_buffer_limit(buffer);
}
log_assert(iov[0].iov_len > 0);
r = writev(fd, iov, 2);
#else /* HAVE_WRITEV */
if(c->tcp_write_and_read) {
r = send(fd, (void*)(((uint8_t*)&len)+c->tcp_write_byte_count),
sizeof(uint16_t)-c->tcp_write_byte_count, 0);
} else {
r = send(fd, (void*)(((uint8_t*)&len)+c->tcp_byte_count),
sizeof(uint16_t)-c->tcp_byte_count, 0);
}
#endif /* HAVE_WRITEV */
if(r == -1) {
#ifndef USE_WINSOCK
# ifdef EPIPE
if(errno == EPIPE && verbosity < 2)
return 0; /* silence 'broken pipe' */
#endif
if(errno == EINTR || errno == EAGAIN)
return 1;
#ifdef ECONNRESET
if(errno == ECONNRESET && verbosity < 2)
return 0; /* silence reset by peer */
#endif
# ifdef HAVE_WRITEV
log_err_addr("tcp writev", strerror(errno),
&c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
# else /* HAVE_WRITEV */
log_err_addr("tcp send s", strerror(errno),
&c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
# endif /* HAVE_WRITEV */
#else
if(WSAGetLastError() == WSAENOTCONN)
return 1;
if(WSAGetLastError() == WSAEINPROGRESS)
return 1;
if(WSAGetLastError() == WSAEWOULDBLOCK) {
ub_winsock_tcp_wouldblock(c->ev->ev,
UB_EV_WRITE);
return 1;
}
if(WSAGetLastError() == WSAECONNRESET && verbosity < 2)
return 0; /* silence reset by peer */
log_err_addr("tcp send s",
wsa_strerror(WSAGetLastError()),
&c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
#endif
return 0;
}
if(c->tcp_write_and_read) {
c->tcp_write_byte_count += r;
if(c->tcp_write_byte_count < sizeof(uint16_t))
return 1;
} else {
c->tcp_byte_count += r;
if(c->tcp_byte_count < sizeof(uint16_t))
return 1;
sldns_buffer_set_position(buffer, c->tcp_byte_count -
sizeof(uint16_t));
}
if((!c->tcp_write_and_read && sldns_buffer_remaining(buffer) == 0) || (c->tcp_write_and_read && c->tcp_write_byte_count == c->tcp_write_pkt_len + 2)) {
tcp_callback_writer(c);
return 1;
}
}
log_assert(c->tcp_write_and_read || sldns_buffer_remaining(buffer) > 0);
log_assert(!c->tcp_write_and_read || c->tcp_write_byte_count < c->tcp_write_pkt_len + 2);
if(c->tcp_write_and_read) {
r = send(fd, (void*)(c->tcp_write_pkt + c->tcp_write_byte_count - 2),
c->tcp_write_pkt_len + 2 - c->tcp_write_byte_count, 0);
} else {
r = send(fd, (void*)sldns_buffer_current(buffer),
sldns_buffer_remaining(buffer), 0);
}
if(r == -1) {
#ifndef USE_WINSOCK
if(errno == EINTR || errno == EAGAIN)
return 1;
#ifdef ECONNRESET
if(errno == ECONNRESET && verbosity < 2)
return 0; /* silence reset by peer */
#endif
#else
if(WSAGetLastError() == WSAEINPROGRESS)
return 1;
if(WSAGetLastError() == WSAEWOULDBLOCK) {
ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
return 1;
}
if(WSAGetLastError() == WSAECONNRESET && verbosity < 2)
return 0; /* silence reset by peer */
#endif
log_err_addr("tcp send r", sock_strerror(errno),
&c->repinfo.remote_addr,
c->repinfo.remote_addrlen);
return 0;
}
if(c->tcp_write_and_read) {
c->tcp_write_byte_count += r;
} else {
sldns_buffer_skip(buffer, r);
}
if((!c->tcp_write_and_read && sldns_buffer_remaining(buffer) == 0) || (c->tcp_write_and_read && c->tcp_write_byte_count == c->tcp_write_pkt_len + 2)) {
tcp_callback_writer(c);
}
return 1;
}
/** read again to drain buffers when there could be more to read, returns 0
* on failure which means the comm point is closed. */
static int
tcp_req_info_read_again(int fd, struct comm_point* c)
{
while(c->tcp_req_info->read_again) {
int r;
c->tcp_req_info->read_again = 0;
if(c->tcp_is_reading)
r = comm_point_tcp_handle_read(fd, c, 0);
else r = comm_point_tcp_handle_write(fd, c);
if(!r) {
reclaim_tcp_handler(c);
if(!c->tcp_do_close) {
fptr_ok(fptr_whitelist_comm_point(
c->callback));
(void)(*c->callback)(c, c->cb_arg,
NETEVENT_CLOSED, NULL);
}
return 0;
}
}
return 1;
}
/** read again to drain buffers when there could be more to read */
static void
tcp_more_read_again(int fd, struct comm_point* c)
{
/* if the packet is done, but another one could be waiting on
* the connection, the callback signals this, and we try again */
/* this continues until the read routines get EAGAIN or so,
* and thus does not call the callback, and the bool is 0 */
int* moreread = c->tcp_more_read_again;
while(moreread && *moreread) {
*moreread = 0;
if(!comm_point_tcp_handle_read(fd, c, 0)) {
reclaim_tcp_handler(c);
if(!c->tcp_do_close) {
fptr_ok(fptr_whitelist_comm_point(
c->callback));
(void)(*c->callback)(c, c->cb_arg,
NETEVENT_CLOSED, NULL);
}
return;
}
}
}
/** write again to fill up when there could be more to write */
static void
tcp_more_write_again(int fd, struct comm_point* c)
{
/* if the packet is done, but another is waiting to be written,
* the callback signals it and we try again. */
/* this continues until the write routines get EAGAIN or so,
* and thus does not call the callback, and the bool is 0 */
int* morewrite = c->tcp_more_write_again;
while(morewrite && *morewrite) {
*morewrite = 0;
if(!comm_point_tcp_handle_write(fd, c)) {
reclaim_tcp_handler(c);
if(!c->tcp_do_close) {
fptr_ok(fptr_whitelist_comm_point(
c->callback));
(void)(*c->callback)(c, c->cb_arg,
NETEVENT_CLOSED, NULL);
}
return;
}
}
}
void
comm_point_tcp_handle_callback(int fd, short event, void* arg)
{
struct comm_point* c = (struct comm_point*)arg;
log_assert(c->type == comm_tcp);
ub_comm_base_now(c->ev->base);
if(c->fd == -1 || c->fd != fd)
return; /* duplicate event, but commpoint closed. */
#ifdef USE_DNSCRYPT
/* Initialize if this is a dnscrypt socket */
if(c->tcp_parent) {
c->dnscrypt = c->tcp_parent->dnscrypt;
}
if(c->dnscrypt && c->dnscrypt_buffer == c->buffer) {
c->dnscrypt_buffer = sldns_buffer_new(sldns_buffer_capacity(c->buffer));
if(!c->dnscrypt_buffer) {
log_err("Could not allocate dnscrypt buffer");
reclaim_tcp_handler(c);
if(!c->tcp_do_close) {
fptr_ok(fptr_whitelist_comm_point(
c->callback));
(void)(*c->callback)(c, c->cb_arg,
NETEVENT_CLOSED, NULL);
}
return;
}
}
#endif
if(event&UB_EV_TIMEOUT) {
verbose(VERB_QUERY, "tcp took too long, dropped");
reclaim_tcp_handler(c);
if(!c->tcp_do_close) {
fptr_ok(fptr_whitelist_comm_point(c->callback));
(void)(*c->callback)(c, c->cb_arg,
NETEVENT_TIMEOUT, NULL);
}
return;
}
if(event&UB_EV_READ
#ifdef USE_MSG_FASTOPEN
&& !(c->tcp_do_fastopen && (event&UB_EV_WRITE))
#endif
) {
int has_tcpq = (c->tcp_req_info != NULL);
int* moreread = c->tcp_more_read_again;
if(!comm_point_tcp_handle_read(fd, c, 0)) {
reclaim_tcp_handler(c);
if(!c->tcp_do_close) {
fptr_ok(fptr_whitelist_comm_point(
c->callback));
(void)(*c->callback)(c, c->cb_arg,
NETEVENT_CLOSED, NULL);
}
return;
}
if(has_tcpq && c->tcp_req_info && c->tcp_req_info->read_again) {
if(!tcp_req_info_read_again(fd, c))
return;
}
if(moreread && *moreread)
tcp_more_read_again(fd, c);
return;
}
if(event&UB_EV_WRITE) {
int has_tcpq = (c->tcp_req_info != NULL);
int* morewrite = c->tcp_more_write_again;
if(!comm_point_tcp_handle_write(fd, c)) {
reclaim_tcp_handler(c);
if(!c->tcp_do_close) {
fptr_ok(fptr_whitelist_comm_point(
c->callback));
(void)(*c->callback)(c, c->cb_arg,
NETEVENT_CLOSED, NULL);
}
return;
}
if(has_tcpq && c->tcp_req_info && c->tcp_req_info->read_again) {
if(!tcp_req_info_read_again(fd, c))
return;
}
if(morewrite && *morewrite)
tcp_more_write_again(fd, c);
return;
}
log_err("Ignored event %d for tcphdl.", event);
}
/** Make http handler free for next assignment */
static void
reclaim_http_handler(struct comm_point* c)
{
log_assert(c->type == comm_http);
if(c->ssl) {
#ifdef HAVE_SSL
SSL_shutdown(c->ssl);
SSL_free(c->ssl);
c->ssl = NULL;
#endif
}
comm_point_close(c);
if(c->tcp_parent) {
if(c != c->tcp_parent->tcp_free) {
c->tcp_parent->cur_tcp_count--;
c->tcp_free = c->tcp_parent->tcp_free;
c->tcp_parent->tcp_free = c;
}
if(!c->tcp_free) {
/* re-enable listening on accept socket */
comm_point_start_listening(c->tcp_parent, -1, -1);
}
}
}
/** read more data for http (with ssl) */
static int
ssl_http_read_more(struct comm_point* c)
{
#ifdef HAVE_SSL
int r;
log_assert(sldns_buffer_remaining(c->buffer) > 0);
ERR_clear_error();
r = SSL_read(c->ssl, (void*)sldns_buffer_current(c->buffer),
(int)sldns_buffer_remaining(c->buffer));
if(r <= 0) {
int want = SSL_get_error(c->ssl, r);
if(want == SSL_ERROR_ZERO_RETURN) {
return 0; /* shutdown, closed */
} else if(want == SSL_ERROR_WANT_READ) {
return 1; /* read more later */
} else if(want == SSL_ERROR_WANT_WRITE) {
c->ssl_shake_state = comm_ssl_shake_hs_write;
comm_point_listen_for_rw(c, 0, 1);
return 1;
} else if(want == SSL_ERROR_SYSCALL) {
#ifdef ECONNRESET
if(errno == ECONNRESET && verbosity < 2)
return 0; /* silence reset by peer */
#endif
if(errno != 0)
log_err("SSL_read syscall: %s",
strerror(errno));
return 0;
}
log_crypto_err_io("could not SSL_read", want);
return 0;
}
verbose(VERB_ALGO, "ssl http read more skip to %d + %d",
(int)sldns_buffer_position(c->buffer), (int)r);
sldns_buffer_skip(c->buffer, (ssize_t)r);
return 1;
#else
(void)c;
return 0;
#endif /* HAVE_SSL */
}
/** read more data for http */
static int
http_read_more(int fd, struct comm_point* c)
{
ssize_t r;
log_assert(sldns_buffer_remaining(c->buffer) > 0);
r = recv(fd, (void*)sldns_buffer_current(c->buffer),
sldns_buffer_remaining(c->buffer), MSG_DONTWAIT);
if(r == 0) {
return 0;
} else if(r == -1) {
#ifndef USE_WINSOCK
if(errno == EINTR || errno == EAGAIN)
return 1;
#else /* USE_WINSOCK */
if(WSAGetLastError() == WSAECONNRESET)
return 0;
if(WSAGetLastError() == WSAEINPROGRESS)
return 1;
if(WSAGetLastError() == WSAEWOULDBLOCK) {
ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
return 1;
}
#endif
log_err_addr("read (in http r)", sock_strerror(errno),
&c->repinfo.remote_addr, c->repinfo.remote_addrlen);
return 0;
}
verbose(VERB_ALGO, "http read more skip to %d + %d",
(int)sldns_buffer_position(c->buffer), (int)r);
sldns_buffer_skip(c->buffer, r);
return 1;
}
/** return true if http header has been read (one line complete) */
static int
http_header_done(sldns_buffer* buf)
{
size_t i;
for(i=sldns_buffer_position(buf); i<sldns_buffer_limit(buf); i++) {
/* there was a \r before the \n, but we ignore that */
if((char)sldns_buffer_read_u8_at(buf, i) == '\n')
return 1;
}
return 0;
}
/** return character string into buffer for header line, moves buffer
* past that line and puts zero terminator into linefeed-newline */
static char*
http_header_line(sldns_buffer* buf)
{
char* result = (char*)sldns_buffer_current(buf);
size_t i;
for(i=sldns_buffer_position(buf); i<sldns_buffer_limit(buf); i++) {
/* terminate the string on the \r */
if((char)sldns_buffer_read_u8_at(buf, i) == '\r')
sldns_buffer_write_u8_at(buf, i, 0);
/* terminate on the \n and skip past the it and done */
if((char)sldns_buffer_read_u8_at(buf, i) == '\n') {
sldns_buffer_write_u8_at(buf, i, 0);
sldns_buffer_set_position(buf, i+1);
return result;
}
}
return NULL;
}
/** move unread buffer to start and clear rest for putting the rest into it */
static void
http_moveover_buffer(sldns_buffer* buf)
{
size_t pos = sldns_buffer_position(buf);
size_t len = sldns_buffer_remaining(buf);
sldns_buffer_clear(buf);
memmove(sldns_buffer_begin(buf), sldns_buffer_at(buf, pos), len);
sldns_buffer_set_position(buf, len);
}
/** a http header is complete, process it */
static int
http_process_initial_header(struct comm_point* c)
{
char* line = http_header_line(c->buffer);
if(!line) return 1;
verbose(VERB_ALGO, "http header: %s", line);
if(strncasecmp(line, "HTTP/1.1 ", 9) == 0) {
/* check returncode */
if(line[9] != '2') {
verbose(VERB_ALGO, "http bad status %s", line+9);
return 0;
}
} else if(strncasecmp(line, "Content-Length: ", 16) == 0) {
if(!c->http_is_chunked)
c->tcp_byte_count = (size_t)atoi(line+16);
} else if(strncasecmp(line, "Transfer-Encoding: chunked", 19+7) == 0) {
c->tcp_byte_count = 0;
c->http_is_chunked = 1;
} else if(line[0] == 0) {
/* end of initial headers */
c->http_in_headers = 0;
if(c->http_is_chunked)
c->http_in_chunk_headers = 1;
/* remove header text from front of buffer
* the buffer is going to be used to return the data segment
* itself and we don't want the header to get returned
* prepended with it */
http_moveover_buffer(c->buffer);
sldns_buffer_flip(c->buffer);
return 1;
}
/* ignore other headers */
return 1;
}
/** a chunk header is complete, process it, return 0=fail, 1=continue next
* header line, 2=done with chunked transfer*/
static int
http_process_chunk_header(struct comm_point* c)
{
char* line = http_header_line(c->buffer);
if(!line) return 1;
if(c->http_in_chunk_headers == 3) {
verbose(VERB_ALGO, "http chunk trailer: %s", line);
/* are we done ? */
if(line[0] == 0 && c->tcp_byte_count == 0) {
/* callback of http reader when NETEVENT_DONE,
* end of data, with no data in buffer */
sldns_buffer_set_position(c->buffer, 0);
sldns_buffer_set_limit(c->buffer, 0);
fptr_ok(fptr_whitelist_comm_point(c->callback));
(void)(*c->callback)(c, c->cb_arg, NETEVENT_DONE, NULL);
/* return that we are done */
return 2;
}
if(line[0] == 0) {
/* continue with header of the next chunk */
c->http_in_chunk_headers = 1;
/* remove header text from front of buffer */
http_moveover_buffer(c->buffer);
sldns_buffer_flip(c->buffer);
return 1;
}
/* ignore further trail headers */
return 1;
}
verbose(VERB_ALGO, "http chunk header: %s", line);
if(c->http_in_chunk_headers == 1) {
/* read chunked start line */
char* end = NULL;
c->tcp_byte_count = (size_t)strtol(line, &end, 16);
if(end == line)
return 0;
c->http_in_chunk_headers = 0;
/* remove header text from front of buffer */
http_moveover_buffer(c->buffer);
sldns_buffer_flip(c->buffer);
if(c->tcp_byte_count == 0) {
/* done with chunks, process chunk_trailer lines */
c->http_in_chunk_headers = 3;
}
return 1;
}
/* ignore other headers */
return 1;
}
/** handle nonchunked data segment, 0=fail, 1=wait */
static int
http_nonchunk_segment(struct comm_point* c)
{
/* c->buffer at position..limit has new data we read in.
* the buffer itself is full of nonchunked data.
* we are looking to read tcp_byte_count more data
* and then the transfer is done. */
size_t remainbufferlen;
size_t got_now = sldns_buffer_limit(c->buffer);
if(c->tcp_byte_count <= got_now) {
/* done, this is the last data fragment */
c->http_stored = 0;
sldns_buffer_set_position(c->buffer, 0);
fptr_ok(fptr_whitelist_comm_point(c->callback));
(void)(*c->callback)(c, c->cb_arg, NETEVENT_DONE, NULL);
return 1;
}
/* if we have the buffer space,
* read more data collected into the buffer */
remainbufferlen = sldns_buffer_capacity(c->buffer) -
sldns_buffer_limit(c->buffer);
if(remainbufferlen+got_now >= c->tcp_byte_count ||
remainbufferlen >= (size_t)(c->ssl?16384:2048)) {
size_t total = sldns_buffer_limit(c->buffer);
sldns_buffer_clear(c->buffer);
sldns_buffer_set_position(c->buffer, total);
c->http_stored = total;
/* return and wait to read more */
return 1;
}
/* call callback with this data amount, then
* wait for more */
c->tcp_byte_count -= got_now;
c->http_stored = 0;
sldns_buffer_set_position(c->buffer, 0);
fptr_ok(fptr_whitelist_comm_point(c->callback));
(void)(*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, NULL);
/* c->callback has to buffer_clear(c->buffer). */
/* return and wait to read more */
return 1;
}
/** handle chunked data segment, return 0=fail, 1=wait, 2=process more */
static int
http_chunked_segment(struct comm_point* c)
{
/* the c->buffer has from position..limit new data we read. */
/* the current chunk has length tcp_byte_count.
* once we read that read more chunk headers.
*/
size_t remainbufferlen;
size_t got_now = sldns_buffer_limit(c->buffer) - c->http_stored;
verbose(VERB_ALGO, "http_chunked_segment: got now %d, tcpbytcount %d, http_stored %d, buffer pos %d, buffer limit %d", (int)got_now, (int)c->tcp_byte_count, (int)c->http_stored, (int)sldns_buffer_position(c->buffer), (int)sldns_buffer_limit(c->buffer));
if(c->tcp_byte_count <= got_now) {
/* the chunk has completed (with perhaps some extra data
* from next chunk header and next chunk) */
/* save too much info into temp buffer */
size_t fraglen;
struct comm_reply repinfo;
c->http_stored = 0;
sldns_buffer_skip(c->buffer, (ssize_t)c->tcp_byte_count);
sldns_buffer_clear(c->http_temp);
sldns_buffer_write(c->http_temp,
sldns_buffer_current(c->buffer),
sldns_buffer_remaining(c->buffer));
sldns_buffer_flip(c->http_temp);
/* callback with this fragment */
fraglen = sldns_buffer_position(c->buffer);
sldns_buffer_set_position(c->buffer, 0);
sldns_buffer_set_limit(c->buffer, fraglen);
repinfo = c->repinfo;
fptr_ok(fptr_whitelist_comm_point(c->callback));
(void)(*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, &repinfo);
/* c->callback has to buffer_clear(). */
/* is commpoint deleted? */
if(!repinfo.c) {
return 1;
}
/* copy waiting info */
sldns_buffer_clear(c->buffer);
sldns_buffer_write(c->buffer,
sldns_buffer_begin(c->http_temp),
sldns_buffer_remaining(c->http_temp));
sldns_buffer_flip(c->buffer);
/* process end of chunk trailer header lines, until
* an empty line */
c->http_in_chunk_headers = 3;
/* process more data in buffer (if any) */
return 2;
}
c->tcp_byte_count -= got_now;
/* if we have the buffer space,
* read more data collected into the buffer */
remainbufferlen = sldns_buffer_capacity(c->buffer) -
sldns_buffer_limit(c->buffer);
if(remainbufferlen >= c->tcp_byte_count ||
remainbufferlen >= 2048) {
size_t total = sldns_buffer_limit(c->buffer);
sldns_buffer_clear(c->buffer);
sldns_buffer_set_position(c->buffer, total);
c->http_stored = total;
/* return and wait to read more */
return 1;
}
/* callback of http reader for a new part of the data */
c->http_stored = 0;
sldns_buffer_set_position(c->buffer, 0);
fptr_ok(fptr_whitelist_comm_point(c->callback));
(void)(*c->callback)(c, c->cb_arg, NETEVENT_NOERROR, NULL);
/* c->callback has to buffer_clear(c->buffer). */
/* return and wait to read more */
return 1;
}
#ifdef HAVE_NGHTTP2
/** Create new http2 session. Called when creating handling comm point. */
static struct http2_session* http2_session_create(struct comm_point* c)
{
struct http2_session* session = calloc(1, sizeof(*session));
if(!session) {
log_err("malloc failure while creating http2 session");
return NULL;
}
session->c = c;
return session;
}
#endif
/** Delete http2 session. After closing connection or on error */
static void http2_session_delete(struct http2_session* h2_session)
{
#ifdef HAVE_NGHTTP2
if(h2_session->callbacks)
nghttp2_session_callbacks_del(h2_session->callbacks);
free(h2_session);
#else
(void)h2_session;
#endif
}
#ifdef HAVE_NGHTTP2
struct http2_stream* http2_stream_create(int32_t stream_id)
{
struct http2_stream* h2_stream = calloc(1, sizeof(*h2_stream));
if(!h2_stream) {
log_err("malloc failure while creating http2 stream");
return NULL;
}
h2_stream->stream_id = stream_id;
return h2_stream;
}
/** Delete http2 stream. After session delete or stream close callback */
static void http2_stream_delete(struct http2_session* h2_session,
struct http2_stream* h2_stream)
{
if(h2_stream->mesh_state) {
mesh_state_remove_reply(h2_stream->mesh, h2_stream->mesh_state,
h2_session->c);
h2_stream->mesh_state = NULL;
}
http2_req_stream_clear(h2_stream);
free(h2_stream);
}
#endif
void http2_stream_add_meshstate(struct http2_stream* h2_stream,
struct mesh_area* mesh, struct mesh_state* m)
{
h2_stream->mesh = mesh;
h2_stream->mesh_state = m;
}
void http2_stream_remove_mesh_state(struct http2_stream* h2_stream)
{
if(!h2_stream)
return;
h2_stream->mesh_state = NULL;
}
/** delete http2 session server. After closing connection. */
static void http2_session_server_delete(struct http2_session* h2_session)
{
#ifdef HAVE_NGHTTP2
struct http2_stream* h2_stream, *next;
nghttp2_session_del(h2_session->session); /* NULL input is fine */
h2_session->session = NULL;
for(h2_stream = h2_session->first_stream; h2_stream;) {
next = h2_stream->next;
http2_stream_delete(h2_session, h2_stream);
h2_stream = next;
}
h2_session->first_stream = NULL;
h2_session->is_drop = 0;
h2_session->postpone_drop = 0;
h2_session->c->h2_stream = NULL;
#endif
(void)h2_session;
}
#ifdef HAVE_NGHTTP2
void http2_session_add_stream(struct http2_session* h2_session,
struct http2_stream* h2_stream)
{
if(h2_session->first_stream)
h2_session->first_stream->prev = h2_stream;
h2_stream->next = h2_session->first_stream;
h2_session->first_stream = h2_stream;
}
/** remove stream from session linked list. After stream close callback or
* closing connection */
static void http2_session_remove_stream(struct http2_session* h2_session,
struct http2_stream* h2_stream)
{
if(h2_stream->prev)
h2_stream->prev->next = h2_stream->next;
else
h2_session->first_stream = h2_stream->next;
if(h2_stream->next)
h2_stream->next->prev = h2_stream->prev;
}
int http2_stream_close_cb(nghttp2_session* ATTR_UNUSED(session),
int32_t stream_id, uint32_t ATTR_UNUSED(error_code), void* cb_arg)
{
struct http2_stream* h2_stream;
struct http2_session* h2_session = (struct http2_session*)cb_arg;
if(!(h2_stream = nghttp2_session_get_stream_user_data(
h2_session->session, stream_id))) {
return 0;
}
http2_session_remove_stream(h2_session, h2_stream);
http2_stream_delete(h2_session, h2_stream);
return 0;
}
ssize_t http2_recv_cb(nghttp2_session* ATTR_UNUSED(session), uint8_t* buf,
size_t len, int ATTR_UNUSED(flags), void* cb_arg)
{
struct http2_session* h2_session = (struct http2_session*)cb_arg;
ssize_t ret;
log_assert(h2_session->c->type == comm_http);
log_assert(h2_session->c->h2_session);
#ifdef HAVE_SSL
if(h2_session->c->ssl) {
int r;
ERR_clear_error();
r = SSL_read(h2_session->c->ssl, buf, len);
if(r <= 0) {
int want = SSL_get_error(h2_session->c->ssl, r);
if(want == SSL_ERROR_ZERO_RETURN) {
return NGHTTP2_ERR_EOF;
} else if(want == SSL_ERROR_WANT_READ) {
return NGHTTP2_ERR_WOULDBLOCK;
} else if(want == SSL_ERROR_WANT_WRITE) {
h2_session->c->ssl_shake_state = comm_ssl_shake_hs_write;
comm_point_listen_for_rw(h2_session->c, 0, 1);
return NGHTTP2_ERR_WOULDBLOCK;
} else if(want == SSL_ERROR_SYSCALL) {
#ifdef ECONNRESET
if(errno == ECONNRESET && verbosity < 2)
return NGHTTP2_ERR_CALLBACK_FAILURE;
#endif
if(errno != 0)
log_err("SSL_read syscall: %s",
strerror(errno));
return NGHTTP2_ERR_CALLBACK_FAILURE;
}
log_crypto_err_io("could not SSL_read", want);
return NGHTTP2_ERR_CALLBACK_FAILURE;
}
return r;
}
#endif /* HAVE_SSL */
ret = recv(h2_session->c->fd, buf, len, MSG_DONTWAIT);
if(ret == 0) {
return NGHTTP2_ERR_EOF;
} else if(ret < 0) {
#ifndef USE_WINSOCK
if(errno == EINTR || errno == EAGAIN)
return NGHTTP2_ERR_WOULDBLOCK;
#ifdef ECONNRESET
if(errno == ECONNRESET && verbosity < 2)
return NGHTTP2_ERR_CALLBACK_FAILURE;
#endif
log_err_addr("could not http2 recv: %s", strerror(errno),
&h2_session->c->repinfo.remote_addr,
h2_session->c->repinfo.remote_addrlen);
#else /* USE_WINSOCK */
if(WSAGetLastError() == WSAECONNRESET)
return NGHTTP2_ERR_CALLBACK_FAILURE;
if(WSAGetLastError() == WSAEINPROGRESS)
return NGHTTP2_ERR_WOULDBLOCK;
if(WSAGetLastError() == WSAEWOULDBLOCK) {
ub_winsock_tcp_wouldblock(h2_session->c->ev->ev,
UB_EV_READ);
return NGHTTP2_ERR_WOULDBLOCK;
}
log_err_addr("could not http2 recv: %s",
wsa_strerror(WSAGetLastError()),
&h2_session->c->repinfo.remote_addr,
h2_session->c->repinfo.remote_addrlen);
#endif
return NGHTTP2_ERR_CALLBACK_FAILURE;
}
return ret;
}
#endif /* HAVE_NGHTTP2 */
/** Handle http2 read */
static int
comm_point_http2_handle_read(int ATTR_UNUSED(fd), struct comm_point* c)
{
#ifdef HAVE_NGHTTP2
int ret;
log_assert(c->h2_session);
/* reading until recv cb returns NGHTTP2_ERR_WOULDBLOCK */
ret = nghttp2_session_recv(c->h2_session->session);
if(ret) {
if(ret != NGHTTP2_ERR_EOF &&
ret != NGHTTP2_ERR_CALLBACK_FAILURE) {
char a[256];
addr_to_str(&c->repinfo.remote_addr,
c->repinfo.remote_addrlen, a, sizeof(a));
verbose(VERB_QUERY, "http2: session_recv from %s failed, "
"error: %s", a, nghttp2_strerror(ret));
}
return 0;
}
if(nghttp2_session_want_write(c->h2_session->session)) {
c->tcp_is_reading = 0;
comm_point_stop_listening(c);
comm_point_start_listening(c, -1, adjusted_tcp_timeout(c));
} else if(!nghttp2_session_want_read(c->h2_session->session))
return 0; /* connection can be closed */
return 1;
#else
(void)c;
return 0;
#endif
}
/**
* Handle http reading callback.
* @param fd: file descriptor of socket.
* @param c: comm point to read from into buffer.
* @return: 0 on error
*/
static int
comm_point_http_handle_read(int fd, struct comm_point* c)
{
log_assert(c->type == comm_http);
log_assert(fd != -1);
/* if we are in ssl handshake, handle SSL handshake */
#ifdef HAVE_SSL
if(c->ssl && c->ssl_shake_state != comm_ssl_shake_none) {
if(!ssl_handshake(c))
return 0;
if(c->ssl_shake_state != comm_ssl_shake_none)
return 1;
}
#endif /* HAVE_SSL */
if(!c->tcp_is_reading)
return 1;
if(c->use_h2) {
return comm_point_http2_handle_read(fd, c);
}
/* http version is <= http/1.1 */
if(c->http_min_version >= http_version_2) {
/* HTTP/2 failed, not allowed to use lower version. */
return 0;
}
/* read more data */
if(c->ssl) {
if(!ssl_http_read_more(c))
return 0;
} else {
if(!http_read_more(fd, c))
return 0;
}
if(c->http_stored >= sldns_buffer_position(c->buffer)) {
/* read did not work but we wanted more data, there is
* no bytes to process now. */
return 1;
}
sldns_buffer_flip(c->buffer);
/* if we are partway in a segment of data, position us at the point
* where we left off previously */
if(c->http_stored < sldns_buffer_limit(c->buffer))
sldns_buffer_set_position(c->buffer, c->http_stored);
else sldns_buffer_set_position(c->buffer, sldns_buffer_limit(c->buffer));
while(sldns_buffer_remaining(c->buffer) > 0) {
/* Handle HTTP/1.x data */
/* if we are reading headers, read more headers */
if(c->http_in_headers || c->http_in_chunk_headers) {
/* if header is done, process the header */
if(!http_header_done(c->buffer)) {
/* copy remaining data to front of buffer
* and set rest for writing into it */
http_moveover_buffer(c->buffer);
/* return and wait to read more */
return 1;
}
if(!c->http_in_chunk_headers) {
/* process initial headers */
if(!http_process_initial_header(c))
return 0;
} else {
/* process chunk headers */
int r = http_process_chunk_header(c);
if(r == 0) return 0;
if(r == 2) return 1; /* done */
/* r == 1, continue */
}
/* see if we have more to process */
continue;
}
if(!c->http_is_chunked) {
/* if we are reading nonchunks, process that*/
return http_nonchunk_segment(c);
} else {
/* if we are reading chunks, read the chunk */
int r = http_chunked_segment(c);
if(r == 0) return 0;
if(r == 1) return 1;
continue;
}
}
/* broke out of the loop; could not process header instead need
* to read more */
/* moveover any remaining data and read more data */
http_moveover_buffer(c->buffer);
/* return and wait to read more */
return 1;
}
/** check pending connect for http */
static int
http_check_connect(int fd, struct comm_point* c)
{
/* check for pending error from nonblocking connect */
/* from Stevens, unix network programming, vol1, 3rd ed, p450*/
int error = 0;
socklen_t len = (socklen_t)sizeof(error);
if(getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&error,
&len) < 0){
#ifndef USE_WINSOCK
error = errno; /* on solaris errno is error */
#else /* USE_WINSOCK */
error = WSAGetLastError();
#endif
}
#ifndef USE_WINSOCK
#if defined(EINPROGRESS) && defined(EWOULDBLOCK)
if(error == EINPROGRESS || error == EWOULDBLOCK)
return 1; /* try again later */
else
#endif
if(error != 0 && verbosity < 2)
return 0; /* silence lots of chatter in the logs */
else if(error != 0) {
log_err_addr("http connect", strerror(error),
&c->repinfo.remote_addr, c->repinfo.remote_addrlen);
#else /* USE_WINSOCK */
/* examine error */
if(error == WSAEINPROGRESS)
return 1;
else if(error == WSAEWOULDBLOCK) {
ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
return 1;
} else if(error != 0 && verbosity < 2)
return 0;
else if(error != 0) {
log_err_addr("http connect", wsa_strerror(error),
&c->repinfo.remote_addr, c->repinfo.remote_addrlen);
#endif /* USE_WINSOCK */
return 0;
}
/* keep on processing this socket */
return 2;
}
/** write more data for http (with ssl) */
static int
ssl_http_write_more(struct comm_point* c)
{
#ifdef HAVE_SSL
int r;
log_assert(sldns_buffer_remaining(c->buffer) > 0);
ERR_clear_error();
r = SSL_write(c->ssl, (void*)sldns_buffer_current(c->buffer),
(int)sldns_buffer_remaining(c->buffer));
if(r <= 0) {
int want = SSL_get_error(c->ssl, r);
if(want == SSL_ERROR_ZERO_RETURN) {
return 0; /* closed */
} else if(want == SSL_ERROR_WANT_READ) {
c->ssl_shake_state = comm_ssl_shake_hs_read;
comm_point_listen_for_rw(c, 1, 0);
return 1; /* wait for read condition */
} else if(want == SSL_ERROR_WANT_WRITE) {
return 1; /* write more later */
} else if(want == SSL_ERROR_SYSCALL) {
#ifdef EPIPE
if(errno == EPIPE && verbosity < 2)
return 0; /* silence 'broken pipe' */
#endif
if(errno != 0)
log_err("SSL_write syscall: %s",
strerror(errno));
return 0;
}
log_crypto_err_io("could not SSL_write", want);
return 0;
}
sldns_buffer_skip(c->buffer, (ssize_t)r);
return 1;
#else
(void)c;
return 0;
#endif /* HAVE_SSL */
}
/** write more data for http */
static int
http_write_more(int fd, struct comm_point* c)
{
ssize_t r;
log_assert(sldns_buffer_remaining(c->buffer) > 0);
r = send(fd, (void*)sldns_buffer_current(c->buffer),
sldns_buffer_remaining(c->buffer), 0);
if(r == -1) {
#ifndef USE_WINSOCK
if(errno == EINTR || errno == EAGAIN)
return 1;
#else
if(WSAGetLastError() == WSAEINPROGRESS)
return 1;
if(WSAGetLastError() == WSAEWOULDBLOCK) {
ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
return 1;
}
#endif
log_err_addr("http send r", sock_strerror(errno),
&c->repinfo.remote_addr, c->repinfo.remote_addrlen);
return 0;
}
sldns_buffer_skip(c->buffer, r);
return 1;
}
#ifdef HAVE_NGHTTP2
ssize_t http2_send_cb(nghttp2_session* ATTR_UNUSED(session), const uint8_t* buf,
size_t len, int ATTR_UNUSED(flags), void* cb_arg)
{
ssize_t ret;
struct http2_session* h2_session = (struct http2_session*)cb_arg;
log_assert(h2_session->c->type == comm_http);
log_assert(h2_session->c->h2_session);
#ifdef HAVE_SSL
if(h2_session->c->ssl) {
int r;
ERR_clear_error();
r = SSL_write(h2_session->c->ssl, buf, len);
if(r <= 0) {
int want = SSL_get_error(h2_session->c->ssl, r);
if(want == SSL_ERROR_ZERO_RETURN) {
return NGHTTP2_ERR_CALLBACK_FAILURE;
} else if(want == SSL_ERROR_WANT_READ) {
h2_session->c->ssl_shake_state = comm_ssl_shake_hs_read;
comm_point_listen_for_rw(h2_session->c, 1, 0);
return NGHTTP2_ERR_WOULDBLOCK;
} else if(want == SSL_ERROR_WANT_WRITE) {
return NGHTTP2_ERR_WOULDBLOCK;
} else if(want == SSL_ERROR_SYSCALL) {
#ifdef EPIPE
if(errno == EPIPE && verbosity < 2)
return NGHTTP2_ERR_CALLBACK_FAILURE;
#endif
if(errno != 0)
log_err("SSL_write syscall: %s",
strerror(errno));
return NGHTTP2_ERR_CALLBACK_FAILURE;
}
log_crypto_err_io("could not SSL_write", want);
return NGHTTP2_ERR_CALLBACK_FAILURE;
}
return r;
}
#endif /* HAVE_SSL */
ret = send(h2_session->c->fd, buf, len, 0);
if(ret == 0) {
return NGHTTP2_ERR_CALLBACK_FAILURE;
} else if(ret < 0) {
#ifndef USE_WINSOCK
if(errno == EINTR || errno == EAGAIN)
return NGHTTP2_ERR_WOULDBLOCK;
#ifdef EPIPE
if(errno == EPIPE && verbosity < 2)
return NGHTTP2_ERR_CALLBACK_FAILURE;
#endif
#ifdef ECONNRESET
if(errno == ECONNRESET && verbosity < 2)
return NGHTTP2_ERR_CALLBACK_FAILURE;
#endif
log_err_addr("could not http2 write: %s", strerror(errno),
&h2_session->c->repinfo.remote_addr,
h2_session->c->repinfo.remote_addrlen);
#else /* USE_WINSOCK */
if(WSAGetLastError() == WSAENOTCONN)
return NGHTTP2_ERR_WOULDBLOCK;
if(WSAGetLastError() == WSAEINPROGRESS)
return NGHTTP2_ERR_WOULDBLOCK;
if(WSAGetLastError() == WSAEWOULDBLOCK) {
ub_winsock_tcp_wouldblock(h2_session->c->ev->ev,
UB_EV_WRITE);
return NGHTTP2_ERR_WOULDBLOCK;
}
if(WSAGetLastError() == WSAECONNRESET && verbosity < 2)
return NGHTTP2_ERR_CALLBACK_FAILURE;
log_err_addr("could not http2 write: %s",
wsa_strerror(WSAGetLastError()),
&h2_session->c->repinfo.remote_addr,
h2_session->c->repinfo.remote_addrlen);
#endif
return NGHTTP2_ERR_CALLBACK_FAILURE;
}
return ret;
}
#endif /* HAVE_NGHTTP2 */
/** Handle http2 writing */
static int
comm_point_http2_handle_write(int ATTR_UNUSED(fd), struct comm_point* c)
{
#ifdef HAVE_NGHTTP2
int ret;
log_assert(c->h2_session);
ret = nghttp2_session_send(c->h2_session->session);
if(ret) {
verbose(VERB_QUERY, "http2: session_send failed, "
"error: %s", nghttp2_strerror(ret));
return 0;
}
if(nghttp2_session_want_read(c->h2_session->session)) {
c->tcp_is_reading = 1;
comm_point_stop_listening(c);
comm_point_start_listening(c, -1, adjusted_tcp_timeout(c));
} else if(!nghttp2_session_want_write(c->h2_session->session))
return 0; /* connection can be closed */
return 1;
#else
(void)c;
return 0;
#endif
}
/**
* Handle http writing callback.
* @param fd: file descriptor of socket.
* @param c: comm point to write buffer out of.
* @return: 0 on error
*/
static int
comm_point_http_handle_write(int fd, struct comm_point* c)
{
log_assert(c->type == comm_http);
log_assert(fd != -1);
/* check pending connect errors, if that fails, we wait for more,
* or we can continue to write contents */
if(c->tcp_check_nb_connect) {
int r = http_check_connect(fd, c);
if(r == 0) return 0;
if(r == 1) return 1;
c->tcp_check_nb_connect = 0;
}
/* if we are in ssl handshake, handle SSL handshake */
#ifdef HAVE_SSL
if(c->ssl && c->ssl_shake_state != comm_ssl_shake_none) {
if(!ssl_handshake(c))
return 0;
if(c->ssl_shake_state != comm_ssl_shake_none)
return 1;
}
#endif /* HAVE_SSL */
if(c->tcp_is_reading)
return 1;
if(c->use_h2) {
return comm_point_http2_handle_write(fd, c);
}
/* http version is <= http/1.1 */
if(c->http_min_version >= http_version_2) {
/* HTTP/2 failed, not allowed to use lower version. */
return 0;
}
/* if we are writing, write more */
if(c->ssl) {
if(!ssl_http_write_more(c))
return 0;
} else {
if(!http_write_more(fd, c))
return 0;
}
/* we write a single buffer contents, that can contain
* the http request, and then flip to read the results */
/* see if write is done */
if(sldns_buffer_remaining(c->buffer) == 0) {
sldns_buffer_clear(c->buffer);
if(c->tcp_do_toggle_rw)
c->tcp_is_reading = 1;
c->tcp_byte_count = 0;
/* switch from listening(write) to listening(read) */
comm_point_stop_listening(c);
comm_point_start_listening(c, -1, -1);
}
return 1;
}
void
comm_point_http_handle_callback(int fd, short event, void* arg)
{
struct comm_point* c = (struct comm_point*)arg;
log_assert(c->type == comm_http);
ub_comm_base_now(c->ev->base);
if(event&UB_EV_TIMEOUT) {
verbose(VERB_QUERY, "http took too long, dropped");
reclaim_http_handler(c);
if(!c->tcp_do_close) {
fptr_ok(fptr_whitelist_comm_point(c->callback));
(void)(*c->callback)(c, c->cb_arg,
NETEVENT_TIMEOUT, NULL);
}
return;
}
if(event&UB_EV_READ) {
if(!comm_point_http_handle_read(fd, c)) {
reclaim_http_handler(c);
if(!c->tcp_do_close) {
fptr_ok(fptr_whitelist_comm_point(
c->callback));
(void)(*c->callback)(c, c->cb_arg,
NETEVENT_CLOSED, NULL);
}
}
return;
}
if(event&UB_EV_WRITE) {
if(!comm_point_http_handle_write(fd, c)) {
reclaim_http_handler(c);
if(!c->tcp_do_close) {
fptr_ok(fptr_whitelist_comm_point(
c->callback));
(void)(*c->callback)(c, c->cb_arg,
NETEVENT_CLOSED, NULL);
}
}
return;
}
log_err("Ignored event %d for httphdl.", event);
}
void comm_point_local_handle_callback(int fd, short event, void* arg)
{
struct comm_point* c = (struct comm_point*)arg;
log_assert(c->type == comm_local);
ub_comm_base_now(c->ev->base);
if(event&UB_EV_READ) {
if(!comm_point_tcp_handle_read(fd, c, 1)) {
fptr_ok(fptr_whitelist_comm_point(c->callback));
(void)(*c->callback)(c, c->cb_arg, NETEVENT_CLOSED,
NULL);
}
return;
}
log_err("Ignored event %d for localhdl.", event);
}
void comm_point_raw_handle_callback(int ATTR_UNUSED(fd),
short event, void* arg)
{
struct comm_point* c = (struct comm_point*)arg;
int err = NETEVENT_NOERROR;
log_assert(c->type == comm_raw);
ub_comm_base_now(c->ev->base);
if(event&UB_EV_TIMEOUT)
err = NETEVENT_TIMEOUT;
fptr_ok(fptr_whitelist_comm_point_raw(c->callback));
(void)(*c->callback)(c, c->cb_arg, err, NULL);
}
struct comm_point*
comm_point_create_udp(struct comm_base *base, int fd, sldns_buffer* buffer,
int pp2_enabled, comm_point_callback_type* callback,
void* callback_arg, struct unbound_socket* socket)
{
struct comm_point* c = (struct comm_point*)calloc(1,
sizeof(struct comm_point));
short evbits;
if(!c)
return NULL;
c->ev = (struct internal_event*)calloc(1,
sizeof(struct internal_event));
if(!c->ev) {
free(c);
return NULL;
}
c->ev->base = base;
c->fd = fd;
c->buffer = buffer;
c->timeout = NULL;
c->tcp_is_reading = 0;
c->tcp_byte_count = 0;
c->tcp_parent = NULL;
c->max_tcp_count = 0;
c->cur_tcp_count = 0;
c->tcp_handlers = NULL;
c->tcp_free = NULL;
c->type = comm_udp;
c->tcp_do_close = 0;
c->do_not_close = 0;
c->tcp_do_toggle_rw = 0;
c->tcp_check_nb_connect = 0;
#ifdef USE_MSG_FASTOPEN
c->tcp_do_fastopen = 0;
#endif
#ifdef USE_DNSCRYPT
c->dnscrypt = 0;
c->dnscrypt_buffer = buffer;
#endif
c->inuse = 0;
c->callback = callback;
c->cb_arg = callback_arg;
c->socket = socket;
c->pp2_enabled = pp2_enabled;
c->pp2_header_state = pp2_header_none;
evbits = UB_EV_READ | UB_EV_PERSIST;
/* ub_event stuff */
c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
comm_point_udp_callback, c);
if(c->ev->ev == NULL) {
log_err("could not baseset udp event");
comm_point_delete(c);
return NULL;
}
if(fd!=-1 && ub_event_add(c->ev->ev, c->timeout) != 0 ) {
log_err("could not add udp event");
comm_point_delete(c);
return NULL;
}
c->event_added = 1;
return c;
}
#if defined(AF_INET6) && defined(IPV6_PKTINFO) && defined(HAVE_RECVMSG)
struct comm_point*
comm_point_create_udp_ancil(struct comm_base *base, int fd,
sldns_buffer* buffer, int pp2_enabled,
comm_point_callback_type* callback, void* callback_arg, struct unbound_socket* socket)
{
struct comm_point* c = (struct comm_point*)calloc(1,
sizeof(struct comm_point));
short evbits;
if(!c)
return NULL;
c->ev = (struct internal_event*)calloc(1,
sizeof(struct internal_event));
if(!c->ev) {
free(c);
return NULL;
}
c->ev->base = base;
c->fd = fd;
c->buffer = buffer;
c->timeout = NULL;
c->tcp_is_reading = 0;
c->tcp_byte_count = 0;
c->tcp_parent = NULL;
c->max_tcp_count = 0;
c->cur_tcp_count = 0;
c->tcp_handlers = NULL;
c->tcp_free = NULL;
c->type = comm_udp;
c->tcp_do_close = 0;
c->do_not_close = 0;
#ifdef USE_DNSCRYPT
c->dnscrypt = 0;
c->dnscrypt_buffer = buffer;
#endif
c->inuse = 0;
c->tcp_do_toggle_rw = 0;
c->tcp_check_nb_connect = 0;
#ifdef USE_MSG_FASTOPEN
c->tcp_do_fastopen = 0;
#endif
c->callback = callback;
c->cb_arg = callback_arg;
c->socket = socket;
c->pp2_enabled = pp2_enabled;
c->pp2_header_state = pp2_header_none;
evbits = UB_EV_READ | UB_EV_PERSIST;
/* ub_event stuff */
c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
comm_point_udp_ancil_callback, c);
if(c->ev->ev == NULL) {
log_err("could not baseset udp event");
comm_point_delete(c);
return NULL;
}
if(fd!=-1 && ub_event_add(c->ev->ev, c->timeout) != 0 ) {
log_err("could not add udp event");
comm_point_delete(c);
return NULL;
}
c->event_added = 1;
return c;
}
#endif
struct comm_point*
comm_point_create_doq(struct comm_base *base, int fd, sldns_buffer* buffer,
comm_point_callback_type* callback, void* callback_arg,
struct unbound_socket* socket, struct doq_table* table,
struct ub_randstate* rnd, const char* ssl_service_key,
const char* ssl_service_pem, struct config_file* cfg)
{
#ifdef HAVE_NGTCP2
struct comm_point* c = (struct comm_point*)calloc(1,
sizeof(struct comm_point));
short evbits;
if(!c)
return NULL;
c->ev = (struct internal_event*)calloc(1,
sizeof(struct internal_event));
if(!c->ev) {
free(c);
return NULL;
}
c->ev->base = base;
c->fd = fd;
c->buffer = buffer;
c->timeout = NULL;
c->tcp_is_reading = 0;
c->tcp_byte_count = 0;
c->tcp_parent = NULL;
c->max_tcp_count = 0;
c->cur_tcp_count = 0;
c->tcp_handlers = NULL;
c->tcp_free = NULL;
c->type = comm_doq;
c->tcp_do_close = 0;
c->do_not_close = 0;
c->tcp_do_toggle_rw = 0;
c->tcp_check_nb_connect = 0;
#ifdef USE_MSG_FASTOPEN
c->tcp_do_fastopen = 0;
#endif
#ifdef USE_DNSCRYPT
c->dnscrypt = 0;
c->dnscrypt_buffer = NULL;
#endif
#ifdef HAVE_NGTCP2
c->doq_socket = doq_server_socket_create(table, rnd, ssl_service_key,
ssl_service_pem, c, base, cfg);
if(!c->doq_socket) {
log_err("could not create doq comm_point");
comm_point_delete(c);
return NULL;
}
#endif
c->inuse = 0;
c->callback = callback;
c->cb_arg = callback_arg;
c->socket = socket;
c->pp2_enabled = 0;
c->pp2_header_state = pp2_header_none;
evbits = UB_EV_READ | UB_EV_PERSIST;
/* ub_event stuff */
c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
comm_point_doq_callback, c);
if(c->ev->ev == NULL) {
log_err("could not baseset udp event");
comm_point_delete(c);
return NULL;
}
if(fd!=-1 && ub_event_add(c->ev->ev, c->timeout) != 0 ) {
log_err("could not add udp event");
comm_point_delete(c);
return NULL;
}
c->event_added = 1;
return c;
#else
/* no libngtcp2, so no QUIC support */
(void)base;
(void)buffer;
(void)callback;
(void)callback_arg;
(void)socket;
(void)rnd;
(void)table;
(void)ssl_service_key;
(void)ssl_service_pem;
(void)cfg;
sock_close(fd);
return NULL;
#endif /* HAVE_NGTCP2 */
}
static struct comm_point*
comm_point_create_tcp_handler(struct comm_base *base,
struct comm_point* parent, size_t bufsize,
struct sldns_buffer* spoolbuf, comm_point_callback_type* callback,
void* callback_arg, struct unbound_socket* socket)
{
struct comm_point* c = (struct comm_point*)calloc(1,
sizeof(struct comm_point));
short evbits;
if(!c)
return NULL;
c->ev = (struct internal_event*)calloc(1,
sizeof(struct internal_event));
if(!c->ev) {
free(c);
return NULL;
}
c->ev->base = base;
c->fd = -1;
c->buffer = sldns_buffer_new(bufsize);
if(!c->buffer) {
free(c->ev);
free(c);
return NULL;
}
c->timeout = (struct timeval*)malloc(sizeof(struct timeval));
if(!c->timeout) {
sldns_buffer_free(c->buffer);
free(c->ev);
free(c);
return NULL;
}
c->tcp_is_reading = 0;
c->tcp_byte_count = 0;
c->tcp_parent = parent;
c->tcp_timeout_msec = parent->tcp_timeout_msec;
c->tcp_conn_limit = parent->tcp_conn_limit;
c->tcl_addr = NULL;
c->tcp_keepalive = 0;
c->max_tcp_count = 0;
c->cur_tcp_count = 0;
c->tcp_handlers = NULL;
c->tcp_free = NULL;
c->type = comm_tcp;
c->tcp_do_close = 0;
c->do_not_close = 0;
c->tcp_do_toggle_rw = 1;
c->tcp_check_nb_connect = 0;
#ifdef USE_MSG_FASTOPEN
c->tcp_do_fastopen = 0;
#endif
#ifdef USE_DNSCRYPT
c->dnscrypt = 0;
/* We don't know just yet if this is a dnscrypt channel. Allocation
* will be done when handling the callback. */
c->dnscrypt_buffer = c->buffer;
#endif
c->repinfo.c = c;
c->callback = callback;
c->cb_arg = callback_arg;
c->socket = socket;
c->pp2_enabled = parent->pp2_enabled;
c->pp2_header_state = pp2_header_none;
if(spoolbuf) {
c->tcp_req_info = tcp_req_info_create(spoolbuf);
if(!c->tcp_req_info) {
log_err("could not create tcp commpoint");
sldns_buffer_free(c->buffer);
free(c->timeout);
free(c->ev);
free(c);
return NULL;
}
c->tcp_req_info->cp = c;
c->tcp_do_close = 1;
c->tcp_do_toggle_rw = 0;
}
/* add to parent free list */
c->tcp_free = parent->tcp_free;
parent->tcp_free = c;
/* ub_event stuff */
evbits = UB_EV_PERSIST | UB_EV_READ | UB_EV_TIMEOUT;
c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
comm_point_tcp_handle_callback, c);
if(c->ev->ev == NULL)
{
log_err("could not basetset tcphdl event");
parent->tcp_free = c->tcp_free;
tcp_req_info_delete(c->tcp_req_info);
sldns_buffer_free(c->buffer);
free(c->timeout);
free(c->ev);
free(c);
return NULL;
}
return c;
}
static struct comm_point*
comm_point_create_http_handler(struct comm_base *base,
struct comm_point* parent, size_t bufsize, int harden_large_queries,
uint32_t http_max_streams, char* http_endpoint,
comm_point_callback_type* callback, void* callback_arg,
struct unbound_socket* socket)
{
struct comm_point* c = (struct comm_point*)calloc(1,
sizeof(struct comm_point));
short evbits;
if(!c)
return NULL;
c->ev = (struct internal_event*)calloc(1,
sizeof(struct internal_event));
if(!c->ev) {
free(c);
return NULL;
}
c->ev->base = base;
c->fd = -1;
c->buffer = sldns_buffer_new(bufsize);
if(!c->buffer) {
free(c->ev);
free(c);
return NULL;
}
c->timeout = (struct timeval*)malloc(sizeof(struct timeval));
if(!c->timeout) {
sldns_buffer_free(c->buffer);
free(c->ev);
free(c);
return NULL;
}
c->tcp_is_reading = 0;
c->tcp_byte_count = 0;
c->tcp_parent = parent;
c->tcp_timeout_msec = parent->tcp_timeout_msec;
c->tcp_conn_limit = parent->tcp_conn_limit;
c->tcl_addr = NULL;
c->tcp_keepalive = 0;
c->max_tcp_count = 0;
c->cur_tcp_count = 0;
c->tcp_handlers = NULL;
c->tcp_free = NULL;
c->type = comm_http;
c->tcp_do_close = 1;
c->do_not_close = 0;
c->tcp_do_toggle_rw = 1; /* will be set to 0 after http2 upgrade */
c->tcp_check_nb_connect = 0;
#ifdef USE_MSG_FASTOPEN
c->tcp_do_fastopen = 0;
#endif
#ifdef USE_DNSCRYPT
c->dnscrypt = 0;
c->dnscrypt_buffer = NULL;
#endif
c->repinfo.c = c;
c->callback = callback;
c->cb_arg = callback_arg;
c->socket = socket;
c->pp2_enabled = 0;
c->pp2_header_state = pp2_header_none;
c->http_min_version = http_version_2;
c->http2_stream_max_qbuffer_size = bufsize;
if(harden_large_queries && bufsize > 512)
c->http2_stream_max_qbuffer_size = 512;
c->http2_max_streams = http_max_streams;
if(!(c->http_endpoint = strdup(http_endpoint))) {
log_err("could not strdup http_endpoint");
sldns_buffer_free(c->buffer);
free(c->timeout);
free(c->ev);
free(c);
return NULL;
}
c->use_h2 = 0;
#ifdef HAVE_NGHTTP2
if(!(c->h2_session = http2_session_create(c))) {
log_err("could not create http2 session");
free(c->http_endpoint);
sldns_buffer_free(c->buffer);
free(c->timeout);
free(c->ev);
free(c);
return NULL;
}
if(!(c->h2_session->callbacks = http2_req_callbacks_create())) {
log_err("could not create http2 callbacks");
http2_session_delete(c->h2_session);
free(c->http_endpoint);
sldns_buffer_free(c->buffer);
free(c->timeout);
free(c->ev);
free(c);
return NULL;
}
#endif
/* add to parent free list */
c->tcp_free = parent->tcp_free;
parent->tcp_free = c;
/* ub_event stuff */
evbits = UB_EV_PERSIST | UB_EV_READ | UB_EV_TIMEOUT;
c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
comm_point_http_handle_callback, c);
if(c->ev->ev == NULL)
{
log_err("could not set http handler event");
parent->tcp_free = c->tcp_free;
http2_session_delete(c->h2_session);
sldns_buffer_free(c->buffer);
free(c->timeout);
free(c->ev);
free(c);
return NULL;
}
return c;
}
struct comm_point*
comm_point_create_tcp(struct comm_base *base, int fd, int num,
int idle_timeout, int harden_large_queries,
uint32_t http_max_streams, char* http_endpoint,
struct tcl_list* tcp_conn_limit, size_t bufsize,
struct sldns_buffer* spoolbuf, enum listen_type port_type,
int pp2_enabled, comm_point_callback_type* callback,
void* callback_arg, struct unbound_socket* socket)
{
struct comm_point* c = (struct comm_point*)calloc(1,
sizeof(struct comm_point));
short evbits;
int i;
/* first allocate the TCP accept listener */
if(!c)
return NULL;
c->ev = (struct internal_event*)calloc(1,
sizeof(struct internal_event));
if(!c->ev) {
free(c);
return NULL;
}
c->ev->base = base;
c->fd = fd;
c->buffer = NULL;
c->timeout = NULL;
c->tcp_is_reading = 0;
c->tcp_byte_count = 0;
c->tcp_timeout_msec = idle_timeout;
c->tcp_conn_limit = tcp_conn_limit;
c->tcl_addr = NULL;
c->tcp_keepalive = 0;
c->tcp_parent = NULL;
c->max_tcp_count = num;
c->cur_tcp_count = 0;
c->tcp_handlers = (struct comm_point**)calloc((size_t)num,
sizeof(struct comm_point*));
if(!c->tcp_handlers) {
free(c->ev);
free(c);
return NULL;
}
c->tcp_free = NULL;
c->type = comm_tcp_accept;
c->tcp_do_close = 0;
c->do_not_close = 0;
c->tcp_do_toggle_rw = 0;
c->tcp_check_nb_connect = 0;
#ifdef USE_MSG_FASTOPEN
c->tcp_do_fastopen = 0;
#endif
#ifdef USE_DNSCRYPT
c->dnscrypt = 0;
c->dnscrypt_buffer = NULL;
#endif
c->callback = NULL;
c->cb_arg = NULL;
c->socket = socket;
c->pp2_enabled = (port_type==listen_type_http?0:pp2_enabled);
c->pp2_header_state = pp2_header_none;
evbits = UB_EV_READ | UB_EV_PERSIST;
/* ub_event stuff */
c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
comm_point_tcp_accept_callback, c);
if(c->ev->ev == NULL) {
log_err("could not baseset tcpacc event");
comm_point_delete(c);
return NULL;
}
if (ub_event_add(c->ev->ev, c->timeout) != 0) {
log_err("could not add tcpacc event");
comm_point_delete(c);
return NULL;
}
c->event_added = 1;
/* now prealloc the handlers */
for(i=0; i<num; i++) {
if(port_type == listen_type_tcp ||
port_type == listen_type_ssl ||
port_type == listen_type_tcp_dnscrypt) {
c->tcp_handlers[i] = comm_point_create_tcp_handler(base,
c, bufsize, spoolbuf, callback, callback_arg, socket);
} else if(port_type == listen_type_http) {
c->tcp_handlers[i] = comm_point_create_http_handler(
base, c, bufsize, harden_large_queries,
http_max_streams, http_endpoint,
callback, callback_arg, socket);
}
else {
log_err("could not create tcp handler, unknown listen "
"type");
return NULL;
}
if(!c->tcp_handlers[i]) {
comm_point_delete(c);
return NULL;
}
}
return c;
}
struct comm_point*
comm_point_create_tcp_out(struct comm_base *base, size_t bufsize,
comm_point_callback_type* callback, void* callback_arg)
{
struct comm_point* c = (struct comm_point*)calloc(1,
sizeof(struct comm_point));
short evbits;
if(!c)
return NULL;
c->ev = (struct internal_event*)calloc(1,
sizeof(struct internal_event));
if(!c->ev) {
free(c);
return NULL;
}
c->ev->base = base;
c->fd = -1;
c->buffer = sldns_buffer_new(bufsize);
if(!c->buffer) {
free(c->ev);
free(c);
return NULL;
}
c->timeout = NULL;
c->tcp_is_reading = 0;
c->tcp_byte_count = 0;
c->tcp_timeout_msec = TCP_QUERY_TIMEOUT;
c->tcp_conn_limit = NULL;
c->tcl_addr = NULL;
c->tcp_keepalive = 0;
c->tcp_parent = NULL;
c->max_tcp_count = 0;
c->cur_tcp_count = 0;
c->tcp_handlers = NULL;
c->tcp_free = NULL;
c->type = comm_tcp;
c->tcp_do_close = 0;
c->do_not_close = 0;
c->tcp_do_toggle_rw = 1;
c->tcp_check_nb_connect = 1;
#ifdef USE_MSG_FASTOPEN
c->tcp_do_fastopen = 1;
#endif
#ifdef USE_DNSCRYPT
c->dnscrypt = 0;
c->dnscrypt_buffer = c->buffer;
#endif
c->repinfo.c = c;
c->callback = callback;
c->cb_arg = callback_arg;
c->pp2_enabled = 0;
c->pp2_header_state = pp2_header_none;
evbits = UB_EV_PERSIST | UB_EV_WRITE;
c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
comm_point_tcp_handle_callback, c);
if(c->ev->ev == NULL)
{
log_err("could not baseset tcpout event");
sldns_buffer_free(c->buffer);
free(c->ev);
free(c);
return NULL;
}
return c;
}
struct comm_point*
comm_point_create_http_out(struct comm_base *base, size_t bufsize,
comm_point_callback_type* callback, void* callback_arg,
sldns_buffer* temp)
{
struct comm_point* c = (struct comm_point*)calloc(1,
sizeof(struct comm_point));
short evbits;
if(!c)
return NULL;
c->ev = (struct internal_event*)calloc(1,
sizeof(struct internal_event));
if(!c->ev) {
free(c);
return NULL;
}
c->ev->base = base;
c->fd = -1;
c->buffer = sldns_buffer_new(bufsize);
if(!c->buffer) {
free(c->ev);
free(c);
return NULL;
}
c->timeout = NULL;
c->tcp_is_reading = 0;
c->tcp_byte_count = 0;
c->tcp_parent = NULL;
c->max_tcp_count = 0;
c->cur_tcp_count = 0;
c->tcp_handlers = NULL;
c->tcp_free = NULL;
c->type = comm_http;
c->tcp_do_close = 0;
c->do_not_close = 0;
c->tcp_do_toggle_rw = 1;
c->tcp_check_nb_connect = 1;
c->http_in_headers = 1;
c->http_in_chunk_headers = 0;
c->http_is_chunked = 0;
c->http_temp = temp;
#ifdef USE_MSG_FASTOPEN
c->tcp_do_fastopen = 1;
#endif
#ifdef USE_DNSCRYPT
c->dnscrypt = 0;
c->dnscrypt_buffer = c->buffer;
#endif
c->repinfo.c = c;
c->callback = callback;
c->cb_arg = callback_arg;
c->pp2_enabled = 0;
c->pp2_header_state = pp2_header_none;
evbits = UB_EV_PERSIST | UB_EV_WRITE;
c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
comm_point_http_handle_callback, c);
if(c->ev->ev == NULL)
{
log_err("could not baseset tcpout event");
#ifdef HAVE_SSL
SSL_free(c->ssl);
#endif
sldns_buffer_free(c->buffer);
free(c->ev);
free(c);
return NULL;
}
return c;
}
struct comm_point*
comm_point_create_local(struct comm_base *base, int fd, size_t bufsize,
comm_point_callback_type* callback, void* callback_arg)
{
struct comm_point* c = (struct comm_point*)calloc(1,
sizeof(struct comm_point));
short evbits;
if(!c)
return NULL;
c->ev = (struct internal_event*)calloc(1,
sizeof(struct internal_event));
if(!c->ev) {
free(c);
return NULL;
}
c->ev->base = base;
c->fd = fd;
c->buffer = sldns_buffer_new(bufsize);
if(!c->buffer) {
free(c->ev);
free(c);
return NULL;
}
c->timeout = NULL;
c->tcp_is_reading = 1;
c->tcp_byte_count = 0;
c->tcp_parent = NULL;
c->max_tcp_count = 0;
c->cur_tcp_count = 0;
c->tcp_handlers = NULL;
c->tcp_free = NULL;
c->type = comm_local;
c->tcp_do_close = 0;
c->do_not_close = 1;
c->tcp_do_toggle_rw = 0;
c->tcp_check_nb_connect = 0;
#ifdef USE_MSG_FASTOPEN
c->tcp_do_fastopen = 0;
#endif
#ifdef USE_DNSCRYPT
c->dnscrypt = 0;
c->dnscrypt_buffer = c->buffer;
#endif
c->callback = callback;
c->cb_arg = callback_arg;
c->pp2_enabled = 0;
c->pp2_header_state = pp2_header_none;
/* ub_event stuff */
evbits = UB_EV_PERSIST | UB_EV_READ;
c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
comm_point_local_handle_callback, c);
if(c->ev->ev == NULL) {
log_err("could not baseset localhdl event");
free(c->ev);
free(c);
return NULL;
}
if (ub_event_add(c->ev->ev, c->timeout) != 0) {
log_err("could not add localhdl event");
ub_event_free(c->ev->ev);
free(c->ev);
free(c);
return NULL;
}
c->event_added = 1;
return c;
}
struct comm_point*
comm_point_create_raw(struct comm_base* base, int fd, int writing,
comm_point_callback_type* callback, void* callback_arg)
{
struct comm_point* c = (struct comm_point*)calloc(1,
sizeof(struct comm_point));
short evbits;
if(!c)
return NULL;
c->ev = (struct internal_event*)calloc(1,
sizeof(struct internal_event));
if(!c->ev) {
free(c);
return NULL;
}
c->ev->base = base;
c->fd = fd;
c->buffer = NULL;
c->timeout = NULL;
c->tcp_is_reading = 0;
c->tcp_byte_count = 0;
c->tcp_parent = NULL;
c->max_tcp_count = 0;
c->cur_tcp_count = 0;
c->tcp_handlers = NULL;
c->tcp_free = NULL;
c->type = comm_raw;
c->tcp_do_close = 0;
c->do_not_close = 1;
c->tcp_do_toggle_rw = 0;
c->tcp_check_nb_connect = 0;
#ifdef USE_MSG_FASTOPEN
c->tcp_do_fastopen = 0;
#endif
#ifdef USE_DNSCRYPT
c->dnscrypt = 0;
c->dnscrypt_buffer = c->buffer;
#endif
c->callback = callback;
c->cb_arg = callback_arg;
c->pp2_enabled = 0;
c->pp2_header_state = pp2_header_none;
/* ub_event stuff */
if(writing)
evbits = UB_EV_PERSIST | UB_EV_WRITE;
else evbits = UB_EV_PERSIST | UB_EV_READ;
c->ev->ev = ub_event_new(base->eb->base, c->fd, evbits,
comm_point_raw_handle_callback, c);
if(c->ev->ev == NULL) {
log_err("could not baseset rawhdl event");
free(c->ev);
free(c);
return NULL;
}
if (ub_event_add(c->ev->ev, c->timeout) != 0) {
log_err("could not add rawhdl event");
ub_event_free(c->ev->ev);
free(c->ev);
free(c);
return NULL;
}
c->event_added = 1;
return c;
}
void
comm_point_close(struct comm_point* c)
{
if(!c)
return;
if(c->fd != -1) {
verbose(5, "comm_point_close of %d: event_del", c->fd);
if(c->event_added) {
if(ub_event_del(c->ev->ev) != 0) {
log_err("could not event_del on close");
}
c->event_added = 0;
}
}
tcl_close_connection(c->tcl_addr);
if(c->tcp_req_info)
tcp_req_info_clear(c->tcp_req_info);
if(c->h2_session)
http2_session_server_delete(c->h2_session);
/* stop the comm point from reading or writing after it is closed. */
if(c->tcp_more_read_again && *c->tcp_more_read_again)
*c->tcp_more_read_again = 0;
if(c->tcp_more_write_again && *c->tcp_more_write_again)
*c->tcp_more_write_again = 0;
/* close fd after removing from event lists, or epoll.. is messed up */
if(c->fd != -1 && !c->do_not_close) {
#ifdef USE_WINSOCK
if(c->type == comm_tcp || c->type == comm_http) {
/* delete sticky events for the fd, it gets closed */
ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_READ);
ub_winsock_tcp_wouldblock(c->ev->ev, UB_EV_WRITE);
}
#endif
verbose(VERB_ALGO, "close fd %d", c->fd);
sock_close(c->fd);
}
c->fd = -1;
}
void
comm_point_delete(struct comm_point* c)
{
if(!c)
return;
if((c->type == comm_tcp || c->type == comm_http) && c->ssl) {
#ifdef HAVE_SSL
SSL_shutdown(c->ssl);
SSL_free(c->ssl);
#endif
}
if(c->type == comm_http && c->http_endpoint) {
free(c->http_endpoint);
c->http_endpoint = NULL;
}
comm_point_close(c);
if(c->tcp_handlers) {
int i;
for(i=0; i<c->max_tcp_count; i++)
comm_point_delete(c->tcp_handlers[i]);
free(c->tcp_handlers);
}
free(c->timeout);
if(c->type == comm_tcp || c->type == comm_local || c->type == comm_http) {
sldns_buffer_free(c->buffer);
#ifdef USE_DNSCRYPT
if(c->dnscrypt && c->dnscrypt_buffer != c->buffer) {
sldns_buffer_free(c->dnscrypt_buffer);
}
#endif
if(c->tcp_req_info) {
tcp_req_info_delete(c->tcp_req_info);
}
if(c->h2_session) {
http2_session_delete(c->h2_session);
}
}
#ifdef HAVE_NGTCP2
if(c->doq_socket)
doq_server_socket_delete(c->doq_socket);
#endif
ub_event_free(c->ev->ev);
free(c->ev);
free(c);
}
#ifdef USE_DNSTAP
static void
send_reply_dnstap(struct dt_env* dtenv,
struct sockaddr* addr, socklen_t addrlen,
struct sockaddr_storage* client_addr, socklen_t client_addrlen,
enum comm_point_type type, void* ssl, sldns_buffer* buffer)
{
log_addr(VERB_ALGO, "from local addr", (void*)addr, addrlen);
log_addr(VERB_ALGO, "response to client", client_addr, client_addrlen);
dt_msg_send_client_response(dtenv, client_addr,
(struct sockaddr_storage*)addr, type, ssl, buffer);
}
#endif
void
comm_point_send_reply(struct comm_reply *repinfo)
{
struct sldns_buffer* buffer;
log_assert(repinfo && repinfo->c);
#ifdef USE_DNSCRYPT
buffer = repinfo->c->dnscrypt_buffer;
if(!dnsc_handle_uncurved_request(repinfo)) {
return;
}
#else
buffer = repinfo->c->buffer;
#endif
if(repinfo->c->type == comm_udp) {
if(repinfo->srctype)
comm_point_send_udp_msg_if(repinfo->c, buffer,
(struct sockaddr*)&repinfo->remote_addr,
repinfo->remote_addrlen, repinfo);
else
comm_point_send_udp_msg(repinfo->c, buffer,
(struct sockaddr*)&repinfo->remote_addr,
repinfo->remote_addrlen, 0);
#ifdef USE_DNSTAP
/*
* sending src (client)/dst (local service) addresses over
* DNSTAP from udp callback
*/
if(repinfo->c->dtenv != NULL && repinfo->c->dtenv->log_client_response_messages) {
send_reply_dnstap(repinfo->c->dtenv,
repinfo->c->socket->addr,
repinfo->c->socket->addrlen,
&repinfo->client_addr, repinfo->client_addrlen,
repinfo->c->type, repinfo->c->ssl,
repinfo->c->buffer);
}
#endif
} else {
#ifdef USE_DNSTAP
struct dt_env* dtenv =
#ifdef HAVE_NGTCP2
repinfo->c->doq_socket
?repinfo->c->dtenv:
#endif
repinfo->c->tcp_parent->dtenv;
struct sldns_buffer* dtbuffer = repinfo->c->tcp_req_info
?repinfo->c->tcp_req_info->spool_buffer
:repinfo->c->buffer;
#ifdef USE_DNSCRYPT
if(repinfo->c->dnscrypt && repinfo->is_dnscrypted)
dtbuffer = repinfo->c->buffer;
#endif
/*
* sending src (client)/dst (local service) addresses over
* DNSTAP from other callbacks
*/
if(dtenv != NULL && dtenv->log_client_response_messages) {
send_reply_dnstap(dtenv,
repinfo->c->socket->addr,
repinfo->c->socket->addrlen,
&repinfo->client_addr, repinfo->client_addrlen,
repinfo->c->type, repinfo->c->ssl,
dtbuffer);
}
#endif
if(repinfo->c->tcp_req_info) {
tcp_req_info_send_reply(repinfo->c->tcp_req_info);
} else if(repinfo->c->use_h2) {
if(!http2_submit_dns_response(repinfo->c->h2_session)) {
comm_point_drop_reply(repinfo);
return;
}
repinfo->c->h2_stream = NULL;
repinfo->c->tcp_is_reading = 0;
comm_point_stop_listening(repinfo->c);
comm_point_start_listening(repinfo->c, -1,
adjusted_tcp_timeout(repinfo->c));
return;
#ifdef HAVE_NGTCP2
} else if(repinfo->c->doq_socket) {
doq_socket_send_reply(repinfo);
#endif
} else {
comm_point_start_listening(repinfo->c, -1,
adjusted_tcp_timeout(repinfo->c));
}
}
}
void
comm_point_drop_reply(struct comm_reply* repinfo)
{
if(!repinfo)
return;
log_assert(repinfo->c);
log_assert(repinfo->c->type != comm_tcp_accept);
if(repinfo->c->type == comm_udp)
return;
if(repinfo->c->tcp_req_info)
repinfo->c->tcp_req_info->is_drop = 1;
if(repinfo->c->type == comm_http) {
if(repinfo->c->h2_session) {
repinfo->c->h2_session->is_drop = 1;
if(!repinfo->c->h2_session->postpone_drop)
reclaim_http_handler(repinfo->c);
return;
}
reclaim_http_handler(repinfo->c);
return;
#ifdef HAVE_NGTCP2
} else if(repinfo->c->type == comm_doq) {
doq_socket_drop_reply(repinfo);
return;
#endif
}
reclaim_tcp_handler(repinfo->c);
}
void
comm_point_stop_listening(struct comm_point* c)
{
verbose(VERB_ALGO, "comm point stop listening %d", c->fd);
if(c->event_added) {
if(ub_event_del(c->ev->ev) != 0) {
log_err("event_del error to stoplisten");
}
c->event_added = 0;
}
}
void
comm_point_start_listening(struct comm_point* c, int newfd, int msec)
{
verbose(VERB_ALGO, "comm point start listening %d (%d msec)",
c->fd==-1?newfd:c->fd, msec);
if(c->type == comm_tcp_accept && !c->tcp_free) {
/* no use to start listening no free slots. */
return;
}
if(c->event_added) {
if(ub_event_del(c->ev->ev) != 0) {
log_err("event_del error to startlisten");
}
c->event_added = 0;
}
if(msec != -1 && msec != 0) {
if(!c->timeout) {
c->timeout = (struct timeval*)malloc(sizeof(
struct timeval));
if(!c->timeout) {
log_err("cpsl: malloc failed. No net read.");
return;
}
}
ub_event_add_bits(c->ev->ev, UB_EV_TIMEOUT);
#ifndef S_SPLINT_S /* splint fails on struct timeval. */
c->timeout->tv_sec = msec/1000;
c->timeout->tv_usec = (msec%1000)*1000;
#endif /* S_SPLINT_S */
} else {
if(msec == 0 || !c->timeout) {
ub_event_del_bits(c->ev->ev, UB_EV_TIMEOUT);
}
}
if(c->type == comm_tcp || c->type == comm_http) {
ub_event_del_bits(c->ev->ev, UB_EV_READ|UB_EV_WRITE);
if(c->tcp_write_and_read) {
verbose(5, "startlistening %d mode rw", (newfd==-1?c->fd:newfd));
ub_event_add_bits(c->ev->ev, UB_EV_READ|UB_EV_WRITE);
} else if(c->tcp_is_reading) {
verbose(5, "startlistening %d mode r", (newfd==-1?c->fd:newfd));
ub_event_add_bits(c->ev->ev, UB_EV_READ);
} else {
verbose(5, "startlistening %d mode w", (newfd==-1?c->fd:newfd));
ub_event_add_bits(c->ev->ev, UB_EV_WRITE);
}
}
if(newfd != -1) {
if(c->fd != -1 && c->fd != newfd) {
verbose(5, "cpsl close of fd %d for %d", c->fd, newfd);
sock_close(c->fd);
}
c->fd = newfd;
ub_event_set_fd(c->ev->ev, c->fd);
}
if(ub_event_add(c->ev->ev, msec==0?NULL:c->timeout) != 0) {
log_err("event_add failed. in cpsl.");
return;
}
c->event_added = 1;
}
void comm_point_listen_for_rw(struct comm_point* c, int rd, int wr)
{
verbose(VERB_ALGO, "comm point listen_for_rw %d %d", c->fd, wr);
if(c->event_added) {
if(ub_event_del(c->ev->ev) != 0) {
log_err("event_del error to cplf");
}
c->event_added = 0;
}
if(!c->timeout) {
ub_event_del_bits(c->ev->ev, UB_EV_TIMEOUT);
}
ub_event_del_bits(c->ev->ev, UB_EV_READ|UB_EV_WRITE);
if(rd) ub_event_add_bits(c->ev->ev, UB_EV_READ);
if(wr) ub_event_add_bits(c->ev->ev, UB_EV_WRITE);
if(ub_event_add(c->ev->ev, c->timeout) != 0) {
log_err("event_add failed. in cplf.");
return;
}
c->event_added = 1;
}
size_t comm_point_get_mem(struct comm_point* c)
{
size_t s;
if(!c)
return 0;
s = sizeof(*c) + sizeof(*c->ev);
if(c->timeout)
s += sizeof(*c->timeout);
if(c->type == comm_tcp || c->type == comm_local) {
s += sizeof(*c->buffer) + sldns_buffer_capacity(c->buffer);
#ifdef USE_DNSCRYPT
s += sizeof(*c->dnscrypt_buffer);
if(c->buffer != c->dnscrypt_buffer) {
s += sldns_buffer_capacity(c->dnscrypt_buffer);
}
#endif
}
if(c->type == comm_tcp_accept) {
int i;
for(i=0; i<c->max_tcp_count; i++)
s += comm_point_get_mem(c->tcp_handlers[i]);
}
return s;
}
struct comm_timer*
comm_timer_create(struct comm_base* base, void (*cb)(void*), void* cb_arg)
{
struct internal_timer *tm = (struct internal_timer*)calloc(1,
sizeof(struct internal_timer));
if(!tm) {
log_err("malloc failed");
return NULL;
}
tm->super.ev_timer = tm;
tm->base = base;
tm->super.callback = cb;
tm->super.cb_arg = cb_arg;
tm->ev = ub_event_new(base->eb->base, -1, UB_EV_TIMEOUT,
comm_timer_callback, &tm->super);
if(tm->ev == NULL) {
log_err("timer_create: event_base_set failed.");
free(tm);
return NULL;
}
return &tm->super;
}
void
comm_timer_disable(struct comm_timer* timer)
{
if(!timer)
return;
ub_timer_del(timer->ev_timer->ev);
timer->ev_timer->enabled = 0;
}
void
comm_timer_set(struct comm_timer* timer, struct timeval* tv)
{
log_assert(tv);
if(timer->ev_timer->enabled)
comm_timer_disable(timer);
if(ub_timer_add(timer->ev_timer->ev, timer->ev_timer->base->eb->base,
comm_timer_callback, timer, tv) != 0)
log_err("comm_timer_set: evtimer_add failed.");
timer->ev_timer->enabled = 1;
}
void
comm_timer_delete(struct comm_timer* timer)
{
if(!timer)
return;
comm_timer_disable(timer);
/* Free the sub struct timer->ev_timer derived from the super struct timer.
* i.e. assert(timer == timer->ev_timer)
*/
ub_event_free(timer->ev_timer->ev);
free(timer->ev_timer);
}
void
comm_timer_callback(int ATTR_UNUSED(fd), short event, void* arg)
{
struct comm_timer* tm = (struct comm_timer*)arg;
if(!(event&UB_EV_TIMEOUT))
return;
ub_comm_base_now(tm->ev_timer->base);
tm->ev_timer->enabled = 0;
fptr_ok(fptr_whitelist_comm_timer(tm->callback));
(*tm->callback)(tm->cb_arg);
}
int
comm_timer_is_set(struct comm_timer* timer)
{
return (int)timer->ev_timer->enabled;
}
size_t
comm_timer_get_mem(struct comm_timer* ATTR_UNUSED(timer))
{
return sizeof(struct internal_timer);
}
struct comm_signal*
comm_signal_create(struct comm_base* base,
void (*callback)(int, void*), void* cb_arg)
{
struct comm_signal* com = (struct comm_signal*)malloc(
sizeof(struct comm_signal));
if(!com) {
log_err("malloc failed");
return NULL;
}
com->base = base;
com->callback = callback;
com->cb_arg = cb_arg;
com->ev_signal = NULL;
return com;
}
void
comm_signal_callback(int sig, short event, void* arg)
{
struct comm_signal* comsig = (struct comm_signal*)arg;
if(!(event & UB_EV_SIGNAL))
return;
ub_comm_base_now(comsig->base);
fptr_ok(fptr_whitelist_comm_signal(comsig->callback));
(*comsig->callback)(sig, comsig->cb_arg);
}
int
comm_signal_bind(struct comm_signal* comsig, int sig)
{
struct internal_signal* entry = (struct internal_signal*)calloc(1,
sizeof(struct internal_signal));
if(!entry) {
log_err("malloc failed");
return 0;
}
log_assert(comsig);
/* add signal event */
entry->ev = ub_signal_new(comsig->base->eb->base, sig,
comm_signal_callback, comsig);
if(entry->ev == NULL) {
log_err("Could not create signal event");
free(entry);
return 0;
}
if(ub_signal_add(entry->ev, NULL) != 0) {
log_err("Could not add signal handler");
ub_event_free(entry->ev);
free(entry);
return 0;
}
/* link into list */
entry->next = comsig->ev_signal;
comsig->ev_signal = entry;
return 1;
}
void
comm_signal_delete(struct comm_signal* comsig)
{
struct internal_signal* p, *np;
if(!comsig)
return;
p=comsig->ev_signal;
while(p) {
np = p->next;
ub_signal_del(p->ev);
ub_event_free(p->ev);
free(p);
p = np;
}
free(comsig);
}
|