libnftnl  1.2.9
nft-object-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 #include <netinet/in.h>
10 
11 #include <linux/netfilter/nf_tables.h>
12 #include <libnftnl/object.h>
13 
14 static int test_ok = 1;
15 
16 static void print_err(const char *msg)
17 {
18  test_ok = 0;
19  printf("\033[31mERROR:\e[0m %s\n", msg);
20 }
21 
22 static void cmp_nftnl_obj(struct nftnl_obj *a, struct nftnl_obj *b)
23 {
24  if (strcmp(nftnl_obj_get_str(a, NFTNL_OBJ_TABLE),
25  nftnl_obj_get_str(b, NFTNL_OBJ_TABLE)) != 0)
26  print_err("table name mismatches");
27  if (strcmp(nftnl_obj_get_str(a, NFTNL_OBJ_NAME),
28  nftnl_obj_get_str(b, NFTNL_OBJ_NAME)) != 0)
29  print_err("name mismatches");
30  if (nftnl_obj_get_u32(a, NFTNL_OBJ_FAMILY) !=
31  nftnl_obj_get_u32(b, NFTNL_OBJ_FAMILY))
32  print_err("family mismatches");
33  if (nftnl_obj_get_u32(a, NFTNL_OBJ_TYPE) !=
34  nftnl_obj_get_u32(b, NFTNL_OBJ_TYPE))
35  print_err("type mismatches");
36 }
37 
38 int main(int argc, char *argv[])
39 {
40  char buf[4096];
41  struct nlmsghdr *nlh;
42  struct nftnl_obj *a;
43  struct nftnl_obj *b;
44 
45  a = nftnl_obj_alloc();
46  b = nftnl_obj_alloc();
47  if (a == NULL || b == NULL)
48  print_err("OOM");
49 
50  nftnl_obj_set_str(a, NFTNL_OBJ_TABLE, "test");
51  nftnl_obj_set_str(a, NFTNL_OBJ_NAME, "test");
52  nftnl_obj_set_u32(a, NFTNL_OBJ_FAMILY, AF_INET);
53  nftnl_obj_set_u32(a, NFTNL_OBJ_USE, 1);
54  nftnl_obj_set_u64(a, NFTNL_OBJ_CTR_BYTES, 0x12345678abcd);
55  nftnl_obj_set_u64(a, NFTNL_OBJ_CTR_PKTS, 0xcd12345678ab);
56 
57  /* cmd extracted from include/linux/netfilter/nf_tables.h */
58  nlh = nftnl_nlmsg_build_hdr(buf, NFT_MSG_NEWOBJ, AF_INET, 0, 1234);
59  nftnl_obj_nlmsg_build_payload(nlh, a);
60 
61  if (nftnl_obj_nlmsg_parse(nlh, b) < 0)
62  print_err("parsing problems");
63 
64  cmp_nftnl_obj(a, b);
65 
66  nftnl_obj_free(a);
67  nftnl_obj_free(b);
68  if (!test_ok)
69  exit(EXIT_FAILURE);
70 
71  printf("%s: \033[32mOK\e[0m\n", argv[0]);
72  return EXIT_SUCCESS;
73 }