diff --git a/connection/connection.go b/connection/connection.go index 67387571c..44161df54 100644 --- a/connection/connection.go +++ b/connection/connection.go @@ -5,6 +5,7 @@ import ( "fmt" ice "github.com/pion/ice/v2" log "github.com/sirupsen/logrus" + "github.com/wiretrustee/wiretrustee/iface" "golang.zx2c4.com/wireguard/wgctrl/wgtypes" "sync" "time" @@ -144,10 +145,20 @@ func (conn *Connection) Open(timeout time.Duration) error { return err } - err = conn.wgProxy.Start(remoteConn) + pair, err := conn.agent.GetSelectedCandidatePair() if err != nil { return err } + // in case the remote peer is in the local network we don't need a Wireguard proxy, direct communication is possible. + if pair.Local.Type() == ice.CandidateTypeHost && pair.Remote.Type() == ice.CandidateTypeHost { + log.Debugf("remote peer %s is in the local network with an address %s", conn.Config.RemoteWgKey.String(), pair.Remote.Address()) + err = conn.wgProxy.StartLocal(fmt.Sprintf("%s:%d", pair.Remote.Address(), iface.WgPort)) + } else { + err = conn.wgProxy.Start(remoteConn) + if err != nil { + return err + } + } log.Infof("opened connection to peer %s", conn.Config.RemoteWgKey.String()) case <-time.After(timeout): @@ -298,7 +309,6 @@ func (conn *Connection) listenOnConnectionStateChanges() error { } log.Infof("will connect to peer %s via a selected connnection candidate pair %s", conn.Config.RemoteWgKey.String(), pair) } else if state == ice.ConnectionStateDisconnected || state == ice.ConnectionStateFailed { - // todo do we really wanna have a connection restart within connection itself? Think of moving it outside err := conn.Close() if err != nil { log.Warnf("error while closing connection to peer %s -> %s", conn.Config.RemoteWgKey.String(), err.Error()) diff --git a/connection/wgproxy.go b/connection/wgproxy.go index 8eae1d111..489b421cb 100644 --- a/connection/wgproxy.go +++ b/connection/wgproxy.go @@ -42,6 +42,15 @@ func (p *WgProxy) Close() error { return nil } +func (p *WgProxy) StartLocal(host string) error { + err := iface.UpdatePeer(p.iface, p.remoteKey, p.allowedIps, DefaultWgKeepAlive, host) + if err != nil { + log.Errorf("error while configuring Wireguard peer [%s] %s", p.remoteKey, err.Error()) + return err + } + return nil +} + // Start starts a new proxy using the ICE connection func (p *WgProxy) Start(remoteConn *ice.Conn) error { diff --git a/iface/iface.go b/iface/iface.go index cb51e9ffd..5909aaeaf 100644 --- a/iface/iface.go +++ b/iface/iface.go @@ -14,6 +14,7 @@ import ( const ( defaultMTU = 1280 + WgPort = 51820 ) // Saves tun device object - is it required? @@ -85,10 +86,12 @@ func Configure(iface string, privateKey string) error { return err } fwmark := 0 + p := WgPort cfg := wgtypes.Config{ PrivateKey: &key, ReplacePeers: false, FirewallMark: &fwmark, + ListenPort: &p, } err = wg.ConfigureDevice(iface, cfg) if err != nil {