Skip to content

Commit e809010

Browse files
committedApr 9, 2025·
Defensive code when downloaded image stream is broken #201
1 parent bfaad95 commit e809010

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed
 

‎src/Html2OpenXml/IO/ImageHeader.cs

+6
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,12 @@ public static Size KeepAspectRatio(Size actualSize, Size preferredSize)
119119
private static FileType DetectFileType (SequentialBinaryReader reader)
120120
{
121121
byte[] magicBytes = new byte[MaxMagicBytesLength];
122+
var availableBytes = reader.BaseStream.Length - reader.BaseStream.Position;
123+
// reasonably, we can assume that if we are at the end of the stream and we read the header,
124+
// the image content must be invalid or truncated.
125+
if (availableBytes < MaxMagicBytesLength)
126+
return FileType.Unrecognized;
127+
122128
reader.Read(magicBytes, 0, MaxMagicBytesLength);
123129

124130
var headerSpan = magicBytes.AsSpan();

‎test/HtmlToOpenXml.Tests/ImageFormats/ImageHeaderTests.cs

+10
Original file line numberDiff line numberDiff line change
@@ -63,5 +63,15 @@ public ImageHeader.FileType GuessFormat_ReturnsFileType(string resourceName)
6363
Assert.That(success, Is.EqualTo(true));
6464
return guessType;
6565
}
66+
67+
[Test(ExpectedResult = ImageHeader.FileType.Unrecognized)]
68+
public ImageHeader.FileType GuessFormat_WithEmpty_ReturnsFileType()
69+
{
70+
using var memoryStream = new MemoryStream();
71+
bool success = ImageHeader.TryDetectFileType(memoryStream, out var guessType);
72+
73+
Assert.That(success, Is.EqualTo(false));
74+
return guessType;
75+
}
6676
}
6777
}

0 commit comments

Comments
 (0)
Please sign in to comment.