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