~trn/gfsmux

ref: 552547081df14ae563f5c8a8e52cad483fe581da gfsmux/stream.go -rw-r--r-- 12.7 KiB
55254708 — Jeffrey H. Johnson Update dependencies 4 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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
package gfsmux

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

// Stream implements net.Conn
type Stream struct {
	id   uint32
	sess *Session

	// slice heads kept for recycle
	buffers [][]byte
	heads   [][]byte

	bufferLock sync.Mutex
	frameSize  int

	// notify a read event
	chReadEvent chan struct{}

	// flag the stream has closed
	die     chan struct{}
	dieOnce sync.Once

	// FIN command
	chFinEvent   chan struct{}
	finEventOnce sync.Once

	// deadlines
	readDeadline  atomic.Value
	writeDeadline atomic.Value

	// per stream sliding window control
	numRead    uint32 // number of consumed bytes
	numWritten uint32 // count num of bytes written
	incr       uint32 // counting for sending

	// UPD (Update) command
	peerConsumed uint32        // num of bytes remote peer has consumed
	peerWindow   uint32        // peer window, init to 256KB, updated by peer
	chUpdate     chan struct{} // notify remote data consumed and window update
}

// newStream initiates a Stream struct
func newStream(
	id uint32,
	frameSize int,
	sess *Session,
) *Stream {
	s := new(
		Stream,
	)
	s.id = id
	s.chReadEvent = make(
		chan struct{},
		1,
	)
	s.chUpdate = make(
		chan struct{},
		1,
	)
	s.frameSize = frameSize
	s.sess = sess
	s.die = make(
		chan struct{},
	)
	s.chFinEvent = make(
		chan struct{},
	)
	s.peerWindow = initialPeerWindow // set to initial window size
	return s
}

// ID returns the unique stream ID.
func (
	s *Stream,
) ID() uint32 {
	return s.id
}

// Read implements net.Conn
func (
	s *Stream,
) Read(
	b []byte,
) (
	n int,
	err error,
) {
	for {
		n, err = s.tryRead(
			b,
		)
		if err == ErrWouldBlock {
			if ew := s.waitRead(); ew != nil {
				return 0, ew
			}
		} else {
			return n, err
		}
	}
}

// tryRead is the nonblocking version of Read
func (
	s *Stream,
) tryRead(
	b []byte,
) (
	n int,
	err error,
) {
	if s.sess.Config.Version == 2 {
		return s.tryReadv2(
			b,
		)
	}

	if len(
		b,
	) == 0 {
		return 0, nil
	}

	s.bufferLock.Lock()
	if len(
		s.buffers,
	) > 0 {
		n = copy(
			b,
			s.buffers[0],
		)
		s.buffers[0] = s.buffers[0][n:]
		if len(
			s.buffers[0],
		) == 0 {
			s.buffers[0] = nil
			s.buffers = s.buffers[1:]
			defaultAllocator.Put(
				s.heads[0],
			)
			s.heads = s.heads[1:]
		}
	}
	s.bufferLock.Unlock()

	if n > 0 {
		s.sess.returnTokens(
			n,
		)
		return n, nil
	}

	select {
	case <-s.die:
		return 0, io.EOF
	default:
		return 0, ErrWouldBlock
	}
}

func (
	s *Stream,
) tryReadv2(
	b []byte,
) (
	n int,
	err error,
) {
	if len(
		b,
	) == 0 {
		return 0, nil
	}

	var notifyConsumed uint32
	s.bufferLock.Lock()
	if len(
		s.buffers,
	) > 0 {
		n = copy(
			b,
			s.buffers[0],
		)
		s.buffers[0] = s.buffers[0][n:]
		if len(
			s.buffers[0],
		) == 0 {
			s.buffers[0] = nil
			s.buffers = s.buffers[1:]
			// full recycle
			defaultAllocator.Put(
				s.heads[0],
			)
			s.heads = s.heads[1:]
		}
	}

	// ideally, if more than half of buffer has consumed, send read ack to
	// peer based on round-trip time of ACK, continuous flowing data won't
	// slow down because of waiting for ACK, as long as the consumer keeps on
	// reading data s.numRead == n ... also notify window at the first read
	s.numRead += uint32(n)
	s.incr += uint32(n)
	if s.incr >= uint32(s.sess.Config.MaxStreamBuffer/2) || s.numRead == uint32(n) {
		notifyConsumed = s.numRead
		s.incr = 0
	}
	s.bufferLock.Unlock()

	if n > 0 {
		s.sess.returnTokens(
			n,
		)
		if notifyConsumed > 0 {
			err := s.sendWindowUpdate(
				notifyConsumed,
			)
			return n, err
		}
		return n, nil
	}

	select {
	case <-s.die:
		return 0, io.EOF
	default:
		return 0, ErrWouldBlock
	}
}

