| 1 |
package desync |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"io" |
| 7 |
"math/rand" |
| 8 |
"net/url" |
| 9 |
"os" |
| 10 |
"os/exec" |
| 11 |
"path/filepath" |
| 12 |
"strconv" |
| 13 |
"strings" |
| 14 |
|
| 15 |
"path" |
| 16 |
|
| 17 |
"github.com/pkg/errors" |
| 18 |
"github.com/pkg/sftp" |
| 19 |
) |
| 20 |
|
| 21 |
var _ WriteStore = &SFTPStore{} |
| 22 |
|
| 23 |
// SFTPStoreBase is the base object for SFTP chunk and index stores. |
| 24 |
type SFTPStoreBase struct { |
| 25 |
location *url.URL |
| 26 |
path string |
| 27 |
client *sftp.Client |
| 28 |
cancel context.CancelFunc |
| 29 |
opt StoreOptions |
| 30 |
extension string |
| 31 |
} |
| 32 |
|
| 33 |
// SFTPStore is a chunk store that uses SFTP over SSH. |
| 34 |
type SFTPStore struct { |
| 35 |
pool chan *SFTPStoreBase |
| 36 |
location *url.URL |
| 37 |
n int |
| 38 |
converters Converters |
| 39 |
} |
| 40 |
|
| 41 |
// Creates a base sftp client. The extension is the chunk file extension |
| 42 |
// derived from the caller's converters, or empty for index stores which |
| 43 |
// don't use converters. |
| 44 |
func newSFTPStoreBase(location *url.URL, opt StoreOptions, extension string) (*SFTPStoreBase, error) { |
| 45 |
sshCmd := os.Getenv("CASYNC_SSH_PATH") |
| 46 |
if sshCmd == "" { |
| 47 |
sshCmd = "ssh" |
| 48 |
} |
| 49 |
host := location.Host |
| 50 |
path := location.Path |
| 51 |
if !strings.HasSuffix(path, "/") { |
| 52 |
path += "/" |
| 53 |
} |
| 54 |
// If a username was given in the URL, prefix the host |
| 55 |
if location.User != nil { |
| 56 |
host = location.User.Username() + "@" + location.Host |
| 57 |
} |
| 58 |
// Reject destinations that ssh would parse as command-line options. |
| 59 |
if err := validateSSHHost(host); err != nil { |
| 60 |
return nil, err |
| 61 |
} |
| 62 |
ctx, cancel := context.WithCancel(context.Background()) |
| 63 |
// "--" terminates option parsing so the destination can't be read as a flag. |
| 64 |
c := exec.CommandContext(ctx, sshCmd, "-s", "--", host, "sftp") |
| 65 |
c.Stderr = os.Stderr |
| 66 |
r, err := c.StdoutPipe() |
| 67 |
if err != nil { |
| 68 |
cancel() |
| 69 |
return nil, err |
| 70 |
} |
| 71 |
w, err := c.StdinPipe() |
| 72 |
if err != nil { |
| 73 |
cancel() |
| 74 |
return nil, err |
| 75 |
} |
| 76 |
if err = c.Start(); err != nil { |
| 77 |
cancel() |
| 78 |
return nil, err |
| 79 |
} |
| 80 |
client, err := sftp.NewClientPipe(r, w) |
| 81 |
if err != nil { |
| 82 |
cancel() |
| 83 |
return nil, err |
| 84 |
} |
| 85 |
// The stat has really two jobs. Confirm that the path actually exists on the |
| 86 |
// server, and also make sure the handshake has happened successfully. SSH |
| 87 |
// may fail if multiple instances access the SSH agent concurrently. |
| 88 |
if _, err = client.Stat(path); err != nil { |
| 89 |
cancel() |
| 90 |
return nil, errors.Wrapf(err, "failed to stat '%s'", path) |
| 91 |
} |
| 92 |
return &SFTPStoreBase{location, path, client, cancel, opt, extension}, nil |
| 93 |
} |
| 94 |
|
| 95 |
// StoreObject adds a new object to a writable index or chunk store. |
| 96 |
func (s *SFTPStoreBase) StoreObject(name string, r io.Reader) error { |
| 97 |
// Write to a tempfile on the remote server. This is not 100% guaranteed to not |
| 98 |
// conflict between goroutines, there's no tempfile() function for remote servers. |
| 99 |
// Use a large enough random number instead to build a tempfile |
| 100 |
tmpfile := name + strconv.Itoa(rand.Int()) |
| 101 |
d := path.Dir(name) |
| 102 |
var errCount int |
| 103 |
retry: |
| 104 |
f, err := s.client.Create(tmpfile) |
| 105 |
if err != nil { |
| 106 |
// It's possible the parent dir doesn't yet exist. Create it while ignoring |
| 107 |
// errors since that could be racy and fail if another goroutine does the |
| 108 |
// same. |
| 109 |
if errCount < 1 { |
| 110 |
s.client.Mkdir(d) |
| 111 |
errCount++ |
| 112 |
goto retry |
| 113 |
} |
| 114 |
return errors.Wrap(err, "sftp:create "+tmpfile) |
| 115 |
} |
| 116 |
|
| 117 |
if _, err := io.Copy(f, r); err != nil { |
| 118 |
s.client.Remove(tmpfile) |
| 119 |
return errors.Wrap(err, "sftp:copying chunk data to "+tmpfile) |
| 120 |
} |
| 121 |
if err = f.Close(); err != nil { |
| 122 |
return errors.Wrap(err, "sftp:closing "+tmpfile) |
| 123 |
} |
| 124 |
return errors.Wrap(s.client.PosixRename(tmpfile, name), "sftp:renaming "+tmpfile+" to "+name) |
| 125 |
} |
| 126 |
|
| 127 |
// Close terminates all client connections |
| 128 |
func (s *SFTPStoreBase) Close() error { |
| 129 |
if s.cancel != nil { |
| 130 |
defer s.cancel() |
| 131 |
} |
| 132 |
return s.client.Close() |
| 133 |
} |
| 134 |
|
| 135 |
func (s *SFTPStoreBase) String() string { |
| 136 |
return s.location.String() |
| 137 |
} |
| 138 |
|
| 139 |
// Returns the path for a chunk |
| 140 |
func (s *SFTPStoreBase) nameFromID(id ChunkID) string { |
| 141 |
sID := id.String() |
| 142 |
name := s.path + sID[0:4] + "/" + sID + s.extension |
| 143 |
return name |
| 144 |
} |
| 145 |
|
| 146 |
// NewSFTPStore initializes a chunk store using SFTP over SSH. |
| 147 |
func NewSFTPStore(location *url.URL, opt StoreOptions) (*SFTPStore, error) { |
| 148 |
converters, err := opt.StorageConverters() |
| 149 |
if err != nil { |
| 150 |
return nil, err |
| 151 |
} |
| 152 |
extension := converters.storageExtension() |
| 153 |
s := &SFTPStore{make(chan *SFTPStoreBase, opt.N), location, opt.N, converters} |
| 154 |
for i := 0; i < opt.N; i++ { |
| 155 |
c, err := newSFTPStoreBase(location, opt, extension) |
| 156 |
if err != nil { |
| 157 |
return nil, err |
| 158 |
} |
| 159 |
s.pool <- c |
| 160 |
} |
| 161 |
return s, nil |
| 162 |
} |
| 163 |
|
| 164 |
// GetChunk returns a chunk from an SFTP store, returns ChunkMissing if the file does not exist |
| 165 |
func (s *SFTPStore) GetChunk(id ChunkID) (*Chunk, error) { |
| 166 |
c := <-s.pool |
| 167 |
defer func() { s.pool <- c }() |
| 168 |
name := c.nameFromID(id) |
| 169 |
f, err := c.client.Open(name) |
| 170 |
if err != nil { |
| 171 |
if os.IsNotExist(err) { |
| 172 |
err = ChunkMissing{id} |
| 173 |
} |
| 174 |
return nil, err |
| 175 |
} |
| 176 |
defer f.Close() |
| 177 |
b, err := io.ReadAll(f) |
| 178 |
if err != nil { |
| 179 |
return nil, errors.Wrapf(err, "unable to read from %s", name) |
| 180 |
} |
| 181 |
return NewChunkFromStorage(id, b, s.converters, c.opt.SkipVerify) |
| 182 |
} |
| 183 |
|
| 184 |
// RemoveChunk deletes a chunk, typically an invalid one, from the filesystem. |
| 185 |
// Used when verifying and repairing caches. |
| 186 |
func (s *SFTPStore) RemoveChunk(id ChunkID) error { |
| 187 |
c := <-s.pool |
| 188 |
defer func() { s.pool <- c }() |
| 189 |
return c.removeChunk(id) |
| 190 |
} |
| 191 |
|
| 192 |
// removeChunk deletes a chunk over this connection. Returns ChunkMissing if |
| 193 |
// the chunk is not in the store. |
| 194 |
func (s *SFTPStoreBase) removeChunk(id ChunkID) error { |
| 195 |
name := s.nameFromID(id) |
| 196 |
if _, err := s.client.Stat(name); err != nil { |
| 197 |
if os.IsNotExist(err) { |
| 198 |
return ChunkMissing{id} |
| 199 |
} |
| 200 |
return err |
| 201 |
} |
| 202 |
return s.client.Remove(name) |
| 203 |
} |
| 204 |
|
| 205 |
// StoreChunk adds a new chunk to the store |
| 206 |
func (s *SFTPStore) StoreChunk(chunk *Chunk) error { |
| 207 |
c := <-s.pool |
| 208 |
defer func() { s.pool <- c }() |
| 209 |
name := c.nameFromID(chunk.ID()) |
| 210 |
b, err := chunk.Storage(s.converters) |
| 211 |
if err != nil { |
| 212 |
return err |
| 213 |
} |
| 214 |
|
| 215 |
return c.StoreObject(name, bytes.NewReader(b)) |
| 216 |
} |
| 217 |
|
| 218 |
// HasChunk returns true if the chunk is in the store |
| 219 |
func (s *SFTPStore) HasChunk(id ChunkID) (bool, error) { |
| 220 |
c := <-s.pool |
| 221 |
defer func() { s.pool <- c }() |
| 222 |
name := c.nameFromID(id) |
| 223 |
_, err := c.client.Stat(name) |
| 224 |
return err == nil, nil |
| 225 |
} |
| 226 |
|
| 227 |
// Prune removes any chunks from the store that are not contained in a list |
| 228 |
// of chunks |
| 229 |
func (s *SFTPStore) Prune(ctx context.Context, ids map[ChunkID]struct{}) error { |
| 230 |
c := <-s.pool |
| 231 |
defer func() { s.pool <- c }() |
| 232 |
walker := c.client.Walk(c.path) |
| 233 |
|
| 234 |
for walker.Step() { |
| 235 |
// See if we're meant to stop |
| 236 |
select { |
| 237 |
case <-ctx.Done(): |
| 238 |
return Interrupted{} |
| 239 |
default: |
| 240 |
} |
| 241 |
if err := walker.Err(); err != nil { |
| 242 |
return err |
| 243 |
} |
| 244 |
info := walker.Stat() |
| 245 |
if info.IsDir() { // Skip dirs |
| 246 |
continue |
| 247 |
} |
| 248 |
// Skip files that aren't chunks matching the store's extension, they |
| 249 |
// may use different compression or encryption settings |
| 250 |
id, ok := chunkIDFromFilename(filepath.Base(walker.Path()), c.extension) |
| 251 |
if !ok { |
| 252 |
continue |
| 253 |
} |
| 254 |
// See if the chunk we're looking at is in the list we want to keep, if |
| 255 |
// not remove it. Use the connection this iteration already holds, |
| 256 |
// RemoveChunk would wait for another one from the pool, forever if |
| 257 |
// the pool size is 1. |
| 258 |
if _, ok := ids[id]; !ok { |
| 259 |
if err := c.removeChunk(id); err != nil { |
| 260 |
return err |
| 261 |
} |
| 262 |
} |
| 263 |
} |
| 264 |
return nil |
| 265 |
} |
| 266 |
|
| 267 |
// Close terminates all client connections |
| 268 |
func (s *SFTPStore) Close() error { |
| 269 |
var err error |
| 270 |
for i := 0; i < s.n; i++ { |
| 271 |
c := <-s.pool |
| 272 |
err = c.Close() |
| 273 |
} |
| 274 |
return err |
| 275 |
} |
| 276 |
|
| 277 |
func (s *SFTPStore) String() string { |
| 278 |
return s.location.String() |
| 279 |
} |