abuild-gzsplit.c 2.06 KB
Newer Older
1
#include <stdio.h>
2
#include <err.h>
3 4 5 6 7 8
#include <fcntl.h>
#include <string.h>
#include <unistd.h>

#include <zlib.h>

9 10 11 12 13 14 15 16 17 18 19
static int find_section(const char *buf, size_t bufsize, const char *str) {
	int len = strlen(str);
	const char *p;

	if (len >= bufsize) return 0;

	p = strrchr(buf, '/');
	if (p++ == NULL) p = buf;
	return strncmp(p, str, len) == 0;
}

20 21 22 23 24 25 26 27 28 29 30
int main(void)
{
	char obuf[8*1024], ibuf[8*1024];
	z_stream zs;
	int r = Z_OK, rc = 1, fd = -1;
	size_t len;

	if (inflateInit2(&zs, 15+32) != Z_OK)
		goto err;

	zs.avail_out = sizeof obuf;
31
	zs.next_out  = (Bytef *)obuf;
32 33

	while (1) {
34 35
		const char *fn = NULL;

36 37
		if (zs.avail_in == 0) {
			zs.avail_in = read(STDIN_FILENO, ibuf, sizeof ibuf);
38
			zs.next_in = (Bytef *)ibuf;
39 40 41 42
			if (zs.avail_in < 0) {
				warn("Failed to read input");
				goto err;
			}
43 44 45 46
			if (zs.avail_in == 0 && r == Z_STREAM_END) goto ok;
		}

		r = inflate(&zs, Z_NO_FLUSH);
47 48 49 50
		if (r != Z_OK && r != Z_STREAM_END) {
			warnx("Failed to inflate input");
			goto err;
		}
51 52 53 54 55

		len = sizeof obuf - zs.avail_out;
		if (len) {
			if (fd < 0) {
				const char *fn;
56

57
				if (find_section(obuf, len, ".SIGN."))
58
					fn = "signatures.tar.gz";
59
				else if (find_section(obuf, len, ".PKGINFO"))
60 61 62
					fn = "control.tar.gz";
				else if (rc == 1)
					fn = "data.tar.gz", rc = 2;
63 64
				else {
					warnx("Failed to find .PKGINFO section");
65
					goto err;
66
				}
67
				fd = open(fn, O_CREAT|O_TRUNC|O_WRONLY, 0777);
68 69 70 71
				if (fd < 0) {
					warn("Failed to open %s", fn);
					goto err;
				}
72
			}
73
			zs.next_out = (Bytef *)obuf;
74 75 76 77 78
			zs.avail_out = sizeof obuf;
		}

		if (zs.avail_in == 0 || r == Z_STREAM_END) {
			len = (void *)zs.next_in - (void *)ibuf;
79 80 81 82
			if (write(fd, ibuf, len) != len) {
				warn("Failed to write to %s", fn);
				goto err;
			}
83
			memmove(ibuf, zs.next_in, zs.avail_in);
84
			zs.next_in = (Bytef *)ibuf;
85 86 87 88 89 90 91 92
		}

		if (r == Z_STREAM_END) {
			if (fd >= 0) {
				close(fd);
				fd = -1;
			}
			inflateEnd(&zs);
93 94 95 96
			if (inflateInit2(&zs, 15+32) != Z_OK) {
				warnx("inflateInit2 failed");
				goto err;
			}
97 98 99 100 101 102 103 104 105 106
		}
	}
ok:
	rc = 0;
err:
	if (fd >= 0) close(fd);
	inflateEnd(&zs);
	return rc;
}