@@ -96,6 +96,9 @@ pub struct Decoder<R> {
96
96
coefficients : Vec < Vec < i16 > > ,
97
97
// Bitmask of which coefficients has been completely decoded.
98
98
coefficients_finished : [ u64 ; MAX_COMPONENTS ] ,
99
+
100
+ // Maximum allowed size of decoded image buffer
101
+ decoding_buffer_size_limit : usize ,
99
102
}
100
103
101
104
impl < R : Read > Decoder < R > {
@@ -115,9 +118,15 @@ impl<R: Read> Decoder<R> {
115
118
exif_data : None ,
116
119
coefficients : Vec :: new ( ) ,
117
120
coefficients_finished : [ 0 ; MAX_COMPONENTS ] ,
121
+ decoding_buffer_size_limit : usize:: MAX ,
118
122
}
119
123
}
120
124
125
+ /// Set maximum buffer size allowed for decoded images
126
+ pub fn set_max_decoding_buffer_size ( & mut self , max : usize ) {
127
+ self . decoding_buffer_size_limit = max;
128
+ }
129
+
121
130
/// Returns metadata about the image.
122
131
///
123
132
/// The returned value will be `None` until a call to either `read_info` or `decode` has
@@ -532,6 +541,15 @@ impl<R: Read> Decoder<R> {
532
541
533
542
let frame = self . frame . as_ref ( ) . unwrap ( ) ;
534
543
544
+ if {
545
+ let required_mem = frame. components . len ( )
546
+ . checked_mul ( frame. output_size . width . into ( ) )
547
+ . and_then ( |m| m. checked_mul ( frame. output_size . height . into ( ) ) ) ;
548
+ required_mem. map_or ( true , |m| self . decoding_buffer_size_limit < m)
549
+ } {
550
+ return Err ( Error :: Format ( "size of decoded image exceeds maximum allowed size" . to_owned ( ) ) ) ;
551
+ }
552
+
535
553
// If we're decoding a progressive jpeg and a component is unfinished, render what we've got
536
554
if frame. coding_process == CodingProcess :: DctProgressive
537
555
&& self . coefficients . len ( ) == frame. components . len ( )
0 commit comments