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

#include "tar/format.h"

#include <ctype.h>
#include <stdio.h>

static 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;
}

static 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 (*((const unsigned char *)str) & 0x80)
		return read_binary(str, digits, out);

	return read_octal(str, digits, out);
}