Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 38 additions & 14 deletions backend/api/safefetch.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,33 +58,57 @@ func validateFetchURL(rawURL string) (*url.URL, error) {
return u, nil
}

// isBlockedIP returns true if dialing this address would reach loopback,
// link-local, RFC1918/ULA private space, multicast, or the unspecified
// address. Pulled out of the dialer so it can be unit-tested directly.
// isBlockedIP returns true if dialing this address would reach a non-public
// destination. It adopts an allow-global-only baseline: anything that is not a
// global-unicast address is blocked (this covers loopback, link-local,
// multicast, and unspecified). On top of that it explicitly blocks RFC1918/ULA
// private space, the RFC 6598 CGNAT range 100.64.0.0/10 for IPv4, and the
// IPv6 transition ranges 6to4 2002::/16 and Teredo 2001::/32 — Go's
// IsGlobalUnicast reports those last two as global, so they must be checked
// explicitly. Pulled out of the dialer so it can be unit-tested directly.
func isBlockedIP(addr netip.Addr) bool {
if !addr.IsValid() {
return true
}
// Unmap so an IPv4-in-IPv6 address (::ffff:127.0.0.1) is checked as IPv4.
addr = addr.Unmap()
if addr.IsLoopback() {

// Allow-global-only baseline. Anything that isn't a routable global
// unicast address (loopback, link-local, multicast, unspecified) is
// refused.
if !addr.IsGlobalUnicast() {
return true
}

// Explicitly block RFC1918 (IPv4) / RFC4193 ULA (IPv6) private space.
if addr.IsPrivate() {
return true
}
if addr.IsLinkLocalUnicast() {
return true
}
if addr.IsLinkLocalMulticast() {
return true
}
if addr.IsMulticast() {
return true

// RFC 6598 carrier-grade NAT: 100.64.0.0/10. Only applies to IPv4.
if addr.Is4() {
b := addr.As4()
if b[0] == 100 && b[1]&0xc0 == 64 {
return true
}
}
if addr.IsUnspecified() {
return true

// Non-global IPv6 transition ranges that Go still classifies as global
// unicast: 6to4 (2002::/16) embeds an arbitrary IPv4 destination and
// Teredo (2001:0::/32) tunnels to one, so either can be used to reach an
// otherwise-blocked v4 target. Block them outright.
if addr.Is6() {
b := addr.As16()
// 6to4: 2002::/16.
if b[0] == 0x20 && b[1] == 0x02 {
return true
}
// Teredo: 2001:0000::/32 (the first 32 bits are 2001:0000).
if b[0] == 0x20 && b[1] == 0x01 && b[2] == 0x00 && b[3] == 0x00 {
return true
}
}

return false
}

Expand Down
14 changes: 14 additions & 0 deletions backend/api/safefetch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,25 @@ func TestIsBlockedIP(t *testing.T) {
{"239.255.255.255", true, "multicast v4 edge"},
{"ff02::1", true, "multicast v6"},

// RFC 6598 carrier-grade NAT 100.64.0.0/10.
{"100.64.0.0", true, "CGNAT low edge"},
{"100.64.0.1", true, "CGNAT"},
{"100.100.100.100", true, "CGNAT mid"},
{"100.127.255.255", true, "CGNAT high edge"},

// Non-global IPv6 transition ranges.
{"2002::1", true, "6to4 2002::/16"},
{"2002:c058:6301::1", true, "6to4 wrapping a public v4"},
{"2001::1", true, "Teredo 2001::/32"},
{"2001:0:4136:e378:8000:63bf:3fff:fdd2", true, "Teredo full"},

{"8.8.8.8", false, "Google DNS"},
{"1.1.1.1", false, "Cloudflare DNS"},
{"2001:4860:4860::8888", false, "Google DNS v6"},
{"172.15.0.1", false, "just below RFC1918"},
{"172.32.0.1", false, "just above RFC1918"},
{"100.63.255.255", false, "just below CGNAT"},
{"100.128.0.0", false, "just above CGNAT"},
}

for _, tc := range cases {
Expand Down
20 changes: 17 additions & 3 deletions backend/engine/diskfree_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@

package engine

import "golang.org/x/sys/unix"
import (
"math"

"golang.org/x/sys/unix"
)

// diskFreeBytes returns the bytes available on the filesystem containing path,
// from the perspective of the calling user (i.e. excluding root-reserved
Expand All @@ -14,6 +18,16 @@ func diskFreeBytes(path string) int64 {
return -1
}
// Bavail × Bsize gives the user-available bytes. Bfree includes
// root-reserved blocks and would over-report.
return int64(stat.Bavail) * int64(stat.Bsize)
// root-reserved blocks and would over-report. Compute in uint64 and
// saturate to MaxInt64 so a huge/odd filesystem can't overflow or wrap
// the int64 result into a negative ("unknown") value.
avail := uint64(stat.Bavail)
bsize := uint64(stat.Bsize)
if bsize == 0 {
return -1
}
if avail > math.MaxInt64/bsize {
return math.MaxInt64
}
return int64(avail * bsize)
}
11 changes: 10 additions & 1 deletion backend/engine/diskfree_windows.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package engine

import "golang.org/x/sys/windows"
import (
"math"

"golang.org/x/sys/windows"
)

// diskFreeBytes returns the bytes available on the volume containing path
// for the calling user (Windows GetDiskFreeSpaceEx's "FreeBytesAvailable",
Expand All @@ -15,5 +19,10 @@ func diskFreeBytes(path string) int64 {
if err := windows.GetDiskFreeSpaceEx(p, &freeAvail, &totalBytes, &totalFree); err != nil {
return -1
}
// freeAvail is a uint64; int64(freeAvail) would truncate/wrap a value
// above MaxInt64 into a negative ("unknown") result. Saturate instead.
if freeAvail > math.MaxInt64 {
return math.MaxInt64
}
return int64(freeAvail)
}
13 changes: 11 additions & 2 deletions backend/engine/safepath.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package engine
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
)
Expand Down Expand Up @@ -58,8 +59,16 @@ func safeRemovePath(saveTo, name string) (string, error) {
// the lexical check above is sufficient and we return cleanTarget directly.
evalSaveTo, err := filepath.EvalSymlinks(cleanSaveTo)
if err != nil {
// saveTo missing or unreadable — best we can do is the lexical check.
return cleanTarget, nil
// This is a DELETE operation, so fail closed. If saveTo doesn't exist
// there's nothing under it to remove and the lexical check already
// passed — degrade to the lexical result. But for any other error
// (permission denied, a symlink loop, an I/O error) we must NOT fall
// back to a lexical-only check: that would let a symlink we couldn't
// resolve redirect the RemoveAll outside saveTo. Refuse instead.
if os.IsNotExist(err) {
return cleanTarget, nil
}
return "", fmt.Errorf("safeRemovePath: cannot resolve save dir %q: %w", saveTo, err)
}
evalTarget, err := filepath.EvalSymlinks(cleanTarget)
if err != nil {
Expand Down
7 changes: 5 additions & 2 deletions backend/engine/scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ type Scheduler struct {
maxActiveDownloads int // 0 = unlimited
maxActiveSeeds int

stop chan struct{}
stop chan struct{}
closeOnce sync.Once
}

func NewScheduler(eng *Engine, maxDL, maxSeeds int, tickEvery time.Duration) *Scheduler {
Expand All @@ -38,7 +39,9 @@ func (s *Scheduler) Limits() (int, int) {
return s.maxActiveDownloads, s.maxActiveSeeds
}

func (s *Scheduler) Close() { close(s.stop) }
// Close stops the scheduler's tick loop. It is idempotent: calling Close more
// than once is safe and will not panic on a double close(s.stop).
func (s *Scheduler) Close() { s.closeOnce.Do(func() { close(s.stop) }) }

func (s *Scheduler) run(every time.Duration) {
t := time.NewTicker(every)
Expand Down
16 changes: 16 additions & 0 deletions backend/engine/scheduler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,22 @@ func TestScheduler_TieBreaksDeterministicallyOnEqualQueuePosition(t *testing.T)
}
}

// TestScheduler_CloseIsIdempotent guards the double-close panic: Close used to
// do a bare close(s.stop), which panics on the second call. A sync.Once makes
// it safe to call Close any number of times.
func TestScheduler_CloseIsIdempotent(t *testing.T) {
fb := NewFakeBackend()
eng := NewEngine(fb, 50*time.Millisecond)
t.Cleanup(func() { _ = eng.Close() })

s := NewScheduler(eng, 2, 0, 50*time.Millisecond)
require.NotPanics(t, func() {
s.Close()
s.Close()
s.Close()
}, "calling Close multiple times must not panic")
}

func TestScheduler_ForceStartBypassesLimit(t *testing.T) {
fb := NewFakeBackend()
eng := NewEngine(fb, 50*time.Millisecond)
Expand Down
27 changes: 20 additions & 7 deletions backend/engine/verify_snapshot.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package engine
import (
"crypto/sha256"
"fmt"
"log"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -40,9 +41,13 @@ type SnapshotStore interface {
}

// computeFileSnapshot returns a SHA-256 over the torrent's on-disk file
// state. Each metainfo file contributes a `path|size|mtime_ns` line; missing
// files contribute `MISSING:<path>` so a deletion changes the digest. The
// path component is the joined relative path inside the torrent (forward-
// state. Each metainfo file contributes a `path|size|mtime_ns|mode` line;
// missing files contribute `MISSING:<path>` so a deletion changes the digest.
// The mode component is the file's os.FileMode bits, so swapping a regular
// file for a directory or symlink (regular↔dir↔symlink) changes the digest
// even if the size/mtime happen to match. We stat with os.Lstat so a planted
// symlink is recorded as a symlink rather than being followed to its target.
// The path component is the joined relative path inside the torrent (forward-
// slash separators) so the digest is stable across OSes for the same files.
//
// `saveTo` matches anacrolix's `storage.NewFile` root: a single-file torrent
Expand All @@ -67,30 +72,38 @@ func computeFileSnapshot(info *metainfo.Info, saveTo string) ([]byte, error) {
// Single-file torrent. Path on disk is saveTo/info.Name.
rel := info.Name
full := filepath.Join(saveTo, info.Name)
st, err := os.Stat(full)
st, err := os.Lstat(full)
if err != nil {
if os.IsNotExist(err) {
writeLine("MISSING:" + rel)
} else {
// Non-not-exist stat error: log it and return so the caller
// falls through to a full piece-by-piece hash rather than
// silently trusting a stale snapshot.
log.Printf("computeFileSnapshot: lstat %q: %v — falling back to full hash", full, err)
return nil, err
}
} else {
writeLine(fmt.Sprintf("%s|%d|%d", rel, st.Size(), st.ModTime().UnixNano()))
writeLine(fmt.Sprintf("%s|%d|%d|%o", rel, st.Size(), st.ModTime().UnixNano(), st.Mode()))
}
} else {
for _, f := range info.Files {
rel := strings.Join(f.Path, "/")
parts := append([]string{saveTo, info.Name}, f.Path...)
full := filepath.Join(parts...)
st, err := os.Stat(full)
st, err := os.Lstat(full)
if err != nil {
if os.IsNotExist(err) {
writeLine("MISSING:" + rel)
continue
}
// Non-not-exist stat error: log it and return so the caller
// falls through to a full piece-by-piece hash rather than
// silently trusting a stale snapshot.
log.Printf("computeFileSnapshot: lstat %q: %v — falling back to full hash", full, err)
return nil, err
}
writeLine(fmt.Sprintf("%s|%d|%d", rel, st.Size(), st.ModTime().UnixNano()))
writeLine(fmt.Sprintf("%s|%d|%d|%o", rel, st.Size(), st.ModTime().UnixNano(), st.Mode()))
}
}
return h.Sum(nil), nil
Expand Down
52 changes: 52 additions & 0 deletions backend/engine/verify_snapshot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,3 +123,55 @@ func TestComputeFileSnapshot_NilInfo(t *testing.T) {
_, err := computeFileSnapshot(nil, t.TempDir())
require.Error(t, err)
}

// TestComputeFileSnapshot_ChangesOnTypeSwap covers the mode/type component of
// the per-file digest line. Swapping a regular file for a directory (a
// regular↔dir swap) must change the digest even though both entries exist —
// otherwise a planted directory/symlink could masquerade as the original file
// and slip past fast-resume. computeFileSnapshot digests st.Mode() (which
// carries the type bits) precisely to catch this.
func TestComputeFileSnapshot_ChangesOnTypeSwap(t *testing.T) {
saveTo := t.TempDir()
info := makeFakeTorrentTree(t, saveTo)

before, err := computeFileSnapshot(info, saveTo)
require.NoError(t, err)

// Replace the regular file a.txt with a directory of the same name. Size
// and even mtime may differ, but the load-bearing assertion is that the
// type change alone is reflected in the digest.
target := filepath.Join(saveTo, info.Name, "a.txt")
require.NoError(t, os.Remove(target))
require.NoError(t, os.Mkdir(target, 0o755))

after, err := computeFileSnapshot(info, saveTo)
require.NoError(t, err)
require.False(t, bytes.Equal(before, after), "regular→dir type swap must alter snapshot")
}

// TestComputeFileSnapshot_NotFollowSymlink verifies os.Lstat semantics: when a
// file is replaced by a symlink (even one pointing at content of the same
// size), the digest records the symlink's own mode rather than following it to
// the target — so the swap is detected. Guards against a symlink-redirection
// fast-resume bypass.
func TestComputeFileSnapshot_NotFollowSymlink(t *testing.T) {
saveTo := t.TempDir()
info := makeFakeTorrentTree(t, saveTo)

before, err := computeFileSnapshot(info, saveTo)
require.NoError(t, err)

// Replace a.txt (content "hello", 5 bytes) with a symlink to another file
// that also holds 5 bytes. If we followed the link via os.Stat the size
// would match and the digest could collide; with os.Lstat the symlink mode
// bit changes the digest.
target := filepath.Join(saveTo, info.Name, "a.txt")
decoy := filepath.Join(saveTo, "decoy.txt")
require.NoError(t, os.WriteFile(decoy, []byte("world"), 0o644))
require.NoError(t, os.Remove(target))
require.NoError(t, os.Symlink(decoy, target))

after, err := computeFileSnapshot(info, saveTo)
require.NoError(t, err)
require.False(t, bytes.Equal(before, after), "regular→symlink swap must alter snapshot (Lstat, not Stat)")
}
2 changes: 1 addition & 1 deletion backend/logging/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
// logDir/mosaic.log and pretty console output to stderr in debug mode.
// Returns a closer that flushes the file writer.
func Init(logDir string, debug bool) (io.Closer, error) {
if err := os.MkdirAll(logDir, 0o755); err != nil {
if err := os.MkdirAll(logDir, 0o700); err != nil {
return nil, err
}

Expand Down
8 changes: 7 additions & 1 deletion backend/notifications/beeep_notifier.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,15 @@ type BeeepNotifier struct{}
// "" to use a platform default. Errors from the underlying delivery surface
// are surfaced verbatim — the caller decides whether to log or ignore.
func (BeeepNotifier) Notify(title, body, icon string) error {
// Hold the lock across BOTH the AppName assignment and the Notify call:
// beeep.Notify reads the package-global beeep.AppName internally, so
// releasing the lock before Notify would let a concurrent Notify (or a
// transitive dep) stomp the value mid-read — a data race that could also
// send the notification under the wrong app name. Serializing the whole
// section is cheap (notifications are infrequent) and race-free.
appNameMu.Lock()
defer appNameMu.Unlock()
beeep.AppName = mosaicAppName
appNameMu.Unlock()
if icon == "" {
return beeep.Notify(title, body, nil)
}
Expand Down
Loading
Loading