Hash :
caeec816
Author :
Date :
2018-11-14T15:41:11
Clean up getdelimfd error handling.
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
/**
* @file
* @brief SMTP client library.
* @author James Humphrey (mail@somnisoft.com)
* @version 1.00
*
* This SMTP client library allows the user to send emails to an SMTP server.
* The user can include custom headers and MIME attachments.
*
* This software has been placed into the public domain using CC0.
*/
/**
* @mainpage smtp-client
*
* This section contains documentation generated directly from the source
* code.
*
* To view the repository details, visit the main smtp-client page at
* <a href='https://www.somnisoft.com/smtp-client'>
* www.somnisoft.com/smtp-client
* </a>.
*/
#if defined(_WIN32) || defined(WIN32)
# define SMTP_IS_WINDOWS
#endif /* SMTP_IS_WINDOWS */
#ifdef SMTP_IS_WINDOWS
# include <winsock2.h>
# include <ws2tcpip.h>
#else /* POSIX */
/**
* Need to define this on some POSIX systems in order to get access to the
* getaddrinfo and localtime_r functions.
*/
# define _POSIX_C_SOURCE 200112L
# include <netinet/in.h>
# include <sys/select.h>
# include <sys/socket.h>
# include <netdb.h>
# include <unistd.h>
#endif /* SMTP_IS_WINDOWS */
#include <errno.h>
#include <limits.h>
#include <signal.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#ifdef SMTP_OPENSSL
# include <openssl/bio.h>
# include <openssl/err.h>
# include <openssl/ssl.h>
# include <openssl/x509.h>
# include <openssl/x509v3.h>
#endif /* SMTP_OPENSSL */
#ifndef SIZE_MAX
/**
* Maximum value of size_t type.
*/
# define SIZE_MAX ((size_t)(-1))
#endif /* SIZE_MAX */
/**
* Get access to the @ref smtp_result_code and @ref smtp_command definitions.
*/
#define SMTP_INTERNAL_DEFINE
#include "smtp.h"
/*
* The SMTP_TEST converts some library routines into special test seams which
* allows the test program to control whether they fail. For example, we can
* control when malloc() fails under certain conditions with an out of
* memory condition.
*/
#ifdef SMTP_TEST
/**
* Declare extern linkage on some functions so we can redefine their behavior
* in the external test suite.
*/
# define SMTP_LINKAGE extern
# include "../test/seams.h"
#else /* !(SMTP_TEST) */
/**
* When not testing, all functions should have static linkage except for those
* in the header.
*/
# define SMTP_LINKAGE static
#endif /* SMTP_TEST */
/**
* Increment the read buffer size by this amount if the delimiter
* has not been found.
*/
#define SMTP_GETDELIM_READ_SZ 1000
/**
* Stores source and destination email addresses.
*/
struct smtp_address{
/**
* Specify from, to, cc, bcc.
*/
enum smtp_address_type type;
/**
* Email address without any special formatting.
*
* For example: mail@example.com
*/
char *email;
/**
* Description of the email address.
*/
char *name;
};
/**
* Attachment data which gets placed in the MIME email section.
*/
struct smtp_attachment{
/**
* File name of the attachment.
*/
char *name;
/**
* Base64-encoded file data.
*/
char *b64_data;
};
/**
* List of email headers to send before the mail body.
*/
struct smtp_header{
/**
* Header name which will get sorted alphabetically in the header list.
*/
char *key;
/**
* Content of the corresponding header key.
*/
char *value;
};
/**
* Main data structure that holds the SMTP client context.
*/
struct smtp{
/**
* Bitwise list of flags controlling the behavior of this SMTP client.
*/
enum smtp_flag flags;
/**
* Standard network socket connection.
*/
int sock;
/**
* Read buffer and line parsing structure.
*/
struct str_getdelimfd gdfd;
/**
* List of headers to print before the mail body.
*/
struct smtp_header *header_list;
/**
* Number of headers in header_list.
*/
size_t num_headers;
/**
* List of from, to, cc, and bcc email addresses.
*/
struct smtp_address *address_list;
/**
* Number of addresses in address_list.
*/
size_t num_address;
/**
* List of attachments to send.
*/
struct smtp_attachment *attachment_list;
/**
* Number of attachments in attachment_list.
*/
size_t num_attachment;
/**
* Status code indicating success/failure.
*
* This code gets returned by most of the header functions.
*/
enum smtp_status_code status_code;
/**
* Timeout in seconds to wait before returning with an error.
*
* This applies to both writing to and reading from a network socket.
*/
long timeout_sec;
/**
* Indicates if this context has an active TLS connection.
* - Set to 0 if TLS connection inactive.
* - Set to 1 if TLS connection currently active.
*/
int tls_on;
/**
* Path to certificate file if using self-signed or untrusted certificate
* not in the default key store.
*/
const char *cafile;
#ifdef SMTP_OPENSSL
/**
* OpenSSL TLS object.
*/
SSL *tls;
/**
* OpenSSL TLS context.
*/
SSL_CTX *tls_ctx;
/**
* OpenSSL TLS I/O abstraction.
*/
BIO *tls_bio;
#endif /* SMTP_OPENSSL */
};
/**
* Check if adding a size_t value will cause a wrap.
*
* @param[in] a Add this value with @p b.
* @param[in] b Add this value with @p a.
* @param[out] result Save the addition to this buffer. Does not
* perform the addition if set to NULL.
* @retval 1 Value wrapped.
* @retval 0 Value did not wrap.
*/
SMTP_LINKAGE int
smtp_si_add_size_t(const size_t a,
const size_t b,
size_t *const result){
int wraps;
#ifdef SMTP_TEST
if(smtp_test_seam_dec_err_ctr(&g_smtp_test_err_si_add_size_t_ctr)){
return 1;
}
#endif /* SMTP_TEST */
if(SIZE_MAX - a < b){
wraps = 1;
}
else{
wraps = 0;
}
if(result){
*result = a + b;
}
return wraps;
}
/**
* Check if subtracting a size_t value will cause wrap.
*
* @param[in] a Subtract this value by @p b.
* @param[in] b Subtract this value from @p a.
* @param[out] result Save the subtraction to this buffer. Does not
* perform the subtraction if set to NULL.
* @retval 1 Value wrapped.
* @retval 0 Value did not wrap.
*/
SMTP_LINKAGE int
smtp_si_sub_size_t(const size_t a,
const size_t b,
size_t *const result){
int wraps;
#ifdef SMTP_TEST
if(smtp_test_seam_dec_err_ctr(&g_smtp_test_err_si_sub_size_t_ctr)){
return 1;
}
#endif /* SMTP_TEST */
if(a < b){
wraps = 1;
}
else{
wraps = 0;
}
if(result){
*result = a - b;
}
return wraps;
}
/**
* Check if multiplying a size_t value will cause a wrap.
*
* @param[in] a Multiply this value with @p b.
* @param[in] b Multiply this value with @p a.
* @param[out] result Save the multiplication to this buffer. Does not
* perform the multiplication if set to NULL.
* @retval 1 Value wrapped.
* @retval 0 Value did not wrap.
*/
SMTP_LINKAGE int
smtp_si_mul_size_t(const size_t a,
const size_t b,
size_t *const result){
int wraps;
#ifdef SMTP_TEST
if(smtp_test_seam_dec_err_ctr(&g_smtp_test_err_si_mul_size_t_ctr)){
return 1;
}
#endif /* SMTP_TEST */
if(b != 0 && a > SIZE_MAX / b){
wraps = 1;
}
else{
wraps = 0;
}
if(result){
*result = a * b;
}
return wraps;
}
/**
* Wait until more data has been made available on the socket read end.
*
* @param[in] smtp SMTP client context.
* @retval 0 If data available to read on the socket.
* @retval -1 If the connection times out before any data appears on the
* socket.
*/
static int
smtp_str_getdelimfd_read_timeout(struct smtp *const smtp){
fd_set readfds;
struct timeval timeout;
int sel_rc;
FD_ZERO(&readfds);
FD_SET(smtp->sock, &readfds);
timeout.tv_sec = smtp->timeout_sec;
timeout.tv_usec = 0;
sel_rc = select(smtp->sock + 1, &readfds, NULL, NULL, &timeout);
if(sel_rc < 1){
return smtp_status_code_set(smtp, SMTP_STATUS_RECV);
}
return smtp->status_code;
}
/**
* This function gets called by the @ref smtp_str_getdelimfd interface when it
* needs to read in more data.
*
* It reads using either the plain socket connection if encryption not
* enabled, or it reads using OpenSSL if it has an active TLS connection.
*
* @param[in] gdfd See @ref str_getdelimfd.
* @param[out] buf Pointer to buffer for storing bytes read.
* @param[in] count Maximum number of bytes to try reading.
* @retval >=0 Number of bytes read.
* @retval -1 Failed to read from the socket.
*/
static long
smtp_str_getdelimfd_read(struct str_getdelimfd *const gdfd,
void *buf,
size_t count){
struct smtp *smtp;
long bytes_read;
smtp = gdfd->user_data;
if(smtp_str_getdelimfd_read_timeout(smtp) != SMTP_STATUS_OK){
return -1;
}
bytes_read = 0;
if(smtp->tls_on){
#ifdef SMTP_OPENSSL
do{
bytes_read = SSL_read(smtp->tls, buf, count);
} while(bytes_read <= 0 && BIO_should_retry(smtp->tls_bio));
#endif /* SMTP_OPENSSL */
}
else{
bytes_read = recv(smtp->sock, buf, count, 0);
}
return bytes_read;
}
/**
* Find and return the location of the delimiter character in the
* search buffer.
*
* This function gets used by the main socket parsing function which
* continually reads from the socket and expands the buffer until it
* encounters the expected delimiter. This function provides the logic
* to check for the delimiter character in order to simplify the code
* in the main parse function.
*
* @param[in] buf Search buffer used to find the delimiter.
* @param[in] buf_len Number of bytes to search for in buf.
* @param[in] delim The delimiter to search for in buf.
* @param[out] delim_pos If delimiter found in buf, return the delimiter
* position in this parameter.
* @retval 1 If the delimiter character found.
* @retval 0 If the delimiter character not found.
*/
static int
smtp_str_getdelimfd_search_delim(const char *const buf,
size_t buf_len,
int delim,
size_t *const delim_pos){
size_t i;
*delim_pos = 0;
for(i = 0; i < buf_len; i++){
if(buf[i] == delim){
*delim_pos = i;
return 1;
}
}
return 0;
}
/**
* Set the internal line buffer to the number of bytes specified.
*
* @param[in] gdfd See @ref str_getdelimfd.
* @param[in] copy_len Number of bytes to copy to the internal line buffer.
* @retval 0 Successfully allocated and copied data over to the new
* line buffer.
* @retval -1 Failed to allocate memory for the new line buffer.
*/
SMTP_LINKAGE int
smtp_str_getdelimfd_set_line_and_buf(struct str_getdelimfd *const gdfd,
size_t copy_len){
size_t copy_len_inc;
size_t nbytes_to_shift;
size_t new_buf_len;
if(gdfd->line){
free(gdfd->line);
gdfd->line = NULL;
}
if(smtp_si_add_size_t(copy_len, 1, ©_len_inc) ||
smtp_si_add_size_t((size_t)gdfd->_buf, copy_len_inc, NULL) ||
smtp_si_sub_size_t(gdfd->_buf_len, copy_len, &nbytes_to_shift) ||
(gdfd->line = calloc(1, copy_len_inc)) == NULL){
return -1;
}
memcpy(gdfd->line, gdfd->_buf, copy_len);
gdfd->line_len = copy_len;
memmove(gdfd->_buf, gdfd->_buf + copy_len_inc, nbytes_to_shift);
if(smtp_si_sub_size_t(nbytes_to_shift, 1, &new_buf_len) == 0){
gdfd->_buf_len = new_buf_len;
}
return 0;
}
/**
* Free memory in the @ref str_getdelimfd data structure.
*
* @param[in] gdfd Frees memory stored in this socket parsing structure.
*/
SMTP_LINKAGE void
smtp_str_getdelimfd_free(struct str_getdelimfd *const gdfd){
free(gdfd->_buf);
free(gdfd->line);
gdfd->_buf = NULL;
gdfd->_bufsz = 0;
gdfd->_buf_len = 0;
gdfd->line = NULL;
gdfd->line_len = 0;
}
/**
* Free the @ref str_getdelimfd and return the @ref STRING_GETDELIMFD_ERROR
* error code.
*
* @param[in] gdfd See @ref str_getdelimfd.
* @return @ref str_getdelim_retcode.
*/
static enum str_getdelim_retcode
smtp_str_getdelimfd_throw_error(struct str_getdelimfd *const gdfd){
smtp_str_getdelimfd_free(gdfd);
return STRING_GETDELIMFD_ERROR;
}
/**
* Read and parse a delimited string using a custom socket read function.
*
* This interface handles all of the logic for expanding the buffer,
* parsing the delimiter in the buffer, and returning each "line"
* to the caller for handling.
*
* @param[in] gdfd See @ref str_getdelimfd.
* @return @ref str_getdelim_retcode.
*/
SMTP_LINKAGE enum str_getdelim_retcode
smtp_str_getdelimfd(struct str_getdelimfd *const gdfd){
size_t delim_pos;
long bytes_read;
void *read_buf_ptr;
char *buf_new;
size_t buf_sz_remaining;
size_t buf_sz_new;
if(gdfd->getdelimfd_read == NULL){
return STRING_GETDELIMFD_ERROR;
}
bytes_read = -1;
while(1){
if(smtp_str_getdelimfd_search_delim(gdfd->_buf,
gdfd->_buf_len,
gdfd->delim,
&delim_pos)){
if(smtp_str_getdelimfd_set_line_and_buf(gdfd, delim_pos) < 0){
return smtp_str_getdelimfd_throw_error(gdfd);
}
return STRING_GETDELIMFD_NEXT;
}else if(bytes_read == 0){
if(smtp_str_getdelimfd_set_line_and_buf(gdfd, gdfd->_buf_len) < 0){
return smtp_str_getdelimfd_throw_error(gdfd);
}
return STRING_GETDELIMFD_DONE;
}
if(smtp_si_sub_size_t(gdfd->_bufsz, gdfd->_buf_len, &buf_sz_remaining)){
return smtp_str_getdelimfd_throw_error(gdfd);
}
if(buf_sz_remaining < SMTP_GETDELIM_READ_SZ){
if(smtp_si_add_size_t(buf_sz_remaining,
SMTP_GETDELIM_READ_SZ,
&buf_sz_new)){
return smtp_str_getdelimfd_throw_error(gdfd);
}
buf_new = realloc(gdfd->_buf, buf_sz_new);
if(buf_new == NULL){
return smtp_str_getdelimfd_throw_error(gdfd);
}
gdfd->_buf = buf_new;
gdfd->_bufsz = buf_sz_new;
}
if(smtp_si_add_size_t((size_t)gdfd->_buf, gdfd->_buf_len, NULL)){
return smtp_str_getdelimfd_throw_error(gdfd);
}
read_buf_ptr = gdfd->_buf + gdfd->_buf_len;
bytes_read = (*gdfd->getdelimfd_read)(gdfd,
read_buf_ptr,
SMTP_GETDELIM_READ_SZ);
if(bytes_read < 0 ||
smtp_si_add_size_t(gdfd->_buf_len, bytes_read, &gdfd->_buf_len)){
return smtp_str_getdelimfd_throw_error(gdfd);
}
}
}
/**
* Copy a string and get the pointer to the end of the copied buffer.
*
* This function behaves similar to POSIX stpcpy(), useful for
* concatenating multiple strings onto a buffer. It always adds a
* null-terminated byte at the end of the string.
*
* @param[in] s1 Destination buffer.
* @param[in] s2 Null-terminated source string to copy to @p s1.
* @return Pointer to location in @p s1 after the last copied byte.
*/
SMTP_LINKAGE char *
smtp_stpcpy(char *s1,
const char *s2){
size_t i;
i = 0;
do{
s1[i] = s2[i];
} while(s2[i++] != '\0');
return &s1[i-1];
}
/**
* Reallocate memory with unsigned wrapping checks.
*
* @param[in] ptr Existing allocation buffer, or NULL when allocating a
* new buffer.
* @param[in] nmemb Number of elements to allocate.
* @param[in] size Size of each element in @p nmemb.
* @retval void* Pointer to a reallocated buffer containing
* @p nmemb * @p size bytes.
* @retval NULL Failed to reallocate memory.
*/
SMTP_LINKAGE void *
smtp_reallocarray(void *ptr,
size_t nmemb,
size_t size){
void *alloc;
size_t size_mul;
if(smtp_si_mul_size_t(nmemb, size, &size_mul)){
alloc = NULL;
errno = ENOMEM;
}
else{
alloc = realloc(ptr, size_mul);
}
return alloc;
}
/**
* Copy a string into a new dynamically allocated buffer.
*
* Returns a dynamically allocated string, with the same contents as the
* input string. The caller must free the returned string when finished.
*
* @param[in] s String to duplicate.
* @retval char* Pointer to a new dynamically allocated string duplicated
* from @p s.
* @retval NULL Failed to allocate memory for the new duplicate string.
*/
SMTP_LINKAGE char *
smtp_strdup(const char *s){
char *dup;
size_t dup_len;
size_t slen;
slen = strlen(s);
if(smtp_si_add_size_t(slen, 1, &dup_len)){
dup = NULL;
errno = ENOMEM;
}
else if((dup = malloc(dup_len)) != NULL){
memcpy(dup, s, dup_len);
}
return dup;
}
/**
* Search for all substrings in a string and replace each instance with a
* replacement string.
*
* @param[in] search Substring to search for in @p s.
* @param[in] replace Replace each instance of the search string with this.
* @param[in] s Null-terminated string to search and replace.
* @retval char* A dynamically allocated string with the replaced instances
* as described above. The caller must free the allocated
* memory when finished.
* @retval NULL Memory allocation failure.
*/
SMTP_LINKAGE char *
smtp_str_replace(const char *const search,
const char *const replace,
const char *const s){
size_t search_len;
size_t replace_len;
size_t replace_len_inc;
size_t slen;
size_t slen_inc;
size_t s_idx;
size_t snew_len;
size_t snew_len_inc;
size_t snew_sz;
size_t snew_sz_dup;
size_t snew_sz_plus_slen;
size_t snew_replace_len_inc;
char *snew;
char *stmp;
search_len = strlen(search);
replace_len = strlen(replace);
slen = strlen(s);
s_idx = 0;
snew = NULL;
snew_len = 0;
snew_sz = 0;
if(smtp_si_add_size_t(replace_len, 1, &replace_len_inc) ||
smtp_si_add_size_t(slen, 1, &slen_inc)){
return NULL;
}
if(s[0] == '\0'){
return smtp_strdup("");
}
else if(search_len < 1){
return smtp_strdup(s);
}
while(s[s_idx]){
if(smtp_si_add_size_t(snew_len, 1, &snew_len_inc) ||
smtp_si_add_size_t(snew_sz, snew_sz, &snew_sz_dup) ||
smtp_si_add_size_t(snew_sz, slen, &snew_sz_plus_slen)){
free(snew);
return NULL;
}
if(strncmp(&s[s_idx], search, search_len) == 0){
if(smtp_si_add_size_t(snew_len, replace_len_inc, &snew_replace_len_inc)){
free(snew);
return NULL;
}
if(snew_replace_len_inc >= snew_sz){
/* snew_sz += snew_sz + slen + replace_len + 1 */
if(smtp_si_add_size_t(snew_sz_dup, slen_inc, &snew_sz) ||
smtp_si_add_size_t(snew_sz, replace_len, &snew_sz) ||
(stmp = realloc(snew, snew_sz)) == NULL){
free(snew);
return NULL;
}
snew = stmp;
}
memcpy(&snew[snew_len], replace, replace_len);
snew_len += replace_len;
s_idx += search_len;
}
else{
if(snew_len_inc >= snew_sz){
/* snew_sz += snew_sz + slen + snew_len + 1 */
if(smtp_si_add_size_t(snew_sz_dup, slen, &snew_sz) ||
smtp_si_add_size_t(snew_sz, snew_len_inc, &snew_sz) ||
(stmp = realloc(snew, snew_sz)) == NULL){
free(snew);
return NULL;
}
snew = stmp;
}
snew[snew_len] = s[s_idx];
s_idx += 1;
snew_len = snew_len_inc;
}
}
snew[snew_len] = '\0';
return snew;
}
/**
* Lookup table used to encode data into base64.
*
* Base64 encoding takes six bits of data and encodes those bits using this
* table. Since 2^6 = 64, this array has 64 entries which maps directly from
* the 6 bit value into the corresponding array value.
*/
static unsigned char g_base64_encode_table[] = {
'A','B','C','D','E','F','G','H','I','J',
'K','L','M','N','O','P','Q','R','S','T',
'U','V','W','X','Y','Z',
'a','b','c','d','e','f','g','h','i','j',
'k','l','m','n','o','p','q','r','s','t',
'u','v','w','x','y','z',
'0','1','2','3','4','5','6','7','8','9',
'+','/'
};
/**
* Encode a single block of binary data into base64.
*
* @param[in] buf Buffer with data to encode.
* @param[in] buf_block_sz Number of bytes in buf to encode (min 1, max 3).
* @param[out] b64 Pointer to buffer with at least 4 bytes for
* storing the base64 encoded result.
*/
static void
smtp_base64_encode_block(const char *const buf,
size_t buf_block_sz,
char *const b64){
unsigned char inb[3] = {0};
unsigned char in_idx[4] = {0};
char outb[5] = {'=', '=', '=', '=', '\0'};
size_t i;
memcpy(inb, buf, buf_block_sz);
in_idx[0] = ((inb[0] >> 2)) & 0x3F;
in_idx[1] = ((inb[0] << 4) | ((inb[1] >> 4) & 0xF)) & 0x3F;
in_idx[2] = ((inb[1] << 2) | ((inb[2] >> 6) & 0x3)) & 0x3F;
in_idx[3] = ((inb[2] )) & 0x3F;
for(i = 0; i < 4; i++){
if(i < buf_block_sz + 1){
outb[i] = g_base64_encode_table[in_idx[i]];
}
b64[i] = outb[i];
}
}
/**
* Encode binary data into a base64 string.
*
* @param[in] buf Binary data to encode in base64.
* @param[in] buflen Number of bytes in the @p buf parameter, or -1 if
* null-terminated.
* @retval char* Dynamically allocated base64 encoded string. The caller
* must free this string when finished.
* @retval NULL Memory allocation failure.
*/
SMTP_LINKAGE char *
smtp_base64_encode(const char *const buf,
size_t buflen){
char *b64;
size_t b64_sz;
size_t buf_i;
size_t b64_i;
size_t remaining_block_sz;
size_t buf_block_sz;
if(buflen == SIZE_MAX){
buflen = strlen(buf);
}
/*
* base64 size expands by 33%
* +1 to round integer division up
* +2 for '=' padding
* +1 null terminator
*/
if(smtp_si_mul_size_t(buflen, 4, NULL)){
return NULL;
}
b64_sz = (4 * buflen / 3) + 1 + 2 + 1;
if((b64 = calloc(1, b64_sz)) == NULL){
return NULL;
}
if(buflen == 0){
return b64;
}
buf_i = 0;
b64_i = 0;
remaining_block_sz = buflen;
while(remaining_block_sz > 0){
if(remaining_block_sz >= 3){
buf_block_sz = 3;
}
else{
buf_block_sz = remaining_block_sz;
}
smtp_base64_encode_block(&buf[buf_i], buf_block_sz, &b64[b64_i]);
/*
* Do not need to check for wrapping because these values restricted to
* range of b64_sz, which has already been checked for wrapping above.
*/
buf_i += 3;
b64_i += 4;
remaining_block_sz -= buf_block_sz;
}
return b64;
}
#ifdef SMTP_OPENSSL
/**
* Lookup table used to decode base64 data.
*
* For base64 encoding, every six bits have been encoded using only the ASCII
* characters from @ref g_base64_encode_table. This table has entries which
* allow the reversal of that process. It has 128 entries which map over to
* the index value from the encoding table. If an indexing result ends up
* with -1 during the decoding process, then that indicates an invalid base64
* character in the encoded data.
*/
static signed char
g_base64_decode_table[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1,
62, /* + */
-1, -1, -1,
63, /* / */
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, /* 0 - 9 */
-1, -1, -1, -1, -1, -1, -1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* A - J */
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, /* K - T */
20, 21, 22, 23, 24, 25, /* U - Z */
-1, -1, -1, -1, -1, -1,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, /* a - j */
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, /* k - t */
46, 47, 48, 49, 50, 51, /* u - z */
-1, -1, -1, -1, -1
};
/**
* Decodes a base64 block of up to four bytes at a time.
*
* @param[in] buf Buffer containing bytes to decode.
* @param[out] decode Buffer for storing base64 decoded bytes.
* @retval >0 Length of the decoded block.
* @retval -1 If the block contains invalid base64 data.
*/
static int
smtp_base64_decode_block(const unsigned char *const buf,
unsigned char *const decode){
int decode_block_len;
size_t i;
signed char decode_table[4];
unsigned char outb[3];
decode_block_len = 0;
for(i = 0; i < 4; i++){
if(buf[i] == '='){
decode_table[i] = 0;
continue;
}
decode_table[i] = g_base64_decode_table[buf[i]];
if(decode_table[i] < 0){
return -1;
}
}
outb[0] = ((decode_table[0] << 2) & 0xFC) | ((decode_table[1] >> 4) & 0x03);
outb[1] = ((decode_table[1] << 4) & 0xF0) | ((decode_table[2] >> 2) & 0x0F);
outb[2] = ((decode_table[2] << 6) & 0xC0) | ((decode_table[3] ) & 0x3F);
decode[0] = outb[0];
decode_block_len += 1;
if(buf[2] == '='){
decode[1] = '\0';
}
else{
decode[1] = outb[1];
decode_block_len += 1;
}
if(buf[3] == '='){
decode[2] = '\0';
}
else{
decode[2] = outb[2];
decode_block_len += 1;
}
return decode_block_len;
}
/**
* Decode a base64 string.
*
* The decode parameter will get dynamically allocated by this function
* if it successfully completes. Therefore, the caller must free the decode
* parameter after use.
*
* @param[in] buf Null-terminated base64 string.
* @param[out] decode Pointer to buffer which will get dynamically allocated
* and will contain the decoded binary data. This parameter
* will get set to NULL if the memory allocation fails.
* @retval >=0 Length of the data stored in the decode parameter.
* @retval -1 Memory allocation failure or invalid base64 byte sequences.
*/
SMTP_LINKAGE long
smtp_base64_decode(const char *const buf,
unsigned char **decode){
size_t buf_len;
size_t buf_len_inc;
size_t buf_i;
unsigned char *b64_decode;
long decode_len;
int decode_block_len;
*decode = NULL;
buf_len = strlen(buf);
if(buf_len % 4 != 0){
return -1;
}
if(smtp_si_add_size_t(buf_len, 1, &buf_len_inc) ||
(b64_decode = calloc(1, buf_len_inc)) == NULL){
return -1;
}
decode_len = 0;
for(buf_i = 0; buf_i < buf_len; buf_i += 4){
if((decode_block_len = smtp_base64_decode_block(
(const unsigned char*)&buf[buf_i],
&b64_decode[decode_len])) < 0){
free(b64_decode);
return -1;
}
decode_len += decode_block_len;
}
*decode = b64_decode;
return decode_len;
}
/**
* Convert binary data to lowercase hexadecimal representation.
*
* @param[in] s Buffer containing binary data to convert.
* @param[in] slen Number of bytes in @p s.
* @retval char* Dynamically allocated string consisting of a hexadecimal
* representation of binary data in @p s. The caller must free
* this memory when finished.
* @retval NULL Memory allocation or encoding error.
*/
SMTP_LINKAGE char *
smtp_bin2hex(const unsigned char *const s,
size_t slen){
char *snew;
size_t alloc_sz;
size_t i;
size_t j;
unsigned hex;
int rc;
/* alloc_sz = slen * 2 + 1 */
if(smtp_si_mul_size_t(slen, 2, &alloc_sz) ||
smtp_si_add_size_t(alloc_sz, 1, &alloc_sz)){
return NULL;
}
if((snew = malloc(alloc_sz)) == NULL){
return NULL;
}
for(i = 0, j = 0; i < slen; i++, j += 2){
hex = s[i];
rc = sprintf(&snew[j], "%02x", hex);
if(rc < 0 || (size_t)rc >= 3){
free(snew);
return NULL;
}
}
snew[j] = '\0';
return snew;
}
#endif /* SMTP_OPENSSL */
/**
* Get the length in bytes of a UTF-8 character.
*
* This consists of a very simple check and assumes the user provides a valid
* UTF-8 byte sequence. It gets the length from the first byte in the sequence
* and does not validate any other bytes in the character sequence or any other
* bits in the first byte of the character sequence.
*
* @param[in] c The first byte in a valid UTF-8 character sequence.
* @retval >0 Number of bytes for the current UTF-8 character sequence.
* @retval -1 Invalid byte sequence.
*/
SMTP_LINKAGE int
smtp_utf8_charlen(unsigned char c){
if((c & 0x80) == 0){ /* 0XXXXXXX */
return 1;
}
else if((c & 0xE0) == 0xC0){ /* 110XXXXX */
return 2;
}
else if((c & 0xF0) == 0xE0){ /* 1110XXXX */
return 3;
}
else if((c & 0xF8) == 0xF0){ /* 11110XXX */
return 4;
}
else{ /* invalid */
return -1;
}
}
/**
* Check if a string contains non-ASCII UTF-8 characters.
*
* Uses the simple algorithm from @ref smtp_utf8_charlen to check for
* non-ASCII UTF-8 characters.
*
* @param[in] s UTF-8 string.
* @retval 1 String contains non-ASCII UTF-8 characters.
* @retval 0 String contains only ASCII characters.
*/
SMTP_LINKAGE int
smtp_str_has_nonascii_utf8(const char *const s){
int i;
int charlen;
for(i = 0; s[i]; i++){
charlen = smtp_utf8_charlen(s[i]);
if(charlen != 1){
return 1;
}
}
return 0;
}
/**
* Get the number of bytes in a UTF-8 string, or a shorter count if
* the string exceeds a maximum specified length.
*
* See @p maxlen for more information on multi-byte parsing.
*
* @param[in] s Null-terminated UTF-8 string.
* @param[in] maxlen Do not check more than @p maxlen bytes of string @p s
* except if in the middle of a multi-byte character.
* @retval strlen(s) If length of s has less bytes than maxlen or the same
* number of bytes as maxlen. See @p maxlen for more details.
* @retval maxlen If length of s has more bytes than maxlen.
* @retval -1 If @p s contains an invalid UTF-8 byte sequence.
*/
SMTP_LINKAGE long
smtp_strnlen_utf8(const char *s,
size_t maxlen){
size_t i;
int utf8_i;
int utf8_len;
for(i = 0; *s && i < maxlen; i += utf8_len){
utf8_len = smtp_utf8_charlen(*s);
if(utf8_len < 0){
return -1;
}
for(utf8_i = 0; utf8_i < utf8_len; utf8_i++){
if(!*s){
return -1;
}
s += 1;
}
}
return i;
}
/**
* Get the offset of the next whitespace block to process folding.
*
* If a string does not have whitespace before @p maxlen, then the index
* will get returned past @p maxlen. Also returns the index of NULL character
* if that fits within the next block. The caller must check for the NULL
* index to indicate the last block. It will skip past any leading whitespace
* even if that means going over maxlen.
*
* Examples:
* @ref smtp_fold_whitespace_get_offset ("Subject: Test WS", 1/2/8/9/10/13) -> 8
* @ref smtp_fold_whitespace_get_offset ("Subject: Test WS", 14/15) -> 13
* @ref smtp_fold_whitespace_get_offset ("Subject: Test WS", 17/18) -> 16
*
* @param[in] s String to get offset from.
* @param[in] maxlen Number of bytes for each line in the string (soft limit).
* @return Index in @p s.
*/
SMTP_LINKAGE size_t
smtp_fold_whitespace_get_offset(const char *const s,
unsigned int maxlen){
size_t i;
size_t offset_i;
i = 0;
offset_i = 0;
while(s[i] == ' ' || s[i] == '\t'){
i += 1;
}
while(s[i]){
if(s[i] == ' ' || s[i] == '\t'){
do{
i += 1;
} while(s[i] == ' ' || s[i] == '\t');
i -= 1;
if(i < maxlen || !offset_i){
offset_i = i;
}
else{
break;
}
}
i += 1;
}
if(!offset_i || i < maxlen){
offset_i = i;
}
return offset_i;
}
/**
* Email header lines should have no more than 78 characters and must
* not be more than 998 characters.
*/
#define SMTP_LINE_MAX 78
/**
* Fold a line at whitespace characters.
*
* This function tries to keep the total number of characters per line under
* @p maxlen, but does not guarantee this. For really long text with no
* whitespace, the line will still extend beyond @p maxlen and possibly
* beyond the RFC limit as defined in @ref SMTP_LINE_MAX. This is by design
* and intended to keep the algorithm simpler to implement. Users sending
* long headers with no space characters should not assume that will work,
* but modern email systems may correctly process those headers anyways.
*
* Lines get folded by adding a [CR][LF] and then two space characters on the
* beginning of the next line. For example, this Subject line:
*
* Subject: Email[WS][WS]Header
*
* Would get folded like this (assuming a small @p maxlen):
*
* Subject: Email[WS][CR][LF]
* [WS][WS]Header
*
* @param[in] s String to fold.
* @param[in] maxlen Number of bytes for each line in the string (soft limit).
* The minimum value of this parameter is 3 and it will get
* forced to 3 if the provided value is less.
* @retval char* Pointer to an allocated string with the contents split into
* separate lines. The caller must free this memory when done.
* @retval NULL Memory allocation failed.
*/
SMTP_LINKAGE char *
smtp_fold_whitespace(const char *const s,
unsigned int maxlen){
const char *const SMTP_LINE_FOLD_STR = "\r\n ";
size_t end_slen;
size_t s_i;
size_t buf_i;
size_t bufsz;
size_t ws_offset;
char *buf;
char *buf_new;
if(maxlen < 3){
maxlen = 3;
}
end_slen = strlen(SMTP_LINE_FOLD_STR);
s_i = 0;
buf_i = 0;
bufsz = 0;
buf = NULL;
while(1){
ws_offset = smtp_fold_whitespace_get_offset(&s[s_i], maxlen - 2);
/* bufsz += ws_offset + end_slen + 1 */
if(smtp_si_add_size_t(bufsz, ws_offset, &bufsz) ||
smtp_si_add_size_t(bufsz, end_slen, &bufsz) ||
smtp_si_add_size_t(bufsz, 1, &bufsz) ||
(buf_new = realloc(buf, bufsz)) == NULL){
free(buf);
return NULL;
}
buf = buf_new;
memcpy(&buf[buf_i], &s[s_i], ws_offset);
buf[buf_i + ws_offset] = '\0';
if(s[s_i + ws_offset] == '\0'){
break;
}
buf_i += ws_offset;
strcat(&buf[buf_i], SMTP_LINE_FOLD_STR);
buf_i += end_slen;
/* WS */
s_i += ws_offset + 1;
}
return buf;
}
/**
* Splits a string into smaller chunks separated by a terminating string.
*
* @param[in] s The string to chunk.
* @param[in] chunklen Number of bytes for each chunk in the string.
* @param[in] end Terminating string placed at the end of each chunk.
* @retval char* Pointer to an allocated string with the contents split into
* separate chunks. The caller must free this memory when done.
* @retval NULL Memory allocation failure.
*/
SMTP_LINKAGE char *
smtp_chunk_split(const char *const s,
size_t chunklen,
const char *const end){
char *snew;
size_t bodylen;
size_t bodylen_inc;
size_t endlen;
size_t endlen_inc;
size_t snewlen;
size_t chunk_i;
size_t snew_i;
size_t body_i;
long body_copy_len;
if(chunklen < 1){
errno = EINVAL;
return NULL;
}
bodylen = strlen(s);
endlen = strlen(end);
if(bodylen < 1){
return smtp_strdup(end);
}
/*
* \0
* snewlen = bodylen + (endlen + 1) * (bodylen / chunklen + 1) + 1
*/
if(smtp_si_add_size_t(endlen, 1, &endlen_inc) ||
smtp_si_add_size_t(bodylen, 1, &bodylen_inc) ||
smtp_si_mul_size_t(endlen_inc, bodylen / chunklen + 1, &snewlen) ||
smtp_si_add_size_t(snewlen, bodylen_inc, &snewlen) ||
(snew = calloc(1, snewlen)) == NULL){
return NULL;
}
body_i = 0;
snew_i = 0;
for(chunk_i = 0; chunk_i < bodylen / chunklen + 1; chunk_i++){
body_copy_len = smtp_strnlen_utf8(&s[body_i], chunklen);
if(body_copy_len < 0){
free(snew);
errno = EINVAL;
return NULL;
}
memcpy(&snew[snew_i], &s[body_i], body_copy_len);
snew_i += body_copy_len;
if(s[body_i] == '\0'){
snew_i += 1;
}
body_i += body_copy_len;
if(endlen > 0){
memcpy(&snew[snew_i], end, endlen);
}
snew_i += endlen;
}
return snew;
}
/**
* Read the entire contents of a file stream and store the data into a
* dynamically allocated buffer.
*
* @param[in] stream File stream already opened by the caller.
* @param[out] bytes_read Number of bytes stored in the return buffer.
* @retval char* A dynamically allocated buffer which contains the entire
* contents of @p stream. The caller must free this memory
* when done.
* @retval NULL Memory allocation or file read error.
*/
SMTP_LINKAGE char *
smtp_ffile_get_contents(FILE *stream,
size_t *bytes_read){
char *read_buf;
size_t bufsz;
size_t bufsz_inc;
char *new_buf;
size_t bytes_read_loop;
const size_t BUFSZ_INCREMENT = 512;
read_buf = NULL;
bufsz = 0;
if(bytes_read){
*bytes_read = 0;
}
do{
if(smtp_si_add_size_t(bufsz, BUFSZ_INCREMENT, &bufsz_inc) ||
(new_buf = realloc(read_buf, bufsz_inc)) == NULL){
free(read_buf);
return NULL;
}
read_buf = new_buf;
bufsz = bufsz_inc;
bytes_read_loop = fread(&read_buf[bufsz - BUFSZ_INCREMENT],
sizeof(char),
BUFSZ_INCREMENT,
stream);
if(bytes_read){
*bytes_read += bytes_read_loop;
}
if(ferror(stream)){
free(read_buf);
return NULL;
}
} while(!feof(stream));
return read_buf;
}
/**
* Read the entire contents of a file from a given path, and store the data
* into a dynamically allocated buffer.
*
* @param[in] filename Path of file to open and read from.
* @param[out] bytes_read Number of bytes stored in the return buffer.
* @retval char* A dynamically allocated buffer which has the contents of
* the file at @p filename. The caller must free this memory when
* done.
* @retval NULL Memory allocation or file read error.
*/
SMTP_LINKAGE char *
smtp_file_get_contents(const char *const filename,
size_t *bytes_read){
FILE *fp;
char *read_buf;
if((fp = fopen(filename, "r")) == NULL){
return NULL;
}
read_buf = smtp_ffile_get_contents(fp, bytes_read);
if(fclose(fp) == EOF){
free(read_buf);
read_buf = NULL;
}
return read_buf;
}
/**
* Parse a server response line into the @ref smtp_command data structure.
*
* @param[in] line Server response string.
* @param[out] cmd Structure containing the server response data broken up
* into its separate components.
* @return See @ref smtp_result_code.
*/
SMTP_LINKAGE int
smtp_parse_cmd_line(char *const line,
struct smtp_command *const cmd){
char *ep;
char code_str[4];
size_t line_len;
line_len = strlen(line);
if(line_len < 5){
cmd->code = SMTP_INTERNAL_ERROR;
cmd->more = 0;
cmd->text = line;
return cmd->code;
}
cmd->text = &line[4];
memcpy(code_str, line, 3);
code_str[3] = '\0';
cmd->code = strtoul(code_str, &ep, 10);
if(*ep != '\0'){
cmd->code = SMTP_INTERNAL_ERROR;
}
cmd->more = line[3] == '-' ? 1 : 0;
return cmd->code;
}
/**
* Prints communication between the client and server to stderr only if
* the debug flag has been set.
*
* @param[in] smtp SMTP client context.
* @param[in] prefix Print this prefix before the main debug line text.
* @param[in] str Debug text to print out.
*/
static void
smtp_puts_dbg(struct smtp *const smtp,
const char *const prefix,
const char *const str){
char *sdup;
size_t i;
if(smtp->flags & SMTP_DEBUG){
if((sdup = smtp_strdup(str)) == NULL){
return;
}
/* Remove carriage return and newline when printing to stderr. */
for(i = 0; sdup[i]; i++){
if(sdup[i] == '\r' || sdup[i] == '\n'){
sdup[i] = ' ';
}
}
if(fprintf(stderr, "[smtp %s]: %s\n", prefix, sdup) < 0){
/* Do not care if this fails. */
}
free(sdup);
}
}
/**
* Read a server response line.
*
* @param[in] smtp SMTP client context.
* @return @ref str_getdelim_retcode.
*/
static enum str_getdelim_retcode
smtp_getline(struct smtp *const smtp){
enum str_getdelim_retcode rc;
errno = 0;
rc = smtp_str_getdelimfd(&smtp->gdfd);
if(errno == ENOMEM){
smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
return rc;
}
else if(rc == STRING_GETDELIMFD_ERROR){
smtp_status_code_set(smtp, SMTP_STATUS_RECV);
return STRING_GETDELIMFD_ERROR;
}
if(smtp->gdfd.line_len > 0){
/* Remove the carriage-return character ('\r'). */
smtp->gdfd.line[smtp->gdfd.line_len - 1] = '\0';
smtp_puts_dbg(smtp, "Server", smtp->gdfd.line);
}
return rc;
}
/**
* Loop through all of the server response lines until the last line, and
* then return the status code from the last response line.
*
* @param[in] smtp SMTP client context.
* @return @ref smtp_result_code.
*/
static int
smtp_read_and_parse_code(struct smtp *const smtp){
struct smtp_command cmd;
enum str_getdelim_retcode rc;
do{
rc = smtp_getline(smtp);
if(rc == STRING_GETDELIMFD_ERROR){
return SMTP_INTERNAL_ERROR;
}
smtp_parse_cmd_line(smtp->gdfd.line, &cmd);
}while (rc != STRING_GETDELIMFD_DONE && cmd.more);
return cmd.code;
}
/**
* Send data to the SMTP server.
*
* Writes a buffer of length len into either the unencrypted TCP socket or
* the TLS encrypted socket, depending on the current underlying mode of
* the socket.
*
* @param[in] smtp SMTP client context.
* @param[in] buf Data to send to the SMTP server.
* @param[in] len Number of bytes in buf.
* @return @ref smtp_status_code.
*/
SMTP_LINKAGE enum smtp_status_code
smtp_write(struct smtp *const smtp,
const char *const buf,
size_t len){
size_t bytes_to_send;
int bytes_sent;
const char *buf_offset;
smtp_puts_dbg(smtp, "Client", buf);
bytes_to_send = len;
buf_offset = buf;
while(bytes_to_send){
if(bytes_to_send > INT_MAX){
return smtp_status_code_set(smtp, SMTP_STATUS_SEND);
}
if(smtp->tls_on){
#ifdef SMTP_OPENSSL
bytes_sent = SSL_write(smtp->tls, buf_offset, bytes_to_send);
if(bytes_sent <= 0){
return smtp_status_code_set(smtp, SMTP_STATUS_SEND);
}
#else /* !(SMTP_OPENSSL) */
/* unreachable */
bytes_sent = 0;
#endif /* SMTP_OPENSSL */
}
else{
bytes_sent = send(smtp->sock, buf_offset, bytes_to_send, 0);
if(bytes_sent < 0){
return smtp_status_code_set(smtp, SMTP_STATUS_SEND);
}
}
bytes_to_send -= bytes_sent;
buf_offset += bytes_sent;
}
return smtp->status_code;
}
/**
* Send a null-terminated string to the SMTP server.
*
* @param[in] smtp SMTP client context.
* @param[in] s Null-terminated string to send to the SMTP server.
* @return See @ref smtp_status_code and @ref smtp_write.
*/
static enum smtp_status_code
smtp_puts(struct smtp *const smtp,
const char *const s){
return smtp_write(smtp, s, strlen(s));
}
/**
* Same as @ref smtp_puts except this function also appends the line
* terminating carriage return and newline bytes at the end of the string.
*
* @param[in] smtp SMTP client context.
* @param[in] s Null-terminated string to send to the SMTP server.
* @return See @ref smtp_status_code and @ref smtp_puts.
*/
static enum smtp_status_code
smtp_puts_terminate(struct smtp *const smtp,
const char *const s){
int rc;
char *line;
char *concat;
size_t slen;
size_t allocsz;
slen = strlen(s);
if(smtp_si_add_size_t(slen, 3, &allocsz) ||
(line = malloc(allocsz)) == NULL){
return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
}
concat = smtp_stpcpy(line, s);
smtp_stpcpy(concat, "\r\n");
rc = smtp_puts(smtp, line);
free(line);
return rc;
}
/**
* Connect to the server using a standard TCP socket.
*
* This function handles the server name lookup to get an IP address
* for the server, and then to connect to that IP using a normal TCP
* connection.
*
* @param[in] smtp SMTP client context.
* @param[in] server Mail server name or IP address.
* @param[in] port Mail server port number.
* @retval 0 Successfully connected to server.
* @retval -1 Failed to connect to server.
*/
static int
smtp_connect(struct smtp *const smtp,
const char *const server,
const char *const port){
struct addrinfo hints;
struct addrinfo *res0;
struct addrinfo *res;
/*
* Windows requires initializing the socket library before we call any
* socket functions.
*/
#ifdef SMTP_IS_WINDOWS
/* Windows global network socket data structure. */
WSADATA wsa_data;
if(WSAStartup(MAKEWORD(2, 2), &wsa_data) != 0){
return -1;
}
#endif /* SMTP_IS_WINDOWS */
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = 0;
hints.ai_protocol = IPPROTO_TCP;
if(getaddrinfo(server, port, &hints, &res0) != 0){
return -1;
}
for(res = res0; res; res = res->ai_next){
smtp->sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if(smtp->sock < 0){
continue;
}
if(connect(smtp->sock, res->ai_addr, res->ai_addrlen) < 0){
#ifdef SMTP_IS_WINDOWS
closesocket(smtp->sock);
#else /* POSIX */
close(smtp->sock);
#endif /* SMTP_IS_WINDOWS */
smtp->sock = -1;
}
else{
break;
}
}
freeaddrinfo(res0);
if(smtp->sock < 0){
return -1;
}
return 0;
}
#ifdef SMTP_OPENSSL
/**
* Initialize the TLS library and establish a TLS handshake with the server
* over the existing socket connection.
*
* @param[in] smtp SMTP client context.
* @param[in] server Server name or IP address.
* @retval 0 Successfully established a TLS connection with the server.
* @retval -1 Failed to establish a TLS connection with the server.
*/
static int
smtp_tls_init(struct smtp *const smtp,
const char *const server){
X509 *X509_cert_peer;
/* Do not need to check the return value since this always returns 1. */
SSL_library_init();
SSL_load_error_strings();
ERR_load_BIO_strings();
OpenSSL_add_all_algorithms();
if((smtp->tls_ctx = SSL_CTX_new(SSLv23_client_method())) == NULL){
return -1;
}
/* Disable SSLv2, SSLv3, and TLSv1.0. */
SSL_CTX_set_options(smtp->tls_ctx,
SSL_OP_NO_SSLv2 |
SSL_OP_NO_SSLv3 |
SSL_OP_NO_TLSv1);
SSL_CTX_set_mode(smtp->tls_ctx, SSL_MODE_AUTO_RETRY);
if((smtp->flags & SMTP_NO_CERT_VERIFY) == 0){
SSL_CTX_set_verify(smtp->tls_ctx, SSL_VERIFY_PEER, NULL);
}
/*
* Set the path to the user-provided CA file or use the default cert paths
* if not provided.
*/
if(smtp->cafile){
if(SSL_CTX_load_verify_locations(smtp->tls_ctx, smtp->cafile, NULL) != 1){
SSL_CTX_free(smtp->tls_ctx);
return -1;
}
}
else{
X509_STORE_set_default_paths(SSL_CTX_get_cert_store(smtp->tls_ctx));
if(ERR_peek_error() != 0){
SSL_CTX_free(smtp->tls_ctx);
return -1;
}
}
if((smtp->tls = SSL_new(smtp->tls_ctx)) == NULL){
SSL_CTX_free(smtp->tls_ctx);
return -1;
}
if((smtp->tls_bio = BIO_new_socket(smtp->sock, 0)) == NULL){
SSL_CTX_free(smtp->tls_ctx);
SSL_free(smtp->tls);
return -1;
}
SSL_set_bio(smtp->tls, smtp->tls_bio, smtp->tls_bio);
SSL_set_connect_state(smtp->tls);
if(SSL_connect(smtp->tls) != 1){
SSL_CTX_free(smtp->tls_ctx);
SSL_free(smtp->tls);
return -1;
}
if(SSL_do_handshake(smtp->tls) != 1){
SSL_CTX_free(smtp->tls_ctx);
SSL_free(smtp->tls);
return -1;
}
/* Verify matching subject in certificate. */
if((smtp->flags & SMTP_NO_CERT_VERIFY) == 0){
if((X509_cert_peer = SSL_get_peer_certificate(smtp->tls)) == NULL){
SSL_CTX_free(smtp->tls_ctx);
SSL_free(smtp->tls);
return -1;
}
if(X509_check_host(X509_cert_peer, server, 0, 0, NULL) != 1){
SSL_CTX_free(smtp->tls_ctx);
SSL_free(smtp->tls);
return -1;
}
X509_free(X509_cert_peer);
}
smtp->tls_on = 1;
return 0;
}
#endif /* SMTP_OPENSSL */
/**
* Send the EHLO command and parse through the responses.
*
* Ignores all of the server extensions that get returned. If a server
* doesn't support an extension we need, then we should receive an error
* later on when we try to use that extension.
*
* @param[in] smtp SMTP client context.
* @return @ref smtp_status_code.
*/
static int
smtp_ehlo(struct smtp *const smtp){
if(smtp_puts(smtp, "EHLO smtp\r\n") != SMTP_STATUS_OK){
return smtp->status_code;
}
smtp_read_and_parse_code(smtp);
return smtp->status_code;
}
/**
* Authenticate using the PLAIN method.
*
* 1. Set the text to the following format: "\0<user>\0<password>",
* or as shown in the format string: "\0%s\0%s", email, password.
* 2. Base64 encode the text from (1).
* 3. Send the constructed auth text from (2) to the server:
* "AUTH PLAIN <b64>\r\n".
*
* @param[in] smtp SMTP client context.
* @param[in] user SMTP account user name.
* @param[in] pass SMTP account password.
* @retval 0 Successfully authenticated.
* @retval -1 Failed to authenticate.
*/
static int
smtp_auth_plain(struct smtp *const smtp,
const char *const user,
const char *const pass){
size_t user_len;
size_t pass_len;
char *login_str;
size_t login_len;
char *login_b64;
size_t login_b64_len;
char *login_send;
char *concat;
/* (1) */
user_len = strlen(user);
pass_len = strlen(pass);
/* login_len = 1 + user_len + 1 + pass_len */
if(smtp_si_add_size_t(user_len, pass_len, &login_len) ||
smtp_si_add_size_t(login_len, 2, &login_len) ||
(login_str = malloc(login_len)) == NULL){
return -1;
}
login_str[0] = '\0';
memcpy(&login_str[1], user, user_len);
login_str[1 + user_len] = '\0';
memcpy(&login_str[1 + user_len + 1], pass, pass_len);
/* (2) */
login_b64 = smtp_base64_encode(login_str, login_len);
free(login_str);
if(login_b64 == NULL){
return -1;
}
/* (3) */
login_b64_len = strlen(login_b64);
if(smtp_si_add_size_t(login_b64_len, 14, &login_b64_len) ||
(login_send = malloc(login_b64_len)) == NULL){
free(login_b64);
return -1;
}
concat = smtp_stpcpy(login_send, "AUTH PLAIN ");
concat = smtp_stpcpy(concat, login_b64);
smtp_stpcpy(concat, "\r\n");
free(login_b64);
smtp_puts(smtp, login_send);
free(login_send);
if(smtp->status_code != SMTP_STATUS_OK){
return -1;
}
if(smtp_read_and_parse_code(smtp) != SMTP_AUTH_SUCCESS){
return -1;
}
return 0;
}
/**
* Authenticate using the LOGIN method.
*
* 1. Base64 encode the user name.
* 2. Send string from (1) as part of the login:
* "AUTH LOGIN <b64_username>\r\n".
* 3. Base64 encode the password and send that by itself on a separate
* line: "<b64_password>\r\n".
*
* @param[in] smtp SMTP client context.
* @param[in] user SMTP account user name.
* @param[in] pass SMTP account password.
* @retval 0 Successfully authenticated.
* @retval -1 Failed to authenticate.
*/
static int
smtp_auth_login(struct smtp *const smtp,
const char *const user,
const char *const pass){
char *b64_user;
char *b64_pass;
size_t b64_user_len;
char *login_str;
char *concat;
/* (1) */
if((b64_user = smtp_base64_encode(user, -1)) == NULL){
return -1;
}
/* (2) */
b64_user_len = strlen(b64_user);
if(smtp_si_add_size_t(b64_user_len, 14, &b64_user_len) ||
(login_str = malloc(b64_user_len)) == NULL){
free(b64_user);
return -1;
}
concat = smtp_stpcpy(login_str, "AUTH LOGIN ");
concat = smtp_stpcpy(concat, b64_user);
smtp_stpcpy(concat, "\r\n");
free(b64_user);
smtp_puts(smtp, login_str);
free(login_str);
if(smtp->status_code != SMTP_STATUS_OK){
return -1;
}
if(smtp_read_and_parse_code(smtp) != SMTP_AUTH_CONTINUE){
return -1;
}
/* (3) */
if((b64_pass = smtp_base64_encode(pass, -1)) == NULL){
return -1;
}
smtp_puts_terminate(smtp, b64_pass);
free(b64_pass);
if(smtp->status_code != SMTP_STATUS_OK){
return -1;
}
if(smtp_read_and_parse_code(smtp) != SMTP_AUTH_SUCCESS){
return -1;
}
return 0;
}
#ifdef SMTP_OPENSSL
/**
* Authenticate using the CRAM-MD5 method.
*
* 1. Send "AUTH CRAM-MD5\r\n" to the server.
* 2. Decode the base64 challenge response from the server.
* 3. Do an MD5 HMAC on (2) using the account password as the key.
* 4. Convert the binary data in (3) to lowercase hex characters.
* 5. Construct the string: "<user> <(4)>".
* 6. Encode (5) into base64 format.
* 7. Send the final string from (6) to the server and check the response.
*
* @param[in] smtp SMTP client context.
* @param[in] user SMTP account user name.
* @param[in] pass SMTP account password.
* @retval 0 Successfully authenticated.
* @retval -1 Failed to authenticate.
*/
static int
smtp_auth_cram_md5(struct smtp *const smtp,
const char *const user,
const char *const pass){
struct smtp_command cmd;
unsigned char *challenge_decoded;
long challenge_decoded_len;
const char *key;
int key_len;
unsigned char hmac[EVP_MAX_MD_SIZE];
unsigned int hmac_len;
unsigned char *hmac_ret;
char *challenge_hex;
size_t user_len;
size_t challenge_hex_len;
char *auth_concat;
char *concat;
size_t auth_concat_len;
char *b64_auth;
/* (1) */
if(smtp_puts(smtp, "AUTH CRAM-MD5\r\n") != SMTP_STATUS_OK){
return -1;
}
if(smtp_getline(smtp) == STRING_GETDELIMFD_ERROR){
return -1;
}
if(smtp_parse_cmd_line(smtp->gdfd.line, &cmd) != SMTP_AUTH_CONTINUE){
return -1;
}
/* (2) */
challenge_decoded_len = smtp_base64_decode(cmd.text, &challenge_decoded);
if(challenge_decoded_len < 0){
return -1;
}
/* (3) */
key = pass;
key_len = strlen(pass);
hmac_ret = HMAC(EVP_md5(),
key, key_len,
challenge_decoded, challenge_decoded_len,
hmac, &hmac_len);
free(challenge_decoded);
if(hmac_ret == NULL){
return -1;
}
/* (4) */
challenge_hex = smtp_bin2hex(hmac, hmac_len);
if(challenge_hex == NULL){
return -1;
}
/* (5) */
user_len = strlen(user);
challenge_hex_len = strlen(challenge_hex);
/* auth_concat_len = user_len + 1 + challenge_hex_len + 1 */
if(smtp_si_add_size_t(user_len, challenge_hex_len, &auth_concat_len) ||
smtp_si_add_size_t(auth_concat_len, 2, &auth_concat_len) ||
(auth_concat = malloc(auth_concat_len)) == NULL){
free(challenge_hex);
return -1;
}
concat = smtp_stpcpy(auth_concat, user);
concat = smtp_stpcpy(concat, " ");
smtp_stpcpy(concat, challenge_hex);
free(challenge_hex);
/* (6) */
b64_auth = smtp_base64_encode(auth_concat, auth_concat_len - 1);
free(auth_concat);
if(b64_auth == NULL){
return -1;
}
/* (7) */
smtp_puts_terminate(smtp, b64_auth);
free(b64_auth);
if(smtp->status_code != SMTP_STATUS_OK){
return -1;
}
if(smtp_read_and_parse_code(smtp) != SMTP_AUTH_SUCCESS){
return -1;
}
return 0;
}
#endif /* SMTP_OPENSSL */
/**
* Set the timeout for the next socket read operation.
*
* @param[in] smtp SMTP client context.
* @param[in] seconds Timeout in seconds.
*/
static void
smtp_set_read_timeout(struct smtp *const smtp,
long seconds){
smtp->timeout_sec = seconds;
}
/**
* Perform a handshake with the SMTP server which includes optionally
* setting up TLS and sending the EHLO greeting.
*
* At this point, the client has already connected to the SMTP server
* through its socket connection. In this function, the client will:
* 1. Optionally convert the connection to TLS (SMTP_SECURITY_TLS).
* 2. Read the initial server greeting.
* 3. Send an EHLO to the server.
* 4. Optionally initiate STARTTLS and resend the EHLO
* (SMTP_SECURITY_STARTTLS).
*
* @param[in] smtp SMTP client context.
* @param[in] server Server name or IP address.
* @param[in] connection_security See @ref smtp_connection_security.
* @return @ref smtp_status_code.
*/
static int
smtp_initiate_handshake(struct smtp *const smtp,
const char *const server,
enum smtp_connection_security connection_security){
/* Eliminate unused warnings if not using SMTP_OPENSSL. */
(void)server;
(void)connection_security;
/* (1) */
#ifdef SMTP_OPENSSL
if(connection_security == SMTP_SECURITY_TLS){
if(smtp_tls_init(smtp, server) < 0){
return smtp_status_code_set(smtp, SMTP_STATUS_HANDSHAKE);
}
}
#endif /* SMTP_OPENSSL */
/* (2) */
/* Get initial 220 message - 5 minute timeout. */
smtp_set_read_timeout(smtp, 60 * 5);
if(smtp_getline(smtp) == STRING_GETDELIMFD_ERROR){
return smtp->status_code;
}
/* (3) */
if(smtp_ehlo(smtp) != SMTP_STATUS_OK){
return smtp->status_code;
}
/* (4) */
#ifdef SMTP_OPENSSL
if(connection_security == SMTP_SECURITY_STARTTLS){
if(smtp_puts(smtp, "STARTTLS\r\n") != SMTP_STATUS_OK){
return smtp->status_code;
}
if(smtp_read_and_parse_code(smtp) != SMTP_READY){
return smtp_status_code_set(smtp, SMTP_STATUS_HANDSHAKE);
}
if(smtp_tls_init(smtp, server) < 0){
return smtp_status_code_set(smtp, SMTP_STATUS_HANDSHAKE);
}
if(smtp_ehlo(smtp) != SMTP_STATUS_OK){
return smtp->status_code;
}
}
#endif /* SMTP_OPENSSL */
return smtp->status_code;
}
/**
Maximum size of an RFC 2822 date string.
@verbatim
Thu, 21 May 1998 05:33:29 -0700
12345678901234567890123456789012
10 20 30 32 (bytes)
@endverbatim
Add more bytes to the 32 maximum size to silence compiler warning on the
computed UTF offset.
*/
#define SMTP_DATE_MAX_SZ (32 + 5)
/**
* Convert the time into an RFC 2822 formatted string.
*
* Example date format:
* Thu, 21 May 1998 05:33:29 -0700
*
* @param[out] date Buffer that has at least SMTP_DATE_MAX_SZ bytes.
* @retval 0 Successfully copied the current date to the buffer.
* @retval -1 Failed to establish the current date or an output
* format error occurred.
*/
SMTP_LINKAGE int
smtp_date_rfc_2822(char *const date){
time_t t;
time_t t_local;
time_t t_utc;
struct tm tm_local;
struct tm tm_utc;
long offset_utc;
int rc;
const char weekday_abbreviation[7][4] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
const char month_abbreviation[12][4] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
if((t = time(NULL)) == (time_t)(-1)){
return -1;
}
#ifdef SMTP_IS_WINDOWS
if(localtime_s(&tm_local, &t) ||
gmtime_s(&tm_utc, &t)){
return -1;
}
#else /* POSIX */
/* Not defined if system does not have localtime_r or gmtime_r. */
# ifdef SMTP_TIME_NO_REENTRANT
struct tm *tm;
/* localtime() not thread-safe. */
if((tm = localtime(&t)) == NULL){
return -1;
}
memcpy(&tm_local, tm, sizeof(tm_local));
/* gmtime() not thread-safe. */
if((tm = gmtime(&t)) == NULL){
return -1;
}
memcpy(&tm_utc, tm, sizeof(tm_utc));
# else /* Reentrant versions: localtime_r() and gmtime_r(). */
if(localtime_r(&t, &tm_local) == NULL ||
gmtime_r(&t, &tm_utc) == NULL){
return -1;
}
# endif /* SMTP_TIME_NO_REENTRANT */
#endif /* SMTP_IS_WINDOWS */
if((t_local = mktime(&tm_local)) == (time_t)(-1)){
return -1;
}
if((t_utc = mktime(&tm_utc)) == (time_t)(-1)){
return -1;
}
/*
* After computing the offset, it will contain a maximum of 4 digits.
* For example, PST time zone will have an offset of -800 which will get
* formatted as -0800 in the sprintf call below.
*/
offset_utc = difftime(t_local, t_utc);
offset_utc = offset_utc / 60 / 60 * 100;
rc = sprintf(date,
"%s, %02d %s %d %02d:%02d:%02d %0+5ld",
weekday_abbreviation[tm_local.tm_wday],
tm_local.tm_mday,
month_abbreviation[tm_local.tm_mon],
tm_local.tm_year + 1900,
tm_local.tm_hour,
tm_local.tm_min,
tm_local.tm_sec, /* 0 - 60 (leap second) */
offset_utc);
if(rc + 1 != SMTP_DATE_MAX_SZ - 5){ /* See @ref SMTP_DATE_MAX_SZ for -5. */
return -1;
}
return 0;
}
/**
* Minimum length of buffer required to hold the MIME boundary test:
* mimeXXXXXXXXXX
* 123456789012345
* 1 10 15 bytes
*/
#define SMTP_MIME_BOUNDARY_LEN 15
/**
* Generate the MIME boundary text field and store it in a user-supplied
* buffer.
*
* For example:
* mimeXXXXXXXXXX
* where each X gets set to a pseudo-random uppercase ASCII character.
*
* This uses a simple pseudo-random number generator since we only care
* about preventing accidental boundary collisions.
*
* @param[out] boundary Buffer that has at least SMTP_MIME_BOUNDARY_LEN bytes.
*/
static void
smtp_gen_mime_boundary(char *const boundary){
size_t i;
strcpy(boundary, "mime");
srand(time(NULL));
for(i = 4; i < SMTP_MIME_BOUNDARY_LEN - 1; i++){
/* Modulo bias okay since we only need to prevent accidental collision. */
boundary[i] = rand() % 26 + 'A';
}
boundary[SMTP_MIME_BOUNDARY_LEN - 1] = '\0';
}
/**
* Print the MIME header and the MIME section containing the email body.
*
* @param[in] smtp SMTP client context.
* @param[in] boundary MIME boundary text.
* @param[in] body Email body text.
* @return @ref smtp_status_code.
*/
static int
smtp_print_mime_header_and_body(struct smtp *const smtp,
const char *const boundary,
const char *const body){
/* Buffer size for the static MIME text used below. */
const size_t MIME_TEXT_BUFSZ = 1000;
char *data_double_dot;
size_t data_double_dot_len;
char *data_header_and_body;
char *concat;
/*
* Insert an extra dot for each line that begins with a dot. This will
* prevent data in the body parameter from prematurely ending the DATA
* segment.
*/
if((data_double_dot = smtp_str_replace("\r\n.", "\r\n..", body)) == NULL){
return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
}
data_double_dot_len = strlen(data_double_dot);
if(smtp_si_add_size_t(data_double_dot_len,
MIME_TEXT_BUFSZ,
&data_double_dot_len) ||
(data_header_and_body = malloc(data_double_dot_len)) == NULL){
free(data_double_dot);
return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
}
concat = smtp_stpcpy(data_header_and_body,
"MIME-Version: 1.0\r\n"
"Content-Type: multipart/mixed; boundary=");
concat = smtp_stpcpy(concat,
boundary);
concat = smtp_stpcpy(concat,
"\r\n"
"\r\n"
"Multipart MIME message.\r\n"
"--");
concat = smtp_stpcpy(concat,
boundary);
concat = smtp_stpcpy(concat,
"\r\n"
"Content-Type: text/plain; charset=\"UTF-8\"\r\n"
"\r\n");
concat = smtp_stpcpy(concat,
data_double_dot);
smtp_stpcpy(concat,
"\r\n"
"\r\n");
free(data_double_dot);
smtp_puts(smtp, data_header_and_body);
free(data_header_and_body);
return smtp->status_code;
}
/**
* Print a MIME section containing an attachment.
*
* @param[in] smtp SMTP client context.
* @param[in] boundary MIME boundary text.
* @param[in] attachment @ref smtp_attachment.
* @return @ref smtp_status_code.
*/
static int
smtp_print_mime_attachment(struct smtp *const smtp,
const char *const boundary,
const struct smtp_attachment *const attachment){
/* Buffer size for the static MIME text used below. */
const size_t MIME_TEXT_BUFSZ = 1000;
size_t name_len;
size_t b64_data_len;
size_t bufsz;
char *mime_attach_text;
char *concat;
name_len = strlen(attachment->name);
b64_data_len = strlen(attachment->b64_data);
/*
* bufsz = SMTP_MIME_BOUNDARY_LEN + name_len + b64_data_len + MIME_TEXT_BUFSZ
*/
if(smtp_si_add_size_t(name_len, b64_data_len, &bufsz) ||
smtp_si_add_size_t(bufsz,
SMTP_MIME_BOUNDARY_LEN + MIME_TEXT_BUFSZ,
&bufsz) ||
(mime_attach_text = malloc(bufsz)) == NULL){
return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
}
concat = smtp_stpcpy(mime_attach_text,
"--");
concat = smtp_stpcpy(concat,
boundary);
concat = smtp_stpcpy(concat,
"\r\n"
"Content-Type: application/octet-stream\r\n"
"Content-Disposition: attachment; filename=\"");
concat = smtp_stpcpy(concat,
attachment->name);
concat = smtp_stpcpy(concat,
"\"\r\n"
"Content-Transfer-Encoding: base64\r\n"
"\r\n");
concat = smtp_stpcpy(concat,
attachment->b64_data);
smtp_stpcpy(concat,
"\r\n"
"\r\n");
smtp_puts(smtp, mime_attach_text);
free(mime_attach_text);
return smtp->status_code;
}
/**
* Prints double hyphen on both sides of the MIME boundary which indicates
* the end of the MIME sections.
*
* @param[in] smtp SMTP client context.
* @param[in] boundary MIME boundary text.
* @return See @ref smtp_status_code and @ref smtp_puts.
*/
static int
smtp_print_mime_end(struct smtp *const smtp,
const char *const boundary){
char *concat;
char mime_end[2 + SMTP_MIME_BOUNDARY_LEN + 4 + 1];
concat = smtp_stpcpy(mime_end, "--");
concat = smtp_stpcpy(concat, boundary);
smtp_stpcpy(concat, "--\r\n");
return smtp_puts(smtp, mime_end);
}
/**
* Send the main email body to the SMTP server.
*
* This includes the MIME sections for the email body and attachments.
*
* @param[in] smtp SMTP client context.
* @param[in] body Null-terminated string to send in the email body.
* @return @ref smtp_status_code.
*/
static int
smtp_print_mime_email(struct smtp *const smtp,
const char *const body){
char boundary[SMTP_MIME_BOUNDARY_LEN];
size_t i;
struct smtp_attachment *attachment;
smtp_gen_mime_boundary(boundary);
if(smtp_print_mime_header_and_body(smtp, boundary, body) != SMTP_STATUS_OK){
return smtp->status_code;
}
for(i = 0; i < smtp->num_attachment; i++){
attachment = &smtp->attachment_list[i];
if(smtp_print_mime_attachment(smtp,
boundary,
attachment) != SMTP_STATUS_OK){
return smtp->status_code;
}
}
return smtp_print_mime_end(smtp, boundary);
}
/**
* Convert a header into an RFC 5322 formatted string and send it to the
* SMTP server.
*
* This will adding proper line wrapping and indentation for long
* header lines.
*
* @param[in] smtp SMTP client context.
* @param[in] header See @ref smtp_header.
* @return @ref smtp_status_code.
*/
static int
smtp_print_header(struct smtp *const smtp,
const struct smtp_header *const header){
size_t key_len;
size_t value_len;
size_t concat_len;
char *header_concat;
char *concat;
char *header_fmt;
if(header->value == NULL){
return smtp->status_code;
}
key_len = strlen(header->key);
value_len = strlen(header->value);
/* concat_len = key_len + 2 + value_len + 1 */
if(smtp_si_add_size_t(key_len, value_len, &concat_len) ||
smtp_si_add_size_t(concat_len, 3, &concat_len) ||
(header_concat = malloc(concat_len)) == NULL){
return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
}
concat = smtp_stpcpy(header_concat, header->key);
concat = smtp_stpcpy(concat, ": ");
smtp_stpcpy(concat, header->value);
header_fmt = smtp_fold_whitespace(header_concat, SMTP_LINE_MAX);
free(header_concat);
if(header_fmt == NULL){
return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
}
smtp_puts_terminate(smtp, header_fmt);
free(header_fmt);
return smtp->status_code;
}
/**
* Take a FROM, TO, and CC address and add it into the email header list.
*
* The following example shows what the final header might look like when
* the client sends an email to two CC addresses:
* Cc: mail1@example.com, mail2@example.com
*
* @param[in] smtp SMTP client context.
* @param[in] address_type @ref smtp_address_type.
* @param[in] key Header key value, for example, To From Cc.
* @return @ref smtp_status_code.
*/
static int
smtp_append_address_to_header(struct smtp *const smtp,
enum smtp_address_type address_type,
const char *const key){
size_t i;
size_t num_address_in_header;
size_t header_value_sz;
size_t name_slen;
size_t email_slen;
size_t concat_len;
struct smtp_address *address;
char *header_value;
char *header_value_new;
char *concat;
num_address_in_header = 0;
header_value_sz = 0;
header_value = NULL;
concat_len = 0;
for(i = 0; i < smtp->num_address; i++){
address = &smtp->address_list[i];
if(address->type == address_type){
name_slen = 0;
if(address->name){
name_slen = strlen(address->name);
}
email_slen = strlen(address->email);
/*
* ', "' NAME '" <' EMAIL > \0
* header_value_sz += 3 + name_slen + 3 + email_slen + 1 + 1
*/
if(smtp_si_add_size_t(header_value_sz, name_slen, &header_value_sz) ||
smtp_si_add_size_t(header_value_sz, email_slen, &header_value_sz) ||
smtp_si_add_size_t(header_value_sz, 3 + 3 + 1 + 1, &header_value_sz)||
(header_value_new = realloc(header_value,
header_value_sz)) == NULL){
free(header_value);
return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
}
header_value = header_value_new;
concat = header_value + concat_len;
if(num_address_in_header > 0){
concat = smtp_stpcpy(concat, ", ");
}
if(name_slen){
concat = smtp_stpcpy(concat, "\"");
concat = smtp_stpcpy(concat, address->name);
concat = smtp_stpcpy(concat, "\" ");
}
concat = smtp_stpcpy(concat, "<");
concat = smtp_stpcpy(concat, address->email);
concat = smtp_stpcpy(concat, ">");
num_address_in_header += 1;
concat_len = concat - header_value;
}
}
if(header_value){
smtp_header_add(smtp, key, header_value);
free(header_value);
}
return smtp->status_code;
}
/**
* Send envelope MAIL FROM or RCPT TO header address.
*
* Examples:
* MAIL FROM:<mail@example.com>
* RCPT TO:<mail@example.com>
*
* @param[in] smtp SMTP client context.
* @param[in] header Either "MAIL FROM" or "RCPT TO".
* @param[in] address @ref smtp_address -> email field.
* @return @ref smtp_status_code.
*/
static int
smtp_mail_envelope_header(struct smtp *const smtp,
const char *const header,
const struct smtp_address *const address){
const char *const SMTPUTF8 = " SMTPUTF8";
const size_t SMTPUTF8_LEN = strlen(SMTPUTF8);
size_t email_len;
size_t bufsz;
char *envelope_address;
char *concat;
const char *smtputf8_opt;
email_len = strlen(address->email);
/* bufsz = 14 + email_len + SMTPUTF8_LEN + 1 */
if(smtp_si_add_size_t(email_len, SMTPUTF8_LEN + 14 + 1, &bufsz) ||
(envelope_address = malloc(bufsz)) == NULL){
return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
}
smtputf8_opt = "";
if(smtp_str_has_nonascii_utf8(address->email)){
smtputf8_opt = SMTPUTF8;
}
concat = smtp_stpcpy(envelope_address, header);
concat = smtp_stpcpy(concat, ":<");
concat = smtp_stpcpy(concat, address->email);
concat = smtp_stpcpy(concat, ">");
concat = smtp_stpcpy(concat, smtputf8_opt);
smtp_stpcpy(concat, "\r\n");
smtp_puts(smtp, envelope_address);
free(envelope_address);
if(smtp->status_code != SMTP_STATUS_OK){
return smtp->status_code;
}
smtp_read_and_parse_code(smtp);
return smtp->status_code;
}
/**
* Comparison function for qsort which sorts headers alphabetically based
* on the key.
*
* @param[in] v1 The first @ref smtp_header to compare.
* @param[in] v2 The second @ref smtp_header to compare.
* @retval 0 If the keys match.
* @retval !0 If the keys do not match.
*/
static int
smtp_header_cmp(const void *v1,
const void *v2){
const struct smtp_header *header1;
const struct smtp_header *header2;
header1 = v1;
header2 = v2;
return strcmp(header1->key, header2->key);
}
/**
* Search function used by bsearch which allows the caller to check for
* headers with existing keys.
*
* @param v1 String to search for in the list.
* @param v2 The @ref smtp_header to compare.
* @retval 0 If the keys match.
* @retval !0 If the keys do not match.
*/
static int
smtp_header_cmp_key(const void *const v1,
const void *const v2){
const char *key;
const struct smtp_header *header2;
key = v1;
header2 = v2;
return strcmp(key, header2->key);
}
/**
* Determine if the header key has already been defined in this context.
*
* @param[in] smtp SMTP client context.
* @param[in] key Header key value to search for.
* @retval 1 If the header already exists in this context.
* @retval 0 If the header does not exist in this context.
*/
static int
smtp_header_exists(const struct smtp *const smtp,
const char *const key){
if(bsearch(key,
smtp->header_list,
smtp->num_headers,
sizeof(*smtp->address_list),
smtp_header_cmp_key) == NULL){
return 0;
}
return 1;
}
/**
* Validate characters in the email header key.
*
* Must consist only of printable US-ASCII characters except colon.
*
* @param[in] key Header key to validate.
* @retval 0 Successful validation.
* @retval -1 Failed to validate.
*/
SMTP_LINKAGE int
smtp_header_key_validate(const char *const key){
unsigned c;
size_t i;
size_t keylen;
keylen = strlen(key);
if(keylen < 1){
return -1;
}
for(i = 0; i < keylen; i++){
c = key[i];
if(c <= ' ' || c > 126 || c == ':'){
return -1;
}
}
return 0;
}
/**
* Validate characters in the email header contents.
*
* Must consist only of printable character, space, or horizontal tab.
*
* @param[in] value Header value to validate.
* @retval 0 Successful validation.
* @retval -1 Failed to validate.
*/
SMTP_LINKAGE int
smtp_header_value_validate(const char *const value){
size_t i;
unsigned char c;
for(i = 0; value[i]; i++){
c = value[i];
if((c < ' ' || c > 126) &&
c != '\t' &&
c < 0x80){ /* Allow UTF-8 byte sequence. */
return -1;
}
}
return 0;
}
/**
* Validate characters in the email address.
*
* The email address must consist only of printable characters excluding
* the angle brackets (<) and (>).
*
* @param[in] email The email address of the party.
* @retval 0 Successful validation.
* @retval -1 Failed to validate.
*/
SMTP_LINKAGE int
smtp_address_validate_email(const char *const email){
size_t i;
unsigned char c;
for(i = 0; email[i]; i++){
c = email[i];
if(c <= ' ' || c == 127 ||
c == '<' || c == '>'){
return -1;
}
}
return 0;
}
/**
* Validate characters in the email name.
*
* Email user name must consist only of printable characters, excluding the
* double quote character.
*
* @param[in] name Email name to validate.
* @retval 0 Successful validation.
* @retval -1 Failed to validate.
*/
SMTP_LINKAGE int
smtp_address_validate_name(const char *const name){
size_t i;
unsigned char c;
for(i = 0; name[i]; i++){
c = name[i];
if(c < ' ' || c == 127 || c == '\"'){
return -1;
}
}
return 0;
}
/**
* Validate characters in the attachment file name.
*
* Must consist only of printable characters or the space character ( ), and
* excluding the quote characters (') and (").
*
* @param[in] name Filename of the attachment shown to recipients.
* @retval 0 Successful validation.
* @retval -1 Failed to validate.
*/
SMTP_LINKAGE int
smtp_attachment_validate_name(const char *const name){
size_t i;
unsigned c;
for(i = 0; name[i]; i++){
c = name[i];
if(c < ' ' || c == 127 ||
c == '\'' || c == '\"'){
return -1;
}
}
return 0;
}
/**
* Special flag value for the SMTP context used to determine if the initial
* memory allocation failed to create the context.
*/
#define SMTP_FLAG_INVALID_MEMORY (enum smtp_flag)(0xFFFFFFFF)
/**
* This error structure used for the single error case where we cannot
* initially allocate memory. This makes it easier to propagate any
* error codes when calling the other header functions because the
* caller will always get a valid SMTP structure returned.
*/
static struct smtp smtp_error = {
SMTP_FLAG_INVALID_MEMORY, /* flags */
0, /* sock */
{ /* gdfd */
NULL, /* _buf */
0, /* _bufsz */
0, /* _buf_len */
0, /* delim */
NULL, /* line */
0, /* line_len */
NULL, /* getdelimfd_read */
NULL /* user_data */
}, /* gdfd */
NULL, /* header_list */
0, /* num_headers */
NULL, /* address_list */
0, /* num_address */
NULL, /* attachment_list */
0, /* num_attachment */
SMTP_STATUS_NOMEM, /* smtp_status_code status_code */
0, /* timeout_sec */
0, /* tls_on */
NULL /* cafile */
#ifdef SMTP_OPENSSL
,
NULL, /* tls */
NULL, /* tls_ctx */
NULL /* tls_bio */
#endif /* SMTP_OPENSSL */
};
/**
* Open a connection to an SMTP server and return the context.
*
* After successfully connecting and performing a handshake with the
* SMTP server, this function will return an SMTP client context which
* the calling program can use in the other API function calls. The
* caller must always use this function prior to any other smtp-client
* library function.
*
* This function always returns a valid SMTP client context even if
* the server connection or memory allocation fails. However, the error
* status will continue to propagate to any further function calls for
* the SMTP context while in this failure mode.
*
* This function will ignore the SIGPIPE signal. Applications that require a
* handler for that signal should set it up after calling this function.
*
* @param[in] server Server name or IP address.
* @param[in] port Server port number.
* @param[in] connection_security See @ref smtp_connection_security.
* @param[in] flags See @ref smtp_flag.
* @param[in] cafile Path to certificate file, or NULL to use
* certificates in the default path.
* @param[out] smtp Pointer to a new SMTP context which will
* always have a valid state even if memory
* allocation fails. When finished, the caller
* must free this context using
* @ref smtp_close.
* @return @ref smtp_status_code.
*/
enum smtp_status_code
smtp_open(const char *const server,
const char *const port,
enum smtp_connection_security connection_security,
enum smtp_flag flags,
const char *const cafile,
struct smtp **smtp){
struct smtp *snew;
if((snew = calloc(1, sizeof(**smtp))) == NULL){
*smtp = &smtp_error;
return smtp_status_code_get(*smtp);
}
*smtp = snew;
snew->flags = flags;
snew->sock = -1;
snew->gdfd.delim = '\n';
snew->gdfd.getdelimfd_read = smtp_str_getdelimfd_read;
snew->gdfd.user_data = snew;
snew->cafile = cafile;
#ifndef SMTP_IS_WINDOWS
signal(SIGPIPE, SIG_IGN);
#endif /* !(SMTP_IS_WINDOWS) */
if(smtp_connect(snew, server, port) < 0){
return smtp_status_code_set(*smtp, SMTP_STATUS_CONNECT);
}
if(smtp_initiate_handshake(snew,
server,
connection_security) != SMTP_STATUS_OK){
return smtp_status_code_set(*smtp, SMTP_STATUS_HANDSHAKE);
}
return snew->status_code;
}
/**
* Authenticate the user using one of the methods listed in
* @ref smtp_authentication_method.
*
* @param[in] smtp SMTP client context.
* @param[in] auth_method See @ref smtp_authentication_method.
* @param[in] user Server authentication user name.
* @param[in] pass Server authentication user password.
* @return @ref smtp_status_code.
*/
enum smtp_status_code
smtp_auth(struct smtp *const smtp,
enum smtp_authentication_method auth_method,
const char *const user,
const char *const pass){
int auth_rc;
if(smtp->status_code != SMTP_STATUS_OK){
return smtp->status_code;
}
switch(auth_method){
case SMTP_AUTH_PLAIN:
auth_rc = smtp_auth_plain(smtp, user, pass);
break;
case SMTP_AUTH_LOGIN:
auth_rc = smtp_auth_login(smtp, user, pass);
break;
#ifdef SMTP_OPENSSL
case SMTP_AUTH_CRAM_MD5:
auth_rc = smtp_auth_cram_md5(smtp, user, pass);
break;
#endif /* SMTP_OPENSSL */
case SMTP_AUTH_NONE:
auth_rc = 0;
break;
default:
return smtp_status_code_set(smtp, SMTP_STATUS_PARAM);
}
if(auth_rc < 0){
return smtp_status_code_set(smtp, SMTP_STATUS_AUTH);
}
return smtp->status_code;
}
/**
* Sends an email using the addresses, attachments, and headers defined
* in the current SMTP context.
*
* The caller must use the smtp_open function prior to this function. The
* 'Date' header also gets generated here if it hasn't already been provided.
*
* @param[in] smtp SMTP client context.
* @param[in] body Null-terminated string to send in the email body.
* @return @ref smtp_status_code.
*/
enum smtp_status_code
smtp_mail(struct smtp *const smtp,
const char *const body){
size_t i;
int has_mail_from;
struct smtp_address *address;
char date[SMTP_DATE_MAX_SZ];
if(smtp->status_code != SMTP_STATUS_OK){
return smtp->status_code;
}
/* MAIL timeout 5 minutes. */
smtp_set_read_timeout(smtp, 60 * 5);
has_mail_from = 0;
for(i = 0; i < smtp->num_address; i++){
address = &smtp->address_list[i];
if(address->type == SMTP_ADDRESS_FROM){
if(smtp_mail_envelope_header(smtp,
"MAIL FROM",
address) != SMTP_STATUS_OK){
return smtp->status_code;
}
has_mail_from = 1;
break;
}
}
if(!has_mail_from){
return smtp_status_code_set(smtp, SMTP_STATUS_PARAM);
}
/* RCPT timeout 5 minutes. */
smtp_set_read_timeout(smtp, 60 * 5);
for(i = 0; i < smtp->num_address; i++){
address = &smtp->address_list[i];
if(address->type != SMTP_ADDRESS_FROM){
if(smtp_mail_envelope_header(smtp,
"RCPT TO",
address) != SMTP_STATUS_OK){
return smtp->status_code;
}
}
}
/* DATA timeout 2 minutes. */
smtp_set_read_timeout(smtp, 60 * 2);
if(smtp_puts(smtp, "DATA\r\n") != SMTP_STATUS_OK){
return smtp->status_code;
}
/* 354 response to DATA must get returned before we can send the message. */
if(smtp_read_and_parse_code(smtp) != SMTP_BEGIN_MAIL){
return smtp_status_code_set(smtp, SMTP_STATUS_SERVER_RESPONSE);
}
if(!smtp_header_exists(smtp, "Date")){
if(smtp_date_rfc_2822(date) < 0){
return smtp_status_code_set(smtp, SMTP_STATUS_DATE);
}
if(smtp_header_add(smtp, "Date", date) != SMTP_STATUS_OK){
return smtp->status_code;
}
}
/* DATA block timeout 3 minutes. */
smtp_set_read_timeout(smtp, 60 * 3);
if(smtp_append_address_to_header(smtp,
SMTP_ADDRESS_FROM,
"From") != SMTP_STATUS_OK ||
smtp_append_address_to_header(smtp,
SMTP_ADDRESS_TO,
"To") != SMTP_STATUS_OK ||
smtp_append_address_to_header(smtp,
SMTP_ADDRESS_CC,
"Cc") != SMTP_STATUS_OK){
return smtp->status_code;
}
for(i = 0; i < smtp->num_headers; i++){
if(smtp_print_header(smtp, &smtp->header_list[i]) != SMTP_STATUS_OK){
return smtp->status_code;
}
}
if(smtp_print_mime_email(smtp, body) != SMTP_STATUS_OK){
return smtp->status_code;
}
/* End of DATA segment. */
if(smtp_puts(smtp, ".\r\n") != SMTP_STATUS_OK){
return smtp->status_code;
}
/* DATA termination timeout 250 return code - 10 minutes. */
smtp_set_read_timeout(smtp, 60 * 10);
if(smtp_read_and_parse_code(smtp) != SMTP_DONE){
return smtp_status_code_set(smtp, SMTP_STATUS_SERVER_RESPONSE);
}
return smtp->status_code;
}
/**
* Close the SMTP connection and frees all resources held by the
* SMTP context.
*
* @param[in] smtp SMTP client context.
* @return @ref smtp_status_code.
*/
enum smtp_status_code
smtp_close(struct smtp *smtp){
enum smtp_status_code status_code;
status_code = smtp->status_code;
if(smtp->flags == SMTP_FLAG_INVALID_MEMORY){
return status_code;
}
if(smtp->sock != -1){
/*
* Do not error out if this fails because we still need to free the
* SMTP client resources.
*/
smtp->status_code = SMTP_STATUS_OK;
smtp_puts(smtp, "QUIT\r\n");
#ifdef SMTP_OPENSSL
if(smtp->tls_on){
SSL_free(smtp->tls);
SSL_CTX_free(smtp->tls_ctx);
}
#endif /* SMTP_OPENSSL */
#ifdef SMTP_IS_WINDOWS
closesocket(smtp->sock);
WSACleanup();
#else /* POSIX */
if(close(smtp->sock) < 0){
if(smtp->status_code == SMTP_STATUS_OK){
smtp_status_code_set(smtp, SMTP_STATUS_CLOSE);
}
}
#endif /* SMTP_IS_WINDOWS */
}
smtp_str_getdelimfd_free(&smtp->gdfd);
smtp_header_clear_all(smtp);
smtp_address_clear_all(smtp);
smtp_attachment_clear_all(smtp);
if(status_code == SMTP_STATUS_OK){
status_code = smtp->status_code;
}
free(smtp);
return status_code;
}
/**
* Get the current status/error code described in @ref smtp_status_code.
*
* @param[in] smtp SMTP client context.
* @return @ref smtp_status_code.
*/
enum smtp_status_code
smtp_status_code_get(const struct smtp *const smtp){
return smtp->status_code;
}
/**
* Set the error status of the SMTP client context and return the same code.
*
* This function allows the caller to clear an error status to SMTP_STATUS_OK
* so that previous errors will stop propagating. However, this will only
* work correctly for clearing the SMTP_STATUS_PARAM and SMTP_STATUS_FILE
* errors. Clearing the status from any other error code will invoke
* undefined behavior and will almost never work correctly.
*
* @param[in] smtp SMTP client context.
* @param[in] status_code See @ref smtp_status_code.
* @return @ref smtp_status_code.
*/
enum smtp_status_code
smtp_status_code_set(struct smtp *const smtp,
enum smtp_status_code status_code){
if((unsigned)status_code >= SMTP_STATUS__LAST){
return smtp_status_code_set(smtp, SMTP_STATUS_PARAM);
}
smtp->status_code = status_code;
return status_code;
}
/**
* Convert a standard smtp-client return code to a description.
*
* @param[in] status_code Status code returned from one of the other
* smtp-client library functions.
* @return String containing a description of the @p status_code. The caller
* must not free or modify this string.
*/
const char *
smtp_status_code_errstr(enum smtp_status_code status_code){
const char *const status_code_err_str[] = {
/* SMTP_STATUS_OK */
"Success",
/* SMTP_STATUS_NOMEM */
"Memory allocation failed",
/* SMTP_STATUS_CONNECT */
"Failed to connect to the mail server",
/* SMTP_STATUS_HANDSHAKE */
"Failed to handshake or negotiate a TLS connection with the server",
/* SMTP_STATUS_AUTH */
"Failed to authenticate with the given credentials",
/* SMTP_STATUS_SEND */
"Failed to send bytes to the server",
/* SMTP_STATUS_RECV */
"Failed to receive bytes from the server",
/* SMTP_STATUS_CLOSE */
"Failed to properly close a connection",
/* SMTP_STATUS_SERVER_RESPONSE */
"SMTP server sent back an unexpected status code",
/* SMTP_STATUS_PARAM */
"Invalid parameter",
/* SMTP_STATUS_FILE */
"Failed to read or open a local file",
/* SMTP_STATUS_DATE */
"Failed to get the local date and time",
/* SMTP_STATUS__LAST */
"Unknown error"
};
if((unsigned)status_code > SMTP_STATUS__LAST){
status_code = SMTP_STATUS__LAST;
}
return status_code_err_str[status_code];
}
/**
* Add a key/value header to the header list in the SMTP context.
*
* This will insert instead of replacing an existing header with the same key.
*
* @param[in] smtp SMTP client context.
* @param[in] key Key name for new header. It must consist only of
* printable US-ASCII characters except colon.
* @param[in] value Value for new header. It must consist only of printable
* US-ASCII, space, or horizontal tab. If set to NULL,
* this will prevent the header from printing out.
* @return @ref smtp_status_code.
*/
enum smtp_status_code
smtp_header_add(struct smtp *const smtp,
const char *const key,
const char *const value){
struct smtp_header *new_header_list;
struct smtp_header *new_header;
size_t num_headers_inc;
if(smtp->status_code != SMTP_STATUS_OK){
return smtp->status_code;
}
if(smtp_header_key_validate(key) < 0){
return smtp_status_code_set(smtp, SMTP_STATUS_PARAM);
}
if(value && smtp_header_value_validate(value) < 0){
return smtp_status_code_set(smtp, SMTP_STATUS_PARAM);
}
if(smtp_si_add_size_t(smtp->num_headers, 1, &num_headers_inc) ||
(new_header_list = smtp_reallocarray(
smtp->header_list,
num_headers_inc,
sizeof(*smtp->header_list))) == NULL){
return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
}
smtp->header_list = new_header_list;
new_header = &smtp->header_list[smtp->num_headers];
new_header->key = smtp_strdup(key);
new_header->value = value ? smtp_strdup(value) : NULL;
if(new_header->key == NULL ||
(new_header->value == NULL && value)){
free(new_header->key);
free(new_header->value);
return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
}
smtp->num_headers = num_headers_inc;
qsort(smtp->header_list,
smtp->num_headers,
sizeof(*smtp->header_list),
smtp_header_cmp);
return smtp->status_code;
}
/**
* Free all memory related to email headers.
*
* @param[in] smtp SMTP client context.
*/
void smtp_header_clear_all(struct smtp *const smtp){
size_t i;
struct smtp_header *header;
for(i = 0; i < smtp->num_headers; i++){
header = &smtp->header_list[i];
free(header->key);
free(header->value);
}
free(smtp->header_list);
smtp->header_list = NULL;
smtp->num_headers = 0;
}
/**
* Add a FROM, TO, CC, or BCC address destination to this SMTP context.
*
* @note Some SMTP servers may reject over 100 recipients.
*
* @param[in] smtp SMTP client context.
* @param[in] type See @ref smtp_address_type.
* @param[in] email The email address of the party. Must consist only of
* printable characters excluding the angle brackets
* (<) and (>).
* @param[in] name Name or description of the party. Must consist only of
* printable characters, excluding the quote characters. If
* set to NULL or empty string, no name will get associated
* with this email.
* @return @ref smtp_status_code.
*/
enum smtp_status_code
smtp_address_add(struct smtp *const smtp,
enum smtp_address_type type,
const char *const email,
const char *const name){
struct smtp_address *new_address_list;
struct smtp_address *new_address;
size_t num_address_inc;
if(smtp->status_code != SMTP_STATUS_OK){
return smtp->status_code;
}
if(smtp_address_validate_email(email) < 0){
return smtp_status_code_set(smtp, SMTP_STATUS_PARAM);
}
if(name && smtp_address_validate_name(name) < 0){
return smtp_status_code_set(smtp, SMTP_STATUS_PARAM);
}
if(smtp_si_add_size_t(smtp->num_address, 1, &num_address_inc)){
return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
}
new_address_list = smtp_reallocarray(smtp->address_list,
num_address_inc,
sizeof(*new_address_list));
if(new_address_list == NULL){
return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
}
new_address = &new_address_list[smtp->num_address];
smtp->address_list = new_address_list;
new_address->type = type;
new_address->email = smtp_strdup(email);
new_address->name = name ? smtp_strdup(name) : NULL;
if(new_address->email == NULL ||
(new_address->name == NULL && name)){
free(new_address->email);
free(new_address->name);
return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
}
smtp->num_address = num_address_inc;
return smtp->status_code;
}
/**
* Free all memory related to the address list.
*
* @param[in] smtp SMTP client context.
*/
void smtp_address_clear_all(struct smtp *const smtp){
size_t i;
struct smtp_address *address;
for(i = 0; i < smtp->num_address; i++){
address = &smtp->address_list[i];
free(address->email);
free(address->name);
}
free(smtp->address_list);
smtp->address_list = NULL;
smtp->num_address = 0;
}
/**
* Add a file attachment from a path.
*
* See @ref smtp_attachment_add_mem for more details.
*
* @param[in] smtp SMTP client context.
* @param[in] name Filename of the attachment shown to recipients.
* @param[in] path Path of file location to read from.
* @return @ref smtp_status_code.
*/
enum smtp_status_code
smtp_attachment_add_path(struct smtp *const smtp,
const char *const name,
const char *const path){
char *data;
size_t bytes_read;
if(smtp->status_code != SMTP_STATUS_OK){
return smtp->status_code;
}
errno = 0;
if((data = smtp_file_get_contents(path, &bytes_read)) == NULL){
if(errno == ENOMEM){
return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
}
return smtp_status_code_set(smtp, SMTP_STATUS_FILE);
}
smtp_attachment_add_mem(smtp, name, data, bytes_read);
free(data);
return smtp->status_code;
}
/**
* Add an attachment using a file pointer.
*
* See @ref smtp_attachment_add_mem for more details.
*
* @param[in] smtp SMTP client context.
* @param[in] name Filename of the attachment shown to recipients.
* @param[in] fp File pointer already opened by the caller.
* @return @ref smtp_status_code.
*/
enum smtp_status_code
smtp_attachment_add_fp(struct smtp *const smtp,
const char *const name,
FILE *fp){
char *data;
size_t bytes_read;
if(smtp->status_code != SMTP_STATUS_OK){
return smtp->status_code;
}
errno = 0;
if((data = smtp_ffile_get_contents(fp, &bytes_read)) == NULL){
if(errno == ENOMEM){
return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
}
return smtp_status_code_set(smtp, SMTP_STATUS_FILE);
}
smtp_attachment_add_mem(smtp, name, data, bytes_read);
free(data);
return smtp->status_code;
}
/**
* Add a MIME attachment to this SMTP context with the data retrieved
* from memory.
*
* The attachment data will get base64 encoded before sending to the server.
*
* @param[in] smtp SMTP client context.
* @param[in] name Filename of the attachment shown to recipients. Must
* consist only of printable characters excluding the
* quote characters (') and ("), or the space character
* ( ).
* @param[in] data Raw attachment data stored in memory.
* @param[in] datasz Number of bytes in @p data, or -1 if data
* null-terminated.
* @return @ref smtp_status_code.
*/
enum smtp_status_code
smtp_attachment_add_mem(struct smtp *const smtp,
const char *const name,
const void *const data,
long datasz){
size_t num_attachment_inc;
struct smtp_attachment *new_attachment_list;
struct smtp_attachment *new_attachment;
char *b64_encode;
if(smtp->status_code != SMTP_STATUS_OK){
return smtp->status_code;
}
if(smtp_attachment_validate_name(name) < 0){
return smtp_status_code_set(smtp, SMTP_STATUS_PARAM);
}
if(datasz < 0){
datasz = strlen(data);
}
if(smtp_si_add_size_t(smtp->num_attachment, 1, &num_attachment_inc) ||
(new_attachment_list = smtp_reallocarray(
smtp->attachment_list,
num_attachment_inc,
sizeof(*new_attachment_list))) == NULL){
return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
}
smtp->attachment_list = new_attachment_list;
new_attachment = &new_attachment_list[smtp->num_attachment];
new_attachment->name = smtp_strdup(name);
b64_encode = smtp_base64_encode(data, datasz);
if(new_attachment->name == NULL || b64_encode == NULL){
free(new_attachment->name);
free(b64_encode);
return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
}
new_attachment->b64_data = smtp_chunk_split(b64_encode,
SMTP_LINE_MAX,
"\r\n");
free(b64_encode);
if(new_attachment->b64_data == NULL){
free(new_attachment->name);
return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
}
smtp->num_attachment = num_attachment_inc;
return smtp->status_code;
}
/**
* Remove all attachments from the SMTP client context.
*
* @param[in] smtp SMTP client context.
*/
void smtp_attachment_clear_all(struct smtp *const smtp){
size_t i;
struct smtp_attachment *attachment;
for(i = 0; i < smtp->num_attachment; i++){
attachment = &smtp->attachment_list[i];
free(attachment->name);
free(attachment->b64_data);
}
free(smtp->attachment_list);
smtp->attachment_list = NULL;
smtp->num_attachment = 0;
}