~trn/gfsmux

ref: 2106.0.0 gfsmux/session.go -rw-r--r-- 12.8 KiB
753dd037 — Jeffrey H. Johnson Update dependencies 3 months ago
                                                                                
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
package gfsmux

import (
	"container/heap"
	"encoding/binary"
	"errors"
	"io"
	"net"
	"sync"
	"sync/atomic"
	"time"
)

const (
	defaultAcceptBacklog = 2048
)

var (
	// ErrInvalidProtocol version or bag negotiation.
	ErrInvalidProtocol = errors.New(
		"invalid protocol",
	)
	// ErrConsumed protocol error, indicates desync
	ErrConsumed = errors.New(
		"peer consumed more than sent",
	)
	// ErrGoAway overflow condition, restart it all.
	ErrGoAway = errors.New(
		"stream id overflows, should start a new Connection",
	)
	// ErrTimeout ...
	ErrTimeout = &timeoutError{}
	// ErrWouldBlock error for invalid blocking I/O operating
	ErrWouldBlock = errors.New(
		"operation would block on IO",
	)
)

var _ net.Error = &timeoutError{}

type timeoutError struct{}

func (
	e *timeoutError,
) Error() string {
	return "timeout"
}

func (
	e *timeoutError,
) Timeout() bool {
	return true
}

func (
	e *timeoutError,
) Temporary() bool {
	return true
}

// WriteRequest ...
type WriteRequest struct {
	Prio   uint64
	frame  Frame
	result chan writeResult
}

type writeResult struct {
	n   int
	err error
}

type buffersWriter interface {
	WriteBuffers(
		v [][]byte,
	) (
		n int,
		err error,
	)
}

// Session defines a multiplexed Connection for streams
type Session struct {
	Conn io.ReadWriteCloser

	Config           *Config
	nextStreamID     uint32 // next stream identifier
	nextStreamIDLock sync.Mutex

	bucket       int32         // token bucket
	bucketNotify chan struct{} // used for waiting for tokens

	streams    map[uint32]*Stream // all streams in this session
	streamLock sync.Mutex         // locks streams

	die     chan struct{} // flag session has died
	dieOnce sync.Once

	// socket error handling
	socketReadError      atomic.Value
	socketWriteError     atomic.Value
	chSocketReadError    chan struct{}
	chSocketWriteError   chan struct{}
	socketReadErrorOnce  sync.Once
	socketWriteErrorOnce sync.Once

	// smux protocol errors
	protoError     atomic.Value
	chProtoError   chan struct{}
	protoErrorOnce sync.Once

	chAccepts chan *Stream

	dataReady int32 // flag data has arrived

	goAway int32 // flag id exhausted

	deadline atomic.Value

	shaper chan WriteRequest // a shaper for writing
	writes chan WriteRequest
}

func newSession(
	Config *Config,
	Conn io.ReadWriteCloser,
	client bool,
) *Session {
	s := new(
		Session,
	)
	s.die = make(
		chan struct{},
	)
	s.Conn = Conn
	s.Config = Config
	s.streams = make(
		map[uint32]*Stream,
	)
	s.chAccepts = make(
		chan *Stream,
		defaultAcceptBacklog,
	)
	s.bucket = int32(
		Config.MaxReceiveBuffer,
	)
	s.bucketNotify = make(
		chan struct{},
		1,
	)
	s.shaper = make(
		chan WriteRequest,
	)
	s.writes = make(
		chan WriteRequest,
	)
	s.chSocketReadError = make(
		chan struct{},
	)
	s.chSocketWriteError = make(
		chan struct{},
	)
	s.chProtoError = make(
		chan struct{},
	)

	if client {
		s.nextStreamID = 1
	} else {
		s.nextStreamID = 0
	}

	go s.shaperLoop()
	go s.recvLoop()
	go s.sendLoop()
	if !Config.KeepAliveDisabled {
		go s.keepalive()
	}
	return s
}

