57 lines
2.6 KiB
C#
57 lines
2.6 KiB
C#
using System.Buffers.Binary;
|
|
using System.IO.Compression;
|
|
|
|
namespace Messenger.Api.Services;
|
|
|
|
// Дополняет декодер: проверяет границы и CRC всех PNG chunks, включая IDAT.
|
|
public static class PngIntegrity
|
|
{
|
|
private static readonly uint[] Table = Enumerable.Range(0, 256).Select(i =>
|
|
{
|
|
uint c = (uint)i;
|
|
for (var bit = 0; bit < 8; bit++) c = (c & 1) != 0 ? 0xedb88320U ^ (c >> 1) : c >> 1;
|
|
return c;
|
|
}).ToArray();
|
|
|
|
public static async Task ValidateAsync(Stream stream, long maxDecodedBytes, CancellationToken ct)
|
|
{
|
|
stream.Position = 8;
|
|
var header = new byte[8];
|
|
var buffer = new byte[65536];
|
|
var checksum = new byte[4];
|
|
using var compressed = new MemoryStream(); // IDAT не больше уже ограниченного файла (10 MiB).
|
|
while (stream.Position < stream.Length)
|
|
{
|
|
await stream.ReadExactlyAsync(header, ct);
|
|
var length = BinaryPrimitives.ReadUInt32BigEndian(header);
|
|
if (length > stream.Length - stream.Position - 4) throw new InvalidDataException("Invalid PNG chunk");
|
|
uint crc = uint.MaxValue;
|
|
for (var i = 4; i < 8; i++) crc = Table[(crc ^ header[i]) & 255] ^ (crc >> 8);
|
|
long remaining = length;
|
|
while (remaining > 0)
|
|
{
|
|
var count = (int)Math.Min(buffer.Length, remaining);
|
|
await stream.ReadExactlyAsync(buffer.AsMemory(0, count), ct);
|
|
if (header.AsSpan(4, 4).SequenceEqual("IDAT"u8))
|
|
await compressed.WriteAsync(buffer.AsMemory(0, count), ct);
|
|
for (var i = 0; i < count; i++) crc = Table[(crc ^ buffer[i]) & 255] ^ (crc >> 8);
|
|
remaining -= count;
|
|
}
|
|
await stream.ReadExactlyAsync(checksum, ct);
|
|
if ((crc ^ uint.MaxValue) != BinaryPrimitives.ReadUInt32BigEndian(checksum))
|
|
throw new InvalidDataException("Invalid PNG checksum");
|
|
}
|
|
// stbi распаковывает PNG до проверки длины пикселей: сначала проверяем
|
|
// размер zlib-потока самостоятельно, не выделяя память под распаковку.
|
|
compressed.Position = 0;
|
|
using var zlib = new ZLibStream(compressed, CompressionMode.Decompress);
|
|
long decoded = 0;
|
|
int read;
|
|
while ((read = await zlib.ReadAsync(buffer, ct)) != 0)
|
|
{
|
|
decoded += read;
|
|
if (decoded > maxDecodedBytes) throw new InvalidDataException("PNG decompression exceeds dimensions");
|
|
}
|
|
}
|
|
}
|