feat: add I2P BitTorrent engine, DHT, and Firefox torrent extension
check / check (macos-latest) (push) Failing after 29s
check / check (ubuntu-latest) (push) Failing after 29s
check / check (windows-latest) (push) Failing after 30s

- 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:
nandi committed 2026-11-28 13:19:03 -08:00
1 parent 14eae00f5c
commit fbe6818c4e
37 files changed
+8543 -9

No files matched your search

+686
View File
@@ -0,0 +1,686 @@
///|
/// Pure-MoonBit BitTorrent Peer Wire Protocol (BEP 3), Extension Protocol (BEP 10),
/// Metadata Exchange (`ut_metadata` BEP 9), I2P Peer Exchange (`i2p_pex`),
/// `i2p_dht` extension negotiation, and I2P HTTP Tracker Announce codec (32B compact hashes).
///|
pub let bt_protocol_string : Bytes = b"\x13BitTorrent protocol"
///|
pub let ext_id_pex : Byte = b'\x01'
///|
pub let ext_id_ut_metadata : Byte = b'\x02'
///|
pub let ext_id_i2p_dht : Byte = b'\x03'
///|
pub let bt_block_size : Int32 = 16384
///|
pub fn encode_handshake(
info_hash : Bytes,
peer_id : Bytes,
) -> Bytes raise BtError {
if info_hash.length() != 20 || peer_id.length() != 20 {
raise InvalidWire("BitTorrent handshake requires 20B info_hash and peer_id")
}
let w = @encoding.Writer::new(capacity=68)
w.write_bytes(bt_protocol_string)
let reserved = FixedArray::make(8, b'\x00')
reserved[5] = b'\x10' // BEP 10 Extension Protocol supported
w.write_bytes(Bytes::from_array(reserved))
w.write_bytes(info_hash)
w.write_bytes(peer_id)
w.to_bytes()
}
///|
/// Decodes the 68-byte BitTorrent peer handshake into `(reserved_8B, info_hash_20B, peer_id_20B)`.
pub fn decode_handshake(buf : Bytes) -> (Bytes, Bytes, Bytes) raise BtError {
if buf.length() < 68 {
raise InvalidWire("handshake shorter than 68 bytes")
}
let pstr = buf[:20].to_owned()
if !@crypto.ct_eq(pstr, bt_protocol_string) {
raise InvalidWire("invalid BitTorrent protocol header")
}
let reserved = buf[20:28].to_owned()
let info_hash = buf[28:48].to_owned()
let peer_id = buf[48:68].to_owned()
(reserved, info_hash, peer_id)
}
///|
#derive(Eq, Debug)
pub(all) enum PeerMessage {
KeepAlive
Choke
Unchoke
Interested
NotInterested
Have(UInt32)
Bitfield(Bytes)
Request(Int32, Int32, Int32)
Piece(Int32, Int32, Bytes)
Cancel(Int32, Int32, Int32)
Extended(Byte, Bytes)
}
///|
/// Encodes a framed Peer Wire message (`4B length BE || id || payload`).
pub fn encode_peer_message(msg : PeerMessage) -> Bytes {
let w = @encoding.Writer::new(capacity=32)
match msg {
KeepAlive => w.write_u32_be(0U)
Choke => {
w.write_u32_be(1U)
w.write_u8(b'\x00')
}
Unchoke => {
w.write_u32_be(1U)
w.write_u8(b'\x01')
}
Interested => {
w.write_u32_be(1U)
w.write_u8(b'\x02')
}
NotInterested => {
w.write_u32_be(1U)
w.write_u8(b'\x03')
}
Have(idx) => {
w.write_u32_be(5U)
w.write_u8(b'\x04')
w.write_u32_be(idx)
}
Bitfield(bf) => {
w.write_u32_be((1 + bf.length()).reinterpret_as_uint())
w.write_u8(b'\x05')
w.write_bytes(bf)
}
Request(idx, begin, len) => {
w.write_u32_be(13U)
w.write_u8(b'\x06')
w.write_u32_be(idx.reinterpret_as_uint())
w.write_u32_be(begin.reinterpret_as_uint())
w.write_u32_be(len.reinterpret_as_uint())
}
Piece(idx, begin, data) => {
w.write_u32_be((9 + data.length()).reinterpret_as_uint())
w.write_u8(b'\x07')
w.write_u32_be(idx.reinterpret_as_uint())
w.write_u32_be(begin.reinterpret_as_uint())
w.write_bytes(data)
}
Cancel(idx, begin, len) => {
w.write_u32_be(13U)
w.write_u8(b'\x08')
w.write_u32_be(idx.reinterpret_as_uint())
w.write_u32_be(begin.reinterpret_as_uint())
w.write_u32_be(len.reinterpret_as_uint())
}
Extended(ext_id, payload) => {
w.write_u32_be((2 + payload.length()).reinterpret_as_uint())
w.write_u8(b'\x14')
w.write_u8(ext_id)
w.write_bytes(payload)
}
}
w.to_bytes()
}
///|
fn be32_at(buf : Array[Byte], off : Int32) -> UInt32 {
(buf[off].to_uint() << 24) |
(buf[off + 1].to_uint() << 16) |
(buf[off + 2].to_uint() << 8) |
buf[off + 3].to_uint()
}
///|
fn consume_front_bytes(buf : Array[Byte], count : Int32) -> Unit {
if count >= buf.length() {
buf.clear()
return
}
let rem : Array[Byte] = Array(capacity=buf.length() - count)
for i = count; i < buf.length(); i = i + 1 {
rem.push(buf[i])
}
buf.clear()
for b in rem {
buf.push(b)
}
}
///|
/// Attempts to decode and pop one framed Peer Wire message from `buf`.
pub fn try_decode_peer_message(buf : Array[Byte]) -> PeerMessage? raise BtError {
if buf.length() < 4 {
return None
}
let msg_len_u = be32_at(buf, 0)
if msg_len_u > 2097152U {
raise InvalidWire("peer wire frame too large: \{msg_len_u}")
}
let msg_len = msg_len_u.reinterpret_as_int()
if buf.length() < 4 + msg_len {
return None
}
if msg_len == 0 {
consume_front_bytes(buf, 4)
return Some(KeepAlive)
}
let body = Bytes::from_array(buf[4:4 + msg_len])
consume_front_bytes(buf, 4 + msg_len)
let r = @encoding.Reader::new(body)
let msg_id = r.read_u8() catch { e => raise Encoding(e) }
match msg_id {
b'\x00' => Some(Choke)
b'\x01' => Some(Unchoke)
b'\x02' => Some(Interested)
b'\x03' => Some(NotInterested)
b'\x04' => {
let idx = r.read_u32_be() catch { e => raise Encoding(e) }
Some(Have(idx))
}
b'\x05' => Some(Bitfield(r.read_remaining()))
b'\x06' => {
let idx = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
let begin = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
let len = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
Some(Request(idx, begin, len))
}
b'\x07' => {
let idx = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
let begin = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
let block = r.read_remaining()
Some(Piece(idx, begin, block))
}
b'\x08' => {
let idx = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
let begin = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
let len = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
Some(Cancel(idx, begin, len))
}
b'\x14' => {
let ext_id = r.read_u8() catch { e => raise Encoding(e) }
Some(Extended(ext_id, r.read_remaining()))
}
_ => Some(KeepAlive)
}
}
///|
#derive(Eq, Debug)
pub(all) struct RemoteExtensions {
mut ut_metadata_id : Byte?
mut i2p_pex_id : Byte?
mut i2p_dht_id : Byte?
mut metadata_size : Int32?
}
///|
/// Builds a BEP 10 extended handshake (`ext_id = 0`) advertising `i2p_pex`,
/// `ut_metadata`, `i2p_dht`, and optional `metadata_size`.
pub fn encode_ext_handshake(metadata_size~ : Int32? = None) -> Bytes {
let m_entries : Array[(Bytes, BVal)] = [
(b"i2p_dht", BInt(ext_id_i2p_dht.to_int().to_int64())),
(b"i2p_pex", BInt(ext_id_pex.to_int().to_int64())),
(b"ut_metadata", BInt(ext_id_ut_metadata.to_int().to_int64())),
]
let root : Array[(Bytes, BVal)] = [
(b"m", BDict(m_entries)),
(b"reqq", BInt(64L)),
(b"v", BBytes(b"moon-i2p/0.1")),
]
match metadata_size {
Some(sz) if sz > 0 => root.push((b"metadata_size", BInt(sz.to_int64())))
_ => ()
}
bencode_encode(BDict(root))
}
///|
/// Parses a remote peer's BEP 10 extended handshake payload.
pub fn decode_ext_handshake(payload : Bytes) -> RemoteExtensions raise BtError {
let d = bencode_decode(payload)
let res : RemoteExtensions = {
ut_metadata_id: None,
i2p_pex_id: None,
i2p_dht_id: None,
metadata_size: None,
}
match bdict_get(d, "m") {
Some(m) => {
match bdict_get_int(m, "ut_metadata") {
Some(v) if v > 0L && v < 256L => res.ut_metadata_id = Some(v.to_byte())
_ => ()
}
match bdict_get_int(m, "i2p_pex") {
Some(v) if v > 0L && v < 256L => res.i2p_pex_id = Some(v.to_byte())
_ => ()
}
match bdict_get_int(m, "i2p_dht") {
Some(v) if v > 0L && v < 256L => res.i2p_dht_id = Some(v.to_byte())
_ => ()
}
}
None => ()
}
match bdict_get_int(d, "metadata_size") {
Some(sz) if sz > 0L && sz <= 16777216L =>
res.metadata_size = Some(sz.to_int())
_ => ()
}
res
}
///|
/// Encodes the I2P DHT extension payload (`{"port": query_port, "rport": reply_port}`).
pub fn encode_i2p_dht_ext(query_port : UInt32, reply_port : UInt32) -> Bytes {
bencode_encode(
BDict([
(b"port", BInt(query_port.to_int64())),
(b"rport", BInt(reply_port.to_int64())),
]),
)
}
///|
/// Decodes an `i2p_dht` extension message into `(query_port, reply_port)`.
pub fn decode_i2p_dht_ext(payload : Bytes) -> (UInt32, UInt32)? {
let d = bencode_decode(payload) catch { _ => return None }
let q = match bdict_get_int(d, "port") {
Some(p) if p > 0L && p <= 65535L => p.to_int().reinterpret_as_uint()
_ => return None
}
let r = match bdict_get_int(d, "rport") {
Some(rp) if rp > 0L && rp <= 65535L => rp.to_int().reinterpret_as_uint()
_ => q + 1U
}
Some((q, r))
}
///|
/// Encodes `i2p_pex` compact 32-byte destination hashes under key `"added"`.
pub fn encode_i2p_pex(peers : Array[@common.Hash]) -> Bytes {
let w = @encoding.Writer::new(capacity=peers.length() * 32)
for h in peers {
w.write_bytes(h.as_bytes())
}
bencode_encode(BDict([(b"added", BBytes(w.to_bytes()))]))
}
///|
/// Decodes an `i2p_pex` message's `"added"` field (`32 * N` byte destination hashes).
pub fn decode_i2p_pex(payload : Bytes) -> Array[@common.Hash] {
let out : Array[@common.Hash] = []
let d = bencode_decode(payload) catch { _ => return out }
match bdict_get_bytes(d, "added") {
Some(blob) => {
let count = blob.length() / 32
for i = 0; i < count; i = i + 1 {
let h = @common.Hash::from_bytes(blob[i * 32:(i + 1) * 32].to_owned()) catch {
_ => continue
}
out.push(h)
}
}
None => ()
}
out
}
///|
#derive(Eq, Debug)
pub(all) enum MetadataMsg {
MetaRequest(Int32)
MetaData(Int32, Int32, Bytes) // (piece, total_size, slice)
MetaReject(Int32)
}
///|
pub fn encode_metadata_request(piece : Int32) -> Bytes {
bencode_encode(
BDict([(b"msg_type", BInt(0L)), (b"piece", BInt(piece.to_int64()))]),
)
}
///|
pub fn encode_metadata_data(
piece : Int32,
total_size : Int32,
slice : Bytes,
) -> Bytes {
let hdr = bencode_encode(
BDict([
(b"msg_type", BInt(1L)),
(b"piece", BInt(piece.to_int64())),
(b"total_size", BInt(total_size.to_int64())),
]),
)
let w = @encoding.Writer::new(capacity=hdr.length() + slice.length())
w.write_bytes(hdr)
w.write_bytes(slice)
w.to_bytes()
}
///|
pub fn encode_metadata_reject(piece : Int32) -> Bytes {
bencode_encode(
BDict([(b"msg_type", BInt(2L)), (b"piece", BInt(piece.to_int64()))]),
)
}
///|
/// Decodes a BEP 9 `ut_metadata` message (dictionary header followed by optional metadata slice).
pub fn decode_metadata_msg(payload : Bytes) -> MetadataMsg raise BtError {
let (d, hdr_end) = bencode_decode_prefix(payload)
let msg_type = match bdict_get_int(d, "msg_type") {
Some(t) => t
None => raise InvalidWire("ut_metadata missing msg_type")
}
let piece = match bdict_get_int(d, "piece") {
Some(p) if p >= 0L => p.to_int()
_ => raise InvalidWire("ut_metadata missing valid piece index")
}
if msg_type == 0L {
return MetaRequest(piece)
}
if msg_type == 1L {
let total_size = match bdict_get_int(d, "total_size") {
Some(s) if s > 0L => s.to_int()
_ => raise InvalidWire("ut_metadata data missing valid total_size")
}
let slice = payload[hdr_end:].to_owned()
return MetaData(piece, total_size, slice)
}
if msg_type == 2L {
return MetaReject(piece)
}
raise InvalidWire("unknown ut_metadata msg_type: \{msg_type}")
}
///|
#derive(Eq, Debug)
pub(all) struct TrackerUrl {
host : String
port : UInt32
request_target : String
}
///|
/// Parses an `http://host[:port]/path` I2P tracker URL. Returns `None` for non-HTTP or non-`.i2p` URLs.
pub fn parse_http_tracker_url(url : String) -> TrackerUrl? {
let trimmed = url.trim().to_owned()
let lower = trimmed.to_lower()
if !lower.has_prefix("http://") {
return None
}
let rest = trimmed[7:].to_owned()
let mut split_at = rest.length()
for i = 0; i < rest.length(); i = i + 1 {
if rest[i] == '/' || rest[i] == '?' {
split_at = i
break
}
}
let auth = rest[:split_at].to_owned()
let tail = rest[split_at:].to_owned()
let request_target = if tail.length() == 0 {
"/"
} else if tail.has_prefix("?") {
"/" + tail
} else {
tail
}
let mut colon = -1
for i = 0; i < auth.length(); i = i + 1 {
if auth[i] == ':' {
colon = i
}
}
let (host_raw, port) = if colon < 0 {
(auth, 80U)
} else {
let ps = auth[colon + 1:].to_owned()
match parse_u32_port_str(ps) {
Some(p) => (auth[:colon].to_owned(), p)
None => return None
}
}
let host = host_raw.to_lower()
if !host.has_suffix(".i2p") || host.length() <= 4 {
return None
}
Some({ host, port, request_target, })
}
///|
/// Builds an HTTP/1.1 tracker announce GET request with I2P `compact=1` and optional `ip=<dest>.i2p`.
pub fn build_http_announce_request(
tracker : TrackerUrl,
info_hash : Bytes,
peer_id : Bytes,
uploaded : Int64,
downloaded : Int64,
left : Int64,
event~ : String = "",
local_dest_b64~ : String = "",
) -> String {
let sep = if tracker.request_target.contains("?") { "&" } else { "?" }
let qs = StringBuilder()
qs.write_string(tracker.request_target)
qs.write_string(sep)
qs.write_string("info_hash=")
qs.write_string(url_encode_bytes(info_hash))
qs.write_string("&peer_id=")
qs.write_string(url_encode_bytes(peer_id))
qs.write_string("&port=6881&uploaded=")
qs.write_string(uploaded.to_string())
qs.write_string("&downloaded=")
qs.write_string(downloaded.to_string())
qs.write_string("&left=")
qs.write_string(left.to_string())
qs.write_string("&compact=1&numwant=50")
if event.length() > 0 {
qs.write_string("&event=")
qs.write_string(event)
}
if local_dest_b64.length() > 0 {
qs.write_string("&ip=")
qs.write_string(local_dest_b64)
qs.write_string(".i2p")
}
let host_hdr = if tracker.port == 80U {
tracker.host
} else {
"\{tracker.host}:\{tracker.port}"
}
"GET \{qs.to_string()} HTTP/1.1\r\nHost: \{host_hdr}\r\nUser-Agent: moon-i2p/0.1\r\nAccept: */*\r\nConnection: close\r\n\r\n"
}
///|
#derive(Eq, Debug)
pub(all) struct TrackerResponse {
interval : Int32
complete : Int32
incomplete : Int32
peers : Array[@common.Hash]
failure_reason : String?
}
///|
fn find_http_body_split(raw : Bytes) -> (Int32, Int32)? {
let n = raw.length()
for i = 0; i < n; i = i + 1 {
if i + 3 < n &&
raw[i] == b'\r' &&
raw[i + 1] == b'\n' &&
raw[i + 2] == b'\r' &&
raw[i + 3] == b'\n' {
return Some((i, i + 4))
}
if i + 1 < n && raw[i] == b'\n' && raw[i + 1] == b'\n' {
return Some((i, i + 2))
}
}
None
}
///|
fn decode_http_chunked(raw : Bytes) -> Bytes raise BtError {
let w = @encoding.Writer::new(capacity=raw.length())
let mut pos = 0
while pos < raw.length() {
let mut line_end = -1
for i = pos; i < raw.length(); i = i + 1 {
if raw[i] == b'\n' {
line_end = i
break
}
}
if line_end < 0 {
raise InvalidWire("malformed chunked tracker response")
}
let trim_end = if line_end > pos && raw[line_end - 1] == b'\r' {
line_end - 1
} else {
line_end
}
let len_str = @encoding.utf8_bytes_to_string(raw[pos:trim_end].to_owned()) catch {
_ => raise InvalidWire("non-UTF8 chunk size")
}
let clean_len = match find_char_or_semi(len_str) {
Some(s) => s.trim().to_owned()
None => len_str.trim().to_owned()
}
let mut chunk_sz = 0
for ch in clean_len {
let n = bt_hex_nibble(ch.to_int())
if n < 0 {
raise InvalidWire("invalid hex chunk size: \{clean_len}")
}
chunk_sz = chunk_sz * 16 + n
}
pos = line_end + 1
if chunk_sz == 0 {
break
}
if pos + chunk_sz > raw.length() {
raise InvalidWire("truncated chunked tracker body")
}
w.write_bytes(raw[pos:pos + chunk_sz].to_owned())
pos += chunk_sz
if pos + 1 < raw.length() && raw[pos] == b'\r' && raw[pos + 1] == b'\n' {
pos += 2
} else if pos < raw.length() && raw[pos] == b'\n' {
pos += 1
}
}
w.to_bytes()
}
///|
fn find_char_or_semi(s : String) -> String? {
for i = 0; i < s.length(); i = i + 1 {
if s[i] == ';' {
return Some(s[:i].to_owned())
}
}
None
}
///|
fn decode_tracker_peer_str(s : String) -> @common.Hash? {
let lower = s.trim().to_owned()
let host_no_i2p = if lower.to_lower().has_suffix(".i2p") {
lower[:lower.length() - 4].to_owned()
} else {
lower
}
if host_no_i2p.to_lower().has_suffix(".b32") && host_no_i2p.length() >= 56 {
let b32 = host_no_i2p[:host_no_i2p.length() - 4].to_owned()
let raw = @encoding.base32_decode(b32) catch { _ => return None }
if raw.length() == 32 {
return Some(@common.Hash::from_bytes(raw)) catch { _ => None }
}
}
let dest = @common.Destination::from_base64(host_no_i2p) catch {
_ => return None
}
Some(dest.hash())
}
///|
/// Parses an HTTP tracker response (including chunked / gzip encoding and 32B I2P compact peers).
pub fn parse_http_tracker_response(
raw : Bytes,
) -> TrackerResponse raise BtError {
let (hdr_end, body_start) = match find_http_body_split(raw) {
Some(p) => p
None => raise InvalidWire("HTTP tracker response missing header terminator")
}
let hdr_text = @encoding.utf8_bytes_to_string(raw[:hdr_end].to_owned()) catch {
e => raise Encoding(e)
}
let lower_hdr = hdr_text.to_lower()
let first_line = match lower_hdr.split("\n").next() {
Some(l) => l.to_owned().trim().to_owned()
None => raise InvalidWire("empty HTTP tracker status line")
}
if !first_line.contains(" 200") && !first_line.contains(" 20") {
raise InvalidWire("tracker HTTP status error: \{first_line}")
}
let mut body = raw[body_start:].to_owned()
if lower_hdr.contains("transfer-encoding: chunked") {
body = decode_http_chunked(body)
}
if lower_hdr.contains("content-encoding: gzip") {
body = @encoding.gzip_decompress(body) catch { e => raise Encoding(e) }
}
let dict = bencode_decode(body)
let failure_reason = bdict_get_string(dict, "failure reason")
let interval = match bdict_get_int(dict, "interval") {
Some(i) if i > 0L => i.to_int()
_ => 300
}
let complete = match bdict_get_int(dict, "complete") {
Some(c) if c >= 0L => c.to_int()
_ => 0
}
let incomplete = match bdict_get_int(dict, "incomplete") {
Some(ic) if ic >= 0L => ic.to_int()
_ => 0
}
let peers : Array[@common.Hash] = []
match bdict_get(dict, "peers") {
Some(BBytes(compact)) => {
let count = compact.length() / 32
for i = 0; i < count; i = i + 1 {
let slice = compact[i * 32:(i + 1) * 32].to_owned()
let is_zero = @crypto.ct_eq(slice, Bytes::make(32, b'\x00'))
if !is_zero {
let h = @common.Hash::from_bytes(slice) catch { _ => continue }
peers.push(h)
}
}
}
Some(BList(plist)) =>
for p in plist {
match bdict_get_string(p, "ip") {
Some(ip_s) =>
match decode_tracker_peer_str(ip_s) {
Some(h) => peers.push(h)
None => ()
}
None => ()
}
}
_ => ()
}
{ interval, complete, incomplete, peers, failure_reason, }
}