2023-01-27 21:37:20 +00:00
|
|
|
// Copyright (c) Tailscale Inc & AUTHORS
|
|
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
2022-02-23 23:47:57 +00:00
|
|
|
|
|
|
|
package tailssh
|
|
|
|
|
|
|
|
import (
|
2022-10-09 21:17:38 +00:00
|
|
|
"context"
|
2022-02-23 23:47:57 +00:00
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// sshContext is the context.Context implementation we use for SSH
|
|
|
|
// that adds a CloseWithError method. Otherwise it's just a normalish
|
|
|
|
// Context.
|
|
|
|
type sshContext struct {
|
2022-10-09 21:17:38 +00:00
|
|
|
underlying context.Context
|
|
|
|
cancel context.CancelFunc // cancels underlying
|
|
|
|
mu sync.Mutex
|
|
|
|
closed bool
|
|
|
|
err error
|
2022-02-23 23:47:57 +00:00
|
|
|
}
|
|
|
|
|
2022-10-09 21:17:38 +00:00
|
|
|
func newSSHContext(ctx context.Context) *sshContext {
|
|
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
|
|
return &sshContext{underlying: ctx, cancel: cancel}
|
2022-02-23 23:47:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (ctx *sshContext) CloseWithError(err error) {
|
|
|
|
ctx.mu.Lock()
|
|
|
|
defer ctx.mu.Unlock()
|
|
|
|
if ctx.closed {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
ctx.closed = true
|
|
|
|
ctx.err = err
|
2022-10-09 21:17:38 +00:00
|
|
|
ctx.cancel()
|
2022-02-23 23:47:57 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (ctx *sshContext) Err() error {
|
|
|
|
ctx.mu.Lock()
|
|
|
|
defer ctx.mu.Unlock()
|
|
|
|
return ctx.err
|
|
|
|
}
|
|
|
|
|
2022-10-09 21:17:38 +00:00
|
|
|
func (ctx *sshContext) Done() <-chan struct{} { return ctx.underlying.Done() }
|
2022-02-23 23:47:57 +00:00
|
|
|
func (ctx *sshContext) Deadline() (deadline time.Time, ok bool) { return }
|
2022-10-09 21:17:38 +00:00
|
|
|
func (ctx *sshContext) Value(k any) any { return ctx.underlying.Value(k) }
|
2022-02-23 23:47:57 +00:00
|
|
|
|
|
|
|
// userVisibleError is a wrapper around an error that implements
|
|
|
|
// SSHTerminationError, so msg is written to their session.
|
|
|
|
type userVisibleError struct {
|
|
|
|
msg string
|
|
|
|
error
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ue userVisibleError) SSHTerminationMessage() string { return ue.msg }
|
|
|
|
|
|
|
|
// SSHTerminationError is implemented by errors that terminate an SSH
|
|
|
|
// session and should be written to user's sessions.
|
|
|
|
type SSHTerminationError interface {
|
|
|
|
error
|
|
|
|
SSHTerminationMessage() string
|
|
|
|
}
|