| 14 | ) |
| 15 | |
| 16 | func NewWireGuardDevice(n *Nylon) (dev *device.Device, tunDevice tun.Device, realItf string, err error) { |
| 17 | itfName := n.InterfaceName // attempt to name the interface |
| 18 | |
| 19 | if runtime.GOOS == "darwin" { |
| 20 | itfName = "utun" |
| 21 | } |
| 22 | |
| 23 | tdev, err := tun.CreateTUN(itfName, device.DefaultMTU) |
| 24 | if err != nil { |
| 25 | return nil, nil, "", fmt.Errorf("failed to create TUN: %v. Check if an interface with the name nylon exists already", err) |
| 26 | } |
| 27 | realInterfaceName, err := tdev.Name() |
| 28 | if err == nil { |
| 29 | itfName = realInterfaceName |
| 30 | } |
| 31 | |
| 32 | wgLog := n.Log.With("module", log.ScopePolyamide) |
| 33 | |
| 34 | // setup WireGuard |
| 35 | dev = device.NewDevice(tdev, conn.NewDefaultBind(), &device.Logger{ |
| 36 | Verbosef: func(format string, args ...any) { |
| 37 | if n.DBG_log_wireguard { |
| 38 | wgLog.Debug(fmt.Sprintf(format, args...)) |
| 39 | } |
| 40 | }, |
| 41 | Errorf: func(format string, args ...any) { |
| 42 | if strings.Contains(format, "Failed to send PolySock packets") { |
| 43 | return |
| 44 | } |
| 45 | wgLog.Error(fmt.Sprintf(format, args...)) |
| 46 | }, |
| 47 | }) |
| 48 | |
| 49 | // start uapi for wg command |
| 50 | n.wgUapi, err = InitUAPI(n.Log, itfName) |
| 51 | if err != nil { |
| 52 | return nil, nil, "", err |
| 53 | } |
| 54 | |
| 55 | if n.wgUapi != nil { |
| 56 | go func() { |
| 57 | for n.Context.Err() == nil { |
| 58 | accept, err := n.wgUapi.Accept() |
| 59 | if err != nil { |
| 60 | n.Log.Debug(err.Error()) |
| 61 | continue |
| 62 | } |
| 63 | go dev.IpcHandle(accept) |
| 64 | } |
| 65 | }() |
| 66 | } |
| 67 | |
| 68 | n.Log.Info("Created WireGuard interface", "name", itfName) |
| 69 | return dev, tdev, itfName, nil |
| 70 | } |
| 71 | |
| 72 | func CleanupWireGuardDevice(n *Nylon) error { |
| 73 | n.Device.Close() |