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 {xml|json} <file>\n", argv[0]);
87 if (strcmp(argv[1],
"xml") == 0) {
88 format = NFTNL_PARSE_XML;
89 outformat = NFTNL_OUTPUT_XML;
90 }
else if (strcmp(argv[1],
"json") == 0) {
91 format = NFTNL_PARSE_JSON;
92 outformat = NFTNL_OUTPUT_JSON;
94 printf(
"Unknown format: xml, json\n");
98 t = table_parse_file(argv[2], format);
102 nftnl_table_fprintf(stdout, t, outformat, 0);
103 fprintf(stdout,
"\n");
106 batching = nftnl_batch_is_supported();
108 perror(
"cannot talk to nfnetlink");
112 batch = mnl_nlmsg_batch_start(buf,
sizeof(buf));
115 nftnl_batch_begin(mnl_nlmsg_batch_current(batch), seq++);
116 mnl_nlmsg_batch_next(batch);
119 family = nftnl_table_get_u32(t, NFTNL_TABLE_FAMILY);
122 nlh = nftnl_table_nlmsg_build_hdr(mnl_nlmsg_batch_current(batch),
123 NFT_MSG_NEWTABLE, family,
124 NLM_F_CREATE|NLM_F_ACK, seq++);
125 nftnl_table_nlmsg_build_payload(nlh, t);
127 mnl_nlmsg_batch_next(batch);
130 nftnl_batch_end(mnl_nlmsg_batch_current(batch), seq++);
131 mnl_nlmsg_batch_next(batch);
134 nl = mnl_socket_open(NETLINK_NETFILTER);
136 perror(
"mnl_socket_open");
140 if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
141 perror(
"mnl_socket_bind");
144 portid = mnl_socket_get_portid(nl);
146 if (mnl_socket_sendto(nl, mnl_nlmsg_batch_head(batch),
147 mnl_nlmsg_batch_size(batch)) < 0) {
148 perror(
"mnl_socket_send");
152 mnl_nlmsg_batch_stop(batch);
154 ret = mnl_socket_recvfrom(nl, buf,
sizeof(buf));
156 ret = mnl_cb_run(buf, ret, table_seq, portid, NULL, NULL);
159 ret = mnl_socket_recvfrom(nl, buf,
sizeof(buf));
166 mnl_socket_close(nl);