/
session.go
448 lines (404 loc) · 9.97 KB
/
session.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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
package spdyframing
import (
"errors"
"fmt"
"io"
"log"
"net/http"
"sync"
)
// See SPDY/3 section 2.6.8.
const defaultInitWnd = 64 * 1024
var (
errClosed = errors.New("closed")
errNotReadable = errors.New("not readable")
errCannotReply = errors.New("cannot reply")
errNotWritable = errors.New("not writable; must reply first")
errFlowControl = errors.New("flow control")
)
type resetError RstStreamStatus
func (e resetError) Error() string {
return fmt.Sprintf("stream was reset: %d", e)
}
// Session represents a session in the low-level SPDY framing layer.
type Session struct {
fr *Framer
wmu sync.Mutex
openMu sync.Mutex // interlock stream id allocation and SYN_STREAM
rstreams map[StreamId]*Stream
nextSynId StreamId
initwnd int32
closing bool
mu sync.RWMutex
// accessed only by read goroutine
lastRecvId StreamId
err error
// not modified
isServer bool
handle func(s *Stream)
done chan bool
}
// Start runs a new session on fr.
// If server is true, the session will initiate even-numbered
// streams and expect odd-numbered streams from the remote
// endpoint; otherwise the reverse. Func handle is called in
// a separate goroutine for every incoming stream.
func Start(fr *Framer, server bool, handle func(*Stream)) *Session {
s := &Session{
fr: fr,
isServer: server,
initwnd: defaultInitWnd,
rstreams: make(map[StreamId]*Stream),
handle: handle,
done: make(chan bool),
}
if server {
s.nextSynId = 2
} else {
s.nextSynId = 1
}
go s.read()
return s
}
// Wait waits until s stops and returns the error, if any.
func (s *Session) Wait() error {
<-s.done
return s.err
}
func (s *Session) set(id SettingsId, val uint32) {
switch id {
case SettingsInitialWindowSize:
if val < 1<<31 {
s.initwnd = int32(val)
}
}
}
// if st.id is 0, add will allocate an outgoing id and set it.
func (s *Session) add(st *Stream) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.closing {
return errors.New("closing")
}
if st.id == 0 {
st.id = s.nextSynId
s.nextSynId += 2
}
s.rstreams[st.id] = st
return nil
}
func (s *Session) maybeRemove(st *Stream) {
s.mu.Lock()
defer s.mu.Unlock()
if st.rclosed && st.wclosed {
if st1 := s.rstreams[st.id]; st1 == st {
delete(s.rstreams, st.id)
}
}
}
func (s *Session) get(id StreamId) *Stream {
s.mu.RLock()
defer s.mu.RUnlock()
return s.rstreams[id]
}
// Run reads and writes frames on s.
func (s *Session) read() {
defer close(s.done)
defer func() {
s.mu.Lock()
s.closing = true
a := make(map[StreamId]*Stream)
for id, st := range s.rstreams {
a[id] = st
}
s.mu.Unlock()
for _, st := range a {
st.rclose(errClosed)
st.wnd.Close(errClosed)
select {
case st.reply <- nil:
default:
}
}
}()
for {
f, err := s.fr.ReadFrame()
if err != nil {
s.err = err
return
}
s.handleRead(f)
}
}
func (s *Session) handleRead(f Frame) {
switch f := f.(type) {
case *SynStreamFrame:
s.handleSynStream(f)
case *SynReplyFrame:
s.handleSynReply(f)
//case *RstStreamFrame:
case *SettingsFrame:
s.handleSettings(f)
case *PingFrame:
go s.writeFrame(f)
//case *GoAwayFrame:
//case *HeadersFrame:
case *WindowUpdateFrame:
s.handleWindowUpdate(f)
//case *CredentialFrame:
case *DataFrame:
s.handleData(f)
default:
log.Println("spdy: ignoring unhandled frame:", f)
}
}
func (s *Session) handleSynStream(f *SynStreamFrame) {
fromServer := f.StreamId%2 == 0
if s.isServer == fromServer || f.StreamId <= s.lastRecvId {
go s.reset(f.StreamId, ProtocolError)
} else {
s.lastRecvId = f.StreamId
st := newStream(s)
st.id = f.StreamId
st.header = f.Headers
err := s.add(st)
if err != nil {
return
}
if f.CFHeader.Flags&ControlFlagUnidirectional != 0 {
st.wclose(errClosed)
}
if f.CFHeader.Flags&ControlFlagFin != 0 {
st.rclose(io.EOF)
}
go s.handle(st)
}
}
func (s *Session) handleSynReply(f *SynReplyFrame) {
st := s.get(f.StreamId)
if st == nil {
go s.reset(f.StreamId, InvalidStream)
return
}
select {
case st.reply <- f.Headers:
default:
go s.reset(f.StreamId, InvalidStream)
return
}
if f.CFHeader.Flags&ControlFlagFin != 0 {
st.rclose(io.EOF)
}
}
func (s *Session) handleSettings(f *SettingsFrame) {
s.mu.Lock()
defer s.mu.Unlock()
for _, v := range f.FlagIdValues {
s.set(v.Id, v.Value)
}
}
func (s *Session) handleWindowUpdate(f *WindowUpdateFrame) {
if st := s.get(f.StreamId); st != nil {
st.handleWindowUpdate(int32(f.DeltaWindowSize))
}
// Ignore WINDOW_UPDATE that comes after we send FLAG_FIN
// or any other invalid stream id. See SPDY/3 section 2.6.8.
}
func (s *Session) handleData(f *DataFrame) {
if st := s.get(f.StreamId); st != nil {
st.handleData(f.Data, f.Flags)
return
}
go s.reset(f.StreamId, InvalidStream)
}
func (s *Session) writeFrame(f Frame) error {
s.wmu.Lock()
defer s.wmu.Unlock()
return s.fr.WriteFrame(f)
}
func (s *Session) reset(id StreamId, status RstStreamStatus) error {
return s.writeFrame(&RstStreamFrame{StreamId: id, Status: status})
}
// Open initiates a new SPDY stream with SYN_STREAM.
// Flags invalid for SYN_STREAM will be silently ignored.
func (s *Session) Open(h http.Header, flag ControlFlags) (*Stream, error) {
st := newStream(s)
st.wready = true
// Avoid a race between calls to writeFrame, below.
// Once add returns, we've assigned the stream id,
// so don't send them out of order.
s.openMu.Lock()
defer s.openMu.Unlock()
err := s.add(st) // sets st.id
if err != nil {
return nil, err
}
if flag&ControlFlagUnidirectional != 0 {
st.rclose(errNotReadable)
} else {
st.reply = make(chan http.Header, 1)
}
if flag&ControlFlagFin != 0 {
st.wclose(errNotWritable)
}
f := &SynStreamFrame{StreamId: st.id, Headers: h}
f.CFHeader.Flags = flag & (ControlFlagUnidirectional | ControlFlagFin)
err = s.writeFrame(f)
if err != nil {
st.rclose(err)
st.wclose(err)
return nil, err
}
return st, nil
}
// Stream represents a stream in the low-level SPDY framing layer.
// It is okay to call Read concurrently with the other methods.
type Stream struct {
id StreamId
sess *Session
pipe pipe // incoming data
rclosed bool
wready bool
wnd semaphore // send window size
wclosed bool
header http.Header // incoming header (SYN_STREAM or SYN_REPLY)
reply chan http.Header
// TODO(kr): unimplemented
// Trailer will be filled in by HEADERS frames received during
// the stream. Once the stream is closed for receiving, Trailer
// is complete and won't be written to again.
//Trailer http.Header
}
func newStream(sess *Session) *Stream {
s := &Stream{sess: sess}
s.pipe.b.buf = make([]byte, defaultInitWnd)
s.pipe.c.L = &s.pipe.m
sess.mu.RLock()
s.wnd.n = sess.initwnd
sess.mu.RUnlock()
s.wnd.c.L = &s.wnd.m
return s
}
// Incoming header, from either SYN_STREAM or SYN_REPLY.
// Returns nil if there is no incoming direction (either
// because s is unidirectional, or because of an error).
func (s *Stream) Header() http.Header {
if s.reply != nil {
s.header = <-s.reply
s.reply = nil
}
return s.header
}
// Reply sends SYN_REPLY with header fields from h.
// It is an error to call Reply twice or to call
// Reply on a stream initiated by the local endpoint.
func (s *Stream) Reply(h http.Header, flag ControlFlags) error {
if s.wready {
return errCannotReply
}
s.wready = true
if flag&ControlFlagFin != 0 {
defer s.wclose(errClosed)
}
f := &SynReplyFrame{StreamId: s.id, Headers: h}
f.CFHeader.Flags = flag
return s.sess.writeFrame(f)
}
// Read reads the contents of DATA frames received on s.
func (s *Stream) Read(p []byte) (n int, err error) {
n, err = s.pipe.Read(p)
s.updateWindow(uint32(n))
return n, err
}
func (s *Stream) updateWindow(delta uint32) error {
if delta < 1 || delta > 1<<31-1 {
return fmt.Errorf("window delta out of range: %d", delta)
}
return s.sess.writeFrame(&WindowUpdateFrame{
StreamId: s.id,
DeltaWindowSize: delta,
})
}
// Write writes p as the contents of one or more DATA frames.
// It is an error to call Write before calling Reply on a stream
// initiated by the remote endpoint.
func (s *Stream) Write(p []byte) (n int, err error) {
for n < len(p) && err == nil {
var c int
c, err = s.writeData(p[n:])
n += c
}
return n, err
}
// writeData writes a single DATA frame containing bytes from p.
func (s *Stream) writeData(p []byte) (int, error) {
if s.wclosed {
return 0, errClosed
}
if !s.wready {
return 0, errNotWritable
}
n, err := s.wnd.Dec(int32(len(p)))
if err != nil {
s.Reset(InternalError)
return 0, err
}
err = s.sess.writeFrame(&DataFrame{StreamId: s.id, Data: p[:n]})
if err != nil {
return 0, err
}
return int(n), nil
}
// Close sends an emtpy DATA or SYN_REPLY frame with FLAG_FIN set.
// This shuts down the writing side of s.
// To close both sides, use Reset.
// It is an error to call Close before calling Reply on a stream
// initiated by the remote endpoint.
func (s *Stream) Close() error {
if s.wclosed {
return errClosed
}
if !s.wready {
return errNotWritable
}
defer s.wclose(errClosed)
return s.sess.writeFrame(&DataFrame{StreamId: s.id, Flags: DataFlagFin})
}
// Reset sends RST_STREAM, closing the stream and indicating
// an error condition.
func (s *Stream) Reset(status RstStreamStatus) error {
defer s.wclose(resetError(status))
defer s.rclose(resetError(status))
return s.sess.reset(s.id, status)
}
func (s *Stream) handleWindowUpdate(delta int32) {
if err := s.wnd.Inc(delta); err != nil {
s.sess.reset(s.id, FlowControlError)
s.wnd.Close(errFlowControl)
s.rclose(errFlowControl)
}
}
func (s *Stream) handleData(p []byte, flag DataFlags) {
if s.rclosed {
go s.sess.reset(s.id, StreamAlreadyClosed)
return
}
switch _, err := s.pipe.Write(p); {
case err != nil:
s.wnd.Close(errFlowControl)
s.rclose(errFlowControl)
s.sess.reset(s.id, FlowControlError)
case flag&DataFlagFin != 0:
s.rclose(io.EOF)
}
}
func (s *Stream) rclose(err error) {
s.rclosed = true
s.pipe.Close(err)
s.sess.maybeRemove(s)
}
func (s *Stream) wclose(err error) {
s.wclosed = true
s.wnd.Close(err)
s.sess.maybeRemove(s)
}