feat: add I2P BitTorrent engine, DHT, and Firefox torrent extension
- Add pure-MoonBit bittorrent package: bencode codec, metainfo/magnet parsing with path traversal checks, peer wire protocol (BEP 10/9), and I2P Kademlia DHT with KRPC and 54-byte compact nodes - Add SHA-1 primitive in crypto for torrent info hashes - Add router torrent API and engine, enabled with --torrent-api (default 127.0.0.1:4445) and --download-dir - Add Firefox WebExtension torrent manager with native messaging host and packed .xpi - Add scripts to build a standalone Firefox + router AppImage and install the native host - Add just targets (proxy, appimage, extension), README docs, and ignore .cache/ and dist/
This commit is contained in:
1 parent
14eae00f5c
commit
fbe6818c4e
37 files changed
+8543
-9
No files matched your search
+15
-3
@@ -446,12 +446,23 @@ fn send_http_proxy_error(
|
||||
status : Int32,
|
||||
reason : String,
|
||||
detail : String,
|
||||
refresh_sec~ : Int32 = 0,
|
||||
) -> Unit {
|
||||
let safe_reason = escape_html(reason)
|
||||
let safe_detail = escape_html(detail)
|
||||
let body = "<!doctype html><html><head><meta charset=\"utf-8\"><title>\{status} \{safe_reason}</title></head><body><h1>\{status} \{safe_reason}</h1><p>\{safe_detail}</p><hr><small>moon-i2p HTTP Proxy</small></body></html>\n"
|
||||
let refresh_meta = if refresh_sec > 0 {
|
||||
"<meta http-equiv=\"refresh\" content=\"\{refresh_sec}\">"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
let refresh_hdr = if refresh_sec > 0 {
|
||||
"Retry-After: \{refresh_sec}\r\n"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
let body = "<!doctype html><html><head><meta charset=\"utf-8\">\{refresh_meta}<title>\{status} \{safe_reason}</title></head><body><h1>\{status} \{safe_reason}</h1><p>\{safe_detail}</p><hr><small>moon-i2p HTTP Proxy</small></body></html>\n"
|
||||
let body_bytes = @encoding.string_to_utf8_bytes(body)
|
||||
let hdr = "HTTP/1.1 \{status} \{reason}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: \{body_bytes.length()}\r\nConnection: close\r\n\r\n"
|
||||
let hdr = "HTTP/1.1 \{status} \{reason}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: \{body_bytes.length()}\r\n\{refresh_hdr}Connection: close\r\n\r\n"
|
||||
let _ = sock.write_all(@encoding.string_to_utf8_bytes(hdr)) catch {
|
||||
_ => return
|
||||
}
|
||||
@@ -788,7 +799,8 @@ fn Router::step_http_proxy(self : Router) -> Bool {
|
||||
pc.sock,
|
||||
503,
|
||||
"Service Unavailable",
|
||||
"I2P router is still bootstrapping tunnels (inbound=\{self.inbound_tunnel_count()}, outbound=\{self.outbound_tunnel_count()}, peers=\{self.peer_count()}). Retry shortly.",
|
||||
"I2P router is still bootstrapping tunnels (inbound=\{self.inbound_tunnel_count()}, outbound=\{self.outbound_tunnel_count()}, peers=\{self.peer_count()}). Retrying automatically...",
|
||||
refresh_sec=3,
|
||||
)
|
||||
pc.sock.close()
|
||||
pc.closed = true
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
"experiments/moon_i2p/ratchet",
|
||||
"experiments/moon_i2p/streaming",
|
||||
"experiments/moon_i2p/sam",
|
||||
"experiments/moon_i2p/bittorrent",
|
||||
}
|
||||
|
||||
supported_targets = "-all+native"
|
||||
@@ -71,6 +71,9 @@ pub struct Router {
|
||||
priv mut http_proxy_listener : @ntcp2_net.TcpListener?
|
||||
priv http_proxy_conns : Array[HttpProxyConn]
|
||||
priv mut http_proxy_session_id : String?
|
||||
priv mut torrent_engine : TorrentEngine?
|
||||
priv mut torrent_api_listener : @ntcp2_net.TcpListener?
|
||||
priv torrent_api_conns : Array[TorrentApiConn]
|
||||
priv mut lease_rr : Int32
|
||||
priv mut outbound_rr : Int32
|
||||
priv mut last_bootstrap_ms : UInt64
|
||||
@@ -263,6 +266,9 @@ pub fn Router::start(
|
||||
http_proxy_listener: None,
|
||||
http_proxy_conns: [],
|
||||
http_proxy_session_id: None,
|
||||
torrent_engine: None,
|
||||
torrent_api_listener: None,
|
||||
torrent_api_conns: [],
|
||||
lease_rr: 0,
|
||||
outbound_rr: 0,
|
||||
last_bootstrap_ms: 0UL,
|
||||
@@ -432,6 +438,19 @@ pub fn Router::reseed_from_url(
|
||||
|
||||
///|
|
||||
pub fn Router::close(self : Router) -> Unit {
|
||||
for ac in self.torrent_api_conns {
|
||||
if !ac.closed {
|
||||
ac.sock.close()
|
||||
ac.closed = true
|
||||
}
|
||||
}
|
||||
match self.torrent_api_listener {
|
||||
Some(l) => {
|
||||
l.close()
|
||||
self.torrent_api_listener = None
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
for pc in self.http_proxy_conns {
|
||||
if !pc.closed {
|
||||
pc.sock.close()
|
||||
@@ -564,6 +583,12 @@ pub fn Router::step(self : Router, poll_ms~ : Int32 = 10) -> Unit {
|
||||
if self.step_http_proxy() {
|
||||
did_work = true
|
||||
}
|
||||
if self.step_torrent_engine() {
|
||||
did_work = true
|
||||
}
|
||||
if self.step_torrent_api() {
|
||||
did_work = true
|
||||
}
|
||||
self.poll_netdb_lookups()
|
||||
self.poll_tunnel_builds()
|
||||
if self.public_mode {
|
||||
|
||||
@@ -504,3 +504,220 @@ test "Proposal 157 Outbound tunnel replying via Inbound tunnel with OBEP ECIES G
|
||||
}
|
||||
assert_true(built_out)
|
||||
}
|
||||
|
||||
///|
|
||||
fn test_http_api_request(
|
||||
port : Int32,
|
||||
rs : Array[@router.Router],
|
||||
http_method : String,
|
||||
path : String,
|
||||
host_hdr : String,
|
||||
headers : Array[(String, String)],
|
||||
body : String,
|
||||
) -> String raise {
|
||||
let sock = @ntcp2_net.TcpSocket::connect("127.0.0.1", port)
|
||||
defer sock.close()
|
||||
let body_bytes = @encoding.string_to_utf8_bytes(body)
|
||||
let sb = StringBuilder()
|
||||
sb.write_string("\{http_method} \{path} HTTP/1.1\r\n")
|
||||
sb.write_string("Host: \{host_hdr}\r\n")
|
||||
for h in headers {
|
||||
sb.write_string("\{h.0}: \{h.1}\r\n")
|
||||
}
|
||||
if body_bytes.length() > 0 {
|
||||
sb.write_string("Content-Length: \{body_bytes.length()}\r\n")
|
||||
}
|
||||
sb.write_string("Connection: close\r\n\r\n")
|
||||
if body.length() > 0 {
|
||||
sb.write_string(body)
|
||||
}
|
||||
sock.write_all(@encoding.string_to_utf8_bytes(sb.to_string()))
|
||||
let resp_bytes = pump_read_until_eof(sock, rs, max_ticks=1500)
|
||||
@encoding.utf8_bytes_to_string(resp_bytes)
|
||||
}
|
||||
|
||||
///|
|
||||
test "2-router I2P DHT + BEP 9 Magnet + Streaming torrent download and HTTP API security" {
|
||||
let seed_dir = "/tmp/moon_i2p_bt_seed"
|
||||
let dl_dir = "/tmp/moon_i2p_bt_dl"
|
||||
@ntcp2_net.mkdir_p(seed_dir)
|
||||
@ntcp2_net.mkdir_p(dl_dir)
|
||||
|
||||
// Deterministic 40 KiB payload spanning 3 x 16 KiB pieces (16384 + 16384 + 8192)
|
||||
let total_len = 40960
|
||||
let raw_arr = FixedArray::make(total_len, b'\x00')
|
||||
for i = 0; i < total_len; i = i + 1 {
|
||||
raw_arr[i] = ((i * 17 + 5) % 251).to_byte()
|
||||
}
|
||||
let payload = Bytes::from_array(raw_arr)
|
||||
@ntcp2_net.write_file_at(seed_dir + "/sample.bin", 0L, payload)
|
||||
// Poison any prior download artifact so stale pieces cannot pass SHA-1
|
||||
@ntcp2_net.write_file_at(
|
||||
dl_dir + "/sample.bin",
|
||||
0L,
|
||||
Bytes::make(total_len, b'\xFF'),
|
||||
)
|
||||
|
||||
let piece_hashes = @encoding.Writer::new(capacity=60)
|
||||
piece_hashes.write_bytes(@crypto.sha1(payload[:16384].to_owned()))
|
||||
piece_hashes.write_bytes(@crypto.sha1(payload[16384:32768].to_owned()))
|
||||
piece_hashes.write_bytes(@crypto.sha1(payload[32768:].to_owned()))
|
||||
let torrent_bytes = @bittorrent.bencode_encode(
|
||||
BDict([
|
||||
(
|
||||
b"info",
|
||||
BDict([
|
||||
(b"length", BInt(total_len.to_int64())),
|
||||
(b"name", BBytes(b"sample.bin")),
|
||||
(b"piece length", BInt(16384L)),
|
||||
(b"pieces", BBytes(piece_hashes.to_bytes())),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
)
|
||||
let meta = @bittorrent.parse_torrent(torrent_bytes)
|
||||
let ih_hex = @encoding.hex_encode(meta.info_hash)
|
||||
|
||||
let router_a = @router.Router::start({
|
||||
sam_host: "127.0.0.1",
|
||||
sam_port: 0,
|
||||
ntcp2_host: "127.0.0.1",
|
||||
ntcp2_port: 0,
|
||||
})
|
||||
defer router_a.close()
|
||||
let router_b = @router.Router::start({
|
||||
sam_host: "127.0.0.1",
|
||||
sam_port: 0,
|
||||
ntcp2_host: "127.0.0.1",
|
||||
ntcp2_port: 0,
|
||||
})
|
||||
defer router_b.close()
|
||||
|
||||
let _ = router_a.netdb.store_router_info(router_b.router_info)
|
||||
let _ = router_b.netdb.store_router_info(router_a.router_info)
|
||||
|
||||
router_a.enable_torrent_engine(download_dir=seed_dir)
|
||||
let seeded_ih = router_a.add_seed_torrent(torrent_bytes, seed_dir)
|
||||
assert_eq(seeded_ih, ih_hex)
|
||||
|
||||
let a_hash = match router_a.torrent_session_hash() {
|
||||
Some(h) => h
|
||||
None => fail("router_a missing __torrent__ session hash")
|
||||
}
|
||||
let now_sec = @ntcp2_net.unix_time_sec()
|
||||
let ls2_a = match router_a.netdb.get_lease_set2(a_hash, now_sec) {
|
||||
Some(l) => l
|
||||
None => fail("router_a missing __torrent__ LeaseSet2")
|
||||
}
|
||||
let _ = router_b.netdb.store_lease_set2(ls2_a, now_sec)
|
||||
|
||||
let api_port = router_b.start_torrent_api(
|
||||
host="127.0.0.1",
|
||||
port=0,
|
||||
download_dir=dl_dir,
|
||||
)
|
||||
assert_true(api_port > 0)
|
||||
let rs = [router_a, router_b]
|
||||
|
||||
// Security check 1: POST without X-Moon-I2P: 1 is rejected with 403
|
||||
let unauth_resp = test_http_api_request(
|
||||
api_port,
|
||||
rs,
|
||||
"POST",
|
||||
"/api/torrents/magnet",
|
||||
"127.0.0.1:\{api_port}",
|
||||
[("Content-Type", "application/json")],
|
||||
"{\"uri\":\"magnet:?xt=urn:btih:\{ih_hex}\"}",
|
||||
)
|
||||
assert_true(unauth_resp.contains("403 Forbidden"))
|
||||
|
||||
// Security check 2: non-loopback Host header (DNS rebinding guard) is rejected with 403
|
||||
let evil_host_resp = test_http_api_request(
|
||||
api_port,
|
||||
rs,
|
||||
"GET",
|
||||
"/api/status",
|
||||
"evil.example",
|
||||
[],
|
||||
"",
|
||||
)
|
||||
assert_true(evil_host_resp.contains("403 Forbidden"))
|
||||
|
||||
// Bootstrap Router B's I2P DHT onto Router A and add pure magnet URI (no trackers/peers)
|
||||
let boot_resp = test_http_api_request(
|
||||
api_port,
|
||||
rs,
|
||||
"POST",
|
||||
"/api/dht/bootstrap",
|
||||
"127.0.0.1:\{api_port}",
|
||||
[("Content-Type", "application/json"), ("X-Moon-I2P", "1")],
|
||||
"{\"b32\":\"\{router_a.torrent_b32_address()}\",\"port\":6881}",
|
||||
)
|
||||
assert_true(boot_resp.contains("200 OK"))
|
||||
assert_true(boot_resp.contains("\"ok\":true"))
|
||||
|
||||
let mag_resp = test_http_api_request(
|
||||
api_port,
|
||||
rs,
|
||||
"POST",
|
||||
"/api/torrents/magnet",
|
||||
"127.0.0.1:\{api_port}",
|
||||
[("Content-Type", "application/json"), ("X-Moon-I2P", "1")],
|
||||
"{\"uri\":\"magnet:?xt=urn:btih:\{ih_hex}&dn=sample.bin\"}",
|
||||
)
|
||||
assert_true(mag_resp.contains("200 OK"))
|
||||
assert_true(mag_resp.contains(ih_hex))
|
||||
|
||||
// Step both routers until DHT discovery -> BEP 9 metadata -> full 3-piece download finishes
|
||||
let mut completed = false
|
||||
for iter = 0; iter < 60; iter = iter + 1 {
|
||||
step_routers(rs, 25)
|
||||
if iter % 4 == 0 {
|
||||
let tlist = test_http_api_request(
|
||||
api_port,
|
||||
rs,
|
||||
"GET",
|
||||
"/api/torrents",
|
||||
"127.0.0.1:\{api_port}",
|
||||
[],
|
||||
"",
|
||||
)
|
||||
if tlist.contains("\"completed\":true") {
|
||||
completed = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_true(completed)
|
||||
|
||||
// Verify downloaded file matches original bytes bit-for-bit
|
||||
let downloaded = @ntcp2_net.read_file_bytes(dl_dir + "/sample.bin")
|
||||
assert_eq(downloaded, payload)
|
||||
|
||||
// Verify DHT routing table & stats recorded live exchanges
|
||||
let status_json = test_http_api_request(
|
||||
api_port,
|
||||
rs,
|
||||
"GET",
|
||||
"/api/status",
|
||||
"127.0.0.1:\{api_port}",
|
||||
[],
|
||||
"",
|
||||
)
|
||||
assert_true(status_json.contains("\"completed_torrents\":1"))
|
||||
assert_true(!status_json.contains("\"queries_sent\":0"))
|
||||
assert_true(!status_json.contains("\"responses_recv\":0"))
|
||||
assert_true(!status_json.contains("\"routing_table_nodes\":0"))
|
||||
assert_true(!status_json.contains("\"peers_discovered\":0"))
|
||||
|
||||
let nodes_json = test_http_api_request(
|
||||
api_port,
|
||||
rs,
|
||||
"GET",
|
||||
"/api/dht/nodes",
|
||||
"127.0.0.1:\{api_port}",
|
||||
[],
|
||||
"",
|
||||
)
|
||||
assert_true(nodes_json.contains(router_a.torrent_b32_address()))
|
||||
}
|
||||
@@ -0,0 +1,907 @@
|
||||
///|
|
||||
/// Localhost-only JSON + .torrent HTTP control API for the Firefox WebExtension
|
||||
/// and CLI tools (`--torrent-api 127.0.0.1:4445`).
|
||||
///
|
||||
/// Security model:
|
||||
/// - Rejects any non-loopback `Host` header (`403 Forbidden`) to prevent DNS rebinding.
|
||||
/// - Requires `X-Moon-I2P: 1` header on all mutating `POST` endpoints (`403 Forbidden`)
|
||||
/// to prevent cross-site form/fetch CSRF from arbitrary web pages.
|
||||
/// - CORS `Access-Control-Allow-Origin` is echoed ONLY for `moz-extension://`,
|
||||
/// `http://127.0.0.1`, or `http://localhost` origins.
|
||||
|
||||
///|
|
||||
priv struct TorrentApiConn {
|
||||
sock : @ntcp2_net.TcpSocket
|
||||
recv_buf : Array[Byte]
|
||||
mut hdr_parsed : Bool
|
||||
mut http_method : String
|
||||
mut path : String
|
||||
mut host_hdr : String
|
||||
mut origin_hdr : String
|
||||
mut has_csrf_hdr : Bool
|
||||
mut content_type : String
|
||||
mut content_len : Int32
|
||||
body_buf : Array[Byte]
|
||||
started_ms : UInt64
|
||||
mut closed : Bool
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Router::start_torrent_api(
|
||||
self : Router,
|
||||
host~ : String = "127.0.0.1",
|
||||
port~ : Int32 = 4445,
|
||||
download_dir~ : String = "",
|
||||
) -> Int32 raise RouterError {
|
||||
self.enable_torrent_engine(download_dir~)
|
||||
match self.torrent_api_listener {
|
||||
Some(l) => return l.port
|
||||
None => ()
|
||||
}
|
||||
let l = @ntcp2_net.TcpListener::bind(host, port) catch { e => raise Net(e) }
|
||||
self.torrent_api_listener = Some(l)
|
||||
l.port
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Router::torrent_api_port(self : Router) -> Int32 {
|
||||
match self.torrent_api_listener {
|
||||
Some(l) => l.port
|
||||
None => 0
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn api_json_escape(s : String) -> String {
|
||||
let out = StringBuilder()
|
||||
for ch in s {
|
||||
let code = ch.to_int()
|
||||
match ch {
|
||||
'"' => out.write_string("\\\"")
|
||||
'\\' => out.write_string("\\\\")
|
||||
'\n' => out.write_string("\\n")
|
||||
'\r' => out.write_string("\\r")
|
||||
'\t' => out.write_string("\\t")
|
||||
_ => if code < 32 { out.write_char(' ') } else { out.write_char(ch) }
|
||||
}
|
||||
}
|
||||
out.to_string()
|
||||
}
|
||||
|
||||
///|
|
||||
fn api_is_loopback_host(host_hdr : String) -> Bool {
|
||||
let lower = host_hdr.trim().to_lower()
|
||||
if lower.length() == 0 {
|
||||
return false
|
||||
}
|
||||
if lower == "127.0.0.1" ||
|
||||
lower.has_prefix("127.0.0.1:") ||
|
||||
lower == "localhost" ||
|
||||
lower.has_prefix("localhost:") ||
|
||||
lower == "[::1]" ||
|
||||
lower.has_prefix("[::1]:") {
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn api_is_allowed_origin(origin : String) -> Bool {
|
||||
let lower = origin.trim().to_lower()
|
||||
lower.has_prefix("moz-extension://") ||
|
||||
lower.has_prefix("http://127.0.0.1") ||
|
||||
lower.has_prefix("http://localhost")
|
||||
}
|
||||
|
||||
///|
|
||||
fn api_parse_decimal(s : String) -> Int32 {
|
||||
let t = s.trim()
|
||||
if t.length() == 0 {
|
||||
return 0
|
||||
}
|
||||
let mut v = 0
|
||||
for i = 0; i < t.length(); i = i + 1 {
|
||||
let c = t[i].to_int()
|
||||
if c < 48 || c > 57 {
|
||||
return 0
|
||||
}
|
||||
if v > 10000000 {
|
||||
return v
|
||||
}
|
||||
v = v * 10 + (c - 48)
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
///|
|
||||
/// Minimal JSON string/integer field extractor for flat API payloads.
|
||||
fn api_json_get_string(json : String, key : String) -> String? {
|
||||
let needle = "\"\{key}\""
|
||||
let n = json.length()
|
||||
let mut pos = 0
|
||||
while pos + needle.length() < n {
|
||||
let mut matched = true
|
||||
for j = 0; j < needle.length(); j = j + 1 {
|
||||
if json[pos + j] != needle[j] {
|
||||
matched = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if matched {
|
||||
let mut i = pos + needle.length()
|
||||
while i < n &&
|
||||
(
|
||||
json[i] == ' ' ||
|
||||
json[i] == '\t' ||
|
||||
json[i] == '\n' ||
|
||||
json[i] == '\r'
|
||||
) {
|
||||
i += 1
|
||||
}
|
||||
if i < n && json[i] == ':' {
|
||||
i += 1
|
||||
while i < n &&
|
||||
(
|
||||
json[i] == ' ' ||
|
||||
json[i] == '\t' ||
|
||||
json[i] == '\n' ||
|
||||
json[i] == '\r'
|
||||
) {
|
||||
i += 1
|
||||
}
|
||||
if i < n && json[i] == '"' {
|
||||
i += 1
|
||||
let sb = StringBuilder()
|
||||
while i < n {
|
||||
let ch = json[i]
|
||||
if ch == '"' {
|
||||
return Some(sb.to_string())
|
||||
}
|
||||
if ch == '\\' && i + 1 < n {
|
||||
let nxt = json[i + 1]
|
||||
match nxt {
|
||||
'"' => sb.write_char('"')
|
||||
'\\' => sb.write_char('\\')
|
||||
'/' => sb.write_char('/')
|
||||
'n' => sb.write_char('\n')
|
||||
'r' => sb.write_char('\r')
|
||||
't' => sb.write_char('\t')
|
||||
_ => sb.write_char(nxt.unsafe_to_char())
|
||||
}
|
||||
i += 2
|
||||
} else {
|
||||
sb.write_char(ch.unsafe_to_char())
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
return None
|
||||
}
|
||||
}
|
||||
}
|
||||
pos += 1
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
///|
|
||||
fn api_json_get_int(json : String, key : String) -> Int32? {
|
||||
let needle = "\"\{key}\""
|
||||
let n = json.length()
|
||||
let mut pos = 0
|
||||
while pos + needle.length() < n {
|
||||
let mut matched = true
|
||||
for j = 0; j < needle.length(); j = j + 1 {
|
||||
if json[pos + j] != needle[j] {
|
||||
matched = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if matched {
|
||||
let mut i = pos + needle.length()
|
||||
while i < n && (json[i] == ' ' || json[i] == '\t') {
|
||||
i += 1
|
||||
}
|
||||
if i < n && json[i] == ':' {
|
||||
i += 1
|
||||
while i < n && (json[i] == ' ' || json[i] == '\t') {
|
||||
i += 1
|
||||
}
|
||||
let sb = StringBuilder()
|
||||
while i < n && json[i] >= '0' && json[i] <= '9' {
|
||||
sb.write_char(json[i].unsafe_to_char())
|
||||
i += 1
|
||||
}
|
||||
let s = sb.to_string()
|
||||
if s.length() > 0 {
|
||||
return Some(api_parse_decimal(s))
|
||||
}
|
||||
}
|
||||
}
|
||||
pos += 1
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
///|
|
||||
fn api_send_response(
|
||||
sock : @ntcp2_net.TcpSocket,
|
||||
status_code : Int32,
|
||||
reason : String,
|
||||
body_json : String,
|
||||
origin_hdr : String,
|
||||
) -> Unit {
|
||||
let body_bytes = @encoding.string_to_utf8_bytes(body_json)
|
||||
let sb = StringBuilder()
|
||||
sb.write_string("HTTP/1.1 \{status_code} \{reason}\r\n")
|
||||
sb.write_string("Content-Type: application/json; charset=utf-8\r\n")
|
||||
sb.write_string("Content-Length: \{body_bytes.length()}\r\n")
|
||||
sb.write_string("Cache-Control: no-store\r\n")
|
||||
if api_is_allowed_origin(origin_hdr) {
|
||||
sb.write_string(
|
||||
"Access-Control-Allow-Origin: \{origin_hdr.trim().to_owned()}\r\n",
|
||||
)
|
||||
sb.write_string(
|
||||
"Access-Control-Allow-Headers: Content-Type, X-Moon-I2P\r\n",
|
||||
)
|
||||
sb.write_string("Access-Control-Allow-Methods: GET, POST, OPTIONS\r\n")
|
||||
}
|
||||
sb.write_string("Connection: close\r\n\r\n")
|
||||
let hdr_bytes = @encoding.string_to_utf8_bytes(sb.to_string())
|
||||
let _ = sock.write_all(hdr_bytes) catch { _ => () }
|
||||
if body_bytes.length() > 0 {
|
||||
let _ = sock.write_all(body_bytes) catch { _ => () }
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn api_router_err_msg(e : RouterError) -> String {
|
||||
match e {
|
||||
Net(_) => "network/disk I/O error"
|
||||
Crypto(_) => "cryptography error"
|
||||
Common(_) => "I2P structure error"
|
||||
Noise(_) => "noise handshake error"
|
||||
NetDb(_) => "NetDB error"
|
||||
I2np(_) => "I2NP message error"
|
||||
Tunnel(_) => "tunnel error"
|
||||
Protocol(msg) => msg
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn api_json_err(msg : String) -> String {
|
||||
"{\"ok\":false,\"error\":\"\{api_json_escape(msg)}\"}"
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::build_api_status_json(self : Router) -> String {
|
||||
let eng = match self.torrent_engine {
|
||||
Some(e) => e
|
||||
None => return "{\"ok\":false,\"error\":\"torrent engine not initialized\"}"
|
||||
}
|
||||
let mut seeding = 0
|
||||
let mut active = 0
|
||||
for t in eng.torrents {
|
||||
if !t.paused {
|
||||
active += 1
|
||||
}
|
||||
if t.completed {
|
||||
seeding += 1
|
||||
}
|
||||
}
|
||||
let tb32 = self.torrent_b32_address()
|
||||
let dht_id = @encoding.hex_encode(eng.dht.local_id)
|
||||
let sb = StringBuilder()
|
||||
sb.write_string("{\"ok\":true,")
|
||||
sb.write_string("\"router_b32\":\"\{self.router_hash().to_b32_address()}\",")
|
||||
sb.write_string("\"public_mode\":\{self.public_mode},")
|
||||
sb.write_string("\"netdb_routers\":\{self.netdb.router_count()},")
|
||||
sb.write_string("\"netdb_floodfills\":\{self.netdb.floodfill_count()},")
|
||||
sb.write_string("\"netdb_leasesets\":\{self.netdb.leaseset_count()},")
|
||||
sb.write_string("\"inbound_tunnels\":\{self.tunnels.inbound.length()},")
|
||||
sb.write_string("\"outbound_tunnels\":\{self.tunnels.outbound.length()},")
|
||||
sb.write_string("\"http_proxy_port\":\{self.http_proxy_port()},")
|
||||
sb.write_string("\"torrent_api_port\":\{self.torrent_api_port()},")
|
||||
sb.write_string("\"torrent_b32\":\"\{api_json_escape(tb32)}\",")
|
||||
sb.write_string("\"download_dir\":\"\{api_json_escape(eng.download_dir)}\",")
|
||||
sb.write_string("\"torrent_count\":\{eng.torrents.length()},")
|
||||
sb.write_string("\"active_torrents\":\{active},")
|
||||
sb.write_string("\"completed_torrents\":\{seeding},")
|
||||
sb.write_string("\"dht\":{")
|
||||
sb.write_string("\"node_id_hex\":\"\{dht_id}\",")
|
||||
sb.write_string("\"query_port\":\{eng.dht.query_port},")
|
||||
sb.write_string("\"reply_port\":\{eng.dht.reply_port},")
|
||||
sb.write_string("\"routing_table_nodes\":\{eng.dht.nodes.length()},")
|
||||
sb.write_string("\"queries_sent\":\{eng.dht.queries_sent},")
|
||||
sb.write_string("\"responses_recv\":\{eng.dht.responses_recv},")
|
||||
sb.write_string("\"queries_recv\":\{eng.dht.queries_recv},")
|
||||
sb.write_string("\"peers_discovered\":\{eng.dht.peers_discovered}")
|
||||
sb.write_string("}}")
|
||||
sb.to_string()
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::build_api_torrents_json(self : Router) -> String {
|
||||
let eng = match self.torrent_engine {
|
||||
Some(e) => e
|
||||
None => return "{\"ok\":true,\"torrents\":[]}"
|
||||
}
|
||||
let sb = StringBuilder()
|
||||
sb.write_string("{\"ok\":true,\"torrents\":[")
|
||||
for i = 0; i < eng.torrents.length(); i = i + 1 {
|
||||
if i > 0 {
|
||||
sb.write_char(',')
|
||||
}
|
||||
let t = eng.torrents[i]
|
||||
let total_len = match t.metainfo {
|
||||
Some(m) => m.total_length
|
||||
None => 0L
|
||||
}
|
||||
let num_pieces = t.have_pieces.length()
|
||||
let mut have_cnt = 0
|
||||
for h in t.have_pieces {
|
||||
if h {
|
||||
have_cnt += 1
|
||||
}
|
||||
}
|
||||
let mut active_peers = 0
|
||||
for p in t.peers {
|
||||
if p.state == 3 {
|
||||
active_peers += 1
|
||||
}
|
||||
}
|
||||
let state_str = if t.error.length() > 0 {
|
||||
"error"
|
||||
} else if t.paused {
|
||||
"paused"
|
||||
} else if t.completed {
|
||||
"seeding"
|
||||
} else if t.metainfo is None {
|
||||
"metadata"
|
||||
} else {
|
||||
"downloading"
|
||||
}
|
||||
let progress_pct = if t.completed {
|
||||
100
|
||||
} else if num_pieces > 0 {
|
||||
have_cnt * 100 / num_pieces
|
||||
} else {
|
||||
0
|
||||
}
|
||||
sb.write_char('{')
|
||||
sb.write_string("\"info_hash\":\"\{t.info_hash_hex}\",")
|
||||
sb.write_string("\"name\":\"\{api_json_escape(t.name)}\",")
|
||||
sb.write_string("\"state\":\"\{state_str}\",")
|
||||
sb.write_string("\"paused\":\{t.paused},")
|
||||
sb.write_string("\"completed\":\{t.completed},")
|
||||
sb.write_string("\"has_metadata\":\{t.metainfo is Some(_)},")
|
||||
sb.write_string("\"total_length\":\{total_len},")
|
||||
sb.write_string("\"downloaded_bytes\":\{t.downloaded_bytes},")
|
||||
sb.write_string("\"uploaded_bytes\":\{t.uploaded_bytes},")
|
||||
sb.write_string("\"have_pieces\":\{have_cnt},")
|
||||
sb.write_string("\"num_pieces\":\{num_pieces},")
|
||||
sb.write_string("\"progress_pct\":\{progress_pct},")
|
||||
sb.write_string("\"known_peers\":\{t.known_peers.length()},")
|
||||
sb.write_string("\"connected_peers\":\{active_peers},")
|
||||
sb.write_string("\"trackers\":\{t.trackers.length()},")
|
||||
sb.write_string("\"download_dir\":\"\{api_json_escape(t.download_dir)}\",")
|
||||
sb.write_string("\"error\":\"\{api_json_escape(t.error)}\"")
|
||||
sb.write_char('}')
|
||||
}
|
||||
sb.write_string("]}")
|
||||
sb.to_string()
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::build_api_dht_nodes_json(self : Router) -> String {
|
||||
let eng = match self.torrent_engine {
|
||||
Some(e) => e
|
||||
None => return "{\"ok\":true,\"nodes\":[]}"
|
||||
}
|
||||
let sb = StringBuilder()
|
||||
sb.write_string("{\"ok\":true,")
|
||||
sb.write_string(
|
||||
"\"local_id_hex\":\"\{@encoding.hex_encode(eng.dht.local_id)}\",",
|
||||
)
|
||||
sb.write_string("\"local_b32\":\"\{self.torrent_b32_address()}\",")
|
||||
sb.write_string("\"query_port\":\{eng.dht.query_port},")
|
||||
sb.write_string("\"reply_port\":\{eng.dht.reply_port},")
|
||||
sb.write_string("\"queries_sent\":\{eng.dht.queries_sent},")
|
||||
sb.write_string("\"responses_recv\":\{eng.dht.responses_recv},")
|
||||
sb.write_string("\"queries_recv\":\{eng.dht.queries_recv},")
|
||||
sb.write_string("\"peers_discovered\":\{eng.dht.peers_discovered},")
|
||||
sb.write_string("\"nodes\":[")
|
||||
for i = 0; i < eng.dht.nodes.length(); i = i + 1 {
|
||||
if i > 0 {
|
||||
sb.write_char(',')
|
||||
}
|
||||
let n = eng.dht.nodes[i]
|
||||
sb.write_char('{')
|
||||
sb.write_string("\"node_id_hex\":\"\{@encoding.hex_encode(n.node_id)}\",")
|
||||
sb.write_string("\"b32\":\"\{n.dest_hash.to_b32_address()}\",")
|
||||
sb.write_string("\"port\":\{n.port},")
|
||||
sb.write_string("\"last_seen_ms\":\{n.last_seen_ms}")
|
||||
sb.write_char('}')
|
||||
}
|
||||
sb.write_string("]}")
|
||||
sb.to_string()
|
||||
}
|
||||
|
||||
///|
|
||||
fn api_parse_header_block(ac : TorrentApiConn, hdr_bytes : Bytes) -> Bool {
|
||||
let text = @encoding.utf8_bytes_to_string(hdr_bytes) catch {
|
||||
_ => return false
|
||||
}
|
||||
let lines : Array[String] = []
|
||||
let sb = StringBuilder()
|
||||
for i = 0; i < text.length(); i = i + 1 {
|
||||
let ch = text[i]
|
||||
if ch == '\r' {
|
||||
continue
|
||||
}
|
||||
if ch == '\n' {
|
||||
lines.push(sb.to_string())
|
||||
sb.reset()
|
||||
} else {
|
||||
sb.write_char(ch.unsafe_to_char())
|
||||
}
|
||||
}
|
||||
if sb.to_string().length() > 0 {
|
||||
lines.push(sb.to_string())
|
||||
}
|
||||
if lines.length() == 0 {
|
||||
return false
|
||||
}
|
||||
let first = lines[0]
|
||||
let mut sp1 = -1
|
||||
let mut sp2 = -1
|
||||
for i = 0; i < first.length(); i = i + 1 {
|
||||
if first[i] == ' ' {
|
||||
if sp1 < 0 {
|
||||
sp1 = i
|
||||
} else {
|
||||
sp2 = i
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if sp1 <= 0 || sp2 <= sp1 + 1 {
|
||||
return false
|
||||
}
|
||||
ac.http_method = first[:sp1].to_owned().to_upper()
|
||||
let target = first[sp1 + 1:sp2].to_owned()
|
||||
let mut qpos = target.length()
|
||||
for i = 0; i < target.length(); i = i + 1 {
|
||||
if target[i] == '?' {
|
||||
qpos = i
|
||||
break
|
||||
}
|
||||
}
|
||||
ac.path = target[:qpos].to_owned()
|
||||
for i = 1; i < lines.length(); i = i + 1 {
|
||||
let line = lines[i]
|
||||
let mut colon = -1
|
||||
for j = 0; j < line.length(); j = j + 1 {
|
||||
if line[j] == ':' {
|
||||
colon = j
|
||||
break
|
||||
}
|
||||
}
|
||||
if colon > 0 {
|
||||
let k = line[:colon].to_owned().trim().to_owned().to_lower()
|
||||
let v = line[colon + 1:].to_owned().trim().to_owned()
|
||||
match k {
|
||||
"host" => ac.host_hdr = v
|
||||
"origin" => ac.origin_hdr = v
|
||||
"content-length" => ac.content_len = api_parse_decimal(v)
|
||||
"content-type" => ac.content_type = v.to_lower()
|
||||
"x-moon-i2p" =>
|
||||
if v == "1" || v.to_lower() == "true" {
|
||||
ac.has_csrf_hdr = true
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
ac.hdr_parsed = true
|
||||
true
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::dispatch_torrent_api_request(
|
||||
self : Router,
|
||||
ac : TorrentApiConn,
|
||||
) -> Unit {
|
||||
if !api_is_loopback_host(ac.host_hdr) {
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
403,
|
||||
"Forbidden",
|
||||
api_json_err("forbidden host header"),
|
||||
ac.origin_hdr,
|
||||
)
|
||||
return
|
||||
}
|
||||
if ac.http_method == "OPTIONS" {
|
||||
api_send_response(ac.sock, 204, "No Content", "", ac.origin_hdr)
|
||||
return
|
||||
}
|
||||
if ac.http_method == "GET" {
|
||||
match ac.path {
|
||||
"/api/status" =>
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
200,
|
||||
"OK",
|
||||
self.build_api_status_json(),
|
||||
ac.origin_hdr,
|
||||
)
|
||||
"/api/torrents" =>
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
200,
|
||||
"OK",
|
||||
self.build_api_torrents_json(),
|
||||
ac.origin_hdr,
|
||||
)
|
||||
"/api/dht/nodes" =>
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
200,
|
||||
"OK",
|
||||
self.build_api_dht_nodes_json(),
|
||||
ac.origin_hdr,
|
||||
)
|
||||
_ =>
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
404,
|
||||
"Not Found",
|
||||
api_json_err("unknown endpoint"),
|
||||
ac.origin_hdr,
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
if ac.http_method != "POST" {
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
405,
|
||||
"Method Not Allowed",
|
||||
api_json_err("method not allowed"),
|
||||
ac.origin_hdr,
|
||||
)
|
||||
return
|
||||
}
|
||||
if !ac.has_csrf_hdr {
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
403,
|
||||
"Forbidden",
|
||||
api_json_err("missing X-Moon-I2P: 1 header"),
|
||||
ac.origin_hdr,
|
||||
)
|
||||
return
|
||||
}
|
||||
let body = Bytes::from_array(ac.body_buf)
|
||||
let body_str = @encoding.utf8_bytes_to_string(body) catch { _ => "" }
|
||||
match ac.path {
|
||||
"/api/torrents/add" => {
|
||||
let raw_torrent = if ac.content_type.contains("application/json") ||
|
||||
(body.length() > 0 && body[0] == b'{') {
|
||||
match api_json_get_string(body_str, "torrent_b64") {
|
||||
Some(b64) =>
|
||||
@encoding.base64_decode(b64) catch {
|
||||
_ => {
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
400,
|
||||
"Bad Request",
|
||||
api_json_err("invalid torrent_b64"),
|
||||
ac.origin_hdr,
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
None => {
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
400,
|
||||
"Bad Request",
|
||||
api_json_err("missing torrent_b64"),
|
||||
ac.origin_hdr,
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
} else {
|
||||
body
|
||||
}
|
||||
let dl_dir = match api_json_get_string(body_str, "download_dir") {
|
||||
Some(d) => d
|
||||
None => ""
|
||||
}
|
||||
try {
|
||||
let ih = self.add_torrent_bytes(raw_torrent, download_dir=dl_dir)
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
200,
|
||||
"OK",
|
||||
"{\"ok\":true,\"info_hash\":\"\{ih}\"}",
|
||||
ac.origin_hdr,
|
||||
)
|
||||
} catch {
|
||||
e =>
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
400,
|
||||
"Bad Request",
|
||||
api_json_err(api_router_err_msg(e)),
|
||||
ac.origin_hdr,
|
||||
)
|
||||
}
|
||||
}
|
||||
"/api/torrents/magnet" => {
|
||||
let uri = match api_json_get_string(body_str, "uri") {
|
||||
Some(u) => u
|
||||
None => {
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
400,
|
||||
"Bad Request",
|
||||
api_json_err("missing magnet uri"),
|
||||
ac.origin_hdr,
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
let dl_dir = match api_json_get_string(body_str, "download_dir") {
|
||||
Some(d) => d
|
||||
None => ""
|
||||
}
|
||||
try {
|
||||
let ih = self.add_torrent_magnet(uri, download_dir=dl_dir)
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
200,
|
||||
"OK",
|
||||
"{\"ok\":true,\"info_hash\":\"\{ih}\"}",
|
||||
ac.origin_hdr,
|
||||
)
|
||||
} catch {
|
||||
e =>
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
400,
|
||||
"Bad Request",
|
||||
api_json_err(api_router_err_msg(e)),
|
||||
ac.origin_hdr,
|
||||
)
|
||||
}
|
||||
}
|
||||
"/api/torrents/pause" => {
|
||||
let ih = api_json_get_string(body_str, "info_hash").unwrap_or("")
|
||||
if self.pause_torrent(ih) {
|
||||
api_send_response(ac.sock, 200, "OK", "{\"ok\":true}", ac.origin_hdr)
|
||||
} else {
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
404,
|
||||
"Not Found",
|
||||
api_json_err("torrent not found"),
|
||||
ac.origin_hdr,
|
||||
)
|
||||
}
|
||||
}
|
||||
"/api/torrents/resume" => {
|
||||
let ih = api_json_get_string(body_str, "info_hash").unwrap_or("")
|
||||
if self.resume_torrent(ih) {
|
||||
api_send_response(ac.sock, 200, "OK", "{\"ok\":true}", ac.origin_hdr)
|
||||
} else {
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
404,
|
||||
"Not Found",
|
||||
api_json_err("torrent not found"),
|
||||
ac.origin_hdr,
|
||||
)
|
||||
}
|
||||
}
|
||||
"/api/torrents/remove" => {
|
||||
let ih = api_json_get_string(body_str, "info_hash").unwrap_or("")
|
||||
if self.remove_torrent(ih) {
|
||||
api_send_response(ac.sock, 200, "OK", "{\"ok\":true}", ac.origin_hdr)
|
||||
} else {
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
404,
|
||||
"Not Found",
|
||||
api_json_err("torrent not found"),
|
||||
ac.origin_hdr,
|
||||
)
|
||||
}
|
||||
}
|
||||
"/api/dht/bootstrap" => {
|
||||
let b32 = api_json_get_string(body_str, "b32").unwrap_or("")
|
||||
let port = match api_json_get_int(body_str, "port") {
|
||||
Some(p) if p > 0 && p <= 65535 => p.reinterpret_as_uint()
|
||||
_ => 6881U
|
||||
}
|
||||
match self.resolve_i2p_host_hash(b32) {
|
||||
Some(h) => {
|
||||
let ok = self.dht_add_bootstrap_node(h, port~)
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
200,
|
||||
"OK",
|
||||
"{\"ok\":\{ok},\"b32\":\"\{h.to_b32_address()}\",\"port\":\{port}}",
|
||||
ac.origin_hdr,
|
||||
)
|
||||
}
|
||||
None =>
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
400,
|
||||
"Bad Request",
|
||||
api_json_err("invalid bootstrap b32/hash"),
|
||||
ac.origin_hdr,
|
||||
)
|
||||
}
|
||||
}
|
||||
_ =>
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
404,
|
||||
"Not Found",
|
||||
api_json_err("unknown endpoint"),
|
||||
ac.origin_hdr,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::step_torrent_api(self : Router) -> Bool {
|
||||
let listener = match self.torrent_api_listener {
|
||||
Some(l) => l
|
||||
None => return false
|
||||
}
|
||||
let mut did_work = false
|
||||
let now_ms = @ntcp2_net.unix_time_ms()
|
||||
|
||||
for _i = 0; _i < 8; _i = _i + 1 {
|
||||
match (listener.accept(timeout_ms=0) catch { _ => None }) {
|
||||
Some(sock) => {
|
||||
self.torrent_api_conns.push({
|
||||
sock,
|
||||
recv_buf: [],
|
||||
hdr_parsed: false,
|
||||
http_method: "",
|
||||
path: "",
|
||||
host_hdr: "",
|
||||
origin_hdr: "",
|
||||
has_csrf_hdr: false,
|
||||
content_type: "",
|
||||
content_len: 0,
|
||||
body_buf: [],
|
||||
started_ms: now_ms,
|
||||
closed: false,
|
||||
})
|
||||
did_work = true
|
||||
}
|
||||
None => break
|
||||
}
|
||||
}
|
||||
|
||||
let mut i = 0
|
||||
while i < self.torrent_api_conns.length() {
|
||||
let ac = self.torrent_api_conns[i]
|
||||
if ac.closed {
|
||||
let _ = self.torrent_api_conns.remove(i)
|
||||
continue
|
||||
}
|
||||
if now_ms > ac.started_ms + 15000UL {
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
408,
|
||||
"Request Timeout",
|
||||
api_json_err("request timeout"),
|
||||
ac.origin_hdr,
|
||||
)
|
||||
ac.sock.close()
|
||||
ac.closed = true
|
||||
let _ = self.torrent_api_conns.remove(i)
|
||||
did_work = true
|
||||
continue
|
||||
}
|
||||
let prev_len = ac.recv_buf.length()
|
||||
let eof = try {
|
||||
let _ = ac.sock.pump_nonblocking(ac.recv_buf, 16384)
|
||||
false
|
||||
} catch {
|
||||
_ => true
|
||||
}
|
||||
if ac.recv_buf.length() != prev_len {
|
||||
did_work = true
|
||||
}
|
||||
if !ac.hdr_parsed {
|
||||
if ac.recv_buf.length() > 65536 {
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
431,
|
||||
"Request Header Fields Too Large",
|
||||
api_json_err("headers too large"),
|
||||
ac.origin_hdr,
|
||||
)
|
||||
ac.sock.close()
|
||||
ac.closed = true
|
||||
let _ = self.torrent_api_conns.remove(i)
|
||||
continue
|
||||
}
|
||||
match find_http_header_end(ac.recv_buf) {
|
||||
Some((hdr_end, sep_len)) => {
|
||||
let all = Bytes::from_array(ac.recv_buf)
|
||||
let hdr_bytes = all[:hdr_end].to_owned()
|
||||
let rem = all[hdr_end + sep_len:].to_owned()
|
||||
ac.recv_buf.clear()
|
||||
if !api_parse_header_block(ac, hdr_bytes) {
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
400,
|
||||
"Bad Request",
|
||||
api_json_err("malformed HTTP request"),
|
||||
ac.origin_hdr,
|
||||
)
|
||||
ac.sock.close()
|
||||
ac.closed = true
|
||||
let _ = self.torrent_api_conns.remove(i)
|
||||
continue
|
||||
}
|
||||
if ac.content_len > 4 * 1024 * 1024 {
|
||||
api_send_response(
|
||||
ac.sock,
|
||||
413,
|
||||
"Payload Too Large",
|
||||
api_json_err("body exceeds 4 MiB limit"),
|
||||
ac.origin_hdr,
|
||||
)
|
||||
ac.sock.close()
|
||||
ac.closed = true
|
||||
let _ = self.torrent_api_conns.remove(i)
|
||||
continue
|
||||
}
|
||||
for j = 0; j < rem.length(); j = j + 1 {
|
||||
ac.body_buf.push(rem[j])
|
||||
}
|
||||
did_work = true
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
} else if ac.recv_buf.length() > 0 {
|
||||
for b in ac.recv_buf {
|
||||
if ac.body_buf.length() <= 4 * 1024 * 1024 {
|
||||
ac.body_buf.push(b)
|
||||
}
|
||||
}
|
||||
ac.recv_buf.clear()
|
||||
}
|
||||
if ac.hdr_parsed && ac.body_buf.length() >= ac.content_len {
|
||||
while ac.body_buf.length() > ac.content_len && ac.content_len >= 0 {
|
||||
let _ = ac.body_buf.pop()
|
||||
}
|
||||
self.dispatch_torrent_api_request(ac)
|
||||
ac.sock.close()
|
||||
ac.closed = true
|
||||
let _ = self.torrent_api_conns.remove(i)
|
||||
did_work = true
|
||||
continue
|
||||
}
|
||||
if eof {
|
||||
ac.sock.close()
|
||||
ac.closed = true
|
||||
let _ = self.torrent_api_conns.remove(i)
|
||||
continue
|
||||
}
|
||||
i += 1
|
||||
}
|
||||
did_work
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user