forked from ldcsoftware/kcp-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtunnel.go
240 lines (199 loc) · 4.85 KB
/
tunnel.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package kcp
import (
"errors"
"io"
"net"
"sync"
"time"
"golang.org/x/net/ipv4"
"golang.org/x/net/ipv6"
)
var (
errInvalidOperation = errors.New("invalid operation")
)
type input_callback func(tunnel *UDPTunnel, data []byte, addr net.Addr)
type MsgQueue struct {
mu sync.Mutex
msgss [2][]ipv4.Message
wIdx int
}
type (
// UDPTunnel defines a session implemented by UDP
UDPTunnel struct {
conn *net.UDPConn // the underlying packet connection
addr *net.UDPAddr
mu sync.RWMutex
inputcb input_callback
// notifications
die chan struct{} // notify tunnel has Closed
dieOnce sync.Once
chFlush chan struct{} // notify Write
// packets waiting to be sent on wire
msgsm map[string]*MsgQueue
msgss [][]ipv4.Message
xconn batchConn // for x/net
xconnWriteError error
//simulate
loss int
delayMin int
delayMax int
}
)
// newUDPSession create a new udp session for client or server
func NewUDPTunnel(laddr string, inputcb input_callback) (tunnel *UDPTunnel, err error) {
// network type detection
addr, err := net.ResolveUDPAddr("udp", laddr)
if err != nil {
return nil, err
}
network := "udp4"
if addr.IP.To4() == nil {
network = "udp"
}
conn, err := net.ListenUDP(network, addr)
if err != nil {
return nil, err
}
tunnel = new(UDPTunnel)
tunnel.conn = conn
tunnel.inputcb = inputcb
tunnel.addr = addr
tunnel.die = make(chan struct{})
tunnel.chFlush = make(chan struct{}, 1)
tunnel.msgss = make([][]ipv4.Message, 0)
tunnel.msgsm = make(map[string]*MsgQueue)
// cast to writebatch conn
if addr.IP.To4() != nil {
tunnel.xconn = ipv4.NewPacketConn(conn)
} else {
tunnel.xconn = ipv6.NewPacketConn(conn)
}
go tunnel.readLoop()
go tunnel.writeLoop()
Logf(INFO, "NewUDPTunnel addr:%v", addr)
return tunnel, nil
}
func (t *UDPTunnel) SetReadBuffer(bytes int) error {
Logf(INFO, "UDPTunnel::SetReadBuffer addr:%v bytes:%v", t.addr, bytes)
return t.conn.SetReadBuffer(bytes)
}
func (t *UDPTunnel) SetWriteBuffer(bytes int) error {
Logf(INFO, "UDPTunnel::SetWriteBuffer addr:%v bytes:%v", t.addr, bytes)
return t.conn.SetWriteBuffer(bytes)
}
func (t *UDPTunnel) Close() error {
Logf(INFO, "UDPTunnel::Close addr:%v", t.addr)
var once bool
t.dieOnce.Do(func() {
once = true
})
if !once {
return io.ErrClosedPipe
}
// maybe leak, but that's ok
// 1. before pushMsgs
// 2. Close
// 3. pushMsgs
close(t.die)
t.conn.Close()
return nil
}
func (t *UDPTunnel) LocalAddr() (addr *net.UDPAddr) {
return t.addr
}
// for test
func (t *UDPTunnel) Simulate(loss float64, delayMin, delayMax int) {
Logf(WARN, "UDPTunnel::Simulate addr:%v loss:%v delayMin:%v delayMax:%v", t.addr, loss, delayMin, delayMax)
t.loss = int(loss * 100)
t.delayMin = delayMin
t.delayMax = delayMax
}
func (t *UDPTunnel) pushMsgs(msgs []ipv4.Message) {
target := msgs[0].Addr.String()
t.mu.RLock()
msgq, ok := t.msgsm[target]
t.mu.RUnlock()
if !ok {
t.mu.Lock()
msgq, ok = t.msgsm[target]
if !ok {
msgq := &MsgQueue{}
t.msgsm[target] = msgq
msgq.msgss[msgq.wIdx] = append(msgq.msgss[msgq.wIdx], msgs...)
t.mu.Unlock()
t.notifyFlush()
return
}
t.mu.Unlock()
}
msgq.mu.Lock()
msgq.msgss[msgq.wIdx] = append(msgq.msgss[msgq.wIdx], msgs...)
msgq.mu.Unlock()
t.notifyFlush()
}
func (t *UDPTunnel) popMsgss(msgss *[][]ipv4.Message) {
t.mu.RLock()
for _, msgq := range t.msgsm {
msgq.mu.Lock()
msgs := msgq.msgss[msgq.wIdx]
msgq.wIdx = (msgq.wIdx + 1) % 2
msgq.msgss[msgq.wIdx] = msgq.msgss[msgq.wIdx][:0]
msgq.mu.Unlock()
if len(msgs) != 0 {
*msgss = append(*msgss, msgs)
}
}
t.mu.RUnlock()
}
func (t *UDPTunnel) releaseMsgss(msgss [][]ipv4.Message) {
for _, msgs := range msgss {
for k := range msgs {
xmitBuf.Put(msgs[k].Buffers[0])
msgs[k].Buffers = nil
}
}
}
func (t *UDPTunnel) output(msgs []ipv4.Message) (err error) {
if len(msgs) == 0 {
return errInvalidOperation
}
select {
case <-t.die:
return io.ErrClosedPipe
default:
}
if t.loss == 0 && t.delayMin == 0 && t.delayMax == 0 {
t.pushMsgs(msgs)
return
}
succMsgs := make([]ipv4.Message, 0)
for k := range msgs {
if lossRand.Intn(100) >= t.loss {
succMsgs = append(succMsgs, msgs[k])
}
}
if t.delayMin == 0 && t.delayMax == 0 && len(succMsgs) != 0 {
t.pushMsgs(succMsgs)
return
}
for _, msg := range succMsgs {
delay := time.Duration(t.delayMin+lossRand.Intn(t.delayMax-t.delayMin)) * time.Millisecond
timerSender.Send(t, msg, delay)
}
return
}
func (t *UDPTunnel) input(data []byte, addr net.Addr) {
t.inputcb(t, data, addr)
}
func (t *UDPTunnel) notifyFlush() {
select {
case t.chFlush <- struct{}{}:
default:
}
}
func (t *UDPTunnel) notifyReadError(err error) {
Logf(ERROR, "UDPTunnel::notifyReadError addr:%v err:%v", t.addr, err)
}
func (t *UDPTunnel) notifyWriteError(err error) {
Logf(ERROR, "UDPTunnel::notifyWriteError addr:%v err:%v", t.addr, err)
}