session

package
v0.0.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 4, 2026 License: AGPL-3.0 Imports: 30 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package session is SSHYard's SSH sessions: it dials with golang.org/x/crypto/ssh, authenticates by password or private key, checks the host key against known_hosts, opens a shell on a PTY that feeds a vt.Terminal, keeps the connection alive and reconnects it.

Index

Constants

View Source
const (
	ReasonExec  = "exec"  // the server refused the exec channel
	ReasonShell = "shell" // sh was not found
	ReasonParse = "parse" // the output was not a metrics frame
)

Reason codes for a collector that will not try again on this connection. The bar translates them; they are not the remote error text (that text includes the script).

View Source
const TagEnv = "LC_SSHYARD_TERM"

TagEnv is the variable that marks a terminal's shell on its server, set with the "env" request before the shell starts. OpenSSH takes LC_* variables in the default configuration of most distributions.

Variables

View Source
var (
	ErrNoDocker     = errors.New("session: docker is not installed")
	ErrDockerDenied = errors.New("session: no permission to use docker")
)

ErrNoDocker is a server without the docker command; ErrDockerDenied one whose daemon the user may not reach (not in the docker group, and no sudo without a password).

View Source
var (
	ErrTruncated = errors.New("session: metrics frame truncated")
	ErrGarbage   = errors.New("session: metrics frame unreadable")
)

ErrTruncated is a frame that was cut off or longer than 4 KB. ErrGarbage is output that is not a metrics frame.

View Source
var DialAgent = dialAgent

DialAgent connects to the system's SSH agent; a var for tests.

View Source
var ErrAgentEmpty = errors.New("session: the SSH agent has no keys")

ErrAgentEmpty reports an agent that holds no keys.

View Source
var ErrAgentUnavailable = errors.New("session: no SSH agent is running")

ErrAgentUnavailable reports that no SSH agent answers: SSH_AUTH_SOCK is unset or dead (macOS, Linux), or the OpenSSH agent service is not running (Windows).

View Source
var ErrInputBusy = errors.New("session: input write in progress")

ErrInputBusy means another whole input write is still in progress. Input is refused rather than queued, so the UI never waits for a blocked writer's lock.

View Source
var ErrKeepAliveTimeout = errors.New("session: server stopped responding (keepalive timeout)")

ErrKeepAliveTimeout reports a server that stopped answering keepalives.

View Source
var ErrNoBanner = errors.New("session: the server sent no SSH greeting")

ErrNoBanner reports a server that accepted the TCP connection but sent nothing, not even its SSH version, before the timeout: sshd hung or overloaded, or a firewall that lets the connection through and then drops what follows.

View Source
var ErrNoCredentials = errors.New("session: no password or key")

ErrNoCredentials reports a host with nothing to authenticate with.

View Source
var ErrNoCwd = errors.New("session: the shell's directory could not be read")

ErrNoCwd is ShellCwd finding no shell, or no directory for it.

View Source
var ErrNoProcs = errors.New("session: the server's processes could not be read")

ErrNoProcs is a server whose processes cannot be read: not Linux (no /proc), or output that is not the script's.

View Source
var ErrPassphraseNeeded = errors.New("session: the private key needs a passphrase")

ErrPassphraseNeeded reports a private key encrypted with a passphrase SSHYard does not have.

View Source
var ErrPassphraseWrong = errors.New("session: wrong passphrase for the private key")

ErrPassphraseWrong reports a passphrase that does not decrypt the key.

Functions

func Dial

func Dial(ctx context.Context, cfg Config) (*ssh.Client, error)

Dial connects and authenticates to the host of cfg: through its proxy and each of its jump hosts in turn, opening a direct-tcpip channel on one to reach the next (no nc on the remote). Every hop checks its host key and logs in with its own credentials. Closing the client returned closes the hops under it; losing one loses it.

func DockerCommand

func DockerCommand(action DockerAction, ref string) string

DockerCommand is the script doing action to ref, "" for an action or a reference that may not be.

func DockerDo

func DockerDo(ctx context.Context, client *ssh.Client, action DockerAction, ref string) error

DockerDo does action to the container or image ref.

func DockerLogs

