sftp

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Jun 5, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AppendKnownHost

func AppendKnownHost(challenge *UnknownHostKeyError) error

AppendKnownHost adds the previously-presented host key to ~/.ssh/known_hosts. Call after the user confirms an UnknownHostKeyError.

func ListSSHHosts

func ListSSHHosts() []string

LookupSSHConfig parses ~/.ssh/config and returns the directives that apply to the given alias. The Config-level Get walks Host blocks (including wildcard patterns) and resolves Include directives, but does NOT substitute OpenSSH built-in defaults — so an empty field means "not set in the user's config", which is what the UI uses to decide whether to fill a form field. ListSSHHosts returns concrete Host aliases declared in ~/.ssh/config. Wildcards and the catch-all "*" pattern are skipped because they aren't useful as connection targets on their own.

Types

type BatchItem

type BatchItem struct {
	RemotePath string
	LocalPath  string
	IsDir      bool
}

BatchItem describes a single download target: file or directory tree.

type BatchOptions

type BatchOptions struct {
	Parallel    int
	OnOverwrite OverwriteCallback
	Verify      bool
}

BatchOptions tunes DownloadBatch/UploadBatch. Parallel <= 0 falls back to 4; values above 32 are capped because each worker holds its own SFTP pipeline and the server typically refuses past that. OnOverwrite is invoked from a worker goroutine when the destination file already exists and must be safe to call concurrently. Verify enables a post-transfer SHA256 check: local sum vs `sha256sum` executed on the server over an ssh.Session. Mismatches are reported via onFailure.

type ChangedHostKeyError

type ChangedHostKeyError struct {
	Hostname    string
	Address     string
	KeyType     string
	Fingerprint string
	// contains filtered or unexported fields
}

ChangedHostKeyError is returned when the server's host key differs from the one stored in known_hosts — possible MITM. Never auto-accepted.

func (*ChangedHostKeyError) Error

func (e *ChangedHostKeyError) Error() string

type Client

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

func Connect

func Connect(host, port, user, password, keyPath, keyPassphrase string) (*Client, error)

func ConnectWithProxy

func ConnectWithProxy(host, port, user, password, keyPath, keyPassphrase, proxyJump string) (*Client, error)

ConnectWithProxy is like Connect but routes the SSH session through the given ProxyJump alias from ~/.ssh/config (single hop). Empty proxyJump is equivalent to Connect. The jump host authenticates via ssh-agent and/or the IdentityFile declared in its own ssh_config block — passwords are not prompted for the jump.

func (*Client) AcquireSession

func (c *Client) AcquireSession() (*sftp.Client, func(), error)

AcquireSession returns a worker-private sftp.Client (own SSH channel, independent flow-control window) from the pool, or creates a new one if the pool is empty. The returned release fn returns the session to the pool, or closes it if the pool is already full. Workers must always call release when done; on error the session is closed instead of pooled.

func (*Client) Chmod

func (c *Client) Chmod(p string, mode os.FileMode) error

func (*Client) Close

func (c *Client) Close()

func (*Client) CopyRemote

func (c *Client) CopyRemote(src, dst string) error

CopyRemote duplicates src to dst on the server via an `cp -R` exec session. SFTP itself has no copy primitive so bytes would otherwise have to travel through the client. Requires a POSIX-ish remote with `cp` in PATH.

func (*Client) DownloadBatch

func (c *Client) DownloadBatch(items []BatchItem, opts BatchOptions, progress func(DownloadProgress), onFailure FailureCallback) error

DownloadBatch downloads many files (and/or directory trees) in parallel. Files inside a single directory get flattened and shared across the worker pool, so a folder of many small files no longer pays RTT serially. For a single large file, performance equals DownloadFile (which already uses concurrent reads internally).

Progress is aggregated: the callback receives DownloadProgress whose Written/Total are sums across the whole batch and File is one of the currently in-flight items (for display). Final emit has File="".

onFailure receives per-file errors. The UI-side callback typically prompts the user and returns Skip or Abort. Abort is sticky: once any worker hears Abort, no further tasks are dispatched and in-flight tasks finish their current file before exiting.

func (*Client) DownloadDir

func (c *Client) DownloadDir(remotePath, localPath string, progress func(DownloadProgress), onFailure FailureCallback) error

func (*Client) DownloadFile

func (c *Client) DownloadFile(remotePath, localPath string, progress func(DownloadProgress)) error

func (*Client) HomeDir

func (c *Client) HomeDir() string

func (*Client) List

func (c *Client) List(remotePath string) ([]FileEntry, error)

func (*Client) Mkdir

func (c *Client) Mkdir(p string) error

func (*Client) ReadFileChunk

func (c *Client) ReadFileChunk(remotePath string, maxBytes int64) (data []byte, truncated bool, err error)

ReadFileChunk reads up to maxBytes from remotePath. truncated is true when the file is larger than maxBytes. Used for in-app preview.

