aboutsummaryrefslogtreecommitdiff
path: root/unpack/extract_file.c
blob: 4d5997a4f073718aee146cce200ff167a7bf32e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/* SPDX-License-Identifier: GPL-3.0-or-later */
#include "rdsquashfs.h"

int extract_file(file_info_t *fi, unsqfs_info_t *info, int outfd)
{
	void *buffer, *scratch, *ptr;
	size_t i, count, fragsz;
	bool compressed;
	uint32_t bs;
	ssize_t ret;

	buffer = malloc(info->block_size * 2);
	if (buffer == NULL) {
		perror("allocating scratch buffer");
		return -1;
	}

	scratch = (char *)buffer + info->block_size;
	count = fi->size / info->block_size;

	if (count > 0) {
		if (lseek(info->sqfsfd, fi->startblock, SEEK_SET) == (off_t)-1)
			goto fail_seek;

		for (i = 0; i < count; ++i) {
			bs = fi->blocksizes[i];

			compressed = (bs & (1 << 24)) == 0;
			bs &= (1 << 24) - 1;

			if (bs > info->block_size)
				goto fail_bs;

			ret = read_retry(info->sqfsfd, buffer, bs);
			if (ret < 0)
				goto fail_rd;

			if ((size_t)ret < bs)
				goto fail_trunc;

			if (compressed) {
				ret = info->cmp->do_block(info->cmp, buffer, bs,
							  scratch,
							  info->block_size);
				if (ret <= 0)
					goto fail;

				bs = ret;
				ptr = scratch;
			} else {
				ptr = buffer;
			}

			ret = write_retry(outfd, ptr, bs);
			if (ret < 0)
				goto fail_wr;

			if ((size_t)ret < bs)
				goto fail_wr_trunc;
		}
	}

	fragsz = fi->size % info->block_size;

	if (fragsz > 0) {
		if (frag_reader_read(info->frag, fi->fragment,
				     fi->fragment_offset, buffer, fragsz)) {
			goto fail;
		}

		ret = write_retry(outfd, buffer, fragsz);
		if (ret < 0)
			goto fail_wr;

		if ((size_t)ret < fragsz)
			goto fail_wr_trunc;
	}

	free(buffer);
	return 0;
fail_seek:
	perror("seek on squashfs");
	goto fail;
fail_wr:
	perror("writing uncompressed block");
	goto fail;
fail_wr_trunc:
	fputs("writing uncompressed block: truncated write\n", stderr);
	goto fail;
fail_rd:
	perror("reading from squashfs");
	goto fail;
fail_trunc:
	fputs("reading from squashfs: unexpected end of file\n", stderr);
	goto fail;
fail_bs:
	fputs("found compressed block larger than block size\n", stderr);
	goto fail;
fail:
	free(buffer);
	return -1;
}