mirror of
https://git.sr.ht/~joren/streamrip-go
synced 2026-10-16 13:57:25 +02:00
Six correctness bugs that the existing tests could not see. The suite passed and `go test -race` was clean throughout, because nothing exercised concurrent token refresh, shared-folder artwork, or hostile metadata. main(): extract run() int main() was a single 1196-line function that registered 20 `defer mainApp.Close()` handlers and then called os.Exit 150 times, so none of them ever ran. Close() is what closes the SQLite handle, flushes the progress bars and removes the artwork temp dirs, so every failed rip leaked temp directories. main() is now a wrapper around run() int and the command bodies return exit codes. Ctrl-C now stops a rip ctx was threaded everywhere but never checked: zero ctx.Err()/ctx.Done() in internal/app and internal/download. Cancellation left Rip() iterating the whole remaining queue, and the retry ladder retried on a dead context, so one Ctrl-C cost three doomed attempts per remaining track. Adds checks to the dispatch loops, the worker-spawn loops and the retry ladder, and routes the MarkFailed/MarkDownloaded bookkeeping through a detached context so the records survive cancellation. Convert and TagFLAC now take a ctx and use exec.CommandContext, so a stalled ffmpeg/ffprobe no longer outlives Ctrl-C. Config race Provider token refresh mutated the shared *config.Config and called SaveFile() from inside download workers with no lock, racing the struct fields and issuing concurrent os.WriteFile against one path. Adds a mutex to config.Config plus UpdateTokens(), and routes all five refresh sites through it. Each provider client gets an authMu guarding loggedIn and its login/refresh path; beatport needed it most, since ensureToken is reached from apiRequest. Artwork cover race artwork.Prepare was check-then-write on a path shared by every worker in a playlist rip. Two workers both saw a missing cover.jpg, both created it, and the loser's cleanup deleted the winner's finished file. Adds a per-folder lock and downloads via a unique temp file + rename. The regression test fails against the old code with 15 of 16 workers getting no cover. Path traversal from remote metadata naming.CleanName stripped <>:"/\|?* and control chars but not "." , so a title of ".." survived into filepath.Join and escaped the download root. SoundCloud and Tidal playlist names are user-generated. Now rejects "." and "..", trims trailing dots, handles Windows device names, adds DEL to the invalid set and caps components at 255 bytes without splitting a rune. app.go gains safeJoin as a second line of defence. Credentials no longer world-readable The config holds plaintext provider passwords, Deezer ARL cookies and OAuth tokens and was written 0o644. Now 0o600, with 0o700 directories, and an existing 0o644 file is tightened on write. Also: deletes the 9 duplicated *-rip-smoke dev commands (~300 lines fully subsumed by `rip id`) and the unreachable second dev-help arm; registers image/png so PNG covers are downscaled instead of being silently saved as cover.jpg containing PNG bytes; adds the missing .gitignore, which was keeping a 21MB build artifact one `git add -A` away from the repo. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
130 lines
3.4 KiB
Go
130 lines
3.4 KiB
Go
package naming
|
|
|
|
import (
|
|
"fmt"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"unicode"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
type Config struct {
|
|
RestrictCharacters bool
|
|
TruncateTo int
|
|
}
|
|
|
|
var tokenRe = regexp.MustCompile(`\{([a-z_]+)(?::0?(\d+))?\}`)
|
|
var invalidPathRe = regexp.MustCompile(`[<>:"/\\|?*\x00-\x1F\x7F]`)
|
|
|
|
func FormatTemplate(template string, values map[string]string) string {
|
|
return tokenRe.ReplaceAllStringFunc(template, func(m string) string {
|
|
groups := tokenRe.FindStringSubmatch(m)
|
|
if len(groups) < 2 {
|
|
return m
|
|
}
|
|
key := groups[1]
|
|
val := values[key]
|
|
if len(groups) >= 3 && groups[2] != "" {
|
|
if n, err := strconv.Atoi(val); err == nil {
|
|
if width, widthErr := strconv.Atoi(groups[2]); widthErr == nil {
|
|
return fmt.Sprintf("%0*d", width, n)
|
|
}
|
|
}
|
|
}
|
|
return val
|
|
})
|
|
}
|
|
|
|
// maxNameBytes is the per-component limit on ext4, APFS and most other modern
|
|
// filesystems. TruncateTo counts runes, so a 120-rune CJK title is ~360 bytes
|
|
// and would fail with ENAMETOOLONG without this second, byte-based cap.
|
|
const maxNameBytes = 255
|
|
|
|
// windowsReserved are device names that cannot be used as a path component on
|
|
// Windows, with or without an extension.
|
|
var windowsReserved = map[string]struct{}{
|
|
"CON": {}, "PRN": {}, "AUX": {}, "NUL": {},
|
|
"COM1": {}, "COM2": {}, "COM3": {}, "COM4": {}, "COM5": {},
|
|
"COM6": {}, "COM7": {}, "COM8": {}, "COM9": {},
|
|
"LPT1": {}, "LPT2": {}, "LPT3": {}, "LPT4": {}, "LPT5": {},
|
|
"LPT6": {}, "LPT7": {}, "LPT8": {}, "LPT9": {},
|
|
}
|
|
|
|
// CleanName turns a remote title into a single safe path component.
|
|
//
|
|
// Everything it receives is attacker-controlled: album, playlist and track
|
|
// titles come straight from provider APIs, and on SoundCloud and Tidal they are
|
|
// user-generated. The result is joined onto the download root by the caller, so
|
|
// it must never be "." or ".." (which would escape or collapse into the parent
|
|
// directory) and must never contain a separator.
|
|
func CleanName(in string, cfg Config) string {
|
|
s := strings.TrimSpace(in)
|
|
s = invalidPathRe.ReplaceAllString(s, "_")
|
|
if cfg.RestrictCharacters {
|
|
r := make([]rune, 0, len(s))
|
|
for _, ch := range s {
|
|
if ch >= 32 && ch <= 126 {
|
|
r = append(r, ch)
|
|
}
|
|
}
|
|
s = string(r)
|
|
}
|
|
if cfg.TruncateTo > 0 {
|
|
runes := []rune(s)
|
|
if len(runes) > cfg.TruncateTo {
|
|
s = string(runes[:cfg.TruncateTo])
|
|
}
|
|
}
|
|
s = truncateBytes(s, maxNameBytes)
|
|
|
|
// Trailing dots and spaces are stripped by Windows, which turns "foo." into
|
|
// "foo" and makes ".." survive as a traversal component.
|
|
s = strings.TrimRight(s, ". ")
|
|
s = strings.TrimSpace(s)
|
|
|
|
if s == "" || isAllDots(s) {
|
|
return "Unknown"
|
|
}
|
|
if _, bad := windowsReserved[strings.ToUpper(s)]; bad {
|
|
return s + "_"
|
|
}
|
|
return s
|
|
}
|
|
|
|
// truncateBytes shortens s to at most max bytes without splitting a rune.
|
|
func truncateBytes(s string, max int) string {
|
|
if len(s) <= max {
|
|
return s
|
|
}
|
|
cut := s[:max]
|
|
for len(cut) > 0 && !utf8.ValidString(cut) {
|
|
cut = cut[:len(cut)-1]
|
|
}
|
|
return cut
|
|
}
|
|
|
|
// isAllDots reports whether s consists only of "." characters, i.e. "." or
|
|
// ".." or any longer run that some filesystems also treat as relative.
|
|
func isAllDots(s string) bool {
|
|
for _, ch := range s {
|
|
if ch != '.' {
|
|
return false
|
|
}
|
|
}
|
|
return len(s) > 0
|
|
}
|
|
|
|
func YearFromDate(date string) string {
|
|
if len(date) >= 4 {
|
|
prefix := date[:4]
|
|
for _, ch := range prefix {
|
|
if !unicode.IsDigit(ch) {
|
|
return "Unknown"
|
|
}
|
|
}
|
|
return prefix
|
|
}
|
|
return "Unknown"
|
|
}
|