tun_linux.go 7.1 KB

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