0001
0002
0003
0004 #include <vmlinux.h>
0005 #include <bpf/bpf_tracing.h>
0006 #include <bpf/bpf_core_read.h>
0007 #include <bpf/bpf_helpers.h>
0008
0009 struct sk_stg {
0010 __u32 pid;
0011 __u32 last_notclose_state;
0012 char comm[16];
0013 };
0014
0015 struct {
0016 __uint(type, BPF_MAP_TYPE_SK_STORAGE);
0017 __uint(map_flags, BPF_F_NO_PREALLOC);
0018 __type(key, int);
0019 __type(value, struct sk_stg);
0020 } sk_stg_map SEC(".maps");
0021
0022
0023 struct {
0024 __uint(type, BPF_MAP_TYPE_SK_STORAGE);
0025 __uint(map_flags, BPF_F_NO_PREALLOC);
0026 __type(key, int);
0027 __type(value, int);
0028 } del_sk_stg_map SEC(".maps");
0029
0030 char task_comm[16] = "";
0031
0032 SEC("tp_btf/inet_sock_set_state")
0033 int BPF_PROG(trace_inet_sock_set_state, struct sock *sk, int oldstate,
0034 int newstate)
0035 {
0036 struct sk_stg *stg;
0037
0038 if (newstate == BPF_TCP_CLOSE)
0039 return 0;
0040
0041 stg = bpf_sk_storage_get(&sk_stg_map, sk, 0,
0042 BPF_SK_STORAGE_GET_F_CREATE);
0043 if (!stg)
0044 return 0;
0045
0046 stg->last_notclose_state = newstate;
0047
0048 bpf_sk_storage_delete(&del_sk_stg_map, sk);
0049
0050 return 0;
0051 }
0052
0053 static void set_task_info(struct sock *sk)
0054 {
0055 struct task_struct *task;
0056 struct sk_stg *stg;
0057
0058 stg = bpf_sk_storage_get(&sk_stg_map, sk, 0,
0059 BPF_SK_STORAGE_GET_F_CREATE);
0060 if (!stg)
0061 return;
0062
0063 stg->pid = bpf_get_current_pid_tgid();
0064
0065 task = (struct task_struct *)bpf_get_current_task();
0066 bpf_core_read_str(&stg->comm, sizeof(stg->comm), &task->comm);
0067 bpf_core_read_str(&task_comm, sizeof(task_comm), &task->comm);
0068 }
0069
0070 SEC("fentry/inet_csk_listen_start")
0071 int BPF_PROG(trace_inet_csk_listen_start, struct sock *sk)
0072 {
0073 set_task_info(sk);
0074
0075 return 0;
0076 }
0077
0078 SEC("fentry/tcp_connect")
0079 int BPF_PROG(trace_tcp_connect, struct sock *sk)
0080 {
0081 set_task_info(sk);
0082
0083 return 0;
0084 }
0085
0086 SEC("fexit/inet_csk_accept")
0087 int BPF_PROG(inet_csk_accept, struct sock *sk, int flags, int *err, bool kern,
0088 struct sock *accepted_sk)
0089 {
0090 set_task_info(accepted_sk);
0091
0092 return 0;
0093 }
0094
0095 char _license[] SEC("license") = "GPL";