libnftnl  1.2.5
nft-expr_meta-test.c
1 /*
2  * (C) 2013 by Ana Rey Botello <anarey@gmail.com>
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  */
10 
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <netinet/in.h>
15 #include <netinet/ip.h>
16 
17 #include <linux/netfilter/nf_tables.h>
18 #include <libmnl/libmnl.h>
19 #include <libnftnl/rule.h>
20 #include <libnftnl/expr.h>
21 
22 static int test_ok = 1;
23 
24 static void print_err(const char *msg)
25 {
26  test_ok = 0;
27  printf("\033[31mERROR:\e[0m %s\n", msg);
28 }
29 
30 static void cmp_nftnl_expr(struct nftnl_expr *rule_a,
31  struct nftnl_expr *rule_b)
32 {
33  if (nftnl_expr_get_u32(rule_a, NFTNL_EXPR_META_KEY) !=
34  nftnl_expr_get_u32(rule_b, NFTNL_EXPR_META_KEY))
35  print_err("Expr NFTNL_EXPR_META_KEY mismatches");
36  if (nftnl_expr_get_u32(rule_a, NFTNL_EXPR_META_DREG) !=
37  nftnl_expr_get_u32(rule_b, NFTNL_EXPR_META_DREG))
38  print_err("Expr NFTNL_EXPR_META_DREG mismatches");
39 }
40 
41 int main(int argc, char *argv[])
42 {
43  struct nftnl_rule *a, *b;
44  struct nftnl_expr *ex;
45  struct nlmsghdr *nlh;
46  char buf[4096];
47  struct nftnl_expr_iter *iter_a, *iter_b;
48  struct nftnl_expr *rule_a, *rule_b;
49 
50  a = nftnl_rule_alloc();
51  b = nftnl_rule_alloc();
52  if (a == NULL || b == NULL)
53  print_err("OOM");
54  ex = nftnl_expr_alloc("meta");
55  if (ex == NULL)
56  print_err("OOM");
57 
58  nftnl_expr_set_u32(ex, NFTNL_EXPR_META_KEY, 0x1234568);
59  nftnl_expr_set_u32(ex, NFTNL_EXPR_META_DREG, 0x78123456);
60 
61  nftnl_rule_add_expr(a, ex);
62 
63  nlh = nftnl_nlmsg_build_hdr(buf, NFT_MSG_NEWRULE, AF_INET, 0, 1234);
64  nftnl_rule_nlmsg_build_payload(nlh, a);
65  if (nftnl_rule_nlmsg_parse(nlh, b) < 0)
66  print_err("parsing problems");
67 
68  iter_a = nftnl_expr_iter_create(a);
69  iter_b = nftnl_expr_iter_create(b);
70  if (iter_a == NULL || iter_b == NULL)
71  print_err("OOM");
72 
73  rule_a = nftnl_expr_iter_next(iter_a);
74  rule_b = nftnl_expr_iter_next(iter_b);
75  if (rule_a == NULL || rule_b == NULL)
76  print_err("OOM");
77 
78  cmp_nftnl_expr(rule_a, rule_b);
79 
80  if (nftnl_expr_iter_next(iter_a) != NULL ||
81  nftnl_expr_iter_next(iter_b) != NULL)
82  print_err("More 1 expr.");
83 
84  nftnl_expr_iter_destroy(iter_a);
85  nftnl_expr_iter_destroy(iter_b);
86  nftnl_rule_free(a);
87  nftnl_rule_free(b);
88 
89  if (!test_ok)
90  exit(EXIT_FAILURE);
91 
92  printf("%s: \033[32mOK\e[0m\n", argv[0]);
93  return EXIT_SUCCESS;
94 }