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
|
package sctp
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"math"
"net"
"sync"
"sync/atomic"
"time"
"github.com/pion/logging"
"github.com/pion/randutil"
)
// Use global random generator to properly seed by crypto grade random.
var globalMathRandomGenerator = randutil.NewMathRandomGenerator() // nolint:gochecknoglobals
// Association errors
var (
ErrChunk = errors.New("abort chunk, with following errors")
ErrShutdownNonEstablished = errors.New("shutdown called in non-established state")
ErrAssociationClosedBeforeConn = errors.New("association closed before connecting")
ErrSilentlyDiscard = errors.New("silently discard")
ErrInitNotStoredToSend = errors.New("the init not stored to send")
ErrCookieEchoNotStoredToSend = errors.New("cookieEcho not stored to send")
ErrSCTPPacketSourcePortZero = errors.New("sctp packet must not have a source port of 0")
ErrSCTPPacketDestinationPortZero = errors.New("sctp packet must not have a destination port of 0")
ErrInitChunkBundled = errors.New("init chunk must not be bundled with any other chunk")
ErrInitChunkVerifyTagNotZero = errors.New("init chunk expects a verification tag of 0 on the packet when out-of-the-blue")
ErrHandleInitState = errors.New("todo: handle Init when in state")
ErrInitAckNoCookie = errors.New("no cookie in InitAck")
ErrInflightQueueTSNPop = errors.New("unable to be popped from inflight queue TSN")
ErrTSNRequestNotExist = errors.New("requested non-existent TSN")
ErrResetPacketInStateNotExist = errors.New("sending reset packet in non-established state")
ErrParamterType = errors.New("unexpected parameter type")
ErrPayloadDataStateNotExist = errors.New("sending payload data in non-established state")
ErrChunkTypeUnhandled = errors.New("unhandled chunk type")
ErrHandshakeInitAck = errors.New("handshake failed (INIT ACK)")
ErrHandshakeCookieEcho = errors.New("handshake failed (COOKIE ECHO)")
)
const (
receiveMTU uint32 = 8192 // MTU for inbound packet (from DTLS)
initialMTU uint32 = 1228 // initial MTU for outgoing packets (to DTLS)
initialRecvBufSize uint32 = 1024 * 1024
commonHeaderSize uint32 = 12
dataChunkHeaderSize uint32 = 16
defaultMaxMessageSize uint32 = 65536
)
// association state enums
const (
closed uint32 = iota
cookieWait
cookieEchoed
established
shutdownAckSent
shutdownPending
shutdownReceived
shutdownSent
)
// retransmission timer IDs
const (
timerT1Init int = iota
timerT1Cookie
timerT2Shutdown
timerT3RTX
timerReconfig
)
// ack mode (for testing)
const (
ackModeNormal int = iota
ackModeNoDelay
ackModeAlwaysDelay
)
// ack transmission state
const (
ackStateIdle int = iota // ack timer is off
ackStateImmediate // will send ack immediately
ackStateDelay // ack timer is on (ack is being delayed)
)
// other constants
const (
acceptChSize = 16
)
func getAssociationStateString(a uint32) string {
switch a {
case closed:
return "Closed"
case cookieWait:
return "CookieWait"
case cookieEchoed:
return "CookieEchoed"
case established:
return "Established"
case shutdownPending:
return "ShutdownPending"
case shutdownSent:
return "ShutdownSent"
case shutdownReceived:
return "ShutdownReceived"
case shutdownAckSent:
return "ShutdownAckSent"
default:
return fmt.Sprintf("Invalid association state %d", a)
}
}
// Association represents an SCTP association
// 13.2. Parameters Necessary per Association (i.e., the TCB)
// Peer : Tag value to be sent in every packet and is received
// Verification: in the INIT or INIT ACK chunk.
// Tag :
//
// My : Tag expected in every inbound packet and sent in the
// Verification: INIT or INIT ACK chunk.
//
// Tag :
// State : A state variable indicating what state the association
// : is in, i.e., COOKIE-WAIT, COOKIE-ECHOED, ESTABLISHED,
// : SHUTDOWN-PENDING, SHUTDOWN-SENT, SHUTDOWN-RECEIVED,
// : SHUTDOWN-ACK-SENT.
//
// Note: No "CLOSED" state is illustrated since if a
// association is "CLOSED" its TCB SHOULD be removed.
type Association struct {
bytesReceived uint64
bytesSent uint64
lock sync.RWMutex
netConn net.Conn
peerVerificationTag uint32
myVerificationTag uint32
state uint32
myNextTSN uint32 // nextTSN
peerLastTSN uint32 // lastRcvdTSN
minTSN2MeasureRTT uint32 // for RTT measurement
willSendForwardTSN bool
willRetransmitFast bool
willRetransmitReconfig bool
willSendShutdown bool
willSendShutdownAck bool
willSendShutdownComplete bool
willSendAbort bool
willSendAbortCause errorCause
// Reconfig
myNextRSN uint32
reconfigs map[uint32]*chunkReconfig
reconfigRequests map[uint32]*paramOutgoingResetRequest
// Non-RFC internal data
sourcePort uint16
destinationPort uint16
myMaxNumInboundStreams uint16
myMaxNumOutboundStreams uint16
myCookie *paramStateCookie
payloadQueue *payloadQueue
inflightQueue *payloadQueue
pendingQueue *pendingQueue
controlQueue *controlQueue
mtu uint32
maxPayloadSize uint32 // max DATA chunk payload size
cumulativeTSNAckPoint uint32
advancedPeerTSNAckPoint uint32
useForwardTSN bool
// Congestion control parameters
maxReceiveBufferSize uint32
maxMessageSize uint32
cwnd uint32 // my congestion window size
rwnd uint32 // calculated peer's receiver windows size
ssthresh uint32 // slow start threshold
partialBytesAcked uint32
inFastRecovery bool
fastRecoverExitPoint uint32
// RTX & Ack timer
rtoMgr *rtoManager
t1Init *rtxTimer
t1Cookie *rtxTimer
t2Shutdown *rtxTimer
t3RTX *rtxTimer
tReconfig *rtxTimer
ackTimer *ackTimer
// Chunks stored for retransmission
storedInit *chunkInit
storedCookieEcho *chunkCookieEcho
streams map[uint16]*Stream
acceptCh chan *Stream
readLoopCloseCh chan struct{}
awakeWriteLoopCh chan struct{}
closeWriteLoopCh chan struct{}
handshakeCompletedCh chan error
closeWriteLoopOnce sync.Once
// local error
silentError error
ackState int
ackMode int // for testing
// stats
stats *associationStats
// per inbound packet context
delayedAckTriggered bool
immediateAckTriggered bool
name string
log logging.LeveledLogger
}
// Config collects the arguments to createAssociation construction into
// a single structure
type Config struct {
NetConn net.Conn
MaxReceiveBufferSize uint32
MaxMessageSize uint32
LoggerFactory logging.LoggerFactory
}
// Server accepts a SCTP stream over a conn
func Server(config Config) (*Association, error) {
a := createAssociation(config)
a.init(false)
select {
case err := <-a.handshakeCompletedCh:
if err != nil {
return nil, err
}
return a, nil
case <-a.readLoopCloseCh:
return nil, ErrAssociationClosedBeforeConn
}
}
// Client opens a SCTP stream over a conn
func Client(config Config) (*Association, error) {
a := createAssociation(config)
a.init(true)
select {
case err := <-a.handshakeCompletedCh:
if err != nil {
return nil, err
}
return a, nil
case <-a.readLoopCloseCh:
return nil, ErrAssociationClosedBeforeConn
}
}
func createAssociation(config Config) *Association {
var maxReceiveBufferSize uint32
if config.MaxReceiveBufferSize == 0 {
maxReceiveBufferSize = initialRecvBufSize
} else {
maxReceiveBufferSize = config.MaxReceiveBufferSize
}
var maxMessageSize uint32
if config.MaxMessageSize == 0 {
maxMessageSize = defaultMaxMessageSize
} else {
maxMessageSize = config.MaxMessageSize
}
tsn := globalMathRandomGenerator.Uint32()
a := &Association{
netConn: config.NetConn,
maxReceiveBufferSize: maxReceiveBufferSize,
maxMessageSize: maxMessageSize,
myMaxNumOutboundStreams: math.MaxUint16,
myMaxNumInboundStreams: math.MaxUint16,
payloadQueue: newPayloadQueue(),
inflightQueue: newPayloadQueue(),
pendingQueue: newPendingQueue(),
controlQueue: newControlQueue(),
mtu: initialMTU,
maxPayloadSize: initialMTU - (commonHeaderSize + dataChunkHeaderSize),
myVerificationTag: globalMathRandomGenerator.Uint32(),
myNextTSN: tsn,
myNextRSN: tsn,
minTSN2MeasureRTT: tsn,
state: closed,
rtoMgr: newRTOManager(),
streams: map[uint16]*Stream{},
reconfigs: map[uint32]*chunkReconfig{},
reconfigRequests: map[uint32]*paramOutgoingResetRequest{},
acceptCh: make(chan *Stream, acceptChSize),
readLoopCloseCh: make(chan struct{}),
awakeWriteLoopCh: make(chan struct{}, 1),
closeWriteLoopCh: make(chan struct{}),
handshakeCompletedCh: make(chan error),
cumulativeTSNAckPoint: tsn - 1,
advancedPeerTSNAckPoint: tsn - 1,
silentError: ErrSilentlyDiscard,
stats: &associationStats{},
log: config.LoggerFactory.NewLogger("sctp"),
}
a.name = fmt.Sprintf("%p", a)
// RFC 4690 Sec 7.2.1
// o The initial cwnd before DATA transmission or after a sufficiently
// long idle period MUST be set to min(4*MTU, max (2*MTU, 4380
// bytes)).
a.cwnd = min32(4*a.mtu, max32(2*a.mtu, 4380))
a.log.Tracef("[%s] updated cwnd=%d ssthresh=%d inflight=%d (INI)",
a.name, a.cwnd, a.ssthresh, a.inflightQueue.getNumBytes())
a.t1Init = newRTXTimer(timerT1Init, a, maxInitRetrans)
a.t1Cookie = newRTXTimer(timerT1Cookie, a, maxInitRetrans)
a.t2Shutdown = newRTXTimer(timerT2Shutdown, a, noMaxRetrans) // retransmit forever
a.t3RTX = newRTXTimer(timerT3RTX, a, noMaxRetrans) // retransmit forever
a.tReconfig = newRTXTimer(timerReconfig, a, noMaxRetrans) // retransmit forever
a.ackTimer = newAckTimer(a)
return a
}
func (a *Association) init(isClient bool) {
a.lock.Lock()
defer a.lock.Unlock()
go a.readLoop()
go a.writeLoop()
if isClient {
a.setState(cookieWait)
init := &chunkInit{}
init.initialTSN = a.myNextTSN
init.numOutboundStreams = a.myMaxNumOutboundStreams
init.numInboundStreams = a.myMaxNumInboundStreams
init.initiateTag = a.myVerificationTag
init.advertisedReceiverWindowCredit = a.maxReceiveBufferSize
setSupportedExtensions(&init.chunkInitCommon)
a.storedInit = init
err := a.sendInit()
if err != nil {
a.log.Errorf("[%s] failed to send init: %s", a.name, err.Error())
}
a.t1Init.start(a.rtoMgr.getRTO())
}
}
// caller must hold a.lock
func (a *Association) sendInit() error {
a.log.Debugf("[%s] sending INIT", a.name)
if a.storedInit == nil {
return ErrInitNotStoredToSend
}
outbound := &packet{}
outbound.verificationTag = a.peerVerificationTag
a.sourcePort = 5000 // Spec??
a.destinationPort = 5000 // Spec??
outbound.sourcePort = a.sourcePort
outbound.destinationPort = a.destinationPort
outbound.chunks = []chunk{a.storedInit}
a.controlQueue.push(outbound)
a.awakeWriteLoop()
return nil
}
// caller must hold a.lock
func (a *Association) sendCookieEcho() error {
if a.storedCookieEcho == nil {
return ErrCookieEchoNotStoredToSend
}
a.log.Debugf("[%s] sending COOKIE-ECHO", a.name)
outbound := &packet{}
outbound.verificationTag = a.peerVerificationTag
outbound.sourcePort = a.sourcePort
outbound.destinationPort = a.destinationPort
outbound.chunks = []chunk{a.storedCookieEcho}
a.controlQueue.push(outbound)
a.awakeWriteLoop()
return nil
}
// Shutdown initiates the shutdown sequence. The method blocks until the
// shutdown sequence is completed and the connection is closed, or until the
// passed context is done, in which case the context's error is returned.
func (a *Association) Shutdown(ctx context.Context) error {
a.log.Debugf("[%s] closing association..", a.name)
state := a.getState()
if state != established {
return fmt.Errorf("%w: shutdown %s", ErrShutdownNonEstablished, a.name)
}
// Attempt a graceful shutdown.
a.setState(shutdownPending)
a.lock.Lock()
if a.inflightQueue.size() == 0 {
// No more outstanding, send shutdown.
a.willSendShutdown = true
a.awakeWriteLoop()
a.setState(shutdownSent)
}
a.lock.Unlock()
select {
case <-a.closeWriteLoopCh:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// Close ends the SCTP Association and cleans up any state
func (a *Association) Close() error {
a.log.Debugf("[%s] closing association..", a.name)
err := a.close()
// Wait for readLoop to end
<-a.readLoopCloseCh
a.log.Debugf("[%s] association closed", a.name)
a.log.Debugf("[%s] stats nDATAs (in) : %d", a.name, a.stats.getNumDATAs())
a.log.Debugf("[%s] stats nSACKs (in) : %d", a.name, a.stats.getNumSACKs())
a.log.Debugf("[%s] stats nT3Timeouts : %d", a.name, a.stats.getNumT3Timeouts())
a.log.Debugf("[%s] stats nAckTimeouts: %d", a.name, a.stats.getNumAckTimeouts())
a.log.Debugf("[%s] stats nFastRetrans: %d", a.name, a.stats.getNumFastRetrans())
return err
}
func (a *Association) close() error {
a.log.Debugf("[%s] closing association..", a.name)
a.setState(closed)
err := a.netConn.Close()
a.closeAllTimers()
// awake writeLoop to exit
a.closeWriteLoopOnce.Do(func() { close(a.closeWriteLoopCh) })
return err
}
// Abort sends the abort packet with user initiated abort and immediately
// closes the connection.
func (a *Association) Abort(reason string) {
a.log.Debugf("[%s] aborting association: %s", a.name, reason)
a.lock.Lock()
a.willSendAbort = true
a.willSendAbortCause = &errorCauseUserInitiatedAbort{
upperLayerAbortReason: []byte(reason),
}
a.lock.Unlock()
a.awakeWriteLoop()
// Wait for readLoop to end
<-a.readLoopCloseCh
}
func (a *Association) closeAllTimers() {
// Close all retransmission & ack timers
a.t1Init.close()
a.t1Cookie.close()
a.t2Shutdown.close()
a.t3RTX.close()
a.tReconfig.close()
a.ackTimer.close()
}
func (a *Association) readLoop() {
var closeErr error
defer func() {
// also stop writeLoop, otherwise writeLoop can be leaked
// if connection is lost when there is no writing packet.
a.closeWriteLoopOnce.Do(func() { close(a.closeWriteLoopCh) })
a.lock.Lock()
for _, s := range a.streams {
a.unregisterStream(s, closeErr)
}
a.lock.Unlock()
close(a.acceptCh)
close(a.readLoopCloseCh)
a.log.Debugf("[%s] association closed", a.name)
a.log.Debugf("[%s] stats nDATAs (in) : %d", a.name, a.stats.getNumDATAs())
a.log.Debugf("[%s] stats nSACKs (in) : %d", a.name, a.stats.getNumSACKs())
a.log.Debugf("[%s] stats nT3Timeouts : %d", a.name, a.stats.getNumT3Timeouts())
a.log.Debugf("[%s] stats nAckTimeouts: %d", a.name, a.stats.getNumAckTimeouts())
a.log.Debugf("[%s] stats nFastRetrans: %d", a.name, a.stats.getNumFastRetrans())
}()
a.log.Debugf("[%s] readLoop entered", a.name)
buffer := make([]byte, receiveMTU)
for {
n, err := a.netConn.Read(buffer)
if err != nil {
closeErr = err
break
}
// Make a buffer sized to what we read, then copy the data we
// read from the underlying transport. We do this because the
// user data is passed to the reassembly queue without
// copying.
inbound := make([]byte, n)
copy(inbound, buffer[:n])
atomic.AddUint64(&a.bytesReceived, uint64(n))
if err = a.handleInbound(inbound); err != nil {
closeErr = err
break
}
}
a.log.Debugf("[%s] readLoop exited %s", a.name, closeErr)
}
func (a *Association) writeLoop() {
a.log.Debugf("[%s] writeLoop entered", a.name)
defer a.log.Debugf("[%s] writeLoop exited", a.name)
loop:
for {
rawPackets, ok := a.gatherOutbound()
for _, raw := range rawPackets {
_, err := a.netConn.Write(raw)
if err != nil {
if !errors.Is(err, io.EOF) {
a.log.Warnf("[%s] failed to write packets on netConn: %v", a.name, err)
}
a.log.Debugf("[%s] writeLoop ended", a.name)
break loop
}
atomic.AddUint64(&a.bytesSent, uint64(len(raw)))
}
if !ok {
if err := a.close(); err != nil {
a.log.Warnf("[%s] failed to close association: %v", a.name, err)
}
return
}
select {
case <-a.awakeWriteLoopCh:
case <-a.closeWriteLoopCh:
break loop
}
}
a.setState(closed)
a.closeAllTimers()
}
func (a *Association) awakeWriteLoop() {
select {
case a.awakeWriteLoopCh <- struct{}{}:
default:
}
}
// unregisterStream un-registers a stream from the association
// The caller should hold the association write lock.
func (a *Association) unregisterStream(s *Stream, err error) {
s.lock.Lock()
defer s.lock.Unlock()
delete(a.streams, s.streamIdentifier)
s.readErr = err
s.readNotifier.Broadcast()
}
// handleInbound parses incoming raw packets
func (a *Association) handleInbound(raw []byte) error {
p := &packet{}
if err := p.unmarshal(raw); err != nil {
a.log.Warnf("[%s] unable to parse SCTP packet %s", a.name, err)
return nil
}
if err := checkPacket(p); err != nil {
a.log.Warnf("[%s] failed validating packet %s", a.name, err)
return nil
}
a.handleChunkStart()
for _, c := range p.chunks {
if err := a.handleChunk(p, c); err != nil {
return err
}
}
a.handleChunkEnd()
return nil
}
// The caller should hold the lock
func (a *Association) gatherDataPacketsToRetransmit(rawPackets [][]byte) [][]byte {
for _, p := range a.getDataPacketsToRetransmit() {
raw, err := p.marshal()
if err != nil {
a.log.Warnf("[%s] failed to serialize a DATA packet to be retransmitted", a.name)
continue
}
rawPackets = append(rawPackets, raw)
}
return rawPackets
}
// The caller should hold the lock
func (a *Association) gatherOutboundDataAndReconfigPackets(rawPackets [][]byte) [][]byte {
// Pop unsent data chunks from the pending queue to send as much as
// cwnd and rwnd allow.
chunks, sisToReset := a.popPendingDataChunksToSend()
if len(chunks) > 0 {
// Start timer. (noop if already started)
a.log.Tracef("[%s] T3-rtx timer start (pt1)", a.name)
a.t3RTX.start(a.rtoMgr.getRTO())
for _, p := range a.bundleDataChunksIntoPackets(chunks) {
raw, err := p.marshal()
if err != nil {
a.log.Warnf("[%s] failed to serialize a DATA packet", a.name)
continue
}
rawPackets = append(rawPackets, raw)
}
}
if len(sisToReset) > 0 || a.willRetransmitReconfig {
if a.willRetransmitReconfig {
a.willRetransmitReconfig = false
a.log.Debugf("[%s] retransmit %d RECONFIG chunk(s)", a.name, len(a.reconfigs))
for _, c := range a.reconfigs {
p := a.createPacket([]chunk{c})
raw, err := p.marshal()
if err != nil {
a.log.Warnf("[%s] failed to serialize a RECONFIG packet to be retransmitted", a.name)
} else {
rawPackets = append(rawPackets, raw)
}
}
}
if len(sisToReset) > 0 {
rsn := a.generateNextRSN()
tsn := a.myNextTSN - 1
c := &chunkReconfig{
paramA: ¶mOutgoingResetRequest{
reconfigRequestSequenceNumber: rsn,
senderLastTSN: tsn,
streamIdentifiers: sisToReset,
},
}
a.reconfigs[rsn] = c // store in the map for retransmission
a.log.Debugf("[%s] sending RECONFIG: rsn=%d tsn=%d streams=%v",
a.name, rsn, a.myNextTSN-1, sisToReset)
p := a.createPacket([]chunk{c})
raw, err := p.marshal()
if err != nil {
a.log.Warnf("[%s] failed to serialize a RECONFIG packet to be transmitted", a.name)
} else {
rawPackets = append(rawPackets, raw)
}
}
if len(a.reconfigs) > 0 {
a.tReconfig.start(a.rtoMgr.getRTO())
}
}
return rawPackets
}
// The caller should hold the lock
func (a *Association) gatherOutboundFastRetransmissionPackets(rawPackets [][]byte) [][]byte {
if a.willRetransmitFast {
a.willRetransmitFast = false
toFastRetrans := []chunk{}
fastRetransSize := commonHeaderSize
for i := 0; ; i++ {
c, ok := a.inflightQueue.get(a.cumulativeTSNAckPoint + uint32(i) + 1)
if !ok {
break // end of pending data
}
if c.acked || c.abandoned() {
continue
}
if c.nSent > 1 || c.missIndicator < 3 {
continue
}
// RFC 4960 Sec 7.2.4 Fast Retransmit on Gap Reports
// 3) Determine how many of the earliest (i.e., lowest TSN) DATA chunks
// marked for retransmission will fit into a single packet, subject
// to constraint of the path MTU of the destination transport
// address to which the packet is being sent. Call this value K.
// Retransmit those K DATA chunks in a single packet. When a Fast
// Retransmit is being performed, the sender SHOULD ignore the value
// of cwnd and SHOULD NOT delay retransmission for this single
// packet.
dataChunkSize := dataChunkHeaderSize + uint32(len(c.userData))
if a.mtu < fastRetransSize+dataChunkSize {
break
}
fastRetransSize += dataChunkSize
a.stats.incFastRetrans()
c.nSent++
a.checkPartialReliabilityStatus(c)
toFastRetrans = append(toFastRetrans, c)
a.log.Tracef("[%s] fast-retransmit: tsn=%d sent=%d htna=%d",
a.name, c.tsn, c.nSent, a.fastRecoverExitPoint)
}
if len(toFastRetrans) > 0 {
raw, err := a.createPacket(toFastRetrans).marshal()
if err != nil {
a.log.Warnf("[%s] failed to serialize a DATA packet to be fast-retransmitted", a.name)
} else {
rawPackets = append(rawPackets, raw)
}
}
}
return rawPackets
}
// The caller should hold the lock
func (a *Association) gatherOutboundSackPackets(rawPackets [][]byte) [][]byte {
if a.ackState == ackStateImmediate {
a.ackState = ackStateIdle
sack := a.createSelectiveAckChunk()
a.log.Debugf("[%s] sending SACK: %s", a.name, sack.String())
raw, err := a.createPacket([]chunk{sack}).marshal()
if err != nil {
a.log.Warnf("[%s] failed to serialize a SACK packet", a.name)
} else {
rawPackets = append(rawPackets, raw)
}
}
return rawPackets
}
// The caller should hold the lock
func (a *Association) gatherOutboundForwardTSNPackets(rawPackets [][]byte) [][]byte {
if a.willSendForwardTSN {
a.willSendForwardTSN = false
if sna32GT(a.advancedPeerTSNAckPoint, a.cumulativeTSNAckPoint) {
fwdtsn := a.createForwardTSN()
raw, err := a.createPacket([]chunk{fwdtsn}).marshal()
if err != nil {
a.log.Warnf("[%s] failed to serialize a Forward TSN packet", a.name)
} else {
rawPackets = append(rawPackets, raw)
}
}
}
return rawPackets
}
func (a *Association) gatherOutboundShutdownPackets(rawPackets [][]byte) ([][]byte, bool) {
ok := true
switch {
case a.willSendShutdown:
a.willSendShutdown = false
shutdown := &chunkShutdown{
cumulativeTSNAck: a.cumulativeTSNAckPoint,
}
raw, err := a.createPacket([]chunk{shutdown}).marshal()
if err != nil {
a.log.Warnf("[%s] failed to serialize a Shutdown packet", a.name)
} else {
a.t2Shutdown.start(a.rtoMgr.getRTO())
rawPackets = append(rawPackets, raw)
}
case a.willSendShutdownAck:
a.willSendShutdownAck = false
shutdownAck := &chunkShutdownAck{}
raw, err := a.createPacket([]chunk{shutdownAck}).marshal()
if err != nil {
a.log.Warnf("[%s] failed to serialize a ShutdownAck packet", a.name)
} else {
a.t2Shutdown.start(a.rtoMgr.getRTO())
rawPackets = append(rawPackets, raw)
}
case a.willSendShutdownComplete:
a.willSendShutdownComplete = false
shutdownComplete := &chunkShutdownComplete{}
raw, err := a.createPacket([]chunk{shutdownComplete}).marshal()
if err != nil {
a.log.Warnf("[%s] failed to serialize a ShutdownComplete packet", a.name)
} else {
rawPackets = append(rawPackets, raw)
ok = false
}
}
return rawPackets, ok
}
func (a *Association) gatherAbortPacket() ([]byte, error) {
cause := a.willSendAbortCause
a.willSendAbort = false
a.willSendAbortCause = nil
abort := &chunkAbort{}
if cause != nil {
abort.errorCauses = []errorCause{cause}
}
raw, err := a.createPacket([]chunk{abort}).marshal()
return raw, err
}
// gatherOutbound gathers outgoing packets. The returned bool value set to
// false means the association should be closed down after the final send.
func (a *Association) gatherOutbound() ([][]byte, bool) {
a.lock.Lock()
defer a.lock.Unlock()
if a.willSendAbort {
pkt, err := a.gatherAbortPacket()
if err != nil {
a.log.Warnf("[%s] failed to serialize an abort packet", a.name)
return nil, false
}
return [][]byte{pkt}, false
}
rawPackets := [][]byte{}
if a.controlQueue.size() > 0 {
for _, p := range a.controlQueue.popAll() {
raw, err := p.marshal()
if err != nil {
a.log.Warnf("[%s] failed to serialize a control packet", a.name)
continue
}
rawPackets = append(rawPackets, raw)
}
}
state := a.getState()
ok := true
switch state {
case established:
rawPackets = a.gatherDataPacketsToRetransmit(rawPackets)
rawPackets = a.gatherOutboundDataAndReconfigPackets(rawPackets)
rawPackets = a.gatherOutboundFastRetransmissionPackets(rawPackets)
rawPackets = a.gatherOutboundSackPackets(rawPackets)
rawPackets = a.gatherOutboundForwardTSNPackets(rawPackets)
case shutdownPending, shutdownSent, shutdownReceived:
rawPackets = a.gatherDataPacketsToRetransmit(rawPackets)
rawPackets = a.gatherOutboundFastRetransmissionPackets(rawPackets)
rawPackets = a.gatherOutboundSackPackets(rawPackets)
rawPackets, ok = a.gatherOutboundShutdownPackets(rawPackets)
case shutdownAckSent:
rawPackets, ok = a.gatherOutboundShutdownPackets(rawPackets)
}
return rawPackets, ok
}
func checkPacket(p *packet) error {
// All packets must adhere to these rules
// This is the SCTP sender's port number. It can be used by the
// receiver in combination with the source IP address, the SCTP
// destination port, and possibly the destination IP address to
// identify the association to which this packet belongs. The port
// number 0 MUST NOT be used.
if p.sourcePort == 0 {
return ErrSCTPPacketSourcePortZero
}
// This is the SCTP port number to which this packet is destined.
// The receiving host will use this port number to de-multiplex the
// SCTP packet to the correct receiving endpoint/application. The
// port number 0 MUST NOT be used.
if p.destinationPort == 0 {
return ErrSCTPPacketDestinationPortZero
}
// Check values on the packet that are specific to a particular chunk type
for _, c := range p.chunks {
switch c.(type) { // nolint:gocritic
case *chunkInit:
// An INIT or INIT ACK chunk MUST NOT be bundled with any other chunk.
// They MUST be the only chunks present in the SCTP packets that carry
// them.
if len(p.chunks) != 1 {
return ErrInitChunkBundled
}
// A packet containing an INIT chunk MUST have a zero Verification
// Tag.
if p.verificationTag != 0 {
return ErrInitChunkVerifyTagNotZero
}
}
}
return nil
}
func min16(a, b uint16) uint16 {
if a < b {
return a
}
return b
}
func max32(a, b uint32) uint32 {
if a > b {
return a
}
return b
}
func min32(a, b uint32) uint32 {
if a < b {
return a
}
return b
}
// setState atomically sets the state of the Association.
// The caller should hold the lock.
func (a *Association) setState(newState uint32) {
oldState := atomic.SwapUint32(&a.state, newState)
if newState != oldState {
a.log.Debugf("[%s] state change: '%s' => '%s'",
a.name,
getAssociationStateString(oldState),
getAssociationStateString(newState))
}
}
// getState atomically returns the state of the Association.
func (a *Association) getState() uint32 {
return atomic.LoadUint32(&a.state)
}
// BytesSent returns the number of bytes sent
func (a *Association) BytesSent() uint64 {
return atomic.LoadUint64(&a.bytesSent)
}
// BytesReceived returns the number of bytes received
func (a *Association) BytesReceived() uint64 {
return atomic.LoadUint64(&a.bytesReceived)
}
func setSupportedExtensions(init *chunkInitCommon) {
// nolint:godox
// TODO RFC5061 https://tools.ietf.org/html/rfc6525#section-5.2
// An implementation supporting this (Supported Extensions Parameter)
// extension MUST list the ASCONF, the ASCONF-ACK, and the AUTH chunks
// in its INIT and INIT-ACK parameters.
init.params = append(init.params, ¶mSupportedExtensions{
ChunkTypes: []chunkType{ctReconfig, ctForwardTSN},
})
}
// The caller should hold the lock.
func (a *Association) handleInit(p *packet, i *chunkInit) ([]*packet, error) {
state := a.getState()
a.log.Debugf("[%s] chunkInit received in state '%s'", a.name, getAssociationStateString(state))
// https://tools.ietf.org/html/rfc4960#section-5.2.1
// Upon receipt of an INIT in the COOKIE-WAIT state, an endpoint MUST
// respond with an INIT ACK using the same parameters it sent in its
// original INIT chunk (including its Initiate Tag, unchanged). When
// responding, the endpoint MUST send the INIT ACK back to the same
// address that the original INIT (sent by this endpoint) was sent.
if state != closed && state != cookieWait && state != cookieEchoed {
// 5.2.2. Unexpected INIT in States Other than CLOSED, COOKIE-ECHOED,
// COOKIE-WAIT, and SHUTDOWN-ACK-SENT
return nil, fmt.Errorf("%w: %s", ErrHandleInitState, getAssociationStateString(state))
}
// Should we be setting any of these permanently until we've ACKed further?
a.myMaxNumInboundStreams = min16(i.numInboundStreams, a.myMaxNumInboundStreams)
a.myMaxNumOutboundStreams = min16(i.numOutboundStreams, a.myMaxNumOutboundStreams)
a.peerVerificationTag = i.initiateTag
a.sourcePort = p.destinationPort
a.destinationPort = p.sourcePort
// 13.2 This is the last TSN received in sequence. This value
// is set initially by taking the peer's initial TSN,
// received in the INIT or INIT ACK chunk, and
// subtracting one from it.
a.peerLastTSN = i.initialTSN - 1
for _, param := range i.params {
switch v := param.(type) { // nolint:gocritic
case *paramSupportedExtensions:
for _, t := range v.ChunkTypes {
if t == ctForwardTSN {
a.log.Debugf("[%s] use ForwardTSN (on init)", a.name)
a.useForwardTSN = true
}
}
}
}
if !a.useForwardTSN {
a.log.Warnf("[%s] not using ForwardTSN (on init)", a.name)
}
outbound := &packet{}
outbound.verificationTag = a.peerVerificationTag
outbound.sourcePort = a.sourcePort
outbound.destinationPort = a.destinationPort
initAck := &chunkInitAck{}
initAck.initialTSN = a.myNextTSN
initAck.numOutboundStreams = a.myMaxNumOutboundStreams
initAck.numInboundStreams = a.myMaxNumInboundStreams
initAck.initiateTag = a.myVerificationTag
initAck.advertisedReceiverWindowCredit = a.maxReceiveBufferSize
if a.myCookie == nil {
var err error
if a.myCookie, err = newRandomStateCookie(); err != nil {
return nil, err
}
}
initAck.params = []param{a.myCookie}
setSupportedExtensions(&initAck.chunkInitCommon)
outbound.chunks = []chunk{initAck}
return pack(outbound), nil
}
// The caller should hold the lock.
func (a *Association) handleInitAck(p *packet, i *chunkInitAck) error {
state := a.getState()
a.log.Debugf("[%s] chunkInitAck received in state '%s'", a.name, getAssociationStateString(state))
if state != cookieWait {
// RFC 4960
// 5.2.3. Unexpected INIT ACK
// If an INIT ACK is received by an endpoint in any state other than the
// COOKIE-WAIT state, the endpoint should discard the INIT ACK chunk.
// An unexpected INIT ACK usually indicates the processing of an old or
// duplicated INIT chunk.
return nil
}
a.myMaxNumInboundStreams = min16(i.numInboundStreams, a.myMaxNumInboundStreams)
a.myMaxNumOutboundStreams = min16(i.numOutboundStreams, a.myMaxNumOutboundStreams)
a.peerVerificationTag = i.initiateTag
a.peerLastTSN = i.initialTSN - 1
if a.sourcePort != p.destinationPort ||
a.destinationPort != p.sourcePort {
a.log.Warnf("[%s] handleInitAck: port mismatch", a.name)
return nil
}
a.rwnd = i.advertisedReceiverWindowCredit
a.log.Debugf("[%s] initial rwnd=%d", a.name, a.rwnd)
// RFC 4690 Sec 7.2.1
// o The initial value of ssthresh MAY be arbitrarily high (for
// example, implementations MAY use the size of the receiver
// advertised window).
a.ssthresh = a.rwnd
a.log.Tracef("[%s] updated cwnd=%d ssthresh=%d inflight=%d (INI)",
a.name, a.cwnd, a.ssthresh, a.inflightQueue.getNumBytes())
a.t1Init.stop()
a.storedInit = nil
var cookieParam *paramStateCookie
for _, param := range i.params {
switch v := param.(type) {
case *paramStateCookie:
cookieParam = v
case *paramSupportedExtensions:
for _, t := range v.ChunkTypes {
if t == ctForwardTSN {
a.log.Debugf("[%s] use ForwardTSN (on initAck)", a.name)
a.useForwardTSN = true
}
}
}
}
if !a.useForwardTSN {
a.log.Warnf("[%s] not using ForwardTSN (on initAck)", a.name)
}
if cookieParam == nil {
return ErrInitAckNoCookie
}
a.storedCookieEcho = &chunkCookieEcho{}
a.storedCookieEcho.cookie = cookieParam.cookie
err := a.sendCookieEcho()
if err != nil {
a.log.Errorf("[%s] failed to send init: %s", a.name, err.Error())
}
a.t1Cookie.start(a.rtoMgr.getRTO())
a.setState(cookieEchoed)
return nil
}
// The caller should hold the lock.
func (a *Association) handleHeartbeat(c *chunkHeartbeat) []*packet {
a.log.Tracef("[%s] chunkHeartbeat", a.name)
hbi, ok := c.params[0].(*paramHeartbeatInfo)
if !ok {
a.log.Warnf("[%s] failed to handle Heartbeat, no ParamHeartbeatInfo", a.name)
}
return pack(&packet{
verificationTag: a.peerVerificationTag,
sourcePort: a.sourcePort,
destinationPort: a.destinationPort,
chunks: []chunk{&chunkHeartbeatAck{
params: []param{
¶mHeartbeatInfo{
heartbeatInformation: hbi.heartbeatInformation,
},
},
}},
})
}
// The caller should hold the lock.
func (a *Association) handleCookieEcho(c *chunkCookieEcho) []*packet {
state := a.getState()
a.log.Debugf("[%s] COOKIE-ECHO received in state '%s'", a.name, getAssociationStateString(state))
if a.myCookie == nil {
a.log.Debugf("[%s] COOKIE-ECHO received before initialization", a.name)
return nil
}
switch state {
default:
return nil
case established:
if !bytes.Equal(a.myCookie.cookie, c.cookie) {
return nil
}
case closed, cookieWait, cookieEchoed:
if !bytes.Equal(a.myCookie.cookie, c.cookie) {
return nil
}
a.t1Init.stop()
a.storedInit = nil
a.t1Cookie.stop()
a.storedCookieEcho = nil
a.setState(established)
a.handshakeCompletedCh <- nil
}
p := &packet{
verificationTag: a.peerVerificationTag,
sourcePort: a.sourcePort,
destinationPort: a.destinationPort,
chunks: []chunk{&chunkCookieAck{}},
}
return pack(p)
}
// The caller should hold the lock.
func (a *Association) handleCookieAck() {
state := a.getState()
a.log.Debugf("[%s] COOKIE-ACK received in state '%s'", a.name, getAssociationStateString(state))
if state != cookieEchoed {
// RFC 4960
// 5.2.5. Handle Duplicate COOKIE-ACK.
// At any state other than COOKIE-ECHOED, an endpoint should silently
// discard a received COOKIE ACK chunk.
return
}
a.t1Cookie.stop()
a.storedCookieEcho = nil
a.setState(established)
a.handshakeCompletedCh <- nil
}
// The caller should hold the lock.
func (a *Association) handleData(d *chunkPayloadData) []*packet {
a.log.Tracef("[%s] DATA: tsn=%d immediateSack=%v len=%d",
a.name, d.tsn, d.immediateSack, len(d.userData))
a.stats.incDATAs()
canPush := a.payloadQueue.canPush(d, a.peerLastTSN)
if canPush {
s := a.getOrCreateStream(d.streamIdentifier, true, PayloadTypeUnknown)
if s == nil {
// silentely discard the data. (sender will retry on T3-rtx timeout)
// see pion/sctp#30
a.log.Debugf("discard %d", d.streamSequenceNumber)
return nil
}
if a.getMyReceiverWindowCredit() > 0 {
// Pass the new chunk to stream level as soon as it arrives
a.payloadQueue.push(d, a.peerLastTSN)
s.handleData(d)
} else {
// Receive buffer is full
lastTSN, ok := a.payloadQueue.getLastTSNReceived()
if ok && sna32LT(d.tsn, lastTSN) {
a.log.Debugf("[%s] receive buffer full, but accepted as this is a missing chunk with tsn=%d ssn=%d", a.name, d.tsn, d.streamSequenceNumber)
a.payloadQueue.push(d, a.peerLastTSN)
s.handleData(d)
} else {
a.log.Debugf("[%s] receive buffer full. dropping DATA with tsn=%d ssn=%d", a.name, d.tsn, d.streamSequenceNumber)
}
}
}
return a.handlePeerLastTSNAndAcknowledgement(d.immediateSack)
}
// A common routine for handleData and handleForwardTSN routines
// The caller should hold the lock.
func (a *Association) handlePeerLastTSNAndAcknowledgement(sackImmediately bool) []*packet {
var reply []*packet
// Try to advance peerLastTSN
// From RFC 3758 Sec 3.6:
// .. and then MUST further advance its cumulative TSN point locally
// if possible
// Meaning, if peerLastTSN+1 points to a chunk that is received,
// advance peerLastTSN until peerLastTSN+1 points to unreceived chunk.
for {
if _, popOk := a.payloadQueue.pop(a.peerLastTSN + 1); !popOk {
break
}
a.peerLastTSN++
for _, rstReq := range a.reconfigRequests {
resp := a.resetStreamsIfAny(rstReq)
if resp != nil {
a.log.Debugf("[%s] RESET RESPONSE: %+v", a.name, resp)
reply = append(reply, resp)
}
}
}
hasPacketLoss := (a.payloadQueue.size() > 0)
if hasPacketLoss {
a.log.Tracef("[%s] packetloss: %s", a.name, a.payloadQueue.getGapAckBlocksString(a.peerLastTSN))
}
if (a.ackState != ackStateImmediate && !sackImmediately && !hasPacketLoss && a.ackMode == ackModeNormal) || a.ackMode == ackModeAlwaysDelay {
if a.ackState == ackStateIdle {
a.delayedAckTriggered = true
} else {
a.immediateAckTriggered = true
}
} else {
a.immediateAckTriggered = true
}
return reply
}
// The caller should hold the lock.
func (a *Association) getMyReceiverWindowCredit() uint32 {
var bytesQueued uint32
for _, s := range a.streams {
bytesQueued += uint32(s.getNumBytesInReassemblyQueue())
}
if bytesQueued >= a.maxReceiveBufferSize {
return 0
}
return a.maxReceiveBufferSize - bytesQueued
}
// OpenStream opens a stream
func (a *Association) OpenStream(streamIdentifier uint16, defaultPayloadType PayloadProtocolIdentifier) (*Stream, error) {
a.lock.Lock()
defer a.lock.Unlock()
return a.getOrCreateStream(streamIdentifier, false, defaultPayloadType), nil
}
// AcceptStream accepts a stream
func (a *Association) AcceptStream() (*Stream, error) {
s, ok := <-a.acceptCh
if !ok {
return nil, io.EOF // no more incoming streams
}
return s, nil
}
// createStream creates a stream. The caller should hold the lock and check no stream exists for this id.
func (a *Association) createStream(streamIdentifier uint16, accept bool) *Stream {
s := &Stream{
association: a,
streamIdentifier: streamIdentifier,
reassemblyQueue: newReassemblyQueue(streamIdentifier),
log: a.log,
name: fmt.Sprintf("%d:%s", streamIdentifier, a.name),
}
s.readNotifier = sync.NewCond(&s.lock)
if accept {
select {
case a.acceptCh <- s:
a.streams[streamIdentifier] = s
a.log.Debugf("[%s] accepted a new stream (streamIdentifier: %d)",
a.name, streamIdentifier)
default:
a.log.Debugf("[%s] dropped a new stream (acceptCh size: %d)",
a.name, len(a.acceptCh))
return nil
}
} else {
a.streams[streamIdentifier] = s
}
return s
}
// getOrCreateStream gets or creates a stream. The caller should hold the lock.
func (a *Association) getOrCreateStream(streamIdentifier uint16, accept bool, defaultPayloadType PayloadProtocolIdentifier) *Stream {
if s, ok := a.streams[streamIdentifier]; ok {
s.SetDefaultPayloadType(defaultPayloadType)
return s
}
s := a.createStream(streamIdentifier, accept)
if s != nil {
s.SetDefaultPayloadType(defaultPayloadType)
}
return s
}
// The caller should hold the lock.
func (a *Association) processSelectiveAck(d *chunkSelectiveAck) (map[uint16]int, uint32, error) { // nolint:gocognit
bytesAckedPerStream := map[uint16]int{}
// New ack point, so pop all ACKed packets from inflightQueue
// We add 1 because the "currentAckPoint" has already been popped from the inflight queue
// For the first SACK we take care of this by setting the ackpoint to cumAck - 1
for i := a.cumulativeTSNAckPoint + 1; sna32LTE(i, d.cumulativeTSNAck); i++ {
c, ok := a.inflightQueue.pop(i)
if !ok {
return nil, 0, fmt.Errorf("%w: %v", ErrInflightQueueTSNPop, i)
}
if !c.acked {
// RFC 4096 sec 6.3.2. Retransmission Timer Rules
// R3) Whenever a SACK is received that acknowledges the DATA chunk
// with the earliest outstanding TSN for that address, restart the
// T3-rtx timer for that address with its current RTO (if there is
// still outstanding data on that address).
if i == a.cumulativeTSNAckPoint+1 {
// T3 timer needs to be reset. Stop it for now.
a.t3RTX.stop()
}
nBytesAcked := len(c.userData)
// Sum the number of bytes acknowledged per stream
if amount, ok := bytesAckedPerStream[c.streamIdentifier]; ok {
bytesAckedPerStream[c.streamIdentifier] = amount + nBytesAcked
} else {
bytesAckedPerStream[c.streamIdentifier] = nBytesAcked
}
// RFC 4960 sec 6.3.1. RTO Calculation
// C4) When data is in flight and when allowed by rule C5 below, a new
// RTT measurement MUST be made each round trip. Furthermore, new
// RTT measurements SHOULD be made no more than once per round trip
// for a given destination transport address.
// C5) Karn's algorithm: RTT measurements MUST NOT be made using
// packets that were retransmitted (and thus for which it is
// ambiguous whether the reply was for the first instance of the
// chunk or for a later instance)
if c.nSent == 1 && sna32GTE(c.tsn, a.minTSN2MeasureRTT) {
a.minTSN2MeasureRTT = a.myNextTSN
rtt := time.Since(c.since).Seconds() * 1000.0
srtt := a.rtoMgr.setNewRTT(rtt)
a.log.Tracef("[%s] SACK: measured-rtt=%f srtt=%f new-rto=%f",
a.name, rtt, srtt, a.rtoMgr.getRTO())
}
}
if a.inFastRecovery && c.tsn == a.fastRecoverExitPoint {
a.log.Debugf("[%s] exit fast-recovery", a.name)
a.inFastRecovery = false
}
}
htna := d.cumulativeTSNAck
// Mark selectively acknowledged chunks as "acked"
for _, g := range d.gapAckBlocks {
for i := g.start; i <= g.end; i++ {
tsn := d.cumulativeTSNAck + uint32(i)
c, ok := a.inflightQueue.get(tsn)
if !ok {
return nil, 0, fmt.Errorf("%w: %v", ErrTSNRequestNotExist, tsn)
}
if !c.acked {
nBytesAcked := a.inflightQueue.markAsAcked(tsn)
// Sum the number of bytes acknowledged per stream
if amount, ok := bytesAckedPerStream[c.streamIdentifier]; ok {
bytesAckedPerStream[c.streamIdentifier] = amount + nBytesAcked
} else {
bytesAckedPerStream[c.streamIdentifier] = nBytesAcked
}
a.log.Tracef("[%s] tsn=%d has been sacked", a.name, c.tsn)
if c.nSent == 1 {
a.minTSN2MeasureRTT = a.myNextTSN
rtt := time.Since(c.since).Seconds() * 1000.0
srtt := a.rtoMgr.setNewRTT(rtt)
a.log.Tracef("[%s] SACK: measured-rtt=%f srtt=%f new-rto=%f",
a.name, rtt, srtt, a.rtoMgr.getRTO())
}
if sna32LT(htna, tsn) {
htna = tsn
}
}
}
}
return bytesAckedPerStream, htna, nil
}
// The caller should hold the lock.
func (a *Association) onCumulativeTSNAckPointAdvanced(totalBytesAcked int) {
// RFC 4096, sec 6.3.2. Retransmission Timer Rules
// R2) Whenever all outstanding data sent to an address have been
// acknowledged, turn off the T3-rtx timer of that address.
if a.inflightQueue.size() == 0 {
a.log.Tracef("[%s] SACK: no more packet in-flight (pending=%d)", a.name, a.pendingQueue.size())
a.t3RTX.stop()
} else {
a.log.Tracef("[%s] T3-rtx timer start (pt2)", a.name)
a.t3RTX.start(a.rtoMgr.getRTO())
}
// Update congestion control parameters
if a.cwnd <= a.ssthresh {
// RFC 4096, sec 7.2.1. Slow-Start
// o When cwnd is less than or equal to ssthresh, an SCTP endpoint MUST
// use the slow-start algorithm to increase cwnd only if the current
// congestion window is being fully utilized, an incoming SACK
// advances the Cumulative TSN Ack Point, and the data sender is not
// in Fast Recovery. Only when these three conditions are met can
// the cwnd be increased; otherwise, the cwnd MUST not be increased.
// If these conditions are met, then cwnd MUST be increased by, at
// most, the lesser of 1) the total size of the previously
// outstanding DATA chunk(s) acknowledged, and 2) the destination's
// path MTU.
if !a.inFastRecovery &&
a.pendingQueue.size() > 0 {
a.cwnd += min32(uint32(totalBytesAcked), a.cwnd) // TCP way
// a.cwnd += min32(uint32(totalBytesAcked), a.mtu) // SCTP way (slow)
a.log.Tracef("[%s] updated cwnd=%d ssthresh=%d acked=%d (SS)",
a.name, a.cwnd, a.ssthresh, totalBytesAcked)
} else {
a.log.Tracef("[%s] cwnd did not grow: cwnd=%d ssthresh=%d acked=%d FR=%v pending=%d",
a.name, a.cwnd, a.ssthresh, totalBytesAcked, a.inFastRecovery, a.pendingQueue.size())
}
} else {
// RFC 4096, sec 7.2.2. Congestion Avoidance
// o Whenever cwnd is greater than ssthresh, upon each SACK arrival
// that advances the Cumulative TSN Ack Point, increase
// partial_bytes_acked by the total number of bytes of all new chunks
// acknowledged in that SACK including chunks acknowledged by the new
// Cumulative TSN Ack and by Gap Ack Blocks.
a.partialBytesAcked += uint32(totalBytesAcked)
// o When partial_bytes_acked is equal to or greater than cwnd and
// before the arrival of the SACK the sender had cwnd or more bytes
// of data outstanding (i.e., before arrival of the SACK, flight size
// was greater than or equal to cwnd), increase cwnd by MTU, and
// reset partial_bytes_acked to (partial_bytes_acked - cwnd).
if a.partialBytesAcked >= a.cwnd && a.pendingQueue.size() > 0 {
a.partialBytesAcked -= a.cwnd
a.cwnd += a.mtu
a.log.Tracef("[%s] updated cwnd=%d ssthresh=%d acked=%d (CA)",
a.name, a.cwnd, a.ssthresh, totalBytesAcked)
}
}
}
// The caller should hold the lock.
func (a *Association) processFastRetransmission(cumTSNAckPoint, htna uint32, cumTSNAckPointAdvanced bool) error {
// HTNA algorithm - RFC 4960 Sec 7.2.4
// Increment missIndicator of each chunks that the SACK reported missing
// when either of the following is met:
// a) Not in fast-recovery
// miss indications are incremented only for missing TSNs prior to the
// highest TSN newly acknowledged in the SACK.
// b) In fast-recovery AND the Cumulative TSN Ack Point advanced
// the miss indications are incremented for all TSNs reported missing
// in the SACK.
if !a.inFastRecovery || (a.inFastRecovery && cumTSNAckPointAdvanced) {
var maxTSN uint32
if !a.inFastRecovery {
// a) increment only for missing TSNs prior to the HTNA
maxTSN = htna
} else {
// b) increment for all TSNs reported missing
maxTSN = cumTSNAckPoint + uint32(a.inflightQueue.size()) + 1
}
for tsn := cumTSNAckPoint + 1; sna32LT(tsn, maxTSN); tsn++ {
c, ok := a.inflightQueue.get(tsn)
if !ok {
return fmt.Errorf("%w: %v", ErrTSNRequestNotExist, tsn)
}
if !c.acked && !c.abandoned() && c.missIndicator < 3 {
c.missIndicator++
if c.missIndicator == 3 {
if !a.inFastRecovery {
// 2) If not in Fast Recovery, adjust the ssthresh and cwnd of the
// destination address(es) to which the missing DATA chunks were
// last sent, according to the formula described in Section 7.2.3.
a.inFastRecovery = true
a.fastRecoverExitPoint = htna
a.ssthresh = max32(a.cwnd/2, 4*a.mtu)
a.cwnd = a.ssthresh
a.partialBytesAcked = 0
a.willRetransmitFast = true
a.log.Tracef("[%s] updated cwnd=%d ssthresh=%d inflight=%d (FR)",
a.name, a.cwnd, a.ssthresh, a.inflightQueue.getNumBytes())
}
}
}
}
}
if a.inFastRecovery && cumTSNAckPointAdvanced {
a.willRetransmitFast = true
}
return nil
}
// The caller should hold the lock.
func (a *Association) handleSack(d *chunkSelectiveAck) error {
a.log.Tracef("[%s] SACK: cumTSN=%d a_rwnd=%d", a.name, d.cumulativeTSNAck, d.advertisedReceiverWindowCredit)
state := a.getState()
if state != established && state != shutdownPending && state != shutdownReceived {
return nil
}
a.stats.incSACKs()
if sna32GT(a.cumulativeTSNAckPoint, d.cumulativeTSNAck) {
// RFC 4960 sec 6.2.1. Processing a Received SACK
// D)
// i) If Cumulative TSN Ack is less than the Cumulative TSN Ack
// Point, then drop the SACK. Since Cumulative TSN Ack is
// monotonically increasing, a SACK whose Cumulative TSN Ack is
// less than the Cumulative TSN Ack Point indicates an out-of-
// order SACK.
a.log.Debugf("[%s] SACK Cumulative ACK %v is older than ACK point %v",
a.name,
d.cumulativeTSNAck,
a.cumulativeTSNAckPoint)
return nil
}
// Process selective ack
bytesAckedPerStream, htna, err := a.processSelectiveAck(d)
if err != nil {
return err
}
var totalBytesAcked int
for _, nBytesAcked := range bytesAckedPerStream {
totalBytesAcked += nBytesAcked
}
cumTSNAckPointAdvanced := false
if sna32LT(a.cumulativeTSNAckPoint, d.cumulativeTSNAck) {
a.log.Tracef("[%s] SACK: cumTSN advanced: %d -> %d",
a.name,
a.cumulativeTSNAckPoint,
d.cumulativeTSNAck)
a.cumulativeTSNAckPoint = d.cumulativeTSNAck
cumTSNAckPointAdvanced = true
a.onCumulativeTSNAckPointAdvanced(totalBytesAcked)
}
for si, nBytesAcked := range bytesAckedPerStream {
if s, ok := a.streams[si]; ok {
a.lock.Unlock()
s.onBufferReleased(nBytesAcked)
a.lock.Lock()
}
}
// New rwnd value
// RFC 4960 sec 6.2.1. Processing a Received SACK
// D)
// ii) Set rwnd equal to the newly received a_rwnd minus the number
// of bytes still outstanding after processing the Cumulative
// TSN Ack and the Gap Ack Blocks.
// bytes acked were already subtracted by markAsAcked() method
bytesOutstanding := uint32(a.inflightQueue.getNumBytes())
if bytesOutstanding >= d.advertisedReceiverWindowCredit {
a.rwnd = 0
} else {
a.rwnd = d.advertisedReceiverWindowCredit - bytesOutstanding
}
err = a.processFastRetransmission(d.cumulativeTSNAck, htna, cumTSNAckPointAdvanced)
if err != nil {
return err
}
if a.useForwardTSN {
// RFC 3758 Sec 3.5 C1
if sna32LT(a.advancedPeerTSNAckPoint, a.cumulativeTSNAckPoint) {
a.advancedPeerTSNAckPoint = a.cumulativeTSNAckPoint
}
// RFC 3758 Sec 3.5 C2
for i := a.advancedPeerTSNAckPoint + 1; ; i++ {
c, ok := a.inflightQueue.get(i)
if !ok {
break
}
if !c.abandoned() {
break
}
a.advancedPeerTSNAckPoint = i
}
// RFC 3758 Sec 3.5 C3
if sna32GT(a.advancedPeerTSNAckPoint, a.cumulativeTSNAckPoint) {
a.willSendForwardTSN = true
}
a.awakeWriteLoop()
}
a.postprocessSack(state, cumTSNAckPointAdvanced)
return nil
}
// The caller must hold the lock. This method was only added because the
// linter was complaining about the "cognitive complexity" of handleSack.
func (a *Association) postprocessSack(state uint32, shouldAwakeWriteLoop bool) {
switch {
case a.inflightQueue.size() > 0:
// Start timer. (noop if already started)
a.log.Tracef("[%s] T3-rtx timer start (pt3)", a.name)
a.t3RTX.start(a.rtoMgr.getRTO())
case state == shutdownPending:
// No more outstanding, send shutdown.
shouldAwakeWriteLoop = true
a.willSendShutdown = true
a.setState(shutdownSent)
case state == shutdownReceived:
// No more outstanding, send shutdown ack.
shouldAwakeWriteLoop = true
a.willSendShutdownAck = true
a.setState(shutdownAckSent)
}
if shouldAwakeWriteLoop {
a.awakeWriteLoop()
}
}
// The caller should hold the lock.
func (a *Association) handleShutdown(_ *chunkShutdown) {
state := a.getState()
switch state {
case established:
if a.inflightQueue.size() > 0 {
a.setState(shutdownReceived)
} else {
// No more outstanding, send shutdown ack.
a.willSendShutdownAck = true
a.setState(shutdownAckSent)
a.awakeWriteLoop()
}
// a.cumulativeTSNAckPoint = c.cumulativeTSNAck
case shutdownSent:
a.willSendShutdownAck = true
a.setState(shutdownAckSent)
a.awakeWriteLoop()
}
}
// The caller should hold the lock.
func (a *Association) handleShutdownAck(_ *chunkShutdownAck) {
state := a.getState()
if state == shutdownSent || state == shutdownAckSent {
a.t2Shutdown.stop()
a.willSendShutdownComplete = true
a.awakeWriteLoop()
}
}
func (a *Association) handleShutdownComplete(_ *chunkShutdownComplete) error {
state := a.getState()
if state == shutdownAckSent {
a.t2Shutdown.stop()
return a.close()
}
return nil
}
func (a *Association) handleAbort(c *chunkAbort) error {
var errStr string
for _, e := range c.errorCauses {
errStr += fmt.Sprintf("(%s)", e)
}
_ = a.close()
return fmt.Errorf("[%s] %w: %s", a.name, ErrChunk, errStr)
}
// createForwardTSN generates ForwardTSN chunk.
// This method will be be called if useForwardTSN is set to false.
// The caller should hold the lock.
func (a *Association) createForwardTSN() *chunkForwardTSN {
// RFC 3758 Sec 3.5 C4
streamMap := map[uint16]uint16{} // to report only once per SI
for i := a.cumulativeTSNAckPoint + 1; sna32LTE(i, a.advancedPeerTSNAckPoint); i++ {
c, ok := a.inflightQueue.get(i)
if !ok {
break
}
ssn, ok := streamMap[c.streamIdentifier]
if !ok {
streamMap[c.streamIdentifier] = c.streamSequenceNumber
} else if sna16LT(ssn, c.streamSequenceNumber) {
// to report only once with greatest SSN
streamMap[c.streamIdentifier] = c.streamSequenceNumber
}
}
fwdtsn := &chunkForwardTSN{
newCumulativeTSN: a.advancedPeerTSNAckPoint,
streams: []chunkForwardTSNStream{},
}
var streamStr string
for si, ssn := range streamMap {
streamStr += fmt.Sprintf("(si=%d ssn=%d)", si, ssn)
fwdtsn.streams = append(fwdtsn.streams, chunkForwardTSNStream{
identifier: si,
sequence: ssn,
})
}
a.log.Tracef("[%s] building fwdtsn: newCumulativeTSN=%d cumTSN=%d - %s", a.name, fwdtsn.newCumulativeTSN, a.cumulativeTSNAckPoint, streamStr)
return fwdtsn
}
// createPacket wraps chunks in a packet.
// The caller should hold the read lock.
func (a *Association) createPacket(cs []chunk) *packet {
return &packet{
verificationTag: a.peerVerificationTag,
sourcePort: a.sourcePort,
destinationPort: a.destinationPort,
chunks: cs,
}
}
// The caller should hold the lock.
func (a *Association) handleReconfig(c *chunkReconfig) ([]*packet, error) {
a.log.Tracef("[%s] handleReconfig", a.name)
pp := make([]*packet, 0)
p, err := a.handleReconfigParam(c.paramA)
if err != nil {
return nil, err
}
if p != nil {
pp = append(pp, p)
}
if c.paramB != nil {
p, err = a.handleReconfigParam(c.paramB)
if err != nil {
return nil, err
}
if p != nil {
pp = append(pp, p)
}
}
return pp, nil
}
// The caller should hold the lock.
func (a *Association) handleForwardTSN(c *chunkForwardTSN) []*packet {
a.log.Tracef("[%s] FwdTSN: %s", a.name, c.String())
if !a.useForwardTSN {
a.log.Warn("[%s] received FwdTSN but not enabled")
// Return an error chunk
cerr := &chunkError{
errorCauses: []errorCause{&errorCauseUnrecognizedChunkType{}},
}
outbound := &packet{}
outbound.verificationTag = a.peerVerificationTag
outbound.sourcePort = a.sourcePort
outbound.destinationPort = a.destinationPort
outbound.chunks = []chunk{cerr}
return []*packet{outbound}
}
// From RFC 3758 Sec 3.6:
// Note, if the "New Cumulative TSN" value carried in the arrived
// FORWARD TSN chunk is found to be behind or at the current cumulative
// TSN point, the data receiver MUST treat this FORWARD TSN as out-of-
// date and MUST NOT update its Cumulative TSN. The receiver SHOULD
// send a SACK to its peer (the sender of the FORWARD TSN) since such a
// duplicate may indicate the previous SACK was lost in the network.
a.log.Tracef("[%s] should send ack? newCumTSN=%d peerLastTSN=%d",
a.name, c.newCumulativeTSN, a.peerLastTSN)
if sna32LTE(c.newCumulativeTSN, a.peerLastTSN) {
a.log.Tracef("[%s] sending ack on Forward TSN", a.name)
a.ackState = ackStateImmediate
a.ackTimer.stop()
a.awakeWriteLoop()
return nil
}
// From RFC 3758 Sec 3.6:
// the receiver MUST perform the same TSN handling, including duplicate
// detection, gap detection, SACK generation, cumulative TSN
// advancement, etc. as defined in RFC 2960 [2]---with the following
// exceptions and additions.
// When a FORWARD TSN chunk arrives, the data receiver MUST first update
// its cumulative TSN point to the value carried in the FORWARD TSN
// chunk,
// Advance peerLastTSN
for sna32LT(a.peerLastTSN, c.newCumulativeTSN) {
a.payloadQueue.pop(a.peerLastTSN + 1) // may not exist
a.peerLastTSN++
}
// Report new peerLastTSN value and abandoned largest SSN value to
// corresponding streams so that the abandoned chunks can be removed
// from the reassemblyQueue.
for _, forwarded := range c.streams {
if s, ok := a.streams[forwarded.identifier]; ok {
s.handleForwardTSNForOrdered(forwarded.sequence)
}
}
// TSN may be forewared for unordered chunks. ForwardTSN chunk does not
// report which stream identifier it skipped for unordered chunks.
// Therefore, we need to broadcast this event to all existing streams for
// unordered chunks.
// See https://github.com/pion/sctp/issues/106
for _, s := range a.streams {
s.handleForwardTSNForUnordered(c.newCumulativeTSN)
}
return a.handlePeerLastTSNAndAcknowledgement(false)
}
func (a *Association) sendResetRequest(streamIdentifier uint16) error {
a.lock.Lock()
defer a.lock.Unlock()
state := a.getState()
if state != established {
return fmt.Errorf("%w: state=%s", ErrResetPacketInStateNotExist,
getAssociationStateString(state))
}
// Create DATA chunk which only contains valid stream identifier with
// nil userData and use it as a EOS from the stream.
c := &chunkPayloadData{
streamIdentifier: streamIdentifier,
beginningFragment: true,
endingFragment: true,
userData: nil,
}
a.pendingQueue.push(c)
a.awakeWriteLoop()
return nil
}
// The caller should hold the lock.
func (a *Association) handleReconfigParam(raw param) (*packet, error) {
switch p := raw.(type) {
case *paramOutgoingResetRequest:
a.log.Tracef("[%s] handleReconfigParam (OutgoingResetRequest)", a.name)
a.reconfigRequests[p.reconfigRequestSequenceNumber] = p
resp := a.resetStreamsIfAny(p)
if resp != nil {
return resp, nil
}
return nil, nil //nolint:nilnil
case *paramReconfigResponse:
a.log.Tracef("[%s] handleReconfigParam (ReconfigResponse)", a.name)
delete(a.reconfigs, p.reconfigResponseSequenceNumber)
if len(a.reconfigs) == 0 {
a.tReconfig.stop()
}
return nil, nil //nolint:nilnil
default:
return nil, fmt.Errorf("%w: %t", ErrParamterType, p)
}
}
// The caller should hold the lock.
func (a *Association) resetStreamsIfAny(p *paramOutgoingResetRequest) *packet {
result := reconfigResultSuccessPerformed
if sna32LTE(p.senderLastTSN, a.peerLastTSN) {
a.log.Debugf("[%s] resetStream(): senderLastTSN=%d <= peerLastTSN=%d",
a.name, p.senderLastTSN, a.peerLastTSN)
for _, id := range p.streamIdentifiers {
s, ok := a.streams[id]
if !ok {
continue
}
a.lock.Unlock()
s.onInboundStreamReset()
a.lock.Lock()
a.log.Debugf("[%s] deleting stream %d", a.name, id)
delete(a.streams, s.streamIdentifier)
}
delete(a.reconfigRequests, p.reconfigRequestSequenceNumber)
} else {
a.log.Debugf("[%s] resetStream(): senderLastTSN=%d > peerLastTSN=%d",
a.name, p.senderLastTSN, a.peerLastTSN)
result = reconfigResultInProgress
}
return a.createPacket([]chunk{&chunkReconfig{
paramA: ¶mReconfigResponse{
reconfigResponseSequenceNumber: p.reconfigRequestSequenceNumber,
result: result,
},
}})
}
// Move the chunk peeked with a.pendingQueue.peek() to the inflightQueue.
// The caller should hold the lock.
func (a *Association) movePendingDataChunkToInflightQueue(c *chunkPayloadData) {
if err := a.pendingQueue.pop(c); err != nil {
a.log.Errorf("[%s] failed to pop from pending queue: %s", a.name, err.Error())
}
// Mark all fragements are in-flight now
if c.endingFragment {
c.setAllInflight()
}
// Assign TSN
c.tsn = a.generateNextTSN()
c.since = time.Now() // use to calculate RTT and also for maxPacketLifeTime
c.nSent = 1 // being sent for the first time
a.checkPartialReliabilityStatus(c)
a.log.Tracef("[%s] sending ppi=%d tsn=%d ssn=%d sent=%d len=%d (%v,%v)",
a.name, c.payloadType, c.tsn, c.streamSequenceNumber, c.nSent, len(c.userData), c.beginningFragment, c.endingFragment)
a.inflightQueue.pushNoCheck(c)
}
// popPendingDataChunksToSend pops chunks from the pending queues as many as
// the cwnd and rwnd allows to send.
// The caller should hold the lock.
func (a *Association) popPendingDataChunksToSend() ([]*chunkPayloadData, []uint16) {
chunks := []*chunkPayloadData{}
var sisToReset []uint16 // stream identifieres to reset
if a.pendingQueue.size() > 0 {
// RFC 4960 sec 6.1. Transmission of DATA Chunks
// A) At any given time, the data sender MUST NOT transmit new data to
// any destination transport address if its peer's rwnd indicates
// that the peer has no buffer space (i.e., rwnd is 0; see Section
// 6.2.1). However, regardless of the value of rwnd (including if it
// is 0), the data sender can always have one DATA chunk in flight to
// the receiver if allowed by cwnd (see rule B, below).
for {
c := a.pendingQueue.peek()
if c == nil {
break // no more pending data
}
dataLen := uint32(len(c.userData))
if dataLen == 0 {
sisToReset = append(sisToReset, c.streamIdentifier)
err := a.pendingQueue.pop(c)
if err != nil {
a.log.Errorf("failed to pop from pending queue: %s", err.Error())
}
continue
}
if uint32(a.inflightQueue.getNumBytes())+dataLen > a.cwnd {
break // would exceeds cwnd
}
if dataLen > a.rwnd {
break // no more rwnd
}
a.rwnd -= dataLen
a.movePendingDataChunkToInflightQueue(c)
chunks = append(chunks, c)
}
// the data sender can always have one DATA chunk in flight to the receiver
if len(chunks) == 0 && a.inflightQueue.size() == 0 {
// Send zero window probe
c := a.pendingQueue.peek()
if c != nil {
a.movePendingDataChunkToInflightQueue(c)
chunks = append(chunks, c)
}
}
}
return chunks, sisToReset
}
// bundleDataChunksIntoPackets packs DATA chunks into packets. It tries to bundle
// DATA chunks into a packet so long as the resulting packet size does not exceed
// the path MTU.
// The caller should hold the lock.
func (a *Association) bundleDataChunksIntoPackets(chunks []*chunkPayloadData) []*packet {
packets := []*packet{}
chunksToSend := []chunk{}
bytesInPacket := int(commonHeaderSize)
for _, c := range chunks {
// RFC 4960 sec 6.1. Transmission of DATA Chunks
// Multiple DATA chunks committed for transmission MAY be bundled in a
// single packet. Furthermore, DATA chunks being retransmitted MAY be
// bundled with new DATA chunks, as long as the resulting packet size
// does not exceed the path MTU.
if bytesInPacket+len(c.userData) > int(a.mtu) {
packets = append(packets, a.createPacket(chunksToSend))
chunksToSend = []chunk{}
bytesInPacket = int(commonHeaderSize)
}
chunksToSend = append(chunksToSend, c)
bytesInPacket += int(dataChunkHeaderSize) + len(c.userData)
}
if len(chunksToSend) > 0 {
packets = append(packets, a.createPacket(chunksToSend))
}
return packets
}
// sendPayloadData sends the data chunks.
func (a *Association) sendPayloadData(chunks []*chunkPayloadData) error {
a.lock.Lock()
defer a.lock.Unlock()
state := a.getState()
if state != established {
return fmt.Errorf("%w: state=%s", ErrPayloadDataStateNotExist,
getAssociationStateString(state))
}
// Push the chunks into the pending queue first.
for _, c := range chunks {
a.pendingQueue.push(c)
}
a.awakeWriteLoop()
return nil
}
// The caller should hold the lock.
func (a *Association) checkPartialReliabilityStatus(c *chunkPayloadData) {
if !a.useForwardTSN {
return
}
// draft-ietf-rtcweb-data-protocol-09.txt section 6
// 6. Procedures
// All Data Channel Establishment Protocol messages MUST be sent using
// ordered delivery and reliable transmission.
//
if c.payloadType == PayloadTypeWebRTCDCEP {
return
}
// PR-SCTP
if s, ok := a.streams[c.streamIdentifier]; ok {
s.lock.RLock()
if s.reliabilityType == ReliabilityTypeRexmit {
if c.nSent >= s.reliabilityValue {
c.setAbandoned(true)
a.log.Tracef("[%s] marked as abandoned: tsn=%d ppi=%d (remix: %d)", a.name, c.tsn, c.payloadType, c.nSent)
}
} else if s.reliabilityType == ReliabilityTypeTimed {
elapsed := int64(time.Since(c.since).Seconds() * 1000)
if elapsed >= int64(s.reliabilityValue) {
c.setAbandoned(true)
a.log.Tracef("[%s] marked as abandoned: tsn=%d ppi=%d (timed: %d)", a.name, c.tsn, c.payloadType, elapsed)
}
}
s.lock.RUnlock()
} else {
a.log.Errorf("[%s] stream %d not found)", a.name, c.streamIdentifier)
}
}
// getDataPacketsToRetransmit is called when T3-rtx is timed out and retransmit outstanding data chunks
// that are not acked or abandoned yet.
// The caller should hold the lock.
func (a *Association) getDataPacketsToRetransmit() []*packet {
awnd := min32(a.cwnd, a.rwnd)
chunks := []*chunkPayloadData{}
var bytesToSend int
var done bool
for i := 0; !done; i++ {
c, ok := a.inflightQueue.get(a.cumulativeTSNAckPoint + uint32(i) + 1)
if !ok {
break // end of pending data
}
if !c.retransmit {
continue
}
if i == 0 && int(a.rwnd) < len(c.userData) {
// Send it as a zero window probe
done = true
} else if bytesToSend+len(c.userData) > int(awnd) {
break
}
// reset the retransmit flag not to retransmit again before the next
// t3-rtx timer fires
c.retransmit = false
bytesToSend += len(c.userData)
c.nSent++
a.checkPartialReliabilityStatus(c)
a.log.Tracef("[%s] retransmitting tsn=%d ssn=%d sent=%d", a.name, c.tsn, c.streamSequenceNumber, c.nSent)
chunks = append(chunks, c)
}
return a.bundleDataChunksIntoPackets(chunks)
}
// generateNextTSN returns the myNextTSN and increases it. The caller should hold the lock.
// The caller should hold the lock.
func (a *Association) generateNextTSN() uint32 {
tsn := a.myNextTSN
a.myNextTSN++
return tsn
}
// generateNextRSN returns the myNextRSN and increases it. The caller should hold the lock.
// The caller should hold the lock.
func (a *Association) generateNextRSN() uint32 {
rsn := a.myNextRSN
a.myNextRSN++
return rsn
}
func (a *Association) createSelectiveAckChunk() *chunkSelectiveAck {
sack := &chunkSelectiveAck{}
sack.cumulativeTSNAck = a.peerLastTSN
sack.advertisedReceiverWindowCredit = a.getMyReceiverWindowCredit()
sack.duplicateTSN = a.payloadQueue.popDuplicates()
sack.gapAckBlocks = a.payloadQueue.getGapAckBlocks(a.peerLastTSN)
return sack
}
func pack(p *packet) []*packet {
return []*packet{p}
}
func (a *Association) handleChunkStart() {
a.lock.Lock()
defer a.lock.Unlock()
a.delayedAckTriggered = false
a.immediateAckTriggered = false
}
func (a *Association) handleChunkEnd() {
a.lock.Lock()
defer a.lock.Unlock()
if a.immediateAckTriggered {
a.ackState = ackStateImmediate
a.ackTimer.stop()
a.awakeWriteLoop()
} else if a.delayedAckTriggered {
// Will send delayed ack in the next ack timeout
a.ackState = ackStateDelay
a.ackTimer.start()
}
}
func (a *Association) handleChunk(p *packet, c chunk) error {
a.lock.Lock()
defer a.lock.Unlock()
var packets []*packet
var err error
if _, err = c.check(); err != nil {
a.log.Errorf("[ %s ] failed validating chunk: %s ", a.name, err)
return nil
}
isAbort := false
switch c := c.(type) {
case *chunkInit:
packets, err = a.handleInit(p, c)
case *chunkInitAck:
err = a.handleInitAck(p, c)
case *chunkAbort:
isAbort = true
err = a.handleAbort(c)
case *chunkError:
var errStr string
for _, e := range c.errorCauses {
errStr += fmt.Sprintf("(%s)", e)
}
a.log.Debugf("[%s] Error chunk, with following errors: %s", a.name, errStr)
case *chunkHeartbeat:
packets = a.handleHeartbeat(c)
case *chunkCookieEcho:
packets = a.handleCookieEcho(c)
case *chunkCookieAck:
a.handleCookieAck()
case *chunkPayloadData:
packets = a.handleData(c)
case *chunkSelectiveAck:
err = a.handleSack(c)
case *chunkReconfig:
packets, err = a.handleReconfig(c)
case *chunkForwardTSN:
packets = a.handleForwardTSN(c)
case *chunkShutdown:
a.handleShutdown(c)
case *chunkShutdownAck:
a.handleShutdownAck(c)
case *chunkShutdownComplete:
err = a.handleShutdownComplete(c)
default:
err = ErrChunkTypeUnhandled
}
// Log and return, the only condition that is fatal is a ABORT chunk
if err != nil {
if isAbort {
return err
}
a.log.Errorf("Failed to handle chunk: %v", err)
return nil
}
if len(packets) > 0 {
a.controlQueue.pushAll(packets)
a.awakeWriteLoop()
}
return nil
}
func (a *Association) onRetransmissionTimeout(id int, nRtos uint) {
a.lock.Lock()
defer a.lock.Unlock()
if id == timerT1Init {
err := a.sendInit()
if err != nil {
a.log.Debugf("[%s] failed to retransmit init (nRtos=%d): %v", a.name, nRtos, err)
}
return
}
if id == timerT1Cookie {
err := a.sendCookieEcho()
if err != nil {
a.log.Debugf("[%s] failed to retransmit cookie-echo (nRtos=%d): %v", a.name, nRtos, err)
}
return
}
if id == timerT2Shutdown {
a.log.Debugf("[%s] retransmission of shutdown timeout (nRtos=%d): %v", a.name, nRtos)
state := a.getState()
switch state {
case shutdownSent:
a.willSendShutdown = true
a.awakeWriteLoop()
case shutdownAckSent:
a.willSendShutdownAck = true
a.awakeWriteLoop()
}
}
if id == timerT3RTX {
a.stats.incT3Timeouts()
// RFC 4960 sec 6.3.3
// E1) For the destination address for which the timer expires, adjust
// its ssthresh with rules defined in Section 7.2.3 and set the
// cwnd <- MTU.
// RFC 4960 sec 7.2.3
// When the T3-rtx timer expires on an address, SCTP should perform slow
// start by:
// ssthresh = max(cwnd/2, 4*MTU)
// cwnd = 1*MTU
a.ssthresh = max32(a.cwnd/2, 4*a.mtu)
a.cwnd = a.mtu
a.log.Tracef("[%s] updated cwnd=%d ssthresh=%d inflight=%d (RTO)",
a.name, a.cwnd, a.ssthresh, a.inflightQueue.getNumBytes())
// RFC 3758 sec 3.5
// A5) Any time the T3-rtx timer expires, on any destination, the sender
// SHOULD try to advance the "Advanced.Peer.Ack.Point" by following
// the procedures outlined in C2 - C5.
if a.useForwardTSN {
// RFC 3758 Sec 3.5 C2
for i := a.advancedPeerTSNAckPoint + 1; ; i++ {
c, ok := a.inflightQueue.get(i)
if !ok {
break
}
if !c.abandoned() {
break
}
a.advancedPeerTSNAckPoint = i
}
// RFC 3758 Sec 3.5 C3
if sna32GT(a.advancedPeerTSNAckPoint, a.cumulativeTSNAckPoint) {
a.willSendForwardTSN = true
}
}
a.log.Debugf("[%s] T3-rtx timed out: nRtos=%d cwnd=%d ssthresh=%d", a.name, nRtos, a.cwnd, a.ssthresh)
/*
a.log.Debugf(" - advancedPeerTSNAckPoint=%d", a.advancedPeerTSNAckPoint)
a.log.Debugf(" - cumulativeTSNAckPoint=%d", a.cumulativeTSNAckPoint)
a.inflightQueue.updateSortedKeys()
for i, tsn := range a.inflightQueue.sorted {
if c, ok := a.inflightQueue.get(tsn); ok {
a.log.Debugf(" - [%d] tsn=%d acked=%v abandoned=%v (%v,%v) len=%d",
i, c.tsn, c.acked, c.abandoned(), c.beginningFragment, c.endingFragment, len(c.userData))
}
}
*/
a.inflightQueue.markAllToRetrasmit()
a.awakeWriteLoop()
return
}
if id == timerReconfig {
a.willRetransmitReconfig = true
a.awakeWriteLoop()
}
}
func (a *Association) onRetransmissionFailure(id int) {
a.lock.Lock()
defer a.lock.Unlock()
if id == timerT1Init {
a.log.Errorf("[%s] retransmission failure: T1-init", a.name)
a.handshakeCompletedCh <- ErrHandshakeInitAck
return
}
if id == timerT1Cookie {
a.log.Errorf("[%s] retransmission failure: T1-cookie", a.name)
a.handshakeCompletedCh <- ErrHandshakeCookieEcho
return
}
if id == timerT2Shutdown {
a.log.Errorf("[%s] retransmission failure: T2-shutdown", a.name)
return
}
if id == timerT3RTX {
// T3-rtx timer will not fail by design
// Justifications:
// * ICE would fail if the connectivity is lost
// * WebRTC spec is not clear how this incident should be reported to ULP
a.log.Errorf("[%s] retransmission failure: T3-rtx (DATA)", a.name)
return
}
}
func (a *Association) onAckTimeout() {
a.lock.Lock()
defer a.lock.Unlock()
a.log.Tracef("[%s] ack timed out (ackState: %d)", a.name, a.ackState)
a.stats.incAckTimeouts()
a.ackState = ackStateImmediate
a.awakeWriteLoop()
}
// bufferedAmount returns total amount (in bytes) of currently buffered user data.
// This is used only by testing.
func (a *Association) bufferedAmount() int {
a.lock.RLock()
defer a.lock.RUnlock()
return a.pendingQueue.getNumBytes() + a.inflightQueue.getNumBytes()
}
// MaxMessageSize returns the maximum message size you can send.
func (a *Association) MaxMessageSize() uint32 {
return atomic.LoadUint32(&a.maxMessageSize)
}
// SetMaxMessageSize sets the maximum message size you can send.
func (a *Association) SetMaxMessageSize(maxMsgSize uint32) {
atomic.StoreUint32(&a.maxMessageSize, maxMsgSize)
}
|