tun_windows.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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, txQueueLen int) (ifce *Tun, err error) {
  15. if len(routes) > 0 {
  16. return nil, fmt.Errorf("Route MTU not supported in Windows")
  17. }
  18. // NOTE: You cannot set the deviceName under Windows, so you must check tun.Device after calling .Activate()
  19. return &Tun{
  20. Cidr: cidr,
  21. MTU: defaultMTU,
  22. }, nil
  23. }
  24. func (c *Tun) Activate() error {
  25. var err error
  26. c.Interface, err = water.New(water.Config{
  27. DeviceType: water.TUN,
  28. PlatformSpecificParams: water.PlatformSpecificParams{
  29. ComponentID: "tap0901",
  30. Network: c.Cidr.String(),
  31. },
  32. })
  33. if err != nil {
  34. return fmt.Errorf("Activate failed: %v", err)
  35. }
  36. c.Device = c.Interface.Name()
  37. // TODO use syscalls instead of exec.Command
  38. err = exec.Command(
  39. "netsh", "interface", "ipv4", "set", "address",
  40. fmt.Sprintf("name=%s", c.Device),
  41. "source=static",
  42. fmt.Sprintf("addr=%s", c.Cidr.IP),
  43. fmt.Sprintf("mask=%s", net.IP(c.Cidr.Mask)),
  44. "gateway=none",
  45. ).Run()
  46. if err != nil {
  47. return fmt.Errorf("failed to run 'netsh' to set address: %s", err)
  48. }
  49. err = exec.Command(
  50. "netsh", "interface", "ipv4", "set", "interface",
  51. c.Device,
  52. fmt.Sprintf("mtu=%d", c.MTU),
  53. ).Run()
  54. if err != nil {
  55. return fmt.Errorf("failed to run 'netsh' to set MTU: %s", err)
  56. }
  57. return nil
  58. }
  59. func (c *Tun) WriteRaw(b []byte) error {
  60. _, err := c.Write(b)
  61. return err
  62. }