sftpsvc

package
v0.0.13 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: AGPL-3.0 Imports: 34 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 sftpsvc is SSHYard's file transfer service over SFTP (github.com/pkg/sftp): it lists remote and local directories and uploads or downloads a single file at a time, reporting progress.

Index

Constants

View Source
const DefaultConcurrency = 3

DefaultConcurrency is how many transfers run at once unless set.

View Source
const DefaultReadLimit int64 = 10 << 20

DefaultReadLimit bounds editor-independent and AI reads.

View Source
const MaxRetries = 3

MaxRetries is how many times a failed transfer is tried again by itself.

View Source
const SumMax = 1 << 20

SumMax is the largest file whose Version has a Sum: saving one reads it again to compare.

Variables

View Source
var (
	// PlanMaxDepth is how many folders deep a plan goes.
	PlanMaxDepth = 64
	// PlanMaxEntries is how many files and folders a plan holds.
	PlanMaxEntries = 200_000
)

Limits on what a download plan walks, so that a server answering with endless folders (a loop, or a "../" entry) cannot hang it.

View Source
var (
	ErrPlanTooDeep  = errors.New("folders nested too deep")
	ErrPlanTooLarge = errors.New("too many files and folders")
	ErrPlanLoop     = errors.New("a folder contains itself")
)

Errors a download plan stops with.

View Source
var (
	ErrUnsafePath        = errors.New("sftp: symbolic link or unsafe path is not allowed")
	ErrUnsafeDestination = errors.New("sftp: destination folder is writable by other users")
	ErrPartChanged       = errors.New("sftp: partial file identity changed")
)
View Source
var ErrBadName = errors.New("sftp: a folder name must be one name, without slashes")

ErrBadName is a new folder's name that is empty or not a single name.

View Source
var ErrChanged = errors.New("sftp: the file changed on the server since it was opened")

ErrChanged is a remote file changed since it was read.

View Source
var ErrDstIsDir = errors.New("a folder is already there")

ErrDstIsDir is a transfer to where a folder is.

View Source
var ErrNotArchive = errors.New("sftpsvc: not an archive")

ErrNotArchive is an archive of a kind Extract does not know.

View Source
var ErrOperationsBusy = errors.New("sftp: too many pending operations")
View Source
var ErrReadLimit = errors.New("sftp: file exceeds read limit")
View Source
var ErrRestoreTaken = errors.New("sftp: a file with that name is there again")

ErrRestoreTaken: a file has the name of the one to restore again.

View Source
var ErrSaveUndone = fmt.Errorf("%w: another window put its old version back while it was saved", ErrChanged)

ErrSaveUndone: while a save without posix-rename was replacing a file, another window (cleaning up a cut save) put its old version back over the new one. It is an ErrChanged: the file on the server is not what was saved, and the user chooses, as for any change there.

View Source
var (

	// ErrSizeMismatch is a copy whose size differs from its source's.
	ErrSizeMismatch = errors.New("sftp: the copy's size differs from the source's")
)
View Source
var ErrUnsafeName = errors.New("not a safe local file name")

ErrUnsafeName is a name from the server that is not safe as a local file name.

Functions

func ArchiveBase

func ArchiveBase(name string) string

ArchiveBase is name without its archive extension, the folder an archive extracts into.

func CompressCommand

func CompressCommand(dir string, names []string, dst string, f ArchiveFormat) string

CompressCommand is the shell command that makes the archive dst, of format f, of the entries names of the remote folder dir, stored by their names. The names go after "./", so that none reads as an option.

func CompressLocal

func CompressLocal(ctx context.Context, dir string, names []string, dst string, f ArchiveFormat) (err error)

CompressLocal makes the archive dst, of format f, of the entries names of the local folder dir, stored by their names. Links are stored as links. A failed or canceled archive is removed.

func CreateLocalFile

func CreateLocalFile(dir, name string) (string, error)

CreateLocalFile makes an empty file named name in the local folder dir.

func Executable

func Executable(name string) bool

Executable says opening a file so named in its default app may run it, by its extension (in any case; trailing dots and spaces dropped as Windows does).

func ExtractCommand

func ExtractCommand(archive, dst string) (string, error)

ExtractCommand is the shell command that extracts the remote archive into the folder dst, which is there.

func ExtractLocal

func ExtractLocal(ctx context.Context, archive, dst string) error

ExtractLocal extracts the local archive into the folder dst, which is there. Every entry stays inside dst (an entry naming a place outside it fails the extraction); links and other special files are left out.

func HasKey

func HasKey(data []byte, pub ssh.PublicKey) bool

