tun_linux.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. package nebula
  2. import (
  3. "fmt"
  4. "io"
  5. "net"
  6. "os"
  7. "strings"
  8. "unsafe"
  9. "github.com/vishvananda/netlink"
  10. "golang.org/x/sys/unix"
  11. )
  12. type Tun struct {
  13. io.ReadWriteCloser
  14. fd int
  15. Device string
  16. Cidr *net.IPNet
  17. MaxMTU int
  18. DefaultMTU int
  19. TXQueueLen int
  20. Routes []route
  21. }
  22. type ifReq struct {
  23. Name [16]byte
  24. Flags uint16
  25. pad [8]byte
  26. }
  27. func ioctl(a1, a2, a3 uintptr) error {
  28. _, _, errno := unix.Syscall(unix.SYS_IOCTL, a1, a2, a3)
  29. if errno != 0 {
  30. return errno
  31. }
  32. return nil
  33. }
  34. /*
  35. func ipv4(addr string) (o [4]byte, err error) {
  36. ip := net.ParseIP(addr).To4()
  37. if ip == nil {
  38. err = fmt.Errorf("failed to parse addr %s", addr)
  39. return
  40. }
  41. for i, b := range ip {
  42. o[i] = b
  43. }
  44. return
  45. }
  46. */
  47. const (
  48. cIFF_TUN = 0x0001
  49. cIFF_NO_PI = 0x1000
  50. )
  51. type ifreqAddr struct {
  52. Name [16]byte
  53. Addr unix.RawSockaddrInet4
  54. pad [8]byte
  55. }
  56. type ifreqMTU struct {
  57. Name [16]byte
  58. MTU int32
  59. pad [8]byte
  60. }
  61. type ifreqQLEN struct {
  62. Name [16]byte
  63. Value int32
  64. pad [8]byte
  65. }
  66. func newTun(deviceName string, cidr *net.IPNet, defaultMTU int, routes []route, txQueueLen int) (ifce *Tun, err error) {
  67. fd, err := unix.Open("/dev/net/tun", os.O_RDWR, 0)
  68. if err != nil {
  69. return nil, err
  70. }
  71. var req ifReq
  72. req.Flags = uint16(cIFF_TUN | cIFF_NO_PI)
  73. copy(req.Name[:], deviceName)
  74. if err = ioctl(uintptr(fd), uintptr(unix.TUNSETIFF), uintptr(unsafe.Pointer(&req))); err != nil {
  75. return
  76. }
  77. name := strings.Trim(string(req.Name[:]), "\x00")
  78. file := os.NewFile(uintptr(fd), "/dev/net/tun")
  79. maxMTU := defaultMTU
  80. for _, r := range routes {
  81. if r.mtu > maxMTU {
  82. maxMTU = r.mtu
  83. }
  84. }
  85. ifce = &Tun{
  86. ReadWriteCloser: file,
  87. fd: int(file.Fd()),
  88. Device: name,
  89. Cidr: cidr,
  90. MaxMTU: maxMTU,
  91. DefaultMTU: defaultMTU,
  92. TXQueueLen: txQueueLen,
  93. Routes: routes,
  94. }
  95. return
  96. }
  97. func (c *Tun) WriteRaw(b []byte) error {
  98. var nn int
  99. for {
  100. max := len(b)
  101. n, err := unix.Write(c.fd, b[nn:max])
  102. if n > 0 {
  103. nn += n
  104. }
  105. if nn == len(b) {
  106. return err
  107. }
  108. if err != nil {
  109. return err
  110. }
  111. if n == 0 {
  112. return io.ErrUnexpectedEOF
  113. }
  114. }
  115. }
  116. func (c Tun) deviceBytes() (o [16]byte) {
  117. for i, c := range c.Device {
  118. o[i] = byte(c)
  119. }
  120. return
  121. }
  122. func (c Tun) Activate() error {
  123. devName := c.deviceBytes()
  124. var addr, mask [4]byte
  125. copy(addr[:], c.Cidr.IP.To4())
  126. copy(mask[:], c.Cidr.Mask)
  127. s, err := unix.Socket(
  128. unix.AF_INET,
  129. unix.SOCK_DGRAM,
  130. unix.IPPROTO_IP,
  131. )
  132. if err != nil {
  133. return err
  134. }
  135. fd := uintptr(s)
  136. ifra := ifreqAddr{
  137. Name: devName,
  138. Addr: unix.RawSockaddrInet4{
  139. Family: unix.AF_INET,
  140. Addr: addr,
  141. },
  142. }
  143. // Set the device ip address
  144. if err = ioctl(fd, unix.SIOCSIFADDR, uintptr(unsafe.Pointer(&ifra))); err != nil {
  145. return fmt.Errorf("failed to set tun address: %s", err)
  146. }
  147. // Set the device network
  148. ifra.Addr.Addr = mask
  149. if err = ioctl(fd, unix.SIOCSIFNETMASK, uintptr(unsafe.Pointer(&ifra))); err != nil {
  150. return fmt.Errorf("failed to set tun netmask: %s", err)
  151. }
  152. // Set the device name
  153. ifrf := ifReq{Name: devName}
  154. if err = ioctl(fd, unix.SIOCGIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  155. return fmt.Errorf("failed to set tun device name: %s", err)
  156. }
  157. // Set the MTU on the device
  158. ifm := ifreqMTU{Name: devName, MTU: int32(c.MaxMTU)}
  159. if err = ioctl(fd, unix.SIOCSIFMTU, uintptr(unsafe.Pointer(&ifm))); err != nil {
  160. return fmt.Errorf("failed to set tun mtu: %s", err)
  161. }
  162. // Set the transmit queue length
  163. ifrq := ifreqQLEN{Name: devName, Value: int32(c.TXQueueLen)}
  164. if err = ioctl(fd, unix.SIOCSIFTXQLEN, uintptr(unsafe.Pointer(&ifrq))); err != nil {
  165. return fmt.Errorf("failed to set tun tx queue length: %s", err)
  166. }
  167. // Bring up the interface
  168. ifrf.Flags = ifrf.Flags | unix.IFF_UP
  169. if err = ioctl(fd, unix.SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  170. return fmt.Errorf("failed to bring the tun device up: %s", err)
  171. }
  172. // Set the routes
  173. link, err := netlink.LinkByName(c.Device)
  174. if err != nil {
  175. return fmt.Errorf("failed to get tun device link: %s", err)
  176. }
  177. // Default route
  178. dr := &net.IPNet{IP: c.Cidr.IP.Mask(c.Cidr.Mask), Mask: c.Cidr.Mask}
  179. nr := netlink.Route{
  180. LinkIndex: link.Attrs().Index,
  181. Dst: dr,
  182. MTU: c.DefaultMTU,
  183. Scope: unix.RT_SCOPE_LINK,
  184. Src: c.Cidr.IP,
  185. Protocol: unix.RTPROT_KERNEL,
  186. Table: unix.RT_TABLE_MAIN,
  187. Type: unix.RTN_UNICAST,
  188. }
  189. err = netlink.RouteReplace(&nr)
  190. if err != nil {
  191. return fmt.Errorf("failed to set mtu %v on the default route %v; %v", c.DefaultMTU, dr, err)
  192. }
  193. // Path routes
  194. for _, r := range c.Routes {
  195. nr := netlink.Route{
  196. LinkIndex: link.Attrs().Index,
  197. Dst: r.route,
  198. MTU: r.mtu,
  199. Scope: unix.RT_SCOPE_LINK,
  200. }
  201. err = netlink.RouteAdd(&nr)
  202. if err != nil {
  203. return fmt.Errorf("failed to set mtu %v on route %v; %v", r.mtu, r.route, err)
  204. }
  205. }
  206. // Run the interface
  207. ifrf.Flags = ifrf.Flags | unix.IFF_UP | unix.IFF_RUNNING
  208. if err = ioctl(fd, unix.SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  209. return fmt.Errorf("failed to run tun device: %s", err)
  210. }
  211. return nil
  212. }