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

static unsigned char a_buf[MAX_WINDOW_SIZE];
static unsigned char b_buf[MAX_WINDOW_SIZE];

int compare_files(file_info_t *a, file_info_t *b, const char *path)
{
	char second_name[strlen(second_path) + strlen(path) + 2];
	char first_name[strlen(first_path) + strlen(path) + 2];
	int afd = -1, bfd = -1, status = 0;
	uint64_t offset, diff;
	ssize_t ret;

	if (a->size != b->size)
		goto out_different;

	if (compare_flags & COMPARE_NO_CONTENTS)
		return 0;

	if (a_is_dir) {
		sprintf(first_name, "%s/%s", first_path, path);

		afd = open(first_name, O_RDONLY);
		if (afd < 0) {
			perror(first_name);
			goto fail;
		}
	}

	if (b_is_dir) {
		sprintf(second_name, "%s/%s", second_path, path);

		bfd = open(second_name, O_RDONLY);
		if (bfd < 0) {
			perror(second_name);
			goto fail;
		}
	}

	for (offset = 0; offset < a->size; offset += diff) {
		diff = a->size - offset;

		if (diff > MAX_WINDOW_SIZE)
			diff = MAX_WINDOW_SIZE;

		if (a_is_dir) {
			if (read_data_at(first_name, offset, afd, a_buf, diff))
				goto out;
		} else {
			ret = data_reader_read(sqfs_a.data, a, offset,
					       a_buf, diff);
			if (ret < 0 || (size_t)ret < diff) {
				fprintf(stderr, "Failed to read %s from %s\n",
					path, first_path);
				return -1;
			}
		}

		if (b_is_dir) {
			if (read_data_at(second_name, offset, bfd, b_buf, diff))
				goto out;
		} else {
			ret = data_reader_read(sqfs_b.data, b, offset,
					       b_buf, diff);
			if (ret < 0 || (size_t)ret < diff) {
				fprintf(stderr, "Failed to read %s from %s\n",
					path, second_path);
				return -1;
			}
		}

		if (memcmp(a_buf, b_buf, diff) != 0)
			goto out_different;
	}
out:
	if (afd >= 0)
		close(afd);
	if (bfd >= 0)
		close(bfd);
	return status;
fail:
	status = -1;
	goto out;
out_different:
	if (compare_flags & COMPARE_EXTRACT_FILES) {
		if (extract_files(a, b, path))
			goto fail;
	}
	status = 1;
	goto out;
}