HasKey reports whether authorized_keys data lists pub, with whatever options and comment; lines that do not parse are skipped.

func IsArchive

func IsArchive(name string, remote bool) bool

IsArchive reports whether name is an archive Extract opens: on the server (remote), or on this computer, which does not read xz.

func IsText

func IsText(data []byte) bool

IsText says whether data looks like text to edit: UTF-8 without NULs in its first 8 KB.

func LocalDirSize

func LocalDirSize(ctx context.Context, p string) (size int64, files int, err error)

LocalDirSize is how much the files under the local folder p hold, and how many there are. Links are not followed.

func LocalExists

func LocalExists(p string) bool

LocalExists says whether something is at the local path.

func LocalGroup added in v0.0.8

func LocalGroup(gid uint32) string

LocalGroup is the name of the local group gid, its number when it has none.

func LocalMode

func LocalMode(m fs.FileMode) fs.FileMode

LocalMode is the mode a downloaded file gets for the server's mode m: read and write for the user, read for group and others where the server gives it (0644 or 0600 style). Execute bits are dropped: a file from a server is not made a program here, and neither are group or other write and set-id bits kept.

func LocalPath

func LocalPath(dir, rel string) (string, error)

LocalPath joins rel, slash-separated names from the server, below the local folder dir: each name must pass SafeName and the result must stay inside dir.

func LocalUser added in v0.0.8

func LocalUser(uid uint32) string

LocalUser is the name of the local user uid, its number when it has none.

func MkdirAllLocal

func MkdirAllLocal(p string) error

MkdirAllLocal creates download-plan directories with the same confinement as the files that will later populate them.

func MkdirLocal

func MkdirLocal(dir, name string) (string, error)

MkdirLocal makes a folder named name in the local directory dir.

func ParseMode

func ParseMode(s string) (fs.FileMode, error)

ParseMode reads permission bits written in octal, as "644" or "0755".

func PartName

func PartName(dst string, remote bool) string

PartName is the prefix for a transfer's random, exclusively created partial file.

func RemoteJoin

func RemoteJoin(elem ...string) string

RemoteJoin joins remote path elements.

func RemoteParent

func RemoteParent(dir string) string

RemoteParent is the parent of a remote directory.

func RemoveLocal

func RemoveLocal(p string) error

RemoveLocal deletes the local path, a folder with what is in it.

func RenameLocal

func RenameLocal(p, name string) (string, error)

RenameLocal renames the local path within its folder to name.

func SafeName

func SafeName(name string) error

SafeName checks a name the server sent before it becomes a local file name, the same way on every OS (a listing made safe on one OS stays safe on another): it must be a single name, not "." or "..", without "/", "\", ":", NUL or other control characters, without a trailing dot or space (Windows drops them), and not a Windows device name (CON, PRN, AUX, NUL, COM1-9, LPT1-9, with or without an extension, in any case).

func ShellQuote

func ShellQuote(s string) string

ShellQuote quotes s as one word of a POSIX shell.

func UniqueName

func UniqueName(p string, remote bool, taken func(string) bool) string

UniqueName returns p, or "name (2).ext" and so on, the first that taken does not report as taken.

func Within

func Within(dir, p string) bool

Within says the local path p is dir or inside it.

Types

type ArchiveFormat

type ArchiveFormat int

ArchiveFormat is the kind of archive Compress makes.

const (
	Zip ArchiveFormat = iota
	TarGz
)

func (ArchiveFormat) Ext

func (f ArchiveFormat) Ext() string

Ext is the file name extension of an archive of the format.

type Client

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

Client is an SFTP session on an SSH connection.

func New

func New(conn *ssh.Client) (*Client, error)

New opens SFTP on an SSH connection; closing the Client does not close the connection.

func NewContext

func NewContext(ctx context.Context, conn *ssh.Client) (*Client, error)

NewContext negotiates only a dedicated channel and shares a pending-channel quota with every SFTP client on the same pooled SSH connection.

func (*Client) Chmod

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

Chmod sets the remote path's permission bits.

func (*Client) Close

func (c *Client) Close() error

Close ends the SFTP session.

func (*Client) CreateFile

func (c *Client) CreateFile(dir, name string) (string, error)

CreateFile makes an empty file named name in the remote folder dir.

func (*Client) DirSize

func (c *Client) DirSize(ctx context.Context, p string) (size int64, files int, err error)

DirSize is how much the files under the remote folder p hold, and how many there are. Links are not followed.

func (*Client) Discard

func (c *Client) Discard(dir string, u Unfinished) error

