1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665
|
/*
* Copyright (c) 1987-2017 by the citadel.org team
*
* This program is open source software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#define _GNU_SOURCE
#include "sysdep.h"
#include <ctype.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <sys/select.h>
#include <fcntl.h>
#include <sys/types.h>
#define SHOW_ME_VAPPEND_PRINTF
#include <stdarg.h>
#include "libcitadel.h"
#include "b64/cencode.h"
#include "b64/cdecode.h"
#ifdef HAVE_ICONV
#include <iconv.h>
#endif
#ifdef HAVE_BACKTRACE
#include <execinfo.h>
#endif
#ifdef UNDEF_MEMCPY
#undef memcpy
#endif
#ifdef HAVE_ZLIB
#include <zlib.h>
int ZEXPORT compress_gzip(Bytef * dest, size_t * destLen,
const Bytef * source, uLong sourceLen, int level);
#endif
int BaseStrBufSize = 64;
int EnableSplice = 0;
int ZLibCompressionRatio = -1; /* defaults to 6 */
#ifdef HAVE_ZLIB
#define DEF_MEM_LEVEL 8 /*< memlevel??? */
#define OS_CODE 0x03 /*< unix */
const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
#endif
const char *StrBufNOTNULL = ((char*) NULL) - 1;
const char HexList[256][3] = {
"00","01","02","03","04","05","06","07","08","09","0A","0B","0C","0D","0E","0F",
"10","11","12","13","14","15","16","17","18","19","1A","1B","1C","1D","1E","1F",
"20","21","22","23","24","25","26","27","28","29","2A","2B","2C","2D","2E","2F",
"30","31","32","33","34","35","36","37","38","39","3A","3B","3C","3D","3E","3F",
"40","41","42","43","44","45","46","47","48","49","4A","4B","4C","4D","4E","4F",
"50","51","52","53","54","55","56","57","58","59","5A","5B","5C","5D","5E","5F",
"60","61","62","63","64","65","66","67","68","69","6A","6B","6C","6D","6E","6F",
"70","71","72","73","74","75","76","77","78","79","7A","7B","7C","7D","7E","7F",
"80","81","82","83","84","85","86","87","88","89","8A","8B","8C","8D","8E","8F",
"90","91","92","93","94","95","96","97","98","99","9A","9B","9C","9D","9E","9F",
"A0","A1","A2","A3","A4","A5","A6","A7","A8","A9","AA","AB","AC","AD","AE","AF",
"B0","B1","B2","B3","B4","B5","B6","B7","B8","B9","BA","BB","BC","BD","BE","BF",
"C0","C1","C2","C3","C4","C5","C6","C7","C8","C9","CA","CB","CC","CD","CE","CF",
"D0","D1","D2","D3","D4","D5","D6","D7","D8","D9","DA","DB","DC","DD","DE","DF",
"E0","E1","E2","E3","E4","E5","E6","E7","E8","E9","EA","EB","EC","ED","EE","EF",
"F0","F1","F2","F3","F4","F5","F6","F7","F8","F9","FA","FB","FC","FD","FE","FF"};
/**
* @defgroup StrBuf Stringbuffer, A class for manipulating strings with dynamic buffers
* StrBuf is a versatile class, aiding the handling of dynamic strings
* * reduce de/reallocations
* * reduce the need to remeasure it
* * reduce scanning over the string (in @ref StrBuf_NextTokenizer "Tokenizers")
* * allow asyncroneous IO for line and Blob based operations
* * reduce the use of memove in those
* * Quick filling in several operations with append functions
*/
/**
* @defgroup StrBuf_DeConstructors Create/Destroy StrBufs
* @ingroup StrBuf
*/
/**
* @defgroup StrBuf_Cast Cast operators to interact with char* based code
* @ingroup StrBuf
* use these operators to interfere with code demanding char*;
* if you need to own the content, smash me. Avoid, since we loose the length information.
*/
/**
* @defgroup StrBuf_Filler Create/Replace/Append Content into a StrBuf
* @ingroup StrBuf
* operations to get your Strings into a StrBuf, manipulating them, or appending
*/
/**
* @defgroup StrBuf_NextTokenizer Fast tokenizer to pull tokens in sequence
* @ingroup StrBuf
* Quick tokenizer; demands of the user to pull its tokens in sequence
*/
/**
* @defgroup StrBuf_Tokenizer tokenizer Functions; Slow ones.
* @ingroup StrBuf
* versatile tokenizer; random access to tokens, but slower; Prefer the @ref StrBuf_NextTokenizer "Next Tokenizer"
*/
/**
* @defgroup StrBuf_BufferedIO Buffered IO with Asynchroneous reads and no unneeded memmoves (the fast ones)
* @ingroup StrBuf
* File IO to fill StrBufs; Works with work-buffer shared across several calls;
* External Cursor to maintain the current read position inside of the buffer
* the non-fast ones will use memove to keep the start of the buffer the read buffer (which is slower)
*/
/**
* @defgroup StrBuf_IO FileIO; Prefer @ref StrBuf_BufferedIO
* @ingroup StrBuf
* Slow I/O; avoid.
*/
/**
* @defgroup StrBuf_DeEnCoder functions to translate the contents of a buffer
* @ingroup StrBuf
* these functions translate the content of a buffer into another representation;
* some are combined Fillers and encoders
*/
/**
* Private Structure for the Stringbuffer
*/
struct StrBuf {
char *buf; /**< the pointer to the dynamic buffer */
long BufSize; /**< how many spcae do we optain */
long BufUsed; /**< StNumber of Chars used excluding the trailing \\0 */
int ConstBuf; /**< are we just a wrapper arround a static buffer and musn't we be changed? */
#ifdef SIZE_DEBUG
long nIncreases; /**< for profiling; cound how many times we needed more */
char bt [SIZ]; /**< Stacktrace of last increase */
char bt_lastinc [SIZ]; /**< How much did we increase last time? */
#endif
};
static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE);
static inline int Ctdl_IsUtf8SequenceStart(const char Char);
#ifdef SIZE_DEBUG
#ifdef HAVE_BACKTRACE
static void StrBufBacktrace(StrBuf *Buf, int which)
{
int n;
char *pstart, *pch;
void *stack_frames[50];
size_t size, i;
char **strings;
if (which)
pstart = pch = Buf->bt;
else
pstart = pch = Buf->bt_lastinc;
size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
strings = backtrace_symbols(stack_frames, size);
for (i = 0; i < size; i++) {
if (strings != NULL)
n = snprintf(pch, SIZ - (pch - pstart), "%s\\n", strings[i]);
else
n = snprintf(pch, SIZ - (pch - pstart), "%p\\n", stack_frames[i]);
pch += n;
}
free(strings);
}
#endif
void dbg_FreeStrBuf(StrBuf *FreeMe, char *FromWhere)
{
if (hFreeDbglog == -1){
pid_t pid = getpid();
char path [SIZ];
snprintf(path, SIZ, "/tmp/libcitadel_strbuf_realloc.log.%d", pid);
hFreeDbglog = open(path, O_APPEND|O_CREAT|O_WRONLY);
}
if ((*FreeMe)->nIncreases > 0)
{
char buf[SIZ * 3];
long n;
n = snprintf(buf, SIZ * 3, "%c+|%ld|%ld|%ld|%s|%s|\n",
FromWhere,
(*FreeMe)->nIncreases,
(*FreeMe)->BufUsed,
(*FreeMe)->BufSize,
(*FreeMe)->bt,
(*FreeMe)->bt_lastinc);
n = write(hFreeDbglog, buf, n);
}
else
{
char buf[128];
long n;
n = snprintf(buf, 128, "%c_|0|%ld%ld|\n",
FromWhere,
(*FreeMe)->BufUsed,
(*FreeMe)->BufSize);
n = write(hFreeDbglog, buf, n);
}
}
void dbg_IncreaseBuf(StrBuf *IncMe)
{
Buf->nIncreases++;
#ifdef HAVE_BACKTRACE
StrBufBacktrace(Buf, 1);
#endif
}
void dbg_Init(StrBuf *Buf)
{
Buf->nIncreases = 0;
Buf->bt[0] = '\0';
Buf->bt_lastinc[0] = '\0';
#ifdef HAVE_BACKTRACE
StrBufBacktrace(Buf, 0);
#endif
}
#else
/* void it... */
#define dbg_FreeStrBuf(a, b)
#define dbg_IncreaseBuf(a)
#define dbg_Init(a)
#endif
/**
* @ingroup StrBuf
* @brief swaps the contents of two StrBufs
* this is to be used to have cheap switched between a work-buffer and a target buffer
* @param A First one
* @param B second one
*/
static inline void iSwapBuffers(StrBuf *A, StrBuf *B)
{
StrBuf C;
memcpy(&C, A, sizeof(*A));
memcpy(A, B, sizeof(*B));
memcpy(B, &C, sizeof(C));
}
void SwapBuffers(StrBuf *A, StrBuf *B)
{
iSwapBuffers(A, B);
}
/**
* @ingroup StrBuf_Cast
* @brief Cast operator to Plain String
* @note if the buffer is altered by StrBuf operations, this pointer may become
* invalid. So don't lean on it after altering the buffer!
* Since this operation is considered cheap, rather call it often than risking
* your pointer to become invalid!
* @param Str the string we want to get the c-string representation for
* @returns the Pointer to the Content. Don't mess with it!
*/
inline const char *ChrPtr(const StrBuf *Str)
{
if (Str == NULL)
return "";
return Str->buf;
}
/**
* @ingroup StrBuf_Cast
* @brief since we know strlen()'s result, provide it here.
* @param Str the string to return the length to
* @returns contentlength of the buffer
*/
inline int StrLength(const StrBuf *Str)
{
return (Str != NULL) ? Str->BufUsed : 0;
}
/**
* @ingroup StrBuf_DeConstructors
* @brief local utility function to resize the buffer
* @param Buf the buffer whichs storage we should increase
* @param KeepOriginal should we copy the original buffer or just start over with a new one
* @param DestSize what should fit in after?
*/
static int IncreaseBuf(StrBuf *Buf, int KeepOriginal, int DestSize)
{
char *NewBuf;
size_t NewSize = Buf->BufSize * 2;
if (Buf->ConstBuf)
return -1;
if (DestSize > 0)
while ((NewSize <= DestSize) && (NewSize != 0))
NewSize *= 2;
if (NewSize == 0)
return -1;
NewBuf= (char*) malloc(NewSize);
if (NewBuf == NULL)
return -1;
if (KeepOriginal && (Buf->BufUsed > 0))
{
memcpy(NewBuf, Buf->buf, Buf->BufUsed);
}
else
{
NewBuf[0] = '\0';
Buf->BufUsed = 0;
}
free (Buf->buf);
Buf->buf = NewBuf;
Buf->BufSize = NewSize;
dbg_IncreaseBuf(Buf);
return Buf->BufSize;
}
/**
* @ingroup StrBuf_DeConstructors
* @brief shrink / increase an _EMPTY_ buffer to NewSize. Buffercontent is thoroughly ignored and flushed.
* @param Buf Buffer to shrink (has to be empty)
* @param ThreshHold if the buffer is bigger then this, its readjusted
* @param NewSize if we Shrink it, how big are we going to be afterwards?
*/
void ReAdjustEmptyBuf(StrBuf *Buf, long ThreshHold, long NewSize)
{
if ((Buf != NULL) &&
(Buf->BufUsed == 0) &&
(Buf->BufSize < ThreshHold)) {
free(Buf->buf);
Buf->buf = (char*) malloc(NewSize);
Buf->BufUsed = 0;
Buf->BufSize = NewSize;
}
}
/**
* @ingroup StrBuf_DeConstructors
* @brief shrink long term buffers to their real size so they don't waste memory
* @param Buf buffer to shrink
* @param Force if not set, will just executed if the buffer is much to big; set for lifetime strings
* @returns physical size of the buffer
*/
long StrBufShrinkToFit(StrBuf *Buf, int Force)
{
if (Buf == NULL)
return -1;
if (Force ||
(Buf->BufUsed + (Buf->BufUsed / 3) > Buf->BufSize))
{
char *TmpBuf;
TmpBuf = (char*) malloc(Buf->BufUsed + 1);
if (TmpBuf == NULL)
return -1;
memcpy (TmpBuf, Buf->buf, Buf->BufUsed + 1);
Buf->BufSize = Buf->BufUsed + 1;
free(Buf->buf);
Buf->buf = TmpBuf;
}
return Buf->BufUsed;
}
/**
* @ingroup StrBuf_DeConstructors
* @brief Allocate a new buffer with default buffer size
* @returns the new stringbuffer
*/
StrBuf* NewStrBuf(void)
{
StrBuf *NewBuf;
NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
if (NewBuf == NULL)
return NULL;
NewBuf->buf = (char*) malloc(BaseStrBufSize);
if (NewBuf->buf == NULL)
{
free(NewBuf);
return NULL;
}
NewBuf->buf[0] = '\0';
NewBuf->BufSize = BaseStrBufSize;
NewBuf->BufUsed = 0;
NewBuf->ConstBuf = 0;
dbg_Init (NewBuf);
return NewBuf;
}
/**
* @ingroup StrBuf_DeConstructors
* @brief Copy Constructor; returns a duplicate of CopyMe
* @param CopyMe Buffer to faxmilate
* @returns the new stringbuffer
*/
StrBuf* NewStrBufDup(const StrBuf *CopyMe)
{
StrBuf *NewBuf;
if (CopyMe == NULL)
return NewStrBuf();
NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
if (NewBuf == NULL)
return NULL;
NewBuf->buf = (char*) malloc(CopyMe->BufSize);
if (NewBuf->buf == NULL)
{
free(NewBuf);
return NULL;
}
memcpy(NewBuf->buf, CopyMe->buf, CopyMe->BufUsed + 1);
NewBuf->BufUsed = CopyMe->BufUsed;
NewBuf->BufSize = CopyMe->BufSize;
NewBuf->ConstBuf = 0;
dbg_Init(NewBuf);
return NewBuf;
}
/**
* @ingroup StrBuf_DeConstructors
* @brief Copy Constructor; CreateRelpaceMe will contain CopyFlushMe afterwards.
* @param NoMe if non-NULL, we will use that buffer as value; KeepOriginal will abused as len.
* @param CopyFlushMe Buffer to faxmilate if KeepOriginal, or to move into CreateRelpaceMe if !KeepOriginal.
* @param CreateRelpaceMe If NULL, will be created, else Flushed and filled CopyFlushMe
* @param KeepOriginal should CopyFlushMe remain intact? or may we Steal its buffer?
* @returns the new stringbuffer
*/
void NewStrBufDupAppendFlush(StrBuf **CreateRelpaceMe, StrBuf *CopyFlushMe, const char *NoMe, int KeepOriginal)
{
StrBuf *NewBuf;
if (CreateRelpaceMe == NULL)
return;
if (NoMe != NULL)
{
if (*CreateRelpaceMe != NULL)
StrBufPlain(*CreateRelpaceMe, NoMe, KeepOriginal);
else
*CreateRelpaceMe = NewStrBufPlain(NoMe, KeepOriginal);
return;
}
if (CopyFlushMe == NULL)
{
if (*CreateRelpaceMe != NULL)
FlushStrBuf(*CreateRelpaceMe);
else
*CreateRelpaceMe = NewStrBuf();
return;
}
/*
* Randomly Chosen: bigger than 64 chars is cheaper to swap the buffers instead of copying.
* else *CreateRelpaceMe may use more memory than needed in a longer term, CopyFlushMe might
* be a big IO-Buffer...
*/
if (KeepOriginal || (StrLength(CopyFlushMe) < 256))
{
if (*CreateRelpaceMe == NULL)
{
*CreateRelpaceMe = NewBuf = NewStrBufPlain(NULL, CopyFlushMe->BufUsed);
dbg_Init(NewBuf);
}
else
{
NewBuf = *CreateRelpaceMe;
FlushStrBuf(NewBuf);
}
StrBufAppendBuf(NewBuf, CopyFlushMe, 0);
}
else
{
if (*CreateRelpaceMe == NULL)
{
*CreateRelpaceMe = NewBuf = NewStrBufPlain(NULL, CopyFlushMe->BufUsed);
dbg_Init(NewBuf);
}
else
NewBuf = *CreateRelpaceMe;
iSwapBuffers (NewBuf, CopyFlushMe);
}
if (!KeepOriginal)
FlushStrBuf(CopyFlushMe);
return;
}
/**
* @ingroup StrBuf_DeConstructors
* @brief create a new Buffer using an existing c-string
* this function should also be used if you want to pre-suggest
* the buffer size to allocate in conjunction with ptr == NULL
* @param ptr the c-string to copy; may be NULL to create a blank instance
* @param nChars How many chars should we copy; -1 if we should measure the length ourselves
* @returns the new stringbuffer
*/
StrBuf* NewStrBufPlain(const char* ptr, int nChars)
{
StrBuf *NewBuf;
size_t Siz = BaseStrBufSize;
size_t CopySize;
NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
if (NewBuf == NULL)
return NULL;
if (nChars < 0)
CopySize = strlen((ptr != NULL)?ptr:"");
else
CopySize = nChars;
while ((Siz <= CopySize) && (Siz != 0))
Siz *= 2;
if (Siz == 0)
{
free(NewBuf);
return NULL;
}
NewBuf->buf = (char*) malloc(Siz);
if (NewBuf->buf == NULL)
{
free(NewBuf);
return NULL;
}
NewBuf->BufSize = Siz;
if (ptr != NULL) {
memcpy(NewBuf->buf, ptr, CopySize);
NewBuf->buf[CopySize] = '\0';
NewBuf->BufUsed = CopySize;
}
else {
NewBuf->buf[0] = '\0';
NewBuf->BufUsed = 0;
}
NewBuf->ConstBuf = 0;
dbg_Init(NewBuf);
return NewBuf;
}
/**
* @ingroup StrBuf_DeConstructors
* @brief Set an existing buffer from a c-string
* @param Buf buffer to load
* @param ptr c-string to put into
* @param nChars set to -1 if we should work 0-terminated
* @returns the new length of the string
*/
int StrBufPlain(StrBuf *Buf, const char* ptr, int nChars)
{
size_t Siz;
size_t CopySize;
if (Buf == NULL)
return -1;
if (ptr == NULL) {
FlushStrBuf(Buf);
return -1;
}
Siz = Buf->BufSize;
if (nChars < 0)
CopySize = strlen(ptr);
else
CopySize = nChars;
while ((Siz <= CopySize) && (Siz != 0))
Siz *= 2;
if (Siz == 0) {
FlushStrBuf(Buf);
return -1;
}
if (Siz != Buf->BufSize)
IncreaseBuf(Buf, 0, Siz);
memcpy(Buf->buf, ptr, CopySize);
Buf->buf[CopySize] = '\0';
Buf->BufUsed = CopySize;
Buf->ConstBuf = 0;
return CopySize;
}
/**
* @ingroup StrBuf_DeConstructors
* @brief use strbuf as wrapper for a string constant for easy handling
* @param StringConstant a string to wrap
* @param SizeOfStrConstant should be sizeof(StringConstant)-1
*/
StrBuf* _NewConstStrBuf(const char* StringConstant, size_t SizeOfStrConstant)
{
StrBuf *NewBuf;
NewBuf = (StrBuf*) malloc(sizeof(StrBuf));
if (NewBuf == NULL)
return NULL;
NewBuf->buf = (char*) StringConstant;
NewBuf->BufSize = SizeOfStrConstant;
NewBuf->BufUsed = SizeOfStrConstant;
NewBuf->ConstBuf = 1;
dbg_Init(NewBuf);
return NewBuf;
}
/**
* @ingroup StrBuf_DeConstructors
* @brief flush the content of a Buf; keep its struct
* @param buf Buffer to flush
*/
int FlushStrBuf(StrBuf *buf)
{
if ((buf == NULL) || (buf->buf == NULL))
return -1;
if (buf->ConstBuf)
return -1;
buf->buf[0] ='\0';
buf->BufUsed = 0;
return 0;
}
/**
* @ingroup StrBuf_DeConstructors
* @brief wipe the content of a Buf thoroughly (overwrite it -> expensive); keep its struct
* @param buf Buffer to wipe
*/
int FLUSHStrBuf(StrBuf *buf)
{
if (buf == NULL)
return -1;
if (buf->ConstBuf)
return -1;
if (buf->BufUsed > 0) {
memset(buf->buf, 0, buf->BufUsed);
buf->BufUsed = 0;
}
return 0;
}
#ifdef SIZE_DEBUG
int hFreeDbglog = -1;
#endif
/**
* @ingroup StrBuf_DeConstructors
* @brief Release a Buffer
* Its a double pointer, so it can NULL your pointer
* so fancy SIG11 appear instead of random results
* @param FreeMe Pointer Pointer to the buffer to free
*/
void FreeStrBuf (StrBuf **FreeMe)
{
if (*FreeMe == NULL)
return;
dbg_FreeStrBuf(FreeMe, 'F');
if (!(*FreeMe)->ConstBuf)
free((*FreeMe)->buf);
free(*FreeMe);
*FreeMe = NULL;
}
/**
* @ingroup StrBuf_DeConstructors
* @brief flatten a Buffer to the Char * we return
* Its a double pointer, so it can NULL your pointer
* so fancy SIG11 appear instead of random results
* The Callee then owns the buffer and is responsible for freeing it.
* @param SmashMe Pointer Pointer to the buffer to release Buf from and free
* @returns the pointer of the buffer; Callee owns the memory thereafter.
*/
char *SmashStrBuf (StrBuf **SmashMe)
{
char *Ret;
if ((SmashMe == NULL) || (*SmashMe == NULL))
return NULL;
dbg_FreeStrBuf(SmashMe, 'S');
Ret = (*SmashMe)->buf;
free(*SmashMe);
*SmashMe = NULL;
return Ret;
}
/**
* @ingroup StrBuf_DeConstructors
* @brief Release the buffer
* If you want put your StrBuf into a Hash, use this as Destructor.
* @param VFreeMe untyped pointer to a StrBuf. be shure to do the right thing [TM]
*/
void HFreeStrBuf (void *VFreeMe)
{
StrBuf *FreeMe = (StrBuf*)VFreeMe;
if (FreeMe == NULL)
return;
dbg_FreeStrBuf(SmashMe, 'H');
if (!FreeMe->ConstBuf)
free(FreeMe->buf);
free(FreeMe);
}
/*******************************************************************************
* Simple string transformations *
*******************************************************************************/
/**
* @ingroup StrBuf
* @brief Wrapper around atol
*/
long StrTol(const StrBuf *Buf)
{
if (Buf == NULL)
return 0;
if(Buf->BufUsed > 0)
return atol(Buf->buf);
else
return 0;
}
/**
* @ingroup StrBuf
* @brief Wrapper around atoi
*/
int StrToi(const StrBuf *Buf)
{
if (Buf == NULL)
return 0;
if (Buf->BufUsed > 0)
return atoi(Buf->buf);
else
return 0;
}
/**
* @ingroup StrBuf
* @brief Checks to see if the string is a pure number
* @param Buf The buffer to inspect
* @returns 1 if its a pure number, 0, if not.
*/
int StrBufIsNumber(const StrBuf *Buf) {
char * pEnd;
if ((Buf == NULL) || (Buf->BufUsed == 0)) {
return 0;
}
strtoll(Buf->buf, &pEnd, 10);
if (pEnd == Buf->buf)
return 0;
if ((pEnd != NULL) && (pEnd == Buf->buf + Buf->BufUsed))
return 1;
if (Buf->buf == pEnd)
return 0;
return 0;
}
/**
* @ingroup StrBuf_Filler
* @brief modifies a Single char of the Buf
* You can point to it via char* or a zero-based integer
* @param Buf The buffer to manipulate
* @param ptr char* to zero; use NULL if unused
* @param nThChar zero based pointer into the string; use -1 if unused
* @param PeekValue The Character to place into the position
*/
long StrBufPeek(StrBuf *Buf, const char* ptr, long nThChar, char PeekValue)
{
if (Buf == NULL)
return -1;
if (ptr != NULL)
nThChar = ptr - Buf->buf;
if ((nThChar < 0) || (nThChar > Buf->BufUsed))
return -1;
Buf->buf[nThChar] = PeekValue;
return nThChar;
}
/**
* @ingroup StrBuf_Filler
* @brief modifies a range of chars of the Buf
* You can point to it via char* or a zero-based integer
* @param Buf The buffer to manipulate
* @param ptr char* to zero; use NULL if unused
* @param nThChar zero based pointer into the string; use -1 if unused
* @param nChars how many chars are to be flushed?
* @param PookValue The Character to place into that area
*/
long StrBufPook(StrBuf *Buf, const char* ptr, long nThChar, long nChars, char PookValue)
{
if (Buf == NULL)
return -1;
if (ptr != NULL)
nThChar = ptr - Buf->buf;
if ((nThChar < 0) || (nThChar > Buf->BufUsed))
return -1;
if (nThChar + nChars > Buf->BufUsed)
nChars = Buf->BufUsed - nThChar;
memset(Buf->buf + nThChar, PookValue, nChars);
/* just to be shure... */
Buf->buf[Buf->BufUsed] = 0;
return nChars;
}
/**
* @ingroup StrBuf_Filler
* @brief Append a StringBuffer to the buffer
* @param Buf Buffer to modify
* @param AppendBuf Buffer to copy at the end of our buffer
* @param Offset Should we start copying from an offset?
*/
void StrBufAppendBuf(StrBuf *Buf, const StrBuf *AppendBuf, unsigned long Offset)
{
if ((AppendBuf == NULL) || (AppendBuf->buf == NULL) ||
(Buf == NULL) || (Buf->buf == NULL))
return;
if (Buf->BufSize - Offset < AppendBuf->BufUsed + Buf->BufUsed + 1)
IncreaseBuf(Buf,
(Buf->BufUsed > 0),
AppendBuf->BufUsed + Buf->BufUsed);
memcpy(Buf->buf + Buf->BufUsed,
AppendBuf->buf + Offset,
AppendBuf->BufUsed - Offset);
Buf->BufUsed += AppendBuf->BufUsed - Offset;
Buf->buf[Buf->BufUsed] = '\0';
}
/**
* @ingroup StrBuf_Filler
* @brief Append a C-String to the buffer
* @param Buf Buffer to modify
* @param AppendBuf Buffer to copy at the end of our buffer
* @param AppendSize number of bytes to copy; set to -1 if we should count it in advance
* @param Offset Should we start copying from an offset?
*/
void StrBufAppendBufPlain(StrBuf *Buf, const char *AppendBuf, long AppendSize, unsigned long Offset)
{
long aps;
long BufSizeRequired;
if ((AppendBuf == NULL) || (Buf == NULL))
return;
if (AppendSize < 0 )
aps = strlen(AppendBuf + Offset);
else
aps = AppendSize - Offset;
BufSizeRequired = Buf->BufUsed + aps + 1;
if (Buf->BufSize <= BufSizeRequired)
IncreaseBuf(Buf, (Buf->BufUsed > 0), BufSizeRequired);
memcpy(Buf->buf + Buf->BufUsed,
AppendBuf + Offset,
aps);
Buf->BufUsed += aps;
Buf->buf[Buf->BufUsed] = '\0';
}
/**
* @ingroup StrBuf_Filler
* @brief sprintf like function appending the formated string to the buffer
* vsnprintf version to wrap into own calls
* @param Buf Buffer to extend by format and Params
* @param format printf alike format to add
* @param ap va_list containing the items for format
*/
void StrBufVAppendPrintf(StrBuf *Buf, const char *format, va_list ap)
{
va_list apl;
size_t BufSize;
size_t nWritten;
size_t Offset;
size_t newused;
if ((Buf == NULL) || (format == NULL))
return;
BufSize = Buf->BufSize;
nWritten = Buf->BufSize + 1;
Offset = Buf->BufUsed;
newused = Offset + nWritten;
while (newused >= BufSize) {
va_copy(apl, ap);
nWritten = vsnprintf(Buf->buf + Offset,
Buf->BufSize - Offset,
format, apl);
va_end(apl);
newused = Offset + nWritten;
if (newused >= Buf->BufSize) {
if (IncreaseBuf(Buf, 1, newused) == -1)
return; /* TODO: error handling? */
newused = Buf->BufSize + 1;
}
else {
Buf->BufUsed = Offset + nWritten;
BufSize = Buf->BufSize;
}
}
}
/**
* @ingroup StrBuf_Filler
* @brief sprintf like function appending the formated string to the buffer
* @param Buf Buffer to extend by format and Params
* @param format printf alike format to add
*/
void StrBufAppendPrintf(StrBuf *Buf, const char *format, ...)
{
size_t BufSize;
size_t nWritten;
size_t Offset;
size_t newused;
va_list arg_ptr;
if ((Buf == NULL) || (format == NULL))
return;
BufSize = Buf->BufSize;
nWritten = Buf->BufSize + 1;
Offset = Buf->BufUsed;
newused = Offset + nWritten;
while (newused >= BufSize) {
va_start(arg_ptr, format);
nWritten = vsnprintf(Buf->buf + Buf->BufUsed,
Buf->BufSize - Buf->BufUsed,
format, arg_ptr);
va_end(arg_ptr);
newused = Buf->BufUsed + nWritten;
if (newused >= Buf->BufSize) {
if (IncreaseBuf(Buf, 1, newused) == -1)
return; /* TODO: error handling? */
newused = Buf->BufSize + 1;
}
else {
Buf->BufUsed += nWritten;
BufSize = Buf->BufSize;
}
}
}
/**
* @ingroup StrBuf_Filler
* @brief sprintf like function putting the formated string into the buffer
* @param Buf Buffer to extend by format and Parameters
* @param format printf alike format to add
*/
void StrBufPrintf(StrBuf *Buf, const char *format, ...)
{
size_t nWritten;
va_list arg_ptr;
if ((Buf == NULL) || (format == NULL))
return;
nWritten = Buf->BufSize + 1;
while (nWritten >= Buf->BufSize) {
va_start(arg_ptr, format);
nWritten = vsnprintf(Buf->buf, Buf->BufSize, format, arg_ptr);
va_end(arg_ptr);
if (nWritten >= Buf->BufSize) {
if (IncreaseBuf(Buf, 0, 0) == -1)
return; /* TODO: error handling? */
nWritten = Buf->BufSize + 1;
continue;
}
Buf->BufUsed = nWritten ;
}
}
/**
* @ingroup StrBuf_Filler
* @brief Callback for cURL to append the webserver reply to a buffer
* @param ptr pre-defined by the cURL API; see man 3 curl for mre info
* @param size pre-defined by the cURL API; see man 3 curl for mre info
* @param nmemb pre-defined by the cURL API; see man 3 curl for mre info
* @param stream pre-defined by the cURL API; see man 3 curl for mre info
*/
size_t CurlFillStrBuf_callback(void *ptr, size_t size, size_t nmemb, void *stream)
{
StrBuf *Target;
Target = stream;
if (ptr == NULL)
return 0;
StrBufAppendBufPlain(Target, ptr, size * nmemb, 0);
return size * nmemb;
}
/**
* @ingroup StrBuf
* @brief extracts a substring from Source into dest
* @param dest buffer to place substring into
* @param Source string to copy substring from
* @param Offset chars to skip from start
* @param nChars number of chars to copy
* @returns the number of chars copied; may be different from nChars due to the size of Source
*/
int StrBufSub(StrBuf *dest, const StrBuf *Source, unsigned long Offset, size_t nChars)
{
size_t NCharsRemain;
if (Offset > Source->BufUsed)
{
if (dest != NULL)
FlushStrBuf(dest);
return 0;
}
if (Offset + nChars < Source->BufUsed)
{
if ((nChars >= dest->BufSize) &&
(IncreaseBuf(dest, 0, nChars + 1) == -1))
return 0;
memcpy(dest->buf, Source->buf + Offset, nChars);
dest->BufUsed = nChars;
dest->buf[dest->BufUsed] = '\0';
return nChars;
}
NCharsRemain = Source->BufUsed - Offset;
if ((NCharsRemain >= dest->BufSize) &&
(IncreaseBuf(dest, 0, NCharsRemain + 1) == -1))
return 0;
memcpy(dest->buf, Source->buf + Offset, NCharsRemain);
dest->BufUsed = NCharsRemain;
dest->buf[dest->BufUsed] = '\0';
return NCharsRemain;
}
/**
* @ingroup StrBuf
* @brief Cut nChars from the start of the string
* @param Buf Buffer to modify
* @param nChars how many chars should be skipped?
*/
void StrBufCutLeft(StrBuf *Buf, int nChars)
{
if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
if (nChars >= Buf->BufUsed) {
FlushStrBuf(Buf);
return;
}
memmove(Buf->buf, Buf->buf + nChars, Buf->BufUsed - nChars);
Buf->BufUsed -= nChars;
Buf->buf[Buf->BufUsed] = '\0';
}
/**
* @ingroup StrBuf
* @brief Cut the trailing n Chars from the string
* @param Buf Buffer to modify
* @param nChars how many chars should be trunkated?
*/
void StrBufCutRight(StrBuf *Buf, int nChars)
{
if ((Buf == NULL) || (Buf->BufUsed == 0) || (Buf->buf == NULL))
return;
if (nChars >= Buf->BufUsed) {
FlushStrBuf(Buf);
return;
}
Buf->BufUsed -= nChars;
Buf->buf[Buf->BufUsed] = '\0';
}
/**
* @ingroup StrBuf
* @brief Cut the string after n Chars
* @param Buf Buffer to modify
* @param AfternChars after how many chars should we trunkate the string?
* @param At if non-null and points inside of our string, cut it there.
*/
void StrBufCutAt(StrBuf *Buf, int AfternChars, const char *At)
{
if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
if (At != NULL){
AfternChars = At - Buf->buf;
}
if ((AfternChars < 0) || (AfternChars >= Buf->BufUsed))
return;
Buf->BufUsed = AfternChars;
Buf->buf[Buf->BufUsed] = '\0';
}
/**
* @ingroup StrBuf
* @brief Strip leading and trailing spaces from a string; with premeasured and adjusted length.
* @param Buf the string to modify
*/
void StrBufTrim(StrBuf *Buf)
{
int delta = 0;
if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
while ((Buf->BufUsed > 0) &&
isspace(Buf->buf[Buf->BufUsed - 1]))
{
Buf->BufUsed --;
}
Buf->buf[Buf->BufUsed] = '\0';
if (Buf->BufUsed == 0) return;
while ((Buf->BufUsed > delta) && (isspace(Buf->buf[delta]))){
delta ++;
}
if (delta > 0) StrBufCutLeft(Buf, delta);
}
/**
* @ingroup StrBuf
* @brief changes all spaces in the string (tab, linefeed...) to Blank (0x20)
* @param Buf the string to modify
*/
void StrBufSpaceToBlank(StrBuf *Buf)
{
char *pche, *pch;
if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
pch = Buf->buf;
pche = pch + Buf->BufUsed;
while (pch < pche)
{
if (isspace(*pch))
*pch = ' ';
pch ++;
}
}
void StrBufStripAllBut(StrBuf *Buf, char leftboundary, char rightboundary)
{
const char *pLeft;
const char *pRight;
if ((Buf == NULL) || (Buf->buf == NULL)) {
return;
}
pRight = strchr(Buf->buf, rightboundary);
if (pRight != NULL) {
StrBufCutAt(Buf, 0, pRight);
}
pLeft = strrchr(ChrPtr(Buf), leftboundary);
if (pLeft != NULL) {
StrBufCutLeft(Buf, pLeft - Buf->buf + 1);
}
}
/**
* @ingroup StrBuf_Filler
* @brief uppercase the contents of a buffer
* @param Buf the buffer to translate
*/
void StrBufUpCase(StrBuf *Buf)
{
char *pch, *pche;
if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
pch = Buf->buf;
pche = pch + Buf->BufUsed;
while (pch < pche) {
*pch = toupper(*pch);
pch ++;
}
}
/**
* @ingroup StrBuf_Filler
* @brief lowercase the contents of a buffer
* @param Buf the buffer to translate
*/
void StrBufLowerCase(StrBuf *Buf)
{
char *pch, *pche;
if ((Buf == NULL) || (Buf->BufUsed == 0)) return;
pch = Buf->buf;
pche = pch + Buf->BufUsed;
while (pch < pche) {
*pch = tolower(*pch);
pch ++;
}
}
/*******************************************************************************
* a tokenizer that kills, maims, and destroys *
*******************************************************************************/
/**
* @ingroup StrBuf_Tokenizer
* @brief Replace a token at a given place with a given length by another token with given length
* @param Buf String where to work on
* @param where where inside of the Buf is the search-token
* @param HowLong How long is the token to be replaced
* @param Repl Token to insert at 'where'
* @param ReplLen Length of repl
* @returns -1 if fail else length of resulting Buf
*/
int StrBufReplaceToken(StrBuf *Buf, long where, long HowLong,
const char *Repl, long ReplLen)
{
if ((Buf == NULL) ||
(where > Buf->BufUsed) ||
(where + HowLong > Buf->BufUsed))
return -1;
if (where + ReplLen - HowLong > Buf->BufSize)
if (IncreaseBuf(Buf, 1, Buf->BufUsed + ReplLen) < 0)
return -1;
memmove(Buf->buf + where + ReplLen,
Buf->buf + where + HowLong,
Buf->BufUsed - where - HowLong);
memcpy(Buf->buf + where,
Repl, ReplLen);
Buf->BufUsed += ReplLen - HowLong;
return Buf->BufUsed;
}
/**
* @ingroup StrBuf_Tokenizer
* @brief Counts the numbmer of tokens in a buffer
* @param source String to count tokens in
* @param tok Tokenizer char to count
* @returns numbers of tokenizer chars found
*/
int StrBufNum_tokens(const StrBuf *source, char tok)
{
char *pch, *pche;
long NTokens;
if ((source == NULL) || (source->BufUsed == 0))
return 0;
if ((source->BufUsed == 1) && (*source->buf == tok))
return 2;
NTokens = 1;
pch = source->buf;
pche = pch + source->BufUsed;
while (pch < pche)
{
if (*pch == tok)
NTokens ++;
pch ++;
}
return NTokens;
}
/**
* @ingroup StrBuf_Tokenizer
* @brief a string tokenizer
* @param Source StringBuffer to read into
* @param parmnum n'th Parameter to remove
* @param separator tokenizer character
* @returns -1 if not found, else length of token.
*/
int StrBufRemove_token(StrBuf *Source, int parmnum, char separator)
{
int ReducedBy;
char *d, *s, *end; /* dest, source */
int count = 0;
/* Find desired @parameter */
end = Source->buf + Source->BufUsed;
d = Source->buf;
while ((d <= end) &&
(count < parmnum))
{
/* End of string, bail! */
if (!*d) {
d = NULL;
break;
}
if (*d == separator) {
count++;
}
d++;
}
if ((d == NULL) || (d >= end))
return 0; /* @Parameter not found */
/* Find next @parameter */
s = d;
while ((s <= end) &&
(*s && *s != separator))
{
s++;
}
if (*s == separator)
s++;
ReducedBy = d - s;
/* Hack and slash */
if (s >= end) {
return 0;
}
else if (*s) {
memmove(d, s, Source->BufUsed - (s - Source->buf));
Source->BufUsed += ReducedBy;
Source->buf[Source->BufUsed] = '\0';
}
else if (d == Source->buf) {
*d = 0;
Source->BufUsed = 0;
}
else {
*--d = '\0';
Source->BufUsed += ReducedBy;
}
/*
while (*s) {
*d++ = *s++;
}
*d = 0;
*/
return ReducedBy;
}
int StrBufExtract_tokenFromStr(StrBuf *dest, const char *Source, long SourceLen, int parmnum, char separator)
{
const StrBuf Temp = {
(char*)Source,
SourceLen,
SourceLen,
1
#ifdef SIZE_DEBUG
,
0,
"",
""
#endif
};
return StrBufExtract_token(dest, &Temp, parmnum, separator);
}
/**
* @ingroup StrBuf_Tokenizer
* @brief a string tokenizer
* @param dest Destination StringBuffer
* @param Source StringBuffer to read into
* @param parmnum n'th Parameter to extract
* @param separator tokenizer character
* @returns -1 if not found, else length of token.
*/
int StrBufExtract_token(StrBuf *dest, const StrBuf *Source, int parmnum, char separator)
{
const char *s, *e; //* source * /
int len = 0; //* running total length of extracted string * /
int current_token = 0; //* token currently being processed * /
if (dest != NULL) {
dest->buf[0] = '\0';
dest->BufUsed = 0;
}
else
return(-1);
if ((Source == NULL) || (Source->BufUsed ==0)) {
return(-1);
}
s = Source->buf;
e = s + Source->BufUsed;
//cit_backtrace();
//lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
while ((s < e) && !IsEmptyStr(s)) {
if (*s == separator) {
++current_token;
}
if (len >= dest->BufSize) {
dest->BufUsed = len;
if (IncreaseBuf(dest, 1, -1) < 0) {
dest->BufUsed --;
break;
}
}
if ( (current_token == parmnum) &&
(*s != separator)) {
dest->buf[len] = *s;
++len;
}
else if (current_token > parmnum) {
break;
}
++s;
}
dest->buf[len] = '\0';
dest->BufUsed = len;
if (current_token < parmnum) {
//lprintf (CTDL_DEBUG,"test <!: %s\n", dest);
return(-1);
}
//lprintf (CTDL_DEBUG,"test <: %d; %s\n", len, dest);
return(len);
}
/**
* @ingroup StrBuf_Tokenizer
* @brief a string tokenizer to fetch an integer
* @param Source String containing tokens
* @param parmnum n'th Parameter to extract
* @param separator tokenizer character
* @returns 0 if not found, else integer representation of the token
*/
int StrBufExtract_int(const StrBuf* Source, int parmnum, char separator)
{
StrBuf tmp;
char buf[64];
tmp.buf = buf;
buf[0] = '\0';
tmp.BufSize = 64;
tmp.BufUsed = 0;
tmp.ConstBuf = 1;
if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
return(atoi(buf));
else
return 0;
}
/**
* @ingroup StrBuf_Tokenizer
* @brief a string tokenizer to fetch a long integer
* @param Source String containing tokens
* @param parmnum n'th Parameter to extract
* @param separator tokenizer character
* @returns 0 if not found, else long integer representation of the token
*/
long StrBufExtract_long(const StrBuf* Source, int parmnum, char separator)
{
StrBuf tmp;
char buf[64];
tmp.buf = buf;
buf[0] = '\0';
tmp.BufSize = 64;
tmp.BufUsed = 0;
tmp.ConstBuf = 1;
if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0)
return(atoi(buf));
else
return 0;
}
/**
* @ingroup StrBuf_Tokenizer
* @brief a string tokenizer to fetch an unsigned long
* @param Source String containing tokens
* @param parmnum n'th Parameter to extract
* @param separator tokenizer character
* @returns 0 if not found, else unsigned long representation of the token
*/
unsigned long StrBufExtract_unsigned_long(const StrBuf* Source, int parmnum, char separator)
{
StrBuf tmp;
char buf[64];
char *pnum;
tmp.buf = buf;
buf[0] = '\0';
tmp.BufSize = 64;
tmp.BufUsed = 0;
tmp.ConstBuf = 1;
if (StrBufExtract_token(&tmp, Source, parmnum, separator) > 0) {
pnum = &buf[0];
if (*pnum == '-')
pnum ++;
return (unsigned long) atol(pnum);
}
else
return 0;
}
/**
* @ingroup StrBuf_NextTokenizer
* @brief a string tokenizer; Bounds checker
* function to make shure whether StrBufExtract_NextToken and friends have reached the end of the string.
* @param Source our tokenbuffer
* @param pStart the token iterator pointer to inspect
* @returns whether the revolving pointer is inside of the search range
*/
int StrBufHaveNextToken(const StrBuf *Source, const char **pStart)
{
if ((Source == NULL) ||
(*pStart == StrBufNOTNULL) ||
(Source->BufUsed == 0))
{
return 0;
}
if (*pStart == NULL)
{
return 1;
}
else if (*pStart > Source->buf + Source->BufUsed)
{
return 0;
}
else if (*pStart <= Source->buf)
{
return 0;
}
return 1;
}
/**
* @ingroup StrBuf_NextTokenizer
* @brief a string tokenizer
* @param dest Destination StringBuffer
* @param Source StringBuffer to read into
* @param pStart pointer to the end of the last token. Feed with NULL on start.
* @param separator tokenizer
* @returns -1 if not found, else length of token.
*/
int StrBufExtract_NextToken(StrBuf *dest, const StrBuf *Source, const char **pStart, char separator)
{
const char *s; /* source */
const char *EndBuffer; /* end stop of source buffer */
int current_token = 0; /* token currently being processed */
int len = 0; /* running total length of extracted string */
if ((Source == NULL) ||
(Source->BufUsed == 0) )
{
*pStart = StrBufNOTNULL;
if (dest != NULL)
FlushStrBuf(dest);
return -1;
}
EndBuffer = Source->buf + Source->BufUsed;
if (dest != NULL)
{
dest->buf[0] = '\0';
dest->BufUsed = 0;
}
else
{
*pStart = EndBuffer + 1;
return -1;
}
if (*pStart == NULL)
{
*pStart = Source->buf; /* we're starting to examine this buffer. */
}
else if ((*pStart < Source->buf) ||
(*pStart > EndBuffer ) )
{
return -1; /* no more tokens to find. */
}
s = *pStart;
/* start to find the next token */
while ((s <= EndBuffer) &&
(current_token == 0) )
{
if (*s == separator)
{
/* we found the next token */
++current_token;
}
if (len >= dest->BufSize)
{
/* our Dest-buffer isn't big enough, increase it. */
dest->BufUsed = len;
if (IncreaseBuf(dest, 1, -1) < 0) {
/* WHUT? no more mem? bail out. */
s = EndBuffer;
dest->BufUsed --;
break;
}
}
if ( (current_token == 0 ) && /* are we in our target token? */
(!IsEmptyStr(s) ) &&
(separator != *s) ) /* don't copy the token itself */
{
dest->buf[len] = *s; /* Copy the payload */
++len; /* remember the bigger size. */
}
++s;
}
/* did we reach the end? */
if ((s > EndBuffer)) {
EndBuffer = StrBufNOTNULL;
*pStart = EndBuffer;
}
else {
*pStart = s; /* remember the position for the next run */
}
/* sanitize our extracted token */
dest->buf[len] = '\0';
dest->BufUsed = len;
return (len);
}
/**
* @ingroup StrBuf_NextTokenizer
* @brief a string tokenizer
* @param Source StringBuffer to read from
* @param pStart pointer to the end of the last token. Feed with NULL.
* @param separator tokenizer character
* @param nTokens number of tokens to fastforward over
* @returns -1 if not found, else length of token.
*/
int StrBufSkip_NTokenS(const StrBuf *Source, const char **pStart, char separator, int nTokens)
{
const char *s, *EndBuffer; //* source * /
int len = 0; //* running total length of extracted string * /
int current_token = 0; //* token currently being processed * /
if ((Source == NULL) ||
(Source->BufUsed ==0)) {
return(-1);
}
if (nTokens == 0)
return Source->BufUsed;
if (*pStart == NULL)
*pStart = Source->buf;
EndBuffer = Source->buf + Source->BufUsed;
if ((*pStart < Source->buf) ||
(*pStart > EndBuffer)) {
return (-1);
}
s = *pStart;
//cit_backtrace();
//lprintf (CTDL_DEBUG, "test >: n: %d sep: %c source: %s \n willi \n", parmnum, separator, source);
while ((s < EndBuffer) && !IsEmptyStr(s)) {
if (*s == separator) {
++current_token;
}
if (current_token >= nTokens) {
break;
}
++s;
}
*pStart = s;
(*pStart) ++;
return(len);
}
/**
* @ingroup StrBuf_NextTokenizer
* @brief a string tokenizer to fetch an integer
* @param Source StringBuffer to read from
* @param pStart Cursor on the tokenstring
* @param separator tokenizer character
* @returns 0 if not found, else integer representation of the token
*/
int StrBufExtractNext_int(const StrBuf* Source, const char **pStart, char separator)
{
StrBuf tmp;
char buf[64];
tmp.buf = buf;
buf[0] = '\0';
tmp.BufSize = 64;
tmp.BufUsed = 0;
tmp.ConstBuf = 1;
if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
return(atoi(buf));
else
return 0;
}
/**
* @ingroup StrBuf_NextTokenizer
* @brief a string tokenizer to fetch a long integer
* @param Source StringBuffer to read from
* @param pStart Cursor on the tokenstring
* @param separator tokenizer character
* @returns 0 if not found, else long integer representation of the token
*/
long StrBufExtractNext_long(const StrBuf* Source, const char **pStart, char separator)
{
StrBuf tmp;
char buf[64];
tmp.buf = buf;
buf[0] = '\0';
tmp.BufSize = 64;
tmp.BufUsed = 0;
tmp.ConstBuf = 1;
if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0)
return(atoi(buf));
else
return 0;
}
/**
* @ingroup StrBuf_NextTokenizer
* @brief a string tokenizer to fetch an unsigned long
* @param Source StringBuffer to read from
* @param pStart Cursor on the tokenstring
* @param separator tokenizer character
* @returns 0 if not found, else unsigned long representation of the token
*/
unsigned long StrBufExtractNext_unsigned_long(const StrBuf* Source, const char **pStart, char separator)
{
StrBuf tmp;
char buf[64];
char *pnum;
tmp.buf = buf;
buf[0] = '\0';
tmp.BufSize = 64;
tmp.BufUsed = 0;
tmp.ConstBuf = 1;
if (StrBufExtract_NextToken(&tmp, Source, pStart, separator) > 0) {
pnum = &buf[0];
if (*pnum == '-')
pnum ++;
return (unsigned long) atol(pnum);
}
else
return 0;
}
/*******************************************************************************
* Escape Appending *
*******************************************************************************/
/**
* @ingroup StrBuf_DeEnCoder
* @brief Escape a string for feeding out as a URL while appending it to a Buffer
* @param OutBuf the output buffer
* @param In Buffer to encode
* @param PlainIn way in from plain old c strings
*/
void StrBufUrlescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
{
const char *pch, *pche;
char *pt, *pte;
int len;
if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
return;
if (PlainIn != NULL) {
len = strlen(PlainIn);
pch = PlainIn;
pche = pch + len;
}
else {
pch = In->buf;
pche = pch + In->BufUsed;
len = In->BufUsed;
}
if (len == 0)
return;
pt = OutBuf->buf + OutBuf->BufUsed;
pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
while (pch < pche) {
if (pt >= pte) {
IncreaseBuf(OutBuf, 1, -1);
pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
pt = OutBuf->buf + OutBuf->BufUsed;
}
if((*pch >= 'a' && *pch <= 'z') ||
(*pch >= '@' && *pch <= 'Z') || /* @ A-Z */
(*pch >= '0' && *pch <= ':') || /* 0-9 : */
(*pch == '!') || (*pch == '_') ||
(*pch == ',') || (*pch == '.'))
{
*(pt++) = *(pch++);
OutBuf->BufUsed++;
}
else {
*pt = '%';
*(pt + 1) = HexList[(unsigned char)*pch][0];
*(pt + 2) = HexList[(unsigned char)*pch][1];
pt += 3;
OutBuf->BufUsed += 3;
pch ++;
}
}
*pt = '\0';
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief Escape a string for feeding out as a the username/password part of an URL while appending it to a Buffer
* @param OutBuf the output buffer
* @param In Buffer to encode
* @param PlainIn way in from plain old c strings
*/
void StrBufUrlescUPAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
{
const char *pch, *pche;
char *pt, *pte;
int len;
if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
return;
if (PlainIn != NULL) {
len = strlen(PlainIn);
pch = PlainIn;
pche = pch + len;
}
else {
pch = In->buf;
pche = pch + In->BufUsed;
len = In->BufUsed;
}
if (len == 0)
return;
pt = OutBuf->buf + OutBuf->BufUsed;
pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
while (pch < pche) {
if (pt >= pte) {
IncreaseBuf(OutBuf, 1, -1);
pte = OutBuf->buf + OutBuf->BufSize - 4; /**< we max append 3 chars at once plus the \0 */
pt = OutBuf->buf + OutBuf->BufUsed;
}
if((*pch >= 'a' && *pch <= 'z') ||
(*pch >= 'A' && *pch <= 'Z') || /* A-Z */
(*pch >= '0' && *pch <= ':') || /* 0-9 : */
(*pch == '!') || (*pch == '_') ||
(*pch == ',') || (*pch == '.'))
{
*(pt++) = *(pch++);
OutBuf->BufUsed++;
}
else {
*pt = '%';
*(pt + 1) = HexList[(unsigned char)*pch][0];
*(pt + 2) = HexList[(unsigned char)*pch][1];
pt += 3;
OutBuf->BufUsed += 3;
pch ++;
}
}
*pt = '\0';
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief append a string with characters having a special meaning in xml encoded to the buffer
* @param OutBuf the output buffer
* @param In Buffer to encode
* @param PlainIn way in from plain old c strings
* @param PlainInLen way in from plain old c strings; maybe you've got binary data or know the length?
* @param OverrideLowChars should chars < 0x20 be replaced by _ or escaped as xml entity?
*/
void StrBufXMLEscAppend(StrBuf *OutBuf,
const StrBuf *In,
const char *PlainIn,
long PlainInLen,
int OverrideLowChars)
{
const char *pch, *pche;
char *pt, *pte;
int IsUtf8Sequence;
int len;
if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
return;
if (PlainIn != NULL) {
if (PlainInLen < 0)
len = strlen((const char*)PlainIn);
else
len = PlainInLen;
pch = PlainIn;
pche = pch + len;
}
else {
pch = (const char*)In->buf;
pche = pch + In->BufUsed;
len = In->BufUsed;
}
if (len == 0)
return;
pt = OutBuf->buf + OutBuf->BufUsed;
/**< we max append 6 chars at once plus the \0 */
pte = OutBuf->buf + OutBuf->BufSize - 6;
while (pch < pche) {
if (pt >= pte) {
OutBuf->BufUsed = pt - OutBuf->buf;
IncreaseBuf(OutBuf, 1, -1);
pte = OutBuf->buf + OutBuf->BufSize - 6;
/**< we max append 3 chars at once plus the \0 */
pt = OutBuf->buf + OutBuf->BufUsed;
}
if (*pch == '<') {
memcpy(pt, HKEY("<"));
pt += 4;
pch ++;
}
else if (*pch == '>') {
memcpy(pt, HKEY(">"));
pt += 4;
pch ++;
}
else if (*pch == '&') {
memcpy(pt, HKEY("&"));
pt += 5;
pch++;
}
else if ((*pch >= 0x20) && (*pch <= 0x7F)) {
*pt = *pch;
pt++; pch++;
}
else {
IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(pch, pche);
if (IsUtf8Sequence)
{
while ((IsUtf8Sequence > 0) &&
(pch < pche))
{
*pt = *pch;
pt ++;
pch ++;
--IsUtf8Sequence;
}
}
else
{
*pt = '&';
pt++;
*pt = HexList[*(unsigned char*)pch][0];
pt ++;
*pt = HexList[*(unsigned char*)pch][1];
pt ++; pch ++;
*pt = '&';
pt++;
pch ++;
}
}
}
*pt = '\0';
OutBuf->BufUsed = pt - OutBuf->buf;
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief append a string in hex encoding to the buffer
* @param OutBuf the output buffer
* @param In Buffer to encode
* @param PlainIn way in from plain old c strings
* @param PlainInLen way in from plain old c strings; maybe you've got binary data or know the length?
*/
void StrBufHexEscAppend(StrBuf *OutBuf, const StrBuf *In, const unsigned char *PlainIn, long PlainInLen)
{
const unsigned char *pch, *pche;
char *pt, *pte;
int len;
if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
return;
if (PlainIn != NULL) {
if (PlainInLen < 0)
len = strlen((const char*)PlainIn);
else
len = PlainInLen;
pch = PlainIn;
pche = pch + len;
}
else {
pch = (const unsigned char*)In->buf;
pche = pch + In->BufUsed;
len = In->BufUsed;
}
if (len == 0)
return;
pt = OutBuf->buf + OutBuf->BufUsed;
pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
while (pch < pche) {
if (pt >= pte) {
IncreaseBuf(OutBuf, 1, -1);
pte = OutBuf->buf + OutBuf->BufSize - 3; /**< we max append 3 chars at once plus the \0 */
pt = OutBuf->buf + OutBuf->BufUsed;
}
*pt = HexList[*pch][0];
pt ++;
*pt = HexList[*pch][1];
pt ++; pch ++; OutBuf->BufUsed += 2;
}
*pt = '\0';
}
void StrBufBase64Append(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn, long PlainInLen, int linebreaks)
{
const char *pch;
char *pt;
int len;
long ExpectLen;
if (((In == NULL) && (PlainIn == NULL)) || (OutBuf == NULL) )
return;
if (PlainIn != NULL) {
if (PlainInLen < 0)
len = strlen(PlainIn);
else
len = PlainInLen;
pch = PlainIn;
}
else {
pch = In->buf;
len = In->BufUsed;
}
if (len == 0)
return;
ExpectLen = ((len * 134) / 100) + OutBuf->BufUsed;
if (ExpectLen > OutBuf->BufSize)
if (IncreaseBuf(OutBuf, 1, ExpectLen) < ExpectLen)
return;
pt = OutBuf->buf + OutBuf->BufUsed;
len = CtdlEncodeBase64(pt, pch, len, linebreaks);
pt += len;
OutBuf->BufUsed += len;
*pt = '\0';
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief append a string in hex encoding to the buffer
* @param OutBuf the output buffer
* @param In Buffer to encode
* @param PlainIn way in from plain old c strings
*/
void StrBufHexescAppend(StrBuf *OutBuf, const StrBuf *In, const char *PlainIn)
{
StrBufHexEscAppend(OutBuf, In, (const unsigned char*) PlainIn, -1);
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief Append a string, escaping characters which have meaning in HTML.
*
* @param Target target buffer
* @param Source source buffer; set to NULL if you just have a C-String
* @param PlainIn Plain-C string to append; set to NULL if unused
* @param nbsp If nonzero, spaces are converted to non-breaking spaces.
* @param nolinebreaks if set to 1, linebreaks are removed from the string.
* if set to 2, linebreaks are replaced by <br/>
*/
long StrEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
{
const char *aptr, *eiptr;
char *bptr, *eptr;
long len;
if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
return -1;
if (PlainIn != NULL) {
aptr = PlainIn;
len = strlen(PlainIn);
eiptr = aptr + len;
}
else {
aptr = Source->buf;
eiptr = aptr + Source->BufUsed;
len = Source->BufUsed;
}
if (len == 0)
return -1;
bptr = Target->buf + Target->BufUsed;
eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
while (aptr < eiptr){
if(bptr >= eptr) {
IncreaseBuf(Target, 1, -1);
eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
bptr = Target->buf + Target->BufUsed;
}
if (*aptr == '<') {
memcpy(bptr, "<", 4);
bptr += 4;
Target->BufUsed += 4;
}
else if (*aptr == '>') {
memcpy(bptr, ">", 4);
bptr += 4;
Target->BufUsed += 4;
}
else if (*aptr == '&') {
memcpy(bptr, "&", 5);
bptr += 5;
Target->BufUsed += 5;
}
else if (*aptr == '"') {
memcpy(bptr, """, 6);
bptr += 6;
Target->BufUsed += 6;
}
else if (*aptr == '\'') {
memcpy(bptr, "'", 5);
bptr += 5;
Target->BufUsed += 5;
}
else if (*aptr == LB) {
*bptr = '<';
bptr ++;
Target->BufUsed ++;
}
else if (*aptr == RB) {
*bptr = '>';
bptr ++;
Target->BufUsed ++;
}
else if (*aptr == QU) {
*bptr ='"';
bptr ++;
Target->BufUsed ++;
}
else if ((*aptr == 32) && (nbsp == 1)) {
memcpy(bptr, " ", 6);
bptr += 6;
Target->BufUsed += 6;
}
else if ((*aptr == '\n') && (nolinebreaks == 1)) {
*bptr='\0'; /* nothing */
}
else if ((*aptr == '\n') && (nolinebreaks == 2)) {
memcpy(bptr, "<br/>", 11);
bptr += 11;
Target->BufUsed += 11;
}
else if ((*aptr == '\r') && (nolinebreaks != 0)) {
*bptr='\0'; /* nothing */
}
else{
*bptr = *aptr;
bptr++;
Target->BufUsed ++;
}
aptr ++;
}
*bptr = '\0';
if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
return -1;
return Target->BufUsed;
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief Append a string, escaping characters which have meaning in HTML.
* Converts linebreaks into blanks; escapes single quotes
* @param Target target buffer
* @param Source source buffer; set to NULL if you just have a C-String
* @param PlainIn Plain-C string to append; set to NULL if unused
*/
void StrMsgEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
{
const char *aptr, *eiptr;
char *tptr, *eptr;
long len;
if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
return ;
if (PlainIn != NULL) {
aptr = PlainIn;
len = strlen(PlainIn);
eiptr = aptr + len;
}
else {
aptr = Source->buf;
eiptr = aptr + Source->BufUsed;
len = Source->BufUsed;
}
if (len == 0)
return;
eptr = Target->buf + Target->BufSize - 8;
tptr = Target->buf + Target->BufUsed;
while (aptr < eiptr){
if(tptr >= eptr) {
IncreaseBuf(Target, 1, -1);
eptr = Target->buf + Target->BufSize - 8;
tptr = Target->buf + Target->BufUsed;
}
if (*aptr == '\n') {
*tptr = ' ';
Target->BufUsed++;
}
else if (*aptr == '\r') {
*tptr = ' ';
Target->BufUsed++;
}
else if (*aptr == '\'') {
*(tptr++) = '&';
*(tptr++) = '#';
*(tptr++) = '3';
*(tptr++) = '9';
*tptr = ';';
Target->BufUsed += 5;
} else {
*tptr = *aptr;
Target->BufUsed++;
}
tptr++; aptr++;
}
*tptr = '\0';
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief Append a string, escaping characters which have meaning in ICAL.
* [\n,]
* @param Target target buffer
* @param Source source buffer; set to NULL if you just have a C-String
* @param PlainIn Plain-C string to append; set to NULL if unused
*/
void StrIcalEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
{
const char *aptr, *eiptr;
char *tptr, *eptr;
long len;
if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
return ;
if (PlainIn != NULL) {
aptr = PlainIn;
len = strlen(PlainIn);
eiptr = aptr + len;
}
else {
aptr = Source->buf;
eiptr = aptr + Source->BufUsed;
len = Source->BufUsed;
}
if (len == 0)
return;
eptr = Target->buf + Target->BufSize - 8;
tptr = Target->buf + Target->BufUsed;
while (aptr < eiptr){
if(tptr + 3 >= eptr) {
IncreaseBuf(Target, 1, -1);
eptr = Target->buf + Target->BufSize - 8;
tptr = Target->buf + Target->BufUsed;
}
if (*aptr == '\n') {
*tptr = '\\';
Target->BufUsed++;
tptr++;
*tptr = 'n';
Target->BufUsed++;
}
else if (*aptr == '\r') {
*tptr = '\\';
Target->BufUsed++;
tptr++;
*tptr = 'r';
Target->BufUsed++;
}
else if (*aptr == ',') {
*tptr = '\\';
Target->BufUsed++;
tptr++;
*tptr = ',';
Target->BufUsed++;
} else {
*tptr = *aptr;
Target->BufUsed++;
}
tptr++; aptr++;
}
*tptr = '\0';
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief Append a string, escaping characters which have meaning in JavaScript strings .
*
* @param Target target buffer
* @param Source source buffer; set to NULL if you just have a C-String
* @param PlainIn Plain-C string to append; set to NULL if unused
* @returns size of result or -1
*/
long StrECMAEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn)
{
const char *aptr, *eiptr;
char *bptr, *eptr;
long len;
int IsUtf8Sequence;
if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
return -1;
if (PlainIn != NULL) {
aptr = PlainIn;
len = strlen(PlainIn);
eiptr = aptr + len;
}
else {
aptr = Source->buf;
eiptr = aptr + Source->BufUsed;
len = Source->BufUsed;
}
if (len == 0)
return -1;
bptr = Target->buf + Target->BufUsed;
eptr = Target->buf + Target->BufSize - 7; /* our biggest unit to put in... */
while (aptr < eiptr){
if(bptr >= eptr) {
IncreaseBuf(Target, 1, -1);
eptr = Target->buf + Target->BufSize - 7; /* our biggest unit to put in... */
bptr = Target->buf + Target->BufUsed;
}
switch (*aptr) {
case '\n':
memcpy(bptr, HKEY("\\n"));
bptr += 2;
Target->BufUsed += 2;
break;
case '\r':
memcpy(bptr, HKEY("\\r"));
bptr += 2;
Target->BufUsed += 2;
break;
case '"':
*bptr = '\\';
bptr ++;
*bptr = '"';
bptr ++;
Target->BufUsed += 2;
break;
case '\\':
if ((*(aptr + 1) == 'u') &&
isxdigit(*(aptr + 2)) &&
isxdigit(*(aptr + 3)) &&
isxdigit(*(aptr + 4)) &&
isxdigit(*(aptr + 5)))
{ /* oh, a unicode escaper. let it pass through. */
memcpy(bptr, aptr, 6);
aptr += 5;
bptr +=6;
Target->BufUsed += 6;
}
else
{
*bptr = '\\';
bptr ++;
*bptr = '\\';
bptr ++;
Target->BufUsed += 2;
}
break;
case '\b':
*bptr = '\\';
bptr ++;
*bptr = 'b';
bptr ++;
Target->BufUsed += 2;
break;
case '\f':
*bptr = '\\';
bptr ++;
*bptr = 'f';
bptr ++;
Target->BufUsed += 2;
break;
case '\t':
*bptr = '\\';
bptr ++;
*bptr = 't';
bptr ++;
Target->BufUsed += 2;
break;
default:
IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
while (IsUtf8Sequence > 0){
*bptr = *aptr;
Target->BufUsed ++;
if (--IsUtf8Sequence)
aptr++;
bptr++;
}
}
aptr ++;
}
*bptr = '\0';
if ((bptr == eptr - 1 ) && !IsEmptyStr(aptr) )
return -1;
return Target->BufUsed;
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief Append a string, escaping characters which have meaning in HTML + json.
*
* @param Target target buffer
* @param Source source buffer; set to NULL if you just have a C-String
* @param PlainIn Plain-C string to append; set to NULL if unused
* @param nbsp If nonzero, spaces are converted to non-breaking spaces.
* @param nolinebreaks if set to 1, linebreaks are removed from the string.
* if set to 2, linebreaks are replaced by <br/>
*/
long StrHtmlEcmaEscAppend(StrBuf *Target, const StrBuf *Source, const char *PlainIn, int nbsp, int nolinebreaks)
{
const char *aptr, *eiptr;
char *bptr, *eptr;
long len;
int IsUtf8Sequence = 0;
if (((Source == NULL) && (PlainIn == NULL)) || (Target == NULL) )
return -1;
if (PlainIn != NULL) {
aptr = PlainIn;
len = strlen(PlainIn);
eiptr = aptr + len;
}
else {
aptr = Source->buf;
eiptr = aptr + Source->BufUsed;
len = Source->BufUsed;
}
if (len == 0)
return -1;
bptr = Target->buf + Target->BufUsed;
eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
while (aptr < eiptr){
if(bptr >= eptr) {
IncreaseBuf(Target, 1, -1);
eptr = Target->buf + Target->BufSize - 11; /* our biggest unit to put in... */
bptr = Target->buf + Target->BufUsed;
}
switch (*aptr) {
case '<':
memcpy(bptr, HKEY("<"));
bptr += 4;
Target->BufUsed += 4;
break;
case '>':
memcpy(bptr, HKEY(">"));
bptr += 4;
Target->BufUsed += 4;
break;
case '&':
memcpy(bptr, HKEY("&"));
bptr += 5;
Target->BufUsed += 5;
break;
case LB:
*bptr = '<';
bptr ++;
Target->BufUsed ++;
break;
case RB:
*bptr = '>';
bptr ++;
Target->BufUsed ++;
break;
case '\n':
switch (nolinebreaks) {
case 1:
*bptr='\0'; /* nothing */
break;
case 2:
memcpy(bptr, HKEY("<br/>"));
bptr += 11;
Target->BufUsed += 11;
break;
default:
memcpy(bptr, HKEY("\\n"));
bptr += 2;
Target->BufUsed += 2;
}
break;
case '\r':
switch (nolinebreaks) {
case 1:
case 2:
*bptr='\0'; /* nothing */
break;
default:
memcpy(bptr, HKEY("\\r"));
bptr += 2;
Target->BufUsed += 2;
break;
}
break;
case '"':
case QU:
*bptr = '\\';
bptr ++;
*bptr = '"';
bptr ++;
Target->BufUsed += 2;
break;
case '\\':
if ((*(aptr + 1) == 'u') &&
isxdigit(*(aptr + 2)) &&
isxdigit(*(aptr + 3)) &&
isxdigit(*(aptr + 4)) &&
isxdigit(*(aptr + 5)))
{ /* oh, a unicode escaper. let it pass through. */
memcpy(bptr, aptr, 6);
aptr += 5;
bptr +=6;
Target->BufUsed += 6;
}
else
{
*bptr = '\\';
bptr ++;
*bptr = '\\';
bptr ++;
Target->BufUsed += 2;
}
break;
case '\b':
*bptr = '\\';
bptr ++;
*bptr = 'b';
bptr ++;
Target->BufUsed += 2;
break;
case '\f':
*bptr = '\\';
bptr ++;
*bptr = 'f';
bptr ++;
Target->BufUsed += 2;
break;
case '\t':
*bptr = '\\';
bptr ++;
*bptr = 't';
bptr ++;
Target->BufUsed += 2;
break;
case 32:
if (nbsp == 1) {
memcpy(bptr, HKEY(" "));
bptr += 6;
Target->BufUsed += 6;
break;
}
default:
IsUtf8Sequence = Ctdl_GetUtf8SequenceLength(aptr, eiptr);
while (IsUtf8Sequence > 0){
*bptr = *aptr;
Target->BufUsed ++;
if (--IsUtf8Sequence)
aptr++;
bptr++;
}
}
aptr ++;
}
*bptr = '\0';
if ((bptr = eptr - 1 ) && !IsEmptyStr(aptr) )
return -1;
return Target->BufUsed;
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief replace all non-Ascii characters by another
* @param Buf buffer to inspect
* @param repl charater to stamp over non ascii chars
*/
void StrBufAsciify(StrBuf *Buf, const char repl)
{
long offset;
for (offset = 0; offset < Buf->BufUsed; offset ++)
if (!isascii(Buf->buf[offset]))
Buf->buf[offset] = repl;
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief unhide special chars hidden to the HTML escaper
* @param target buffer to put the unescaped string in
* @param source buffer to unescape
*/
void StrBufEUid_unescapize(StrBuf *target, const StrBuf *source)
{
int a, b, len;
char hex[3];
if ((source == NULL) || (target == NULL) || (target->buf == NULL))
{
return;
}
if (target != NULL)
FlushStrBuf(target);
len = source->BufUsed;
for (a = 0; a < len; ++a) {
if (target->BufUsed >= target->BufSize)
IncreaseBuf(target, 1, -1);
if (source->buf[a] == '=') {
hex[0] = source->buf[a + 1];
hex[1] = source->buf[a + 2];
hex[2] = 0;
b = 0;
sscanf(hex, "%02x", &b);
target->buf[target->BufUsed] = b;
target->buf[++target->BufUsed] = 0;
a += 2;
}
else {
target->buf[target->BufUsed] = source->buf[a];
target->buf[++target->BufUsed] = 0;
}
}
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief hide special chars from the HTML escapers and friends
* @param target buffer to put the escaped string in
* @param source buffer to escape
*/
void StrBufEUid_escapize(StrBuf *target, const StrBuf *source)
{
int i, len;
if (target != NULL)
FlushStrBuf(target);
if ((source == NULL) || (target == NULL) || (target->buf == NULL))
{
return;
}
len = source->BufUsed;
for (i=0; i<len; ++i) {
if (target->BufUsed + 4 >= target->BufSize)
IncreaseBuf(target, 1, -1);
if ( (isalnum(source->buf[i])) ||
(source->buf[i]=='-') ||
(source->buf[i]=='_') ) {
target->buf[target->BufUsed++] = source->buf[i];
}
else {
sprintf(&target->buf[target->BufUsed],
"=%02X",
(0xFF &source->buf[i]));
target->BufUsed += 3;
}
}
target->buf[target->BufUsed + 1] = '\0';
}
/*******************************************************************************
* Quoted Printable de/encoding *
*******************************************************************************/
/**
* @ingroup StrBuf_DeEnCoder
* @brief decode a buffer from base 64 encoding; destroys original
* @param Buf Buffor to transform
*/
int StrBufDecodeBase64(StrBuf *Buf)
{
char *xferbuf;
size_t siz;
if (Buf == NULL)
return -1;
xferbuf = (char*) malloc(Buf->BufSize);
if (xferbuf == NULL)
return -1;
*xferbuf = '\0';
siz = CtdlDecodeBase64(xferbuf,
Buf->buf,
Buf->BufUsed);
free(Buf->buf);
Buf->buf = xferbuf;
Buf->BufUsed = siz;
Buf->buf[Buf->BufUsed] = '\0';
return siz;
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief decode a buffer from base 64 encoding; expects targetbuffer
* @param BufIn Buffor to transform
* @param BufOut Buffer to put result into
*/
int StrBufDecodeBase64To(const StrBuf *BufIn, StrBuf *BufOut)
{
if ((BufIn == NULL) || (BufOut == NULL))
return -1;
if (BufOut->BufSize < BufIn->BufUsed)
IncreaseBuf(BufOut, 0, BufIn->BufUsed);
BufOut->BufUsed = CtdlDecodeBase64(BufOut->buf,
BufIn->buf,
BufIn->BufUsed);
return BufOut->BufUsed;
}
typedef struct __z_enc_stream {
StrBuf OutBuf;
z_stream zstream;
} z_enc_stream;
vStreamT *StrBufNewStreamContext(eStreamType type, const char **Err)
{
base64_decodestate *state;;
*Err = NULL;
switch (type)
{
case eBase64Decode:
case eBase64Encode:
state = (base64_decodestate*) malloc(sizeof(base64_decodestate));
base64_init_decodestate(state);
return (vStreamT*) state;
break;
case eZLibDecode:
{
z_enc_stream *stream;
int err;
stream = (z_enc_stream *) malloc(sizeof(z_enc_stream));
memset(stream, 0, sizeof(z_enc_stream));
stream->OutBuf.BufSize = 4*SIZ; /// TODO 64
stream->OutBuf.buf = (char*)malloc(stream->OutBuf.BufSize);
err = inflateInit(&stream->zstream);
if (err != Z_OK) {
StrBufDestroyStreamContext(type, (vStreamT**) &stream, Err);
*Err = zError(err);
return NULL;
}
return (vStreamT*) stream;
}
case eZLibEncode:
{
z_enc_stream *stream;
int err;
stream = (z_enc_stream *) malloc(sizeof(z_enc_stream));
memset(stream, 0, sizeof(z_enc_stream));
stream->OutBuf.BufSize = 4*SIZ; /// todo 64
stream->OutBuf.buf = (char*)malloc(stream->OutBuf.BufSize);
/* write gzip header */
stream->OutBuf.BufUsed = snprintf
(stream->OutBuf.buf,
stream->OutBuf.BufSize,
"%c%c%c%c%c%c%c%c%c%c",
gz_magic[0], gz_magic[1], Z_DEFLATED,
0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
OS_CODE);
err = deflateInit2(&stream->zstream,
ZLibCompressionRatio,
Z_DEFLATED,
-MAX_WBITS,
DEF_MEM_LEVEL,
Z_DEFAULT_STRATEGY);
if (err != Z_OK) {
StrBufDestroyStreamContext(type, (vStreamT**) &stream, Err);
*Err = zError(err);
return NULL;
}
return (vStreamT*) stream;
}
case eEmtyCodec:
/// TODO
break;
}
return NULL;
}
int StrBufDestroyStreamContext(eStreamType type, vStreamT **vStream, const char **Err)
{
int err;
int rc = 0;
*Err = NULL;
if ((vStream == NULL) || (*vStream==NULL)) {
*Err = strerror(EINVAL);
return EINVAL;
}
switch (type)
{
case eBase64Encode:
case eBase64Decode:
free(*vStream);
*vStream = NULL;
break;
case eZLibDecode:
{
z_enc_stream *stream = (z_enc_stream *)*vStream;
(void)inflateEnd(&stream->zstream);
free(stream->OutBuf.buf);
free(stream);
}
case eZLibEncode:
{
z_enc_stream *stream = (z_enc_stream *)*vStream;
err = deflateEnd(&stream->zstream);
if (err != Z_OK) {
*Err = zError(err);
rc = -1;
}
free(stream->OutBuf.buf);
free(stream);
*vStream = NULL;
break;
}
case eEmtyCodec:
break; /// TODO
}
return rc;
}
int StrBufStreamTranscode(eStreamType type, IOBuffer *Target, IOBuffer *In, const char* pIn, long pInLen, vStreamT *vStream, int LastChunk, const char **Err)
{
int rc = 0;
switch (type)
{
case eBase64Encode:
{
/// TODO
/*
// base64_decodestate *state = (base64_decodestate*)vStream;
long ExpectLen;
if (In != NULL)
{
pIn = In->buf;
pInLen = In->BufUsed;
}
if ((In == NULL) || (vStream == NULL))
return;
ExpectLen = (pInLen / 4) * 3;
if (Target->BufSize - Target->BufUsed < ExpectLen)
{
IncreaseBuf(Target, 1, Target->BufUsed + ExpectLen + 1);
}
//// ExpectLen = base64_encode_block(pIn, pInLen, Target->buf + Target->BufUsed, state);
Target->BufUsed += ExpectLen;
Target->buf[Target->BufUsed] = '\0';
*/
}
break;
case eBase64Decode:
{
/*
base64_decodestate *state = (base64_decodestate *)vStream;
long ExpectLen;
if (In != NULL)
{
pIn = In->buf;
pInLen = In->BufUsed;
}
if ((pIn == NULL) || (vStream == NULL))
return;
ExpectLen = (pInLen / 4) * 3;
if (Target->BufSize - Target->BufUsed < ExpectLen)
{
IncreaseBuf(Target, 1, Target->BufUsed + ExpectLen + 1);
}
ExpectLen = base64_decode_block(pIn, pInLen, Target->buf + Target->BufUsed, state);
Target->BufUsed += ExpectLen;
Target->buf[Target->BufUsed] = '\0';
*/
}
break;
case eZLibEncode:
{
z_enc_stream *stream = (z_enc_stream *)vStream;
int org_outbuf_len = stream->OutBuf.BufUsed;
int err;
unsigned int chunkavail;
if (In->ReadWritePointer != NULL)
{
stream->zstream.next_in = (Bytef *) In->ReadWritePointer;
stream->zstream.avail_in = (uInt) In->Buf->BufUsed -
(In->ReadWritePointer - In->Buf->buf);
}
else
{
stream->zstream.next_in = (Bytef *) In->Buf->buf;
stream->zstream.avail_in = (uInt) In->Buf->BufUsed;
}
stream->zstream.next_out = (unsigned char*)stream->OutBuf.buf + stream->OutBuf.BufUsed;
stream->zstream.avail_out = chunkavail = (uInt) stream->OutBuf.BufSize - stream->OutBuf.BufUsed;
err = deflate(&stream->zstream, (LastChunk) ? Z_FINISH : Z_NO_FLUSH);
stream->OutBuf.BufUsed += (chunkavail - stream->zstream.avail_out);
if (Target &&
(LastChunk ||
(stream->OutBuf.BufUsed != org_outbuf_len)
))
{
iSwapBuffers(Target->Buf, &stream->OutBuf);
}
if (stream->zstream.avail_in == 0)
{
FlushStrBuf(In->Buf);
In->ReadWritePointer = NULL;
}
else
{
if (stream->zstream.avail_in < 64)
{
memmove(In->Buf->buf,
In->Buf->buf + In->Buf->BufUsed - stream->zstream.avail_in,
stream->zstream.avail_in);
In->Buf->BufUsed = stream->zstream.avail_in;
In->Buf->buf[In->Buf->BufUsed] = '\0';
}
else
{
In->ReadWritePointer = In->Buf->buf +
(In->Buf->BufUsed - stream->zstream.avail_in);
}
}
rc = (LastChunk && (err != Z_FINISH));
if (!rc && (err != Z_OK)) {
*Err = zError(err);
}
}
break;
case eZLibDecode: {
z_enc_stream *stream = (z_enc_stream *)vStream;
int org_outbuf_len = stream->zstream.total_out;
int err;
if ((stream->zstream.avail_out != 0) && (stream->zstream.next_in != NULL)) {
if (In->ReadWritePointer != NULL)
{
stream->zstream.next_in = (Bytef *) In->ReadWritePointer;
stream->zstream.avail_in = (uInt) In->Buf->BufUsed -
(In->ReadWritePointer - In->Buf->buf);
}
else
{
stream->zstream.next_in = (Bytef *) In->Buf->buf;
stream->zstream.avail_in = (uInt) In->Buf->BufUsed;
}
}
stream->zstream.next_out = (unsigned char*)stream->OutBuf.buf + stream->OutBuf.BufUsed;
stream->zstream.avail_out = (uInt) stream->OutBuf.BufSize - stream->OutBuf.BufUsed;
err = inflate(&stream->zstream, Z_NO_FLUSH);
///assert(ret != Z_STREAM_ERROR); /* state not clobbered * /
switch (err) {
case Z_NEED_DICT:
err = Z_DATA_ERROR; /* and fall through */
case Z_DATA_ERROR:
*Err = zError(err);
case Z_MEM_ERROR:
(void)inflateEnd(&stream->zstream);
return err;
}
stream->OutBuf.BufUsed += stream->zstream.total_out + org_outbuf_len;
if (Target) iSwapBuffers(Target->Buf, &stream->OutBuf);
if (stream->zstream.avail_in == 0)
{
FlushStrBuf(In->Buf);
In->ReadWritePointer = NULL;
}
else
{
if (stream->zstream.avail_in < 64)
{
memmove(In->Buf->buf,
In->Buf->buf + In->Buf->BufUsed - stream->zstream.avail_in,
stream->zstream.avail_in);
In->Buf->BufUsed = stream->zstream.avail_in;
In->Buf->buf[In->Buf->BufUsed] = '\0';
}
else
{
In->ReadWritePointer = In->Buf->buf +
(In->Buf->BufUsed - stream->zstream.avail_in);
}
}
}
break;
case eEmtyCodec: {
}
break; /// TODO
}
return rc;
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief decode a buffer from base 64 encoding; destroys original
* @param Buf Buffor to transform
*/
int StrBufDecodeHex(StrBuf *Buf)
{
unsigned int ch;
char *pch, *pche, *pchi;
if (Buf == NULL) return -1;
pch = pchi = Buf->buf;
pche = pch + Buf->BufUsed;
while (pchi < pche){
ch = decode_hex(pchi);
*pch = ch;
pch ++;
pchi += 2;
}
*pch = '\0';
Buf->BufUsed = pch - Buf->buf;
return Buf->BufUsed;
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief replace all chars >0x20 && < 0x7F with Mute
* @param Mute char to put over invalid chars
* @param Buf Buffor to transform
*/
int StrBufSanitizeAscii(StrBuf *Buf, const char Mute)
{
unsigned char *pch;
if (Buf == NULL) return -1;
pch = (unsigned char *)Buf->buf;
while (pch < (unsigned char *)Buf->buf + Buf->BufUsed) {
if ((*pch < 0x20) || (*pch > 0x7F))
*pch = Mute;
pch ++;
}
return Buf->BufUsed;
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief remove escaped strings from i.e. the url string (like %20 for blanks)
* @param Buf Buffer to translate
* @param StripBlanks Reduce several blanks to one?
*/
long StrBufUnescape(StrBuf *Buf, int StripBlanks)
{
int a, b;
char hex[3];
long len;
if (Buf == NULL)
return -1;
while ((Buf->BufUsed > 0) && (isspace(Buf->buf[Buf->BufUsed - 1]))){
Buf->buf[Buf->BufUsed - 1] = '\0';
Buf->BufUsed --;
}
a = 0;
while (a < Buf->BufUsed) {
if (Buf->buf[a] == '+')
Buf->buf[a] = ' ';
else if (Buf->buf[a] == '%') {
/* don't let % chars through, rather truncate the input. */
if (a + 2 > Buf->BufUsed) {
Buf->buf[a] = '\0';
Buf->BufUsed = a;
}
else {
hex[0] = Buf->buf[a + 1];
hex[1] = Buf->buf[a + 2];
hex[2] = 0;
b = 0;
sscanf(hex, "%02x", &b);
Buf->buf[a] = (char) b;
len = Buf->BufUsed - a - 2;
if (len > 0)
memmove(&Buf->buf[a + 1], &Buf->buf[a + 3], len);
Buf->BufUsed -=2;
}
}
a++;
}
return a;
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief RFC2047-encode a header field if necessary.
* If no non-ASCII characters are found, the string
* will be copied verbatim without encoding.
*
* @param target Target buffer.
* @param source Source string to be encoded.
* @returns encoded length; -1 if non success.
*/
int StrBufRFC2047encode(StrBuf **target, const StrBuf *source)
{
const char headerStr[] = "=?UTF-8?Q?";
int need_to_encode = 0;
int i = 0;
unsigned char ch;
if ((source == NULL) ||
(target == NULL))
return -1;
while ((i < source->BufUsed) &&
(!IsEmptyStr (&source->buf[i])) &&
(need_to_encode == 0)) {
if (((unsigned char) source->buf[i] < 32) ||
((unsigned char) source->buf[i] > 126)) {
need_to_encode = 1;
}
i++;
}
if (!need_to_encode) {
if (*target == NULL) {
*target = NewStrBufPlain(source->buf, source->BufUsed);
}
else {
FlushStrBuf(*target);
StrBufAppendBuf(*target, source, 0);
}
if (*target != 0)
return (*target)->BufUsed;
else
return 0;
}
if (*target == NULL)
*target = NewStrBufPlain(NULL, sizeof(headerStr) + source->BufUsed * 2);
else if (sizeof(headerStr) + source->BufUsed >= (*target)->BufSize)
IncreaseBuf(*target, sizeof(headerStr) + source->BufUsed, 0);
memcpy ((*target)->buf, headerStr, sizeof(headerStr) - 1);
(*target)->BufUsed = sizeof(headerStr) - 1;
for (i=0; (i < source->BufUsed); ++i) {
if ((*target)->BufUsed + 4 >= (*target)->BufSize)
IncreaseBuf(*target, 1, 0);
ch = (unsigned char) source->buf[i];
if ((ch < 32) ||
(ch > 126) ||
(ch == '=') ||
(ch == '?') ||
(ch == '_') ||
(ch == '[') ||
(ch == ']') )
{
sprintf(&(*target)->buf[(*target)->BufUsed], "=%02X", ch);
(*target)->BufUsed += 3;
}
else {
if (ch == ' ')
(*target)->buf[(*target)->BufUsed] = '_';
else
(*target)->buf[(*target)->BufUsed] = ch;
(*target)->BufUsed++;
}
}
if ((*target)->BufUsed + 4 >= (*target)->BufSize)
IncreaseBuf(*target, 1, 0);
(*target)->buf[(*target)->BufUsed++] = '?';
(*target)->buf[(*target)->BufUsed++] = '=';
(*target)->buf[(*target)->BufUsed] = '\0';
return (*target)->BufUsed;;
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief Quoted-Printable encode a message; make it < 80 columns width.
* @param source Source string to be encoded.
* @returns buffer with encoded message.
*/
StrBuf *StrBufRFC2047encodeMessage(const StrBuf *EncodeMe)
{
StrBuf *OutBuf;
char *Optr, *OEptr;
const char *ptr, *eptr;
unsigned char ch;
int LinePos;
OutBuf = NewStrBufPlain(NULL, StrLength(EncodeMe) * 4);
Optr = OutBuf->buf;
OEptr = OutBuf->buf + OutBuf->BufSize;
ptr = EncodeMe->buf;
eptr = EncodeMe->buf + EncodeMe->BufUsed;
LinePos = 0;
while (ptr < eptr)
{
if (Optr + 4 >= OEptr)
{
long Offset;
Offset = Optr - OutBuf->buf;
OutBuf->BufUsed = Optr - OutBuf->buf;
IncreaseBuf(OutBuf, 1, 0);
Optr = OutBuf->buf + Offset;
OEptr = OutBuf->buf + OutBuf->BufSize;
}
if (*ptr == '\r')
{
/* ignore carriage returns */
ptr ++;
}
else if (*ptr == '\n') {
/* hard line break */
memcpy(Optr, HKEY("=0A"));
Optr += 3;
LinePos += 3;
ptr ++;
}
else if (( (*ptr >= 32) && (*ptr <= 60) ) ||
( (*ptr >= 62) && (*ptr <= 126) ))
{
*Optr = *ptr;
Optr ++;
ptr ++;
LinePos ++;
}
else {
ch = *ptr;
*Optr = '=';
Optr ++;
*Optr = HexList[ch][0];
Optr ++;
*Optr = HexList[ch][1];
Optr ++;
LinePos += 3;
ptr ++;
}
if (LinePos > 72) {
/* soft line break */
if (isspace(*(Optr - 1))) {
ch = *(Optr - 1);
Optr --;
*Optr = '=';
Optr ++;
*Optr = HexList[ch][0];
Optr ++;
*Optr = HexList[ch][1];
Optr ++;
LinePos += 3;
}
*Optr = '=';
Optr ++;
*Optr = '\n';
Optr ++;
LinePos = 0;
}
}
*Optr = '\0';
OutBuf->BufUsed = Optr - OutBuf->buf;
return OutBuf;
}
static void AddRecipient(StrBuf *Target,
StrBuf *UserName,
StrBuf *EmailAddress,
StrBuf *EncBuf)
{
int QuoteMe = 0;
if (StrLength(Target) > 0) StrBufAppendBufPlain(Target, HKEY(", "), 0);
if (strchr(ChrPtr(UserName), ',') != NULL) QuoteMe = 1;
if (QuoteMe) StrBufAppendBufPlain(Target, HKEY("\""), 0);
StrBufRFC2047encode(&EncBuf, UserName);
StrBufAppendBuf(Target, EncBuf, 0);
if (QuoteMe) StrBufAppendBufPlain(Target, HKEY("\" "), 0);
else StrBufAppendBufPlain(Target, HKEY(" "), 0);
if (StrLength(EmailAddress) > 0){
StrBufAppendBufPlain(Target, HKEY("<"), 0);
StrBufAppendBuf(Target, EmailAddress, 0); /* TODO: what about IDN???? */
StrBufAppendBufPlain(Target, HKEY(">"), 0);
}
}
/**
* \brief QP encode parts of an email TO/CC/BCC vector, and strip/filter invalid parts
* \param Recp Source list of email recipients
* \param UserName Temporary buffer for internal use; Please provide valid buffer.
* \param EmailAddress Temporary buffer for internal use; Please provide valid buffer.
* \param EncBuf Temporary buffer for internal use; Please provide valid buffer.
* \returns encoded & sanitized buffer with the contents of Recp; Caller owns this memory.
*/
StrBuf *StrBufSanitizeEmailRecipientVector(const StrBuf *Recp,
StrBuf *UserName,
StrBuf *EmailAddress,
StrBuf *EncBuf)
{
StrBuf *Target;
const char *pch, *pche;
const char *UserStart, *UserEnd, *EmailStart, *EmailEnd, *At;
if ((Recp == NULL) || (StrLength(Recp) == 0))
return NULL;
pch = ChrPtr(Recp);
pche = pch + StrLength(Recp);
if (!CheckEncode(pch, -1, pche))
return NewStrBufDup(Recp);
Target = NewStrBufPlain(NULL, StrLength(Recp));
while ((pch != NULL) && (pch < pche))
{
while (isspace(*pch)) pch++;
UserEnd = EmailStart = EmailEnd = NULL;
if ((*pch == '"') || (*pch == '\'')) {
UserStart = pch + 1;
UserEnd = strchr(UserStart, *pch);
if (UserEnd == NULL)
break; ///TODO: Userfeedback??
EmailStart = UserEnd + 1;
while (isspace(*EmailStart))
EmailStart++;
if (UserEnd == UserStart) {
UserStart = UserEnd = NULL;
}
if (*EmailStart == '<') {
EmailStart++;
EmailEnd = strchr(EmailStart, '>');
if (EmailEnd == NULL)
EmailEnd = strchr(EmailStart, ',');
}
else {
EmailEnd = strchr(EmailStart, ',');
}
if (EmailEnd == NULL)
EmailEnd = pche;
pch = EmailEnd + 1;
}
else {
int gt = 0;
UserStart = pch;
EmailEnd = strchr(UserStart, ',');
if (EmailEnd == NULL) {
EmailEnd = strchr(pch, '>');
pch = NULL;
if (EmailEnd != NULL) {
gt = 1;
}
else {
EmailEnd = pche;
}
}
else {
pch = EmailEnd + 1;
while ((EmailEnd > UserStart) && !gt &&
((*EmailEnd == ',') ||
(*EmailEnd == '>') ||
(isspace(*EmailEnd))))
{
if (*EmailEnd == '>')
gt = 1;
else
EmailEnd--;
}
if (EmailEnd == UserStart)
break;
}
if (gt) {
EmailStart = strchr(UserStart, '<');
if ((EmailStart == NULL) || (EmailStart > EmailEnd))
break;
UserEnd = EmailStart;
while ((UserEnd > UserStart) &&
isspace (*(UserEnd - 1)))
UserEnd --;
EmailStart ++;
if (UserStart >= UserEnd)
UserStart = UserEnd = NULL;
}
else { /* this is a local recipient... no domain, just a realname */
EmailStart = UserStart;
At = strchr(EmailStart, '@');
if (At == NULL) {
UserEnd = EmailEnd;
EmailEnd = NULL;
}
else {
EmailStart = UserStart;
UserStart = NULL;
}
}
}
if ((UserStart != NULL) && (UserEnd != NULL))
StrBufPlain(UserName, UserStart, UserEnd - UserStart);
else if ((UserStart != NULL) && (UserEnd == NULL))
StrBufPlain(UserName, UserStart, UserEnd - UserStart);
else
FlushStrBuf(UserName);
if ((EmailStart != NULL) && (EmailEnd != NULL))
StrBufPlain(EmailAddress, EmailStart, EmailEnd - EmailStart);
else if ((EmailStart != NULL) && (EmailEnd == NULL))
StrBufPlain(EmailAddress, EmailStart, EmailEnd - pche);
else
FlushStrBuf(EmailAddress);
AddRecipient(Target, UserName, EmailAddress, EncBuf);
if (pch == NULL)
break;
if ((pch != NULL) && (*pch == ','))
pch ++;
if (pch != NULL) while (isspace(*pch))
pch ++;
}
return Target;
}
/**
* @ingroup StrBuf
* @brief replaces all occurances of 'search' by 'replace'
* @param buf Buffer to modify
* @param search character to search
* @param replace character to replace search by
*/
void StrBufReplaceChars(StrBuf *buf, char search, char replace)
{
long i;
if (buf == NULL)
return;
for (i=0; i<buf->BufUsed; i++)
if (buf->buf[i] == search)
buf->buf[i] = replace;
}
/**
* @ingroup StrBuf
* @brief removes all \\r s from the string, or replaces them with \n if its not a combination of both.
* @param buf Buffer to modify
*/
void StrBufToUnixLF(StrBuf *buf)
{
char *pche, *pchS, *pchT;
if (buf == NULL)
return;
pche = buf->buf + buf->BufUsed;
pchS = pchT = buf->buf;
while (pchS < pche)
{
if (*pchS == '\r')
{
pchS ++;
if (*pchS != '\n') {
*pchT = '\n';
pchT++;
}
}
*pchT = *pchS;
pchT++; pchS++;
}
*pchT = '\0';
buf->BufUsed = pchT - buf->buf;
}
/*******************************************************************************
* Iconv Wrapper; RFC822 de/encoding *
*******************************************************************************/
/**
* @ingroup StrBuf_DeEnCoder
* @brief Wrapper around iconv_open()
* Our version adds aliases for non-standard Microsoft charsets
* such as 'MS950', aliasing them to names like 'CP950'
*
* @param tocode Target encoding
* @param fromcode Source encoding
* @param pic anonimized pointer to iconv struct
*/
void ctdl_iconv_open(const char *tocode, const char *fromcode, void *pic)
{
#ifdef HAVE_ICONV
iconv_t ic = (iconv_t)(-1) ;
ic = iconv_open(tocode, fromcode);
if (ic == (iconv_t)(-1) ) {
char alias_fromcode[64];
if ( (strlen(fromcode) == 5) && (!strncasecmp(fromcode, "MS", 2)) ) {
safestrncpy(alias_fromcode, fromcode, sizeof alias_fromcode);
alias_fromcode[0] = 'C';
alias_fromcode[1] = 'P';
ic = iconv_open(tocode, alias_fromcode);
}
}
*(iconv_t *)pic = ic;
#endif
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief find one chunk of a RFC822 encoded string
* @param Buffer where to search
* @param bptr where to start searching
* @returns found position, NULL if none.
*/
static inline const char *FindNextEnd (const StrBuf *Buf, const char *bptr)
{
const char * end;
/* Find the next ?Q? */
if (Buf->BufUsed - (bptr - Buf->buf) < 6)
return NULL;
end = strchr(bptr + 2, '?');
if (end == NULL)
return NULL;
if ((Buf->BufUsed - (end - Buf->buf) > 3) &&
(((*(end + 1) == 'B') || (*(end + 1) == 'Q')) ||
((*(end + 1) == 'b') || (*(end + 1) == 'q'))) &&
(*(end + 2) == '?')) {
/* skip on to the end of the cluster, the next ?= */
end = strstr(end + 3, "?=");
}
else
/* sort of half valid encoding, try to find an end. */
end = strstr(bptr, "?=");
return end;
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief convert one buffer according to the preselected iconv pointer PIC
* @param ConvertBuf buffer we need to translate
* @param TmpBuf To share a workbuffer over several iterations. prepare to have it filled with useless stuff afterwards.
* @param pic Pointer to the iconv-session Object
*/
void StrBufConvert(StrBuf *ConvertBuf, StrBuf *TmpBuf, void *pic)
{
#ifdef HAVE_ICONV
long trycount = 0;
size_t siz;
iconv_t ic;
char *ibuf; /**< Buffer of characters to be converted */
char *obuf; /**< Buffer for converted characters */
size_t ibuflen; /**< Length of input buffer */
size_t obuflen; /**< Length of output buffer */
if ((ConvertBuf == NULL) || (TmpBuf == NULL))
return;
/* since we're converting to utf-8, one glyph may take up to 6 bytes */
if (ConvertBuf->BufUsed * 6 >= TmpBuf->BufSize)
IncreaseBuf(TmpBuf, 0, ConvertBuf->BufUsed * 6);
TRYAGAIN:
ic = *(iconv_t*)pic;
ibuf = ConvertBuf->buf;
ibuflen = ConvertBuf->BufUsed;
obuf = TmpBuf->buf;
obuflen = TmpBuf->BufSize;
siz = iconv(ic, &ibuf, &ibuflen, &obuf, &obuflen);
if (siz < 0) {
if (errno == E2BIG) {
trycount ++;
IncreaseBuf(TmpBuf, 0, 0);
if (trycount < 5)
goto TRYAGAIN;
}
else if (errno == EILSEQ){
/* hm, invalid utf8 sequence... what to do now? */
/* An invalid multibyte sequence has been encountered in the input */
}
else if (errno == EINVAL) {
/* An incomplete multibyte sequence has been encountered in the input. */
}
FlushStrBuf(TmpBuf);
}
else {
TmpBuf->BufUsed = TmpBuf->BufSize - obuflen;
TmpBuf->buf[TmpBuf->BufUsed] = '\0';
/* little card game: wheres the red lady? */
iSwapBuffers(ConvertBuf, TmpBuf);
FlushStrBuf(TmpBuf);
}
#endif
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief catches one RFC822 encoded segment, and decodes it.
* @param Target buffer to fill with result
* @param DecodeMe buffer with stuff to process
* @param SegmentStart points to our current segment in DecodeMe
* @param SegmentEnd Points to the end of our current segment in DecodeMe
* @param ConvertBuf Workbuffer shared between several iterations. Random content; needs to be valid
* @param ConvertBuf2 Workbuffer shared between several iterations. Random content; needs to be valid
* @param FoundCharset Characterset to default decoding to; if we find another we will overwrite it.
*/
inline static void DecodeSegment(StrBuf *Target,
const StrBuf *DecodeMe,
const char *SegmentStart,
const char *SegmentEnd,
StrBuf *ConvertBuf,
StrBuf *ConvertBuf2,
StrBuf *FoundCharset)
{
StrBuf StaticBuf;
char charset[128];
char encoding[16];
#ifdef HAVE_ICONV
iconv_t ic = (iconv_t)(-1);
#else
void *ic = NULL;
#endif
/* Now we handle foreign character sets properly encoded
* in RFC2047 format.
*/
StaticBuf.buf = (char*) SegmentStart; /*< it will just be read there... */
StaticBuf.BufUsed = SegmentEnd - SegmentStart;
StaticBuf.BufSize = DecodeMe->BufSize - (SegmentStart - DecodeMe->buf);
extract_token(charset, SegmentStart, 1, '?', sizeof charset);
if (FoundCharset != NULL) {
FlushStrBuf(FoundCharset);
StrBufAppendBufPlain(FoundCharset, charset, -1, 0);
}
extract_token(encoding, SegmentStart, 2, '?', sizeof encoding);
StrBufExtract_token(ConvertBuf, &StaticBuf, 3, '?');
*encoding = toupper(*encoding);
if (*encoding == 'B') { /**< base64 */
if (ConvertBuf2->BufSize < ConvertBuf->BufUsed)
IncreaseBuf(ConvertBuf2, 0, ConvertBuf->BufUsed);
ConvertBuf2->BufUsed = CtdlDecodeBase64(ConvertBuf2->buf,
ConvertBuf->buf,
ConvertBuf->BufUsed);
}
else if (*encoding == 'Q') { /**< quoted-printable */
long pos;
pos = 0;
while (pos < ConvertBuf->BufUsed)
{
if (ConvertBuf->buf[pos] == '_')
ConvertBuf->buf[pos] = ' ';
pos++;
}
if (ConvertBuf2->BufSize < ConvertBuf->BufUsed)
IncreaseBuf(ConvertBuf2, 0, ConvertBuf->BufUsed);
ConvertBuf2->BufUsed = CtdlDecodeQuotedPrintable(
ConvertBuf2->buf,
ConvertBuf->buf,
ConvertBuf->BufUsed);
}
else {
StrBufAppendBuf(ConvertBuf2, ConvertBuf, 0);
}
#ifdef HAVE_ICONV
ctdl_iconv_open("UTF-8", charset, &ic);
if (ic != (iconv_t)(-1) ) {
#endif
StrBufConvert(ConvertBuf2, ConvertBuf, &ic);
StrBufAppendBuf(Target, ConvertBuf2, 0);
#ifdef HAVE_ICONV
iconv_close(ic);
}
else {
StrBufAppendBufPlain(Target, HKEY("(unreadable)"), 0);
}
#endif
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief Handle subjects with RFC2047 encoding such as: [deprecated old syntax!]
* =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
* @param Target where to put the decoded string to
* @param DecodeMe buffer with encoded string
* @param DefaultCharset if we don't find one, which should we use?
* @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
* put it here for later use where no string might be known.
*/
void StrBuf_RFC822_to_Utf8(StrBuf *Target, const StrBuf *DecodeMe, const StrBuf* DefaultCharset, StrBuf *FoundCharset)
{
StrBuf *ConvertBuf;
StrBuf *ConvertBuf2;
ConvertBuf = NewStrBufPlain(NULL, StrLength(DecodeMe));
ConvertBuf2 = NewStrBufPlain(NULL, StrLength(DecodeMe));
StrBuf_RFC822_2_Utf8(Target,
DecodeMe,
DefaultCharset,
FoundCharset,
ConvertBuf,
ConvertBuf2);
FreeStrBuf(&ConvertBuf);
FreeStrBuf(&ConvertBuf2);
}
/**
* @ingroup StrBuf_DeEnCoder
* @brief Handle subjects with RFC2047 encoding such as:
* =?koi8-r?B?78bP0s3Mxc7JxSDXz9rE1dvO2c3JINvB0sHNySDP?=
* @param Target where to put the decoded string to
* @param DecodeMe buffer with encoded string
* @param DefaultCharset if we don't find one, which should we use?
* @param FoundCharset overrides DefaultCharset if non-empty; If we find a charset inside of the string,
* put it here for later use where no string might be known.
* @param ConvertBuf workbuffer. feed in, you shouldn't care about its content.
* @param ConvertBuf2 workbuffer. feed in, you shouldn't care about its content.
*/
void StrBuf_RFC822_2_Utf8(StrBuf *Target,
const StrBuf *DecodeMe,
const StrBuf* DefaultCharset,
StrBuf *FoundCharset,
StrBuf *ConvertBuf,
StrBuf *ConvertBuf2)
{
StrBuf *DecodedInvalidBuf = NULL;
const StrBuf *DecodeMee = DecodeMe;
const char *start, *end, *next, *nextend, *ptr = NULL;
#ifdef HAVE_ICONV
iconv_t ic = (iconv_t)(-1) ;
#endif
const char *eptr;
int passes = 0;
int i;
int illegal_non_rfc2047_encoding = 0;
if (DecodeMe == NULL)
return;
/* Sometimes, badly formed messages contain strings which were simply
* written out directly in some foreign character set instead of
* using RFC2047 encoding. This is illegal but we will attempt to
* handle it anyway by converting from a user-specified default
* charset to UTF-8 if we see any nonprintable characters.
*/
for (i=0; i<DecodeMe->BufUsed; ++i) {
if ((DecodeMe->buf[i] < 32) || (DecodeMe->buf[i] > 126)) {
illegal_non_rfc2047_encoding = 1;
break;
}
}
if ((illegal_non_rfc2047_encoding) &&
(strcasecmp(ChrPtr(DefaultCharset), "UTF-8")) &&
(strcasecmp(ChrPtr(DefaultCharset), "us-ascii")) )
{
#ifdef HAVE_ICONV
ctdl_iconv_open("UTF-8", ChrPtr(DefaultCharset), &ic);
if (ic != (iconv_t)(-1) ) {
DecodedInvalidBuf = NewStrBufDup(DecodeMe);
StrBufConvert(DecodedInvalidBuf, ConvertBuf, &ic);///TODO: don't void const?
DecodeMee = DecodedInvalidBuf;
iconv_close(ic);
}
#endif
}
/* pre evaluate the first pair */
end = NULL;
start = strstr(DecodeMee->buf, "=?");
eptr = DecodeMee->buf + DecodeMee->BufUsed;
if (start != NULL)
end = FindNextEnd (DecodeMee, start + 2);
else {
StrBufAppendBuf(Target, DecodeMee, 0);
FreeStrBuf(&DecodedInvalidBuf);
return;
}
if (start != DecodeMee->buf) {
long nFront;
nFront = start - DecodeMee->buf;
StrBufAppendBufPlain(Target, DecodeMee->buf, nFront, 0);
}
/*
* Since spammers will go to all sorts of absurd lengths to get their
* messages through, there are LOTS of corrupt headers out there.
* So, prevent a really badly formed RFC2047 header from throwing
* this function into an infinite loop.
*/
while ((start != NULL) &&
(end != NULL) &&
(start < eptr) &&
(end < eptr) &&
(passes < 20))
{
passes++;
DecodeSegment(Target,
DecodeMee,
start,
end,
ConvertBuf,
ConvertBuf2,
FoundCharset);
next = strstr(end, "=?");
nextend = NULL;
if ((next != NULL) &&
(next < eptr))
nextend = FindNextEnd(DecodeMee, next);
if (nextend == NULL)
next = NULL;
/* did we find two partitions */
if ((next != NULL) &&
((next - end) > 2))
{
ptr = end + 2;
while ((ptr < next) &&
(isspace(*ptr) ||
(*ptr == '\r') ||
(*ptr == '\n') ||
(*ptr == '\t')))
ptr ++;
/*
* did we find a gab just filled with blanks?
* if not, copy its stuff over.
*/
if (ptr != next)
{
StrBufAppendBufPlain(Target,
end + 2,
next - end - 2,
0);
}
}
/* our next-pair is our new first pair now. */
ptr = end + 2;
start = next;
end = nextend;
}
end = ptr;
nextend = DecodeMee->buf + DecodeMee->BufUsed;
if ((end != NULL) && (end < nextend)) {
ptr = end;
while ( (ptr < nextend) &&
(isspace(*ptr) ||
(*ptr == '\r') ||
(*ptr == '\n') ||
(*ptr == '\t')))
ptr ++;
if (ptr < nextend)
StrBufAppendBufPlain(Target, end, nextend - end, 0);
}
FreeStrBuf(&DecodedInvalidBuf);
}
/*******************************************************************************
* Manipulating UTF-8 Strings *
*******************************************************************************/
/**
* @ingroup StrBuf
* @brief evaluate the length of an utf8 special character sequence
* @param Char the character to examine
* @returns width of utf8 chars in bytes; if the sequence is broken 0 is returned; 1 if its simply ASCII.
*/
static inline int Ctdl_GetUtf8SequenceLength(const char *CharS, const char *CharE)
{
int n = 0;
unsigned char test = (1<<7);
if ((*CharS & 0xC0) != 0xC0)
return 1;
while ((n < 8) &&
((test & ((unsigned char)*CharS)) != 0))
{
test = test >> 1;
n ++;
}
if ((n > 6) || ((CharE - CharS) < n))
n = 0;
return n;
}
/**
* @ingroup StrBuf
* @brief detect whether this char starts an utf-8 encoded char
* @param Char character to inspect
* @returns yes or no
*/
static inline int Ctdl_IsUtf8SequenceStart(const char Char)
{
/** 11??.???? indicates an UTF8 Sequence. */
return ((Char & 0xC0) == 0xC0);
}
/**
* @ingroup StrBuf
* @brief measure the number of glyphs in an UTF8 string...
* @param Buf string to measure
* @returns the number of glyphs in Buf
*/
long StrBuf_Utf8StrLen(StrBuf *Buf)
{
int n = 0;
int m = 0;
char *aptr, *eptr;
if ((Buf == NULL) || (Buf->BufUsed == 0))
return 0;
aptr = Buf->buf;
eptr = Buf->buf + Buf->BufUsed;
while ((aptr < eptr) && (*aptr != '\0')) {
if (Ctdl_IsUtf8SequenceStart(*aptr)){
m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
while ((aptr < eptr) && (*aptr++ != '\0')&& (m-- > 0) );
n ++;
}
else {
n++;
aptr++;
}
}
return n;
}
/**
* @ingroup StrBuf
* @brief cuts a string after maxlen glyphs
* @param Buf string to cut to maxlen glyphs
* @param maxlen how long may the string become?
* @returns current length of the string
*/
long StrBuf_Utf8StrCut(StrBuf *Buf, int maxlen)
{
char *aptr, *eptr;
int n = 0, m = 0;
aptr = Buf->buf;
eptr = Buf->buf + Buf->BufUsed;
while ((aptr < eptr) && (*aptr != '\0')) {
if (Ctdl_IsUtf8SequenceStart(*aptr)){
m = Ctdl_GetUtf8SequenceLength(aptr, eptr);
while ((*aptr++ != '\0') && (m-- > 0));
n ++;
}
else {
n++;
aptr++;
}
if (n >= maxlen) {
*aptr = '\0';
Buf->BufUsed = aptr - Buf->buf;
return Buf->BufUsed;
}
}
return Buf->BufUsed;
}
/*******************************************************************************
* wrapping ZLib *
*******************************************************************************/
/**
* @ingroup StrBuf_DeEnCoder
* @brief uses the same calling syntax as compress2(), but it
* creates a stream compatible with HTTP "Content-encoding: gzip"
* @param dest compressed buffer
* @param destLen length of the compresed data
* @param source source to encode
* @param sourceLen length of source to encode
* @param level compression level
*/
#ifdef HAVE_ZLIB
int ZEXPORT compress_gzip(Bytef * dest,
size_t * destLen,
const Bytef * source,
uLong sourceLen,
int level)
{
/* write gzip header */
snprintf((char *) dest, *destLen,
"%c%c%c%c%c%c%c%c%c%c",
gz_magic[0], gz_magic[1], Z_DEFLATED,
0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /* xflags */ ,
OS_CODE);
/* normal deflate */
z_stream stream;
int err;
stream.next_in = (Bytef *) source;
stream.avail_in = (uInt) sourceLen;
stream.next_out = dest + 10L; // after header
stream.avail_out = (uInt) * destLen;
if ((uLong) stream.avail_out != *destLen)
return Z_BUF_ERROR;
stream.zalloc = (alloc_func) 0;
stream.zfree = (free_func) 0;
stream.opaque = (voidpf) 0;
err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
if (err != Z_OK)
return err;
err = deflate(&stream, Z_FINISH);
if (err != Z_STREAM_END) {
deflateEnd(&stream);
return err == Z_OK ? Z_BUF_ERROR : err;
}
*destLen = stream.total_out + 10L;
/* write CRC and Length */
uLong crc = crc32(0L, source, sourceLen);
int n;
for (n = 0; n < 4; ++n, ++*destLen) {
dest[*destLen] = (int) (crc & 0xff);
crc >>= 8;
}
uLong len = stream.total_in;
for (n = 0; n < 4; ++n, ++*destLen) {
dest[*destLen] = (int) (len & 0xff);
len >>= 8;
}
err = deflateEnd(&stream);
return err;
}
#endif
/**
* @ingroup StrBuf_DeEnCoder
* @brief compress the buffer with gzip
* Attention! If you feed this a Const String, you must maintain the uncompressed buffer yourself!
* @param Buf buffer whose content is to be gzipped
*/
int CompressBuffer(StrBuf *Buf)
{
#ifdef HAVE_ZLIB
char *compressed_data = NULL;
size_t compressed_len, bufsize;
int i = 0;
bufsize = compressed_len = Buf->BufUsed + (Buf->BufUsed / 100) + 100;
compressed_data = malloc(compressed_len);
if (compressed_data == NULL)
return -1;
/* Flush some space after the used payload so valgrind shuts up... */
while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
Buf->buf[Buf->BufUsed + i++] = '\0';
if (compress_gzip((Bytef *) compressed_data,
&compressed_len,
(Bytef *) Buf->buf,
(uLongf) Buf->BufUsed, Z_BEST_SPEED) == Z_OK) {
if (!Buf->ConstBuf)
free(Buf->buf);
Buf->buf = compressed_data;
Buf->BufUsed = compressed_len;
Buf->BufSize = bufsize;
/* Flush some space after the used payload so valgrind shuts up... */
i = 0;
while ((i < 10) && (Buf->BufUsed + i < Buf->BufSize))
Buf->buf[Buf->BufUsed + i++] = '\0';
return 1;
} else {
free(compressed_data);
}
#endif /* HAVE_ZLIB */
return 0;
}
/*******************************************************************************
* File I/O; Callbacks to libevent *
*******************************************************************************/
long StrBuf_read_one_chunk_callback (int fd, short event, IOBuffer *FB)
{
long bufremain = 0;
int n;
if ((FB == NULL) || (FB->Buf == NULL))
return -1;
/*
* check whether the read pointer is somewhere in a range
* where a cut left is inexpensive
*/
if (FB->ReadWritePointer != NULL)
{
long already_read;
already_read = FB->ReadWritePointer - FB->Buf->buf;
bufremain = FB->Buf->BufSize - FB->Buf->BufUsed - 1;
if (already_read != 0) {
long unread;
unread = FB->Buf->BufUsed - already_read;
/* else nothing to compact... */
if (unread == 0) {
FB->ReadWritePointer = FB->Buf->buf;
bufremain = FB->Buf->BufSize;
}
else if ((unread < 64) ||
(bufremain < already_read))
{
/*
* if its just a tiny bit remaining, or we run out of space...
* lets tidy up.
*/
FB->Buf->BufUsed = unread;
if (unread < already_read)
memcpy(FB->Buf->buf, FB->ReadWritePointer, unread);
else
memmove(FB->Buf->buf, FB->ReadWritePointer, unread);
FB->ReadWritePointer = FB->Buf->buf;
bufremain = FB->Buf->BufSize - unread - 1;
}
else if (bufremain < (FB->Buf->BufSize / 10))
{
/* get a bigger buffer */
IncreaseBuf(FB->Buf, 0, FB->Buf->BufUsed + 1);
FB->ReadWritePointer = FB->Buf->buf + unread;
bufremain = FB->Buf->BufSize - unread - 1;
/*TODO: special increase function that won't copy the already read! */
}
}
else if (bufremain < 10) {
IncreaseBuf(FB->Buf, 1, FB->Buf->BufUsed + 10);
FB->ReadWritePointer = FB->Buf->buf;
bufremain = FB->Buf->BufSize - FB->Buf->BufUsed - 1;
}
}
else {
FB->ReadWritePointer = FB->Buf->buf;
bufremain = FB->Buf->BufSize - 1;
}
n = read(fd, FB->Buf->buf + FB->Buf->BufUsed, bufremain);
if (n > 0) {
FB->Buf->BufUsed += n;
FB->Buf->buf[FB->Buf->BufUsed] = '\0';
}
return n;
}
int StrBuf_write_one_chunk_callback(int fd, short event, IOBuffer *FB)
{
long WriteRemain;
int n;
if ((FB == NULL) || (FB->Buf == NULL))
return -1;
if (FB->ReadWritePointer != NULL)
{
WriteRemain = FB->Buf->BufUsed -
(FB->ReadWritePointer -
FB->Buf->buf);
}
else {
FB->ReadWritePointer = FB->Buf->buf;
WriteRemain = FB->Buf->BufUsed;
}
n = write(fd, FB->ReadWritePointer, WriteRemain);
if (n > 0) {
FB->ReadWritePointer += n;
if (FB->ReadWritePointer ==
FB->Buf->buf + FB->Buf->BufUsed)
{
FlushStrBuf(FB->Buf);
FB->ReadWritePointer = NULL;
return 0;
}
// check whether we've got something to write
// get the maximum chunk plus the pointer we can send
// write whats there
// if not all was sent, remember the send pointer for the next time
return FB->ReadWritePointer - FB->Buf->buf + FB->Buf->BufUsed;
}
return n;
}
/**
* @ingroup StrBuf_IO
* @brief extract a "next line" from Buf; Ptr to persist across several iterations
* @param LineBuf your line will be copied here.
* @param FB BLOB with lines of text...
* @param Ptr moved arround to keep the next-line across several iterations
* has to be &NULL on start; will be &NotNULL on end of buffer
* @returns size of copied buffer
*/
eReadState StrBufChunkSipLine(StrBuf *LineBuf, IOBuffer *FB)
{
const char *aptr, *ptr, *eptr;
char *optr, *xptr;
if ((FB == NULL) || (LineBuf == NULL) || (LineBuf->buf == NULL))
return eReadFail;
if ((FB->Buf == NULL) || (FB->ReadWritePointer == StrBufNOTNULL)) {
FB->ReadWritePointer = StrBufNOTNULL;
return eReadFail;
}
FlushStrBuf(LineBuf);
if (FB->ReadWritePointer == NULL)
ptr = aptr = FB->Buf->buf;
else
ptr = aptr = FB->ReadWritePointer;
optr = LineBuf->buf;
eptr = FB->Buf->buf + FB->Buf->BufUsed;
xptr = LineBuf->buf + LineBuf->BufSize - 1;
while ((ptr <= eptr) &&
(*ptr != '\n') &&
(*ptr != '\r') )
{
*optr = *ptr;
optr++; ptr++;
if (optr == xptr) {
LineBuf->BufUsed = optr - LineBuf->buf;
IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
optr = LineBuf->buf + LineBuf->BufUsed;
xptr = LineBuf->buf + LineBuf->BufSize - 1;
}
}
if (ptr >= eptr) {
if (optr > LineBuf->buf)
optr --;
if ((*(ptr - 1) != '\r') && (*(ptr - 1) != '\n')) {
LineBuf->BufUsed = optr - LineBuf->buf;
*optr = '\0';
if ((FB->ReadWritePointer != NULL) &&
(FB->ReadWritePointer != FB->Buf->buf))
{
/* Ok, the client application read all the data
it was interested in so far. Since there is more to read,
we now shrink the buffer, and move the rest over.
*/
StrBufCutLeft(FB->Buf,
FB->ReadWritePointer - FB->Buf->buf);
FB->ReadWritePointer = FB->Buf->buf;
}
return eMustReadMore;
}
}
LineBuf->BufUsed = optr - LineBuf->buf;
*optr = '\0';
if ((ptr <= eptr) && (*ptr == '\r'))
ptr ++;
if ((ptr <= eptr) && (*ptr == '\n'))
ptr ++;
if (ptr < eptr) {
FB->ReadWritePointer = ptr;
}
else {
FlushStrBuf(FB->Buf);
FB->ReadWritePointer = NULL;
}
return eReadSuccess;
}
/**
* @ingroup StrBuf_CHUNKED_IO
* @brief check whether the chunk-buffer has more data waiting or not.
* @param FB Chunk-Buffer to inspect
*/
eReadState StrBufCheckBuffer(IOBuffer *FB)
{
if (FB == NULL)
return eReadFail;
if (FB->Buf->BufUsed == 0)
return eReadSuccess;
if (FB->ReadWritePointer == NULL)
return eBufferNotEmpty;
if (FB->Buf->buf + FB->Buf->BufUsed > FB->ReadWritePointer)
return eBufferNotEmpty;
return eReadSuccess;
}
long IOBufferStrLength(IOBuffer *FB)
{
if ((FB == NULL) || (FB->Buf == NULL))
return 0;
if (FB->ReadWritePointer == NULL)
return StrLength(FB->Buf);
return StrLength(FB->Buf) - (FB->ReadWritePointer - FB->Buf->buf);
}
inline static void FDIOBufferFlush(FDIOBuffer *FDB)
{
memset(FDB, 0, sizeof(FDIOBuffer));
FDB->OtherFD = -1;
FDB->SplicePipe[0] = -1;
FDB->SplicePipe[1] = -1;
}
void FDIOBufferInit(FDIOBuffer *FDB, IOBuffer *IO, int FD, long TotalSendSize)
{
FDIOBufferFlush(FDB);
FDB->TotalSendSize = TotalSendSize;
if (TotalSendSize > 0)
FDB->ChunkSize = TotalSendSize;
else
{
TotalSendSize = SIZ * 10;
FDB->ChunkSize = TotalSendSize;
}
FDB->IOB = IO;
#ifdef LINUX_SPLICE
if (EnableSplice)
pipe(FDB->SplicePipe);
else
#endif
FDB->ChunkBuffer = NewStrBufPlain(NULL, TotalSendSize+ 1);
FDB->OtherFD = FD;
}
void FDIOBufferDelete(FDIOBuffer *FDB)
{
#ifdef LINUX_SPLICE
if (EnableSplice)
{
if (FDB->SplicePipe[0] > 0)
close(FDB->SplicePipe[0]);
if (FDB->SplicePipe[1] > 0)
close(FDB->SplicePipe[1]);
}
else
#endif
FreeStrBuf(&FDB->ChunkBuffer);
if (FDB->OtherFD > 0)
close(FDB->OtherFD);
FDIOBufferFlush(FDB);
}
int FileSendChunked(FDIOBuffer *FDB, const char **Err)
{
ssize_t sent, pipesize;
if (FDB->TotalSendSize > 0)
{
#ifdef LINUX_SPLICE
if (EnableSplice)
{
if (FDB->PipeSize == 0)
{
pipesize = splice(FDB->OtherFD,
&FDB->TotalSentAlready,
FDB->SplicePipe[1],
NULL,
FDB->ChunkSendRemain,
SPLICE_F_MOVE);
if (pipesize == -1)
{
*Err = strerror(errno);
return pipesize;
}
FDB->PipeSize = pipesize;
}
sent = splice(FDB->SplicePipe[0],
NULL,
FDB->IOB->fd,
NULL,
FDB->PipeSize,
SPLICE_F_MORE | SPLICE_F_MOVE | SPLICE_F_NONBLOCK);
if (sent == -1)
{
*Err = strerror(errno);
return sent;
}
FDB->PipeSize -= sent;
FDB->ChunkSendRemain -= sent;
return sent;
}
else
#endif
{
char *pRead;
long nRead = 0;
pRead = FDB->ChunkBuffer->buf;
while ((FDB->ChunkBuffer->BufUsed < FDB->TotalSendSize) && (nRead >= 0))
{
nRead = read(FDB->OtherFD, pRead, FDB->TotalSendSize - FDB->ChunkBuffer->BufUsed);
if (nRead > 0) {
FDB->ChunkBuffer->BufUsed += nRead;
FDB->ChunkBuffer->buf[FDB->ChunkBuffer->BufUsed] = '\0';
}
else if (nRead == 0) {}
else return nRead;
}
nRead = write(FDB->IOB->fd,
FDB->ChunkBuffer->buf + FDB->TotalSentAlready,
FDB->ChunkBuffer->BufUsed - FDB->TotalSentAlready);
if (nRead >= 0) {
FDB->TotalSentAlready += nRead;
FDB->ChunkSendRemain -= nRead;
return FDB->ChunkSendRemain;
}
else {
return nRead;
}
}
}
else
{
#ifdef LINUX_SPLICE
if (EnableSplice)
{
if (FDB->PipeSize == 0)
{
pipesize = splice(FDB->OtherFD,
&FDB->TotalSentAlready,
FDB->SplicePipe[1],
NULL,
SIZ * 10,
SPLICE_F_MOVE);
if (pipesize == -1)
{
*Err = strerror(errno);
return pipesize;
}
FDB->PipeSize = pipesize;
if (pipesize == 0)
return -1;
}
sent = splice(FDB->SplicePipe[0],
NULL,
FDB->IOB->fd,
NULL,
FDB->PipeSize,
SPLICE_F_MORE | SPLICE_F_MOVE | SPLICE_F_NONBLOCK);
if (sent == -1)
{
*Err = strerror(errno);
return sent;
}
FDB->PipeSize -= sent;
FDB->ChunkSendRemain -= sent;
return sent;
}
else
#endif
{
char *pRead;
long nRead = 0;
pRead = FDB->ChunkBuffer->buf;
while ((FDB->ChunkSendRemain == 0) &&
(FDB->ChunkBuffer->BufUsed < FDB->ChunkBuffer->BufSize) &&
(nRead >= 0))
{
FDB->TotalSentAlready = 0;
nRead = read(FDB->OtherFD, pRead, FDB->ChunkBuffer->BufSize - FDB->ChunkBuffer->BufUsed);
if (nRead > 0) {
FDB->ChunkBuffer->BufUsed += nRead;
FDB->ChunkBuffer->buf[FDB->ChunkBuffer->BufUsed] = '\0';
FDB->ChunkSendRemain += nRead;
}
else if (nRead == 0)
{
return -1;
}
else
{
*Err = strerror(errno);
return nRead;
}
}
nRead = write(FDB->IOB->fd,
FDB->ChunkBuffer->buf + FDB->TotalSentAlready,
FDB->ChunkBuffer->BufUsed - FDB->TotalSentAlready);
if (nRead >= 0) {
FDB->TotalSentAlready += nRead;
FDB->ChunkSendRemain -= nRead;
if (FDB->ChunkSendRemain == 0)
{
FDB->ChunkBuffer->BufUsed = 0;
FDB->TotalSentAlready = 0;
}
return FDB->ChunkSendRemain;
}
else {
return nRead;
}
}
}
}
int FileRecvChunked(FDIOBuffer *FDB, const char **Err)
{
ssize_t sent, pipesize;
#ifdef LINUX_SPLICE
if (EnableSplice)
{
if (FDB->PipeSize == 0)
{
pipesize = splice(FDB->IOB->fd,
NULL,
FDB->SplicePipe[1],
NULL,
FDB->ChunkSendRemain,
SPLICE_F_MORE | SPLICE_F_MOVE|SPLICE_F_NONBLOCK);
if (pipesize == -1)
{
*Err = strerror(errno);
return pipesize;
}
FDB->PipeSize = pipesize;
}
sent = splice(FDB->SplicePipe[0],
NULL,
FDB->OtherFD,
&FDB->TotalSentAlready,
FDB->PipeSize,
SPLICE_F_MORE | SPLICE_F_MOVE);
if (sent == -1)
{
*Err = strerror(errno);
return sent;
}
FDB->PipeSize -= sent;
FDB->ChunkSendRemain -= sent;
return sent;
}
else
#endif
{
sent = read(FDB->IOB->fd, FDB->ChunkBuffer->buf, FDB->ChunkSendRemain);
if (sent > 0) {
int nWritten = 0;
int rc;
FDB->ChunkBuffer->BufUsed = sent;
while (nWritten < FDB->ChunkBuffer->BufUsed) {
rc = write(FDB->OtherFD, FDB->ChunkBuffer->buf + nWritten, FDB->ChunkBuffer->BufUsed - nWritten);
if (rc < 0) {
*Err = strerror(errno);
return rc;
}
nWritten += rc;
}
FDB->ChunkBuffer->BufUsed = 0;
FDB->TotalSentAlready += sent;
FDB->ChunkSendRemain -= sent;
return FDB->ChunkSendRemain;
}
else if (sent < 0) {
*Err = strerror(errno);
return sent;
}
return 0;
}
}
int FileMoveChunked(FDIOBuffer *FDB, const char **Err)
{
ssize_t sent, pipesize;
#ifdef LINUX_SPLICE
if (EnableSplice)
{
if (FDB->PipeSize == 0)
{
pipesize = splice(FDB->IOB->fd,
&FDB->TotalReadAlready,
FDB->SplicePipe[1],
NULL,
FDB->ChunkSendRemain,
SPLICE_F_MORE | SPLICE_F_MOVE|SPLICE_F_NONBLOCK);
if (pipesize == -1)
{
*Err = strerror(errno);
return pipesize;
}
FDB->PipeSize = pipesize;
}
sent = splice(FDB->SplicePipe[0],
NULL,
FDB->OtherFD,
&FDB->TotalSentAlready,
FDB->PipeSize,
SPLICE_F_MORE | SPLICE_F_MOVE);
if (sent == -1)
{
*Err = strerror(errno);
return sent;
}
FDB->PipeSize -= sent;
FDB->ChunkSendRemain -= sent;
return sent;
}
else
#endif
{
sent = read(FDB->IOB->fd, FDB->ChunkBuffer->buf, FDB->ChunkSendRemain);
if (sent > 0) {
int nWritten = 0;
int rc;
FDB->ChunkBuffer->BufUsed = sent;
while (nWritten < FDB->ChunkBuffer->BufUsed) {
rc = write(FDB->OtherFD, FDB->ChunkBuffer->buf + nWritten, FDB->ChunkBuffer->BufUsed - nWritten);
if (rc < 0) {
*Err = strerror(errno);
return rc;
}
nWritten += rc;
}
FDB->ChunkBuffer->BufUsed = 0;
FDB->TotalSentAlready += sent;
FDB->ChunkSendRemain -= sent;
return FDB->ChunkSendRemain;
}
else if (sent < 0) {
*Err = strerror(errno);
return sent;
}
return 0;
}
}
eReadState WriteIOBAlreadyRead(FDIOBuffer *FDB, const char **Error)
{
int IsNonBlock;
int fdflags;
long rlen;
long should_write;
int nSuccessLess = 0;
struct timeval tv;
fd_set rfds;
fdflags = fcntl(FDB->OtherFD, F_GETFL);
IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
while ((FDB->IOB->ReadWritePointer - FDB->IOB->Buf->buf < FDB->IOB->Buf->BufUsed) &&
(FDB->ChunkSendRemain > 0))
{
if (IsNonBlock){
tv.tv_sec = 1; /* selectresolution; */
tv.tv_usec = 0;
FD_ZERO(&rfds);
FD_SET(FDB->OtherFD, &rfds);
if (select(FDB->OtherFD + 1, NULL, &rfds, NULL, &tv) == -1) {
*Error = strerror(errno);
return eReadFail;
}
}
if (IsNonBlock && ! FD_ISSET(FDB->OtherFD, &rfds)) {
nSuccessLess ++;
continue;
}
should_write = FDB->IOB->Buf->BufUsed -
(FDB->IOB->ReadWritePointer - FDB->IOB->Buf->buf);
if (should_write > FDB->ChunkSendRemain)
should_write = FDB->ChunkSendRemain;
rlen = write(FDB->OtherFD,
FDB->IOB->ReadWritePointer,
should_write);
if (rlen < 1) {
*Error = strerror(errno);
return eReadFail;
}
FDB->TotalSentAlready += rlen;
FDB->IOB->ReadWritePointer += rlen;
FDB->ChunkSendRemain -= rlen;
}
if (FDB->IOB->ReadWritePointer >= FDB->IOB->Buf->buf + FDB->IOB->Buf->BufUsed)
{
FlushStrBuf(FDB->IOB->Buf);
FDB->IOB->ReadWritePointer = NULL;
}
if (FDB->ChunkSendRemain == 0)
return eReadSuccess;
else
return eMustReadMore;
}
/*******************************************************************************
* File I/O; Prefer buffered read since its faster! *
*******************************************************************************/
/**
* @ingroup StrBuf_IO
* @brief Read a line from socket
* flushes and closes the FD on error
* @param buf the buffer to get the input to
* @param fd pointer to the filedescriptor to read
* @param append Append to an existing string or replace?
* @param Error strerror() on error
* @returns numbers of chars read
*/
int StrBufTCP_read_line(StrBuf *buf, int *fd, int append, const char **Error)
{
int len, rlen, slen;
if ((buf == NULL) || (buf->buf == NULL)) {
*Error = strerror(EINVAL);
return -1;
}
if (!append)
FlushStrBuf(buf);
slen = len = buf->BufUsed;
while (1) {
rlen = read(*fd, &buf->buf[len], 1);
if (rlen < 1) {
*Error = strerror(errno);
close(*fd);
*fd = -1;
return -1;
}
if (buf->buf[len] == '\n')
break;
if (buf->buf[len] != '\r')
len ++;
if (len + 2 >= buf->BufSize) {
buf->BufUsed = len;
buf->buf[len+1] = '\0';
IncreaseBuf(buf, 1, -1);
}
}
buf->BufUsed = len;
buf->buf[len] = '\0';
return len - slen;
}
/**
* @ingroup StrBuf_BufferedIO
* @brief Read a line from socket
* flushes and closes the FD on error
* @param Line the line to read from the fd / I/O Buffer
* @param buf the buffer to get the input to
* @param fd pointer to the filedescriptor to read
* @param timeout number of successless selects until we bail out
* @param selectresolution how long to wait on each select
* @param Error strerror() on error
* @returns numbers of chars read
*/
int StrBufTCP_read_buffered_line(StrBuf *Line,
StrBuf *buf,
int *fd,
int timeout,
int selectresolution,
const char **Error)
{
int len, rlen;
int nSuccessLess = 0;
fd_set rfds;
char *pch = NULL;
int fdflags;
int IsNonBlock;
struct timeval tv;
if (buf->BufUsed > 0) {
pch = strchr(buf->buf, '\n');
if (pch != NULL) {
rlen = 0;
len = pch - buf->buf;
if (len > 0 && (*(pch - 1) == '\r') )
rlen ++;
StrBufSub(Line, buf, 0, len - rlen);
StrBufCutLeft(buf, len + 1);
return len - rlen;
}
}
if (buf->BufSize - buf->BufUsed < 10)
IncreaseBuf(buf, 1, -1);
fdflags = fcntl(*fd, F_GETFL);
IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
while ((nSuccessLess < timeout) && (pch == NULL)) {
if (IsNonBlock){
tv.tv_sec = selectresolution;
tv.tv_usec = 0;
FD_ZERO(&rfds);
FD_SET(*fd, &rfds);
if (select(*fd + 1, NULL, &rfds, NULL, &tv) == -1) {
*Error = strerror(errno);
close (*fd);
*fd = -1;
return -1;
}
}
if (IsNonBlock && ! FD_ISSET(*fd, &rfds)) {
nSuccessLess ++;
continue;
}
rlen = read(*fd,
&buf->buf[buf->BufUsed],
buf->BufSize - buf->BufUsed - 1);
if (rlen < 1) {
*Error = strerror(errno);
close(*fd);
*fd = -1;
return -1;
}
else if (rlen > 0) {
nSuccessLess = 0;
buf->BufUsed += rlen;
buf->buf[buf->BufUsed] = '\0';
pch = strchr(buf->buf, '\n');
if ((pch == NULL) &&
(buf->BufUsed + 10 > buf->BufSize) &&
(IncreaseBuf(buf, 1, -1) == -1))
return -1;
continue;
}
}
if (pch != NULL) {
rlen = 0;
len = pch - buf->buf;
if (len > 0 && (*(pch - 1) == '\r') )
rlen ++;
StrBufSub(Line, buf, 0, len - rlen);
StrBufCutLeft(buf, len + 1);
return len - rlen;
}
return -1;
}
static const char *ErrRBLF_PreConditionFailed="StrBufTCP_read_buffered_line_fast: Wrong arguments or invalid Filedescriptor";
static const char *ErrRBLF_SelectFailed="StrBufTCP_read_buffered_line_fast: Select failed without reason";
static const char *ErrRBLF_NotEnoughSentFromServer="StrBufTCP_read_buffered_line_fast: No complete line was sent from peer";
/**
* @ingroup StrBuf_BufferedIO
* @brief Read a line from socket
* flushes and closes the FD on error
* @param Line where to append our Line read from the fd / I/O Buffer;
* @param IOBuf the buffer to get the input to; lifetime pair to FD
* @param Pos pointer to the current read position, should be NULL initialized on opening the FD it belongs to.!
* @param fd pointer to the filedescriptor to read
* @param timeout number of successless selects until we bail out
* @param selectresolution how long to wait on each select
* @param Error strerror() on error
* @returns numbers of chars read or -1 in case of error. "\n" will become 0
*/
int StrBufTCP_read_buffered_line_fast(StrBuf *Line,
StrBuf *IOBuf,
const char **Pos,
int *fd,
int timeout,
int selectresolution,
const char **Error)
{
const char *pche = NULL;
const char *pos = NULL;
const char *pLF;
int len, rlen, retlen;
int nSuccessLess = 0;
fd_set rfds;
const char *pch = NULL;
int fdflags;
int IsNonBlock;
struct timeval tv;
retlen = 0;
if ((Line == NULL) ||
(Pos == NULL) ||
(IOBuf == NULL) ||
(*fd == -1))
{
if (Pos != NULL)
*Pos = NULL;
*Error = ErrRBLF_PreConditionFailed;
return -1;
}
pos = *Pos;
if ((IOBuf->BufUsed > 0) &&
(pos != NULL) &&
(pos < IOBuf->buf + IOBuf->BufUsed))
{
char *pcht;
pche = IOBuf->buf + IOBuf->BufUsed;
pch = pos;
pcht = Line->buf;
while ((pch < pche) && (*pch != '\n'))
{
if (Line->BufUsed + 10 > Line->BufSize)
{
long apos;
apos = pcht - Line->buf;
*pcht = '\0';
IncreaseBuf(Line, 1, -1);
pcht = Line->buf + apos;
}
*pcht++ = *pch++;
Line->BufUsed++;
retlen++;
}
len = pch - pos;
if (len > 0 && (*(pch - 1) == '\r') )
{
retlen--;
len --;
pcht --;
Line->BufUsed --;
}
*pcht = '\0';
if ((pch >= pche) || (*pch == '\0'))
{
FlushStrBuf(IOBuf);
*Pos = NULL;
pch = NULL;
pos = 0;
}
if ((pch != NULL) &&
(pch <= pche))
{
if (pch + 1 >= pche) {
*Pos = NULL;
FlushStrBuf(IOBuf);
}
else
*Pos = pch + 1;
return retlen;
}
else
FlushStrBuf(IOBuf);
}
/* If we come here, Pos is Unset since we read everything into Line, and now go for more. */
if (IOBuf->BufSize - IOBuf->BufUsed < 10)
IncreaseBuf(IOBuf, 1, -1);
fdflags = fcntl(*fd, F_GETFL);
IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
pLF = NULL;
while ((nSuccessLess < timeout) &&
(pLF == NULL) &&
(*fd != -1)) {
if (IsNonBlock)
{
tv.tv_sec = 1;
tv.tv_usec = 0;
FD_ZERO(&rfds);
FD_SET(*fd, &rfds);
if (select((*fd) + 1, &rfds, NULL, NULL, &tv) == -1) {
*Error = strerror(errno);
close (*fd);
*fd = -1;
if (*Error == NULL)
*Error = ErrRBLF_SelectFailed;
return -1;
}
if (! FD_ISSET(*fd, &rfds) != 0) {
nSuccessLess ++;
continue;
}
}
rlen = read(*fd,
&IOBuf->buf[IOBuf->BufUsed],
IOBuf->BufSize - IOBuf->BufUsed - 1);
if (rlen < 1) {
*Error = strerror(errno);
close(*fd);
*fd = -1;
return -1;
}
else if (rlen > 0) {
nSuccessLess = 0;
pLF = IOBuf->buf + IOBuf->BufUsed;
IOBuf->BufUsed += rlen;
IOBuf->buf[IOBuf->BufUsed] = '\0';
pche = IOBuf->buf + IOBuf->BufUsed;
while ((pLF < pche) && (*pLF != '\n'))
pLF ++;
if ((pLF >= pche) || (*pLF == '\0'))
pLF = NULL;
if (IOBuf->BufUsed + 10 > IOBuf->BufSize)
{
long apos = 0;
if (pLF != NULL) apos = pLF - IOBuf->buf;
IncreaseBuf(IOBuf, 1, -1);
if (pLF != NULL) pLF = IOBuf->buf + apos;
}
continue;
}
else
{
nSuccessLess++;
}
}
*Pos = NULL;
if (pLF != NULL) {
pos = IOBuf->buf;
len = pLF - pos;
if (len > 0 && (*(pLF - 1) == '\r') )
len --;
StrBufAppendBufPlain(Line, ChrPtr(IOBuf), len, 0);
if (pLF + 1 >= IOBuf->buf + IOBuf->BufUsed)
{
FlushStrBuf(IOBuf);
}
else
*Pos = pLF + 1;
return retlen + len;
}
*Error = ErrRBLF_NotEnoughSentFromServer;
return -1;
}
static const char *ErrRBLF_BLOBPreConditionFailed="StrBufReadBLOB: Wrong arguments or invalid Filedescriptor";
/**
* @ingroup StrBuf_IO
* @brief Input binary data from socket
* flushes and closes the FD on error
* @param Buf the buffer to get the input to
* @param fd pointer to the filedescriptor to read
* @param append Append to an existing string or replace?
* @param nBytes the maximal number of bytes to read
* @param Error strerror() on error
* @returns numbers of chars read
*/
int StrBufReadBLOB(StrBuf *Buf, int *fd, int append, long nBytes, const char **Error)
{
int fdflags;
int rlen;
int nSuccessLess;
int nRead = 0;
char *ptr;
int IsNonBlock;
struct timeval tv;
fd_set rfds;
if ((Buf == NULL) || (Buf->buf == NULL) || (*fd == -1))
{
*Error = ErrRBLF_BLOBPreConditionFailed;
return -1;
}
if (!append)
FlushStrBuf(Buf);
if (Buf->BufUsed + nBytes >= Buf->BufSize)
IncreaseBuf(Buf, 1, Buf->BufUsed + nBytes);
ptr = Buf->buf + Buf->BufUsed;
fdflags = fcntl(*fd, F_GETFL);
IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
nSuccessLess = 0;
while ((nRead < nBytes) &&
(*fd != -1))
{
if (IsNonBlock)
{
tv.tv_sec = 1;
tv.tv_usec = 0;
FD_ZERO(&rfds);
FD_SET(*fd, &rfds);
if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
*Error = strerror(errno);
close (*fd);
*fd = -1;
if (*Error == NULL)
*Error = ErrRBLF_SelectFailed;
return -1;
}
if (! FD_ISSET(*fd, &rfds) != 0) {
nSuccessLess ++;
continue;
}
}
if ((rlen = read(*fd,
ptr,
nBytes - nRead)) == -1) {
close(*fd);
*fd = -1;
*Error = strerror(errno);
return rlen;
}
nRead += rlen;
ptr += rlen;
Buf->BufUsed += rlen;
}
Buf->buf[Buf->BufUsed] = '\0';
return nRead;
}
const char *ErrRBB_BLOBFPreConditionFailed = "StrBufReadBLOBBuffered: to many selects; aborting.";
const char *ErrRBB_too_many_selects = "StrBufReadBLOBBuffered: to many selects; aborting.";
/**
* @ingroup StrBuf_BufferedIO
* @brief Input binary data from socket
* flushes and closes the FD on error
* @param Blob put binary thing here
* @param IOBuf the buffer to get the input to
* @param Pos offset inside of IOBuf
* @param fd pointer to the filedescriptor to read
* @param append Append to an existing string or replace?
* @param nBytes the maximal number of bytes to read
* @param check whether we should search for '000\n' terminators in case of timeouts
* @param Error strerror() on error
* @returns numbers of chars read
*/
int StrBufReadBLOBBuffered(StrBuf *Blob,
StrBuf *IOBuf,
const char **Pos,
int *fd,
int append,
long nBytes,
int check,
const char **Error)
{
const char *pos;
int fdflags;
int rlen = 0;
int nRead = 0;
int nAlreadyRead = 0;
int IsNonBlock;
char *ptr;
fd_set rfds;
struct timeval tv;
int nSuccessLess = 0;
int MaxTries;
if ((Blob == NULL) ||
(*fd == -1) ||
(IOBuf == NULL) ||
(Pos == NULL))
{
if (Pos != NULL)
*Pos = NULL;
*Error = ErrRBB_BLOBFPreConditionFailed;
return -1;
}
if (!append)
FlushStrBuf(Blob);
if (Blob->BufUsed + nBytes >= Blob->BufSize)
IncreaseBuf(Blob, append, Blob->BufUsed + nBytes);
pos = *Pos;
if (pos != NULL)
rlen = pos - IOBuf->buf;
rlen = IOBuf->BufUsed - rlen;
if ((IOBuf->BufUsed > 0) &&
(pos != NULL) &&
(pos < IOBuf->buf + IOBuf->BufUsed))
{
if (rlen < nBytes) {
memcpy(Blob->buf + Blob->BufUsed, pos, rlen);
Blob->BufUsed += rlen;
Blob->buf[Blob->BufUsed] = '\0';
nAlreadyRead = nRead = rlen;
*Pos = NULL;
}
if (rlen >= nBytes) {
memcpy(Blob->buf + Blob->BufUsed, pos, nBytes);
Blob->BufUsed += nBytes;
Blob->buf[Blob->BufUsed] = '\0';
if (rlen == nBytes) {
*Pos = NULL;
FlushStrBuf(IOBuf);
}
else
*Pos += nBytes;
return nBytes;
}
}
FlushStrBuf(IOBuf);
*Pos = NULL;
if (IOBuf->BufSize < nBytes - nRead)
IncreaseBuf(IOBuf, 0, nBytes - nRead);
ptr = IOBuf->buf;
fdflags = fcntl(*fd, F_GETFL);
IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
if (IsNonBlock)
MaxTries = 1000;
else
MaxTries = 100000;
nBytes -= nRead;
nRead = 0;
while ((nSuccessLess < MaxTries) &&
(nRead < nBytes) &&
(*fd != -1)) {
if (IsNonBlock)
{
tv.tv_sec = 1;
tv.tv_usec = 0;
FD_ZERO(&rfds);
FD_SET(*fd, &rfds);
if (select(*fd + 1, &rfds, NULL, NULL, &tv) == -1) {
*Error = strerror(errno);
close (*fd);
*fd = -1;
if (*Error == NULL)
*Error = ErrRBLF_SelectFailed;
return -1;
}
if (! FD_ISSET(*fd, &rfds) != 0) {
nSuccessLess ++;
continue;
}
}
rlen = read(*fd,
ptr,
IOBuf->BufSize - (ptr - IOBuf->buf));
if (rlen == -1) {
close(*fd);
*fd = -1;
*Error = strerror(errno);
return rlen;
}
else if (rlen == 0){
if ((check == NNN_TERM) &&
(nRead > 5) &&
(strncmp(IOBuf->buf + IOBuf->BufUsed - 5, "\n000\n", 5) == 0))
{
StrBufPlain(Blob, HKEY("\n000\n"));
StrBufCutRight(Blob, 5);
return Blob->BufUsed;
}
else if (!IsNonBlock)
nSuccessLess ++;
else if (nSuccessLess > MaxTries) {
FlushStrBuf(IOBuf);
*Error = ErrRBB_too_many_selects;
return -1;
}
}
else if (rlen > 0) {
nSuccessLess = 0;
nRead += rlen;
ptr += rlen;
IOBuf->BufUsed += rlen;
}
}
if (nSuccessLess >= MaxTries) {
FlushStrBuf(IOBuf);
*Error = ErrRBB_too_many_selects;
return -1;
}
if (nRead > nBytes) {
*Pos = IOBuf->buf + nBytes;
}
Blob->buf[Blob->BufUsed] = '\0';
StrBufAppendBufPlain(Blob, IOBuf->buf, nBytes, 0);
if (*Pos == NULL) {
FlushStrBuf(IOBuf);
}
return nRead + nAlreadyRead;
}
/**
* @ingroup StrBuf_IO
* @brief extract a "next line" from Buf; Ptr to persist across several iterations
* @param LineBuf your line will be copied here.
* @param Buf BLOB with lines of text...
* @param Ptr moved arround to keep the next-line across several iterations
* has to be &NULL on start; will be &NotNULL on end of buffer
* @returns size of remaining buffer
*/
int StrBufSipLine(StrBuf *LineBuf, const StrBuf *Buf, const char **Ptr)
{
const char *aptr, *ptr, *eptr;
char *optr, *xptr;
if ((Buf == NULL) ||
(*Ptr == StrBufNOTNULL) ||
(LineBuf == NULL)||
(LineBuf->buf == NULL))
{
*Ptr = StrBufNOTNULL;
return 0;
}
FlushStrBuf(LineBuf);
if (*Ptr==NULL)
ptr = aptr = Buf->buf;
else
ptr = aptr = *Ptr;
optr = LineBuf->buf;
eptr = Buf->buf + Buf->BufUsed;
xptr = LineBuf->buf + LineBuf->BufSize - 1;
while ((ptr <= eptr) &&
(*ptr != '\n') &&
(*ptr != '\r') )
{
*optr = *ptr;
optr++; ptr++;
if (optr == xptr) {
LineBuf->BufUsed = optr - LineBuf->buf;
IncreaseBuf(LineBuf, 1, LineBuf->BufUsed + 1);
optr = LineBuf->buf + LineBuf->BufUsed;
xptr = LineBuf->buf + LineBuf->BufSize - 1;
}
}
if ((ptr >= eptr) && (optr > LineBuf->buf))
optr --;
LineBuf->BufUsed = optr - LineBuf->buf;
*optr = '\0';
if ((ptr <= eptr) && (*ptr == '\r'))
ptr ++;
if ((ptr <= eptr) && (*ptr == '\n'))
ptr ++;
if (ptr < eptr) {
*Ptr = ptr;
}
else {
*Ptr = StrBufNOTNULL;
}
return Buf->BufUsed - (ptr - Buf->buf);
}
/**
* @ingroup StrBuf_IO
* @brief removes double slashes from pathnames
* @param Dir directory string to filter
* @param RemoveTrailingSlash allows / disallows trailing slashes
*/
void StrBufStripSlashes(StrBuf *Dir, int RemoveTrailingSlash)
{
char *a, *b;
a = b = Dir->buf;
while (!IsEmptyStr(a)) {
if (*a == '/') {
while (*a == '/')
a++;
*b = '/';
b++;
}
else {
*b = *a;
b++; a++;
}
}
if ((RemoveTrailingSlash) &&
(b > Dir->buf) &&
(*(b - 1) == '/')){
b--;
}
*b = '\0';
Dir->BufUsed = b - Dir->buf;
}
/*
* Decode a quoted-printable encoded StrBuf buffer "in place"
* This is possible because the decoded will always be shorter than the encoded
* so we don't have to worry about the buffer being to small.
*/
void StrBufDecodeQP(StrBuf *Buf)
{
if (!Buf) { // sanity check #1
return;
}
int source_len = StrLength(Buf);
if (source_len < 1) { // sanity check #2
return;
}
int spos = 0; // source position
int tpos = 0; // target position
while (spos < source_len) {
if (!strncmp(&Buf->buf[spos], "=\r\n", 3)) {
spos += 3;
}
else if (!strncmp(&Buf->buf[spos], "=\n", 2)) {
spos += 2;
}
else if (Buf->buf[spos] == '=') {
++spos;
int ch;
sscanf(&Buf->buf[spos], "%02x", &ch);
Buf->buf[tpos++] = ch;
spos +=2;
}
else {
Buf->buf[tpos++] = Buf->buf[spos++];
}
}
Buf->buf[tpos] = 0;
Buf->BufUsed = tpos;
}
|