xdp.rs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. use std::{ffi::CStr, mem::MaybeUninit, net::UdpSocket, num::NonZeroU32, time::Duration};
  2. use aya::{
  3. maps::{Array, CpuMap, XskMap},
  4. programs::{Xdp, XdpFlags},
  5. Bpf,
  6. };
  7. use object::{Object, ObjectSection, ObjectSymbol, SymbolSection};
  8. use test_log::test;
  9. use xdpilone::{BufIdx, IfInfo, Socket, SocketConfig, Umem, UmemConfig};
  10. use crate::utils::NetNsGuard;
  11. #[test]
  12. fn af_xdp() {
  13. let _netns = NetNsGuard::new();
  14. let mut bpf = Bpf::load(crate::REDIRECT).unwrap();
  15. let mut socks: XskMap<_> = bpf.take_map("SOCKS").unwrap().try_into().unwrap();
  16. let xdp: &mut Xdp = bpf
  17. .program_mut("redirect_sock")
  18. .unwrap()
  19. .try_into()
  20. .unwrap();
  21. xdp.load().unwrap();
  22. xdp.attach("lo", XdpFlags::default()).unwrap();
  23. // So this needs to be page aligned. Pages are 4k on all mainstream architectures except for
  24. // Apple Silicon which uses 16k pages. So let's align on that for tests to run natively there.
  25. #[repr(align(16384))]
  26. struct PacketMap(MaybeUninit<[u8; 4096]>);
  27. // Safety: don't access alloc down the line.
  28. let mut alloc = Box::new(PacketMap(MaybeUninit::uninit()));
  29. let umem = {
  30. // Safety: this is a shared buffer between the kernel and us, uninitialized memory is valid.
  31. let mem = unsafe { alloc.0.assume_init_mut() }.as_mut().into();
  32. // Safety: we cannot access `mem` further down the line because it falls out of scope.
  33. unsafe { Umem::new(UmemConfig::default(), mem).unwrap() }
  34. };
  35. let mut iface = IfInfo::invalid();
  36. iface
  37. .from_name(CStr::from_bytes_with_nul(b"lo\0").unwrap())
  38. .unwrap();
  39. let sock = Socket::with_shared(&iface, &umem).unwrap();
  40. let mut fq_cq = umem.fq_cq(&sock).unwrap(); // Fill Queue / Completion Queue
  41. let cfg = SocketConfig {
  42. rx_size: NonZeroU32::new(32),
  43. ..Default::default()
  44. };
  45. let rxtx = umem.rx_tx(&sock, &cfg).unwrap(); // RX + TX Queues
  46. let mut rx = rxtx.map_rx().unwrap();
  47. umem.bind(&rxtx).unwrap();
  48. socks.set(0, rx.as_raw_fd(), 0).unwrap();
  49. let frame = umem.frame(BufIdx(0)).unwrap();
  50. // Produce a frame to be filled by the kernel
  51. let mut writer = fq_cq.fill(1);
  52. writer.insert_once(frame.offset);
  53. writer.commit();
  54. let sock = UdpSocket::bind("127.0.0.1:0").unwrap();
  55. let port = sock.local_addr().unwrap().port();
  56. sock.send_to(b"hello AF_XDP", "127.0.0.1:1777").unwrap();
  57. assert_eq!(rx.available(), 1);
  58. let desc = rx.receive(1).read().unwrap();
  59. let buf = unsafe {
  60. &frame.addr.as_ref()[desc.addr as usize..(desc.addr as usize + desc.len as usize)]
  61. };
  62. let (eth, buf) = buf.split_at(14);
  63. assert_eq!(eth[12..14], [0x08, 0x00]); // IP
  64. let (ip, buf) = buf.split_at(20);
  65. assert_eq!(ip[9], 17); // UDP
  66. let (udp, payload) = buf.split_at(8);
  67. assert_eq!(&udp[0..2], port.to_be_bytes().as_slice()); // Source
  68. assert_eq!(&udp[2..4], 1777u16.to_be_bytes().as_slice()); // Dest
  69. assert_eq!(payload, b"hello AF_XDP");
  70. }
  71. #[test]
  72. fn prog_sections() {
  73. let obj_file = object::File::parse(crate::XDP_SEC).unwrap();
  74. ensure_symbol(&obj_file, "xdp", "xdp_plain");
  75. ensure_symbol(&obj_file, "xdp.frags", "xdp_frags");
  76. ensure_symbol(&obj_file, "xdp/cpumap", "xdp_cpumap");
  77. ensure_symbol(&obj_file, "xdp/devmap", "xdp_devmap");
  78. ensure_symbol(&obj_file, "xdp.frags/cpumap", "xdp_frags_cpumap");
  79. ensure_symbol(&obj_file, "xdp.frags/devmap", "xdp_frags_devmap");
  80. }
  81. #[track_caller]
  82. fn ensure_symbol(obj_file: &object::File, sec_name: &str, sym_name: &str) {
  83. let sec = obj_file.section_by_name(sec_name).unwrap_or_else(|| {
  84. let secs = obj_file
  85. .sections()
  86. .flat_map(|sec| sec.name().ok().map(|name| name.to_owned()))
  87. .collect::<Vec<_>>();
  88. panic!("section {sec_name} not found. available sections: {secs:?}");
  89. });
  90. let sec = SymbolSection::Section(sec.index());
  91. let syms = obj_file
  92. .symbols()
  93. .filter(|sym| sym.section() == sec)
  94. .filter_map(|sym| sym.name().ok())
  95. .collect::<Vec<_>>();
  96. assert!(
  97. syms.contains(&sym_name),
  98. "symbol not found. available symbols in section: {syms:?}"
  99. );
  100. }
  101. #[test]
  102. fn map_load() {
  103. let bpf = Bpf::load(crate::XDP_SEC).unwrap();
  104. bpf.program("xdp_plain").unwrap();
  105. bpf.program("xdp_frags").unwrap();
  106. bpf.program("xdp_cpumap").unwrap();
  107. bpf.program("xdp_devmap").unwrap();
  108. bpf.program("xdp_frags_cpumap").unwrap();
  109. bpf.program("xdp_frags_devmap").unwrap();
  110. }
  111. #[test]
  112. fn cpumap_chain() {
  113. let _netns = NetNsGuard::new();
  114. let mut bpf = Bpf::load(crate::REDIRECT).unwrap();
  115. // Load our cpumap and our canary map
  116. let mut cpus: CpuMap<_> = bpf.take_map("CPUS").unwrap().try_into().unwrap();
  117. let hits: Array<_, u32> = bpf.take_map("HITS").unwrap().try_into().unwrap();
  118. let xdp_chain_fd = {
  119. // Load the chained program to run on the target CPU
  120. let xdp: &mut Xdp = bpf
  121. .program_mut("redirect_cpu_chain")
  122. .unwrap()
  123. .try_into()
  124. .unwrap();
  125. xdp.load().unwrap();
  126. xdp.fd().unwrap()
  127. };
  128. cpus.set(0, 2048, Some(xdp_chain_fd), 0).unwrap();
  129. // Load the main program
  130. let xdp: &mut Xdp = bpf.program_mut("redirect_cpu").unwrap().try_into().unwrap();
  131. xdp.load().unwrap();
  132. xdp.attach("lo", XdpFlags::default()).unwrap();
  133. const PAYLOAD: &str = "hello cpumap";
  134. let sock = UdpSocket::bind("127.0.0.1:0").unwrap();
  135. let addr = sock.local_addr().unwrap();
  136. sock.set_read_timeout(Some(Duration::from_secs(60)))
  137. .unwrap();
  138. sock.send_to(PAYLOAD.as_bytes(), addr).unwrap();
  139. // Read back the packet to ensure it went through the entire network stack, including our two
  140. // probes.
  141. let mut buf = [0u8; PAYLOAD.len() + 1];
  142. let n = sock.recv(&mut buf).unwrap();
  143. assert_eq!(&buf[..n], PAYLOAD.as_bytes());
  144. assert_eq!(hits.get(&0, 0).unwrap(), 1);
  145. assert_eq!(hits.get(&1, 0).unwrap(), 1);
  146. }