gzread.c 21.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/* gzread.c -- zlib functions for reading gzip files
C
coffeys 已提交
26
 * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013, 2016 Mark Adler
27 28 29 30 31 32 33 34
 * For conditions of distribution and use, see copyright notice in zlib.h
 */

#include "gzguts.h"

/* Local functions */
local int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *));
local int gz_avail OF((gz_statep));
35
local int gz_look OF((gz_statep));
36
local int gz_decomp OF((gz_statep));
37
local int gz_fetch OF((gz_statep));
38
local int gz_skip OF((gz_statep, z_off64_t));
C
coffeys 已提交
39
local z_size_t gz_read OF((gz_statep, voidp, z_size_t));
40 41 42 43 44 45 46 47 48 49 50 51

/* Use read() to load a buffer -- return -1 on error, otherwise 0.  Read from
   state->fd, and update state->eof, state->err, and state->msg as appropriate.
   This function needs to loop on read(), since read() is not guaranteed to
   read the number of bytes requested, depending on the type of descriptor. */
local int gz_load(state, buf, len, have)
    gz_statep state;
    unsigned char *buf;
    unsigned len;
    unsigned *have;
{
    int ret;
C
coffeys 已提交
52
    unsigned get, max = ((unsigned)-1 >> 2) + 1;
53 54 55

    *have = 0;
    do {
C
coffeys 已提交
56 57 58 59
        get = len - *have;
        if (get > max)
            get = max;
        ret = read(state->fd, buf + *have, get);
60 61
        if (ret <= 0)
            break;
C
coffeys 已提交
62
        *have += (unsigned)ret;
63 64 65 66 67 68 69 70 71 72 73 74 75 76
    } while (*have < len);
    if (ret < 0) {
        gz_error(state, Z_ERRNO, zstrerror());
        return -1;
    }
    if (ret == 0)
        state->eof = 1;
    return 0;
}

/* Load up input buffer and set eof flag if last data loaded -- return -1 on
   error, 0 otherwise.  Note that the eof flag is set when the end of the input
   file is reached, even though there may be unused data in the buffer.  Once
   that data has been used, no more attempts will be made to read the file.
77 78 79
   If strm->avail_in != 0, then the current data is moved to the beginning of
   the input buffer, and then the remainder of the buffer is loaded with the
   available data from the input file. */
80 81 82
local int gz_avail(state)
    gz_statep state;
{
83
    unsigned got;
84 85
    z_streamp strm = &(state->strm);

86
    if (state->err != Z_OK && state->err != Z_BUF_ERROR)
87 88
        return -1;
    if (state->eof == 0) {
89 90 91 92 93 94 95 96 97 98
        if (strm->avail_in) {       /* copy what's there to the start */
            unsigned char *p = state->in;
            unsigned const char *q = strm->next_in;
            unsigned n = strm->avail_in;
            do {
                *p++ = *q++;
            } while (--n);
        }
        if (gz_load(state, state->in + strm->avail_in,
                    state->size - strm->avail_in, &got) == -1)
99
            return -1;
100
        strm->avail_in += got;
101 102 103 104 105
        strm->next_in = state->in;
    }
    return 0;
}

106
/* Look for gzip header, set up for inflate or copy.  state->x.have must be 0.
107 108 109
   If this is the first time in, allocate required memory.  state->how will be
   left unchanged if there is no more input data available, will be set to COPY
   if there is no gzip header and direct copying will be performed, or it will
110 111 112 113 114 115
   be set to GZIP for decompression.  If direct copying, then leftover input
   data from the input buffer will be copied to the output buffer.  In that
   case, all further file reads will be directly to either the output buffer or
   a user buffer.  If decompressing, the inflate state will be initialized.
   gz_look() will return 0 on success or -1 on failure. */
