package http3

import (
	
	
	
	
	
	
	
	
	
	
	

	
	
	
	
	

	
)

const maxQuarterStreamID = 1<<60 - 1

var errGoAway = errors.New("connection in graceful shutdown")

// invalidStreamID is a stream ID that is invalid. The first valid stream ID in QUIC is 0.
const invalidStreamID = quic.StreamID(-1)

// Conn is an HTTP/3 connection.
// It has all methods from the quic.Conn expect for AcceptStream, AcceptUniStream,
// SendDatagram and ReceiveDatagram.
type Conn struct {
	conn *quic.Conn
	*transport.Options

	ctx context.Context

	isServer bool
	logger   *slog.Logger

	enableDatagrams bool

	decoder *qpack.Decoder

	streamMx     sync.Mutex
	streams      map[quic.StreamID]*stateTrackingStream
	lastStreamID quic.StreamID
	maxStreamID  quic.StreamID

	settings         *Settings
	receivedSettings chan struct{}

	idleTimeout time.Duration
	idleTimer   *time.Timer

	qlogger qlogwriter.Recorder

	// Track received unidirectional streams (only one of each type allowed)
	rcvdControlStr      atomic.Bool
	rcvdQPACKEncoderStr atomic.Bool
	rcvdQPACKDecoderStr atomic.Bool
}

func newConnection(
	 context.Context,
	 *quic.Conn,
	 bool,
	 bool,
	 *slog.Logger,
	 time.Duration,
	 *transport.Options,
) *Conn {
	var  qlogwriter.Recorder
	if  := .QlogTrace();  != nil && .SupportsSchemas(qlog.EventSchema) {
		 = .AddProducer()
	}
	 := &Conn{
		ctx:              ,
		conn:             ,
		Options:          ,
		isServer:         ,
		logger:           ,
		idleTimeout:      ,
		enableDatagrams:  ,
		decoder:          qpack.NewDecoder(),
		receivedSettings: make(chan struct{}),
		streams:          make(map[quic.StreamID]*stateTrackingStream),
		maxStreamID:      InvalidStreamID,
		lastStreamID:     InvalidStreamID,
		qlogger:          ,
	}
	if  > 0 {
		.idleTimer = time.AfterFunc(, .onIdleTimer)
	}
	return 
}

func ( *Conn) () (*quic.Stream, error) {
	return .conn.OpenStream()
}

func ( *Conn) ( context.Context) (*quic.Stream, error) {
	return .conn.OpenStreamSync()
}

func ( *Conn) () (*quic.SendStream, error) {
	return .conn.OpenUniStream()
}

func ( *Conn) ( context.Context) (*quic.SendStream, error) {
	return .conn.OpenUniStreamSync()
}

func ( *Conn) () net.Addr {
	return .conn.LocalAddr()
}

func ( *Conn) () net.Addr {
	return .conn.RemoteAddr()
}

func ( *Conn) () <-chan struct{} {
	return .conn.HandshakeComplete()
}

func ( *Conn) () quic.ConnectionState {
	return .conn.ConnectionState()
}

func ( *Conn) () {
	.CloseWithError(quic.ApplicationErrorCode(ErrCodeNoError), "idle timeout")
}

func ( *Conn) ( quic.StreamID) {
	.streamMx.Lock()
	defer .streamMx.Unlock()

	delete(.streams, )
	if .idleTimeout > 0 && len(.streams) == 0 {
		.idleTimer.Reset(.idleTimeout)
	}
	// The server is performing a graceful shutdown.
	// If no more streams are remaining, close the connection.
	if .maxStreamID != invalidStreamID {
		if len(.streams) == 0 {
			.CloseWithError(quic.ApplicationErrorCode(ErrCodeNoError), "")
		}
	}
}

func ( *Conn) (
	 context.Context,
	 *requestWriter,
	 chan<- struct{},
	 bool,
	 int,
) (*RequestStream, error) {
	.streamMx.Lock()
	 := .maxStreamID
	var  quic.StreamID
	if .lastStreamID == invalidStreamID {
		 = 0
	} else {
		 = .lastStreamID + 4
	}
	.streamMx.Unlock()
	// Streams with stream ID equal to or greater than the stream ID carried in the GOAWAY frame
	// will be rejected, see section 5.2 of RFC 9114.
	if  != invalidStreamID &&  >=  {
		return nil, errGoAway
	}

	,  := .OpenStreamSync()
	if  != nil {
		return nil, 
	}
	 := newStateTrackingStream(, , func( []byte) error { return .sendDatagram(.StreamID(), ) })
	.streamMx.Lock()
	.streams[.StreamID()] = 
	.lastStreamID = .StreamID()
	.streamMx.Unlock()
	 := &http.Response{}
	 := httptrace.ContextClientTrace()
	return newRequestStream(
		,
		.Options,
		newStream(, , , func( io.Reader,  *headersFrame) error {
			,  := .decodeTrailers(, .StreamID(), , )
			if  != nil {
				return 
			}
			.Trailer = 
			return nil
		}, .qlogger),
		,
		,
		.decoder,
		,
		,
		,
	), nil
}

