tun_linux.go 7.3 KB

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