local int gz_look(state)
116 117 118 119 120 121 122
    gz_statep state;
{
    z_streamp strm = &(state->strm);

    /* allocate read buffers and inflate memory */
    if (state->size == 0) {
        /* allocate buffers */
123 124
        state->in = (unsigned char *)malloc(state->want);
        state->out = (unsigned char *)malloc(state->want << 1);
125
        if (state->in == NULL || state->out == NULL) {
C
coffeys 已提交
126 127
            free(state->out);
            free(state->in);
128 129 130 131 132 133 134 135 136 137 138
            gz_error(state, Z_MEM_ERROR, "out of memory");
            return -1;
        }
        state->size = state->want;

        /* allocate inflate memory */
        state->strm.zalloc = Z_NULL;
        state->strm.zfree = Z_NULL;
        state->strm.opaque = Z_NULL;
        state->strm.avail_in = 0;
        state->strm.next_in = Z_NULL;
139
        if (inflateInit2(&(state->strm), 15 + 16) != Z_OK) {    /* gunzip */
140 141 142 143 144 145 146 147
            free(state->out);
            free(state->in);
            state->size = 0;
            gz_error(state, Z_MEM_ERROR, "out of memory");
            return -1;
        }
    }

148 149
    /* get at least the magic bytes in the input buffer */
    if (strm->avail_in < 2) {
150 151 152 153 154 155
        if (gz_avail(state) == -1)
            return -1;
        if (strm->avail_in == 0)
            return 0;
    }

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
    /* look for gzip magic bytes -- if there, do gzip decoding (note: there is
       a logical dilemma here when considering the case of a partially written
       gzip file, to wit, if a single 31 byte is written, then we cannot tell
       whether this is a single-byte file, or just a partially written gzip
       file -- for here we assume that if a gzip file is being written, then
       the header will be written in a single operation, so that reading a
       single byte is sufficient indication that it is not a gzip file) */
    if (strm->avail_in > 1 &&
            strm->next_in[0] == 31 && strm->next_in[1] == 139) {
        inflateReset(strm);
        state->how = GZIP;
        state->direct = 0;
        return 0;
    }

    /* no gzip header -- if we were decoding gzip before, then this is trailing
       garbage.  Ignore the trailing garbage and finish. */
    if (state->direct == 0) {
        strm->avail_in = 0;
        state->eof = 1;
        state->x.have = 0;
        return 0;
178 179
    }

180 181 182 183
    /* doing raw i/o, copy any leftover input to output -- this assumes that
       the output buffer is larger than the input buffer, which also assures
       space for gzungetc() */
    state->x.next = state->out;
184
    if (strm->avail_in) {
185 186
        memcpy(state->x.next, strm->next_in, strm->avail_in);
        state->x.have = strm->avail_in;
187 188 189 190 191 192 193 194
        strm->avail_in = 0;
    }
    state->how = COPY;
    state->direct = 1;
    return 0;
}

/* Decompress from input to the provided next_out and avail_out in the state.
195 196 197 198
   On return, state->x.have and state->x.next point to the just decompressed
   data.  If the gzip stream completes, state->how is reset to LOOK to look for
   the next gzip stream or raw data, once state->x.have is depleted.  Returns 0
   on success, -1 on failure. */
199 200 201
local int gz_decomp(state)
    gz_statep state;
{
202
    int ret = Z_OK;
203 204 205 206 207 208 209 210 211 212
    unsigned had;
    z_streamp strm = &(state->strm);

    /* fill output buffer up to end of deflate stream */
    had = strm->avail_out;
    do {
        /* get more input for inflate() */
        if (strm->avail_in == 0 && gz_avail(state) == -1)
            return -1;
        if (strm->avail_in == 0) {
213 214
            gz_error(state, Z_BUF_ERROR, "unexpected end of file");
            break;
215 216 217 218 219 220
        }

        /* decompress and handle errors */
        ret = inflate(strm, Z_NO_FLUSH);
        if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) {
            gz_error(state, Z_STREAM_ERROR,
221
                     "internal error: inflate stream corrupt");
222 223 224 225 226 227 228 229
            return -1;
        }
        if (ret == Z_MEM_ERROR) {
            gz_error(state, Z_MEM_ERROR, "out of memory");
            return -1;
        }
        if (ret == Z_DATA_ERROR) {              /* deflate stream invalid */
            gz_error(state, Z_DATA_ERROR,
230
                     strm->msg == NULL ? "compressed data error" : strm->msg);
231 232 233 234
            return -1;
        }
    } while (strm->avail_out && ret != Z_STREAM_END);

235 236 237
    /* update available output */
    state->x.have = had - strm->avail_out;
    state->x.next = strm->next_out - state->x.have;
238

239 240 241
    /* if the gzip stream completed successfully, look for another */
    if (ret == Z_STREAM_END)
        state->how = LOOK;
242 243 244 245 246

    /* good decompression */
    return 0;
}

247
/* Fetch data and put it in the output buffer.  Assumes state->x.have is 0.
248 249
   Data is either copied from the input file or decompressed from the input
   file depending on state->how.  If state->how is LOOK, then a gzip header is
250 251 252 253
   looked for to determine whether to copy or decompress.  Returns -1 on error,
   otherwise 0.  gz_fetch() will leave state->how as COPY or GZIP unless the
   end of the input file has been reached and all data has been processed.  */
