bpftrace - tcpstates.bt
此工具参考bcc-tcpstates 编写, 用于实现跟踪系统 TCP 连接状态(TCP状态机)。 通过在内核态动态函数 kprobe:tcp_set_state 插桩监控 sock 状态变化实现:
#!/usr/bin/env bpftrace
#include <net/tcp_states.h>
#include <net/sock.h>
#include <linux/socket.h>
#include <linux/tcp.h>
BEGIN
{
printf("%-20s %-7s %-20s %-7s ",
"LADDR", "LPORT", "RADDR", "RPORT");
printf("%-11s -> %-11s\n", "OLD", "NEW");
@tcpstate[0] = "UNKNOWN";
@tcpstate[1] = "ESTABLISHED";
@tcpstate[2] = "SYN_SENT";
@tcpstate[3] = "SYN_RECV";
@tcpstate[4] = "FIN_WAIT1";
@tcpstate[5] = "FIN_WAIT2";
@tcpstate[6] = "TIME_WAIT";
@tcpstate[7] = "CLOSE";
@tcpstate[8] = "CLOSE_WAIT";
@tcpstate[9] = "LAST_ACK";
@tcpstate[10] = "LISTEN";
@tcpstate[11] = "CLOSING";
@tcpstate[12] = "NEW_SYN_RECV";
}
kprobe:tcp_set_state
{
$sk = (struct sock *)arg0;
$newstate = arg1;
$oldstate = $sk->__sk_common.skc_state;
$lport = $sk->__sk_common.skc_num;
$dport = $sk->__sk_common.skc_dport;
$dport = ($dport >> 8) | (($dport << 8) & 0xff00);
$family = $sk->__sk_common.skc_family;
$saddr = ntop(0);
$daddr = ntop(0);
if ($family == AF_INET) {
$saddr = ntop(AF_INET, $sk->__sk_common.skc_rcv_saddr);
$daddr = ntop(AF_INET, $sk->__sk_common.skc_daddr);
} else {
// AF_INET6
$saddr = ntop(AF_INET6,
$sk->__sk_common.skc_v6_rcv_saddr.in6_u.u6_addr8);
$daddr = ntop(AF_INET6,
$sk->__sk_common.skc_v6_daddr.in6_u.u6_addr8);
}
if ($newstate > 12) {
printf("%-20s %-7d %-20s %-7d %-11d -> %-11d\n", $saddr, $lport, $daddr, $dport, $oldstate, $newstate);
} else {
printf("%-20s %-7d %-20s %-7d %-11s -> %-11s\n", $saddr, $lport, $daddr, $dport, @tcpstate[$oldstate], @tcpstate[$newstate]);
}
}
END
{
clear(@tcpstate)
}
运行结果:
# ./tcpstates.bt
Attaching 3 probes...
LADDR LPORT RADDR RPORT OLD -> NEW
192.168.22.42 0 192.168.22.44 3310 CLOSE -> SYN_SENT
192.168.22.42 37626 192.168.22.44 3310 SYN_SENT -> ESTABLISHED
192.168.22.42 37626 192.168.22.44 3310 ESTABLISHED -> FIN_WAIT1
192.168.22.42 37626 192.168.22.44 3310 FIN_WAIT1 -> FIN_WAIT2
192.168.22.42 37626 192.168.22.44 3310 FIN_WAIT2 -> CLOSE
192.168.22.42 0 192.168.22.44 3310 CLOSE -> SYN_SENT
192.168.22.42 37628 192.168.22.44 3310 SYN_SENT -> ESTABLISHED
192.168.22.42 37628 192.168.22.44 3310 ESTABLISHED -> CLOSE
192.168.22.42 0 192.168.22.44 3310 CLOSE -> SYN_SENT
192.168.22.42 37630 192.168.22.44 3310 SYN_SENT -> ESTABLISHED
192.168.22.42 37630 192.168.22.44 3310 ESTABLISHED -> CLOSE_WAIT
192.168.22.42 37630 192.168.22.44 3310 CLOSE_WAIT -> LAST_ACK
192.168.22.42 37630 192.168.22.44 3310 LAST_ACK -> CLOSE
192.168.22.42 0 192.168.22.44 3310 CLOSE -> SYN_SENT
192.168.22.42 37634 192.168.22.44 3310 SYN_SENT -> CLOSE
参考
BPF Compiler Collection (BCC) bpftrace bpftrace Cheat Sheet
|