diff options
| author | Irene Knapp <ireneista@irenes.space> | 2026-11-25 01:00:00 -0700 |
|---|---|---|
| committer | Irene Knapp <ireneista@irenes.space> | 2026-11-25 01:00:00 -0700 |
| commit | 893c15a2eeb16156c0b4f3e4ea815098b8f477be (patch) | |
| tree | 2ddb46c4f3f7461d5dc792ee7c0270e204f4ef81 /src | |
| parent | da6bc6bdbf50da0eeeb4b544395c1b392d228d21 (diff) | |
route i3 replies to the corresponding requestor
Force-Push: yes Change-Id: Ibe6fb298c9399f1ce3eaaeffecbad13b164eafbf
Diffstat (limited to 'src')
| -rw-r--r-- | src/error.rs | 13 | ||||
| -rw-r--r-- | src/facility/i3.rs | 370 |
2 files changed, 229 insertions, 154 deletions
diff --git a/src/error.rs b/src/error.rs index a0aa68e..f7ef553 100644 --- a/src/error.rs +++ b/src/error.rs @@ -40,6 +40,19 @@ impl From<std::num::ParseIntError> for Error { } } +impl From<std::str::Utf8Error> for Error { + fn from(error: std::str::Utf8Error) -> Error { + Error(format!("UTF8: {}", error)) + } +} + +impl From<std::string::FromUtf8Error> for Error { + fn from(error: std::string::FromUtf8Error) -> Error { + Error(format!("UTF8: {}", error)) + } +} + + impl<T> From<std::sync::PoisonError<T>> for Error { fn from(error: std::sync::PoisonError<T>) -> Error { Error(format!("Lock poisoned: {}", error)) diff --git a/src/facility/i3.rs b/src/facility/i3.rs index 141b6d8..acd8a56 100644 --- a/src/facility/i3.rs +++ b/src/facility/i3.rs @@ -9,11 +9,13 @@ use std::path::{ Path, PathBuf }; use std::slice::{ from_raw_parts, from_raw_parts_mut }; use std::sync::Arc; +use async_channel::{ unbounded, Sender }; 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 async_task::Task; use futures_lite::{ AsyncReadExt, AsyncWriteExt, StreamExt }; use futures_lite::io::{ split, ReadHalf, WriteHalf }; @@ -25,6 +27,8 @@ const MAGIC_NUMBER: &[u8; 6] = b"i3-ipc"; pub struct I3 { read_socket: Arc<Mutex<ReadHalf<UnixStream>>>, write_socket: Arc<Mutex<WriteHalf<UnixStream>>>, + receive_task: Task<()>, + pending_commands: Arc<Mutex<Vec<(u32, Sender<String>)>>>, } @@ -48,13 +52,20 @@ impl CreatableFacility for I3 { let read_socket = Arc::new(Mutex::new(read_socket)); let write_socket = Arc::new(Mutex::new(write_socket)); + let pending_commands = Arc::new(Mutex::new(Vec::new())); + let receive_task = executor.spawn( - I3::receive_loop(Arc::clone(&read_socket))); - receive_task.detach(); + receive_loop(Arc::clone(&read_socket), + Arc::clone(&pending_commands))); + + let mut i3 = I3 { + read_socket, write_socket, receive_task, pending_commands + }; - I3::write(Arc::clone(&write_socket), 2, b"[ \"mode\" ]").await?; + let response = i3.command(2, "[ \"mode\" ]").await?; + println!("it worked??? {}", response); - Ok(I3 { read_socket, write_socket }) + Ok(i3) } } @@ -78,7 +89,7 @@ impl I3 { */ let path = PathBuf::from(path); - match Self::try_socket_path(&path).await { + match try_socket_path(&path).await { Ok(Some(socket)) => { return Ok(socket); } Ok(None) => { } Err(error) => { errors.push(error); } @@ -95,7 +106,7 @@ impl I3 { if let Some(mut path) = xdg_runtime_directory()? { path.push("i3/"); - match Self::try_socket_directory(&path).await { + match try_socket_directory(&path).await { Ok(Some(socket)) => { return Ok(socket); } Ok(None) => { } Err(error) => { errors.push(error); } @@ -105,7 +116,7 @@ impl I3 { let username = get_username().await?; let tmp_path: PathBuf = "/tmp/".into(); - match Self::try_tmp_directory(&tmp_path, &username).await { + match try_tmp_directory(&tmp_path, &username).await { Ok(Some(socket)) => { return Ok(socket); } Ok(None) => { } Err(error) => { errors.push(error); } @@ -115,189 +126,240 @@ impl I3 { Err(Error::custom("i3 window manager socket not found")) } - /* One of the ways to find an i3 socket is to look within the tmp directory - * for subdirectories with names having a specific pattern. Do that. - */ - async fn try_tmp_directory(path: &Path, username: &str) - -> Result<Option<UnixStream>> - { - let mut directory = read_dir(path).await?; + async fn command(&mut self, type_code: u32, body: &str) -> Result<String> { + let (sender, receiver) = unbounded(); - while let Some(entry) = directory.try_next().await? { - /* Do not follow symlinks for the name check. + { + /* Because we hold this lock while performing the write, we know that + * items in the vector are in the same order as the commands were sent in. * - * Note also that if the name isn't valid Unicode, it doesn't match the - * pattern anyway. + * Since i3 guarantees that replies come in the same order as requests, + * that's the only property we need to route them. See receive_loop() for + * the other half of this logic. */ - if let Some(name) = entry.file_name().to_str() { - let prefix = format!("i3-{}.", username); - - if name.starts_with(&prefix) { - let tail = &name[prefix.len() ..]; - - if tail.len() == 6 { - let full_path = path.join(name); - if let Some(socket) - = Self::try_socket_directory(&full_path).await? - { - return Ok(Some(socket)); - } - } - } - } + let mut pending_commands = self.pending_commands.lock().await; + + write(Arc::clone(&self.write_socket), type_code, body.as_bytes()).await?; + pending_commands.push((type_code, sender)); } - Ok(None) + let response = receiver.recv().await?; + + Ok(response) } +} - /* Several of the ways to find an i3 socket start with a known directory - * name, and look immediately within it for a socket with a name having a - * specific pattern. Handle that case. - * - * The directory iteration logic is a lot like that for try_tmp_directory(). - * In principle, it could make sense to write a helper. - */ - async fn try_socket_directory(path: &Path) -> Result<Option<UnixStream>> { - let mut directory = read_dir(path).await?; - while let Some(entry) = directory.try_next().await? { - /* Do not follow symlinks for the name check. - * - * Note also that if the name isn't valid Unicode, it doesn't match the - * pattern anyway. - */ - if let Some(name) = entry.file_name().to_str() { - let prefix = "ipc-socket."; - if name.starts_with(prefix) { - let tail = &name[prefix.len() ..]; +/* One of the ways to find an i3 socket is to look within the tmp directory + * for subdirectories with names having a specific pattern. Do that. + */ +async fn try_tmp_directory(path: &Path, username: &str) + -> Result<Option<UnixStream>> +{ + let mut directory = read_dir(path).await?; - if tail.len() > 0 - && tail.chars().all(|c| { c.is_ascii_digit() }) - { - let full_path = path.join(name); - if let Some(socket) = Self::try_socket_path(&full_path).await? { - return Ok(Some(socket)); - } + while let Some(entry) = directory.try_next().await? { + /* Do not follow symlinks for the name check. + * + * Note also that if the name isn't valid Unicode, it doesn't match the + * pattern anyway. + */ + if let Some(name) = entry.file_name().to_str() { + let prefix = format!("i3-{}.", username); + + if name.starts_with(&prefix) { + let tail = &name[prefix.len() ..]; + + if tail.len() == 6 { + let full_path = path.join(name); + if let Some(socket) = try_socket_directory(&full_path).await? { + return Ok(Some(socket)); } } } } - - Ok(None) } - /* If we have a candidate full path to an i3 socket, see if it works. */ - async fn try_socket_path(path: &Path) -> Result<Option<UnixStream>> { - /* Do follow symlinks, for the socket check. */ - if !metadata(path).await?.file_type().is_socket() { - return Ok(None); - } + Ok(None) +} - /* Unix-domain sockets don't use open(), despite appearing in the - * 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. +/* Several of the ways to find an i3 socket start with a known directory + * name, and look immediately within it for a socket with a name having a + * specific pattern. Handle that case. + * + * The directory iteration logic is a lot like that for try_tmp_directory(). + * In principle, it could make sense to write a helper. + */ +async fn try_socket_directory(path: &Path) -> Result<Option<UnixStream>> { + let mut directory = read_dir(path).await?; + + while let Some(entry) = directory.try_next().await? { + /* Do not follow symlinks for the name check. + * + * Note also that if the name isn't valid Unicode, it doesn't match the + * pattern anyway. */ - Ok(Some(UnixStream::connect(path).await?)) - } - - async fn receive_loop(socket: Arc<Mutex<ReadHalf<UnixStream>>>) { - 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); + if let Some(name) = entry.file_name().to_str() { + let prefix = "ipc-socket."; + if name.starts_with(prefix) { + let tail = &name[prefix.len() ..]; + + if tail.len() > 0 + && tail.chars().all(|c| { c.is_ascii_digit() }) + { + let full_path = path.join(name); + if let Some(socket) = try_socket_path(&full_path).await? { + return Ok(Some(socket)); } } - Err(error) => { error.log() } } } } - async fn write(socket: Arc<Mutex<WriteHalf<UnixStream>>>, type_code: u32, - body: &[u8]) - -> Result<()> - { - let mut socket = socket.lock().await; + Ok(None) +} + +/* If we have a candidate full path to an i3 socket, see if it works. */ +async fn try_socket_path(path: &Path) -> Result<Option<UnixStream>> { + /* Do follow symlinks, for the socket check. */ + if !metadata(path).await?.file_type().is_socket() { + return Ok(None); + } + + /* Unix-domain sockets don't use open(), despite appearing in the + * 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. + */ + Ok(Some(UnixStream::connect(path).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. +async fn receive_loop(socket: Arc<Mutex<ReadHalf<UnixStream>>>, + pending_commands: Arc<Mutex<Vec<(u32, Sender<String>)>>>) +{ + loop { + /* This function is the only place we read responses or consume pending + * commands, and it's only ever invoked once. So, we know that as long as + * we consume commands in order, we haven't messed up the order. * - * 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. + * On the write end, things are more difficult; see I3::command() for + * details of how we use the mutex there. */ - 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::<u32>()) - }); - header[10 .. 14].copy_from_slice(unsafe { - from_raw_parts(&raw const type_code as *const u8, size_of::<u32>()) - }); - - socket.write_all(&header).await?; - socket.write_all(body).await?; + match read(Arc::clone(&socket)).await { + Ok((type_code, body)) => { + if type_code & 0x80000000 != 0 { + let event_code = type_code & 0x7fffffff; + println!("received event code {} body {}", event_code, body); + } else { + let mut pending_commands = pending_commands.lock().await; + + let mut found_index = None; + for (index, (pending_type_code, _)) + in pending_commands.iter().enumerate() + { + if *pending_type_code == type_code { + found_index = Some(index); + break; + } + } - Ok(()) + if let Some(index) = found_index { + let (_, sender) = pending_commands.remove(index); + + if let Err(error) = sender.send(body).await { + Into::<Error>::into(error).log(); + } + } else { + // TODO + println!("received unexpected response type code {} body {}", type_code, body); + } + } + } + Err(error) => { error.log() } + } } +} + +async fn write(socket: Arc<Mutex<WriteHalf<UnixStream>>>, type_code: u32, + body: &[u8]) + -> Result<()> +{ + let mut socket = socket.lock().await; - /* 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. + /* 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. * - * 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. + * 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::<u32>()) + }); + header[10 .. 14].copy_from_slice(unsafe { + from_raw_parts(&raw const type_code as *const u8, size_of::<u32>()) + }); + + 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<Mutex<ReadHalf<UnixStream>>>) + -> Result<(u32, String)> +{ + let mut socket = socket.lock().await; + + /* While it might be nice to use uninitialized memory for this, doing so + * is a giant pain. */ - async fn read(socket: Arc<Mutex<ReadHalf<UnixStream>>>) - -> Result<(u32, Vec<u8>)> - { - let mut socket = socket.lock().await; + let mut header: [u8; 14] = [0; 14]; + socket.read_exact(&mut header).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")); + } - 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::<u32>()) + }.copy_from_slice(&header[6 .. 10]); - let mut length: u32 = 0; - unsafe { - from_raw_parts_mut(&raw mut length as *mut u8, size_of::<u32>()) - }.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::<u32>()) + }.copy_from_slice(&header[10 .. 14]); - let mut type_code: u32 = 0; - unsafe { - from_raw_parts_mut(&raw mut type_code as *mut u8, size_of::<u32>()) - }.copy_from_slice(&header[10 .. 14]); + let mut body: Vec<u8> = [0].repeat(length as usize); + socket.read_exact(&mut body).await?; - let mut body: Vec<u8> = [0].repeat(length as usize); - socket.read_exact(&mut body).await?; + let body = String::from_utf8(body)?; - Ok((type_code, body)) - } + Ok((type_code, body)) } |