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
|
/*
* io.c --- routines for dealing with input and output and records
*/
/*
* Copyright (C) 1986, 1988, 1989, 1991-2014 the Free Software Foundation, Inc.
*
* This file is part of GAWK, the GNU implementation of the
* AWK Programming Language.
*
* GAWK 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 3 of the License, or
* (at your option) any later version.
*
* GAWK is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
/* For OSF/1 to get struct sockaddr_storage */
#if defined(__osf__) && !defined(_OSF_SOURCE)
#define _OSF_SOURCE
#endif
#include "awk.h"
#ifdef HAVE_SYS_PARAM_H
#undef RE_DUP_MAX /* avoid spurious conflict w/regex.h */
#include <sys/param.h>
#endif /* HAVE_SYS_PARAM_H */
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif /* HAVE_SYS_IOCTL_H */
#ifndef O_ACCMODE
#define O_ACCMODE (O_RDONLY|O_WRONLY|O_RDWR)
#endif
#if ! defined(S_ISREG) && defined(S_IFREG)
#define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
#endif
#ifdef HAVE_TERMIOS_H
#include <termios.h>
#endif
#ifdef HAVE_STROPTS_H
#include <stropts.h>
#endif
#ifdef HAVE_SOCKETS
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#else
#include <socket.h>
#endif /* HAVE_SYS_SOCKET_H */
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#else /* ! HAVE_NETINET_IN_H */
#include <in.h>
#endif /* HAVE_NETINET_IN_H */
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif /* HAVE_NETDB_H */
#ifndef HAVE_GETADDRINFO
#include "missing_d/getaddrinfo.h"
#endif
#ifndef AI_ADDRCONFIG /* not everyone has this symbol */
#define AI_ADDRCONFIG 0
#endif /* AI_ADDRCONFIG */
#ifndef HAVE_SOCKADDR_STORAGE
#define sockaddr_storage sockaddr /* for older systems */
#endif /* HAVE_SOCKADDR_STORAGE */
#endif /* HAVE_SOCKETS */
#ifndef AF_UNSPEC
#define AF_UNSPEC 0
#endif
#ifndef AF_INET
#define AF_INET 2
#endif
#ifndef AF_INET6
#define AF_INET6 10
#endif
#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif
#if defined(HAVE_POPEN_H)
#include "popen.h"
#endif
#ifdef __EMX__
#include <process.h>
#endif
#ifndef ENFILE
#define ENFILE EMFILE
#endif
#if defined(__DJGPP__)
#define closemaybesocket(fd) close(fd)
#endif
#if defined(VMS)
#include <ssdef.h>
#ifndef SS$_EXBYTLM
#define SS$_EXBYTLM 0x2a14 /* VMS 8.4 seen */
#endif
#include <rmsdef.h>
#define closemaybesocket(fd) close(fd)
#endif
#ifdef HAVE_SOCKETS
#ifndef SHUT_RD
# ifdef SD_RECEIVE
# define SHUT_RD SD_RECEIVE
# else
# define SHUT_RD 0
# endif
#endif
#ifndef SHUT_WR
# ifdef SD_SEND
# define SHUT_WR SD_SEND
# else
# define SHUT_WR 1
# endif
#endif
#ifndef SHUT_RDWR
# ifdef SD_BOTH
# define SHUT_RDWR SD_BOTH
# else
# define SHUT_RDWR 2
# endif
#endif
/* MinGW defines non-trivial macros on pc/socket.h. */
#ifndef FD_TO_SOCKET
# define FD_TO_SOCKET(fd) (fd)
# define closemaybesocket(fd) close(fd)
#endif
#ifndef SOCKET_TO_FD
# define SOCKET_TO_FD(s) (s)
# define SOCKET int
#endif
#endif /* HAVE_SOCKETS */
#ifndef HAVE_SETSID
#define setsid() /* nothing */
#endif /* HAVE_SETSID */
#if defined(GAWK_AIX)
#undef TANDEM /* AIX defines this in one of its header files */
#endif
#ifdef __DJGPP__
#define PIPES_SIMULATED
#endif
#ifdef __MINGW32__
# ifndef PIPES_SIMULATED
# define pipe(fds) _pipe(fds, 0, O_NOINHERIT)
# endif
#endif
#ifdef HAVE_MPFR
/* increment NR or FNR */
#define INCREMENT_REC(X) (do_mpfr && X == (LONG_MAX - 1)) ? \
(mpz_add_ui(M##X, M##X, 1), X = 0) : X++
#else
#define INCREMENT_REC(X) X++
#endif
typedef enum { CLOSE_ALL, CLOSE_TO, CLOSE_FROM } two_way_close_type;
/* Several macros to make the code a bit clearer. */
#define at_eof(iop) (((iop)->flag & IOP_AT_EOF) != 0)
#define has_no_data(iop) ((iop)->dataend == NULL)
#define no_data_left(iop) ((iop)->off >= (iop)->dataend)
/*
* The key point to the design is to split out the code that searches through
* a buffer looking for the record and the terminator into separate routines,
* with a higher-level routine doing the reading of data and buffer management.
* This makes the code easier to manage; the buffering code is the same
* independent of how we find a record. Communication is via the return
* value:
*/
typedef enum recvalues {
REC_OK, /* record and terminator found, recmatch struct filled in */
NOTERM, /* no terminator found, give me more input data */
TERMATEND, /* found terminator at end of buffer */
TERMNEAREND /* found terminator close to end of buffer, for when
the RE might be match more data further in
the file. */
} RECVALUE;
/*
* Between calls to a scanning routine, the state is stored in
* an enum scanstate variable. Not all states apply to all
* variants, but the higher code doesn't really care.
*/
typedef enum scanstate {
NOSTATE, /* scanning not started yet (all) */
INLEADER, /* skipping leading data (RS = "") */
INDATA, /* in body of record (all) */
INTERM /* scanning terminator (RS = "", RS = regexp) */
} SCANSTATE;
/*
* When a record is seen (REC_OK or TERMATEND), the following
* structure is filled in.
*/
struct recmatch {
char *start; /* record start */
size_t len; /* length of record */
char *rt_start; /* start of terminator */
size_t rt_len; /* length of terminator */
};
static int iop_close(IOBUF *iop);
struct redirect *redirect(NODE *redir_exp, int redirtype, int *errflg);
static void close_one(void);
static int close_redir(struct redirect *rp, bool exitwarn, two_way_close_type how);
#ifndef PIPES_SIMULATED
static int wait_any(int interesting);
#endif
static IOBUF *gawk_popen(const char *cmd, struct redirect *rp);
static IOBUF *iop_alloc(int fd, const char *name, int errno_val);
static IOBUF *iop_finish(IOBUF *iop);
static int gawk_pclose(struct redirect *rp);
static int str2mode(const char *mode);
static int two_way_open(const char *str, struct redirect *rp);
static int pty_vs_pipe(const char *command);
static void find_input_parser(IOBUF *iop);
static bool find_output_wrapper(awk_output_buf_t *outbuf);
static void init_output_wrapper(awk_output_buf_t *outbuf);
static bool find_two_way_processor(const char *name, struct redirect *rp);
static RECVALUE rs1scan(IOBUF *iop, struct recmatch *recm, SCANSTATE *state);
static RECVALUE rsnullscan(IOBUF *iop, struct recmatch *recm, SCANSTATE *state);
static RECVALUE rsrescan(IOBUF *iop, struct recmatch *recm, SCANSTATE *state);
static RECVALUE (*matchrec)(IOBUF *iop, struct recmatch *recm, SCANSTATE *state) = rs1scan;
static int get_a_record(char **out, IOBUF *iop, int *errcode);
static void free_rp(struct redirect *rp);
static int inetfile(const char *str, int *length, int *family);
static NODE *in_PROCINFO(const char *pidx1, const char *pidx2, NODE **full_idx);
static long get_read_timeout(IOBUF *iop);
static ssize_t read_with_timeout(int fd, char *buf, size_t size);
static bool read_can_timeout = false;
static long read_timeout;
static long read_default_timeout;
static struct redirect *red_head = NULL;
static NODE *RS = NULL;
static Regexp *RS_re_yes_case; /* regexp for RS when ignoring case */
static Regexp *RS_re_no_case; /* regexp for RS when not ignoring case */
static Regexp *RS_regexp;
bool RS_is_null;
extern NODE *ARGC_node;
extern NODE *ARGV_node;
extern NODE *ARGIND_node;
extern NODE **fields_arr;
/* init_io --- set up timeout related variables */
void
init_io()
{
long tmout;
/* Only MinGW has a non-trivial implementation of this. */
init_sockets();
/*
* N.B.: all these hacks are to minimize the effect
* on programs that do not care about timeout.
*/
/* Parse the env. variable only once */
tmout = getenv_long("GAWK_READ_TIMEOUT");
if (tmout > 0) {
read_default_timeout = tmout;
read_can_timeout = true;
}
/*
* PROCINFO entries for timeout are dynamic;
* We can't be any more specific than this.
*/
if (PROCINFO_node != NULL)
read_can_timeout = true;
}
#if defined(__DJGPP__) || defined(__MINGW32__) || defined(__EMX__) || defined(__CYGWIN__)
/* binmode --- convert BINMODE to string for fopen */
static const char *
binmode(const char *mode)
{
switch (mode[0]) {
case 'r':
if ((BINMODE & BINMODE_INPUT) != 0)
mode = "rb";
break;
case 'w':
case 'a':
if ((BINMODE & BINMODE_OUTPUT) != 0)
mode = (mode[0] == 'w' ? "wb" : "ab");
break;
}
return mode;
}
#else
#define binmode(mode) (mode)
#endif
#ifdef VMS
/* File pointers have an extra level of indirection, and there are cases where
`stdin' can be null. That can crash gawk if fileno() is used as-is. */
static int vmsrtl_fileno(FILE *);
static int vmsrtl_fileno(fp) FILE *fp; { return fileno(fp); }
#undef fileno
#define fileno(FP) (((FP) && *(FP)) ? vmsrtl_fileno(FP) : -1)
#endif /* VMS */
/* after_beginfile --- reset necessary state after BEGINFILE has run */
void
after_beginfile(IOBUF **curfile)
{
IOBUF *iop;
iop = *curfile;
assert(iop != NULL);
/*
* Input parsers could have been changed by BEGINFILE,
* so delay check until now.
*/
find_input_parser(iop);
if (! iop->valid) {
const char *fname;
int errcode;
bool valid;
fname = iop->public.name;
errcode = iop->errcode;
valid = iop->valid;
errno = 0;
update_ERRNO_int(errcode);
iop_close(iop);
*curfile = NULL;
if (! valid && errcode == EISDIR && ! do_traditional) {
warning(_("command line argument `%s' is a directory: skipped"), fname);
return; /* read next file */
}
fatal(_("cannot open file `%s' for reading (%s)"),
fname, strerror(errcode));
}
}
/* nextfile --- move to the next input data file */
/*
* Return value > 0 ----> run BEGINFILE block
* *curfile = NULL ----> hit EOF, run ENDFILE block
*/
int
nextfile(IOBUF **curfile, bool skipping)
{
static long i = 1;
static bool files = false;
NODE *arg, *tmp;
const char *fname;
int fd = INVALID_HANDLE;
int errcode = 0;
IOBUF *iop = *curfile;
long argc;
if (skipping) { /* for 'nextfile' call */
errcode = 0;
if (iop != NULL) {
errcode = iop->errcode;
(void) iop_close(iop);
}
*curfile = NULL;
return (errcode == 0);
}
if (iop != NULL) {
if (at_eof(iop)) {
assert(iop->public.fd != INVALID_HANDLE);
(void) iop_close(iop);
*curfile = NULL;
return 1; /* run endfile block */
} else
return 0;
}
argc = get_number_si(ARGC_node->var_value);
for (; i < argc; i++) {
tmp = make_number((AWKNUM) i);
(void) force_string(tmp);
arg = in_array(ARGV_node, tmp);
unref(tmp);
if (arg == NULL || arg->stlen == 0)
continue;
arg = force_string(arg);
arg->stptr[arg->stlen] = '\0';
if (! do_traditional) {
unref(ARGIND_node->var_value);
ARGIND_node->var_value = make_number((AWKNUM) i);
}
if (! arg_assign(arg->stptr, false)) {
files = true;
fname = arg->stptr;
/* manage the awk variables: */
unref(FILENAME_node->var_value);
FILENAME_node->var_value = dupnode(arg);
#ifdef HAVE_MPFR
if (is_mpg_number(FNR_node->var_value))
mpz_set_ui(MFNR, 0);
#endif
FNR = 0;
/* IOBUF management: */
errno = 0;
fd = devopen(fname, binmode("r"));
if (fd == INVALID_HANDLE && errno == EMFILE) {
close_one();
close_one();
fd = devopen(fname, binmode("r"));
}
errcode = errno;
if (! do_traditional)
update_ERRNO_int(errno);
iop = iop_alloc(fd, fname, errcode);
*curfile = iop_finish(iop);
if (iop->public.fd == INVALID_HANDLE)
iop->errcode = errcode;
else if (iop->valid)
iop->errcode = 0;
if (! do_traditional && iop->errcode != 0)
update_ERRNO_int(iop->errcode);
return ++i; /* run beginfile block */
}
}
if (files == false) {
files = true;
/* no args. -- use stdin */
/* FNR is init'ed to 0 */
errno = 0;
if (! do_traditional)
update_ERRNO_int(errno);
unref(FILENAME_node->var_value);
FILENAME_node->var_value = make_string("-", 1);
FILENAME_node->var_value->flags |= MAYBE_NUM; /* be pedantic */
fname = "-";
iop = iop_alloc(fileno(stdin), fname, 0);
*curfile = iop_finish(iop);
if (iop->public.fd == INVALID_HANDLE) {
errcode = errno;
errno = 0;
update_ERRNO_int(errno);
(void) iop_close(iop);
*curfile = NULL;
fatal(_("cannot open file `%s' for reading (%s)"),
fname, strerror(errcode));
}
return ++i; /* run beginfile block */
}
return -1; /* end of input, run end block or Op_atexit */
}
/* set_FNR --- update internal FNR from awk variable */
void
set_FNR()
{
NODE *n = FNR_node->var_value;
(void) force_number(n);
#ifdef HAVE_MPFR
if (is_mpg_number(n))
FNR = mpg_set_var(FNR_node);
else
#endif
FNR = get_number_si(n);
}
/* set_NR --- update internal NR from awk variable */
void
set_NR()
{
NODE *n = NR_node->var_value;
(void) force_number(n);
#ifdef HAVE_MPFR
if (is_mpg_number(n))
NR = mpg_set_var(NR_node);
else
#endif
NR = get_number_si(n);
}
/* inrec --- This reads in a record from the input file */
int
inrec(IOBUF *iop, int *errcode)
{
char *begin;
int cnt;
int retval = 0;
if (at_eof(iop) && no_data_left(iop))
cnt = EOF;
else if ((iop->flag & IOP_CLOSED) != 0)
cnt = EOF;
else
cnt = get_a_record(& begin, iop, errcode);
if (cnt == EOF) {
retval = 1;
if (*errcode > 0)
update_ERRNO_int(*errcode);
} else {
INCREMENT_REC(NR);
INCREMENT_REC(FNR);
set_record(begin, cnt);
}
return retval;
}
/* remap_std_file --- reopen a standard descriptor on /dev/null */
static int
remap_std_file(int oldfd)
{
int newfd;
int ret = -1;
/*
* Give OS-specific routines in gawkmisc.c a chance to interpret
* "/dev/null" as appropriate for their platforms.
*/
newfd = os_devopen("/dev/null", O_RDWR);
if (newfd == INVALID_HANDLE)
newfd = open("/dev/null", O_RDWR);
if (newfd >= 0) {
/* if oldfd is open, dup2() will close oldfd for us first. */
ret = dup2(newfd, oldfd);
if (ret == 0)
close(newfd);
} else
ret = 0;
return ret;
}
/* iop_close --- close an open IOP */
static int
iop_close(IOBUF *iop)
{
int ret = 0;
if (iop == NULL)
return 0;
errno = 0;
iop->flag &= ~IOP_AT_EOF;
iop->flag |= IOP_CLOSED; /* there may be dangling pointers */
iop->dataend = NULL;
/*
* Closing standard files can cause crufty code elsewhere to lose.
* So we remap the standard file to /dev/null.
* Thanks to Jim Meyering for the suggestion.
*/
if (iop->public.close_func != NULL)
iop->public.close_func(&iop->public);
if (iop->public.fd != INVALID_HANDLE) {
if (iop->public.fd == fileno(stdin)
|| iop->public.fd == fileno(stdout)
|| iop->public.fd == fileno(stderr))
ret = remap_std_file(iop->public.fd);
else
ret = closemaybesocket(iop->public.fd);
}
if (ret == -1)
warning(_("close of fd %d (`%s') failed (%s)"), iop->public.fd,
iop->public.name, strerror(errno));
/*
* Be careful -- $0 may still reference the buffer even though
* an explicit close is being done; in the future, maybe we
* can do this a bit better.
*/
if (iop->buf) {
if ((fields_arr[0]->stptr >= iop->buf)
&& (fields_arr[0]->stptr < (iop->buf + iop->size))) {
NODE *t;
t = make_string(fields_arr[0]->stptr,
fields_arr[0]->stlen);
unref(fields_arr[0]);
fields_arr[0] = t;
/*
* This used to be here:
*
* reset_record();
*
* Don't do that; reset_record() throws away all fields,
* saves FS etc. We just need to make sure memory isn't
* corrupted and that references to $0 and fields work.
*/
}
efree(iop->buf);
iop->buf = NULL;
}
efree(iop);
return ret == -1 ? 1 : 0;
}
/* redflags2str --- turn redirection flags into a string, for debugging */
const char *
redflags2str(int flags)
{
static const struct flagtab redtab[] = {
{ RED_FILE, "RED_FILE" },
{ RED_PIPE, "RED_PIPE" },
{ RED_READ, "RED_READ" },
{ RED_WRITE, "RED_WRITE" },
{ RED_APPEND, "RED_APPEND" },
{ RED_NOBUF, "RED_NOBUF" },
{ RED_EOF, "RED_EOF" },
{ RED_TWOWAY, "RED_TWOWAY" },
{ RED_PTY, "RED_PTY" },
{ RED_SOCKET, "RED_SOCKET" },
{ RED_TCP, "RED_TCP" },
{ 0, NULL }
};
return genflags2str(flags, redtab);
}
/* redirect --- Redirection for printf and print commands */
struct redirect *
redirect(NODE *redir_exp, int redirtype, int *errflg)
{
struct redirect *rp;
char *str;
int tflag = 0;
int outflag = 0;
const char *direction = "to";
const char *mode;
int fd;
const char *what = NULL;
bool new_rp = false;
int len; /* used with /inet */
static struct redirect *save_rp = NULL; /* hold onto rp that should
* be freed for reuse
*/
if (do_sandbox)
fatal(_("redirection not allowed in sandbox mode"));
switch (redirtype) {
case redirect_append:
tflag = RED_APPEND;
/* FALL THROUGH */
case redirect_output:
outflag = (RED_FILE|RED_WRITE);
tflag |= outflag;
if (redirtype == redirect_output)
what = ">";
else
what = ">>";
break;
case redirect_pipe:
tflag = (RED_PIPE|RED_WRITE);
what = "|";
break;
case redirect_pipein:
tflag = (RED_PIPE|RED_READ);
what = "|";
break;
case redirect_input:
tflag = (RED_FILE|RED_READ);
what = "<";
break;
case redirect_twoway:
tflag = (RED_READ|RED_WRITE|RED_TWOWAY);
what = "|&";
break;
default:
cant_happen();
}
if (do_lint && (redir_exp->flags & STRCUR) == 0)
lintwarn(_("expression in `%s' redirection only has numeric value"),
what);
redir_exp = force_string(redir_exp);
str = redir_exp->stptr;
if (str == NULL || *str == '\0')
fatal(_("expression for `%s' redirection has null string value"),
what);
if (do_lint && (strncmp(str, "0", redir_exp->stlen) == 0
|| strncmp(str, "1", redir_exp->stlen) == 0))
lintwarn(_("filename `%s' for `%s' redirection may be result of logical expression"),
str, what);
#ifdef HAVE_SOCKETS
/*
* Use /inet4 to force IPv4, /inet6 to force IPv6, and plain
* /inet will be whatever we get back from the system.
*/
if (inetfile(str, & len, NULL)) {
tflag |= RED_SOCKET;
if (strncmp(str + len, "tcp/", 4) == 0)
tflag |= RED_TCP; /* use shutdown when closing */
}
#endif /* HAVE_SOCKETS */
for (rp = red_head; rp != NULL; rp = rp->next) {
#ifndef PIPES_SIMULATED
/*
* This is an efficiency hack. We want to
* recover the process slot for dead children,
* if at all possible. Messing with signal() for
* SIGCLD leads to lots of headaches. However, if
* we've gotten EOF from a child input pipeline, it's
* a good bet that the child has died. So recover it.
*/
if ((rp->flag & RED_EOF) != 0 && redirtype == redirect_pipein) {
if (rp->pid != -1)
#ifdef __MINGW32__
/* MinGW cannot wait for any process. */
wait_any(rp->pid);
#else
wait_any(0);
#endif
}
#endif /* PIPES_SIMULATED */
/* now check for a match */
if (strlen(rp->value) == redir_exp->stlen
&& memcmp(rp->value, str, redir_exp->stlen) == 0
&& ((rp->flag & ~(RED_NOBUF|RED_EOF|RED_PTY)) == tflag
|| (outflag != 0
&& (rp->flag & (RED_FILE|RED_WRITE)) == outflag))) {
int rpflag = (rp->flag & ~(RED_NOBUF|RED_EOF|RED_PTY));
int newflag = (tflag & ~(RED_NOBUF|RED_EOF|RED_PTY));
if (do_lint && rpflag != newflag)
lintwarn(
_("unnecessary mixing of `>' and `>>' for file `%.*s'"),
(int) redir_exp->stlen, rp->value);
break;
}
}
if (rp == NULL) {
new_rp = true;
if (save_rp != NULL) {
rp = save_rp;
efree(rp->value);
} else
emalloc(rp, struct redirect *, sizeof(struct redirect), "redirect");
emalloc(str, char *, redir_exp->stlen + 1, "redirect");
memcpy(str, redir_exp->stptr, redir_exp->stlen);
str[redir_exp->stlen] = '\0';
rp->value = str;
rp->flag = tflag;
init_output_wrapper(& rp->output);
rp->output.name = str;
rp->iop = NULL;
rp->pid = -1;
rp->status = 0;
} else
str = rp->value; /* get \0 terminated string */
save_rp = rp;
while (rp->output.fp == NULL && rp->iop == NULL) {
if (! new_rp && (rp->flag & RED_EOF) != 0) {
/*
* Encountered EOF on file or pipe -- must be cleared
* by explicit close() before reading more
*/
save_rp = NULL;
return rp;
}
mode = NULL;
errno = 0;
switch (redirtype) {
case redirect_output:
mode = binmode("w");
if ((rp->flag & RED_USED) != 0)
mode = (rp->mode[1] == 'b') ? "ab" : "a";
break;
case redirect_append:
mode = binmode("a");
break;
case redirect_pipe:
/* synchronize output before new pipe */
(void) flush_io();
os_restore_mode(fileno(stdin));
if ((rp->output.fp = popen(str, binmode("w"))) == NULL)
fatal(_("can't open pipe `%s' for output (%s)"),
str, strerror(errno));
/* set close-on-exec */
os_close_on_exec(fileno(rp->output.fp), str, "pipe", "to");
rp->flag |= RED_NOBUF;
break;
case redirect_pipein:
direction = "from";
if (gawk_popen(str, rp) == NULL)
fatal(_("can't open pipe `%s' for input (%s)"),
str, strerror(errno));
break;
case redirect_input:
direction = "from";
fd = devopen(str, binmode("r"));
if (fd == INVALID_HANDLE && errno == EISDIR) {
*errflg = EISDIR;
/* do not free rp, saving it for reuse (save_rp = rp) */
return NULL;
}
rp->iop = iop_alloc(fd, str, errno);
find_input_parser(rp->iop);
iop_finish(rp->iop);
if (! rp->iop->valid) {
if (! do_traditional && rp->iop->errcode != 0)
update_ERRNO_int(rp->iop->errcode);
iop_close(rp->iop);
rp->iop = NULL;
}
break;
case redirect_twoway:
direction = "to/from";
if (! two_way_open(str, rp)) {
#ifdef HAVE_SOCKETS
if (inetfile(str, NULL, NULL)) {
*errflg = errno;
/* do not free rp, saving it for reuse (save_rp = rp) */
return NULL;
} else
#endif
fatal(_("can't open two way pipe `%s' for input/output (%s)"),
str, strerror(errno));
}
break;
default:
cant_happen();
}
if (mode != NULL) {
errno = 0;
rp->output.mode = mode;
fd = devopen(str, mode);
if (fd > INVALID_HANDLE) {
if (fd == fileno(stdin))
rp->output.fp = stdin;
else if (fd == fileno(stdout))
rp->output.fp = stdout;
else if (fd == fileno(stderr))
rp->output.fp = stderr;
else {
const char *omode = mode;
#if defined(F_GETFL) && defined(O_APPEND)
int fd_flags;
fd_flags = fcntl(fd, F_GETFL);
if (fd_flags != -1 && (fd_flags & O_APPEND) == O_APPEND)
omode = binmode("a");
#endif
os_close_on_exec(fd, str, "file", "");
rp->output.fp = fdopen(fd, (const char *) omode);
rp->mode = (const char *) mode;
/* don't leak file descriptors */
if (rp->output.fp == NULL)
close(fd);
}
if (rp->output.fp != NULL && os_isatty(fd))
rp->flag |= RED_NOBUF;
/* Move rp to the head of the list. */
if (! new_rp && red_head != rp) {
if ((rp->prev->next = rp->next) != NULL)
rp->next->prev = rp->prev;
red_head->prev = rp;
rp->prev = NULL;
rp->next = red_head;
red_head = rp;
}
}
find_output_wrapper(& rp->output);
}
if (rp->output.fp == NULL && rp->iop == NULL) {
/* too many files open -- close one and try again */
if (errno == EMFILE || errno == ENFILE)
close_one();
#ifdef VMS
/* Alpha/VMS V7.1+ C RTL is returning these instead
of EMFILE (haven't tried other post-V6.2 systems) */
else if ((errno == EIO || errno == EVMSERR) &&
(vaxc$errno == SS$_EXQUOTA ||
vaxc$errno == SS$_EXBYTLM ||
vaxc$errno == RMS$_ACC ||
vaxc$errno == RMS$_SYN))
close_one();
#endif
else {
/*
* Some other reason for failure.
*
* On redirection of input from a file,
* just return an error, so e.g. getline
* can return -1. For output to file,
* complain. The shell will complain on
* a bad command to a pipe.
*/
if (errflg != NULL)
*errflg = errno;
if ( redirtype == redirect_output
|| redirtype == redirect_append) {
/* multiple messages make life easier for translators */
if (*direction == 'f')
fatal(_("can't redirect from `%s' (%s)"),
str, strerror(errno));
else
fatal(_("can't redirect to `%s' (%s)"),
str, strerror(errno));
} else {
/* do not free rp, saving it for reuse (save_rp = rp) */
return NULL;
}
}
}
}
if (new_rp) {
/*
* It opened successfully, hook it into the list.
* Maintain the list in most-recently-used first order.
*/
if (red_head != NULL)
red_head->prev = rp;
rp->prev = NULL;
rp->next = red_head;
red_head = rp;
}
save_rp = NULL;
return rp;
}
/* getredirect --- find the struct redirect for this file or pipe */
struct redirect *
getredirect(const char *str, int len)
{
struct redirect *rp;
for (rp = red_head; rp != NULL; rp = rp->next)
if (strlen(rp->value) == len && memcmp(rp->value, str, len) == 0)
return rp;
return NULL;
}
/* close_one --- temporarily close an open file to re-use the fd */
static void
close_one()
{
struct redirect *rp;
struct redirect *rplast = NULL;
static bool warned = false;
if (do_lint && ! warned) {
warned = true;
lintwarn(_("reached system limit for open files: starting to multiplex file descriptors"));
}
/* go to end of list first, to pick up least recently used entry */
for (rp = red_head; rp != NULL; rp = rp->next)
rplast = rp;
/* now work back up through the list */
for (rp = rplast; rp != NULL; rp = rp->prev) {
/* don't close standard files! */
if (rp->output.fp == NULL || rp->output.fp == stderr || rp->output.fp == stdout)
continue;
if ((rp->flag & (RED_FILE|RED_WRITE)) == (RED_FILE|RED_WRITE)) {
rp->flag |= RED_USED;
errno = 0;
if (rp->output.gawk_fclose(rp->output.fp, rp->output.opaque) != 0)
warning(_("close of `%s' failed (%s)."),
rp->value, strerror(errno));
rp->output.fp = NULL;
break;
}
}
if (rp == NULL)
/* surely this is the only reason ??? */
fatal(_("too many pipes or input files open"));
}
/* do_close --- completely close an open file or pipe */
NODE *
do_close(int nargs)
{
NODE *tmp, *tmp2;
struct redirect *rp;
two_way_close_type how = CLOSE_ALL; /* default */
if (nargs == 2) {
/* 2nd arg if present: "to" or "from" for two-way pipe */
/* DO NOT use _() on the strings here! */
tmp2 = POP_STRING();
if (strcasecmp(tmp2->stptr, "to") == 0)
how = CLOSE_TO;
else if (strcasecmp(tmp2->stptr, "from") == 0)
how = CLOSE_FROM;
else {
DEREF(tmp2);
fatal(_("close: second argument must be `to' or `from'"));
}
DEREF(tmp2);
}
tmp = POP_STRING(); /* 1st arg: redir to close */
for (rp = red_head; rp != NULL; rp = rp->next) {
if (strlen(rp->value) == tmp->stlen
&& memcmp(rp->value, tmp->stptr, tmp->stlen) == 0)
break;
}
if (rp == NULL) { /* no match, return -1 */
char *cp;
if (do_lint)
lintwarn(_("close: `%.*s' is not an open file, pipe or co-process"),
(int) tmp->stlen, tmp->stptr);
if (! do_traditional) {
/* update ERRNO manually, using errno = ENOENT is a stretch. */
cp = _("close of redirection that was never opened");
update_ERRNO_string(cp);
}
DEREF(tmp);
return make_number((AWKNUM) -1.0);
}
DEREF(tmp);
fflush(stdout); /* synchronize regular output */
tmp = make_number((AWKNUM) close_redir(rp, false, how));
rp = NULL;
/*
* POSIX says close() returns 0 on success, non-zero otherwise.
* For POSIX, at this point we just return 0. Otherwise we
* return the exit status of the process or of pclose(), depending.
* This whole business is a mess.
*/
if (do_posix) {
unref(tmp);
tmp = make_number((AWKNUM) 0);
}
return tmp;
}
/* close_rp --- separate function to just do closing */
static int
close_rp(struct redirect *rp, two_way_close_type how)
{
int status = 0;
errno = 0;
if ((rp->flag & RED_TWOWAY) != 0) { /* two-way pipe */
/* write end: */
if ((how == CLOSE_ALL || how == CLOSE_TO) && rp->output.fp != NULL) {
#ifdef HAVE_SOCKETS
if ((rp->flag & RED_TCP) != 0)
(void) shutdown(fileno(rp->output.fp), SHUT_WR);
#endif /* HAVE_SOCKETS */
if ((rp->flag & RED_PTY) != 0) {
rp->output.gawk_fwrite("\004\n", sizeof("\004\n") - 1, 1, rp->output.fp, rp->output.opaque);
rp->output.gawk_fflush(rp->output.fp, rp->output.opaque);
}
status = rp->output.gawk_fclose(rp->output.fp, rp->output.opaque);
rp->output.fp = NULL;
}
/* read end: */
if (how == CLOSE_ALL || how == CLOSE_FROM) {
if ((rp->flag & RED_SOCKET) != 0 && rp->iop != NULL) {
#ifdef HAVE_SOCKETS
if ((rp->flag & RED_TCP) != 0)
(void) shutdown(rp->iop->public.fd, SHUT_RD);
#endif /* HAVE_SOCKETS */
(void) iop_close(rp->iop);
} else
status = gawk_pclose(rp);
rp->iop = NULL;
}
} else if ((rp->flag & (RED_PIPE|RED_WRITE)) == (RED_PIPE|RED_WRITE)) {
/* write to pipe */
status = pclose(rp->output.fp);
if ((BINMODE & BINMODE_INPUT) != 0)
os_setbinmode(fileno(stdin), O_BINARY);
rp->output.fp = NULL;
} else if (rp->output.fp != NULL) { /* write to file */
status = rp->output.gawk_fclose(rp->output.fp, rp->output.opaque);
rp->output.fp = NULL;
} else if (rp->iop != NULL) { /* read from pipe/file */
if ((rp->flag & RED_PIPE) != 0) /* read from pipe */
status = gawk_pclose(rp);
/* gawk_pclose sets rp->iop to null */
else { /* read from file */
status = iop_close(rp->iop);
rp->iop = NULL;
}
}
return status;
}
/* close_redir --- close an open file or pipe */
static int
close_redir(struct redirect *rp, bool exitwarn, two_way_close_type how)
{
int status = 0;
if (rp == NULL)
return 0;
if (rp->output.fp == stdout || rp->output.fp == stderr)
goto checkwarn; /* bypass closing, remove from list */
if (do_lint && (rp->flag & RED_TWOWAY) == 0 && how != CLOSE_ALL)
lintwarn(_("close: redirection `%s' not opened with `|&', second argument ignored"),
rp->value);
status = close_rp(rp, how);
if (status != 0) {
int save_errno = errno;
char *s = strerror(save_errno);
/*
* BWK's awk, as far back as SVR4 (1989) would check
* and warn about the status of close. However, when
* we did this we got too many complaints, so we moved
* it to be under lint control.
*/
if (do_lint) {
if ((rp->flag & RED_PIPE) != 0)
lintwarn(_("failure status (%d) on pipe close of `%s' (%s)"),
status, rp->value, s);
else
lintwarn(_("failure status (%d) on file close of `%s' (%s)"),
status, rp->value, s);
}
if (! do_traditional) {
/* set ERRNO too so that program can get at it */
update_ERRNO_int(save_errno);
}
}
checkwarn:
if (exitwarn) {
/*
* Don't use lintwarn() here. If lint warnings are fatal,
* doing so prevents us from closing other open redirections.
*
* Using multiple full messages instead of string parameters
* for the types makes message translation easier.
*/
if ((rp->flag & RED_SOCKET) != 0)
warning(_("no explicit close of socket `%s' provided"),
rp->value);
else if ((rp->flag & RED_TWOWAY) != 0)
warning(_("no explicit close of co-process `%s' provided"),
rp->value);
else if ((rp->flag & RED_PIPE) != 0)
warning(_("no explicit close of pipe `%s' provided"),
rp->value);
else
warning(_("no explicit close of file `%s' provided"),
rp->value);
}
/* remove it from the list if closing both or both ends have been closed */
if (how == CLOSE_ALL || (rp->iop == NULL && rp->output.fp == NULL)) {
if (rp->next != NULL)
rp->next->prev = rp->prev;
if (rp->prev != NULL)
rp->prev->next = rp->next;
else
red_head = rp->next;
free_rp(rp);
}
return status;
}
/* flush_io --- flush all open output files */
int
flush_io()
{
struct redirect *rp;
int status = 0;
errno = 0;
/* we don't warn about stdout/stderr if EPIPE, but we do error exit */
if (fflush(stdout)) {
if (errno != EPIPE)
warning(_("error writing standard output (%s)"), strerror(errno));
status++;
}
if (fflush(stderr)) {
if (errno != EPIPE)
warning(_("error writing standard error (%s)"), strerror(errno));
status++;
}
for (rp = red_head; rp != NULL; rp = rp->next)
/* flush both files and pipes, what the heck */
if ((rp->flag & RED_WRITE) != 0 && rp->output.fp != NULL) {
if (rp->output.gawk_fflush(rp->output.fp, rp->output.opaque)) {
if ((rp->flag & RED_PIPE) != 0)
warning(_("pipe flush of `%s' failed (%s)."),
rp->value, strerror(errno));
else if ((rp->flag & RED_TWOWAY) != 0)
warning(_("co-process flush of pipe to `%s' failed (%s)."),
rp->value, strerror(errno));
else
warning(_("file flush of `%s' failed (%s)."),
rp->value, strerror(errno));
status++;
}
}
if (status != 0)
status = -1; /* canonicalize it */
return status;
}
/* close_io --- close all open files, called when exiting */
int
close_io(bool *stdio_problem)
{
struct redirect *rp;
struct redirect *next;
int status = 0;
errno = 0;
for (rp = red_head; rp != NULL; rp = next) {
next = rp->next;
/*
* close_redir() will print a message if needed.
* if do_lint, warn about lack of explicit close
*/
if (close_redir(rp, do_lint, CLOSE_ALL))
status++;
rp = NULL;
}
/*
* Some of the non-Unix os's have problems doing an fclose()
* on stdout and stderr. Since we don't really need to close
* them, we just flush them, and do that across the board.
*/
*stdio_problem = false;
/* we don't warn about stdout/stderr if EPIPE, but we do error exit */
if (fflush(stdout) != 0) {
if (errno != EPIPE)
warning(_("error writing standard output (%s)"), strerror(errno));
status++;
*stdio_problem = true;
}
if (fflush(stderr) != 0) {
if (errno != EPIPE)
warning(_("error writing standard error (%s)"), strerror(errno));
status++;
*stdio_problem = true;
}
return status;
}
/* str2mode --- convert a string mode to an integer mode */
static int
str2mode(const char *mode)
{
int ret;
const char *second = & mode[1];
if (*second == 'b')
second++;
switch(mode[0]) {
case 'r':
ret = O_RDONLY;
if (*second == '+' || *second == 'w')
ret = O_RDWR;
break;
case 'w':
ret = O_WRONLY|O_CREAT|O_TRUNC;
if (*second == '+' || *second == 'r')
ret = O_RDWR|O_CREAT|O_TRUNC;
break;
case 'a':
ret = O_WRONLY|O_APPEND|O_CREAT;
if (*second == '+')
ret = O_RDWR|O_APPEND|O_CREAT;
break;
default:
ret = 0; /* lint */
cant_happen();
}
if (strchr(mode, 'b') != NULL)
ret |= O_BINARY;
return ret;
}
#ifdef HAVE_SOCKETS
/* socketopen --- open a socket and set it into connected state */
static int
socketopen(int family, int type, const char *localpname,
const char *remotepname, const char *remotehostname)
{
struct addrinfo *lres, *lres0;
struct addrinfo lhints;
struct addrinfo *rres, *rres0;
struct addrinfo rhints;
int lerror, rerror;
int socket_fd = INVALID_HANDLE;
int any_remote_host = (strcmp(remotehostname, "0") == 0);
memset(& lhints, '\0', sizeof (lhints));
lhints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
lhints.ai_socktype = type;
lhints.ai_family = family;
lerror = getaddrinfo(NULL, localpname, & lhints, & lres);
if (lerror) {
if (strcmp(localpname, "0") != 0)
fatal(_("local port %s invalid in `/inet'"), localpname);
lres0 = NULL;
lres = & lhints;
} else
lres0 = lres;
while (lres != NULL) {
memset (& rhints, '\0', sizeof (rhints));
rhints.ai_flags = lhints.ai_flags;
rhints.ai_socktype = lhints.ai_socktype;
rhints.ai_family = lhints.ai_family;
rhints.ai_protocol = lhints.ai_protocol;
rerror = getaddrinfo(any_remote_host ? NULL : remotehostname,
remotepname, & rhints, & rres);
if (rerror) {
if (lres0 != NULL)
freeaddrinfo(lres0);
fatal(_("remote host and port information (%s, %s) invalid"), remotehostname, remotepname);
}
rres0 = rres;
socket_fd = INVALID_HANDLE;
while (rres != NULL) {
socket_fd = socket(rres->ai_family,
rres->ai_socktype, rres->ai_protocol);
if (socket_fd < 0 || socket_fd == INVALID_HANDLE)
goto nextrres;
if (type == SOCK_STREAM) {
int on = 1;
#ifdef SO_LINGER
struct linger linger;
memset(& linger, '\0', sizeof(linger));
#endif
setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR,
(char *) & on, sizeof(on));
#ifdef SO_LINGER
linger.l_onoff = 1;
/* linger for 30/100 second */
linger.l_linger = 30;
setsockopt(socket_fd, SOL_SOCKET, SO_LINGER,
(char *) & linger, sizeof(linger));
#endif
}
if (bind(socket_fd, lres->ai_addr, lres->ai_addrlen) != 0)
goto nextrres;
if (! any_remote_host) { /* not ANY => create a client */
if (connect(socket_fd, rres->ai_addr, rres->ai_addrlen) == 0)
break;
} else { /* remote host is ANY => create a server */
if (type == SOCK_STREAM) {
int clientsocket_fd = INVALID_HANDLE;
struct sockaddr_storage remote_addr;
socklen_t namelen = sizeof(remote_addr);
if (listen(socket_fd, 1) >= 0
&& (clientsocket_fd = accept(socket_fd,
(struct sockaddr *) & remote_addr,
& namelen)) >= 0) {
closemaybesocket(socket_fd);
socket_fd = clientsocket_fd;
break;
}
} else if (type == SOCK_DGRAM) {
#ifdef MSG_PEEK
char buf[10];
struct sockaddr_storage remote_addr;
socklen_t read_len = 0;
if (recvfrom(socket_fd, buf, 1, MSG_PEEK,
(struct sockaddr *) & remote_addr,
& read_len) >= 0
&& read_len
&& connect(socket_fd,
(struct sockaddr *) & remote_addr,
read_len) == 0)
break;
#endif
}
}
nextrres:
if (socket_fd != INVALID_HANDLE)
closemaybesocket(socket_fd);
socket_fd = INVALID_HANDLE;
rres = rres->ai_next;
}
freeaddrinfo(rres0);
if (socket_fd != INVALID_HANDLE)
break;
lres = lres->ai_next;
}
if (lres0)
freeaddrinfo(lres0);
return socket_fd;
}
#endif /* HAVE_SOCKETS */
/* devopen --- handle /dev/std{in,out,err}, /dev/fd/N, regular files */
/*
* Strictly speaking, "name" is not a "const char *" because we temporarily
* change the string.
*/
int
devopen(const char *name, const char *mode)
{
int openfd;
char *cp;
char *ptr;
int flag = 0;
int len;
int family;
if (strcmp(name, "-") == 0)
return fileno(stdin);
flag = str2mode(mode);
openfd = INVALID_HANDLE;
if (do_traditional)
goto strictopen;
if ((openfd = os_devopen(name, flag)) != INVALID_HANDLE) {
os_close_on_exec(openfd, name, "file", "");
return openfd;
}
if (strncmp(name, "/dev/", 5) == 0) {
cp = (char *) name + 5;
if (strcmp(cp, "stdin") == 0 && (flag & O_ACCMODE) == O_RDONLY)
openfd = fileno(stdin);
else if (strcmp(cp, "stdout") == 0 && (flag & O_ACCMODE) == O_WRONLY)
openfd = fileno(stdout);
else if (strcmp(cp, "stderr") == 0 && (flag & O_ACCMODE) == O_WRONLY)
openfd = fileno(stderr);
else if (strncmp(cp, "fd/", 3) == 0) {
struct stat sbuf;
cp += 3;
openfd = (int) strtoul(cp, & ptr, 10);
if (openfd <= INVALID_HANDLE || ptr == cp
|| fstat(openfd, & sbuf) < 0)
openfd = INVALID_HANDLE;
}
/* do not set close-on-exec for inherited fd's */
if (openfd != INVALID_HANDLE)
return openfd;
} else if (inetfile(name, & len, & family)) {
#ifdef HAVE_SOCKETS
/* /inet/protocol/localport/hostname/remoteport */
int protocol;
char *hostname;
char *hostnameslastcharp;
char *localpname;
char *localpnamelastcharp;
cp = (char *) name + len;
/* which protocol? */
if (strncmp(cp, "tcp/", 4) == 0)
protocol = SOCK_STREAM;
else if (strncmp(cp, "udp/", 4) == 0)
protocol = SOCK_DGRAM;
else {
protocol = SOCK_STREAM; /* shut up the compiler */
fatal(_("no (known) protocol supplied in special filename `%s'"),
name);
}
cp += 4;
/* which localport? */
localpname = cp;
while (*cp != '/' && *cp != '\0')
cp++;
/*
* Require a port, let them explicitly put 0 if
* they don't care.
*/
if (*cp != '/' || cp == localpname)
fatal(_("special file name `%s' is incomplete"), name);
/*
* We change the special file name temporarily because we
* need a 0-terminated string here for conversion with atoi().
* By using atoi() the use of decimal numbers is enforced.
*/
*cp = '\0';
localpnamelastcharp = cp;
/* which hostname? */
cp++;
hostname = cp;
while (*cp != '/' && *cp != '\0')
cp++;
if (*cp != '/' || cp == hostname) {
*localpnamelastcharp = '/';
fatal(_("must supply a remote hostname to `/inet'"));
}
*cp = '\0';
hostnameslastcharp = cp;
/* which remoteport? */
cp++;
/*
* The remote port ends the special file name.
* This means there already is a '\0' at the end of the string.
* Therefore no need to patch any string ending.
*
* Here too, require a port, let them explicitly put 0 if
* they don't care.
*/
if (*cp == '\0') {
*localpnamelastcharp = '/';
*hostnameslastcharp = '/';
fatal(_("must supply a remote port to `/inet'"));
}
{
#define DEFAULT_RETRIES 20
static unsigned long def_retries = DEFAULT_RETRIES;
static bool first_time = true;
unsigned long retries = 0;
static long msleep = 1000;
if (first_time) {
char *cp, *end;
unsigned long count = 0;
char *ms2;
first_time = false;
if ((cp = getenv("GAWK_SOCK_RETRIES")) != NULL) {
count = strtoul(cp, & end, 10);
if (end != cp && count > 0)
def_retries = count;
}
/*
* Env var is in milliseconds, paramter to usleep()
* is microseconds, make the conversion. Default is
* 1 millisecond.
*/
if ((ms2 = getenv("GAWK_MSEC_SLEEP")) != NULL) {
msleep = strtol(ms2, & end, 10);
if (end == ms2 || msleep < 0)
msleep = 1000;
else
msleep *= 1000;
}
}
retries = def_retries;
do {
openfd = socketopen(family, protocol, localpname, cp, hostname);
retries--;
} while (openfd == INVALID_HANDLE && retries > 0 && usleep(msleep) == 0);
}
*localpnamelastcharp = '/';
*hostnameslastcharp = '/';
#else /* ! HAVE_SOCKETS */
fatal(_("TCP/IP communications are not supported"));
#endif /* HAVE_SOCKETS */
}
strictopen:
if (openfd == INVALID_HANDLE)
openfd = open(name, flag, 0666);
#if defined(__EMX__) || defined(__MINGW32__)
if (openfd == INVALID_HANDLE && errno == EACCES) {
/* On OS/2 and Windows directory access via open() is
not permitted. */
struct stat buf;
int l, f;
if (!inetfile(name, &l, &f)
&& stat(name, & buf) == 0 && S_ISDIR(buf.st_mode))
errno = EISDIR;
}
#endif
if (openfd != INVALID_HANDLE) {
if (openfd > fileno(stderr))
os_close_on_exec(openfd, name, "file", "");
}
return openfd;
}
/* two_way_open --- open a two way communications channel */
static int
two_way_open(const char *str, struct redirect *rp)
{
static bool no_ptys = false;
#ifdef HAVE_SOCKETS
/* case 1: socket */
if (inetfile(str, NULL, NULL)) {
int fd, newfd;
fd = devopen(str, "rw");
if (fd == INVALID_HANDLE)
return false;
if ((BINMODE & BINMODE_OUTPUT) != 0)
os_setbinmode(fd, O_BINARY);
rp->output.fp = fdopen(fd, binmode("wb"));
if (rp->output.fp == NULL) {
close(fd);
return false;
}
newfd = dup(fd);
if (newfd < 0) {
rp->output.gawk_fclose(rp->output.fp, rp->output.opaque);
return false;
}
if ((BINMODE & BINMODE_INPUT) != 0)
os_setbinmode(newfd, O_BINARY);
os_close_on_exec(fd, str, "socket", "to/from");
os_close_on_exec(newfd, str, "socket", "to/from");
rp->iop = iop_alloc(newfd, str, 0);
rp->output.name = str;
find_input_parser(rp->iop);
iop_finish(rp->iop);
if (! rp->iop->valid) {
if (! do_traditional && rp->iop->errcode != 0)
update_ERRNO_int(rp->iop->errcode);
iop_close(rp->iop);
rp->iop = NULL;
rp->output.gawk_fclose(rp->output.fp, rp->output.opaque);
return false;
}
rp->flag |= RED_SOCKET;
return true;
}
#endif /* HAVE_SOCKETS */
/* case 2: see if an extension wants it */
if (find_two_way_processor(str, rp))
return true;
#if defined(HAVE_TERMIOS_H) && ! defined(ZOS_USS)
/* case 3: use ptys for two-way communications to child */
if (! no_ptys && pty_vs_pipe(str)) {
static bool initialized = false;
static char first_pty_letter;
#if defined(HAVE_GRANTPT) && ! defined(HAVE_POSIX_OPENPT)
static int have_dev_ptmx;
#endif
char slavenam[32];
char c;
int master, dup_master;
int slave;
int save_errno;
pid_t pid;
struct stat statb;
struct termios st;
/* Use array of chars to avoid ASCII / EBCDIC issues */
static char pty_chars[] = "pqrstuvwxyzabcdefghijklmno";
int i;
if (! initialized) {
initialized = true;
#if defined(HAVE_GRANTPT) && ! defined(HAVE_POSIX_OPENPT)
have_dev_ptmx = (stat("/dev/ptmx", & statb) >= 0);
#endif
i = 0;
do {
c = pty_chars[i++];
sprintf(slavenam, "/dev/pty%c0", c);
if (stat(slavenam, & statb) >= 0) {
first_pty_letter = c;
break;
}
} while (pty_chars[i] != '\0');
}
#ifdef HAVE_GRANTPT
#ifdef HAVE_POSIX_OPENPT
{
master = posix_openpt(O_RDWR|O_NOCTTY);
#else
if (have_dev_ptmx) {
master = open("/dev/ptmx", O_RDWR);
#endif
if (master >= 0) {
char *tem;
grantpt(master);
unlockpt(master);
tem = ptsname(master);
if (tem != NULL) {
strcpy(slavenam, tem);
goto got_the_pty;
}
(void) close(master);
}
}
#endif
if (first_pty_letter) {
/*
* Assume /dev/ptyXNN and /dev/ttyXN naming system.
* The FIRST_PTY_LETTER gives the first X to try.
* We try in the sequence FIRST_PTY_LETTER, ..,
* 'z', 'a', .., FIRST_PTY_LETTER.
* Is this worthwhile, or just over-zealous?
*/
c = first_pty_letter;
do {
int i;
char *cp;
for (i = 0; i < 16; i++) {
sprintf(slavenam, "/dev/pty%c%x", c, i);
if (stat(slavenam, & statb) < 0) {
no_ptys = true; /* bypass all this next time */
goto use_pipes;
}
if ((master = open(slavenam, O_RDWR)) >= 0) {
slavenam[sizeof("/dev/") - 1] = 't';
if (access(slavenam, R_OK | W_OK) == 0)
goto got_the_pty;
close(master);
}
}
/* move to next character */
cp = strchr(pty_chars, c);
if (cp[1] != '\0')
cp++;
else
cp = pty_chars;
c = *cp;
} while (c != first_pty_letter);
} else
no_ptys = true;
/* Couldn't find a pty. Fall back to using pipes. */
goto use_pipes;
got_the_pty:
if ((slave = open(slavenam, O_RDWR)) < 0) {
close(master);
fatal(_("could not open `%s', mode `%s'"),
slavenam, "r+");
}
#ifdef I_PUSH
/*
* Push the necessary modules onto the slave to
* get terminal semantics.
*/
ioctl(slave, I_PUSH, "ptem");
ioctl(slave, I_PUSH, "ldterm");
#endif
tcgetattr(slave, & st);
st.c_iflag &= ~(ISTRIP | IGNCR | INLCR | IXOFF);
st.c_iflag |= (ICRNL | IGNPAR | BRKINT | IXON);
st.c_oflag &= ~OPOST;
st.c_cflag &= ~CSIZE;
st.c_cflag |= CREAD | CS8 | CLOCAL;
st.c_lflag &= ~(ECHO | ECHOE | ECHOK | NOFLSH | TOSTOP);
st.c_lflag |= ISIG;
/* Set some control codes to default values */
#ifdef VINTR
st.c_cc[VINTR] = '\003'; /* ^c */
#endif
#ifdef VQUIT
st.c_cc[VQUIT] = '\034'; /* ^| */
#endif
#ifdef VERASE
st.c_cc[VERASE] = '\177'; /* ^? */
#endif
#ifdef VKILL
st.c_cc[VKILL] = '\025'; /* ^u */
#endif
#ifdef VEOF
st.c_cc[VEOF] = '\004'; /* ^d */
#endif
tcsetattr(slave, TCSANOW, & st);
switch (pid = fork()) {
case 0:
/* Child process */
setsid();
#ifdef TIOCSCTTY
ioctl(slave, TIOCSCTTY, 0);
#endif
if (close(master) == -1)
fatal(_("close of master pty failed (%s)"), strerror(errno));
if (close(1) == -1)
fatal(_("close of stdout in child failed (%s)"),
strerror(errno));
if (dup(slave) != 1)
fatal(_("moving slave pty to stdout in child failed (dup: %s)"), strerror(errno));
if (close(0) == -1)
fatal(_("close of stdin in child failed (%s)"),
strerror(errno));
if (dup(slave) != 0)
fatal(_("moving slave pty to stdin in child failed (dup: %s)"), strerror(errno));
if (close(slave))
fatal(_("close of slave pty failed (%s)"), strerror(errno));
/* stderr does NOT get dup'ed onto child's stdout */
signal(SIGPIPE, SIG_DFL);
execl("/bin/sh", "sh", "-c", str, NULL);
_exit(errno == ENOENT ? 127 : 126);
case -1:
save_errno = errno;
close(master);
close(slave);
errno = save_errno;
return false;
}
/* parent */
if (close(slave) != 0) {
close(master);
(void) kill(pid, SIGKILL);
fatal(_("close of slave pty failed (%s)"), strerror(errno));
}
rp->pid = pid;
rp->iop = iop_alloc(master, str, 0);
find_input_parser(rp->iop);
iop_finish(rp->iop);
if (! rp->iop->valid) {
if (! do_traditional && rp->iop->errcode != 0)
update_ERRNO_int(rp->iop->errcode);
iop_close(rp->iop);
rp->iop = NULL;
(void) kill(pid, SIGKILL);
return false;
}
rp->output.name = str;
/*
* Force read and write ends of two-way connection to
* be different fd's so they can be closed independently.
*/
rp->output.mode = "w";
if ((dup_master = dup(master)) < 0
|| (rp->output.fp = fdopen(dup_master, "w")) == NULL) {
iop_close(rp->iop);
rp->iop = NULL;
(void) close(master);
(void) kill(pid, SIGKILL);
if (dup_master > 0)
(void) close(dup_master);
return false;
} else
find_output_wrapper(& rp->output);
rp->flag |= RED_PTY;
os_close_on_exec(master, str, "pipe", "from");
os_close_on_exec(dup_master, str, "pipe", "to");
first_pty_letter = '\0'; /* reset for next command */
return true;
}
#endif /* defined(HAVE_TERMIOS_H) && ! defined(ZOS_USS) */
use_pipes:
#ifndef PIPES_SIMULATED /* real pipes */
/* case 4: two way pipe to a child process */
{
int ptoc[2], ctop[2];
int pid;
int save_errno;
#if defined(__EMX__) || defined(__MINGW32__)
int save_stdout, save_stdin;
#ifdef __MINGW32__
char *qcmd = NULL;
#endif
#endif
if (pipe(ptoc) < 0)
return false; /* errno set, diagnostic from caller */
if (pipe(ctop) < 0) {
save_errno = errno;
close(ptoc[0]);
close(ptoc[1]);
errno = save_errno;
return false;
}
#if defined(__EMX__) || defined(__MINGW32__)
save_stdin = dup(0); /* duplicate stdin */
save_stdout = dup(1); /* duplicate stdout */
if (save_stdout == -1 || save_stdin == -1) {
/* if an error occurs close all open file handles */
save_errno = errno;
if (save_stdin != -1)
close(save_stdin);
if (save_stdout != -1)
close(save_stdout);
close(ptoc[0]); close(ptoc[1]);
close(ctop[0]); close(ctop[1]);
errno = save_errno;
return false;
}
/* connect pipes to stdin and stdout */
close(1); /* close stdout */
if (dup(ctop[1]) != 1) { /* connect pipe input to stdout */
close(save_stdin); close(save_stdout);
close(ptoc[0]); close(ptoc[1]);
close(ctop[0]); close(ctop[1]);
fatal(_("moving pipe to stdout in child failed (dup: %s)"), strerror(errno));
}
close(0); /* close stdin */
if (dup(ptoc[0]) != 0) { /* connect pipe output to stdin */
close(save_stdin); close(save_stdout);
close(ptoc[0]); close(ptoc[1]);
close(ctop[0]); close(ctop[1]);
fatal(_("moving pipe to stdin in child failed (dup: %s)"), strerror(errno));
}
/* none of these handles must be inherited by the child process */
(void) close(ptoc[0]); /* close pipe output, child will use stdin instead */
(void) close(ctop[1]); /* close pipe input, child will use stdout instead */
os_close_on_exec(ptoc[1], str, "pipe", "from"); /* pipe input: output of the parent process */
os_close_on_exec(ctop[0], str, "pipe", "from"); /* pipe output: input of the parent process */
os_close_on_exec(save_stdin, str, "pipe", "from"); /* saved stdin of the parent process */
os_close_on_exec(save_stdout, str, "pipe", "from"); /* saved stdout of the parent process */
/* stderr does NOT get dup'ed onto child's stdout */
#ifdef __EMX__
pid = spawnl(P_NOWAIT, "/bin/sh", "sh", "-c", str, NULL);
#else /* __MINGW32__ */
pid = spawnl(P_NOWAIT, getenv("ComSpec"), "cmd.exe", "/c",
qcmd = quote_cmd(str), NULL);
efree(qcmd);
#endif
/* restore stdin and stdout */
close(1);
if (dup(save_stdout) != 1) {
close(save_stdin); close(save_stdout);
close(ptoc[1]); close(ctop[0]);
fatal(_("restoring stdout in parent process failed\n"));
}
close(save_stdout);
close(0);
if (dup(save_stdin) != 0) {
close(save_stdin);
close(ptoc[1]); close(ctop[0]);
fatal(_("restoring stdin in parent process failed\n"));
}
close(save_stdin);
if (pid < 0) { /* spawnl() failed */
save_errno = errno;
close(ptoc[1]);
close(ctop[0]);
errno = save_errno;
return false;
}
#else /* NOT __EMX__, NOT __MINGW32__ */
if ((pid = fork()) < 0) {
save_errno = errno;
close(ptoc[0]); close(ptoc[1]);
close(ctop[0]); close(ctop[1]);
errno = save_errno;
return false;
}
if (pid == 0) { /* child */
if (close(1) == -1)
fatal(_("close of stdout in child failed (%s)"),
strerror(errno));
if (dup(ctop[1]) != 1)
fatal(_("moving pipe to stdout in child failed (dup: %s)"), strerror(errno));
if (close(0) == -1)
fatal(_("close of stdin in child failed (%s)"),
strerror(errno));
if (dup(ptoc[0]) != 0)
fatal(_("moving pipe to stdin in child failed (dup: %s)"), strerror(errno));
if ( close(ptoc[0]) == -1 || close(ptoc[1]) == -1
|| close(ctop[0]) == -1 || close(ctop[1]) == -1)
fatal(_("close of pipe failed (%s)"), strerror(errno));
/* stderr does NOT get dup'ed onto child's stdout */
execl("/bin/sh", "sh", "-c", str, NULL);
_exit(errno == ENOENT ? 127 : 126);
}
#endif /* NOT __EMX__, NOT __MINGW32__ */
/* parent */
if ((BINMODE & BINMODE_INPUT) != 0)
os_setbinmode(ctop[0], O_BINARY);
if ((BINMODE & BINMODE_OUTPUT) != 0)
os_setbinmode(ptoc[1], O_BINARY);
rp->pid = pid;
rp->iop = iop_alloc(ctop[0], str, 0);
find_input_parser(rp->iop);
iop_finish(rp->iop);
if (! rp->iop->valid) {
if (! do_traditional && rp->iop->errcode != 0)
update_ERRNO_int(rp->iop->errcode);
iop_close(rp->iop);
rp->iop = NULL;
(void) close(ctop[1]);
(void) close(ptoc[0]);
(void) close(ptoc[1]);
(void) kill(pid, SIGKILL);
return false;
}
rp->output.fp = fdopen(ptoc[1], binmode("w"));
rp->output.mode = "w";
rp->output.name = str;
if (rp->output.fp == NULL) {
iop_close(rp->iop);
rp->iop = NULL;
(void) close(ctop[0]);
(void) close(ctop[1]);
(void) close(ptoc[0]);
(void) close(ptoc[1]);
(void) kill(pid, SIGKILL);
return false;
}
else
find_output_wrapper(& rp->output);
#if !defined(__EMX__) && !defined(__MINGW32__)
os_close_on_exec(ctop[0], str, "pipe", "from");
os_close_on_exec(ptoc[1], str, "pipe", "from");
(void) close(ptoc[0]);
(void) close(ctop[1]);
#endif
return true;
}
#else /*PIPES_SIMULATED*/
fatal(_("`|&' not supported"));
/*NOTREACHED*/
return false;
#endif
}
#ifndef PIPES_SIMULATED /* real pipes */
/* wait_any --- wait for a child process, close associated pipe */
static int
wait_any(int interesting) /* pid of interest, if any */
{
RETSIGTYPE (*hstat)(int), (*istat)(int), (*qstat)(int);
int pid;
int status = 0;
struct redirect *redp;
istat = signal(SIGINT, SIG_IGN);
#ifdef __MINGW32__
if (interesting < 0) {
status = -1;
pid = -1;
}
else
pid = _cwait(& status, interesting, 0);
if (pid == interesting && pid > 0) {
for (redp = red_head; redp != NULL; redp = redp->next)
if (interesting == redp->pid) {
redp->pid = -1;
redp->status = status;
break;
}
}
#else
hstat = signal(SIGHUP, SIG_IGN);
qstat = signal(SIGQUIT, SIG_IGN);
for (;;) {
# ifdef HAVE_SYS_WAIT_H /* POSIX compatible sys/wait.h */
pid = wait(& status);
# else
pid = wait((union wait *) & status);
# endif
if (interesting && pid == interesting) {
break;
} else if (pid != -1) {
for (redp = red_head; redp != NULL; redp = redp->next)
if (pid == redp->pid) {
redp->pid = -1;
redp->status = status;
break;
}
}
if (pid == -1 && errno == ECHILD)
break;
}
signal(SIGHUP, hstat);
signal(SIGQUIT, qstat);
#endif
signal(SIGINT, istat);
return status;
}
/* gawk_popen --- open an IOBUF on a child process */
static IOBUF *
gawk_popen(const char *cmd, struct redirect *rp)
{
int p[2];
int pid;
#if defined(__EMX__) || defined(__MINGW32__)
int save_stdout;
#ifdef __MINGW32__
char *qcmd = NULL;
#endif
#endif
/*
* We used to wait for any children to synchronize input and output,
* but this could cause gawk to hang when it is started in a pipeline
* and thus has a child process feeding it input (shell dependent).
*
* (void) wait_any(0); // wait for outstanding processes
*/
if (pipe(p) < 0)
fatal(_("cannot open pipe `%s' (%s)"), cmd, strerror(errno));
#if defined(__EMX__) || defined(__MINGW32__)
rp->iop = NULL;
save_stdout = dup(1); /* save stdout */
if (save_stdout == -1) {
close(p[0]);
close(p[1]);
return NULL; /* failed */
}
close(1); /* close stdout */
if (dup(p[1]) != 1) {
close(p[0]);
close(p[1]);
fatal(_("moving pipe to stdout in child failed (dup: %s)"),
strerror(errno));
}
/* none of these handles must be inherited by the child process */
close(p[1]); /* close pipe input */
os_close_on_exec(p[0], cmd, "pipe", "from"); /* pipe output: input of the parent process */
os_close_on_exec(save_stdout, cmd, "pipe", "from"); /* saved stdout of the parent process */
#ifdef __EMX__
pid = spawnl(P_NOWAIT, "/bin/sh", "sh", "-c", cmd, NULL);
#else /* __MINGW32__ */
pid = spawnl(P_NOWAIT, getenv("ComSpec"), "cmd.exe", "/c",
qcmd = quote_cmd(cmd), NULL);
efree(qcmd);
#endif
/* restore stdout */
close(1);
if (dup(save_stdout) != 1) {
close(p[0]);
fatal(_("restoring stdout in parent process failed\n"));
}
close(save_stdout);
#else /* NOT __EMX__, NOT __MINGW32__ */
if ((pid = fork()) == 0) {
if (close(1) == -1)
fatal(_("close of stdout in child failed (%s)"),
strerror(errno));
if (dup(p[1]) != 1)
fatal(_("moving pipe to stdout in child failed (dup: %s)"), strerror(errno));
if (close(p[0]) == -1 || close(p[1]) == -1)
fatal(_("close of pipe failed (%s)"), strerror(errno));
execl("/bin/sh", "sh", "-c", cmd, NULL);
_exit(errno == ENOENT ? 127 : 126);
}
#endif /* NOT __EMX__, NOT __MINGW32__ */
if (pid == -1) {
close(p[0]); close(p[1]);
fatal(_("cannot create child process for `%s' (fork: %s)"), cmd, strerror(errno));
}
rp->pid = pid;
#if !defined(__EMX__) && !defined(__MINGW32__)
if (close(p[1]) == -1) {
close(p[0]);
fatal(_("close of pipe failed (%s)"), strerror(errno));
}
#endif
os_close_on_exec(p[0], cmd, "pipe", "from");
if ((BINMODE & BINMODE_INPUT) != 0)
os_setbinmode(p[0], O_BINARY);
rp->iop = iop_alloc(p[0], cmd, 0);
find_input_parser(rp->iop);
iop_finish(rp->iop);
if (! rp->iop->valid) {
if (! do_traditional && rp->iop->errcode != 0)
update_ERRNO_int(rp->iop->errcode);
iop_close(rp->iop);
rp->iop = NULL;
}
return rp->iop;
}
/* gawk_pclose --- close an open child pipe */
static int
gawk_pclose(struct redirect *rp)
{
if (rp->iop != NULL)
(void) iop_close(rp->iop);
rp->iop = NULL;
/* process previously found, return stored status */
if (rp->pid == -1)
return rp->status;
rp->status = wait_any(rp->pid);
rp->pid = -1;
return rp->status;
}
#else /* PIPES_SIMULATED */
/*
* use temporary file rather than pipe
* except if popen() provides real pipes too
*/
/* gawk_popen --- open an IOBUF on a child process */
static IOBUF *
gawk_popen(const char *cmd, struct redirect *rp)
{
FILE *current;
os_restore_mode(fileno(stdin));
current = popen(cmd, binmode("r"));
if ((BINMODE & BINMODE_INPUT) != 0)
os_setbinmode(fileno(stdin), O_BINARY);
if (current == NULL)
return NULL;
os_close_on_exec(fileno(current), cmd, "pipe", "from");
rp->iop = iop_alloc(fileno(current), cmd, 0);
find_input_parser(rp->iop);
iop_finish(rp->iop);
if (! rp->iop->valid) {
if (! do_traditional && rp->iop->errcode != 0)
update_ERRNO_int(rp->iop->errcode);
(void) pclose(current);
rp->iop->public.fd = INVALID_HANDLE;
iop_close(rp->iop);
rp->iop = NULL;
current = NULL;
}
rp->ifp = current;
return rp->iop;
}
/* gawk_pclose --- close an open child pipe */
static int
gawk_pclose(struct redirect *rp)
{
int rval, aval, fd = rp->iop->public.fd;
if (rp->iop != NULL) {
rp->iop->public.fd = dup(fd); /* kludge to allow close() + pclose() */
rval = iop_close(rp->iop);
}
rp->iop = NULL;
aval = pclose(rp->ifp);
rp->ifp = NULL;
return (rval < 0 ? rval : aval);
}
#endif /* PIPES_SIMULATED */
/* do_getline_redir --- read in a line, into var and with redirection */
NODE *
do_getline_redir(int into_variable, enum redirval redirtype)
{
struct redirect *rp = NULL;
IOBUF *iop;
int cnt = EOF;
char *s = NULL;
int errcode;
NODE *redir_exp = NULL;
NODE **lhs = NULL;
int redir_error = 0;
if (into_variable)
lhs = POP_ADDRESS();
assert(redirtype != redirect_none);
redir_exp = TOP();
rp = redirect(redir_exp, redirtype, & redir_error);
DEREF(redir_exp);
decr_sp();
if (rp == NULL) {
if (redir_error) { /* failed redirect */
if (! do_traditional)
update_ERRNO_int(redir_error);
}
return make_number((AWKNUM) -1.0);
}
iop = rp->iop;
if (iop == NULL) /* end of input */
return make_number((AWKNUM) 0.0);
errcode = 0;
cnt = get_a_record(& s, iop, & errcode);
if (errcode != 0) {
if (! do_traditional && (errcode != -1))
update_ERRNO_int(errcode);
return make_number((AWKNUM) -1.0);
}
if (cnt == EOF) {
/*
* Don't do iop_close() here if we are
* reading from a pipe; otherwise
* gawk_pclose will not be called.
*/
if ((rp->flag & (RED_PIPE|RED_TWOWAY)) == 0) {
(void) iop_close(iop);
rp->iop = NULL;
}
rp->flag |= RED_EOF; /* sticky EOF */
return make_number((AWKNUM) 0.0);
}
if (lhs == NULL) /* no optional var. */
set_record(s, cnt);
else { /* assignment to variable */
unref(*lhs);
*lhs = make_string(s, cnt);
(*lhs)->flags |= MAYBE_NUM;
}
return make_number((AWKNUM) 1.0);
}
/* do_getline --- read in a line, into var and without redirection */
NODE *
do_getline(int into_variable, IOBUF *iop)
{
int cnt = EOF;
char *s = NULL;
int errcode;
if (iop == NULL) { /* end of input */
if (into_variable)
(void) POP_ADDRESS();
return make_number((AWKNUM) 0.0);
}
errcode = 0;
cnt = get_a_record(& s, iop, & errcode);
if (errcode != 0) {
if (! do_traditional && (errcode != -1))
update_ERRNO_int(errcode);
if (into_variable)
(void) POP_ADDRESS();
return make_number((AWKNUM) -1.0);
}
if (cnt == EOF)
return NULL; /* try next file */
INCREMENT_REC(NR);
INCREMENT_REC(FNR);
if (! into_variable) /* no optional var. */
set_record(s, cnt);
else { /* assignment to variable */
NODE **lhs;
lhs = POP_ADDRESS();
unref(*lhs);
*lhs = make_string(s, cnt);
(*lhs)->flags |= MAYBE_NUM;
}
return make_number((AWKNUM) 1.0);
}
typedef struct {
const char *envname;
char **dfltp; /* pointer to address of default path */
char try_cwd; /* always search current directory? */
char **awkpath; /* array containing library search paths */
int max_pathlen; /* length of the longest item in awkpath */
} path_info;
static path_info pi_awkpath = {
/* envname */ "AWKPATH",
/* dfltp */ & defpath,
/* try_cwd */ true,
};
static path_info pi_awklibpath = {
/* envname */ "AWKLIBPATH",
/* dfltp */ & deflibpath,
/* try_cwd */ false,
};
/* init_awkpath --- split path(=$AWKPATH) into components */
static void
init_awkpath(path_info *pi)
{
char *path;
char *start, *end, *p;
int len, i;
int max_path; /* (# of allocated paths)-1 */
#define INC_PATH 5
pi->max_pathlen = 0;
if ((path = getenv(pi->envname)) == NULL || *path == '\0')
path = pi->dfltp[0];
max_path = INC_PATH;
emalloc(pi->awkpath, char **, (max_path + 1) * sizeof(char *), "init_awkpath");
memset(pi->awkpath, 0, (max_path + 1) * sizeof(char *));
end = start = path;
i = 0;
while (*start) {
while (*end && *end != envsep)
end++;
len = end - start;
if (len > 0) {
emalloc(p, char *, len + 2, "init_awkpath");
memcpy(p, start, len);
/* add directory punctuation if necessary */
if (! isdirpunct(end[-1]))
p[len++] = '/';
p[len] = '\0';
if (i == max_path) {
max_path += INC_PATH;
erealloc(pi->awkpath, char **, (max_path + 1) * sizeof(char *), "init_awkpath");
memset(pi->awkpath + i, 0, (INC_PATH + 1) * sizeof(char *));
}
pi->awkpath[i++] = p;
if (len > pi->max_pathlen)
pi->max_pathlen = len;
}
/* skip one or more envsep char */
while (*end && *end == envsep)
end++;
start = end;
}
pi->awkpath[i] = NULL;
#undef INC_PATH
}
/* get_cwd -- get current working directory */
static char *
get_cwd ()
{
#define BSIZE 100
char *buf;
size_t bsize = BSIZE;
emalloc(buf, char *, bsize * sizeof(char), "get_cwd");
while (true) {
if (getcwd(buf, bsize) == buf)
return buf;
if (errno != ERANGE) {
efree(buf);
return NULL;
}
bsize *= 2;
erealloc(buf, char *, bsize * sizeof(char), "get_cwd");
}
#undef BSIZE
}
/* do_find_source --- search $AWKPATH for file, return NULL if not found */
static char *
do_find_source(const char *src, struct stat *stb, int *errcode, path_info *pi)
{
char *path;
int i;
assert(errcode != NULL);
/* some kind of path name, no search */
if (ispath(src)) {
emalloc(path, char *, strlen(src) + 1, "do_find_source");
strcpy(path, src);
if (stat(path, stb) == 0)
return path;
*errcode = errno;
efree(path);
return NULL;
}
/* try current directory before $AWKPATH search */
if (pi->try_cwd && stat(src, stb) == 0) {
path = get_cwd();
if (path == NULL) {
*errcode = errno;
return NULL;
}
erealloc(path, char *, strlen(path) + strlen(src) + 2, "do_find_source");
#ifdef VMS
if (strcspn(path,">]:") == strlen(path))
strcat(path, "/");
#else
strcat(path, "/");
#endif
strcat(path, src);
return path;
}
if (pi->awkpath == NULL)
init_awkpath(pi);
emalloc(path, char *, pi->max_pathlen + strlen(src) + 1, "do_find_source");
for (i = 0; pi->awkpath[i] != NULL; i++) {
if (strcmp(pi->awkpath[i], "./") == 0 || strcmp(pi->awkpath[i], ".") == 0)
*path = '\0';
else
strcpy(path, pi->awkpath[i]);
strcat(path, src);
if (stat(path, stb) == 0)
return path;
}
/* not found, give up */
*errcode = errno;
efree(path);
return NULL;
}
/* find_source --- find source file with default file extension handling */
char *
find_source(const char *src, struct stat *stb, int *errcode, int is_extlib)
{
char *path;
path_info *pi = (is_extlib ? & pi_awklibpath : & pi_awkpath);
*errcode = 0;
if (src == NULL || *src == '\0')
return NULL;
path = do_find_source(src, stb, errcode, pi);
if (path == NULL && is_extlib) {
char *file_ext;
int save_errno;
size_t src_len;
size_t suffix_len;
#define EXTLIB_SUFFIX "." SHLIBEXT
src_len = strlen(src);
suffix_len = strlen(EXTLIB_SUFFIX);
/* check if already has the SUFFIX */
if (src_len >= suffix_len && strcmp(& src[src_len - suffix_len], EXTLIB_SUFFIX) == 0)
return NULL;
/* append EXTLIB_SUFFIX and try again */
save_errno = errno;
emalloc(file_ext, char *, src_len + suffix_len + 1, "find_source");
sprintf(file_ext, "%s%s", src, EXTLIB_SUFFIX);
path = do_find_source(file_ext, stb, errcode, pi);
efree(file_ext);
if (path == NULL)
errno = save_errno;
return path;
#undef EXTLIB_SUFFIX
}
/*
* Try searching with .awk appended if the platform headers have not specified
* another suffix.
*/
#ifndef DEFAULT_FILETYPE
#define DEFAULT_FILETYPE ".awk"
#endif
#ifdef DEFAULT_FILETYPE
if (! do_traditional && path == NULL) {
char *file_awk;
int save_errno = errno;
#ifdef VMS
int vms_save = vaxc$errno;
#endif
/* append ".awk" and try again */
emalloc(file_awk, char *, strlen(src) +
sizeof(DEFAULT_FILETYPE) + 1, "find_source");
sprintf(file_awk, "%s%s", src, DEFAULT_FILETYPE);
path = do_find_source(file_awk, stb, errcode, pi);
efree(file_awk);
if (path == NULL) {
errno = save_errno;
#ifdef VMS
vaxc$errno = vms_save;
#endif
}
}
#endif /*DEFAULT_FILETYPE*/
return path;
}
/* srcopen --- open source file */
int
srcopen(SRCFILE *s)
{
int fd = INVALID_HANDLE;
if (s->stype == SRC_STDIN)
fd = fileno(stdin);
else if (s->stype == SRC_FILE || s->stype == SRC_INC)
fd = devopen(s->fullpath, "r");
/* set binary mode so that debugger byte offset calculations will be right */
if (fd != INVALID_HANDLE)
os_setbinmode(fd, O_BINARY);
return fd;
}
/* input parsers, mainly for use by extension functions */
static awk_input_parser_t *ip_head, *ip_tail;
/*
* register_input_parser --- add an input parser to the list, FIFO.
* The main reason to use FIFO is to provide the diagnostic
* with the correct information: input parser 2 conflicts
* with input parser 1. Otherwise LIFO would have been easier.
*/
void
register_input_parser(awk_input_parser_t *input_parser)
{
if (input_parser == NULL)
fatal(_("register_input_parser: received NULL pointer"));
input_parser->next = NULL; /* force it */
if (ip_head == NULL) {
ip_head = ip_tail = input_parser;
} else {
ip_tail->next = input_parser;
ip_tail = ip_tail->next;
}
}
/* find_input_parser --- search the list of input parsers */
static void
find_input_parser(IOBUF *iop)
{
awk_input_parser_t *ip, *ip2;
/* if already associated with an input parser, bail out early */
if (iop->public.get_record != NULL)
return;
ip = ip2 = NULL;
for (ip2 = ip_head; ip2 != NULL; ip2 = ip2->next) {
if (ip2->can_take_file(& iop->public)) {
if (ip == NULL)
ip = ip2; /* found first one */
else
fatal(_("input parser `%s' conflicts with previously installed input parser `%s'"),
ip2->name, ip->name);
}
}
if (ip != NULL) {
if (! ip->take_control_of(& iop->public))
warning(_("input parser `%s' failed to open `%s'"),
ip->name, iop->public.name);
else
iop->valid = true;
}
}
/* output wrappers --- for use by extensions */
static awk_output_wrapper_t *op_head, *op_tail;
/*
* register_output_wrapper --- add an output wrapper to the list.
* Same stuff here as for input parsers.
*/
void
register_output_wrapper(awk_output_wrapper_t *wrapper)
{
if (wrapper == NULL)
fatal(_("register_output_wrapper: received NULL pointer"));
wrapper->next = NULL; /* force it */
if (op_head == NULL) {
op_head = op_tail = wrapper;
} else {
op_tail->next = wrapper;
op_tail = op_tail->next;
}
}
/* find_output_wrapper --- search the list of output wrappers */
static bool
find_output_wrapper(awk_output_buf_t *outbuf)
{
awk_output_wrapper_t *op, *op2;
/* if already associated with an output wrapper, bail out early */
if (outbuf->redirected)
return false;
op = op2 = NULL;
for (op2 = op_head; op2 != NULL; op2 = op2->next) {
if (op2->can_take_file(outbuf)) {
if (op == NULL)
op = op2; /* found first one */
else
fatal(_("output wrapper `%s' conflicts with previously installed output wrapper `%s'"),
op2->name, op->name);
}
}
if (op != NULL) {
if (! op->take_control_of(outbuf)) {
warning(_("output wrapper `%s' failed to open `%s'"),
op->name, outbuf->name);
return false;
}
return true;
}
return false;
}
/* two way processors --- for use by extensions */
static awk_two_way_processor_t *tw_head, *tw_tail;
/* register_two_way_processor --- register a two-way I/O processor, for extensions */
void
register_two_way_processor(awk_two_way_processor_t *processor)
{
if (processor == NULL)
fatal(_("register_output_processor: received NULL pointer"));
processor->next = NULL; /* force it */
if (tw_head == NULL) {
tw_head = tw_tail = processor;
} else {
tw_tail->next = processor;
tw_tail = tw_tail->next;
}
}
/* find_two_way_processor --- search the list of two way processors */
static bool
find_two_way_processor(const char *name, struct redirect *rp)
{
awk_two_way_processor_t *tw, *tw2;
/* if already associated with i/o, bail out early */
if ( (rp->iop != NULL && rp->iop->public.fd != INVALID_HANDLE)
|| rp->output.fp != NULL)
return false;
tw = tw2 = NULL;
for (tw2 = tw_head; tw2 != NULL; tw2 = tw2->next) {
if (tw2->can_take_two_way(name)) {
if (tw == NULL)
tw = tw2; /* found first one */
else
fatal(_("two-way processor `%s' conflicts with previously installed two-way processor `%s'"),
tw2->name, tw->name);
}
}
if (tw != NULL) {
if (rp->iop == NULL)
rp->iop = iop_alloc(INVALID_HANDLE, name, 0);
if (! tw->take_control_of(name, & rp->iop->public, & rp->output)) {
warning(_("two way processor `%s' failed to open `%s'"),
tw->name, name);
return false;
}
iop_finish(rp->iop);
return true;
}
return false;
}
/*
* IOBUF management is somewhat complicated. In particular,
* it is possible and OK for an IOBUF to be allocated with
* a file descriptor that is either valid or not usable with
* read(2), in case an input parser will come along later and
* make it readable. Alternatively, an input parser can simply
* come along and take over reading on a valid readable descriptor.
*
* The first stage is simply to allocate the IOBUF. This is done
* during nextfile() for command line files and by redirect()
* and other routines for getline, input pipes, and the input
* side of a two-way pipe.
*
* The second stage is to check for input parsers. This is done
* for command line files in after_beginfile() and for the others
* as part of the full flow. At this point, either:
* - The fd is valid on a readable file
* - The input parser has taken over a valid fd and made
* it usable (e.g., directories)
* - Or the input parser has simply hijacked the reading
* (such as the gawkextlib XML extension)
* If none of those are true, the fd should be closed, reset
* to INVALID_HANDLE, and iop->errcode set to indicate the error
* (EISDIR for directories, EIO for anything else).
* iop->valid should be set to false in this case.
*
* Otherwise, after the second stage, iop->errcode should be
* zero, iop->valid should be true, and iop->public.fd should
* not be INVALID_HANDLE.
*
* The third stage is to set up the rest of the IOBUF for
* use by get_a_record(). In this case, iop->valid must
* be true already, and iop->public.fd cannot be INVALID_HANDLE.
*
* Checking for input parsers for command line files is delayed
* to after_beginfile() so that the BEGINFILE rule has an
* opportunity to look at FILENAME and ERRNO and attempt to
* recover with a custom input parser. The XML extension, in
* particular, relies strongly upon this ability.
*/
/* iop_alloc --- allocate an IOBUF structure for an open fd */
static IOBUF *
iop_alloc(int fd, const char *name, int errno_val)
{
IOBUF *iop;
emalloc(iop, IOBUF *, sizeof(IOBUF), "iop_alloc");
memset(iop, '\0', sizeof(IOBUF));
iop->public.fd = fd;
iop->public.name = name;
iop->public.read_func = ( ssize_t(*)() ) read;
iop->valid = false;
iop->errcode = errno_val;
if (fd != INVALID_HANDLE)
fstat(fd, & iop->public.sbuf);
#if defined(__EMX__) || defined(__MINGW32__)
else if (errno_val == EISDIR) {
iop->public.sbuf.st_mode = (_S_IFDIR | _S_IRWXU);
iop->public.fd = FAKE_FD_VALUE;
}
#endif
return iop;
}
/* iop_finish --- finish setting up an IOBUF */
static IOBUF *
iop_finish(IOBUF *iop)
{
bool isdir = false;
if (iop->public.fd != INVALID_HANDLE) {
if (os_isreadable(& iop->public, & isdir))
iop->valid = true;
else {
if (isdir)
iop->errcode = EISDIR;
else {
iop->errcode = EIO;
/*
* Extensions can supply values that are not
* INVALID_HANDLE but that are also not real
* file descriptors. So check the fd before
* trying to close it, which avoids errors
* on some operating systems.
*
* The fcntl call works for Windows, too.
*/
#if defined(F_GETFL)
if (fcntl(iop->public.fd, F_GETFL) >= 0)
#endif
(void) close(iop->public.fd);
iop->public.fd = INVALID_HANDLE;
}
/*
* Don't close directories: after_beginfile(),
* special cases them.
*/
}
}
if (! iop->valid || iop->public.fd == INVALID_HANDLE)
return iop;
if (os_isatty(iop->public.fd))
iop->flag |= IOP_IS_TTY;
iop->readsize = iop->size = optimal_bufsize(iop->public.fd, & iop->public.sbuf);
if (do_lint && S_ISREG(iop->public.sbuf.st_mode) && iop->public.sbuf.st_size == 0)
lintwarn(_("data file `%s' is empty"), iop->public.name);
iop->errcode = errno = 0;
iop->count = iop->scanoff = 0;
emalloc(iop->buf, char *, iop->size += 2, "iop_finish");
iop->off = iop->buf;
iop->dataend = NULL;
iop->end = iop->buf + iop->size;
iop->flag |= IOP_AT_START;
return iop;
}
#define set_RT_to_null() \
(void)(! do_traditional && (unref(RT_node->var_value), \
RT_node->var_value = dupnode(Nnull_string)))
#define set_RT(str, len) \
(void)(! do_traditional && (unref(RT_node->var_value), \
RT_node->var_value = make_string(str, len)))
/*
* grow_iop_buffer:
*
* grow must increase size of buffer, set end, make sure off and dataend
* point at the right spot.
*/
static void
grow_iop_buffer(IOBUF *iop)
{
size_t valid = iop->dataend - iop->off;
size_t off = iop->off - iop->buf;
size_t newsize;
/*
* Lop off original extra two bytes, double the size,
* add them back.
*/
newsize = ((iop->size - 2) * 2) + 2;
/* Check for overflow */
if (newsize <= iop->size)
fatal(_("could not allocate more input memory"));
/* Make sure there's room for a disk block */
if (newsize - valid < iop->readsize)
newsize += iop->readsize + 2;
/* Check for overflow, again */
if (newsize <= iop->size)
fatal(_("could not allocate more input memory"));
iop->size = newsize;
erealloc(iop->buf, char *, iop->size, "grow_iop_buffer");
iop->off = iop->buf + off;
iop->dataend = iop->off + valid;
iop->end = iop->buf + iop->size;
}
/* Here are the routines. */
/* rs1scan --- scan for a single character record terminator */
static RECVALUE
rs1scan(IOBUF *iop, struct recmatch *recm, SCANSTATE *state)
{
char *bp;
char rs;
#if MBS_SUPPORT
size_t mbclen = 0;
mbstate_t mbs;
#endif
memset(recm, '\0', sizeof(struct recmatch));
rs = RS->stptr[0];
*(iop->dataend) = rs; /* set sentinel */
recm->start = iop->off; /* beginning of record */
bp = iop->off;
if (*state == INDATA) /* skip over data we've already seen */
bp += iop->scanoff;
#if MBS_SUPPORT
/*
* From: Bruno Haible <bruno@clisp.org>
* To: Aharon Robbins <arnold@skeeve.com>, gnits@gnits.org
* Subject: Re: multibyte locales: any way to find if a character isn't multibyte?
* Date: Mon, 23 Jun 2003 12:20:16 +0200
* Cc: isamu@yamato.ibm.com
*
* Hi,
*
* > Is there any way to make the following query to the current locale?
* >
* > Given an 8-bit value, can this value ever appear as part of
* > a multibyte character?
*
* There is no simple answer here. The easiest solution I see is to
* get the current locale's codeset (via locale_charset() which is a
* wrapper around nl_langinfo(CODESET)), and then perform a case-by-case
* treatment of the known multibyte encodings, from GB2312 to EUC-JISX0213;
* for the unibyte encodings, a single btowc() call will tell you.
*
* > This is particularly critical for me for ASCII newline ('\n'). If I
* > can be guaranteed that it never shows up as part of a multibyte character,
* > I can speed up gawk considerably in mulitbyte locales.
*
* This is much simpler to answer!
* In all ASCII based multibyte encodings used for locales today (this
* excludes EBCDIC based doublebyte encodings from IBM, and also excludes
* ISO-2022-JP which is used for email exchange but not as a locale encoding)
* ALL bytes in the range 0x00..0x2F occur only as a single character, not
* as part of a multibyte character.
*
* So it's safe to assume, but deserves a comment in the source.
*
* Bruno
***************************************************************
* From: Bruno Haible <bruno@clisp.org>
* To: Aharon Robbins <arnold@skeeve.com>
* Subject: Re: multibyte locales: any way to find if a character isn't multibyte?
* Date: Mon, 23 Jun 2003 14:27:49 +0200
*
* On Monday 23 June 2003 14:11, you wrote:
*
* > if (rs != '\n' && MB_CUR_MAX > 1) {
*
* If you assume ASCII, you can even write
*
* if (rs >= 0x30 && MB_CUR_MAX > 1) {
*
* (this catches also the space character) but if portability to EBCDIC
* systems is desired, your code is fine as is.
*
* Bruno
*/
/* Thus, the check for \n here; big speedup ! */
if (rs != '\n' && gawk_mb_cur_max > 1) {
int len = iop->dataend - bp;
int found = 0;
memset(& mbs, 0, sizeof(mbstate_t));
do {
if (*bp == rs)
found = 1;
if (is_valid_character(*bp))
mbclen = 1;
else
mbclen = mbrlen(bp, len, & mbs);
if ( mbclen == 1
|| mbclen == (size_t) -1
|| mbclen == (size_t) -2
|| mbclen == 0) {
/* We treat it as a single-byte character. */
mbclen = 1;
}
len -= mbclen;
bp += mbclen;
} while (len > 0 && ! found);
/* Check that newline found isn't the sentinel. */
if (found && (bp - mbclen) < iop->dataend) {
/*
* Set len to what we have so far, in case this is
* all there is.
*/
recm->len = bp - recm->start - mbclen;
recm->rt_start = bp - mbclen;
recm->rt_len = mbclen;
*state = NOSTATE;
return REC_OK;
} else {
/* also set len */
recm->len = bp - recm->start;
*state = INDATA;
iop->scanoff = bp - iop->off;
return NOTERM;
}
}
#endif
while (*bp != rs)
bp++;
/* set len to what we have so far, in case this is all there is */
recm->len = bp - recm->start;
if (bp < iop->dataend) { /* found it in the buffer */
recm->rt_start = bp;
recm->rt_len = 1;
*state = NOSTATE;
return REC_OK;
} else {
*state = INDATA;
iop->scanoff = bp - iop->off;
return NOTERM;
}
}
/* rsrescan --- search for a regex match in the buffer */
static RECVALUE
rsrescan(IOBUF *iop, struct recmatch *recm, SCANSTATE *state)
{
char *bp;
size_t restart = 0, reend = 0;
Regexp *RSre = RS_regexp;
int regex_flags = RE_NEED_START;
memset(recm, '\0', sizeof(struct recmatch));
recm->start = iop->off;
bp = iop->off;
if (*state == INDATA)
bp += iop->scanoff;
if ((iop->flag & IOP_AT_START) == 0)
regex_flags |= RE_NO_BOL;
again:
/* case 1, no match */
if (research(RSre, bp, 0, iop->dataend - bp, regex_flags) == -1) {
/* set len, in case this all there is. */
recm->len = iop->dataend - iop->off;
return NOTERM;
}
/* ok, we matched within the buffer, set start and end */
restart = RESTART(RSre, iop->off);
reend = REEND(RSre, iop->off);
/* case 2, null regex match, grow buffer, try again */
if (restart == reend) {
*state = INDATA;
iop->scanoff = reend + 1;
/*
* If still room in buffer, skip over null match
* and restart search. Otherwise, return.
*/
if (bp + iop->scanoff < iop->dataend) {
bp += iop->scanoff;
goto again;
}
recm->len = (bp - iop->off) + restart;
return NOTERM;
}
/*
* At this point, we have a non-empty match.
*
* First, fill in rest of data. The rest of the cases return
* a record and terminator.
*/
recm->len = restart;
recm->rt_start = bp + restart;
recm->rt_len = reend - restart;
*state = NOSTATE;
/*
* 3. Match exactly at end:
* if re is a simple string match
* found a simple string match at end, return REC_OK
* else
* grow buffer, add more data, try again
* fi
*/
if (iop->off + reend >= iop->dataend) {
if (reisstring(RS->stptr, RS->stlen, RSre, iop->off))
return REC_OK;
else
return TERMATEND;
}
/*
* 4. Match within xxx bytes of end & maybe islong re:
* return TERMNEAREND
*/
/*
* case 4, match succeeded, but there may be more in
* the next input buffer.
*
* Consider an RS of xyz(abc)? where the
* exact end of the buffer is xyza and the
* next two, unread, characters are bc.
*
* This matches the "xyz" and ends up putting the
* "abc" into the front of the next record. Ooops.
*
* The re->maybe_long member is true if the
* regex contains one of: + * ? |. This is a very
* simple heuristic, but in combination with the
* "end of match within a few bytes of end of buffer"
* check, should keep things reasonable.
*/
/* succession of tests is easier to trace in GDB. */
if (RSre->maybe_long) {
char *matchend = iop->off + reend;
if (iop->dataend - matchend < RS->stlen)
return TERMNEAREND;
}
return REC_OK;
}
/* rsnullscan --- handle RS = "" */
static RECVALUE
rsnullscan(IOBUF *iop, struct recmatch *recm, SCANSTATE *state)
{
char *bp;
if (*state == NOSTATE || *state == INLEADER)
memset(recm, '\0', sizeof(struct recmatch));
recm->start = iop->off;
bp = iop->off;
if (*state != NOSTATE)
bp += iop->scanoff;
/* set sentinel */
*(iop->dataend) = '\n';
if (*state == INTERM)
goto find_longest_terminator;
else if (*state == INDATA)
goto scan_data;
/* else
fall into things from beginning,
either NOSTATE or INLEADER */
/* skip_leading: */
/* leading newlines are ignored */
while (*bp == '\n' && bp < iop->dataend)
bp++;
if (bp >= iop->dataend) { /* LOTS of leading newlines, sheesh. */
*state = INLEADER;
iop->scanoff = bp - iop->off;
return NOTERM;
}
iop->off = recm->start = bp; /* real start of record */
scan_data:
while (*bp++ != '\n')
continue;
if (bp >= iop->dataend) { /* no full terminator */
iop->scanoff = recm->len = bp - iop->off - 1;
if (bp == iop->dataend) { /* half a terminator */
recm->rt_start = bp - 1;
recm->rt_len = 1;
}
*state = INDATA;
return NOTERM;
}
/* found one newline before end of buffer, check next char */
if (*bp != '\n')
goto scan_data;
/* we've now seen at least two newlines */
*state = INTERM;
recm->len = bp - iop->off - 1;
recm->rt_start = bp - 1;
find_longest_terminator:
/* find as many newlines as we can, to set RT */
while (*bp == '\n' && bp < iop->dataend)
bp++;
recm->rt_len = bp - recm->rt_start;
iop->scanoff = bp - iop->off;
if (bp >= iop->dataend)
return TERMATEND;
return REC_OK;
}
/*
* get_a_record --- read a record from IOP into out,
* return length of EOF, set RT.
* Note that errcode is never NULL, and the caller initializes *errcode to 0.
*/
static int
get_a_record(char **out, /* pointer to pointer to data */
IOBUF *iop, /* input IOP */
int *errcode) /* pointer to error variable */
{
struct recmatch recm;
SCANSTATE state;
RECVALUE ret;
int retval;
NODE *rtval = NULL;
static RECVALUE (*lastmatchrec)(IOBUF *iop, struct recmatch *recm, SCANSTATE *state) = NULL;
if (at_eof(iop) && no_data_left(iop))
return EOF;
if (read_can_timeout)
read_timeout = get_read_timeout(iop);
if (iop->public.get_record != NULL) {
char *rt_start;
size_t rt_len;
int rc = iop->public.get_record(out, &iop->public, errcode,
&rt_start, &rt_len);
if (rc == EOF)
iop->flag |= IOP_AT_EOF;
else {
if (rt_len != 0)
set_RT(rt_start, rt_len);
else
set_RT_to_null();
}
return rc;
}
/* fill initial buffer */
if (has_no_data(iop) || no_data_left(iop)) {
iop->count = iop->public.read_func(iop->public.fd, iop->buf, iop->readsize);
if (iop->count == 0) {
iop->flag |= IOP_AT_EOF;
return EOF;
} else if (iop->count == -1) {
iop->flag |= IOP_AT_EOF;
*errcode = errno;
return EOF;
} else {
iop->dataend = iop->buf + iop->count;
iop->off = iop->buf;
}
}
/* loop through file to find a record */
state = NOSTATE;
for (;;) {
size_t dataend_off;
size_t room_left;
size_t amt_to_read;
ret = (*matchrec)(iop, & recm, & state);
iop->flag &= ~IOP_AT_START;
if (ret == REC_OK)
break;
/* need to add more data to buffer */
/* shift data down in buffer */
dataend_off = iop->dataend - iop->off;
memmove(iop->buf, iop->off, dataend_off);
iop->off = iop->buf;
iop->dataend = iop->buf + dataend_off;
/* adjust recm contents */
recm.start = iop->off;
if (recm.rt_start != NULL)
recm.rt_start = iop->off + recm.len;
/* read more data, break if EOF */
#ifndef MIN
#define MIN(x, y) (x < y ? x : y)
#endif
/* subtract one in read count to leave room for sentinel */
room_left = iop->end - iop->dataend - 1;
amt_to_read = MIN(iop->readsize, room_left);
if (amt_to_read < iop->readsize) {
grow_iop_buffer(iop);
/* adjust recm contents */
recm.start = iop->off;
if (recm.rt_start != NULL)
recm.rt_start = iop->off + recm.len;
/* recalculate amt_to_read */
room_left = iop->end - iop->dataend - 1;
amt_to_read = MIN(iop->readsize, room_left);
}
while (amt_to_read + iop->readsize < room_left)
amt_to_read += iop->readsize;
#ifdef SSIZE_MAX
/*
* POSIX limits read to SSIZE_MAX. There are (bizarre)
* systems where this amount is small.
*/
amt_to_read = MIN(amt_to_read, SSIZE_MAX);
#endif
iop->count = iop->public.read_func(iop->public.fd, iop->dataend, amt_to_read);
if (iop->count == -1) {
*errcode = errno;
iop->flag |= IOP_AT_EOF;
break;
} else if (iop->count == 0) {
/*
* hit EOF before matching RS, so end
* the record and set RT to ""
*/
iop->flag |= IOP_AT_EOF;
break;
} else
iop->dataend += iop->count;
}
/* set record, RT, return right value */
/*
* rtval is not a static pointer to avoid dangling pointer problems
* in case awk code assigns to RT. A remote possibility, to be sure,
* but Bitter Experience teaches us not to make ``that'll never
* happen'' kinds of assumptions.
*/
rtval = RT_node->var_value;
if (recm.rt_len == 0) {
set_RT_to_null();
lastmatchrec = NULL;
} else {
assert(recm.rt_start != NULL);
/*
* Optimization. For rs1 case, don't set RT if
* character is same as last time. This knocks a
* chunk of time off something simple like
*
* gawk '{ print }' /some/big/file
*
* Similarly, for rsnull case, if length of new RT is
* shorter than current RT, just bump length down in RT.
*
* Make sure that matchrec didn't change since the last
* check. (Ugh, details, details, details.)
*/
if (lastmatchrec == NULL || lastmatchrec != matchrec) {
lastmatchrec = matchrec;
set_RT(recm.rt_start, recm.rt_len);
} else if (matchrec == rs1scan) {
if (rtval->stlen != 1 || rtval->stptr[0] != recm.rt_start[0])
set_RT(recm.rt_start, recm.rt_len);
/* else
leave it alone */
} else if (matchrec == rsnullscan) {
if (rtval->stlen >= recm.rt_len) {
rtval->stlen = recm.rt_len;
free_wstr(rtval);
} else
set_RT(recm.rt_start, recm.rt_len);
} else
set_RT(recm.rt_start, recm.rt_len);
}
if (recm.len == 0) {
*out = NULL;
retval = 0;
} else {
assert(recm.start != NULL);
*out = recm.start;
retval = recm.len;
}
iop->off += recm.len + recm.rt_len;
if (recm.len == 0 && recm.rt_len == 0 && at_eof(iop))
return EOF;
else
return retval;
}
/* set_RS --- update things as appropriate when RS is set */
void
set_RS()
{
static NODE *save_rs = NULL;
/*
* Don't use cmp_nodes(), which pays attention to IGNORECASE.
*/
if (save_rs
&& RS_node->var_value->stlen == save_rs->stlen
&& memcmp(RS_node->var_value->stptr, save_rs->stptr, save_rs->stlen) == 0) {
/*
* It could be that just IGNORECASE changed. If so,
* update the regex and then do the same for FS.
* set_IGNORECASE() relies on this routine to call
* set_FS().
*/
RS_regexp = (IGNORECASE ? RS_re_no_case : RS_re_yes_case);
goto set_FS;
}
unref(save_rs);
save_rs = dupnode(RS_node->var_value);
RS_is_null = false;
RS = force_string(RS_node->var_value);
/*
* used to be if (RS_regexp != NULL) { refree(..); refree(..); ...; }.
* Please do not remerge the if condition; hinders memory deallocation
* in case of fatal error in make_regexp.
*/
refree(RS_re_yes_case); /* NULL argument is ok */
refree(RS_re_no_case);
RS_re_yes_case = RS_re_no_case = RS_regexp = NULL;
if (RS->stlen == 0) {
RS_is_null = true;
matchrec = rsnullscan;
} else if (RS->stlen > 1) {
static bool warned = false;
RS_re_yes_case = make_regexp(RS->stptr, RS->stlen, false, true, true);
RS_re_no_case = make_regexp(RS->stptr, RS->stlen, true, true, true);
RS_regexp = (IGNORECASE ? RS_re_no_case : RS_re_yes_case);
matchrec = rsrescan;
if (do_lint && ! warned) {
lintwarn(_("multicharacter value of `RS' is a gawk extension"));
warned = true;
}
} else
matchrec = rs1scan;
set_FS:
if (current_field_sep() == Using_FS)
set_FS();
}
/* pty_vs_pipe --- return true if should use pty instead of pipes for `|&' */
/*
* This works by checking if PROCINFO["command", "pty"] exists and is true.
*/
static int
pty_vs_pipe(const char *command)
{
#ifdef HAVE_TERMIOS_H
NODE *val;
if (PROCINFO_node == NULL)
return false;
val = in_PROCINFO(command, "pty", NULL);
if (val) {
if ((val->flags & MAYBE_NUM) != 0)
(void) force_number(val);
if ((val->flags & NUMBER) != 0)
return ! iszero(val);
else
return (val->stlen != 0);
}
#endif /* HAVE_TERMIOS_H */
return false;
}
/* iopflags2str --- make IOP flags printable */
const char *
iopflags2str(int flag)
{
static const struct flagtab values[] = {
{ IOP_IS_TTY, "IOP_IS_TTY" },
{ IOP_AT_EOF, "IOP_AT_EOF" },
{ IOP_CLOSED, "IOP_CLOSED" },
{ IOP_AT_START, "IOP_AT_START" },
{ 0, NULL }
};
return genflags2str(flag, values);
}
/* free_rp --- release the memory used by rp */
static void
free_rp(struct redirect *rp)
{
efree(rp->value);
efree(rp);
}
/* inetfile --- return true for a /inet special file, set other values */
static int
inetfile(const char *str, int *length, int *family)
{
bool ret = false;
if (strncmp(str, "/inet/", 6) == 0) {
ret = true;
if (length != NULL)
*length = 6;
if (family != NULL)
*family = AF_UNSPEC;
} else if (strncmp(str, "/inet4/", 7) == 0) {
ret = true;
if (length != NULL)
*length = 7;
if (family != NULL)
*family = AF_INET;
} else if (strncmp(str, "/inet6/", 7) == 0) {
ret = true;
if (length != NULL)
*length = 7;
if (family != NULL)
*family = AF_INET6;
#ifndef HAVE_GETADDRINFO
fatal(_("IPv6 communication is not supported"));
#endif
}
return ret;
}
/*
* in_PROCINFO --- return value for a PROCINFO element with
* SUBSEP seperated indices.
*/
static NODE *
in_PROCINFO(const char *pidx1, const char *pidx2, NODE **full_idx)
{
char *str;
size_t str_len;
NODE *r, *sub = NULL;
NODE *subsep = SUBSEP_node->var_value;
/* full_idx is in+out parameter */
if (full_idx)
sub = *full_idx;
str_len = strlen(pidx1) + subsep->stlen + strlen(pidx2);
if (sub == NULL) {
emalloc(str, char *, str_len + 1, "in_PROCINFO");
sub = make_str_node(str, str_len, ALREADY_MALLOCED);
if (full_idx)
*full_idx = sub;
} else if (str_len != sub->stlen) {
/* *full_idx != NULL */
assert(sub->valref == 1);
erealloc(sub->stptr, char *, str_len + 1, "in_PROCINFO");
sub->stlen = str_len;
}
sprintf(sub->stptr, "%s%.*s%s", pidx1, (int)subsep->stlen,
subsep->stptr, pidx2);
r = in_array(PROCINFO_node, sub);
if (! full_idx)
unref(sub);
return r;
}
/* get_read_timeout --- get timeout in milliseconds for reading */
static long
get_read_timeout(IOBUF *iop)
{
long tmout = 0;
if (PROCINFO_node != NULL) {
const char *name = iop->public.name;
NODE *val = NULL;
static NODE *full_idx = NULL;
static const char *last_name = NULL;
/*
* Do not re-construct the full index when last redirection
* string is the same as the current; "efficiency_hack++".
*/
if (full_idx == NULL || strcmp(name, last_name) != 0) {
val = in_PROCINFO(name, "READ_TIMEOUT", & full_idx);
if (last_name != NULL)
efree((void *) last_name);
last_name = estrdup(name, strlen(name));
} else /* use cached full index */
val = in_array(PROCINFO_node, full_idx);
if (val != NULL) {
(void) force_number(val);
tmout = get_number_si(val);
}
} else
tmout = read_default_timeout; /* initialized from env. variable in init_io() */
/* overwrite read routine only if an extension has not done so */
if ((iop->public.read_func == ( ssize_t(*)() ) read) && tmout > 0)
iop->public.read_func = read_with_timeout;
return tmout;
}
/*
* read_with_timeout --- read with a timeout, return failure
* if no data is available within the timeout period.
*/
static ssize_t
read_with_timeout(int fd, char *buf, size_t size)
{
#if ! defined(VMS)
fd_set readfds;
struct timeval tv;
#ifdef __MINGW32__
/*
* Only sockets can be read with a timeout. Also, the FD_*
* macros work on SOCKET type, not on int file descriptors.
*/
SOCKET s = valid_socket(fd);
if (!s)
return read(fd, buf, size);
#else
int s = fd;
#endif
tv.tv_sec = read_timeout / 1000;
tv.tv_usec = 1000 * (read_timeout - 1000 * tv.tv_sec);
FD_ZERO(& readfds);
FD_SET(s, & readfds);
errno = 0;
/*
* Note: the 1st arg of 'select' is ignored on MS-Windows, so
* it's not a mistake to pass fd+1 there, although we use
* sockets, not file descriptors.
*/
if (select(fd + 1, & readfds, NULL, NULL, & tv) < 0)
return -1;
if (FD_ISSET(s, & readfds))
return read(fd, buf, size);
/* else
timed out */
/* Set a meaningful errno */
#ifdef ETIMEDOUT
errno = ETIMEDOUT;
#else
errno = EAGAIN;
#endif
return -1;
#else /* VMS */
return read(fd, buf, size);
#endif /* VMS */
}
/*
* Dummy pass through functions for default output.
*/
/* gawk_fwrite --- like fwrite */
static size_t
gawk_fwrite(const void *buf, size_t size, size_t count, FILE *fp, void *opaque)
{
(void) opaque;
return fwrite(buf, size, count, fp);
}
static int
gawk_fflush(FILE *fp, void *opaque)
{
(void) opaque;
return fflush(fp);
}
static int
gawk_ferror(FILE *fp, void *opaque)
{
(void) opaque;
return ferror(fp);
}
static int
gawk_fclose(FILE *fp, void *opaque)
{
int result;
#ifdef __MINGW32__
SOCKET s = valid_socket (fileno(fp));
#endif
(void) opaque;
result = fclose(fp);
#ifdef __MINGW32__
if (s && closesocket(s) == SOCKET_ERROR)
result = -1;
#endif
return result;
}
/* init_output_wrapper --- initialize the output wrapper */
static void
init_output_wrapper(awk_output_buf_t *outbuf)
{
outbuf->name = NULL;
outbuf->mode = NULL;
outbuf->fp = NULL;
outbuf->opaque = NULL;
outbuf->redirected = awk_false;
outbuf->gawk_fwrite = gawk_fwrite;
outbuf->gawk_fflush = gawk_fflush;
outbuf->gawk_ferror = gawk_ferror;
outbuf->gawk_fclose = gawk_fclose;
}
|