From 2b6e98d3a31efab44202ba4d35b64169ac039988 Mon Sep 17 00:00:00 2001 From: Sir Darkrengarius Date: Mon, 1 Jul 2019 14:05:17 +0300 Subject: [PATCH 1/2] Protect access to listener with mutex --- internal/therealssh/channel.go | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/internal/therealssh/channel.go b/internal/therealssh/channel.go index c3fd9a1b6e..96181dcc83 100644 --- a/internal/therealssh/channel.go +++ b/internal/therealssh/channel.go @@ -11,6 +11,7 @@ import ( "os/user" "path/filepath" "strings" + "sync" "github.com/kr/pty" @@ -33,9 +34,10 @@ type SSHChannel struct { conn net.Conn msgCh chan []byte - session *Session - listener *net.UnixListener - dataCh chan []byte + session *Session + listenerMx sync.Mutex + listener *net.UnixListener + dataCh chan []byte } // OpenChannel constructs new SSHChannel with empty Session. @@ -149,7 +151,9 @@ func (sshCh *SSHChannel) ServeSocket() error { return fmt.Errorf("failed to open unix socket: %s", err) } + sshCh.listenerMx.Lock() sshCh.listener = l + sshCh.listenerMx.Unlock() conn, err := l.AcceptUnix() if err != nil { return fmt.Errorf("failed to accept connection: %s", err) @@ -158,8 +162,7 @@ func (sshCh *SSHChannel) ServeSocket() error { debug("got new socket connection") defer func() { conn.Close() - sshCh.listener.Close() - sshCh.listener = nil + sshCh.closeListener() //nolint:errcheck os.Remove(sshCh.SocketPath()) }() @@ -258,9 +261,7 @@ func (sshCh *SSHChannel) Close() error { sErr = sshCh.session.Close() } - if sshCh.listener != nil { - lErr = sshCh.listener.Close() - } + lErr = sshCh.closeListener() if sErr != nil { return sErr @@ -273,6 +274,19 @@ func (sshCh *SSHChannel) Close() error { return nil } +func (sshCh *SSHChannel) closeListener() error { + sshCh.listenerMx.Lock() + defer sshCh.listenerMx.Unlock() + + if sshCh.listener != nil { + err := sshCh.listener.Close() + sshCh.listener = nil + return err + } + + return nil +} + func debug(format string, v ...interface{}) { if !Debug { return From 907d1702d98317be2dfc87b69760f156352b2917 Mon Sep 17 00:00:00 2001 From: Sir Darkrengarius Date: Mon, 8 Jul 2019 11:31:51 +0300 Subject: [PATCH 2/2] Remove unnecessary `listener != nil` check --- internal/therealssh/channel.go | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/internal/therealssh/channel.go b/internal/therealssh/channel.go index 85882b8161..eafa235bf3 100644 --- a/internal/therealssh/channel.go +++ b/internal/therealssh/channel.go @@ -318,13 +318,7 @@ func (sshCh *SSHChannel) closeListener() error { sshCh.listenerMx.Lock() defer sshCh.listenerMx.Unlock() - if sshCh.listener != nil { - err := sshCh.listener.Close() - sshCh.listener = nil - return err - } - - return nil + return sshCh.listener.Close() } func debug(format string, v ...interface{}) {