use super::super::{CarriedFds, CarriedSheep, Handover};
use super::rehearse_blob::refuse_repeated_fds;
use crate::sys;
use std::fs::File;
use std::io;
use std::os::fd::{OwnedFd, RawFd};
use tokio::net::unix::pipe;
#[derive(Debug)]
pub struct Adopted {
pub listener: tokio::net::UnixListener,
pub sheep: Vec<AdoptedSheep>,
pub pidfile: File,
}
#[derive(Debug)]
pub struct AdoptedSheep {
pub carried: CarriedSheep,
pub out_pipe: Option<pipe::Receiver>,
pub err_pipe: Option<pipe::Receiver>,
pub out_log: Option<tokio::fs::File>,
pub err_log: Option<tokio::fs::File>,
pub stdin_pipe: Option<pipe::Sender>,
pub channel: Option<tokio::net::UnixStream>,
}
#[track_caller]
pub fn adopt(blob: &Handover) -> io::Result<Adopted> {
refuse_repeated_fds(blob)?;
let listener = adopt_listener(blob.listener_fd)?;
let sheep = blob
.sheep
.iter()
.map(adopt_sheep)
.collect::<io::Result<Vec<_>>>()?;
let pidfile = adopt_fd(blob.pidfile_fd, "the pidfile lock")?;
Ok(Adopted {
listener,
sheep,
pidfile,
})
}
pub(super) fn adopt_fd(fd: RawFd, what: &str) -> io::Result<File> {
sys::adopt_handover_fd(fd).map_err(|error| {
io::Error::new(
io::ErrorKind::InvalidInput,
format!("{what} did not survive the handover: {error}"),
)
})
}
pub(super) fn adopt_listener(fd: RawFd) -> io::Result<tokio::net::UnixListener> {
let file = adopt_fd(fd, "the control listener")?;
let listener = std::os::unix::net::UnixListener::from(OwnedFd::from(file));
listener.set_nonblocking(true)?;
tokio::net::UnixListener::from_std(listener)
}
fn adopt_sheep(carried: &CarriedSheep) -> io::Result<AdoptedSheep> {
let CarriedFds {
out_pipe,
err_pipe,
out_log,
err_log,
stdin,
channel,
} = carried.fds;
let name = &carried.name;
Ok(AdoptedSheep {
out_pipe: adopt_pipe(out_pipe, name, "stdout")?,
err_pipe: adopt_pipe(err_pipe, name, "stderr")?,
out_log: adopt_log(out_log, name, "stdout")?,
err_log: adopt_log(err_log, name, "stderr")?,
stdin_pipe: adopt_stdin(stdin, name)?,
channel: adopt_channel(channel, name)?,
carried: carried.clone(),
})
}
pub(super) fn adopt_channel(
fd: Option<RawFd>,
sheep: &str,
) -> io::Result<Option<tokio::net::UnixStream>> {
let Some(fd) = fd else { return Ok(None) };
let file = adopt_fd(fd, &format!("sheep '{sheep}' shepherd channel"))?;
let socket = std::os::unix::net::UnixStream::from(OwnedFd::from(file));
socket.peer_addr().map_err(|error| {
io::Error::new(
error.kind(),
format!("sheep '{sheep}' shepherd channel is not a connected socket: {error}"),
)
})?;
socket.set_nonblocking(true)?;
tokio::net::UnixStream::from_std(socket).map(Some)
}
pub(super) fn adopt_pipe(
fd: Option<RawFd>,
sheep: &str,
stream: &str,
) -> io::Result<Option<pipe::Receiver>> {
let Some(fd) = fd else { return Ok(None) };
let file = adopt_fd(fd, &format!("sheep '{sheep}' {stream} pipe"))?;
pipe::Receiver::from_file(file).map(Some).map_err(|error| {
io::Error::new(
error.kind(),
format!("sheep '{sheep}' {stream} pipe is not a readable pipe: {error}"),
)
})
}
pub(super) fn adopt_stdin(fd: Option<RawFd>, sheep: &str) -> io::Result<Option<pipe::Sender>> {
let Some(fd) = fd else { return Ok(None) };
let file = adopt_fd(fd, &format!("sheep '{sheep}' stdin pipe"))?;
pipe::Sender::from_file(file).map(Some).map_err(|error| {
io::Error::new(
error.kind(),
format!("sheep '{sheep}' stdin is not a writable pipe: {error}"),
)
})
}
pub(super) fn adopt_log(
fd: Option<RawFd>,
sheep: &str,
stream: &str,
) -> io::Result<Option<tokio::fs::File>> {
let Some(fd) = fd else { return Ok(None) };
let file = adopt_fd(fd, &format!("sheep '{sheep}' {stream} log"))?;
Ok(Some(tokio::fs::File::from_std(file)))
}
#[cfg(test)]
mod tests {
use super::super::super::CarriedFds;
use std::os::fd::IntoRawFd as _;
use std::time::Duration;
use tokio::io::{AsyncSeekExt as _, AsyncWriteExt as _};
use super::super::testing::*;
use super::*;
#[tokio::test]
async fn an_adopted_listener_accepts() {
let dir = tempfile::tempdir().unwrap();
let socket = dir.path().join("shep.sock");
let blob = blob_with(&socket, Vec::new());
let adopted = adopt(&blob).unwrap();
let listener = adopted.listener;
let accept = tokio::spawn(async move { listener.accept().await });
let _client = tokio::net::UnixStream::connect(&socket).await.unwrap();
tokio::time::timeout(Duration::from_secs(10), accept)
.await
.expect("the adopted listener must accept")
.unwrap()
.expect("the adopted listener accepts");
}
#[tokio::test]
async fn a_blob_naming_one_descriptor_twice_is_refused() {
let dir = tempfile::tempdir().unwrap();
let socket = dir.path().join("shep.sock");
let mut blob = blob_with(
&socket,
vec![carried(CarriedFds {
out_pipe: None,
err_pipe: None,
out_log: None,
err_log: None,
stdin: None,
channel: None,
})],
);
blob.sheep[0].fds.out_log = Some(blob.listener_fd);
let err = adopt(&blob).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput, "{err}");
assert!(
err.to_string().contains("more than once"),
"the refusal must say what is wrong with the blob: {err}"
);
}
#[tokio::test]
async fn an_adopted_log_handle_still_appends() {
let dir = tempfile::tempdir().unwrap();
let socket = dir.path().join("shep.sock");
let log = dir.path().join("web-out.log");
std::fs::write(&log, b"first\n").unwrap();
let handle = std::fs::OpenOptions::new().append(true).open(&log).unwrap();
let blob = blob_with(
&socket,
vec![carried(CarriedFds {
out_pipe: None,
err_pipe: None,
out_log: Some(handle.into_raw_fd()),
err_log: None,
stdin: None,
channel: None,
})],
);
let mut adopted = adopt(&blob).unwrap();
let mut out = adopted.sheep[0].out_log.take().expect("an adopted log");
out.seek(std::io::SeekFrom::Start(0)).await.unwrap();
out.write_all(b"second\n").await.unwrap();
out.flush().await.unwrap();
assert_eq!(
std::fs::read_to_string(&log).unwrap(),
"first\nsecond\n",
"a write at offset 0 overwrote the file, so O_APPEND was lost"
);
}
#[tokio::test]
async fn a_blob_naming_a_descriptor_that_is_not_open_fails_loudly() {
let dir = tempfile::tempdir().unwrap();
let socket = dir.path().join("shep.sock");
let blob = blob_with(
&socket,
vec![carried(CarriedFds {
out_pipe: Some(NEVER_OPEN),
err_pipe: None,
out_log: None,
err_log: None,
stdin: None,
channel: None,
})],
);
let err = adopt(&blob).expect_err("a descriptor that is not open must refuse");
let text = err.to_string();
assert!(
text.contains("web"),
"the refusal must name the sheep: {text}"
);
assert!(
text.contains("stdout"),
"the refusal must name the stream: {text}"
);
}
#[tokio::test]
async fn a_refused_rehydrate_leaves_the_pidfile_lock_held() {
let dir = tempfile::tempdir().unwrap();
let socket = dir.path().join("shep.sock");
let blob = blob_with(
&socket,
vec![carried(CarriedFds {
out_pipe: Some(NEVER_OPEN),
err_pipe: None,
out_log: None,
err_log: None,
stdin: None,
channel: None,
})],
);
let pidfile_fd = blob.pidfile_fd;
adopt(&blob).expect_err("a descriptor that is not open must refuse");
assert!(
nix::fcntl::fcntl(pidfile_fd, nix::fcntl::FcntlArg::F_GETFD).is_ok(),
"the pidfile descriptor was closed by a failed rehydrate"
);
}
#[tokio::test]
async fn an_adopted_pipe_reads_what_was_written_before_the_adoption() {
let dir = tempfile::tempdir().unwrap();
let socket = dir.path().join("shep.sock");
let (reader, mut writer) = std::io::pipe().unwrap();
std::io::Write::write_all(&mut writer, b"a line\n").unwrap();
drop(writer);
let blob = blob_with(
&socket,
vec![carried(CarriedFds {
out_pipe: Some(reader.into_raw_fd()),
err_pipe: None,
out_log: None,
err_log: None,
stdin: None,
channel: None,
})],
);
let mut adopted = adopt(&blob).unwrap();
let out = adopted.sheep[0].out_pipe.take().expect("an adopted pipe");
let mut lines = tokio::io::AsyncBufReadExt::lines(tokio::io::BufReader::new(out));
let line = tokio::time::timeout(Duration::from_secs(10), lines.next_line())
.await
.expect("the adopted pipe must produce the line written before it")
.unwrap();
assert_eq!(line.as_deref(), Some("a line"));
}
#[tokio::test]
async fn an_adopted_stdin_pipe_writes_to_the_end_the_child_reads() {
let dir = tempfile::tempdir().unwrap();
let socket = dir.path().join("shep.sock");
let (mut child_end, daemon_end) = std::io::pipe().unwrap();
let blob = blob_with(
&socket,
vec![carried(CarriedFds {
out_pipe: None,
err_pipe: None,
out_log: None,
err_log: None,
stdin: Some(daemon_end.into_raw_fd()),
channel: None,
})],
);
let mut adopted = adopt(&blob).unwrap();
let mut stdin = adopted.sheep[0]
.stdin_pipe
.take()
.expect("an adopted stdin pipe");
stdin.write_all(b"whisper\n").await.unwrap();
stdin.flush().await.unwrap();
let mut buf = [0_u8; 8];
std::io::Read::read_exact(&mut child_end, &mut buf).expect("the child end must read");
assert_eq!(&buf, b"whisper\n");
}
#[tokio::test]
async fn a_pipe_read_end_offered_as_stdin_is_refused() {
let dir = tempfile::tempdir().unwrap();
let socket = dir.path().join("shep.sock");
let (reader, _writer) = std::io::pipe().unwrap();
let blob = blob_with(
&socket,
vec![carried(CarriedFds {
out_pipe: None,
err_pipe: None,
out_log: None,
err_log: None,
stdin: Some(reader.into_raw_fd()),
channel: None,
})],
);
let err = adopt(&blob).expect_err("a read end is not something to write to");
let text = err.to_string();
assert!(
text.contains("web"),
"the refusal must name the sheep: {text}"
);
assert!(
text.contains("stdin"),
"the refusal must name what could not be adopted: {text}"
);
}
#[tokio::test]
async fn a_log_file_offered_as_a_pipe_is_refused() {
let dir = tempfile::tempdir().unwrap();
let socket = dir.path().join("shep.sock");
let file = tempfile::tempfile().unwrap();
let blob = blob_with(
&socket,
vec![carried(CarriedFds {
out_pipe: Some(file.into_raw_fd()),
err_pipe: None,
out_log: None,
err_log: None,
stdin: None,
channel: None,
})],
);
let err = adopt(&blob).expect_err("a file is not a pipe");
assert!(err.to_string().contains("web"), "{err}");
}
#[tokio::test]
async fn an_adopted_channel_carries_both_directions() {
use tokio::io::AsyncBufReadExt as _;
let dir = tempfile::tempdir().unwrap();
let socket = dir.path().join("shep.sock");
let (daemon_end, child_end) = std::os::unix::net::UnixStream::pair().unwrap();
child_end.set_nonblocking(true).unwrap();
let child_end = tokio::net::UnixStream::from_std(child_end).unwrap();
let blob = blob_with(
&socket,
vec![carried(CarriedFds {
out_pipe: None,
err_pipe: None,
out_log: None,
err_log: None,
stdin: None,
channel: Some(daemon_end.into_raw_fd()),
})],
);
let mut adopted = adopt(&blob).unwrap();
let channel = adopted.sheep[0]
.channel
.take()
.expect("an adopted shepherd channel");
let (read_half, mut write_half) = tokio::io::split(channel);
let (child_read, mut child_write) = tokio::io::split(child_end);
let mut child = tokio::io::BufReader::new(child_read);
write_half
.write_all(b"{\"kind\":\"shutdown\"}\n")
.await
.unwrap();
let mut line = String::new();
child
.read_line(&mut line)
.await
.expect("the child end must read");
assert_eq!(line, "{\"kind\":\"shutdown\"}\n");
child_write
.write_all(b"{\"kind\":\"ready\"}\n")
.await
.unwrap();
let mut back = String::new();
tokio::io::BufReader::new(read_half)
.read_line(&mut back)
.await
.expect("the daemon end must read");
assert_eq!(back, "{\"kind\":\"ready\"}\n");
}
#[tokio::test]
async fn a_file_offered_as_a_shepherd_channel_is_refused() {
let dir = tempfile::tempdir().unwrap();
let socket = dir.path().join("shep.sock");
let file = tempfile::tempfile().unwrap();
let blob = blob_with(
&socket,
vec![carried(CarriedFds {
out_pipe: None,
err_pipe: None,
out_log: None,
err_log: None,
stdin: None,
channel: Some(file.into_raw_fd()),
})],
);
let err = adopt(&blob).expect_err("a file is not a connected socket");
let text = err.to_string();
assert!(
text.contains("web"),
"the refusal must name the sheep: {text}"
);
assert!(
text.contains("shepherd channel"),
"the refusal must name what could not be adopted: {text}"
);
}
#[tokio::test]
async fn a_listening_socket_offered_as_a_shepherd_channel_is_refused() {
let dir = tempfile::tempdir().unwrap();
let socket = dir.path().join("shep.sock");
let other = dir.path().join("other.sock");
let listening = std::os::unix::net::UnixListener::bind(&other).unwrap();
let blob = blob_with(
&socket,
vec![carried(CarriedFds {
out_pipe: None,
err_pipe: None,
out_log: None,
err_log: None,
stdin: None,
channel: Some(listening.into_raw_fd()),
})],
);
let err = adopt(&blob).expect_err("a listener is not a connected socket");
assert!(
err.to_string().contains("shepherd channel"),
"the refusal must name what could not be adopted: {err}"
);
}
}