1use crate::mcp::Server;
14use serde_json::{json, Value};
15use std::io::{Read, Write};
16use std::net::{SocketAddr, TcpListener, TcpStream};
17use std::sync::mpsc::{sync_channel, Receiver, TrySendError};
18use std::sync::{Arc, Mutex};
19use std::time::{Duration, Instant};
20
21pub const OPERATIONS: [&str; 5] = ["encode", "decode", "inspect", "compare", "discover"];
23
24const MAX_HEAD_BYTES: usize = 16 * 1024;
26
27#[derive(Clone, Debug)]
30pub struct Options {
31 pub workers: usize,
33 pub queue: usize,
36 pub timeout: Duration,
39 pub max_body_bytes: u64,
41 pub any_host: bool,
45 pub studio: bool,
47 pub registry: bool,
50 pub operations: bool,
53 pub federation: Option<Arc<Federation>>,
55}
56
57pub struct Federation {
67 pub upstreams: Vec<String>,
68 pub timeout: Duration,
70 pub max_bytes: u64,
72 pub cache_bytes: u64,
74 check: Option<UpstreamCheck>,
78 asking: Mutex<()>,
79 kept: Mutex<std::collections::VecDeque<(String, Arc<[u8]>)>>,
80 absent: Mutex<std::collections::VecDeque<(String, Instant)>>,
81 failed: Mutex<Vec<Option<Instant>>>,
85}
86
87pub type UpstreamCheck = Box<dyn Fn(&kute::Vocabulary) -> Result<(), String> + Send + Sync>;
88
89impl std::fmt::Debug for Federation {
90 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91 f.debug_struct("Federation").field("upstreams", &self.upstreams).field("check", &self.check.is_some()).finish_non_exhaustive()
92 }
93}
94
95const ABSENT_FOR: Duration = Duration::from_secs(60);
97const REST_FOR: Duration = Duration::from_secs(30);
99const ABSENT_KEPT: usize = 1024;
101
102fn locked<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
103 mutex.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
104}
105
106impl Federation {
107 pub fn new(upstreams: Vec<String>, timeout: Duration, max_bytes: u64, cache_bytes: u64, check: Option<UpstreamCheck>) -> kute::Result<Self> {
108 for upstream in &upstreams {
109 crate::registry::parse_url(upstream)?;
110 }
111 let failed = Mutex::new(vec![None; upstreams.len()]);
112 Ok(Self { upstreams, timeout, max_bytes, cache_bytes, check, asking: Mutex::new(()), kept: Default::default(), absent: Default::default(), failed })
113 }
114
115 fn cached(&self, digest: &str) -> Option<Arc<[u8]>> {
116 locked(&self.kept).iter().find(|(d, _)| d == digest).map(|(_, file)| file.clone())
117 }
118
119 fn find(&self, engine: &kute::Engine, digest: &str, ask: bool) -> Result<Option<Arc<[u8]>>, Reply> {
122 if let Some(file) = self.cached(digest) {
123 return Ok(Some(file));
124 }
125 if !ask {
126 return Ok(None);
127 }
128 {
129 let mut absent = locked(&self.absent);
130 absent.retain(|(_, when)| when.elapsed() < ABSENT_FOR);
131 if absent.iter().any(|(d, _)| d == digest) {
132 return Ok(None);
133 }
134 }
135 let _asking = match self.asking.try_lock() {
139 Ok(guard) => guard,
140 Err(std::sync::TryLockError::Poisoned(poisoned)) => poisoned.into_inner(),
141 Err(std::sync::TryLockError::WouldBlock) => return Err(problem(503, "Service Unavailable", "busy", "this registry is asking another for a vocabulary; try again")),
142 };
143 if let Some(file) = self.cached(digest) {
144 return Ok(Some(file));
145 }
146 let mut every_upstream_said_no = true;
147 for (i, upstream) in self.upstreams.iter().enumerate() {
148 if locked(&self.failed)[i].is_some_and(|when| when.elapsed() < REST_FOR) {
149 every_upstream_said_no = false;
151 continue;
152 }
153 match crate::registry::take(engine, upstream, digest, self.max_bytes, self.timeout, true) {
154 Ok(crate::registry::Taken::Found(vocabulary, _)) => {
155 if self.check.as_ref().is_some_and(|check| check(&vocabulary).is_err()) {
158 every_upstream_said_no = false;
159 locked(&self.failed)[i] = Some(Instant::now());
160 continue;
161 }
162 let Ok(file) = kute::vocab::to_vec(&vocabulary) else { continue };
164 let file: Arc<[u8]> = file.into();
165 if file.len() as u64 <= self.cache_bytes {
166 let mut kept = locked(&self.kept);
167 kept.push_back((digest.to_string(), file.clone()));
168 while kept.iter().map(|(_, f)| f.len() as u64).sum::<u64>() > self.cache_bytes {
169 kept.pop_front();
170 }
171 }
172 return Ok(Some(file));
173 }
174 Ok(crate::registry::Taken::Absent(_)) => {}
175 Err(_) => {
178 every_upstream_said_no = false;
179 locked(&self.failed)[i] = Some(Instant::now());
180 }
181 }
182 }
183 if every_upstream_said_no {
184 let mut absent = locked(&self.absent);
185 if absent.len() >= ABSENT_KEPT {
186 absent.pop_front();
187 }
188 absent.push_back((digest.to_string(), Instant::now()));
189 }
190 Ok(None)
191 }
192}
193
194const STUDIO: [(&str, &str, &str); 3] = [
197 ("/studio", "text/html; charset=utf-8", include_str!("../studio/index.html")),
198 ("/studio/studio.css", "text/css; charset=utf-8", include_str!("../studio/studio.css")),
199 ("/studio/studio.js", "text/javascript; charset=utf-8", include_str!("../studio/studio.js")),
200];
201
202const STUDIO_POLICY: &str = "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
206
207impl Default for Options {
208 fn default() -> Self {
209 Self { workers: 4, queue: 16, timeout: Duration::from_secs(10), max_body_bytes: 3 << 20, any_host: false, studio: false, registry: false, operations: true, federation: None }
210 }
211}
212
213struct Reply {
214 status: u16,
215 reason: &'static str,
216 body: Value,
217 allow: Option<&'static str>,
218 page: Option<(&'static str, &'static str)>,
220 file: Option<Box<[u8]>>,
222}
223
224fn problem(status: u16, reason: &'static str, code: &str, message: impl Into<String>) -> Reply {
225 Reply { status, reason, body: json!({ "error": { "code": code, "message": message.into() } }), allow: None, page: None, file: None }
226}
227
228fn ok(body: Value) -> Reply {
229 Reply { status: 200, reason: "OK", body, allow: None, page: None, file: None }
230}
231
232struct Request {
233 method: String,
234 path: String,
235 host: Option<String>,
236 content_type: Option<String>,
237 body: Vec<u8>,
238 via: bool,
240}
241
242fn loopback_name(host: &str) -> bool {
243 let name = if let Some(rest) = host.strip_prefix('[') {
244 match rest.split_once(']') {
246 Some((name, after)) if after.is_empty() || after.strip_prefix(':').is_some_and(|port| port.chars().all(|c| c.is_ascii_digit())) => name,
247 _ => return false,
248 }
249 } else {
250 host.rsplit_once(':').map_or(host, |(name, port)| if port.chars().all(|c| c.is_ascii_digit()) { name } else { host })
251 };
252 name.eq_ignore_ascii_case("localhost") || name.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback())
253}
254
255fn read_request(stream: &mut TcpStream, options: &Options) -> Result<Request, Reply> {
257 let deadline = Instant::now() + options.timeout;
258 let late = || problem(408, "Request Timeout", "timeout", "the request did not arrive in time");
259 let mut buffer: Vec<u8> = Vec::with_capacity(1024);
260 let mut chunk = [0u8; 4096];
261 let head_end = loop {
262 if let Some(at) = buffer.windows(4).position(|w| w == b"\r\n\r\n") {
263 break at;
264 }
265 if buffer.len() > MAX_HEAD_BYTES {
266 return Err(problem(431, "Request Header Fields Too Large", "headers_too_large", format!("the request line and headers may take {MAX_HEAD_BYTES} bytes")));
267 }
268 let left = deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()).ok_or_else(late)?;
269 stream.set_read_timeout(Some(left)).map_err(|_| late())?;
270 match stream.read(&mut chunk) {
271 Ok(0) => return Err(problem(400, "Bad Request", "bad_request", "the connection closed before the request was complete")),
272 Ok(n) => buffer.extend_from_slice(&chunk[..n]),
273 Err(_) => return Err(late()),
274 }
275 };
276 if head_end > MAX_HEAD_BYTES {
277 return Err(problem(431, "Request Header Fields Too Large", "headers_too_large", format!("the request line and headers may take {MAX_HEAD_BYTES} bytes")));
278 }
279 let bad = |what: &str| problem(400, "Bad Request", "bad_request", what.to_string());
280 let head = std::str::from_utf8(&buffer[..head_end]).map_err(|_| bad("the request line and headers are not text"))?;
281 let mut lines = head.split("\r\n");
282 let mut first = lines.next().unwrap_or("").split(' ');
283 let (method, target, version) = (first.next().unwrap_or(""), first.next().unwrap_or(""), first.next().unwrap_or(""));
284 if method.is_empty() || !target.starts_with('/') || !matches!(version, "HTTP/1.0" | "HTTP/1.1") || first.next().is_some() {
285 return Err(bad("the request line is not HTTP/1.x"));
286 }
287 let (mut host, mut content_type, mut length, mut chunked, mut via) = (None, None, None, false, false);
288 for line in lines {
289 let (name, value) = line.split_once(':').ok_or_else(|| bad("a header line has no colon"))?;
290 if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)) {
294 return Err(bad("a header name is not a token"));
295 }
296 let value = value.trim_matches([' ', '\t']);
297 if value.bytes().any(|b| (b < 0x20 && b != b'\t') || b == 0x7f) {
298 return Err(bad("a header value holds a control character"));
299 }
300 match name.to_ascii_lowercase().as_str() {
301 "host" => {
302 if host.is_some() {
303 return Err(bad("two Host headers"));
304 }
305 host = Some(value.to_string());
306 }
307 "content-type" => content_type = Some(value.to_ascii_lowercase()),
308 "content-length" => {
309 let n: u64 = Some(value).filter(|v| !v.is_empty() && v.bytes().all(|b| b.is_ascii_digit())).and_then(|v| v.parse().ok()).ok_or_else(|| bad("Content-Length is not a number"))?;
311 if length.is_some_and(|earlier| earlier != n) {
312 return Err(bad("two different Content-Length headers"));
313 }
314 length = Some(n);
315 }
316 "transfer-encoding" => chunked = true,
317 "kute-registry-via" => via = true,
318 _ => {}
319 }
320 }
321 if chunked {
322 return Err(problem(411, "Length Required", "length_required", "send the body with Content-Length, not a transfer encoding"));
323 }
324 let path = target.split('?').next().unwrap_or("").to_string();
325 let mut body = buffer[head_end + 4..].to_vec();
326 let length = match (method, length) {
327 (_, Some(n)) => n,
328 ("POST", None) => return Err(problem(411, "Length Required", "length_required", "a POST needs Content-Length")),
329 (_, None) => 0,
330 };
331 if length > options.max_body_bytes {
332 return Err(problem(413, "Content Too Large", "too_large", format!("the body is {length} bytes; the limit is {}", options.max_body_bytes)));
333 }
334 let length = length as usize;
335 if body.len() > length {
336 return Err(bad("more bytes than Content-Length; one request per connection"));
337 }
338 while body.len() < length {
339 let left = deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()).ok_or_else(late)?;
340 stream.set_read_timeout(Some(left)).map_err(|_| late())?;
341 let want = chunk.len().min(length - body.len());
342 match stream.read(&mut chunk[..want]) {
343 Ok(0) => return Err(bad("the connection closed before the body was complete")),
344 Ok(n) => body.extend_from_slice(&chunk[..n]),
345 Err(_) => return Err(late()),
346 }
347 }
348 Ok(Request { method: method.to_string(), path, host, content_type, body, via })
349}
350
351fn route(server: &Server, request: &Request, options: &Options) -> Reply {
352 if !options.any_host && !request.host.as_deref().is_some_and(loopback_name) {
353 return problem(403, "Forbidden", "forbidden_host", "this service answers only requests addressed to localhost");
354 }
355 if let Some((_, content_type, text)) = STUDIO.iter().find(|(path, _, _)| options.studio && *path == request.path) {
356 if request.method != "GET" {
357 return Reply { allow: Some("GET"), ..problem(405, "Method Not Allowed", "method_not_allowed", "the page is read with GET") };
358 }
359 return Reply { page: Some((content_type, text)), ..ok(Value::Null) };
360 }
361 let operation = match request.path.strip_prefix("/v1/") {
362 Some(rest) => rest,
363 None => return problem(404, "Not Found", "not_found", "the interface is under /v1/"),
364 };
365 if operation == "capabilities" {
366 if request.method != "GET" {
367 return Reply { allow: Some("GET"), ..problem(405, "Method Not Allowed", "method_not_allowed", "capabilities is read with GET") };
368 }
369 let mut held = match server.call("inspect", &json!({})) {
370 Ok(v) => v,
371 Err(message) => return problem(500, "Internal Server Error", "internal", message),
372 };
373 held["api"] = json!("v1");
374 held["software"] = json!(format!("kute {}", kute::KUTE_VERSION));
375 held["operations"] = if options.operations { json!(OPERATIONS) } else { json!([]) };
376 held["registry"] = json!(options.registry);
377 held["limits"]["max_body_bytes"] = json!(options.max_body_bytes);
378 return ok(held);
379 }
380 if operation == "vocabularies" || operation.starts_with("vocabularies/") {
381 if !options.registry {
384 return problem(404, "Not Found", "not_found", "this service does not give vocabulary files");
385 }
386 if request.method != "GET" {
387 return Reply { allow: Some("GET"), ..problem(405, "Method Not Allowed", "method_not_allowed", "vocabularies are read with GET; nothing can be sent to this registry") };
388 }
389 let Some(digest) = operation.strip_prefix("vocabularies/") else {
390 let mut listing = server.registry_list();
391 listing["upstreams"] = json!(options.federation.as_ref().map(|f| f.upstreams.clone()).unwrap_or_default());
393 listing["upstream_files_need_a_trusted_signature"] = json!(options.federation.as_ref().is_some_and(|f| f.check.is_some()));
394 return ok(listing);
395 };
396 if !crate::registry::is_digest(digest) {
399 return problem(404, "Not Found", "not_found", "a vocabulary is asked for by its digest: sha256: and 64 lowercase hex digits");
400 }
401 return match server.registry_file(digest) {
402 Some(Ok(file)) => Reply { file: Some(file.into_boxed_slice()), ..ok(Value::Null) },
403 Some(Err(_)) => problem(500, "Internal Server Error", "internal", "the vocabulary could not be written out"),
404 None => {
405 let found = match &options.federation {
408 Some(federation) => federation.find(server.engine(), digest, !request.via),
409 None => Ok(None),
410 };
411 match found {
412 Ok(Some(file)) => Reply { file: Some(file.to_vec().into_boxed_slice()), ..ok(Value::Null) },
413 Ok(None) => problem(404, "Not Found", "not_found", "no vocabulary with that digest is held here"),
414 Err(reply) => reply,
415 }
416 }
417 };
418 }
419 if !OPERATIONS.contains(&operation) || !options.operations {
420 return problem(404, "Not Found", "not_found", format!("there is no operation {operation:?}"));
421 }
422 if request.method != "POST" {
423 return Reply { allow: Some("POST"), ..problem(405, "Method Not Allowed", "method_not_allowed", "operations are called with POST") };
424 }
425 if !request.content_type.as_deref().is_some_and(|t| t == "application/json" || t.starts_with("application/json;")) {
428 return problem(415, "Unsupported Media Type", "unsupported_media_type", "send Content-Type: application/json");
429 }
430 let arguments: Value = match serde_json::from_slice(&request.body) {
431 Ok(v) => v,
432 Err(e) => return problem(400, "Bad Request", "bad_json", format!("the body is not JSON: {e}")),
433 };
434 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| server.call(operation, &arguments))) {
438 Ok(Ok(result)) => ok(result),
439 Ok(Err(message)) => problem(422, "Unprocessable Content", "refused", message),
440 Err(_) => problem(500, "Internal Server Error", "internal", "the operation failed unexpectedly"),
441 }
442}
443
444fn answer(stream: &mut TcpStream, reply: &Reply, options: &Options) {
445 let (content_type, body) = match (reply.page, &reply.file) {
446 (Some((content_type, text)), _) => (content_type, text.as_bytes().to_vec()),
447 (None, Some(file)) => ("application/json", file.to_vec()),
448 (None, None) => ("application/json", serde_json::to_vec(&reply.body).unwrap_or_else(|_| b"{}".to_vec())),
449 };
450 let mut head = format!(
451 "HTTP/1.1 {} {}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n",
452 reply.status,
453 reply.reason,
454 body.len()
455 );
456 if reply.status == 503 {
457 head.push_str("Retry-After: 1\r\n");
458 }
459 if reply.page.is_some() {
460 head.push_str(&format!("Content-Security-Policy: {STUDIO_POLICY}\r\nReferrer-Policy: no-referrer\r\nX-Frame-Options: DENY\r\n"));
461 }
462 if let Some(allow) = reply.allow {
463 head.push_str(&format!("Allow: {allow}\r\n"));
464 }
465 head.push_str("\r\n");
466 let _ = stream.set_write_timeout(Some(options.timeout));
467 if stream.write_all(head.as_bytes()).is_ok() && stream.write_all(&body).is_ok() {
468 let _ = stream.flush();
469 }
470 let _ = stream.shutdown(std::net::Shutdown::Write);
471 let started = Instant::now();
479 let _ = stream.set_read_timeout(Some(Duration::from_millis(50)));
480 let (mut scrap, mut discarded) = ([0u8; 4096], 0usize);
481 while discarded < 1_048_576 && started.elapsed() < Duration::from_millis(500) {
482 match stream.read(&mut scrap) {
483 Ok(0) | Err(_) => break,
484 Ok(n) => discarded += n,
485 }
486 }
487}
488
489fn serve_one(server: &Server, mut stream: TcpStream, options: &Options) {
490 let reply = match read_request(&mut stream, options) {
491 Ok(request) => route(server, &request, options),
492 Err(reply) => reply,
493 };
494 answer(&mut stream, &reply, options);
495}
496
497fn work(server: Arc<Server>, jobs: Arc<Mutex<Receiver<TcpStream>>>, options: Options) {
498 loop {
499 let next = jobs.lock().map(|queue| queue.recv());
500 match next {
501 Ok(Ok(stream)) => serve_one(&server, stream, &options),
502 _ => return,
503 }
504 }
505}
506
507pub fn serve(server: Server, listener: TcpListener, options: Options) -> kute::Result<()> {
509 let server = Arc::new(server);
510 let (send, receive) = sync_channel::<TcpStream>(options.queue.max(1));
511 let receive = Arc::new(Mutex::new(receive));
512 for _ in 0..options.workers.max(1) {
513 let (server, receive, options) = (server.clone(), receive.clone(), options.clone());
514 std::thread::spawn(move || work(server, receive, options));
515 }
516 for stream in listener.incoming() {
517 let stream = match stream {
518 Ok(s) => s,
519 Err(_) => continue,
520 };
521 match send.try_send(stream) {
522 Ok(()) => {}
523 Err(TrySendError::Full(mut stream)) => {
524 let busy = Reply { ..problem(503, "Service Unavailable", "busy", "every worker is busy and the queue is full; try again") };
526 let brief = Options { timeout: Duration::from_secs(1), ..options.clone() };
527 answer(&mut stream, &busy, &brief);
528 }
529 Err(TrySendError::Disconnected(_)) => return Err(kute::KuteError::Backend("the workers stopped".into())),
530 }
531 }
532 Ok(())
533}
534
535pub fn is_loopback(address: &SocketAddr) -> bool {
537 address.ip().is_loopback()
538}