1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-07-15 09:44:37 -04:00
v2fly/transport/ray/direct.go

116 lines
1.7 KiB
Go
Raw Normal View History

2015-10-14 09:07:13 -04:00
package ray
import (
2016-04-18 12:44:10 -04:00
"io"
2016-12-09 05:35:27 -05:00
"v2ray.com/core/common/buf"
2015-10-14 09:07:13 -04:00
)
const (
2016-12-02 08:22:46 -05:00
bufferSize = 512
2015-10-14 09:07:13 -04:00
)
2015-10-15 07:15:59 -04:00
// NewRay creates a new Ray for direct traffic transport.
2015-10-14 09:07:13 -04:00
func NewRay() Ray {
return &directRay{
2016-04-18 12:44:10 -04:00
Input: NewStream(),
Output: NewStream(),
2015-10-14 09:07:13 -04:00
}
}
type directRay struct {
2016-04-18 12:44:10 -04:00
Input *Stream
Output *Stream
2015-10-14 09:07:13 -04:00
}
2016-11-27 15:39:09 -05:00
func (v *directRay) OutboundInput() InputStream {
return v.Input
2015-10-14 09:07:13 -04:00
}
2016-11-27 15:39:09 -05:00
func (v *directRay) OutboundOutput() OutputStream {
return v.Output
2015-10-14 09:07:13 -04:00
}
2016-11-27 15:39:09 -05:00
func (v *directRay) InboundInput() OutputStream {
return v.Input
2015-10-14 09:07:13 -04:00
}
2016-11-27 15:39:09 -05:00
func (v *directRay) InboundOutput() InputStream {
return v.Output
2015-10-14 09:07:13 -04:00
}
2016-04-18 12:44:10 -04:00
type Stream struct {
2016-12-24 18:42:03 -05:00
buffer chan *buf.Buffer
srcClose chan bool
destClose chan bool
2016-04-18 12:44:10 -04:00
}
func NewStream() *Stream {
return &Stream{
2016-12-24 18:42:03 -05:00
buffer: make(chan *buf.Buffer, bufferSize),
srcClose: make(chan bool),
destClose: make(chan bool),
2016-04-18 12:44:10 -04:00
}
}
2016-12-09 05:35:27 -05:00
func (v *Stream) Read() (*buf.Buffer, error) {
2016-12-24 18:42:03 -05:00
select {
case <-v.destClose:
return nil, io.ErrClosedPipe
case b := <-v.buffer:
return b, nil
default:
select {
case b := <-v.buffer:
return b, nil
case <-v.srcClose:
return nil, io.EOF
}
2016-04-18 12:44:10 -04:00
}
}
2016-12-22 11:28:06 -05:00
func (v *Stream) Write(data *buf.Buffer) (err error) {
2016-12-24 18:42:03 -05:00
select {
case <-v.destClose:
return io.ErrClosedPipe
case <-v.srcClose:
return io.ErrClosedPipe
default:
select {
case <-v.destClose:
return io.ErrClosedPipe
case <-v.srcClose:
return io.ErrClosedPipe
case v.buffer <- data:
return nil
2016-05-08 22:04:51 -04:00
}
2016-12-24 18:42:03 -05:00
}
2016-04-18 12:44:10 -04:00
}
2016-11-27 15:39:09 -05:00
func (v *Stream) Close() {
2016-12-22 11:28:06 -05:00
defer swallowPanic()
2016-12-24 18:42:03 -05:00
close(v.srcClose)
2016-04-18 12:44:10 -04:00
}
2016-11-27 15:39:09 -05:00
func (v *Stream) Release() {
2016-12-22 11:28:06 -05:00
defer swallowPanic()
2016-12-24 18:42:03 -05:00
close(v.destClose)
v.Close()
2016-12-22 11:28:06 -05:00
2016-12-24 18:42:03 -05:00
n := len(v.buffer)
for i := 0; i < n; i++ {
select {
case b := <-v.buffer:
b.Release()
default:
return
}
2016-04-18 12:44:10 -04:00
}
2016-12-22 11:28:06 -05:00
}
func swallowPanic() {
recover()
2016-04-18 12:44:10 -04:00
}