1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771
|
diff --git a/.gitignore b/.gitignore
index f64b4cf..2c6ee56 100644
--- a/.gitignore
+++ b/.gitignore
@@ -65,6 +65,7 @@ man/*.7
examples/.deps/
examples/*.o
examples/coap-client
+examples/perf-client
examples/coap-etsi_iot_01
examples/coap-rd
examples/coap-server
diff --git a/Makefile.am b/Makefile.am
index 5b4d2fb..6713f39 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -156,11 +156,11 @@ coap_dtls_receive \
coap_dtls_send \
coap_dtls_session_update_mtu \
coap_dtls_startup \
-coap_endpoint_new_dtls_session \
coap_mfree_endpoint \
coap_packet_extract_pbuf \
coap_pdu_from_pbuf \
coap_session_mfree \
+coap_session_new_dtls_session \
coap_socket_accept_tcp \
coap_socket_bind_tcp \
coap_socket_bind_udp \
diff --git a/configure.ac b/configure.ac
index be5fe2a..cee1744 100644
--- a/configure.ac
+++ b/configure.ac
@@ -2,6 +2,7 @@
#
# Copyright (C) 2010-2015 Olaf Bergmann <bergmann@tzi.org>
# (C) 2015-2018 Carsten Schoenert <c.schoenert@t-online.de>
+# Copyright (c) 2018 by cisco Systems, Inc.
#
# Please run 'autogen.sh' to let autoconf produce a configure script.
@@ -525,6 +526,19 @@ if test "x$build_gcov" = "xyes"; then
fi
fi
+# configure options
+# __cisco__
+AC_ARG_WITH([cisco],
+ [AS_HELP_STRING([--with-cisco],
+ [Include Cisco specific changes])],
+ [with_cisco="$withval"],
+ [with_cisco="no"])
+
+if test "x$with_cisco" = "xyes"; then
+ AC_DEFINE(HAVE_CISCO, [1], [Define if the system should be built with Cisco changes enabled])
+fi
+
+
# end configure options
#######################
@@ -729,8 +743,14 @@ if test "x$build_examples" = "xyes"; then
else
AC_MSG_RESULT([ build examples : "no"])
fi
+if test "x$with_cisco" = "xyes"; then
+ AC_MSG_RESULT([ build cisco : "yes"])
+else
+ AC_MSG_RESULT([ build cisco : "no"])
+fi
if test "x$build_gcov" = "xyes"; then
AC_MSG_RESULT([ build with gcov support : "yes"])
else
AC_MSG_RESULT([ build with gcov support : "no"])
fi
+
diff --git a/examples/Makefile.am b/examples/Makefile.am
index c34750b..4adee58 100644
--- a/examples/Makefile.am
+++ b/examples/Makefile.am
@@ -1,6 +1,7 @@
# examples/Makefile.am
#
# Copyright (C) 2015 Carsten Schoenert <c.schoenert@t-online.de>
+# Copyright (c) 2018 by cisco Systems, Inc.
#
# This file is part of the CoAP C library libcoap. Please see README and
# COPYING for terms of use.
@@ -13,13 +14,15 @@ AM_CFLAGS = -I$(top_builddir)/include -I$(top_srcdir)/include \
-I$(top_srcdir)/include/coap$(LIBCOAP_API_VERSION) \
$(WARNING_CFLAGS) $(DTLS_CFLAGS) -std=c99
-#
-bin_PROGRAMS = coap-client coap-server coap-rd
+bin_PROGRAMS = coap-client perf-client coap-server coap-rd
check_PROGRAMS = coap-etsi_iot_01 coap-tiny
coap_client_SOURCES = client.c
coap_client_LDADD = $(DTLS_LIBS) $(top_builddir)/.libs/libcoap-$(LIBCOAP_NAME_SUFFIX).la
+perf_client_SOURCES = perf-client.c
+perf_client_LDADD = $(DTLS_LIBS) $(top_builddir)/.libs/libcoap-$(LIBCOAP_NAME_SUFFIX).la -lm
+
coap_server_SOURCES = coap-server.c
coap_server_LDADD = $(DTLS_LIBS) $(top_builddir)/.libs/libcoap-$(LIBCOAP_NAME_SUFFIX).la
diff --git a/examples/client.c b/examples/client.c
index bac3d06..560695e 100644
--- a/examples/client.c
+++ b/examples/client.c
@@ -30,6 +30,7 @@
#include <netdb.h>
#endif
+#define HAVE_CISCO 1
#include <coap2/coap.h>
#define MAX_USER 128 /* Maximum length of a user name (i.e., PSK
diff --git a/examples/coap-rd.c b/examples/coap-rd.c
index 4ee1295..81fcd3f 100644
--- a/examples/coap-rd.c
+++ b/examples/coap-rd.c
@@ -38,6 +38,7 @@
#include <dirent.h>
#endif
+#define HAVE_CISCO 1
#include <coap2/coap.h>
#define COAP_RESOURCE_CHECK_TIME 2
diff --git a/examples/coap-server.c b/examples/coap-server.c
index 9187426..ee9cd8f 100644
--- a/examples/coap-server.c
+++ b/examples/coap-server.c
@@ -36,6 +36,7 @@
/* Need to refresh time once per sec */
#define COAP_RESOURCE_CHECK_TIME 1
+#define HAVE_CISCO 1
#include <coap2/coap.h>
#ifndef min
diff --git a/examples/perf-client.c b/examples/perf-client.c
new file mode 100644
index 0000000..d817bb4
--- /dev/null
+++ b/examples/perf-client.c
@@ -0,0 +1,2281 @@
+/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+
+/* perf-coap -- performance CoAP client
+ *
+ * Copyright (C) 2010--2016 Olaf Bergmann <bergmann@tzi.org>
+ * Copyright (c) 2018-2019 by Cisco Systems, Inc.
+ *
+ * This file is part of the CoAP library libcoap. Please see README for terms of
+ * use.
+ */
+
+#include <string.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <ctype.h>
+#include <signal.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <math.h>
+#ifdef _WIN32
+#define strcasecmp _stricmp
+#include "getopt.c"
+#if !defined(S_ISDIR)
+#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
+#endif
+#else
+#include <unistd.h>
+#include <sys/select.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <netdb.h>
+#include <sys/time.h>
+#endif
+
+#define HAVE_CISCO 1
+#include <coap2/coap.h>
+
+#define MAX_USER 128 /* Maximum length of a user name (i.e., PSK
+ * identity) in bytes. */
+#define MAX_KEY 64 /* Maximum length of a key (i.e., PSK) in bytes. */
+#define MAX_CMD 255 /* Maximum command length */
+
+int flags = 0;
+
+/* Used for time measurements in performance testing */
+struct timeval stop, start;
+
+/* Used to create directory for the output certs from performance tests */
+struct stat st = {0};
+
+static unsigned char _token_data[8];
+coap_binary_t the_token = { 0, _token_data };
+
+#define FLAGS_BLOCK 0x01
+
+static coap_optlist_t *optlist = NULL;
+static coap_optlist_t *optlist2 = NULL;
+
+/* Request URI.
+ * TODO: associate the resources with transaction id and make it expireable */
+static coap_uri_t uri;
+
+static coap_string_t proxy = { 0, NULL };
+static uint16_t proxy_port = COAP_DEFAULT_PORT;
+static unsigned int ping_seconds = 0;
+
+/* reading is done when this flag is set */
+static int ready = 0;
+
+static coap_string_t output_file = { 0, NULL }; /* output file name */
+static coap_string_t output_dir = { 0, NULL }; /* output directory name for performance tests */
+static coap_string_t log_file = { 0, NULL }; /* log file for performance tests */
+
+static FILE *file = NULL; /* output file stream */
+static FILE *perf_log = NULL; /* logging file stream */
+
+static coap_string_t payload = { 0, NULL }; /* optional payload to send */
+static coap_string_t payload2 = { 0, NULL }; /* optional second payload to send */
+
+static int reliable = 0;
+
+unsigned char msgtype = COAP_MESSAGE_CON; /* usually, requests are sent confirmable */
+
+static char *cert_file = NULL; /* Combined certificate and private key in PEM */
+static char *ca_file = NULL; /* CA for cert_file - for cert checking in PEM */
+static char *root_ca_file = NULL; /* List of trusted Root CAs in PEM */
+
+typedef unsigned char method_t;
+method_t method = 1; /* the method we are using in our requests */
+
+coap_block_t block = { .num = 0, .m = 0, .szx = 6 };
+uint16_t last_block1_tid = 0;
+
+unsigned int wait_seconds = 90; /* default timeout in seconds */
+unsigned int wait_ms = 0;
+int wait_ms_reset = 0;
+int obs_started = 0;
+unsigned int obs_seconds = 30; /* default observe time */
+unsigned int obs_ms = 0; /* timeout for current subscription */
+int obs_ms_reset = 0;
+
+#ifndef min
+#define min(a,b) ((a) < (b) ? (a) : (b))
+#endif
+
+#ifdef __GNUC__
+#define UNUSED_PARAM __attribute__ ((unused))
+#else /* not a GCC */
+#define UNUSED_PARAM
+#endif /* GCC */
+
+static int quit = 0;
+
+/* SIGINT handler: set quit to 1 for graceful termination */
+static void
+handle_sigint(int signum UNUSED_PARAM) {
+ quit = 1;
+}
+
+static int
+append_to_output(const uint8_t *data, size_t len) {
+ size_t written;
+ if (!file) {
+ if (!output_file.s || (output_file.length && output_file.s[0] == '-'))
+ file = stdout;
+ else {
+ if (!(file = fopen((char *)output_file.s, "a"))) {
+ perror("fopen");
+ return -1;
+ }
+ }
+ }
+
+ do {
+ written = fwrite(data, 1, len, file);
+ len -= written;
+ data += written;
+ } while ( written && len );
+ fflush(file);
+ file = 0;
+
+ return 0;
+}
+
+static void
+close_output(void) {
+ if (file) {
+
+ /* add a newline before closing in case were writing to stdout */
+ if (!output_file.s || (output_file.length && output_file.s[0] == '-'))
+ fwrite("\n", 1, 1, file);
+
+ fflush(file);
+ fclose(file);
+ }
+}
+
+/*
+ * Use this to close the log after done writing all the messages
+ */
+static void
+close_log(void) {
+ if (perf_log) {
+
+ /* add a newline before closing in case were writing to stdout */
+ if (!log_file.s || (log_file.length && log_file.s[0] == '-'))
+ fwrite("\n", 1, 1, perf_log);
+
+ fflush(perf_log);
+ fclose(perf_log);
+ }
+}
+
+static coap_pdu_t *
+coap_new_request(coap_context_t *ctx,
+ coap_session_t *session,
+ method_t m,
+ coap_optlist_t **options,
+ unsigned char *data,
+ size_t length) {
+ coap_pdu_t *pdu;
+ (void)ctx;
+
+ if (!(pdu = coap_new_pdu(session)))
+ return NULL;
+
+ pdu->type = msgtype;
+ pdu->tid = coap_new_message_id(session);
+ pdu->code = m;
+
+ if ( !coap_add_token(pdu, the_token.length, the_token.s)) {
+ coap_log(LOG_DEBUG, "cannot add token to request\n");
+ }
+
+ if (options)
+ coap_add_optlist_pdu(pdu, options);
+
+ if (length) {
+ if ((flags & FLAGS_BLOCK) == 0)
+ coap_add_data(pdu, length, data);
+ else
+ coap_add_block(pdu, length, data, block.num, block.szx);
+ }
+
+ return pdu;
+}
+
+static coap_tid_t
+clear_obs(coap_context_t *ctx, coap_session_t *session) {
+ coap_pdu_t *pdu;
+ coap_optlist_t *option;
+ coap_tid_t tid = COAP_INVALID_TID;
+ unsigned char buf[2];
+ (void)ctx;
+
+ /* create bare PDU w/o any option */
+ pdu = coap_pdu_init(msgtype,
+ COAP_REQUEST_GET,
+ coap_new_message_id(session),
+ coap_session_max_pdu_size(session));
+
+ if (!pdu) {
+ return tid;
+ }
+
+ if (!coap_add_token(pdu, the_token.length, the_token.s)) {
+ coap_log(LOG_CRIT, "cannot add token\n");
+ goto error;
+ }
+
+ for (option = optlist; option; option = option->next ) {
+ if (option->number == COAP_OPTION_URI_HOST) {
+ if (!coap_add_option(pdu, option->number, option->length,
+ option->data)) {
+ goto error;
+ }
+ break;
+ }
+ }
+
+ if (!coap_add_option(pdu,
+ COAP_OPTION_OBSERVE,
+ coap_encode_var_safe(buf, sizeof(buf), COAP_OBSERVE_CANCEL),
+ buf)) {
+ coap_log(LOG_CRIT, "cannot add option Observe: %u\n", COAP_OBSERVE_CANCEL);
+ goto error;
+ }
+
+ for (option = optlist; option; option = option->next ) {
+ switch (option->number) {
+ case COAP_OPTION_URI_PORT :
+ case COAP_OPTION_URI_PATH :
+ case COAP_OPTION_URI_QUERY :
+ if (!coap_add_option(pdu, option->number, option->length,
+ option->data)) {
+ goto error;
+ }
+ break;
+ default:
+ ;
+ }
+ }
+
+ if (flags & FLAGS_BLOCK) {
+ block.num = 0;
+ block.m = 0;
+ coap_add_option(pdu,
+ COAP_OPTION_BLOCK2,
+ coap_encode_var_safe(buf, sizeof(buf), (block.num << 4 | block.m << 3 | block.szx)),
+ buf);
+ }
+
+ if (coap_get_log_level() < LOG_DEBUG)
+ coap_show_pdu(LOG_INFO, pdu);
+
+
+ tid = coap_send(session, pdu);
+
+ if (tid == COAP_INVALID_TID)
+ coap_log(LOG_DEBUG, "clear_obs: error sending new request\n");
+
+ return tid;
+ error:
+
+ coap_delete_pdu(pdu);
+ return tid;
+}
+
+static int
+resolve_address(const coap_str_const_t *server, struct sockaddr *dst) {
+
+ struct addrinfo *res, *ainfo;
+ struct addrinfo hints;
+ static char addrstr[256];
+ int error, len=-1;
+
+ memset(addrstr, 0, sizeof(addrstr));
+ if (server->length)
+ memcpy(addrstr, server->s, server->length);
+ else
+ memcpy(addrstr, "localhost", 9);
+
+ memset ((char *)&hints, 0, sizeof(hints));
+ hints.ai_socktype = SOCK_DGRAM;
+ hints.ai_family = AF_UNSPEC;
+
+ error = getaddrinfo(addrstr, NULL, &hints, &res);
+
+ if (error != 0) {
+ fprintf(stderr, "getaddrinfo: %s\n%s from %s\n", gai_strerror(error), addrstr, server->s);
+ return error;
+ }
+
+ for (ainfo = res; ainfo != NULL; ainfo = ainfo->ai_next) {
+ switch (ainfo->ai_family) {
+ case AF_INET6:
+ case AF_INET:
+ len = ainfo->ai_addrlen;
+ memcpy(dst, ainfo->ai_addr, len);
+ goto finish;
+ default:
+ ;
+ }
+ }
+
+ finish:
+ freeaddrinfo(res);
+ return len;
+}
+
+#define HANDLE_BLOCK1(Pdu) \
+ ((method == COAP_REQUEST_PUT || method == COAP_REQUEST_POST) && \
+ ((flags & FLAGS_BLOCK) == 0) && \
+ ((Pdu)->hdr->code == COAP_RESPONSE_CODE(201) || \
+ (Pdu)->hdr->code == COAP_RESPONSE_CODE(204)))
+
+static inline int
+check_token(coap_pdu_t *received) {
+ return received->token_length == the_token.length &&
+ memcmp(received->token, the_token.s, the_token.length) == 0;
+}
+
+static void
+message_handler(struct coap_context_t *ctx,
+ coap_session_t *session,
+ coap_pdu_t *sent,
+ coap_pdu_t *received,
+ const coap_tid_t id UNUSED_PARAM) {
+
+ coap_pdu_t *pdu = NULL;
+ coap_opt_t *block_opt;
+ coap_opt_iterator_t opt_iter;
+ unsigned char buf[4];
+ coap_optlist_t *option;
+ size_t len;
+ unsigned char *databuf;
+ coap_tid_t tid;
+
+#ifndef NDEBUG
+ coap_log(LOG_DEBUG, "** process incoming %d.%02d response:\n",
+ (received->code >> 5), received->code & 0x1F);
+ if (coap_get_log_level() < LOG_DEBUG)
+ coap_show_pdu(LOG_INFO, received);
+#endif
+
+ /* check if this is a response to our original request */
+ if (!check_token(received)) {
+ /* drop if this was just some message, or send RST in case of notification */
+ if (!sent && (received->type == COAP_MESSAGE_CON ||
+ received->type == COAP_MESSAGE_NON))
+ coap_send_rst(session, received);
+ return;
+ }
+
+ if (received->type == COAP_MESSAGE_RST) {
+ coap_log(LOG_INFO, "got RST\n");
+ return;
+ }
+
+ /* output the received data, if any */
+ if (COAP_RESPONSE_CLASS(received->code) == 2) {
+
+ /* set obs timer if we have successfully subscribed a resource */
+ if (!obs_started && coap_check_option(received, COAP_OPTION_OBSERVE, &opt_iter)) {
+ coap_log(LOG_DEBUG,
+ "observation relationship established, set timeout to %d\n",
+ obs_seconds);
+ obs_started = 1;
+ obs_ms = obs_seconds * 1000;
+ obs_ms_reset = 1;
+ }
+
+ /* Got some data, check if block option is set. Behavior is undefined if
+ * both, Block1 and Block2 are present. */
+ block_opt = coap_check_option(received, COAP_OPTION_BLOCK2, &opt_iter);
+ if (block_opt) { /* handle Block2 */
+ uint16_t blktype = opt_iter.type;
+
+ /* TODO: check if we are looking at the correct block number */
+ if (coap_get_data(received, &len, &databuf))
+ append_to_output(databuf, len);
+
+ if (coap_opt_block_num(block_opt) == 0) {
+ /* See if observe is set in first response */
+ ready = coap_check_option(received,
+ COAP_OPTION_OBSERVE, &opt_iter) == NULL;
+ }
+ if(COAP_OPT_BLOCK_MORE(block_opt)) {
+ /* more bit is set */
+ coap_log(LOG_DEBUG, "found the M bit, block size is %u, block nr. %u\n",
+ COAP_OPT_BLOCK_SZX(block_opt),
+ coap_opt_block_num(block_opt));
+
+ /* create pdu with request for next block */
+ pdu = coap_new_request(ctx, session, method, NULL, NULL, 0); /* first, create bare PDU w/o any option */
+ if ( pdu ) {
+ /* add URI components from optlist */
+ for (option = optlist; option; option = option->next ) {
+ switch (option->number) {
+ case COAP_OPTION_URI_HOST :
+ case COAP_OPTION_URI_PORT :
+ case COAP_OPTION_URI_PATH :
+ case COAP_OPTION_URI_QUERY :
+ coap_add_option(pdu, option->number, option->length,
+ option->data);
+ break;
+ default:
+ ; /* skip other options */
+ }
+ }
+
+ /* finally add updated block option from response, clear M bit */
+ /* blocknr = (blocknr & 0xfffffff7) + 0x10; */
+ coap_log(LOG_DEBUG, "query block %d\n",
+ (coap_opt_block_num(block_opt) + 1));
+ coap_add_option(pdu,
+ blktype,
+ coap_encode_var_safe(buf, sizeof(buf),
+ ((coap_opt_block_num(block_opt) + 1) << 4) |
+ COAP_OPT_BLOCK_SZX(block_opt)), buf);
+
+ tid = coap_send(session, pdu);
+
+ if (tid == COAP_INVALID_TID) {
+ coap_log(LOG_DEBUG, "message_handler: error sending new request\n");
+ } else {
+ wait_ms = wait_seconds * 1000;
+ wait_ms_reset = 1;
+ }
+
+ return;
+ }
+ }
+ return;
+ } else { /* no Block2 option */
+ block_opt = coap_check_option(received, COAP_OPTION_BLOCK1, &opt_iter);
+
+ if (block_opt) { /* handle Block1 */
+ unsigned int szx = COAP_OPT_BLOCK_SZX(block_opt);
+ unsigned int num = coap_opt_block_num(block_opt);
+ coap_log(LOG_DEBUG,
+ "found Block1 option, block size is %u, block nr. %u\n",
+ szx, num);
+ if (szx != block.szx) {
+ unsigned int bytes_sent = ((block.num + 1) << (block.szx + 4));
+ if (bytes_sent % (1 << (szx + 4)) == 0) {
+ /* Recompute the block number of the previous packet given the new block size */
+ num = block.num = (bytes_sent >> (szx + 4)) - 1;
+ block.szx = szx;
+ coap_log(LOG_DEBUG,
+ "new Block1 size is %u, block number %u completed\n",
+ (1 << (block.szx + 4)), block.num);
+ } else {
+ coap_log(LOG_DEBUG, "ignoring request to increase Block1 size, "
+ "next block is not aligned on requested block size boundary. "
+ "(%u x %u mod %u = %u != 0)\n",
+ block.num + 1, (1 << (block.szx + 4)), (1 << (szx + 4)),
+ bytes_sent % (1 << (szx + 4)));
+ }
+ }
+ if (last_block1_tid == received->tid) {
+ /*
+ * Duplicate BLOCK1 ACK
+ *
+ * RFCs not clear here, but on a lossy connection, there could
+ * be multiple BLOCK1 ACKs, causing the client to retransmit the
+ * same block multiple times.
+ *
+ * Once a block has been ACKd, there is no need to retransmit it.
+ */
+ return;
+ }
+ last_block1_tid = received->tid;
+
+ if (payload.length <= (block.num+1) * (1 << (block.szx + 4))) {
+ coap_log(LOG_DEBUG, "upload ready\n");
+ if (coap_get_data(received, &len, &databuf))
+ append_to_output(databuf, len);
+ ready = 1;
+ return;
+ }
+
+ /* create pdu with request for next block */
+ pdu = coap_new_request(ctx, session, method, NULL, NULL, 0); /* first, create bare PDU w/o any option */
+ if (pdu) {
+
+ /* add URI components from optlist */
+ for (option = optlist; option; option = option->next ) {
+ switch (option->number) {
+ case COAP_OPTION_URI_HOST :
+ case COAP_OPTION_URI_PORT :
+ case COAP_OPTION_URI_PATH :
+ case COAP_OPTION_CONTENT_FORMAT :
+ case COAP_OPTION_URI_QUERY :
+ coap_add_option(pdu, option->number, option->length,
+ option->data);
+ break;
+ default:
+ ; /* skip other options */
+ }
+ }
+
+ /* finally add updated block option from response, clear M bit */
+ /* blocknr = (blocknr & 0xfffffff7) + 0x10; */
+ block.num = num + 1;
+ block.m = ((block.num+1) * (1 << (block.szx + 4)) < payload.length);
+
+ coap_log(LOG_DEBUG, "send block %d\n", block.num);
+ coap_add_option(pdu,
+ COAP_OPTION_BLOCK1,
+ coap_encode_var_safe(buf, sizeof(buf),
+ (block.num << 4) | (block.m << 3) | block.szx), buf);
+
+ coap_add_block(pdu,
+ payload.length,
+ payload.s,
+ block.num,
+ block.szx);
+ if (coap_get_log_level() < LOG_DEBUG)
+ coap_show_pdu(LOG_INFO, pdu);
+
+ tid = coap_send(session, pdu);
+
+ if (tid == COAP_INVALID_TID) {
+ coap_log(LOG_DEBUG, "message_handler: error sending new request\n");
+ } else {
+ wait_ms = wait_seconds * 1000;
+ wait_ms_reset = 1;
+ }
+
+ return;
+ }
+ } else {
+ /* There is no block option set, just read the data and we are done. */
+ if (coap_get_data(received, &len, &databuf))
+ append_to_output(databuf, len);
+ }
+ }
+ } else { /* no 2.05 */
+
+ /* check if an error was signaled and output payload if so */
+ if (COAP_RESPONSE_CLASS(received->code) >= 4) {
+ fprintf(stderr, "%d.%02d",
+ (received->code >> 5), received->code & 0x1F);
+ if (coap_get_data(received, &len, &databuf)) {
+ fprintf(stderr, " ");
+ while(len--)
+ fprintf(stderr, "%c", *databuf++);
+ }
+ fprintf(stderr, "\n");
+ }
+
+ }
+
+ /* any pdu that has been created in this function must be sent by now */
+ assert(pdu == NULL);
+
+ /* our job is done, we can exit at any time */
+ ready = coap_check_option(received, COAP_OPTION_OBSERVE, &opt_iter) == NULL;
+}
+
+/* message_handler_fnd_post */
+static void
+message_handler_fnd_post(struct coap_context_t *ctx,
+ coap_session_t *session,
+ coap_pdu_t *sent,
+ coap_pdu_t *received,
+ const coap_tid_t id UNUSED_PARAM) {
+
+ coap_pdu_t *pdu = NULL;
+ coap_opt_t *block_opt;
+ coap_opt_iterator_t opt_iter;
+ unsigned char buf[4];
+ coap_optlist_t *option;
+ size_t len;
+ unsigned char *databuf;
+ coap_tid_t tid;
+
+#ifndef NDEBUG
+ coap_log(LOG_DEBUG, "** process incoming %d.%02d response:\n",
+ (received->code >> 5), received->code & 0x1F);
+ if (coap_get_log_level() < LOG_DEBUG)
+ coap_show_pdu(LOG_INFO, received);
+#endif
+
+ /* check if this is a response to our original request */
+ if (!check_token(received)) {
+ /* drop if this was just some message, or send RST in case of notification */
+ if (!sent && (received->type == COAP_MESSAGE_CON ||
+ received->type == COAP_MESSAGE_NON))
+ coap_send_rst(session, received);
+ return;
+ }
+
+ if (received->type == COAP_MESSAGE_RST) {
+ coap_log(LOG_INFO, "got RST\n");
+ return;
+ }
+
+ /* output the received data, if any */
+ if (COAP_RESPONSE_CLASS(received->code) == 2) {
+
+ /* set obs timer if we have successfully subscribed a resource */
+ if (!obs_started && coap_check_option(received, COAP_OPTION_OBSERVE, &opt_iter)) {
+ coap_log(LOG_DEBUG,
+ "observation relationship established, set timeout to %d\n",
+ obs_seconds);
+ obs_started = 1;
+ obs_ms = obs_seconds * 1000;
+ obs_ms_reset = 1;
+ }
+
+ /* Got some data, check if block option is set. Behavior is undefined if
+ * both, Block1 and Block2 are present. */
+ block_opt = coap_check_option(received, COAP_OPTION_BLOCK2, &opt_iter);
+ if (block_opt) { /* handle Block2 */
+ uint16_t blktype = opt_iter.type;
+
+ /* TODO: check if we are looking at the correct block number */
+ if (coap_get_data(received, &len, &databuf))
+ append_to_output(databuf, len);
+
+ if (coap_opt_block_num(block_opt) == 0) {
+ /* See if observe is set in first response */
+ ready = coap_check_option(received,
+ COAP_OPTION_OBSERVE, &opt_iter) == NULL;
+ }
+ if(COAP_OPT_BLOCK_MORE(block_opt)) {
+ /* more bit is set */
+ coap_log(LOG_DEBUG, "found the M bit, block size is %u, block nr. %u\n",
+ COAP_OPT_BLOCK_SZX(block_opt),
+ coap_opt_block_num(block_opt));
+
+ /* create pdu with request for next block */
+ pdu = coap_new_request(ctx, session, method, NULL, NULL, 0); /* first, create bare PDU w/o any option */
+ if ( pdu ) {
+ /* add URI components from optlist */
+ for (option = optlist2; option; option = option->next ) {
+ switch (option->number) {
+ case COAP_OPTION_URI_HOST :
+ case COAP_OPTION_URI_PORT :
+ case COAP_OPTION_URI_PATH :
+ case COAP_OPTION_URI_QUERY :
+ coap_add_option(pdu, option->number, option->length,
+ option->data);
+ break;
+ default:
+ ; /* skip other options */
+ }
+ }
+
+ /* finally add updated block option from response, clear M bit */
+ /* blocknr = (blocknr & 0xfffffff7) + 0x10; */
+ coap_log(LOG_DEBUG, "query block %d\n",
+ (coap_opt_block_num(block_opt) + 1));
+ coap_add_option(pdu,
+ blktype,
+ coap_encode_var_safe(buf, sizeof(buf),
+ ((coap_opt_block_num(block_opt) + 1) << 4) |
+ COAP_OPT_BLOCK_SZX(block_opt)), buf);
+
+ tid = coap_send(session, pdu);
+
+ if (tid == COAP_INVALID_TID) {
+ coap_log(LOG_DEBUG, "message_handler: error sending new request\n");
+ } else {
+ wait_ms = wait_seconds * 1000;
+ wait_ms_reset = 1;
+ }
+
+ return;
+ }
+ }
+ return;
+ } else { /* no Block2 option */
+ block_opt = coap_check_option(received, COAP_OPTION_BLOCK1, &opt_iter);
+
+ if (block_opt) { /* handle Block1 */
+ unsigned int szx = COAP_OPT_BLOCK_SZX(block_opt);
+ unsigned int num = coap_opt_block_num(block_opt);
+ coap_log(LOG_DEBUG,
+ "found Block1 option, block size is %u, block nr. %u\n",
+ szx, num);
+ if (szx != block.szx) {
+ unsigned int bytes_sent = ((block.num + 1) << (block.szx + 4));
+ if (bytes_sent % (1 << (szx + 4)) == 0) {
+ /* Recompute the block number of the previous packet given the new block size */
+ num = block.num = (bytes_sent >> (szx + 4)) - 1;
+ block.szx = szx;
+ coap_log(LOG_DEBUG,
+ "new Block1 size is %u, block number %u completed\n",
+ (1 << (block.szx + 4)), block.num);
+ } else {
+ coap_log(LOG_DEBUG, "ignoring request to increase Block1 size, "
+ "next block is not aligned on requested block size boundary. "
+ "(%u x %u mod %u = %u != 0)\n",
+ block.num + 1, (1 << (block.szx + 4)), (1 << (szx + 4)),
+ bytes_sent % (1 << (szx + 4)));
+ }
+ }
+
+ if (last_block1_tid == received->tid) {
+ /*
+ * Duplicate BLOCK1 ACK
+ *
+ * RFCs not clear here, but on a lossy connection, there could
+ * be multiple BLOCK1 ACKs, causing the client to retransmit the
+ * same block multiple times.
+ *
+ * Once a block has been ACKd, there is no need to retransmit it.
+ */
+ return;
+ }
+ last_block1_tid = received->tid;
+
+ if (payload.length <= (block.num+1) * (1 << (block.szx + 4))) {
+ coap_log(LOG_DEBUG, "upload ready\n");
+ if (coap_get_data(received, &len, &databuf))
+ append_to_output(databuf, len);
+ ready = 1;
+ return;
+ }
+
+ /* create pdu with request for next block */
+ pdu = coap_new_request(ctx, session, method, NULL, NULL, 0); /* first, create bare PDU w/o any option */
+ if (pdu) {
+
+ /* add URI components from optlist */
+ for (option = optlist2; option; option = option->next ) {
+ switch (option->number) {
+ case COAP_OPTION_URI_HOST :
+ case COAP_OPTION_URI_PORT :
+ case COAP_OPTION_URI_PATH :
+ case COAP_OPTION_CONTENT_FORMAT :
+ case COAP_OPTION_URI_QUERY :
+ coap_add_option(pdu, option->number, option->length,
+ option->data);
+ break;
+ default:
+ ; /* skip other options */
+ }
+ }
+
+ /* finally add updated block option from response, clear M bit */
+ /* blocknr = (blocknr & 0xfffffff7) + 0x10; */
+ block.num = num + 1;
+ block.m = ((block.num+1) * (1 << (block.szx + 4)) < payload.length);
+
+ coap_log(LOG_DEBUG, "send block %d\n", block.num);
+ coap_add_option(pdu,
+ COAP_OPTION_BLOCK1,
+ coap_encode_var_safe(buf, sizeof(buf),
+ (block.num << 4) | (block.m << 3) | block.szx), buf);
+
+ coap_add_block(pdu,
+ payload.length,
+ payload.s,
+ block.num,
+ block.szx);
+ if (coap_get_log_level() < LOG_DEBUG)
+ coap_show_pdu(LOG_INFO, pdu);
+
+ tid = coap_send(session, pdu);
+
+ if (tid == COAP_INVALID_TID) {
+ coap_log(LOG_DEBUG, "message_handler: error sending new request\n");
+ } else {
+ wait_ms = wait_seconds * 1000;
+ wait_ms_reset = 1;
+ }
+
+ return;
+ }
+ } else {
+ /* There is no block option set, just read the data and we are done. */
+ if (coap_get_data(received, &len, &databuf))
+ append_to_output(databuf, len);
+ }
+ }
+ } else { /* no 2.05 */
+
+ /* check if an error was signaled and output payload if so */
+ if (COAP_RESPONSE_CLASS(received->code) >= 4) {
+ fprintf(stderr, "%d.%02d",
+ (received->code >> 5), received->code & 0x1F);
+ if (coap_get_data(received, &len, &databuf)) {
+ fprintf(stderr, " ");
+ while(len--)
+ fprintf(stderr, "%c", *databuf++);
+ }
+ fprintf(stderr, "\n");
+ }
+
+ }
+
+ /* any pdu that has been created in this function must be sent by now */
+ assert(pdu == NULL);
+
+ /* our job is done, we can exit at any time */
+ ready = coap_check_option(received, COAP_OPTION_OBSERVE, &opt_iter) == NULL;
+}
+
+static void
+usage( const char *program, const char *version) {
+ const char *p;
+ char buffer[64];
+
+ p = strrchr( program, '/' );
+ if ( p )
+ program = ++p;
+
+ fprintf( stderr, "%s v%s -- a small CoAP implementation\n"
+ "(c) 2010-2018 Olaf Bergmann <bergmann@tzi.org> and others\n\n"
+ "%s\n\n"
+ "Usage: %s [-a addr] [-b [num,]size] [-c certfile] [-C cafile] [-e text]\n"
+ "\t\t[-f file] [-k key] [-l loss] [-m method] [-o file]\n"
+ "\t\t[-p port] [-r] [-s duration] [-t type] [-u user]\n"
+ "\t\t[-v num] [-A type] [-B seconds] [-K interval] [-N] [-O num,text]\n"
+ "\t\t[-P addr[:port]] [-R root_cafile] [-T token] [-U] URI\n\n"
+ "\tURI can be an absolute URI or a URI prefixed with scheme and host\n\n"
+ "General Options\n"
+ "\t-a addr\t\tThe local interface address to use\n"
+ "\t-b [num,]size\tBlock size to be used in GET/PUT/POST requests\n"
+ "\t \t\t(value must be a multiple of 16 not larger than 1024)\n"
+ "\t \t\tIf num is present, the request chain will start at\n"
+ "\t \t\tblock num\n"
+ "\t-c certfile\tPEM file containing both CERTIFICATE and PRIVATE KEY\n"
+ "\t \t\tThis argument requires (D)TLS with PKI to be available\n"
+ "\t-d path\t\tDirectory to store files received from the server\n"
+ "\t-e text\t\tInclude text as payload (use percent-encoding for\n"
+ "\t \t\tnon-ASCII characters)\n"
+ "\t-i iterations\tNumber of iterations to run. (i.e. 10 coap requests)\n"
+ "\t-f file\t\tFile to send with PUT/POST (use '-' for STDIN)\n"
+ "\t-k key \t\tPre-shared key for the specified user. This argument\n"
+ "\t \t\trequires (D)TLS with PSK to be available\n"
+ "\t-l list\t\tFail to send some datagrams specified by a comma separated\n"
+ "\t \t\tlist of numbers or number ranges (for debugging only)\n"
+ "\t-l loss%%\tRandomly fail to send datagrams with the specified\n"
+ "\t \t\tprobability - 100%% all datagrams, 0%% no datagrams\n"
+ "\t-m method\tRequest method (get|put|post|delete|fetch|patch|ipatch),\n"
+ "\t \t\tdefault is 'get'\n"
+ "\t-o file\t\tOutput received data to this file (use '-' for STDOUT)\n"
+ "\t-p port\t\tListen on specified port\n"
+ "\t-r \t\tUse reliable protocol (TCP or TLS)\n"
+ "\t-s duration\tSubscribe to / Observe resource for given duration [s]\n"
+ "\t-t type\t\tContent format for given resource for PUT/POST\n"
+ "\t-u user\t\tUser identity for pre-shared key mode. This argument\n"
+ "\t \t\trequires (D)TLS with PSK to be available\n"
+ "\t-v num \t\tVerbosity level (default: 3)\n"
+ "\t-A type\t\tAccepted media type\n"
+ "\t-B seconds\tBreak operation after waiting given seconds\n"
+ "\t \t\t(default is %d)\n"
+ "\t-C cafile\tPEM file containing the CA Certificate that was used to\n"
+ "\t \t\tsign the certfile. This will trigger the validation of\n"
+ "\t \t\tthe server certificate. If certfile is self-signed (as\n"
+ "\t \t\tdefined by '-c certfile'), then you need to have on the\n"
+ "\t \t\tcommand line the same filename for both the certfile and\n"
+ "\t \t\tcafile (as in '-c certfile -C certfile') to trigger\n"
+ "\t \t\tvalidation\n"
+ "\t-1 ms \t\tDelay before crts coap messages in FND style requests. \n"
+ "\t \t\tMeasured in ms\n"
+ "\t-2 ms \t\tDelay before the 1st sen coap messages in FND style requests. \n"
+ "\t \t\tMeasured in ms\n"
+ "\t-3 ms \t\tDelay before the 2nd sen coap messages in FND style requests. \n"
+ "\t \t\tMeasured in ms\n"
+ "\t-I ms \t\tDelay between iterations in ms\n"
+ "\t-K interval\tsend a ping after interval seconds of inactivity (TCP only)\n"
+ "\t-N \t\tSend NON-confirmable message\n"
+ "\t-O num,text\tAdd option num with contents text to request\n"
+ "\t-P addr[:port]\tUse proxy (automatically adds Proxy-Uri option to\n"
+ "\t \t\trequest)\n"
+ "\t-R root_cafile\tPEM file containing the set of trusted root CAs that\n"
+ "\t \t\tare to be used to validate the server certificate.\n"
+ "\t \t\tThe '-C cafile' does not have to be in this list and is\n"
+ "\t \t\t'trusted' for the verification.\n"
+ "\t \t\tAlternatively, this can point to a directory containing a\n"
+ "\t \t\tset of CA PEM files\n"
+ "\t-S ms \t\tDelay in starting coap requests in ms\n"
+ "\t-T token\tInclude specified token\n"
+ "\t-U \t\tNever include Uri-Host or Uri-Port options\n"
+ "\n"
+ "Examples:\n"
+ "\tcoap-client -m get coap://[::1]/\n"
+ "\tcoap-client -m get coap://[::1]/.well-known/core\n"
+ "\tcoap-client -m get coap+tcp://[::1]/.well-known/core\n"
+ "\tcoap-client -m get coaps://[::1]/.well-known/core\n"
+ "\tcoap-client -m get coaps+tcp://[::1]/.well-known/core\n"
+ "\tcoap-client -m get -T cafe coap://[::1]/time\n"
+ "\techo -n 1000 | coap-client -m put -T cafe coap://[::1]/time -f -\n"
+ ,program, version, coap_string_tls_version(buffer, sizeof(buffer))
+ ,program, wait_seconds);
+}
+
+typedef struct {
+ uint16_t code;
+ const char *media_type;
+} content_type_t;
+
+static void
+cmdline_content_type(char *arg, uint16_t key) {
+ static content_type_t content_types[] = {
+ { 0, "plain" },
+ { 0, "text/plain" },
+ { 40, "link" },
+ { 40, "link-format" },
+ { 40, "application/link-format" },
+ { 41, "xml" },
+ { 41, "application/xml" },
+ { 42, "binary" },
+ { 42, "octet-stream" },
+ { 42, "application/octet-stream" },
+ { 47, "exi" },
+ { 47, "application/exi" },
+ { 50, "json" },
+ { 50, "application/json" },
+ { 60, "cbor" },
+ { 60, "application/cbor" },
+ { 286, "application/pkcs10" },
+ { 255, NULL }
+ };
+ coap_optlist_t *node;
+ unsigned char i;
+ uint16_t value;
+ uint8_t buf[2];
+
+ if (isdigit(*arg)) {
+ value = atoi(arg);
+ } else {
+ for (i=0;
+ content_types[i].media_type &&
+ strncmp(arg, content_types[i].media_type, strlen(arg)) != 0 ;
+ ++i)
+ ;
+
+ if (content_types[i].media_type) {
+ value = content_types[i].code;
+ } else {
+ coap_log(LOG_WARNING, "W: unknown content-format '%s'\n",arg);
+ return;
+ }
+ }
+
+ node = coap_new_optlist(key, coap_encode_var_safe(buf, sizeof(buf), value), buf);
+ if (node) {
+ coap_insert_optlist(&optlist, node);
+ }
+}
+
+/* Create the content type for pkcs10 */
+static void
+cmdline_content_type2(uint16_t key) {
+ coap_optlist_t *node;
+ uint16_t value;
+ uint8_t buf[2];
+
+ /* Content type for pkcs10 */
+ value = 286;
+ node = coap_new_optlist(key, coap_encode_var_safe(buf, sizeof(buf), value), buf);
+ if (node) {
+ coap_insert_optlist(&optlist2, node);
+ }
+}
+
+static uint16_t
+get_default_port(const coap_uri_t *u) {
+ return coap_uri_scheme_is_secure(u) ? COAPS_DEFAULT_PORT : COAP_DEFAULT_PORT;
+}
+
+
+static int
+cmdline_uri2(char *arg, int create_uri_opts) {
+ unsigned char portbuf[2];
+#define BUFSIZE 40
+ unsigned char _buf[BUFSIZE];
+ unsigned char *buf = _buf;
+ size_t buflen;
+ int res;
+
+ if (proxy.length) { /* create Proxy-Uri from argument */
+ size_t len = strlen(arg);
+ while (len > 270) {
+ coap_insert_optlist(&optlist2,
+ coap_new_optlist(COAP_OPTION_PROXY_URI,
+ 270,
+ (unsigned char *)arg));
+
+ len -= 270;
+ arg += 270;
+ }
+
+ coap_insert_optlist(&optlist2,
+ coap_new_optlist(COAP_OPTION_PROXY_URI,
+ len,
+ (unsigned char *)arg));
+
+ } else { /* split arg into Uri-* options */
+ if (coap_split_uri((unsigned char *)arg, strlen(arg), &uri) < 0) {
+ coap_log(LOG_ERR, "invalid CoAP URI\n");
+ return -1;
+ }
+
+ if (uri.scheme==COAP_URI_SCHEME_COAPS && !reliable && !coap_dtls_is_supported()) {
+ coap_log(LOG_EMERG,
+ "coaps URI scheme not supported in this version of libcoap\n");
+ return -1;
+ }
+
+ if ((uri.scheme==COAP_URI_SCHEME_COAPS_TCP || (uri.scheme==COAP_URI_SCHEME_COAPS && reliable)) && !coap_tls_is_supported()) {
+ coap_log(LOG_EMERG,
+ "coaps+tcp URI scheme not supported in this version of libcoap\n");
+ return -1;
+ }
+
+ if (uri.port != get_default_port(&uri) && create_uri_opts) {
+ coap_insert_optlist(&optlist2,
+ coap_new_optlist(COAP_OPTION_URI_PORT,
+ coap_encode_var_safe(portbuf, sizeof(portbuf),
+ (uri.port & 0xffff)),
+ portbuf));
+ }
+
+ if (uri.path.length) {
+ buflen = BUFSIZE;
+ res = coap_split_path(uri.path.s, uri.path.length, buf, &buflen);
+
+ while (res--) {
+ coap_insert_optlist(&optlist2,
+ coap_new_optlist(COAP_OPTION_URI_PATH,
+ coap_opt_length(buf),
+ coap_opt_value(buf)));
+
+ buf += coap_opt_size(buf);
+ }
+ }
+
+ if (uri.query.length) {
+ buflen = BUFSIZE;
+ buf = _buf;
+ res = coap_split_query(uri.query.s, uri.query.length, buf, &buflen);
+
+ while (res--) {
+ coap_insert_optlist(&optlist2,
+ coap_new_optlist(COAP_OPTION_URI_QUERY,
+ coap_opt_length(buf),
+ coap_opt_value(buf)));
+
+ buf += coap_opt_size(buf);
+ }
+ }
+ }
+
+ return 0;
+}
+
+/**
+ * Sets global URI options according to the URI passed as @p arg.
+ * This function returns 0 on success or -1 on error.
+ *
+ * @param arg The URI string.
+ * @param create_uri_opts Flags that indicate whether Uri-Host and
+ * Uri-Port should be suppressed.
+ * @return 0 on success, -1 otherwise
+ */
+static int
+cmdline_uri(char *arg, int create_uri_opts) {
+ unsigned char portbuf[2];
+#define BUFSIZE 40
+ unsigned char _buf[BUFSIZE];
+ unsigned char *buf = _buf;
+ size_t buflen;
+ int res;
+
+ if (proxy.length) { /* create Proxy-Uri from argument */
+ size_t len = strlen(arg);
+ while (len > 270) {
+ coap_insert_optlist(&optlist,
+ coap_new_optlist(COAP_OPTION_PROXY_URI,
+ 270,
+ (unsigned char *)arg));
+
+ len -= 270;
+ arg += 270;
+ }
+
+ coap_insert_optlist(&optlist,
+ coap_new_optlist(COAP_OPTION_PROXY_URI,
+ len,
+ (unsigned char *)arg));
+
+ } else { /* split arg into Uri-* options */
+ if (coap_split_uri((unsigned char *)arg, strlen(arg), &uri) < 0) {
+ coap_log(LOG_ERR, "invalid CoAP URI\n");
+ return -1;
+ }
+
+ if (uri.scheme==COAP_URI_SCHEME_COAPS && !reliable && !coap_dtls_is_supported()) {
+ coap_log(LOG_EMERG,
+ "coaps URI scheme not supported in this version of libcoap\n");
+ return -1;
+ }
+
+ if ((uri.scheme==COAP_URI_SCHEME_COAPS_TCP || (uri.scheme==COAP_URI_SCHEME_COAPS && reliable)) && !coap_tls_is_supported()) {
+ coap_log(LOG_EMERG,
+ "coaps+tcp URI scheme not supported in this version of libcoap\n");
+ return -1;
+ }
+
+ if (uri.port != get_default_port(&uri) && create_uri_opts) {
+ coap_insert_optlist(&optlist,
+ coap_new_optlist(COAP_OPTION_URI_PORT,
+ coap_encode_var_safe(portbuf, sizeof(portbuf),
+ (uri.port & 0xffff)),
+ portbuf));
+ }
+
+ if (uri.path.length) {
+ buflen = BUFSIZE;
+ res = coap_split_path(uri.path.s, uri.path.length, buf, &buflen);
+
+ while (res--) {
+ coap_insert_optlist(&optlist,
+ coap_new_optlist(COAP_OPTION_URI_PATH,
+ coap_opt_length(buf),
+ coap_opt_value(buf)));
+
+ buf += coap_opt_size(buf);
+ }
+ }
+
+ if (uri.query.length) {
+ buflen = BUFSIZE;
+ buf = _buf;
+ res = coap_split_query(uri.query.s, uri.query.length, buf, &buflen);
+
+ while (res--) {
+ coap_insert_optlist(&optlist,
+ coap_new_optlist(COAP_OPTION_URI_QUERY,
+ coap_opt_length(buf),
+ coap_opt_value(buf)));
+
+ buf += coap_opt_size(buf);
+ }
+ }
+ }
+
+ return 0;
+}
+
+static int
+cmdline_blocksize(char *arg) {
+ uint16_t size;
+
+ again:
+ size = 0;
+ while(*arg && *arg != ',')
+ size = size * 10 + (*arg++ - '0');
+
+ if (*arg == ',') {
+ arg++;
+ block.num = size;
+ goto again;
+ }
+
+ if (size)
+ block.szx = (coap_fls(size >> 4) - 1) & 0x07;
+
+ flags |= FLAGS_BLOCK;
+ return 1;
+}
+
+/* Called after processing the options from the commandline to set
+ * Block1 or Block2 depending on method. */
+static void
+set_blocksize(void) {
+ static unsigned char buf[4]; /* hack: temporarily take encoded bytes */
+ uint16_t opt;
+ unsigned int opt_length;
+
+ if (method != COAP_REQUEST_DELETE) {
+ opt = method == COAP_REQUEST_GET ? COAP_OPTION_BLOCK2 : COAP_OPTION_BLOCK1;
+
+ block.m = (opt == COAP_OPTION_BLOCK1) &&
+ ((1u << (block.szx + 4)) < payload.length);
+
+ opt_length = coap_encode_var_safe(buf, sizeof(buf),
+ (block.num << 4 | block.m << 3 | block.szx));
+
+ coap_insert_optlist(&optlist, coap_new_optlist(opt, opt_length, buf));
+ }
+}
+
+static void
+set_blocksize_fnd_post(void) {
+ static unsigned char buf[4]; /* hack: temporarily take encoded bytes */
+ uint16_t opt;
+ unsigned int opt_length;
+
+ if (method != COAP_REQUEST_DELETE) {
+ opt = method == COAP_REQUEST_GET ? COAP_OPTION_BLOCK2 : COAP_OPTION_BLOCK1;
+
+ block.m = (opt == COAP_OPTION_BLOCK1) &&
+ ((1u << (block.szx + 4)) < payload.length);
+
+ opt_length = coap_encode_var_safe(buf, sizeof(buf),
+ (block.num << 4 | block.m << 3 | block.szx));
+
+ coap_insert_optlist(&optlist2, coap_new_optlist(opt, opt_length, buf));
+ }
+}
+
+static void
+cmdline_subscribe(char *arg) {
+ obs_seconds = atoi(arg);
+ coap_insert_optlist(&optlist, coap_new_optlist(COAP_OPTION_OBSERVE,
+ COAP_OBSERVE_ESTABLISH, NULL));
+}
+
+static int
+cmdline_proxy(char *arg) {
+ char *proxy_port_str = strrchr((const char *)arg, ':'); /* explicit port ? */
+ if (proxy_port_str) {
+ char *ipv6_delimiter = strrchr((const char *)arg, ']');
+ if (!ipv6_delimiter) {
+ if (proxy_port_str == strchr((const char *)arg, ':')) {
+ /* host:port format - host not in ipv6 hexadecimal string format */
+ *proxy_port_str++ = '\0'; /* split */
+ proxy_port = atoi(proxy_port_str);
+ }
+ } else {
+ arg = strchr((const char *)arg, '[');
+ if (!arg) return 0;
+ arg++;
+ *ipv6_delimiter = '\0'; /* split */
+ if (ipv6_delimiter + 1 == proxy_port_str++) {
+ /* [ipv6 address]:port */
+ proxy_port = atoi(proxy_port_str);
+ }
+ }
+ }
+
+ proxy.length = strlen(arg);
+ if ( (proxy.s = coap_malloc(proxy.length + 1)) == NULL) {
+ proxy.length = 0;
+ return 0;
+ }
+
+ memcpy(proxy.s, arg, proxy.length+1);
+ return 1;
+}
+
+static inline void
+cmdline_token(char *arg) {
+ the_token.length = min(sizeof(_token_data), strlen(arg));
+ if (the_token.length > 0) {
+ memcpy((char *)the_token.s, arg, the_token.length);
+ }
+}
+
+static void
+cmdline_option(char *arg) {
+ unsigned int num = 0;
+
+ while (*arg && *arg != ',') {
+ num = num * 10 + (*arg - '0');
+ ++arg;
+ }
+ if (*arg == ',')
+ ++arg;
+
+ coap_insert_optlist(&optlist,
+ coap_new_optlist(num, strlen(arg), (unsigned char *)arg));
+}
+
+/**
+ * Calculates decimal value from hexadecimal ASCII character given in
+ * @p c. The caller must ensure that @p c actually represents a valid
+ * heaxdecimal character, e.g. with isxdigit(3).
+ *
+ * @hideinitializer
+ */
+#define hexchar_to_dec(c) ((c) & 0x40 ? ((c) & 0x0F) + 9 : ((c) & 0x0F))
+
+/**
+ * Decodes percent-encoded characters while copying the string @p seg
+ * of size @p length to @p buf. The caller of this function must
+ * ensure that the percent-encodings are correct (i.e. the character
+ * '%' is always followed by two hex digits. and that @p buf provides
+ * sufficient space to hold the result. This function is supposed to
+ * be called by make_decoded_option() only.
+ *
+ * @param seg The segment to decode and copy.
+ * @param length Length of @p seg.
+ * @param buf The result buffer.
+ */
+static void
+decode_segment(const uint8_t *seg, size_t length, unsigned char *buf) {
+
+ while (length--) {
+
+ if (*seg == '%') {
+ *buf = (hexchar_to_dec(seg[1]) << 4) + hexchar_to_dec(seg[2]);
+
+ seg += 2; length -= 2;
+ } else {
+ *buf = *seg;
+ }
+
+ ++buf; ++seg;
+ }
+}
+
+/**
+ * Runs through the given path (or query) segment and checks if
+ * percent-encodings are correct. This function returns @c -1 on error
+ * or the length of @p s when decoded.
+ */
+static int
+check_segment(const uint8_t *s, size_t length) {
+
+ size_t n = 0;
+
+ while (length) {
+ if (*s == '%') {
+ if (length < 2 || !(isxdigit(s[1]) && isxdigit(s[2])))
+ return -1;
+
+ s += 2;
+ length -= 2;
+ }
+
+ ++s; ++n; --length;
+ }
+
+ return n;
+}
+
+static int
+cmdline_input(char *text, coap_string_t *buf) {
+ int len;
+ len = check_segment((unsigned char *)text, strlen(text));
+
+ if (len < 0)
+ return 0;
+
+ buf->s = (unsigned char *)coap_malloc(len);
+ if (!buf->s)
+ return 0;
+
+ buf->length = len;
+ decode_segment((unsigned char *)text, strlen(text), buf->s);
+ return 1;
+}
+
+static int
+cmdline_input_from_file(char *filename, coap_string_t *buf) {
+ FILE *inputfile = NULL;
+ ssize_t len;
+ int result = 1;
+ struct stat statbuf;
+
+ if (!filename || !buf)
+ return 0;
+
+ if (filename[0] == '-' && !filename[1]) { /* read from stdin */
+ buf->length = 20000;
+ buf->s = (unsigned char *)coap_malloc(buf->length);
+ if (!buf->s)
+ return 0;
+
+ inputfile = stdin;
+ } else {
+ /* read from specified input file */
+ inputfile = fopen(filename, "r");
+ if ( !inputfile ) {
+ perror("cmdline_input_from_file: fopen");
+ return 0;
+ }
+
+ if (fstat(fileno(inputfile), &statbuf) < 0) {
+ perror("cmdline_input_from_file: stat");
+ fclose(inputfile);
+ return 0;
+ }
+
+ buf->length = statbuf.st_size;
+ buf->s = (unsigned char *)coap_malloc(buf->length);
+ if (!buf->s) {
+ fclose(inputfile);
+ return 0;
+ }
+ }
+
+ len = fread(buf->s, 1, buf->length, inputfile);
+
+ if (len < 0 || ((size_t)len < buf->length)) {
+ if (ferror(inputfile) != 0) {
+ perror("cmdline_input_from_file: fread");
+ coap_free(buf->s);
+ buf->length = 0;
+ buf->s = NULL;
+ result = 0;
+ } else {
+ buf->length = len;
+ }
+ }
+
+ if (inputfile != stdin)
+ fclose(inputfile);
+
+ return result;
+}
+
+static method_t
+cmdline_method(char *arg) {
+ static const char *methods[] =
+ { 0, "get", "post", "put", "delete", "fetch", "patch", "ipatch", 0};
+ unsigned char i;
+
+ for (i=1; methods[i] && strcasecmp(arg,methods[i]) != 0 ; ++i)
+ ;
+
+ return i; /* note that we do not prevent illegal methods */
+}
+
+static ssize_t
+cmdline_read_user(char *arg, unsigned char *buf, size_t maxlen) {
+ size_t len = strnlen(arg, maxlen);
+ if (len) {
+ memcpy(buf, arg, len);
+ }
+ return len;
+}
+
+static ssize_t
+cmdline_read_key(char *arg, unsigned char *buf, size_t maxlen) {
+ size_t len = strnlen(arg, maxlen);
+ if (len) {
+ memcpy(buf, arg, len);
+ return len;
+ }
+ return -1;
+}
+
+static int
+verify_cn_callback(const char *cn,
+ const uint8_t *asn1_public_cert UNUSED_PARAM,
+ size_t asn1_length UNUSED_PARAM,
+ coap_session_t *session UNUSED_PARAM,
+ unsigned depth,
+ int validated UNUSED_PARAM,
+ void *arg UNUSED_PARAM
+) {
+ coap_log(LOG_INFO, "CN '%s' presented by server (%s)\n",
+ cn, depth ? "CA" : "Certificate");
+ return 1;
+}
+
+static coap_dtls_pki_t *
+setup_pki(void) {
+ static coap_dtls_pki_t dtls_pki;
+ static char client_sni[256];
+
+ memset (&dtls_pki, 0, sizeof(dtls_pki));
+ dtls_pki.version = COAP_DTLS_PKI_SETUP_VERSION;
+ if (ca_file) {
+ /*
+ * Add in additional certificate checking.
+ * This list of enabled can be tuned for the specific
+ * requirements - see 'man coap_encryption'.
+ */
+ dtls_pki.verify_peer_cert = 1;
+ dtls_pki.require_peer_cert = 1;
+ dtls_pki.allow_self_signed = 1;
+ dtls_pki.allow_expired_certs = 1;
+ dtls_pki.cert_chain_validation = 1;
+ dtls_pki.cert_chain_verify_depth = 2;
+ dtls_pki.check_cert_revocation = 1;
+ dtls_pki.allow_no_crl = 1;
+ dtls_pki.allow_expired_crl = 1;
+ dtls_pki.validate_cn_call_back = verify_cn_callback;
+ dtls_pki.cn_call_back_arg = NULL;
+ dtls_pki.validate_sni_call_back = NULL;
+ dtls_pki.sni_call_back_arg = NULL;
+ memset(client_sni, 0, sizeof(client_sni));
+ if (uri.host.length)
+ memcpy(client_sni, uri.host.s, min(uri.host.length, sizeof(client_sni)));
+ else
+ memcpy(client_sni, "localhost", 9);
+ dtls_pki.client_sni = client_sni;
+ }
+ dtls_pki.pki_key.key_type = COAP_PKI_KEY_PEM;
+ dtls_pki.pki_key.key.pem.public_cert = cert_file;
+ dtls_pki.pki_key.key.pem.private_key = cert_file;
+ dtls_pki.pki_key.key.pem.ca_file = ca_file;
+ return &dtls_pki;
+}
+
+#ifdef _WIN32
+#define S_ISDIR(x) (((x) & S_IFMT) == S_IFDIR)
+#endif
+
+static coap_session_t *
+get_session(
+ coap_context_t *ctx,
+ const char *local_addr,
+ const char *local_port,
+ coap_proto_t proto,
+ coap_address_t *dst,
+ const char *identity,
+ const uint8_t *key,
+ unsigned key_len
+) {
+ coap_session_t *session = NULL;
+
+ /* If general root CAs are defined */
+ if (root_ca_file) {
+ struct stat stbuf;
+ if ((stat(root_ca_file, &stbuf) == 0) && S_ISDIR(stbuf.st_mode)) {
+ coap_context_set_pki_root_cas(ctx, NULL, root_ca_file);
+ } else {
+ coap_context_set_pki_root_cas(ctx, root_ca_file, NULL);
+ }
+ }
+
+ if ( local_addr ) {
+ int s;
+ struct addrinfo hints;
+ struct addrinfo *result = NULL, *rp;
+
+ memset( &hints, 0, sizeof( struct addrinfo ) );
+ hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
+ hints.ai_socktype = COAP_PROTO_RELIABLE(proto) ? SOCK_STREAM : SOCK_DGRAM; /* Coap uses UDP */
+ hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST | AI_NUMERICSERV | AI_ALL;
+
+ s = getaddrinfo( local_addr, local_port, &hints, &result );
+ if ( s != 0 ) {
+ fprintf( stderr, "getaddrinfo: %s\n", gai_strerror( s ) );
+ return NULL;
+ }
+
+ /* iterate through results until success */
+ for ( rp = result; rp != NULL; rp = rp->ai_next ) {
+ coap_address_t bind_addr;
+ if ( rp->ai_addrlen <= sizeof( bind_addr.addr ) ) {
+ coap_address_init( &bind_addr );
+ bind_addr.size = rp->ai_addrlen;
+ memcpy( &bind_addr.addr, rp->ai_addr, rp->ai_addrlen );
+ if (cert_file && (proto == COAP_PROTO_DTLS || proto == COAP_PROTO_TLS)) {
+ coap_dtls_pki_t *dtls_pki = setup_pki();
+ session = coap_new_client_session_pki(ctx, &bind_addr, dst, proto, dtls_pki);
+ }
+ else if ((identity || key) &&
+ (proto == COAP_PROTO_DTLS || proto == COAP_PROTO_TLS) ) {
+ session = coap_new_client_session_psk( ctx, &bind_addr, dst, proto,
+ identity, key, key_len );
+ }
+ else {
+ session = coap_new_client_session( ctx, &bind_addr, dst, proto );
+ }
+ if ( session )
+ break;
+ }
+ }
+ freeaddrinfo( result );
+ } else {
+ if (cert_file && (proto == COAP_PROTO_DTLS || proto == COAP_PROTO_TLS)) {
+ coap_dtls_pki_t *dtls_pki = setup_pki();
+ session = coap_new_client_session_pki(ctx, NULL, dst, proto, dtls_pki);
+ }
+ else if ((identity || key) &&
+ (proto == COAP_PROTO_DTLS || proto == COAP_PROTO_TLS) )
+ session = coap_new_client_session_psk( ctx, NULL, dst, proto,
+ identity, key, key_len );
+ else
+ session = coap_new_client_session( ctx, NULL, dst, proto );
+ }
+ return session;
+}
+
+/*
+ * We need our own log handler so that we can write our timing logs
+ * into the logfile instead of stdout
+ */
+static
+void perf_log_handler (coap_log_t level, const char *message)
+{
+ if (!perf_log) {
+ if (!log_file.s || (log_file.length && log_file.s[0] == '-'))
+ perf_log = stdout;
+ else {
+ if (!(perf_log = fopen((char *)log_file.s, "w"))) {
+ fprintf(stdout, "Logging is set to %i", level);
+ perror("fopen");
+ }
+ }
+ }
+ fwrite(message, 1, strlen(message), perf_log);
+ fflush(perf_log);
+}
+
+int
+main(int argc, char **argv) {
+ coap_context_t *ctx1 = NULL;
+ coap_context_t *ctx2 = NULL;
+ coap_session_t *session = NULL;
+ coap_address_t dst;
+ static char addr[INET6_ADDRSTRLEN];
+ void *addrptr = NULL;
+ int result = -1;
+ coap_pdu_t *pdu;
+ static coap_str_const_t server;
+ uint16_t port = COAP_DEFAULT_PORT;
+ char port_str[NI_MAXSERV] = "0";
+ char node_str[NI_MAXHOST] = "";
+ int opt, res;
+ coap_log_t log_level = LOG_WARNING;
+ unsigned char user[MAX_USER + 1], key[MAX_KEY];
+ ssize_t user_length = 0, key_length = 0;
+ int create_uri_opts = 1;
+ /* Performance additions */
+ int iterations;
+ int start_delay = 0, iteration_delay = 0;
+ int fnd_delay1 = 0, fnd_delay2 = 0, fnd_delay3 = 0;
+ char output_log[MAX_CMD] = "/tmp/coap_debug.log";
+ long double pid = getpid();
+ double start_time, stop_time, elapsed;
+ int filename_length; /* Length of the path and name for the logfile */
+ char* uri_cacerts;
+ char* uri_simple_enroll;
+ int len_cacerts, len_simple_enroll;
+ int group = 0;
+ char* message_request;
+ int failure = 0;
+ char requested_method[5];
+ struct sigaction sa;
+
+ while ((opt = getopt(argc, argv, "Nra:b:c:e:d:f:i:k:m:p:s:t:o:v:A:B:C:G:I:O:P:R:S:T:u:U:l:K:M:1:2:3:")) != -1) {
+ switch (opt) {
+ case 'a':
+ strncpy(node_str, optarg, NI_MAXHOST - 1);
+ node_str[NI_MAXHOST - 1] = '\0';
+ break;
+ case 'b':
+ cmdline_blocksize(optarg);
+ break;
+ case 'B':
+ wait_seconds = atoi(optarg);
+ break;
+ case 'c':
+ cert_file = optarg;
+ break;
+ case 'C':
+ ca_file = optarg;
+ break;
+ case 'd':
+ output_dir.length = strlen(optarg);
+ output_dir.s = (unsigned char *)coap_malloc(output_dir.length + 1);
+
+ if (!output_dir.s) {
+ fprintf(stderr, "cannot set output dir: insufficient memory\n");
+ exit(-1);
+ } else {
+ /* copy directory name including trailing zero */
+ memcpy(output_dir.s, optarg, output_dir.length + 1);
+ if (stat((char *)output_dir.s, &st) == -1) {
+ mkdir((char *)output_dir.s, 0700);
+ }
+ /* Since we have an output dir, lets put it in the
+ * output directory to avoid collisions
+ */
+ filename_length = strlen("/coap_debug") + strlen(".log"); /* length of file name */
+ filename_length += output_dir.length; /* Add the length of the output directory */
+ filename_length += floor(log10(abs(pid))); /* Add the length of the pid */
+ if(MAX_CMD > filename_length) {
+ sprintf(output_log, "%s/coap_debug_%ld.log", output_dir.s, (long)pid);
+ }
+ }
+ break;
+ case 'S':
+ start_delay = atoi(optarg);
+ break;
+ case 'G':
+ /* Group messages into one handshake (crts/sen/sen) */
+ group = atoi(optarg);
+ break;
+ case 'i':
+ iterations = atoi(optarg);
+ break;
+ case 'I':
+ iteration_delay = atoi(optarg);
+ break;
+ case 'R':
+ root_ca_file = optarg;
+ break;
+ case 'e':
+ if (!cmdline_input(optarg, &payload))
+ payload.length = 0;
+ break;
+ case 'f':
+ if (!cmdline_input_from_file(optarg, &payload))
+ payload.length = 0;
+ break;
+ case 'F':
+ if (!cmdline_input_from_file(optarg, &payload2))
+ payload.length = 0;
+ break;
+ case 'k':
+ key_length = cmdline_read_key(optarg, key, MAX_KEY);
+ break;
+ case 'p':
+ strncpy(port_str, optarg, NI_MAXSERV - 1);
+ port_str[NI_MAXSERV - 1] = '\0';
+ break;
+ case 'm':
+ method = cmdline_method(optarg);
+ break;
+ case 'M':
+ /* Message request (crts/sen/sren/attr) */
+ message_request = coap_malloc(strlen(optarg));
+ strcpy(message_request, optarg);
+ break;
+ case 'N':
+ msgtype = COAP_MESSAGE_NON;
+ break;
+ case 's':
+ cmdline_subscribe(optarg);
+ break;
+ case 'o':
+ output_file.length = strlen(optarg);
+ output_file.s = (unsigned char *)coap_malloc(output_file.length + 1);
+
+ if (!output_file.s) {
+ fprintf(stderr, "cannot set output file: insufficient memory\n");
+ exit(-1);
+ } else {
+ /* copy filename including trailing zero */
+ memcpy(output_file.s, optarg, output_file.length + 1);
+ }
+ break;
+ case 'A':
+ cmdline_content_type(optarg, COAP_OPTION_ACCEPT);
+ break;
+ case 't':
+ cmdline_content_type(optarg, COAP_OPTION_CONTENT_TYPE);
+ break;
+ case 'O':
+ cmdline_option(optarg);
+ break;
+ case 'P':
+ if (!cmdline_proxy(optarg)) {
+ fprintf(stderr, "error specifying proxy address\n");
+ exit(-1);
+ }
+ break;
+ case 'T':
+ cmdline_token(optarg);
+ break;
+ case 'u':
+ user_length = cmdline_read_user(optarg, user, MAX_USER);
+ if (user_length >= 0)
+ user[user_length] = 0;
+ break;
+ case 'U':
+ create_uri_opts = 0;
+ break;
+ case 'v':
+ log_level = strtol(optarg, NULL, 10);
+ break;
+ case 'l':
+ if (!coap_debug_set_packet_loss(optarg)) {
+ usage(argv[0], LIBCOAP_PACKAGE_VERSION);
+ exit(1);
+ }
+ break;
+ case 'r':
+ reliable = 1;
+ break;
+ case 'K':
+ ping_seconds = atoi(optarg);
+ break;
+ case '1':
+ /* Delay before FND crts */
+ fnd_delay1 = atoi(optarg);
+ break;
+ case '2':
+ /* Delay before FND SEN1 */
+ fnd_delay2 = atoi(optarg);
+ break;
+ case '3':
+ /* Delay before FND SEN2 */
+ fnd_delay3 = atoi(optarg);
+ break;
+ default:
+ usage( argv[0], LIBCOAP_PACKAGE_VERSION );
+ exit( 1 );
+ }
+ }
+
+ /*
+ * Set up the log file with either the default established above or in the
+ * output directory established via command line argument.
+ */
+ log_file.length = strlen(output_log);
+ log_file.s = (unsigned char *)coap_malloc(log_file.length + 1);
+ if (!log_file.s) {
+ fprintf(stderr, "cannot set output file: insufficient memory\n");
+ exit(-1);
+ } else {
+ memcpy(log_file.s, output_log, log_file.length + 1);
+ }
+ /*
+ * Adding this below to use a custom log handler. Need this to output to a predictable file
+ */
+ coap_set_log_handler(perf_log_handler);
+
+ coap_startup();
+ coap_dtls_set_log_level(log_level);
+ coap_set_log_level(log_level);
+
+ /* This needs to be done to handle multiple requests */
+ if (group == 3) {
+ if (payload.length == 0) {
+ coap_log( LOG_CRIT, "No CSR specified.\n");
+ fprintf(stderr, "No CSR specified.\n");
+ exit(1);
+ }
+ len_cacerts = strlen(argv[optind]) + strlen("est/crts");
+ uri_cacerts = (char*) malloc(len_cacerts);
+ uri_cacerts = strcpy(uri_cacerts, argv[optind]);
+ uri_cacerts = strcat(uri_cacerts, "est/crts");
+ len_simple_enroll = strlen(argv[optind]) + strlen("est/sen");
+ uri_simple_enroll = (char*) malloc(len_simple_enroll);
+ uri_simple_enroll = strcpy(uri_simple_enroll, argv[optind]);
+ uri_simple_enroll = strcat(uri_simple_enroll, "est/sen");
+ /* Simple enroll needs to have content type set */
+ cmdline_content_type2(COAP_OPTION_CONTENT_TYPE);
+ } else { /* Use message_request parameter to build resource */
+ len_cacerts = strlen(argv[optind]) + strlen(message_request);
+ uri_cacerts = (char*) malloc(len_cacerts);
+ uri_cacerts = strcpy(uri_cacerts, argv[optind]);
+ uri_cacerts = strcat(uri_cacerts, message_request);
+ if (strstr(message_request,"sen") != NULL || strstr(message_request,"sren")
+ != NULL) {
+ char content_sen[4];
+ sprintf(content_sen, "%d", COAP_MEDIA_TYPE_PKCS10);
+ cmdline_content_type(content_sen, COAP_OPTION_CONTENT_TYPE);
+ }
+ }
+
+ if (optind < argc) {
+ /* Prepare the cacerts uri or the request passed in */
+ if (cmdline_uri(uri_cacerts, create_uri_opts) < 0) {
+ exit(1);
+ }
+ } else {
+ usage( argv[0], LIBCOAP_PACKAGE_VERSION );
+ exit( 1 );
+ }
+
+ /* construct CoAP message */
+ if (!proxy.length && addrptr
+ && (inet_ntop(dst.addr.sa.sa_family, addrptr, addr, sizeof(addr)) != 0)
+ && (strlen(addr) != uri.host.length
+ || memcmp(addr, uri.host.s, uri.host.length) != 0)
+ && create_uri_opts) {
+ /* add Uri-Host */
+
+ coap_insert_optlist(&optlist,
+ coap_new_optlist(COAP_OPTION_URI_HOST,
+ uri.host.length,
+ uri.host.s));
+ }
+
+ if (group == 3) {
+ /* Prepare for the simple enroll uri */
+ if (cmdline_uri2(uri_simple_enroll, create_uri_opts) < 0) {
+ exit(1);
+ }
+
+ /* If we are grouping three requests in one handshake */
+ if (!proxy.length && addrptr
+ && (inet_ntop(dst.addr.sa.sa_family, addrptr, addr, sizeof(addr)) != 0)
+ && (strlen(addr) != uri.host.length
+ || memcmp(addr, uri.host.s, uri.host.length) != 0)
+ && create_uri_opts) {
+ /* add Uri-Host */
+
+ coap_insert_optlist(&optlist2,
+ coap_new_optlist(COAP_OPTION_URI_HOST,
+ uri.host.length,
+ uri.host.s));
+ }
+ }
+
+ if ( ( user_length < 0 ) || ( key_length < 0 ) ) {
+ coap_log( LOG_CRIT, "Invalid user name or key specified\n" );
+ goto finish;
+ }
+
+ if (proxy.length) {
+ server.length = proxy.length;
+ server.s = proxy.s;
+ port = proxy_port;
+ } else {
+ server = uri.host;
+ port = uri.port;
+ }
+
+ /* resolve destination address where server should be sent */
+ res = resolve_address(&server, &dst.addr.sa);
+
+ if (res < 0) {
+ fprintf(stderr, "failed to resolve address\n");
+ exit(-1);
+ }
+
+ /* add Uri-Host if server address differs from uri.host */
+ switch (dst.addr.sa.sa_family) {
+ case AF_INET:
+ addrptr = &dst.addr.sin.sin_addr;
+ /* create context for IPv4 */
+ break;
+ case AF_INET6:
+ addrptr = &dst.addr.sin6.sin6_addr;
+ break;
+ default:
+ ;
+ }
+
+
+ for(int i = 1; i < iterations+1; i++) {
+
+
+ ctx1 = coap_new_context( NULL );
+ if ( !ctx1 ) {
+ coap_log( LOG_EMERG, "cannot create context\n" );
+ goto finish;
+ }
+
+ coap_context_set_keepalive(ctx1, ping_seconds);
+
+ dst.size = res;
+ dst.addr.sin.sin_port = htons( port );
+
+ /* Delay the start of this process */
+ if(start_delay != 0) {
+ usleep(start_delay * 1000);
+ }
+
+ coap_register_option(ctx1, COAP_OPTION_BLOCK2);
+ coap_register_response_handler(ctx1, message_handler);
+
+ if(iteration_delay != 0 && i > 0) {
+ usleep(iteration_delay * 1000);
+ }
+
+ failure = 0;
+ char file_name[80];
+
+ /* Set up the output cacert file for this iteration */
+ sprintf(file_name, "%s/%ld_%i.cacert", output_dir.s, (long)pid, i);
+ output_file.length = strlen(file_name);
+ output_file.s = (unsigned char *)coap_malloc(output_file.length + 1);
+
+ if (!output_file.s) {
+ fprintf(stderr, "cannot set output file: insufficient memory\n");
+ exit(-1);
+ } else {
+ /* copy filename including trailing zero */
+ memcpy(output_file.s, file_name, output_file.length + 1);
+ }
+
+ session = get_session(
+ ctx1,
+ node_str[0] ? node_str : NULL, port_str,
+ uri.scheme==COAP_URI_SCHEME_COAP_TCP ? COAP_PROTO_TCP :
+ uri.scheme==COAP_URI_SCHEME_COAPS_TCP ? COAP_PROTO_TLS :
+ (reliable ?
+ uri.scheme==COAP_URI_SCHEME_COAPS ? COAP_PROTO_TLS : COAP_PROTO_TCP
+ : uri.scheme==COAP_URI_SCHEME_COAPS ? COAP_PROTO_DTLS : COAP_PROTO_UDP),
+ &dst,
+ user_length > 0 ? (const char *)user : NULL,
+ key_length > 0 ? key : NULL, (unsigned)key_length
+ );
+
+ if ( !session ) {
+ coap_log( LOG_EMERG, "cannot create client session\n" );
+ goto finish;
+ }
+
+ /* This is if we are doing FND style transaction: crts/sen/sen */
+ /* FND Stage: Get CACERTS */
+ if (group == 3) {
+ /* The first request is a get for cacerts */
+ strcpy(requested_method,"get");
+ method = cmdline_method(requested_method);
+ }
+
+ /* set block option if requested at commandline */
+ if (flags & FLAGS_BLOCK)
+ set_blocksize();
+
+ if (! (pdu = coap_new_request(ctx1, session, method, &optlist, payload.s, payload.length))) {
+ goto finish;
+ }
+ gettimeofday(&start, NULL);
+#ifndef NDEBUG
+ coap_log(LOG_DEBUG, "sending CoAP request:\n");
+ if (coap_get_log_level() < LOG_DEBUG)
+ coap_show_pdu(LOG_INFO, pdu);
+#endif
+
+ wait_ms = wait_seconds * 1000;
+ coap_log(LOG_DEBUG, "timeout is set to %u seconds\n", wait_seconds);
+
+ memset (&sa, 0, sizeof(sa));
+ sigemptyset(&sa.sa_mask);
+ sa.sa_handler = handle_sigint;
+ sa.sa_flags = 0;
+ sigaction (SIGINT, &sa, NULL);
+ sigaction (SIGTERM, &sa, NULL);
+
+ /* Logging for performance */
+ coap_log(LOG_EMERG, "Timestamp start: %u\n", (unsigned)time(NULL));
+
+ /* Delay the start of the first fnd message (crts) */
+ if(fnd_delay1 != 0) {
+ usleep(fnd_delay1 * 1000);
+ }
+ coap_send(session, pdu);
+
+ while (!quit && !(ready && coap_can_exit(ctx1)) ) {
+
+ result = coap_run_once( ctx1, wait_ms == 0 ?
+ obs_ms : obs_ms == 0 ?
+ min(wait_ms, 1000) : min( wait_ms, obs_ms ) );
+
+ if ( result >= 0 ) {
+ if ( wait_ms > 0 && !wait_ms_reset ) {
+ if ( (unsigned)result >= wait_ms ) {
+ coap_log(LOG_INFO, "timeout\n");
+ failure = 1;
+ break;
+ } else {
+ wait_ms -= result;
+ }
+ }
+ if ( obs_ms > 0 && !obs_ms_reset ) {
+ if ( (unsigned)result >= obs_ms ) {
+ coap_log(LOG_DEBUG, "clear observation relationship\n" );
+ clear_obs( ctx1, session ); /* FIXME: handle error case COAP_TID_INVALID */
+
+ /* make sure that the obs timer does not fire again */
+ obs_ms = 0;
+ obs_seconds = 0;
+ } else {
+ obs_ms -= result;
+ }
+ }
+ wait_ms_reset = 0;
+ obs_ms_reset = 0;
+ }
+ }
+ coap_session_release( session );
+ coap_free_context( ctx1 );
+ coap_cleanup();
+
+ /* If this is not an FND style request, finish the iteration */
+ if(group == 1) {
+ goto finish;
+ }
+ /* Set up the output cacert file for this iteration */
+ close_output();
+
+ /* FND Stage: First Simple Enroll */
+ /* Set up the output simple enroll file for this iteration */
+ sprintf(file_name, "%s/%ld_%i.sen1", output_dir.s, (long)pid, i);
+ output_file.length = strlen(file_name);
+ output_file.s = (unsigned char *)coap_malloc(output_file.length + 1);
+
+ if (!output_file.s) {
+ fprintf(stderr, "cannot set output file: insufficient memory\n");
+ exit(-1);
+ } else {
+ /* copy filename including trailing zero */
+ memcpy(output_file.s, file_name, output_file.length + 1);
+ }
+
+ /* Create new Context to have the right BLOCK option */
+
+ ctx2 = coap_new_context( NULL );
+ if ( !ctx2 ) {
+ coap_log( LOG_EMERG, "cannot create context\n" );
+ goto finish;
+ }
+
+ coap_context_set_keepalive(ctx2, ping_seconds);
+
+ session = get_session(
+ ctx2,
+ node_str[0] ? node_str : NULL, port_str,
+ uri.scheme==COAP_URI_SCHEME_COAP_TCP ? COAP_PROTO_TCP :
+ uri.scheme==COAP_URI_SCHEME_COAPS_TCP ? COAP_PROTO_TLS :
+ (reliable ?
+ uri.scheme==COAP_URI_SCHEME_COAPS ? COAP_PROTO_TLS : COAP_PROTO_TCP
+ : uri.scheme==COAP_URI_SCHEME_COAPS ? COAP_PROTO_DTLS : COAP_PROTO_UDP),
+ &dst,
+ user_length > 0 ? (const char *)user : NULL,
+ key_length > 0 ? key : NULL, (unsigned)key_length
+ );
+
+
+ strcpy(requested_method, "post");
+ method = cmdline_method(requested_method);
+ coap_register_option(ctx2, COAP_OPTION_BLOCK1);
+ coap_register_response_handler(ctx2, message_handler_fnd_post);
+
+ if (flags & FLAGS_BLOCK) {
+ block.num=0;
+ set_blocksize_fnd_post();
+ }
+
+ if (! (pdu = coap_new_request(ctx2, session, method, &optlist2, payload.s, payload.length))) {
+ fprintf(stderr, "going to finish");
+ goto finish;
+ }
+
+ /* Delay the start of the second fnd message (first sen) */
+ if(fnd_delay2 != 0) {
+ usleep(fnd_delay2 * 1000);
+ }
+ coap_send(session, pdu);
+ wait_ms = wait_seconds * 1000;
+
+ while ( !(ready && coap_can_exit(ctx2)) ) {
+
+ result = coap_run_once( ctx2, wait_ms == 0 ?
+ obs_ms : obs_ms == 0 ?
+ min(wait_ms, 1000) : min( wait_ms, obs_ms ) );
+
+ if (result >= 0) {
+ if (wait_ms > 0 && !wait_ms_reset) {
+ if ((unsigned)result >= wait_ms) {
+ coap_log(LOG_INFO, "timeout\n");
+ failure = 1;
+ break;
+ } else {
+ wait_ms -= result;
+ }
+ }
+ if (obs_ms > 0 && !obs_ms_reset) {
+ if ((unsigned)result >= obs_ms) {
+ coap_log(LOG_DEBUG, "clear observation relationship\n" );
+ clear_obs( ctx2, session ); /* FIXME: handle error case COAP_TID_INVALID */
+
+ /* make sure that the obs timer does not fire again */
+ obs_ms = 0;
+ obs_seconds = 0;
+ } else {
+ obs_ms -= result;
+ }
+ }
+ wait_ms_reset = 0;
+ obs_ms_reset = 0;
+ }
+ }
+ close_output();
+
+ /* FND Stage: Second Simple Enroll */
+ /* Set up the output simple enroll file for this iteration */
+ sprintf(file_name, "%s/%ld_%i.sen2", output_dir.s, (long)pid, i);
+ output_file.length = strlen(file_name);
+ output_file.s = (unsigned char *)coap_malloc(output_file.length + 1);
+
+ if (!output_file.s) {
+ fprintf(stderr, "cannot set output file: insufficient memory\n");
+ exit(-1);
+ } else {
+ /* copy filename including trailing zero */
+ memcpy(output_file.s, file_name, output_file.length + 1);
+ }
+
+ /* Reset the block number since we've been using it */
+ if (flags & FLAGS_BLOCK) {
+ block.num=0;
+ }
+ if (! (pdu = coap_new_request(ctx2, session, method, &optlist2, payload.s, payload.length))) {
+ goto finish;
+ }
+
+ /* Delay the start of the third fnd message (2nd sen) */
+ if(fnd_delay3 != 0) {
+ usleep(fnd_delay3 * 1000);
+ }
+ coap_send(session, pdu);
+ wait_ms = wait_seconds * 1000;
+
+ while ( !(ready && coap_can_exit(ctx2)) ) {
+ result = coap_run_once( ctx2, wait_ms == 0 ?
+ obs_ms : obs_ms == 0 ?
+ min(wait_ms, 1000) : min( wait_ms, obs_ms ) );
+
+ if ( result >= 0 ) {
+ if ( wait_ms > 0 && !wait_ms_reset ) {
+ if ( (unsigned)result >= wait_ms ) {
+ coap_log(LOG_INFO, "timeout\n");
+ failure = 1;
+ break;
+ } else {
+ wait_ms -= result;
+ }
+ }
+ if ( obs_ms > 0 && !obs_ms_reset ) {
+ if ( (unsigned)result >= obs_ms ) {
+ coap_log(LOG_DEBUG, "clear observation relationship\n" );
+ clear_obs( ctx2, session ); /* FIXME: handle error case COAP_TID_INVALID */
+
+ /* make sure that the obs timer does not fire again */
+ obs_ms = 0;
+ obs_seconds = 0;
+ } else {
+ obs_ms -= result;
+ }
+ }
+ wait_ms_reset = 0;
+ obs_ms_reset = 0;
+ }
+ }
+ coap_session_release( session );
+ coap_free_context( ctx2 );
+
+ close_output();
+ coap_cleanup();
+
+ result = 0;
+
+ finish:
+ /* Logging for performance */
+ coap_log(LOG_EMERG, "Timestamp stop: %u\n", (unsigned)time(NULL));
+ gettimeofday(&stop, NULL);
+ start_time = start.tv_sec + start.tv_usec * .000001;
+ stop_time = stop.tv_sec + stop.tv_usec * .000001;
+ elapsed = (stop_time - start_time)*1000; /* Convert to ms as it is a more useful measurement */
+
+ if (!failure) {
+ fprintf(stdout, "Runtime for (PID:%ld, iteration:%i): %fms (%f:%f) | Delays(ms): %i %i %i\n", (long)pid, i, elapsed, start_time, stop_time,fnd_delay1,fnd_delay2,fnd_delay3);
+ coap_log(LOG_EMERG, "Runtime for (PID:%ld, iteration:%i): %fms | Delays(ms): %i %i %i\n", (long)pid, i, elapsed,fnd_delay1,fnd_delay2,fnd_delay3);
+ } else {
+ fprintf(stdout, "Runtime for (PID:%ld, iteration:%i): ***TIMEOUT***\n", (long)pid, i);
+ coap_log(LOG_EMERG, "Runtime for (PID:%ld, iteration:%i): ***TIMEOUT***\n", (long)pid, i);
+ }
+
+ } /* End iterations */
+ coap_delete_optlist(optlist);
+ coap_delete_optlist(optlist2);
+
+ close_log();
+
+ return result;
+}
diff --git a/include/coap2/coap_dtls.h b/include/coap2/coap_dtls.h
index 2f61e03..4e2a724 100644
--- a/include/coap2/coap_dtls.h
+++ b/include/coap2/coap_dtls.h
@@ -15,6 +15,13 @@
#include "coap_session.h"
#include "pdu.h"
+#if HAVE_CISCO
+#include <openssl/ssl.h>
+#include <openssl/err.h>
+#include <openssl/rand.h>
+#include <openssl/hmac.h>
+#include <openssl/x509v3.h>
+#endif
/**
* @defgroup dtls DTLS Support
* API functions for interfacing with DTLS libraries.
@@ -59,6 +66,36 @@ coap_tls_version_t *coap_get_tls_library_version(void);
struct coap_dtls_pki_t;
+#if HAVE_CISCO
+/**
+ * Security setup handler that can be used as application call-back in
+ * coap_context_set_pki().
+ * Typically, this will be calling additonal functions like
+ * SSL_CTX_set_tlsext_servername_callback() etc.
+ *
+ * @param tls_context The security context definition - e.g. SSL_CTX * for
+ * OpenSSL. This will be dependent on the underlying TLS
+ * library - see coap_get_tls_library_version()
+ * @param tls_session The security session definition - e.g. SSL * for OpenSSL.
+ * NULL if server call-back.
+ * This will be dependent on the underlying TLS library -
+ * see coap_get_tls_library_version()
+ * @param setup_data A structure containing setup data originally passed into
+ * coap_context_set_pki() or coap_new_client_session_pki().
+ *
+ * @return @c 1 if successful, else @c 0.
+ */
+/*
+ * CISCO: This is the previous call back prototype where the application is
+ * permitted to set up PKI in the SSL_CTX at init time and not on
+ * every single client hello
+ */
+typedef int (*coap_dtls_init_security_setup_t)(void *tls_context, void* tls_session,
+ struct coap_dtls_pki_t *setup_data);
+
+#define coap_dtls_timer_callback_t DTLS_timer_cb
+#endif /* CISCO */
+
/**
* Additional Security setup handler that can be set up by
* coap_context_set_pki().
@@ -131,6 +168,9 @@ typedef enum coap_asn1_privatekey_type_t {
typedef enum coap_pki_key_t {
COAP_PKI_KEY_PEM, /**< The PKI key type is PEM */
COAP_PKI_KEY_ASN1, /**< The PKI key type is ASN.1 (DER) */
+#if HAVE_CISCO
+ COAP_PKI_KEY_OSSL, /**< The PKI key type is native OpenSSL structures */
+#endif
} coap_pki_key_t;
/**
@@ -155,6 +195,19 @@ typedef struct coap_pki_key_asn1_t {
coap_asn1_privatekey_type_t private_key_type; /**< Private Key Type */
} coap_pki_key_asn1_t;
+#if HAVE_CISCO
+/**
+ * The structure that holds the OpenSSL native PKI definitions.
+ */
+typedef struct coap_pki_key_openssl_t {
+ X509_STORE *ca_certs; /**< ASN1 (DER) Common CA Cert */
+ X509 *public_cert; /**< ASN1 (DER) Public Cert */
+ EVP_PKEY *private_key; /**< ASN1 (DER) Private Key */
+ size_t public_cert_len; /**< ASN1 Public Cert length */
+ size_t private_key_len; /**< ASN1 Private Key length */
+} coap_pki_key_openssl_t;
+#endif
+
/**
* The structure that holds the PKI key information.
*/
@@ -163,6 +216,9 @@ typedef struct coap_dtls_key_t {
union {
coap_pki_key_pem_t pem; /**< for PEM keys */
coap_pki_key_asn1_t asn1; /**< for ASN.1 (DER) keys */
+#if HAVE_CISCO
+ coap_pki_key_openssl_t ossl; /**< for ASN.1 (DER) keys */
+#endif
} key;
} coap_dtls_key_t;
@@ -226,13 +282,46 @@ typedef struct coap_dtls_pki_t {
coap_dtls_sni_callback_t validate_sni_call_back;
void *sni_call_back_arg; /**< Passed in to the sni call-back function */
+#if HAVE_CISCO /* Cisco specific - the previous mechanism used */
+ /** Application Setup call-back definition, overriding libcoap's TLS call-backs.
+ * If not @p NULL, then application is handling the characteristics of the TLS
+ * connection setup in the defined call-back handler. If set, then none of
+ * the options or call-backs above are acted on.
+ * Otherwise, libcoap internally based on the selected options handles the
+ * TLS connection setup.
+ */
+ coap_dtls_init_security_setup_t app_override_tls_setup_call_back;
+ void *override_call_back_arg; /**< Passed in to the override call-back function */
+
+ /** DTLS timer call-back function.
+ * If not @p NULL, this callback function is registered with OpenSSL as the
+ * timer function to set the DTLS handshake timer value. Since it's being immediately
+ * passed to OpenSSL, we'll just alias it to the OpenSSL callback function.
+ *
+ * Unlike the other *_arg variables, this one is not going to be passed to
+ * the callback since it cannot be, the callback is being invoked from
+ * OpenSSL. Instead, we use this to allow the application (CiscoEST) to
+ * pass in the EST ctx so we can store it away in the CoAP session
+ * structure's app element. This way we can obtain addressability back to
+ * the EST context in the timer callback function.
+ */
+ coap_dtls_timer_callback_t dtls_timer_call_back;
+ void *dtls_timer_call_back_arg;
+
+ /** DTLS handshake MTU.
+ * If not @p 0, this value is used to set the DTLS handshake MTU value in
+ * CiscoSSL
+ */
+ uint16_t dtls_handshake_mtu;
+#endif /* CISCO */
+
/** Addtional Security call-back handler that is invoked when libcoap has
* done the standerd, defined validation checks at the TLS level,
* If not @p NULL, called from within the TLS Client Hello connection
* setup.
*/
coap_dtls_security_setup_t additional_tls_setup_call_back;
-
+
char* client_sni; /**< If not NULL, SNI to use in client TLS setup.
Owned by the client app and must remain valid
during the call to coap_new_client_session_pki() */
diff --git a/include/coap2/coap_io.h b/include/coap2/coap_io.h
index 2685af3..7a7a69a 100644
--- a/include/coap2/coap_io.h
+++ b/include/coap2/coap_io.h
@@ -16,7 +16,15 @@
#include "address.h"
#ifndef COAP_RXBUFFER_SIZE
+
+#if HAVE_OPENSSL && HAVE_CISCO
+/* Set buffer size to a size capable of capturing the largest DTLS packet */
+#include <openssl/ssl3.h>
+#define COAP_RXBUFFER_SIZE (SSL3_RT_MAX_PACKET_SIZE + 1)
+#else
#define COAP_RXBUFFER_SIZE 1472
+#endif /* HAVE_OPENSSL */
+
#endif /* COAP_RXBUFFER_SIZE */
#ifdef _WIN32
diff --git a/include/coap2/coap_session.h b/include/coap2/coap_session.h
index f42b206..1b4b419 100644
--- a/include/coap2/coap_session.h
+++ b/include/coap2/coap_session.h
@@ -306,7 +306,10 @@ typedef struct coap_endpoint_t {
coap_socket_t sock; /**< socket object for the interface, if any */
coap_address_t bind_addr; /**< local interface address */
coap_session_t *sessions; /**< list of active sessions */
- coap_session_t hello; /**< special session of DTLS hello messages */
+#if HAVE_CISCO
+ uint16_t session_max; /**< maximum number of active DTLS sessions */
+ uint16_t session_cnt; /**< current number of active DTLS sessions */
+#endif
} coap_endpoint_t;
/**
@@ -328,6 +331,15 @@ coap_endpoint_t *coap_new_endpoint(struct coap_context_t *context, const coap_ad
*/
void coap_endpoint_set_default_mtu(coap_endpoint_t *endpoint, unsigned mtu);
+/**
+* Set the endpoint's maximum session count. This is the maximum number of sessions at any moment
+* on this endpoint.
+*
+* @param endpoint The CoAP endpoint.
+* @param session_max maximum number of active DTLS sessions
+*/
+void coap_endpoint_set_session_max(coap_endpoint_t *ep, unsigned session_max);
+
void coap_free_endpoint(coap_endpoint_t *ep);
@@ -347,24 +359,24 @@ const char *coap_endpoint_str(const coap_endpoint_t *endpoint);
* @param endpoint Active endpoint the packet was received on.
* @param packet Received packet.
* @param now The current time in ticks.
-* @return The CoAP session.
+* @return The CoAP session or @c NULL if error.
*/
coap_session_t *coap_endpoint_get_session(coap_endpoint_t *endpoint,
const struct coap_packet_t *packet, coap_tick_t now);
/**
- * Create a new DTLS session for the @p endpoint.
+ * Create a new DTLS session for the @p session.
+ * Note: the @p session is released if no DTLS server session can be created.
*
* @ingroup dtls_internal
*
- * @param endpoint Endpoint to add DTLS session to
- * @param packet Received packet information to base session on.
+ * @param session Session to add DTLS session to
* @param now The current time in ticks.
*
- * @return Created CoAP session or @c NULL if error.
+ * @return CoAP session or @c NULL if error.
*/
-coap_session_t *coap_endpoint_new_dtls_session(coap_endpoint_t *endpoint,
- const struct coap_packet_t *packet, coap_tick_t now);
+coap_session_t *coap_session_new_dtls_session(coap_session_t *session,
+ coap_tick_t now);
coap_session_t *coap_session_get_by_peer(struct coap_context_t *ctx,
const struct coap_address_t *remote_addr, int ifindex);
@@ -384,8 +396,11 @@ void coap_session_mfree(coap_session_t *session);
* Number of seconds when to expect an ACK or a response to an
* outstanding CON message.
* RFC 7252, Section 4.8 Default value of ACK_TIMEOUT is 2
+ * In the RA FND style performance testing, it was found that
+ * an ACK_TIMEOUT of 5 is actually the optimal value and will
+ * be a baseline recommendation to start with.
*/
-#define COAP_DEFAULT_ACK_TIMEOUT ((coap_fixed_point_t){2,0})
+#define COAP_DEFAULT_ACK_TIMEOUT ((coap_fixed_point_t){5,0})
/**
* A factor that is used to randomize the wait time before a message
diff --git a/include/coap2/pdu.h b/include/coap2/pdu.h
index e84a0b3..73ae828 100644
--- a/include/coap2/pdu.h
+++ b/include/coap2/pdu.h
@@ -106,6 +106,7 @@ struct coap_session_t;
#define COAP_OPTION_PROXY_URI 35 /* C, String, 1-1034 B, (none) */
#define COAP_OPTION_PROXY_SCHEME 39 /* C, String, 1-255 B, (none) */
#define COAP_OPTION_SIZE1 60 /* E, uint, 0-4 B, (none) */
+#define COAP_MEDIA_TYPE_PKCS10 286 /* Media type used for CSRs on EST */
/* option types from RFC 7641 */
diff --git a/libcoap-2.map b/libcoap-2.map
index 584d914..a489e45 100644
--- a/libcoap-2.map
+++ b/libcoap-2.map
@@ -48,6 +48,7 @@ global:
coap_encode_var_safe;
coap_endpoint_get_session;
coap_endpoint_set_default_mtu;
+ coap_endpoint_set_session_max;
coap_endpoint_str;
coap_find_async;
coap_find_attr;
diff --git a/libcoap-2.sym b/libcoap-2.sym
index b52ce21..2d50110 100644
--- a/libcoap-2.sym
+++ b/libcoap-2.sym
@@ -46,6 +46,7 @@ coap_dtls_set_log_level
coap_encode_var_safe
coap_endpoint_get_session
coap_endpoint_set_default_mtu
+coap_endpoint_set_session_max
coap_endpoint_str
coap_find_async
coap_find_attr
diff --git a/scripts/cisco_diffs.sh b/scripts/cisco_diffs.sh
new file mode 100755
index 0000000..1d55e12
--- /dev/null
+++ b/scripts/cisco_diffs.sh
@@ -0,0 +1,47 @@
+#!/bin/bash
+
+#set -x
+
+if [ $# -ne 1 ]; then
+ echo "Usage: $0 <patch file name (e.g. libcoap.cisco_specific.1.0.0.06292019)> "
+
+ exit 1
+fi
+
+#
+# Be user friendly and compensate for being in wrong directory
+#
+pdir=`basename $PWD`
+if [ "$pdir" = "scripts" ]; then
+
+ cd ..
+ pdir=`basename $PWD`
+ if [ "$pdir" != "libcoap" ]; then
+ echo "Please run this script from libcoap/ or libcoap/scripts"
+ exit 1
+ fi
+fi
+
+#
+# Place the patch file into the top level directory
+#
+PATCHFILE=./$1.patch
+echo "Creating $PATCHFILE..."
+
+#
+# The diff generated below will include all the changes we've added to the
+# Cisco specific branch.
+#
+
+git diff origin/develop..feature/libcoap_cisco_develop | tee $PATCHFILE
+
+#
+# To adhere to PSB requirement SEC-CHK-PUBL-2, use SHA512 hashes for
+# validating downloaded software
+#
+echo "Creating SHA-512 file for $PATCHFILE..."
+openssl dgst -sha512 $PATCHFILE | tee $PATCHFILE.sha512
+
+#cat $PATCHFILE.sha512
+
+ls -l $PATCHFILE*
diff --git a/src/block.c b/src/block.c
index ed652f4..67ce236 100644
--- a/src/block.c
+++ b/src/block.c
@@ -186,8 +186,19 @@ coap_add_data_blocked_response(coap_resource_t *resource,
block2.num = 0;
block2_requested = 1;
}
+ /*
+ * PDB: In successful case, ESToCoAP states different codes
+ * for GET versus POST. CoAP was hard coding 2.05 here
+ * with no way to give 2.04, so we load the response code
+ * in the response PDU structure before calling and prevent
+ * it from being overwritten here.
+ */
+#if !HAVE_CISCO
response->code = COAP_RESPONSE_CODE(205);
-
+#else
+ coap_log(LOG_DEBUG, "coap response code = %d\n", response->code);
+#endif
+
/* add etag for the resource */
memset(etag, 0, sizeof(etag));
coap_hash(data, length, etag);
diff --git a/src/coap_gnutls.c b/src/coap_gnutls.c
index 8f94091..447349c 100644
--- a/src/coap_gnutls.c
+++ b/src/coap_gnutls.c
@@ -1173,11 +1173,9 @@ coap_dtls_free_gnutls_env(coap_gnutls_context_t *g_context,
void *coap_dtls_new_server_session(coap_session_t *c_session) {
coap_gnutls_env_t *g_env =
- (coap_gnutls_env_t *)c_session->endpoint->hello.tls;
+ (coap_gnutls_env_t *)c_session->tls;
gnutls_transport_set_ptr(g_env->g_session, c_session);
- /* For the next one */
- c_session->endpoint->hello.tls = NULL;
return g_env;
}
@@ -1277,6 +1275,7 @@ void coap_dtls_free_session(coap_session_t *c_session) {
coap_dtls_free_gnutls_env(c_session->context->dtls_context,
c_session->tls, COAP_PROTO_NOT_RELIABLE(c_session->proto));
c_session->tls = NULL;
+ coap_handle_event(c_session->context, COAP_EVENT_DTLS_CLOSED, c_session);
}
}
@@ -1716,7 +1715,9 @@ ssize_t coap_tls_read(coap_session_t *c_session,
}
if (c_session->dtls_event >= 0) {
- coap_handle_event(c_session->context, c_session->dtls_event, c_session);
+ /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */
+ if (c_session->dtls_event != COAP_EVENT_DTLS_CLOSED)
+ coap_handle_event(c_session->context, c_session->dtls_event, c_session);
if (c_session->dtls_event == COAP_EVENT_DTLS_ERROR ||
c_session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
coap_session_disconnected(c_session, COAP_NACK_TLS_FAILED);
diff --git a/src/coap_io.c b/src/coap_io.c
index 37ecbf0..ab3fcf5 100644
--- a/src/coap_io.c
+++ b/src/coap_io.c
@@ -94,7 +94,6 @@ struct coap_endpoint_t *
void
coap_mfree_endpoint(struct coap_endpoint_t *ep) {
ep_initialized = 0;
- coap_session_mfree(&ep->hello);
}
int
@@ -184,7 +183,6 @@ struct coap_endpoint_t *
void
coap_mfree_endpoint(struct coap_endpoint_t *ep) {
- coap_session_mfree(&ep->hello);
coap_free_type(COAP_ENDPOINT, ep);
}
@@ -243,12 +241,28 @@ coap_socket_bind_udp(coap_socket_t *sock,
break;
}
- if (bind(sock->fd, &listen_addr->addr.sa, listen_addr->size) == COAP_SOCKET_ERROR) {
- coap_log(LOG_WARNING, "coap_socket_bind_udp: bind: %s\n",
- coap_socket_strerror());
- goto error;
+#if HAVE_CISCO
+ /*
+ * In EST/RA we pass in a port number to allow the init processing to
+ * continue as normal but what will actually happen is the RA/EST code will
+ * swap in the actual file descriptor/port from which to read, causing this
+ * port here to never be processed and effectively dead. CiscoRA was
+ * setting this port here to the default for CoAP, 5683, and this is causing
+ * conflicts for FND, so now RA will pass in 0. This logic is still needed when
+ * built with estserver/estproxy, so now only bind the port if the port num is
+ * something other than 0.
+ */
+ if (listen_addr->addr.sin.sin_port != 0x0) {
+#endif
+ if (bind(sock->fd, &listen_addr->addr.sa, listen_addr->size) == COAP_SOCKET_ERROR) {
+ coap_log(LOG_WARNING, "coap_socket_bind_udp: bind: %s\n",
+ coap_socket_strerror());
+ goto error;
+ }
+#if HAVE_CISCO
}
-
+#endif
+
bound_addr->size = (socklen_t)sizeof(*bound_addr);
if (getsockname(sock->fd, &bound_addr->addr.sa, &bound_addr->size) < 0) {
coap_log(LOG_WARNING,
@@ -1057,6 +1071,13 @@ coap_network_read(coap_socket_t *sock, coap_packet_t *packet) {
}
#endif /* IP_PKTINFO */
}
+#if HAVE_CISCO
+ /* Cisco specific change. If the stack is dirty, ifindex will not be 0
+ * initially. Insure that it is */
+ if (!CMSG_FIRSTHDR(&mhdr)) {
+ packet->ifindex = 0;
+ }
+#endif
}
#endif /* !defined(WITH_CONTIKI) */
#ifdef WITH_CONTIKI
diff --git a/src/coap_openssl.c b/src/coap_openssl.c
index 0547a23..d11e116 100644
--- a/src/coap_openssl.c
+++ b/src/coap_openssl.c
@@ -68,6 +68,37 @@
#define TLSEXT_TYPE_server_certificate_type 20
#endif
+#if HAVE_CISCO
+/* Cisco PSV SEC_CRY_PRIM4 Required Ciphers */
+#define SEC_CRY_PRIM_4_CIPHER_LIST "ECDHE-ECDSA-AES128-GCM-SHA256:\
+ECDHE-RSA-AES128-GCM-SHA256:\
+AES128-GCM-SHA256:\
+ECDHE-ECDSA-CHACHA20-POLY1305:\
+ECDHE-RSA-CHACHA20-POLY1305:\
+ECDHE-ECDSA-AES128-SHA256:\
+ECDHE-ECDSA-AES128-SHA:\
+ECDHE-RSA-AES128-SHA:\
+ECDHE-RSA-AES128-SHA256:\
+AES128-SHA256:\
+AES128-SHA:\
+ECDHE-ECDSA-AES256-GCM-SHA384:\
+ECDHE-RSA-AES256-GCM-SHA384:\
+AES256-GCM-SHA384:\
+ECDHE-ECDSA-AES256-SHA384:\
+ECDHE-RSA-AES256-SHA384:\
+AES256-SHA256:\
+DHE-RSA-AES128-GCM-SHA256:\
+DHE-RSA-AES128-SHA:\
+DHE-RSA-AES128-SHA256:\
+DHE-RSA-AES256-GCM-SHA384:\
+DHE-DSS-AES256-GCM-SHA384:\
+DHE-RSA-AES256-SHA256:\
+DHE-DSS-AES128-GCM-SHA256:\
+DHE-DSS-AES128-SHA:\
+DHE-DSS-AES128-SHA256:\
+DHE-DSS-AES256-SHA256:\
+ECDHE-ECDSA-AES128-CCM8" /* This Cipher is required by EST CoAPs */
+#endif /* HAVE_CISCO */
/* This structure encapsulates the OpenSSL context object. */
typedef struct coap_dtls_context_t {
SSL_CTX *ctx;
@@ -103,6 +134,19 @@ typedef struct coap_openssl_context_t {
sni_entry *sni_entry_list;
} coap_openssl_context_t;
+#if HAVE_CISCO
+/*
+ * Hold onto the MTU to be used during the DTLS handshake phase of
+ * a connection. By default, we just let it be the default value that
+ * libcoap wants to use. But, this can be overridden below when CiscoEST
+ * calls in and has a specific MTU value. Normally, using a global in this way
+ * is bad due to multithreading issues. In this case the intention is for
+ * all connections to use this MTU during the DTLS handshake, so there's
+ * no real need to maintain a context specific setting.
+ */
+static int dtls_handshake_mtu = COAP_DEFAULT_MTU;
+#endif
+
int coap_dtls_is_supported(void) {
if (SSLeay() < 0x10100000L) {
coap_log(LOG_WARNING, "OpenSSL version 1.1.0 or later is required\n");
@@ -504,6 +548,14 @@ void *coap_dtls_new_context(struct coap_context_t *coap_context) {
SSL_CTX_set_app_data(context->dtls.ctx, &context->dtls);
SSL_CTX_set_read_ahead(context->dtls.ctx, 1);
SSL_CTX_set_cipher_list(context->dtls.ctx, "TLSv1.2:TLSv1.0");
+#if HAVE_CISCO
+ /*
+ * As part of the Cisco PSB we require a stricter set of ciphers to use
+ * during a DTLS connection and thus this call to set ciphers is
+ * required
+ */
+ SSL_CTX_set_cipher_list(context->dtls.ctx, SEC_CRY_PRIM_4_CIPHER_LIST);
+#endif
if (!RAND_bytes(cookie_secret, (int)sizeof(cookie_secret))) {
if (dtls_log_level >= LOG_WARNING)
coap_log(LOG_WARNING,
@@ -537,6 +589,13 @@ void *coap_dtls_new_context(struct coap_context_t *coap_context) {
SSL_CTX_set_app_data(context->tls.ctx, &context->tls);
SSL_CTX_set_min_proto_version(context->tls.ctx, TLS1_VERSION);
SSL_CTX_set_cipher_list(context->tls.ctx, "TLSv1.2:TLSv1.0");
+#if HAVE_CISCO
+ /*
+ * As part of the Cisco PSB we require a stricter set of ciphers to use
+ * during a TLS connection and thus this call to set ciphers is required
+ */
+ SSL_CTX_set_cipher_list(context->tls.ctx, SEC_CRY_PRIM_4_CIPHER_LIST);
+#endif
SSL_CTX_set_info_callback(context->tls.ctx, coap_dtls_info_callback);
context->tls.meth = BIO_meth_new(BIO_TYPE_SOCKET, "coapsock");
if (!context->tls.meth)
@@ -684,9 +743,12 @@ setup_pki_server(SSL_CTX *ctx,
}
}
else {
+#if !HAVE_CISCO
+/* Cisco specific: prevent error return to allow setup_pki_server to complete */
coap_log(LOG_ERR,
"*** setup_pki: (D)TLS: No Server Certificate defined\n");
return 0;
+#endif
}
if (setup_data->pki_key.key.pem.private_key &&
@@ -702,9 +764,12 @@ setup_pki_server(SSL_CTX *ctx,
}
}
else {
+#if !HAVE_CISCO
+/* Cisco specific: prevent error return to allow setup_pki_server to complete */
coap_log(LOG_ERR,
"*** setup_pki: (D)TLS: No Server Private Key defined\n");
return 0;
+#endif
}
if (setup_data->pki_key.key.pem.ca_file &&
@@ -718,11 +783,13 @@ setup_pki_server(SSL_CTX *ctx,
if (cert_names != NULL)
SSL_CTX_set_client_CA_list(ctx, cert_names);
else {
+#if !HAVE_CISCO
+/* Cisco specific: prevent error return to allow setup_pki_server to complete */
coap_log(LOG_WARNING,
- "*** setup_pki: (D)TLS: %s: Unable to configure "
- "client CA File\n",
+ "*** setup_pki: (D)TLS: %s: Unable to configure client CA File\n",
setup_data->pki_key.key.pem.ca_file);
return 0;
+#endif
}
st = SSL_CTX_get_cert_store(ctx);
in = BIO_new(BIO_s_file());
@@ -758,9 +825,12 @@ setup_pki_server(SSL_CTX *ctx,
}
}
else {
+#if !HAVE_CISCO
+/* Cisco specific: prevent error return to allow setup_pki_server to complete */
coap_log(LOG_ERR,
"*** setup_pki: (D)TLS: No Server Certificate defined\n");
return 0;
+#endif
}
if (setup_data->pki_key.key.asn1.private_key &&
@@ -801,6 +871,59 @@ setup_pki_server(SSL_CTX *ctx,
X509_free(x509);
}
break;
+#if HAVE_CISCO
+ case COAP_PKI_KEY_OSSL:
+ /*
+ * First load the ID cert for the server
+ */
+ if (setup_data->pki_key.key.ossl.public_cert) {
+ if (!(SSL_CTX_use_certificate(ctx, setup_data->pki_key.key.ossl.public_cert))) {
+ coap_log(LOG_WARNING,
+ "*** setup_pki: (D)TLS: %s: Unable to configure "
+ "Server Certificate\n",
+ "OpenSSL defined structures");
+ return 0;
+ }
+ }
+ else {
+ coap_log(LOG_ERR,
+ "*** setup_pki: (D)TLS: No Server Certificate defined\n");
+ return 0;
+ }
+
+ /*
+ * Then load the private key
+ */
+ if (setup_data->pki_key.key.ossl.private_key) {
+ if (!(SSL_CTX_use_PrivateKey(ctx, setup_data->pki_key.key.ossl.private_key))) {
+ coap_log(LOG_WARNING,
+ "*** setup_pki: (D)TLS: %s: Unable to configure "
+ "Server Private Key\n",
+ "OpenSSL defined structures");
+ return 0;
+ }
+ }
+ else {
+ coap_log(LOG_ERR,
+ "*** setup_pki: (D)TLS: No Server Private Key defined\n");
+ return 0;
+ }
+
+ /*
+ * And finally, the CA certs used when building the cert chain during handshaking
+ */
+ if (setup_data->pki_key.key.ossl.ca_certs) {
+ SSL_CTX_set_cert_store(ctx, setup_data->pki_key.key.ossl.ca_certs);
+ }
+ else {
+ coap_log(LOG_WARNING,
+ "*** setup_pki: (D)TLS: %s: %s: Unable to configure "
+ "client CA File\n",
+ "OpenSSL defined structures", setup_data->pki_key.key.pem.ca_file);
+ return 0;
+ }
+ break;
+#endif
default:
coap_log(LOG_ERR,
"*** setup_pki: (D)TLS: Unknown key type %d\n",
@@ -955,6 +1078,73 @@ setup_pki_ssl(SSL *ssl,
X509_free(x509);
}
break;
+#if HAVE_CISCO
+ case COAP_PKI_KEY_OSSL:
+ /*
+ * First load the ID cert for the server
+ */
+ if (setup_data->pki_key.key.ossl.public_cert) {
+ if (!(SSL_use_certificate(ssl, setup_data->pki_key.key.ossl.public_cert))) {
+ coap_log(LOG_WARNING,
+ "*** setup_pki: (D)TLS: %s: Unable to configure "
+ "Client Certificate\n",
+ "OpenSSL defined structures");
+ return 0;
+ }
+ }
+ else {
+ coap_log(LOG_ERR,
+ "*** setup_pki: (D)TLS: No Client Certificate defined\n");
+ return 0;
+ }
+
+ /*
+ * Then load the private key
+ */
+ if (setup_data->pki_key.key.ossl.private_key) {
+ if (!(SSL_use_PrivateKey(ssl, setup_data->pki_key.key.ossl.private_key))) {
+ coap_log(LOG_WARNING,
+ "*** setup_pki: (D)TLS: %s: Unable to configure "
+ "Client Private Key\n",
+ "OpenSSL defined structures");
+ return 0;
+ }
+ }
+ else {
+ coap_log(LOG_ERR,
+ "*** setup_pki: (D)TLS: No Client Private Key defined\n");
+ return 0;
+ }
+
+ /*
+ * And finally, the CA certs used when building the cert chain during handshaking
+ */
+ if (setup_data->pki_key.key.ossl.ca_certs) {
+
+ if (!SSL_set1_verify_cert_store(ssl, setup_data->pki_key.key.ossl.ca_certs)) {
+ /*
+ * something went wrong
+ */
+ coap_log(LOG_ERR, "*** setup_pki: (D)TLS: Failed to set the X509 store"
+ " for verification.\n");
+ return 0;
+ }
+ if (!SSL_set1_chain_cert_store(ssl, setup_data->pki_key.key.ossl.ca_certs)) {
+ /*
+ * something went wrong
+ */
+ coap_log(LOG_ERR, "*** setup_pki: (D)TLS: Failed to set the X509 store"
+ " for chain building when handshaking.\n");
+ return 0;
+ }
+ } else {
+ coap_log(LOG_ERR,
+ "*** setup_pki: (D)TLS: No CA certs defined\n");
+ return 0;
+ }
+
+ break;
+#endif
default:
coap_log(LOG_ERR,
"*** setup_pki: (D)TLS: Unknown key type %d\n",
@@ -1186,7 +1376,13 @@ tls_secret_call_back(SSL *ssl,
/*
* Force a PSK algorithm to be used, so we do PSK
*/
+#if !HAVE_CISCO
+ /*
+ * As part of the Cisco PSB we require a stricter set of ciphers which does
+ * not include any PSK ciphers and thus this call must be removed
+ */
SSL_set_cipher_list (ssl, "PSK:!NULL");
+#endif
SSL_set_psk_server_callback(ssl, coap_dtls_psk_server_callback);
}
if (setup_data->additional_tls_setup_call_back) {
@@ -1249,6 +1445,14 @@ tls_server_name_call_back(SSL *ssl,
SSL_CTX_set_app_data(ctx, &context->dtls);
SSL_CTX_set_read_ahead(ctx, 1);
SSL_CTX_set_cipher_list(ctx, "TLSv1.2:TLSv1.0");
+#if HAVE_CISCO
+ /*
+ * As part of the Cisco PSB we require a stricter set of ciphers to use
+ * during a DTLS connection and thus this call to set ciphers is
+ * required
+ */
+ SSL_CTX_set_cipher_list(ctx, SEC_CRY_PRIM_4_CIPHER_LIST);
+#endif
SSL_CTX_set_cookie_generate_cb(ctx, coap_dtls_generate_cookie);
SSL_CTX_set_cookie_verify_cb(ctx, coap_dtls_verify_cookie);
SSL_CTX_set_info_callback(ctx, coap_dtls_info_callback);
@@ -1262,6 +1466,13 @@ tls_server_name_call_back(SSL *ssl,
SSL_CTX_set_app_data(ctx, &context->tls);
SSL_CTX_set_min_proto_version(ctx, TLS1_VERSION);
SSL_CTX_set_cipher_list(ctx, "TLSv1.2:TLSv1.0");
+#if HAVE_CISCO
+ /*
+ * As part of the Cisco PSB we require a stricter set of ciphers to use
+ * during a TLS connection and thus this call to set ciphers is required
+ */
+ SSL_CTX_set_cipher_list(ctx, SEC_CRY_PRIM_4_CIPHER_LIST);
+#endif
SSL_CTX_set_info_callback(ctx, coap_dtls_info_callback);
SSL_CTX_set_alpn_select_cb(ctx, server_alpn_callback, NULL);
}
@@ -1269,6 +1480,9 @@ tls_server_name_call_back(SSL *ssl,
sni_setup_data.pki_key.key_type = new_entry->key_type;
sni_setup_data.pki_key.key.pem = new_entry->key.pem;
sni_setup_data.pki_key.key.asn1 = new_entry->key.asn1;
+#if HAVE_CISCO
+ sni_setup_data.pki_key.key.ossl = new_entry->key.ossl;
+#endif
setup_pki_server(ctx, &sni_setup_data);
context->sni_entry_list = OPENSSL_realloc(context->sni_entry_list,
@@ -1496,6 +1710,21 @@ is_x509:
if (!setup_data->additional_tls_setup_call_back(ssl, setup_data))
return 0;
}
+
+#if HAVE_CISCO
+ /*
+ * If the application layer has registered a dtls timer callback function,
+ * and in the case of EST it will have, then register it now with OpenSSL.
+ * For CiscoEST, we also know that the arg value is the EST ctx. Set this
+ * into the CoAP session structure so that we can walk our way back to it from
+ * the SSL structure.
+ */
+ if (setup_data->dtls_timer_call_back) {
+ DTLS_set_timer_cb(ssl, setup_data->dtls_timer_call_back);
+ coap_session_set_app_data(session, setup_data->dtls_timer_call_back_arg);
+ }
+#endif
+
return SSL_CLIENT_HELLO_SUCCESS;
}
#endif /* OPENSSL_VERSION_NUMBER >= 0x10101000L */
@@ -1525,16 +1754,47 @@ coap_dtls_context_set_pki(coap_context_t *ctx,
* which is not in 1.1.0
*/
#if OPENSSL_VERSION_NUMBER < 0x10101000L
- if (SSLeay() >= 0x10101000L) {
- coap_log(LOG_WARNING,
- "OpenSSL compiled with %lux, linked with %lux, so "
- "no certificate checking\n",
- OPENSSL_VERSION_NUMBER, SSLeay());
+#if HAVE_CISCO
+ /*
+ * Cisco: Go back to the implementation where the application gets a chance to set
+ * up the PKI mode at init time by being invoked with the context structure. We will
+ * load the private key, certificate, and trust store from the OpenSSL structures we have
+ * since we don't have files to
+ */
+ if (setup_data->app_override_tls_setup_call_back) {
+ /* Application wants to be in total control */
+ if (!setup_data->app_override_tls_setup_call_back(context->dtls.ctx,
+ NULL, setup_data))
+ return 0;
+ } else
+#endif /* CISCO */
+ {
+ if (SSLeay() >= 0x10101000L) {
+ coap_log(LOG_WARNING,
+ "OpenSSL compiled with %lux, linked with %lux, so "
+ "no certificate checking\n",
+ OPENSSL_VERSION_NUMBER, SSLeay());
+ }
+ SSL_CTX_set_tlsext_servername_arg(context->dtls.ctx, &context->setup_data);
+ SSL_CTX_set_tlsext_servername_callback(context->dtls.ctx,
+ tls_server_name_call_back);
}
- SSL_CTX_set_tlsext_servername_arg(context->dtls.ctx, &context->setup_data);
- SSL_CTX_set_tlsext_servername_callback(context->dtls.ctx,
- tls_server_name_call_back);
#else /* OPENSSL_VERSION_NUMBER >= 0x10101000L */
+#if HAVE_CISCO
+ /*
+ * Cisco: Go back to the implementation where the application gets a chance to set
+ * up the PKI mode at init time by being invoked with the context structure. We will
+ * load the private key, certificate, and trust store from the OpenSSL structures we have
+ * since we don't have files to
+ */
+ if (setup_data->app_override_tls_setup_call_back) {
+ /* Application wants to be in total control */
+ if (!setup_data->app_override_tls_setup_call_back(context->dtls.ctx,
+ NULL, setup_data))
+ return 0;
+ }
+#endif /* CISCO */
+
SSL_CTX_set_client_hello_cb(context->dtls.ctx,
tls_client_hello_call_back,
NULL);
@@ -1586,7 +1846,25 @@ coap_dtls_context_set_pki(coap_context_t *ctx,
SSL_set_bio(context->dtls.ssl, bio, bio);
SSL_set_app_data(context->dtls.ssl, NULL);
SSL_set_options(context->dtls.ssl, SSL_OP_COOKIE_EXCHANGE);
+#if HAVE_CISCO
+ /*
+ * If we're in Cisco EST mode we need to provide a way to limit the MTU
+ * during DTLS handshake phase. This value is being passed in from
+ * CiscoEST. I suspect the actual setting of the MTU in OpenSSL here is
+ * not really achieving anything but is being done because the existing
+ * code is doing it. What seemed to really work was to set this global
+ * static here and then make the call when the client hello is processed
+ * in coap_dtls_hello().
+ */
+ if (setup_data->dtls_handshake_mtu) {
+ dtls_handshake_mtu = setup_data->dtls_handshake_mtu;
+ SSL_set_mtu(context->dtls.ssl, setup_data->dtls_handshake_mtu);
+ } else {
+ SSL_set_mtu(context->dtls.ssl, COAP_DEFAULT_MTU);
+ }
+#else
SSL_set_mtu(context->dtls.ssl, COAP_DEFAULT_MTU);
+#endif
}
context->psk_pki_enabled |= IS_PKI;
return 1;
@@ -1716,7 +1994,13 @@ setup_client_ssl_session(coap_session_t *session, SSL *ssl
if (context->psk_pki_enabled & IS_PSK) {
SSL_set_psk_client_callback(ssl, coap_dtls_psk_client_callback);
SSL_set_psk_server_callback(ssl, coap_dtls_psk_server_callback);
+#if !HAVE_CISCO
+ /*
+ * As part of the Cisco PSB we require a stricter set of ciphers which does
+ * not include any PSK ciphers and thus this call must be removed
+ */
SSL_set_cipher_list(ssl, "PSK:!NULL");
+#endif
}
if (context->psk_pki_enabled & IS_PKI) {
coap_dtls_pki_t *setup_data = &context->setup_data;
@@ -1815,6 +2099,8 @@ void coap_dtls_free_session(coap_session_t *session) {
}
SSL_free(ssl);
session->tls = NULL;
+ if (session->context)
+ coap_handle_event(session->context, COAP_EVENT_DTLS_CLOSED, session);
}
}
@@ -1843,7 +2129,9 @@ int coap_dtls_send(coap_session_t *session,
}
if (session->dtls_event >= 0) {
- coap_handle_event(session->context, session->dtls_event, session);
+ /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */
+ if (session->dtls_event != COAP_EVENT_DTLS_CLOSED)
+ coap_handle_event(session->context, session->dtls_event, session);
if (session->dtls_event == COAP_EVENT_DTLS_ERROR ||
session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
coap_session_disconnected(session, COAP_NACK_TLS_FAILED);
@@ -1890,7 +2178,11 @@ int coap_dtls_hello(coap_session_t *session,
coap_ssl_data *ssl_data;
int r;
+#if HAVE_CISCO
+ SSL_set_mtu(dtls->ssl, dtls_handshake_mtu);
+#else
SSL_set_mtu(dtls->ssl, session->mtu);
+#endif
ssl_data = (coap_ssl_data*)BIO_get_data(SSL_get_rbio(dtls->ssl));
ssl_data->session = session;
ssl_data->pdu = data;
@@ -1944,7 +2236,9 @@ int coap_dtls_receive(coap_session_t *session,
r = -1;
}
if (session->dtls_event >= 0) {
- coap_handle_event(session->context, session->dtls_event, session);
+ /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */
+ if (session->dtls_event != COAP_EVENT_DTLS_CLOSED)
+ coap_handle_event(session->context, session->dtls_event, session);
if (session->dtls_event == COAP_EVENT_DTLS_ERROR ||
session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
coap_session_disconnected(session, COAP_NACK_TLS_FAILED);
@@ -2116,6 +2410,8 @@ void coap_tls_free_session(coap_session_t *session) {
}
SSL_free(ssl);
session->tls = NULL;
+ if (session->context)
+ coap_handle_event(session->context, COAP_EVENT_DTLS_CLOSED, session);
}
}
@@ -2160,7 +2456,9 @@ ssize_t coap_tls_write(coap_session_t *session,
}
if (session->dtls_event >= 0) {
- coap_handle_event(session->context, session->dtls_event, session);
+ /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */
+ if (session->dtls_event != COAP_EVENT_DTLS_CLOSED)
+ coap_handle_event(session->context, session->dtls_event, session);
if (session->dtls_event == COAP_EVENT_DTLS_ERROR ||
session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
coap_session_disconnected(session, COAP_NACK_TLS_FAILED);
@@ -2209,7 +2507,9 @@ ssize_t coap_tls_read(coap_session_t *session,
}
if (session->dtls_event >= 0) {
- coap_handle_event(session->context, session->dtls_event, session);
+ /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */
+ if (session->dtls_event != COAP_EVENT_DTLS_CLOSED)
+ coap_handle_event(session->context, session->dtls_event, session);
if (session->dtls_event == COAP_EVENT_DTLS_ERROR ||
session->dtls_event == COAP_EVENT_DTLS_CLOSED) {
coap_session_disconnected(session, COAP_NACK_TLS_FAILED);
diff --git a/src/coap_session.c b/src/coap_session.c
index aeee47a..a772139 100644
--- a/src/coap_session.c
+++ b/src/coap_session.c
@@ -101,6 +101,17 @@ coap_make_session(coap_proto_t proto, coap_session_type_t type,
const coap_address_t *local_if, const coap_address_t *local_addr,
const coap_address_t *remote_addr, int ifindex, coap_context_t *context,
coap_endpoint_t *endpoint) {
+
+#if HAVE_CISCO
+ /*
+ * If we've met the maximum number of active sessions, then just return
+ * and prevent a new session from starting.
+ */
+ if (endpoint != NULL && endpoint->session_cnt >= endpoint->session_max) {
+ return (NULL);
+ }
+#endif
+
coap_session_t *session = (coap_session_t*)coap_malloc_type(COAP_SESSION, sizeof(coap_session_t));
if (!session)
return NULL;
@@ -141,6 +152,11 @@ coap_make_session(coap_proto_t proto, coap_session_type_t type,
/* initialize message id */
prng((unsigned char *)&session->tx_mid, sizeof(session->tx_mid));
+#if HAVE_CISCO
+if(endpoint != NULL)
+ endpoint->session_cnt++;
+#endif
+
return session;
}
@@ -183,7 +199,13 @@ void coap_session_free(coap_session_t *session) {
coap_session_mfree(session);
coap_log(LOG_DEBUG, "***%s: session closed\n", coap_session_str(session));
- coap_free_type(COAP_SESSION, session);
+#if HAVE_CISCO
+ if (session->endpoint) {
+ session->endpoint->session_cnt--;
+ }
+#endif
+
+ coap_free_type(COAP_SESSION, session);
}
size_t coap_session_max_pdu_size(coap_session_t *session) {
@@ -452,8 +474,6 @@ coap_endpoint_get_session(coap_endpoint_t *endpoint,
coap_session_t *oldest = NULL;
coap_session_t *oldest_hs = NULL;
- endpoint->hello.ifindex = -1;
-
LL_FOREACH(endpoint->sessions, session) {
if (session->ifindex == packet->ifindex &&
coap_address_equals(&session->local_addr, &packet->dst) &&
@@ -462,15 +482,33 @@ coap_endpoint_get_session(coap_endpoint_t *endpoint,
session->last_rx_tx = now;
return session;
}
- if (session->ref == 0 && session->delayqueue == NULL &&
- session->type == COAP_SESSION_TYPE_SERVER) {
- ++num_idle;
- if (oldest==NULL || session->last_rx_tx < oldest->last_rx_tx)
- oldest = session;
-
- if (session->state == COAP_SESSION_STATE_HANDSHAKE) {
+
+ if (session->ref == 0 && session->delayqueue == NULL) {
+#if !HAVE_CISCO
+ if (session->type == COAP_SESSION_TYPE_SERVER) {
+#else
+ if ((session->type == COAP_SESSION_TYPE_SERVER) &&
+ /* prevent sessions from being dropped for the first 10 seconds */
+ session->last_rx_tx+10000 < now) {
+#endif
+ ++num_idle;
+ if (oldest==NULL || session->last_rx_tx < oldest->last_rx_tx)
+ oldest = session;
+
+ if (session->state == COAP_SESSION_STATE_HANDSHAKE) {
+ ++num_hs;
+ /* See if this is a partial (D)TLS session set up
+ which needs to be cleared down to prevent DOS */
+ if ((session->last_rx_tx + COAP_PARTIAL_SESSION_TIMEOUT_TICKS) < now) {
+ if (oldest_hs == NULL ||
+ session->last_rx_tx < oldest_hs->last_rx_tx)
+ oldest_hs = session;
+ }
+ }
+ }
+ else if (session->type == COAP_SESSION_TYPE_HELLO) {
++num_hs;
- /* See if this is a partial SSL session set up
+ /* See if this is a partial (D)TLS session set up for Client Hello
which needs to be cleared down to prevent DOS */
if ((session->last_rx_tx + COAP_PARTIAL_SESSION_TIMEOUT_TICKS) < now) {
if (oldest_hs == NULL ||
@@ -483,6 +521,10 @@ coap_endpoint_get_session(coap_endpoint_t *endpoint,
if (endpoint->context->max_idle_sessions > 0 &&
num_idle >= endpoint->context->max_idle_sessions) {
+#if HAVE_CISCO
+ coap_log(LOG_WARNING, "***%s: Established DTLS session timed out\n",
+ coap_session_str(oldest));
+#endif
coap_session_free(oldest);
}
else if (oldest_hs) {
@@ -494,7 +536,7 @@ coap_endpoint_get_session(coap_endpoint_t *endpoint,
if (num_hs > (endpoint->context->max_handshake_sessions ?
endpoint->context->max_handshake_sessions :
COAP_DEFAULT_MAX_HANDSHAKE_SESSIONS)) {
- /* Maxed out on number of session in SSL negotiation state */
+ /* Maxed out on number of sessions in (D)TLS negotiation state */
coap_log(LOG_DEBUG,
"Oustanding sessions in COAP_SESSION_STATE_HANDSHAKE too "
"large. New request ignored\n");
@@ -502,42 +544,80 @@ coap_endpoint_get_session(coap_endpoint_t *endpoint,
}
if (endpoint->proto == COAP_PROTO_DTLS) {
- session = &endpoint->hello;
- coap_address_copy(&session->local_addr, &packet->dst);
- coap_address_copy(&session->remote_addr, &packet->src);
- session->ifindex = packet->ifindex;
- } else {
- session = coap_make_session(endpoint->proto, COAP_SESSION_TYPE_SERVER,
- NULL, &packet->dst, &packet->src, packet->ifindex, endpoint->context,
- endpoint);
- if (session) {
- session->last_rx_tx = now;
- if (endpoint->proto == COAP_PROTO_UDP)
- session->state = COAP_SESSION_STATE_ESTABLISHED;
- LL_PREPEND(endpoint->sessions, session);
- coap_log(LOG_DEBUG, "***%s: new incoming session\n",
- coap_session_str(session));
+ /*
+ * Need to check that this actually is a Client Hello before wasting
+ * time allocating and then freeing off session.
+ */
+
+ /*
+ * Generic header structure of the DTLS record layer.
+ * typedef struct __attribute__((__packed__)) {
+ * uint8_t content_type; content type of the included message
+ * uint16_t version; Protocol version
+ * uint16_t epoch; counter for cipher state changes
+ * uint8_t sequence_number[6]; sequence number
+ * uint16_t length; length of the following fragment
+ * uint8_t handshake; If content_type == DTLS_CT_HANDSHAKE
+ * } dtls_record_handshake_t;
+ */
+#define OFF_CONTENT_TYPE 0 /* offset of content_type in dtls_record_handshake_t */
+#define DTLS_CT_ALERT 21 /* Content Type Alert */
+#define DTLS_CT_HANDSHAKE 22 /* Content Type Handshake */
+#define OFF_HANDSHAKE_TYPE 13 /* offset of handshake in dtls_record_handshake_t */
+#define DTLS_HT_CLIENT_HELLO 1 /* Client Hello handshake type */
+
+#ifdef WITH_LWIP
+ const uint8_t *payload = (const uint8_t*)packet->pbuf->payload;
+ size_t length = packet->pbuf->len;
+#else /* ! WITH_LWIP */
+ const uint8_t *payload = (const uint8_t*)packet->payload;
+ size_t length = packet->length;
+#endif /* ! WITH_LWIP */
+ if (length < (OFF_HANDSHAKE_TYPE + 1)) {
+ coap_log(LOG_DEBUG,
+ "coap_dtls_hello: ContentType %d Short Packet (%ld < %d) dropped\n",
+ payload[OFF_CONTENT_TYPE], length,
+ OFF_HANDSHAKE_TYPE + 1);
+ return NULL;
}
+ if (payload[OFF_CONTENT_TYPE] != DTLS_CT_HANDSHAKE ||
+ payload[OFF_HANDSHAKE_TYPE] != DTLS_HT_CLIENT_HELLO) {
+ /* only log if not a late alert */
+ if (payload[OFF_CONTENT_TYPE] != DTLS_CT_ALERT)
+ coap_log(LOG_DEBUG,
+ "coap_dtls_hello: ContentType %d Handshake %d dropped\n",
+ payload[OFF_CONTENT_TYPE], payload[OFF_HANDSHAKE_TYPE]);
+ return NULL;
+ }
+ }
+
+ session = coap_make_session(endpoint->proto, COAP_SESSION_TYPE_SERVER,
+ NULL, &packet->dst, &packet->src, packet->ifindex, endpoint->context,
+ endpoint);
+ if (session) {
+ session->last_rx_tx = now;
+ if (endpoint->proto == COAP_PROTO_UDP)
+ session->state = COAP_SESSION_STATE_ESTABLISHED;
+ else if (endpoint->proto == COAP_PROTO_DTLS) {
+ session->type = COAP_SESSION_TYPE_HELLO;
+ }
+ LL_PREPEND(endpoint->sessions, session);
+ coap_log(LOG_DEBUG, "***%s: new incoming session\n",
+ coap_session_str(session));
}
return session;
}
coap_session_t *
-coap_endpoint_new_dtls_session(coap_endpoint_t *endpoint,
- const coap_packet_t *packet, coap_tick_t now) {
- coap_session_t *session = coap_make_session(COAP_PROTO_DTLS,
- COAP_SESSION_TYPE_SERVER, NULL, &packet->dst, &packet->src,
- packet->ifindex, endpoint->context, endpoint);
+coap_session_new_dtls_session(coap_session_t *session,
+ coap_tick_t now) {
if (session) {
session->last_rx_tx = now;
- session->state = COAP_SESSION_STATE_HANDSHAKE;
+ session->type = COAP_SESSION_TYPE_SERVER;
session->tls = coap_dtls_new_server_session(session);
if (session->tls) {
session->state = COAP_SESSION_STATE_HANDSHAKE;
- LL_PREPEND(endpoint->sessions, session);
- coap_log(LOG_DEBUG, "***%s: new incoming session\n",
- coap_session_str(session));
} else {
coap_session_free(session);
session = NULL;
@@ -875,14 +955,6 @@ coap_new_endpoint(coap_context_t *context, const coap_address_t *listen_addr, co
ep->sock.flags |= COAP_SOCKET_NOT_EMPTY | COAP_SOCKET_BOUND;
- if (proto == COAP_PROTO_DTLS) {
- ep->hello.proto = proto;
- ep->hello.type = COAP_SESSION_TYPE_HELLO;
- ep->hello.mtu = ep->default_mtu;
- ep->hello.context = context;
- ep->hello.endpoint = ep;
- }
-
ep->default_mtu = COAP_DEFAULT_MTU;
LL_PREPEND(context->endpoint, ep);
@@ -893,6 +965,40 @@ error:
return NULL;
}
+#if HAVE_CISCO
+/*
+ * Trying to keep this API function as close to other ones in this code as
+ * possible. For example, returning void yet input parameters need to be
+ * error checked. It seems the behavior is to just assert if something is
+ * not correct.
+ */
+void coap_endpoint_set_session_max (coap_endpoint_t *ep, unsigned int session_max) {
+
+ /*
+ * Error check the input parameters
+ */
+ assert(ep);
+ assert(session_max);
+
+ /*
+ * Store away the max sessions value in the endpoint
+ */
+ ep->session_max = (uint16_t)session_max;
+
+ /*
+ * Enable the check to free up the oldest idle session(s) when
+ * new ones are needed.
+ */
+/*
+ * PDB NOTE: Setting to session_max - 1 will allow 2 new sessions about
+ * every 10 seconds. That seemed slow.
+ * Setting it to have the max (session_max/2) would seem better.
+ */
+/* ep->context->max_idle_sessions = session_max - 1; */
+ ep->context->max_idle_sessions = session_max - (session_max/2);
+}
+#endif
+
void coap_endpoint_set_default_mtu(coap_endpoint_t *ep, unsigned mtu) {
ep->default_mtu = (uint16_t)mtu;
}
@@ -930,8 +1036,6 @@ coap_session_get_by_peer(coap_context_t *ctx,
return s;
}
LL_FOREACH(ctx->endpoint, ep) {
- if (ep->hello.ifindex == ifindex && coap_address_equals(&ep->hello.remote_addr, remote_addr))
- return &ep->hello;
LL_FOREACH(ep->sessions, s) {
if (s->ifindex == ifindex && coap_address_equals(&s->remote_addr, remote_addr))
return s;
diff --git a/src/coap_tinydtls.c b/src/coap_tinydtls.c
index c3e5c23..b3d79cb 100644
--- a/src/coap_tinydtls.c
+++ b/src/coap_tinydtls.c
@@ -326,8 +326,11 @@ coap_dtls_session_update_mtu(coap_session_t *session) {
void
coap_dtls_free_session(coap_session_t *coap_session) {
- struct dtls_context_t *ctx = (struct dtls_context_t *)coap_session->context->dtls_context;
- if (coap_session->tls) {
+ struct dtls_context_t *ctx;
+ if (coap_session->context == NULL)
+ return;
+ ctx = (struct dtls_context_t *)coap_session->context->dtls_context;
+ if (coap_session->tls && ctx) {
dtls_peer_t *peer = dtls_get_peer(ctx, (session_t *)coap_session->tls);
if ( peer )
dtls_reset_peer(ctx, peer);
@@ -336,6 +339,7 @@ coap_dtls_free_session(coap_session_t *coap_session) {
coap_log(LOG_DEBUG, "***removed session %p\n", coap_session->tls);
coap_free_type(COAP_DTLS_SESSION, coap_session->tls);
coap_session->tls = NULL;
+ coap_handle_event(coap_session->context, COAP_EVENT_DTLS_CLOSED, coap_session);
}
}
@@ -359,10 +363,12 @@ coap_dtls_send(coap_session_t *session,
coap_log(LOG_WARNING, "coap_dtls_send: cannot send PDU\n");
if (coap_event_dtls >= 0) {
- coap_handle_event(session->context, coap_event_dtls, session);
+ /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */
+ if (coap_event_dtls != COAP_EVENT_DTLS_CLOSED)
+ coap_handle_event(session->context, coap_event_dtls, session);
if (coap_event_dtls == COAP_EVENT_DTLS_CONNECTED)
coap_session_connected(session);
- else if (coap_event_dtls == DTLS_ALERT_CLOSE_NOTIFY || coap_event_dtls == COAP_EVENT_DTLS_ERROR)
+ else if (coap_event_dtls == COAP_EVENT_DTLS_CLOSED || coap_event_dtls == COAP_EVENT_DTLS_ERROR)
coap_session_disconnected(session, COAP_NACK_TLS_FAILED);
}
@@ -412,10 +418,12 @@ coap_dtls_receive(coap_session_t *session,
}
if (coap_event_dtls >= 0) {
- coap_handle_event(session->context, coap_event_dtls, session);
+ /* COAP_EVENT_DTLS_CLOSED event reported in coap_session_disconnected() */
+ if (coap_event_dtls != COAP_EVENT_DTLS_CLOSED)
+ coap_handle_event(session->context, coap_event_dtls, session);
if (coap_event_dtls == COAP_EVENT_DTLS_CONNECTED)
coap_session_connected(session);
- else if (coap_event_dtls == DTLS_ALERT_CLOSE_NOTIFY || coap_event_dtls == COAP_EVENT_DTLS_ERROR)
+ else if (coap_event_dtls == COAP_EVENT_DTLS_CLOSED || coap_event_dtls == COAP_EVENT_DTLS_ERROR)
coap_session_disconnected(session, COAP_NACK_TLS_FAILED);
}
diff --git a/src/net.c b/src/net.c
index 2d84a8b..1db4194 100644
--- a/src/net.c
+++ b/src/net.c
@@ -1286,7 +1286,7 @@ coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t n
coap_session_str(session), bytes_read);
result = coap_handle_dgram_for_proto(ctx, session, packet);
if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
- coap_endpoint_new_dtls_session(endpoint, packet, now);
+ coap_session_new_dtls_session(session, now);
}
}
|