local int gz_fetch(state)
254 255 256 257
    gz_statep state;
{
    z_streamp strm = &(state->strm);

258 259 260 261 262 263 264 265 266 267 268 269 270
    do {
        switch(state->how) {
        case LOOK:      /* -> LOOK, COPY (only if never GZIP), or GZIP */
            if (gz_look(state) == -1)
                return -1;
            if (state->how == LOOK)
                return 0;
            break;
        case COPY:      /* -> COPY */
            if (gz_load(state, state->out, state->size << 1, &(state->x.have))
                    == -1)
                return -1;
            state->x.next = state->out;
271
            return 0;
272 273 274 275 276 277 278
        case GZIP:      /* -> GZIP or LOOK (if end of gzip stream) */
            strm->avail_out = state->size << 1;
            strm->next_out = state->out;
            if (gz_decomp(state) == -1)
                return -1;
        }
    } while (state->x.have == 0 && (!state->eof || strm->avail_in));
279 280 281 282 283 284 285 286 287 288 289 290 291
    return 0;
}

/* Skip len uncompressed bytes of output.  Return -1 on error, 0 on success. */
local int gz_skip(state, len)
    gz_statep state;
    z_off64_t len;
{
    unsigned n;

    /* skip over len bytes or reach end-of-file, whichever comes first */
    while (len)
        /* skip over whatever is in output buffer */
292 293 294 295 296 297
        if (state->x.have) {
            n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > len ?
                (unsigned)len : state->x.have;
            state->x.have -= n;
            state->x.next += n;
            state->x.pos += n;
298 299 300 301 302 303 304 305 306 307
            len -= n;
        }

        /* output buffer empty -- return if we're at the end of the input */
        else if (state->eof && state->strm.avail_in == 0)
            break;

        /* need more data to skip -- load up output buffer */
        else {
            /* get more output, looking for header if required */
308
            if (gz_fetch(state) == -1)
309 310 311 312 313
                return -1;
        }
    return 0;
}

C
coffeys 已提交
314 315 316 317 318 319
/* Read len bytes into buf from file, or less than len up to the end of the
   input.  Return the number of bytes read.  If zero is returned, either the
   end of file was reached, or there was an error.  state->err must be
   consulted in that case to determine which. */
local z_size_t gz_read(state, buf, len)
    gz_statep state;
320
    voidp buf;
C
coffeys 已提交
321
    z_size_t len;
322
{
C
coffeys 已提交
323 324
    z_size_t got;
    unsigned n;
325 326 327 328 329 330 331 332 333

    /* if len is zero, avoid unnecessary operations */
    if (len == 0)
        return 0;

    /* process a skip request */
    if (state->seek) {
        state->seek = 0;
        if (gz_skip(state, state->skip) == -1)
C
coffeys 已提交
334
            return 0;
335 336 337 338 339
    }

    /* get len bytes to buf, or less than len if at the end */
    got = 0;
    do {
C
coffeys 已提交
340 341 342 343 344
        /* set n to the maximum amount of len that fits in an unsigned int */
        n = -1;
        if (n > len)
            n = (unsigned)len;

345
        /* first just try copying data from the output buffer */
346
        if (state->x.have) {
C
coffeys 已提交
347 348
            if (state->x.have < n)
                n = state->x.have;
349 350 351
            memcpy(buf, state->x.next, n);
            state->x.next += n;
            state->x.have -= n;
352 353 354
        }

        /* output buffer empty -- return if we're at the end of the input */
C
coffeys 已提交
355
        else if (state->eof && state->strm.avail_in == 0) {
356
            state->past = 1;        /* tried to read past end */
357
            break;
358
        }
359 360 361

        /* need output data -- for small len or new stream load up our output
           buffer */
C
coffeys 已提交
362
        else if (state->how == LOOK || n < (state->size << 1)) {
363
            /* get more output, looking for header if required */
364
            if (gz_fetch(state) == -1)
C
coffeys 已提交
365
                return 0;
366
            continue;       /* no progress yet -- go back to copy above */
367 368 369 370 371 372
            /* the copy above assures that we will leave with space in the
               output buffer, allowing at least one gzungetc() to succeed */
        }

        /* large len -- read directly into user buffer */
        else if (state->how == COPY) {      /* read directly */
C
coffeys 已提交
373 374
            if (gz_load(state, (unsigned char *)buf, n, &n) == -1)
                return 0;
375 376 377 378
        }

        /* large len -- decompress directly into user buffer */
        else {  /* state->how == GZIP */
C
coffeys 已提交
379 380
            state->strm.avail_out = n;
            state->strm.next_out = (unsigned char *)buf;
381
            if (gz_decomp(state) == -1)
C
coffeys 已提交
382
                return 0;
383 384
            n = state->x.have;
            state->x.have = 0;
385 386 387 388 389 390
        }

        /* update progress */
        len -= n;
        buf = (char *)buf + n;
        got += n;
391
        state->x.pos += n;
392 393
    } while (len);

C
coffeys 已提交
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
    /* return number of bytes read into user buffer */
    return got;
}