func DockerLogs(ctx context.Context, client *ssh.Client, ref string, lines int) (string, error)

DockerLogs is the last lines of a container's output, stdout and stderr together.

func DockerRefOK

func DockerRefOK(ref string) bool

DockerRefOK reports whether ref may go into a docker command.

func Exec

func Exec(ctx context.Context, client *ssh.Client, command string, stdout, stderr io.Writer) error

Exec runs command on an already-authenticated client. It never dials and does not take a pool reference. stdout and stderr receive the remote output as it arrives; a nil writer discards that stream. Cancelling ctx closes the channel. Exec waits for the remote exit status: a non-zero status is *ssh.ExitError, and a cancel with no status returns ctx.Err().

func ExecStarted

func ExecStarted(ctx context.Context, client *ssh.Client, command string, stdout, stderr io.Writer, started func(*ssh.Session)) error

ExecStarted is Exec. started, when set, is called after the command starts and must not block. The session stays open until ExecStarted returns; the callback may Signal it until then.

func MetricsCommand

func MetricsCommand(interval int, mount string) string

MetricsCommand is the remote command: sh -c of the fixed script, then the interval and the mount as arguments. It re-checks both, so a caller that skipped Normalize still cannot interpolate them.

func MetricsInterval

func MetricsInterval(n int) int

MetricsInterval returns n when it is 1, 2, 5 or 10, and 2 otherwise.

func MetricsMountOK

func MetricsMountOK(mount string) bool

MetricsMountOK reports whether mount may be passed to the remote script. Empty is fine. Anything else must be an absolute path with no shell metacharacters; the command quotes it as well.

func ProcsCommand

func ProcsCommand() string

ProcsCommand is the remote command reading the processes once.

func ShellCwd

func ShellCwd(ctx context.Context, client *ssh.Client, tag string) (string, error)

ShellCwd asks the server over client which directory the shell tagged tag is in, for a shell that does not report it (OSC 7); "" for a shell the server did not tag, found as the connection's one terminal. It reads Linux's /proc, so it fails on other servers, as when it finds no shell, or more than one untagged (ErrNoCwd).

Types

type CPU

type CPU struct {
	User, Nice, System, Idle, IOWait, IRQ, SoftIRQ, Steal uint64
}

CPU counters are cumulative jiffies (or ticks) since boot.

type Collector

type Collector struct {
	// contains filtered or unexported fields
}

Collector runs one metrics command on a client it does not own and does not dial. One host's panes share one Collector. A failure sticks to that client; a later Start with a different client (a reconnect) tries once more.

func NewCollector

func NewCollector() *Collector

NewCollector returns a collector that is not running.

func (*Collector) Start

func (c *Collector) Start(client *ssh.Client, interval int, mount string)

Start runs the metrics command on client. It does nothing when client is nil, when this client already failed, or when the same command is already running. A new client replaces the previous run. Start does not wait: the new command waits, on its own goroutine, until the previous one has left its channel, and a command cancelled before that opens nothing.

func (*Collector) Stop

func (c *Collector) Stop()

Stop cancels the command and returns without waiting for the channel. It does not mark the collector failed, so a later Start runs again.

func (*Collector) View

func (c *Collector) View() (Reading, string)

View returns the latest reading. reason is a Reason constant when this client has failed and is empty otherwise.

func (*Collector) Wait

func (c *Collector) Wait(ctx context.Context) error

Wait blocks until the latest command has finished or ctx ends. A nil ctx waits until the command finishes.

type Config

type Config struct {
	Addr string // host:port
	User string
	// Credentials returns the credentials to authenticate with, read
	// from the keychain or asked of the user. It is called for every
	// connection attempt, off the UI goroutine.
	Credentials func(ctx context.Context) (Credentials, error)
	// HostKey checks the server's key; a KnownHosts' Callback.
	HostKey ssh.HostKeyCallback
	// Dial dials the TCP connection; nil is net.Dialer.
	Dial func(ctx context.Context, network, addr string) (net.Conn, error)
	// Timeout bounds dialing and the SSH handshake; 0 is 15 seconds.
	Timeout time.Duration
	// Pool, when set, shares the connection under Key with the other
	// sessions of the pool on the same Key: they open their own channel
	// (a shell, SFTP) on one authenticated connection.
	Pool *Pool
	Key  string
	// Name names the host in progress reports; ID identifies it in a
	// HopError.
	Name, ID string
	// Jumps are the hosts dialed through first, first hop first.
	Jumps []Hop
	// Proxy, when set, is what the first hop is dialed through.
	Proxy *netproxy.Dialer
	// Progress, when set, hears the name of each hop as it is dialed.
	Progress func(hop string)
}

