github.com/sagernet/quic-go@v0.43.1-beta.1/streams_map_incoming.go (about)

     1  package quic
     2  
     3  import (
     4  	"context"
     5  	"sync"
     6  
     7  	"github.com/sagernet/quic-go/internal/protocol"
     8  	"github.com/sagernet/quic-go/internal/wire"
     9  )
    10  
    11  type incomingStream interface {
    12  	closeForShutdown(error)
    13  }
    14  
    15  // When a stream is deleted before it was accepted, we can't delete it from the map immediately.
    16  // We need to wait until the application accepts it, and delete it then.
    17  type incomingStreamEntry[T incomingStream] struct {
    18  	stream       T
    19  	shouldDelete bool
    20  }
    21  
    22  type incomingStreamsMap[T incomingStream] struct {
    23  	mutex         sync.RWMutex
    24  	newStreamChan chan struct{}
    25  
    26  	streamType protocol.StreamType
    27  	streams    map[protocol.StreamNum]incomingStreamEntry[T]
    28  
    29  	nextStreamToAccept protocol.StreamNum // the next stream that will be returned by AcceptStream()
    30  	nextStreamToOpen   protocol.StreamNum // the highest stream that the peer opened
    31  	maxStream          protocol.StreamNum // the highest stream that the peer is allowed to open
    32  	maxNumStreams      uint64             // maximum number of streams
    33  
    34  	newStream        func(protocol.StreamNum) T
    35  	queueMaxStreamID func(*wire.MaxStreamsFrame)
    36  
    37  	closeErr error
    38  }
    39  
    40  func newIncomingStreamsMap[T incomingStream](
    41  	streamType protocol.StreamType,
    42  	newStream func(protocol.StreamNum) T,
    43  	maxStreams uint64,
    44  	queueControlFrame func(wire.Frame),
    45  ) *incomingStreamsMap[T] {
    46  	return &incomingStreamsMap[T]{
    47  		newStreamChan:      make(chan struct{}, 1),
    48  		streamType:         streamType,
    49  		streams:            make(map[protocol.StreamNum]incomingStreamEntry[T]),
    50  		maxStream:          protocol.StreamNum(maxStreams),
    51  		maxNumStreams:      maxStreams,
    52  		newStream:          newStream,
    53  		nextStreamToOpen:   1,
    54  		nextStreamToAccept: 1,
    55  		queueMaxStreamID:   func(f *wire.MaxStreamsFrame) { queueControlFrame(f) },
    56  	}
    57  }
    58  
    59  func (m *incomingStreamsMap[T]) AcceptStream(ctx context.Context) (T, error) {
    60  	// drain the newStreamChan, so we don't check the map twice if the stream doesn't exist
    61  	select {
    62  	case <-m.newStreamChan:
    63  	default:
    64  	}
    65  
    66  	m.mutex.Lock()
    67  
    68  	var num protocol.StreamNum
    69  	var entry incomingStreamEntry[T]
    70  	for {
    71  		num = m.nextStreamToAccept
    72  		if m.closeErr != nil {
    73  			m.mutex.Unlock()
    74  			return *new(T), m.closeErr
    75  		}
    76  		var ok bool
    77  		entry, ok = m.streams[num]
    78  		if ok {
    79  			break
    80  		}
    81  		m.mutex.Unlock()
    82  		select {
    83  		case <-ctx.Done():
    84  			return *new(T), ctx.Err()
    85  		case <-m.newStreamChan:
    86  		}
    87  		m.mutex.Lock()
    88  	}
    89  	m.nextStreamToAccept++
    90  	// If this stream was completed before being accepted, we can delete it now.
    91  	if entry.shouldDelete {
    92  		if err := m.deleteStream(num); err != nil {
    93  			m.mutex.Unlock()
    94  			return *new(T), err
    95  		}
    96  	}
    97  	m.mutex.Unlock()
    98  	return entry.stream, nil
    99  }
   100  
   101  func (m *incomingStreamsMap[T]) GetOrOpenStream(num protocol.StreamNum) (T, error) {
   102  	m.mutex.RLock()
   103  	if num > m.maxStream {
   104  		m.mutex.RUnlock()
   105  		return *new(T), streamError{
   106  			message: "peer tried to open stream %d (current limit: %d)",
   107  			nums:    []protocol.StreamNum{num, m.maxStream},
   108  		}
   109  	}
   110  	// if the num is smaller than the highest we accepted
   111  	// * this stream exists in the map, and we can return it, or
   112  	// * this stream was already closed, then we can return the nil
   113  	if num < m.nextStreamToOpen {
   114  		var s T
   115  		// If the stream was already queued for deletion, and is just waiting to be accepted, don't return it.
   116  		if entry, ok := m.streams[num]; ok && !entry.shouldDelete {
   117  			s = entry.stream
   118  		}
   119  		m.mutex.RUnlock()
   120  		return s, nil
   121  	}
   122  	m.mutex.RUnlock()
   123  
   124  	m.mutex.Lock()
   125  	// no need to check the two error conditions from above again
   126  	// * maxStream can only increase, so if the id was valid before, it definitely is valid now
   127  	// * highestStream is only modified by this function
   128  	for newNum := m.nextStreamToOpen; newNum <= num; newNum++ {
   129  		m.streams[newNum] = incomingStreamEntry[T]{stream: m.newStream(newNum)}
   130  		select {
   131  		case m.newStreamChan <- struct{}{}:
   132  		default:
   133  		}
   134  	}
   135  	m.nextStreamToOpen = num + 1
   136  	entry := m.streams[num]
   137  	m.mutex.Unlock()
   138  	return entry.stream, nil
   139  }
   140  
   141  func (m *incomingStreamsMap[T]) DeleteStream(num protocol.StreamNum) error {
   142  	m.mutex.Lock()
   143  	defer m.mutex.Unlock()
   144  
   145  	return m.deleteStream(num)
   146  }
   147  
   148  func (m *incomingStreamsMap[T]) deleteStream(num protocol.StreamNum) error {
   149  	if _, ok := m.streams[num]; !ok {
   150  		return streamError{
   151  			message: "tried to delete unknown incoming stream %d",
   152  			nums:    []protocol.StreamNum{num},
   153  		}
   154  	}
   155  
   156  	// Don't delete this stream yet, if it was not yet accepted.
   157  	// Just save it to streamsToDelete map, to make sure it is deleted as soon as it gets accepted.
   158  	if num >= m.nextStreamToAccept {
   159  		entry, ok := m.streams[num]
   160  		if ok && entry.shouldDelete {
   161  			return streamError{
   162  				message: "tried to delete incoming stream %d multiple times",
   163  				nums:    []protocol.StreamNum{num},
   164  			}
   165  		}
   166  		entry.shouldDelete = true
   167  		m.streams[num] = entry // can't assign to struct in map, so we need to reassign
   168  		return nil
   169  	}
   170  
   171  	delete(m.streams, num)
   172  	// queue a MAX_STREAM_ID frame, giving the peer the option to open a new stream
   173  	if m.maxNumStreams > uint64(len(m.streams)) {
   174  		maxStream := m.nextStreamToOpen + protocol.StreamNum(m.maxNumStreams-uint64(len(m.streams))) - 1
   175  		// Never send a value larger than protocol.MaxStreamCount.
   176  		if maxStream <= protocol.MaxStreamCount {
   177  			m.maxStream = maxStream
   178  			m.queueMaxStreamID(&wire.MaxStreamsFrame{
   179  				Type:         m.streamType,
   180  				MaxStreamNum: m.maxStream,
   181  			})
   182  		}
   183  	}
   184  	return nil
   185  }
   186  
   187  func (m *incomingStreamsMap[T]) CloseWithError(err error) {
   188  	m.mutex.Lock()
   189  	m.closeErr = err
   190  	for _, entry := range m.streams {
   191  		entry.stream.closeForShutdown(err)
   192  	}
   193  	m.mutex.Unlock()
   194  	close(m.newStreamChan)
   195  }