/* -- see zlib.h -- */
int ZEXPORT gzread(file, buf, len)
    gzFile file;
    voidp buf;
    unsigned len;
{
    gz_statep state;

    /* get internal structure */
    if (file == NULL)
        return -1;
    state = (gz_statep)file;

    /* check that we're reading and that there's no (serious) error */
    if (state->mode != GZ_READ ||
            (state->err != Z_OK && state->err != Z_BUF_ERROR))
        return -1;

    /* since an int is returned, make sure len fits in one, otherwise return
       with an error (this avoids a flaw in the interface) */
    if ((int)len < 0) {
        gz_error(state, Z_STREAM_ERROR, "request does not fit in an int");
        return -1;
    }

    /* read len or fewer bytes to buf */
    len = (unsigned)gz_read(state, buf, len);

    /* check for an error */
    if (len == 0 && state->err != Z_OK && state->err != Z_BUF_ERROR)
        return -1;

    /* return the number of bytes read (this is assured to fit in an int) */
    return (int)len;
}

/* -- see zlib.h -- */
z_size_t ZEXPORT gzfread(buf, size, nitems, file)
    voidp buf;
    z_size_t size;
    z_size_t nitems;
    gzFile file;
{
    z_size_t len;
    gz_statep state;

    /* get internal structure */
    if (file == NULL)
        return 0;
    state = (gz_statep)file;

    /* check that we're reading and that there's no (serious) error */
    if (state->mode != GZ_READ ||
            (state->err != Z_OK && state->err != Z_BUF_ERROR))
        return 0;

    /* compute bytes to read -- error on overflow */
    len = nitems * size;
    if (size && len / size != nitems) {
        gz_error(state, Z_STREAM_ERROR, "request does not fit in a size_t");
        return 0;
    }

    /* read len or fewer bytes to buf, return the number of full items read */
    return len ? gz_read(state, buf, len) / size : 0;
463 464 465
}

/* -- see zlib.h -- */
466 467 468 469 470
#ifdef Z_PREFIX_SET
#  undef z_gzgetc
#else
#  undef gzgetc
#endif
471 472 473 474 475 476 477 478 479 480 481 482
int ZEXPORT gzgetc(file)
    gzFile file;
{
    int ret;
    unsigned char buf[1];
    gz_statep state;

    /* get internal structure */
    if (file == NULL)
        return -1;
    state = (gz_statep)file;

483 484 485
    /* check that we're reading and that there's no (serious) error */
    if (state->mode != GZ_READ ||
        (state->err != Z_OK && state->err != Z_BUF_ERROR))
486 487 488
        return -1;

    /* try output buffer (no need to check for skip request) */
489 490 491 492
    if (state->x.have) {
        state->x.have--;
        state->x.pos++;
        return *(state->x.next)++;
493 494
    }

C
coffeys 已提交
495 496
    /* nothing there -- try gz_read() */
    ret = (int)gz_read(state, buf, 1);
497 498 499
    return ret < 1 ? -1 : buf[0];
}

500 501 502 503 504 505
int ZEXPORT gzgetc_(file)
gzFile file;
{
    return gzgetc(file);
}

