xref: /aosp_15_r20/external/iptables/utils/nfbpf_compile.c (revision a71a954618bbadd4a345637e5edcf36eec826889)
1 /*
2  * BPF program compilation tool
3  *
4  * Generates decimal output, similar to `tcpdump -ddd ...`.
5  * Unlike tcpdump, will generate for any given link layer type.
6  *
7  * Written by Willem de Bruijn ([email protected])
8  * Copyright Google, Inc. 2013
9  * Licensed under the GNU General Public License version 2 (GPLv2)
10 */
11 
12 #include <pcap.h>
13 #include <stdio.h>
14 
main(int argc,char ** argv)15 int main(int argc, char **argv)
16 {
17 	struct bpf_program program;
18 	struct bpf_insn *ins;
19 	int i, dlt = DLT_RAW;
20 	pcap_t *pcap;
21 
22 	if (argc < 2 || argc > 3) {
23 		fprintf(stderr, "Usage:    %s [link] '<program>'\n\n"
24 				"          link is a pcap linklayer type:\n"
25 				"          one of EN10MB, RAW, SLIP, ...\n\n"
26 				"Examples: %s RAW 'tcp and greater 100'\n"
27 				"          %s EN10MB 'ip proto 47'\n'",
28 				argv[0], argv[0], argv[0]);
29 		return 1;
30 	}
31 
32 	if (argc == 3) {
33 		dlt = pcap_datalink_name_to_val(argv[1]);
34 		if (dlt == -1) {
35 			fprintf(stderr, "Unknown datalinktype: %s\n", argv[1]);
36 			return 1;
37 		}
38 	}
39 
40 	pcap = pcap_open_dead(dlt, 65535);
41 	if (!pcap) {
42 		fprintf(stderr, "Memory allocation failure\n");
43 		return 1;
44 	}
45 	if (pcap_compile(pcap, &program, argv[argc - 1], 1,
46 				PCAP_NETMASK_UNKNOWN)) {
47 		fprintf(stderr, "Compilation error\n");
48 		pcap_close(pcap);
49 		return 1;
50 	}
51 
52 	printf("%d,", program.bf_len);
53 	ins = program.bf_insns;
54 	for (i = 0; i < program.bf_len-1; ++ins, ++i)
55 		printf("%u %u %u %u,", ins->code, ins->jt, ins->jf, ins->k);
56 
57 	printf("%u %u %u %u\n", ins->code, ins->jt, ins->jf, ins->k);
58 
59 	pcap_freecode(&program);
60 	pcap_close(pcap);
61 	return 0;
62 }
63 
64