tun: use Ioctl{Get,Set}IfreqMTU from golang.org/x/sys/unix on macOS

Direct syscalls using unix.Syscall(unix.SYS_*, ...) are discouraged on
macOS and might not be supported in future versions. Switch to use
unix.Ioctl{Get,Set}IfreqMTU to get and set an interface's MTU.

Signed-off-by: Tobias Klauser <tklauser@distanz.ch>
Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
This commit is contained in:
Tobias Klauser 2020-10-27 14:39:35 +01:00 committed by Jason A. Donenfeld
parent 8ae09213a7
commit e6b7c4eef3

View file

@ -298,11 +298,6 @@ func (tun *NativeTun) Close() error {
} }
func (tun *NativeTun) setMTU(n int) error { func (tun *NativeTun) setMTU(n int) error {
// open datagram socket
var fd int
fd, err := unix.Socket( fd, err := unix.Socket(
unix.AF_INET, unix.AF_INET,
unix.SOCK_DGRAM, unix.SOCK_DGRAM,
@ -315,29 +310,18 @@ func (tun *NativeTun) setMTU(n int) error {
defer unix.Close(fd) defer unix.Close(fd)
// do ioctl call var ifr unix.IfreqMTU
copy(ifr.Name[:], tun.name)
var ifr [32]byte ifr.MTU = int32(n)
copy(ifr[:], tun.name) err = unix.IoctlSetIfreqMTU(fd, &ifr)
*(*uint32)(unsafe.Pointer(&ifr[unix.IFNAMSIZ])) = uint32(n) if err != nil {
_, _, errno := unix.Syscall( return fmt.Errorf("failed to set MTU on %s: %w", tun.name, err)
unix.SYS_IOCTL,
uintptr(fd),
uintptr(unix.SIOCSIFMTU),
uintptr(unsafe.Pointer(&ifr[0])),
)
if errno != 0 {
return fmt.Errorf("failed to set MTU on %s", tun.name)
} }
return nil return nil
} }
func (tun *NativeTun) MTU() (int, error) { func (tun *NativeTun) MTU() (int, error) {
// open datagram socket
fd, err := unix.Socket( fd, err := unix.Socket(
unix.AF_INET, unix.AF_INET,
unix.SOCK_DGRAM, unix.SOCK_DGRAM,
@ -350,19 +334,10 @@ func (tun *NativeTun) MTU() (int, error) {
defer unix.Close(fd) defer unix.Close(fd)
// do ioctl call ifr, err := unix.IoctlGetIfreqMTU(fd, tun.name)
if err != nil {
var ifr [64]byte return 0, fmt.Errorf("failed to get MTU on %s: %w", tun.name, err)
copy(ifr[:], tun.name)
_, _, errno := unix.Syscall(
unix.SYS_IOCTL,
uintptr(fd),
uintptr(unix.SIOCGIFMTU),
uintptr(unsafe.Pointer(&ifr[0])),
)
if errno != 0 {
return 0, fmt.Errorf("failed to get MTU on %s", tun.name)
} }
return int(*(*int32)(unsafe.Pointer(&ifr[16]))), nil return int(ifr.MTU), nil
} }