func ( *Conn) ( io.Reader,  quic.StreamID,  *headersFrame,  int) (http.Header, error) {
	if .Length > uint64() {
		maybeQlogInvalidHeadersFrame(.qlogger, , .Length)
		return nil, fmt.Errorf("http3: HEADERS frame too large: %d bytes (max: %d)", .Length, )
	}

	 := make([]byte, .Length)
	if ,  := io.ReadFull(, );  != nil {
		return nil, 
	}
	 := .decoder.Decode()
	var  []qpack.HeaderField
	var  *[]qpack.HeaderField
	if .qlogger != nil {
		 = make([]qpack.HeaderField, 0, 16)
		 = &
	}
	,  := parseTrailers(, , )
	if  != nil {
		maybeQlogInvalidHeadersFrame(.qlogger, , .Length)
		return nil, 
	}
	if .qlogger != nil {
		qlogParsedHeadersFrame(.qlogger, , , )
	}
	return , nil
}

func ( *Conn) ( quic.ApplicationErrorCode,  string) error {
	if .idleTimer != nil {
		.idleTimer.Stop()
	}
	return .conn.CloseWithError(, )
}

func ( *Conn) ( *quic.ReceiveStream) {
	,  := quicvarint.Read(quicvarint.NewReader())
	if  != nil {
		if .logger != nil {
			.logger.Debug("reading stream type on stream failed", "stream ID", .StreamID(), "error", )
		}
		return
	}
	// We're only interested in the control stream here.
	switch  {
	case streamTypeControlStream:
	case streamTypeQPACKEncoderStream:
		if  := .rcvdQPACKEncoderStr.CompareAndSwap(false, true); ! {
			.CloseWithError(quic.ApplicationErrorCode(ErrCodeStreamCreationError), "duplicate QPACK encoder stream")
		}
		// Our QPACK implementation doesn't use the dynamic table yet.
		return
	case streamTypeQPACKDecoderStream:
		if  := .rcvdQPACKDecoderStr.CompareAndSwap(false, true); ! {
			.CloseWithError(quic.ApplicationErrorCode(ErrCodeStreamCreationError), "duplicate QPACK decoder stream")
		}
		// Our QPACK implementation doesn't use the dynamic table yet.
		return
	case streamTypePushStream:
		if .isServer {
			// only the server can push
			.CloseWithError(quic.ApplicationErrorCode(ErrCodeStreamCreationError), "")
		} else {
			// we never increased the Push ID, so we don't expect any push streams
			.CloseWithError(quic.ApplicationErrorCode(ErrCodeIDError), "")
		}
		return
	default:
		.CancelRead(quic.StreamErrorCode(ErrCodeStreamCreationError))
		return
	}
	// Only a single control stream is allowed.
	if  := .rcvdControlStr.CompareAndSwap(false, true); ! {
		.conn.CloseWithError(quic.ApplicationErrorCode(ErrCodeStreamCreationError), "duplicate control stream")
		return
	}
	.handleControlStream()
}

