From 5e5de3a34314d9ac3f549a93e3e30a5a9ce66966 Mon Sep 17 00:00:00 2001 From: Revertron <105154+Revertron@users.noreply.github.com> Date: Tue, 6 Aug 2024 11:28:15 +0200 Subject: [PATCH] Fixed wait for TUN to come up (#1157) So, the function waiting for TUN to come up never succeeds: ``` func waitForTUNUp(ch <-chan wgtun.Event) bool { t := time.After(time.Second * 5) for { select { case ev := <-ch: if ev == wgtun.EventUp { return true } case <-t: return false } } } ``` I've tried the sleep for one second, and it works flawlessly on several PCs. Another point - sometimes, if the service stop abruptly (in case of some errors) there is an old hidden device in the system, that we need to uninstall, and then create new. --- src/tun/tun_windows.go | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/src/tun/tun_windows.go b/src/tun/tun_windows.go index 7bcdb7ac..a2861894 100644 --- a/src/tun/tun_windows.go +++ b/src/tun/tun_windows.go @@ -8,10 +8,12 @@ import ( "fmt" "log" "net/netip" + "time" "github.com/yggdrasil-network/yggdrasil-go/src/config" "golang.org/x/sys/windows" + "golang.zx2c4.com/wintun" wgtun "golang.zx2c4.com/wireguard/tun" "golang.zx2c4.com/wireguard/windows/elevate" "golang.zx2c4.com/wireguard/windows/tunnel/winipcfg" @@ -31,14 +33,23 @@ func (tun *TunAdapter) setup(ifname string, addr string, mtu uint64) error { if guid, err = windows.GUIDFromString("{8f59971a-7872-4aa6-b2eb-061fc4e9d0a7}"); err != nil { return err } - if iface, err = wgtun.CreateTUNWithRequestedGUID(ifname, &guid, int(mtu)); err != nil { - return err - } - if !waitForTUNUp(iface.Events()) { - return fmt.Errorf("TUN did not come up in time") + iface, err = wgtun.CreateTUNWithRequestedGUID(ifname, &guid, int(mtu)) + if err != nil { + // Very rare condition, it will purge the old device and create new + tun.log.Printf("Error creating TUN: '%s'", err) + wintun.Uninstall() + time.Sleep(3 * time.Second) + tun.log.Printf("Trying again") + iface, err = wgtun.CreateTUNWithRequestedGUID(ifname, &guid, int(mtu)) + if err != nil { + return err + } } + tun.log.Printf("Waiting for TUN to come up") + time.Sleep(1 * time.Second) tun.iface = iface if addr != "" { + tun.log.Printf("Setting up address") if err = tun.setupAddress(addr); err != nil { tun.log.Errorln("Failed to set up TUN address:", err) return err @@ -51,6 +62,7 @@ func (tun *TunAdapter) setup(ifname string, addr string, mtu uint64) error { if mtu, err := iface.MTU(); err == nil { tun.mtu = uint64(mtu) } + tun.log.Printf("TUN is set up successfully") return nil }) }