/usr/include/d/std/net/curl.d is in libphobos2-ldc-dev 1:0.17.1-1ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 | // Written in the D programming language.
/**
Networking client functionality as provided by $(WEB _curl.haxx.se/libcurl,
libcurl). The libcurl library must be installed on the system in order to use
this module.
$(SCRIPT inhibitQuickIndex = 1;)
$(DIVC quickindex,
$(BOOKTABLE ,
$(TR $(TH Category) $(TH Functions)
)
$(TR $(TDNW High level) $(TD $(MYREF download) $(MYREF upload) $(MYREF get)
$(MYREF post) $(MYREF put) $(MYREF del) $(MYREF options) $(MYREF trace)
$(MYREF connect) $(MYREF byLine) $(MYREF byChunk)
$(MYREF byLineAsync) $(MYREF byChunkAsync) )
)
$(TR $(TDNW Low level) $(TD $(MYREF HTTP) $(MYREF FTP) $(MYREF
SMTP) )
)
)
)
Note:
You may need to link to the $(B curl) library, e.g. by adding $(D "libs": ["curl"])
to your $(B dub.json) file if you are using $(LINK2 http://code.dlang.org, DUB).
Windows x86 note:
A DMD compatible libcurl static library can be downloaded from the dlang.org
$(LINK2 http://dlang.org/download.html, download page).
Compared to using libcurl directly this module allows simpler client code for
common uses, requires no unsafe operations, and integrates better with the rest
of the language. Futhermore it provides <a href="std_range.html">$(D range)</a>
access to protocols supported by libcurl both synchronously and asynchronously.
A high level and a low level API are available. The high level API is built
entirely on top of the low level one.
The high level API is for commonly used functionality such as HTTP/FTP get. The
$(LREF byLineAsync) and $(LREF byChunkAsync) provides asynchronous <a
href="std_range.html">$(D ranges)</a> that performs the request in another
thread while handling a line/chunk in the current thread.
The low level API allows for streaming and other advanced features.
$(BOOKTABLE Cheat Sheet,
$(TR $(TH Function Name) $(TH Description)
)
$(LEADINGROW High level)
$(TR $(TDNW $(LREF download)) $(TD $(D
download("ftp.digitalmars.com/sieve.ds", "/tmp/downloaded-ftp-file"))
downloads file from URL to file system.)
)
$(TR $(TDNW $(LREF upload)) $(TD $(D
upload("/tmp/downloaded-ftp-file", "ftp.digitalmars.com/sieve.ds");)
uploads file from file system to URL.)
)
$(TR $(TDNW $(LREF get)) $(TD $(D
get("dlang.org")) returns a string containing the dlang.org web page.)
)
$(TR $(TDNW $(LREF put)) $(TD $(D
put("dlang.org", "Hi")) returns a string containing
the dlang.org web page. after a HTTP PUT of "hi")
)
$(TR $(TDNW $(LREF post)) $(TD $(D
post("dlang.org", "Hi")) returns a string containing
the dlang.org web page. after a HTTP POST of "hi")
)
$(TR $(TDNW $(LREF byLine)) $(TD $(D
byLine("dlang.org")) returns a range of strings containing the
dlang.org web page.)
)
$(TR $(TDNW $(LREF byChunk)) $(TD $(D
byChunk("dlang.org", 10)) returns a range of ubyte[10] containing the
dlang.org web page.)
)
$(TR $(TDNW $(LREF byLineAsync)) $(TD $(D
byLineAsync("dlang.org")) returns a range of strings containing the dlang.org web
page asynchronously.)
)
$(TR $(TDNW $(LREF byChunkAsync)) $(TD $(D
byChunkAsync("dlang.org", 10)) returns a range of ubyte[10] containing the
dlang.org web page asynchronously.)
)
$(LEADINGROW Low level
)
$(TR $(TDNW $(LREF HTTP)) $(TD $(D HTTP) struct for advanced usage))
$(TR $(TDNW $(LREF FTP)) $(TD $(D FTP) struct for advanced usage))
$(TR $(TDNW $(LREF SMTP)) $(TD $(D SMTP) struct for advanced usage))
)
Example:
---
import std.net.curl, std.stdio;
// Return a string containing the content specified by an URL
string content = get("dlang.org");
// Post data and return a string containing the content specified by an URL
string content = post("mydomain.com/here.cgi", "post data");
// Get content of file from ftp server
string content = get("ftp.digitalmars.com/sieve.ds");
// Post and print out content line by line. The request is done in another thread.
foreach (line; byLineAsync("dlang.org", "Post data"))
writeln(line);
// Get using a line range and proxy settings
auto client = HTTP();
client.proxy = "1.2.3.4";
foreach (line; byLine("dlang.org", client))
writeln(line);
---
For more control than the high level functions provide, use the low level API:
Example:
---
import std.net.curl, std.stdio;
// GET with custom data receivers
auto http = HTTP("dlang.org");
http.onReceiveHeader =
(in char[] key, in char[] value) { writeln(key, ": ", value); };
http.onReceive = (ubyte[] data) { /+ drop +/ return data.length; };
http.perform();
---
First, an instance of the reference-counted HTTP struct is created. Then the
custom delegates are set. These will be called whenever the HTTP instance
receives a header and a data buffer, respectively. In this simple example, the
headers are written to stdout and the data is ignored. If the request should be
stopped before it has finished then return something less than data.length from
the onReceive callback. See $(LREF onReceiveHeader)/$(LREF onReceive) for more
information. Finally the HTTP request is effected by calling perform(), which is
synchronous.
Source: $(PHOBOSSRC std/net/_curl.d)
Copyright: Copyright Jonas Drewsen 2011-2012
License: $(WEB www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: Jonas Drewsen. Some of the SMTP code contributed by Jimmy Cao.
Credits: The functionally is based on $(WEB _curl.haxx.se/libcurl, libcurl).
LibCurl is licensed under an MIT/X derivative license.
*/
/*
Copyright Jonas Drewsen 2011 - 2012.
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
*/
module std.net.curl;
import core.thread;
import etc.c.curl;
import std.algorithm;
import std.array;
import std.concurrency;
import std.conv;
import std.datetime;
import std.encoding;
import std.exception;
import std.regex;
import std.socket : InternetAddress;
import std.string;
import std.traits;
import std.typecons;
import std.typetuple;
import std.internal.cstring;
public import etc.c.curl : CurlOption;
version(unittest)
{
// Run unit test with the PHOBOS_TEST_ALLOW_NET=1 set in order to
// allow net traffic
import std.stdio;
import std.range;
import std.process : environment;
import std.file : tempDir;
import std.path : buildPath;
// Source code for the test service is available at
// https://github.com/jcd/d-lang-testservice
enum testService = "d-lang.appspot.com";
enum testUrl1 = "http://"~testService~"/testUrl1";
enum testUrl2 = "http://"~testService~"/testUrl2";
// No anonymous DigitalMars FTP access as of 2015
//enum testUrl3 = "ftp://ftp.digitalmars.com/sieve.ds";
enum testUrl4 = testService~"/testUrl1";
enum testUrl5 = "http://"~testService~"/testUrl3";
}
version(StdDdoc) import std.stdio;
extern (C) void exit(int);
// Default data timeout for Protocols
private enum _defaultDataTimeout = dur!"minutes"(2);
/**
Macros:
CALLBACK_PARAMS = $(TABLE ,
$(DDOC_PARAM_ROW
$(DDOC_PARAM_ID $(DDOC_PARAM dlTotal))
$(DDOC_PARAM_DESC total bytes to download)
)
$(DDOC_PARAM_ROW
$(DDOC_PARAM_ID $(DDOC_PARAM dlNow))
$(DDOC_PARAM_DESC currently downloaded bytes)
)
$(DDOC_PARAM_ROW
$(DDOC_PARAM_ID $(DDOC_PARAM ulTotal))
$(DDOC_PARAM_DESC total bytes to upload)
)
$(DDOC_PARAM_ROW
$(DDOC_PARAM_ID $(DDOC_PARAM ulNow))
$(DDOC_PARAM_DESC currently uploaded bytes)
)
)
*/
/** Connection type used when the URL should be used to auto detect the protocol.
*
* This struct is used as placeholder for the connection parameter when calling
* the high level API and the connection type (HTTP/FTP) should be guessed by
* inspecting the URL parameter.
*
* The rules for guessing the protocol are:
* 1, if URL starts with ftp://, ftps:// or ftp. then FTP connection is assumed.
* 2, HTTP connection otherwise.
*
* Example:
* ---
* import std.net.curl;
* // Two requests below will do the same.
* string content;
*
* // Explicit connection provided
* content = get!HTTP("dlang.org");
*
* // Guess connection type by looking at the URL
* content = get!AutoProtocol("ftp://foo.com/file");
* // and since AutoProtocol is default this is the same as
* connect = get("ftp://foo.com/file");
* // and will end up detecting FTP from the url and be the same as
* connect = get!FTP("ftp://foo.com/file");
* ---
*/
struct AutoProtocol { }
// Returns true if the url points to an FTP resource
private bool isFTPUrl(const(char)[] url)
{
return startsWith(url.toLower(), "ftp://", "ftps://", "ftp.") != 0;
}
// Is true if the Conn type is a valid Curl Connection type.
private template isCurlConn(Conn)
{
enum auto isCurlConn = is(Conn : HTTP) ||
is(Conn : FTP) || is(Conn : AutoProtocol);
}
/** HTTP/FTP download to local file system.
*
* Params:
* url = resource to download
* saveToPath = path to store the downloaded content on local disk
* conn = connection to use e.g. FTP or HTTP. The default AutoProtocol will
* guess connection type and create a new instance for this call only.
*
* Example:
* ----
* import std.net.curl;
* download("d-lang.appspot.com/testUrl2", "/tmp/downloaded-http-file");
* ----
*/
void download(Conn = AutoProtocol)(const(char)[] url, string saveToPath, Conn conn = Conn())
if (isCurlConn!Conn)
{
static if (is(Conn : HTTP) || is(Conn : FTP))
{
import std.stdio : File;
conn.url = url;
auto f = File(saveToPath, "wb");
conn.onReceive = (ubyte[] data) { f.rawWrite(data); return data.length; };
conn.perform();
}
else
{
if (isFTPUrl(url))
return download!FTP(url, saveToPath, FTP());
else
return download!HTTP(url, saveToPath, HTTP());
}
}
unittest
{
if (!netAllowed()) return;
// No anonymous DigitalMars FTP access as of 2015
//download("ftp.digitalmars.com/sieve.ds", buildPath(tempDir(), "downloaded-ftp-file"));
auto fn = buildPath(tempDir(), "downloaded-http-file");
download("d-lang.appspot.com/testUrl1", fn);
assert(std.file.readText(fn) == "Hello world\n");
download!(HTTP)("d-lang.appspot.com/testUrl1", fn);
assert(std.file.readText(fn) == "Hello world\n");
}
/** Upload file from local files system using the HTTP or FTP protocol.
*
* Params:
* loadFromPath = path load data from local disk.
* url = resource to upload to
* conn = connection to use e.g. FTP or HTTP. The default AutoProtocol will
* guess connection type and create a new instance for this call only.
*
* Example:
* ----
* import std.net.curl;
* upload("/tmp/downloaded-ftp-file", "ftp.digitalmars.com/sieve.ds");
* upload("/tmp/downloaded-http-file", "d-lang.appspot.com/testUrl2");
* ----
*/
void upload(Conn = AutoProtocol)(string loadFromPath, const(char)[] url, Conn conn = Conn())
if (isCurlConn!Conn)
{
static if (is(Conn : HTTP))
{
conn.url = url;
conn.method = HTTP.Method.put;
}
else static if (is(Conn : FTP))
{
conn.url = url;
conn.handle.set(CurlOption.upload, 1L);
}
else
{
if (isFTPUrl(url))
return upload!FTP(loadFromPath, url, FTP());
else
return upload!HTTP(loadFromPath, url, HTTP());
}
static if (is(Conn : HTTP) || is(Conn : FTP))
{
static import std.file;
void[] f;
conn.onSend = (void[] data)
{
f = std.file.read(loadFromPath);
return f.length;
};
conn.contentLength = f.length;
conn.perform();
}
}
unittest
{
if (!netAllowed()) return;
// upload(buildPath(tempDir(), "downloaded-ftp-file"), "ftp.digitalmars.com/sieve.ds");
upload(buildPath(tempDir(), "downloaded-http-file"), "d-lang.appspot.com/testUrl2");
}
/** HTTP/FTP get content.
*
* Params:
* url = resource to get
* conn = connection to use e.g. FTP or HTTP. The default AutoProtocol will
* guess connection type and create a new instance for this call only.
*
* The template parameter $(D T) specifies the type to return. Possible values
* are $(D char) and $(D ubyte) to return $(D char[]) or $(D ubyte[]). If asking
* for $(D char), content will be converted from the connection character set
* (specified in HTTP response headers or FTP connection properties, both ISO-8859-1
* by default) to UTF-8.
*
* Example:
* ----
* import std.net.curl;
* string content = get("d-lang.appspot.com/testUrl2");
* ----
*
* Returns:
* A T[] range containing the content of the resource pointed to by the URL.
*
* Throws:
*
* $(D CurlException) on error.
*
* See_Also: $(LREF HTTP.Method)
*/
T[] get(Conn = AutoProtocol, T = char)(const(char)[] url, Conn conn = Conn())
if ( isCurlConn!Conn && (is(T == char) || is(T == ubyte)) )
{
static if (is(Conn : HTTP))
{
conn.method = HTTP.Method.get;
return _basicHTTP!(T)(url, "", conn);
}
else static if (is(Conn : FTP))
{
return _basicFTP!(T)(url, "", conn);
}
else
{
if (isFTPUrl(url))
return get!(FTP,T)(url, FTP());
else
return get!(HTTP,T)(url, HTTP());
}
}
unittest
{
if (!netAllowed()) return;
auto res = get(testUrl1);
assert(res == "Hello world\n",
"get!HTTP() returns unexpected content " ~ res);
res = get(testUrl4);
assert(res == "Hello world\n",
"get!HTTP() returns unexpected content: " ~ res);
// No anonymous DigitalMars FTP access as of 2015
//res = get(testUrl3);
//assert(res.startsWith("\r\n/* Eratosthenes Sieve prime number calculation. */"),
// "get!FTP() returns unexpected content");
}
/** HTTP post content.
*
* Params:
* url = resource to post to
* postData = data to send as the body of the request. An array
* of an arbitrary type is accepted and will be cast to ubyte[]
* before sending it.
* conn = connection to use e.g. FTP or HTTP. The default AutoProtocol will
* guess connection type and create a new instance for this call only.
*
* The template parameter $(D T) specifies the type to return. Possible values
* are $(D char) and $(D ubyte) to return $(D char[]) or $(D ubyte[]). If asking
* for $(D char), content will be converted from the connection character set
* (specified in HTTP response headers or FTP connection properties, both ISO-8859-1
* by default) to UTF-8.
*
* Example:
* ----
* import std.net.curl;
* string content = post("d-lang.appspot.com/testUrl2", [1,2,3,4]);
* ----
*
* Returns:
* A T[] range containing the content of the resource pointed to by the URL.
*
* See_Also: $(LREF HTTP.Method)
*/
T[] post(T = char, PostUnit)(const(char)[] url, const(PostUnit)[] postData, HTTP conn = HTTP())
if (is(T == char) || is(T == ubyte))
{
conn.method = HTTP.Method.post;
return _basicHTTP!(T)(url, postData, conn);
}
unittest
{
if (!netAllowed()) return;
{
string data = "Hello world";
auto res = post(testUrl2, data);
assert(res == data,
"post!HTTP() returns unexpected content " ~ res);
}
{
ubyte[] data;
foreach (n; 0..256)
data ~= cast(ubyte)n;
auto res = post!ubyte(testUrl2, data);
assert(res == data,
"post!HTTP() with binary data returns unexpected content (" ~ text(res.length) ~ " bytes)");
}
{
string data = "Hello world";
auto res = post(testUrl5, data);
assert(res == data,
"post!HTTP() returns unexpected content after redirect " ~ res);
}
}
/** HTTP/FTP put content.
*
* Params:
* url = resource to put
* putData = data to send as the body of the request. An array
* of an arbitrary type is accepted and will be cast to ubyte[]
* before sending it.
* conn = connection to use e.g. FTP or HTTP. The default AutoProtocol will
* guess connection type and create a new instance for this call only.
*
* The template parameter $(D T) specifies the type to return. Possible values
* are $(D char) and $(D ubyte) to return $(D char[]) or $(D ubyte[]). If asking
* for $(D char), content will be converted from the connection character set
* (specified in HTTP response headers or FTP connection properties, both ISO-8859-1
* by default) to UTF-8.
*
* Example:
* ----
* import std.net.curl;
* string content = put("d-lang.appspot.com/testUrl2",
* "Putting this data");
* ----
*
* Returns:
* A T[] range containing the content of the resource pointed to by the URL.
*
* See_Also: $(LREF HTTP.Method)
*/
T[] put(Conn = AutoProtocol, T = char, PutUnit)(const(char)[] url, const(PutUnit)[] putData,
Conn conn = Conn())
if ( isCurlConn!Conn && (is(T == char) || is(T == ubyte)) )
{
static if (is(Conn : HTTP))
{
conn.method = HTTP.Method.put;
return _basicHTTP!(T)(url, putData, conn);
}
else static if (is(Conn : FTP))
{
return _basicFTP!(T)(url, putData, conn);
}
else
{
if (isFTPUrl(url))
return put!(FTP,T)(url, putData, FTP());
else
return put!(HTTP,T)(url, putData, HTTP());
}
}
unittest
{
if (!netAllowed()) return;
auto res = put(testUrl2, "Hello world");
assert(res == "Hello world",
"put!HTTP() returns unexpected content " ~ res);
// TODO: need ftp server to test with
// res = get(testUrl3);
// assert(res.startsWith("\r\n/* Eratosthenes Sieve prime number calculation. */"),
// "get!FTP() returns unexpected content");
}
/** HTTP/FTP delete content.
*
* Params:
* url = resource to delete
* conn = connection to use e.g. FTP or HTTP. The default AutoProtocol will
* guess connection type and create a new instance for this call only.
*
* Example:
* ----
* import std.net.curl;
* del("d-lang.appspot.com/testUrl2");
* ----
*
* See_Also: $(LREF HTTP.Method)
*/
void del(Conn = AutoProtocol)(const(char)[] url, Conn conn = Conn())
if (isCurlConn!Conn)
{
static if (is(Conn : HTTP))
{
conn.method = HTTP.Method.del;
_basicHTTP!char(url, cast(void[]) null, conn);
}
else static if (is(Conn : FTP))
{
auto trimmed = url.findSplitAfter("ftp://")[1];
auto t = trimmed.findSplitAfter("/");
enum minDomainNameLength = 3;
enforce!CurlException(t[0].length > minDomainNameLength,
text("Invalid FTP URL for delete ", url));
conn.url = t[0];
enforce!CurlException(!t[1].empty,
text("No filename specified to delete for URL ", url));
conn.addCommand("DELE " ~ t[1]);
conn.perform();
}
else
{
if (isFTPUrl(url))
return del!FTP(url, FTP());
else
return del!HTTP(url, HTTP());
}
}
unittest
{
if (!netAllowed()) return;
del(testUrl1);
}
/** HTTP options request.
*
* Params:
* url = resource make a option call to
* optionsData = options data to send as the body of the request. An array
* of an arbitrary type is accepted and will be cast to ubyte[]
* before sending it.
* conn = connection to use e.g. FTP or HTTP. The default AutoProtocol will
* guess connection type and create a new instance for this call only.
*
* The template parameter $(D T) specifies the type to return. Possible values
* are $(D char) and $(D ubyte) to return $(D char[]) or $(D ubyte[]).
* Currently the HTTP RFC does not specify any usage of the optionsData and
* for this reason the example below does not send optionsData to the server.
*
* Example:
* ----
* import std.net.curl;
* auto http = HTTP();
* options("d-lang.appspot.com/testUrl2", null, http);
* writeln("Allow set to " ~ http.responseHeaders["Allow"]);
* ----
*
* Returns:
* A T[] range containing the options of the resource pointed to by the URL.
*
* See_Also: $(LREF HTTP.Method)
*/
T[] options(T = char, OptionsUnit)(const(char)[] url,
const(OptionsUnit)[] optionsData = null,
HTTP conn = HTTP())
if (is(T == char) || is(T == ubyte))
{
conn.method = HTTP.Method.options;
return _basicHTTP!(T)(url, optionsData, conn);
}
unittest
{
if (!netAllowed()) return;
auto res = options(testUrl2, "Hello world");
assert(res == "Hello world",
"options!HTTP() returns unexpected content " ~ res);
}
unittest
{
if (!netAllowed()) return;
auto res = options(testUrl1, []);
assert(res == "Hello world\n",
"options!HTTP() returns unexpected content " ~ res);
}
/** HTTP trace request.
*
* Params:
* url = resource make a trace call to
* conn = connection to use e.g. FTP or HTTP. The default AutoProtocol will
* guess connection type and create a new instance for this call only.
*
* The template parameter $(D T) specifies the type to return. Possible values
* are $(D char) and $(D ubyte) to return $(D char[]) or $(D ubyte[]).
*
* Example:
* ----
* import std.net.curl;
* trace("d-lang.appspot.com/testUrl1");
* ----
*
* Returns:
* A T[] range containing the trace info of the resource pointed to by the URL.
*
* See_Also: $(LREF HTTP.Method)
*/
T[] trace(T = char)(const(char)[] url, HTTP conn = HTTP())
if (is(T == char) || is(T == ubyte))
{
conn.method = HTTP.Method.trace;
return _basicHTTP!(T)(url, cast(void[]) null, conn);
}
unittest
{
if (!netAllowed()) return;
auto res = trace(testUrl1);
assert(res == "Hello world\n",
"trace!HTTP() returns unexpected content " ~ res);
}
/** HTTP connect request.
*
* Params:
* url = resource make a connect to
* conn = connection to use e.g. FTP or HTTP. The default AutoProtocol will
* guess connection type and create a new instance for this call only.
*
* The template parameter $(D T) specifies the type to return. Possible values
* are $(D char) and $(D ubyte) to return $(D char[]) or $(D ubyte[]).
*
* Example:
* ----
* import std.net.curl;
* connect("d-lang.appspot.com/testUrl1");
* ----
*
* Returns:
* A T[] range containing the connect info of the resource pointed to by the URL.
*
* See_Also: $(LREF HTTP.Method)
*/
T[] connect(T = char)(const(char)[] url, HTTP conn = HTTP())
if (is(T == char) || is(T == ubyte))
{
conn.method = HTTP.Method.connect;
return _basicHTTP!(T)(url, cast(void[]) null, conn);
}
unittest
{
// google appspot does not allow connect method.
// if (!netAllowed()) return;
// auto res = connect(testUrl1);
// assert(res == "Hello world\n",
// "connect!HTTP() returns unexpected content " ~ res);
}
/*
* Helper function for the high level interface.
*
* It performs an HTTP request using the client which must have
* been setup correctly before calling this function.
*/
private auto _basicHTTP(T)(const(char)[] url, const(void)[] sendData, HTTP client)
{
scope (exit)
{
client.onReceiveHeader = null;
client.onReceiveStatusLine = null;
client.onReceive = null;
if (sendData !is null &&
(client.method == HTTP.Method.post || client.method == HTTP.Method.put))
{
client.onSend = null;
client.handle.onSeek = null;
}
}
client.url = url;
HTTP.StatusLine statusLine;
ubyte[] content;
string[string] headers;
client.onReceive = (ubyte[] data)
{
content ~= data;
return data.length;
};
if (sendData !is null &&
(client.method == HTTP.Method.post || client.method == HTTP.Method.put))
{
client.contentLength = sendData.length;
auto remainingData = sendData;
client.onSend = delegate size_t(void[] buf)
{
size_t minLen = min(buf.length, remainingData.length);
if (minLen == 0) return 0;
buf[0..minLen] = remainingData[0..minLen];
remainingData = remainingData[minLen..$];
return minLen;
};
client.handle.onSeek = delegate(long offset, CurlSeekPos mode)
{
switch (mode)
{
case CurlSeekPos.set:
remainingData = sendData[cast(size_t)offset..$];
return CurlSeek.ok;
default:
// As of curl 7.18.0, libcurl will not pass
// anything other than CurlSeekPos.set.
return CurlSeek.cantseek;
}
};
}
client.onReceiveHeader = (in char[] key,
in char[] value)
{
if (auto v = key in headers)
{
*v ~= ", ";
*v ~= value;
}
else
headers[key] = value.idup;
};
client.onReceiveStatusLine = (HTTP.StatusLine l) { statusLine = l; };
client.perform();
enforce!CurlException(statusLine.code / 100 == 2,
format("HTTP request returned status code %d (%s)",
statusLine.code, statusLine.reason));
// Default charset defined in HTTP RFC
auto charset = "ISO-8859-1";
if (auto v = "content-type" in headers)
{
auto m = match(cast(char[]) (*v), regex("charset=([^;,]*)"));
if (!m.empty && m.captures.length > 1)
{
charset = m.captures[1].idup;
}
}
return _decodeContent!T(content, charset);
}
unittest
{
if (!netAllowed()) return;
auto e = collectException!CurlException(get(testUrl1 ~ "nonexisting"));
assert(e.msg == "HTTP request returned status code 404 (Not Found)");
}
/*
* Helper function for the high level interface.
*
* It performs an FTP request using the client which must have
* been setup correctly before calling this function.
*/
private auto _basicFTP(T)(const(char)[] url, const(void)[] sendData, FTP client)
{
scope (exit)
{
client.onReceive = null;
if (!sendData.empty)
client.onSend = null;
}
ubyte[] content;
if (client.encoding.empty)
client.encoding = "ISO-8859-1";
client.url = url;
client.onReceive = (ubyte[] data)
{
content ~= data;
return data.length;
};
if (!sendData.empty)
{
client.handle.set(CurlOption.upload, 1L);
client.onSend = delegate size_t(void[] buf)
{
size_t minLen = min(buf.length, sendData.length);
if (minLen == 0) return 0;
buf[0..minLen] = sendData[0..minLen];
sendData = sendData[minLen..$];
return minLen;
};
}
client.perform();
return _decodeContent!T(content, client.encoding);
}
/* Used by _basicHTTP() and _basicFTP() to decode ubyte[] to
* correct string format
*/
private auto _decodeContent(T)(ubyte[] content, string encoding)
{
static if (is(T == ubyte))
{
return content;
}
else
{
// Optimally just return the utf8 encoded content
if (encoding == "UTF-8")
return cast(char[])(content);
// The content has to be re-encoded to utf8
auto scheme = EncodingScheme.create(encoding);
enforce!CurlException(scheme !is null,
format("Unknown encoding '%s'", encoding));
auto strInfo = decodeString(content, scheme);
enforce!CurlException(strInfo[0] != size_t.max,
format("Invalid encoding sequence for encoding '%s'",
encoding));
return strInfo[1];
}
}
alias KeepTerminator = Flag!"keepTerminator";
/+
struct ByLineBuffer(Char)
{
bool linePresent;
bool EOF;
Char[] buffer;
ubyte[] decodeRemainder;
bool append(const(ubyte)[] data)
{
byLineBuffer ~= data;
}
@property bool linePresent()
{
return byLinePresent;
}
Char[] get()
{
if (!linePresent)
{
// Decode ubyte[] into Char[] until a Terminator is found.
// If not Terminator is found and EOF is false then raise an
// exception.
}
return byLineBuffer;
}
}
++/
/** HTTP/FTP fetch content as a range of lines.
*
* A range of lines is returned when the request is complete. If the method or
* other request properties is to be customized then set the $(D conn) parameter
* with a HTTP/FTP instance that has these properties set.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* foreach (line; byLine("dlang.org"))
* writeln(line);
* ----
*
* Params:
* url = The url to receive content from
* keepTerminator = KeepTerminator.yes signals that the line terminator should be
* returned as part of the lines in the range.
* terminator = The character that terminates a line
* conn = The connection to use e.g. HTTP or FTP.
*
* Returns:
* A range of Char[] with the content of the resource pointer to by the URL
*/
auto byLine(Conn = AutoProtocol, Terminator = char, Char = char)
(const(char)[] url, KeepTerminator keepTerminator = KeepTerminator.no,
Terminator terminator = '\n', Conn conn = Conn())
if (isCurlConn!Conn && isSomeChar!Char && isSomeChar!Terminator)
{
static struct SyncLineInputRange
{
private Char[] lines;
private Char[] current;
private bool currentValid;
private bool keepTerminator;
private Terminator terminator;
this(Char[] lines, bool kt, Terminator terminator)
{
this.lines = lines;
this.keepTerminator = kt;
this.terminator = terminator;
currentValid = true;
popFront();
}
@property @safe bool empty()
{
return !currentValid;
}
@property @safe Char[] front()
{
enforce!CurlException(currentValid, "Cannot call front() on empty range");
return current;
}
void popFront()
{
enforce!CurlException(currentValid, "Cannot call popFront() on empty range");
if (lines.empty)
{
currentValid = false;
return;
}
if (keepTerminator)
{
auto r = findSplitAfter(lines, [ terminator ]);
if (r[0].empty)
{
current = r[1];
lines = r[0];
}
else
{
current = r[0];
lines = r[1];
}
}
else
{
auto r = findSplit(lines, [ terminator ]);
current = r[0];
lines = r[2];
}
}
}
auto result = _getForRange!Char(url, conn);
return SyncLineInputRange(result, keepTerminator == KeepTerminator.yes, terminator);
}
unittest
{
if (!netAllowed()) return;
auto res = byLine(testUrl1);
auto line = res.front;
assert(line == "Hello world",
"byLine!HTTP() returns unexpected content: " ~ line);
auto res2 = byLine(testUrl1, KeepTerminator.no, '\n', HTTP());
line = res2.front;
assert(line == "Hello world",
"byLine!HTTP() returns unexpected content: " ~ line);
}
/** HTTP/FTP fetch content as a range of chunks.
*
* A range of chunks is returned when the request is complete. If the method or
* other request properties is to be customized then set the $(D conn) parameter
* with a HTTP/FTP instance that has these properties set.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* foreach (chunk; byChunk("dlang.org", 100))
* writeln(chunk); // chunk is ubyte[100]
* ----
*
* Params:
* url = The url to receive content from
* chunkSize = The size of each chunk
* conn = The connection to use e.g. HTTP or FTP.
*
* Returns:
* A range of ubyte[chunkSize] with the content of the resource pointer to by the URL
*/
auto byChunk(Conn = AutoProtocol)
(const(char)[] url, size_t chunkSize = 1024, Conn conn = Conn())
if (isCurlConn!(Conn))
{
static struct SyncChunkInputRange
{
private size_t chunkSize;
private ubyte[] _bytes;
private size_t offset;
this(ubyte[] bytes, size_t chunkSize)
{
this._bytes = bytes;
this.chunkSize = chunkSize;
}
@property @safe auto empty()
{
return offset == _bytes.length;
}
@property ubyte[] front()
{
size_t nextOffset = offset + chunkSize;
if (nextOffset > _bytes.length) nextOffset = _bytes.length;
return _bytes[offset..nextOffset];
}
@safe void popFront()
{
offset += chunkSize;
if (offset > _bytes.length) offset = _bytes.length;
}
}
auto result = _getForRange!ubyte(url, conn);
return SyncChunkInputRange(result, chunkSize);
}
unittest
{
if (!netAllowed()) return;
auto res = byChunk(testUrl1);
auto line = res.front;
assert(line == cast(ubyte[])"Hello world\n",
"byLineAsync!HTTP() returns unexpected content " ~ to!string(line));
auto res2 = byChunk(testUrl1, 1024, HTTP());
line = res2.front;
assert(line == cast(ubyte[])"Hello world\n",
"byLineAsync!HTTP() returns unexpected content: " ~ to!string(line));
}
private T[] _getForRange(T,Conn)(const(char)[] url, Conn conn)
{
static if (is(Conn : HTTP))
{
conn.method = conn.method == HTTP.Method.undefined ? HTTP.Method.get : conn.method;
return _basicHTTP!(T)(url, null, conn);
}
else static if (is(Conn : FTP))
{
return _basicFTP!(T)(url, null, conn);
}
else
{
if (isFTPUrl(url))
return get!(FTP,T)(url, FTP());
else
return get!(HTTP,T)(url, HTTP());
}
}
/*
Main thread part of the message passing protocol used for all async
curl protocols.
*/
private mixin template WorkerThreadProtocol(Unit, alias units)
{
@property bool empty()
{
tryEnsureUnits();
return state == State.done;
}
@property Unit[] front()
{
tryEnsureUnits();
assert(state == State.gotUnits,
format("Expected %s but got $s",
State.gotUnits, state));
return units;
}
void popFront()
{
tryEnsureUnits();
assert(state == State.gotUnits,
format("Expected %s but got $s",
State.gotUnits, state));
state = State.needUnits;
// Send to worker thread for buffer reuse
workerTid.send(cast(immutable(Unit)[]) units);
units = null;
}
/** Wait for duration or until data is available and return true if data is
available
*/
bool wait(Duration d)
{
if (state == State.gotUnits)
return true;
enum noDur = dur!"hnsecs"(0);
StopWatch sw;
sw.start();
while (state != State.gotUnits && d > noDur)
{
final switch (state)
{
case State.needUnits:
receiveTimeout(d,
(Tid origin, CurlMessage!(immutable(Unit)[]) _data)
{
if (origin != workerTid)
return false;
units = cast(Unit[]) _data.data;
state = State.gotUnits;
return true;
},
(Tid origin, CurlMessage!bool f)
{
if (origin != workerTid)
return false;
state = state.done;
return true;
}
);
break;
case State.gotUnits: return true;
case State.done:
return false;
}
d -= sw.peek();
sw.reset();
}
return state == State.gotUnits;
}
enum State
{
needUnits,
gotUnits,
done
}
State state;
void tryEnsureUnits()
{
while (true)
{
final switch (state)
{
case State.needUnits:
receive(
(Tid origin, CurlMessage!(immutable(Unit)[]) _data)
{
if (origin != workerTid)
return false;
units = cast(Unit[]) _data.data;
state = State.gotUnits;
return true;
},
(Tid origin, CurlMessage!bool f)
{
if (origin != workerTid)
return false;
state = state.done;
return true;
}
);
break;
case State.gotUnits: return;
case State.done:
return;
}
}
}
}
// Workaround bug #2458
// It should really be defined inside the byLineAsync method.
// Do not create instances of this struct since it will be
// moved when the bug has been fixed.
// Range that reads one line at a time asynchronously.
static struct AsyncLineInputRange(Char)
{
private Char[] line;
mixin WorkerThreadProtocol!(Char, line);
private Tid workerTid;
private State running;
private this(Tid tid, size_t transmitBuffers, size_t bufferSize)
{
workerTid = tid;
state = State.needUnits;
// Send buffers to other thread for it to use. Since no mechanism is in
// place for moving ownership a cast to shared is done here and casted
// back to non-shared in the receiving end.
foreach (i ; 0..transmitBuffers)
{
auto arr = new Char[](bufferSize);
workerTid.send(cast(immutable(Char[]))arr);
}
}
}
/** HTTP/FTP fetch content as a range of lines asynchronously.
*
* A range of lines is returned immediately and the request that fetches the
* lines is performed in another thread. If the method or other request
* properties is to be customized then set the $(D conn) parameter with a
* HTTP/FTP instance that has these properties set.
*
* If $(D postData) is non-_null the method will be set to $(D post) for HTTP
* requests.
*
* The background thread will buffer up to transmitBuffers number of lines
* before it stops receiving data from network. When the main thread reads the
* lines from the range it frees up buffers and allows for the background thread
* to receive more data from the network.
*
* If no data is available and the main thread accesses the range it will block
* until data becomes available. An exception to this is the $(D wait(Duration)) method on
* the $(LREF AsyncLineInputRange). This method will wait at maximum for the
* specified duration and return true if data is available.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* // Get some pages in the background
* auto range1 = byLineAsync("www.google.com");
* auto range2 = byLineAsync("www.wikipedia.org");
* foreach (line; byLineAsync("dlang.org"))
* writeln(line);
*
* // Lines already fetched in the background and ready
* foreach (line; range1) writeln(line);
* foreach (line; range2) writeln(line);
* ----
*
* ----
* import std.net.curl, std.stdio;
* // Get a line in a background thread and wait in
* // main thread for 2 seconds for it to arrive.
* auto range3 = byLineAsync("dlang.com");
* if (range.wait(dur!"seconds"(2)))
* writeln(range.front);
* else
* writeln("No line received after 2 seconds!");
* ----
*
* Params:
* url = The url to receive content from
* postData = Data to HTTP Post
* keepTerminator = KeepTerminator.yes signals that the line terminator should be
* returned as part of the lines in the range.
* terminator = The character that terminates a line
* transmitBuffers = The number of lines buffered asynchronously
* conn = The connection to use e.g. HTTP or FTP.
*
* Returns:
* A range of Char[] with the content of the resource pointer to by the
* URL.
*/
auto byLineAsync(Conn = AutoProtocol, Terminator = char, Char = char, PostUnit)
(const(char)[] url, const(PostUnit)[] postData,
KeepTerminator keepTerminator = KeepTerminator.no,
Terminator terminator = '\n',
size_t transmitBuffers = 10, Conn conn = Conn())
if (isCurlConn!Conn && isSomeChar!Char && isSomeChar!Terminator)
{
static if (is(Conn : AutoProtocol))
{
if (isFTPUrl(url))
return byLineAsync(url, postData, keepTerminator,
terminator, transmitBuffers, FTP());
else
return byLineAsync(url, postData, keepTerminator,
terminator, transmitBuffers, HTTP());
}
else
{
// 50 is just an arbitrary number for now
setMaxMailboxSize(thisTid, 50, OnCrowding.block);
auto tid = spawn(&_spawnAsync!(Conn, Char, Terminator));
tid.send(thisTid);
tid.send(terminator);
tid.send(keepTerminator == KeepTerminator.yes);
_asyncDuplicateConnection(url, conn, postData, tid);
return AsyncLineInputRange!Char(tid, transmitBuffers,
Conn.defaultAsyncStringBufferSize);
}
}
/// ditto
auto byLineAsync(Conn = AutoProtocol, Terminator = char, Char = char)
(const(char)[] url, KeepTerminator keepTerminator = KeepTerminator.no,
Terminator terminator = '\n',
size_t transmitBuffers = 10, Conn conn = Conn())
{
static if (is(Conn : AutoProtocol))
{
if (isFTPUrl(url))
return byLineAsync(url, cast(void[])null, keepTerminator,
terminator, transmitBuffers, FTP());
else
return byLineAsync(url, cast(void[])null, keepTerminator,
terminator, transmitBuffers, HTTP());
}
else
{
return byLineAsync(url, cast(void[])null, keepTerminator,
terminator, transmitBuffers, conn);
}
}
unittest
{
if (!netAllowed()) return;
auto res = byLineAsync(testUrl2, "Hello world");
auto line = res.front;
assert(line == "Hello world",
"byLineAsync!HTTP() returns unexpected content " ~ line);
res = byLineAsync(testUrl1);
line = res.front;
assert(line == "Hello world",
"byLineAsync!HTTP() returns unexpected content: " ~ line);
}
// Workaround bug #2458
// It should really be defined inside the byLineAsync method.
// Do not create instances of this struct since it will be
// moved when the bug has been fixed.
// Range that reads one chunk at a time asynchronously.
static struct AsyncChunkInputRange
{
private ubyte[] chunk;
mixin WorkerThreadProtocol!(ubyte, chunk);
private Tid workerTid;
private State running;
private this(Tid tid, size_t transmitBuffers, size_t chunkSize)
{
workerTid = tid;
state = State.needUnits;
// Send buffers to other thread for it to use. Since no mechanism is in
// place for moving ownership a cast to shared is done here and a cast
// back to non-shared in the receiving end.
foreach (i ; 0..transmitBuffers)
{
ubyte[] arr = new ubyte[](chunkSize);
workerTid.send(cast(immutable(ubyte[]))arr);
}
}
}
/** HTTP/FTP fetch content as a range of chunks asynchronously.
*
* A range of chunks is returned immediately and the request that fetches the
* chunks is performed in another thread. If the method or other request
* properties is to be customized then set the $(D conn) parameter with a
* HTTP/FTP instance that has these properties set.
*
* If $(D postData) is non-_null the method will be set to $(D post) for HTTP
* requests.
*
* The background thread will buffer up to transmitBuffers number of chunks
* before is stops receiving data from network. When the main thread reads the
* chunks from the range it frees up buffers and allows for the background
* thread to receive more data from the network.
*
* If no data is available and the main thread access the range it will block
* until data becomes available. An exception to this is the $(D wait(Duration))
* method on the $(LREF AsyncChunkInputRange). This method will wait at maximum for the specified
* duration and return true if data is available.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* // Get some pages in the background
* auto range1 = byChunkAsync("www.google.com", 100);
* auto range2 = byChunkAsync("www.wikipedia.org");
* foreach (chunk; byChunkAsync("dlang.org"))
* writeln(chunk); // chunk is ubyte[100]
*
* // Chunks already fetched in the background and ready
* foreach (chunk; range1) writeln(chunk);
* foreach (chunk; range2) writeln(chunk);
* ----
*
* ----
* import std.net.curl, std.stdio;
* // Get a line in a background thread and wait in
* // main thread for 2 seconds for it to arrive.
* auto range3 = byChunkAsync("dlang.com", 10);
* if (range.wait(dur!"seconds"(2)))
* writeln(range.front);
* else
* writeln("No chunk received after 2 seconds!");
* ----
*
* Params:
* url = The url to receive content from
* postData = Data to HTTP Post
* chunkSize = The size of the chunks
* transmitBuffers = The number of chunks buffered asynchronously
* conn = The connection to use e.g. HTTP or FTP.
*
* Returns:
* A range of ubyte[chunkSize] with the content of the resource pointer to by
* the URL.
*/
auto byChunkAsync(Conn = AutoProtocol, PostUnit)
(const(char)[] url, const(PostUnit)[] postData,
size_t chunkSize = 1024, size_t transmitBuffers = 10,
Conn conn = Conn())
if (isCurlConn!(Conn))
{
static if (is(Conn : AutoProtocol))
{
if (isFTPUrl(url))
return byChunkAsync(url, postData, chunkSize,
transmitBuffers, FTP());
else
return byChunkAsync(url, postData, chunkSize,
transmitBuffers, HTTP());
}
else
{
// 50 is just an arbitrary number for now
setMaxMailboxSize(thisTid, 50, OnCrowding.block);
auto tid = spawn(&_spawnAsync!(Conn, ubyte));
tid.send(thisTid);
_asyncDuplicateConnection(url, conn, postData, tid);
return AsyncChunkInputRange(tid, transmitBuffers, chunkSize);
}
}
/// ditto
auto byChunkAsync(Conn = AutoProtocol)
(const(char)[] url,
size_t chunkSize = 1024, size_t transmitBuffers = 10,
Conn conn = Conn())
if (isCurlConn!(Conn))
{
static if (is(Conn : AutoProtocol))
{
if (isFTPUrl(url))
return byChunkAsync(url, cast(void[])null, chunkSize,
transmitBuffers, FTP());
else
return byChunkAsync(url, cast(void[])null, chunkSize,
transmitBuffers, HTTP());
}
else
{
return byChunkAsync(url, cast(void[])null, chunkSize,
transmitBuffers, conn);
}
}
unittest
{
if (!netAllowed()) return;
auto res = byChunkAsync(testUrl2, "Hello world");
auto line = res.front;
assert(line == cast(ubyte[])"Hello world",
"byLineAsync!HTTP() returns unexpected content " ~ to!string(line));
res = byChunkAsync(testUrl1);
line = res.front;
assert(line == cast(ubyte[])"Hello world\n",
"byLineAsync!HTTP() returns unexpected content: " ~ to!string(line));
}
/* Used by byLineAsync/byChunkAsync to duplicate an existing connection
* that can be used exclusively in a spawned thread.
*/
private void _asyncDuplicateConnection(Conn, PostData)
(const(char)[] url, Conn conn, PostData postData, Tid tid)
{
// no move semantic available in std.concurrency ie. must use casting.
auto connDup = conn.dup();
connDup.url = url;
static if ( is(Conn : HTTP) )
{
connDup.p.headersOut = null;
connDup.method = conn.method == HTTP.Method.undefined ?
HTTP.Method.get : conn.method;
if (postData !is null)
{
if (connDup.method == HTTP.Method.put)
{
connDup.handle.set(CurlOption.infilesize_large,
postData.length);
}
else
{
// post
connDup.method = HTTP.Method.post;
connDup.handle.set(CurlOption.postfieldsize_large,
postData.length);
}
connDup.handle.set(CurlOption.copypostfields,
cast(void*) postData.ptr);
}
tid.send(cast(ulong)connDup.handle.handle);
tid.send(connDup.method);
}
else
{
enforce!CurlException(postData is null,
"Cannot put ftp data using byLineAsync()");
tid.send(cast(ulong)connDup.handle.handle);
tid.send(HTTP.Method.undefined);
}
connDup.p.curl.handle = null; // make sure handle is not freed
}
/*
Mixin template for all supported curl protocols. This is the commom
functionallity such as timeouts and network interface settings. This should
really be in the HTTP/FTP/SMTP structs but the documentation tool does not
support a mixin to put its doc strings where a mixin is done. Therefore docs
in this template is copied into each of HTTP/FTP/SMTP below.
*/
private mixin template Protocol()
{
/// Value to return from $(D onSend)/$(D onReceive) delegates in order to
/// pause a request
alias requestPause = CurlReadFunc.pause;
/// Value to return from onSend delegate in order to abort a request
alias requestAbort = CurlReadFunc.abort;
static uint defaultAsyncStringBufferSize = 100;
/**
The curl handle used by this connection.
*/
@property ref Curl handle() return
{
return p.curl;
}
/**
True if the instance is stopped. A stopped instance is not usable.
*/
@property bool isStopped()
{
return p.curl.stopped;
}
/// Stop and invalidate this instance.
void shutdown()
{
p.curl.shutdown();
}
/** Set verbose.
This will print request information to stderr.
*/
@property void verbose(bool on)
{
p.curl.set(CurlOption.verbose, on ? 1L : 0L);
}
// Connection settings
/// Set timeout for activity on connection.
@property void dataTimeout(Duration d)
{
p.curl.set(CurlOption.low_speed_limit, 1);
p.curl.set(CurlOption.low_speed_time, d.total!"seconds");
}
/** Set maximum time an operation is allowed to take.
This includes dns resolution, connecting, data transfer, etc.
*/
@property void operationTimeout(Duration d)
{
p.curl.set(CurlOption.timeout_ms, d.total!"msecs");
}
/// Set timeout for connecting.
@property void connectTimeout(Duration d)
{
p.curl.set(CurlOption.connecttimeout_ms, d.total!"msecs");
}
// Network settings
/** Proxy
* See: $(WEB curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY, _proxy)
*/
@property void proxy(const(char)[] host)
{
p.curl.set(CurlOption.proxy, host);
}
/** Proxy port
* See: $(WEB curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXYPORT, _proxy_port)
*/
@property void proxyPort(ushort port)
{
p.curl.set(CurlOption.proxyport, cast(long) port);
}
/// Type of proxy
alias CurlProxy = etc.c.curl.CurlProxy;
/** Proxy type
* See: $(WEB curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY, _proxy_type)
*/
@property void proxyType(CurlProxy type)
{
p.curl.set(CurlOption.proxytype, cast(long) type);
}
/// DNS lookup timeout.
@property void dnsTimeout(Duration d)
{
p.curl.set(CurlOption.dns_cache_timeout, d.total!"msecs");
}
/**
* The network interface to use in form of the the IP of the interface.
*
* Example:
* ----
* theprotocol.netInterface = "192.168.1.32";
* theprotocol.netInterface = [ 192, 168, 1, 32 ];
* ----
*
* See: $(XREF socket, InternetAddress)
*/
@property void netInterface(const(char)[] i)
{
p.curl.set(CurlOption.intrface, i);
}
/// ditto
@property void netInterface(const(ubyte)[4] i)
{
auto str = format("%d.%d.%d.%d", i[0], i[1], i[2], i[3]);
netInterface = str;
}
/// ditto
@property void netInterface(InternetAddress i)
{
netInterface = i.toAddrString();
}
/**
Set the local outgoing port to use.
Params:
port = the first outgoing port number to try and use
*/
@property void localPort(ushort port)
{
p.curl.set(CurlOption.localport, cast(long)port);
}
/**
Set the local outgoing port range to use.
This can be used together with the localPort property.
Params:
range = if the first port is occupied then try this many
port number forwards
*/
@property void localPortRange(ushort range)
{
p.curl.set(CurlOption.localportrange, cast(long)range);
}
/** Set the tcp no-delay socket option on or off.
See: $(WEB curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTTCPNODELAY, nodelay)
*/
@property void tcpNoDelay(bool on)
{
p.curl.set(CurlOption.tcp_nodelay, cast(long) (on ? 1 : 0) );
}
/** Sets whether SSL peer certificates should be verified.
See: $(WEB curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTSSLVERIFYPEER, verifypeer)
*/
@property void verifyPeer(bool on)
{
p.curl.set(CurlOption.ssl_verifypeer, on ? 1 : 0);
}
/** Sets whether the host within an SSL certificate should be verified.
See: $(WEB curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTSSLVERIFYHOST, verifypeer)
*/
@property void verifyHost(bool on)
{
p.curl.set(CurlOption.ssl_verifyhost, on ? 2 : 0);
}
// Authentication settings
/**
Set the user name, password and optionally domain for authentication
purposes.
Some protocols may need authentication in some cases. Use this
function to provide credentials.
Params:
username = the username
password = the password
domain = used for NTLM authentication only and is set to the NTLM domain
name
*/
void setAuthentication(const(char)[] username, const(char)[] password,
const(char)[] domain = "")
{
if (!domain.empty)
username = format("%s/%s", domain, username);
p.curl.set(CurlOption.userpwd, format("%s:%s", username, password));
}
unittest
{
if (!netAllowed()) return;
auto http = HTTP("http://www.protected.com");
http.onReceiveHeader =
(in char[] key,
in char[] value) { /* writeln(key ~ ": " ~ value); */ };
http.onReceive = (ubyte[] data) { return data.length; };
http.setAuthentication("myuser", "mypassword");
http.perform();
}
/**
Set the user name and password for proxy authentication.
Params:
username = the username
password = the password
*/
void setProxyAuthentication(const(char)[] username, const(char)[] password)
{
p.curl.set(CurlOption.proxyuserpwd,
format("%s:%s",
username.replace(":", "%3A"),
password.replace(":", "%3A"))
);
}
/**
* The event handler that gets called when data is needed for sending. The
* length of the $(D void[]) specifies the maximum number of bytes that can
* be sent.
*
* Returns:
* The callback returns the number of elements in the buffer that have been
* filled and are ready to send.
* The special value $(D .abortRequest) can be returned in order to abort the
* current request.
* The special value $(D .pauseRequest) can be returned in order to pause the
* current request.
*
* Example:
* ----
* import std.net.curl;
* string msg = "Hello world";
* auto client = HTTP("dlang.org");
* client.onSend = delegate size_t(void[] data)
* {
* auto m = cast(void[])msg;
* size_t length = m.length > data.length ? data.length : m.length;
* if (length == 0) return 0;
* data[0..length] = m[0..length];
* msg = msg[length..$];
* return length;
* };
* client.perform();
* ----
*/
@property void onSend(size_t delegate(void[]) callback)
{
p.curl.clear(CurlOption.postfields); // cannot specify data when using callback
p.curl.onSend = callback;
}
/**
* The event handler that receives incoming data. Be sure to copy the
* incoming ubyte[] since it is not guaranteed to be valid after the
* callback returns.
*
* Returns:
* The callback returns the number of incoming bytes read. If the entire array is
* not read the request will abort.
* The special value .pauseRequest can be returned in order to pause the
* current request.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* auto client = HTTP("dlang.org");
* client.onReceive = (ubyte[] data)
* {
* writeln("Got data", to!(const(char)[])(data));
* return data.length;
* };
* client.perform();
* ----
*/
@property void onReceive(size_t delegate(ubyte[]) callback)
{
p.curl.onReceive = callback;
}
/**
* The event handler that gets called to inform of upload/download progress.
*
* Params:
* dlTotal = total bytes to download
* dlNow = currently downloaded bytes
* ulTotal = total bytes to upload
* ulNow = currently uploaded bytes
*
* Returns:
* Return 0 from the callback to signal success, return non-zero to abort
* transfer
*
* Example:
* ----
* import std.net.curl, std.stdio;
* auto client = HTTP("dlang.org");
* client.onProgress = delegate int(size_t dl, size_t dln, size_t ul, size_t ult)
* {
* writeln("Progress: downloaded ", dln, " of ", dl);
* writeln("Progress: uploaded ", uln, " of ", ul);
* };
* client.perform();
* ----
*/
@property void onProgress(int delegate(size_t dlTotal, size_t dlNow,
size_t ulTotal, size_t ulNow) callback)
{
p.curl.onProgress = callback;
}
}
/*
Decode $(D ubyte[]) array using the provided EncodingScheme up to maxChars
Returns: Tuple of ubytes read and the $(D Char[]) characters decoded.
Not all ubytes are guaranteed to be read in case of decoding error.
*/
private Tuple!(size_t,Char[])
decodeString(Char = char)(const(ubyte)[] data,
EncodingScheme scheme,
size_t maxChars = size_t.max)
{
Char[] res;
auto startLen = data.length;
size_t charsDecoded = 0;
while (data.length && charsDecoded < maxChars)
{
dchar dc = scheme.safeDecode(data);
if (dc == INVALID_SEQUENCE)
{
return typeof(return)(size_t.max, cast(Char[])null);
}
charsDecoded++;
res ~= dc;
}
return typeof(return)(startLen-data.length, res);
}
/*
Decode $(D ubyte[]) array using the provided $(D EncodingScheme) until a the
line terminator specified is found. The basesrc parameter is effectively
prepended to src as the first thing.
This function is used for decoding as much of the src buffer as
possible until either the terminator is found or decoding fails. If
it fails as the last data in the src it may mean that the src buffer
were missing some bytes in order to represent a correct code
point. Upon the next call to this function more bytes have been
received from net and the failing bytes should be given as the
basesrc parameter. It is done this way to minimize data copying.
Returns: true if a terminator was found
Not all ubytes are guaranteed to be read in case of decoding error.
any decoded chars will be inserted into dst.
*/
private bool decodeLineInto(Terminator, Char = char)(ref const(ubyte)[] basesrc,
ref const(ubyte)[] src,
ref Char[] dst,
EncodingScheme scheme,
Terminator terminator)
{
auto startLen = src.length;
size_t charsDecoded = 0;
// if there is anything in the basesrc then try to decode that
// first.
if (basesrc.length != 0)
{
// Try to ensure 4 entries in the basesrc by copying from src.
auto blen = basesrc.length;
size_t len = (basesrc.length + src.length) >= 4 ?
4 : basesrc.length + src.length;
basesrc.length = len;
dchar dc = scheme.safeDecode(basesrc);
if (dc == INVALID_SEQUENCE)
{
enforce!CurlException(len != 4, "Invalid code sequence");
return false;
}
dst ~= dc;
src = src[len-basesrc.length-blen .. $]; // remove used ubytes from src
basesrc.length = 0;
}
while (src.length)
{
auto lsrc = src;
dchar dc = scheme.safeDecode(src);
if (dc == INVALID_SEQUENCE)
{
if (src.empty)
{
// The invalid sequence was in the end of the src. Maybe there
// just need to be more bytes available so these last bytes are
// put back to src for later use.
src = lsrc;
return false;
}
dc = '?';
}
dst ~= dc;
if (dst.endsWith(terminator))
return true;
}
return false; // no terminator found
}
/**
* HTTP client functionality.
*
* Example:
* ---
* import std.net.curl, std.stdio;
*
* // Get with custom data receivers
* auto http = HTTP("dlang.org");
* http.onReceiveHeader =
* (in char[] key, in char[] value) { writeln(key ~ ": " ~ value); };
* http.onReceive = (ubyte[] data) { /+ drop +/ return data.length; };
* http.perform();
*
* // Put with data senders
* auto msg = "Hello world";
* http.contentLength = msg.length;
* http.onSend = (void[] data)
* {
* auto m = cast(void[])msg;
* size_t len = m.length > data.length ? data.length : m.length;
* if (len == 0) return len;
* data[0..len] = m[0..len];
* msg = msg[len..$];
* return len;
* };
* http.perform();
*
* // Track progress
* http.method = HTTP.Method.get;
* http.url = "http://upload.wikimedia.org/wikipedia/commons/"
* "5/53/Wikipedia-logo-en-big.png";
* http.onReceive = (ubyte[] data) { return data.length; };
* http.onProgress = (size_t dltotal, size_t dlnow,
* size_t ultotal, size_t ulnow)
* {
* writeln("Progress ", dltotal, ", ", dlnow, ", ", ultotal, ", ", ulnow);
* return 0;
* };
* http.perform();
* ---
*
* See_Also: $(WEB www.ietf.org/rfc/rfc2616.txt, RFC2616)
*
*/
struct HTTP
{
mixin Protocol;
/// Authentication method equal to $(ECXREF curl, CurlAuth)
alias AuthMethod = CurlAuth;
static private uint defaultMaxRedirects = 10;
private struct Impl
{
~this()
{
if (headersOut !is null)
Curl.curl.slist_free_all(headersOut);
if (curl.handle !is null) // work around RefCounted/emplace bug
curl.shutdown();
}
Curl curl;
curl_slist* headersOut;
string[string] headersIn;
string charset;
/// The status line of the final sub-request in a request.
StatusLine status;
private void delegate(StatusLine) onReceiveStatusLine;
/// The HTTP method to use.
Method method = Method.undefined;
@property void onReceiveHeader(void delegate(in char[] key,
in char[] value) callback)
{
// Wrap incoming callback in order to separate http status line from
// http headers. On redirected requests there may be several such
// status lines. The last one is the one recorded.
auto dg = (in char[] header)
{
import std.utf : UTFException;
try
{
if (header.empty)
{
// header delimiter
return;
}
if (header.startsWith("HTTP/"))
{
string[string] empty;
headersIn = empty; // clear
auto m = match(header, regex(r"^HTTP/(\d+)\.(\d+) (\d+) (.*)$"));
if (m.empty)
{
// Invalid status line
}
else
{
status.majorVersion = to!ushort(m.captures[1]);
status.minorVersion = to!ushort(m.captures[2]);
status.code = to!ushort(m.captures[3]);
status.reason = m.captures[4].idup;
if (onReceiveStatusLine != null)
onReceiveStatusLine(status);
}
return;
}
// Normal http header
auto m = match(cast(char[]) header, regex("(.*?): (.*)$"));
auto fieldName = m.captures[1].toLower().idup;
if (fieldName == "content-type")
{
auto mct = match(cast(char[]) m.captures[2],
regex("charset=([^;]*)"));
if (!mct.empty && mct.captures.length > 1)
charset = mct.captures[1].idup;
}
if (!m.empty && callback !is null)
callback(fieldName, m.captures[2]);
headersIn[fieldName] = m.captures[2].idup;
}
catch(UTFException e)
{
//munch it - a header should be all ASCII, any "wrong UTF" is broken header
}
};
curl.onReceiveHeader = dg;
}
}
private RefCounted!Impl p;
/** Time condition enumeration as an alias of $(ECXREF curl, CurlTimeCond)
$(WEB www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.25, _RFC2616 Section 14.25)
*/
alias TimeCond = CurlTimeCond;
/**
Constructor taking the url as parameter.
*/
static HTTP opCall(const(char)[] url)
{
HTTP http;
http.initialize();
http.url = url;
return http;
}
static HTTP opCall()
{
HTTP http;
http.initialize();
return http;
}
HTTP dup()
{
HTTP copy;
copy.initialize();
copy.p.method = p.method;
curl_slist* cur = p.headersOut;
curl_slist* newlist = null;
while (cur)
{
newlist = Curl.curl.slist_append(newlist, cur.data);
cur = cur.next;
}
copy.p.headersOut = newlist;
copy.p.curl.set(CurlOption.httpheader, copy.p.headersOut);
copy.p.curl = p.curl.dup();
copy.dataTimeout = _defaultDataTimeout;
copy.onReceiveHeader = null;
return copy;
}
private void initialize()
{
p.curl.initialize();
maxRedirects = HTTP.defaultMaxRedirects;
p.charset = "ISO-8859-1"; // Default charset defined in HTTP RFC
p.method = Method.undefined;
setUserAgent(HTTP.defaultUserAgent);
dataTimeout = _defaultDataTimeout;
onReceiveHeader = null;
version (unittest) verbose = true;
verifyPeer = true;
verifyHost = true;
}
/**
Perform a http request.
After the HTTP client has been setup and possibly assigned callbacks the
$(D perform()) method will start performing the request towards the
specified server.
Params:
throwOnError = whether to throw an exception or return a CurlCode on error
*/
CurlCode perform(ThrowOnError throwOnError = ThrowOnError.yes)
{
p.status.reset();
final switch (p.method)
{
case Method.head:
p.curl.set(CurlOption.nobody, 1L);
break;
case Method.undefined:
case Method.get:
p.curl.set(CurlOption.httpget, 1L);
break;
case Method.post:
p.curl.set(CurlOption.post, 1L);
break;
case Method.put:
p.curl.set(CurlOption.upload, 1L);
break;
case Method.del:
p.curl.set(CurlOption.customrequest, "DELETE");
break;
case Method.options:
p.curl.set(CurlOption.customrequest, "OPTIONS");
break;
case Method.trace:
p.curl.set(CurlOption.customrequest, "TRACE");
break;
case Method.connect:
p.curl.set(CurlOption.customrequest, "CONNECT");
break;
}
return p.curl.perform(throwOnError);
}
/// The URL to specify the location of the resource.
@property void url(const(char)[] url)
{
if (!startsWith(url.toLower(), "http://", "https://"))
url = "http://" ~ url;
p.curl.set(CurlOption.url, url);
}
/// Set the CA certificate bundle file to use for SSL peer verification
@property void caInfo(const(char)[] caFile)
{
p.curl.set(CurlOption.cainfo, caFile);
}
// This is a workaround for mixed in content not having its
// docs mixed in.
version (StdDdoc)
{
/// Value to return from $(D onSend)/$(D onReceive) delegates in order to
/// pause a request
alias requestPause = CurlReadFunc.pause;
/// Value to return from onSend delegate in order to abort a request
alias requestAbort = CurlReadFunc.abort;
/**
True if the instance is stopped. A stopped instance is not usable.
*/
@property bool isStopped();
/// Stop and invalidate this instance.
void shutdown();
/** Set verbose.
This will print request information to stderr.
*/
@property void verbose(bool on);
// Connection settings
/// Set timeout for activity on connection.
@property void dataTimeout(Duration d);
/** Set maximum time an operation is allowed to take.
This includes dns resolution, connecting, data transfer, etc.
*/
@property void operationTimeout(Duration d);
/// Set timeout for connecting.
@property void connectTimeout(Duration d);
// Network settings
/** Proxy
* See: $(WEB curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY, _proxy)
*/
@property void proxy(const(char)[] host);
/** Proxy port
* See: $(WEB curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXYPORT, _proxy_port)
*/
@property void proxyPort(ushort port);
/// Type of proxy
alias CurlProxy = etc.c.curl.CurlProxy;
/** Proxy type
* See: $(WEB curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY, _proxy_type)
*/
@property void proxyType(CurlProxy type);
/// DNS lookup timeout.
@property void dnsTimeout(Duration d);
/**
* The network interface to use in form of the the IP of the interface.
*
* Example:
* ----
* theprotocol.netInterface = "192.168.1.32";
* theprotocol.netInterface = [ 192, 168, 1, 32 ];
* ----
*
* See: $(XREF socket, InternetAddress)
*/
@property void netInterface(const(char)[] i);
/// ditto
@property void netInterface(const(ubyte)[4] i);
/// ditto
@property void netInterface(InternetAddress i);
/**
Set the local outgoing port to use.
Params:
port = the first outgoing port number to try and use
*/
@property void localPort(ushort port);
/**
Set the local outgoing port range to use.
This can be used together with the localPort property.
Params:
range = if the first port is occupied then try this many
port number forwards
*/
@property void localPortRange(ushort range);
/** Set the tcp no-delay socket option on or off.
See: $(WEB curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTTCPNODELAY, nodelay)
*/
@property void tcpNoDelay(bool on);
// Authentication settings
/**
Set the user name, password and optionally domain for authentication
purposes.
Some protocols may need authentication in some cases. Use this
function to provide credentials.
Params:
username = the username
password = the password
domain = used for NTLM authentication only and is set to the NTLM domain
name
*/
void setAuthentication(const(char)[] username, const(char)[] password,
const(char)[] domain = "");
/**
Set the user name and password for proxy authentication.
Params:
username = the username
password = the password
*/
void setProxyAuthentication(const(char)[] username, const(char)[] password);
/**
* The event handler that gets called when data is needed for sending. The
* length of the $(D void[]) specifies the maximum number of bytes that can
* be sent.
*
* Returns:
* The callback returns the number of elements in the buffer that have been
* filled and are ready to send.
* The special value $(D .abortRequest) can be returned in order to abort the
* current request.
* The special value $(D .pauseRequest) can be returned in order to pause the
* current request.
*
* Example:
* ----
* import std.net.curl;
* string msg = "Hello world";
* auto client = HTTP("dlang.org");
* client.onSend = delegate size_t(void[] data)
* {
* auto m = cast(void[])msg;
* size_t length = m.length > data.length ? data.length : m.length;
* if (length == 0) return 0;
* data[0..length] = m[0..length];
* msg = msg[length..$];
* return length;
* };
* client.perform();
* ----
*/
@property void onSend(size_t delegate(void[]) callback);
/**
* The event handler that receives incoming data. Be sure to copy the
* incoming ubyte[] since it is not guaranteed to be valid after the
* callback returns.
*
* Returns:
* The callback returns the incoming bytes read. If not the entire array is
* the request will abort.
* The special value .pauseRequest can be returned in order to pause the
* current request.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* auto client = HTTP("dlang.org");
* client.onReceive = (ubyte[] data)
* {
* writeln("Got data", to!(const(char)[])(data));
* return data.length;
* };
* client.perform();
* ----
*/
@property void onReceive(size_t delegate(ubyte[]) callback);
/**
* Register an event handler that gets called to inform of
* upload/download progress.
*
* Callback_parameters:
* $(CALLBACK_PARAMS)
*
* Callback_returns: Return 0 to signal success, return non-zero to
* abort transfer.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* auto client = HTTP("dlang.org");
* client.onProgress = delegate int(size_t dl, size_t dln, size_t ul, size_t ult)
* {
* writeln("Progress: downloaded ", dln, " of ", dl);
* writeln("Progress: uploaded ", uln, " of ", ul);
* };
* client.perform();
* ----
*/
@property void onProgress(int delegate(size_t dlTotal, size_t dlNow,
size_t ulTotal, size_t ulNow) callback);
}
/** Clear all outgoing headers.
*/
void clearRequestHeaders()
{
if (p.headersOut !is null)
Curl.curl.slist_free_all(p.headersOut);
p.headersOut = null;
p.curl.clear(CurlOption.httpheader);
}
/** Add a header e.g. "X-CustomField: Something is fishy".
*
* There is no remove header functionality. Do a $(LREF clearRequestHeaders)
* and set the needed headers instead.
*
* Example:
* ---
* import std.net.curl;
* auto client = HTTP();
* client.addRequestHeader("X-Custom-ABC", "This is the custom value");
* string content = get("dlang.org", client);
* ---
*/
void addRequestHeader(const(char)[] name, const(char)[] value)
{
if (icmp(name, "User-Agent") == 0)
return setUserAgent(value);
string nv = format("%s: %s", name, value);
p.headersOut = Curl.curl.slist_append(p.headersOut,
nv.tempCString().buffPtr);
p.curl.set(CurlOption.httpheader, p.headersOut);
}
/**
* The default "User-Agent" value send with a request.
* It has the form "Phobos-std.net.curl/$(I PHOBOS_VERSION) (libcurl/$(I CURL_VERSION))"
*/
static string defaultUserAgent() @property
{
import std.compiler : version_major, version_minor;
// http://curl.haxx.se/docs/versions.html
enum fmt = "Phobos-std.net.curl/%d.%03d (libcurl/%d.%d.%d)";
enum maxLen = fmt.length - "%d%03d%d%d%d".length + 10 + 10 + 3 + 3 + 3;
static char[maxLen] buf = void;
static string userAgent;
if (!userAgent.length)
{
auto curlVer = Curl.curl.version_info(CURLVERSION_NOW).version_num;
userAgent = cast(immutable)sformat(
buf, fmt, version_major, version_minor,
curlVer >> 16 & 0xFF, curlVer >> 8 & 0xFF, curlVer & 0xFF);
}
return userAgent;
}
/** Set the value of the user agent request header field.
*
* By default a request has it's "User-Agent" field set to $(LREF
* defaultUserAgent) even if $(D setUserAgent) was never called. Pass
* an empty string to suppress the "User-Agent" field altogether.
*/
void setUserAgent(const(char)[] userAgent)
{
p.curl.set(CurlOption.useragent, userAgent);
}
/** The headers read from a successful response.
*
*/
@property string[string] responseHeaders()
{
return p.headersIn;
}
/// HTTP method used.
@property void method(Method m)
{
p.method = m;
}
/// ditto
@property Method method()
{
return p.method;
}
/**
HTTP status line of last response. One call to perform may
result in several requests because of redirection.
*/
@property StatusLine statusLine()
{
return p.status;
}
/// Set the active cookie string e.g. "name1=value1;name2=value2"
void setCookie(const(char)[] cookie)
{
p.curl.set(CurlOption.cookie, cookie);
}
/// Set a file path to where a cookie jar should be read/stored.
void setCookieJar(const(char)[] path)
{
p.curl.set(CurlOption.cookiefile, path);
if (path.length)
p.curl.set(CurlOption.cookiejar, path);
}
/// Flush cookie jar to disk.
void flushCookieJar()
{
p.curl.set(CurlOption.cookielist, "FLUSH");
}
/// Clear session cookies.
void clearSessionCookies()
{
p.curl.set(CurlOption.cookielist, "SESS");
}
/// Clear all cookies.
void clearAllCookies()
{
p.curl.set(CurlOption.cookielist, "ALL");
}
/**
Set time condition on the request.
Params:
cond = $(D CurlTimeCond.{none,ifmodsince,ifunmodsince,lastmod})
timestamp = Timestamp for the condition
$(WEB www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.25, _RFC2616 Section 14.25)
*/
void setTimeCondition(HTTP.TimeCond cond, SysTime timestamp)
{
p.curl.set(CurlOption.timecondition, cond);
p.curl.set(CurlOption.timevalue, timestamp.toUnixTime());
}
/** Specifying data to post when not using the onSend callback.
*
* The data is NOT copied by the library. Content-Type will default to
* application/octet-stream. Data is not converted or encoded by this
* method.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* auto http = HTTP("http://www.mydomain.com");
* http.onReceive = (ubyte[] data) { writeln(to!(const(char)[])(data)); return data.length; };
* http.postData = [1,2,3,4,5];
* http.perform();
* ----
*/
@property void postData(const(void)[] data)
{
setPostData(data, "application/octet-stream");
}
/** Specifying data to post when not using the onSend callback.
*
* The data is NOT copied by the library. Content-Type will default to
* text/plain. Data is not converted or encoded by this method.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* auto http = HTTP("http://www.mydomain.com");
* http.onReceive = (ubyte[] data) { writeln(to!(const(char)[])(data)); return data.length; };
* http.postData = "The quick....";
* http.perform();
* ----
*/
@property void postData(const(char)[] data)
{
setPostData(data, "text/plain");
}
/**
* Specify data to post when not using the onSend callback, with
* user-specified Content-Type.
* Params:
* data = Data to post.
* contentType = MIME type of the data, for example, "text/plain" or
* "application/octet-stream". See also:
* $(LINK2 http://en.wikipedia.org/wiki/Internet_media_type,
* Internet media type) on Wikipedia.
* -----
* import std.net.curl;
* auto http = HTTP("http://onlineform.example.com");
* auto data = "app=login&username=bob&password=s00perS3kret";
* http.setPostData(data, "application/x-www-form-urlencoded");
* http.onReceive = (ubyte[] data) { return data.length; };
* http.perform();
* -----
*/
void setPostData(const(void)[] data, string contentType)
{
// cannot use callback when specifying data directly so it is disabled here.
p.curl.clear(CurlOption.readfunction);
addRequestHeader("Content-Type", contentType);
p.curl.set(CurlOption.postfields, cast(void*)data.ptr);
p.curl.set(CurlOption.postfieldsize, data.length);
if (method == Method.undefined)
method = Method.post;
}
unittest
{
if (!netAllowed()) return;
ubyte[] data;
foreach (n; 0..256)
data ~= cast(ubyte)n;
auto http = HTTP(testUrl2);
http.postData = data;
ubyte[] result;
http.onReceive = (ubyte[] data) { result ~= data; return data.length; };
http.perform();
assert(data == result,
"HTTP POST with binary data returns unexpected content (" ~ text(result.length) ~ " bytes)");
}
/**
* Set the event handler that receives incoming headers.
*
* The callback will receive a header field key, value as parameter. The
* $(D const(char)[]) arrays are not valid after the delegate has returned.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* auto http = HTTP("dlang.org");
* http.onReceive = (ubyte[] data) { writeln(to!(const(char)[])(data)); return data.length; };
* http.onReceiveHeader = (in char[] key, in char[] value) { writeln(key, " = ", value); };
* http.perform();
* ----
*/
@property void onReceiveHeader(void delegate(in char[] key,
in char[] value) callback)
{
p.onReceiveHeader = callback;
}
/**
Callback for each received StatusLine.
Notice that several callbacks can be done for each call to
$(D perform()) due to redirections.
See_Also: $(LREF StatusLine)
*/
@property void onReceiveStatusLine(void delegate(StatusLine) callback)
{
p.onReceiveStatusLine = callback;
}
/**
The content length in bytes when using request that has content
e.g. POST/PUT and not using chunked transfer. Is set as the
"Content-Length" header. Set to size_t.max to reset to chunked transfer.
*/
@property void contentLength(size_t len)
{
CurlOption lenOpt;
// Force post if necessary
if (p.method != Method.put && p.method != Method.post)
p.method = Method.post;
if (p.method == Method.put)
lenOpt = CurlOption.infilesize_large;
else
// post
lenOpt = CurlOption.postfieldsize_large;
if (len == size_t.max)
{
// HTTP 1.1 supports requests with no length header set.
addRequestHeader("Transfer-Encoding", "chunked");
addRequestHeader("Expect", "100-continue");
}
else
{
p.curl.set(lenOpt, len);
}
}
/**
Authentication method as specified in $(LREF AuthMethod).
*/
@property void authenticationMethod(AuthMethod authMethod)
{
p.curl.set(CurlOption.httpauth, cast(long) authMethod);
}
/**
Set max allowed redirections using the location header.
uint.max for infinite.
*/
@property void maxRedirects(uint maxRedirs)
{
if (maxRedirs == uint.max)
{
// Disable
p.curl.set(CurlOption.followlocation, 0);
}
else
{
p.curl.set(CurlOption.followlocation, 1);
p.curl.set(CurlOption.maxredirs, maxRedirs);
}
}
/** <a name="HTTP.Method"/ >The standard HTTP methods :
* $(WEB www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.1, _RFC2616 Section 5.1.1)
*/
enum Method
{
undefined,
head, ///
get, ///
post, ///
put, ///
del, ///
options, ///
trace, ///
connect ///
}
/**
HTTP status line ie. the first line returned in an HTTP response.
If authentication or redirections are done then the status will be for
the last response received.
*/
struct StatusLine
{
ushort majorVersion; /// Major HTTP version ie. 1 in HTTP/1.0.
ushort minorVersion; /// Minor HTTP version ie. 0 in HTTP/1.0.
ushort code; /// HTTP status line code e.g. 200.
string reason; /// HTTP status line reason string.
/// Reset this status line
@safe void reset()
{
majorVersion = 0;
minorVersion = 0;
code = 0;
reason = "";
}
///
string toString()
{
return format("%s %s (%s.%s)",
code, reason, majorVersion, minorVersion);
}
}
} // HTTP
/**
FTP client functionality.
See_Also: $(WEB tools.ietf.org/html/rfc959, RFC959)
*/
struct FTP
{
mixin Protocol;
private struct Impl
{
~this()
{
if (commands !is null)
Curl.curl.slist_free_all(commands);
if (curl.handle !is null) // work around RefCounted/emplace bug
curl.shutdown();
}
curl_slist* commands;
Curl curl;
string encoding;
}
private RefCounted!Impl p;
/**
FTP access to the specified url.
*/
static FTP opCall(const(char)[] url)
{
FTP ftp;
ftp.initialize();
ftp.url = url;
return ftp;
}
static FTP opCall()
{
FTP ftp;
ftp.initialize();
return ftp;
}
FTP dup()
{
FTP copy = FTP();
copy.initialize();
copy.p.encoding = p.encoding;
copy.p.curl = p.curl.dup();
curl_slist* cur = p.commands;
curl_slist* newlist = null;
while (cur)
{
newlist = Curl.curl.slist_append(newlist, cur.data);
cur = cur.next;
}
copy.p.commands = newlist;
copy.p.curl.set(CurlOption.postquote, copy.p.commands);
copy.dataTimeout = _defaultDataTimeout;
return copy;
}
private void initialize()
{
p.curl.initialize();
p.encoding = "ISO-8859-1";
dataTimeout = _defaultDataTimeout;
version (unittest) verbose = true;
}
/**
Performs the ftp request as it has been configured.
After a FTP client has been setup and possibly assigned callbacks the $(D
perform()) method will start performing the actual communication with the
server.
Params:
throwOnError = whether to throw an exception or return a CurlCode on error
*/
CurlCode perform(ThrowOnError throwOnError = ThrowOnError.yes)
{
return p.curl.perform(throwOnError);
}
/// The URL to specify the location of the resource.
@property void url(const(char)[] url)
{
if (!startsWith(url.toLower(), "ftp://", "ftps://"))
url = "ftp://" ~ url;
p.curl.set(CurlOption.url, url);
}
// This is a workaround for mixed in content not having its
// docs mixed in.
version (StdDdoc)
{
/// Value to return from $(D onSend)/$(D onReceive) delegates in order to
/// pause a request
alias requestPause = CurlReadFunc.pause;
/// Value to return from onSend delegate in order to abort a request
alias requestAbort = CurlReadFunc.abort;
/**
True if the instance is stopped. A stopped instance is not usable.
*/
@property bool isStopped();
/// Stop and invalidate this instance.
void shutdown();
/** Set verbose.
This will print request information to stderr.
*/
@property void verbose(bool on);
// Connection settings
/// Set timeout for activity on connection.
@property void dataTimeout(Duration d);
/** Set maximum time an operation is allowed to take.
This includes dns resolution, connecting, data transfer, etc.
*/
@property void operationTimeout(Duration d);
/// Set timeout for connecting.
@property void connectTimeout(Duration d);
// Network settings
/** Proxy
* See: $(WEB curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY, _proxy)
*/
@property void proxy(const(char)[] host);
/** Proxy port
* See: $(WEB curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXYPORT, _proxy_port)
*/
@property void proxyPort(ushort port);
/// Type of proxy
alias CurlProxy = etc.c.curl.CurlProxy;
/** Proxy type
* See: $(WEB curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY, _proxy_type)
*/
@property void proxyType(CurlProxy type);
/// DNS lookup timeout.
@property void dnsTimeout(Duration d);
/**
* The network interface to use in form of the the IP of the interface.
*
* Example:
* ----
* theprotocol.netInterface = "192.168.1.32";
* theprotocol.netInterface = [ 192, 168, 1, 32 ];
* ----
*
* See: $(XREF socket, InternetAddress)
*/
@property void netInterface(const(char)[] i);
/// ditto
@property void netInterface(const(ubyte)[4] i);
/// ditto
@property void netInterface(InternetAddress i);
/**
Set the local outgoing port to use.
Params:
port = the first outgoing port number to try and use
*/
@property void localPort(ushort port);
/**
Set the local outgoing port range to use.
This can be used together with the localPort property.
Params:
range = if the first port is occupied then try this many
port number forwards
*/
@property void localPortRange(ushort range);
/** Set the tcp no-delay socket option on or off.
See: $(WEB curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTTCPNODELAY, nodelay)
*/
@property void tcpNoDelay(bool on);
// Authentication settings
/**
Set the user name, password and optionally domain for authentication
purposes.
Some protocols may need authentication in some cases. Use this
function to provide credentials.
Params:
username = the username
password = the password
domain = used for NTLM authentication only and is set to the NTLM domain
name
*/
void setAuthentication(const(char)[] username, const(char)[] password,
const(char)[] domain = "");
/**
Set the user name and password for proxy authentication.
Params:
username = the username
password = the password
*/
void setProxyAuthentication(const(char)[] username, const(char)[] password);
/**
* The event handler that gets called when data is needed for sending. The
* length of the $(D void[]) specifies the maximum number of bytes that can
* be sent.
*
* Returns:
* The callback returns the number of elements in the buffer that have been
* filled and are ready to send.
* The special value $(D .abortRequest) can be returned in order to abort the
* current request.
* The special value $(D .pauseRequest) can be returned in order to pause the
* current request.
*
*/
@property void onSend(size_t delegate(void[]) callback);
/**
* The event handler that receives incoming data. Be sure to copy the
* incoming ubyte[] since it is not guaranteed to be valid after the
* callback returns.
*
* Returns:
* The callback returns the incoming bytes read. If not the entire array is
* the request will abort.
* The special value .pauseRequest can be returned in order to pause the
* current request.
*
*/
@property void onReceive(size_t delegate(ubyte[]) callback);
/**
* The event handler that gets called to inform of upload/download progress.
*
* Callback_parameters:
* $(CALLBACK_PARAMS)
*
* Callback_returns:
* Return 0 from the callback to signal success, return non-zero to
* abort transfer.
*/
@property void onProgress(int delegate(size_t dlTotal, size_t dlNow,
size_t ulTotal, size_t ulNow) callback);
}
/** Clear all commands send to ftp server.
*/
void clearCommands()
{
if (p.commands !is null)
Curl.curl.slist_free_all(p.commands);
p.commands = null;
p.curl.clear(CurlOption.postquote);
}
/** Add a command to send to ftp server.
*
* There is no remove command functionality. Do a $(LREF clearCommands) and
* set the needed commands instead.
*
* Example:
* ---
* import std.net.curl;
* auto client = FTP();
* client.addCommand("RNFR my_file.txt");
* client.addCommand("RNTO my_renamed_file.txt");
* upload("my_file.txt", "ftp.digitalmars.com", client);
* ---
*/
void addCommand(const(char)[] command)
{
p.commands = Curl.curl.slist_append(p.commands,
command.tempCString().buffPtr);
p.curl.set(CurlOption.postquote, p.commands);
}
/// Connection encoding. Defaults to ISO-8859-1.
@property void encoding(string name)
{
p.encoding = name;
}
/// ditto
@property string encoding()
{
return p.encoding;
}
/**
The content length in bytes of the ftp data.
*/
@property void contentLength(size_t len)
{
p.curl.set(CurlOption.infilesize_large, len);
}
}
/**
* Basic SMTP protocol support.
*
* Example:
* ---
* import std.net.curl;
*
* // Send an email with SMTPS
* auto smtp = SMTP("smtps://smtp.gmail.com");
* smtp.setAuthentication("from.addr@gmail.com", "password");
* smtp.mailTo = ["<to.addr@gmail.com>"];
* smtp.mailFrom = "<from.addr@gmail.com>";
* smtp.message = "Example Message";
* smtp.perform();
* ---
*
* See_Also: $(WEB www.ietf.org/rfc/rfc2821.txt, RFC2821)
*/
struct SMTP
{
mixin Protocol;
private struct Impl
{
~this()
{
if (curl.handle !is null) // work around RefCounted/emplace bug
curl.shutdown();
}
Curl curl;
@property void message(string msg)
{
auto _message = msg;
/**
This delegate reads the message text and copies it.
*/
curl.onSend = delegate size_t(void[] data)
{
if (!msg.length) return 0;
auto m = cast(void[])msg;
size_t to_copy = min(data.length, _message.length);
data[0..to_copy] = (cast(void[])_message)[0..to_copy];
_message = _message[to_copy..$];
return to_copy;
};
}
}
private RefCounted!Impl p;
/**
Sets to the URL of the SMTP server.
*/
static SMTP opCall(const(char)[] url)
{
SMTP smtp;
smtp.initialize();
smtp.url = url;
return smtp;
}
static SMTP opCall()
{
SMTP smtp;
smtp.initialize();
return smtp;
}
/+ TODO: The other structs have this function.
SMTP dup()
{
SMTP copy = SMTP();
copy.initialize();
copy.p.encoding = p.encoding;
copy.p.curl = p.curl.dup();
curl_slist* cur = p.commands;
curl_slist* newlist = null;
while (cur)
{
newlist = Curl.curl.slist_append(newlist, cur.data);
cur = cur.next;
}
copy.p.commands = newlist;
copy.p.curl.set(CurlOption.postquote, copy.p.commands);
copy.dataTimeout = _defaultDataTimeout;
return copy;
}
+/
/**
Performs the request as configured.
Params:
throwOnError = whether to throw an exception or return a CurlCode on error
*/
CurlCode perform(ThrowOnError throwOnError = ThrowOnError.yes)
{
return p.curl.perform(throwOnError);
}
/// The URL to specify the location of the resource.
@property void url(const(char)[] url)
{
auto lowered = url.toLower();
if (lowered.startsWith("smtps://"))
{
p.curl.set(CurlOption.use_ssl, CurlUseSSL.all);
}
else
{
enforce!CurlException(lowered.startsWith("smtp://"),
"The url must be for the smtp protocol.");
}
p.curl.set(CurlOption.url, url);
}
private void initialize()
{
p.curl.initialize();
p.curl.set(CurlOption.upload, 1L);
dataTimeout = _defaultDataTimeout;
verifyPeer = true;
verifyHost = true;
}
// This is a workaround for mixed in content not having its
// docs mixed in.
version (StdDdoc)
{
/// Value to return from $(D onSend)/$(D onReceive) delegates in order to
/// pause a request
alias requestPause = CurlReadFunc.pause;
/// Value to return from onSend delegate in order to abort a request
alias requestAbort = CurlReadFunc.abort;
/**
True if the instance is stopped. A stopped instance is not usable.
*/
@property bool isStopped();
/// Stop and invalidate this instance.
void shutdown();
/** Set verbose.
This will print request information to stderr.
*/
@property void verbose(bool on);
// Connection settings
/// Set timeout for activity on connection.
@property void dataTimeout(Duration d);
/** Set maximum time an operation is allowed to take.
This includes dns resolution, connecting, data transfer, etc.
*/
@property void operationTimeout(Duration d);
/// Set timeout for connecting.
@property void connectTimeout(Duration d);
// Network settings
/** Proxy
* See: $(WEB curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY, _proxy)
*/
@property void proxy(const(char)[] host);
/** Proxy port
* See: $(WEB curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXYPORT, _proxy_port)
*/
@property void proxyPort(ushort port);
/// Type of proxy
alias CurlProxy = etc.c.curl.CurlProxy;
/** Proxy type
* See: $(WEB curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTPROXY, _proxy_type)
*/
@property void proxyType(CurlProxy type);
/// DNS lookup timeout.
@property void dnsTimeout(Duration d);
/**
* The network interface to use in form of the the IP of the interface.
*
* Example:
* ----
* theprotocol.netInterface = "192.168.1.32";
* theprotocol.netInterface = [ 192, 168, 1, 32 ];
* ----
*
* See: $(XREF socket, InternetAddress)
*/
@property void netInterface(const(char)[] i);
/// ditto
@property void netInterface(const(ubyte)[4] i);
/// ditto
@property void netInterface(InternetAddress i);
/**
Set the local outgoing port to use.
Params:
port = the first outgoing port number to try and use
*/
@property void localPort(ushort port);
/**
Set the local outgoing port range to use.
This can be used together with the localPort property.
Params:
range = if the first port is occupied then try this many
port number forwards
*/
@property void localPortRange(ushort range);
/** Set the tcp no-delay socket option on or off.
See: $(WEB curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTTCPNODELAY, nodelay)
*/
@property void tcpNoDelay(bool on);
// Authentication settings
/**
Set the user name, password and optionally domain for authentication
purposes.
Some protocols may need authentication in some cases. Use this
function to provide credentials.
Params:
username = the username
password = the password
domain = used for NTLM authentication only and is set to the NTLM domain
name
*/
void setAuthentication(const(char)[] username, const(char)[] password,
const(char)[] domain = "");
/**
Set the user name and password for proxy authentication.
Params:
username = the username
password = the password
*/
void setProxyAuthentication(const(char)[] username, const(char)[] password);
/**
* The event handler that gets called when data is needed for sending. The
* length of the $(D void[]) specifies the maximum number of bytes that can
* be sent.
*
* Returns:
* The callback returns the number of elements in the buffer that have been
* filled and are ready to send.
* The special value $(D .abortRequest) can be returned in order to abort the
* current request.
* The special value $(D .pauseRequest) can be returned in order to pause the
* current request.
*/
@property void onSend(size_t delegate(void[]) callback);
/**
* The event handler that receives incoming data. Be sure to copy the
* incoming ubyte[] since it is not guaranteed to be valid after the
* callback returns.
*
* Returns:
* The callback returns the incoming bytes read. If not the entire array is
* the request will abort.
* The special value .pauseRequest can be returned in order to pause the
* current request.
*/
@property void onReceive(size_t delegate(ubyte[]) callback);
/**
* The event handler that gets called to inform of upload/download progress.
*
* Callback_parameters:
* $(CALLBACK_PARAMS)
*
* Callback_returns:
* Return 0 from the callback to signal success, return non-zero to
* abort transfer.
*/
@property void onProgress(int delegate(size_t dlTotal, size_t dlNow,
size_t ulTotal, size_t ulNow) callback);
}
/**
Setter for the sender's email address.
*/
@property void mailFrom()(const(char)[] sender)
{
assert(!sender.empty, "Sender must not be empty");
p.curl.set(CurlOption.mail_from, sender);
}
/**
Setter for the recipient email addresses.
*/
void mailTo()(const(char)[][] recipients...)
{
assert(!recipients.empty, "Recipient must not be empty");
curl_slist* recipients_list = null;
foreach(recipient; recipients)
{
recipients_list =
Curl.curl.slist_append(recipients_list,
recipient.tempCString().buffPtr);
}
p.curl.set(CurlOption.mail_rcpt, recipients_list);
}
/**
Sets the message body text.
*/
@property void message(string msg)
{
p.message = msg;
}
}
/++
Exception thrown on errors in std.net.curl functions.
+/
class CurlException : Exception
{
/++
Params:
msg = The message for the exception.
file = The file where the exception occurred.
line = The line number where the exception occurred.
next = The previous exception in the chain of exceptions, if any.
+/
@safe pure nothrow
this(string msg,
string file = __FILE__,
size_t line = __LINE__,
Throwable next = null)
{
super(msg, file, line, next);
}
}
/++
Exception thrown on timeout errors in std.net.curl functions.
+/
class CurlTimeoutException : CurlException
{
/++
Params:
msg = The message for the exception.
file = The file where the exception occurred.
line = The line number where the exception occurred.
next = The previous exception in the chain of exceptions, if any.
+/
@safe pure nothrow
this(string msg,
string file = __FILE__,
size_t line = __LINE__,
Throwable next = null)
{
super(msg, file, line, next);
}
}
/// Equal to $(ECXREF curl, CURLcode)
alias CurlCode = CURLcode;
import std.typecons : Flag;
/// Flag to specify whether or not an exception is thrown on error.
alias ThrowOnError = Flag!"throwOnError";
private struct CurlAPI
{
static struct API
{
extern(C):
import core.stdc.config : c_long;
CURLcode function(c_long flags) global_init;
void function() global_cleanup;
curl_version_info_data * function(CURLversion) version_info;
CURL* function() easy_init;
CURLcode function(CURL *curl, CURLoption option,...) easy_setopt;
CURLcode function(CURL *curl) easy_perform;
CURL* function(CURL *curl) easy_duphandle;
char* function(CURLcode) easy_strerror;
CURLcode function(CURL *handle, int bitmask) easy_pause;
void function(CURL *curl) easy_cleanup;
curl_slist* function(curl_slist *, char *) slist_append;
void function(curl_slist *) slist_free_all;
}
__gshared API _api;
__gshared void* _handle;
static ref API instance() @property
{
import std.concurrency;
initOnce!_handle(loadAPI());
return _api;
}
static void* loadAPI()
{
version (Posix)
{
import core.sys.posix.dlfcn;
alias loadSym = dlsym;
}
else version (Windows)
{
import core.sys.windows.windows;
alias loadSym = GetProcAddress;
}
else
static assert(0, "unimplemented");
void* handle;
version (Posix)
handle = dlopen(null, RTLD_LAZY);
else version (Windows)
handle = GetModuleHandleA(null);
assert(handle !is null);
// try to load curl from the executable to allow static linking
if (loadSym(handle, "curl_global_init") is null)
{
version (Posix)
dlclose(handle);
version (OSX)
static immutable names = ["libcurl.4.dylib"];
else version (Posix)
static immutable names = ["libcurl.so", "libcurl.so.4", "libcurl-gnutls.so.4", "libcurl-nss.so.4", "libcurl.so.3"];
else version (Windows)
static immutable names = ["libcurl.dll", "curl.dll"];
foreach (name; names)
{
version (Posix)
handle = dlopen(name.ptr, RTLD_LAZY);
else version (Windows)
handle = LoadLibraryA(name.ptr);
if (handle !is null) break;
}
enforce!CurlException(handle !is null, "Failed to load curl, tried %(%s, %).".format(names));
}
foreach (mem; __traits(allMembers, API))
{
void* p = loadSym(handle, "curl_"~mem);
__traits(getMember, _api, mem) = cast(typeof(__traits(getMember, _api, mem)))
enforce!CurlException(p, "Couldn't load curl_"~mem~" from libcurl.");
}
enforce!CurlException(!_api.global_init(CurlGlobal.all),
"Failed to initialize libcurl");
return handle;
}
shared static ~this()
{
if (_handle is null) return;
_api.global_cleanup();
version (Posix)
{
import core.sys.posix.dlfcn;
dlclose(_handle);
}
else version (Windows)
{
import core.sys.windows.windows;
FreeLibrary(_handle);
}
else
static assert(0, "unimplemented");
_api = API.init;
_handle = null;
}
}
/**
Wrapper to provide a better interface to libcurl than using the plain C API.
It is recommended to use the $(D HTTP)/$(D FTP) etc. structs instead unless
raw access to libcurl is needed.
Warning: This struct uses interior pointers for callbacks. Only allocate it
on the stack if you never move or copy it. This also means passing by reference
when passing Curl to other functions. Otherwise always allocate on
the heap.
*/
struct Curl
{
alias OutData = void[];
alias InData = ubyte[];
bool stopped;
private static auto ref curl() @property { return CurlAPI.instance(); }
// A handle should not be used by two threads simultaneously
private CURL* handle;
// May also return $(D CURL_READFUNC_ABORT) or $(D CURL_READFUNC_PAUSE)
private size_t delegate(OutData) _onSend;
private size_t delegate(InData) _onReceive;
private void delegate(in char[]) _onReceiveHeader;
private CurlSeek delegate(long,CurlSeekPos) _onSeek;
private int delegate(curl_socket_t,CurlSockType) _onSocketOption;
private int delegate(size_t dltotal, size_t dlnow,
size_t ultotal, size_t ulnow) _onProgress;
alias requestPause = CurlReadFunc.pause;
alias requestAbort = CurlReadFunc.abort;
/**
Initialize the instance by creating a working curl handle.
*/
void initialize()
{
enforce!CurlException(!handle, "Curl instance already initialized");
handle = curl.easy_init();
enforce!CurlException(handle, "Curl instance couldn't be initialized");
stopped = false;
set(CurlOption.nosignal, 1);
}
/**
Duplicate this handle.
The new handle will have all options set as the one it was duplicated
from. An exception to this is that all options that cannot be shared
across threads are reset thereby making it safe to use the duplicate
in a new thread.
*/
Curl dup()
{
Curl copy;
copy.handle = curl.easy_duphandle(handle);
copy.stopped = false;
with (CurlOption) {
auto tt = TypeTuple!(file, writefunction, writeheader,
headerfunction, infile,
readfunction, ioctldata, ioctlfunction,
seekdata, seekfunction, sockoptdata,
sockoptfunction, opensocketdata,
opensocketfunction, noprogress,
progressdata, progressfunction,
debugdata, debugfunction,
interleavedata,
interleavefunction, chunk_data,
chunk_bgn_function, chunk_end_function,
fnmatch_data, fnmatch_function,
cookiejar, postfields);
foreach(option; tt)
copy.clear(option);
}
// The options are only supported by libcurl when it has been built
// against certain versions of OpenSSL - if your libcurl uses an old
// OpenSSL, or uses an entirely different SSL engine, attempting to
// clear these normally will raise an exception
copy.clearIfSupported(CurlOption.ssl_ctx_function);
copy.clearIfSupported(CurlOption.ssh_keydata);
// Enable for curl version > 7.21.7
static if (LIBCURL_VERSION_MAJOR >= 7 &&
LIBCURL_VERSION_MINOR >= 21 &&
LIBCURL_VERSION_PATCH >= 7)
{
copy.clear(CurlOption.closesocketdata);
copy.clear(CurlOption.closesocketfunction);
}
copy.set(CurlOption.nosignal, 1);
// copy.clear(CurlOption.ssl_ctx_data); Let ssl function be shared
// copy.clear(CurlOption.ssh_keyfunction); Let key function be shared
/*
Allow sharing of conv functions
copy.clear(CurlOption.conv_to_network_function);
copy.clear(CurlOption.conv_from_network_function);
copy.clear(CurlOption.conv_from_utf8_function);
*/
return copy;
}
private void _check(CurlCode code)
{
enforce!CurlTimeoutException(code != CurlError.operation_timedout,
errorString(code));
enforce!CurlException(code == CurlError.ok,
errorString(code));
}
private string errorString(CurlCode code)
{
import core.stdc.string : strlen;
auto msgZ = curl.easy_strerror(code);
// doing the following (instead of just using std.conv.to!string) avoids 1 allocation
return format("%s on handle %s", msgZ[0 .. core.stdc.string.strlen(msgZ)], handle);
}
private void throwOnStopped(string message = null)
{
auto def = "Curl instance called after being cleaned up";
enforce!CurlException(!stopped,
message == null ? def : message);
}
/**
Stop and invalidate this curl instance.
Warning: Do not call this from inside a callback handler e.g. $(D onReceive).
*/
void shutdown()
{
throwOnStopped();
stopped = true;
curl.easy_cleanup(this.handle);
this.handle = null;
}
/**
Pausing and continuing transfers.
*/
void pause(bool sendingPaused, bool receivingPaused)
{
throwOnStopped();
_check(curl.easy_pause(this.handle,
(sendingPaused ? CurlPause.send_cont : CurlPause.send) |
(receivingPaused ? CurlPause.recv_cont : CurlPause.recv)));
}
/**
Set a string curl option.
Params:
option = A $(ECXREF curl, CurlOption) as found in the curl documentation
value = The string
*/
void set(CurlOption option, const(char)[] value)
{
throwOnStopped();
_check(curl.easy_setopt(this.handle, option, value.tempCString().buffPtr));
}
/**
Set a long curl option.
Params:
option = A $(ECXREF curl, CurlOption) as found in the curl documentation
value = The long
*/
void set(CurlOption option, long value)
{
throwOnStopped();
_check(curl.easy_setopt(this.handle, option, value));
}
/**
Set a void* curl option.
Params:
option = A $(ECXREF curl, CurlOption) as found in the curl documentation
value = The pointer
*/
void set(CurlOption option, void* value)
{
throwOnStopped();
_check(curl.easy_setopt(this.handle, option, value));
}
/**
Clear a pointer option.
Params:
option = A $(ECXREF curl, CurlOption) as found in the curl documentation
*/
void clear(CurlOption option)
{
throwOnStopped();
_check(curl.easy_setopt(this.handle, option, null));
}
/**
Clear a pointer option. Does not raise an exception if the underlying
libcurl does not support the option. Use sparingly.
Params:
option = A $(ECXREF curl, CurlOption) as found in the curl documentation
*/
void clearIfSupported(CurlOption option)
{
throwOnStopped();
auto rval = curl.easy_setopt(this.handle, option, null);
if (rval != CurlError.unknown_telnet_option)
{
_check(rval);
}
}
/**
perform the curl request by doing the HTTP,FTP etc. as it has
been setup beforehand.
Params:
throwOnError = whether to throw an exception or return a CurlCode on error
*/
CurlCode perform(ThrowOnError throwOnError = ThrowOnError.yes)
{
throwOnStopped();
CurlCode code = curl.easy_perform(this.handle);
if (throwOnError)
_check(code);
return code;
}
// Explicitly undocumented. It will be removed in November 2015.
deprecated("Pass ThrowOnError.yes or .no instead of a boolean.")
CurlCode perform(bool throwOnError)
{
return perform(cast(ThrowOnError)throwOnError);
}
/**
* The event handler that receives incoming data.
*
* Params:
* callback = the callback that receives the $(D ubyte[]) data.
* Be sure to copy the incoming data and not store
* a slice.
*
* Returns:
* The callback returns the incoming bytes read. If not the entire array is
* the request will abort.
* The special value HTTP.pauseRequest can be returned in order to pause the
* current request.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* Curl curl;
* curl.initialize();
* curl.set(CurlOption.url, "http://dlang.org");
* curl.onReceive = (ubyte[] data) { writeln("Got data", to!(const(char)[])(data)); return data.length;};
* curl.perform();
* ----
*/
@property void onReceive(size_t delegate(InData) callback)
{
_onReceive = (InData id)
{
throwOnStopped("Receive callback called on cleaned up Curl instance");
return callback(id);
};
set(CurlOption.file, cast(void*) &this);
set(CurlOption.writefunction, cast(void*) &Curl._receiveCallback);
}
/**
* The event handler that receives incoming headers for protocols
* that uses headers.
*
* Params:
* callback = the callback that receives the header string.
* Make sure the callback copies the incoming params if
* it needs to store it because they are references into
* the backend and may very likely change.
*
* Example:
* ----
* import std.net.curl, std.stdio;
* Curl curl;
* curl.initialize();
* curl.set(CurlOption.url, "http://dlang.org");
* curl.onReceiveHeader = (in char[] header) { writeln(header); };
* curl.perform();
* ----
*/
@property void onReceiveHeader(void delegate(in char[]) callback)
{
_onReceiveHeader = (in char[] od)
{
throwOnStopped("Receive header callback called on "~
"cleaned up Curl instance");
callback(od);
};
set(CurlOption.writeheader, cast(void*) &this);
set(CurlOption.headerfunction,
cast(void*) &Curl._receiveHeaderCallback);
}
/**
* The event handler that gets called when data is needed for sending.
*
* Params:
* callback = the callback that has a $(D void[]) buffer to be filled
*
* Returns:
* The callback returns the number of elements in the buffer that have been
* filled and are ready to send.
* The special value $(D Curl.abortRequest) can be returned in
* order to abort the current request.
* The special value $(D Curl.pauseRequest) can be returned in order to
* pause the current request.
*
* Example:
* ----
* import std.net.curl;
* Curl curl;
* curl.initialize();
* curl.set(CurlOption.url, "http://dlang.org");
*
* string msg = "Hello world";
* curl.onSend = (void[] data)
* {
* auto m = cast(void[])msg;
* size_t length = m.length > data.length ? data.length : m.length;
* if (length == 0) return 0;
* data[0..length] = m[0..length];
* msg = msg[length..$];
* return length;
* };
* curl.perform();
* ----
*/
@property void onSend(size_t delegate(OutData) callback)
{
_onSend = (OutData od)
{
throwOnStopped("Send callback called on cleaned up Curl instance");
return callback(od);
};
set(CurlOption.infile, cast(void*) &this);
set(CurlOption.readfunction, cast(void*) &Curl._sendCallback);
}
/**
* The event handler that gets called when the curl backend needs to seek
* the data to be sent.
*
* Params:
* callback = the callback that receives a seek offset and a seek position
* $(ECXREF curl, CurlSeekPos)
*
* Returns:
* The callback returns the success state of the seeking
* $(ECXREF curl, CurlSeek)
*
* Example:
* ----
* import std.net.curl;
* Curl curl;
* curl.initialize();
* curl.set(CurlOption.url, "http://dlang.org");
* curl.onSeek = (long p, CurlSeekPos sp)
* {
* return CurlSeek.cantseek;
* };
* curl.perform();
* ----
*/
@property void onSeek(CurlSeek delegate(long, CurlSeekPos) callback)
{
_onSeek = (long ofs, CurlSeekPos sp)
{
throwOnStopped("Seek callback called on cleaned up Curl instance");
return callback(ofs, sp);
};
set(CurlOption.seekdata, cast(void*) &this);
set(CurlOption.seekfunction, cast(void*) &Curl._seekCallback);
}
/**
* The event handler that gets called when the net socket has been created
* but a $(D connect()) call has not yet been done. This makes it possible to set
* misc. socket options.
*
* Params:
* callback = the callback that receives the socket and socket type
* $(ECXREF curl, CurlSockType)
*
* Returns:
* Return 0 from the callback to signal success, return 1 to signal error
* and make curl close the socket
*
* Example:
* ----
* import std.net.curl;
* Curl curl;
* curl.initialize();
* curl.set(CurlOption.url, "http://dlang.org");
* curl.onSocketOption = delegate int(curl_socket_t s, CurlSockType t) { /+ do stuff +/ };
* curl.perform();
* ----
*/
@property void onSocketOption(int delegate(curl_socket_t,
CurlSockType) callback)
{
_onSocketOption = (curl_socket_t sock, CurlSockType st)
{
throwOnStopped("Socket option callback called on "~
"cleaned up Curl instance");
return callback(sock, st);
};
set(CurlOption.sockoptdata, cast(void*) &this);
set(CurlOption.sockoptfunction,
cast(void*) &Curl._socketOptionCallback);
}
/**
* The event handler that gets called to inform of upload/download progress.
*
* Params:
* callback = the callback that receives the (total bytes to download,
* currently downloaded bytes, total bytes to upload, currently uploaded
* bytes).
*
* Returns:
* Return 0 from the callback to signal success, return non-zero to abort
* transfer
*
* Example:
* ----
* import std.net.curl;
* Curl curl;
* curl.initialize();
* curl.set(CurlOption.url, "http://dlang.org");
* curl.onProgress = delegate int(size_t dltotal, size_t dlnow, size_t ultotal, size_t uln)
* {
* writeln("Progress: downloaded bytes ", dlnow, " of ", dltotal);
* writeln("Progress: uploaded bytes ", ulnow, " of ", ultotal);
* curl.perform();
* };
* ----
*/
@property void onProgress(int delegate(size_t dlTotal,
size_t dlNow,
size_t ulTotal,
size_t ulNow) callback)
{
_onProgress = (size_t dlt, size_t dln, size_t ult, size_t uln)
{
throwOnStopped("Progress callback called on cleaned "~
"up Curl instance");
return callback(dlt, dln, ult, uln);
};
set(CurlOption.noprogress, 0);
set(CurlOption.progressdata, cast(void*) &this);
set(CurlOption.progressfunction, cast(void*) &Curl._progressCallback);
}
// Internal C callbacks to register with libcurl
extern (C) private static
size_t _receiveCallback(const char* str,
size_t size, size_t nmemb, void* ptr)
{
auto b = cast(Curl*) ptr;
if (b._onReceive != null)
return b._onReceive(cast(InData)(str[0..size*nmemb]));
return size*nmemb;
}
extern (C) private static
size_t _receiveHeaderCallback(const char* str,
size_t size, size_t nmemb, void* ptr)
{
auto b = cast(Curl*) ptr;
auto s = str[0..size*nmemb].chomp();
if (b._onReceiveHeader != null)
b._onReceiveHeader(s);
return size*nmemb;
}
extern (C) private static
size_t _sendCallback(char *str, size_t size, size_t nmemb, void *ptr)
{
Curl* b = cast(Curl*) ptr;
auto a = cast(void[]) str[0..size*nmemb];
if (b._onSend == null)
return 0;
return b._onSend(a);
}
extern (C) private static
int _seekCallback(void *ptr, curl_off_t offset, int origin)
{
auto b = cast(Curl*) ptr;
if (b._onSeek == null)
return CurlSeek.cantseek;
// origin: CurlSeekPos.set/current/end
// return: CurlSeek.ok/fail/cantseek
return b._onSeek(cast(long) offset, cast(CurlSeekPos) origin);
}
extern (C) private static
int _socketOptionCallback(void *ptr,
curl_socket_t curlfd, curlsocktype purpose)
{
auto b = cast(Curl*) ptr;
if (b._onSocketOption == null)
return 0;
// return: 0 ok, 1 fail
return b._onSocketOption(curlfd, cast(CurlSockType) purpose);
}
extern (C) private static
int _progressCallback(void *ptr,
double dltotal, double dlnow,
double ultotal, double ulnow)
{
auto b = cast(Curl*) ptr;
if (b._onProgress == null)
return 0;
// return: 0 ok, 1 fail
return b._onProgress(cast(size_t)dltotal, cast(size_t)dlnow,
cast(size_t)ultotal, cast(size_t)ulnow);
}
}
// Internal messages send between threads.
// The data is wrapped in this struct in order to ensure that
// other std.concurrency.receive calls does not pick up our messages
// by accident.
private struct CurlMessage(T)
{
public T data;
}
private static CurlMessage!T curlMessage(T)(T data)
{
return CurlMessage!T(data);
}
// Pool of to be used for reusing buffers
private struct Pool(Data)
{
private struct Entry
{
Data data;
Entry* next;
}
private Entry* root;
private Entry* freeList;
@safe @property bool empty()
{
return root == null;
}
@safe nothrow void push(Data d)
{
if (freeList == null)
{
// Allocate new Entry since there is no one
// available in the freeList
freeList = new Entry;
}
freeList.data = d;
Entry* oldroot = root;
root = freeList;
freeList = freeList.next;
root.next = oldroot;
}
@safe Data pop()
{
enforce!Exception(root != null, "pop() called on empty pool");
auto d = root.data;
auto n = root.next;
root.next = freeList;
freeList = root;
root = n;
return d;
}
}
// Shared function for reading incoming chunks of data and
// sending the to a parent thread
private static size_t _receiveAsyncChunks(ubyte[] data, ref ubyte[] outdata,
Pool!(ubyte[]) freeBuffers,
ref ubyte[] buffer, Tid fromTid,
ref bool aborted)
{
immutable datalen = data.length;
// Copy data to fill active buffer
while (!data.empty)
{
// Make sure a buffer is present
while ( outdata.empty && freeBuffers.empty)
{
// Active buffer is invalid and there are no
// available buffers in the pool. Wait for buffers
// to return from main thread in order to reuse
// them.
receive((immutable(ubyte)[] buf)
{
buffer = cast(ubyte[])buf;
outdata = buffer[];
},
(bool flag) { aborted = true; }
);
if (aborted) return cast(size_t)0;
}
if (outdata.empty)
{
buffer = freeBuffers.pop();
outdata = buffer[];
}
// Copy data
auto copyBytes = outdata.length < data.length ?
outdata.length : data.length;
outdata[0..copyBytes] = data[0..copyBytes];
outdata = outdata[copyBytes..$];
data = data[copyBytes..$];
if (outdata.empty)
fromTid.send(thisTid, curlMessage(cast(immutable(ubyte)[])buffer));
}
return datalen;
}
// ditto
private static void _finalizeAsyncChunks(ubyte[] outdata, ref ubyte[] buffer,
Tid fromTid)
{
if (!outdata.empty)
{
// Resize the last buffer
buffer.length = buffer.length - outdata.length;
fromTid.send(thisTid, curlMessage(cast(immutable(ubyte)[])buffer));
}
}
// Shared function for reading incoming lines of data and sending the to a
// parent thread
private static size_t _receiveAsyncLines(Terminator, Unit)
(const(ubyte)[] data, ref EncodingScheme encodingScheme,
bool keepTerminator, Terminator terminator,
ref const(ubyte)[] leftOverBytes, ref bool bufferValid,
ref Pool!(Unit[]) freeBuffers, ref Unit[] buffer,
Tid fromTid, ref bool aborted)
{
immutable datalen = data.length;
// Terminator is specified and buffers should be resized as determined by
// the terminator
// Copy data to active buffer until terminator is found.
// Decode as many lines as possible
while (true)
{
// Make sure a buffer is present
while (!bufferValid && freeBuffers.empty)
{
// Active buffer is invalid and there are no available buffers in
// the pool. Wait for buffers to return from main thread in order to
// reuse them.
receive((immutable(Unit)[] buf)
{
buffer = cast(Unit[])buf;
buffer.length = 0;
buffer.assumeSafeAppend();
bufferValid = true;
},
(bool flag) { aborted = true; }
);
if (aborted) return cast(size_t)0;
}
if (!bufferValid)
{
buffer = freeBuffers.pop();
bufferValid = true;
}
// Try to read a line from left over bytes from last onReceive plus the
// newly received bytes.
try
{
if (decodeLineInto(leftOverBytes, data, buffer,
encodingScheme, terminator))
{
if (keepTerminator)
{
fromTid.send(thisTid,
curlMessage(cast(immutable(Unit)[])buffer));
}
else
{
static if (isArray!Terminator)
fromTid.send(thisTid,
curlMessage(cast(immutable(Unit)[])
buffer[0..$-terminator.length]));
else
fromTid.send(thisTid,
curlMessage(cast(immutable(Unit)[])
buffer[0..$-1]));
}
bufferValid = false;
}
else
{
// Could not decode an entire line. Save
// bytes left in data for next call to
// onReceive. Can be up to a max of 4 bytes.
enforce!CurlException(data.length <= 4,
format(
"Too many bytes left not decoded %s"~
" > 4. Maybe the charset specified in"~
" headers does not match "~
"the actual content downloaded?",
data.length));
leftOverBytes ~= data;
break;
}
}
catch (CurlException ex)
{
prioritySend(fromTid, cast(immutable(CurlException))ex);
return cast(size_t)0;
}
}
return datalen;
}
// ditto
private static
void _finalizeAsyncLines(Unit)(bool bufferValid, Unit[] buffer, Tid fromTid)
{
if (bufferValid && buffer.length != 0)
fromTid.send(thisTid, curlMessage(cast(immutable(Unit)[])buffer[0..$]));
}
// Spawn a thread for handling the reading of incoming data in the
// background while the delegate is executing. This will optimize
// throughput by allowing simultaneous input (this struct) and
// output (e.g. AsyncHTTPLineOutputRange).
private static void _spawnAsync(Conn, Unit, Terminator = void)()
{
Tid fromTid = receiveOnly!Tid();
// Get buffer to read into
Pool!(Unit[]) freeBuffers; // Free list of buffer objects
// Number of bytes filled into active buffer
Unit[] buffer;
bool aborted = false;
EncodingScheme encodingScheme;
static if ( !is(Terminator == void))
{
// Only lines reading will receive a terminator
auto terminator = receiveOnly!Terminator();
auto keepTerminator = receiveOnly!bool();
// max number of bytes to carry over from an onReceive
// callback. This is 4 because it is the max code units to
// decode a code point in the supported encodings.
auto leftOverBytes = new const(ubyte)[4];
leftOverBytes.length = 0;
auto bufferValid = false;
}
else
{
Unit[] outdata;
}
// no move semantic available in std.concurrency ie. must use casting.
auto connDup = cast(CURL*)receiveOnly!ulong();
auto client = Conn();
client.p.curl.handle = connDup;
// receive a method for both ftp and http but just use it for http
auto method = receiveOnly!(HTTP.Method)();
client.onReceive = (ubyte[] data)
{
// If no terminator is specified the chunk size is fixed.
static if ( is(Terminator == void) )
return _receiveAsyncChunks(data, outdata, freeBuffers, buffer,
fromTid, aborted);
else
return _receiveAsyncLines(data, encodingScheme,
keepTerminator, terminator, leftOverBytes,
bufferValid, freeBuffers, buffer,
fromTid, aborted);
};
static if ( is(Conn == HTTP) )
{
client.method = method;
// register dummy header handler
client.onReceiveHeader = (in char[] key, in char[] value)
{
if (key == "content-type")
encodingScheme = EncodingScheme.create(client.p.charset);
};
}
else
{
encodingScheme = EncodingScheme.create(client.encoding);
}
// Start the request
CurlCode code;
try
{
code = client.perform(ThrowOnError.no);
}
catch (Exception ex)
{
prioritySend(fromTid, cast(immutable(Exception)) ex);
fromTid.send(thisTid, curlMessage(true)); // signal done
return;
}
if (code != CurlError.ok)
{
if (aborted && (code == CurlError.aborted_by_callback ||
code == CurlError.write_error))
{
fromTid.send(thisTid, curlMessage(true)); // signal done
return;
}
prioritySend(fromTid, cast(immutable(CurlException))
new CurlException(client.p.curl.errorString(code)));
fromTid.send(thisTid, curlMessage(true)); // signal done
return;
}
// Send remaining data that is not a full chunk size
static if ( is(Terminator == void) )
_finalizeAsyncChunks(outdata, buffer, fromTid);
else
_finalizeAsyncLines(bufferValid, buffer, fromTid);
fromTid.send(thisTid, curlMessage(true)); // signal done
}
version (unittest) private auto netAllowed()
{
return environment.get("PHOBOS_TEST_ALLOW_NET") != null;
}
|