gzlib.c 16.0 KB
Newer Older
M
Mark Adler 已提交
1
/* gzlib.c -- zlib functions common to reading and writing gzip files
M
Mark Adler 已提交
2
 * Copyright (C) 2004, 2010, 2011, 2012, 2013 Mark Adler
M
Mark Adler 已提交
3 4 5 6 7
 * For conditions of distribution and use, see copyright notice in zlib.h
 */

#include "gzguts.h"

8
#if defined(_WIN32) && !defined(__BORLANDC__)
9 10
#  define LSEEK _lseeki64
#else
M
Mark Adler 已提交
11
#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
M
Mark Adler 已提交
12 13 14 15
#  define LSEEK lseek64
#else
#  define LSEEK lseek
#endif
16
#endif
M
Mark Adler 已提交
17 18 19

/* Local functions */
local void gz_reset OF((gz_statep));
20
local gzFile gz_open OF((const void *, int, const char *));
M
Mark Adler 已提交
21

M
Mark Adler 已提交
22
#if defined UNDER_CE
M
Mark Adler 已提交
23

M
Mark Adler 已提交
24 25 26
/* Map the Windows error number in ERROR to a locale-dependent error message
   string and return a pointer to it.  Typically, the values for ERROR come
   from GetLastError.
M
Mark Adler 已提交
27

M
Mark Adler 已提交
28 29
   The string pointed to shall not be modified by the application, but may be
   overwritten by a subsequent call to gz_strwinerror
M
Mark Adler 已提交
30

M
Mark Adler 已提交
31 32
   The gz_strwinerror function does not change the current setting of
   GetLastError. */
M
Mark Adler 已提交
33
char ZLIB_INTERNAL *gz_strwinerror (error)
M
Mark Adler 已提交
34 35 36 37 38 39 40
     DWORD error;
{
    static char buf[1024];

    wchar_t *msgbuf;
    DWORD lasterr = GetLastError();
    DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
M
Mark Adler 已提交
41 42 43 44 45 46 47
        | FORMAT_MESSAGE_ALLOCATE_BUFFER,
        NULL,
        error,
        0, /* Default language */
        (LPVOID)&msgbuf,
        0,
        NULL);
M
Mark Adler 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
    if (chars != 0) {
        /* If there is an \r\n appended, zap it.  */
        if (chars >= 2
            && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') {
            chars -= 2;
            msgbuf[chars] = 0;
        }

        if (chars > sizeof (buf) - 1) {
            chars = sizeof (buf) - 1;
            msgbuf[chars] = 0;
        }

        wcstombs(buf, msgbuf, chars + 1);
        LocalFree(msgbuf);
    }
    else {
        sprintf(buf, "unknown win32 error (%ld)", error);
    }

    SetLastError(lasterr);
    return buf;
}

M
Mark Adler 已提交
72
#endif /* UNDER_CE */
M
Mark Adler 已提交
73 74 75 76 77

/* Reset gzip file state */
local void gz_reset(state)
    gz_statep state;
{
78
    state->x.have = 0;              /* no output data available */
M
Mark Adler 已提交
79 80
    if (state->mode == GZ_READ) {   /* for reading ... */
        state->eof = 0;             /* not at end of file */
81
        state->past = 0;            /* have not read past end yet */
M
Mark Adler 已提交
82
        state->how = LOOK;          /* look for gzip header */
M
Mark Adler 已提交
83
    }
M
Mark Adler 已提交
84 85
    state->seek = 0;                /* no seek request pending */
    gz_error(state, Z_OK, NULL);    /* clear error */
86
    state->x.pos = 0;               /* no uncompressed data yet */
M
Mark Adler 已提交
87
    state->strm.avail_in = 0;       /* no input data yet */
M
Mark Adler 已提交
88 89 90
}

/* Open a gzip file either by name or file descriptor. */
M
Mark Adler 已提交
91
local gzFile gz_open(path, fd, mode)
92
    const void *path;
