2024-01-01 10:31:45 +00:00
|
|
|
// Copyright (C) 2019 Nicola Murino
|
2022-07-17 18:16:00 +00:00
|
|
|
//
|
|
|
|
// This program is free software: you can redistribute it and/or modify
|
|
|
|
// it under the terms of the GNU Affero General Public License as published
|
|
|
|
// by the Free Software Foundation, version 3.
|
|
|
|
//
|
|
|
|
// This program is distributed in the hope that it will be useful,
|
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU Affero General Public License for more details.
|
|
|
|
//
|
|
|
|
// You should have received a copy of the GNU Affero General Public License
|
2023-01-03 09:18:30 +00:00
|
|
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
2022-07-17 18:16:00 +00:00
|
|
|
|
2020-12-12 09:31:09 +00:00
|
|
|
package vfs
|
|
|
|
|
|
|
|
import (
|
2021-04-03 14:00:55 +00:00
|
|
|
"bufio"
|
2022-11-01 11:22:54 +00:00
|
|
|
"bytes"
|
2024-02-25 10:12:57 +00:00
|
|
|
"crypto/rsa"
|
2020-12-12 09:31:09 +00:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
2022-11-01 11:22:54 +00:00
|
|
|
"hash/fnv"
|
2020-12-12 09:31:09 +00:00
|
|
|
"io"
|
2022-05-09 17:09:43 +00:00
|
|
|
"io/fs"
|
2020-12-12 09:31:09 +00:00
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"path"
|
|
|
|
"path/filepath"
|
2022-11-01 11:22:54 +00:00
|
|
|
"strconv"
|
2020-12-12 09:31:09 +00:00
|
|
|
"strings"
|
2020-12-23 16:15:55 +00:00
|
|
|
"sync"
|
2022-11-01 11:22:54 +00:00
|
|
|
"sync/atomic"
|
2020-12-12 09:31:09 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/eikenb/pipeat"
|
|
|
|
"github.com/pkg/sftp"
|
2022-11-01 11:22:54 +00:00
|
|
|
"github.com/robfig/cron/v3"
|
2020-12-12 09:31:09 +00:00
|
|
|
"github.com/rs/xid"
|
2022-01-06 10:54:43 +00:00
|
|
|
"github.com/sftpgo/sdk"
|
2020-12-12 09:31:09 +00:00
|
|
|
"golang.org/x/crypto/ssh"
|
|
|
|
|
2022-07-24 14:18:54 +00:00
|
|
|
"github.com/drakkan/sftpgo/v2/internal/kms"
|
|
|
|
"github.com/drakkan/sftpgo/v2/internal/logger"
|
|
|
|
"github.com/drakkan/sftpgo/v2/internal/util"
|
|
|
|
"github.com/drakkan/sftpgo/v2/internal/version"
|
2020-12-12 09:31:09 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2021-04-23 20:53:13 +00:00
|
|
|
// sftpFsName is the name for the SFTP Fs implementation
|
2022-11-01 11:22:54 +00:00
|
|
|
sftpFsName = "sftpfs"
|
|
|
|
logSenderSFTPCache = "sftpCache"
|
|
|
|
maxSessionsPerConnection = 5
|
2020-12-12 09:31:09 +00:00
|
|
|
)
|
|
|
|
|
2022-11-01 11:22:54 +00:00
|
|
|
var (
|
|
|
|
// ErrSFTPLoop defines the error to return if an SFTP loop is detected
|
|
|
|
ErrSFTPLoop = errors.New("SFTP loop or nested local SFTP folders detected")
|
|
|
|
sftpConnsCache = newSFTPConnectionCache()
|
|
|
|
)
|
2021-04-01 16:53:48 +00:00
|
|
|
|
2020-12-12 09:31:09 +00:00
|
|
|
// SFTPFsConfig defines the configuration for SFTP based filesystem
|
|
|
|
type SFTPFsConfig struct {
|
2022-01-06 09:11:47 +00:00
|
|
|
sdk.BaseSFTPFsConfig
|
|
|
|
Password *kms.Secret `json:"password,omitempty"`
|
|
|
|
PrivateKey *kms.Secret `json:"private_key,omitempty"`
|
2022-05-30 17:01:12 +00:00
|
|
|
KeyPassphrase *kms.Secret `json:"key_passphrase,omitempty"`
|
2022-01-06 09:11:47 +00:00
|
|
|
forbiddenSelfUsernames []string `json:"-"`
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
2021-09-11 12:19:17 +00:00
|
|
|
// HideConfidentialData hides confidential data
|
|
|
|
func (c *SFTPFsConfig) HideConfidentialData() {
|
|
|
|
if c.Password != nil {
|
|
|
|
c.Password.Hide()
|
|
|
|
}
|
|
|
|
if c.PrivateKey != nil {
|
|
|
|
c.PrivateKey.Hide()
|
|
|
|
}
|
2022-05-30 17:01:12 +00:00
|
|
|
if c.KeyPassphrase != nil {
|
|
|
|
c.KeyPassphrase.Hide()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *SFTPFsConfig) setNilSecretsIfEmpty() {
|
|
|
|
if c.Password != nil && c.Password.IsEmpty() {
|
|
|
|
c.Password = nil
|
|
|
|
}
|
|
|
|
if c.PrivateKey != nil && c.PrivateKey.IsEmpty() {
|
|
|
|
c.PrivateKey = nil
|
|
|
|
}
|
|
|
|
if c.KeyPassphrase != nil && c.KeyPassphrase.IsEmpty() {
|
|
|
|
c.KeyPassphrase = nil
|
2022-05-30 17:00:39 +00:00
|
|
|
}
|
2021-09-11 12:19:17 +00:00
|
|
|
}
|
|
|
|
|
2022-08-15 19:39:04 +00:00
|
|
|
func (c *SFTPFsConfig) isEqual(other SFTPFsConfig) bool {
|
2021-03-27 18:10:27 +00:00
|
|
|
if c.Endpoint != other.Endpoint {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if c.Username != other.Username {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if c.Prefix != other.Prefix {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if c.DisableCouncurrentReads != other.DisableCouncurrentReads {
|
|
|
|
return false
|
|
|
|
}
|
2021-04-03 14:00:55 +00:00
|
|
|
if c.BufferSize != other.BufferSize {
|
|
|
|
return false
|
|
|
|
}
|
2021-03-27 18:10:27 +00:00
|
|
|
if len(c.Fingerprints) != len(other.Fingerprints) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
for _, fp := range c.Fingerprints {
|
2022-05-19 17:49:51 +00:00
|
|
|
if !util.Contains(other.Fingerprints, fp) {
|
2021-03-27 18:10:27 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
c.setEmptyCredentialsIfNil()
|
|
|
|
other.setEmptyCredentialsIfNil()
|
|
|
|
if !c.Password.IsEqual(other.Password) {
|
|
|
|
return false
|
|
|
|
}
|
2022-05-30 17:01:12 +00:00
|
|
|
if !c.KeyPassphrase.IsEqual(other.KeyPassphrase) {
|
2022-05-30 17:00:39 +00:00
|
|
|
return false
|
|
|
|
}
|
2021-03-27 18:10:27 +00:00
|
|
|
return c.PrivateKey.IsEqual(other.PrivateKey)
|
|
|
|
}
|
|
|
|
|
2020-12-12 09:31:09 +00:00
|
|
|
func (c *SFTPFsConfig) setEmptyCredentialsIfNil() {
|
|
|
|
if c.Password == nil {
|
|
|
|
c.Password = kms.NewEmptySecret()
|
|
|
|
}
|
|
|
|
if c.PrivateKey == nil {
|
|
|
|
c.PrivateKey = kms.NewEmptySecret()
|
|
|
|
}
|
2022-05-30 17:01:12 +00:00
|
|
|
if c.KeyPassphrase == nil {
|
|
|
|
c.KeyPassphrase = kms.NewEmptySecret()
|
2022-05-30 17:00:39 +00:00
|
|
|
}
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
2022-08-15 19:39:04 +00:00
|
|
|
func (c *SFTPFsConfig) isSameResource(other SFTPFsConfig) bool {
|
|
|
|
if c.EqualityCheckMode > 0 || other.EqualityCheckMode > 0 {
|
|
|
|
if c.Username != other.Username {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return c.Endpoint == other.Endpoint
|
|
|
|
}
|
|
|
|
|
2022-04-28 10:55:01 +00:00
|
|
|
// validate returns an error if the configuration is not valid
|
|
|
|
func (c *SFTPFsConfig) validate() error {
|
2020-12-12 09:31:09 +00:00
|
|
|
c.setEmptyCredentialsIfNil()
|
|
|
|
if c.Endpoint == "" {
|
2024-01-11 18:26:13 +00:00
|
|
|
return util.NewI18nError(errors.New("endpoint cannot be empty"), util.I18nErrorEndpointRequired)
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
if !strings.Contains(c.Endpoint, ":") {
|
|
|
|
c.Endpoint += ":22"
|
|
|
|
}
|
2021-02-03 10:29:04 +00:00
|
|
|
_, _, err := net.SplitHostPort(c.Endpoint)
|
|
|
|
if err != nil {
|
2024-01-11 18:26:13 +00:00
|
|
|
return util.NewI18nError(fmt.Errorf("invalid endpoint: %v", err), util.I18nErrorEndpointInvalid)
|
2021-02-03 10:29:04 +00:00
|
|
|
}
|
2020-12-12 09:31:09 +00:00
|
|
|
if c.Username == "" {
|
2024-01-11 18:26:13 +00:00
|
|
|
return util.NewI18nError(errors.New("username cannot be empty"), util.I18nErrorFsUsernameRequired)
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
2021-04-04 20:32:25 +00:00
|
|
|
if c.BufferSize < 0 || c.BufferSize > 16 {
|
|
|
|
return errors.New("invalid buffer_size, valid range is 0-16")
|
2021-04-03 14:00:55 +00:00
|
|
|
}
|
2022-08-15 19:39:04 +00:00
|
|
|
if !isEqualityCheckModeValid(c.EqualityCheckMode) {
|
|
|
|
return errors.New("invalid equality_check_mode")
|
|
|
|
}
|
2021-04-03 14:00:55 +00:00
|
|
|
if err := c.validateCredentials(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if c.Prefix != "" {
|
2021-07-11 13:26:51 +00:00
|
|
|
c.Prefix = util.CleanPath(c.Prefix)
|
2021-04-03 14:00:55 +00:00
|
|
|
} else {
|
|
|
|
c.Prefix = "/"
|
|
|
|
}
|
2024-02-25 10:12:57 +00:00
|
|
|
return c.validatePrivateKey()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *SFTPFsConfig) validatePrivateKey() error {
|
|
|
|
if c.PrivateKey.IsPlain() {
|
|
|
|
var signer ssh.Signer
|
|
|
|
var err error
|
|
|
|
if c.KeyPassphrase.IsPlain() {
|
|
|
|
signer, err = ssh.ParsePrivateKeyWithPassphrase([]byte(c.PrivateKey.GetPayload()),
|
|
|
|
[]byte(c.KeyPassphrase.GetPayload()))
|
|
|
|
} else {
|
|
|
|
signer, err = ssh.ParsePrivateKey([]byte(c.PrivateKey.GetPayload()))
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return util.NewI18nError(fmt.Errorf("invalid private key: %w", err), util.I18nErrorPrivKeyInvalid)
|
|
|
|
}
|
|
|
|
if key, ok := signer.PublicKey().(ssh.CryptoPublicKey); ok {
|
|
|
|
cryptoKey := key.CryptoPublicKey()
|
|
|
|
if rsaKey, ok := cryptoKey.(*rsa.PublicKey); ok {
|
|
|
|
if size := rsaKey.N.BitLen(); size < 2048 {
|
|
|
|
return util.NewI18nError(
|
|
|
|
fmt.Errorf("rsa key with size %d not accepted, minimum 2048", size),
|
|
|
|
util.I18nErrorKeySizeInvalid,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-04-03 14:00:55 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *SFTPFsConfig) validateCredentials() error {
|
2020-12-12 09:31:09 +00:00
|
|
|
if c.Password.IsEmpty() && c.PrivateKey.IsEmpty() {
|
2024-01-11 18:26:13 +00:00
|
|
|
return util.NewI18nError(errors.New("credentials cannot be empty"), util.I18nErrorFsCredentialsRequired)
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
if c.Password.IsEncrypted() && !c.Password.IsValid() {
|
|
|
|
return errors.New("invalid encrypted password")
|
|
|
|
}
|
|
|
|
if !c.Password.IsEmpty() && !c.Password.IsValidInput() {
|
|
|
|
return errors.New("invalid password")
|
|
|
|
}
|
|
|
|
if c.PrivateKey.IsEncrypted() && !c.PrivateKey.IsValid() {
|
|
|
|
return errors.New("invalid encrypted private key")
|
|
|
|
}
|
|
|
|
if !c.PrivateKey.IsEmpty() && !c.PrivateKey.IsValidInput() {
|
|
|
|
return errors.New("invalid private key")
|
|
|
|
}
|
2022-05-30 17:01:12 +00:00
|
|
|
if c.KeyPassphrase.IsEncrypted() && !c.KeyPassphrase.IsValid() {
|
|
|
|
return errors.New("invalid encrypted private key passphrase")
|
|
|
|
}
|
|
|
|
if !c.KeyPassphrase.IsEmpty() && !c.KeyPassphrase.IsValidInput() {
|
|
|
|
return errors.New("invalid private key passphrase")
|
|
|
|
}
|
2020-12-12 09:31:09 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-06-11 08:41:34 +00:00
|
|
|
// ValidateAndEncryptCredentials validates the config and encrypts credentials if they are in plain text
|
2022-04-28 10:55:01 +00:00
|
|
|
func (c *SFTPFsConfig) ValidateAndEncryptCredentials(additionalData string) error {
|
|
|
|
if err := c.validate(); err != nil {
|
2024-01-11 18:26:13 +00:00
|
|
|
var errI18n *util.I18nError
|
|
|
|
errValidation := util.NewValidationError(fmt.Sprintf("could not validate SFTP fs config: %v", err))
|
|
|
|
if errors.As(err, &errI18n) {
|
|
|
|
return util.NewI18nError(errValidation, errI18n.Message)
|
|
|
|
}
|
|
|
|
return util.NewI18nError(errValidation, util.I18nErrorFsValidation)
|
2022-04-28 10:55:01 +00:00
|
|
|
}
|
2020-12-12 09:31:09 +00:00
|
|
|
if c.Password.IsPlain() {
|
|
|
|
c.Password.SetAdditionalData(additionalData)
|
|
|
|
if err := c.Password.Encrypt(); err != nil {
|
2024-01-11 18:26:13 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError(fmt.Sprintf("could not encrypt SFTP fs password: %v", err)),
|
|
|
|
util.I18nErrorFsValidation,
|
|
|
|
)
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
if c.PrivateKey.IsPlain() {
|
|
|
|
c.PrivateKey.SetAdditionalData(additionalData)
|
|
|
|
if err := c.PrivateKey.Encrypt(); err != nil {
|
2024-01-11 18:26:13 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError(fmt.Sprintf("could not encrypt SFTP fs private key: %v", err)),
|
|
|
|
util.I18nErrorFsValidation,
|
|
|
|
)
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
}
|
2022-05-30 17:01:12 +00:00
|
|
|
if c.KeyPassphrase.IsPlain() {
|
|
|
|
c.KeyPassphrase.SetAdditionalData(additionalData)
|
|
|
|
if err := c.KeyPassphrase.Encrypt(); err != nil {
|
2024-01-11 18:26:13 +00:00
|
|
|
return util.NewI18nError(
|
|
|
|
util.NewValidationError(fmt.Sprintf("could not encrypt SFTP fs private key passphrase: %v", err)),
|
|
|
|
util.I18nErrorFsValidation,
|
|
|
|
)
|
2022-05-30 17:00:39 +00:00
|
|
|
}
|
|
|
|
}
|
2020-12-12 09:31:09 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-11-01 11:22:54 +00:00
|
|
|
// getUniqueID returns an hash of the settings used to connect to the SFTP server
|
|
|
|
func (c *SFTPFsConfig) getUniqueID(partition int) uint64 {
|
|
|
|
h := fnv.New64a()
|
|
|
|
var b bytes.Buffer
|
|
|
|
|
|
|
|
b.WriteString(c.Endpoint)
|
|
|
|
b.WriteString(c.Username)
|
|
|
|
b.WriteString(strings.Join(c.Fingerprints, ""))
|
|
|
|
b.WriteString(strconv.FormatBool(c.DisableCouncurrentReads))
|
|
|
|
b.WriteString(strconv.FormatInt(c.BufferSize, 10))
|
|
|
|
b.WriteString(c.Password.GetPayload())
|
|
|
|
b.WriteString(c.PrivateKey.GetPayload())
|
|
|
|
b.WriteString(c.KeyPassphrase.GetPayload())
|
|
|
|
if allowSelfConnections != 0 {
|
|
|
|
b.WriteString(strings.Join(c.forbiddenSelfUsernames, ""))
|
|
|
|
}
|
|
|
|
b.WriteString(strconv.Itoa(partition))
|
|
|
|
|
|
|
|
h.Write(b.Bytes())
|
|
|
|
return h.Sum64()
|
|
|
|
}
|
|
|
|
|
2020-12-12 09:31:09 +00:00
|
|
|
// SFTPFs is a Fs implementation for SFTP backends
|
|
|
|
type SFTPFs struct {
|
|
|
|
connectionID string
|
2021-03-21 18:15:47 +00:00
|
|
|
// if not empty this fs is mouted as virtual folder in the specified path
|
2021-04-03 14:00:55 +00:00
|
|
|
mountPath string
|
|
|
|
localTempDir string
|
|
|
|
config *SFTPFsConfig
|
2022-11-01 11:22:54 +00:00
|
|
|
conn *sftpConnection
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
2021-04-23 20:53:13 +00:00
|
|
|
// NewSFTPFs returns an SFTPFs object that allows to interact with an SFTP server
|
2021-04-03 14:00:55 +00:00
|
|
|
func NewSFTPFs(connectionID, mountPath, localTempDir string, forbiddenSelfUsernames []string, config SFTPFsConfig) (Fs, error) {
|
|
|
|
if localTempDir == "" {
|
2023-10-17 16:06:52 +00:00
|
|
|
localTempDir = getLocalTempDir()
|
2021-04-03 14:00:55 +00:00
|
|
|
}
|
2022-04-28 10:55:01 +00:00
|
|
|
if err := config.validate(); err != nil {
|
2020-12-12 09:31:09 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
2021-03-27 18:10:27 +00:00
|
|
|
if !config.Password.IsEmpty() {
|
|
|
|
if err := config.Password.TryDecrypt(); err != nil {
|
2020-12-12 09:31:09 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
2021-03-27 18:10:27 +00:00
|
|
|
if !config.PrivateKey.IsEmpty() {
|
|
|
|
if err := config.PrivateKey.TryDecrypt(); err != nil {
|
2020-12-12 09:31:09 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
2022-05-30 17:01:12 +00:00
|
|
|
if !config.KeyPassphrase.IsEmpty() {
|
|
|
|
if err := config.KeyPassphrase.TryDecrypt(); err != nil {
|
2022-05-30 17:00:39 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
2021-04-01 16:53:48 +00:00
|
|
|
config.forbiddenSelfUsernames = forbiddenSelfUsernames
|
2020-12-12 09:31:09 +00:00
|
|
|
sftpFs := &SFTPFs{
|
|
|
|
connectionID: connectionID,
|
2022-04-02 16:32:46 +00:00
|
|
|
mountPath: getMountPath(mountPath),
|
2021-04-03 14:00:55 +00:00
|
|
|
localTempDir: localTempDir,
|
2020-12-12 09:31:09 +00:00
|
|
|
config: &config,
|
2022-11-01 11:22:54 +00:00
|
|
|
conn: sftpConnsCache.Get(&config, connectionID),
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
err := sftpFs.createConnection()
|
2022-11-01 11:22:54 +00:00
|
|
|
if err != nil {
|
|
|
|
sftpFs.Close() //nolint:errcheck
|
|
|
|
}
|
2020-12-12 09:31:09 +00:00
|
|
|
return sftpFs, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Name returns the name for the Fs implementation
|
|
|
|
func (fs *SFTPFs) Name() string {
|
2022-11-01 11:22:54 +00:00
|
|
|
return fmt.Sprintf(`%s %q@%q`, sftpFsName, fs.config.Username, fs.config.Endpoint)
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// ConnectionID returns the connection ID associated to this Fs implementation
|
|
|
|
func (fs *SFTPFs) ConnectionID() string {
|
|
|
|
return fs.connectionID
|
|
|
|
}
|
|
|
|
|
|
|
|
// Stat returns a FileInfo describing the named file
|
|
|
|
func (fs *SFTPFs) Stat(name string) (os.FileInfo, error) {
|
2022-11-01 11:22:54 +00:00
|
|
|
client, err := fs.conn.getClient()
|
|
|
|
if err != nil {
|
2020-12-12 09:31:09 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
return client.Stat(name)
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Lstat returns a FileInfo describing the named file
|
|
|
|
func (fs *SFTPFs) Lstat(name string) (os.FileInfo, error) {
|
2022-11-01 11:22:54 +00:00
|
|
|
client, err := fs.conn.getClient()
|
|
|
|
if err != nil {
|
2020-12-12 09:31:09 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
return client.Lstat(name)
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Open opens the named file for reading
|
2024-01-24 18:59:50 +00:00
|
|
|
func (fs *SFTPFs) Open(name string, offset int64) (File, PipeReader, func(), error) {
|
2022-11-01 11:22:54 +00:00
|
|
|
client, err := fs.conn.getClient()
|
|
|
|
if err != nil {
|
2020-12-12 09:31:09 +00:00
|
|
|
return nil, nil, nil, err
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
f, err := client.Open(name)
|
2021-05-26 05:48:37 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, nil, err
|
|
|
|
}
|
2021-04-03 14:00:55 +00:00
|
|
|
if offset > 0 {
|
|
|
|
_, err = f.Seek(offset, io.SeekStart)
|
|
|
|
if err != nil {
|
|
|
|
f.Close()
|
|
|
|
return nil, nil, nil, err
|
|
|
|
}
|
|
|
|
}
|
2022-07-21 16:42:22 +00:00
|
|
|
if fs.config.BufferSize == 0 {
|
|
|
|
return f, nil, nil, nil
|
|
|
|
}
|
2021-04-03 14:00:55 +00:00
|
|
|
r, w, err := pipeat.PipeInDir(fs.localTempDir)
|
|
|
|
if err != nil {
|
|
|
|
f.Close()
|
|
|
|
return nil, nil, nil, err
|
|
|
|
}
|
2023-08-12 16:51:47 +00:00
|
|
|
p := NewPipeReader(r)
|
|
|
|
|
2021-04-03 14:00:55 +00:00
|
|
|
go func() {
|
2021-06-05 14:07:09 +00:00
|
|
|
// if we enable buffering the client stalls
|
|
|
|
//br := bufio.NewReaderSize(f, int(fs.config.BufferSize)*1024*1024)
|
|
|
|
//n, err := fs.copy(w, br)
|
2021-04-04 20:32:25 +00:00
|
|
|
n, err := io.Copy(w, f)
|
2021-04-03 14:00:55 +00:00
|
|
|
w.CloseWithError(err) //nolint:errcheck
|
|
|
|
f.Close()
|
2023-02-27 18:02:43 +00:00
|
|
|
fsLog(fs, logger.LevelDebug, "download completed, path: %q size: %v, err: %v", name, n, err)
|
2021-04-03 14:00:55 +00:00
|
|
|
}()
|
|
|
|
|
2023-08-12 16:51:47 +00:00
|
|
|
return nil, p, nil, nil
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Create creates or opens the named file for writing
|
2023-10-22 14:30:04 +00:00
|
|
|
func (fs *SFTPFs) Create(name string, flag, _ int) (File, PipeWriter, func(), error) {
|
2022-11-01 11:22:54 +00:00
|
|
|
client, err := fs.conn.getClient()
|
2020-12-12 09:31:09 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, nil, err
|
|
|
|
}
|
2021-04-03 14:00:55 +00:00
|
|
|
if fs.config.BufferSize == 0 {
|
|
|
|
var f File
|
|
|
|
if flag == 0 {
|
2022-11-01 11:22:54 +00:00
|
|
|
f, err = client.Create(name)
|
2021-04-03 14:00:55 +00:00
|
|
|
} else {
|
2022-11-01 11:22:54 +00:00
|
|
|
f, err = client.OpenFile(name, flag)
|
2021-04-03 14:00:55 +00:00
|
|
|
}
|
|
|
|
return f, nil, nil, err
|
|
|
|
}
|
|
|
|
// buffering is enabled
|
2022-11-01 11:22:54 +00:00
|
|
|
f, err := client.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC)
|
2021-04-03 14:00:55 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, nil, err
|
|
|
|
}
|
|
|
|
r, w, err := pipeat.PipeInDir(fs.localTempDir)
|
|
|
|
if err != nil {
|
|
|
|
f.Close()
|
|
|
|
return nil, nil, nil, err
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
2021-04-03 14:00:55 +00:00
|
|
|
p := NewPipeWriter(w)
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
bw := bufio.NewWriterSize(f, int(fs.config.BufferSize)*1024*1024)
|
|
|
|
// we don't use io.Copy since bufio.Writer implements io.WriterTo and
|
|
|
|
// so it calls the sftp.File WriteTo method without buffering
|
2023-05-16 16:08:14 +00:00
|
|
|
n, err := doCopy(bw, r, nil)
|
2021-04-03 14:00:55 +00:00
|
|
|
errFlush := bw.Flush()
|
|
|
|
if err == nil && errFlush != nil {
|
|
|
|
err = errFlush
|
|
|
|
}
|
2021-04-05 09:28:28 +00:00
|
|
|
var errTruncate error
|
|
|
|
if err != nil {
|
|
|
|
errTruncate = f.Truncate(n)
|
|
|
|
}
|
2021-04-03 14:00:55 +00:00
|
|
|
errClose := f.Close()
|
|
|
|
if err == nil && errClose != nil {
|
|
|
|
err = errClose
|
|
|
|
}
|
|
|
|
r.CloseWithError(err) //nolint:errcheck
|
|
|
|
p.Done(err)
|
2023-02-27 18:02:43 +00:00
|
|
|
fsLog(fs, logger.LevelDebug, "upload completed, path: %q, readed bytes: %v, err: %v err truncate: %v",
|
2021-04-03 14:00:55 +00:00
|
|
|
name, n, err, errTruncate)
|
|
|
|
}()
|
|
|
|
|
|
|
|
return nil, p, nil, nil
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Rename renames (moves) source to target.
|
2023-01-06 11:33:50 +00:00
|
|
|
func (fs *SFTPFs) Rename(source, target string) (int, int64, error) {
|
2022-08-15 19:39:04 +00:00
|
|
|
if source == target {
|
2023-01-06 11:33:50 +00:00
|
|
|
return -1, -1, nil
|
2022-08-15 19:39:04 +00:00
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
client, err := fs.conn.getClient()
|
|
|
|
if err != nil {
|
2023-01-06 11:33:50 +00:00
|
|
|
return -1, -1, err
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
if _, ok := client.HasExtension("posix-rename@openssh.com"); ok {
|
2023-01-06 11:33:50 +00:00
|
|
|
err := client.PosixRename(source, target)
|
|
|
|
return -1, -1, err
|
2022-02-16 15:05:56 +00:00
|
|
|
}
|
2023-01-06 11:33:50 +00:00
|
|
|
err = client.Rename(source, target)
|
|
|
|
return -1, -1, err
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Remove removes the named file or (empty) directory.
|
|
|
|
func (fs *SFTPFs) Remove(name string, isDir bool) error {
|
2022-11-01 11:22:54 +00:00
|
|
|
client, err := fs.conn.getClient()
|
|
|
|
if err != nil {
|
2020-12-12 09:31:09 +00:00
|
|
|
return err
|
|
|
|
}
|
2022-02-16 15:46:28 +00:00
|
|
|
if isDir {
|
2022-11-01 11:22:54 +00:00
|
|
|
return client.RemoveDirectory(name)
|
2022-02-16 15:46:28 +00:00
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
return client.Remove(name)
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Mkdir creates a new directory with the specified name and default permissions
|
|
|
|
func (fs *SFTPFs) Mkdir(name string) error {
|
2022-11-01 11:22:54 +00:00
|
|
|
client, err := fs.conn.getClient()
|
|
|
|
if err != nil {
|
2020-12-12 09:31:09 +00:00
|
|
|
return err
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
return client.Mkdir(name)
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Symlink creates source as a symbolic link to target.
|
|
|
|
func (fs *SFTPFs) Symlink(source, target string) error {
|
2022-11-01 11:22:54 +00:00
|
|
|
client, err := fs.conn.getClient()
|
|
|
|
if err != nil {
|
2020-12-12 09:31:09 +00:00
|
|
|
return err
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
return client.Symlink(source, target)
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Readlink returns the destination of the named symbolic link
|
|
|
|
func (fs *SFTPFs) Readlink(name string) (string, error) {
|
2022-11-01 11:22:54 +00:00
|
|
|
client, err := fs.conn.getClient()
|
|
|
|
if err != nil {
|
2020-12-12 09:31:09 +00:00
|
|
|
return "", err
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
resolved, err := client.ReadLink(name)
|
2022-04-27 16:38:46 +00:00
|
|
|
if err != nil {
|
|
|
|
return resolved, err
|
|
|
|
}
|
|
|
|
resolved = path.Clean(resolved)
|
|
|
|
if !path.IsAbs(resolved) {
|
|
|
|
// we assume that multiple links are not followed
|
|
|
|
resolved = path.Join(path.Dir(name), resolved)
|
|
|
|
}
|
|
|
|
return fs.GetRelativePath(resolved), nil
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Chown changes the numeric uid and gid of the named file.
|
|
|
|
func (fs *SFTPFs) Chown(name string, uid int, gid int) error {
|
2022-11-01 11:22:54 +00:00
|
|
|
client, err := fs.conn.getClient()
|
|
|
|
if err != nil {
|
2020-12-12 09:31:09 +00:00
|
|
|
return err
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
return client.Chown(name, uid, gid)
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Chmod changes the mode of the named file to mode.
|
|
|
|
func (fs *SFTPFs) Chmod(name string, mode os.FileMode) error {
|
2022-11-01 11:22:54 +00:00
|
|
|
client, err := fs.conn.getClient()
|
|
|
|
if err != nil {
|
2020-12-12 09:31:09 +00:00
|
|
|
return err
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
return client.Chmod(name, mode)
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Chtimes changes the access and modification times of the named file.
|
2023-03-22 18:02:54 +00:00
|
|
|
func (fs *SFTPFs) Chtimes(name string, atime, mtime time.Time, _ bool) error {
|
2022-11-01 11:22:54 +00:00
|
|
|
client, err := fs.conn.getClient()
|
|
|
|
if err != nil {
|
2020-12-12 09:31:09 +00:00
|
|
|
return err
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
return client.Chtimes(name, atime, mtime)
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Truncate changes the size of the named file.
|
|
|
|
func (fs *SFTPFs) Truncate(name string, size int64) error {
|
2022-11-01 11:22:54 +00:00
|
|
|
client, err := fs.conn.getClient()
|
|
|
|
if err != nil {
|
2020-12-12 09:31:09 +00:00
|
|
|
return err
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
return client.Truncate(name, size)
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// ReadDir reads the directory named by dirname and returns
|
|
|
|
// a list of directory entries.
|
2024-02-15 19:53:56 +00:00
|
|
|
func (fs *SFTPFs) ReadDir(dirname string) (DirLister, error) {
|
2022-11-01 11:22:54 +00:00
|
|
|
client, err := fs.conn.getClient()
|
|
|
|
if err != nil {
|
2020-12-12 09:31:09 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
2024-02-15 19:53:56 +00:00
|
|
|
files, err := client.ReadDir(dirname)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &baseDirLister{files}, nil
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
2021-04-03 14:00:55 +00:00
|
|
|
// IsUploadResumeSupported returns true if resuming uploads is supported.
|
|
|
|
func (fs *SFTPFs) IsUploadResumeSupported() bool {
|
|
|
|
return fs.config.BufferSize == 0
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
2023-10-22 14:09:30 +00:00
|
|
|
// IsConditionalUploadResumeSupported returns if resuming uploads is supported
|
|
|
|
// for the specified size
|
|
|
|
func (fs *SFTPFs) IsConditionalUploadResumeSupported(_ int64) bool {
|
|
|
|
return fs.IsUploadResumeSupported()
|
|
|
|
}
|
|
|
|
|
2020-12-12 09:31:09 +00:00
|
|
|
// IsAtomicUploadSupported returns true if atomic upload is supported.
|
2021-04-03 14:00:55 +00:00
|
|
|
func (fs *SFTPFs) IsAtomicUploadSupported() bool {
|
|
|
|
return fs.config.BufferSize == 0
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// IsNotExist returns a boolean indicating whether the error is known to
|
|
|
|
// report that a file or directory does not exist
|
|
|
|
func (*SFTPFs) IsNotExist(err error) bool {
|
2022-05-09 17:09:43 +00:00
|
|
|
return errors.Is(err, fs.ErrNotExist)
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// IsPermission returns a boolean indicating whether the error is known to
|
|
|
|
// report that permission is denied.
|
|
|
|
func (*SFTPFs) IsPermission(err error) bool {
|
2021-10-16 08:32:18 +00:00
|
|
|
if _, ok := err.(*pathResolutionError); ok {
|
|
|
|
return true
|
|
|
|
}
|
2022-05-09 17:09:43 +00:00
|
|
|
return errors.Is(err, fs.ErrPermission)
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// IsNotSupported returns true if the error indicate an unsupported operation
|
|
|
|
func (*SFTPFs) IsNotSupported(err error) bool {
|
|
|
|
if err == nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return err == ErrVfsUnsupported
|
|
|
|
}
|
|
|
|
|
|
|
|
// CheckRootPath creates the specified local root directory if it does not exists
|
|
|
|
func (fs *SFTPFs) CheckRootPath(username string, uid int, gid int) bool {
|
2022-07-21 16:42:22 +00:00
|
|
|
// local directory for temporary files in buffer mode
|
2023-05-16 16:08:14 +00:00
|
|
|
osFs := NewOsFs(fs.ConnectionID(), fs.localTempDir, "", nil)
|
2022-07-21 16:42:22 +00:00
|
|
|
osFs.CheckRootPath(username, uid, gid)
|
2021-03-27 18:10:27 +00:00
|
|
|
if fs.config.Prefix == "/" {
|
|
|
|
return true
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
client, err := fs.conn.getClient()
|
|
|
|
if err != nil {
|
2022-02-24 15:11:35 +00:00
|
|
|
return false
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
if err := client.MkdirAll(fs.config.Prefix); err != nil {
|
|
|
|
fsLog(fs, logger.LevelDebug, "error creating root directory %q for user %q: %v", fs.config.Prefix, username, err)
|
2021-03-27 18:10:27 +00:00
|
|
|
return false
|
|
|
|
}
|
2020-12-12 09:31:09 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// ScanRootDirContents returns the number of files contained in a directory and
|
|
|
|
// their size
|
|
|
|
func (fs *SFTPFs) ScanRootDirContents() (int, int64, error) {
|
|
|
|
return fs.GetDirSize(fs.config.Prefix)
|
|
|
|
}
|
|
|
|
|
2021-12-16 17:18:36 +00:00
|
|
|
// CheckMetadata checks the metadata consistency
|
|
|
|
func (*SFTPFs) CheckMetadata() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-12-12 09:31:09 +00:00
|
|
|
// GetAtomicUploadPath returns the path to use for an atomic upload
|
|
|
|
func (*SFTPFs) GetAtomicUploadPath(name string) string {
|
|
|
|
dir := path.Dir(name)
|
|
|
|
guid := xid.New().String()
|
|
|
|
return path.Join(dir, ".sftpgo-upload."+guid+"."+path.Base(name))
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetRelativePath returns the path for a file relative to the sftp prefix if any.
|
|
|
|
// This is the path as seen by SFTPGo users
|
|
|
|
func (fs *SFTPFs) GetRelativePath(name string) string {
|
|
|
|
rel := path.Clean(name)
|
|
|
|
if rel == "." {
|
|
|
|
rel = ""
|
|
|
|
}
|
|
|
|
if !path.IsAbs(rel) {
|
|
|
|
return "/" + rel
|
|
|
|
}
|
|
|
|
if fs.config.Prefix != "/" {
|
|
|
|
if !strings.HasPrefix(rel, fs.config.Prefix) {
|
|
|
|
rel = "/"
|
|
|
|
}
|
|
|
|
rel = path.Clean("/" + strings.TrimPrefix(rel, fs.config.Prefix))
|
|
|
|
}
|
2021-03-21 18:15:47 +00:00
|
|
|
if fs.mountPath != "" {
|
|
|
|
rel = path.Join(fs.mountPath, rel)
|
|
|
|
}
|
2020-12-12 09:31:09 +00:00
|
|
|
return rel
|
|
|
|
}
|
|
|
|
|
|
|
|
// Walk walks the file tree rooted at root, calling walkFn for each file or
|
|
|
|
// directory in the tree, including root
|
|
|
|
func (fs *SFTPFs) Walk(root string, walkFn filepath.WalkFunc) error {
|
2022-11-01 11:22:54 +00:00
|
|
|
client, err := fs.conn.getClient()
|
|
|
|
if err != nil {
|
2020-12-12 09:31:09 +00:00
|
|
|
return err
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
walker := client.Walk(root)
|
2020-12-12 09:31:09 +00:00
|
|
|
for walker.Step() {
|
|
|
|
err := walker.Err()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
err = walkFn(walker.Path(), walker.Stat(), err)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Join joins any number of path elements into a single path
|
|
|
|
func (*SFTPFs) Join(elem ...string) string {
|
|
|
|
return path.Join(elem...)
|
|
|
|
}
|
|
|
|
|
|
|
|
// HasVirtualFolders returns true if folders are emulated
|
|
|
|
func (*SFTPFs) HasVirtualFolders() bool {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// ResolvePath returns the matching filesystem path for the specified virtual path
|
|
|
|
func (fs *SFTPFs) ResolvePath(virtualPath string) (string, error) {
|
2021-03-21 18:15:47 +00:00
|
|
|
if fs.mountPath != "" {
|
|
|
|
virtualPath = strings.TrimPrefix(virtualPath, fs.mountPath)
|
|
|
|
}
|
2020-12-12 09:31:09 +00:00
|
|
|
if !path.IsAbs(virtualPath) {
|
|
|
|
virtualPath = path.Clean("/" + virtualPath)
|
|
|
|
}
|
|
|
|
fsPath := fs.Join(fs.config.Prefix, virtualPath)
|
|
|
|
if fs.config.Prefix != "/" && fsPath != "/" {
|
|
|
|
// we need to check if this path is a symlink outside the given prefix
|
|
|
|
// or a file/dir inside a dir symlinked outside the prefix
|
|
|
|
var validatedPath string
|
|
|
|
var err error
|
|
|
|
validatedPath, err = fs.getRealPath(fsPath)
|
2022-05-09 17:09:43 +00:00
|
|
|
isNotExist := fs.IsNotExist(err)
|
|
|
|
if err != nil && !isNotExist {
|
2023-02-27 18:02:43 +00:00
|
|
|
fsLog(fs, logger.LevelError, "Invalid path resolution, original path %v resolved %q err: %v",
|
2020-12-12 09:31:09 +00:00
|
|
|
virtualPath, fsPath, err)
|
|
|
|
return "", err
|
2022-05-09 17:09:43 +00:00
|
|
|
} else if isNotExist {
|
|
|
|
for fs.IsNotExist(err) {
|
2020-12-12 09:31:09 +00:00
|
|
|
validatedPath = path.Dir(validatedPath)
|
|
|
|
if validatedPath == "/" {
|
|
|
|
err = nil
|
|
|
|
break
|
|
|
|
}
|
|
|
|
validatedPath, err = fs.getRealPath(validatedPath)
|
|
|
|
}
|
|
|
|
if err != nil {
|
2023-02-27 18:02:43 +00:00
|
|
|
fsLog(fs, logger.LevelError, "Invalid path resolution, dir %q original path %q resolved %q err: %v",
|
2020-12-12 09:31:09 +00:00
|
|
|
validatedPath, virtualPath, fsPath, err)
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if err := fs.isSubDir(validatedPath); err != nil {
|
2023-02-27 18:02:43 +00:00
|
|
|
fsLog(fs, logger.LevelError, "Invalid path resolution, dir %q original path %q resolved %q err: %v",
|
2020-12-12 09:31:09 +00:00
|
|
|
validatedPath, virtualPath, fsPath, err)
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return fsPath, nil
|
|
|
|
}
|
|
|
|
|
2022-07-17 14:02:45 +00:00
|
|
|
// RealPath implements the FsRealPather interface
|
|
|
|
func (fs *SFTPFs) RealPath(p string) (string, error) {
|
2022-11-01 11:22:54 +00:00
|
|
|
client, err := fs.conn.getClient()
|
|
|
|
if err != nil {
|
2022-07-17 14:02:45 +00:00
|
|
|
return "", err
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
resolved, err := client.RealPath(p)
|
2022-07-17 14:02:45 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
if fs.config.Prefix != "/" {
|
|
|
|
if err := fs.isSubDir(resolved); err != nil {
|
|
|
|
fsLog(fs, logger.LevelError, "Invalid real path resolution, original path %q resolved %q err: %v",
|
|
|
|
p, resolved, err)
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return fs.GetRelativePath(resolved), nil
|
|
|
|
}
|
|
|
|
|
2020-12-12 09:31:09 +00:00
|
|
|
// getRealPath returns the real remote path trying to resolve symbolic links if any
|
|
|
|
func (fs *SFTPFs) getRealPath(name string) (string, error) {
|
2022-11-01 11:22:54 +00:00
|
|
|
client, err := fs.conn.getClient()
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2022-04-27 16:38:46 +00:00
|
|
|
linksWalked := 0
|
|
|
|
for {
|
2022-11-01 11:22:54 +00:00
|
|
|
info, err := client.Lstat(name)
|
2022-04-27 16:38:46 +00:00
|
|
|
if err != nil {
|
|
|
|
return name, err
|
|
|
|
}
|
|
|
|
if info.Mode()&os.ModeSymlink == 0 {
|
|
|
|
return name, nil
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
resolvedLink, err := client.ReadLink(name)
|
2022-04-27 16:38:46 +00:00
|
|
|
if err != nil {
|
2022-07-17 14:02:45 +00:00
|
|
|
return name, fmt.Errorf("unable to resolve link to %q: %w", name, err)
|
2022-04-27 16:38:46 +00:00
|
|
|
}
|
|
|
|
resolvedLink = path.Clean(resolvedLink)
|
|
|
|
if path.IsAbs(resolvedLink) {
|
|
|
|
name = resolvedLink
|
|
|
|
} else {
|
|
|
|
name = path.Join(path.Dir(name), resolvedLink)
|
|
|
|
}
|
|
|
|
linksWalked++
|
|
|
|
if linksWalked > 10 {
|
2022-07-17 14:02:45 +00:00
|
|
|
fsLog(fs, logger.LevelError, "unable to get real path, too many links: %d", linksWalked)
|
2022-04-27 16:38:46 +00:00
|
|
|
return "", &pathResolutionError{err: "too many links"}
|
|
|
|
}
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (fs *SFTPFs) isSubDir(name string) error {
|
|
|
|
if name == fs.config.Prefix {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if len(name) < len(fs.config.Prefix) {
|
2023-02-27 18:02:43 +00:00
|
|
|
err := fmt.Errorf("path %q is not inside: %q", name, fs.config.Prefix)
|
2021-10-16 08:32:18 +00:00
|
|
|
return &pathResolutionError{err: err.Error()}
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
if !strings.HasPrefix(name, fs.config.Prefix+"/") {
|
2023-02-27 18:02:43 +00:00
|
|
|
err := fmt.Errorf("path %q is not inside: %q", name, fs.config.Prefix)
|
2021-10-16 08:32:18 +00:00
|
|
|
return &pathResolutionError{err: err.Error()}
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetDirSize returns the number of files and the size for a folder
|
|
|
|
// including any subfolders
|
|
|
|
func (fs *SFTPFs) GetDirSize(dirname string) (int, int64, error) {
|
|
|
|
numFiles := 0
|
|
|
|
size := int64(0)
|
2022-11-01 11:22:54 +00:00
|
|
|
client, err := fs.conn.getClient()
|
|
|
|
if err != nil {
|
2020-12-12 09:31:09 +00:00
|
|
|
return numFiles, size, err
|
|
|
|
}
|
2022-08-16 15:59:13 +00:00
|
|
|
isDir, err := isDirectory(fs, dirname)
|
2020-12-12 09:31:09 +00:00
|
|
|
if err == nil && isDir {
|
2022-11-01 11:22:54 +00:00
|
|
|
walker := client.Walk(dirname)
|
2020-12-12 09:31:09 +00:00
|
|
|
for walker.Step() {
|
|
|
|
err := walker.Err()
|
|
|
|
if err != nil {
|
|
|
|
return numFiles, size, err
|
|
|
|
}
|
|
|
|
if walker.Stat().Mode().IsRegular() {
|
|
|
|
size += walker.Stat().Size()
|
|
|
|
numFiles++
|
2022-11-01 11:22:54 +00:00
|
|
|
if numFiles%1000 == 0 {
|
|
|
|
fsLog(fs, logger.LevelDebug, "dirname %q scan in progress, files: %d, size: %d", dirname, numFiles, size)
|
|
|
|
}
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return numFiles, size, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetMimeType returns the content type
|
|
|
|
func (fs *SFTPFs) GetMimeType(name string) (string, error) {
|
2022-11-01 11:22:54 +00:00
|
|
|
client, err := fs.conn.getClient()
|
|
|
|
if err != nil {
|
2020-12-12 09:31:09 +00:00
|
|
|
return "", err
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
f, err := client.OpenFile(name, os.O_RDONLY)
|
2020-12-12 09:31:09 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
var buf [512]byte
|
|
|
|
n, err := io.ReadFull(f, buf[:])
|
|
|
|
if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
ctype := http.DetectContentType(buf[:n])
|
|
|
|
// Rewind file.
|
|
|
|
_, err = f.Seek(0, io.SeekStart)
|
|
|
|
return ctype, err
|
|
|
|
}
|
|
|
|
|
2022-05-15 05:30:36 +00:00
|
|
|
// GetAvailableDiskSize returns the available size for the specified path
|
2021-02-11 18:45:52 +00:00
|
|
|
func (fs *SFTPFs) GetAvailableDiskSize(dirName string) (*sftp.StatVFS, error) {
|
2022-11-01 11:22:54 +00:00
|
|
|
client, err := fs.conn.getClient()
|
|
|
|
if err != nil {
|
2021-02-11 18:45:52 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
if _, ok := client.HasExtension("statvfs@openssh.com"); !ok {
|
2021-02-11 18:45:52 +00:00
|
|
|
return nil, ErrStorageSizeUnavailable
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
return client.StatVFS(dirName)
|
2021-02-11 18:45:52 +00:00
|
|
|
}
|
|
|
|
|
2020-12-12 09:31:09 +00:00
|
|
|
// Close the connection
|
|
|
|
func (fs *SFTPFs) Close() error {
|
2022-11-01 11:22:54 +00:00
|
|
|
fs.conn.RemoveSession(fs.connectionID)
|
|
|
|
return nil
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
2022-11-01 11:22:54 +00:00
|
|
|
func (fs *SFTPFs) createConnection() error {
|
|
|
|
err := fs.conn.OpenConnection()
|
|
|
|
if err != nil {
|
|
|
|
fsLog(fs, logger.LevelError, "error opening connection: %v", err)
|
|
|
|
return err
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
return nil
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
2022-11-01 11:22:54 +00:00
|
|
|
type sftpConnection struct {
|
|
|
|
config *SFTPFsConfig
|
|
|
|
logSender string
|
|
|
|
sshClient *ssh.Client
|
|
|
|
sftpClient *sftp.Client
|
|
|
|
mu sync.RWMutex
|
|
|
|
isConnected bool
|
|
|
|
sessions map[string]bool
|
|
|
|
lastActivity time.Time
|
|
|
|
}
|
|
|
|
|
|
|
|
func newSFTPConnection(config *SFTPFsConfig, sessionID string) *sftpConnection {
|
|
|
|
c := &sftpConnection{
|
|
|
|
config: config,
|
|
|
|
logSender: fmt.Sprintf(`%s "%s@%s"`, sftpFsName, config.Username, config.Endpoint),
|
|
|
|
isConnected: false,
|
|
|
|
sessions: map[string]bool{},
|
|
|
|
lastActivity: time.Now().UTC(),
|
|
|
|
}
|
|
|
|
c.sessions[sessionID] = true
|
|
|
|
return c
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *sftpConnection) OpenConnection() error {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
|
|
|
|
return c.openConnNoLock()
|
|
|
|
}
|
|
|
|
|
2024-04-27 10:03:38 +00:00
|
|
|
func (c *sftpConnection) getKeySigner() (ssh.Signer, error) {
|
|
|
|
privPayload := c.config.PrivateKey.GetPayload()
|
|
|
|
if privPayload == "" {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
if key := c.config.KeyPassphrase.GetPayload(); key != "" {
|
|
|
|
return ssh.ParsePrivateKeyWithPassphrase([]byte(privPayload), []byte(key))
|
|
|
|
}
|
|
|
|
return ssh.ParsePrivateKey([]byte(privPayload))
|
|
|
|
}
|
|
|
|
|
2022-11-01 11:22:54 +00:00
|
|
|
func (c *sftpConnection) openConnNoLock() error {
|
|
|
|
if c.isConnected {
|
|
|
|
logger.Debug(c.logSender, "", "reusing connection")
|
|
|
|
return nil
|
|
|
|
}
|
2020-12-23 16:15:55 +00:00
|
|
|
|
2022-11-01 11:22:54 +00:00
|
|
|
logger.Debug(c.logSender, "", "try to open a new connection")
|
2020-12-12 09:31:09 +00:00
|
|
|
clientConfig := &ssh.ClientConfig{
|
2022-11-01 11:22:54 +00:00
|
|
|
User: c.config.Username,
|
2022-07-19 21:28:33 +00:00
|
|
|
HostKeyCallback: func(_ string, _ net.Addr, key ssh.PublicKey) error {
|
2021-04-01 16:53:48 +00:00
|
|
|
fp := ssh.FingerprintSHA256(key)
|
2022-05-19 17:49:51 +00:00
|
|
|
if util.Contains(sftpFingerprints, fp) {
|
2022-10-12 16:12:12 +00:00
|
|
|
if allowSelfConnections == 0 {
|
2022-11-01 11:22:54 +00:00
|
|
|
logger.Log(logger.LevelError, c.logSender, "", "SFTP self connections not allowed")
|
2022-10-12 16:12:12 +00:00
|
|
|
return ErrSFTPLoop
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
if util.Contains(c.config.forbiddenSelfUsernames, c.config.Username) {
|
|
|
|
logger.Log(logger.LevelError, c.logSender, "",
|
|
|
|
"SFTP loop or nested local SFTP folders detected, username %q, forbidden usernames: %+v",
|
|
|
|
c.config.Username, c.config.forbiddenSelfUsernames)
|
2021-04-01 16:53:48 +00:00
|
|
|
return ErrSFTPLoop
|
|
|
|
}
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
if len(c.config.Fingerprints) > 0 {
|
|
|
|
for _, provided := range c.config.Fingerprints {
|
2020-12-12 09:31:09 +00:00
|
|
|
if provided == fp {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
return fmt.Errorf("invalid fingerprint %q", fp)
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
logger.Log(logger.LevelWarn, c.logSender, "", "login without host key validation, please provide at least a fingerprint!")
|
2020-12-12 09:31:09 +00:00
|
|
|
return nil
|
|
|
|
},
|
2024-04-27 10:03:38 +00:00
|
|
|
Timeout: 15 * time.Second,
|
2024-05-01 17:42:09 +00:00
|
|
|
ClientVersion: fmt.Sprintf("SSH-2.0-%s", version.GetServerVersion("_", false)),
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
2024-04-27 10:03:38 +00:00
|
|
|
signer, err := c.getKeySigner()
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("sftpfs: unable to parse the private key: %w", err)
|
|
|
|
}
|
|
|
|
if signer != nil {
|
|
|
|
clientConfig.Auth = append(clientConfig.Auth, ssh.PublicKeys(signer))
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
2024-04-27 10:03:38 +00:00
|
|
|
if pwd := c.config.Password.GetPayload(); pwd != "" {
|
|
|
|
clientConfig.Auth = append(clientConfig.Auth, ssh.Password(pwd))
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
2024-02-24 19:35:09 +00:00
|
|
|
supportedAlgos := ssh.SupportedAlgorithms()
|
|
|
|
insecureAlgos := ssh.InsecureAlgorithms()
|
|
|
|
// add all available ciphers, KEXs and MACs, they are negotiated according to the order
|
|
|
|
clientConfig.Ciphers = append(supportedAlgos.Ciphers, ssh.InsecureCipherAES128CBC,
|
|
|
|
ssh.InsecureCipherAES192CBC, ssh.InsecureCipherAES256CBC)
|
|
|
|
clientConfig.KeyExchanges = append(supportedAlgos.KeyExchanges, insecureAlgos.KeyExchanges...)
|
|
|
|
clientConfig.MACs = append(supportedAlgos.MACs, insecureAlgos.MACs...)
|
2022-11-01 11:22:54 +00:00
|
|
|
sshClient, err := ssh.Dial("tcp", c.config.Endpoint, clientConfig)
|
2020-12-12 09:31:09 +00:00
|
|
|
if err != nil {
|
2022-11-01 11:22:54 +00:00
|
|
|
return fmt.Errorf("sftpfs: unable to connect: %w", err)
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
sftpClient, err := sftp.NewClient(sshClient, c.getClientOptions()...)
|
2020-12-12 09:31:09 +00:00
|
|
|
if err != nil {
|
2022-11-01 11:22:54 +00:00
|
|
|
sshClient.Close()
|
|
|
|
return fmt.Errorf("sftpfs: unable to create SFTP client: %w", err)
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
c.sshClient = sshClient
|
|
|
|
c.sftpClient = sftpClient
|
|
|
|
c.isConnected = true
|
|
|
|
go c.Wait()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *sftpConnection) getClientOptions() []sftp.ClientOption {
|
|
|
|
var options []sftp.ClientOption
|
|
|
|
if c.config.DisableCouncurrentReads {
|
|
|
|
options = append(options, sftp.UseConcurrentReads(false))
|
|
|
|
logger.Debug(c.logSender, "", "disabling concurrent reads")
|
2021-03-06 14:41:40 +00:00
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
if c.config.BufferSize > 0 {
|
|
|
|
options = append(options, sftp.UseConcurrentWrites(true))
|
|
|
|
logger.Debug(c.logSender, "", "enabling concurrent writes")
|
2021-04-03 14:00:55 +00:00
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
return options
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
|
2022-11-01 11:22:54 +00:00
|
|
|
func (c *sftpConnection) getClient() (*sftp.Client, error) {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
|
|
|
|
if c.isConnected {
|
|
|
|
return c.sftpClient, nil
|
|
|
|
}
|
|
|
|
err := c.openConnNoLock()
|
|
|
|
return c.sftpClient, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *sftpConnection) Wait() {
|
2022-11-04 19:25:01 +00:00
|
|
|
done := make(chan struct{})
|
2022-11-01 11:22:54 +00:00
|
|
|
|
|
|
|
go func() {
|
|
|
|
var watchdogInProgress atomic.Bool
|
2022-11-04 19:25:01 +00:00
|
|
|
ticker := time.NewTicker(30 * time.Second)
|
|
|
|
defer ticker.Stop()
|
|
|
|
|
2022-11-01 11:22:54 +00:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ticker.C:
|
|
|
|
if watchdogInProgress.Load() {
|
|
|
|
logger.Error(c.logSender, "", "watchdog still in progress, closing hanging connection")
|
|
|
|
c.sshClient.Close()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
go func() {
|
|
|
|
watchdogInProgress.Store(true)
|
|
|
|
defer watchdogInProgress.Store(false)
|
|
|
|
|
|
|
|
_, err := c.sftpClient.Getwd()
|
|
|
|
if err != nil {
|
|
|
|
logger.Error(c.logSender, "", "watchdog error: %v", err)
|
|
|
|
}
|
|
|
|
}()
|
2022-11-04 19:25:01 +00:00
|
|
|
case <-done:
|
2022-11-01 11:22:54 +00:00
|
|
|
logger.Debug(c.logSender, "", "quitting watchdog")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2020-12-12 09:31:09 +00:00
|
|
|
// we wait on the sftp client otherwise if the channel is closed but not the connection
|
|
|
|
// we don't detect the event.
|
2022-11-01 11:22:54 +00:00
|
|
|
err := c.sftpClient.Wait()
|
|
|
|
logger.Log(logger.LevelDebug, c.logSender, "", "sftp channel closed: %v", err)
|
2022-11-04 19:25:01 +00:00
|
|
|
close(done)
|
2020-12-23 16:15:55 +00:00
|
|
|
|
2022-11-01 11:22:54 +00:00
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
2020-12-23 16:15:55 +00:00
|
|
|
|
2022-11-01 11:22:54 +00:00
|
|
|
c.isConnected = false
|
|
|
|
if c.sshClient != nil {
|
|
|
|
c.sshClient.Close()
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-01 11:22:54 +00:00
|
|
|
func (c *sftpConnection) Close() error {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
|
|
|
|
logger.Debug(c.logSender, "", "closing connection")
|
|
|
|
var sftpErr, sshErr error
|
|
|
|
if c.sftpClient != nil {
|
|
|
|
sftpErr = c.sftpClient.Close()
|
|
|
|
}
|
|
|
|
if c.sshClient != nil {
|
|
|
|
sshErr = c.sshClient.Close()
|
|
|
|
}
|
|
|
|
if sftpErr != nil {
|
|
|
|
return sftpErr
|
|
|
|
}
|
|
|
|
c.isConnected = false
|
|
|
|
return sshErr
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *sftpConnection) AddSession(sessionID string) {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
|
|
|
|
c.sessions[sessionID] = true
|
|
|
|
logger.Debug(c.logSender, "", "added session %s, active sessions: %d", sessionID, len(c.sessions))
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *sftpConnection) RemoveSession(sessionID string) {
|
|
|
|
c.mu.Lock()
|
|
|
|
defer c.mu.Unlock()
|
|
|
|
|
|
|
|
delete(c.sessions, sessionID)
|
|
|
|
logger.Debug(c.logSender, "", "removed session %s, active sessions: %d", sessionID, len(c.sessions))
|
|
|
|
if len(c.sessions) == 0 {
|
|
|
|
c.lastActivity = time.Now().UTC()
|
2020-12-12 09:31:09 +00:00
|
|
|
}
|
|
|
|
}
|
2022-11-01 11:22:54 +00:00
|
|
|
|
|
|
|
func (c *sftpConnection) ActiveSessions() int {
|
|
|
|
c.mu.RLock()
|
|
|
|
defer c.mu.RUnlock()
|
|
|
|
|
|
|
|
return len(c.sessions)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *sftpConnection) GetLastActivity() time.Time {
|
|
|
|
c.mu.RLock()
|
|
|
|
defer c.mu.RUnlock()
|
|
|
|
|
|
|
|
if len(c.sessions) > 0 {
|
|
|
|
return time.Now().UTC()
|
|
|
|
}
|
|
|
|
logger.Debug(c.logSender, "", "last activity %s", c.lastActivity)
|
|
|
|
return c.lastActivity
|
|
|
|
}
|
|
|
|
|
|
|
|
type sftpConnectionsCache struct {
|
|
|
|
scheduler *cron.Cron
|
|
|
|
sync.RWMutex
|
|
|
|
items map[uint64]*sftpConnection
|
|
|
|
}
|
|
|
|
|
|
|
|
func newSFTPConnectionCache() *sftpConnectionsCache {
|
|
|
|
c := &sftpConnectionsCache{
|
2023-02-21 17:18:24 +00:00
|
|
|
scheduler: cron.New(cron.WithLocation(time.UTC), cron.WithLogger(cron.DiscardLogger)),
|
2022-11-01 11:22:54 +00:00
|
|
|
items: make(map[uint64]*sftpConnection),
|
|
|
|
}
|
|
|
|
_, err := c.scheduler.AddFunc("@every 1m", c.Cleanup)
|
|
|
|
util.PanicOnError(err)
|
|
|
|
c.scheduler.Start()
|
|
|
|
return c
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *sftpConnectionsCache) Get(config *SFTPFsConfig, sessionID string) *sftpConnection {
|
|
|
|
partition := 0
|
|
|
|
key := config.getUniqueID(partition)
|
|
|
|
|
|
|
|
c.Lock()
|
|
|
|
defer c.Unlock()
|
|
|
|
|
|
|
|
var oldKey uint64
|
|
|
|
for {
|
|
|
|
if val, ok := c.items[key]; ok {
|
|
|
|
activeSessions := val.ActiveSessions()
|
|
|
|
if activeSessions < maxSessionsPerConnection || key == oldKey {
|
|
|
|
logger.Debug(logSenderSFTPCache, "",
|
|
|
|
"reusing connection for session ID %q, key: %d, active sessions %d, active connections: %d",
|
|
|
|
sessionID, key, activeSessions+1, len(c.items))
|
|
|
|
val.AddSession(sessionID)
|
|
|
|
return val
|
|
|
|
}
|
|
|
|
partition++
|
|
|
|
oldKey = key
|
|
|
|
key = config.getUniqueID(partition)
|
|
|
|
logger.Debug(logSenderSFTPCache, "",
|
|
|
|
"connection full, generated new key for partition: %d, active sessions: %d, key: %d, old key: %d",
|
|
|
|
partition, activeSessions, oldKey, key)
|
|
|
|
} else {
|
|
|
|
conn := newSFTPConnection(config, sessionID)
|
|
|
|
c.items[key] = conn
|
|
|
|
logger.Debug(logSenderSFTPCache, "",
|
|
|
|
"adding new connection for session ID %q, partition: %d, key: %d, active connections: %d",
|
|
|
|
sessionID, partition, key, len(c.items))
|
|
|
|
return conn
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *sftpConnectionsCache) Remove(key uint64) {
|
|
|
|
c.Lock()
|
|
|
|
defer c.Unlock()
|
|
|
|
|
|
|
|
if conn, ok := c.items[key]; ok {
|
|
|
|
delete(c.items, key)
|
|
|
|
logger.Debug(logSenderSFTPCache, "", "removed connection with key %d, active connections: %d", key, len(c.items))
|
|
|
|
|
|
|
|
defer conn.Close()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *sftpConnectionsCache) Cleanup() {
|
|
|
|
c.RLock()
|
|
|
|
|
|
|
|
for k, conn := range c.items {
|
|
|
|
if val := conn.GetLastActivity(); val.Before(time.Now().Add(-30 * time.Second)) {
|
|
|
|
logger.Debug(conn.logSender, "", "removing inactive connection, last activity %s", val)
|
|
|
|
|
|
|
|
defer func(key uint64) {
|
|
|
|
c.Remove(key)
|
|
|
|
}(k)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
c.RUnlock()
|
|
|
|
}
|