github.com/TugasAkhir-QUIC/quic-go@v0.0.2-0.20240215011318-d20e25a9054c/http3/client.go (about)

     1  package http3
     2  
     3  import (
     4  	"context"
     5  	"crypto/tls"
     6  	"errors"
     7  	"fmt"
     8  	"io"
     9  	"net"
    10  	"net/http"
    11  	"strconv"
    12  	"sync"
    13  	"sync/atomic"
    14  	"time"
    15  
    16  	"github.com/TugasAkhir-QUIC/quic-go"
    17  	"github.com/TugasAkhir-QUIC/quic-go/internal/protocol"
    18  	"github.com/TugasAkhir-QUIC/quic-go/internal/utils"
    19  	"github.com/TugasAkhir-QUIC/quic-go/quicvarint"
    20  
    21  	"github.com/quic-go/qpack"
    22  )
    23  
    24  // MethodGet0RTT allows a GET request to be sent using 0-RTT.
    25  // Note that 0-RTT data doesn't provide replay protection.
    26  const MethodGet0RTT = "GET_0RTT"
    27  
    28  const (
    29  	defaultUserAgent              = "quic-go HTTP/3"
    30  	defaultMaxResponseHeaderBytes = 10 * 1 << 20 // 10 MB
    31  )
    32  
    33  var defaultQuicConfig = &quic.Config{
    34  	MaxIncomingStreams: -1, // don't allow the server to create bidirectional streams
    35  	KeepAlivePeriod:    10 * time.Second,
    36  }
    37  
    38  type dialFunc func(ctx context.Context, addr string, tlsCfg *tls.Config, cfg *quic.Config) (quic.EarlyConnection, error)
    39  
    40  var dialAddr dialFunc = quic.DialAddrEarly
    41  
    42  type roundTripperOpts struct {
    43  	DisableCompression bool
    44  	EnableDatagram     bool
    45  	MaxHeaderBytes     int64
    46  	AdditionalSettings map[uint64]uint64
    47  	StreamHijacker     func(FrameType, quic.Connection, quic.Stream, error) (hijacked bool, err error)
    48  	UniStreamHijacker  func(StreamType, quic.Connection, quic.ReceiveStream, error) (hijacked bool)
    49  }
    50  
    51  // client is a HTTP3 client doing requests
    52  type client struct {
    53  	tlsConf *tls.Config
    54  	config  *quic.Config
    55  	opts    *roundTripperOpts
    56  
    57  	dialOnce     sync.Once
    58  	dialer       dialFunc
    59  	handshakeErr error
    60  
    61  	requestWriter *requestWriter
    62  
    63  	decoder *qpack.Decoder
    64  
    65  	hostname string
    66  	conn     atomic.Pointer[quic.EarlyConnection]
    67  
    68  	logger utils.Logger
    69  }
    70  
    71  var _ roundTripCloser = &client{}
    72  
    73  func newClient(hostname string, tlsConf *tls.Config, opts *roundTripperOpts, conf *quic.Config, dialer dialFunc) (roundTripCloser, error) {
    74  	if conf == nil {
    75  		conf = defaultQuicConfig.Clone()
    76  	}
    77  	if len(conf.Versions) == 0 {
    78  		conf = conf.Clone()
    79  		conf.Versions = []quic.Version{protocol.SupportedVersions[0]}
    80  	}
    81  	if len(conf.Versions) != 1 {
    82  		return nil, errors.New("can only use a single QUIC version for dialing a HTTP/3 connection")
    83  	}
    84  	if conf.MaxIncomingStreams == 0 {
    85  		conf.MaxIncomingStreams = -1 // don't allow any bidirectional streams
    86  	}
    87  	conf.EnableDatagrams = opts.EnableDatagram
    88  	logger := utils.DefaultLogger.WithPrefix("h3 client")
    89  
    90  	if tlsConf == nil {
    91  		tlsConf = &tls.Config{}
    92  	} else {
    93  		tlsConf = tlsConf.Clone()
    94  	}
    95  	if tlsConf.ServerName == "" {
    96  		sni, _, err := net.SplitHostPort(hostname)
    97  		if err != nil {
    98  			// It's ok if net.SplitHostPort returns an error - it could be a hostname/IP address without a port.
    99  			sni = hostname
   100  		}
   101  		tlsConf.ServerName = sni
   102  	}
   103  	// Replace existing ALPNs by H3
   104  	tlsConf.NextProtos = []string{versionToALPN(conf.Versions[0])}
   105  
   106  	return &client{
   107  		hostname:      authorityAddr("https", hostname),
   108  		tlsConf:       tlsConf,
   109  		requestWriter: newRequestWriter(logger),
   110  		decoder:       qpack.NewDecoder(func(hf qpack.HeaderField) {}),
   111  		config:        conf,
   112  		opts:          opts,
   113  		dialer:        dialer,
   114  		logger:        logger,
   115  	}, nil
   116  }
   117  
   118  func (c *client) dial(ctx context.Context) error {
   119  	var err error
   120  	var conn quic.EarlyConnection
   121  	if c.dialer != nil {
   122  		conn, err = c.dialer(ctx, c.hostname, c.tlsConf, c.config)
   123  	} else {
   124  		conn, err = dialAddr(ctx, c.hostname, c.tlsConf, c.config)
   125  	}
   126  	if err != nil {
   127  		return err
   128  	}
   129  	c.conn.Store(&conn)
   130  
   131  	// send the SETTINGs frame, using 0-RTT data, if possible
   132  	go func() {
   133  		if err := c.setupConn(conn); err != nil {
   134  			c.logger.Debugf("Setting up connection failed: %s", err)
   135  			conn.CloseWithError(quic.ApplicationErrorCode(ErrCodeInternalError), "")
   136  		}
   137  	}()
   138  
   139  	if c.opts.StreamHijacker != nil {
   140  		go c.handleBidirectionalStreams(conn)
   141  	}
   142  	go c.handleUnidirectionalStreams(conn)
   143  	return nil
   144  }
   145  
   146  func (c *client) setupConn(conn quic.EarlyConnection) error {
   147  	// open the control stream
   148  	str, err := conn.OpenUniStream()
   149  	if err != nil {
   150  		return err
   151  	}
   152  	b := make([]byte, 0, 64)
   153  	b = quicvarint.Append(b, streamTypeControlStream)
   154  	// send the SETTINGS frame
   155  	b = (&settingsFrame{Datagram: c.opts.EnableDatagram, Other: c.opts.AdditionalSettings}).Append(b)
   156  	_, err = str.Write(b)
   157  	return err
   158  }
   159  
   160  func (c *client) handleBidirectionalStreams(conn quic.EarlyConnection) {
   161  	for {
   162  		str, err := conn.AcceptStream(context.Background())
   163  		if err != nil {
   164  			c.logger.Debugf("accepting bidirectional stream failed: %s", err)
   165  			return
   166  		}
   167  		go func(str quic.Stream) {
   168  			_, err := parseNextFrame(str, func(ft FrameType, e error) (processed bool, err error) {
   169  				return c.opts.StreamHijacker(ft, conn, str, e)
   170  			})
   171  			if err == errHijacked {
   172  				return
   173  			}
   174  			if err != nil {
   175  				c.logger.Debugf("error handling stream: %s", err)
   176  			}
   177  			conn.CloseWithError(quic.ApplicationErrorCode(ErrCodeFrameUnexpected), "received HTTP/3 frame on bidirectional stream")
   178  		}(str)
   179  	}
   180  }
   181  
   182  func (c *client) handleUnidirectionalStreams(conn quic.EarlyConnection) {
   183  	for {
   184  		str, err := conn.AcceptUniStream(context.Background())
   185  		if err != nil {
   186  			c.logger.Debugf("accepting unidirectional stream failed: %s", err)
   187  			return
   188  		}
   189  
   190  		go func(str quic.ReceiveStream) {
   191  			streamType, err := quicvarint.Read(quicvarint.NewReader(str))
   192  			if err != nil {
   193  				if c.opts.UniStreamHijacker != nil && c.opts.UniStreamHijacker(StreamType(streamType), conn, str, err) {
   194  					return
   195  				}
   196  				c.logger.Debugf("reading stream type on stream %d failed: %s", str.StreamID(), err)
   197  				return
   198  			}
   199  			// We're only interested in the control stream here.
   200  			switch streamType {
   201  			case streamTypeControlStream:
   202  			case streamTypeQPACKEncoderStream, streamTypeQPACKDecoderStream:
   203  				// Our QPACK implementation doesn't use the dynamic table yet.
   204  				// TODO: check that only one stream of each type is opened.
   205  				return
   206  			case streamTypePushStream:
   207  				// We never increased the Push ID, so we don't expect any push streams.
   208  				conn.CloseWithError(quic.ApplicationErrorCode(ErrCodeIDError), "")
   209  				return
   210  			default:
   211  				if c.opts.UniStreamHijacker != nil && c.opts.UniStreamHijacker(StreamType(streamType), conn, str, nil) {
   212  					return
   213  				}
   214  				str.CancelRead(quic.StreamErrorCode(ErrCodeStreamCreationError))
   215  				return
   216  			}
   217  			f, err := parseNextFrame(str, nil)
   218  			if err != nil {
   219  				conn.CloseWithError(quic.ApplicationErrorCode(ErrCodeFrameError), "")
   220  				return
   221  			}
   222  			sf, ok := f.(*settingsFrame)
   223  			if !ok {
   224  				conn.CloseWithError(quic.ApplicationErrorCode(ErrCodeMissingSettings), "")
   225  				return
   226  			}
   227  			if !sf.Datagram {
   228  				return
   229  			}
   230  			// If datagram support was enabled on our side as well as on the server side,
   231  			// we can expect it to have been negotiated both on the transport and on the HTTP/3 layer.
   232  			// Note: ConnectionState() will block until the handshake is complete (relevant when using 0-RTT).
   233  			if c.opts.EnableDatagram && !conn.ConnectionState().SupportsDatagrams {
   234  				conn.CloseWithError(quic.ApplicationErrorCode(ErrCodeSettingsError), "missing QUIC Datagram support")
   235  			}
   236  		}(str)
   237  	}
   238  }
   239  
   240  func (c *client) Close() error {
   241  	conn := c.conn.Load()
   242  	if conn == nil {
   243  		return nil
   244  	}
   245  	return (*conn).CloseWithError(quic.ApplicationErrorCode(ErrCodeNoError), "")
   246  }
   247  
   248  func (c *client) maxHeaderBytes() uint64 {
   249  	if c.opts.MaxHeaderBytes <= 0 {
   250  		return defaultMaxResponseHeaderBytes
   251  	}
   252  	return uint64(c.opts.MaxHeaderBytes)
   253  }
   254  
   255  // RoundTripOpt executes a request and returns a response
   256  func (c *client) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) {
   257  	rsp, err := c.roundTripOpt(req, opt)
   258  	if err != nil && req.Context().Err() != nil {
   259  		// if the context was canceled, return the context cancellation error
   260  		err = req.Context().Err()
   261  	}
   262  	return rsp, err
   263  }
   264  
   265  func (c *client) roundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Response, error) {
   266  	if authorityAddr("https", hostnameFromRequest(req)) != c.hostname {
   267  		return nil, fmt.Errorf("http3 client BUG: RoundTripOpt called for the wrong client (expected %s, got %s)", c.hostname, req.Host)
   268  	}
   269  
   270  	c.dialOnce.Do(func() {
   271  		c.handshakeErr = c.dial(req.Context())
   272  	})
   273  	if c.handshakeErr != nil {
   274  		return nil, c.handshakeErr
   275  	}
   276  
   277  	// At this point, c.conn is guaranteed to be set.
   278  	conn := *c.conn.Load()
   279  
   280  	// Immediately send out this request, if this is a 0-RTT request.
   281  	if req.Method == MethodGet0RTT {
   282  		req.Method = http.MethodGet
   283  	} else {
   284  		// wait for the handshake to complete
   285  		select {
   286  		case <-conn.HandshakeComplete():
   287  		case <-req.Context().Done():
   288  			return nil, req.Context().Err()
   289  		}
   290  	}
   291  
   292  	str, err := conn.OpenStreamSync(req.Context())
   293  	if err != nil {
   294  		return nil, err
   295  	}
   296  
   297  	// Request Cancellation:
   298  	// This go routine keeps running even after RoundTripOpt() returns.
   299  	// It is shut down when the application is done processing the body.
   300  	reqDone := make(chan struct{})
   301  	done := make(chan struct{})
   302  	go func() {
   303  		defer close(done)
   304  		select {
   305  		case <-req.Context().Done():
   306  			str.CancelWrite(quic.StreamErrorCode(ErrCodeRequestCanceled))
   307  			str.CancelRead(quic.StreamErrorCode(ErrCodeRequestCanceled))
   308  		case <-reqDone:
   309  		}
   310  	}()
   311  
   312  	doneChan := reqDone
   313  	if opt.DontCloseRequestStream {
   314  		doneChan = nil
   315  	}
   316  	rsp, rerr := c.doRequest(req, conn, str, opt, doneChan)
   317  	if rerr.err != nil { // if any error occurred
   318  		close(reqDone)
   319  		<-done
   320  		if rerr.streamErr != 0 { // if it was a stream error
   321  			str.CancelWrite(quic.StreamErrorCode(rerr.streamErr))
   322  		}
   323  		if rerr.connErr != 0 { // if it was a connection error
   324  			var reason string
   325  			if rerr.err != nil {
   326  				reason = rerr.err.Error()
   327  			}
   328  			conn.CloseWithError(quic.ApplicationErrorCode(rerr.connErr), reason)
   329  		}
   330  		return nil, maybeReplaceError(rerr.err)
   331  	}
   332  	if opt.DontCloseRequestStream {
   333  		close(reqDone)
   334  		<-done
   335  	}
   336  	return rsp, maybeReplaceError(rerr.err)
   337  }
   338  
   339  // cancelingReader reads from the io.Reader.
   340  // It cancels writing on the stream if any error other than io.EOF occurs.
   341  type cancelingReader struct {
   342  	r   io.Reader
   343  	str Stream
   344  }
   345  
   346  func (r *cancelingReader) Read(b []byte) (int, error) {
   347  	n, err := r.r.Read(b)
   348  	if err != nil && err != io.EOF {
   349  		r.str.CancelWrite(quic.StreamErrorCode(ErrCodeRequestCanceled))
   350  	}
   351  	return n, err
   352  }
   353  
   354  func (c *client) sendRequestBody(str Stream, body io.ReadCloser, contentLength int64) error {
   355  	defer body.Close()
   356  	buf := make([]byte, bodyCopyBufferSize)
   357  	sr := &cancelingReader{str: str, r: body}
   358  	if contentLength == -1 {
   359  		_, err := io.CopyBuffer(str, sr, buf)
   360  		return err
   361  	}
   362  
   363  	// make sure we don't send more bytes than the content length
   364  	n, err := io.CopyBuffer(str, io.LimitReader(sr, contentLength), buf)
   365  	if err != nil {
   366  		return err
   367  	}
   368  	var extra int64
   369  	extra, err = io.CopyBuffer(io.Discard, sr, buf)
   370  	n += extra
   371  	if n > contentLength {
   372  		str.CancelWrite(quic.StreamErrorCode(ErrCodeRequestCanceled))
   373  		return fmt.Errorf("http: ContentLength=%d with Body length %d", contentLength, n)
   374  	}
   375  	return err
   376  }
   377  
   378  func (c *client) doRequest(req *http.Request, conn quic.EarlyConnection, str quic.Stream, opt RoundTripOpt, reqDone chan<- struct{}) (*http.Response, requestError) {
   379  	var requestGzip bool
   380  	if !c.opts.DisableCompression && req.Method != "HEAD" && req.Header.Get("Accept-Encoding") == "" && req.Header.Get("Range") == "" {
   381  		requestGzip = true
   382  	}
   383  	if err := c.requestWriter.WriteRequestHeader(str, req, requestGzip); err != nil {
   384  		return nil, newStreamError(ErrCodeInternalError, err)
   385  	}
   386  
   387  	if req.Body == nil && !opt.DontCloseRequestStream {
   388  		str.Close()
   389  	}
   390  
   391  	hstr := newStream(str, func() { conn.CloseWithError(quic.ApplicationErrorCode(ErrCodeFrameUnexpected), "") })
   392  	if req.Body != nil {
   393  		// send the request body asynchronously
   394  		go func() {
   395  			contentLength := int64(-1)
   396  			// According to the documentation for http.Request.ContentLength,
   397  			// a value of 0 with a non-nil Body is also treated as unknown content length.
   398  			if req.ContentLength > 0 {
   399  				contentLength = req.ContentLength
   400  			}
   401  			if err := c.sendRequestBody(hstr, req.Body, contentLength); err != nil {
   402  				c.logger.Errorf("Error writing request: %s", err)
   403  			}
   404  			if !opt.DontCloseRequestStream {
   405  				hstr.Close()
   406  			}
   407  		}()
   408  	}
   409  
   410  	frame, err := parseNextFrame(str, nil)
   411  	if err != nil {
   412  		return nil, newStreamError(ErrCodeFrameError, err)
   413  	}
   414  	hf, ok := frame.(*headersFrame)
   415  	if !ok {
   416  		return nil, newConnError(ErrCodeFrameUnexpected, errors.New("expected first frame to be a HEADERS frame"))
   417  	}
   418  	if hf.Length > c.maxHeaderBytes() {
   419  		return nil, newStreamError(ErrCodeFrameError, fmt.Errorf("HEADERS frame too large: %d bytes (max: %d)", hf.Length, c.maxHeaderBytes()))
   420  	}
   421  	headerBlock := make([]byte, hf.Length)
   422  	if _, err := io.ReadFull(str, headerBlock); err != nil {
   423  		return nil, newStreamError(ErrCodeRequestIncomplete, err)
   424  	}
   425  	hfs, err := c.decoder.DecodeFull(headerBlock)
   426  	if err != nil {
   427  		// TODO: use the right error code
   428  		return nil, newConnError(ErrCodeGeneralProtocolError, err)
   429  	}
   430  
   431  	res, err := responseFromHeaders(hfs)
   432  	if err != nil {
   433  		return nil, newStreamError(ErrCodeMessageError, err)
   434  	}
   435  	connState := conn.ConnectionState().TLS
   436  	res.TLS = &connState
   437  	res.Request = req
   438  	// Check that the server doesn't send more data in DATA frames than indicated by the Content-Length header (if set).
   439  	// See section 4.1.2 of RFC 9114.
   440  	var httpStr Stream
   441  	if _, ok := res.Header["Content-Length"]; ok && res.ContentLength >= 0 {
   442  		httpStr = newLengthLimitedStream(hstr, res.ContentLength)
   443  	} else {
   444  		httpStr = hstr
   445  	}
   446  	respBody := newResponseBody(httpStr, conn, reqDone)
   447  
   448  	// Rules for when to set Content-Length are defined in https://tools.ietf.org/html/rfc7230#section-3.3.2.
   449  	_, hasTransferEncoding := res.Header["Transfer-Encoding"]
   450  	isInformational := res.StatusCode >= 100 && res.StatusCode < 200
   451  	isNoContent := res.StatusCode == http.StatusNoContent
   452  	isSuccessfulConnect := req.Method == http.MethodConnect && res.StatusCode >= 200 && res.StatusCode < 300
   453  	if !hasTransferEncoding && !isInformational && !isNoContent && !isSuccessfulConnect {
   454  		res.ContentLength = -1
   455  		if clens, ok := res.Header["Content-Length"]; ok && len(clens) == 1 {
   456  			if clen64, err := strconv.ParseInt(clens[0], 10, 64); err == nil {
   457  				res.ContentLength = clen64
   458  			}
   459  		}
   460  	}
   461  
   462  	if requestGzip && res.Header.Get("Content-Encoding") == "gzip" {
   463  		res.Header.Del("Content-Encoding")
   464  		res.Header.Del("Content-Length")
   465  		res.ContentLength = -1
   466  		res.Body = newGzipReader(respBody)
   467  		res.Uncompressed = true
   468  	} else {
   469  		res.Body = respBody
   470  	}
   471  
   472  	return res, requestError{}
   473  }
   474  
   475  func (c *client) HandshakeComplete() bool {
   476  	conn := c.conn.Load()
   477  	if conn == nil {
   478  		return false
   479  	}
   480  	select {
   481  	case <-(*conn).HandshakeComplete():
   482  		return true
   483  	default:
   484  		return false
   485  	}
   486  }