Debian Codegraph @

proto/session.go

raw
1 package proto
2
3 import (
4 "fmt"
5 "github.com/inconshreveable/muxado/proto/frame"
6 "io"
7 "net"
8 "reflect"
9 "sync"
10 "sync/atomic"
11 "time"
12 )
13
14 const (
15 defaultWindowSize = 0x10000 // 64KB
16 defaultAcceptQueueDepth = 100
17 MinExtensionType = 0xFFFFFFFF - 0x100 // 512 extensions
18 )
19
20 // private interface for Sessions to call Streams
21 type stream interface {
22 IStream
23 handleStreamData(*frame.RStreamData)
24 handleStreamWndInc(*frame.RStreamWndInc)
25 handleStreamRst(*frame.RStreamRst)
26 closeWith(error)
27 }
28
29 // for extensions
30 type ExtAccept func() (IStream, error)
31 type Extension interface {
32 Start(ISession, ExtAccept) frame.StreamType
33 }
34
35 type deadReason struct {
36 errorCode frame.ErrorCode
37 err error
38 remoteDebug []byte
39 }
40
41 // factory function that creates new streams
42 type streamFactory func(id frame.StreamId, priority frame.StreamPriority, streamType frame.StreamType, finLocal bool, finRemote bool, windowSize uint32, sess session) stream
43
44 // checks the parity of a stream id (local vs remote, client vs server)
45 type parityFn func(frame.StreamId) bool
46
47 // state for each half of the session (remote and local)
48 type halfState struct {
49 goneAway int32 // true if that half of the stream has gone away
50 lastId uint32 // last id used/seen from one half of the session
51 }
52
53 // Session implements a simple streaming session manager. It has the following characteristics:
54 //
55 // - When closing the Session, it does not linger, all pending write operations will fail immediately.
56 // - It completely ignores stream priority when processing and writing frames
57 // - It offers no customization of settings like window size/ping time
58 type Session struct {
59 conn net.Conn // connection the transport is running over
60 transport frame.Transport // transport
61 streams StreamMap // all active streams
62 local halfState // client state
63 remote halfState // server state
64 syn *frame.WStreamSyn // STREAM_SYN frame for opens
65 wr sync.Mutex // synchronization when writing frames
66 accept chan stream // new streams opened by the remote
67 diebit int32 // true if we're dying
68 remoteDebug []byte // debugging data sent in the remote's GoAway frame
69 defaultWindowSize uint32 // window size when creating new streams
70 newStream streamFactory // factory function to make new streams
71 dead chan deadReason // dead
72 isLocal parityFn // determines if a stream id is local or remote
73 exts map[frame.StreamType]chan stream // map of extension stream type -> accept channel for the extension
74 }
75
76 func NewSession(conn net.Conn, newStream streamFactory, isClient bool, exts []Extension) ISession {
77 sess := &Session{
78 conn: conn,
79 transport: frame.NewBasicTransport(conn),
80 streams: NewConcurrentStreamMap(),
81 local: halfState{lastId: 0},
82 remote: halfState{lastId: 0},
83 syn: frame.NewWStreamSyn(),
84 diebit: 0,
85 defaultWindowSize: defaultWindowSize,
86 accept: make(chan stream, defaultAcceptQueueDepth),
87 newStream: newStream,
88 dead: make(chan deadReason, 1), // don't block die() if there is no Wait call
89 exts: make(map[frame.StreamType]chan stream),
90 }
91
92 if isClient {
93 sess.isLocal = sess.isClient
94 sess.local.lastId += 1
95 } else {
96 sess.isLocal = sess.isServer
97 sess.remote.lastId += 1
98 }
99
100 for _, ext := range exts {
101 sess.startExtension(ext)
102 }
103
104 go sess.reader()
105
106 return sess
107 }
108
109 ////////////////////////////////
110 // public interface
111 ////////////////////////////////
112
113 func (s *Session) Open() (IStream, error) {
114 return s.OpenStream(0, 0, false)
115 }
116
117 func (s *Session) OpenStream(priority frame.StreamPriority, streamType frame.StreamType, fin bool) (ret IStream, err error) {
118 // check if the remote has gone away
119 if atomic.LoadInt32(&s.remote.goneAway) == 1 {
120 return nil, fmt.Errorf("Failed to create stream, remote has gone away.")
121 }
122
123 // this lock prevents the following race:
124 // goroutine1 goroutine2
125 // - inc stream id
126 // - inc stream id
127 // - send streamsyn
128 // - send streamsyn
129 s.wr.Lock()
130
131 // get the next id we can use
132 nextId := frame.StreamId(atomic.AddUint32(&s.local.lastId, 2))
133
134 // make the stream
135 str := s.newStream(nextId, priority, streamType, fin, false, s.defaultWindowSize, s)
136
137 // add to to the stream map
138 s.streams.Set(nextId, str)
139
140 // write the frame
141 if err = s.syn.Set(nextId, priority, streamType, fin); err != nil {
142 s.wr.Unlock()
143 s.die(frame.InternalError, err)
144 return
145 }
146
147 if err = s.transport.WriteFrame(s.syn); err != nil {
148 s.wr.Unlock()
149 s.die(frame.InternalError, err)
150 return
151 }
152
153 s.wr.Unlock()
154 return str, nil
155 }
156
157 func (s *Session) Accept() (str IStream, err error) {
158 var ok bool
159 if str, ok = <-s.accept; !ok {
160 return nil, fmt.Errorf("Session closed")
161 }
162
163 return
164 }
165
166 func (s *Session) Kill() error {
167 return s.transport.Close()
168 }
169
170 func (s *Session) Close() error {
171 return s.die(frame.NoError, fmt.Errorf("Session Close()"))
172 }
173
174 func (s *Session) GoAway(errorCode frame.ErrorCode, debug []byte) (err error) {
175 if !atomic.CompareAndSwapInt32(&s.local.goneAway, 0, 1) {
176 return fmt.Errorf("Already sent GoAway!")
177 }
178
179 s.wr.Lock()
180 f := frame.NewWGoAway()
181 remoteId := frame.StreamId(atomic.LoadUint32(&s.remote.lastId))
182 if err = f.Set(remoteId, errorCode, debug); err != nil {
183 s.wr.Unlock()
184 s.die(frame.InternalError, err)
185 return
186 }
187
188 if err = s.transport.WriteFrame(f); err != nil {
189 s.wr.Unlock()
190 s.die(frame.InternalError, err)
191 return
192 }
193
194 s.wr.Unlock()
195 return
196 }
197
198 func (s *Session) LocalAddr() net.Addr {
199 return s.conn.LocalAddr()
200 }
201
202 func (s *Session) RemoteAddr() net.Addr {
203 return s.conn.RemoteAddr()
204 }
205
206 func (s *Session) Wait() (frame.ErrorCode, error, []byte) {
207 reason := <-s.dead
208 return reason.errorCode, reason.err, reason.remoteDebug
209 }
210
211 ////////////////////////////////
212 // private interface for streams
213 ////////////////////////////////
214
215 // removeStream removes a stream from this session's stream registry
216 //
217 // It does not error if the stream is not present
218 func (s *Session) removeStream(id frame.StreamId) {
219 s.streams.Delete(id)
220 return
221 }
222
223 // writeFrame writes the given frame to the transport and returns the error from the write operation
224 func (s *Session) writeFrame(f frame.WFrame, dl time.Time) (err error) {
225 s.wr.Lock()
226 s.conn.SetWriteDeadline(dl)
227 err = s.transport.WriteFrame(f)
228 s.wr.Unlock()
229 return
230 }
231
232 // die closes the session cleanly with the given error and protocol error code
233 func (s *Session) die(errorCode frame.ErrorCode, err error) error {
234 // only one shutdown ever happens
235 if !atomic.CompareAndSwapInt32(&s.diebit, 0, 1) {
236 return fmt.Errorf("Shutdown already in progress")
237 }
238
239 // send a go away frame
240 s.GoAway(errorCode, []byte(err.Error()))
241
242 // now we're safe to stop accepting incoming connections
243 close(s.accept)
244
245 // we cleaned up as best as possible, close the transport
246 s.transport.Close()
247
248 // notify all of the streams that we're closing
249 s.streams.Each(func(id frame.StreamId, str stream) {
250 str.closeWith(fmt.Errorf("Session closed"))
251 })
252
253 s.dead <- deadReason{errorCode, err, s.remoteDebug}
254
255 return nil
256 }
257
258 ////////////////////////////////
259 // internal methods
260 ////////////////////////////////
261
262 // reader() reads frames from the underlying transport and handles passes them to handleFrame
263 func (s *Session) reader() {
264 defer s.recoverPanic("reader()")
265
266 // close all of the extension accept channels when we're done
267 // we do this here instead of in die() since otherwise it wouldn't
268 // be safe to access s.exts
269 defer func() {
270 for _, extAccept := range s.exts {
271 close(extAccept)
272 }
273 }()
274
275 for {
276 f, err := s.transport.ReadFrame()
277 if err != nil {
278 // if we fail to read a frame, terminate the session
279 _, ok := err.(*frame.FramingError)
280 if ok {
281 s.die(frame.ProtocolError, err)
282 } else {
283 s.die(frame.InternalError, err)
284 }
285 return
286 }
287
288 s.handleFrame(f)
289 }
290 }
291
292 func (s *Session) handleFrame(rf frame.RFrame) {
293 switch f := rf.(type) {
294 case *frame.RStreamSyn:
295 // if we're going away, refuse new streams
296 if atomic.LoadInt32(&s.local.goneAway) == 1 {
297 rstF := frame.NewWStreamRst()
298 rstF.Set(f.StreamId(), frame.RefusedStream)
299 go s.writeFrame(rstF, time.Time{})
300 return
301 }
302
303 if f.StreamId() <= frame.StreamId(atomic.LoadUint32(&s.remote.lastId)) {
304 s.die(frame.ProtocolError, fmt.Errorf("Stream id %d is less than last remote id.", f.StreamId()))
305 return
306 }
307
308 if s.isLocal(f.StreamId()) {
309 s.die(frame.ProtocolError, fmt.Errorf("Stream id has wrong parity for remote endpoint: %d", f.StreamId()))
310 return
311 }
312
313 // update last remote id
314 atomic.StoreUint32(&s.remote.lastId, uint32(f.StreamId()))
315
316 // make the new stream
317 str := s.newStream(f.StreamId(), f.StreamPriority(), f.StreamType(), false, f.Fin(), s.defaultWindowSize, s)
318
319 // add it to the stream map
320 s.streams.Set(f.StreamId(), str)
321
322 // check if this is an extension stream
323 if f.StreamType() >= MinExtensionType {
324 extAccept, ok := s.exts[f.StreamType()]
325 if !ok {
326 // Extension type of stream not registered
327 fRst := frame.NewWStreamRst()
328 if err := fRst.Set(f.StreamId(), frame.StreamClosed); err != nil {
329 s.die(frame.InternalError, err)
330 }
331
332 s.wr.Lock()
333 defer s.wr.Unlock()
334 s.transport.WriteFrame(fRst)
335 } else {
336 extAccept <- str
337 }
338
339 return
340 }
341
342 // put the new stream on the accept channel
343 s.accept <- str
344
345 case *frame.RStreamData:
346 if str := s.getStream(f.StreamId()); str != nil {
347 str.handleStreamData(f)
348 } else {
349 // if we get a data frame on a non-existent connection, we still
350 // need to read out the frame body so that the stream stays in a
351 // good state. read the payload into a throwaway buffer
352 discard := make([]byte, f.Length())
353 io.ReadFull(f.Reader(), discard)
354
355 // DATA frames on closed connections are just stream-level errors
356 fRst := frame.NewWStreamRst()
357 if err := fRst.Set(f.StreamId(), frame.StreamClosed); err != nil {
358 s.die(frame.InternalError, err)
359 }
360
361 s.wr.Lock()
362 defer s.wr.Unlock()
363 s.transport.WriteFrame(fRst)
364 return
365 }
366
367 case *frame.RStreamRst:
368 // delegate to the stream to handle these frames
369 if str := s.getStream(f.StreamId()); str != nil {
370 str.handleStreamRst(f)
371 }
372 case *frame.RStreamWndInc:
373 // delegate to the stream to handle these frames
374 if str := s.getStream(f.StreamId()); str != nil {
375 str.handleStreamWndInc(f)
376 }
377
378 case *frame.RGoAway:
379 atomic.StoreInt32(&s.remote.goneAway, 1)
380 s.remoteDebug = f.Debug()
381
382 lastId := f.LastStreamId()
383 s.streams.Each(func(id frame.StreamId, str stream) {
384 // close all streams that we opened above the last handled id
385 if s.isLocal(str.Id()) && str.Id() > lastId {
386 str.closeWith(fmt.Errorf("Remote is going away"))
387 }
388 })
389
390 default:
391 s.die(frame.ProtocolError, fmt.Errorf("Unrecognized frame type: %v", reflect.TypeOf(f)))
392 return
393 }
394 }
395
396 func (s *Session) recoverPanic(prefix string) {
397 if r := recover(); r != nil {
398 s.die(frame.InternalError, fmt.Errorf("%s panic: %v", prefix, r))
399 }
400 }
401
402 func (s *Session) getStream(id frame.StreamId) (str stream) {
403 // decide if this id is in the "idle" state (i.e. greater than any we've seen for that parity)
404 var lastId *uint32
405 if s.isLocal(id) {
406 lastId = &s.local.lastId
407 } else {
408 lastId = &s.remote.lastId
409 }
410
411 if uint32(id) > atomic.LoadUint32(lastId) {
412 s.die(frame.ProtocolError, fmt.Errorf("%d is an invalid, unassigned stream id", id))
413 }
414
415 // find the stream in the stream map
416 var ok bool
417 if str, ok = s.streams.Get(id); !ok {
418 return nil
419 }
420
421 return
422 }
423
424 // check if a stream id is for a client stream. client streams are odd
425 func (s *Session) isClient(id frame.StreamId) bool {
426 return uint32(id)&1 == 1
427 }
428
429 func (s *Session) isServer(id frame.StreamId) bool {
430 return !s.isClient(id)
431 }
432
433 //////////////////////////////////////////////
434 // session extensions
435 //////////////////////////////////////////////
436 func (s *Session) startExtension(ext Extension) {
437 accept := make(chan stream)
438 extAccept := func() (IStream, error) {
439 s, ok := <-accept
440 if !ok {
441 return nil, fmt.Errorf("Failed to accept connection, shutting down")
442 }
443
444 return s, nil
445 }
446
447 extType := ext.Start(s, extAccept)
448 s.exts[extType] = accept
449 }
450
451 //////////////////////////////////////////////
452 // net adaptors
453 //////////////////////////////////////////////
454 func (s *Session) NetDial(_, _ string) (net.Conn, error) {
455 str, err := s.Open()
456 return net.Conn(str), err
457 }
458
459 func (s *Session) NetListener() net.Listener {
460 return &netListenerAdaptor{s}
461 }
462
463 type netListenerAdaptor struct {
464 *Session
465 }
466
467 func (a *netListenerAdaptor) Addr() net.Addr {
468 return a.LocalAddr()
469 }
470
471 func (a *netListenerAdaptor) Accept() (net.Conn, error) {
472 str, err := a.Session.Accept()
473 return net.Conn(str), err
474 }