| 1 |
// SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly> |
| 2 |
// SPDX-License-Identifier: MIT |
| 3 |
|
| 4 |
package sctp |
| 5 |
|
| 6 |
import ( |
| 7 |
"bytes" |
| 8 |
"context" |
| 9 |
"encoding/binary" |
| 10 |
"errors" |
| 11 |
"fmt" |
| 12 |
"io" |
| 13 |
"math" |
| 14 |
"net" |
| 15 |
"strings" |
| 16 |
"sync" |
| 17 |
"sync/atomic" |
| 18 |
"time" |
| 19 |
|
| 20 |
"github.com/pion/logging" |
| 21 |
"github.com/pion/randutil" |
| •22 |
"github.com/pion/transport/v3/deadline" |
| 23 |
) |
| 24 |
|
| 25 |
// Port 5000 shows up in examples for SDPs used by WebRTC. Since this implementation |
| 26 |
// assumes it will be used by DTLS over UDP, the port is only meaningful for de-multiplexing |
| 27 |
// but more-so verification. |
| 28 |
// Example usage: https://www.rfc-editor.org/rfc/rfc8841.html#section-13.1-2 |
| 29 |
const defaultSCTPSrcDstPort = 5000 |
| 30 |
|
| 31 |
// Use global random generator to properly seed by crypto grade random. |
| 32 |
var globalMathRandomGenerator = randutil.NewMathRandomGenerator() // nolint:gochecknoglobals |
| 33 |
|
| 34 |
// Generates a non-zero Initiate tag. |
| 35 |
func generateInitiateTag() uint32 { |
| 36 |
for { |
| 37 |
if u := globalMathRandomGenerator.Uint32(); u != 0 { |
| 38 |
return u |
| 39 |
} |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
// Association errors. |
| 44 |
var ( |
| 45 |
ErrChunk = errors.New("abort chunk, with following errors") |
| 46 |
ErrShutdownNonEstablished = errors.New("shutdown called in non-established state") |
| 47 |
ErrAssociationClosedBeforeConn = errors.New("association closed before connecting") |
| 48 |
ErrAssociationClosed = errors.New("association closed") |
| 49 |
ErrSilentlyDiscard = errors.New("silently discard") |
| 50 |
ErrInitNotStoredToSend = errors.New("the init not stored to send") |
| 51 |
ErrCookieEchoNotStoredToSend = errors.New("cookieEcho not stored to send") |
| 52 |
ErrSCTPPacketSourcePortZero = errors.New("sctp packet must not have a source port of 0") |
| 53 |
ErrSCTPPacketDestinationPortZero = errors.New("sctp packet must not have a destination port of 0") |
| 54 |
ErrInitChunkBundled = errors.New("init chunk must not be bundled with any other chunk") |
| 55 |
ErrInitChunkVerifyTagNotZero = errors.New( |
| 56 |
"init chunk expects a verification tag of 0 on the packet when out-of-the-blue", |
| 57 |
) |
| 58 |
ErrHandleInitState = errors.New("todo: handle Init when in state") |
| 59 |
ErrInitAckNoCookie = errors.New("no cookie in InitAck") |
| 60 |
ErrInflightQueueTSNPop = errors.New("unable to be popped from inflight queue TSN") |
| 61 |
ErrTSNRequestNotExist = errors.New("requested non-existent TSN") |
| 62 |
ErrResetPacketInStateNotExist = errors.New("sending reset packet in non-established state") |
| 63 |
ErrParamterType = errors.New("unexpected parameter type") |
| 64 |
ErrPayloadDataStateNotExist = errors.New("sending payload data in non-established state") |
| 65 |
ErrChunkTypeUnhandled = errors.New("unhandled chunk type") |
| 66 |
ErrHandshakeInitAck = errors.New("handshake failed (INIT ACK)") |
| 67 |
ErrHandshakeCookieEcho = errors.New("handshake failed (COOKIE ECHO)") |
| 68 |
ErrTooManyReconfigRequests = errors.New("too many outstanding reconfig requests") |
| 69 |
) |
| 70 |
|
| 71 |
const ( |
| 72 |
receiveMTU uint32 = 8192 // MTU for inbound packet (from DTLS) |
| 73 |
initialMTU uint32 = 1191 // initial MTU for outgoing packets (to DTLS) |
| 74 |
initialRecvBufSize uint32 = 1024 * 1024 |
| 75 |
commonHeaderSize uint32 = packetHeaderSize |
| 76 |
dataChunkHeaderSize uint32 = chunkHeaderSize + payloadDataHeaderSize |
| 77 |
iDataChunkHeaderSize uint32 = chunkHeaderSize + iDataHeaderSize |
| 78 |
defaultMaxMessageSize uint32 = 65536 |
| 79 |
) |
| 80 |
|
| 81 |
func payloadDataChunkHeaderSize(useInterleaving bool) uint32 { |
| 82 |
if useInterleaving { |
| 83 |
return iDataChunkHeaderSize |
| 84 |
} |
| 85 |
|
| 86 |
return dataChunkHeaderSize |
| 87 |
} |
| 88 |
|
| 89 |
func maxPayloadSizeForMTU(mtu uint32, useInterleaving bool) uint32 { |
| 90 |
headerSize := commonHeaderSize + payloadDataChunkHeaderSize(useInterleaving) |
| 91 |
if mtu <= headerSize { |
| 92 |
return 0 |
| 93 |
} |
| 94 |
|
| 95 |
payloadSize := mtu - headerSize |
| 96 |
|
| 97 |
return payloadSize - payloadSize%paddingMultiple |
| 98 |
} |
| 99 |
|
| 100 |
func validateMTU(mtu uint32) error { |
| 101 |
if mtu == 0 { |
| 102 |
return errZeroMTUOption |
| 103 |
} |
| 104 |
if maxPayloadSizeForMTU(mtu, true) == 0 { |
| 105 |
return errMTUTooSmallOption |
| 106 |
} |
| 107 |
|
| 108 |
return nil |
| 109 |
} |
| 110 |
|
| 111 |
// PartialReliabilityMode indicates the negotiated partial reliability mode. |
| 112 |
type PartialReliabilityMode int |
| 113 |
|
| 114 |
// PartialReliabilityMode values. |
| 115 |
const ( |
| 116 |
PartialReliabilityModeNone PartialReliabilityMode = iota |
| 117 |
PartialReliabilityModeForwardTSN |
| 118 |
PartialReliabilityModeIForwardTSN |
| 119 |
) |
| 120 |
|
| 121 |
// AssociationMetadata describes negotiated association capabilities. |
| 122 |
type AssociationMetadata struct { |
| 123 |
// MessageInterleavingEnabled indicates whether RFC 8260 user message interleaving was negotiated. |
| 124 |
MessageInterleavingEnabled bool `json:"messageInterleavingEnabled"` |
| 125 |
|
| 126 |
// PartialReliabilityMode indicates which FORWARD-TSN variant is active. |
| 127 |
PartialReliabilityMode PartialReliabilityMode `json:"partialReliabilityMode"` |
| 128 |
|
| 129 |
// ZeroChecksumSendingEnabled indicates whether outgoing packets use zero checksum. |
| 130 |
ZeroChecksumSendingEnabled bool `json:"zeroChecksumSendingEnabled"` |
| 131 |
|
| 132 |
// ZeroChecksumReceivingEnabled indicates whether incoming packets may use zero checksum. |
| 133 |
ZeroChecksumReceivingEnabled bool `json:"zeroChecksumReceivingEnabled"` |
| 134 |
} |
| 135 |
|
| 136 |
// association state enums. |
| 137 |
const ( |
| 138 |
closed uint32 = iota |
| 139 |
cookieWait |
| 140 |
cookieEchoed |
| 141 |
established |
| 142 |
shutdownAckSent |
| 143 |
shutdownPending |
| 144 |
shutdownReceived |
| 145 |
shutdownSent |
| 146 |
) |
| 147 |
|
| 148 |
// retransmission timer IDs. |
| 149 |
const ( |
| 150 |
timerT1Init int = iota |
| 151 |
timerT1Cookie |
| 152 |
timerT2Shutdown |
| 153 |
timerT3RTX |
| 154 |
timerReconfig |
| 155 |
) |
| 156 |
|
| 157 |
// ack mode (for testing). |
| 158 |
const ( |
| 159 |
ackModeNormal int = iota |
| 160 |
ackModeNoDelay |
| 161 |
ackModeAlwaysDelay |
| 162 |
) |
| 163 |
|
| 164 |
// ack transmission state. |
| 165 |
const ( |
| 166 |
ackStateIdle int = iota // ack timer is off |
| 167 |
ackStateImmediate // will send ack immediately |
| 168 |
ackStateDelay // ack timer is on (ack is being delayed) |
| 169 |
) |
| 170 |
|
| 171 |
// other constants. |
| 172 |
const ( |
| 173 |
acceptChSize = 16 |
| 174 |
// avgChunkSize is an estimate of the average chunk size. There is no theory behind |
| 175 |
// this estimate. |
| 176 |
avgChunkSize = 500 |
| 177 |
// minTSNOffset is the minimum offset over the cummulative TSN that we will enqueue |
| 178 |
// irrespective of the receive buffer size |
| 179 |
// see getMaxTSNOffset. |
| 180 |
minTSNOffset = 2000 |
| 181 |
// maxTSNOffset is the maximum offset over the cummulative TSN that we will enqueue |
| 182 |
// irrespective of the receive buffer size |
| 183 |
// see getMaxTSNOffset. |
| 184 |
maxTSNOffset = 40000 |
| 185 |
// maxReconfigRequests is the maximum number of reconfig requests we will keep outstanding. |
| 186 |
maxReconfigRequests = 1000 |
| 187 |
|
| 188 |
// TLR Adaptive burst mitigation uses quarter-MTU units. |
| 189 |
// 1 MTU == 4 units, 0.25 MTU == 1 unit. |
| 190 |
tlrUnitsPerMTU = 4 |
| 191 |
|
| 192 |
// Default burst limits. |
| 193 |
tlrBurstDefaultFirstRTT = 16 // 4.0 MTU |
| 194 |
tlrBurstDefaultLaterRTT = 8 // 2.0 MTU |
| 195 |
|
| 196 |
// Minimum burst limits. |
| 197 |
tlrBurstMinFirstRTT = 8 // 2.0 MTU |
| 198 |
tlrBurstMinLaterRTT = 5 // 1.25 MTU |
| 199 |
|
| 200 |
// Adaptation steps. |
| 201 |
tlrBurstStepDownFirstRTT = 4 // reduce by 1.0 MTU |
| 202 |
tlrBurstStepDownLaterRTT = 1 // reduce by 0.25 MTU |
| 203 |
|
| 204 |
tlrGoodOpsResetThreshold = 16 |
| 205 |
) |
| 206 |
|
| 207 |
func getAssociationStateString(assoc uint32) string { |
| 208 |
switch assoc { |
| 209 |
case closed: |
| 210 |
return "Closed" |
| 211 |
case cookieWait: |
| 212 |
return "CookieWait" |
| 213 |
case cookieEchoed: |
| 214 |
return "CookieEchoed" |
| 215 |
case established: |
| 216 |
return "Established" |
| 217 |
case shutdownPending: |
| 218 |
return "ShutdownPending" |
| 219 |
case shutdownSent: |
| 220 |
return "ShutdownSent" |
| 221 |
case shutdownReceived: |
| 222 |
return "ShutdownReceived" |
| 223 |
case shutdownAckSent: |
| 224 |
return "ShutdownAckSent" |
| 225 |
default: |
| 226 |
return fmt.Sprintf("Invalid association state %d", assoc) |
| 227 |
} |
| 228 |
} |
| 229 |
|
| 230 |
// Association represents an SCTP association |
| 231 |
// 13.2. Parameters Necessary per Association (i.e., the TCB) |
| 232 |
// |
| 233 |
// Peer : Tag value to be sent in every packet and is received |
| 234 |
// Verification: in the INIT or INIT ACK chunk. |
| 235 |
// Tag : |
| 236 |
// State : A state variable indicating what state the association |
| 237 |
// : is in, i.e., COOKIE-WAIT, COOKIE-ECHOED, ESTABLISHED, |
| 238 |
// : SHUTDOWN-PENDING, SHUTDOWN-SENT, SHUTDOWN-RECEIVED, |
| 239 |
// : SHUTDOWN-ACK-SENT. |
| 240 |
// |
| 241 |
// Note: No "CLOSED" state is illustrated since if a |
| 242 |
// association is "CLOSED" its TCB SHOULD be removed. |
| 243 |
// Note: By nature of an Association being constructed with one net.Conn, |
| 244 |
// it is not a multi-home supporting implementation of SCTP. |
| 245 |
type Association struct { |
| 246 |
bytesReceived uint64 |
| 247 |
bytesSent uint64 |
| 248 |
|
| 249 |
lock sync.RWMutex |
| 250 |
|
| 251 |
netConn net.Conn |
| 252 |
netConnCloseOnce sync.Once |
| 253 |
netConnCloseErr error |
| 254 |
|
| 255 |
peerVerificationTag uint32 |
| 256 |
myVerificationTag uint32 |
| 257 |
state uint32 |
| 258 |
initialTSN uint32 |
| 259 |
myNextTSN uint32 // nextTSN |
| 260 |
minTSN2MeasureRTT uint32 // for RTT measurement |
| 261 |
willSendForwardTSN bool |
| 262 |
willRetransmitFast bool |
| 263 |
willRetransmitReconfig bool |
| 264 |
|
| 265 |
willSendShutdown bool |
| 266 |
willSendShutdownAck bool |
| 267 |
willSendShutdownComplete bool |
| 268 |
shutdownCompletePending bool |
| 269 |
|
| 270 |
willSendAbort bool |
| 271 |
willSendAbortCause errorCause |
| 272 |
abortSentOnce sync.Once |
| 273 |
abortSentCh chan struct{} |
| 274 |
|
| 275 |
// Reconfig |
| 276 |
myNextRSN uint32 |
| 277 |
reconfigs map[uint32]*chunkReconfig |
| 278 |
reconfigRequests map[uint32]*paramOutgoingResetRequest |
| 279 |
|
| 280 |
// Non-RFC internal data |
| 281 |
sourcePort uint16 |
| 282 |
destinationPort uint16 |
| 283 |
myMaxNumInboundStreams uint16 |
| 284 |
myMaxNumOutboundStreams uint16 |
| 285 |
myCookie *paramStateCookie |
| 286 |
payloadQueue *receivePayloadQueue |
| 287 |
inflightQueue *payloadQueue |
| 288 |
pendingQueue *pendingQueue |
| 289 |
controlQueue *controlQueue |
| 290 |
mtu uint32 |
| 291 |
maxPayloadSize uint32 // max DATA chunk payload size |
| 292 |
srtt atomic.Value // type float64 |
| 293 |
cumulativeTSNAckPoint uint32 |
| 294 |
advancedPeerTSNAckPoint uint32 |
| 295 |
useForwardTSN bool |
| 296 |
useIForwardTSN bool |
| 297 |
useInterleaving bool |
| 298 |
localInterleaving bool |
| 299 |
peerInterleaving bool |
| 300 |
peerForwardTSN bool |
| 301 |
peerIForwardTSN bool |
| 302 |
sendZeroChecksum bool |
| 303 |
recvZeroChecksum bool |
| 304 |
|
| 305 |
// Congestion control parameters |
| 306 |
maxReceiveBufferSize uint32 |
| 307 |
maxMessageSize uint32 |
| 308 |
maxReassemblyQueueEntries uint32 |
| 309 |
cwnd uint32 // my congestion window size |
| 310 |
rwnd uint32 // calculated peer's receiver windows size |
| 311 |
ssthresh uint32 // slow start threshold |
| 312 |
partialBytesAcked uint32 |
| 313 |
inFastRecovery bool |
| 314 |
fastRecoverExitPoint uint32 |
| 315 |
minCwnd uint32 // Minimum congestion window |
| 316 |
fastRtxWnd uint32 // Send window for fast retransmit |
| 317 |
cwndCAStep uint32 // Step of congestion window increase at Congestion Avoidance |
| 318 |
|
| 319 |
// RTX & Ack timer |
| 320 |
rtoMgr *rtoManager |
| 321 |
t1Init *rtxTimer |
| 322 |
t1Cookie *rtxTimer |
| 323 |
t2Shutdown *rtxTimer |
| 324 |
t3RTX *rtxTimer |
| 325 |
tReconfig *rtxTimer |
| 326 |
ackTimer *ackTimer |
| 327 |
|
| 328 |
// RACK / TLP state |
| 329 |
rack rackSettings // rack configurable options |
| 330 |
rackReoWnd time.Duration // dynamic reordering window |
| 331 |
rackMinRTT time.Duration // min observed RTT |
| 332 |
rackDeliveredTime time.Time // send time of most recently delivered original chunk |
| 333 |
rackHighestDeliveredOrigTSN uint32 |
| 334 |
rackReorderingSeen bool // ever observed reordering for this association |
| 335 |
rackKeepInflatedRecoveries int // keep inflated reoWnd for 16 loss recoveries |
| 336 |
// RACK xmit-time ordered list |
| 337 |
rackHead *chunkPayloadData |
| 338 |
rackTail *chunkPayloadData |
| 339 |
|
| 340 |
// Unified timer for RACK and PTO driven by a single goroutine. |
| 341 |
// Deadlines are protected with timerMu. |
| 342 |
timerMu sync.Mutex |
| 343 |
timerUpdateCh chan struct{} |
| 344 |
rackDeadline time.Time |
| 345 |
ptoDeadline time.Time |
| 346 |
|
| 347 |
// Chunks stored for retransmission |
| 348 |
storedInit *chunkInit |
| 349 |
storedCookieEcho *chunkCookieEcho |
| 350 |
|
| 351 |
streams map[uint16]*Stream |
| 352 |
acceptCh chan *Stream |
| 353 |
readLoopCloseCh chan struct{} |
| 354 |
awakeWriteLoopCh chan struct{} |
| 355 |
closeWriteLoopCh chan struct{} |
| 356 |
handshakeCompletedCh chan error |
| 357 |
|
| 358 |
closeWriteLoopOnce sync.Once |
| 359 |
|
| 360 |
// local error |
| 361 |
silentError error |
| 362 |
|
| 363 |
ackState int |
| 364 |
ackMode int // for testing |
| 365 |
|
| 366 |
// stats |
| 367 |
stats *associationStats |
| 368 |
|
| 369 |
// per inbound packet context |
| 370 |
delayedAckTriggered bool |
| 371 |
immediateAckTriggered bool |
| 372 |
|
| 373 |
blockWrite bool |
| 374 |
writePending bool |
| 375 |
writeNotify chan struct{} |
| 376 |
|
| 377 |
name string |
| 378 |
log logging.LeveledLogger |
| 379 |
|
| 380 |
// Adaptive burst mitigation variables |
| 381 |
tlrActive bool |
| 382 |
tlrFirstRTT bool // first RTT of this TLR operation |
| 383 |
tlrHadAdditionalLoss bool |
| 384 |
tlrEndTSN uint32 // recovery is done when cumAck >= tlrEndTSN |
| 385 |
|
| 386 |
tlrBurstFirstRTTUnits int64 // quarter-MTU units |
| 387 |
tlrBurstLaterRTTUnits int64 // quarter-MTU units |
| 388 |
|
| 389 |
tlrGoodOps uint32 // count of TLR ops completed w/o additional loss |
| 390 |
tlrStartTime time.Time // time of first recovery RTT |
| 391 |
} |
| 392 |
|
| 393 |
type snapConfig struct { |
| 394 |
// Local and remote SCTP init to use for SNAP |
| 395 |
localInit []byte |
| 396 |
remoteInit []byte |
| 397 |
} |
| 398 |
|
| 399 |
// Config collects the arguments to createAssociation construction into |
| 400 |
// a single structure. |
| 401 |
type Config struct { |
| 402 |
LoggerFactory logging.LoggerFactory |
| 403 |
Name string |
| 404 |
NetConn net.Conn |
| 405 |
BlockWrite bool |
| 406 |
EnableZeroChecksum bool |
| 407 |
MTU uint32 |
| 408 |
|
| 409 |
// congestion control configuration |
| 410 |
MaxReceiveBufferSize uint32 |
| 411 |
MaxMessageSize uint32 |
| 412 |
// RTOMax is the maximum retransmission timeout in milliseconds |
| 413 |
RTOMax float64 |
| 414 |
// Minimum congestion window |
| 415 |
MinCwnd uint32 |
| 416 |
// Send window for fast retransmit |
| 417 |
FastRtxWnd uint32 |
| 418 |
// Step of congestion window increase at Congestion Avoidance |
| 419 |
CwndCAStep uint32 |
| 420 |
|
| 421 |
// RACK config options |
| 422 |
rack rackSettings |
| 423 |
|
| 424 |
// User message interleaving config options |
| 425 |
interleaving *interleavingSettings |
| 426 |
|
| 427 |
// Reassembly queue config options |
| 428 |
maxReassemblyQueueEntries uint32 |
| 429 |
|
| 430 |
// SNAP/sctp-init |
| 431 |
snapConfig *snapConfig |
| 432 |
|
| 433 |
enableInterleaving bool |
| 434 |
enableInterleavingSet bool |
| 435 |
} |
| 436 |
|
| 437 |
// Server accepts a SCTP stream over a conn. |
| 438 |
// |
| 439 |
// Deprecated: Use ServerWithOptions instead. |
| 440 |
func Server(config Config) (*Association, error) { |
| 441 |
return ServerWithOptions(config) |
| 442 |
} |
| 443 |
|
| 444 |
// ServerWithOptions accepts a SCTP stream over a conn. |
| 445 |
func ServerWithOptions(opts ...ServerOption) (*Association, error) { |
| 446 |
assoc, err := createServerAssociation(opts...) |
| 447 |
if err != nil { |
| 448 |
return nil, err |
| 449 |
} |
| 450 |
assoc.initServer() |
| 451 |
|
| 452 |
select { |
| 453 |
case err := <-assoc.handshakeCompletedCh: |
| 454 |
if err != nil { |
| 455 |
return nil, err |
| 456 |
} |
| 457 |
|
| 458 |
return assoc, nil |
| 459 |
case <-assoc.readLoopCloseCh: |
| 460 |
return nil, ErrAssociationClosedBeforeConn |
| 461 |
} |
| 462 |
} |
| 463 |
|
| 464 |
// Client opens a SCTP stream over a conn. |
| 465 |
// |
| 466 |
// Deprecated: Use ClientWithOptions instead. |
| 467 |
func Client(config Config) (*Association, error) { |
| 468 |
return ClientWithOptions(config) |
| 469 |
} |
| 470 |
|
| 471 |
// ClientWithOptions opens a SCTP stream over a conn. |
| 472 |
func ClientWithOptions(opts ...ClientOption) (*Association, error) { |
| 473 |
return createClientWithOptionsWithContext(context.Background(), opts...) |
| 474 |
} |
| 475 |
|
| 476 |
func createClientWithContext(ctx context.Context, config Config) (*Association, error) { |
| 477 |
return createClientWithOptionsWithContext(ctx, config) |
| 478 |
} |
| 479 |
|
| 480 |
func createSNAPAssociation(config *Config) (*Association, error) { |
| 481 |
// SNAP, aka sctp-init in the SDP. |
| 482 |
remote := &chunkInit{} |
| 483 |
err := remote.unmarshal(config.snapConfig.remoteInit) |
| 484 |
if err != nil { |
| 485 |
return nil, err |
| 486 |
} |
| 487 |
local := &chunkInit{} |
| 488 |
err = local.unmarshal(config.snapConfig.localInit) |
| 489 |
if err != nil { |
| 490 |
return nil, err |
| 491 |
} |
| 492 |
assoc := createAssociationFromConfigWithTsn(config, local.initialTSN) |
| 493 |
if err = assoc.initWithOutOfBandTokens(local, remote); err != nil { |
| 494 |
return nil, err |
| 495 |
} |
| 496 |
|
| 497 |
return assoc, nil |
| 498 |
} |
| 499 |
|
| 500 |
func createClientWithOptionsWithContext(ctx context.Context, opts ...ClientOption) (*Association, error) { |
| 501 |
config, err := buildClientConfig(opts...) |
| 502 |
if err != nil { |
| 503 |
return nil, err |
| 504 |
} |
| 505 |
if config.snapConfig != nil && len(config.snapConfig.remoteInit) != 0 && len(config.snapConfig.localInit) != 0 { |
| 506 |
return createSNAPAssociation(config) |
| 507 |
} |
| 508 |
assoc, err := createClientAssociation(opts...) |
| 509 |
if err != nil { |
| 510 |
return nil, err |
| 511 |
} |
| 512 |
|
| 513 |
assoc.initClient() |
| 514 |
|
| 515 |
select { |
| 516 |
case <-ctx.Done(): |
| 517 |
assoc.log.Errorf("[%s] client handshake canceled: state=%s", assoc.name, getAssociationStateString(assoc.getState())) |
| 518 |
assoc.Close() // nolint:errcheck,gosec |
| 519 |
|
| 520 |
return nil, ctx.Err() |
| 521 |
case err := <-assoc.handshakeCompletedCh: |
| 522 |
if err != nil { |
| 523 |
return nil, err |
| 524 |
} |
| 525 |
|
| 526 |
return assoc, nil |
| 527 |
case <-assoc.readLoopCloseCh: |
| 528 |
return nil, ErrAssociationClosedBeforeConn |
| 529 |
} |
| 530 |
} |
| 531 |
|
| 532 |
// applyDefaults applies default values to the config. |
| 533 |
func (c *Config) applyDefaults() { |
| 534 |
if c.LoggerFactory == nil { |
| 535 |
c.LoggerFactory = logging.NewDefaultLoggerFactory() |
| 536 |
} |
| 537 |
if c.MaxReceiveBufferSize == 0 { |
| 538 |
c.MaxReceiveBufferSize = initialRecvBufSize |
| 539 |
} |
| 540 |
if c.MaxMessageSize == 0 { |
| 541 |
c.MaxMessageSize = defaultMaxMessageSize |
| 542 |
} |
| 543 |
if c.MTU == 0 { |
| 544 |
c.MTU = initialMTU |
| 545 |
} |
| 546 |
if !c.enableInterleavingSet { |
| 547 |
c.enableInterleaving = true |
| 548 |
} |
| 549 |
if c.interleaving == nil { |
| 550 |
c.interleaving = &interleavingSettings{} |
| 551 |
} |
| 552 |
if c.interleaving.newStreamScheduler == nil { |
| 553 |
setWeightedFairQueueingStreamScheduler(c.interleaving) |
| 554 |
} |
| 555 |
} |
| 556 |
|
| 557 |
func createServerAssociation(opts ...ServerOption) (*Association, error) { |
| 558 |
cfg, err := buildServerConfig(opts...) |
| 559 |
if err != nil { |
| 560 |
return nil, err |
| 561 |
} |
| 562 |
|
| 563 |
return createAssociationFromConfig(cfg) |
| 564 |
} |
| 565 |
|
| 566 |
func (a *Association) initServer() { |
| 567 |
a.lock.Lock() |
| 568 |
defer a.lock.Unlock() |
| 569 |
|
| 570 |
go a.readLoop() |
| 571 |
go a.writeLoop() |
| 572 |
} |
| 573 |
|
| 574 |
// applyServer allows the exported Config to act as a ServerOption. |
| 575 |
func (c Config) applyServer(cfg *Config) error { //nolint:dupl,cyclop |
| 576 |
if c.LoggerFactory != nil { |
| 577 |
cfg.LoggerFactory = c.LoggerFactory |
| 578 |
} |
| 579 |
if c.Name != "" { |
| 580 |
cfg.Name = c.Name |
| 581 |
} |
| 582 |
if c.NetConn != nil { |
| 583 |
cfg.NetConn = c.NetConn |
| 584 |
} |
| 585 |
|
| 586 |
cfg.BlockWrite = c.BlockWrite |
| 587 |
cfg.EnableZeroChecksum = c.EnableZeroChecksum |
| 588 |
|
| 589 |
if c.MTU != 0 { |
| 590 |
if err := validateMTU(c.MTU); err != nil { |
| 591 |
return err |
| 592 |
} |
| 593 |
cfg.MTU = c.MTU |
| 594 |
} |
| 595 |
if c.MaxReceiveBufferSize != 0 { |
| 596 |
cfg.MaxReceiveBufferSize = c.MaxReceiveBufferSize |
| 597 |
} |
| 598 |
if c.MaxMessageSize != 0 { |
| 599 |
cfg.MaxMessageSize = c.MaxMessageSize |
| 600 |
} |
| 601 |
if c.maxReassemblyQueueEntries != 0 { |
| 602 |
cfg.maxReassemblyQueueEntries = c.maxReassemblyQueueEntries |
| 603 |
} |
| 604 |
if c.RTOMax != 0 { |
| 605 |
cfg.RTOMax = c.RTOMax |
| 606 |
} |
| 607 |
if c.MinCwnd != 0 { |
| 608 |
cfg.MinCwnd = c.MinCwnd |
| 609 |
} |
| 610 |
if c.FastRtxWnd != 0 { |
| 611 |
cfg.FastRtxWnd = c.FastRtxWnd |
| 612 |
} |
| 613 |
if c.CwndCAStep != 0 { |
| 614 |
cfg.CwndCAStep = c.CwndCAStep |
| 615 |
} |
| 616 |
|
| 617 |
cfg.rack = c.rack |
| 618 |
cfg.interleaving = cloneInterleavingSettings(c.interleaving) |
| 619 |
if c.enableInterleavingSet { |
| 620 |
cfg.enableInterleaving = c.enableInterleaving |
| 621 |
cfg.enableInterleavingSet = true |
| 622 |
} |
| 623 |
|
| 624 |
return nil |
| 625 |
} |
| 626 |
|
| 627 |
func buildServerConfig(opts ...ServerOption) (*Config, error) { |
| 628 |
cfg := &Config{} |
| 629 |
cfg.applyDefaults() |
| 630 |
|
| 631 |
for _, opt := range opts { |
| 632 |
if opt == nil { |
| 633 |
continue |
| 634 |
} |
| 635 |
if err := opt.applyServer(cfg); err != nil { |
| 636 |
return nil, err |
| 637 |
} |
| 638 |
} |
| 639 |
|
| 640 |
cfg.applyDefaults() |
| 641 |
|
| 642 |
if cfg.NetConn == nil { |
| 643 |
return nil, errNilNetConn |
| 644 |
} |
| 645 |
|
| 646 |
return cfg, nil |
| 647 |
} |
| 648 |
|
| 649 |
func createClientAssociation(opts ...ClientOption) (*Association, error) { |
| 650 |
cfg, err := buildClientConfig(opts...) |
| 651 |
if err != nil { |
| 652 |
return nil, err |
| 653 |
} |
| 654 |
|
| 655 |
return createAssociationFromConfig(cfg) |
| 656 |
} |
| 657 |
|
| 658 |
func (a *Association) initClient() { |
| 659 |
a.lock.Lock() |
| 660 |
defer a.lock.Unlock() |
| 661 |
|
| 662 |
go a.readLoop() |
| 663 |
go a.writeLoop() |
| 664 |
|
| 665 |
init := &chunkInit{} |
| 666 |
init.initialTSN = a.myNextTSN |
| 667 |
init.numOutboundStreams = a.myMaxNumOutboundStreams |
| 668 |
init.numInboundStreams = a.myMaxNumInboundStreams |
| 669 |
init.initiateTag = a.myVerificationTag |
| 670 |
init.advertisedReceiverWindowCredit = a.maxReceiveBufferSize |
| 671 |
setSupportedExtensions(&init.chunkInitCommon, a.localInterleaving) |
| 672 |
|
| 673 |
if a.recvZeroChecksum { |
| 674 |
init.params = append(init.params, ¶mZeroChecksumAcceptable{edmid: dtlsErrorDetectionMethod}) |
| 675 |
} |
| 676 |
|
| 677 |
a.storedInit = init |
| 678 |
|
| 679 |
err := a.sendInit() |
| 680 |
if err != nil { |
| 681 |
a.log.Errorf("[%s] failed to send init: %s", a.name, err.Error()) |
| 682 |
} |
| 683 |
|
| 684 |
// After sending the INIT chunk, "A" starts the T1-init timer and enters the COOKIE-WAIT state. |
| 685 |
// Note: ideally we would set state after the timer starts but since we don't do this in an atomic |
| 686 |
// set + timer-start, it's safer to just set the state first so that we don't have a timer expiration |
| 687 |
// race. |
| 688 |
a.setState(cookieWait) |
| 689 |
a.t1Init.start(a.rtoMgr.getRTO()) |
| 690 |
} |
| 691 |
|
| 692 |
// applyClient allows the exported Config to act as a ClientOption. |
| 693 |
// this is currently the same as applyServer. |
| 694 |
func (c Config) applyClient(cfg *Config) error { //nolint:dupl,cyclop |
| 695 |
if c.LoggerFactory != nil { |
| 696 |
cfg.LoggerFactory = c.LoggerFactory |
| 697 |
} |
| 698 |
if c.Name != "" { |
| 699 |
cfg.Name = c.Name |
| 700 |
} |
| 701 |
if c.NetConn != nil { |
| 702 |
cfg.NetConn = c.NetConn |
| 703 |
} |
| 704 |
|
| 705 |
cfg.BlockWrite = c.BlockWrite |
| 706 |
cfg.EnableZeroChecksum = c.EnableZeroChecksum |
| 707 |
|
| 708 |
if c.MTU != 0 { |
| 709 |
if err := validateMTU(c.MTU); err != nil { |
| 710 |
return err |
| 711 |
} |
| 712 |
cfg.MTU = c.MTU |
| 713 |
} |
| 714 |
if c.MaxReceiveBufferSize != 0 { |
| 715 |
cfg.MaxReceiveBufferSize = c.MaxReceiveBufferSize |
| 716 |
} |
| 717 |
if c.MaxMessageSize != 0 { |
| 718 |
cfg.MaxMessageSize = c.MaxMessageSize |
| 719 |
} |
| 720 |
if c.maxReassemblyQueueEntries != 0 { |
| 721 |
cfg.maxReassemblyQueueEntries = c.maxReassemblyQueueEntries |
| 722 |
} |
| 723 |
if c.RTOMax != 0 { |
| 724 |
cfg.RTOMax = c.RTOMax |
| 725 |
} |
| 726 |
if c.MinCwnd != 0 { |
| 727 |
cfg.MinCwnd = c.MinCwnd |
| 728 |
} |
| 729 |
if c.FastRtxWnd != 0 { |
| 730 |
cfg.FastRtxWnd = c.FastRtxWnd |
| 731 |
} |
| 732 |
if c.CwndCAStep != 0 { |
| 733 |
cfg.CwndCAStep = c.CwndCAStep |
| 734 |
} |
| 735 |
|
| 736 |
cfg.rack = c.rack |
| 737 |
cfg.interleaving = cloneInterleavingSettings(c.interleaving) |
| 738 |
if c.enableInterleavingSet { |
| 739 |
cfg.enableInterleaving = c.enableInterleaving |
| 740 |
cfg.enableInterleavingSet = true |
| 741 |
} |
| 742 |
|
| 743 |
cfg.snapConfig = c.snapConfig |
| 744 |
|
| 745 |
return nil |
| 746 |
} |
| 747 |
|
| 748 |
func buildClientConfig(opts ...ClientOption) (*Config, error) { |
| 749 |
cfg := &Config{} |
| 750 |
cfg.applyDefaults() |
| 751 |
|
| 752 |
for _, opt := range opts { |
| 753 |
if opt == nil { |
| 754 |
continue |
| 755 |
} |
| 756 |
if err := opt.applyClient(cfg); err != nil { |
| 757 |
return nil, err |
| 758 |
} |
| 759 |
} |
| 760 |
|
| 761 |
cfg.applyDefaults() |
| 762 |
|
| 763 |
if cfg.NetConn == nil { |
| 764 |
return nil, errNilNetConn |
| 765 |
} |
| 766 |
|
| 767 |
return cfg, nil |
| 768 |
} |
| 769 |
|
| 770 |
func createAssociationFromConfig(cfg *Config) (*Association, error) { |
| 771 |
if cfg.MTU != 0 { |
| 772 |
if err := validateMTU(cfg.MTU); err != nil { |
| 773 |
return nil, err |
| 774 |
} |
| 775 |
} |
| 776 |
|
| 777 |
tsn := globalMathRandomGenerator.Uint32() |
| 778 |
|
| 779 |
return createAssociationFromConfigWithTsn(cfg, tsn), nil |
| 780 |
} |
| 781 |
|
| 782 |
func createAssociationFromConfigWithTsn(cfg *Config, tsn uint32) *Association { |
| 783 |
maxReceiveBufferSize := cfg.MaxReceiveBufferSize |
| 784 |
if maxReceiveBufferSize == 0 { |
| 785 |
maxReceiveBufferSize = initialRecvBufSize |
| 786 |
} |
| 787 |
|
| 788 |
maxMessageSize := cfg.MaxMessageSize |
| 789 |
if maxMessageSize == 0 { |
| 790 |
maxMessageSize = defaultMaxMessageSize |
| 791 |
} |
| 792 |
|
| 793 |
mtu := cfg.MTU |
| 794 |
if mtu == 0 { |
| 795 |
mtu = initialMTU |
| 796 |
} |
| 797 |
|
| 798 |
rtoMax := cfg.RTOMax |
| 799 |
interleaving := cfg.interleaving |
| 800 |
if interleaving == nil { |
| 801 |
interleaving = &interleavingSettings{} |
| 802 |
setWeightedFairQueueingStreamScheduler(interleaving) |
| 803 |
} |
| 804 |
|
| 805 |
assoc := &Association{ |
| 806 |
netConn: cfg.NetConn, |
| 807 |
maxReceiveBufferSize: maxReceiveBufferSize, |
| 808 |
maxMessageSize: maxMessageSize, |
| 809 |
maxReassemblyQueueEntries: cfg.maxReassemblyQueueEntries, |
| 810 |
minCwnd: cfg.MinCwnd, |
| 811 |
fastRtxWnd: cfg.FastRtxWnd, |
| 812 |
cwndCAStep: cfg.CwndCAStep, |
| 813 |
|
| 814 |
myMaxNumOutboundStreams: math.MaxUint16, |
| 815 |
myMaxNumInboundStreams: math.MaxUint16, |
| 816 |
|
| 817 |
payloadQueue: newReceivePayloadQueue(getMaxTSNOffset(maxReceiveBufferSize)), |
| 818 |
inflightQueue: newPayloadQueue(), |
| 819 |
pendingQueue: newPendingQueue(interleaving.newStreamScheduler), |
| 820 |
controlQueue: newControlQueue(), |
| 821 |
mtu: mtu, |
| 822 |
maxPayloadSize: maxPayloadSizeForMTU(mtu, false), |
| 823 |
myVerificationTag: generateInitiateTag(), |
| 824 |
initialTSN: tsn, |
| 825 |
myNextTSN: tsn, |
| 826 |
myNextRSN: tsn, |
| 827 |
minTSN2MeasureRTT: tsn, |
| 828 |
state: closed, |
| 829 |
rtoMgr: newRTOManager(rtoMax), |
| 830 |
streams: map[uint16]*Stream{}, |
| 831 |
reconfigs: map[uint32]*chunkReconfig{}, |
| 832 |
reconfigRequests: map[uint32]*paramOutgoingResetRequest{}, |
| 833 |
acceptCh: make(chan *Stream, acceptChSize), |
| 834 |
readLoopCloseCh: make(chan struct{}), |
| 835 |
awakeWriteLoopCh: make(chan struct{}, 1), |
| 836 |
closeWriteLoopCh: make(chan struct{}), |
| 837 |
handshakeCompletedCh: make(chan error), |
| 838 |
cumulativeTSNAckPoint: tsn - 1, |
| 839 |
advancedPeerTSNAckPoint: tsn - 1, |
| 840 |
recvZeroChecksum: cfg.EnableZeroChecksum, |
| 841 |
localInterleaving: cfg.enableInterleaving, |
| 842 |
silentError: ErrSilentlyDiscard, |
| 843 |
stats: &associationStats{}, |
| 844 |
log: cfg.LoggerFactory.NewLogger("sctp"), |
| 845 |
name: cfg.Name, |
| 846 |
blockWrite: cfg.BlockWrite, |
| 847 |
writeNotify: make(chan struct{}, 1), |
| 848 |
abortSentCh: make(chan struct{}), |
| 849 |
} |
| 850 |
|
| 851 |
// adaptive burst mitigation defaults |
| 852 |
assoc.tlrBurstFirstRTTUnits = tlrBurstDefaultFirstRTT |
| 853 |
assoc.tlrBurstLaterRTTUnits = tlrBurstDefaultLaterRTT |
| 854 |
|
| 855 |
// RACK defaults |
| 856 |
assoc.rack.rackWCDelAck = cfg.rack.rackWCDelAck |
| 857 |
if assoc.rack.rackWCDelAck == 0 { |
| 858 |
assoc.rack.rackWCDelAck = 200 * time.Millisecond // WCDelAckT, RACK for SCTP section 2C |
| 859 |
} |
| 860 |
|
| 861 |
assoc.rack.rackMinRTTWnd = cfg.rack.rackMinRTTWnd |
| 862 |
if assoc.rack.rackMinRTTWnd == nil { |
| 863 |
assoc.rack.rackMinRTTWnd = newWindowedMin(30 * time.Second) |
| 864 |
} |
| 865 |
|
| 866 |
assoc.timerUpdateCh = make(chan struct{}, 1) |
| 867 |
go assoc.timerLoop() |
| 868 |
|
| 869 |
assoc.rack.rackReoWndFloor = cfg.rack.rackReoWndFloor // optional floor; usually 0 |
| 870 |
assoc.rackKeepInflatedRecoveries = 0 |
| 871 |
|
| 872 |
if assoc.name == "" { |
| 873 |
assoc.name = fmt.Sprintf("%p", assoc) |
| 874 |
} |
| 875 |
|
| 876 |
assoc.setCWND(min32(4*assoc.MTU(), max32(2*assoc.MTU(), 4380))) |
| 877 |
assoc.log.Tracef("[%s] updated cwnd=%d ssthresh=%d inflight=%d (INI)", |
| 878 |
assoc.name, assoc.CWND(), assoc.ssthresh, assoc.inflightQueue.getNumBytes()) |
| 879 |
|
| 880 |
assoc.srtt.Store(float64(0)) |
| 881 |
assoc.t1Init = newRTXTimer(timerT1Init, assoc, maxInitRetrans, rtoMax) |
| 882 |
assoc.t1Cookie = newRTXTimer(timerT1Cookie, assoc, maxInitRetrans, rtoMax) |
| 883 |
assoc.t2Shutdown = newRTXTimer(timerT2Shutdown, assoc, noMaxRetrans, rtoMax) |
| 884 |
assoc.t3RTX = newRTXTimer(timerT3RTX, assoc, noMaxRetrans, rtoMax) |
| 885 |
assoc.tReconfig = newRTXTimer(timerReconfig, assoc, noMaxRetrans, rtoMax) |
| 886 |
assoc.ackTimer = newAckTimer(assoc) |
| 887 |
|
| 888 |
return assoc |
| 889 |
} |
| 890 |
|
| 891 |
func (a *Association) initWithOutOfBandTokens(localInit *chunkInit, remoteInit *chunkInit) error { |
| 892 |
a.lock.Lock() |
| 893 |
defer a.lock.Unlock() |
| 894 |
|
| 895 |
go a.readLoop() |
| 896 |
go a.writeLoop() |
| 897 |
|
| 898 |
a.payloadQueue.init(remoteInit.initialTSN - 1) |
| 899 |
a.myMaxNumInboundStreams = min16(localInit.numInboundStreams, remoteInit.numInboundStreams) |
| 900 |
a.myMaxNumOutboundStreams = min16(localInit.numOutboundStreams, remoteInit.numOutboundStreams) |
| 901 |
a.setRWND(remoteInit.advertisedReceiverWindowCredit) |
| 902 |
a.peerVerificationTag = remoteInit.initiateTag |
| 903 |
a.sourcePort = defaultSCTPSrcDstPort |
| 904 |
a.destinationPort = defaultSCTPSrcDstPort |
| 905 |
|
| 906 |
localExtensions := getSupportedExtensions(localInit.params) |
| 907 |
a.localInterleaving = localExtensions.interleaving |
| 908 |
a.setPeerSupportedExtensions(getSupportedExtensions(remoteInit.params)) |
| 909 |
a.setSendZeroChecksum(remoteInit.params) |
| 910 |
|
| 911 |
a.ssthresh = a.RWND() |
| 912 |
|
| 913 |
if err := a.establish("init"); err != nil { |
| 914 |
return err |
| 915 |
} |
| 916 |
|
| 917 |
return nil |
| 918 |
} |
| 919 |
|
| 920 |
func (a *Association) setPeerSupportedExtensions(extensions supportedExtensions) { |
| 921 |
a.peerForwardTSN = extensions.forwardTSN |
| 922 |
a.peerInterleaving = extensions.interleaving |
| 923 |
a.peerIForwardTSN = extensions.iForwardTSN |
| 924 |
} |
| 925 |
|
| 926 |
func (a *Association) setSendZeroChecksum(params []param) { |
| 927 |
for _, param := range params { |
| 928 |
if zeroChecksum, ok := param.(*paramZeroChecksumAcceptable); ok { |
| 929 |
a.sendZeroChecksum = zeroChecksum.edmid == dtlsErrorDetectionMethod |
| 930 |
} |
| 931 |
} |
| 932 |
} |
| 933 |
|
| 934 |
func (a *Association) logNegotiatedExtensions(stage string) { |
| 935 |
switch { |
| 936 |
case a.useInterleaving: |
| 937 |
a.log.Debugf("[%s] use interleaving (on %s)", a.name, stage) |
| 938 |
if !a.useIForwardTSN { |
| 939 |
a.log.Warnf("[%s] not using I-ForwardTSN (on %s)", a.name, stage) |
| 940 |
} |
| 941 |
case a.useForwardTSN: |
| 942 |
a.log.Debugf("[%s] use ForwardTSN (on %s)", a.name, stage) |
| 943 |
default: |
| 944 |
a.log.Warnf("[%s] not using ForwardTSN (on %s)", a.name, stage) |
| 945 |
} |
| 946 |
} |
| 947 |
|
| 948 |
// establish finalizes negotiated options and transitions the association to ESTABLISHED. |
| 949 |
// The caller should hold the lock. |
| 950 |
func (a *Association) establish(stage string) error { |
| 951 |
if err := a.updateInterleavingState(); err != nil { |
| 952 |
return err |
| 953 |
} |
| 954 |
a.logNegotiatedExtensions(stage) |
| 955 |
a.setState(established) |
| 956 |
|
| 957 |
return nil |
| 958 |
} |
| 959 |
|
| 960 |
// caller must hold a.lock. |
| 961 |
func (a *Association) sendInit() error { |
| 962 |
a.log.Debugf("[%s] sending INIT", a.name) |
| 963 |
if a.storedInit == nil { |
| 964 |
return ErrInitNotStoredToSend |
| 965 |
} |
| 966 |
|
| 967 |
outbound := &packet{} |
| 968 |
outbound.verificationTag = 0 |
| 969 |
a.sourcePort = defaultSCTPSrcDstPort |
| 970 |
a.destinationPort = defaultSCTPSrcDstPort |
| 971 |
outbound.sourcePort = a.sourcePort |
| 972 |
outbound.destinationPort = a.destinationPort |
| 973 |
|
| 974 |
outbound.chunks = []chunk{a.storedInit} |
| 975 |
|
| 976 |
a.controlQueue.push(outbound) |
| 977 |
a.awakeWriteLoop() |
| 978 |
|
| 979 |
return nil |
| 980 |
} |
| 981 |
|
| 982 |
// caller must hold a.lock. |
| 983 |
func (a *Association) sendCookieEcho() error { |
| 984 |
if a.storedCookieEcho == nil { |
| 985 |
return ErrCookieEchoNotStoredToSend |
| 986 |
} |
| 987 |
|
| 988 |
a.log.Debugf("[%s] sending COOKIE-ECHO", a.name) |
| 989 |
|
| 990 |
outbound := &packet{} |
| 991 |
outbound.verificationTag = a.peerVerificationTag |
| 992 |
outbound.sourcePort = a.sourcePort |
| 993 |
outbound.destinationPort = a.destinationPort |
| 994 |
outbound.chunks = []chunk{a.storedCookieEcho} |
| 995 |
|
| 996 |
a.controlQueue.push(outbound) |
| 997 |
a.awakeWriteLoop() |
| 998 |
|
| 999 |
return nil |
| 1000 |
} |
| 1001 |
|
| 1002 |
// Shutdown initiates the shutdown sequence. The method blocks until the |
| 1003 |
// shutdown sequence is completed and the connection is closed, or until the |
| 1004 |
// passed context is done, in which case the context's error is returned. |
| 1005 |
func (a *Association) Shutdown(ctx context.Context) error { |
| 1006 |
a.log.Debugf("[%s] closing association..", a.name) |
| 1007 |
|
| 1008 |
a.lock.Lock() |
| 1009 |
|
| 1010 |
state := a.getState() |
| 1011 |
|
| 1012 |
if state != established { |
| 1013 |
a.lock.Unlock() |
| 1014 |
|
| 1015 |
return fmt.Errorf("%w: shutdown %s", ErrShutdownNonEstablished, a.name) |
| 1016 |
} |
| 1017 |
|
| 1018 |
// Attempt a graceful shutdown. |
| 1019 |
a.setState(shutdownPending) |
| 1020 |
a.unblockPendingWrites() |
| 1021 |
|
| 1022 |
if !a.hasPendingOrInflightData() { |
| 1023 |
// No more outstanding, send shutdown. |
| 1024 |
a.willSendShutdown = true |
| 1025 |
a.setState(shutdownSent) |
| 1026 |
} |
| 1027 |
|
| 1028 |
a.awakeWriteLoop() |
| 1029 |
a.lock.Unlock() |
| 1030 |
|
| 1031 |
select { |
| 1032 |
case <-a.closeWriteLoopCh: |
| 1033 |
return nil |
| 1034 |
case <-ctx.Done(): |
| 1035 |
return ctx.Err() |
| 1036 |
} |
| 1037 |
} |
| 1038 |
|
| 1039 |
// Close ends the SCTP Association and cleans up any state. |
| 1040 |
func (a *Association) Close() error { |
| 1041 |
a.log.Debugf("[%s] closing association..", a.name) |
| 1042 |
|
| 1043 |
err := a.close() |
| 1044 |
|
| 1045 |
// Wait for readLoop to end |
| 1046 |
<-a.readLoopCloseCh |
| 1047 |
|
| 1048 |
a.log.Debugf("[%s] association closed", a.name) |
| 1049 |
a.log.Debugf("[%s] stats nPackets (in) : %d", a.name, a.stats.getNumPacketsReceived()) |
| 1050 |
a.log.Debugf("[%s] stats nPackets (out) : %d", a.name, a.stats.getNumPacketsSent()) |
| 1051 |
a.log.Debugf("[%s] stats nDATAs (in) : %d", a.name, a.stats.getNumDATAs()) |
| 1052 |
a.log.Debugf("[%s] stats nSACKs (in) : %d", a.name, a.stats.getNumSACKsReceived()) |
| 1053 |
a.log.Debugf("[%s] stats nSACKs (out) : %d", a.name, a.stats.getNumSACKsSent()) |
| 1054 |
a.log.Debugf("[%s] stats nT3Timeouts : %d", a.name, a.stats.getNumT3Timeouts()) |
| 1055 |
a.log.Debugf("[%s] stats nAckTimeouts: %d", a.name, a.stats.getNumAckTimeouts()) |
| 1056 |
a.log.Debugf("[%s] stats nFastRetrans: %d", a.name, a.stats.getNumFastRetrans()) |
| 1057 |
|
| 1058 |
return err |
| 1059 |
} |
| 1060 |
|
| 1061 |
func (a *Association) close() error { |
| 1062 |
a.log.Debugf("[%s] closing association..", a.name) |
| 1063 |
|
| 1064 |
a.setState(closed) |
| 1065 |
|
| 1066 |
err := a.closeNetConn() |
| 1067 |
|
| 1068 |
a.closeAllTimers() |
| 1069 |
|
| 1070 |
// awake writeLoop to exit |
| 1071 |
a.closeWriteLoopOnce.Do(func() { close(a.closeWriteLoopCh) }) |
| 1072 |
|
| 1073 |
return err |
| 1074 |
} |
| 1075 |
|
| 1076 |
func (a *Association) closeNetConn() error { |
| 1077 |
a.netConnCloseOnce.Do(func() { |
| 1078 |
a.netConnCloseErr = a.netConn.Close() |
| 1079 |
}) |
| 1080 |
|
| 1081 |
return a.netConnCloseErr |
| 1082 |
} |
| 1083 |
|
| 1084 |
// Abort sends the abort packet with user initiated abort and immediately |
| 1085 |
// closes the connection. |
| 1086 |
func (a *Association) Abort(reason string) { |
| 1087 |
a.log.Debugf("[%s] aborting association: %s", a.name, reason) |
| 1088 |
|
| 1089 |
a.lock.Lock() |
| 1090 |
|
| 1091 |
a.willSendAbort = true |
| 1092 |
a.willSendAbortCause = &errorCauseUserInitiatedAbort{ |
| 1093 |
upperLayerAbortReason: []byte(reason), |
| 1094 |
} |
| 1095 |
|
| 1096 |
a.lock.Unlock() |
| 1097 |
|
| 1098 |
flushTimeout := 200 * time.Millisecond |
| 1099 |
|
| 1100 |
// short bound for abort flush. |
| 1101 |
_ = a.netConn.SetWriteDeadline(time.Now().Add(flushTimeout)) |
| 1102 |
a.awakeWriteLoop() |
| 1103 |
|
| 1104 |
// Give writeLoop a chance to write the ABORT before we force readLoop to exit |
| 1105 |
// (readLoop exit closes closeWriteLoopCh and can race the ABORT send). |
| 1106 |
select { |
| 1107 |
case <-a.abortSentCh: |
| 1108 |
case <-time.After(flushTimeout): |
| 1109 |
} |
| 1110 |
|
| 1111 |
// unblock readLoop even if the underlying connection is half-open. |
| 1112 |
// We want Abort to return promptly during shutdown. |
| 1113 |
_ = a.netConn.SetReadDeadline(time.Now()) |
| 1114 |
|
| 1115 |
// Wait for readLoop to end |
| 1116 |
<-a.readLoopCloseCh |
| 1117 |
|
| 1118 |
// Ensure ABORT write was at least attempted before returning (bounded). |
| 1119 |
select { |
| 1120 |
case <-a.abortSentCh: |
| 1121 |
case <-time.After(flushTimeout): |
| 1122 |
} |
| 1123 |
} |
| 1124 |
|
| 1125 |
func (a *Association) closeAllTimers() { |
| 1126 |
// Close all retransmission & ack timers |
| 1127 |
a.t1Init.close() |
| 1128 |
a.t1Cookie.close() |
| 1129 |
a.t2Shutdown.close() |
| 1130 |
a.t3RTX.close() |
| 1131 |
a.tReconfig.close() |
| 1132 |
a.ackTimer.close() |
| 1133 |
a.stopRackTimer() |
| 1134 |
a.stopPTOTimer() |
| 1135 |
} |
| 1136 |
|
| 1137 |
func (a *Association) readLoop() { |
| 1138 |
var closeErr error |
| 1139 |
defer func() { |
| 1140 |
// also stop writeLoop, otherwise writeLoop can be leaked |
| 1141 |
// if connection is lost when there is no writing packet. |
| 1142 |
a.closeWriteLoopOnce.Do(func() { close(a.closeWriteLoopCh) }) |
| 1143 |
|
| 1144 |
a.lock.Lock() |
| 1145 |
a.setState(closed) |
| 1146 |
for _, s := range a.streams { |
| 1147 |
a.unregisterStream(s, closeErr) |
| 1148 |
} |
| 1149 |
a.unblockPendingWrites() |
| 1150 |
a.lock.Unlock() |
| 1151 |
close(a.acceptCh) |
| 1152 |
close(a.readLoopCloseCh) |
| 1153 |
|
| 1154 |
a.log.Debugf("[%s] association closed", a.name) |
| 1155 |
a.log.Debugf("[%s] stats nDATAs (in) : %d", a.name, a.stats.getNumDATAs()) |
| 1156 |
a.log.Debugf("[%s] stats nSACKs (in) : %d", a.name, a.stats.getNumSACKsReceived()) |
| 1157 |
a.log.Debugf("[%s] stats nT3Timeouts : %d", a.name, a.stats.getNumT3Timeouts()) |
| 1158 |
a.log.Debugf("[%s] stats nAckTimeouts: %d", a.name, a.stats.getNumAckTimeouts()) |
| 1159 |
a.log.Debugf("[%s] stats nFastRetrans: %d", a.name, a.stats.getNumFastRetrans()) |
| 1160 |
}() |
| 1161 |
|
| 1162 |
a.log.Debugf("[%s] readLoop entered", a.name) |
| 1163 |
buffer := make([]byte, receiveMTU) |
| 1164 |
|
| 1165 |
for { |
| 1166 |
n, err := a.netConn.Read(buffer) |
| 1167 |
if err != nil { |
| 1168 |
closeErr = err |
| 1169 |
|
| 1170 |
break |
| 1171 |
} |
| 1172 |
// Make a buffer sized to what we read, then copy the data we |
| 1173 |
// read from the underlying transport. We do this because the |
| 1174 |
// user data is passed to the reassembly queue without |
| 1175 |
// copying. |
| 1176 |
inbound := make([]byte, n) |
| 1177 |
copy(inbound, buffer[:n]) |
| 1178 |
atomic.AddUint64(&a.bytesReceived, uint64(n)) //nolint:gosec // G115 |
| 1179 |
if err = a.handleInbound(inbound); err != nil { |
| 1180 |
closeErr = err |
| 1181 |
|
| 1182 |
break |
| 1183 |
} |
| 1184 |
} |
| 1185 |
|
| 1186 |
a.log.Debugf("[%s] readLoop exited %s", a.name, closeErr) |
| 1187 |
} |
| 1188 |
|
| 1189 |
func (a *Association) writeLoop() { // nolint:cyclop |
| 1190 |
a.log.Debugf("[%s] writeLoop entered", a.name) |
| 1191 |
defer a.log.Debugf("[%s] writeLoop exited", a.name) |
| 1192 |
|
| 1193 |
loop: |
| 1194 |
for { |
| 1195 |
rawPackets, ok := a.gatherOutbound() |
| 1196 |
|
| 1197 |
for _, raw := range rawPackets { |
| 1198 |
isAbortPacket := len(raw) > int(commonHeaderSize) && raw[commonHeaderSize] == byte(ctAbort) |
| 1199 |
_, err := a.netConn.Write(raw) |
| 1200 |
if isAbortPacket { |
| 1201 |
a.abortSentOnce.Do(func() { close(a.abortSentCh) }) |
| 1202 |
} |
| 1203 |
if err != nil { |
| 1204 |
if !errors.Is(err, io.EOF) { |
| 1205 |
a.log.Warnf("[%s] failed to write packets on netConn: %v", a.name, err) |
| 1206 |
} |
| 1207 |
a.log.Debugf("[%s] writeLoop ended", a.name) |
| 1208 |
|
| 1209 |
// A write failure may be one-sided, leaving readLoop blocked in |
| 1210 |
// Read. Close the transport so association teardown can finish. |
| 1211 |
_ = a.closeNetConn() |
| 1212 |
|
| 1213 |
break loop |
| 1214 |
} |
| 1215 |
atomic.AddUint64(&a.bytesSent, uint64(len(raw))) |
| 1216 |
a.stats.incPacketsSent() |
| 1217 |
} |
| 1218 |
|
| 1219 |
if !ok { |
| 1220 |
if err := a.close(); err != nil { |
| 1221 |
a.log.Warnf("[%s] failed to close association: %v", a.name, err) |
| 1222 |
} |
| 1223 |
|
| 1224 |
return |
| 1225 |
} |
| 1226 |
|
| 1227 |
select { |
| 1228 |
case <-a.awakeWriteLoopCh: |
| 1229 |
case <-a.closeWriteLoopCh: |
| 1230 |
a.lock.Lock() |
| 1231 |
abortPending := a.willSendAbort |
| 1232 |
a.lock.Unlock() |
| 1233 |
if abortPending { |
| 1234 |
// If an ABORT is pending, prefer sending it even if readLoop has |
| 1235 |
// already ended and closed closeWriteLoopCh. |
| 1236 |
continue |
| 1237 |
} |
| 1238 |
|
| 1239 |
break loop |
| 1240 |
} |
| 1241 |
} |
| 1242 |
|
| 1243 |
a.setState(closed) |
| 1244 |
a.closeAllTimers() |
| 1245 |
} |
| 1246 |
|
| 1247 |
func (a *Association) awakeWriteLoop() { |
| 1248 |
select { |
| 1249 |
case a.awakeWriteLoopCh <- struct{}{}: |
| 1250 |
default: |
| 1251 |
} |
| 1252 |
} |
| 1253 |
|
| 1254 |
func (a *Association) isBlockWrite() bool { |
| 1255 |
return a.blockWrite |
| 1256 |
} |
| 1257 |
|
| 1258 |
// Mark the association is writable and unblock the waiting write, |
| 1259 |
// the caller should hold the association write lock. |
| 1260 |
func (a *Association) notifyBlockWritable() { |
| 1261 |
a.writePending = false |
| 1262 |
select { |
| 1263 |
case a.writeNotify <- struct{}{}: |
| 1264 |
default: |
| 1265 |
} |
| 1266 |
} |
| 1267 |
|
| 1268 |
// unblockPendingWrites wakes all goroutines waiting on the blocked write. |
| 1269 |
// Note: the caller should hold the association lock. |
| 1270 |
func (a *Association) unblockPendingWrites() { |
| 1271 |
if !a.blockWrite { |
| 1272 |
return |
| 1273 |
} |
| 1274 |
|
| 1275 |
a.writePending = false |
| 1276 |
close(a.writeNotify) |
| 1277 |
a.writeNotify = make(chan struct{}, 1) |
| 1278 |
} |
| 1279 |
|
| 1280 |
// unregisterStream un-registers a stream from the association |
| 1281 |
// The caller should hold the association write lock. |
| 1282 |
func (a *Association) unregisterStream(s *Stream, err error) { |
| 1283 |
s.lock.Lock() |
| 1284 |
defer s.lock.Unlock() |
| 1285 |
|
| 1286 |
delete(a.streams, s.streamIdentifier) |
| 1287 |
s.readErr = err |
| 1288 |
s.readNotifier.Broadcast() |
| 1289 |
} |
| 1290 |
|
| 1291 |
func chunkMandatoryChecksum(cc []chunk) bool { |
| 1292 |
for _, c := range cc { |
| 1293 |
switch c.(type) { |
| 1294 |
case *chunkInit, *chunkCookieEcho: |
| 1295 |
return true |
| 1296 |
} |
| 1297 |
} |
| 1298 |
|
| 1299 |
return false |
| 1300 |
} |
| 1301 |
|
| 1302 |
func (a *Association) marshalPacket(p *packet) ([]byte, error) { |
| 1303 |
return p.marshal(!a.sendZeroChecksum || chunkMandatoryChecksum(p.chunks)) |
| 1304 |
} |
| 1305 |
|
| 1306 |
func (a *Association) unmarshalPacket(raw []byte) (*packet, error) { |
| 1307 |
p := &packet{} |
| 1308 |
if err := p.unmarshal(!a.recvZeroChecksum, raw); err != nil { |
| 1309 |
return nil, err |
| 1310 |
} |
| 1311 |
|
| 1312 |
return p, nil |
| 1313 |
} |
| 1314 |
|
| 1315 |
// handleInbound parses incoming raw packets. |
| 1316 |
func (a *Association) handleInbound(raw []byte) error { |
| 1317 |
pkt, err := a.unmarshalPacket(raw) |
| 1318 |
if err != nil { |
| 1319 |
a.log.Warnf("[%s] unable to parse SCTP packet %s", a.name, err) |
| 1320 |
|
| 1321 |
return nil |
| 1322 |
} |
| 1323 |
|
| 1324 |
if err := checkPacket(pkt); err != nil { |
| 1325 |
a.log.Warnf("[%s] failed validating packet %s", a.name, err) |
| 1326 |
|
| 1327 |
return nil |
| 1328 |
} |
| 1329 |
|
| 1330 |
a.handleChunksStart() |
| 1331 |
|
| 1332 |
for _, c := range pkt.chunks { |
| 1333 |
if err := a.handleChunk(pkt, c); err != nil { |
| 1334 |
return err |
| 1335 |
} |
| 1336 |
} |
| 1337 |
|
| 1338 |
a.handleChunksEnd() |
| 1339 |
|
| 1340 |
return nil |
| 1341 |
} |
| 1342 |
|
| 1343 |
// The caller should hold the lock. |
| 1344 |
func (a *Association) gatherDataPacketsToRetransmit(rawPackets [][]byte, budgetUnits *int64, consumed *bool) [][]byte { |
| 1345 |
for _, p := range a.getDataPacketsToRetransmit(budgetUnits, consumed) { |
| 1346 |
raw, err := a.marshalPacket(p) |
| 1347 |
if err != nil { |
| 1348 |
a.log.Warnf("[%s] failed to serialize a DATA packet to be retransmitted", a.name) |
| 1349 |
|
| 1350 |
continue |
| 1351 |
} |
| 1352 |
rawPackets = append(rawPackets, raw) |
| 1353 |
} |
| 1354 |
|
| 1355 |
return rawPackets |
| 1356 |
} |
| 1357 |
|
| 1358 |
// The caller should hold the lock. |
| 1359 |
func (a *Association) gatherOutboundReconfigPackets(rawPackets [][]byte) [][]byte { |
| 1360 |
if !a.willRetransmitReconfig { |
| 1361 |
return rawPackets |
| 1362 |
} |
| 1363 |
|
| 1364 |
a.willRetransmitReconfig = false |
| 1365 |
a.log.Debugf("[%s] retransmit %d RECONFIG chunk(s)", a.name, len(a.reconfigs)) |
| 1366 |
for _, c := range a.reconfigs { |
| 1367 |
p := a.createPacket([]chunk{c}) |
| 1368 |
raw, err := a.marshalPacket(p) |
| 1369 |
if err != nil { |
| 1370 |
a.log.Warnf("[%s] failed to serialize a RECONFIG packet to be retransmitted", a.name) |
| 1371 |
} else { |
| 1372 |
rawPackets = append(rawPackets, raw) |
| 1373 |
} |
| 1374 |
} |
| 1375 |
|
| 1376 |
return rawPackets |
| 1377 |
} |
| 1378 |
|
| 1379 |
// The caller should hold the lock. |
| 1380 |
// |
| 1381 |
//nolint:cyclop |
| 1382 |
func (a *Association) gatherOutboundDataAndReconfigPackets( |
| 1383 |
rawPackets [][]byte, |
| 1384 |
budgetUnits *int64, |
| 1385 |
consumed *bool, |
| 1386 |
) [][]byte { |
| 1387 |
// Pop unsent data chunks from the pending queue to send as much as |
| 1388 |
// cwnd and rwnd allow. |
| 1389 |
chunks, sisToReset := a.popPendingDataChunksToSend(budgetUnits, consumed) |
| 1390 |
|
| 1391 |
if len(chunks) > 0 { |
| 1392 |
// Start timer. (noop if already started) |
| 1393 |
a.log.Tracef("[%s] T3-rtx timer start (pt1)", a.name) |
| 1394 |
a.t3RTX.start(a.rtoMgr.getRTO()) |
| 1395 |
for _, p := range a.bundleDataChunksIntoPackets(chunks) { |
| 1396 |
raw, err := a.marshalPacket(p) |
| 1397 |
if err != nil { |
| 1398 |
a.log.Warnf("[%s] failed to serialize a DATA packet", a.name) |
| 1399 |
|
| 1400 |
continue |
| 1401 |
} |
| 1402 |
rawPackets = append(rawPackets, raw) |
| 1403 |
} |
| 1404 |
// RFC 8985 (RACK) schedule PTO on new data transmission |
| 1405 |
a.schedulePTOAfterSendLocked() |
| 1406 |
} |
| 1407 |
|
| 1408 |
if len(sisToReset) > 0 || a.willRetransmitReconfig { //nolint:nestif |
| 1409 |
rawPackets = a.gatherOutboundReconfigPackets(rawPackets) |
| 1410 |
|
| 1411 |
if len(sisToReset) > 0 { |
| 1412 |
rsn := a.generateNextRSN() |
| 1413 |
tsn := a.myNextTSN - 1 |
| 1414 |
c := &chunkReconfig{ |
| 1415 |
paramA: ¶mOutgoingResetRequest{ |
| 1416 |
reconfigRequestSequenceNumber: rsn, |
| 1417 |
senderLastTSN: tsn, |
| 1418 |
streamIdentifiers: sisToReset, |
| 1419 |
}, |
| 1420 |
} |
| 1421 |
a.reconfigs[rsn] = c // store in the map for retransmission |
| 1422 |
a.log.Debugf("[%s] sending RECONFIG: rsn=%d tsn=%d streams=%v", |
| 1423 |
a.name, rsn, a.myNextTSN-1, sisToReset) |
| 1424 |
p := a.createPacket([]chunk{c}) |
| 1425 |
raw, err := a.marshalPacket(p) |
| 1426 |
if err != nil { |
| 1427 |
a.log.Warnf("[%s] failed to serialize a RECONFIG packet to be transmitted", a.name) |
| 1428 |
} else { |
| 1429 |
rawPackets = append(rawPackets, raw) |
| 1430 |
} |
| 1431 |
} |
| 1432 |
|
| 1433 |
if len(a.reconfigs) > 0 { |
| 1434 |
a.tReconfig.start(a.rtoMgr.getRTO()) |
| 1435 |
} |
| 1436 |
} |
| 1437 |
|
| 1438 |
return rawPackets |
| 1439 |
} |
| 1440 |
|
| 1441 |
// The caller should hold the lock. |
| 1442 |
// |
| 1443 |
//nolint:cyclop |
| 1444 |
func (a *Association) gatherOutboundFastRetransmissionPackets( //nolint:gocognit |
| 1445 |
rawPackets [][]byte, |
| 1446 |
budgetScaled *int64, |
| 1447 |
consumed *bool, |
| 1448 |
) [][]byte { |
| 1449 |
if !a.willRetransmitFast { |
| 1450 |
return rawPackets |
| 1451 |
} |
| 1452 |
a.willRetransmitFast = false |
| 1453 |
|
| 1454 |
toFastRetrans := []*chunkPayloadData{} |
| 1455 |
fastRetransSize := int(commonHeaderSize) |
| 1456 |
fastRetransWnd := int(max(a.MTU(), a.fastRtxWnd)) |
| 1457 |
now := time.Now() |
| 1458 |
|
| 1459 |
// MTU bundling + burst budgeting tracker |
| 1460 |
bytesInPacket := 0 |
| 1461 |
stopBundling := false |
| 1462 |
|
| 1463 |
for i := 0; ; i++ { |
| 1464 |
chunkPayload, ok := a.inflightQueue.get(a.cumulativeTSNAckPoint + uint32(i) + 1) //nolint:gosec // G115 |
| 1465 |
if !ok { |
| 1466 |
break // end of pending data |
| 1467 |
} |
| 1468 |
|
| 1469 |
if chunkPayload.acked || chunkPayload.abandoned() { |
| 1470 |
continue |
| 1471 |
} |
| 1472 |
|
| 1473 |
if chunkPayload.nSent > 1 || chunkPayload.missIndicator < 3 { |
| 1474 |
continue |
| 1475 |
} |
| 1476 |
|
| 1477 |
// RFC 4960 Sec 7.2.4 Fast Retransmit on Gap Reports |
| 1478 |
// 3) Determine how many of the earliest (i.e., lowest TSN) DATA chunks |
| 1479 |
// marked for retransmission will fit into a single packet, subject |
| 1480 |
// to constraint of the path MTU of the destination transport |
| 1481 |
// address to which the packet is being sent. Call this value K. |
| 1482 |
// Retransmit those K DATA chunks in a single packet. When a Fast |
| 1483 |
// Retransmit is being performed, the sender SHOULD ignore the value |
| 1484 |
// of cwnd and SHOULD NOT delay retransmission for this single |
| 1485 |
// packet. |
| 1486 |
|
| 1487 |
chunkBytes := chunkPayload.chunkSizeInPacket() |
| 1488 |
|
| 1489 |
// fast retransmit window cap |
| 1490 |
if fastRetransWnd < fastRetransSize+chunkBytes { |
| 1491 |
break |
| 1492 |
} |
| 1493 |
|
| 1494 |
// MTU bundling + burst budget before mutating |
| 1495 |
for { |
| 1496 |
addBytes := chunkBytes |
| 1497 |
|
| 1498 |
if bytesInPacket == 0 { |
| 1499 |
addBytes += int(commonHeaderSize) |
| 1500 |
if addBytes > int(a.MTU()) { |
| 1501 |
stopBundling = true |
| 1502 |
|
| 1503 |
break |
| 1504 |
} |
| 1505 |
} else if bytesInPacket+chunkBytes > int(a.MTU()) { |
| 1506 |
// start a new packet and retry this same chunk as first in packet |
| 1507 |
bytesInPacket = 0 |
| 1508 |
|
| 1509 |
continue |
| 1510 |
} |
| 1511 |
|
| 1512 |
if !a.tlrAllowSendLocked(budgetScaled, consumed, addBytes) { |
| 1513 |
// budget exhausted, stop selecting any more fast-rtx chunks |
| 1514 |
stopBundling = true |
| 1515 |
|
| 1516 |
break |
| 1517 |
} |
| 1518 |
|
| 1519 |
if bytesInPacket == 0 { |
| 1520 |
bytesInPacket = int(commonHeaderSize) |
| 1521 |
} |
| 1522 |
bytesInPacket += chunkBytes |
| 1523 |
|
| 1524 |
break |
| 1525 |
} |
| 1526 |
|
| 1527 |
if stopBundling { |
| 1528 |
break |
| 1529 |
} |
| 1530 |
|
| 1531 |
fastRetransSize += chunkBytes |
| 1532 |
a.stats.incFastRetrans() |
| 1533 |
|
| 1534 |
// Update for retransmission |
| 1535 |
chunkPayload.nSent++ |
| 1536 |
chunkPayload.since = now |
| 1537 |
a.rackRemove(chunkPayload) |
| 1538 |
a.rackInsert(chunkPayload) |
| 1539 |
|
| 1540 |
a.checkPartialReliabilityStatus(chunkPayload) |
| 1541 |
toFastRetrans = append(toFastRetrans, chunkPayload) |
| 1542 |
a.log.Tracef("[%s] fast-retransmit: tsn=%d sent=%d htna=%d", |
| 1543 |
a.name, chunkPayload.tsn, chunkPayload.nSent, a.fastRecoverExitPoint) |
| 1544 |
} |
| 1545 |
|
| 1546 |
if len(toFastRetrans) == 0 { |
| 1547 |
return rawPackets |
| 1548 |
} |
| 1549 |
|
| 1550 |
for _, p := range a.bundleDataChunksIntoPackets(toFastRetrans) { |
| 1551 |
raw, err := a.marshalPacket(p) |
| 1552 |
if err != nil { |
| 1553 |
a.log.Warnf("[%s] failed to serialize a DATA packet to be fast-retransmitted", a.name) |
| 1554 |
|
| 1555 |
continue |
| 1556 |
} |
| 1557 |
rawPackets = append(rawPackets, raw) |
| 1558 |
} |
| 1559 |
|
| 1560 |
return rawPackets |
| 1561 |
} |
| 1562 |
|
| 1563 |
// The caller should hold the lock. |
| 1564 |
func (a *Association) gatherOutboundSackPackets(rawPackets [][]byte) [][]byte { |
| 1565 |
if a.ackState == ackStateImmediate { |
| 1566 |
a.ackState = ackStateIdle |
| 1567 |
sack := a.createSelectiveAckChunk() |
| 1568 |
a.stats.incSACKsSent() |
| 1569 |
a.log.Debugf("[%s] sending SACK: %s", a.name, sack) |
| 1570 |
raw, err := a.marshalPacket(a.createPacket([]chunk{sack})) |
| 1571 |
if err != nil { |
| 1572 |
a.log.Warnf("[%s] failed to serialize a SACK packet", a.name) |
| 1573 |
} else { |
| 1574 |
rawPackets = append(rawPackets, raw) |
| 1575 |
} |
| 1576 |
} |
| 1577 |
|
| 1578 |
return rawPackets |
| 1579 |
} |
| 1580 |
|
| 1581 |
// The caller should hold the lock. |
| 1582 |
func (a *Association) gatherOutboundForwardTSNPackets(rawPackets [][]byte) [][]byte { |
| 1583 |
if a.willSendForwardTSN { //nolint:nestif |
| 1584 |
a.willSendForwardTSN = false |
| 1585 |
if sna32GT(a.advancedPeerTSNAckPoint, a.cumulativeTSNAckPoint) { |
| 1586 |
var fwdtsn chunk |
| 1587 |
if a.useIForwardTSN { |
| 1588 |
fwdtsn = a.createIForwardTSN() |
| 1589 |
} else if a.useForwardTSN { |
| 1590 |
fwdtsn = a.createForwardTSN() |
| 1591 |
} |
| 1592 |
if fwdtsn == nil { |
| 1593 |
return rawPackets |
| 1594 |
} |
| 1595 |
raw, err := a.marshalPacket(a.createPacket([]chunk{fwdtsn})) |
| 1596 |
if err != nil { |
| 1597 |
a.log.Warnf("[%s] failed to serialize a Forward TSN packet", a.name) |
| 1598 |
} else { |
| 1599 |
rawPackets = append(rawPackets, raw) |
| 1600 |
} |
| 1601 |
} |
| 1602 |
} |
| 1603 |
|
| 1604 |
return rawPackets |
| 1605 |
} |
| 1606 |
|
| 1607 |
func (a *Association) gatherOutboundShutdownPackets(rawPackets [][]byte) ([][]byte, bool) { |
| 1608 |
ok := true |
| 1609 |
|
| 1610 |
switch { |
| 1611 |
case a.willSendShutdownComplete: |
| 1612 |
a.willSendShutdownComplete = false |
| 1613 |
a.willSendShutdownAck = false |
| 1614 |
a.willSendShutdown = false |
| 1615 |
|
| 1616 |
shutdownComplete := &chunkShutdownComplete{} |
| 1617 |
|
| 1618 |
raw, err := a.marshalPacket(a.createPacket([]chunk{shutdownComplete})) |
| 1619 |
if err != nil { |
| 1620 |
a.log.Warnf("[%s] failed to serialize a ShutdownComplete packet", a.name) |
| 1621 |
} else { |
| 1622 |
rawPackets = append(rawPackets, raw) |
| 1623 |
ok = false |
| 1624 |
} |
| 1625 |
case a.willSendShutdownAck: |
| 1626 |
a.willSendShutdownAck = false |
| 1627 |
a.willSendShutdown = false |
| 1628 |
|
| 1629 |
shutdownAck := &chunkShutdownAck{} |
| 1630 |
|
| 1631 |
raw, err := a.marshalPacket(a.createPacket([]chunk{shutdownAck})) |
| 1632 |
if err != nil { |
| 1633 |
a.log.Warnf("[%s] failed to serialize a ShutdownAck packet", a.name) |
| 1634 |
} else { |
| 1635 |
a.t2Shutdown.start(a.rtoMgr.getRTO()) |
| 1636 |
rawPackets = append(rawPackets, raw) |
| 1637 |
} |
| 1638 |
case a.willSendShutdown: |
| 1639 |
a.willSendShutdown = false |
| 1640 |
|
| 1641 |
shutdown := &chunkShutdown{ |
| 1642 |
cumulativeTSNAck: a.peerLastTSN(), |
| 1643 |
} |
| 1644 |
|
| 1645 |
raw, err := a.marshalPacket(a.createPacket([]chunk{shutdown})) |
| 1646 |
if err != nil { |
| 1647 |
a.log.Warnf("[%s] failed to serialize a Shutdown packet", a.name) |
| 1648 |
} else { |
| 1649 |
a.t2Shutdown.start(a.rtoMgr.getRTO()) |
| 1650 |
rawPackets = append(rawPackets, raw) |
| 1651 |
} |
| 1652 |
} |
| 1653 |
|
| 1654 |
return rawPackets, ok |
| 1655 |
} |
| 1656 |
|
| 1657 |
func (a *Association) gatherAbortPacket() ([]byte, error) { |
| 1658 |
cause := a.willSendAbortCause |
| 1659 |
|
| 1660 |
a.willSendAbort = false |
| 1661 |
a.willSendAbortCause = nil |
| 1662 |
|
| 1663 |
abort := &chunkAbort{} |
| 1664 |
|
| 1665 |
if cause != nil { |
| 1666 |
abort.errorCauses = []errorCause{cause} |
| 1667 |
} |
| 1668 |
|
| 1669 |
raw, err := a.marshalPacket(a.createPacket([]chunk{abort})) |
| 1670 |
|
| 1671 |
return raw, err |
| 1672 |
} |
| 1673 |
|
| 1674 |
// The caller should hold the lock. The final bool reports whether the |
| 1675 |
// returned packets terminate the association and suppress all other output. |
| 1676 |
func (a *Association) gatherOutboundPriorityPackets() ([][]byte, bool, bool) { |
| 1677 |
if a.willSendAbort { |
| 1678 |
pkt, err := a.gatherAbortPacket() |
| 1679 |
if err != nil { |
| 1680 |
a.log.Warnf("[%s] failed to serialize an abort packet", a.name) |
| 1681 |
// If we can't marshal the ABORT, no write will occur, but Abort() may |
| 1682 |
// still be waiting on abortSentCh. Signal completion of the ABORT attempt |
| 1683 |
// (even though it failed) to avoid unnecessary delays. |
| 1684 |
a.abortSentOnce.Do(func() { close(a.abortSentCh) }) |
| 1685 |
|
| 1686 |
return nil, false, true |
| 1687 |
} |
| 1688 |
|
| 1689 |
return [][]byte{pkt}, false, true |
| 1690 |
} |
| 1691 |
|
| 1692 |
// Once SHUTDOWN ACK has been received, SHUTDOWN COMPLETE is the only |
| 1693 |
// protocol response left to send. Do not let queued control or DATA |
| 1694 |
// traffic delay the terminal response. |
| 1695 |
if a.willSendShutdownComplete { |
| 1696 |
rawPackets, ok := a.gatherOutboundShutdownPackets(nil) |
| 1697 |
|
| 1698 |
return rawPackets, ok, true |
| 1699 |
} |
| 1700 |
|
| 1701 |
// A retransmitted or crossed SHUTDOWN must not sit behind unrelated |
| 1702 |
// control traffic while the peer is waiting for SHUTDOWN ACK. |
| 1703 |
if a.getState() == shutdownAckSent && a.willSendShutdownAck { |
| 1704 |
rawPackets, ok := a.gatherOutboundShutdownPackets(nil) |
| 1705 |
|
| 1706 |
return rawPackets, ok, false |
| 1707 |
} |
| 1708 |
|
| 1709 |
// DATA received after sending SHUTDOWN requires an immediate updated |
| 1710 |
// SHUTDOWN response, plus a SACK when gaps or duplicates require one. |
| 1711 |
if a.getState() == shutdownSent && a.willSendShutdown { |
| 1712 |
rawPackets := a.gatherOutboundSackPackets(nil) |
| 1713 |
rawPackets, ok := a.gatherOutboundShutdownPackets(rawPackets) |
| 1714 |
|
| 1715 |
return rawPackets, ok, false |
| 1716 |
} |
| 1717 |
|
| 1718 |
return nil, true, false |
| 1719 |
} |
| 1720 |
|
| 1721 |
// gatherOutbound gathers outgoing packets. The returned bool value set to |
| 1722 |
// false means the association should be closed down after the final send. |
| 1723 |
func (a *Association) gatherOutbound() ([][]byte, bool) { |
| 1724 |
a.lock.Lock() |
| 1725 |
defer a.lock.Unlock() |
| 1726 |
|
| 1727 |
rawPackets, ok, terminal := a.gatherOutboundPriorityPackets() |
| 1728 |
if terminal { |
| 1729 |
return rawPackets, ok |
| 1730 |
} |
| 1731 |
|
| 1732 |
if a.controlQueue.size() > 0 { |
| 1733 |
for _, p := range a.controlQueue.popAll() { |
| 1734 |
raw, err := a.marshalPacket(p) |
| 1735 |
if err != nil { |
| 1736 |
a.log.Warnf("[%s] failed to serialize a control packet", a.name) |
| 1737 |
|
| 1738 |
continue |
| 1739 |
} |
| 1740 |
rawPackets = append(rawPackets, raw) |
| 1741 |
} |
| 1742 |
} |
| 1743 |
|
| 1744 |
state := a.getState() |
| 1745 |
|
| 1746 |
switch state { |
| 1747 |
case established: |
| 1748 |
budgetUnits := a.tlrCurrentBurstBudgetScaledLocked() |
| 1749 |
consumed := false |
| 1750 |
|
| 1751 |
rawPackets = a.gatherDataPacketsToRetransmit(rawPackets, &budgetUnits, &consumed) |
| 1752 |
rawPackets = a.gatherOutboundDataAndReconfigPackets(rawPackets, &budgetUnits, &consumed) |
| 1753 |
rawPackets = a.gatherOutboundFastRetransmissionPackets(rawPackets, &budgetUnits, &consumed) |
| 1754 |
|
| 1755 |
// control traffic shouldn't be limited. |
| 1756 |
rawPackets = a.gatherOutboundSackPackets(rawPackets) |
| 1757 |
rawPackets = a.gatherOutboundForwardTSNPackets(rawPackets) |
| 1758 |
case shutdownPending, shutdownReceived: |
| 1759 |
budgetUnits := a.tlrCurrentBurstBudgetScaledLocked() |
| 1760 |
consumed := false |
| 1761 |
|
| 1762 |
rawPackets = a.gatherDataPacketsToRetransmit(rawPackets, &budgetUnits, &consumed) |
| 1763 |
rawPackets = a.gatherOutboundDataAndReconfigPackets(rawPackets, &budgetUnits, &consumed) |
| 1764 |
rawPackets = a.gatherOutboundFastRetransmissionPackets(rawPackets, &budgetUnits, &consumed) |
| 1765 |
a.advanceShutdownAfterDataDrain(state) |
| 1766 |
|
| 1767 |
rawPackets = a.gatherOutboundSackPackets(rawPackets) |
| 1768 |
rawPackets = a.gatherOutboundForwardTSNPackets(rawPackets) |
| 1769 |
rawPackets, ok = a.gatherOutboundShutdownPackets(rawPackets) |
| 1770 |
case shutdownSent: |
| 1771 |
rawPackets = a.gatherOutboundSackPackets(rawPackets) |
| 1772 |
rawPackets, ok = a.gatherOutboundShutdownPackets(rawPackets) |
| 1773 |
rawPackets = a.gatherOutboundReconfigPackets(rawPackets) |
| 1774 |
case shutdownAckSent: |
| 1775 |
rawPackets, ok = a.gatherOutboundShutdownPackets(rawPackets) |
| 1776 |
rawPackets = a.gatherOutboundReconfigPackets(rawPackets) |
| 1777 |
} |
| 1778 |
|
| 1779 |
return rawPackets, ok |
| 1780 |
} |
| 1781 |
|
| 1782 |
func checkPacket(pkt *packet) error { |
| 1783 |
// All packets must adhere to these rules |
| 1784 |
|
| 1785 |
// This is the SCTP sender's port number. It can be used by the |
| 1786 |
// receiver in combination with the source IP address, the SCTP |
| 1787 |
// destination port, and possibly the destination IP address to |
| 1788 |
// identify the association to which this packet belongs. The port |
| 1789 |
// number 0 MUST NOT be used. |
| 1790 |
if pkt.sourcePort == 0 { |
| 1791 |
return ErrSCTPPacketSourcePortZero |
| 1792 |
} |
| 1793 |
|
| 1794 |
// This is the SCTP port number to which this packet is destined. |
| 1795 |
// The receiving host will use this port number to de-multiplex the |
| 1796 |
// SCTP packet to the correct receiving endpoint/application. The |
| 1797 |
// port number 0 MUST NOT be used. |
| 1798 |
if pkt.destinationPort == 0 { |
| 1799 |
return ErrSCTPPacketDestinationPortZero |
| 1800 |
} |
| 1801 |
|
| 1802 |
// Check values on the packet that are specific to a particular chunk type |
| 1803 |
for _, c := range pkt.chunks { |
| 1804 |
switch c.(type) { // nolint:gocritic |
| 1805 |
case *chunkInit: |
| 1806 |
// An INIT or INIT ACK chunk MUST NOT be bundled with any other chunk. |
| 1807 |
// They MUST be the only chunks present in the SCTP packets that carry |
| 1808 |
// them. |
| 1809 |
if len(pkt.chunks) != 1 { |
| 1810 |
return ErrInitChunkBundled |
| 1811 |
} |
| 1812 |
|
| 1813 |
// A packet containing an INIT chunk MUST have a zero Verification |
| 1814 |
// Tag. |
| 1815 |
if pkt.verificationTag != 0 { |
| 1816 |
return ErrInitChunkVerifyTagNotZero |
| 1817 |
} |
| 1818 |
} |
| 1819 |
} |
| 1820 |
|
| 1821 |
return nil |
| 1822 |
} |
| 1823 |
|
| 1824 |
func min16(a, b uint16) uint16 { |
| 1825 |
if a < b { |
| 1826 |
return a |
| 1827 |
} |
| 1828 |
|
| 1829 |
return b |
| 1830 |
} |
| 1831 |
|
| 1832 |
func max32(a, b uint32) uint32 { |
| 1833 |
if a > b { |
| 1834 |
return a |
| 1835 |
} |
| 1836 |
|
| 1837 |
return b |
| 1838 |
} |
| 1839 |
|
| 1840 |
func min32(a, b uint32) uint32 { |
| 1841 |
if a < b { |
| 1842 |
return a |
| 1843 |
} |
| 1844 |
|
| 1845 |
return b |
| 1846 |
} |
| 1847 |
|
| 1848 |
// peerLastTSN return last received cumulative TSN. |
| 1849 |
func (a *Association) peerLastTSN() uint32 { |
| 1850 |
return a.payloadQueue.getcumulativeTSN() |
| 1851 |
} |
| 1852 |
|
| 1853 |
// setState atomically sets the state of the Association. |
| 1854 |
// The caller should hold the lock. |
| 1855 |
func (a *Association) setState(newState uint32) { |
| 1856 |
oldState := atomic.SwapUint32(&a.state, newState) |
| 1857 |
if newState != oldState { |
| 1858 |
a.log.Debugf("[%s] state change: '%s' => '%s'", |
| 1859 |
a.name, |
| 1860 |
getAssociationStateString(oldState), |
| 1861 |
getAssociationStateString(newState)) |
| 1862 |
} |
| 1863 |
} |
| 1864 |
|
| 1865 |
// getState atomically returns the state of the Association. |
| 1866 |
func (a *Association) getState() uint32 { |
| 1867 |
return atomic.LoadUint32(&a.state) |
| 1868 |
} |
| 1869 |
|
| 1870 |
// BytesSent returns the number of bytes sent. |
| 1871 |
func (a *Association) BytesSent() uint64 { |
| 1872 |
return atomic.LoadUint64(&a.bytesSent) |
| 1873 |
} |
| 1874 |
|
| 1875 |
// BytesReceived returns the number of bytes received. |
| 1876 |
func (a *Association) BytesReceived() uint64 { |
| 1877 |
return atomic.LoadUint64(&a.bytesReceived) |
| 1878 |
} |
| 1879 |
|
| 1880 |
// MTU returns the association's current MTU. |
| 1881 |
func (a *Association) MTU() uint32 { |
| 1882 |
return atomic.LoadUint32(&a.mtu) |
| 1883 |
} |
| 1884 |
|
| 1885 |
// CWND returns the association's current congestion window (cwnd). |
| 1886 |
func (a *Association) CWND() uint32 { |
| 1887 |
return atomic.LoadUint32(&a.cwnd) |
| 1888 |
} |
| 1889 |
|
| 1890 |
func (a *Association) setCWND(cwnd uint32) { |
| 1891 |
if cwnd < a.minCwnd { |
| 1892 |
cwnd = a.minCwnd |
| 1893 |
} |
| 1894 |
atomic.StoreUint32(&a.cwnd, cwnd) |
| 1895 |
} |
| 1896 |
|
| 1897 |
// RWND returns the association's current receiver window (rwnd). |
| 1898 |
func (a *Association) RWND() uint32 { |
| 1899 |
return atomic.LoadUint32(&a.rwnd) |
| 1900 |
} |
| 1901 |
|
| 1902 |
func (a *Association) setRWND(rwnd uint32) { |
| 1903 |
atomic.StoreUint32(&a.rwnd, rwnd) |
| 1904 |
} |
| 1905 |
|
| 1906 |
// SRTT returns the latest smoothed round-trip time (srrt). |
| 1907 |
func (a *Association) SRTT() float64 { |
| 1908 |
return a.srtt.Load().(float64) //nolint:forcetypeassert |
| 1909 |
} |
| 1910 |
|
| 1911 |
// Metadata returns negotiated association metadata. The ok return value is false |
| 1912 |
// until the SCTP handshake has completed. |
| 1913 |
func (a *Association) Metadata() (AssociationMetadata, bool) { |
| 1914 |
a.lock.RLock() |
| 1915 |
defer a.lock.RUnlock() |
| 1916 |
|
| 1917 |
if a.getState() != established { |
| 1918 |
return AssociationMetadata{}, false |
| 1919 |
} |
| 1920 |
|
| 1921 |
partialReliabilityMode := PartialReliabilityModeNone |
| 1922 |
switch { |
| 1923 |
case a.useIForwardTSN: |
| 1924 |
partialReliabilityMode = PartialReliabilityModeIForwardTSN |
| 1925 |
case a.useForwardTSN: |
| 1926 |
partialReliabilityMode = PartialReliabilityModeForwardTSN |
| 1927 |
} |
| 1928 |
|
| 1929 |
return AssociationMetadata{ |
| 1930 |
MessageInterleavingEnabled: a.useInterleaving, |
| 1931 |
PartialReliabilityMode: partialReliabilityMode, |
| 1932 |
ZeroChecksumSendingEnabled: a.sendZeroChecksum, |
| 1933 |
ZeroChecksumReceivingEnabled: a.recvZeroChecksum, |
| 1934 |
}, true |
| 1935 |
} |
| 1936 |
|
| 1937 |
// getMaxTSNOffset returns the maximum offset over the current cummulative TSN that |
| 1938 |
// we are willing to enqueue. This ensures that we keep the bytes utilized in the receive |
| 1939 |
// buffer within a small multiple of the user provided max receive buffer size. |
| 1940 |
func getMaxTSNOffset(maxReceiveBufferSize uint32) uint32 { |
| 1941 |
// 4 is a magic number here. There is no theory behind this. |
| 1942 |
offset := min(max((maxReceiveBufferSize*4)/avgChunkSize, minTSNOffset), maxTSNOffset) |
| 1943 |
|
| 1944 |
return offset |
| 1945 |
} |
| 1946 |
|
| 1947 |
func setSupportedExtensions(init *chunkInitCommon, enableInterleaving bool) { |
| 1948 |
// nolint:godox |
| 1949 |
// TODO RFC5061 https://tools.ietf.org/html/rfc6525#section-5.2 |
| 1950 |
// An implementation supporting this (Supported Extensions Parameter) |
| 1951 |
// extension MUST list the ASCONF, the ASCONF-ACK, and the AUTH chunks |
| 1952 |
// in its INIT and INIT-ACK parameters. |
| 1953 |
chunkTypes := []chunkType{ctReconfig, ctForwardTSN} |
| 1954 |
if enableInterleaving { |
| 1955 |
chunkTypes = append(chunkTypes, ctIData, ctIForwardTSN) |
| 1956 |
} |
| 1957 |
init.params = append(init.params, ¶mSupportedExtensions{ |
| 1958 |
ChunkTypes: chunkTypes, |
| 1959 |
}) |
| 1960 |
} |
| 1961 |
|
| 1962 |
type supportedExtensions struct { |
| 1963 |
forwardTSN bool |
| 1964 |
interleaving bool |
| 1965 |
iForwardTSN bool |
| 1966 |
} |
| 1967 |
|
| 1968 |
func getSupportedExtensions(params []param) supportedExtensions { |
| 1969 |
var extensions supportedExtensions |
| 1970 |
for _, param := range params { |
| 1971 |
if supported, ok := param.(*paramSupportedExtensions); ok { |
| 1972 |
parsed := supportedExtensionsFromChunkTypes(supported.ChunkTypes) |
| 1973 |
extensions.forwardTSN = extensions.forwardTSN || parsed.forwardTSN |
| 1974 |
extensions.interleaving = extensions.interleaving || parsed.interleaving |
| 1975 |
extensions.iForwardTSN = extensions.iForwardTSN || parsed.iForwardTSN |
| 1976 |
} |
| 1977 |
} |
| 1978 |
|
| 1979 |
return extensions |
| 1980 |
} |
| 1981 |
|
| 1982 |
func supportedExtensionsFromChunkTypes(chunkTypes []chunkType) supportedExtensions { |
| 1983 |
var extensions supportedExtensions |
| 1984 |
for _, t := range chunkTypes { |
| 1985 |
switch t { |
| 1986 |
case ctForwardTSN: |
| 1987 |
extensions.forwardTSN = true |
| 1988 |
case ctIData: |
| 1989 |
extensions.interleaving = true |
| 1990 |
case ctIForwardTSN: |
| 1991 |
extensions.iForwardTSN = true |
| 1992 |
default: |
| 1993 |
} |
| 1994 |
} |
| 1995 |
|
| 1996 |
return extensions |
| 1997 |
} |
| 1998 |
|
| 1999 |
func (a *Association) updateInterleavingState() error { |
| 2000 |
useInterleaving := a.localInterleaving && a.peerInterleaving |
| 2001 |
if useInterleaving != a.useInterleaving { |
| 2002 |
if err := a.pendingQueue.setInterleaving(useInterleaving); err != nil { |
| 2003 |
return err |
| 2004 |
} |
| 2005 |
|
| 2006 |
a.useInterleaving = useInterleaving |
| 2007 |
a.maxPayloadSize = maxPayloadSizeForMTU(a.mtu, useInterleaving) |
| 2008 |
} |
| 2009 |
|
| 2010 |
if useInterleaving { |
| 2011 |
a.useIForwardTSN = a.peerIForwardTSN && a.localInterleaving |
| 2012 |
a.useForwardTSN = false |
| 2013 |
} else { |
| 2014 |
a.useIForwardTSN = false |
| 2015 |
a.useForwardTSN = a.peerForwardTSN |
| 2016 |
} |
| 2017 |
|
| 2018 |
return nil |
| 2019 |
} |
| 2020 |
|
| 2021 |
func (a *Association) partialReliabilityEnabled() bool { |
| 2022 |
return a.useForwardTSN || a.useIForwardTSN |
| 2023 |
} |
| 2024 |
|
| 2025 |
// The caller should hold the lock. |
| 2026 |
func (a *Association) abortProtocolViolation(reason string) { |
| 2027 |
a.log.Warnf("[%s] protocol violation: %s", a.name, reason) |
| 2028 |
a.willSendAbort = true |
| 2029 |
a.willSendAbortCause = &errorCauseProtocolViolation{ |
| 2030 |
errorCauseHeader: errorCauseHeader{code: protocolViolation}, |
| 2031 |
additionalInformation: []byte(reason), |
| 2032 |
} |
| 2033 |
a.awakeWriteLoop() |
| 2034 |
} |
| 2035 |
|
| 2036 |
// The caller should hold the lock. |
| 2037 |
func (a *Association) retransmitShutdownAck() { |
| 2038 |
if a.shutdownCompletePending { |
| 2039 |
return |
| 2040 |
} |
| 2041 |
|
| 2042 |
a.t2Shutdown.stop() |
| 2043 |
a.willSendShutdown = false |
| 2044 |
a.willSendShutdownAck = true |
| 2045 |
a.awakeWriteLoop() |
| 2046 |
} |
| 2047 |
|
| 2048 |
// The caller should hold the lock. |
| 2049 |
// |
| 2050 |
//nolint:cyclop |
| 2051 |
func (a *Association) handleInit(pkt *packet, initChunk *chunkInit) ([]*packet, error) { |
| 2052 |
state := a.getState() |
| 2053 |
a.log.Debugf("[%s] chunkInit received in state '%s'", a.name, getAssociationStateString(state)) |
| 2054 |
|
| 2055 |
if state == shutdownAckSent { |
| 2056 |
// RFC 9260 Section 9.2: only an INIT whose SCTP port pair belongs |
| 2057 |
// to this association triggers a retransmission of SHUTDOWN ACK. |
| 2058 |
if a.sourcePort == pkt.destinationPort && a.destinationPort == pkt.sourcePort { |
| 2059 |
a.retransmitShutdownAck() |
| 2060 |
} |
| 2061 |
|
| 2062 |
return nil, nil |
| 2063 |
} |
| 2064 |
|
| 2065 |
// https://tools.ietf.org/html/rfc4960#section-5.2.1 |
| 2066 |
// Upon receipt of an INIT in the COOKIE-WAIT state, an endpoint MUST |
| 2067 |
// respond with an INIT ACK using the same parameters it sent in its |
| 2068 |
// original INIT chunk (including its Initiate Tag, unchanged). When |
| 2069 |
// responding, the endpoint MUST send the INIT ACK back to the same |
| 2070 |
// address that the original INIT (sent by this endpoint) was sent. |
| 2071 |
|
| 2072 |
if state != closed && state != cookieWait && state != cookieEchoed { |
| 2073 |
// 5.2.2. Unexpected INIT in States Other than CLOSED, COOKIE-ECHOED, |
| 2074 |
// COOKIE-WAIT, and SHUTDOWN-ACK-SENT |
| 2075 |
return nil, fmt.Errorf("%w: %s", ErrHandleInitState, getAssociationStateString(state)) |
| 2076 |
} |
| 2077 |
|
| 2078 |
// NOTE: Setting these prior to a reception of a COOKIE ECHO chunk containing |
| 2079 |
// our cookie is not compliant with https://www.rfc-editor.org/rfc/rfc9260#section-5.1-2.2.3. |
| 2080 |
// It makes us more vulnerable to resource attacks, albeit minimally so. |
| 2081 |
// https://www.rfc-editor.org/rfc/rfc9260#sec_handle_stream_parameters |
| 2082 |
a.myMaxNumInboundStreams = min16(initChunk.numInboundStreams, a.myMaxNumInboundStreams) |
| 2083 |
a.myMaxNumOutboundStreams = min16(initChunk.numOutboundStreams, a.myMaxNumOutboundStreams) |
| 2084 |
a.peerVerificationTag = initChunk.initiateTag |
| 2085 |
a.sourcePort = pkt.destinationPort |
| 2086 |
a.destinationPort = pkt.sourcePort |
| 2087 |
|
| 2088 |
// 13.2 This is the last TSN received in sequence. This value |
| 2089 |
// is set initially by taking the peer's initial TSN, |
| 2090 |
// received in the INIT or INIT ACK chunk, and |
| 2091 |
// subtracting one from it. |
| 2092 |
a.payloadQueue.init(initChunk.initialTSN - 1) |
| 2093 |
|
| 2094 |
a.setRWND(initChunk.advertisedReceiverWindowCredit) |
| 2095 |
a.log.Debugf("[%s] initial rwnd=%d", a.name, a.RWND()) |
| 2096 |
|
| 2097 |
a.peerInterleaving = false |
| 2098 |
a.peerForwardTSN = false |
| 2099 |
a.peerIForwardTSN = false |
| 2100 |
|
| 2101 |
for _, param := range initChunk.params { |
| 2102 |
switch val := param.(type) { // nolint:gocritic |
| 2103 |
case *paramSupportedExtensions: |
| 2104 |
extensions := supportedExtensionsFromChunkTypes(val.ChunkTypes) |
| 2105 |
a.peerForwardTSN = a.peerForwardTSN || extensions.forwardTSN |
| 2106 |
a.peerInterleaving = a.peerInterleaving || extensions.interleaving |
| 2107 |
a.peerIForwardTSN = a.peerIForwardTSN || extensions.iForwardTSN |
| 2108 |
case *paramZeroChecksumAcceptable: |
| 2109 |
a.sendZeroChecksum = val.edmid == dtlsErrorDetectionMethod |
| 2110 |
} |
| 2111 |
} |
| 2112 |
|
| 2113 |
if err := a.updateInterleavingState(); err != nil { |
| 2114 |
return nil, err |
| 2115 |
} |
| 2116 |
if a.useInterleaving { //nolint:nestif,gocritic |
| 2117 |
a.log.Debugf("[%s] use interleaving (on init)", a.name) |
| 2118 |
if !a.useIForwardTSN { |
| 2119 |
a.log.Warnf("[%s] not using I-ForwardTSN (on init)", a.name) |
| 2120 |
} |
| 2121 |
} else if a.useForwardTSN { |
| 2122 |
a.log.Debugf("[%s] use ForwardTSN (on init)", a.name) |
| 2123 |
} else { |
| 2124 |
a.log.Warnf("[%s] not using ForwardTSN (on init)", a.name) |
| 2125 |
} |
| 2126 |
|
| 2127 |
outbound := &packet{} |
| 2128 |
outbound.verificationTag = a.peerVerificationTag |
| 2129 |
outbound.sourcePort = a.sourcePort |
| 2130 |
outbound.destinationPort = a.destinationPort |
| 2131 |
|
| 2132 |
initAck := &chunkInitAck{} |
| 2133 |
a.log.Debug("sending INIT ACK") |
| 2134 |
|
| 2135 |
initAck.initialTSN = a.myNextTSN |
| 2136 |
initAck.numOutboundStreams = a.myMaxNumOutboundStreams |
| 2137 |
initAck.numInboundStreams = a.myMaxNumInboundStreams |
| 2138 |
initAck.initiateTag = a.myVerificationTag |
| 2139 |
initAck.advertisedReceiverWindowCredit = a.maxReceiveBufferSize |
| 2140 |
|
| 2141 |
if a.myCookie == nil { |
| 2142 |
var err error |
| 2143 |
// NOTE: This generation process is not compliant with |
| 2144 |
// 5.1.3. Generating State Cookie (https://www.rfc-editor.org/rfc/rfc4960#section-5.1.3) |
| 2145 |
if a.myCookie, err = newRandomStateCookie(); err != nil { |
| 2146 |
return nil, err |
| 2147 |
} |
| 2148 |
} |
| 2149 |
|
| 2150 |
initAck.params = []param{a.myCookie} |
| 2151 |
|
| 2152 |
if a.recvZeroChecksum { |
| 2153 |
initAck.params = append(initAck.params, ¶mZeroChecksumAcceptable{edmid: dtlsErrorDetectionMethod}) |
| 2154 |
} |
| 2155 |
a.log.Debugf("[%s] sendZeroChecksum=%t (on init)", a.name, a.sendZeroChecksum) |
| 2156 |
|
| 2157 |
setSupportedExtensions(&initAck.chunkInitCommon, a.localInterleaving) |
| 2158 |
|
| 2159 |
outbound.chunks = []chunk{initAck} |
| 2160 |
|
| 2161 |
return pack(outbound), nil |
| 2162 |
} |
| 2163 |
|
| 2164 |
// The caller should hold the lock. |
| 2165 |
func (a *Association) handleInitAck(pkt *packet, initChunkAck *chunkInitAck) error { //nolint:cyclop |
| 2166 |
state := a.getState() |
| 2167 |
a.log.Debugf("[%s] chunkInitAck received in state '%s'", a.name, getAssociationStateString(state)) |
| 2168 |
if state != cookieWait { |
| 2169 |
// RFC 4960 |
| 2170 |
// 5.2.3. Unexpected INIT ACK |
| 2171 |
// If an INIT ACK is received by an endpoint in any state other than the |
| 2172 |
// COOKIE-WAIT state, the endpoint should discard the INIT ACK chunk. |
| 2173 |
// An unexpected INIT ACK usually indicates the processing of an old or |
| 2174 |
// duplicated INIT chunk. |
| 2175 |
return nil |
| 2176 |
} |
| 2177 |
|
| 2178 |
a.myMaxNumInboundStreams = min16(initChunkAck.numInboundStreams, a.myMaxNumInboundStreams) |
| 2179 |
a.myMaxNumOutboundStreams = min16(initChunkAck.numOutboundStreams, a.myMaxNumOutboundStreams) |
| 2180 |
a.peerVerificationTag = initChunkAck.initiateTag |
| 2181 |
a.payloadQueue.init(initChunkAck.initialTSN - 1) |
| 2182 |
if a.sourcePort != pkt.destinationPort || |
| 2183 |
a.destinationPort != pkt.sourcePort { |
| 2184 |
a.log.Warnf("[%s] handleInitAck: port mismatch", a.name) |
| 2185 |
|
| 2186 |
return nil |
| 2187 |
} |
| 2188 |
|
| 2189 |
a.setRWND(initChunkAck.advertisedReceiverWindowCredit) |
| 2190 |
a.log.Debugf("[%s] initial rwnd=%d", a.name, a.RWND()) |
| 2191 |
|
| 2192 |
// RFC 4960 Sec 7.2.1 |
| 2193 |
// o The initial value of ssthresh MAY be arbitrarily high (for |
| 2194 |
// example, implementations MAY use the size of the receiver |
| 2195 |
// advertised window). |
| 2196 |
a.ssthresh = a.RWND() |
| 2197 |
a.log.Tracef("[%s] updated cwnd=%d ssthresh=%d inflight=%d (INI)", |
| 2198 |
a.name, a.CWND(), a.ssthresh, a.inflightQueue.getNumBytes()) |
| 2199 |
|
| 2200 |
a.t1Init.stop() |
| 2201 |
a.storedInit = nil |
| 2202 |
|
| 2203 |
a.peerInterleaving = false |
| 2204 |
a.peerForwardTSN = false |
| 2205 |
a.peerIForwardTSN = false |
| 2206 |
|
| 2207 |
var cookieParam *paramStateCookie |
| 2208 |
for _, param := range initChunkAck.params { |
| 2209 |
switch val := param.(type) { |
| 2210 |
case *paramStateCookie: |
| 2211 |
cookieParam = val |
| 2212 |
case *paramSupportedExtensions: |
| 2213 |
extensions := supportedExtensionsFromChunkTypes(val.ChunkTypes) |
| 2214 |
a.peerForwardTSN = a.peerForwardTSN || extensions.forwardTSN |
| 2215 |
a.peerInterleaving = a.peerInterleaving || extensions.interleaving |
| 2216 |
a.peerIForwardTSN = a.peerIForwardTSN || extensions.iForwardTSN |
| 2217 |
case *paramZeroChecksumAcceptable: |
| 2218 |
a.sendZeroChecksum = val.edmid == dtlsErrorDetectionMethod |
| 2219 |
} |
| 2220 |
} |
| 2221 |
|
| 2222 |
a.log.Debugf("[%s] sendZeroChecksum=%t (on initAck)", a.name, a.sendZeroChecksum) |
| 2223 |
|
| 2224 |
if err := a.updateInterleavingState(); err != nil { |
| 2225 |
return err |
| 2226 |
} |
| 2227 |
if a.useInterleaving { //nolint:gocritic |
| 2228 |
a.log.Tracef("[%s] use interleaving (on initAck)", a.name) |
| 2229 |
if !a.useIForwardTSN { |
| 2230 |
a.log.Warnf("[%s] not using I-ForwardTSN (on initAck)", a.name) |
| 2231 |
} |
| 2232 |
} else if a.useForwardTSN { |
| 2233 |
a.log.Tracef("[%s] use ForwardTSN (on initAck)", a.name) |
| 2234 |
} else { |
| 2235 |
a.log.Warnf("[%s] not using ForwardTSN (on initAck)", a.name) |
| 2236 |
} |
| 2237 |
if cookieParam == nil { |
| 2238 |
return ErrInitAckNoCookie |
| 2239 |
} |
| 2240 |
|
| 2241 |
a.storedCookieEcho = &chunkCookieEcho{} |
| 2242 |
a.storedCookieEcho.cookie = cookieParam.cookie |
| 2243 |
|
| 2244 |
err := a.sendCookieEcho() |
| 2245 |
if err != nil { |
| 2246 |
a.log.Errorf("[%s] failed to send init: %s", a.name, err.Error()) |
| 2247 |
} |
| 2248 |
|
| 2249 |
a.t1Cookie.start(a.rtoMgr.getRTO()) |
| 2250 |
a.setState(cookieEchoed) |
| 2251 |
|
| 2252 |
return nil |
| 2253 |
} |
| 2254 |
|
| 2255 |
// The caller should hold the lock. |
| 2256 |
func (a *Association) handleHeartbeat(c *chunkHeartbeat) []*packet { |
| 2257 |
a.log.Tracef("[%s] chunkHeartbeat", a.name) |
| 2258 |
|
| 2259 |
if len(c.params) == 0 { |
| 2260 |
a.log.Warnf("[%s] Heartbeat without ParamHeartbeatInfo (no params)", a.name) |
| 2261 |
|
| 2262 |
return nil |
| 2263 |
} |
| 2264 |
|
| 2265 |
info, ok := c.params[0].(*paramHeartbeatInfo) |
| 2266 |
if !ok { |
| 2267 |
a.log.Warnf("[%s] Heartbeat without ParamHeartbeatInfo (got %T)", a.name, c.params[0]) |
| 2268 |
|
| 2269 |
return nil |
| 2270 |
} |
| 2271 |
|
| 2272 |
return pack(&packet{ |
| 2273 |
verificationTag: a.peerVerificationTag, |
| 2274 |
sourcePort: a.sourcePort, |
| 2275 |
destinationPort: a.destinationPort, |
| 2276 |
chunks: []chunk{&chunkHeartbeatAck{ |
| 2277 |
params: []param{ |
| 2278 |
¶mHeartbeatInfo{ |
| 2279 |
heartbeatInformation: info.heartbeatInformation, |
| 2280 |
}, |
| 2281 |
}, |
| 2282 |
}}, |
| 2283 |
}) |
| 2284 |
} |
| 2285 |
|
| 2286 |
// The caller should hold the lock. |
| 2287 |
func (a *Association) handleHeartbeatAck(c *chunkHeartbeatAck) { |
| 2288 |
a.log.Tracef("[%s] chunkHeartbeatAck", a.name) |
| 2289 |
|
| 2290 |
if len(c.params) == 0 { |
| 2291 |
return |
| 2292 |
} |
| 2293 |
|
| 2294 |
info, ok := c.params[0].(*paramHeartbeatInfo) |
| 2295 |
if !ok { |
| 2296 |
a.log.Warnf("[%s] HeartbeatAck without ParamHeartbeatInfo", a.name) |
| 2297 |
|
| 2298 |
return |
| 2299 |
} |
| 2300 |
|
| 2301 |
// active RTT probe: if heartbeatInformation is exactly 8 bytes, treat it |
| 2302 |
// as a big-endian unix nano timestamp. |
| 2303 |
if len(info.heartbeatInformation) == 8 { |
| 2304 |
ns := binary.BigEndian.Uint64(info.heartbeatInformation) |
| 2305 |
if ns > math.MaxInt64 { |
| 2306 |
// Malformed or future-unsafe value; ignore this heartbeat-ack. |
| 2307 |
a.log.Warnf("[%s] HB RTT: timestamp overflows int64, ignoring", a.name) |
| 2308 |
|
| 2309 |
return |
| 2310 |
} |
| 2311 |
|
| 2312 |
sentNanos := int64(ns) |
| 2313 |
sent := time.Unix(0, sentNanos) |
| 2314 |
now := time.Now() |
| 2315 |
|
| 2316 |
if !sent.IsZero() && !now.Before(sent) { |
| 2317 |
rttMs := now.Sub(sent).Seconds() * 1000.0 |
| 2318 |
srtt := a.rtoMgr.setNewRTT(rttMs) |
| 2319 |
a.srtt.Store(srtt) |
| 2320 |
|
| 2321 |
a.rack.rackMinRTTWnd.Push(now, now.Sub(sent)) |
| 2322 |
|
| 2323 |
a.log.Tracef("[%s] HB RTT: measured=%.3fms srtt=%.3fms rto=%.3fms", |
| 2324 |
a.name, rttMs, srtt, a.rtoMgr.getRTO()) |
| 2325 |
} |
| 2326 |
} |
| 2327 |
} |
| 2328 |
|
| 2329 |
// The caller should hold the lock. |
| 2330 |
func (a *Association) handleCookieEcho(cookieEcho *chunkCookieEcho) []*packet { |
| 2331 |
state := a.getState() |
| 2332 |
a.log.Debugf("[%s] COOKIE-ECHO received in state '%s'", a.name, getAssociationStateString(state)) |
| 2333 |
|
| 2334 |
if a.myCookie == nil { |
| 2335 |
a.log.Debugf("[%s] COOKIE-ECHO received before initialization", a.name) |
| 2336 |
|
| 2337 |
return nil |
| 2338 |
} |
| 2339 |
switch state { |
| 2340 |
default: |
| 2341 |
return nil |
| 2342 |
case established: |
| 2343 |
if !bytes.Equal(a.myCookie.cookie, cookieEcho.cookie) { |
| 2344 |
return nil |
| 2345 |
} |
| 2346 |
case closed, cookieWait, cookieEchoed: |
| 2347 |
if !bytes.Equal(a.myCookie.cookie, cookieEcho.cookie) { |
| 2348 |
return nil |
| 2349 |
} |
| 2350 |
|
| 2351 |
// RFC wise, these do not seem to belong here, but removing them |
| 2352 |
// causes TestCookieEchoRetransmission to break |
| 2353 |
a.t1Init.stop() |
| 2354 |
a.storedInit = nil |
| 2355 |
|
| 2356 |
a.t1Cookie.stop() |
| 2357 |
a.storedCookieEcho = nil |
| 2358 |
|
| 2359 |
if err := a.establish("cookieEcho"); err != nil { |
| 2360 |
a.completeHandshake(err) |
| 2361 |
|
| 2362 |
return nil |
| 2363 |
} |
| 2364 |
if !a.completeHandshake(nil) { |
| 2365 |
return nil |
| 2366 |
} |
| 2367 |
} |
| 2368 |
|
| 2369 |
p := &packet{ |
| 2370 |
verificationTag: a.peerVerificationTag, |
| 2371 |
sourcePort: a.sourcePort, |
| 2372 |
destinationPort: a.destinationPort, |
| 2373 |
chunks: []chunk{&chunkCookieAck{}}, |
| 2374 |
} |
| 2375 |
|
| 2376 |
return pack(p) |
| 2377 |
} |
| 2378 |
|
| 2379 |
// The caller should hold the lock. |
| 2380 |
func (a *Association) handleCookieAck() { |
| 2381 |
state := a.getState() |
| 2382 |
a.log.Debugf("[%s] COOKIE-ACK received in state '%s'", a.name, getAssociationStateString(state)) |
| 2383 |
if state != cookieEchoed { |
| 2384 |
// RFC 4960 |
| 2385 |
// 5.2.5. Handle Duplicate COOKIE-ACK. |
| 2386 |
// At any state other than COOKIE-ECHOED, an endpoint should silently |
| 2387 |
// discard a received COOKIE ACK chunk. |
| 2388 |
return |
| 2389 |
} |
| 2390 |
|
| 2391 |
a.t1Cookie.stop() |
| 2392 |
a.storedCookieEcho = nil |
| 2393 |
|
| 2394 |
if err := a.establish("cookieAck"); err != nil { |
| 2395 |
a.completeHandshake(err) |
| 2396 |
|
| 2397 |
return |
| 2398 |
} |
| 2399 |
a.completeHandshake(nil) |
| 2400 |
} |
| 2401 |
|
| 2402 |
func isDataReceiveState(state uint32) bool { |
| 2403 |
return state == established || state == shutdownPending || state == shutdownSent |
| 2404 |
} |
| 2405 |
|
| 2406 |
func (a *Association) canHandleData(state uint32) bool { |
| 2407 |
return !a.shutdownCompletePending && isDataReceiveState(state) |
| 2408 |
} |
| 2409 |
|
| 2410 |
// The caller should hold the lock. |
| 2411 |
func (a *Association) handleData(chunkPayload *chunkPayloadData) []*packet { |
| 2412 |
state := a.getState() |
| 2413 |
if !a.canHandleData(state) { |
| 2414 |
return nil |
| 2415 |
} |
| 2416 |
|
| 2417 |
if chunkPayload.isIData() != a.useInterleaving { |
| 2418 |
if chunkPayload.isIData() { |
| 2419 |
a.abortProtocolViolation("received I-DATA without interleaving negotiated") |
| 2420 |
} else { |
| 2421 |
a.abortProtocolViolation("received DATA with interleaving negotiated") |
| 2422 |
} |
| 2423 |
|
| 2424 |
return nil |
| 2425 |
} |
| 2426 |
|
| 2427 |
a.log.Tracef("[%s] DATA: tsn=%d immediateSack=%v len=%d", |
| 2428 |
a.name, chunkPayload.tsn, chunkPayload.immediateSack, len(chunkPayload.userData)) |
| 2429 |
a.stats.incDATAs() |
| 2430 |
|
| 2431 |
if state == shutdownSent { |
| 2432 |
// RFC 9260 Sections 6 and 9.2 require DATA received in |
| 2433 |
// SHUTDOWN-SENT to be acknowledged without delay and answered with a |
| 2434 |
// SHUTDOWN. Restart T2 when that SHUTDOWN is sent. |
| 2435 |
a.willSendShutdown = true |
| 2436 |
a.t2Shutdown.stop() |
| 2437 |
} |
| 2438 |
|
| 2439 |
canPush := a.payloadQueue.canPush(chunkPayload.tsn) |
| 2440 |
if canPush { |
| 2441 |
if !a.acceptPayloadData(chunkPayload) { |
| 2442 |
if state == shutdownSent { |
| 2443 |
return a.handlePeerLastTSNAndAcknowledgement(true) |
| 2444 |
} |
| 2445 |
|
| 2446 |
return nil |
| 2447 |
} |
| 2448 |
} |
| 2449 |
|
| 2450 |
// Upon the reception of a new DATA chunk, an endpoint shall examine the |
| 2451 |
// continuity of the TSNs received. If the endpoint detects a gap in |
| 2452 |
// the received DATA chunk sequence, it SHOULD send a SACK with Gap Ack |
| 2453 |
// Blocks immediately. The data receiver continues sending a SACK after |
| 2454 |
// receipt of each SCTP packet that doesn't fill the gap. |
| 2455 |
// https://datatracker.ietf.org/doc/html/rfc4960#section-6.7 |
| 2456 |
expectedTSN := a.peerLastTSN() + 1 |
| 2457 |
gapDetected := sna32GT(chunkPayload.tsn, expectedTSN) |
| 2458 |
|
| 2459 |
sackNow := chunkPayload.immediateSack || gapDetected |
| 2460 |
if state == shutdownSent { |
| 2461 |
sackNow = true |
| 2462 |
} |
| 2463 |
|
| 2464 |
return a.handlePeerLastTSNAndAcknowledgement(sackNow) |
| 2465 |
} |
| 2466 |
|
| 2467 |
// The caller should hold the lock. |
| 2468 |
func (a *Association) acceptPayloadData(chunkPayload *chunkPayloadData) bool { |
| 2469 |
stream := a.getOrCreateStream(chunkPayload.streamIdentifier, true, PayloadTypeUnknown) |
| 2470 |
if stream == nil { |
| 2471 |
// silently discard the data. (sender will retry on T3-rtx timeout) |
| 2472 |
// see pion/sctp#30 |
| 2473 |
a.log.Debugf("[%s] discard %d", a.name, chunkPayload.streamSequenceNumber) |
| 2474 |
|
| 2475 |
return false |
| 2476 |
} |
| 2477 |
|
| 2478 |
if a.getMyReceiverWindowCredit() > 0 { |
| 2479 |
// Pass the new chunk to stream level as soon as it arrives |
| 2480 |
return a.pushPayloadDataToStream(stream, chunkPayload) |
| 2481 |
} |
| 2482 |
|
| 2483 |
// Receive buffer is full |
| 2484 |
lastTSN, ok := a.payloadQueue.getLastTSNReceived() |
| 2485 |
if !ok || !sna32LT(chunkPayload.tsn, lastTSN) { |
| 2486 |
a.log.Debugf( |
| 2487 |
"[%s] receive buffer full. dropping DATA with tsn=%d ssn=%d", |
| 2488 |
a.name, chunkPayload.tsn, chunkPayload.streamSequenceNumber, |
| 2489 |
) |
| 2490 |
|
| 2491 |
return true |
| 2492 |
} |
| 2493 |
|
| 2494 |
a.log.Debugf( |
| 2495 |
"[%s] receive buffer full, but accepted as this is a missing chunk with tsn=%d ssn=%d", |
| 2496 |
a.name, chunkPayload.tsn, chunkPayload.streamSequenceNumber, |
| 2497 |
) |
| 2498 |
|
| 2499 |
return a.pushPayloadDataToStream(stream, chunkPayload) |
| 2500 |
} |
| 2501 |
|
| 2502 |
// The caller should hold the lock. |
| 2503 |
func (a *Association) pushPayloadDataToStream(stream *Stream, chunkPayload *chunkPayloadData) bool { |
| 2504 |
a.payloadQueue.push(chunkPayload.tsn) |
| 2505 |
if err := stream.handleData(chunkPayload); err != nil { |
| 2506 |
a.abortProtocolViolation(err.Error()) |
| 2507 |
|
| 2508 |
return false |
| 2509 |
} |
| 2510 |
|
| 2511 |
return true |
| 2512 |
} |
| 2513 |
|
| 2514 |
// A common routine for handleData and handleForwardTSN routines |
| 2515 |
// The caller should hold the lock. |
| 2516 |
func (a *Association) handlePeerLastTSNAndAcknowledgement(sackImmediately bool) []*packet { //nolint:cyclop |
| 2517 |
var reply []*packet |
| 2518 |
|
| 2519 |
// Try to advance peerLastTSN |
| 2520 |
|
| 2521 |
// From RFC 3758 Sec 3.6: |
| 2522 |
// .. and then MUST further advance its cumulative TSN point locally |
| 2523 |
// if possible |
| 2524 |
// Meaning, if peerLastTSN+1 points to a chunk that is received, |
| 2525 |
// advance peerLastTSN until peerLastTSN+1 points to unreceived chunk. |
| 2526 |
for { |
| 2527 |
if popOk := a.payloadQueue.pop(false); !popOk { |
| 2528 |
break |
| 2529 |
} |
| 2530 |
|
| 2531 |
for _, rstReq := range a.reconfigRequests { |
| 2532 |
resp := a.resetStreamsIfAny(rstReq) |
| 2533 |
if resp != nil { |
| 2534 |
a.log.Debugf("[%s] RESET RESPONSE: %+v", a.name, resp) |
| 2535 |
reply = append(reply, resp) |
| 2536 |
} |
| 2537 |
} |
| 2538 |
} |
| 2539 |
|
| 2540 |
hasPacketLoss := (a.payloadQueue.size() > 0) |
| 2541 |
if hasPacketLoss { |
| 2542 |
a.log.Tracef("[%s] packetloss: %s", a.name, a.payloadQueue.getGapAckBlocksString()) |
| 2543 |
} |
| 2544 |
|
| 2545 |
// RFC 4960 $6.7: SHOULD ack immediately when detecting a gap. |
| 2546 |
if sackImmediately || hasPacketLoss || a.ackMode == ackModeNoDelay { |
| 2547 |
a.immediateAckTriggered = true |
| 2548 |
|
| 2549 |
return reply |
| 2550 |
} |
| 2551 |
|
| 2552 |
if a.ackMode == ackModeAlwaysDelay || (a.ackMode == ackModeNormal && a.ackState != ackStateImmediate) { |
| 2553 |
if a.ackState == ackStateIdle { |
| 2554 |
a.delayedAckTriggered = true |
| 2555 |
} else { |
| 2556 |
a.immediateAckTriggered = true |
| 2557 |
} |
| 2558 |
|
| 2559 |
return reply |
| 2560 |
} |
| 2561 |
|
| 2562 |
a.immediateAckTriggered = true |
| 2563 |
|
| 2564 |
return reply |
| 2565 |
} |
| 2566 |
|
| 2567 |
// The caller should hold the lock. |
| 2568 |
func (a *Association) getMyReceiverWindowCredit() uint32 { |
| 2569 |
var bytesQueued uint32 |
| 2570 |
for _, s := range a.streams { |
| 2571 |
bytesQueued += uint32(s.getNumBytesInReassemblyQueue()) //nolint:gosec // G115 |
| 2572 |
} |
| 2573 |
|
| 2574 |
if bytesQueued >= a.maxReceiveBufferSize { |
| 2575 |
return 0 |
| 2576 |
} |
| 2577 |
|
| 2578 |
return a.maxReceiveBufferSize - bytesQueued |
| 2579 |
} |
| 2580 |
|
| 2581 |
// OpenStream opens a stream. |
| 2582 |
func (a *Association) OpenStream( |
| 2583 |
streamIdentifier uint16, |
| 2584 |
defaultPayloadType PayloadProtocolIdentifier, |
| 2585 |
) (*Stream, error) { |
| 2586 |
a.lock.Lock() |
| 2587 |
defer a.lock.Unlock() |
| 2588 |
|
| 2589 |
switch a.getState() { |
| 2590 |
case shutdownAckSent, shutdownPending, shutdownReceived, shutdownSent, closed: |
| 2591 |
return nil, ErrAssociationClosed |
| 2592 |
} |
| 2593 |
|
| 2594 |
return a.getOrCreateStream(streamIdentifier, false, defaultPayloadType), nil |
| 2595 |
} |
| 2596 |
|
| 2597 |
// AcceptStream accepts a stream. |
| 2598 |
func (a *Association) AcceptStream() (*Stream, error) { |
| 2599 |
s, ok := <-a.acceptCh |
| 2600 |
if !ok { |
| 2601 |
return nil, io.EOF // no more incoming streams |
| 2602 |
} |
| 2603 |
|
| 2604 |
return s, nil |
| 2605 |
} |
| 2606 |
|
| 2607 |
// createStream creates a stream. The caller should hold the lock and check no stream exists for this id. |
| 2608 |
func (a *Association) createStream(streamIdentifier uint16, accept bool) *Stream { |
| 2609 |
stream := &Stream{ |
| 2610 |
association: a, |
| 2611 |
streamIdentifier: streamIdentifier, |
| 2612 |
reassemblyQueue: newReassemblyQueue( |
| 2613 |
streamIdentifier, |
| 2614 |
a.maxReassemblyQueueEntries, |
| 2615 |
), |
| 2616 |
log: a.log, |
| 2617 |
name: fmt.Sprintf("%d:%s", streamIdentifier, a.name), |
| 2618 |
writeDeadline: deadline.New(), |
| 2619 |
} |
| 2620 |
|
| 2621 |
stream.readNotifier = sync.NewCond(&stream.lock) |
| 2622 |
|
| 2623 |
if accept { |
| 2624 |
select { |
| 2625 |
case a.acceptCh <- stream: |
| 2626 |
a.streams[streamIdentifier] = stream |
| 2627 |
a.log.Debugf("[%s] accepted a new stream (streamIdentifier: %d)", |
| 2628 |
a.name, streamIdentifier) |
| 2629 |
default: |
| 2630 |
a.log.Debugf("[%s] dropped a new stream (acceptCh size: %d)", |
| 2631 |
a.name, len(a.acceptCh)) |
| 2632 |
|
| 2633 |
return nil |
| 2634 |
} |
| 2635 |
} else { |
| 2636 |
a.streams[streamIdentifier] = stream |
| 2637 |
} |
| 2638 |
|
| 2639 |
return stream |
| 2640 |
} |
| 2641 |
|
| 2642 |
// getOrCreateStream gets or creates a stream. The caller should hold the lock. |
| 2643 |
func (a *Association) getOrCreateStream( |
| 2644 |
streamIdentifier uint16, |
| 2645 |
accept bool, |
| 2646 |
defaultPayloadType PayloadProtocolIdentifier, |
| 2647 |
) *Stream { |
| 2648 |
if s, ok := a.streams[streamIdentifier]; ok { |
| 2649 |
s.SetDefaultPayloadType(defaultPayloadType) |
| 2650 |
|
| 2651 |
return s |
| 2652 |
} |
| 2653 |
|
| 2654 |
s := a.createStream(streamIdentifier, accept) |
| 2655 |
if s != nil { |
| 2656 |
s.SetDefaultPayloadType(defaultPayloadType) |
| 2657 |
} |
| 2658 |
|
| 2659 |
return s |
| 2660 |
} |
| 2661 |
|
| 2662 |
// The caller should hold the lock. |
| 2663 |
// |
| 2664 |
//nolint:gocognit,cyclop |
| 2665 |
func (a *Association) processSelectiveAck(selectiveAckChunk *chunkSelectiveAck) ( |
| 2666 |
bytesAckedPerStream map[uint16]int, |
| 2667 |
htna uint32, |
| 2668 |
newestDeliveredSendTime time.Time, |
| 2669 |
newestDeliveredOrigTSN uint32, |
| 2670 |
deliveredFound bool, |
| 2671 |
err error, |
| 2672 |
) { |
| 2673 |
bytesAckedPerStream = map[uint16]int{} |
| 2674 |
now := time.Now() // capture the time for this SACK |
| 2675 |
|
| 2676 |
// Validate that full range exists in the inflight queue to prevent partial pops |
| 2677 |
// left over from an invalid SACK that causes the cumulativeTSNAckPoint to be updated |
| 2678 |
// incorrectly and causes weird state and race conditions. |
| 2679 |
if sna32LT(a.cumulativeTSNAckPoint, selectiveAckChunk.cumulativeTSNAck) { |
| 2680 |
firstTSN := a.cumulativeTSNAckPoint + 1 |
| 2681 |
if _, ok := a.inflightQueue.get(firstTSN); !ok { |
| 2682 |
return nil, 0, time.Time{}, 0, false, fmt.Errorf("%w: %v", ErrInflightQueueTSNPop, firstTSN) |
| 2683 |
} |
| 2684 |
if _, ok := a.inflightQueue.get(selectiveAckChunk.cumulativeTSNAck); !ok { |
| 2685 |
return nil, 0, time.Time{}, 0, false, |
| 2686 |
fmt.Errorf("%w: %v", ErrInflightQueueTSNPop, selectiveAckChunk.cumulativeTSNAck) |
| 2687 |
} |
| 2688 |
} |
| 2689 |
for _, gap := range selectiveAckChunk.gapAckBlocks { |
| 2690 |
if gap.start == 0 { |
| 2691 |
return nil, 0, time.Time{}, 0, false, |
| 2692 |
fmt.Errorf("%w: %v", ErrTSNRequestNotExist, selectiveAckChunk.cumulativeTSNAck) |
| 2693 |
} |
| 2694 |
if gap.start > gap.end { |
| 2695 |
return nil, 0, time.Time{}, 0, false, |
| 2696 |
fmt.Errorf("%w: invalid Gap Ack Block %d-%d", ErrTSNRequestNotExist, gap.start, gap.end) |
| 2697 |
} |
| 2698 |
|
| 2699 |
firstTSN := selectiveAckChunk.cumulativeTSNAck + uint32(gap.start) |
| 2700 |
if _, ok := a.inflightQueue.get(firstTSN); !ok { |
| 2701 |
return nil, 0, time.Time{}, 0, false, fmt.Errorf("%w: %v", ErrTSNRequestNotExist, firstTSN) |
| 2702 |
} |
| 2703 |
lastTSN := selectiveAckChunk.cumulativeTSNAck + uint32(gap.end) |
| 2704 |
if lastTSN != firstTSN { |
| 2705 |
if _, ok := a.inflightQueue.get(lastTSN); !ok { |
| 2706 |
return nil, 0, time.Time{}, 0, false, |
| 2707 |
fmt.Errorf("%w: %v", ErrTSNRequestNotExist, lastTSN) |
| 2708 |
} |
| 2709 |
} |
| 2710 |
} |
| 2711 |
|
| 2712 |
// New ack point, so pop all ACKed packets from inflightQueue |
| 2713 |
// We add 1 because the "currentAckPoint" has already been popped from the inflight queue |
| 2714 |
// For the first SACK we take care of this by setting the ackpoint to cumAck - 1 |
| 2715 |
for idx := a.cumulativeTSNAckPoint + 1; sna32LTE(idx, selectiveAckChunk.cumulativeTSNAck); idx++ { |
| 2716 |
chunkPayload, ok := a.inflightQueue.pop(idx) |
| 2717 |
if !ok { |
| 2718 |
return nil, 0, time.Time{}, 0, false, fmt.Errorf("%w: %v", ErrInflightQueueTSNPop, idx) |
| 2719 |
} |
| 2720 |
|
| 2721 |
// RACK: remove from xmit-time list since it's delivered |
| 2722 |
a.rackRemove(chunkPayload) |
| 2723 |
|
| 2724 |
if !chunkPayload.acked { //nolint:nestif |
| 2725 |
// RFC 4960 sec 6.3.2. Retransmission Timer Rules |
| 2726 |
// R3) Whenever a SACK is received that acknowledges the DATA chunk |
| 2727 |
// with the earliest outstanding TSN for that address, restart the |
| 2728 |
// T3-rtx timer for that address with its current RTO (if there is |
| 2729 |
// still outstanding data on that address). |
| 2730 |
if idx == a.cumulativeTSNAckPoint+1 { |
| 2731 |
// T3 timer needs to be reset. Stop it for now. |
| 2732 |
a.t3RTX.stop() |
| 2733 |
} |
| 2734 |
|
| 2735 |
nBytesAcked := len(chunkPayload.userData) |
| 2736 |
|
| 2737 |
// Sum the number of bytes acknowledged per stream |
| 2738 |
if amount, ok := bytesAckedPerStream[chunkPayload.streamIdentifier]; ok { |
| 2739 |
bytesAckedPerStream[chunkPayload.streamIdentifier] = amount + nBytesAcked |
| 2740 |
} else { |
| 2741 |
bytesAckedPerStream[chunkPayload.streamIdentifier] = nBytesAcked |
| 2742 |
} |
| 2743 |
|
| 2744 |
// RFC 4960 sec 6.3.1. RTO Calculation |
| 2745 |
// C4) When data is in flight and when allowed by rule C5 below, a new |
| 2746 |
// RTT measurement MUST be made each round trip. Furthermore, new |
| 2747 |
// RTT measurements SHOULD be made no more than once per round trip |
| 2748 |
// for a given destination transport address. |
| 2749 |
// C5) Karn's algorithm: RTT measurements MUST NOT be made using |
| 2750 |
// packets that were retransmitted (and thus for which it is |
| 2751 |
// ambiguous whether the reply was for the first instance of the |
| 2752 |
// chunk or for a later instance) |
| 2753 |
if sna32GTE(chunkPayload.tsn, a.minTSN2MeasureRTT) { |
| 2754 |
// Only original transmissions for classic RTT measurement (Karn's rule) |
| 2755 |
if chunkPayload.nSent == 1 { |
| 2756 |
a.minTSN2MeasureRTT = a.myNextTSN |
| 2757 |
rtt := now.Sub(chunkPayload.since).Seconds() * 1000.0 |
| 2758 |
srtt := a.rtoMgr.setNewRTT(rtt) |
| 2759 |
a.srtt.Store(srtt) |
| 2760 |
|
| 2761 |
// use a window to determine minRtt instead of a global min |
| 2762 |
// as the RTT can fluctuate, which can cause problems if going from a |
| 2763 |
// high RTT to a low RTT. |
| 2764 |
a.rack.rackMinRTTWnd.Push(now, now.Sub(chunkPayload.since)) |
| 2765 |
|
| 2766 |
a.log.Tracef("[%s] SACK: measured-rtt=%f srtt=%f new-rto=%f", |
| 2767 |
a.name, rtt, srtt, a.rtoMgr.getRTO()) |
| 2768 |
} |
| 2769 |
} |
| 2770 |
|
| 2771 |
// RFC 8985 (RACK) sec 5.2: RACK.segment is the most recently sent |
| 2772 |
// segment that has been delivered, including retransmissions. |
| 2773 |
if chunkPayload.since.After(newestDeliveredSendTime) { |
| 2774 |
newestDeliveredSendTime = chunkPayload.since |
| 2775 |
newestDeliveredOrigTSN = chunkPayload.tsn |
| 2776 |
deliveredFound = true |
| 2777 |
} |
| 2778 |
} |
| 2779 |
|
| 2780 |
if a.inFastRecovery && chunkPayload.tsn == a.fastRecoverExitPoint { |
| 2781 |
a.log.Debugf("[%s] exit fast-recovery", a.name) |
| 2782 |
a.inFastRecovery = false |
| 2783 |
} |
| 2784 |
} |
| 2785 |
|
| 2786 |
htna = selectiveAckChunk.cumulativeTSNAck |
| 2787 |
|
| 2788 |
// Mark selectively acknowledged chunks as "acked" |
| 2789 |
for _, g := range selectiveAckChunk.gapAckBlocks { |
| 2790 |
for i := uint32(g.start); i <= uint32(g.end); i++ { |
| 2791 |
tsn := selectiveAckChunk.cumulativeTSNAck + i |
| 2792 |
chunkPayload, ok := a.inflightQueue.get(tsn) |
| 2793 |
if !ok { |
| 2794 |
return nil, 0, time.Time{}, 0, false, fmt.Errorf("%w: %v", ErrTSNRequestNotExist, tsn) |
| 2795 |
} |
| 2796 |
|
| 2797 |
// RACK: remove from xmit-time list since it's delivered |
| 2798 |
a.rackRemove(chunkPayload) |
| 2799 |
|
| 2800 |
if !chunkPayload.acked { //nolint:nestif |
| 2801 |
nBytesAcked := a.inflightQueue.markAsAcked(tsn) |
| 2802 |
|
| 2803 |
// Sum the number of bytes acknowledged per stream |
| 2804 |
if amount, ok := bytesAckedPerStream[chunkPayload.streamIdentifier]; ok { |
| 2805 |
bytesAckedPerStream[chunkPayload.streamIdentifier] = amount + nBytesAcked |
| 2806 |
} else { |
| 2807 |
bytesAckedPerStream[chunkPayload.streamIdentifier] = nBytesAcked |
| 2808 |
} |
| 2809 |
|
| 2810 |
a.log.Tracef("[%s] tsn=%d has been sacked", a.name, chunkPayload.tsn) |
| 2811 |
|
| 2812 |
// RTT / RTO and RACK updates |
| 2813 |
if sna32GTE(chunkPayload.tsn, a.minTSN2MeasureRTT) { |
| 2814 |
// Only original transmissions for classic RTT measurement |
| 2815 |
if chunkPayload.nSent == 1 { |
| 2816 |
a.minTSN2MeasureRTT = a.myNextTSN |
| 2817 |
rtt := now.Sub(chunkPayload.since).Seconds() * 1000.0 |
| 2818 |
srtt := a.rtoMgr.setNewRTT(rtt) |
| 2819 |
a.srtt.Store(srtt) |
| 2820 |
|
| 2821 |
a.rack.rackMinRTTWnd.Push(now, now.Sub(chunkPayload.since)) |
| 2822 |
|
| 2823 |
a.log.Tracef("[%s] SACK: measured-rtt=%f srtt=%f new-rto=%f", |
| 2824 |
a.name, rtt, srtt, a.rtoMgr.getRTO()) |
| 2825 |
} |
| 2826 |
} |
| 2827 |
|
| 2828 |
if chunkPayload.since.After(newestDeliveredSendTime) { |
| 2829 |
newestDeliveredSendTime = chunkPayload.since |
| 2830 |
newestDeliveredOrigTSN = chunkPayload.tsn |
| 2831 |
deliveredFound = true |
| 2832 |
} |
| 2833 |
} |
| 2834 |
|
| 2835 |
if sna32LT(htna, tsn) { |
| 2836 |
htna = tsn |
| 2837 |
} |
| 2838 |
} |
| 2839 |
} |
| 2840 |
|
| 2841 |
return bytesAckedPerStream, htna, newestDeliveredSendTime, newestDeliveredOrigTSN, deliveredFound, nil |
| 2842 |
} |
| 2843 |
|
| 2844 |
// The caller should hold the lock. |
| 2845 |
func (a *Association) onCumulativeTSNAckPointAdvanced(totalBytesAcked int) { |
| 2846 |
// RFC 4960, sec 6.3.2. Retransmission Timer Rules |
| 2847 |
// R2) Whenever all outstanding data sent to an address have been |
| 2848 |
// acknowledged, turn off the T3-rtx timer of that address. |
| 2849 |
if a.inflightQueue.size() == 0 { |
| 2850 |
a.log.Tracef("[%s] SACK: no more packet in-flight (pending=%d)", a.name, a.pendingQueue.size()) |
| 2851 |
a.t3RTX.stop() |
| 2852 |
a.stopPTOTimer() |
| 2853 |
a.stopRackTimer() |
| 2854 |
} else { |
| 2855 |
a.log.Tracef("[%s] T3-rtx timer start (pt2)", a.name) |
| 2856 |
a.t3RTX.start(a.rtoMgr.getRTO()) |
| 2857 |
} |
| 2858 |
|
| 2859 |
// Update congestion control parameters |
| 2860 |
if a.CWND() <= a.ssthresh { //nolint:nestif |
| 2861 |
// RFC 4960, sec 7.2.1. Slow-Start |
| 2862 |
// o When cwnd is less than or equal to ssthresh, an SCTP endpoint MUST |
| 2863 |
// use the slow-start algorithm to increase cwnd only if the current |
| 2864 |
// congestion window is being fully utilized, an incoming SACK |
| 2865 |
// advances the Cumulative TSN Ack Point, and the data sender is not |
| 2866 |
// in Fast Recovery. Only when these three conditions are met can |
| 2867 |
// the cwnd be increased; otherwise, the cwnd MUST not be increased. |
| 2868 |
// If these conditions are met, then cwnd MUST be increased by, at |
| 2869 |
// most, the lesser of 1) the total size of the previously |
| 2870 |
// outstanding DATA chunk(s) acknowledged, and 2) the destination's |
| 2871 |
// path MTU. |
| 2872 |
if !a.inFastRecovery && |
| 2873 |
a.pendingQueue.size() > 0 { |
| 2874 |
a.setCWND(a.CWND() + min32(uint32(totalBytesAcked), a.CWND())) //nolint:gosec // G115 |
| 2875 |
// a.cwnd += min32(uint32(totalBytesAcked), a.MTU()) // SCTP way (slow) |
| 2876 |
a.log.Tracef("[%s] updated cwnd=%d ssthresh=%d acked=%d (SS)", |
| 2877 |
a.name, a.CWND(), a.ssthresh, totalBytesAcked) |
| 2878 |
} else { |
| 2879 |
a.log.Tracef("[%s] cwnd did not grow: cwnd=%d ssthresh=%d acked=%d FR=%v pending=%d", |
| 2880 |
a.name, a.CWND(), a.ssthresh, totalBytesAcked, a.inFastRecovery, a.pendingQueue.size()) |
| 2881 |
} |
| 2882 |
} else { |
| 2883 |
// RFC 4960, sec 7.2.2. Congestion Avoidance |
| 2884 |
// o Whenever cwnd is greater than ssthresh, upon each SACK arrival |
| 2885 |
// that advances the Cumulative TSN Ack Point, increase |
| 2886 |
// partial_bytes_acked by the total number of bytes of all new chunks |
| 2887 |
// acknowledged in that SACK including chunks acknowledged by the new |
| 2888 |
// Cumulative TSN Ack and by Gap Ack Blocks. |
| 2889 |
a.partialBytesAcked += uint32(totalBytesAcked) //nolint:gosec // G115 |
| 2890 |
|
| 2891 |
// o When partial_bytes_acked is equal to or greater than cwnd and |
| 2892 |
// before the arrival of the SACK the sender had cwnd or more bytes |
| 2893 |
// of data outstanding (i.e., before arrival of the SACK, flight size |
| 2894 |
// was greater than or equal to cwnd), increase cwnd by MTU, and |
| 2895 |
// reset partial_bytes_acked to (partial_bytes_acked - cwnd). |
| 2896 |
if a.partialBytesAcked >= a.CWND() && a.pendingQueue.size() > 0 { |
| 2897 |
a.partialBytesAcked -= a.CWND() |
| 2898 |
step := max(a.MTU(), a.cwndCAStep) |
| 2899 |
a.setCWND(a.CWND() + step) |
| 2900 |
a.log.Tracef("[%s] updated cwnd=%d ssthresh=%d acked=%d (CA)", |
| 2901 |
a.name, a.CWND(), a.ssthresh, totalBytesAcked) |
| 2902 |
} |
| 2903 |
} |
| 2904 |
} |
| 2905 |
|
| 2906 |
// The caller should hold the lock. |
| 2907 |
// |
| 2908 |
//nolint:cyclop |
| 2909 |
func (a *Association) processFastRetransmission( //nolint:gocognit |
| 2910 |
cumTSNAckPoint uint32, |
| 2911 |
gapAckBlocks []gapAckBlock, |
| 2912 |
htna uint32, |
| 2913 |
cumTSNAckPointAdvanced bool, |
| 2914 |
) error { |
| 2915 |
// HTNA algorithm - RFC 4960 Sec 7.2.4 |
| 2916 |
// Increment missIndicator of each chunks that the SACK reported missing |
| 2917 |
// when either of the following is met: |
| 2918 |
// a) Not in fast-recovery |
| 2919 |
// miss indications are incremented only for missing TSNs prior to the |
| 2920 |
// highest TSN newly acknowledged in the SACK. |
| 2921 |
// b) In fast-recovery AND the Cumulative TSN Ack Point advanced |
| 2922 |
// the miss indications are incremented for all TSNs reported missing |
| 2923 |
// in the SACK. |
| 2924 |
//nolint:nestif |
| 2925 |
if !a.inFastRecovery || |
| 2926 |
(a.inFastRecovery && cumTSNAckPointAdvanced) { |
| 2927 |
var maxTSN uint32 |
| 2928 |
if !a.inFastRecovery { |
| 2929 |
// a) increment only for missing TSNs prior to the HTNA |
| 2930 |
maxTSN = htna |
| 2931 |
} else { |
| 2932 |
// b) increment for all TSNs reported missing |
| 2933 |
maxTSN = cumTSNAckPoint |
| 2934 |
if len(gapAckBlocks) > 0 { |
| 2935 |
maxTSN += uint32(gapAckBlocks[len(gapAckBlocks)-1].end) |
| 2936 |
} |
| 2937 |
} |
| 2938 |
|
| 2939 |
for tsn := cumTSNAckPoint + 1; sna32LT(tsn, maxTSN); tsn++ { |
| 2940 |
c, ok := a.inflightQueue.get(tsn) |
| 2941 |
if !ok { |
| 2942 |
return fmt.Errorf("%w: %v", ErrTSNRequestNotExist, tsn) |
| 2943 |
} |
| 2944 |
if !c.acked && !c.abandoned() && c.missIndicator < 3 { |
| 2945 |
c.missIndicator++ |
| 2946 |
if c.missIndicator == 3 { |
| 2947 |
if a.tlrActive { |
| 2948 |
a.tlrApplyAdditionalLossLocked(time.Now()) |
| 2949 |
} |
| 2950 |
|
| 2951 |
if !a.inFastRecovery { |
| 2952 |
// 2) If not in Fast Recovery, adjust the ssthresh and cwnd of the |
| 2953 |
// destination address(es) to which the missing DATA chunks were |
| 2954 |
// last sent, according to the formula described in Section 7.2.3. |
| 2955 |
a.inFastRecovery = true |
| 2956 |
a.fastRecoverExitPoint = htna |
| 2957 |
a.ssthresh = max32(a.CWND()/2, 4*a.MTU()) |
| 2958 |
a.setCWND(a.ssthresh) |
| 2959 |
a.partialBytesAcked = 0 |
| 2960 |
a.willRetransmitFast = true |
| 2961 |
|
| 2962 |
a.log.Tracef("[%s] updated cwnd=%d ssthresh=%d inflight=%d (FR)", |
| 2963 |
a.name, a.CWND(), a.ssthresh, a.inflightQueue.getNumBytes()) |
| 2964 |
} |
| 2965 |
} |
| 2966 |
} |
| 2967 |
} |
| 2968 |
} |
| 2969 |
|
| 2970 |
if a.inFastRecovery && cumTSNAckPointAdvanced { |
| 2971 |
a.willRetransmitFast = true |
| 2972 |
} |
| 2973 |
|
| 2974 |
return nil |
| 2975 |
} |
| 2976 |
|
| 2977 |
type acknowledgementResult struct { |
| 2978 |
htna uint32 |
| 2979 |
newestDeliveredSendTime time.Time |
| 2980 |
newestDeliveredOrigTSN uint32 |
| 2981 |
processed bool |
| 2982 |
cumTSNAckPointAdvanced bool |
| 2983 |
deliveredFound bool |
| 2984 |
} |
| 2985 |
|
| 2986 |
// processAcknowledgement applies the fields shared by SACK and SHUTDOWN. |
| 2987 |
// The caller should hold the lock. |
| 2988 |
func (a *Association) processAcknowledgement( |
| 2989 |
selectiveAckChunk *chunkSelectiveAck, |
| 2990 |
) (acknowledgementResult, error) { |
| 2991 |
if sna32GT(a.cumulativeTSNAckPoint, selectiveAckChunk.cumulativeTSNAck) { |
| 2992 |
// RFC 4960 sec 6.2.1. Processing a Received SACK |
| 2993 |
// D) |
| 2994 |
// i) If Cumulative TSN Ack is less than the Cumulative TSN Ack |
| 2995 |
// Point, then drop the SACK. Since Cumulative TSN Ack is |
| 2996 |
// monotonically increasing, a SACK whose Cumulative TSN Ack is |
| 2997 |
// less than the Cumulative TSN Ack Point indicates an out-of- |
| 2998 |
// order SACK. |
| 2999 |
|
| 3000 |
a.log.Debugf("[%s] SACK Cumulative ACK %v is older than ACK point %v", |
| 3001 |
a.name, |
| 3002 |
selectiveAckChunk.cumulativeTSNAck, |
| 3003 |
a.cumulativeTSNAckPoint) |
| 3004 |
|
| 3005 |
return acknowledgementResult{}, nil |
| 3006 |
} |
| 3007 |
|
| 3008 |
// Process selective ack |
| 3009 |
bytesAckedPerStream, htna, |
| 3010 |
newestDeliveredSendTime, newestDeliveredOrigTSN, |
| 3011 |
deliveredFound, err := a.processSelectiveAck(selectiveAckChunk) |
| 3012 |
if err != nil { |
| 3013 |
return acknowledgementResult{}, err |
| 3014 |
} |
| 3015 |
|
| 3016 |
var totalBytesAcked int |
| 3017 |
for _, nBytesAcked := range bytesAckedPerStream { |
| 3018 |
totalBytesAcked += nBytesAcked |
| 3019 |
} |
| 3020 |
|
| 3021 |
cumTSNAckPointAdvanced := false |
| 3022 |
if sna32LT(a.cumulativeTSNAckPoint, selectiveAckChunk.cumulativeTSNAck) { |
| 3023 |
a.log.Tracef("[%s] SACK: cumTSN advanced: %d -> %d", |
| 3024 |
a.name, |
| 3025 |
a.cumulativeTSNAckPoint, |
| 3026 |
selectiveAckChunk.cumulativeTSNAck) |
| 3027 |
|
| 3028 |
a.cumulativeTSNAckPoint = selectiveAckChunk.cumulativeTSNAck |
| 3029 |
cumTSNAckPointAdvanced = true |
| 3030 |
a.onCumulativeTSNAckPointAdvanced(totalBytesAcked) |
| 3031 |
} |
| 3032 |
|
| 3033 |
for si, nBytesAcked := range bytesAckedPerStream { |
| 3034 |
if s, ok := a.streams[si]; ok { |
| 3035 |
a.lock.Unlock() |
| 3036 |
s.onBufferReleased(nBytesAcked) |
| 3037 |
a.lock.Lock() |
| 3038 |
} |
| 3039 |
} |
| 3040 |
|
| 3041 |
return acknowledgementResult{ |
| 3042 |
htna: htna, |
| 3043 |
newestDeliveredSendTime: newestDeliveredSendTime, |
| 3044 |
newestDeliveredOrigTSN: newestDeliveredOrigTSN, |
| 3045 |
processed: true, |
| 3046 |
cumTSNAckPointAdvanced: cumTSNAckPointAdvanced, |
| 3047 |
deliveredFound: deliveredFound, |
| 3048 |
}, nil |
| 3049 |
} |
| 3050 |
|
| 3051 |
// finishAcknowledgement applies acknowledgement processing that does not |
| 3052 |
// depend on SACK-only fields. |
| 3053 |
// The caller should hold the lock. |
| 3054 |
func (a *Association) finishAcknowledgement( |
| 3055 |
selectiveAckChunk *chunkSelectiveAck, |
| 3056 |
result acknowledgementResult, |
| 3057 |
) error { |
| 3058 |
err := a.processFastRetransmission( |
| 3059 |
selectiveAckChunk.cumulativeTSNAck, |
| 3060 |
selectiveAckChunk.gapAckBlocks, |
| 3061 |
result.htna, |
| 3062 |
result.cumTSNAckPointAdvanced, |
| 3063 |
) |
| 3064 |
if err != nil { |
| 3065 |
return err |
| 3066 |
} |
| 3067 |
|
| 3068 |
if a.partialReliabilityEnabled() { |
| 3069 |
// RFC 3758 Sec 3.5 C1 |
| 3070 |
if sna32LT(a.advancedPeerTSNAckPoint, a.cumulativeTSNAckPoint) { |
| 3071 |
a.advancedPeerTSNAckPoint = a.cumulativeTSNAckPoint |
| 3072 |
} |
| 3073 |
|
| 3074 |
// RFC 3758 Sec 3.5 C2 |
| 3075 |
for i := a.advancedPeerTSNAckPoint + 1; ; i++ { |
| 3076 |
c, ok := a.inflightQueue.get(i) |
| 3077 |
if !ok { |
| 3078 |
break |
| 3079 |
} |
| 3080 |
if !c.abandoned() { |
| 3081 |
break |
| 3082 |
} |
| 3083 |
a.advancedPeerTSNAckPoint = i |
| 3084 |
} |
| 3085 |
|
| 3086 |
// RFC 3758 Sec 3.5 C3 |
| 3087 |
if sna32GT(a.advancedPeerTSNAckPoint, a.cumulativeTSNAckPoint) { |
| 3088 |
a.willSendForwardTSN = true |
| 3089 |
} |
| 3090 |
a.awakeWriteLoop() |
| 3091 |
} |
| 3092 |
|
| 3093 |
return nil |
| 3094 |
} |
| 3095 |
|
| 3096 |
// The caller should hold the lock. |
| 3097 |
// |
| 3098 |
//nolint:cyclop |
| 3099 |
func (a *Association) handleSack(selectiveAckChunk *chunkSelectiveAck) error { |
| 3100 |
a.log.Tracef( |
| 3101 |
"[%s] SACK: cumTSN=%d a_rwnd=%d", |
| 3102 |
a.name, selectiveAckChunk.cumulativeTSNAck, selectiveAckChunk.advertisedReceiverWindowCredit, |
| 3103 |
) |
| 3104 |
state := a.getState() |
| 3105 |
if state != established && state != shutdownPending && state != shutdownReceived { |
| 3106 |
return nil |
| 3107 |
} |
| 3108 |
|
| 3109 |
a.stats.incSACKsReceived() |
| 3110 |
|
| 3111 |
result, err := a.processAcknowledgement(selectiveAckChunk) |
| 3112 |
if err != nil || !result.processed { |
| 3113 |
return err |
| 3114 |
} |
| 3115 |
|
| 3116 |
// New rwnd value |
| 3117 |
// RFC 4960 sec 6.2.1. Processing a Received SACK |
| 3118 |
// D) |
| 3119 |
// ii) Set rwnd equal to the newly received a_rwnd minus the number |
| 3120 |
// of bytes still outstanding after processing the Cumulative |
| 3121 |
// TSN Ack and the Gap Ack Blocks. |
| 3122 |
|
| 3123 |
// bytes acked were already subtracted by markAsAcked() method |
| 3124 |
bytesOutstanding := uint32(a.inflightQueue.getNumBytes()) //nolint:gosec // G115 |
| 3125 |
if bytesOutstanding >= selectiveAckChunk.advertisedReceiverWindowCredit { |
| 3126 |
a.setRWND(0) |
| 3127 |
} else { |
| 3128 |
a.setRWND(selectiveAckChunk.advertisedReceiverWindowCredit - bytesOutstanding) |
| 3129 |
} |
| 3130 |
|
| 3131 |
if err = a.finishAcknowledgement(selectiveAckChunk, result); err != nil { |
| 3132 |
return err |
| 3133 |
} |
| 3134 |
|
| 3135 |
a.postprocessSack(state, result.cumTSNAckPointAdvanced) |
| 3136 |
|
| 3137 |
// RACK |
| 3138 |
a.onRackAfterSACK( |
| 3139 |
result.deliveredFound, |
| 3140 |
result.newestDeliveredSendTime, |
| 3141 |
result.newestDeliveredOrigTSN, |
| 3142 |
selectiveAckChunk, |
| 3143 |
) |
| 3144 |
|
| 3145 |
// adaptive burst mitigation |
| 3146 |
ackProgress := result.cumTSNAckPointAdvanced || result.deliveredFound |
| 3147 |
a.tlrMaybeFinishLocked(ackProgress) |
| 3148 |
|
| 3149 |
return nil |
| 3150 |
} |
| 3151 |
|
| 3152 |
// The caller must hold the lock. This method was only added because the |
| 3153 |
// linter was complaining about the "cognitive complexity" of handleSack. |
| 3154 |
func (a *Association) postprocessSack(state uint32, shouldAwakeWriteLoop bool) { |
| 3155 |
switch { |
| 3156 |
case a.inflightQueue.size() > 0: |
| 3157 |
// Start timer. (noop if already started) |
| 3158 |
a.log.Tracef("[%s] T3-rtx timer start (pt3)", a.name) |
| 3159 |
a.t3RTX.start(a.rtoMgr.getRTO()) |
| 3160 |
case a.pendingQueue.size() > 0: |
| 3161 |
// The SACK opened room for DATA accepted before shutdown started. |
| 3162 |
shouldAwakeWriteLoop = true |
| 3163 |
default: |
| 3164 |
// No more queued or outstanding DATA; advance shutdown if needed. |
| 3165 |
if a.advanceShutdownAfterDataDrain(state) { |
| 3166 |
shouldAwakeWriteLoop = true |
| 3167 |
} |
| 3168 |
} |
| 3169 |
|
| 3170 |
if shouldAwakeWriteLoop { |
| 3171 |
a.awakeWriteLoop() |
| 3172 |
} |
| 3173 |
} |
| 3174 |
|
| 3175 |
// The caller should hold the lock. |
| 3176 |
func (a *Association) advanceShutdownAfterDataDrain(state uint32) bool { |
| 3177 |
if a.hasPendingOrInflightData() { |
| 3178 |
return false |
| 3179 |
} |
| 3180 |
|
| 3181 |
switch state { |
| 3182 |
case shutdownPending: |
| 3183 |
a.willSendShutdown = true |
| 3184 |
a.setState(shutdownSent) |
| 3185 |
case shutdownReceived: |
| 3186 |
a.willSendShutdownAck = true |
| 3187 |
a.setState(shutdownAckSent) |
| 3188 |
default: |
| 3189 |
return false |
| 3190 |
} |
| 3191 |
|
| 3192 |
return true |
| 3193 |
} |
| 3194 |
|
| 3195 |
// The caller should hold the lock. |
| 3196 |
func (a *Association) hasPendingOrInflightData() bool { |
| 3197 |
return a.pendingQueue.size() > 0 || a.inflightQueue.size() > 0 |
| 3198 |
} |
| 3199 |
|
| 3200 |
// processShutdownAcknowledgement processes the Cumulative TSN Ack carried by |
| 3201 |
// a SHUTDOWN without applying SACK-only fields such as a_rwnd. |
| 3202 |
// The caller should hold the lock. |
| 3203 |
func (a *Association) processShutdownAcknowledgement(c *chunkShutdown) error { |
| 3204 |
// RFC 9260 Section 9.2 permits SHUTDOWN to cumulatively acknowledge |
| 3205 |
// contiguous DATA without a separate SACK. |
| 3206 |
ack := &chunkSelectiveAck{cumulativeTSNAck: c.cumulativeTSNAck} |
| 3207 |
result, err := a.processAcknowledgement(ack) |
| 3208 |
if err != nil { |
| 3209 |
return err |
| 3210 |
} |
| 3211 |
if result.processed { |
| 3212 |
if err = a.finishAcknowledgement(ack, result); err != nil { |
| 3213 |
return err |
| 3214 |
} |
| 3215 |
|
| 3216 |
a.onRackAfterSACK( |
| 3217 |
result.deliveredFound, |
| 3218 |
result.newestDeliveredSendTime, |
| 3219 |
result.newestDeliveredOrigTSN, |
| 3220 |
ack, |
| 3221 |
) |
| 3222 |
a.tlrMaybeFinishLocked(result.cumTSNAckPointAdvanced || result.deliveredFound) |
| 3223 |
} |
| 3224 |
|
| 3225 |
return nil |
| 3226 |
} |
| 3227 |
|
| 3228 |
func isShutdownHandleState(state uint32) bool { |
| 3229 |
switch state { |
| 3230 |
case established, shutdownPending, shutdownReceived, shutdownSent: |
| 3231 |
return true |
| 3232 |
default: |
| 3233 |
return false |
| 3234 |
} |
| 3235 |
} |
| 3236 |
|
| 3237 |
func entersShutdownReceived(state uint32) bool { |
| 3238 |
return state == established || state == shutdownPending |
| 3239 |
} |
| 3240 |
|
| 3241 |
// The caller should hold the lock. |
| 3242 |
func (a *Association) finishShutdownHandling(state uint32) { |
| 3243 |
switch state { |
| 3244 |
case established, shutdownPending, shutdownReceived: |
| 3245 |
if a.hasPendingOrInflightData() { |
| 3246 |
a.setState(shutdownReceived) |
| 3247 |
if a.pendingQueue.size() > 0 { |
| 3248 |
a.awakeWriteLoop() |
| 3249 |
} |
| 3250 |
} else { |
| 3251 |
// No more queued or outstanding DATA, send shutdown ack. |
| 3252 |
a.willSendShutdownAck = true |
| 3253 |
a.setState(shutdownAckSent) |
| 3254 |
|
| 3255 |
a.awakeWriteLoop() |
| 3256 |
} |
| 3257 |
} |
| 3258 |
} |
| 3259 |
|
| 3260 |
// The caller should hold the lock. |
| 3261 |
func (a *Association) handleShutdown(shutdown *chunkShutdown) error { |
| 3262 |
if a.shutdownCompletePending { |
| 3263 |
return nil |
| 3264 |
} |
| 3265 |
|
| 3266 |
state := a.getState() |
| 3267 |
if state == shutdownAckSent { |
| 3268 |
// Continue responding to retransmitted SHUTDOWN chunks after reaching |
| 3269 |
// SHUTDOWN-RECEIVED, as required by RFC 9260 Section 9.2. |
| 3270 |
a.retransmitShutdownAck() |
| 3271 |
|
| 3272 |
return nil |
| 3273 |
} |
| 3274 |
|
| 3275 |
if state == shutdownSent { |
| 3276 |
// RFC 9260 Section 9.2 requires an immediate SHUTDOWN ACK for a |
| 3277 |
// crossed shutdown. Since SHUTDOWN-SENT is entered only after all |
| 3278 |
// outbound DATA has been acknowledged, the peer's cumulative TSN ACK |
| 3279 |
// cannot release any additional DATA and must not delay the response. |
| 3280 |
a.t2Shutdown.stop() |
| 3281 |
a.willSendShutdown = false |
| 3282 |
a.willSendShutdownAck = true |
| 3283 |
a.setState(shutdownAckSent) |
| 3284 |
|
| 3285 |
a.awakeWriteLoop() |
| 3286 |
|
| 3287 |
return nil |
| 3288 |
} |
| 3289 |
|
| 3290 |
if !isShutdownHandleState(state) { |
| 3291 |
return nil |
| 3292 |
} |
| 3293 |
|
| 3294 |
if entersShutdownReceived(state) { |
| 3295 |
// Reject new user DATA before acknowledgement processing can release |
| 3296 |
// a.lock and invoke a stream's OnBufferedAmountLow callback. |
| 3297 |
a.setState(shutdownReceived) |
| 3298 |
} |
| 3299 |
|
| 3300 |
previousCumulativeTSNAckPoint := a.cumulativeTSNAckPoint |
| 3301 |
if err := a.processShutdownAcknowledgement(shutdown); err != nil { |
| 3302 |
// Invalid acknowledgement fields are rejected before the transmit |
| 3303 |
// acknowledgement point advances. Restore the pre-SHUTDOWN state so a |
| 3304 |
// malformed chunk cannot strand the association in SHUTDOWN-RECEIVED. |
| 3305 |
if a.cumulativeTSNAckPoint == previousCumulativeTSNAckPoint { |
| 3306 |
a.setState(state) |
| 3307 |
} |
| 3308 |
|
| 3309 |
return err |
| 3310 |
} |
| 3311 |
|
| 3312 |
if entersShutdownReceived(state) { |
| 3313 |
a.unblockPendingWrites() |
| 3314 |
} |
| 3315 |
a.finishShutdownHandling(state) |
| 3316 |
|
| 3317 |
return nil |
| 3318 |
} |
| 3319 |
|
| 3320 |
// The caller should hold the lock. |
| 3321 |
func (a *Association) handleShutdownAck(_ *chunkShutdownAck) { |
| 3322 |
state := a.getState() |
| 3323 |
if state == shutdownSent || state == shutdownAckSent { |
| 3324 |
a.t2Shutdown.stop() |
| 3325 |
a.willSendShutdown = false |
| 3326 |
a.willSendShutdownAck = false |
| 3327 |
a.shutdownCompletePending = true |
| 3328 |
a.willSendShutdownComplete = true |
| 3329 |
|
| 3330 |
a.awakeWriteLoop() |
| 3331 |
} |
| 3332 |
} |
| 3333 |
|
| 3334 |
func (a *Association) handleShutdownComplete(_ *chunkShutdownComplete) error { |
| 3335 |
state := a.getState() |
| 3336 |
if state == shutdownAckSent { |
| 3337 |
a.t2Shutdown.stop() |
| 3338 |
|
| 3339 |
return a.close() |
| 3340 |
} |
| 3341 |
|
| 3342 |
return nil |
| 3343 |
} |
| 3344 |
|
| 3345 |
func (a *Association) handleAbort(c *chunkAbort) error { |
| 3346 |
var errStr strings.Builder |
| 3347 |
for _, e := range c.errorCauses { |
| 3348 |
fmt.Fprintf(&errStr, "(%s)", e) |
| 3349 |
} |
| 3350 |
|
| 3351 |
_ = a.close() |
| 3352 |
|
| 3353 |
return fmt.Errorf("[%s] %w: %s", a.name, ErrChunk, errStr.String()) |
| 3354 |
} |
| 3355 |
|
| 3356 |
// createForwardTSN generates ForwardTSN chunk. |
| 3357 |
// This method will be be called if useForwardTSN is set to false. |
| 3358 |
// The caller should hold the lock. |
| 3359 |
func (a *Association) createForwardTSN() *chunkForwardTSN { |
| 3360 |
// RFC 3758 Sec 3.5 C4 |
| 3361 |
streamMap := map[uint16]uint16{} // to report only once per SI |
| 3362 |
for i := a.cumulativeTSNAckPoint + 1; sna32LTE(i, a.advancedPeerTSNAckPoint); i++ { |
| 3363 |
c, ok := a.inflightQueue.get(i) |
| 3364 |
if !ok { |
| 3365 |
break |
| 3366 |
} |
| 3367 |
|
| 3368 |
ssn, ok := streamMap[c.streamIdentifier] |
| 3369 |
if !ok { |
| 3370 |
streamMap[c.streamIdentifier] = c.streamSequenceNumber |
| 3371 |
} else if sna16LT(ssn, c.streamSequenceNumber) { |
| 3372 |
// to report only once with greatest SSN |
| 3373 |
streamMap[c.streamIdentifier] = c.streamSequenceNumber |
| 3374 |
} |
| 3375 |
} |
| 3376 |
|
| 3377 |
fwdtsn := &chunkForwardTSN{ |
| 3378 |
newCumulativeTSN: a.advancedPeerTSNAckPoint, |
| 3379 |
streams: []chunkForwardTSNStream{}, |
| 3380 |
} |
| 3381 |
|
| 3382 |
var streamStr strings.Builder |
| 3383 |
for si, ssn := range streamMap { |
| 3384 |
fmt.Fprintf(&streamStr, "(si=%d ssn=%d)", si, ssn) |
| 3385 |
fwdtsn.streams = append(fwdtsn.streams, chunkForwardTSNStream{ |
| 3386 |
identifier: si, |
| 3387 |
sequence: ssn, |
| 3388 |
}) |
| 3389 |
} |
| 3390 |
a.log.Tracef( |
| 3391 |
"[%s] building fwdtsn: newCumulativeTSN=%d cumTSN=%d - %s", |
| 3392 |
a.name, fwdtsn.newCumulativeTSN, a.cumulativeTSNAckPoint, streamStr.String(), |
| 3393 |
) |
| 3394 |
|
| 3395 |
return fwdtsn |
| 3396 |
} |
| 3397 |
|
| 3398 |
// createIForwardTSN generates I-FORWARD-TSN chunk. |
| 3399 |
// The caller should hold the lock. |
| 3400 |
func (a *Association) createIForwardTSN() *chunkIForwardTSN { |
| 3401 |
ordered := map[uint16]uint32{} |
| 3402 |
unordered := map[uint16]uint32{} |
| 3403 |
for i := a.cumulativeTSNAckPoint + 1; sna32LTE(i, a.advancedPeerTSNAckPoint); i++ { |
| 3404 |
c, ok := a.inflightQueue.get(i) |
| 3405 |
if !ok { |
| 3406 |
break |
| 3407 |
} |
| 3408 |
if c.unordered { |
| 3409 |
mid, ok := unordered[c.streamIdentifier] |
| 3410 |
if !ok || sna32LT(mid, c.messageIdentifier) { |
| 3411 |
unordered[c.streamIdentifier] = c.messageIdentifier |
| 3412 |
} |
| 3413 |
} else { |
| 3414 |
mid, ok := ordered[c.streamIdentifier] |
| 3415 |
if !ok || sna32LT(mid, c.messageIdentifier) { |
| 3416 |
ordered[c.streamIdentifier] = c.messageIdentifier |
| 3417 |
} |
| 3418 |
} |
| 3419 |
} |
| 3420 |
|
| 3421 |
fwdtsn := &chunkIForwardTSN{ |
| 3422 |
newCumulativeTSN: a.advancedPeerTSNAckPoint, |
| 3423 |
streams: []chunkIForwardTSNStream{}, |
| 3424 |
} |
| 3425 |
|
| 3426 |
for si, mid := range ordered { |
| 3427 |
fwdtsn.streams = append(fwdtsn.streams, chunkIForwardTSNStream{ |
| 3428 |
identifier: si, |
| 3429 |
unordered: false, |
| 3430 |
messageIdentifier: mid, |
| 3431 |
}) |
| 3432 |
} |
| 3433 |
for si, mid := range unordered { |
| 3434 |
fwdtsn.streams = append(fwdtsn.streams, chunkIForwardTSNStream{ |
| 3435 |
identifier: si, |
| 3436 |
unordered: true, |
| 3437 |
messageIdentifier: mid, |
| 3438 |
}) |
| 3439 |
} |
| 3440 |
|
| 3441 |
return fwdtsn |
| 3442 |
} |
| 3443 |
|
| 3444 |
// createPacket wraps chunks in a packet. |
| 3445 |
// The caller should hold the read lock. |
| 3446 |
func (a *Association) createPacket(cs []chunk) *packet { |
| 3447 |
return &packet{ |
| 3448 |
verificationTag: a.peerVerificationTag, |
| 3449 |
sourcePort: a.sourcePort, |
| 3450 |
destinationPort: a.destinationPort, |
| 3451 |
chunks: cs, |
| 3452 |
} |
| 3453 |
} |
| 3454 |
|
| 3455 |
// The caller should hold the lock. |
| 3456 |
func (a *Association) handleReconfig(reconfigChunk *chunkReconfig) ([]*packet, error) { |
| 3457 |
a.log.Tracef("[%s] handleReconfig", a.name) |
| 3458 |
|
| 3459 |
pp := make([]*packet, 0) |
| 3460 |
|
| 3461 |
pkt, err := a.handleReconfigParam(reconfigChunk.paramA) |
| 3462 |
if err != nil { |
| 3463 |
return nil, err |
| 3464 |
} |
| 3465 |
if pkt != nil { |
| 3466 |
pp = append(pp, pkt) |
| 3467 |
} |
| 3468 |
|
| 3469 |
if reconfigChunk.paramB != nil { |
| 3470 |
pkt, err = a.handleReconfigParam(reconfigChunk.paramB) |
| 3471 |
if err != nil { |
| 3472 |
return nil, err |
| 3473 |
} |
| 3474 |
if pkt != nil { |
| 3475 |
pp = append(pp, pkt) |
| 3476 |
} |
| 3477 |
} |
| 3478 |
|
| 3479 |
return pp, nil |
| 3480 |
} |
| 3481 |
|
| 3482 |
// The caller should hold the lock. |
| 3483 |
func (a *Association) handleForwardTSN(chunkTSN *chunkForwardTSN) []*packet { |
| 3484 |
a.log.Tracef("[%s] FwdTSN: %s", a.name, chunkTSN.String()) |
| 3485 |
|
| 3486 |
if a.useInterleaving { |
| 3487 |
a.abortProtocolViolation("received FORWARD-TSN with interleaving enabled") |
| 3488 |
|
| 3489 |
return nil |
| 3490 |
} |
| 3491 |
|
| 3492 |
if !a.useForwardTSN { |
| 3493 |
a.log.Warn("[%s] received FwdTSN but not enabled") |
| 3494 |
// Return an error chunk |
| 3495 |
cerr := &chunkError{ |
| 3496 |
errorCauses: []errorCause{&errorCauseUnrecognizedChunkType{}}, |
| 3497 |
} |
| 3498 |
outbound := &packet{} |
| 3499 |
outbound.verificationTag = a.peerVerificationTag |
| 3500 |
outbound.sourcePort = a.sourcePort |
| 3501 |
outbound.destinationPort = a.destinationPort |
| 3502 |
outbound.chunks = []chunk{cerr} |
| 3503 |
|
| 3504 |
return []*packet{outbound} |
| 3505 |
} |
| 3506 |
|
| 3507 |
// From RFC 3758 Sec 3.6: |
| 3508 |
// Note, if the "New Cumulative TSN" value carried in the arrived |
| 3509 |
// FORWARD TSN chunk is found to be behind or at the current cumulative |
| 3510 |
// TSN point, the data receiver MUST treat this FORWARD TSN as out-of- |
| 3511 |
// date and MUST NOT update its Cumulative TSN. The receiver SHOULD |
| 3512 |
// send a SACK to its peer (the sender of the FORWARD TSN) since such a |
| 3513 |
// duplicate may indicate the previous SACK was lost in the network. |
| 3514 |
|
| 3515 |
a.log.Tracef("[%s] should send ack? newCumTSN=%d peerLastTSN=%d", |
| 3516 |
a.name, chunkTSN.newCumulativeTSN, a.peerLastTSN()) |
| 3517 |
if sna32LTE(chunkTSN.newCumulativeTSN, a.peerLastTSN()) { |
| 3518 |
a.log.Tracef("[%s] sending ack on Forward TSN", a.name) |
| 3519 |
a.ackState = ackStateImmediate |
| 3520 |
a.ackTimer.stop() |
| 3521 |
a.awakeWriteLoop() |
| 3522 |
|
| 3523 |
return nil |
| 3524 |
} |
| 3525 |
|
| 3526 |
// From RFC 3758 Sec 3.6: |
| 3527 |
// the receiver MUST perform the same TSN handling, including duplicate |
| 3528 |
// detection, gap detection, SACK generation, cumulative TSN |
| 3529 |
// advancement, etc. as defined in RFC 2960 [2]---with the following |
| 3530 |
// exceptions and additions. |
| 3531 |
|
| 3532 |
// When a FORWARD TSN chunk arrives, the data receiver MUST first update |
| 3533 |
// its cumulative TSN point to the value carried in the FORWARD TSN |
| 3534 |
// chunk, |
| 3535 |
|
| 3536 |
a.payloadQueue.advanceCumulativeTSN(chunkTSN.newCumulativeTSN) |
| 3537 |
|
| 3538 |
// Report new peerLastTSN value and abandoned largest SSN value to |
| 3539 |
// corresponding streams so that the abandoned chunks can be removed |
| 3540 |
// from the reassemblyQueue. |
| 3541 |
for _, forwarded := range chunkTSN.streams { |
| 3542 |
if s, ok := a.streams[forwarded.identifier]; ok { |
| 3543 |
s.handleForwardTSNForOrdered(forwarded.sequence) |
| 3544 |
} |
| 3545 |
} |
| 3546 |
|
| 3547 |
// TSN may be forewared for unordered chunks. ForwardTSN chunk does not |
| 3548 |
// report which stream identifier it skipped for unordered chunks. |
| 3549 |
// Therefore, we need to broadcast this event to all existing streams for |
| 3550 |
// unordered chunks. |
| 3551 |
// See https://github.com/pion/sctp/issues/106 |
| 3552 |
for _, s := range a.streams { |
| 3553 |
s.handleForwardTSNForUnordered(chunkTSN.newCumulativeTSN) |
| 3554 |
} |
| 3555 |
|
| 3556 |
return a.handlePeerLastTSNAndAcknowledgement(false) |
| 3557 |
} |
| 3558 |
|
| 3559 |
// The caller should hold the lock. |
| 3560 |
func (a *Association) handleIForwardTSN(chunkTSN *chunkIForwardTSN) []*packet { |
| 3561 |
a.log.Tracef("[%s] I-FwdTSN: %s", a.name, chunkTSN.String()) |
| 3562 |
|
| 3563 |
if !a.useIForwardTSN { |
| 3564 |
a.abortProtocolViolation("received I-FORWARD-TSN without support") |
| 3565 |
|
| 3566 |
return nil |
| 3567 |
} |
| 3568 |
|
| 3569 |
a.log.Tracef("[%s] should send ack? newCumTSN=%d peerLastTSN=%d", |
| 3570 |
a.name, chunkTSN.newCumulativeTSN, a.peerLastTSN()) |
| 3571 |
if sna32LTE(chunkTSN.newCumulativeTSN, a.peerLastTSN()) { |
| 3572 |
a.log.Tracef("[%s] sending ack on I-Forward TSN", a.name) |
| 3573 |
a.ackState = ackStateImmediate |
| 3574 |
a.ackTimer.stop() |
| 3575 |
a.awakeWriteLoop() |
| 3576 |
|
| 3577 |
return nil |
| 3578 |
} |
| 3579 |
|
| 3580 |
a.payloadQueue.advanceCumulativeTSN(chunkTSN.newCumulativeTSN) |
| 3581 |
|
| 3582 |
for _, forwarded := range chunkTSN.streams { |
| 3583 |
if s, ok := a.streams[forwarded.identifier]; ok { |
| 3584 |
if forwarded.unordered { |
| 3585 |
s.handleForwardTSNForUnorderedMID(forwarded.messageIdentifier) |
| 3586 |
} else { |
| 3587 |
s.handleForwardTSNForOrderedMID(forwarded.messageIdentifier) |
| 3588 |
} |
| 3589 |
} |
| 3590 |
} |
| 3591 |
|
| 3592 |
return a.handlePeerLastTSNAndAcknowledgement(false) |
| 3593 |
} |
| 3594 |
|
| 3595 |
func (a *Association) sendResetRequest(streamIdentifier uint16) error { |
| 3596 |
a.lock.Lock() |
| 3597 |
defer a.lock.Unlock() |
| 3598 |
|
| 3599 |
state := a.getState() |
| 3600 |
if state != established { |
| 3601 |
return fmt.Errorf("%w: state=%s", ErrResetPacketInStateNotExist, |
| 3602 |
getAssociationStateString(state)) |
| 3603 |
} |
| 3604 |
|
| 3605 |
// Create DATA chunk which only contains valid stream identifier with |
| 3606 |
// nil userData and use it as a EOS from the stream. |
| 3607 |
c := &chunkPayloadData{ |
| 3608 |
streamIdentifier: streamIdentifier, |
| 3609 |
beginningFragment: true, |
| 3610 |
endingFragment: true, |
| 3611 |
userData: nil, |
| 3612 |
} |
| 3613 |
|
| 3614 |
a.pendingQueue.push(c) |
| 3615 |
a.awakeWriteLoop() |
| 3616 |
|
| 3617 |
return nil |
| 3618 |
} |
| 3619 |
|
| 3620 |
// The caller should hold the lock. |
| 3621 |
// |
| 3622 |
//nolint:cyclop |
| 3623 |
func (a *Association) handleReconfigParam(raw param) (*packet, error) { |
| 3624 |
switch par := raw.(type) { |
| 3625 |
case *paramOutgoingResetRequest: |
| 3626 |
a.log.Tracef("[%s] handleReconfigParam (OutgoingResetRequest)", a.name) |
| 3627 |
if a.peerLastTSN() < par.senderLastTSN && len(a.reconfigRequests) >= maxReconfigRequests { |
| 3628 |
// We have too many reconfig requests outstanding. Drop the request and let |
| 3629 |
// the peer retransmit. A well behaved peer should only have 1 outstanding |
| 3630 |
// reconfig request. |
| 3631 |
// |
| 3632 |
// RFC 6525: https://www.rfc-editor.org/rfc/rfc6525.html#section-5.1.1 |
| 3633 |
// At any given time, there MUST NOT be more than one request in flight. |
| 3634 |
// So, if the Re-configuration Timer is running and the RE-CONFIG chunk |
| 3635 |
// contains at least one request parameter, the chunk MUST be buffered. |
| 3636 |
// chrome: |
| 3637 |
// https://chromium.googlesource.com/external/webrtc/+/refs/heads/main/net/dcsctp/socket/stream_reset_handler.cc#271 |
| 3638 |
return nil, fmt.Errorf("%w: %d", ErrTooManyReconfigRequests, len(a.reconfigRequests)) |
| 3639 |
} |
| 3640 |
a.reconfigRequests[par.reconfigRequestSequenceNumber] = par |
| 3641 |
resp := a.resetStreamsIfAny(par) |
| 3642 |
if resp != nil { |
| 3643 |
return resp, nil |
| 3644 |
} |
| 3645 |
|
| 3646 |
return nil, nil //nolint:nilnil |
| 3647 |
case *paramReconfigResponse: |
| 3648 |
a.log.Tracef("[%s] handleReconfigParam (ReconfigResponse)", a.name) |
| 3649 |
if par.result == reconfigResultInProgress { |
| 3650 |
// RFC 6525: https://www.rfc-editor.org/rfc/rfc6525.html#section-5.2.7 |
| 3651 |
// |
| 3652 |
// If the Result field indicates "In progress", the timer for the |
| 3653 |
// Re-configuration Request Sequence Number is started again. If |
| 3654 |
// the timer runs out, the RE-CONFIG chunk MUST be retransmitted |
| 3655 |
// but the corresponding error counters MUST NOT be incremented. |
| 3656 |
if _, ok := a.reconfigs[par.reconfigResponseSequenceNumber]; ok { |
| 3657 |
a.tReconfig.stop() |
| 3658 |
a.tReconfig.start(a.rtoMgr.getRTO()) |
| 3659 |
} |
| 3660 |
|
| 3661 |
return nil, nil //nolint:nilnil |
| 3662 |
} |
| 3663 |
if par.result == reconfigResultSuccessPerformed { |
| 3664 |
a.resetOutgoingStreamSequenceNumbers(par.reconfigResponseSequenceNumber) |
| 3665 |
} |
| 3666 |
delete(a.reconfigs, par.reconfigResponseSequenceNumber) |
| 3667 |
if len(a.reconfigs) == 0 { |
| 3668 |
a.tReconfig.stop() |
| 3669 |
} |
| 3670 |
|
| 3671 |
return nil, nil //nolint:nilnil |
| 3672 |
default: |
| 3673 |
return nil, fmt.Errorf("%w: %t", ErrParamterType, par) |
| 3674 |
} |
| 3675 |
} |
| 3676 |
|
| 3677 |
// The caller should hold the lock. |
| 3678 |
func (a *Association) resetOutgoingStreamSequenceNumbers(reconfigRequestSequenceNumber uint32) { |
| 3679 |
reconfig := a.reconfigs[reconfigRequestSequenceNumber] |
| 3680 |
if reconfig == nil { |
| 3681 |
return |
| 3682 |
} |
| 3683 |
resetRequest, ok := reconfig.paramA.(*paramOutgoingResetRequest) |
| 3684 |
if !ok { |
| 3685 |
return |
| 3686 |
} |
| 3687 |
for _, id := range resetRequest.streamIdentifiers { |
| 3688 |
if s, ok := a.streams[id]; ok { |
| 3689 |
s.resetOutgoingStreamSequenceNumbers() |
| 3690 |
} |
| 3691 |
} |
| 3692 |
} |
| 3693 |
|
| 3694 |
// The caller should hold the lock. |
| 3695 |
func (a *Association) resetStreamsIfAny(resetRequest *paramOutgoingResetRequest) *packet { |
| 3696 |
result := reconfigResultSuccessPerformed |
| 3697 |
if sna32LTE(resetRequest.senderLastTSN, a.peerLastTSN()) { |
| 3698 |
a.log.Debugf("[%s] resetStream(): senderLastTSN=%d <= peerLastTSN=%d", |
| 3699 |
a.name, resetRequest.senderLastTSN, a.peerLastTSN()) |
| 3700 |
for _, id := range resetRequest.streamIdentifiers { |
| 3701 |
s, ok := a.streams[id] |
| 3702 |
if !ok { |
| 3703 |
continue |
| 3704 |
} |
| 3705 |
a.lock.Unlock() |
| 3706 |
s.onInboundStreamReset() |
| 3707 |
a.lock.Lock() |
| 3708 |
a.log.Debugf("[%s] deleting stream %d", a.name, id) |
| 3709 |
delete(a.streams, s.streamIdentifier) |
| 3710 |
} |
| 3711 |
delete(a.reconfigRequests, resetRequest.reconfigRequestSequenceNumber) |
| 3712 |
} else { |
| 3713 |
a.log.Debugf("[%s] resetStream(): senderLastTSN=%d > peerLastTSN=%d", |
| 3714 |
a.name, resetRequest.senderLastTSN, a.peerLastTSN()) |
| 3715 |
result = reconfigResultInProgress |
| 3716 |
} |
| 3717 |
|
| 3718 |
return a.createPacket([]chunk{&chunkReconfig{ |
| 3719 |
paramA: ¶mReconfigResponse{ |
| 3720 |
reconfigResponseSequenceNumber: resetRequest.reconfigRequestSequenceNumber, |
| 3721 |
result: result, |
| 3722 |
}, |
| 3723 |
}}) |
| 3724 |
} |
| 3725 |
|
| 3726 |
// Move the chunk peeked with a.pendingQueue.peek() to the inflightQueue. |
| 3727 |
// The caller should hold the lock. |
| 3728 |
func (a *Association) movePendingDataChunkToInflightQueue(chunkPayload *chunkPayloadData) { |
| 3729 |
if err := a.pendingQueue.pop(chunkPayload); err != nil { |
| 3730 |
a.log.Errorf("[%s] failed to pop from pending queue: %s", a.name, err.Error()) |
| 3731 |
} |
| 3732 |
|
| 3733 |
if chunkPayload.endingFragment { |
| 3734 |
chunkPayload.setAllInflight() |
| 3735 |
} |
| 3736 |
|
| 3737 |
// Assign TSN and original send time |
| 3738 |
chunkPayload.tsn = a.generateNextTSN() |
| 3739 |
chunkPayload.since = time.Now() |
| 3740 |
chunkPayload.nSent = 1 |
| 3741 |
|
| 3742 |
a.checkPartialReliabilityStatus(chunkPayload) |
| 3743 |
|
| 3744 |
a.log.Tracef( |
| 3745 |
"[%s] sending ppi=%d tsn=%d ssn=%d sent=%d len=%d (%v,%v)", |
| 3746 |
a.name, |
| 3747 |
chunkPayload.payloadType, |
| 3748 |
chunkPayload.tsn, |
| 3749 |
chunkPayload.streamSequenceNumber, |
| 3750 |
chunkPayload.nSent, |
| 3751 |
len(chunkPayload.userData), |
| 3752 |
chunkPayload.beginningFragment, |
| 3753 |
chunkPayload.endingFragment, |
| 3754 |
) |
| 3755 |
|
| 3756 |
a.inflightQueue.pushNoCheck(chunkPayload) |
| 3757 |
|
| 3758 |
// RACK: track outstanding original transmissions by send time. |
| 3759 |
a.rackInsert(chunkPayload) |
| 3760 |
} |
| 3761 |
|
| 3762 |
// popPendingDataChunksToSend pops chunks from the pending queues as many as |
| 3763 |
// the cwnd and rwnd allows to send. |
| 3764 |
// The caller should hold the lock. |
| 3765 |
// |
| 3766 |
//nolint:cyclop |
| 3767 |
func (a *Association) popPendingDataChunksToSend( //nolint:cyclop,gocognit |
| 3768 |
budgetScaled *int64, |
| 3769 |
consumed *bool, |
| 3770 |
) ([]*chunkPayloadData, []uint16) { |
| 3771 |
chunks := []*chunkPayloadData{} |
| 3772 |
var sisToReset []uint16 // stream indentifiers to reset |
| 3773 |
|
| 3774 |
// track current packet size for MTU bundling so budgeting is accurate. |
| 3775 |
bytesInPacket := 0 |
| 3776 |
|
| 3777 |
if a.pendingQueue.size() > 0 { //nolint:nestif |
| 3778 |
// RFC 4960 sec 6.1. Transmission of DATA Chunks |
| 3779 |
// A) At any given time, the data sender MUST NOT transmit new data to |
| 3780 |
// any destination transport address if its peer's rwnd indicates |
| 3781 |
// that the peer has no buffer space (i.e., rwnd is 0; see Section |
| 3782 |
// 6.2.1). However, regardless of the value of rwnd (including if it |
| 3783 |
// is 0), the data sender can always have one DATA chunk in flight to |
| 3784 |
// the receiver if allowed by cwnd (see rule B, below). |
| 3785 |
|
| 3786 |
for { |
| 3787 |
chunkPayload := a.pendingQueue.peek() |
| 3788 |
if chunkPayload == nil { |
| 3789 |
break // no more pending data |
| 3790 |
} |
| 3791 |
|
| 3792 |
dataLen := uint32(len(chunkPayload.userData)) //nolint:gosec // G115 |
| 3793 |
if dataLen == 0 { |
| 3794 |
sisToReset = append(sisToReset, chunkPayload.streamIdentifier) |
| 3795 |
err := a.pendingQueue.pop(chunkPayload) |
| 3796 |
if err != nil { |
| 3797 |
a.log.Errorf("failed to pop from pending queue: %s", err.Error()) |
| 3798 |
} |
| 3799 |
|
| 3800 |
continue |
| 3801 |
} |
| 3802 |
|
| 3803 |
if uint32(a.inflightQueue.getNumBytes())+dataLen > a.CWND() { //nolint:gosec // G115 |
| 3804 |
break // would exceeds cwnd |
| 3805 |
} |
| 3806 |
|
| 3807 |
if dataLen > a.RWND() { |
| 3808 |
break // no more rwnd |
| 3809 |
} |
| 3810 |
|
| 3811 |
chunkBytes := chunkPayload.chunkSizeInPacket() |
| 3812 |
|
| 3813 |
// ensure MTU bundling matches bundleDataChunksIntoPackets(). |
| 3814 |
addBytes := chunkBytes |
| 3815 |
if bytesInPacket == 0 { |
| 3816 |
addBytes += int(commonHeaderSize) |
| 3817 |
if addBytes > int(a.MTU()) { |
| 3818 |
break |
| 3819 |
} |
| 3820 |
|
| 3821 |
// reserve budget for common header + first chunk. |
| 3822 |
if !a.tlrAllowSendLocked(budgetScaled, consumed, addBytes) { |
| 3823 |
break |
| 3824 |
} |
| 3825 |
|
| 3826 |
bytesInPacket = int(commonHeaderSize) |
| 3827 |
} else { |
| 3828 |
// if it doesn't fit, start a new packet and retry same chunk. |
| 3829 |
if bytesInPacket+chunkBytes > int(a.MTU()) { |
| 3830 |
bytesInPacket = 0 |
| 3831 |
|
| 3832 |
continue |
| 3833 |
} |
| 3834 |
|
| 3835 |
// reserve budget for the additional chunk bytes. |
| 3836 |
if !a.tlrAllowSendLocked(budgetScaled, consumed, chunkBytes) { |
| 3837 |
break |
| 3838 |
} |
| 3839 |
} |
| 3840 |
|
| 3841 |
a.setRWND(a.RWND() - dataLen) |
| 3842 |
|
| 3843 |
a.movePendingDataChunkToInflightQueue(chunkPayload) |
| 3844 |
chunks = append(chunks, chunkPayload) |
| 3845 |
bytesInPacket += chunkBytes |
| 3846 |
} |
| 3847 |
|
| 3848 |
// allow one DATA chunk if nothing is inflight to the receiver. |
| 3849 |
if len(chunks) == 0 && a.inflightQueue.size() == 0 { |
| 3850 |
// Send zero window probe |
| 3851 |
c := a.pendingQueue.peek() |
| 3852 |
if c != nil && len(c.userData) > 0 { |
| 3853 |
// probe is a new packet: common header + chunk bytes. |
| 3854 |
chunkBytes := c.chunkSizeInPacket() |
| 3855 |
addBytes := int(commonHeaderSize) + chunkBytes |
| 3856 |
|
| 3857 |
if addBytes <= int(a.MTU()) && a.tlrAllowSendLocked(budgetScaled, consumed, addBytes) { |
| 3858 |
a.movePendingDataChunkToInflightQueue(c) |
| 3859 |
chunks = append(chunks, c) |
| 3860 |
} |
| 3861 |
} |
| 3862 |
} |
| 3863 |
} |
| 3864 |
|
| 3865 |
if a.blockWrite && len(chunks) > 0 && a.pendingQueue.size() == 0 { |
| 3866 |
a.log.Tracef("[%s] all pending data have been sent, notify writable", a.name) |
| 3867 |
a.notifyBlockWritable() |
| 3868 |
} |
| 3869 |
|
| 3870 |
return chunks, sisToReset |
| 3871 |
} |
| 3872 |
|
| 3873 |
// bundleDataChunksIntoPackets packs DATA chunks into packets. It tries to bundle |
| 3874 |
// DATA chunks into a packet so long as the resulting packet size does not exceed |
| 3875 |
// the path MTU. |
| 3876 |
// The caller should hold the lock. |
| 3877 |
func (a *Association) bundleDataChunksIntoPackets(chunks []*chunkPayloadData) []*packet { |
| 3878 |
packets := []*packet{} |
| 3879 |
chunksToSend := []chunk{} |
| 3880 |
bytesInPacket := int(commonHeaderSize) |
| 3881 |
|
| 3882 |
for _, chunkPayload := range chunks { |
| 3883 |
// RFC 4960 sec 6.1. Transmission of DATA Chunks |
| 3884 |
// Multiple DATA chunks committed for transmission MAY be bundled in a |
| 3885 |
// single packet. Furthermore, DATA chunks being retransmitted MAY be |
| 3886 |
// bundled with new DATA chunks, as long as the resulting packet size |
| 3887 |
// does not exceed the path MTU. |
| 3888 |
chunkSizeInPacket := chunkPayload.chunkSizeInPacket() |
| 3889 |
if bytesInPacket+chunkSizeInPacket > int(a.MTU()) { |
| 3890 |
packets = append(packets, a.createPacket(chunksToSend)) |
| 3891 |
chunksToSend = []chunk{} |
| 3892 |
bytesInPacket = int(commonHeaderSize) |
| 3893 |
} |
| 3894 |
chunksToSend = append(chunksToSend, chunkPayload) |
| 3895 |
bytesInPacket += chunkSizeInPacket |
| 3896 |
} |
| 3897 |
|
| 3898 |
if len(chunksToSend) > 0 { |
| 3899 |
packets = append(packets, a.createPacket(chunksToSend)) |
| 3900 |
} |
| 3901 |
|
| 3902 |
return packets |
| 3903 |
} |
| 3904 |
|
| 3905 |
// sendPayloadData sends the data chunks. |
| 3906 |
func (a *Association) sendPayloadData(ctx context.Context, chunks []*chunkPayloadData) error { |
| 3907 |
a.lock.Lock() |
| 3908 |
|
| 3909 |
state := a.getState() |
| 3910 |
if state != established { |
| 3911 |
a.lock.Unlock() |
| 3912 |
|
| 3913 |
return fmt.Errorf("%w: state=%s", ErrPayloadDataStateNotExist, |
| 3914 |
getAssociationStateString(state)) |
| 3915 |
} |
| 3916 |
|
| 3917 |
if a.blockWrite { |
| 3918 |
for a.writePending { |
| 3919 |
writeNotify := a.writeNotify |
| 3920 |
a.lock.Unlock() |
| 3921 |
select { |
| 3922 |
case <-ctx.Done(): |
| 3923 |
return ctx.Err() |
| 3924 |
case <-writeNotify: |
| 3925 |
} |
| 3926 |
a.lock.Lock() |
| 3927 |
|
| 3928 |
state = a.getState() |
| 3929 |
if state != established { |
| 3930 |
a.lock.Unlock() |
| 3931 |
|
| 3932 |
return fmt.Errorf("%w: state=%s", ErrPayloadDataStateNotExist, |
| 3933 |
getAssociationStateString(state)) |
| 3934 |
} |
| 3935 |
} |
| 3936 |
a.writePending = true |
| 3937 |
} |
| 3938 |
|
| 3939 |
// Push the chunks into the pending queue first. |
| 3940 |
for _, c := range chunks { |
| 3941 |
a.pendingQueue.push(c) |
| 3942 |
} |
| 3943 |
|
| 3944 |
a.lock.Unlock() |
| 3945 |
a.awakeWriteLoop() |
| 3946 |
|
| 3947 |
return nil |
| 3948 |
} |
| 3949 |
|
| 3950 |
// The caller should hold the lock. |
| 3951 |
func (a *Association) checkPartialReliabilityStatus(chunkPayload *chunkPayloadData) { |
| 3952 |
if !a.partialReliabilityEnabled() { |
| 3953 |
return |
| 3954 |
} |
| 3955 |
|
| 3956 |
// draft-ietf-rtcweb-data-protocol-09.txt section 6 |
| 3957 |
// 6. Procedures |
| 3958 |
// All Data Channel Establishment Protocol messages MUST be sent using |
| 3959 |
// ordered delivery and reliable transmission. |
| 3960 |
// |
| 3961 |
if chunkPayload.payloadType == PayloadTypeWebRTCDCEP { |
| 3962 |
return |
| 3963 |
} |
| 3964 |
|
| 3965 |
// PR-SCTP |
| 3966 |
if stream, ok := a.streams[chunkPayload.streamIdentifier]; ok { //nolint:nestif |
| 3967 |
stream.lock.RLock() |
| 3968 |
if stream.reliabilityType == ReliabilityTypeRexmit { |
| 3969 |
if chunkPayload.nSent >= stream.reliabilityValue { |
| 3970 |
chunkPayload.setAbandoned(true) |
| 3971 |
a.rackRemove(chunkPayload) |
| 3972 |
a.log.Tracef( |
| 3973 |
"[%s] marked as abandoned: tsn=%d ppi=%d (remix: %d)", |
| 3974 |
a.name, chunkPayload.tsn, chunkPayload.payloadType, chunkPayload.nSent, |
| 3975 |
) |
| 3976 |
} |
| 3977 |
} else if stream.reliabilityType == ReliabilityTypeTimed { |
| 3978 |
elapsed := int64(time.Since(chunkPayload.since).Seconds() * 1000) |
| 3979 |
if elapsed >= int64(stream.reliabilityValue) { |
| 3980 |
chunkPayload.setAbandoned(true) |
| 3981 |
a.rackRemove(chunkPayload) |
| 3982 |
a.log.Tracef( |
| 3983 |
"[%s] marked as abandoned: tsn=%d ppi=%d (timed: %d)", |
| 3984 |
a.name, chunkPayload.tsn, chunkPayload.payloadType, elapsed, |
| 3985 |
) |
| 3986 |
} |
| 3987 |
} |
| 3988 |
stream.lock.RUnlock() |
| 3989 |
} else { |
| 3990 |
// Remote has reset its send side of the stream, we can still send data. |
| 3991 |
a.log.Tracef("[%s] stream %d not found, remote reset", a.name, chunkPayload.streamIdentifier) |
| 3992 |
} |
| 3993 |
} |
| 3994 |
|
| 3995 |
// getDataPacketsToRetransmit is called when T3-rtx is timed out and retransmit outstanding data chunks |
| 3996 |
// that are not acked or abandoned yet. |
| 3997 |
// The caller should hold the lock. |
| 3998 |
func (a *Association) getDataPacketsToRetransmit(budgetScaled *int64, consumed *bool) []*packet { //nolint:cyclop |
| 3999 |
awnd := min32(a.CWND(), a.RWND()) |
| 4000 |
chunks := []*chunkPayloadData{} |
| 4001 |
var bytesToSend int |
| 4002 |
currRtxTimestamp := time.Now() |
| 4003 |
|
| 4004 |
bytesInPacket := 0 |
| 4005 |
|
| 4006 |
for i := 0; ; i++ { |
| 4007 |
chunkPayload, ok := a.inflightQueue.get(a.cumulativeTSNAckPoint + uint32(i) + 1) //nolint:gosec // G115 |
| 4008 |
if !ok { |
| 4009 |
break // end of pending data |
| 4010 |
} |
| 4011 |
|
| 4012 |
if !chunkPayload.retransmit { |
| 4013 |
continue |
| 4014 |
} |
| 4015 |
|
| 4016 |
if i == 0 && int(a.RWND()) < len(chunkPayload.userData) { |
| 4017 |
// allow as zero window probe |
| 4018 |
} else if bytesToSend+len(chunkPayload.userData) > int(awnd) { |
| 4019 |
break |
| 4020 |
} |
| 4021 |
|
| 4022 |
chunkBytes := chunkPayload.chunkSizeInPacket() |
| 4023 |
|
| 4024 |
// retry as first chunk in a new packet if needed. |
| 4025 |
for { |
| 4026 |
addBytes := chunkBytes |
| 4027 |
if bytesInPacket == 0 { |
| 4028 |
addBytes += int(commonHeaderSize) |
| 4029 |
if addBytes > int(a.MTU()) { |
| 4030 |
return a.bundleDataChunksIntoPackets(chunks) |
| 4031 |
} |
| 4032 |
} else if bytesInPacket+chunkBytes > int(a.MTU()) { |
| 4033 |
bytesInPacket = 0 |
| 4034 |
|
| 4035 |
continue |
| 4036 |
} |
| 4037 |
|
| 4038 |
// burst budget gate before mutating the chunk. |
| 4039 |
if !a.tlrAllowSendLocked(budgetScaled, consumed, addBytes) { |
| 4040 |
return a.bundleDataChunksIntoPackets(chunks) |
| 4041 |
} |
| 4042 |
|
| 4043 |
if bytesInPacket == 0 { |
| 4044 |
bytesInPacket = int(commonHeaderSize) |
| 4045 |
} |
| 4046 |
bytesInPacket += chunkBytes |
| 4047 |
|
| 4048 |
break |
| 4049 |
} |
| 4050 |
|
| 4051 |
chunkPayload.retransmit = false |
| 4052 |
bytesToSend += len(chunkPayload.userData) |
| 4053 |
|
| 4054 |
// Update for retransmission |
| 4055 |
chunkPayload.nSent++ |
| 4056 |
chunkPayload.since = currRtxTimestamp |
| 4057 |
a.rackRemove(chunkPayload) |
| 4058 |
a.rackInsert(chunkPayload) |
| 4059 |
|
| 4060 |
a.checkPartialReliabilityStatus(chunkPayload) |
| 4061 |
|
| 4062 |
a.log.Tracef( |
| 4063 |
"[%s] retransmitting tsn=%d ssn=%d sent=%d", |
| 4064 |
a.name, chunkPayload.tsn, chunkPayload.streamSequenceNumber, chunkPayload.nSent, |
| 4065 |
) |
| 4066 |
|
| 4067 |
chunks = append(chunks, chunkPayload) |
| 4068 |
} |
| 4069 |
|
| 4070 |
return a.bundleDataChunksIntoPackets(chunks) |
| 4071 |
} |
| 4072 |
|
| 4073 |
// generateNextTSN returns the myNextTSN and increases it. The caller should hold the lock. |
| 4074 |
// The caller should hold the lock. |
| 4075 |
func (a *Association) generateNextTSN() uint32 { |
| 4076 |
tsn := a.myNextTSN |
| 4077 |
a.myNextTSN++ |
| 4078 |
|
| 4079 |
return tsn |
| 4080 |
} |
| 4081 |
|
| 4082 |
// generateNextRSN returns the myNextRSN and increases it. The caller should hold the lock. |
| 4083 |
// The caller should hold the lock. |
| 4084 |
func (a *Association) generateNextRSN() uint32 { |
| 4085 |
rsn := a.myNextRSN |
| 4086 |
a.myNextRSN++ |
| 4087 |
|
| 4088 |
return rsn |
| 4089 |
} |
| 4090 |
|
| 4091 |
func (a *Association) createSelectiveAckChunk() *chunkSelectiveAck { |
| 4092 |
sack := &chunkSelectiveAck{} |
| 4093 |
sack.cumulativeTSNAck = a.peerLastTSN() |
| 4094 |
sack.advertisedReceiverWindowCredit = a.getMyReceiverWindowCredit() |
| 4095 |
sack.duplicateTSN = a.payloadQueue.popDuplicates() |
| 4096 |
sack.gapAckBlocks = a.payloadQueue.getGapAckBlocks() |
| 4097 |
|
| 4098 |
return sack |
| 4099 |
} |
| 4100 |
|
| 4101 |
func pack(p *packet) []*packet { |
| 4102 |
return []*packet{p} |
| 4103 |
} |
| 4104 |
|
| 4105 |
func (a *Association) handleChunksStart() { |
| 4106 |
a.lock.Lock() |
| 4107 |
defer a.lock.Unlock() |
| 4108 |
|
| 4109 |
a.stats.incPacketsReceived() |
| 4110 |
|
| 4111 |
a.delayedAckTriggered = false |
| 4112 |
a.immediateAckTriggered = false |
| 4113 |
} |
| 4114 |
|
| 4115 |
func (a *Association) handleChunksEnd() { |
| 4116 |
a.lock.Lock() |
| 4117 |
defer a.lock.Unlock() |
| 4118 |
|
| 4119 |
if a.immediateAckTriggered { |
| 4120 |
a.ackState = ackStateImmediate |
| 4121 |
a.ackTimer.stop() |
| 4122 |
a.awakeWriteLoop() |
| 4123 |
} else if a.delayedAckTriggered { |
| 4124 |
// Will send delayed ack in the next ack timeout |
| 4125 |
a.ackState = ackStateDelay |
| 4126 |
a.ackTimer.start() |
| 4127 |
} |
| 4128 |
} |
| 4129 |
|
| 4130 |
func (a *Association) handleChunk(receivedPacket *packet, receivedChunk chunk) error { //nolint:cyclop |
| 4131 |
a.lock.Lock() |
| 4132 |
defer a.lock.Unlock() |
| 4133 |
|
| 4134 |
var packets []*packet |
| 4135 |
var err error |
| 4136 |
|
| 4137 |
var abort bool |
| 4138 |
if abort, err = receivedChunk.check(); err != nil { |
| 4139 |
a.log.Errorf("[%s] failed validating chunk: %s ", a.name, err) |
| 4140 |
if abort && shouldAbortOnChunkValidationError(receivedChunk) { |
| 4141 |
a.abortProtocolViolation(err.Error()) |
| 4142 |
} |
| 4143 |
|
| 4144 |
return nil |
| 4145 |
} |
| 4146 |
|
| 4147 |
isAbort := false |
| 4148 |
|
| 4149 |
switch receivedChunk := receivedChunk.(type) { |
| 4150 |
// Note: We do not do the following for chunkInit, chunkInitAck, and chunkCookieEcho: |
| 4151 |
// If an endpoint receives an INIT, INIT ACK, or COOKIE ECHO chunk but decides not to establish the |
| 4152 |
// new association due to missing mandatory parameters in the received INIT or INIT ACK chunk, invalid |
| 4153 |
// parameter values, or lack of local resources, it SHOULD respond with an ABORT chunk. |
| 4154 |
|
| 4155 |
case *chunkInit: |
| 4156 |
packets, err = a.handleInit(receivedPacket, receivedChunk) |
| 4157 |
|
| 4158 |
case *chunkInitAck: |
| 4159 |
err = a.handleInitAck(receivedPacket, receivedChunk) |
| 4160 |
|
| 4161 |
case *chunkAbort: |
| 4162 |
isAbort = true |
| 4163 |
err = a.handleAbort(receivedChunk) |
| 4164 |
|
| 4165 |
case *chunkError: |
| 4166 |
var errStr strings.Builder |
| 4167 |
for _, e := range receivedChunk.errorCauses { |
| 4168 |
fmt.Fprintf(&errStr, "(%s)", e) |
| 4169 |
} |
| 4170 |
a.log.Debugf("[%s] Error chunk, with following errors: %s", a.name, errStr.String()) |
| 4171 |
|
| 4172 |
case *chunkHeartbeat: |
| 4173 |
packets = a.handleHeartbeat(receivedChunk) |
| 4174 |
|
| 4175 |
case *chunkHeartbeatAck: |
| 4176 |
a.handleHeartbeatAck(receivedChunk) |
| 4177 |
|
| 4178 |
case *chunkCookieEcho: |
| 4179 |
packets = a.handleCookieEcho(receivedChunk) |
| 4180 |
|
| 4181 |
case *chunkCookieAck: |
| 4182 |
a.handleCookieAck() |
| 4183 |
|
| 4184 |
case *chunkPayloadData: |
| 4185 |
packets = a.handleData(receivedChunk) |
| 4186 |
|
| 4187 |
case *chunkSelectiveAck: |
| 4188 |
err = a.handleSack(receivedChunk) |
| 4189 |
|
| 4190 |
case *chunkReconfig: |
| 4191 |
packets, err = a.handleReconfig(receivedChunk) |
| 4192 |
|
| 4193 |
case *chunkForwardTSN: |
| 4194 |
packets = a.handleForwardTSN(receivedChunk) |
| 4195 |
case *chunkIForwardTSN: |
| 4196 |
packets = a.handleIForwardTSN(receivedChunk) |
| 4197 |
|
| 4198 |
case *chunkShutdown: |
| 4199 |
err = a.handleShutdown(receivedChunk) |
| 4200 |
case *chunkShutdownAck: |
| 4201 |
a.handleShutdownAck(receivedChunk) |
| 4202 |
case *chunkShutdownComplete: |
| 4203 |
err = a.handleShutdownComplete(receivedChunk) |
| 4204 |
|
| 4205 |
default: |
| 4206 |
err = ErrChunkTypeUnhandled |
| 4207 |
} |
| 4208 |
|
| 4209 |
// Log and return, the only condition that is fatal is a ABORT chunk |
| 4210 |
if err != nil { |
| 4211 |
if isAbort { |
| 4212 |
return err |
| 4213 |
} |
| 4214 |
|
| 4215 |
a.log.Errorf("Failed to handle chunk: %v", err) |
| 4216 |
|
| 4217 |
return nil |
| 4218 |
} |
| 4219 |
|
| 4220 |
if len(packets) > 0 { |
| 4221 |
a.controlQueue.pushAll(packets) |
| 4222 |
a.awakeWriteLoop() |
| 4223 |
} |
| 4224 |
|
| 4225 |
return nil |
| 4226 |
} |
| 4227 |
|
| 4228 |
func shouldAbortOnChunkValidationError(receivedChunk chunk) bool { |
| 4229 |
switch receivedChunk.(type) { |
| 4230 |
case *chunkInit, *chunkInitAck, *chunkCookieEcho: |
| 4231 |
return false |
| 4232 |
default: |
| 4233 |
return true |
| 4234 |
} |
| 4235 |
} |
| 4236 |
|
| 4237 |
// The caller should hold the lock. |
| 4238 |
func (a *Association) onShutdownTimeout(nRtos uint) { |
| 4239 |
a.log.Debugf("[%s] retransmission of shutdown timeout (nRtos=%d): %v", a.name, nRtos) |
| 4240 |
if a.shutdownCompletePending { |
| 4241 |
return |
| 4242 |
} |
| 4243 |
|
| 4244 |
switch a.getState() { |
| 4245 |
case shutdownSent: |
| 4246 |
a.willSendShutdown = true |
| 4247 |
a.awakeWriteLoop() |
| 4248 |
case shutdownAckSent: |
| 4249 |
a.willSendShutdownAck = true |
| 4250 |
a.awakeWriteLoop() |
| 4251 |
} |
| 4252 |
} |
| 4253 |
|
| 4254 |
func (a *Association) onRetransmissionTimeout(id int, nRtos uint) { //nolint:cyclop |
| 4255 |
a.lock.Lock() |
| 4256 |
defer a.lock.Unlock() |
| 4257 |
|
| 4258 |
if id == timerT1Init { |
| 4259 |
err := a.sendInit() |
| 4260 |
if err != nil { |
| 4261 |
a.log.Debugf("[%s] failed to retransmit init (nRtos=%d): %v", a.name, nRtos, err) |
| 4262 |
} |
| 4263 |
|
| 4264 |
return |
| 4265 |
} |
| 4266 |
|
| 4267 |
if id == timerT1Cookie { |
| 4268 |
err := a.sendCookieEcho() |
| 4269 |
if err != nil { |
| 4270 |
a.log.Debugf("[%s] failed to retransmit cookie-echo (nRtos=%d): %v", a.name, nRtos, err) |
| 4271 |
} |
| 4272 |
|
| 4273 |
return |
| 4274 |
} |
| 4275 |
|
| 4276 |
if id == timerT2Shutdown { |
| 4277 |
a.onShutdownTimeout(nRtos) |
| 4278 |
|
| 4279 |
return |
| 4280 |
} |
| 4281 |
|
| 4282 |
if id == timerT3RTX { //nolint:nestif |
| 4283 |
a.stats.incT3Timeouts() |
| 4284 |
|
| 4285 |
// RFC 4960 sec 6.3.3 |
| 4286 |
// E1) For the destination address for which the timer expires, adjust |
| 4287 |
// its ssthresh with rules defined in Section 7.2.3 and set the |
| 4288 |
// cwnd <- MTU. |
| 4289 |
// RFC 4960 sec 7.2.3 |
| 4290 |
// When the T3-rtx timer expires on an address, SCTP should perform slow |
| 4291 |
// start by: |
| 4292 |
// ssthresh = max(cwnd/2, 4*MTU) |
| 4293 |
// cwnd = 1*MTU |
| 4294 |
|
| 4295 |
a.ssthresh = max32(a.CWND()/2, 4*a.MTU()) |
| 4296 |
a.setCWND(a.MTU()) |
| 4297 |
a.log.Tracef("[%s] updated cwnd=%d ssthresh=%d inflight=%d (RTO)", |
| 4298 |
a.name, a.CWND(), a.ssthresh, a.inflightQueue.getNumBytes()) |
| 4299 |
// If not in Fast Recovery, enter Fast Recovery and mark the highest outstanding TSN as the Fast Recovery exit point. |
| 4300 |
// When a SACK acknowledges all TSNs up to and including this exit point, Fast Recovery is exited. |
| 4301 |
// https://www.rfc-editor.org/rfc/rfc4960#section-7.2.4 |
| 4302 |
// https://www.rfc-editor.org/rfc/rfc9260.html#section-7.2.4 |
| 4303 |
if a.inFastRecovery { |
| 4304 |
a.inFastRecovery = false |
| 4305 |
a.willRetransmitFast = false |
| 4306 |
a.fastRecoverExitPoint = 0 |
| 4307 |
a.partialBytesAcked = 0 |
| 4308 |
a.log.Debugf("[%s] exit fast-recovery (RTO)", a.name) |
| 4309 |
} |
| 4310 |
|
| 4311 |
// RFC 3758 sec 3.5 |
| 4312 |
// A5) Any time the T3-rtx timer expires, on any destination, the sender |
| 4313 |
// SHOULD try to advance the "Advanced.Peer.Ack.Point" by following |
| 4314 |
// the procedures outlined in C2 - C5. |
| 4315 |
if a.partialReliabilityEnabled() { |
| 4316 |
// RFC 3758 Sec 3.5 C2 |
| 4317 |
for i := a.advancedPeerTSNAckPoint + 1; ; i++ { |
| 4318 |
c, ok := a.inflightQueue.get(i) |
| 4319 |
if !ok { |
| 4320 |
break |
| 4321 |
} |
| 4322 |
if !c.abandoned() { |
| 4323 |
break |
| 4324 |
} |
| 4325 |
a.advancedPeerTSNAckPoint = i |
| 4326 |
} |
| 4327 |
|
| 4328 |
// RFC 3758 Sec 3.5 C3 |
| 4329 |
if sna32GT(a.advancedPeerTSNAckPoint, a.cumulativeTSNAckPoint) { |
| 4330 |
a.willSendForwardTSN = true |
| 4331 |
} |
| 4332 |
} |
| 4333 |
|
| 4334 |
a.log.Debugf("[%s] T3-rtx timed out: nRtos=%d cwnd=%d ssthresh=%d", a.name, nRtos, a.CWND(), a.ssthresh) |
| 4335 |
|
| 4336 |
/* |
| 4337 |
a.log.Debugf(" - advancedPeerTSNAckPoint=%d", a.advancedPeerTSNAckPoint) |
| 4338 |
a.log.Debugf(" - cumulativeTSNAckPoint=%d", a.cumulativeTSNAckPoint) |
| 4339 |
a.inflightQueue.updateSortedKeys() |
| 4340 |
for i, tsn := range a.inflightQueue.sorted { |
| 4341 |
if c, ok := a.inflightQueue.get(tsn); ok { |
| 4342 |
a.log.Debugf(" - [%d] tsn=%d acked=%v abandoned=%v (%v,%v) len=%d", |
| 4343 |
i, c.tsn, c.acked, c.abandoned(), c.beginningFragment, c.endingFragment, len(c.userData)) |
| 4344 |
} |
| 4345 |
} |
| 4346 |
*/ |
| 4347 |
|
| 4348 |
a.inflightQueue.markAllToRetrasmit() |
| 4349 |
a.awakeWriteLoop() |
| 4350 |
|
| 4351 |
return |
| 4352 |
} |
| 4353 |
|
| 4354 |
if id == timerReconfig { |
| 4355 |
a.willRetransmitReconfig = true |
| 4356 |
a.awakeWriteLoop() |
| 4357 |
} |
| 4358 |
} |
| 4359 |
|
| 4360 |
func (a *Association) onRetransmissionFailure(id int) { |
| 4361 |
a.lock.Lock() |
| 4362 |
defer a.lock.Unlock() |
| 4363 |
|
| 4364 |
if id == timerT1Init { |
| 4365 |
a.log.Errorf("[%s] retransmission failure: T1-init", a.name) |
| 4366 |
a.completeHandshake(ErrHandshakeInitAck) |
| 4367 |
|
| 4368 |
return |
| 4369 |
} |
| 4370 |
|
| 4371 |
if id == timerT1Cookie { |
| 4372 |
a.log.Errorf("[%s] retransmission failure: T1-cookie", a.name) |
| 4373 |
a.completeHandshake(ErrHandshakeCookieEcho) |
| 4374 |
|
| 4375 |
return |
| 4376 |
} |
| 4377 |
|
| 4378 |
if id == timerT2Shutdown { |
| 4379 |
a.log.Errorf("[%s] retransmission failure: T2-shutdown", a.name) |
| 4380 |
|
| 4381 |
return |
| 4382 |
} |
| 4383 |
|
| 4384 |
if id == timerT3RTX { |
| 4385 |
// T3-rtx timer will not fail by design |
| 4386 |
// Justifications: |
| 4387 |
// * ICE would fail if the connectivity is lost |
| 4388 |
// * WebRTC spec is not clear how this incident should be reported to ULP |
| 4389 |
a.log.Errorf("[%s] retransmission failure: T3-rtx (DATA)", a.name) |
| 4390 |
|
| 4391 |
return |
| 4392 |
} |
| 4393 |
} |
| 4394 |
|
| 4395 |
func (a *Association) onAckTimeout() { |
| 4396 |
a.lock.Lock() |
| 4397 |
defer a.lock.Unlock() |
| 4398 |
|
| 4399 |
a.log.Tracef("[%s] ack timed out (ackState: %d)", a.name, a.ackState) |
| 4400 |
a.stats.incAckTimeouts() |
| 4401 |
|
| 4402 |
a.ackState = ackStateImmediate |
| 4403 |
a.awakeWriteLoop() |
| 4404 |
} |
| 4405 |
|
| 4406 |
// BufferedAmount returns total amount (in bytes) of currently buffered user data. |
| 4407 |
func (a *Association) BufferedAmount() int { |
| 4408 |
a.lock.RLock() |
| 4409 |
defer a.lock.RUnlock() |
| 4410 |
|
| 4411 |
return a.pendingQueue.getNumBytes() + a.inflightQueue.getNumBytes() |
| 4412 |
} |
| 4413 |
|
| 4414 |
// MaxMessageSize returns the maximum message size you can send. |
| 4415 |
func (a *Association) MaxMessageSize() uint32 { |
| 4416 |
return atomic.LoadUint32(&a.maxMessageSize) |
| 4417 |
} |
| 4418 |
|
| 4419 |
// SetMaxMessageSize sets the maximum message size you can send. |
| 4420 |
func (a *Association) SetMaxMessageSize(maxMsgSize uint32) { |
| 4421 |
atomic.StoreUint32(&a.maxMessageSize, maxMsgSize) |
| 4422 |
} |
| 4423 |
|
| 4424 |
// completeHandshake sends the given error to handshakeCompletedCh unless the read/write |
| 4425 |
// side of the association closes before that can happen. It returns whether it was able |
| 4426 |
// to send on the channel or not. |
| 4427 |
func (a *Association) completeHandshake(handshakeErr error) bool { |
| 4428 |
select { |
| 4429 |
// Note: This is a future place where the user could be notified (COMMUNICATION UP) |
| 4430 |
case a.handshakeCompletedCh <- handshakeErr: |
| 4431 |
return true |
| 4432 |
case <-a.closeWriteLoopCh: // check the read/write sides for closure |
| 4433 |
case <-a.readLoopCloseCh: |
| 4434 |
} |
| 4435 |
|
| 4436 |
return false |
| 4437 |
} |
| 4438 |
|
| 4439 |
func (a *Association) pokeTimerLoop() { |
| 4440 |
// enqueue a single wake-up without blocking. |
| 4441 |
select { |
| 4442 |
case a.timerUpdateCh <- struct{}{}: |
| 4443 |
default: |
| 4444 |
} |
| 4445 |
} |
| 4446 |
|
| 4447 |
func (a *Association) startRackTimer(dur time.Duration) { |
| 4448 |
a.timerMu.Lock() |
| 4449 |
|
| 4450 |
if dur <= 0 { |
| 4451 |
a.rackDeadline = time.Time{} |
| 4452 |
} else { |
| 4453 |
a.rackDeadline = time.Now().Add(dur) |
| 4454 |
} |
| 4455 |
|
| 4456 |
a.timerMu.Unlock() |
| 4457 |
|
| 4458 |
a.pokeTimerLoop() |
| 4459 |
} |
| 4460 |
|
| 4461 |
func (a *Association) stopRackTimer() { |
| 4462 |
a.timerMu.Lock() |
| 4463 |
a.rackDeadline = time.Time{} |
| 4464 |
a.timerMu.Unlock() |
| 4465 |
|
| 4466 |
a.pokeTimerLoop() |
| 4467 |
} |
| 4468 |
|
| 4469 |
func (a *Association) startPTOTimer(dur time.Duration) { |
| 4470 |
a.timerMu.Lock() |
| 4471 |
|
| 4472 |
if dur <= 0 { |
| 4473 |
a.ptoDeadline = time.Time{} |
| 4474 |
} else { |
| 4475 |
a.ptoDeadline = time.Now().Add(dur) |
| 4476 |
} |
| 4477 |
|
| 4478 |
a.timerMu.Unlock() |
| 4479 |
|
| 4480 |
a.pokeTimerLoop() |
| 4481 |
} |
| 4482 |
|
| 4483 |
func (a *Association) stopPTOTimer() { |
| 4484 |
a.timerMu.Lock() |
| 4485 |
a.ptoDeadline = time.Time{} |
| 4486 |
a.timerMu.Unlock() |
| 4487 |
|
| 4488 |
a.pokeTimerLoop() |
| 4489 |
} |
| 4490 |
|
| 4491 |
// drainTimer safely stops a timer and drains its channel if needed. |
| 4492 |
func drainTimer(t *time.Timer) { |
| 4493 |
if !t.Stop() { |
| 4494 |
select { |
| 4495 |
case <-t.C: |
| 4496 |
default: |
| 4497 |
} |
| 4498 |
} |
| 4499 |
} |
| 4500 |
|
| 4501 |
// timerLoop runs one goroutine per association for RACK and PTO deadlines. |
| 4502 |
// this only runs if RACK is enabled. |
| 4503 |
func (a *Association) timerLoop() { //nolint:gocognit,cyclop |
| 4504 |
// begin with a disarmed timer. |
| 4505 |
timer := time.NewTimer(time.Hour) |
| 4506 |
drainTimer(timer) |
| 4507 |
armed := false |
| 4508 |
|
| 4509 |
for { |
| 4510 |
// compute the earliest non-zero deadline. |
| 4511 |
a.timerMu.Lock() |
| 4512 |
rackDeadline := a.rackDeadline |
| 4513 |
ptoDeadline := a.ptoDeadline |
| 4514 |
a.timerMu.Unlock() |
| 4515 |
|
| 4516 |
var next time.Time |
| 4517 |
switch { |
| 4518 |
case rackDeadline.IsZero(): |
| 4519 |
next = ptoDeadline |
| 4520 |
case ptoDeadline.IsZero(): |
| 4521 |
next = rackDeadline |
| 4522 |
default: |
| 4523 |
if rackDeadline.Before(ptoDeadline) { |
| 4524 |
next = rackDeadline |
| 4525 |
} else { |
| 4526 |
next = ptoDeadline |
| 4527 |
} |
| 4528 |
} |
| 4529 |
|
| 4530 |
if next.IsZero() { |
| 4531 |
if armed { |
| 4532 |
drainTimer(timer) |
| 4533 |
armed = false |
| 4534 |
} |
| 4535 |
} else { |
| 4536 |
d := time.Until(next) |
| 4537 |
|
| 4538 |
if d <= 0 { |
| 4539 |
d = time.Nanosecond |
| 4540 |
} |
| 4541 |
|
| 4542 |
if armed { |
| 4543 |
drainTimer(timer) |
| 4544 |
} |
| 4545 |
|
| 4546 |
timer.Reset(d) |
| 4547 |
armed = true |
| 4548 |
} |
| 4549 |
|
| 4550 |
select { |
| 4551 |
case <-a.closeWriteLoopCh: |
| 4552 |
if armed { |
| 4553 |
drainTimer(timer) |
| 4554 |
} |
| 4555 |
|
| 4556 |
return |
| 4557 |
|
| 4558 |
case <-a.timerUpdateCh: |
| 4559 |
// re-compute deadlines and (re)arm in next loop iteration. |
| 4560 |
|
| 4561 |
case <-timer.C: |
| 4562 |
armed = false |
| 4563 |
|
| 4564 |
// snapshot & clear due deadlines before firing to avoid races with re-arms. |
| 4565 |
currTime := time.Now() |
| 4566 |
var fireRack, firePTO bool |
| 4567 |
|
| 4568 |
a.timerMu.Lock() |
| 4569 |
|
| 4570 |
if !a.rackDeadline.IsZero() && !currTime.Before(a.rackDeadline) { |
| 4571 |
fireRack = true |
| 4572 |
a.rackDeadline = time.Time{} |
| 4573 |
} |
| 4574 |
|
| 4575 |
if !a.ptoDeadline.IsZero() && !currTime.Before(a.ptoDeadline) { |
| 4576 |
firePTO = true |
| 4577 |
a.ptoDeadline = time.Time{} |
| 4578 |
} |
| 4579 |
|
| 4580 |
a.timerMu.Unlock() |
| 4581 |
|
| 4582 |
// fire callbacks without holding timerMu. |
| 4583 |
if fireRack { |
| 4584 |
a.onRackTimeout() |
| 4585 |
} |
| 4586 |
|
| 4587 |
if firePTO { |
| 4588 |
a.onPTOTimer() |
| 4589 |
} |
| 4590 |
} |
| 4591 |
} |
| 4592 |
} |
| 4593 |
|
| 4594 |
// onRackAfterSACK implements the RACK logic (RACK for SCTP section 2A/B, section 3) and TLP scheduling (section 2C). |
| 4595 |
func (a *Association) onRackAfterSACK( // nolint:gocognit,cyclop,gocyclo |
| 4596 |
deliveredFound bool, |
| 4597 |
newestDeliveredSendTime time.Time, |
| 4598 |
newestDeliveredOrigTSN uint32, |
| 4599 |
sack *chunkSelectiveAck, |
| 4600 |
) { |
| 4601 |
// store the current time for when we check if it's needed in step 2 (whether we should maintain ReoWND) |
| 4602 |
currTime := time.Now() |
| 4603 |
|
| 4604 |
// 1) Update highest delivered original TSN for reordering detection (section 2B) |
| 4605 |
if deliveredFound { |
| 4606 |
if sna32LT(a.rackHighestDeliveredOrigTSN, newestDeliveredOrigTSN) { |
| 4607 |
a.rackHighestDeliveredOrigTSN = newestDeliveredOrigTSN |
| 4608 |
} else { |
| 4609 |
// ACK of an original TSN below the high-watermark -> reordering observed |
| 4610 |
a.rackReorderingSeen = true |
| 4611 |
} |
| 4612 |
if newestDeliveredSendTime.After(a.rackDeliveredTime) { |
| 4613 |
a.rackDeliveredTime = newestDeliveredSendTime |
| 4614 |
} |
| 4615 |
} |
| 4616 |
|
| 4617 |
// 2) Maintain ReoWND (RACK for SCTP section 2B) |
| 4618 |
if minRTT := a.rack.rackMinRTTWnd.Min(currTime); minRTT > 0 { |
| 4619 |
a.rackMinRTT = minRTT |
| 4620 |
} |
| 4621 |
|
| 4622 |
var base time.Duration |
| 4623 |
if a.rackMinRTT > 0 { |
| 4624 |
base = max(a.rackMinRTT/4, a.rack.rackReoWndFloor) |
| 4625 |
} |
| 4626 |
|
| 4627 |
// Suppress during recovery if no reordering ever seen; else (re)initialize from base if zero. |
| 4628 |
if !a.rackReorderingSeen && (a.inFastRecovery || a.t3RTX.isRunning()) { |
| 4629 |
a.rackReoWnd = 0 |
| 4630 |
} else if a.rackReoWnd == 0 && base > 0 { |
| 4631 |
a.rackReoWnd = base |
| 4632 |
} |
| 4633 |
|
| 4634 |
// DSACK-style inflation using SCTP duplicate TSNs (RACK for SCTP section 3 noting SCTP |
| 4635 |
// natively reports duplicates + RACK for SCTP section 2B policy) |
| 4636 |
if len(sack.duplicateTSN) > 0 && a.rackMinRTT > 0 { |
| 4637 |
a.rackReoWnd += max(a.rackMinRTT/4, a.rack.rackReoWndFloor) |
| 4638 |
// keep inflated for 16 loss recoveries before reset |
| 4639 |
a.rackKeepInflatedRecoveries = 16 |
| 4640 |
a.log.Tracef("[%s] RACK: DSACK/dupTSN seen, inflate reoWnd to %v", a.name, a.rackReoWnd) |
| 4641 |
} |
| 4642 |
|
| 4643 |
// decrement the keep inflated counter when we leave recovery |
| 4644 |
if !a.inFastRecovery && a.rackKeepInflatedRecoveries > 0 { |
| 4645 |
a.rackKeepInflatedRecoveries-- |
| 4646 |
if a.rackKeepInflatedRecoveries == 0 && a.rackMinRTT > 0 { |
| 4647 |
a.rackReoWnd = a.rackMinRTT / 4 |
| 4648 |
} |
| 4649 |
} |
| 4650 |
|
| 4651 |
// RFC 8985: the reordering window MUST be bounded by SRTT. |
| 4652 |
if srttMs := a.SRTT(); srttMs > 0 { |
| 4653 |
if srttDur := time.Duration(srttMs * 1e6); a.rackReoWnd > srttDur { |
| 4654 |
a.rackReoWnd = srttDur |
| 4655 |
} |
| 4656 |
} |
| 4657 |
|
| 4658 |
// 3) Loss marking on ACK: any outstanding chunk whose (send_time + reoWnd) < newestDeliveredSendTime |
| 4659 |
// is lost (RACK for SCTP section 2A) |
| 4660 |
if !a.rackDeliveredTime.IsZero() { //nolint:nestif |
| 4661 |
marked := false |
| 4662 |
|
| 4663 |
for chunk := a.rackHead; chunk != nil; { |
| 4664 |
next := chunk.rackNext // save in case we remove c |
| 4665 |
|
| 4666 |
// but clean up if they exist. |
| 4667 |
if chunk.acked || chunk.abandoned() { |
| 4668 |
a.rackRemove(chunk) |
| 4669 |
chunk = next |
| 4670 |
|
| 4671 |
continue |
| 4672 |
} |
| 4673 |
|
| 4674 |
if chunk.retransmit || chunk.nSent > 1 { |
| 4675 |
// Either already scheduled for retransmit or not an original send: |
| 4676 |
// skip but keep in list in case it's still outstanding. |
| 4677 |
chunk = next |
| 4678 |
|
| 4679 |
continue |
| 4680 |
} |
| 4681 |
|
| 4682 |
// Ordered by original send time. If this one is too new, |
| 4683 |
// all later ones are even newer -> short-circuit. |
| 4684 |
if !chunk.since.Add(a.rackReoWnd).Before(a.rackDeliveredTime) { |
| 4685 |
break |
| 4686 |
} |
| 4687 |
|
| 4688 |
// Mark as lost by RACK. |
| 4689 |
chunk.retransmit = true |
| 4690 |
marked = true |
| 4691 |
|
| 4692 |
// Remove from xmit-time list: we no longer need RACK for this TSN. |
| 4693 |
a.rackRemove(chunk) |
| 4694 |
|
| 4695 |
a.log.Tracef("[%s] RACK: mark lost tsn=%d (sent=%v, delivered=%v, reoWnd=%v)", |
| 4696 |
a.name, chunk.tsn, chunk.since, a.rackDeliveredTime, a.rackReoWnd) |
| 4697 |
|
| 4698 |
chunk = next |
| 4699 |
} |
| 4700 |
|
| 4701 |
if marked { |
| 4702 |
// loss detected during active TLR so we must reduce burst |
| 4703 |
if a.tlrActive { |
| 4704 |
a.tlrApplyAdditionalLossLocked(currTime) |
| 4705 |
} |
| 4706 |
|
| 4707 |
a.awakeWriteLoop() |
| 4708 |
} |
| 4709 |
} |
| 4710 |
|
| 4711 |
// 4) Arm the RACK timer if there are still outstanding but not-yet-overdue chunks (RACK for SCTP section 2A) |
| 4712 |
if a.rackHead != nil && !a.rackDeliveredTime.IsZero() { |
| 4713 |
// RackRTT = RTT of the most recently delivered packet |
| 4714 |
rackRTT := max(time.Since(a.rackDeliveredTime), time.Duration(0)) |
| 4715 |
a.startRackTimer(rackRTT + a.rackReoWnd) // RACK for SCTP section 2A |
| 4716 |
} else { |
| 4717 |
a.stopRackTimer() |
| 4718 |
} |
| 4719 |
|
| 4720 |
// 5) Re/schedule Tail Loss Probe (PTO) (RACK for SCTP section 2C) |
| 4721 |
// Triggered when new data is sent or cum-ack advances; we approximate by scheduling on every SACK that advanced |
| 4722 |
if a.inflightQueue.size() == 0 { |
| 4723 |
a.stopPTOTimer() |
| 4724 |
|
| 4725 |
return |
| 4726 |
} |
| 4727 |
|
| 4728 |
var pto time.Duration |
| 4729 |
srttMs := a.SRTT() |
| 4730 |
if srttMs > 0 { |
| 4731 |
srtt := time.Duration(srttMs * 1e6) |
| 4732 |
extra := 2 * time.Millisecond |
| 4733 |
|
| 4734 |
if a.inflightQueue.size() == 1 { |
| 4735 |
extra = a.rack.rackWCDelAck // 200ms for single outstanding, else 2ms |
| 4736 |
} |
| 4737 |
|
| 4738 |
pto = 2*srtt + extra |
| 4739 |
} else { |
| 4740 |
pto = time.Second // no RTT yet |
| 4741 |
} |
| 4742 |
|
| 4743 |
a.startPTOTimer(pto) |
| 4744 |
} |
| 4745 |
|
| 4746 |
// schedulePTOAfterSendLocked starts/restarts the PTO timer when new data is transmitted. |
| 4747 |
// Caller must hold a.lock. |
| 4748 |
func (a *Association) schedulePTOAfterSendLocked() { |
| 4749 |
if a.inflightQueue.size() == 0 { |
| 4750 |
a.stopPTOTimer() |
| 4751 |
|
| 4752 |
return |
| 4753 |
} |
| 4754 |
|
| 4755 |
var pto time.Duration |
| 4756 |
if srttMs := a.SRTT(); srttMs > 0 { |
| 4757 |
srtt := time.Duration(srttMs * 1e6) |
| 4758 |
extra := 2 * time.Millisecond |
| 4759 |
|
| 4760 |
if a.inflightQueue.size() == 1 { |
| 4761 |
extra = a.rack.rackWCDelAck |
| 4762 |
} |
| 4763 |
|
| 4764 |
pto = 2*srtt + extra |
| 4765 |
} else { |
| 4766 |
pto = time.Second |
| 4767 |
} |
| 4768 |
|
| 4769 |
a.startPTOTimer(pto) |
| 4770 |
} |
| 4771 |
|
| 4772 |
// onRackTimeout is fired to avoid waiting for the next ACK. |
| 4773 |
func (a *Association) onRackTimeout() { |
| 4774 |
a.lock.Lock() |
| 4775 |
defer a.lock.Unlock() |
| 4776 |
a.onRackTimeoutLocked() |
| 4777 |
} |
| 4778 |
|
| 4779 |
func (a *Association) onRackTimeoutLocked() { //nolint:cyclop |
| 4780 |
if a.rackDeliveredTime.IsZero() { |
| 4781 |
return |
| 4782 |
} |
| 4783 |
|
| 4784 |
marked := false |
| 4785 |
|
| 4786 |
for chunk := a.rackHead; chunk != nil; { |
| 4787 |
next := chunk.rackNext |
| 4788 |
|
| 4789 |
if chunk.acked || chunk.abandoned() { |
| 4790 |
a.rackRemove(chunk) |
| 4791 |
chunk = next |
| 4792 |
|
| 4793 |
continue |
| 4794 |
} |
| 4795 |
if chunk.retransmit || chunk.nSent > 1 { |
| 4796 |
chunk = next |
| 4797 |
|
| 4798 |
continue |
| 4799 |
} |
| 4800 |
|
| 4801 |
if !chunk.since.Add(a.rackReoWnd).Before(a.rackDeliveredTime) { |
| 4802 |
// too new, later ones are newer so we can skip. |
| 4803 |
break |
| 4804 |
} |
| 4805 |
|
| 4806 |
chunk.retransmit = true |
| 4807 |
marked = true |
| 4808 |
a.rackRemove(chunk) |
| 4809 |
|
| 4810 |
a.log.Tracef("[%s] RACK timer: mark lost tsn=%d", a.name, chunk.tsn) |
| 4811 |
|
| 4812 |
chunk = next |
| 4813 |
} |
| 4814 |
|
| 4815 |
if marked { |
| 4816 |
// loss detected during active TLR so we must reduce burst |
| 4817 |
if a.tlrActive { |
| 4818 |
a.tlrApplyAdditionalLossLocked(time.Now()) |
| 4819 |
} |
| 4820 |
|
| 4821 |
a.awakeWriteLoop() |
| 4822 |
} |
| 4823 |
} |
| 4824 |
|
| 4825 |
func (a *Association) onPTOTimer() { |
| 4826 |
a.lock.Lock() |
| 4827 |
defer a.lock.Unlock() |
| 4828 |
a.onPTOTimerLocked() |
| 4829 |
} |
| 4830 |
|
| 4831 |
func (a *Association) onPTOTimerLocked() { |
| 4832 |
// if nothing is inflight, PTO should not drive TLR. |
| 4833 |
// use PTO as a chance to probe RTT via HEARTBEAT instead of retransmitting DATA. |
| 4834 |
if a.inflightQueue.size() == 0 { |
| 4835 |
a.stopPTOTimer() |
| 4836 |
a.log.Tracef("[%s] PTO idle: sending active HEARTBEAT for RTT probe", a.name) |
| 4837 |
a.sendActiveHeartbeatLocked() |
| 4838 |
|
| 4839 |
return |
| 4840 |
} |
| 4841 |
|
| 4842 |
currTime := time.Now() |
| 4843 |
|
| 4844 |
if !a.tlrActive { |
| 4845 |
a.tlrBeginLocked() |
| 4846 |
} else { |
| 4847 |
a.tlrApplyAdditionalLossLocked(currTime) |
| 4848 |
} |
| 4849 |
|
| 4850 |
// If we have unsent data, PTO should just wake the writer. |
| 4851 |
if a.pendingQueue.size() > 0 { |
| 4852 |
a.awakeWriteLoop() |
| 4853 |
|
| 4854 |
return |
| 4855 |
} |
| 4856 |
|
| 4857 |
// otherwise retransmit most recently sent in-flight DATA. |
| 4858 |
var latest *chunkPayloadData |
| 4859 |
for i := uint32(0); ; i++ { |
| 4860 |
c, ok := a.inflightQueue.get(a.cumulativeTSNAckPoint + i + 1) |
| 4861 |
if !ok { |
| 4862 |
break |
| 4863 |
} |
| 4864 |
|
| 4865 |
if c.acked || c.abandoned() { |
| 4866 |
continue |
| 4867 |
} |
| 4868 |
|
| 4869 |
latest = c |
| 4870 |
} |
| 4871 |
|
| 4872 |
if latest != nil && !latest.retransmit { |
| 4873 |
latest.retransmit = true |
| 4874 |
a.log.Tracef("[%s] PTO fired: probe tsn=%d", a.name, latest.tsn) |
| 4875 |
a.awakeWriteLoop() |
| 4876 |
} |
| 4877 |
} |
| 4878 |
|
| 4879 |
func (a *Association) rackInsert(c *chunkPayloadData) { |
| 4880 |
if c == nil || c.rackInList { |
| 4881 |
return |
| 4882 |
} |
| 4883 |
|
| 4884 |
if a.rackTail != nil { |
| 4885 |
a.rackTail.rackNext = c |
| 4886 |
c.rackPrev = a.rackTail |
| 4887 |
} else { |
| 4888 |
a.rackHead = c |
| 4889 |
} |
| 4890 |
a.rackTail = c |
| 4891 |
c.rackInList = true |
| 4892 |
} |
| 4893 |
|
| 4894 |
func (a *Association) rackRemove(chunk *chunkPayloadData) { |
| 4895 |
if chunk == nil || !chunk.rackInList { |
| 4896 |
return |
| 4897 |
} |
| 4898 |
|
| 4899 |
if prev := chunk.rackPrev; prev != nil { |
| 4900 |
prev.rackNext = chunk.rackNext |
| 4901 |
} else { |
| 4902 |
a.rackHead = chunk.rackNext |
| 4903 |
} |
| 4904 |
|
| 4905 |
if next := chunk.rackNext; next != nil { |
| 4906 |
next.rackPrev = chunk.rackPrev |
| 4907 |
} else { |
| 4908 |
a.rackTail = chunk.rackPrev |
| 4909 |
} |
| 4910 |
|
| 4911 |
chunk.rackPrev = nil |
| 4912 |
chunk.rackNext = nil |
| 4913 |
chunk.rackInList = false |
| 4914 |
} |
| 4915 |
|
| 4916 |
// caller must hold a.lock. |
| 4917 |
func (a *Association) tlrFirstRTTDurationLocked() time.Duration { |
| 4918 |
// Use SRTT when available; fall back to a safe default. |
| 4919 |
if srttMs := a.SRTT(); srttMs > 0 { |
| 4920 |
return time.Duration(srttMs * 1e6) |
| 4921 |
} |
| 4922 |
|
| 4923 |
return time.Second |
| 4924 |
} |
| 4925 |
|
| 4926 |
// caller must hold a.lock. |
| 4927 |
func (a *Association) tlrUpdatePhaseLocked(currTime time.Time) { |
| 4928 |
if !a.tlrActive || !a.tlrFirstRTT { |
| 4929 |
return |
| 4930 |
} |
| 4931 |
if a.tlrStartTime.IsZero() { |
| 4932 |
return |
| 4933 |
} |
| 4934 |
|
| 4935 |
if currTime.Sub(a.tlrStartTime) >= a.tlrFirstRTTDurationLocked() { |
| 4936 |
a.tlrFirstRTT = false |
| 4937 |
} |
| 4938 |
} |
| 4939 |
|
| 4940 |
// caller must hold a.lock. |
| 4941 |
func (a *Association) tlrCurrentBurstUnitsLocked() int64 { |
| 4942 |
if !a.tlrActive { |
| 4943 |
return 0 |
| 4944 |
} |
| 4945 |
|
| 4946 |
a.tlrUpdatePhaseLocked(time.Now()) |
| 4947 |
|
| 4948 |
if a.tlrFirstRTT { |
| 4949 |
return a.tlrBurstFirstRTTUnits |
| 4950 |
} |
| 4951 |
|
| 4952 |
return a.tlrBurstLaterRTTUnits |
| 4953 |
} |
| 4954 |
|
| 4955 |
// caller must hold a.lock. |
| 4956 |
// Returns remaining burst budget in "scaled bytes": bytes * 4 (quarter-MTU precision). |
| 4957 |
func (a *Association) tlrCurrentBurstBudgetScaledLocked() int64 { |
| 4958 |
if !a.tlrActive { |
| 4959 |
return 0 |
| 4960 |
} |
| 4961 |
|
| 4962 |
units := a.tlrCurrentBurstUnitsLocked() |
| 4963 |
|
| 4964 |
return units * int64(a.MTU()) |
| 4965 |
} |
| 4966 |
|
| 4967 |
// caller must hold a.lock. |
| 4968 |
func (a *Association) tlrHighestOutstandingTSNLocked() (uint32, bool) { |
| 4969 |
var last uint32 |
| 4970 |
found := false |
| 4971 |
|
| 4972 |
for i := uint32(0); ; i++ { |
| 4973 |
tsn := a.cumulativeTSNAckPoint + i + 1 |
| 4974 |
_, ok := a.inflightQueue.get(tsn) |
| 4975 |
if !ok { |
| 4976 |
break |
| 4977 |
} |
| 4978 |
last = tsn |
| 4979 |
found = true |
| 4980 |
} |
| 4981 |
|
| 4982 |
return last, found |
| 4983 |
} |
| 4984 |
|
| 4985 |
// caller must hold a.lock. |
| 4986 |
func (a *Association) tlrBeginLocked() { |
| 4987 |
currTime := time.Now() |
| 4988 |
|
| 4989 |
a.tlrActive = true |
| 4990 |
a.tlrFirstRTT = true |
| 4991 |
a.tlrHadAdditionalLoss = false |
| 4992 |
a.tlrStartTime = currTime |
| 4993 |
|
| 4994 |
if endTSN, ok := a.tlrHighestOutstandingTSNLocked(); ok { |
| 4995 |
a.tlrEndTSN = endTSN |
| 4996 |
} else { |
| 4997 |
a.tlrEndTSN = a.cumulativeTSNAckPoint |
| 4998 |
} |
| 4999 |
} |
| 5000 |
|
| 5001 |
// caller must hold a.lock. |
| 5002 |
func (a *Association) tlrApplyAdditionalLossLocked(currTime time.Time) { |
| 5003 |
if !a.tlrActive { |
| 5004 |
return |
| 5005 |
} |
| 5006 |
|
| 5007 |
// Decide whether we're still within the first recovery RTT window. |
| 5008 |
a.tlrUpdatePhaseLocked(currTime) |
| 5009 |
|
| 5010 |
a.tlrHadAdditionalLoss = true |
| 5011 |
a.tlrGoodOps = 0 |
| 5012 |
|
| 5013 |
if a.tlrFirstRTT { |
| 5014 |
// Loss during first recovery RTT => initial burst too high. |
| 5015 |
a.tlrBurstFirstRTTUnits -= tlrBurstStepDownFirstRTT |
| 5016 |
if a.tlrBurstFirstRTTUnits < tlrBurstMinFirstRTT { |
| 5017 |
a.tlrBurstFirstRTTUnits = tlrBurstMinFirstRTT |
| 5018 |
} |
| 5019 |
} else { |
| 5020 |
// Loss during later RTTs => increasing rate too high. |
| 5021 |
a.tlrBurstLaterRTTUnits -= tlrBurstStepDownLaterRTT |
| 5022 |
if a.tlrBurstLaterRTTUnits < tlrBurstMinLaterRTT { |
| 5023 |
a.tlrBurstLaterRTTUnits = tlrBurstMinLaterRTT |
| 5024 |
} |
| 5025 |
} |
| 5026 |
} |
| 5027 |
|
| 5028 |
// caller must hold a.lock. |
| 5029 |
func (a *Association) tlrMaybeFinishLocked(ackProgress bool) { |
| 5030 |
if !a.tlrActive { |
| 5031 |
return |
| 5032 |
} |
| 5033 |
|
| 5034 |
// determine if we should move from the first RTT burst to later RTT burst. |
| 5035 |
if a.tlrFirstRTT && ackProgress { |
| 5036 |
a.tlrFirstRTT = false |
| 5037 |
} |
| 5038 |
|
| 5039 |
// finish once cumulatively ACKed through the tail we were recovering. |
| 5040 |
if sna32GTE(a.cumulativeTSNAckPoint, a.tlrEndTSN) { |
| 5041 |
if !a.tlrHadAdditionalLoss { |
| 5042 |
a.tlrGoodOps++ |
| 5043 |
if a.tlrGoodOps >= tlrGoodOpsResetThreshold { |
| 5044 |
a.tlrBurstFirstRTTUnits = tlrBurstDefaultFirstRTT |
| 5045 |
a.tlrBurstLaterRTTUnits = tlrBurstDefaultLaterRTT |
| 5046 |
a.tlrGoodOps = 0 |
| 5047 |
} |
| 5048 |
} else { |
| 5049 |
a.tlrGoodOps = 0 |
| 5050 |
} |
| 5051 |
|
| 5052 |
a.tlrActive = false |
| 5053 |
a.tlrFirstRTT = false |
| 5054 |
a.tlrHadAdditionalLoss = false |
| 5055 |
a.tlrEndTSN = 0 |
| 5056 |
} |
| 5057 |
} |
| 5058 |
|
| 5059 |
// caller must hold a.lock. |
| 5060 |
// "budgetScaled" is remaining burst budget in (bytes*4) scale. |
| 5061 |
// "consumed" allows the first send in a burst. |
| 5062 |
func (a *Association) tlrAllowSendLocked(budgetScaled *int64, consumed *bool, estBytes int) bool { |
| 5063 |
if !a.tlrActive || budgetScaled == nil || consumed == nil { |
| 5064 |
return true |
| 5065 |
} |
| 5066 |
if estBytes <= 0 { |
| 5067 |
return true |
| 5068 |
} |
| 5069 |
|
| 5070 |
needScaled := int64(estBytes) * tlrUnitsPerMTU // bytes*4 |
| 5071 |
if *consumed && *budgetScaled < needScaled { |
| 5072 |
return false |
| 5073 |
} |
| 5074 |
|
| 5075 |
*budgetScaled -= needScaled |
| 5076 |
if *budgetScaled < 0 { |
| 5077 |
*budgetScaled = 0 |
| 5078 |
} |
| 5079 |
*consumed = true |
| 5080 |
|
| 5081 |
return true |
| 5082 |
} |
| 5083 |
|
| 5084 |
// ActiveHeartbeat sends a HEARTBEAT chunk on the association to perform an |
| 5085 |
// on-demand RTT measurement without application payload. |
| 5086 |
// |
| 5087 |
// It is safe to call from outside; it will take the association lock and |
| 5088 |
// be a no-op if the association is not established. |
| 5089 |
func (a *Association) ActiveHeartbeat() { |
| 5090 |
a.lock.Lock() |
| 5091 |
defer a.lock.Unlock() |
| 5092 |
|
| 5093 |
if a.getState() != established { |
| 5094 |
return |
| 5095 |
} |
| 5096 |
|
| 5097 |
a.sendActiveHeartbeatLocked() |
| 5098 |
} |
| 5099 |
|
| 5100 |
// caller must hold a.lock. |
| 5101 |
func (a *Association) sendActiveHeartbeatLocked() { |
| 5102 |
now := time.Now().UnixNano() |
| 5103 |
buf := make([]byte, 8) |
| 5104 |
binary.BigEndian.PutUint64(buf, uint64(now)) //nolint:gosec // time.now() will never be negative |
| 5105 |
|
| 5106 |
info := ¶mHeartbeatInfo{heartbeatInformation: buf} |
| 5107 |
|
| 5108 |
hb := &chunkHeartbeat{ |
| 5109 |
chunkHeader: chunkHeader{ |
| 5110 |
typ: ctHeartbeat, |
| 5111 |
flags: 0, |
| 5112 |
}, |
| 5113 |
params: []param{info}, |
| 5114 |
} |
| 5115 |
|
| 5116 |
a.controlQueue.push(&packet{ |
| 5117 |
verificationTag: a.peerVerificationTag, |
| 5118 |
sourcePort: a.sourcePort, |
| 5119 |
destinationPort: a.destinationPort, |
| 5120 |
chunks: []chunk{hb}, |
| 5121 |
}) |
| 5122 |
a.awakeWriteLoop() |
| 5123 |
} |
| 5124 |
|
| 5125 |
// GenerateOutOfBandToken generates an out-of-band connection token (i.e. a |
| 5126 |
// serialized SCTP INIT chunk) for use with SNAP. |
| 5127 |
func GenerateOutOfBandToken(opts ...ClientOption) ([]byte, error) { |
| 5128 |
config := &Config{} |
| 5129 |
config.applyDefaults() |
| 5130 |
|
| 5131 |
for _, opt := range opts { |
| 5132 |
if opt == nil { |
| 5133 |
continue |
| 5134 |
} |
| 5135 |
if err := opt.applyClient(config); err != nil { |
| 5136 |
return nil, err |
| 5137 |
} |
| 5138 |
} |
| 5139 |
|
| 5140 |
config.applyDefaults() |
| 5141 |
|
| 5142 |
init := &chunkInit{} |
| 5143 |
init.initialTSN = globalMathRandomGenerator.Uint32() |
| 5144 |
init.numOutboundStreams = math.MaxUint16 |
| 5145 |
init.numInboundStreams = math.MaxUint16 |
| 5146 |
init.initiateTag = generateInitiateTag() |
| 5147 |
init.advertisedReceiverWindowCredit = config.MaxReceiveBufferSize |
| 5148 |
setSupportedExtensions(&init.chunkInitCommon, config.enableInterleaving) |
| 5149 |
|
| 5150 |
if config.EnableZeroChecksum { |
| 5151 |
init.params = append(init.params, ¶mZeroChecksumAcceptable{edmid: dtlsErrorDetectionMethod}) |
| 5152 |
} |
| 5153 |
_, err := init.check() |
| 5154 |
if err != nil { |
| 5155 |
return nil, err |
| 5156 |
} |
| 5157 |
|
| 5158 |
return init.marshal() |
| 5159 |
} |