From 5c3e32ceb6371d59580240a7851f9fdea6d9b9ef Mon Sep 17 00:00:00 2001 From: Jason Krause Date: Mon, 23 Nov 2026 10:00:29 -0700 Subject: [PATCH] Fail a track download that ends before its Content-Length A connection to the Deezer CDN that closed partway could end the response body like a normal finish. The track was saved short and reported as downloaded. A FLAC cut short still reports its full length in its STREAMINFO header, so later checks didn't notice either. DecodeTrackStreamAsync now returns the bytes it read, and GetRawTrackStream and WriteRawTrackToFile compare that with the response's Content-Length. A shortfall throws IncompleteTrackException. A response without Content-Length (chunked) skips the check. Co-Authored-By: Claude Opus 5.5 --- DeezNET.Tests/DecryptionTests.cs | 39 +++++++++++++++++++ DeezNET/Decryption.cs | 22 ++++++++++- DeezNET/Downloader.cs | 17 +++++--- .../Exceptions/IncompleteTrackException.cs | 11 ++++++ 4 files changed, 82 insertions(+), 7 deletions(-) create mode 100644 DeezNET/Exceptions/IncompleteTrackException.cs diff --git a/DeezNET.Tests/DecryptionTests.cs b/DeezNET.Tests/DecryptionTests.cs index 0971717..9302beb 100644 --- a/DeezNET.Tests/DecryptionTests.cs +++ b/DeezNET.Tests/DecryptionTests.cs @@ -1,4 +1,5 @@ using System.Text; +using DeezNET.Exceptions; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Modes; @@ -120,6 +121,44 @@ public async Task DecodeTrackStreamAsyncShortReadTest() outStream.ToArray().ShouldBe(track); } + [Fact] + public async Task DecodeTrackStreamAsyncReturnsBytesReadTest() + { + // the encrypted input, which is what Content-Length counts, not the decoded output + byte[] encrypted = Encrypt(Track(6144 * 2 + 100), Key); + using ShortReadStream stream = new(encrypted); + using MemoryStream outStream = new(); + + long received = await Decryption.DecodeTrackStreamAsync(stream, outStream, true, Key, TimeSpan.FromSeconds(5)); + + received.ShouldBe(encrypted.Length); + } + + [Fact] + public async Task DecodeTrackStreamAsyncTruncatedBodyIsCaughtTest() + { + // a connection closed early looks like the end of the stream; only the length shows the track is short + byte[] encrypted = Encrypt(Track(6144 * 3), Key); + using MemoryStream stream = new(encrypted[..(6144 + 1000)]); + using MemoryStream outStream = new(); + + long received = await Decryption.DecodeTrackStreamAsync(stream, outStream, true, Key, TimeSpan.FromSeconds(5)); + + Should.Throw(() => Decryption.EnsureComplete(received, encrypted.Length, 42)) + .Message.ShouldContain("ended after 7144 of 18432 bytes"); + } + + [Theory] + [InlineData(100, 100L)] + [InlineData(100, null)] + [InlineData(100, 0L)] + [InlineData(150, 100L)] + public void EnsureCompleteAllowsTest(long received, long? expected) + { + // a matching length, no Content-Length, or more than expected + Should.NotThrow(() => Decryption.EnsureComplete(received, expected, 42)); + } + [Fact] public async Task DecodeTrackStreamAsyncStallTimesOutTest() { diff --git a/DeezNET/Decryption.cs b/DeezNET/Decryption.cs index 9310f85..df95f28 100644 --- a/DeezNET/Decryption.cs +++ b/DeezNET/Decryption.cs @@ -5,6 +5,7 @@ using Org.BouncyCastle.Security; using System.Security.Cryptography; using System.Text; +using DeezNET.Exceptions; namespace DeezNET; @@ -37,19 +38,38 @@ public static void DecodeTrackStream(Stream input, Stream output, bool isCrypted /// The track's Blowfish key. /// The longest to wait for more data before giving up with a . Null waits indefinitely. /// Cancels the operation. - public static async Task DecodeTrackStreamAsync(Stream input, Stream output, bool isCrypted, string blowfishKey, TimeSpan? readTimeout = null, CancellationToken token = default) + /// The number of bytes read from , to compare with the size the server reported. + public static async Task DecodeTrackStreamAsync(Stream input, Stream output, bool isCrypted, string blowfishKey, TimeSpan? readTimeout = null, CancellationToken token = default) { bool isStart = true; + long totalRead = 0; int bytesRead; byte[] buffer = new byte[BLOCK_SIZE]; while ((bytesRead = await ReadBlockAsync(input, buffer, readTimeout, token)) > 0) { + totalRead += bytesRead; + int offset = DecodeBlock(buffer, bytesRead, isCrypted, blowfishKey, isStart); isStart = false; await output.WriteAsync(buffer.AsMemory(offset, bytesRead - offset), token); } + + return totalRead; + } + + /// + /// Throws when fewer bytes arrived than the server said it would send. A connection closed partway can end the body + /// like a normal finish, and a FLAC cut short still reports its full length in its header, so nothing else notices. + /// + /// The bytes read from the response body. + /// The response's Content-Length, or null when the server didn't send one. + /// The track, for the error message. + public static void EnsureComplete(long received, long? expected, long trackId) + { + if (expected is > 0 && received < expected) + throw new IncompleteTrackException($"Track ID {trackId} ended after {received} of {expected} bytes. The connection to the Deezer CDN closed early."); } // Decrypts the block in place and returns where its audio starts. diff --git a/DeezNET/Downloader.cs b/DeezNET/Downloader.cs index b43bdff..51ecdb0 100644 --- a/DeezNET/Downloader.cs +++ b/DeezNET/Downloader.cs @@ -41,9 +41,12 @@ public async Task GetRawTrackStream(long trackId, Bitrate bitrate, Bitra { MemoryStream outStream = new(); - var (stream, blowfishKey, isCrypted) = await GetEncryptedTrackData(trackId, bitrate, fallback, token); + var (stream, blowfishKey, isCrypted, contentLength) = await GetEncryptedTrackData(trackId, bitrate, fallback, token); using (stream) - await Decryption.DecodeTrackStreamAsync(stream, outStream, isCrypted, blowfishKey, ReadTimeout, token); + { + long received = await Decryption.DecodeTrackStreamAsync(stream, outStream, isCrypted, blowfishKey, ReadTimeout, token); + Decryption.EnsureComplete(received, contentLength, trackId); + } outStream.Seek(0, SeekOrigin.Begin); return outStream; @@ -74,12 +77,13 @@ public async Task GetRawTrackBytes(long trackId, Bitrate bitrate, Bitrat public async Task WriteRawTrackToFile(long trackId, string trackPath, Bitrate bitrate, Bitrate? fallback = null, CancellationToken token = default) { // fetch first so a failed request doesn't leave an empty file behind - var (stream, blowfishKey, isCrypted) = await GetEncryptedTrackData(trackId, bitrate, fallback, token); + var (stream, blowfishKey, isCrypted, contentLength) = await GetEncryptedTrackData(trackId, bitrate, fallback, token); using (stream) { using FileStream fileStream = new(trackPath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, useAsync: true); - await Decryption.DecodeTrackStreamAsync(stream, fileStream, isCrypted, blowfishKey, ReadTimeout, token); + long received = await Decryption.DecodeTrackStreamAsync(stream, fileStream, isCrypted, blowfishKey, ReadTimeout, token); + Decryption.EnsureComplete(received, contentLength, trackId); } } @@ -246,7 +250,7 @@ public static string GetCDNUrl(string id, int resolution) return string.Format(CDN_TEMPLATE, id, resolution); } - private async Task<(Stream stream, string blowfishKey, bool isCrypted)> GetEncryptedTrackData(long trackId, Bitrate bitrate, Bitrate? fallback = null, CancellationToken token = default) + private async Task<(Stream stream, string blowfishKey, bool isCrypted, long? contentLength)> GetEncryptedTrackData(long trackId, Bitrate bitrate, Bitrate? fallback = null, CancellationToken token = default) { JToken page = await _gw.GetTrackPage(trackId, token); TrackUrls urls = await GetTrackUrl(page["DATA"]!["TRACK_TOKEN"]!.ToString(), bitrate, token); @@ -282,7 +286,8 @@ public static string GetCDNUrl(string id, int resolution) string blowfishKey = Decryption.GenerateBlowfishKey(trackId.ToString()); bool isCrypted = encryptedUri.ToString().Contains("/mobile/") || encryptedUri.ToString().Contains("/media/"); - return (stream, blowfishKey, isCrypted); + // null when the CDN sends no Content-Length (a chunked response), which skips the completeness check + return (stream, blowfishKey, isCrypted, response.Content.Headers.ContentLength); } private async Task GetTrackUrl(string token, Bitrate bitrate, CancellationToken cancelToken = default, bool isRetry = false) diff --git a/DeezNET/Exceptions/IncompleteTrackException.cs b/DeezNET/Exceptions/IncompleteTrackException.cs new file mode 100644 index 0000000..27d93be --- /dev/null +++ b/DeezNET/Exceptions/IncompleteTrackException.cs @@ -0,0 +1,11 @@ +namespace DeezNET.Exceptions; + +/// +/// Thrown when a track's download ends before the size the Deezer CDN reported. +/// +public class IncompleteTrackException : Exception +{ + public IncompleteTrackException() { } + public IncompleteTrackException(string message) : base(message) { } + public IncompleteTrackException(string message, Exception inner) : base(message, inner) { } +}