tun_darwin.go 1.8 KB

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