-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.go
430 lines (375 loc) · 9.54 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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
// go-nghttp2
//
// Copyright (c) 2014 Tatsuhiro Tsujikawa
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package nghttp2
import (
"bufio"
"bytes"
"crypto/tls"
"fmt"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
)
var (
H2Protos = []string{"h2", "h2-16", "h2-14"}
)
// ConfigureServer adds HTTP/2 support to http.Server.
func ConfigureServer(hs *http.Server, conf *Server) {
// Mostof the code in this function was copied from
// https://github.com/bradfitz/http2/blob/master/server.go
if conf == nil {
conf = new(Server)
}
if hs.TLSConfig == nil {
hs.TLSConfig = new(tls.Config)
}
hs.TLSConfig.NextProtos = append(hs.TLSConfig.NextProtos, H2Protos...)
if hs.TLSNextProto == nil {
hs.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
}
for _, proto := range H2Protos {
hs.TLSNextProto[proto] = func(_ *http.Server, c *tls.Conn, h http.Handler) {
conf.handleConn(c, h)
}
}
}
type Server struct {
}
func (srv *Server) handleConn(rwc net.Conn, h http.Handler) {
br := bufio.NewReader(rwc)
bw := bufio.NewWriterSize(rwc, 4096)
buf := bufio.NewReadWriter(br, bw)
sc := &serverConn{
rwc: rwc,
handler: h,
streams: make(map[int32]*stream),
remoteAddr: rwc.RemoteAddr().String(),
buf: buf,
inBuf: make([]byte, 4096),
readCh: make(chan int),
readDoneCh: make(chan struct{}),
writeReqCh: make(chan *writeReq, 200),
}
sc.s = newSession(sc)
if tc, ok := rwc.(*tls.Conn); ok {
sc.tlsState = new(tls.ConnectionState)
*sc.tlsState = tc.ConnectionState()
}
sc.serve()
}
const (
writeReqResponse = iota // request to write final HEADERS
writeReqData // request to write one or more DATA
writeReqRstStream // request to write RST_STREAM
writeReqConsumed // indicates that some uploaded bytes are consumed
)
type writeReq struct {
t int // type of request; writeReqResponse or writeReqData
rw *responseWriter // responseWriter this request refers to
es bool // no more read/write HEADER or DATA is expected
status int // status code if t == writeReqResponse
header http.Header // header fields if t == writeReqResponse
p []byte // data chunk if t == writeReqData
errCode uint32 // error code if t == writeReqRstStream
n int32 // the number of consumed bytes if t == writeReqConsumed
}
type serverConn struct {
rwc net.Conn // i/o connection
remoteAddr string // network address of remote side
tlsState *tls.ConnectionState // or nil when not using TLS
handler http.Handler // to handle request
streams map[int32]*stream // to store HTTP/2 streams
buf *bufio.ReadWriter // buffered(rwc, rwc)
inBuf []byte // input buffer
s *session // session wrapper to nghttp2 C interface
readCh chan int
readDoneCh chan struct{}
writeReqCh chan *writeReq
wg sync.WaitGroup // to wait for all handler goroutines finish
}
func (sc *serverConn) serve() {
defer func() {
sc.s.free()
sc.rwc.Close()
close(sc.readDoneCh)
for _, st := range sc.streams {
if st.rw == nil {
continue
}
close(st.rw.dataDoneCh)
}
// wait for handler finished before closing
// sc.writeReqCh which handler may write into.
sc.wg.Wait()
close(sc.writeReqCh)
}()
if err := sc.s.submitSettings([]settingsEntry{{settingsMaxConcurrentStreams, 100}}); err != nil {
return
}
go sc.doRead()
for {
if err := sc.doWrite(); err != nil {
return
}
select {
case n, ok := <-sc.readCh:
if !ok {
return
}
if err := sc.handleInput(n); err != nil {
return
}
sc.readDoneCh <- struct{}{}
case wreq, ok := <-sc.writeReqCh:
Loop:
for {
if !ok {
return
}
if err := sc.handleWriteReq(wreq); err != nil {
return
}
select {
case wreq, ok = <-sc.writeReqCh:
break
default:
break Loop
}
}
}
}
}
func (sc *serverConn) handleWriteReq(wreq *writeReq) error {
rw := wreq.rw
if wreq.es {
rw.es = true
}
switch wreq.t {
case writeReqResponse:
rw.snapStatus = wreq.status
rw.snapHeader = wreq.header
if err := sc.s.submitResponse(rw.st, rw.es); err != nil {
return fmt.Errorf("sc.s.submitResponse: %w", err)
}
case writeReqData:
rw.p = wreq.p
sc.s.resumeData(rw.st)
case writeReqRstStream:
if err := sc.s.resetStreamCode(rw.st, wreq.errCode); err != nil {
return fmt.Errorf("sc.s.resetStreamCode: %w", err)
}
case writeReqConsumed:
sc.s.consume(rw.st, wreq.n)
}
return nil
}
func (sc *serverConn) doRead() {
for {
n, err := sc.buf.Read(sc.inBuf)
if err != nil {
close(sc.readCh)
return
}
select {
case sc.readCh <- n:
case <-sc.readDoneCh:
// serve() already existed
close(sc.readCh)
return
}
if _, ok := <-sc.readDoneCh; !ok {
close(sc.readCh)
return
}
}
}
func (sc *serverConn) handleInput(n int) error {
if err := sc.s.deserialize(sc.inBuf, n); err != nil {
return err
}
return nil
}
func (sc *serverConn) doWrite() error {
for {
p, err := sc.s.serialize()
if err != nil {
return err
}
if p == nil {
break
}
if _, err := sc.buf.Write(p); err != nil {
return err
}
}
sc.buf.Flush()
if !sc.s.wantReadWrite() {
return fmt.Errorf("no more/read write for this session")
}
return nil
}
func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request) {
defer sc.wg.Done()
defer func() {
if err := recover(); err != nil {
rw.resetStream()
}
}()
sc.handler.ServeHTTP(rw, req)
_ = rw.finishRequest()
}
func (sc *serverConn) openStream(id int32) {
st := &stream{
id: id,
header: make(http.Header),
}
sc.streams[id] = st
}
func (sc *serverConn) closeStream(st *stream) {
if st.rw != nil {
close(st.rw.dataDoneCh)
}
delete(sc.streams, st.id)
}
func (sc *serverConn) headerReadDone(st *stream, es bool) error {
if st.rw != nil {
// just return if response is already committed
return nil
}
host := st.authority
if host == "" {
host = st.header.Get("host")
}
justAuthority := false
rawurl := st.path
if st.method == "CONNECT" {
justAuthority = true
rawurl = "http://" + rawurl
}
url, err := url.ParseRequestURI(rawurl)
if err != nil {
if err := sc.s.resetStream(st); err != nil {
return fmt.Errorf("sc.s.resetStream(st) failed")
}
return nil
}
// do the same way in net/http/server.go
if justAuthority {
url.Scheme = ""
}
if st.header.Get("host") == "" {
st.header.Set("Host", host)
}
// cookie header field may be split into multiple fields.
// Concatenate them into one.
var cookieBuf bytes.Buffer
if cookies, ok := st.header["Cookie"]; ok {
if len(cookies) > 1 {
for _, c := range cookies {
cookieBuf.WriteString(c)
cookieBuf.WriteString("; ")
}
cookieBuf.Truncate(cookieBuf.Len() - 2)
st.header.Set("Cookie", cookieBuf.String())
}
}
contentLength := int64(-1)
if v := st.header.Get("Content-Length"); v != "" {
// libnghttp2 guarantees the value of Content-Length
// can be parsed as int64_t.
contentLength, _ = strconv.ParseInt(v, 10, 64)
} else if es {
contentLength = 0
}
rb := &requestBody{}
rb.c.L = &rb.mu
req := &http.Request{
Method: st.method,
URL: url,
RemoteAddr: sc.remoteAddr,
Header: st.header,
RequestURI: st.path,
Proto: "HTTP/2.0",
ProtoMajor: 2,
ProtoMinor: 0,
TLS: sc.tlsState,
Host: host,
Body: rb,
ContentLength: contentLength,
}
rw := &responseWriter{
sc: sc,
st: st,
req: req,
handlerHeader: make(http.Header),
contentLength: -1,
// Create at least 1 space so that write is not
// blocked
dataDoneCh: make(chan struct{}, 1),
}
st.rw = rw
rb.rw = rw
if expect := st.header.Get("Expect"); expect != "" {
expect = strings.ToLower(expect)
if strings.Contains(expect, "100-continue") {
st.header.Del("Expect")
if err := sc.s.submitHeaders(st, 100); err != nil {
return err
}
}
}
sc.wg.Add(1)
go sc.runHandler(rw, req)
return nil
}
// handleError returns error page. We don't create http.Request
// object in this case.
func (sc *serverConn) handleError(st *stream, code int) {
rw := &responseWriter{
sc: sc,
st: st,
handlerHeader: make(http.Header),
contentLength: -1,
}
st.rw = rw
sc.wg.Add(1)
go func() {
defer sc.wg.Done()
http.Error(rw, fmt.Sprintf("%v %v", code, http.StatusText(code)), code)
_ = rw.finishRequest()
}()
}
func (sc *serverConn) handleUpload(st *stream, p []byte) {
if st.rw == nil {
return
}
req := st.rw.req
if req == nil {
return
}
rb := req.Body.(*requestBody)
rb.write(p)
}