package http3
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"net/http/httptrace"
"sync"
"sync/atomic"
"time"
"github.com/imroc/req/v3/internal/transport"
"github.com/quic-go/quic-go"
"github.com/quic-go/quic-go/http3/qlog"
"github.com/quic-go/quic-go/qlogwriter"
"github.com/quic-go/quic-go/quicvarint"
"github.com/quic-go/qpack"
)
const maxQuarterStreamID = 1 <<60 - 1
var errGoAway = errors .New ("connection in graceful shutdown" )
const invalidStreamID = quic .StreamID (-1 )
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
rcvdControlStr atomic .Bool
rcvdQPACKEncoderStr atomic .Bool
rcvdQPACKDecoderStr atomic .Bool
}
func newConnection(
ctx context .Context ,
quicConn *quic .Conn ,
enableDatagrams bool ,
isServer bool ,
logger *slog .Logger ,
idleTimeout time .Duration ,
options *transport .Options ,
) *Conn {
var qlogger qlogwriter .Recorder
if qlogTrace := quicConn .QlogTrace (); qlogTrace != nil && qlogTrace .SupportsSchemas (qlog .EventSchema ) {
qlogger = qlogTrace .AddProducer ()
}
c := &Conn {
ctx : ctx ,
conn : quicConn ,
Options : options ,
isServer : isServer ,
logger : logger ,
idleTimeout : idleTimeout ,
enableDatagrams : enableDatagrams ,
decoder : qpack .NewDecoder (),
receivedSettings : make (chan struct {}),
streams : make (map [quic .StreamID ]*stateTrackingStream ),
maxStreamID : InvalidStreamID ,
lastStreamID : InvalidStreamID ,
qlogger : qlogger ,
}
if idleTimeout > 0 {
c .idleTimer = time .AfterFunc (idleTimeout , c .onIdleTimer )
}
return c
}
func (c *Conn ) OpenStream () (*quic .Stream , error ) {
return c .conn .OpenStream ()
}
func (c *Conn ) OpenStreamSync (ctx context .Context ) (*quic .Stream , error ) {
return c .conn .OpenStreamSync (ctx )
}
func (c *Conn ) OpenUniStream () (*quic .SendStream , error ) {
return c .conn .OpenUniStream ()
}
func (c *Conn ) OpenUniStreamSync (ctx context .Context ) (*quic .SendStream , error ) {
return c .conn .OpenUniStreamSync (ctx )
}
func (c *Conn ) LocalAddr () net .Addr {
return c .conn .LocalAddr ()
}
func (c *Conn ) RemoteAddr () net .Addr {
return c .conn .RemoteAddr ()
}
func (c *Conn ) HandshakeComplete () <-chan struct {} {
return c .conn .HandshakeComplete ()
}
func (c *Conn ) ConnectionState () quic .ConnectionState {
return c .conn .ConnectionState ()
}
func (c *Conn ) onIdleTimer () {
c .CloseWithError (quic .ApplicationErrorCode (ErrCodeNoError ), "idle timeout" )
}
func (c *Conn ) clearStream (id quic .StreamID ) {
c .streamMx .Lock ()
defer c .streamMx .Unlock ()
delete (c .streams , id )
if c .idleTimeout > 0 && len (c .streams ) == 0 {
c .idleTimer .Reset (c .idleTimeout )
}
if c .maxStreamID != invalidStreamID {
if len (c .streams ) == 0 {
c .CloseWithError (quic .ApplicationErrorCode (ErrCodeNoError ), "" )
}
}
}
func (c *Conn ) openRequestStream (
ctx context .Context ,
requestWriter *requestWriter ,
reqDone chan <- struct {},
disableCompression bool ,
maxHeaderBytes int ,
) (*RequestStream , error ) {
c .streamMx .Lock ()
maxStreamID := c .maxStreamID
var nextStreamID quic .StreamID
if c .lastStreamID == invalidStreamID {
nextStreamID = 0
} else {
nextStreamID = c .lastStreamID + 4
}
c .streamMx .Unlock ()
if maxStreamID != invalidStreamID && nextStreamID >= maxStreamID {
return nil , errGoAway
}
str , err := c .OpenStreamSync (ctx )
if err != nil {
return nil , err
}
hstr := newStateTrackingStream (str , c , func (b []byte ) error { return c .sendDatagram (str .StreamID (), b ) })
c .streamMx .Lock ()
c .streams [str .StreamID ()] = hstr
c .lastStreamID = str .StreamID ()
c .streamMx .Unlock ()
rsp := &http .Response {}
trace := httptrace .ContextClientTrace (ctx )
return newRequestStream (
ctx ,
c .Options ,
newStream (hstr , c , trace , func (r io .Reader , hf *headersFrame ) error {
hdr , err := c .decodeTrailers (r , str .StreamID (), hf , maxHeaderBytes )
if err != nil {
return err
}
rsp .Trailer = hdr
return nil
}, c .qlogger ),
requestWriter ,
reqDone ,
c .decoder ,
disableCompression ,
maxHeaderBytes ,
rsp ,
), nil
}
func (c *Conn ) decodeTrailers (r io .Reader , streamID quic .StreamID , hf *headersFrame , maxHeaderBytes int ) (http .Header , error ) {
if hf .Length > uint64 (maxHeaderBytes ) {
maybeQlogInvalidHeadersFrame (c .qlogger , streamID , hf .Length )
return nil , fmt .Errorf ("http3: HEADERS frame too large: %d bytes (max: %d)" , hf .Length , maxHeaderBytes )
}
b := make ([]byte , hf .Length )
if _ , err := io .ReadFull (r , b ); err != nil {
return nil , err
}
decodeFn := c .decoder .Decode (b )
var fields []qpack .HeaderField
var headerFields *[]qpack .HeaderField
if c .qlogger != nil {
fields = make ([]qpack .HeaderField , 0 , 16 )
headerFields = &fields
}
trailers , err := parseTrailers (decodeFn , maxHeaderBytes , headerFields )
if err != nil {
maybeQlogInvalidHeadersFrame (c .qlogger , streamID , hf .Length )
return nil , err
}
if c .qlogger != nil {
qlogParsedHeadersFrame (c .qlogger , streamID , hf , fields )
}
return trailers , nil
}
func (c *Conn ) CloseWithError (code quic .ApplicationErrorCode , msg string ) error {
if c .idleTimer != nil {
c .idleTimer .Stop ()
}
return c .conn .CloseWithError (code , msg )
}
func (c *Conn ) handleUnidirectionalStream (str *quic .ReceiveStream ) {
streamType , err := quicvarint .Read (quicvarint .NewReader (str ))
if err != nil {
if c .logger != nil {
c .logger .Debug ("reading stream type on stream failed" , "stream ID" , str .StreamID (), "error" , err )
}
return
}
switch streamType {
case streamTypeControlStream :
case streamTypeQPACKEncoderStream :
if isFirst := c .rcvdQPACKEncoderStr .CompareAndSwap (false , true ); !isFirst {
c .CloseWithError (quic .ApplicationErrorCode (ErrCodeStreamCreationError ), "duplicate QPACK encoder stream" )
}
return
case streamTypeQPACKDecoderStream :
if isFirst := c .rcvdQPACKDecoderStr .CompareAndSwap (false , true ); !isFirst {
c .CloseWithError (quic .ApplicationErrorCode (ErrCodeStreamCreationError ), "duplicate QPACK decoder stream" )
}
return
case streamTypePushStream :
if c .isServer {
c .CloseWithError (quic .ApplicationErrorCode (ErrCodeStreamCreationError ), "" )
} else {
c .CloseWithError (quic .ApplicationErrorCode (ErrCodeIDError ), "" )
}
return
default :
str .CancelRead (quic .StreamErrorCode (ErrCodeStreamCreationError ))
return
}
if isFirstControlStr := c .rcvdControlStr .CompareAndSwap (false , true ); !isFirstControlStr {
c .conn .CloseWithError (quic .ApplicationErrorCode (ErrCodeStreamCreationError ), "duplicate control stream" )
return
}
c .handleControlStream (str )
}
func (c *Conn ) handleControlStream (str *quic .ReceiveStream ) {
fp := &frameParser {closeConn : c .conn .CloseWithError , r : str , streamID : str .StreamID ()}
f , err := fp .ParseNext (c .qlogger )
if err != nil {
var serr *quic .StreamError
if err == io .EOF || errors .As (err , &serr ) {
c .conn .CloseWithError (quic .ApplicationErrorCode (ErrCodeClosedCriticalStream ), "" )
return
}
c .conn .CloseWithError (quic .ApplicationErrorCode (ErrCodeFrameError ), "" )
return
}
sf , ok := f .(*settingsFrame )
if !ok {
c .conn .CloseWithError (quic .ApplicationErrorCode (ErrCodeMissingSettings ), "" )
return
}
c .settings = &Settings {
EnableDatagrams : sf .Datagram ,
EnableExtendedConnect : sf .ExtendedConnect ,
Other : sf .Other ,
}
close (c .receivedSettings )
if sf .Datagram {
if c .enableDatagrams && !c .ConnectionState ().SupportsDatagrams .Remote {
c .CloseWithError (quic .ApplicationErrorCode (ErrCodeSettingsError ), "missing QUIC Datagram support" )
return
}
go func () {
if err := c .receiveDatagrams (); err != nil {
if c .logger != nil {
c .logger .Debug ("receiving datagrams failed" , "error" , err )
}
}
}()
}
if c .isServer {
return
}
for {
f , err := fp .ParseNext (c .qlogger )
if err != nil {
var serr *quic .StreamError
if err == io .EOF || errors .As (err , &serr ) {
c .conn .CloseWithError (quic .ApplicationErrorCode (ErrCodeClosedCriticalStream ), "" )
return
}
c .conn .CloseWithError (quic .ApplicationErrorCode (ErrCodeFrameError ), "" )
return
}
goaway , ok := f .(*goAwayFrame )
if !ok {
c .conn .CloseWithError (quic .ApplicationErrorCode (ErrCodeFrameUnexpected ), "" )
return
}
if goaway .StreamID %4 != 0 {
c .conn .CloseWithError (quic .ApplicationErrorCode (ErrCodeIDError ), "" )
return
}
c .streamMx .Lock ()
if c .maxStreamID != invalidStreamID && goaway .StreamID > c .maxStreamID {
c .streamMx .Unlock ()
c .conn .CloseWithError (quic .ApplicationErrorCode (ErrCodeIDError ), "" )
return
}
c .maxStreamID = goaway .StreamID
hasActiveStreams := len (c .streams ) > 0
c .streamMx .Unlock ()
if !hasActiveStreams {
c .CloseWithError (quic .ApplicationErrorCode (ErrCodeNoError ), "" )
return
}
}
}
func (c *Conn ) sendDatagram (streamID quic .StreamID , b []byte ) error {
data := make ([]byte , 0 , len (b )+8 )
quarterStreamID := uint64 (streamID / 4 )
data = quicvarint .Append (data , uint64 (streamID /4 ))
data = append (data , b ...)
if c .qlogger != nil {
c .qlogger .RecordEvent (qlog .DatagramCreated {
QuarterStreamID : quarterStreamID ,
Raw : qlog .RawInfo {
Length : len (data ),
PayloadLength : len (b ),
},
})
}
return c .conn .SendDatagram (data )
}
func (c *Conn ) receiveDatagrams () error {
for {
b , err := c .conn .ReceiveDatagram (context .Background ())
if err != nil {
return err
}
quarterStreamID , n , err := quicvarint .Parse (b )
if err != nil {
c .CloseWithError (quic .ApplicationErrorCode (ErrCodeDatagramError ), "" )
return fmt .Errorf ("could not read quarter stream id: %w" , err )
}
if c .qlogger != nil {
c .qlogger .RecordEvent (qlog .DatagramParsed {
QuarterStreamID : quarterStreamID ,
Raw : qlog .RawInfo {
Length : len (b ),
PayloadLength : len (b ) - n ,
},
})
}
if quarterStreamID > maxQuarterStreamID {
c .CloseWithError (quic .ApplicationErrorCode (ErrCodeDatagramError ), "" )
return fmt .Errorf ("invalid quarter stream id: %w" , err )
}
streamID := quic .StreamID (4 * quarterStreamID )
c .streamMx .Lock ()
dg , ok := c .streams [streamID ]
c .streamMx .Unlock ()
if !ok {
continue
}
dg .enqueueDatagram (b [n :])
}
}
func (c *Conn ) ReceivedSettings () <-chan struct {} { return c .receivedSettings }
func (c *Conn ) Settings () *Settings { return c .settings }
func (c *Conn ) Context () context .Context { return c .ctx }
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .