1/*
2 * Copyright (c) 1998 Michael Smith.
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 */
26
27#include "stand.h"
28
29#include <sys/stat.h>
30#include <string.h>
31#include <zlib.h>
32
33#define Z_BUFSIZE 2048	/* XXX larger? */
34
35struct z_file
36{
37    int			zf_rawfd;
38    off_t		zf_dataoffset;
39    z_stream		zf_zstream;
40    unsigned char	zf_buf[Z_BUFSIZE];
41    int			zf_endseen;
42};
43
44static int	zf_fill(struct z_file *z);
45static int	zf_open(const char *path, struct open_file *f);
46static int	zf_close(struct open_file *f);
47static int	zf_read(struct open_file *f, void *buf, size_t size, size_t *resid);
48static off_t	zf_seek(struct open_file *f, off_t offset, int where);
49static int	zf_stat(struct open_file *f, struct stat *sb);
50
51struct fs_ops gzipfs_fsops = {
52	.fs_name = "zip",
53	.fo_open = zf_open,
54	.fo_close = zf_close,
55	.fo_read = zf_read,
56	.fo_write = null_write,
57	.fo_seek = zf_seek,
58	.fo_stat = zf_stat,
59	.fo_readdir = null_readdir,
60};
61
62static int
63zf_fill(struct z_file *zf)
64{
65    int		result;
66    int		req;
67
68    req = Z_BUFSIZE - zf->zf_zstream.avail_in;
69    result = 0;
70
71    /* If we need more */
72    if (req > 0) {
73	/* move old data to bottom of buffer */
74	if (req < Z_BUFSIZE)
75	    bcopy(zf->zf_buf + req, zf->zf_buf, Z_BUFSIZE - req);
76
77	/* read to fill buffer and update availibility data */
78	result = read(zf->zf_rawfd, zf->zf_buf + zf->zf_zstream.avail_in, req);
79	zf->zf_zstream.next_in = zf->zf_buf;
80	if (result >= 0)
81	    zf->zf_zstream.avail_in += result;
82    }
83    return(result);
84}
85
86/*
87 * Adapted from get_byte/check_header in libz
88 *
89 * Returns 0 if the header is OK, nonzero if not.
90 */
91static int
92get_byte(struct z_file *zf, off_t *curoffp)
93{
94    if ((zf->zf_zstream.avail_in == 0) && (zf_fill(zf) == -1))
95	return(-1);
96    zf->zf_zstream.avail_in--;
97    ++*curoffp;
98    return(*(zf->zf_zstream.next_in)++);
99}
100
101static int gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
102
103/* gzip flag byte */
104#define ASCII_FLAG	0x01 /* bit 0 set: file probably ascii text */
105#define HEAD_CRC	0x02 /* bit 1 set: header CRC present */
106#define EXTRA_FIELD	0x04 /* bit 2 set: extra field present */
107#define ORIG_NAME	0x08 /* bit 3 set: original file name present */
108#define COMMENT		0x10 /* bit 4 set: file comment present */
109#define RESERVED	0xE0 /* bits 5..7: reserved */
110
111static int
112check_header(struct z_file *zf)
113{
114    int		method; /* method byte */
115    int		flags;  /* flags byte */
116    uInt	len;
117    int		c;
118
119    zf->zf_dataoffset = 0;
120    /* Check the gzip magic header */
121    for (len = 0; len < 2; len++) {
122	c = get_byte(zf, &zf->zf_dataoffset);
123	if (c != gz_magic[len]) {
124	    return(1);
125	}
126    }
127    method = get_byte(zf, &zf->zf_dataoffset);
128    flags = get_byte(zf, &zf->zf_dataoffset);
129    if (method != Z_DEFLATED || (flags & RESERVED) != 0) {
130	return(1);
131    }
132
133    /* Discard time, xflags and OS code: */
134    for (len = 0; len < 6; len++) (void)get_byte(zf, &zf->zf_dataoffset);
135
136    if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */
137	len  =  (uInt)get_byte(zf, &zf->zf_dataoffset);
138	len += ((uInt)get_byte(zf, &zf->zf_dataoffset))<<8;
139	/* len is garbage if EOF but the loop below will quit anyway */
140	while (len-- != 0 && get_byte(zf, &zf->zf_dataoffset) != -1) ;
141    }
142    if ((flags & ORIG_NAME) != 0) { /* skip the original file name */
143	while ((c = get_byte(zf, &zf->zf_dataoffset)) != 0 && c != -1) ;
144    }
145    if ((flags & COMMENT) != 0) {   /* skip the .gz file comment */
146	while ((c = get_byte(zf, &zf->zf_dataoffset)) != 0 && c != -1) ;
147    }
148    if ((flags & HEAD_CRC) != 0) {  /* skip the header crc */
149	for (len = 0; len < 2; len++) c = get_byte(zf, &zf->zf_dataoffset);
150    }
151    /* if there's data left, we're in business */
152    return((c == -1) ? 1 : 0);
153}
154
155static int
156zf_open(const char *fname, struct open_file *f)
157{
158    static char		*zfname;
159    int			rawfd;
160    struct z_file	*zf;
161    char		*cp;
162    int			error;
163    struct stat		sb;
164
165    /* Have to be in "just read it" mode */
166    if (f->f_flags != F_READ)
167	return(EPERM);
168
169    /* If the name already ends in .gz or .bz2, ignore it */
170    if ((cp = strrchr(fname, '.')) && (!strcmp(cp, ".gz")
171	    || !strcmp(cp, ".bz2") || !strcmp(cp, ".split")))
172	return(ENOENT);
173
174    /* Construct new name */
175    zfname = malloc(strlen(fname) + 4);
176    if (zfname == NULL)
177        return(ENOMEM);
178    sprintf(zfname, "%s.gz", fname);
179
180    /* Try to open the compressed datafile */
181    rawfd = open(zfname, O_RDONLY);
182    free(zfname);
183    if (rawfd == -1)
184	return(ENOENT);
185
186    if (fstat(rawfd, &sb) < 0) {
187	printf("zf_open: stat failed\n");
188	close(rawfd);
189	return(ENOENT);
190    }
191    if (!S_ISREG(sb.st_mode)) {
192	printf("zf_open: not a file\n");
193	close(rawfd);
194	return(EISDIR);			/* best guess */
195    }
196
197    /* Allocate a z_file structure, populate it */
198    zf = malloc(sizeof(struct z_file));
199    if (zf == NULL)
200        return(ENOMEM);
201    bzero(zf, sizeof(struct z_file));
202    zf->zf_rawfd = rawfd;
203
204    /* Verify that the file is gzipped */
205    if (check_header(zf)) {
206	close(zf->zf_rawfd);
207	free(zf);
208	return(EFTYPE);
209    }
210
211    /* Initialise the inflation engine */
212    if ((error = inflateInit2(&(zf->zf_zstream), -15)) != Z_OK) {
213	printf("zf_open: inflateInit returned %d : %s\n", error, zf->zf_zstream.msg);
214	close(zf->zf_rawfd);
215	free(zf);
216	return(EIO);
217    }
218
219    /* Looks OK, we'll take it */
220    f->f_fsdata = zf;
221    return(0);
222}
223
224static int
225zf_close(struct open_file *f)
226{
227    struct z_file	*zf = (struct z_file *)f->f_fsdata;
228
229    inflateEnd(&(zf->zf_zstream));
230    close(zf->zf_rawfd);
231    free(zf);
232    return(0);
233}
234
235static int
236zf_read(struct open_file *f, void *buf, size_t size, size_t *resid)
237{
238    struct z_file	*zf = (struct z_file *)f->f_fsdata;
239    int			error;
240
241    zf->zf_zstream.next_out = buf;			/* where and how much */
242    zf->zf_zstream.avail_out = size;
243
244    while (zf->zf_zstream.avail_out && zf->zf_endseen == 0) {
245	if ((zf->zf_zstream.avail_in == 0) && (zf_fill(zf) == -1)) {
246	    printf("zf_read: fill error\n");
247	    return(EIO);
248	}
249	if (zf->zf_zstream.avail_in == 0) {		/* oops, unexpected EOF */
250	    printf("zf_read: unexpected EOF\n");
251	    if (zf->zf_zstream.avail_out == size)
252		return(EIO);
253	    break;
254	}
255
256	error = inflate(&zf->zf_zstream, Z_SYNC_FLUSH);	/* decompression pass */
257	if (error == Z_STREAM_END) {			/* EOF, all done */
258	    zf->zf_endseen = 1;
259	    break;
260	}
261	if (error != Z_OK) {				/* argh, decompression error */
262	    printf("inflate: %s\n", zf->zf_zstream.msg);
263	    return(EIO);
264	}
265    }
266    if (resid != NULL)
267	*resid = zf->zf_zstream.avail_out;
268    return(0);
269}
270
271static int
272zf_rewind(struct open_file *f)
273{
274    struct z_file	*zf = (struct z_file *)f->f_fsdata;
275
276    if (lseek(zf->zf_rawfd, zf->zf_dataoffset, SEEK_SET) == -1)
277	return(-1);
278    zf->zf_zstream.avail_in = 0;
279    zf->zf_zstream.next_in = NULL;
280    zf->zf_endseen = 0;
281    (void)inflateReset(&zf->zf_zstream);
282
283    return(0);
284}
285
286static off_t
287zf_seek(struct open_file *f, off_t offset, int where)
288{
289    struct z_file	*zf = (struct z_file *)f->f_fsdata;
290    off_t		target;
291    char		discard[16];
292
293    switch (where) {
294    case SEEK_SET:
295	target = offset;
296	break;
297    case SEEK_CUR:
298	target = offset + zf->zf_zstream.total_out;
299	break;
300    default:
301	errno = EINVAL;
302	return(-1);
303    }
304
305    /* rewind if required */
306    if (target < zf->zf_zstream.total_out && zf_rewind(f) != 0)
307	return(-1);
308
309    /* skip forwards if required */
310    while (target > zf->zf_zstream.total_out) {
311	errno = zf_read(f, discard, min(sizeof(discard),
312	    target - zf->zf_zstream.total_out), NULL);
313	if (errno)
314	    return(-1);
315	/* Break out of loop if end of file has been reached. */
316	if (zf->zf_endseen)
317	    break;
318    }
319    /* This is where we are (be honest if we overshot) */
320    return(zf->zf_zstream.total_out);
321}
322
323
324static int
325zf_stat(struct open_file *f, struct stat *sb)
326{
327    struct z_file	*zf = (struct z_file *)f->f_fsdata;
328    int			result;
329
330    /* stat as normal, but indicate that size is unknown */
331    if ((result = fstat(zf->zf_rawfd, sb)) == 0)
332	sb->st_size = -1;
333    return(result);
334}
335
336
337
338