// WriteTo implements io.WriteTo
func (
	s *Stream,
) WriteTo(
	w io.Writer,
) (
	n int64,
	err error,
) {
	if s.sess.Config.Version == 2 {
		return s.writeTov2(
			w,
		)
	}

	for {
		var buf []byte
		s.bufferLock.Lock()
		if len(
			s.buffers,
		) > 0 {
			buf = s.buffers[0]
			s.buffers = s.buffers[1:]
			s.heads = s.heads[1:]
		}
		s.bufferLock.Unlock()

		if buf != nil {
			nw, ew := w.Write(
				buf,
			)
			s.sess.returnTokens(
				len(
					buf,
				),
			)
			defaultAllocator.Put(
				buf,
			)
			if nw > 0 {
				n += int64(nw)
			}

			if ew != nil {
				return n, ew
			}
		} else if ew := s.waitRead(); ew != nil {
			return n, ew
		}
	}
}

func (
	s *Stream,
) writeTov2(
	w io.Writer,
) (
	n int64,
	err error,
) {
	for {
		var notifyConsumed uint32
		var buf []byte
		s.bufferLock.Lock()
		if len(
			s.buffers,
		) > 0 {
			buf = s.buffers[0]
			s.buffers = s.buffers[1:]
			s.heads = s.heads[1:]
		}
		s.numRead += uint32(
			len(
				buf,
			),
		)
		s.incr += uint32(
			len(
				buf,
			),
		)
		if s.incr >= uint32(s.sess.Config.MaxStreamBuffer/2) || s.numRead == uint32(len(buf)) {
			notifyConsumed = s.numRead
			s.incr = 0
		}
		s.bufferLock.Unlock()

		if buf != nil {
			nw, ew := w.Write(
				buf,
			)
			s.sess.returnTokens(
				len(
					buf,
				),
			)
			defaultAllocator.Put(
				buf,
			)
			if nw > 0 {
				n += int64(nw)
			}

			if ew != nil {
				return n, ew
			}

			if notifyConsumed > 0 {
				if err := s.sendWindowUpdate(
					notifyConsumed,
				); err != nil {
					return n, err
				}
			}
		} else if ew := s.waitRead(); ew != nil {
			return n, ew
		}
	}
}

func (
	s *Stream,
) sendWindowUpdate(
	consumed uint32,
) error {
	var timer *time.Timer
	var deadline <-chan time.Time
	if d, ok := s.readDeadline.Load().(time.Time); ok && !d.IsZero() {
		timer = time.NewTimer(
			time.Until(
				d,
			),
		)
		defer timer.Stop()
		deadline = timer.C
	}

	frame := NewFrame(
		byte(s.sess.Config.Version),
		CmdUpd,
		s.id,
	)
	var hdr updHeader
	binary.LittleEndian.PutUint32(
		hdr[:],
		consumed,
	)
	binary.LittleEndian.PutUint32(
		hdr[4:],
		uint32(s.sess.Config.MaxStreamBuffer),
	)
	frame.Data = hdr[:]
	_, err := s.sess.WriteFrameInternal(
		frame,
		deadline,
		0,
	)
	return err
}

