aboutsummaryrefslogtreecommitdiffstats
path: root/sum_fd.c
blob: c4f41d040ae4e5707888c636264579070dedd7c3 (plain) (blame)
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
/* See LICENSE file for copyright and license details. */
#include "common.h"


int
libsha1_sum_fd(int fd, enum libsha1_algorithm algorithm, void *restrict hashsum)
{
	struct libsha1_state state;
	ssize_t r;
#ifndef _WIN32
	struct stat attr;
#endif
	size_t blksize = 4096;
	char *restrict chunk;

	if (libsha1_init(&state, algorithm) < 0)
		return -1;

#ifndef _WIN32
	if (fstat(fd, &attr) == 0 && attr.st_blksize > 0)
		blksize = (size_t)(attr.st_blksize);
#endif

#if ALLOCA_LIMIT > 0
	if (blksize > (size_t)ALLOCA_LIMIT) {
		blksize = (size_t)ALLOCA_LIMIT;
		blksize -= blksize % sizeof(((struct libsha1_state)NULL)->chunk);
		if (!blksize)
			blksize = sizeof(((struct libsha1_state)NULL)->chunk);
	}
# if defined(__clang__)
	/* We are using a limit so it's just like declaring an array
	 * in a function, except we might use less of the stack. */
#  pragma clang diagnostic push
#  pragma clang diagnostic ignored "-Walloca"
# endif
	chunk = alloca(blksize);
# if defined(__clang__)
#  pragma clang diagnostic pop
# endif
#else
	chunk = malloc(blksize);
	if (!chunk)
		return -1;
#endif

	for (;;) {
		r = read(fd, chunk, blksize);
		if (r <= 0) {
			if (!r)
				break;
			if (errno == EINTR)
				continue;
#if ALLOCA_LIMIT <= 0
			free(chunk);
#endif
			return -1;
		}
		libsha1_update(&state, chunk, (size_t)r * 8);
	}

	libsha1_digest(&state, NULL, 0, hashsum);

#if ALLOCA_LIMIT <= 0
	free(chunk);
#endif
	return 0;
}