srdusr
aboutsummaryrefslogtreecommitdiffstats
path: root/include/wireframe/filter.hpp
blob: 49fa4ab99d9ac435e1766284ea34c1155d952856 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#pragma once

#include <pcap.h>

#include <optional>
#include <string>

// Thin wrapper around libpcap's BPF filter compiler. tcpdump-style
// filter syntax ("tcp port 80", "host 10.0.0.1 and not icmp") already
// has a correct, well-tested parser and compiler in libpcap itself --
// hand-rolling a second one would be a large, separate project with no
// bearing on this one's actual goal (the C++ memory model), so this
// wraps the existing implementation instead of reinventing it.
namespace wireframe {

// Compiles `expression` against `handle`'s linktype/snaplen into
// `out`. `handle` can be a real, already-open capture handle, or a
// throwaway one from pcap_open_dead() - pcap_compile() only needs the
// handle to know the linktype and to report errors via pcap_geterr(),
// it doesn't require an active capture. That's what makes this
// testable without root or a real interface.
//
// Returns nullopt on success (with `out` filled in and owned by the
// caller - pcap_freecode(out) once it's no longer needed, including
// after a successful pcap_setfilter()). Returns pcap's error message
// on failure, and leaves `out` unmodified.
inline std::optional<std::string> compile_filter(pcap_t* handle, const std::string& expression,
                                                   bpf_program* out) {
    if (pcap_compile(handle, out, expression.c_str(), /*optimize=*/1, PCAP_NETMASK_UNKNOWN) ==
        -1) {
        return std::string(pcap_geterr(handle));
    }
    return std::nullopt;
}

}  // namespace wireframe