route/vendor/github.com/lucas-clemente/quic-go/h2quic/client.go

291 lines
6.7 KiB
Go
Raw Normal View History

2017-12-12 02:51:45 +00:00
package h2quic
import (
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"net/http"
"strings"
"sync"
"golang.org/x/net/http2"
"golang.org/x/net/http2/hpack"
"golang.org/x/net/idna"
quic "github.com/lucas-clemente/quic-go"
2018-01-03 19:19:49 +00:00
"github.com/lucas-clemente/quic-go/internal/protocol"
"github.com/lucas-clemente/quic-go/internal/utils"
2017-12-12 02:51:45 +00:00
"github.com/lucas-clemente/quic-go/qerr"
)
2018-01-03 19:19:49 +00:00
type roundTripperOpts struct {
DisableCompression bool
}
var dialAddr = quic.DialAddr
2017-12-12 02:51:45 +00:00
2018-01-03 19:19:49 +00:00
// client is a HTTP2 client doing QUIC requests
type client struct {
mutex sync.RWMutex
2017-12-12 02:51:45 +00:00
2018-01-03 19:19:49 +00:00
tlsConf *tls.Config
config *quic.Config
opts *roundTripperOpts
2017-12-12 02:51:45 +00:00
2018-01-03 19:19:49 +00:00
hostname string
handshakeErr error
dialOnce sync.Once
2017-12-12 02:51:45 +00:00
session quic.Session
headerStream quic.Stream
headerErr *qerr.QuicError
2018-01-03 19:19:49 +00:00
headerErrored chan struct{} // this channel is closed if an error occurs on the header stream
2017-12-12 02:51:45 +00:00
requestWriter *requestWriter
responses map[protocol.StreamID]chan *http.Response
}
2018-01-03 19:19:49 +00:00
var _ http.RoundTripper = &client{}
2017-12-12 02:51:45 +00:00
2018-01-03 19:19:49 +00:00
var defaultQuicConfig = &quic.Config{
RequestConnectionIDOmission: true,
KeepAlive: true,
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
// newClient creates a new client
func newClient(
hostname string,
tlsConfig *tls.Config,
opts *roundTripperOpts,
quicConfig *quic.Config,
) *client {
config := defaultQuicConfig
if quicConfig != nil {
config = quicConfig
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
return &client{
hostname: authorityAddr("https", hostname),
responses: make(map[protocol.StreamID]chan *http.Response),
tlsConf: tlsConfig,
config: config,
opts: opts,
headerErrored: make(chan struct{}),
2017-12-12 02:51:45 +00:00
}
}
2018-01-03 19:19:49 +00:00
// dial dials the connection
func (c *client) dial() error {
2017-12-12 02:51:45 +00:00
var err error
2018-01-03 19:19:49 +00:00
c.session, err = dialAddr(c.hostname, c.tlsConf, c.config)
if err != nil {
return err
}
2017-12-12 02:51:45 +00:00
// once the version has been negotiated, open the header stream
c.headerStream, err = c.session.OpenStream()
if err != nil {
return err
}
c.requestWriter = newRequestWriter(c.headerStream)
go c.handleHeaderStream()
return nil
}
2018-01-03 19:19:49 +00:00
func (c *client) handleHeaderStream() {
2017-12-12 02:51:45 +00:00
decoder := hpack.NewDecoder(4096, func(hf hpack.HeaderField) {})
h2framer := http2.NewFramer(nil, c.headerStream)
2018-01-20 18:07:01 +00:00
var err error
for err == nil {
err = c.readResponse(h2framer, decoder)
2017-12-12 02:51:45 +00:00
}
2018-01-20 18:07:01 +00:00
utils.Debugf("Error handling header stream: %s", err)
c.headerErr = qerr.Error(qerr.InvalidHeadersStreamData, err.Error())
2017-12-12 02:51:45 +00:00
// stop all running request
2018-01-03 19:19:49 +00:00
close(c.headerErrored)
2017-12-12 02:51:45 +00:00
}
2018-01-20 18:07:01 +00:00
func (c *client) readResponse(h2framer *http2.Framer, decoder *hpack.Decoder) error {
frame, err := h2framer.ReadFrame()
if err != nil {
return err
}
hframe, ok := frame.(*http2.HeadersFrame)
if !ok {
return errors.New("not a headers frame")
}
mhframe := &http2.MetaHeadersFrame{HeadersFrame: hframe}
mhframe.Fields, err = decoder.DecodeFull(hframe.HeaderBlockFragment())
if err != nil {
return fmt.Errorf("cannot read header fields: %s", err.Error())
}
c.mutex.RLock()
responseChan, ok := c.responses[protocol.StreamID(hframe.StreamID)]
c.mutex.RUnlock()
if !ok {
return fmt.Errorf("response channel for stream %d not found", hframe.StreamID)
}
rsp, err := responseFromHeaders(mhframe)
if err != nil {
return err
}
responseChan <- rsp
return nil
}
2018-01-03 19:19:49 +00:00
// Roundtrip executes a request and returns a response
func (c *client) RoundTrip(req *http.Request) (*http.Response, error) {
2017-12-12 02:51:45 +00:00
// TODO: add port to address, if it doesn't have one
if req.URL.Scheme != "https" {
return nil, errors.New("quic http2: unsupported scheme")
}
if authorityAddr("https", hostnameFromRequest(req)) != c.hostname {
2018-01-03 19:19:49 +00:00
return nil, fmt.Errorf("h2quic Client BUG: RoundTrip called for the wrong client (expected %s, got %s)", c.hostname, req.Host)
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
c.dialOnce.Do(func() {
c.handshakeErr = c.dial()
})
2017-12-12 02:51:45 +00:00
2018-01-03 19:19:49 +00:00
if c.handshakeErr != nil {
return nil, c.handshakeErr
2017-12-12 02:51:45 +00:00
}
2018-01-03 19:19:49 +00:00
hasBody := (req.Body != nil)
responseChan := make(chan *http.Response)
2017-12-12 02:51:45 +00:00
dataStream, err := c.session.OpenStreamSync()
if err != nil {
2018-01-03 19:19:49 +00:00
_ = c.CloseWithError(err)
2017-12-12 02:51:45 +00:00
return nil, err
}
2018-01-03 19:19:49 +00:00
c.mutex.Lock()
c.responses[dataStream.StreamID()] = responseChan
2017-12-12 02:51:45 +00:00
c.mutex.Unlock()
var requestedGzip bool
2018-01-03 19:19:49 +00:00
if !c.opts.DisableCompression && req.Header.Get("Accept-Encoding") == "" && req.Header.Get("Range") == "" && req.Method != "HEAD" {
2017-12-12 02:51:45 +00:00
requestedGzip = true
}
// TODO: add support for trailers
endStream := !hasBody
err = c.requestWriter.WriteRequest(req, dataStream.StreamID(), endStream, requestedGzip)
if err != nil {
2018-01-03 19:19:49 +00:00
_ = c.CloseWithError(err)
2017-12-12 02:51:45 +00:00
return nil, err
}
resc := make(chan error, 1)
if hasBody {
go func() {
resc <- c.writeRequestBody(dataStream, req.Body)
}()
}
var res *http.Response
var receivedResponse bool
var bodySent bool
if !hasBody {
bodySent = true
}
for !(bodySent && receivedResponse) {
select {
2018-01-03 19:19:49 +00:00
case res = <-responseChan:
2017-12-12 02:51:45 +00:00
receivedResponse = true
c.mutex.Lock()
delete(c.responses, dataStream.StreamID())
c.mutex.Unlock()
case err := <-resc:
bodySent = true
if err != nil {
return nil, err
}
2018-01-03 19:19:49 +00:00
case <-c.headerErrored:
// an error occured on the header stream
_ = c.CloseWithError(c.headerErr)
return nil, c.headerErr
2017-12-12 02:51:45 +00:00
}
}
// TODO: correctly set this variable
var streamEnded bool
isHead := (req.Method == "HEAD")
res = setLength(res, isHead, streamEnded)
if streamEnded || isHead {
res.Body = noBody
} else {
res.Body = dataStream
if requestedGzip && res.Header.Get("Content-Encoding") == "gzip" {
res.Header.Del("Content-Encoding")
res.Header.Del("Content-Length")
res.ContentLength = -1
res.Body = &gzipReader{body: res.Body}
res.Uncompressed = true
}
}
res.Request = req
return res, nil
}
2018-01-03 19:19:49 +00:00
func (c *client) writeRequestBody(dataStream quic.Stream, body io.ReadCloser) (err error) {
2017-12-12 02:51:45 +00:00
defer func() {
cerr := body.Close()
if err == nil {
// TODO: what to do with dataStream here? Maybe reset it?
err = cerr
}
}()
_, err = io.Copy(dataStream, body)
if err != nil {
// TODO: what to do with dataStream here? Maybe reset it?
return err
}
return dataStream.Close()
}
// Close closes the client
2018-01-03 19:19:49 +00:00
func (c *client) CloseWithError(e error) error {
if c.session == nil {
return nil
}
return c.session.Close(e)
}
func (c *client) Close() error {
return c.CloseWithError(nil)
2017-12-12 02:51:45 +00:00
}
// copied from net/transport.go
// authorityAddr returns a given authority (a host/IP, or host:port / ip:port)
// and returns a host:port. The port 443 is added if needed.
func authorityAddr(scheme string, authority string) (addr string) {
host, port, err := net.SplitHostPort(authority)
if err != nil { // authority didn't have a port
port = "443"
if scheme == "http" {
port = "80"
}
host = authority
}
if a, err := idna.ToASCII(host); err == nil {
host = a
}
// IPv6 address literal, without a port:
if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
return host + ":" + port
}
return net.JoinHostPort(host, port)
}