Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- Matroska: deeply nested SimpleTags no longer crash the process with a stack overflow (#150). `MatroskaFile.Read` parses SimpleTags up to 64 levels deep and keeps any deeper SimpleTag as its stored bytes, which a save writes back unchanged; a file with SimpleTags nested 100,000 deep used to end the process on open. A save that moves Cues already walks only the RFC 9559 §5.1.5 paths.
- Ogg Vorbis comment packets that run across pages without the continuation flag keep their comments, and a stream whose last audio page is cut off keeps its duration (#126). `missing_flag.ogg` from that issue now opens with its title, artist, album, genre, cover and 10.189 s duration. Its framing byte is 0x01: the comments were lost in page reassembly, not at the framing bit.
- The Vorbis comment framing bit is read as the spec defines it: the low bit of the first byte after the declared comment list ([v-comment.html](https://xiph.org/vorbis/doc/v-comment.html) steps 7-8, Vorbis I spec 5.2.1, bit order per 2.1.4). 0x01, 0x03, 0x81 and 0xFF are accepted, and padding after that byte is ignored. A framing byte of 0x00, any other byte with the low bit clear, or a packet that ends at the comment list is rejected, as in libvorbis and mutagen. All 60 Ogg Vorbis files in the test corpora use 0x01.
- Ogg Opus: OpusTags split across pages without the continuation flag keeps its tags (they were empty). When the last audio page is cut off, `MediaFile.Read` on a stream reports the duration instead of 0, for example `psycho4.opus` (244 s).
Expand Down
22 changes: 18 additions & 4 deletions src/TagLibSharp2/Matroska/MatroskaFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -875,7 +875,7 @@ static TagBlock ReadTag (ReadOnlySpan<byte> body)
if (element.Id == MatroskaIds.Targets)
ReadTargets (payload, block);
else if (element.Id == MatroskaIds.SimpleTag)
block.Tags.Add (ReadSimpleTag (payload));
block.Tags.Add (ReadSimpleTag (payload, 1));
offset = element.End;
}

Expand Down Expand Up @@ -937,7 +937,14 @@ static void NoteTargetUid (ReadOnlySpan<byte> payload, ref bool all, ref bool sp
specific = true;
}

static SimpleTag ReadSimpleTag (ReadOnlySpan<byte> body)
/// <summary>
/// The deepest <c>SimpleTag</c> nesting parsed into <see cref="SimpleTag.Children"/>. RFC 9559 §5.1.8.1.2
/// lets a SimpleTag nest without a limit, so the reader stops descending here and keeps each deeper
/// SimpleTag as its stored bytes, which a save writes back unchanged. No tag mapping reads that deep.
/// </summary>
internal const int MaxSimpleTagDepth = 64;

static SimpleTag ReadSimpleTag (ReadOnlySpan<byte> body, int depth)
{
var name = string.Empty;
string? text = null;
Expand All @@ -946,6 +953,7 @@ static SimpleTag ReadSimpleTag (ReadOnlySpan<byte> body)
byte[]? binary = null;
var isDefault = true;
var children = new List<SimpleTag> ();
List<byte[]>? kept = null;
var offset = 0;
while (offset < body.Length) {
if (!EbmlReader.TryRead (body, offset, body.Length, out var element) || element.UnknownSize)
Expand All @@ -963,8 +971,12 @@ static SimpleTag ReadSimpleTag (ReadOnlySpan<byte> body)
binary = payload.ToArray ();
else if (element.Id == MatroskaIds.TagDefault || element.Id == MatroskaIds.TagDefaultBogus)
isDefault = IsFlagSet (payload);
else if (element.Id == MatroskaIds.SimpleTag)
children.Add (ReadSimpleTag (payload));
else if (element.Id == MatroskaIds.SimpleTag) {
if (depth < MaxSimpleTagDepth)
children.Add (ReadSimpleTag (payload, depth + 1));
else
(kept ??= new List<byte[]> ()).Add (body.Slice (element.Position, element.End - element.Position).ToArray ());
}
offset = element.End;
}

Expand All @@ -975,6 +987,8 @@ static SimpleTag ReadSimpleTag (ReadOnlySpan<byte> body)
};
foreach (var child in children)
tag.Children.Add (child);
if (kept is not null)
tag.KeptChildren.AddRange (kept);
return tag;
}

Expand Down
8 changes: 8 additions & 0 deletions src/TagLibSharp2/Matroska/MatroskaTag.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1354,6 +1354,12 @@ public SimpleTag (string name, string? text, bool isDefault = true)

public List<SimpleTag> Children { get; } = new ();

/// <summary>
/// Nested SimpleTags below <see cref="MatroskaFile.MaxSimpleTagDepth"/>, as their stored bytes.
/// They are written back after <see cref="Children"/>, so the nesting is kept without being parsed.
/// </summary>
public List<byte[]> KeptChildren { get; } = new ();

public BinaryData Render ()
{
using var body = new BinaryDataBuilder ();
Expand All @@ -1370,6 +1376,8 @@ public BinaryData Render ()
body.Add (EbmlWriter.Master (MatroskaIds.TagBinary, Binary));
foreach (var child in Children)
body.Add (child.Render ());
foreach (var child in KeptChildren)
body.Add (child);
return EbmlWriter.Master (MatroskaIds.SimpleTag, body.ToBinaryData ().Span);
}
}
Expand Down
239 changes: 239 additions & 0 deletions tests/TagLibSharp2.Tests/Matroska/MatroskaDeepNestingTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
// Copyright (c) 2025-2026 Stephen Shaw and contributors
// Licensed under the MIT License. See LICENSE file in the project root for full license information.

using TagLibSharp2.Matroska;
using TagLibSharp2.Tests.Core;

namespace TagLibSharp2.Tests.Matroska;

// A file controls how deep its elements nest. Reading or saving must not recurse once per level,
// or a small crafted file ends the process with a stack overflow that no caller can catch.
public partial class MatroskaFileTests
{
const int HostileDepth = 100_000;

[TestMethod]
public void Save_CuePointsNestedDeep_DoesNotOverflowTheStack ()
{
var marker = new byte[] { 0xC1, 0xC2, 0xC3, 0xC4 };
var info = Master (0x1549A966, Element (0x7BA9, "Live"u8));
var inner = Master (MatroskaIds.CueTrackPositions,
Element (0xF7, new byte[] { 1 }),
Element (MatroskaIds.CueClusterPosition, new byte[] { 0x10 }));
var cues = Wide (MatroskaIds.Cues, Nested (MatroskaIds.CuePoint, HostileDepth, [], inner));
var cluster = Unknown (0x1F43B675, Element (0xEC, marker));
var original = DeepWideFile (info, cues, cluster);
var parsed = MatroskaFile.Read (original).File!;
parsed.Tag.Title = new string ('N', 400);

var fs = new MockFileSystem ();
fs.AddFile ("/deep-cues.mkv", original);
var saved = parsed.SaveToFile ("/deep-cues.mkv", original, fs);

Assert.IsTrue (saved.IsSuccess, saved.Error);
var bytes = fs.ReadAllBytes ("/deep-cues.mkv");
Assert.AreEqual (1, CountOf (bytes, marker));
Assert.AreEqual (new string ('N', 400), MatroskaFile.Read (bytes).File!.Tag.Title);
}

[TestMethod]
public void Save_CueClusterPositionOffTheSpecPath_IsLeftAsStored ()
{
// RFC 9559 §5.1.5 places CueClusterPosition only in Cues\CuePoint\CueTrackPositions.
var marker = new byte[] { 0xC1, 0xC2, 0xC3, 0xC4 };
var info = Master (0x1549A966, Element (0x7BA9, "Live"u8));
var stray = Element (MatroskaIds.CueClusterPosition, new byte[] { 0x00, 0x7E });
var cues = Master (MatroskaIds.Cues, Master (MatroskaIds.CuePoint, Element (0xB3, new byte[] { 0 }), stray));
var cluster = Unknown (0x1F43B675, Element (0xEC, marker));
var original = FileWith (info, cues, cluster);
var parsed = MatroskaFile.Read (original).File!;
parsed.Tag.Title = new string ('N', 400);

var fs = new MockFileSystem ();
fs.AddFile ("/stray.mkv", original);
var saved = parsed.SaveToFile ("/stray.mkv", original, fs);

Assert.IsTrue (saved.IsSuccess, saved.Error);
Assert.AreEqual (1, CountOf (fs.ReadAllBytes ("/stray.mkv"), stray));
}

[TestMethod]
public void Read_SimpleTagsNestedDeep_DoesNotOverflowAndSaveKeepsTheNesting ()
{
var leaf = Master (0x67C8, Element (0x45A3, "LEAF"u8), Element (0x4487, "deepest"u8));
var chain = Nested (0x67C8, HostileDepth, Element (0x45A3, "N"u8), leaf);
var title = Wide (0x67C8, Concat (Element (0x45A3, "TITLE"u8), Element (0x4487, "Outer"u8), chain));
var tags = Wide (0x1254C367, Wide (0x7373, Concat (Master (0x63C0, Element (0x68CA, new byte[] { 30 })), title)));
var original = DeepWideFile (Master (0x1549A966, Element (0x7BA9, "Deep"u8)), tags);

var read = MatroskaFile.Read (original);

Assert.IsTrue (read.IsSuccess, read.Error);
Assert.AreEqual ("Outer", read.File!.Tag.Title);

read.File.Tag.Artist = "Someone";
var rendered = read.File.Render (original).ToArray ();
Assert.AreNotEqual (0, rendered.Length);
Assert.AreEqual (1, Occurrences (rendered, KeptSlice (chain)), "the SimpleTags below the parse depth are written back as stored, once");
Assert.AreEqual (HostileDepth, NestingBelowTitle (rendered));

var reread = MatroskaFile.Read (rendered).File!;
Assert.AreEqual ("Outer", reread.Tag.Title);
Assert.AreEqual ("Someone", reread.Tag.Artist);
}

// TITLE is level 1 and each chain link is one level deeper, so the leaf sits at level depth + 2.
// Levels up to MaxSimpleTagDepth are parsed and re-encoded with minimal sizes; anything deeper is
// kept as stored. Every element here is written with an 8-octet size, so a parsed one changes bytes
// and a kept one does not.
[TestMethod]
[DataRow (MatroskaFile.MaxSimpleTagDepth - 2, false)]
[DataRow (MatroskaFile.MaxSimpleTagDepth - 1, true)]
[DataRow (MatroskaFile.MaxSimpleTagDepth, true)]
[DataRow (MatroskaFile.MaxSimpleTagDepth + 1, true)]
[DataRow (MatroskaFile.MaxSimpleTagDepth + 5, true)]
public void Save_SimpleTagsAtAndPastTheParseDepth_KeepOnlyTheDeeperOnesAsStored (int depth, bool kept)
{
var leaf = Wide (0x67C8, Concat (Element (0x45A3, "LEAF"u8), Element (0x4487, "v"u8)));
var chain = Nested (0x67C8, depth, Element (0x45A3, "N"u8), leaf);
var title = Wide (0x67C8, Concat (Element (0x45A3, "TITLE"u8), Element (0x4487, "Outer"u8), chain));
var original = DeepWideFile (
Master (0x1549A966, Element (0x7BA9, "Deep"u8)),
Wide (0x1254C367, Wide (0x7373, Concat (Master (0x63C0, Element (0x68CA, new byte[] { 30 })), title))));
var file = MatroskaFile.Read (original).File!;

file.Tag.Artist = "Someone";
var rendered = file.Render (original).ToArray ();

Assert.AreEqual (depth, NestingBelowTitle (rendered));
Assert.AreEqual (kept ? 1 : 0, Occurrences (rendered, leaf), "the leaf's stored bytes");
if (kept)
Assert.AreEqual (1, Occurrences (rendered, KeptSlice (chain)));
Assert.IsTrue (MatroskaFile.Read (rendered).IsSuccess);
Assert.AreEqual (1, Occurrences (rendered, Element (0x45A3, "LEAF"u8)), "the leaf is written once");
Assert.AreEqual (1, Occurrences (rendered, Element (0x4487, "v"u8)), "with its value");
}

[TestMethod]
[DataRow (MatroskaFile.MaxSimpleTagDepth - 1)]
[DataRow (MatroskaFile.MaxSimpleTagDepth)]
[DataRow (MatroskaFile.MaxSimpleTagDepth + 1)]
[DataRow (MatroskaFile.MaxSimpleTagDepth + 5)]
public void Save_SimpleTagsNestedPastTheParseDepth_AreByteIdenticalAfterAnEdit (int depth)
{
var leaf = Master (0x67C8, Element (0x45A3, "LEAF"u8), Element (0x4487, "v"u8));
var chain = Nested (0x67C8, depth, Element (0x45A3, "N"u8), leaf);
var title = Wide (0x67C8, Concat (Element (0x45A3, "TITLE"u8), Element (0x4487, "Outer"u8), chain));
var original = DeepWideFile (
Master (0x1549A966, Element (0x7BA9, "Deep"u8)),
Wide (0x1254C367, Wide (0x7373, Concat (Master (0x63C0, Element (0x68CA, new byte[] { 30 })), title))));
var file = MatroskaFile.Read (original).File!;

file.Tag.Artist = "Someone";
var rendered = MatroskaFile.Read (file.Render (original).ToArray ()).File!;
rendered.Tag.Artist = null;
var restored = rendered.Render (file.Render (original).ToArray ()).ToArray ();

Assert.AreEqual (depth, NestingBelowTitle (restored));
Assert.AreEqual (1, Occurrences (restored, KeptSlice (chain)), "the kept SimpleTags survive two saves byte for byte");
}

[TestMethod]
[DataRow (MatroskaFile.MaxSimpleTagDepth + 1)]
[DataRow (MatroskaFile.MaxSimpleTagDepth + 5)]
public void Save_NewValueOnATagNestedPastTheParseDepth_KeepsItsNesting (int depth)
{
var leaf = Master (0x67C8, Element (0x45A3, "LEAF"u8), Element (0x4487, "v"u8));
var chain = Nested (0x67C8, depth, Element (0x45A3, "N"u8), leaf);
var title = Wide (0x67C8, Concat (Element (0x45A3, "TITLE"u8), Element (0x4487, "Outer"u8), chain));
var original = DeepWideFile (
Master (0x1549A966, Element (0x7BA9, "Deep"u8)),
Wide (0x1254C367, Wide (0x7373, Concat (Master (0x63C0, Element (0x68CA, new byte[] { 30 })), title))));
var file = MatroskaFile.Read (original).File!;

file.Tag.Title = "Renamed";
var rendered = file.Render (original).ToArray ();

Assert.AreEqual ("Renamed", MatroskaFile.Read (rendered).File!.Tag.Title);
Assert.AreEqual (depth, NestingBelowTitle (rendered));
Assert.AreEqual (1, Occurrences (rendered, KeptSlice (chain)));
}

// The stored bytes of the first SimpleTag below the parse depth: chain link MaxSimpleTagDepth - 1
// (link i is level i + 2), through the end of the chain, which is that link's whole subtree.
static byte[] KeptSlice (byte[] chain)
{
var link = Id (0x67C8).Length + 8 + Element (0x45A3, "N"u8).Length;
return chain.AsSpan ((MatroskaFile.MaxSimpleTagDepth - 1) * link).ToArray ();
}

static int Occurrences (byte[] data, byte[] pattern)
{
var count = 0;
var span = data.AsSpan ();
var at = span.IndexOf (pattern);
while (at >= 0) {
count++;
span = span.Slice (at + 1);
at = span.IndexOf (pattern);
}

return count;
}

// Counts the SimpleTags nested under the first TITLE SimpleTag by walking the bytes.
static int NestingBelowTitle (byte[] file)
{
var title = file.AsSpan ().IndexOf ("TITLE"u8);
Assert.IsTrue (title >= 0);
var count = 0;
var span = file.AsSpan (title);
var name = new byte[] { 0x45, 0xA3, 0x81, (byte)'N' };
var at = span.IndexOf (name);
while (at >= 0) {
count++;
span = span.Slice (at + name.Length);
at = span.IndexOf (name);
}

return count;
}

// Each level is the element ID, an 8-octet size (RFC 8794 §4.4), the prefix, then the next level.
static byte[] Nested (ulong id, int depth, byte[] prefix, byte[] innermost)
{
var idBytes = Id (id);
var level = idBytes.Length + 8 + prefix.Length;
var result = new byte[(level * depth) + innermost.Length];
for (var i = 0; i < depth; i++) {
var at = i * level;
idBytes.CopyTo (result, at);
WriteWideSize (result, at + idBytes.Length, (ulong)(result.Length - at - level + prefix.Length));
prefix.CopyTo (result, at + idBytes.Length + 8);
}

innermost.CopyTo (result, level * depth);
return result;
}

static byte[] Wide (ulong id, byte[] payload)
{
var idBytes = Id (id);
var result = new byte[idBytes.Length + 8 + payload.Length];
idBytes.CopyTo (result, 0);
WriteWideSize (result, idBytes.Length, (ulong)payload.Length);
payload.CopyTo (result, idBytes.Length + 8);
return result;
}

static byte[] DeepWideFile (params byte[][] segmentChildren) => Matroska (Wide (0x18538067, Concat (segmentChildren)));

static void WriteWideSize (byte[] buffer, int at, ulong size)
{
buffer[at] = 0x01;
for (var i = 7; i >= 1; i--) {
buffer[at + i] = (byte)size;
size >>= 8;
}
}
}
Loading