2 *------------------------------------------------------------------
3 * Copyright (c) 2023 Cisco and/or its affiliates.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *------------------------------------------------------------------
18 #include <vlib/vlib.h>
19 #include <bpf_trace_filter/bpf_trace_filter.h>
22 bpf_trace_filter_init (vlib_main_t *vm)
24 bpf_trace_filter_main_t *btm = &bpf_trace_filter_main;
25 btm->pcap = pcap_open_dead (DLT_EN10MB, 65535);
30 int vnet_is_packet_traced (vlib_buffer_t *b, u32 classify_table_index,
34 format_bpf_trace_filter (u8 *s, va_list *a)
36 bpf_trace_filter_main_t *btm = va_arg (*a, bpf_trace_filter_main_t *);
37 struct bpf_insn *insn;
40 return format (s, "bpf trace filter is not set");
42 insn = btm->prog.bf_insns;
43 for (int i = 0; i < btm->prog.bf_len; insn++, i++)
44 s = format (s, "%s\n", bpf_image (insn, i));
50 bpf_trace_filter_set_unset (const char *bpf_expr, u8 is_del, u8 optimize)
52 bpf_trace_filter_main_t *btm = &bpf_trace_filter_main;
58 pcap_freecode (&btm->prog);
64 pcap_freecode (&btm->prog);
66 if (pcap_compile (btm->pcap, &btm->prog, (char *) bpf_expr, optimize,
67 PCAP_NETMASK_UNKNOWN))
69 return clib_error_return (0, "Failed pcap_compile of %s", bpf_expr);
77 bpf_is_packet_traced (vlib_buffer_t *b, u32 classify_table_index, int func)
79 bpf_trace_filter_main_t *bfm = &bpf_trace_filter_main;
80 struct pcap_pkthdr phdr = { 0 };
84 if (classify_table_index != ~0 &&
85 (res1 = vnet_is_packet_traced (b, classify_table_index, 0)) != 1)
91 phdr.caplen = b->current_length;
92 phdr.len = b->current_length;
93 res = pcap_offline_filter (&bfm->prog, &phdr, vlib_buffer_get_current (b));
97 VLIB_REGISTER_TRACE_FILTER_FUNCTION (bpf_trace_filter_fn, static) = {
98 .name = "bpf_trace_filter",
99 .description = "bpf based trace filter",
101 .function = bpf_is_packet_traced
104 VLIB_INIT_FUNCTION (bpf_trace_filter_init);
105 bpf_trace_filter_main_t bpf_trace_filter_main;
107 * fd.io coding-style-patch-verification: ON
110 * eval: (c-set-style "gnu")