func (
	s *Stream,
) waitRead() error {
	var timer *time.Timer
	var deadline <-chan time.Time
	if d, ok := s.readDeadline.Load().(time.Time); ok && !d.IsZero() {
		timer = time.NewTimer(
			time.Until(
				d,
			),
		)
		defer timer.Stop()
		deadline = timer.C
	}

	select {
	case <-s.chReadEvent:
		return nil
	case <-s.chFinEvent:
		// BUG(xtaci): Fix for https://github.com/xtaci/smux/issues/82 // XXX
		s.bufferLock.Lock()
		defer s.bufferLock.Unlock()
		if len(
			s.buffers,
		) > 0 {
			return nil
		}
		return io.EOF
	case <-s.sess.chSocketReadError:
		return s.sess.socketReadError.Load().(error)
	case <-s.sess.chProtoError:
		return s.sess.protoError.Load().(error)
	case <-deadline:
		return ErrTimeout
	case <-s.die:
		return io.ErrClosedPipe
	}
}

// Write implements net.Conn
//
// Behavior when multiple concurrent goroutines write is not deterministic,
// so the frames will interleave in random ways.
func (
	s *Stream,
) Write(
	b []byte,
) (
	n int,
	err error,
) {
	if s.sess.Config.Version == 2 {
		return s.writeV2(
			b,
		)
	}

	var deadline <-chan time.Time
	if d, ok := s.writeDeadline.Load().(time.Time); ok && !d.IsZero() {
		timer := time.NewTimer(
			time.Until(
				d,
			),
		)
		defer timer.Stop()
		deadline = timer.C
	}

	// check if stream has closed
	select {
	case <-s.die:
		return 0, io.ErrClosedPipe
	default:
	}

	// frame split and transmit
	sent := 0
	frame := NewFrame(
		byte(s.sess.Config.Version),
		CmdPsh,
		s.id,
	)
	bts := b
	for len(
		bts,
	) > 0 {
		sz := len(
			bts,
		)
		if sz > s.frameSize {
			sz = s.frameSize
		}
		frame.Data = bts[:sz]
		bts = bts[sz:]
		n, err := s.sess.WriteFrameInternal(
			frame,
			deadline,
			uint64(s.numWritten),
		)
		s.numWritten++
		sent += n
		if err != nil {
			return sent, err
		}
	}

	return sent, nil
}

func (
	s *Stream,
) writeV2(
	b []byte,
) (
	n int,
	err error,
) {
	// check for empty input
	if len(b) == 0 {
		return 0, nil
	}

	// check if stream has closed
	select {
	case <-s.die:
		return 0, io.ErrClosedPipe
	default:
	}

	// create write deadline timer
	var deadline <-chan time.Time
	if d, ok := s.writeDeadline.Load().(time.Time); ok && !d.IsZero() {
		timer := time.NewTimer(
			time.Until(
				d,
			),
		)
		defer timer.Stop()
		deadline = timer.C
	}

	// frame split and transmit process
	sent := 0
	frame := NewFrame(
		byte(s.sess.Config.Version),
		CmdPsh,
		s.id,
	)

	for {
		// per stream sliding window control
		// [.... [consumed... numWritten] ... win... ]
		// [.... [consumed...................+rmtwnd]]
		var bts []byte
		// note:
		// even if uint32 overflow, this math still works:
		// eg1: uint32(0) - uint32(math.MaxUint32) = 1
		// eg2: int32(uint32(0) - uint32(1)) = -1
		// security check for misbehavior
		inflight := int32(atomic.LoadUint32(
			&s.numWritten,
		) - atomic.LoadUint32(
			&s.peerConsumed,
		))
		if inflight < 0 {
			return 0, ErrConsumed
		}

		win := int32(atomic.LoadUint32(
			&s.peerWindow,
		)) - inflight
		if win > 0 {
			if win > int32(len(
				b,
			)) {
				bts = b
				b = nil
			} else {
				bts = b[:win]
				b = b[win:]
			}

			for len(
				bts,
			) > 0 {
				sz := len(
					bts,
				)
				if sz > s.frameSize {
					sz = s.frameSize
				}
				frame.Data = bts[:sz]
				bts = bts[sz:]
				n, err := s.sess.WriteFrameInternal(
					frame,
					deadline,
					uint64(atomic.LoadUint32(
						&s.numWritten,
					),
					),
				)
				atomic.AddUint32(
					&s.numWritten,
					uint32(sz),
				)
				sent += n
				if err != nil {
					return sent, err
				}
			}
		}

		// if there is any data remaining to be sent
		// wait until stream closes, window changes or deadline reached
		// this blocking behavior will inform upper layer to do flow control
		if len(
			b,
		) > 0 {
			select {
			case <-s.chFinEvent: // if fin arrived, future window update is impossible
				return 0, io.EOF
			case <-s.die:
				return sent, io.ErrClosedPipe
			case <-deadline:
				return sent, ErrTimeout
			case <-s.sess.chSocketWriteError:
				return sent, s.sess.socketWriteError.Load().(error)
			case <-s.chUpdate:
				continue
			}
		} else {
			return sent, nil
		}
	}
}