Discard removes the old version of an unfinished save.

func (*Client) Download

func (c *Client) Download(ctx context.Context, remote, localDir string, progress Progress) (string, error)

Download copies the remote file to localDir, under its own name, and returns the local path. It writes a temporary file and renames it, so a failed download leaves nothing behind.

func (*Client) Exists

func (c *Client) Exists(p string) bool

Exists says whether something is at the remote path.

func (*Client) Home

func (c *Client) Home() (string, error)

Home is the directory the server starts in.

func (*Client) InstallKey

func (c *Client) InstallKey(pub ssh.PublicKey, line string) (added bool, err error)

InstallKey appends line, the authorized_keys line of pub, to ~/.ssh/authorized_keys of the login, unless pub is there already (added is then false). What it creates it makes private, the directory 0700 and the file 0600, as ssh-copy-id does, and the name never has any other mode (see mkdirPrivate); the modes of what is there it leaves alone, so that a setup the server refuses stays visible (see the check that follows an install).

func (*Client) List

func (c *Client) List(dir string) ([]Entry, error)

List lists a remote directory, directories first.

func (*Client) ListContext

func (c *Client) ListContext(ctx context.Context, dir string) ([]Entry, error)

ListContext interrupts a stalled listing on its own SFTP channel.

func (*Client) ListUnfinished

func (c *Client) ListUnfinished(dir string) ([]Entry, []Unfinished, error)

ListUnfinished lists a remote directory, directories first, and the files there whose last save did not finish (to Restore or Discard).

func (*Client) Mkdir

func (c *Client) Mkdir(dir, name string) (string, error)

Mkdir makes a folder named name in the remote directory dir.

func (*Client) MkdirAll

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

MkdirAll makes the remote folder and its parents.

func (*Client) Names added in v0.0.8

func (c *Client) Names() (users, groups map[uint32]string)

Names are the server's user and group names, by ID, from its /etc/passwd and /etc/group: empty when it has none to read (an ID is then shown as a number). The names are the server's: show them as untrusted text.

func (*Client) PlanDownload

func (c *Client) PlanDownload(ctx context.Context, srcs []string, localDir string) ([]Item, []Skip, error)

