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 }