M
Mark Adler 已提交
93 94 95 96
    int fd;
    const char *mode;
{
    gz_statep state;
97
    size_t len;
98
    int oflag;
99 100 101 102 103 104
#ifdef O_CLOEXEC
    int cloexec = 0;
#endif
#ifdef O_EXCL
    int exclusive = 0;
#endif
M
Mark Adler 已提交
105

M
Mark Adler 已提交
106 107 108 109
    /* check input */
    if (path == NULL)
        return NULL;

M
Mark Adler 已提交
110
    /* allocate gzFile structure to return */
111
    state = (gz_statep)malloc(sizeof(gz_state));
M
Mark Adler 已提交
112 113 114 115 116 117 118 119 120 121
    if (state == NULL)
        return NULL;
    state->size = 0;            /* no buffers allocated yet */
    state->want = GZBUFSIZE;    /* requested buffer size */
    state->msg = NULL;          /* no error message yet */

    /* interpret mode */
    state->mode = GZ_NONE;
    state->level = Z_DEFAULT_COMPRESSION;
    state->strategy = Z_DEFAULT_STRATEGY;
122
    state->direct = 0;
M
Mark Adler 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
    while (*mode) {
        if (*mode >= '0' && *mode <= '9')
            state->level = *mode - '0';
        else
            switch (*mode) {
            case 'r':
                state->mode = GZ_READ;
                break;
#ifndef NO_GZCOMPRESS
            case 'w':
                state->mode = GZ_WRITE;
                break;
            case 'a':
                state->mode = GZ_APPEND;
                break;
#endif
            case '+':       /* can't read and write at the same time */
                free(state);
                return NULL;
            case 'b':       /* ignore -- will request binary anyway */
                break;
144
#ifdef O_CLOEXEC
145 146 147
            case 'e':
                cloexec = 1;
                break;
148 149
#endif
#ifdef O_EXCL
150 151 152
            case 'x':
                exclusive = 1;
                break;
153
#endif
M
Mark Adler 已提交
154 155 156 157 158 159 160 161 162 163 164
            case 'f':
                state->strategy = Z_FILTERED;
                break;
            case 'h':
                state->strategy = Z_HUFFMAN_ONLY;
                break;
            case 'R':
                state->strategy = Z_RLE;
                break;
            case 'F':
                state->strategy = Z_FIXED;
M
Mark Adler 已提交
165
                break;
166 167
            case 'T':
                state->direct = 1;
M
Mark Adler 已提交
168
                break;
M
Mark Adler 已提交
169 170 171 172 173 174 175 176 177 178 179 180
            default:        /* could consider as an error, but just ignore */
                ;
            }
        mode++;
    }

    /* must provide an "r", "w", or "a" */
    if (state->mode == GZ_NONE) {
        free(state);
        return NULL;
    }

181 182 183 184 185 186 187 188 189
    /* can't force transparent read */
    if (state->mode == GZ_READ) {
        if (state->direct) {
            free(state);
            return NULL;
        }
        state->direct = 1;      /* for empty file */
    }

M
Mark Adler 已提交
190
    /* save the path name for error messages */
191 192 193 194 195 196 197 198
#ifdef _WIN32
    if (fd == -2) {
        len = wcstombs(NULL, path, 0);
        if (len == (size_t)-1)
            len = 0;
    }
    else
#endif
199 200
        len = strlen((const char *)path);
    state->path = (char *)malloc(len + 1);
M
Mark Adler 已提交
201 202 203 204
    if (state->path == NULL) {
        free(state);
        return NULL;
    }
205 206 207 208 209 210 211 212
#ifdef _WIN32
    if (fd == -2)
        if (len)
            wcstombs(state->path, path, len + 1);
        else
            *(state->path) = 0;
    else
#endif
213 214 215
#if !defined(NO_snprintf) && !defined(NO_vsnprintf)
        snprintf(state->path, len + 1, "%s", (const char *)path);
#else
216
        strcpy(state->path, path);
217
#endif
M
Mark Adler 已提交
218

219 220
    /* compute the flags for open() */
    oflag =
M
Mark Adler 已提交
221
#ifdef O_LARGEFILE
222
        O_LARGEFILE |
M
Mark Adler 已提交
223 224
#endif
#ifdef O_BINARY
225
        O_BINARY |
226 227
#endif
#ifdef O_CLOEXEC
228
        (cloexec ? O_CLOEXEC : 0) |
M
Mark Adler 已提交
229
#endif
230 231 232
        (state->mode == GZ_READ ?
         O_RDONLY :
         (O_WRONLY | O_CREAT |
233
#ifdef O_EXCL
234 235 236 237 238 239 240 241 242 243
          (exclusive ? O_EXCL : 0) |
#endif
          (state->mode == GZ_WRITE ?
           O_TRUNC :
           O_APPEND)));

    /* open the file with the appropriate flags (or just use fd) */
    state->fd = fd > -1 ? fd : (
#ifdef _WIN32
        fd == -2 ? _wopen(path, oflag, 0666) :
244
#endif
245
        open((const char *)path, oflag, 0666));
M
Mark Adler 已提交
246
    if (state->fd == -1) {
M
Mark Adler 已提交
247
        free(state->path);
M
Mark Adler 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
        free(state);
        return NULL;
    }
    if (state->mode == GZ_APPEND)
        state->mode = GZ_WRITE;         /* simplify later checks */

    /* save the current position for rewinding (only if reading) */
    if (state->mode == GZ_READ) {
        state->start = LSEEK(state->fd, 0, SEEK_CUR);
        if (state->start == -1) state->start = 0;
    }

    /* initialize stream */
    gz_reset(state);

    /* return stream */
    return (gzFile)state;
}

