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
- Variables
- func ArchiveBase(name string) string
- func CompressCommand(dir string, names []string, dst string, f ArchiveFormat) string
- func CompressLocal(ctx context.Context, dir string, names []string, dst string, f ArchiveFormat) (err error)
- func CreateLocalFile(dir, name string) (string, error)
- func Executable(name string) bool
- func ExtractCommand(archive, dst string) (string, error)
- func ExtractLocal(ctx context.Context, archive, dst string) error
- func HasKey(data []byte, pub ssh.PublicKey) bool
- func IsArchive(name string, remote bool) bool
- func IsText(data []byte) bool
- func LocalDirSize(ctx context.Context, p string) (size int64, files int, err error)
- func LocalExists(p string) bool
- func LocalGroup(gid uint32) string
- func LocalMode(m fs.FileMode) fs.FileMode
- func LocalPath(dir, rel string) (string, error)
- func LocalUser(uid uint32) string
- func MkdirAllLocal(p string) error
- func MkdirLocal(dir, name string) (string, error)
- func ParseMode(s string) (fs.FileMode, error)
- func PartName(dst string, remote bool) string
- func RemoteJoin(elem ...string) string
- func RemoteParent(dir string) string
- func RemoveLocal(p string) error
- func RenameLocal(p, name string) (string, error)
- func SafeName(name string) error
- func ShellQuote(s string) string
- func UniqueName(p string, remote bool, taken func(string) bool) string
- func Within(dir, p string) bool
- type ArchiveFormat
- type Client
- func (c *Client) Chmod(p string, mode fs.FileMode) error
- func (c *Client) Close() error
- func (c *Client) CreateFile(dir, name string) (string, error)
- func (c *Client) DirSize(ctx context.Context, p string) (size int64, files int, err error)
- func (c *Client) Discard(dir string, u Unfinished) error
- func (c *Client) Download(ctx context.Context, remote, localDir string, progress Progress) (string, error)
- func (c *Client) Exists(p string) bool
- func (c *Client) Home() (string, error)
- func (c *Client) InstallKey(pub ssh.PublicKey, line string) (added bool, err error)
- func (c *Client) List(dir string) ([]Entry, error)
- func (c *Client) ListContext(ctx context.Context, dir string) ([]Entry, error)
- func (c *Client) ListUnfinished(dir string) ([]Entry, []Unfinished, error)
- func (c *Client) Mkdir(dir, name string) (string, error)
- func (c *Client) MkdirAll(p string) error
- func (c *Client) Names() (users, groups map[uint32]string)
- func (c *Client) PlanDownload(ctx context.Context, srcs []string, localDir string) ([]Item, []Skip, error)
- func (c *Client) PlanUpload(ctx context.Context, srcs []string, remoteDir string) ([]Item, error)
- func (c *Client) ReadFile(p string) ([]byte, Version, error)
- func (c *Client) ReadFileContext(ctx context.Context, p string, limit int64) ([]byte, Version, error)
- func (c *Client) ReadFileNoLinksContext(ctx context.Context, p string, limit int64) ([]byte, Version, error)
- func (c *Client) Remove(p string) error
- func (c *Client) Rename(p, name string) (string, error)
- func (c *Client) ResolvePath(ctx context.Context, p string) (string, error)
- func (c *Client) Restore(dir string, u Unfinished) error
- func (c *Client) SCP() bool
- func (c *Client) Stat(p string) (Entry, error)
- func (c *Client) Upload(ctx context.Context, local, remoteDir string, progress Progress) (string, error)
- func (c *Client) Version(p string) (Version, error)
- func (c *Client) WriteFile(p string, data []byte, was Version) (Version, error)
- func (c *Client) WriteFileNoLinks(p string, data []byte, was Version) (Version, error)
- func (c *Client) WriteFileNoLinksContext(ctx context.Context, p string, data []byte, was Version) (Version, error)
- type Direction
- type Entry
- type Item
- type Progress
- type Skip
- type SkipReason
- type Transfer
- type TransferState
- type Transfers
- func (ts *Transfers) Add(dir Direction, src, dst, name string) int
- func (ts *Transfers) Cancel(id int)
- func (ts *Transfers) CancelAll()
- func (ts *Transfers) ClearFinished()
- func (ts *Transfers) Concurrency() int
- func (ts *Transfers) List() []Transfer
- func (ts *Transfers) Pause(id int)
- func (ts *Transfers) PauseAll()
- func (ts *Transfers) Resume(id int)
- func (ts *Transfers) ResumeAll()
- func (ts *Transfers) Retry(id int)
- func (ts *Transfers) SetConcurrency(n int)
- func (ts *Transfers) Wait()
- type Unfinished
- type Version
Constants ¶
const DefaultConcurrency = 3
DefaultConcurrency is how many transfers run at once unless set.
const DefaultReadLimit int64 = 10 << 20
DefaultReadLimit bounds editor-independent and AI reads.
const MaxRetries = 3
MaxRetries is how many times a failed transfer is tried again by itself.
const SumMax = 1 << 20
SumMax is the largest file whose Version has a Sum: saving one reads it again to compare.
Variables ¶
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.
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.
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") )
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.
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.
var ErrDstIsDir = errors.New("a folder is already there")
ErrDstIsDir is a transfer to where a folder is.
var ErrNotArchive = errors.New("sftpsvc: not an archive")
ErrNotArchive is an archive of a kind Extract does not know.
var ErrOperationsBusy = errors.New("sftp: too many pending operations")
var ErrReadLimit = errors.New("sftp: file exceeds read limit")
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.
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.
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") )
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 ¶
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 ¶
CreateLocalFile makes an empty file named name in the local folder dir.
func Executable ¶
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 ¶
ExtractCommand is the shell command that extracts the remote archive into the folder dst, which is there.
func ExtractLocal ¶
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 ¶
HasKey reports whether authorized_keys data lists pub, with whatever options and comment; lines that do not parse are skipped.
func IsArchive ¶
IsArchive reports whether name is an archive Extract opens: on the server (remote), or on this computer, which does not read xz.
func IsText ¶
IsText says whether data looks like text to edit: UTF-8 without NULs in its first 8 KB.
func LocalDirSize ¶
LocalDirSize is how much the files under the local folder p hold, and how many there are. Links are not followed.
func LocalExists ¶
LocalExists says whether something is at the local path.
func LocalGroup ¶ added in v0.0.8
LocalGroup is the name of the local group gid, its number when it has none.
func LocalMode ¶
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 ¶
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
LocalUser is the name of the local user uid, its number when it has none.
func MkdirAllLocal ¶
MkdirAllLocal creates download-plan directories with the same confinement as the files that will later populate them.
func MkdirLocal ¶
MkdirLocal makes a folder named name in the local directory dir.
func RemoteParent ¶
RemoteParent is the parent of a remote directory.
func RemoveLocal ¶
RemoveLocal deletes the local path, a folder with what is in it.
func RenameLocal ¶
RenameLocal renames the local path within its folder to name.
func SafeName ¶
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 ¶
ShellQuote quotes s as one word of a POSIX shell.
func UniqueName ¶
UniqueName returns p, or "name (2).ext" and so on, the first that taken does not report as taken.
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 NewContext ¶
NewContext negotiates only a dedicated channel and shares a pending-channel quota with every SFTP client on the same pooled SSH connection.
func (*Client) CreateFile ¶
CreateFile makes an empty file named name in the remote folder dir.
func (*Client) DirSize ¶
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) InstallKey ¶
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) ListContext ¶
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) Names ¶ added in v0.0.8
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 ¶
PlanUpload lists what uploading the local paths into remoteDir copies: folders recursively, folders before what is in them.
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) ResolvePath ¶
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) 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) WriteFile ¶
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 (*Client) WriteFileNoLinks ¶
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 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.
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 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).
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 ¶
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) 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 ¶
Concurrency is how many transfers run at once.
func (*Transfers) PauseAll ¶
func (ts *Transfers) PauseAll()
PauseAll pauses every queued and running transfer.
func (*Transfers) ResumeAll ¶
func (ts *Transfers) ResumeAll()
ResumeAll resumes every paused transfer.
func (*Transfers) Retry ¶
Retry queues a failed or canceled transfer again, with its retries counted afresh; a failed one resumes from its part file.
func (*Transfers) SetConcurrency ¶
SetConcurrency sets how many transfers run at once (1 or more). Those running go on; more start when there is room.
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
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
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.