PlanDownload lists what downloading the remote paths into localDir copies: folders recursively, folders before what is in them. What it cannot copy safely it leaves out and returns as skips, and the rest still downloads: a name that does not pass SafeName, a link to a folder inside a folder, a link to nothing. A path chosen that is itself a link to a folder is followed (the server resolves it; the loop check and the limits below apply as to any folder). Names no file can have ("", ".", "..", or with "/" or NUL: a server's trick) are dropped, as List hides them. Where each item goes stays in localDir.

It stops with an error at PlanMaxDepth, at PlanMaxEntries (items, skips and listed entries not yet planned, all counted), and at a folder met again (by its real path). Folders are listed a reply at a time on a second SFTP session (dirPager), so a folder of a million names stops at the limit, holding no more than it; only when the server refuses that session, or it breaks (a protocol error, from the folder it broke in on), is each folder read whole first.

func (*Client) PlanUpload

func (c *Client) PlanUpload(ctx context.Context, srcs []string, remoteDir string) ([]Item, error)

PlanUpload lists what uploading the local paths into remoteDir copies: folders recursively, folders before what is in them.

func (*Client) ReadFile

func (c *Client) ReadFile(p string) ([]byte, Version, error)

ReadFile reads at most DefaultReadLimit bytes.

func (*Client) ReadFileContext

func (c *Client) ReadFileContext(ctx context.Context, p string, limit int64) ([]byte, Version, error)

ReadFileContext uses a dedicated SFTP session, so cancellation interrupts stalled server requests without closing other files or the SSH connection.

func (*Client) ReadFileNoLinksContext

func (c *Client) ReadFileNoLinksContext(ctx context.Context, p string, limit int64) ([]byte, Version, error)

ReadFileNoLinksContext repeats the path check on the operation session immediately before opening, rather than trusting an earlier policy check.

func (*Client) Remove

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

Remove deletes the remote path, a folder with what is in it.

func (*Client) Rename

func (c *Client) Rename(p, name string) (string, error)

Rename renames the remote path within its folder to name.

func (*Client) ResolvePath

func (c *Client) ResolvePath(ctx context.Context, p string) (string, error)

ResolvePath rejects symlinks in every existing component. SFTP v3 has no openat/no-follow operation: this is a conservative check, not an atomic guarantee against a server changing its namespace concurrently.

func (*Client) Restore

func (c *Client) Restore(dir string, u Unfinished) error

Restore puts the old version of an unfinished save back under its name, unless a file has that name again (ErrRestoreTaken): looked up right before, then with posix-rename where the server has it, else in ways that never replace a file (a hard link, or a copy created only if the name is free) rather than plain rename, which replaces on some servers.

func (*Client) SCP added in v0.0.9

func (c *Client) SCP() bool

SCP reports a server without SFTP, whose files move with scp.

func (*Client) Stat

func (c *Client) Stat(p string) (Entry, error)

Stat describes the remote path, following links.

func (*Client) Upload

func (c *Client) Upload(ctx context.Context, local, remoteDir string, progress Progress) (string, error)

Upload copies the local file to remoteDir, under its own name, and returns the remote path. A failed upload leaves no partial file.

func (*Client) Version

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

Version is the remote file's version now.

func (*Client) WriteFile

func (c *Client) WriteFile(p string, data []byte, was Version) (Version, error)

WriteFile replaces the remote file with data, unless it is no longer the version was (ErrChanged); a zero was writes regardless. It returns the new version. With a Sum in was, the file is read again and compared, as its size and time may not show an edit.

The file is replaced atomically: data goes to a hidden sibling (".sshyard-…-name", mode 0600 while written), which gets the file's mode (and its owner and group, when they differ and the server lets it) and is renamed over it with posix-rename@openssh.com; a reader sees the old file or the new one, and a failed or cut save leaves the old one. Without that extension, the file is moved aside, the copy put in its place, and the old one removed (or put back if that fails). A link is written through (its target replaced). The file is written in place as before, truncated, only when a copy cannot replace it as it is: the folder is not writable, or its owner or group cannot be kept. A file the user may not write is not replaced either (the permission error). A replaced file is a new inode: hard links to the old one keep it.

func (c *Client) WriteFileNoLinks(p string, data []byte, was Version) (Version, error)

WriteFileNoLinks does not adopt a link that appeared after authorization.

func (*Client) WriteFileNoLinksContext

func (c *Client) WriteFileNoLinksContext(ctx context.Context, p string, data []byte, was Version) (Version, error)

WriteFileNoLinksContext keeps validation and atomic replacement on a dedicated cancellable session. Cancellation cannot undo a rename already completed.

type Direction

type Direction int

Direction is which way a transfer goes.

const (
	Upload Direction = iota
	Download
)

type Entry

type Entry struct {
	Name    string
	Size    int64
	Mode    fs.FileMode
	ModTime time.Time
	IsDir   bool
	// UID and GID are the owner and the group, when IDs says they are
	// known (not on Windows).
	UID, GID uint32
	IDs      bool
}

Entry is a file or directory of a listing.

func ListLocal

func ListLocal(dir string) ([]Entry, error)

ListLocal lists a local directory, directories first.

type Item

type Item struct {
	Src, Dst string
	// Rel is the path below the folder the user chose, with slashes.
	Rel   string
	Size  int64
	IsDir bool
	// Exists says a file is already at Dst (folders merge).
	Exists bool
}

Item is a file or folder a transfer plan copies, with where it goes.

type Progress

type Progress func(done, total int64)

Progress reports bytes done of total.

type Skip

type Skip struct {
	// Src is the remote path, Rel the path below the folder chosen.
	Src, Rel string
	Reason   SkipReason
}

Skip is something a download plan leaves out, and why.

type SkipReason

type SkipReason int

SkipReason is why a download plan leaves something out.

const (
	// SkipName is a name the server allows that is not safe as a local
	// file name (SafeName): "aux.c", "10:30.log", "x.".
	SkipName SkipReason = iota
	// SkipLinkedFolder is a link to a folder inside a folder being
	// downloaded: links are followed only for what was chosen.
	SkipLinkedFolder
	// SkipBrokenLink is a link whose target cannot be read.
	SkipBrokenLink
)

type Transfer

type Transfer struct {
	ID    int
	Name  string // what the list shows, as a path under the folder dropped
	Dir   Direction
	Src   string
	Dst   string
	Bytes int64
	Total int64
	State TransferState
	Err   error
	// Destination is the path written, once Done.
	Destination string
	// Attempt is how many times it failed and was tried again by itself.
	Attempt int
	// Offset is where the last start resumed from, 0 from the beginning.
	Offset int64
	// Speed is the recent rate in bytes per second while it runs.
	Speed float64
	// contains filtered or unexported fields
}

Transfer is one file being copied, from Src to Dst (both full paths).

func (Transfer) Active

func (t Transfer) Active() bool

Active is a transfer that has not ended.

func (Transfer) ETA

func (t Transfer) ETA() time.Duration

ETA is the time left at the current speed, 0 when unknown.

func (Transfer) Percent

func (t Transfer) Percent() int

Percent is how far the transfer is, 0 to 100.

type TransferState

type TransferState int

TransferState is where a transfer is.

const (
	// Queued waits for a free slot (or for its retry).
	Queued TransferState = iota
	Running
	// Paused keeps what was copied; Resume goes on from there.
	Paused
	Done
	Failed
	// Canceled removed what was copied.
	Canceled
)

type Transfers

type Transfers struct {
	// OnChange is called from any goroutine when a transfer changes.
	OnChange func()
	// Client returns the SFTP client to use, waiting until there is one
	// (the connection may be down), or ctx's error.
	Client func(ctx context.Context) (*Client, error)
	// Logf logs resumes and retries; log.Printf when nil.
	Logf func(format string, args ...any)
	// Backoff is the wait before retry n (1-based); 1s, 2s, 4s when nil.
	Backoff func(n int) time.Duration
	// contains filtered or unexported fields
}

Transfers is a queue of file transfers: a few run at once (Concurrency), the others wait; each can be paused, resumed, retried and canceled. A transfer writes a part file next to its destination (".name.sshyard-part") and renames it when complete, so that a paused or failed one resumes from the part's size, and a canceled one leaves nothing behind.

func (*Transfers) Add

func (ts *Transfers) Add(dir Direction, src, dst, name string) int

Add queues copying src to dst (full paths: local to remote for an Upload, remote to local for a Download). name is what the list shows.

func (*Transfers) Cancel

func (ts *Transfers) Cancel(id int)

Cancel stops a transfer that has not ended and removes its part file.

func (*Transfers) CancelAll

func (ts *Transfers) CancelAll()

CancelAll cancels every transfer that has not ended.

func (*Transfers) ClearFinished

func (ts *Transfers) ClearFinished()

ClearFinished drops the transfers that ended (a canceled one whose part file is still being removed stays until it is).

func (*Transfers) Concurrency

func (ts *Transfers) Concurrency() int

Concurrency is how many transfers run at once.

func (*Transfers) List

func (ts *Transfers) List() []Transfer

List returns copies of the transfers, in the order they were added.

func (*Transfers) Pause

func (ts *Transfers) Pause(id int)

Pause stops a queued or running transfer, keeping what it copied.

func (*Transfers) PauseAll

func (ts *Transfers) PauseAll()

PauseAll pauses every queued and running transfer.

func (*Transfers) Resume

func (ts *Transfers) Resume(id int)

Resume queues a paused transfer again; it goes on from where it was.

func (*Transfers) ResumeAll

func (ts *Transfers) ResumeAll()

ResumeAll resumes every paused transfer.

func (*Transfers) Retry

func (ts *Transfers) Retry(id int)

Retry queues a failed or canceled transfer again, with its retries counted afresh; a failed one resumes from its part file.

func (*Transfers) SetConcurrency

func (ts *Transfers) SetConcurrency(n int)

SetConcurrency sets how many transfers run at once (1 or more). Those running go on; more start when there is room.

func (*Transfers) Wait

func (ts *Transfers) Wait()

Wait blocks until no transfer is queued or running and no canceled one's part file is still being removed, for tests.

type Unfinished

type Unfinished struct {
	Name, Backup string
}

Unfinished is a file whose last save did not finish: it is missing, and its old version is at Backup, both names in the same folder.

type Version

type Version struct {
	Size    int64
	ModTime time.Time
	// Sum is the SHA-256 of the content read or written, for a file of
	// at most SumMax bytes (zero for a larger one, and from Version): an
	// edit that keeps the size and the time (within a second, on
	// servers that keep only seconds) still changes it.
	Sum [sha256.Size]byte
}

Version is what a remote file was when read: an edit is saved over it only if it is still that.

func ReadLocalFile added in v0.0.8

func ReadLocalFile(p string, limit int64) ([]byte, Version, error)

ReadLocalFile reads the local file p, of at most limit bytes (ErrReadLimit), and its version, as ReadFileContext does a remote one.

func WriteLocalFile added in v0.0.8

func WriteLocalFile(p string, data []byte, was Version) (Version, error)

WriteLocalFile replaces the local file p (the file a link names) with data, unless it is no longer the version was (ErrChanged); a zero was writes regardless. The new content goes to a hidden sibling first, renamed over the file with its mode, so that a failed save leaves the file as it was; where that cannot be (the folder is not writable), the file is written in place.

Jump to

Keyboard shortcuts

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