-
Notifications
You must be signed in to change notification settings - Fork 0
/
direct.go
125 lines (109 loc) · 1.86 KB
/
direct.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package ray
import (
"io"
"sync"
"time"
"v2ray.com/core/common/alloc"
)
const (
bufferSize = 128
)
// NewRay creates a new Ray for direct traffic transport.
func NewRay() Ray {
return &directRay{
Input: NewStream(),
Output: NewStream(),
}
}
type directRay struct {
Input *Stream
Output *Stream
}
func (v *directRay) OutboundInput() InputStream {
return v.Input
}
func (v *directRay) OutboundOutput() OutputStream {
return v.Output
}
func (v *directRay) InboundInput() OutputStream {
return v.Input
}
func (v *directRay) InboundOutput() InputStream {
return v.Output
}
type Stream struct {
access sync.RWMutex
closed bool
buffer chan *alloc.Buffer
}
func NewStream() *Stream {
return &Stream{
buffer: make(chan *alloc.Buffer, bufferSize),
}
}
func (v *Stream) Read() (*alloc.Buffer, error) {
if v.buffer == nil {
return nil, io.EOF
}
v.access.RLock()
if v.buffer == nil {
v.access.RUnlock()
return nil, io.EOF
}
channel := v.buffer
v.access.RUnlock()
result, open := <-channel
if !open {
return nil, io.EOF
}
return result, nil
}
func (v *Stream) Write(data *alloc.Buffer) error {
for !v.closed {
err := v.TryWriteOnce(data)
if err != io.ErrNoProgress {
return err
}
}
return io.ErrClosedPipe
}
func (v *Stream) TryWriteOnce(data *alloc.Buffer) error {
v.access.RLock()
defer v.access.RUnlock()
if v.closed {
return io.ErrClosedPipe
}
select {
case v.buffer <- data:
return nil
case <-time.After(2 * time.Second):
return io.ErrNoProgress
}
}
func (v *Stream) Close() {
if v.closed {
return
}
v.access.Lock()
defer v.access.Unlock()
if v.closed {
return
}
v.closed = true
close(v.buffer)
}
func (v *Stream) Release() {
if v.buffer == nil {
return
}
v.Close()
v.access.Lock()
defer v.access.Unlock()
if v.buffer == nil {
return
}
for data := range v.buffer {
data.Release()
}
v.buffer = nil
}