use std::fs;
use std::io::{self, BufRead, BufReader, ErrorKind, Read, Write};
use std::net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream};
use std::path::Path;
use std::time::Duration;
const INTRODUCTION: Duration = Duration::from_secs(5);
const CHECK: Duration = Duration::from_secs(1);
pub struct Listener {
listener: TcpListener,
pub(crate) note: Note,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Note {
port: u16,
client: String,
server: String,
pid: u32,
}
impl Note {
fn read(path: &Path) -> io::Result<Self> {
let text = fs::read_to_string(path)?;
let invalid = || io::Error::new(ErrorKind::InvalidData, "not a Cellix endpoint");
let mut parts = text.split_whitespace();
let mut next = || parts.next().ok_or_else(invalid);
let note = Self {
port: next()?.parse().map_err(|_| invalid())?,
client: next()?.to_string(),
server: next()?.to_string(),
pid: next()?.parse().map_err(|_| invalid())?,
};
Ok(note)
}
fn line(&self) -> String {
format!(
"{} {} {} {}\n",
self.port, self.client, self.server, self.pid
)
}
pub(crate) fn is_at(&self, path: &Path) -> bool {
Self::read(path).is_ok_and(|note| note == *self)
}
fn forget(&self, path: &Path) {
if self.is_at(path) {
let _ = fs::remove_file(path);
}
}
}
fn write_private(path: &Path, bytes: &[u8]) -> io::Result<()> {
let mut options = fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
options.open(path)?.write_all(bytes)
}
pub fn bind(path: &Path) -> io::Result<Listener> {
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?;
let note = Note {
port: listener.local_addr()?.port(),
client: crate::new_token()?,
server: crate::new_token()?,
pid: std::process::id(),
};
let partial = path.with_extension(format!("{}.partial", note.pid));
write_private(&partial, note.line().as_bytes())?;
fs::rename(&partial, path)?;
Ok(Listener { listener, note })
}
fn same(given: &str, token: &str) -> bool {
given.len() == token.len()
&& given
.bytes()
.zip(token.bytes())
.fold(0, |differ, (a, b)| differ | (a ^ b))
== 0
}
fn short_line(reader: &mut impl BufRead) -> io::Result<String> {
let mut line = String::new();
reader.take(256).read_line(&mut line)?;
Ok(line.trim_end().to_string())
}
impl Listener {
pub fn incoming(&self) -> impl Iterator<Item = TcpStream> + '_ {
self.listener.incoming().flatten()
}
pub fn admit(&self, mut stream: TcpStream) -> io::Result<(BufReader<TcpStream>, TcpStream)> {
stream.set_read_timeout(Some(INTRODUCTION))?;
let mut reader = BufReader::new(stream.try_clone()?);
if !same(&short_line(&mut reader)?, &self.note.client) {
return Err(io::Error::new(ErrorKind::PermissionDenied, "wrong token"));
}
writeln!(stream, "{}", self.note.server)?;
stream.set_read_timeout(None)?;
Ok((reader, stream))
}
}
fn running(pid: u32) -> bool {
#[cfg(unix)]
{
let Ok(pid) = libc::pid_t::try_from(pid) else {
return false;
};
let found = unsafe { libc::kill(pid, 0) } == 0;
found || io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
}
#[cfg(windows)]
{
use windows_sys::Win32::Foundation::{CloseHandle, ERROR_ACCESS_DENIED, GetLastError};
use windows_sys::Win32::System::Threading::{
GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
};
const STILL_ACTIVE: u32 = 259;
unsafe {
let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
if process.is_null() {
return GetLastError() == ERROR_ACCESS_DENIED;
}
let mut code = 0;
let ok = GetExitCodeProcess(process, &mut code) != 0;
CloseHandle(process);
!ok || code == STILL_ACTIVE
}
}
#[cfg(not(any(unix, windows)))]
{
let _ = pid;
true
}
}
pub fn connect(path: &Path, wait: Duration) -> io::Result<TcpStream> {
let note = Note::read(path)?;
let gone = |why: &str| {
note.forget(path);
io::Error::new(ErrorKind::NotFound, format!("no Cellix there: {why}"))
};
if !running(note.pid) {
return Err(gone("its process has ended"));
}
let address = SocketAddr::from((Ipv4Addr::LOCALHOST, note.port));
let Ok(mut stream) = TcpStream::connect_timeout(&address, wait) else {
return Err(gone("no one listens on its port"));
};
stream.set_read_timeout(Some(wait))?;
writeln!(stream, "{}", note.client)?;
let answer = short_line(&mut BufReader::new(stream.try_clone()?));
match answer {
Ok(answer) if same(&answer, ¬e.server) => Ok(stream),
Ok(_) => Err(gone("something else holds its port")),
Err(e) => Err(e),
}
}
pub fn alive(path: &Path) -> bool {
connect(path, CHECK).is_ok()
}