// OpenStream is used to create a new stream
func (
	s *Session,
) OpenStream() (
	*Stream,
	error,
) {
	if s.IsClosed() {
		return nil, io.ErrClosedPipe
	}

	// generate stream id
	s.nextStreamIDLock.Lock()
	if s.goAway > 0 {
		s.nextStreamIDLock.Unlock()
		return nil, ErrGoAway
	}

	s.nextStreamID += 2
	Sid := s.nextStreamID
	if Sid == Sid%2 { // stream-id overflows
		s.goAway = 1
		s.nextStreamIDLock.Unlock()
		return nil, ErrGoAway
	}
	s.nextStreamIDLock.Unlock()

	stream := newStream(
		Sid,
		s.Config.MaxFrameSize,
		s,
	)

	if _, err := s.WriteFrame(
		NewFrame(
			byte(s.Config.Version),
			CmdSyn,
			Sid,
		),
	); err != nil {
		return nil, err
	}

	s.streamLock.Lock()
	defer s.streamLock.Unlock()
	select {
	case <-s.chSocketReadError:
		return nil, s.socketReadError.Load().(error)
	case <-s.chSocketWriteError:
		return nil, s.socketWriteError.Load().(error)
	case <-s.die:
		return nil, io.ErrClosedPipe
	default:
		s.streams[Sid] = stream
		return stream, nil
	}
}

// Open returns a generic ReadWriteCloser
func (
	s *Session,
) Open() (
	io.ReadWriteCloser,
	error,
) {
	return s.OpenStream()
}

// AcceptStream is used to block until the next available stream
// is ready to be accepted.
func (
	s *Session,
) AcceptStream() (
	*Stream,
	error,
) {
	var deadline <-chan time.Time
	if d, ok := s.deadline.Load().(time.Time); ok && !d.IsZero() {
		timer := time.NewTimer(
			time.Until(
				d,
			),
		)
		defer timer.Stop()
		deadline = timer.C
	}

	select {
	case stream := <-s.chAccepts:
		return stream, nil
	case <-deadline:
		return nil, ErrTimeout
	case <-s.chSocketReadError:
		return nil, s.socketReadError.Load().(error)
	case <-s.chProtoError:
		return nil, s.protoError.Load().(error)
	case <-s.die:
		return nil, io.ErrClosedPipe
	}
}

// Accept Returns a generic ReadWriteCloser instead of smux.Stream
func (
	s *Session,
) Accept() (
	io.ReadWriteCloser,
	error,
) {
	return s.AcceptStream()
}

// Close is used to close the session and all streams.
func (
	s *Session,
) Close() error {
	var once bool
	s.dieOnce.Do(func() {
		close(
			s.die,
		)
		once = true
	})

	if once {
		s.streamLock.Lock()
		for k := range s.streams {
			s.streams[k].sessionClose()
		}
		s.streamLock.Unlock()
		return s.Conn.Close()
	}
	return io.ErrClosedPipe
}

// notifyBucket notifies recvLoop that bucket is available
func (
	s *Session,
) notifyBucket() {
	select {
	case s.bucketNotify <- struct{}{}:
	default:
	}
}

func (
	s *Session,
) notifyReadError(
	err error,
) {
	s.socketReadErrorOnce.Do(func() {
		s.socketReadError.Store(
			err,
		)
		close(
			s.chSocketReadError,
		)
	})
}

func (
	s *Session,
) notifyWriteError(
	err error,
) {
	s.socketWriteErrorOnce.Do(func() {
		s.socketWriteError.Store(
			err,
		)
		close(
			s.chSocketWriteError,
		)
	})
}

func (
	s *Session,
) notifyProtoError(
	err error,
) {
	s.protoErrorOnce.Do(func() {
		s.protoError.Store(
			err,
		)
		close(
			s.chProtoError,
		)
	})
}

// IsClosed does a safe check to see if we have shutdown
func (
	s *Session,
) IsClosed() bool {
	select {
	case <-s.die:
		return true
	default:
		return false
	}
}

// NumStreams returns the number of currently open streams
func (
	s *Session,
) NumStreams() int {
	if s.IsClosed() {
		return 0
	}
	s.streamLock.Lock()
	defer s.streamLock.Unlock()
	return len(
		s.streams,
	)
}

// SetDeadline sets a deadline used by Accept* calls.
// A zero time value disables the deadline.
func (
	s *Session,
) SetDeadline(
	t time.Time,
) error {
	s.deadline.Store(
		t,
	)
	return nil
}

