aboutsummaryrefslogtreecommitdiff
path: root/lib/common/data_reader_dump.c
blob: 7902c2567a1d197cefffbbd44bb449a65bce705a (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
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
 * data_reader_dump.c
 *
 * Copyright (C) 2019 David Oberhollenzer <goliath@infraroot.at>
 */
#include "common.h"

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>

int sqfs_data_reader_dump(const char *name, sqfs_data_reader_t *data,
			  const sqfs_inode_generic_t *inode,
			  ostream_t *fp, size_t block_size)
{
	size_t i, diff, chunk_size;
	sqfs_u64 filesz;
	sqfs_u8 *chunk;
	int err;

	sqfs_inode_get_file_size(inode, &filesz);

	for (i = 0; i < sqfs_inode_get_file_block_count(inode); ++i) {
		diff = (filesz < block_size) ? filesz : block_size;

		if (SQFS_IS_SPARSE_BLOCK(inode->extra[i])) {
			if (ostream_append_sparse(fp, diff))
				return -1;
		} else {
			err = sqfs_data_reader_get_block(data, inode, i,
							 &chunk_size, &chunk);
			if (err) {
				sqfs_perror(name, "reading data block", err);
				return -1;
			}

			err = ostream_append(fp, chunk, chunk_size);
			free(chunk);

			if (err)
				return -1;
		}

		filesz -= diff;
	}

	if (filesz > 0) {
		err = sqfs_data_reader_get_fragment(data, inode,
						    &chunk_size, &chunk);
		if (err) {
			sqfs_perror(name, "reading fragment block", err);
			return -1;
		}

		err = ostream_append(fp, chunk, chunk_size);
		free(chunk);

		if (err)
			return -1;
	}

	return 0;
}