session

package
v0.0.20 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: AGPL-3.0 Imports: 35 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, private key or the SSH agent, 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 MaxOfferedKeys = 5

MaxOfferedKeys bounds the keys one login offers, the agent's and this computer's together: sshd's MaxAuthTries is 6 by default, and every key refused counts.

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 (
	ErrNoTmux      = errors.New("session: tmux is not installed")
	ErrTmuxUnknown = errors.New("session: the shell's state could not be read")
)

ErrNoTmux is a server without the tmux command; ErrTmuxUnknown is TmuxShellIdle not finding out whether the shell waits at its prompt.

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 ErrCertificate = errors.New("session: the certificate does not fit the private key")

ErrCertificate reports a certificate that cannot be read or is not for the private key.

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 ErrKnownHostsChanged = errors.New("session: known_hosts changed meanwhile")

ErrKnownHostsChanged reports that known_hosts changed while a key was being removed from it; nothing was written.

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 ErrNoBreak = errors.New("session: this connection cannot send a break")

ErrNoBreak is Break on a session whose connection cannot send one.

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 KeyID added in v0.0.12

func KeyID(pub ssh.PublicKey) string

KeyID identifies a public key: the hex SHA-256 of its wire form, the digest its SHA256 fingerprint shows.

func MetricsCommand

func MetricsCommand(interval int, mount string) string

MetricsCommand starts sh reading the script from stdin, with the interval and mount as arguments. Keeping the script out of exec requests avoids Dropbear's command-string limit. Both arguments are re-checked here.

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).

func TmuxAttachCommand added in v0.0.17

func TmuxAttachCommand(id string) string

TmuxAttachCommand is the command a shell is given to attach to the session id, "" for an ID that is not one. The ID is quoted, which any shell reads alike.

func TmuxDetach added in v0.0.17

func TmuxDetach(ctx context.Context, client *ssh.Client, tty string) error

TmuxDetach detaches the client tty from its session, which goes on.

func TmuxKill added in v0.0.17

func TmuxKill(ctx context.Context, client *ssh.Client, id string) error

TmuxKill ends the session id and what runs in it.

func TmuxNameOK added in v0.0.17

func TmuxNameOK(name string) bool

TmuxNameOK reports whether a session may be given name: 1 to 64 characters, no control character, and neither a colon nor a period, which tmux would change to an underscore, nor a leading hyphen or space, which it would read as an option or keep unseen.

func TmuxNew added in v0.0.17

func TmuxNew(ctx context.Context, client *ssh.Client, name, dir string) (string, error)

TmuxNew starts a detached session named name in dir ("" the home folder) and returns its ID.

func TmuxNewOrAttachCommand added in v0.0.17

func TmuxNewOrAttachCommand(name string) string

TmuxNewOrAttachCommand is the command a shell is given to attach to the session named name, created first when there is none, "" for a name that may not be one. tmux takes the name as it is, not as a prefix.

func TmuxRename added in v0.0.17

func TmuxRename(ctx context.Context, client *ssh.Client, id, name string) error

TmuxRename names the session id name.

func TmuxSelectWindow added in v0.0.17

func TmuxSelectWindow(ctx context.Context, client *ssh.Client, id string, window int) error

TmuxSelectWindow makes window the current window of the session id; -1 leaves it.

func TmuxShellIdle added in v0.0.17

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

TmuxShellIdle reports whether the shell tagged tag waits at its prompt, where a command typed into its terminal runs; ErrTmuxUnknown when the server cannot tell (no tag, no /proc).

func TmuxSwitch added in v0.0.17

func TmuxSwitch(ctx context.Context, client *ssh.Client, tty, id string, window int) error

TmuxSwitch shows the session id on the client tty, which stays attached; window, from 0, selects one of its windows first, -1 none.

Types

type Breaker added in v0.0.14

type Breaker interface {
	Break(d time.Duration) error
}

