package http3
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"maps"
"net/http"
"net/http/httptrace"
"net/textproto"
"time"
"github.com/imroc/req/v3/internal/dump"
"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/quicvarint"
"github.com/quic-go/qpack"
)
const (
MethodGet0RTT = "GET_0RTT"
MethodHead0RTT = "HEAD_0RTT"
)
const (
defaultUserAgent = "quic-go HTTP/3"
defaultMaxResponseHeaderBytes = 10 * 1 << 20
)
type errConnUnusable struct { e error }
func (e *errConnUnusable ) Unwrap () error { return e .e }
func (e *errConnUnusable ) Error () string { return fmt .Sprintf ("http3: conn unusable: %s" , e .e .Error()) }
const max1xxResponses = 5
var defaultQuicConfig = &quic .Config {
MaxIncomingStreams : -1 ,
KeepAlivePeriod : 10 * time .Second ,
}
type ClientConn struct {
*transport .Options
conn *Conn
enableDatagrams bool
additionalSettings map [uint64 ]uint64
maxResponseHeaderBytes int
disableCompression bool
logger *slog .Logger
requestWriter *requestWriter
decoder *qpack .Decoder
}
var _ http .RoundTripper = &ClientConn {}
func newClientConn(
opts *transport .Options ,
conn *quic .Conn ,
enableDatagrams bool ,
additionalSettings map [uint64 ]uint64 ,
maxResponseHeaderBytes int ,
disableCompression bool ,
logger *slog .Logger ,
) *ClientConn {
c := &ClientConn {
Options : opts ,
enableDatagrams : enableDatagrams ,
additionalSettings : additionalSettings ,
disableCompression : disableCompression ,
logger : logger ,
}
if maxResponseHeaderBytes <= 0 {
c .maxResponseHeaderBytes = defaultMaxResponseHeaderBytes
} else {
c .maxResponseHeaderBytes = maxResponseHeaderBytes
}
c .decoder = qpack .NewDecoder ()
c .requestWriter = newRequestWriter ()
c .conn = newConnection (
conn .Context (),
conn ,
c .enableDatagrams ,
false ,
c .logger ,
0 ,
opts ,
)
go func () {
if err := c .setupConn (); err != nil {
if c .logger != nil {
c .logger .Debug ("Setting up connection failed" , "error" , err )
}
c .conn .CloseWithError (quic .ApplicationErrorCode (ErrCodeInternalError ), "" )
}
}()
return c
}
func (c *ClientConn ) handleUnidirectionalStream (str *quic .ReceiveStream ) {
c .conn .handleUnidirectionalStream (str )
}
func (c *ClientConn ) OpenRequestStream (ctx context .Context ) (*RequestStream , error ) {
return c .conn .openRequestStream (ctx , c .requestWriter , nil , c .disableCompression , c .maxResponseHeaderBytes )
}
func (c *ClientConn ) setupConn () error {
str , err := c .conn .OpenUniStream ()
if err != nil {
return err
}
b := make ([]byte , 0 , 64 )
b = quicvarint .Append (b , streamTypeControlStream )
b = (&settingsFrame {
Datagram : c .enableDatagrams ,
Other : c .additionalSettings ,
MaxFieldSectionSize : int64 (c .maxResponseHeaderBytes ),
}).Append (b )
if c .conn .qlogger != nil {
sf := qlog .SettingsFrame {
MaxFieldSectionSize : int64 (c .maxResponseHeaderBytes ),
Other : maps .Clone (c .additionalSettings ),
}
if c .enableDatagrams {
sf .Datagram = pointer (true )
}
c .conn .qlogger .RecordEvent (qlog .FrameCreated {
StreamID : str .StreamID (),
Raw : qlog .RawInfo {Length : len (b )},
Frame : qlog .Frame {Frame : sf },
})
}
_, err = str .Write (b )
return err
}
func (c *ClientConn ) HandleBidirectionalStream (str *quic .Stream ) {
c .conn .CloseWithError (
quic .ApplicationErrorCode (ErrCodeStreamCreationError ),
fmt .Sprintf ("server opened bidirectional stream %d" , str .StreamID ()),
)
}
func (c *ClientConn ) RoundTrip (req *http .Request ) (*http .Response , error ) {
rsp , err := c .roundTrip (req )
if err != nil && req .Context ().Err () != nil {
err = req .Context ().Err ()
}
return rsp , err
}
func (c *ClientConn ) roundTrip (req *http .Request ) (*http .Response , error ) {
switch req .Method {
case MethodGet0RTT :
reqCopy := *req
req = &reqCopy
req .Method = http .MethodGet
case MethodHead0RTT :
reqCopy := *req
req = &reqCopy
req .Method = http .MethodHead
default :
select {
case <- c .conn .HandshakeComplete ():
case <- req .Context ().Done ():
return nil , req .Context ().Err ()
}
}
if isExtendedConnectRequest (req ) {
connCtx := c .conn .Context ()
select {
case <- c .conn .ReceivedSettings ():
case <- connCtx .Done ():
return nil , context .Cause (connCtx )
}
if !c .conn .Settings ().EnableExtendedConnect {
return nil , errors .New ("http3: server didn't enable Extended CONNECT" )
}
}
reqDone := make (chan struct {})
str , err := c .conn .openRequestStream (
req .Context (),
c .requestWriter ,
reqDone ,
c .disableCompression ,
c .maxResponseHeaderBytes ,
)
if err != nil {
return nil , &errConnUnusable {e : err }
}
done := make (chan struct {})
go func () {
defer close (done )
select {
case <- req .Context ().Done ():
str .CancelWrite (quic .StreamErrorCode (ErrCodeRequestCanceled ))
str .CancelRead (quic .StreamErrorCode (ErrCodeRequestCanceled ))
case <- reqDone :
}
}()
rsp , err := c .doRequest (req , str )
if err != nil {
close (reqDone )
<-done
return nil , maybeReplaceError (err )
}
return rsp , maybeReplaceError (err )
}
func (c *ClientConn ) ReceivedSettings () <-chan struct {} {
return c .conn .ReceivedSettings ()
}
func (c *ClientConn ) Settings () *Settings {
return c .conn .Settings ()
}
func (c *ClientConn ) CloseWithError (code ErrCode , msg string ) error {
return c .conn .CloseWithError (quic .ApplicationErrorCode (code ), msg )
}
func (c *ClientConn ) Context () context .Context {
return c .conn .Context ()
}
type cancelingReader struct {
r io .Reader
str *RequestStream
}
func (r *cancelingReader ) Read (b []byte ) (int , error ) {
n , err := r .r .Read (b )
if err != nil && err != io .EOF {
r .str .CancelWrite (quic .StreamErrorCode (ErrCodeRequestCanceled ))
}
return n , err
}
func (c *ClientConn ) sendRequestBody (str *RequestStream , body io .ReadCloser , contentLength int64 , dumps []*dump .Dumper ) error {
defer body .Close ()
buf := make ([]byte , bodyCopyBufferSize )
sr := &cancelingReader {str : str , r : body }
var w io .Writer = str
if len (dumps ) > 0 {
for _ , d := range dumps {
w = io .MultiWriter (w , d .RequestBodyOutput ())
}
}
writeTail := func () {
for _ , d := range dumps {
d .Output ().Write ([]byte ("\r\n\r\n" ))
}
}
if contentLength == -1 {
written , err := io .CopyBuffer (w , sr , buf )
if len (dumps ) > 0 && err == nil && written > 0 {
writeTail ()
}
return err
}
n , err := io .CopyBuffer (str , io .LimitReader (sr , contentLength ), buf )
if err != nil {
return err
} else {
if len (dumps ) > 0 && n > 0 {
writeTail ()
}
}
var extra int64
extra , err = io .CopyBuffer (io .Discard , sr , buf )
n += extra
if n > contentLength {
str .CancelWrite (quic .StreamErrorCode (ErrCodeRequestCanceled ))
return fmt .Errorf ("http: ContentLength=%d with Body length %d" , contentLength , n )
}
return err
}
func (c *ClientConn ) doRequest (req *http .Request , str *RequestStream ) (*http .Response , error ) {
trace := httptrace .ContextClientTrace (req .Context ())
var sendingReqFailed bool
if err := str .sendRequestHeader (req ); err != nil {
traceWroteRequest (trace , err )
if c .logger != nil {
c .logger .Debug ("error writing request" , "error" , err )
}
sendingReqFailed = true
}
if !sendingReqFailed {
if req .Body == nil {
traceWroteRequest (trace , nil )
str .Close ()
} else {
go func () {
contentLength := int64 (-1 )
if req .ContentLength > 0 {
contentLength = req .ContentLength
}
dumps := dump .GetDumpers (req .Context (), c .Dump )
err := c .sendRequestBody (str , req .Body , contentLength , dumps )
traceWroteRequest (trace , err )
if err != nil {
if c .logger != nil {
c .logger .Debug ("error writing request" , "error" , err )
}
}
str .Close ()
}()
}
}
var num1xx int
var res *http .Response
for {
var err error
res , err = str .ReadResponse ()
if err != nil {
return nil , err
}
resCode := res .StatusCode
is1xx := 100 <= resCode && resCode <= 199
is1xxNonTerminal := is1xx && resCode != http .StatusSwitchingProtocols
if is1xxNonTerminal {
num1xx ++
if num1xx > max1xxResponses {
str .CancelRead (quic .StreamErrorCode (ErrCodeExcessiveLoad ))
str .CancelWrite (quic .StreamErrorCode (ErrCodeExcessiveLoad ))
return nil , errors .New ("http3: too many 1xx informational responses" )
}
traceGot1xxResponse (trace , resCode , textproto .MIMEHeader (res .Header ))
if resCode == http .StatusContinue {
traceGot100Continue (trace )
}
continue
}
break
}
connState := c .conn .ConnectionState ().TLS
res .TLS = &connState
res .Request = req
return res , nil
}
func (c *ClientConn ) Conn () *Conn {
return c .conn
}
type RawClientConn struct {
*ClientConn
}
func (c *RawClientConn ) HandleUnidirectionalStream (str *quic .ReceiveStream ) {
c .handleUnidirectionalStream (str )
}
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 .