diff --git a/.gitignore b/.gitignore index dc47257..0589295 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,5 @@ target .moonagent/ __pycache__/ *.pyc +.cache/ +dist/ diff --git a/README.md b/README.md index 0cfb373..c586cda 100644 --- a/README.md +++ b/README.md @@ -58,10 +58,25 @@ moon build --target native cmd/client just proxy # Optional flags: -# --http-proxy [host:port] Enable HTTP-over-I2P proxy (default: 127.0.0.1:4444) -# --hops <1..4> Tunnel length (e.g. --hops 2 for 2-hop Inbound & Outbound tunnels) -# --hosts Load hostname=base64dest (or .b32.i2p) entries from a local I2P hosts.txt -# --debug Log peer dials, tunnel builds, NetDB lookups, and Garlic/Streaming state +# --http-proxy [host:port] Enable HTTP-over-I2P proxy (default: 127.0.0.1:4444) +# --torrent-api [host:port] Enable BitTorrent + I2P DHT HTTP API (default: 127.0.0.1:4445) +# --download-dir Download directory for I2P torrents (default: ~/Downloads/moon-i2p) +# --hops <1..4> Tunnel length (e.g. --hops 2 for 2-hop Inbound & Outbound tunnels) +# --hosts Load hostname=base64dest (or .b32.i2p) entries from a local I2P hosts.txt +# --debug Log peer dials, tunnel builds, NetDB lookups, and Garlic/Streaming state + +# Or launch via just (starts --public --http-proxy 127.0.0.1:4444 --torrent-api 127.0.0.1:4445): +just proxy + +# Build a standalone zero-setup Firefox + moon-i2p router AppImage (insulaocculta.i2p homepage): +just appimage +./dist/MoonI2P-Browser-x86_64.AppImage + +# Firefox WebExtension + I2P DHT Torrent Manager: +# Installs native messaging host (~/.mozilla & ~/.config/mozilla) and packs .xpi: +just extension +# Load `extensions/firefox-i2p-torrent/manifest.json` temporarily in Firefox (`about:debugging`) +# or install `extensions/firefox-i2p-torrent.xpi`. # Once tunnels are up (`tunnels=in:2/out:2`), browse .i2p / .b32.i2p eepsites via the HTTP proxy: # Point your browser's HTTP Proxy to 127.0.0.1:4444 (or test with curl): diff --git a/bittorrent/bencode.mbt b/bittorrent/bencode.mbt new file mode 100644 index 0000000..dcbac56 --- /dev/null +++ b/bittorrent/bencode.mbt @@ -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") +} diff --git a/bittorrent/bittorrent_test.mbt b/bittorrent/bittorrent_test.mbt new file mode 100644 index 0000000..b7ac496 --- /dev/null +++ b/bittorrent/bittorrent_test.mbt @@ -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) +} diff --git a/bittorrent/dht.mbt b/bittorrent/dht.mbt new file mode 100644 index 0000000..c2920d7 --- /dev/null +++ b/bittorrent/dht.mbt @@ -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 +} diff --git a/bittorrent/metainfo.mbt b/bittorrent/metainfo.mbt new file mode 100644 index 0000000..9a472a9 --- /dev/null +++ b/bittorrent/metainfo.mbt @@ -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:") + } + 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() +} diff --git a/bittorrent/moon.pkg b/bittorrent/moon.pkg new file mode 100644 index 0000000..72abb26 --- /dev/null +++ b/bittorrent/moon.pkg @@ -0,0 +1,5 @@ +import { + "experiments/moon_i2p/encoding", + "experiments/moon_i2p/crypto", + "experiments/moon_i2p/common", +} diff --git a/bittorrent/pkg.generated.mbti b/bittorrent/pkg.generated.mbti new file mode 100644 index 0000000..2b2d20f --- /dev/null +++ b/bittorrent/pkg.generated.mbti @@ -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 diff --git a/bittorrent/wire.mbt b/bittorrent/wire.mbt new file mode 100644 index 0000000..b1f2d46 --- /dev/null +++ b/bittorrent/wire.mbt @@ -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=.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, } +} diff --git a/cmd/router/main.mbt b/cmd/router/main.mbt index 4df6b09..4305c98 100644 --- a/cmd/router/main.mbt +++ b/cmd/router/main.mbt @@ -52,6 +52,12 @@ fn print_usage() -> Unit { " --http-proxy [host:port] Enable HTTP-over-I2P proxy (default when omitted: 127.0.0.1:4444)", ) println(" --proxy [host:port] Alias for --http-proxy") + println( + " --torrent-api [host:port] Enable BitTorrent + I2P DHT HTTP API (default: 127.0.0.1:4445)", + ) + println( + " --download-dir Download folder for I2P torrents (default: ~/Downloads/moon-i2p)", + ) println( " --ntcp2-host NTCP2 advertise/bind IP (default: 127.0.0.1)", ) @@ -91,6 +97,10 @@ fn main { let mut http_proxy_enabled = false let mut http_proxy_host = "127.0.0.1" let mut http_proxy_port = 4444 + let mut torrent_api_enabled = false + let mut torrent_api_host = "127.0.0.1" + let mut torrent_api_port = 4445 + let mut download_dir = "" let mut ntcp2_host = "127.0.0.1" let mut ntcp2_port = 0 let mut floodfill = false @@ -146,6 +156,35 @@ fn main { i += 1 } } + "--torrent-api" => { + torrent_api_enabled = true + if i + 1 < args.length() && !args[i + 1].has_prefix("-") { + match split_host_port(args[i + 1]) { + Some((h, p)) => { + torrent_api_host = h + torrent_api_port = p + i += 2 + } + None => + match parse_port(args[i + 1]) { + Some(p) => { + torrent_api_port = p + i += 2 + } + None => i += 1 + } + } + } else { + i += 1 + } + } + "--download-dir" => + if i + 1 < args.length() { + download_dir = args[i + 1] + i += 2 + } else { + i += 1 + } "--ntcp2-port" => if i + 1 < args.length() { match parse_port(args[i + 1]) { @@ -271,6 +310,21 @@ fn main { } } } + if torrent_api_enabled { + let _ = r.start_torrent_api( + host=torrent_api_host, + port=torrent_api_port, + download_dir~, + ) catch { + _ => { + r.close() + println( + "error: failed to bind Torrent API on \{torrent_api_host}:\{torrent_api_port}", + ) + return + } + } + } for pf in peer_files { let _ = r.load_peer_file(pf) catch { _ => { @@ -333,6 +387,11 @@ fn main { if http_proxy_enabled { println(" HTTP Proxy: \{http_proxy_host}:\{r.http_proxy_port()}") } + if torrent_api_enabled { + println( + " Torrent API: \{torrent_api_host}:\{r.torrent_api_port()} (b32=\{r.torrent_b32_address()})", + ) + } println( " NetDB peers: \{r.netdb.router_count()} (floodfills=\{r.netdb.floodfill_count()})", ) diff --git a/crypto/crypto_test.mbt b/crypto/crypto_test.mbt index fab221a..3b02995 100644 --- a/crypto/crypto_test.mbt +++ b/crypto/crypto_test.mbt @@ -286,3 +286,21 @@ test "curve25519 elligator2 encode/decode reference vectors and properties" { } assert_true(encodable_count >= 10) } + +///| +test "sha1 FIPS 180-4 / RFC 3174 test vectors" { + assert_eq( + @encoding.hex_encode(@crypto.sha1(b"")), + "da39a3ee5e6b4b0d3255bfef95601890afd80709", + ) + assert_eq( + @encoding.hex_encode(@crypto.sha1(b"abc")), + "a9993e364706816aba3e25717850c26c9cd0d89d", + ) + assert_eq( + @encoding.hex_encode( + @crypto.sha1(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), + ), + "84983e441c3bd26ebaae4aa1f95129e5e54670f1", + ) +} diff --git a/crypto/pkg.generated.mbti b/crypto/pkg.generated.mbti index c9f2444..7e65253 100644 --- a/crypto/pkg.generated.mbti +++ b/crypto/pkg.generated.mbti @@ -44,6 +44,8 @@ pub fn hmac_sha256(Bytes, Bytes) -> Bytes pub fn poly1305_mac(Bytes, Bytes) -> Bytes raise CryptoError +pub fn sha1(Bytes) -> Bytes + pub fn sha256(Bytes) -> Bytes pub fn sha512(Bytes) -> Bytes @@ -64,6 +66,16 @@ pub suberror CryptoError { } // Types and methods +pub struct Sha1 { + state : FixedArray[UInt32] + block : FixedArray[Byte] + mut block_len : Int32 + mut total_len : UInt64 +} +pub fn Sha1::finalize(Self) -> Bytes +pub fn Sha1::new() -> Self +pub fn Sha1::update(Self, Bytes) -> Unit + pub struct Sha256 { state : FixedArray[UInt32] block : FixedArray[Byte] diff --git a/crypto/sha1.mbt b/crypto/sha1.mbt new file mode 100644 index 0000000..dcc138e --- /dev/null +++ b/crypto/sha1.mbt @@ -0,0 +1,123 @@ +///| +/// Pure-MoonBit FIPS 180-4 / RFC 3174 SHA-1 implementation +/// (used for BitTorrent `info_hash`, piece verification, and BEP 5 Kademlia IDs). + +///| +fn sha1_rotl32(x : UInt32, n : Int32) -> UInt32 { + (x << n) | (x >> (32 - n)) +} + +///| +/// Incremental SHA-1 hasher (FIPS 180-4). +pub struct Sha1 { + state : FixedArray[UInt32] + block : FixedArray[Byte] + mut block_len : Int32 + mut total_len : UInt64 +} + +///| +pub fn Sha1::new() -> Sha1 { + { + state: [0x67452301U, 0xefcdab89U, 0x98badcfeU, 0x10325476U, 0xc3d2e1f0U], + block: FixedArray::make(64, b'\x00'), + block_len: 0, + total_len: 0UL, + } +} + +///| +fn Sha1::compress(self : Sha1) -> Unit { + let w = FixedArray::make(80, 0U) + for i = 0; i < 16; i = i + 1 { + let j = i * 4 + w[i] = (self.block[j].to_uint() << 24) | + (self.block[j + 1].to_uint() << 16) | + (self.block[j + 2].to_uint() << 8) | + self.block[j + 3].to_uint() + } + for i = 16; i < 80; i = i + 1 { + w[i] = sha1_rotl32(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1) + } + let mut a = self.state[0] + let mut b = self.state[1] + let mut c = self.state[2] + let mut d = self.state[3] + let mut e = self.state[4] + for i = 0; i < 80; i = i + 1 { + let (f, k) = if i < 20 { + ((b & c) | (b.lnot() & d), 0x5a827999U) + } else if i < 40 { + (b ^ c ^ d, 0x6ed9eba1U) + } else if i < 60 { + ((b & c) | (b & d) | (c & d), 0x8f1bbcdcU) + } else { + (b ^ c ^ d, 0xca62c1d6U) + } + let temp = sha1_rotl32(a, 5) + f + e + k + w[i] + e = d + d = c + c = sha1_rotl32(b, 30) + b = a + a = temp + } + self.state[0] = self.state[0] + a + self.state[1] = self.state[1] + b + self.state[2] = self.state[2] + c + self.state[3] = self.state[3] + d + self.state[4] = self.state[4] + e +} + +///| +pub fn Sha1::update(self : Sha1, data : Bytes) -> Unit { + let len = data.length() + self.total_len = self.total_len + len.to_uint64() + for i = 0; i < len; i = i + 1 { + self.block[self.block_len] = data[i] + self.block_len += 1 + if self.block_len == 64 { + self.compress() + self.block_len = 0 + } + } +} + +///| +pub fn Sha1::finalize(self : Sha1) -> Bytes { + let bit_len = self.total_len * 8UL + self.block[self.block_len] = b'\x80' + self.block_len += 1 + if self.block_len > 56 { + while self.block_len < 64 { + self.block[self.block_len] = b'\x00' + self.block_len += 1 + } + self.compress() + self.block_len = 0 + } + while self.block_len < 56 { + self.block[self.block_len] = b'\x00' + self.block_len += 1 + } + for i = 0; i < 8; i = i + 1 { + self.block[56 + i] = ((bit_len >> (56 - i * 8)) & 0xFFUL).to_byte() + } + self.compress() + let out = FixedArray::make(20, b'\x00') + for i = 0; i < 5; i = i + 1 { + let v = self.state[i] + out[i * 4] = ((v >> 24) & 0xFFU).to_byte() + out[i * 4 + 1] = ((v >> 16) & 0xFFU).to_byte() + out[i * 4 + 2] = ((v >> 8) & 0xFFU).to_byte() + out[i * 4 + 3] = (v & 0xFFU).to_byte() + } + Bytes::from_array(out) +} + +///| +/// Computes the 20-byte SHA-1 digest of `data`. +pub fn sha1(data : Bytes) -> Bytes { + let h = Sha1::new() + h.update(data) + h.finalize() +} diff --git a/extensions/firefox-i2p-torrent.xpi b/extensions/firefox-i2p-torrent.xpi new file mode 100644 index 0000000..9fb717a Binary files /dev/null and b/extensions/firefox-i2p-torrent.xpi differ diff --git a/extensions/firefox-i2p-torrent/background.js b/extensions/firefox-i2p-torrent/background.js new file mode 100644 index 0000000..cce3ec8 --- /dev/null +++ b/extensions/firefox-i2p-torrent/background.js @@ -0,0 +1,257 @@ +"use strict"; + +const DEFAULT_SETTINGS = { + proxyEnabled: true, + proxyHost: "127.0.0.1", + proxyPort: 4444, + apiHost: "127.0.0.1", + apiPort: 4445, + downloadDir: "", + interceptTorrents: true, +}; + +let cachedSettings = { ...DEFAULT_SETTINGS }; +let syncedAppImageEnv = false; + +async function loadSettings() { + const stored = await browser.storage.local.get(DEFAULT_SETTINGS); + cachedSettings = { ...DEFAULT_SETTINGS, ...stored }; + return cachedSettings; +} + +async function syncFromNativeEnv(force = false) { + const st = await nativeCommand("status"); + if (st && st.appimage && (!syncedAppImageEnv || force)) { + let changed = false; + if (st.env_proxy_host && st.env_proxy_host !== cachedSettings.proxyHost) { + cachedSettings.proxyHost = st.env_proxy_host; + changed = true; + } + if (st.env_proxy_port > 0 && st.env_proxy_port !== Number(cachedSettings.proxyPort)) { + cachedSettings.proxyPort = st.env_proxy_port; + changed = true; + } + if (st.env_api_host && st.env_api_host !== cachedSettings.apiHost) { + cachedSettings.apiHost = st.env_api_host; + changed = true; + } + if (st.env_api_port > 0 && st.env_api_port !== Number(cachedSettings.apiPort)) { + cachedSettings.apiPort = st.env_api_port; + changed = true; + } + if (st.env_download_dir && !cachedSettings.downloadDir) { + cachedSettings.downloadDir = st.env_download_dir; + changed = true; + } + syncedAppImageEnv = true; + if (changed) { + await browser.storage.local.set(cachedSettings); + } + } + return st; +} + +loadSettings().then(() => syncFromNativeEnv()); + +browser.storage.onChanged.addListener((changes, area) => { + if (area !== "local") return; + for (const [key, val] of Object.entries(changes)) { + cachedSettings[key] = val.newValue; + } +}); + +function isLoopbackHost(hostname) { + return ( + hostname === "127.0.0.1" || + hostname === "localhost" || + hostname === "::1" || + hostname === "[::1]" + ); +} + +// Route *.i2p URLs through moon-i2p HTTP proxy; never proxy loopback API calls. +browser.proxy.onRequest.addListener( + (requestInfo) => { + try { + const url = new URL(requestInfo.url); + const host = url.hostname.toLowerCase(); + if (isLoopbackHost(host)) { + return { type: "direct" }; + } + if (cachedSettings.proxyEnabled && host.endsWith(".i2p")) { + return { + type: "http", + host: cachedSettings.proxyHost || "127.0.0.1", + port: Number(cachedSettings.proxyPort) || 4444, + }; + } + } catch (_e) { + // Fall through to direct + } + return { type: "direct" }; + }, + { urls: [""] } +); + +function apiBaseUrl() { + const host = cachedSettings.apiHost || "127.0.0.1"; + const port = Number(cachedSettings.apiPort) || 4445; + return `http://${host}:${port}`; +} + +async function apiJson(path, method = "GET", bodyObj = null) { + const headers = {}; + const opts = { method, headers, cache: "no-store" }; + if (method === "POST") { + headers["X-Moon-I2P"] = "1"; + headers["Content-Type"] = "application/json"; + opts.body = JSON.stringify(bodyObj || {}); + } + const resp = await fetch(`${apiBaseUrl()}${path}`, opts); + const text = await resp.text(); + let data = null; + try { + data = JSON.parse(text); + } catch (_e) { + data = { ok: resp.ok, raw: text }; + } + if (!resp.ok && data && !data.error) { + data.error = `HTTP ${resp.status}`; + } + return data; +} + +function bytesToBase64(bytes) { + let bin = ""; + const chunk = 0x8000; + for (let i = 0; i < bytes.length; i += chunk) { + bin += String.fromCharCode(...bytes.subarray(i, i + chunk)); + } + return btoa(bin); +} + +async function addTorrentBytes(uint8Bytes) { + const b64 = bytesToBase64(uint8Bytes); + return apiJson("/api/torrents/add", "POST", { + torrent_b64: b64, + download_dir: cachedSettings.downloadDir || "", + }); +} + +async function addTorrentFromUrl(urlStr) { + const resp = await fetch(urlStr, { cache: "no-store" }); + if (!resp.ok) { + throw new Error(`Failed to fetch .torrent (${resp.status})`); + } + const buf = await resp.arrayBuffer(); + return addTorrentBytes(new Uint8Array(buf)); +} + +async function nativeCommand(cmd, extra = {}) { + try { + return await browser.runtime.sendNativeMessage("moon_i2p_torrent", { + cmd, + proxy_host: cachedSettings.proxyHost || "127.0.0.1", + proxy_port: Number(cachedSettings.proxyPort) || 4444, + api_host: cachedSettings.apiHost || "127.0.0.1", + api_port: Number(cachedSettings.apiPort) || 4445, + download_dir: cachedSettings.downloadDir || "", + ...extra, + }); + } catch (err) { + return { ok: false, available: false, error: String(err) }; + } +} + +async function gatherFullState() { + await loadSettings(); + const nativeStatus = await syncFromNativeEnv(); + const [routerStatus, torrents, dht] = await Promise.all([ + apiJson("/api/status").catch((e) => ({ ok: false, error: String(e) })), + apiJson("/api/torrents").catch(() => ({ ok: false, torrents: [] })), + apiJson("/api/dht/nodes").catch(() => ({ ok: false, nodes: [] })), + ]); + return { + settings: cachedSettings, + nativeStatus, + routerStatus, + torrents: torrents.torrents || [], + dht, + }; +} + +// Intercept completed/started .torrent downloads from .i2p when enabled. +browser.downloads.onCreated.addListener(async (item) => { + try { + if (!cachedSettings.interceptTorrents || !item.url) return; + const u = new URL(item.url); + if (!u.hostname.toLowerCase().endsWith(".i2p")) return; + if ( + u.pathname.toLowerCase().endsWith(".torrent") || + (item.mime && item.mime.includes("bittorrent")) + ) { + await browser.downloads.cancel(item.id).catch(() => {}); + await browser.downloads.erase({ id: item.id }).catch(() => {}); + await addTorrentFromUrl(item.url); + } + } catch (_e) { + // Ignore cancellation failures on fast transfers + } +}); + +browser.runtime.onMessage.addListener(async (msg) => { + await loadSettings(); + switch (msg?.type) { + case "getState": + return gatherFullState(); + case "saveSettings": { + const next = { ...cachedSettings, ...(msg.settings || {}) }; + await browser.storage.local.set(next); + cachedSettings = next; + return { ok: true, settings: cachedSettings }; + } + case "startRouter": + return nativeCommand("start_router"); + case "stopRouter": + return nativeCommand("stop_router"); + case "addMagnet": + return apiJson("/api/torrents/magnet", "POST", { + uri: msg.uri || "", + download_dir: cachedSettings.downloadDir || "", + }); + case "addTorrentUrl": + try { + return await addTorrentFromUrl(msg.url); + } catch (e) { + return { ok: false, error: String(e) }; + } + case "addTorrentB64": + return apiJson("/api/torrents/add", "POST", { + torrent_b64: msg.torrentB64 || "", + download_dir: cachedSettings.downloadDir || "", + }); + case "pauseTorrent": + return apiJson("/api/torrents/pause", "POST", { info_hash: msg.infoHash }); + case "resumeTorrent": + return apiJson("/api/torrents/resume", "POST", { info_hash: msg.infoHash }); + case "removeTorrent": + return apiJson("/api/torrents/remove", "POST", { info_hash: msg.infoHash }); + case "bootstrapDht": + return apiJson("/api/dht/bootstrap", "POST", { + b32: msg.b32 || "", + port: Number(msg.port) || 6881, + }); + case "openManager": { + const url = browser.runtime.getURL("manager.html"); + const existing = await browser.tabs.query({ url }); + if (existing.length > 0) { + await browser.tabs.update(existing[0].id, { active: true }); + } else { + await browser.tabs.create({ url }); + } + return { ok: true }; + } + default: + return { ok: false, error: "unknown message type" }; + } +}); diff --git a/extensions/firefox-i2p-torrent/content.js b/extensions/firefox-i2p-torrent/content.js new file mode 100644 index 0000000..d1b86bb --- /dev/null +++ b/extensions/firefox-i2p-torrent/content.js @@ -0,0 +1,71 @@ +"use strict"; + +(function () { + function showToast(text, isError) { + let el = document.getElementById("moon-i2p-torrent-toast"); + if (!el) { + el = document.createElement("div"); + el.id = "moon-i2p-torrent-toast"; + el.style.cssText = [ + "position:fixed", + "right:18px", + "bottom:18px", + "z-index:2147483647", + "padding:10px 14px", + "border-radius:10px", + "font-family:system-ui,-apple-system,sans-serif", + "font-size:13px", + "color:#f8fafc", + "box-shadow:0 8px 24px rgba(0,0,0,0.35)", + "border:1px solid rgba(255,255,255,0.16)", + "max-width:360px", + ].join(";"); + document.documentElement.appendChild(el); + } + el.style.background = isError ? "#991b1b" : "#0f172a"; + el.textContent = text; + clearTimeout(el._hideTimer); + el._hideTimer = setTimeout(() => { + if (el.parentNode) el.parentNode.removeChild(el); + }, 4500); + } + + document.addEventListener( + "click", + async (ev) => { + if (ev.button !== 0 || ev.altKey || ev.ctrlKey || ev.metaKey || ev.shiftKey) { + return; + } + const anchor = ev.target && ev.target.closest ? ev.target.closest("a[href]") : null; + if (!anchor) return; + const href = anchor.getAttribute("href") || ""; + let absUrl = ""; + try { + absUrl = new URL(href, window.location.href).href; + } catch (_e) { + return; + } + const isMagnet = absUrl.toLowerCase().startsWith("magnet:"); + const isTorrent = /\.torrent(\?.*)?$/i.test(absUrl); + if (!isMagnet && !isTorrent) return; + + ev.preventDefault(); + ev.stopPropagation(); + try { + const res = await browser.runtime.sendMessage( + isMagnet + ? { type: "addMagnet", uri: absUrl } + : { type: "addTorrentUrl", url: absUrl } + ); + if (res && res.ok) { + showToast(`Added to moon-i2p (${(res.info_hash || "").slice(0, 12)}...)`, false); + } else { + showToast(`moon-i2p error: ${(res && res.error) || "router offline?"}`, true); + } + } catch (err) { + showToast(`moon-i2p error: ${err}`, true); + } + }, + true + ); +})(); diff --git a/extensions/firefox-i2p-torrent/icon.svg b/extensions/firefox-i2p-torrent/icon.svg new file mode 100644 index 0000000..8f1ab55 --- /dev/null +++ b/extensions/firefox-i2p-torrent/icon.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/extensions/firefox-i2p-torrent/manager.html b/extensions/firefox-i2p-torrent/manager.html new file mode 100644 index 0000000..b11cb9c --- /dev/null +++ b/extensions/firefox-i2p-torrent/manager.html @@ -0,0 +1,108 @@ + + + + + Moon I2P Torrent & DHT Manager + + + +
+
+ + moon-i2p BitTorrent & I2P DHT Manager +
+
+ Offline + + +
+
+ +
+
+

