use std::{
ffi::{OsStr, OsString},
fs, io,
os::unix::fs::PermissionsExt,
path::Path,
};
use tokio::net::{UnixListener, UnixStream};
use super::{endpoint::peer_is_owner, files::current_uid};
pub(crate) type LocalAccepted = UnixStream;
pub(crate) type LocalConnected = UnixStream;
pub(crate) struct LocalListener {
socket: UnixListener,
_dir: tempfile::TempDir,
uid: u32,
}
impl LocalListener {
pub(crate) fn bind_private(prefix: &str) -> io::Result<(Self, OsString)> {
let dir = tempfile::Builder::new()
.prefix(&format!("{prefix}-"))
.permissions(fs::Permissions::from_mode(0o700))
.tempdir()?;
let path = dir.path().join("s");
let socket = UnixListener::bind(&path)?;
fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?;
let listener = Self {
socket,
_dir: dir,
uid: current_uid(),
};
Ok((listener, path.into_os_string()))
}
pub(crate) async fn accept(&mut self) -> io::Result<LocalAccepted> {
loop {
let (stream, _) = self.socket.accept().await?;
if peer_is_owner(&stream, self.uid) {
return Ok(stream);
}
}
}
}
pub(crate) async fn connect_local(address: &OsStr) -> io::Result<LocalConnected> {
connect_owned_by(address, current_uid()).await
}
async fn connect_owned_by(address: &OsStr, uid: u32) -> io::Result<LocalConnected> {
let stream = UnixStream::connect(Path::new(address)).await?;
if !peer_is_owner(&stream, uid) {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!(
"{} is another user's endpoint",
Path::new(address).display()
),
));
}
Ok(stream)
}
#[cfg(test)]
#[path = "local_tests.rs"]
mod tests;