mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 18:47:20 +01:00
* sftp: copy only the stored bytes on a non-truncating open A size set by a truncate that grows a file stores nothing, but opening the file for writing without O_TRUNC copied its whole logical size into the temp file as zeros. Copy up to the last stored byte and extend the temp file to the size, which leaves the rest sparse. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: upload only up to the written data on close Close streamed the whole temp file, so a hole after the data, from a truncate that grew the file before or during the open, was read back and uploaded as zeros. Track where the copied and written bytes end, upload up to there, and keep the rest as the file's size. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: leave the data end alone on an empty write A zero-length WRITE far past the data moved the data end there, so Close uploaded the hole before it as zeros. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: cap what the test filer reads from an upload An upload that wrongly carries a large hole now fails the test instead of filling memory. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: hash nothing past an out-of-range size A stored size past the largest file offset turned negative and sliced the inline content out of range. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: refuse a setstat size past the largest file offset Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: fail the hash of an out-of-range size Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: check the size before returning a stored md5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
217 lines
6.4 KiB
Go
217 lines
6.4 KiB
Go
package sftpd
|
|
|
|
import (
|
|
"context"
|
|
"crypto/md5"
|
|
"crypto/sha1"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"hash"
|
|
"io"
|
|
"math"
|
|
"path"
|
|
"regexp"
|
|
"strings"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/filer"
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
filer_pb "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
"golang.org/x/crypto/ssh"
|
|
)
|
|
|
|
// The SSH "exec" requests answered here are the few that SFTP clients and
|
|
// scripts commonly run over the same connection to verify transfers by hash
|
|
// and show free space.
|
|
// There is no shell: each command is matched by name and its single path
|
|
// argument is resolved inside the user's home, with the user's permissions.
|
|
//
|
|
// echo <text> prints text (clients use it to detect the shell type)
|
|
// md5sum [path] "<hex> <path>", or the empty-input hash without a path
|
|
// sha1sum [path] likewise
|
|
// df [-k] [path] one df -k style line for the filer's volume capacity
|
|
|
|
// shellUnEscapeRegex undoes the backslash escaping clients apply to paths
|
|
var shellUnEscapeRegex = regexp.MustCompile(`\\(.)`)
|
|
|
|
func shellUnEscape(s string) string {
|
|
s = strings.ReplaceAll(s, "'\n'", "\n")
|
|
return shellUnEscapeRegex.ReplaceAllString(s, `$1`)
|
|
}
|
|
|
|
// trimCommand drops surrounding whitespace but keeps a trailing space that is
|
|
// escaped, since it is part of the last file name (`md5sum a\ `)
|
|
func trimCommand(command string) string {
|
|
command = strings.TrimLeft(command, " \t")
|
|
for len(command) > 0 && strings.ContainsRune(" \t\r\n", rune(command[len(command)-1])) {
|
|
backslashes := 0
|
|
for i := len(command) - 2; i >= 0 && command[i] == '\\'; i-- {
|
|
backslashes++
|
|
}
|
|
if backslashes%2 == 1 {
|
|
break
|
|
}
|
|
command = command[:len(command)-1]
|
|
}
|
|
return command
|
|
}
|
|
|
|
// operandPath makes a command's path operand absolute in the user's view,
|
|
// where a relative name is relative to the home ("/"), as an SFTP client sees
|
|
// it; toAbsolutePath expects such a path
|
|
func operandPath(p string) string {
|
|
return path.Join("/", p)
|
|
}
|
|
|
|
// ctxWriter fails writes once ctx is done, so a hash of a large sparse file
|
|
// stops writing zeros when the connection ends
|
|
type ctxWriter struct {
|
|
ctx context.Context
|
|
w io.Writer
|
|
}
|
|
|
|
func (c ctxWriter) Write(p []byte) (int, error) {
|
|
if err := c.ctx.Err(); err != nil {
|
|
return 0, err
|
|
}
|
|
return c.w.Write(p)
|
|
}
|
|
|
|
type execRequest struct {
|
|
Command string
|
|
}
|
|
|
|
type subsystemRequest struct {
|
|
Name string
|
|
}
|
|
|
|
type exitStatus struct {
|
|
Status uint32
|
|
}
|
|
|
|
// handleExec runs one exec request on channel and closes it, reporting the
|
|
// exit status the way a shell would. ctx ends with the channel, so a hash of a
|
|
// large file stops reading once the client closes the session.
|
|
func (s *SFTPService) handleExec(ctx context.Context, channel ssh.Channel, fs *SftpServer, command string) {
|
|
defer channel.Close()
|
|
status := uint32(0)
|
|
if err := fs.execCommand(ctx, channel, command); err != nil {
|
|
status = 1
|
|
fmt.Fprintf(channel.Stderr(), "%v\n", err)
|
|
glog.V(1).Infof("sftp exec %q for %s: %v", command, fs.user.Username, err)
|
|
}
|
|
if _, err := channel.SendRequest("exit-status", false, ssh.Marshal(exitStatus{Status: status})); err != nil {
|
|
glog.V(1).Infof("sftp exec exit-status: %v", err)
|
|
}
|
|
}
|
|
|
|
func (fs *SftpServer) execCommand(ctx context.Context, out io.Writer, command string) error {
|
|
name, args, _ := strings.Cut(trimCommand(command), " ")
|
|
args = strings.TrimLeft(args, " ")
|
|
switch name {
|
|
case "echo":
|
|
_, err := fmt.Fprintf(out, "%s\n", args)
|
|
return err
|
|
case "md5sum":
|
|
return fs.hashsum(ctx, out, "md5", shellUnEscape(args))
|
|
case "sha1sum":
|
|
return fs.hashsum(ctx, out, "sha1", shellUnEscape(args))
|
|
case "df":
|
|
if args == "-k" || strings.HasPrefix(args, "-k ") {
|
|
args = strings.TrimLeft(args[2:], " ")
|
|
}
|
|
return fs.df(ctx, out, shellUnEscape(args))
|
|
default:
|
|
return fmt.Errorf("%s: command not supported", name)
|
|
}
|
|
}
|
|
|
|
func newHash(kind string) hash.Hash {
|
|
if kind == "sha1" {
|
|
return sha1.New()
|
|
}
|
|
return md5.New()
|
|
}
|
|
|
|
// hashsum prints the hash of the file at userPath, or of empty input when
|
|
// there is none, in the coreutils "<hex> <name>" format
|
|
func (fs *SftpServer) hashsum(ctx context.Context, out io.Writer, kind, userPath string) error {
|
|
if userPath == "" {
|
|
_, err := fmt.Fprintf(out, "%s -\n", hex.EncodeToString(newHash(kind).Sum(nil)))
|
|
return err
|
|
}
|
|
sum, err := fs.fileHash(ctx, kind, userPath)
|
|
if err != nil {
|
|
return fmt.Errorf("%s: %s: %w", kind+"sum", userPath, err)
|
|
}
|
|
_, err = fmt.Fprintf(out, "%s %s\n", sum, userPath)
|
|
return err
|
|
}
|
|
|
|
func (fs *SftpServer) fileHash(ctx context.Context, kind, userPath string) (string, error) {
|
|
absPath, err := fs.toAbsolutePath(operandPath(userPath))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if err := fs.checkFilePermission(absPath, "read"); err != nil {
|
|
return "", err
|
|
}
|
|
entry, err := fs.getEntry(absPath)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if entry.IsDirectory {
|
|
return "", errors.New("is a directory")
|
|
}
|
|
// the filer keeps the MD5 of files uploaded in one piece, and writers
|
|
// clear it when they change the content; it is the same MD5 the S3 and
|
|
// WebDAV ETags report
|
|
size := filer.FileSize(entry)
|
|
if size > math.MaxInt64 {
|
|
return "", fmt.Errorf("size %d is out of range", size)
|
|
}
|
|
if kind == "md5" && entry.Attributes != nil && len(entry.Attributes.Md5) > 0 {
|
|
return hex.EncodeToString(entry.Attributes.Md5), nil
|
|
}
|
|
h := newHash(kind)
|
|
if err := fs.writeContent(ctx, absPath, entry, int64(size), ctxWriter{ctx, h}); err != nil {
|
|
return "", err
|
|
}
|
|
return hex.EncodeToString(h.Sum(nil)), nil
|
|
}
|
|
|
|
// df prints the filer's volume capacity in df -k format; the path has to
|
|
// exist inside the user's home
|
|
func (fs *SftpServer) df(ctx context.Context, out io.Writer, userPath string) error {
|
|
if userPath == "" {
|
|
userPath = "/"
|
|
}
|
|
absPath, err := fs.toAbsolutePath(operandPath(userPath))
|
|
if err == nil {
|
|
_, err = fs.getEntry(absPath)
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("df: %s: %w", userPath, err)
|
|
}
|
|
var resp *filer_pb.StatisticsResponse
|
|
err = fs.callWithClient(false, func(ctx context.Context, client filer_pb.SeaweedFilerClient) error {
|
|
var err error
|
|
resp, err = client.Statistics(ctx, &filer_pb.StatisticsRequest{})
|
|
return err
|
|
})
|
|
if err != nil {
|
|
return fmt.Errorf("df: %w", err)
|
|
}
|
|
total, used := resp.TotalSize/1024, resp.UsedSize/1024
|
|
avail := uint64(0)
|
|
if total > used {
|
|
avail = total - used
|
|
}
|
|
percent := uint64(0)
|
|
if total > 0 {
|
|
percent = (100*used + total - 1) / total
|
|
}
|
|
_, err = fmt.Fprintf(out, "Filesystem 1K-blocks Used Available Use%% Mounted on\nseaweedfs %d %d %d %d%% /\n", total, used, avail, percent)
|
|
return err
|
|
}
|