libnftnl  1.2.2
nft-expr_reject-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 
15 #include <netinet/in.h>
16 #include <netinet/ip.h>
17 #include <linux/netfilter/nf_tables.h>
18 #include <linux/netfilter/xt_iprange.h>
19 #include <libmnl/libmnl.h>
20 #include <libnftnl/rule.h>
21 #include <libnftnl/expr.h>
22 
23 static int test_ok = 1;
24 
25 static void print_err(const char *msg)
26 {
27  test_ok = 0;
28  printf("\033[31mERROR:\e[0m %s\n", msg);
29 }
30 
31 static void cmp_nftnl_expr(struct nftnl_expr *rule_a,
32  struct nftnl_expr *rule_b)
33 {
34  if (nftnl_expr_get_u32(rule_a, NFTNL_EXPR_REJECT_TYPE) !=
35  nftnl_expr_get_u32(rule_b, NFTNL_EXPR_REJECT_TYPE))
36  print_err("Expr NFTNL_EXPR_REJECT_TYPE mismatches");
37  if (nftnl_expr_get_u32(rule_a, NFTNL_EXPR_REJECT_CODE) !=
38  nftnl_expr_get_u32(rule_b, NFTNL_EXPR_REJECT_CODE))
39  print_err("Expr NFTNL_EXPR_REJECT_CODE mismatches");
40 }
41 
42 int main(int argc, char *argv[])
43 {
44  struct nftnl_rule *a, *b;
45  struct nftnl_expr *ex;
46  struct nlmsghdr *nlh;
47  char buf[4096];
48  struct nftnl_expr_iter *iter_a, *iter_b;
49  struct nftnl_expr *rule_a, *rule_b;
50 
51  a = nftnl_rule_alloc();
52  b = nftnl_rule_alloc();
53  if (a == NULL || b == NULL)
54  print_err("OOM");
55  ex = nftnl_expr_alloc("reject");
56  if (ex == NULL)
57  print_err("OOM");
58 
59  nftnl_expr_set_u32(ex, NFTNL_EXPR_REJECT_TYPE, 0x12345678);
60  nftnl_expr_set_u32(ex, NFTNL_EXPR_REJECT_CODE, 0x45681234);
61 
62  nftnl_rule_add_expr(a, ex);
63 
64  nlh = nftnl_rule_nlmsg_build_hdr(buf, NFT_MSG_NEWRULE, AF_INET, 0, 1234);
65  nftnl_rule_nlmsg_build_payload(nlh, a);
66 
67  if (nftnl_rule_nlmsg_parse(nlh, b) < 0)
68  print_err("parsing problems");
69 
70  iter_a = nftnl_expr_iter_create(a);
71  iter_b = nftnl_expr_iter_create(b);
72  if (iter_a == NULL || iter_b == NULL)
73  print_err("OOM");
74 
75  rule_a = nftnl_expr_iter_next(iter_a);
76  rule_b = nftnl_expr_iter_next(iter_b);
77  if (rule_a == NULL || rule_b == NULL)
78  print_err("OOM");
79 
80  cmp_nftnl_expr(rule_a, rule_b);
81 
82  if (nftnl_expr_iter_next(iter_a) != NULL ||
83  nftnl_expr_iter_next(iter_b) != NULL)
84  print_err("More 1 expr.");
85 
86  nftnl_expr_iter_destroy(iter_a);
87  nftnl_expr_iter_destroy(iter_b);
88  nftnl_rule_free(a);
89  nftnl_rule_free(b);
90 
91  if (!test_ok)
92  exit(EXIT_FAILURE);
93 
94  printf("%s: \033[32mOK\e[0m\n", argv[0]);
95  return EXIT_SUCCESS;
96 }