11// Copyright (c) Six Labors.
22// Licensed under the Six Labors Split License.
33
4+ using System . Diagnostics . CodeAnalysis ;
45using SixLabors . ImageSharp . IO ;
56using SixLabors . ImageSharp . Memory ;
67using SixLabors . ImageSharp . Metadata ;
@@ -95,6 +96,7 @@ public ImageInfo Identify(BufferedReadStream stream, CancellationToken cancellat
9596 /// Processes the ppm header.
9697 /// </summary>
9798 /// <param name="stream">The input stream.</param>
99+ /// <exception cref="InvalidImageContentException">An EOF marker has been read before the image has been decoded.</exception>
98100 private void ProcessHeader ( BufferedReadStream stream )
99101 {
100102 Span < byte > buffer = stackalloc byte [ 2 ] ;
@@ -144,14 +146,22 @@ private void ProcessHeader(BufferedReadStream stream)
144146 throw new InvalidImageContentException ( "Unknown of not implemented image type encountered." ) ;
145147 }
146148
147- stream . SkipWhitespaceAndComments ( ) ;
148- int width = stream . ReadDecimal ( ) ;
149- stream . SkipWhitespaceAndComments ( ) ;
150- int height = stream . ReadDecimal ( ) ;
151- stream . SkipWhitespaceAndComments ( ) ;
149+ if ( ! stream . TrySkipWhitespaceAndComments ( ) ||
150+ ! stream . TryReadDecimal ( out int width ) ||
151+ ! stream . TrySkipWhitespaceAndComments ( ) ||
152+ ! stream . TryReadDecimal ( out int height ) ||
153+ ! stream . TrySkipWhitespaceAndComments ( ) )
154+ {
155+ ThrowPrematureEof ( ) ;
156+ }
157+
152158 if ( this . colorType != PbmColorType . BlackAndWhite )
153159 {
154- this . maxPixelValue = stream . ReadDecimal ( ) ;
160+ if ( ! stream . TryReadDecimal ( out this . maxPixelValue ) )
161+ {
162+ ThrowPrematureEof ( ) ;
163+ }
164+
155165 if ( this . maxPixelValue > 255 )
156166 {
157167 this . componentType = PbmComponentType . Short ;
@@ -161,7 +171,7 @@ private void ProcessHeader(BufferedReadStream stream)
161171 this . componentType = PbmComponentType . Byte ;
162172 }
163173
164- stream . SkipWhitespaceAndComments ( ) ;
174+ stream . TrySkipWhitespaceAndComments ( ) ;
165175 }
166176 else
167177 {
@@ -174,6 +184,9 @@ private void ProcessHeader(BufferedReadStream stream)
174184 meta . Encoding = this . encoding ;
175185 meta . ColorType = this . colorType ;
176186 meta . ComponentType = this . componentType ;
187+
188+ [ DoesNotReturn ]
189+ static void ThrowPrematureEof ( ) => throw new InvalidImageContentException ( "Reached EOF while reading the header." ) ;
177190 }
178191
179192 private void ProcessPixels < TPixel > ( BufferedReadStream stream , Buffer2D < TPixel > pixels )
0 commit comments