github.com/stackdocker/rkt@v0.10.1-0.20151109095037-1aa827478248/networking/tuntap/tuntap.go (about) 1 // Copyright 2015 The rkt 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 package tuntap 16 17 import ( 18 "bytes" 19 "fmt" 20 "os" 21 "syscall" 22 "unsafe" 23 ) 24 25 const ( 26 Tun = 0x1 27 Tap = 0x2 28 29 NoPi = 0x1000 30 OneQueue = 0x2000 31 VnetHdr = 0x4000 32 TunExcl = 0x8000 33 ) 34 35 type ifReq struct { 36 Name [0x10]byte 37 Flags uint16 38 pad [0x28 - 0x12]byte 39 } 40 41 type Interface struct { 42 name string 43 file *os.File 44 } 45 46 func Open(ifName string, kind uint16) (*Interface, error) { 47 if ifName == "" { 48 ifName = "tap%d" 49 } 50 file, err := os.OpenFile("/dev/net/tun", os.O_RDWR, 0) 51 if err != nil { 52 return nil, err 53 } 54 55 var req ifReq 56 copy(req.Name[:15], ifName) 57 req.Flags = kind | NoPi | VnetHdr 58 59 _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, file.Fd(), uintptr(syscall.TUNSETIFF), uintptr(unsafe.Pointer(&req))) 60 if errno != 0 { 61 file.Close() 62 return nil, fmt.Errorf("ioctl failed (TUNSETIFF): %v", errno) 63 } 64 65 return &Interface{ 66 name: string(req.Name[:bytes.IndexByte(req.Name[:], 0)]), 67 file: file, 68 }, nil 69 } 70 71 func (iface *Interface) Close() error { 72 return iface.file.Close() 73 } 74 75 func operateOnIface(name string, kind uint16, persistency uintptr) (string, error) { 76 iface, err := Open(name, kind) 77 if err != nil { 78 return "", err 79 } 80 81 _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, iface.file.Fd(), uintptr(syscall.TUNSETPERSIST), persistency) 82 err = iface.Close() 83 if err != nil { 84 return "", fmt.Errorf("iface close error : %v", err) 85 } 86 87 if errno != 0 { 88 return "", fmt.Errorf("ioctl failed (TUNSETPERSIST): %v", errno) 89 } 90 91 return iface.name, nil 92 } 93 94 func CreatePersistentIface(nameTemplate string, kind uint16) (string, error) { 95 return operateOnIface(nameTemplate, kind, 1) 96 } 97 98 func RemovePersistentIface(name string, kind uint16) error { 99 _, err := operateOnIface(name, kind, 0) 100 return err 101 }