16 #include <netinet/in.h>
17 #include <sys/types.h>
22 #include <linux/netfilter/nf_tables.h>
24 #include <libmnl/libmnl.h>
25 #include <libnftnl/table.h>
26 #include <libnftnl/common.h>
28 static struct nftnl_table *table_parse_file(
const char *file, uint16_t format)
32 struct nftnl_parse_err *err;
35 t = nftnl_table_alloc();
41 fd = open(file, O_RDONLY);
47 if (read(fd, data,
sizeof(data)) < 0) {
54 err = nftnl_parse_err_alloc();
60 if (nftnl_table_parse(t, format, data, err) < 0) {
61 nftnl_parse_perror(
"Unable to parse file", err);
62 nftnl_parse_err_free(err);
66 nftnl_parse_err_free(err);
71 int main(
int argc,
char *argv[])
73 struct mnl_socket *nl;
74 char buf[MNL_SOCKET_BUFFER_SIZE];
76 uint32_t portid, seq, table_seq;
79 uint16_t family, format, outformat;
80 struct mnl_nlmsg_batch *batch;
83 printf(
"Usage: %s {json} <file>\n", argv[0]);
87 if (strcmp(argv[1],
"json") == 0) {
88 format = NFTNL_PARSE_JSON;
89 outformat = NFTNL_OUTPUT_JSON;
91 printf(
"Unknown format: only json is supported\n");
95 t = table_parse_file(argv[2], format);
99 nftnl_table_fprintf(stdout, t, outformat, 0);
100 fprintf(stdout,
"\n");
103 batching = nftnl_batch_is_supported();
105 perror(
"cannot talk to nfnetlink");
109 batch = mnl_nlmsg_batch_start(buf,
sizeof(buf));
112 nftnl_batch_begin(mnl_nlmsg_batch_current(batch), seq++);
113 mnl_nlmsg_batch_next(batch);
116 family = nftnl_table_get_u32(t, NFTNL_TABLE_FAMILY);
119 nlh = nftnl_table_nlmsg_build_hdr(mnl_nlmsg_batch_current(batch),
120 NFT_MSG_NEWTABLE, family,
121 NLM_F_CREATE|NLM_F_ACK, seq++);
122 nftnl_table_nlmsg_build_payload(nlh, t);
124 mnl_nlmsg_batch_next(batch);
127 nftnl_batch_end(mnl_nlmsg_batch_current(batch), seq++);
128 mnl_nlmsg_batch_next(batch);
131 nl = mnl_socket_open(NETLINK_NETFILTER);
133 perror(
"mnl_socket_open");
137 if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
138 perror(
"mnl_socket_bind");
141 portid = mnl_socket_get_portid(nl);
143 if (mnl_socket_sendto(nl, mnl_nlmsg_batch_head(batch),
144 mnl_nlmsg_batch_size(batch)) < 0) {
145 perror(
"mnl_socket_send");
149 mnl_nlmsg_batch_stop(batch);
151 ret = mnl_socket_recvfrom(nl, buf,
sizeof(buf));
153 ret = mnl_cb_run(buf, ret, table_seq, portid, NULL, NULL);
156 ret = mnl_socket_recvfrom(nl, buf,
sizeof(buf));
163 mnl_socket_close(nl);