From e804197acb26a1900b6d5de61cf0d5eabc5b8345 Mon Sep 17 00:00:00 2001 From: Mathias Fredriksson Date: Thu, 28 Jul 2022 21:54:48 +0300 Subject: [PATCH] fix: Guard pty window resize after close Could help alleviate #3236. --- agent/agent.go | 2 +- pty/pty_other.go | 23 ++++++++++++++++++----- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/agent/agent.go b/agent/agent.go index 4bdd1d9103409..a16a4585da58a 100644 --- a/agent/agent.go +++ b/agent/agent.go @@ -457,7 +457,7 @@ func (a *agent) handleSSHSession(session ssh.Session) (retErr error) { for win := range windowSize { resizeErr := ptty.Resize(uint16(win.Height), uint16(win.Width)) if resizeErr != nil { - a.logger.Warn(context.Background(), "failed to resize tty", slog.Error(err)) + a.logger.Warn(context.Background(), "failed to resize tty", slog.Error(resizeErr)) } } }() diff --git a/pty/pty_other.go b/pty/pty_other.go index 23a605f36210b..55f66b4d675c6 100644 --- a/pty/pty_other.go +++ b/pty/pty_other.go @@ -10,6 +10,7 @@ import ( "sync" "github.com/creack/pty" + "golang.org/x/xerrors" ) func newPty() (PTY, error) { @@ -26,6 +27,8 @@ func newPty() (PTY, error) { type otherPty struct { mutex sync.Mutex + closed bool + err error pty, tty *os.File } @@ -55,6 +58,9 @@ func (p *otherPty) Output() ReadWriter { func (p *otherPty) Resize(height uint16, width uint16) error { p.mutex.Lock() defer p.mutex.Unlock() + if p.closed { + return p.err + } return pty.Setsize(p.pty, &pty.Winsize{ Rows: height, Cols: width, @@ -65,17 +71,24 @@ func (p *otherPty) Close() error { p.mutex.Lock() defer p.mutex.Unlock() + if p.closed { + return p.err + } + p.closed = true + err := p.pty.Close() + err2 := p.tty.Close() if err != nil { - _ = p.tty.Close() - return err + err = err2 } - err = p.tty.Close() if err != nil { - return err + p.err = err + } else { + p.err = xerrors.New("pty: closed") } - return nil + + return err } func (p *otherProcess) Wait() error {