-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathtun_device.go
99 lines (73 loc) · 1.62 KB
/
tun_device.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
package core
import (
"io"
"os"
"syscall"
"github.com/polevpn/water"
)
type TunDevice struct {
ifce *water.Interface
}
type IosTunFile struct {
io.ReadWriteCloser
tun *os.File
header [4]byte
}
func (itf *IosTunFile) Read(p []byte) (int, error) {
buf := make([]byte, len(p)+4)
n, err := itf.tun.Read(buf)
if err != nil {
return n, err
}
copy(itf.header[:], buf[0:4])
copy(p, buf[4:n])
return n - 4, err
}
func (itf *IosTunFile) Write(p []byte) (int, error) {
buf := make([]byte, len(p)+4)
ipVer := p[0] >> 4
if ipVer == VERSION_IP_V4 {
itf.header[3] = syscall.AF_INET
} else if ipVer == VERSION_IP_V6 {
itf.header[3] = syscall.AF_INET6
}
copy(buf[:4], itf.header[:])
copy(buf[4:], p)
_, err := itf.tun.Write(buf)
return len(p), err
}
func (itf *IosTunFile) Close() error {
return itf.tun.Close()
}
func NewIosTunFile(tun *os.File) *IosTunFile {
itf := &IosTunFile{tun: tun}
return itf
}
func NewTunDevice() (*TunDevice, error) {
device := &TunDevice{}
config := water.Config{
DeviceType: water.TUN,
}
ifce, err := water.New(config)
if err != nil {
return nil, err
}
device.ifce = ifce
return device, nil
}
func AttachTunDevice(fd int) *TunDevice {
device := &TunDevice{}
device.ifce = water.NewInterface("tun", os.NewFile(uintptr(fd), "tun"), false)
return device
}
func AttachTunDeviceIos(fd int) *TunDevice {
device := &TunDevice{}
device.ifce = water.NewInterface("tun", NewIosTunFile(os.NewFile(uintptr(fd), "tun")), false)
return device
}
func (td *TunDevice) GetInterface() *water.Interface {
return td.ifce
}
func (td *TunDevice) Close() error {
return td.ifce.Close()
}