libnftnl  1.0.2
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_nft_rule_expr(struct nft_rule_expr *rule_a,
31  struct nft_rule_expr *rule_b)
32 {
33  if (nft_rule_expr_get_u32(rule_a, NFT_EXPR_META_KEY) !=
34  nft_rule_expr_get_u32(rule_b, NFT_EXPR_META_KEY))
35  print_err("Expr NFT_EXPR_META_KEY mismatches");
36  if (nft_rule_expr_get_u32(rule_a, NFT_EXPR_META_DREG) !=
37  nft_rule_expr_get_u32(rule_b, NFT_EXPR_META_DREG))
38  print_err("Expr NFT_EXPR_META_DREG mismatches");
39 }
40 
41 int main(int argc, char *argv[])
42 {
43  struct nft_rule *a, *b;
44  struct nft_rule_expr *ex;
45  struct nlmsghdr *nlh;
46  char buf[4096];
47  struct nft_rule_expr_iter *iter_a, *iter_b;
48  struct nft_rule_expr *rule_a, *rule_b;
49 
50  a = nft_rule_alloc();
51  b = nft_rule_alloc();
52  if (a == NULL || b == NULL)
53  print_err("OOM");
54  ex = nft_rule_expr_alloc("meta");
55  if (ex == NULL)
56  print_err("OOM");
57 
58  nft_rule_expr_set_u32(ex, NFT_EXPR_META_KEY, 0x1234568);
59  nft_rule_expr_set_u32(ex, NFT_EXPR_META_DREG, 0x12345678);
60 
61  nft_rule_add_expr(a, ex);
62 
63  nlh = nft_rule_nlmsg_build_hdr(buf, NFT_MSG_NEWRULE, AF_INET, 0, 1234);
64  nft_rule_nlmsg_build_payload(nlh, a);
65  if (nft_rule_nlmsg_parse(nlh, b) < 0)
66  print_err("parsing problems");
67 
68  iter_a = nft_rule_expr_iter_create(a);
69  iter_b = nft_rule_expr_iter_create(b);
70  if (iter_a == NULL || iter_b == NULL)
71  print_err("OOM");
72 
73  rule_a = nft_rule_expr_iter_next(iter_a);
74  rule_b = nft_rule_expr_iter_next(iter_b);
75  if (rule_a == NULL || rule_b == NULL)
76  print_err("OOM");
77 
78  cmp_nft_rule_expr(rule_a, rule_b);
79 
80  if (nft_rule_expr_iter_next(iter_a) != NULL ||
81  nft_rule_expr_iter_next(iter_b) != NULL)
82  print_err("More 1 expr.");
83 
84  nft_rule_expr_iter_destroy(iter_a);
85  nft_rule_expr_iter_destroy(iter_b);
86  nft_rule_free(a);
87  nft_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 }
Definition: rule.c:34