tun_linux.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. //go:build !android && !e2e_testing
  2. // +build !android,!e2e_testing
  3. package nebula
  4. import (
  5. "fmt"
  6. "io"
  7. "net"
  8. "os"
  9. "strings"
  10. "unsafe"
  11. "github.com/sirupsen/logrus"
  12. "github.com/vishvananda/netlink"
  13. "golang.org/x/sys/unix"
  14. )
  15. type Tun struct {
  16. io.ReadWriteCloser
  17. fd int
  18. Device string
  19. Cidr *net.IPNet
  20. MaxMTU int
  21. DefaultMTU int
  22. TXQueueLen int
  23. Routes []route
  24. UnsafeRoutes []route
  25. l *logrus.Logger
  26. }
  27. type ifReq struct {
  28. Name [16]byte
  29. Flags uint16
  30. pad [8]byte
  31. }
  32. func ioctl(a1, a2, a3 uintptr) error {
  33. _, _, errno := unix.Syscall(unix.SYS_IOCTL, a1, a2, a3)
  34. if errno != 0 {
  35. return errno
  36. }
  37. return nil
  38. }
  39. /*
  40. func ipv4(addr string) (o [4]byte, err error) {
  41. ip := net.ParseIP(addr).To4()
  42. if ip == nil {
  43. err = fmt.Errorf("failed to parse addr %s", addr)
  44. return
  45. }
  46. for i, b := range ip {
  47. o[i] = b
  48. }
  49. return
  50. }
  51. */
  52. const (
  53. cIFF_TUN = 0x0001
  54. cIFF_NO_PI = 0x1000
  55. cIFF_MULTI_QUEUE = 0x0100
  56. )
  57. type ifreqAddr struct {
  58. Name [16]byte
  59. Addr unix.RawSockaddrInet4
  60. pad [8]byte
  61. }
  62. type ifreqMTU struct {
  63. Name [16]byte
  64. MTU int32
  65. pad [8]byte
  66. }
  67. type ifreqQLEN struct {
  68. Name [16]byte
  69. Value int32
  70. pad [8]byte
  71. }
  72. func newTunFromFd(l *logrus.Logger, deviceFd int, cidr *net.IPNet, defaultMTU int, routes []route, unsafeRoutes []route, txQueueLen int) (ifce *Tun, err error) {
  73. file := os.NewFile(uintptr(deviceFd), "/dev/net/tun")
  74. ifce = &Tun{
  75. ReadWriteCloser: file,
  76. fd: int(file.Fd()),
  77. Device: "tun0",
  78. Cidr: cidr,
  79. DefaultMTU: defaultMTU,
  80. TXQueueLen: txQueueLen,
  81. Routes: routes,
  82. UnsafeRoutes: unsafeRoutes,
  83. l: l,
  84. }
  85. return
  86. }
  87. func newTun(l *logrus.Logger, deviceName string, cidr *net.IPNet, defaultMTU int, routes []route, unsafeRoutes []route, txQueueLen int, multiqueue bool) (ifce *Tun, err error) {
  88. fd, err := unix.Open("/dev/net/tun", os.O_RDWR, 0)
  89. if err != nil {
  90. return nil, err
  91. }
  92. var req ifReq
  93. req.Flags = uint16(cIFF_TUN | cIFF_NO_PI)
  94. if multiqueue {
  95. req.Flags |= cIFF_MULTI_QUEUE
  96. }
  97. copy(req.Name[:], deviceName)
  98. if err = ioctl(uintptr(fd), uintptr(unix.TUNSETIFF), uintptr(unsafe.Pointer(&req))); err != nil {
  99. return nil, err
  100. }
  101. name := strings.Trim(string(req.Name[:]), "\x00")
  102. file := os.NewFile(uintptr(fd), "/dev/net/tun")
  103. maxMTU := defaultMTU
  104. for _, r := range routes {
  105. if r.mtu > maxMTU {
  106. maxMTU = r.mtu
  107. }
  108. }
  109. ifce = &Tun{
  110. ReadWriteCloser: file,
  111. fd: int(file.Fd()),
  112. Device: name,
  113. Cidr: cidr,
  114. MaxMTU: maxMTU,
  115. DefaultMTU: defaultMTU,
  116. TXQueueLen: txQueueLen,
  117. Routes: routes,
  118. UnsafeRoutes: unsafeRoutes,
  119. l: l,
  120. }
  121. return
  122. }
  123. func (c *Tun) NewMultiQueueReader() (io.ReadWriteCloser, error) {
  124. fd, err := unix.Open("/dev/net/tun", os.O_RDWR, 0)
  125. if err != nil {
  126. return nil, err
  127. }
  128. var req ifReq
  129. req.Flags = uint16(cIFF_TUN | cIFF_NO_PI | cIFF_MULTI_QUEUE)
  130. copy(req.Name[:], c.Device)
  131. if err = ioctl(uintptr(fd), uintptr(unix.TUNSETIFF), uintptr(unsafe.Pointer(&req))); err != nil {
  132. return nil, err
  133. }
  134. file := os.NewFile(uintptr(fd), "/dev/net/tun")
  135. return file, nil
  136. }
  137. func (c *Tun) WriteRaw(b []byte) error {
  138. var nn int
  139. for {
  140. max := len(b)
  141. n, err := unix.Write(c.fd, b[nn:max])
  142. if n > 0 {
  143. nn += n
  144. }
  145. if nn == len(b) {
  146. return err
  147. }
  148. if err != nil {
  149. return err
  150. }
  151. if n == 0 {
  152. return io.ErrUnexpectedEOF
  153. }
  154. }
  155. }
  156. func (c *Tun) Write(b []byte) (int, error) {
  157. return len(b), c.WriteRaw(b)
  158. }
  159. func (c Tun) deviceBytes() (o [16]byte) {
  160. for i, c := range c.Device {
  161. o[i] = byte(c)
  162. }
  163. return
  164. }
  165. func (c Tun) Activate() error {
  166. devName := c.deviceBytes()
  167. var addr, mask [4]byte
  168. copy(addr[:], c.Cidr.IP.To4())
  169. copy(mask[:], c.Cidr.Mask)
  170. s, err := unix.Socket(
  171. unix.AF_INET,
  172. unix.SOCK_DGRAM,
  173. unix.IPPROTO_IP,
  174. )
  175. if err != nil {
  176. return err
  177. }
  178. fd := uintptr(s)
  179. ifra := ifreqAddr{
  180. Name: devName,
  181. Addr: unix.RawSockaddrInet4{
  182. Family: unix.AF_INET,
  183. Addr: addr,
  184. },
  185. }
  186. // Set the device ip address
  187. if err = ioctl(fd, unix.SIOCSIFADDR, uintptr(unsafe.Pointer(&ifra))); err != nil {
  188. return fmt.Errorf("failed to set tun address: %s", err)
  189. }
  190. // Set the device network
  191. ifra.Addr.Addr = mask
  192. if err = ioctl(fd, unix.SIOCSIFNETMASK, uintptr(unsafe.Pointer(&ifra))); err != nil {
  193. return fmt.Errorf("failed to set tun netmask: %s", err)
  194. }
  195. // Set the device name
  196. ifrf := ifReq{Name: devName}
  197. if err = ioctl(fd, unix.SIOCGIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  198. return fmt.Errorf("failed to set tun device name: %s", err)
  199. }
  200. // Set the MTU on the device
  201. ifm := ifreqMTU{Name: devName, MTU: int32(c.MaxMTU)}
  202. if err = ioctl(fd, unix.SIOCSIFMTU, uintptr(unsafe.Pointer(&ifm))); err != nil {
  203. // This is currently a non fatal condition because the route table must have the MTU set appropriately as well
  204. c.l.WithError(err).Error("Failed to set tun mtu")
  205. }
  206. // Set the transmit queue length
  207. ifrq := ifreqQLEN{Name: devName, Value: int32(c.TXQueueLen)}
  208. if err = ioctl(fd, unix.SIOCSIFTXQLEN, uintptr(unsafe.Pointer(&ifrq))); err != nil {
  209. // If we can't set the queue length nebula will still work but it may lead to packet loss
  210. c.l.WithError(err).Error("Failed to set tun tx queue length")
  211. }
  212. // Bring up the interface
  213. ifrf.Flags = ifrf.Flags | unix.IFF_UP
  214. if err = ioctl(fd, unix.SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  215. return fmt.Errorf("failed to bring the tun device up: %s", err)
  216. }
  217. // Set the routes
  218. link, err := netlink.LinkByName(c.Device)
  219. if err != nil {
  220. return fmt.Errorf("failed to get tun device link: %s", err)
  221. }
  222. // Default route
  223. dr := &net.IPNet{IP: c.Cidr.IP.Mask(c.Cidr.Mask), Mask: c.Cidr.Mask}
  224. nr := netlink.Route{
  225. LinkIndex: link.Attrs().Index,
  226. Dst: dr,
  227. MTU: c.DefaultMTU,
  228. AdvMSS: c.advMSS(route{}),
  229. Scope: unix.RT_SCOPE_LINK,
  230. Src: c.Cidr.IP,
  231. Protocol: unix.RTPROT_KERNEL,
  232. Table: unix.RT_TABLE_MAIN,
  233. Type: unix.RTN_UNICAST,
  234. }
  235. err = netlink.RouteReplace(&nr)
  236. if err != nil {
  237. return fmt.Errorf("failed to set mtu %v on the default route %v; %v", c.DefaultMTU, dr, err)
  238. }
  239. // Path routes
  240. for _, r := range c.Routes {
  241. nr := netlink.Route{
  242. LinkIndex: link.Attrs().Index,
  243. Dst: r.route,
  244. MTU: r.mtu,
  245. AdvMSS: c.advMSS(r),
  246. Scope: unix.RT_SCOPE_LINK,
  247. }
  248. err = netlink.RouteAdd(&nr)
  249. if err != nil {
  250. return fmt.Errorf("failed to set mtu %v on route %v; %v", r.mtu, r.route, err)
  251. }
  252. }
  253. // Unsafe path routes
  254. for _, r := range c.UnsafeRoutes {
  255. nr := netlink.Route{
  256. LinkIndex: link.Attrs().Index,
  257. Dst: r.route,
  258. MTU: r.mtu,
  259. Priority: r.metric,
  260. AdvMSS: c.advMSS(r),
  261. Scope: unix.RT_SCOPE_LINK,
  262. }
  263. err = netlink.RouteAdd(&nr)
  264. if err != nil {
  265. return fmt.Errorf("failed to set mtu %v on route %v; %v", r.mtu, r.route, err)
  266. }
  267. }
  268. // Run the interface
  269. ifrf.Flags = ifrf.Flags | unix.IFF_UP | unix.IFF_RUNNING
  270. if err = ioctl(fd, unix.SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifrf))); err != nil {
  271. return fmt.Errorf("failed to run tun device: %s", err)
  272. }
  273. return nil
  274. }
  275. func (c *Tun) CidrNet() *net.IPNet {
  276. return c.Cidr
  277. }
  278. func (c *Tun) DeviceName() string {
  279. return c.Device
  280. }
  281. func (c Tun) advMSS(r route) int {
  282. mtu := r.mtu
  283. if r.mtu == 0 {
  284. mtu = c.DefaultMTU
  285. }
  286. // We only need to set advmss if the route MTU does not match the device MTU
  287. if mtu != c.MaxMTU {
  288. return mtu - 40
  289. }
  290. return 0
  291. }