diff --git a/oryx-ebpf/src/main.rs b/oryx-ebpf/src/main.rs index 051681d..1490b86 100644 --- a/oryx-ebpf/src/main.rs +++ b/oryx-ebpf/src/main.rs @@ -3,9 +3,10 @@ use aya_ebpf::{ bindings::{TC_ACT_PIPE, TC_ACT_SHOT}, - macros::{classifier, map}, + macros::{cgroup_sock_addr, classifier, map}, maps::{Array, HashMap, RingBuf}, - programs::TcContext, + programs::{SockAddrContext, TcContext}, + EbpfContext, }; use core::mem; use network_types::{ @@ -24,6 +25,9 @@ use oryx_common::{ #[map] static DATA: RingBuf = RingBuf::with_byte_size(4096 * RawPacket::LEN as u32, 0); +#[map] +static PID_DATA: RingBuf = RingBuf::with_byte_size(1024, 0); + #[map] static NETWORK_FILTERS: Array = Array::with_max_entries(8, 0); @@ -306,6 +310,24 @@ fn process(ctx: TcContext) -> Result { Ok(TC_ACT_PIPE) } +#[cgroup_sock_addr(connect4)] +pub fn socket_connect(ctx: SockAddrContext) -> i32 { + match sock_connect(ctx) { + Ok(ret) => ret, + Err(ret) => ret, + } +} + +fn sock_connect(ctx: SockAddrContext) -> Result { + let pid = ctx.pid(); + + if let Some(mut buf) = PID_DATA.reserve::(0) { + unsafe { (*buf.as_mut_ptr()) = pid }; + buf.submit(0); + } + Ok(1) +} + #[panic_handler] fn panic(_info: &core::panic::PanicInfo) -> ! { unsafe { core::hint::unreachable_unchecked() } diff --git a/oryx-tui/src/app.rs b/oryx-tui/src/app.rs index 6fbaea5..ecf50b4 100644 --- a/oryx-tui/src/app.rs +++ b/oryx-tui/src/app.rs @@ -5,7 +5,7 @@ use ratatui::{ }; use std::{ error, - sync::{Arc, Mutex}, + sync::{atomic::AtomicBool, Arc, Mutex}, thread, time::Duration, }; @@ -14,7 +14,7 @@ use crate::{ filter::Filter, help::Help, packet::{direction::TrafficDirection, NetworkPacket}, - pid, + pid::{self, ConnectionMap}, }; use crate::{filter::IoChannels, notification::Notification}; @@ -50,6 +50,8 @@ pub struct App { pub data_channel_sender: kanal::Sender<([u8; RawPacket::LEN], TrafficDirection)>, pub is_editing: bool, pub active_popup: Option, + pub pid_terminate: Arc, + pub pid_map: Arc>, } impl Default for App { @@ -61,19 +63,24 @@ impl Default for App { impl App { pub fn new() -> Self { let packets = Arc::new(Mutex::new(Vec::with_capacity(RawPacket::LEN * 1024 * 1024))); + let pid_map = Arc::new(Mutex::new(ConnectionMap::new())); let (sender, receiver) = kanal::unbounded(); let firewall_channels = IoChannels::new(); thread::spawn({ let packets = packets.clone(); + let pid_map = pid_map.clone(); move || loop { - let pid_map = pid::ConnectionMap::new(); if let Ok((raw_packet, direction)) = receiver.recv() { let network_packet = NetworkPacket::from(raw_packet); let pid = { if direction == TrafficDirection::Egress { + let pid_map = { + let map = pid_map.lock().unwrap(); + map.clone() + }; pid::get_pid(network_packet, &pid_map) } else { None @@ -107,6 +114,8 @@ impl App { data_channel_sender: sender, is_editing: false, active_popup: None, + pid_terminate: Arc::new(AtomicBool::new(false)), + pid_map, } } @@ -147,6 +156,8 @@ impl App { pub fn quit(&mut self) { self.filter.terminate(); + self.pid_terminate + .store(true, std::sync::atomic::Ordering::Relaxed); thread::sleep(Duration::from_millis(110)); self.running = false; } diff --git a/oryx-tui/src/ebpf.rs b/oryx-tui/src/ebpf.rs index 2d3164d..1ccb4ad 100644 --- a/oryx-tui/src/ebpf.rs +++ b/oryx-tui/src/ebpf.rs @@ -1,6 +1,7 @@ pub mod egress; mod firewall; pub mod ingress; +pub mod pid; use std::{io, os::fd::AsRawFd}; @@ -16,8 +17,8 @@ pub struct RingBuffer<'a> { } impl<'a> RingBuffer<'a> { - fn new(ebpf: &'a mut Ebpf) -> Self { - let buffer = RingBuf::try_from(ebpf.map_mut("DATA").unwrap()).unwrap(); + fn new(ebpf: &'a mut Ebpf, name: &'a str) -> Self { + let buffer = RingBuf::try_from(ebpf.map_mut(name).unwrap()).unwrap(); Self { buffer } } diff --git a/oryx-tui/src/ebpf/egress.rs b/oryx-tui/src/ebpf/egress.rs index a0b19cf..62fec09 100644 --- a/oryx-tui/src/ebpf/egress.rs +++ b/oryx-tui/src/ebpf/egress.rs @@ -193,7 +193,7 @@ pub fn load_egress( }); // packets reading - let mut ring_buf = RingBuffer::new(&mut bpf); + let mut ring_buf = RingBuffer::new(&mut bpf, "DATA"); poll.registry() .register( diff --git a/oryx-tui/src/ebpf/ingress.rs b/oryx-tui/src/ebpf/ingress.rs index 2db027a..9be9941 100644 --- a/oryx-tui/src/ebpf/ingress.rs +++ b/oryx-tui/src/ebpf/ingress.rs @@ -197,7 +197,7 @@ pub fn load_ingress( }); // packets reader - let mut ring_buf = RingBuffer::new(&mut bpf); + let mut ring_buf = RingBuffer::new(&mut bpf, "DATA"); poll.registry() .register( diff --git a/oryx-tui/src/ebpf/pid.rs b/oryx-tui/src/ebpf/pid.rs new file mode 100644 index 0000000..16af030 --- /dev/null +++ b/oryx-tui/src/ebpf/pid.rs @@ -0,0 +1,132 @@ +use std::{ + fs::{self, File}, + os::fd::AsRawFd, + sync::{atomic::AtomicBool, Arc, Mutex}, + thread, + time::Duration, +}; + +use aya::{ + include_bytes_aligned, + programs::{CgroupAttachMode, CgroupSockAddr}, + EbpfLoader, +}; +use log::error; + +use crate::{ + event::Event, + notification::{Notification, NotificationLevel}, + pid::ConnectionMap, +}; +use mio::{unix::SourceFd, Events, Interest, Poll, Token}; + +use super::RingBuffer; + +pub fn load_pid( + pid_map: Arc>, + notification_sender: kanal::Sender, + terminate: Arc, +) { + thread::spawn({ + move || { + let rlim = libc::rlimit { + rlim_cur: libc::RLIM_INFINITY, + rlim_max: libc::RLIM_INFINITY, + }; + + unsafe { libc::setrlimit(libc::RLIMIT_MEMLOCK, &rlim) }; + + #[cfg(debug_assertions)] + let mut bpf = match EbpfLoader::new().load(include_bytes_aligned!( + "../../../target/bpfel-unknown-none/debug/oryx" + )) { + Ok(v) => v, + Err(e) => { + error!("Failed to load the pid eBPF bytecode. {}", e); + Notification::send( + "Failed to load the pid eBPF bytecode", + NotificationLevel::Error, + notification_sender, + ) + .unwrap(); + return; + } + }; + + #[cfg(not(debug_assertions))] + let mut bpf = match EbpfLoader::new().load(include_bytes_aligned!( + "../../../target/bpfel-unknown-none/debug/oryx" + )) { + Ok(v) => v, + Err(e) => { + error!("Failed to load the pid eBPF bytecode. {}", e); + Notification::send( + "Failed to load the pid eBPF bytecode", + NotificationLevel::Error, + notification_sender, + ) + .unwrap(); + return; + } + }; + + let sock_connect: &mut CgroupSockAddr = bpf + .program_mut("socket_connect") + .unwrap() + .try_into() + .unwrap(); + sock_connect.load().unwrap(); + let file = File::open("/sys/fs/cgroup/user.slice").unwrap(); + + sock_connect.attach(file, CgroupAttachMode::Single).unwrap(); + + let mut poll = Poll::new().unwrap(); + let mut events = Events::with_capacity(128); + + let mut ring_buf = RingBuffer::new(&mut bpf, "PID_DATA"); + + poll.registry() + .register( + &mut SourceFd(&ring_buf.buffer.as_raw_fd()), + Token(0), + Interest::READABLE, + ) + .unwrap(); + + loop { + poll.poll(&mut events, Some(Duration::from_millis(100))) + .unwrap(); + if terminate.load(std::sync::atomic::Ordering::Relaxed) { + break; + } + for event in &events { + if terminate.load(std::sync::atomic::Ordering::Relaxed) { + break; + } + if event.token() == Token(0) && event.is_readable() { + if terminate.load(std::sync::atomic::Ordering::Relaxed) { + break; + } + while let Some(item) = ring_buf.next() { + if terminate.load(std::sync::atomic::Ordering::Relaxed) { + break; + } + let pid: [u8; 4] = item.to_owned().try_into().unwrap(); + let pid = u32::from_ne_bytes(pid); + + let fd_dir = format!("/proc/{}/fd", pid); + if let Ok(_fds) = fs::read_dir(&fd_dir) { + let mut map = pid_map.lock().unwrap(); + *map = ConnectionMap::new(); + } + } + } + } + } + + let _ = poll + .registry() + .deregister(&mut SourceFd(&ring_buf.buffer.as_raw_fd())); + } + }); +} diff --git a/oryx-tui/src/handler.rs b/oryx-tui/src/handler.rs index dca3f05..9b127b1 100644 --- a/oryx-tui/src/handler.rs +++ b/oryx-tui/src/handler.rs @@ -5,6 +5,7 @@ use std::{ use crate::{ app::{ActivePopup, App, AppResult}, + ebpf::pid::load_pid, event::Event, filter::FocusedBlock, section::{stats::Stats, FocusedSection}, @@ -24,6 +25,11 @@ pub fn handle_key_events( app.section.stats = Some(Stats::new(app.packets.clone())); app.filter .start(event_sender.clone(), app.data_channel_sender.clone())?; + load_pid( + app.pid_map.clone(), + event_sender.clone(), + app.pid_terminate.clone(), + ); sleep(Duration::from_millis(100)); app.start_sniffing = true; diff --git a/test-sock-addr/.gitignore b/test-sock-addr/.gitignore deleted file mode 100644 index 9db7029..0000000 --- a/test-sock-addr/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -### https://raw.github.com/github/gitignore/master/Rust.gitignore - -# Generated by Cargo -# will have compiled files and executables -debug/ -target/ - -# These are backup files generated by rustfmt -**/*.rs.bk diff --git a/test-sock-addr/Cargo.lock b/test-sock-addr/Cargo.lock deleted file mode 100644 index 0bb3096..0000000 --- a/test-sock-addr/Cargo.lock +++ /dev/null @@ -1,813 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "addr2line" -version = "0.24.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1" -dependencies = [ - "gimli", -] - -[[package]] -name = "adler2" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" - -[[package]] -name = "allocator-api2" -version = "0.2.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f" - -[[package]] -name = "anstyle" -version = "1.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" - -[[package]] -name = "anyhow" -version = "1.0.93" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c95c10ba0b00a02636238b814946408b1322d5ac4760326e6fb8ec956d85775" - -[[package]] -name = "assert_matches" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9" - -[[package]] -name = "aya" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d18bc4e506fbb85ab7392ed993a7db4d1a452c71b75a246af4a80ab8c9d2dd50" -dependencies = [ - "assert_matches", - "aya-obj", - "bitflags", - "bytes", - "libc", - "log", - "object", - "once_cell", - "thiserror", - "tokio", -] - -[[package]] -name = "aya-ebpf" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8dbaf5409a1a0982e5c9bdc0f499a55fe5ead39fe9c846012053faf0d404f73" -dependencies = [ - "aya-ebpf-bindings", - "aya-ebpf-cty", - "aya-ebpf-macros", - "rustversion", -] - -[[package]] -name = "aya-ebpf-bindings" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "783dc1a82a3d71d83286165381dcc1b1d41643f4b110733d135547527c000a9a" -dependencies = [ - "aya-ebpf-cty", -] - -[[package]] -name = "aya-ebpf-cty" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cce099aaf3abb89f9a1f8594ffe07fa53738ebc2882fac624d10d9ba31a1b10" - -[[package]] -name = "aya-ebpf-macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f47f7b4a75eb5f1d7ba0fb5628d247b1cf20388658899177875dabdda66865" -dependencies = [ - "proc-macro-error", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "aya-log" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b600d806c1d07d3b81ab5f4a2a95fd80f479a0d3f1d68f29064d660865f85f02" -dependencies = [ - "aya", - "aya-log-common", - "bytes", - "log", - "thiserror", - "tokio", -] - -[[package]] -name = "aya-log-common" -version = "0.1.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "befef9fe882e63164a2ba0161874e954648a72b0e1c4b361f532d590638c4eec" -dependencies = [ - "num_enum", -] - -[[package]] -name = "aya-log-ebpf" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae348f459df78a79e5cd5e164b6562b927033b97ca3b033605b341a474f44510" -dependencies = [ - "aya-ebpf", - "aya-log-common", - "aya-log-ebpf-macros", -] - -[[package]] -name = "aya-log-ebpf-macros" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6d8251a75f56077db51892041aa6b77c70ef2723845d7a210979700b2f01bc4" -dependencies = [ - "aya-log-common", - "aya-log-parser", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "aya-log-parser" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14b102eb5c88c9aa0b49102d3fbcee08ecb0dfa81014f39b373311de7a7032cb" -dependencies = [ - "aya-log-common", -] - -[[package]] -name = "aya-obj" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c51b96c5a8ed8705b40d655273bc4212cbbf38d4e3be2788f36306f154523ec7" -dependencies = [ - "bytes", - "core-error", - "hashbrown", - "log", - "object", - "thiserror", -] - -[[package]] -name = "backtrace" -version = "0.3.74" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a" -dependencies = [ - "addr2line", - "cfg-if", - "libc", - "miniz_oxide", - "object", - "rustc-demangle", - "windows-targets", -] - -[[package]] -name = "bitflags" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" - -[[package]] -name = "bytes" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ac0150caa2ae65ca5bd83f25c7de183dea78d4d366469f148435e2acfbad0da" - -[[package]] -name = "camino" -version = "1.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b96ec4966b5813e2c0507c1f86115c8c5abaadc3980879c3424042a02fd1ad3" -dependencies = [ - "serde", -] - -[[package]] -name = "cargo-platform" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24b1f0365a6c6bb4020cd05806fd0d33c44d38046b8bd7f0e40814b9763cabfc" -dependencies = [ - "serde", -] - -[[package]] -name = "cargo_metadata" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d886547e41f740c616ae73108f6eb70afe6d940c7bc697cb30f13daec073037" -dependencies = [ - "camino", - "cargo-platform", - "semver", - "serde", - "serde_json", - "thiserror", -] - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "clap" -version = "4.5.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b97f376d85a664d5837dbae44bf546e6477a679ff6610010f17276f686d867e8" -dependencies = [ - "clap_builder", - "clap_derive", -] - -[[package]] -name = "clap_builder" -version = "4.5.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19bc80abd44e4bed93ca373a0704ccbd1b710dc5749406201bb018272808dc54" -dependencies = [ - "anstyle", - "clap_lex", -] - -[[package]] -name = "clap_derive" -version = "4.5.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ac6a0c7b1a9e9a5186361f67dfa1b88213572f427fb9ab038efb2bd8c582dab" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "clap_lex" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1462739cb27611015575c0c11df5df7601141071f07518d56fcc1be504cbec97" - -[[package]] -name = "core-error" -version = "0.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "efcdb2972eb64230b4c50646d8498ff73f5128d196a90c7236eec4cbe8619b8f" -dependencies = [ - "version_check", -] - -[[package]] -name = "crc32fast" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "either" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" - -[[package]] -name = "env_filter" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f2c92ceda6ceec50f43169f9ee8424fe2db276791afde7b2cd8bc084cb376ab" -dependencies = [ - "log", -] - -[[package]] -name = "env_logger" -version = "0.11.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13fa619b91fb2381732789fc5de83b45675e882f66623b7d8cb4f643017018d" -dependencies = [ - "env_filter", - "log", -] - -[[package]] -name = "equivalent" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" - -[[package]] -name = "errno" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" -dependencies = [ - "libc", - "windows-sys", -] - -[[package]] -name = "foldhash" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f81ec6369c545a7d40e4589b5597581fa1c441fe1cce96dd1de43159910a36a2" - -[[package]] -name = "gimli" -version = "0.31.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" - -[[package]] -name = "hashbrown" -version = "0.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a9bfc1af68b1726ea47d3d5109de126281def866b33970e10fbab11b5dafab3" -dependencies = [ - "allocator-api2", - "equivalent", - "foldhash", -] - -[[package]] -name = "heck" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" - -[[package]] -name = "hermit-abi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" - -[[package]] -name = "home" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3d1354bf6b7235cb4a0576c2619fd4ed18183f689b12b006a0ee7329eeff9a5" -dependencies = [ - "windows-sys", -] - -[[package]] -name = "indexmap" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "707907fe3c25f5424cce2cb7e1cbcafee6bdbe735ca90ef77c29e84591e5b9da" -dependencies = [ - "equivalent", - "hashbrown", -] - -[[package]] -name = "itoa" -version = "1.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" - -[[package]] -name = "libc" -version = "0.2.162" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18d287de67fe55fd7e1581fe933d965a5a9477b38e949cfa9f8574ef01506398" - -[[package]] -name = "linux-raw-sys" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" - -[[package]] -name = "log" -version = "0.4.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" - -[[package]] -name = "memchr" -version = "2.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" - -[[package]] -name = "miniz_oxide" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2d80299ef12ff69b16a84bb182e3b9df68b5a91574d3d4fa6e41b65deec4df1" -dependencies = [ - "adler2", -] - -[[package]] -name = "mio" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80e04d1dcff3aae0704555fe5fee3bcfaf3d1fdf8a7e521d5b9d2b42acb52cec" -dependencies = [ - "hermit-abi", - "libc", - "wasi", - "windows-sys", -] - -[[package]] -name = "num_enum" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e613fc340b2220f734a8595782c551f1250e969d87d3be1ae0579e8d4065179" -dependencies = [ - "num_enum_derive", -] - -[[package]] -name = "num_enum_derive" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af1844ef2428cc3e1cb900be36181049ef3d3193c63e43026cfe202983b27a56" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "object" -version = "0.36.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aedf0a2d09c573ed1d8d85b30c119153926a2b36dce0ab28322c09a117a4683e" -dependencies = [ - "crc32fast", - "hashbrown", - "indexmap", - "memchr", -] - -[[package]] -name = "once_cell" -version = "1.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775" - -[[package]] -name = "pin-project-lite" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "915a1e146535de9163f3987b8944ed8cf49a18bb0056bcebcdcece385cece4ff" - -[[package]] -name = "proc-macro-error" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" -dependencies = [ - "proc-macro-error-attr", - "proc-macro2", - "quote", - "version_check", -] - -[[package]] -name = "proc-macro-error-attr" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" -dependencies = [ - "proc-macro2", - "quote", - "version_check", -] - -[[package]] -name = "proc-macro2" -version = "1.0.89" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f139b0662de085916d1fb67d2b4169d1addddda1919e696f3252b740b629986e" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quote" -version = "1.0.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "rustc-demangle" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" - -[[package]] -name = "rustix" -version = "0.38.39" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "375116bee2be9ed569afe2154ea6a99dfdffd257f533f187498c2a8f5feaf4ee" -dependencies = [ - "bitflags", - "errno", - "libc", - "linux-raw-sys", - "windows-sys", -] - -[[package]] -name = "rustversion" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e819f2bc632f285be6d7cd36e25940d45b2391dd6d9b939e79de557f7014248" - -[[package]] -name = "ryu" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" - -[[package]] -name = "semver" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" -dependencies = [ - "serde", -] - -[[package]] -name = "serde" -version = "1.0.214" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f55c3193aca71c12ad7890f1785d2b73e1b9f63a0bbc353c08ef26fe03fc56b5" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.214" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de523f781f095e28fa605cdce0f8307e451cc0fd14e2eb4cd2e98a355b147766" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "serde_json" -version = "1.0.132" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d726bfaff4b320266d395898905d0eba0345aae23b54aee3a737e260fd46db03" -dependencies = [ - "itoa", - "memchr", - "ryu", - "serde", -] - -[[package]] -name = "signal-hook-registry" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" -dependencies = [ - "libc", -] - -[[package]] -name = "socket2" -version = "0.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" -dependencies = [ - "libc", - "windows-sys", -] - -[[package]] -name = "syn" -version = "2.0.87" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "test-sockaddr" -version = "0.1.0" -dependencies = [ - "anyhow", - "aya", - "aya-log", - "cargo_metadata", - "clap", - "env_logger", - "libc", - "log", - "test-sockaddr-common", - "test-sockaddr-ebpf", - "tokio", -] - -[[package]] -name = "test-sockaddr-common" -version = "0.1.0" -dependencies = [ - "aya", -] - -[[package]] -name = "test-sockaddr-ebpf" -version = "0.1.0" -dependencies = [ - "aya-ebpf", - "aya-log-ebpf", - "test-sockaddr-common", - "which", -] - -[[package]] -name = "thiserror" -version = "1.0.68" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02dd99dc800bbb97186339685293e1cc5d9df1f8fae2d0aecd9ff1c77efea892" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.68" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7c61ec9a6f64d2793d8a45faba21efbe3ced62a886d44c36a009b2b519b4c7e" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tokio" -version = "1.41.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22cfb5bee7a6a52939ca9224d6ac897bb669134078daa8735560897f69de4d33" -dependencies = [ - "backtrace", - "libc", - "mio", - "pin-project-lite", - "signal-hook-registry", - "socket2", - "tokio-macros", - "windows-sys", -] - -[[package]] -name = "tokio-macros" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "unicode-ident" -version = "1.0.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e91b56cd4cadaeb79bbf1a5645f6b4f8dc5bde8834ad5894a8db35fda9efa1fe" - -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - -[[package]] -name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" - -[[package]] -name = "which" -version = "6.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ee928febd44d98f2f459a4a79bd4d928591333a494a10a868418ac1b39cf1f" -dependencies = [ - "either", - "home", - "rustix", - "winsafe", -] - -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets", -] - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "winsafe" -version = "0.0.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" diff --git a/test-sock-addr/Cargo.toml b/test-sock-addr/Cargo.toml deleted file mode 100644 index 130adf4..0000000 --- a/test-sock-addr/Cargo.toml +++ /dev/null @@ -1,32 +0,0 @@ -[workspace] -resolver = "2" -members = ["test-sockaddr", "test-sockaddr-common", "test-sockaddr-ebpf"] -default-members = ["test-sockaddr", "test-sockaddr-common"] - -[workspace.dependencies] -aya = { version = "0.13.0", default-features = false } -aya-ebpf = { version = "0.1.1", default-features = false } -aya-log = { version = "0.2.1", default-features = false } -aya-log-ebpf = { version = "0.1.1", default-features = false } - -anyhow = { version = "1", default-features = false } -cargo_metadata = { version = "0.18.0", default-features = false } -# `std` feature is currently required to build `clap`. -# -# See https://github.com/clap-rs/clap/blob/61f5ee5/clap_builder/src/lib.rs#L15. -clap = { version = "4.5.20", default-features = false, features = ["std"] } -env_logger = { version = "0.11.5", default-features = false } -libc = { version = "0.2.159", default-features = false } -log = { version = "0.4.22", default-features = false } -tokio = { version = "1.40.0", default-features = false } -which = { version = "6.0.0", default-features = false } - -[profile.dev] -panic = "abort" - -[profile.release] -panic = "abort" - -[profile.release.package.test-sockaddr-ebpf] -debug = 2 -codegen-units = 1 diff --git a/test-sock-addr/README.md b/test-sock-addr/README.md deleted file mode 100644 index 28b39b4..0000000 --- a/test-sock-addr/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# test-sockaddr - -## Prerequisites - -1. stable rust toolchains: `rustup toolchain install stable` -1. nightly rust toolchains: `rustup toolchain install nightly --component rust-src` -1. (if cross-compiling) rustup target: `rustup target add ${ARCH}-unknown-linux-musl` -1. (if cross-compiling) LLVM: (e.g.) `brew install llvm` (on macOS) -1. (if cross-compiling) C toolchain: (e.g.) [`brew install filosottile/musl-cross/musl-cross`](https://github.com/FiloSottile/homebrew-musl-cross) (on macOS) -1. bpf-linker: `cargo install bpf-linker` (`--no-default-features` on macOS) - -## Build & Run - -Use `cargo build`, `cargo check`, etc. as normal. Run your program with: - -```shell -cargo run --release --config 'target."cfg(all())".runner="sudo -E"' -``` - -Cargo build scripts are used to automatically build the eBPF correctly and include it in the -program. - -## Cross-compiling on macOS - -Cross compilation should work on both Intel and Apple Silicon Macs. - -```shell -CC=${ARCH}-linux-musl-gcc cargo build --package test-sockaddr --release \ - --target=${ARCH}-unknown-linux-musl \ - --config=target.${ARCH}-unknown-linux-musl.linker=\"${ARCH}-linux-musl-gcc\" -``` -The cross-compiled program `target/${ARCH}-unknown-linux-musl/release/test-sockaddr` can be -copied to a Linux server or VM and run there. diff --git a/test-sock-addr/rustfmt.toml b/test-sock-addr/rustfmt.toml deleted file mode 100644 index 53f7b6d..0000000 --- a/test-sock-addr/rustfmt.toml +++ /dev/null @@ -1,4 +0,0 @@ -group_imports = "StdExternalCrate" -imports_granularity = "Crate" -reorder_imports = true -unstable_features = true diff --git a/test-sock-addr/test-sockaddr-common/Cargo.toml b/test-sock-addr/test-sockaddr-common/Cargo.toml deleted file mode 100644 index a4c37a3..0000000 --- a/test-sock-addr/test-sockaddr-common/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "test-sockaddr-common" -version = "0.1.0" -edition = "2021" - -[features] -default = [] -user = ["aya"] - -[dependencies] -aya = { workspace = true, optional = true } - -[lib] -path = "src/lib.rs" diff --git a/test-sock-addr/test-sockaddr-common/src/lib.rs b/test-sock-addr/test-sockaddr-common/src/lib.rs deleted file mode 100644 index 0c9ac1a..0000000 --- a/test-sock-addr/test-sockaddr-common/src/lib.rs +++ /dev/null @@ -1 +0,0 @@ -#![no_std] diff --git a/test-sock-addr/test-sockaddr-ebpf/.cargo/config.toml b/test-sock-addr/test-sockaddr-ebpf/.cargo/config.toml deleted file mode 100644 index d8d7a20..0000000 --- a/test-sock-addr/test-sockaddr-ebpf/.cargo/config.toml +++ /dev/null @@ -1,12 +0,0 @@ -# We have this so that one doesn't need to manually pass -# --target=bpfel-unknown-none -Z build-std=core when running cargo -# check/build/doc etc. -# -# NB: this file gets loaded only if you run cargo from this directory, it's -# ignored if you run from the workspace root. See -# https://doc.rust-lang.org/cargo/reference/config.html#hierarchical-structure -[build] -target = ["bpfeb-unknown-none", "bpfel-unknown-none"] - -[unstable] -build-std = ["core"] diff --git a/test-sock-addr/test-sockaddr-ebpf/Cargo.toml b/test-sock-addr/test-sockaddr-ebpf/Cargo.toml deleted file mode 100644 index b33ee72..0000000 --- a/test-sock-addr/test-sockaddr-ebpf/Cargo.toml +++ /dev/null @@ -1,17 +0,0 @@ -[package] -name = "test-sockaddr-ebpf" -version = "0.1.0" -edition = "2021" - -[dependencies] -test-sockaddr-common = { path = "../test-sockaddr-common" } - -aya-ebpf = { workspace = true } -aya-log-ebpf = { workspace = true } - -[build-dependencies] -which = { workspace = true } - -[[bin]] -name = "test-sockaddr" -path = "src/main.rs" diff --git a/test-sock-addr/test-sockaddr-ebpf/build.rs b/test-sock-addr/test-sockaddr-ebpf/build.rs deleted file mode 100644 index f83c317..0000000 --- a/test-sock-addr/test-sockaddr-ebpf/build.rs +++ /dev/null @@ -1,17 +0,0 @@ -use which::which; - -/// Building this crate has an undeclared dependency on the `bpf-linker` binary. This would be -/// better expressed by [artifact-dependencies][bindeps] but issues such as -/// https://github.com/rust-lang/cargo/issues/12385 make their use impractical for the time being. -/// -/// This file implements an imperfect solution: it causes cargo to rebuild the crate whenever the -/// mtime of `which bpf-linker` changes. Note that possibility that a new bpf-linker is added to -/// $PATH ahead of the one used as the cache key still exists. Solving this in the general case -/// would require rebuild-if-changed-env=PATH *and* rebuild-if-changed={every-directory-in-PATH} -/// which would likely mean far too much cache invalidation. -/// -/// [bindeps]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html?highlight=feature#artifact-dependencies -fn main() { - let bpf_linker = which("bpf-linker").unwrap(); - println!("cargo:rerun-if-changed={}", bpf_linker.to_str().unwrap()); -} diff --git a/test-sock-addr/test-sockaddr-ebpf/rust-toolchain.toml b/test-sock-addr/test-sockaddr-ebpf/rust-toolchain.toml deleted file mode 100644 index f70d225..0000000 --- a/test-sock-addr/test-sockaddr-ebpf/rust-toolchain.toml +++ /dev/null @@ -1,3 +0,0 @@ -[toolchain] -channel = "nightly" -components = ["rust-src"] diff --git a/test-sock-addr/test-sockaddr-ebpf/src/lib.rs b/test-sock-addr/test-sockaddr-ebpf/src/lib.rs deleted file mode 100644 index 3ac3e59..0000000 --- a/test-sock-addr/test-sockaddr-ebpf/src/lib.rs +++ /dev/null @@ -1,3 +0,0 @@ -#![no_std] - -// This file exists to enable the library target. diff --git a/test-sock-addr/test-sockaddr-ebpf/src/main.rs b/test-sock-addr/test-sockaddr-ebpf/src/main.rs deleted file mode 100644 index e71ca42..0000000 --- a/test-sock-addr/test-sockaddr-ebpf/src/main.rs +++ /dev/null @@ -1,81 +0,0 @@ -#![no_std] -#![no_main] - -use core::net::Ipv4Addr; - -use aya_ebpf::{ - bindings::{bpf_sock, bpf_sock_addr}, - helpers::bpf_get_current_pid_tgid, - macros::{cgroup_sock, cgroup_sock_addr}, - programs::{SockAddrContext, SockContext}, -}; -use aya_log_ebpf::info; - -#[cgroup_sock_addr(connect4)] -pub fn socket_connect(ctx: SockAddrContext) -> i32 { - info!(&ctx, "connect"); - match sock_connect(ctx) { - Ok(ret) => ret, - Err(ret) => ret, - } -} - -#[cgroup_sock(post_bind4)] -pub fn socket_create(ctx: SockContext) -> i32 { - info!(&ctx, "create"); - match sock_create(ctx) { - Ok(ret) => ret, - Err(ret) => ret, - } -} -fn sock_create(ctx: SockContext) -> Result { - let sock = unsafe { *(ctx.sock as *const bpf_sock) }; - let proto = sock.protocol; - let family = sock.family; - let type_ = sock.type_; - - info!( - &ctx, - "create sock with proto :{} fam {} type {} ", proto, family, type_, - ); - Ok(1) -} - -// pub struct bpf_sock_addr { -// pub user_family: __u32, -// pub user_ip4: __u32, -// pub user_ip6: [__u32; 4usize], -// pub user_port: __u32, -// pub family: __u32, -// pub type_: __u32, -// pub protocol: __u32, -// pub msg_src_ip4: __u32, -// pub msg_src_ip6: [__u32; 4usize], -// pub __bindgen_anon_1: bpf_sock_addr__bindgen_ty_1, -// } -fn sock_connect(ctx: SockAddrContext) -> Result { - let pid = (bpf_get_current_pid_tgid() >> 32) as u32; - let sock_addr = unsafe { *(ctx.sock_addr as *const bpf_sock_addr) }; - - let family = sock_addr.family; - let proto = sock_addr.protocol as u8; - let ipv4 = sock_addr.user_ip4; - - let port = sock_addr.user_port; - info!( - &ctx, - "pid:{} family:{} proto:{} ip:{} port:{} ", - pid, - family, - proto, - Ipv4Addr::from_bits(u32::from_be(ipv4)), - u16::from_be(port as u16) - ); - Ok(1) -} - -#[cfg(not(test))] -#[panic_handler] -fn panic(_info: &core::panic::PanicInfo) -> ! { - loop {} -} diff --git a/test-sock-addr/test-sockaddr/Cargo.toml b/test-sock-addr/test-sockaddr/Cargo.toml deleted file mode 100644 index 857d2ec..0000000 --- a/test-sock-addr/test-sockaddr/Cargo.toml +++ /dev/null @@ -1,36 +0,0 @@ -[package] -name = "test-sockaddr" -version = "0.1.0" -edition = "2021" - -[dependencies] -test-sockaddr-common = { path = "../test-sockaddr-common", features = ["user"] } - -anyhow = { workspace = true, default-features = true } -aya = { workspace = true } -aya-log = { workspace = true } -env_logger = { workspace = true } -libc = { workspace = true } -log = { workspace = true } -tokio = { workspace = true, features = ["macros", "rt", "rt-multi-thread", "net", "signal"] } - -clap = { workspace = true, features = ["derive"] } -[build-dependencies] -cargo_metadata = { workspace = true } -# TODO(https://github.com/rust-lang/cargo/issues/12375): this should be an artifact dependency, but -# it's not possible to tell cargo to use `-Z build-std` to build it. We cargo-in-cargo in the build -# script to build this, but we want to teach cargo about the dependecy so that cache invalidation -# works properly. -# -# Note also that https://github.com/rust-lang/cargo/issues/10593 occurs when `target = ...` is added -# to an artifact dependency; it seems possible to work around that by setting `resolver = "1"` in -# Cargo.toml in the workspace root. -# -# Finally note that *any* usage of `artifact = ...` in *any* Cargo.toml in the workspace breaks -# workflows with stable cargo; stable cargo outright refuses to load manifests that use unstable -# features. -test-sockaddr-ebpf = { path = "../test-sockaddr-ebpf" } - -[[bin]] -name = "test-sockaddr" -path = "src/main.rs" diff --git a/test-sock-addr/test-sockaddr/build.rs b/test-sock-addr/test-sockaddr/build.rs deleted file mode 100644 index c162571..0000000 --- a/test-sock-addr/test-sockaddr/build.rs +++ /dev/null @@ -1,150 +0,0 @@ -use std::{ - env, fs, - io::{BufRead as _, BufReader}, - path::PathBuf, - process::{Child, Command, Stdio}, -}; - -use cargo_metadata::{ - Artifact, CompilerMessage, Message, Metadata, MetadataCommand, Package, Target, -}; - -/// This crate has a runtime dependency on artifacts produced by the `test-sockaddr-ebpf` crate. -/// This would be better expressed as one or more [artifact-dependencies][bindeps] but issues such -/// as: -/// -/// * https://github.com/rust-lang/cargo/issues/12374 -/// * https://github.com/rust-lang/cargo/issues/12375 -/// * https://github.com/rust-lang/cargo/issues/12385 -/// -/// prevent their use for the time being. -/// -/// [bindeps]: https://doc.rust-lang.org/nightly/cargo/reference/unstable.html?highlight=feature#artifact-dependencies -fn main() { - let Metadata { packages, .. } = MetadataCommand::new().no_deps().exec().unwrap(); - let ebpf_package = packages - .into_iter() - .find(|Package { name, .. }| name == "test-sockaddr-ebpf") - .unwrap(); - - let out_dir = env::var_os("OUT_DIR").unwrap(); - let out_dir = PathBuf::from(out_dir); - - let endian = env::var_os("CARGO_CFG_TARGET_ENDIAN").unwrap(); - let target = if endian == "big" { - "bpfeb" - } else if endian == "little" { - "bpfel" - } else { - panic!("unsupported endian={:?}", endian) - }; - - // TODO(https://github.com/rust-lang/cargo/issues/4001): Make this `false` if we can determine - // we're in a check build. - let build_ebpf = true; - if build_ebpf { - let arch = env::var_os("CARGO_CFG_TARGET_ARCH").unwrap(); - - let target = format!("{target}-unknown-none"); - - let Package { manifest_path, .. } = ebpf_package; - let ebpf_dir = manifest_path.parent().unwrap(); - - // We have a build-dependency on `test-sockaddr-ebpf`, so cargo will automatically rebuild us - // if `test-sockaddr-ebpf`'s *library* target or any of its dependencies change. Since we - // depend on `test-sockaddr-ebpf`'s *binary* targets, that only gets us half of the way. This - // stanza ensures cargo will rebuild us on changes to the binaries too, which gets us the - // rest of the way. - println!("cargo:rerun-if-changed={}", ebpf_dir.as_str()); - - let mut cmd = Command::new("cargo"); - cmd.args([ - "build", - "-Z", - "build-std=core", - "--bins", - "--message-format=json", - "--release", - "--target", - &target, - ]); - - cmd.env("CARGO_CFG_BPF_TARGET_ARCH", arch); - - // Workaround to make sure that the rust-toolchain.toml is respected. - for key in ["RUSTUP_TOOLCHAIN", "RUSTC", "RUSTC_WORKSPACE_WRAPPER"] { - cmd.env_remove(key); - } - cmd.current_dir(ebpf_dir); - - // Workaround for https://github.com/rust-lang/cargo/issues/6412 where cargo flocks itself. - let ebpf_target_dir = out_dir.join("test-sockaddr-ebpf"); - cmd.arg("--target-dir").arg(&ebpf_target_dir); - - let mut child = cmd - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap_or_else(|err| panic!("failed to spawn {cmd:?}: {err}")); - let Child { stdout, stderr, .. } = &mut child; - - // Trampoline stdout to cargo warnings. - let stderr = stderr.take().unwrap(); - let stderr = BufReader::new(stderr); - let stderr = std::thread::spawn(move || { - for line in stderr.lines() { - let line = line.unwrap(); - println!("cargo:warning={line}"); - } - }); - - let stdout = stdout.take().unwrap(); - let stdout = BufReader::new(stdout); - let mut executables = Vec::new(); - for message in Message::parse_stream(stdout) { - #[allow(clippy::collapsible_match)] - match message.expect("valid JSON") { - Message::CompilerArtifact(Artifact { - executable, - target: Target { name, .. }, - .. - }) => { - if let Some(executable) = executable { - executables.push((name, executable.into_std_path_buf())); - } - } - Message::CompilerMessage(CompilerMessage { message, .. }) => { - for line in message.rendered.unwrap_or_default().split('\n') { - println!("cargo:warning={line}"); - } - } - Message::TextLine(line) => { - println!("cargo:warning={line}"); - } - _ => {} - } - } - - let status = child - .wait() - .unwrap_or_else(|err| panic!("failed to wait for {cmd:?}: {err}")); - assert_eq!(status.code(), Some(0), "{cmd:?} failed: {status:?}"); - - stderr.join().map_err(std::panic::resume_unwind).unwrap(); - - for (name, binary) in executables { - let dst = out_dir.join(name); - let _: u64 = fs::copy(&binary, &dst) - .unwrap_or_else(|err| panic!("failed to copy {binary:?} to {dst:?}: {err}")); - } - } else { - let Package { targets, .. } = ebpf_package; - for Target { name, kind, .. } in targets { - if *kind != ["bin"] { - continue; - } - let dst = out_dir.join(name); - fs::write(&dst, []).unwrap_or_else(|err| panic!("failed to create {dst:?}: {err}")); - } - } -} diff --git a/test-sock-addr/test-sockaddr/src/main.rs b/test-sock-addr/test-sockaddr/src/main.rs deleted file mode 100644 index 2fda7b7..0000000 --- a/test-sock-addr/test-sockaddr/src/main.rs +++ /dev/null @@ -1,59 +0,0 @@ -use std::fs::File; - -use aya::programs::{links::CgroupAttachMode, CgroupSock, CgroupSockAddr}; -use clap::Parser; -#[rustfmt::skip] -use log::{debug, warn}; - -use tokio::signal; - -#[tokio::main] -async fn main() -> anyhow::Result<()> { - env_logger::init(); - - // Bump the memlock rlimit. This is needed for older kernels that don't use the - // new memcg based accounting, see https://lwn.net/Articles/837122/ - let rlim = libc::rlimit { - rlim_cur: libc::RLIM_INFINITY, - rlim_max: libc::RLIM_INFINITY, - }; - let ret = unsafe { libc::setrlimit(libc::RLIMIT_MEMLOCK, &rlim) }; - if ret != 0 { - debug!("remove limit on locked memory failed, ret is: {}", ret); - } - - let mut ebpf = aya::Ebpf::load(aya::include_bytes_aligned!(concat!( - env!("OUT_DIR"), - "/test-sockaddr" - )))?; - if let Err(e) = aya_log::EbpfLogger::init(&mut ebpf) { - // This can happen if you remove all log statements from your eBPF program. - warn!("failed to initialize eBPF logger: {}", e); - } - let file = File::open("/sys/fs/cgroup/user.slice")?; - let sock_create: &mut CgroupSock = ebpf.program_mut("socket_create").unwrap().try_into()?; - sock_create.load()?; - sock_create.attach(file, CgroupAttachMode::Single)?; - - let mut ebpf = aya::Ebpf::load(aya::include_bytes_aligned!(concat!( - env!("OUT_DIR"), - "/test-sockaddr" - )))?; - if let Err(e) = aya_log::EbpfLogger::init(&mut ebpf) { - // This can happen if you remove all log statements from your eBPF program. - warn!("failed to initialize eBPF logger: {}", e); - } - let sock_connect: &mut CgroupSockAddr = - ebpf.program_mut("socket_connect").unwrap().try_into()?; - sock_connect.load()?; - let file = File::open("/sys/fs/cgroup/user.slice")?; - - sock_connect.attach(file, CgroupAttachMode::Single)?; - - let ctrl_c = signal::ctrl_c(); - println!("Waiting for Ctrl-C..."); - ctrl_c.await?; - println!("Exiting..."); - - Ok(()) -}