Config is how to connect to a host.

type Container

type Container struct {
	ID      string `json:"ID"`
	Name    string `json:"Names"`
	Image   string `json:"Image"`
	Command string `json:"Command"`
	State   string `json:"State"` // running, exited, paused, created, restarting, dead
	Status  string `json:"Status"`
	Ports   string `json:"Ports"`
	Created string `json:"RunningFor"`
}

Container is a Docker container as docker ps lists it.

func (Container) Running

func (c Container) Running() bool

Running reports whether the container runs (paused or not).

type Core

type Core struct {
	Pct float64
	OK  bool
}

Core is one core's busy percent since the previous sample.

type Credentials

type Credentials struct {
	Password   string
	PrivateKey []byte
	Passphrase []byte
	// Agent signs with the system SSH agent's keys.
	Agent bool
	// User, when set, logs in instead of Config.User (a credential's
	// own user name).
	User string
}

Credentials are what a host authenticates with.

type Decoder

type Decoder struct {
	// contains filtered or unexported fields
}

Decoder splits a byte stream into frames. A line "." between frames is a heartbeat and is ignored. Write returns every complete sample before the first error.

func (*Decoder) Close

func (d *Decoder) Close() error

Close reports a frame that was still open, or a half-read line.

func (*Decoder) Write

func (d *Decoder) Write(p []byte) ([]Sample, error)

Write appends p and returns the frames that finished with this write.

type DockerAction

type DockerAction string

DockerAction is what can be done to a container or an image.

const (
	DockerStart       DockerAction = "start"
	DockerStop        DockerAction = "stop"
	DockerRestart     DockerAction = "restart"
	DockerPause       DockerAction = "pause"
	DockerUnpause     DockerAction = "unpause"
	DockerRemove      DockerAction = "rm -f"
	DockerRemoveImage DockerAction = "rmi"
)

type DockerInfo

type DockerInfo struct {
	Version    string
	Sudo       bool
	Containers []Container
	Images     []Image
}

DockerInfo is what DockerList read. Sudo is set when the user reaches the daemon only through sudo.

func DockerList

func DockerList(ctx context.Context, client *ssh.Client) (DockerInfo, error)

DockerList reads the containers and the images of the server.

func ParseDockerList

func ParseDockerList(out []byte) (DockerInfo, error)

ParseDockerList reads the output of the list script.

type GPU

type GPU struct {
	Util, MemUsed, MemTotal, Temp int64
	UtilOK, MemOK, TempOK         bool
}

GPU is one NVIDIA device. An OK flag is false when that field was "-".

type Hop

type Hop struct {
	// Name is how progress and errors name the hop.
	Name        string
	Addr        string
	User        string
	Credentials func(ctx context.Context) (Credentials, error)
	HostKey     ssh.HostKeyCallback
	// ID identifies the hop's host to the caller, in a HopError.
	ID string
}

Hop is one host dialed through on the way to Config.Addr: a jump host, with its own credentials and host key check.

type HopError

type HopError struct {
	Index int
	ID    string
	Name  string
	// Jump is whether the hop is a jump host, not the target.
	Jump bool
	Err  error
}

HopError is a failure at one hop of a jump chain: Index 0 is the first jump host, len(Jumps) the target.

func (*HopError) Error

func (e *HopError) Error() string

func (*HopError) Unwrap

func (e *HopError) Unwrap() error

type HostKeyChangedError

type HostKeyChangedError struct {
	Host        string
	Key         ssh.PublicKey
	Fingerprint string
	Line        int // the line of known_hosts with the old key
	File        string
}

HostKeyChangedError reports a host whose key does not match the one in known_hosts: possibly an attack, so SSHYard refuses to connect and does not offer to replace the key.

