diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 060ffc3..de1ab66 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -30,6 +30,37 @@ jobs: run: cd frontend && npm ci && npm run build - run: go test ./... -race -count=1 -timeout=300s + vuln: + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: '1.25' + cache: true + - uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'npm' + cache-dependency-path: frontend/package-lock.json + - name: Pre-build frontend for embed + # Same reason as the go job — //go:embed needs frontend/dist. + run: cd frontend && npm ci && npm run build + - name: Install Wails system deps + run: | + sudo apt-get update + sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.0-dev pkg-config + - name: govulncheck + # Advisory-only for now: govulncheck exits non-zero when it finds + # vulnerabilities in dependencies the code calls. Pre-existing + # vulns in golang.org/x/crypto and gofeed shouldn't block a PR + # that doesn't touch them — we surface the report in the CI logs + # and address the findings in a dedicated dependency-update PR. + continue-on-error: true + run: | + go install golang.org/x/vuln/cmd/govulncheck@latest + $(go env GOPATH)/bin/govulncheck ./... + frontend: runs-on: ubuntu-22.04 steps: diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..b5f7753 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Dylan Hart + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index 8f19366..ab0add9 100644 --- a/README.md +++ b/README.md @@ -87,4 +87,4 @@ Security: open a private advisory at [exec/mosaic/security/advisories/new](https ## License -© 2026 Dylan Hart. See [LICENSE](./LICENSE) once added; otherwise all rights reserved pending an explicit license declaration. +MIT — see [LICENSE](./LICENSE). diff --git a/backend/api/service.go b/backend/api/service.go index c5ab382..e831a8e 100644 --- a/backend/api/service.go +++ b/backend/api/service.go @@ -1,26 +1,12 @@ package api import ( - "bytes" - "context" "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "net/url" - "os" - "path/filepath" - "sort" - "strconv" "sync" "time" - "github.com/rs/zerolog/log" - "mosaic/backend/engine" "mosaic/backend/persistence" - "mosaic/backend/remote/cred" "mosaic/backend/updater" ) @@ -255,2300 +241,3 @@ const ( // watcher is absent; persists across launches so we don't nag. settingGnomeAppIndicatorDismissed = "desktop.gnome_appindicator_dismissed" ) - -// WebConfigDTO is the transport shape for the optional HTTP+WS interface. -// APIKey is only populated by RotateAPIKey (shown once); GetWebConfig returns -// the stored key so the UI can display it after navigation. -type WebConfigDTO struct { - Enabled bool `json:"enabled"` - Port int `json:"port"` - BindAll bool `json:"bind_all"` - Username string `json:"username"` - APIKey string `json:"api_key"` -} - -// adminUserID is the id of the admin account seeded by migration 0009. The -// desktop "Web Interface" pane and mosaicd's ephemeral-password bootstrap both -// operate on this user — it is the single login for the desktop build and the -// initial administrator on a fresh mosaicd install. -const adminUserID = 1 - -func (s *Service) GetWebConfig(ctx context.Context) WebConfigDTO { - if !CallerFrom(ctx).CanChangeSettings() { - return WebConfigDTO{} - } - port := s.intSetting(ctx, settingWebPort) - if port == 0 { - port = 8080 - } - dto := WebConfigDTO{ - Enabled: s.boolSetting(ctx, settingWebEnabled), - Port: port, - BindAll: s.boolSettingDefault(ctx, settingWebBindAll, false), - Username: "admin", - } - // Username + api-key hint live on the admin user row, not in settings. - if u, err := s.users.Get(ctx, adminUserID); err == nil { - dto.Username = u.Username - dto.APIKey = u.APIKeyHint - } - return dto -} - -func (s *Service) SetWebConfig(ctx context.Context, c WebConfigDTO) error { - if !CallerFrom(ctx).CanChangeSettings() { - return ErrForbidden - } - if err := s.setBoolSetting(ctx, settingWebEnabled, c.Enabled); err != nil { - return err - } - if err := s.setIntSetting(ctx, settingWebPort, c.Port); err != nil { - return err - } - if err := s.setBoolSetting(ctx, settingWebBindAll, c.BindAll); err != nil { - return err - } - // The desktop "Web Interface" pane edits the admin user's username here. - // A username change forces that user's sessions to re-authenticate. - if c.Username != "" { - u, err := s.users.Get(ctx, adminUserID) - if err == nil && u.Username != c.Username { - u.Username = c.Username - if err := s.users.Update(ctx, u); err != nil { - return err - } - s.invalidateCaller(adminUserID) - } - } - s.fireWebConfigChanged(s.GetWebConfig(ctx)) - return nil -} - -// OnWebConfigChange registers a callback invoked (synchronously) after a -// SetWebConfig call commits. The callback receives the freshly-read DTO so -// the remote.Server can restart with the new bind/port/enabled state. -// Pass nil to unregister. -func (s *Service) OnWebConfigChange(cb func(WebConfigDTO)) { - s.webHookMu.Lock() - s.onWebCfgChanged = cb - s.webHookMu.Unlock() -} - -func (s *Service) fireWebConfigChanged(c WebConfigDTO) { - s.webHookMu.RLock() - cb := s.onWebCfgChanged - s.webHookMu.RUnlock() - if cb != nil { - cb(c) - } -} - -// SetWebPassword sets the admin user's password (UI / REST "change password" -// path) and marks it operator-set so mosaicd stops minting ephemeral ones. -// Every active session for that user is revoked. The hash + password_set flag -// are written by a single atomic UPDATE, so there is no partial-failure window. -func (s *Service) SetWebPassword(ctx context.Context, plain string) error { - if !CallerFrom(ctx).CanManageUsers() { - return ErrForbidden - } - if err := s.setUserPasswordHash(ctx, adminUserID, plain, true); err != nil { - return err - } - s.invalidateCaller(adminUserID) - return nil -} - -// SetWebPasswordEphemeral sets the admin user's password without flipping the -// "user set" flag and without touching active sessions. Used only by mosaicd's -// per-restart auto-generated password flow (qBittorrent-nox style). -func (s *Service) SetWebPasswordEphemeral(ctx context.Context, plain string) error { - return s.setUserPasswordHash(ctx, adminUserID, plain, false) -} - -// IsWebPasswordUserSet reports whether the admin user's password was set -// explicitly by the operator. mosaicd consults it to decide whether to mint a -// fresh ephemeral password on each boot. Fail-safe default is true: if the -// admin row is unreadable for any reason, we report "operator-set" so we don't -// silently regenerate a password over the operator's existing one. -func (s *Service) IsWebPasswordUserSet(ctx context.Context) bool { - u, err := s.users.Get(ctx, adminUserID) - if err != nil { - return true - } - return u.PasswordSet -} - -func (s *Service) setUserPasswordHash(ctx context.Context, userID int, plain string, userSet bool) error { - hash, err := cred.HashPassword(plain) - if err != nil { - return err - } - return s.users.SetPasswordHash(ctx, userID, hash, userSet) -} - -// RotateAPIKey mints a fresh API key for the admin user (desktop "Web -// Interface" pane). The cleartext is returned once — only its hash is stored. -func (s *Service) RotateAPIKey(ctx context.Context) (string, error) { - if !CallerFrom(ctx).CanManageUsers() { - return "", ErrForbidden - } - return s.RotateUserAPIKey(ctx, adminUserID) -} - -// ReconcileLegacyAPIKey migrates a pre-0009 plaintext web_api_key setting into -// the admin user's hashed key column, then clears the setting. Idempotent and -// safe to call on every startup: it no-ops once the legacy key is gone or the -// admin already has a key. -func (s *Service) ReconcileLegacyAPIKey(ctx context.Context) error { - legacy, _ := s.settings.Get(ctx, settingWebAPIKey) - if legacy == "" { - return nil - } - u, err := s.users.Get(ctx, adminUserID) - if err != nil { - return err - } - if u.APIKeyHash == "" { - if err := s.users.SetAPIKey(ctx, adminUserID, - cred.HashAPIKey(legacy), cred.APIKeyHint(legacy)); err != nil { - return err - } - } - return s.settings.Set(ctx, settingWebAPIKey, "") -} - -// UpdaterConfigDTO is the persisted updater preferences shape (channel + -// enabled toggle + cached last-check metadata for UI display). -type UpdaterConfigDTO struct { - Enabled bool `json:"enabled"` - Channel string `json:"channel"` // "stable" | "beta" - LastCheckedAt int64 `json:"last_checked_at"` // unix seconds - LastSeenVersion string `json:"last_seen_version"` - // InstallSource classifies how this binary was installed: "apt" - // (managed by apt — auto-updater is dormant), "appimage", or - // "manual". The SPA renders Updates pane copy off this field. - InstallSource string `json:"install_source"` -} - -// UpdateInfoDTO mirrors updater.Info plus CurrentVersion so the UI can render -// "X → Y" without needing a separate AppVersion call. -type UpdateInfoDTO struct { - Available bool `json:"available"` - LatestVersion string `json:"latest_version"` - AssetURL string `json:"asset_url"` - AssetFilename string `json:"asset_filename"` - CheckedAt int64 `json:"checked_at"` // unix seconds - CurrentVersion string `json:"current_version"` -} - -// AttachUpdater wires the live *updater.Updater + build-time version into the -// Service after construction. main.go calls this once at startup; tests can -// leave it unset to exercise the disabled-updater path. -// -// installSource is the freshly-detected classification of how the running -// binary was installed (apt / appimage / manual). The SPA reads it via -// UpdaterConfigDTO so the Updates pane can render an "apt-managed — use -// `apt upgrade` to update" banner instead of a misleading toggle. -func (s *Service) AttachUpdater(u *updater.Updater, version string, installSource updater.InstallSource) { - s.updater = u - s.appVersion = version - s.installSource = installSource -} - -// AttachWatchFolder wires the live *WatchFolder into the Service so that -// SetWatchFolder can (re)start the polling loop when the user changes the -// configuration. main.go calls this once after construction. -func (s *Service) AttachWatchFolder(w *WatchFolder) { - s.watchFolder = w -} - -// WatchFolderDTO is the transport shape for the watch-folder settings. -type WatchFolderDTO struct { - Path string `json:"path"` - DeleteAfterAdd bool `json:"delete_after_add"` - Enabled bool `json:"enabled"` -} - -// GetWatchFolder reads the current watch-folder configuration from settings. -func (s *Service) GetWatchFolder(ctx context.Context) WatchFolderDTO { - if !CallerFrom(ctx).CanChangeSettings() { - return WatchFolderDTO{} - } - path, _ := s.settings.Get(ctx, settingWatchFolderPath) - return WatchFolderDTO{ - Path: path, - DeleteAfterAdd: s.boolSetting(ctx, settingWatchFolderDeleteAfterAdd), - Enabled: s.boolSetting(ctx, settingWatchFolderEnabled), - } -} - -// SetWatchFolder persists the watch-folder configuration and (re)starts or -// stops the watcher accordingly. -func (s *Service) SetWatchFolder(ctx context.Context, c WatchFolderDTO) error { - // Admin-only: the path is an unconfined server-side directory the daemon - // will read from — and, with DeleteAfterAdd, delete files in. That is a - // filesystem-reach primitive, not an ordinary preference, so it sits above - // the delegable PermChangeSettings flag. Reads (GetWatchFolder) stay under - // CanChangeSettings so a settings-delegate can still see the config. - if !CallerFrom(ctx).IsAdmin() { - return ErrForbidden - } - if err := s.settings.Set(ctx, settingWatchFolderPath, c.Path); err != nil { - return err - } - if err := s.setBoolSetting(ctx, settingWatchFolderDeleteAfterAdd, c.DeleteAfterAdd); err != nil { - return err - } - if err := s.setBoolSetting(ctx, settingWatchFolderEnabled, c.Enabled); err != nil { - return err - } - if s.watchFolder != nil { - if c.Enabled && c.Path != "" { - s.watchFolder.Start(c.Path, c.DeleteAfterAdd) - } else { - s.watchFolder.Stop() - } - } - return nil -} - -// AppVersion returns the build-time version string the Service was set with. -// Empty string if neither SetAppVersion nor AttachUpdater has been called. -func (s *Service) AppVersion() string { - return s.appVersion -} - -// SetAppVersion records the build-time version on the Service so AppVersion() -// (and the /api/version endpoint behind it) can return it even when the -// updater isn't wired — notably in the daemon, where auto-update is -// intentionally not attached. AttachUpdater also writes this field, so calling -// SetAppVersion before AttachUpdater is safe and the values will match. -func (s *Service) SetAppVersion(version string) { - s.appVersion = version -} - -// UpdaterEnabled reports whether the auto-update goroutine should run. The -// setting defaults to true (if absent in the settings table). Stored as -// "true" / "false" strings via setBoolSetting. -func (s *Service) UpdaterEnabled(ctx context.Context) bool { - v, err := s.settings.Get(ctx, settingUpdaterEnabled) - if err != nil || v == "" { - return true - } - return v == "true" -} - -// UpdaterChannel returns the configured update channel ("stable" by default). -func (s *Service) UpdaterChannel(ctx context.Context) string { - ch, _ := s.settings.Get(ctx, settingUpdaterChannel) - if ch == "" { - return "stable" - } - return ch -} - -func (s *Service) GetUpdaterConfig(ctx context.Context) UpdaterConfigDTO { - if !CallerFrom(ctx).CanChangeSettings() { - return UpdaterConfigDTO{} - } - seen, _ := s.settings.Get(ctx, settingUpdaterLastSeenVersion) - src := string(s.installSource) - if src == "" { - src = string(updater.InstallSourceManual) - } - return UpdaterConfigDTO{ - Enabled: s.UpdaterEnabled(ctx), - Channel: s.UpdaterChannel(ctx), - LastCheckedAt: int64(s.intSetting(ctx, settingUpdaterLastChecked)), - LastSeenVersion: seen, - InstallSource: src, - } -} - -func (s *Service) SetUpdaterConfig(ctx context.Context, c UpdaterConfigDTO) error { - // Admin-only, not merely CanChangeSettings: the updater downloads and - // swaps the running server binary, so steering its channel/enablement is a - // host-integrity operation, not an ordinary preference. PermChangeSettings - // is a delegable, sub-admin flag and must not reach this far. - if !CallerFrom(ctx).IsAdmin() { - return ErrForbidden - } - if c.Channel != "stable" && c.Channel != "beta" { - return fmt.Errorf("channel must be stable or beta") - } - if err := s.setBoolSetting(ctx, settingUpdaterEnabled, c.Enabled); err != nil { - return err - } - if err := s.settings.Set(ctx, settingUpdaterChannel, c.Channel); err != nil { - return err - } - s.fireUpdaterConfigChanged(s.GetUpdaterConfig(ctx)) - return nil -} - -// OnUpdaterConfigChange registers a synchronous callback invoked after a -// SetUpdaterConfig commit, mirroring OnWebConfigChange / -// OnDesktopIntegrationChange. main.go uses it to push channel changes into -// the live GitHubSource and to start/stop the periodic check goroutine — -// without it, both silently required an app restart. Pass nil to unregister. -// Only one callback is supported. The daemon never registers one (auto-update -// is intentionally not wired there); firing is nil-safe. -func (s *Service) OnUpdaterConfigChange(cb func(UpdaterConfigDTO)) { - s.updaterHookMu.Lock() - s.onUpdaterChanged = cb - s.updaterHookMu.Unlock() -} - -func (s *Service) fireUpdaterConfigChanged(c UpdaterConfigDTO) { - s.updaterHookMu.RLock() - cb := s.onUpdaterChanged - s.updaterHookMu.RUnlock() - if cb != nil { - cb(c) - } -} - -func (s *Service) CheckForUpdate(ctx context.Context) (UpdateInfoDTO, error) { - // Same admin-only gate as InstallUpdate / SetUpdaterConfig: the check - // performs an outbound HTTP request and writes two settings rows, and it is - // the precursor to an install, so it belongs to the same host-integrity - // boundary rather than the delegable PermChangeSettings flag. - if !CallerFrom(ctx).IsAdmin() { - return UpdateInfoDTO{}, ErrForbidden - } - if s.updater == nil { - return UpdateInfoDTO{CurrentVersion: s.appVersion}, fmt.Errorf("updater disabled") - } - info, err := s.updater.Check(ctx) - if err != nil { - return UpdateInfoDTO{CurrentVersion: s.appVersion}, err - } - _ = s.setIntSetting(ctx, settingUpdaterLastChecked, int(info.CheckedAt.Unix())) - if info.Available { - _ = s.settings.Set(ctx, settingUpdaterLastSeenVersion, info.LatestVersion) - } - return UpdateInfoDTO{ - Available: info.Available, - LatestVersion: info.LatestVersion, - AssetURL: info.AssetURL, - AssetFilename: info.AssetFilename, - CheckedAt: info.CheckedAt.Unix(), - CurrentVersion: s.appVersion, - }, nil -} - -func (s *Service) InstallUpdate(ctx context.Context) error { - // Admin-only: this replaces the running server binary. A non-admin holding - // the delegable PermChangeSettings flag must not be able to swap the host's - // executable. - if !CallerFrom(ctx).IsAdmin() { - return ErrForbidden - } - if s.updater == nil { - return fmt.Errorf("updater disabled") - } - if s.installSource == updater.InstallSourceAPT { - return fmt.Errorf("this Mosaic is managed by apt — run `sudo apt update && sudo apt upgrade mosaic` to update") - } - last := s.updater.Last() - if err := s.updater.Install(ctx, last); err != nil { - return err - } - // Fire the desktop notification (if a Notifier was attached and the user - // hasn't disabled the notify_on_update toggle — the Notifier itself does - // the toggle gating). Done here rather than from a hook in the updater - // package because updater.Updater doesn't expose an OnInstalled callback. - if s.updateInstalledNotifier != nil { - s.updateInstalledNotifier.NotifyUpdateInstalled(last.LatestVersion) - } - return nil -} - -// MakeUpdateInfoDTO converts a raw updater.Info to the API DTO. Used by main.go -// to wrap OnAvailable callback payloads for the WS/Wails event emission. -func (s *Service) MakeUpdateInfoDTO(info updater.Info) UpdateInfoDTO { - return UpdateInfoDTO{ - Available: info.Available, - LatestVersion: info.LatestVersion, - AssetURL: info.AssetURL, - AssetFilename: info.AssetFilename, - CheckedAt: info.CheckedAt.Unix(), - CurrentVersion: s.appVersion, - } -} - -// DesktopIntegrationDTO is the transport shape for system-tray + notifications -// + close-to-tray preferences. The frontend keys off these JSON names; do not -// rename without coordinating with the frontend agent owning the settings UI. -type DesktopIntegrationDTO struct { - TrayEnabled bool `json:"tray_enabled"` // default true - CloseToTray bool `json:"close_to_tray"` // default true on Linux/Windows when tray is enabled; ignored on macOS - StartMinimized bool `json:"start_minimized"` // default false — start hidden in tray, no window - NotifyOnComplete bool `json:"notify_on_complete"` // default true - NotifyOnError bool `json:"notify_on_error"` // default true - NotifyOnUpdate bool `json:"notify_on_update"` // default true -} - -// boolSettingDefault reads a bool setting with a presence-aware default — -// "" (never written) returns def, otherwise "true"/"false" parses normally. -// This is the shape we want for DesktopIntegrationDTO defaults: a fresh DB -// must yield TrayEnabled=true even though boolSetting alone would return false. -func (s *Service) boolSettingDefault(ctx context.Context, key string, def bool) bool { - v, err := s.settings.Get(ctx, key) - if err != nil || v == "" { - return def - } - return v == "true" -} - -func (s *Service) GetDesktopIntegration(ctx context.Context) DesktopIntegrationDTO { - return DesktopIntegrationDTO{ - TrayEnabled: s.boolSettingDefault(ctx, settingDesktopTrayEnabled, true), - // Default true (when tray is enabled): closing the window into a - // running tray icon matches every mainstream client (qBittorrent, - // Discord, Slack, Steam). Default-off was surprising — users - // closed the window expecting standard "minimize to tray" UX and - // instead lost their session. Users who want close = quit can - // flip this off in Settings → Desktop Integration. - CloseToTray: s.boolSettingDefault(ctx, settingDesktopCloseToTray, true), - StartMinimized: s.boolSettingDefault(ctx, settingDesktopStartMinimized, false), - NotifyOnComplete: s.boolSettingDefault(ctx, settingDesktopNotifyOnComplete, true), - NotifyOnError: s.boolSettingDefault(ctx, settingDesktopNotifyOnError, true), - NotifyOnUpdate: s.boolSettingDefault(ctx, settingDesktopNotifyOnUpdate, true), - } -} - -// SetDesktopIntegration persists the user's desktop-integration preferences -// and fires the change hook so the running tray/notifications goroutines can -// reconfigure themselves. No validation: the user is allowed to disable -// everything (a perfectly reasonable choice). -func (s *Service) SetDesktopIntegration(ctx context.Context, c DesktopIntegrationDTO) error { - if !CallerFrom(ctx).CanChangeSettings() { - return ErrForbidden - } - if err := s.setBoolSetting(ctx, settingDesktopTrayEnabled, c.TrayEnabled); err != nil { - return err - } - if err := s.setBoolSetting(ctx, settingDesktopCloseToTray, c.CloseToTray); err != nil { - return err - } - if err := s.setBoolSetting(ctx, settingDesktopStartMinimized, c.StartMinimized); err != nil { - return err - } - if err := s.setBoolSetting(ctx, settingDesktopNotifyOnComplete, c.NotifyOnComplete); err != nil { - return err - } - if err := s.setBoolSetting(ctx, settingDesktopNotifyOnError, c.NotifyOnError); err != nil { - return err - } - if err := s.setBoolSetting(ctx, settingDesktopNotifyOnUpdate, c.NotifyOnUpdate); err != nil { - return err - } - s.fireDesktopIntegrationChanged(c) - return nil -} - -// IsGnomeAppIndicatorPromptDismissed reports whether the user has -// previously clicked Dismiss on the in-app Gnome AppIndicator prompt. -// Once true, the SPA stops showing the prompt even if the tray watcher -// is still absent — manual re-trigger via Settings would be the path -// back to nagging if we ever surface that. -func (s *Service) IsGnomeAppIndicatorPromptDismissed(ctx context.Context) bool { - v, _ := s.settings.Get(ctx, settingGnomeAppIndicatorDismissed) - return v == "true" -} - -// DismissGnomeAppIndicatorPrompt persists the "user said no" flag. -func (s *Service) DismissGnomeAppIndicatorPrompt(ctx context.Context) error { - return s.settings.Set(ctx, settingGnomeAppIndicatorDismissed, "true") -} - -// OnDesktopIntegrationChange registers a synchronous callback invoked after a -// SetDesktopIntegration commit. main.go uses this to push the updated -// notification toggles into the live notifications.Subscriber. Pass nil to -// unregister. Only one callback is supported. -func (s *Service) OnDesktopIntegrationChange(cb func(DesktopIntegrationDTO)) { - s.desktopHookMu.Lock() - s.onDesktopChanged = cb - s.desktopHookMu.Unlock() -} - -func (s *Service) fireDesktopIntegrationChanged(c DesktopIntegrationDTO) { - s.desktopHookMu.RLock() - cb := s.onDesktopChanged - s.desktopHookMu.RUnlock() - if cb != nil { - cb(c) - } -} - -func (s *Service) GetDefaultSavePath(ctx context.Context) (string, error) { - v, err := s.settings.Get(ctx, settingDefaultSavePath) - if errors.Is(err, persistence.ErrNotFound) { - return s.defaultSavePath, nil - } - if err != nil { - return "", err - } - return v, nil -} - -func (s *Service) SetDefaultSavePath(ctx context.Context, path string) error { - if !CallerFrom(ctx).CanChangeSettings() { - return ErrForbidden - } - return s.settings.Set(ctx, settingDefaultSavePath, path) -} - -func (s *Service) defaultPath(ctx context.Context) string { - if v, err := s.GetDefaultSavePath(ctx); err == nil { - return v - } - return s.defaultSavePath -} - -// TorrentDTO is the shape returned to UI/transport callers. -type TorrentDTO struct { - ID string `json:"id"` - Name string `json:"name"` - Magnet string `json:"magnet"` - SavePath string `json:"save_path"` - TotalBytes int64 `json:"total_bytes"` - BytesDone int64 `json:"bytes_done"` - Progress float64 `json:"progress"` // 0..1 - DownloadRate int64 `json:"download_rate"` - UploadRate int64 `json:"upload_rate"` - Peers int `json:"peers"` - Seeds int `json:"seeds"` - Paused bool `json:"paused"` - Completed bool `json:"completed"` - AddedAt int64 `json:"added_at"` // unix seconds - CategoryID *int `json:"category_id"` - Tags []TagDTO `json:"tags"` - QueuePosition int `json:"queue_position"` - ForceStart bool `json:"force_start"` - Sequential bool `json:"sequential"` - Queued bool `json:"queued"` - Verifying bool `json:"verifying"` - FilesMissing bool `json:"files_missing"` - // Access is the requesting caller's access level on this torrent - // ("owner" | "editor" | "viewer"). Admins always see "owner". The SPA - // uses it to gate per-row controls. - Access string `json:"access"` -} - -// unixOrZero serializes a record timestamp for the wire, mapping the zero -// time (record missing or lookup failed) to 0. time.Time{}.Unix() is -// -62135596800, which the SPA would render as a date in year 1. -func unixOrZero(t time.Time) int64 { - if t.IsZero() { - return 0 - } - return t.Unix() -} - -func toDTO(s engine.Snapshot, addedAt time.Time) TorrentDTO { - prog := 0.0 - if s.TotalBytes > 0 { - prog = float64(s.BytesDone) / float64(s.TotalBytes) - } - return TorrentDTO{ - ID: string(s.ID), - Name: s.Name, - Magnet: s.Magnet, - SavePath: s.SavePath, - TotalBytes: s.TotalBytes, - BytesDone: s.BytesDone, - Progress: prog, - DownloadRate: s.RateDown, - UploadRate: s.RateUp, - Peers: s.Peers, - Seeds: s.Seeds, - Paused: s.Paused, - Completed: s.Completed, - AddedAt: unixOrZero(addedAt), - QueuePosition: s.QueuePosition, - ForceStart: s.ForceStart, - Sequential: s.Sequential, - Queued: s.Queued, - Verifying: s.Verifying, - FilesMissing: s.FilesMissing, - } -} - -func (s *Service) AddMagnet(ctx context.Context, magnet, savePath string) (engine.TorrentID, error) { - caller := CallerFrom(ctx) - if !caller.CanAddTorrents() { - return "", ErrForbidden - } - savePath, err := s.resolveSavePath(ctx, caller, savePath) - if err != nil { - return "", err - } - id, err := s.engine.AddMagnet(ctx, magnet, savePath) - if err != nil { - return "", fmt.Errorf("add magnet: %w", err) - } - snap, err := s.engine.Snapshot(id) - if err != nil { - // Highly unlikely directly after AddMagnet, but if it happens we can't - // build a record without the name — roll the engine add back rather - // than leave a torrent we can't track. - if rmErr := s.engine.Remove(id, false); rmErr != nil { - log.Warn().Err(rmErr).Str("infohash", string(id)).Msg("AddMagnet: engine rollback after snapshot failure also failed") - } - return "", err - } - if err := s.persistAndGrantTorrent(ctx, id, caller, persistence.TorrentRecord{ - InfoHash: string(id), - Name: snap.Name, - Magnet: magnet, - SavePath: savePath, - AddedAt: time.Now(), - }); err != nil { - return "", err - } - return id, nil -} - -// grantOwner records that the caller owns a torrent. Adding an infohash that -// another user already added makes the caller a co-owner (Grant upserts). -func (s *Service) grantOwner(ctx context.Context, infohash string, caller Caller) error { - uid := caller.UserID - return s.access.Grant(ctx, infohash, uid, persistence.AccessOwner, &uid) -} - -// persistAndGrantTorrent runs the post-engine-add steps (persist record, -// record ownership) with rollback semantics. The caller has already added the -// torrent to the engine and provides the persistence record. Without this -// rollback, a failed Save left the torrent in the engine but absent from the -// DB — it would download for the rest of this session, then vanish on next -// restart (RestoreOnStartup walks the DB, not the engine). A failed grantOwner -// left an orphaned, ownerless record visible to admins only. -// -// engine.Remove is called with deleteFiles=false: the operation just failed, -// nothing material has been downloaded yet, and we don't want to clobber -// anything that might have. Rollback errors are logged but not returned — -// the original failure is what the caller needs to see. -func (s *Service) persistAndGrantTorrent(ctx context.Context, id engine.TorrentID, caller Caller, rec persistence.TorrentRecord) error { - if err := s.torrents.Save(ctx, rec); err != nil { - if rmErr := s.engine.Remove(id, false); rmErr != nil { - log.Warn().Err(rmErr).Str("infohash", string(id)).Msg("add torrent: engine rollback after persist failure also failed; torrent will linger until restart") - } - return fmt.Errorf("persist: %w", err) - } - if err := s.grantOwner(ctx, string(id), caller); err != nil { - if rmErr := s.torrents.Remove(ctx, string(id)); rmErr != nil { - log.Warn().Err(rmErr).Str("infohash", string(id)).Msg("add torrent: persist rollback after grant failure also failed; record will survive as orphaned") - } - if rmErr := s.engine.Remove(id, false); rmErr != nil { - log.Warn().Err(rmErr).Str("infohash", string(id)).Msg("add torrent: engine rollback after grant failure also failed; torrent will linger until restart") - } - return fmt.Errorf("grant owner: %w", err) - } - return nil -} - -// resolveSavePath returns the cleaned absolute save path the engine should -// MkdirAll into, after applying the per-user containment policy. -// -// Admins (including the system caller used by the Wails desktop and internal -// workers) keep unrestricted behavior — the operator already has shell access -// to the host. Non-admin callers are pinned to /: -// an unconstrained save_path would let a low-privilege multi-user mosaicd -// account write torrent data into arbitrary directories the daemon process -// can reach (/etc/cron.d, another user's home, the daemon's data dir). -func (s *Service) resolveSavePath(ctx context.Context, caller Caller, savePath string) (string, error) { - if caller.IsAdmin() { - if savePath == "" { - savePath = s.defaultPath(ctx) - } - return engine.ValidateSavePath("", savePath, false) - } - if caller.Username == "" || s.defaultSavePath == "" { - return "", ErrForbidden - } - userRoot := filepath.Join(s.defaultSavePath, caller.Username) - if savePath == "" { - savePath = userRoot - } - return engine.ValidateSavePath(userRoot, savePath, true) -} - -// requireTorrentAccess returns ErrForbidden unless the caller holds at least -// minLevel access on the torrent. Admins and the system caller always pass. -func (s *Service) requireTorrentAccess(ctx context.Context, infohash, minLevel string) error { - caller := CallerFrom(ctx) - if caller.SeesAllTorrents() { - return nil - } - lvl, err := s.access.AccessFor(ctx, infohash, caller.UserID) - if err != nil { - return err - } - if persistence.AccessRank(lvl) < persistence.AccessRank(minLevel) { - return ErrForbidden - } - return nil -} - -func (s *Service) AddTorrentFile(ctx context.Context, filePath, savePath string) (engine.TorrentID, error) { - caller := CallerFrom(ctx) - if !caller.CanAddTorrents() { - return "", ErrForbidden - } - savePath, err := s.resolveSavePath(ctx, caller, savePath) - if err != nil { - return "", err - } - blob, err := os.ReadFile(filePath) - if err != nil { - return "", fmt.Errorf("read torrent file: %w", err) - } - id, err := s.engine.AddFile(ctx, blob, savePath) - if err != nil { - return "", fmt.Errorf("add torrent: %w", err) - } - snap, err := s.engine.Snapshot(id) - if err != nil { - if rmErr := s.engine.Remove(id, false); rmErr != nil { - log.Warn().Err(rmErr).Str("infohash", string(id)).Msg("AddTorrentFile: engine rollback after snapshot failure also failed") - } - return "", err - } - if err := s.persistAndGrantTorrent(ctx, id, caller, persistence.TorrentRecord{ - InfoHash: string(id), - Name: snap.Name, - SavePath: savePath, - AddedAt: time.Now(), - Metainfo: blob, - }); err != nil { - return "", err - } - return id, nil -} - -func (s *Service) AddTorrentBytes(ctx context.Context, blob []byte, savePath string) (engine.TorrentID, error) { - caller := CallerFrom(ctx) - if !caller.CanAddTorrents() { - return "", ErrForbidden - } - savePath, err := s.resolveSavePath(ctx, caller, savePath) - if err != nil { - return "", err - } - id, err := s.engine.AddFile(ctx, blob, savePath) - if err != nil { - return "", fmt.Errorf("add torrent bytes: %w", err) - } - snap, err := s.engine.Snapshot(id) - if err != nil { - if rmErr := s.engine.Remove(id, false); rmErr != nil { - log.Warn().Err(rmErr).Str("infohash", string(id)).Msg("AddTorrentBytes: engine rollback after snapshot failure also failed") - } - return "", err - } - if err := s.persistAndGrantTorrent(ctx, id, caller, persistence.TorrentRecord{ - InfoHash: string(id), - Name: snap.Name, - SavePath: savePath, - AddedAt: time.Now(), - Metainfo: blob, - }); err != nil { - return "", err - } - return id, nil -} - -// Pause/Resume/Recheck require editor-or-higher access on the torrent. -func (s *Service) Pause(ctx context.Context, id engine.TorrentID) error { - if err := s.requireTorrentAccess(ctx, string(id), persistence.AccessEditor); err != nil { - return err - } - if err := s.engine.Pause(id); err != nil { - return err - } - // Persist so the pause survives a restart (RestoreOnStartup re-pauses - // from the paused column). Log-don't-fail: the engine state is already - // applied and a DB hiccup shouldn't surface as a failed pause. - if err := s.torrents.SetPaused(ctx, string(id), true); err != nil { - log.Warn().Err(err).Str("id", string(id)).Msg("Pause: persist paused state failed") - } - return nil -} - -func (s *Service) Resume(ctx context.Context, id engine.TorrentID) error { - if err := s.requireTorrentAccess(ctx, string(id), persistence.AccessEditor); err != nil { - return err - } - if err := s.engine.Resume(id); err != nil { - return err - } - if err := s.torrents.SetPaused(ctx, string(id), false); err != nil { - log.Warn().Err(err).Str("id", string(id)).Msg("Resume: persist paused state failed") - } - return nil -} - -func (s *Service) Recheck(ctx context.Context, id engine.TorrentID) error { - if err := s.requireTorrentAccess(ctx, string(id), persistence.AccessEditor); err != nil { - return err - } - return s.engine.Recheck(id) -} - -// PauseAll pauses every torrent currently known to the engine. Errors on -// individual torrents are logged but don't abort the loop — best-effort -// semantics so a single missing/dead torrent can't strand the rest. -// Used by the system-tray "Pause all" item. -func (s *Service) PauseAll(ctx context.Context) { - for _, snap := range s.engine.List() { - if snap.Paused { - continue - } - if err := s.engine.Pause(snap.ID); err != nil { - log.Warn().Err(err).Str("id", string(snap.ID)).Msg("PauseAll: pause failed") - continue - } - if err := s.torrents.SetPaused(ctx, string(snap.ID), true); err != nil { - log.Warn().Err(err).Str("id", string(snap.ID)).Msg("PauseAll: persist paused state failed") - } - } -} - -// ResumeAll is the mirror of PauseAll. Used by the system-tray "Resume all" -// item when the engine is in the globally-paused state. -func (s *Service) ResumeAll(ctx context.Context) { - for _, snap := range s.engine.List() { - if !snap.Paused { - continue - } - if err := s.engine.Resume(snap.ID); err != nil { - log.Warn().Err(err).Str("id", string(snap.ID)).Msg("ResumeAll: resume failed") - continue - } - if err := s.torrents.SetPaused(ctx, string(snap.ID), false); err != nil { - log.Warn().Err(err).Str("id", string(snap.ID)).Msg("ResumeAll: persist paused state failed") - } - } -} - -// UpdateInstalledNotifier is the post-install hook the desktop-integration -// notifications package implements. Defining the contract as an interface -// here keeps the api package free of a notifications-package import. -type UpdateInstalledNotifier interface { - NotifyUpdateInstalled(version string) -} - -// AttachUpdateInstalledNotifier wires the notifications subscriber into the -// Service so InstallUpdate can fire the OS-level notification on success. -// Pass nil (or never call) to disable the post-install notification. -func (s *Service) AttachUpdateInstalledNotifier(n UpdateInstalledNotifier) { - s.updateInstalledNotifier = n -} - -// Remove tears a torrent down or detaches it from the caller's view. An admin -// (or the last remaining owner) fully removes it from the engine + database; -// any other user with access just loses their own grant — the torrent keeps -// running for everyone else. A caller with no access gets ErrForbidden. -func (s *Service) Remove(ctx context.Context, id engine.TorrentID, deleteFiles bool) error { - caller := CallerFrom(ctx) - hash := string(id) - if !caller.SeesAllTorrents() { - lvl, err := s.access.AccessFor(ctx, hash, caller.UserID) - if err != nil { - return err - } - if lvl == "" { - return ErrForbidden - } - if lvl != persistence.AccessOwner { - return s.access.Revoke(ctx, hash, caller.UserID) - } - owners, err := s.access.OwnerCount(ctx, hash) - if err != nil { - return err - } - if owners > 1 { - return s.access.Revoke(ctx, hash, caller.UserID) - } - } - if err := s.engine.Remove(id, deleteFiles); err != nil { - return err - } - // torrent_access rows cascade-delete with the torrents row. - return s.torrents.Remove(ctx, hash) -} - -// TorrentTickSnapshot is the per-tick state shared across every connected -// user: the engine's torrent snapshots, the persistence records keyed by -// infohash, and the tags map. None of it is caller-dependent, so mosaicd's -// streamTicks builds it ONCE per tick (see BuildTorrentTickSnapshot) and then -// fans it out — instead of re-running torrents.List + tags.ForAllTorrents + -// the full engine walk once per connected user. -type TorrentTickSnapshot struct { - snaps []engine.Snapshot - byHash map[string]persistence.TorrentRecord - tagsByHash map[string][]persistence.Tag -} - -// BuildTorrentTickSnapshot gathers the caller-independent torrent state for -// one tick. Call it once, then pass the result to ListTorrentsFromSnapshot / -// GlobalStatsFromSnapshot for each connected user. -func (s *Service) BuildTorrentTickSnapshot(ctx context.Context) (TorrentTickSnapshot, error) { - records, err := s.torrents.List(ctx) - if err != nil { - return TorrentTickSnapshot{}, err - } - byHash := make(map[string]persistence.TorrentRecord, len(records)) - for _, r := range records { - byHash[r.InfoHash] = r - } - // Pre-v0.4.3 we called s.tags.ForTorrent(ctx, infohash) inside the DTO - // loop — N+1 SELECTs every tick (~500ms cadence). One bulk fetch instead, - // hashed by infohash so assembly is an O(1) lookup. - tagsByHash, err := s.tags.ForAllTorrents(ctx) - if err != nil { - return TorrentTickSnapshot{}, err - } - snaps := s.engine.List() - // Persist completed_at the first time we observe a torrent complete. - // Every flavor's tick path funnels through here, so this is the one - // choke point where the service sees the completion transition. The - // record's nil check keeps the write to exactly once per torrent — - // RestoreOnStartup reads the column to arm missing-files detection, and - // the inspector surfaces it as DetailDTO.CompletedAt. - now := time.Now() - for _, snap := range snaps { - rec, ok := byHash[string(snap.ID)] - if !ok || !snap.Completed || rec.CompletedAt != nil { - continue - } - if err := s.torrents.SetCompletedAt(ctx, string(snap.ID), now); err != nil { - log.Warn().Err(err).Str("id", string(snap.ID)).Msg("tick: persist completed_at failed") - continue - } - t := now - rec.CompletedAt = &t - byHash[string(snap.ID)] = rec - } - return TorrentTickSnapshot{ - snaps: snaps, - byHash: byHash, - tagsByHash: tagsByHash, - }, nil -} - -func (s *Service) ListTorrents(ctx context.Context) ([]TorrentDTO, error) { - tick, err := s.BuildTorrentTickSnapshot(ctx) - if err != nil { - return nil, err - } - return s.ListTorrentsFromSnapshot(ctx, tick) -} - -// ListTorrentsFromSnapshot assembles a caller's torrent DTO list from an -// already-built TorrentTickSnapshot. The shared snapshot is byte-identical -// across users; only the access filter, per-user Access level, sort, and DTO -// assembly happen here — so streamTicks pays the DB/engine cost once per tick -// rather than once per connected user. Output matches the old per-user -// ListTorrents exactly. -func (s *Service) ListTorrentsFromSnapshot(ctx context.Context, tick TorrentTickSnapshot) ([]TorrentDTO, error) { - caller := CallerFrom(ctx) - // Non-admin callers see only torrents they hold an access grant for. - var accessByHash map[string]string - if !caller.SeesAllTorrents() { - var err error - accessByHash, err = s.access.InfohashesForUser(ctx, caller.UserID) - if err != nil { - return nil, err - } - } - out := make([]TorrentDTO, 0, len(tick.snaps)) - for _, snap := range tick.snaps { - hash := string(snap.ID) - access := persistence.AccessOwner - if !caller.SeesAllTorrents() { - lvl, visible := accessByHash[hash] - if !visible { - continue - } - access = lvl - } - rec, ok := tick.byHash[hash] - // No DB record (engine-only torrent, e.g. a restore raced the tick): - // use the zero time, which unixOrZero serializes as added_at=0. A - // fresh time.Now() here changed every tick, scrambling the added_at - // sort below and defeating streamTicks' frame dedup. - var addedAt time.Time - if ok { - snap.SavePath = rec.SavePath - if snap.Magnet == "" { - snap.Magnet = rec.Magnet - } - addedAt = rec.AddedAt - } - dto := toDTO(snap, addedAt) - dto.Access = access - if ok { - dto.CategoryID = rec.CategoryID - } - tags := tick.tagsByHash[hash] - dto.Tags = make([]TagDTO, 0, len(tags)) - for _, tg := range tags { - dto.Tags = append(dto.Tags, TagDTO{ID: tg.ID, Name: tg.Name, Color: tg.Color}) - } - out = append(out, dto) - } - // Stable order — engine.List() iterates anacrolix's internal map (random - // per call), which would swap rows on every tick. Sort by added_at desc - // (newest first), tie-broken by id so identical-second adds don't flip. - sort.Slice(out, func(i, j int) bool { - if out[i].AddedAt != out[j].AddedAt { - return out[i].AddedAt > out[j].AddedAt - } - return out[i].ID < out[j].ID - }) - return out, nil -} - -// GlobalStats is the snapshot displayed in the status bar. -type GlobalStats struct { - TotalTorrents int `json:"total_torrents"` - ActiveTorrents int `json:"active_torrents"` - SeedingTorrents int `json:"seeding_torrents"` - TotalDownloadRate int64 `json:"total_download_rate"` - TotalUploadRate int64 `json:"total_upload_rate"` - TotalPeers int `json:"total_peers"` -} - -// EngineSnapshots returns the engine's current per-torrent snapshot slice. -// It is caller-independent: streamTicks walks the engine once per tick and -// passes the result to GlobalStatsFromSnapshot for each connected user. -func (s *Service) EngineSnapshots() []engine.Snapshot { - return s.engine.List() -} - -func (s *Service) GlobalStats(ctx context.Context) (GlobalStats, error) { - return s.GlobalStatsFromSnapshot(ctx, s.engine.List()) -} - -// GlobalStatsFromSnapshot computes a caller's status-bar aggregate from an -// already-fetched engine snapshot slice. The snapshot is identical across -// users; per-user stats are just a filtered reduction of it, so streamTicks -// can walk the engine once per tick and reuse the slice for every connected -// user. Output matches the old per-user GlobalStats exactly. -func (s *Service) GlobalStatsFromSnapshot(ctx context.Context, snaps []engine.Snapshot) (GlobalStats, error) { - caller := CallerFrom(ctx) - // Non-admin callers get an aggregate scoped to their own torrents only — - // the status bar must not leak the existence/bandwidth of other users'. - var visible map[string]string - if !caller.SeesAllTorrents() { - var err error - visible, err = s.access.InfohashesForUser(ctx, caller.UserID) - if err != nil { - return GlobalStats{}, err - } - } - var st GlobalStats - for _, snap := range snaps { - if visible != nil { - if _, ok := visible[string(snap.ID)]; !ok { - continue - } - } - st.TotalTorrents++ - if !snap.Paused && !snap.Completed { - st.ActiveTorrents++ - } - if snap.Completed { - st.SeedingTorrents++ - } - st.TotalDownloadRate += snap.RateDown - st.TotalUploadRate += snap.RateUp - st.TotalPeers += snap.Peers - } - return st, nil -} - -// DetailDTO is the inspector tick payload, returned from DetailForFocus or -// emitted via the inspector:tick event. -type DetailDTO struct { - ID string `json:"id"` - Name string `json:"name"` - // Overview-tab fields — always present - Magnet string `json:"magnet"` - SavePath string `json:"save_path"` - TotalBytes int64 `json:"total_bytes"` - BytesDone int64 `json:"bytes_done"` - Progress float64 `json:"progress"` - Ratio float64 `json:"ratio"` - TotalDown int64 `json:"total_down"` - TotalUp int64 `json:"total_up"` - Peers int `json:"peers"` - Seeds int `json:"seeds"` - AddedAt int64 `json:"added_at"` - CompletedAt int64 `json:"completed_at,omitempty"` - // Status flags so the inspector can color the progress bar without - // re-deriving from the torrents list. - Paused bool `json:"paused"` - Completed bool `json:"completed"` - FilesMissing bool `json:"files_missing"` - - Files []FileDTO `json:"files,omitempty"` - PeersList []PeerDTO `json:"peers_list,omitempty"` - Trackers []TrackerDTO `json:"trackers,omitempty"` -} - -type FileDTO struct { - Index int `json:"index"` - Path string `json:"path"` - Size int64 `json:"size"` - BytesDone int64 `json:"bytes_done"` - Progress float64 `json:"progress"` - Priority string `json:"priority"` // "skip" | "normal" | "high" | "max" -} - -type PeerDTO struct { - IP string `json:"ip"` - Port int `json:"port"` - Client string `json:"client"` - Flags string `json:"flags"` - Progress float64 `json:"progress"` - DownloadRate int64 `json:"download_rate"` - UploadRate int64 `json:"upload_rate"` - Country string `json:"country"` -} - -type TrackerDTO struct { - URL string `json:"url"` - Status string `json:"status"` - Seeds int `json:"seeds"` - Peers int `json:"peers"` - Downloaded int `json:"downloaded"` - LastAnnounce int64 `json:"last_announce"` - NextAnnounce int64 `json:"next_announce"` -} - -// SetInspectorFocus tells the service which torrent + tabs the caller's UI is -// looking at. Focus is tracked per user, so concurrent mosaicd sessions don't -// clobber each other. Subsequent DetailForFocus calls (and the inspector:tick -// event) return the appropriately-scoped Detail. tabs is a subset of: -// "overview", "files", "peers", "trackers", "speed". -func (s *Service) SetInspectorFocus(ctx context.Context, id string, tabs []string) error { - uid := CallerFrom(ctx).UserID - if id == "" { - s.ClearInspectorFocus(ctx) - return nil - } - scope := scopeForTabs(tabs) - s.focusMu.Lock() - s.focus[uid] = focusState{id: engine.TorrentID(id), scope: scope} - s.focusMu.Unlock() - return nil -} - -// ClearInspectorFocus drops the caller's inspector focus. -func (s *Service) ClearInspectorFocus(ctx context.Context) { - uid := CallerFrom(ctx).UserID - s.focusMu.Lock() - delete(s.focus, uid) - s.focusMu.Unlock() -} - -// DetailForFocus returns the caller's focused torrent detail, or nil if no -// focus is set or the caller no longer has access to that torrent. -func (s *Service) DetailForFocus(ctx context.Context) (*DetailDTO, error) { - caller := CallerFrom(ctx) - s.focusMu.RLock() - f, ok := s.focus[caller.UserID] - s.focusMu.RUnlock() - if !ok || f.id == "" { - return nil, nil - } - if !caller.SeesAllTorrents() { - lvl, err := s.access.AccessFor(ctx, string(f.id), caller.UserID) - if err != nil { - return nil, err - } - if lvl == "" { - return nil, nil - } - } - d, err := s.engine.DetailedSnapshot(f.id, f.scope) - if err != nil { - return nil, err - } - addedAt, completedAt := s.lookupRecordTimes(ctx, f.id) - dto := detailToDTO(d, addedAt, completedAt) - return &dto, nil -} - -func scopeForTabs(tabs []string) engine.DetailScope { - scope := engine.DetailScope{} - for _, t := range tabs { - switch t { - case "files": - scope.Files = true - case "peers": - scope.Peers = true - case "trackers": - scope.Trackers = true - } - } - return scope -} - -func (s *Service) lookupRecordTimes(ctx context.Context, id engine.TorrentID) (time.Time, *time.Time) { - rec, err := s.torrents.Get(ctx, string(id)) - if err != nil { - return time.Time{}, nil - } - return rec.AddedAt, rec.CompletedAt -} - -func detailToDTO(d engine.Detail, addedAt time.Time, completedAt *time.Time) DetailDTO { - snap := d.Snapshot - prog := 0.0 - if snap.TotalBytes > 0 { - prog = float64(snap.BytesDone) / float64(snap.TotalBytes) - } - dto := DetailDTO{ - ID: string(snap.ID), - Name: snap.Name, - Magnet: snap.Magnet, - SavePath: snap.SavePath, - TotalBytes: snap.TotalBytes, - BytesDone: snap.BytesDone, - Progress: prog, - Ratio: ratioOf(snap.BytesDown, snap.BytesUp), - TotalDown: snap.BytesDown, - TotalUp: snap.BytesUp, - Peers: snap.Peers, - Seeds: snap.Seeds, - AddedAt: unixOrZero(addedAt), - Paused: snap.Paused, - Completed: snap.Completed, - FilesMissing: snap.FilesMissing, - } - if completedAt != nil { - dto.CompletedAt = completedAt.Unix() - } - for _, f := range d.Files { - fp := 0.0 - if f.Size > 0 { - fp = float64(f.BytesDone) / float64(f.Size) - } - dto.Files = append(dto.Files, FileDTO{ - Index: f.Index, Path: f.Path, Size: f.Size, BytesDone: f.BytesDone, Progress: fp, - Priority: priorityToString(f.Priority), - }) - } - for _, p := range d.Peers { - dto.PeersList = append(dto.PeersList, PeerDTO{ - IP: p.IP, Port: p.Port, Client: p.ClientName, Flags: p.Flags, - Progress: p.Progress, DownloadRate: p.DownloadRate, UploadRate: p.UploadRate, Country: p.CountryCode, - }) - } - for _, t := range d.Trackers { - dto.Trackers = append(dto.Trackers, TrackerDTO{ - URL: t.URL, Status: t.Status, Seeds: t.Seeds, Peers: t.Peers, Downloaded: t.Downloaded, - LastAnnounce: t.LastAnnounce.Unix(), NextAnnounce: t.NextAnnounce.Unix(), - }) - } - return dto -} - -func ratioOf(down, up int64) float64 { - if down == 0 { - return 0 - } - return float64(up) / float64(down) -} - -func priorityToString(p engine.Priority) string { - switch p { - case engine.PrioritySkip: - return "skip" - case engine.PriorityHigh: - return "high" - case engine.PriorityMax: - return "max" - } - return "normal" -} - -type CategoryDTO struct { - ID int `json:"id"` - Name string `json:"name"` - DefaultSavePath string `json:"default_save_path"` - Color string `json:"color"` -} - -type TagDTO struct { - ID int `json:"id"` - Name string `json:"name"` - Color string `json:"color"` -} - -func (s *Service) CreateCategory(ctx context.Context, name, defaultPath, color string) (int, error) { - if !CallerFrom(ctx).CanManageCatTags() { - return 0, ErrForbidden - } - return s.categories.Create(ctx, persistence.Category{Name: name, DefaultSavePath: defaultPath, Color: color}) -} - -func (s *Service) ListCategories(ctx context.Context) ([]CategoryDTO, error) { - cats, err := s.categories.List(ctx) - if err != nil { - return nil, err - } - out := make([]CategoryDTO, 0, len(cats)) - for _, c := range cats { - out = append(out, CategoryDTO{ID: c.ID, Name: c.Name, DefaultSavePath: c.DefaultSavePath, Color: c.Color}) - } - return out, nil -} - -func (s *Service) UpdateCategory(ctx context.Context, id int, name, defaultPath, color string) error { - if !CallerFrom(ctx).CanManageCatTags() { - return ErrForbidden - } - return s.categories.Update(ctx, persistence.Category{ID: id, Name: name, DefaultSavePath: defaultPath, Color: color}) -} - -func (s *Service) DeleteCategory(ctx context.Context, id int) error { - if !CallerFrom(ctx).CanManageCatTags() { - return ErrForbidden - } - return s.categories.Delete(ctx, id) -} - -func (s *Service) CreateTag(ctx context.Context, name, color string) (int, error) { - if !CallerFrom(ctx).CanManageCatTags() { - return 0, ErrForbidden - } - return s.tags.Create(ctx, persistence.Tag{Name: name, Color: color}) -} - -func (s *Service) ListTags(ctx context.Context) ([]TagDTO, error) { - tags, err := s.tags.List(ctx) - if err != nil { - return nil, err - } - out := make([]TagDTO, 0, len(tags)) - for _, t := range tags { - out = append(out, TagDTO{ID: t.ID, Name: t.Name, Color: t.Color}) - } - return out, nil -} - -func (s *Service) DeleteTag(ctx context.Context, id int) error { - if !CallerFrom(ctx).CanManageCatTags() { - return ErrForbidden - } - return s.tags.Delete(ctx, id) -} - -// AssignTag/UnassignTag attach an existing tag to a torrent — that is per- -// torrent organisation, so editor access on the torrent is sufficient (you -// don't need the global manage-cat-tags permission, which gates the tag set -// itself). -func (s *Service) AssignTag(ctx context.Context, infohash string, tagID int) error { - if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { - return err - } - return s.tags.Assign(ctx, infohash, tagID) -} - -func (s *Service) UnassignTag(ctx context.Context, infohash string, tagID int) error { - if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { - return err - } - return s.tags.Unassign(ctx, infohash, tagID) -} - -func (s *Service) ListTagsFor(ctx context.Context, infohash string) ([]TagDTO, error) { - tags, err := s.tags.ForTorrent(ctx, infohash) - if err != nil { - return nil, err - } - out := make([]TagDTO, 0, len(tags)) - for _, t := range tags { - out = append(out, TagDTO{ID: t.ID, Name: t.Name, Color: t.Color}) - } - return out, nil -} - -func (s *Service) SetTorrentCategory(ctx context.Context, infohash string, categoryID *int) error { - if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { - return err - } - return s.torrents.SetCategory(ctx, infohash, categoryID) -} - -// TorrentRateLimitsDTO is the per-torrent bandwidth cap transport shape. -// Down/Up are in KB/s; 0 means unlimited. -type TorrentRateLimitsDTO struct { - DownKbps int64 `json:"down_kbps"` - UpKbps int64 `json:"up_kbps"` -} - -// GetTorrentRateLimits returns the persisted per-torrent rate limits in KB/s. -func (s *Service) GetTorrentRateLimits(ctx context.Context, infohash string) (TorrentRateLimitsDTO, error) { - if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessViewer); err != nil { - return TorrentRateLimitsDTO{}, err - } - rec, err := s.torrents.Get(ctx, infohash) - if err != nil { - return TorrentRateLimitsDTO{}, err - } - return TorrentRateLimitsDTO{ - DownKbps: rec.DownRateLimit / 1024, - UpKbps: rec.UpRateLimit / 1024, - }, nil -} - -// SetTorrentRateLimits sets per-torrent download/upload caps. downKbps and -// upKbps are in KB/s; 0 means unlimited. Changes are persisted and applied -// to the live engine immediately. -func (s *Service) SetTorrentRateLimits(ctx context.Context, infohash string, downKbps, upKbps int64) error { - if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { - return err - } - if downKbps < 0 || upKbps < 0 { - return fmt.Errorf("rate limits must be >= 0") - } - downBPS := downKbps * 1024 - upBPS := upKbps * 1024 - if err := s.torrents.SetRateLimits(ctx, infohash, downBPS, upBPS); err != nil { - return fmt.Errorf("persist rate limits: %w", err) - } - return s.engine.SetTorrentRateLimits(engine.TorrentID(infohash), downBPS, upBPS) -} - -// validateTrackerURL returns an error if the URL is not a valid http, https, or -// udp tracker URL. Trackers over ws/wss are also accepted (WebSocket trackers). -func validateTrackerURL(raw string) error { - u, err := url.Parse(raw) - if err != nil { - return fmt.Errorf("invalid URL: %w", err) - } - switch u.Scheme { - case "http", "https", "udp", "ws", "wss": - // accepted - default: - return fmt.Errorf("tracker URL must use http, https, udp, ws, or wss scheme (got %q)", u.Scheme) - } - if u.Host == "" { - return fmt.Errorf("tracker URL has no host") - } - return nil -} - -// AddTracker adds a user-supplied tracker URL to a torrent and persists it so -// it survives restarts. Requires editor access on the torrent. -func (s *Service) AddTracker(ctx context.Context, infohash, trackerURL string) error { - if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { - return err - } - if err := validateTrackerURL(trackerURL); err != nil { - return err - } - if err := s.engine.AddTracker(engine.TorrentID(infohash), trackerURL); err != nil { - return fmt.Errorf("add tracker to engine: %w", err) - } - if s.trackers != nil { - if err := s.trackers.Add(ctx, infohash, trackerURL); err != nil { - return fmt.Errorf("persist tracker: %w", err) - } - } - return nil -} - -// RemoveTracker removes a user-supplied tracker URL from a torrent and deletes -// its persisted record. Requires editor access on the torrent. -func (s *Service) RemoveTracker(ctx context.Context, infohash, trackerURL string) error { - if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { - return err - } - if err := s.engine.RemoveTracker(engine.TorrentID(infohash), trackerURL); err != nil { - return fmt.Errorf("remove tracker from engine: %w", err) - } - if s.trackers != nil { - if err := s.trackers.Remove(ctx, infohash, trackerURL); err != nil { - return fmt.Errorf("remove persisted tracker: %w", err) - } - } - return nil -} - -func (s *Service) SetFilePriorities(ctx context.Context, infohash string, prios map[int]string) error { - if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { - return err - } - mapped := make(map[int]engine.Priority, len(prios)) - for idx, p := range prios { - switch p { - case "skip": - mapped[idx] = engine.PrioritySkip - case "high": - mapped[idx] = engine.PriorityHigh - case "max": - mapped[idx] = engine.PriorityMax - default: - mapped[idx] = engine.PriorityNormal - } - } - return s.engine.SetFilePriorities(engine.TorrentID(infohash), mapped) -} - -// LimitsDTO is the bandwidth-limits transport shape (kbps units). -type LimitsDTO struct { - DownKbps int `json:"down_kbps"` - UpKbps int `json:"up_kbps"` - AltDownKbps int `json:"alt_down_kbps"` - AltUpKbps int `json:"alt_up_kbps"` - AltActive bool `json:"alt_active"` -} - -// QueueLimitsDTO is the queue-slot transport shape. -type QueueLimitsDTO struct { - MaxActiveDownloads int `json:"max_active_downloads"` - MaxActiveSeeds int `json:"max_active_seeds"` -} - -func (s *Service) GetLimits(ctx context.Context) (LimitsDTO, error) { - return LimitsDTO{ - DownKbps: s.intSetting(ctx, settingDownKbps), - UpKbps: s.intSetting(ctx, settingUpKbps), - AltDownKbps: s.intSetting(ctx, settingAltDownKbps), - AltUpKbps: s.intSetting(ctx, settingAltUpKbps), - AltActive: s.boolSetting(ctx, settingAltActive), - }, nil -} - -func (s *Service) SetLimits(ctx context.Context, l LimitsDTO) error { - if !CallerFrom(ctx).CanChangeSettings() { - return ErrForbidden - } - if err := s.setIntSetting(ctx, settingDownKbps, l.DownKbps); err != nil { - return err - } - if err := s.setIntSetting(ctx, settingUpKbps, l.UpKbps); err != nil { - return err - } - if err := s.setIntSetting(ctx, settingAltDownKbps, l.AltDownKbps); err != nil { - return err - } - if err := s.setIntSetting(ctx, settingAltUpKbps, l.AltUpKbps); err != nil { - return err - } - if err := s.setBoolSetting(ctx, settingAltActive, l.AltActive); err != nil { - return err - } - return s.applyLimits(ctx) -} - -// ToggleAltSpeed flips the alt-speed flag and reapplies engine limits. Returns -// the new alt_active state. -func (s *Service) ToggleAltSpeed(ctx context.Context) (bool, error) { - if !CallerFrom(ctx).CanChangeSettings() { - return s.boolSetting(ctx, settingAltActive), ErrForbidden - } - cur := s.boolSetting(ctx, settingAltActive) - next := !cur - if err := s.setBoolSetting(ctx, settingAltActive, next); err != nil { - return cur, err - } - return next, s.applyLimits(ctx) -} - -func (s *Service) applyLimits(ctx context.Context) error { - l, _ := s.GetLimits(ctx) - down, up := l.DownKbps*1024, l.UpKbps*1024 - if l.AltActive { - down, up = l.AltDownKbps*1024, l.AltUpKbps*1024 - } - return s.engine.SetGlobalRateLimits(down, up) -} - -// PeerLimitsDTO carries the connection-level settings users can adjust from -// Settings → Connection. Most fields require a restart to take effect because -// anacrolix exposes them only at Client construction; MaxPeersPerTorrent is -// runtime-mutable and gets pushed to every running torrent on Set. -type PeerLimitsDTO struct { - ListenPort int `json:"listen_port"` // 0 = let OS pick at startup - MaxPeersPerTorrent int `json:"max_peers_per_torrent"` // 0 = anacrolix default (80) - DHTEnabled bool `json:"dht_enabled"` - EncryptionEnabled bool `json:"encryption_enabled"` - // UPnPEnabled enables automatic UPnP/NAT-PMP port forwarding via the - // router. anacrolix runs the discovery on startup so a restart is required - // after toggling. Defaults to true (anacrolix's own default). - UPnPEnabled bool `json:"upnp_enabled"` -} - -func (s *Service) GetPeerLimits(ctx context.Context) PeerLimitsDTO { - if !CallerFrom(ctx).CanChangeSettings() { - return PeerLimitsDTO{} - } - // DHT + encryption + UPnP default to true (matches anacrolix's defaults + - // good privacy hygiene). The bool helpers in this Service treat unset as - // false, so use a presence-aware reader. - dhtRaw, _ := s.settings.Get(ctx, settingDHTEnabled) - dhtEnabled := dhtRaw == "" || dhtRaw == "true" // default-on - encRaw, _ := s.settings.Get(ctx, settingEncryptionEnabled) - encEnabled := encRaw == "" || encRaw == "true" // default-on - upnpRaw, _ := s.settings.Get(ctx, settingUPnPEnabled) - upnpEnabled := upnpRaw == "" || upnpRaw == "true" // default-on (matches anacrolix) - return PeerLimitsDTO{ - ListenPort: s.intSetting(ctx, settingPeerListenPort), - MaxPeersPerTorrent: s.intSetting(ctx, settingMaxPeersPerTorrent), - DHTEnabled: dhtEnabled, - EncryptionEnabled: encEnabled, - UPnPEnabled: upnpEnabled, - } -} - -func (s *Service) SetPeerLimits(ctx context.Context, p PeerLimitsDTO) error { - if !CallerFrom(ctx).CanChangeSettings() { - return ErrForbidden - } - if p.ListenPort < 0 || p.ListenPort > 65535 { - return fmt.Errorf("listen port must be 0..65535") - } - if p.MaxPeersPerTorrent < 0 { - return fmt.Errorf("max peers per torrent must be >= 0") - } - if err := s.setIntSetting(ctx, settingPeerListenPort, p.ListenPort); err != nil { - return err - } - if err := s.setIntSetting(ctx, settingMaxPeersPerTorrent, p.MaxPeersPerTorrent); err != nil { - return err - } - if err := s.setBoolSetting(ctx, settingDHTEnabled, p.DHTEnabled); err != nil { - return err - } - if err := s.setBoolSetting(ctx, settingEncryptionEnabled, p.EncryptionEnabled); err != nil { - return err - } - if err := s.setBoolSetting(ctx, settingUPnPEnabled, p.UPnPEnabled); err != nil { - return err - } - // Per-torrent cap is the only one anacrolix lets us mutate at runtime. - // ListenPort / DHT / Encryption / UPnP changes take effect at next launch. - if err := s.engine.ApplyPerTorrentMaxPeers(p.MaxPeersPerTorrent); err != nil { - return err - } - return nil -} - -func (s *Service) GetQueueLimits(ctx context.Context) QueueLimitsDTO { - return QueueLimitsDTO{ - MaxActiveDownloads: s.intSetting(ctx, settingMaxActiveDL), - MaxActiveSeeds: s.intSetting(ctx, settingMaxActiveSeeds), - } -} - -func (s *Service) SetQueueLimits(ctx context.Context, q QueueLimitsDTO) error { - if !CallerFrom(ctx).CanChangeSettings() { - return ErrForbidden - } - if err := s.setIntSetting(ctx, settingMaxActiveDL, q.MaxActiveDownloads); err != nil { - return err - } - if err := s.setIntSetting(ctx, settingMaxActiveSeeds, q.MaxActiveSeeds); err != nil { - return err - } - if s.scheduler != nil { - s.scheduler.SetLimits(q.MaxActiveDownloads, q.MaxActiveSeeds) - } - return nil -} - -func (s *Service) SetQueuePosition(ctx context.Context, infohash string, pos int) error { - if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { - return err - } - if err := s.torrents.SetQueuePosition(ctx, infohash, pos); err != nil { - return err - } - s.engine.SetQueuePosition(engine.TorrentID(infohash), pos) - return nil -} - -func (s *Service) SetForceStart(ctx context.Context, infohash string, force bool) error { - if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { - return err - } - if err := s.torrents.SetForceStart(ctx, infohash, force); err != nil { - return err - } - s.engine.SetForceStart(engine.TorrentID(infohash), force) - return nil -} - -// SetSequential enables or disables sequential piece download for a torrent. -// When enabled, pieces are requested in order from first to last, allowing -// media to be previewed or streamed before the download completes. When -// disabled, the default rarest-first strategy is restored. -func (s *Service) SetSequential(ctx context.Context, infohash string, enabled bool) error { - if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { - return err - } - if err := s.torrents.SetSequential(ctx, infohash, enabled); err != nil { - return err - } - s.engine.SetSequential(engine.TorrentID(infohash), enabled) - return nil -} - -// ScheduleRuleDTO is the transport shape for a time-of-day bandwidth rule. -type ScheduleRuleDTO struct { - ID int `json:"id"` - DaysMask int `json:"days_mask"` - StartMin int `json:"start_min"` - EndMin int `json:"end_min"` - DownKbps int `json:"down_kbps"` - UpKbps int `json:"up_kbps"` - AltOnly bool `json:"alt_only"` - Enabled bool `json:"enabled"` -} - -func toScheduleRuleDTO(r persistence.ScheduleRule) ScheduleRuleDTO { - return ScheduleRuleDTO{ - ID: r.ID, DaysMask: r.DaysMask, StartMin: r.StartMin, EndMin: r.EndMin, - DownKbps: r.DownKbps, UpKbps: r.UpKbps, AltOnly: r.AltOnly, Enabled: r.Enabled, - } -} - -func (s *Service) ListScheduleRules(ctx context.Context) ([]ScheduleRuleDTO, error) { - if s.scheduleRules == nil { - return nil, nil - } - rules, err := s.scheduleRules.List(ctx) - if err != nil { - return nil, err - } - out := make([]ScheduleRuleDTO, 0, len(rules)) - for _, r := range rules { - out = append(out, toScheduleRuleDTO(r)) - } - return out, nil -} - -func (s *Service) CreateScheduleRule(ctx context.Context, r ScheduleRuleDTO) (int, error) { - if !CallerFrom(ctx).CanChangeSettings() { - return 0, ErrForbidden - } - return s.scheduleRules.Create(ctx, persistence.ScheduleRule{ - DaysMask: r.DaysMask, StartMin: r.StartMin, EndMin: r.EndMin, - DownKbps: r.DownKbps, UpKbps: r.UpKbps, AltOnly: r.AltOnly, Enabled: r.Enabled, - }) -} - -func (s *Service) UpdateScheduleRule(ctx context.Context, r ScheduleRuleDTO) error { - if !CallerFrom(ctx).CanChangeSettings() { - return ErrForbidden - } - return s.scheduleRules.Update(ctx, persistence.ScheduleRule{ - ID: r.ID, DaysMask: r.DaysMask, StartMin: r.StartMin, EndMin: r.EndMin, - DownKbps: r.DownKbps, UpKbps: r.UpKbps, AltOnly: r.AltOnly, Enabled: r.Enabled, - }) -} - -func (s *Service) DeleteScheduleRule(ctx context.Context, id int) error { - if !CallerFrom(ctx).CanChangeSettings() { - return ErrForbidden - } - return s.scheduleRules.Delete(ctx, id) -} - -// BlocklistDTO is the transport shape for the IP blocklist config + status. -type BlocklistDTO struct { - URL string `json:"url"` - Enabled bool `json:"enabled"` - LastLoadedAt int64 `json:"last_loaded_at"` - Entries int `json:"entries"` - Error string `json:"error,omitempty"` -} - -func (s *Service) GetBlocklist(ctx context.Context) BlocklistDTO { - if !CallerFrom(ctx).CanChangeSettings() { - return BlocklistDTO{} - } - rawURL, _ := s.settings.Get(ctx, settingBlocklistURL) - en := s.boolSetting(ctx, settingBlocklistEnabled) - s.blocklistMu.RLock() - defer s.blocklistMu.RUnlock() - dto := BlocklistDTO{URL: redactURLCredentials(rawURL), Enabled: en, Entries: s.blocklist.entries, Error: s.blocklist.lastErr} - if !s.blocklist.loadedAt.IsZero() { - dto.LastLoadedAt = s.blocklist.loadedAt.Unix() - } - return dto -} - -// redactURLCredentials strips userinfo from a URL so a stored "http://user:pw@host/..." -// blocklist URL doesn't leak the password back to the SPA in GetBlocklist. The -// raw URL with credentials remains in settings (so refresh still works); only -// the DTO is scrubbed. -func redactURLCredentials(raw string) string { - if raw == "" { - return raw - } - u, err := url.Parse(raw) - if err != nil || u.User == nil { - return raw - } - u.User = nil - return u.String() -} - -func (s *Service) SetBlocklistURL(ctx context.Context, url string, enabled bool) error { - if !CallerFrom(ctx).CanChangeSettings() { - return ErrForbidden - } - // Reject obviously dangerous URLs at write time. The dialer in - // safeHTTPClient is the second layer that catches DNS-rebind tricks. - if enabled && url != "" { - if _, err := validateFetchURL(url); err != nil { - return fmt.Errorf("blocklist URL must be http or https and not point at a private/loopback address: %w", err) - } - } - if err := s.settings.Set(ctx, settingBlocklistURL, url); err != nil { - return err - } - if err := s.setBoolSetting(ctx, settingBlocklistEnabled, enabled); err != nil { - return err - } - if !enabled || url == "" { - _ = s.engine.SetIPBlocklist(nil) - s.blocklistMu.Lock() - s.blocklist = blocklistState{} - s.blocklistMu.Unlock() - return nil - } - return s.RefreshBlocklist(ctx) -} - -func (s *Service) RefreshBlocklist(ctx context.Context) error { - if !CallerFrom(ctx).CanChangeSettings() { - return ErrForbidden - } - url, _ := s.settings.Get(ctx, settingBlocklistURL) - if url == "" { - return errors.New("no blocklist URL configured") - } - if _, err := validateFetchURL(url); err != nil { - return fmt.Errorf("refusing to fetch blocklist: %w", err) - } - - httpCtx, cancel := context.WithTimeout(ctx, 30*time.Second) - defer cancel() - req, err := http.NewRequestWithContext(httpCtx, "GET", url, nil) - if err != nil { - return err - } - client := safeHTTPClient(30 * time.Second) - resp, err := client.Do(req) - if err != nil { - s.blocklistMu.Lock() - s.blocklist.lastErr = err.Error() - s.blocklistMu.Unlock() - return err - } - defer resp.Body.Close() - - body, err := io.ReadAll(io.LimitReader(resp.Body, 50*1024*1024)) // 50MB safety cap - if err != nil { - s.blocklistMu.Lock() - s.blocklist.lastErr = err.Error() - s.blocklistMu.Unlock() - return err - } - - if err := s.engine.SetIPBlocklist(bytes.NewReader(body)); err != nil { - s.blocklistMu.Lock() - s.blocklist.lastErr = err.Error() - s.blocklistMu.Unlock() - return err - } - - s.blocklistMu.Lock() - s.blocklist = blocklistState{loadedAt: time.Now(), entries: countLines(body), lastErr: ""} - s.blocklistMu.Unlock() - return nil -} - -func countLines(b []byte) int { - n := 0 - for _, x := range b { - if x == '\n' { - n++ - } - } - return n -} - -// RestoreOnStartup hydrates engine + scheduler limits from persisted settings -// AND re-adds every persisted torrent to the engine so prior-session downloads -// resume on next launch. Call this once after constructing the Service. -// -// Installs SystemCaller on the context so callers don't have to — this is the -// trusted startup hydration path, not a user-driven action. -func (s *Service) RestoreOnStartup(ctx context.Context) error { - ctx = WithCaller(ctx, SystemCaller) - if err := s.recoverInvalidAdminPasswordHash(ctx); err != nil { - log.Warn().Err(err).Msg("restore: recover invalid admin password hash failed") - } - q := s.GetQueueLimits(ctx) - if s.scheduler != nil { - s.scheduler.SetLimits(q.MaxActiveDownloads, q.MaxActiveSeeds) - } - if err := s.applyLimits(ctx); err != nil { - return err - } - - records, err := s.torrents.List(ctx) - if err != nil { - return fmt.Errorf("list persisted torrents: %w", err) - } - failed := 0 - orphaned := 0 - for _, r := range records { - var id engine.TorrentID - var addErr error - switch { - case len(r.Metainfo) > 0: - id, addErr = s.engine.AddFile(ctx, r.Metainfo, r.SavePath) - case r.Magnet != "": - id, addErr = s.engine.AddMagnet(ctx, r.Magnet, r.SavePath) - default: - log.Warn().Str("infohash", r.InfoHash).Str("name", r.Name).Msg("restore: skipping orphan record (no magnet, no metainfo)") - orphaned++ - continue - } - if addErr != nil { - log.Warn().Err(addErr).Str("infohash", r.InfoHash).Str("name", r.Name).Msg("restore: re-add failed") - failed++ - continue - } - // If the persistence layer recorded this torrent as previously complete, - // tell the engine — its post-VerifyData hook flags FilesMissing and - // pauses the torrent if the on-disk pieces no longer match (the user - // deleted files between sessions). Without this hint VerifyData silently - // turns a deleted file into a redownload. - if r.CompletedAt != nil { - s.engine.MarkExpectedComplete(id) - } - // Propagate persisted queue ordering so the scheduler's tie-breaks - // are stable across launches. Without this every restored torrent - // has QueuePosition=0 and ForceStart=false in the engine, and any - // non-zero MaxActiveSeeds / MaxActiveDownloads picks arbitrary - // victims via sort.Slice's unstable ordering — a completed torrent - // that was seeding fine yesterday can come back paused-by-queue - // today with no peers attached. - s.engine.SetQueuePosition(id, r.QueuePosition) - s.engine.SetForceStart(id, r.ForceStart) - // Re-apply sequential download preference so the piece-priority - // gradient takes effect immediately on restore, before any pieces - // are requested. SetSequential is a no-op if the torrent hasn't - // received metainfo yet (GotInfo not fired); verifyAndStart will - // have applied Normal priorities by then anyway and the gradient - // will be overwritten — but for file-added torrents (metainfo - // already present) this ensures sequential behavior from the start. - if r.Sequential { - s.engine.SetSequential(id, true) - } - // Surface persisted user-pause too, otherwise a torrent the user - // paused last session resumes silently. - if r.Paused { - if err := s.engine.Pause(id); err != nil { - log.Warn().Err(err).Str("infohash", r.InfoHash).Msg("restore: re-pause failed") - } - } - // Re-apply persisted per-torrent rate limits. - if r.DownRateLimit != 0 || r.UpRateLimit != 0 { - if err := s.engine.SetTorrentRateLimits(id, r.DownRateLimit, r.UpRateLimit); err != nil { - log.Warn().Err(err).Str("infohash", r.InfoHash).Msg("restore: re-apply rate limits failed") - } - } - // Re-apply any user-added trackers. - if s.trackers != nil { - urls, err := s.trackers.List(ctx, r.InfoHash) - if err != nil { - log.Warn().Err(err).Str("infohash", r.InfoHash).Msg("restore: list user trackers failed") - } else { - for _, u := range urls { - if err := s.engine.AddTracker(id, u); err != nil { - log.Warn().Err(err).Str("infohash", r.InfoHash).Str("url", u).Msg("restore: re-add tracker failed") - } - } - } - } - } - if failed > 0 || orphaned > 0 { - log.Warn().Int("failed", failed).Int("orphaned", orphaned).Int("total", len(records)).Msg("restore: not all torrents could be re-added") - } - return nil -} - -func (s *Service) intSetting(ctx context.Context, key string) int { - v, err := s.settings.Get(ctx, key) - if err != nil { - return 0 - } - n, _ := strconv.Atoi(v) - return n -} - -func (s *Service) setIntSetting(ctx context.Context, key string, n int) error { - return s.settings.Set(ctx, key, strconv.Itoa(n)) -} - -func (s *Service) boolSetting(ctx context.Context, key string) bool { - v, _ := s.settings.Get(ctx, key) - return v == "true" -} - -func (s *Service) setBoolSetting(ctx context.Context, key string, b bool) error { - v := "false" - if b { - v = "true" - } - return s.settings.Set(ctx, key, v) -} - -// ─── Seed Policy ───────────────────────────────────────────────────────────── - -const ( - settingSeedingRatioLimit = "seeding.ratio_limit" // float64 as string; "" = no global limit - settingSeedingTimeMiniLimit = "seeding.time_min_limit" // int (minutes) as string; "" = no global limit -) - -// SeedingDefaultsDTO carries the global seeding-stop defaults. -// nil pointer fields mean "no limit". -type SeedingDefaultsDTO struct { - RatioLimit *float64 `json:"ratio_limit"` // bytes_up / bytes_done; nil = no limit - TimeMinLimit *int `json:"time_min_limit"` // minutes; nil = no limit -} - -// SeedPolicyDTO is the per-torrent override. -// nil = "use global default"; non-nil object with nil fields = "no limit for this torrent". -type SeedPolicyDTO struct { - // UseGlobal, when true, means the per-torrent override is cleared — - // the torrent reverts to global defaults. - UseGlobal bool `json:"use_global"` - RatioLimit *float64 `json:"ratio_limit"` - TimeMinLimit *int `json:"time_min_limit"` -} - -func (s *Service) GetSeedingDefaults(ctx context.Context) SeedingDefaultsDTO { - var dto SeedingDefaultsDTO - if v, err := s.settings.Get(ctx, settingSeedingRatioLimit); err == nil && v != "" { - if f, err := strconv.ParseFloat(v, 64); err == nil { - dto.RatioLimit = &f - } - } - if v, err := s.settings.Get(ctx, settingSeedingTimeMiniLimit); err == nil && v != "" { - if n, err := strconv.Atoi(v); err == nil { - dto.TimeMinLimit = &n - } - } - return dto -} - -func (s *Service) SetSeedingDefaults(ctx context.Context, d SeedingDefaultsDTO) error { - if !CallerFrom(ctx).CanChangeSettings() { - return ErrForbidden - } - ratioStr := "" - if d.RatioLimit != nil { - ratioStr = strconv.FormatFloat(*d.RatioLimit, 'f', -1, 64) - } - if err := s.settings.Set(ctx, settingSeedingRatioLimit, ratioStr); err != nil { - return err - } - timeStr := "" - if d.TimeMinLimit != nil { - timeStr = strconv.Itoa(*d.TimeMinLimit) - } - return s.settings.Set(ctx, settingSeedingTimeMiniLimit, timeStr) -} - -func (s *Service) GetTorrentSeedPolicy(ctx context.Context, infohash string) (SeedPolicyDTO, error) { - if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessViewer); err != nil { - return SeedPolicyDTO{}, err - } - rec, err := s.torrents.Get(ctx, infohash) - if err != nil { - return SeedPolicyDTO{}, err - } - if rec.SeedPolicy == nil { - return SeedPolicyDTO{UseGlobal: true}, nil - } - var p seedPolicyJSON - if err := jsonUnmarshal([]byte(*rec.SeedPolicy), &p); err != nil { - return SeedPolicyDTO{UseGlobal: true}, nil - } - return SeedPolicyDTO{ - UseGlobal: false, - RatioLimit: p.RatioLimit, - TimeMinLimit: p.TimeMinLimit, - }, nil -} - -func (s *Service) SetTorrentSeedPolicy(ctx context.Context, infohash string, p SeedPolicyDTO) error { - if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { - return err - } - if p.UseGlobal { - return s.torrents.SetSeedPolicy(ctx, infohash, nil) - } - raw, err := jsonMarshal(seedPolicyJSON{ - RatioLimit: p.RatioLimit, - TimeMinLimit: p.TimeMinLimit, - }) - if err != nil { - return fmt.Errorf("marshal seed policy: %w", err) - } - str := string(raw) - return s.torrents.SetSeedPolicy(ctx, infohash, &str) -} - -// seedPolicyJSON is the wire/storage shape for a per-torrent seed policy. -type seedPolicyJSON struct { - RatioLimit *float64 `json:"ratio_limit"` - TimeMinLimit *int `json:"time_min_limit"` -} - -// CheckSeedLimits inspects every completed, non-paused torrent and pauses -// any that have exceeded their effective seeding limit (ratio or time). -// It is designed to be called on a periodic ticker (e.g. every 30 seconds). -// -// Each pass also checkpoints the engine's session-scoped transfer counters -// into the persisted total_uploaded/total_downloaded columns (for every -// persisted torrent, not just completed ones), and computes the ratio from -// the persisted total — anacrolix's BytesUp resets each process start, so a -// ratio computed from it restarted at 0 on every launch and ratio limits -// effectively never fired across sessions. -func (s *Service) CheckSeedLimits(ctx context.Context) { - ctx = WithCaller(ctx, SystemCaller) - defaults := s.GetSeedingDefaults(ctx) - snaps := s.engine.List() - // One bulk SELECT per pass instead of a per-torrent Get every 30s. - records, err := s.torrents.List(ctx) - if err != nil { - log.Warn().Err(err).Msg("seed policy: list torrents failed") - return - } - byHash := make(map[string]persistence.TorrentRecord, len(records)) - for _, r := range records { - byHash[r.InfoHash] = r - } - now := time.Now() - live := make(map[string]struct{}, len(snaps)) - for _, snap := range snaps { - live[string(snap.ID)] = struct{}{} - rec, ok := byHash[string(snap.ID)] - if !ok { - continue - } - totalUp := s.checkpointTransferTotals(ctx, &rec, snap) - if !snap.Completed || snap.Paused { - continue - } - // Determine effective policy: per-torrent override wins over global default. - var ratioLimit *float64 - var timeMinLimit *int - if rec.SeedPolicy != nil { - var p seedPolicyJSON - if jsonUnmarshal([]byte(*rec.SeedPolicy), &p) == nil { - ratioLimit = p.RatioLimit - timeMinLimit = p.TimeMinLimit - } - } else { - ratioLimit = defaults.RatioLimit - timeMinLimit = defaults.TimeMinLimit - } - if ratioLimit == nil && timeMinLimit == nil { - continue - } - // Record seeding start time on first encounter. - if rec.SeedingStartedAt == nil { - if err := s.torrents.SetSeedingStartedAt(ctx, string(snap.ID), &now); err != nil { - log.Warn().Err(err).Str("id", string(snap.ID)).Msg("seed policy: failed to record seeding_started_at") - } - rec.SeedingStartedAt = &now - } - exceeded := false - if ratioLimit != nil && snap.BytesDone > 0 { - ratio := float64(totalUp) / float64(snap.BytesDone) - if ratio >= *ratioLimit { - exceeded = true - } - } - if !exceeded && timeMinLimit != nil && rec.SeedingStartedAt != nil { - elapsed := now.Sub(*rec.SeedingStartedAt) - if elapsed >= time.Duration(*timeMinLimit)*time.Minute { - exceeded = true - } - } - if exceeded { - if err := s.engine.Pause(snap.ID); err != nil { - log.Warn().Err(err).Str("id", string(snap.ID)).Msg("seed policy: pause failed") - } else { - log.Info().Str("id", string(snap.ID)).Str("name", snap.Name).Msg("seed policy: paused torrent — limit reached") - } - } - } - // Prune observations for torrents no longer in the engine so a removed - // and re-added infohash starts from fresh counters and the map doesn't - // grow unbounded across remove cycles. - s.seedCheckMu.Lock() - for hash := range s.lastSeedCounters { - if _, ok := live[hash]; !ok { - delete(s.lastSeedCounters, hash) - } - } - s.seedCheckMu.Unlock() -} - -// checkpointTransferTotals persists the delta between the engine's -// session-scoped transfer counters and the last value this process observed -// for the torrent, returning the updated cumulative uploaded total. A counter -// lower than the last observation means the engine restarted (counters reset -// to zero) — the full current value is the delta. On a write failure the -// observation is rolled back so the delta is retried next pass instead of -// being lost. -func (s *Service) checkpointTransferTotals(ctx context.Context, rec *persistence.TorrentRecord, snap engine.Snapshot) int64 { - hash := string(snap.ID) - s.seedCheckMu.Lock() - last, seen := s.lastSeedCounters[hash] - upDelta, downDelta := snap.BytesUp-last.up, snap.BytesDown-last.down - if upDelta < 0 { - upDelta = snap.BytesUp - } - if downDelta < 0 { - downDelta = snap.BytesDown - } - s.lastSeedCounters[hash] = sessionCounters{up: snap.BytesUp, down: snap.BytesDown} - s.seedCheckMu.Unlock() - if upDelta == 0 && downDelta == 0 { - return rec.TotalUploaded - } - if err := s.torrents.AddTransferTotals(ctx, hash, upDelta, downDelta); err != nil { - log.Warn().Err(err).Str("id", hash).Msg("seed policy: persist transfer totals failed") - s.seedCheckMu.Lock() - if seen { - s.lastSeedCounters[hash] = last - } else { - delete(s.lastSeedCounters, hash) - } - s.seedCheckMu.Unlock() - return rec.TotalUploaded - } - rec.TotalUploaded += upDelta - rec.TotalDownloaded += downDelta - return rec.TotalUploaded -} diff --git a/backend/api/service_seeding.go b/backend/api/service_seeding.go new file mode 100644 index 0000000..d448402 --- /dev/null +++ b/backend/api/service_seeding.go @@ -0,0 +1,247 @@ +package api + +import ( + "context" + "fmt" + "strconv" + "time" + + "github.com/rs/zerolog/log" + + "mosaic/backend/engine" + "mosaic/backend/persistence" +) + +// ─── Seed Policy ───────────────────────────────────────────────────────────── + +const ( + settingSeedingRatioLimit = "seeding.ratio_limit" // float64 as string; "" = no global limit + settingSeedingTimeMiniLimit = "seeding.time_min_limit" // int (minutes) as string; "" = no global limit +) + +// SeedingDefaultsDTO carries the global seeding-stop defaults. +// nil pointer fields mean "no limit". +type SeedingDefaultsDTO struct { + RatioLimit *float64 `json:"ratio_limit"` // bytes_up / bytes_done; nil = no limit + TimeMinLimit *int `json:"time_min_limit"` // minutes; nil = no limit +} + +// SeedPolicyDTO is the per-torrent override. +// nil = "use global default"; non-nil object with nil fields = "no limit for this torrent". +type SeedPolicyDTO struct { + // UseGlobal, when true, means the per-torrent override is cleared — + // the torrent reverts to global defaults. + UseGlobal bool `json:"use_global"` + RatioLimit *float64 `json:"ratio_limit"` + TimeMinLimit *int `json:"time_min_limit"` +} + +func (s *Service) GetSeedingDefaults(ctx context.Context) SeedingDefaultsDTO { + var dto SeedingDefaultsDTO + if v, err := s.settings.Get(ctx, settingSeedingRatioLimit); err == nil && v != "" { + if f, err := strconv.ParseFloat(v, 64); err == nil { + dto.RatioLimit = &f + } + } + if v, err := s.settings.Get(ctx, settingSeedingTimeMiniLimit); err == nil && v != "" { + if n, err := strconv.Atoi(v); err == nil { + dto.TimeMinLimit = &n + } + } + return dto +} + +func (s *Service) SetSeedingDefaults(ctx context.Context, d SeedingDefaultsDTO) error { + if !CallerFrom(ctx).CanChangeSettings() { + return ErrForbidden + } + ratioStr := "" + if d.RatioLimit != nil { + ratioStr = strconv.FormatFloat(*d.RatioLimit, 'f', -1, 64) + } + if err := s.settings.Set(ctx, settingSeedingRatioLimit, ratioStr); err != nil { + return err + } + timeStr := "" + if d.TimeMinLimit != nil { + timeStr = strconv.Itoa(*d.TimeMinLimit) + } + return s.settings.Set(ctx, settingSeedingTimeMiniLimit, timeStr) +} + +func (s *Service) GetTorrentSeedPolicy(ctx context.Context, infohash string) (SeedPolicyDTO, error) { + if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessViewer); err != nil { + return SeedPolicyDTO{}, err + } + rec, err := s.torrents.Get(ctx, infohash) + if err != nil { + return SeedPolicyDTO{}, err + } + if rec.SeedPolicy == nil { + return SeedPolicyDTO{UseGlobal: true}, nil + } + var p seedPolicyJSON + if err := jsonUnmarshal([]byte(*rec.SeedPolicy), &p); err != nil { + return SeedPolicyDTO{UseGlobal: true}, nil + } + return SeedPolicyDTO{ + UseGlobal: false, + RatioLimit: p.RatioLimit, + TimeMinLimit: p.TimeMinLimit, + }, nil +} + +func (s *Service) SetTorrentSeedPolicy(ctx context.Context, infohash string, p SeedPolicyDTO) error { + if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { + return err + } + if p.UseGlobal { + return s.torrents.SetSeedPolicy(ctx, infohash, nil) + } + raw, err := jsonMarshal(seedPolicyJSON{ + RatioLimit: p.RatioLimit, + TimeMinLimit: p.TimeMinLimit, + }) + if err != nil { + return fmt.Errorf("marshal seed policy: %w", err) + } + str := string(raw) + return s.torrents.SetSeedPolicy(ctx, infohash, &str) +} + +// seedPolicyJSON is the wire/storage shape for a per-torrent seed policy. +type seedPolicyJSON struct { + RatioLimit *float64 `json:"ratio_limit"` + TimeMinLimit *int `json:"time_min_limit"` +} + +// CheckSeedLimits inspects every completed, non-paused torrent and pauses +// any that have exceeded their effective seeding limit (ratio or time). +// It is designed to be called on a periodic ticker (e.g. every 30 seconds). +// +// Each pass also checkpoints the engine's session-scoped transfer counters +// into the persisted total_uploaded/total_downloaded columns (for every +// persisted torrent, not just completed ones), and computes the ratio from +// the persisted total — anacrolix's BytesUp resets each process start, so a +// ratio computed from it restarted at 0 on every launch and ratio limits +// effectively never fired across sessions. +func (s *Service) CheckSeedLimits(ctx context.Context) { + ctx = WithCaller(ctx, SystemCaller) + defaults := s.GetSeedingDefaults(ctx) + snaps := s.engine.List() + // One bulk SELECT per pass instead of a per-torrent Get every 30s. + records, err := s.torrents.List(ctx) + if err != nil { + log.Warn().Err(err).Msg("seed policy: list torrents failed") + return + } + byHash := make(map[string]persistence.TorrentRecord, len(records)) + for _, r := range records { + byHash[r.InfoHash] = r + } + now := time.Now() + live := make(map[string]struct{}, len(snaps)) + for _, snap := range snaps { + live[string(snap.ID)] = struct{}{} + rec, ok := byHash[string(snap.ID)] + if !ok { + continue + } + totalUp := s.checkpointTransferTotals(ctx, &rec, snap) + if !snap.Completed || snap.Paused { + continue + } + // Determine effective policy: per-torrent override wins over global default. + var ratioLimit *float64 + var timeMinLimit *int + if rec.SeedPolicy != nil { + var p seedPolicyJSON + if jsonUnmarshal([]byte(*rec.SeedPolicy), &p) == nil { + ratioLimit = p.RatioLimit + timeMinLimit = p.TimeMinLimit + } + } else { + ratioLimit = defaults.RatioLimit + timeMinLimit = defaults.TimeMinLimit + } + if ratioLimit == nil && timeMinLimit == nil { + continue + } + // Record seeding start time on first encounter. + if rec.SeedingStartedAt == nil { + if err := s.torrents.SetSeedingStartedAt(ctx, string(snap.ID), &now); err != nil { + log.Warn().Err(err).Str("id", string(snap.ID)).Msg("seed policy: failed to record seeding_started_at") + } + rec.SeedingStartedAt = &now + } + exceeded := false + if ratioLimit != nil && snap.BytesDone > 0 { + ratio := float64(totalUp) / float64(snap.BytesDone) + if ratio >= *ratioLimit { + exceeded = true + } + } + if !exceeded && timeMinLimit != nil && rec.SeedingStartedAt != nil { + elapsed := now.Sub(*rec.SeedingStartedAt) + if elapsed >= time.Duration(*timeMinLimit)*time.Minute { + exceeded = true + } + } + if exceeded { + if err := s.engine.Pause(snap.ID); err != nil { + log.Warn().Err(err).Str("id", string(snap.ID)).Msg("seed policy: pause failed") + } else { + log.Info().Str("id", string(snap.ID)).Str("name", snap.Name).Msg("seed policy: paused torrent — limit reached") + } + } + } + // Prune observations for torrents no longer in the engine so a removed + // and re-added infohash starts from fresh counters and the map doesn't + // grow unbounded across remove cycles. + s.seedCheckMu.Lock() + for hash := range s.lastSeedCounters { + if _, ok := live[hash]; !ok { + delete(s.lastSeedCounters, hash) + } + } + s.seedCheckMu.Unlock() +} + +// checkpointTransferTotals persists the delta between the engine's +// session-scoped transfer counters and the last value this process observed +// for the torrent, returning the updated cumulative uploaded total. A counter +// lower than the last observation means the engine restarted (counters reset +// to zero) — the full current value is the delta. On a write failure the +// observation is rolled back so the delta is retried next pass instead of +// being lost. +func (s *Service) checkpointTransferTotals(ctx context.Context, rec *persistence.TorrentRecord, snap engine.Snapshot) int64 { + hash := string(snap.ID) + s.seedCheckMu.Lock() + last, seen := s.lastSeedCounters[hash] + upDelta, downDelta := snap.BytesUp-last.up, snap.BytesDown-last.down + if upDelta < 0 { + upDelta = snap.BytesUp + } + if downDelta < 0 { + downDelta = snap.BytesDown + } + s.lastSeedCounters[hash] = sessionCounters{up: snap.BytesUp, down: snap.BytesDown} + s.seedCheckMu.Unlock() + if upDelta == 0 && downDelta == 0 { + return rec.TotalUploaded + } + if err := s.torrents.AddTransferTotals(ctx, hash, upDelta, downDelta); err != nil { + log.Warn().Err(err).Str("id", hash).Msg("seed policy: persist transfer totals failed") + s.seedCheckMu.Lock() + if seen { + s.lastSeedCounters[hash] = last + } else { + delete(s.lastSeedCounters, hash) + } + s.seedCheckMu.Unlock() + return rec.TotalUploaded + } + rec.TotalUploaded += upDelta + rec.TotalDownloaded += downDelta + return rec.TotalUploaded +} \ No newline at end of file diff --git a/backend/api/service_settings.go b/backend/api/service_settings.go new file mode 100644 index 0000000..b41bbc8 --- /dev/null +++ b/backend/api/service_settings.go @@ -0,0 +1,741 @@ +package api + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "time" + + "mosaic/backend/persistence" + "mosaic/backend/remote/cred" +) + +// ─── Web config ───────────────────────────────────────────────────────────── + +// WebConfigDTO is the transport shape for the optional HTTP+WS interface. +// APIKey is only populated by RotateAPIKey (shown once); GetWebConfig returns +// the stored key so the UI can display it after navigation. +type WebConfigDTO struct { + Enabled bool `json:"enabled"` + Port int `json:"port"` + BindAll bool `json:"bind_all"` + Username string `json:"username"` + APIKey string `json:"api_key"` +} + +// adminUserID is the id of the admin account seeded by migration 0009. The +// desktop "Web Interface" pane and mosaicd's ephemeral-password bootstrap both +// operate on this user — it is the single login for the desktop build and the +// initial administrator on a fresh mosaicd install. +const adminUserID = 1 + +func (s *Service) GetWebConfig(ctx context.Context) WebConfigDTO { + if !CallerFrom(ctx).CanChangeSettings() { + return WebConfigDTO{} + } + port := s.intSetting(ctx, settingWebPort) + if port == 0 { + port = 8080 + } + dto := WebConfigDTO{ + Enabled: s.boolSetting(ctx, settingWebEnabled), + Port: port, + BindAll: s.boolSettingDefault(ctx, settingWebBindAll, false), + Username: "admin", + } + if u, err := s.users.Get(ctx, adminUserID); err == nil { + dto.Username = u.Username + dto.APIKey = u.APIKeyHint + } + return dto +} + +func (s *Service) SetWebConfig(ctx context.Context, c WebConfigDTO) error { + if !CallerFrom(ctx).CanChangeSettings() { + return ErrForbidden + } + if err := s.setBoolSetting(ctx, settingWebEnabled, c.Enabled); err != nil { + return err + } + if err := s.setIntSetting(ctx, settingWebPort, c.Port); err != nil { + return err + } + if err := s.setBoolSetting(ctx, settingWebBindAll, c.BindAll); err != nil { + return err + } + if c.Username != "" { + u, err := s.users.Get(ctx, adminUserID) + if err == nil && u.Username != c.Username { + u.Username = c.Username + if err := s.users.Update(ctx, u); err != nil { + return err + } + s.invalidateCaller(adminUserID) + } + } + s.fireWebConfigChanged(s.GetWebConfig(ctx)) + return nil +} + +// OnWebConfigChange registers a callback invoked (synchronously) after a +// SetWebConfig call commits. The callback receives the freshly-read DTO so +// the remote.Server can restart with the new bind/port/enabled state. +// Pass nil to unregister. +func (s *Service) OnWebConfigChange(cb func(WebConfigDTO)) { + s.webHookMu.Lock() + s.onWebCfgChanged = cb + s.webHookMu.Unlock() +} + +func (s *Service) fireWebConfigChanged(c WebConfigDTO) { + s.webHookMu.RLock() + cb := s.onWebCfgChanged + s.webHookMu.RUnlock() + if cb != nil { + cb(c) + } +} + +// ─── Web password ──────────────────────────────────────────────────────────── + +// SetWebPassword sets the admin user's password (UI / REST "change password" +// path) and marks it operator-set so mosaicd stops minting ephemeral ones. +// Every active session for that user is revoked. The hash + password_set flag +// are written by a single atomic UPDATE, so there is no partial-failure window. +func (s *Service) SetWebPassword(ctx context.Context, plain string) error { + if !CallerFrom(ctx).CanManageUsers() { + return ErrForbidden + } + if err := s.setUserPasswordHash(ctx, adminUserID, plain, true); err != nil { + return err + } + s.invalidateCaller(adminUserID) + return nil +} + +// SetWebPasswordEphemeral sets the admin user's password without flipping the +// "user set" flag and without touching active sessions. Used only by mosaicd's +// per-restart auto-generated password flow (qBittorrent-nox style). +func (s *Service) SetWebPasswordEphemeral(ctx context.Context, plain string) error { + return s.setUserPasswordHash(ctx, adminUserID, plain, false) +} + +// IsWebPasswordUserSet reports whether the admin user's password was set +// explicitly by the operator. mosaicd consults it to decide whether to mint a +// fresh ephemeral password on each boot. Fail-safe default is true: if the +// admin row is unreadable for any reason, we report "operator-set" so we don't +// silently regenerate a password over the operator's existing one. +func (s *Service) IsWebPasswordUserSet(ctx context.Context) bool { + u, err := s.users.Get(ctx, adminUserID) + if err != nil { + return true + } + return u.PasswordSet +} + +func (s *Service) setUserPasswordHash(ctx context.Context, userID int, plain string, userSet bool) error { + hash, err := cred.HashPassword(plain) + if err != nil { + return err + } + return s.users.SetPasswordHash(ctx, userID, hash, userSet) +} + +// RotateAPIKey mints a fresh API key for the admin user (desktop "Web +// Interface" pane). The cleartext is returned once — only its hash is stored. +func (s *Service) RotateAPIKey(ctx context.Context) (string, error) { + if !CallerFrom(ctx).CanManageUsers() { + return "", ErrForbidden + } + return s.RotateUserAPIKey(ctx, adminUserID) +} + +// ReconcileLegacyAPIKey migrates a pre-0009 plaintext web_api_key setting into +// the admin user's hashed key column, then clears the setting. Idempotent and +// safe to call on every startup: it no-ops once the legacy key is gone or the +// admin already has a key. +func (s *Service) ReconcileLegacyAPIKey(ctx context.Context) error { + legacy, _ := s.settings.Get(ctx, settingWebAPIKey) + if legacy == "" { + return nil + } + u, err := s.users.Get(ctx, adminUserID) + if err != nil { + return err + } + if u.APIKeyHash == "" { + if err := s.users.SetAPIKey(ctx, adminUserID, + cred.HashAPIKey(legacy), cred.APIKeyHint(legacy)); err != nil { + return err + } + } + return s.settings.Set(ctx, settingWebAPIKey, "") +} + +// ─── Save path ─────────────────────────────────────────────────────────────── + +func (s *Service) GetDefaultSavePath(ctx context.Context) (string, error) { + v, err := s.settings.Get(ctx, settingDefaultSavePath) + if errors.Is(err, persistence.ErrNotFound) { + return s.defaultSavePath, nil + } + if err != nil { + return "", err + } + return v, nil +} + +func (s *Service) SetDefaultSavePath(ctx context.Context, path string) error { + if !CallerFrom(ctx).CanChangeSettings() { + return ErrForbidden + } + return s.settings.Set(ctx, settingDefaultSavePath, path) +} + +func (s *Service) defaultPath(ctx context.Context) string { + if v, err := s.GetDefaultSavePath(ctx); err == nil { + return v + } + return s.defaultSavePath +} + +// ─── Bandwidth limits ──────────────────────────────────────────────────────── + +// LimitsDTO is the bandwidth-limits transport shape (kbps units). +type LimitsDTO struct { + DownKbps int `json:"down_kbps"` + UpKbps int `json:"up_kbps"` + AltDownKbps int `json:"alt_down_kbps"` + AltUpKbps int `json:"alt_up_kbps"` + AltActive bool `json:"alt_active"` +} + +func (s *Service) GetLimits(ctx context.Context) (LimitsDTO, error) { + return LimitsDTO{ + DownKbps: s.intSetting(ctx, settingDownKbps), + UpKbps: s.intSetting(ctx, settingUpKbps), + AltDownKbps: s.intSetting(ctx, settingAltDownKbps), + AltUpKbps: s.intSetting(ctx, settingAltUpKbps), + AltActive: s.boolSetting(ctx, settingAltActive), + }, nil +} + +func (s *Service) SetLimits(ctx context.Context, l LimitsDTO) error { + if !CallerFrom(ctx).CanChangeSettings() { + return ErrForbidden + } + if err := s.setIntSetting(ctx, settingDownKbps, l.DownKbps); err != nil { + return err + } + if err := s.setIntSetting(ctx, settingUpKbps, l.UpKbps); err != nil { + return err + } + if err := s.setIntSetting(ctx, settingAltDownKbps, l.AltDownKbps); err != nil { + return err + } + if err := s.setIntSetting(ctx, settingAltUpKbps, l.AltUpKbps); err != nil { + return err + } + if err := s.setBoolSetting(ctx, settingAltActive, l.AltActive); err != nil { + return err + } + return s.applyLimits(ctx) +} + +// ToggleAltSpeed flips the alt-speed flag and reapplies engine limits. Returns +// the new alt_active state. +func (s *Service) ToggleAltSpeed(ctx context.Context) (bool, error) { + if !CallerFrom(ctx).CanChangeSettings() { + return s.boolSetting(ctx, settingAltActive), ErrForbidden + } + cur := s.boolSetting(ctx, settingAltActive) + next := !cur + if err := s.setBoolSetting(ctx, settingAltActive, next); err != nil { + return cur, err + } + return next, s.applyLimits(ctx) +} + +func (s *Service) applyLimits(ctx context.Context) error { + l, _ := s.GetLimits(ctx) + down, up := l.DownKbps*1024, l.UpKbps*1024 + if l.AltActive { + down, up = l.AltDownKbps*1024, l.AltUpKbps*1024 + } + return s.engine.SetGlobalRateLimits(down, up) +} + +// ─── Queue limits ──────────────────────────────────────────────────────────── + +// QueueLimitsDTO is the queue-slot transport shape. +type QueueLimitsDTO struct { + MaxActiveDownloads int `json:"max_active_downloads"` + MaxActiveSeeds int `json:"max_active_seeds"` +} + +func (s *Service) GetQueueLimits(ctx context.Context) QueueLimitsDTO { + return QueueLimitsDTO{ + MaxActiveDownloads: s.intSetting(ctx, settingMaxActiveDL), + MaxActiveSeeds: s.intSetting(ctx, settingMaxActiveSeeds), + } +} + +func (s *Service) SetQueueLimits(ctx context.Context, q QueueLimitsDTO) error { + if !CallerFrom(ctx).CanChangeSettings() { + return ErrForbidden + } + if err := s.setIntSetting(ctx, settingMaxActiveDL, q.MaxActiveDownloads); err != nil { + return err + } + if err := s.setIntSetting(ctx, settingMaxActiveSeeds, q.MaxActiveSeeds); err != nil { + return err + } + if s.scheduler != nil { + s.scheduler.SetLimits(q.MaxActiveDownloads, q.MaxActiveSeeds) + } + return nil +} + +// ─── Peer limits ───────────────────────────────────────────────────────────── + +// PeerLimitsDTO carries the connection-level settings users can adjust from +// Settings → Connection. Most fields require a restart to take effect because +// anacrolix exposes them only at Client construction; MaxPeersPerTorrent is +// runtime-mutable and gets pushed to every running torrent on Set. +type PeerLimitsDTO struct { + ListenPort int `json:"listen_port"` // 0 = let OS pick at startup + MaxPeersPerTorrent int `json:"max_peers_per_torrent"` // 0 = anacrolix default (80) + DHTEnabled bool `json:"dht_enabled"` + EncryptionEnabled bool `json:"encryption_enabled"` + // UPnPEnabled enables automatic UPnP/NAT-PMP port forwarding via the + // router. anacrolix runs the discovery on startup so a restart is required + // after toggling. Defaults to true (anacrolix's own default). + UPnPEnabled bool `json:"upnp_enabled"` +} + +func (s *Service) GetPeerLimits(ctx context.Context) PeerLimitsDTO { + if !CallerFrom(ctx).CanChangeSettings() { + return PeerLimitsDTO{} + } + dhtRaw, _ := s.settings.Get(ctx, settingDHTEnabled) + dhtEnabled := dhtRaw == "" || dhtRaw == "true" // default-on + encRaw, _ := s.settings.Get(ctx, settingEncryptionEnabled) + encEnabled := encRaw == "" || encRaw == "true" // default-on + upnpRaw, _ := s.settings.Get(ctx, settingUPnPEnabled) + upnpEnabled := upnpRaw == "" || upnpRaw == "true" // default-on (matches anacrolix) + return PeerLimitsDTO{ + ListenPort: s.intSetting(ctx, settingPeerListenPort), + MaxPeersPerTorrent: s.intSetting(ctx, settingMaxPeersPerTorrent), + DHTEnabled: dhtEnabled, + EncryptionEnabled: encEnabled, + UPnPEnabled: upnpEnabled, + } +} + +func (s *Service) SetPeerLimits(ctx context.Context, p PeerLimitsDTO) error { + if !CallerFrom(ctx).CanChangeSettings() { + return ErrForbidden + } + if p.ListenPort < 0 || p.ListenPort > 65535 { + return fmt.Errorf("listen port must be 0..65535") + } + if p.MaxPeersPerTorrent < 0 { + return fmt.Errorf("max peers per torrent must be >= 0") + } + if err := s.setIntSetting(ctx, settingPeerListenPort, p.ListenPort); err != nil { + return err + } + if err := s.setIntSetting(ctx, settingMaxPeersPerTorrent, p.MaxPeersPerTorrent); err != nil { + return err + } + if err := s.setBoolSetting(ctx, settingDHTEnabled, p.DHTEnabled); err != nil { + return err + } + if err := s.setBoolSetting(ctx, settingEncryptionEnabled, p.EncryptionEnabled); err != nil { + return err + } + if err := s.setBoolSetting(ctx, settingUPnPEnabled, p.UPnPEnabled); err != nil { + return err + } + if err := s.engine.ApplyPerTorrentMaxPeers(p.MaxPeersPerTorrent); err != nil { + return err + } + return nil +} + +// ─── Schedule rules ────────────────────────────────────────────────────────── + +// ScheduleRuleDTO is the transport shape for a time-of-day bandwidth rule. +type ScheduleRuleDTO struct { + ID int `json:"id"` + DaysMask int `json:"days_mask"` + StartMin int `json:"start_min"` + EndMin int `json:"end_min"` + DownKbps int `json:"down_kbps"` + UpKbps int `json:"up_kbps"` + AltOnly bool `json:"alt_only"` + Enabled bool `json:"enabled"` +} + +func toScheduleRuleDTO(r persistence.ScheduleRule) ScheduleRuleDTO { + return ScheduleRuleDTO{ + ID: r.ID, DaysMask: r.DaysMask, StartMin: r.StartMin, EndMin: r.EndMin, + DownKbps: r.DownKbps, UpKbps: r.UpKbps, AltOnly: r.AltOnly, Enabled: r.Enabled, + } +} + +func (s *Service) ListScheduleRules(ctx context.Context) ([]ScheduleRuleDTO, error) { + if s.scheduleRules == nil { + return nil, nil + } + rules, err := s.scheduleRules.List(ctx) + if err != nil { + return nil, err + } + out := make([]ScheduleRuleDTO, 0, len(rules)) + for _, r := range rules { + out = append(out, toScheduleRuleDTO(r)) + } + return out, nil +} + +func (s *Service) CreateScheduleRule(ctx context.Context, r ScheduleRuleDTO) (int, error) { + if !CallerFrom(ctx).CanChangeSettings() { + return 0, ErrForbidden + } + return s.scheduleRules.Create(ctx, persistence.ScheduleRule{ + DaysMask: r.DaysMask, StartMin: r.StartMin, EndMin: r.EndMin, + DownKbps: r.DownKbps, UpKbps: r.UpKbps, AltOnly: r.AltOnly, Enabled: r.Enabled, + }) +} + +func (s *Service) UpdateScheduleRule(ctx context.Context, r ScheduleRuleDTO) error { + if !CallerFrom(ctx).CanChangeSettings() { + return ErrForbidden + } + return s.scheduleRules.Update(ctx, persistence.ScheduleRule{ + ID: r.ID, DaysMask: r.DaysMask, StartMin: r.StartMin, EndMin: r.EndMin, + DownKbps: r.DownKbps, UpKbps: r.UpKbps, AltOnly: r.AltOnly, Enabled: r.Enabled, + }) +} + +func (s *Service) DeleteScheduleRule(ctx context.Context, id int) error { + if !CallerFrom(ctx).CanChangeSettings() { + return ErrForbidden + } + return s.scheduleRules.Delete(ctx, id) +} + +// ─── IP Blocklist ──────────────────────────────────────────────────────────── + +// BlocklistDTO is the transport shape for the IP blocklist config + status. +type BlocklistDTO struct { + URL string `json:"url"` + Enabled bool `json:"enabled"` + LastLoadedAt int64 `json:"last_loaded_at"` + Entries int `json:"entries"` + Error string `json:"error,omitempty"` +} + +func (s *Service) GetBlocklist(ctx context.Context) BlocklistDTO { + if !CallerFrom(ctx).CanChangeSettings() { + return BlocklistDTO{} + } + rawURL, _ := s.settings.Get(ctx, settingBlocklistURL) + en := s.boolSetting(ctx, settingBlocklistEnabled) + s.blocklistMu.RLock() + defer s.blocklistMu.RUnlock() + dto := BlocklistDTO{URL: redactURLCredentials(rawURL), Enabled: en, Entries: s.blocklist.entries, Error: s.blocklist.lastErr} + if !s.blocklist.loadedAt.IsZero() { + dto.LastLoadedAt = s.blocklist.loadedAt.Unix() + } + return dto +} + +// redactURLCredentials strips userinfo from a URL so a stored "http://user:pw@host/..." +// blocklist URL doesn't leak the password back to the SPA in GetBlocklist. The +// raw URL with credentials remains in settings (so refresh still works); only +// the DTO is scrubbed. +func redactURLCredentials(raw string) string { + if raw == "" { + return raw + } + u, err := url.Parse(raw) + if err != nil || u.User == nil { + return raw + } + u.User = nil + return u.String() +} + +func (s *Service) SetBlocklistURL(ctx context.Context, url string, enabled bool) error { + if !CallerFrom(ctx).CanChangeSettings() { + return ErrForbidden + } + if enabled && url != "" { + if _, err := validateFetchURL(url); err != nil { + return fmt.Errorf("blocklist URL must be http or https and not point at a private/loopback address: %w", err) + } + } + if err := s.settings.Set(ctx, settingBlocklistURL, url); err != nil { + return err + } + if err := s.setBoolSetting(ctx, settingBlocklistEnabled, enabled); err != nil { + return err + } + if !enabled || url == "" { + _ = s.engine.SetIPBlocklist(nil) + s.blocklistMu.Lock() + s.blocklist = blocklistState{} + s.blocklistMu.Unlock() + return nil + } + return s.RefreshBlocklist(ctx) +} + +func (s *Service) RefreshBlocklist(ctx context.Context) error { + if !CallerFrom(ctx).CanChangeSettings() { + return ErrForbidden + } + url, _ := s.settings.Get(ctx, settingBlocklistURL) + if url == "" { + return errors.New("no blocklist URL configured") + } + if _, err := validateFetchURL(url); err != nil { + return fmt.Errorf("refusing to fetch blocklist: %w", err) + } + + httpCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(httpCtx, "GET", url, nil) + if err != nil { + return err + } + client := safeHTTPClient(30 * time.Second) + resp, err := client.Do(req) + if err != nil { + s.blocklistMu.Lock() + s.blocklist.lastErr = err.Error() + s.blocklistMu.Unlock() + return err + } + defer resp.Body.Close() + + body, err := io.ReadAll(io.LimitReader(resp.Body, 50*1024*1024)) // 50MB safety cap + if err != nil { + s.blocklistMu.Lock() + s.blocklist.lastErr = err.Error() + s.blocklistMu.Unlock() + return err + } + + if err := s.engine.SetIPBlocklist(bytes.NewReader(body)); err != nil { + s.blocklistMu.Lock() + s.blocklist.lastErr = err.Error() + s.blocklistMu.Unlock() + return err + } + + s.blocklistMu.Lock() + s.blocklist = blocklistState{loadedAt: time.Now(), entries: countLines(body), lastErr: ""} + s.blocklistMu.Unlock() + return nil +} + +func countLines(b []byte) int { + n := 0 + for _, x := range b { + if x == '\n' { + n++ + } + } + return n +} + +// ─── Watch folder ──────────────────────────────────────────────────────────── + +// WatchFolderDTO is the transport shape for the watch-folder settings. +type WatchFolderDTO struct { + Path string `json:"path"` + DeleteAfterAdd bool `json:"delete_after_add"` + Enabled bool `json:"enabled"` +} + +// GetWatchFolder reads the current watch-folder configuration from settings. +func (s *Service) GetWatchFolder(ctx context.Context) WatchFolderDTO { + if !CallerFrom(ctx).CanChangeSettings() { + return WatchFolderDTO{} + } + path, _ := s.settings.Get(ctx, settingWatchFolderPath) + return WatchFolderDTO{ + Path: path, + DeleteAfterAdd: s.boolSetting(ctx, settingWatchFolderDeleteAfterAdd), + Enabled: s.boolSetting(ctx, settingWatchFolderEnabled), + } +} + +// SetWatchFolder persists the watch-folder configuration and (re)starts or +// stops the watcher accordingly. +func (s *Service) SetWatchFolder(ctx context.Context, c WatchFolderDTO) error { + if !CallerFrom(ctx).IsAdmin() { + return ErrForbidden + } + if err := s.settings.Set(ctx, settingWatchFolderPath, c.Path); err != nil { + return err + } + if err := s.setBoolSetting(ctx, settingWatchFolderDeleteAfterAdd, c.DeleteAfterAdd); err != nil { + return err + } + if err := s.setBoolSetting(ctx, settingWatchFolderEnabled, c.Enabled); err != nil { + return err + } + if s.watchFolder != nil { + if c.Enabled && c.Path != "" { + s.watchFolder.Start(c.Path, c.DeleteAfterAdd) + } else { + s.watchFolder.Stop() + } + } + return nil +} + +// AttachWatchFolder wires the live *WatchFolder into the Service so that +// SetWatchFolder can (re)start the polling loop when the user changes the +// configuration. main.go calls this once after construction. +func (s *Service) AttachWatchFolder(w *WatchFolder) { + s.watchFolder = w +} + +// ─── Desktop integration ───────────────────────────────────────────────────── + +// DesktopIntegrationDTO is the transport shape for system-tray + notifications +// + close-to-tray preferences. The frontend keys off these JSON names; do not +// rename without coordinating with the frontend agent owning the settings UI. +type DesktopIntegrationDTO struct { + TrayEnabled bool `json:"tray_enabled"` // default true + CloseToTray bool `json:"close_to_tray"` // default true on Linux/Windows when tray is enabled; ignored on macOS + StartMinimized bool `json:"start_minimized"` // default false — start hidden in tray, no window + NotifyOnComplete bool `json:"notify_on_complete"` // default true + NotifyOnError bool `json:"notify_on_error"` // default true + NotifyOnUpdate bool `json:"notify_on_update"` // default true +} + +// boolSettingDefault reads a bool setting with a presence-aware default — +// "" (never written) returns def, otherwise "true"/"false" parses normally. +// This is the shape we want for DesktopIntegrationDTO defaults: a fresh DB +// must yield TrayEnabled=true even though boolSetting alone would return false. +func (s *Service) boolSettingDefault(ctx context.Context, key string, def bool) bool { + v, err := s.settings.Get(ctx, key) + if err != nil || v == "" { + return def + } + return v == "true" +} + +func (s *Service) GetDesktopIntegration(ctx context.Context) DesktopIntegrationDTO { + return DesktopIntegrationDTO{ + TrayEnabled: s.boolSettingDefault(ctx, settingDesktopTrayEnabled, true), + CloseToTray: s.boolSettingDefault(ctx, settingDesktopCloseToTray, true), + StartMinimized: s.boolSettingDefault(ctx, settingDesktopStartMinimized, false), + NotifyOnComplete: s.boolSettingDefault(ctx, settingDesktopNotifyOnComplete, true), + NotifyOnError: s.boolSettingDefault(ctx, settingDesktopNotifyOnError, true), + NotifyOnUpdate: s.boolSettingDefault(ctx, settingDesktopNotifyOnUpdate, true), + } +} + +// SetDesktopIntegration persists the user's desktop-integration preferences +// and fires the change hook so the running tray/notifications goroutines can +// reconfigure themselves. No validation: the user is allowed to disable +// everything (a perfectly reasonable choice). +func (s *Service) SetDesktopIntegration(ctx context.Context, c DesktopIntegrationDTO) error { + if !CallerFrom(ctx).CanChangeSettings() { + return ErrForbidden + } + if err := s.setBoolSetting(ctx, settingDesktopTrayEnabled, c.TrayEnabled); err != nil { + return err + } + if err := s.setBoolSetting(ctx, settingDesktopCloseToTray, c.CloseToTray); err != nil { + return err + } + if err := s.setBoolSetting(ctx, settingDesktopStartMinimized, c.StartMinimized); err != nil { + return err + } + if err := s.setBoolSetting(ctx, settingDesktopNotifyOnComplete, c.NotifyOnComplete); err != nil { + return err + } + if err := s.setBoolSetting(ctx, settingDesktopNotifyOnError, c.NotifyOnError); err != nil { + return err + } + if err := s.setBoolSetting(ctx, settingDesktopNotifyOnUpdate, c.NotifyOnUpdate); err != nil { + return err + } + s.fireDesktopIntegrationChanged(c) + return nil +} + +// IsGnomeAppIndicatorPromptDismissed reports whether the user has +// previously clicked Dismiss on the in-app Gnome AppIndicator prompt. +// Once true, the SPA stops showing the prompt even if the tray watcher +// is still absent — manual re-trigger via Settings would be the path +// back to nagging if we ever surface that. +func (s *Service) IsGnomeAppIndicatorPromptDismissed(ctx context.Context) bool { + v, _ := s.settings.Get(ctx, settingGnomeAppIndicatorDismissed) + return v == "true" +} + +// DismissGnomeAppIndicatorPrompt persists the "user said no" flag. +func (s *Service) DismissGnomeAppIndicatorPrompt(ctx context.Context) error { + return s.settings.Set(ctx, settingGnomeAppIndicatorDismissed, "true") +} + +// OnDesktopIntegrationChange registers a synchronous callback invoked after a +// SetDesktopIntegration commit. main.go uses this to push the updated +// notification toggles into the live notifications.Subscriber. Pass nil to +// unregister. Only one callback is supported. +func (s *Service) OnDesktopIntegrationChange(cb func(DesktopIntegrationDTO)) { + s.desktopHookMu.Lock() + s.onDesktopChanged = cb + s.desktopHookMu.Unlock() +} + +func (s *Service) fireDesktopIntegrationChanged(c DesktopIntegrationDTO) { + s.desktopHookMu.RLock() + cb := s.onDesktopChanged + s.desktopHookMu.RUnlock() + if cb != nil { + cb(c) + } +} + +// ─── Setting helpers ───────────────────────────────────────────────────────── + +func (s *Service) intSetting(ctx context.Context, key string) int { + v, err := s.settings.Get(ctx, key) + if err != nil { + return 0 + } + n, _ := strconv.Atoi(v) + return n +} + +func (s *Service) setIntSetting(ctx context.Context, key string, n int) error { + return s.settings.Set(ctx, key, strconv.Itoa(n)) +} + +func (s *Service) boolSetting(ctx context.Context, key string) bool { + v, _ := s.settings.Get(ctx, key) + return v == "true" +} + +func (s *Service) setBoolSetting(ctx context.Context, key string, b bool) error { + v := "false" + if b { + v = "true" + } + return s.settings.Set(ctx, key, v) +} \ No newline at end of file diff --git a/backend/api/service_torrents.go b/backend/api/service_torrents.go new file mode 100644 index 0000000..a19ccd6 --- /dev/null +++ b/backend/api/service_torrents.go @@ -0,0 +1,1125 @@ +package api + +import ( + "context" + "fmt" + "net/url" + "os" + "path/filepath" + "sort" + "time" + + "github.com/rs/zerolog/log" + + "mosaic/backend/engine" + "mosaic/backend/persistence" +) + +// TorrentDTO is the shape returned to UI/transport callers. +type TorrentDTO struct { + ID string `json:"id"` + Name string `json:"name"` + Magnet string `json:"magnet"` + SavePath string `json:"save_path"` + TotalBytes int64 `json:"total_bytes"` + BytesDone int64 `json:"bytes_done"` + Progress float64 `json:"progress"` // 0..1 + DownloadRate int64 `json:"download_rate"` + UploadRate int64 `json:"upload_rate"` + Peers int `json:"peers"` + Seeds int `json:"seeds"` + Paused bool `json:"paused"` + Completed bool `json:"completed"` + AddedAt int64 `json:"added_at"` // unix seconds + CategoryID *int `json:"category_id"` + Tags []TagDTO `json:"tags"` + QueuePosition int `json:"queue_position"` + ForceStart bool `json:"force_start"` + Sequential bool `json:"sequential"` + Queued bool `json:"queued"` + Verifying bool `json:"verifying"` + FilesMissing bool `json:"files_missing"` + // Access is the requesting caller's access level on this torrent + // ("owner" | "editor" | "viewer"). Admins always see "owner". The SPA + // uses it to gate per-row controls. + Access string `json:"access"` +} + +// unixOrZero serializes a record timestamp for the wire, mapping the zero +// time (record missing or lookup failed) to 0. time.Time{}.Unix() is +// -62135596800, which the SPA would render as a date in year 1. +func unixOrZero(t time.Time) int64 { + if t.IsZero() { + return 0 + } + return t.Unix() +} + +func toDTO(s engine.Snapshot, addedAt time.Time) TorrentDTO { + prog := 0.0 + if s.TotalBytes > 0 { + prog = float64(s.BytesDone) / float64(s.TotalBytes) + } + return TorrentDTO{ + ID: string(s.ID), + Name: s.Name, + Magnet: s.Magnet, + SavePath: s.SavePath, + TotalBytes: s.TotalBytes, + BytesDone: s.BytesDone, + Progress: prog, + DownloadRate: s.RateDown, + UploadRate: s.RateUp, + Peers: s.Peers, + Seeds: s.Seeds, + Paused: s.Paused, + Completed: s.Completed, + AddedAt: unixOrZero(addedAt), + QueuePosition: s.QueuePosition, + ForceStart: s.ForceStart, + Sequential: s.Sequential, + Queued: s.Queued, + Verifying: s.Verifying, + FilesMissing: s.FilesMissing, + } +} + +func (s *Service) AddMagnet(ctx context.Context, magnet, savePath string) (engine.TorrentID, error) { + caller := CallerFrom(ctx) + if !caller.CanAddTorrents() { + return "", ErrForbidden + } + savePath, err := s.resolveSavePath(ctx, caller, savePath) + if err != nil { + return "", err + } + id, err := s.engine.AddMagnet(ctx, magnet, savePath) + if err != nil { + return "", fmt.Errorf("add magnet: %w", err) + } + snap, err := s.engine.Snapshot(id) + if err != nil { + if rmErr := s.engine.Remove(id, false); rmErr != nil { + log.Warn().Err(rmErr).Str("infohash", string(id)).Msg("AddMagnet: engine rollback after snapshot failure also failed") + } + return "", err + } + if err := s.persistAndGrantTorrent(ctx, id, caller, persistence.TorrentRecord{ + InfoHash: string(id), + Name: snap.Name, + Magnet: magnet, + SavePath: savePath, + AddedAt: time.Now(), + }); err != nil { + return "", err + } + return id, nil +} + +// grantOwner records that the caller owns a torrent. Adding an infohash that +// another user already added makes the caller a co-owner (Grant upserts). +func (s *Service) grantOwner(ctx context.Context, infohash string, caller Caller) error { + uid := caller.UserID + return s.access.Grant(ctx, infohash, uid, persistence.AccessOwner, &uid) +} + +// persistAndGrantTorrent runs the post-engine-add steps (persist record, +// record ownership) with rollback semantics. The caller has already added the +// torrent to the engine and provides the persistence record. Without this +// rollback, a failed Save left the torrent in the engine but absent from the +// DB — it would download for the rest of this session, then vanish on next +// restart (RestoreOnStartup walks the DB, not the engine). A failed grantOwner +// left an orphaned, ownerless record visible to admins only. +// +// engine.Remove is called with deleteFiles=false: the operation just failed, +// nothing material has been downloaded yet, and we don't want to clobber +// anything that might have. Rollback errors are logged but not returned — +// the original failure is what the caller needs to see. +func (s *Service) persistAndGrantTorrent(ctx context.Context, id engine.TorrentID, caller Caller, rec persistence.TorrentRecord) error { + if err := s.torrents.Save(ctx, rec); err != nil { + if rmErr := s.engine.Remove(id, false); rmErr != nil { + log.Warn().Err(rmErr).Str("infohash", string(id)).Msg("add torrent: engine rollback after persist failure also failed; torrent will linger until restart") + } + return fmt.Errorf("persist: %w", err) + } + if err := s.grantOwner(ctx, string(id), caller); err != nil { + if rmErr := s.torrents.Remove(ctx, string(id)); rmErr != nil { + log.Warn().Err(rmErr).Str("infohash", string(id)).Msg("add torrent: persist rollback after grant failure also failed; record will survive as orphaned") + } + if rmErr := s.engine.Remove(id, false); rmErr != nil { + log.Warn().Err(rmErr).Str("infohash", string(id)).Msg("add torrent: engine rollback after grant failure also failed; torrent will linger until restart") + } + return fmt.Errorf("grant owner: %w", err) + } + return nil +} + +// resolveSavePath returns the cleaned absolute save path the engine should +// MkdirAll into, after applying the per-user containment policy. +// +// Admins (including the system caller used by the Wails desktop and internal +// workers) keep unrestricted behavior — the operator already has shell access +// to the host. Non-admin callers are pinned to /: +// an unconstrained save_path would let a low-privilege multi-user mosaicd +// account write torrent data into arbitrary directories the daemon process +// can reach (/etc/cron.d, another user's home, the daemon's data dir). +func (s *Service) resolveSavePath(ctx context.Context, caller Caller, savePath string) (string, error) { + if caller.IsAdmin() { + if savePath == "" { + savePath = s.defaultPath(ctx) + } + return engine.ValidateSavePath("", savePath, false) + } + if caller.Username == "" || s.defaultSavePath == "" { + return "", ErrForbidden + } + userRoot := filepath.Join(s.defaultSavePath, caller.Username) + if savePath == "" { + savePath = userRoot + } + return engine.ValidateSavePath(userRoot, savePath, true) +} + +// requireTorrentAccess returns ErrForbidden unless the caller holds at least +// minLevel access on the torrent. Admins and the system caller always pass. +func (s *Service) requireTorrentAccess(ctx context.Context, infohash, minLevel string) error { + caller := CallerFrom(ctx) + if caller.SeesAllTorrents() { + return nil + } + lvl, err := s.access.AccessFor(ctx, infohash, caller.UserID) + if err != nil { + return err + } + if persistence.AccessRank(lvl) < persistence.AccessRank(minLevel) { + return ErrForbidden + } + return nil +} + +func (s *Service) AddTorrentFile(ctx context.Context, filePath, savePath string) (engine.TorrentID, error) { + caller := CallerFrom(ctx) + if !caller.CanAddTorrents() { + return "", ErrForbidden + } + savePath, err := s.resolveSavePath(ctx, caller, savePath) + if err != nil { + return "", err + } + blob, err := os.ReadFile(filePath) + if err != nil { + return "", fmt.Errorf("read torrent file: %w", err) + } + id, err := s.engine.AddFile(ctx, blob, savePath) + if err != nil { + return "", fmt.Errorf("add torrent: %w", err) + } + snap, err := s.engine.Snapshot(id) + if err != nil { + if rmErr := s.engine.Remove(id, false); rmErr != nil { + log.Warn().Err(rmErr).Str("infohash", string(id)).Msg("AddTorrentFile: engine rollback after snapshot failure also failed") + } + return "", err + } + if err := s.persistAndGrantTorrent(ctx, id, caller, persistence.TorrentRecord{ + InfoHash: string(id), + Name: snap.Name, + SavePath: savePath, + AddedAt: time.Now(), + Metainfo: blob, + }); err != nil { + return "", err + } + return id, nil +} + +func (s *Service) AddTorrentBytes(ctx context.Context, blob []byte, savePath string) (engine.TorrentID, error) { + caller := CallerFrom(ctx) + if !caller.CanAddTorrents() { + return "", ErrForbidden + } + savePath, err := s.resolveSavePath(ctx, caller, savePath) + if err != nil { + return "", err + } + id, err := s.engine.AddFile(ctx, blob, savePath) + if err != nil { + return "", fmt.Errorf("add torrent bytes: %w", err) + } + snap, err := s.engine.Snapshot(id) + if err != nil { + if rmErr := s.engine.Remove(id, false); rmErr != nil { + log.Warn().Err(rmErr).Str("infohash", string(id)).Msg("AddTorrentBytes: engine rollback after snapshot failure also failed") + } + return "", err + } + if err := s.persistAndGrantTorrent(ctx, id, caller, persistence.TorrentRecord{ + InfoHash: string(id), + Name: snap.Name, + SavePath: savePath, + AddedAt: time.Now(), + Metainfo: blob, + }); err != nil { + return "", err + } + return id, nil +} + +// Pause/Resume/Recheck require editor-or-higher access on the torrent. +func (s *Service) Pause(ctx context.Context, id engine.TorrentID) error { + if err := s.requireTorrentAccess(ctx, string(id), persistence.AccessEditor); err != nil { + return err + } + if err := s.engine.Pause(id); err != nil { + return err + } + if err := s.torrents.SetPaused(ctx, string(id), true); err != nil { + log.Warn().Err(err).Str("id", string(id)).Msg("Pause: persist paused state failed") + } + return nil +} + +func (s *Service) Resume(ctx context.Context, id engine.TorrentID) error { + if err := s.requireTorrentAccess(ctx, string(id), persistence.AccessEditor); err != nil { + return err + } + if err := s.engine.Resume(id); err != nil { + return err + } + if err := s.torrents.SetPaused(ctx, string(id), false); err != nil { + log.Warn().Err(err).Str("id", string(id)).Msg("Resume: persist paused state failed") + } + return nil +} + +func (s *Service) Recheck(ctx context.Context, id engine.TorrentID) error { + if err := s.requireTorrentAccess(ctx, string(id), persistence.AccessEditor); err != nil { + return err + } + return s.engine.Recheck(id) +} + +// PauseAll pauses every torrent currently known to the engine. Errors on +// individual torrents are logged but don't abort the loop — best-effort +// semantics so a single missing/dead torrent can't strand the rest. +// Used by the system-tray "Pause all" item. +func (s *Service) PauseAll(ctx context.Context) { + for _, snap := range s.engine.List() { + if snap.Paused { + continue + } + if err := s.engine.Pause(snap.ID); err != nil { + log.Warn().Err(err).Str("id", string(snap.ID)).Msg("PauseAll: pause failed") + continue + } + if err := s.torrents.SetPaused(ctx, string(snap.ID), true); err != nil { + log.Warn().Err(err).Str("id", string(snap.ID)).Msg("PauseAll: persist paused state failed") + } + } +} + +// ResumeAll is the mirror of PauseAll. Used by the system-tray "Resume all" +// item when the engine is in the globally-paused state. +func (s *Service) ResumeAll(ctx context.Context) { + for _, snap := range s.engine.List() { + if !snap.Paused { + continue + } + if err := s.engine.Resume(snap.ID); err != nil { + log.Warn().Err(err).Str("id", string(snap.ID)).Msg("ResumeAll: resume failed") + continue + } + if err := s.torrents.SetPaused(ctx, string(snap.ID), false); err != nil { + log.Warn().Err(err).Str("id", string(snap.ID)).Msg("ResumeAll: persist paused state failed") + } + } +} + +// UpdateInstalledNotifier is the post-install hook the desktop-integration +// notifications package implements. Defining the contract as an interface +// here keeps the api package free of a notifications-package import. +type UpdateInstalledNotifier interface { + NotifyUpdateInstalled(version string) +} + +// AttachUpdateInstalledNotifier wires the notifications subscriber into the +// Service so InstallUpdate can fire the OS-level notification on success. +// Pass nil (or never call) to disable the post-install notification. +func (s *Service) AttachUpdateInstalledNotifier(n UpdateInstalledNotifier) { + s.updateInstalledNotifier = n +} + +// Remove tears a torrent down or detaches it from the caller's view. An admin +// (or the last remaining owner) fully removes it from the engine + database; +// any other user with access just loses their own grant — the torrent keeps +// running for everyone else. A caller with no access gets ErrForbidden. +func (s *Service) Remove(ctx context.Context, id engine.TorrentID, deleteFiles bool) error { + caller := CallerFrom(ctx) + hash := string(id) + if !caller.SeesAllTorrents() { + lvl, err := s.access.AccessFor(ctx, hash, caller.UserID) + if err != nil { + return err + } + if lvl == "" { + return ErrForbidden + } + if lvl != persistence.AccessOwner { + return s.access.Revoke(ctx, hash, caller.UserID) + } + owners, err := s.access.OwnerCount(ctx, hash) + if err != nil { + return err + } + if owners > 1 { + return s.access.Revoke(ctx, hash, caller.UserID) + } + } + if err := s.engine.Remove(id, deleteFiles); err != nil { + return err + } + // torrent_access rows cascade-delete with the torrents row. + return s.torrents.Remove(ctx, hash) +} + +// TorrentTickSnapshot is the per-tick state shared across every connected +// user: the engine's torrent snapshots, the persistence records keyed by +// infohash, and the tags map. None of it is caller-dependent, so mosaicd's +// streamTicks builds it ONCE per tick (see BuildTorrentTickSnapshot) and then +// fans it out — instead of re-running torrents.List + tags.ForAllTorrents + +// the full engine walk once per connected user. +type TorrentTickSnapshot struct { + snaps []engine.Snapshot + byHash map[string]persistence.TorrentRecord + tagsByHash map[string][]persistence.Tag +} + +// BuildTorrentTickSnapshot gathers the caller-independent torrent state for +// one tick. Call it once, then pass the result to ListTorrentsFromSnapshot / +// GlobalStatsFromSnapshot for each connected user. +func (s *Service) BuildTorrentTickSnapshot(ctx context.Context) (TorrentTickSnapshot, error) { + records, err := s.torrents.List(ctx) + if err != nil { + return TorrentTickSnapshot{}, err + } + byHash := make(map[string]persistence.TorrentRecord, len(records)) + for _, r := range records { + byHash[r.InfoHash] = r + } + // Pre-v0.4.3 we called s.tags.ForTorrent(ctx, infohash) inside the DTO + // loop — N+1 SELECTs every tick (~500ms cadence). One bulk fetch instead, + // hashed by infohash so assembly is an O(1) lookup. + tagsByHash, err := s.tags.ForAllTorrents(ctx) + if err != nil { + return TorrentTickSnapshot{}, err + } + snaps := s.engine.List() + // Persist completed_at the first time we observe a torrent complete. + // Every flavor's tick path funnels through here, so this is the one + // choke point where the service sees the completion transition. The + // record's nil check keeps the write to exactly once per torrent — + // RestoreOnStartup reads the column to arm missing-files detection, and + // the inspector surfaces it as DetailDTO.CompletedAt. + now := time.Now() + for _, snap := range snaps { + rec, ok := byHash[string(snap.ID)] + if !ok || !snap.Completed || rec.CompletedAt != nil { + continue + } + if err := s.torrents.SetCompletedAt(ctx, string(snap.ID), now); err != nil { + log.Warn().Err(err).Str("id", string(snap.ID)).Msg("tick: persist completed_at failed") + continue + } + t := now + rec.CompletedAt = &t + byHash[string(snap.ID)] = rec + } + return TorrentTickSnapshot{ + snaps: snaps, + byHash: byHash, + tagsByHash: tagsByHash, + }, nil +} + +func (s *Service) ListTorrents(ctx context.Context) ([]TorrentDTO, error) { + tick, err := s.BuildTorrentTickSnapshot(ctx) + if err != nil { + return nil, err + } + return s.ListTorrentsFromSnapshot(ctx, tick) +} + +// ListTorrentsFromSnapshot assembles a caller's torrent DTO list from an +// already-built TorrentTickSnapshot. The shared snapshot is byte-identical +// across users; only the access filter, per-user Access level, sort, and DTO +// assembly happen here — so streamTicks pays the DB/engine cost once per tick +// rather than once per connected user. Output matches the old per-user +// ListTorrents exactly. +func (s *Service) ListTorrentsFromSnapshot(ctx context.Context, tick TorrentTickSnapshot) ([]TorrentDTO, error) { + caller := CallerFrom(ctx) + var accessByHash map[string]string + if !caller.SeesAllTorrents() { + var err error + accessByHash, err = s.access.InfohashesForUser(ctx, caller.UserID) + if err != nil { + return nil, err + } + } + out := make([]TorrentDTO, 0, len(tick.snaps)) + for _, snap := range tick.snaps { + hash := string(snap.ID) + access := persistence.AccessOwner + if !caller.SeesAllTorrents() { + lvl, visible := accessByHash[hash] + if !visible { + continue + } + access = lvl + } + rec, ok := tick.byHash[hash] + var addedAt time.Time + if ok { + snap.SavePath = rec.SavePath + if snap.Magnet == "" { + snap.Magnet = rec.Magnet + } + addedAt = rec.AddedAt + } + dto := toDTO(snap, addedAt) + dto.Access = access + if ok { + dto.CategoryID = rec.CategoryID + } + tags := tick.tagsByHash[hash] + dto.Tags = make([]TagDTO, 0, len(tags)) + for _, tg := range tags { + dto.Tags = append(dto.Tags, TagDTO{ID: tg.ID, Name: tg.Name, Color: tg.Color}) + } + out = append(out, dto) + } + sort.Slice(out, func(i, j int) bool { + if out[i].AddedAt != out[j].AddedAt { + return out[i].AddedAt > out[j].AddedAt + } + return out[i].ID < out[j].ID + }) + return out, nil +} + +// GlobalStats is the snapshot displayed in the status bar. +type GlobalStats struct { + TotalTorrents int `json:"total_torrents"` + ActiveTorrents int `json:"active_torrents"` + SeedingTorrents int `json:"seeding_torrents"` + TotalDownloadRate int64 `json:"total_download_rate"` + TotalUploadRate int64 `json:"total_upload_rate"` + TotalPeers int `json:"total_peers"` +} + +// EngineSnapshots returns the engine's current per-torrent snapshot slice. +// It is caller-independent: streamTicks walks the engine once per tick and +// passes the result to GlobalStatsFromSnapshot for each connected user. +func (s *Service) EngineSnapshots() []engine.Snapshot { + return s.engine.List() +} + +func (s *Service) GlobalStats(ctx context.Context) (GlobalStats, error) { + return s.GlobalStatsFromSnapshot(ctx, s.engine.List()) +} + +// GlobalStatsFromSnapshot computes a caller's status-bar aggregate from an +// already-fetched engine snapshot slice. The snapshot is identical across +// users; per-user stats are just a filtered reduction of it, so streamTicks +// can walk the engine once per tick and reuse the slice for every connected +// user. Output matches the old per-user GlobalStats exactly. +func (s *Service) GlobalStatsFromSnapshot(ctx context.Context, snaps []engine.Snapshot) (GlobalStats, error) { + caller := CallerFrom(ctx) + var visible map[string]string + if !caller.SeesAllTorrents() { + var err error + visible, err = s.access.InfohashesForUser(ctx, caller.UserID) + if err != nil { + return GlobalStats{}, err + } + } + var st GlobalStats + for _, snap := range snaps { + if visible != nil { + if _, ok := visible[string(snap.ID)]; !ok { + continue + } + } + st.TotalTorrents++ + if !snap.Paused && !snap.Completed { + st.ActiveTorrents++ + } + if snap.Completed { + st.SeedingTorrents++ + } + st.TotalDownloadRate += snap.RateDown + st.TotalUploadRate += snap.RateUp + st.TotalPeers += snap.Peers + } + return st, nil +} + +// ─── Inspector ─────────────────────────────────────────────────────────────── + +// DetailDTO is the inspector tick payload, returned from DetailForFocus or +// emitted via the inspector:tick event. +type DetailDTO struct { + ID string `json:"id"` + Name string `json:"name"` + // Overview-tab fields — always present + Magnet string `json:"magnet"` + SavePath string `json:"save_path"` + TotalBytes int64 `json:"total_bytes"` + BytesDone int64 `json:"bytes_done"` + Progress float64 `json:"progress"` + Ratio float64 `json:"ratio"` + TotalDown int64 `json:"total_down"` + TotalUp int64 `json:"total_up"` + Peers int `json:"peers"` + Seeds int `json:"seeds"` + AddedAt int64 `json:"added_at"` + CompletedAt int64 `json:"completed_at,omitempty"` + // Status flags so the inspector can color the progress bar without + // re-deriving from the torrents list. + Paused bool `json:"paused"` + Completed bool `json:"completed"` + FilesMissing bool `json:"files_missing"` + + Files []FileDTO `json:"files,omitempty"` + PeersList []PeerDTO `json:"peers_list,omitempty"` + Trackers []TrackerDTO `json:"trackers,omitempty"` +} + +type FileDTO struct { + Index int `json:"index"` + Path string `json:"path"` + Size int64 `json:"size"` + BytesDone int64 `json:"bytes_done"` + Progress float64 `json:"progress"` + Priority string `json:"priority"` // "skip" | "normal" | "high" | "max" +} + +type PeerDTO struct { + IP string `json:"ip"` + Port int `json:"port"` + Client string `json:"client"` + Flags string `json:"flags"` + Progress float64 `json:"progress"` + DownloadRate int64 `json:"download_rate"` + UploadRate int64 `json:"upload_rate"` + Country string `json:"country"` +} + +type TrackerDTO struct { + URL string `json:"url"` + Status string `json:"status"` + Seeds int `json:"seeds"` + Peers int `json:"peers"` + Downloaded int `json:"downloaded"` + LastAnnounce int64 `json:"last_announce"` + NextAnnounce int64 `json:"next_announce"` +} + +// SetInspectorFocus tells the service which torrent + tabs the caller's UI is +// looking at. Focus is tracked per user, so concurrent mosaicd sessions don't +// clobber each other. Subsequent DetailForFocus calls (and the inspector:tick +// event) return the appropriately-scoped Detail. tabs is a subset of: +// "overview", "files", "peers", "trackers", "speed". +func (s *Service) SetInspectorFocus(ctx context.Context, id string, tabs []string) error { + uid := CallerFrom(ctx).UserID + if id == "" { + s.ClearInspectorFocus(ctx) + return nil + } + scope := scopeForTabs(tabs) + s.focusMu.Lock() + s.focus[uid] = focusState{id: engine.TorrentID(id), scope: scope} + s.focusMu.Unlock() + return nil +} + +// ClearInspectorFocus drops the caller's inspector focus. +func (s *Service) ClearInspectorFocus(ctx context.Context) { + uid := CallerFrom(ctx).UserID + s.focusMu.Lock() + delete(s.focus, uid) + s.focusMu.Unlock() +} + +// DetailForFocus returns the caller's focused torrent detail, or nil if no +// focus is set or the caller no longer has access to that torrent. +func (s *Service) DetailForFocus(ctx context.Context) (*DetailDTO, error) { + caller := CallerFrom(ctx) + s.focusMu.RLock() + f, ok := s.focus[caller.UserID] + s.focusMu.RUnlock() + if !ok || f.id == "" { + return nil, nil + } + if !caller.SeesAllTorrents() { + lvl, err := s.access.AccessFor(ctx, string(f.id), caller.UserID) + if err != nil { + return nil, err + } + if lvl == "" { + return nil, nil + } + } + d, err := s.engine.DetailedSnapshot(f.id, f.scope) + if err != nil { + return nil, err + } + addedAt, completedAt := s.lookupRecordTimes(ctx, f.id) + dto := detailToDTO(d, addedAt, completedAt) + return &dto, nil +} + +func scopeForTabs(tabs []string) engine.DetailScope { + scope := engine.DetailScope{} + for _, t := range tabs { + switch t { + case "files": + scope.Files = true + case "peers": + scope.Peers = true + case "trackers": + scope.Trackers = true + } + } + return scope +} + +func (s *Service) lookupRecordTimes(ctx context.Context, id engine.TorrentID) (time.Time, *time.Time) { + rec, err := s.torrents.Get(ctx, string(id)) + if err != nil { + return time.Time{}, nil + } + return rec.AddedAt, rec.CompletedAt +} + +func detailToDTO(d engine.Detail, addedAt time.Time, completedAt *time.Time) DetailDTO { + snap := d.Snapshot + prog := 0.0 + if snap.TotalBytes > 0 { + prog = float64(snap.BytesDone) / float64(snap.TotalBytes) + } + dto := DetailDTO{ + ID: string(snap.ID), + Name: snap.Name, + Magnet: snap.Magnet, + SavePath: snap.SavePath, + TotalBytes: snap.TotalBytes, + BytesDone: snap.BytesDone, + Progress: prog, + Ratio: ratioOf(snap.BytesDown, snap.BytesUp), + TotalDown: snap.BytesDown, + TotalUp: snap.BytesUp, + Peers: snap.Peers, + Seeds: snap.Seeds, + AddedAt: unixOrZero(addedAt), + Paused: snap.Paused, + Completed: snap.Completed, + FilesMissing: snap.FilesMissing, + } + if completedAt != nil { + dto.CompletedAt = completedAt.Unix() + } + for _, f := range d.Files { + fp := 0.0 + if f.Size > 0 { + fp = float64(f.BytesDone) / float64(f.Size) + } + dto.Files = append(dto.Files, FileDTO{ + Index: f.Index, Path: f.Path, Size: f.Size, BytesDone: f.BytesDone, Progress: fp, + Priority: priorityToString(f.Priority), + }) + } + for _, p := range d.Peers { + dto.PeersList = append(dto.PeersList, PeerDTO{ + IP: p.IP, Port: p.Port, Client: p.ClientName, Flags: p.Flags, + Progress: p.Progress, DownloadRate: p.DownloadRate, UploadRate: p.UploadRate, Country: p.CountryCode, + }) + } + for _, t := range d.Trackers { + dto.Trackers = append(dto.Trackers, TrackerDTO{ + URL: t.URL, Status: t.Status, Seeds: t.Seeds, Peers: t.Peers, Downloaded: t.Downloaded, + LastAnnounce: t.LastAnnounce.Unix(), NextAnnounce: t.NextAnnounce.Unix(), + }) + } + return dto +} + +func ratioOf(down, up int64) float64 { + if down == 0 { + return 0 + } + return float64(up) / float64(down) +} + +func priorityToString(p engine.Priority) string { + switch p { + case engine.PrioritySkip: + return "skip" + case engine.PriorityHigh: + return "high" + case engine.PriorityMax: + return "max" + } + return "normal" +} + +// ─── Categories / Tags ─────────────────────────────────────────────────────── + +type CategoryDTO struct { + ID int `json:"id"` + Name string `json:"name"` + DefaultSavePath string `json:"default_save_path"` + Color string `json:"color"` +} + +type TagDTO struct { + ID int `json:"id"` + Name string `json:"name"` + Color string `json:"color"` +} + +func (s *Service) CreateCategory(ctx context.Context, name, defaultPath, color string) (int, error) { + if !CallerFrom(ctx).CanManageCatTags() { + return 0, ErrForbidden + } + return s.categories.Create(ctx, persistence.Category{Name: name, DefaultSavePath: defaultPath, Color: color}) +} + +func (s *Service) ListCategories(ctx context.Context) ([]CategoryDTO, error) { + cats, err := s.categories.List(ctx) + if err != nil { + return nil, err + } + out := make([]CategoryDTO, 0, len(cats)) + for _, c := range cats { + out = append(out, CategoryDTO{ID: c.ID, Name: c.Name, DefaultSavePath: c.DefaultSavePath, Color: c.Color}) + } + return out, nil +} + +func (s *Service) UpdateCategory(ctx context.Context, id int, name, defaultPath, color string) error { + if !CallerFrom(ctx).CanManageCatTags() { + return ErrForbidden + } + return s.categories.Update(ctx, persistence.Category{ID: id, Name: name, DefaultSavePath: defaultPath, Color: color}) +} + +func (s *Service) DeleteCategory(ctx context.Context, id int) error { + if !CallerFrom(ctx).CanManageCatTags() { + return ErrForbidden + } + return s.categories.Delete(ctx, id) +} + +func (s *Service) CreateTag(ctx context.Context, name, color string) (int, error) { + if !CallerFrom(ctx).CanManageCatTags() { + return 0, ErrForbidden + } + return s.tags.Create(ctx, persistence.Tag{Name: name, Color: color}) +} + +func (s *Service) ListTags(ctx context.Context) ([]TagDTO, error) { + tags, err := s.tags.List(ctx) + if err != nil { + return nil, err + } + out := make([]TagDTO, 0, len(tags)) + for _, t := range tags { + out = append(out, TagDTO{ID: t.ID, Name: t.Name, Color: t.Color}) + } + return out, nil +} + +func (s *Service) DeleteTag(ctx context.Context, id int) error { + if !CallerFrom(ctx).CanManageCatTags() { + return ErrForbidden + } + return s.tags.Delete(ctx, id) +} + +// AssignTag/UnassignTag attach an existing tag to a torrent — that is per- +// torrent organisation, so editor access on the torrent is sufficient (you +// don't need the global manage-cat-tags permission, which gates the tag set +// itself). +func (s *Service) AssignTag(ctx context.Context, infohash string, tagID int) error { + if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { + return err + } + return s.tags.Assign(ctx, infohash, tagID) +} + +func (s *Service) UnassignTag(ctx context.Context, infohash string, tagID int) error { + if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { + return err + } + return s.tags.Unassign(ctx, infohash, tagID) +} + +func (s *Service) ListTagsFor(ctx context.Context, infohash string) ([]TagDTO, error) { + tags, err := s.tags.ForTorrent(ctx, infohash) + if err != nil { + return nil, err + } + out := make([]TagDTO, 0, len(tags)) + for _, t := range tags { + out = append(out, TagDTO{ID: t.ID, Name: t.Name, Color: t.Color}) + } + return out, nil +} + +func (s *Service) SetTorrentCategory(ctx context.Context, infohash string, categoryID *int) error { + if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { + return err + } + return s.torrents.SetCategory(ctx, infohash, categoryID) +} + +// ─── Per-torrent rate limits ─────────────────────────────────────────────── + +// TorrentRateLimitsDTO is the per-torrent bandwidth cap transport shape. +// Down/Up are in KB/s; 0 means unlimited. +type TorrentRateLimitsDTO struct { + DownKbps int64 `json:"down_kbps"` + UpKbps int64 `json:"up_kbps"` +} + +// GetTorrentRateLimits returns the persisted per-torrent rate limits in KB/s. +func (s *Service) GetTorrentRateLimits(ctx context.Context, infohash string) (TorrentRateLimitsDTO, error) { + if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessViewer); err != nil { + return TorrentRateLimitsDTO{}, err + } + rec, err := s.torrents.Get(ctx, infohash) + if err != nil { + return TorrentRateLimitsDTO{}, err + } + return TorrentRateLimitsDTO{ + DownKbps: rec.DownRateLimit / 1024, + UpKbps: rec.UpRateLimit / 1024, + }, nil +} + +// SetTorrentRateLimits sets per-torrent download/upload caps. downKbps and +// upKbps are in KB/s; 0 means unlimited. Changes are persisted and applied +// to the live engine immediately. +func (s *Service) SetTorrentRateLimits(ctx context.Context, infohash string, downKbps, upKbps int64) error { + if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { + return err + } + if downKbps < 0 || upKbps < 0 { + return fmt.Errorf("rate limits must be >= 0") + } + downBPS := downKbps * 1024 + upBPS := upKbps * 1024 + if err := s.torrents.SetRateLimits(ctx, infohash, downBPS, upBPS); err != nil { + return fmt.Errorf("persist rate limits: %w", err) + } + return s.engine.SetTorrentRateLimits(engine.TorrentID(infohash), downBPS, upBPS) +} + +// ─── Trackers ─────────────────────────────────────────────────────────────── + +// validateTrackerURL returns an error if the URL is not a valid http, https, or +// udp tracker URL. Trackers over ws/wss are also accepted (WebSocket trackers). +func validateTrackerURL(raw string) error { + u, err := url.Parse(raw) + if err != nil { + return fmt.Errorf("invalid URL: %w", err) + } + switch u.Scheme { + case "http", "https", "udp", "ws", "wss": + // accepted + default: + return fmt.Errorf("tracker URL must use http, https, udp, ws, or wss scheme (got %q)", u.Scheme) + } + if u.Host == "" { + return fmt.Errorf("tracker URL has no host") + } + return nil +} + +// AddTracker adds a user-supplied tracker URL to a torrent and persists it so +// it survives restarts. Requires editor access on the torrent. +func (s *Service) AddTracker(ctx context.Context, infohash, trackerURL string) error { + if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { + return err + } + if err := validateTrackerURL(trackerURL); err != nil { + return err + } + if err := s.engine.AddTracker(engine.TorrentID(infohash), trackerURL); err != nil { + return fmt.Errorf("add tracker to engine: %w", err) + } + if s.trackers != nil { + if err := s.trackers.Add(ctx, infohash, trackerURL); err != nil { + return fmt.Errorf("persist tracker: %w", err) + } + } + return nil +} + +// RemoveTracker removes a user-supplied tracker URL from a torrent and deletes +// its persisted record. Requires editor access on the torrent. +func (s *Service) RemoveTracker(ctx context.Context, infohash, trackerURL string) error { + if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { + return err + } + if err := s.engine.RemoveTracker(engine.TorrentID(infohash), trackerURL); err != nil { + return fmt.Errorf("remove tracker from engine: %w", err) + } + if s.trackers != nil { + if err := s.trackers.Remove(ctx, infohash, trackerURL); err != nil { + return fmt.Errorf("remove persisted tracker: %w", err) + } + } + return nil +} + +func (s *Service) SetFilePriorities(ctx context.Context, infohash string, prios map[int]string) error { + if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { + return err + } + mapped := make(map[int]engine.Priority, len(prios)) + for idx, p := range prios { + switch p { + case "skip": + mapped[idx] = engine.PrioritySkip + case "high": + mapped[idx] = engine.PriorityHigh + case "max": + mapped[idx] = engine.PriorityMax + default: + mapped[idx] = engine.PriorityNormal + } + } + return s.engine.SetFilePriorities(engine.TorrentID(infohash), mapped) +} + +// ─── Queue ─────────────────────────────────────────────────────────────────── + +func (s *Service) SetQueuePosition(ctx context.Context, infohash string, pos int) error { + if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { + return err + } + if err := s.torrents.SetQueuePosition(ctx, infohash, pos); err != nil { + return err + } + s.engine.SetQueuePosition(engine.TorrentID(infohash), pos) + return nil +} + +func (s *Service) SetForceStart(ctx context.Context, infohash string, force bool) error { + if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { + return err + } + if err := s.torrents.SetForceStart(ctx, infohash, force); err != nil { + return err + } + s.engine.SetForceStart(engine.TorrentID(infohash), force) + return nil +} + +// SetSequential enables or disables sequential piece download for a torrent. +// When enabled, pieces are requested in order from first to last, allowing +// media to be previewed or streamed before the download completes. When +// disabled, the default rarest-first strategy is restored. +func (s *Service) SetSequential(ctx context.Context, infohash string, enabled bool) error { + if err := s.requireTorrentAccess(ctx, infohash, persistence.AccessEditor); err != nil { + return err + } + if err := s.torrents.SetSequential(ctx, infohash, enabled); err != nil { + return err + } + s.engine.SetSequential(engine.TorrentID(infohash), enabled) + return nil +} + +// ─── Restore on startup ───────────────────────────────────────────────────── + +// RestoreOnStartup hydrates engine + scheduler limits from persisted settings +// AND re-adds every persisted torrent to the engine so prior-session downloads +// resume on next launch. Call this once after constructing the Service. +// +// Installs SystemCaller on the context so callers don't have to — this is the +// trusted startup hydration path, not a user-driven action. +func (s *Service) RestoreOnStartup(ctx context.Context) error { + ctx = WithCaller(ctx, SystemCaller) + if err := s.recoverInvalidAdminPasswordHash(ctx); err != nil { + log.Warn().Err(err).Msg("restore: recover invalid admin password hash failed") + } + q := s.GetQueueLimits(ctx) + if s.scheduler != nil { + s.scheduler.SetLimits(q.MaxActiveDownloads, q.MaxActiveSeeds) + } + if err := s.applyLimits(ctx); err != nil { + return err + } + + records, err := s.torrents.List(ctx) + if err != nil { + return fmt.Errorf("list persisted torrents: %w", err) + } + failed := 0 + orphaned := 0 + for _, r := range records { + var id engine.TorrentID + var addErr error + switch { + case len(r.Metainfo) > 0: + id, addErr = s.engine.AddFile(ctx, r.Metainfo, r.SavePath) + case r.Magnet != "": + id, addErr = s.engine.AddMagnet(ctx, r.Magnet, r.SavePath) + default: + log.Warn().Str("infohash", r.InfoHash).Str("name", r.Name).Msg("restore: skipping orphan record (no magnet, no metainfo)") + orphaned++ + continue + } + if addErr != nil { + log.Warn().Err(addErr).Str("infohash", r.InfoHash).Str("name", r.Name).Msg("restore: re-add failed") + failed++ + continue + } + if r.CompletedAt != nil { + s.engine.MarkExpectedComplete(id) + } + s.engine.SetQueuePosition(id, r.QueuePosition) + s.engine.SetForceStart(id, r.ForceStart) + if r.Sequential { + s.engine.SetSequential(id, true) + } + if r.Paused { + if err := s.engine.Pause(id); err != nil { + log.Warn().Err(err).Str("infohash", r.InfoHash).Msg("restore: re-pause failed") + } + } + if r.DownRateLimit != 0 || r.UpRateLimit != 0 { + if err := s.engine.SetTorrentRateLimits(id, r.DownRateLimit, r.UpRateLimit); err != nil { + log.Warn().Err(err).Str("infohash", r.InfoHash).Msg("restore: re-apply rate limits failed") + } + } + if s.trackers != nil { + urls, err := s.trackers.List(ctx, r.InfoHash) + if err != nil { + log.Warn().Err(err).Str("infohash", r.InfoHash).Msg("restore: list user trackers failed") + } else { + for _, u := range urls { + if err := s.engine.AddTracker(id, u); err != nil { + log.Warn().Err(err).Str("infohash", r.InfoHash).Str("url", u).Msg("restore: re-add tracker failed") + } + } + } + } + } + if failed > 0 || orphaned > 0 { + log.Warn().Int("failed", failed).Int("orphaned", orphaned).Int("total", len(records)).Msg("restore: not all torrents could be re-added") + } + return nil +} \ No newline at end of file diff --git a/backend/api/service_updater.go b/backend/api/service_updater.go new file mode 100644 index 0000000..ec78df6 --- /dev/null +++ b/backend/api/service_updater.go @@ -0,0 +1,211 @@ +package api + +import ( + "context" + "fmt" + + "mosaic/backend/updater" +) + +// UpdaterConfigDTO is the persisted updater preferences shape (channel + +// enabled toggle + cached last-check metadata for UI display). +type UpdaterConfigDTO struct { + Enabled bool `json:"enabled"` + Channel string `json:"channel"` // "stable" | "beta" + LastCheckedAt int64 `json:"last_checked_at"` // unix seconds + LastSeenVersion string `json:"last_seen_version"` + // InstallSource classifies how this binary was installed: "apt" + // (managed by apt — auto-updater is dormant), "appimage", or + // "manual". The SPA renders Updates pane copy off this field. + InstallSource string `json:"install_source"` +} + +// UpdateInfoDTO mirrors updater.Info plus CurrentVersion so the UI can render +// "X → Y" without needing a separate AppVersion call. +type UpdateInfoDTO struct { + Available bool `json:"available"` + LatestVersion string `json:"latest_version"` + AssetURL string `json:"asset_url"` + AssetFilename string `json:"asset_filename"` + CheckedAt int64 `json:"checked_at"` // unix seconds + CurrentVersion string `json:"current_version"` +} + +// AttachUpdater wires the live *updater.Updater + build-time version into the +// Service after construction. main.go calls this once at startup; tests can +// leave it unset to exercise the disabled-updater path. +// +// installSource is the freshly-detected classification of how the running +// binary was installed (apt / appimage / manual). The SPA reads it via +// UpdaterConfigDTO so the Updates pane can render an "apt-managed — use +// `apt upgrade` to update" banner instead of a misleading toggle. +func (s *Service) AttachUpdater(u *updater.Updater, version string, installSource updater.InstallSource) { + s.updater = u + s.appVersion = version + s.installSource = installSource +} + +// AppVersion returns the build-time version string the Service was set with. +// Empty string if neither SetAppVersion nor AttachUpdater has been called. +func (s *Service) AppVersion() string { + return s.appVersion +} + +// SetAppVersion records the build-time version on the Service so AppVersion() +// (and the /api/version endpoint behind it) can return it even when the +// updater isn't wired — notably in the daemon, where auto-update is +// intentionally not attached. AttachUpdater also writes this field, so calling +// SetAppVersion before AttachUpdater is safe and the values will match. +func (s *Service) SetAppVersion(version string) { + s.appVersion = version +} + +// UpdaterEnabled reports whether the auto-update goroutine should run. The +// setting defaults to true (if absent in the settings table). Stored as +// "true" / "false" strings via setBoolSetting. +func (s *Service) UpdaterEnabled(ctx context.Context) bool { + v, err := s.settings.Get(ctx, settingUpdaterEnabled) + if err != nil || v == "" { + return true + } + return v == "true" +} + +// UpdaterChannel returns the configured update channel ("stable" by default). +func (s *Service) UpdaterChannel(ctx context.Context) string { + ch, _ := s.settings.Get(ctx, settingUpdaterChannel) + if ch == "" { + return "stable" + } + return ch +} + +func (s *Service) GetUpdaterConfig(ctx context.Context) UpdaterConfigDTO { + if !CallerFrom(ctx).CanChangeSettings() { + return UpdaterConfigDTO{} + } + seen, _ := s.settings.Get(ctx, settingUpdaterLastSeenVersion) + src := string(s.installSource) + if src == "" { + src = string(updater.InstallSourceManual) + } + return UpdaterConfigDTO{ + Enabled: s.UpdaterEnabled(ctx), + Channel: s.UpdaterChannel(ctx), + LastCheckedAt: int64(s.intSetting(ctx, settingUpdaterLastChecked)), + LastSeenVersion: seen, + InstallSource: src, + } +} + +func (s *Service) SetUpdaterConfig(ctx context.Context, c UpdaterConfigDTO) error { + // Admin-only, not merely CanChangeSettings: the updater downloads and + // swaps the running server binary, so steering its channel/enablement is a + // host-integrity operation, not an ordinary preference. PermChangeSettings + // is a delegable, sub-admin flag and must not reach this far. + if !CallerFrom(ctx).IsAdmin() { + return ErrForbidden + } + if c.Channel != "stable" && c.Channel != "beta" { + return fmt.Errorf("channel must be stable or beta") + } + if err := s.setBoolSetting(ctx, settingUpdaterEnabled, c.Enabled); err != nil { + return err + } + if err := s.settings.Set(ctx, settingUpdaterChannel, c.Channel); err != nil { + return err + } + s.fireUpdaterConfigChanged(s.GetUpdaterConfig(ctx)) + return nil +} + +// OnUpdaterConfigChange registers a synchronous callback invoked after a +// SetUpdaterConfig commit, mirroring OnWebConfigChange / +// OnDesktopIntegrationChange. main.go uses it to push channel changes into +// the live GitHubSource and to start/stop the periodic check goroutine — +// without it, both silently required an app restart. Pass nil to unregister. +// Only one callback is supported. The daemon never registers one (auto-update +// is intentionally not wired there); firing is nil-safe. +func (s *Service) OnUpdaterConfigChange(cb func(UpdaterConfigDTO)) { + s.updaterHookMu.Lock() + s.onUpdaterChanged = cb + s.updaterHookMu.Unlock() +} + +func (s *Service) fireUpdaterConfigChanged(c UpdaterConfigDTO) { + s.updaterHookMu.RLock() + cb := s.onUpdaterChanged + s.updaterHookMu.RUnlock() + if cb != nil { + cb(c) + } +} + +func (s *Service) CheckForUpdate(ctx context.Context) (UpdateInfoDTO, error) { + // Same admin-only gate as InstallUpdate / SetUpdaterConfig: the check + // performs an outbound HTTP request and writes two settings rows, and it is + // the precursor to an install, so it belongs to the same host-integrity + // boundary rather than the delegable PermChangeSettings flag. + if !CallerFrom(ctx).IsAdmin() { + return UpdateInfoDTO{}, ErrForbidden + } + if s.updater == nil { + return UpdateInfoDTO{CurrentVersion: s.appVersion}, fmt.Errorf("updater disabled") + } + info, err := s.updater.Check(ctx) + if err != nil { + return UpdateInfoDTO{CurrentVersion: s.appVersion}, err + } + _ = s.setIntSetting(ctx, settingUpdaterLastChecked, int(info.CheckedAt.Unix())) + if info.Available { + _ = s.settings.Set(ctx, settingUpdaterLastSeenVersion, info.LatestVersion) + } + return UpdateInfoDTO{ + Available: info.Available, + LatestVersion: info.LatestVersion, + AssetURL: info.AssetURL, + AssetFilename: info.AssetFilename, + CheckedAt: info.CheckedAt.Unix(), + CurrentVersion: s.appVersion, + }, nil +} + +func (s *Service) InstallUpdate(ctx context.Context) error { + // Admin-only: this replaces the running server binary. A non-admin holding + // the delegable PermChangeSettings flag must not be able to swap the host's + // executable. + if !CallerFrom(ctx).IsAdmin() { + return ErrForbidden + } + if s.updater == nil { + return fmt.Errorf("updater disabled") + } + if s.installSource == updater.InstallSourceAPT { + return fmt.Errorf("this Mosaic is managed by apt — run `sudo apt update && sudo apt upgrade mosaic` to update") + } + last := s.updater.Last() + if err := s.updater.Install(ctx, last); err != nil { + return err + } + // Fire the desktop notification (if a Notifier was attached and the user + // hasn't disabled the notify_on_update toggle — the Notifier itself does + // the toggle gating). Done here rather than from a hook in the updater + // package because updater.Updater doesn't expose an OnInstalled callback. + if s.updateInstalledNotifier != nil { + s.updateInstalledNotifier.NotifyUpdateInstalled(last.LatestVersion) + } + return nil +} + +// MakeUpdateInfoDTO converts a raw updater.Info to the API DTO. Used by main.go +// to wrap OnAvailable callback payloads for the WS/Wails event emission. +func (s *Service) MakeUpdateInfoDTO(info updater.Info) UpdateInfoDTO { + return UpdateInfoDTO{ + Available: info.Available, + LatestVersion: info.LatestVersion, + AssetURL: info.AssetURL, + AssetFilename: info.AssetFilename, + CheckedAt: info.CheckedAt.Unix(), + CurrentVersion: s.appVersion, + } +} \ No newline at end of file diff --git a/backend/engine/anacrolix.go b/backend/engine/anacrolix.go index 4813482..299dc75 100644 --- a/backend/engine/anacrolix.go +++ b/backend/engine/anacrolix.go @@ -1,18 +1,15 @@ package engine import ( - "bytes" "context" "errors" "fmt" "io" "log" - "math" "net" "net/http" "os" goruntime "runtime" - "strconv" "strings" "sync" "sync/atomic" @@ -22,9 +19,7 @@ import ( g "github.com/anacrolix/generics" "github.com/anacrolix/torrent" "github.com/anacrolix/torrent/iplist" - "github.com/anacrolix/torrent/metainfo" "github.com/anacrolix/torrent/storage" - anacrolix_types "github.com/anacrolix/torrent/types" "golang.org/x/time/rate" ) @@ -678,802 +673,6 @@ func idFor(t *torrent.Torrent) TorrentID { return TorrentID(t.InfoHash().HexString()) } -func (a *AnacrolixBackend) AddMagnet(ctx context.Context, magnet, savePath string) (TorrentID, error) { - // SECURITY: savePath is caller-controlled. In multi-user mosaicd a - // non-admin must NOT be able to MkdirAll into arbitrary daemon-writable - // paths (/etc/cron.d, ~root/.ssh, another user's home). Callers in - // api/service.go must funnel non-admin save paths through - // engine.ValidateSavePath(userRoot, savePath, /*restrictToRoot=*/ true) - // BEFORE invoking AddMagnet. Admin and single-user-desktop callers - // pass restrictToRoot=false to keep the current unrestricted behavior. - // This function intentionally does not re-validate because the engine - // doesn't know the caller's role/userID — that context lives in api/. - if err := os.MkdirAll(savePath, 0o755); err != nil { - return "", err - } - spec, err := torrent.TorrentSpecFromMagnetUri(magnet) - if err != nil { - return "", err - } - spec.Storage = newFileStorage(savePath, a.pieceCompletion, a.preallocateFullFiles) - t, _, err := a.client.AddTorrentSpec(spec) - if err != nil { - return "", err - } - id := idFor(t) - a.mu.Lock() - a.bySaveTo[id] = savePath - a.byID[id] = t - a.mu.Unlock() - a.installWriteErrorHook(id, t) - a.spawnVerify(ctx, id, t) - return id, nil -} - -// spawnVerify runs verifyAndStart on a tracked goroutine so Close() can -// wait for it to finish before tearing down the client + bolt. The -// caller's ctx still governs the pre-GotInfo wait (so a Wails shutdown -// or a slow magnet add can be cancelled during DHT lookup); past -// GotInfo verifyAndStart switches to engineCtx, which Close() cancels. -func (a *AnacrolixBackend) spawnVerify(ctx context.Context, id TorrentID, t *torrent.Torrent) { - a.verifyWg.Add(1) - go func() { - defer a.verifyWg.Done() - a.verifyAndStart(ctx, id, t) - }() -} - -// verifyAndStart hashes existing files (so resume picks up partials), then -// either kicks DownloadAll OR — if Service marked this torrent as previously -// complete and verify finds <100% — flags FilesMissing and pauses so the -// app doesn't silently redownload bytes the user just deleted. -// -// The caller's ctx is honored ONLY for the pre-GotInfo wait (so a Wails -// shutdown / HTTP-handler return / RSS-poll-cycle end cancels DHT lookup -// promptly). Past GotInfo we switch to context.Background() — verify and -// priority-lift must complete regardless of who originated the Add, or -// the torrent silently never downloads. Pre-fix: every Add path threaded -// the caller's request-scoped ctx all the way through; HTTP handlers, -// RSS PollNow, and any second-instance IPC dispatch returned before -// verify finished, the cancelled-ctx check before setAllFilesPriority -// bailed, file priorities stayed at PiecePriorityNone, and peers -// connected but no pieces were ever requested. The Wails GUI happened -// to dodge it because app.go threads the long-lived a.ctx. -// Anacrolix's own goroutines are cancelled on Client.Close (which -// Engine.Close calls), so Background ctx is shutdown-safe. -func (a *AnacrolixBackend) verifyAndStart(ctx context.Context, id TorrentID, t *torrent.Torrent) { - // Wait for metainfo. AddFile already has it (channel is pre-closed); - // AddMagnet has to fetch it via DHT/PEX before we can hash anything. - // Listen on engineCtx too: anacrolix's gotMetainfoC is closed by - // onSetInfo (when metainfo IS received), NOT by t.Drop / Client.Close, - // so a magnet that never resolves would wedge the goroutine forever - // and the engine's verifyWg.Wait at shutdown couldn't return until - // the 5s drain timeout (or, on macOS at least, longer — Wails's - // shutdown order kept the X-button click feeling like the app was - // frozen). engineCtx.Done firing on Close drops these goroutines - // promptly so verifyWg drains in milliseconds. - select { - case <-t.GotInfo(): - case <-ctx.Done(): - return - case <-a.engineCtx.Done(): - return - } - // Past GotInfo — switch from the caller's ctx (which an HTTP handler - // or RSS poller will cancel as soon as the call returns) to the - // engine's lifetime ctx (which Close() cancels). Verify must outlive - // any specific request, but it MUST NOT outlive the engine — Close - // closes the bolt + anacrolix client, and an in-flight verify dispatch - // would crash or hang otherwise. - ctx = a.engineCtx - - a.setVerifying(id, true) - defer a.setVerifying(id, false) - - // Disk-space precheck. Once metadata is in we know how many bytes - // the torrent will need; if the save path's filesystem can't fit - // what's missing (BytesMissing already discounts what's on disk), - // fail fast with a clear error rather than letting anacrolix start - // requesting and surfacing ENOSPC chunk-write errors mid-flight. - // 64 MB headroom for filesystem overhead and a margin against - // concurrent writers; we'd rather error a borderline torrent than - // silently disable it after consuming the last few hundred MB. - if info := t.Info(); info != nil { - if needed := t.BytesMissing(); needed > 0 { - if free := diskFreeBytes(a.saveDirFor(id)); free >= 0 && free < needed+(64<<20) { - t.DisallowDataDownload() - a.raiseError(id, fmt.Errorf("insufficient disk space: %d bytes free, need %d (+64 MB headroom) for %q", - free, needed, info.Name)) - return - } - } - } - - // Fast-resume: if we have a snapshot from a prior session and the - // on-disk file state still matches, replay the saved per-piece - // bitmap into bolt to undo anacrolix's setCompletionFromPartFiles - // wipe (which fired during AddTorrentSpec for any partial torrent), - // then skip the full re-hash. For complete torrents the bitmap - // matches what bolt already has and the replay is a no-op; for - // partials it's the difference between a stat-per-file fast resume - // and reading every byte of a 13 GB preallocated .part to find the - // 200 MB we actually have. - // - // If file digest doesn't match (user deleted/edited bytes - // off-Mosaic between sessions), we fall through to verifyDataParallel - // — the bitmap would be lying about what's on disk. Same fall-through - // applies if no snapshot was ever saved (legacy or first-Add). - if a.snapshotStore != nil { - if snap, wasComplete, bitmap, ok := a.snapshotStore.LoadPieceBitmap(id); ok { - if bitmap == nil { - log.Printf("verify: snapshot exists but no bitmap for %s — falling through to full hash", id) - } else if info := t.Info(); info == nil { - log.Printf("verify: snapshot exists but t.Info() is nil for %s — falling through to full hash", id) - } else { - saveTo := a.saveDirFor(id) - cur, snapErr := computeFileSnapshot(info, saveTo) - if snapErr != nil { - log.Printf("verify: computeFileSnapshot error for %s: %v — falling through to full hash", id, snapErr) - } else if !bytes.Equal(snap, cur) { - log.Printf("verify: file-state mismatch for %s — files changed off-Mosaic; running full hash", id) - } else { - if wasComplete { - // Complete torrent: setCompletionFromPartFiles already set all - // pieces to complete in bolt (files exist at the final path with - // the right size). No need to replay the bitmap — that would just - // be 7000+ redundant bolt View transactions, each confirming what - // bolt already knows. Skipping the replay keeps this path at - // ~5ms (snapshot load + file stat) vs. 200-800ms. - log.Printf("verify: fast-resume %s — skipping hash (complete, no bolt restore needed)", id) - a.snapshotMu.Lock() - a.snapshotSaved[id] = true - a.snapshotMu.Unlock() - } else { - // Partial torrent: setCompletionFromPartFiles marked pieces for - // incomplete files as "not complete" because their .part file is - // not at the final path. Replay the saved bitmap so anacrolix - // sees the actual per-piece state without re-hashing. - restored := a.restoreBoltFromBitmap(t, bitmap) - log.Printf("verify: fast-resume %s — skipping hash (partial, restored=%d pieces)", id, restored) - } - if ctx.Err() == nil { - a.applyPostVerifyPriorities(id, t) - } - return - } - } - } else { - log.Printf("verify: no snapshot for %s — first-add or recheck; running full hash", id) - } - } - - verifyDataParallel(ctx, t) - - a.verifyMu.RLock() - wasComplete := a.expectedComplete[id] - a.verifyMu.RUnlock() - - // BytesMissing is the canonical "is anything still needed" check. - if wasComplete && t.BytesMissing() > 0 { - a.verifyMu.Lock() - a.filesMissing[id] = true - a.verifyMu.Unlock() - // Pause the torrent so it doesn't silently redownload. User can hit - // Resume to either replace missing files or remove the entry. - a.pausedMu.Lock() - a.paused[id] = true - a.pausedMu.Unlock() - t.SetMaxEstablishedConns(0) - return - } - - // Now that the torrent is fully present, persist the snapshot so the - // next startup can take the fast-resume path. - a.saveSnapshotIfComplete(id, t) - - a.applyPostVerifyPriorities(id, t) -} - -// applyPostVerifyPriorities restores piece priorities once verify finishes. -// SetSequential may have run while the verify was in flight; blindly resetting -// every file to Normal here would silently revert the sequential gradient, so -// re-apply it instead when the flag is set. -func (a *AnacrolixBackend) applyPostVerifyPriorities(id TorrentID, t *torrent.Torrent) { - a.pausedMu.RLock() - sequential := a.sequential[id] - a.pausedMu.RUnlock() - if sequential { - applySequentialPriorities(t, true) - return - } - setAllFilesPriority(t, anacrolix_types.PiecePriorityNormal) -} - -// setAllFilesPriority is the file-aware replacement for t.DownloadAll(). -// DownloadAll raises piece priorities directly via DownloadPieces() but -// never touches File.prio, which means File.Priority() keeps returning -// PiecePriorityNone (which we surface as "Skip" in the Files pane). The -// piece-level effect is the same — anacrolix's purePriority() takes the -// max across each piece's overlapping files plus the per-piece raise — -// but iterating and SetPriority'ing each file lifts BOTH file.prio AND -// the underlying pieces, so the UI displays the correct file priority -// instead of misleading the user into thinking the files are skipped. -// -// Safe before t.GotInfo only if t.Files() returns the populated list; in -// practice all callers are past GotInfo by the time they hit this. -func setAllFilesPriority(t *torrent.Torrent, prio anacrolix_types.PiecePriority) { - for _, f := range t.Files() { - f.SetPriority(prio) - } -} - -// saveSnapshotIfComplete is the per-tick dedup'd path for completed -// torrents — once a torrent finishes downloading and the engine ticker -// observes the transition, this fires once and snapshotSaved quiesces -// it. Bitmap is recorded too so a fully-complete torrent's restart -// avoids touching disk at all. -func (a *AnacrolixBackend) saveSnapshotIfComplete(id TorrentID, t *torrent.Torrent) { - a.snapshotMu.Lock() - saved := a.snapshotSaved[id] - a.snapshotMu.Unlock() - if saved { - return - } - if t.BytesMissing() != 0 { - return - } - if !a.writeSnapshot(id, t, true) { - return - } - a.snapshotMu.Lock() - a.snapshotSaved[id] = true - a.snapshotMu.Unlock() -} - -// saveSnapshotForCheckpoint records the file digest + per-piece bitmap -// at a quiesced point in the torrent's lifetime — typically pause or -// engine shutdown. Unlike saveSnapshotIfComplete it works for partial -// torrents too: the bitmap captures exactly which pieces bolt thinks -// are complete RIGHT NOW, and the next add can replay it after -// anacrolix's storage init wipes bolt for partials. Skips while verify -// is mid-flight (capturing a half-verified state would replay -// nonsense). wasComplete is recorded honestly. -func (a *AnacrolixBackend) saveSnapshotForCheckpoint(id TorrentID, t *torrent.Torrent) { - a.verifyMu.RLock() - verifying := a.verifying[id] - a.verifyMu.RUnlock() - if verifying { - return - } - complete := t.BytesMissing() == 0 - if !a.writeSnapshot(id, t, complete) { - return - } - if complete { - a.snapshotMu.Lock() - a.snapshotSaved[id] = true - a.snapshotMu.Unlock() - } -} - -// writeSnapshot is the shared implementation: compute the file-state -// digest + per-piece completion bitmap, persist them via the snapshot -// store atomically. The bitmap is what lets the next launch avoid the -// brutal "verify all 13 GB to find the 200 MB we have" rehash — -// anacrolix's setCompletionFromPartFiles wipes bolt's complete entries -// for any partial-with-.part-files torrent, but if the file digest -// matches what we recorded with the bitmap, we know the disk state -// hasn't changed off-Mosaic and can replay the bitmap straight back -// into bolt to restore anacrolix's per-piece view in one cheap loop. -// -// Falls back to plain snapshot save (no bitmap) if reading per-piece -// completion fails — the legacy verify path still covers correctness. -func (a *AnacrolixBackend) writeSnapshot(id TorrentID, t *torrent.Torrent, complete bool) bool { - if a.snapshotStore == nil { - return false - } - info := t.Info() - if info == nil { - return false - } - saveTo := a.saveDirFor(id) - cur, err := computeFileSnapshot(info, saveTo) - if err != nil { - log.Printf("verify: compute snapshot for %s: %v", id, err) - return false - } - bitmap := piecesToBitmap(t) - if err := a.snapshotStore.SavePieceBitmap(id, cur, complete, bitmap); err != nil { - log.Printf("verify: save snapshot/bitmap for %s: %v", id, err) - return false - } - return true -} - -// piecesToBitmap reads anacrolix's per-piece completion view via -// PieceState and packs it into a `(NumPieces+7)/8`-byte bitmap. Bit i -// is set iff piece i is complete. Reading PieceState is cheap (no -// disk I/O — it's a memory read off the cached completion state). -func piecesToBitmap(t *torrent.Torrent) []byte { - n := t.NumPieces() - if n <= 0 { - return nil - } - out := make([]byte, (n+7)/8) - for i := 0; i < n; i++ { - if t.PieceState(i).Complete { - out[i/8] |= 1 << (uint(i) & 7) - } - } - return out -} - -// restoreBoltFromBitmap replays a saved per-piece completion bitmap -// into anacrolix's bolt store. Called after AddTorrentSpec runs (which -// invokes setCompletionFromPartFiles, wiping any "complete" bolt -// entries for partial torrents) but before verifyAndStart kicks off — -// the next time anacrolix consults bolt for piece N, it sees the -// restored truth and storageCompletionOk flips to true so the piece -// becomes eligible for requests immediately, no re-hash needed. -// -// Caller is responsible for verifying the file-state snapshot matches -// before calling this; otherwise we'd be lying to anacrolix about what -// bytes are actually on disk. -func (a *AnacrolixBackend) restoreBoltFromBitmap(t *torrent.Torrent, bitmap []byte) int { - if a.pieceCompletion == nil || len(bitmap) == 0 { - return 0 - } - n := t.NumPieces() - ih := t.InfoHash() - restored := 0 - for i := 0; i < n; i++ { - byteIdx := i / 8 - if byteIdx >= len(bitmap) { - break - } - complete := bitmap[byteIdx]&(1<<(uint(i)&7)) != 0 - if !complete { - // We don't restore "incomplete" — bolt's default state for - // missing entries is already storageCompletionOk=false / - // piece-not-complete. Setting false explicitly would just - // add a row per piece for no benefit. Pieces marked - // complete are the only ones worth replaying. - continue - } - if err := a.pieceCompletion.Set(metainfo.PieceKey{InfoHash: ih, Index: i}, true); err != nil { - log.Printf("verify: restore piece %d for %s: %v", i, idFor(t), err) - continue - } - restored++ - } - return restored -} - -// saveDirFor returns the per-torrent save root captured at AddFile/AddMagnet -// time (same value passed to anacrolix's storage.NewFile). Files for the -// torrent live at filepath.Join(saveDir, info.Name, file.Path...). -func (a *AnacrolixBackend) saveDirFor(id TorrentID) string { - a.mu.Lock() - defer a.mu.Unlock() - return a.bySaveTo[id] -} - -// verifyDataParallel hashes every piece of t, but unlike t.VerifyData() -// (which iterates pieces sequentially and blocks on each one), it dispatches -// up to `workers` outer goroutines so the lib's piece-hasher worker pool -// stays saturated. anacrolix's t.VerifyData has a TODO admitting the -// sequential design; queuing-1-and-waiting-1 means PieceHashersPerTorrent -// > 1 buys us nothing. v0.2.10 used NumCPU/2 capped at 8 here, but the -// client locker contention inside anacrolix means more outer goroutines -// just spin without throughput — so v0.2.11 caps at NumCPU/4 (2..4) to -// match PieceHashersPerTorrent in NewAnacrolixBackend. -func verifyDataParallel(ctx context.Context, t *torrent.Torrent) { - n := t.NumPieces() - if n == 0 { - return - } - workers := goruntime.NumCPU() / 4 - if workers < 2 { - workers = 2 - } - if workers > 4 { - workers = 4 - } - if workers > n { - workers = n - } - sem := make(chan struct{}, workers) - var wg sync.WaitGroup - for i := 0; i < n; i++ { - select { - case <-ctx.Done(): - wg.Wait() - return - case sem <- struct{}{}: - } - wg.Add(1) - go func(idx int) { - defer wg.Done() - defer func() { <-sem }() - _ = t.Piece(idx).VerifyDataContext(ctx) - }(i) - } - wg.Wait() -} - -func (a *AnacrolixBackend) setVerifying(id TorrentID, v bool) { - a.verifyMu.Lock() - if v { - a.verifying[id] = true - } else { - delete(a.verifying, id) - } - a.verifyMu.Unlock() -} - -// MarkExpectedComplete marks this torrent as having been 100% on a prior -// session, so verifyAndStart can flag FilesMissing if VerifyData reveals -// the user deleted files. Service.RestoreOnStartup calls this when the -// persisted record's CompletedAt is non-nil. -func (a *AnacrolixBackend) MarkExpectedComplete(id TorrentID) { - a.verifyMu.Lock() - a.expectedComplete[id] = true - a.verifyMu.Unlock() -} - -func (a *AnacrolixBackend) AddFile(ctx context.Context, blob []byte, savePath string) (TorrentID, error) { - // SECURITY: same caller-controlled-path concern as AddMagnet. See the - // note there. The api/service.go AddTorrentFile / AddTorrentBytes paths - // are expected to ValidateSavePath before calling in. - if err := os.MkdirAll(savePath, 0o755); err != nil { - return "", err - } - mi, err := metainfo.Load(bytes.NewReader(blob)) - if err != nil { - return "", err - } - spec := torrent.TorrentSpecFromMetaInfo(mi) - spec.Storage = newFileStorage(savePath, a.pieceCompletion, a.preallocateFullFiles) - t, _, err := a.client.AddTorrentSpec(spec) - if err != nil { - return "", err - } - id := idFor(t) - a.mu.Lock() - a.bySaveTo[id] = savePath - a.byID[id] = t - a.mu.Unlock() - a.installWriteErrorHook(id, t) - // Same verify-then-start flow as AddMagnet — the GotInfo wait inside - // verifyAndStart is a no-op here since metainfo is already attached. - a.spawnVerify(ctx, id, t) - return id, nil -} - -func (a *AnacrolixBackend) Pause(id TorrentID) error { - t, ok := a.find(id) - if !ok { - return errors.New("not found") - } - // Two-step pause: - // 1. DisallowDataDownload — stops anacrolix from issuing piece - // requests, even if peer conns come back up. This is the - // load-bearing guarantee. - // 2. SetMaxEstablishedConns(0) — drops existing peer conns and - // refuses new ones, so we're not accepting/uploading either. - // - // Pre-fix Pause only did #2, which has a known race against the - // scheduler tick: scheduler reads List() at t=0, user clicks Pause - // at t=10ms (paused flag flips, conns drop), scheduler iterates the - // stale snapshot and calls ScheduledPause(id, false) → - // SetMaxEstablishedConns(80), peers reconnect, anacrolix happily - // resumes piece requests because the priority lift is still in place. - // User sees a paused torrent that's still downloading. Disallow - // closes the gap regardless of conn-cap thrashing. - t.DisallowDataDownload() - t.SetMaxEstablishedConns(0) - a.pausedMu.Lock() - a.paused[id] = true - a.pausedMu.Unlock() - // Checkpoint the file state + per-piece bitmap. The bitmap is what - // makes fast-resume work for partial torrents post-anacrolix's - // per-add storage init wipe — the next add will replay it back into - // bolt after the wipe so anacrolix sees the actual disk state - // without re-hashing every piece. - a.saveSnapshotForCheckpoint(id, t) - return nil -} - -func (a *AnacrolixBackend) Resume(id TorrentID) error { - t, ok := a.find(id) - if !ok { - return errors.New("not found") - } - t.SetMaxEstablishedConns(int(a.maxConnsPerTorrent.Load())) - a.pausedMu.Lock() - a.paused[id] = false - delete(a.scheduledPause, id) - a.pausedMu.Unlock() - // If this resume comes after a FilesMissing flag (user wants to redownload - // after files were deleted), clear the flag — VerifyData will rerun if - // new pieces fail. - a.verifyMu.Lock() - delete(a.filesMissing, id) - a.verifyMu.Unlock() - // Resume is also the recovery path after a disk-full / write-error - // stoppage: AllowDataDownload clears the dataDownloadDisallowed flag - // our write-error hook (and anacrolix's storage-completion error - // path) sets. Idempotent if it was never disallowed. - t.AllowDataDownload() - return nil -} - -// ApplyPerTorrentMaxPeers updates SetMaxEstablishedConns on every running -// torrent. Used when the user changes the "max peers per torrent" setting. -// Already-paused torrents keep their cap of 0 (we set it to 0 to pause); -// the new cap is stored in maxConnsPerTorrent so Resume (and the -// scheduler's re-enable path) restore it instead of a hardcoded default. -func (a *AnacrolixBackend) ApplyPerTorrentMaxPeers(n int) error { - if n <= 0 { - n = 80 // anacrolix default - } - a.maxConnsPerTorrent.Store(int64(n)) - a.pausedMu.RLock() - paused := make(map[TorrentID]bool, len(a.paused)) - for id, v := range a.paused { - paused[id] = v - } - a.pausedMu.RUnlock() - for _, t := range a.client.Torrents() { - id := TorrentID(t.InfoHash().HexString()) - if paused[id] { - continue - } - t.SetMaxEstablishedConns(n) - } - return nil -} - -// Recheck re-hashes every piece against the metainfo. Surfaced via the -// Recheck context-menu item in the SPA. Runs on a goroutine — large torrents -// take a while; while running the Verifying pill shows in the UI. -// -// We invalidate the fast-resume snapshot up front: a Recheck means the user -// wants the verify to actually run, and once it finishes we'll write a new -// snapshot from the just-verified state. -func (a *AnacrolixBackend) Recheck(id TorrentID) error { - t, ok := a.find(id) - if !ok { - return errors.New("not found") - } - if a.snapshotStore != nil { - if err := a.snapshotStore.DeleteVerifySnapshot(id); err != nil { - log.Printf("verify: delete snapshot for %s: %v", id, err) - } - } - // Clear the in-memory dedup so saveSnapshotIfComplete re-runs after the - // recheck finishes (it's the same write the original goroutine did - // inline pre-v0.4.4). The retry-backoff stamp goes too — a user-driven - // recheck should attempt the save immediately. - a.snapshotMu.Lock() - delete(a.snapshotSaved, id) - delete(a.snapshotRetryAt, id) - a.snapshotMu.Unlock() - a.setVerifying(id, true) - a.verifyWg.Add(1) - go func() { - defer a.verifyWg.Done() - defer a.setVerifying(id, false) - verifyDataParallel(a.engineCtx, t) - // Don't snapshot if the engine is shutting down — saveSnapshotIfComplete - // writes to the snapshot store, which Close will tear down right after - // it cancels engineCtx and waits on verifyWg. - if a.engineCtx.Err() != nil { - return - } - a.saveSnapshotIfComplete(id, t) - }() - return nil -} - -func (a *AnacrolixBackend) Remove(id TorrentID, deleteFiles bool) error { - t, ok := a.find(id) - if !ok { - return errors.New("not found") - } - a.mu.Lock() - saveTo := a.bySaveTo[id] - delete(a.bySaveTo, id) - delete(a.byID, id) - a.mu.Unlock() - a.pausedMu.Lock() - delete(a.paused, id) - delete(a.queuePos, id) - delete(a.forceStart, id) - delete(a.sequential, id) - delete(a.scheduledPause, id) - a.pausedMu.Unlock() - a.snapshotMu.Lock() - delete(a.snapshotSaved, id) - delete(a.snapshotRetryAt, id) - a.snapshotMu.Unlock() - a.rateMu.Lock() - delete(a.prevRates, id) - delete(a.prevPeerRates, id) - a.rateMu.Unlock() - // Clear per-torrent limits so the limiter goroutine exits on next tick. - a.perLimitMu.Lock() - delete(a.perTorrentDown, id) - delete(a.perTorrentUp, id) - a.perLimitMu.Unlock() - // t.Drop holds the client lock while it tears the torrent down, and - // inside that the cleanup waits on a per-torrent wait group that - // covers (among other things) tracker stop announces. A - // tracker that's hanging on a TCP connect (HTTP-only trackers like - // the checkmyiptorrent variant the user hit) can hold this for as - // long as the OS connect timeout, blocking the UI's "Remove" call. - // Cap at 5s and let anacrolix finish on its own — our in-memory - // state has already been cleaned, the user has already been told - // "removed." - dropDone := make(chan struct{}) - go func() { - t.Drop() - close(dropDone) - }() - select { - case <-dropDone: - case <-time.After(5 * time.Second): - log.Printf("remove: t.Drop timeout for %s — proceeding without waiting", id) - } - if deleteFiles && saveTo != "" { - if info := t.Info(); info != nil { - // Path-traversal defense: a malicious .torrent's info.Name can be - // "../../something" — joining it raw would let RemoveAll walk above - // saveTo and delete arbitrary files. safeRemovePath validates - // containment (resolving symlinks on both ends when present) and - // returns an error we log+skip on. The in-memory unsubscribe - // (t.Drop, the map deletes above) has already happened — only the - // disk delete is conditional on validation. - // - // Additional defense-in-depth: saveTo itself was caller-controlled - // at Add time. In multi-user mode the api/ layer is expected to - // validate it via engine.ValidateSavePath before AddMagnet/AddFile, - // but we sanity-check here too — a saveTo that's empty, relative, - // contains NUL, or resolves to a filesystem root must not have - // RemoveAll fired on it under any circumstances. - if err := sanityCheckSaveTo(saveTo); err != nil { - log.Printf("refusing to delete files for torrent: saveTo=%q error=%v", saveTo, err) - } else { - path, err := safeRemovePath(saveTo, info.Name) - if err != nil { - log.Printf("refusing to delete files for torrent: name=%q error=%v", info.Name, err) - } else { - _ = os.RemoveAll(path) - } - } - } - } - return nil -} - -func (a *AnacrolixBackend) List() []Snapshot { - ts := a.client.Torrents() - out := make([]Snapshot, 0, len(ts)) - // Collect newly-completed ids inside the locked region; persist their - // fast-resume snapshots in goroutines after the locks are released so - // the file I/O doesn't block the tick. spawnSnapshotSave dedupes against - // snapshotSaved / the in-flight guard, so subsequent ticks observe - // completion as a no-op until Recheck or Remove clears the flag. - var completed []completedFor - // Rates come from the centralized sampler's immutable cache — this loop - // only reads, never mutates prevRates, so concurrent List() calls (one - // per connected user, back-to-back, every tick) all see identical rates. - rates := a.rateCache.Load() - a.pausedMu.RLock() - a.verifyMu.RLock() - for _, t := range ts { - id := TorrentID(t.InfoHash().HexString()) - var rate rateValue - if rates != nil { - rate = (*rates)[id] - } - snap := snapshotFor(t, rate, a.paused[id], a.queuePos[id], a.forceStart[id], a.sequential[id], a.scheduledPause[id], a.verifying[id], a.filesMissing[id]) - out = append(out, snap) - if snap.Completed && a.snapshotStore != nil { - completed = append(completed, completedFor{id: id, t: t}) - } - } - a.verifyMu.RUnlock() - a.pausedMu.RUnlock() - for _, c := range completed { - a.spawnSnapshotSave(c.id, c.t) - } - return out -} - -// snapshotSaveRetryBackoff is how long spawnSnapshotSave waits after a failed -// snapshot write before trying that torrent again. -const snapshotSaveRetryBackoff = 30 * time.Second - -// spawnSnapshotSave runs saveSnapshotIfComplete on a goroutine, at most one -// in flight per torrent. List() used to `go saveSnapshotIfComplete(...)` for -// every completed torrent on every tick; snapshotSaved is only set on a -// successful write, so a persistently failing snapshot store spawned N -// goroutines several times per second forever, each taking the client lock. -// Failures back off for snapshotSaveRetryBackoff before the next attempt. -func (a *AnacrolixBackend) spawnSnapshotSave(id TorrentID, t *torrent.Torrent) { - a.snapshotMu.Lock() - if a.snapshotSaved[id] || a.snapshotInflight[id] || time.Now().Before(a.snapshotRetryAt[id]) { - a.snapshotMu.Unlock() - return - } - a.snapshotInflight[id] = true - a.snapshotMu.Unlock() - go func() { - a.saveSnapshotIfComplete(id, t) - a.snapshotMu.Lock() - delete(a.snapshotInflight, id) - if a.snapshotSaved[id] { - delete(a.snapshotRetryAt, id) - } else { - a.snapshotRetryAt[id] = time.Now().Add(snapshotSaveRetryBackoff) - } - a.snapshotMu.Unlock() - }() -} - -type completedFor struct { - id TorrentID - t *torrent.Torrent -} - -func (a *AnacrolixBackend) Snapshot(id TorrentID) (Snapshot, error) { - t, ok := a.find(id) - if !ok { - return Snapshot{}, errors.New("not found") - } - a.pausedMu.RLock() - paused := a.paused[id] - queuePos := a.queuePos[id] - forceStart := a.forceStart[id] - sequential := a.sequential[id] - queued := a.scheduledPause[id] - a.pausedMu.RUnlock() - a.verifyMu.RLock() - verifying := a.verifying[id] - filesMissing := a.filesMissing[id] - a.verifyMu.RUnlock() - snap := snapshotFor(t, a.rateFor(id), paused, queuePos, forceStart, sequential, queued, verifying, filesMissing) - return snap, nil -} - -func (a *AnacrolixBackend) SetFilePriorities(id TorrentID, prios map[int]Priority) error { - t, ok := a.find(id) - if !ok { - return errors.New("not found") - } - files := t.Files() - for idx, p := range prios { - if idx < 0 || idx >= len(files) { - continue - } - files[idx].SetPriority(prioToAnacrolix(p)) - } - return nil -} - -func prioToAnacrolix(p Priority) anacrolix_types.PiecePriority { - switch p { - case PrioritySkip: - return anacrolix_types.PiecePriorityNone - case PriorityHigh: - return anacrolix_types.PiecePriorityHigh - case PriorityMax: - return anacrolix_types.PiecePriorityNow - } - return anacrolix_types.PiecePriorityNormal -} - func (a *AnacrolixBackend) Close() error { // Cancel engineCtx FIRST so verify goroutines stop dispatching new // piece hashes; then wait for in-flight ones to drain. Without this, @@ -1558,252 +757,6 @@ func (a *AnacrolixBackend) find(id TorrentID) (*torrent.Torrent, bool) { return nil, false } -// DetailedSnapshot pulls files/peers/trackers from the underlying anacrolix -// Torrent based on scope. We translate to our FileEntry/PeerEntry/TrackerEntry -// domain types. -func (a *AnacrolixBackend) DetailedSnapshot(id TorrentID, scope DetailScope) (Detail, error) { - t, ok := a.find(id) - if !ok { - return Detail{}, errors.New("not found") - } - a.pausedMu.RLock() - paused := a.paused[id] - queuePos := a.queuePos[id] - forceStart := a.forceStart[id] - sequential := a.sequential[id] - queued := a.scheduledPause[id] - a.pausedMu.RUnlock() - a.verifyMu.RLock() - verifying := a.verifying[id] - filesMissing := a.filesMissing[id] - a.verifyMu.RUnlock() - snap := snapshotFor(t, a.rateFor(id), paused, queuePos, forceStart, sequential, queued, verifying, filesMissing) - d := Detail{Snapshot: snap} - - if scope.Files { - for i, f := range t.Files() { - d.Files = append(d.Files, FileEntry{ - Index: i, - Path: f.DisplayPath(), - Size: f.Length(), - BytesDone: f.BytesCompleted(), - Priority: prioFromAnacrolix(f.Priority()), - }) - } - } - - if scope.Peers { - // Per-peer windowed download rate: store last-tick cumulative - // BytesReadUsefulData per peer, divide the next tick's delta by - // the elapsed time. Falls back to 0 on the first tick (no prior - // sample) and on completion (we wouldn't be requesting chunks - // anyway). The per-peer map is still guarded by rateMu, shared - // with the rate sampler's prune of prevRates. - complete := t.BytesMissing() == 0 - now := time.Now() - a.rateMu.Lock() - prevPeers := a.prevPeerRates[id] - if prevPeers == nil { - prevPeers = make(map[string]peerRateSample) - } - nextPeers := make(map[string]peerRateSample, len(prevPeers)) - for _, pc := range t.PeerConns() { - addr := pc.RemoteAddr.String() - ip := addr - port := 0 - if h, p, err := splitHostPort(addr); err == nil { - ip = h - port = p - } - name, _ := pc.PeerClientName.Load().(string) - peerKey := addr // ip:port — stable per connection - // Assign Stats() to a local: Count.Int64 is a pointer-receiver - // method, and a field on a non-addressable function return - // value isn't itself addressable. - peerStats := pc.Stats() - cumDown := peerStats.ConnStats.BytesReadUsefulData.Int64() - var dlRate int64 - sample := peerRateSample{at: now, down: cumDown} - if !complete { - if prev, ok := prevPeers[peerKey]; ok { - if dt := now.Sub(prev.at); dt < minPeerRateSampleInterval { - // A second consumer called back-to-back (two web users - // focused on the same torrent each get a per-user - // DetailForFocus tick): dt is microseconds, so a fresh - // delta would read as 0 B/s or spike — the same - // multi-reader hazard the torrent-level sampler fixed - // centrally (see sampleRates). Reuse the previously - // computed rate and keep the old sample so the next - // real tick still has a meaningful dt. - dlRate = prev.rate - sample = prev - } else if secs := dt.Seconds(); secs > 0 { - dlRate = int64(float64(cumDown-prev.down) / secs) - if dlRate < 0 { - dlRate = 0 - } - sample.rate = dlRate - } - } - } - nextPeers[peerKey] = sample - d.Peers = append(d.Peers, PeerEntry{ - IP: ip, - Port: port, - ClientName: name, - Flags: peerFlagsFor(pc), - Progress: pieceProgressOf(t, pc), - DownloadRate: dlRate, - UploadRate: clampRate(peerStats.LastWriteUploadRate), - CountryCode: "", - }) - } - // Drop entries for peers that disconnected since the last tick - // (they're not in `seen`); nextPeers is already filtered to - // currently-present peers by virtue of being built from `conns`. - a.prevPeerRates[id] = nextPeers - a.rateMu.Unlock() - } - - if scope.Trackers { - // anacrolix v1.61 doesn't expose per-tracker announce state; the best - // signal we have is whether metadata has loaded (Info != nil). Before - // metadata, no tracker has produced a useful response yet → "Updating". - // After metadata, fall back to "OK" (best-effort). A future plan or - // upstream PR can refine this with real per-tracker error state. - status := "OK" - if t.Info() == nil { - status = "Updating" - } - mi := t.Metainfo() - for _, tier := range mi.AnnounceList { - for _, url := range tier { - d.Trackers = append(d.Trackers, TrackerEntry{ - URL: url, - Status: status, - }) - } - } - if len(d.Trackers) == 0 && mi.Announce != "" { - d.Trackers = append(d.Trackers, TrackerEntry{URL: mi.Announce, Status: status}) - } - } - - return d, nil -} - -func prioFromAnacrolix(p anacrolix_types.PiecePriority) Priority { - switch p { - case anacrolix_types.PiecePriorityNone: - return PrioritySkip - case anacrolix_types.PiecePriorityNormal: - return PriorityNormal - case anacrolix_types.PiecePriorityHigh: - return PriorityHigh - case anacrolix_types.PiecePriorityNow: - return PriorityMax - } - return PriorityNormal -} - -func splitHostPort(addr string) (string, int, error) { - h, p, err := net.SplitHostPort(addr) - if err != nil { - return "", 0, err - } - port, err := strconv.Atoi(p) - if err != nil { - return h, 0, err - } - return h, port, nil -} - -// bep20PeerID derives the 8-byte BEP-20 peer-id prefix from a -// "Mosaic/X.Y.Z" version string. Format is "-MSnnnn-" where nnnn is the -// 4-digit zero-padded numeric version (X*100 + Y*10 + Z, capped at 4 -// digits). Returns "" if the input doesn't parse as a recognizable -// semver — anacrolix will fall back to its default Bep20 in that case. -// -// Example: "Mosaic/0.5.7" → "-MS0057-". -func bep20PeerID(clientVersion string) string { - // Pull the digits after the slash. - slash := strings.IndexByte(clientVersion, '/') - if slash < 0 || slash == len(clientVersion)-1 { - return "" - } - parts := strings.SplitN(clientVersion[slash+1:], ".", 4) - if len(parts) < 2 { - return "" - } - var nums [3]int - for i := 0; i < 3 && i < len(parts); i++ { - // Strip a leading "v" on the first part if present. - s := parts[i] - if i == 0 { - s = strings.TrimPrefix(s, "v") - } - // Only accept the leading run of digits — allows "0.5.7-rc1" → 0,5,7. - end := 0 - for end < len(s) && s[end] >= '0' && s[end] <= '9' { - end++ - } - if end == 0 { - return "" - } - n, err := strconv.Atoi(s[:end]) - if err != nil { - return "" - } - nums[i] = n - } - combined := nums[0]*100 + nums[1]*10 + nums[2] - if combined > 9999 { - combined = 9999 - } - return fmt.Sprintf("-MS%04d-", combined) -} - -// clampRate sanitizes anacrolix's float64 per-peer rate counters before -// they reach our int64 DTO. NaN ((0 piece-data bytes)/(0 ns) for peers -// we're not actually exchanging data with), +Inf (writeDuration sub- -// nanosecond), and negative values all get pinned to safe ranges. -// -// Pre-fix the int64() cast on NaN produced math.MinInt64 -// (-9223372036854775808) and the SPA rendered "-922337203685477600 B/s" -// for "majority of peers" because that's the resting state of -// LastWriteUploadRate on conns we never piece-uploaded to. -func clampRate(f float64) int64 { - if math.IsNaN(f) || f < 0 { - return 0 - } - if math.IsInf(f, 1) || f > float64(math.MaxInt64) { - return math.MaxInt64 - } - return int64(f) -} - -// peerFlagsFor returns the BitTorrent peer flag string. anacrolix v1.61 keeps -// peerInterested/peerChoking unexported and ships no header-obfuscation -// accessor, so we cannot read the bits — Plan 4 (or an upstream PR) refines. -func peerFlagsFor(pc *torrent.PeerConn) string { - _ = pc - return "" -} - -// pieceProgressOf returns 0..1 of pieces this peer has. *roaring.Bitmap has -// no Len() method; the denominator is the parent torrent's piece count. -func pieceProgressOf(t *torrent.Torrent, pc *torrent.PeerConn) float64 { - pp := pc.PeerPieces() - if pp.IsEmpty() { - return 0 - } - n := t.NumPieces() - if n == 0 { - return 0 - } - return float64(pp.GetCardinality()) / float64(n) -} - // snapshotFor builds a Snapshot for a torrent. The down/up rate is supplied // by the caller from the centralized rate cache (see sampleRates) — this // function no longer computes or stores rate samples, so it is a pure read @@ -1847,367 +800,3 @@ func snapshotFor(t *torrent.Torrent, rate rateValue, paused bool, queuePos int, // SetGlobalRateLimits mutates the existing limiter pointers in place. Passing // 0 means unlimited (rate.Inf, with a 256 KB burst floor for peer messages). -func (a *AnacrolixBackend) SetGlobalRateLimits(downBPS, upBPS int) error { - if downBPS <= 0 { - a.dlLim.SetLimit(rate.Inf) - a.dlLim.SetBurst(256 << 10) - } else { - a.dlLim.SetLimit(rate.Limit(downBPS)) - a.dlLim.SetBurst(max(downBPS, 256<<10)) - } - if upBPS <= 0 { - a.ulLim.SetLimit(rate.Inf) - a.ulLim.SetBurst(256 << 10) - } else { - a.ulLim.SetLimit(rate.Limit(upBPS)) - a.ulLim.SetBurst(max(upBPS, 256<<10)) - } - return nil -} - -// SetTorrentRateLimits sets per-torrent download/upload caps in bytes/sec. -// 0 means unlimited. Enforcement uses a background duty-cycle goroutine -// registered on verifyWg so Close() waits for it to drain. If the torrent -// already has a limiter goroutine running (prior call to SetTorrentRateLimits) -// it will pick up the new limits on its next tick — no new goroutine is -// spawned for subsequent updates. -func (a *AnacrolixBackend) SetTorrentRateLimits(id TorrentID, downBPS, upBPS int64) error { - if downBPS < 0 { - downBPS = 0 - } - if upBPS < 0 { - upBPS = 0 - } - a.perLimitMu.Lock() - a.perTorrentDown[id] = downBPS - a.perTorrentUp[id] = upBPS - // Lifecycle is tracked via limiterRunning, NOT the previous limit values: - // a clear-to-(0,0) followed by a non-zero set within one tick leaves the - // old goroutine alive (it never observes the transient 0,0), so spawning - // another would race it. The goroutine clears the flag under perLimitMu - // with a limits re-check before exiting, so set-after-clear either reuses - // the live limiter or deterministically starts a fresh one. - needsStart := (downBPS != 0 || upBPS != 0) && !a.limiterRunning[id] - if needsStart { - a.limiterRunning[id] = true - } - a.perLimitMu.Unlock() - - if needsStart { - t, ok := a.find(id) - if !ok { - a.perLimitMu.Lock() - delete(a.limiterRunning, id) - a.perLimitMu.Unlock() - return errors.New("not found") - } - a.verifyWg.Add(1) - go a.runPerTorrentLimiter(id, t) - } else if downBPS == 0 && upBPS == 0 { - // Limits cleared — ensure download/upload are allowed - // (the goroutine may have left them disallowed). - t, ok := a.find(id) - if !ok { - return nil - } - t.AllowDataDownload() - t.AllowDataUpload() - } - return nil -} - -// runPerTorrentLimiter is a background goroutine that enforces per-torrent -// rate limits by sampling byte counters every 500ms and using -// DisallowDataDownload/AllowDataDownload (and the Upload equivalents) to -// implement a duty-cycle approximation. -// -// The approach: each 500ms tick we read how many bytes were transferred since -// the last tick. If the torrent exceeded its budget (bytes_this_tick > -// limit_per_500ms), we disallow data for the overrun fraction of the next -// interval. Otherwise we allow data. This is a coarse token-bucket; actual -// throughput will hover around the configured cap ±1 tick's worth (~one -// per-piece chunk, ~16 KB by default in anacrolix) rather than being -// byte-perfect. -// -// The goroutine exits when: (a) engineCtx is cancelled (engine shutdown), or -// (b) both down and up limits drop to 0 (user cleared the limit). -func (a *AnacrolixBackend) runPerTorrentLimiter(id TorrentID, t *torrent.Torrent) { - defer a.verifyWg.Done() - const interval = 500 * time.Millisecond - ticker := time.NewTicker(interval) - defer ticker.Stop() - - var prevDown, prevUp int64 - var dlBlocked, ulBlocked bool - - // Helper: read current cumulative stats from anacrolix. - readStats := func() (down, up int64) { - s := t.Stats() - return s.BytesReadData.Int64(), s.BytesWrittenData.Int64() - } - - prevDown, prevUp = readStats() - - for { - select { - case <-a.engineCtx.Done(): - // Engine shutting down — re-enable before exit so state is clean. - if dlBlocked { - t.AllowDataDownload() - } - if ulBlocked { - t.AllowDataUpload() - } - return - case <-ticker.C: - } - - a.perLimitMu.RLock() - downLimit := a.perTorrentDown[id] - upLimit := a.perTorrentUp[id] - a.perLimitMu.RUnlock() - - // Both limits cleared — re-enable and exit. Confirm under the write - // lock and clear limiterRunning atomically with the re-check: a - // SetTorrentRateLimits that re-set non-zero limits between our - // RLock read and here must either be observed (keep running) or - // happen strictly after the flag is cleared (spawns a fresh - // limiter). Without the re-check this goroutine could exit just as - // the setter saw it as still-running and skipped the spawn, - // leaving the torrent unlimited. - if downLimit == 0 && upLimit == 0 { - a.perLimitMu.Lock() - if a.perTorrentDown[id] != 0 || a.perTorrentUp[id] != 0 { - a.perLimitMu.Unlock() - continue - } - delete(a.limiterRunning, id) - a.perLimitMu.Unlock() - if dlBlocked { - t.AllowDataDownload() - } - if ulBlocked { - t.AllowDataUpload() - } - return - } - - curDown, curUp := readStats() - deltaDown := curDown - prevDown - deltaUp := curUp - prevUp - prevDown, prevUp = curDown, curUp - - // Budget per interval (bytes allowed per 500ms tick). - budgetDown := int64(float64(downLimit) * interval.Seconds()) - budgetUp := int64(float64(upLimit) * interval.Seconds()) - - // Download enforcement. - if downLimit > 0 { - // Check paused state — if paused we don't manage download allow/disallow - // to avoid conflicting with Pause()'s DisallowDataDownload. - a.pausedMu.RLock() - isPaused := a.paused[id] - a.pausedMu.RUnlock() - if !isPaused { - if deltaDown > budgetDown { - // Over budget — disallow for next tick. - if !dlBlocked { - t.DisallowDataDownload() - dlBlocked = true - } - } else { - // Under budget — allow. - if dlBlocked { - t.AllowDataDownload() - dlBlocked = false - } - } - } - } else if dlBlocked { - t.AllowDataDownload() - dlBlocked = false - } - - // Upload enforcement. - if upLimit > 0 { - if deltaUp > budgetUp { - if !ulBlocked { - t.DisallowDataUpload() - ulBlocked = true - } - } else { - if ulBlocked { - t.AllowDataUpload() - ulBlocked = false - } - } - } else if ulBlocked { - t.AllowDataUpload() - ulBlocked = false - } - } -} - -// AddTracker adds a single tracker URL to an existing torrent in its own tier. -// anacrolix's AddTrackers takes a slice of tiers ([][]string); we pass one -// tier containing the single URL so it doesn't compete with metainfo trackers. -func (a *AnacrolixBackend) AddTracker(id TorrentID, url string) error { - t, ok := a.find(id) - if !ok { - return errors.New("not found") - } - t.AddTrackers([][]string{{url}}) - return nil -} - -// RemoveTracker removes a single tracker URL from an existing torrent. -// anacrolix v1.61 exposes ModifyTrackers which replaces the entire announce -// list atomically — it stops existing announcers and rebuilds from the -// provided list. We reconstruct the announce list without the target URL and -// pass it to ModifyTrackers. The call is a no-op if the URL doesn't appear. -func (a *AnacrolixBackend) RemoveTracker(id TorrentID, url string) error { - t, ok := a.find(id) - if !ok { - return errors.New("not found") - } - mi := t.Metainfo() - // Build filtered announce list, excluding the target URL from every tier. - var newList [][]string - for _, tier := range mi.AnnounceList { - var newTier []string - for _, u := range tier { - if u != url { - newTier = append(newTier, u) - } - } - if len(newTier) > 0 { - newList = append(newList, newTier) - } - } - // Also handle the legacy single-announce field by treating it as a tier. - if mi.Announce != "" && mi.Announce != url { - // Only add it if it isn't already covered by AnnounceList to avoid dups. - covered := false - for _, tier := range newList { - for _, u := range tier { - if u == mi.Announce { - covered = true - break - } - } - } - if !covered { - newList = append([][]string{{mi.Announce}}, newList...) - } - } - // ModifyTrackers stops all existing tracker goroutines and replaces the - // announce list atomically. This is the correct removal mechanism in - // anacrolix v1.61. - t.ModifyTrackers(newList) - return nil -} - -func (a *AnacrolixBackend) SetQueuePosition(id TorrentID, pos int) { - a.pausedMu.Lock() - a.queuePos[id] = pos - a.pausedMu.Unlock() -} - -func (a *AnacrolixBackend) SetForceStart(id TorrentID, force bool) { - a.pausedMu.Lock() - a.forceStart[id] = force - a.pausedMu.Unlock() -} - -// SetSequential enables or disables sequential piece download for a torrent. -// When enabled, pieces are assigned descending priorities so that earlier -// pieces have higher urgency — anacrolix then requests them in index order, -// allowing users to preview/stream media while the download is in progress. -// When disabled, piece priorities are reset to Normal (rarest-first default). -// -// The gradient uses all non-None priority levels (Normal..Now, values 1–5). -// Pieces are divided evenly into up to 5 buckets; the first bucket gets the -// highest priority (PiecePriorityNow) and the last gets PiecePriorityNormal. -// This ensures that even with a large number of pieces the request strategy -// strongly prefers lower-indexed pieces for the whole file while still allowing -// anacrolix's internal tie-breaking to handle unavailable / already-complete -// pieces gracefully. -func (a *AnacrolixBackend) SetSequential(id TorrentID, enabled bool) { - a.pausedMu.Lock() - a.sequential[id] = enabled - a.pausedMu.Unlock() - t, ok := a.find(id) - if !ok { - return - } - applySequentialPriorities(t, enabled) -} - -// applySequentialPriorities adjusts per-piece priorities on t to implement -// sequential (in-order) downloading. It must be called after GotInfo (piece -// count is valid). Safe to call from any goroutine — Piece.SetPriority takes -// the client lock internally. -func applySequentialPriorities(t *torrent.Torrent, sequential bool) { - n := t.NumPieces() - if n == 0 { - return - } - if !sequential { - // Reset to Normal so the default rarest-first strategy takes over. - for i := 0; i < n; i++ { - t.Piece(i).SetPriority(anacrolix_types.PiecePriorityNormal) - } - return - } - // Divide pieces into up to 5 buckets mapped to priority levels - // PiecePriorityNow (5) → PiecePriorityNormal (1). - const levels = 5 // PiecePriorityNow=5 down to PiecePriorityNormal=1 - for i := 0; i < n; i++ { - // bucket: 0 = earliest (highest priority), levels-1 = latest (lowest) - bucket := (i * levels) / n - if bucket >= levels { - bucket = levels - 1 - } - // prio: levels (Now) for bucket 0, 1 (Normal) for bucket levels-1 - prio := anacrolix_types.PiecePriority(levels - bucket) - t.Piece(i).SetPriority(prio) - } -} - -// ScheduledPause is the scheduler's pause channel — independent from the -// user's manual Pause. It uses the same SetMaxEstablishedConns(0/cap) trick -// the manual Pause uses, but writes only the scheduledPause map flag so -// snapshots can distinguish "user-paused" from "queue-held". -// -// CRITICAL: ScheduledPause(id, false) MUST refuse to re-enable a -// user-paused torrent. The scheduler reads a List() snapshot once per -// tick; if the user clicks Pause between the List() read and the -// per-id apply loop, the scheduler will try to ScheduledPause(false) -// the now-paused torrent. Without this guard, SetMaxEstablishedConns(80) -// fires and peers reconnect to a "paused" torrent. Pause's -// DisallowDataDownload prevents new piece requests but uploads + half- -// open conns can still leak through — and the UX bug ("paused torrent -// is still downloading") is exactly this race. -func (a *AnacrolixBackend) ScheduledPause(id TorrentID, paused bool) { - t, ok := a.find(id) - if !ok { - return - } - if !paused { - // Re-enable path — refuse if the user has paused this torrent. - a.pausedMu.RLock() - userPaused := a.paused[id] - a.pausedMu.RUnlock() - if userPaused { - return - } - } - if paused { - t.SetMaxEstablishedConns(0) - } else { - t.SetMaxEstablishedConns(int(a.maxConnsPerTorrent.Load())) - } - a.pausedMu.Lock() - a.scheduledPause[id] = paused - a.pausedMu.Unlock() -} diff --git a/backend/engine/anacrolix_detail.go b/backend/engine/anacrolix_detail.go new file mode 100644 index 0000000..1e0d1f9 --- /dev/null +++ b/backend/engine/anacrolix_detail.go @@ -0,0 +1,262 @@ +package engine + +import ( + "errors" + "fmt" + "math" + "net" + "strconv" + "strings" + "time" + + "github.com/anacrolix/torrent" + anacrolix_types "github.com/anacrolix/torrent/types" +) + +func (a *AnacrolixBackend) DetailedSnapshot(id TorrentID, scope DetailScope) (Detail, error) { + t, ok := a.find(id) + if !ok { + return Detail{}, errors.New("not found") + } + a.pausedMu.RLock() + paused := a.paused[id] + queuePos := a.queuePos[id] + forceStart := a.forceStart[id] + sequential := a.sequential[id] + queued := a.scheduledPause[id] + a.pausedMu.RUnlock() + a.verifyMu.RLock() + verifying := a.verifying[id] + filesMissing := a.filesMissing[id] + a.verifyMu.RUnlock() + snap := snapshotFor(t, a.rateFor(id), paused, queuePos, forceStart, sequential, queued, verifying, filesMissing) + d := Detail{Snapshot: snap} + + if scope.Files { + for i, f := range t.Files() { + d.Files = append(d.Files, FileEntry{ + Index: i, + Path: f.DisplayPath(), + Size: f.Length(), + BytesDone: f.BytesCompleted(), + Priority: prioFromAnacrolix(f.Priority()), + }) + } + } + + if scope.Peers { + // Per-peer windowed download rate: store last-tick cumulative + // BytesReadUsefulData per peer, divide the next tick's delta by + // the elapsed time. Falls back to 0 on the first tick (no prior + // sample) and on completion (we wouldn't be requesting chunks + // anyway). The per-peer map is still guarded by rateMu, shared + // with the rate sampler's prune of prevRates. + complete := t.BytesMissing() == 0 + now := time.Now() + a.rateMu.Lock() + prevPeers := a.prevPeerRates[id] + if prevPeers == nil { + prevPeers = make(map[string]peerRateSample) + } + nextPeers := make(map[string]peerRateSample, len(prevPeers)) + for _, pc := range t.PeerConns() { + addr := pc.RemoteAddr.String() + ip := addr + port := 0 + if h, p, err := splitHostPort(addr); err == nil { + ip = h + port = p + } + name, _ := pc.PeerClientName.Load().(string) + peerKey := addr // ip:port — stable per connection + // Assign Stats() to a local: Count.Int64 is a pointer-receiver + // method, and a field on a non-addressable function return + // value isn't itself addressable. + peerStats := pc.Stats() + cumDown := peerStats.ConnStats.BytesReadUsefulData.Int64() + var dlRate int64 + sample := peerRateSample{at: now, down: cumDown} + if !complete { + if prev, ok := prevPeers[peerKey]; ok { + if dt := now.Sub(prev.at); dt < minPeerRateSampleInterval { + // A second consumer called back-to-back (two web users + // focused on the same torrent each get a per-user + // DetailForFocus tick): dt is microseconds, so a fresh + // delta would read as 0 B/s or spike — the same + // multi-reader hazard the torrent-level sampler fixed + // centrally (see sampleRates). Reuse the previously + // computed rate and keep the old sample so the next + // real tick still has a meaningful dt. + dlRate = prev.rate + sample = prev + } else if secs := dt.Seconds(); secs > 0 { + dlRate = int64(float64(cumDown-prev.down) / secs) + if dlRate < 0 { + dlRate = 0 + } + sample.rate = dlRate + } + } + } + nextPeers[peerKey] = sample + d.Peers = append(d.Peers, PeerEntry{ + IP: ip, + Port: port, + ClientName: name, + Flags: peerFlagsFor(pc), + Progress: pieceProgressOf(t, pc), + DownloadRate: dlRate, + UploadRate: clampRate(peerStats.LastWriteUploadRate), + CountryCode: "", + }) + } + // Drop entries for peers that disconnected since the last tick + // (they're not in `seen`); nextPeers is already filtered to + // currently-present peers by virtue of being built from `conns`. + a.prevPeerRates[id] = nextPeers + a.rateMu.Unlock() + } + + if scope.Trackers { + // anacrolix v1.61 doesn't expose per-tracker announce state; the best + // signal we have is whether metadata has loaded (Info != nil). Before + // metadata, no tracker has produced a useful response yet → "Updating". + // After metadata, fall back to "OK" (best-effort). A future plan or + // upstream PR can refine this with real per-tracker error state. + status := "OK" + if t.Info() == nil { + status = "Updating" + } + mi := t.Metainfo() + for _, tier := range mi.AnnounceList { + for _, url := range tier { + d.Trackers = append(d.Trackers, TrackerEntry{ + URL: url, + Status: status, + }) + } + } + if len(d.Trackers) == 0 && mi.Announce != "" { + d.Trackers = append(d.Trackers, TrackerEntry{URL: mi.Announce, Status: status}) + } + } + + return d, nil +} + +func prioFromAnacrolix(p anacrolix_types.PiecePriority) Priority { + switch p { + case anacrolix_types.PiecePriorityNone: + return PrioritySkip + case anacrolix_types.PiecePriorityNormal: + return PriorityNormal + case anacrolix_types.PiecePriorityHigh: + return PriorityHigh + case anacrolix_types.PiecePriorityNow: + return PriorityMax + } + return PriorityNormal +} + +func splitHostPort(addr string) (string, int, error) { + h, p, err := net.SplitHostPort(addr) + if err != nil { + return "", 0, err + } + port, err := strconv.Atoi(p) + if err != nil { + return h, 0, err + } + return h, port, nil +} + +// bep20PeerID derives the 8-byte BEP-20 peer-id prefix from a +// "Mosaic/X.Y.Z" version string. Format is "-MSnnnn-" where nnnn is the +// 4-digit zero-padded numeric version (X*100 + Y*10 + Z, capped at 4 +// digits). Returns "" if the input doesn't parse as a recognizable +// semver — anacrolix will fall back to its default Bep20 in that case. +// +// Example: "Mosaic/0.5.7" → "-MS0057-". +func bep20PeerID(clientVersion string) string { + // Pull the digits after the slash. + slash := strings.IndexByte(clientVersion, '/') + if slash < 0 || slash == len(clientVersion)-1 { + return "" + } + parts := strings.SplitN(clientVersion[slash+1:], ".", 4) + if len(parts) < 2 { + return "" + } + var nums [3]int + for i := 0; i < 3 && i < len(parts); i++ { + // Strip a leading "v" on the first part if present. + s := parts[i] + if i == 0 { + s = strings.TrimPrefix(s, "v") + } + // Only accept the leading run of digits — allows "0.5.7-rc1" → 0,5,7. + end := 0 + for end < len(s) && s[end] >= '0' && s[end] <= '9' { + end++ + } + if end == 0 { + return "" + } + n, err := strconv.Atoi(s[:end]) + if err != nil { + return "" + } + nums[i] = n + } + combined := nums[0]*100 + nums[1]*10 + nums[2] + if combined > 9999 { + combined = 9999 + } + return fmt.Sprintf("-MS%04d-", combined) +} + +// clampRate sanitizes anacrolix's float64 per-peer rate counters before +// they reach our int64 DTO. NaN ((0 piece-data bytes)/(0 ns) for peers +// we're not actually exchanging data with), +Inf (writeDuration sub- +// nanosecond), and negative values all get pinned to safe ranges. +// +// Pre-fix the int64() cast on NaN produced math.MinInt64 +// (-9223372036854775808) and the SPA rendered "-922337203685477600 B/s" +// for "majority of peers" because that's the resting state of +// LastWriteUploadRate on conns we never piece-uploaded to. +func clampRate(f float64) int64 { + if math.IsNaN(f) || f < 0 { + return 0 + } + if math.IsInf(f, 1) || f > float64(math.MaxInt64) { + return math.MaxInt64 + } + return int64(f) +} + +// peerFlagsFor returns the BitTorrent peer flag string. anacrolix v1.61 keeps +// peerInterested/peerChoking unexported and ships no header-obfuscation +// accessor, so we cannot read the bits — Plan 4 (or an upstream PR) refines. +func peerFlagsFor(pc *torrent.PeerConn) string { + _ = pc + return "" +} + +// pieceProgressOf returns 0..1 of pieces this peer has. *roaring.Bitmap has +// no Len() method; the denominator is the parent torrent's piece count. +func pieceProgressOf(t *torrent.Torrent, pc *torrent.PeerConn) float64 { + pp := pc.PeerPieces() + if pp.IsEmpty() { + return 0 + } + n := t.NumPieces() + if n == 0 { + return 0 + } + return float64(pp.GetCardinality()) / float64(n) +} + +// snapshotFor builds a Snapshot for a torrent. The down/up rate is supplied +// by the caller from the centralized rate cache (see sampleRates) — this +// function no longer computes or stores rate samples, so it is a pure read +// of the torrent and is safe to call concurrently from any number of readers. diff --git a/backend/engine/anacrolix_limits.go b/backend/engine/anacrolix_limits.go new file mode 100644 index 0000000..6c64960 --- /dev/null +++ b/backend/engine/anacrolix_limits.go @@ -0,0 +1,214 @@ +package engine + +import ( + "errors" + "time" + + "github.com/anacrolix/torrent" + "golang.org/x/time/rate" +) + +func (a *AnacrolixBackend) SetGlobalRateLimits(downBPS, upBPS int) error { + if downBPS <= 0 { + a.dlLim.SetLimit(rate.Inf) + a.dlLim.SetBurst(256 << 10) + } else { + a.dlLim.SetLimit(rate.Limit(downBPS)) + a.dlLim.SetBurst(max(downBPS, 256<<10)) + } + if upBPS <= 0 { + a.ulLim.SetLimit(rate.Inf) + a.ulLim.SetBurst(256 << 10) + } else { + a.ulLim.SetLimit(rate.Limit(upBPS)) + a.ulLim.SetBurst(max(upBPS, 256<<10)) + } + return nil +} + +// SetTorrentRateLimits sets per-torrent download/upload caps in bytes/sec. +// 0 means unlimited. Enforcement uses a background duty-cycle goroutine +// registered on verifyWg so Close() waits for it to drain. If the torrent +// already has a limiter goroutine running (prior call to SetTorrentRateLimits) +// it will pick up the new limits on its next tick — no new goroutine is +// spawned for subsequent updates. +func (a *AnacrolixBackend) SetTorrentRateLimits(id TorrentID, downBPS, upBPS int64) error { + if downBPS < 0 { + downBPS = 0 + } + if upBPS < 0 { + upBPS = 0 + } + a.perLimitMu.Lock() + a.perTorrentDown[id] = downBPS + a.perTorrentUp[id] = upBPS + // Lifecycle is tracked via limiterRunning, NOT the previous limit values: + // a clear-to-(0,0) followed by a non-zero set within one tick leaves the + // old goroutine alive (it never observes the transient 0,0), so spawning + // another would race it. The goroutine clears the flag under perLimitMu + // with a limits re-check before exiting, so set-after-clear either reuses + // the live limiter or deterministically starts a fresh one. + needsStart := (downBPS != 0 || upBPS != 0) && !a.limiterRunning[id] + if needsStart { + a.limiterRunning[id] = true + } + a.perLimitMu.Unlock() + + if needsStart { + t, ok := a.find(id) + if !ok { + a.perLimitMu.Lock() + delete(a.limiterRunning, id) + a.perLimitMu.Unlock() + return errors.New("not found") + } + a.verifyWg.Add(1) + go a.runPerTorrentLimiter(id, t) + } else if downBPS == 0 && upBPS == 0 { + // Limits cleared — ensure download/upload are allowed + // (the goroutine may have left them disallowed). + t, ok := a.find(id) + if !ok { + return nil + } + t.AllowDataDownload() + t.AllowDataUpload() + } + return nil +} + +// runPerTorrentLimiter is a background goroutine that enforces per-torrent +// rate limits by sampling byte counters every 500ms and using +// DisallowDataDownload/AllowDataDownload (and the Upload equivalents) to +// implement a duty-cycle approximation. +// +// The approach: each 500ms tick we read how many bytes were transferred since +// the last tick. If the torrent exceeded its budget (bytes_this_tick > +// limit_per_500ms), we disallow data for the overrun fraction of the next +// interval. Otherwise we allow data. This is a coarse token-bucket; actual +// throughput will hover around the configured cap ±1 tick's worth (~one +// per-piece chunk, ~16 KB by default in anacrolix) rather than being +// byte-perfect. +// +// The goroutine exits when: (a) engineCtx is cancelled (engine shutdown), or +// (b) both down and up limits drop to 0 (user cleared the limit). +func (a *AnacrolixBackend) runPerTorrentLimiter(id TorrentID, t *torrent.Torrent) { + defer a.verifyWg.Done() + const interval = 500 * time.Millisecond + ticker := time.NewTicker(interval) + defer ticker.Stop() + + var prevDown, prevUp int64 + var dlBlocked, ulBlocked bool + + // Helper: read current cumulative stats from anacrolix. + readStats := func() (down, up int64) { + s := t.Stats() + return s.BytesReadData.Int64(), s.BytesWrittenData.Int64() + } + + prevDown, prevUp = readStats() + + for { + select { + case <-a.engineCtx.Done(): + // Engine shutting down — re-enable before exit so state is clean. + if dlBlocked { + t.AllowDataDownload() + } + if ulBlocked { + t.AllowDataUpload() + } + return + case <-ticker.C: + } + + a.perLimitMu.RLock() + downLimit := a.perTorrentDown[id] + upLimit := a.perTorrentUp[id] + a.perLimitMu.RUnlock() + + // Both limits cleared — re-enable and exit. Confirm under the write + // lock and clear limiterRunning atomically with the re-check: a + // SetTorrentRateLimits that re-set non-zero limits between our + // RLock read and here must either be observed (keep running) or + // happen strictly after the flag is cleared (spawns a fresh + // limiter). Without the re-check this goroutine could exit just as + // the setter saw it as still-running and skipped the spawn, + // leaving the torrent unlimited. + if downLimit == 0 && upLimit == 0 { + a.perLimitMu.Lock() + if a.perTorrentDown[id] != 0 || a.perTorrentUp[id] != 0 { + a.perLimitMu.Unlock() + continue + } + delete(a.limiterRunning, id) + a.perLimitMu.Unlock() + if dlBlocked { + t.AllowDataDownload() + } + if ulBlocked { + t.AllowDataUpload() + } + return + } + + curDown, curUp := readStats() + deltaDown := curDown - prevDown + deltaUp := curUp - prevUp + prevDown, prevUp = curDown, curUp + + // Budget per interval (bytes allowed per 500ms tick). + budgetDown := int64(float64(downLimit) * interval.Seconds()) + budgetUp := int64(float64(upLimit) * interval.Seconds()) + + // Download enforcement. + if downLimit > 0 { + // Check paused state — if paused we don't manage download allow/disallow + // to avoid conflicting with Pause()'s DisallowDataDownload. + a.pausedMu.RLock() + isPaused := a.paused[id] + a.pausedMu.RUnlock() + if !isPaused { + if deltaDown > budgetDown { + // Over budget — disallow for next tick. + if !dlBlocked { + t.DisallowDataDownload() + dlBlocked = true + } + } else { + // Under budget — allow. + if dlBlocked { + t.AllowDataDownload() + dlBlocked = false + } + } + } + } else if dlBlocked { + t.AllowDataDownload() + dlBlocked = false + } + + // Upload enforcement. + if upLimit > 0 { + if deltaUp > budgetUp { + if !ulBlocked { + t.DisallowDataUpload() + ulBlocked = true + } + } else { + if ulBlocked { + t.AllowDataUpload() + ulBlocked = false + } + } + } else if ulBlocked { + t.AllowDataUpload() + ulBlocked = false + } + } +} + +// AddTracker adds a single tracker URL to an existing torrent in its own tier. +// anacrolix's AddTrackers takes a slice of tiers ([][]string); we pass one +// tier containing the single URL so it doesn't compete with metainfo trackers. diff --git a/backend/engine/anacrolix_torrents.go b/backend/engine/anacrolix_torrents.go new file mode 100644 index 0000000..a0427e4 --- /dev/null +++ b/backend/engine/anacrolix_torrents.go @@ -0,0 +1,814 @@ +package engine + +import ( + "bytes" + "context" + "errors" + "fmt" + "log" + "os" + goruntime "runtime" + "sync" + "time" + + "github.com/anacrolix/torrent" + "github.com/anacrolix/torrent/metainfo" + anacrolix_types "github.com/anacrolix/torrent/types" +) + +func (a *AnacrolixBackend) AddMagnet(ctx context.Context, magnet, savePath string) (TorrentID, error) { + // SECURITY: savePath is caller-controlled. In multi-user mosaicd a + // non-admin must NOT be able to MkdirAll into arbitrary daemon-writable + // paths (/etc/cron.d, ~root/.ssh, another user's home). Callers in + // api/service.go must funnel non-admin save paths through + // engine.ValidateSavePath(userRoot, savePath, /*restrictToRoot=*/ true) + // BEFORE invoking AddMagnet. Admin and single-user-desktop callers + // pass restrictToRoot=false to keep the current unrestricted behavior. + // This function intentionally does not re-validate because the engine + // doesn't know the caller's role/userID — that context lives in api/. + if err := os.MkdirAll(savePath, 0o755); err != nil { + return "", err + } + spec, err := torrent.TorrentSpecFromMagnetUri(magnet) + if err != nil { + return "", err + } + spec.Storage = newFileStorage(savePath, a.pieceCompletion, a.preallocateFullFiles) + t, _, err := a.client.AddTorrentSpec(spec) + if err != nil { + return "", err + } + id := idFor(t) + a.mu.Lock() + a.bySaveTo[id] = savePath + a.byID[id] = t + a.mu.Unlock() + a.installWriteErrorHook(id, t) + a.spawnVerify(ctx, id, t) + return id, nil +} + +// spawnVerify runs verifyAndStart on a tracked goroutine so Close() can +// wait for it to finish before tearing down the client + bolt. The +// caller's ctx still governs the pre-GotInfo wait (so a Wails shutdown +// or a slow magnet add can be cancelled during DHT lookup); past +// GotInfo verifyAndStart switches to engineCtx, which Close() cancels. +func (a *AnacrolixBackend) spawnVerify(ctx context.Context, id TorrentID, t *torrent.Torrent) { + a.verifyWg.Add(1) + go func() { + defer a.verifyWg.Done() + a.verifyAndStart(ctx, id, t) + }() +} + +// verifyAndStart hashes existing files (so resume picks up partials), then +// either kicks DownloadAll OR — if Service marked this torrent as previously +// complete and verify finds <100% — flags FilesMissing and pauses so the +// app doesn't silently redownload bytes the user just deleted. +// +// The caller's ctx is honored ONLY for the pre-GotInfo wait (so a Wails +// shutdown / HTTP-handler return / RSS-poll-cycle end cancels DHT lookup +// promptly). Past GotInfo we switch to context.Background() — verify and +// priority-lift must complete regardless of who originated the Add, or +// the torrent silently never downloads. Pre-fix: every Add path threaded +// the caller's request-scoped ctx all the way through; HTTP handlers, +// RSS PollNow, and any second-instance IPC dispatch returned before +// verify finished, the cancelled-ctx check before setAllFilesPriority +// bailed, file priorities stayed at PiecePriorityNone, and peers +// connected but no pieces were ever requested. The Wails GUI happened +// to dodge it because app.go threads the long-lived a.ctx. +// Anacrolix's own goroutines are cancelled on Client.Close (which +// Engine.Close calls), so Background ctx is shutdown-safe. +func (a *AnacrolixBackend) verifyAndStart(ctx context.Context, id TorrentID, t *torrent.Torrent) { + // Wait for metainfo. AddFile already has it (channel is pre-closed); + // AddMagnet has to fetch it via DHT/PEX before we can hash anything. + // Listen on engineCtx too: anacrolix's gotMetainfoC is closed by + // onSetInfo (when metainfo IS received), NOT by t.Drop / Client.Close, + // so a magnet that never resolves would wedge the goroutine forever + // and the engine's verifyWg.Wait at shutdown couldn't return until + // the 5s drain timeout (or, on macOS at least, longer — Wails's + // shutdown order kept the X-button click feeling like the app was + // frozen). engineCtx.Done firing on Close drops these goroutines + // promptly so verifyWg drains in milliseconds. + select { + case <-t.GotInfo(): + case <-ctx.Done(): + return + case <-a.engineCtx.Done(): + return + } + // Past GotInfo — switch from the caller's ctx (which an HTTP handler + // or RSS poller will cancel as soon as the call returns) to the + // engine's lifetime ctx (which Close() cancels). Verify must outlive + // any specific request, but it MUST NOT outlive the engine — Close + // closes the bolt + anacrolix client, and an in-flight verify dispatch + // would crash or hang otherwise. + ctx = a.engineCtx + + a.setVerifying(id, true) + defer a.setVerifying(id, false) + + // Disk-space precheck. Once metadata is in we know how many bytes + // the torrent will need; if the save path's filesystem can't fit + // what's missing (BytesMissing already discounts what's on disk), + // fail fast with a clear error rather than letting anacrolix start + // requesting and surfacing ENOSPC chunk-write errors mid-flight. + // 64 MB headroom for filesystem overhead and a margin against + // concurrent writers; we'd rather error a borderline torrent than + // silently disable it after consuming the last few hundred MB. + if info := t.Info(); info != nil { + if needed := t.BytesMissing(); needed > 0 { + if free := diskFreeBytes(a.saveDirFor(id)); free >= 0 && free < needed+(64<<20) { + t.DisallowDataDownload() + a.raiseError(id, fmt.Errorf("insufficient disk space: %d bytes free, need %d (+64 MB headroom) for %q", + free, needed, info.Name)) + return + } + } + } + + // Fast-resume: if we have a snapshot from a prior session and the + // on-disk file state still matches, replay the saved per-piece + // bitmap into bolt to undo anacrolix's setCompletionFromPartFiles + // wipe (which fired during AddTorrentSpec for any partial torrent), + // then skip the full re-hash. For complete torrents the bitmap + // matches what bolt already has and the replay is a no-op; for + // partials it's the difference between a stat-per-file fast resume + // and reading every byte of a 13 GB preallocated .part to find the + // 200 MB we actually have. + // + // If file digest doesn't match (user deleted/edited bytes + // off-Mosaic between sessions), we fall through to verifyDataParallel + // — the bitmap would be lying about what's on disk. Same fall-through + // applies if no snapshot was ever saved (legacy or first-Add). + if a.snapshotStore != nil { + if snap, wasComplete, bitmap, ok := a.snapshotStore.LoadPieceBitmap(id); ok { + if bitmap == nil { + log.Printf("verify: snapshot exists but no bitmap for %s — falling through to full hash", id) + } else if info := t.Info(); info == nil { + log.Printf("verify: snapshot exists but t.Info() is nil for %s — falling through to full hash", id) + } else { + saveTo := a.saveDirFor(id) + cur, snapErr := computeFileSnapshot(info, saveTo) + if snapErr != nil { + log.Printf("verify: computeFileSnapshot error for %s: %v — falling through to full hash", id, snapErr) + } else if !bytes.Equal(snap, cur) { + log.Printf("verify: file-state mismatch for %s — files changed off-Mosaic; running full hash", id) + } else { + if wasComplete { + // Complete torrent: setCompletionFromPartFiles already set all + // pieces to complete in bolt (files exist at the final path with + // the right size). No need to replay the bitmap — that would just + // be 7000+ redundant bolt View transactions, each confirming what + // bolt already knows. Skipping the replay keeps this path at + // ~5ms (snapshot load + file stat) vs. 200-800ms. + log.Printf("verify: fast-resume %s — skipping hash (complete, no bolt restore needed)", id) + a.snapshotMu.Lock() + a.snapshotSaved[id] = true + a.snapshotMu.Unlock() + } else { + // Partial torrent: setCompletionFromPartFiles marked pieces for + // incomplete files as "not complete" because their .part file is + // not at the final path. Replay the saved bitmap so anacrolix + // sees the actual per-piece state without re-hashing. + restored := a.restoreBoltFromBitmap(t, bitmap) + log.Printf("verify: fast-resume %s — skipping hash (partial, restored=%d pieces)", id, restored) + } + if ctx.Err() == nil { + a.applyPostVerifyPriorities(id, t) + } + return + } + } + } else { + log.Printf("verify: no snapshot for %s — first-add or recheck; running full hash", id) + } + } + + verifyDataParallel(ctx, t) + + a.verifyMu.RLock() + wasComplete := a.expectedComplete[id] + a.verifyMu.RUnlock() + + // BytesMissing is the canonical "is anything still needed" check. + if wasComplete && t.BytesMissing() > 0 { + a.verifyMu.Lock() + a.filesMissing[id] = true + a.verifyMu.Unlock() + // Pause the torrent so it doesn't silently redownload. User can hit + // Resume to either replace missing files or remove the entry. + a.pausedMu.Lock() + a.paused[id] = true + a.pausedMu.Unlock() + t.SetMaxEstablishedConns(0) + return + } + + // Now that the torrent is fully present, persist the snapshot so the + // next startup can take the fast-resume path. + a.saveSnapshotIfComplete(id, t) + + a.applyPostVerifyPriorities(id, t) +} + +// applyPostVerifyPriorities restores piece priorities once verify finishes. +// SetSequential may have run while the verify was in flight; blindly resetting +// every file to Normal here would silently revert the sequential gradient, so +// re-apply it instead when the flag is set. +func (a *AnacrolixBackend) applyPostVerifyPriorities(id TorrentID, t *torrent.Torrent) { + a.pausedMu.RLock() + sequential := a.sequential[id] + a.pausedMu.RUnlock() + if sequential { + applySequentialPriorities(t, true) + return + } + setAllFilesPriority(t, anacrolix_types.PiecePriorityNormal) +} + +// setAllFilesPriority is the file-aware replacement for t.DownloadAll(). +// DownloadAll raises piece priorities directly via DownloadPieces() but +// never touches File.prio, which means File.Priority() keeps returning +// PiecePriorityNone (which we surface as "Skip" in the Files pane). The +// piece-level effect is the same — anacrolix's purePriority() takes the +// max across each piece's overlapping files plus the per-piece raise — +// but iterating and SetPriority'ing each file lifts BOTH file.prio AND +// the underlying pieces, so the UI displays the correct file priority +// instead of misleading the user into thinking the files are skipped. +// +// Safe before t.GotInfo only if t.Files() returns the populated list; in +// practice all callers are past GotInfo by the time they hit this. +func setAllFilesPriority(t *torrent.Torrent, prio anacrolix_types.PiecePriority) { + for _, f := range t.Files() { + f.SetPriority(prio) + } +} + +// saveSnapshotIfComplete is the per-tick dedup'd path for completed +// torrents — once a torrent finishes downloading and the engine ticker +// observes the transition, this fires once and snapshotSaved quiesces +// it. Bitmap is recorded too so a fully-complete torrent's restart +// avoids touching disk at all. +func (a *AnacrolixBackend) saveSnapshotIfComplete(id TorrentID, t *torrent.Torrent) { + a.snapshotMu.Lock() + saved := a.snapshotSaved[id] + a.snapshotMu.Unlock() + if saved { + return + } + if t.BytesMissing() != 0 { + return + } + if !a.writeSnapshot(id, t, true) { + return + } + a.snapshotMu.Lock() + a.snapshotSaved[id] = true + a.snapshotMu.Unlock() +} + +// saveSnapshotForCheckpoint records the file digest + per-piece bitmap +// at a quiesced point in the torrent's lifetime — typically pause or +// engine shutdown. Unlike saveSnapshotIfComplete it works for partial +// torrents too: the bitmap captures exactly which pieces bolt thinks +// are complete RIGHT NOW, and the next add can replay it after +// anacrolix's storage init wipes bolt for partials. Skips while verify +// is mid-flight (capturing a half-verified state would replay +// nonsense). wasComplete is recorded honestly. +func (a *AnacrolixBackend) saveSnapshotForCheckpoint(id TorrentID, t *torrent.Torrent) { + a.verifyMu.RLock() + verifying := a.verifying[id] + a.verifyMu.RUnlock() + if verifying { + return + } + complete := t.BytesMissing() == 0 + if !a.writeSnapshot(id, t, complete) { + return + } + if complete { + a.snapshotMu.Lock() + a.snapshotSaved[id] = true + a.snapshotMu.Unlock() + } +} + +// writeSnapshot is the shared implementation: compute the file-state +// digest + per-piece completion bitmap, persist them via the snapshot +// store atomically. The bitmap is what lets the next launch avoid the +// brutal "verify all 13 GB to find the 200 MB we have" rehash — +// anacrolix's setCompletionFromPartFiles wipes bolt's complete entries +// for any partial-with-.part-files torrent, but if the file digest +// matches what we recorded with the bitmap, we know the disk state +// hasn't changed off-Mosaic and can replay the bitmap straight back +// into bolt to restore anacrolix's per-piece view in one cheap loop. +// +// Falls back to plain snapshot save (no bitmap) if reading per-piece +// completion fails — the legacy verify path still covers correctness. +func (a *AnacrolixBackend) writeSnapshot(id TorrentID, t *torrent.Torrent, complete bool) bool { + if a.snapshotStore == nil { + return false + } + info := t.Info() + if info == nil { + return false + } + saveTo := a.saveDirFor(id) + cur, err := computeFileSnapshot(info, saveTo) + if err != nil { + log.Printf("verify: compute snapshot for %s: %v", id, err) + return false + } + bitmap := piecesToBitmap(t) + if err := a.snapshotStore.SavePieceBitmap(id, cur, complete, bitmap); err != nil { + log.Printf("verify: save snapshot/bitmap for %s: %v", id, err) + return false + } + return true +} + +// piecesToBitmap reads anacrolix's per-piece completion view via +// PieceState and packs it into a `(NumPieces+7)/8`-byte bitmap. Bit i +// is set iff piece i is complete. Reading PieceState is cheap (no +// disk I/O — it's a memory read off the cached completion state). +func piecesToBitmap(t *torrent.Torrent) []byte { + n := t.NumPieces() + if n <= 0 { + return nil + } + out := make([]byte, (n+7)/8) + for i := 0; i < n; i++ { + if t.PieceState(i).Complete { + out[i/8] |= 1 << (uint(i) & 7) + } + } + return out +} + +// restoreBoltFromBitmap replays a saved per-piece completion bitmap +// into anacrolix's bolt store. Called after AddTorrentSpec runs (which +// invokes setCompletionFromPartFiles, wiping any "complete" bolt +// entries for partial torrents) but before verifyAndStart kicks off — +// the next time anacrolix consults bolt for piece N, it sees the +// restored truth and storageCompletionOk flips to true so the piece +// becomes eligible for requests immediately, no re-hash needed. +// +// Caller is responsible for verifying the file-state snapshot matches +// before calling this; otherwise we'd be lying to anacrolix about what +// bytes are actually on disk. +func (a *AnacrolixBackend) restoreBoltFromBitmap(t *torrent.Torrent, bitmap []byte) int { + if a.pieceCompletion == nil || len(bitmap) == 0 { + return 0 + } + n := t.NumPieces() + ih := t.InfoHash() + restored := 0 + for i := 0; i < n; i++ { + byteIdx := i / 8 + if byteIdx >= len(bitmap) { + break + } + complete := bitmap[byteIdx]&(1<<(uint(i)&7)) != 0 + if !complete { + // We don't restore "incomplete" — bolt's default state for + // missing entries is already storageCompletionOk=false / + // piece-not-complete. Setting false explicitly would just + // add a row per piece for no benefit. Pieces marked + // complete are the only ones worth replaying. + continue + } + if err := a.pieceCompletion.Set(metainfo.PieceKey{InfoHash: ih, Index: i}, true); err != nil { + log.Printf("verify: restore piece %d for %s: %v", i, idFor(t), err) + continue + } + restored++ + } + return restored +} + +// saveDirFor returns the per-torrent save root captured at AddFile/AddMagnet +// time (same value passed to anacrolix's storage.NewFile). Files for the +// torrent live at filepath.Join(saveDir, info.Name, file.Path...). +func (a *AnacrolixBackend) saveDirFor(id TorrentID) string { + a.mu.Lock() + defer a.mu.Unlock() + return a.bySaveTo[id] +} + +// verifyDataParallel hashes every piece of t, but unlike t.VerifyData() +// (which iterates pieces sequentially and blocks on each one), it dispatches +// up to `workers` outer goroutines so the lib's piece-hasher worker pool +// stays saturated. anacrolix's t.VerifyData has a TODO admitting the +// sequential design; queuing-1-and-waiting-1 means PieceHashersPerTorrent +// > 1 buys us nothing. v0.2.10 used NumCPU/2 capped at 8 here, but the +// client locker contention inside anacrolix means more outer goroutines +// just spin without throughput — so v0.2.11 caps at NumCPU/4 (2..4) to +// match PieceHashersPerTorrent in NewAnacrolixBackend. +func verifyDataParallel(ctx context.Context, t *torrent.Torrent) { + n := t.NumPieces() + if n == 0 { + return + } + workers := goruntime.NumCPU() / 4 + if workers < 2 { + workers = 2 + } + if workers > 4 { + workers = 4 + } + if workers > n { + workers = n + } + sem := make(chan struct{}, workers) + var wg sync.WaitGroup + for i := 0; i < n; i++ { + select { + case <-ctx.Done(): + wg.Wait() + return + case sem <- struct{}{}: + } + wg.Add(1) + go func(idx int) { + defer wg.Done() + defer func() { <-sem }() + _ = t.Piece(idx).VerifyDataContext(ctx) + }(i) + } + wg.Wait() +} + +func (a *AnacrolixBackend) setVerifying(id TorrentID, v bool) { + a.verifyMu.Lock() + if v { + a.verifying[id] = true + } else { + delete(a.verifying, id) + } + a.verifyMu.Unlock() +} + +// MarkExpectedComplete marks this torrent as having been 100% on a prior +// session, so verifyAndStart can flag FilesMissing if VerifyData reveals +// the user deleted files. Service.RestoreOnStartup calls this when the +// persisted record's CompletedAt is non-nil. +func (a *AnacrolixBackend) MarkExpectedComplete(id TorrentID) { + a.verifyMu.Lock() + a.expectedComplete[id] = true + a.verifyMu.Unlock() +} + +func (a *AnacrolixBackend) AddFile(ctx context.Context, blob []byte, savePath string) (TorrentID, error) { + // SECURITY: same caller-controlled-path concern as AddMagnet. See the + // note there. The api/service.go AddTorrentFile / AddTorrentBytes paths + // are expected to ValidateSavePath before calling in. + if err := os.MkdirAll(savePath, 0o755); err != nil { + return "", err + } + mi, err := metainfo.Load(bytes.NewReader(blob)) + if err != nil { + return "", err + } + spec := torrent.TorrentSpecFromMetaInfo(mi) + spec.Storage = newFileStorage(savePath, a.pieceCompletion, a.preallocateFullFiles) + t, _, err := a.client.AddTorrentSpec(spec) + if err != nil { + return "", err + } + id := idFor(t) + a.mu.Lock() + a.bySaveTo[id] = savePath + a.byID[id] = t + a.mu.Unlock() + a.installWriteErrorHook(id, t) + // Same verify-then-start flow as AddMagnet — the GotInfo wait inside + // verifyAndStart is a no-op here since metainfo is already attached. + a.spawnVerify(ctx, id, t) + return id, nil +} + +func (a *AnacrolixBackend) Pause(id TorrentID) error { + t, ok := a.find(id) + if !ok { + return errors.New("not found") + } + // Two-step pause: + // 1. DisallowDataDownload — stops anacrolix from issuing piece + // requests, even if peer conns come back up. This is the + // load-bearing guarantee. + // 2. SetMaxEstablishedConns(0) — drops existing peer conns and + // refuses new ones, so we're not accepting/uploading either. + // + // Pre-fix Pause only did #2, which has a known race against the + // scheduler tick: scheduler reads List() at t=0, user clicks Pause + // at t=10ms (paused flag flips, conns drop), scheduler iterates the + // stale snapshot and calls ScheduledPause(id, false) → + // SetMaxEstablishedConns(80), peers reconnect, anacrolix happily + // resumes piece requests because the priority lift is still in place. + // User sees a paused torrent that's still downloading. Disallow + // closes the gap regardless of conn-cap thrashing. + t.DisallowDataDownload() + t.SetMaxEstablishedConns(0) + a.pausedMu.Lock() + a.paused[id] = true + a.pausedMu.Unlock() + // Checkpoint the file state + per-piece bitmap. The bitmap is what + // makes fast-resume work for partial torrents post-anacrolix's + // per-add storage init wipe — the next add will replay it back into + // bolt after the wipe so anacrolix sees the actual disk state + // without re-hashing every piece. + a.saveSnapshotForCheckpoint(id, t) + return nil +} + +func (a *AnacrolixBackend) Resume(id TorrentID) error { + t, ok := a.find(id) + if !ok { + return errors.New("not found") + } + t.SetMaxEstablishedConns(int(a.maxConnsPerTorrent.Load())) + a.pausedMu.Lock() + a.paused[id] = false + delete(a.scheduledPause, id) + a.pausedMu.Unlock() + // If this resume comes after a FilesMissing flag (user wants to redownload + // after files were deleted), clear the flag — VerifyData will rerun if + // new pieces fail. + a.verifyMu.Lock() + delete(a.filesMissing, id) + a.verifyMu.Unlock() + // Resume is also the recovery path after a disk-full / write-error + // stoppage: AllowDataDownload clears the dataDownloadDisallowed flag + // our write-error hook (and anacrolix's storage-completion error + // path) sets. Idempotent if it was never disallowed. + t.AllowDataDownload() + return nil +} + +// ApplyPerTorrentMaxPeers updates SetMaxEstablishedConns on every running +// torrent. Used when the user changes the "max peers per torrent" setting. +// Already-paused torrents keep their cap of 0 (we set it to 0 to pause); +// the new cap is stored in maxConnsPerTorrent so Resume (and the +// scheduler's re-enable path) restore it instead of a hardcoded default. +func (a *AnacrolixBackend) ApplyPerTorrentMaxPeers(n int) error { + if n <= 0 { + n = 80 // anacrolix default + } + a.maxConnsPerTorrent.Store(int64(n)) + a.pausedMu.RLock() + paused := make(map[TorrentID]bool, len(a.paused)) + for id, v := range a.paused { + paused[id] = v + } + a.pausedMu.RUnlock() + for _, t := range a.client.Torrents() { + id := TorrentID(t.InfoHash().HexString()) + if paused[id] { + continue + } + t.SetMaxEstablishedConns(n) + } + return nil +} + +// Recheck re-hashes every piece against the metainfo. Surfaced via the +// Recheck context-menu item in the SPA. Runs on a goroutine — large torrents +// take a while; while running the Verifying pill shows in the UI. +// +// We invalidate the fast-resume snapshot up front: a Recheck means the user +// wants the verify to actually run, and once it finishes we'll write a new +// snapshot from the just-verified state. +func (a *AnacrolixBackend) Recheck(id TorrentID) error { + t, ok := a.find(id) + if !ok { + return errors.New("not found") + } + if a.snapshotStore != nil { + if err := a.snapshotStore.DeleteVerifySnapshot(id); err != nil { + log.Printf("verify: delete snapshot for %s: %v", id, err) + } + } + // Clear the in-memory dedup so saveSnapshotIfComplete re-runs after the + // recheck finishes (it's the same write the original goroutine did + // inline pre-v0.4.4). The retry-backoff stamp goes too — a user-driven + // recheck should attempt the save immediately. + a.snapshotMu.Lock() + delete(a.snapshotSaved, id) + delete(a.snapshotRetryAt, id) + a.snapshotMu.Unlock() + a.setVerifying(id, true) + a.verifyWg.Add(1) + go func() { + defer a.verifyWg.Done() + defer a.setVerifying(id, false) + verifyDataParallel(a.engineCtx, t) + // Don't snapshot if the engine is shutting down — saveSnapshotIfComplete + // writes to the snapshot store, which Close will tear down right after + // it cancels engineCtx and waits on verifyWg. + if a.engineCtx.Err() != nil { + return + } + a.saveSnapshotIfComplete(id, t) + }() + return nil +} + +func (a *AnacrolixBackend) Remove(id TorrentID, deleteFiles bool) error { + t, ok := a.find(id) + if !ok { + return errors.New("not found") + } + a.mu.Lock() + saveTo := a.bySaveTo[id] + delete(a.bySaveTo, id) + delete(a.byID, id) + a.mu.Unlock() + a.pausedMu.Lock() + delete(a.paused, id) + delete(a.queuePos, id) + delete(a.forceStart, id) + delete(a.sequential, id) + delete(a.scheduledPause, id) + a.pausedMu.Unlock() + a.snapshotMu.Lock() + delete(a.snapshotSaved, id) + delete(a.snapshotRetryAt, id) + a.snapshotMu.Unlock() + a.rateMu.Lock() + delete(a.prevRates, id) + delete(a.prevPeerRates, id) + a.rateMu.Unlock() + // Clear per-torrent limits so the limiter goroutine exits on next tick. + a.perLimitMu.Lock() + delete(a.perTorrentDown, id) + delete(a.perTorrentUp, id) + a.perLimitMu.Unlock() + // t.Drop holds the client lock while it tears the torrent down, and + // inside that the cleanup waits on a per-torrent wait group that + // covers (among other things) tracker stop announces. A + // tracker that's hanging on a TCP connect (HTTP-only trackers like + // the checkmyiptorrent variant the user hit) can hold this for as + // long as the OS connect timeout, blocking the UI's "Remove" call. + // Cap at 5s and let anacrolix finish on its own — our in-memory + // state has already been cleaned, the user has already been told + // "removed." + dropDone := make(chan struct{}) + go func() { + t.Drop() + close(dropDone) + }() + select { + case <-dropDone: + case <-time.After(5 * time.Second): + log.Printf("remove: t.Drop timeout for %s — proceeding without waiting", id) + } + if deleteFiles && saveTo != "" { + if info := t.Info(); info != nil { + // Path-traversal defense: a malicious .torrent's info.Name can be + // "../../something" — joining it raw would let RemoveAll walk above + // saveTo and delete arbitrary files. safeRemovePath validates + // containment (resolving symlinks on both ends when present) and + // returns an error we log+skip on. The in-memory unsubscribe + // (t.Drop, the map deletes above) has already happened — only the + // disk delete is conditional on validation. + // + // Additional defense-in-depth: saveTo itself was caller-controlled + // at Add time. In multi-user mode the api/ layer is expected to + // validate it via engine.ValidateSavePath before AddMagnet/AddFile, + // but we sanity-check here too — a saveTo that's empty, relative, + // contains NUL, or resolves to a filesystem root must not have + // RemoveAll fired on it under any circumstances. + if err := sanityCheckSaveTo(saveTo); err != nil { + log.Printf("refusing to delete files for torrent: saveTo=%q error=%v", saveTo, err) + } else { + path, err := safeRemovePath(saveTo, info.Name) + if err != nil { + log.Printf("refusing to delete files for torrent: name=%q error=%v", info.Name, err) + } else { + _ = os.RemoveAll(path) + } + } + } + } + return nil +} + +func (a *AnacrolixBackend) List() []Snapshot { + ts := a.client.Torrents() + out := make([]Snapshot, 0, len(ts)) + // Collect newly-completed ids inside the locked region; persist their + // fast-resume snapshots in goroutines after the locks are released so + // the file I/O doesn't block the tick. spawnSnapshotSave dedupes against + // snapshotSaved / the in-flight guard, so subsequent ticks observe + // completion as a no-op until Recheck or Remove clears the flag. + var completed []completedFor + // Rates come from the centralized sampler's immutable cache — this loop + // only reads, never mutates prevRates, so concurrent List() calls (one + // per connected user, back-to-back, every tick) all see identical rates. + rates := a.rateCache.Load() + a.pausedMu.RLock() + a.verifyMu.RLock() + for _, t := range ts { + id := TorrentID(t.InfoHash().HexString()) + var rate rateValue + if rates != nil { + rate = (*rates)[id] + } + snap := snapshotFor(t, rate, a.paused[id], a.queuePos[id], a.forceStart[id], a.sequential[id], a.scheduledPause[id], a.verifying[id], a.filesMissing[id]) + out = append(out, snap) + if snap.Completed && a.snapshotStore != nil { + completed = append(completed, completedFor{id: id, t: t}) + } + } + a.verifyMu.RUnlock() + a.pausedMu.RUnlock() + for _, c := range completed { + a.spawnSnapshotSave(c.id, c.t) + } + return out +} + +// snapshotSaveRetryBackoff is how long spawnSnapshotSave waits after a failed +// snapshot write before trying that torrent again. +const snapshotSaveRetryBackoff = 30 * time.Second + +// spawnSnapshotSave runs saveSnapshotIfComplete on a goroutine, at most one +// in flight per torrent. List() used to `go saveSnapshotIfComplete(...)` for +// every completed torrent on every tick; snapshotSaved is only set on a +// successful write, so a persistently failing snapshot store spawned N +// goroutines several times per second forever, each taking the client lock. +// Failures back off for snapshotSaveRetryBackoff before the next attempt. +func (a *AnacrolixBackend) spawnSnapshotSave(id TorrentID, t *torrent.Torrent) { + a.snapshotMu.Lock() + if a.snapshotSaved[id] || a.snapshotInflight[id] || time.Now().Before(a.snapshotRetryAt[id]) { + a.snapshotMu.Unlock() + return + } + a.snapshotInflight[id] = true + a.snapshotMu.Unlock() + go func() { + a.saveSnapshotIfComplete(id, t) + a.snapshotMu.Lock() + delete(a.snapshotInflight, id) + if a.snapshotSaved[id] { + delete(a.snapshotRetryAt, id) + } else { + a.snapshotRetryAt[id] = time.Now().Add(snapshotSaveRetryBackoff) + } + a.snapshotMu.Unlock() + }() +} + +type completedFor struct { + id TorrentID + t *torrent.Torrent +} + +func (a *AnacrolixBackend) Snapshot(id TorrentID) (Snapshot, error) { + t, ok := a.find(id) + if !ok { + return Snapshot{}, errors.New("not found") + } + a.pausedMu.RLock() + paused := a.paused[id] + queuePos := a.queuePos[id] + forceStart := a.forceStart[id] + sequential := a.sequential[id] + queued := a.scheduledPause[id] + a.pausedMu.RUnlock() + a.verifyMu.RLock() + verifying := a.verifying[id] + filesMissing := a.filesMissing[id] + a.verifyMu.RUnlock() + snap := snapshotFor(t, a.rateFor(id), paused, queuePos, forceStart, sequential, queued, verifying, filesMissing) + return snap, nil +} + +func (a *AnacrolixBackend) SetFilePriorities(id TorrentID, prios map[int]Priority) error { + t, ok := a.find(id) + if !ok { + return errors.New("not found") + } + files := t.Files() + for idx, p := range prios { + if idx < 0 || idx >= len(files) { + continue + } + files[idx].SetPriority(prioToAnacrolix(p)) + } + return nil +} + +func prioToAnacrolix(p Priority) anacrolix_types.PiecePriority { + switch p { + case PrioritySkip: + return anacrolix_types.PiecePriorityNone + case PriorityHigh: + return anacrolix_types.PiecePriorityHigh + case PriorityMax: + return anacrolix_types.PiecePriorityNow + } + return anacrolix_types.PiecePriorityNormal +} + diff --git a/backend/engine/anacrolix_trackers.go b/backend/engine/anacrolix_trackers.go new file mode 100644 index 0000000..3e14613 --- /dev/null +++ b/backend/engine/anacrolix_trackers.go @@ -0,0 +1,169 @@ +package engine + +import ( + "errors" + + "github.com/anacrolix/torrent" + anacrolix_types "github.com/anacrolix/torrent/types" +) + +func (a *AnacrolixBackend) AddTracker(id TorrentID, url string) error { + t, ok := a.find(id) + if !ok { + return errors.New("not found") + } + t.AddTrackers([][]string{{url}}) + return nil +} + +// RemoveTracker removes a single tracker URL from an existing torrent. +// anacrolix v1.61 exposes ModifyTrackers which replaces the entire announce +// list atomically — it stops existing announcers and rebuilds from the +// provided list. We reconstruct the announce list without the target URL and +// pass it to ModifyTrackers. The call is a no-op if the URL doesn't appear. +func (a *AnacrolixBackend) RemoveTracker(id TorrentID, url string) error { + t, ok := a.find(id) + if !ok { + return errors.New("not found") + } + mi := t.Metainfo() + // Build filtered announce list, excluding the target URL from every tier. + var newList [][]string + for _, tier := range mi.AnnounceList { + var newTier []string + for _, u := range tier { + if u != url { + newTier = append(newTier, u) + } + } + if len(newTier) > 0 { + newList = append(newList, newTier) + } + } + // Also handle the legacy single-announce field by treating it as a tier. + if mi.Announce != "" && mi.Announce != url { + // Only add it if it isn't already covered by AnnounceList to avoid dups. + covered := false + for _, tier := range newList { + for _, u := range tier { + if u == mi.Announce { + covered = true + break + } + } + } + if !covered { + newList = append([][]string{{mi.Announce}}, newList...) + } + } + // ModifyTrackers stops all existing tracker goroutines and replaces the + // announce list atomically. This is the correct removal mechanism in + // anacrolix v1.61. + t.ModifyTrackers(newList) + return nil +} + +func (a *AnacrolixBackend) SetQueuePosition(id TorrentID, pos int) { + a.pausedMu.Lock() + a.queuePos[id] = pos + a.pausedMu.Unlock() +} + +func (a *AnacrolixBackend) SetForceStart(id TorrentID, force bool) { + a.pausedMu.Lock() + a.forceStart[id] = force + a.pausedMu.Unlock() +} + +// SetSequential enables or disables sequential piece download for a torrent. +// When enabled, pieces are assigned descending priorities so that earlier +// pieces have higher urgency — anacrolix then requests them in index order, +// allowing users to preview/stream media while the download is in progress. +// When disabled, piece priorities are reset to Normal (rarest-first default). +// +// The gradient uses all non-None priority levels (Normal..Now, values 1–5). +// Pieces are divided evenly into up to 5 buckets; the first bucket gets the +// highest priority (PiecePriorityNow) and the last gets PiecePriorityNormal. +// This ensures that even with a large number of pieces the request strategy +// strongly prefers lower-indexed pieces for the whole file while still allowing +// anacrolix's internal tie-breaking to handle unavailable / already-complete +// pieces gracefully. +func (a *AnacrolixBackend) SetSequential(id TorrentID, enabled bool) { + a.pausedMu.Lock() + a.sequential[id] = enabled + a.pausedMu.Unlock() + t, ok := a.find(id) + if !ok { + return + } + applySequentialPriorities(t, enabled) +} + +// applySequentialPriorities adjusts per-piece priorities on t to implement +// sequential (in-order) downloading. It must be called after GotInfo (piece +// count is valid). Safe to call from any goroutine — Piece.SetPriority takes +// the client lock internally. +func applySequentialPriorities(t *torrent.Torrent, sequential bool) { + n := t.NumPieces() + if n == 0 { + return + } + if !sequential { + // Reset to Normal so the default rarest-first strategy takes over. + for i := 0; i < n; i++ { + t.Piece(i).SetPriority(anacrolix_types.PiecePriorityNormal) + } + return + } + // Divide pieces into up to 5 buckets mapped to priority levels + // PiecePriorityNow (5) → PiecePriorityNormal (1). + const levels = 5 // PiecePriorityNow=5 down to PiecePriorityNormal=1 + for i := 0; i < n; i++ { + // bucket: 0 = earliest (highest priority), levels-1 = latest (lowest) + bucket := (i * levels) / n + if bucket >= levels { + bucket = levels - 1 + } + // prio: levels (Now) for bucket 0, 1 (Normal) for bucket levels-1 + prio := anacrolix_types.PiecePriority(levels - bucket) + t.Piece(i).SetPriority(prio) + } +} + +// ScheduledPause is the scheduler's pause channel — independent from the +// user's manual Pause. It uses the same SetMaxEstablishedConns(0/cap) trick +// the manual Pause uses, but writes only the scheduledPause map flag so +// snapshots can distinguish "user-paused" from "queue-held". +// +// CRITICAL: ScheduledPause(id, false) MUST refuse to re-enable a +// user-paused torrent. The scheduler reads a List() snapshot once per +// tick; if the user clicks Pause between the List() read and the +// per-id apply loop, the scheduler will try to ScheduledPause(false) +// the now-paused torrent. Without this guard, SetMaxEstablishedConns(80) +// fires and peers reconnect to a "paused" torrent. Pause's +// DisallowDataDownload prevents new piece requests but uploads + half- +// open conns can still leak through — and the UX bug ("paused torrent +// is still downloading") is exactly this race. +func (a *AnacrolixBackend) ScheduledPause(id TorrentID, paused bool) { + t, ok := a.find(id) + if !ok { + return + } + if !paused { + // Re-enable path — refuse if the user has paused this torrent. + a.pausedMu.RLock() + userPaused := a.paused[id] + a.pausedMu.RUnlock() + if userPaused { + return + } + } + if paused { + t.SetMaxEstablishedConns(0) + } else { + t.SetMaxEstablishedConns(int(a.maxConnsPerTorrent.Load())) + } + a.pausedMu.Lock() + a.scheduledPause[id] = paused + a.pausedMu.Unlock() +}