tun.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package wireguard
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "net/netip"
  8. "runtime"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "github.com/xtls/xray-core/common/log"
  13. "golang.zx2c4.com/wireguard/conn"
  14. "golang.zx2c4.com/wireguard/device"
  15. "golang.zx2c4.com/wireguard/tun"
  16. )
  17. type Tunnel interface {
  18. BuildDevice(ipc string, bind conn.Bind) error
  19. DialContextTCPAddrPort(ctx context.Context, addr netip.AddrPort) (net.Conn, error)
  20. DialUDPAddrPort(laddr, raddr netip.AddrPort) (net.Conn, error)
  21. Close() error
  22. }
  23. type tunnel struct {
  24. tun tun.Device
  25. device *device.Device
  26. rw sync.Mutex
  27. }
  28. func (t *tunnel) BuildDevice(ipc string, bind conn.Bind) (err error) {
  29. t.rw.Lock()
  30. defer t.rw.Unlock()
  31. if t.device != nil {
  32. return errors.New("device is already initialized")
  33. }
  34. logger := &device.Logger{
  35. Verbosef: func(format string, args ...any) {
  36. log.Record(&log.GeneralMessage{
  37. Severity: log.Severity_Debug,
  38. Content: fmt.Sprintf(format, args...),
  39. })
  40. },
  41. Errorf: func(format string, args ...any) {
  42. log.Record(&log.GeneralMessage{
  43. Severity: log.Severity_Error,
  44. Content: fmt.Sprintf(format, args...),
  45. })
  46. },
  47. }
  48. t.device = device.NewDevice(t.tun, bind, logger)
  49. if err = t.device.IpcSet(ipc); err != nil {
  50. return err
  51. }
  52. if err = t.device.Up(); err != nil {
  53. return err
  54. }
  55. return nil
  56. }
  57. func (t *tunnel) Close() (err error) {
  58. t.rw.Lock()
  59. defer t.rw.Unlock()
  60. if t.device == nil {
  61. return nil
  62. }
  63. t.device.Close()
  64. t.device = nil
  65. err = t.tun.Close()
  66. t.tun = nil
  67. return nil
  68. }
  69. func CalculateInterfaceName(name string) (tunName string) {
  70. if runtime.GOOS == "darwin" {
  71. tunName = "utun"
  72. } else if name != "" {
  73. tunName = name
  74. } else {
  75. tunName = "tun"
  76. }
  77. interfaces, err := net.Interfaces()
  78. if err != nil {
  79. return
  80. }
  81. var tunIndex int
  82. for _, netInterface := range interfaces {
  83. if strings.HasPrefix(netInterface.Name, tunName) {
  84. index, parseErr := strconv.ParseInt(netInterface.Name[len(tunName):], 10, 16)
  85. if parseErr == nil {
  86. tunIndex = int(index) + 1
  87. }
  88. }
  89. }
  90. tunName = fmt.Sprintf("%s%d", tunName, tunIndex)
  91. return
  92. }