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