提交 Haven Android 仓库源码 v5.87.79

This commit is contained in:
ali
2026-09-10 13:45:36 +08:00
parent 87b452c4dc
commit 22f4ca5830
2524 changed files with 599455 additions and 1 deletions
+30
View File
@@ -0,0 +1,30 @@
plugins {
alias(libs.plugins.android.library)
}
android {
namespace = "sh.haven.core.mcp"
compileSdk = 37
defaultConfig {
minSdk = 26
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
}
dependencies {
testImplementation(libs.junit)
// Real org.json for unit tests (android.jar's is stubbed under
// the default unit-test configuration).
testImplementation("org.json:json:20260814")
}
kotlin {
compilerOptions {
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
}
}
@@ -0,0 +1,96 @@
package sh.haven.core.mcp
import java.io.BufferedInputStream
import java.io.InputStream
import java.io.OutputStream
/**
* Keep-alive HTTP/1.1 connection loop (#mcp-backbone Stage 4). Serves up to
* [MAX_KEEPALIVE_REQUESTS] requests off one stream pair, which is what lets an
* MCP client hold a single warm connection instead of dialling per request —
* the contract the workstation failover proxy existed to paper over.
*/
/**
* Requests served per connection before the server closes it. A finite cap so
* one peer can't hold a worker thread forever; far above anything a real MCP
* session sends in one connection, and a client just reconnects when it hits.
*/
const val MAX_KEEPALIVE_REQUESTS: Int = 1000
/** One HTTP response as data — built by the request handler, written by the loop. */
class HttpResponse(
val status: Int,
val statusText: String,
val body: ByteArray,
val contentType: String? = null,
/** Extra response headers, e.g. `Mcp-Session-Id`, CORS. */
val headers: List<Pair<String, String>> = emptyList(),
)
/** Convenience: a plain-text response ([status] with [text] as both reason and body). */
fun textResponse(status: Int, text: String): HttpResponse =
HttpResponse(status, text, text.toByteArray(Charsets.UTF_8), "text/plain; charset=utf-8")
/**
* Serve requests off one connection until the peer closes, asks to close
* (`Connection: close`), speaks a non-1.1 HTTP version, sends something
* malformed, or [maxRequests] is reached. [handler] maps each parsed request
* to a response; the loop owns framing and the `Connection` header.
*
* A read timeout (idle keep-alive peer) after at least one served request is a
* normal close; on the FIRST request it propagates so the caller can log it
* (same visibility the one-shot server had).
*/
fun serveHttpConnection(
input: InputStream,
output: OutputStream,
maxRequests: Int = MAX_KEEPALIVE_REQUESTS,
handler: (ParsedHttpRequest) -> HttpResponse,
) {
// Buffered so per-byte header scanning isn't a syscall storm.
val bin = if (input is BufferedInputStream) input else BufferedInputStream(input)
var served = 0
while (served < maxRequests) {
val res = try {
parseHttpRequest(bin)
} catch (e: java.net.SocketTimeoutException) {
if (served == 0) throw e
return // idle keep-alive connection timing out is a normal close
}
when (res) {
is HttpParseResult.Closed -> return
is HttpParseResult.Fail -> {
writeHttpResponse(output, textResponse(res.status, res.reason), keepAlive = false)
return
}
is HttpParseResult.Ok -> {
val req = res.request
served++
val response = handler(req)
val peerWantsClose =
req.headers["connection"]?.contains("close", ignoreCase = true) == true
val keep = !peerWantsClose &&
req.httpVersion.equals("HTTP/1.1", ignoreCase = true) &&
served < maxRequests
writeHttpResponse(output, response, keepAlive = keep)
if (!keep) return
}
}
}
}
/** Write [response] with correct framing and an explicit `Connection` header. */
fun writeHttpResponse(out: OutputStream, response: HttpResponse, keepAlive: Boolean) {
val head = buildString {
append("HTTP/1.1 ${response.status} ${response.statusText}\r\n")
response.contentType?.let { append("Content-Type: $it\r\n") }
append("Content-Length: ${response.body.size}\r\n")
response.headers.forEach { (k, v) -> append("$k: $v\r\n") }
append("Connection: ${if (keepAlive) "keep-alive" else "close"}\r\n")
append("\r\n")
}
out.write(head.toByteArray(Charsets.UTF_8))
if (response.body.isNotEmpty()) out.write(response.body)
out.flush()
}
@@ -0,0 +1,134 @@
package sh.haven.core.mcp
import java.io.InputStream
/**
* Byte-level HTTP/1.1 framing for the MCP backbone (#mcp-backbone Stage 4 —
* Layer A). Extracted from the server so the parser, its DoS bounds, and the
* keep-alive connection loop ([serveHttpConnection]) are one shared,
* socket-free-testable core rather than transport-specific copies.
*/
/**
* Hard cap on a request body (#mcp-backbone Stage 0). The body buffer is sized
* from the client-supplied `Content-Length`; without a bound, a hostile
* `Content-Length: 2000000000` forces a multi-GB allocation → OutOfMemoryError
* before a byte of body arrives. MCP request bodies are small JSON (bulk bytes
* go out-of-band via serve_file), so 8 MiB is generous headroom. A larger or
* negative length is refused with 413 before any allocation.
*/
const val MAX_BODY_BYTES: Int = 8 * 1024 * 1024
/**
* Hard cap on the HTTP header block (#mcp-backbone Stage 0). The header reader
* accumulates bytes until the CRLFCRLF terminator; without a bound a peer that
* never sends the blank line (Slowloris) grows the buffer until the socket
* timeout. 64 KiB is far above any real MCP request's headers.
*/
const val MAX_HEADER_BYTES: Int = 64 * 1024
/** Outcome of [parseHttpRequest]. */
sealed interface HttpParseResult {
data class Ok(val request: ParsedHttpRequest) : HttpParseResult
/** Malformed or oversized — [status]/[reason] is the HTTP error to return. */
data class Fail(val status: Int, val reason: String) : HttpParseResult
/** Clean EOF before any bytes — the peer closed without sending a request. */
object Closed : HttpParseResult
}
/**
* One parsed HTTP request. [headers] keys are lowercased; [body] is UTF-8.
* [httpVersion] is the request-line version token (`HTTP/1.1`); anything else
* gets close-per-response semantics from [serveHttpConnection].
*/
data class ParsedHttpRequest(
val method: String,
val path: String,
val headers: Map<String, String>,
val body: String,
val httpVersion: String = "HTTP/1.1",
)
/**
* Byte-accurate HTTP/1.1 request parser (#mcp-backbone Stage 0). Reads the
* header block up to the CRLFCRLF terminator (bounded by [MAX_HEADER_BYTES]),
* then reads exactly `Content-Length` BYTES (bounded by [MAX_BODY_BYTES]) and
* decodes them as UTF-8.
*
* Replaces a char-based read that (a) sized the body buffer from an unbounded
* `Content-Length` (a hostile length OOM'd the process) and (b) counted CHARS
* against a BYTE length, so any multibyte-UTF-8 body under-filled the loop and
* stalled the read until the 70 s socket timeout. Pure over an [InputStream] so
* it is unit-testable without a socket.
*/
fun parseHttpRequest(input: InputStream): HttpParseResult {
val head = java.io.ByteArrayOutputStream(512)
val cr = '\r'.code
val lf = '\n'.code
var state = 0 // progress through the CR LF CR LF terminator
while (true) {
if (head.size() >= MAX_HEADER_BYTES) {
return HttpParseResult.Fail(431, "Request Header Fields Too Large")
}
val b = input.read()
if (b < 0) {
return if (head.size() == 0) HttpParseResult.Closed
else HttpParseResult.Fail(400, "Bad Request")
}
head.write(b)
state = when {
state == 0 && b == cr -> 1
state == 1 && b == lf -> 2
state == 2 && b == cr -> 3
state == 3 && b == lf -> 4
b == cr -> 1
else -> 0
}
if (state == 4) break
}
// Headers are ASCII/latin1; decode the block that way for line splitting.
val lines = head.toString("ISO-8859-1").split("\r\n")
val parts = lines.firstOrNull().orEmpty().split(" ")
if (parts.size < 3) return HttpParseResult.Fail(400, "Bad Request")
val headers = HashMap<String, String>()
for (i in 1 until lines.size) {
val line = lines[i]
if (line.isEmpty()) break
val colon = line.indexOf(':')
if (colon > 0) {
headers[line.substring(0, colon).trim().lowercase()] = line.substring(colon + 1).trim()
}
}
val contentLength = headers["content-length"]?.toIntOrNull() ?: 0
if (contentLength !in 0..MAX_BODY_BYTES) return HttpParseResult.Fail(413, "Payload Too Large")
val body = if (contentLength > 0) {
val buf = ByteArray(contentLength)
var read = 0
while (read < contentLength) {
val n = input.read(buf, read, contentLength - read)
if (n < 0) return HttpParseResult.Fail(400, "Bad Request") // body truncated by EOF
read += n
}
String(buf, Charsets.UTF_8)
} else ""
return HttpParseResult.Ok(ParsedHttpRequest(parts[0], parts[1], headers, body, parts[2]))
}
/**
* True iff [origin] (an HTTP `Origin` header, `scheme://host[:port]`) names a
* loopback host. The browser DNS-rebinding / CSRF guard rejects a POST carrying
* any other Origin — a page served from a real host sends its domain as the
* Origin host, never `127.0.0.1`. A `null`/opaque origin (sandboxed iframe,
* `file://`) is treated as non-loopback and denied. Non-browser MCP clients send
* no Origin at all and bypass the check entirely.
*/
fun isLoopbackOrigin(origin: String): Boolean {
val afterScheme = origin.substringAfter("://", "").substringBefore('/')
val host = if (afterScheme.startsWith("[")) {
val end = afterScheme.indexOf(']')
if (end > 0) afterScheme.substring(1, end) else afterScheme
} else {
afterScheme.substringBefore(':')
}
return host == "localhost" || host == "::1" || host.startsWith("127.")
}
@@ -0,0 +1,54 @@
package sh.haven.core.mcp
import org.json.JSONObject
/**
* JSON-RPC 2.0 frame builders + protocol error types shared by Haven's MCP
* server and its guest-MCP client (#mcp-backbone Stage 4 — Layer A), so the
* two sides can't drift. Note: MCP revision 2025-06-18 REMOVED JSON-RPC
* batching, so a single frame per body is the spec-correct shape, not a gap.
*/
/** A request (or, with a null [id], a notification) frame. */
fun jsonRpcRequest(id: Any?, method: String, params: JSONObject? = null): JSONObject =
JSONObject().apply {
put("jsonrpc", "2.0")
if (id != null) put("id", id)
put("method", method)
if (params != null) put("params", params)
}
fun jsonRpcResult(id: Any?, result: Any?): String {
val obj = JSONObject()
obj.put("jsonrpc", "2.0")
if (id != null) obj.put("id", id)
obj.put("result", result ?: JSONObject.NULL)
return obj.toString()
}
fun jsonRpcError(id: Any?, code: Int, message: String): String {
val obj = JSONObject()
obj.put("jsonrpc", "2.0")
if (id != null) obj.put("id", id) else obj.put("id", JSONObject.NULL)
obj.put("error", JSONObject().apply {
put("code", code)
put("message", message)
})
return obj.toString()
}
/** Lightweight error type carrying a JSON-RPC error code. */
open class McpError(val code: Int, message: String) : RuntimeException(message)
/**
* Raised by the server's dispatcher when a non-initialize request presents an
* `Mcp-Session-Id` it doesn't recognise. The HTTP layer maps this to **404**,
* which is the streamable-HTTP-spec signal that tells the client to
* re-`initialize` and retry — fixing the "won't reconnect after Haven restart
* without dropping the Claude Code session" wedge.
*
* The error message is informational only; clients react to the 404
* status, not the body.
*/
class SessionExpiredError :
McpError(-32001, "MCP session expired; re-initialize")
@@ -0,0 +1,98 @@
package sh.haven.core.mcp
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
/**
* Pins the keep-alive connection loop (#mcp-backbone Stage 4): several
* requests served off ONE stream pair — the property that retires the
* connection-per-request contract (and with it the failover proxy's reason
* to exist) — plus the close conditions: `Connection: close`, HTTP/1.0,
* malformed input, and the per-connection request cap.
*/
class HttpConnectionTest {
private fun request(body: String, extraHeaders: String = "", version: String = "HTTP/1.1"): String =
"POST /mcp $version\r\nContent-Length: ${body.toByteArray().size}\r\n$extraHeaders\r\n$body"
/** Serve [raw] and return (responses-as-text, number of handler calls). */
private fun serve(raw: String, maxRequests: Int = MAX_KEEPALIVE_REQUESTS): Pair<String, Int> {
val out = ByteArrayOutputStream()
var calls = 0
serveHttpConnection(ByteArrayInputStream(raw.toByteArray(Charsets.UTF_8)), out, maxRequests) { req ->
calls++
HttpResponse(200, "OK", "echo:${req.body}".toByteArray(), "text/plain")
}
return out.toString(Charsets.UTF_8) to calls
}
@Test
fun `two pipelined requests are served on one connection`() {
val (text, calls) = serve(request("""{"a":1}""") + request("""{"b":2}"""))
assertEquals(2, calls)
assertTrue("first response missing", text.contains("echo:{\"a\":1}"))
assertTrue("second response missing", text.contains("echo:{\"b\":2}"))
assertTrue("first response must advertise keep-alive", text.contains("Connection: keep-alive"))
}
@Test
fun `connection close header ends the loop after one response`() {
val (text, calls) = serve(
request("""{"a":1}""", extraHeaders = "Connection: close\r\n") + request("""{"b":2}"""),
)
assertEquals("second request must not be served after Connection: close", 1, calls)
assertTrue(text.contains("Connection: close"))
assertFalse(text.contains("echo:{\"b\":2}"))
}
@Test
fun `http 1_0 requests default to close`() {
val (text, calls) = serve(request("""{"a":1}""", version = "HTTP/1.0") + request("""{"b":2}"""))
assertEquals(1, calls)
assertTrue(text.contains("Connection: close"))
}
@Test
fun `the per-connection request cap closes the connection`() {
val (text, calls) = serve(request("x") + request("y") + request("z"), maxRequests = 2)
assertEquals(2, calls)
assertFalse("third request beyond the cap must not be served", text.contains("echo:z"))
// The capped (second) response must tell the client to reconnect.
assertTrue(text.trimEnd().split("Connection: ").last().startsWith("close"))
}
@Test
fun `malformed input gets an error response and a close`() {
val out = ByteArrayOutputStream()
var calls = 0
serveHttpConnection(
ByteArrayInputStream("POST /mcp HTTP/1.1\r\nContent-Length: -5\r\n\r\n".toByteArray()),
out,
) { calls++; textResponse(200, "OK") }
assertEquals(0, calls)
val text = out.toString(Charsets.UTF_8)
assertTrue(text.startsWith("HTTP/1.1 413"))
assertTrue(text.contains("Connection: close"))
}
@Test
fun `peer closing between requests is a clean end`() {
val (_, calls) = serve(request("""{"a":1}""")) // EOF right after request 1
assertEquals(1, calls)
}
@Test
fun `responses carry correct content-length framing for multibyte bodies`() {
val out = ByteArrayOutputStream()
serveHttpConnection(
ByteArrayInputStream(request("x").toByteArray(Charsets.UTF_8)), out,
) { HttpResponse(200, "OK", "中文😀".toByteArray(Charsets.UTF_8), "text/plain") }
val text = out.toByteArray().toString(Charsets.UTF_8)
val expected = "中文😀".toByteArray(Charsets.UTF_8).size
assertTrue("byte-accurate Content-Length", text.contains("Content-Length: $expected"))
}
}
@@ -0,0 +1,97 @@
package sh.haven.core.mcp
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.ByteArrayInputStream
/**
* Pins the byte-level HTTP framing (#mcp-backbone Stage 0). The parser is pure
* over an InputStream, so these run without a socket or Robolectric. They guard
* the two defects the rewrite fixed — unbounded Content-Length (OOM) and a
* char-vs-byte body read that hung on multibyte UTF-8 — plus the header bound
* and the Origin/CSRF helper.
*/
class HttpFramingTest {
private fun parse(raw: String) =
parseHttpRequest(ByteArrayInputStream(raw.toByteArray(Charsets.UTF_8)))
@Test
fun `parses a normal POST with a json body`() {
val body = """{"jsonrpc":"2.0","id":1,"method":"ping"}"""
val raw = "POST /mcp HTTP/1.1\r\nHost: 127.0.0.1:8730\r\n" +
"Content-Length: ${body.toByteArray().size}\r\n\r\n$body"
val res = parse(raw)
assertTrue(res is HttpParseResult.Ok)
res as HttpParseResult.Ok
assertEquals("POST", res.request.method)
assertEquals("/mcp", res.request.path)
assertEquals(body, res.request.body)
}
@Test
fun `multibyte utf8 body is read by byte length, not char count`() {
// '中文' is 3 bytes/char, '😀' is a 4-byte surrogate pair — so the byte
// Content-Length exceeds the char count. The old char-counting loop
// under-filled and stalled until the socket timeout; this must not.
val body = """{"text":"中文😀"}"""
val bytes = body.toByteArray(Charsets.UTF_8)
val raw = "POST /mcp HTTP/1.1\r\nContent-Length: ${bytes.size}\r\n\r\n"
.toByteArray(Charsets.UTF_8) + bytes
val res = parseHttpRequest(ByteArrayInputStream(raw))
assertTrue(res is HttpParseResult.Ok)
assertEquals(body, (res as HttpParseResult.Ok).request.body)
}
@Test
fun `oversized content-length is refused before allocation`() {
val res = parse("POST /mcp HTTP/1.1\r\nContent-Length: 2000000000\r\n\r\n")
assertTrue(res is HttpParseResult.Fail)
assertEquals(413, (res as HttpParseResult.Fail).status)
}
@Test
fun `negative content-length is refused`() {
val res = parse("POST /mcp HTTP/1.1\r\nContent-Length: -5\r\n\r\n")
assertEquals(413, (res as HttpParseResult.Fail).status)
}
@Test
fun `an unterminated header block is bounded, not read forever`() {
// No terminating CRLFCRLF; a single header far past MAX_HEADER_BYTES.
val res = parse("POST /mcp HTTP/1.1\r\nX-Pad: " + "a".repeat(70 * 1024))
assertTrue(res is HttpParseResult.Fail)
assertEquals(431, (res as HttpParseResult.Fail).status)
}
@Test
fun `a body truncated by EOF fails rather than hanging`() {
val res = parse("POST /mcp HTTP/1.1\r\nContent-Length: 100\r\n\r\nshort")
assertTrue(res is HttpParseResult.Fail)
assertEquals(400, (res as HttpParseResult.Fail).status)
}
@Test
fun `a clean close before any bytes is Closed`() {
assertTrue(parse("") is HttpParseResult.Closed)
}
@Test
fun `header names are lowercased and parsed`() {
val res = parse("GET /mcp HTTP/1.1\r\nMcp-Session-Id: abc\r\n\r\n") as HttpParseResult.Ok
assertEquals("abc", res.request.headers["mcp-session-id"])
}
@Test
fun `loopback origins are accepted and real hosts rejected`() {
assertTrue(isLoopbackOrigin("http://127.0.0.1:8730"))
assertTrue(isLoopbackOrigin("http://localhost:8788"))
assertTrue(isLoopbackOrigin("http://[::1]:8730"))
assertTrue(isLoopbackOrigin("http://127.5.5.5"))
assertFalse(isLoopbackOrigin("https://evil.example"))
assertFalse(isLoopbackOrigin("http://192.168.1.5:8730"))
assertFalse(isLoopbackOrigin("null"))
}
}