forked from lifei6671/ssproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.go
120 lines (106 loc) · 2.11 KB
/
io.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
package ssproxy
import (
"github.com/lifei6671/ssproxy/logs"
"io"
"net"
"sync"
"time"
)
const ByteSize = 4108
var pipeBytePool = &sync.Pool{
New: func() interface{} {
return make([]byte, ByteSize)
},
}
type TrafficFunc func(n int)
type Pipeline struct {
read time.Duration
write time.Duration
}
func NewPipeline(readDeadline time.Duration, writeDeadline time.Duration) *Pipeline {
return &Pipeline{read: readDeadline, write: writeDeadline}
}
func (p *Pipeline) Pipe(local, remote net.Conn, trafficFunc TrafficFunc) (written int64, err error) {
buf := pipeBytePool.Get().([]byte)
defer func() {
pipeBytePool.Put(buf)
}()
for {
if p.read > 0 {
_ = local.SetReadDeadline(time.Now().Add(p.read))
}
nr, er := local.Read(buf)
if nr > 0 {
if p.write > 0 {
_ = remote.SetWriteDeadline(time.Now().Add(p.write))
}
nw, ew := remote.Write(buf[0:nr])
if nw > 0 {
written += int64(nw)
if trafficFunc != nil {
trafficFunc(nw)
}
}
if ew != nil {
err = ew
if oe, ok := ew.(*net.OpError); ok {
logs.Error("write OpError ->", oe.Op, oe.Err)
}
break
}
if nr != nw {
err = io.ErrShortWrite
break
}
}
if er != nil {
if er != io.EOF {
err = er
if oe, ok := err.(*net.OpError); ok {
logs.Error("read OpError ->", oe.Op, oe.Err)
}
}
break
}
}
return written, err
}
func Pipe(reader io.Reader, writer io.Writer, trafficFunc TrafficFunc) (written int64, err error) {
buf := pipeBytePool.Get().([]byte)
defer func() {
pipeBytePool.Put(buf)
}()
for {
nr, er := reader.Read(buf)
if nr > 0 {
nw, ew := writer.Write(buf[0:nr])
if nw > 0 {
written += int64(nw)
if trafficFunc != nil {
trafficFunc(nw)
}
}
if ew != nil {
err = ew
if oe, ok := ew.(*net.OpError); ok {
logs.Error("write OpError ->", oe.Op, oe.Err)
}
break
}
if nr != nw {
err = io.ErrShortWrite
break
}
}
if er != nil {
if er != io.EOF {
err = er
if oe, ok := err.(*net.OpError); ok {
logs.Error("read OpError ->", oe.Op, oe.Err)
}
}
break
}
}
return written, err
}