• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Test for the filter API
3  */
4 
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <arpa/inet.h>
9 #include <errno.h>
10 
11 #include <libnetfilter_conntrack/libnetfilter_conntrack.h>
12 
event_cb(enum nf_conntrack_msg_type type,struct nf_conntrack * ct,void * data)13 static int event_cb(enum nf_conntrack_msg_type type,
14 		    struct nf_conntrack *ct,
15 		    void *data)
16 {
17 	static int n = 0;
18 	char buf[1024];
19 
20 	nfct_snprintf(buf, sizeof(buf), ct, type, NFCT_O_PLAIN, NFCT_OF_TIME);
21 	printf("%s\n", buf);
22 
23 	if (++n == 10)
24 		return NFCT_CB_STOP;
25 
26 	return NFCT_CB_CONTINUE;
27 }
28 
main(void)29 int main(void)
30 {
31 	int i, ret;
32 	struct nfct_handle *h;
33 	struct nfct_filter *filter;
34 
35 	h = nfct_open(CONNTRACK, NF_NETLINK_CONNTRACK_NEW |
36 				 NF_NETLINK_CONNTRACK_UPDATE);
37 	if (!h) {
38 		perror("nfct_open");
39 		return 0;
40 	}
41 
42 	filter = nfct_filter_create();
43 	if (!filter) {
44 		perror("nfct_create_filter");
45 		return 0;
46 	}
47 
48 	if (nfct_filter_attach(nfct_fd(h), filter) == -1) {
49 		perror("nfct_filter_attach");
50 		return 0;
51 	}
52 
53 	/* protocol 255 is skipped since we support up to 255 protocols max */
54 	for (i=0; i<IPPROTO_MAX; i++)
55 		nfct_filter_add_attr_u32(filter,NFCT_FILTER_L4PROTO,i);
56 
57 	/* up to 127 IP addresses, above that adding is noop */
58 	for (i=0; i<128; i++) {
59 		/* BSF always wants data in host-byte order */
60 		struct nfct_filter_ipv4 fltr_ipv4 = {
61 			.addr = ntohl(inet_addr("127.0.0.1")) + i,
62 			.mask = 0xffffffff,
63 		};
64 		nfct_filter_add_attr(filter, NFCT_FILTER_SRC_IPV4, &fltr_ipv4);
65 	};
66 
67 	if (nfct_filter_attach(nfct_fd(h), filter) == -1) {
68 		perror("nfct_filter_attach");
69 		return 0;
70 	}
71 
72 	nfct_filter_destroy(filter);
73 
74 	nfct_callback_register(h, NFCT_T_ALL, event_cb, NULL);
75 
76 	ret = nfct_catch(h);
77 	printf("test ret=%d (%s)\n", ret, strerror(errno));
78 	return EXIT_SUCCESS;
79 }
80