1use crate::*;
2use tokio::io::{AsyncReadExt, AsyncWriteExt};
3
4#[derive(serde::Deserialize)]
5struct Limits { request: usize, response: usize }
6static LIMITS: std::sync::LazyLock<Limits> = std::sync::LazyLock::new(|| serde_json::from_str(include_str!("host-protocol.json")).expect("host protocol limits"));
7
8static SLOTS: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(4);
9
10pub async fn sample(app: Arc<App>) -> Result<Arc<Document>> {
11 app.cache
12 .get("host-sample".into(), Duration::from_secs(1), || async {
13 call(json!({"operation":"host.sample"})).await
14 })
15 .await
16}
17
18pub async fn call(request: Value) -> Result<Value> {
19 let _slot = tokio::time::timeout(Duration::from_secs(70), SLOTS.acquire())
20 .await
21 .map_err(|_| {
22 Error::new(
23 504,
24 "The host operation is taking too long. Check its logs, then retry.",
25 )
26 })??;
27 open(request).await.map(|(value, _)| value)
28}
29
30// Streams authenticate the same Unix peer and use the same framed JSON header.
31pub async fn open(request: Value) -> Result<(Value, tokio::net::UnixStream)> {
32 let timeout = if matches!(
33 request["operation"].as_str(),
34 Some("vm.create" | "vm.media" | "vm.preset" | "vm.ai")
35 ) {
36 910
37 } else if request["operation"] == "vm.computer" {
38 300
39 } else if request["operation"] == "vm.act" {
40 240
41 } else if request["operation"] == "copyparty.manage" {
42 310
43 } else {
44 70
45 };
46 tokio::time::timeout(Duration::from_secs(timeout), async {
47 let mut socket = tokio::net::UnixStream::connect(env(
48 "SNOWGLOBE_HOST_SOCKET",
49 "/run/snowglobe-host/host.sock",
50 ))
51 .await?;
52 #[cfg(target_os = "linux")]
53 if socket.peer_cred()?.uid() != 0 {
54 return Err(Error::new(
55 502,
56 "The host service identity couldn't be verified.",
57 ));
58 }
59 let mut message = serde_json::to_vec(&request)?;
60 message.push(b'\n');
61 if message.len() > LIMITS.request {
62 return Err(Error::new(
63 400,
64 "The host request is too large. Narrow the selection.",
65 ));
66 }
67 socket.write_all(&message).await?;
68 let value = response(&mut socket).await?;
69 Ok((value, socket))
70 })
71 .await
72 .map_err(|_| Error::new(504, "The host connection timed out. Try again."))?
73}
74
75pub async fn response(socket: &mut tokio::net::UnixStream) -> Result<Value> {
76 let length = socket.read_u32().await? as usize;
77 if length > LIMITS.response {
78 return Err(Error::new(
79 502,
80 "The host response is too large. Narrow the selection.",
81 ));
82 }
83 let mut bytes = vec![0; length];
84 socket.read_exact(&mut bytes).await?;
85 let mut response: Value = serde_json::from_slice(&bytes)?;
86 if let Some(message) = response["error"].as_str() {
87 return Err(Error::new(
88 response["status"]
89 .as_u64()
90 .filter(|s| (400..=599).contains(s))
91 .unwrap_or(502) as u16,
92 message,
93 ));
94 }
95 response
96 .as_object_mut()
97 .and_then(|v| v.remove("value"))
98 .ok_or_else(|| {
99 Error::new(
100 502,
101 "The host response is incomplete. Check its logs, then retry.",
102 )
103 })
104}