use crate::protocol::Frame;
use crate::protocol::stream;
use crate::sync::{Executor, ExecutorOptions};
use anyhow::Result;
use std::path::PathBuf;
pub async fn execute(options: &ExecutorOptions) -> Result<()> {
#[cfg(unix)]
make_stderr_non_blocking();
crate::platform::fs::enlarge_pipe(&std::io::stdin());
crate::platform::fs::enlarge_pipe(&std::io::stdout());
#[cfg(unix)]
let (send, recv) = (
match fdio::FdWrite::stdout() {
Ok(w) => Box::new(w) as Box<dyn tokio::io::AsyncWrite + Unpin + Send>,
Err(_) => Box::new(tokio::io::stdout()),
},
match fdio::FdRead::stdin() {
Ok(r) => Box::new(r) as Box<dyn tokio::io::AsyncRead + Unpin + Send>,
Err(_) => Box::new(tokio::io::stdin()),
},
);
#[cfg(not(unix))]
let (send, recv) = (
Box::new(tokio::io::stdout()) as Box<dyn tokio::io::AsyncWrite + Unpin + Send>,
Box::new(tokio::io::stdin()) as Box<dyn tokio::io::AsyncRead + Unpin + Send>,
);
let root = PathBuf::from(".");
let mut executor = Executor::new(send, recv);
let stats = executor.serve(&root, options).await;
drop(executor);
let stats = match stats {
Ok(stats) => stats,
Err(e) => {
let mut out = error_stdout();
let _ = tokio::time::timeout(
std::time::Duration::from_secs(2),
stream::send_frame(
&mut out,
&Frame::Error {
message: e.to_string(),
},
),
)
.await;
return Err(e.into());
}
};
if !options.quiet {
use std::io::Write;
let line = format!(
"Synced {} files, {} bytes",
stats.files_received + stats.files_sent,
stats.bytes_transferred
);
let _ = std::io::stderr().write_all(line.as_bytes());
let _ = std::io::stderr().write_all(b"\n");
}
Ok(())
}
#[cfg(unix)]
fn make_stderr_non_blocking() {
let flags = unsafe { libc::fcntl(libc::STDERR_FILENO, libc::F_GETFL) };
if flags >= 0 {
unsafe { libc::fcntl(libc::STDERR_FILENO, libc::F_SETFL, flags | libc::O_NONBLOCK) };
}
}
#[cfg(unix)]
fn error_stdout() -> Box<dyn tokio::io::AsyncWrite + Unpin + Send> {
match fdio::FdWrite::stdout() {
Ok(w) => Box::new(w) as Box<dyn tokio::io::AsyncWrite + Unpin + Send>,
Err(_) => Box::new(tokio::io::stdout()),
}
}
#[cfg(not(unix))]
fn error_stdout() -> Box<dyn tokio::io::AsyncWrite + Unpin + Send> {
Box::new(tokio::io::stdout())
}
#[cfg(unix)]
mod fdio {
use std::io;
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::io::unix::AsyncFd;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
fn dup_nonblocking(fd: RawFd) -> io::Result<OwnedFd> {
let duped = unsafe { libc::dup(fd) };
if duped < 0 {
return Err(io::Error::last_os_error());
}
let owned = unsafe { OwnedFd::from_raw_fd(duped) };
let flags = unsafe { libc::fcntl(owned.as_raw_fd(), libc::F_GETFL) };
if flags < 0
|| unsafe { libc::fcntl(owned.as_raw_fd(), libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0
{
return Err(io::Error::last_os_error());
}
Ok(owned)
}
pub(crate) struct FdRead {
fd: AsyncFd<OwnedFd>,
}
impl FdRead {
pub(crate) fn stdin() -> io::Result<Self> {
Ok(Self {
fd: AsyncFd::new(dup_nonblocking(0)?)?,
})
}
}
impl AsyncRead for FdRead {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
loop {
let mut guard = std::task::ready!(self.fd.poll_read_ready(cx))?;
if let Ok(Ok(n)) = guard.try_io(|fd| {
let n = unsafe {
libc::read(
fd.as_raw_fd(),
buf.unfilled_mut().as_mut_ptr().cast(),
buf.remaining(),
)
};
if n < 0 {
Err(io::Error::last_os_error())
} else {
Ok(usize::try_from(n).map_err(|_| io::Error::other("read length overflow"))?)
}
}) {
if n == 0 {
return Poll::Ready(Ok(())); }
buf.advance(n);
return Poll::Ready(Ok(()));
}
}
}
}
pub(crate) struct FdWrite {
fd: AsyncFd<OwnedFd>,
}
impl FdWrite {
pub(crate) fn stdout() -> io::Result<Self> {
Ok(Self {
fd: AsyncFd::new(dup_nonblocking(1)?)?,
})
}
}
impl AsyncWrite for FdWrite {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
loop {
let mut guard = std::task::ready!(self.fd.poll_write_ready(cx))?;
if let Ok(Ok(n)) = guard.try_io(|fd| {
let n = unsafe { libc::write(fd.as_raw_fd(), buf.as_ptr().cast(), buf.len()) };
if n < 0 {
Err(io::Error::last_os_error())
} else {
Ok(usize::try_from(n).map_err(|_| io::Error::other("write length overflow"))?)
}
}) {
return Poll::Ready(Ok(n));
}
}
}
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(Ok(()))
}
}
}