/* -- see zlib.h -- */
gzFile ZEXPORT gzopen(path, mode)
    const char *path;
    const char *mode;
{
M
Mark Adler 已提交
272
    return gz_open(path, -1, mode);
M
Mark Adler 已提交
273 274 275 276 277 278 279
}

/* -- see zlib.h -- */
gzFile ZEXPORT gzopen64(path, mode)
    const char *path;
    const char *mode;
{
M
Mark Adler 已提交
280
    return gz_open(path, -1, mode);
M
Mark Adler 已提交
281 282 283 284 285 286 287
}

/* -- see zlib.h -- */
gzFile ZEXPORT gzdopen(fd, mode)
    int fd;
    const char *mode;
{
M
Mark Adler 已提交
288 289
    char *path;         /* identifier for error messages */
    gzFile gz;
M
Mark Adler 已提交
290

291
    if (fd == -1 || (path = (char *)malloc(7 + 3 * sizeof(int))) == NULL)
M
Mark Adler 已提交
292
        return NULL;
293 294 295
#if !defined(NO_snprintf) && !defined(NO_vsnprintf)
    snprintf(path, 7 + 3 * sizeof(int), "<fd:%d>", fd); /* for debugging */
#else
M
Mark Adler 已提交
296
    sprintf(path, "<fd:%d>", fd);   /* for debugging */
297
#endif
M
Mark Adler 已提交
298 299 300
    gz = gz_open(path, fd, mode);
    free(path);
    return gz;
M
Mark Adler 已提交
301 302 303
}

/* -- see zlib.h -- */
304 305
#ifdef _WIN32
gzFile ZEXPORT gzopen_w(path, mode)
306
    const wchar_t *path;
307 308 309 310 311 312 313
    const char *mode;
{
    return gz_open(path, -2, mode);
}
#endif

/* -- see zlib.h -- */
M
Mark Adler 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
int ZEXPORT gzbuffer(file, size)
    gzFile file;
    unsigned size;
{
    gz_statep state;

    /* get internal structure and check integrity */
    if (file == NULL)
        return -1;
    state = (gz_statep)file;
    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
        return -1;

    /* make sure we haven't already allocated memory */
    if (state->size != 0)
        return -1;

    /* check and set requested size */
332 333
    if (size < 2)
        size = 2;               /* need two bytes to check magic header */
M
Mark Adler 已提交
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
    state->want = size;
    return 0;
}

/* -- see zlib.h -- */
int ZEXPORT gzrewind(file)
    gzFile file;
{
    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 error */
350 351
    if (state->mode != GZ_READ ||
            (state->err != Z_OK && state->err != Z_BUF_ERROR))
M
Mark Adler 已提交
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
        return -1;

    /* back up and start over */
    if (LSEEK(state->fd, state->start, SEEK_SET) == -1)
        return -1;
    gz_reset(state);
    return 0;
}

