1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2025-01-05 00:47:51 -05:00

fix data race in pipe

This commit is contained in:
Darien Raymond 2018-04-18 15:11:03 +02:00
parent 10d7ed2e83
commit 845606d86c
No known key found for this signature in database
GPG Key ID: 7251FFA14BB18169
2 changed files with 33 additions and 3 deletions

View File

@ -1,6 +1,7 @@
package pipe package pipe
import ( import (
"errors"
"io" "io"
"sync" "sync"
"time" "time"
@ -26,9 +27,14 @@ type pipe struct {
state state state state
} }
var errBufferFull = errors.New("buffer full")
func (p *pipe) getState(forRead bool) error { func (p *pipe) getState(forRead bool) error {
switch p.state { switch p.state {
case open: case open:
if !forRead && p.limit >= 0 && p.data.Len() > p.limit {
return errBufferFull
}
return nil return nil
case closed: case closed:
if forRead { if forRead {
@ -105,9 +111,10 @@ func (p *pipe) WriteMultiBuffer(mb buf.MultiBuffer) error {
} }
for { for {
if p.limit < 0 || p.data.Len()+mb.Len() <= p.limit { err := p.writeMultiBufferInternal(mb)
defer p.readSignal.Signal() if err == nil || err != errBufferFull {
return p.writeMultiBufferInternal(mb) p.readSignal.Signal()
return err
} }
<-p.writeSignal.Wait() <-p.writeSignal.Wait()

View File

@ -0,0 +1,23 @@
package pipe_test
import (
"testing"
"v2ray.com/core/common/buf"
. "v2ray.com/core/transport/pipe"
. "v2ray.com/ext/assert"
)
func TestPipeReadWrite(t *testing.T) {
assert := With(t)
pReader, pWriter := New()
payload := []byte{'a', 'b', 'c', 'd'}
b := buf.New()
b.Append(payload)
assert(pWriter.WriteMultiBuffer(buf.NewMultiBufferValue(b)), IsNil)
rb, err := pReader.ReadMultiBuffer()
assert(err, IsNil)
assert(rb.String(), Equals, b.String())
}