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
|
/* $Id: ncbi_http_connector.c,v 6.195 2016/09/08 15:54:13 fukanchi Exp $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Anton Lavrentiev, Denis Vakatov
*
* File Description:
* Implement CONNECTOR for the HTTP-based network connection
*
* See in "ncbi_connector.h" for the detailed specification of the underlying
* connector("CONNECTOR", "SConnectorTag") methods and structures.
*
*/
#include "ncbi_ansi_ext.h"
#include "ncbi_comm.h"
#include "ncbi_priv.h"
#include <connect/ncbi_base64.h>
#include <connect/ncbi_http_connector.h>
#include <ctype.h>
#include <errno.h>
#include <stdlib.h>
#define NCBI_USE_ERRCODE_X Connect_HTTP
/***********************************************************************
* INTERNAL -- Auxiliary types and static functions
***********************************************************************/
/* Connection states, see table below
*/
enum EConnState {
eCS_WriteRequest = 0,
eCS_FlushRequest = 1,
eCS_ReadHeader = 2,
eCS_ReadBody = 4,
eCS_DoneBody = 5, /* NB: |eCS_ReadBody */
eCS_Discard = 7, /* NB: |eCS_DoneBody */
eCS_Eom = 0xF /* NB: |eCS_Discard */
};
typedef unsigned EBConnState; /* packed EConnState */
/* Whether the connector is allowed to connect
* NB: In order to be able to connect, fCC_Once must be set.
*/
enum ECanConnect {
fCC_None, /* 0 */
fCC_Once, /* 1 */
fCC_Unlimited /* 0|2 */
};
typedef unsigned EBCanConnect; /* packed ECanConnect */
typedef unsigned short TBHTTP_Flags; /* packed THTTP_Flags */
typedef unsigned EBSwitch; /* packed ESwitch */
typedef enum {
eEM_Drop, /* 0 */
eEM_Wait, /* 1 */
eEM_Read, /* 2 */
eEM_Flush /* 1|2 */
} EExtractMode;
typedef enum {
eRetry_None = 0, /* 0 */
eRetry_Unused = 1, /* yet */
eRetry_Redirect = 2, /* 2 */
eRetry_Redirect303 = 3, /* 2|1 */
eRetry_Authenticate = 4, /* 4 */
eRetry_ProxyAuthenticate = 5 /* 4|1 */
} ERetry;
typedef struct {
ERetry mode;
const char* data;
} SRetry;
/* All internal data necessary to perform the (re)connect and I/O:
*
* IDLE: sock == NULL AND (can_connect & fCC_Once) [store data in w_buf]
* CONN: otherwise [read from either sock or r_buf]
*
* The following connection states are defined (sock != NULL):
* --------------+--------------------------------------------------
* WriteRequest | HTTP request body is being written
* FlushRequest | HTTP request is being completed and flushed out
* ReadHeader | HTTP response header is being read
* ReadBody | HTTP response body is being read
* DoneBody | HTTP body is all read out of the connection
* Discard | HTTP data (if any) to be discarded
* Eom | HTTP connection is closing
* --------------+--------------------------------------------------
*/
typedef struct {
SConnNetInfo* net_info; /* network configuration parameters */
FHTTP_ParseHeader parse_header; /* callback to parse HTTP reply header */
void* user_data; /* user data handle for callbacks (CB) */
FHTTP_Adjust adjust; /* on-the-fly net_info adjustment CB */
FHTTP_Cleanup cleanup; /* cleanup callback */
TBHTTP_Flags flags; /* as passed to constructor */
EBSwitch unsafe_redir:2; /* if unsafe redirects are allowed */
EBSwitch error_header:2; /* only err.HTTP header on SOME debug */
EBCanConnect can_connect:2; /* whether more connections permitted */
EBConnState conn_state:4; /* connection state per table above */
unsigned auth_done:1; /* website authorization sent */
unsigned proxy_auth_done:1; /* proxy authorization sent */
unsigned skip_host:1; /* do *not* add the "Host:" header tag */
unsigned keepalive:1; /* connection keep-alive */
unsigned chunked:1; /* if writing/reading chunked, HTTP/1.1*/
unsigned entity:1; /* if there's entity payload (body)/1.1*/
unsigned unused:5;
unsigned minor_fault:3; /* incr each minor failure since majo */
unsigned short major_fault; /* incr each major failure since open */
unsigned short http_code; /* last http code response */
SOCK sock; /* socket; NULL if not in "READ" mode */
const STimeout* o_timeout; /* NULL(infinite), dflt or ptr to next */
STimeout oo_timeout; /* storage for (finite) open timeout */
const STimeout* w_timeout; /* NULL(infinite), dflt or ptr to next */
STimeout ww_timeout; /* storage for a (finite) write tmo */
BUF http; /* storage for HTTP reply */
BUF r_buf; /* storage to accumulate input data */
BUF w_buf; /* storage to accumulate output data */
size_t w_len; /* pending message body size */
TNCBI_BigCount expected; /* expected to receive before end/EOF */
TNCBI_BigCount received; /* actually received so far */
} SHttpConnector;
static const char kHttpHostTag[] = "Host: ";
static const STimeout kZeroTimeout = {0, 0};
/* NCBI messaging support */
static int s_MessageIssued = 0;
static FHTTP_NcbiMessageHook s_MessageHook = 0;
/* -1=nothing to do; 0=failure; 1=success */
static int/*tri-state*/ x_Authenticate(SHttpConnector* uuu,
ERetry auth)
{
static const char kProxyAuthorization[] = "Proxy-Authorization: Basic ";
static const char kAuthorization[] = "Authorization: Basic ";
char buf[80+sizeof(uuu->net_info->user)*4], *s;
size_t taglen, userlen, passlen, len, n;
const char *tag, *user, *pass;
switch (auth) {
case eRetry_Authenticate:
if (uuu->auth_done)
return -1/*nothing to do*/;
tag = kAuthorization;
taglen = sizeof(kAuthorization) - 1;
user = uuu->net_info->user;
pass = uuu->net_info->pass;
break;
case eRetry_ProxyAuthenticate:
if (uuu->proxy_auth_done)
return -1/*nothing to do*/;
tag = kProxyAuthorization;
taglen = sizeof(kProxyAuthorization) - 1;
user = uuu->net_info->http_proxy_user;
pass = uuu->net_info->http_proxy_pass;
break;
default:
assert(0);
return 0/*failure*/;
}
assert(tag && user && pass);
if (!*user)
return -1/*nothing to do*/;
if (auth == eRetry_Authenticate)
uuu->auth_done = 1/*true*/;
else
uuu->proxy_auth_done = 1/*true*/;
userlen = strlen(user);
passlen = strlen(pass);
s = buf + sizeof(buf) - passlen;
if (pass[0] == '[' && pass[passlen - 1] == ']') {
if (BASE64_Decode(pass + 1, passlen - 2, &len, s, passlen, &n)
&& len == passlen - 2) {
len = n;
} else
len = 0;
} else
len = 0;
s -= userlen;
memcpy(--s, user, userlen);
s[userlen++] = ':';
if (!len) {
memcpy(s + userlen, pass, passlen);
len = userlen + passlen;
} else
len += userlen;
/* usable room */
userlen = (size_t)(s - buf);
assert(userlen > taglen);
userlen -= taglen + 1;
BASE64_Encode(s, len, &n, buf + taglen, userlen, &passlen, 0);
if (len != n || buf[taglen + passlen])
return 0/*failure*/;
memcpy(buf, tag, taglen);
return ConnNetInfo_OverrideUserHeader(uuu->net_info, buf);
}
static int/*bool*/ x_UnsafeRedirectOK(SHttpConnector* uuu)
{
if (uuu->unsafe_redir == eDefault) {
if (!(uuu->flags & fHTTP_UnsafeRedirects)) {
char val[32];
const char* dflt = NULL;
if (uuu->net_info->scheme == eURL_Https
&& (strspn(uuu->net_info->host, "0123456789.")
== strlen(uuu->net_info->host))) {
dflt = "TRUE";
}
ConnNetInfo_GetValue(0, "HTTP_UNSAFE_REDIRECTS",
val, sizeof(val), dflt);
uuu->unsafe_redir = ConnNetInfo_Boolean(val) ? eOn : eOff;
} else
uuu->unsafe_redir = eOn;
}
return uuu->unsafe_redir == eOn ? 1/*true*/ : 0/*false*/;
}
#ifdef __GNUC__
inline
#endif /*__GNUC__*/
static int/*bool*/ x_IsWriteThru(const SHttpConnector* uuu)
{
return uuu->net_info->version && (uuu->flags & fHTTP_WriteThru)
? 1/*true*/ : 0/*false*/;
}
/* -1=prohibited; 0=okay; 1=failure */
static int/*bool tri-state inverted*/ x_RetryAuth(SHttpConnector* uuu,
const SRetry* retry)
{
int result;
switch (retry->mode) {
case eRetry_Authenticate:
if (uuu->net_info->scheme != eURL_Https
&& !x_UnsafeRedirectOK(uuu)) {
return -1/*prohibited*/;
}
break;
case eRetry_ProxyAuthenticate:
if (!uuu->net_info->http_proxy_host[0] ||
!uuu->net_info->http_proxy_port) {
return -1/*prohibited*/;
}
break;
default:
assert(0);
return 1/*failed*/;
}
result = x_Authenticate(uuu, retry->mode);
return result < 0 ? 1/*failed*/ : !result/*done*/;
}
/* Try to fix connection parameters (called for an unconnected connector) */
static EIO_Status s_Adjust(SHttpConnector* uuu,
const SRetry* retry,
EExtractMode extract)
{
EIO_Status status;
const char* msg;
assert(!retry || !retry->data || *retry->data);
assert(!uuu->sock && uuu->can_connect != fCC_None);
if (!retry || !retry->mode || uuu->minor_fault > 5) {
uuu->minor_fault = 0;
uuu->major_fault++;
} else
uuu->minor_fault++;
if (uuu->major_fault >= uuu->net_info->max_try) {
msg = extract != eEM_Drop && uuu->major_fault > 1
? "[HTTP%s%s] Too many failed attempts (%hu), giving up" : "";
} else if (retry && retry->mode) {
char* url = ConnNetInfo_URL(uuu->net_info);
int secure = 0/*false(yet)*/;
int fail = 0;
switch (retry->mode) {
case eRetry_Redirect:
if (uuu->entity)
fail = -2;
/*FALLTHRU*/
case eRetry_Redirect303:
if (!fail && uuu->net_info->req_method == eReqMethod_Connect)
fail = 2;
else if (!fail && retry->data && *retry->data != '?') {
if (uuu->net_info->req_method != eReqMethod_Post
|| retry->mode == eRetry_Redirect303
|| x_UnsafeRedirectOK(uuu)
|| !(x_IsWriteThru(uuu) || BUF_Size(uuu->w_buf))) {
char host[sizeof(uuu->net_info->host)];
unsigned short port = uuu->net_info->port;
strcpy(host, uuu->net_info->host);
if (uuu->net_info->scheme == eURL_Https)
secure = 1/*true*/;
uuu->net_info->args[0] = '\0'/*arguments not inherited*/;
fail = !ConnNetInfo_ParseURL(uuu->net_info, retry->data);
if (!fail) {
if (secure && uuu->net_info->scheme != eURL_Https
&& !x_UnsafeRedirectOK(uuu)) {
fail = -1;
} else {
if (port != uuu->net_info->port ||
strcasecmp(uuu->net_info->host, host) != 0) {
/* drop the flag on host / port replaced */
uuu->skip_host = 0/*false*/;
}
if (retry->mode == eRetry_Redirect303) {
if (uuu->net_info->req_method ==
eReqMethod_Post) {
uuu->net_info->req_method =
eReqMethod_Get;
} else
fail = -2;
}
if (!fail && (uuu->flags & fHTTP_AdjustOnRedirect)
&& uuu->adjust
&& !uuu->adjust(uuu->net_info,
uuu->user_data, 0)) {
fail = 1;
}
}
}
} else
fail = -1 - x_IsWriteThru(uuu);
} else if (!fail)
fail = 1;
if (fail) {
CORE_LOGF_X(2, eLOG_Error,
("[HTTP%s%s] %s %s%s to %s%s%s",
url ? "; " : "",
url ? url : "",
fail < -1 ? "Invalid" :
fail < 0 ? "Prohibited" :
fail > 1 ? "Spurious tunnel" : "Cannot",
fail == -1 && secure ? "insecure " : "",
fail > 1 || retry->mode != eRetry_Redirect303
? "redirect" : "submission",
retry->data ? "\"" : "<",
retry->data ? retry->data : "NULL",
retry->data ? "\"" : ">"));
status = fail > 1 ? eIO_NotSupported : eIO_Closed;
} else {
CORE_LOGF_X(17, eLOG_Trace,
("[HTTP%s%s] %s \"%s\"",
url ? "; " : "",
url ? url : "",
retry->mode == eRetry_Redirect303
? "Finishing submission with" : "Redirecting to",
retry->data));
status = eIO_Success;
}
break;
case eRetry_Authenticate:
if (uuu->net_info->req_method == eReqMethod_Connect)
fail = 3;
/*FALLTHRU*/
case eRetry_ProxyAuthenticate:
if (!fail) {
if (!retry->data
|| strncasecmp(retry->data, "basic",
strcspn(retry->data, " \t")) != 0) {
fail = -2;
} else if (!(fail = x_RetryAuth(uuu, retry))
&& x_IsWriteThru(uuu)) {
fail = 2;
}
}
if (fail) {
CORE_LOGF_X(3, eLOG_Error,
("[HTTP%s%s] %s %s %c%s%c",
url ? "; " : "",
url ? url : "",
retry->mode == eRetry_Authenticate
? "Authorization" : "Proxy authorization",
fail > 2 ? "not allowed with CONNECT" :
fail < -1 ? "not implemented" :
fail > 1 ? "must be pushed with write-through" :
fail < 0 ? "prohibited" : "failed",
"(["[!retry->data],
retry->data ? retry->data : "NULL",
")]"[!retry->data]));
status = fail < 0 ? eIO_NotSupported : eIO_Closed;
} else {
CORE_LOGF_X(18, eLOG_Trace,
("[HTTP%s%s] Authorizing%s",
url ? "; " : "",
url ? url : "",
retry->mode == eRetry_Authenticate
? "" : " proxy"));
status = eIO_Success;
}
break;
default:
CORE_LOGF_X(4, eLOG_Critical,
("[HTTP%s%s] Unknown retry mode #%u",
url ? "; " : "",
url ? url : "", (unsigned int) retry->mode));
status = eIO_Unknown;
assert(0);
break;
}
if (url)
free(url);
if (status != eIO_Success)
uuu->can_connect = fCC_None;
return status;
} else if (uuu->adjust && !uuu->adjust(uuu->net_info,
uuu->user_data,
uuu->major_fault)) {
msg = extract != eEM_Drop && uuu->major_fault > 1
? "[HTTP%s%s] Retry attempts (%hu) exhausted, giving up" : "";
} else
return eIO_Success;
assert(msg);
if (*msg) {
char* url = ConnNetInfo_URL(uuu->net_info);
CORE_LOGF_X(1, eLOG_Error,
(msg,
url ? "; " : "",
url ? url : "", uuu->major_fault));
if (url)
free(url);
}
uuu->can_connect = fCC_None;
return eIO_Closed;
}
static char* x_HostPort(size_t reserve, const char* host, unsigned short xport)
{
size_t hostlen = strlen(host), portlen;
char* hostport, port[16];
if (!xport) {
portlen = 1;
port[0] = '\0';
} else
portlen = (size_t) sprintf(port, ":%hu", xport) + 1;
hostport = (char*) malloc(reserve + hostlen + portlen);
if (hostport) {
memcpy(hostport + reserve, host, hostlen);
hostlen += reserve;
memcpy(hostport + hostlen, port, portlen);
}
return hostport;
}
static int/*bool*/ x_SetHttpHostTag(SConnNetInfo* net_info)
{
char* tag;
int/*bool*/ retval;
tag = x_HostPort(sizeof(kHttpHostTag)-1, net_info->host, net_info->port);
if (tag) {
memcpy(tag, kHttpHostTag, sizeof(kHttpHostTag)-1);
retval = ConnNetInfo_OverrideUserHeader(net_info, tag);
free(tag);
} else
retval = 0/*failure*/;
return retval;
}
static void x_SetRequestIDs(SConnNetInfo* net_info)
{
char* id = CORE_GetNcbiRequestID(eNcbiRequestID_SID);
assert(!id || *id);
if (id) {
char* tag;
size_t len = strlen(id);
if (!(tag = (char*) realloc(id, ++len + sizeof(HTTP_NCBI_SID)))) {
ConnNetInfo_DeleteUserHeader(net_info, HTTP_NCBI_SID);
free(id);
} else {
memmove(tag + sizeof(HTTP_NCBI_SID), tag, len);
memcpy (tag, HTTP_NCBI_SID, sizeof(HTTP_NCBI_SID) - 1);
tag[sizeof(HTTP_NCBI_SID) - 1] = ' ';
ConnNetInfo_OverrideUserHeader(net_info, tag);
free(tag);
}
}
id = CORE_GetNcbiRequestID(eNcbiRequestID_HitID);
assert(!id || *id);
if (id) {
char* tag;
size_t len = strlen(id);
if (!(tag = (char*) realloc(id, ++len + sizeof(HTTP_NCBI_PHID)))) {
ConnNetInfo_DeleteUserHeader(net_info, HTTP_NCBI_PHID);
free(id);
} else {
memmove(tag + sizeof(HTTP_NCBI_PHID), tag, len);
memcpy (tag, HTTP_NCBI_PHID, sizeof(HTTP_NCBI_PHID) - 1);
tag[sizeof(HTTP_NCBI_PHID) - 1] = ' ';
ConnNetInfo_OverrideUserHeader(net_info, tag);
free(tag);
}
}
}
/* Connect to the HTTP server, specified by uuu->net_info's "port:host".
* Return eIO_Success only if socket connection has succeeded and uuu->sock
* is non-zero. If unsuccessful, try to adjust uuu->net_info by s_Adjust(),
* and then re-try the connection attempt.
*/
static EIO_Status s_Connect(SHttpConnector* uuu,
const STimeout* timeout,
EExtractMode extract)
{
EIO_Status status;
SOCK sock;
assert(!uuu->sock);
uuu->http_code = 0;
if (!(uuu->can_connect & fCC_Once)) {
if (extract == eEM_Read && uuu->net_info->max_try
&& uuu->can_connect == fCC_None) {
char* url = ConnNetInfo_URL(uuu->net_info);
CORE_LOGF_X(5, eLOG_Critical,
("[HTTP%s%s] Connector is no longer usable",
url ? "; " : "",
url ? url : ""));
if (url)
free(url);
}
return eIO_Closed;
}
uuu->entity = 0;
/* the re-try loop... */
for (;;) {
TSOCK_Flags flags
= (uuu->net_info->debug_printout == eDebugPrintout_Data
? fSOCK_KeepAlive | fSOCK_LogOn
: fSOCK_KeepAlive | fSOCK_LogDefault);
sock = 0;
uuu->chunked = 0;
if (uuu->net_info->req_method != eReqMethod_Connect
&& uuu->net_info->scheme == eURL_Https
&& uuu->net_info->http_proxy_host[0]
&& uuu->net_info->http_proxy_port) {
SConnNetInfo* net_info = ConnNetInfo_Clone(uuu->net_info);
if (!net_info) {
status = eIO_Unknown;
break;
}
net_info->scheme = eURL_Http;
net_info->user[0] = '\0';
net_info->pass[0] = '\0';
if (net_info->port == 0)
net_info->port = CONN_PORT_HTTPS;
net_info->firewall = 0/*false*/;
ConnNetInfo_DeleteUserHeader(net_info, kHttpHostTag);
status = HTTP_CreateTunnel(net_info, fHTTP_NoUpread, &sock);
assert((status == eIO_Success) ^ !sock);
ConnNetInfo_Destroy(net_info);
} else
status = eIO_Success;
if (status == eIO_Success) {
EReqMethod req_method = uuu->net_info->req_method;
int/*bool*/ reset_user_header;
char* http_user_header;
const char* host;
unsigned short port;
char* path;
char* args;
char* temp;
size_t len;
/* RFC7230 now requires Host: for CONNECT as well */
if (!uuu->skip_host && !x_SetHttpHostTag(uuu->net_info)) {
status = eIO_Unknown;
break;
}
if (x_IsWriteThru(uuu)) {
assert(req_method != eReqMethod_Connect);
if (req_method == eReqMethod_Any)
req_method = BUF_Size(uuu->w_buf)
? eReqMethod_Post : eReqMethod_Get;
if (req_method != eReqMethod_Head &&
req_method != eReqMethod_Get) {
if (!ConnNetInfo_OverrideUserHeader
(uuu->net_info, "Transfer-Encoding: chunked")) {
status = eIO_Unknown;
break;
}
uuu->chunked = 1;
}
len = 0;
} else
len = BUF_Size(uuu->w_buf);
if (req_method == eReqMethod_Connect
|| (uuu->net_info->scheme != eURL_Https
&& uuu->net_info->http_proxy_host[0]
&& uuu->net_info->http_proxy_port)) {
if (uuu->net_info->http_push_auth
&& !x_Authenticate(uuu, eRetry_ProxyAuthenticate)) {
status = eIO_Unknown;
break;
}
host = uuu->net_info->http_proxy_host;
port = uuu->net_info->http_proxy_port;
path = ConnNetInfo_URL(uuu->net_info);
if (!path) {
status = eIO_Unknown;
break;
}
if (req_method == eReqMethod_Connect) {
/* Tunnel */
assert(!uuu->net_info->version);
if (!len) {
args = 0;
} else if (!(temp = (char*) malloc(len))
|| BUF_Peek(uuu->w_buf, temp, len) != len) {
if (temp)
free(temp);
status = eIO_Unknown;
free(path);
break;
} else
args = temp;
} else {
/* Proxied HTTP */
assert(uuu->net_info->scheme == eURL_Http);
if (uuu->flags & fHCC_UrlEncodeArgs) {
/* args added to path not valid(unencoded), remove */
if ((temp = strchr(path, '?')) != 0)
*temp = '\0';
args = uuu->net_info->args;
} else
args = 0;
}
} else {
/* Direct HTTP[S] or tunneled HTTPS */
if (uuu->net_info->http_push_auth
&& (uuu->net_info->scheme == eURL_Https
|| x_UnsafeRedirectOK(uuu))
&& !x_Authenticate(uuu, eRetry_Authenticate)) {
status = eIO_Unknown;
break;
}
host = uuu->net_info->host;
port = uuu->net_info->port;
path = uuu->net_info->path;
args = uuu->net_info->args;
}
/* encode args (obsolete feature) */
if (req_method != eReqMethod_Connect
&& args && (uuu->flags & fHCC_UrlEncodeArgs)) {
size_t args_len = strcspn(args, "#");
assert(args == uuu->net_info->args);
if (args_len > 0) {
size_t rd_len, wr_len;
size_t size = args_len * 3;
if (!(temp = (char*) malloc(size + 1))) {
int error = errno;
temp = ConnNetInfo_URL(uuu->net_info);
CORE_LOGF_ERRNO_X(20, eLOG_Error, error,
("[HTTP%s%s] Out of memory encoding"
" URL arguments (%lu bytes)",
temp ? "; " : "",
temp ? temp : "",
(unsigned long)(size + 1)));
if (temp)
free(temp);
if (path != uuu->net_info->path)
free(path);
status = eIO_Unknown;
break;
}
URL_Encode(args, args_len, &rd_len, temp, size, &wr_len);
assert(rd_len == args_len);
assert(wr_len <= size);
temp[wr_len] = '\0';
args = temp;
} else
args = 0;
}
/* NCBI request IDs */
if (!(uuu->flags & fHTTP_NoAutomagicSID))
x_SetRequestIDs(uuu->net_info);
/* identify the connector in the User-Agent: header tag */
http_user_header = (uuu->net_info->http_user_header
? strdup(uuu->net_info->http_user_header)
: 0);
if (!uuu->net_info->http_user_header == !http_user_header) {
ConnNetInfo_ExtendUserHeader
(uuu->net_info, "User-Agent: NCBIHttpConnector"
#ifdef NCBI_CXX_TOOLKIT
" (CXX Toolkit)"
#else
" (C Toolkit)"
#endif /*NCBI_CXX_TOOLKIT*/
);
reset_user_header = 1;
} else
reset_user_header = 0;
if (uuu->net_info->debug_printout)
ConnNetInfo_Log(uuu->net_info, eLOG_Note, CORE_GetLOG());
/* connect & send HTTP header */
if (uuu->net_info->scheme == eURL_Https)
flags |= fSOCK_Secure;
if (!(uuu->flags & fHTTP_NoUpread))
flags |= fSOCK_ReadOnWrite;
status = URL_ConnectEx(host, port, path, args,
req_method | (uuu->net_info->version
? eReqMethod_v1
: 0), len,
uuu->o_timeout, timeout,
uuu->net_info->http_user_header,
uuu->net_info->credentials,
flags, &sock);
if (reset_user_header) {
ConnNetInfo_SetUserHeader(uuu->net_info, 0);
uuu->net_info->http_user_header = http_user_header;
}
if (path != uuu->net_info->path)
free(path);
if (args != uuu->net_info->args && args)
free(args);
if (sock) {
assert(status == eIO_Success);
uuu->w_len = req_method != eReqMethod_Connect
? BUF_Size(uuu->w_buf) : 0;
break;
}
} else
assert(!sock);
assert(status != eIO_Success);
/* connection failed, try another server */
if (s_Adjust(uuu, 0, extract) != eIO_Success)
break;
}
if (status == eIO_Success) {
uuu->conn_state = eCS_WriteRequest;
uuu->sock = sock;
assert(sock);
} else if (sock) {
SOCK_Abort(sock);
SOCK_Close(sock);
}
return status;
}
/* Unconditionally drop the connection w/o any wait */
static void s_DropConnection(SHttpConnector* uuu)
{
assert(uuu->sock);
if (!(uuu->conn_state & eCS_ReadBody) || uuu->conn_state == eCS_Discard)
SOCK_Abort(uuu->sock);
else
SOCK_SetTimeout(uuu->sock, eIO_Close, &kZeroTimeout);
SOCK_Close(uuu->sock);
uuu->sock = 0;
}
typedef struct {
SOCK sock;
EIO_Status status;
} XBUF_PeekCBCtx;
static size_t x_WriteBuf(void* data, const void* buf, size_t size)
{
XBUF_PeekCBCtx* ctx = (XBUF_PeekCBCtx*) data;
size_t written;
assert(buf && size);
if (ctx->status != eIO_Success)
return 0;
ctx->status = SOCK_Write(ctx->sock, buf, size,
&written, eIO_WritePlain);
return written;
}
/* Connect to the server specified by uuu->net_info, then compose and form
* relevant HTTP header, and flush the accumulated output data(uuu->w_buf)
* after the HTTP header.
* If connection/write unsuccessful, retry to reconnect and send the data
* again until permitted by s_Adjust().
*/
static EIO_Status s_ConnectAndSend(SHttpConnector* uuu,
const STimeout* timeout,
EExtractMode extract)
{
EIO_Status status;
for (;;) {
char buf[80];
int error;
size_t off;
char* url;
if (uuu->sock)
status = eIO_Success;
else if ((status = s_Connect(uuu, timeout, extract)) != eIO_Success)
break;
if (uuu->w_len) {
XBUF_PeekCBCtx ctx;
ctx.sock = uuu->sock;
ctx.status = eIO_Success/*NB:==status*/;
off = BUF_Size(uuu->w_buf) - uuu->w_len;
assert(uuu->conn_state < eCS_ReadHeader);
SOCK_SetTimeout(ctx.sock, eIO_Write, uuu->w_timeout);
uuu->w_len -= BUF_PeekAtCB(uuu->w_buf, off,
x_WriteBuf, &ctx, uuu->w_len);
status = ctx.status;
} else
off = 0;
if (status == eIO_Success) {
if (uuu->w_len)
continue;
if (uuu->conn_state > eCS_FlushRequest)
break;
if (!uuu->chunked)
uuu->conn_state = eCS_FlushRequest;
if (uuu->conn_state == eCS_FlushRequest) {
/* "flush" */
status = SOCK_Write(uuu->sock, 0, 0, 0, eIO_WritePlain);
if (status == eIO_Success) {
uuu->conn_state = eCS_ReadHeader;
uuu->keepalive = 0/*uuu->net_info->version*/;
uuu->expected = (TNCBI_BigCount)(-1L);
uuu->received = 0;
uuu->chunked = 0;
BUF_Erase(uuu->http);
break;
}
} else
break;
}
if (status == eIO_Timeout
&& (extract == eEM_Wait
|| (timeout && !(timeout->sec | timeout->usec)))) {
break;
}
error = errno;
if (uuu->w_len && uuu->conn_state == eCS_WriteRequest) {
if (!x_IsWriteThru(uuu)) {
sprintf(buf, "write request body at offset %lu",
(unsigned long) off);
} else
strcpy(buf, "write request body");
} else {
if (uuu->w_len)
strcpy(buf, "finalize request body");
else
strcpy(buf, "finalize request");
}
url = ConnNetInfo_URL(uuu->net_info);
CORE_LOGF_ERRNO_X(6, eLOG_Error, error,
("[HTTP%s%s] Cannot %s (%s)",
url ? "; " : "",
url ? url : "", buf, IO_StatusStr(status)));
if (url)
free(url);
/* write failed; close and try to use another server, if possible */
s_DropConnection(uuu);
assert(status != eIO_Success);
if ((status = s_Adjust(uuu, 0, extract)) != eIO_Success)
break/*closed*/;
}
return status;
}
static int/*bool*/ x_IsValidParam(const char* param, size_t paramlen)
{
const char* e = (const char*) memchr(param, '=', paramlen);
size_t len;
if (!e || e == param)
return 0/*false*/;
if ((len = (size_t)(++e - param)) >= paramlen)
return 0/*false*/;
assert(!isspace((unsigned char)(*param)));
if (strcspn(param, " \t") < len)
return 0/*false*/;
if (*e == '\'' || *e == '"') {
/* a quoted string */
assert(len < paramlen);
len = paramlen - len;
if (!(e = (const char*) memchr(e + 1, *e, --len)))
return 0/*false*/;
e++/*skip the quote*/;
} else
e += strcspn(e, " \t");
if (e != param + paramlen && e + strspn(e, " \t") != param + paramlen)
return 0/*false*/;
return 1/*true*/;
}
static int/*bool*/ x_IsValidChallenge(const char* text, size_t len)
{
/* Challenge must contain a scheme name token and a non-empty param
* list (comma-separated pairs token={token|quoted_string}), with at
* least one parameter being named "realm=".
*/
size_t word = strcspn(text, " \t");
int retval = 0/*false*/;
if (word < len) {
/* 1st word is always the scheme name */
const char* param = text + word;
for (param += strspn(param, " \t"); param < text + len;
param += strspn(param, ", \t")) {
size_t paramlen = (size_t)(text + len - param);
const char* c = (const char*) memchr(param, ',', paramlen);
if (c)
paramlen = (size_t)(c - param);
if (!x_IsValidParam(param, paramlen))
return 0/*false*/;
if (paramlen > 6 && strncasecmp(param, "realm=", 6) == 0)
retval = 1/*true, but keep scanning*/;
param += c ? ++paramlen : paramlen;
}
}
return retval;
}
static size_t x_PushbackBuf(void* data, const void* buf, size_t size)
{
XBUF_PeekCBCtx* ctx = (XBUF_PeekCBCtx*) data;
assert(buf && size);
if (ctx->status == eIO_Success)
ctx->status = SOCK_Pushback(ctx->sock, buf, size);
return ctx->status != eIO_Success ? 0 : size;
}
static int/*bool*/ x_Pushback(SOCK sock, BUF buf)
{
size_t size = BUF_Size(buf);
XBUF_PeekCBCtx ctx;
ctx.sock = sock;
ctx.status = eIO_Success;
size ^= BUF_PeekAtCB(buf, 0, x_PushbackBuf, &ctx, size);
BUF_Destroy(buf);
return size ? 0 : 1;
}
static EIO_Status x_ReadChunkHead(SHttpConnector* uuu, int/*bool*/ first)
{
int n;
BUF buf;
char* str;
size_t size;
TNCBI_BigCount chunk;
EIO_Status status;
buf = 0;
str = 0;
size = 0;
for (;;) {
size_t off;
if (size > 2) {
if (!(str = (char*) malloc(size + 1)))
break;
verify(BUF_Peek(buf, str, size) == size);
if (!first && (str[0] != '\r' || str[1] != '\n')) {
free(str);
str = 0;
break;
}
assert(str[size - 1] == '\n');
str[size] = '\0';
break;
}
status = SOCK_StripToPattern(uuu->sock, "\r\n", 2, &buf, &off);
if (status != eIO_Success || (size += off) != BUF_Size(buf))
break;
}
if (!str
|| sscanf(str, "%" NCBI_BIGCOUNT_FORMAT_SPEC_HEX "%n", &chunk, &n) < 1
|| (!isspace((unsigned char) str[n]) && str[n] != ';')) {
char* url = ConnNetInfo_URL(uuu->net_info);
CORE_LOGF_X(23, eLOG_Error,
("[HTTP%s%s] Cannot read chunk size%s%.*s",
url ? "; " : "",
url ? url : "",
str ? ": " : "",
str ? (int)(size - (first ? 2 : 4)) : 0,
str ? str + (first ? 0 : 2) : ""));
if (url)
free(url);
if (str) {
free(str);
BUF_Destroy(buf);
return eIO_Closed;
}
return x_Pushback(uuu->sock, buf) ? eIO_Unknown : eIO_Closed;
}
free(str);
uuu->expected = chunk;
uuu->received = 0;
BUF_Destroy(buf);
return eIO_Success;
}
static EIO_Status x_ReadChunkTail(SHttpConnector* uuu)
{
EIO_Status status;
BUF buf = 0;
do {
size_t n;
status = SOCK_StripToPattern(uuu->sock, "\r\n", 2, &buf, &n);
if (n == 2) {
/*last trailer*/
BUF_Destroy(buf);
uuu->conn_state = eCS_Discard;
return eIO_Closed;
}
} while (status == eIO_Success);
return x_Pushback(uuu->sock, buf) ? status : eIO_Closed;
}
/* If "size"==0, then "buf" is a pointer to a BUF to receive the current body.
* Otherwise, "buf" is a non-NULL destination buffer.
*/
static EIO_Status s_ReadData(SHttpConnector* uuu,
void* buf, size_t size,
size_t* n_read, EIO_ReadMethod how)
{
BUF* xxx;
EIO_Status status;
assert(buf && n_read && !*n_read);
if (!uuu->chunked || uuu->expected > uuu->received) {
if (!size) {
size = uuu->expected != (TNCBI_BigCount)(-1L)
? uuu->expected - uuu->received
: 4096;
if (!size) {
assert(!uuu->chunked);
uuu->conn_state = eCS_DoneBody;
return eIO_Closed;
}
if (size > 2 * 4096)
size = 2 * 4096;
xxx = (BUF*) buf;
if (!(buf = (void*) malloc(size))) {
int error = errno;
char* url = ConnNetInfo_URL(uuu->net_info);
CORE_LOGF_ERRNO_X(24, eLOG_Error, error,
("[HTTP%s%s] Cannot allocate response chunk"
" (%lu byte%s)",
url ? "; " : "",
url ? url : "",
(unsigned long) size, &"s"[size == 1]));
if (url)
free(url);
return eIO_Unknown;
}
} else if (uuu->chunked) {
assert(uuu->expected != (TNCBI_BigCount)(-1L));
if (size > uuu->expected - uuu->received)
size = uuu->expected - uuu->received;
xxx = 0;
} else if (uuu->expected == uuu->received) {
uuu->conn_state = eCS_DoneBody;
return eIO_Closed;
} else
xxx = 0;
status = SOCK_Read(uuu->sock, buf, size, n_read, how);
if (xxx && !BUF_AppendEx(xxx, buf, size, buf, *n_read)) {
int error = errno;
char* url = ConnNetInfo_URL(uuu->net_info);
CORE_LOGF_ERRNO_X(25, eLOG_Error, error,
("[HTTP%s%s] Cannot collect response body",
url ? "; " : "",
url ? url : ""));
if (url)
free(url);
free(buf);
status = eIO_Unknown;
}
return status;
}
if ((status = x_ReadChunkHead(uuu, !uuu->expected)) != eIO_Success)
return status;
if (uuu->expected) {
assert(uuu->expected != (TNCBI_BigCount)(-1L) && !uuu->received);
if (size > uuu->expected)
size = uuu->expected;
return s_ReadData(uuu, buf, size, n_read, how);
}
uuu->conn_state = eCS_DoneBody;
return x_ReadChunkTail(uuu);
}
static int/*bool*/ x_IsErrorHeader(SHttpConnector* uuu)
{
if (uuu->error_header == eDefault) {
char val[32];
ConnNetInfo_GetValue(0, "HTTP_ERROR_HEADER_ONLY", val, sizeof(val), 0);
uuu->error_header = ConnNetInfo_Boolean(val) ? eOn : eOff;
}
return uuu->error_header == eOn ? 1/*true*/ : 0/*false*/;
}
/* Read and parse HTTP header */
static EIO_Status s_ReadHeader(SHttpConnector* uuu,
SRetry* retry,
EExtractMode extract)
{
enum EHTTP_Tag {
eHTTP_NcbiMsg = 1 << 0,
eHTTP_NcbiSid = 1 << 1,
eHTTP_Location = 1 << 2,
eHTTP_Connection = 1 << 3,
eHTTP_Authenticate = 1 << 4,
eHTTP_ContentLength = 1 << 5,
eHTTP_TransferEncoding = 1 << 6
};
typedef unsigned short THTTP_Tags; /* Bitwise-OR of EHTTP_Tag */
char* url = 0, *hdr, *s;
EHTTP_HeaderParse header_parse;
int http_code;
size_t size, n;
EIO_Status status;
int fatal;
THTTP_Tags tags;
assert(uuu->sock && uuu->conn_state == eCS_ReadHeader);
memset(retry, 0, sizeof(*retry));
/*retry->mode = eRetry_None;
retry->data = 0;*/
/* line by line HTTP header input */
for (;;) {
/* do we have full header yet? */
if ((size = BUF_Size(uuu->http)) >= 4) {
if (!(hdr = (char*) malloc(size + 1))) {
int error = errno;
assert(!url);
url = ConnNetInfo_URL(uuu->net_info);
CORE_LOGF_ERRNO_X(7, eLOG_Error, error,
("[HTTP%s%s] Cannot allocate header"
" (%lu bytes)",
url ? "; " : "",
url ? url : "",
(unsigned long) size));
if (url)
free(url);
return eIO_Unknown;
}
verify(BUF_Peek(uuu->http, hdr, size) == size);
if (memcmp(&hdr[size - 4], "\r\n\r\n", 4) == 0) {
/* full header captured */
hdr[size] = '\0';
break;
}
free(hdr);
}
status = SOCK_StripToPattern(uuu->sock, "\r\n", 2, &uuu->http, &n);
if (status != eIO_Success || size + n != BUF_Size(uuu->http)) {
ELOG_Level level;
if (status == eIO_Timeout) {
const STimeout* tmo = SOCK_GetTimeout(uuu->sock, eIO_Read);
if (!tmo)
level = eLOG_Error;
else if (extract == eEM_Wait)
return status;
else if (tmo->sec | tmo->usec)
level = eLOG_Warning;
else
level = eLOG_Trace;
} else
level = eLOG_Error;
assert(!url);
url = ConnNetInfo_URL(uuu->net_info);
CORE_LOGF_X(8, level,
("[HTTP%s%s] Cannot %s header (%s)",
url ? "; " : "",
url ? url : "", status != eIO_Success
? "read" : "scan",
IO_StatusStr(status != eIO_Success
? status : eIO_Unknown)));
if (url)
free(url);
return status != eIO_Success ? status : eIO_Unknown;
}
}
/* the entire header has been read */
uuu->conn_state = eCS_ReadBody;
BUF_Erase(uuu->http);
/* HTTP status must come on the first line of the response */
fatal = 0/*false*/;
if (sscanf(hdr, "HTTP/%*d.%*d %d ", &http_code) != 1 || !http_code)
http_code = -1;
uuu->http_code = http_code;
if (http_code < 200 || 299 < http_code) {
if (http_code == 301 || http_code == 302 || http_code == 307)
retry->mode = eRetry_Redirect;
else if (http_code == 303)
retry->mode = eRetry_Redirect303;
else if (http_code == 401)
retry->mode = eRetry_Authenticate;
else if (http_code == 407)
retry->mode = eRetry_ProxyAuthenticate;
else if (http_code <= 0 ||
http_code == 400 || http_code == 403 ||
http_code == 404 || http_code == 405 ||
http_code == 406 || http_code == 410) {
fatal = 1/*true*/;
}
} else
http_code = 0/*no server error*/;
if (uuu->net_info->debug_printout == eDebugPrintout_Some
&& (http_code || !x_IsErrorHeader(uuu))) {
/* HTTP header gets printed as part of data logging when
uuu->net_info->debug_printout == eDebugPrintout_Data. */
const char* header_header;
if (!http_code)
header_header = "HTTP header";
else if (fatal)
header_header = "HTTP header (fatal)";
else if (uuu->flags & fHTTP_KeepHeader)
header_header = "HTTP header (error)";
else if (retry->mode == eRetry_Redirect)
header_header = "HTTP header (redirect)";
else if (retry->mode == eRetry_Redirect303)
header_header = "HTTP header (see other)";
else if (retry->mode & eRetry_Authenticate)
header_header = "HTTP header (authentication)";
else if (retry->mode)
header_header = 0, assert(0);
else
header_header = "HTTP header (retriable server error)";
assert(!url);
url = ConnNetInfo_URL(uuu->net_info);
CORE_DATAF_X(9, fatal ? eLOG_Error : eLOG_Note, hdr, size,
("[HTTP%s%s] %s",
url ? "; " : "",
url ? url : "", header_header));
}
if (!(uuu->flags & fHTTP_KeepHeader)) {
if (fatal) {
if (!uuu->net_info->debug_printout && !uuu->parse_header) {
char text[40];
assert(http_code);
if (!url)
url = ConnNetInfo_URL(uuu->net_info);
if (http_code > 0)
sprintf(text, "%d", http_code);
else
strncpy0(text, "occurred", sizeof(text) - 1);
CORE_LOGF_X(22, eLOG_Error,
("[HTTP%s%s] Fatal error %s",
url ? "; " : "",
url ? url : "", text));
}
if (!uuu->adjust)
uuu->net_info->max_try = 0;
}
header_parse = uuu->parse_header
? uuu->parse_header(hdr, uuu->user_data, http_code)
: eHTTP_HeaderSuccess;
if (header_parse == eHTTP_HeaderError) {
retry->mode = eRetry_None;
if (uuu->net_info->debug_printout == eDebugPrintout_Some
&& !http_code/*i.e. was okay*/ && x_IsErrorHeader(uuu)) {
if (!url)
url = ConnNetInfo_URL(uuu->net_info);
CORE_DATAF_X(9, eLOG_Note, hdr, size,
("[HTTP%s%s] HTTP header (parse error)",
url ? "; " : "",
url ? url : ""));
}
} else if (header_parse == eHTTP_HeaderComplete) {
/* i.e. stop processing */
retry->mode = eRetry_None;
http_code = 0/*fake success*/;
}
} else {
header_parse = eHTTP_HeaderSuccess;
retry->mode = eRetry_None;
}
tags = eHTTP_NcbiMsg | eHTTP_Connection
| (retry->mode & eRetry_Redirect ? eHTTP_Location :
retry->mode & eRetry_Authenticate ? eHTTP_Authenticate : 0)
| (uuu->flags & fHTTP_NoAutomagicSID ? 0 : eHTTP_NcbiSid);
if (uuu->http_code / 100 != 1 && uuu->http_code != 204)
tags |= eHTTP_ContentLength | eHTTP_TransferEncoding;
/* NB: the loop may clobber "hdr" unless fHTTP_KeepHeader is set */
for (s = strchr(hdr, '\n'); s && *s; s = strchr(s + 1, '\n')) {
if (tags & eHTTP_NcbiMsg) {
/* parse NCBI message */
static const char kNcbiMsgTag[] = "\n" HTTP_NCBI_MESSAGE;
if (strncasecmp(s, kNcbiMsgTag, sizeof(kNcbiMsgTag) - 1) == 0) {
char* msg = s + sizeof(kNcbiMsgTag) - 1, *e;
while (*msg && isspace((unsigned char)(*msg)))
++msg;
if (!(e = strchr(msg, '\r')) && !(e = strchr(msg, '\n')))
break;
do {
if (!isspace((unsigned char) e[-1]))
break;
} while (--e > msg);
n = (size_t)(e - msg);
if (n) {
char c = msg[n];
msg[n] = '\0';
if (s_MessageHook) {
if (s_MessageIssued <= 0) {
s_MessageIssued = 1;
s_MessageHook(msg);
}
} else {
s_MessageIssued = -1;
CORE_LOGF_X(10, eLOG_Critical,
("[NCBI-MESSAGE] %s", msg));
}
msg[n] = c;
}
tags &= ~eHTTP_NcbiMsg;
continue;
}
}
if (tags & eHTTP_NcbiSid) {
/* parse NCBI SID */
static const char kNcbiSidTag[] = "\n" HTTP_NCBI_SID;
if (strncasecmp(s, kNcbiSidTag, sizeof(kNcbiSidTag) - 1) == 0) {
char* sid = s + sizeof(kNcbiSidTag) - 1, *e;
while (*sid && isspace((unsigned char)(*sid)))
++sid;
if (!(e = strchr(sid, '\r')) && !(e = strchr(sid, '\n')))
break;
do {
if (!isspace((unsigned char) e[-1]))
break;
} while (--e > sid);
n = (size_t)(e - sid);
if (n) {
char c = sid[n];
sid[n] = '\0';
ConnNetInfo_OverrideUserHeader(uuu->net_info, s + 1);
sid[n] = c;
}
tags &= ~eHTTP_NcbiSid;
continue;
}
}
if (tags & eHTTP_Location) {
/* parse "Location" pointer */
static const char kLocationTag[] = "\nLocation:";
assert(http_code);
if (strncasecmp(s, kLocationTag, sizeof(kLocationTag) - 1) == 0) {
char* loc = s + sizeof(kLocationTag) - 1, *e;
while (*loc && isspace((unsigned char)(*loc)))
++loc;
if (!(e = strchr(loc, '\r')) && !(e = strchr(loc, '\n')))
break;
do {
if (!isspace((unsigned char) e[-1]))
break;
} while (--e > loc);
n = (size_t)(e - loc);
if (n) {
memmove(hdr, loc, n);
hdr[n] = '\0';
retry->data = hdr;
}
tags &= ~eHTTP_Location;
continue;
}
}
if (tags & eHTTP_Connection) {
/* parse "Connection" tag */
static const char kConnectionTag[] = "\nConnection:";
if (strncasecmp(s, kConnectionTag, sizeof(kConnectionTag)-1) == 0){
char* con = s + sizeof(kConnectionTag) - 1, *e;
while (*con && isspace((unsigned char)(*con)))
++con;
if (!(e = strchr(con, '\r')) && !(e = strchr(con, '\n')))
break;
do {
if (!isspace((unsigned char) e[-1]))
break;
} while (--e > con);
n = (size_t)(e - con);
if (strncasecmp(con, "close", n) == 0)
uuu->keepalive = 0;
tags &= ~eHTTP_Connection;
continue;
}
}
if (tags & eHTTP_Authenticate) {
/* parse "Authenticate"/"Proxy-Authenticate" tags */
static const char kAuthenticateTag[] = "-Authenticate:";
assert(http_code);
if (strncasecmp(s + (retry->mode == eRetry_Authenticate ? 4 : 6),
kAuthenticateTag, sizeof(kAuthenticateTag)-1)==0) {
if ((retry->mode == eRetry_Authenticate
&& strncasecmp(s, "\nWWW", 4) == 0) ||
(retry->mode == eRetry_ProxyAuthenticate
&& strncasecmp(s, "\nProxy", 6) == 0)) {
char* txt = s + sizeof(kAuthenticateTag) - 1, *e;
txt += retry->mode == eRetry_Authenticate ? 4 : 6;
while (*txt && isspace((unsigned char)(*txt)))
++txt;
if (!(e = strchr(txt, '\r')) && !(e = strchr(txt, '\n')))
break;
do {
if (!isspace((unsigned char) e[-1]))
break;
} while (--e > txt);
n = (size_t)(e - txt);
if (n && x_IsValidChallenge(txt, n)) {
memmove(hdr, txt, n);
hdr[n] = '\0';
retry->data = hdr;
}
tags &= ~eHTTP_Authenticate;
continue;
}
}
}
if (tags & eHTTP_ContentLength) {
/* parse "Content-Length" for non-HEAD/CONNECT */
static const char kContentLenTag[] = "\nContent-Length:";
if (strncasecmp(s, kContentLenTag, sizeof(kContentLenTag)-1) == 0){
if (!uuu->chunked
&& uuu->net_info->req_method != eReqMethod_Head
&& uuu->net_info->req_method != eReqMethod_Connect) {
const char* len = s + sizeof(kContentLenTag) - 1, *e;
int tmp;
while (*len && isspace((unsigned char)(*len)))
len++;
if (!(e = strchr(len, '\r')) && !(e = strchr(len, '\n')))
break;
do {
if (!isspace((unsigned char) e[-1]))
break;
} while (--e > len);
if (e == len
|| sscanf(len, "%" NCBI_BIGCOUNT_FORMAT_SPEC "%n",
&uuu->expected, &tmp) < 1
|| len + tmp != e) {
uuu->expected = (TNCBI_BigCount)(-1L)/*no checks*/;
}
}
tags &= ~eHTTP_ContentLength;
continue;
}
}
if (tags & eHTTP_TransferEncoding) {
static const char kTransferEncodingTag[] = "\nTransfer-Encoding:";
if (strncasecmp(s, kTransferEncodingTag,
sizeof(kTransferEncodingTag)-1) == 0) {
const char* te = s + sizeof(kTransferEncodingTag) - 1, *e;
while (*te && isspace((unsigned char)(*te)))
te++;
if (!(e = strchr(te, '\r')) && !(e = strchr(te, '\n')))
break;
do {
if (!isspace((unsigned char) e[-1]))
break;
} while(--e > te);
n = (size_t)(e - te);
if (n < 7 || strncasecmp(&e[-7], "chunked", 7) != 0
|| (!isspace((unsigned char) e[-8])
&& e[-8] != ':' && e[-8] != ',')) {
uuu->keepalive = 0;
} else
uuu->chunked = 1;
uuu->expected = 0;
tags &= ~(eHTTP_ContentLength | eHTTP_TransferEncoding);
if (!uuu->net_info->version) {
CORE_LOG(eLOG_Warning,
"Chunked transfer encoding within HTTP/1.0");
}
continue;
}
}
if (!tags)
break;
}
if (uuu->flags & fHTTP_KeepHeader) {
assert(retry->mode == eRetry_None);
if (!BUF_AppendEx(&uuu->r_buf, hdr, 0, hdr, size)) {
int error = errno;
if (!url)
url = ConnNetInfo_URL(uuu->net_info);
CORE_LOGF_ERRNO_X(11, eLOG_Error, error,
("[HTTP%s%s] Cannot save HTTP header",
url ? "; " : "",
url ? url : ""));
free(hdr);
}
if (url)
free(url);
return eIO_Success;
}
if (!retry->data)
free(hdr);
if (http_code == 0) {
if (url)
free(url);
return header_parse == eHTTP_HeaderError ? eIO_Unknown : eIO_Success;
}
assert(header_parse != eHTTP_HeaderComplete);
if (uuu->net_info->debug_printout
|| header_parse == eHTTP_HeaderContinue) {
if (http_code > 0/*real error, w/only a very short body expected*/) {
static const STimeout kDefConnTimeout = {
(unsigned int)
DEF_CONN_TIMEOUT,
(unsigned int)
((DEF_CONN_TIMEOUT - (unsigned int) DEF_CONN_TIMEOUT)
* 1000000.0)
};
SOCK_SetTimeout(uuu->sock, eIO_Read, &kDefConnTimeout);
}
do {
n = 0;
status = s_ReadData(uuu, &uuu->http, 0, &n, eIO_ReadPlain);
uuu->received += n;
} while (status == eIO_Success);
if (header_parse == eHTTP_HeaderContinue && status == eIO_Closed) {
if (url)
free(url);
return retry->mode ? status : eIO_Success;
}
} else
status = eIO_Success/*NB: irrelevant*/;
if (uuu->net_info->debug_printout == eDebugPrintout_Some
|| header_parse == eHTTP_HeaderContinue) {
const char* err = status != eIO_Closed ? IO_StatusStr(status) : 0;
if (!url)
url = ConnNetInfo_URL(uuu->net_info);
assert(status != eIO_Success);
assert(!err || *err);
if (header_parse == eHTTP_HeaderContinue) {
assert(err/*status != eIO_Closed*/);
CORE_LOGF_X(19, eLOG_Warning,
("[HTTP%s%s] Server error message incomplete (%s)",
url ? "; " : "",
url ? url : "", err));
} else if (!(size = BUF_Size(uuu->http))) {
CORE_LOGF_X(12, err && !(uuu->flags & fHTTP_SuppressMessages)
? eLOG_Warning : eLOG_Trace,
("[HTTP%s%s] No error message received from server"
"%s%s%s",
url ? "; " : "",
url ? url : "",
err ? " (" : "",
err ? err : "", &")"[!err]));
} else if ((s = (char*) malloc(size)) != 0) {
n = BUF_Read(uuu->http, s, size);
if (n != size) {
CORE_LOGF_X(13, eLOG_Error,
("[HTTP%s%s] Cannot extract server error message"
" from buffer entirely (%lu/%lu)",
url ? "; " : "",
url ? url : "",
(unsigned long) n, (unsigned long) size));
}
if (n) {
CORE_DATAF_X(14, eLOG_Note, s, n,
("[HTTP%s%s] Server error message%s%s%s",
url ? "; " : "",
url ? url : "",
err ? " (" : "",
err ? err : "", &")"[!err]));
}
free(s);
} else {
CORE_LOGF_X(15, eLOG_Error,
("[HTTP%s%s] Cannot allocate server error message"
" (%lu byte%s)",
url ? "; " : "",
url ? url : "",
(unsigned long) size, &"s"[size == 1]));
}
}
if (url)
free(url);
if (header_parse != eHTTP_HeaderContinue)
BUF_Erase(uuu->http);
return eIO_Unknown;
}
/* Prepare connector for reading. Open socket if necessary and make an initial
* connect and send, re-trying if possible until success.
* Return codes:
* eIO_Success = success, connector is ready for reading (uuu->sock != NULL);
* eIO_Timeout = maybe (check uuu->sock) connected and no data available yet;
* other code = error, not connected (uuu->sock == NULL).
* NB: On error, uuu->r_buf may be updated to contain new pending data!
*/
static EIO_Status s_PreRead(SHttpConnector* uuu,
const STimeout* timeout,
EExtractMode extract)
{
EIO_Status status;
for (;;) {
EIO_Status adjust;
SRetry retry;
if ((status = s_ConnectAndSend(uuu, timeout, extract)) != eIO_Success)
break;
assert(!uuu->w_len);
if (uuu->conn_state == eCS_WriteRequest) {
assert(x_IsWriteThru(uuu) && uuu->chunked);
BUF_Erase(uuu->w_buf);
if (!BUF_Write(&uuu->w_buf, "0\r\n\r\n", 5)) {
status = eIO_Unknown;
break;
}
uuu->w_len = 5;
uuu->conn_state = eCS_FlushRequest;
status = s_ConnectAndSend(uuu, timeout, extract);
if (status != eIO_Success)
break;
assert(!uuu->w_len);
}
if (extract == eEM_Flush)
return eIO_Success;
assert(uuu->sock && uuu->conn_state > eCS_FlushRequest);
if (extract == eEM_Wait
&& (uuu->conn_state & eCS_DoneBody) == eCS_DoneBody) {
return eIO_Closed;
}
/* set read timeout before leaving (s_Read() expects it set) */
SOCK_SetTimeout(uuu->sock, eIO_Read, timeout);
if (uuu->conn_state & eCS_ReadBody)
return eIO_Success;
assert(uuu->conn_state == eCS_ReadHeader);
if ((status = s_ReadHeader(uuu, &retry, extract)) == eIO_Success) {
assert((uuu->conn_state & eCS_ReadBody) && !retry.mode);
/* pending output data no longer needed */
BUF_Erase(uuu->w_buf);
break;
}
assert(status != eIO_Timeout || !retry.mode);
/* if polling then bail out with eIO_Timeout */
if (status == eIO_Timeout
&& (extract == eEM_Wait
|| (timeout && !(timeout->sec | timeout->usec)))) {
assert(!retry.data);
return eIO_Timeout;
}
/* HTTP header read error; disconnect and retry */
s_DropConnection(uuu);
assert(status != eIO_Success);
adjust = s_Adjust(uuu, &retry, extract);
if (retry.data)
free((void*) retry.data);
if (adjust != eIO_Success) {
if (adjust != eIO_Closed)
status = adjust;
break;
}
}
if (BUF_Size(uuu->http) && !BUF_Splice(&uuu->r_buf, uuu->http))
BUF_Erase(uuu->http);
assert(!BUF_Size(uuu->http));
return status;
}
/* NB: Sets the EOM read state */
static void x_Close(SHttpConnector* uuu)
{
/* since this is merely an acknowledgement, it will be "instant" */
SOCK_SetTimeout(uuu->sock, eIO_Close, &kZeroTimeout);
SOCK_CloseEx(uuu->sock, 0/*retain SOCK*/);
uuu->conn_state = eCS_Eom;
}
/* Read non-header data from connection */
static EIO_Status s_Read(SHttpConnector* uuu, void* buf,
size_t size, size_t* n_read)
{
EIO_Status status;
assert(uuu->conn_state & eCS_ReadBody);
assert(uuu->sock && size && n_read && !*n_read);
assert(uuu->net_info->req_method != eReqMethod_Connect);
if ((uuu->conn_state & eCS_DoneBody) == eCS_DoneBody) {
if (!uuu->chunked)
return eIO_Closed;
if (uuu->conn_state == eCS_Discard)
x_Close(uuu);
return uuu->conn_state != eCS_Eom ? x_ReadChunkTail(uuu) : eIO_Closed;
}
assert(uuu->received <= uuu->expected);
if (uuu->net_info->req_method == eReqMethod_Head
|| uuu->http_code / 100 == 1
|| uuu->http_code == 204
|| uuu->http_code == 304) {
status = eIO_Closed;
} else if (!uuu->net_info->version && (uuu->flags & fHCC_UrlDecodeInput)) {
/* read and URL-decode */
size_t n_peeked, n_decoded;
TNCBI_BigCount remain = uuu->expected - uuu->received;
size_t peek_size = size > remain ? (size_t)(remain + 1) : size;
void* peek_buf = malloc(peek_size *= 3);
/* peek the data */
status= SOCK_Read(uuu->sock,peek_buf,peek_size,&n_peeked,eIO_ReadPeek);
if (status == eIO_Success) {
if (URL_DecodeEx(peek_buf,n_peeked,&n_decoded,buf,size,n_read,"")){
/* decode, then discard successfully decoded data from input */
if (n_decoded) {
SOCK_Read(uuu->sock,0,n_decoded,&n_peeked,eIO_ReadPersist);
assert(n_peeked == n_decoded);
uuu->received += n_decoded;
} else {
assert(!*n_read);
if (size) {
/* if at EOF and remaining data cannot be decoded */
status = SOCK_Status(uuu->sock, eIO_Read);
if (status == eIO_Closed)
status = eIO_Unknown;
}
}
} else
status = eIO_Unknown;
if (status != eIO_Success) {
char* url = ConnNetInfo_URL(uuu->net_info);
CORE_LOGF_X(16, eLOG_Error,
("[HTTP%s%s] Cannot URL-decode data: %s",
url ? "; " : "",
url ? url : "", IO_StatusStr(status)));
if (url)
free(url);
}
} else
assert(!n_peeked);
if (peek_buf)
free(peek_buf);
} else {
/* just read, with no URL-decoding */
status = s_ReadData(uuu, buf, size, n_read, eIO_ReadPlain);
uuu->received += *n_read;
}
if (status == eIO_Closed && !uuu->keepalive)
x_Close(uuu);
if (uuu->expected != (TNCBI_BigCount)(-1L)) {
const char* how = 0;
if (uuu->received < uuu->expected) {
if (status == eIO_Closed) {
status = eIO_Unknown;
how = "premature EOM in";
}
} else {
if (uuu->expected < uuu->received) {
if (uuu->flags & fHCC_UrlDecodeInput) {
assert(*n_read);
--(*n_read);
} else {
TNCBI_BigCount excess = uuu->received - uuu->expected;
assert(*n_read >= excess);
*n_read -= (size_t) excess;
}
uuu->conn_state = eCS_Discard;
status = eIO_Unknown;
how = "too much";
}
}
if (how) {
char* url = ConnNetInfo_URL(uuu->net_info);
CORE_LOGF_X(21, eLOG_Warning,
("[HTTP%s%s] Got %s data (received "
"%" NCBI_BIGCOUNT_FORMAT_SPEC " vs. "
"%" NCBI_BIGCOUNT_FORMAT_SPEC " expected)",
url ? "; " : "",
url ? url : "", how,
uuu->received,
uuu->expected != (TNCBI_BigCount)(-1L) ?
uuu->expected : 0));
if (url)
free(url);
}
}
return status;
}
/* Reset/readout input data and close socket */
static EIO_Status s_Disconnect(SHttpConnector* uuu,
const STimeout* timeout,
EExtractMode extract)
{
EIO_Status status = eIO_Success;
assert(!(extract & eEM_Wait)); /* here it's only either drop or read */
BUF_Erase(uuu->http);
if (extract == eEM_Drop)
BUF_Erase(uuu->r_buf);
else if ((status = s_PreRead(uuu, timeout, extract)) == eIO_Success) {
do {
char buf[4096];
size_t x_read = 0;
status = s_Read(uuu, buf, sizeof(buf), &x_read);
if (!BUF_Write(&uuu->r_buf, buf, x_read))
status = eIO_Unknown;
} while (status == eIO_Success);
if (status == eIO_Closed)
status = eIO_Success;
}
if (uuu->sock) /* s_PreRead() might have dropped the connection already */
s_DropConnection(uuu);
uuu->can_connect &= ~fCC_Once;
return status;
}
static void s_OpenHttpConnector(SHttpConnector* uuu,
const STimeout* timeout)
{
/* NOTE: the real connect will be performed on the first "READ", or
* "FLUSH/CLOSE", or on "WAIT" on read -- see in "s_ConnectAndSend" */
assert(!uuu->sock);
/* store timeouts for later use */
if (timeout) {
uuu->oo_timeout = *timeout;
uuu->o_timeout = &uuu->oo_timeout;
uuu->ww_timeout = *timeout;
uuu->w_timeout = &uuu->ww_timeout;
} else {
uuu->o_timeout = kInfiniteTimeout;
uuu->w_timeout = kInfiniteTimeout;
}
/* reset the auto-reconnect/re-try/auth features */
uuu->can_connect = (uuu->flags & fHTTP_AutoReconnect
? fCC_Unlimited | fCC_Once : fCC_Once);
uuu->major_fault = 0;
uuu->minor_fault = 0;
uuu->auth_done = 0;
uuu->proxy_auth_done = 0;
}
static void s_DestroyHttpConnector(SHttpConnector* uuu)
{
assert(!uuu->sock);
if (uuu->cleanup)
uuu->cleanup(uuu->user_data);
ConnNetInfo_Destroy(uuu->net_info);
BUF_Destroy(uuu->http);
BUF_Destroy(uuu->r_buf);
BUF_Destroy(uuu->w_buf);
free(uuu);
}
/***********************************************************************
* INTERNAL -- "s_VT_*" functions for the "virt. table" of connector methods
***********************************************************************/
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
static const char* s_VT_GetType (CONNECTOR connector);
static char* s_VT_Descr (CONNECTOR connector);
static EIO_Status s_VT_Open (CONNECTOR connector,
const STimeout* timeout);
static EIO_Status s_VT_Wait (CONNECTOR connector,
EIO_Event event,
const STimeout* timeout);
static EIO_Status s_VT_Write (CONNECTOR connector,
const void* buf,
size_t size,
size_t* n_written,
const STimeout* timeout);
static EIO_Status s_VT_Flush (CONNECTOR connector,
const STimeout* timeout);
static EIO_Status s_VT_Read (CONNECTOR connector,
void* buf,
size_t size,
size_t* n_read,
const STimeout* timeout);
static EIO_Status s_VT_Status (CONNECTOR connector,
EIO_Event dir);
static EIO_Status s_VT_Close (CONNECTOR connector,
const STimeout* timeout);
static void s_Setup (CONNECTOR connector);
static void s_Destroy (CONNECTOR connector);
#ifdef __cplusplus
} /* extern "C" */
#endif /* __cplusplus */
/*ARGSUSED*/
static const char* s_VT_GetType
(CONNECTOR connector)
{
return "HTTP";
}
static char* s_VT_Descr
(CONNECTOR connector)
{
return ConnNetInfo_URL(((SHttpConnector*) connector->handle)->net_info);
}
static EIO_Status s_VT_Open
(CONNECTOR connector,
const STimeout* timeout)
{
s_OpenHttpConnector((SHttpConnector*) connector->handle, timeout);
return eIO_Success;
}
static EIO_Status s_VT_Wait
(CONNECTOR connector,
EIO_Event event,
const STimeout* timeout)
{
SHttpConnector* uuu = (SHttpConnector*) connector->handle;
EIO_Status status;
assert(event == eIO_Read || event == eIO_Write);
switch (event) {
case eIO_Read:
if (BUF_Size(uuu->r_buf))
return eIO_Success;
if (uuu->can_connect == fCC_None)
return eIO_Closed;
status = s_PreRead(uuu, timeout, eEM_Wait);
if (BUF_Size(uuu->r_buf))
return eIO_Success;
if (status != eIO_Success)
return status;
assert(uuu->sock);
return SOCK_Wait(uuu->sock, eIO_Read, timeout);
case eIO_Write:
if (uuu->can_connect == fCC_None)
return eIO_Closed;
if (!x_IsWriteThru(uuu)) {
return uuu->sock && uuu->can_connect == fCC_Once
? eIO_Closed : eIO_Success;
}
if (!uuu->sock && !BUF_Size(uuu->w_buf))
return eIO_Success;
if (!uuu->sock || uuu->conn_state < eCS_ReadHeader) {
status = s_ConnectAndSend(uuu, timeout, eEM_Flush);
if (status != eIO_Success)
return status;
} else
return uuu->can_connect == fCC_Once ? eIO_Closed : eIO_Success;
assert(uuu->sock);
assert(uuu->conn_state < eCS_ReadHeader && !uuu->w_len);
return uuu->conn_state < eCS_FlushRequest
? SOCK_Wait(uuu->sock, eIO_Write, timeout)
: eIO_Success;
default:
assert(0);
break;
}
return eIO_InvalidArg;
}
static EIO_Status s_VT_Write
(CONNECTOR connector,
const void* buf,
size_t size,
size_t* n_written,
const STimeout* timeout)
{
SHttpConnector* uuu = (SHttpConnector*) connector->handle;
EIO_Status status;
assert(!*n_written);
/* store the write timeout */
if (timeout) {
uuu->ww_timeout = *timeout;
uuu->w_timeout = &uuu->ww_timeout;
} else
uuu->w_timeout = kInfiniteTimeout;
/* if trying to write after a request then close the socket first,
* and so return to "IDLE" */
if (uuu->sock && uuu->conn_state > eCS_WriteRequest) {
status = s_Disconnect(uuu, timeout,
uuu->flags & fHTTP_DropUnread
? eEM_Drop : eEM_Read);
if (status != eIO_Success)
return status;
}
if (uuu->can_connect == fCC_None)
return eIO_Closed; /* no more connects permitted */
uuu->can_connect |= fCC_Once;
/* check if writing is at all legitimate */
if (size && (uuu->net_info->req_method == eReqMethod_Head ||
uuu->net_info->req_method == eReqMethod_Get)) {
return eIO_Closed;
}
/* write-through with HTTP/1.1 */
if (x_IsWriteThru(uuu)) {
if (BUF_Size(uuu->w_buf)) {
status = s_ConnectAndSend(uuu, timeout, eEM_Flush);
if (status != eIO_Success)
return status;
}
assert(!uuu->sock || (uuu->conn_state == eCS_WriteRequest
&& !uuu->w_len));
if (size) {
char prefix[80];
int n = sprintf(prefix, "%" NCBI_BIGCOUNT_FORMAT_SPEC_HEX "\r\n",
(TNCBI_BigCount) size);
BUF_Erase(uuu->w_buf);
if (!BUF_Write(&uuu->w_buf, prefix, (size_t) n) ||
!BUF_Write(&uuu->w_buf, buf, size) ||
!BUF_Write(&uuu->w_buf, "\r\n", 2)) {
BUF_Erase(uuu->w_buf);
return eIO_Unknown;
}
*n_written = size;
size += n + 2;
uuu->w_len = size;
uuu->entity = 1;
}
return eIO_Success;
}
/* accumulate all output in a memory buffer */
if (size && (uuu->flags & fHCC_UrlEncodeOutput)) {
/* with URL-encoding */
size_t dst_size = 3 * size;
void* dst = malloc(dst_size);
URL_Encode(buf, size, n_written, dst, dst_size, &dst_size);
if (!*n_written
|| !BUF_AppendEx(&uuu->w_buf, dst, 0, dst, dst_size)) {
if (dst)
free(dst);
return eIO_Unknown;
}
} else {
/* "as is" (without URL-encoding) */
if (!BUF_Write(&uuu->w_buf, buf, size))
return eIO_Unknown;
*n_written = size;
}
return eIO_Success;
}
static EIO_Status s_VT_Flush
(CONNECTOR connector,
const STimeout* timeout)
{
SHttpConnector* uuu = (SHttpConnector*) connector->handle;
EIO_Status status;
if (!uuu->sock && uuu->can_connect == fCC_None)
return eIO_Closed;
if (timeout) {
uuu->ww_timeout = *timeout;
uuu->w_timeout = &uuu->ww_timeout;
} else
uuu->w_timeout = timeout;
if (!(uuu->flags & fHTTP_Flushable))
return eIO_Success;
if (uuu->sock
&& !(x_IsWriteThru(uuu) && uuu->conn_state < eCS_ReadHeader)) {
return eIO_Success;
}
status = x_IsWriteThru(uuu)
? s_ConnectAndSend(uuu, timeout, eEM_Flush)
: s_PreRead (uuu, timeout, eEM_Flush);
return BUF_Size(uuu->r_buf) ? eIO_Success : status;
}
static EIO_Status s_VT_Read
(CONNECTOR connector,
void* buf,
size_t size,
size_t* n_read,
const STimeout* timeout)
{
SHttpConnector* uuu = (SHttpConnector*) connector->handle;
EExtractMode extract = BUF_Size(uuu->r_buf) ? eEM_Flush : eEM_Read;
EIO_Status status = uuu->can_connect & fCC_Once
? s_PreRead(uuu, timeout, extract) : eIO_Closed;
size_t x_read = BUF_Read(uuu->r_buf, buf, size);
assert(n_read && !*n_read);
if (x_read < size && extract == eEM_Read && status == eIO_Success) {
status = s_Read(uuu, (char*) buf + x_read, size - x_read, n_read);
*n_read += x_read;
} else
*n_read = x_read;
return extract == eEM_Read ? status : eIO_Success;
}
static EIO_Status s_VT_Status
(CONNECTOR connector,
EIO_Event dir)
{
SHttpConnector* uuu = (SHttpConnector*) connector->handle;
return uuu->sock ? SOCK_Status(uuu->sock, dir) :
(uuu->can_connect == fCC_None ? eIO_Closed : eIO_Success);
}
static EIO_Status s_VT_Close
(CONNECTOR connector,
const STimeout* timeout)
{
SHttpConnector* uuu = (SHttpConnector*) connector->handle;
/* Send the accumulated output data(if any) to server, then close the
* socket. Regardless of the flush, clear both input and output buffers.
*/
if ((uuu->can_connect & fCC_Once)
&& ((!uuu->sock && BUF_Size(uuu->w_buf))
|| (uuu->flags & fHTTP_Flushable))) {
/* "WRITE" mode and data (or just flag) is still pending */
s_PreRead(uuu, timeout, eEM_Drop);
}
s_Disconnect(uuu, timeout, eEM_Drop);
assert(!uuu->sock);
/* clear pending output data, if any */
BUF_Erase(uuu->w_buf);
return eIO_Success;
}
static void s_Setup
(CONNECTOR connector)
{
SHttpConnector* uuu = (SHttpConnector*) connector->handle;
SMetaConnector* meta = connector->meta;
/* initialize virtual table */
CONN_SET_METHOD(meta, get_type, s_VT_GetType, connector);
CONN_SET_METHOD(meta, descr, s_VT_Descr, connector);
CONN_SET_METHOD(meta, open, s_VT_Open, connector);
CONN_SET_METHOD(meta, wait, s_VT_Wait, connector);
CONN_SET_METHOD(meta, write, s_VT_Write, connector);
CONN_SET_METHOD(meta, flush, s_VT_Flush, connector);
CONN_SET_METHOD(meta, read, s_VT_Read, connector);
CONN_SET_METHOD(meta, status, s_VT_Status, connector);
CONN_SET_METHOD(meta, close, s_VT_Close, connector);
CONN_SET_DEFAULT_TIMEOUT(meta, uuu->net_info->timeout);
}
static void s_Destroy
(CONNECTOR connector)
{
SHttpConnector* uuu = (SHttpConnector*) connector->handle;
connector->handle = 0;
s_DestroyHttpConnector(uuu);
free(connector);
}
/* NB: per the standard, the HTTP tag name is misspelled as "Referer" */
static int/*bool*/ x_FixupUserHeader(SConnNetInfo* net_info,
int* /*bool*/ has_sid)
{
int/*bool*/ has_referer = 0/*false*/;
int/*bool*/ has_host = 0/*false*/;
const char* s;
if ((s = net_info->http_user_header) != 0) {
int/*bool*/ first = 1/*true*/;
while (*s) {
if (strncasecmp(s, &"\nReferer:"[first], 9 - first) == 0) {
has_referer = 1/*true*/;
} else if (strncasecmp(s, &"\nHost:"[first], 6 - first) == 0) {
has_host = 1/*true*/;
#ifdef HAVE_LIBCONNEXT
} else if (strncasecmp(s, &"\nCAF"[first], 4 - first) == 0
&& (s[4 - first] == '-' || s[4 - first] == ':')) {
char* caftag = strndup(s + !first, strcspn(s + !first, " \t"));
if (caftag) {
size_t cafoff = (size_t)(s - net_info->http_user_header);
ConnNetInfo_DeleteUserHeader(net_info, caftag);
free(caftag);
if (!(s = net_info->http_user_header) || !*(s += cafoff))
break;
continue;
}
#endif /*HAVE_LIBCONNEXT*/
} else if (!*has_sid
&& strncasecmp(s, &"\n" HTTP_NCBI_SID[first],
sizeof(HTTP_NCBI_SID) - first) == 0) {
*has_sid = 1/*true*/;
}
if (!(s = strchr(++s, '\n')))
break;
first = 0/*false*/;
}
}
s = CORE_GetAppName();
if (s && *s) {
char buf[128];
sprintf(buf, "User-Agent: %.80s", s);
ConnNetInfo_ExtendUserHeader(net_info, buf);
}
if (!has_referer && net_info->http_referer && *net_info->http_referer
&& (s = (char*) malloc(strlen(net_info->http_referer) + 10)) != 0) {
sprintf((char*) s, "Referer: %s", net_info->http_referer);
ConnNetInfo_AppendUserHeader(net_info, s);
free((void*) s);
}
return has_host;
}
static EIO_Status s_CreateHttpConnector
(const SConnNetInfo* net_info,
const char* user_header,
int/*bool*/ tunnel,
THTTP_Flags flags,
SHttpConnector** http)
{
SConnNetInfo* xxx;
SHttpConnector* uuu;
char* fff;
int/*bool*/ sid;
*http = 0;
xxx = net_info ? ConnNetInfo_Clone(net_info) : ConnNetInfo_Create(0);
if (!xxx)
return eIO_Unknown;
if (xxx->req_method >= eReqMethod_v1) {
xxx->req_method &= ~eReqMethod_v1;
xxx->version = 1;
if (flags & fHTTP_PushAuth)
xxx->http_push_auth = 1;
}
if (!tunnel) {
if (xxx->req_method == eReqMethod_Connect
|| (xxx->scheme != eURL_Unspec &&
xxx->scheme != eURL_Https &&
xxx->scheme != eURL_Http)) {
ConnNetInfo_Destroy(xxx);
return eIO_InvalidArg;
}
if (xxx->scheme == eURL_Unspec)
xxx->scheme = eURL_Http;
if ((fff = strchr(xxx->args, '#')) != 0)
*fff = '\0';
}
if (!ConnNetInfo_OverrideUserHeader(xxx, user_header)) {
ConnNetInfo_Destroy(xxx);
return eIO_Unknown;
}
if (tunnel) {
if (!xxx->http_proxy_host[0] || !xxx->http_proxy_port) {
ConnNetInfo_Destroy(xxx);
return eIO_InvalidArg;
}
xxx->req_method = eReqMethod_Connect;
xxx->version = 0;
xxx->path[0] = '\0';
xxx->args[0] = '\0';
if (xxx->http_referer) {
free((void*) xxx->http_referer);
xxx->http_referer = 0;
}
ConnNetInfo_DeleteUserHeader(xxx, "Referer:");
}
if (xxx->max_try == 0 || (flags & fHTTP_NoAutoRetry))
xxx->max_try = 1;
if (!(uuu = (SHttpConnector*) malloc(sizeof(SHttpConnector)))) {
ConnNetInfo_Destroy(xxx);
return eIO_Unknown;
}
/* initialize internal data structure */
uuu->net_info = xxx;
uuu->parse_header = 0;
uuu->user_data = 0;
uuu->adjust = 0;
uuu->cleanup = 0;
sid = flags & fHTTP_NoAutomagicSID ? 1 : tunnel;
uuu->skip_host = x_FixupUserHeader(xxx, &sid);
if (sid)
flags |= fHTTP_NoAutomagicSID;
uuu->flags = flags;
uuu->unsafe_redir = flags & fHTTP_UnsafeRedirects ? eOn : eOff;
uuu->error_header = eDefault;
uuu->can_connect = fCC_None; /* will be properly set at open */
uuu->unused = 0;
uuu->sock = 0;
uuu->o_timeout = kDefaultTimeout; /* deliberately bad values here... */
uuu->w_timeout = kDefaultTimeout; /* ...must be reset prior to use */
uuu->http = 0;
uuu->r_buf = 0;
uuu->w_buf = 0;
uuu->w_len = 0;
if (tunnel)
s_OpenHttpConnector(uuu, xxx->timeout);
/* else there are some unintialized fields left -- they are inited later */
*http = uuu;
return eIO_Success;
}
static CONNECTOR s_CreateConnector
(const SConnNetInfo* net_info,
const char* user_header,
THTTP_Flags flags,
FHTTP_ParseHeader parse_header,
void* user_data,
FHTTP_Adjust adjust,
FHTTP_Cleanup cleanup)
{
SHttpConnector* uuu;
CONNECTOR ccc;
if (s_CreateHttpConnector(net_info, user_header, 0/*regular*/,
flags, &uuu) != eIO_Success) {
assert(!uuu);
return 0;
}
assert(uuu);
if (!(ccc = (SConnector*) malloc(sizeof(SConnector)))) {
s_DestroyHttpConnector(uuu);
return 0;
}
/* initialize additional internal data structure */
uuu->parse_header = parse_header;
uuu->user_data = user_data;
uuu->adjust = adjust;
uuu->cleanup = cleanup;
/* enable an override from outside */
if (!uuu->unsafe_redir)
uuu->unsafe_redir = eDefault;
/* initialize connector structure */
ccc->handle = uuu;
ccc->next = 0;
ccc->meta = 0;
ccc->setup = s_Setup;
ccc->destroy = s_Destroy;
return ccc;
}
/***********************************************************************
* EXTERNAL -- the connector's "constructor"
***********************************************************************/
extern CONNECTOR HTTP_CreateConnector
(const SConnNetInfo* net_info,
const char* user_header,
THTTP_Flags flags)
{
return s_CreateConnector(net_info, user_header, flags, 0, 0, 0, 0);
}
extern CONNECTOR HTTP_CreateConnectorEx
(const SConnNetInfo* net_info,
THTTP_Flags flags,
FHTTP_ParseHeader parse_header,
void* user_data,
FHTTP_Adjust adjust,
FHTTP_Cleanup cleanup)
{
return s_CreateConnector(net_info, 0/*user_header*/, flags,
parse_header, user_data, adjust, cleanup);
}
extern EIO_Status HTTP_CreateTunnelEx
(const SConnNetInfo* net_info,
THTTP_Flags flags,
const void* data,
size_t size,
SOCK* sock)
{
unsigned short http_code;
EIO_Status status;
SHttpConnector* uuu;
if (!sock)
return eIO_InvalidArg;
*sock = 0;
status = s_CreateHttpConnector(net_info, 0/*user_header*/, 1/*tunnel*/,
flags | fHTTP_DropUnread, &uuu);
if (status != eIO_Success) {
assert(!uuu);
return status;
}
assert(uuu && !BUF_Size(uuu->w_buf));
if (!size || BUF_Prepend(&uuu->w_buf, data, size)) {
if (size)
sprintf(uuu->net_info->args, "[%lu]", (unsigned long) size);
status = s_PreRead(uuu, uuu->net_info->timeout, eEM_Wait);
if (status == eIO_Success) {
assert(uuu->conn_state == eCS_ReadBody);
assert(uuu->http_code / 100 == 2);
assert(uuu->sock);
*sock = uuu->sock;
http_code = 0;
uuu->sock = 0;
} else {
if (uuu->sock)
s_DropConnection(uuu);
http_code = uuu->http_code;
}
} else {
http_code = 0;
status = eIO_Unknown;
}
s_DestroyHttpConnector(uuu);
switch (http_code) {
case 503:
return eIO_NotSupported;
case 426:
case 404:
return eIO_InvalidArg;
case 403:
return eIO_Closed;
default:
break;
}
return status;
}
extern EIO_Status HTTP_CreateTunnel
(const SConnNetInfo* net_info,
THTTP_Flags flags,
SOCK* sock)
{
return HTTP_CreateTunnelEx(net_info, flags, 0, 0, sock);
}
extern void HTTP_SetNcbiMessageHook(FHTTP_NcbiMessageHook hook)
{
if (hook) {
if (hook != s_MessageHook)
s_MessageIssued = s_MessageIssued ? -1 : -2;
} else if (s_MessageIssued < -1)
s_MessageIssued = 0;
s_MessageHook = hook;
}
|