func ( *Conn) ( *quic.ReceiveStream) {
	 := &frameParser{closeConn: .conn.CloseWithError, r: , streamID: .StreamID()}
	,  := .ParseNext(.qlogger)
	if  != nil {
		var  *quic.StreamError
		if  == io.EOF || errors.As(, &) {
			.conn.CloseWithError(quic.ApplicationErrorCode(ErrCodeClosedCriticalStream), "")
			return
		}
		.conn.CloseWithError(quic.ApplicationErrorCode(ErrCodeFrameError), "")
		return
	}
	,  := .(*settingsFrame)
	if ! {
		.conn.CloseWithError(quic.ApplicationErrorCode(ErrCodeMissingSettings), "")
		return
	}
	.settings = &Settings{
		EnableDatagrams:       .Datagram,
		EnableExtendedConnect: .ExtendedConnect,
		Other:                 .Other,
	}
	close(.receivedSettings)
	if .Datagram {
		// If datagram support was enabled on our side as well as on the server side,
		// we can expect it to have been negotiated both on the transport and on the HTTP/3 layer.
		// Note: ConnectionState() will block until the handshake is complete (relevant when using 0-RTT).
		if .enableDatagrams && !.ConnectionState().SupportsDatagrams.Remote {
			.CloseWithError(quic.ApplicationErrorCode(ErrCodeSettingsError), "missing QUIC Datagram support")
			return
		}
		go func() {
			if  := .receiveDatagrams();  != nil {
				if .logger != nil {
					.logger.Debug("receiving datagrams failed", "error", )
				}
			}
		}()
	}

	// we don't support server push, hence we don't expect any GOAWAY frames from the client
	if .isServer {
		return
	}

	for {
		,  := .ParseNext(.qlogger)
		if  != nil {
			var  *quic.StreamError
			if  == io.EOF || errors.As(, &) {
				.conn.CloseWithError(quic.ApplicationErrorCode(ErrCodeClosedCriticalStream), "")
				return
			}
			.conn.CloseWithError(quic.ApplicationErrorCode(ErrCodeFrameError), "")
			return
		}
		// GOAWAY is the only frame allowed at this point:
		// * unexpected frames are ignored by the frame parser
		// * we don't support any extension that might add support for more frames
		,  := .(*goAwayFrame)
		if ! {
			.conn.CloseWithError(quic.ApplicationErrorCode(ErrCodeFrameUnexpected), "")
			return
		}
		if .StreamID%4 != 0 { // client-initiated, bidirectional streams
			.conn.CloseWithError(quic.ApplicationErrorCode(ErrCodeIDError), "")
			return
		}
		.streamMx.Lock()
		if .maxStreamID != invalidStreamID && .StreamID > .maxStreamID {
			.streamMx.Unlock()
			.conn.CloseWithError(quic.ApplicationErrorCode(ErrCodeIDError), "")
			return
		}
		.maxStreamID = .StreamID
		 := len(.streams) > 0
		.streamMx.Unlock()

		// immediately close the connection if there are currently no active requests
		if ! {
			.CloseWithError(quic.ApplicationErrorCode(ErrCodeNoError), "")
			return
		}
	}
}

func ( *Conn) ( quic.StreamID,  []byte) error {
	// TODO: this creates a lot of garbage and an additional copy
	 := make([]byte, 0, len()+8)
	 := uint64( / 4)
	 = quicvarint.Append(, uint64(/4))
	 = append(, ...)
	if .qlogger != nil {
		.qlogger.RecordEvent(qlog.DatagramCreated{
			QuarterStreamID: ,
			Raw: qlog.RawInfo{
				Length:        len(),
				PayloadLength: len(),
			},
		})
	}
	return .conn.SendDatagram()
}

func ( *Conn) () error {
	for {
		,  := .conn.ReceiveDatagram(context.Background())
		if  != nil {
			return 
		}
		, ,  := quicvarint.Parse()
		if  != nil {
			.CloseWithError(quic.ApplicationErrorCode(ErrCodeDatagramError), "")
			return fmt.Errorf("could not read quarter stream id: %w", )
		}
		if .qlogger != nil {
		.qlogger.RecordEvent(qlog.DatagramParsed{
			QuarterStreamID: ,
				Raw: qlog.RawInfo{
					Length:        len(),
					PayloadLength: len() - ,
				},
			})
		}
		if  > maxQuarterStreamID {
			.CloseWithError(quic.ApplicationErrorCode(ErrCodeDatagramError), "")
			return fmt.Errorf("invalid quarter stream id: %w", )
		}
		 := quic.StreamID(4 * )
		.streamMx.Lock()
		,  := .streams[]
		.streamMx.Unlock()
		if ! {
			continue
		}
		.enqueueDatagram([:])
	}
}

// ReceivedSettings returns a channel that is closed once the peer's SETTINGS frame was received.
// Settings can be obtained from the Settings method after the channel was closed.
func ( *Conn) () <-chan struct{} { return .receivedSettings }

// Settings returns the settings received on this connection.
// It is only valid to call this function after the channel returned by ReceivedSettings was closed.
func ( *Conn) () *Settings { return .settings }

// Context returns the context of the underlying QUIC connection.
func ( *Conn) () context.Context { return .ctx }