use kevy_resp::{Reply, encode_command};
use kevy_resp_client::ReplyReadBuf;
use std::io::{self, Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::os::fd::{AsRawFd, RawFd};
use std::os::unix::net::UnixStream;
use std::time::Duration;
#[derive(Debug)]
pub(crate) enum LinkError {
Eof,
Io(io::ErrorKind, String),
Protocol(Option<u8>),
}
impl LinkError {
pub(crate) fn text(&self) -> String {
match self {
LinkError::Eof => "Server closed the connection".to_string(),
LinkError::Io(_, text) => text.clone(),
LinkError::Protocol(Some(byte)) => {
let shown = String::from_utf8_lossy(&super::repr::repr(&[*byte])).into_owned();
format!("Protocol error, got {shown} as reply type byte")
}
LinkError::Protocol(None) => "Protocol error".to_string(),
}
}
pub(crate) fn is_reconnectable(&self) -> bool {
matches!(self, LinkError::Eof)
|| matches!(self, LinkError::Io(k, _) if matches!(k, io::ErrorKind::ConnectionReset | io::ErrorKind::BrokenPipe))
}
}
pub(crate) type Parsed = (Reply, Vec<Vec<u8>>);
enum Stream {
Tcp(TcpStream),
Unix(UnixStream),
Secure(Box<kevy_resp_client::SecureStream>),
}
pub(crate) struct Conn {
stream: Stream,
buf: ReplyReadBuf,
chunk: Box<[u8]>,
}
pub(crate) fn strerror(e: &io::Error) -> String {
if e.kind() == io::ErrorKind::TimedOut && e.raw_os_error().is_none() {
return "Connection timed out".to_string();
}
let text = e.to_string();
let text = text.strip_prefix("failed to lookup address information: ").unwrap_or(&text);
match text.rfind(" (os error ") {
Some(cut) => text[..cut].to_string(),
None => text.to_string(),
}
}
impl Conn {
pub(crate) fn tcp(host: &[u8], port: i32, timeout: Option<f64>) -> Result<Conn, String> {
Ok(Conn::over(Stream::Tcp(dial_tcp(host, port as u16, timeout)?)))
}
pub(crate) fn secure(
host: &[u8],
port: i32,
timeout: Option<f64>,
target: &super::opts::SecureTarget,
) -> Result<Conn, String> {
let me = match &target.client_key_file {
Some(path) => Some(
kevy_resp_client::load_client_key(path)
.map_err(|e| format!("client key {}: {}", path.display(), strerror(&e)))?,
),
None => None,
};
let tcp = dial_tcp(host, port as u16, timeout)?;
let s = kevy_resp_client::SecureStream::handshake(tcp, target.server_key, me.as_ref())
.map_err(|e| strerror(&e))?;
Ok(Conn::over(Stream::Secure(Box::new(s))))
}
pub(crate) fn unix(path: &[u8]) -> Result<Conn, String> {
use std::os::unix::ffi::OsStrExt;
let path = std::ffi::OsStr::from_bytes(path);
UnixStream::connect(path).map(|s| Conn::over(Stream::Unix(s))).map_err(|e| strerror(&e))
}
fn over(stream: Stream) -> Conn {
Conn {
stream,
buf: ReplyReadBuf::with_capacity(16 * 1024),
chunk: vec![0; 16 * 1024].into_boxed_slice(),
}
}
pub(crate) fn send(&mut self, argv: &[Vec<u8>]) -> Result<(), LinkError> {
let mut frame = Vec::new();
encode_command(&mut frame, argv);
self.write_raw(&frame)
}
pub(crate) fn request(&mut self, argv: &[&[u8]]) -> Result<Reply, LinkError> {
let mut replies = self.pipeline(&[argv.to_vec()])?;
replies.pop().ok_or(LinkError::Eof)
}
pub(crate) fn pipeline(&mut self, commands: &[Vec<&[u8]>]) -> Result<Vec<Reply>, LinkError> {
let mut frame = Vec::new();
for argv in commands {
kevy_resp::encode_command_borrowed(&mut frame, argv);
}
self.write_raw(&frame)?;
let mut replies = Vec::with_capacity(commands.len());
while replies.len() < commands.len() {
match self.read_reply()? {
(Reply::Push(_), _) => {}
(reply, _) => replies.push(reply),
}
}
Ok(replies)
}
pub(crate) fn write_raw(&mut self, bytes: &[u8]) -> Result<(), LinkError> {
let r = match &mut self.stream {
Stream::Tcp(s) => s.write_all(bytes),
Stream::Unix(s) => s.write_all(bytes),
Stream::Secure(s) => s.write_all(bytes),
};
r.map_err(|e| LinkError::Io(e.kind(), strerror(&e)))
}
pub(crate) fn read_reply(&mut self) -> Result<Parsed, LinkError> {
loop {
if let Some(parsed) = self.buffered_reply()? {
return Ok(parsed);
}
let n = self.read_stream().map_err(|e| LinkError::Io(e.kind(), strerror(&e)))?;
if n == 0 {
return Err(LinkError::Eof);
}
}
}
fn read_stream(&mut self) -> io::Result<usize> {
let n = match &mut self.stream {
Stream::Tcp(s) => s.read(&mut self.chunk)?,
Stream::Unix(s) => s.read(&mut self.chunk)?,
Stream::Secure(s) => s.read(&mut self.chunk)?,
};
self.buf.extend(&self.chunk[..n]);
if let Stream::Secure(s) = &mut self.stream {
let mut more = vec![0u8; s.buffered()];
s.read_exact(&mut more)?;
self.buf.extend(&more);
}
Ok(n)
}
pub(crate) fn buffered_reply(&mut self) -> Result<Option<Parsed>, LinkError> {
match self.buf.parse_next_keeping_double_text() {
Ok(parsed) => Ok(parsed.map(|(reply, _, texts)| (reply, texts))),
Err(_) => {
const TYPE_BYTES: &[u8] = b"+-:$*%~,#=(_>!|";
let first = self.buf.pending().first().copied();
Err(LinkError::Protocol(first.filter(|b| !TYPE_BYTES.contains(b))))
}
}
}
pub(crate) fn read_raw(&mut self, into: &mut [u8]) -> Result<usize, LinkError> {
let n = match &mut self.stream {
Stream::Tcp(s) => s.read(into),
Stream::Unix(s) => s.read(into),
Stream::Secure(s) => s.read(into),
}
.map_err(|e| LinkError::Io(e.kind(), strerror(&e)))?;
if n == 0 { Err(LinkError::Eof) } else { Ok(n) }
}
pub(crate) fn unread(&mut self, bytes: &[u8]) {
self.buf.extend(bytes);
}
pub(crate) fn writer(&self) -> io::Result<Box<dyn Write + Send>> {
Ok(match &self.stream {
Stream::Tcp(s) => Box::new(s.try_clone()?),
Stream::Unix(s) => Box::new(s.try_clone()?),
Stream::Secure(s) => Box::new(s.writer()?),
})
}
pub(crate) fn set_read_timeout(&self, limit: Option<Duration>) -> io::Result<()> {
match &self.stream {
Stream::Tcp(s) => s.set_read_timeout(limit),
Stream::Unix(s) => s.set_read_timeout(limit),
Stream::Secure(s) => s.socket().set_read_timeout(limit),
}
}
pub(crate) fn fd(&self) -> RawFd {
match &self.stream {
Stream::Tcp(s) => s.as_raw_fd(),
Stream::Unix(s) => s.as_raw_fd(),
Stream::Secure(s) => s.socket().as_raw_fd(),
}
}
}
fn dial_tcp(host: &[u8], port: u16, timeout: Option<f64>) -> Result<TcpStream, String> {
let host = String::from_utf8_lossy(host).into_owned();
let stream = match timeout {
None => TcpStream::connect((host.as_str(), port)).map_err(|e| strerror(&e))?,
Some(secs) => connect_with_timeout(&host, port, Duration::from_secs_f64(secs))?,
};
let _ = stream.set_nodelay(true); Ok(stream)
}
fn connect_with_timeout(host: &str, port: u16, timeout: Duration) -> Result<TcpStream, String> {
let addrs = (host, port).to_socket_addrs().map_err(|e| strerror(&e))?;
let mut last = String::from("Connection refused");
for addr in addrs {
match TcpStream::connect_timeout(&addr, timeout) {
Ok(s) => return Ok(s),
Err(e) => last = strerror(&e),
}
}
Err(last)
}
impl crate::link::Link for Conn {
fn request_borrowed(&mut self, argv: &[&[u8]]) -> std::io::Result<Reply> {
self.request(argv).map_err(link_error)
}
fn pipeline_raw(&mut self, raw: &[u8], n: usize) -> std::io::Result<Vec<Reply>> {
self.write_raw(raw).map_err(link_error)?;
let mut replies = Vec::with_capacity(n);
while replies.len() < n {
match self.read_reply().map_err(link_error)? {
(Reply::Push(_), _) => {}
(reply, _) => replies.push(reply),
}
}
Ok(replies)
}
}
fn link_error(e: LinkError) -> std::io::Error {
match e {
LinkError::Io(kind, text) => std::io::Error::new(kind, text),
LinkError::Protocol(_) => std::io::Error::new(std::io::ErrorKind::InvalidData, e.text()),
LinkError::Eof => std::io::Error::new(std::io::ErrorKind::UnexpectedEof, e.text()),
}
}
#[cfg(test)]
mod tests {
use super::{LinkError, link_error};
use std::io::ErrorKind;
#[test]
fn a_lost_link_keeps_its_kind_when_a_tool_reads_it() {
let io = link_error(LinkError::Io(ErrorKind::ConnectionReset, "Connection reset".into()));
assert_eq!(
(io.kind(), io.to_string()),
(ErrorKind::ConnectionReset, "Connection reset".into())
);
assert_eq!(link_error(LinkError::Eof).kind(), ErrorKind::UnexpectedEof);
assert_eq!(link_error(LinkError::Protocol(Some(b'x'))).kind(), ErrorKind::InvalidData);
}
fn secure_conn_answering(replies: Vec<u8>) -> super::Conn {
use kevy_noise::{Frames, Keypair, Responder, frame};
use std::io::{Read, Write};
let key = Keypair::from_secret([1; 32]);
let public = key.public();
let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = l.local_addr().unwrap().port();
std::thread::spawn(move || {
let (mut s, _) = l.accept().unwrap();
let (mut frames, mut chunk) = (Frames::default(), [0u8; 4096]);
let mut next = |s: &mut std::net::TcpStream, f: &mut Frames| loop {
if let Some(m) = f.next() {
return m;
}
let n = s.read(&mut chunk).unwrap();
f.push(&chunk[..n]);
};
let m1 = next(&mut s, &mut frames);
let prologue = b"kevy-client\x001";
let (_, r) =
Responder::accept(&key, Keypair::from_secret([2; 32]), prologue, &m1).unwrap();
let (m2, mut t) = r.finish(b"").unwrap();
s.write_all(&frame(&m2).unwrap()).unwrap();
let _request = t.open(&next(&mut s, &mut frames)).unwrap();
s.write_all(&frame(&t.seal(&replies).unwrap()).unwrap()).unwrap();
std::thread::sleep(std::time::Duration::from_secs(5)); });
let target = super::super::opts::SecureTarget { server_key: public, client_key_file: None };
super::Conn::secure(b"127.0.0.1", i32::from(port), None, &target).unwrap()
}
#[test]
fn one_read_leaves_no_decrypted_bytes_behind_in_the_stream() {
let replies = b"+OK\r\n".repeat(4000); let mut conn = secure_conn_answering(replies);
conn.send(&[b"PING".to_vec()]).unwrap();
assert!(conn.read_reply().is_ok());
for i in 1..4000 {
assert!(matches!(conn.buffered_reply(), Ok(Some(_))), "reply {i} was not buffered");
}
}
}