Skip to content

Commit

Permalink
session/grpchijack: fix race
Browse files Browse the repository at this point in the history
Signed-off-by: Akihiro Suda <akihiro.suda.cz@hco.ntt.co.jp>
  • Loading branch information
AkihiroSuda committed May 8, 2019
1 parent 97b4b9a commit 2991d2c
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions session/grpchijack/dial.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,14 @@ type conn struct {
lastBuf []byte

closedOnce sync.Once
readMu sync.Mutex
mu sync.Mutex
err error
closeCh chan struct{}
}

func (c *conn) Read(b []byte) (n int, err error) {
c.readMu.Lock()
defer c.readMu.Unlock()
c.mu.Lock()
defer c.mu.Unlock()

if c.lastBuf != nil {
n := copy(b, c.lastBuf)
Expand All @@ -79,6 +79,8 @@ func (c *conn) Read(b []byte) (n int, err error) {
}

func (c *conn) Write(b []byte) (int, error) {
c.mu.Lock()
defer c.mu.Unlock()
m := &controlapi.BytesMessage{Data: b}
if err := c.stream.SendMsg(m); err != nil {
return 0, err
Expand All @@ -87,6 +89,8 @@ func (c *conn) Write(b []byte) (int, error) {
}

func (c *conn) Close() (err error) {
c.mu.Lock()
defer c.mu.Unlock()
c.closedOnce.Do(func() {
defer func() {
close(c.closeCh)
Expand All @@ -99,7 +103,6 @@ func (c *conn) Close() (err error) {
}
}

c.readMu.Lock()
for {
m := new(controlapi.BytesMessage)
m.Data = c.buf
Expand All @@ -114,7 +117,6 @@ func (c *conn) Close() (err error) {
c.buf = m.Data[:cap(m.Data)]
c.lastBuf = append(c.lastBuf, c.buf...)
}
c.readMu.Unlock()

})
return nil
Expand Down

0 comments on commit 2991d2c

Please sign in to comment.