Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[bep52|bep47] Fix file ordering sanity check and padding for empty files #612

Merged
merged 1 commit into from
Jan 29, 2023
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
4 changes: 2 additions & 2 deletions src/MonoTorrent.Client/MonoTorrent/Torrent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -629,7 +629,7 @@ void LoadInternal (BEncodedDictionary torrentInformation, RawInfoHashes infoHash

var merkleTrees = dict.ToDictionary (
key => MerkleRoot.FromMemory (key.Key.AsMemory ()),
kvp => ReadOnlyMerkleLayers.FromLayer (PieceLength, MerkleRoot.FromMemory (kvp.Key.AsMemory ()), ((BEncodedString)kvp.Value).Span) ?? throw new TorrentException ($"Invalid merkle tree. A layer not produce the expected root hash.")
kvp => ReadOnlyMerkleLayers.FromLayer (PieceLength, MerkleRoot.FromMemory (kvp.Key.AsMemory ()), ((BEncodedString) kvp.Value).Span) ?? throw new TorrentException ($"Invalid merkle tree. A layer not produce the expected root hash.")
);

hashesV2 = LoadHashesV2 (Files, merkleTrees, PieceLength);
Expand Down Expand Up @@ -778,7 +778,7 @@ static void LoadTorrentFilesV2 (string key, BEncodedDictionary data, List<ITorre
if (key == "") {
var length = ((BEncodedNumber) data["length"]).Number;
if (length == 0) {
files.Add (new TorrentFile (path, length, 0, 0, 0, TorrentFileAttributes.None, 0));
files.Insert (0, new TorrentFile (path, length, 0, 0, 0, TorrentFileAttributes.None, 0));
} else {
totalPieces++;
var offsetInTorrent = (files.LastOrDefault ()?.OffsetInTorrent ?? 0) + (files.LastOrDefault ()?.Length ?? 0) + (files.LastOrDefault ()?.Padding ?? 0);
Expand Down
6 changes: 4 additions & 2 deletions src/MonoTorrent.Client/MonoTorrent/TorrentCreator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -265,8 +265,10 @@ internal async Task<BEncodedDictionary> CreateAsync (string name, ITorrentFileSo
if (Type.HasV2 ())
rawFiles = rawFiles.OrderBy (t => t.Destination, StringComparer.Ordinal).ToArray ();

// The last file never has padding bytes
rawFiles[rawFiles.Length - 1].padding = 0;
// The last non-empty file never has padding bytes
var last = rawFiles.Where (t => t.length != 0).Last ();
var index = Array.IndexOf (rawFiles, last);
rawFiles[index].padding = 0;

var files = TorrentFileInfo.Create (PieceLength, rawFiles);
var manager = new TorrentManagerInfo (files,
Expand Down
2 changes: 2 additions & 0 deletions src/MonoTorrent.Client/MonoTorrent/TorrentFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,8 @@ internal static ITorrentFile[] Create (int pieceLength, TorrentFileTuple[] files
// Do not try to handle this, it would be very messy.
throw new ArgumentException ("Can not handle torrent that starts with padding");
} else {
if (files[real].length == 0)
throw new InvalidOperationException ("Attempted to add padding bytes to a file which should not have padding.");
// add the count to it will also work in case of consecutive padding files, also slightly edge-case-y
files[real].padding += files[t].length;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ private static async Task<Torrent> CreateTestTorrent (TorrentType type)
[TestCase(TorrentType.V1OnlyWithPaddingFiles)]
[TestCase(TorrentType.V1V2Hybrid)]
[TestCase(TorrentType.V2Only)]
public async Task CreateHybridWithUnusualFilenames (TorrentType type)
public async Task CreateWithUnusualFilenames (TorrentType type)
{
var files = new Source {
TorrentName = "asd",
Expand All @@ -92,6 +92,45 @@ public async Task CreateHybridWithUnusualFilenames (TorrentType type)
Assert.DoesNotThrow (() => Torrent.Load (torrent));
}

[Test]
[TestCase (TorrentType.V1Only)]
[TestCase (TorrentType.V1OnlyWithPaddingFiles)]
[TestCase (TorrentType.V1V2Hybrid)]
[TestCase (TorrentType.V2Only)]
public async Task CreateWithManyEmptyFiles (TorrentType type)
{
var files = new Source {
TorrentName = "asd",
Files = new[] {
new FileMapping("a", "a", 0),
new FileMapping("b", "b", PieceLength),
new FileMapping("c", "c", 0),
new FileMapping("d1", "d1", PieceLength / 2),
new FileMapping("d2", "d2", PieceLength / 2),
new FileMapping("e", "e", 0),
new FileMapping("f", "f", 0),
new FileMapping("g", "g", PieceLength + 1),
new FileMapping("h", "h", 0),
}
};

var torrent = Torrent.Load (await CreateTestBenc (type, files));
foreach(var emptyFile in files.Files.Where (t => t.Length == 0)) {
var file = torrent.Files.Single (t => t.Path == emptyFile.Destination);
Assert.AreEqual (0, file.Length);
Assert.AreEqual (0, file.OffsetInTorrent);
Assert.AreEqual (0, file.StartPieceIndex);
Assert.AreEqual (0, file.EndPieceIndex);
Assert.AreEqual (0, file.Padding);
Assert.IsTrue (file.PiecesRoot.IsEmpty);
}
var expectedPadding = type == TorrentType.V1OnlyWithPaddingFiles || type == TorrentType.V1V2Hybrid ? PieceLength / 2 : 0;
Assert.AreEqual (0, torrent.Files.Single (t => t.Path == "b").Padding);
Assert.AreEqual (expectedPadding, torrent.Files.Single (t => t.Path == "d1").Padding);
Assert.AreEqual (expectedPadding, torrent.Files.Single (t => t.Path == "d2").Padding);
Assert.AreEqual (0, torrent.Files.Single (t => t.Path == "g").Padding);
}

[Test]
public async Task FileLengthSameAsPieceLength ([Values (TorrentType.V1Only, TorrentType.V1V2Hybrid)] TorrentType type)
{
Expand Down