-
Notifications
You must be signed in to change notification settings - Fork 9
/
tunio.go
135 lines (113 loc) · 1.89 KB
/
tunio.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
package core
import (
"sync"
)
const (
IP4_HEADER_LEN = 20
TCP_HEADER_LEN = 20
UDP_HEADER_LEN = 8
DNS_PORT = 53
MTU = 1504
)
type TunIO struct {
device *TunDevice
wch chan []byte
mtu int
handler func(pkt []byte)
closed bool
size int
mutex *sync.Mutex
}
func NewTunIO(size int) *TunIO {
return &TunIO{
closed: true,
mtu: MTU,
size: size,
mutex: &sync.Mutex{},
}
}
func (t *TunIO) SetPacketHandler(handler func(pkt []byte)) {
t.handler = handler
}
func (t *TunIO) AttachDevice(device *TunDevice) {
t.wch = make(chan []byte, t.size)
t.device = device
t.closed = false
}
func (t *TunIO) Close() error {
if t.closed {
return nil
}
if t.wch != nil {
t.wch <- nil
close(t.wch)
}
t.closed = true
var err error
if t.device != nil {
err = t.device.Close()
}
return err
}
func (t *TunIO) IsClosed() bool {
return t.closed
}
func (t *TunIO) StartProcess() {
go t.read()
go t.write()
}
func (t *TunIO) read() {
defer func() {
if !t.closed {
t.handler(nil) //notify close exception
}
t.Close()
}()
defer PanicHandler()
for {
pkt := make([]byte, t.mtu)
n, err := t.device.GetInterface().Read(pkt)
if err != nil {
plog.Error("tun read end,status=", err)
return
}
pkt = pkt[:n]
if t.handler != nil {
t.handler(pkt)
}
}
}
func (t *TunIO) write() {
defer func() {
if !t.closed {
t.handler(nil) //notify close exception
}
t.Close()
}()
defer PanicHandler()
for {
pkt, ok := <-t.wch
if !ok {
plog.Info("tunio writing channel closed")
return
}
if pkt == nil {
plog.Info("exit write process")
return
}
_, err := t.device.GetInterface().Write(pkt)
if err != nil {
plog.Error("tun write end,status=", err)
return
}
}
}
func (t *TunIO) Enqueue(pkt []byte) {
if t.IsClosed() {
plog.Debug("tun device have been closed")
return
}
if t.wch != nil {
t.wch <- pkt
}
}