-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsyscalls_linux.go
118 lines (96 loc) · 2.36 KB
/
syscalls_linux.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
// +build linux
package water
import (
"os"
"strings"
"syscall"
"unsafe"
)
const (
cIFF_TUN = 0x0001
cIFF_TAP = 0x0002
cIFF_NO_PI = 0x1000
cIFF_MULTI_QUEUE = 0x0100
)
type ifReq struct {
Name [0x10]byte
Flags uint16
pad [0x28 - 0x10 - 2]byte
}
func ioctl(fd uintptr, request uintptr, argp uintptr) error {
_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(request), argp)
if errno != 0 {
return os.NewSyscallError("ioctl", errno)
}
return nil
}
func newTAP(config Config) (ifce *Interface, err error) {
file, err := os.OpenFile("/dev/net/tun", os.O_RDWR, 0)
if err != nil {
return nil, err
}
var flags uint16
flags = cIFF_TAP | cIFF_NO_PI
if config.PlatformSpecificParams.MultiQueue {
flags |= cIFF_MULTI_QUEUE
}
name, err := createInterface(file.Fd(), config.Name, flags)
if err != nil {
return nil, err
}
if err = setDeviceOptions(file.Fd(), config); err != nil {
return nil, err
}
ifce = &Interface{isTAP: true, ReadWriteCloser: file, name: name}
return
}
func newTUN(config Config) (ifce *Interface, err error) {
file, err := os.OpenFile("/dev/net/tun", os.O_RDWR, 0)
if err != nil {
return nil, err
}
var flags uint16
flags = cIFF_TUN | cIFF_NO_PI
if config.PlatformSpecificParams.MultiQueue {
flags |= cIFF_MULTI_QUEUE
}
name, err := createInterface(file.Fd(), config.Name, flags)
if err != nil {
return nil, err
}
if err = setDeviceOptions(file.Fd(), config); err != nil {
return nil, err
}
ifce = &Interface{isTAP: false, ReadWriteCloser: file, name: name}
return
}
func createInterface(fd uintptr, ifName string, flags uint16) (createdIFName string, err error) {
var req ifReq
req.Flags = flags
copy(req.Name[:], ifName)
err = ioctl(fd, syscall.TUNSETIFF, uintptr(unsafe.Pointer(&req)))
if err != nil {
return
}
createdIFName = strings.Trim(string(req.Name[:]), "\x00")
return
}
func setDeviceOptions(fd uintptr, config Config) (err error) {
// Device Permissions
if config.Permissions != nil {
// Set Owner
if err = ioctl(fd, syscall.TUNSETOWNER, uintptr(config.Permissions.Owner)); err != nil {
return
}
// Set Group
if err = ioctl(fd, syscall.TUNSETGROUP, uintptr(config.Permissions.Group)); err != nil {
return
}
}
// Set/Clear Persist Device Flag
value := 0
if config.Persist {
value = 1
}
return ioctl(fd, syscall.TUNSETPERSIST, uintptr(value))
}