2
0

tun_linux.go 5.4 KB

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