Skip to content

Commit

Permalink
Merge pull request #50 from libp2p/fix/reset-closed
Browse files Browse the repository at this point in the history
fix: reset a stream even if closed remotely
  • Loading branch information
Stebalien authored May 7, 2019
2 parents 94af77d + fef7686 commit dec60e0
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 7 deletions.
34 changes: 34 additions & 0 deletions multiplex_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"net"
"testing"
"time"

streammux "github.com/libp2p/go-stream-muxer"
)

func init() {
Expand Down Expand Up @@ -362,6 +364,38 @@ func TestReset(t *testing.T) {
}
}

func TestResetAfterEOF(t *testing.T) {
a, b := net.Pipe()

mpa := NewMultiplex(a, false)
mpb := NewMultiplex(b, true)

defer mpa.Close()
defer mpb.Close()

sa, err := mpa.NewStream()
if err != nil {
t.Fatal(err)
}
sb, err := mpb.Accept()

if err := sa.Close(); err != nil {
t.Fatal(err)
}

n, err := sb.Read([]byte{0})
if n != 0 || err != io.EOF {
t.Fatal(err)
}

sb.Reset()

n, err = sa.Read([]byte{0})
if n != 0 || err != streammux.ErrReset {
t.Fatal(err)
}
}

func TestOpenAfterClose(t *testing.T) {
a, b := net.Pipe()

Expand Down
19 changes: 12 additions & 7 deletions stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,22 +203,27 @@ func (s *Stream) Close() error {

func (s *Stream) Reset() error {
s.clLock.Lock()
isClosed := s.isClosed()
if s.closedRemote && isClosed {

// Don't reset when fully closed.
if s.closedRemote && s.isClosed() {
s.clLock.Unlock()
return nil
}

if !s.closedRemote {
close(s.reset)
// We generally call this to tell the other side to go away. No point in waiting around.
go s.mp.sendMsg(context.Background(), s.id.header(resetTag), nil)
// Don't reset twice.
select {
case <-s.reset:
s.clLock.Unlock()
return nil
default:
}

close(s.reset)
s.doCloseLocal()

s.closedRemote = true

go s.mp.sendMsg(context.Background(), s.id.header(resetTag), nil)

s.clLock.Unlock()

s.mp.chLock.Lock()
Expand Down

0 comments on commit dec60e0

Please sign in to comment.