Breaker is a Stream that can send a break: a serial port, or Telnet's BRK.

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
	// Certificate, when set, is an OpenSSH user certificate of
	// PrivateKey (a key-cert.pub line), offered before the bare key.
	Certificate []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
	// TryAgent offers the agent's keys when an agent runs; unlike Agent,
	// no agent or an empty one is no error.
	TryAgent bool
	// LocalKeys are this computer's key files, offered with the agent's
	// keys (see offerKeys).
	LocalKeys []LocalKey
	// IdentitiesOnly offers only the keys the config names, as ssh's
	// option of that name; with none named, the files alone.
	IdentitiesOnly bool
	// Prefer is the KeyID offered first: the one that logged in last.
	Prefer string
	// Skip are the KeyIDs never offered.
	Skip []string
	// OnKey hears the KeyID of the TryAgent or local key that logged in.
	OnKey func(id 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
	// Old are the keys known_hosts has for the host.
	Old []ssh.PublicKey
}

HostKeyChangedError reports a host whose key does not match the one in known_hosts: possibly an attack, so SSHYard refuses to connect. Only the user, having compared the fingerprints, replaces the key (Replace).

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 KeysRefusedError added in v0.0.12

type KeysRefusedError struct {
	Offered int
	Err     error
}

KeysRefusedError is a login that offered Offered keys and no password, all of them refused.

func (*KeysRefusedError) Error added in v0.0.12

func (e *KeysRefusedError) Error() string

func (*KeysRefusedError) Unwrap added in v0.0.12

func (e *KeysRefusedError) Unwrap() error

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
	// KindCertificate: the certificate does not fit the private key.
	KindCertificate
	// 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
	// KindLocalKey: a key file of this computer the server accepts needs
	// its passphrase (LocalKeyError).
	KindLocalKey
	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) For added in v0.0.18

func (k *KnownHosts) For(host string) []KnownKey

For is the keys trusted for host (host:port as dialed).

func (*KnownHosts) Forget added in v0.0.18

func (k *KnownHosts) Forget(host string) error

Forget removes the keys the file has for host (host:port as dialed), so the next connection asks to trust its key again.

func (*KnownHosts) List added in v0.0.18

func (k *KnownHosts) List() []KnownKey

List is the keys of the file, in its order.

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.

func (*KnownHosts) Remove added in v0.0.18

func (k *KnownHosts) Remove(key KnownKey) error

Remove removes the line of key, one of List; ErrKnownHostsChanged when that line no longer has it.

func (*KnownHosts) Replace added in v0.0.18

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

Replace trusts key for host (host:port as dialed) in place of the keys the file has for it.

type KnownKey added in v0.0.18

type KnownKey struct {
	Hosts       []string
	Key         ssh.PublicKey
	Fingerprint string
	Line        int
}

KnownKey is a key of the file: the hosts its line names, as written (hashed names stay hashed), and the line.

func (KnownKey) Hashed added in v0.0.18

func (k KnownKey) Hashed() bool

Hashed reports whether the line names its hosts by their hashes only.

type LocalKey added in v0.0.12

type LocalKey struct {
	Path string
	// Public is the key's public half, known without its passphrase.
	Public ssh.PublicKey
	// PEM is the file; nil when only the agent holds the private half
	// (an IdentityFile naming a public key).
	PEM []byte
	// Encrypted keys need Passphrase to sign.
	Encrypted  bool
	Passphrase []byte
	// Explicit keys are named for the host by ~/.ssh/config.
	Explicit bool
}

LocalKey is a private key file of this computer, offered by a host that asks for its password only when no key logs in.

type LocalKeyError added in v0.0.12

type LocalKeyError struct {
	Path   string
	ID     string
	Public ssh.PublicKey
	Wrong  bool
}

LocalKeyError is a key file of this computer the server accepts that cannot sign: it has no passphrase, or Wrong, the one given does not open it. The login stops there, so that the passphrase can be asked.

func (*LocalKeyError) Error added in v0.0.12

func (e *LocalKeyError) Error() string

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 Opener added in v0.0.14

type Opener = func(ctx context.Context, cols, rows int, term string) (Stream, error)

Opener opens a session's stream, for Options.Open.

func Serial added in v0.0.14

func Serial(c serial.Config) Opener

Serial opens the serial port of c.

func Telnet added in v0.0.14

func Telnet(cfg Config) Opener

