-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream.go
307 lines (274 loc) · 5.78 KB
/
stream.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
// Copyright (c) 2013, Daniel Morsing
// For more information, see the LICENSE file
package spdy
import (
"bufio"
"bytes"
"errors"
"fmt"
"github.com/DanielMorsing/spdy/framing"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"sync"
)
// stream represents a spdy stream within a session
type stream struct {
// the stream id for this stream
id framing.StreamId
// window size
sendWindow uint32
receiveWindow uint32
windowOffset uint32
priority uint8
reset chan struct{}
recvData chan struct{}
windowUpdate chan struct{}
session *session
receivedFin bool
closed bool
buf bytes.Buffer
// channel to communicate with outframer.
ofchan chan struct{}
// mutex to protect the window variables
mu sync.Mutex
}
func newStream(sess *session, syn *framing.SynStreamFrame) *stream {
s := &stream{
id: syn.StreamId,
priority: syn.Priority,
sendWindow: sess.initialSendWindow,
receiveWindow: sess.receiveWindow,
reset: make(chan struct{}),
session: sess,
windowUpdate: make(chan struct{}, 1),
ofchan: make(chan struct{}, 1),
}
if syn.CFHeader.Flags&framing.ControlFlagFin != 0 {
s.receivedFin = true
} else {
s.recvData = make(chan struct{}, 1)
}
return s
}
func (str *stream) isClosed() bool {
if str.closed {
return true
}
select {
case <-str.reset:
str.closed = true
return true
default:
return false
}
}
func (str *stream) handleReq(hnd http.Handler, hdr http.Header) {
rw := responseWriter{
stream: str,
header: make(http.Header),
}
req, err := mkrequest(hdr)
if err != nil {
// spdy is weird in the case where a stream req doesn't have the right headers.
// you need to send a 400 reply, rather than a stream reset.
go func() {
defer rw.close()
rw.WriteHeader(http.StatusBadRequest)
}()
return
}
rw.bufw = bufio.NewWriter(str)
if !str.receivedFin {
req.Body = ioutil.NopCloser(str)
}
go func() {
defer rw.close()
hnd.ServeHTTP(&rw, req)
}()
}
var requiredHeaders = [...]string{
":method",
":path",
":version",
":scheme",
":host",
}
func mkrequest(hdr http.Header) (*http.Request, error) {
for _, r := range requiredHeaders {
if _, ok := hdr[r]; !ok {
return nil, errors.New("invalid headers")
}
}
rm := make([]string, 0, len(hdr))
req := new(http.Request)
req.URL = new(url.URL)
for k, v := range hdr {
if k[0] == ':' {
rm = append(rm, k)
}
switch k {
case ":method":
req.Method = v[0]
case ":path":
req.URL.Path = v[0]
case ":version":
s := v[0]
req.URL.Host = s
req.Host = s
major, minor, ok := http.ParseHTTPVersion(s)
if ok {
req.ProtoMajor = major
req.ProtoMinor = minor
}
case ":scheme":
req.URL.Scheme = v[0]
case ":host":
req.Host = v[0]
req.URL.Host = v[0]
}
}
for _, k := range rm {
delete(hdr, k)
}
req.Header = hdr
return req, nil
}
func (str *stream) Write(b []byte) (int, error) {
n := 0
var err error
for {
if len(b) == 0 {
break
}
tb, blocked := str.truncateBuffer(b)
if blocked {
err := str.waitWindow()
if err != nil {
return n, err
}
continue
}
err := str.session.of.write(str, tb)
if err != nil {
return n, err
}
n += len(tb)
b = b[len(tb):]
}
return n, err
}
func (str *stream) waitWindow() error {
select {
case <-str.windowUpdate:
return nil
case <-str.reset:
return io.ErrClosedPipe
}
}
func (str *stream) Read(b []byte) (int, error) {
for {
n, gotData, err := str.tryRead(b)
if gotData {
return n, err
}
select {
case <-str.recvData:
case <-str.reset:
return 0, io.ErrClosedPipe
}
}
}
func (str *stream) tryRead(b []byte) (int, bool, error) {
str.mu.Lock()
defer str.mu.Unlock()
n, err := str.buf.Read(b)
if str.receivedFin {
// have everything buffered, no need to update window size
return n, true, err
}
str.windowOffset += uint32(n)
if err != io.EOF {
if str.receiveWindow < 4096 {
str.receiveWindow += str.windowOffset
str.session.of.sendWindowUpdate(str, str.windowOffset)
str.windowOffset = 0
}
return n, true, err
}
return 0, false, nil
}
// this method truncates the buffer to a more reasonable size for a spdy frame.
// It also reports whether we're blocked on the sending window.
func (str *stream) truncateBuffer(b []byte) ([]byte, bool) {
str.mu.Lock()
defer str.mu.Unlock()
if str.sendWindow == 0 {
return b, true
}
// limit frame size so that multiple streams are more efficiently multiplexed
// on to the connection.
if len(b) > 2000 {
b = b[:2000]
}
if len(b) > int(str.sendWindow) {
b = b[:str.sendWindow]
}
str.sendWindow -= uint32(len(b))
return b, false
}
// sends a synreply frame
func (str *stream) sendAck(hdr http.Header) {
if str.isClosed() {
return
}
str.session.of.reply(str, hdr)
}
func (str *stream) sendFin() {
if str.isClosed() {
return
}
str.session.of.sendFin(str)
str.closed = true
select {
case str.session.finch <- str:
case <-str.reset:
}
}
// responseWriter is the type passed to the request handler.
// it is only touched by the handling goroutine.
type responseWriter struct {
stream *stream
headerWritten bool
header http.Header
bufw *bufio.Writer
}
func (rw *responseWriter) Write(b []byte) (int, error) {
if !rw.headerWritten {
rw.WriteHeader(http.StatusOK)
}
return rw.bufw.Write(b)
}
func (rw *responseWriter) Header() http.Header {
return rw.header
}
func (rw *responseWriter) WriteHeader(code int) {
if rw.headerWritten {
log.Println("Header written twice")
return
}
s := fmt.Sprintf("%d %s", code, http.StatusText(code))
rw.header.Set(":status", s)
rw.header.Set(":version", "HTTP/1.1")
rw.stream.sendAck(rw.header)
rw.headerWritten = true
}
func (rw *responseWriter) close() {
if !rw.headerWritten {
rw.WriteHeader(http.StatusOK)
}
rw.bufw.Flush()
rw.stream.sendFin()
}