-
Notifications
You must be signed in to change notification settings - Fork 5
/
server.go
379 lines (352 loc) · 8.58 KB
/
server.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
// Package h2c implements HTTP/2 h2c.
//
// HTTP/2 h2c server implementation would not available in golang standard library
// because of the policy. This package provides h2c handy implementation.
package h2c
import (
"bufio"
"bytes"
"encoding/base64"
"encoding/binary"
"golang.org/x/net/http2"
"golang.org/x/net/http2/hpack"
"io"
"log"
"net"
"net/http"
"net/textproto"
"strings"
"unicode"
)
type Server struct {
// Actual content handler
http.Handler
// Disable RFC 7540 3.4 behavior
DisableDirect bool
}
// Converts byte slice of SETTINGS frame payload into http2.Setting slice.
func ParseSettings(b []byte) []http2.Setting {
var r []http2.Setting
for i := 0; i < len(b)/6; i++ {
r = append(r, http2.Setting{
ID: http2.SettingID(binary.BigEndian.Uint16(b[i*6:])),
Val: binary.BigEndian.Uint32(b[i*6+2:]),
})
}
return r
}
var sensitiveHeaders []string = []string{
"Cookie",
"Set-Cookie",
"Authorization",
}
// RFC7540 8.1.2.2
var connectionHeaders []string = []string{
"Connection",
"Keep-Alive",
"Proxy-Connection",
"Transfer-Encoding",
"Upgrade",
"HTTP2-Settings",
}
type InitRequest struct {
Settings []http2.Setting // HTTP2-Settings parameters
HeaderBlock []byte // http2 header block hpack-ed from HTTP/1.1 headers
}
// Prepares an http/2 request binaries from http.Request.
// Returns nil if upgrade failed.
func InitH2c(req *http.Request) *InitRequest {
upgrade := false
if vs, ok := req.Header[textproto.CanonicalMIMEHeaderKey("Upgrade")]; ok {
sp := func(c rune) bool { return unicode.IsSpace(c) || c == ',' }
// RFC 7230 3.2.2 comma-separated field value
for _, v := range vs {
for _, s := range strings.FieldsFunc(v, sp) {
if s == "h2c" {
upgrade = true
}
}
}
}
if !upgrade {
return nil
}
var settings []http2.Setting
if vs, ok := req.Header[textproto.CanonicalMIMEHeaderKey("HTTP2-Settings")]; ok && len(vs) == 1 {
if b, e := base64.RawURLEncoding.DecodeString(vs[0]); e != nil {
return nil
} else if len(b)%6 != 0 {
return nil
} else {
settings = ParseSettings(b)
}
} else {
return nil
}
buf := bytes.NewBuffer(nil)
enc := hpack.NewEncoder(buf)
for _, s := range settings {
switch s.ID {
case http2.SettingHeaderTableSize:
enc.SetMaxDynamicTableSize(s.Val)
}
}
wh := func(name, value string, sensitive bool) error {
if len(value) == 0 {
return nil
}
return enc.WriteField(hpack.HeaderField{
Name: strings.ToLower(name),
Value: value,
Sensitive: sensitive,
})
}
if err := wh(":method", req.Method, false); err != nil {
return nil
}
host := req.URL.Host
if len(host) == 0 {
host = req.Host
}
if err := wh(":authority", host, false); err != nil {
return nil
}
if req.Method != "CONNECT" {
scheme := "http"
if len(req.URL.Scheme) > 0 {
scheme = req.URL.Scheme
}
if err := wh(":scheme", scheme, false); err != nil {
return nil
}
if err := wh(":path", req.URL.Path, false); err != nil {
return nil
}
}
for k, vs := range req.Header {
skip := false
for _, h := range connectionHeaders {
if k == textproto.CanonicalMIMEHeaderKey(h) {
skip = true
}
}
if skip {
continue
}
sensitive := false
for _, h := range sensitiveHeaders {
if k == textproto.CanonicalMIMEHeaderKey(h) {
sensitive = true
}
}
for _, v := range vs {
if err := wh(k, v, sensitive); err != nil {
return nil
}
}
}
return &InitRequest{
Settings: settings,
HeaderBlock: buf.Bytes(),
}
}
type h2cInitReqBody struct {
*http2.Framer
*bytes.Buffer // Framer writes to this
Body io.Reader
FrameSize uint32
buf []byte
streamEnd bool
}
func (rd *h2cInitReqBody) Read(b []byte) (int, error) {
if !rd.streamEnd && rd.Buffer.Len() < len(b) {
if len(rd.buf) == 0 {
rd.buf = make([]byte, rd.FrameSize)
}
n, err := rd.Body.Read(rd.buf)
if n == 0 || err == io.EOF {
rd.streamEnd = true
}
if err := rd.Framer.WriteData(1, rd.streamEnd, rd.buf[:n]); err != nil {
return 0, err
}
}
return rd.Buffer.Read(b)
}
type vacuumPreface struct {
io.Reader
}
func (rd vacuumPreface) Read(b []byte) (int, error) {
n, err := rd.Reader.Read([]byte(http2.ClientPreface))
if n != len(http2.ClientPreface) {
return n, io.ErrUnexpectedEOF
}
if err != nil && err != io.EOF {
return n, err
}
return 0, io.EOF
}
type conn struct {
net.Conn // embed for methods
io.Reader
*bufio.Writer
vacuumAck bool
buf []byte
}
func (c conn) Read(b []byte) (int, error) {
return c.Reader.Read(b)
}
func (c *conn) Write(b []byte) (int, error) {
if c.vacuumAck {
c.buf = append(c.buf, b...)
for c.vacuumAck {
if len(c.buf) < 9 {
return len(b), nil // just buffered into c.buf
}
fh, err := http2.ReadFrameHeader(bytes.NewBuffer(c.buf))
if err != nil {
return 0, err // in case frame was broken
} else if uint32(len(c.buf)) < 9+fh.Length {
return len(b), nil // just buffered into c.buf
}
buf := c.buf[:9+fh.Length]
c.buf = c.buf[9+fh.Length:]
if http2.FrameSettings == fh.Type && fh.Flags.Has(http2.FlagSettingsAck) {
c.vacuumAck = false
} else if n, err := c.Writer.Write(buf); err != nil {
return n, err
}
}
n, err := c.Writer.Write(c.buf)
c.Writer.Flush()
return n, err
}
n, err := c.Writer.Write(b)
c.Writer.Flush()
return n, err
}
// ServeHTTP implements http.Handler interface for HTTP/2 h2c upgrade.
func (u Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if hijacker, ok := w.(http.Hijacker); ok {
if !u.DisableDirect && r.Method == "PRI" && r.URL.Path == "*" && r.Proto == "HTTP/2.0" {
body := "SM\r\n\r\n"
con, rw, err := hijacker.Hijack()
defer con.Close()
if err != nil {
log.Printf("Hijack failed %v", err)
} else if n, err := io.MultiReader(r.Body, rw).Read([]byte(body)); n != len(body) {
log.Printf("%d %v", n, err)
} else {
wrap := io.MultiReader(bytes.NewBuffer([]byte(http2.ClientPreface)), rw)
nc := &conn{
Conn: con,
Writer: rw.Writer,
Reader: wrap,
}
h2c := &http2.Server{}
h2c.ServeConn(nc, &http2.ServeConnOpts{Handler: u.Handler})
return
}
http.Error(w, "Server could not handle the request.", http.StatusMethodNotAllowed)
return
}
if initReq := InitH2c(r); initReq != nil {
fsz := uint32(1 << 14) // RFC default
for _, s := range initReq.Settings {
if s.ID == http2.SettingMaxFrameSize && s.Val != 0 {
fsz = s.Val
}
}
onError := func(e error) {
log.Print(e)
http.Error(w, "Error in upgrading initial request", http.StatusInternalServerError)
}
h2req := bytes.NewBuffer([]byte(http2.ClientPreface))
fr := http2.NewFramer(h2req, nil)
if err := fr.WriteSettings(initReq.Settings...); err != nil {
onError(err)
return
}
hdr := initReq.HeaderBlock
if uint32(len(hdr)) <= fsz {
if err := fr.WriteHeaders(http2.HeadersFrameParam{
StreamID: 1,
BlockFragment: hdr,
EndHeaders: true,
}); err != nil {
onError(err)
return
}
} else {
if err := fr.WriteHeaders(http2.HeadersFrameParam{
StreamID: 1,
BlockFragment: hdr[:fsz],
}); err != nil {
onError(err)
return
}
hdr = hdr[fsz:]
for len(hdr) > 0 {
if uint32(len(hdr)) > fsz {
if err := fr.WriteContinuation(1, false, hdr[:fsz]); err != nil {
onError(err)
return
}
hdr = hdr[fsz:]
} else {
if err := fr.WriteContinuation(1, true, hdr); err != nil {
onError(err)
return
}
hdr = nil
}
}
}
con, rw, err := hijacker.Hijack()
// Note: It seems rw is a wrapper for con.
// r.Body.Read still looks working unless rw.Read call.
defer con.Close()
if err != nil {
onError(err)
rw.Flush()
return
}
rw.Write([]byte(
"HTTP/1.1 101 Switching Protocols\r\n" +
"Connection: upgrade\r\n" +
"Upgrade: h2c\r\n" +
"\r\n"))
h2req2 := &h2cInitReqBody{
Framer: fr,
Buffer: h2req,
Body: r.Body,
FrameSize: fsz,
}
nc := &conn{
Conn: con,
Writer: rw.Writer,
Reader: io.MultiReader(h2req2, vacuumPreface{rw}, rw),
vacuumAck: true, // because we sent HTTP2-Settings payload
}
h2c := &http2.Server{}
for _, s := range initReq.Settings {
switch s.ID {
case http2.SettingMaxConcurrentStreams:
h2c.MaxConcurrentStreams = s.Val
case http2.SettingMaxFrameSize:
h2c.MaxReadFrameSize = s.Val
default:
// just ignore
}
}
h2c.ServeConn(nc, &http2.ServeConnOpts{Handler: u.Handler})
return
}
}
if u.Handler != nil {
u.Handler.ServeHTTP(w, r)
} else {
http.DefaultServeMux.ServeHTTP(w, r)
}
return
}