Debian Codegraph @

kernel_test.go

raw symbols SCIP
1 package cbpfc
2
3 import (
4 "bytes"
5 "net"
6 "testing"
7 "time"
8 "unsafe"
9
10 "golang.org/x/net/bpf"
11 "golang.org/x/sys/unix"
12 )
13
14 // kernelBackend is a backend that runs cBPF in the kernel
15 func kernelBackend(tb testing.TB, insns []bpf.Instruction, in []byte, opts backendOpts) result {
16 // There's no easy way to support fixed offsets, we'd have to rewrite all the LoadAbsolute and LoadIndirect
17 // instructions.
18 if opts.offset != 0 {
19 tb.Skip()
20 }
21
22 filter, err := bpf.Assemble(insns)
23 if err != nil {
24 tb.Fatal(err)
25 }
26
27 // Use a unix socket to test the filter
28 // This doesn't risk interfering with any other network traffic, doesn't require / add special
29 // headers (as would be the case if we used UDP for example) that the XDP tests don't deal with,
30 // and doesn't require any special permissions
31 read, err := net.ListenUnixgram("unixgram", &net.UnixAddr{Name: "", Net: "unixgram"})
32 if err != nil {
33 tb.Fatal(err)
34 }
35 defer read.Close()
36 readConn, err := read.SyscallConn()
37 if err != nil {
38 tb.Fatal(err)
39 }
40 err = readConn.Control(func(fd uintptr) {
41 err := unix.SetsockoptSockFprog(int(fd), unix.SOL_SOCKET, unix.SO_ATTACH_FILTER, &unix.SockFprog{
42 Len: uint16(len(filter)),
43 Filter: (*unix.SockFilter)(unsafe.Pointer(&filter[0])),
44 })
45 if err != nil {
46 tb.Fatal(err)
47 }
48 })
49 if err != nil {
50 tb.Fatal(err)
51 }
52
53 write, err := net.Dial("unixgram", read.LocalAddr().String())
54 if err != nil {
55 tb.Fatal(err)
56 }
57 defer write.Close()
58
59 if _, err := write.Write(in); err != nil {
60 tb.Fatal(err)
61 }
62
63 read.SetDeadline(time.Now().Add(50 * time.Millisecond))
64
65 // SocketFilters only allow matching packets through
66 // If the packet does not match, the only signal we have is the absence of a packet
67 var out [1500]byte
68 n, err := read.Read(out[:])
69 if err != nil {
70 if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
71 return noMatch
72 }
73
74 tb.Fatal(err)
75 }
76
77 // Sanity check we received the right packet
78 // Received packet is truncated to the SocketFilter's return value
79 if !bytes.Equal(in[:n], out[:n]) {
80 tb.Fatalf("Received unexpected packet:\nSent: %v\nGot: %v\n", in, out[:n])
81 }
82
83 return match
84 }