/
tunhandlercli.go
147 lines (133 loc) · 2.77 KB
/
tunhandlercli.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
package core
import (
"context"
"errors"
"net"
"sync/atomic"
"time"
log "github.com/sirupsen/logrus"
"github.com/wencaiwulue/kubevpn/pkg/config"
)
func (h *tunHandler) HandleClient(ctx context.Context, tun net.Conn) {
d := &Device{
tun: tun,
closed: atomic.Bool{},
thread: MaxThread,
tunInboundRaw: make(chan *DataElem, MaxSize),
tunInbound: make(chan *DataElem, MaxSize),
tunOutbound: make(chan *DataElem, MaxSize),
chExit: h.chExit,
}
defer d.Close()
d.Start()
remoteAddr, err := net.ResolveUDPAddr("udp", h.node.Remote)
if err != nil {
log.Errorf("[tun] %s: remote addr: %v", tun.LocalAddr(), err)
return
}
for i := 0; i < MaxThread; i++ {
go func() {
for {
select {
case <-ctx.Done():
return
default:
}
func() {
cancel, cancelFunc := context.WithCancel(ctx)
defer cancelFunc()
var packetConn net.PacketConn
defer func() {
if packetConn != nil {
_ = packetConn.Close()
}
}()
if !h.chain.IsEmpty() {
cc, errs := h.chain.DialContext(cancel)
if errs != nil {
log.Debug(errs)
time.Sleep(time.Second * 5)
return
}
var ok bool
if packetConn, ok = cc.(net.PacketConn); !ok {
errs = errors.New("not a packet connection")
log.Errorf("[tun] %s - %s: %s", tun.LocalAddr(), remoteAddr, errs)
return
}
} else {
var errs error
var lc net.ListenConfig
packetConn, errs = lc.ListenPacket(cancel, "udp", "")
if errs != nil {
log.Error(errs)
return
}
}
errs := h.transportTunCli(cancel, d, packetConn, remoteAddr)
if errs != nil {
log.Debugf("[tun] %s: %v", tun.LocalAddr(), errs)
}
}()
}
}()
}
select {
case s := <-h.chExit:
log.Error(s)
return
case <-ctx.Done():
return
}
}
func (h *tunHandler) transportTunCli(ctx context.Context, d *Device, conn net.PacketConn, remoteAddr net.Addr) error {
errChan := make(chan error, 2)
defer conn.Close()
go func() {
for e := range d.tunInbound {
select {
case <-ctx.Done():
return
default:
}
if e.src.Equal(e.dst) {
if d.closed.Load() {
return
}
d.tunOutbound <- e
continue
}
_, err := conn.WriteTo(e.data[:e.length], remoteAddr)
config.LPool.Put(e.data[:])
if err != nil {
errChan <- err
return
}
}
}()
go func() {
for {
select {
case <-ctx.Done():
return
default:
}
b := config.LPool.Get().([]byte)
n, _, err := conn.ReadFrom(b[:])
if err != nil {
errChan <- err
return
}
if d.closed.Load() {
return
}
d.tunOutbound <- &DataElem{data: b[:], length: n}
}
}()
select {
case err := <-errChan:
return err
case <-ctx.Done():
return nil
}
}