forked from SlyMarbo/spdy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
response_stream.go
389 lines (328 loc) · 8.19 KB
/
response_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
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
// Copyright 2013 Jamie Hall. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package spdy3
import (
"bytes"
"errors"
"fmt"
"net/http"
"strconv"
"sync"
"github.com/SlyMarbo/spdy/common"
"github.com/SlyMarbo/spdy/spdy3/frames"
)
// ResponseStream is a structure that implements the
// Stream interface. This is used for responding to
// client requests.
type ResponseStream struct {
sync.Mutex
shutdownOnce sync.Once
conn *Conn
streamID common.StreamID
flow *flowControl
requestBody *bytes.Buffer
state *common.StreamState
output chan<- common.Frame
request *http.Request
handler http.Handler
header http.Header
priority common.Priority
unidirectional bool
responseCode int
stop chan bool
ready chan struct{}
wroteHeader bool
}
func NewResponseStream(conn *Conn, frame *frames.SYN_STREAM, output chan<- common.Frame, handler http.Handler, request *http.Request) *ResponseStream {
out := new(ResponseStream)
out.conn = conn
out.streamID = frame.StreamID
out.output = output
out.handler = handler
if out.handler == nil {
out.handler = http.DefaultServeMux
}
out.request = request
out.priority = frame.Priority
out.stop = conn.stop
out.unidirectional = frame.Flags.UNIDIRECTIONAL()
out.requestBody = new(bytes.Buffer)
out.state = new(common.StreamState)
out.header = make(http.Header)
out.responseCode = 0
out.ready = make(chan struct{})
out.wroteHeader = false
if frame.Flags.FIN() {
close(out.ready)
out.state.CloseThere()
}
out.request.Body = &common.ReadCloser{out.requestBody}
return out
}
/***********************
* http.ResponseWriter *
***********************/
func (s *ResponseStream) Header() http.Header {
return s.header
}
// Write is the main method with which data is sent.
func (s *ResponseStream) Write(inputData []byte) (int, error) {
if s.unidirectional {
return 0, errors.New("Error: Stream is unidirectional.")
}
if s.closed() || s.state.ClosedHere() {
return 0, errors.New("Error: Stream already closed.")
}
// Copy the data locally to avoid any pointer issues.
data := make([]byte, len(inputData))
copy(data, inputData)
// Default to 200 response.
if !s.wroteHeader {
s.WriteHeader(http.StatusOK)
}
// Send any new headers.
s.writeHeader()
// Chunk the response if necessary.
// Data is sent to the flow control to
// ensure that the protocol is followed.
written := 0
for len(data) > common.MAX_DATA_SIZE {
n, err := s.flow.Write(data[:common.MAX_DATA_SIZE])
if err != nil {
return written, err
}
written += n
data = data[common.MAX_DATA_SIZE:]
}
n, err := s.flow.Write(data)
written += n
return written, err
}
// WriteHeader is used to set the HTTP status code.
func (s *ResponseStream) WriteHeader(code int) {
if s.unidirectional {
log.Println("Error: Stream is unidirectional.")
return
}
if s.wroteHeader {
log.Println("Error: Multiple calls to ResponseWriter.WriteHeader.")
return
}
s.wroteHeader = true
s.responseCode = code
s.header.Set(":status", strconv.Itoa(code))
s.header.Set(":version", "HTTP/1.1")
// Create the response SYN_REPLY.
synReply := new(frames.SYN_REPLY)
synReply.StreamID = s.streamID
synReply.Header = make(http.Header)
// Clear the headers that have been sent.
for name, values := range s.header {
for _, value := range values {
synReply.Header.Add(name, value)
}
s.header.Del(name)
}
// These responses have no body, so close the stream now.
if code == 204 || code == 304 || code/100 == 1 {
synReply.Flags = common.FLAG_FIN
s.state.CloseHere()
}
s.output <- synReply
}
/*****************
* io.Closer *
*****************/
func (s *ResponseStream) Close() error {
defer common.Recover()
s.Lock()
s.shutdownOnce.Do(s.shutdown)
s.Unlock()
return nil
}
func (s *ResponseStream) shutdown() {
s.writeHeader()
if s.state != nil {
s.state.Close()
}
if s.flow != nil {
s.flow.Close()
}
if s.requestBody != nil {
s.requestBody.Reset()
s.requestBody = nil
}
s.conn.requestStreamLimit.Close()
s.request = nil
s.handler = nil
s.stop = nil
s.conn.streamsLock.Lock()
delete(s.conn.streams, s.streamID)
s.conn.streamsLock.Unlock()
}
/**********
* Stream *
**********/
func (s *ResponseStream) Conn() common.Conn {
return s.conn
}
func (s *ResponseStream) ReceiveFrame(frame common.Frame) error {
s.Lock()
defer s.Unlock()
if frame == nil {
return errors.New("Error: Nil frame received.")
}
// Process the frame depending on its type.
switch frame := frame.(type) {
case *frames.DATA:
s.requestBody.Write(frame.Data)
s.flow.Receive(frame.Data)
if frame.Flags.FIN() {
select {
case <-s.ready:
default:
close(s.ready)
}
s.state.CloseThere()
}
case *frames.SYN_REPLY:
if frame.Flags.FIN() {
select {
case <-s.ready:
default:
close(s.ready)
}
s.state.CloseThere()
}
case *frames.HEADERS:
return errors.New("Received unexpected HEADERS frame")
case *frames.WINDOW_UPDATE:
err := s.flow.UpdateWindow(frame.DeltaWindowSize)
if err != nil {
reply := new(frames.RST_STREAM)
reply.StreamID = s.streamID
reply.Status = common.RST_STREAM_FLOW_CONTROL_ERROR
s.output <- reply
return err
}
default:
return errors.New(fmt.Sprintf("Received unknown frame of type %T.", frame))
}
return nil
}
func (s *ResponseStream) CloseNotify() <-chan bool {
return s.stop
}
// run is the main control path of
// the stream. It is prepared, the
// registered handler is called,
// and then the stream is cleaned
// up and closed.
func (s *ResponseStream) Run() error {
// Catch any panics.
defer func() {
if v := recover(); v != nil {
if s != nil && s.state != nil && !s.state.Closed() {
log.Printf("Encountered stream error: %v (%[1]T)\n", v)
}
}
}()
// Make sure Request is prepared.
if s.requestBody == nil || s.request.Body == nil {
s.requestBody = new(bytes.Buffer)
s.request.Body = &common.ReadCloser{s.requestBody}
}
// Wait until the full request has been received.
<-s.ready
/***************
*** HANDLER ***
***************/
s.handler.ServeHTTP(s, s.request)
// Make sure any queued data has been sent.
if err := s.flow.Wait(); err != nil {
log.Println(err)
}
// Close the stream with a SYN_REPLY if
// none has been sent, or an empty DATA
// frame, if a SYN_REPLY has been sent
// already.
// If the stream is already closed at
// this end, then nothing happens.
if !s.unidirectional {
if s.state.OpenHere() && !s.wroteHeader {
h := s.header
if h == nil {
h = make(http.Header)
}
h.Set(":status", "200")
h.Set(":version", "HTTP/1.1")
// Create the response SYN_REPLY.
synReply := new(frames.SYN_REPLY)
synReply.Flags = common.FLAG_FIN
synReply.StreamID = s.streamID
synReply.Header = make(http.Header)
for name, values := range h {
for _, value := range values {
synReply.Header.Add(name, value)
}
h.Del(name)
}
s.output <- synReply
} else if s.state.OpenHere() {
// Create the DATA.
data := new(frames.DATA)
data.StreamID = s.streamID
data.Flags = common.FLAG_FIN
data.Data = []byte{}
s.output <- data
}
}
// Clean up state.
s.state.CloseHere()
if s.state.Closed() {
return s.Close()
}
return nil
}
func (s *ResponseStream) State() *common.StreamState {
return s.state
}
func (s *ResponseStream) StreamID() common.StreamID {
return s.streamID
}
func (s *ResponseStream) closed() bool {
if s.conn == nil || s.state == nil || s.handler == nil {
return true
}
select {
case _ = <-s.stop:
return true
default:
return false
}
}
// writeHeader is used to flush HTTP headers.
func (s *ResponseStream) writeHeader() {
if len(s.header) == 0 || s.unidirectional {
return
}
// Create the HEADERS frame.
header := new(frames.HEADERS)
header.StreamID = s.streamID
header.Header = make(http.Header)
// Clear the headers that have been sent.
for name, values := range s.header {
for _, value := range values {
header.Header.Add(name, value)
}
s.header.Del(name)
}
s.output <- header
}
/******************
* PriorityStream *
******************/
func (s *ResponseStream) Priority() common.Priority {
return s.priority
}