506 507 508 509 510 511 512 513 514 515 516 517
/* -- see zlib.h -- */
int ZEXPORT gzungetc(c, file)
    int c;
    gzFile file;
{
    gz_statep state;

    /* get internal structure */
    if (file == NULL)
        return -1;
    state = (gz_statep)file;

518 519 520
    /* check that we're reading and that there's no (serious) error */
    if (state->mode != GZ_READ ||
        (state->err != Z_OK && state->err != Z_BUF_ERROR))
521 522 523 524 525 526 527 528 529 530 531 532 533 534
        return -1;

    /* process a skip request */
    if (state->seek) {
        state->seek = 0;
        if (gz_skip(state, state->skip) == -1)
            return -1;
    }

    /* can't push EOF */
    if (c < 0)
        return -1;

    /* if output buffer empty, put byte at end (allows more pushing) */
535 536 537
    if (state->x.have == 0) {
        state->x.have = 1;
        state->x.next = state->out + (state->size << 1) - 1;
C
coffeys 已提交
538
        state->x.next[0] = (unsigned char)c;
539 540
        state->x.pos--;
        state->past = 0;
541 542 543 544
        return c;
    }

    /* if no room, give up (must have already done a gzungetc()) */
545 546
    if (state->x.have == (state->size << 1)) {
        gz_error(state, Z_DATA_ERROR, "out of room to push characters");
547 548 549 550
        return -1;
    }

    /* slide output data if needed and insert byte before existing data */
551 552
    if (state->x.next == state->out) {
        unsigned char *src = state->out + state->x.have;
553 554 555
        unsigned char *dest = state->out + (state->size << 1);
        while (src > state->out)
            *--dest = *--src;
556
        state->x.next = dest;
557
    }
558 559
    state->x.have++;
    state->x.next--;
C
coffeys 已提交
560
    state->x.next[0] = (unsigned char)c;
561 562
    state->x.pos--;
    state->past = 0;
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
    return c;
}

/* -- see zlib.h -- */
char * ZEXPORT gzgets(file, buf, len)
    gzFile file;
    char *buf;
    int len;
{
    unsigned left, n;
    char *str;
    unsigned char *eol;
    gz_statep state;

    /* check parameters and get internal structure */
    if (file == NULL || buf == NULL || len < 1)
        return NULL;
    state = (gz_statep)file;

582 583 584
    /* check that we're reading and that there's no (serious) error */
    if (state->mode != GZ_READ ||
        (state->err != Z_OK && state->err != Z_BUF_ERROR))
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
        return NULL;

    /* process a skip request */
    if (state->seek) {
        state->seek = 0;
        if (gz_skip(state, state->skip) == -1)
            return NULL;
    }

    /* copy output bytes up to new line or len - 1, whichever comes first --
       append a terminating zero to the string (we don't check for a zero in
       the contents, let the user worry about that) */
    str = buf;
    left = (unsigned)len - 1;
    if (left) do {
        /* assure that something is in the output buffer */
601 602 603 604 605
        if (state->x.have == 0 && gz_fetch(state) == -1)
            return NULL;                /* error */
        if (state->x.have == 0) {       /* end of file */
            state->past = 1;            /* read past end */
            break;                      /* return what we have */
606 607 608
        }

        /* look for end-of-line in current output buffer */
609 610
        n = state->x.have > left ? left : state->x.have;
        eol = (unsigned char *)memchr(state->x.next, '\n', n);
611
        if (eol != NULL)
612
            n = (unsigned)(eol - state->x.next) + 1;
613 614

        /* copy through end-of-line, or remainder if not found */
615 616 617 618
        memcpy(buf, state->x.next, n);
        state->x.have -= n;
        state->x.next += n;
        state->x.pos += n;
619 620 621 622
        left -= n;
        buf += n;
    } while (left && eol == NULL);

623 624 625
    /* return terminated string, or if nothing, end of file */
    if (buf == str)
        return NULL;
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
    buf[0] = 0;
    return str;
}

/* -- see zlib.h -- */
int ZEXPORT gzdirect(file)
    gzFile file;
{
    gz_statep state;

    /* get internal structure */
    if (file == NULL)
        return 0;
    state = (gz_statep)file;

    /* if the state is not known, but we can find out, then do so (this is
       mainly for right after a gzopen() or gzdopen()) */
643 644
    if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0)
        (void)gz_look(state);
645

646
    /* return 1 if transparent, 0 if processing a gzip stream */
647 648 649 650 651 652 653
    return state->direct;
}

/* -- see zlib.h -- */
int ZEXPORT gzclose_r(file)
    gzFile file;
{
654
    int ret, err;
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
    gz_statep state;

    /* get internal structure */
    if (file == NULL)
        return Z_STREAM_ERROR;
    state = (gz_statep)file;

    /* check that we're reading */
    if (state->mode != GZ_READ)
        return Z_STREAM_ERROR;

    /* free memory and close file */
    if (state->size) {
        inflateEnd(&(state->strm));
        free(state->out);
        free(state->in);
    }
672
    err = state->err == Z_BUF_ERROR ? Z_BUF_ERROR : Z_OK;
673 674 675 676
    gz_error(state, Z_OK, NULL);
    free(state->path);
    ret = close(state->fd);
    free(state);
677
    return ret ? Z_ERRNO : err;
678
}