#[cfg(windows)]
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use ::tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
#[cfg(unix)]
type OwnedRead = ::tokio::net::unix::pipe::Receiver;
#[cfg(windows)]
type OwnedRead = WinOwnedRead;
pub struct ChildStdin {
pub(super) inner: InInner,
}
pub(super) enum InInner {
Tokio(::tokio::process::ChildStdin),
Owned(OwnedWrite),
}
#[cfg(unix)]
type OwnedWrite = ::tokio::net::unix::pipe::Sender;
#[cfg(windows)]
type OwnedWrite = WinOwnedWrite;
pub struct ChildStdout {
pub(super) inner: OutInner,
}
pub struct ChildStderr {
pub(super) inner: OutInner,
}
pub(super) enum OutInner {
Stdout(::tokio::process::ChildStdout),
Stderr(::tokio::process::ChildStderr),
Owned(OwnedRead),
}
#[cfg(unix)]
pub(super) type OwnedStd = crate::child::ParentEnd;
#[cfg(windows)]
#[derive(Debug)]
pub(super) enum OwnedStd {
Read(WinOwnedRead),
Write(WinOwnedWrite),
}
impl AsyncWrite for ChildStdin {
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<std::io::Result<usize>> {
match &mut self.inner {
InInner::Tokio(s) => Pin::new(s).poll_write(cx, buf),
InInner::Owned(s) => Pin::new(s).poll_write(cx, buf),
}
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
match &mut self.inner {
InInner::Tokio(s) => Pin::new(s).poll_flush(cx),
InInner::Owned(s) => Pin::new(s).poll_flush(cx),
}
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
match &mut self.inner {
InInner::Tokio(s) => Pin::new(s).poll_shutdown(cx),
InInner::Owned(s) => Pin::new(s).poll_shutdown(cx),
}
}
}
impl OutInner {
fn poll_read_inner(&mut self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
match self {
OutInner::Stdout(s) => Pin::new(s).poll_read(cx, buf),
OutInner::Stderr(s) => Pin::new(s).poll_read(cx, buf),
OutInner::Owned(s) => Pin::new(s).poll_read(cx, buf),
}
}
}
impl AsyncRead for ChildStdout {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
self.inner.poll_read_inner(cx, buf)
}
}
impl AsyncRead for ChildStderr {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
self.inner.poll_read_inner(cx, buf)
}
}
impl std::fmt::Debug for ChildStdin {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ChildStdin").finish_non_exhaustive()
}
}
impl std::fmt::Debug for ChildStdout {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ChildStdout").finish_non_exhaustive()
}
}
impl std::fmt::Debug for ChildStderr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ChildStderr").finish_non_exhaustive()
}
}
#[cfg(windows)]
pub(crate) fn overlapped_out_pipe() -> Result<
(
::tokio::net::windows::named_pipe::NamedPipeServer,
std::os::windows::io::OwnedHandle,
),
crate::error::Error,
> {
overlapped_pipe(false)
}
#[cfg(windows)]
pub(crate) fn overlapped_in_pipe() -> Result<
(
::tokio::net::windows::named_pipe::NamedPipeServer,
std::os::windows::io::OwnedHandle,
),
crate::error::Error,
> {
overlapped_pipe(true)
}
#[cfg(windows)]
fn overlapped_pipe(
parent_writes: bool,
) -> Result<
(
::tokio::net::windows::named_pipe::NamedPipeServer,
std::os::windows::io::OwnedHandle,
),
crate::error::Error,
> {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let mut r = [0u8; 8];
getrandom::fill(&mut r).map_err(|e| crate::error::Error::Io(std::io::Error::other(e)))?;
let name = format!(
r"\\.\pipe\cosca.{}.{}.{:016x}",
std::process::id(),
COUNTER.fetch_add(1, Ordering::Relaxed),
u64::from_ne_bytes(r)
);
overlapped_pipe_named(&name, parent_writes)
}
#[cfg(windows)]
pub(crate) fn overlapped_pipe_named(
name: &str,
parent_writes: bool,
) -> Result<
(
::tokio::net::windows::named_pipe::NamedPipeServer,
std::os::windows::io::OwnedHandle,
),
crate::error::Error,
> {
use ::tokio::net::windows::named_pipe::ServerOptions;
let server = ServerOptions::new()
.access_inbound(!parent_writes)
.access_outbound(parent_writes)
.first_pipe_instance(true) .reject_remote_clients(true)
.max_instances(1)
.create(name)
.map_err(|e| {
if e.kind() == std::io::ErrorKind::PermissionDenied {
log::warn!("merge-target pipe name {name} already claimed (squat suspected) or ACL-denied: {e}");
} else {
log::debug!("merge-target pipe creation failed for {name}: {e}");
}
crate::error::Error::Io(std::io::Error::new(
e.kind(),
format!(
"creating merge-target pipe {name}: {e} (PermissionDenied means the name is already claimed — never attached — or creation is denied)"
),
))
})?;
let client = open_client_slot(name, parent_writes)?;
Ok((server, client))
}
#[cfg(windows)]
pub(crate) fn open_client_slot(
name: &str,
parent_writes: bool,
) -> Result<std::os::windows::io::OwnedHandle, crate::error::Error> {
std::fs::OpenOptions::new()
.read(parent_writes)
.write(!parent_writes)
.open(name)
.map(std::os::windows::io::OwnedHandle::from)
.map_err(|e| {
log::warn!("merge-target pipe {name}: client-slot open failed ({e}); slot theft suspected");
crate::error::Error::Io(e)
})
}
#[cfg(windows)]
pub(crate) fn connect_task(
server: ::tokio::net::windows::named_pipe::NamedPipeServer,
) -> ::tokio::task::JoinHandle<std::io::Result<::tokio::net::windows::named_pipe::NamedPipeServer>> {
::tokio::spawn(async move { server.connect().await.map(|()| server) })
}
#[cfg(windows)]
#[derive(Debug)]
pub(super) enum ConnectingPipe {
Connecting(::tokio::task::JoinHandle<std::io::Result<::tokio::net::windows::named_pipe::NamedPipeServer>>),
Ready(::tokio::net::windows::named_pipe::NamedPipeServer),
Failed(std::io::ErrorKind, String),
}
#[cfg(windows)]
impl ConnectingPipe {
fn poll_ready_server(
&mut self,
cx: &mut Context<'_>,
) -> Poll<std::io::Result<&mut ::tokio::net::windows::named_pipe::NamedPipeServer>> {
loop {
match self {
ConnectingPipe::Connecting(handle) => match Pin::new(handle).poll(cx) {
Poll::Ready(Ok(Ok(server))) => *self = ConnectingPipe::Ready(server),
Poll::Ready(Ok(Err(e))) => {
*self = ConnectingPipe::Failed(e.kind(), e.to_string());
return Poll::Ready(Err(e));
}
Poll::Ready(Err(join)) => {
let e = std::io::Error::other(join);
*self = ConnectingPipe::Failed(e.kind(), e.to_string());
return Poll::Ready(Err(e));
}
Poll::Pending => return Poll::Pending,
},
ConnectingPipe::Ready(server) => return Poll::Ready(Ok(server)),
ConnectingPipe::Failed(kind, msg) => return Poll::Ready(Err(std::io::Error::new(*kind, msg.clone()))),
}
}
}
}
#[cfg(windows)]
#[derive(Debug)]
pub(super) struct WinOwnedRead(pub(super) ConnectingPipe);
#[cfg(windows)]
impl WinOwnedRead {
fn poll_read_inner(&mut self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
let server = std::task::ready!(self.0.poll_ready_server(cx))?;
Pin::new(server).poll_read(cx, buf)
}
}
#[cfg(windows)]
impl AsyncRead for WinOwnedRead {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
self.poll_read_inner(cx, buf)
}
}
#[cfg(windows)]
#[derive(Debug)]
pub(super) struct WinOwnedWrite(pub(super) ConnectingPipe);
#[cfg(windows)]
impl WinOwnedWrite {
fn poll_write_inner(&mut self, cx: &mut Context<'_>, buf: &[u8]) -> Poll<std::io::Result<usize>> {
let server = std::task::ready!(self.0.poll_ready_server(cx))?;
Pin::new(server).poll_write(cx, buf)
}
fn poll_flush_inner(&mut self, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
let server = std::task::ready!(self.0.poll_ready_server(cx))?;
Pin::new(server).poll_flush(cx)
}
fn poll_shutdown_inner(&mut self, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
let server = std::task::ready!(self.0.poll_ready_server(cx))?;
Pin::new(server).poll_shutdown(cx)
}
}
#[cfg(windows)]
impl AsyncWrite for WinOwnedWrite {
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<std::io::Result<usize>> {
self.poll_write_inner(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
self.poll_flush_inner(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
self.poll_shutdown_inner(cx)
}
}
#[cfg(windows)]
pub(crate) fn owned_overlapped_pipe(
dir: crate::stdio::Direction,
) -> Result<(std::os::windows::io::OwnedHandle, OwnedStd), crate::error::Error> {
use crate::stdio::Direction;
match dir {
Direction::In => {
let (server, client) = overlapped_in_pipe()?;
let connecting = ConnectingPipe::Connecting(connect_task(server));
Ok((client, OwnedStd::Write(WinOwnedWrite(connecting))))
}
Direction::Out => {
let (server, client) = overlapped_out_pipe()?;
let connecting = ConnectingPipe::Connecting(connect_task(server));
Ok((client, OwnedStd::Read(WinOwnedRead(connecting))))
}
}
}
#[cfg(test)]
#[path = "stdio_tests.rs"]
mod stdio_tests;