forked from Alienero/tun-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
tun_darwin.go
69 lines (60 loc) · 1.58 KB
/
tun_darwin.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
package tun
import (
"errors"
"fmt"
"log"
"net"
"os"
"os/exec"
)
type tuntap struct {
mtu int
actualName string
fd *os.File
}
func OpenTunTap(addr net.IP, network net.IP, mask net.IP) (Tun, error) {
t := &tuntap{
mtu: 1500,
}
dynamicOpened := false
for i := 0; i < 16; i++ {
tunName := fmt.Sprintf("/dev/tun%d", i)
t.actualName = fmt.Sprintf("tun%d", i)
fd, err := os.OpenFile(tunName, os.O_RDWR, 0)
if err == nil {
t.fd = fd
dynamicOpened = true
break
}
log.Printf("[WARN] Failed to open TUN/TAP device '%s': %v", t.actualName, err)
}
if !dynamicOpened {
return nil, errors.New("cannot allocate TUN/TAP device dynamically.")
}
log.Printf("[INFO] TUN/TAP device %s opened.", t.actualName)
if err := t.setupAddress(addr, network, mask); err != nil {
return nil, err
}
return t, nil
}
func (tun *tuntap) setupAddress(addr net.IP, network net.IP, mask net.IP) error {
cmd := exec.Command("/sbin/ifconfig", tun.actualName, "delete")
_ = cmd.Run()
log.Printf("[INFO] NOTE: Tried to delete pre-existing TUN/TAP instance -- no problem if failed.")
cmd = exec.Command("/sbin/ifconfig", tun.actualName,
addr.String(), network.String(), "netmask", mask.String(), "mtu", "1500", "up")
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("Mac OS X ifconfig failed: %v: %s", err, output)
}
return nil
}
func (tun *tuntap) Write(buf []byte) (int, error) {
return write(tun.fd, buf)
}
func (tun *tuntap) Read(buf []byte) (int, error) {
return read(tun.fd, tun.mtu, buf)
}
func (tun *tuntap) Close() error {
return close(tun.fd)
}