taildrop: implement asynchronous file deletion (#9844)

File resumption requires keeping partial files around for some time,
but we must still eventually delete them if never resumed.
Thus, we implement asynchronous file deletion, which could
spawn a background goroutine to delete the files.

We also use the same mechanism for deleting files on Windows,
where a file can't be deleted if there is still an open file handle.
We can enqueue those with the asynchronous file deleter as well.

Updates tailscale/corp#14772

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
pull/9859/head
Joe Tsai 1 year ago committed by GitHub
parent 33bb2bbfe9
commit c2a551469c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -646,6 +646,9 @@ func (b *LocalBackend) Shutdown() {
if b.sockstatLogger != nil { if b.sockstatLogger != nil {
b.sockstatLogger.Shutdown() b.sockstatLogger.Shutdown()
} }
if b.peerAPIServer != nil {
b.peerAPIServer.taildrop.Shutdown()
}
b.unregisterNetMon() b.unregisterNetMon()
b.unregisterHealthWatch() b.unregisterHealthWatch()
@ -3614,14 +3617,14 @@ func (b *LocalBackend) initPeerAPIListener() {
ps := &peerAPIServer{ ps := &peerAPIServer{
b: b, b: b,
taildrop: &taildrop.Manager{ taildrop: taildrop.ManagerOptions{
Logf: b.logf, Logf: b.logf,
Clock: tstime.DefaultClock{b.clock}, Clock: tstime.DefaultClock{Clock: b.clock},
Dir: fileRoot, Dir: fileRoot,
DirectFileMode: b.directFileRoot != "", DirectFileMode: b.directFileRoot != "",
AvoidFinalRename: !b.directFileDoFinalRename, AvoidFinalRename: !b.directFileDoFinalRename,
SendFileNotify: b.sendFileNotify, SendFileNotify: b.sendFileNotify,
}, }.New(),
} }
if dm, ok := b.sys.DNSManager.GetOK(); ok { if dm, ok := b.sys.DNSManager.GetOK(); ok {
ps.resolver = dm.Resolver() ps.resolver = dm.Resolver()

@ -68,7 +68,7 @@ func bodyNotContains(sub string) check {
func fileHasSize(name string, size int) check { func fileHasSize(name string, size int) check {
return func(t *testing.T, e *peerAPITestEnv) { return func(t *testing.T, e *peerAPITestEnv) {
root := e.ph.ps.taildrop.Dir root := e.ph.ps.taildrop.Dir()
if root == "" { if root == "" {
t.Errorf("no rootdir; can't check whether %q has size %v", name, size) t.Errorf("no rootdir; can't check whether %q has size %v", name, size)
return return
@ -84,7 +84,7 @@ func fileHasSize(name string, size int) check {
func fileHasContents(name string, want string) check { func fileHasContents(name string, want string) check {
return func(t *testing.T, e *peerAPITestEnv) { return func(t *testing.T, e *peerAPITestEnv) {
root := e.ph.ps.taildrop.Dir root := e.ph.ps.taildrop.Dir()
if root == "" { if root == "" {
t.Errorf("no rootdir; can't check contents of %q", name) t.Errorf("no rootdir; can't check contents of %q", name)
return return
@ -540,12 +540,12 @@ func TestHandlePeerAPI(t *testing.T) {
if !tt.omitRoot { if !tt.omitRoot {
rootDir = t.TempDir() rootDir = t.TempDir()
if e.ph.ps.taildrop == nil { if e.ph.ps.taildrop == nil {
e.ph.ps.taildrop = &taildrop.Manager{ e.ph.ps.taildrop = taildrop.ManagerOptions{
Logf: e.logBuf.Logf, Logf: e.logBuf.Logf,
Dir: rootDir,
}.New()
} }
} }
e.ph.ps.taildrop.Dir = rootDir
}
for _, req := range tt.reqs { for _, req := range tt.reqs {
e.rr = httptest.NewRecorder() e.rr = httptest.NewRecorder()
if req.Host == "example.com" { if req.Host == "example.com" {
@ -583,10 +583,10 @@ func TestFileDeleteRace(t *testing.T) {
capFileSharing: true, capFileSharing: true,
clock: &tstest.Clock{}, clock: &tstest.Clock{},
}, },
taildrop: &taildrop.Manager{ taildrop: taildrop.ManagerOptions{
Logf: t.Logf, Logf: t.Logf,
Dir: dir, Dir: dir,
}, }.New(),
} }
ph := &peerAPIHandler{ ph := &peerAPIHandler{
isSelf: true, isSelf: true,

@ -0,0 +1,182 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package taildrop
import (
"container/list"
"context"
"io/fs"
"os"
"path/filepath"
"strings"
"sync"
"time"
"tailscale.com/syncs"
"tailscale.com/tstime"
"tailscale.com/types/logger"
)
// deleteDelay is the amount of time to wait before we delete a file.
// A shorter value ensures timely deletion of deleted and partial files, while
// a longer value provides more opportunity for partial files to be resumed.
const deleteDelay = time.Hour
// fileDeleter manages asynchronous deletion of files after deleteDelay.
type fileDeleter struct {
logf logger.Logf
clock tstime.DefaultClock
event func(string) // called for certain events; for testing only
dir string
mu sync.Mutex
queue list.List
byName map[string]*list.Element
emptySignal chan struct{} // signal that the queue is empty
group syncs.WaitGroup
shutdownCtx context.Context
shutdown context.CancelFunc
}
// deleteFile is a specific file to delete after deleteDelay.
type deleteFile struct {
name string
inserted time.Time
}
func (d *fileDeleter) Init(logf logger.Logf, clock tstime.DefaultClock, event func(string), dir string) {
d.logf = logf
d.clock = clock
d.dir = dir
d.event = event
// From a cold-start, load the list of partial and deleted files.
d.byName = make(map[string]*list.Element)
d.emptySignal = make(chan struct{})
d.shutdownCtx, d.shutdown = context.WithCancel(context.Background())
d.group.Go(func() {
d.event("start init")
defer d.event("end init")
rangeDir(dir, func(de fs.DirEntry) bool {
switch {
case d.shutdownCtx.Err() != nil:
return false // terminate early
case !de.Type().IsRegular():
return true
case strings.Contains(de.Name(), partialSuffix):
d.Insert(de.Name())
case strings.Contains(de.Name(), deletedSuffix):
// Best-effort immediate deletion of deleted files.
name := strings.TrimSuffix(de.Name(), deletedSuffix)
if os.Remove(filepath.Join(dir, name)) == nil {
if os.Remove(filepath.Join(dir, de.Name())) == nil {
break
}
}
// Otherwise, enqueue the file for later deletion.
d.Insert(de.Name())
}
return true
})
})
}
// Insert enqueues baseName for eventual deletion.
func (d *fileDeleter) Insert(baseName string) {
d.mu.Lock()
defer d.mu.Unlock()
if d.shutdownCtx.Err() != nil {
return
}
if _, ok := d.byName[baseName]; ok {
return // already queued for deletion
}
d.byName[baseName] = d.queue.PushBack(&deleteFile{baseName, d.clock.Now()})
if d.queue.Len() == 1 {
d.group.Go(func() { d.waitAndDelete(deleteDelay) })
}
}
// waitAndDelete is an asynchronous deletion goroutine.
// At most one waitAndDelete routine is ever running at a time.
// It is not started unless there is at least one file in the queue.
func (d *fileDeleter) waitAndDelete(wait time.Duration) {
tc, ch := d.clock.NewTimer(wait)
defer tc.Stop() // cleanup the timer resource if we stop early
d.event("start waitAndDelete")
defer d.event("end waitAndDelete")
select {
case <-d.shutdownCtx.Done():
case <-d.emptySignal:
case now := <-ch:
d.mu.Lock()
defer d.mu.Unlock()
// Iterate over all files to delete, and delete anything old enough.
var next *list.Element
var failed []*list.Element
for elem := d.queue.Front(); elem != nil; elem = next {
next = elem.Next()
file := elem.Value.(*deleteFile)
if now.Sub(file.inserted) < deleteDelay {
break // everything after this is recently inserted
}
// Delete the expired file.
if name, ok := strings.CutSuffix(file.name, deletedSuffix); ok {
if err := os.Remove(filepath.Join(d.dir, name)); err != nil && !os.IsNotExist(err) {
d.logf("could not delete: %v", redactError(err))
failed = append(failed, elem)
continue
}
}
if err := os.Remove(filepath.Join(d.dir, file.name)); err != nil && !os.IsNotExist(err) {
d.logf("could not delete: %v", redactError(err))
failed = append(failed, elem)
continue
}
d.queue.Remove(elem)
delete(d.byName, file.name)
d.event("deleted " + file.name)
}
for _, elem := range failed {
elem.Value.(*deleteFile).inserted = now // retry after deleteDelay
d.queue.MoveToBack(elem)
}
// If there are still some files to delete, retry again later.
if d.queue.Len() > 0 {
file := d.queue.Front().Value.(*deleteFile)
retryAfter := deleteDelay - now.Sub(file.inserted)
d.group.Go(func() { d.waitAndDelete(retryAfter) })
}
}
}
// Remove dequeues baseName from eventual deletion.
func (d *fileDeleter) Remove(baseName string) {
d.mu.Lock()
defer d.mu.Unlock()
if elem := d.byName[baseName]; elem != nil {
d.queue.Remove(elem)
delete(d.byName, baseName)
// Signal to terminate any waitAndDelete goroutines.
if d.queue.Len() == 0 {
select {
case <-d.shutdownCtx.Done():
case d.emptySignal <- struct{}{}:
}
}
}
}
// Shutdown shuts down the deleter.
// It blocks until all goroutines are stopped.
func (d *fileDeleter) Shutdown() {
d.mu.Lock() // acquire lock to ensure no new goroutines start after shutdown
d.shutdown()
d.mu.Unlock()
d.group.Wait()
}

@ -0,0 +1,132 @@
// Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package taildrop
import (
"os"
"path/filepath"
"slices"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"tailscale.com/tstest"
"tailscale.com/tstime"
"tailscale.com/util/must"
)
func TestDeleter(t *testing.T) {
dir := t.TempDir()
must.Do(touchFile(filepath.Join(dir, "foo.partial")))
must.Do(touchFile(filepath.Join(dir, "bar.partial")))
must.Do(touchFile(filepath.Join(dir, "fizz")))
must.Do(touchFile(filepath.Join(dir, "fizz.deleted")))
must.Do(touchFile(filepath.Join(dir, "buzz.deleted"))) // lacks a matching "buzz" file
checkDirectory := func(want ...string) {
t.Helper()
var got []string
for _, de := range must.Get(os.ReadDir(dir)) {
got = append(got, de.Name())
}
slices.Sort(got)
slices.Sort(want)
if diff := cmp.Diff(got, want); diff != "" {
t.Fatalf("directory mismatch (-got +want):\n%s", diff)
}
}
clock := tstest.NewClock(tstest.ClockOpts{Start: time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)})
advance := func(d time.Duration) {
t.Helper()
t.Logf("advance: %v", d)
clock.Advance(d)
}
eventsChan := make(chan string, 1000)
checkEvents := func(want ...string) {
t.Helper()
tm := time.NewTimer(10 * time.Second)
defer tm.Stop()
var got []string
for range want {
select {
case event := <-eventsChan:
t.Logf("event: %s", event)
got = append(got, event)
case <-tm.C:
t.Fatalf("timed out waiting for event: got %v, want %v", got, want)
}
}
slices.Sort(got)
slices.Sort(want)
if diff := cmp.Diff(got, want); diff != "" {
t.Fatalf("events mismatch (-got +want):\n%s", diff)
}
}
eventHook := func(event string) { eventsChan <- event }
var fd fileDeleter
fd.Init(t.Logf, tstime.DefaultClock{Clock: clock}, eventHook, dir)
defer fd.Shutdown()
insert := func(name string) {
t.Helper()
t.Logf("insert: %v", name)
fd.Insert(name)
}
remove := func(name string) {
t.Helper()
t.Logf("remove: %v", name)
fd.Remove(name)
}
checkEvents("start init")
checkEvents("end init", "start waitAndDelete")
checkDirectory("foo.partial", "bar.partial", "buzz.deleted")
advance(deleteDelay / 2)
checkDirectory("foo.partial", "bar.partial", "buzz.deleted")
advance(deleteDelay / 2)
checkEvents("deleted foo.partial", "deleted bar.partial", "deleted buzz.deleted")
checkEvents("end waitAndDelete")
checkDirectory()
must.Do(touchFile(filepath.Join(dir, "one.partial")))
insert("one.partial")
checkEvents("start waitAndDelete")
advance(deleteDelay / 4)
must.Do(touchFile(filepath.Join(dir, "two.partial")))
insert("two.partial")
advance(deleteDelay / 4)
must.Do(touchFile(filepath.Join(dir, "three.partial")))
insert("three.partial")
advance(deleteDelay / 4)
must.Do(touchFile(filepath.Join(dir, "four.partial")))
insert("four.partial")
advance(deleteDelay / 4)
checkEvents("deleted one.partial")
checkDirectory("two.partial", "three.partial", "four.partial")
checkEvents("end waitAndDelete", "start waitAndDelete")
advance(deleteDelay / 4)
checkEvents("deleted two.partial")
checkDirectory("three.partial", "four.partial")
checkEvents("end waitAndDelete", "start waitAndDelete")
advance(deleteDelay / 4)
checkEvents("deleted three.partial")
checkDirectory("four.partial")
checkEvents("end waitAndDelete", "start waitAndDelete")
advance(deleteDelay / 4)
checkEvents("deleted four.partial")
checkDirectory()
checkEvents("end waitAndDelete")
insert("wuzz.partial")
checkEvents("start waitAndDelete")
remove("wuzz.partial")
checkEvents("end waitAndDelete")
}

@ -9,6 +9,7 @@ import (
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"io" "io"
"io/fs"
"os" "os"
"slices" "slices"
"strings" "strings"
@ -72,35 +73,24 @@ func hexAppendEncode(dst, src []byte) []byte {
// PartialFiles returns a list of partial files in [Handler.Dir] // PartialFiles returns a list of partial files in [Handler.Dir]
// that were sent (or is actively being sent) by the provided id. // that were sent (or is actively being sent) by the provided id.
func (m *Manager) PartialFiles(id ClientID) (ret []string, err error) { func (m *Manager) PartialFiles(id ClientID) (ret []string, err error) {
if m == nil || m.Dir == "" { if m == nil || m.opts.Dir == "" {
return nil, ErrNoTaildrop return nil, ErrNoTaildrop
} }
if m.DirectFileMode && m.AvoidFinalRename { if m.opts.DirectFileMode && m.opts.AvoidFinalRename {
return nil, nil // resuming is not supported for users that peek at our file structure return nil, nil // resuming is not supported for users that peek at our file structure
} }
f, err := os.Open(m.Dir)
if err != nil {
return ret, err
}
defer f.Close()
suffix := id.partialSuffix() suffix := id.partialSuffix()
for { if err := rangeDir(m.opts.Dir, func(de fs.DirEntry) bool {
des, err := f.ReadDir(10)
if err != nil {
return ret, err
}
for _, de := range des {
if name := de.Name(); strings.HasSuffix(name, suffix) { if name := de.Name(); strings.HasSuffix(name, suffix) {
ret = append(ret, name) ret = append(ret, name)
} }
return true
}); err != nil {
return ret, redactError(err)
} }
if err == io.EOF {
return ret, nil return ret, nil
} }
}
}
// HashPartialFile hashes the contents of a partial file sent by id, // HashPartialFile hashes the contents of a partial file sent by id,
// starting at the specified offset and for the specified length. // starting at the specified offset and for the specified length.
@ -109,14 +99,14 @@ func (m *Manager) PartialFiles(id ClientID) (ret []string, err error) {
// If [FileHashes.Length] is less than length and no error occurred, // If [FileHashes.Length] is less than length and no error occurred,
// then it implies that all remaining content in the file has been hashed. // then it implies that all remaining content in the file has been hashed.
func (m *Manager) HashPartialFile(id ClientID, baseName string, offset, length int64) (FileChecksums, error) { func (m *Manager) HashPartialFile(id ClientID, baseName string, offset, length int64) (FileChecksums, error) {
if m == nil || m.Dir == "" { if m == nil || m.opts.Dir == "" {
return FileChecksums{}, ErrNoTaildrop return FileChecksums{}, ErrNoTaildrop
} }
if m.DirectFileMode && m.AvoidFinalRename { if m.opts.DirectFileMode && m.opts.AvoidFinalRename {
return FileChecksums{}, nil // resuming is not supported for users that peek at our file structure return FileChecksums{}, nil // resuming is not supported for users that peek at our file structure
} }
dstFile, err := m.joinDir(baseName) dstFile, err := joinDir(m.opts.Dir, baseName)
if err != nil { if err != nil {
return FileChecksums{}, err return FileChecksums{}, err
} }
@ -125,12 +115,12 @@ func (m *Manager) HashPartialFile(id ClientID, baseName string, offset, length i
if os.IsNotExist(err) { if os.IsNotExist(err) {
return FileChecksums{}, nil return FileChecksums{}, nil
} }
return FileChecksums{}, err return FileChecksums{}, redactError(err)
} }
defer f.Close() defer f.Close()
if _, err := f.Seek(offset, io.SeekStart); err != nil { if _, err := f.Seek(offset, io.SeekStart); err != nil {
return FileChecksums{}, err return FileChecksums{}, redactError(err)
} }
checksums := FileChecksums{ checksums := FileChecksums{
Offset: offset, Offset: offset,
@ -145,7 +135,7 @@ func (m *Manager) HashPartialFile(id ClientID, baseName string, offset, length i
for { for {
switch n, err := io.ReadFull(r, b); { switch n, err := io.ReadFull(r, b); {
case err != nil && err != io.EOF && err != io.ErrUnexpectedEOF: case err != nil && err != io.EOF && err != io.ErrUnexpectedEOF:
return checksums, err return checksums, redactError(err)
case n == 0: case n == 0:
return checksums, nil return checksums, nil
default: default:

@ -19,7 +19,8 @@ func TestResume(t *testing.T) {
defer func() { blockSize = oldBlockSize }() defer func() { blockSize = oldBlockSize }()
blockSize = 256 blockSize = 256
m := Manager{Logf: t.Logf, Dir: t.TempDir()} m := ManagerOptions{Logf: t.Logf, Dir: t.TempDir()}.New()
defer m.Shutdown()
rn := rand.New(rand.NewSource(0)) rn := rand.New(rand.NewSource(0))
want := make([]byte, 12345) want := make([]byte, 12345)
@ -32,7 +33,7 @@ func TestResume(t *testing.T) {
}) })
must.Do(err) must.Do(err)
must.Get(m.PutFile("", "foo", r, offset, -1)) must.Get(m.PutFile("", "foo", r, offset, -1))
got := must.Get(os.ReadFile(must.Get(m.joinDir("foo")))) got := must.Get(os.ReadFile(must.Get(joinDir(m.opts.Dir, "foo"))))
if !bytes.Equal(got, want) { if !bytes.Equal(got, want) {
t.Errorf("content mismatches") t.Errorf("content mismatches")
} }
@ -54,7 +55,7 @@ func TestResume(t *testing.T) {
break break
} }
} }
got := must.Get(os.ReadFile(must.Get(m.joinDir("foo")))) got := must.Get(os.ReadFile(must.Get(joinDir(m.opts.Dir, "foo"))))
if !bytes.Equal(got, want) { if !bytes.Equal(got, want) {
t.Errorf("content mismatches") t.Errorf("content mismatches")
} }

@ -12,7 +12,6 @@ import (
"path/filepath" "path/filepath"
"runtime" "runtime"
"sort" "sort"
"strings"
"time" "time"
"tailscale.com/client/tailscale/apitype" "tailscale.com/client/tailscale/apitype"
@ -21,163 +20,98 @@ import (
// HasFilesWaiting reports whether any files are buffered in [Handler.Dir]. // HasFilesWaiting reports whether any files are buffered in [Handler.Dir].
// This always returns false when [Handler.DirectFileMode] is false. // This always returns false when [Handler.DirectFileMode] is false.
func (m *Manager) HasFilesWaiting() bool { func (m *Manager) HasFilesWaiting() (has bool) {
if m == nil || m.Dir == "" || m.DirectFileMode { if m == nil || m.opts.Dir == "" || m.opts.DirectFileMode {
return false return false
} }
if m.knownEmpty.Load() {
// Optimization: this is usually empty, so avoid opening // Optimization: this is usually empty, so avoid opening
// the directory and checking. We can't cache the actual // the directory and checking. We can't cache the actual
// has-files-or-not values as the macOS/iOS client might // has-files-or-not values as the macOS/iOS client might
// in the future use+delete the files directly. So only // in the future use+delete the files directly. So only
// keep this negative cache. // keep this negative cache.
totalReceived := m.totalReceived.Load()
if totalReceived == m.emptySince.Load() {
return false return false
} }
f, err := os.Open(m.Dir)
if err != nil { // Check whether there is at least one one waiting file.
return false err := rangeDir(m.opts.Dir, func(de fs.DirEntry) bool {
}
defer f.Close()
for {
des, err := f.ReadDir(10)
for _, de := range des {
name := de.Name() name := de.Name()
if strings.HasSuffix(name, partialSuffix) { if isPartialOrDeleted(name) || !de.Type().IsRegular() {
continue
}
if name, ok := strings.CutSuffix(name, deletedSuffix); ok { // for Windows + tests
// After we're done looping over files, then try
// to delete this file. Don't do it proactively,
// as the OS may return "foo.jpg.deleted" before "foo.jpg"
// and we don't want to delete the ".deleted" file before
// enumerating to the "foo.jpg" file.
defer tryDeleteAgain(filepath.Join(m.Dir, name))
continue
}
if de.Type().IsRegular() {
_, err := os.Stat(filepath.Join(m.Dir, name+deletedSuffix))
if os.IsNotExist(err) {
return true return true
} }
if err == nil { _, err := os.Stat(filepath.Join(m.opts.Dir, name+deletedSuffix))
tryDeleteAgain(filepath.Join(m.Dir, name)) if os.IsNotExist(err) {
continue has = true
} return false
}
}
if err == io.EOF {
m.knownEmpty.Store(true)
}
if err != nil {
break
} }
return true
})
// If there are no more waiting files, record totalReceived as emptySince
// so that we can short-circuit the expensive directory traversal
// if no files have been received after the start of this call.
if err == nil && !has {
m.emptySince.Store(totalReceived)
} }
return false return has
} }
// WaitingFiles returns the list of files that have been sent by a // WaitingFiles returns the list of files that have been sent by a
// peer that are waiting in [Handler.Dir]. // peer that are waiting in [Handler.Dir].
// This always returns nil when [Handler.DirectFileMode] is false. // This always returns nil when [Handler.DirectFileMode] is false.
func (m *Manager) WaitingFiles() (ret []apitype.WaitingFile, err error) { func (m *Manager) WaitingFiles() (ret []apitype.WaitingFile, err error) {
if m == nil || m.Dir == "" { if m == nil || m.opts.Dir == "" {
return nil, ErrNoTaildrop return nil, ErrNoTaildrop
} }
if m.DirectFileMode { if m.opts.DirectFileMode {
return nil, nil return nil, nil
} }
f, err := os.Open(m.Dir) if err := rangeDir(m.opts.Dir, func(de fs.DirEntry) bool {
if err != nil {
return nil, err
}
defer f.Close()
var deleted map[string]bool // "foo.jpg" => true (if "foo.jpg.deleted" exists)
for {
des, err := f.ReadDir(10)
for _, de := range des {
name := de.Name() name := de.Name()
if strings.HasSuffix(name, partialSuffix) { if isPartialOrDeleted(name) || !de.Type().IsRegular() {
continue return true
}
if name, ok := strings.CutSuffix(name, deletedSuffix); ok { // for Windows + tests
if deleted == nil {
deleted = map[string]bool{}
}
deleted[name] = true
continue
} }
if de.Type().IsRegular() { _, err := os.Stat(filepath.Join(m.opts.Dir, name+deletedSuffix))
if os.IsNotExist(err) {
fi, err := de.Info() fi, err := de.Info()
if err != nil { if err != nil {
continue return true
} }
ret = append(ret, apitype.WaitingFile{ ret = append(ret, apitype.WaitingFile{
Name: filepath.Base(name), Name: filepath.Base(name),
Size: fi.Size(), Size: fi.Size(),
}) })
} }
} return true
if err == io.EOF { }); err != nil {
break return nil, redactError(err)
}
if err != nil {
return nil, err
}
}
if len(deleted) > 0 {
// Filter out any return values "foo.jpg" where a
// "foo.jpg.deleted" marker file exists on disk.
all := ret
ret = ret[:0]
for _, wf := range all {
if !deleted[wf.Name] {
ret = append(ret, wf)
}
}
// And do some opportunistic deleting while we're here.
// Maybe Windows is done virus scanning the file we tried
// to delete a long time ago and will let us delete it now.
for name := range deleted {
tryDeleteAgain(filepath.Join(m.Dir, name))
}
} }
sort.Slice(ret, func(i, j int) bool { return ret[i].Name < ret[j].Name }) sort.Slice(ret, func(i, j int) bool { return ret[i].Name < ret[j].Name })
return ret, nil return ret, nil
} }
// tryDeleteAgain tries to delete path (and path+deletedSuffix) after
// it failed earlier. This happens on Windows when various anti-virus
// tools hook into filesystem operations and have the file open still
// while we're trying to delete it. In that case we instead mark it as
// deleted (writing a "foo.jpg.deleted" marker file), but then we
// later try to clean them up.
//
// fullPath is the full path to the file without the deleted suffix.
func tryDeleteAgain(fullPath string) {
if err := os.Remove(fullPath); err == nil || os.IsNotExist(err) {
os.Remove(fullPath + deletedSuffix)
}
}
// DeleteFile deletes a file of the given baseName from [Handler.Dir]. // DeleteFile deletes a file of the given baseName from [Handler.Dir].
// This method is only allowed when [Handler.DirectFileMode] is false. // This method is only allowed when [Handler.DirectFileMode] is false.
func (m *Manager) DeleteFile(baseName string) error { func (m *Manager) DeleteFile(baseName string) error {
if m == nil || m.Dir == "" { if m == nil || m.opts.Dir == "" {
return ErrNoTaildrop return ErrNoTaildrop
} }
if m.DirectFileMode { if m.opts.DirectFileMode {
return errors.New("deletes not allowed in direct mode") return errors.New("deletes not allowed in direct mode")
} }
path, err := m.joinDir(baseName) path, err := joinDir(m.opts.Dir, baseName)
if err != nil { if err != nil {
return err return err
} }
var bo *backoff.Backoff var bo *backoff.Backoff
logf := m.Logf logf := m.opts.Logf
t0 := m.Clock.Now() t0 := m.opts.Clock.Now()
for { for {
err := os.Remove(path) err := os.Remove(path)
if err != nil && !os.IsNotExist(err) { if err != nil && !os.IsNotExist(err) {
err = redactErr(err) err = redactError(err)
// Put a retry loop around deletes on Windows. Windows // Put a retry loop around deletes on Windows. Windows
// file descriptor closes are effectively asynchronous, // file descriptor closes are effectively asynchronous,
// as a bunch of hooks run on/after close, and we can't // as a bunch of hooks run on/after close, and we can't
@ -192,13 +126,14 @@ func (m *Manager) DeleteFile(baseName string) error {
if bo == nil { if bo == nil {
bo = backoff.NewBackoff("delete-retry", logf, 1*time.Second) bo = backoff.NewBackoff("delete-retry", logf, 1*time.Second)
} }
if m.Clock.Since(t0) < 5*time.Second { if m.opts.Clock.Since(t0) < 5*time.Second {
bo.BackOff(context.Background(), err) bo.BackOff(context.Background(), err)
continue continue
} }
if err := touchFile(path + deletedSuffix); err != nil { if err := touchFile(path + deletedSuffix); err != nil {
logf("peerapi: failed to leave deleted marker: %v", err) logf("peerapi: failed to leave deleted marker: %v", err)
} }
m.deleter.Insert(baseName + deletedSuffix)
} }
logf("peerapi: failed to DeleteFile: %v", err) logf("peerapi: failed to DeleteFile: %v", err)
return err return err
@ -210,7 +145,7 @@ func (m *Manager) DeleteFile(baseName string) error {
func touchFile(path string) error { func touchFile(path string) error {
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0666) f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0666)
if err != nil { if err != nil {
return redactErr(err) return redactError(err)
} }
return f.Close() return f.Close()
} }
@ -218,28 +153,27 @@ func touchFile(path string) error {
// OpenFile opens a file of the given baseName from [Handler.Dir]. // OpenFile opens a file of the given baseName from [Handler.Dir].
// This method is only allowed when [Handler.DirectFileMode] is false. // This method is only allowed when [Handler.DirectFileMode] is false.
func (m *Manager) OpenFile(baseName string) (rc io.ReadCloser, size int64, err error) { func (m *Manager) OpenFile(baseName string) (rc io.ReadCloser, size int64, err error) {
if m == nil || m.Dir == "" { if m == nil || m.opts.Dir == "" {
return nil, 0, ErrNoTaildrop return nil, 0, ErrNoTaildrop
} }
if m.DirectFileMode { if m.opts.DirectFileMode {
return nil, 0, errors.New("opens not allowed in direct mode") return nil, 0, errors.New("opens not allowed in direct mode")
} }
path, err := m.joinDir(baseName) path, err := joinDir(m.opts.Dir, baseName)
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err
} }
if fi, err := os.Stat(path + deletedSuffix); err == nil && fi.Mode().IsRegular() { if _, err := os.Stat(path + deletedSuffix); err == nil {
tryDeleteAgain(path) return nil, 0, redactError(&fs.PathError{Op: "open", Path: path, Err: fs.ErrNotExist})
return nil, 0, &fs.PathError{Op: "open", Path: redacted, Err: fs.ErrNotExist}
} }
f, err := os.Open(path) f, err := os.Open(path)
if err != nil { if err != nil {
return nil, 0, redactErr(err) return nil, 0, redactError(err)
} }
fi, err := f.Stat() fi, err := f.Stat()
if err != nil { if err != nil {
f.Close() f.Close()
return nil, 0, redactErr(err) return nil, 0, redactError(err)
} }
return f, fi.Size(), nil return f, fi.Size(), nil
} }

@ -8,6 +8,7 @@ import (
"errors" "errors"
"io" "io"
"os" "os"
"path/filepath"
"sync" "sync"
"time" "time"
@ -72,25 +73,25 @@ func (f *incomingFile) Write(p []byte) (n int, err error) {
// offset to specify where to resume receiving data at. // offset to specify where to resume receiving data at.
func (m *Manager) PutFile(id ClientID, baseName string, r io.Reader, offset, length int64) (int64, error) { func (m *Manager) PutFile(id ClientID, baseName string, r io.Reader, offset, length int64) (int64, error) {
switch { switch {
case m == nil || m.Dir == "": case m == nil || m.opts.Dir == "":
return 0, ErrNoTaildrop return 0, ErrNoTaildrop
case !envknob.CanTaildrop(): case !envknob.CanTaildrop():
return 0, ErrNoTaildrop return 0, ErrNoTaildrop
case distro.Get() == distro.Unraid && !m.DirectFileMode: case distro.Get() == distro.Unraid && !m.opts.DirectFileMode:
return 0, ErrNotAccessible return 0, ErrNotAccessible
} }
dstPath, err := m.joinDir(baseName) dstPath, err := joinDir(m.opts.Dir, baseName)
if err != nil { if err != nil {
return 0, err return 0, err
} }
redactAndLogError := func(action string, err error) error { redactAndLogError := func(action string, err error) error {
err = redactErr(err) err = redactError(err)
m.Logf("put %v error: %v", action, err) m.opts.Logf("put %v error: %v", action, err)
return err return err
} }
avoidPartialRename := m.DirectFileMode && m.AvoidFinalRename avoidPartialRename := m.opts.DirectFileMode && m.opts.AvoidFinalRename
if avoidPartialRename { if avoidPartialRename {
// Users using AvoidFinalRename are depending on the exact filename // Users using AvoidFinalRename are depending on the exact filename
// of the partial files. So avoid injecting the id into it. // of the partial files. So avoid injecting the id into it.
@ -98,20 +99,16 @@ func (m *Manager) PutFile(id ClientID, baseName string, r io.Reader, offset, len
} }
// Check whether there is an in-progress transfer for the file. // Check whether there is an in-progress transfer for the file.
sendFileNotify := m.SendFileNotify
if sendFileNotify == nil {
sendFileNotify = func() {} // avoid nil panics below
}
partialPath := dstPath + id.partialSuffix() partialPath := dstPath + id.partialSuffix()
inFileKey := incomingFileKey{id, baseName} inFileKey := incomingFileKey{id, baseName}
inFile, loaded := m.incomingFiles.LoadOrInit(inFileKey, func() *incomingFile { inFile, loaded := m.incomingFiles.LoadOrInit(inFileKey, func() *incomingFile {
inFile := &incomingFile{ inFile := &incomingFile{
clock: m.Clock, clock: m.opts.Clock,
started: m.Clock.Now(), started: m.opts.Clock.Now(),
size: length, size: length,
sendFileNotify: sendFileNotify, sendFileNotify: m.opts.SendFileNotify,
} }
if m.DirectFileMode { if m.opts.DirectFileMode {
inFile.partialPath = partialPath inFile.partialPath = partialPath
} }
return inFile return inFile
@ -120,6 +117,7 @@ func (m *Manager) PutFile(id ClientID, baseName string, r io.Reader, offset, len
return 0, ErrFileExists return 0, ErrFileExists
} }
defer m.incomingFiles.Delete(inFileKey) defer m.incomingFiles.Delete(inFileKey)
m.deleter.Remove(filepath.Base(partialPath)) // avoid deleting the partial file while receiving
// Create (if not already) the partial file with read-write permissions. // Create (if not already) the partial file with read-write permissions.
f, err := os.OpenFile(partialPath, os.O_CREATE|os.O_RDWR, 0666) f, err := os.OpenFile(partialPath, os.O_CREATE|os.O_RDWR, 0666)
@ -133,9 +131,7 @@ func (m *Manager) PutFile(id ClientID, baseName string, r io.Reader, offset, len
os.Remove(partialPath) // best-effort os.Remove(partialPath) // best-effort
return return
} }
m.deleter.Insert(filepath.Base(partialPath)) // mark partial file for eventual deletion
// TODO: We need to delete partialPath eventually.
// However, this must be done after some period of time.
} }
}() }()
inFile.w = f inFile.w = f
@ -177,8 +173,8 @@ func (m *Manager) PutFile(id ClientID, baseName string, r io.Reader, offset, len
inFile.mu.Lock() inFile.mu.Lock()
inFile.done = true inFile.done = true
inFile.mu.Unlock() inFile.mu.Unlock()
m.knownEmpty.Store(false) m.totalReceived.Add(1)
sendFileNotify() m.opts.SendFileNotify()
return fileLength, nil return fileLength, nil
} }
@ -236,8 +232,8 @@ func (m *Manager) PutFile(id ClientID, baseName string, r io.Reader, offset, len
if maxRetries <= 0 { if maxRetries <= 0 {
return 0, errors.New("too many retries trying to rename partial file") return 0, errors.New("too many retries trying to rename partial file")
} }
m.knownEmpty.Store(false) m.totalReceived.Add(1)
sendFileNotify() m.opts.SendFileNotify()
return fileLength, nil return fileLength, nil
} }

@ -12,6 +12,8 @@ package taildrop
import ( import (
"errors" "errors"
"hash/adler32" "hash/adler32"
"io"
"io/fs"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
@ -30,6 +32,27 @@ import (
"tailscale.com/util/multierr" "tailscale.com/util/multierr"
) )
var (
ErrNoTaildrop = errors.New("Taildrop disabled; no storage directory")
ErrInvalidFileName = errors.New("invalid filename")
ErrFileExists = errors.New("file already exists")
ErrNotAccessible = errors.New("Taildrop folder not configured or accessible")
)
const (
// partialSuffix is the suffix appended to files while they're
// still in the process of being transferred.
partialSuffix = ".partial"
// deletedSuffix is the suffix for a deleted marker file
// that's placed next to a file (without the suffix) that we
// tried to delete, but Windows wouldn't let us. These are
// only written on Windows (and in tests), but they're not
// permitted to be uploaded directly on any platform, like
// partial files.
deletedSuffix = ".deleted"
)
// ClientID is an opaque identifier for file resumption. // ClientID is an opaque identifier for file resumption.
// A client can only list and resume partial files for its own ID. // A client can only list and resume partial files for its own ID.
// It must contain any filesystem specific characters (e.g., slashes). // It must contain any filesystem specific characters (e.g., slashes).
@ -42,8 +65,8 @@ func (id ClientID) partialSuffix() string {
return "." + string(id) + partialSuffix // e.g., ".n12345CNTRL.partial" return "." + string(id) + partialSuffix // e.g., ".n12345CNTRL.partial"
} }
// Manager manages the state for receiving and managing taildropped files. // ManagerOptions are options to configure the [Manager].
type Manager struct { type ManagerOptions struct {
Logf logger.Logf Logf logger.Logf
Clock tstime.DefaultClock Clock tstime.DefaultClock
@ -80,39 +103,56 @@ type Manager struct {
// to the function when reception completes. // to the function when reception completes.
// It is not called if nil. // It is not called if nil.
SendFileNotify func() SendFileNotify func()
}
knownEmpty atomic.Bool // Manager manages the state for receiving and managing taildropped files.
type Manager struct {
opts ManagerOptions
// incomingFiles is a map of files actively being received.
incomingFiles syncs.Map[incomingFileKey, *incomingFile] incomingFiles syncs.Map[incomingFileKey, *incomingFile]
// deleter managers asynchronous deletion of files.
deleter fileDeleter
// renameMu is used to protect os.Rename calls so that they are atomic. // renameMu is used to protect os.Rename calls so that they are atomic.
renameMu sync.Mutex renameMu sync.Mutex
}
var ( // totalReceived counts the cumulative total of received files.
ErrNoTaildrop = errors.New("Taildrop disabled; no storage directory") totalReceived atomic.Int64
ErrInvalidFileName = errors.New("invalid filename") // emptySince specifies that there were no waiting files
ErrFileExists = errors.New("file already exists") // since this value of totalReceived.
ErrNotAccessible = errors.New("Taildrop folder not configured or accessible") emptySince atomic.Int64
) }
const ( // New initializes a new taildrop manager.
// partialSuffix is the suffix appended to files while they're // It may spawn asynchronous goroutines to delete files,
// still in the process of being transferred. // so the Shutdown method must be called for resource cleanup.
partialSuffix = ".partial" func (opts ManagerOptions) New() *Manager {
if opts.Logf == nil {
opts.Logf = logger.Discard
}
if opts.SendFileNotify == nil {
opts.SendFileNotify = func() {}
}
m := &Manager{opts: opts}
m.deleter.Init(opts.Logf, opts.Clock, func(string) {}, opts.Dir)
m.emptySince.Store(-1) // invalidate this cache
return m
}
// deletedSuffix is the suffix for a deleted marker file // Dir returns the directory.
// that's placed next to a file (without the suffix) that we func (m *Manager) Dir() string {
// tried to delete, but Windows wouldn't let us. These are return m.opts.Dir
// only written on Windows (and in tests), but they're not }
// permitted to be uploaded directly on any platform, like
// partial files.
deletedSuffix = ".deleted"
)
// redacted is a fake path name we use in errors, to avoid // Shutdown shuts down the Manager.
// accidentally logging actual filenames anywhere. // It blocks until all spawned goroutines have stopped running.
const redacted = "redacted" func (m *Manager) Shutdown() {
if m != nil {
m.deleter.shutdown()
m.deleter.group.Wait()
}
}
func validFilenameRune(r rune) bool { func validFilenameRune(r rune) bool {
switch r { switch r {
@ -131,7 +171,11 @@ func validFilenameRune(r rune) bool {
return unicode.IsPrint(r) return unicode.IsPrint(r)
} }
func (m *Manager) joinDir(baseName string) (fullPath string, err error) { func isPartialOrDeleted(s string) bool {
return strings.HasSuffix(s, deletedSuffix) || strings.HasSuffix(s, partialSuffix)
}
func joinDir(dir, baseName string) (fullPath string, err error) {
if !utf8.ValidString(baseName) { if !utf8.ValidString(baseName) {
return "", ErrInvalidFileName return "", ErrInvalidFileName
} }
@ -145,8 +189,7 @@ func (m *Manager) joinDir(baseName string) (fullPath string, err error) {
clean := path.Clean(baseName) clean := path.Clean(baseName)
if clean != baseName || if clean != baseName ||
clean == "." || clean == ".." || clean == "." || clean == ".." ||
strings.HasSuffix(clean, deletedSuffix) || isPartialOrDeleted(clean) {
strings.HasSuffix(clean, partialSuffix) {
return "", ErrInvalidFileName return "", ErrInvalidFileName
} }
for _, r := range baseName { for _, r := range baseName {
@ -157,7 +200,32 @@ func (m *Manager) joinDir(baseName string) (fullPath string, err error) {
if !filepath.IsLocal(baseName) { if !filepath.IsLocal(baseName) {
return "", ErrInvalidFileName return "", ErrInvalidFileName
} }
return filepath.Join(m.Dir, baseName), nil return filepath.Join(dir, baseName), nil
}
// rangeDir iterates over the contents of a directory, calling fn for each entry.
// It continues iterating while fn returns true.
// It reports the number of entries seen.
func rangeDir(dir string, fn func(fs.DirEntry) bool) error {
f, err := os.Open(dir)
if err != nil {
return err
}
defer f.Close()
for {
des, err := f.ReadDir(10)
for _, de := range des {
if !fn(de) {
return nil
}
}
if err != nil {
if err == io.EOF {
return nil
}
return err
}
}
} }
// IncomingFiles returns a list of active incoming files. // IncomingFiles returns a list of active incoming files.
@ -182,16 +250,20 @@ func (m *Manager) IncomingFiles() []ipn.PartialFile {
return files return files
} }
type redactedErr struct { // redacted is a fake path name we use in errors, to avoid
// accidentally logging actual filenames anywhere.
const redacted = "redacted"
type redactedError struct {
msg string msg string
inner error inner error
} }
func (re *redactedErr) Error() string { func (re *redactedError) Error() string {
return re.msg return re.msg
} }
func (re *redactedErr) Unwrap() error { func (re *redactedError) Unwrap() error {
return re.inner return re.inner
} }
@ -205,7 +277,7 @@ func redactString(s string) string {
return string(b) return string(b)
} }
func redactErr(root error) error { func redactError(root error) error {
// redactStrings is a list of sensitive strings that were redacted. // redactStrings is a list of sensitive strings that were redacted.
// It is not sufficient to just snub out sensitive fields in Go errors // It is not sufficient to just snub out sensitive fields in Go errors
// since some wrapper errors like fmt.Errorf pre-cache the error string, // since some wrapper errors like fmt.Errorf pre-cache the error string,
@ -243,7 +315,7 @@ func redactErr(root error) error {
for _, toRedact := range redactStrings { for _, toRedact := range redactStrings {
s = strings.ReplaceAll(s, toRedact, redactString(toRedact)) s = strings.ReplaceAll(s, toRedact, redactString(toRedact))
} }
return &redactedErr{msg: s, inner: root} return &redactedError{msg: s, inner: root}
} }
var ( var (

@ -4,153 +4,37 @@
package taildrop package taildrop
import ( import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath" "path/filepath"
"runtime" "strings"
"testing" "testing"
) )
// Tests "foo.jpg.deleted" marks (for Windows). func TestJoinDir(t *testing.T) {
func TestDeletedMarkers(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
h := &Manager{Dir: dir} tests := []struct {
in string
nothingWaiting := func() { want string // just relative to m.Dir
t.Helper() wantOk bool
h.knownEmpty.Store(false)
if h.HasFilesWaiting() {
t.Fatal("unexpected files waiting")
}
}
touch := func(base string) {
t.Helper()
if err := touchFile(filepath.Join(dir, base)); err != nil {
t.Fatal(err)
}
}
wantEmptyTempDir := func() {
t.Helper()
if fis, err := os.ReadDir(dir); err != nil {
t.Fatal(err)
} else if len(fis) > 0 && runtime.GOOS != "windows" {
for _, fi := range fis {
t.Errorf("unexpected file in tempdir: %q", fi.Name())
}
}
}
nothingWaiting()
wantEmptyTempDir()
touch("foo.jpg.deleted")
nothingWaiting()
wantEmptyTempDir()
touch("foo.jpg.deleted")
touch("foo.jpg")
nothingWaiting()
wantEmptyTempDir()
touch("foo.jpg.deleted")
touch("foo.jpg")
wf, err := h.WaitingFiles()
if err != nil {
t.Fatal(err)
}
if len(wf) != 0 {
t.Fatalf("WaitingFiles = %d; want 0", len(wf))
}
wantEmptyTempDir()
touch("foo.jpg.deleted")
touch("foo.jpg")
if rc, _, err := h.OpenFile("foo.jpg"); err == nil {
rc.Close()
t.Fatal("unexpected foo.jpg open")
}
wantEmptyTempDir()
// And verify basics still work in non-deleted cases.
touch("foo.jpg")
touch("bar.jpg.deleted")
if wf, err := h.WaitingFiles(); err != nil {
t.Error(err)
} else if len(wf) != 1 {
t.Errorf("WaitingFiles = %d; want 1", len(wf))
} else if wf[0].Name != "foo.jpg" {
t.Errorf("unexpected waiting file %+v", wf[0])
}
if rc, _, err := h.OpenFile("foo.jpg"); err != nil {
t.Fatal(err)
} else {
rc.Close()
}
}
func TestRedactErr(t *testing.T) {
testCases := []struct {
name string
err func() error
want string
}{ }{
{ {"", "", false},
name: "PathError", {"foo", "foo", true},
err: func() error { {"./foo", "", false},
return &os.PathError{ {"../foo", "", false},
Op: "open", {"foo/bar", "", false},
Path: "/tmp/sensitive.txt", {"😋", "😋", true},
Err: fs.ErrNotExist, {"\xde\xad\xbe\xef", "", false},
{"foo.partial", "", false},
{"foo.deleted", "", false},
{strings.Repeat("a", 1024), "", false},
{"foo:bar", "", false},
} }
}, for _, tt := range tests {
want: `open redacted.41360718: file does not exist`, got, gotErr := joinDir(dir, tt.in)
}, got, _ = filepath.Rel(dir, got)
{ gotOk := gotErr == nil
name: "LinkError", if got != tt.want || gotOk != tt.wantOk {
err: func() error { t.Errorf("joinDir(%q) = (%v, %v), want (%v, %v)", tt.in, got, gotOk, tt.want, tt.wantOk)
return &os.LinkError{
Op: "symlink",
Old: "/tmp/sensitive.txt",
New: "/tmp/othersensitive.txt",
Err: fs.ErrNotExist,
}
},
want: `symlink redacted.41360718 redacted.6bcf093a: file does not exist`,
},
{
name: "something else",
err: func() error { return errors.New("i am another error type") },
want: `i am another error type`,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// For debugging
var i int
for err := tc.err(); err != nil; err = errors.Unwrap(err) {
t.Logf("%d: %T @ %p", i, err, err)
i++
}
t.Run("Root", func(t *testing.T) {
got := redactErr(tc.err()).Error()
if got != tc.want {
t.Errorf("err = %q; want %q", got, tc.want)
}
})
t.Run("Wrapped", func(t *testing.T) {
wrapped := fmt.Errorf("wrapped error: %w", tc.err())
want := "wrapped error: " + tc.want
got := redactErr(wrapped).Error()
if got != want {
t.Errorf("err = %q; want %q", got, want)
} }
})
})
} }
} }

Loading…
Cancel
Save