From f5f13d801fae3051e3da4f43235825a384365339 Mon Sep 17 00:00:00 2001 From: v2ray Date: Fri, 20 May 2016 13:56:19 +0200 Subject: [PATCH] add a lock to protect reader/writer from panic --- common/io/buffered_reader.go | 12 ++++++++++++ common/io/buffered_writer.go | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/common/io/buffered_reader.go b/common/io/buffered_reader.go index 92c45f463..2381ee872 100644 --- a/common/io/buffered_reader.go +++ b/common/io/buffered_reader.go @@ -2,11 +2,13 @@ package io import ( "io" + "sync" "github.com/v2ray/v2ray-core/common/alloc" ) type BufferedReader struct { + sync.Mutex reader io.Reader buffer *alloc.Buffer cached bool @@ -21,6 +23,9 @@ func NewBufferedReader(rawReader io.Reader) *BufferedReader { } func (this *BufferedReader) Release() { + this.Lock() + defer this.Unlock() + this.buffer.Release() this.buffer = nil this.reader = nil @@ -35,6 +40,13 @@ func (this *BufferedReader) SetCached(cached bool) { } func (this *BufferedReader) Read(b []byte) (int, error) { + this.Lock() + defer this.Unlock() + + if this.reader == nil { + return 0, io.EOF + } + if !this.cached { if !this.buffer.IsEmpty() { return this.buffer.Read(b) diff --git a/common/io/buffered_writer.go b/common/io/buffered_writer.go index a48a5ac21..c98496750 100644 --- a/common/io/buffered_writer.go +++ b/common/io/buffered_writer.go @@ -2,11 +2,13 @@ package io import ( "io" + "sync" "github.com/v2ray/v2ray-core/common/alloc" ) type BufferedWriter struct { + sync.Mutex writer io.Writer buffer *alloc.Buffer cached bool @@ -21,6 +23,13 @@ func NewBufferedWriter(rawWriter io.Writer) *BufferedWriter { } func (this *BufferedWriter) Write(b []byte) (int, error) { + this.Lock() + defer this.Unlock() + + if this.writer == nil { + return 0, io.EOF + } + if !this.cached { return this.writer.Write(b) } @@ -35,6 +44,12 @@ func (this *BufferedWriter) Write(b []byte) (int, error) { } func (this *BufferedWriter) Flush() error { + this.Lock() + defer this.Unlock() + if this.writer == nil { + return io.EOF + } + defer this.buffer.Clear() for !this.buffer.IsEmpty() { nBytes, err := this.writer.Write(this.buffer.Value) @@ -58,6 +73,9 @@ func (this *BufferedWriter) SetCached(cached bool) { } func (this *BufferedWriter) Release() { + this.Lock() + defer this.Unlock() + this.Flush() this.buffer.Release() this.buffer = nil