xref: /aosp_15_r20/external/iptables/extensions/libxt_mac.c (revision a71a954618bbadd4a345637e5edcf36eec826889)
1 #include <stdio.h>
2 #if defined(__GLIBC__) && __GLIBC__ == 2
3 #include <net/ethernet.h>
4 #else
5 #include <linux/if_ether.h>
6 #endif
7 #include <xtables.h>
8 #include <linux/netfilter/xt_mac.h>
9 
10 enum {
11 	O_MAC = 0,
12 };
13 
mac_help(void)14 static void mac_help(void)
15 {
16 	printf(
17 "mac match options:\n"
18 "[!] --mac-source XX:XX:XX:XX:XX:XX\n"
19 "				Match source MAC address\n");
20 }
21 
22 #define s struct xt_mac_info
23 static const struct xt_option_entry mac_opts[] = {
24 	{.name = "mac-source", .id = O_MAC, .type = XTTYPE_ETHERMAC,
25 	 .flags = XTOPT_MAND | XTOPT_INVERT | XTOPT_PUT,
26 	 XTOPT_POINTER(s, srcaddr)},
27 	XTOPT_TABLEEND,
28 };
29 #undef s
30 
mac_parse(struct xt_option_call * cb)31 static void mac_parse(struct xt_option_call *cb)
32 {
33 	struct xt_mac_info *macinfo = cb->data;
34 
35 	xtables_option_parse(cb);
36 	if (cb->invert)
37 		macinfo->invert = 1;
38 }
39 
40 static void
mac_print(const void * ip,const struct xt_entry_match * match,int numeric)41 mac_print(const void *ip, const struct xt_entry_match *match, int numeric)
42 {
43 	const struct xt_mac_info *info = (void *)match->data;
44 
45 	printf(" MAC ");
46 
47 	if (info->invert)
48 		printf("! ");
49 
50 	xtables_print_mac(info->srcaddr);
51 }
52 
mac_save(const void * ip,const struct xt_entry_match * match)53 static void mac_save(const void *ip, const struct xt_entry_match *match)
54 {
55 	const struct xt_mac_info *info = (void *)match->data;
56 
57 	if (info->invert)
58 		printf(" !");
59 
60 	printf(" --mac-source ");
61 	xtables_print_mac(info->srcaddr);
62 }
63 
print_mac_xlate(const unsigned char * macaddress,struct xt_xlate * xl)64 static void print_mac_xlate(const unsigned char *macaddress,
65 			    struct xt_xlate *xl)
66 {
67 	unsigned int i;
68 
69 	xt_xlate_add(xl, "%02x", macaddress[0]);
70 	for (i = 1; i < ETH_ALEN; ++i)
71 		xt_xlate_add(xl, ":%02x", macaddress[i]);
72 }
73 
mac_xlate(struct xt_xlate * xl,const struct xt_xlate_mt_params * params)74 static int mac_xlate(struct xt_xlate *xl,
75 		     const struct xt_xlate_mt_params *params)
76 {
77 	const struct xt_mac_info *info = (void *)params->match->data;
78 
79 	xt_xlate_add(xl, "ether saddr%s ", info->invert ? " !=" : "");
80 	print_mac_xlate(info->srcaddr, xl);
81 
82 	return 1;
83 }
84 
85 static struct xtables_match mac_match = {
86 	.family		= NFPROTO_UNSPEC,
87 	.name		= "mac",
88 	.version	= XTABLES_VERSION,
89 	.size		= XT_ALIGN(sizeof(struct xt_mac_info)),
90 	.userspacesize	= XT_ALIGN(sizeof(struct xt_mac_info)),
91 	.help		= mac_help,
92 	.x6_parse	= mac_parse,
93 	.print		= mac_print,
94 	.save		= mac_save,
95 	.x6_options	= mac_opts,
96 	.xlate		= mac_xlate,
97 };
98 
_init(void)99 void _init(void)
100 {
101 	xtables_register_match(&mac_match);
102 }
103