libnftnl  1.0.2
nft-table-add.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;
29  struct nft_table *t = NULL;
30  int ret;
31 
32  if (argc != 3) {
33  fprintf(stderr, "%s <family> <name>\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  nft_table_attr_set(t, NFT_TABLE_ATTR_NAME, argv[2]);
58 
59  nlh = nft_table_nlmsg_build_hdr(buf, NFT_MSG_NEWTABLE, family,
60  NLM_F_ACK, seq);
61  nft_table_nlmsg_build_payload(nlh, t);
62  nft_table_free(t);
63 
64  nl = mnl_socket_open(NETLINK_NETFILTER);
65  if (nl == NULL) {
66  perror("mnl_socket_open");
67  exit(EXIT_FAILURE);
68  }
69 
70  if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
71  perror("mnl_socket_bind");
72  exit(EXIT_FAILURE);
73  }
74  portid = mnl_socket_get_portid(nl);
75 
76  if (mnl_socket_sendto(nl, nlh, nlh->nlmsg_len) < 0) {
77  perror("mnl_socket_send");
78  exit(EXIT_FAILURE);
79  }
80 
81  ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
82  while (ret > 0) {
83  ret = mnl_cb_run(buf, ret, seq, portid, NULL, NULL);
84  if (ret <= 0)
85  break;
86  ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
87  }
88  if (ret == -1) {
89  perror("error");
90  exit(EXIT_FAILURE);
91  }
92  mnl_socket_close(nl);
93 
94  return EXIT_SUCCESS;
95 }