/* -- see zlib.h -- */
z_off64_t ZEXPORT gzseek64(file, offset, whence)
    gzFile file;
    z_off64_t offset;
    int whence;
{
    unsigned n;
    z_off64_t ret;
    gz_statep state;

    /* get internal structure and check integrity */
    if (file == NULL)
        return -1;
    state = (gz_statep)file;
    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
        return -1;

    /* check that there's no error */
379
    if (state->err != Z_OK && state->err != Z_BUF_ERROR)
M
Mark Adler 已提交
380 381 382 383 384 385 386 387
        return -1;

    /* can only seek from start or relative to current position */
    if (whence != SEEK_SET && whence != SEEK_CUR)
        return -1;

    /* normalize offset to a SEEK_CUR specification */
    if (whence == SEEK_SET)
388
        offset -= state->x.pos;
M
Mark Adler 已提交
389 390 391
    else if (state->seek)
        offset += state->skip;
    state->seek = 0;
M
Mark Adler 已提交
392 393

    /* if within raw area while reading, just go there */
M
Mark Adler 已提交
394
    if (state->mode == GZ_READ && state->how == COPY &&
395 396
            state->x.pos + offset >= 0) {
        ret = LSEEK(state->fd, offset - state->x.have, SEEK_CUR);
M
Mark Adler 已提交
397 398
        if (ret == -1)
            return -1;
399
        state->x.have = 0;
M
Mark Adler 已提交
400
        state->eof = 0;
401
        state->past = 0;
M
Mark Adler 已提交
402 403 404
        state->seek = 0;
        gz_error(state, Z_OK, NULL);
        state->strm.avail_in = 0;
405 406
        state->x.pos += offset;
        return state->x.pos;
M
Mark Adler 已提交
407 408 409 410 411 412
    }

    /* calculate skip amount, rewinding if needed for back seek when reading */
    if (offset < 0) {
        if (state->mode != GZ_READ)         /* writing -- can't go backwards */
            return -1;
413
        offset += state->x.pos;
M
Mark Adler 已提交
414 415 416 417 418 419
        if (offset < 0)                     /* before start of file! */
            return -1;
        if (gzrewind(file) == -1)           /* rewind, then skip to offset */
            return -1;
    }

M
Mark Adler 已提交
420
    /* if reading, skip what's in output buffer (one less gzgetc() check) */
M
Mark Adler 已提交
421
    if (state->mode == GZ_READ) {
422 423 424 425 426
        n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > offset ?
            (unsigned)offset : state->x.have;
        state->x.have -= n;
        state->x.next += n;
        state->x.pos += n;
M
Mark Adler 已提交
427 428 429 430 431 432 433 434
        offset -= n;
    }

    /* request skip (if not zero) */
    if (offset) {
        state->seek = 1;
        state->skip = offset;
    }
435
    return state->x.pos + offset;
M
Mark Adler 已提交
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 463
}

/* -- see zlib.h -- */
z_off_t ZEXPORT gzseek(file, offset, whence)
    gzFile file;
    z_off_t offset;
    int whence;
{
    z_off64_t ret;

    ret = gzseek64(file, (z_off64_t)offset, whence);
    return ret == (z_off_t)ret ? (z_off_t)ret : -1;
}

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

    /* get internal structure and check integrity */
    if (file == NULL)
        return -1;
    state = (gz_statep)file;
    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
        return -1;

    /* return position */
464
    return state->x.pos + (state->seek ? state->skip : 0);
M
Mark Adler 已提交
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
}

/* -- see zlib.h -- */
z_off_t ZEXPORT gztell(file)
    gzFile file;
{
    z_off64_t ret;

    ret = gztell64(file);
    return ret == (z_off_t)ret ? (z_off_t)ret : -1;
}

/* -- see zlib.h -- */
z_off64_t ZEXPORT gzoffset64(file)
    gzFile file;
{
    z_off64_t offset;
    gz_statep state;

    /* get internal structure and check integrity */
    if (file == NULL)
        return -1;
    state = (gz_statep)file;
    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
        return -1;

    /* compute and return effective offset in file */
    offset = LSEEK(state->fd, 0, SEEK_CUR);
    if (offset == -1)
        return -1;
    if (state->mode == GZ_READ)             /* reading */
        offset -= state->strm.avail_in;     /* don't count buffered input */
    return offset;
}

/* -- see zlib.h -- */
z_off_t ZEXPORT gzoffset(file)
    gzFile file;
{
    z_off64_t ret;

    ret = gzoffset64(file);
    return ret == (z_off_t)ret ? (z_off_t)ret : -1;
}

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

    /* get internal structure and check integrity */
    if (file == NULL)