I2P Router & HTTP Proxy

+
+
+
NetDB / Tunnels
+
--
+
+
+
I2P Proxy (.i2p)
+ +
+
+
+
Torrent Session .b32.i2p (share with DHT peers)
+
--
+
+
+ +
+

+ I2P Kademlia DHT (Proto 17 / 18) + 0 nodes +

+
+
+
Secure Node ID (20B)
+
--
+
+
+
Sent / Recv / Peers
+
0 / 0 / 0
+
+
+
+ + + +
+
+
+
+ +
+

Add Torrent or Magnet URI

+
+ + +
+
+ Drop a .torrent file here or click to select one from disk + +
+
+
+ +
+

+ Active & Completed Torrents + 0 +

+
No torrents added yet.
+
+ +
+

Extension & Router Settings

+
+
+
HTTP Proxy Port
+
Torrent API Port
+
+
+
Default Download Directory
+ +
+
+ + +
+
+
+ + + + diff --git a/extensions/firefox-i2p-torrent/manifest.json b/extensions/firefox-i2p-torrent/manifest.json new file mode 100644 index 0000000..752da85 --- /dev/null +++ b/extensions/firefox-i2p-torrent/manifest.json @@ -0,0 +1,41 @@ +{ + "manifest_version": 2, + "name": "Moon I2P Torrent & Proxy", + "version": "0.1.0", + "description": "Route .i2p browsing through moon-i2p and manage I2P BitTorrent + I2P DHT torrents from Firefox.", + "icons": { + "48": "icon.svg", + "96": "icon.svg" + }, + "browser_specific_settings": { + "gecko": { + "id": "moon-i2p-torrent@local", + "strict_min_version": "109.0" + } + }, + "permissions": [ + "proxy", + "storage", + "tabs", + "downloads", + "nativeMessaging", + "http://127.0.0.1/*", + "http://localhost/*", + "*://*.i2p/*" + ], + "background": { + "scripts": ["background.js"] + }, + "browser_action": { + "default_icon": "icon.svg", + "default_title": "Moon I2P Torrent & DHT", + "default_popup": "popup.html" + }, + "content_scripts": [ + { + "matches": ["*://*.i2p/*"], + "js": ["content.js"], + "run_at": "document_idle" + } + ] +} diff --git a/extensions/firefox-i2p-torrent/popup.html b/extensions/firefox-i2p-torrent/popup.html new file mode 100644 index 0000000..af147db --- /dev/null +++ b/extensions/firefox-i2p-torrent/popup.html @@ -0,0 +1,112 @@ + + + + + Moon I2P Torrent + + + +
+
+ + moon-i2p Torrent +
+
+ Offline + +
+
+ +
+

+ I2P Router & Proxy + + + + +

+
+
+
NetDB / Tunnels
+
--
+
+
+
I2P Proxy (.i2p)
+
+ +
+
+
+
+
Torrent Session .b32.i2p
+
--
+
+
+ +
+

+ I2P DHT + 0 nodes +

+
+
+
DHT Node ID (20B)
+
--
+
+
+
Sent / Recv / Peers
+
0 / 0 / 0
+
+
+
+ + + +
+
+ +
+

Add I2P Torrent

+
+ + +
+
+ Drop a .torrent file here or click to browse + +
+
+
+ +
+

+ Torrents + 0 +

