xref: /freebsd/stand/libsa/pkgfs.c (revision 3c4ba5f55438f7afd4f4b0b56f88f2bb505fd6a6)
1 /*-
2  * Copyright (c) 2007-2014, Juniper Networks, Inc.
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 <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include "stand.h"
31 
32 #include <sys/stat.h>
33 #include <sys/stdint.h>
34 #include <string.h>
35 #include <zlib.h>
36 
37 #ifdef PKGFS_DEBUG
38 #define	DBG(x)	printf x
39 #else
40 #define	DBG(x)
41 #endif
42 
43 static int   pkg_open(const char *, struct open_file *);
44 static int   pkg_close(struct open_file *);
45 static int   pkg_read(struct open_file *, void *, size_t, size_t *);
46 static off_t pkg_seek(struct open_file *, off_t, int);
47 static int   pkg_stat(struct open_file *, struct stat *);
48 static int   pkg_readdir(struct open_file *, struct dirent *);
49 static off_t pkg_atol(const char *, unsigned);
50 
51 struct fs_ops pkgfs_fsops = {
52 	.fs_name = "pkg",
53 	.fo_open = pkg_open,
54 	.fo_close = pkg_close,
55 	.fo_read = pkg_read,
56 	.fo_write = null_write,
57 	.fo_seek = pkg_seek,
58 	.fo_stat = pkg_stat,
59 	.fo_readdir = pkg_readdir,
60 };
61 
62 #define PKG_BUFSIZE	512
63 #define	PKG_MAXCACHESZ	(512 * 1024)
64 
65 #define	PKG_FILEEXT	".tgz"
66 
67 /*
68  * Layout of POSIX 'ustar' header.
69  */
70 struct ustar_hdr {
71 	char	ut_name[100];
72 	char	ut_mode[8];
73 	char	ut_uid[8];
74 	char	ut_gid[8];
75 	char	ut_size[12];
76 	char	ut_mtime[12];
77 	char	ut_checksum[8];
78 	char	ut_typeflag[1];
79 	char	ut_linkname[100];
80 	char	ut_magic[6];		/* For POSIX: "ustar\0" */
81 	char	ut_version[2];		/* For POSIX: "00" */
82 	char	ut_uname[32];
83 	char	ut_gname[32];
84 	char	ut_rdevmajor[8];
85 	char	ut_rdevminor[8];
86 	union {
87 		struct {
88 			char	prefix[155];
89 		} posix;
90 		struct {
91 			char	atime[12];
92 			char	ctime[12];
93 			char	offset[12];
94 			char	longnames[4];
95 			char	unused[1];
96 			struct gnu_sparse {
97 				char	offset[12];
98 				char	numbytes[12];
99 			} sparse[4];
100 			char	isextended[1];
101 			char	realsize[12];
102 		} gnu;
103 	} u;
104 	u_char __padding[12];
105 };
106 
107 struct package;
108 
109 struct tarfile
110 {
111 	struct package *tf_pkg;
112 	struct tarfile *tf_next;
113 	struct ustar_hdr tf_hdr;
114 	off_t	tf_ofs;
115 	off_t	tf_size;
116 	off_t	tf_fp;
117 	size_t	tf_cachesz;
118 	void	*tf_cache;
119 };
120 
121 struct package
122 {
123 	struct package *pkg_chain;
124 	int	pkg_fd;
125 	off_t	pkg_ofs;
126 	z_stream pkg_zs;
127 	struct tarfile *pkg_first;
128 	struct tarfile *pkg_last;
129 	u_char	pkg_buf[PKG_BUFSIZE];
130 };
131 
132 static struct package *package = NULL;
133 
134 static int new_package(int, struct package **);
135 static int cache_data(struct tarfile *tf, int);
136 
137 void
138 pkgfs_cleanup(void)
139 {
140 	struct package *chain;
141 	struct tarfile *tf, *tfn;
142 
143 	while (package != NULL) {
144 		inflateEnd(&package->pkg_zs);
145 		close(package->pkg_fd);
146 
147 		tf = package->pkg_first;
148 		while (tf != NULL) {
149 			tfn = tf->tf_next;
150 			if (tf->tf_cachesz > 0)
151 				free(tf->tf_cache);
152 			free(tf);
153 			tf = tfn;
154 		}
155 
156 		chain = package->pkg_chain;
157 		free(package);
158 		package = chain;
159 	}
160 }
161 
162 int
163 pkgfs_init(const char *pkgname, struct fs_ops *proto)
164 {
165 	struct package *pkg;
166 	int error, fd;
167 
168 	pkg = NULL;
169 	if (proto != &pkgfs_fsops)
170 		pkgfs_cleanup();
171 
172 	exclusive_file_system = proto;
173 
174 	fd = open(pkgname, O_RDONLY);
175 
176 	exclusive_file_system = NULL;
177 
178 	if (fd == -1)
179 		return (errno);
180 
181 	error = new_package(fd, &pkg);
182 	if (error) {
183 		close(fd);
184 		return (error);
185 	}
186 
187 	if (pkg == NULL)
188 		return (EDOOFUS);
189 
190 	pkg->pkg_chain = package;
191 	package = pkg;
192 	exclusive_file_system = &pkgfs_fsops;
193 	return (0);
194 }
195 
196 static int get_mode(struct tarfile *);
197 static int get_zipped(struct package *, void *, size_t);
198 static int new_package(int, struct package **);
199 static struct tarfile *scan_tarfile(struct package *, struct tarfile *);
200 
201 static int
202 pkg_open_follow(const char *fn, struct open_file *f, int lnks)
203 {
204 	struct tarfile *tf;
205 
206 	if (fn == NULL || f == NULL)
207 		return (EINVAL);
208 
209 	if (package == NULL)
210 		return (ENXIO);
211 
212 	/*
213 	 * We can only read from a package, so reject request to open
214 	 * for write-only or read-write.
215 	 */
216 	if (f->f_flags != F_READ)
217 		return (EPERM);
218 
219 	/*
220 	 * Scan the file headers for the named file. We stop scanning
221 	 * at the first filename that has the .pkg extension. This is
222 	 * a package within a package. We assume we have all the files
223 	 * we need up-front and without having to dig within nested
224 	 * packages.
225 	 *
226 	 * Note that we preserve streaming properties as much as possible.
227 	 */
228 	while (*fn == '/')
229 		fn++;
230 
231 	/*
232 	 * Allow opening of the root directory for use by readdir()
233 	 * to support listing files in the package.
234 	 */
235 	if (*fn == '\0') {
236 		f->f_fsdata = NULL;
237 		return (0);
238 	}
239 
240 	tf = scan_tarfile(package, NULL);
241 	while (tf != NULL) {
242 		if (strcmp(fn, tf->tf_hdr.ut_name) == 0) {
243 			f->f_fsdata = tf;
244 			tf->tf_fp = 0;	/* Reset the file pointer. */
245 			DBG(("%s: found %s type %c\n", __func__,
246 			     fn, tf->tf_hdr.ut_typeflag[0]));
247 			if (tf->tf_hdr.ut_typeflag[0] == '2') {
248 			    /* we have a symlink
249 			     * Note: ut_linkname is only 100 chars!
250 			     */
251 			    if (lnks++ >= 8)
252 				return (EMLINK);
253 			    return pkg_open_follow(tf->tf_hdr.ut_linkname,
254 				f, lnks);
255 			}
256 			return (0);
257 		}
258 		tf = scan_tarfile(package, tf);
259 	}
260 	return (errno);
261 }
262 
263 static int
264 pkg_open(const char *fn, struct open_file *f)
265 {
266     return pkg_open_follow(fn, f, 0);
267 }
268 
269 static int
270 pkg_close(struct open_file *f)
271 {
272 	struct tarfile *tf;
273 
274 	tf = (struct tarfile *)f->f_fsdata;
275 	if (tf == NULL)
276 		return (0);
277 
278 	/*
279 	 * Free up the cache if we read all of the file.
280 	 */
281 	if (tf->tf_fp == tf->tf_size && tf->tf_cachesz > 0) {
282 		free(tf->tf_cache);
283 		tf->tf_cachesz = 0;
284 	}
285 	return (0);
286 }
287 
288 static int
289 pkg_read(struct open_file *f, void *buf, size_t size, size_t *res)
290 {
291 	struct tarfile *tf;
292 	char *p;
293 	off_t fp;
294 	size_t sz;
295 
296 	tf = (struct tarfile *)f->f_fsdata;
297 	if (tf == NULL) {
298 		if (res != NULL)
299 			*res = size;
300 		return (EBADF);
301 	}
302 
303 	if (tf->tf_cachesz == 0)
304 		cache_data(tf, 1);
305 
306 	fp = tf->tf_fp;
307 	p = buf;
308 	sz = 0;
309 	while (size > 0) {
310 		sz = tf->tf_size - fp;
311 		if (fp < tf->tf_cachesz && tf->tf_cachesz < tf->tf_size)
312 			sz = tf->tf_cachesz - fp;
313 		if (size < sz)
314 			sz = size;
315 		if (sz == 0)
316 			break;
317 
318 		if (fp < tf->tf_cachesz) {
319 			/* Satisfy the request from cache. */
320 			memcpy(p, tf->tf_cache + fp, sz);
321 			fp += sz;
322 			p += sz;
323 			size -= sz;
324 			continue;
325 		}
326 
327 		if (get_zipped(tf->tf_pkg, p, sz) == -1) {
328 			sz = -1;
329 			break;
330 		}
331 
332 		fp += sz;
333 		p += sz;
334 		size -= sz;
335 	}
336 
337 	tf->tf_fp = fp;
338 	if (res != NULL)
339 		*res = size;
340 	return ((sz == -1) ? errno : 0);
341 }
342 
343 static off_t
344 pkg_seek(struct open_file *f, off_t ofs, int whence)
345 {
346 	char buf[512];
347 	struct tarfile *tf;
348 	off_t delta;
349 	off_t nofs;
350 	size_t sz, res;
351 	int error;
352 
353 	tf = (struct tarfile *)f->f_fsdata;
354 	if (tf == NULL) {
355 		errno = EBADF;
356 		return (-1);
357 	}
358 
359 	switch (whence) {
360 	case SEEK_SET:
361 		delta = ofs - tf->tf_fp;
362 		break;
363 	case SEEK_CUR:
364 		delta = ofs;
365 		break;
366 	case SEEK_END:
367 		delta = tf->tf_size - tf->tf_fp + ofs;
368 		break;
369 	default:
370 		errno = EINVAL;
371 		return (-1);
372 	}
373 
374 	if (delta < 0) {
375 		/* seeking backwards - ok if within cache */
376 		if (tf->tf_cachesz > 0 && tf->tf_fp <= tf->tf_cachesz) {
377 			nofs = tf->tf_fp + delta;
378 			if (nofs >= 0) {
379 				tf->tf_fp = nofs;
380 				return (tf->tf_fp);
381 			}
382 		}
383 		DBG(("%s: negative file seek (%jd)\n", __func__,
384 		    (intmax_t)delta));
385 		errno = ESPIPE;
386 		return (-1);
387 	}
388 
389 	while (delta > 0 && tf->tf_fp < tf->tf_size) {
390 		sz = (delta > sizeof(buf)) ? sizeof(buf) : delta;
391 		error = pkg_read(f, buf, sz, &res);
392 		if (error != 0) {
393 			errno = error;
394 			return (-1);
395 		}
396 		delta -= sz - res;
397 	}
398 
399 	return (tf->tf_fp);
400 }
401 
402 static int
403 pkg_stat(struct open_file *f, struct stat *sb)
404 {
405 	struct tarfile *tf;
406 
407 	tf = (struct tarfile *)f->f_fsdata;
408 	if (tf == NULL)
409 		return (EBADF);
410 	memset(sb, 0, sizeof(*sb));
411 	sb->st_mode = get_mode(tf);
412 	if ((sb->st_mode & S_IFMT) == 0) {
413 		/* tar file bug - assume regular file */
414 		sb->st_mode |= S_IFREG;
415 	}
416 	sb->st_size = tf->tf_size;
417 	sb->st_blocks = (tf->tf_size + 511) / 512;
418 	sb->st_mtime = pkg_atol(tf->tf_hdr.ut_mtime, 12);
419 	sb->st_dev = (off_t)((uintptr_t)tf->tf_pkg);
420 	sb->st_ino = tf->tf_ofs;	/* unique per tf_pkg */
421 	return (0);
422 }
423 
424 static int
425 pkg_readdir(struct open_file *f, struct dirent *d)
426 {
427 	struct tarfile *tf;
428 
429 	tf = (struct tarfile *)f->f_fsdata;
430 	if (tf != NULL)
431 		return (EBADF);
432 
433 	tf = scan_tarfile(package, NULL);
434 	if (tf == NULL)
435 		return (ENOENT);
436 
437 	d->d_fileno = 0;
438 	d->d_reclen = sizeof(*d);
439 	d->d_type = DT_REG;
440 	memcpy(d->d_name, tf->tf_hdr.ut_name, sizeof(d->d_name));
441 	return (0);
442 }
443 
444 /*
445  * Low-level support functions.
446  */
447 
448 static int
449 get_byte(struct package *pkg, off_t *op)
450 {
451 	int c;
452 
453 	if (pkg->pkg_zs.avail_in == 0) {
454 		c = read(pkg->pkg_fd, pkg->pkg_buf, PKG_BUFSIZE);
455 		if (c <= 0)
456 			return (-1);
457 		pkg->pkg_zs.avail_in = c;
458 		pkg->pkg_zs.next_in = pkg->pkg_buf;
459 	}
460 
461 	c = *pkg->pkg_zs.next_in;
462 	pkg->pkg_zs.next_in++;
463 	pkg->pkg_zs.avail_in--;
464 	(*op)++;
465 	return (c);
466 }
467 
468 static int
469 get_zipped(struct package *pkg, void *buf, size_t bufsz)
470 {
471 	int c;
472 
473 	pkg->pkg_zs.next_out = buf;
474 	pkg->pkg_zs.avail_out = bufsz;
475 
476 	while (pkg->pkg_zs.avail_out) {
477 		if (pkg->pkg_zs.avail_in == 0) {
478 			c = read(pkg->pkg_fd, pkg->pkg_buf, PKG_BUFSIZE);
479 			if (c <= 0) {
480 				errno = EIO;
481 				return (-1);
482 			}
483 			pkg->pkg_zs.avail_in = c;
484 			pkg->pkg_zs.next_in = pkg->pkg_buf;
485 		}
486 
487 		c = inflate(&pkg->pkg_zs, Z_SYNC_FLUSH);
488 		if (c != Z_OK && c != Z_STREAM_END) {
489 			errno = EIO;
490 			return (-1);
491 		}
492 	}
493 
494 	pkg->pkg_ofs += bufsz;
495 	return (0);
496 }
497 
498 /**
499  * @brief
500  * cache data of a tarfile
501  *
502  * @param[in] tf
503  *	tarfile pointer
504  *
505  * @param[in] force
506  *	If file size > PKG_MAXCACHESZ, cache that much
507  *
508  * @return 0, -1 (errno set to error value)
509  */
510 static int
511 cache_data(struct tarfile *tf, int force)
512 {
513 	struct package *pkg;
514 	size_t sz;
515 
516 	if (tf == NULL) {
517 		DBG(("%s: no file to cache data for?\n", __func__));
518 		errno = EINVAL;
519 		return (-1);
520 	}
521 
522 	pkg = tf->tf_pkg;
523 	if (pkg == NULL) {
524 		DBG(("%s: no package associated with file?\n", __func__));
525 		errno = EINVAL;
526 		return (-1);
527 	}
528 
529 	if (tf->tf_cachesz > 0) {
530 		DBG(("%s: data already cached\n", __func__));
531 		errno = EINVAL;
532 		return (-1);
533 	}
534 
535 	if (tf->tf_ofs != pkg->pkg_ofs) {
536 		DBG(("%s: caching after force read of file %s?\n",
537 		    __func__, tf->tf_hdr.ut_name));
538 		errno = EINVAL;
539 		return (-1);
540 	}
541 
542 	/* We don't cache everything... */
543 	if (tf->tf_size > PKG_MAXCACHESZ && !force)  {
544 		errno = ENOBUFS;
545 		return (-1);
546 	}
547 
548 	sz = tf->tf_size < PKG_MAXCACHESZ ? tf->tf_size : PKG_MAXCACHESZ;
549 	/* All files are padded to a multiple of 512 bytes. */
550 	sz = (sz + 0x1ff) & ~0x1ff;
551 
552 	tf->tf_cache = malloc(sz);
553 	if (tf->tf_cache == NULL) {
554 		DBG(("%s: could not allocate %d bytes\n", __func__, (int)sz));
555 		errno = ENOMEM;
556 		return (-1);
557 	}
558 
559 	tf->tf_cachesz = sz;
560 	return (get_zipped(pkg, tf->tf_cache, sz));
561 }
562 
563 /*
564  * Note that this implementation does not (and should not!) obey
565  * locale settings; you cannot simply substitute strtol here, since
566  * it does obey locale.
567  */
568 static off_t
569 pkg_atol8(const char *p, unsigned char_cnt)
570 {
571         int64_t l, limit, last_digit_limit;
572         int digit, sign, base;
573 
574         base = 8;
575         limit = INT64_MAX / base;
576         last_digit_limit = INT64_MAX % base;
577 
578         while (*p == ' ' || *p == '\t')
579                 p++;
580         if (*p == '-') {
581                 sign = -1;
582                 p++;
583         } else
584                 sign = 1;
585 
586         l = 0;
587         digit = *p - '0';
588         while (digit >= 0 && digit < base  && char_cnt-- > 0) {
589                 if (l>limit || (l == limit && digit > last_digit_limit)) {
590                         l = UINT64_MAX; /* Truncate on overflow. */
591                         break;
592                 }
593                 l = (l * base) + digit;
594                 digit = *++p - '0';
595         }
596         return (sign < 0) ? -l : l;
597 }
598 
599 /*
600  * Parse a base-256 integer.  This is just a straight signed binary
601  * value in big-endian order, except that the high-order bit is
602  * ignored.  Remember that "int64_t" may or may not be exactly 64
603  * bits; the implementation here tries to avoid making any assumptions
604  * about the actual size of an int64_t.  It does assume we're using
605  * twos-complement arithmetic, though.
606  */
607 static int64_t
608 pkg_atol256(const char *_p, unsigned char_cnt)
609 {
610         int64_t l, upper_limit, lower_limit;
611         const unsigned char *p = (const unsigned char *)_p;
612 
613         upper_limit = INT64_MAX / 256;
614         lower_limit = INT64_MIN / 256;
615 
616         /* Pad with 1 or 0 bits, depending on sign. */
617         if ((0x40 & *p) == 0x40)
618                 l = (int64_t)-1;
619         else
620                 l = 0;
621         l = (l << 6) | (0x3f & *p++);
622         while (--char_cnt > 0) {
623                 if (l > upper_limit) {
624                         l = INT64_MAX; /* Truncate on overflow */
625                         break;
626                 } else if (l < lower_limit) {
627                         l = INT64_MIN;
628                         break;
629                 }
630                 l = (l << 8) | (0xff & (int64_t)*p++);
631         }
632         return (l);
633 }
634 
635 static off_t
636 pkg_atol(const char *p, unsigned char_cnt)
637 {
638 	/*
639 	 * Technically, GNU pkg considers a field to be in base-256
640 	 * only if the first byte is 0xff or 0x80.
641 	 */
642 	if (*p & 0x80)
643 		return (pkg_atol256(p, char_cnt));
644 	return (pkg_atol8(p, char_cnt));
645 }
646 
647 static int
648 get_mode(struct tarfile *tf)
649 {
650 	return (pkg_atol(tf->tf_hdr.ut_mode, sizeof(tf->tf_hdr.ut_mode)));
651 }
652 
653 /* GZip flag byte */
654 #define ASCII_FLAG	0x01 /* bit 0 set: file probably ascii text */
655 #define HEAD_CRC	0x02 /* bit 1 set: header CRC present */
656 #define EXTRA_FIELD	0x04 /* bit 2 set: extra field present */
657 #define ORIG_NAME	0x08 /* bit 3 set: original file name present */
658 #define COMMENT		0x10 /* bit 4 set: file comment present */
659 #define RESERVED	0xE0 /* bits 5..7: reserved */
660 
661 static int
662 new_package(int fd, struct package **pp)
663 {
664 	struct package *pkg;
665 	off_t ofs;
666 	int flags, i, error;
667 
668 	pkg = malloc(sizeof(*pkg));
669 	if (pkg == NULL)
670 		return (ENOMEM);
671 
672 	bzero(pkg, sizeof(*pkg));
673 	pkg->pkg_fd = fd;
674 
675 	/*
676 	 * Parse the header.
677 	 */
678 	error = EFTYPE;
679 	ofs = 0;
680 
681 	/* Check megic. */
682 	if (get_byte(pkg, &ofs) != 0x1f || get_byte(pkg, &ofs) != 0x8b)
683 		goto fail;
684 	/* Check method. */
685 	if (get_byte(pkg, &ofs) != Z_DEFLATED)
686 		goto fail;
687 	/* Check flags. */
688 	flags = get_byte(pkg, &ofs);
689 	if (flags & RESERVED)
690 		goto fail;
691 
692 	/* Skip time, xflags and OS code. */
693 	for (i = 0; i < 6; i++) {
694 		if (get_byte(pkg, &ofs) == -1)
695 			goto fail;
696 	}
697 
698 	/* Skip extra field. */
699 	if (flags & EXTRA_FIELD) {
700 		i = (get_byte(pkg, &ofs) & 0xff) |
701 		    ((get_byte(pkg, &ofs) << 8) & 0xff);
702 		while (i-- > 0) {
703 			if (get_byte(pkg, &ofs) == -1)
704 				goto fail;
705 		}
706 	}
707 
708 	/* Skip original file name. */
709 	if (flags & ORIG_NAME) {
710 		do {
711 			i = get_byte(pkg, &ofs);
712 		} while (i != 0 && i != -1);
713 		if (i == -1)
714 			goto fail;
715 	}
716 
717 	/* Print the comment if it's there. */
718 	if (flags & COMMENT) {
719 		while (1) {
720 			i = get_byte(pkg, &ofs);
721 			if (i == -1)
722 				goto fail;
723 			if (i == 0)
724 				break;
725 			putchar(i);
726 		}
727 	}
728 
729 	/* Skip the CRC. */
730 	if (flags & HEAD_CRC) {
731 		if (get_byte(pkg, &ofs) == -1)
732 			goto fail;
733 		if (get_byte(pkg, &ofs) == -1)
734 			goto fail;
735 	}
736 
737 	/*
738 	 * Done parsing the ZIP header. Spkgt the inflation engine.
739 	 */
740 	error = inflateInit2(&pkg->pkg_zs, -15);
741 	if (error != Z_OK)
742 		goto fail;
743 
744 	*pp = pkg;
745 	return (0);
746 
747  fail:
748 	free(pkg);
749 	return (error);
750 }
751 
752 static struct tarfile *
753 scan_tarfile(struct package *pkg, struct tarfile *last)
754 {
755 	char buf[512];
756 	struct tarfile *cur;
757 	off_t ofs;
758 	size_t sz;
759 
760 	cur = (last != NULL) ? last->tf_next : pkg->pkg_first;
761 	if (cur == NULL) {
762 		ofs = (last != NULL) ? last->tf_ofs + last->tf_size :
763 		    pkg->pkg_ofs;
764 		ofs = (ofs + 0x1ff) & ~0x1ff;
765 
766 		/* Check if we've reached EOF. */
767 		if (ofs < pkg->pkg_ofs) {
768 			errno = ENOSPC;
769 			return (NULL);
770 		}
771 
772 		if (ofs != pkg->pkg_ofs) {
773 			if (last != NULL && pkg->pkg_ofs == last->tf_ofs) {
774 				if (cache_data(last, 0) == -1)
775 					return (NULL);
776 			} else {
777 				sz = ofs - pkg->pkg_ofs;
778 				while (sz != 0) {
779 					if (sz > sizeof(buf))
780 						sz = sizeof(buf);
781 					if (get_zipped(pkg, buf, sz) == -1)
782 						return (NULL);
783 					sz = ofs - pkg->pkg_ofs;
784 				}
785 			}
786 		}
787 
788 		cur = malloc(sizeof(*cur));
789 		if (cur == NULL)
790 			return (NULL);
791 		memset(cur, 0, sizeof(*cur));
792 		cur->tf_pkg = pkg;
793 
794 		while (1) {
795 			if (get_zipped(pkg, &cur->tf_hdr,
796 			    sizeof(cur->tf_hdr)) == -1) {
797 				free(cur);
798 				return (NULL);
799 			}
800 
801 			/*
802 			 * There are always 2 empty blocks appended to
803 			 * a PKG. It marks the end of the archive.
804 			 */
805 			if (strncmp(cur->tf_hdr.ut_magic, "ustar", 5) != 0) {
806 				free(cur);
807 				errno = ENOSPC;
808 				return (NULL);
809 			}
810 
811 			cur->tf_ofs = pkg->pkg_ofs;
812 			cur->tf_size = pkg_atol(cur->tf_hdr.ut_size,
813 			    sizeof(cur->tf_hdr.ut_size));
814 
815 			if (cur->tf_hdr.ut_name[0] != '+')
816 				break;
817 
818 			/*
819 			 * Skip package meta-files.
820 			 */
821 			ofs = cur->tf_ofs + cur->tf_size;
822 			ofs = (ofs + 0x1ff) & ~0x1ff;
823 			while (pkg->pkg_ofs < ofs) {
824 				if (get_zipped(pkg, buf, sizeof(buf)) == -1) {
825 					free(cur);
826 					return (NULL);
827 				}
828 			}
829 		}
830 
831 		if (last != NULL)
832 			last->tf_next = cur;
833 		else
834 			pkg->pkg_first = cur;
835 		pkg->pkg_last = cur;
836 	}
837 
838 	return (cur);
839 }
840