libnftnl  1.0.2
nft-table-upd.c
1 /*
2  * (C) 2012 by Pablo Neira Ayuso <pablo@netfilter.org>
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This software has been sponsored by Sophos Astaro <http://www.sophos.com>
10  */
11 
12 #include <stdlib.h>
13 #include <time.h>
14 #include <string.h>
15 #include <netinet/in.h>
16 
17 #include <linux/netfilter.h>
18 #include <linux/netfilter/nf_tables.h>
19 
20 #include <libmnl/libmnl.h>
21 #include <libnftnl/table.h>
22 
23 int main(int argc, char *argv[])
24 {
25  struct mnl_socket *nl;
26  char buf[MNL_SOCKET_BUFFER_SIZE];
27  struct nlmsghdr *nlh;
28  uint32_t portid, seq, family, flags;
29  struct nft_table *t = NULL;
30  int ret;
31 
32  if (argc != 4) {
33  fprintf(stderr, "%s <family> <name> <state>\n", argv[0]);
34  exit(EXIT_FAILURE);
35  }
36 
37  t = nft_table_alloc();
38  if (t == NULL) {
39  perror("OOM");
40  exit(EXIT_FAILURE);
41  }
42 
43  seq = time(NULL);
44  if (strcmp(argv[1], "ip") == 0)
45  family = NFPROTO_IPV4;
46  else if (strcmp(argv[1], "ip6") == 0)
47  family = NFPROTO_IPV6;
48  else if (strcmp(argv[1], "bridge") == 0)
49  family = NFPROTO_BRIDGE;
50  else if (strcmp(argv[1], "arp") == 0)
51  family = NFPROTO_ARP;
52  else {
53  fprintf(stderr, "Unknown family: ip, ip6, bridge, arp\n");
54  exit(EXIT_FAILURE);
55  }
56 
57  if (strcmp(argv[3], "active") == 0)
58  flags = 0;
59  else if (strcmp(argv[3], "dormant") == 0)
60  flags = NFT_TABLE_F_DORMANT;
61  else {
62  fprintf(stderr, "Unknown state: active, dormant\n");
63  exit(EXIT_FAILURE);
64  }
65 
66  nft_table_attr_set(t, NFT_TABLE_ATTR_NAME, argv[2]);
67  nft_table_attr_set_u32(t, NFT_TABLE_ATTR_FLAGS, flags);
68 
69  nlh = nft_table_nlmsg_build_hdr(buf, NFT_MSG_NEWTABLE, family,
70  NLM_F_ACK, seq);
71  nft_table_nlmsg_build_payload(nlh, t);
72  nft_table_free(t);
73 
74  nl = mnl_socket_open(NETLINK_NETFILTER);
75  if (nl == NULL) {
76  perror("mnl_socket_open");
77  exit(EXIT_FAILURE);
78  }
79 
80  if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
81  perror("mnl_socket_bind");
82  exit(EXIT_FAILURE);
83  }
84  portid = mnl_socket_get_portid(nl);
85 
86  if (mnl_socket_sendto(nl, nlh, nlh->nlmsg_len) < 0) {
87  perror("mnl_socket_send");
88  exit(EXIT_FAILURE);
89  }
90 
91  ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
92  while (ret > 0) {
93  ret = mnl_cb_run(buf, ret, seq, portid, NULL, NULL);
94  if (ret <= 0)
95  break;
96  ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
97  }
98  if (ret == -1) {
99  perror("error");
100  exit(EXIT_FAILURE);
101  }
102  mnl_socket_close(nl);
103 
104  return EXIT_SUCCESS;
105 }