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
@@ -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
|
||||
}
|
||||
Reference in new issue
Block a user