Skip to content

Commit

Permalink
refactor(ipc): replace old methods with new
Browse files Browse the repository at this point in the history
  • Loading branch information
rkuklik committed Jun 18, 2024
1 parent 089ab9e commit 64bd080
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 67 deletions.
33 changes: 16 additions & 17 deletions client/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use clap::Parser;
use std::time::Duration;
use std::{path::Path, time::Duration};

use clap::Parser;
use common::{
cache,
ipc::{self, connect_to_socket, get_socket_path, read_socket, Answer, RequestSend},
ipc::{self, read_socket, Answer, Client, IpcSocket, RequestSend},
};

mod imgproc;
Expand All @@ -19,10 +19,10 @@ fn main() -> Result<(), String> {
return cache::clean().map_err(|e| format!("failed to clean the cache: {e}"));
}

let socket = IpcSocket::connect().map_err(|err| err.to_string())?;
loop {
let socket = connect_to_socket(&get_socket_path(), 5, 100)?;
RequestSend::Ping.send(&socket)?;
let bytes = read_socket(&socket)?;
RequestSend::Ping.send(socket.as_fd())?;
let bytes = read_socket(socket.as_fd())?;
let answer = Answer::receive(bytes);
if let Answer::Ping(configured) = answer {
if configured {
Expand All @@ -42,9 +42,9 @@ fn process_swww_args(args: &Swww) -> Result<(), String> {
Some(request) => request,
None => return Ok(()),
};
let socket = connect_to_socket(&get_socket_path(), 5, 100)?;
request.send(&socket)?;
let bytes = read_socket(&socket)?;
let socket = IpcSocket::connect().map_err(|err| err.to_string())?;
request.send(socket.as_fd())?;
let bytes = read_socket(socket.as_fd())?;
drop(socket);
match Answer::receive(bytes) {
Answer::Info(info) => info.iter().for_each(|i| println!("{}", i)),
Expand All @@ -54,16 +54,15 @@ fn process_swww_args(args: &Swww) -> Result<(), String> {
let tries = 20;
#[cfg(not(debug_assertions))]
let tries = 10;
let socket_path = get_socket_path();
let path = IpcSocket::<Client>::path();
let path = Path::new(path);
for _ in 0..tries {
if !socket_path.exists() {
if !path.exists() {
return Ok(());
}
std::thread::sleep(Duration::from_millis(100));
}
return Err(format!(
"Could not confirm socket deletion at: {socket_path:?}"
));
return Err(format!("Could not confirm socket deletion at: {path:?}"));
}
}
Answer::Ping(_) => {
Expand Down Expand Up @@ -213,9 +212,9 @@ fn get_format_dims_and_outputs(
let mut dims: Vec<(u32, u32)> = Vec::new();
let mut imgs: Vec<ipc::BgImg> = Vec::new();

let socket = connect_to_socket(&get_socket_path(), 5, 100)?;
RequestSend::Query.send(&socket)?;
let bytes = read_socket(&socket)?;
let socket = IpcSocket::connect().map_err(|err| err.to_string())?;
RequestSend::Query.send(socket.as_fd())?;
let bytes = read_socket(socket.as_fd())?;
drop(socket);
let answer = Answer::receive(bytes);
match answer {
Expand Down
20 changes: 4 additions & 16 deletions common/src/ipc/socket.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::env;
use std::marker::PhantomData;
use std::path::PathBuf;
use std::sync::OnceLock;
use std::time::Duration;

Expand Down Expand Up @@ -41,6 +40,10 @@ impl<T> IpcSocket<T> {
}
}

pub fn to_fd(self) -> OwnedFd {
self.fd
}

fn socket_file() -> String {
let runtime = env::var("XDG_RUNTIME_DIR");
let display = env::var("WAYLAND_DISPLAY");
Expand Down Expand Up @@ -193,18 +196,3 @@ pub(super) fn send_socket_msg(
net::sendmsg(stream, &[iov], &mut ancillary, net::SendFlags::empty())
.map(|written| written == socket_msg.len())
}

#[must_use]
pub fn get_socket_path() -> PathBuf {
IpcSocket::<Client>::path().into()
}

/// We make sure the Stream is always set to blocking mode
///
/// * `tries` - how many times to attempt the connection
/// * `interval` - how long to wait between attempts, in milliseconds
pub fn connect_to_socket(_: &PathBuf, _: u8, _: u64) -> Result<OwnedFd, String> {
IpcSocket::connect()
.map(|socket| socket.fd)
.map_err(|err| err.to_string())
}
55 changes: 21 additions & 34 deletions daemon/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,16 @@ use std::{
fs,
io::{IsTerminal, Write},
num::{NonZeroI32, NonZeroU32},
path::PathBuf,
path::Path,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
};

use common::ipc::{
connect_to_socket, get_socket_path, read_socket, Answer, BgInfo, ImageReq, MmappedStr,
RequestRecv, RequestSend, Scale,
read_socket, Answer, BgInfo, ImageReq, IpcSocket, MmappedStr, RequestRecv, RequestSend, Scale,
Server,
};

use animations::Animator;
Expand Down Expand Up @@ -525,25 +525,26 @@ fn setup_signals() {
struct SocketWrapper(OwnedFd);
impl SocketWrapper {
fn new() -> Result<Self, String> {
let socket_addr = get_socket_path();
let addr = IpcSocket::<Server>::path();
let addr = Path::new(addr);

if socket_addr.exists() {
if is_daemon_running(&socket_addr)? {
if addr.exists() {
if is_daemon_running()? {
return Err(
"There is an swww-daemon instance already running on this socket!".to_string(),
);
} else {
warn!(
"socket file {} was not deleted when the previous daemon exited",
socket_addr.to_string_lossy()
addr.to_string_lossy()
);
if let Err(e) = std::fs::remove_file(&socket_addr) {
if let Err(e) = std::fs::remove_file(addr) {
return Err(format!("failed to delete previous socket: {e}"));
}
}
}

let runtime_dir = match socket_addr.parent() {
let runtime_dir = match addr.parent() {
Some(path) => path,
None => return Err("couldn't find a valid runtime directory".to_owned()),
};
Expand All @@ -555,34 +556,20 @@ impl SocketWrapper {
}
}

let socket = rustix::net::socket_with(
rustix::net::AddressFamily::UNIX,
rustix::net::SocketType::STREAM,
rustix::net::SocketFlags::CLOEXEC.union(rustix::net::SocketFlags::NONBLOCK),
None,
)
.expect("failed to create socket file descriptor");

rustix::net::bind_unix(
&socket,
&rustix::net::SocketAddrUnix::new(&socket_addr).unwrap(),
)
.unwrap();

rustix::net::listen(&socket, 0).unwrap();
let socket = IpcSocket::server().map_err(|err| err.to_string())?;

debug!("Created socket in {:?}", socket_addr);
Ok(Self(socket))
debug!("Created socket in {:?}", addr);
Ok(Self(socket.to_fd()))
}
}

impl Drop for SocketWrapper {
fn drop(&mut self) {
let socket_addr = get_socket_path();
if let Err(e) = fs::remove_file(&socket_addr) {
error!("Failed to remove socket at {socket_addr:?}: {e}");
let addr = IpcSocket::<Server>::path();
if let Err(e) = fs::remove_file(Path::new(addr)) {
error!("Failed to remove socket at {addr}: {e}");
}
info!("Removed socket at {:?}", socket_addr);
info!("Removed socket at {addr}");
}
}

Expand Down Expand Up @@ -648,16 +635,16 @@ fn make_logger(quiet: bool) {
.unwrap();
}

pub fn is_daemon_running(addr: &PathBuf) -> Result<bool, String> {
let sock = match connect_to_socket(addr, 5, 100) {
pub fn is_daemon_running() -> Result<bool, String> {
let sock = match IpcSocket::connect() {
Ok(s) => s,
// likely a connection refused; either way, this is a reliable signal there's no surviving
// daemon.
Err(_) => return Ok(false),
};

RequestSend::Ping.send(&sock)?;
let answer = Answer::receive(read_socket(&sock)?);
RequestSend::Ping.send(sock.as_fd())?;
let answer = Answer::receive(read_socket(sock.as_fd())?);
match answer {
Answer::Ping(_) => Ok(true),
_ => Err("Daemon did not return Answer::Ping, as expected".to_string()),
Expand Down

0 comments on commit 64bd080

Please sign in to comment.