Telnet opens a Telnet connection to cfg.Addr, dialed with cfg.Dial, through cfg.Proxy when set, within cfg.Timeout.

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
	// Shell is the shell a local session runs; zero is the first of
	// Shells.
	Shell Shell
	// Open, when set, opens the terminal's stream instead of an SSH
	// shell: a Telnet connection or a serial port. The session has no
	// Client; it ends, Exited, when the other end closes the stream, and
	// is reconnected when the stream is lost.
	Open func(ctx context.Context, cols, rows int, term string) (Stream, error)
	// Login answers an opened stream's login and password prompts with
	// the Config's User and Credentials, read before it is opened.
	Login bool
	// NewLine is what Enter sends on an opened stream; "" is "\r".
	NewLine string
	// LocalEcho shows what is typed on an opened stream, for a device
	// that does not echo it.
	LocalEcho bool
	// Dir is the folder an SSH shell goes to each time it starts: a cd
	// typed once the shell has gone quiet (enterShell). "~" or "~/…" is
	// under the home folder.
	Dir string
	// Start, when set, is asked each time an SSH shell starts for a
	// command to type after the cd to Dir, as an attach to a tmux
	// session; "" types none. It may take its time, and run commands on
	// client.
	Start func(ctx context.Context, client *ssh.Client) string
}

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 Prober added in v0.0.14

type Prober interface {
	Probe(ctx context.Context) (time.Duration, error)
}

Prober is a Stream that can measure its round trip, which keeps it alive: a Telnet connection's TIMING-MARK.

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) Break added in v0.0.14

func (s *Session) Break() error

Break sends a break, on a serial port or a Telnet connection.

func (*Session) CanBreak added in v0.0.14

func (s *Session) CanBreak() bool

CanBreak reports whether Break can send one now.

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) Send added in v0.0.12

func (s *Session) Send(p []byte) error

Send writes p to the shell without waiting for it: after the input still being written, in order. Typed input goes this way, so a stalled connection never holds up the UI thread.

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 Shell added in v0.0.11

type Shell struct {
	// ID names the shell across runs: "pwsh" or "wsl:Ubuntu" on Windows,
	// its path elsewhere.
	ID string
	// Name is how the shell is shown.
	Name string
	// Path is the program, Args what follows it.
	Path string
	Args []string
	// Env are entries set over the app's environment.
	Env []string
}

Shell is a shell this computer runs in local sessions.

func Shells added in v0.0.11

func Shells() []Shell

Shells are the shells of this computer, the default first; there is always one.

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 Stream added in v0.0.14

type Stream interface {
	io.ReadWriteCloser
	// Resize tells the other end the terminal's size, where it has one.
	Resize(cols, rows int) error
}

Stream is a terminal that is no SSH shell: the byte stream of a Telnet connection or a serial port (Options.Open), or a local shell's pseudo-terminal. Output is read from it and input written to it.

type TmuxClient added in v0.0.17

type TmuxClient struct {
	TTY     string
	Session string
	Mine    bool
}

TmuxClient is a terminal attached to a session: Mine is set for the terminal the list was read for.

type TmuxInfo added in v0.0.17

type TmuxInfo struct {
	Version  string
	Tells    bool
	Sessions []TmuxSession
	Clients  []TmuxClient
}

TmuxInfo is what TmuxList read. Tells is set when the server tells the asking terminal's client from the others: without it none is Mine.

func ParseTmuxList added in v0.0.17

func ParseTmuxList(out []byte) TmuxInfo

ParseTmuxList reads the output of the list script. Lines it does not understand are skipped.

func TmuxList added in v0.0.17

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

TmuxList reads the server's tmux sessions, for the terminal tagged tag ("" for none).

func (TmuxInfo) Mine added in v0.0.17

func (t TmuxInfo) Mine() (TmuxClient, bool)

Mine is the client of the terminal the list was read for.

func (TmuxInfo) Session added in v0.0.17

func (t TmuxInfo) Session(id string) (TmuxSession, bool)

Session is the session id.

type TmuxSession added in v0.0.17

type TmuxSession struct {
	ID       string
	Name     string
	Windows  int
	Attached int
	Created  time.Time
	Activity time.Time
	Path     string
	Wins     []TmuxWindow
}

TmuxSession is a tmux session: Attached counts its clients, Path is the folder its new windows start in.

type TmuxWindow added in v0.0.17

type TmuxWindow struct {
	Index  int
	Name   string
	Active bool
	Panes  int
}

TmuxWindow is a window of a tmux session.

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