From 099eff8891d1d7bd081bb1c9218ff5c0863921b2 Mon Sep 17 00:00:00 2001 From: Nick Craig-Wood Date: Mon, 15 Nov 2021 12:21:43 +0000 Subject: [PATCH] sftp: refactor so we only have one way of running remote commands This also returns errors from running ssh Hash commands which we didn't do before. --- backend/sftp/sftp.go | 30 +++++------------------------- 1 file changed, 5 insertions(+), 25 deletions(-) diff --git a/backend/sftp/sftp.go b/backend/sftp/sftp.go index 6f77e8d4a..ebdc4a24c 100644 --- a/backend/sftp/sftp.go +++ b/backend/sftp/sftp.go @@ -1110,10 +1110,12 @@ func (f *Fs) run(ctx context.Context, cmd string) ([]byte, error) { session.Stdout = &stdout session.Stderr = &stderr + fs.Debugf(f, "Running remote command: %s", cmd) err = session.Run(cmd) if err != nil { - return nil, fmt.Errorf("failed to run %q: %s: %w", cmd, stderr.Bytes(), err) + return nil, fmt.Errorf("failed to run %q: %s: %w", cmd, bytes.TrimSpace(stderr.Bytes()), err) } + fs.Debugf(f, "Remote command result: %s", bytes.TrimSpace(stdout.Bytes())) return stdout.Bytes(), nil } @@ -1230,8 +1232,6 @@ func (o *Object) Remote() string { // Hash returns the selected checksum of the file // If no checksum is available it returns "" func (o *Object) Hash(ctx context.Context, r hash.Type) (string, error) { - o.fs.addSession() // Show session in use - defer o.fs.removeSession() if o.fs.opt.DisableHashCheck { return "", nil } @@ -1255,36 +1255,16 @@ func (o *Object) Hash(ctx context.Context, r hash.Type) (string, error) { return "", hash.ErrUnsupported } - c, err := o.fs.getSftpConnection(ctx) - if err != nil { - return "", fmt.Errorf("Hash get SFTP connection: %w", err) - } - session, err := c.sshClient.NewSession() - o.fs.putSftpConnection(&c, err) - if err != nil { - return "", fmt.Errorf("Hash put SFTP connection: %w", err) - } - - var stdout, stderr bytes.Buffer - session.Stdout = &stdout - session.Stderr = &stderr escapedPath := shellEscape(o.path()) if o.fs.opt.PathOverride != "" { escapedPath = shellEscape(path.Join(o.fs.opt.PathOverride, o.remote)) } - err = session.Run(hashCmd + " " + escapedPath) - fs.Debugf(nil, "sftp cmd = %s", escapedPath) + b, err := o.fs.run(ctx, hashCmd+" "+escapedPath) if err != nil { - _ = session.Close() - fs.Debugf(o, "Failed to calculate %v hash: %v (%s)", r, err, bytes.TrimSpace(stderr.Bytes())) - return "", nil + return "", fmt.Errorf("failed to calculate %v hash: %w", r, err) } - _ = session.Close() - b := stdout.Bytes() - fs.Debugf(nil, "sftp output = %q", b) str := parseHash(b) - fs.Debugf(nil, "sftp hash = %q", str) if r == hash.MD5 { o.md5sum = &str } else if r == hash.SHA1 {