-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathtaptun_freebsd.go
98 lines (79 loc) · 2.06 KB
/
taptun_freebsd.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
package taptun
import (
"errors"
"os"
"syscall"
"unsafe"
)
type ifreq struct {
name [syscall.IFNAMSIZ]byte
_ [16]byte
}
func interfaceName(fd uintptr) (string, error) {
var name [syscall.IFNAMSIZ]byte
arg := fiodgnameArg{length: syscall.IFNAMSIZ, buf: unsafe.Pointer(&name)}
if err := ioctl(fd, FIODGNAME, unsafe.Pointer(&arg)); err != nil {
return "", err
}
return cstringToGoString(name[:]), nil
}
type ifrenameArg struct {
name [syscall.IFNAMSIZ]byte
data uintptr
}
func renameInterface(from string, to string) error {
s, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, 0)
if err != nil {
return err
}
defer func() {
syscall.Close(s)
}()
var ifr ifrenameArg
copy(ifr.name[:], []byte(from))
var toName [syscall.IFNAMSIZ]byte
copy(toName[:], []byte(to))
ifr.data = uintptr(unsafe.Pointer(&toName))
return ioctl(uintptr(s), syscall.SIOCSIFNAME, unsafe.Pointer(&ifr))
}
func createInterface(clonefile string, name string) (string, *os.File, error) {
// Last byte of name must be nil for C string, so name must be
// short enough to allow that
if len(name) > syscall.IFNAMSIZ-1 {
return "", nil, errors.New("device name too long")
}
f, err := os.OpenFile(clonefile, os.O_RDWR, 0600)
if err != nil {
return "", nil, err
}
fd := f.Fd()
ifname, err := interfaceName(fd)
if err != nil {
f.Close()
return "", nil, err
}
// Interface renamed after creation if a name is specified
if name != "" {
if err := renameInterface(ifname, name); err != nil {
return "", nil, err
}
ifname = name
}
return ifname, f, nil
}
func destroyInterface(name string) error {
s, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, syscall.IPPROTO_IP)
if err != nil {
return err
}
defer syscall.Close(s)
ifreq := ifreq{}
copy(ifreq.name[:], []byte(name))
return ioctl(uintptr(s), syscall.SIOCIFDESTROY, unsafe.Pointer(&ifreq))
}
func openTun(name string) (string, *os.File, error) {
return createInterface("/dev/tun", name)
}
func openTap(name string) (string, *os.File, error) {
return createInterface("/dev/tap", name)
}