From 29ad8301fc7c86e68cd0c249d2279e4aaf380be9 Mon Sep 17 00:00:00 2001 From: Andrew Haines Date: Fri, 2 Jun 2017 10:11:46 +0100 Subject: [PATCH] Fix underflow of Zlib::GzipReader#pos [ruby-core:81488] [Bug #13616] --- ext/zlib/zlib.c | 11 ++++++++--- test/zlib/test_zlib.rb | 12 ++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/ext/zlib/zlib.c b/ext/zlib/zlib.c index bc1b47c221..db1a1c392f 100644 --- a/ext/zlib/zlib.c +++ b/ext/zlib/zlib.c @@ -3393,7 +3393,14 @@ static VALUE rb_gzfile_total_out(VALUE obj) { struct gzfile *gz = get_gzfile(obj); - return rb_uint2inum(gz->z.stream.total_out - ZSTREAM_BUF_FILLED(&gz->z)); + uLong total_out = gz->z.stream.total_out; + long buf_filled = ZSTREAM_BUF_FILLED(&gz->z); + + if (total_out >= (uLong)buf_filled) { + return rb_uint2inum(total_out - buf_filled); + } else { + return LONG2FIX(-(buf_filled - total_out)); + } } /* @@ -4800,5 +4807,3 @@ Init_zlib(void) * Raised when the data length recorded in the gzip file footer is not equivalent * to the length of the actual uncompressed data. */ - - diff --git a/test/zlib/test_zlib.rb b/test/zlib/test_zlib.rb index b6a4510b80..d53717ef74 100644 --- a/test/zlib/test_zlib.rb +++ b/test/zlib/test_zlib.rb @@ -663,6 +663,18 @@ def test_ungetc_paragraph } end + def test_ungetc_at_start_of_file + s = "".dup + w = Zlib::GzipWriter.new(StringIO.new(s)) + w << "abc" + w.close + r = Zlib::GzipReader.new(StringIO.new(s)) + + r.ungetc ?! + + assert_equal(-1, r.pos, "[ruby-core:81488][Bug #13616]") + end + def test_open Tempfile.create("test_zlib_gzip_reader_open") {|t| t.close -- 2.13.0