libnftnl  1.2.9
nft-set-del.c
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 /*
3  * (C) 2012 by Pablo Neira Ayuso <pablo@netfilter.org>
4  *
5  * This software has been sponsored by Sophos Astaro <http://www.sophos.com>
6  */
7 
8 #include <stdlib.h>
9 #include <time.h>
10 #include <string.h>
11 #include <netinet/in.h>
12 
13 #include <linux/netfilter.h>
14 #include <linux/netfilter/nf_tables.h>
15 
16 #include <libmnl/libmnl.h>
17 #include <libnftnl/set.h>
18 
19 int main(int argc, char *argv[])
20 {
21  struct mnl_socket *nl;
22  char buf[MNL_SOCKET_BUFFER_SIZE];
23  struct nlmsghdr *nlh;
24  struct mnl_nlmsg_batch *batch;
25  uint32_t portid, seq, family;
26  struct nftnl_set *t = NULL;
27  int ret;
28 
29  if (argc != 4) {
30  fprintf(stderr, "%s <family> <table> <set>\n", argv[0]);
31  exit(EXIT_FAILURE);
32  }
33 
34  t = nftnl_set_alloc();
35  if (t == NULL) {
36  perror("OOM");
37  exit(EXIT_FAILURE);
38  }
39 
40  seq = time(NULL);
41  if (strcmp(argv[1], "ip") == 0)
42  family = NFPROTO_IPV4;
43  else if (strcmp(argv[1], "ip6") == 0)
44  family = NFPROTO_IPV6;
45  else if (strcmp(argv[1], "inet") == 0)
46  family = NFPROTO_INET;
47  else if (strcmp(argv[1], "bridge") == 0)
48  family = NFPROTO_BRIDGE;
49  else if (strcmp(argv[1], "arp") == 0)
50  family = NFPROTO_ARP;
51  else {
52  fprintf(stderr, "Unknown family: ip, ip6, inet, bridge, arp\n");
53  exit(EXIT_FAILURE);
54  }
55 
56  batch = mnl_nlmsg_batch_start(buf, sizeof(buf));
57 
58  nftnl_batch_begin(mnl_nlmsg_batch_current(batch), seq++);
59  mnl_nlmsg_batch_next(batch);
60 
61  nlh = nftnl_nlmsg_build_hdr(mnl_nlmsg_batch_current(batch),
62  NFT_MSG_DELSET, family, NLM_F_ACK, seq);
63  nftnl_set_set_str(t, NFTNL_SET_TABLE, argv[2]);
64  nftnl_set_set_str(t, NFTNL_SET_NAME, argv[3]);
65 
66  nftnl_set_nlmsg_build_payload(nlh, t);
67  nftnl_set_free(t);
68  mnl_nlmsg_batch_next(batch);
69 
70  nftnl_batch_end(mnl_nlmsg_batch_current(batch), seq++);
71  mnl_nlmsg_batch_next(batch);
72 
73  nl = mnl_socket_open(NETLINK_NETFILTER);
74  if (nl == NULL) {
75  perror("mnl_socket_open");
76  exit(EXIT_FAILURE);
77  }
78 
79  if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
80  perror("mnl_socket_bind");
81  exit(EXIT_FAILURE);
82  }
83  portid = mnl_socket_get_portid(nl);
84 
85  ret = mnl_socket_sendto(nl, mnl_nlmsg_batch_head(batch),
86  mnl_nlmsg_batch_size(batch));
87  if (ret < 0) {
88  perror("mnl_socket_send");
89  exit(EXIT_FAILURE);
90  }
91 
92  mnl_nlmsg_batch_stop(batch);
93 
94  ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
95  while (ret < 0) {
96  perror("mnl_socket_recvfrom");
97  exit(EXIT_FAILURE);
98  }
99 
100  ret = mnl_cb_run(buf, ret, 0, portid, NULL, NULL);
101  if (ret < 0) {
102  perror("mnl_cb_run");
103  exit(EXIT_FAILURE);
104  }
105  mnl_socket_close(nl);
106 
107  return EXIT_SUCCESS;
108 }