github.com/coreos/mantle@v0.13.0/platform/local/tap.go (about) 1 // Copyright 2014-2015 CoreOS, Inc. 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 package local 16 17 import ( 18 "bytes" 19 "os" 20 "syscall" 21 "unsafe" 22 23 "github.com/vishvananda/netlink" 24 ) 25 26 const ( 27 tunDevice = "/dev/net/tun" 28 ) 29 30 // Tun/Tap device that is compatible with the netlink library. 31 type TunTap struct { 32 *netlink.LinkAttrs 33 *os.File 34 } 35 36 func (tt *TunTap) Attrs() *netlink.LinkAttrs { 37 return tt.LinkAttrs 38 } 39 40 func (tt *TunTap) Type() string { 41 return "tun" 42 } 43 44 type ifreqFlags struct { 45 IfrnName [syscall.IFNAMSIZ]byte 46 IfruFlags uint16 47 } 48 49 func ioctl(fd, request, argp uintptr) error { 50 _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, fd, request, argp) 51 if errno != 0 { 52 return errno 53 } 54 return nil 55 } 56 57 func fromZeroTerm(s []byte) string { 58 return string(bytes.TrimRight(s, "\000")) 59 } 60 61 func newTunTap(name string, flags uint16) (*TunTap, error) { 62 dev, err := os.OpenFile(tunDevice, os.O_RDWR, 0) 63 if err != nil { 64 return nil, err 65 } 66 67 var ifr ifreqFlags 68 copy(ifr.IfrnName[:len(ifr.IfrnName)-1], []byte(name+"\000")) 69 ifr.IfruFlags = flags | syscall.IFF_NO_PI 70 71 err = ioctl(dev.Fd(), syscall.TUNSETIFF, uintptr(unsafe.Pointer(&ifr))) 72 if err != nil { 73 return nil, err 74 } 75 76 ifname := fromZeroTerm(ifr.IfrnName[:len(ifr.IfrnName)-1]) 77 iflink, err := netlink.LinkByName(ifname) 78 if err != nil { 79 dev.Close() 80 return nil, err 81 } 82 83 tt := TunTap{ 84 File: dev, 85 LinkAttrs: iflink.Attrs(), 86 } 87 88 return &tt, nil 89 } 90 91 func AddLinkTap(name string) (*TunTap, error) { 92 return newTunTap(name, syscall.IFF_TAP) 93 } 94 95 func AddLinkTun(name string) (*TunTap, error) { 96 return newTunTap(name, syscall.IFF_TUN) 97 }