func (*HostKeyChangedError) Error

func (e *HostKeyChangedError) Error() string

type Image

type Image struct {
	ID         string `json:"ID"`
	Repository string `json:"Repository"`
	Tag        string `json:"Tag"`
	Size       string `json:"Size"`
	Created    string `json:"CreatedSince"`
}

Image is a Docker image as docker images lists it.

func (Image) Ref

func (i Image) Ref() string

Ref is the image as docker names it: repository:tag, or its ID when it has neither.

type Kind

type Kind int

Kind is a category of connection error, for the message the UI shows.

const (
	KindNone Kind = iota
	KindAuth
	KindNetwork
	KindTimeout
	// KindNoBanner: the server took the connection but never answered.
	KindNoBanner
	KindHostUnknown
	KindHostChanged
	KindPassphrase
	KindNoCredentials
	// KindAgent: the SSH agent is not running or has no keys.
	KindAgent
	// KindProxyAuth: the proxy refused its user name and password.
	KindProxyAuth
	// KindProxy: the proxy could not be reached, or would not connect.
	KindProxy
	KindOther
)

func Classify

func Classify(err error) Kind

Classify returns the kind of a connection error.

func (Kind) Retryable

func (k Kind) Retryable() bool

Retryable reports whether reconnecting automatically may help: not when the user has to do something first.

type KnownHosts

type KnownHosts struct {
	// contains filtered or unexported fields
}

KnownHosts is a known_hosts file in OpenSSH's format, SSHYard's own, which it adds keys the user trusts to.

func OpenKnownHosts

func OpenKnownHosts(path string) (*KnownHosts, error)

OpenKnownHosts opens the known_hosts file at path, creating it.

func (*KnownHosts) Add

func (k *KnownHosts) Add(host string, key ssh.PublicKey) error

Add trusts key for host (host:port as dialed).

func (*KnownHosts) Callback

func (k *KnownHosts) Callback() ssh.HostKeyCallback

Callback is the ssh.HostKeyCallback that checks keys against the file.

func (*KnownHosts) Contents

func (k *KnownHosts) Contents() ([]byte, error)

Contents is the file as it is.

func (*KnownHosts) Merge

func (k *KnownHosts) Merge(data []byte) (int, error)

Merge adds the lines of data, another known_hosts file, that this one does not have, and returns how many. Comments, blank lines and lines that do not parse are left out, so the file stays readable.

func (*KnownHosts) Path

func (k *KnownHosts) Path() string

Path is the file's path.

type NIC

type NIC struct {
	Name   string
	RX, TX uint64
}

NIC counters are cumulative bytes since boot.

type NICRate

type NICRate struct {
	Name     string
	Up, Down float64
	OK       bool
}

NICRate is one interface's bytes per second since the previous sample.

type Options

type Options struct {
	// KeepAlive is how often to probe the server; 0 turns probes off.
	KeepAlive time.Duration
	// KeepAliveMax is how many probes in a row may fail before the
	// connection counts as lost; 0 is 3.
	KeepAliveMax int
	// AutoReconnect reconnects after the connection is lost.
	AutoReconnect bool
	// MaxAttempts bounds automatic reconnects in a row; 0 is 8.
	MaxAttempts int
	// Backoff is the first retry delay, doubled each attempt up to
	// MaxBackoff; 0 are 1 and 30 seconds.
	Backoff, MaxBackoff time.Duration
	// Term is the TERM to request; "" is xterm-256color.
	Term string
	// Scrollback is the terminal's scrollback; 0 is vt.DefaultScrollback.
	Scrollback int
	// NoShell connects without a shell or PTY, for a files (SFTP) pane:
	// the connection is kept, probed and reconnected like a shell's.
	NoShell bool
	// Local runs the user's shell on this computer, in a pseudo-terminal,
	// instead of connecting anywhere: the Config is not used, and the
	// session has no Client. It ends, Exited, with the shell.
	Local bool
}

Options are a session's behavior.

type Pool

type Pool struct {
	// contains filtered or unexported fields
}

