You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/transport/ray/direct.go

174 lines
2.5 KiB

package ray
import (
"context"
"io"
"sync"
"time"
"v2ray.com/core/common/buf"
)
9 years ago
// NewRay creates a new Ray for direct traffic transport.
func NewRay(ctx context.Context) Ray {
return &directRay{
Input: NewStream(ctx),
Output: NewStream(ctx),
}
}
type directRay struct {
Input *Stream
Output *Stream
}
8 years ago
func (v *directRay) OutboundInput() InputStream {
return v.Input
}
8 years ago
func (v *directRay) OutboundOutput() OutputStream {
return v.Output
}
8 years ago
func (v *directRay) InboundInput() OutputStream {
return v.Input
}
8 years ago
func (v *directRay) InboundOutput() InputStream {
return v.Output
}
type Stream struct {
access sync.RWMutex
data buf.MultiBuffer
ctx context.Context
wakeup chan bool
close bool
err bool
}
func NewStream(ctx context.Context) *Stream {
return &Stream{
ctx: ctx,
wakeup: make(chan bool, 1),
}
}
func (s *Stream) getData() (buf.MultiBuffer, error) {
s.access.Lock()
defer s.access.Unlock()
if s.data != nil {
mb := s.data
s.data = nil
return mb, nil
}
if s.close {
return nil, io.EOF
}
if s.err {
return nil, io.ErrClosedPipe
}
return nil, nil
}
8 years ago
func (s *Stream) Peek(b *buf.Buffer) {
s.access.RLock()
defer s.access.RUnlock()
8 years ago
b.Reset(func(data []byte) (int, error) {
return s.data.Copy(data), nil
})
}
func (s *Stream) Read() (buf.MultiBuffer, error) {
for {
mb, err := s.getData()
if err != nil {
return nil, err
}
if mb != nil {
return mb, nil
}
select {
case <-s.ctx.Done():
return nil, io.EOF
case <-s.wakeup:
}
}
}
func (s *Stream) ReadTimeout(timeout time.Duration) (buf.MultiBuffer, error) {
for {
mb, err := s.getData()
if err != nil {
return nil, err
}
if mb != nil {
return mb, nil
8 years ago
}
select {
case <-s.ctx.Done():
return nil, io.EOF
case <-time.After(timeout):
8 years ago
return nil, buf.ErrReadTimeout
case <-s.wakeup:
}
}
}
8 years ago
func (s *Stream) Write(data buf.MultiBuffer) error {
if data.IsEmpty() {
8 years ago
return nil
}
s.access.Lock()
defer s.access.Unlock()
8 years ago
if s.err || s.close {
data.Release()
return io.ErrClosedPipe
}
if s.data == nil {
s.data = data
} else {
s.data.AppendMulti(data)
}
s.wakeUp()
8 years ago
return nil
}
func (s *Stream) wakeUp() {
select {
case s.wakeup <- true:
default:
}
}
8 years ago
func (s *Stream) Close() {
s.access.Lock()
s.close = true
s.wakeUp()
s.access.Unlock()
}
8 years ago
func (s *Stream) CloseError() {
s.access.Lock()
s.err = true
if s.data != nil {
s.data.Release()
s.data = nil
}
s.wakeUp()
s.access.Unlock()
8 years ago
}