tos_values.c revision 648fd1ad68ae2ec675ac07efee80783912535404
1#include <stdbool.h>
2#include <stdint.h>
3#include <stdio.h>
4#include <linux/ip.h>
5
6#ifndef IPTOS_NORMALSVC
7#	define IPTOS_NORMALSVC 0
8#endif
9
10struct tos_value_mask {
11	uint8_t value, mask;
12};
13
14static const struct tos_symbol_info {
15	unsigned char value;
16	const char *name;
17} tos_symbol_names[] = {
18	{IPTOS_LOWDELAY,    "Minimize-Delay"},
19	{IPTOS_THROUGHPUT,  "Maximize-Throughput"},
20	{IPTOS_RELIABILITY, "Maximize-Reliability"},
21	{IPTOS_MINCOST,     "Minimize-Cost"},
22	{IPTOS_NORMALSVC,   "Normal-Service"},
23	{},
24};
25
26/*
27 * tos_parse_numeric - parse sth. like "15/255"
28 *
29 * @str:	input string
30 * @tvm:	(value/mask) tuple
31 * @max:	maximum allowed value (must be pow(2,some_int)-1)
32 */
33static bool tos_parse_numeric(const char *str, struct tos_value_mask *tvm,
34                              unsigned int max)
35{
36	unsigned int value;
37	char *end;
38
39	xtables_strtoui(str, &end, &value, 0, max);
40	tvm->value = value;
41	tvm->mask  = max;
42
43	if (*end == '/') {
44		const char *p = end + 1;
45
46		if (!xtables_strtoui(p, &end, &value, 0, max))
47			xtables_error(PARAMETER_PROBLEM, "Illegal value: \"%s\"",
48			           str);
49		tvm->mask = value;
50	}
51
52	if (*end != '\0')
53		xtables_error(PARAMETER_PROBLEM, "Illegal value: \"%s\"", str);
54	return true;
55}
56
57/**
58 * @str:	input string
59 * @tvm:	(value/mask) tuple
60 * @def_mask:	mask to force when a symbolic name is used
61 */
62static bool tos_parse_symbolic(const char *str, struct tos_value_mask *tvm,
63    unsigned int def_mask)
64{
65	static const unsigned int max = UINT8_MAX;
66	const struct tos_symbol_info *symbol;
67	char *tmp;
68
69	if (xtables_strtoui(str, &tmp, NULL, 0, max))
70		return tos_parse_numeric(str, tvm, max);
71
72	/* Do not consider ECN bits when using preset names */
73	tvm->mask = def_mask;
74	for (symbol = tos_symbol_names; symbol->name != NULL; ++symbol)
75		if (strcasecmp(str, symbol->name) == 0) {
76			tvm->value = symbol->value;
77			return true;
78		}
79
80	xtables_error(PARAMETER_PROBLEM, "Symbolic name \"%s\" is unknown", str);
81	return false;
82}
83
84static bool tos_try_print_symbolic(const char *prefix,
85    u_int8_t value, u_int8_t mask)
86{
87	const struct tos_symbol_info *symbol;
88
89	if (mask != 0x3F)
90		return false;
91
92	for (symbol = tos_symbol_names; symbol->name != NULL; ++symbol)
93		if (value == symbol->value) {
94			printf("%s%s ", prefix, symbol->name);
95			return true;
96		}
97
98	return false;
99}
100