12 #include <arpa/inet.h>
16 #include <linux/netfilter/nf_tables.h>
18 #include <libmnl/libmnl.h>
19 #include <libnftnl/object.h>
25 nftnl_obj_counter_set(
struct nftnl_obj *e, uint16_t type,
26 const void *data, uint32_t data_len)
28 struct nftnl_obj_counter *ctr = nftnl_obj_data(e);
31 case NFTNL_OBJ_CTR_BYTES:
32 memcpy(&ctr->bytes, data,
sizeof(ctr->bytes));
34 case NFTNL_OBJ_CTR_PKTS:
35 memcpy(&ctr->pkts, data,
sizeof(ctr->pkts));
44 nftnl_obj_counter_get(
const struct nftnl_obj *e, uint16_t type,
47 struct nftnl_obj_counter *ctr = nftnl_obj_data(e);
50 case NFTNL_OBJ_CTR_BYTES:
51 *data_len =
sizeof(ctr->bytes);
53 case NFTNL_OBJ_CTR_PKTS:
54 *data_len =
sizeof(ctr->pkts);
60 static int nftnl_obj_counter_cb(
const struct nlattr *attr,
void *data)
62 const struct nlattr **tb = data;
63 int type = mnl_attr_get_type(attr);
65 if (mnl_attr_type_valid(attr, NFTA_COUNTER_MAX) < 0)
69 case NFTA_COUNTER_BYTES:
70 case NFTA_COUNTER_PACKETS:
71 if (mnl_attr_validate(attr, MNL_TYPE_U64) < 0)
81 nftnl_obj_counter_build(
struct nlmsghdr *nlh,
const struct nftnl_obj *e)
83 struct nftnl_obj_counter *ctr = nftnl_obj_data(e);
85 if (e->flags & (1 << NFTNL_OBJ_CTR_BYTES))
86 mnl_attr_put_u64(nlh, NFTA_COUNTER_BYTES, htobe64(ctr->bytes));
87 if (e->flags & (1 << NFTNL_OBJ_CTR_PKTS))
88 mnl_attr_put_u64(nlh, NFTA_COUNTER_PACKETS, htobe64(ctr->pkts));
92 nftnl_obj_counter_parse(
struct nftnl_obj *e,
struct nlattr *attr)
94 struct nftnl_obj_counter *ctr = nftnl_obj_data(e);
95 struct nlattr *tb[NFTA_COUNTER_MAX+1] = {};
97 if (mnl_attr_parse_nested(attr, nftnl_obj_counter_cb, tb) < 0)
100 if (tb[NFTA_COUNTER_BYTES]) {
101 ctr->bytes = be64toh(mnl_attr_get_u64(tb[NFTA_COUNTER_BYTES]));
102 e->flags |= (1 << NFTNL_OBJ_CTR_BYTES);
104 if (tb[NFTA_COUNTER_PACKETS]) {
105 ctr->pkts = be64toh(mnl_attr_get_u64(tb[NFTA_COUNTER_PACKETS]));
106 e->flags |= (1 << NFTNL_OBJ_CTR_PKTS);
112 static int nftnl_obj_counter_snprintf_default(
char *buf,
size_t len,
113 const struct nftnl_obj *e)
115 struct nftnl_obj_counter *ctr = nftnl_obj_data(e);
117 return snprintf(buf, len,
"pkts %"PRIu64
" bytes %"PRIu64
" ",
118 ctr->pkts, ctr->bytes);
121 static int nftnl_obj_counter_snprintf(
char *buf,
size_t len, uint32_t type,
123 const struct nftnl_obj *e)
129 case NFTNL_OUTPUT_DEFAULT:
130 return nftnl_obj_counter_snprintf_default(buf, len, e);
131 case NFTNL_OUTPUT_XML:
132 case NFTNL_OUTPUT_JSON:
139 struct obj_ops obj_ops_counter = {
141 .type = NFT_OBJECT_COUNTER,
142 .alloc_len =
sizeof(
struct nftnl_obj_counter),
143 .max_attr = NFTA_COUNTER_MAX,
144 .set = nftnl_obj_counter_set,
145 .get = nftnl_obj_counter_get,
146 .parse = nftnl_obj_counter_parse,
147 .build = nftnl_obj_counter_build,
148 .snprintf = nftnl_obj_counter_snprintf,