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
|
/*
* Name server resolution
*
* Copyright 2014 Baptiste Assmann <bedis9@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <import/ebistree.h>
#include <haproxy/action.h>
#include <haproxy/api.h>
#include <haproxy/applet.h>
#include <haproxy/cfgparse.h>
#include <haproxy/channel.h>
#include <haproxy/check.h>
#include <haproxy/cli.h>
#include <haproxy/dns.h>
#include <haproxy/dns_ring.h>
#include <haproxy/errors.h>
#include <haproxy/fd.h>
#include <haproxy/http_rules.h>
#include <haproxy/log.h>
#include <haproxy/net_helper.h>
#include <haproxy/protocol.h>
#include <haproxy/proxy.h>
#include <haproxy/resolvers.h>
#include <haproxy/sample.h>
#include <haproxy/sc_strm.h>
#include <haproxy/server.h>
#include <haproxy/stats.h>
#include <haproxy/stconn.h>
#include <haproxy/task.h>
#include <haproxy/tcp_rules.h>
#include <haproxy/ticks.h>
#include <haproxy/time.h>
#include <haproxy/tools.h>
#include <haproxy/vars.h>
#include <haproxy/xxhash.h>
#if defined(USE_PROMEX)
#include <promex/promex.h>
#endif
struct list sec_resolvers = LIST_HEAD_INIT(sec_resolvers);
struct list resolv_srvrq_list = LIST_HEAD_INIT(resolv_srvrq_list);
static THREAD_LOCAL struct list death_row; /* list of deferred resolutions to kill, local validity only */
static THREAD_LOCAL unsigned int recurse = 0; /* counter to track calls to public functions */
static THREAD_LOCAL uint64_t resolv_query_id_seed = 0; /* random seed */
struct resolvers *curr_resolvers = NULL;
DECLARE_STATIC_POOL(resolv_answer_item_pool, "resolv_answer_item", sizeof(struct resolv_answer_item));
DECLARE_STATIC_POOL(resolv_resolution_pool, "resolv_resolution", sizeof(struct resolv_resolution));
DECLARE_POOL(resolv_requester_pool, "resolv_requester", sizeof(struct resolv_requester));
static unsigned int resolution_uuid = 1;
unsigned int resolv_failed_resolutions = 0;
struct task *process_resolvers(struct task *t, void *context, unsigned int state);
static void resolv_free_resolution(struct resolv_resolution *resolution);
static void _resolv_unlink_resolution(struct resolv_requester *requester);
static void enter_resolver_code();
static void leave_resolver_code();
enum {
RSLV_STAT_ID,
RSLV_STAT_PID,
RSLV_STAT_SENT,
RSLV_STAT_SND_ERROR,
RSLV_STAT_VALID,
RSLV_STAT_UPDATE,
RSLV_STAT_CNAME,
RSLV_STAT_CNAME_ERROR,
RSLV_STAT_ANY_ERR,
RSLV_STAT_NX,
RSLV_STAT_TIMEOUT,
RSLV_STAT_REFUSED,
RSLV_STAT_OTHER,
RSLV_STAT_INVALID,
RSLV_STAT_TOO_BIG,
RSLV_STAT_TRUNCATED,
RSLV_STAT_OUTDATED,
RSLV_STAT_END,
};
static struct stat_col resolv_stats[] = {
[RSLV_STAT_ID] = { .name = "id", .desc = "ID" },
[RSLV_STAT_PID] = { .name = "pid", .desc = "Parent ID" },
[RSLV_STAT_SENT] = { .name = "sent", .desc = "Sent" },
[RSLV_STAT_SND_ERROR] = { .name = "send_error", .desc = "Send error" },
[RSLV_STAT_VALID] = { .name = "valid", .desc = "Valid" },
[RSLV_STAT_UPDATE] = { .name = "update", .desc = "Update" },
[RSLV_STAT_CNAME] = { .name = "cname", .desc = "CNAME" },
[RSLV_STAT_CNAME_ERROR] = { .name = "cname_error", .desc = "CNAME error" },
[RSLV_STAT_ANY_ERR] = { .name = "any_err", .desc = "Any errors" },
[RSLV_STAT_NX] = { .name = "nx", .desc = "NX" },
[RSLV_STAT_TIMEOUT] = { .name = "timeout", .desc = "Timeout" },
[RSLV_STAT_REFUSED] = { .name = "refused", .desc = "Refused" },
[RSLV_STAT_OTHER] = { .name = "other", .desc = "Other" },
[RSLV_STAT_INVALID] = { .name = "invalid", .desc = "Invalid" },
[RSLV_STAT_TOO_BIG] = { .name = "too_big", .desc = "Too big" },
[RSLV_STAT_TRUNCATED] = { .name = "truncated", .desc = "Truncated" },
[RSLV_STAT_OUTDATED] = { .name = "outdated", .desc = "Outdated" },
};
static struct dns_counters dns_counters;
static int resolv_fill_stats(void *d, struct field *stats, unsigned int *selected_field)
{
struct dns_counters *counters = d;
unsigned int current_field = (selected_field != NULL ? *selected_field : 0);
for (; current_field < RSLV_STAT_END; current_field++) {
struct field metric = { 0 };
switch (current_field) {
case RSLV_STAT_ID:
metric = mkf_str(FO_CONFIG, counters->id);
break;
case RSLV_STAT_PID:
metric = mkf_str(FO_CONFIG, counters->pid);
break;
case RSLV_STAT_SENT:
metric = mkf_u64(FN_GAUGE, counters->sent);
break;
case RSLV_STAT_SND_ERROR:
metric = mkf_u64(FN_GAUGE, counters->snd_error);
break;
case RSLV_STAT_VALID:
metric = mkf_u64(FN_GAUGE, counters->app.resolver.valid);
break;
case RSLV_STAT_UPDATE:
metric = mkf_u64(FN_GAUGE, counters->app.resolver.update);
break;
case RSLV_STAT_CNAME:
metric = mkf_u64(FN_GAUGE, counters->app.resolver.cname);
break;
case RSLV_STAT_CNAME_ERROR:
metric = mkf_u64(FN_GAUGE, counters->app.resolver.cname_error);
break;
case RSLV_STAT_ANY_ERR:
metric = mkf_u64(FN_GAUGE, counters->app.resolver.any_err);
break;
case RSLV_STAT_NX:
metric = mkf_u64(FN_GAUGE, counters->app.resolver.nx);
break;
case RSLV_STAT_TIMEOUT:
metric = mkf_u64(FN_GAUGE, counters->app.resolver.timeout);
break;
case RSLV_STAT_REFUSED:
metric = mkf_u64(FN_GAUGE, counters->app.resolver.refused);
break;
case RSLV_STAT_OTHER:
metric = mkf_u64(FN_GAUGE, counters->app.resolver.other);
break;
case RSLV_STAT_INVALID:
metric = mkf_u64(FN_GAUGE, counters->app.resolver.invalid);
break;
case RSLV_STAT_TOO_BIG:
metric = mkf_u64(FN_GAUGE, counters->app.resolver.too_big);
break;
case RSLV_STAT_TRUNCATED:
metric = mkf_u64(FN_GAUGE, counters->app.resolver.truncated);
break;
case RSLV_STAT_OUTDATED:
metric = mkf_u64(FN_GAUGE, counters->app.resolver.outdated);
break;
default:
/* not used for frontends. If a specific metric
* is requested, return an error. Otherwise continue.
*/
if (selected_field != NULL)
return 0;
continue;
}
stats[current_field] = metric;
if (selected_field != NULL)
break;
}
return 1;
}
static struct stats_module rslv_stats_module = {
.name = "resolvers",
.domain_flags = STATS_DOMAIN_RESOLVERS << STATS_DOMAIN,
.fill_stats = resolv_fill_stats,
.stats = resolv_stats,
.stats_count = RSLV_STAT_END,
.counters = &dns_counters,
.counters_size = sizeof(dns_counters),
.clearable = 0,
};
INITCALL1(STG_REGISTER, stats_register_module, &rslv_stats_module);
/* CLI context used during "show resolvers" */
struct show_resolvers_ctx {
struct resolvers *forced_section;
struct resolvers *resolvers;
struct dns_nameserver *ns;
};
/* Returns a pointer to the resolvers matching the id <id>. NULL is returned if
* no match is found.
*/
struct resolvers *find_resolvers_by_id(const char *id)
{
struct resolvers *res;
list_for_each_entry(res, &sec_resolvers, list) {
if (strcmp(res->id, id) == 0)
return res;
}
return NULL;
}
/* Returns a pointer to the nameserver matching numerical <id> within <parent>
* resolver section. NULL is returned if no match is found.
*/
struct dns_nameserver *find_nameserver_by_resolvers_and_id(struct resolvers *parent, unsigned int id)
{
struct dns_nameserver *ns;
list_for_each_entry(ns, &parent->nameservers, list) {
if (ns->puid == id)
return ns;
}
return NULL;
}
/* Returns a pointer on the SRV request matching the name <name> for the proxy
* <px>. NULL is returned if no match is found.
*/
struct resolv_srvrq *find_srvrq_by_name(const char *name, struct proxy *px)
{
struct resolv_srvrq *srvrq;
list_for_each_entry(srvrq, &resolv_srvrq_list, list) {
if (srvrq->proxy == px && strcmp(srvrq->name, name) == 0)
return srvrq;
}
return NULL;
}
/* Allocates a new SRVRQ for the given server with the name <fqdn>. It returns
* NULL if an error occurred. */
struct resolv_srvrq *new_resolv_srvrq(struct server *srv, char *fqdn)
{
struct proxy *px = srv->proxy;
struct resolv_srvrq *srvrq = NULL;
int fqdn_len, hostname_dn_len;
fqdn_len = strlen(fqdn);
hostname_dn_len = resolv_str_to_dn_label(fqdn, fqdn_len, trash.area,
trash.size);
if (hostname_dn_len == -1) {
ha_alert("%s '%s', server '%s': failed to parse FQDN '%s'\n",
proxy_type_str(px), px->id, srv->id, fqdn);
goto err;
}
if ((srvrq = calloc(1, sizeof(*srvrq))) == NULL) {
ha_alert("%s '%s', server '%s': out of memory\n",
proxy_type_str(px), px->id, srv->id);
goto err;
}
srvrq->obj_type = OBJ_TYPE_SRVRQ;
srvrq->proxy = px;
srvrq->name = strdup(fqdn);
srvrq->hostname_dn = strdup(trash.area);
srvrq->hostname_dn_len = hostname_dn_len;
if (!srvrq->name || !srvrq->hostname_dn) {
ha_alert("%s '%s', server '%s': out of memory\n",
proxy_type_str(px), px->id, srv->id);
goto err;
}
LIST_INIT(&srvrq->attached_servers);
srvrq->named_servers = EB_ROOT;
LIST_APPEND(&resolv_srvrq_list, &srvrq->list);
return srvrq;
err:
if (srvrq) {
free(srvrq->name);
free(srvrq->hostname_dn);
free(srvrq);
}
return NULL;
}
/* finds and return the SRV answer item associated to a requester (whose type is 'server').
*
* returns NULL in case of error or not found.
*/
struct resolv_answer_item *find_srvrq_answer_record(const struct resolv_requester *requester)
{
struct resolv_resolution *res;
struct eb32_node *eb32;
struct server *srv;
if (!requester)
return NULL;
if ((srv = objt_server(requester->owner)) == NULL)
return NULL;
/* check if the server is managed by a SRV record */
if (srv->srvrq == NULL)
return NULL;
res = srv->srvrq->requester->resolution;
/* search an ANSWER record whose target points to the server's hostname and whose port is
* the same as server's svc_port */
for (eb32 = eb32_first(&res->response.answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
struct resolv_answer_item *item = eb32_entry(eb32, typeof(*item), link);
if (memcmp(srv->hostname_dn, item->data.target, srv->hostname_dn_len) == 0 &&
(srv->svc_port == item->port))
return item;
}
return NULL;
}
/* 2 bytes random generator to generate DNS query ID */
static inline uint16_t resolv_rnd16(void)
{
if (!resolv_query_id_seed)
resolv_query_id_seed = now_ms;
resolv_query_id_seed ^= resolv_query_id_seed << 13;
resolv_query_id_seed ^= resolv_query_id_seed >> 7;
resolv_query_id_seed ^= resolv_query_id_seed << 17;
return resolv_query_id_seed;
}
static inline int resolv_resolution_timeout(struct resolv_resolution *res)
{
return res->resolvers->timeout.resolve;
}
/* Updates a resolvers' task timeout for next wake up and queue it */
static void resolv_update_resolvers_timeout(struct resolvers *resolvers)
{
struct resolv_resolution *res;
int next = TICK_ETERNITY;
if (!LIST_ISEMPTY(&resolvers->resolutions.curr)) {
res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
next = tick_add(now_ms, resolvers->timeout.resolve);
next = tick_first(next, tick_add(res->last_query, resolvers->timeout.retry));
}
list_for_each_entry(res, &resolvers->resolutions.wait, list)
next = tick_first(next, tick_add(res->last_resolution, resolv_resolution_timeout(res)));
resolvers->t->expire = next;
task_queue(resolvers->t);
}
/* Forges a DNS query. It needs the following information from the caller:
* - <query_id> : the DNS query id corresponding to this query
* - <query_type> : DNS_RTYPE_* request DNS record type (A, AAAA, ANY...)
* - <hostname_dn> : hostname in domain name format
* - <hostname_dn_len> : length of <hostname_dn>
*
* To store the query, the caller must pass a buffer <buf> and its size
* <bufsize>. It returns the number of written bytes in success, -1 if <buf> is
* too short.
*/
static int resolv_build_query(int query_id, int query_type, unsigned int accepted_payload_size,
char *hostname_dn, int hostname_dn_len, char *buf, int bufsize)
{
struct dns_header dns_hdr;
struct dns_question qinfo;
struct dns_additional_record edns;
char *p = buf;
if (sizeof(dns_hdr) + sizeof(qinfo) + sizeof(edns) + hostname_dn_len >= bufsize)
return -1;
memset(buf, 0, bufsize);
/* Set dns query headers */
dns_hdr.id = (unsigned short) htons(query_id);
dns_hdr.flags = htons(0x0100); /* qr=0, opcode=0, aa=0, tc=0, rd=1, ra=0, z=0, rcode=0 */
dns_hdr.qdcount = htons(1); /* 1 question */
dns_hdr.ancount = 0;
dns_hdr.nscount = 0;
dns_hdr.arcount = htons(1);
memcpy(p, &dns_hdr, sizeof(dns_hdr));
p += sizeof(dns_hdr);
/* Set up query hostname */
memcpy(p, hostname_dn, hostname_dn_len);
p += hostname_dn_len;
*p++ = 0;
/* Set up query info (type and class) */
qinfo.qtype = htons(query_type);
qinfo.qclass = htons(DNS_RCLASS_IN);
memcpy(p, &qinfo, sizeof(qinfo));
p += sizeof(qinfo);
/* Set the DNS extension */
edns.name = 0;
edns.type = htons(DNS_RTYPE_OPT);
edns.udp_payload_size = htons(accepted_payload_size);
edns.extension = 0;
edns.data_length = 0;
memcpy(p, &edns, sizeof(edns));
p += sizeof(edns);
return (p - buf);
}
/* Sends a DNS query to resolvers associated to a resolution. It returns 0 on
* success or -1 if trash buffer is not large enough to build a valid query.
*/
static int resolv_send_query(struct resolv_resolution *resolution)
{
struct resolvers *resolvers = resolution->resolvers;
struct dns_nameserver *ns;
int len;
/* Update resolution */
resolution->nb_queries = 0;
resolution->nb_responses = 0;
resolution->last_query = now_ms;
len = resolv_build_query(resolution->query_id, resolution->query_type,
resolvers->accepted_payload_size,
resolution->hostname_dn, resolution->hostname_dn_len,
trash.area, trash.size);
if (len < 0) {
send_log(NULL, LOG_NOTICE,
"can not build the query message for %s, in resolvers %s.\n",
resolution->hostname_dn, resolvers->id);
return -1;
}
list_for_each_entry(ns, &resolvers->nameservers, list) {
if (dns_send_nameserver(ns, trash.area, len) >= 0)
resolution->nb_queries++;
}
/* Push the resolution at the end of the active list */
LIST_DEL_INIT(&resolution->list);
LIST_APPEND(&resolvers->resolutions.curr, &resolution->list);
return 0;
}
/* Prepares and sends a DNS resolution. It returns 1 if the query was sent, 0 if
* skipped and -1 if an error occurred.
*/
static int
resolv_run_resolution(struct resolv_resolution *resolution)
{
struct resolvers *resolvers = resolution->resolvers;
int query_id, i;
/* Avoid sending requests for resolutions that don't yet have an
* hostname, ie resolutions linked to servers that do not yet have an
* fqdn */
if (!resolution->hostname_dn)
return 0;
/* Check if a resolution has already been started for this server return
* directly to avoid resolution pill up. */
if (resolution->step != RSLV_STEP_NONE)
return 0;
/* Generates a new query id. We try at most 100 times to find a free
* query id */
for (i = 0; i < 100; ++i) {
query_id = resolv_rnd16();
if (!eb32_lookup(&resolvers->query_ids, query_id))
break;
query_id = -1;
}
if (query_id == -1) {
send_log(NULL, LOG_NOTICE,
"could not generate a query id for %s, in resolvers %s.\n",
resolution->hostname_dn, resolvers->id);
return -1;
}
/* Update resolution parameters */
resolution->query_id = query_id;
resolution->qid.key = query_id;
resolution->step = RSLV_STEP_RUNNING;
resolution->query_type = resolution->prefered_query_type;
resolution->try = resolvers->resolve_retries;
eb32_insert(&resolvers->query_ids, &resolution->qid);
/* Send the DNS query */
resolution->try -= 1;
resolv_send_query(resolution);
return 1;
}
/* Performs a name resolution for the requester <req> */
void resolv_trigger_resolution(struct resolv_requester *req)
{
struct resolvers *resolvers;
struct resolv_resolution *res;
int exp;
if (!req || !req->resolution)
return;
res = req->resolution;
resolvers = res->resolvers;
enter_resolver_code();
/* The resolution must not be triggered yet. Use the cached response, if
* valid */
exp = tick_add(res->last_resolution, resolvers->hold.valid);
if (resolvers->t && (!tick_isset(resolvers->t->expire) || res->status != RSLV_STATUS_VALID ||
!tick_isset(res->last_resolution) || tick_is_expired(exp, now_ms))) {
/* If the resolution is not running and the requester is a
* server, reset the resolution timer to force a quick
* resolution.
*/
if (res->step == RSLV_STEP_NONE &&
(obj_type(req->owner) == OBJ_TYPE_SERVER ||
obj_type(req->owner) == OBJ_TYPE_SRVRQ))
res->last_resolution = TICK_ETERNITY;
task_wakeup(resolvers->t, TASK_WOKEN_OTHER);
}
leave_resolver_code();
}
/* Resets some resolution parameters to initial values and also delete the query
* ID from the resolver's tree.
*/
static void resolv_reset_resolution(struct resolv_resolution *resolution)
{
/* update resolution status */
resolution->step = RSLV_STEP_NONE;
resolution->try = 0;
resolution->last_resolution = now_ms;
resolution->nb_queries = 0;
resolution->nb_responses = 0;
resolution->query_type = resolution->prefered_query_type;
/* clean up query id */
eb32_delete(&resolution->qid);
resolution->query_id = 0;
resolution->qid.key = 0;
}
/* Returns the query id contained in a DNS response */
static inline unsigned short resolv_response_get_query_id(unsigned char *resp)
{
return resp[0] * 256 + resp[1];
}
/* Analyses, re-builds and copies the name <name> from the DNS response packet
* <buffer>. <name> must point to the 'data_len' information or pointer 'c0'
* for compressed data. The result is copied into <dest>, ensuring we don't
* overflow using <dest_len> Returns the number of bytes the caller can move
* forward. If 0 it means an error occurred while parsing the name. <offset> is
* the number of bytes the caller could move forward.
*/
int resolv_read_name(unsigned char *buffer, unsigned char *bufend,
unsigned char *name, char *destination, int dest_len,
int *offset, unsigned int depth)
{
int nb_bytes = 0, n = 0;
int label_len;
unsigned char *reader = name;
char *dest = destination;
while (1) {
if (reader >= bufend)
goto err;
/* Name compression is in use */
if ((*reader & 0xc0) == 0xc0) {
if (reader + 1 >= bufend)
goto err;
/* Must point BEFORE current position */
if ((buffer + reader[1]) > reader)
goto err;
if (depth++ > 100)
goto err;
n = resolv_read_name(buffer, bufend, buffer + (*reader & 0x3f)*256 + reader[1],
dest, dest_len - nb_bytes, offset, depth);
if (n == 0)
goto err;
dest += n;
nb_bytes += n;
goto out;
}
label_len = *reader;
if (label_len == 0)
goto out;
/* Check if:
* - we won't read outside the buffer
* - there is enough place in the destination
*/
if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len))
goto err;
/* +1 to take label len + label string */
label_len++;
memcpy(dest, reader, label_len);
dest += label_len;
nb_bytes += label_len;
reader += label_len;
}
out:
/* offset computation:
* parse from <name> until finding either NULL or a pointer "c0xx"
*/
reader = name;
*offset = 0;
while (reader < bufend) {
if ((reader[0] & 0xc0) == 0xc0) {
*offset += 2;
break;
}
else if (*reader == 0) {
*offset += 1;
break;
}
*offset += 1;
++reader;
}
return nb_bytes;
err:
return 0;
}
/* Reinitialize the list of aborted resolutions before calling certain
* functions relying on it. The list must be processed by calling
* leave_resolver_code() after operations.
*/
static void enter_resolver_code()
{
if (!recurse)
LIST_INIT(&death_row);
recurse++;
}
/* Add a resolution to the death_row. */
static void abort_resolution(struct resolv_resolution *res)
{
/* Remove the resolution from query_ids tree and from any resolvers list */
eb32_delete(&res->qid);
res->query_id = 0;
res->qid.key = 0;
LIST_DEL_INIT(&res->list);
LIST_APPEND(&death_row, &res->list);
}
/* This releases any aborted resolution found in the death row. It is mandatory
* to call enter_resolver_code() first before the function (or loop) that
* needs to defer deletions. Note that some of them are in relation via internal
* objects and might cause the deletion of other ones from the same list, so we
* must absolutely not use a list_for_each_entry_safe() nor any such thing here,
* and solely rely on each call to remove the first remaining list element.
*/
static void leave_resolver_code()
{
struct resolv_resolution *res;
recurse--;
if (recurse)
return;
while (!LIST_ISEMPTY(&death_row)) {
res = LIST_NEXT(&death_row, struct resolv_resolution *, list);
resolv_free_resolution(res);
}
/* make sure nobody tries to add anything without having initialized it */
death_row = (struct list){ };
}
/* Cleanup fqdn/port and address of a server attached to a SRV resolution. This
* happens when an SRV item is purged or when the server status is considered as
* obsolete.
*
* Must be called with the DNS lock held, and with the death_row already
* initialized via enter_resolver_code().
*/
static void resolv_srvrq_cleanup_srv(struct server *srv)
{
struct server_inetaddr srv_addr;
_resolv_unlink_resolution(srv->resolv_requester);
HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
srvrq_set_srv_down(srv);
ha_free(&srv->hostname);
ha_free(&srv->hostname_dn);
srv->hostname_dn_len = 0;
memset(&srv_addr, 0, sizeof(srv_addr));
/* unset server's addr AND port */
server_set_inetaddr(srv, &srv_addr, SERVER_INETADDR_UPDATER_NONE, NULL);
srv->flags |= SRV_F_NO_RESOLUTION;
ebpt_delete(&srv->host_dn);
ha_free(&srv->host_dn.key);
HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
LIST_DEL_INIT(&srv->srv_rec_item);
LIST_APPEND(&srv->srvrq->attached_servers, &srv->srv_rec_item);
srv->srvrq_check->expire = TICK_ETERNITY;
}
/* Takes care to cleanup a server resolution when it is outdated. This only
* happens for a server relying on a SRV record.
*/
static struct task *resolv_srvrq_expire_task(struct task *t, void *context, unsigned int state)
{
struct server *srv = context;
if (!tick_is_expired(t->expire, now_ms))
goto end;
enter_resolver_code();
HA_SPIN_LOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
resolv_srvrq_cleanup_srv(srv);
HA_SPIN_UNLOCK(DNS_LOCK, &srv->srvrq->resolvers->lock);
leave_resolver_code();
end:
return t;
}
/* Checks for any obsolete record, also identify any SRV request, and try to
* find a corresponding server.
*/
static void resolv_check_response(struct resolv_resolution *res)
{
struct resolvers *resolvers = res->resolvers;
struct resolv_requester *req;
struct eb32_node *eb32, *eb32_back;
struct server *srv, *srvback;
struct resolv_srvrq *srvrq;
for (eb32 = eb32_first(&res->response.answer_tree); eb32 && (eb32_back = eb32_next(eb32), 1); eb32 = eb32_back) {
struct resolv_answer_item *item = eb32_entry(eb32, typeof(*item), link);
struct resolv_answer_item *ar_item = item->ar_item;
/* clean up obsolete Additional record */
if (ar_item && tick_is_lt(tick_add(ar_item->last_seen, resolvers->hold.obsolete), now_ms)) {
/* Cleaning up the AR item will trigger an extra DNS resolution, except if the SRV
* item is also obsolete.
*/
pool_free(resolv_answer_item_pool, ar_item);
item->ar_item = NULL;
}
/* Remove obsolete items */
if (tick_is_lt(tick_add(item->last_seen, resolvers->hold.obsolete), now_ms)) {
if (item->type == DNS_RTYPE_A || item->type == DNS_RTYPE_AAAA) {
/* Remove any associated server */
list_for_each_entry_safe(srv, srvback, &item->attached_servers, ip_rec_item) {
LIST_DEL_INIT(&srv->ip_rec_item);
}
}
else if (item->type == DNS_RTYPE_SRV) {
/* Remove any associated server */
list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item)
resolv_srvrq_cleanup_srv(srv);
}
eb32_delete(&item->link);
if (item->ar_item) {
pool_free(resolv_answer_item_pool, item->ar_item);
item->ar_item = NULL;
}
pool_free(resolv_answer_item_pool, item);
continue;
}
if (item->type != DNS_RTYPE_SRV)
continue;
/* Now process SRV records */
list_for_each_entry(req, &res->requesters, list) {
struct ebpt_node *node;
char target[DNS_MAX_NAME_SIZE+1];
int i;
if ((srvrq = objt_resolv_srvrq(req->owner)) == NULL)
continue;
/* Check if a server already uses that record */
srv = NULL;
list_for_each_entry(srv, &item->attached_servers, srv_rec_item) {
if (srv->srvrq == srvrq) {
HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
goto srv_found;
}
}
/* If not empty we try to match a server
* in server state file tree with the same hostname
*/
if (!eb_is_empty(&srvrq->named_servers)) {
srv = NULL;
/* convert the key to lookup in lower case */
for (i = 0 ; item->data.target[i] ; i++)
target[i] = tolower(item->data.target[i]);
target[i] = 0;
node = ebis_lookup(&srvrq->named_servers, target);
if (node) {
srv = ebpt_entry(node, struct server, host_dn);
HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
/* an entry was found with the same hostname
* let check this node if the port matches
* and try next node if the hostname
* is still the same
*/
while (1) {
if (srv->svc_port == item->port) {
/* server found, we remove it from tree */
ebpt_delete(node);
ha_free(&srv->host_dn.key);
goto srv_found;
}
HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
node = ebpt_next(node);
if (!node)
break;
srv = ebpt_entry(node, struct server, host_dn);
HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
if ((item->data_len != srv->hostname_dn_len)
|| memcmp(srv->hostname_dn, item->data.target, item->data_len) != 0) {
HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
break;
}
}
}
}
/* Pick the first server listed in srvrq (those ones don't
* have hostname and are free to use)
*/
srv = NULL;
list_for_each_entry(srv, &srvrq->attached_servers, srv_rec_item) {
LIST_DEL_INIT(&srv->srv_rec_item);
HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
goto srv_found;
}
srv = NULL;
srv_found:
/* And update this server, if found (srv is locked here) */
if (srv) {
struct server_inetaddr srv_addr;
uint8_t ip_change = 0;
/* re-enable DNS resolution for this server by default */
srv->flags &= ~SRV_F_NO_RESOLUTION;
srv->srvrq_check->expire = TICK_ETERNITY;
server_get_inetaddr(srv, &srv_addr);
srv_addr.port.svc = item->port;
srv_addr.port.map = 0;
/* Check if an Additional Record is associated to this SRV record.
* Perform some sanity checks too to ensure the record can be used.
* If all fine, we simply pick up the IP address found and associate
* it to the server. And DNS resolution is disabled for this server.
*/
if ((item->ar_item != NULL) &&
(item->ar_item->type == DNS_RTYPE_A || item->ar_item->type == DNS_RTYPE_AAAA))
{
switch (item->ar_item->type) {
case DNS_RTYPE_A:
srv_addr.family = AF_INET;
srv_addr.addr.v4 = item->ar_item->data.in4.sin_addr;
break;
case DNS_RTYPE_AAAA:
srv_addr.family = AF_INET6;
srv_addr.addr.v6 = item->ar_item->data.in6.sin6_addr;
break;
}
srv->flags |= SRV_F_NO_RESOLUTION;
/* Unlink A/AAAA resolution for this server if there is an AR item.
* It is usless to perform an extra resolution
*/
_resolv_unlink_resolution(srv->resolv_requester);
ip_change = 1;
}
if (ip_change)
server_set_inetaddr_warn(srv, &srv_addr, SERVER_INETADDR_UPDATER_DNS_AR);
else
server_set_inetaddr(srv, &srv_addr, SERVER_INETADDR_UPDATER_NONE, NULL);
if (!srv->hostname_dn) {
const char *msg = NULL;
char hostname[DNS_MAX_NAME_SIZE+1];
if (resolv_dn_label_to_str(item->data.target, item->data_len,
hostname, sizeof(hostname)) == -1) {
HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
continue;
}
msg = srv_update_fqdn(srv, hostname, "SRV record", 1);
if (msg)
send_log(srv->proxy, LOG_NOTICE, "%s", msg);
}
if (!LIST_INLIST(&srv->srv_rec_item))
LIST_APPEND(&item->attached_servers, &srv->srv_rec_item);
if (!(srv->flags & SRV_F_NO_RESOLUTION)) {
/* If there is no AR item responsible of the FQDN resolution,
* trigger a dedicated DNS resolution
*/
if (!srv->resolv_requester || !srv->resolv_requester->resolution)
resolv_link_resolution(srv, OBJ_TYPE_SERVER, 1);
}
if (!srv->resolv_opts.ignore_weight) {
char weight[9];
int ha_weight;
/* DNS weight range if from 0 to 65535
* HAProxy weight is from 0 to 256
* The rule below ensures that weight 0 is well respected
* while allowing a "mapping" from DNS weight into HAProxy's one.
*/
ha_weight = (item->weight + 255) / 256;
snprintf(weight, sizeof(weight), "%d", ha_weight);
server_parse_weight_change_request(srv, weight);
}
HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
}
}
}
}
/* Validates that the buffer DNS response provided in <resp> and finishing
* before <bufend> is valid from a DNS protocol point of view.
*
* The result is stored in <resolution>' response, buf_response,
* response_query_records and response_answer_records members.
*
* This function returns one of the RSLV_RESP_* code to indicate the type of
* error found.
*/
static int resolv_validate_dns_response(unsigned char *resp, unsigned char *bufend,
struct resolv_resolution *resolution, int max_answer_records)
{
unsigned char *reader;
char *previous_dname, tmpname[DNS_MAX_NAME_SIZE];
int len, flags, offset;
int nb_saved_records;
struct resolv_query_item *query;
struct resolv_answer_item *answer_record, *tmp_record;
struct resolv_response *r_res;
struct eb32_node *eb32;
uint32_t key = 0;
int i, found = 0;
int cause = RSLV_RESP_ERROR;
reader = resp;
len = 0;
previous_dname = NULL;
query = NULL;
answer_record = NULL;
/* Initialization of response buffer and structure */
r_res = &resolution->response;
/* query id */
if (reader + 2 >= bufend)
goto invalid_resp;
r_res->header.id = reader[0] * 256 + reader[1];
reader += 2;
/* Flags and rcode are stored over 2 bytes
* First byte contains:
* - response flag (1 bit)
* - opcode (4 bits)
* - authoritative (1 bit)
* - truncated (1 bit)
* - recursion desired (1 bit)
*/
if (reader + 2 >= bufend)
goto invalid_resp;
flags = reader[0] * 256 + reader[1];
if ((flags & DNS_FLAG_REPLYCODE) != DNS_RCODE_NO_ERROR) {
if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_NX_DOMAIN) {
cause = RSLV_RESP_NX_DOMAIN;
goto return_error;
}
else if ((flags & DNS_FLAG_REPLYCODE) == DNS_RCODE_REFUSED) {
cause = RSLV_RESP_REFUSED;
goto return_error;
}
else {
cause = RSLV_RESP_ERROR;
goto return_error;
}
}
/* Move forward 2 bytes for flags */
reader += 2;
/* 2 bytes for question count */
if (reader + 2 >= bufend)
goto invalid_resp;
r_res->header.qdcount = reader[0] * 256 + reader[1];
/* (for now) we send one query only, so we expect only one in the
* response too */
if (r_res->header.qdcount != 1) {
cause = RSLV_RESP_QUERY_COUNT_ERROR;
goto return_error;
}
if (r_res->header.qdcount > DNS_MAX_QUERY_RECORDS)
goto invalid_resp;
reader += 2;
/* 2 bytes for answer count */
if (reader + 2 >= bufend)
goto invalid_resp;
r_res->header.ancount = reader[0] * 256 + reader[1];
if (r_res->header.ancount == 0) {
cause = RSLV_RESP_ANCOUNT_ZERO;
goto return_error;
}
/* Check if too many records are announced */
if (r_res->header.ancount > max_answer_records)
goto invalid_resp;
reader += 2;
/* 2 bytes authority count */
if (reader + 2 >= bufend)
goto invalid_resp;
r_res->header.nscount = reader[0] * 256 + reader[1];
reader += 2;
/* 2 bytes additional count */
if (reader + 2 >= bufend)
goto invalid_resp;
r_res->header.arcount = reader[0] * 256 + reader[1];
reader += 2;
/* Parsing dns queries. For now there is only one query and it exists
* because (qdcount == 1).
*/
query = &resolution->response_query_records[0];
/* Name is a NULL terminated string in our case, since we have
* one query per response and the first one can't be compressed
* (using the 0x0c format) */
offset = 0;
len = resolv_read_name(resp, bufend, reader, query->name, DNS_MAX_NAME_SIZE, &offset, 0);
if (len == 0)
goto invalid_resp;
/* Now let's check the query's dname corresponds to the one we sent. */
if (len != resolution->hostname_dn_len ||
memcmp(query->name, resolution->hostname_dn, resolution->hostname_dn_len) != 0) {
cause = RSLV_RESP_WRONG_NAME;
goto return_error;
}
reader += offset;
previous_dname = query->name;
/* move forward 2 bytes for question type */
if (reader + 2 >= bufend)
goto invalid_resp;
query->type = reader[0] * 256 + reader[1];
reader += 2;
/* move forward 2 bytes for question class */
if (reader + 2 >= bufend)
goto invalid_resp;
query->class = reader[0] * 256 + reader[1];
reader += 2;
/* TRUNCATED flag must be checked after we could read the query type
* because a TRUNCATED SRV query type response can still be exploited
*/
if (query->type != DNS_RTYPE_SRV && flags & DNS_FLAG_TRUNCATED) {
cause = RSLV_RESP_TRUNCATED;
goto return_error;
}
/* now parsing response records */
nb_saved_records = 0;
for (i = 0; i < r_res->header.ancount; i++) {
if (reader >= bufend)
goto invalid_resp;
answer_record = pool_alloc(resolv_answer_item_pool);
if (answer_record == NULL)
goto invalid_resp;
/* initialization */
answer_record->ar_item = NULL;
answer_record->last_seen = TICK_ETERNITY;
LIST_INIT(&answer_record->attached_servers);
answer_record->link.node.leaf_p = NULL;
offset = 0;
len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
if (len == 0)
goto invalid_resp;
/* Check if the current record dname is valid. previous_dname
* points either to queried dname or last CNAME target */
if (query->type != DNS_RTYPE_SRV && memcmp(previous_dname, tmpname, len) != 0) {
if (i == 0) {
/* First record, means a mismatch issue between
* queried dname and dname found in the first
* record */
goto invalid_resp;
}
else {
/* If not the first record, this means we have a
* CNAME resolution error.
*/
cause = RSLV_RESP_CNAME_ERROR;
goto return_error;
}
}
memcpy(answer_record->name, tmpname, len);
answer_record->name[len] = 0;
reader += offset;
if (reader >= bufend)
goto invalid_resp;
/* 2 bytes for record type (A, AAAA, CNAME, etc...) */
if (reader + 2 > bufend)
goto invalid_resp;
answer_record->type = reader[0] * 256 + reader[1];
reader += 2;
/* 2 bytes for class (2) */
if (reader + 2 > bufend)
goto invalid_resp;
answer_record->class = reader[0] * 256 + reader[1];
reader += 2;
/* 4 bytes for ttl (4) */
if (reader + 4 > bufend)
goto invalid_resp;
answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
+ reader[2] * 256 + reader[3];
reader += 4;
/* Now reading data len */
if (reader + 2 > bufend)
goto invalid_resp;
answer_record->data_len = reader[0] * 256 + reader[1];
/* Move forward 2 bytes for data len */
reader += 2;
if (reader + answer_record->data_len > bufend)
goto invalid_resp;
/* Analyzing record content */
switch (answer_record->type) {
case DNS_RTYPE_A:
/* ipv4 is stored on 4 bytes */
if (answer_record->data_len != 4)
goto invalid_resp;
answer_record->data.in4.sin_family = AF_INET;
memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
key = XXH32(reader, answer_record->data_len, answer_record->type);
break;
case DNS_RTYPE_CNAME:
/* Check if this is the last record and update the caller about the status:
* no IP could be found and last record was a CNAME. Could be triggered
* by a wrong query type
*
* + 1 because answer_record_id starts at 0
* while number of answers is an integer and
* starts at 1.
*/
if (i + 1 == r_res->header.ancount) {
cause = RSLV_RESP_CNAME_ERROR;
goto return_error;
}
offset = 0;
len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
if (len == 0)
goto invalid_resp;
memcpy(answer_record->data.target, tmpname, len);
answer_record->data.target[len] = 0;
key = XXH32(tmpname, len, answer_record->type);
previous_dname = answer_record->data.target;
break;
case DNS_RTYPE_SRV:
/* Answer must contain :
* - 2 bytes for the priority
* - 2 bytes for the weight
* - 2 bytes for the port
* - the target hostname
*/
if (answer_record->data_len <= 6)
goto invalid_resp;
answer_record->priority = read_n16(reader);
reader += sizeof(uint16_t);
answer_record->weight = read_n16(reader);
reader += sizeof(uint16_t);
answer_record->port = read_n16(reader);
reader += sizeof(uint16_t);
offset = 0;
len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
if (len == 0)
goto invalid_resp;
answer_record->data_len = len;
memcpy(answer_record->data.target, tmpname, len);
answer_record->data.target[len] = 0;
key = XXH32(tmpname, len, answer_record->type);
if (answer_record->ar_item != NULL) {
pool_free(resolv_answer_item_pool, answer_record->ar_item);
answer_record->ar_item = NULL;
}
break;
case DNS_RTYPE_AAAA:
/* ipv6 is stored on 16 bytes */
if (answer_record->data_len != 16)
goto invalid_resp;
answer_record->data.in6.sin6_family = AF_INET6;
memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
key = XXH32(reader, answer_record->data_len, answer_record->type);
break;
} /* switch (record type) */
/* Increment the counter for number of records saved into our
* local response */
nb_saved_records++;
/* Move forward answer_record->data_len for analyzing next
* record in the response */
reader += ((answer_record->type == DNS_RTYPE_SRV)
? offset
: answer_record->data_len);
/* Lookup to see if we already had this entry */
found = 0;
for (eb32 = eb32_lookup(&r_res->answer_tree, key); eb32 != NULL; eb32 = eb32_next(eb32)) {
tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
if (tmp_record->type != answer_record->type)
continue;
switch(tmp_record->type) {
case DNS_RTYPE_A:
if (!memcmp(&answer_record->data.in4.sin_addr,
&tmp_record->data.in4.sin_addr,
sizeof(answer_record->data.in4.sin_addr)))
found = 1;
break;
case DNS_RTYPE_AAAA:
if (!memcmp(&answer_record->data.in6.sin6_addr,
&tmp_record->data.in6.sin6_addr,
sizeof(answer_record->data.in6.sin6_addr)))
found = 1;
break;
case DNS_RTYPE_SRV:
if (answer_record->data_len == tmp_record->data_len &&
memcmp(answer_record->data.target, tmp_record->data.target, answer_record->data_len) == 0 &&
answer_record->port == tmp_record->port) {
tmp_record->weight = answer_record->weight;
found = 1;
}
break;
default:
break;
}
if (found == 1)
break;
}
if (found == 1) {
tmp_record->last_seen = now_ms;
pool_free(resolv_answer_item_pool, answer_record);
answer_record = NULL;
}
else {
answer_record->last_seen = now_ms;
answer_record->ar_item = NULL;
answer_record->link.key = key;
eb32_insert(&r_res->answer_tree, &answer_record->link);
answer_record = NULL;
}
} /* for i 0 to ancount */
/* Save the number of records we really own */
r_res->header.ancount = nb_saved_records;
/* now parsing additional records for SRV queries only */
if (query->type != DNS_RTYPE_SRV)
goto skip_parsing_additional_records;
/* if we find Authority records, just skip them */
for (i = 0; i < r_res->header.nscount; i++) {
offset = 0;
len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE,
&offset, 0);
if (len == 0)
continue;
if (reader + offset + 10 >= bufend)
goto invalid_resp;
reader += offset;
/* skip 2 bytes for class */
reader += 2;
/* skip 2 bytes for type */
reader += 2;
/* skip 4 bytes for ttl */
reader += 4;
/* read data len */
len = reader[0] * 256 + reader[1];
reader += 2;
if (reader + len >= bufend)
goto invalid_resp;
reader += len;
}
nb_saved_records = 0;
for (i = 0; i < r_res->header.arcount; i++) {
if (reader >= bufend)
goto invalid_resp;
answer_record = pool_alloc(resolv_answer_item_pool);
if (answer_record == NULL)
goto invalid_resp;
answer_record->last_seen = TICK_ETERNITY;
LIST_INIT(&answer_record->attached_servers);
offset = 0;
len = resolv_read_name(resp, bufend, reader, tmpname, DNS_MAX_NAME_SIZE, &offset, 0);
if (len == 0) {
pool_free(resolv_answer_item_pool, answer_record);
answer_record = NULL;
continue;
}
memcpy(answer_record->name, tmpname, len);
answer_record->name[len] = 0;
reader += offset;
if (reader >= bufend)
goto invalid_resp;
/* 2 bytes for record type (A, AAAA, CNAME, etc...) */
if (reader + 2 > bufend)
goto invalid_resp;
answer_record->type = reader[0] * 256 + reader[1];
reader += 2;
/* 2 bytes for class (2) */
if (reader + 2 > bufend)
goto invalid_resp;
answer_record->class = reader[0] * 256 + reader[1];
reader += 2;
/* 4 bytes for ttl (4) */
if (reader + 4 > bufend)
goto invalid_resp;
answer_record->ttl = reader[0] * 16777216 + reader[1] * 65536
+ reader[2] * 256 + reader[3];
reader += 4;
/* Now reading data len */
if (reader + 2 > bufend)
goto invalid_resp;
answer_record->data_len = reader[0] * 256 + reader[1];
/* Move forward 2 bytes for data len */
reader += 2;
if (reader + answer_record->data_len > bufend)
goto invalid_resp;
/* Analyzing record content */
switch (answer_record->type) {
case DNS_RTYPE_A:
/* ipv4 is stored on 4 bytes */
if (answer_record->data_len != 4)
goto invalid_resp;
answer_record->data.in4.sin_family = AF_INET;
memcpy(&answer_record->data.in4.sin_addr, reader, answer_record->data_len);
break;
case DNS_RTYPE_AAAA:
/* ipv6 is stored on 16 bytes */
if (answer_record->data_len != 16)
goto invalid_resp;
answer_record->data.in6.sin6_family = AF_INET6;
memcpy(&answer_record->data.in6.sin6_addr, reader, answer_record->data_len);
break;
default:
pool_free(resolv_answer_item_pool, answer_record);
answer_record = NULL;
continue;
} /* switch (record type) */
/* Increment the counter for number of records saved into our
* local response */
nb_saved_records++;
/* Move forward answer_record->data_len for analyzing next
* record in the response */
reader += answer_record->data_len;
/* Lookup to see if we already had this entry */
found = 0;
for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
struct resolv_answer_item *ar_item;
tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
if (tmp_record->type != DNS_RTYPE_SRV || !tmp_record->ar_item)
continue;
ar_item = tmp_record->ar_item;
if (ar_item->type != answer_record->type || ar_item->last_seen == now_ms ||
len != tmp_record->data_len ||
memcmp(answer_record->name, tmp_record->data.target, tmp_record->data_len) != 0)
continue;
switch(ar_item->type) {
case DNS_RTYPE_A:
if (!memcmp(&answer_record->data.in4.sin_addr,
&ar_item->data.in4.sin_addr,
sizeof(answer_record->data.in4.sin_addr)))
found = 1;
break;
case DNS_RTYPE_AAAA:
if (!memcmp(&answer_record->data.in6.sin6_addr,
&ar_item->data.in6.sin6_addr,
sizeof(answer_record->data.in6.sin6_addr)))
found = 1;
break;
default:
break;
}
if (found == 1)
break;
}
if (found == 1) {
tmp_record->ar_item->last_seen = now_ms;
pool_free(resolv_answer_item_pool, answer_record);
answer_record = NULL;
}
else {
answer_record->last_seen = now_ms;
answer_record->ar_item = NULL;
// looking for the SRV record in the response list linked to this additional record
for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
tmp_record = eb32_entry(eb32, typeof(*tmp_record), link);
if (tmp_record->type == DNS_RTYPE_SRV &&
tmp_record->ar_item == NULL &&
memcmp(tmp_record->data.target, answer_record->name, tmp_record->data_len) == 0) {
/* Always use the received additional record to refresh info */
pool_free(resolv_answer_item_pool, tmp_record->ar_item);
tmp_record->ar_item = answer_record;
answer_record = NULL;
break;
}
}
if (answer_record) {
pool_free(resolv_answer_item_pool, answer_record);
answer_record = NULL;
}
}
} /* for i 0 to arcount */
skip_parsing_additional_records:
/* Save the number of records we really own */
r_res->header.arcount = nb_saved_records;
resolv_check_response(resolution);
return RSLV_RESP_VALID;
invalid_resp:
cause = RSLV_RESP_INVALID;
return_error:
pool_free(resolv_answer_item_pool, answer_record);
return cause;
}
/* Searches dn_name resolution in resp.
* If existing IP not found, return the first IP matching family_priority,
* otherwise, first ip found
* The following tasks are the responsibility of the caller:
* - <r_res> contains an error free DNS response
* For both cases above, resolv_validate_dns_response is required
* returns one of the RSLV_UPD_* code
*/
int resolv_get_ip_from_response(struct resolv_response *r_res,
struct resolv_options *resolv_opts, void *currentip,
short currentip_sin_family,
void **newip, short *newip_sin_family,
struct server *owner)
{
struct resolv_answer_item *record, *found_record = NULL;
struct eb32_node *eb32;
int family_priority;
int currentip_found;
unsigned char *newip4, *newip6;
int currentip_sel;
int j;
int score, max_score;
int allowed_duplicated_ip;
/* srv is linked to an alive ip record */
if (owner && LIST_INLIST(&owner->ip_rec_item))
return RSLV_UPD_NO;
family_priority = resolv_opts->family_prio;
allowed_duplicated_ip = resolv_opts->accept_duplicate_ip;
*newip = newip4 = newip6 = NULL;
currentip_found = 0;
*newip_sin_family = AF_UNSPEC;
max_score = -1;
/* Select an IP regarding configuration preference.
* Top priority is the preferred network ip version,
* second priority is the preferred network.
* the last priority is the currently used IP,
*
* For these three priorities, a score is calculated. The
* weight are:
* 8 - preferred ip version.
* 4 - preferred network.
* 2 - if the ip in the record is not affected to any other server in the same backend (duplication)
* 1 - current ip.
* The result with the biggest score is returned.
*/
for (eb32 = eb32_first(&r_res->answer_tree); eb32 != NULL; eb32 = eb32_next(eb32)) {
void *ip;
unsigned char ip_type;
record = eb32_entry(eb32, typeof(*record), link);
if (record->type == DNS_RTYPE_A) {
ip_type = AF_INET;
ip = &record->data.in4.sin_addr;
}
else if (record->type == DNS_RTYPE_AAAA) {
ip_type = AF_INET6;
ip = &record->data.in6.sin6_addr;
}
else
continue;
score = 0;
/* Check for preferred ip protocol. */
if (ip_type == family_priority)
score += 8;
/* Check for preferred network. */
for (j = 0; j < resolv_opts->pref_net_nb; j++) {
/* Compare only the same addresses class. */
if (resolv_opts->pref_net[j].family != ip_type)
continue;
if ((ip_type == AF_INET &&
in_net_ipv4(ip,
&resolv_opts->pref_net[j].mask.in4,
&resolv_opts->pref_net[j].addr.in4)) ||
(ip_type == AF_INET6 &&
in_net_ipv6(ip,
&resolv_opts->pref_net[j].mask.in6,
&resolv_opts->pref_net[j].addr.in6))) {
score += 4;
break;
}
}
/* Check if the IP found in the record is already affected to a
* member of a group. If not, the score should be incremented
* by 2. */
if (owner) {
struct server *srv;
int already_used = 0;
list_for_each_entry(srv, &record->attached_servers, ip_rec_item) {
if (srv == owner)
continue;
if (srv->proxy == owner->proxy) {
already_used = 1;
break;
}
}
if (already_used) {
if (!allowed_duplicated_ip) {
continue;
}
}
else {
score += 2;
}
} else {
score += 2;
}
/* Check for current ip matching. */
if (ip_type == currentip_sin_family &&
((currentip_sin_family == AF_INET &&
!memcmp(ip, currentip, 4)) ||
(currentip_sin_family == AF_INET6 &&
!memcmp(ip, currentip, 16)))) {
score++;
currentip_sel = 1;
}
else
currentip_sel = 0;
/* Keep the address if the score is better than the previous
* score. The maximum score is 15, if this value is reached, we
* break the parsing. Implicitly, this score is reached the ip
* selected is the current ip. */
if (score > max_score) {
if (ip_type == AF_INET)
newip4 = ip;
else
newip6 = ip;
found_record = record;
currentip_found = currentip_sel;
if (score == 15) {
/* this was not registered on the current record but it matches
* let's fix it (it may comes from state file */
if (owner)
LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
return RSLV_UPD_NO;
}
max_score = score;
}
} /* list for each record entries */
/* No IP found in the response */
if (!newip4 && !newip6)
return RSLV_UPD_NO_IP_FOUND;
/* Case when the caller looks first for an IPv4 address */
if (family_priority == AF_INET) {
if (newip4) {
*newip = newip4;
*newip_sin_family = AF_INET;
}
else if (newip6) {
*newip = newip6;
*newip_sin_family = AF_INET6;
}
}
/* Case when the caller looks first for an IPv6 address */
else if (family_priority == AF_INET6) {
if (newip6) {
*newip = newip6;
*newip_sin_family = AF_INET6;
}
else if (newip4) {
*newip = newip4;
*newip_sin_family = AF_INET;
}
}
/* Case when the caller have no preference (we prefer IPv6) */
else if (family_priority == AF_UNSPEC) {
if (newip6) {
*newip = newip6;
*newip_sin_family = AF_INET6;
}
else if (newip4) {
*newip = newip4;
*newip_sin_family = AF_INET;
}
}
/* the ip of this record was chosen for the server */
if (owner && found_record) {
LIST_DEL_INIT(&owner->ip_rec_item);
LIST_APPEND(&found_record->attached_servers, &owner->ip_rec_item);
}
eb32 = eb32_first(&r_res->answer_tree);
if (eb32) {
/* Move the first record to the end of the list, for internal
* round robin.
*/
eb32_delete(eb32);
eb32_insert(&r_res->answer_tree, eb32);
}
return (currentip_found ? RSLV_UPD_NO : RSLV_UPD_SRVIP_NOT_FOUND);
}
/* Turns a domain name label into a string: 3www7haproxy3org into www.haproxy.org
*
* <dn> contains the input label of <dn_len> bytes long and does not need to be
* null-terminated. <str> must be allocated large enough to contain a full host
* name plus the trailing zero, and the allocated size must be passed in
* <str_len>.
*
* In case of error, -1 is returned, otherwise, the number of bytes copied in
* <str> (including the terminating null byte).
*/
int resolv_dn_label_to_str(const char *dn, int dn_len, char *str, int str_len)
{
char *ptr;
int i, sz;
if (str_len < dn_len)
return -1;
ptr = str;
for (i = 0; i < dn_len; ++i) {
sz = dn[i];
if (i)
*ptr++ = '.';
/* copy the string at i+1 to lower case */
for (; sz > 0; sz--)
*(ptr++) = tolower(dn[++i]);
}
*ptr++ = '\0';
return (ptr - str);
}
/* Turns a string into domain name label: www.haproxy.org into 3www7haproxy3org
*
* <str> contains the input string that is <str_len> bytes long (trailing zero
* not needed). <dn> buffer must be allocated large enough to contain the
* encoded string and a trailing zero, so it must be at least str_len+2, and
* this allocated buffer size must be passed in <dn_len>.
*
* In case of error, -1 is returned, otherwise, the number of bytes copied in
* <dn> (excluding the terminating null byte).
*/
int resolv_str_to_dn_label(const char *str, int str_len, char *dn, int dn_len)
{
int i, offset;
if (dn_len < str_len + 2)
return -1;
/* First byte of dn will be used to store the length of the first
* label */
offset = 0;
for (i = 0; i < str_len; ++i) {
if (str[i] == '.') {
/* 2 or more consecutive dots is invalid */
if (i == offset)
return -1;
/* ignore trailing dot */
if (i + 1 == str_len)
break;
dn[offset] = (i - offset);
offset = i+1;
continue;
}
dn[i+1] = tolower(str[i]);
}
dn[offset] = i - offset;
dn[i+1] = '\0';
return i+1;
}
/* Validates host name:
* - total size
* - each label size individually
* returns:
* 0 in case of error. If <err> is not NULL, an error message is stored there.
* 1 when no error. <err> is left unaffected.
*/
int resolv_hostname_validation(const char *string, char **err)
{
int i;
if (strlen(string) > DNS_MAX_NAME_SIZE) {
if (err)
*err = DNS_TOO_LONG_FQDN;
return 0;
}
while (*string) {
i = 0;
while (*string && *string != '.' && i < DNS_MAX_LABEL_SIZE) {
if (!(*string == '-' || *string == '_' ||
(*string >= 'a' && *string <= 'z') ||
(*string >= 'A' && *string <= 'Z') ||
(*string >= '0' && *string <= '9'))) {
if (err)
*err = DNS_INVALID_CHARACTER;
return 0;
}
i++;
string++;
}
if (!(*string))
break;
if (*string != '.' && i >= DNS_MAX_LABEL_SIZE) {
if (err)
*err = DNS_LABEL_TOO_LONG;
return 0;
}
string++;
}
return 1;
}
/* Picks up an available resolution from the different resolution list
* associated to a resolvers section, in this order:
* 1. check in resolutions.curr for the same hostname and query_type
* 2. check in resolutions.wait for the same hostname and query_type
* 3. Get a new resolution from resolution pool
*
* Returns an available resolution, NULL if none found.
*/
static struct resolv_resolution *resolv_pick_resolution(struct resolvers *resolvers,
char **hostname_dn, int hostname_dn_len,
int query_type)
{
struct resolv_resolution *res;
if (!*hostname_dn)
goto from_pool;
/* Search for same hostname and query type in resolutions.curr */
list_for_each_entry(res, &resolvers->resolutions.curr, list) {
if (!res->hostname_dn)
continue;
if ((query_type == res->prefered_query_type) &&
hostname_dn_len == res->hostname_dn_len &&
memcmp(*hostname_dn, res->hostname_dn, hostname_dn_len) == 0)
return res;
}
/* Search for same hostname and query type in resolutions.wait */
list_for_each_entry(res, &resolvers->resolutions.wait, list) {
if (!res->hostname_dn)
continue;
if ((query_type == res->prefered_query_type) &&
hostname_dn_len == res->hostname_dn_len &&
memcmp(*hostname_dn, res->hostname_dn, hostname_dn_len) == 0)
return res;
}
from_pool:
/* No resolution could be found, so let's allocate a new one */
res = pool_zalloc(resolv_resolution_pool);
if (res) {
res->resolvers = resolvers;
res->uuid = resolution_uuid;
res->status = RSLV_STATUS_NONE;
res->step = RSLV_STEP_NONE;
res->last_valid = now_ms;
LIST_INIT(&res->requesters);
res->response.answer_tree = EB_ROOT;
res->prefered_query_type = query_type;
res->query_type = query_type;
res->hostname_dn = *hostname_dn;
res->hostname_dn_len = hostname_dn_len;
++resolution_uuid;
/* Move the resolution to the resolvers wait queue */
LIST_APPEND(&resolvers->resolutions.wait, &res->list);
}
return res;
}
/* deletes and frees all answer_items from the resolution's answer_list */
static void resolv_purge_resolution_answer_records(struct resolv_resolution *resolution)
{
struct eb32_node *eb32, *eb32_back;
struct resolv_answer_item *item;
for (eb32 = eb32_first(&resolution->response.answer_tree);
eb32 && (eb32_back = eb32_next(eb32), 1);
eb32 = eb32_back) {
item = eb32_entry(eb32, typeof(*item), link);
eb32_delete(&item->link);
pool_free(resolv_answer_item_pool, item->ar_item);
pool_free(resolv_answer_item_pool, item);
}
}
/* Releases a resolution from its requester(s) and move it back to the pool */
static void resolv_free_resolution(struct resolv_resolution *resolution)
{
struct resolv_requester *req, *reqback;
/* clean up configuration */
resolv_reset_resolution(resolution);
resolution->hostname_dn = NULL;
resolution->hostname_dn_len = 0;
list_for_each_entry_safe(req, reqback, &resolution->requesters, list) {
LIST_DEL_INIT(&req->list);
req->resolution = NULL;
}
resolv_purge_resolution_answer_records(resolution);
LIST_DEL_INIT(&resolution->list);
pool_free(resolv_resolution_pool, resolution);
}
/* If *<req> is not NULL, returns it, otherwise tries to allocate a requester
* and makes it owned by this obj_type, with the proposed callback and error
* callback. On success, *req is assigned the allocated requester. Returns
* NULL on allocation failure.
*/
static struct resolv_requester *
resolv_get_requester(struct resolv_requester **req, enum obj_type *owner,
int (*cb)(struct resolv_requester *, struct dns_counters *),
int (*err_cb)(struct resolv_requester *, int))
{
struct resolv_requester *tmp;
if (*req)
return *req;
tmp = pool_alloc(resolv_requester_pool);
if (!tmp)
goto end;
LIST_INIT(&tmp->list);
tmp->owner = owner;
tmp->resolution = NULL;
tmp->requester_cb = cb;
tmp->requester_error_cb = err_cb;
*req = tmp;
end:
return tmp;
}
/* Links a requester (a server or a resolv_srvrq) with a resolution. It returns 0
* on success, -1 otherwise.
*/
int resolv_link_resolution(void *requester, int requester_type, int requester_locked)
{
struct resolv_resolution *res = NULL;
struct resolv_requester *req;
struct resolvers *resolvers;
struct server *srv = NULL;
struct resolv_srvrq *srvrq = NULL;
struct stream *stream = NULL;
char **hostname_dn;
int hostname_dn_len, query_type;
enter_resolver_code();
switch (requester_type) {
case OBJ_TYPE_SERVER:
srv = (struct server *)requester;
if (!requester_locked)
HA_SPIN_LOCK(SERVER_LOCK, &srv->lock);
req = resolv_get_requester(&srv->resolv_requester,
&srv->obj_type,
snr_resolution_cb,
snr_resolution_error_cb);
if (!requester_locked)
HA_SPIN_UNLOCK(SERVER_LOCK, &srv->lock);
if (!req)
goto err;
hostname_dn = &srv->hostname_dn;
hostname_dn_len = srv->hostname_dn_len;
resolvers = srv->resolvers;
query_type = ((srv->resolv_opts.family_prio == AF_INET)
? DNS_RTYPE_A
: DNS_RTYPE_AAAA);
break;
case OBJ_TYPE_SRVRQ:
srvrq = (struct resolv_srvrq *)requester;
req = resolv_get_requester(&srvrq->requester,
&srvrq->obj_type,
snr_resolution_cb,
srvrq_resolution_error_cb);
if (!req)
goto err;
hostname_dn = &srvrq->hostname_dn;
hostname_dn_len = srvrq->hostname_dn_len;
resolvers = srvrq->resolvers;
query_type = DNS_RTYPE_SRV;
break;
case OBJ_TYPE_STREAM:
stream = (struct stream *)requester;
req = resolv_get_requester(&stream->resolv_ctx.requester,
&stream->obj_type,
act_resolution_cb,
act_resolution_error_cb);
if (!req)
goto err;
hostname_dn = &stream->resolv_ctx.hostname_dn;
hostname_dn_len = stream->resolv_ctx.hostname_dn_len;
resolvers = stream->resolv_ctx.parent->arg.resolv.resolvers;
query_type = ((stream->resolv_ctx.parent->arg.resolv.opts->family_prio == AF_INET)
? DNS_RTYPE_A
: DNS_RTYPE_AAAA);
break;
default:
goto err;
}
/* Get a resolution from the resolvers' wait queue or pool */
if ((res = resolv_pick_resolution(resolvers, hostname_dn, hostname_dn_len, query_type)) == NULL)
goto err;
req->resolution = res;
LIST_APPEND(&res->requesters, &req->list);
leave_resolver_code();
return 0;
err:
if (res && LIST_ISEMPTY(&res->requesters))
resolv_free_resolution(res);
leave_resolver_code();
return -1;
}
/* This function removes all server/srvrq references on answer items. */
void resolv_detach_from_resolution_answer_items(struct resolv_resolution *res, struct resolv_requester *req)
{
struct eb32_node *eb32, *eb32_back;
struct resolv_answer_item *item;
struct server *srv, *srvback;
struct resolv_srvrq *srvrq;
enter_resolver_code();
if ((srv = objt_server(req->owner)) != NULL) {
LIST_DEL_INIT(&srv->ip_rec_item);
}
else if ((srvrq = objt_resolv_srvrq(req->owner)) != NULL) {
for (eb32 = eb32_first(&res->response.answer_tree);
eb32 && (eb32_back = eb32_next(eb32), 1);
eb32 = eb32_back) {
item = eb32_entry(eb32, typeof(*item), link);
if (item->type == DNS_RTYPE_SRV) {
list_for_each_entry_safe(srv, srvback, &item->attached_servers, srv_rec_item) {
if (srv->srvrq == srvrq)
resolv_srvrq_cleanup_srv(srv);
}
}
}
}
leave_resolver_code();
}
/* Removes a requester from a DNS resolution. It takes takes care of all the
* consequences. It also cleans up some parameters from the requester.
*/
static void _resolv_unlink_resolution(struct resolv_requester *requester)
{
struct resolv_resolution *res;
struct resolv_requester *req;
/* Nothing to do */
if (!requester || !requester->resolution)
return;
res = requester->resolution;
/* Clean up the requester */
LIST_DEL_INIT(&requester->list);
requester->resolution = NULL;
/* remove ref from the resolution answer item list to the requester */
resolv_detach_from_resolution_answer_items(res, requester);
/* We need to find another requester linked on this resolution */
if (!LIST_ISEMPTY(&res->requesters))
req = LIST_NEXT(&res->requesters, struct resolv_requester *, list);
else {
abort_resolution(res);
return;
}
/* Move hostname_dn related pointers to the next requester */
switch (obj_type(req->owner)) {
case OBJ_TYPE_SERVER:
res->hostname_dn = __objt_server(req->owner)->hostname_dn;
res->hostname_dn_len = __objt_server(req->owner)->hostname_dn_len;
break;
case OBJ_TYPE_SRVRQ:
res->hostname_dn = __objt_resolv_srvrq(req->owner)->hostname_dn;
res->hostname_dn_len = __objt_resolv_srvrq(req->owner)->hostname_dn_len;
break;
case OBJ_TYPE_STREAM:
res->hostname_dn = __objt_stream(req->owner)->resolv_ctx.hostname_dn;
res->hostname_dn_len = __objt_stream(req->owner)->resolv_ctx.hostname_dn_len;
break;
default:
res->hostname_dn = NULL;
res->hostname_dn_len = 0;
break;
}
}
/* The public version of the function above that deals with the death row. */
void resolv_unlink_resolution(struct resolv_requester *requester)
{
enter_resolver_code();
_resolv_unlink_resolution(requester);
leave_resolver_code();
}
/* Called when a network IO is generated on a name server socket for an incoming
* packet. It performs the following actions:
* - check if the packet requires processing (not outdated resolution)
* - ensure the DNS packet received is valid and call requester's callback
* - call requester's error callback if invalid response
* - check the dn_name in the packet against the one sent
*/
static int resolv_process_responses(struct dns_nameserver *ns)
{
struct dns_counters *tmpcounters;
struct resolvers *resolvers;
struct resolv_resolution *res;
unsigned char buf[DNS_MAX_UDP_MESSAGE + 1];
unsigned char *bufend;
int buflen, dns_resp;
int max_answer_records;
unsigned short query_id;
struct eb32_node *eb;
struct resolv_requester *req;
int keep_answer_items;
resolvers = ns->parent;
enter_resolver_code();
HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
/* process all pending input messages */
while (1) {
/* read message received */
memset(buf, '\0', resolvers->accepted_payload_size + 1);
if ((buflen = dns_recv_nameserver(ns, (void *)buf, sizeof(buf))) <= 0) {
break;
}
/* message too big */
if (buflen > resolvers->accepted_payload_size) {
ns->counters->app.resolver.too_big++;
continue;
}
/* initializing variables */
bufend = buf + buflen; /* pointer to mark the end of the buffer */
/* read the query id from the packet (16 bits) */
if (buf + 2 > bufend) {
ns->counters->app.resolver.invalid++;
continue;
}
query_id = resolv_response_get_query_id(buf);
/* search the query_id in the pending resolution tree */
eb = eb32_lookup(&resolvers->query_ids, query_id);
if (eb == NULL) {
/* unknown query id means an outdated response and can be safely ignored */
ns->counters->app.resolver.outdated++;
continue;
}
/* known query id means a resolution in progress */
res = eb32_entry(eb, struct resolv_resolution, qid);
/* number of responses received */
res->nb_responses++;
max_answer_records = (resolvers->accepted_payload_size - DNS_HEADER_SIZE) / DNS_MIN_RECORD_SIZE;
dns_resp = resolv_validate_dns_response(buf, bufend, res, max_answer_records);
switch (dns_resp) {
case RSLV_RESP_VALID:
break;
case RSLV_RESP_INVALID:
case RSLV_RESP_QUERY_COUNT_ERROR:
case RSLV_RESP_WRONG_NAME:
res->status = RSLV_STATUS_INVALID;
ns->counters->app.resolver.invalid++;
break;
case RSLV_RESP_NX_DOMAIN:
res->status = RSLV_STATUS_NX;
ns->counters->app.resolver.nx++;
break;
case RSLV_RESP_REFUSED:
res->status = RSLV_STATUS_REFUSED;
ns->counters->app.resolver.refused++;
break;
case RSLV_RESP_ANCOUNT_ZERO:
res->status = RSLV_STATUS_OTHER;
ns->counters->app.resolver.any_err++;
break;
case RSLV_RESP_CNAME_ERROR:
res->status = RSLV_STATUS_OTHER;
ns->counters->app.resolver.cname_error++;
break;
case RSLV_RESP_TRUNCATED:
res->status = RSLV_STATUS_OTHER;
ns->counters->app.resolver.truncated++;
break;
case RSLV_RESP_NO_EXPECTED_RECORD:
case RSLV_RESP_ERROR:
case RSLV_RESP_INTERNAL:
res->status = RSLV_STATUS_OTHER;
ns->counters->app.resolver.other++;
break;
}
/* Wait all nameservers response to handle errors */
if (dns_resp != RSLV_RESP_VALID && res->nb_responses < res->nb_queries)
continue;
/* Process error codes */
if (dns_resp != RSLV_RESP_VALID) {
if (res->prefered_query_type != res->query_type) {
/* The fallback on the query type was already performed,
* so check the try counter. If it falls to 0, we can
* report an error. Else, wait the next attempt. */
if (!res->try)
goto report_res_error;
}
else {
/* Fallback from A to AAAA or the opposite and re-send
* the resolution immediately. try counter is not
* decremented. */
if (res->prefered_query_type == DNS_RTYPE_A) {
res->query_type = DNS_RTYPE_AAAA;
resolv_send_query(res);
}
else if (res->prefered_query_type == DNS_RTYPE_AAAA) {
res->query_type = DNS_RTYPE_A;
resolv_send_query(res);
}
}
continue;
}
/* So the resolution succeeded */
res->status = RSLV_STATUS_VALID;
res->last_valid = now_ms;
ns->counters->app.resolver.valid++;
goto report_res_success;
report_res_error:
keep_answer_items = 0;
list_for_each_entry(req, &res->requesters, list)
keep_answer_items |= req->requester_error_cb(req, dns_resp);
if (!keep_answer_items)
resolv_purge_resolution_answer_records(res);
resolv_reset_resolution(res);
LIST_DEL_INIT(&res->list);
LIST_APPEND(&resolvers->resolutions.wait, &res->list);
continue;
report_res_success:
/* Only the 1rst requester s managed by the server, others are
* from the cache */
tmpcounters = ns->counters;
list_for_each_entry(req, &res->requesters, list) {
struct server *s = objt_server(req->owner);
if (s)
HA_SPIN_LOCK(SERVER_LOCK, &s->lock);
req->requester_cb(req, tmpcounters);
if (s)
HA_SPIN_UNLOCK(SERVER_LOCK, &s->lock);
tmpcounters = NULL;
}
resolv_reset_resolution(res);
LIST_DEL_INIT(&res->list);
LIST_APPEND(&resolvers->resolutions.wait, &res->list);
continue;
}
resolv_update_resolvers_timeout(resolvers);
HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
leave_resolver_code();
return buflen;
}
/* Processes DNS resolution. First, it checks the active list to detect expired
* resolutions and retry them if possible. Else a timeout is reported. Then, it
* checks the wait list to trigger new resolutions.
*/
struct task *process_resolvers(struct task *t, void *context, unsigned int state)
{
struct resolvers *resolvers = context;
struct resolv_resolution *res, *resback;
int exp;
enter_resolver_code();
HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
/* Handle all expired resolutions from the active list. Elements that
* need to be removed will in fact be moved to the death_row. Other
* ones will be handled normally.
*/
res = LIST_NEXT(&resolvers->resolutions.curr, struct resolv_resolution *, list);
while (&res->list != &resolvers->resolutions.curr) {
resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
if (LIST_ISEMPTY(&res->requesters)) {
abort_resolution(res);
res = resback;
continue;
}
/* When we find the first resolution in the future, then we can
* stop here */
exp = tick_add(res->last_query, resolvers->timeout.retry);
if (!tick_is_expired(exp, now_ms))
break;
/* If current resolution has been tried too many times and
* finishes in timeout we update its status and remove it from
* the list */
if (!res->try) {
struct resolv_requester *req;
int keep_answer_items = 0;
/* Notify the result to the requesters */
if (!res->nb_responses)
res->status = RSLV_STATUS_TIMEOUT;
list_for_each_entry(req, &res->requesters, list)
keep_answer_items |= req->requester_error_cb(req, res->status);
if (!keep_answer_items)
resolv_purge_resolution_answer_records(res);
/* Clean up resolution info and remove it from the
* current list */
resolv_reset_resolution(res);
/* subsequent entries might have been deleted here */
resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
LIST_DEL_INIT(&res->list);
LIST_APPEND(&resolvers->resolutions.wait, &res->list);
res = resback;
}
else {
/* Otherwise resend the DNS query and requeue the resolution */
if (!res->nb_responses || res->prefered_query_type != res->query_type) {
/* No response received (a real timeout) or fallback already done */
res->query_type = res->prefered_query_type;
res->try--;
}
else {
/* Fallback from A to AAAA or the opposite and re-send
* the resolution immediately. try counter is not
* decremented. */
if (res->prefered_query_type == DNS_RTYPE_A)
res->query_type = DNS_RTYPE_AAAA;
else if (res->prefered_query_type == DNS_RTYPE_AAAA)
res->query_type = DNS_RTYPE_A;
else
res->try--;
}
resolv_send_query(res);
resback = LIST_NEXT(&res->list, struct resolv_resolution *, list);
res = resback;
}
}
/* Handle all resolutions in the wait list */
list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
if (unlikely(stopping)) {
/* If haproxy is stopping, check if the resolution to know if it must be run or not.
* If at least a requester is a stream (because of a do-resolv action) or if there
* is a requester attached to a running proxy, the resolution is performed.
* Otherwise, it is skipped for now.
*/
struct resolv_requester *req;
int must_run = 0;
list_for_each_entry(req, &res->requesters, list) {
struct proxy *px = NULL;
switch (obj_type(req->owner)) {
case OBJ_TYPE_SERVER:
px = __objt_server(req->owner)->proxy;
break;
case OBJ_TYPE_SRVRQ:
px = __objt_resolv_srvrq(req->owner)->proxy;
break;
case OBJ_TYPE_STREAM:
/* Always perform the resolution */
must_run = 1;
break;
default:
break;
}
/* Perform the resolution if the proxy is not stopped or disabled */
if (px && !(px->flags & (PR_FL_DISABLED|PR_FL_STOPPED)))
must_run = 1;
if (must_run)
break;
}
if (!must_run) {
/* Skip the reolsution. reset it and wait for the next wakeup */
resolv_reset_resolution(res);
continue;
}
}
if (LIST_ISEMPTY(&res->requesters)) {
abort_resolution(res);
continue;
}
exp = tick_add(res->last_resolution, resolv_resolution_timeout(res));
if (tick_isset(res->last_resolution) && !tick_is_expired(exp, now_ms))
continue;
if (resolv_run_resolution(res) != 1) {
res->last_resolution = now_ms;
LIST_DEL_INIT(&res->list);
LIST_INSERT(&resolvers->resolutions.wait, &res->list);
}
}
resolv_update_resolvers_timeout(resolvers);
HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
if (unlikely(stopping)) {
struct dns_nameserver *ns;
if (LIST_ISEMPTY(&resolvers->resolutions.curr))
t->expire = TICK_ETERNITY;
list_for_each_entry(ns, &resolvers->nameservers, list) {
if (ns->stream)
task_wakeup(ns->stream->task_idle, TASK_WOKEN_MSG);
}
}
/* now we can purge all queued deletions */
leave_resolver_code();
return t;
}
/* destroy a resolvers */
static void resolvers_destroy(struct resolvers *resolvers)
{
struct dns_nameserver *ns, *nsback;
struct resolv_resolution *res, *resback;
struct resolv_requester *req, *reqback;
list_for_each_entry_safe(ns, nsback, &resolvers->nameservers, list) {
free(ns->id);
free((char *)ns->conf.file);
if (ns->dgram) {
if (ns->dgram->conn.t.sock.fd != -1) {
fd_delete(ns->dgram->conn.t.sock.fd);
close(ns->dgram->conn.t.sock.fd);
}
dns_ring_free(ns->dgram->ring_req);
free(ns->dgram);
}
if (ns->stream) {
dns_ring_free(ns->stream->ring_req);
task_destroy(ns->stream->task_req);
task_destroy(ns->stream->task_rsp);
free(ns->stream);
}
LIST_DEL_INIT(&ns->list);
EXTRA_COUNTERS_FREE(ns->extra_counters);
free(ns);
}
list_for_each_entry_safe(res, resback, &resolvers->resolutions.curr, list) {
list_for_each_entry_safe(req, reqback, &res->requesters, list) {
LIST_DEL_INIT(&req->list);
pool_free(resolv_requester_pool, req);
}
resolv_free_resolution(res);
}
list_for_each_entry_safe(res, resback, &resolvers->resolutions.wait, list) {
list_for_each_entry_safe(req, reqback, &res->requesters, list) {
LIST_DEL_INIT(&req->list);
pool_free(resolv_requester_pool, req);
}
resolv_free_resolution(res);
}
free_proxy(resolvers->px);
free(resolvers->id);
free((char *)resolvers->conf.file);
task_destroy(resolvers->t);
LIST_DEL_INIT(&resolvers->list);
free(resolvers);
}
/* Release memory allocated by DNS */
static void resolvers_deinit(void)
{
struct resolvers *resolvers, *resolversback;
struct resolv_srvrq *srvrq, *srvrqback;
list_for_each_entry_safe(resolvers, resolversback, &sec_resolvers, list) {
resolvers_destroy(resolvers);
}
list_for_each_entry_safe(srvrq, srvrqback, &resolv_srvrq_list, list) {
free(srvrq->name);
free(srvrq->hostname_dn);
LIST_DEL_INIT(&srvrq->list);
free(srvrq);
}
}
/* Finalizes the DNS configuration by allocating required resources and checking
* live parameters.
* Returns 0 on success, 1 on error.
*/
static int resolvers_finalize_config(void)
{
struct resolvers *resolvers;
struct proxy *px;
int err_code = 0;
enter_resolver_code();
/* allocate pool of resolution per resolvers */
list_for_each_entry(resolvers, &sec_resolvers, list) {
struct dns_nameserver *ns;
struct task *t;
/* Check if we can create the socket with nameservers info */
list_for_each_entry(ns, &resolvers->nameservers, list) {
int fd;
if (ns->dgram) {
/* Check nameserver info */
if ((fd = socket(ns->dgram->conn.addr.to.ss_family, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
if (!resolvers->conf.implicit) { /* emit a warning only if it was configured manually */
ha_alert("resolvers '%s': can't create socket for nameserver '%s'.\n",
resolvers->id, ns->id);
err_code |= (ERR_ALERT|ERR_ABORT);
}
continue;
}
if (connect(fd, (struct sockaddr*)&ns->dgram->conn.addr.to, get_addr_len(&ns->dgram->conn.addr.to)) == -1) {
if (!resolvers->conf.implicit) { /* emit a warning only if it was configured manually */
ha_warning("resolvers '%s': can't connect socket for nameserver '%s'.\n",
resolvers->id, ns->id);
}
close(fd);
err_code |= ERR_WARN;
continue;
}
close(fd);
}
}
/* Create the task associated to the resolvers section */
if ((t = task_new_anywhere()) == NULL) {
ha_alert("resolvers '%s' : out of memory.\n", resolvers->id);
err_code |= (ERR_ALERT|ERR_ABORT);
goto err;
}
/* Update task's parameters */
t->process = process_resolvers;
t->context = resolvers;
resolvers->t = t;
task_wakeup(t, TASK_WOKEN_INIT);
}
for (px = proxies_list; px; px = px->next) {
struct server *srv;
if (px->flags & PR_FL_DISABLED) {
/* must not run and will not work anyway since
* nothing in the proxy is initialized.
*/
continue;
}
for (srv = px->srv; srv; srv = srv->next) {
struct resolvers *resolvers;
if (!srv->resolvers_id)
continue;
if ((resolvers = find_resolvers_by_id(srv->resolvers_id)) == NULL) {
ha_alert("%s '%s', server '%s': unable to find required resolvers '%s'\n",
proxy_type_str(px), px->id, srv->id, srv->resolvers_id);
err_code |= (ERR_ALERT|ERR_ABORT);
continue;
}
srv->resolvers = resolvers;
srv->srvrq_check = NULL;
if (srv->srvrq) {
if (!srv->srvrq->resolvers) {
srv->srvrq->resolvers = srv->resolvers;
if (resolv_link_resolution(srv->srvrq, OBJ_TYPE_SRVRQ, 0) == -1) {
ha_alert("%s '%s' : unable to set DNS resolution for server '%s'.\n",
proxy_type_str(px), px->id, srv->id);
err_code |= (ERR_ALERT|ERR_ABORT);
continue;
}
}
srv->srvrq_check = task_new_anywhere();
if (!srv->srvrq_check) {
ha_alert("%s '%s' : unable to create SRVRQ task for server '%s'.\n",
proxy_type_str(px), px->id, srv->id);
err_code |= (ERR_ALERT|ERR_ABORT);
goto err;
}
srv->srvrq_check->process = resolv_srvrq_expire_task;
srv->srvrq_check->context = srv;
srv->srvrq_check->expire = TICK_ETERNITY;
}
else if (resolv_link_resolution(srv, OBJ_TYPE_SERVER, 0) == -1) {
ha_alert("%s '%s', unable to set DNS resolution for server '%s'.\n",
proxy_type_str(px), px->id, srv->id);
err_code |= (ERR_ALERT|ERR_ABORT);
continue;
}
srv->flags |= SRV_F_NON_PURGEABLE;
}
}
if (err_code & (ERR_ALERT|ERR_ABORT))
goto err;
leave_resolver_code();
return 0;
err:
leave_resolver_code();
resolvers_deinit();
return 1;
}
static int stats_dump_resolv_to_buffer(struct stconn *sc,
struct dns_nameserver *ns,
struct field *stats, size_t stats_count,
struct list *stat_modules)
{
struct appctx *appctx = __sc_appctx(sc);
struct stats_module *mod;
size_t idx = 0;
memset(stats, 0, sizeof(struct field) * stats_count);
list_for_each_entry(mod, stat_modules, list) {
struct counters_node *counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
if (!mod->fill_stats(counters, stats + idx, NULL))
continue;
idx += mod->stats_count;
}
if (!stats_dump_one_line(stats, idx, appctx))
return 0;
if (!stats_putchk(appctx, NULL, NULL))
goto full;
return 1;
full:
return 0;
}
/* Uses <appctx.ctx.stats.obj1> as a pointer to the current resolver and <obj2>
* as a pointer to the current nameserver.
*/
int stats_dump_resolvers(struct stconn *sc,
struct field *stats, size_t stats_count,
struct list *stat_modules)
{
struct appctx *appctx = __sc_appctx(sc);
struct show_stat_ctx *ctx = appctx->svcctx;
struct channel *rep = sc_ic(sc);
struct resolvers *resolver = ctx->obj1;
struct dns_nameserver *ns = ctx->obj2;
if (!resolver)
resolver = LIST_NEXT(&sec_resolvers, struct resolvers *, list);
/* dump resolvers */
list_for_each_entry_from(resolver, &sec_resolvers, list) {
ctx->obj1 = resolver;
ns = ctx->obj2 ?
ctx->obj2 :
LIST_NEXT(&resolver->nameservers, struct dns_nameserver *, list);
list_for_each_entry_from(ns, &resolver->nameservers, list) {
ctx->obj2 = ns;
if (buffer_almost_full(&rep->buf)) {
sc_need_room(sc, b_size(&rep->buf) / 2);
goto full;
}
if (!stats_dump_resolv_to_buffer(sc, ns,
stats, stats_count,
stat_modules)) {
return 0;
}
}
ctx->obj2 = NULL;
}
return 1;
full:
return 0;
}
void resolv_stats_clear_counters(int clrall, struct list *stat_modules)
{
struct resolvers *resolvers;
struct dns_nameserver *ns;
struct stats_module *mod;
void *counters;
list_for_each_entry(mod, stat_modules, list) {
if (!mod->clearable && !clrall)
continue;
list_for_each_entry(resolvers, &sec_resolvers, list) {
list_for_each_entry(ns, &resolvers->nameservers, list) {
counters = EXTRA_COUNTERS_GET(ns->extra_counters, mod);
memcpy(counters, mod->counters, mod->counters_size);
}
}
}
}
int resolv_allocate_counters(struct list *stat_modules)
{
struct stats_module *mod;
struct resolvers *resolvers;
struct dns_nameserver *ns;
list_for_each_entry(resolvers, &sec_resolvers, list) {
list_for_each_entry(ns, &resolvers->nameservers, list) {
EXTRA_COUNTERS_REGISTER(&ns->extra_counters, COUNTERS_RSLV,
alloc_failed);
list_for_each_entry(mod, stat_modules, list) {
EXTRA_COUNTERS_ADD(mod,
ns->extra_counters,
mod->counters,
mod->counters_size);
}
EXTRA_COUNTERS_ALLOC(ns->extra_counters, alloc_failed);
list_for_each_entry(mod, stat_modules, list) {
memcpy(ns->extra_counters->data + mod->counters_off[ns->extra_counters->type],
mod->counters, mod->counters_size);
/* Store the ns counters pointer */
if (strcmp(mod->name, "resolvers") == 0) {
ns->counters = (struct dns_counters *)ns->extra_counters->data + mod->counters_off[COUNTERS_RSLV];
ns->counters->id = ns->id;
ns->counters->ns_puid = ns->puid;
ns->counters->pid = resolvers->id;
}
}
}
}
return 1;
alloc_failed:
return 0;
}
/* if an arg is found, it sets the optional resolvers section pointer into a
* show_resolvers_ctx struct pointed to by svcctx, or NULL when dumping all.
*/
static int cli_parse_stat_resolvers(char **args, char *payload, struct appctx *appctx, void *private)
{
struct show_resolvers_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
struct resolvers *presolvers;
if (*args[2]) {
list_for_each_entry(presolvers, &sec_resolvers, list) {
if (strcmp(presolvers->id, args[2]) == 0) {
ctx->forced_section = presolvers;
break;
}
}
if (ctx->forced_section == NULL)
return cli_err(appctx, "Can't find that resolvers section\n");
}
return 0;
}
/* Dumps counters from all resolvers section and associated name servers. It
* returns 0 if the output buffer is full and it needs to be called again,
* otherwise non-zero. It may limit itself to the resolver pointed to by the
* <resolvers> field of struct show_resolvers_ctx pointed to by <svcctx> if
* it's not null.
*/
static int cli_io_handler_dump_resolvers_to_buffer(struct appctx *appctx)
{
struct show_resolvers_ctx *ctx = appctx->svcctx;
struct resolvers *resolvers = ctx->resolvers;
struct dns_nameserver *ns;
chunk_reset(&trash);
if (LIST_ISEMPTY(&sec_resolvers)) {
if (applet_putstr(appctx, "No resolvers found\n") == -1)
goto full;
}
else {
if (!resolvers)
resolvers = LIST_ELEM(sec_resolvers.n, typeof(resolvers), list);
list_for_each_entry_from(resolvers, &sec_resolvers, list) {
if (ctx->forced_section != NULL && ctx->forced_section != resolvers)
continue;
ctx->resolvers = resolvers;
ns = ctx->ns;
if (!ns) {
chunk_printf(&trash, "Resolvers section %s\n", resolvers->id);
if (applet_putchk(appctx, &trash) == -1)
goto full;
ns = LIST_ELEM(resolvers->nameservers.n, typeof(ns), list);
ctx->ns = ns;
}
list_for_each_entry_from(ns, &resolvers->nameservers, list) {
chunk_reset(&trash);
chunk_appendf(&trash, " nameserver %s:\n", ns->id);
chunk_appendf(&trash, " sent: %lld\n", ns->counters->sent);
chunk_appendf(&trash, " snd_error: %lld\n", ns->counters->snd_error);
chunk_appendf(&trash, " valid: %lld\n", ns->counters->app.resolver.valid);
chunk_appendf(&trash, " update: %lld\n", ns->counters->app.resolver.update);
chunk_appendf(&trash, " cname: %lld\n", ns->counters->app.resolver.cname);
chunk_appendf(&trash, " cname_error: %lld\n", ns->counters->app.resolver.cname_error);
chunk_appendf(&trash, " any_err: %lld\n", ns->counters->app.resolver.any_err);
chunk_appendf(&trash, " nx: %lld\n", ns->counters->app.resolver.nx);
chunk_appendf(&trash, " timeout: %lld\n", ns->counters->app.resolver.timeout);
chunk_appendf(&trash, " refused: %lld\n", ns->counters->app.resolver.refused);
chunk_appendf(&trash, " other: %lld\n", ns->counters->app.resolver.other);
chunk_appendf(&trash, " invalid: %lld\n", ns->counters->app.resolver.invalid);
chunk_appendf(&trash, " too_big: %lld\n", ns->counters->app.resolver.too_big);
chunk_appendf(&trash, " truncated: %lld\n", ns->counters->app.resolver.truncated);
chunk_appendf(&trash, " outdated: %lld\n", ns->counters->app.resolver.outdated);
if (applet_putchk(appctx, &trash) == -1)
goto full;
ctx->ns = ns;
}
ctx->ns = NULL;
/* was this the only section to dump ? */
if (ctx->forced_section)
break;
}
}
/* done! */
return 1;
full:
/* the output buffer is full, retry later */
return 0;
}
/* register cli keywords */
static struct cli_kw_list cli_kws = {{ }, {
{ { "show", "resolvers", NULL }, "show resolvers [id] : dumps counters from all resolvers section and associated name servers",
cli_parse_stat_resolvers, cli_io_handler_dump_resolvers_to_buffer },
{{},}
}
};
INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
/*
* Prepare <rule> for hostname resolution.
* Returns -1 in case of any allocation failure, 0 if not.
* On error, a global failure counter is also incremented.
*/
static int action_prepare_for_resolution(struct stream *stream, const char *hostname, int hostname_len)
{
char *hostname_dn;
int hostname_dn_len;
struct buffer *tmp = get_trash_chunk();
if (!hostname)
return 0;
hostname_dn = tmp->area;
hostname_dn_len = resolv_str_to_dn_label(hostname, hostname_len,
hostname_dn, tmp->size);
if (hostname_dn_len == -1)
goto err;
stream->resolv_ctx.hostname_dn = strdup(hostname_dn);
stream->resolv_ctx.hostname_dn_len = hostname_dn_len;
if (!stream->resolv_ctx.hostname_dn)
goto err;
return 0;
err:
ha_free(&stream->resolv_ctx.hostname_dn);
resolv_failed_resolutions += 1;
return -1;
}
/*
* Execute the "do-resolution" action. May be called from {tcp,http}request.
*/
enum act_return resolv_action_do_resolve(struct act_rule *rule, struct proxy *px,
struct session *sess, struct stream *s, int flags)
{
struct resolv_resolution *resolution;
struct sample *smp;
struct resolv_requester *req;
struct resolvers *resolvers;
struct resolv_resolution *res;
int exp, locked = 0;
enum act_return ret = ACT_RET_CONT;
resolvers = rule->arg.resolv.resolvers;
enter_resolver_code();
/* we have a response to our DNS resolution */
use_cache:
if (s->resolv_ctx.requester && s->resolv_ctx.requester->resolution != NULL) {
resolution = s->resolv_ctx.requester->resolution;
if (!locked) {
HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
locked = 1;
}
if (resolution->step == RSLV_STEP_RUNNING)
goto yield;
if (resolution->step == RSLV_STEP_NONE) {
/* We update the variable only if we have a valid
* response. If the response was not received yet, we
* must yield.
*/
if (resolution->status == RSLV_STATUS_NONE)
goto yield;
if (resolution->status == RSLV_STATUS_VALID) {
struct sample smp;
short ip_sin_family = 0;
void *ip = NULL;
resolv_get_ip_from_response(&resolution->response, rule->arg.resolv.opts, NULL,
0, &ip, &ip_sin_family, NULL);
switch (ip_sin_family) {
case AF_INET:
smp.data.type = SMP_T_IPV4;
memcpy(&smp.data.u.ipv4, ip, 4);
break;
case AF_INET6:
smp.data.type = SMP_T_IPV6;
memcpy(&smp.data.u.ipv6, ip, 16);
break;
default:
ip = NULL;
}
if (ip) {
smp.px = px;
smp.sess = sess;
smp.strm = s;
vars_set_by_name(rule->arg.resolv.varname, strlen(rule->arg.resolv.varname), &smp);
}
}
}
goto release_requester;
}
/* need to configure and start a new DNS resolution */
smp = sample_fetch_as_type(px, sess, s, SMP_OPT_DIR_REQ|SMP_OPT_FINAL, rule->arg.resolv.expr, SMP_T_STR);
if (smp == NULL)
goto end;
if (action_prepare_for_resolution(s, smp->data.u.str.area, smp->data.u.str.data) == -1)
goto end; /* on error, ignore the action */
s->resolv_ctx.parent = rule;
HA_SPIN_LOCK(DNS_LOCK, &resolvers->lock);
locked = 1;
resolv_link_resolution(s, OBJ_TYPE_STREAM, 0);
/* Check if there is a fresh enough response in the cache of our associated resolution */
req = s->resolv_ctx.requester;
if (!req || !req->resolution)
goto release_requester; /* on error, ignore the action */
res = req->resolution;
exp = tick_add(res->last_resolution, resolvers->hold.valid);
if (resolvers->t && res->status == RSLV_STATUS_VALID && tick_isset(res->last_resolution)
&& !tick_is_expired(exp, now_ms)) {
goto use_cache;
}
resolv_trigger_resolution(s->resolv_ctx.requester);
yield:
if (flags & ACT_OPT_FINAL)
goto release_requester;
ret = ACT_RET_YIELD;
end:
leave_resolver_code();
if (locked)
HA_SPIN_UNLOCK(DNS_LOCK, &resolvers->lock);
return ret;
release_requester:
ha_free(&s->resolv_ctx.hostname_dn);
s->resolv_ctx.hostname_dn_len = 0;
if (s->resolv_ctx.requester) {
_resolv_unlink_resolution(s->resolv_ctx.requester);
pool_free(resolv_requester_pool, s->resolv_ctx.requester);
s->resolv_ctx.requester = NULL;
}
goto end;
}
static void release_resolv_action(struct act_rule *rule)
{
release_sample_expr(rule->arg.resolv.expr);
free(rule->arg.resolv.varname);
free(rule->arg.resolv.resolvers_id);
free(rule->arg.resolv.opts);
}
/* parse "do-resolve" action
* This action takes the following arguments:
* do-resolve(<varName>,<resolversSectionName>,<resolvePrefer>) <expr>
*
* - <varName> is the variable name where the result of the DNS resolution will be stored
* (mandatory)
* - <resolversSectionName> is the name of the resolvers section to use to perform the resolution
* (mandatory)
* - <resolvePrefer> can be either 'ipv4' or 'ipv6' and is the IP family we would like to resolve first
* (optional), defaults to ipv6
* - <expr> is an HAProxy expression used to fetch the name to be resolved
*/
enum act_parse_ret resolv_parse_do_resolve(const char **args, int *orig_arg, struct proxy *px, struct act_rule *rule, char **err)
{
int cur_arg;
struct sample_expr *expr;
unsigned int where;
const char *beg, *end;
/* orig_arg points to the first argument, but we need to analyse the command itself first */
cur_arg = *orig_arg - 1;
/* locate varName, which is mandatory */
beg = strchr(args[cur_arg], '(');
if (beg == NULL)
goto do_resolve_parse_error;
beg = beg + 1; /* beg should points to the first character after opening parenthesis '(' */
end = strchr(beg, ',');
if (end == NULL)
goto do_resolve_parse_error;
rule->arg.resolv.varname = my_strndup(beg, end - beg);
if (rule->arg.resolv.varname == NULL)
goto do_resolve_parse_error;
/* locate resolversSectionName, which is mandatory.
* Since next parameters are optional, the delimiter may be comma ','
* or closing parenthesis ')'
*/
beg = end + 1;
end = strchr(beg, ',');
if (end == NULL)
end = strchr(beg, ')');
if (end == NULL)
goto do_resolve_parse_error;
rule->arg.resolv.resolvers_id = my_strndup(beg, end - beg);
if (rule->arg.resolv.resolvers_id == NULL)
goto do_resolve_parse_error;
rule->arg.resolv.opts = calloc(1, sizeof(*rule->arg.resolv.opts));
if (rule->arg.resolv.opts == NULL)
goto do_resolve_parse_error;
/* Default priority is ipv6 */
rule->arg.resolv.opts->family_prio = AF_INET6;
/* optional arguments accepted for now:
* ipv4 or ipv6
*/
while (*end != ')') {
beg = end + 1;
end = strchr(beg, ',');
if (end == NULL)
end = strchr(beg, ')');
if (end == NULL)
goto do_resolve_parse_error;
if (strncmp(beg, "ipv4", end - beg) == 0) {
rule->arg.resolv.opts->family_prio = AF_INET;
}
else if (strncmp(beg, "ipv6", end - beg) == 0) {
rule->arg.resolv.opts->family_prio = AF_INET6;
}
else {
goto do_resolve_parse_error;
}
}
cur_arg = cur_arg + 1;
expr = sample_parse_expr((char **)args, &cur_arg, px->conf.args.file, px->conf.args.line, err, &px->conf.args, NULL);
if (!expr)
goto do_resolve_parse_error;
where = 0;
if (px->cap & PR_CAP_FE)
where |= SMP_VAL_FE_HRQ_HDR;
if (px->cap & PR_CAP_BE)
where |= SMP_VAL_BE_HRQ_HDR;
if (!(expr->fetch->val & where)) {
memprintf(err,
"fetch method '%s' extracts information from '%s', none of which is available here",
args[cur_arg-1], sample_src_names(expr->fetch->use));
free(expr);
return ACT_RET_PRS_ERR;
}
rule->arg.resolv.expr = expr;
rule->action = ACT_CUSTOM;
rule->action_ptr = resolv_action_do_resolve;
*orig_arg = cur_arg;
rule->check_ptr = check_action_do_resolve;
rule->release_ptr = release_resolv_action;
return ACT_RET_PRS_OK;
do_resolve_parse_error:
ha_free(&rule->arg.resolv.varname);
ha_free(&rule->arg.resolv.resolvers_id);
memprintf(err, "Can't parse '%s'. Expects 'do-resolve(<varname>,<resolvers>[,<options>]) <expr>'. Available options are 'ipv4' and 'ipv6'",
args[cur_arg]);
return ACT_RET_PRS_ERR;
}
static struct action_kw_list http_req_kws = { { }, {
{ "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
{ /* END */ }
}};
INITCALL1(STG_REGISTER, http_req_keywords_register, &http_req_kws);
static struct action_kw_list tcp_req_cont_actions = {ILH, {
{ "do-resolve", resolv_parse_do_resolve, KWF_MATCH_PREFIX },
{ /* END */ }
}};
INITCALL1(STG_REGISTER, tcp_req_cont_keywords_register, &tcp_req_cont_actions);
/* Check an "http-request do-resolve" action.
*
* The function returns 1 in success case, otherwise, it returns 0 and err is
* filled.
*/
int check_action_do_resolve(struct act_rule *rule, struct proxy *px, char **err)
{
struct resolvers *resolvers = NULL;
if (rule->arg.resolv.resolvers_id == NULL) {
memprintf(err,"Proxy '%s': %s", px->id, "do-resolve action without resolvers");
return 0;
}
resolvers = find_resolvers_by_id(rule->arg.resolv.resolvers_id);
if (resolvers == NULL) {
memprintf(err,"Can't find resolvers section '%s' for do-resolve action", rule->arg.resolv.resolvers_id);
return 0;
}
rule->arg.resolv.resolvers = resolvers;
return 1;
}
void resolvers_setup_proxy(struct proxy *px)
{
px->fe_counters.last_change = px->be_counters.last_change = ns_to_sec(now_ns);
px->cap = PR_CAP_FE | PR_CAP_BE;
px->maxconn = 0;
px->conn_retries = 1;
px->timeout.server = TICK_ETERNITY;
px->timeout.client = TICK_ETERNITY;
px->timeout.connect = 1000; // by default same than timeout.resolve
px->accept = NULL;
px->options2 |= PR_O2_INDEPSTR | PR_O2_SMARTCON;
}
static int parse_resolve_conf(char **errmsg, char **warnmsg)
{
struct dns_nameserver *newnameserver = NULL;
const char *whitespace = "\r\n\t ";
char *resolv_line = NULL;
int resolv_linenum = 0;
FILE *f = NULL;
char *address = NULL;
struct sockaddr_storage *sk = NULL;
struct protocol *proto;
int duplicate_name = 0;
int err_code = 0;
if ((resolv_line = malloc(sizeof(*resolv_line) * LINESIZE)) == NULL) {
memprintf(errmsg, "out of memory.\n");
err_code |= ERR_ALERT | ERR_FATAL;
goto resolv_out;
}
if ((f = fopen("/etc/resolv.conf", "r")) == NULL) {
if (errmsg)
memprintf(errmsg, "failed to open /etc/resolv.conf.");
err_code |= ERR_ALERT | ERR_FATAL;
goto resolv_out;
}
sk = calloc(1, sizeof(*sk));
if (sk == NULL) {
if (errmsg)
memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
err_code |= ERR_ALERT | ERR_FATAL;
goto resolv_out;
}
while (fgets(resolv_line, LINESIZE, f) != NULL) {
resolv_linenum++;
if (strncmp(resolv_line, "nameserver", 10) != 0)
continue;
address = strtok(resolv_line + 10, whitespace);
if (address == resolv_line + 10)
continue;
if (address == NULL) {
if (warnmsg)
memprintf(warnmsg, "%sparsing [/etc/resolv.conf:%d] : nameserver line is missing address.\n",
*warnmsg ? *warnmsg : "", resolv_linenum);
err_code |= ERR_WARN;
continue;
}
duplicate_name = 0;
list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
if (strcmp(newnameserver->id, address) == 0) {
if (warnmsg)
memprintf(warnmsg, "%sParsing [/etc/resolv.conf:%d] : generated name for /etc/resolv.conf nameserver '%s' conflicts with another nameserver (declared at %s:%d), it appears to be a duplicate and will be excluded.\n",
*warnmsg ? *warnmsg : "", resolv_linenum, address, newnameserver->conf.file, newnameserver->conf.line);
err_code |= ERR_WARN;
duplicate_name = 1;
}
}
if (duplicate_name)
continue;
memset(sk, 0, sizeof(*sk));
if (!str2ip2(address, sk, 1)) {
if (warnmsg)
memprintf(warnmsg, "%sparsing [/etc/resolv.conf:%d] : address '%s' could not be recognized, nameserver will be excluded.\n",
*warnmsg ? *warnmsg : "", resolv_linenum, address);
err_code |= ERR_WARN;
continue;
}
set_host_port(sk, 53);
proto = protocol_lookup(sk->ss_family, PROTO_TYPE_STREAM, 0);
if (!proto || !proto->connect) {
if (warnmsg)
memprintf(warnmsg, "%sparsing [/etc/resolv.conf:%d] : '%s' : connect() not supported for this address family.\n",
*warnmsg ? *warnmsg : "", resolv_linenum, address);
err_code |= ERR_WARN;
continue;
}
if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
if (errmsg)
memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
err_code |= ERR_ALERT | ERR_FATAL;
goto resolv_out;
}
if (dns_dgram_init(newnameserver, sk) < 0) {
if (errmsg)
memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
err_code |= ERR_ALERT | ERR_FATAL;
free(newnameserver);
goto resolv_out;
}
newnameserver->conf.file = strdup("/etc/resolv.conf");
if (newnameserver->conf.file == NULL) {
if (errmsg)
memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
err_code |= ERR_ALERT | ERR_FATAL;
free(newnameserver);
goto resolv_out;
}
newnameserver->id = strdup(address);
if (newnameserver->id == NULL) {
if (errmsg)
memprintf(errmsg, "parsing [/etc/resolv.conf:%d] : out of memory.", resolv_linenum);
err_code |= ERR_ALERT | ERR_FATAL;
free((char *)newnameserver->conf.file);
free(newnameserver);
goto resolv_out;
}
newnameserver->parent = curr_resolvers;
newnameserver->process_responses = resolv_process_responses;
newnameserver->conf.line = resolv_linenum;
newnameserver->puid = curr_resolvers->nb_nameservers;
LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
curr_resolvers->nb_nameservers++;
}
resolv_out:
free(sk);
free(resolv_line);
if (f != NULL)
fclose(f);
return err_code;
}
static int resolvers_new(struct resolvers **resolvers, const char *id, const char *file, int linenum)
{
struct resolvers *r = NULL;
struct proxy *p = NULL;
int err_code = 0;
if ((r = calloc(1, sizeof(*r))) == NULL) {
err_code |= ERR_ALERT | ERR_ABORT;
goto out;
}
/* allocate new proxy to tcp servers */
p = calloc(1, sizeof *p);
if (!p) {
err_code |= ERR_ALERT | ERR_FATAL;
goto out;
}
init_new_proxy(p);
resolvers_setup_proxy(p);
p->parent = r;
p->id = strdup(id);
p->conf.args.file = p->conf.file = strdup(file);
p->conf.args.line = p->conf.line = linenum;
r->px = p;
/* default values */
LIST_APPEND(&sec_resolvers, &r->list);
r->conf.file = strdup(file);
r->conf.line = linenum;
r->id = strdup(id);
r->query_ids = EB_ROOT;
/* default maximum response size */
r->accepted_payload_size = 512;
/* default hold period for nx, other, refuse and timeout is 30s */
r->hold.nx = 30000;
r->hold.other = 30000;
r->hold.refused = 30000;
r->hold.timeout = 30000;
r->hold.obsolete = 0;
/* default hold period for valid is 10s */
r->hold.valid = 10000;
r->timeout.resolve = 1000;
r->timeout.retry = 1000;
r->resolve_retries = 3;
r->nb_nameservers = 0;
LIST_INIT(&r->nameservers);
LIST_INIT(&r->resolutions.curr);
LIST_INIT(&r->resolutions.wait);
HA_SPIN_INIT(&r->lock);
*resolvers = r;
out:
if (err_code & (ERR_FATAL|ERR_ABORT)) {
ha_free(&r);
ha_free(&p);
}
return err_code;
}
/*
* Parse a <resolvers> section.
* Returns the error code, 0 if OK, or any combination of :
* - ERR_ABORT: must abort ASAP
* - ERR_FATAL: we can continue parsing but not start the service
* - ERR_WARN: a warning has been emitted
* - ERR_ALERT: an alert has been emitted
* Only the two first ones can stop processing, the two others are just
* indicators.
*/
int cfg_parse_resolvers(const char *file, int linenum, char **args, int kwm)
{
const char *err;
int err_code = 0;
char *errmsg = NULL;
char *warnmsg = NULL;
if (strcmp(args[0], "resolvers") == 0) { /* new resolvers section */
if (!*args[1]) {
ha_alert("parsing [%s:%d] : missing name for resolvers section.\n", file, linenum);
err_code |= ERR_ALERT | ERR_ABORT;
goto out;
}
err = invalid_char(args[1]);
if (err) {
ha_alert("parsing [%s:%d] : character '%c' is not permitted in '%s' name '%s'.\n",
file, linenum, *err, args[0], args[1]);
err_code |= ERR_ALERT | ERR_ABORT;
goto out;
}
list_for_each_entry(curr_resolvers, &sec_resolvers, list) {
/* Error if two resolvers owns the same name */
if (strcmp(curr_resolvers->id, args[1]) == 0) {
ha_alert("Parsing [%s:%d]: resolvers '%s' has same name as another resolvers (declared at %s:%d).\n",
file, linenum, args[1], curr_resolvers->conf.file, curr_resolvers->conf.line);
err_code |= ERR_ALERT | ERR_ABORT;
}
}
err_code |= resolvers_new(&curr_resolvers, args[1], file, linenum);
if (err_code & ERR_ALERT) {
ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
goto out;
}
}
else if (strcmp(args[0], "nameserver") == 0) { /* nameserver definition */
struct dns_nameserver *newnameserver = NULL;
struct sockaddr_storage *sk;
int port1, port2;
struct protocol *proto;
if (!*args[2]) {
ha_alert("parsing [%s:%d] : '%s' expects <name> and <addr>[:<port>] as arguments.\n",
file, linenum, args[0]);
err_code |= ERR_ALERT | ERR_FATAL;
goto out;
}
err = invalid_char(args[1]);
if (err) {
ha_alert("parsing [%s:%d] : character '%c' is not permitted in server name '%s'.\n",
file, linenum, *err, args[1]);
err_code |= ERR_ALERT | ERR_FATAL;
goto out;
}
list_for_each_entry(newnameserver, &curr_resolvers->nameservers, list) {
/* Error if two resolvers owns the same name */
if (strcmp(newnameserver->id, args[1]) == 0) {
ha_alert("Parsing [%s:%d]: nameserver '%s' has same name as another nameserver (declared at %s:%d).\n",
file, linenum, args[1], newnameserver->conf.file, newnameserver->conf.line);
err_code |= ERR_ALERT | ERR_FATAL;
}
}
sk = str2sa_range(args[2], NULL, &port1, &port2, NULL, &proto, NULL,
&errmsg, NULL, NULL, PA_O_RESOLVE | PA_O_PORT_OK | PA_O_PORT_MAND | PA_O_DGRAM | PA_O_STREAM | PA_O_DEFAULT_DGRAM);
if (!sk) {
ha_alert("parsing [%s:%d] : '%s %s' : %s\n", file, linenum, args[0], args[1], errmsg);
err_code |= ERR_ALERT | ERR_FATAL;
goto out;
}
if ((newnameserver = calloc(1, sizeof(*newnameserver))) == NULL) {
ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
err_code |= ERR_ALERT | ERR_ABORT;
goto out;
}
if (proto && proto->xprt_type == PROTO_TYPE_STREAM) {
err_code |= parse_server(file, linenum, args, curr_resolvers->px, NULL,
SRV_PARSE_PARSE_ADDR|SRV_PARSE_INITIAL_RESOLVE);
if (err_code & (ERR_FATAL|ERR_ABORT)) {
err_code |= ERR_ABORT;
goto out;
}
if (dns_stream_init(newnameserver, curr_resolvers->px->srv) < 0) {
ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
err_code |= ERR_ALERT|ERR_ABORT;
goto out;
}
}
else if (dns_dgram_init(newnameserver, sk) < 0) {
ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
err_code |= ERR_ALERT | ERR_ABORT;
goto out;
}
if ((newnameserver->conf.file = strdup(file)) == NULL) {
ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
err_code |= ERR_ALERT | ERR_ABORT;
goto out;
}
if ((newnameserver->id = strdup(args[1])) == NULL) {
ha_alert("parsing [%s:%d] : out of memory.\n", file, linenum);
err_code |= ERR_ALERT | ERR_ABORT;
goto out;
}
newnameserver->parent = curr_resolvers;
newnameserver->process_responses = resolv_process_responses;
newnameserver->conf.line = linenum;
newnameserver->puid = curr_resolvers->nb_nameservers;
/* the nameservers are linked backward first */
LIST_APPEND(&curr_resolvers->nameservers, &newnameserver->list);
curr_resolvers->nb_nameservers++;
}
else if (strcmp(args[0], "parse-resolv-conf") == 0) {
err_code |= parse_resolve_conf(&errmsg, &warnmsg);
if (err_code & ERR_WARN) {
indent_msg(&warnmsg, 8);
ha_warning("parsing [%s:%d]: %s\n", file, linenum, warnmsg);
ha_free(&warnmsg);
}
if (err_code & ERR_ALERT) {
indent_msg(&errmsg, 8);
ha_alert("parsing [%s:%d]: %s\n", file, linenum, errmsg);
ha_free(&errmsg);
goto out;
}
}
else if (strcmp(args[0], "hold") == 0) { /* hold periods */
const char *res;
unsigned int time;
if (!*args[2]) {
ha_alert("parsing [%s:%d] : '%s' expects an <event> and a <time> as arguments.\n",
file, linenum, args[0]);
ha_alert("<event> can be either 'valid', 'nx', 'refused', 'timeout', or 'other'\n");
err_code |= ERR_ALERT | ERR_FATAL;
goto out;
}
res = parse_time_err(args[2], &time, TIME_UNIT_MS);
if (res == PARSE_TIME_OVER) {
ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s>, maximum value is 2147483647 ms (~24.8 days).\n",
file, linenum, args[1], args[0]);
err_code |= ERR_ALERT | ERR_FATAL;
goto out;
}
else if (res == PARSE_TIME_UNDER) {
ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s>, minimum non-null value is 1 ms.\n",
file, linenum, args[1], args[0]);
err_code |= ERR_ALERT | ERR_FATAL;
goto out;
}
else if (res) {
ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s>.\n",
file, linenum, *res, args[0]);
err_code |= ERR_ALERT | ERR_FATAL;
goto out;
}
if (strcmp(args[1], "nx") == 0)
curr_resolvers->hold.nx = time;
else if (strcmp(args[1], "other") == 0)
curr_resolvers->hold.other = time;
else if (strcmp(args[1], "refused") == 0)
curr_resolvers->hold.refused = time;
else if (strcmp(args[1], "timeout") == 0)
curr_resolvers->hold.timeout = time;
else if (strcmp(args[1], "valid") == 0)
curr_resolvers->hold.valid = time;
else if (strcmp(args[1], "obsolete") == 0)
curr_resolvers->hold.obsolete = time;
else {
ha_alert("parsing [%s:%d] : '%s' unknown <event>: '%s', expects either 'nx', 'timeout', 'valid', 'obsolete' or 'other'.\n",
file, linenum, args[0], args[1]);
err_code |= ERR_ALERT | ERR_FATAL;
goto out;
}
}
else if (strcmp(args[0], "accepted_payload_size") == 0) {
int i = 0;
if (!*args[1]) {
ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
file, linenum, args[0]);
err_code |= ERR_ALERT | ERR_FATAL;
goto out;
}
i = atoi(args[1]);
if (i < DNS_HEADER_SIZE || i > DNS_MAX_UDP_MESSAGE) {
ha_alert("parsing [%s:%d] : '%s' must be between %d and %d inclusive (was %s).\n",
file, linenum, args[0], DNS_HEADER_SIZE, DNS_MAX_UDP_MESSAGE, args[1]);
err_code |= ERR_ALERT | ERR_FATAL;
goto out;
}
curr_resolvers->accepted_payload_size = i;
}
else if (strcmp(args[0], "resolution_pool_size") == 0) {
ha_alert("parsing [%s:%d] : '%s' directive is not supported anymore (it never appeared in a stable release).\n",
file, linenum, args[0]);
err_code |= ERR_ALERT | ERR_FATAL;
goto out;
}
else if (strcmp(args[0], "resolve_retries") == 0) {
if (!*args[1]) {
ha_alert("parsing [%s:%d] : '%s' expects <nb> as argument.\n",
file, linenum, args[0]);
err_code |= ERR_ALERT | ERR_FATAL;
goto out;
}
curr_resolvers->resolve_retries = atoi(args[1]);
}
else if (strcmp(args[0], "timeout") == 0) {
if (!*args[1]) {
ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments.\n",
file, linenum, args[0]);
err_code |= ERR_ALERT | ERR_FATAL;
goto out;
}
else if (strcmp(args[1], "retry") == 0 ||
strcmp(args[1], "resolve") == 0) {
const char *res;
unsigned int tout;
if (!*args[2]) {
ha_alert("parsing [%s:%d] : '%s %s' expects <time> as argument.\n",
file, linenum, args[0], args[1]);
err_code |= ERR_ALERT | ERR_FATAL;
goto out;
}
res = parse_time_err(args[2], &tout, TIME_UNIT_MS);
if (res == PARSE_TIME_OVER) {
ha_alert("parsing [%s:%d]: timer overflow in argument <%s> to <%s %s>, maximum value is 2147483647 ms (~24.8 days).\n",
file, linenum, args[2], args[0], args[1]);
err_code |= ERR_ALERT | ERR_FATAL;
goto out;
}
else if (res == PARSE_TIME_UNDER) {
ha_alert("parsing [%s:%d]: timer underflow in argument <%s> to <%s %s>, minimum non-null value is 1 ms.\n",
file, linenum, args[2], args[0], args[1]);
err_code |= ERR_ALERT | ERR_FATAL;
goto out;
}
else if (res) {
ha_alert("parsing [%s:%d]: unexpected character '%c' in argument to <%s %s>.\n",
file, linenum, *res, args[0], args[1]);
err_code |= ERR_ALERT | ERR_FATAL;
goto out;
}
if (args[1][2] == 't')
curr_resolvers->timeout.retry = tout;
else {
curr_resolvers->timeout.resolve = tout;
curr_resolvers->px->timeout.connect = tout;
}
}
else {
ha_alert("parsing [%s:%d] : '%s' expects 'retry' or 'resolve' and <time> as arguments got '%s'.\n",
file, linenum, args[0], args[1]);
err_code |= ERR_ALERT | ERR_FATAL;
goto out;
}
}
else if (*args[0] != 0) {
ha_alert("parsing [%s:%d] : unknown keyword '%s' in '%s' section\n", file, linenum, args[0], cursection);
err_code |= ERR_ALERT | ERR_FATAL;
goto out;
}
out:
free(errmsg);
free(warnmsg);
return err_code;
}
/* try to create a "default" resolvers section which uses "/etc/resolv.conf"
*
* This function is opportunistic and does not try to display errors or warnings.
*/
int resolvers_create_default()
{
int err_code = ERR_NONE;
if (global.mode & MODE_MWORKER_WAIT) /* does not create the section if in wait mode */
return ERR_NONE;
/* if the section already exists, do nothing */
if (find_resolvers_by_id("default"))
return ERR_NONE;
curr_resolvers = NULL;
err_code |= resolvers_new(&curr_resolvers, "default", "<internal>", 0);
if (err_code & ERR_CODE)
goto err;
curr_resolvers->conf.implicit = 1;
err_code |= parse_resolve_conf(NULL, NULL);
if (err_code & ERR_CODE)
goto err;
/* check if there was any nameserver in the resolvconf file */
if (LIST_ISEMPTY(&curr_resolvers->nameservers)) {
err_code |= ERR_FATAL;
goto err;
}
err:
if (err_code & ERR_CODE) {
resolvers_destroy(curr_resolvers);
curr_resolvers = NULL;
}
/* we never return an error there, we only try to create this section
* if that's possible */
return ERR_NONE;
}
int cfg_post_parse_resolvers()
{
int err_code = 0;
struct server *srv;
if (curr_resolvers) {
/* prepare forward server descriptors */
if (curr_resolvers->px) {
srv = curr_resolvers->px->srv;
while (srv) {
/* init ssl if needed */
if (srv->use_ssl == 1 && xprt_get(XPRT_SSL) && xprt_get(XPRT_SSL)->prepare_srv) {
if (xprt_get(XPRT_SSL)->prepare_srv(srv)) {
ha_alert("unable to prepare SSL for server '%s' in resolvers section '%s'.\n", srv->id, curr_resolvers->id);
err_code |= ERR_ALERT | ERR_FATAL;
break;
}
}
srv = srv->next;
}
}
}
curr_resolvers = NULL;
return err_code;
}
REGISTER_CONFIG_SECTION("resolvers", cfg_parse_resolvers, cfg_post_parse_resolvers);
REGISTER_POST_DEINIT(resolvers_deinit);
REGISTER_CONFIG_POSTPARSER("dns runtime resolver", resolvers_finalize_config);
REGISTER_PRE_CHECK(resolvers_create_default);
#if defined(USE_PROMEX)
static int rslv_promex_metric_info(unsigned int id, struct promex_metric *metric, struct ist *desc)
{
if (id >= RSLV_STAT_END)
return -1;
if (id == RSLV_STAT_ID || id == RSLV_STAT_PID)
return 0;
*metric = (struct promex_metric){ .n = ist(resolv_stats[id].name), .type = PROMEX_MT_GAUGE, .flags = PROMEX_FL_MODULE_METRIC };
*desc = ist(resolv_stats[id].desc);
return 1;
}
static void *rslv_promex_start_ts(void *unused, unsigned int id)
{
struct resolvers *resolver;
if (LIST_ISEMPTY(&sec_resolvers))
return NULL;
/* Find the first resolvers with at least one nameserver */
list_for_each_entry(resolver, &sec_resolvers, list) {
if (LIST_ISEMPTY(&resolver->nameservers))
continue;
return LIST_NEXT(&resolver->nameservers, struct dns_nameserver *, list);
}
return NULL;
}
static void *rslv_promex_next_ts(void *unused, void *metric_ctx, unsigned int id)
{
struct dns_nameserver *ns = metric_ctx;
struct resolvers *resolver = ns->parent;
ns = LIST_NEXT(&ns->list, struct dns_nameserver *, list);
if (&ns->list == &resolver->nameservers) {
/* Find the next resolver with at least on nameserver */
resolver = LIST_NEXT(&resolver->list, struct resolvers *, list);
list_for_each_entry_from(resolver, &sec_resolvers, list) {
if (LIST_ISEMPTY(&resolver->nameservers))
continue;
return LIST_NEXT(&resolver->nameservers, struct dns_nameserver *, list);
}
ns = NULL;
}
return ns;
}
static int rslv_promex_fill_ts(void *unused, void *metric_ctx, unsigned int id, struct promex_label *labels, struct field *field)
{
struct dns_nameserver *ns = metric_ctx;
struct resolvers *resolver = ns->parent;
struct field stats[RSLV_STAT_END];
int ret;
labels[0].name = ist("resolver");
labels[0].value = ist(resolver->id);
labels[1].name = ist("nameserver");
labels[1].value = ist(ns->id);
ret = resolv_fill_stats(ns->counters, stats, &id);
if (ret == 1)
*field = stats[id];
return ret;
}
static struct promex_module promex_resolver_module = {
.name = IST("resolver"),
.metric_info = rslv_promex_metric_info,
.start_ts = rslv_promex_start_ts,
.next_ts = rslv_promex_next_ts,
.fill_ts = rslv_promex_fill_ts,
.nb_metrics = RSLV_STAT_END,
};
INITCALL1(STG_REGISTER, promex_register_module, &promex_resolver_module);
#endif
|