tun_darwin.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // +build !ios
  2. package nebula
  3. import (
  4. "fmt"
  5. "io"
  6. "net"
  7. "os/exec"
  8. "strconv"
  9. "github.com/songgao/water"
  10. )
  11. type Tun struct {
  12. Device string
  13. Cidr *net.IPNet
  14. MTU int
  15. UnsafeRoutes []route
  16. *water.Interface
  17. }
  18. func newTun(deviceName string, cidr *net.IPNet, defaultMTU int, routes []route, unsafeRoutes []route, txQueueLen int, multiqueue bool) (ifce *Tun, err error) {
  19. if len(routes) > 0 {
  20. return nil, fmt.Errorf("route MTU not supported in Darwin")
  21. }
  22. // NOTE: You cannot set the deviceName under Darwin, so you must check tun.Device after calling .Activate()
  23. return &Tun{
  24. Cidr: cidr,
  25. MTU: defaultMTU,
  26. UnsafeRoutes: unsafeRoutes,
  27. }, nil
  28. }
  29. func newTunFromFd(deviceFd int, cidr *net.IPNet, defaultMTU int, routes []route, unsafeRoutes []route, txQueueLen int) (ifce *Tun, err error) {
  30. return nil, fmt.Errorf("newTunFromFd not supported in Darwin")
  31. }
  32. func (c *Tun) Activate() error {
  33. var err error
  34. c.Interface, err = water.New(water.Config{
  35. DeviceType: water.TUN,
  36. })
  37. if err != nil {
  38. return fmt.Errorf("activate failed: %v", err)
  39. }
  40. c.Device = c.Interface.Name()
  41. // TODO use syscalls instead of exec.Command
  42. if err = exec.Command("/sbin/ifconfig", c.Device, c.Cidr.String(), c.Cidr.IP.String()).Run(); err != nil {
  43. return fmt.Errorf("failed to run 'ifconfig': %s", err)
  44. }
  45. if err = exec.Command("/sbin/route", "-n", "add", "-net", c.Cidr.String(), "-interface", c.Device).Run(); err != nil {
  46. return fmt.Errorf("failed to run 'route add': %s", err)
  47. }
  48. if err = exec.Command("/sbin/ifconfig", c.Device, "mtu", strconv.Itoa(c.MTU)).Run(); err != nil {
  49. return fmt.Errorf("failed to run 'ifconfig': %s", err)
  50. }
  51. // Unsafe path routes
  52. for _, r := range c.UnsafeRoutes {
  53. if err = exec.Command("/sbin/route", "-n", "add", "-net", r.route.String(), "-interface", c.Device).Run(); err != nil {
  54. return fmt.Errorf("failed to run 'route add' for unsafe_route %s: %s", r.route.String(), err)
  55. }
  56. }
  57. return nil
  58. }
  59. func (c *Tun) CidrNet() *net.IPNet {
  60. return c.Cidr
  61. }
  62. func (c *Tun) DeviceName() string {
  63. return c.Device
  64. }
  65. func (c *Tun) WriteRaw(b []byte) error {
  66. _, err := c.Write(b)
  67. return err
  68. }
  69. func (t *Tun) NewMultiQueueReader() (io.ReadWriteCloser, error) {
  70. return nil, fmt.Errorf("TODO: multiqueue not implemented for darwin")
  71. }