2
0

tun_windows.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package nebula
  2. import (
  3. "fmt"
  4. "net"
  5. "os/exec"
  6. "github.com/songgao/water"
  7. )
  8. type Tun struct {
  9. Device string
  10. Cidr *net.IPNet
  11. MTU int
  12. *water.Interface
  13. }
  14. func newTun(deviceName string, cidr *net.IPNet, defaultMTU int, routes []route, unsafeRoutes []route, txQueueLen int) (ifce *Tun, err error) {
  15. if len(routes) > 0 {
  16. return nil, fmt.Errorf("Route MTU not supported in Windows")
  17. }
  18. if len(unsafeRoutes) > 0 {
  19. return nil, fmt.Errorf("unsafeRoutes not supported in Windows")
  20. }
  21. // NOTE: You cannot set the deviceName under Windows, so you must check tun.Device after calling .Activate()
  22. return &Tun{
  23. Cidr: cidr,
  24. MTU: defaultMTU,
  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. PlatformSpecificParams: water.PlatformSpecificParams{
  32. ComponentID: "tap0901",
  33. Network: c.Cidr.String(),
  34. },
  35. })
  36. if err != nil {
  37. return fmt.Errorf("Activate failed: %v", err)
  38. }
  39. c.Device = c.Interface.Name()
  40. // TODO use syscalls instead of exec.Command
  41. err = exec.Command(
  42. "netsh", "interface", "ipv4", "set", "address",
  43. fmt.Sprintf("name=%s", c.Device),
  44. "source=static",
  45. fmt.Sprintf("addr=%s", c.Cidr.IP),
  46. fmt.Sprintf("mask=%s", net.IP(c.Cidr.Mask)),
  47. "gateway=none",
  48. ).Run()
  49. if err != nil {
  50. return fmt.Errorf("failed to run 'netsh' to set address: %s", err)
  51. }
  52. err = exec.Command(
  53. "netsh", "interface", "ipv4", "set", "interface",
  54. c.Device,
  55. fmt.Sprintf("mtu=%d", c.MTU),
  56. ).Run()
  57. if err != nil {
  58. return fmt.Errorf("failed to run 'netsh' to set MTU: %s", err)
  59. }
  60. return nil
  61. }
  62. func (c *Tun) WriteRaw(b []byte) error {
  63. _, err := c.Write(b)
  64. return err
  65. }