13 #include <arpa/inet.h>
15 #include <linux/netfilter/nf_tables.h>
18 #include <libmnl/libmnl.h>
19 #include <libnftnl/expr.h>
20 #include <libnftnl/rule.h>
24 enum nft_registers dreg;
28 nftnl_expr_rt_set(
struct nftnl_expr *e, uint16_t type,
29 const void *data, uint32_t data_len)
34 case NFTNL_EXPR_RT_KEY:
35 memcpy(&rt->key, data, data_len);
37 case NFTNL_EXPR_RT_DREG:
38 memcpy(&rt->dreg, data, data_len);
45 nftnl_expr_rt_get(
const struct nftnl_expr *e, uint16_t type,
51 case NFTNL_EXPR_RT_KEY:
52 *data_len =
sizeof(rt->key);
54 case NFTNL_EXPR_RT_DREG:
55 *data_len =
sizeof(rt->dreg);
61 static int nftnl_expr_rt_cb(
const struct nlattr *attr,
void *data)
63 const struct nlattr **tb = data;
64 int type = mnl_attr_get_type(attr);
66 if (mnl_attr_type_valid(attr, NFTA_RT_MAX) < 0)
72 if (mnl_attr_validate(attr, MNL_TYPE_U32) < 0)
82 nftnl_expr_rt_build(
struct nlmsghdr *nlh,
const struct nftnl_expr *e)
86 if (e->flags & (1 << NFTNL_EXPR_RT_KEY))
87 mnl_attr_put_u32(nlh, NFTA_RT_KEY, htonl(rt->key));
88 if (e->flags & (1 << NFTNL_EXPR_RT_DREG))
89 mnl_attr_put_u32(nlh, NFTA_RT_DREG, htonl(rt->dreg));
93 nftnl_expr_rt_parse(
struct nftnl_expr *e,
struct nlattr *attr)
96 struct nlattr *tb[NFTA_RT_MAX+1] = {};
98 if (mnl_attr_parse_nested(attr, nftnl_expr_rt_cb, tb) < 0)
101 if (tb[NFTA_RT_KEY]) {
102 rt->key = ntohl(mnl_attr_get_u32(tb[NFTA_RT_KEY]));
103 e->flags |= (1 << NFTNL_EXPR_RT_KEY);
105 if (tb[NFTA_RT_DREG]) {
106 rt->dreg = ntohl(mnl_attr_get_u32(tb[NFTA_RT_DREG]));
107 e->flags |= (1 << NFTNL_EXPR_RT_DREG);
113 static const char *rt_key2str_array[NFT_RT_MAX + 1] = {
114 [NFT_RT_CLASSID] =
"classid",
115 [NFT_RT_NEXTHOP4] =
"nexthop4",
116 [NFT_RT_NEXTHOP6] =
"nexthop6",
117 [NFT_RT_TCPMSS] =
"tcpmss",
118 [NFT_RT_XFRM] =
"ipsec",
121 static const char *rt_key2str(uint8_t key)
123 if (key <= NFT_RT_MAX)
124 return rt_key2str_array[key];
129 static inline int str2rt_key(
const char *str)
133 for (i = 0; i < NFT_RT_MAX; i++) {
134 if (strcmp(str, rt_key2str_array[i]) == 0)
143 nftnl_expr_rt_snprintf(
char *buf,
size_t len,
144 uint32_t flags,
const struct nftnl_expr *e)
148 if (e->flags & (1 << NFTNL_EXPR_RT_DREG)) {
149 return snprintf(buf, len,
"load %s => reg %u ",
150 rt_key2str(rt->key), rt->dreg);
155 static struct attr_policy rt_attr_policy[__NFTNL_EXPR_RT_MAX] = {
156 [NFTNL_EXPR_RT_KEY] = { .maxlen =
sizeof(uint32_t) },
157 [NFTNL_EXPR_RT_DREG] = { .maxlen =
sizeof(uint32_t) },
160 struct expr_ops expr_ops_rt = {
163 .nftnl_max_attr = __NFTNL_EXPR_RT_MAX - 1,
164 .attr_policy = rt_attr_policy,
165 .set = nftnl_expr_rt_set,
166 .get = nftnl_expr_rt_get,
167 .parse = nftnl_expr_rt_parse,
168 .build = nftnl_expr_rt_build,
169 .output = nftnl_expr_rt_snprintf,