mirror of
https://github.com/nadoo/glider.git
synced 2026-11-19 07:09:42 +08:00
chore: update dependencies and optimize some code style
This commit is contained in:
1 parent
40809b56a9
commit
bd40b07388
23 files changed
+321
-1348
No files matched your search
+118
-54
@@ -1,3 +1,25 @@
|
||||
// MIT License
|
||||
//
|
||||
// Copyright (c) 2016-2017 xtaci
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
|
||||
package smux
|
||||
|
||||
import (
|
||||
@@ -11,36 +33,41 @@ import (
|
||||
"github.com/nadoo/glider/pkg/pool"
|
||||
)
|
||||
|
||||
// Stream implements net.Conn
|
||||
// wrapper for GC
|
||||
type Stream struct {
|
||||
id uint32
|
||||
*stream
|
||||
}
|
||||
|
||||
// Stream implements net.Conn
|
||||
type stream struct {
|
||||
id uint32 // Stream identifier
|
||||
sess *Session
|
||||
|
||||
buffers [][]byte
|
||||
heads [][]byte // slice heads kept for recycle
|
||||
buffers [][]byte // the sequential buffers of stream
|
||||
heads [][]byte // slice heads of the buffers above, kept for recycle
|
||||
|
||||
bufferLock sync.Mutex
|
||||
frameSize int
|
||||
bufferLock sync.Mutex // Mutex to protect access to buffers
|
||||
frameSize int // Maximum frame size for the stream
|
||||
|
||||
// notify a read event
|
||||
chReadEvent chan struct{}
|
||||
|
||||
// flag the stream has closed
|
||||
die chan struct{}
|
||||
dieOnce sync.Once
|
||||
dieOnce sync.Once // Ensures die channel is closed only once
|
||||
|
||||
// FIN command
|
||||
chFinEvent chan struct{}
|
||||
finEventOnce sync.Once
|
||||
finEventOnce sync.Once // Ensures chFinEvent is closed only once
|
||||
|
||||
// deadlines
|
||||
readDeadline atomic.Value
|
||||
writeDeadline atomic.Value
|
||||
|
||||
// per stream sliding window control
|
||||
numRead uint32 // number of consumed bytes
|
||||
numRead uint32 // count num of bytes read
|
||||
numWritten uint32 // count num of bytes written
|
||||
incr uint32 // counting for sending
|
||||
incr uint32 // bytes sent since last window update
|
||||
|
||||
// UPD command
|
||||
peerConsumed uint32 // num of bytes the peer has consumed
|
||||
@@ -48,9 +75,9 @@ type Stream struct {
|
||||
chUpdate chan struct{} // notify of remote data consuming and window update
|
||||
}
|
||||
|
||||
// newStream initiates a Stream struct
|
||||
func newStream(id uint32, frameSize int, sess *Session) *Stream {
|
||||
s := new(Stream)
|
||||
// newStream initializes and returns a new Stream.
|
||||
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)
|
||||
@@ -59,16 +86,17 @@ func newStream(id uint32, frameSize int, sess *Session) *Stream {
|
||||
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 {
|
||||
// ID returns the stream's unique identifier.
|
||||
func (s *stream) ID() uint32 {
|
||||
return s.id
|
||||
}
|
||||
|
||||
// Read implements net.Conn
|
||||
func (s *Stream) Read(b []byte) (n int, err error) {
|
||||
// Read reads data from the stream into the provided buffer.
|
||||
func (s *stream) Read(b []byte) (n int, err error) {
|
||||
for {
|
||||
n, err = s.tryRead(b)
|
||||
if err == ErrWouldBlock {
|
||||
@@ -81,8 +109,8 @@ func (s *Stream) Read(b []byte) (n int, err error) {
|
||||
}
|
||||
}
|
||||
|
||||
// tryRead is the nonblocking version of Read
|
||||
func (s *Stream) tryRead(b []byte) (n int, err error) {
|
||||
// tryRead attempts to read data from the stream without blocking.
|
||||
func (s *stream) tryRead(b []byte) (n int, err error) {
|
||||
if s.sess.config.Version == 2 {
|
||||
return s.tryReadv2(b)
|
||||
}
|
||||
@@ -91,6 +119,7 @@ func (s *Stream) tryRead(b []byte) (n int, err error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// A critical section to copy data from buffers to
|
||||
s.bufferLock.Lock()
|
||||
if len(s.buffers) > 0 {
|
||||
n = copy(b, s.buffers[0])
|
||||
@@ -118,7 +147,8 @@ func (s *Stream) tryRead(b []byte) (n int, err error) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Stream) tryReadv2(b []byte) (n int, err error) {
|
||||
// tryReadv2 is the non-blocking version of Read for version 2 streams.
|
||||
func (s *stream) tryReadv2(b []byte) (n int, err error) {
|
||||
if len(b) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
@@ -139,20 +169,25 @@ func (s *Stream) tryReadv2(b []byte) (n int, err error) {
|
||||
|
||||
// in an ideal environment:
|
||||
// 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
|
||||
// based on round-trip time of ACK, continous flowing data
|
||||
// won't slow down due to waiting for ACK, as long as the
|
||||
// consumer keeps on reading data.
|
||||
//
|
||||
// s.numRead == n implies that it's the initial reading
|
||||
s.numRead += uint32(n)
|
||||
s.incr += uint32(n)
|
||||
|
||||
// for initial reading, send window update
|
||||
if s.incr >= uint32(s.sess.config.MaxStreamBuffer/2) || s.numRead == uint32(n) {
|
||||
notifyConsumed = s.numRead
|
||||
s.incr = 0
|
||||
s.incr = 0 // reset couting for next window update
|
||||
}
|
||||
s.bufferLock.Unlock()
|
||||
|
||||
if n > 0 {
|
||||
s.sess.returnTokens(n)
|
||||
|
||||
// send window update if necessary
|
||||
if notifyConsumed > 0 {
|
||||
err := s.sendWindowUpdate(notifyConsumed)
|
||||
return n, err
|
||||
@@ -170,7 +205,12 @@ func (s *Stream) tryReadv2(b []byte) (n int, err error) {
|
||||
}
|
||||
|
||||
// WriteTo implements io.WriteTo
|
||||
func (s *Stream) WriteTo(w io.Writer) (n int64, err error) {
|
||||
// WriteTo writes data to w until there's no more data to write or when an error occurs.
|
||||
// The return value n is the number of bytes written. Any error encountered during the write is also returned.
|
||||
// WriteTo calls Write in a loop until there is no more data to write or when an error occurs.
|
||||
// If the underlying stream is a v2 stream, it will send window update to peer when necessary.
|
||||
// If the underlying stream is a v1 stream, it will not send window update to peer.
|
||||
func (s *stream) WriteTo(w io.Writer) (n int64, err error) {
|
||||
if s.sess.config.Version == 2 {
|
||||
return s.writeTov2(w)
|
||||
}
|
||||
@@ -187,6 +227,7 @@ func (s *Stream) WriteTo(w io.Writer) (n int64, err error) {
|
||||
|
||||
if buf != nil {
|
||||
nw, ew := w.Write(buf)
|
||||
// NOTE: WriteTo is a reader, so we need to return tokens here
|
||||
s.sess.returnTokens(len(buf))
|
||||
pool.PutBuffer(buf)
|
||||
if nw > 0 {
|
||||
@@ -202,7 +243,8 @@ func (s *Stream) WriteTo(w io.Writer) (n int64, err error) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Stream) writeTov2(w io.Writer) (n int64, err error) {
|
||||
// check comments in WriteTo
|
||||
func (s *stream) writeTov2(w io.Writer) (n int64, err error) {
|
||||
for {
|
||||
var notifyConsumed uint32
|
||||
var buf []byte
|
||||
@@ -222,6 +264,7 @@ func (s *Stream) writeTov2(w io.Writer) (n int64, err error) {
|
||||
|
||||
if buf != nil {
|
||||
nw, ew := w.Write(buf)
|
||||
// NOTE: WriteTo is a reader, so we need to return tokens here
|
||||
s.sess.returnTokens(len(buf))
|
||||
pool.PutBuffer(buf)
|
||||
if nw > 0 {
|
||||
@@ -243,7 +286,8 @@ func (s *Stream) writeTov2(w io.Writer) (n int64, err error) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Stream) sendWindowUpdate(consumed uint32) error {
|
||||
// sendWindowUpdate sends a window update frame to the peer.
|
||||
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() {
|
||||
@@ -257,11 +301,12 @@ func (s *Stream) sendWindowUpdate(consumed uint32) error {
|
||||
binary.LittleEndian.PutUint32(hdr[:], consumed)
|
||||
binary.LittleEndian.PutUint32(hdr[4:], uint32(s.sess.config.MaxStreamBuffer))
|
||||
frame.data = hdr[:]
|
||||
_, err := s.sess.writeFrameInternal(frame, deadline, CLSDATA)
|
||||
_, err := s.sess.writeFrameInternal(frame, deadline, CLSCTRL)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Stream) waitRead() error {
|
||||
// waitRead blocks until a read event occurs or a deadline is reached.
|
||||
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() {
|
||||
@@ -271,10 +316,10 @@ func (s *Stream) waitRead() error {
|
||||
}
|
||||
|
||||
select {
|
||||
case <-s.chReadEvent:
|
||||
case <-s.chReadEvent: // notify some data has arrived, or closed
|
||||
return nil
|
||||
case <-s.chFinEvent:
|
||||
// BUG(xtaci): Fix for https://github.com/xtaci/smux/issues/82
|
||||
// BUGFIX(xtaci): Fix for https://github.com/xtaci/smux/issues/82
|
||||
s.bufferLock.Lock()
|
||||
defer s.bufferLock.Unlock()
|
||||
if len(s.buffers) > 0 {
|
||||
@@ -297,7 +342,7 @@ func (s *Stream) waitRead() error {
|
||||
//
|
||||
// Note that the behavior when multiple goroutines write concurrently is not deterministic,
|
||||
// frames may interleave in random way.
|
||||
func (s *Stream) Write(b []byte) (n int, err error) {
|
||||
func (s *stream) Write(b []byte) (n int, err error) {
|
||||
if s.sess.config.Version == 2 {
|
||||
return s.writeV2(b)
|
||||
}
|
||||
@@ -311,6 +356,8 @@ func (s *Stream) Write(b []byte) (n int, err error) {
|
||||
|
||||
// check if stream has closed
|
||||
select {
|
||||
case <-s.chFinEvent: // passive closing
|
||||
return 0, io.EOF
|
||||
case <-s.die:
|
||||
return 0, io.ErrClosedPipe
|
||||
default:
|
||||
@@ -338,7 +385,8 @@ func (s *Stream) Write(b []byte) (n int, err error) {
|
||||
return sent, nil
|
||||
}
|
||||
|
||||
func (s *Stream) writeV2(b []byte) (n int, err error) {
|
||||
// writeV2 writes data to the stream for version 2 streams.
|
||||
func (s *stream) writeV2(b []byte) (n int, err error) {
|
||||
// check empty input
|
||||
if len(b) == 0 {
|
||||
return 0, nil
|
||||
@@ -346,6 +394,8 @@ func (s *Stream) writeV2(b []byte) (n int, err error) {
|
||||
|
||||
// check if stream has closed
|
||||
select {
|
||||
case <-s.chFinEvent:
|
||||
return 0, io.EOF
|
||||
case <-s.die:
|
||||
return 0, io.ErrClosedPipe
|
||||
default:
|
||||
@@ -372,14 +422,18 @@ func (s *Stream) writeV2(b []byte) (n int, err error) {
|
||||
// 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
|
||||
//
|
||||
// basicially, you can take it as a MODULAR ARITHMETIC
|
||||
inflight := int32(atomic.LoadUint32(&s.numWritten) - atomic.LoadUint32(&s.peerConsumed))
|
||||
if inflight < 0 {
|
||||
if inflight < 0 { // security check for malformed data
|
||||
return 0, ErrConsumed
|
||||
}
|
||||
|
||||
// make sure you understand 'win' is calculated in modular arithmetic(2^32(4GB))
|
||||
win := int32(atomic.LoadUint32(&s.peerWindow)) - inflight
|
||||
|
||||
if win > 0 {
|
||||
// determine how many bytes to send
|
||||
if win > int32(len(b)) {
|
||||
bts = b
|
||||
b = nil
|
||||
@@ -388,13 +442,17 @@ func (s *Stream) writeV2(b []byte) (n int, err error) {
|
||||
b = b[win:]
|
||||
}
|
||||
|
||||
// frame split and transmit
|
||||
for len(bts) > 0 {
|
||||
// splitting frame
|
||||
sz := len(bts)
|
||||
if sz > s.frameSize {
|
||||
sz = s.frameSize
|
||||
}
|
||||
frame.data = bts[:sz]
|
||||
bts = bts[sz:]
|
||||
|
||||
// transmit of frame
|
||||
n, err := s.sess.writeFrameInternal(frame, deadline, CLSDATA)
|
||||
atomic.AddUint32(&s.numWritten, uint32(sz))
|
||||
sent += n
|
||||
@@ -404,12 +462,12 @@ func (s *Stream) writeV2(b []byte) (n int, err error) {
|
||||
}
|
||||
}
|
||||
|
||||
// if there is any data remaining to be sent
|
||||
// if there is any data left to be sent,
|
||||
// wait until stream closes, window changes or deadline reached
|
||||
// this blocking behavior will inform upper layer to do flow control
|
||||
// this blocking behavior will back propagate flow control to upper layer.
|
||||
if len(b) > 0 {
|
||||
select {
|
||||
case <-s.chFinEvent: // if fin arrived, future window update is impossible
|
||||
case <-s.chFinEvent:
|
||||
return 0, io.EOF
|
||||
case <-s.die:
|
||||
return sent, io.ErrClosedPipe
|
||||
@@ -417,7 +475,7 @@ func (s *Stream) writeV2(b []byte) (n int, err error) {
|
||||
return sent, ErrTimeout
|
||||
case <-s.sess.chSocketWriteError:
|
||||
return sent, s.sess.socketWriteError.Load().(error)
|
||||
case <-s.chUpdate:
|
||||
case <-s.chUpdate: // notify of remote data consuming and window update
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
@@ -427,7 +485,7 @@ func (s *Stream) writeV2(b []byte) (n int, err error) {
|
||||
}
|
||||
|
||||
// Close implements net.Conn
|
||||
func (s *Stream) Close() error {
|
||||
func (s *stream) Close() error {
|
||||
var once bool
|
||||
var err error
|
||||
s.dieOnce.Do(func() {
|
||||
@@ -436,7 +494,13 @@ func (s *Stream) Close() error {
|
||||
})
|
||||
|
||||
if once {
|
||||
_, err = s.sess.writeFrame(newFrame(byte(s.sess.config.Version), cmdFIN, s.id))
|
||||
// send FIN in order
|
||||
f := newFrame(byte(s.sess.config.Version), cmdFIN, s.id)
|
||||
|
||||
timer := time.NewTimer(openCloseTimeout)
|
||||
defer timer.Stop()
|
||||
|
||||
_, err = s.sess.writeFrameInternal(f, timer.C, CLSDATA)
|
||||
s.sess.streamClosed(s.id)
|
||||
return err
|
||||
} else {
|
||||
@@ -446,14 +510,14 @@ func (s *Stream) Close() error {
|
||||
|
||||
// GetDieCh returns a readonly chan which can be readable
|
||||
// when the stream is to be closed.
|
||||
func (s *Stream) GetDieCh() <-chan struct{} {
|
||||
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 {
|
||||
func (s *stream) SetReadDeadline(t time.Time) error {
|
||||
s.readDeadline.Store(t)
|
||||
s.notifyReadEvent()
|
||||
return nil
|
||||
@@ -462,7 +526,7 @@ func (s *Stream) SetReadDeadline(t time.Time) error {
|
||||
// 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 {
|
||||
func (s *stream) SetWriteDeadline(t time.Time) error {
|
||||
s.writeDeadline.Store(t)
|
||||
return nil
|
||||
}
|
||||
@@ -470,7 +534,7 @@ func (s *Stream) SetWriteDeadline(t time.Time) error {
|
||||
// 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 {
|
||||
func (s *stream) SetDeadline(t time.Time) error {
|
||||
if err := s.SetReadDeadline(t); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -481,10 +545,10 @@ func (s *Stream) SetDeadline(t time.Time) error {
|
||||
}
|
||||
|
||||
// session closes
|
||||
func (s *Stream) sessionClose() { s.dieOnce.Do(func() { close(s.die) }) }
|
||||
func (s *stream) sessionClose() { s.dieOnce.Do(func() { close(s.die) }) }
|
||||
|
||||
// LocalAddr satisfies net.Conn interface
|
||||
func (s *Stream) LocalAddr() net.Addr {
|
||||
func (s *stream) LocalAddr() net.Addr {
|
||||
if ts, ok := s.sess.conn.(interface {
|
||||
LocalAddr() net.Addr
|
||||
}); ok {
|
||||
@@ -494,7 +558,7 @@ func (s *Stream) LocalAddr() net.Addr {
|
||||
}
|
||||
|
||||
// RemoteAddr satisfies net.Conn interface
|
||||
func (s *Stream) RemoteAddr() net.Addr {
|
||||
func (s *stream) RemoteAddr() net.Addr {
|
||||
if ts, ok := s.sess.conn.(interface {
|
||||
RemoteAddr() net.Addr
|
||||
}); ok {
|
||||
@@ -504,7 +568,7 @@ func (s *Stream) RemoteAddr() net.Addr {
|
||||
}
|
||||
|
||||
// pushBytes append buf to buffers
|
||||
func (s *Stream) pushBytes(buf []byte) (written int, err error) {
|
||||
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)
|
||||
@@ -513,7 +577,7 @@ func (s *Stream) pushBytes(buf []byte) (written int, err error) {
|
||||
}
|
||||
|
||||
// recycleTokens transform remaining bytes to tokens(will truncate buffer)
|
||||
func (s *Stream) recycleTokens() (n int) {
|
||||
func (s *stream) recycleTokens() (n int) {
|
||||
s.bufferLock.Lock()
|
||||
for k := range s.buffers {
|
||||
n += len(s.buffers[k])
|
||||
@@ -526,7 +590,7 @@ func (s *Stream) recycleTokens() (n int) {
|
||||
}
|
||||
|
||||
// notify read event
|
||||
func (s *Stream) notifyReadEvent() {
|
||||
func (s *stream) notifyReadEvent() {
|
||||
select {
|
||||
case s.chReadEvent <- struct{}{}:
|
||||
default:
|
||||
@@ -534,7 +598,7 @@ func (s *Stream) notifyReadEvent() {
|
||||
}
|
||||
|
||||
// update command
|
||||
func (s *Stream) update(consumed uint32, window uint32) {
|
||||
func (s *stream) update(consumed uint32, window uint32) {
|
||||
atomic.StoreUint32(&s.peerConsumed, consumed)
|
||||
atomic.StoreUint32(&s.peerWindow, window)
|
||||
select {
|
||||
@@ -544,7 +608,7 @@ func (s *Stream) update(consumed uint32, window uint32) {
|
||||
}
|
||||
|
||||
// mark this stream has been closed in protocol
|
||||
func (s *Stream) fin() {
|
||||
func (s *stream) fin() {
|
||||
s.finEventOnce.Do(func() {
|
||||
close(s.chFinEvent)
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user