Debian Codegraph @

examples/xdp_live_frame/main.go

raw symbols SCIP
1 //go:build linux
2
3 // This program demonstrates using BPF_F_TEST_XDP_LIVE_FRAMES to run an XDP
4 // program in "live frame mode". In this mode, the kernel sends packets directly
5 // to the network interface using the XDP program's return value (e.g., XDP_TX).
6 // This is useful for high-performance packet generation and testing.
7 //
8 // Usage: go run . <ifname> <repeat> <batch_size> <src_ip> <dst_ip> <dst_mac>
9 //
10 // This example requires Linux kernel version 5.18 or newer.
11 package main
12
13 import (
14 "encoding/binary"
15 "log"
16 "net"
17 "os"
18 "strconv"
19
20 "golang.org/x/sys/unix"
21
22 "github.com/cilium/ebpf"
23 "github.com/cilium/ebpf/internal/sys"
24 "github.com/cilium/ebpf/link"
25 )
26
27 //go:generate go tool bpf2go -tags linux bpf xdp.c -- -I../headers
28
29 func main() {
30 if len(os.Args) < 7 {
31 log.Fatalf("Usage: %s <ifname> <repeat> <batch_size> <src_ip> <dst_ip> <dst_mac>", os.Args[0])
32 }
33
34 // Look up the network interface by name.
35 ifaceName := os.Args[1]
36 iface, err := net.InterfaceByName(ifaceName)
37 if err != nil {
38 log.Fatalf("lookup network iface %q: %s", ifaceName, err)
39 }
40
41 repeat, err := strconv.ParseUint(os.Args[2], 10, 32)
42 if err != nil {
43 log.Fatalf("parsing repeat count %q: %s", os.Args[2], err)
44 }
45
46 batchSize, err := strconv.ParseUint(os.Args[3], 10, 32)
47 if err != nil {
48 log.Fatalf("parsing batch size %q: %s", os.Args[3], err)
49 }
50
51 srcIP := net.ParseIP(os.Args[4]).To4()
52 if srcIP == nil {
53 log.Fatalf("invalid source IP address: %s", os.Args[4])
54 }
55
56 dstIP := net.ParseIP(os.Args[5]).To4()
57 if dstIP == nil {
58 log.Fatalf("invalid destination IP address: %s", os.Args[5])
59 }
60
61 dstMAC, err := net.ParseMAC(os.Args[6])
62 if err != nil {
63 log.Fatalf("invalid destination MAC address %q: %s", os.Args[6], err)
64 }
65
66 // Load pre-compiled programs into the kernel.
67 objs := bpfObjects{}
68 if err := loadBpfObjects(&objs, nil); err != nil {
69 log.Fatalf("loading objects: %s", err)
70 }
71 defer objs.Close()
72
73 // Attach an XDP program to the interface first.
74 // This is required for XDP_TX to work in live frame mode.
75 l, err := link.AttachXDP(link.XDPOptions{
76 Program: objs.XdpProgPass,
77 Interface: iface.Index,
78 })
79 if err != nil {
80 log.Fatalf("could not attach XDP program: %s", err)
81 }
82 defer l.Close()
83
84 log.Printf("Attached XDP program to iface %q (index %d)", iface.Name, iface.Index)
85 log.Printf("Running XDP program in live frame mode with Repeat: %d, BatchSize: %d", repeat, batchSize)
86 log.Printf("Src MAC: %s, Dst MAC: %s", iface.HardwareAddr, dstMAC)
87 log.Printf("Src IP: %s, Dst IP: %s", srcIP, dstIP)
88
89 // Build a UDP packet with Ethernet header
90 pkt := buildUDPPacket(iface.HardwareAddr, dstMAC, srcIP, dstIP, 12345, 9999, []byte("Hello, XDP!"))
91
92 xdpmd := &sys.XdpMd{
93 DataEnd: uint32(len(pkt)),
94 IngressIfindex: uint32(iface.Index),
95 }
96 ret, err := objs.XdpProgTx.Run(&ebpf.RunOptions{
97 Data: pkt,
98 Repeat: uint32(repeat),
99 Flags: unix.BPF_F_TEST_XDP_LIVE_FRAMES,
100 Context: xdpmd,
101 BatchSize: uint32(batchSize),
102 })
103 if err != nil {
104 log.Fatalf("running XDP program with BPF_F_TEST_XDP_LIVE_FRAMES: %s", err)
105 }
106
107 log.Printf("XDP program completed with return value: %d", ret)
108 }
109
110 // buildUDPPacket creates an Ethernet + IPv4 + UDP packet.
111 func buildUDPPacket(srcMAC, dstMAC net.HardwareAddr, srcIP, dstIP net.IP, srcPort, dstPort uint16, payload []byte) []byte {
112 // Ethernet header (14 bytes)
113 eth := make([]byte, 14)
114 copy(eth[0:6], dstMAC)
115 copy(eth[6:12], srcMAC)
116 binary.BigEndian.PutUint16(eth[12:14], 0x0800) // IPv4
117
118 // IPv4 header (20 bytes, no options)
119 ipHeaderLen := 20
120 udpLen := 8 + len(payload)
121 totalLen := ipHeaderLen + udpLen
122
123 ip := make([]byte, ipHeaderLen)
124 ip[0] = 0x45 // Version (4) + IHL (5)
125 ip[1] = 0x00 // DSCP + ECN
126 binary.BigEndian.PutUint16(ip[2:4], uint16(totalLen)) // Total length
127 binary.BigEndian.PutUint16(ip[4:6], 0x0000) // Identification
128 binary.BigEndian.PutUint16(ip[6:8], 0x4000) // Flags (Don't Fragment) + Fragment Offset
129 ip[8] = 64 // TTL
130 ip[9] = 17 // Protocol (UDP)
131 // ip[10:12] = checksum (calculated below)
132 copy(ip[12:16], srcIP)
133 copy(ip[16:20], dstIP)
134
135 // Calculate IP header checksum
136 binary.BigEndian.PutUint16(ip[10:12], ipChecksum(ip))
137
138 // UDP header (8 bytes)
139 udp := make([]byte, 8)
140 binary.BigEndian.PutUint16(udp[0:2], srcPort)
141 binary.BigEndian.PutUint16(udp[2:4], dstPort)
142 binary.BigEndian.PutUint16(udp[4:6], uint16(udpLen))
143 // udp[6:8] = checksum (optional for IPv4, set to 0)
144
145 // Combine all parts
146 pkt := make([]byte, 0, 14+totalLen)
147 pkt = append(pkt, eth...)
148 pkt = append(pkt, ip...)
149 pkt = append(pkt, udp...)
150 pkt = append(pkt, payload...)
151
152 return pkt
153 }
154
155 // ipChecksum calculates the IP header checksum.
156 func ipChecksum(header []byte) uint16 {
157 var sum uint32
158 for i := 0; i < len(header); i += 2 {
159 sum += uint32(binary.BigEndian.Uint16(header[i : i+2]))
160 }
161 for sum > 0xffff {
162 sum = (sum & 0xffff) + (sum >> 16)
163 }
164 return ^uint16(sum)
165 }