Debian Codegraph @

stream.go

raw ◀ ▶
1 Debian patch touch this file
1 // SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
2 // SPDX-License-Identifier: MIT
3
4 package sctp
5
6 import (
7 "errors"
8 "fmt"
9 "io"
10 "os"
11 "sync"
12 "sync/atomic"
13 "time"
14
15 "github.com/pion/logging"
•16 "github.com/pion/transport/v3/deadline"
17 )
18
19 const (
20 // ReliabilityTypeReliable is used for reliable transmission.
21 ReliabilityTypeReliable byte = 0
22 // ReliabilityTypeRexmit is used for partial reliability by retransmission count.
23 ReliabilityTypeRexmit byte = 1
24 // ReliabilityTypeTimed is used for partial reliability by retransmission duration.
25 ReliabilityTypeTimed byte = 2
26 )
27
28 // StreamState is an enum for SCTP Stream state field
29 // This field identifies the state of stream.
30 type StreamState int
31
32 // StreamState enums.
33 const (
34 StreamStateOpen StreamState = iota // Stream object starts with StreamStateOpen
35 StreamStateClosing // Outgoing stream is being reset
36 StreamStateClosed // Stream has been closed
37 )
38
39 func (ss StreamState) String() string {
40 switch ss {
41 case StreamStateOpen:
42 return "open"
43 case StreamStateClosing:
44 return "closing"
45 case StreamStateClosed:
46 return "closed"
47 }
48
49 return "unknown"
50 }
51
52 // SCTP stream errors.
53 var (
54 ErrOutboundPacketTooLarge = errors.New("outbound packet larger than maximum message size")
55 ErrStreamClosed = errors.New("stream closed")
56 ErrReadDeadlineExceeded = fmt.Errorf("read deadline exceeded: %w", os.ErrDeadlineExceeded)
57 )
58
59 // Stream represents an SCTP stream.
60 type Stream struct {
61 association *Association
62 lock sync.RWMutex
63 streamIdentifier uint16
64 defaultPayloadType PayloadProtocolIdentifier
65 reassemblyQueue *reassemblyQueue
66 sequenceNumber uint16
67 nextOrderedMID uint32
68 nextUnorderedMID uint32
69 readNotifier *sync.Cond
70 readErr error
71 readTimeoutCancel chan struct{}
72 writeDeadline *deadline.Deadline
73 writeLock sync.Mutex
74 unordered bool
75 reliabilityType byte
76 reliabilityValue uint32
77 bufferedAmount uint64
78 bufferedAmountLow uint64
79 onBufferedAmountLow func()
80 state StreamState
81 log logging.LeveledLogger
82 name string
83 }
84
85 // StreamIdentifier returns the Stream identifier associated to the stream.
86 func (s *Stream) StreamIdentifier() uint16 {
87 s.lock.RLock()
88 defer s.lock.RUnlock()
89
90 return s.streamIdentifier
91 }
92
93 // SetDefaultPayloadType sets the default payload type used by Write.
94 func (s *Stream) SetDefaultPayloadType(defaultPayloadType PayloadProtocolIdentifier) {
95 atomic.StoreUint32((*uint32)(&s.defaultPayloadType), uint32(defaultPayloadType))
96 }
97
98 // SetReliabilityParams sets reliability parameters for this stream.
99 func (s *Stream) SetReliabilityParams(unordered bool, relType byte, relVal uint32) {
100 s.lock.Lock()
101 defer s.lock.Unlock()
102
103 s.setReliabilityParams(unordered, relType, relVal)
104 }
105
106 // setReliabilityParams sets reliability parameters for this stream.
107 // The caller should hold the lock.
108 func (s *Stream) setReliabilityParams(unordered bool, relType byte, relVal uint32) {
109 s.log.Debugf("[%s] reliability params: ordered=%v type=%d value=%d",
110 s.name, !unordered, relType, relVal)
111 s.unordered = unordered
112 s.reliabilityType = relType
113 s.reliabilityValue = relVal
114 }
115
116 // Read reads a packet of len(p) bytes, dropping the Payload Protocol Identifier.
117 // Returns EOF when the stream is reset or an error if the stream is closed
118 // otherwise.
119 func (s *Stream) Read(p []byte) (int, error) {
120 n, _, err := s.ReadSCTP(p)
121
122 return n, err
123 }
124
125 // ReadSCTP reads a packet of len(payload) bytes and returns the associated Payload
126 // Protocol Identifier.
127 // Returns EOF when the stream is reset or an error if the stream is closed
128 // otherwise.
129 func (s *Stream) ReadSCTP(payload []byte) (int, PayloadProtocolIdentifier, error) {
130 s.lock.Lock()
131 defer s.lock.Unlock()
132
133 defer func() {
134 // close readTimeoutCancel if the current read timeout routine is no longer effective
135 if s.readTimeoutCancel != nil && s.readErr != nil {
136 close(s.readTimeoutCancel)
137 s.readTimeoutCancel = nil
138 }
139 }()
140
141 for {
142 n, ppi, err := s.reassemblyQueue.read(payload)
143 if err == nil || errors.Is(err, io.ErrShortBuffer) {
144 return n, ppi, err
145 }
146
147 if s.readErr != nil {
148 return 0, PayloadProtocolIdentifier(0), s.readErr
149 }
150
151 s.readNotifier.Wait()
152 }
153 }
154
155 // SetReadDeadline sets the read deadline in an identical way to net.Conn.
156 func (s *Stream) SetReadDeadline(deadline time.Time) error {
157 s.lock.Lock()
158 defer s.lock.Unlock()
159
160 if s.readTimeoutCancel != nil {
161 close(s.readTimeoutCancel)
162 s.readTimeoutCancel = nil
163 }
164
165 if s.readErr != nil {
166 if !errors.Is(s.readErr, ErrReadDeadlineExceeded) {
167 return nil
168 }
169 s.readErr = nil
170 }
171
172 if !deadline.IsZero() {
173 s.readTimeoutCancel = make(chan struct{})
174
175 go func(readTimeoutCancel chan struct{}) {
176 t := time.NewTimer(time.Until(deadline))
177 select {
178 case <-readTimeoutCancel:
179 t.Stop()
180
181 return
182 case <-t.C:
183 select {
184 case <-readTimeoutCancel:
185 return
186 default:
187 }
188 s.lock.Lock()
189 if s.readErr == nil {
190 s.readErr = ErrReadDeadlineExceeded
191 }
192 s.readTimeoutCancel = nil
193 s.lock.Unlock()
194
195 s.readNotifier.Signal()
196 }
197 }(s.readTimeoutCancel)
198 }
199
200 return nil
201 }
202
203 func (s *Stream) handleData(pd *chunkPayloadData) error {
204 s.lock.Lock()
205 defer s.lock.Unlock()
206
207 var readable bool
208 complete, err := s.reassemblyQueue.pushWithError(pd)
209 if err != nil {
210 return err
211 }
212 if complete {
213 readable = s.reassemblyQueue.isReadable()
214 s.log.Debugf("[%s] reassemblyQueue readable=%v", s.name, readable)
215 if readable {
216 s.log.Debugf("[%s] readNotifier.signal()", s.name)
217 s.readNotifier.Signal()
218 s.log.Debugf("[%s] readNotifier.signal() done", s.name)
219 }
220 }
221
222 return nil
223 }
224
225 func (s *Stream) handleForwardTSNForOrdered(ssn uint16) {
226 var readable bool
227
228 func() {
229 s.lock.Lock()
230 defer s.lock.Unlock()
231
232 if s.unordered {
233 return // unordered chunks are handled by handleForwardUnordered method
234 }
235
236 // Remove all chunks older than or equal to the new TSN from
237 // the reassemblyQueue.
238 s.reassemblyQueue.forwardTSNForOrdered(ssn)
239 readable = s.reassemblyQueue.isReadable()
240 }()
241
242 // Notify the reader asynchronously if there's a data chunk to read.
243 if readable {
244 s.readNotifier.Signal()
245 }
246 }
247
248 func (s *Stream) handleForwardTSNForUnordered(newCumulativeTSN uint32) {
249 var readable bool
250
251 func() {
252 s.lock.Lock()
253 defer s.lock.Unlock()
254
255 if !s.unordered {
256 return // ordered chunks are handled by handleForwardTSNOrdered method
257 }
258
259 // Remove all chunks older than or equal to the new TSN from
260 // the reassemblyQueue.
261 s.reassemblyQueue.forwardTSNForUnordered(newCumulativeTSN)
262 readable = s.reassemblyQueue.isReadable()
263 }()
264
265 // Notify the reader asynchronously if there's a data chunk to read.
266 if readable {
267 s.readNotifier.Signal()
268 }
269 }
270
271 func (s *Stream) handleForwardTSNForOrderedMID(mid uint32) {
272 var readable bool
273
274 func() {
275 s.lock.Lock()
276 defer s.lock.Unlock()
277
278 s.reassemblyQueue.forwardTSNForOrderedMID(mid)
279 readable = s.reassemblyQueue.isReadable()
280 }()
281
282 if readable {
283 s.readNotifier.Signal()
284 }
285 }
286
287 func (s *Stream) handleForwardTSNForUnorderedMID(mid uint32) {
288 var readable bool
289
290 func() {
291 s.lock.Lock()
292 defer s.lock.Unlock()
293
294 s.reassemblyQueue.forwardTSNForUnorderedMID(mid)
295 readable = s.reassemblyQueue.isReadable()
296 }()
297
298 if readable {
299 s.readNotifier.Signal()
300 }
301 }
302
303 // Write writes len(payload) bytes from payload with the default Payload Protocol Identifier.
304 func (s *Stream) Write(payload []byte) (n int, err error) {
305 ppi := PayloadProtocolIdentifier(atomic.LoadUint32((*uint32)(&s.defaultPayloadType)))
306
307 return s.WriteSCTP(payload, ppi)
308 }
309
310 // WriteSCTP writes len(payload) bytes from payload to the DTLS connection.
311 func (s *Stream) WriteSCTP(payload []byte, ppi PayloadProtocolIdentifier) (int, error) {
312 maxMessageSize := s.association.MaxMessageSize()
313 if len(payload) > int(maxMessageSize) {
314 return 0, fmt.Errorf("%w: %v", ErrOutboundPacketTooLarge, maxMessageSize)
315 }
316
317 if s.State() != StreamStateOpen {
318 return 0, ErrStreamClosed
319 }
320
321 // the send could fail if the association is blocked for writing (timeout), it will left a hole
322 // in the stream sequence number space, so we need to lock the write to avoid concurrent send and decrement
323 // the sequence number in case of failure
324 if s.association.isBlockWrite() {
325 s.writeLock.Lock()
326 }
327 useInterleaving := s.association.useInterleaving
328 chunks, unordered := s.packetize(payload, ppi)
329 n := len(payload)
330 err := s.association.sendPayloadData(s.writeDeadline, chunks)
331 if err != nil { //nolint:nestif
332 s.lock.Lock()
333 s.bufferedAmount -= uint64(n)
334 if useInterleaving {
335 if unordered {
336 s.nextUnorderedMID--
337 } else {
338 s.nextOrderedMID--
339 }
340 } else if !unordered {
341 s.sequenceNumber--
342 }
343 s.lock.Unlock()
344 n = 0
345 }
346 if s.association.isBlockWrite() {
347 s.writeLock.Unlock()
348 }
349
350 return n, err
351 }
352
353 // SetWriteDeadline sets the write deadline in an identical way to net.Conn,
354 // it will only work for blocking writes.
355 func (s *Stream) SetWriteDeadline(deadline time.Time) error {
356 s.writeDeadline.Set(deadline)
357
358 return nil
359 }
360
361 // SetDeadline sets the read and write deadlines in an identical way to net.Conn.
362 func (s *Stream) SetDeadline(t time.Time) error {
363 if err := s.SetReadDeadline(t); err != nil {
364 return err
365 }
366
367 return s.SetWriteDeadline(t)
368 }
369
370 func (s *Stream) packetize(raw []byte, ppi PayloadProtocolIdentifier) ([]*chunkPayloadData, bool) {
371 s.lock.Lock()
372 defer s.lock.Unlock()
373
374 offset := uint32(0)
375 remaining := uint32(len(raw)) //nolint:gosec // G115
376
377 // From draft-ietf-rtcweb-data-protocol-09, section 6:
378 // All Data Channel Establishment Protocol messages MUST be sent using
379 // ordered delivery and reliable transmission.
380 unordered := ppi != PayloadTypeWebRTCDCEP && s.unordered
381
382 useInterleaving := s.association.useInterleaving
383 var mid uint32
384 if useInterleaving {
385 if unordered {
386 mid = s.nextUnorderedMID
387 s.nextUnorderedMID++
388 } else {
389 mid = s.nextOrderedMID
390 s.nextOrderedMID++
391 }
392 }
393
394 var chunks []*chunkPayloadData
395 var head *chunkPayloadData
396 fsn := uint32(0)
397 for remaining != 0 {
398 fragmentSize := min32(s.association.maxPayloadSize, remaining)
399
400 // Copy the userdata since we'll have to store it until acked
401 // and the caller may re-use the buffer in the mean time
402 userData := make([]byte, fragmentSize)
403 copy(userData, raw[offset:offset+fragmentSize])
404
405 chunk := &chunkPayloadData{
406 streamIdentifier: s.streamIdentifier,
407 userData: userData,
408 unordered: unordered,
409 beginningFragment: offset == 0,
410 endingFragment: remaining-fragmentSize == 0,
411 immediateSack: false,
412 payloadType: ppi,
413 streamSequenceNumber: s.sequenceNumber,
414 messageIdentifier: mid,
415 fragmentSequenceNumber: fsn,
416 iData: useInterleaving,
417 head: head,
418 }
419
420 if useInterleaving {
421 chunk.streamSequenceNumber = uint16(mid) //nolint:gosec
422 }
423
424 if head == nil {
425 head = chunk
426 }
427
428 chunks = append(chunks, chunk)
429
430 fsn++
431 remaining -= fragmentSize
432 offset += fragmentSize
433 }
434
435 // RFC 4960 Sec 6.6
436 // Note: When transmitting ordered and unordered data, an endpoint does
437 // not increment its Stream Sequence Number when transmitting a DATA
438 // chunk with U flag set to 1.
439 if !useInterleaving && !unordered {
440 s.sequenceNumber++
441 }
442
443 s.bufferedAmount += uint64(len(raw))
444 s.log.Tracef("[%s] bufferedAmount = %d", s.name, s.bufferedAmount)
445
446 return chunks, unordered
447 }
448
449 // Close closes the write-direction of the stream.
450 // Future calls to Write are not permitted after calling Close.
451 func (s *Stream) Close() error {
452 if sid, resetOutbound := func() (uint16, bool) {
453 s.lock.Lock()
454 defer s.lock.Unlock()
455
456 s.log.Debugf("[%s] Close: state=%s", s.name, s.state.String())
457
458 if s.state == StreamStateOpen {
459 if s.readErr == nil {
460 s.state = StreamStateClosing
461 } else {
462 s.state = StreamStateClosed
463 }
464 s.log.Debugf("[%s] state change: open => %s", s.name, s.state.String())
465
466 return s.streamIdentifier, true
467 }
468
469 return s.streamIdentifier, false
470 }(); resetOutbound {
471 // Reset the outgoing stream
472 // https://tools.ietf.org/html/rfc6525
473 return s.association.sendResetRequest(sid)
474 }
475
476 return nil
477 }
478
479 // BufferedAmount returns the number of bytes of data currently queued to be sent over this stream.
480 func (s *Stream) BufferedAmount() uint64 {
481 s.lock.RLock()
482 defer s.lock.RUnlock()
483
484 return s.bufferedAmount
485 }
486
487 // BufferedAmountLowThreshold returns the number of bytes of buffered outgoing data that is
488 // considered "low." Defaults to 0.
489 func (s *Stream) BufferedAmountLowThreshold() uint64 {
490 s.lock.RLock()
491 defer s.lock.RUnlock()
492
493 return s.bufferedAmountLow
494 }
495
496 // SetBufferedAmountLowThreshold is used to update the threshold.
497 // See BufferedAmountLowThreshold().
498 func (s *Stream) SetBufferedAmountLowThreshold(th uint64) {
499 s.lock.Lock()
500 defer s.lock.Unlock()
501
502 s.bufferedAmountLow = th
503 }
504
505 // OnBufferedAmountLow sets the callback handler which would be called when the number of
506 // bytes of outgoing data buffered is lower than the threshold.
507 func (s *Stream) OnBufferedAmountLow(f func()) {
508 s.lock.Lock()
509 defer s.lock.Unlock()
510
511 s.onBufferedAmountLow = f
512 }
513
514 // This method is called by association's readLoop (go-)routine to notify this stream
515 // of the specified amount of outgoing data has been delivered to the peer.
516 func (s *Stream) onBufferReleased(nBytesReleased int) {
517 if nBytesReleased <= 0 {
518 return
519 }
520
521 s.lock.Lock()
522
523 fromAmount := s.bufferedAmount
524
525 if s.bufferedAmount < uint64(nBytesReleased) {
526 s.bufferedAmount = 0
527 s.log.Errorf("[%s] released buffer size %d should be <= %d",
528 s.name, nBytesReleased, s.bufferedAmount)
529 } else {
530 s.bufferedAmount -= uint64(nBytesReleased)
531 }
532
533 s.log.Tracef("[%s] bufferedAmount = %d", s.name, s.bufferedAmount)
534
535 if s.onBufferedAmountLow != nil && fromAmount > s.bufferedAmountLow && s.bufferedAmount <= s.bufferedAmountLow {
536 f := s.onBufferedAmountLow
537 s.lock.Unlock()
538 f()
539
540 return
541 }
542
543 s.lock.Unlock()
544 }
545
546 func (s *Stream) getNumBytesInReassemblyQueue() int {
547 // No lock is required as it reads the size with atomic load function.
548 return s.reassemblyQueue.getNumBytes()
549 }
550
551 func (s *Stream) onInboundStreamReset() {
552 s.lock.Lock()
553 defer s.lock.Unlock()
554
555 s.log.Debugf("[%s] onInboundStreamReset: state=%s", s.name, s.state.String())
556
557 // No more inbound data to read. Unblock the read with io.EOF.
558 // This should cause DCEP layer (datachannel package) to call Close() which
559 // will reset outgoing stream also.
560
561 // See RFC 8831 section 6.7:
562 // if one side decides to close the data channel, it resets the corresponding
563 // outgoing stream. When the peer sees that an incoming stream was
564 // reset, it also resets its corresponding outgoing stream. Once this
565 // is completed, the data channel is closed.
566
567 s.readErr = io.EOF
568 s.readNotifier.Broadcast()
569
570 if s.state == StreamStateClosing {
571 s.log.Debugf("[%s] state change: closing => closed", s.name)
572 s.state = StreamStateClosed
573 }
574 }
575
576 func (s *Stream) resetOutgoingStreamSequenceNumbers() {
577 s.lock.Lock()
578 defer s.lock.Unlock()
579
580 // RFC 8260 extends RFC 6525 stream reset, so when an outgoing stream is
581 // reset, the SSN and both ordered/unordered MID counters restart at zero.
582 s.sequenceNumber = 0
583 s.nextOrderedMID = 0
584 s.nextUnorderedMID = 0
585 }
586
587 // State return the stream state.
588 func (s *Stream) State() StreamState {
589 s.lock.RLock()
590 defer s.lock.RUnlock()
591
592 return s.state
593 }