func (*Client) ReadFileRange

func (c *Client) ReadFileRange(remotePath string, offset, maxBytes int64) (data []byte, total int64, err error)

ReadFileRange reads up to maxBytes from remotePath starting at offset and returns the total file size so the caller can detect EOF. Used by preview paging to fetch further chunks on demand.

func (c *Client) Readlink(p string) (string, error)

Readlink returns the literal target of a symlink (relative or absolute, as stored on the server). Used for "→ target" display next to symlinks.

func (*Client) Remove

func (c *Client) Remove(p string) error

Remove deletes a file. For directories use RemoveAll.

func (*Client) RemoveAll

func (c *Client) RemoveAll(p string) error

RemoveAll deletes p recursively. Safe on both files and directories.

func (*Client) Rename

func (c *Client) Rename(oldPath, newPath string) error

func (*Client) SHA256Remote

func (c *Client) SHA256Remote(remotePath string) (string, error)

SHA256Remote runs `sha256sum -- path` over a fresh ssh session and parses the first hex token. Requires `sha256sum` in the server's PATH.

func (*Client) Stat

func (c *Client) Stat(path string) (os.FileInfo, error)

func (*Client) UploadBatch

func (c *Client) UploadBatch(items []UploadItem, opts BatchOptions, progress func(UploadProgress), onFailure FailureCallback) error

UploadBatch uploads many files (and/or directory trees) in parallel using the same worker-pool pattern as DownloadBatch. The pre-scan phase walks local directories, builds a flat task list and aggregates byte totals, then `Parallel` workers (each with its own SFTP session) consume the queue.

func (*Client) UploadDir

func (c *Client) UploadDir(localRoot, remoteRoot string, progress func(UploadProgress), onFailure FailureCallback) error

func (*Client) UploadFile

func (c *Client) UploadFile(localPath, remotePath string, progress func(UploadProgress)) error

type DownloadProgress

type DownloadProgress struct {
	Written    int64
	Total      int64
	File       string
	ScanFile   string // non-empty during pre-scan phase
	FilesDone  int64  // completed files (download phase)
	FilesTotal int64  // total files — accurate after scan, zero during scan
}

type FailureCallback

type FailureCallback func(path string, err error) FailureDecision

FailureCallback is invoked when a file or sub-directory fails to download. Return DecisionSkip to continue with the next entry, DecisionAbort to stop.

type FailureDecision

type FailureDecision int
const (
	DecisionAbort FailureDecision = iota
	DecisionSkip
)

type FileEntry

type FileEntry struct {
	Name      string
	Path      string
	IsDir     bool
	IsSymlink bool
	Size      int64
	Mode      os.FileMode
	ModTime   time.Time
}

type OverwriteCallback

type OverwriteCallback func(path string, existingSize, newSize int64) OverwriteDecision

OverwriteCallback is invoked when a destination file already exists. existingSize/newSize help the UI show a meaningful prompt. The caller is expected to be sticky on "all"-variants on its own side.

type OverwriteDecision

type OverwriteDecision int
const (
	OverwriteAbort OverwriteDecision = iota
	OverwriteSkip
	OverwriteReplace
	// OverwriteResume — destination is a prefix of source; continue writing
	// from existingSize. Only meaningful when existingSize < newSize, the
	// callback is expected to enforce that.
	OverwriteResume
)

type PassphraseRequiredError

type PassphraseRequiredError struct {
	KeyPath       string
	BadPassphrase bool
}

PassphraseRequiredError signals that the private key at KeyPath is encrypted and the caller must supply a passphrase. BadPassphrase is set when a passphrase was attempted but didn't decrypt — the UI uses this to switch the prompt's error message between "enter passphrase" and "wrong passphrase, try again".

func (*PassphraseRequiredError) Error

func (e *PassphraseRequiredError) Error() string

type SSHConfigEntry

type SSHConfigEntry struct {
	HostName     string
	Port         string
	User         string
	IdentityFile string
	ProxyJump    string
}

func LookupSSHConfig

func LookupSSHConfig(alias string) SSHConfigEntry

type UnknownHostKeyError

type UnknownHostKeyError struct {
	Hostname    string
	Address     string
	KeyType     string
	Fingerprint string
	// contains filtered or unexported fields
}

UnknownHostKeyError is returned when the server's host key is not in known_hosts. The caller can show the fingerprint, ask the user, and on approval append it via AppendKnownHost.

func (*UnknownHostKeyError) Error

func (e *UnknownHostKeyError) Error() string

type UploadItem

type UploadItem struct {
	LocalPath  string
	RemotePath string
	IsDir      bool
}

UploadItem describes a single upload target.

type UploadProgress

type UploadProgress struct {
	Written    int64
	Total      int64
	File       string
	ScanFile   string
	FilesDone  int64
	FilesTotal int64
}

UploadProgress mirrors DownloadProgress but for the upload direction.

Jump to

Keyboard shortcuts

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