Branch data Line data Source code
1 : : /* SPDX-License-Identifier: GPL-2.0-only */
2 : : /*
3 : : * Copyright (c) 2023 Meta Platforms, Inc. and affiliates.
4 : : */
5 : :
6 : : // clang-format off
7 : : // Include net/if.h before any kernel header to avoid conflicts.
8 : : #include <net/if.h>
9 : : // clang-format on
10 : :
11 : : #include "bpfilter/if.h"
12 : :
13 : : #include <errno.h>
14 : : #include <limits.h>
15 : : #include <sys/types.h>
16 : :
17 : : #include "bpfilter/helper.h"
18 : :
19 : : static char _bf_if_name[IFNAMSIZ];
20 : :
21 : 53 : int bf_if_index_from_name(const char *name)
22 : : {
23 : : unsigned int r;
24 : :
25 : : assert(name);
26 : :
27 : 53 : r = if_nametoindex(name);
28 [ + + ]: 53 : if (r == 0)
29 : : return -ENOENT;
30 : :
31 [ - + ]: 17 : if (r > INT_MAX)
32 : 0 : return -E2BIG;
33 : :
34 : : return (int)r;
35 : : }
36 : :
37 : 4 : const char *bf_if_name_from_index(int index)
38 : : {
39 [ + + ]: 4 : if (!if_indextoname(index, _bf_if_name))
40 : 2 : return NULL;
41 : :
42 : : return _bf_if_name;
43 : : }
44 : :
45 : 51 : int bf_if_index_from_str(const char *str, uint32_t *ifindex)
46 : : {
47 : : int idx;
48 : : unsigned long parsed;
49 : : char *endptr;
50 : :
51 : : assert(str);
52 : : assert(ifindex);
53 : :
54 : 51 : idx = bf_if_index_from_name(str);
55 [ + + ]: 51 : if (idx > 0) {
56 : 16 : *ifindex = (uint32_t)idx;
57 : 16 : return 0;
58 : : }
59 : :
60 : 35 : errno = 0;
61 : 35 : parsed = strtoul(str, &endptr, BF_BASE_10);
62 [ + + + - : 35 : if (*endptr == '\0' && errno == 0 && parsed > 0 && parsed <= UINT32_MAX) {
+ + ]
63 : 23 : *ifindex = (uint32_t)parsed;
64 : 23 : return 0;
65 : : }
66 : :
67 : : return -EINVAL;
68 : : }
|