From 8088c7a59172a1bfc4e3cab65fb7355cae989947 Mon Sep 17 00:00:00 2001 From: braginini Date: Mon, 21 Jun 2021 11:18:03 +0200 Subject: [PATCH] feature: add stop handling for engine --- cmd/root.go | 2 +- cmd/up.go | 4 +++- connection/engine.go | 17 +++++++++++++++++ iface/iface.go | 5 +++++ 4 files changed, 26 insertions(+), 2 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index 6f0c6d4621c..1c7b0a472cb 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -53,7 +53,7 @@ func SetupCloseHandler() { go func() { for range c { fmt.Println("\r- Ctrl+C pressed in Terminal") - os.Exit(0) + stopUP <- 0 } }() } diff --git a/cmd/up.go b/cmd/up.go index 2646c8fd30b..9c6003f6835 100644 --- a/cmd/up.go +++ b/cmd/up.go @@ -39,6 +39,7 @@ var ( iFaceBlackList[config.IFaceBlackList[i]] = struct{}{} } engine := connection.NewEngine(signalClient, config.StunTurnURLs, config.WgIface, config.WgAddr, iFaceBlackList) + defer engine.Stop() err = engine.Start(myKey, config.Peers) if err != nil { @@ -48,8 +49,9 @@ var ( //signalClient.WaitConnected() SetupCloseHandler() - <-stopUP + code := <-stopUP log.Println("Receive signal to stop running") + os.Exit(code) }, } ) diff --git a/connection/engine.go b/connection/engine.go index 80928e0a35f..0f5c4841440 100644 --- a/connection/engine.go +++ b/connection/engine.go @@ -46,6 +46,23 @@ func NewEngine(signal *signal.Client, stunsTurns []*ice.URL, wgIface string, wgA iFaceBlackList: iFaceBlackList, } } +func (e *Engine) Stop() error { + err := iface.Delete() + if err != nil { + log.Errorf("error while deleting Wireguard interface") + return err + } + + err = e.signal.Close() + if err != nil { + log.Errorf("error while closing a connection to the signal server") + return err + } + for _, c := range e.conns { + c.Close() //nolint + } + return nil +} // Start creates a new tunnel interface and listens to signals from the Signal service. // It also creates an Go routine to handle each peer communication from the config file diff --git a/iface/iface.go b/iface/iface.go index cb51e9ffdd3..e254a5cd554 100644 --- a/iface/iface.go +++ b/iface/iface.go @@ -19,6 +19,11 @@ const ( // Saves tun device object - is it required? var tunIface tun.Device +// Delete deletes an existing Wireguard interface +func Delete() error { + return tunIface.Close() +} + // Create Creates a new Wireguard interface, sets a given IP and brings it up. // Will reuse an existing one. func Create(iface string, address string) error {