M
Mark Adler 已提交
518
        return 0;
M
Mark Adler 已提交
519 520
    state = (gz_statep)file;
    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
M
Mark Adler 已提交
521
        return 0;
M
Mark Adler 已提交
522 523

    /* return end-of-file state */
524
    return state->mode == GZ_READ ? state->past : 0;
M
Mark Adler 已提交
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
}

/* -- see zlib.h -- */
const char * ZEXPORT gzerror(file, errnum)
    gzFile file;
    int *errnum;
{
    gz_statep state;

    /* get internal structure and check integrity */
    if (file == NULL)
        return NULL;
    state = (gz_statep)file;
    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
        return NULL;

    /* return error information */
M
Mark Adler 已提交
542 543
    if (errnum != NULL)
        *errnum = state->err;
544 545
    return state->err == Z_MEM_ERROR ? "out of memory" :
                                       (state->msg == NULL ? "" : state->msg);
M
Mark Adler 已提交
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
}

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

    /* get internal structure and check integrity */
    if (file == NULL)
        return;
    state = (gz_statep)file;
    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
        return;

    /* clear error and end-of-file */
562
    if (state->mode == GZ_READ) {
M
Mark Adler 已提交
563
        state->eof = 0;
564 565
        state->past = 0;
    }
M
Mark Adler 已提交
566 567 568 569
    gz_error(state, Z_OK, NULL);
}

/* Create an error message in allocated memory and set state->err and
M
Mark Adler 已提交
570
   state->msg accordingly.  Free any previous error message already there.  Do
M
Mark Adler 已提交
571
   not try to free or allocate space if the error is Z_MEM_ERROR (out of
M
Mark Adler 已提交
572 573 574
   memory).  Simply save the error message as a static string.  If there is an
   allocation failure constructing the error message, then convert the error to
   out of memory. */
M
Mark Adler 已提交
575
void ZLIB_INTERNAL gz_error(state, err, msg)
M
Mark Adler 已提交
576 577
    gz_statep state;
    int err;
M
Mark Adler 已提交
578
    const char *msg;
M
Mark Adler 已提交
579 580 581 582 583 584 585 586
{
    /* free previously allocated message and clear */
    if (state->msg != NULL) {
        if (state->err != Z_MEM_ERROR)
            free(state->msg);
        state->msg = NULL;
    }

587 588 589 590
    /* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */
    if (err != Z_OK && err != Z_BUF_ERROR)
        state->x.have = 0;

M
Mark Adler 已提交
591 592 593 594 595
    /* set error code, and if no message, then done */
    state->err = err;
    if (msg == NULL)
        return;

596 597
    /* for an out of memory error, return literal string when requested */
    if (err == Z_MEM_ERROR)
M
Mark Adler 已提交
598 599 600
        return;

    /* construct error message with path */
601 602
    if ((state->msg = (char *)malloc(strlen(state->path) + strlen(msg) + 3)) ==
            NULL) {
M
Mark Adler 已提交
603 604 605
        state->err = Z_MEM_ERROR;
        return;
    }
606 607 608 609
#if !defined(NO_snprintf) && !defined(NO_vsnprintf)
    snprintf(state->msg, strlen(state->path) + strlen(msg) + 3,
             "%s%s%s", state->path, ": ", msg);
#else
M
Mark Adler 已提交
610 611 612
    strcpy(state->msg, state->path);
    strcat(state->msg, ": ");
    strcat(state->msg, msg);
613
#endif
M
Mark Adler 已提交
614 615 616
    return;
}

M
Mark Adler 已提交
617 618 619 620 621
#ifndef INT_MAX
/* portably return maximum value for an int (when limits.h presumed not
   available) -- we need to do this to cover cases where 2's complement not
   used, since C standard permits 1's complement and sign-bit representations,
   otherwise we could just use ((unsigned)-1) >> 1 */
M
Mark Adler 已提交
622
unsigned ZLIB_INTERNAL gz_intmax()
M
Mark Adler 已提交
623 624 625 626 627 628 629 630 631 632 633 634
{
    unsigned p, q;

    p = 1;
    do {
        q = p;
        p <<= 1;
        p++;
    } while (p > q);
    return q >> 1;
}
#endif