From 67ca506fdff988fa6dce0dad4af51aeb564d7536 Mon Sep 17 00:00:00 2001 From: gertdreyer Date: Mon, 19 Jul 2021 17:32:54 +0200 Subject: [PATCH] Diffing of configuration data (#136) Prevent full reload of wireguard (ReplacePeers: true,) as that can break active sessions. This is done with the UpdateOnly and Removed flags to manage peers. --- server.go | 47 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/server.go b/server.go index 0ab767f..137575b 100644 --- a/server.go +++ b/server.go @@ -275,6 +275,14 @@ func (s *Server) configureWireGuard() error { return err } + log.Debugf("Getting current Wireguard config") + currentdev, err := wg.Device(*wgLinkName) + if err != nil { + return err + } + currentpeers := currentdev.Peers + diffpeers := make([]wgtypes.PeerConfig, 0); + peers := make([]wgtypes.PeerConfig, 0) for user, cfg := range s.Config.Users { for id, dev := range cfg.Clients { @@ -297,11 +305,46 @@ func (s *Server) configureWireGuard() error { } } + // Determine peers updated and to be removed from WireGuard + for _, i := range currentpeers{ + found := false + for _, j := range peers{ + if (i.PublicKey == j.PublicKey){ + found = true + j.UpdateOnly = true + diffpeers = append(diffpeers, j) + break + } + } + if (!found){ + peertoremove := wgtypes.PeerConfig{ + PublicKey : i.PublicKey, + Remove : true, + } + diffpeers = append(diffpeers, peertoremove) + } + } + + // Determine peers to be added to WireGuard + for _, i := range peers{ + found := false + for _, j := range currentpeers{ + if (i.PublicKey == j.PublicKey){ + found = true + break + } + } + if (!found){ + diffpeers = append(diffpeers, i) + } + } + + cfg := wgtypes.Config{ PrivateKey: &key, ListenPort: wgListenPort, - ReplacePeers: true, - Peers: peers, + ReplacePeers: false, + Peers: diffpeers, } err = wg.ConfigureDevice(*wgLinkName, cfg) if err != nil {