Skip to main content

kute_cli/
http.rs

1//! A small HTTP service over the same five read-only operations as the MCP
2//! server, and through the same code: `encode`, `decode`, `inspect`,
3//! `compare`, `discover`, plus `capabilities`. Version 1 of the interface
4//! lives under `/v1/`.
5//!
6//! It is written directly on `std::net` so that every bound is in this
7//! file: one request per connection, a fixed number of workers, a fixed
8//! queue, a deadline on reading, a cap on the header block and on the body.
9//! It does not speak TLS and does not authenticate anyone, so it listens
10//! on the loopback interface unless told otherwise, and on loopback it
11//! answers only requests addressed to a loopback host name.
12
13use 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
21/// The operations a POST may name.
22pub const OPERATIONS: [&str; 5] = ["encode", "decode", "inspect", "compare", "discover"];
23
24/// Most bytes of request line and headers.
25const MAX_HEAD_BYTES: usize = 16 * 1024;
26
27/// What the service may cost, apart from the per-call limits of the
28/// operations themselves.
29#[derive(Clone, Debug)]
30pub struct Options {
31    /// Requests handled at once.
32    pub workers: usize,
33    /// Accepted connections that may wait for a worker. Past it, a
34    /// connection is answered 503 and closed.
35    pub queue: usize,
36    /// A request must arrive whole within this time, and its answer must
37    /// be taken within it.
38    pub timeout: Duration,
39    /// Longest request body.
40    pub max_body_bytes: u64,
41    /// Answer requests whatever host they name. Off, only loopback names
42    /// are answered, which keeps a web page from reaching the service
43    /// through a name it controls.
44    pub any_host: bool,
45    /// Serve the Studio page under `/studio`.
46    pub studio: bool,
47    /// Give the files of the held vocabularies to whoever asks, under
48    /// `/v1/vocabularies`. Off, those paths do not exist.
49    pub registry: bool,
50    /// Answer the five operations. Off, the service is a registry and
51    /// nothing else: no caller can make it compute.
52    pub operations: bool,
53    /// Other registries to ask for a vocabulary this one does not hold.
54    pub federation: Option<Arc<Federation>>,
55}
56
57/// Asking other registries, and what that may cost this one.
58///
59/// A vocabulary this registry does not hold is asked for upstream, in
60/// the order the upstreams were named, checked as `kute fetch` checks
61/// one (parsed, valid, the digest recomputed, test vectors run), and
62/// kept in memory to be given again. Every bound is here: one question
63/// upstream at a time, however many callers ask; a deadline and a size
64/// limit on each; a cache of fixed size; and a short memory of digests
65/// nobody had, so that asking for them again costs nothing.
66pub struct Federation {
67    pub upstreams: Vec<String>,
68    /// Longest wait for one upstream.
69    pub timeout: Duration,
70    /// Largest file taken from an upstream.
71    pub max_bytes: u64,
72    /// Most bytes of upstream files kept. The oldest go first.
73    pub cache_bytes: u64,
74    /// What an upstream file must pass, beyond being the content its
75    /// digest names: a signature from a key this registry trusts. With
76    /// none, a file is passed on whoever signed it or nobody.
77    check: Option<UpstreamCheck>,
78    asking: Mutex<()>,
79    kept: Mutex<std::collections::VecDeque<(String, Arc<[u8]>)>>,
80    absent: Mutex<std::collections::VecDeque<(String, Instant)>>,
81    /// For each upstream, when it last failed. One that failed is not
82    /// asked again for a while, so a slow or broken upstream named
83    /// first costs its timeout once and not on every question.
84    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
95/// How long a digest that no upstream had is remembered as absent.
96const ABSENT_FOR: Duration = Duration::from_secs(60);
97/// How long an upstream that failed, stalled or sent something else is left alone.
98const REST_FOR: Duration = Duration::from_secs(30);
99/// How many such digests are remembered.
100const 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    /// The file with this digest from the cache or, when `ask` is set,
120    /// from the first upstream that gives it. `Ok(None)` when nobody has it.
121    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        // One question upstream at a time. A caller who arrives meanwhile
136        // is told to come back, and its worker is free at once: callers
137        // asking for digests nobody has cannot hold every worker.
138        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                // Not asked, so it has not said no.
150                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                    // The right content without a signature this registry
156                    // requires is not kept: the next upstream may have it signed.
157                    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                    // Written out again here, not passed on as it came.
163                    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                // An upstream that failed or sent something else is passed
176                // over, and is not taken as having said the file is absent.
177                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
194/// The Studio page: three files compiled into the binary. The page loads
195/// nothing else and calls only `/v1/` on the origin it came from.
196const 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
202/// What the page may do, enforced by the browser: scripts and styles from
203/// this origin only, requests to this origin only, no frames, no forms
204/// posting elsewhere, nothing else at all.
205const 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    /// A file of the Studio page, as (content type, text), sent instead of `body`.
219    page: Option<(&'static str, &'static str)>,
220    /// A vocabulary file, sent instead of `body`.
221    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    /// Another registry is asking on a caller's behalf.
239    via: bool,
240}
241
242fn loopback_name(host: &str) -> bool {
243    let name = if let Some(rest) = host.strip_prefix('[') {
244        // [::1] or [::1]:port, and nothing else after the bracket
245        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
255/// Read one request within the deadline and the size limits.
256fn 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        // A name is a token: no space before the colon, no continuation
291        // line. Something in front of this service that read such a line
292        // another way would disagree with it about where the request ends.
293        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                // Digits only: `parse` alone would take "+5".
310                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        // Without the option the paths do not exist, and the answer does
382        // not say what is held.
383        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            // Who else this registry asks. What they hold is theirs to say.
392            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        // Only a digest reaches the lookup: a file is named by the hash
397        // of its content and by nothing else.
398        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                // Not held here. A registry asking for another is answered
406                // from what is here and kept, and no further.
407                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    // A JSON content type cannot be sent across origins by a web page
426    // without the browser asking first, and this service never agrees.
427    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    // A panic in an operation must not end the worker: with every worker
435    // gone the service would accept connections and answer none. No input
436    // is known to cause one.
437    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    // A request refused before it was read to its end leaves bytes
472    // unread, and closing over unread bytes resets the connection on
473    // some systems (seen on macOS), which can take the answer with it.
474    // So read what is left and throw it away: at most 1 MiB and half a
475    // second, then close whatever the client does. The answer is safe
476    // only if all of what was sent is read, so the limit is the largest
477    // unread request an answer is guaranteed to survive.
478    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
507/// Serve until the listener fails. Each connection carries one request.
508pub 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                // Answered here, without reading: reading is what a worker is for.
525                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
535/// Whether an address is on the loopback interface.
536pub fn is_loopback(address: &SocketAddr) -> bool {
537    address.ip().is_loopback()
538}