This commit is contained in:
Generated
+9
@@ -5,3 +5,12 @@ version = 4
|
||||
[[package]]
|
||||
name = "alkane-os"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.190"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
|
||||
|
||||
+3
-1
@@ -8,7 +8,9 @@ description = "Portable mining and tuning core for Alkane control boards"
|
||||
[lib]
|
||||
name = "alkane_os"
|
||||
|
||||
[dependencies]
|
||||
libc = "0.2.169"
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
|
||||
|
||||
+158
-8
@@ -4,15 +4,18 @@
|
||||
use crate::HardwareBackend;
|
||||
use std::fmt;
|
||||
use std::io::{self, Read, Write};
|
||||
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
use std::os::unix::net::UnixStream;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const MAGIC: [u8; 4] = *b"ALKH";
|
||||
const VERSION: u8 = 1;
|
||||
const RESPONSE: u16 = 1;
|
||||
const HEADER_LEN: usize = 16;
|
||||
const MAX_PAYLOAD: usize = 4096;
|
||||
const IO_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
|
||||
const SEND_FRAME: u8 = 1;
|
||||
const RECEIVE_FRAME: u8 = 2;
|
||||
@@ -59,13 +62,13 @@ pub struct HalClient {
|
||||
|
||||
impl HalClient {
|
||||
pub fn connect(path: impl AsRef<Path>) -> Result<Self, HalError> {
|
||||
let stream = UnixStream::connect(path)?;
|
||||
let stream = connect_until(path.as_ref(), Instant::now() + IO_TIMEOUT)?;
|
||||
Self::from_stream(stream)
|
||||
}
|
||||
|
||||
pub fn from_stream(stream: UnixStream) -> Result<Self, HalError> {
|
||||
stream.set_read_timeout(Some(Duration::from_secs(2)))?;
|
||||
stream.set_write_timeout(Some(Duration::from_secs(2)))?;
|
||||
stream.set_read_timeout(Some(IO_TIMEOUT))?;
|
||||
stream.set_write_timeout(Some(IO_TIMEOUT))?;
|
||||
Ok(Self {
|
||||
stream,
|
||||
sequence: 0,
|
||||
@@ -90,6 +93,7 @@ impl HalClient {
|
||||
}
|
||||
|
||||
fn exchange_inner(&mut self, opcode: u8, payload: &[u8]) -> Result<Vec<u8>, HalError> {
|
||||
let deadline = Instant::now() + IO_TIMEOUT;
|
||||
self.sequence = self.sequence.wrapping_add(1);
|
||||
let sequence = self.sequence;
|
||||
let mut header = [0_u8; HEADER_LEN];
|
||||
@@ -98,10 +102,10 @@ impl HalClient {
|
||||
header[5] = opcode;
|
||||
header[8..12].copy_from_slice(&sequence.to_le_bytes());
|
||||
header[12..16].copy_from_slice(&(payload.len() as u32).to_le_bytes());
|
||||
self.stream.write_all(&header)?;
|
||||
self.stream.write_all(payload)?;
|
||||
write_all_until(&mut self.stream, &header, deadline)?;
|
||||
write_all_until(&mut self.stream, payload, deadline)?;
|
||||
|
||||
self.stream.read_exact(&mut header)?;
|
||||
read_exact_until(&mut self.stream, &mut header, deadline)?;
|
||||
if header[..4] != MAGIC || header[4] != VERSION || header[5] != opcode {
|
||||
return Err(HalError::Protocol("response identity mismatch"));
|
||||
}
|
||||
@@ -116,8 +120,11 @@ impl HalClient {
|
||||
return Err(HalError::Protocol("invalid response length"));
|
||||
}
|
||||
let mut body = vec![0_u8; length];
|
||||
self.stream.read_exact(&mut body)?;
|
||||
read_exact_until(&mut self.stream, &mut body, deadline)?;
|
||||
if body[0] != 0 {
|
||||
if !matches!(body[0], 1..=3) || body.len() != 1 {
|
||||
return Err(HalError::Protocol("invalid error response"));
|
||||
}
|
||||
return Err(HalError::Device(body[0]));
|
||||
}
|
||||
Ok(body[1..].to_vec())
|
||||
@@ -132,6 +139,149 @@ impl HalClient {
|
||||
}
|
||||
}
|
||||
|
||||
fn timeout_error() -> io::Error {
|
||||
io::Error::new(io::ErrorKind::TimedOut, "HAL operation timed out")
|
||||
}
|
||||
|
||||
fn remaining(deadline: Instant) -> io::Result<Duration> {
|
||||
deadline
|
||||
.checked_duration_since(Instant::now())
|
||||
.filter(|duration| !duration.is_zero())
|
||||
.ok_or_else(timeout_error)
|
||||
}
|
||||
|
||||
fn write_all_until(stream: &mut UnixStream, mut data: &[u8], deadline: Instant) -> io::Result<()> {
|
||||
while !data.is_empty() {
|
||||
stream.set_write_timeout(Some(remaining(deadline)?))?;
|
||||
match stream.write(data) {
|
||||
Ok(0) => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::WriteZero,
|
||||
"HAL socket closed",
|
||||
))
|
||||
}
|
||||
Ok(count) => data = &data[count..],
|
||||
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_exact_until(
|
||||
stream: &mut UnixStream,
|
||||
mut data: &mut [u8],
|
||||
deadline: Instant,
|
||||
) -> io::Result<()> {
|
||||
while !data.is_empty() {
|
||||
stream.set_read_timeout(Some(remaining(deadline)?))?;
|
||||
match stream.read(data) {
|
||||
Ok(0) => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::UnexpectedEof,
|
||||
"HAL socket closed",
|
||||
))
|
||||
}
|
||||
Ok(count) => data = &mut data[count..],
|
||||
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn connect_until(path: &Path, deadline: Instant) -> io::Result<UnixStream> {
|
||||
let bytes = path.as_os_str().as_bytes();
|
||||
let max_path = std::mem::size_of::<libc::sockaddr_un>()
|
||||
- std::mem::offset_of!(libc::sockaddr_un, sun_path);
|
||||
if bytes.is_empty() || bytes.len() >= max_path || bytes.contains(&0) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"invalid HAL socket path",
|
||||
));
|
||||
}
|
||||
let raw = unsafe {
|
||||
libc::socket(
|
||||
libc::AF_UNIX,
|
||||
libc::SOCK_STREAM | libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC,
|
||||
0,
|
||||
)
|
||||
};
|
||||
if raw < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let fd = unsafe { OwnedFd::from_raw_fd(raw) };
|
||||
let mut address: libc::sockaddr_un = unsafe { std::mem::zeroed() };
|
||||
address.sun_family = libc::AF_UNIX as libc::sa_family_t;
|
||||
for (destination, source) in address.sun_path.iter_mut().zip(bytes) {
|
||||
*destination = *source as libc::c_char;
|
||||
}
|
||||
let length =
|
||||
(std::mem::offset_of!(libc::sockaddr_un, sun_path) + bytes.len() + 1) as libc::socklen_t;
|
||||
loop {
|
||||
let result = unsafe {
|
||||
libc::connect(
|
||||
fd.as_raw_fd(),
|
||||
&address as *const _ as *const libc::sockaddr,
|
||||
length,
|
||||
)
|
||||
};
|
||||
if result == 0 {
|
||||
break;
|
||||
}
|
||||
let error = io::Error::last_os_error();
|
||||
if error.raw_os_error() == Some(libc::EISCONN) {
|
||||
break;
|
||||
}
|
||||
if !matches!(
|
||||
error.raw_os_error(),
|
||||
Some(libc::EINPROGRESS) | Some(libc::EAGAIN)
|
||||
) {
|
||||
return Err(error);
|
||||
}
|
||||
let mut poll_fd = libc::pollfd {
|
||||
fd: fd.as_raw_fd(),
|
||||
events: libc::POLLOUT,
|
||||
revents: 0,
|
||||
};
|
||||
let wait = remaining(deadline)?.as_millis().min(i32::MAX as u128) as i32;
|
||||
let polled = unsafe { libc::poll(&mut poll_fd, 1, wait.max(1)) };
|
||||
if polled < 0 {
|
||||
let error = io::Error::last_os_error();
|
||||
if error.kind() == io::ErrorKind::Interrupted {
|
||||
continue;
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
if polled == 0 {
|
||||
return Err(timeout_error());
|
||||
}
|
||||
let mut socket_error: libc::c_int = 0;
|
||||
let mut socket_error_len = std::mem::size_of_val(&socket_error) as libc::socklen_t;
|
||||
if unsafe {
|
||||
libc::getsockopt(
|
||||
fd.as_raw_fd(),
|
||||
libc::SOL_SOCKET,
|
||||
libc::SO_ERROR,
|
||||
&mut socket_error as *mut _ as *mut libc::c_void,
|
||||
&mut socket_error_len,
|
||||
)
|
||||
} < 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
if socket_error != 0 {
|
||||
return Err(io::Error::from_raw_os_error(socket_error));
|
||||
}
|
||||
if error.raw_os_error() == Some(libc::EINPROGRESS) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let stream = UnixStream::from(fd);
|
||||
stream.set_nonblocking(false)?;
|
||||
Ok(stream)
|
||||
}
|
||||
|
||||
impl HardwareBackend for HalClient {
|
||||
type Error = HalError;
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ use alkane_os::HardwareBackend;
|
||||
use std::io::{Read, Write};
|
||||
use std::os::unix::net::UnixStream;
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
fn reply(socket: &mut UnixStream, request: &[u8; 16], body: &[u8]) {
|
||||
let mut header = *request;
|
||||
@@ -88,3 +89,56 @@ fn rejects_wrong_response_sequence() {
|
||||
));
|
||||
worker.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_malformed_error_response_and_poisoned_connection() {
|
||||
for body in [&[4_u8][..], &[3_u8, 99][..]] {
|
||||
let (client, mut server) = UnixStream::pair().unwrap();
|
||||
let response = body.to_vec();
|
||||
let worker = thread::spawn(move || {
|
||||
let mut header = [0_u8; 16];
|
||||
server.read_exact(&mut header).unwrap();
|
||||
let mut request = [0_u8; 1];
|
||||
server.read_exact(&mut request).unwrap();
|
||||
reply(&mut server, &header, &response);
|
||||
});
|
||||
let mut backend = HalClient::from_stream(client).unwrap();
|
||||
assert!(matches!(
|
||||
backend.set_psu_enabled(true),
|
||||
Err(HalError::Protocol("invalid error response"))
|
||||
));
|
||||
assert!(matches!(
|
||||
backend.set_psu_enabled(true),
|
||||
Err(HalError::Protocol("connection is unusable"))
|
||||
));
|
||||
worker.join().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slow_partial_response_hits_absolute_exchange_deadline() {
|
||||
let (client, mut server) = UnixStream::pair().unwrap();
|
||||
let worker = thread::spawn(move || {
|
||||
let mut header = [0_u8; 16];
|
||||
server.read_exact(&mut header).unwrap();
|
||||
let mut request = [0_u8; 1];
|
||||
server.read_exact(&mut request).unwrap();
|
||||
header[6..8].copy_from_slice(&1_u16.to_le_bytes());
|
||||
header[12..16].copy_from_slice(&1_u32.to_le_bytes());
|
||||
for byte in header.into_iter().chain([0]) {
|
||||
if server.write_all(&[byte]).is_err() {
|
||||
break;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(250));
|
||||
}
|
||||
});
|
||||
let mut backend = HalClient::from_stream(client).unwrap();
|
||||
let start = Instant::now();
|
||||
assert!(matches!(
|
||||
backend.set_psu_enabled(true),
|
||||
Err(HalError::Io(_))
|
||||
));
|
||||
assert!(start.elapsed() < Duration::from_secs(4));
|
||||
drop(backend);
|
||||
worker.join().unwrap();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user