github.com/MerlinKodo/gvisor@v0.0.0-20231110090155-957f62ecf90e/pkg/tcpip/link/tun/tun_unsafe.go (about) 1 // Copyright 2018 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 //go:build linux 16 // +build linux 17 18 // Package tun contains methods to open TAP and TUN devices. 19 package tun 20 21 import ( 22 "unsafe" 23 24 "golang.org/x/sys/unix" 25 ) 26 27 // Open opens the specified TUN device, sets it to non-blocking mode, and 28 // returns its file descriptor. 29 func Open(name string) (int, error) { 30 return open(name, unix.IFF_TUN|unix.IFF_NO_PI) 31 } 32 33 // OpenTAP opens the specified TAP device, sets it to non-blocking mode, and 34 // returns its file descriptor. 35 func OpenTAP(name string) (int, error) { 36 return open(name, unix.IFF_TAP|unix.IFF_NO_PI) 37 } 38 39 func open(name string, flags uint16) (int, error) { 40 fd, err := unix.Open("/dev/net/tun", unix.O_RDWR, 0) 41 if err != nil { 42 return -1, err 43 } 44 45 var ifr struct { 46 name [16]byte 47 flags uint16 48 _ [22]byte 49 } 50 51 copy(ifr.name[:], name) 52 ifr.flags = flags 53 _, _, errno := unix.Syscall(unix.SYS_IOCTL, uintptr(fd), unix.TUNSETIFF, uintptr(unsafe.Pointer(&ifr))) 54 if errno != 0 { 55 unix.Close(fd) 56 return -1, errno 57 } 58 59 if err = unix.SetNonblock(fd, true); err != nil { 60 unix.Close(fd) 61 return -1, err 62 } 63 64 return fd, nil 65 }