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

#include "internal.h"

int read_octal(const char *str, int digits, sqfs_u64 *out)
{
	sqfs_u64 result = 0;

	while (digits > 0 && isspace(*str)) {
		++str;
		--digits;
	}

	while (digits > 0 && *str >= '0' && *str <= '7') {
		if (result > 0x1FFFFFFFFFFFFFFFUL) {
			fputs("numeric overflow parsing tar header\n", stderr);
			return -1;
		}

		result = (result << 3) | (*(str++) - '0');
		--digits;
	}

	*out = result;
	return 0;
}

int read_binary(const char *str, int digits, sqfs_u64 *out)
{
	sqfs_u64 x, ov, result = 0;
	bool first = true;

	while (digits > 0) {
		x = *((const unsigned char *)str++);
		--digits;

		if (first) {
			first = false;
			if (x == 0xFF) {
				result = 0xFFFFFFFFFFFFFFFFUL;
			} else {
				x &= 0x7F;
				result = 0;
				if (digits > 7 && x != 0)
					goto fail_ov;
			}
		}

		ov = (result >> 56) & 0xFF;

		if (ov != 0 && ov != 0xFF)
			goto fail_ov;

		result = (result << 8) | x;
	}

	*out = result;
	return 0;
fail_ov:
	fputs("numeric overflow parsing tar header\n", stderr);
	return -1;
}

int read_number(const char *str, int digits, sqfs_u64 *out)
{
	if (*((unsigned char *)str) & 0x80)
		return read_binary(str, digits, out);

	return read_octal(str, digits, out);
}

int pax_read_decimal(const char *str, sqfs_u64 *out)
{
	sqfs_u64 result = 0;

	while (*str >= '0' && *str <= '9') {
		if (result > 0xFFFFFFFFFFFFFFFFUL / 10) {
			fputs("numeric overflow parsing pax header\n", stderr);
			return -1;
		}

		result = (result * 10) + (*(str++) - '0');
	}

	*out = result;
	return 0;
}