4
#include <bpf/bpf_helpers.h>
5
#include <bpf/bpf_core_read.h>
6
#include <bpf/bpf_tracing.h>
7
#include <bpf/bpf_endian.h>
10
#include <gadget/mntns_filter.h>
16
const volatile pid_t target_pid = 0;
17
const volatile int target_family = -1;
20
__uint(type, BPF_MAP_TYPE_HASH);
21
__uint(max_entries, 10240);
22
__type(key, struct ip_key_t);
23
__type(value, struct traffic_t);
26
static int probe_ip(bool receiving, struct sock *sk, size_t size)
28
struct ip_key_t ip_key = {};
29
struct traffic_t *trafficp;
34
pid = bpf_get_current_pid_tgid() >> 32;
35
if (target_pid != 0 && target_pid != pid)
38
family = BPF_CORE_READ(sk, __sk_common.skc_family);
39
if (target_family != -1 && target_family != family)
43
if (family != AF_INET && family != AF_INET6)
46
mntns_id = gadget_get_mntns_id();
48
if (gadget_should_discard_mntns_id(mntns_id))
52
bpf_get_current_comm(&ip_key.name, sizeof(ip_key.name));
53
ip_key.lport = BPF_CORE_READ(sk, __sk_common.skc_num);
54
ip_key.dport = bpf_ntohs(BPF_CORE_READ(sk, __sk_common.skc_dport));
55
ip_key.family = family;
56
ip_key.mntnsid = mntns_id;
58
if (family == AF_INET) {
59
bpf_probe_read_kernel(&ip_key.saddr,
60
sizeof(sk->__sk_common.skc_rcv_saddr),
61
&sk->__sk_common.skc_rcv_saddr);
62
bpf_probe_read_kernel(&ip_key.daddr,
63
sizeof(sk->__sk_common.skc_daddr),
64
&sk->__sk_common.skc_daddr);
70
bpf_probe_read_kernel(
72
sizeof(sk->__sk_common.skc_v6_rcv_saddr.in6_u.u6_addr32),
73
&sk->__sk_common.skc_v6_rcv_saddr.in6_u.u6_addr32);
74
bpf_probe_read_kernel(
76
sizeof(sk->__sk_common.skc_v6_daddr.in6_u.u6_addr32),
77
&sk->__sk_common.skc_v6_daddr.in6_u.u6_addr32);
80
trafficp = bpf_map_lookup_elem(&ip_map, &ip_key);
82
struct traffic_t zero;
92
bpf_map_update_elem(&ip_map, &ip_key, &zero, BPF_NOEXIST);
95
trafficp->received += size;
97
trafficp->sent += size;
99
bpf_map_update_elem(&ip_map, &ip_key, trafficp, BPF_EXIST);
105
SEC("kprobe/tcp_sendmsg")
106
int BPF_KPROBE(ig_toptcp_sdmsg, struct sock *sk, struct msghdr *msg,
109
return probe_ip(false, sk, size);
118
SEC("kprobe/tcp_cleanup_rbuf")
119
int BPF_KPROBE(ig_toptcp_clean, struct sock *sk, int copied)
124
return probe_ip(true, sk, copied);
127
char LICENSE[] SEC("license") = "GPL";