tun.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright 2015 flannel 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. package ip
  15. import (
  16. "bytes"
  17. "fmt"
  18. "os"
  19. "syscall"
  20. "unsafe"
  21. )
  22. const (
  23. tunDevice = "/dev/net/tun"
  24. ifnameSize = 16
  25. )
  26. type ifreqFlags struct {
  27. IfrnName [ifnameSize]byte
  28. IfruFlags uint16
  29. }
  30. func ioctl(fd int, request, argp uintptr) error {
  31. _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), request, argp)
  32. if errno != 0 {
  33. return fmt.Errorf("ioctl failed with '%s'", errno)
  34. }
  35. return nil
  36. }
  37. func fromZeroTerm(s []byte) string {
  38. return string(bytes.TrimRight(s, "\000"))
  39. }
  40. func OpenTun(name string) (*os.File, string, error) {
  41. tun, err := os.OpenFile(tunDevice, os.O_RDWR, 0)
  42. if err != nil {
  43. return nil, "", err
  44. }
  45. var ifr ifreqFlags
  46. copy(ifr.IfrnName[:len(ifr.IfrnName)-1], []byte(name+"\000"))
  47. ifr.IfruFlags = syscall.IFF_TUN | syscall.IFF_NO_PI
  48. err = ioctl(int(tun.Fd()), syscall.TUNSETIFF, uintptr(unsafe.Pointer(&ifr)))
  49. if err != nil {
  50. return nil, "", err
  51. }
  52. ifname := fromZeroTerm(ifr.IfrnName[:ifnameSize])
  53. return tun, ifname, nil
  54. }