libnftnl 1.2.9
nft-expr_target-test.c
1/* SPDX-License-Identifier: GPL-2.0-or-later */
2/*
3 * (C) 2013 by Ana Rey Botello <anarey@gmail.com>
4 */
5
6#include <stdio.h>
7#include <stdlib.h>
8#include <string.h>
9
10#include <netinet/in.h>
11#include <netinet/ip.h>
12#include <linux/netfilter/nf_tables.h>
13#include <libmnl/libmnl.h>
14#include <libnftnl/rule.h>
15#include <libnftnl/expr.h>
16
17static int test_ok = 1;
18
19static void print_err(const char *msg)
20{
21 test_ok = 0;
22 printf("\033[31mERROR:\e[0m %s\n", msg);
23}
24
25static void print_err2(const char *msg, uint32_t a, uint32_t b)
26{
27 test_ok = 0;
28 printf("\033[31mERROR:\e[0m %s size a: %d b: %d \n",msg, a, b);
29}
30
31static void cmp_nftnl_expr(struct nftnl_expr *rule_a,
32 struct nftnl_expr *rule_b)
33{
34 uint32_t lena, lenb;
35
36 if (strcmp(nftnl_expr_get_str(rule_a, NFTNL_EXPR_TG_NAME),
37 nftnl_expr_get_str(rule_b, NFTNL_EXPR_TG_NAME)) != 0)
38 print_err("Expr NFTNL_EXPR_TG_NAME mismatches");
39 if (nftnl_expr_get_u32(rule_a, NFTNL_EXPR_TG_REV) !=
40 nftnl_expr_get_u32(rule_b, NFTNL_EXPR_TG_REV))
41 print_err("Expr NFTNL_EXPR_TG_REV mismatches");
42 nftnl_expr_get(rule_a, NFTNL_EXPR_TG_INFO, &lena);
43 nftnl_expr_get(rule_b, NFTNL_EXPR_TG_INFO, &lenb);
44 if (lena != lenb)
45 print_err2("Expr NFTNL_EXPR_TG_INFO size mismatches", lena, lenb);
46}
47
48int main(int argc, char *argv[])
49{
50 struct nftnl_rule *a, *b;
51 struct nftnl_expr *ex;
52 struct nlmsghdr *nlh;
53 char buf[4096];
54 struct nftnl_expr_iter *iter_a, *iter_b;
55 struct nftnl_expr *rule_a, *rule_b;
56 char data[] = "0123456789abcdef";
57
58 a = nftnl_rule_alloc();
59 b = nftnl_rule_alloc();
60 if (a == NULL || b == NULL)
61 print_err("OOM");
62
63 ex = nftnl_expr_alloc("target");
64 if (ex == NULL)
65 print_err("OOM");
66
67 nftnl_expr_set(ex, NFTNL_EXPR_TG_NAME, "test", strlen("test"));
68 nftnl_expr_set_u32(ex, NFTNL_EXPR_TG_REV, 0x56781234);
69 nftnl_expr_set(ex, NFTNL_EXPR_TG_INFO, strdup(data), sizeof(data));
70 nftnl_rule_add_expr(a, ex);
71
72 nlh = nftnl_nlmsg_build_hdr(buf, NFT_MSG_NEWRULE, AF_INET, 0, 1234);
73 nftnl_rule_nlmsg_build_payload(nlh, a);
74
75 if (nftnl_rule_nlmsg_parse(nlh, b) < 0)
76 print_err("parsing problems");
77
78 iter_a = nftnl_expr_iter_create(a);
79 iter_b = nftnl_expr_iter_create(b);
80 if (iter_a == NULL || iter_b == NULL)
81 print_err("OOM");
82
83 rule_a = nftnl_expr_iter_next(iter_a);
84 rule_b = nftnl_expr_iter_next(iter_b);
85 if (rule_a == NULL || rule_b == NULL)
86 print_err("OOM");
87
88 cmp_nftnl_expr(rule_a, rule_b);
89
90 if (nftnl_expr_iter_next(iter_a) != NULL ||
91 nftnl_expr_iter_next(iter_b) != NULL)
92 print_err("More 1 expr.");
93
94 nftnl_expr_iter_destroy(iter_a);
95 nftnl_expr_iter_destroy(iter_b);
96 nftnl_rule_free(a);
97 nftnl_rule_free(b);
98
99 if (!test_ok)
100 exit(EXIT_FAILURE);
101 printf("%s: \033[32mOK\e[0m\n", argv[0]);
102 return EXIT_SUCCESS;
103}