17 #include <netinet/in.h>
18 #include <arpa/inet.h>
19 #include <sys/types.h>
24 #include <linux/netfilter.h>
25 #include <linux/netfilter/nf_tables.h>
27 #include <libmnl/libmnl.h>
28 #include <libnftnl/rule.h>
30 static struct nftnl_rule *rule_parse_file(
const char *file, uint16_t format)
34 struct nftnl_parse_err *err;
37 fd = open(file, O_RDONLY);
43 if (read(fd, data,
sizeof(data)) < 0) {
50 r = nftnl_rule_alloc();
56 err = nftnl_parse_err_alloc();
62 if (nftnl_rule_parse(r, format, data, err) < 0) {
63 nftnl_parse_perror(
"Unable to parse file", err);
64 nftnl_parse_err_free(err);
69 nftnl_rule_unset(r, NFTNL_RULE_HANDLE);
71 nftnl_parse_err_free(err);
75 int main(
int argc,
char *argv[])
77 struct mnl_socket *nl;
78 struct mnl_nlmsg_batch *batch;
79 char buf[MNL_SOCKET_BUFFER_SIZE];
81 uint32_t portid, seq, rule_seq;
84 uint16_t family, format, outformat;
87 printf(
"Usage: %s {json} <file>\n", argv[0]);
91 if (strcmp(argv[1],
"json") == 0) {
92 format = NFTNL_PARSE_JSON;
93 outformat = NFTNL_OUTPUT_JSON;
95 printf(
"Unknown format: json\n");
99 r = rule_parse_file(argv[2], format);
103 nftnl_rule_fprintf(stdout, r, outformat, 0);
104 fprintf(stdout,
"\n");
106 batching = nftnl_batch_is_supported();
108 perror(
"Cannot talk to nfnetlink");
113 batch = mnl_nlmsg_batch_start(buf,
sizeof(buf));
116 nftnl_batch_begin(mnl_nlmsg_batch_current(batch), seq++);
117 mnl_nlmsg_batch_next(batch);
121 family = nftnl_rule_get_u32(r, NFTNL_RULE_FAMILY);
122 nlh = nftnl_rule_nlmsg_build_hdr(mnl_nlmsg_batch_current(batch),
123 NFT_MSG_NEWRULE, family,
124 NLM_F_CREATE|NLM_F_APPEND|NLM_F_ACK,
126 nftnl_rule_nlmsg_build_payload(nlh, r);
128 mnl_nlmsg_batch_next(batch);
131 nftnl_batch_end(mnl_nlmsg_batch_current(batch), seq++);
132 mnl_nlmsg_batch_next(batch);
135 nl = mnl_socket_open(NETLINK_NETFILTER);
137 perror(
"mnl_socket_open");
141 if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
142 perror(
"mnl_socket_bind");
145 portid = mnl_socket_get_portid(nl);
147 if (mnl_socket_sendto(nl, mnl_nlmsg_batch_head(batch),
148 mnl_nlmsg_batch_size(batch)) < 0) {
149 perror(
"mnl_socket_send");
153 mnl_nlmsg_batch_stop(batch);
155 ret = mnl_socket_recvfrom(nl, buf,
sizeof(buf));
157 ret = mnl_cb_run(buf, ret, rule_seq, portid, NULL, NULL);
160 ret = mnl_socket_recvfrom(nl, buf,
sizeof(buf));
166 mnl_socket_close(nl);