about summary refs log tree commit diff
path: root/src/facility
diff options
context:
space:
mode:
Diffstat (limited to 'src/facility')
-rw-r--r--src/facility/envsys.rs3
-rw-r--r--src/facility/i3.rs131
2 files changed, 126 insertions, 8 deletions
diff --git a/src/facility/envsys.rs b/src/facility/envsys.rs
index 0f5582b..cb2f004 100644
--- a/src/facility/envsys.rs
+++ b/src/facility/envsys.rs
@@ -6,6 +6,7 @@ use std::any::Any;
 use std::ffi::c_void;
 use std::slice::from_raw_parts;
 
+use async_executor::StaticExecutor;
 use async_fs::File;
 use futures_lite::future;
 use rustix::ioctl::{ ioctl, Opcode, Getter };
@@ -42,7 +43,7 @@ impl Facility for EnvSys {
 impl CreatableFacility for EnvSys {
   const FACILITY_TYPE: FacilityType = FacilityType::ENVSYS;
 
-  async fn new() -> Result<Self> {
+  async fn new(_executor: &StaticExecutor) -> Result<Self> {
     let sysmon = File::open("/dev/sysmon").await?;
     let dictionary = get_dictionary(&sysmon).await?;
 
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<Mutex<ReadHalf<UnixStream>>>,
+  write_socket: Arc<Mutex<WriteHalf<UnixStream>>>,
 }
 
 
@@ -30,10 +41,20 @@ impl Facility for I3 {
 impl CreatableFacility for I3 {
   const FACILITY_TYPE: FacilityType = FacilityType::I3;
 
-  async fn new() -> Result<Self> {
+  async fn new(executor: &'static StaticExecutor) -> Result<Self> {
     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<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);
+          }
+        }
+        Err(error) => { error.log() }
+      }
+    }
+  }
+
+  async fn write(socket: Arc<Mutex<WriteHalf<UnixStream>>>, 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::<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, Vec<u8>)>
+  {
+    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::<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]);
 
-    println!("Found i3 socket {}", path.display());
+    let mut body: Vec<u8> = [0].repeat(length as usize);
+    socket.read_exact(&mut body).await?;
 
-    Ok(Some(socket))
+    Ok((type_code, body))
   }
 }