+
No torrents added yet.
+
+ +
+ Settings (API, Proxy & Download Folder) +
+
+
Proxy Port
+
Torrent API Port
+
+
+
Download Directory
+ +
+
+ + +
+
+
+ + + + diff --git a/extensions/firefox-i2p-torrent/ui.css b/extensions/firefox-i2p-torrent/ui.css new file mode 100644 index 0000000..a5fe3a4 --- /dev/null +++ b/extensions/firefox-i2p-torrent/ui.css @@ -0,0 +1,240 @@ +:root { + color-scheme: dark; + --bg: #0b1120; + --card: #131c31; + --border: #23304d; + --text: #e2e8f0; + --muted: #94a3b8; + --accent: #6d5dfc; + --teal: #14b8a6; + --danger: #ef4444; + --warn: #f59e0b; +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + background: var(--bg); + color: var(--text); + font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; + font-size: 13px; + line-height: 1.45; +} + +body.popup { + width: 450px; + min-height: 540px; + padding: 12px; +} + +body.manager { + max-width: 980px; + margin: 0 auto; + padding: 20px; +} + +header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin-bottom: 12px; +} + +.brand { + display: flex; + align-items: center; + gap: 8px; + font-weight: 700; + font-size: 15px; +} + +.brand img { + width: 24px; + height: 24px; +} + +.pill { + display: inline-block; + padding: 2px 8px; + border-radius: 999px; + font-size: 11px; + font-weight: 600; + background: #1e293b; + color: var(--muted); +} + +.pill.online { + background: rgba(20, 184, 166, 0.18); + color: #5eead4; +} + +.pill.offline { + background: rgba(239, 68, 68, 0.18); + color: #fca5a5; +} + +.card { + background: var(--card); + border: 1px solid var(--border); + border-radius: 10px; + padding: 10px 12px; + margin-bottom: 10px; +} + +.card h2 { + margin: 0 0 8px 0; + font-size: 12px; + text-transform: uppercase; + letter-spacing: 0.05em; + color: var(--muted); + display: flex; + justify-content: space-between; + align-items: center; +} + +.grid-2 { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 8px; +} + +.stat { + background: rgba(15, 23, 42, 0.55); + border: 1px solid rgba(255, 255, 255, 0.06); + border-radius: 7px; + padding: 6px 8px; +} + +.stat-label { + font-size: 11px; + color: var(--muted); +} + +.stat-val { + font-size: 13px; + font-weight: 600; + word-break: break-all; +} + +.mono { + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; + font-size: 11px; +} + +.row { + display: flex; + gap: 6px; + align-items: center; +} + +input[type="text"], +input[type="number"] { + width: 100%; + background: #0b1222; + color: var(--text); + border: 1px solid var(--border); + border-radius: 6px; + padding: 6px 8px; + font-size: 12px; +} + +button { + background: var(--accent); + color: #fff; + border: 0; + border-radius: 6px; + padding: 6px 10px; + font-size: 12px; + font-weight: 600; + cursor: pointer; + white-space: nowrap; +} + +button.secondary { + background: #1e293b; + color: var(--text); + border: 1px solid var(--border); +} + +button.danger { + background: rgba(239, 68, 68, 0.2); + color: #fca5a5; + border: 1px solid rgba(239, 68, 68, 0.35); +} + +button:disabled { + opacity: 0.5; + cursor: default; +} + +.dropzone { + margin-top: 8px; + border: 1px dashed var(--border); + border-radius: 8px; + padding: 8px; + text-align: center; + color: var(--muted); + cursor: pointer; +} + +.dropzone.drag { + border-color: var(--teal); + color: var(--text); +} + +.torrent-item { + padding: 8px 0; + border-top: 1px solid rgba(255, 255, 255, 0.06); +} + +.torrent-item:first-child { + border-top: 0; + padding-top: 0; +} + +.progress-track { + width: 100%; + height: 6px; + background: #0b1222; + border-radius: 999px; + overflow: hidden; + margin: 5px 0; +} + +.progress-fill { + height: 100%; + background: linear-gradient(90deg, var(--accent), var(--teal)); +} + +.msg { + font-size: 12px; + margin-top: 6px; + min-height: 16px; + color: #5eead4; +} + +.msg.err { + color: #fca5a5; +} + +details summary { + cursor: pointer; + color: var(--muted); + font-size: 12px; +} + +.node-list { + max-height: 130px; + overflow-y: auto; + margin-top: 6px; + font-size: 11px; +} + +.node-row { + padding: 3px 0; + border-bottom: 1px solid rgba(255, 255, 255, 0.05); +} diff --git a/extensions/firefox-i2p-torrent/ui.js b/extensions/firefox-i2p-torrent/ui.js new file mode 100644 index 0000000..b7c85bc --- /dev/null +++ b/extensions/firefox-i2p-torrent/ui.js @@ -0,0 +1,241 @@ +"use strict"; + +const $ = (id) => document.getElementById(id); + +function fmtBytes(n) { + if (!n || n <= 0) return "0 B"; + const units = ["B", "KiB", "MiB", "GiB"]; + let u = 0; + let v = n; + while (v >= 1024 && u < units.length - 1) { + v /= 1024; + u++; + } + return `${v.toFixed(u === 0 ? 0 : 1)} ${units[u]}`; +} + +function setMsg(text, isErr = false) { + const el = $("status-msg"); + if (!el) return; + el.textContent = text; + el.className = isErr ? "msg err" : "msg"; +} + +function escapeHtml(s) { + return String(s || "").replace(/[&<>"']/g, (c) => ({ + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'", + })[c]); +} + +function bytesToBase64(bytes) { + let bin = ""; + const chunk = 0x8000; + for (let i = 0; i < bytes.length; i += chunk) { + bin += String.fromCharCode(...bytes.subarray(i, i + chunk)); + } + return btoa(bin); +} + +let settingsPopulated = false; + +async function refresh() { + const st = await browser.runtime.sendMessage({ type: "getState" }); + const cfg = st.settings || {}; + const rs = st.routerStatus || {}; + const ns = st.nativeStatus || {}; + const dht = st.dht || {}; + + $("proxy-enabled").checked = !!cfg.proxyEnabled; + $("proxy-addr").textContent = `${cfg.proxyHost || "127.0.0.1"}:${cfg.proxyPort || 4444}`; + + if (!settingsPopulated) { + settingsPopulated = true; + $("cfg-proxy-port").value = cfg.proxyPort || 4444; + $("cfg-api-port").value = cfg.apiPort || 4445; + $("cfg-dl-dir").value = cfg.downloadDir || ""; + $("cfg-intercept").checked = !!cfg.interceptTorrents; + } + + const pill = $("router-pill"); + const startBtn = $("start-router-btn"); + const stopBtn = $("stop-router-btn"); + if (rs.ok) { + pill.textContent = rs.public_mode ? "Public Online" : "Online"; + pill.className = "pill online"; + startBtn.style.display = "none"; + stopBtn.style.display = ns.managed_running ? "" : "none"; + $("net-summary").textContent = `${rs.netdb_routers || 0} peers · ${rs.inbound_tunnels || 0}in/${rs.outbound_tunnels || 0}out`; + $("torrent-b32").textContent = rs.torrent_b32 || "--"; + const d = rs.dht || {}; + $("dht-summary").textContent = `${d.routing_table_nodes || 0} nodes (UDP-over-I2CP ${d.query_port || 6881}/${d.reply_port || 6882})`; + $("dht-node-id").textContent = d.node_id_hex || "--"; + $("dht-stats").textContent = `${d.queries_sent || 0} / ${d.responses_recv || 0} / ${d.peers_discovered || 0}`; + } else { + pill.textContent = "Offline"; + pill.className = "pill offline"; + startBtn.style.display = ""; + stopBtn.style.display = "none"; + $("net-summary").textContent = "Router unreachable"; + $("torrent-b32").textContent = "--"; + } + + const nodesEl = $("dht-nodes-list"); + if (nodesEl) { + const nodes = dht.nodes || []; + nodesEl.innerHTML = + nodes.length === 0 + ? "No DHT nodes yet. Bootstrap above or connect to a peer." + : nodes + .map( + (n) => + `
${escapeHtml(n.b32)}:${n.port} (${escapeHtml((n.node_id_hex || "").slice(0, 12))}...)
` + ) + .join(""); + } + + const list = st.torrents || []; + $("torrent-count").textContent = String(list.length); + const tEl = $("torrents-list"); + if (list.length === 0) { + tEl.innerHTML = "
No active torrents. Paste a magnet link or drop a .torrent file above.
"; + } else { + tEl.innerHTML = list + .map((t) => { + const pct = Number(t.progress_pct || 0); + const toggleLabel = t.paused ? "Resume" : "Pause"; + const toggleType = t.paused ? "resumeTorrent" : "pauseTorrent"; + return ` +
+
+ ${escapeHtml(t.name)} + ${escapeHtml(t.state)} · ${pct}% +
+
+
+ ${fmtBytes(t.downloaded_bytes)} / ${fmtBytes(t.total_length)} · ${t.have_pieces}/${t.num_pieces} pcs · ${t.connected_peers}/${t.known_peers} peers + + + + +
+ ${t.error ? `
${escapeHtml(t.error)}
` : ""} +
+ `; + }) + .join(""); + } +} + +document.addEventListener("DOMContentLoaded", () => { + if ($("open-manager-btn")) { + $("open-manager-btn").addEventListener("click", () => + browser.runtime.sendMessage({ type: "openManager" }) + ); + } + + $("proxy-enabled").addEventListener("change", async (e) => { + await browser.runtime.sendMessage({ + type: "saveSettings", + settings: { proxyEnabled: e.target.checked }, + }); + refresh(); + }); + + $("start-router-btn").addEventListener("click", async () => { + setMsg("Starting moon-i2p router via native host..."); + const res = await browser.runtime.sendMessage({ type: "startRouter" }); + if (res && res.ok) { + setMsg("Router starting (waiting for API & tunnels)..."); + } else { + setMsg(`Failed to start router: ${(res && res.error) || "run just extension"}`, true); + } + setTimeout(refresh, 700); + }); + + $("stop-router-btn").addEventListener("click", async () => { + await browser.runtime.sendMessage({ type: "stopRouter" }); + setMsg("Stopped router."); + setTimeout(refresh, 400); + }); + + $("bootstrap-form").addEventListener("submit", async (e) => { + e.preventDefault(); + const b32 = $("bootstrap-b32").value.trim(); + const port = Number($("bootstrap-port").value) || 6881; + if (!b32) return; + const res = await browser.runtime.sendMessage({ type: "bootstrapDht", b32, port }); + setMsg(res && res.ok ? `Sent DHT ping to ${res.b32}:${res.port}` : `DHT error: ${res?.error || "failed"}`, !res?.ok); + refresh(); + }); + + $("magnet-form").addEventListener("submit", async (e) => { + e.preventDefault(); + const uri = $("magnet-uri").value.trim(); + if (!uri) return; + const res = await browser.runtime.sendMessage({ type: "addMagnet", uri }); + if (res && res.ok) { + $("magnet-uri").value = ""; + setMsg(`Added magnet ${res.info_hash.slice(0, 12)}...`); + } else { + setMsg(`Magnet failed: ${res?.error || "router offline"}`, true); + } + refresh(); + }); + + const dz = $("dropzone"); + const fileIn = $("torrent-file"); + const handleFile = async (file) => { + if (!file) return; + const buf = new Uint8Array(await file.arrayBuffer()); + const res = await browser.runtime.sendMessage({ + type: "addTorrentB64", + torrentB64: bytesToBase64(buf), + }); + setMsg(res && res.ok ? `Added ${file.name} (${res.info_hash.slice(0, 12)}...)` : `Add failed: ${res?.error}`, !res?.ok); + refresh(); + }; + dz.addEventListener("click", () => fileIn.click()); + fileIn.addEventListener("change", () => handleFile(fileIn.files[0])); + dz.addEventListener("dragover", (e) => { + e.preventDefault(); + dz.classList.add("drag"); + }); + dz.addEventListener("dragleave", () => dz.classList.remove("drag")); + dz.addEventListener("drop", (e) => { + e.preventDefault(); + dz.classList.remove("drag"); + handleFile(e.dataTransfer.files[0]); + }); + + $("torrents-list").addEventListener("click", async (e) => { + const btn = e.target.closest(".act-btn"); + if (!btn) return; + await browser.runtime.sendMessage({ + type: btn.dataset.act, + infoHash: btn.dataset.ih, + }); + refresh(); + }); + + $("settings-form").addEventListener("submit", async (e) => { + e.preventDefault(); + await browser.runtime.sendMessage({ + type: "saveSettings", + settings: { + proxyPort: Number($("cfg-proxy-port").value) || 4444, + apiPort: Number($("cfg-api-port").value) || 4445, + downloadDir: $("cfg-dl-dir").value.trim(), + interceptTorrents: $("cfg-intercept").checked, + }, + }); + setMsg("Settings saved."); + refresh(); + }); + + refresh(); + setInterval(refresh, 2000); +}); diff --git a/justfile b/justfile index 13a3e07..72d5d2e 100644 --- a/justfile +++ b/justfile @@ -11,10 +11,18 @@ build: moon build --target native cmd/router moon build --target native cmd/client -# Start public I2P router with embedded HTTP proxy on 127.0.0.1:4444 +# Start public I2P router with embedded HTTP proxy and BitTorrent + DHT API proxy: moon build --target native cmd/router - ./_build/native/debug/build/cmd/router/router.exe --public --http-proxy 127.0.0.1:4444 + ./_build/native/debug/build/cmd/router/router.exe --public --http-proxy 127.0.0.1:4444 --torrent-api 127.0.0.1:4445 + +# Install Firefox Native Messaging host and build extensions/firefox-i2p-torrent.xpi +extension: + python3 scripts/install_firefox_native_host.py + +# Build self-contained Linux x86_64 Firefox + moon-i2p router AppImage +appimage: + python3 scripts/build_appimage.py # Run all MoonBit tests across wasm, js, and native targets test: diff --git a/ntcp2_net/net_stub.c b/ntcp2_net/net_stub.c index c722af9..2e67328 100644 --- a/ntcp2_net/net_stub.c +++ b/ntcp2_net/net_stub.c @@ -613,3 +613,112 @@ int32_t moon_i2p_net_fetch_https( } return total; } + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_mkdir_p(moonbit_bytes_t path_bytes, int32_t path_len) { + if (path_len <= 0 || path_len >= 1024) { + net_set_error("invalid directory path length"); + return -1; + } + char path[1024]; + memcpy(path, path_bytes, (size_t)path_len); + path[path_len] = '\0'; + for (int32_t i = 1; i < path_len; i++) { + if (path[i] == '/') { + path[i] = '\0'; + if (mkdir(path, 0755) < 0 && errno != EEXIST) { + net_set_error(strerror(errno)); + return -1; + } + path[i] = '/'; + } + } + if (mkdir(path, 0755) < 0 && errno != EEXIST) { + net_set_error(strerror(errno)); + return -1; + } + return 0; +} + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_write_file_at( + moonbit_bytes_t path_bytes, + int32_t path_len, + int64_t offset, + moonbit_bytes_t data, + int32_t data_len) { + if (path_len <= 0 || path_len >= 1024 || offset < 0 || data_len < 0) { + net_set_error("invalid write_file_at arguments"); + return -1; + } + char path[1024]; + memcpy(path, path_bytes, (size_t)path_len); + path[path_len] = '\0'; + int fd = open(path, O_CREAT | O_WRONLY, 0644); + if (fd < 0) { + net_set_error(strerror(errno)); + return -1; + } + int32_t wrote = 0; + while (wrote < data_len) { + ssize_t n = pwrite(fd, data + wrote, (size_t)(data_len - wrote), (off_t)(offset + wrote)); + if (n < 0) { + if (errno == EINTR) continue; + net_set_error(strerror(errno)); + close(fd); + return -1; + } + wrote += (int32_t)n; + } + close(fd); + return 0; +} + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_read_file_at( + moonbit_bytes_t path_bytes, + int32_t path_len, + int64_t offset, + moonbit_bytes_t dst, + int32_t max_len) { + if (path_len <= 0 || path_len >= 1024 || offset < 0 || max_len < 0) { + net_set_error("invalid read_file_at arguments"); + return -1; + } + char path[1024]; + memcpy(path, path_bytes, (size_t)path_len); + path[path_len] = '\0'; + int fd = open(path, O_RDONLY); + if (fd < 0) { + net_set_error(strerror(errno)); + return -1; + } + int32_t total = 0; + while (total < max_len) { + ssize_t n = pread(fd, dst + total, (size_t)(max_len - total), (off_t)(offset + total)); + if (n < 0) { + if (errno == EINTR) continue; + net_set_error(strerror(errno)); + close(fd); + return -1; + } + if (n == 0) break; + total += (int32_t)n; + } + close(fd); + return total; +} + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_home_dir(moonbit_bytes_t dst, int32_t max_len) { + const char *home = getenv("HOME"); + if (home == NULL || max_len <= 0) { + return 0; + } + int32_t len = (int32_t)strlen(home); + if (len > max_len) { + len = max_len; + } + memcpy(dst, home, (size_t)len); + return len; +} diff --git a/ntcp2_net/transport.mbt b/ntcp2_net/transport.mbt index b85cd00..543b428 100644 --- a/ntcp2_net/transport.mbt +++ b/ntcp2_net/transport.mbt @@ -140,6 +140,34 @@ extern "C" fn c_fetch_https( max_len : Int32, ) -> Int32 = "moon_i2p_net_fetch_https" +///| +#borrow(path) +extern "C" fn c_mkdir_p(path : Bytes, path_len : Int32) -> Int32 = "moon_i2p_net_mkdir_p" + +///| +#borrow(path, data) +extern "C" fn c_write_file_at( + path : Bytes, + path_len : Int32, + offset : Int64, + data : Bytes, + data_len : Int32, +) -> Int32 = "moon_i2p_net_write_file_at" + +///| +#borrow(path, dst) +extern "C" fn c_read_file_at( + path : Bytes, + path_len : Int32, + offset : Int64, + dst : FixedArray[Byte], + max_len : Int32, +) -> Int32 = "moon_i2p_net_read_file_at" + +///| +#borrow(dst) +extern "C" fn c_home_dir(dst : FixedArray[Byte], max_len : Int32) -> Int32 = "moon_i2p_net_home_dir" + ///| fn last_os_error() -> String { let n = c_last_error_len() @@ -245,6 +273,60 @@ pub fn read_file_bytes(path : String) -> Bytes raise Ntcp2NetError { Bytes::from_array(buf)[:got].to_owned() } +///| +/// Creates directory `path` and any missing parent directories (`mkdir -p`). +pub fn mkdir_p(path : String) -> Unit raise Ntcp2NetError { + let pb = @encoding.string_to_utf8_bytes(path) + if c_mkdir_p(pb, pb.length()) < 0 { + raise IoError("mkdir_p(\{path}) failed: \{last_os_error()}") + } +} + +///| +/// Writes `data` at byte `offset` into `path` (creating the file if missing). +pub fn write_file_at( + path : String, + offset : Int64, + data : Bytes, +) -> Unit raise Ntcp2NetError { + let pb = @encoding.string_to_utf8_bytes(path) + if c_write_file_at(pb, pb.length(), offset, data, data.length()) < 0 { + raise IoError("write_file_at(\{path}) failed: \{last_os_error()}") + } +} + +///| +/// Reads up to `len` bytes starting at byte `offset` from `path`. +pub fn read_file_at( + path : String, + offset : Int64, + len : Int32, +) -> Bytes raise Ntcp2NetError { + if len <= 0 { + return b"" + } + let pb = @encoding.string_to_utf8_bytes(path) + let buf = FixedArray::make(len, b'\x00') + let got = c_read_file_at(pb, pb.length(), offset, buf, len) + if got < 0 { + raise IoError("read_file_at(\{path}) failed: \{last_os_error()}") + } + Bytes::from_array(buf)[:got].to_owned() +} + +///| +/// Returns the `HOME` directory path, or empty string if unset. +pub fn get_home_dir() -> String { + let buf = FixedArray::make(1024, b'\x00') + let n = c_home_dir(buf, 1024) + if n <= 0 { + return "" + } + @encoding.utf8_bytes_to_string(Bytes::from_array(buf)[:n].to_owned()) catch { + _ => "" + } +} + ///| /// Native POSIX TCP socket wrapper with exact-length reads and line reading. pub struct TcpSocket { diff --git a/router/http_proxy.mbt b/router/http_proxy.mbt index e2ff23d..1f96e6c 100644 --- a/router/http_proxy.mbt +++ b/router/http_proxy.mbt @@ -446,12 +446,23 @@ fn send_http_proxy_error( status : Int32, reason : String, detail : String, + refresh_sec~ : Int32 = 0, ) -> Unit { let safe_reason = escape_html(reason) let safe_detail = escape_html(detail) - let body = "\{status} \{safe_reason}

\{status} \{safe_reason}

\{safe_detail}


moon-i2p HTTP Proxy\n" + let refresh_meta = if refresh_sec > 0 { + "" + } else { + "" + } + let refresh_hdr = if refresh_sec > 0 { + "Retry-After: \{refresh_sec}\r\n" + } else { + "" + } + let body = "\{refresh_meta}\{status} \{safe_reason}

\{status} \{safe_reason}

\{safe_detail}


moon-i2p HTTP Proxy\n" let body_bytes = @encoding.string_to_utf8_bytes(body) - let hdr = "HTTP/1.1 \{status} \{reason}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: \{body_bytes.length()}\r\nConnection: close\r\n\r\n" + let hdr = "HTTP/1.1 \{status} \{reason}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: \{body_bytes.length()}\r\n\{refresh_hdr}Connection: close\r\n\r\n" let _ = sock.write_all(@encoding.string_to_utf8_bytes(hdr)) catch { _ => return } @@ -788,7 +799,8 @@ fn Router::step_http_proxy(self : Router) -> Bool { pc.sock, 503, "Service Unavailable", - "I2P router is still bootstrapping tunnels (inbound=\{self.inbound_tunnel_count()}, outbound=\{self.outbound_tunnel_count()}, peers=\{self.peer_count()}). Retry shortly.", + "I2P router is still bootstrapping tunnels (inbound=\{self.inbound_tunnel_count()}, outbound=\{self.outbound_tunnel_count()}, peers=\{self.peer_count()}). Retrying automatically...", + refresh_sec=3, ) pc.sock.close() pc.closed = true diff --git a/router/moon.pkg b/router/moon.pkg index 8dd1b0d..da74465 100644 --- a/router/moon.pkg +++ b/router/moon.pkg @@ -11,6 +11,7 @@ import { "experiments/moon_i2p/ratchet", "experiments/moon_i2p/streaming", "experiments/moon_i2p/sam", + "experiments/moon_i2p/bittorrent", } supported_targets = "-all+native" diff --git a/router/router.mbt b/router/router.mbt index e17bfc3..21024b4 100644 --- a/router/router.mbt +++ b/router/router.mbt @@ -71,6 +71,9 @@ pub struct Router { priv mut http_proxy_listener : @ntcp2_net.TcpListener? priv http_proxy_conns : Array[HttpProxyConn] priv mut http_proxy_session_id : String? + priv mut torrent_engine : TorrentEngine? + priv mut torrent_api_listener : @ntcp2_net.TcpListener? + priv torrent_api_conns : Array[TorrentApiConn] priv mut lease_rr : Int32 priv mut outbound_rr : Int32 priv mut last_bootstrap_ms : UInt64 @@ -263,6 +266,9 @@ pub fn Router::start( http_proxy_listener: None, http_proxy_conns: [], http_proxy_session_id: None, + torrent_engine: None, + torrent_api_listener: None, + torrent_api_conns: [], lease_rr: 0, outbound_rr: 0, last_bootstrap_ms: 0UL, @@ -432,6 +438,19 @@ pub fn Router::reseed_from_url( ///| pub fn Router::close(self : Router) -> Unit { + for ac in self.torrent_api_conns { + if !ac.closed { + ac.sock.close() + ac.closed = true + } + } + match self.torrent_api_listener { + Some(l) => { + l.close() + self.torrent_api_listener = None + } + None => () + } for pc in self.http_proxy_conns { if !pc.closed { pc.sock.close() @@ -564,6 +583,12 @@ pub fn Router::step(self : Router, poll_ms~ : Int32 = 10) -> Unit { if self.step_http_proxy() { did_work = true } + if self.step_torrent_engine() { + did_work = true + } + if self.step_torrent_api() { + did_work = true + } self.poll_netdb_lookups() self.poll_tunnel_builds() if self.public_mode { diff --git a/router/router_test.mbt b/router/router_test.mbt index f844756..3dc1263 100644 --- a/router/router_test.mbt +++ b/router/router_test.mbt @@ -504,3 +504,220 @@ test "Proposal 157 Outbound tunnel replying via Inbound tunnel with OBEP ECIES G } assert_true(built_out) } + +///| +fn test_http_api_request( + port : Int32, + rs : Array[@router.Router], + http_method : String, + path : String, + host_hdr : String, + headers : Array[(String, String)], + body : String, +) -> String raise { + let sock = @ntcp2_net.TcpSocket::connect("127.0.0.1", port) + defer sock.close() + let body_bytes = @encoding.string_to_utf8_bytes(body) + let sb = StringBuilder() + sb.write_string("\{http_method} \{path} HTTP/1.1\r\n") + sb.write_string("Host: \{host_hdr}\r\n") + for h in headers { + sb.write_string("\{h.0}: \{h.1}\r\n") + } + if body_bytes.length() > 0 { + sb.write_string("Content-Length: \{body_bytes.length()}\r\n") + } + sb.write_string("Connection: close\r\n\r\n") + if body.length() > 0 { + sb.write_string(body) + } + sock.write_all(@encoding.string_to_utf8_bytes(sb.to_string())) + let resp_bytes = pump_read_until_eof(sock, rs, max_ticks=1500) + @encoding.utf8_bytes_to_string(resp_bytes) +} + +///| +test "2-router I2P DHT + BEP 9 Magnet + Streaming torrent download and HTTP API security" { + let seed_dir = "/tmp/moon_i2p_bt_seed" + let dl_dir = "/tmp/moon_i2p_bt_dl" + @ntcp2_net.mkdir_p(seed_dir) + @ntcp2_net.mkdir_p(dl_dir) + + // Deterministic 40 KiB payload spanning 3 x 16 KiB pieces (16384 + 16384 + 8192) + let total_len = 40960 + let raw_arr = FixedArray::make(total_len, b'\x00') + for i = 0; i < total_len; i = i + 1 { + raw_arr[i] = ((i * 17 + 5) % 251).to_byte() + } + let payload = Bytes::from_array(raw_arr) + @ntcp2_net.write_file_at(seed_dir + "/sample.bin", 0L, payload) + // Poison any prior download artifact so stale pieces cannot pass SHA-1 + @ntcp2_net.write_file_at( + dl_dir + "/sample.bin", + 0L, + Bytes::make(total_len, b'\xFF'), + ) + + let piece_hashes = @encoding.Writer::new(capacity=60) + piece_hashes.write_bytes(@crypto.sha1(payload[:16384].to_owned())) + piece_hashes.write_bytes(@crypto.sha1(payload[16384:32768].to_owned())) + piece_hashes.write_bytes(@crypto.sha1(payload[32768:].to_owned())) + let torrent_bytes = @bittorrent.bencode_encode( + BDict([ + ( + b"info", + BDict([ + (b"length", BInt(total_len.to_int64())), + (b"name", BBytes(b"sample.bin")), + (b"piece length", BInt(16384L)), + (b"pieces", BBytes(piece_hashes.to_bytes())), + ]), + ), + ]), + ) + let meta = @bittorrent.parse_torrent(torrent_bytes) + let ih_hex = @encoding.hex_encode(meta.info_hash) + + let router_a = @router.Router::start({ + sam_host: "127.0.0.1", + sam_port: 0, + ntcp2_host: "127.0.0.1", + ntcp2_port: 0, + }) + defer router_a.close() + let router_b = @router.Router::start({ + sam_host: "127.0.0.1", + sam_port: 0, + ntcp2_host: "127.0.0.1", + ntcp2_port: 0, + }) + defer router_b.close() + + let _ = router_a.netdb.store_router_info(router_b.router_info) + let _ = router_b.netdb.store_router_info(router_a.router_info) + + router_a.enable_torrent_engine(download_dir=seed_dir) + let seeded_ih = router_a.add_seed_torrent(torrent_bytes, seed_dir) + assert_eq(seeded_ih, ih_hex) + + let a_hash = match router_a.torrent_session_hash() { + Some(h) => h + None => fail("router_a missing __torrent__ session hash") + } + let now_sec = @ntcp2_net.unix_time_sec() + let ls2_a = match router_a.netdb.get_lease_set2(a_hash, now_sec) { + Some(l) => l + None => fail("router_a missing __torrent__ LeaseSet2") + } + let _ = router_b.netdb.store_lease_set2(ls2_a, now_sec) + + let api_port = router_b.start_torrent_api( + host="127.0.0.1", + port=0, + download_dir=dl_dir, + ) + assert_true(api_port > 0) + let rs = [router_a, router_b] + + // Security check 1: POST without X-Moon-I2P: 1 is rejected with 403 + let unauth_resp = test_http_api_request( + api_port, + rs, + "POST", + "/api/torrents/magnet", + "127.0.0.1:\{api_port}", + [("Content-Type", "application/json")], + "{\"uri\":\"magnet:?xt=urn:btih:\{ih_hex}\"}", + ) + assert_true(unauth_resp.contains("403 Forbidden")) + + // Security check 2: non-loopback Host header (DNS rebinding guard) is rejected with 403 + let evil_host_resp = test_http_api_request( + api_port, + rs, + "GET", + "/api/status", + "evil.example", + [], + "", + ) + assert_true(evil_host_resp.contains("403 Forbidden")) + + // Bootstrap Router B's I2P DHT onto Router A and add pure magnet URI (no trackers/peers) + let boot_resp = test_http_api_request( + api_port, + rs, + "POST", + "/api/dht/bootstrap", + "127.0.0.1:\{api_port}", + [("Content-Type", "application/json"), ("X-Moon-I2P", "1")], + "{\"b32\":\"\{router_a.torrent_b32_address()}\",\"port\":6881}", + ) + assert_true(boot_resp.contains("200 OK")) + assert_true(boot_resp.contains("\"ok\":true")) + + let mag_resp = test_http_api_request( + api_port, + rs, + "POST", + "/api/torrents/magnet", + "127.0.0.1:\{api_port}", + [("Content-Type", "application/json"), ("X-Moon-I2P", "1")], + "{\"uri\":\"magnet:?xt=urn:btih:\{ih_hex}&dn=sample.bin\"}", + ) + assert_true(mag_resp.contains("200 OK")) + assert_true(mag_resp.contains(ih_hex)) + + // Step both routers until DHT discovery -> BEP 9 metadata -> full 3-piece download finishes + let mut completed = false + for iter = 0; iter < 60; iter = iter + 1 { + step_routers(rs, 25) + if iter % 4 == 0 { + let tlist = test_http_api_request( + api_port, + rs, + "GET", + "/api/torrents", + "127.0.0.1:\{api_port}", + [], + "", + ) + if tlist.contains("\"completed\":true") { + completed = true + break + } + } + } + assert_true(completed) + + // Verify downloaded file matches original bytes bit-for-bit + let downloaded = @ntcp2_net.read_file_bytes(dl_dir + "/sample.bin") + assert_eq(downloaded, payload) + + // Verify DHT routing table & stats recorded live exchanges + let status_json = test_http_api_request( + api_port, + rs, + "GET", + "/api/status", + "127.0.0.1:\{api_port}", + [], + "", + ) + assert_true(status_json.contains("\"completed_torrents\":1")) + assert_true(!status_json.contains("\"queries_sent\":0")) + assert_true(!status_json.contains("\"responses_recv\":0")) + assert_true(!status_json.contains("\"routing_table_nodes\":0")) + assert_true(!status_json.contains("\"peers_discovered\":0")) + + let nodes_json = test_http_api_request( + api_port, + rs, + "GET", + "/api/dht/nodes", + "127.0.0.1:\{api_port}", + [], + "", + ) + assert_true(nodes_json.contains(router_a.torrent_b32_address())) +} diff --git a/router/torrent_api.mbt b/router/torrent_api.mbt new file mode 100644 index 0000000..b6997e1 --- /dev/null +++ b/router/torrent_api.mbt @@ -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 +} diff --git a/router/torrent_engine.mbt b/router/torrent_engine.mbt new file mode 100644 index 0000000..bbb4386 --- /dev/null +++ b/router/torrent_engine.mbt @@ -0,0 +1,2590 @@ +///| +/// Pure MoonBit Router-integrated I2P BitTorrent + I2P DHT Engine. +/// +/// Transport stack: +/// - Peer & Tracker TCP-like streams: I2P Streaming (`from_port=0U`, `to_port=0U` / tracker port) +/// over Proposal 144 ECIES-X25519-AEAD-Ratchet Garlic using internal `"__torrent__"` session. +/// - I2P DHT KRPC (`ping`, `find_node`, `get_peers`, `announce_peer`): +/// - Queries: I2CP protocol `17` (0x11) Ed25519 RepliableDatagram with `LeaseSet2` piggybacked +/// - Replies: I2CP protocol `18` (0x12) RawDatagram to requester's `rport` (`query_port + 1`) + +///| +priv struct TorrentTrackerConn { + url : String + host : String + port : UInt32 + path : String + mut state : Int32 // 0=idle/backoff, 1=lookup_ls2, 2=streaming, 3=error_backoff + mut started_ms : UInt64 + mut next_announce_ms : UInt64 + mut stream_id : UInt32 + mut peer_hash : @common.Hash? + mut sent_req : Bool + recv_buf : Array[Byte] +} + +///| +priv struct TorrentPeerConn { + peer_hash : @common.Hash + mut state : Int32 // 0=lookup_ls2, 1=streaming_connect, 2=await_bt_hs, 3=active, 4=closed + mut started_ms : UInt64 + mut last_activity_ms : UInt64 + mut stream_id : UInt32 + mut peer_static : Bytes + mut lease_gw : @common.Hash? + mut lease_tid : UInt32 + recv_buf : Array[Byte] + send_buf : Array[Byte] + mut sent_bt_hs : Bool + mut sent_ext_hs : Bool + mut peer_choking : Bool + mut am_choking : Bool + mut am_interested : Bool + mut remote_ext : @bittorrent.RemoteExtensions? + mut peer_bitfield : Array[Bool] + in_flight : Array[(Int32, Int32, Int32, UInt64)] // (piece_idx, begin, len, req_ms) + mut dht_pinged : Bool +} + +///| +priv struct TorrentInboundConn { + stream_id : UInt32 + peer_hash : @common.Hash + peer_static : Bytes + lease_gw : @common.Hash + lease_tid : UInt32 + started_ms : UInt64 + recv_buf : Array[Byte] +} + +///| +priv struct ActivePieceBuf { + piece_idx : Int32 + data : FixedArray[Byte] + got_blocks : Array[Bool] + num_blocks : Int32 +} + +///| +priv struct ActiveTorrent { + info_hash : Bytes + info_hash_hex : String + mut name : String + download_dir : String + mut metainfo : @bittorrent.Metainfo? + mut raw_info : Bytes + mut paused : Bool + mut completed : Bool + mut error : String + mut downloaded_bytes : UInt64 + mut uploaded_bytes : UInt64 + mut have_pieces : Array[Bool] + inflight_pieces : Array[ActivePieceBuf] + mut meta_size : Int32 + meta_pieces : Array[(Int32, Bytes)] + mut meta_req_ms : UInt64 + known_peers : Array[@common.Hash] + peers : Array[TorrentPeerConn] + trackers : Array[TorrentTrackerConn] + mut last_dht_lookup_ms : UInt64 + mut last_pex_ms : UInt64 +} + +///| +priv struct TorrentEngine { + session_id : String + peer_id : Bytes + mut download_dir : String + dht : @bittorrent.I2pDht + torrents : Array[ActiveTorrent] + pending_inbound : Array[TorrentInboundConn] + pending_dht_pings : Array[(@common.Hash, UInt32, UInt64)] + mut last_dht_maint_ms : UInt64 + mut last_ls2_pub_ms : UInt64 + mut last_ls2_pub_tunnels : Int32 +} + +///| +fn bt_default_download_dir() -> String { + let home = @ntcp2_net.get_home_dir() + if home.length() > 0 { + home + "/Downloads/moon-i2p" + } else { + "./downloads" + } +} + +///| +fn bt_normalize_dir(dir : String) -> String { + if dir.length() > 1 && dir.has_suffix("/") { + dir[:dir.length() - 1].to_owned() + } else { + dir + } +} + +///| +fn bt_join_rel_path(base_dir : String, segs : Array[String]) -> String { + let out = StringBuilder() + out.write_string(bt_normalize_dir(base_dir)) + for seg in segs { + out.write_char('/') + out.write_string(seg) + } + out.to_string() +} + +///| +fn bt_parent_dir(base_dir : String, segs : Array[String]) -> String { + if segs.length() <= 1 { + return bt_normalize_dir(base_dir) + } + let out = StringBuilder() + out.write_string(bt_normalize_dir(base_dir)) + for i = 0; i < segs.length() - 1; i = i + 1 { + out.write_char('/') + out.write_string(segs[i]) + } + out.to_string() +} + +///| +fn bt_hex_lower(s : String) -> String { + s.trim().to_owned().to_lower() +} + +///| +fn bt_err_msg(e : @bittorrent.BtError) -> String { + match e { + InvalidBencode(m) => "invalid bencode: \{m}" + InvalidMetainfo(m) => "invalid metainfo: \{m}" + InvalidMagnet(m) => "invalid magnet: \{m}" + InvalidWire(m) => "wire error: \{m}" + InvalidKrpc(m) => "KRPC error: \{m}" + Encoding(_) => "encoding error" + Common(_) => "I2P structure error" + } +} + +///| +fn bt_piece_length(meta : @bittorrent.Metainfo, piece_idx : Int32) -> Int32 { + let num = meta.piece_hashes.length() + if piece_idx < 0 || piece_idx >= num { + return 0 + } + let start = piece_idx.to_int64() * meta.piece_length + let rem = meta.total_length - start + if rem <= 0L { + 0 + } else if rem < meta.piece_length { + rem.to_int() + } else { + meta.piece_length.to_int() + } +} + +///| +fn bt_write_piece_to_files( + t : ActiveTorrent, + piece_idx : Int32, + piece_bytes : Bytes, +) -> Bool { + let meta = match t.metainfo { + Some(m) => m + None => return false + } + let global_start = piece_idx.to_int64() * meta.piece_length + let mut cursor = 0 + let mut file_start = 0L + for f in meta.files { + let file_end = file_start + f.length + let piece_end = global_start + piece_bytes.length().to_int64() + if piece_end > file_start && global_start < file_end { + let overlap_start = if global_start > file_start { + global_start + } else { + file_start + } + let overlap_end = if piece_end < file_end { piece_end } else { file_end } + let chunk_len = (overlap_end - overlap_start).to_int() + let slice_off = (overlap_start - global_start).to_int() + let file_off = overlap_start - file_start + let pdir = bt_parent_dir(t.download_dir, f.path) + let _ = @ntcp2_net.mkdir_p(pdir) catch { _ => return false } + let full_path = bt_join_rel_path(t.download_dir, f.path) + let chunk = piece_bytes[slice_off:slice_off + chunk_len].to_owned() + let _ = @ntcp2_net.write_file_at(full_path, file_off, chunk) catch { + _ => return false + } + cursor += chunk_len + } + file_start = file_end + } + cursor == piece_bytes.length() +} + +///| +fn bt_read_span_from_files( + t : ActiveTorrent, + piece_idx : Int32, + begin : Int32, + length : Int32, +) -> Bytes? { + let meta = match t.metainfo { + Some(m) => m + None => return None + } + if length <= 0 || begin < 0 { + return None + } + let plen = bt_piece_length(meta, piece_idx) + if begin + length > plen { + return None + } + let global_start = piece_idx.to_int64() * meta.piece_length + begin.to_int64() + let global_end = global_start + length.to_int64() + let w = @encoding.Writer::new(capacity=length) + let mut file_start = 0L + for f in meta.files { + let file_end = file_start + f.length + if global_end > file_start && global_start < file_end { + let overlap_start = if global_start > file_start { + global_start + } else { + file_start + } + let overlap_end = if global_end < file_end { + global_end + } else { + file_end + } + let chunk_len = (overlap_end - overlap_start).to_int() + let file_off = overlap_start - file_start + let full_path = bt_join_rel_path(t.download_dir, f.path) + let got = @ntcp2_net.read_file_at(full_path, file_off, chunk_len) catch { + _ => return None + } + if got.length() != chunk_len { + return None + } + w.write_bytes(got) + } + file_start = file_end + } + let res = w.to_bytes() + if res.length() == length { + Some(res) + } else { + None + } +} + +///| +fn bt_verify_existing_pieces(t : ActiveTorrent) -> Unit { + let meta = match t.metainfo { + Some(m) => m + None => return + } + let num = meta.piece_hashes.length() + if t.have_pieces.length() != num { + t.have_pieces = Array::make(num, false) + } + let mut done_bytes = 0UL + let mut all_have = num > 0 + for i = 0; i < num; i = i + 1 { + let plen = bt_piece_length(meta, i) + match bt_read_span_from_files(t, i, 0, plen) { + Some(pbytes) => + if @crypto.ct_eq(@crypto.sha1(pbytes), meta.piece_hashes[i]) { + t.have_pieces[i] = true + done_bytes += plen.to_uint64() + } else { + t.have_pieces[i] = false + all_have = false + } + None => { + t.have_pieces[i] = false + all_have = false + } + } + } + t.downloaded_bytes = done_bytes + t.completed = all_have +} + +///| +fn bt_init_torrent_metainfo( + t : ActiveTorrent, + meta : @bittorrent.Metainfo, +) -> Unit { + t.name = meta.name + t.raw_info = meta.raw_info + t.meta_size = meta.raw_info.length() + t.metainfo = Some(meta) + t.have_pieces = Array::make(meta.piece_hashes.length(), false) + for tr in meta.trackers { + bt_add_tracker_url(t, tr) + } + bt_verify_existing_pieces(t) +} + +///| +fn bt_add_tracker_url(t : ActiveTorrent, url : String) -> Unit { + match @bittorrent.parse_http_tracker_url(url) { + Some(parsed) => { + for existing in t.trackers { + if existing.url == url { + return + } + } + t.trackers.push({ + url, + host: parsed.host, + port: parsed.port, + path: parsed.request_target, + state: 0, + started_ms: 0UL, + next_announce_ms: 0UL, + stream_id: 0U, + peer_hash: None, + sent_req: false, + recv_buf: [], + }) + } + None => () + } +} + +///| +fn bt_add_known_peer( + t : ActiveTorrent, + peer_hash : @common.Hash, + local_hash : @common.Hash, +) -> Bool { + if peer_hash == local_hash { + return false + } + for h in t.known_peers { + if h == peer_hash { + return false + } + } + t.known_peers.push(peer_hash) + true +} + +///| +fn bt_build_bitfield_bytes(have : Array[Bool]) -> Bytes { + let num = have.length() + let byte_len = (num + 7) / 8 + let buf = FixedArray::make(byte_len, b'\x00') + for i = 0; i < num; i = i + 1 { + if have[i] { + let b = buf[i / 8].to_int() | (0x80 >> (i % 8)) + buf[i / 8] = b.to_byte() + } + } + Bytes::from_array(buf) +} + +///| +fn bt_decode_bitfield(payload : Bytes, num_pieces : Int32) -> Array[Bool] { + let out = Array::make(num_pieces, false) + for i = 0; i < num_pieces; i = i + 1 { + let byte_idx = i / 8 + if byte_idx < payload.length() { + let mask = 0x80 >> (i % 8) + if (payload[byte_idx].to_int() & mask) != 0 { + out[i] = true + } + } + } + out +} + +///| +fn bt_pop_front_bytes(buf : Array[Byte], count : Int32) -> Unit { + if count <= 0 { + return + } + if count >= buf.length() { + buf.clear() + return + } + let rem : Array[Byte] = [] + for i = count; i < buf.length(); i = i + 1 { + rem.push(buf[i]) + } + buf.clear() + for b in rem { + buf.push(b) + } +} + +///| +fn bt_find_torrent_by_ih(eng : TorrentEngine, ih : Bytes) -> ActiveTorrent? { + for t in eng.torrents { + if @crypto.ct_eq(t.info_hash, ih) { + return Some(t) + } + } + None +} + +///| +fn bt_find_torrent_by_hex( + eng : TorrentEngine, + hex_ih : String, +) -> ActiveTorrent? { + let norm = bt_hex_lower(hex_ih) + for t in eng.torrents { + if t.info_hash_hex == norm { + return Some(t) + } + } + None +} + +///| +fn Router::resolve_i2p_host_hash(self : Router, host : String) -> @common.Hash? { + let trimmed = host.trim().to_owned() + if trimmed.length() == 0 { + return None + } + match parse_b32_hash(trimmed) { + Some(h) => return Some(h) + None => () + } + let lower = trimmed.to_lower() + if lower.length() >= 52 && !lower.contains(".") { + match parse_b32_hash(lower + ".b32.i2p") { + Some(h) => return Some(h) + None => () + } + } + if lower.length() == 64 { + let raw = @encoding.hex_decode(lower) catch { _ => b"" } + if raw.length() == 32 { + let h = @common.Hash::from_bytes(raw) catch { _ => return None } + return Some(h) + } + } + match self.resolve_b32_alias(lower) { + Some(h) => return Some(h) + None => () + } + match self.resolve_name_local(lower, None) { + Some(pub_b64) => { + let d = @common.Destination::from_base64(pub_b64) catch { + _ => return None + } + Some(d.hash()) + } + None => None + } +} + +///| +fn Router::ensure_torrent_session(self : Router) -> SamSession? { + let sid = "__torrent__" + match self.find_session_by_id(sid) { + Some(s) => return Some(s) + None => () + } + let (dest, pub_b64, _priv_b64, xkp, seed) = generate_transient_destination() catch { + _ => return None + } + let hash = dest.hash() + let b32 = dest.b32_address() + let sess : SamSession = { + id: sid, + dest, + hash, + pub_b64, + b32, + virtual_tid: self.alloc_tunnel_id(), + x25519_pub: Some(xkp.public_key), + ed_seed: Some(seed), + ratchet: Some(@ratchet.RatchetSessionManager::new(xkp)), + stream_mgr: Some( + @streaming.StreamManager::new( + dest, + seed, + initial_stream_id=self.alloc_stream_id(), + ), + ), + } + self.sessions.push(sess) + self.publish_session_leaseset2(sess) + Some(sess) +} + +///| +/// Enables the router's integrated I2P BitTorrent + I2P DHT engine. +pub fn Router::enable_torrent_engine( + self : Router, + download_dir~ : String = "", + dht_query_port~ : UInt32 = 6881U, + dht_reply_port~ : UInt32 = 6882U, +) -> Unit raise RouterError { + let dl_trimmed = download_dir.trim().to_owned() + let clean_dir = if dl_trimmed.length() > 0 { + bt_normalize_dir(dl_trimmed) + } else { + bt_default_download_dir() + } + let _ = @ntcp2_net.mkdir_p(clean_dir) catch { e => raise Net(e) } + match self.torrent_engine { + Some(eng) => { + if dl_trimmed.length() > 0 { + eng.download_dir = clean_dir + } + return + } + None => () + } + let sess = match self.ensure_torrent_session() { + Some(s) => s + None => raise Protocol("failed to initialize __torrent__ I2P session") + } + let rand14 = @ntcp2_net.random_bytes(14) catch { e => raise Net(e) } + let secret = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) } + let dht = @bittorrent.I2pDht::new( + sess.hash, + rand14, + secret, + query_port=dht_query_port, + reply_port=dht_reply_port, + ) catch { + e => raise Protocol("failed to init I2P DHT: \{bt_err_msg(e)}") + } + let pid_rand = @ntcp2_net.random_bytes(12) catch { e => raise Net(e) } + let pw = @encoding.Writer::new(capacity=20) + pw.write_bytes(b"-MI0100-") + pw.write_bytes(pid_rand) + self.torrent_engine = Some({ + session_id: sess.id, + peer_id: pw.to_bytes(), + download_dir: clean_dir, + dht, + torrents: [], + pending_inbound: [], + pending_dht_pings: [], + last_dht_maint_ms: 0UL, + last_ls2_pub_ms: @ntcp2_net.unix_time_ms(), + last_ls2_pub_tunnels: self.tunnels.inbound.length(), + }) +} + +///| +pub fn Router::torrent_session_hash(self : Router) -> @common.Hash? { + match self.find_session_by_id("__torrent__") { + Some(s) => Some(s.hash) + None => None + } +} + +///| +pub fn Router::torrent_b32_address(self : Router) -> String { + match self.find_session_by_id("__torrent__") { + Some(s) => s.b32 + None => "" + } +} + +///| +fn Router::enqueue_dht_bootstrap( + self : Router, + eng : TorrentEngine, + node_hash : @common.Hash, + port : UInt32, +) -> Bool { + match self.find_session_by_id(eng.session_id) { + Some(s) if node_hash == s.hash => return false + None => return false + _ => () + } + let use_port = if port == 0U { 6881U } else { port } + let now_ms = @ntcp2_net.unix_time_ms() + for p in eng.pending_dht_pings { + if p.0 == node_hash && p.1 == use_port { + return true + } + } + let _ = self.start_proxy_netdb_lookup(node_hash) + eng.pending_dht_pings.push((node_hash, use_port, now_ms)) + true +} + +///| +pub fn Router::dht_add_bootstrap_node( + self : Router, + node_hash : @common.Hash, + port~ : UInt32 = 6881U, +) -> Bool { + let eng = match self.torrent_engine { + Some(e) => e + None => return false + } + self.enqueue_dht_bootstrap(eng, node_hash, port) +} + +///| +pub fn Router::add_torrent_bytes( + self : Router, + torrent_bytes : Bytes, + download_dir~ : String = "", +) -> String raise RouterError { + self.enable_torrent_engine(download_dir~) + let eng = match self.torrent_engine { + Some(e) => e + None => raise Protocol("torrent engine unavailable") + } + let meta = @bittorrent.parse_torrent(torrent_bytes) catch { + e => raise Protocol("invalid .torrent metainfo: \{bt_err_msg(e)}") + } + let hex = @encoding.hex_encode(meta.info_hash) + let dl_trimmed = download_dir.trim().to_owned() + let target_dir = if dl_trimmed.length() > 0 { + let d = bt_normalize_dir(dl_trimmed) + let _ = @ntcp2_net.mkdir_p(d) catch { e => raise Net(e) } + d + } else { + eng.download_dir + } + match bt_find_torrent_by_ih(eng, meta.info_hash) { + Some(existing) => { + if existing.metainfo is None { + bt_init_torrent_metainfo(existing, meta) + } + for tr in meta.trackers { + bt_add_tracker_url(existing, tr) + } + existing.paused = false + return hex + } + None => () + } + let now_ms = @ntcp2_net.unix_time_ms() + let t : ActiveTorrent = { + info_hash: meta.info_hash, + info_hash_hex: hex, + name: meta.name, + download_dir: target_dir, + metainfo: Some(meta), + raw_info: meta.raw_info, + paused: false, + completed: false, + error: "", + downloaded_bytes: 0UL, + uploaded_bytes: 0UL, + have_pieces: Array::make(meta.piece_hashes.length(), false), + inflight_pieces: [], + meta_size: meta.raw_info.length(), + meta_pieces: [], + meta_req_ms: 0UL, + known_peers: [], + peers: [], + trackers: [], + last_dht_lookup_ms: 0UL, + last_pex_ms: 0UL, + } + bt_init_torrent_metainfo(t, meta) + eng.torrents.push(t) + match self.find_session_by_id(eng.session_id) { + Some(sess) => eng.dht.store_peer(t.info_hash, sess.hash, now_ms) + None => () + } + hex +} + +///| +pub fn Router::add_seed_torrent( + self : Router, + torrent_bytes : Bytes, + seed_dir : String, +) -> String raise RouterError { + self.add_torrent_bytes(torrent_bytes, download_dir=seed_dir) +} + +///| +pub fn Router::add_torrent_magnet( + self : Router, + uri : String, + download_dir~ : String = "", +) -> String raise RouterError { + self.enable_torrent_engine(download_dir~) + let eng = match self.torrent_engine { + Some(e) => e + None => raise Protocol("torrent engine unavailable") + } + let mag = @bittorrent.parse_magnet(uri) catch { + e => raise Protocol("invalid magnet URI: \{bt_err_msg(e)}") + } + let hex = @encoding.hex_encode(mag.info_hash) + let dl_trimmed = download_dir.trim().to_owned() + let target_dir = if dl_trimmed.length() > 0 { + let d = bt_normalize_dir(dl_trimmed) + let _ = @ntcp2_net.mkdir_p(d) catch { e => raise Net(e) } + d + } else { + eng.download_dir + } + match bt_find_torrent_by_ih(eng, mag.info_hash) { + Some(existing) => { + for tr in mag.trackers { + bt_add_tracker_url(existing, tr) + } + for dn in mag.dht_nodes { + match self.resolve_i2p_host_hash(dn.0) { + Some(h) => { + let _ = self.enqueue_dht_bootstrap(eng, h, dn.1) + } + None => () + } + } + existing.paused = false + return hex + } + None => () + } + let now_ms = @ntcp2_net.unix_time_ms() + let t : ActiveTorrent = { + info_hash: mag.info_hash, + info_hash_hex: hex, + name: if mag.display_name.length() > 0 { + mag.display_name + } else { + hex + }, + download_dir: target_dir, + metainfo: None, + raw_info: b"", + paused: false, + completed: false, + error: "", + downloaded_bytes: 0UL, + uploaded_bytes: 0UL, + have_pieces: [], + inflight_pieces: [], + meta_size: 0, + meta_pieces: [], + meta_req_ms: 0UL, + known_peers: [], + peers: [], + trackers: [], + last_dht_lookup_ms: 0UL, + last_pex_ms: 0UL, + } + for tr in mag.trackers { + bt_add_tracker_url(t, tr) + } + for dn in mag.dht_nodes { + match self.resolve_i2p_host_hash(dn.0) { + Some(h) => { + let _ = self.enqueue_dht_bootstrap(eng, h, dn.1) + } + None => () + } + } + eng.torrents.push(t) + match self.find_session_by_id(eng.session_id) { + Some(sess) => eng.dht.store_peer(t.info_hash, sess.hash, now_ms) + None => () + } + hex +} + +///| +pub fn Router::pause_torrent(self : Router, info_hash_hex : String) -> Bool { + let eng = match self.torrent_engine { + Some(e) => e + None => return false + } + match bt_find_torrent_by_hex(eng, info_hash_hex) { + Some(t) => { + t.paused = true + let mgr_opt = match self.find_session_by_id(eng.session_id) { + Some(s) => s.stream_mgr + None => None + } + let now_ms = @ntcp2_net.unix_time_ms() + for p in t.peers { + p.state = 4 + match mgr_opt { + Some(mgr) if p.stream_id != 0U => { + match find_stream_by_id(mgr, p.stream_id) { + Some(c) => { + let _ = c.close(now_ms) catch { _ => () } + } + None => () + } + remove_stream_by_id(mgr, p.stream_id) + } + _ => () + } + } + t.peers.clear() + true + } + None => false + } +} + +///| +pub fn Router::resume_torrent(self : Router, info_hash_hex : String) -> Bool { + let eng = match self.torrent_engine { + Some(e) => e + None => return false + } + match bt_find_torrent_by_hex(eng, info_hash_hex) { + Some(t) => { + t.paused = false + t.last_dht_lookup_ms = 0UL + for tr in t.trackers { + tr.next_announce_ms = 0UL + } + true + } + None => false + } +} + +///| +pub fn Router::remove_torrent(self : Router, info_hash_hex : String) -> Bool { + let eng = match self.torrent_engine { + Some(e) => e + None => return false + } + let norm = bt_hex_lower(info_hash_hex) + let mgr_opt = match self.find_session_by_id(eng.session_id) { + Some(s) => s.stream_mgr + None => None + } + let now_ms = @ntcp2_net.unix_time_ms() + for i = 0; i < eng.torrents.length(); i = i + 1 { + if eng.torrents[i].info_hash_hex == norm { + let t = eng.torrents[i] + for p in t.peers { + match mgr_opt { + Some(mgr) if p.stream_id != 0U => { + match find_stream_by_id(mgr, p.stream_id) { + Some(c) => { + let _ = c.close(now_ms) catch { _ => () } + } + None => () + } + remove_stream_by_id(mgr, p.stream_id) + } + _ => () + } + } + for tr in t.trackers { + match mgr_opt { + Some(mgr) if tr.stream_id != 0U => + remove_stream_by_id(mgr, tr.stream_id) + _ => () + } + } + let _ = eng.torrents.remove(i) + return true + } + } + false +} + +///| +fn Router::send_torrent_i2cp( + self : Router, + sess : SamSession, + peer_hash : @common.Hash, + i2cp_bytes : Bytes, + send_ls2~ : Bool = false, +) -> Bool { + let ratchet = match sess.ratchet { + Some(r) => r + None => return false + } + let now_sec = @ntcp2_net.unix_time_sec() + let ls2 = match self.netdb.get_lease_set2(peer_hash, now_sec) { + Some(l) if l.leases.length() > 0 => l + _ => return false + } + let peer_static = match extract_x25519_key(ls2) { + Some(k) => k + None => return false + } + let valid : Array[@common.Lease2] = [] + for l in ls2.leases { + if l.end_date_sec > now_sec { + valid.push(l) + } + } + let pool = if valid.length() > 0 { valid } else { ls2.leases } + let rr = if self.lease_rr < 0 { 0 } else { self.lease_rr } + self.lease_rr = (self.lease_rr + 1) & 0x3FFFFFFF + let chosen = pool[rr % pool.length()] + let exp_sec = now_sec + 60U + let blocks : Array[@ratchet.RatchetBlock] = [] + if send_ls2 { + match self.build_session_leaseset2(sess, now_sec) { + Some(my_ls2) => { + let ls_bytes = my_ls2.to_bytes() catch { _ => b"" } + if ls_bytes.length() > 0 { + let ls_blk = @ratchet.garlic_clove_block( + Local, + self.alloc_msg_id(), + exp_sec, + DatabaseStore( + key=sess.hash, + store_type=b'\x03', + reply_token=0U, + reply_tunnel_id=0U, + reply_gateway=None, + data=ls_bytes, + ), + ) catch { + _ => return false + } + blocks.push(ls_blk) + } + } + None => () + } + } + let clove = @ratchet.garlic_clove_block( + Destination(peer_hash), + self.alloc_msg_id(), + exp_sec, + Data(data=i2cp_bytes), + ) catch { + _ => return false + } + blocks.push(clove) + let wire = ratchet.encrypt_to_peer(peer_static, blocks, now_sec, next_rand_32) catch { + _ => return false + } + self.send_routed_i2np( + chosen.tunnel_gw, + Some(chosen.tunnel_id), + Garlic(data=wire), + ) + true +} + +///| +fn Router::send_dht_query( + self : Router, + eng : TorrentEngine, + sess : SamSession, + target_hash : @common.Hash, + target_port : UInt32, + kind : @bittorrent.KrpcQueryKind, + now_ms : UInt64, + info_hash~ : Bytes? = None, +) -> Bool { + if target_hash == sess.hash { + return false + } + let seed = match sess.ed_seed { + Some(s) => s + None => return false + } + let now_sec = (now_ms / 1000UL).to_uint() + match self.netdb.get_lease_set2(target_hash, now_sec) { + Some(l) if l.leases.length() > 0 => () + _ => { + let _ = self.start_proxy_netdb_lookup(target_hash) + return false + } + } + let tx_id = eng.dht.alloc_tx_id() + let payload = @bittorrent.encode_krpc( + Query(tx_id~, sender_id=eng.dht.local_id, kind~), + ) + let dgram = @streaming.RepliableDatagram::sign_ed25519( + sess.dest, + seed, + payload, + ) catch { + _ => return false + } + let port = if target_port == 0U { 6881U } else { target_port } + let i2cp = dgram.to_i2cp_bytes(from_port=eng.dht.query_port, to_port=port) + if !self.send_torrent_i2cp(sess, target_hash, i2cp, send_ls2=true) { + return false + } + let kind_str = match kind { + Ping => "ping" + FindNode(..) => "find_node" + GetPeers(..) => "get_peers" + AnnouncePeer(..) => "announce_peer" + } + eng.dht.register_pending_tx( + tx_id, + kind_str, + target_hash, + port, + now_ms, + info_hash~, + ) + true +} + +///| +fn Router::send_dht_reply( + self : Router, + eng : TorrentEngine, + sess : SamSession, + target_hash : @common.Hash, + reply_port : UInt32, + tx_id : Bytes, + nodes : Bytes, + values : Array[Bytes], + token : Bytes?, +) -> Bool { + let payload = @bittorrent.encode_krpc( + Response(tx_id~, sender_id=eng.dht.local_id, nodes~, values~, token~), + ) + let i2cp = @streaming.encode_raw_datagram( + payload, + from_port=eng.dht.query_port, + to_port=reply_port, + ) + self.send_torrent_i2cp(sess, target_hash, i2cp, send_ls2=false) +} + +///| +fn Router::poll_dht_datagrams( + self : Router, + eng : TorrentEngine, + sess : SamSession, + mgr : @streaming.StreamManager, + now_ms : UInt64, +) -> Bool { + let mut did_work = false + + // 1. Incoming Repliable Datagrams (proto 0x11): KRPC Queries + while mgr.incoming_repliable_dgrams.length() > 0 { + did_work = true + let (hdr, dgram) = mgr.incoming_repliable_dgrams.remove(0) + if hdr.to_port != 0U && hdr.to_port != eng.dht.query_port { + continue + } + if !dgram.verify() { + continue + } + let sender_hash = dgram.sender.hash() + let sender_port = if hdr.from_port > 0U { hdr.from_port } else { 6881U } + let reply_port = if sender_port < 65535U { + sender_port + 1U + } else { + sender_port + } + let msg = Some(@bittorrent.decode_krpc(dgram.payload)) catch { _ => None } + match msg { + Some(Query(tx_id~, sender_id~, kind~)) => { + eng.dht.record_query_recv() + let _ = eng.dht.upsert_node(sender_id, sender_hash, sender_port, now_ms) + match kind { + Ping => { + let _ = self.send_dht_reply( + eng, + sess, + sender_hash, + reply_port, + tx_id, + b"", + [], + None, + ) + } + FindNode(target~) => { + let closest = eng.dht.closest_nodes(target, limit=8) + let compact = @bittorrent.encode_compact_nodes(closest) + let _ = self.send_dht_reply( + eng, + sess, + sender_hash, + reply_port, + tx_id, + compact, + [], + None, + ) + } + GetPeers(info_hash~) => { + let tk = eng.dht.make_token(sender_hash) + let local_peers = eng.dht.get_peers_local(info_hash, now_ms) + match bt_find_torrent_by_ih(eng, info_hash) { + Some(t) if !t.paused => { + let mut has_self = false + for ph in local_peers { + if ph == sess.hash { + has_self = true + break + } + } + if !has_self { + local_peers.push(sess.hash) + } + } + _ => () + } + let values : Array[Bytes] = [] + for ph in local_peers { + values.push(ph.as_bytes()) + } + let compact = if values.length() == 0 { + @bittorrent.encode_compact_nodes( + eng.dht.closest_nodes(info_hash, limit=8), + ) + } else { + b"" + } + let _ = self.send_dht_reply( + eng, + sess, + sender_hash, + reply_port, + tx_id, + compact, + values, + Some(tk), + ) + } + AnnouncePeer(info_hash~, ..) => { + match kind { + AnnouncePeer(token~, ..) => + if eng.dht.verify_token(sender_hash, token) { + eng.dht.store_peer(info_hash, sender_hash, now_ms) + } + _ => () + } + let _ = self.send_dht_reply( + eng, + sess, + sender_hash, + reply_port, + tx_id, + b"", + [], + None, + ) + } + } + } + _ => () + } + } + + // 2. Incoming Raw Datagrams (proto 0x12): KRPC Responses + while mgr.incoming_raw_dgrams.length() > 0 { + did_work = true + let (hdr, raw) = mgr.incoming_raw_dgrams.remove(0) + if hdr.to_port != 0U && + hdr.to_port != eng.dht.reply_port && + hdr.to_port != eng.dht.query_port { + continue + } + let msg = Some(@bittorrent.decode_krpc(raw)) catch { _ => None } + match msg { + Some(Response(tx_id~, sender_id~, nodes~, values~, token~)) => + match eng.dht.take_pending_tx(tx_id) { + Some(tx) => { + let _ = eng.dht.upsert_node( + sender_id, + tx.dest_hash, + tx.port, + now_ms, + ) + if nodes.length() > 0 { + let decoded_nodes = @bittorrent.decode_compact_nodes( + nodes, + now_ms~, + ) catch { + _ => [] + } + for dn in decoded_nodes { + let added = eng.dht.upsert_node( + dn.node_id, + dn.dest_hash, + dn.port, + now_ms, + ) + if added { + match tx.info_hash { + Some(ih) => + match bt_find_torrent_by_ih(eng, ih) { + Some(t) if !t.paused && t.known_peers.length() < 8 => { + let _ = self.send_dht_query( + eng, + sess, + dn.dest_hash, + dn.port, + GetPeers(info_hash=ih), + now_ms, + info_hash=Some(ih), + ) + } + _ => () + } + None => () + } + } + } + } + match tx.info_hash { + Some(ih) => + match bt_find_torrent_by_ih(eng, ih) { + Some(t) => { + let mut newly_added = 0UL + for v in values { + if v.length() == 32 { + let ph = @common.Hash::from_bytes(v) catch { + _ => continue + } + eng.dht.store_peer(ih, ph, now_ms) + if bt_add_known_peer(t, ph, sess.hash) { + newly_added += 1UL + } + } + } + if newly_added > 0UL { + eng.dht.record_peers_discovered(newly_added) + } + if tx.kind == "get_peers" && !t.paused { + match token { + Some(tk) => { + let _ = self.send_dht_query( + eng, + sess, + tx.dest_hash, + tx.port, + AnnouncePeer( + info_hash=ih, + port=eng.dht.query_port, + token=tk, + implied_port=false, + ), + now_ms, + info_hash=Some(ih), + ) + } + None => () + } + } + } + None => () + } + None => () + } + } + None => () + } + _ => () + } + } + did_work +} + +///| +fn Router::step_dht( + self : Router, + eng : TorrentEngine, + sess : SamSession, + now_ms : UInt64, +) -> Bool { + let mut did_work = false + eng.dht.prune_expired_txs(now_ms) + + // Retry pending bootstrap pings once peer LeaseSet2 resolves + let mut pi = 0 + while pi < eng.pending_dht_pings.length() { + let (ph, port, started_ms) = eng.pending_dht_pings[pi] + if self.send_dht_query(eng, sess, ph, port, Ping, now_ms) { + let _ = eng.pending_dht_pings.remove(pi) + did_work = true + continue + } + if now_ms > started_ms + 30000UL { + let _ = eng.pending_dht_pings.remove(pi) + continue + } + pi += 1 + } + + // Background self-lookup maintenance every 25s + if eng.dht.nodes.length() > 0 && now_ms >= eng.last_dht_maint_ms + 25000UL { + eng.last_dht_maint_ms = now_ms + let closest = eng.dht.closest_nodes(eng.dht.local_id, limit=3) + for n in closest { + if self.send_dht_query( + eng, + sess, + n.dest_hash, + n.port, + FindNode(target=eng.dht.local_id), + now_ms, + ) { + did_work = true + } + } + } + + // Per-torrent DHT peer lookup & announce + for t in eng.torrents { + if t.paused || eng.dht.nodes.length() == 0 { + continue + } + eng.dht.store_peer(t.info_hash, sess.hash, now_ms) + let interval_ms = if t.known_peers.length() == 0 && !t.completed { + 800UL + } else { + 15000UL + } + if now_ms >= t.last_dht_lookup_ms + interval_ms { + t.last_dht_lookup_ms = now_ms + let closest = eng.dht.closest_nodes(t.info_hash, limit=4) + for n in closest { + if self.send_dht_query( + eng, + sess, + n.dest_hash, + n.port, + GetPeers(info_hash=t.info_hash), + now_ms, + info_hash=Some(t.info_hash), + ) { + did_work = true + } + } + } + } + did_work +} + +///| +fn Router::step_trackers( + self : Router, + eng : TorrentEngine, + sess : SamSession, + mgr : @streaming.StreamManager, + now_ms : UInt64, +) -> Bool { + let now_sec = (now_ms / 1000UL).to_uint() + let mut did_work = false + for t in eng.torrents { + if t.paused { + continue + } + for tr in t.trackers { + match tr.state { + 0 => { + if now_ms < tr.next_announce_ms { + continue + } + match self.resolve_i2p_host_hash(tr.host) { + Some(thash) => { + tr.peer_hash = Some(thash) + tr.state = 1 + tr.started_ms = now_ms + tr.recv_buf.clear() + tr.sent_req = false + let _ = self.start_proxy_netdb_lookup(thash) + did_work = true + } + None => tr.next_announce_ms = now_ms + 30000UL + } + } + 1 => { + let thash = match tr.peer_hash { + Some(h) => h + None => { + tr.state = 0 + tr.next_announce_ms = now_ms + 30000UL + continue + } + } + match self.netdb.get_lease_set2(thash, now_sec) { + Some(ls2) if ls2.leases.length() > 0 => { + let to_port = if tr.port == 80U { 0U } else { tr.port } + let conn = mgr.connect(thash, now_ms, from_port=0U, to_port~) catch { + _ => { + tr.state = 0 + tr.next_announce_ms = now_ms + 20000UL + continue + } + } + tr.stream_id = conn.local_stream_id + tr.state = 2 + tr.started_ms = now_ms + match extract_x25519_key(ls2) { + Some(pstat) => + self.flush_stream_outbound( + sess, + conn, + thash, + pstat, + ls2.leases[0].tunnel_gw, + ls2.leases[0].tunnel_id, + send_ls2=true, + ) + None => () + } + did_work = true + } + _ => + if now_ms > tr.started_ms + 25000UL { + tr.state = 0 + tr.next_announce_ms = now_ms + 30000UL + } + } + } + 2 => { + let thash = match tr.peer_hash { + Some(h) => h + None => { + tr.state = 0 + continue + } + } + let conn = match find_stream_by_id(mgr, tr.stream_id) { + Some(c) => c + None => { + tr.state = 0 + tr.next_announce_ms = now_ms + 20000UL + continue + } + } + if !tr.sent_req && conn.state == Established { + let total_len = match t.metainfo { + Some(m) => m.total_length + None => 0L + } + let left = if total_len.reinterpret_as_uint64() > t.downloaded_bytes { + (total_len.reinterpret_as_uint64() - t.downloaded_bytes).reinterpret_as_int64() + } else { + 0L + } + let req_str = @bittorrent.build_http_announce_request( + { host: tr.host, port: tr.port, request_target: tr.path, }, + t.info_hash, + eng.peer_id, + t.uploaded_bytes.reinterpret_as_int64(), + t.downloaded_bytes.reinterpret_as_int64(), + left, + event=if t.completed { "completed" } else { "started" }, + local_dest_b64=sess.pub_b64, + ) + let _ = conn.write(@encoding.string_to_utf8_bytes(req_str), now_ms) catch { + _ => 0 + } + tr.sent_req = true + match self.netdb.get_lease_set2(thash, now_sec) { + Some(ls2) if ls2.leases.length() > 0 => + match extract_x25519_key(ls2) { + Some(pstat) => + self.flush_stream_outbound( + sess, + conn, + thash, + pstat, + ls2.leases[0].tunnel_gw, + ls2.leases[0].tunnel_id, + send_ls2=false, + ) + None => () + } + _ => () + } + did_work = true + } + let avail = conn.read_available() + if avail.length() > 0 { + for i = 0; i < avail.length(); i = i + 1 { + if tr.recv_buf.length() < 512 * 1024 { + tr.recv_buf.push(avail[i]) + } + } + did_work = true + } + if conn.is_eof() || + conn.state == Reset || + now_ms > tr.started_ms + 25000UL { + let _ = conn.close(now_ms) catch { _ => () } + remove_stream_by_id(mgr, tr.stream_id) + tr.stream_id = 0U + let mut next_wait = 60000UL + if tr.recv_buf.length() > 0 { + let raw = Bytes::from_array(tr.recv_buf) + tr.recv_buf.clear() + let resp_opt = Some(@bittorrent.parse_http_tracker_response(raw)) catch { + _ => None + } + match resp_opt { + Some(resp) => { + for ph in resp.peers { + if bt_add_known_peer(t, ph, sess.hash) { + eng.dht.record_peers_discovered(1UL) + } + } + if resp.interval >= 15 { + next_wait = resp.interval.to_uint64() * 1000UL + } + } + None => () + } + } + tr.state = 0 + tr.next_announce_ms = now_ms + next_wait + did_work = true + } + } + _ => tr.state = 0 + } + } + } + did_work +} + +///| +fn Router::bt_flush_peer_send_buf( + self : Router, + sess : SamSession, + conn : @streaming.StreamConnection, + peer : TorrentPeerConn, + now_ms : UInt64, +) -> Bool { + if peer.send_buf.length() == 0 { + return false + } + let wrote = conn.write(Bytes::from_array(peer.send_buf), now_ms) catch { + _ => 0 + } + if wrote <= 0 { + return false + } + bt_pop_front_bytes(peer.send_buf, wrote) + match (peer.lease_gw, peer.peer_static.length() == 32) { + (Some(gw), true) => + self.flush_stream_outbound( + sess, + conn, + peer.peer_hash, + peer.peer_static, + gw, + peer.lease_tid, + send_ls2=false, + ) + _ => () + } + true +} + +///| +fn Router::bt_send_peer_wire( + self : Router, + sess : SamSession, + conn : @streaming.StreamConnection, + peer : TorrentPeerConn, + data : Bytes, + now_ms : UInt64, +) -> Unit { + for i = 0; i < data.length(); i = i + 1 { + peer.send_buf.push(data[i]) + } + let _ = self.bt_flush_peer_send_buf(sess, conn, peer, now_ms) +} + +///| +fn Router::bt_send_post_handshake( + self : Router, + sess : SamSession, + conn : @streaming.StreamConnection, + t : ActiveTorrent, + peer : TorrentPeerConn, + now_ms : UInt64, +) -> Unit { + if !peer.sent_ext_hs { + peer.sent_ext_hs = true + let msize : Int32? = if t.meta_size > 0 { Some(t.meta_size) } else { None } + let ext_hs = @bittorrent.encode_ext_handshake(metadata_size=msize) + self.bt_send_peer_wire( + sess, + conn, + peer, + @bittorrent.encode_peer_message(Extended(b'\x00', ext_hs)), + now_ms, + ) + if t.have_pieces.length() > 0 { + let bf = bt_build_bitfield_bytes(t.have_pieces) + self.bt_send_peer_wire( + sess, + conn, + peer, + @bittorrent.encode_peer_message(Bitfield(bf)), + now_ms, + ) + } + if peer.am_choking { + peer.am_choking = false + self.bt_send_peer_wire( + sess, + conn, + peer, + @bittorrent.encode_peer_message(Unchoke), + now_ms, + ) + } + if !t.completed && !peer.am_interested { + peer.am_interested = true + self.bt_send_peer_wire( + sess, + conn, + peer, + @bittorrent.encode_peer_message(Interested), + now_ms, + ) + } + } +} + +///| +fn Router::bt_handle_ext_message( + self : Router, + eng : TorrentEngine, + sess : SamSession, + conn : @streaming.StreamConnection, + t : ActiveTorrent, + peer : TorrentPeerConn, + ext_id : Byte, + payload : Bytes, + now_ms : UInt64, +) -> Unit { + if ext_id == b'\x00' { + let re = @bittorrent.decode_ext_handshake(payload) catch { _ => return } + peer.remote_ext = Some(re) + match re.metadata_size { + Some(ms) if ms > 0 && t.meta_size == 0 => t.meta_size = ms + _ => () + } + match re.i2p_dht_id { + Some(did) => { + let msg = @bittorrent.encode_i2p_dht_ext( + eng.dht.query_port, + eng.dht.reply_port, + ) + self.bt_send_peer_wire( + sess, + conn, + peer, + @bittorrent.encode_peer_message(Extended(did, msg)), + now_ms, + ) + } + None => () + } + return + } + if ext_id == @bittorrent.ext_id_ut_metadata { + let mm = @bittorrent.decode_metadata_msg(payload) catch { _ => return } + match mm { + MetaRequest(piece) => { + if t.raw_info.length() == 0 || piece < 0 { + match peer.remote_ext { + Some(re) => + match re.ut_metadata_id { + Some(rid) => + self.bt_send_peer_wire( + sess, + conn, + peer, + @bittorrent.encode_peer_message( + Extended(rid, @bittorrent.encode_metadata_reject(piece)), + ), + now_ms, + ) + None => () + } + None => () + } + return + } + let off = piece * 16384 + if off >= t.raw_info.length() { + return + } + let end = if off + 16384 < t.raw_info.length() { + off + 16384 + } else { + t.raw_info.length() + } + let slice = t.raw_info[off:end].to_owned() + match peer.remote_ext { + Some(re) => + match re.ut_metadata_id { + Some(rid) => + self.bt_send_peer_wire( + sess, + conn, + peer, + @bittorrent.encode_peer_message( + Extended( + rid, + @bittorrent.encode_metadata_data( + piece, + t.raw_info.length(), + slice, + ), + ), + ), + now_ms, + ) + None => () + } + None => () + } + } + MetaData(piece, total_size, slice) => { + if t.metainfo is Some(_) { + return + } + if total_size > 0 && total_size <= 8 * 1024 * 1024 { + t.meta_size = total_size + let mut exists = false + for mp in t.meta_pieces { + if mp.0 == piece { + exists = true + break + } + } + if !exists { + t.meta_pieces.push((piece, slice)) + } + let need_pieces = (total_size + 16383) / 16384 + if t.meta_pieces.length() >= need_pieces { + let w = @encoding.Writer::new(capacity=total_size) + let mut ok = true + for idx = 0; idx < need_pieces; idx = idx + 1 { + let mut found : Bytes? = None + for mp in t.meta_pieces { + if mp.0 == idx { + found = Some(mp.1) + break + } + } + match found { + Some(b) => w.write_bytes(b) + None => { + ok = false + break + } + } + } + if ok { + let raw = w.to_bytes() + if raw.length() == total_size && + @crypto.ct_eq(@crypto.sha1(raw), t.info_hash) { + let parsed = @bittorrent.parse_info_dict(raw) catch { + e => { + t.error = "metadata parse failed: \{bt_err_msg(e)}" + return + } + } + bt_init_torrent_metainfo(t, parsed) + t.meta_pieces.clear() + } else { + t.meta_pieces.clear() + } + } + } + } + } + MetaReject(_) => () + } + return + } + if ext_id == @bittorrent.ext_id_pex { + let added = @bittorrent.decode_i2p_pex(payload) + for ph in added { + if bt_add_known_peer(t, ph, sess.hash) { + eng.dht.record_peers_discovered(1UL) + } + } + return + } + if ext_id == @bittorrent.ext_id_i2p_dht { + match @bittorrent.decode_i2p_dht_ext(payload) { + Some((qp, _rp)) => + if !peer.dht_pinged { + peer.dht_pinged = true + let _ = self.send_dht_query( + eng, + sess, + peer.peer_hash, + qp, + Ping, + now_ms, + ) + } + None => () + } + } +} + +///| +fn Router::bt_request_metadata_if_needed( + self : Router, + sess : SamSession, + conn : @streaming.StreamConnection, + t : ActiveTorrent, + peer : TorrentPeerConn, + now_ms : UInt64, +) -> Unit { + if t.metainfo is Some(_) || t.meta_size <= 0 { + return + } + if now_ms < t.meta_req_ms + 2500UL { + return + } + let rid = match peer.remote_ext { + Some(re) => + match re.ut_metadata_id { + Some(id) => id + None => return + } + None => return + } + let need_pieces = (t.meta_size + 16383) / 16384 + for p = 0; p < need_pieces; p = p + 1 { + let mut have = false + for mp in t.meta_pieces { + if mp.0 == p { + have = true + break + } + } + if !have { + t.meta_req_ms = now_ms + self.bt_send_peer_wire( + sess, + conn, + peer, + @bittorrent.encode_peer_message( + Extended(rid, @bittorrent.encode_metadata_request(p)), + ), + now_ms, + ) + return + } + } +} + +///| +fn Router::bt_schedule_piece_requests( + self : Router, + sess : SamSession, + conn : @streaming.StreamConnection, + t : ActiveTorrent, + peer : TorrentPeerConn, + now_ms : UInt64, +) -> Unit { + let meta = match t.metainfo { + Some(m) => m + None => return + } + if t.completed || peer.peer_choking { + return + } + // Drop timed-out in-flight requests (> 12s) + let mut i = 0 + while i < peer.in_flight.length() { + if now_ms > peer.in_flight[i].3 + 12000UL { + let _ = peer.in_flight.remove(i) + } else { + i += 1 + } + } + let max_pipeline = 4 + let num_pieces = meta.piece_hashes.length() + while peer.in_flight.length() < max_pipeline { + let mut picked : (Int32, Int32, Int32)? = None + // First fill blocks inside already-active piece buffers + for pbuf in t.inflight_pieces { + let pidx = pbuf.piece_idx + if pidx < peer.peer_bitfield.length() && !peer.peer_bitfield[pidx] { + continue + } + let plen = bt_piece_length(meta, pidx) + for bidx = 0; bidx < pbuf.num_blocks; bidx = bidx + 1 { + if pbuf.got_blocks[bidx] { + continue + } + let begin = bidx * @bittorrent.bt_block_size + let mut already_req = false + for op in t.peers { + for inf in op.in_flight { + if inf.0 == pidx && inf.1 == begin { + already_req = true + break + } + } + if already_req { + break + } + } + if !already_req { + let rem = plen - begin + let blen = if rem < @bittorrent.bt_block_size { + rem + } else { + @bittorrent.bt_block_size + } + picked = Some((pidx, begin, blen)) + break + } + } + if picked is Some(_) { + break + } + } + // Otherwise start a new piece buffer we don't have yet + if picked is None && t.inflight_pieces.length() < 4 { + for pidx = 0; pidx < num_pieces; pidx = pidx + 1 { + if t.have_pieces[pidx] { + continue + } + if pidx < peer.peer_bitfield.length() && !peer.peer_bitfield[pidx] { + continue + } + let mut active = false + for pbuf in t.inflight_pieces { + if pbuf.piece_idx == pidx { + active = true + break + } + } + if active { + continue + } + let plen = bt_piece_length(meta, pidx) + if plen <= 0 { + continue + } + let nblocks = (plen + @bittorrent.bt_block_size - 1) / + @bittorrent.bt_block_size + t.inflight_pieces.push({ + piece_idx: pidx, + data: FixedArray::make(plen, b'\x00'), + got_blocks: Array::make(nblocks, false), + num_blocks: nblocks, + }) + let blen = if plen < @bittorrent.bt_block_size { + plen + } else { + @bittorrent.bt_block_size + } + picked = Some((pidx, 0, blen)) + break + } + } + match picked { + Some((pidx, begin, blen)) => { + peer.in_flight.push((pidx, begin, blen, now_ms)) + self.bt_send_peer_wire( + sess, + conn, + peer, + @bittorrent.encode_peer_message(Request(pidx, begin, blen)), + now_ms, + ) + } + None => break + } + } +} + +///| +fn Router::bt_on_piece_block( + self : Router, + sess : SamSession, + mgr : @streaming.StreamManager, + t : ActiveTorrent, + peer : TorrentPeerConn, + piece_idx : Int32, + begin : Int32, + block : Bytes, + now_ms : UInt64, +) -> Unit { + let meta = match t.metainfo { + Some(m) => m + None => return + } + // Remove from peer.in_flight + let mut k = 0 + while k < peer.in_flight.length() { + if peer.in_flight[k].0 == piece_idx && peer.in_flight[k].1 == begin { + let _ = peer.in_flight.remove(k) + break + } + k += 1 + } + if begin % @bittorrent.bt_block_size != 0 { + return + } + let bidx = begin / @bittorrent.bt_block_size + for p_i = 0; p_i < t.inflight_pieces.length(); p_i = p_i + 1 { + let pbuf = t.inflight_pieces[p_i] + if pbuf.piece_idx == piece_idx { + if bidx >= 0 && + bidx < pbuf.num_blocks && + begin + block.length() <= pbuf.data.length() { + for j = 0; j < block.length(); j = j + 1 { + pbuf.data[begin + j] = block[j] + } + pbuf.got_blocks[bidx] = true + } + let mut complete = true + for g in pbuf.got_blocks { + if !g { + complete = false + break + } + } + if complete { + let piece_bytes = Bytes::from_array(pbuf.data) + let _ = t.inflight_pieces.remove(p_i) + if @crypto.ct_eq( + @crypto.sha1(piece_bytes), + meta.piece_hashes[piece_idx], + ) { + if bt_write_piece_to_files(t, piece_idx, piece_bytes) { + t.have_pieces[piece_idx] = true + t.downloaded_bytes += piece_bytes.length().to_uint64() + let have_msg = @bittorrent.encode_peer_message( + Have(piece_idx.reinterpret_as_uint()), + ) + for op in t.peers { + if op.state == 3 { + match find_stream_by_id(mgr, op.stream_id) { + Some(oc) => + self.bt_send_peer_wire(sess, oc, op, have_msg, now_ms) + None => () + } + } + } + let mut all_done = true + for h in t.have_pieces { + if !h { + all_done = false + break + } + } + if all_done { + t.completed = true + } + } + } + } + break + } + } +} + +///| +fn Router::bt_process_peer_messages( + self : Router, + eng : TorrentEngine, + sess : SamSession, + mgr : @streaming.StreamManager, + conn : @streaming.StreamConnection, + t : ActiveTorrent, + peer : TorrentPeerConn, + now_ms : UInt64, +) -> Unit { + for _iter = 0; _iter < 64; _iter = _iter + 1 { + let msg_opt = @bittorrent.try_decode_peer_message(peer.recv_buf) catch { + _ => { + peer.state = 4 + return + } + } + match msg_opt { + None => break + Some(msg) => { + peer.last_activity_ms = now_ms + match msg { + KeepAlive => () + Choke => { + peer.peer_choking = true + peer.in_flight.clear() + } + Unchoke => peer.peer_choking = false + Interested | NotInterested => () + Have(idx) => { + let pidx = idx.reinterpret_as_int() + if pidx >= 0 { + while peer.peer_bitfield.length() <= pidx { + peer.peer_bitfield.push(false) + } + peer.peer_bitfield[pidx] = true + } + } + Bitfield(bf) => + match t.metainfo { + Some(m) => + peer.peer_bitfield = bt_decode_bitfield( + bf, + m.piece_hashes.length(), + ) + None => + // Guess piece count from bitfield bytes until metadata arrives + peer.peer_bitfield = bt_decode_bitfield(bf, bf.length() * 8) + } + Request(piece_idx, begin, req_len) => + if req_len > 0 && + req_len <= 32768 && + piece_idx >= 0 && + piece_idx < t.have_pieces.length() && + t.have_pieces[piece_idx] { + match bt_read_span_from_files(t, piece_idx, begin, req_len) { + Some(block) => { + t.uploaded_bytes += block.length().to_uint64() + self.bt_send_peer_wire( + sess, + conn, + peer, + @bittorrent.encode_peer_message( + Piece(piece_idx, begin, block), + ), + now_ms, + ) + } + None => () + } + } + Piece(piece_idx, begin, block) => + self.bt_on_piece_block( + sess, mgr, t, peer, piece_idx, begin, block, now_ms, + ) + Cancel(_, _, _) => () + Extended(eid, epayload) => + self.bt_handle_ext_message( + eng, sess, conn, t, peer, eid, epayload, now_ms, + ) + } + } + } + } +} + +///| +fn Router::step_torrent_engine(self : Router) -> Bool { + let eng = match self.torrent_engine { + Some(e) => e + None => return false + } + let sess = match self.find_session_by_id(eng.session_id) { + Some(s) => s + None => return false + } + let mgr = match sess.stream_mgr { + Some(m) => m + None => return false + } + let now_ms = @ntcp2_net.unix_time_ms() + let now_sec = (now_ms / 1000UL).to_uint() + let mut did_work = false + + // 0. Republish __torrent__ LeaseSet2 once inbound tunnels appear or every 120s + let cur_in = self.tunnels.inbound.length() + if (cur_in > 0 && eng.last_ls2_pub_tunnels == 0) || + now_ms >= eng.last_ls2_pub_ms + 120000UL { + eng.last_ls2_pub_ms = now_ms + eng.last_ls2_pub_tunnels = cur_in + self.publish_session_leaseset2(sess) + } + + // 1. Poll I2P DHT datagrams (proto 0x11 + 0x12) and run DHT maintenance + if self.poll_dht_datagrams(eng, sess, mgr, now_ms) { + did_work = true + } + if self.step_dht(eng, sess, now_ms) { + did_work = true + } + + // 2. Drive I2P HTTP trackers + if self.step_trackers(eng, sess, mgr, now_ms) { + did_work = true + } + + // 3. Accept incoming I2P Streaming connections on __torrent__ + for _k = 0; _k < 8; _k = _k + 1 { + match mgr.accept_next() { + Some(conn) => { + did_work = true + let mut peer_static = b"" + let mut gw = self.router_hash() + let mut tid = sess.virtual_tid + match self.netdb.get_lease_set2(conn.remote_hash, now_sec) { + Some(ls2) if ls2.leases.length() > 0 => { + gw = ls2.leases[0].tunnel_gw + tid = ls2.leases[0].tunnel_id + match extract_x25519_key(ls2) { + Some(k) => peer_static = k + None => () + } + } + _ => () + } + self.flush_stream_outbound( + sess, + conn, + conn.remote_hash, + peer_static, + gw, + tid, + send_ls2=true, + ) + eng.pending_inbound.push({ + stream_id: conn.local_stream_id, + peer_hash: conn.remote_hash, + peer_static, + lease_gw: gw, + lease_tid: tid, + started_ms: now_ms, + recv_buf: [], + }) + } + None => break + } + } + + // Match pending inbound streams once 68-byte BitTorrent handshake arrives + let mut ib_i = 0 + while ib_i < eng.pending_inbound.length() { + let ib = eng.pending_inbound[ib_i] + let conn = match find_stream_by_id(mgr, ib.stream_id) { + Some(c) => c + None => { + let _ = eng.pending_inbound.remove(ib_i) + continue + } + } + let avail = conn.read_available() + if avail.length() > 0 { + for j = 0; j < avail.length(); j = j + 1 { + ib.recv_buf.push(avail[j]) + } + did_work = true + } + if ib.recv_buf.length() >= 68 { + let hs_raw = Bytes::from_array(ib.recv_buf[:68]) + let parsed_hs = Some(@bittorrent.decode_handshake(hs_raw)) catch { + _ => None + } + match parsed_hs { + Some((_ext, ih, _remote_pid)) => + match bt_find_torrent_by_ih(eng, ih) { + Some(t) if !t.paused => { + let _ = bt_add_known_peer(t, ib.peer_hash, sess.hash) + bt_pop_front_bytes(ib.recv_buf, 68) + let rem_buf : Array[Byte] = [] + for b in ib.recv_buf { + rem_buf.push(b) + } + let peer : TorrentPeerConn = { + peer_hash: ib.peer_hash, + state: 3, + started_ms: now_ms, + last_activity_ms: now_ms, + stream_id: conn.local_stream_id, + peer_static: ib.peer_static, + lease_gw: Some(ib.lease_gw), + lease_tid: ib.lease_tid, + recv_buf: rem_buf, + send_buf: [], + sent_bt_hs: true, + sent_ext_hs: false, + peer_choking: true, + am_choking: true, + am_interested: false, + remote_ext: None, + peer_bitfield: [], + in_flight: [], + dht_pinged: false, + } + let hs_out = @bittorrent.encode_handshake( + t.info_hash, + eng.peer_id, + ) catch { + _ => b"" + } + self.bt_send_peer_wire(sess, conn, peer, hs_out, now_ms) + self.bt_send_post_handshake(sess, conn, t, peer, now_ms) + self.bt_process_peer_messages( + eng, sess, mgr, conn, t, peer, now_ms, + ) + t.peers.push(peer) + let _ = eng.pending_inbound.remove(ib_i) + did_work = true + continue + } + _ => { + let _ = conn.close(now_ms) catch { _ => () } + remove_stream_by_id(mgr, conn.local_stream_id) + let _ = eng.pending_inbound.remove(ib_i) + continue + } + } + None => { + let _ = conn.close(now_ms) catch { _ => () } + remove_stream_by_id(mgr, conn.local_stream_id) + let _ = eng.pending_inbound.remove(ib_i) + continue + } + } + } + if conn.state == Reset || conn.is_eof() || now_ms > ib.started_ms + 25000UL { + let _ = conn.close(now_ms) catch { _ => () } + remove_stream_by_id(mgr, conn.local_stream_id) + let _ = eng.pending_inbound.remove(ib_i) + continue + } + ib_i += 1 + } + + // 4. Spawn outbound peer connections and pump active peer swarms + for t in eng.torrents { + if t.paused { + continue + } + // Spawn up to 12 peers per torrent when incomplete + if !t.completed { + for kh in t.known_peers { + if t.peers.length() >= 12 { + break + } + let mut already = kh == sess.hash + if !already { + for p in t.peers { + if p.peer_hash == kh { + already = true + break + } + } + } + if !already { + let _ = self.start_proxy_netdb_lookup(kh) + t.peers.push({ + peer_hash: kh, + state: 0, + started_ms: now_ms, + last_activity_ms: now_ms, + stream_id: 0U, + peer_static: b"", + lease_gw: None, + lease_tid: 0U, + recv_buf: [], + send_buf: [], + sent_bt_hs: false, + sent_ext_hs: false, + peer_choking: true, + am_choking: true, + am_interested: false, + remote_ext: None, + peer_bitfield: [], + in_flight: [], + dht_pinged: false, + }) + did_work = true + } + } + } + + let mut pi = 0 + while pi < t.peers.length() { + let p = t.peers[pi] + match p.state { + 0 => { + match self.netdb.get_lease_set2(p.peer_hash, now_sec) { + Some(ls2) if ls2.leases.length() > 0 => + match extract_x25519_key(ls2) { + Some(pstat) => { + let conn = mgr.connect( + p.peer_hash, + now_ms, + from_port=0U, + to_port=0U, + ) catch { + _ => { + p.state = 4 + continue + } + } + p.stream_id = conn.local_stream_id + p.peer_static = pstat + p.lease_gw = Some(ls2.leases[0].tunnel_gw) + p.lease_tid = ls2.leases[0].tunnel_id + p.state = 1 + p.started_ms = now_ms + self.flush_stream_outbound( + sess, + conn, + p.peer_hash, + pstat, + ls2.leases[0].tunnel_gw, + ls2.leases[0].tunnel_id, + send_ls2=true, + ) + did_work = true + } + None => () + } + _ => () + } + if p.state == 0 && now_ms > p.started_ms + 30000UL { + p.state = 4 + } + } + 1 => { + let conn = match find_stream_by_id(mgr, p.stream_id) { + Some(c) => c + None => { + p.state = 4 + continue + } + } + if conn.state == Established { + p.state = 2 + p.last_activity_ms = now_ms + if !p.sent_bt_hs { + p.sent_bt_hs = true + let hs = @bittorrent.encode_handshake(t.info_hash, eng.peer_id) catch { + _ => b"" + } + self.bt_send_peer_wire(sess, conn, p, hs, now_ms) + } + did_work = true + } else if conn.state == Reset || now_ms > p.started_ms + 30000UL { + p.state = 4 + } + } + 2 => { + let conn = match find_stream_by_id(mgr, p.stream_id) { + Some(c) => c + None => { + p.state = 4 + continue + } + } + if self.bt_flush_peer_send_buf(sess, conn, p, now_ms) { + did_work = true + } + let avail = conn.read_available() + if avail.length() > 0 { + for j = 0; j < avail.length(); j = j + 1 { + p.recv_buf.push(avail[j]) + } + did_work = true + } + if p.recv_buf.length() >= 68 { + let hs_raw = Bytes::from_array(p.recv_buf[:68]) + let parsed = Some(@bittorrent.decode_handshake(hs_raw)) catch { + _ => None + } + match parsed { + Some((_ext, ih, _pid)) if @crypto.ct_eq(ih, t.info_hash) => { + bt_pop_front_bytes(p.recv_buf, 68) + p.state = 3 + p.last_activity_ms = now_ms + self.bt_send_post_handshake(sess, conn, t, p, now_ms) + self.bt_process_peer_messages( + eng, sess, mgr, conn, t, p, now_ms, + ) + } + _ => p.state = 4 + } + } else if conn.is_eof() || + conn.state == Reset || + now_ms > p.last_activity_ms + 20000UL { + p.state = 4 + } + } + 3 => { + let conn = match find_stream_by_id(mgr, p.stream_id) { + Some(c) => c + None => { + p.state = 4 + continue + } + } + if self.bt_flush_peer_send_buf(sess, conn, p, now_ms) { + did_work = true + } + let avail = conn.read_available() + if avail.length() > 0 { + for j = 0; j < avail.length(); j = j + 1 { + p.recv_buf.push(avail[j]) + } + p.last_activity_ms = now_ms + did_work = true + } + self.bt_process_peer_messages(eng, sess, mgr, conn, t, p, now_ms) + if p.state == 3 { + self.bt_request_metadata_if_needed(sess, conn, t, p, now_ms) + self.bt_schedule_piece_requests(sess, conn, t, p, now_ms) + if conn.is_eof() || conn.state == Reset { + p.state = 4 + } + } + } + _ => () + } + if p.state == 4 { + if p.stream_id != 0U { + match find_stream_by_id(mgr, p.stream_id) { + Some(c) => { + let _ = c.close(now_ms) catch { _ => () } + } + None => () + } + remove_stream_by_id(mgr, p.stream_id) + } + let _ = t.peers.remove(pi) + did_work = true + continue + } + pi += 1 + } + + // Periodic i2p_pex gossip (every 30s) + if t.peers.length() > 0 && + t.known_peers.length() > 0 && + now_ms >= t.last_pex_ms + 30000UL { + t.last_pex_ms = now_ms + let pex_bytes = @bittorrent.encode_i2p_pex(t.known_peers) + for p in t.peers { + if p.state == 3 { + match (p.remote_ext, find_stream_by_id(mgr, p.stream_id)) { + (Some(re), Some(conn)) => + match re.i2p_pex_id { + Some(pid) => + self.bt_send_peer_wire( + sess, + conn, + p, + @bittorrent.encode_peer_message(Extended(pid, pex_bytes)), + now_ms, + ) + None => () + } + _ => () + } + } + } + } + } + did_work +} diff --git a/scripts/build_appimage.py b/scripts/build_appimage.py new file mode 100755 index 0000000..2a8555b --- /dev/null +++ b/scripts/build_appimage.py @@ -0,0 +1,466 @@ +#!/usr/bin/env python3 +"""Build a self-contained MoonI2P-Browser x86_64 AppImage. + +Bundles: + - Official Mozilla Firefox ESR (x86_64) + - Native moon-i2p router (--public, HTTP proxy, BitTorrent + I2P DHT API) + - Pre-installed moon-i2p-torrent@local Firefox WebExtension & Native Messaging host + - Pre-configured homepage http://insulaocculta.i2p/, I2P PAC routing, and HTTPS-First disabled for .i2p +""" + +import json +import os +import shutil +import stat +import subprocess +import sys +import tarfile +import urllib.request +import zipfile +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +CACHE_DIR = REPO_ROOT / ".cache" / "appimage" +APP_DIR = CACHE_DIR / "AppDir" +DIST_DIR = REPO_ROOT / "dist" +OUTPUT_APPIMAGE = DIST_DIR / "MoonI2P-Browser-x86_64.AppImage" + +EXT_SRC = REPO_ROOT / "extensions" / "firefox-i2p-torrent" +EXT_XPI = REPO_ROOT / "extensions" / "firefox-i2p-torrent.xpi" +NATIVE_HOST_SRC = REPO_ROOT / "scripts" / "moon_i2p_native_host.py" + +FIREFOX_ESR_URL = ( + "https://download.mozilla.org/?product=firefox-esr-latest-ssl&os=linux64&lang=en-US" +) +APPIMAGE_RUNTIME_URL = ( + "https://github.com/AppImage/type2-runtime/releases/download/continuous/runtime-x86_64" +) + + +def run(cmd, cwd=None, check=True): + print(f"[build_appimage] $ {' '.join(map(str, cmd))}") + return subprocess.run(cmd, cwd=str(cwd or REPO_ROOT), check=check) + + +def download_cached(url: str, dest: Path, min_bytes: int = 100_000) -> Path: + dest.parent.mkdir(parents=True, exist_ok=True) + if dest.is_file() and dest.stat().st_size >= min_bytes: + print(f"[build_appimage] Using cached {dest} ({dest.stat().st_size} bytes)") + return dest + tmp = dest.with_suffix(dest.suffix + ".part") + print(f"[build_appimage] Downloading {url} -> {dest}") + req = urllib.request.Request(url, headers={"User-Agent": "moon-i2p-appimage-builder/1.0"}) + with urllib.request.urlopen(req, timeout=180) as resp, open(tmp, "wb") as fp: + shutil.copyfileobj(resp, fp, length=1024 * 256) + if tmp.stat().st_size < min_bytes: + raise RuntimeError(f"Downloaded file too small: {tmp} ({tmp.stat().st_size} bytes)") + tmp.replace(dest) + return dest + + +def build_router_binary() -> Path: + rel_bin = REPO_ROOT / "_build" / "native" / "release" / "build" / "cmd" / "router" / "router.exe" + dbg_bin = REPO_ROOT / "_build" / "native" / "debug" / "build" / "cmd" / "router" / "router.exe" + res = subprocess.run( + ["moon", "build", "--target", "native", "--release", "cmd/router"], + cwd=str(REPO_ROOT), + ) + if res.returncode == 0 and rel_bin.is_file(): + return rel_bin + run(["moon", "build", "--target", "native", "cmd/router"]) + if not dbg_bin.is_file(): + raise FileNotFoundError(f"router binary not built at {dbg_bin}") + return dbg_bin + + +def build_extension_xpi() -> Path: + EXT_XPI.parent.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(EXT_XPI, "w", compression=zipfile.ZIP_DEFLATED) as zf: + for path in sorted(EXT_SRC.rglob("*")): + if path.is_file(): + zf.write(path, path.relative_to(EXT_SRC).as_posix()) + return EXT_XPI + + +def make_executable(path: Path): + mode = os.stat(path).st_mode + os.chmod(path, mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) + + +def write_firefox_configs(firefox_dir: Path): + pref_dir = firefox_dir / "defaults" / "pref" + pref_dir.mkdir(parents=True, exist_ok=True) + (pref_dir / "autoconfig.js").write_text( + 'pref("general.config.filename", "mozilla.cfg");\n' + 'pref("general.config.obscure_value", 0);\n', + encoding="utf-8", + ) + + # First line MUST be a comment (`//`). + (firefox_dir / "mozilla.cfg").write_text( + "// Moon I2P Browser defaults (Firefox ESR AppImage)\n" + 'pref("xpinstall.signatures.required", false);\n' + 'pref("extensions.autoDisableScopes", 0);\n' + 'pref("extensions.enabledScopes", 15);\n' + 'pref("extensions.sideloadScopes", 15);\n' + 'pref("extensions.startupScanScopes", 15);\n' + 'pref("extensions.installDistroAddons", true);\n' + 'defaultPref("browser.startup.homepage", "http://insulaocculta.i2p/");\n' + 'defaultPref("browser.startup.page", 1);\n' + 'defaultPref("dom.security.https_only_mode", false);\n' + 'defaultPref("dom.security.https_only_mode_pbm", false);\n' + 'defaultPref("dom.security.https_first", false);\n' + 'defaultPref("dom.security.https_first_pbm", false);\n' + 'pref("browser.fixup.domainsuffixwhitelist.i2p", true);\n' + 'pref("network.trr.mode", 5);\n' + 'pref("network.proxy.socks_remote_dns", true);\n' + 'pref("network.captive-portal-service.enabled", false);\n' + 'pref("network.connectivity-service.enabled", false);\n' + 'pref("browser.shell.checkDefaultBrowser", false);\n' + 'pref("app.update.auto", false);\n' + 'pref("app.update.enabled", false);\n', + encoding="utf-8", + ) + + dist_dir = firefox_dir / "distribution" + dist_dir.mkdir(parents=True, exist_ok=True) + policies = { + "policies": { + "Homepage": { + "URL": "http://insulaocculta.i2p/", + "StartPage": "homepage", + "Locked": False, + }, + "OverrideFirstRunPage": "", + "OverridePostUpdatePage": "", + "DontCheckDefaultBrowser": True, + "DisableAppUpdate": True, + "DisableTelemetry": True, + "DisablePocket": True, + "DisableFirefoxStudies": True, + "DNSOverHTTPS": {"Enabled": False}, + "Bookmarks": [ + { + "Title": "Insula Occulta", + "URL": "http://insulaocculta.i2p/", + "Placement": "toolbar", + }, + { + "Title": "I2P Stats", + "URL": "http://stats.i2p/", + "Placement": "toolbar", + }, + { + "Title": "zzz.i2p", + "URL": "http://zzz.i2p/", + "Placement": "toolbar", + }, + { + "Title": "Postman Tracker", + "URL": "http://tracker2.postman.i2p/", + "Placement": "toolbar", + }, + { + "Title": "NotBob Directory", + "URL": "http://notbob.i2p/", + "Placement": "toolbar", + }, + ], + "ExtensionSettings": { + "moon-i2p-torrent@local": { + "default_area": "navbar", + "private_browsing": True, + "updates_disabled": True, + } + }, + } + } + (dist_dir / "policies.json").write_text( + json.dumps(policies, indent=2) + "\n", encoding="utf-8" + ) + + +APP_RUN_SH = r'''#!/usr/bin/env bash +set -euo pipefail + +APPDIR="$(dirname "$(readlink -f "$0")")" +DATA_DIR="${MOON_I2P_DATA_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/moon-i2p-browser}" +PROFILE_DIR="${MOON_I2P_PROFILE_DIR:-$DATA_DIR/profile}" +DOWNLOAD_DIR="${MOON_I2P_DOWNLOAD_DIR:-$HOME/Downloads/moon-i2p}" + +mkdir -p "$DATA_DIR" "$PROFILE_DIR/extensions" "$DOWNLOAD_DIR" + +# Ensure the bundled extension XPI is installed in the browser profile. +cp -f "$APPDIR/usr/share/moon-i2p/moon-i2p-torrent@local.xpi" \ + "$PROFILE_DIR/extensions/moon-i2p-torrent@local.xpi" + +# Install a stable Native Messaging host wrapper outside the ephemeral /tmp mount. +if [[ "${MOON_I2P_NO_HOST_INSTALL:-0}" != "1" ]]; then + HOST_COPY="$DATA_DIR/moon_i2p_native_host.py" + cp -f "$APPDIR/usr/bin/moon_i2p_native_host.py" "$HOST_COPY" + chmod 755 "$HOST_COPY" + for NM_DIR in "$HOME/.mozilla/native-messaging-hosts" "$HOME/.config/mozilla/native-messaging-hosts"; do + mkdir -p "$NM_DIR" + cat > "$NM_DIR/moon_i2p_torrent.json" < "$PROFILE_DIR/i2p.pac" < "$PROFILE_DIR/user.js" </dev/null; then + kill -TERM "$FF_PID" 2>/dev/null || true + wait "$FF_PID" 2>/dev/null || true + fi + if [[ -n "$ROUTER_PID" ]] && kill -0 "$ROUTER_PID" 2>/dev/null; then + kill -TERM "$ROUTER_PID" 2>/dev/null || true + for _ in $(seq 1 20); do + kill -0 "$ROUTER_PID" 2>/dev/null || break + sleep 0.1 + done + if kill -0 "$ROUTER_PID" 2>/dev/null; then + kill -KILL "$ROUTER_PID" 2>/dev/null || true + fi + wait "$ROUTER_PID" 2>/dev/null || true + fi + exit "$rc" +} +trap cleanup EXIT INT TERM + +"$ROUTER_BIN" \ + --public \ + --sam "127.0.0.1:$SAM_PORT" \ + --http-proxy "127.0.0.1:$PROXY_PORT" \ + --torrent-api "127.0.0.1:$API_PORT" \ + --download-dir "$DOWNLOAD_DIR" \ + >> "$DATA_DIR/router.log" 2>&1 & +ROUTER_PID=$! + +cat > "$DATA_DIR/active_ports.json" < 4 * 1024 * 1024: + return None + data = sys.stdin.buffer.read(msg_len) + if len(data) < msg_len: + return None + return json.loads(data.decode("utf-8")) + + +def send_msg(obj): + encoded = json.dumps(obj).encode("utf-8") + sys.stdout.buffer.write(struct.pack(" bool: + try: + with socket.create_connection((host, port), timeout=0.3): + return True + except OSError: + return False + + +def read_managed_pid(): + if not PID_FILE.is_file(): + return None + try: + pid = int(PID_FILE.read_text(encoding="utf-8").strip()) + os.kill(pid, 0) + return pid + except (ValueError, OSError): + return None + + +def handle_request(req: dict) -> dict: + cmd = req.get("cmd", "") + is_appimage = os.environ.get("MOON_I2P_APPIMAGE") == "1" + env_proxy_host = os.environ.get("MOON_I2P_PROXY_HOST") or "" + env_proxy_port = int(os.environ.get("MOON_I2P_PROXY_PORT") or 0) + env_api_host = os.environ.get("MOON_I2P_API_HOST") or "" + env_api_port = int(os.environ.get("MOON_I2P_API_PORT") or 0) + env_download_dir = (os.environ.get("MOON_I2P_DOWNLOAD_DIR") or "").strip() + + proxy_host = env_proxy_host if (is_appimage and env_proxy_host) else str(req.get("proxy_host") or "127.0.0.1") + proxy_port = env_proxy_port if (is_appimage and env_proxy_port > 0) else int(req.get("proxy_port") or 4444) + api_host = env_api_host if (is_appimage and env_api_host) else str(req.get("api_host") or "127.0.0.1") + api_port = env_api_port if (is_appimage and env_api_port > 0) else int(req.get("api_port") or 4445) + download_dir = env_download_dir if (is_appimage and env_download_dir) else str(req.get("download_dir") or "").strip() + + if cmd == "status": + managed_pid = read_managed_pid() + return { + "ok": True, + "available": True, + "appimage": is_appimage, + "env_proxy_host": env_proxy_host, + "env_proxy_port": env_proxy_port, + "env_api_host": env_api_host, + "env_api_port": env_api_port, + "env_download_dir": env_download_dir, + "api_reachable": is_tcp_listening(api_host, api_port), + "managed_running": managed_pid is not None, + "managed_pid": managed_pid, + "router_bin": find_router_binary(), + } + + if cmd == "start_router": + if is_tcp_listening(api_host, api_port): + return { + "ok": True, + "already_running": True, + "managed_pid": read_managed_pid(), + } + router_bin = find_router_binary() + if not router_bin: + return { + "ok": False, + "error": "router.exe not found; run `moon build --target native cmd/router`", + } + args = [ + router_bin, + "--public", + "--http-proxy", + f"{proxy_host}:{proxy_port}", + "--torrent-api", + f"{api_host}:{api_port}", + ] + if download_dir: + args.extend(["--download-dir", download_dir]) + with open(LOG_FILE, "ab") as log_fp: + proc = subprocess.Popen( + args, + cwd=str(REPO_ROOT), + stdin=subprocess.DEVNULL, + stdout=log_fp, + stderr=log_fp, + start_new_session=True, + ) + PID_FILE.write_text(f"{proc.pid}\n", encoding="utf-8") + deadline = time.time() + 2.0 + while time.time() < deadline: + if is_tcp_listening(api_host, api_port): + return {"ok": True, "pid": proc.pid, "api_reachable": True} + if proc.poll() is not None: + return { + "ok": False, + "error": f"router.exe exited early (code={proc.returncode}); see {LOG_FILE}", + } + time.sleep(0.1) + return {"ok": True, "pid": proc.pid, "api_reachable": False, "starting": True} + + if cmd == "stop_router": + pid = read_managed_pid() + if pid is None: + return {"ok": True, "stopped": False} + try: + os.kill(pid, signal.SIGTERM) + PID_FILE.unlink(missing_ok=True) + return {"ok": True, "stopped": True, "pid": pid} + except OSError as exc: + return {"ok": False, "error": str(exc)} + + return {"ok": False, "error": f"unknown cmd: {cmd}"} + + +def main(): + while True: + req = read_msg() + if req is None: + break + send_msg(handle_request(req)) + + +if __name__ == "__main__": + main() diff --git a/streaming/pkg.generated.mbti b/streaming/pkg.generated.mbti index 5d356a1..8566060 100644 --- a/streaming/pkg.generated.mbti +++ b/streaming/pkg.generated.mbti @@ -110,6 +110,8 @@ pub struct StreamManager { streams : Array[StreamConnection] pending_accept : Array[StreamConnection] incoming_datagrams : Array[RepliableDatagram] + incoming_repliable_dgrams : Array[(@encoding.I2cpGzipHeader, RepliableDatagram)] + incoming_raw_dgrams : Array[(@encoding.I2cpGzipHeader, Bytes)] } pub fn StreamManager::accept_next(Self) -> StreamConnection? pub fn StreamManager::connect(Self, @common.Hash, UInt64, from_port? : UInt32, to_port? : UInt32) -> StreamConnection raise StreamingError diff --git a/streaming/stream.mbt b/streaming/stream.mbt index aee4feb..e5a8dbf 100644 --- a/streaming/stream.mbt +++ b/streaming/stream.mbt @@ -657,6 +657,10 @@ pub struct StreamManager { streams : Array[StreamConnection] pending_accept : Array[StreamConnection] incoming_datagrams : Array[RepliableDatagram] + incoming_repliable_dgrams : Array[ + (@encoding.I2cpGzipHeader, RepliableDatagram), + ] + incoming_raw_dgrams : Array[(@encoding.I2cpGzipHeader, Bytes)] } ///| @@ -672,6 +676,8 @@ pub fn StreamManager::new( streams: [], pending_accept: [], incoming_datagrams: [], + incoming_repliable_dgrams: [], + incoming_raw_dgrams: [], } } @@ -736,9 +742,14 @@ pub fn StreamManager::handle_incoming_i2cp( let dg = RepliableDatagram::decode(raw) if dg.verify() { self.incoming_datagrams.push(dg) + self.incoming_repliable_dgrams.push((hdr, dg)) } return None } + if hdr.protocol == b'\x12' { + self.incoming_raw_dgrams.push((hdr, raw)) + return None + } if hdr.protocol != b'\x06' { return None } diff --git a/streaming/streaming_test.mbt b/streaming/streaming_test.mbt index ddceaca..8a6056d 100644 --- a/streaming/streaming_test.mbt +++ b/streaming/streaming_test.mbt @@ -326,3 +326,30 @@ test "Streaming caches offline transient key from SYN-ACK to verify CLOSE withou assert_eq(a_stream.read_available(), b"HTTP/1.0 200 OK\r\n\r\nhi") assert_eq(a_stream.is_eof(), true) } + +///| +test "StreamManager dispatches protocol 17 repliable and protocol 18 raw datagrams with ports" { + let (alice_dest, alice_seed) = make_test_identity(b'\x61') + let (bob_dest, bob_seed) = make_test_identity(b'\x62') + let bob_mgr = @streaming.StreamManager::new(bob_dest, bob_seed) + let rep = @streaming.RepliableDatagram::sign_ed25519( + alice_dest, alice_seed, b"dht-query", + ) + let _ = bob_mgr.handle_incoming_i2cp( + rep.to_i2cp_bytes(from_port=6881U, to_port=6881U), + 100UL, + ) + assert_eq(bob_mgr.incoming_datagrams.length(), 1) + assert_eq(bob_mgr.incoming_repliable_dgrams.length(), 1) + assert_eq(bob_mgr.incoming_repliable_dgrams[0].0.from_port, 6881U) + assert_eq(bob_mgr.incoming_repliable_dgrams[0].0.to_port, 6881U) + assert_eq(bob_mgr.incoming_repliable_dgrams[0].1.payload, b"dht-query") + + let _ = bob_mgr.handle_incoming_i2cp( + @streaming.encode_raw_datagram(b"dht-reply", from_port=6882U, to_port=6882U), + 101UL, + ) + assert_eq(bob_mgr.incoming_raw_dgrams.length(), 1) + assert_eq(bob_mgr.incoming_raw_dgrams[0].0.from_port, 6882U) + assert_eq(bob_mgr.incoming_raw_dgrams[0].1, b"dht-reply") +}