From da6bc6bdbf50da0eeeb4b544395c1b392d228d21 Mon Sep 17 00:00:00 2001 From: Irene Knapp Date: Tue, 24 Nov 2026 19:20:10 -0700 Subject: switch to Send mutices; make the i3 protocol work that was a lot of painful debugging, but not much code in the end Force-Push: yes Change-Id: Ib38842ac3dafb4ab71ee041d0425accee1e9f067 --- src/facility/i3.rs | 131 ++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 124 insertions(+), 7 deletions(-) (limited to 'src/facility/i3.rs') diff --git a/src/facility/i3.rs b/src/facility/i3.rs index c2f9878..141b6d8 100644 --- a/src/facility/i3.rs +++ b/src/facility/i3.rs @@ -4,16 +4,27 @@ use crate::unix::get_username; use crate::xdg::xdg_runtime_directory; use std::any::Any; +use std::mem::size_of; use std::path::{ Path, PathBuf }; +use std::slice::{ from_raw_parts, from_raw_parts_mut }; +use std::sync::Arc; +use async_executor::StaticExecutor; use async_fs::{ metadata, read_dir }; use async_fs::unix::FileTypeExt; +use async_lock::Mutex; use async_net::unix::UnixStream; -use futures_lite::StreamExt; +use futures_lite::{ AsyncReadExt, AsyncWriteExt, StreamExt }; +use futures_lite::io::{ split, ReadHalf, WriteHalf }; + + +#[allow(unused)] +const MAGIC_NUMBER: &[u8; 6] = b"i3-ipc"; pub struct I3 { - socket: UnixStream, + read_socket: Arc>>, + write_socket: Arc>>, } @@ -30,10 +41,20 @@ impl Facility for I3 { impl CreatableFacility for I3 { const FACILITY_TYPE: FacilityType = FacilityType::I3; - async fn new() -> Result { + async fn new(executor: &'static StaticExecutor) -> Result { let socket = Self::find_socket().await?; - Ok(I3 { socket }) + let (read_socket, write_socket) = split(socket); + let read_socket = Arc::new(Mutex::new(read_socket)); + let write_socket = Arc::new(Mutex::new(write_socket)); + + let receive_task = executor.spawn( + I3::receive_loop(Arc::clone(&read_socket))); + receive_task.detach(); + + I3::write(Arc::clone(&write_socket), 2, b"[ \"mode\" ]").await?; + + Ok(I3 { read_socket, write_socket }) } } @@ -176,11 +197,107 @@ impl I3 { * filesystem. If you think about it, that makes sense: Each process that * opens it gets its own send/receive pair. It's not like a pipe. */ - let socket = UnixStream::connect(path).await?; + Ok(Some(UnixStream::connect(path).await?)) + } + + async fn receive_loop(socket: Arc>>) { + loop { + match I3::read(Arc::clone(&socket)).await { + Ok((type_code, body)) => { + let body = String::from_utf8(body).unwrap(); // TODO + + if type_code & 0x80000000 != 0 { + let event_code = type_code & 0x7fffffff; + println!("received event code {} body {}", event_code, body); + } else { + println!("received type code {} body {}", type_code, body); + } + } + Err(error) => { error.log() } + } + } + } + + async fn write(socket: Arc>>, type_code: u32, + body: &[u8]) + -> Result<()> + { + let mut socket = socket.lock().await; + + /* After extensive debugging culminating in socat MITM, it turns out that + * i3 is picky about the header being received in a single packet; if it's + * split, i3 doesn't think it's received a message. + * + * We originally used a repr(C) struct for the header, but the magic + * number is six bytes long, which breaks alignment, so it had to be done + * as two parts, which provoked the misbehavior. Of course we have no + * control over what splitting lower layers of the system might do, but in + * practice as long as we put everything in a single syscall we'll be fine. + * + * So, rather than using a struct, we allocate the whole header as a byte + * array. This is tedious to code, but better for performance anyhow, as + * it's less copying. + * + * We use pointer casts because i3 specifies that it uses the + * architecture's preferred endianness, and this is the easiest way to get + * that. It brings up bad memories of patching other people's programs in + * the 90s to swab their bytes, back when people were in the habit of being + * inadvertently architecture-dependent. Communal trauma notwithstanding, + * in Rust it's about as safe as it can reasonably be. + */ + let length = body.len() as u32; + let mut header: [u8; 14] = [0; 14]; + header[0 .. 6].copy_from_slice(MAGIC_NUMBER); + header[6 .. 10].copy_from_slice(unsafe { + from_raw_parts(&raw const length as *const u8, size_of::()) + }); + header[10 .. 14].copy_from_slice(unsafe { + from_raw_parts(&raw const type_code as *const u8, size_of::()) + }); + + socket.write_all(&header).await?; + socket.write_all(body).await?; + + Ok(()) + } + + /* The two calls to read_exact() in here need to be done without releasing + * the mutex. Since they are async functions, doing so holds the lock across + * threads. That means we are in Send-future-land, and must use the Send + * mutices from async_lock, not the non-Send mutices from std. + * + * This is the entire reason we use async_lock. That's fine, it's worth it, + * it's just also worth knowing what we're getting for it. + */ + async fn read(socket: Arc>>) + -> Result<(u32, Vec)> + { + let mut socket = socket.lock().await; + + /* While it might be nice to use uninitialized memory for this, doing so + * is a giant pain. + */ + let mut header: [u8; 14] = [0; 14]; + socket.read_exact(&mut header).await?; + + if &header[0 .. 6] != MAGIC_NUMBER { + return Err(Error::custom("Received wrong magic number from i3")); + } + + let mut length: u32 = 0; + unsafe { + from_raw_parts_mut(&raw mut length as *mut u8, size_of::()) + }.copy_from_slice(&header[6 .. 10]); + + let mut type_code: u32 = 0; + unsafe { + from_raw_parts_mut(&raw mut type_code as *mut u8, size_of::()) + }.copy_from_slice(&header[10 .. 14]); - println!("Found i3 socket {}", path.display()); + let mut body: Vec = [0].repeat(length as usize); + socket.read_exact(&mut body).await?; - Ok(Some(socket)) + Ok((type_code, body)) } } -- cgit 1.4.1