redirect.rs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #![no_std]
  2. #![no_main]
  3. use aya_bpf::{
  4. bindings::xdp_action,
  5. macros::{map, xdp},
  6. maps::{Array, CpuMap, DevMap, DevMapHash, XskMap},
  7. programs::XdpContext,
  8. };
  9. #[map]
  10. static SOCKS: XskMap = XskMap::with_max_entries(1, 0);
  11. #[map]
  12. static DEVS: DevMap = DevMap::with_max_entries(1, 0);
  13. #[map]
  14. static DEVS_HASH: DevMapHash = DevMapHash::with_max_entries(1, 0);
  15. #[map]
  16. static CPUS: CpuMap = CpuMap::with_max_entries(1, 0);
  17. /// Hits of a probe, used to test program chaining through CpuMap/DevMap.
  18. /// The first slot counts how many times the "raw" xdp program got executed, while the second slot
  19. /// counts how many times the map programs got executed.
  20. /// This allows the test harness to assert that a specific step got executed.
  21. #[map]
  22. static mut HITS: Array<u32> = Array::with_max_entries(2, 0);
  23. #[xdp]
  24. pub fn redirect_sock(_ctx: XdpContext) -> u32 {
  25. SOCKS.redirect(0, 0).unwrap_or(xdp_action::XDP_ABORTED)
  26. }
  27. #[xdp]
  28. pub fn redirect_dev(_ctx: XdpContext) -> u32 {
  29. inc_hit(0);
  30. DEVS.redirect(0, 0).unwrap_or(xdp_action::XDP_ABORTED)
  31. }
  32. #[xdp]
  33. pub fn redirect_dev_hash(_ctx: XdpContext) -> u32 {
  34. inc_hit(0);
  35. DEVS_HASH.redirect(10, 0).unwrap_or(xdp_action::XDP_ABORTED)
  36. }
  37. #[xdp]
  38. pub fn redirect_cpu(_ctx: XdpContext) -> u32 {
  39. inc_hit(0);
  40. CPUS.redirect(0, 0).unwrap_or(xdp_action::XDP_ABORTED)
  41. }
  42. #[xdp(map = "cpumap")]
  43. pub fn redirect_cpu_chain(_ctx: XdpContext) -> u32 {
  44. inc_hit(1);
  45. xdp_action::XDP_PASS
  46. }
  47. #[xdp(map = "devmap")]
  48. pub fn redirect_dev_chain(_ctx: XdpContext) -> u32 {
  49. inc_hit(1);
  50. xdp_action::XDP_PASS
  51. }
  52. #[inline(always)]
  53. fn inc_hit(index: u32) {
  54. if let Some(hit) = unsafe { HITS.get_ptr_mut(index) } {
  55. unsafe { *hit += 1 };
  56. }
  57. }
  58. #[cfg(not(test))]
  59. #[panic_handler]
  60. fn panic(_info: &core::panic::PanicInfo) -> ! {
  61. loop {}
  62. }