001/**
002 * Java Web Archive Toolkit - Software to read and validate ARC, WARC
003 * and GZip files. (http://jwat.org/)
004 * Copyright 2011-2012 Netarkivet.dk (http://netarkivet.dk/)
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.jwat.gzip;
019
020import org.jwat.common.ByteCountingPushBackInputStream;
021import org.jwat.common.Diagnosis;
022import org.jwat.common.DiagnosisType;
023import org.jwat.common.Diagnostics;
024import org.jwat.common.ISO8859_1;
025
026import java.io.BufferedInputStream;
027import java.io.ByteArrayOutputStream;
028import java.io.Closeable;
029import java.io.EOFException;
030import java.io.IOException;
031import java.io.InputStream;
032import java.util.Date;
033import java.util.zip.CRC32;
034import java.util.zip.DataFormatException;
035import java.util.zip.Inflater;
036
037/**
038 * A reader for (multi-part) GZip files. Validates header and CRC's.
039 * Entries are read sequentially from the input stream. Random access is
040 * supported indirectly if the used input stream supports this.
041 * Compressed data is available through an uncompressing input stream wrapper.
042 *
043 * @author nicl
044 */
045public class GzipReader implements Closeable {
046
047    /** Buffer size to use when read skipping. */
048    public static final int SKIP_READ_BUFFER_SIZE = 8192;
049
050    /** Read buffer used by the skip method. */
051    protected byte[] skip_read_buffer = new byte[SKIP_READ_BUFFER_SIZE];
052
053    /** Default input buffer size. */
054    public static final int DEFAULT_INPUT_BUFFER_SIZE = 8192;
055
056    /** Input stream of GZip (multi-part) file. */
057    protected ByteCountingPushBackInputStream pbin;
058    /** Inflater used to uncompress GZip entries. */
059    protected Inflater inf = new Inflater( true );
060    /** Checksum object used to calculate CRC16 and CRC32 values. */
061    protected CRC32 crc = new CRC32();
062    /** Last number of bytes read into the input buffer. */
063    protected int lastInput;
064    /** Input buffer used to feed the inflater. */
065    protected byte[] inputBytes;
066
067    /** ISO-8859-1 validating de-/encoder. */
068    protected final ISO8859_1 iso8859_1 = new ISO8859_1();
069
070    /** Compliance status for records parsed up to now. */
071    protected boolean bIsCompliant = true;
072
073    /** Validation errors and warnings. */
074    public final Diagnostics<Diagnosis> diagnostics = new Diagnostics<Diagnosis>();
075
076    /** Entries read. */
077    protected int entries = 0;
078
079    /** Entry offset, updated each time an entry is closed. */
080    protected long startOffset = -1;
081
082    /** Number of bytes consumed by this reader. */
083    protected long consumed;
084
085    /** Current GZip entry object. */
086    protected GzipEntry gzipEntry;
087
088    /** Partial GZip entry which could not be completely read. */
089    public GzipEntry partialEntry;
090
091    /** Buffer used to read header.  */
092    protected byte[] headerBytes = new byte[10];
093    /** Buffer used to read the XLEN value. */
094    protected byte[] xlenBytes = new byte[2];
095    /** Buffer used to read the FNAME data. */
096    protected byte[] fnameBytes;
097    /** Buffer used to read the FCOMMENT data. */
098    protected byte[] fcommentBytes;
099    /** Buffer used to read the CRC16 value. */
100    protected byte[] crc16Bytes = new byte[2];
101    /** Buffer used to read trailer. */
102    protected byte[] trailerBytes = new byte[8];
103
104    /**
105     * Check head of <code>PushBackInputStream</code> for a GZip magic number.
106     * The state of the <code>PushBackInputStream</code> is the same after the
107     * call as before the call.
108     * @param pbin <code>PushBackInputStream</code> with GZip entries
109     * @return boolean indicating presence of a GZip magic number
110     * @throws IOException if an I/O error occurs while examining head of stream
111     */
112    public static boolean isGzipped(ByteCountingPushBackInputStream pbin) throws IOException {
113        if (pbin == null) {
114            throw new IllegalArgumentException("'pbin'is null!");
115        }
116        byte[] magicBytes = new byte[2];
117        int magicNumber = 0xdeadbeef;
118        // Look for the leading 2 magic bytes in front of every valid GZip entry.
119        int read = pbin.readFully(magicBytes);
120        if (read == 2) {
121            magicNumber = ((magicBytes[1] & 255) << 8) | (magicBytes[0] & 255);
122        }
123        if (read > 0) {
124            pbin.unread(magicBytes, 0, read);
125        }
126        return (magicNumber == GzipConstants.GZIP_MAGIC);
127    }
128
129    /**
130     * Construct a GZip reader with a default input buffer size of
131     * DEFAULT_INPUT_BUFFER_SIZE.
132     * @param in input stream of GZip file
133     */
134    public GzipReader(InputStream in) {
135        if (in == null) {
136            throw new IllegalArgumentException("in is null!");
137        }
138        pbin = new ByteCountingPushBackInputStream(in, DEFAULT_INPUT_BUFFER_SIZE);
139        inputBytes = new byte[DEFAULT_INPUT_BUFFER_SIZE];
140    }
141
142    /**
143     * Construct a GZip reader with the specified input buffer size.
144     * @param in input stream of GZip file
145     * @param buffer_size input buffer size to use
146     */
147    public GzipReader(InputStream in, int buffer_size) {
148        if (in == null) {
149            throw new IllegalArgumentException("in is null!");
150        }
151        if (buffer_size <= 0) {
152            throw new IllegalArgumentException(
153                    "buffer_size is less or equals to zero: " + buffer_size);
154        }
155        in = new BufferedInputStream(in, buffer_size);
156        pbin = new ByteCountingPushBackInputStream(in, DEFAULT_INPUT_BUFFER_SIZE);
157        inputBytes = new byte[DEFAULT_INPUT_BUFFER_SIZE];
158    }
159
160    /**
161     * Release resources associated with this reader.
162     * Also closes the <code>InputStream</code> supplied to the constructor.
163     * @throws IOException if an I/O error occurs while closing reader
164     */
165    public void close() throws IOException {
166        if (gzipEntry != null) {
167            gzipEntry.close();
168            startOffset = pbin.getConsumed();
169            gzipEntry = null;
170        }
171        if (inf != null) {
172            inf.end();
173            inf = null;
174        }
175        if (pbin != null){
176            pbin.close();
177        }
178        pbin = null;
179    }
180
181    /**
182     * Returns a boolean indicating whether all entries parsed so far are compliant.
183     * @return a boolean indicating whether all entries parsed so far are compliant
184     */
185    public boolean isCompliant() {
186        return bIsCompliant;
187    }
188
189    /**
190     * Returns the offset of the current entry or -1 if none have been read.
191     * @return the offset of the current entry or -1
192     */
193    public long getStartOffset() {
194        return startOffset;
195    }
196
197    /**
198     * Returns the current offset in the input stream. Which could be anywhere
199     * in the (multi-part) GZip file.
200     * @return current offset in the input stream
201     */
202    public long getOffset() {
203        if (pbin != null) {
204            return pbin.getConsumed();
205        } else {
206            return consumed;
207        }
208    }
209
210    /**
211     * Get number of bytes consumed by this reader.
212     * Updated after each record has been read.
213     * @return number of bytes consumed by this reader
214     */
215    public long getConsumed() {
216        return consumed;
217    }
218
219    /**
220     * Get the next GZip entry header and prepare the compressed data for
221     * input stream retrieval.
222     * @return GZip entry or null
223     * @throws IOException if an I/O error occurs while reading entry
224     */
225    public GzipEntry getNextEntry() throws IOException {
226        if (gzipEntry != null) {
227            gzipEntry.close();
228            gzipEntry = null;
229        }
230        int read = pbin.readFully(headerBytes);
231        if (read == 10) {
232            try {
233                crc.reset();
234                inf.reset();
235                startOffset = pbin.getConsumed() - 10;
236                gzipEntry = new GzipEntry();
237                gzipEntry.reader = this;
238                gzipEntry.startOffset = startOffset;
239                /*
240                 * Header.
241                 */
242                gzipEntry.magic = ((headerBytes[1] & 255) << 8) | (headerBytes[0] & 255);
243                gzipEntry.cm = (short)(headerBytes[2] & 255);
244                gzipEntry.flg = (short)(headerBytes[3] & 255);
245                gzipEntry.mtime = ((headerBytes[7] & 255) << 24) | ((headerBytes[6] & 255) << 16) | ((headerBytes[5] & 255) << 8) | (headerBytes[4] & 255);
246                gzipEntry.date = (gzipEntry.mtime != 0) ? new Date(gzipEntry.mtime * 1000) : null;
247                gzipEntry.xfl = (short)(headerBytes[8] & 255);
248                gzipEntry.os = (short)(headerBytes[9] & 255);
249                crc.update(headerBytes);
250                if (gzipEntry.magic != GzipConstants.GZIP_MAGIC) {
251                    gzipEntry.diagnostics.addError(
252                            new Diagnosis(
253                                    DiagnosisType.INVALID_EXPECTED,
254                                    "Magic Value",
255                                    Integer.toHexString(gzipEntry.magic),
256                                    Integer.toHexString(GzipConstants.GZIP_MAGIC)
257                                )
258                            );
259                }
260                if (gzipEntry.cm != GzipConstants.CM_DEFLATE) {
261                    // Currently only the deflate compression method is supported in GZip.
262                    gzipEntry.diagnostics.addError(
263                            new Diagnosis(
264                                    DiagnosisType.INVALID_EXPECTED,
265                                    "Compression Method",
266                                    Integer.toHexString(gzipEntry.cm),
267                                    Integer.toHexString(GzipConstants.CM_DEFLATE)
268                                )
269                            );
270                } else {
271                    // Currently only the deflate compression method is supported in GZip.
272                    // Check to see whether some xfl reserved bits have been used.
273                    if ((gzipEntry.xfl & GzipConstants.DEFLATE_XLF_RESERVED) != 0) {
274                        gzipEntry.diagnostics.addWarning(
275                                new Diagnosis(
276                                        DiagnosisType.RESERVED,
277                                        "eXtra FLags",
278                                        Integer.toHexString(gzipEntry.xfl & GzipConstants.DEFLATE_XLF_RESERVED)
279                                    )
280                                );
281                    }
282                    if ((gzipEntry.xfl & GzipConstants.DEFLATE_XFL_COMPRESSION_MASK) == GzipConstants.DEFLATE_XFL_COMPRESSION_MASK) {
283                        gzipEntry.diagnostics.addError(
284                                new Diagnosis(
285                                        DiagnosisType.INVALID_DATA,
286                                        "eXtra FLags",
287                                        Integer.toHexString(gzipEntry.xfl & GzipConstants.DEFLATE_XFL_COMPRESSION_MASK)
288                                    )
289                                );
290                    }
291                }
292                if ((gzipEntry.flg & GzipConstants.FLG_FRESERVED) != 0) {
293                    gzipEntry.diagnostics.addWarning(
294                            new Diagnosis(
295                                    DiagnosisType.RESERVED,
296                                    "FLaGs",
297                                    Integer.toHexString(gzipEntry.flg & GzipConstants.FLG_FRESERVED)
298                                )
299                            );
300                }
301                if (!GzipConstants.osIdxStr.containsKey((int)gzipEntry.os)) {
302                    gzipEntry.diagnostics.addWarning(
303                            new Diagnosis(
304                                    DiagnosisType.UNKNOWN,
305                                    "Operating System",
306                                    Integer.toString(gzipEntry.os)
307                        )
308                    );
309                }
310                /*
311                 * FTEXT.
312                 */
313                if ((gzipEntry.flg & GzipConstants.FLG_FTEXT) == GzipConstants.FLG_FTEXT) {
314                    gzipEntry.bFText = true;
315                }
316                /*
317                 * FEXTRA.
318                 */
319                if ((gzipEntry.flg & GzipConstants.FLG_FEXTRA) == GzipConstants.FLG_FEXTRA) {
320                    read = pbin.read(xlenBytes);
321                    if (read == 2) {
322                        gzipEntry.xlen = ((xlenBytes[1] & 255) << 8) | (xlenBytes[0] & 255);
323                        if (gzipEntry.xlen > 0) {
324                            gzipEntry.extraBytes = new byte[gzipEntry.xlen];
325                            read = pbin.readFully(gzipEntry.extraBytes);
326                            if (read != gzipEntry.xlen) {
327                                throw new EOFException("Unexpected EOF!");
328                            }
329                            int idx = 0;
330                            boolean b = true;
331                            GzipExtraData extraData;
332                            int len;
333                            while (b) {
334                                if (idx <= gzipEntry.extraBytes.length - 4) {
335                                    extraData = new GzipExtraData();
336                                    extraData.si1 = (byte)(gzipEntry.extraBytes[idx++] & 255);
337                                    extraData.si2 = (byte)(gzipEntry.extraBytes[idx++] & 255);
338                                    len = ((gzipEntry.extraBytes[idx+1] & 255) << 8) | (gzipEntry.extraBytes[idx] & 255);
339                                    idx += 2;
340                                    if (idx + len <= gzipEntry.extraBytes.length) {
341                                        extraData.data = new byte[len];
342                                        System.arraycopy(gzipEntry.extraBytes, idx, extraData.data, 0, len);
343                                        idx += len;
344                                        gzipEntry.extraData.add(extraData);
345                                    } else {
346                                        b = false;
347                                    }
348                                } else {
349                                    b = false;
350                                }
351                            }
352                            if (idx != gzipEntry.extraBytes.length) {
353                                gzipEntry.diagnostics.addError(
354                                        new Diagnosis(
355                                                DiagnosisType.INVALID_DATA,
356                                                "FEXTRA",
357                                                "Invalid structure",
358                                                "Data truncated"
359                                            )
360                                        );
361                            }
362                        } else {
363                            gzipEntry.extraBytes = new byte[0];
364                        }
365                    } else {
366                        throw new EOFException("Unexpected EOF!");
367                    }
368                    crc.update(xlenBytes);
369                    crc.update(gzipEntry.extraBytes);
370                }
371                /*
372                 * FNAME.
373                 */
374                if ((gzipEntry.flg & GzipConstants.FLG_FNAME) == GzipConstants.FLG_FNAME) {
375                    fnameBytes = readZeroTerminated();
376                    if (fnameBytes == null) {
377                        throw new EOFException("Unexpected EOF!");
378                    }
379                    if (!iso8859_1.decode(fnameBytes, "")) {
380                        gzipEntry.diagnostics.addWarning(
381                                new Diagnosis(
382                                        DiagnosisType.INVALID_ENCODING,
383                                        "FName",
384                                        iso8859_1.decoded,
385                                        "ISO-8859-1"
386                                    )
387                                );
388                    }
389                    gzipEntry.fname = iso8859_1.decoded;
390                    crc.update(fnameBytes);
391                    crc.update(0);
392                }
393                /*
394                 * FCOMMENT.
395                 */
396                if ((gzipEntry.flg & GzipConstants.FLG_FCOMMENT) == GzipConstants.FLG_FCOMMENT) {
397                    fcommentBytes = readZeroTerminated();
398                    if (fcommentBytes == null) {
399                        throw new EOFException("Unexpected EOF!");
400                    }
401                    if (!iso8859_1.decode(fcommentBytes, "\n")) {
402                        gzipEntry.diagnostics.addWarning(
403                                new Diagnosis(
404                                        DiagnosisType.INVALID_ENCODING,
405                                        "FComment",
406                                        iso8859_1.decoded,
407                                        "ISO-8859-1"
408                                    )
409                                );
410                    }
411                    gzipEntry.fcomment = iso8859_1.decoded;
412                    crc.update(fcommentBytes);
413                    crc.update(0);
414                }
415                /*
416                 * FHCRC.
417                 */
418                if ((gzipEntry.flg & GzipConstants.FLG_FHCRC) == GzipConstants.FLG_FHCRC) {
419                    read = pbin.read(crc16Bytes);
420                    if (read == 2) {
421                        gzipEntry.bFhCrc = true;
422                        gzipEntry.crc16 = ((crc16Bytes[1] & 255) << 8) | (crc16Bytes[0] & 255);
423                    } else {
424                        throw new EOFException("Unexpected EOF!");
425                    }
426                }
427                /*
428                 * Computed crc16.
429                 */
430                gzipEntry.comp_crc16 = ((int)crc.getValue()) & 0x0000ffff;
431                crc.reset();
432                if (gzipEntry.crc16 != null && gzipEntry.crc16 != gzipEntry.comp_crc16) {
433                    gzipEntry.diagnostics.addError(
434                            new Diagnosis(
435                                    DiagnosisType.INVALID_EXPECTED,
436                                    "CRC16",
437                                    Integer.toHexString(gzipEntry.crc16),
438                                    Integer.toHexString(gzipEntry.comp_crc16)
439                                )
440                            );
441                }
442                /*
443                 * Prepare Entry InputStream.
444                 */
445                lastInput = 0;
446                gzipEntry.in = new GzipEntryInputStream(this, gzipEntry);
447                // Compliance
448                if (gzipEntry.diagnostics.hasErrors() || gzipEntry.diagnostics.hasWarnings()) {
449                    gzipEntry.bIsCompliant = false;
450                } else {
451                    gzipEntry.bIsCompliant = true;
452                }
453                bIsCompliant &= gzipEntry.bIsCompliant;
454                ++entries;
455            } catch (EOFException e) {
456                partialEntry = gzipEntry;
457                diagnostics.addError(new Diagnosis(DiagnosisType.INVALID_DATA, "GZip file", "Unexpected EOF!"));
458                bIsCompliant = false;
459                gzipEntry = null;
460            }
461        } else {
462            // Require one or more entries to be present.
463            if (entries == 0) {
464                diagnostics.addError(new Diagnosis(DiagnosisType.ERROR_EXPECTED, "GZip file", "One or more entries"));
465                bIsCompliant = false;
466            }
467            if (pbin.read() != -1) {
468                diagnostics.addError(new Diagnosis(DiagnosisType.INVALID_DATA, "GZip file", "Unexpected trailing data!"));
469                bIsCompliant = false;
470            }
471        }
472        return gzipEntry;
473    }
474
475    /**
476     * Read non-compressed zero terminated data.
477     * @return zero terminated data
478     * @throws IOException if an I/O error occurs while reading data
479     */
480    protected byte[] readZeroTerminated() throws IOException {
481        ByteArrayOutputStream out = new ByteArrayOutputStream(32);
482        int b;
483        while ((b = pbin.read()) > 0) {
484            out.write(b);
485        }
486        return (b != -1) ? out.toByteArray() : null;
487    }
488
489    /**
490     * Read the non-compressed trailing 8 bytes with CRC32 and ISize values.
491     * @param entry Gzip entry
492     * @throws IOException if an I/O error occurs while reading data
493     */
494    protected void readTrailer(GzipEntry entry) throws IOException {
495        int read = pbin.readFully(trailerBytes);
496        entry.consumed = pbin.getConsumed() - entry.startOffset;
497        entry.compressed_size = inf.getBytesRead();
498        entry.uncompressed_size = inf.getBytesWritten();
499        consumed += entry.consumed;
500        entry.reader = null;
501        if (read == 8) {
502            entry.crc32 = ((trailerBytes[3] & 255) << 24) | ((trailerBytes[2] & 255) << 16) | ((trailerBytes[1] & 255) << 8) | (trailerBytes[0] & 255);
503            entry.isize = ((trailerBytes[7] & 255) << 24) | ((trailerBytes[6] & 255) << 16) | ((trailerBytes[5] & 255) << 8) | (trailerBytes[4] & 255);
504            entry.comp_crc32 = (int)(crc.getValue() & 0xffffffff);
505            entry.comp_isize = (int)(inf.getBytesWritten() & 0xffffffff);
506            if (entry.comp_crc32 != entry.crc32) {
507                entry.diagnostics.addError(
508                        new Diagnosis(
509                                DiagnosisType.INVALID_EXPECTED,
510                                "CRC32",
511                                Integer.toHexString(entry.crc32),
512                                Integer.toHexString(entry.comp_crc32)
513                            )
514                        );
515            }
516            if (entry.comp_isize != entry.isize) {
517                entry.diagnostics.addError(
518                        new Diagnosis(
519                                DiagnosisType.INVALID_EXPECTED,
520                                "ISize",
521                                Long.toString(entry.isize),
522                                Long.toString(entry.comp_isize)
523                            )
524                        );
525            }
526        } else {
527            gzipEntry.diagnostics.addError(new Diagnosis(DiagnosisType.INVALID_DATA, "GZip file", "Unexpected EOF!"));
528            bIsCompliant = false;
529        }
530        // Compliance
531        if (gzipEntry.diagnostics.hasErrors() || gzipEntry.diagnostics.hasWarnings()) {
532            gzipEntry.bIsCompliant = false;
533        } else {
534            gzipEntry.bIsCompliant = true;
535        }
536        bIsCompliant &= gzipEntry.bIsCompliant;
537    }
538
539    /**
540     * Read and uncompress data into a buffer.
541     * @param b destination buffer for uncompressed data
542     * @param off offset in buffer
543     * @param len length of uncompressed data to read
544     * @return number of bytes uncompressed or -1
545     * @throws DataFormatException if the compressed data is in an unknown format
546     * @throws IOException if an I/O error occurs while reading data
547     */
548    protected int readInflated(byte[] b, int off, int len)
549                                    throws DataFormatException, IOException {
550        int inflated = 0;
551        while((inflated = inf.inflate(b, off, len)) == 0) {
552            if (inf.finished()) {
553                return -1;
554            } else if (inf.needsDictionary()) {
555                gzipEntry.diagnostics.addError(new Diagnosis(DiagnosisType.INVALID_DATA, "GZip file", "Unexpected EOF!"));
556                bIsCompliant = false;
557                throw new DataFormatException("Dictionary needed!");
558            } else if (inf.needsInput()) {
559                lastInput = pbin.read(inputBytes, 0, inputBytes.length);
560                if (lastInput == -1) {
561                    gzipEntry.diagnostics.addError(new Diagnosis(DiagnosisType.INVALID_DATA, "GZip file", "Unexpected EOF!"));
562                    bIsCompliant = false;
563                    throw new DataFormatException("Data missing!");
564                }
565                inf.setInput(inputBytes, 0, lastInput);
566            } else {
567                gzipEntry.diagnostics.addError(new Diagnosis(DiagnosisType.INVALID_DATA, "GZip file", "Unexpected EOF!"));
568                bIsCompliant = false;
569                throw new DataFormatException("Inflater malfunction!");
570            }
571        }
572        return inflated;
573    }
574
575    /**
576     * <code>InputStream</code> to expose GZip'ed data in a controlled fashion.
577     *
578     * @author nicl
579     */
580    protected static class GzipEntryInputStream extends InputStream {
581
582        /** GZip reader used to inflate. */
583        GzipReader reader;
584
585        /** Associated GZip entry. */
586        GzipEntry gzipEntry;
587
588        /** End of uncompressed file status. */
589        boolean bEof = false;
590
591        /** Small buffer used by the read() method. */
592        byte[] singleByteArray = new byte[1];
593
594        /**
595         * Construct input stream bound to a specific reader and entry.
596         * @param reader GZip reader
597         * @param gzipEntry GZip entry
598         */
599        public GzipEntryInputStream(GzipReader reader,
600                                    GzipEntry gzipEntry) {
601            this.reader = reader;
602            this.gzipEntry = gzipEntry;
603        }
604
605        @Override
606        public void close() throws IOException {
607            while (!bEof) {
608                skip(reader.skip_read_buffer.length);
609            }
610            reader = null;
611            gzipEntry = null;
612            singleByteArray = null;
613            bEof = true;
614        }
615
616        @Override
617        public int available() throws IOException {
618            return !bEof ? 1 : 0;
619        }
620
621        @Override
622        public int read() throws IOException {
623            return read(singleByteArray, 0, 1) != -1 ? (singleByteArray[0] & 255) : -1;
624        }
625
626        @Override
627        public int read(byte[] b) throws IOException {
628            return read(b, 0, b.length);
629        }
630
631        @Override
632        public int read(byte[] b, int off, int len) throws IOException {
633            if (bEof) {
634                return -1;
635            }
636            int read;
637            try {
638                read = reader.readInflated(b, off, len);
639            } catch (DataFormatException e) {
640                gzipEntry.diagnostics.addError(new Diagnosis(DiagnosisType.INVALID_DATA, "GZip file", "Unexpected EOF!"));
641                reader.bIsCompliant = false;
642                throw new IOException(e);
643            }
644            if (read != -1) {
645                reader.crc.update(b, off, read);
646            }
647            else {
648                int remaining = reader.inf.getRemaining();
649                if (remaining > reader.lastInput) {
650                    throw new IOException("Remaining larger than lastInput!");
651                }
652                reader.pbin.unread(reader.inputBytes, reader.lastInput - remaining,
653                                   remaining);
654                bEof = true;
655                reader.readTrailer(gzipEntry);
656            }
657            return read;
658        }
659
660        @Override
661        public long skip(long n) throws IOException {
662            if (bEof) {
663                return 0;
664            }
665            long remaining = n;
666            long skipped = 0;
667            long readLast = 0;
668            while (remaining > 0 && readLast != -1) {
669                remaining -= readLast;
670                skipped += readLast;
671                if (remaining > 0) {
672                    readLast = read(reader.skip_read_buffer, 0,
673                            (int) Math.min(remaining, SKIP_READ_BUFFER_SIZE));
674                }
675            }
676            return skipped;
677        }
678
679        @Override
680        public boolean markSupported() {
681            return false;
682        }
683
684        @Override
685        public synchronized void mark(int readlimit) {
686        }
687
688        @Override
689        public synchronized void reset() throws IOException {
690            throw new UnsupportedOperationException();
691        }
692
693    }
694
695}