// LocalAddr satisfies net.Conn interface
func (
	s *Session,
) LocalAddr() net.Addr {
	if ts, ok := s.Conn.(interface {
		LocalAddr() net.Addr
	}); ok {
		return ts.LocalAddr()
	}
	return nil
}

// RemoteAddr satisfies net.Conn interface
func (
	s *Session,
) RemoteAddr() net.Addr {
	if ts, ok := s.Conn.(interface {
		RemoteAddr() net.Addr
	}); ok {
		return ts.RemoteAddr()
	}
	return nil
}

// notify the session that a stream has closed
func (
	s *Session,
) streamClosed(
	Sid uint32,
) {
	s.streamLock.Lock()
	// return remaining tokens to the bucket
	if n := s.streams[Sid].recycleTokens(); n > 0 {
		if atomic.AddInt32(
			&s.bucket,
			int32(n),
		) > 0 {
			s.notifyBucket()
		}
	}
	delete(
		s.streams,
		Sid,
	)
	s.streamLock.Unlock()
}

// returnTokens is called by stream to return token after read
func (
	s *Session,
) returnTokens(
	n int,
) {
	if atomic.AddInt32(
		&s.bucket,
		int32(n),
	) > 0 {
		s.notifyBucket()
	}
}

// recvLoop keeps on reading from underlying Connection if tokens are available
func (
	s *Session,
) recvLoop() {
	var hdr rawHeader
	var updHdr updHeader

	for {
		for atomic.LoadInt32(
			&s.bucket,
		) <= 0 && !s.IsClosed() {
			select {
			case <-s.bucketNotify:
			case <-s.die:
				return
			}
		}

		// read header first
		if _, err := io.ReadFull(
			s.Conn,
			hdr[:],
		); err == nil {
			atomic.StoreInt32(
				&s.dataReady,
				1,
			)
			if hdr.Version() != byte(
				s.Config.Version,
			) {
				s.notifyProtoError(
					ErrInvalidProtocol,
				)
				return
			}
			Sid := hdr.StreamID()
			switch hdr.Cmd() {
			case CmdNop:
			case CmdSyn:
				s.streamLock.Lock()
				if _, ok := s.streams[Sid]; !ok {
					stream := newStream(
						Sid,
						s.Config.MaxFrameSize,
						s,
					)
					s.streams[Sid] = stream
					select {
					case s.chAccepts <- stream:
					case <-s.die:
					}
				}
				s.streamLock.Unlock()
			case CmdFin:
				s.streamLock.Lock()
				if stream, ok := s.streams[Sid]; ok {
					stream.fin()
					stream.notifyReadEvent()
				}
				s.streamLock.Unlock()
			case CmdPsh:
				if hdr.Length() > 0 {
					newbuf := defaultAllocator.Get(
						int(hdr.Length()),
					)
					if written, err := io.ReadFull(
						s.Conn,
						newbuf,
					); err == nil {
						s.streamLock.Lock()
						if stream, ok := s.streams[Sid]; ok {
							stream.pushBytes(
								newbuf,
							)
							atomic.AddInt32(
								&s.bucket,
								-int32(written),
							)
							stream.notifyReadEvent()
						}
						s.streamLock.Unlock()
					} else {
						s.notifyReadError(
							err,
						)
						return
					}
				}
			case CmdUpd:
				if _, err := io.ReadFull(
					s.Conn,
					updHdr[:],
				); err == nil {
					s.streamLock.Lock()
					if stream, ok := s.streams[Sid]; ok {
						stream.update(
							updHdr.Consumed(),
							updHdr.Window(),
						)
					}
					s.streamLock.Unlock()
				} else {
					s.notifyReadError(
						err,
					)
					return
				}
			default:
				s.notifyProtoError(
					ErrInvalidProtocol,
				)
				return
			}
		} else {
			s.notifyReadError(
				err,
			)
			return
		}
	}
}

