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