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

+307
View File
@@ -0,0 +1,307 @@
///|
/// Pure-MoonBit BitTorrent Bencode codec and error types (BEP 3),
/// including raw `"info"` dictionary slice extraction for exact SHA-1 `info_hash`.
///|
#derive(Eq, Debug)
pub suberror BtError {
InvalidBencode(String)
InvalidMetainfo(String)
InvalidMagnet(String)
InvalidWire(String)
InvalidKrpc(String)
Encoding(@encoding.EncodingError)
Common(@common.CommonError)
}
///|
#derive(Eq, Debug)
pub(all) enum BVal {
BInt(Int64)
BBytes(Bytes)
BList(Array[BVal])
BDict(Array[(Bytes, BVal)])
}
///|
fn cmp_bytes_lex(a : Bytes, b : Bytes) -> Int32 {
let n = if a.length() < b.length() { a.length() } else { b.length() }
for i = 0; i < n; i = i + 1 {
let ai = a[i].to_int()
let bi = b[i].to_int()
if ai < bi {
return -1
}
if ai > bi {
return 1
}
}
if a.length() < b.length() {
-1
} else if a.length() > b.length() {
1
} else {
0
}
}
///|
fn encode_bval_into(w : @encoding.Writer, val : BVal) -> Unit {
match val {
BInt(n) => {
w.write_u8(b'i')
w.write_bytes(@encoding.string_to_utf8_bytes(n.to_string()))
w.write_u8(b'e')
}
BBytes(b) => {
w.write_bytes(@encoding.string_to_utf8_bytes(b.length().to_string()))
w.write_u8(b':')
w.write_bytes(b)
}
BList(items) => {
w.write_u8(b'l')
for item in items {
encode_bval_into(w, item)
}
w.write_u8(b'e')
}
BDict(entries) => {
w.write_u8(b'd')
let sorted : Array[(Bytes, BVal)] = Array(capacity=entries.length())
for e in entries {
sorted.push(e)
}
sorted.sort_by(fn(a, b) { cmp_bytes_lex(a.0, b.0) })
for e in sorted {
encode_bval_into(w, BBytes(e.0))
encode_bval_into(w, e.1)
}
w.write_u8(b'e')
}
}
}
///|
/// Encodes a `BVal` into canonical sorted Bencode bytes.
pub fn bencode_encode(val : BVal) -> Bytes {
let w = @encoding.Writer::new(capacity=64)
encode_bval_into(w, val)
w.to_bytes()
}
///|
fn decode_int_slice(
data : Bytes,
start : Int32,
end : Int32,
allow_negative~ : Bool = true,
) -> Int64 raise BtError {
if start >= end {
raise InvalidBencode("empty integer field")
}
let mut neg = false
let mut idx = start
if data[idx] == b'-' {
if !allow_negative {
raise InvalidBencode("negative length not allowed")
}
neg = true
idx += 1
if idx >= end {
raise InvalidBencode("dangling minus sign")
}
if data[idx] == b'0' {
raise InvalidBencode("negative zero or leading zero after minus")
}
} else if end - idx > 1 && data[idx] == b'0' {
raise InvalidBencode("leading zero in integer")
}
let mut acc = 0L
while idx < end {
let b = data[idx].to_int()
if b < 48 || b > 57 {
raise InvalidBencode("non-digit byte in integer: \{b}")
}
acc = acc * 10L + (b - 48).to_int64()
idx += 1
}
if neg {
-acc
} else {
acc
}
}
///|
fn find_byte(data : Bytes, target : Byte, start : Int32) -> Int32? {
for i = start; i < data.length(); i = i + 1 {
if data[i] == target {
return Some(i)
}
}
None
}
///|
fn decode_bval_at(
data : Bytes,
pos : Int32,
depth : Int32,
) -> (BVal, Int32) raise BtError {
if depth > 64 {
raise InvalidBencode("bencode nesting depth exceeded")
}
if pos >= data.length() {
raise InvalidBencode("unexpected EOF")
}
let tag = data[pos]
if tag == b'i' {
let end_pos = match find_byte(data, b'e', pos + 1) {
Some(e) => e
None => raise InvalidBencode("unterminated integer")
}
let val = decode_int_slice(data, pos + 1, end_pos)
return (BInt(val), end_pos + 1)
}
if tag == b'l' {
let items : Array[BVal] = []
let mut cur = pos + 1
while true {
if cur >= data.length() {
raise InvalidBencode("unterminated list")
}
if data[cur] == b'e' {
return (BList(items), cur + 1)
}
let (item, next_pos) = decode_bval_at(data, cur, depth + 1)
items.push(item)
cur = next_pos
}
}
if tag == b'd' {
let entries : Array[(Bytes, BVal)] = []
let mut cur = pos + 1
while true {
if cur >= data.length() {
raise InvalidBencode("unterminated dictionary")
}
if data[cur] == b'e' {
return (BDict(entries), cur + 1)
}
let (kval, after_key) = decode_bval_at(data, cur, depth + 1)
let key_bytes = match kval {
BBytes(kb) => kb
_ => raise InvalidBencode("dictionary key must be byte string")
}
let (vval, after_val) = decode_bval_at(data, after_key, depth + 1)
entries.push((key_bytes, vval))
cur = after_val
}
}
if tag.to_int() >= 48 && tag.to_int() <= 57 {
let colon = match find_byte(data, b':', pos) {
Some(c) => c
None => raise InvalidBencode("missing ':' in byte string")
}
let len64 = decode_int_slice(data, pos, colon, allow_negative=false)
if len64 < 0L || len64 > 33554432L {
raise InvalidBencode("invalid byte string length: \{len64}")
}
let slen = len64.to_int()
let data_start = colon + 1
if data_start + slen > data.length() {
raise InvalidBencode("truncated byte string")
}
let raw = data[data_start:data_start + slen].to_owned()
return (BBytes(raw), data_start + slen)
}
raise InvalidBencode("unexpected bencode tag byte: \{tag.to_int()}")
}
///|
/// Decodes one Bencode value starting at `start`, returning `(value, next_offset)`.
pub fn bencode_decode_prefix(
data : Bytes,
start~ : Int32 = 0,
) -> (BVal, Int32) raise BtError {
decode_bval_at(data, start, 0)
}
///|
/// Decodes a complete standalone Bencode value, rejecting trailing garbage bytes.
pub fn bencode_decode(data : Bytes) -> BVal raise BtError {
let (val, next_pos) = decode_bval_at(data, 0, 0)
if next_pos != data.length() {
raise InvalidBencode(
"trailing bytes after bencode root: \{data.length() - next_pos}",
)
}
val
}
///|
/// Returns the value for ASCII `key` inside a `BDict`.
pub fn bdict_get(val : BVal, key : String) -> BVal? {
let kb = @encoding.string_to_utf8_bytes(key)
match val {
BDict(entries) => {
for e in entries {
if @crypto.ct_eq(e.0, kb) {
return Some(e.1)
}
}
None
}
_ => None
}
}
///|
pub fn bdict_get_bytes(val : BVal, key : String) -> Bytes? {
match bdict_get(val, key) {
Some(BBytes(b)) => Some(b)
_ => None
}
}
///|
pub fn bdict_get_string(val : BVal, key : String) -> String? {
match bdict_get_bytes(val, key) {
Some(b) => Some(@encoding.utf8_bytes_to_string(b)) catch { _ => None }
None => None
}
}
///|
pub fn bdict_get_int(val : BVal, key : String) -> Int64? {
match bdict_get(val, key) {
Some(BInt(n)) => Some(n)
_ => None
}
}
///|
/// Locates and returns the exact raw Bencode byte slice of the top-level `"info"`
/// dictionary from `.torrent` bytes, guaranteeing a bit-exact SHA-1 `info_hash`.
pub fn extract_info_raw(torrent_bytes : Bytes) -> Bytes raise BtError {
if torrent_bytes.length() == 0 || torrent_bytes[0] != b'd' {
raise InvalidMetainfo("torrent root must be a Bencode dictionary")
}
let mut cur = 1
while cur < torrent_bytes.length() {
if torrent_bytes[cur] == b'e' {
raise InvalidMetainfo("torrent dictionary missing 'info' key")
}
let (kval, val_start) = decode_bval_at(torrent_bytes, cur, 0)
let key_bytes = match kval {
BBytes(kb) => kb
_ => raise InvalidMetainfo("top-level torrent key must be bytes")
}
let (_vval, val_end) = decode_bval_at(torrent_bytes, val_start, 0)
if key_bytes == b"info" {
return torrent_bytes[val_start:val_end].to_owned()
}
cur = val_end
}
raise InvalidMetainfo("unterminated top-level torrent dictionary")
}
+269
View File
@@ -0,0 +1,269 @@
///|
test "Bencode encode/decode canonical sorting and raw info slice extraction" {
let val : @bittorrent.BVal = BDict([
(b"z", BInt(-42L)),
(b"a", BList([BBytes(b"hi"), BInt(0L), BBytes(b"")])),
])
let enc = @bittorrent.bencode_encode(val)
assert_eq(enc, b"d1:al2:hii0e0:e1:zi-42ee")
// Keys are sorted lexicographically in encoded output: 1:a before 1:z
let expected : @bittorrent.BVal = BDict([
(b"a", BList([BBytes(b"hi"), BInt(0L), BBytes(b"")])),
(b"z", BInt(-42L)),
])
assert_eq(@bittorrent.bencode_decode(enc), expected)
assert_eq(@bittorrent.bencode_encode(val), b"d1:al2:hii0e0:e1:zi-42ee")
assert_eq(enc, b"d1:al2:hii0e0:e1:zi-42ee")
// Prefix decode leaves trailing raw slice intact (BEP 9 ut_metadata)
let combined = b"d8:msg_typei1e5:piecei0eeRAW_SLICE"
let (hdr, next_off) = @bittorrent.bencode_decode_prefix(combined)
assert_eq(@bittorrent.bdict_get_int(hdr, "msg_type"), Some(1L))
assert_eq(combined[next_off:].to_owned(), b"RAW_SLICE")
}
///|
test "Metainfo parsing, path traversal rejection, and magnet hex/base32 links" {
let data = b"Hello I2P BitTorrent world!"
let phash = @crypto.sha1(data)
let raw_info = @bittorrent.bencode_encode(
BDict([
(b"length", BInt(data.length().to_int64())),
(b"name", BBytes(b"hello.txt")),
(b"piece length", BInt(16384L)),
(b"pieces", BBytes(phash)),
]),
)
let torrent = @bittorrent.bencode_encode(
BDict([
(b"announce", BBytes(b"http://tracker.insulaocculta.i2p/a")),
(
b"announce-list",
BList([BList([BBytes(b"http://opentracker.dg2.i2p/a")])]),
),
(
b"info",
BDict([
(b"length", BInt(data.length().to_int64())),
(b"name", BBytes(b"hello.txt")),
(b"piece length", BInt(16384L)),
(b"pieces", BBytes(phash)),
]),
),
]),
)
let meta = @bittorrent.parse_torrent(torrent)
assert_eq(meta.info_hash, @crypto.sha1(raw_info))
assert_eq(meta.name, "hello.txt")
assert_eq(meta.total_length, 27L)
assert_eq(meta.files.length(), 1)
assert_eq(meta.files[0].path, ["hello.txt"])
assert_eq(meta.trackers.length(), 2)
// Reject path traversal segments in multi-file info dictionary
let evil_info = @bittorrent.bencode_encode(
BDict([
(
b"files",
BList([
BDict([
(b"length", BInt(5L)),
(b"path", BList([BBytes(b".."), BBytes(b"etc"), BBytes(b"passwd")])),
]),
]),
),
(b"name", BBytes(b"bad")),
(b"piece length", BInt(16384L)),
(b"pieces", BBytes(@crypto.sha1(b"12345"))),
]),
)
let mut rejected = false
let _ = @bittorrent.parse_info_dict(evil_info) catch {
_ => {
rejected = true
meta
}
}
assert_true(rejected)
// Hex & Base32 magnet links
let hex_ih = @encoding.hex_encode(meta.info_hash)
let m1 = @bittorrent.parse_magnet(
"magnet:?xt=urn:btih:\{hex_ih}&dn=hello+world.txt&tr=http%3A%2F%2Ftracker.insulaocculta.i2p%2Fa",
)
assert_eq(m1.info_hash, meta.info_hash)
assert_eq(m1.display_name, "hello world.txt")
assert_eq(m1.trackers, ["http://tracker.insulaocculta.i2p/a"])
let b32_ih = @encoding.base32_encode(meta.info_hash)
let m2 = @bittorrent.parse_magnet("magnet:?xt=urn:btih:\{b32_ih}")
assert_eq(m2.info_hash, meta.info_hash)
}
///|
test "Peer wire framing, BEP 10/9, i2p_pex, i2p_dht, and chunked I2P HTTP tracker" {
let ih = @crypto.sha1(b"ih-wire-test")
let pid = @crypto.sha1(b"peer-id-test")
let hs = @bittorrent.encode_handshake(ih, pid)
let (res, dih, dpid) = @bittorrent.decode_handshake(hs)
assert_eq(res[5], b'\x10')
assert_eq(dih, ih)
assert_eq(dpid, pid)
let stream_buf : Array[Byte] = []
let msgs : Array[@bittorrent.PeerMessage] = [
KeepAlive,
Unchoke,
Interested,
Have(7U),
Bitfield(b"\x80"),
Request(1, 0, 16384),
Piece(1, 0, b"payload-bytes"),
Extended(b'\x00', @bittorrent.encode_ext_handshake(metadata_size=Some(512))),
Extended(b'\x03', @bittorrent.encode_i2p_dht_ext(6881U, 6882U)),
]
for m in msgs {
let enc = @bittorrent.encode_peer_message(m)
for i = 0; i < enc.length(); i = i + 1 {
stream_buf.push(enc[i])
}
}
for expected in msgs {
assert_eq(@bittorrent.try_decode_peer_message(stream_buf), Some(expected))
}
assert_eq(@bittorrent.try_decode_peer_message(stream_buf), None)
// Extended handshake + i2p_dht + i2p_pex + ut_metadata
let rext = @bittorrent.decode_ext_handshake(
@bittorrent.encode_ext_handshake(metadata_size=Some(512)),
)
assert_eq(rext.i2p_pex_id, Some(b'\x01'))
assert_eq(rext.ut_metadata_id, Some(b'\x02'))
assert_eq(rext.i2p_dht_id, Some(b'\x03'))
assert_eq(rext.metadata_size, Some(512))
assert_eq(
@bittorrent.decode_i2p_dht_ext(@bittorrent.encode_i2p_dht_ext(6881U, 6882U)),
Some((6881U, 6882U)),
)
let h1 = @common.Hash::sha256(b"peer1")
let h2 = @common.Hash::sha256(b"peer2")
assert_eq(@bittorrent.decode_i2p_pex(@bittorrent.encode_i2p_pex([h1, h2])), [
h1, h2,
])
let md_raw = @bittorrent.encode_metadata_data(0, 128, b"INFO_SLICE")
assert_eq(
@bittorrent.decode_metadata_msg(md_raw),
MetaData(0, 128, b"INFO_SLICE"),
)
// Chunked I2P HTTP tracker response with 32B compact peer hashes
let compact_peers = @encoding.Writer::new(capacity=64)
compact_peers.write_bytes(h1.as_bytes())
compact_peers.write_bytes(h2.as_bytes())
let bbody = @bittorrent.bencode_encode(
BDict([
(b"complete", BInt(3L)),
(b"incomplete", BInt(1L)),
(b"interval", BInt(120L)),
(b"peers", BBytes(compact_peers.to_bytes())),
]),
)
let http_resp = "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n\{bbody.length().to_int64()}\r\n"
// Hex chunk size
let hex_len = bbody.length()
let mut hx = ""
if hex_len < 16 {
hx = "0"
}
let _ = http_resp
let chunked = @encoding.Writer::new()
chunked.write_bytes(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n")
// Compute hex digits of bbody.length()
let digits : Array[Char] = []
let mut n = hex_len
while n > 0 {
let d = n % 16
digits.push(
if d < 10 {
(48 + d).unsafe_to_char()
} else {
(97 + d - 10).unsafe_to_char()
},
)
n = n / 16
}
let hx_sb = StringBuilder()
for k = digits.length() - 1; k >= 0; k = k - 1 {
hx_sb.write_char(digits[k])
}
let _ = hx
chunked.write_bytes(
@encoding.string_to_utf8_bytes(hx_sb.to_string() + "\r\n"),
)
chunked.write_bytes(bbody)
chunked.write_bytes(b"\r\n0\r\n\r\n")
let tresp = @bittorrent.parse_http_tracker_response(chunked.to_bytes())
assert_eq(tresp.interval, 120)
assert_eq(tresp.complete, 3)
assert_eq(tresp.incomplete, 1)
assert_eq(tresp.peers, [h1, h2])
}
///|
test "I2P DHT Secure Node ID, 54B compact nodes, KRPC round-trips, and XOR routing" {
let dh_a = @common.Hash::sha256(b"node-a-dest")
let dh_b = @common.Hash::sha256(b"node-b-dest")
let dht_a = @bittorrent.I2pDht::new(
dh_a,
b"rand14bytes_aa",
b"secret-a",
query_port=6881U,
reply_port=6882U,
)
assert_true(@bittorrent.verify_i2p_dht_node_id(dht_a.local_id, dh_a, 6881U))
assert_true(!@bittorrent.verify_i2p_dht_node_id(dht_a.local_id, dh_a, 6889U))
let id_b = @bittorrent.make_i2p_dht_node_id(dh_b, 6881U, b"rand14bytes_bb")
assert_true(dht_a.upsert_node(id_b, dh_b, 6881U, 1000UL))
assert_eq(dht_a.nodes.length(), 1)
// Tampered Node ID must fail Secure Node ID check
assert_true(!dht_a.upsert_node(Bytes::make(20, b'\x77'), dh_b, 6881U, 1001UL))
// 54B compact node encode/decode round-trip
let nodes_blob = @bittorrent.encode_compact_nodes(dht_a.closest_nodes(id_b))
assert_eq(nodes_blob.length(), 54)
let decoded_nodes = @bittorrent.decode_compact_nodes(
nodes_blob,
now_ms=2000UL,
)
assert_eq(decoded_nodes.length(), 1)
assert_eq(decoded_nodes[0].node_id, id_b)
assert_eq(decoded_nodes[0].dest_hash, dh_b)
assert_eq(decoded_nodes[0].port, 6881U)
// KRPC queries & responses round-trip
let ih = @crypto.sha1(b"dht-swarm-hash")
let tok = dht_a.make_token(dh_b)
assert_true(dht_a.verify_token(dh_b, tok))
assert_true(!dht_a.verify_token(dh_a, tok))
let q_gp : @bittorrent.KrpcMessage = Query(
tx_id=b"t1",
sender_id=id_b,
kind=GetPeers(info_hash=ih),
)
assert_eq(@bittorrent.decode_krpc(@bittorrent.encode_krpc(q_gp)), q_gp)
dht_a.store_peer(ih, dh_b, 5000UL)
assert_eq(dht_a.get_peers_local(ih, 5001UL), [dh_b])
let r_gp : @bittorrent.KrpcMessage = Response(
tx_id=b"t1",
sender_id=dht_a.local_id,
nodes=nodes_blob,
values=[dh_b.as_bytes()],
token=Some(tok),
)
assert_eq(@bittorrent.decode_krpc(@bittorrent.encode_krpc(r_gp)), r_gp)
}
+619
View File
@@ -0,0 +1,619 @@
///|
/// Canonical Pure-MoonBit I2P BitTorrent DHT (BEP 5 adapted per I2P DHT specification):
/// - Secure Node IDs: first 4B = dest_hash[0..4], next 2B = dest_hash[4..6] ^ port_be16
/// - 54-byte compact nodes: 20B node_id || 32B dest_hash || 2B port_be16
/// - KRPC query/response/error codec & routing table with Kademlia XOR distance
///|
/// Builds a Secure I2P DHT 20-byte Node ID bound to `dest_hash` and `query_port`.
pub fn make_i2p_dht_node_id(
dest_hash : @common.Hash,
query_port : UInt32,
rand14 : Bytes,
) -> Bytes raise BtError {
if rand14.length() < 14 {
raise InvalidKrpc("rand14 must be at least 14 bytes")
}
let hb = dest_hash.as_bytes()
let out = FixedArray::make(20, b'\x00')
out[0] = hb[0]
out[1] = hb[1]
out[2] = hb[2]
out[3] = hb[3]
out[4] = (hb[4].to_int() ^ ((query_port.reinterpret_as_int() >> 8) & 0xFF)).to_byte()
out[5] = (hb[5].to_int() ^ (query_port.reinterpret_as_int() & 0xFF)).to_byte()
for i = 0; i < 14; i = i + 1 {
out[6 + i] = rand14[i]
}
Bytes::from_array(out)
}
///|
/// Verifies that `node_id` (20B) satisfies I2P DHT Secure Node ID rules for `(dest_hash, query_port)`.
pub fn verify_i2p_dht_node_id(
node_id : Bytes,
dest_hash : @common.Hash,
query_port : UInt32,
) -> Bool {
if node_id.length() != 20 {
return false
}
let hb = dest_hash.as_bytes()
let p_hi = (query_port.reinterpret_as_int() >> 8) & 0xFF
let p_lo = query_port.reinterpret_as_int() & 0xFF
node_id[0] == hb[0] &&
node_id[1] == hb[1] &&
node_id[2] == hb[2] &&
node_id[3] == hb[3] &&
node_id[4] == (hb[4].to_int() ^ p_hi).to_byte() &&
node_id[5] == (hb[5].to_int() ^ p_lo).to_byte()
}
///|
#derive(Eq, Debug)
pub(all) struct DhtNode {
node_id : Bytes // 20B
dest_hash : @common.Hash
port : UInt32
last_seen_ms : UInt64
}
///|
/// Encodes DHT nodes in canonical 54-byte I2P compact format (`20B id || 32B dest_hash || 2B port_be16`).
pub fn encode_compact_nodes(nodes : Array[DhtNode]) -> Bytes {
let w = @encoding.Writer::new(capacity=nodes.length() * 54)
for n in nodes {
if n.node_id.length() == 20 {
w.write_bytes(n.node_id)
w.write_bytes(n.dest_hash.as_bytes())
w.write_u16_be(n.port)
}
}
w.to_bytes()
}
///|
/// Decodes canonical 54-byte compact I2P DHT nodes (`nodes` dictionary field).
pub fn decode_compact_nodes(
blob : Bytes,
now_ms~ : UInt64 = 0UL,
) -> Array[DhtNode] raise BtError {
if blob.length() % 54 != 0 {
raise InvalidKrpc(
"compact I2P DHT nodes length must be a multiple of 54, got \{blob.length()}",
)
}
let count = blob.length() / 54
let out : Array[DhtNode] = Array(capacity=count)
for i = 0; i < count; i = i + 1 {
let off = i * 54
let node_id = blob[off:off + 20].to_owned()
let dh = @common.Hash::from_bytes(blob[off + 20:off + 52].to_owned()) catch {
e => raise Common(e)
}
let port = ((blob[off + 52].to_int() << 8) | blob[off + 53].to_int()).reinterpret_as_uint()
if port > 0U {
out.push({ node_id, dest_hash: dh, port, last_seen_ms: now_ms, })
}
}
out
}
///|
/// Computes 20-byte Kademlia XOR distance between `a` and `b`.
pub fn xor_distance_20(a : Bytes, b : Bytes) -> Bytes {
let out = FixedArray::make(20, b'\x00')
let n = if a.length() < b.length() { a.length() } else { b.length() }
let len = if n < 20 { n } else { 20 }
for i = 0; i < len; i = i + 1 {
out[i] = (a[i].to_int() ^ b[i].to_int()).to_byte()
}
Bytes::from_array(out)
}
///|
pub fn cmp_distance_20(a : Bytes, b : Bytes) -> Int32 {
cmp_bytes_lex(a, b)
}
///|
#derive(Eq, Debug)
pub(all) enum KrpcQueryKind {
Ping
FindNode(target~ : Bytes)
GetPeers(info_hash~ : Bytes)
AnnouncePeer(
info_hash~ : Bytes,
port~ : UInt32,
token~ : Bytes,
implied_port~ : Bool
)
}
///|
#derive(Eq, Debug)
pub(all) enum KrpcMessage {
Query(tx_id~ : Bytes, sender_id~ : Bytes, kind~ : KrpcQueryKind)
Response(
tx_id~ : Bytes,
sender_id~ : Bytes,
nodes~ : Bytes,
values~ : Array[Bytes],
token~ : Bytes?
)
ErrorMsg(tx_id~ : Bytes, code~ : Int64, msg~ : String)
}
///|
/// Encodes a KRPC message into Bencode bytes.
pub fn encode_krpc(msg : KrpcMessage) -> Bytes {
match msg {
Query(tx_id~, sender_id~, kind~) =>
match kind {
Ping =>
bencode_encode(
BDict([
(b"a", BDict([(b"id", BBytes(sender_id))])),
(b"q", BBytes(b"ping")),
(b"t", BBytes(tx_id)),
(b"y", BBytes(b"q")),
]),
)
FindNode(target~) =>
bencode_encode(
BDict([
(
b"a",
BDict([(b"id", BBytes(sender_id)), (b"target", BBytes(target))]),
),
(b"q", BBytes(b"find_node")),
(b"t", BBytes(tx_id)),
(b"y", BBytes(b"q")),
]),
)
GetPeers(info_hash~) =>
bencode_encode(
BDict([
(
b"a",
BDict([
(b"id", BBytes(sender_id)),
(b"info_hash", BBytes(info_hash)),
]),
),
(b"q", BBytes(b"get_peers")),
(b"t", BBytes(tx_id)),
(b"y", BBytes(b"q")),
]),
)
AnnouncePeer(info_hash~, port~, token~, implied_port~) => {
let args : Array[(Bytes, BVal)] = [
(b"id", BBytes(sender_id)),
(b"info_hash", BBytes(info_hash)),
(b"port", BInt(port.to_int64())),
(b"token", BBytes(token)),
]
if implied_port {
args.push((b"implied_port", BInt(1L)))
}
bencode_encode(
BDict([
(b"a", BDict(args)),
(b"q", BBytes(b"announce_peer")),
(b"t", BBytes(tx_id)),
(b"y", BBytes(b"q")),
]),
)
}
}
Response(tx_id~, sender_id~, nodes~, values~, token~) => {
let r_entries : Array[(Bytes, BVal)] = [(b"id", BBytes(sender_id))]
if nodes.length() > 0 {
r_entries.push((b"nodes", BBytes(nodes)))
}
if values.length() > 0 {
let vlist : Array[BVal] = Array(capacity=values.length())
for v in values {
vlist.push(BBytes(v))
}
r_entries.push((b"values", BList(vlist)))
}
match token {
Some(tk) => r_entries.push((b"token", BBytes(tk)))
None => ()
}
bencode_encode(
BDict([
(b"r", BDict(r_entries)),
(b"t", BBytes(tx_id)),
(b"y", BBytes(b"r")),
]),
)
}
ErrorMsg(tx_id~, code~, msg~) =>
bencode_encode(
BDict([
(
b"e",
BList([BInt(code), BBytes(@encoding.string_to_utf8_bytes(msg))]),
),
(b"t", BBytes(tx_id)),
(b"y", BBytes(b"e")),
]),
)
}
}
///|
/// Decodes a Bencoded KRPC packet.
pub fn decode_krpc(data : Bytes) -> KrpcMessage raise BtError {
let root = bencode_decode(data)
let tx_id = match bdict_get_bytes(root, "t") {
Some(t) => t
None => raise InvalidKrpc("KRPC packet missing 't' transaction id")
}
let y = match bdict_get_string(root, "y") {
Some(yv) => yv
None => raise InvalidKrpc("KRPC packet missing 'y' message type")
}
if y == "q" {
let q = match bdict_get_string(root, "q") {
Some(qv) => qv
None => raise InvalidKrpc("KRPC query missing 'q'")
}
let a = match bdict_get(root, "a") {
Some(av) => av
None => raise InvalidKrpc("KRPC query missing 'a'")
}
let sender_id = match bdict_get_bytes(a, "id") {
Some(id) if id.length() == 20 => id
_ => raise InvalidKrpc("KRPC query missing valid 20B 'id'")
}
if q == "ping" {
return Query(tx_id~, sender_id~, kind=Ping)
}
if q == "find_node" {
let target = match bdict_get_bytes(a, "target") {
Some(t) if t.length() == 20 => t
_ => raise InvalidKrpc("find_node missing valid 20B 'target'")
}
return Query(tx_id~, sender_id~, kind=FindNode(target~))
}
if q == "get_peers" {
let info_hash = match bdict_get_bytes(a, "info_hash") {
Some(ih) if ih.length() == 20 => ih
_ => raise InvalidKrpc("get_peers missing valid 20B 'info_hash'")
}
return Query(tx_id~, sender_id~, kind=GetPeers(info_hash~))
}
if q == "announce_peer" {
let info_hash = match bdict_get_bytes(a, "info_hash") {
Some(ih) if ih.length() == 20 => ih
_ => raise InvalidKrpc("announce_peer missing valid 20B 'info_hash'")
}
let port = match bdict_get_int(a, "port") {
Some(p) if p > 0L && p <= 65535L => p.to_int().reinterpret_as_uint()
_ => 6881U
}
let implied = match bdict_get_int(a, "implied_port") {
Some(v) => v != 0L
None => false
}
let token = match bdict_get_bytes(a, "token") {
Some(tk) => tk
None => raise InvalidKrpc("announce_peer missing 'token'")
}
return Query(
tx_id~,
sender_id~,
kind=AnnouncePeer(info_hash~, port~, token~, implied_port=implied),
)
}
raise InvalidKrpc("unsupported KRPC query '\{q}'")
}
if y == "r" {
let r = match bdict_get(root, "r") {
Some(rv) => rv
None => raise InvalidKrpc("KRPC response missing 'r'")
}
let sender_id = match bdict_get_bytes(r, "id") {
Some(id) if id.length() == 20 => id
_ => raise InvalidKrpc("KRPC response missing valid 20B 'id'")
}
let nodes = match bdict_get_bytes(r, "nodes") {
Some(n) => n
None => b""
}
let values : Array[Bytes] = []
match bdict_get(r, "values") {
Some(BList(vlist)) =>
for item in vlist {
match item {
BBytes(vb) => values.push(vb)
_ => ()
}
}
_ => ()
}
let token = bdict_get_bytes(r, "token")
return Response(tx_id~, sender_id~, nodes~, values~, token~)
}
if y == "e" {
match bdict_get(root, "e") {
Some(BList(elist)) if elist.length() >= 2 => {
let code = match elist[0] {
BInt(c) => c
_ => 201L
}
let msg = match elist[1] {
BBytes(mb) =>
@encoding.utf8_bytes_to_string(mb) catch {
_ => "krpc error"
}
_ => "krpc error"
}
return ErrorMsg(tx_id~, code~, msg~)
}
_ => return ErrorMsg(tx_id~, code=201L, msg="malformed krpc error")
}
}
raise InvalidKrpc("unknown KRPC message type '\{y}'")
}
///|
#derive(Eq, Debug)
pub(all) struct DhtPendingTx {
tx_id : Bytes
kind : String // "ping" | "find_node" | "get_peers" | "announce_peer"
info_hash : Bytes?
dest_hash : @common.Hash
port : UInt32
sent_ms : UInt64
}
///|
priv struct DhtPeerEntry {
peer_hash : @common.Hash
expires_ms : UInt64
}
///|
/// Pure-MoonBit I2P Kademlia DHT state machine (routing table, token secret, peer store).
pub struct I2pDht {
local_id : Bytes // 20B Secure I2P Node ID
local_dest_hash : @common.Hash
query_port : UInt32
reply_port : UInt32
priv secret : Bytes
nodes : Array[DhtNode]
pending_txs : Array[DhtPendingTx]
priv peer_store : Array[(Bytes, Array[DhtPeerEntry])] // (info_hash_20B, peers)
mut next_tx_seq : UInt32
mut queries_sent : UInt64
mut responses_recv : UInt64
mut queries_recv : UInt64
mut peers_discovered : UInt64
}
///|
pub fn I2pDht::new(
local_dest_hash : @common.Hash,
rand14 : Bytes,
secret : Bytes,
query_port~ : UInt32 = 6881U,
reply_port~ : UInt32 = 6882U,
) -> I2pDht raise BtError {
let local_id = make_i2p_dht_node_id(local_dest_hash, query_port, rand14)
{
local_id,
local_dest_hash,
query_port,
reply_port,
secret,
nodes: [],
pending_txs: [],
peer_store: [],
next_tx_seq: 1U,
queries_sent: 0UL,
responses_recv: 0UL,
queries_recv: 0UL,
peers_discovered: 0UL,
}
}
///|
pub fn I2pDht::alloc_tx_id(self : I2pDht) -> Bytes {
let id = self.next_tx_seq
self.next_tx_seq = id + 1U
let w = @encoding.Writer::new(capacity=4)
w.write_u32_be(id)
w.to_bytes()
}
///|
pub fn I2pDht::register_pending_tx(
self : I2pDht,
tx_id : Bytes,
kind : String,
dest_hash : @common.Hash,
port : UInt32,
sent_ms : UInt64,
info_hash~ : Bytes? = None,
) -> Unit {
while self.pending_txs.length() >= 256 {
let _ = self.pending_txs.remove(0)
}
self.pending_txs.push({ tx_id, kind, info_hash, dest_hash, port, sent_ms, })
self.queries_sent += 1UL
}
///|
pub fn I2pDht::take_pending_tx(self : I2pDht, tx_id : Bytes) -> DhtPendingTx? {
for i = 0; i < self.pending_txs.length(); i = i + 1 {
if @crypto.ct_eq(self.pending_txs[i].tx_id, tx_id) {
self.responses_recv += 1UL
return Some(self.pending_txs.remove(i))
}
}
None
}
///|
pub fn I2pDht::record_query_recv(self : I2pDht) -> Unit {
self.queries_recv += 1UL
}
///|
pub fn I2pDht::record_peers_discovered(self : I2pDht, count : UInt64) -> Unit {
self.peers_discovered += count
}
///|
pub fn I2pDht::prune_expired_txs(self : I2pDht, now_ms : UInt64) -> Unit {
let mut i = 0
while i < self.pending_txs.length() {
if now_ms > self.pending_txs[i].sent_ms + 30000UL {
let _ = self.pending_txs.remove(i)
} else {
i += 1
}
}
}
///|
/// Inserts or refreshes a remote DHT node, enforcing Secure I2P Node ID verification by default.
pub fn I2pDht::upsert_node(
self : I2pDht,
node_id : Bytes,
dest_hash : @common.Hash,
port : UInt32,
now_ms : UInt64,
verify_secure_id~ : Bool = true,
) -> Bool {
if node_id.length() != 20 || port == 0U {
return false
}
if dest_hash == self.local_dest_hash {
return false
}
if verify_secure_id && !verify_i2p_dht_node_id(node_id, dest_hash, port) {
return false
}
for i = 0; i < self.nodes.length(); i = i + 1 {
if self.nodes[i].dest_hash == dest_hash && self.nodes[i].port == port {
self.nodes[i] = { node_id, dest_hash, port, last_seen_ms: now_ms, }
return true
}
}
if self.nodes.length() >= 160 {
// Evict oldest seen node outside top close neighborhood
let mut oldest_idx = 0
let mut oldest_ms = self.nodes[0].last_seen_ms
for i = 1; i < self.nodes.length(); i = i + 1 {
if self.nodes[i].last_seen_ms < oldest_ms {
oldest_ms = self.nodes[i].last_seen_ms
oldest_idx = i
}
}
let _ = self.nodes.remove(oldest_idx)
}
self.nodes.push({ node_id, dest_hash, port, last_seen_ms: now_ms, })
true
}
///|
/// Returns up to `limit` known DHT nodes sorted closest by 20-byte XOR distance to `target_20`.
pub fn I2pDht::closest_nodes(
self : I2pDht,
target_20 : Bytes,
limit~ : Int32 = 8,
) -> Array[DhtNode] {
let pairs : Array[(Bytes, DhtNode)] = Array(capacity=self.nodes.length())
for n in self.nodes {
pairs.push((xor_distance_20(n.node_id, target_20), n))
}
pairs.sort_by(fn(a, b) { cmp_distance_20(a.0, b.0) })
let out : Array[DhtNode] = []
let cap = if limit < pairs.length() { limit } else { pairs.length() }
for i = 0; i < cap; i = i + 1 {
out.push(pairs[i].1)
}
out
}
///|
pub fn I2pDht::make_token(self : I2pDht, sender_hash : @common.Hash) -> Bytes {
let w = @encoding.Writer::new(capacity=self.secret.length() + 32)
w.write_bytes(self.secret)
w.write_bytes(sender_hash.as_bytes())
@crypto.sha256(w.to_bytes())[:8].to_owned()
}
///|
pub fn I2pDht::verify_token(
self : I2pDht,
sender_hash : @common.Hash,
token : Bytes,
) -> Bool {
@crypto.ct_eq(self.make_token(sender_hash), token)
}
///|
pub fn I2pDht::store_peer(
self : I2pDht,
info_hash : Bytes,
peer_hash : @common.Hash,
now_ms : UInt64,
) -> Unit {
if info_hash.length() != 20 {
return
}
let expires_ms = now_ms + 1800000UL // 30 minutes
for entry in self.peer_store {
if @crypto.ct_eq(entry.0, info_hash) {
let mut updated = false
for j = 0; j < entry.1.length(); j = j + 1 {
if entry.1[j].peer_hash == peer_hash {
entry.1[j] = { peer_hash, expires_ms, }
updated = true
break
}
}
if !updated {
while entry.1.length() >= 64 {
let _ = entry.1.remove(0)
}
entry.1.push({ peer_hash, expires_ms, })
}
return
}
}
while self.peer_store.length() >= 128 {
let _ = self.peer_store.remove(0)
}
self.peer_store.push((info_hash, [{ peer_hash, expires_ms, }]))
}
///|
pub fn I2pDht::get_peers_local(
self : I2pDht,
info_hash : Bytes,
now_ms : UInt64,
) -> Array[@common.Hash] {
let out : Array[@common.Hash] = []
for entry in self.peer_store {
if @crypto.ct_eq(entry.0, info_hash) {
let mut j = 0
while j < entry.1.length() {
if entry.1[j].expires_ms <= now_ms {
let _ = entry.1.remove(j)
} else {
out.push(entry.1[j].peer_hash)
j += 1
}
}
break
}
}
out
}
+408
View File
@@ -0,0 +1,408 @@
///|
/// Pure-MoonBit BitTorrent Metainfo (`.torrent` BEP 3/12) and Magnet (BEP 9) parser
/// with path traversal sanitization and RFC 3986 percent-encoding helpers.
///|
#derive(Eq, Debug)
pub(all) struct TorrentFile {
path : Array[String]
length : Int64
}
///|
#derive(Eq, Debug)
pub(all) struct Metainfo {
info_hash : Bytes // 20-byte SHA-1
name : String
piece_length : Int64
piece_hashes : Array[Bytes]
total_length : Int64
files : Array[TorrentFile]
trackers : Array[String]
raw_info : Bytes
}
///|
#derive(Eq, Debug)
pub(all) struct MagnetLink {
info_hash : Bytes // 20-byte SHA-1
display_name : String
trackers : Array[String]
dht_nodes : Array[(String, UInt32)]
}
///|
fn check_safe_path_segment(seg : String) -> String raise BtError {
if seg.length() == 0 || seg == "." || seg == ".." {
raise InvalidMetainfo("unsafe path segment '\{seg}'")
}
for ch in seg {
if ch == '/' || ch == '\\' || ch.to_int() < 0x20 {
raise InvalidMetainfo(
"illegal character in torrent path segment '\{seg}'",
)
}
}
seg
}
///|
fn sanitize_path_segments(segs : Array[String]) -> Array[String] raise BtError {
if segs.length() == 0 {
raise InvalidMetainfo("empty torrent file path")
}
let out : Array[String] = Array(capacity=segs.length())
for s in segs {
out.push(check_safe_path_segment(s))
}
out
}
///|
fn append_unique_str(list : Array[String], val : String) -> Unit {
if val.length() == 0 {
return
}
for item in list {
if item == val {
return
}
}
list.push(val)
}
///|
/// Parses the raw `"info"` dictionary bytes (`BEP 9` / `.torrent` `"info"` value)
/// into a validated `Metainfo`.
pub fn parse_info_dict(
raw_info : Bytes,
trackers~ : Array[String] = [],
) -> Metainfo raise BtError {
let info = bencode_decode(raw_info)
if !(info is BDict(_)) {
raise InvalidMetainfo("info value must be a dictionary")
}
let raw_name = match bdict_get_string(info, "name") {
Some(n) => n
None => raise InvalidMetainfo("info dictionary missing UTF-8 'name'")
}
let name = check_safe_path_segment(raw_name)
let piece_length = match bdict_get_int(info, "piece length") {
Some(pl) if pl > 0L => pl
_ => raise InvalidMetainfo("info dictionary missing valid 'piece length'")
}
let pieces_blob = match bdict_get_bytes(info, "pieces") {
Some(pb) if pb.length() > 0 && pb.length() % 20 == 0 => pb
_ => raise InvalidMetainfo("info dictionary has invalid 'pieces' blob")
}
let num_pieces = pieces_blob.length() / 20
let piece_hashes : Array[Bytes] = Array(capacity=num_pieces)
for i = 0; i < num_pieces; i = i + 1 {
piece_hashes.push(pieces_blob[i * 20:(i + 1) * 20].to_owned())
}
let files : Array[TorrentFile] = []
let mut total_length = 0L
match bdict_get(info, "files") {
Some(BList(flist)) => {
if flist.length() == 0 {
raise InvalidMetainfo("multi-file torrent has empty 'files' list")
}
for entry in flist {
let flen = match bdict_get_int(entry, "length") {
Some(l) if l >= 0L => l
_ => raise InvalidMetainfo("file entry missing valid 'length'")
}
let segs : Array[String] = [name]
match bdict_get(entry, "path") {
Some(BList(plist)) => {
if plist.length() == 0 {
raise InvalidMetainfo("file entry has empty 'path'")
}
for pitem in plist {
match pitem {
BBytes(pb) => {
let ps = @encoding.utf8_bytes_to_string(pb) catch {
e => raise Encoding(e)
}
segs.push(ps)
}
_ => raise InvalidMetainfo("non-string element in file 'path'")
}
}
}
_ => raise InvalidMetainfo("file entry missing 'path' list")
}
let clean = sanitize_path_segments(segs)
files.push({ path: clean, length: flen, })
total_length = total_length + flen
}
}
Some(_) => raise InvalidMetainfo("'files' entry must be a list")
None => {
let flen = match bdict_get_int(info, "length") {
Some(l) if l >= 0L => l
_ => raise InvalidMetainfo("single-file torrent missing valid 'length'")
}
files.push({ path: [name], length: flen, })
total_length = flen
}
}
if total_length > 0L {
let expected_pieces = (total_length + piece_length - 1L) / piece_length
if expected_pieces != num_pieces.to_int64() {
raise InvalidMetainfo(
"piece hash count \{num_pieces} does not match length \{total_length} / piece_length \{piece_length}",
)
}
}
let clean_trackers : Array[String] = []
for tr in trackers {
append_unique_str(clean_trackers, tr)
}
{
info_hash: @crypto.sha1(raw_info),
name,
piece_length,
piece_hashes,
total_length,
files,
trackers: clean_trackers,
raw_info,
}
}
///|
/// Parses a full `.torrent` file (BEP 3 + BEP 12 `announce-list`) and validates all fields.
pub fn parse_torrent(torrent_bytes : Bytes) -> Metainfo raise BtError {
let root = bencode_decode(torrent_bytes)
let trackers : Array[String] = []
match bdict_get_string(root, "announce") {
Some(tr) => append_unique_str(trackers, tr.trim().to_owned())
None => ()
}
match bdict_get(root, "announce-list") {
Some(BList(tiers)) =>
for tier in tiers {
match tier {
BList(urls) =>
for u in urls {
match u {
BBytes(ub) => {
let us = @encoding.utf8_bytes_to_string(ub) catch { _ => "" }
append_unique_str(trackers, us.trim().to_owned())
}
_ => ()
}
}
_ => ()
}
}
_ => ()
}
let raw_info = extract_info_raw(torrent_bytes)
parse_info_dict(raw_info, trackers~)
}
///|
fn bt_hex_nibble(c : Int32) -> Int32 {
if c >= 48 && c <= 57 {
c - 48
} else if c >= 65 && c <= 70 {
c - 55
} else if c >= 97 && c <= 102 {
c - 87
} else {
-1
}
}
///|
fn percent_decode_param(s : String, plus_as_space~ : Bool = true) -> String {
let out : Array[Byte] = []
let raw = @encoding.string_to_utf8_bytes(s)
let mut i = 0
while i < raw.length() {
let b = raw[i]
if plus_as_space && b == b'+' {
out.push(b' ')
i += 1
} else if b == b'%' && i + 2 < raw.length() {
let hi = bt_hex_nibble(raw[i + 1].to_int())
let lo = bt_hex_nibble(raw[i + 2].to_int())
if hi >= 0 && lo >= 0 {
out.push(((hi << 4) | lo).to_byte())
i += 3
continue
}
out.push(b)
i += 1
} else {
out.push(b)
i += 1
}
}
@encoding.utf8_bytes_to_string(Bytes::from_array(out)) catch {
_ => s
}
}
///|
fn parse_u32_port_str(s : String) -> UInt32? {
if s.length() == 0 {
return None
}
let mut val = 0U
for ch in s {
if ch < '0' || ch > '9' {
return None
}
val = val * 10U + (ch.to_int() - '0'.to_int()).reinterpret_as_uint()
if val > 65535U {
return None
}
}
if val == 0U {
None
} else {
Some(val)
}
}
///|
fn parse_host_port_pair(spec : String) -> (String, UInt32)? {
let mut colon = -1
for i = 0; i < spec.length(); i = i + 1 {
if spec[i] == ':' {
colon = i
}
}
if colon <= 0 || colon + 1 >= spec.length() {
return None
}
let host = spec[:colon].to_owned().trim().to_owned()
let port_s = spec[colon + 1:].to_owned().trim().to_owned()
match parse_u32_port_str(port_s) {
Some(p) if host.length() > 0 => Some((host, p))
_ => None
}
}
///|
/// Parses a BitTorrent `magnet:?xt=urn:btih:...` URI (40-char hex or 32-char Base32 info_hash).
pub fn parse_magnet(uri : String) -> MagnetLink raise BtError {
let trimmed = uri.trim().to_owned()
if !trimmed.to_lower().has_prefix("magnet:?") {
raise InvalidMagnet("URI must start with 'magnet:?'")
}
let query = trimmed[8:].to_owned()
let mut info_hash : Bytes? = None
let mut display_name = ""
let trackers : Array[String] = []
let dht_nodes : Array[(String, UInt32)] = []
for part_view in query.split("&") {
let part = part_view.to_owned()
if part.length() == 0 {
continue
}
let mut eq = -1
for i = 0; i < part.length(); i = i + 1 {
if part[i] == '=' {
eq = i
break
}
}
if eq <= 0 {
continue
}
let key = part[:eq].to_owned().to_lower()
let raw_val = part[eq + 1:].to_owned()
if key == "xt" {
let decoded = percent_decode_param(raw_val, plus_as_space=false)
let lower_xt = decoded.to_lower()
if lower_xt.has_prefix("urn:btih:") {
let hash_str = decoded[9:].to_owned()
let parsed = if hash_str.length() == 40 {
@encoding.hex_decode(hash_str) catch {
e => raise Encoding(e)
}
} else if hash_str.length() == 32 {
@encoding.base32_decode(hash_str) catch {
e => raise Encoding(e)
}
} else {
raise InvalidMagnet(
"unsupported btih hash length: \{hash_str.length()}",
)
}
if parsed.length() != 20 {
raise InvalidMagnet("decoded btih must be 20 bytes")
}
info_hash = Some(parsed)
}
} else if key == "dn" {
display_name = percent_decode_param(raw_val, plus_as_space=true)
} else if key == "tr" {
let tr = percent_decode_param(raw_val, plus_as_space=false)
.trim()
.to_owned()
append_unique_str(trackers, tr)
} else if key == "dht" || key == "x.pe" {
let val = percent_decode_param(raw_val, plus_as_space=false)
match parse_host_port_pair(val) {
Some(pair) => dht_nodes.push(pair)
None => ()
}
}
}
let ih = match info_hash {
Some(h) => h
None => raise InvalidMagnet("magnet URI missing xt=urn:btih:<hash>")
}
let name = if display_name.length() > 0 {
display_name
} else {
@encoding.hex_encode(ih)
}
{ info_hash: ih, display_name: name, trackers, dht_nodes, }
}
///|
fn hex_upper_char(n : Int32) -> Char {
if n < 10 {
(48 + n).unsafe_to_char()
} else {
(65 + n - 10).unsafe_to_char()
}
}
///|
fn is_rfc3986_unreserved(b : Byte) -> Bool {
let v = b.to_int()
(v >= 65 && v <= 90) ||
(v >= 97 && v <= 122) ||
(v >= 48 && v <= 57) ||
v == 45 || // '-'
v == 95 || // '_'
v == 46 || // '.'
v == 126 // '~'
}
///|
/// Percent-encodes raw bytes (such as `info_hash` / `peer_id`) for BitTorrent tracker GET queries.
pub fn url_encode_bytes(data : Bytes) -> String {
let sb = StringBuilder(size_hint=data.length() * 3)
for i = 0; i < data.length(); i = i + 1 {
let b = data[i]
if is_rfc3986_unreserved(b) {
sb.write_char(b.to_int().unsafe_to_char())
} else {
let v = b.to_int()
sb.write_char('%')
sb.write_char(hex_upper_char((v >> 4) & 0xF))
sb.write_char(hex_upper_char(v & 0xF))
}
}
sb.to_string()
}
+5
View File
@@ -0,0 +1,5 @@
import {
"experiments/moon_i2p/encoding",
"experiments/moon_i2p/crypto",
"experiments/moon_i2p/common",
}
+251
View File
@@ -0,0 +1,251 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/moon_i2p/bittorrent"
import {
"experiments/moon_i2p/common",
"experiments/moon_i2p/encoding",
"moonbitlang/core/debug",
}
// Values
pub fn bdict_get(BVal, String) -> BVal?
pub fn bdict_get_bytes(BVal, String) -> Bytes?
pub fn bdict_get_int(BVal, String) -> Int64?
pub fn bdict_get_string(BVal, String) -> String?
pub fn bencode_decode(Bytes) -> BVal raise BtError
pub fn bencode_decode_prefix(Bytes, start? : Int32) -> (BVal, Int32) raise BtError
pub fn bencode_encode(BVal) -> Bytes
pub let bt_block_size : Int32
pub let bt_protocol_string : Bytes
pub fn build_http_announce_request(TrackerUrl, Bytes, Bytes, Int64, Int64, Int64, event? : String, local_dest_b64? : String) -> String
pub fn cmp_distance_20(Bytes, Bytes) -> Int32
pub fn decode_compact_nodes(Bytes, now_ms? : UInt64) -> Array[DhtNode] raise BtError
pub fn decode_ext_handshake(Bytes) -> RemoteExtensions raise BtError
pub fn decode_handshake(Bytes) -> (Bytes, Bytes, Bytes) raise BtError
pub fn decode_i2p_dht_ext(Bytes) -> (UInt32, UInt32)?
pub fn decode_i2p_pex(Bytes) -> Array[@common.Hash]
pub fn decode_krpc(Bytes) -> KrpcMessage raise BtError
pub fn decode_metadata_msg(Bytes) -> MetadataMsg raise BtError
pub fn encode_compact_nodes(Array[DhtNode]) -> Bytes
pub fn encode_ext_handshake(metadata_size? : Int32?) -> Bytes
pub fn encode_handshake(Bytes, Bytes) -> Bytes raise BtError
pub fn encode_i2p_dht_ext(UInt32, UInt32) -> Bytes
pub fn encode_i2p_pex(Array[@common.Hash]) -> Bytes
pub fn encode_krpc(KrpcMessage) -> Bytes
pub fn encode_metadata_data(Int32, Int32, Bytes) -> Bytes
pub fn encode_metadata_reject(Int32) -> Bytes
pub fn encode_metadata_request(Int32) -> Bytes
pub fn encode_peer_message(PeerMessage) -> Bytes
pub let ext_id_i2p_dht : Byte
pub let ext_id_pex : Byte
pub let ext_id_ut_metadata : Byte
pub fn extract_info_raw(Bytes) -> Bytes raise BtError
pub fn make_i2p_dht_node_id(@common.Hash, UInt32, Bytes) -> Bytes raise BtError
pub fn parse_http_tracker_response(Bytes) -> TrackerResponse raise BtError
pub fn parse_http_tracker_url(String) -> TrackerUrl?
pub fn parse_info_dict(Bytes, trackers? : Array[String]) -> Metainfo raise BtError
pub fn parse_magnet(String) -> MagnetLink raise BtError
pub fn parse_torrent(Bytes) -> Metainfo raise BtError
pub fn try_decode_peer_message(Array[Byte]) -> PeerMessage? raise BtError
pub fn url_encode_bytes(Bytes) -> String
pub fn verify_i2p_dht_node_id(Bytes, @common.Hash, UInt32) -> Bool
pub fn xor_distance_20(Bytes, Bytes) -> Bytes
// Errors
#derive(Eq, @debug.Debug)
pub suberror BtError {
InvalidBencode(String)
InvalidMetainfo(String)
InvalidMagnet(String)
InvalidWire(String)
InvalidKrpc(String)
Encoding(@encoding.EncodingError)
Common(@common.CommonError)
}
// Types and methods
#derive(Eq, @debug.Debug)
pub(all) enum BVal {
BInt(Int64)
BBytes(Bytes)
BList(Array[BVal])
BDict(Array[(Bytes, BVal)])
}
#derive(Eq, @debug.Debug)
pub(all) struct DhtNode {
node_id : Bytes
dest_hash : @common.Hash
port : UInt32
last_seen_ms : UInt64
}
#derive(Eq, @debug.Debug)
pub(all) struct DhtPendingTx {
tx_id : Bytes
kind : String
info_hash : Bytes?
dest_hash : @common.Hash
port : UInt32
sent_ms : UInt64
}
pub struct I2pDht {
local_id : Bytes
local_dest_hash : @common.Hash
query_port : UInt32
reply_port : UInt32
nodes : Array[DhtNode]
pending_txs : Array[DhtPendingTx]
mut next_tx_seq : UInt32
mut queries_sent : UInt64
mut responses_recv : UInt64
mut queries_recv : UInt64
mut peers_discovered : UInt64
// private fields
}
pub fn I2pDht::alloc_tx_id(Self) -> Bytes
pub fn I2pDht::closest_nodes(Self, Bytes, limit? : Int32) -> Array[DhtNode]
pub fn I2pDht::get_peers_local(Self, Bytes, UInt64) -> Array[@common.Hash]
pub fn I2pDht::make_token(Self, @common.Hash) -> Bytes
pub fn I2pDht::new(@common.Hash, Bytes, Bytes, query_port? : UInt32, reply_port? : UInt32) -> Self raise BtError
pub fn I2pDht::prune_expired_txs(Self, UInt64) -> Unit
pub fn I2pDht::record_peers_discovered(Self, UInt64) -> Unit
pub fn I2pDht::record_query_recv(Self) -> Unit
pub fn I2pDht::register_pending_tx(Self, Bytes, String, @common.Hash, UInt32, UInt64, info_hash? : Bytes?) -> Unit
pub fn I2pDht::store_peer(Self, Bytes, @common.Hash, UInt64) -> Unit
pub fn I2pDht::take_pending_tx(Self, Bytes) -> DhtPendingTx?
pub fn I2pDht::upsert_node(Self, Bytes, @common.Hash, UInt32, UInt64, verify_secure_id? : Bool) -> Bool
pub fn I2pDht::verify_token(Self, @common.Hash, Bytes) -> Bool
#derive(Eq, @debug.Debug)
pub(all) enum KrpcMessage {
Query(tx_id~ : Bytes, sender_id~ : Bytes, kind~ : KrpcQueryKind)
Response(tx_id~ : Bytes, sender_id~ : Bytes, nodes~ : Bytes, values~ : Array[Bytes], token~ : Bytes?)
ErrorMsg(tx_id~ : Bytes, code~ : Int64, msg~ : String)
}
#derive(Eq, @debug.Debug)
pub(all) enum KrpcQueryKind {
Ping
FindNode(target~ : Bytes)
GetPeers(info_hash~ : Bytes)
AnnouncePeer(info_hash~ : Bytes, port~ : UInt32, token~ : Bytes, implied_port~ : Bool)
}
#derive(Eq, @debug.Debug)
pub(all) struct MagnetLink {
info_hash : Bytes
display_name : String
trackers : Array[String]
dht_nodes : Array[(String, UInt32)]
}
#derive(Eq, @debug.Debug)
pub(all) enum MetadataMsg {
MetaRequest(Int32)
MetaData(Int32, Int32, Bytes)
MetaReject(Int32)
}
#derive(Eq, @debug.Debug)
pub(all) struct Metainfo {
info_hash : Bytes
name : String
piece_length : Int64
piece_hashes : Array[Bytes]
total_length : Int64
files : Array[TorrentFile]
trackers : Array[String]
raw_info : Bytes
}
#derive(Eq, @debug.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)
}
#derive(Eq, @debug.Debug)
pub(all) struct RemoteExtensions {
mut ut_metadata_id : Byte?
mut i2p_pex_id : Byte?
mut i2p_dht_id : Byte?
mut metadata_size : Int32?
}
#derive(Eq, @debug.Debug)
pub(all) struct TorrentFile {
path : Array[String]
length : Int64
}
#derive(Eq, @debug.Debug)
pub(all) struct TrackerResponse {
interval : Int32
complete : Int32
incomplete : Int32
peers : Array[@common.Hash]
failure_reason : String?
}
#derive(Eq, @debug.Debug)
pub(all) struct TrackerUrl {
host : String
port : UInt32
request_target : String
}
// Type aliases
// Traits
+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, }
}