Pool shares one authenticated SSH connection per host among sessions, as OpenSSH's ControlMaster does: a second terminal, a split or a files pane on a host already connected opens a channel (a shell, the SFTP subsystem) on the connection there is, without dialing or asking for a password again. Connections are counted: the last session to let go of one closes it. When one drops, every session on it reconnects, and the first to do so dials the one new connection the others then share, so the credentials are asked for once.

func NewPool

func NewPool() *Pool

NewPool returns an empty pool.

func (*Pool) Acquire

func (p *Pool) Acquire(ctx context.Context, key string, cfg Config) (client *ssh.Client, release func(), err error)

Acquire returns the pool's connection under key, dialing it with cfg when there is none (or the one there was broke). Sessions that ask while it is being dialed wait for that dial and share what it gives, its error too. release lets go of the connection; it is safe to call more than once.

func (*Pool) Broken

func (p *Pool) Broken(client *ssh.Client)

Broken reports a connection lost: the pool forgets it, so that the next Acquire dials a new one, and closes it, so that every session on it notices.

func (*Pool) Shared

func (p *Pool) Shared(key string) int

Shared reports how many sessions hold the connection under key, 0 when there is none.

type Proc

type Proc struct {
	PID        int
	Name, User string
	// CPU is the share of one CPU it took between the readings, in
	// percent, as top shows it (up to 100 per CPU); CPUOK is false for a
	// process the first reading lacked.
	CPU    float64
	CPUOK  bool
	MemKB  uint64
	MemPct float64
	// Disk is the bytes it read and wrote from disk a second between the
	// readings, DiskOK whether that is known.
	Disk   float64
	DiskOK bool
}

Proc is a process as two readings show it.

func ProcDelta

func ProcDelta(prev, cur ProcSample) []Proc

ProcDelta is the processes of cur, with what they used since prev.

type ProcRaw

type ProcRaw struct {
	PID   int
	Name  string
	UID   string
	Ticks uint64 // user and system CPU time, in clock ticks
	RSS   uint64 // resident pages
	// Read and Write are the bytes the process read and wrote from disk,
	// IOOK whether they could be read.
	Read, Write uint64
	IOOK        bool
}

ProcRaw is one process as one reading of /proc saw it.

type ProcSample

type ProcSample struct {
	At       time.Time
	CPUTotal uint64 // all CPUs' time, in clock ticks
	CPUs     int
	PageKB   uint64
	MemKB    uint64
	Users    map[string]string // names by uid
	Procs    map[int]ProcRaw
}

ProcSample is one reading of a server's processes.

func ParseProcs

func ParseProcs(out []byte) (ProcSample, error)

ParseProcs reads the output of ProcsCommand.

func ReadProcs

func ReadProcs(ctx context.Context, client *ssh.Client) (ProcSample, error)

ReadProcs reads the processes of the server over client once.

type Reading

type Reading struct {
	OS                      string
	CPU                     float64
	CPUOK                   bool
	Cores                   []Core
	MemUsedKB, MemTotalKB   uint64
	MemPct                  float64
	MemOK                   bool
	SwapUsedKB, SwapTotalKB uint64
	SwapPct                 float64
	SwapOK                  bool
	Vols                    []VolUse
	Load1, Load5, Load15    float64
	LoadOK                  bool
	NetUp, NetDown          float64 // bytes per second, non-loopback
	NetOK                   bool
	NICs                    []NICRate
	GPUs                    []GPU
}

Reading is what the bar shows. Tick-based CPU and network stay unknown until a second sample. A cpupct line is already a percent. Memory, disk, load and GPU come from the latest sample.

func Delta

func Delta(prev, cur Sample, dt time.Duration) Reading

Delta turns two samples into bar figures. dt is the time from prev to cur; network rates need it, CPU percent does not. A counter that goes backwards is a reset: that CPU is unknown, and that interface's rate for the interval is 0.

type Sample

type Sample struct {
	OS                   string
	CPU                  CPU
	CPUOK                bool
	CPUPct               float64
	CPUPctOK             bool // set by a cpupct line, which is already a percent
	Cores                []CPU
	MemTotal, MemAvail   uint64
	SwapTotal, SwapFree  uint64
	MemOK                bool
	Load1, Load5, Load15 float64
	LoadOK               bool
	NICs                 []NIC
	Vols                 []Vol
	GPUs                 []GPU
}

