fix(library): a UTF-16 tag frame with a stray trailing zero no longer hides the whole file (#8060)
release / go (push) Successful in 2m4s
release / web (push) Successful in 1m21s
release / govulncheck (push) Successful in 20s
release / integration (push) Successful in 4m9s
release / android (push) Successful in 4m28s
release / Build signed APK (push) Successful in 4m56s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 14s
release / Verify release artifacts (tag releases only) (push) Skipped

Some taggers end a UTF-16 text frame with a two-byte terminator and then
one more zero byte, so the frame holds an odd number of bytes.
dhowden/tag refuses the whole tag when it meets one, and the scanner
then skipped the file: 61 tracks on dev (whole albums from one tagger,
with a genre or year frame written this way) never reached the library.

internal/tagread.ReadFrom reads with dhowden/tag first. When that fails
on an ID3v2.3/2.4 tag, it rebuilds the tag in memory with the stray
byte trimmed from each such frame and reads it again. Anything else
still fails with dhowden/tag's own error. The scanner, both MBID
backfills, embedded cover art and Subsonic lyrics all read through it.

The ID3v2 primitives (syncsafe and frame sizes, the extended header,
unsynchronisation) move from library/id3v2genre.go into tagread, so the
genre reader and the repair share one copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 14:05:55 -05:00
co-authored by Claude Opus 5.5
parent 17a9052acb
commit c9e058b3c9
9 changed files with 334 additions and 95 deletions
+84
View File
@@ -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
}
+147
View File
@@ -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))
}
+82
View File
@@ -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)
}
}