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}
54
55const STUDIO: [(&str, &str, &str); 3] = [
58 ("/studio", "text/html; charset=utf-8", include_str!("../studio/index.html")),
59 ("/studio/studio.css", "text/css; charset=utf-8", include_str!("../studio/studio.css")),
60 ("/studio/studio.js", "text/javascript; charset=utf-8", include_str!("../studio/studio.js")),
61];
62
63const STUDIO_POLICY: &str = "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
67
68impl Default for Options {
69 fn default() -> Self {
70 Self { workers: 4, queue: 16, timeout: Duration::from_secs(10), max_body_bytes: 3 << 20, any_host: false, studio: false, registry: false, operations: true }
71 }
72}
73
74struct Reply {
75 status: u16,
76 reason: &'static str,
77 body: Value,
78 allow: Option<&'static str>,
79 page: Option<(&'static str, &'static str)>,
81 file: Option<Box<[u8]>>,
83}
84
85fn problem(status: u16, reason: &'static str, code: &str, message: impl Into<String>) -> Reply {
86 Reply { status, reason, body: json!({ "error": { "code": code, "message": message.into() } }), allow: None, page: None, file: None }
87}
88
89fn ok(body: Value) -> Reply {
90 Reply { status: 200, reason: "OK", body, allow: None, page: None, file: None }
91}
92
93struct Request {
94 method: String,
95 path: String,
96 host: Option<String>,
97 content_type: Option<String>,
98 body: Vec<u8>,
99}
100
101fn loopback_name(host: &str) -> bool {
102 let name = if let Some(rest) = host.strip_prefix('[') {
103 match rest.split_once(']') {
105 Some((name, after)) if after.is_empty() || after.strip_prefix(':').is_some_and(|port| port.chars().all(|c| c.is_ascii_digit())) => name,
106 _ => return false,
107 }
108 } else {
109 host.rsplit_once(':').map_or(host, |(name, port)| if port.chars().all(|c| c.is_ascii_digit()) { name } else { host })
110 };
111 name.eq_ignore_ascii_case("localhost") || name.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback())
112}
113
114fn read_request(stream: &mut TcpStream, options: &Options) -> Result<Request, Reply> {
116 let deadline = Instant::now() + options.timeout;
117 let late = || problem(408, "Request Timeout", "timeout", "the request did not arrive in time");
118 let mut buffer: Vec<u8> = Vec::with_capacity(1024);
119 let mut chunk = [0u8; 4096];
120 let head_end = loop {
121 if let Some(at) = buffer.windows(4).position(|w| w == b"\r\n\r\n") {
122 break at;
123 }
124 if buffer.len() > MAX_HEAD_BYTES {
125 return Err(problem(431, "Request Header Fields Too Large", "headers_too_large", format!("the request line and headers may take {MAX_HEAD_BYTES} bytes")));
126 }
127 let left = deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()).ok_or_else(late)?;
128 stream.set_read_timeout(Some(left)).map_err(|_| late())?;
129 match stream.read(&mut chunk) {
130 Ok(0) => return Err(problem(400, "Bad Request", "bad_request", "the connection closed before the request was complete")),
131 Ok(n) => buffer.extend_from_slice(&chunk[..n]),
132 Err(_) => return Err(late()),
133 }
134 };
135 if head_end > MAX_HEAD_BYTES {
136 return Err(problem(431, "Request Header Fields Too Large", "headers_too_large", format!("the request line and headers may take {MAX_HEAD_BYTES} bytes")));
137 }
138 let bad = |what: &str| problem(400, "Bad Request", "bad_request", what.to_string());
139 let head = std::str::from_utf8(&buffer[..head_end]).map_err(|_| bad("the request line and headers are not text"))?;
140 let mut lines = head.split("\r\n");
141 let mut first = lines.next().unwrap_or("").split(' ');
142 let (method, target, version) = (first.next().unwrap_or(""), first.next().unwrap_or(""), first.next().unwrap_or(""));
143 if method.is_empty() || !target.starts_with('/') || !matches!(version, "HTTP/1.0" | "HTTP/1.1") || first.next().is_some() {
144 return Err(bad("the request line is not HTTP/1.x"));
145 }
146 let (mut host, mut content_type, mut length, mut chunked) = (None, None, None, false);
147 for line in lines {
148 let (name, value) = line.split_once(':').ok_or_else(|| bad("a header line has no colon"))?;
149 if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)) {
153 return Err(bad("a header name is not a token"));
154 }
155 let value = value.trim_matches([' ', '\t']);
156 if value.bytes().any(|b| (b < 0x20 && b != b'\t') || b == 0x7f) {
157 return Err(bad("a header value holds a control character"));
158 }
159 match name.to_ascii_lowercase().as_str() {
160 "host" => {
161 if host.is_some() {
162 return Err(bad("two Host headers"));
163 }
164 host = Some(value.to_string());
165 }
166 "content-type" => content_type = Some(value.to_ascii_lowercase()),
167 "content-length" => {
168 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"))?;
170 if length.is_some_and(|earlier| earlier != n) {
171 return Err(bad("two different Content-Length headers"));
172 }
173 length = Some(n);
174 }
175 "transfer-encoding" => chunked = true,
176 _ => {}
177 }
178 }
179 if chunked {
180 return Err(problem(411, "Length Required", "length_required", "send the body with Content-Length, not a transfer encoding"));
181 }
182 let path = target.split('?').next().unwrap_or("").to_string();
183 let mut body = buffer[head_end + 4..].to_vec();
184 let length = match (method, length) {
185 (_, Some(n)) => n,
186 ("POST", None) => return Err(problem(411, "Length Required", "length_required", "a POST needs Content-Length")),
187 (_, None) => 0,
188 };
189 if length > options.max_body_bytes {
190 return Err(problem(413, "Content Too Large", "too_large", format!("the body is {length} bytes; the limit is {}", options.max_body_bytes)));
191 }
192 let length = length as usize;
193 if body.len() > length {
194 return Err(bad("more bytes than Content-Length; one request per connection"));
195 }
196 while body.len() < length {
197 let left = deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()).ok_or_else(late)?;
198 stream.set_read_timeout(Some(left)).map_err(|_| late())?;
199 let want = chunk.len().min(length - body.len());
200 match stream.read(&mut chunk[..want]) {
201 Ok(0) => return Err(bad("the connection closed before the body was complete")),
202 Ok(n) => body.extend_from_slice(&chunk[..n]),
203 Err(_) => return Err(late()),
204 }
205 }
206 Ok(Request { method: method.to_string(), path, host, content_type, body })
207}
208
209fn route(server: &Server, request: &Request, options: &Options) -> Reply {
210 if !options.any_host && !request.host.as_deref().is_some_and(loopback_name) {
211 return problem(403, "Forbidden", "forbidden_host", "this service answers only requests addressed to localhost");
212 }
213 if let Some((_, content_type, text)) = STUDIO.iter().find(|(path, _, _)| options.studio && *path == request.path) {
214 if request.method != "GET" {
215 return Reply { allow: Some("GET"), ..problem(405, "Method Not Allowed", "method_not_allowed", "the page is read with GET") };
216 }
217 return Reply { page: Some((content_type, text)), ..ok(Value::Null) };
218 }
219 let operation = match request.path.strip_prefix("/v1/") {
220 Some(rest) => rest,
221 None => return problem(404, "Not Found", "not_found", "the interface is under /v1/"),
222 };
223 if operation == "capabilities" {
224 if request.method != "GET" {
225 return Reply { allow: Some("GET"), ..problem(405, "Method Not Allowed", "method_not_allowed", "capabilities is read with GET") };
226 }
227 let mut held = match server.call("inspect", &json!({})) {
228 Ok(v) => v,
229 Err(message) => return problem(500, "Internal Server Error", "internal", message),
230 };
231 held["api"] = json!("v1");
232 held["software"] = json!(format!("kute {}", kute::KUTE_VERSION));
233 held["operations"] = if options.operations { json!(OPERATIONS) } else { json!([]) };
234 held["registry"] = json!(options.registry);
235 held["limits"]["max_body_bytes"] = json!(options.max_body_bytes);
236 return ok(held);
237 }
238 if operation == "vocabularies" || operation.starts_with("vocabularies/") {
239 if !options.registry {
242 return problem(404, "Not Found", "not_found", "this service does not give vocabulary files");
243 }
244 if request.method != "GET" {
245 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") };
246 }
247 let Some(digest) = operation.strip_prefix("vocabularies/") else { return ok(server.registry_list()) };
248 if !crate::registry::is_digest(digest) {
251 return problem(404, "Not Found", "not_found", "a vocabulary is asked for by its digest: sha256: and 64 lowercase hex digits");
252 }
253 return match server.registry_file(digest) {
254 Some(Ok(file)) => Reply { file: Some(file.into_boxed_slice()), ..ok(Value::Null) },
255 Some(Err(_)) => problem(500, "Internal Server Error", "internal", "the vocabulary could not be written out"),
256 None => problem(404, "Not Found", "not_found", "no vocabulary with that digest is held here"),
257 };
258 }
259 if !OPERATIONS.contains(&operation) || !options.operations {
260 return problem(404, "Not Found", "not_found", format!("there is no operation {operation:?}"));
261 }
262 if request.method != "POST" {
263 return Reply { allow: Some("POST"), ..problem(405, "Method Not Allowed", "method_not_allowed", "operations are called with POST") };
264 }
265 if !request.content_type.as_deref().is_some_and(|t| t == "application/json" || t.starts_with("application/json;")) {
268 return problem(415, "Unsupported Media Type", "unsupported_media_type", "send Content-Type: application/json");
269 }
270 let arguments: Value = match serde_json::from_slice(&request.body) {
271 Ok(v) => v,
272 Err(e) => return problem(400, "Bad Request", "bad_json", format!("the body is not JSON: {e}")),
273 };
274 match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| server.call(operation, &arguments))) {
278 Ok(Ok(result)) => ok(result),
279 Ok(Err(message)) => problem(422, "Unprocessable Content", "refused", message),
280 Err(_) => problem(500, "Internal Server Error", "internal", "the operation failed unexpectedly"),
281 }
282}
283
284fn answer(stream: &mut TcpStream, reply: &Reply, options: &Options) {
285 let (content_type, body) = match (reply.page, &reply.file) {
286 (Some((content_type, text)), _) => (content_type, text.as_bytes().to_vec()),
287 (None, Some(file)) => ("application/json", file.to_vec()),
288 (None, None) => ("application/json", serde_json::to_vec(&reply.body).unwrap_or_else(|_| b"{}".to_vec())),
289 };
290 let mut head = format!(
291 "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",
292 reply.status,
293 reply.reason,
294 body.len()
295 );
296 if reply.page.is_some() {
297 head.push_str(&format!("Content-Security-Policy: {STUDIO_POLICY}\r\nReferrer-Policy: no-referrer\r\nX-Frame-Options: DENY\r\n"));
298 }
299 if let Some(allow) = reply.allow {
300 head.push_str(&format!("Allow: {allow}\r\n"));
301 }
302 head.push_str("\r\n");
303 let _ = stream.set_write_timeout(Some(options.timeout));
304 if stream.write_all(head.as_bytes()).is_ok() && stream.write_all(&body).is_ok() {
305 let _ = stream.flush();
306 }
307 let _ = stream.shutdown(std::net::Shutdown::Write);
308 let started = Instant::now();
316 let _ = stream.set_read_timeout(Some(Duration::from_millis(50)));
317 let (mut scrap, mut discarded) = ([0u8; 4096], 0usize);
318 while discarded < 1_048_576 && started.elapsed() < Duration::from_millis(500) {
319 match stream.read(&mut scrap) {
320 Ok(0) | Err(_) => break,
321 Ok(n) => discarded += n,
322 }
323 }
324}
325
326fn serve_one(server: &Server, mut stream: TcpStream, options: &Options) {
327 let reply = match read_request(&mut stream, options) {
328 Ok(request) => route(server, &request, options),
329 Err(reply) => reply,
330 };
331 answer(&mut stream, &reply, options);
332}
333
334fn work(server: Arc<Server>, jobs: Arc<Mutex<Receiver<TcpStream>>>, options: Options) {
335 loop {
336 let next = jobs.lock().map(|queue| queue.recv());
337 match next {
338 Ok(Ok(stream)) => serve_one(&server, stream, &options),
339 _ => return,
340 }
341 }
342}
343
344pub fn serve(server: Server, listener: TcpListener, options: Options) -> kute::Result<()> {
346 let server = Arc::new(server);
347 let (send, receive) = sync_channel::<TcpStream>(options.queue.max(1));
348 let receive = Arc::new(Mutex::new(receive));
349 for _ in 0..options.workers.max(1) {
350 let (server, receive, options) = (server.clone(), receive.clone(), options.clone());
351 std::thread::spawn(move || work(server, receive, options));
352 }
353 for stream in listener.incoming() {
354 let stream = match stream {
355 Ok(s) => s,
356 Err(_) => continue,
357 };
358 match send.try_send(stream) {
359 Ok(()) => {}
360 Err(TrySendError::Full(mut stream)) => {
361 let busy = Reply { ..problem(503, "Service Unavailable", "busy", "every worker is busy and the queue is full; try again") };
363 let brief = Options { timeout: Duration::from_secs(1), ..options.clone() };
364 answer(&mut stream, &busy, &brief);
365 }
366 Err(TrySendError::Disconnected(_)) => return Err(kute::KuteError::Backend("the workers stopped".into())),
367 }
368 }
369 Ok(())
370}
371
372pub fn is_loopback(address: &SocketAddr) -> bool {
374 address.ip().is_loopback()
375}