Sample is one metrics frame. OK flags are false when that line was absent.

func ParseFrame

func ParseFrame(body string) (Sample, error)

ParseFrame parses one frame body (without the <<<SSHYARD / >>> markers).

type Session

type Session struct {
	Term *vt.Terminal

	// OnChange, when set, is called from any goroutine whenever the
	// terminal or the status changes: the app invalidates its window.
	OnChange func()
	// contains filtered or unexported fields
}

Session is a shell on a host. Its terminal stays the same across reconnects, so scrollback survives them.

func New

func New(cfg Config, opts Options, cols, rows int) *Session

New returns a session of cols×rows; Start connects it.

func (*Session) CaptureInput

func (s *Session) CaptureInput() (io.Writer, error)

CaptureInput binds input to the current connection. A later reconnect never redirects these writes to a different shell. Writes may block on remote flow control, so callers on the UI thread must write in a background goroutine.

func (*Session) Client

func (s *Session) Client() *ssh.Client

Client returns the SSH client while connected, for SFTP.

func (*Session) Close

func (s *Session) Close()

Close ends the session for good.

func (*Session) Config

func (s *Session) Config() Config

Config returns the session's configuration.

func (*Session) Done

func (s *Session) Done() <-chan struct{}

Done is closed when the session's connection loop ends.

func (*Session) Latency

func (s *Session) Latency() (time.Duration, bool)

Latency is the last keepalive round trip. ok is false until one probe has been answered.

func (*Session) Reconnect

func (s *Session) Reconnect()

Reconnect connects again now: after a failure, after the connection was lost, or while waiting for the next automatic attempt. The user does this after fixing what failed (trusting a host key, typing a password).

func (*Session) Resize

func (s *Session) Resize(cols, rows int)

Resize changes the size of the terminal and of the remote PTY.

func (*Session) SetProbe

func (s *Session) SetProbe(d time.Duration)

SetProbe sets how often a visible metrics bar measures keepalive round trip. d <= 0 keeps Options.KeepAlive (and sends nothing when that is 0). The same value again does not wake the probe, so a frame may call this every time it draws.

func (*Session) Start

func (s *Session) Start()

Start connects the session in the background.

func (*Session) Status

func (s *Session) Status() Status

Status returns the session's status.

func (*Session) Tag

func (s *Session) Tag() (string, bool)

Tag is the mark of the session's shell (TagEnv), and whether the server took it for the shell running now.

func (*Session) Write

func (s *Session) Write(p []byte) (int, error)

Write sends input to the shell; it is dropped while disconnected.

type State

type State int

State is a session's connection state.

const (
	Idle State = iota
	Connecting
	Connected
	Reconnecting // waiting to retry after the connection was lost
	Disconnected // the connection was lost and is not retried
	Exited       // the remote shell exited
	Failed       // connecting failed in a way the user must address
	Closed       // the user closed the session
)

func (State) String

func (s State) String() string

type Status

type Status struct {
	State State
	Err   error
	// Attempt is the reconnect attempt, from 1; Retry when it starts.
	Attempt int
	Retry   time.Time
	// Connects counts successful connections.
	Connects int
	// Hop is the host being dialed while connecting through jump
	// hosts: a jump host's name, or the host's own at the last hop.
	Hop string
}

Status is a session's state, for the UI.

type UnknownHostError

type UnknownHostError struct {
	Host        string // host:port as dialed
	Key         ssh.PublicKey
	Fingerprint string // SHA256:...
}

UnknownHostError reports a host whose key is not in known_hosts yet. The UI shows its fingerprint and, when the user trusts it, calls KnownHosts.Add and connects again.

func (*UnknownHostError) Error

func (e *UnknownHostError) Error() string

type Vol

type Vol struct {
	TotalKB, UsedKB uint64
	Mount           string
}

Vol is one filesystem, in kibibytes.

type VolUse

type VolUse struct {
	Mount           string
	TotalKB, UsedKB uint64
	Pct             float64
}

VolUse is one filesystem. Pct may be over 100 when used exceeds total.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL