-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
h2.go
207 lines (200 loc) · 5.27 KB
/
h2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package goproxy
import (
"bufio"
"crypto/tls"
"errors"
"io"
"net"
"net/http"
"strings"
"golang.org/x/net/http2"
)
var ErrInvalidH2Frame = errors.New("invalid H2 frame")
// H2Transport is an implementation of RoundTripper that abstracts an entire
// HTTP/2 session, sending all client frames to the server and responses back
// to the client.
type H2Transport struct {
ClientReader io.Reader
ClientWriter io.Writer
TLSConfig *tls.Config
Host string
}
// RoundTrip executes an HTTP/2 session (including all contained streams).
// The request and response are ignored but any error encountered during the
// proxying from the session is returned as a result of the invocation.
func (r *H2Transport) RoundTrip(_ *http.Request) (*http.Response, error) {
raddr := r.Host
if !strings.Contains(raddr, ":") {
raddr += ":443"
}
rawServerTLS, err := dial("tcp", raddr)
if err != nil {
return nil, err
}
defer rawServerTLS.Close()
// Ensure that we only advertise HTTP/2 as the accepted protocol.
r.TLSConfig.NextProtos = []string{http2.NextProtoTLS}
// Initiate TLS and check remote host name against certificate.
rawServerTLS = tls.Client(rawServerTLS, r.TLSConfig)
rawTLSConn, ok := rawServerTLS.(*tls.Conn)
if !ok {
return nil, errors.New("invalid TLS connection")
}
if err = rawTLSConn.Handshake(); err != nil {
return nil, err
}
if r.TLSConfig == nil || !r.TLSConfig.InsecureSkipVerify {
if err = rawTLSConn.VerifyHostname(raddr[:strings.LastIndex(raddr, ":")]); err != nil {
return nil, err
}
}
// Send new client preface to match the one parsed in req.
if _, err := io.WriteString(rawServerTLS, http2.ClientPreface); err != nil {
return nil, err
}
serverTLSReader := bufio.NewReader(rawServerTLS)
cToS := http2.NewFramer(rawServerTLS, r.ClientReader)
sToC := http2.NewFramer(r.ClientWriter, serverTLSReader)
errSToC := make(chan error)
errCToS := make(chan error)
go func() {
for {
if err := proxyFrame(sToC); err != nil {
errSToC <- err
break
}
}
}()
go func() {
for {
if err := proxyFrame(cToS); err != nil {
errCToS <- err
break
}
}
}()
for i := 0; i < 2; i++ {
select {
case err := <-errSToC:
if !errors.Is(err, io.EOF) {
return nil, err
}
case err := <-errCToS:
if !errors.Is(err, io.EOF) {
return nil, err
}
}
}
return nil, nil
}
func dial(network, addr string) (c net.Conn, err error) {
addri, err := net.ResolveTCPAddr(network, addr)
if err != nil {
return
}
c, err = net.DialTCP(network, nil, addri)
return
}
// proxyFrame reads a single frame from the Framer and, when successful, writes
// a ~identical one back to the Framer.
func proxyFrame(fr *http2.Framer) error {
f, err := fr.ReadFrame()
if err != nil {
return err
}
switch f.Header().Type {
case http2.FrameData:
tf, ok := f.(*http2.DataFrame)
if !ok {
return ErrInvalidH2Frame
}
terr := fr.WriteData(tf.StreamID, tf.StreamEnded(), tf.Data())
if terr == nil && tf.StreamEnded() {
terr = io.EOF
}
return terr
case http2.FrameHeaders:
tf, ok := f.(*http2.HeadersFrame)
if !ok {
return ErrInvalidH2Frame
}
terr := fr.WriteHeaders(http2.HeadersFrameParam{
StreamID: tf.StreamID,
BlockFragment: tf.HeaderBlockFragment(),
EndStream: tf.StreamEnded(),
EndHeaders: tf.HeadersEnded(),
PadLength: 0,
Priority: tf.Priority,
})
if terr == nil && tf.StreamEnded() {
terr = io.EOF
}
return terr
case http2.FrameContinuation:
tf, ok := f.(*http2.ContinuationFrame)
if !ok {
return ErrInvalidH2Frame
}
return fr.WriteContinuation(tf.StreamID, tf.HeadersEnded(), tf.HeaderBlockFragment())
case http2.FrameGoAway:
tf, ok := f.(*http2.GoAwayFrame)
if !ok {
return ErrInvalidH2Frame
}
return fr.WriteGoAway(tf.StreamID, tf.ErrCode, tf.DebugData())
case http2.FramePing:
tf, ok := f.(*http2.PingFrame)
if !ok {
return ErrInvalidH2Frame
}
return fr.WritePing(tf.IsAck(), tf.Data)
case http2.FrameRSTStream:
tf, ok := f.(*http2.RSTStreamFrame)
if !ok {
return ErrInvalidH2Frame
}
return fr.WriteRSTStream(tf.StreamID, tf.ErrCode)
case http2.FrameSettings:
tf, ok := f.(*http2.SettingsFrame)
if !ok {
return ErrInvalidH2Frame
}
if tf.IsAck() {
return fr.WriteSettingsAck()
}
var settings []http2.Setting
// NOTE: If we want to parse headers, need to handle
// settings where s.ID == http2.SettingHeaderTableSize and
// accordingly update the Framer options.
for i := 0; i < tf.NumSettings(); i++ {
settings = append(settings, tf.Setting(i))
}
return fr.WriteSettings(settings...)
case http2.FrameWindowUpdate:
tf, ok := f.(*http2.WindowUpdateFrame)
if !ok {
return ErrInvalidH2Frame
}
return fr.WriteWindowUpdate(tf.StreamID, tf.Increment)
case http2.FramePriority:
tf, ok := f.(*http2.PriorityFrame)
if !ok {
return ErrInvalidH2Frame
}
return fr.WritePriority(tf.StreamID, tf.PriorityParam)
case http2.FramePushPromise:
tf, ok := f.(*http2.PushPromiseFrame)
if !ok {
return ErrInvalidH2Frame
}
return fr.WritePushPromise(http2.PushPromiseParam{
StreamID: tf.StreamID,
PromiseID: tf.PromiseID,
BlockFragment: tf.HeaderBlockFragment(),
EndHeaders: tf.HeadersEnded(),
PadLength: 0,
})
default:
return errors.New("Unsupported frame: " + string(f.Header().Type))
}
}