1mod client;
4#[cfg(test)]
5mod tests;
6pub use client::Client;
7
8use super::{Capabilities, Error, Request as RuntimeRequest, Response as RuntimeResponse};
9use serde::{Deserialize, Serialize, de::DeserializeOwned};
10use std::{
11 fmt::Write as _,
12 io::{self, Read, Write},
13 os::unix::fs::{DirBuilderExt as _, FileTypeExt as _, MetadataExt as _},
14 path::{Path, PathBuf},
15 time::{Duration, Instant},
16};
17
18pub const VERSION: u32 = 1;
20pub const MAX_REQUEST_BYTES: usize = 128 * 1024 * 1024;
22pub const MAX_RESPONSE_BYTES: usize = 640 * 1024 * 1024;
24pub const IO_TIMEOUT: Duration = Duration::from_secs(5);
26
27#[derive(Clone, Debug, Serialize, Deserialize)]
29#[serde(tag = "operation", rename_all = "snake_case", deny_unknown_fields)]
30pub enum Request {
31 Capabilities,
33 Execute {
35 id: String,
37 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
39 temporal_replay: bool,
40 request: RuntimeRequest,
42 },
43 Cancel {
45 id: String,
47 },
48}
49
50#[derive(Clone, Debug, Serialize, Deserialize)]
52#[serde(tag = "kind", rename_all = "snake_case")]
53pub enum Response {
54 Capabilities {
56 capabilities: Capabilities,
58 },
59 Completed {
61 id: String,
63 response: RuntimeResponse,
65 },
66 Cancelled {
68 id: String,
70 found: bool,
72 },
73 Error {
75 error: Error,
77 },
78}
79
80#[derive(Serialize, Deserialize)]
81#[serde(deny_unknown_fields)]
82struct Envelope<T> {
83 version: u32,
84 body: T,
85}
86
87struct Bounded(Vec<u8>, usize);
88impl Write for Bounded {
89 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
90 if bytes.len() > self.1.saturating_sub(self.0.len()) {
91 return Err(io::Error::new(
92 io::ErrorKind::InvalidData,
93 "SAIL6201: runtime frame exceeds its bound",
94 ));
95 }
96 self.0.extend_from_slice(bytes);
97 Ok(bytes.len())
98 }
99 fn flush(&mut self) -> io::Result<()> {
100 Ok(())
101 }
102}
103
104pub fn write_frame<T: Serialize>(
109 writer: &mut impl Write,
110 body: &T,
111 bound: usize,
112) -> io::Result<()> {
113 let mut encoded = Bounded(Vec::new(), bound);
114 serde_json::to_writer(
115 &mut encoded,
116 &Envelope {
117 version: VERSION,
118 body,
119 },
120 )
121 .map_err(|e| io::Error::new(e.io_error_kind().unwrap_or(io::ErrorKind::InvalidData), e))?;
122 let length = u32::try_from(encoded.0.len()).map_err(io::Error::other)?;
123 writer.write_all(&length.to_be_bytes())?;
124 writer.write_all(&encoded.0)?;
125 writer.flush()
126}
127
128pub fn read_frame<T: DeserializeOwned>(reader: &mut impl Read, bound: usize) -> io::Result<T> {
133 let mut header = [0_u8; 4];
134 reader.read_exact(&mut header)?;
135 let length = usize::try_from(u32::from_be_bytes(header)).map_err(io::Error::other)?;
136 if length == 0 || length > bound {
137 return Err(io::Error::new(
138 io::ErrorKind::InvalidData,
139 "SAIL6201: runtime frame exceeds its bound",
140 ));
141 }
142 let mut bytes = vec![0_u8; length];
143 reader.read_exact(&mut bytes)?;
144 let envelope: Envelope<T> = crate::temporal::decode(&bytes).map_err(io::Error::other)?;
145 if envelope.version != VERSION {
146 return Err(io::Error::new(
147 io::ErrorKind::InvalidData,
148 "SAIL6201: incompatible runtime endpoint; restart sail serve",
149 ));
150 }
151 Ok(envelope.body)
152}
153
154#[must_use]
156pub fn socket_path(cache_socket: &Path) -> PathBuf {
157 let jobs = crate::jobs::socket_path(cache_socket);
158 let hash = sail_key::sha256(jobs.as_os_str().as_encoded_bytes());
159 let mut suffix = String::new();
160 for byte in hash.iter().take(8) {
161 let _ = write!(suffix, "{byte:02x}");
162 }
163 jobs.with_file_name(format!("rt-{suffix}")).join("v1.sock")
164}
165
166pub fn private_parent(socket: &Path, create: bool) -> io::Result<()> {
171 let parent = socket
172 .parent()
173 .ok_or_else(|| io::Error::other("SAIL6201: runtime endpoint has no parent"))?;
174 if create {
175 let mut builder = std::fs::DirBuilder::new();
176 builder.mode(0o700);
177 if let Err(e) = builder.create(parent)
178 && e.kind() != io::ErrorKind::AlreadyExists
179 {
180 return Err(e);
181 }
182 }
183 let metadata = std::fs::symlink_metadata(parent)?;
184 if !metadata.is_dir()
185 || metadata.uid() != rustix::process::geteuid().as_raw()
186 || metadata.mode() & 0o777 != 0o700
187 {
188 return Err(io::Error::new(
189 io::ErrorKind::PermissionDenied,
190 "SAIL6201: runtime parent must be an owned real directory with mode 0700",
191 ));
192 }
193 Ok(())
194}
195
196pub fn validate_socket(socket: &Path) -> io::Result<()> {
201 private_parent(socket, false)?;
202 let metadata = std::fs::symlink_metadata(socket)?;
203 if !metadata.file_type().is_socket()
204 || metadata.uid() != rustix::process::geteuid().as_raw()
205 || metadata.mode() & 0o777 != 0o600
206 {
207 return Err(io::Error::new(
208 io::ErrorKind::PermissionDenied,
209 "SAIL6201: runtime endpoint must be an owned socket with mode 0600",
210 ));
211 }
212 Ok(())
213}
214
215pub struct Deadline<'a> {
217 stream: &'a std::os::unix::net::UnixStream,
218 until: Instant,
219 prepared: bool,
220}
221impl<'a> Deadline<'a> {
222 #[must_use]
224 pub fn new(stream: &'a std::os::unix::net::UnixStream, duration: Duration) -> Self {
225 Self {
226 stream,
227 until: Instant::now() + duration,
228 prepared: false,
229 }
230 }
231 fn remaining(&self) -> io::Result<Duration> {
232 self.until
233 .checked_duration_since(Instant::now())
234 .filter(|duration| !duration.is_zero())
235 .ok_or_else(|| {
236 io::Error::new(
237 io::ErrorKind::TimedOut,
238 "SAIL6201: runtime frame deadline expired",
239 )
240 })
241 }
242}
243impl Deadline<'_> {
244 fn prepare(&mut self) -> io::Result<()> {
245 if !self.prepared {
246 self.stream.set_nonblocking(true)?;
247 self.prepared = true;
248 }
249 Ok(())
250 }
251 fn pause(&self) -> io::Result<()> {
252 std::thread::sleep(self.remaining()?.min(Duration::from_millis(2)));
253 Ok(())
254 }
255}
256impl Read for Deadline<'_> {
257 fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
258 self.prepare()?;
259 loop {
260 self.remaining()?;
261 match self.stream.read(bytes) {
262 Err(e) if e.kind() == io::ErrorKind::WouldBlock => self.pause()?,
263 Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
264 result => return result,
265 }
266 }
267 }
268}
269impl Write for Deadline<'_> {
270 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
271 self.prepare()?;
272 loop {
273 self.remaining()?;
274 match self.stream.write(bytes) {
275 Err(e) if e.kind() == io::ErrorKind::WouldBlock => self.pause()?,
276 Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
277 result => return result,
278 }
279 }
280 }
281 fn flush(&mut self) -> io::Result<()> {
282 self.stream.flush()
283 }
284}