func (
	s *Session,
) keepalive() {
	tickerPing := time.NewTicker(
		s.Config.KeepAliveInterval,
	)
	tickerTimeout := time.NewTicker(
		s.Config.KeepAliveTimeout,
	)
	defer tickerPing.Stop()
	defer tickerTimeout.Stop()
	for {
		select {
		case <-tickerPing.C:
			s.WriteFrameInternal(
				NewFrame(
					byte(s.Config.Version),
					CmdNop,
					0,
				),
				tickerPing.C,
				0,
			)
			s.notifyBucket() // force a signal to the recvLoop
		case <-tickerTimeout.C:
			if !atomic.CompareAndSwapInt32(
				&s.dataReady,
				1,
				0,
			) {
				// recvLoop may block while bucket is 0, in this case,
				// session should not be closed.
				if atomic.LoadInt32(
					&s.bucket,
				) > 0 {
					s.Close()
					return
				}
			}
		case <-s.die:
			return
		}
	}
}

// shaper shapes the sending sequence among streams
func (
	s *Session,
) shaperLoop() {
	var reqs ShaperHeap
	var next WriteRequest
	var chWrite chan WriteRequest

	for {
		if len(
			reqs,
		) > 0 {
			chWrite = s.writes
			next = heap.Pop(&reqs).(WriteRequest)
		} else {
			chWrite = nil
		}

		select {
		case <-s.die:
			return
		case r := <-s.shaper:
			if chWrite != nil { // next is valid, reshape
				heap.Push(
					&reqs,
					next,
				)
			}
			heap.Push(
				&reqs,
				r,
			)
		case chWrite <- next:
		}
	}
}

func (
	s *Session,
) sendLoop() {
	var buf []byte
	var n int
	var err error
	var vec [][]byte // vector for writeBuffers

	bw, ok := s.Conn.(buffersWriter)
	if ok {
		buf = make([]byte, HeaderSize)
		vec = make([][]byte, 2)
	} else {
		buf = make([]byte, (1<<16)+HeaderSize)
	}

	for {
		select {
		case <-s.die:
			return
		case request := <-s.writes:
			buf[0] = request.frame.Ver
			buf[1] = request.frame.Cmd
			binary.LittleEndian.PutUint16(
				buf[2:],
				uint16(
					len(
						request.frame.Data,
					),
				),
			)
			binary.LittleEndian.PutUint32(
				buf[4:],
				request.frame.Sid,
			)

			if len(
				vec,
			) > 0 {
				vec[0] = buf[:HeaderSize]
				vec[1] = request.frame.Data
				n, err = bw.WriteBuffers(
					vec,
				)
			} else {
				copy(
					buf[HeaderSize:],
					request.frame.Data,
				)
				n, err = s.Conn.Write(
					buf[:HeaderSize+len(request.frame.Data)],
				)
			}

			n -= HeaderSize
			if n < 0 {
				n = 0
			}

			result := writeResult{
				n:   n,
				err: err,
			}

			request.result <- result
			close(
				request.result,
			)

			// store Conn error
			if err != nil {
				s.notifyWriteError(
					err,
				)
				return
			}
		}
	}
}

// WriteFrame writes the frame to the underlying Connection
// and returns the number of bytes written if successful
func (
	s *Session,
) WriteFrame(
	f Frame,
) (
	n int,
	err error,
) {
	return s.WriteFrameInternal(
		f,
		nil,
		0,
	)
}

// WriteFrameInternal is to support deadline used in keepalive
func (
	s *Session,
) WriteFrameInternal(
	f Frame,
	deadline <-chan time.Time,
	Prio uint64,
) (
	int,
	error,
) {
	req := WriteRequest{
		Prio:  Prio,
		frame: f,
		result: make(
			chan writeResult,
			1,
		),
	}
	select {
	case s.shaper <- req:
	case <-s.die:
		return 0, io.ErrClosedPipe
	case <-s.chSocketWriteError:
		return 0, s.socketWriteError.Load().(error)
	case <-deadline:
		return 0, ErrTimeout
	}

	select {
	case result := <-req.result:
		return result.n, result.err
	case <-s.die:
		return 0, io.ErrClosedPipe
	case <-s.chSocketWriteError:
		return 0, s.socketWriteError.Load().(error)
	case <-deadline:
		return 0, ErrTimeout
	}
}