// Close implements net.Conn
func (
	s *Stream,
) Close() error {
	var once bool
	var err error
	s.dieOnce.Do(func() {
		close(
			s.die,
		)
		once = true
	})

	if once {
		_, err = s.sess.WriteFrame(
			NewFrame(
				byte(s.sess.Config.Version),
				CmdFin,
				s.id,
			),
		)
		s.sess.streamClosed(
			s.id,
		)
		return err
	}
	return io.ErrClosedPipe
}

// GetDieCh returns a readonly chan which can be readable
// when the stream is to be closed.
func (
	s *Stream,
) GetDieCh() <-chan struct{} {
	return s.die
}

// SetReadDeadline sets the read deadline as defined by
// net.Conn.SetReadDeadline.
// A zero time value disables the deadline.
func (
	s *Stream,
) SetReadDeadline(
	t time.Time,
) error {
	s.readDeadline.Store(
		t,
	)
	s.notifyReadEvent()
	return nil
}

// SetWriteDeadline sets the write deadline as defined by
// net.Conn.SetWriteDeadline.
// A zero time value disables the deadline.
func (
	s *Stream,
) SetWriteDeadline(
	t time.Time,
) error {
	s.writeDeadline.Store(
		t,
	)
	return nil
}

// SetDeadline sets both read and write deadlines as defined by
// net.Conn.SetDeadline.
// A zero time value disables the deadlines.
func (
	s *Stream,
) SetDeadline(
	t time.Time,
) error {
	if err := s.SetReadDeadline(
		t,
	); err != nil {
		return err
	}
	if err := s.SetWriteDeadline(
		t,
	); err != nil {
		return err
	}
	return nil
}

// session closes
func (
	s *Stream,
) sessionClose() {
	s.dieOnce.Do(func() {
		close(
			s.die,
		)
	})
}

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

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

// pushBytes append buf to buffers
func (
	s *Stream,
) pushBytes(
	buf []byte,
) (
	written int,
	err error,
) {
	s.bufferLock.Lock()
	s.buffers = append(
		s.buffers,
		buf,
	)
	s.heads = append(
		s.heads,
		buf,
	)
	s.bufferLock.Unlock()
	return
}

// recycleTokens transform remaining bytes to tokens(will truncate buffer)
func (
	s *Stream,
) recycleTokens() (
	n int,
) {
	s.bufferLock.Lock()
	for k := range s.buffers {
		n += len(
			s.buffers[k],
		)
		defaultAllocator.Put(
			s.heads[k],
		)
	}
	s.buffers = nil
	s.heads = nil
	s.bufferLock.Unlock()
	return
}

// notify read event
func (
	s *Stream,
) notifyReadEvent() {
	select {
	case s.chReadEvent <- struct{}{}:
	default:
	}
}

// update command
func (
	s *Stream,
) update(
	consumed,
	window uint32,
) {
	atomic.StoreUint32(
		&s.peerConsumed,
		consumed,
	)
	atomic.StoreUint32(
		&s.peerWindow,
		window,
	)
	select {
	case s.chUpdate <- struct{}{}:
	default:
	}
}

// mark this stream has been closed in protocol
func (
	s *Stream,
) fin() {
	s.finEventOnce.Do(func() {
		close(
			s.chFinEvent,
		)
	})
}