diff --git a/internal/coverart/embedded.go b/internal/coverart/embedded.go index f49ef1a9..fb3964ab 100644 --- a/internal/coverart/embedded.go +++ b/internal/coverart/embedded.go @@ -5,7 +5,7 @@ import ( "fmt" "os" - "github.com/dhowden/tag" + "git.fabledsword.com/bvandeusen/minstrel/internal/tagread" ) // ErrNoEmbeddedArt indicates the audio file has no embedded picture. @@ -33,7 +33,7 @@ func ExtractEmbeddedAlbumArt(path string) ([]byte, error) { } defer func() { _ = f.Close() }() - meta, err := tag.ReadFrom(f) + meta, err := tagread.ReadFrom(f) if err != nil { return nil, fmt.Errorf("tag read: %w", err) } diff --git a/internal/library/id3v2genre.go b/internal/library/id3v2genre.go index 49de328d..69dc2588 100644 --- a/internal/library/id3v2genre.go +++ b/internal/library/id3v2genre.go @@ -6,6 +6,8 @@ import ( "io" "strings" "unicode/utf16" + + "git.fabledsword.com/bvandeusen/minstrel/internal/tagread" ) // Why this file exists at all: github.com/dhowden/tag reads every other field @@ -27,12 +29,6 @@ import ( // So the TCON frame is parsed here directly. Only the genre frame — everything // else still comes from dhowden/tag, which handles it fine. -// maxID3TagSize caps how much of a file we'll buffer looking for TCON. Real -// tags are kilobytes; embedded cover art pushes them to a few megabytes. The -// cap exists so a corrupt or hostile size field can't make the scanner -// allocate wildly on a file it was only asked to index. -const maxID3TagSize = 16 << 20 - // errNoGenreFrame means the file carries no readable genre frame. It is an // expected outcome (plenty of files are untagged), not a failure. var errNoGenreFrame = errors.New("library: no ID3v2 genre frame") @@ -62,8 +58,8 @@ func readID3v2GenreValues(rs io.ReadSeeker) ([]string, error) { return nil, errNoGenreFrame } tagFlags := hdr[5] - size := syncsafeInt(hdr[6:10]) - if size <= 0 || size > maxID3TagSize { + size := tagread.SyncsafeInt(hdr[6:10]) + if size <= 0 || size > tagread.MaxTagSize { return nil, errNoGenreFrame } @@ -83,11 +79,11 @@ func readID3v2GenreValues(rs io.ReadSeeker) ([]string, error) { // Whole-tag unsynchronisation (2.2/2.3). 2.4 moved this per-frame, but // some writers still set it at tag level, and undoing it twice is // harmless: after the first pass no 0xFF 0x00 pairs remain. - body = undoUnsynchronisation(body) + body = tagread.UndoUnsynchronisation(body) } if major >= 3 && tagFlags&0x40 != 0 { var ok bool - if body, ok = skipExtendedHeader(body, major); !ok { + if body, ok = tagread.SkipExtendedHeader(body, major); !ok { return nil, errNoGenreFrame } } @@ -99,7 +95,7 @@ func readID3v2GenreValues(rs io.ReadSeeker) ([]string, error) { func findGenreFrame(body []byte, major byte) ([]string, error) { // 2.2 frames: 3-byte id + 3-byte size, no flags. 2.3/2.4: 4-byte id + // 4-byte size + 2-byte flags. The size field is the other difference that - // matters — see frameSize. + // matters — see tagread.FrameSize. idLen, sizeLen, flagLen := 4, 4, 2 wantID := "TCON" if major == 2 { @@ -115,7 +111,7 @@ func findGenreFrame(body []byte, major byte) ([]string, error) { if body[off] == 0 { break } - size := frameSize(body[off+idLen:off+idLen+sizeLen], major) + size := tagread.FrameSize(body[off+idLen:off+idLen+sizeLen], major) if size <= 0 || off+hdrLen+size > len(body) { // Bogus length — we can't trust any offset past this point. break @@ -136,25 +132,6 @@ func findGenreFrame(body []byte, major byte) ([]string, error) { return nil, errNoGenreFrame } -// frameSize decodes a frame's length field. 2.4 made it syncsafe (7 bits per -// byte); 2.2 and 2.3 are plain big-endian. Reading a 2.3 size as syncsafe (or -// the reverse) yields a plausible-looking wrong offset rather than an obvious -// error, which is exactly how frame-walking bugs go unnoticed. -func frameSize(b []byte, major byte) int { - switch major { - case 2: - return int(b[0])<<16 | int(b[1])<<8 | int(b[2]) - case 3: - n := binary.BigEndian.Uint32(b) - if n > maxID3TagSize { - return -1 - } - return int(n) - default: - return syncsafeInt(b) - } -} - // frameData strips per-frame wrappers and reports whether the payload is // readable at all. Compressed and encrypted frames are not (we have no // zlib-in-frame or key handling, and neither is meaningful for a genre tag). @@ -192,7 +169,7 @@ func frameData(data []byte, major byte, flags uint16) ([]byte, bool) { data = data[4:] // syncsafe expanded size; we don't need it } if flags&0x0002 != 0 { - data = undoUnsynchronisation(data) + data = tagread.UndoUnsynchronisation(data) } return data, true } @@ -333,56 +310,3 @@ func decodeUTF16(b []byte, bigEndian bool) string { } return string(utf16.Decode(units)) } - -// skipExtendedHeader advances past the optional extended header. The two -// versions disagree about whether the size field counts itself, which is worth -// spelling out because getting it wrong offsets the entire frame list by four -// bytes and makes every frame id look like padding. -func skipExtendedHeader(body []byte, major byte) ([]byte, bool) { - if len(body) < 4 { - return nil, false - } - if major == 3 { - // 2.3: size EXCLUDES the four size bytes themselves. - size := int(binary.BigEndian.Uint32(body[0:4])) - if size < 0 || 4+size > len(body) { - return nil, false - } - return body[4+size:], true - } - // 2.4: syncsafe size INCLUDING the size bytes. - size := syncsafeInt(body[0:4]) - if size < 4 || size > len(body) { - return nil, false - } - return body[size:], true -} - -// syncsafeInt decodes a 4-byte synchsafe integer (7 significant bits per byte). -func syncsafeInt(b []byte) int { - if len(b) < 4 { - return -1 - } - // A set high bit means this isn't a valid synchsafe integer. Some writers - // emit a plain big-endian size here; refusing is safer than silently - // dropping bits and walking to a wrong offset. - for _, c := range b[:4] { - if c&0x80 != 0 { - return -1 - } - } - return int(b[0])<<21 | int(b[1])<<14 | int(b[2])<<7 | int(b[3]) -} - -// undoUnsynchronisation collapses the 0xFF 0x00 pairs that unsynchronisation -// inserts to stop a tag from looking like an MPEG frame sync. -func undoUnsynchronisation(b []byte) []byte { - out := make([]byte, 0, len(b)) - for i := 0; i < len(b); i++ { - out = append(out, b[i]) - if b[i] == 0xFF && i+1 < len(b) && b[i+1] == 0x00 { - i++ - } - } - return out -} diff --git a/internal/library/mbidbackfill.go b/internal/library/mbidbackfill.go index 569b179c..0ba2744f 100644 --- a/internal/library/mbidbackfill.go +++ b/internal/library/mbidbackfill.go @@ -6,11 +6,11 @@ import ( "log/slog" "os" - "github.com/dhowden/tag" "github.com/jackc/pgx/v5/pgxpool" "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/tagread" ) // BackfillMBIDsResult tallies what the one-shot worker did. @@ -147,7 +147,7 @@ func readMBIDsForFile(path string, logger *slog.Logger) (albumMBID, artistMBID s } defer func() { _ = f.Close() }() - meta, err := tag.ReadFrom(f) + meta, err := tagread.ReadFrom(f) if err != nil { logger.Warn("mbid backfill: tag read failed", "path", path, "err", err) return "", "" @@ -241,7 +241,7 @@ func readRecordingMBIDForFile(path string, logger *slog.Logger) string { } defer func() { _ = f.Close() }() - meta, err := tag.ReadFrom(f) + meta, err := tagread.ReadFrom(f) if err != nil { logger.Warn("track mbid backfill: tag read failed", "path", path, "err", err) return "" diff --git a/internal/library/scanner.go b/internal/library/scanner.go index c23e0a23..71253614 100644 --- a/internal/library/scanner.go +++ b/internal/library/scanner.go @@ -15,7 +15,6 @@ import ( "sync" "time" - "github.com/dhowden/tag" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" @@ -23,6 +22,7 @@ import ( "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" syncpkg "git.fabledsword.com/bvandeusen/minstrel/internal/sync" + "git.fabledsword.com/bvandeusen/minstrel/internal/tagread" ) // audioExtensions is the set the scanner indexes. Keep in sync with @@ -368,7 +368,7 @@ func (s *Scanner) scanFile( } defer func() { _ = f.Close() }() - meta, err := tag.ReadFrom(f) + meta, err := tagread.ReadFrom(f) if err != nil { return pgtype.UUID{}, false, fmt.Errorf("tag read: %w", err) } diff --git a/internal/library/vorbisgenre.go b/internal/library/vorbisgenre.go index e216c58b..ba9bb42a 100644 --- a/internal/library/vorbisgenre.go +++ b/internal/library/vorbisgenre.go @@ -7,6 +7,8 @@ import ( "errors" "io" "strings" + + "git.fabledsword.com/bvandeusen/minstrel/internal/tagread" ) // Why this file exists: Vorbis comments (FLAC, Ogg Vorbis, Opus) say a field @@ -59,7 +61,7 @@ func readFLACValues(rs io.ReadSeeker, key string) ([]string, error) { if _, err := io.ReadFull(rs, rest[:]); err != nil { return nil, errNoGenreFrame } - size := syncsafeInt(rest[2:6]) + size := tagread.SyncsafeInt(rest[2:6]) if size < 0 { return nil, errNoGenreFrame } diff --git a/internal/subsonic/lyrics.go b/internal/subsonic/lyrics.go index 8755fa18..5c0392c1 100644 --- a/internal/subsonic/lyrics.go +++ b/internal/subsonic/lyrics.go @@ -11,11 +11,11 @@ import ( "strconv" "strings" - "github.com/dhowden/tag" "github.com/jackc/pgx/v5" "git.fabledsword.com/bvandeusen/minstrel/internal/db" "git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq" + "git.fabledsword.com/bvandeusen/minstrel/internal/tagread" ) // Lyrics are read from the music files when an app asks, not stored: a .lrc @@ -97,7 +97,7 @@ func readLyrics(path string) (songLyrics, bool) { return songLyrics{}, false } defer func() { _ = f.Close() }() - meta, err := tag.ReadFrom(f) + meta, err := tagread.ReadFrom(f) if err != nil { return songLyrics{}, false } diff --git a/internal/tagread/id3v2.go b/internal/tagread/id3v2.go new file mode 100644 index 00000000..a96b565d --- /dev/null +++ b/internal/tagread/id3v2.go @@ -0,0 +1,84 @@ +package tagread + +import "encoding/binary" + +// The ID3v2 primitives both tag readers share: this package's repair pass +// and the library's own multi-value genre reader (library/id3v2genre.go). + +// MaxTagSize caps how much of a file we'll buffer while reading a tag. Real +// tags are kilobytes; embedded cover art pushes them to a few megabytes. The +// cap exists so a corrupt or hostile size field can't make the scanner +// allocate wildly on a file it was only asked to index. +const MaxTagSize = 16 << 20 + +// SyncsafeInt decodes a 4-byte synchsafe integer (7 significant bits per byte). +func SyncsafeInt(b []byte) int { + if len(b) < 4 { + return -1 + } + // A set high bit means this isn't a valid synchsafe integer. Some writers + // emit a plain big-endian size here; refusing is safer than silently + // dropping bits and walking to a wrong offset. + for _, c := range b[:4] { + if c&0x80 != 0 { + return -1 + } + } + return int(b[0])<<21 | int(b[1])<<14 | int(b[2])<<7 | int(b[3]) +} + +// FrameSize decodes a frame's length field. 2.4 made it syncsafe (7 bits per +// byte); 2.2 and 2.3 are plain big-endian. Reading a 2.3 size as syncsafe (or +// the reverse) yields a plausible-looking wrong offset rather than an obvious +// error, which is exactly how frame-walking bugs go unnoticed. +func FrameSize(b []byte, major byte) int { + switch major { + case 2: + return int(b[0])<<16 | int(b[1])<<8 | int(b[2]) + case 3: + n := binary.BigEndian.Uint32(b) + if n > MaxTagSize { + return -1 + } + return int(n) + default: + return SyncsafeInt(b) + } +} + +// SkipExtendedHeader advances past the optional extended header. The two +// versions disagree about whether the size field counts itself, which is worth +// spelling out because getting it wrong offsets the entire frame list by four +// bytes and makes every frame id look like padding. +func SkipExtendedHeader(body []byte, major byte) ([]byte, bool) { + if len(body) < 4 { + return nil, false + } + if major == 3 { + // 2.3: size EXCLUDES the four size bytes themselves. + size := int(binary.BigEndian.Uint32(body[0:4])) + if size < 0 || 4+size > len(body) { + return nil, false + } + return body[4+size:], true + } + // 2.4: syncsafe size INCLUDING the size bytes. + size := SyncsafeInt(body[0:4]) + if size < 4 || size > len(body) { + return nil, false + } + return body[size:], true +} + +// UndoUnsynchronisation collapses the 0xFF 0x00 pairs that unsynchronisation +// inserts to stop a tag from looking like an MPEG frame sync. +func UndoUnsynchronisation(b []byte) []byte { + out := make([]byte, 0, len(b)) + for i := 0; i < len(b); i++ { + out = append(out, b[i]) + if b[i] == 0xFF && i+1 < len(b) && b[i+1] == 0x00 { + i++ + } + } + return out +} diff --git a/internal/tagread/tagread.go b/internal/tagread/tagread.go new file mode 100644 index 00000000..4f8afdaa --- /dev/null +++ b/internal/tagread/tagread.go @@ -0,0 +1,147 @@ +// Package tagread reads a music file's tags. It is github.com/dhowden/tag +// with one repair: dhowden/tag refuses a whole file when a single UTF-16 text +// frame holds an odd number of bytes, and some taggers end a UTF-16 frame +// with one zero byte too many (a two-byte terminator followed by a stray +// single one). Those files then read as having no tags at all, and the +// scanner skipped them. When dhowden/tag fails, ReadFrom rebuilds the ID3v2 +// tag in memory without the stray byte and reads it again. +package tagread + +import ( + "bytes" + "encoding/binary" + "io" + + "github.com/dhowden/tag" +) + +// ReadFrom reads rs's tags, as tag.ReadFrom does. When that fails on an ID3v2 +// tag with a stray trailing zero in a UTF-16 text frame, it answers from a +// copy of the tag with that byte removed. Any other failure returns +// tag.ReadFrom's own error. +func ReadFrom(rs io.ReadSeeker) (tag.Metadata, error) { + start, err := rs.Seek(0, io.SeekCurrent) + if err != nil { + return nil, err + } + meta, err := tag.ReadFrom(rs) + if err == nil { + return meta, nil + } + if _, serr := rs.Seek(start, io.SeekStart); serr != nil { + return nil, err + } + fixed, ok := repairID3v2(rs) + if !ok { + return nil, err + } + repaired, rerr := tag.ReadFrom(bytes.NewReader(fixed)) + if rerr != nil { + return nil, err + } + return repaired, nil +} + +// repairID3v2 reads the ID3v2 tag at rs's position and returns it rebuilt +// with each stray trailing zero trimmed (trimStrayNul). It reports false +// when there is no ID3v2.3 or 2.4 tag, the tag can't be walked safely, or +// nothing needed trimming, so the caller keeps the original error. +// +// Only the tag is returned: dhowden/tag reads an ID3v2 file's tags without +// touching the audio after them. +func repairID3v2(rs io.Reader) ([]byte, bool) { + var hdr [10]byte + if _, err := io.ReadFull(rs, hdr[:]); err != nil || string(hdr[0:3]) != "ID3" { + return nil, false + } + major, flags := hdr[3], hdr[5] + // A whole-tag unsynchronised tag would have to be re-synchronised after + // the edit; 2.2 has a different frame layout. Neither is worth the risk + // for a repair. + if (major != 3 && major != 4) || flags&0x80 != 0 { + return nil, false + } + size := SyncsafeInt(hdr[6:10]) + if size <= 0 || size > MaxTagSize { + return nil, false + } + body := make([]byte, size) + if _, err := io.ReadFull(rs, body); err != nil { + return nil, false + } + frames := body + if flags&0x40 != 0 { + var ok bool + if frames, ok = SkipExtendedHeader(body, major); !ok { + return nil, false + } + } + + out := make([]byte, 0, len(body)) + out = append(out, body[:len(body)-len(frames)]...) // the extended header, unchanged + changed := false + off := 0 + for off+10 <= len(frames) && frames[off] != 0 { + n := FrameSize(frames[off+4:off+8], major) + if n < 0 || off+10+n > len(frames) { + return nil, false + } + id := string(frames[off : off+4]) + frameFlags := frames[off+8 : off+10] + data := frames[off+10 : off+10+n] + if frameFlags[0] == 0 && frameFlags[1] == 0 { + if trimmed, ok := trimStrayNul(id, data); ok { + data, changed = trimmed, true + } + } + out = append(out, frames[off:off+4]...) + out = appendFrameSize(out, len(data), major) + out = append(out, frameFlags...) + out = append(out, data...) + off += 10 + n + } + if !changed { + return nil, false + } + out = append(out, frames[off:]...) // padding + + tagBytes := make([]byte, 0, 10+len(out)) + tagBytes = append(tagBytes, hdr[:6]...) + tagBytes = appendSyncsafe(tagBytes, len(out)) + return append(tagBytes, out...), true +} + +// trimStrayNul drops the last byte of a UTF-16 text frame whose text runs +// to an odd number of bytes and ends in zero: the stray terminator. A UTF-16 +// frame of odd length that ends any other way is left alone. +func trimStrayNul(id string, data []byte) ([]byte, bool) { + textStart := 1 // the encoding byte + switch { + case id == "COMM" || id == "USLT": + textStart = 4 // encoding, then a three-letter language + case id[0] != 'T': + return nil, false + } + if len(data) <= textStart || (data[0] != 1 && data[0] != 2) { + return nil, false + } + if (len(data)-textStart)%2 == 0 || data[len(data)-1] != 0 { + return nil, false + } + return data[:len(data)-1], true +} + +// appendFrameSize writes a frame's length field: syncsafe in 2.4, plain +// big-endian in 2.3 (FrameSize reads both). +func appendFrameSize(b []byte, n int, major byte) []byte { + if major == 4 { + return appendSyncsafe(b, n) + } + return binary.BigEndian.AppendUint32(b, uint32(n)) +} + +// appendSyncsafe writes n as a 4-byte syncsafe integer (SyncsafeInt reads +// it). n is at most MaxTagSize, well inside the 28 bits it can hold. +func appendSyncsafe(b []byte, n int) []byte { + return append(b, byte(n>>21&0x7f), byte(n>>14&0x7f), byte(n>>7&0x7f), byte(n&0x7f)) +} diff --git a/internal/tagread/tagread_test.go b/internal/tagread/tagread_test.go new file mode 100644 index 00000000..8bf0e135 --- /dev/null +++ b/internal/tagread/tagread_test.go @@ -0,0 +1,82 @@ +package tagread + +import ( + "bytes" + "encoding/binary" + "testing" + + "github.com/dhowden/tag" +) + +// frame builds one ID3v2 frame for the given major version. +func frame(major byte, id string, data []byte) []byte { + b := []byte(id) + b = appendFrameSize(b, len(data), major) + b = append(b, 0, 0) + return append(b, data...) +} + +// id3 wraps frames in an ID3v2 header and ten bytes of padding. +func id3(major byte, frames ...[]byte) []byte { + body := bytes.Join(frames, nil) + body = append(body, make([]byte, 10)...) + b := []byte{'I', 'D', '3', major, 0, 0} + b = appendSyncsafe(b, len(body)) + return append(b, body...) +} + +// utf16BE encodes s as encoding-1 frame data: the encoding byte, a +// big-endian BOM, the text, and the two-byte terminator. +func utf16BE(s string) []byte { + b := []byte{1, 0xFE, 0xFF} + for _, r := range s { + b = binary.BigEndian.AppendUint16(b, uint16(r)) + } + return append(b, 0, 0) +} + +func utf8Text(s string) []byte { return append(append([]byte{3}, s...), 0) } + +// The frames a real file in the library carried: a UTF-16 genre ending in +// three zero bytes, which dhowden/tag rejects for the whole file. +func TestReadFrom_TrimsAStrayZeroAfterAUTF16Frame(t *testing.T) { + for _, major := range []byte{3, 4} { + strayGenre := append(utf16BE("Punk Rock"), 0) + file := id3(major, + frame(major, "TCON", strayGenre), + frame(major, "TIT2", utf8Text("A Million Miles")), + frame(major, "TPE1", utf8Text("Goldfinger")), + ) + if _, err := tag.ReadFrom(bytes.NewReader(file)); err == nil { + t.Fatalf("v2.%d: dhowden/tag read the fixture; it no longer reproduces the fault", major) + } + meta, err := ReadFrom(bytes.NewReader(file)) + if err != nil { + t.Fatalf("v2.%d: ReadFrom: %v", major, err) + } + if meta.Title() != "A Million Miles" || meta.Artist() != "Goldfinger" || meta.Genre() != "Punk Rock" { + t.Fatalf("v2.%d: title %q artist %q genre %q", major, meta.Title(), meta.Artist(), meta.Genre()) + } + } +} + +func TestReadFrom_LeavesOtherFailuresAlone(t *testing.T) { + // Odd-length UTF-16 that doesn't end in zero is not the stray + // terminator, so it is not guessed at. + odd := append(utf16BE("Rock"), 'x') + file := id3(4, frame(4, "TCON", odd)) + if _, err := ReadFrom(bytes.NewReader(file)); err == nil { + t.Fatal("ReadFrom read a frame it should not have repaired") + } + if _, err := ReadFrom(bytes.NewReader([]byte("not a music file at all"))); err == nil { + t.Fatal("ReadFrom read a file with no tags") + } +} + +func TestReadFrom_AWellFormedTagIsReadAsIs(t *testing.T) { + file := id3(4, frame(4, "TCON", utf16BE("Ska")), frame(4, "TIT2", utf8Text("Beacon"))) + meta, err := ReadFrom(bytes.NewReader(file)) + if err != nil || meta.Genre() != "Ska" || meta.Title() != "Beacon" { + t.Fatalf("meta %v err %v", meta, err) + } +}