/* gzread.c -- zlib functions for reading gzip files1* Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013, 2016 Mark Adler2* For conditions of distribution and use, see copyright notice in zlib.h3*/45#include "gzguts.h"67/* Local functions */8local int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *));9local int gz_avail OF((gz_statep));10local int gz_look OF((gz_statep));11local int gz_decomp OF((gz_statep));12local int gz_fetch OF((gz_statep));13local int gz_skip OF((gz_statep, z_off64_t));14local z_size_t gz_read OF((gz_statep, voidp, z_size_t));1516/* Use read() to load a buffer -- return -1 on error, otherwise 0. Read from17state->fd, and update state->eof, state->err, and state->msg as appropriate.18This function needs to loop on read(), since read() is not guaranteed to19read the number of bytes requested, depending on the type of descriptor. */20local int gz_load(state, buf, len, have)21gz_statep state;22unsigned char *buf;23unsigned len;24unsigned *have;25{26int ret;27unsigned get, max = ((unsigned)-1 >> 2) + 1;2829*have = 0;30do {31get = len - *have;32if (get > max)33get = max;34ret = read(state->fd, buf + *have, get);35if (ret <= 0)36break;37*have += (unsigned)ret;38} while (*have < len);39if (ret < 0) {40gz_error(state, Z_ERRNO, zstrerror());41return -1;42}43if (ret == 0)44state->eof = 1;45return 0;46}4748/* Load up input buffer and set eof flag if last data loaded -- return -1 on49error, 0 otherwise. Note that the eof flag is set when the end of the input50file is reached, even though there may be unused data in the buffer. Once51that data has been used, no more attempts will be made to read the file.52If strm->avail_in != 0, then the current data is moved to the beginning of53the input buffer, and then the remainder of the buffer is loaded with the54available data from the input file. */55local int gz_avail(state)56gz_statep state;57{58unsigned got;59z_streamp strm = &(state->strm);6061if (state->err != Z_OK && state->err != Z_BUF_ERROR)62return -1;63if (state->eof == 0) {64if (strm->avail_in) { /* copy what's there to the start */65unsigned char *p = state->in;66unsigned const char *q = strm->next_in;67unsigned n = strm->avail_in;68do {69*p++ = *q++;70} while (--n);71}72if (gz_load(state, state->in + strm->avail_in,73state->size - strm->avail_in, &got) == -1)74return -1;75strm->avail_in += got;76strm->next_in = state->in;77}78return 0;79}8081/* Look for gzip header, set up for inflate or copy. state->x.have must be 0.82If this is the first time in, allocate required memory. state->how will be83left unchanged if there is no more input data available, will be set to COPY84if there is no gzip header and direct copying will be performed, or it will85be set to GZIP for decompression. If direct copying, then leftover input86data from the input buffer will be copied to the output buffer. In that87case, all further file reads will be directly to either the output buffer or88a user buffer. If decompressing, the inflate state will be initialized.89gz_look() will return 0 on success or -1 on failure. */90local int gz_look(state)91gz_statep state;92{93z_streamp strm = &(state->strm);9495/* allocate read buffers and inflate memory */96if (state->size == 0) {97/* allocate buffers */98state->in = (unsigned char *)malloc(state->want);99state->out = (unsigned char *)malloc(state->want << 1);100if (state->in == NULL || state->out == NULL) {101free(state->out);102free(state->in);103gz_error(state, Z_MEM_ERROR, "out of memory");104return -1;105}106state->size = state->want;107108/* allocate inflate memory */109state->strm.zalloc = Z_NULL;110state->strm.zfree = Z_NULL;111state->strm.opaque = Z_NULL;112state->strm.avail_in = 0;113state->strm.next_in = Z_NULL;114if (inflateInit2(&(state->strm), 15 + 16) != Z_OK) { /* gunzip */115free(state->out);116free(state->in);117state->size = 0;118gz_error(state, Z_MEM_ERROR, "out of memory");119return -1;120}121}122123/* get at least the magic bytes in the input buffer */124if (strm->avail_in < 2) {125if (gz_avail(state) == -1)126return -1;127if (strm->avail_in == 0)128return 0;129}130131/* look for gzip magic bytes -- if there, do gzip decoding (note: there is132a logical dilemma here when considering the case of a partially written133gzip file, to wit, if a single 31 byte is written, then we cannot tell134whether this is a single-byte file, or just a partially written gzip135file -- for here we assume that if a gzip file is being written, then136the header will be written in a single operation, so that reading a137single byte is sufficient indication that it is not a gzip file) */138if (strm->avail_in > 1 &&139strm->next_in[0] == 31 && strm->next_in[1] == 139) {140inflateReset(strm);141state->how = GZIP;142state->direct = 0;143return 0;144}145146/* no gzip header -- if we were decoding gzip before, then this is trailing147garbage. Ignore the trailing garbage and finish. */148if (state->direct == 0) {149strm->avail_in = 0;150state->eof = 1;151state->x.have = 0;152return 0;153}154155/* doing raw i/o, copy any leftover input to output -- this assumes that156the output buffer is larger than the input buffer, which also assures157space for gzungetc() */158state->x.next = state->out;159if (strm->avail_in) {160memcpy(state->x.next, strm->next_in, strm->avail_in);161state->x.have = strm->avail_in;162strm->avail_in = 0;163}164state->how = COPY;165state->direct = 1;166return 0;167}168169/* Decompress from input to the provided next_out and avail_out in the state.170On return, state->x.have and state->x.next point to the just decompressed171data. If the gzip stream completes, state->how is reset to LOOK to look for172the next gzip stream or raw data, once state->x.have is depleted. Returns 0173on success, -1 on failure. */174local int gz_decomp(state)175gz_statep state;176{177int ret = Z_OK;178unsigned had;179z_streamp strm = &(state->strm);180181/* fill output buffer up to end of deflate stream */182had = strm->avail_out;183do {184/* get more input for inflate() */185if (strm->avail_in == 0 && gz_avail(state) == -1)186return -1;187if (strm->avail_in == 0) {188gz_error(state, Z_BUF_ERROR, "unexpected end of file");189break;190}191192/* decompress and handle errors */193ret = inflate(strm, Z_NO_FLUSH);194if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) {195gz_error(state, Z_STREAM_ERROR,196"internal error: inflate stream corrupt");197return -1;198}199if (ret == Z_MEM_ERROR) {200gz_error(state, Z_MEM_ERROR, "out of memory");201return -1;202}203if (ret == Z_DATA_ERROR) { /* deflate stream invalid */204gz_error(state, Z_DATA_ERROR,205strm->msg == NULL ? "compressed data error" : strm->msg);206return -1;207}208} while (strm->avail_out && ret != Z_STREAM_END);209210/* update available output */211state->x.have = had - strm->avail_out;212state->x.next = strm->next_out - state->x.have;213214/* if the gzip stream completed successfully, look for another */215if (ret == Z_STREAM_END)216state->how = LOOK;217218/* good decompression */219return 0;220}221222/* Fetch data and put it in the output buffer. Assumes state->x.have is 0.223Data is either copied from the input file or decompressed from the input224file depending on state->how. If state->how is LOOK, then a gzip header is225looked for to determine whether to copy or decompress. Returns -1 on error,226otherwise 0. gz_fetch() will leave state->how as COPY or GZIP unless the227end of the input file has been reached and all data has been processed. */228local int gz_fetch(state)229gz_statep state;230{231z_streamp strm = &(state->strm);232233do {234switch(state->how) {235case LOOK: /* -> LOOK, COPY (only if never GZIP), or GZIP */236if (gz_look(state) == -1)237return -1;238if (state->how == LOOK)239return 0;240break;241case COPY: /* -> COPY */242if (gz_load(state, state->out, state->size << 1, &(state->x.have))243== -1)244return -1;245state->x.next = state->out;246return 0;247case GZIP: /* -> GZIP or LOOK (if end of gzip stream) */248strm->avail_out = state->size << 1;249strm->next_out = state->out;250if (gz_decomp(state) == -1)251return -1;252}253} while (state->x.have == 0 && (!state->eof || strm->avail_in));254return 0;255}256257/* Skip len uncompressed bytes of output. Return -1 on error, 0 on success. */258local int gz_skip(state, len)259gz_statep state;260z_off64_t len;261{262unsigned n;263264/* skip over len bytes or reach end-of-file, whichever comes first */265while (len)266/* skip over whatever is in output buffer */267if (state->x.have) {268n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > len ?269(unsigned)len : state->x.have;270state->x.have -= n;271state->x.next += n;272state->x.pos += n;273len -= n;274}275276/* output buffer empty -- return if we're at the end of the input */277else if (state->eof && state->strm.avail_in == 0)278break;279280/* need more data to skip -- load up output buffer */281else {282/* get more output, looking for header if required */283if (gz_fetch(state) == -1)284return -1;285}286return 0;287}288289/* Read len bytes into buf from file, or less than len up to the end of the290input. Return the number of bytes read. If zero is returned, either the291end of file was reached, or there was an error. state->err must be292consulted in that case to determine which. */293local z_size_t gz_read(state, buf, len)294gz_statep state;295voidp buf;296z_size_t len;297{298z_size_t got;299unsigned n;300301/* if len is zero, avoid unnecessary operations */302if (len == 0)303return 0;304305/* process a skip request */306if (state->seek) {307state->seek = 0;308if (gz_skip(state, state->skip) == -1)309return 0;310}311312/* get len bytes to buf, or less than len if at the end */313got = 0;314do {315/* set n to the maximum amount of len that fits in an unsigned int */316n = -1;317if (n > len)318n = (int)len;319320/* first just try copying data from the output buffer */321if (state->x.have) {322if (state->x.have < n)323n = state->x.have;324memcpy(buf, state->x.next, n);325state->x.next += n;326state->x.have -= n;327}328329/* output buffer empty -- return if we're at the end of the input */330else if (state->eof && state->strm.avail_in == 0) {331state->past = 1; /* tried to read past end */332break;333}334335/* need output data -- for small len or new stream load up our output336buffer */337else if (state->how == LOOK || n < (state->size << 1)) {338/* get more output, looking for header if required */339if (gz_fetch(state) == -1)340return 0;341continue; /* no progress yet -- go back to copy above */342/* the copy above assures that we will leave with space in the343output buffer, allowing at least one gzungetc() to succeed */344}345346/* large len -- read directly into user buffer */347else if (state->how == COPY) { /* read directly */348if (gz_load(state, (unsigned char *)buf, n, &n) == -1)349return 0;350}351352/* large len -- decompress directly into user buffer */353else { /* state->how == GZIP */354state->strm.avail_out = n;355state->strm.next_out = (unsigned char *)buf;356if (gz_decomp(state) == -1)357return 0;358n = state->x.have;359state->x.have = 0;360}361362/* update progress */363len -= n;364buf = (char *)buf + n;365got += n;366state->x.pos += n;367} while (len);368369/* return number of bytes read into user buffer */370return got;371}372373/* -- see zlib.h -- */374int ZEXPORT gzread(file, buf, len)375gzFile file;376voidp buf;377unsigned len;378{379gz_statep state;380381/* get internal structure */382if (file == NULL)383return -1;384state = (gz_statep)file;385386/* check that we're reading and that there's no (serious) error */387if (state->mode != GZ_READ ||388(state->err != Z_OK && state->err != Z_BUF_ERROR))389return -1;390391/* since an int is returned, make sure len fits in one, otherwise return392with an error (this avoids a flaw in the interface) */393if ((int)len < 0) {394gz_error(state, Z_STREAM_ERROR, "request does not fit in an int");395return -1;396}397398/* read len or fewer bytes to buf */399len = (int)gz_read(state, buf, len);400401/* check for an error */402if (len == 0 && state->err != Z_OK && state->err != Z_BUF_ERROR)403return -1;404405/* return the number of bytes read (this is assured to fit in an int) */406return (int)len;407}408409/* -- see zlib.h -- */410z_size_t ZEXPORT gzfread(buf, size, nitems, file)411voidp buf;412z_size_t size;413z_size_t nitems;414gzFile file;415{416z_size_t len;417gz_statep state;418419/* get internal structure */420if (file == NULL)421return 0;422state = (gz_statep)file;423424/* check that we're reading and that there's no (serious) error */425if (state->mode != GZ_READ ||426(state->err != Z_OK && state->err != Z_BUF_ERROR))427return 0;428429/* compute bytes to read -- error on overflow */430len = nitems * size;431if (size && len / size != nitems) {432gz_error(state, Z_STREAM_ERROR, "request does not fit in a size_t");433return 0;434}435436/* read len or fewer bytes to buf, return the number of full items read */437return len ? gz_read(state, buf, len) / size : 0;438}439440/* -- see zlib.h -- */441#ifdef Z_PREFIX_SET442# undef z_gzgetc443#else444# undef gzgetc445#endif446int ZEXPORT gzgetc(file)447gzFile file;448{449int ret;450unsigned char buf[1];451gz_statep state;452453/* get internal structure */454if (file == NULL)455return -1;456state = (gz_statep)file;457458/* check that we're reading and that there's no (serious) error */459if (state->mode != GZ_READ ||460(state->err != Z_OK && state->err != Z_BUF_ERROR))461return -1;462463/* try output buffer (no need to check for skip request) */464if (state->x.have) {465state->x.have--;466state->x.pos++;467return *(state->x.next)++;468}469470/* nothing there -- try gz_read() */471ret = (int)gz_read(state, buf, 1);472return ret < 1 ? -1 : buf[0];473}474475int ZEXPORT gzgetc_(file)476gzFile file;477{478return gzgetc(file);479}480481/* -- see zlib.h -- */482int ZEXPORT gzungetc(c, file)483int c;484gzFile file;485{486gz_statep state;487488/* get internal structure */489if (file == NULL)490return -1;491state = (gz_statep)file;492493/* check that we're reading and that there's no (serious) error */494if (state->mode != GZ_READ ||495(state->err != Z_OK && state->err != Z_BUF_ERROR))496return -1;497498/* process a skip request */499if (state->seek) {500state->seek = 0;501if (gz_skip(state, state->skip) == -1)502return -1;503}504505/* can't push EOF */506if (c < 0)507return -1;508509/* if output buffer empty, put byte at end (allows more pushing) */510if (state->x.have == 0) {511state->x.have = 1;512state->x.next = state->out + (state->size << 1) - 1;513state->x.next[0] = (unsigned char)c;514state->x.pos--;515state->past = 0;516return c;517}518519/* if no room, give up (must have already done a gzungetc()) */520if (state->x.have == (state->size << 1)) {521gz_error(state, Z_DATA_ERROR, "out of room to push characters");522return -1;523}524525/* slide output data if needed and insert byte before existing data */526if (state->x.next == state->out) {527unsigned char *src = state->out + state->x.have;528unsigned char *dest = state->out + (state->size << 1);529while (src > state->out)530*--dest = *--src;531state->x.next = dest;532}533state->x.have++;534state->x.next--;535state->x.next[0] = (unsigned char)c;536state->x.pos--;537state->past = 0;538return c;539}540541/* -- see zlib.h -- */542char * ZEXPORT gzgets(file, buf, len)543gzFile file;544char *buf;545int len;546{547unsigned left, n;548char *str;549unsigned char *eol;550gz_statep state;551552/* check parameters and get internal structure */553if (file == NULL || buf == NULL || len < 1)554return NULL;555state = (gz_statep)file;556557/* check that we're reading and that there's no (serious) error */558if (state->mode != GZ_READ ||559(state->err != Z_OK && state->err != Z_BUF_ERROR))560return NULL;561562/* process a skip request */563if (state->seek) {564state->seek = 0;565if (gz_skip(state, state->skip) == -1)566return NULL;567}568569/* copy output bytes up to new line or len - 1, whichever comes first --570append a terminating zero to the string (we don't check for a zero in571the contents, let the user worry about that) */572str = buf;573left = (unsigned)len - 1;574if (left) do {575/* assure that something is in the output buffer */576if (state->x.have == 0 && gz_fetch(state) == -1)577return NULL; /* error */578if (state->x.have == 0) { /* end of file */579state->past = 1; /* read past end */580break; /* return what we have */581}582583/* look for end-of-line in current output buffer */584n = state->x.have > left ? left : state->x.have;585eol = (unsigned char *)memchr(state->x.next, '\n', n);586if (eol != NULL)587n = (unsigned)(eol - state->x.next) + 1;588589/* copy through end-of-line, or remainder if not found */590memcpy(buf, state->x.next, n);591state->x.have -= n;592state->x.next += n;593state->x.pos += n;594left -= n;595buf += n;596} while (left && eol == NULL);597598/* return terminated string, or if nothing, end of file */599if (buf == str)600return NULL;601buf[0] = 0;602return str;603}604605/* -- see zlib.h -- */606int ZEXPORT gzdirect(file)607gzFile file;608{609gz_statep state;610611/* get internal structure */612if (file == NULL)613return 0;614state = (gz_statep)file;615616/* if the state is not known, but we can find out, then do so (this is617mainly for right after a gzopen() or gzdopen()) */618if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0)619(void)gz_look(state);620621/* return 1 if transparent, 0 if processing a gzip stream */622return state->direct;623}624625/* -- see zlib.h -- */626int ZEXPORT gzclose_r(file)627gzFile file;628{629int ret, err;630gz_statep state;631632/* get internal structure */633if (file == NULL)634return Z_STREAM_ERROR;635state = (gz_statep)file;636637/* check that we're reading */638if (state->mode != GZ_READ)639return Z_STREAM_ERROR;640641/* free memory and close file */642if (state->size) {643inflateEnd(&(state->strm));644free(state->out);645free(state->in);646}647err = state->err == Z_BUF_ERROR ? Z_BUF_ERROR : Z_OK;648gz_error(state, Z_OK, NULL);649free(state->path);650ret = close(state->fd);651free(state);652return ret ? Z_ERRNO : err;653}654655656