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

- Add pure-MoonBit bittorrent package: bencode codec, metainfo/magnet parsing with path traversal checks, peer wire protocol (BEP 10/9), and I2P Kademlia DHT with KRPC and 54-byte compact nodes
- Add SHA-1 primitive in crypto for torrent info hashes
- Add router torrent API and engine, enabled with --torrent-api (default 127.0.0.1:4445) and --download-dir
- Add Firefox WebExtension torrent manager with native messaging host and packed .xpi
- Add scripts to build a standalone Firefox + router AppImage and install the native host
- Add just targets (proxy, appimage, extension), README docs, and ignore .cache/ and dist/
This commit is contained in:
nandi committed 2026-11-28 13:19:03 -08:00
1 parent 14eae00f5c
commit fbe6818c4e
37 files changed
+8543 -9

No files matched your search

+2
View File
@@ -6,3 +6,5 @@ target
.moonagent/ .moonagent/
__pycache__/ __pycache__/
*.pyc *.pyc
.cache/
dist/
+19 -4
View File
@@ -58,10 +58,25 @@ moon build --target native cmd/client
just proxy just proxy
# Optional flags: # Optional flags:
# --http-proxy [host:port] Enable HTTP-over-I2P proxy (default: 127.0.0.1:4444) # --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) # --torrent-api [host:port] Enable BitTorrent + I2P DHT HTTP API (default: 127.0.0.1:4445)
# --hosts <hosts.txt> Load hostname=base64dest (or .b32.i2p) entries from a local I2P hosts.txt # --download-dir <dir> Download directory for I2P torrents (default: ~/Downloads/moon-i2p)
# --debug Log peer dials, tunnel builds, NetDB lookups, and Garlic/Streaming state # --hops <1..4> Tunnel length (e.g. --hops 2 for 2-hop Inbound & Outbound tunnels)
# --hosts <hosts.txt> 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: # 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): # Point your browser's HTTP Proxy to 127.0.0.1:4444 (or test with curl):
+307
View File
@@ -0,0 +1,307 @@
///|
/// Pure-MoonBit BitTorrent Bencode codec and error types (BEP 3),
/// including raw `"info"` dictionary slice extraction for exact SHA-1 `info_hash`.
///|
#derive(Eq, Debug)
pub suberror BtError {
InvalidBencode(String)
InvalidMetainfo(String)
InvalidMagnet(String)
InvalidWire(String)
InvalidKrpc(String)
Encoding(@encoding.EncodingError)
Common(@common.CommonError)
}
///|
#derive(Eq, Debug)
pub(all) enum BVal {
BInt(Int64)
BBytes(Bytes)
BList(Array[BVal])
BDict(Array[(Bytes, BVal)])
}
///|
fn cmp_bytes_lex(a : Bytes, b : Bytes) -> Int32 {
let n = if a.length() < b.length() { a.length() } else { b.length() }
for i = 0; i < n; i = i + 1 {
let ai = a[i].to_int()
let bi = b[i].to_int()
if ai < bi {
return -1
}
if ai > bi {
return 1
}
}
if a.length() < b.length() {
-1
} else if a.length() > b.length() {
1
} else {
0
}
}
///|
fn encode_bval_into(w : @encoding.Writer, val : BVal) -> Unit {
match val {
BInt(n) => {
w.write_u8(b'i')
w.write_bytes(@encoding.string_to_utf8_bytes(n.to_string()))
w.write_u8(b'e')
}
BBytes(b) => {
w.write_bytes(@encoding.string_to_utf8_bytes(b.length().to_string()))
w.write_u8(b':')
w.write_bytes(b)
}
BList(items) => {
w.write_u8(b'l')
for item in items {
encode_bval_into(w, item)
}
w.write_u8(b'e')
}
BDict(entries) => {
w.write_u8(b'd')
let sorted : Array[(Bytes, BVal)] = Array(capacity=entries.length())
for e in entries {
sorted.push(e)
}
sorted.sort_by(fn(a, b) { cmp_bytes_lex(a.0, b.0) })
for e in sorted {
encode_bval_into(w, BBytes(e.0))
encode_bval_into(w, e.1)
}
w.write_u8(b'e')
}
}
}
///|
/// Encodes a `BVal` into canonical sorted Bencode bytes.
pub fn bencode_encode(val : BVal) -> Bytes {
let w = @encoding.Writer::new(capacity=64)
encode_bval_into(w, val)
w.to_bytes()
}
///|
fn decode_int_slice(
data : Bytes,
start : Int32,
end : Int32,
allow_negative~ : Bool = true,
) -> Int64 raise BtError {
if start >= end {
raise InvalidBencode("empty integer field")
}
let mut neg = false
let mut idx = start
if data[idx] == b'-' {
if !allow_negative {
raise InvalidBencode("negative length not allowed")
}
neg = true
idx += 1
if idx >= end {
raise InvalidBencode("dangling minus sign")
}
if data[idx] == b'0' {
raise InvalidBencode("negative zero or leading zero after minus")
}
} else if end - idx > 1 && data[idx] == b'0' {
raise InvalidBencode("leading zero in integer")
}
let mut acc = 0L
while idx < end {
let b = data[idx].to_int()
if b < 48 || b > 57 {
raise InvalidBencode("non-digit byte in integer: \{b}")
}
acc = acc * 10L + (b - 48).to_int64()
idx += 1
}
if neg {
-acc
} else {
acc
}
}
///|
fn find_byte(data : Bytes, target : Byte, start : Int32) -> Int32? {
for i = start; i < data.length(); i = i + 1 {
if data[i] == target {
return Some(i)
}
}
None
}
///|
fn decode_bval_at(
data : Bytes,
pos : Int32,
depth : Int32,
) -> (BVal, Int32) raise BtError {
if depth > 64 {
raise InvalidBencode("bencode nesting depth exceeded")
}
if pos >= data.length() {
raise InvalidBencode("unexpected EOF")
}
let tag = data[pos]
if tag == b'i' {
let end_pos = match find_byte(data, b'e', pos + 1) {
Some(e) => e
None => raise InvalidBencode("unterminated integer")
}
let val = decode_int_slice(data, pos + 1, end_pos)
return (BInt(val), end_pos + 1)
}
if tag == b'l' {
let items : Array[BVal] = []
let mut cur = pos + 1
while true {
if cur >= data.length() {
raise InvalidBencode("unterminated list")
}
if data[cur] == b'e' {
return (BList(items), cur + 1)
}
let (item, next_pos) = decode_bval_at(data, cur, depth + 1)
items.push(item)
cur = next_pos
}
}
if tag == b'd' {
let entries : Array[(Bytes, BVal)] = []
let mut cur = pos + 1
while true {
if cur >= data.length() {
raise InvalidBencode("unterminated dictionary")
}
if data[cur] == b'e' {
return (BDict(entries), cur + 1)
}
let (kval, after_key) = decode_bval_at(data, cur, depth + 1)
let key_bytes = match kval {
BBytes(kb) => kb
_ => raise InvalidBencode("dictionary key must be byte string")
}
let (vval, after_val) = decode_bval_at(data, after_key, depth + 1)
entries.push((key_bytes, vval))
cur = after_val
}
}
if tag.to_int() >= 48 && tag.to_int() <= 57 {
let colon = match find_byte(data, b':', pos) {
Some(c) => c
None => raise InvalidBencode("missing ':' in byte string")
}
let len64 = decode_int_slice(data, pos, colon, allow_negative=false)
if len64 < 0L || len64 > 33554432L {
raise InvalidBencode("invalid byte string length: \{len64}")
}
let slen = len64.to_int()
let data_start = colon + 1
if data_start + slen > data.length() {
raise InvalidBencode("truncated byte string")
}
let raw = data[data_start:data_start + slen].to_owned()
return (BBytes(raw), data_start + slen)
}
raise InvalidBencode("unexpected bencode tag byte: \{tag.to_int()}")
}
///|
/// Decodes one Bencode value starting at `start`, returning `(value, next_offset)`.
pub fn bencode_decode_prefix(
data : Bytes,
start~ : Int32 = 0,
) -> (BVal, Int32) raise BtError {
decode_bval_at(data, start, 0)
}
///|
/// Decodes a complete standalone Bencode value, rejecting trailing garbage bytes.
pub fn bencode_decode(data : Bytes) -> BVal raise BtError {
let (val, next_pos) = decode_bval_at(data, 0, 0)
if next_pos != data.length() {
raise InvalidBencode(
"trailing bytes after bencode root: \{data.length() - next_pos}",
)
}
val
}
///|
/// Returns the value for ASCII `key` inside a `BDict`.
pub fn bdict_get(val : BVal, key : String) -> BVal? {
let kb = @encoding.string_to_utf8_bytes(key)
match val {
BDict(entries) => {
for e in entries {
if @crypto.ct_eq(e.0, kb) {
return Some(e.1)
}
}
None
}
_ => None
}
}
///|
pub fn bdict_get_bytes(val : BVal, key : String) -> Bytes? {
match bdict_get(val, key) {
Some(BBytes(b)) => Some(b)
_ => None
}
}
///|
pub fn bdict_get_string(val : BVal, key : String) -> String? {
match bdict_get_bytes(val, key) {
Some(b) => Some(@encoding.utf8_bytes_to_string(b)) catch { _ => None }
None => None
}
}
///|
pub fn bdict_get_int(val : BVal, key : String) -> Int64? {
match bdict_get(val, key) {
Some(BInt(n)) => Some(n)
_ => None
}
}
///|
/// Locates and returns the exact raw Bencode byte slice of the top-level `"info"`
/// dictionary from `.torrent` bytes, guaranteeing a bit-exact SHA-1 `info_hash`.
pub fn extract_info_raw(torrent_bytes : Bytes) -> Bytes raise BtError {
if torrent_bytes.length() == 0 || torrent_bytes[0] != b'd' {
raise InvalidMetainfo("torrent root must be a Bencode dictionary")
}
let mut cur = 1
while cur < torrent_bytes.length() {
if torrent_bytes[cur] == b'e' {
raise InvalidMetainfo("torrent dictionary missing 'info' key")
}
let (kval, val_start) = decode_bval_at(torrent_bytes, cur, 0)
let key_bytes = match kval {
BBytes(kb) => kb
_ => raise InvalidMetainfo("top-level torrent key must be bytes")
}
let (_vval, val_end) = decode_bval_at(torrent_bytes, val_start, 0)
if key_bytes == b"info" {
return torrent_bytes[val_start:val_end].to_owned()
}
cur = val_end
}
raise InvalidMetainfo("unterminated top-level torrent dictionary")
}
+269
View File
@@ -0,0 +1,269 @@
///|
test "Bencode encode/decode canonical sorting and raw info slice extraction" {
let val : @bittorrent.BVal = BDict([
(b"z", BInt(-42L)),
(b"a", BList([BBytes(b"hi"), BInt(0L), BBytes(b"")])),
])
let enc = @bittorrent.bencode_encode(val)
assert_eq(enc, b"d1:al2:hii0e0:e1:zi-42ee")
// Keys are sorted lexicographically in encoded output: 1:a before 1:z
let expected : @bittorrent.BVal = BDict([
(b"a", BList([BBytes(b"hi"), BInt(0L), BBytes(b"")])),
(b"z", BInt(-42L)),
])
assert_eq(@bittorrent.bencode_decode(enc), expected)
assert_eq(@bittorrent.bencode_encode(val), b"d1:al2:hii0e0:e1:zi-42ee")
assert_eq(enc, b"d1:al2:hii0e0:e1:zi-42ee")
// Prefix decode leaves trailing raw slice intact (BEP 9 ut_metadata)
let combined = b"d8:msg_typei1e5:piecei0eeRAW_SLICE"
let (hdr, next_off) = @bittorrent.bencode_decode_prefix(combined)
assert_eq(@bittorrent.bdict_get_int(hdr, "msg_type"), Some(1L))
assert_eq(combined[next_off:].to_owned(), b"RAW_SLICE")
}
///|
test "Metainfo parsing, path traversal rejection, and magnet hex/base32 links" {
let data = b"Hello I2P BitTorrent world!"
let phash = @crypto.sha1(data)
let raw_info = @bittorrent.bencode_encode(
BDict([
(b"length", BInt(data.length().to_int64())),
(b"name", BBytes(b"hello.txt")),
(b"piece length", BInt(16384L)),
(b"pieces", BBytes(phash)),
]),
)
let torrent = @bittorrent.bencode_encode(
BDict([
(b"announce", BBytes(b"http://tracker.insulaocculta.i2p/a")),
(
b"announce-list",
BList([BList([BBytes(b"http://opentracker.dg2.i2p/a")])]),
),
(
b"info",
BDict([
(b"length", BInt(data.length().to_int64())),
(b"name", BBytes(b"hello.txt")),
(b"piece length", BInt(16384L)),
(b"pieces", BBytes(phash)),
]),
),
]),
)
let meta = @bittorrent.parse_torrent(torrent)
assert_eq(meta.info_hash, @crypto.sha1(raw_info))
assert_eq(meta.name, "hello.txt")
assert_eq(meta.total_length, 27L)
assert_eq(meta.files.length(), 1)
assert_eq(meta.files[0].path, ["hello.txt"])
assert_eq(meta.trackers.length(), 2)
// Reject path traversal segments in multi-file info dictionary
let evil_info = @bittorrent.bencode_encode(
BDict([
(
b"files",
BList([
BDict([
(b"length", BInt(5L)),
(b"path", BList([BBytes(b".."), BBytes(b"etc"), BBytes(b"passwd")])),
]),
]),
),
(b"name", BBytes(b"bad")),
(b"piece length", BInt(16384L)),
(b"pieces", BBytes(@crypto.sha1(b"12345"))),
]),
)
let mut rejected = false
let _ = @bittorrent.parse_info_dict(evil_info) catch {
_ => {
rejected = true
meta
}
}
assert_true(rejected)
// Hex & Base32 magnet links
let hex_ih = @encoding.hex_encode(meta.info_hash)
let m1 = @bittorrent.parse_magnet(
"magnet:?xt=urn:btih:\{hex_ih}&dn=hello+world.txt&tr=http%3A%2F%2Ftracker.insulaocculta.i2p%2Fa",
)
assert_eq(m1.info_hash, meta.info_hash)
assert_eq(m1.display_name, "hello world.txt")
assert_eq(m1.trackers, ["http://tracker.insulaocculta.i2p/a"])
let b32_ih = @encoding.base32_encode(meta.info_hash)
let m2 = @bittorrent.parse_magnet("magnet:?xt=urn:btih:\{b32_ih}")
assert_eq(m2.info_hash, meta.info_hash)
}
///|
test "Peer wire framing, BEP 10/9, i2p_pex, i2p_dht, and chunked I2P HTTP tracker" {
let ih = @crypto.sha1(b"ih-wire-test")
let pid = @crypto.sha1(b"peer-id-test")
let hs = @bittorrent.encode_handshake(ih, pid)
let (res, dih, dpid) = @bittorrent.decode_handshake(hs)
assert_eq(res[5], b'\x10')
assert_eq(dih, ih)
assert_eq(dpid, pid)
let stream_buf : Array[Byte] = []
let msgs : Array[@bittorrent.PeerMessage] = [
KeepAlive,
Unchoke,
Interested,
Have(7U),
Bitfield(b"\x80"),
Request(1, 0, 16384),
Piece(1, 0, b"payload-bytes"),
Extended(b'\x00', @bittorrent.encode_ext_handshake(metadata_size=Some(512))),
Extended(b'\x03', @bittorrent.encode_i2p_dht_ext(6881U, 6882U)),
]
for m in msgs {
let enc = @bittorrent.encode_peer_message(m)
for i = 0; i < enc.length(); i = i + 1 {
stream_buf.push(enc[i])
}
}
for expected in msgs {
assert_eq(@bittorrent.try_decode_peer_message(stream_buf), Some(expected))
}
assert_eq(@bittorrent.try_decode_peer_message(stream_buf), None)
// Extended handshake + i2p_dht + i2p_pex + ut_metadata
let rext = @bittorrent.decode_ext_handshake(
@bittorrent.encode_ext_handshake(metadata_size=Some(512)),
)
assert_eq(rext.i2p_pex_id, Some(b'\x01'))
assert_eq(rext.ut_metadata_id, Some(b'\x02'))
assert_eq(rext.i2p_dht_id, Some(b'\x03'))
assert_eq(rext.metadata_size, Some(512))
assert_eq(
@bittorrent.decode_i2p_dht_ext(@bittorrent.encode_i2p_dht_ext(6881U, 6882U)),
Some((6881U, 6882U)),
)
let h1 = @common.Hash::sha256(b"peer1")
let h2 = @common.Hash::sha256(b"peer2")
assert_eq(@bittorrent.decode_i2p_pex(@bittorrent.encode_i2p_pex([h1, h2])), [
h1, h2,
])
let md_raw = @bittorrent.encode_metadata_data(0, 128, b"INFO_SLICE")
assert_eq(
@bittorrent.decode_metadata_msg(md_raw),
MetaData(0, 128, b"INFO_SLICE"),
)
// Chunked I2P HTTP tracker response with 32B compact peer hashes
let compact_peers = @encoding.Writer::new(capacity=64)
compact_peers.write_bytes(h1.as_bytes())
compact_peers.write_bytes(h2.as_bytes())
let bbody = @bittorrent.bencode_encode(
BDict([
(b"complete", BInt(3L)),
(b"incomplete", BInt(1L)),
(b"interval", BInt(120L)),
(b"peers", BBytes(compact_peers.to_bytes())),
]),
)
let http_resp = "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n\{bbody.length().to_int64()}\r\n"
// Hex chunk size
let hex_len = bbody.length()
let mut hx = ""
if hex_len < 16 {
hx = "0"
}
let _ = http_resp
let chunked = @encoding.Writer::new()
chunked.write_bytes(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n")
// Compute hex digits of bbody.length()
let digits : Array[Char] = []
let mut n = hex_len
while n > 0 {
let d = n % 16
digits.push(
if d < 10 {
(48 + d).unsafe_to_char()
} else {
(97 + d - 10).unsafe_to_char()
},
)
n = n / 16
}
let hx_sb = StringBuilder()
for k = digits.length() - 1; k >= 0; k = k - 1 {
hx_sb.write_char(digits[k])
}
let _ = hx
chunked.write_bytes(
@encoding.string_to_utf8_bytes(hx_sb.to_string() + "\r\n"),
)
chunked.write_bytes(bbody)
chunked.write_bytes(b"\r\n0\r\n\r\n")
let tresp = @bittorrent.parse_http_tracker_response(chunked.to_bytes())
assert_eq(tresp.interval, 120)
assert_eq(tresp.complete, 3)
assert_eq(tresp.incomplete, 1)
assert_eq(tresp.peers, [h1, h2])
}
///|
test "I2P DHT Secure Node ID, 54B compact nodes, KRPC round-trips, and XOR routing" {
let dh_a = @common.Hash::sha256(b"node-a-dest")
let dh_b = @common.Hash::sha256(b"node-b-dest")
let dht_a = @bittorrent.I2pDht::new(
dh_a,
b"rand14bytes_aa",
b"secret-a",
query_port=6881U,
reply_port=6882U,
)
assert_true(@bittorrent.verify_i2p_dht_node_id(dht_a.local_id, dh_a, 6881U))
assert_true(!@bittorrent.verify_i2p_dht_node_id(dht_a.local_id, dh_a, 6889U))
let id_b = @bittorrent.make_i2p_dht_node_id(dh_b, 6881U, b"rand14bytes_bb")
assert_true(dht_a.upsert_node(id_b, dh_b, 6881U, 1000UL))
assert_eq(dht_a.nodes.length(), 1)
// Tampered Node ID must fail Secure Node ID check
assert_true(!dht_a.upsert_node(Bytes::make(20, b'\x77'), dh_b, 6881U, 1001UL))
// 54B compact node encode/decode round-trip
let nodes_blob = @bittorrent.encode_compact_nodes(dht_a.closest_nodes(id_b))
assert_eq(nodes_blob.length(), 54)
let decoded_nodes = @bittorrent.decode_compact_nodes(
nodes_blob,
now_ms=2000UL,
)
assert_eq(decoded_nodes.length(), 1)
assert_eq(decoded_nodes[0].node_id, id_b)
assert_eq(decoded_nodes[0].dest_hash, dh_b)
assert_eq(decoded_nodes[0].port, 6881U)
// KRPC queries & responses round-trip
let ih = @crypto.sha1(b"dht-swarm-hash")
let tok = dht_a.make_token(dh_b)
assert_true(dht_a.verify_token(dh_b, tok))
assert_true(!dht_a.verify_token(dh_a, tok))
let q_gp : @bittorrent.KrpcMessage = Query(
tx_id=b"t1",
sender_id=id_b,
kind=GetPeers(info_hash=ih),
)
assert_eq(@bittorrent.decode_krpc(@bittorrent.encode_krpc(q_gp)), q_gp)
dht_a.store_peer(ih, dh_b, 5000UL)
assert_eq(dht_a.get_peers_local(ih, 5001UL), [dh_b])
let r_gp : @bittorrent.KrpcMessage = Response(
tx_id=b"t1",
sender_id=dht_a.local_id,
nodes=nodes_blob,
values=[dh_b.as_bytes()],
token=Some(tok),
)
assert_eq(@bittorrent.decode_krpc(@bittorrent.encode_krpc(r_gp)), r_gp)
}
+619
View File
@@ -0,0 +1,619 @@
///|
/// Canonical Pure-MoonBit I2P BitTorrent DHT (BEP 5 adapted per I2P DHT specification):
/// - Secure Node IDs: first 4B = dest_hash[0..4], next 2B = dest_hash[4..6] ^ port_be16
/// - 54-byte compact nodes: 20B node_id || 32B dest_hash || 2B port_be16
/// - KRPC query/response/error codec & routing table with Kademlia XOR distance
///|
/// Builds a Secure I2P DHT 20-byte Node ID bound to `dest_hash` and `query_port`.
pub fn make_i2p_dht_node_id(
dest_hash : @common.Hash,
query_port : UInt32,
rand14 : Bytes,
) -> Bytes raise BtError {
if rand14.length() < 14 {
raise InvalidKrpc("rand14 must be at least 14 bytes")
}
let hb = dest_hash.as_bytes()
let out = FixedArray::make(20, b'\x00')
out[0] = hb[0]
out[1] = hb[1]
out[2] = hb[2]
out[3] = hb[3]
out[4] = (hb[4].to_int() ^ ((query_port.reinterpret_as_int() >> 8) & 0xFF)).to_byte()
out[5] = (hb[5].to_int() ^ (query_port.reinterpret_as_int() & 0xFF)).to_byte()
for i = 0; i < 14; i = i + 1 {
out[6 + i] = rand14[i]
}
Bytes::from_array(out)
}
///|
/// Verifies that `node_id` (20B) satisfies I2P DHT Secure Node ID rules for `(dest_hash, query_port)`.
pub fn verify_i2p_dht_node_id(
node_id : Bytes,
dest_hash : @common.Hash,
query_port : UInt32,
) -> Bool {
if node_id.length() != 20 {
return false
}
let hb = dest_hash.as_bytes()
let p_hi = (query_port.reinterpret_as_int() >> 8) & 0xFF
let p_lo = query_port.reinterpret_as_int() & 0xFF
node_id[0] == hb[0] &&
node_id[1] == hb[1] &&
node_id[2] == hb[2] &&
node_id[3] == hb[3] &&
node_id[4] == (hb[4].to_int() ^ p_hi).to_byte() &&
node_id[5] == (hb[5].to_int() ^ p_lo).to_byte()
}
///|
#derive(Eq, Debug)
pub(all) struct DhtNode {
node_id : Bytes // 20B
dest_hash : @common.Hash
port : UInt32
last_seen_ms : UInt64
}
///|
/// Encodes DHT nodes in canonical 54-byte I2P compact format (`20B id || 32B dest_hash || 2B port_be16`).
pub fn encode_compact_nodes(nodes : Array[DhtNode]) -> Bytes {
let w = @encoding.Writer::new(capacity=nodes.length() * 54)
for n in nodes {
if n.node_id.length() == 20 {
w.write_bytes(n.node_id)
w.write_bytes(n.dest_hash.as_bytes())
w.write_u16_be(n.port)
}
}
w.to_bytes()
}
///|
/// Decodes canonical 54-byte compact I2P DHT nodes (`nodes` dictionary field).
pub fn decode_compact_nodes(
blob : Bytes,
now_ms~ : UInt64 = 0UL,
) -> Array[DhtNode] raise BtError {
if blob.length() % 54 != 0 {
raise InvalidKrpc(
"compact I2P DHT nodes length must be a multiple of 54, got \{blob.length()}",
)
}
let count = blob.length() / 54
let out : Array[DhtNode] = Array(capacity=count)
for i = 0; i < count; i = i + 1 {
let off = i * 54
let node_id = blob[off:off + 20].to_owned()
let dh = @common.Hash::from_bytes(blob[off + 20:off + 52].to_owned()) catch {
e => raise Common(e)
}
let port = ((blob[off + 52].to_int() << 8) | blob[off + 53].to_int()).reinterpret_as_uint()
if port > 0U {
out.push({ node_id, dest_hash: dh, port, last_seen_ms: now_ms, })
}
}
out
}
///|
/// Computes 20-byte Kademlia XOR distance between `a` and `b`.
pub fn xor_distance_20(a : Bytes, b : Bytes) -> Bytes {
let out = FixedArray::make(20, b'\x00')
let n = if a.length() < b.length() { a.length() } else { b.length() }
let len = if n < 20 { n } else { 20 }
for i = 0; i < len; i = i + 1 {
out[i] = (a[i].to_int() ^ b[i].to_int()).to_byte()
}
Bytes::from_array(out)
}
///|
pub fn cmp_distance_20(a : Bytes, b : Bytes) -> Int32 {
cmp_bytes_lex(a, b)
}
///|
#derive(Eq, Debug)
pub(all) enum KrpcQueryKind {
Ping
FindNode(target~ : Bytes)
GetPeers(info_hash~ : Bytes)
AnnouncePeer(
info_hash~ : Bytes,
port~ : UInt32,
token~ : Bytes,
implied_port~ : Bool
)
}
///|
#derive(Eq, Debug)
pub(all) enum KrpcMessage {
Query(tx_id~ : Bytes, sender_id~ : Bytes, kind~ : KrpcQueryKind)
Response(
tx_id~ : Bytes,
sender_id~ : Bytes,
nodes~ : Bytes,
values~ : Array[Bytes],
token~ : Bytes?
)
ErrorMsg(tx_id~ : Bytes, code~ : Int64, msg~ : String)
}
///|
/// Encodes a KRPC message into Bencode bytes.
pub fn encode_krpc(msg : KrpcMessage) -> Bytes {
match msg {
Query(tx_id~, sender_id~, kind~) =>
match kind {
Ping =>
bencode_encode(
BDict([
(b"a", BDict([(b"id", BBytes(sender_id))])),
(b"q", BBytes(b"ping")),
(b"t", BBytes(tx_id)),
(b"y", BBytes(b"q")),
]),
)
FindNode(target~) =>
bencode_encode(
BDict([
(
b"a",
BDict([(b"id", BBytes(sender_id)), (b"target", BBytes(target))]),
),
(b"q", BBytes(b"find_node")),
(b"t", BBytes(tx_id)),
(b"y", BBytes(b"q")),
]),
)
GetPeers(info_hash~) =>
bencode_encode(
BDict([
(
b"a",
BDict([
(b"id", BBytes(sender_id)),
(b"info_hash", BBytes(info_hash)),
]),
),
(b"q", BBytes(b"get_peers")),
(b"t", BBytes(tx_id)),
(b"y", BBytes(b"q")),
]),
)
AnnouncePeer(info_hash~, port~, token~, implied_port~) => {
let args : Array[(Bytes, BVal)] = [
(b"id", BBytes(sender_id)),
(b"info_hash", BBytes(info_hash)),
(b"port", BInt(port.to_int64())),
(b"token", BBytes(token)),
]
if implied_port {
args.push((b"implied_port", BInt(1L)))
}
bencode_encode(
BDict([
(b"a", BDict(args)),
(b"q", BBytes(b"announce_peer")),
(b"t", BBytes(tx_id)),
(b"y", BBytes(b"q")),
]),
)
}
}
Response(tx_id~, sender_id~, nodes~, values~, token~) => {
let r_entries : Array[(Bytes, BVal)] = [(b"id", BBytes(sender_id))]
if nodes.length() > 0 {
r_entries.push((b"nodes", BBytes(nodes)))
}
if values.length() > 0 {
let vlist : Array[BVal] = Array(capacity=values.length())
for v in values {
vlist.push(BBytes(v))
}
r_entries.push((b"values", BList(vlist)))
}
match token {
Some(tk) => r_entries.push((b"token", BBytes(tk)))
None => ()
}
bencode_encode(
BDict([
(b"r", BDict(r_entries)),
(b"t", BBytes(tx_id)),
(b"y", BBytes(b"r")),
]),
)
}
ErrorMsg(tx_id~, code~, msg~) =>
bencode_encode(
BDict([
(
b"e",
BList([BInt(code), BBytes(@encoding.string_to_utf8_bytes(msg))]),
),
(b"t", BBytes(tx_id)),
(b"y", BBytes(b"e")),
]),
)
}
}
///|
/// Decodes a Bencoded KRPC packet.
pub fn decode_krpc(data : Bytes) -> KrpcMessage raise BtError {
let root = bencode_decode(data)
let tx_id = match bdict_get_bytes(root, "t") {
Some(t) => t
None => raise InvalidKrpc("KRPC packet missing 't' transaction id")
}
let y = match bdict_get_string(root, "y") {
Some(yv) => yv
None => raise InvalidKrpc("KRPC packet missing 'y' message type")
}
if y == "q" {
let q = match bdict_get_string(root, "q") {
Some(qv) => qv
None => raise InvalidKrpc("KRPC query missing 'q'")
}
let a = match bdict_get(root, "a") {
Some(av) => av
None => raise InvalidKrpc("KRPC query missing 'a'")
}
let sender_id = match bdict_get_bytes(a, "id") {
Some(id) if id.length() == 20 => id
_ => raise InvalidKrpc("KRPC query missing valid 20B 'id'")
}
if q == "ping" {
return Query(tx_id~, sender_id~, kind=Ping)
}
if q == "find_node" {
let target = match bdict_get_bytes(a, "target") {
Some(t) if t.length() == 20 => t
_ => raise InvalidKrpc("find_node missing valid 20B 'target'")
}
return Query(tx_id~, sender_id~, kind=FindNode(target~))
}
if q == "get_peers" {
let info_hash = match bdict_get_bytes(a, "info_hash") {
Some(ih) if ih.length() == 20 => ih
_ => raise InvalidKrpc("get_peers missing valid 20B 'info_hash'")
}
return Query(tx_id~, sender_id~, kind=GetPeers(info_hash~))
}
if q == "announce_peer" {
let info_hash = match bdict_get_bytes(a, "info_hash") {
Some(ih) if ih.length() == 20 => ih
_ => raise InvalidKrpc("announce_peer missing valid 20B 'info_hash'")
}
let port = match bdict_get_int(a, "port") {
Some(p) if p > 0L && p <= 65535L => p.to_int().reinterpret_as_uint()
_ => 6881U
}
let implied = match bdict_get_int(a, "implied_port") {
Some(v) => v != 0L
None => false
}
let token = match bdict_get_bytes(a, "token") {
Some(tk) => tk
None => raise InvalidKrpc("announce_peer missing 'token'")
}
return Query(
tx_id~,
sender_id~,
kind=AnnouncePeer(info_hash~, port~, token~, implied_port=implied),
)
}
raise InvalidKrpc("unsupported KRPC query '\{q}'")
}
if y == "r" {
let r = match bdict_get(root, "r") {
Some(rv) => rv
None => raise InvalidKrpc("KRPC response missing 'r'")
}
let sender_id = match bdict_get_bytes(r, "id") {
Some(id) if id.length() == 20 => id
_ => raise InvalidKrpc("KRPC response missing valid 20B 'id'")
}
let nodes = match bdict_get_bytes(r, "nodes") {
Some(n) => n
None => b""
}
let values : Array[Bytes] = []
match bdict_get(r, "values") {
Some(BList(vlist)) =>
for item in vlist {
match item {
BBytes(vb) => values.push(vb)
_ => ()
}
}
_ => ()
}
let token = bdict_get_bytes(r, "token")
return Response(tx_id~, sender_id~, nodes~, values~, token~)
}
if y == "e" {
match bdict_get(root, "e") {
Some(BList(elist)) if elist.length() >= 2 => {
let code = match elist[0] {
BInt(c) => c
_ => 201L
}
let msg = match elist[1] {
BBytes(mb) =>
@encoding.utf8_bytes_to_string(mb) catch {
_ => "krpc error"
}
_ => "krpc error"
}
return ErrorMsg(tx_id~, code~, msg~)
}
_ => return ErrorMsg(tx_id~, code=201L, msg="malformed krpc error")
}
}
raise InvalidKrpc("unknown KRPC message type '\{y}'")
}
///|
#derive(Eq, Debug)
pub(all) struct DhtPendingTx {
tx_id : Bytes
kind : String // "ping" | "find_node" | "get_peers" | "announce_peer"
info_hash : Bytes?
dest_hash : @common.Hash
port : UInt32
sent_ms : UInt64
}
///|
priv struct DhtPeerEntry {
peer_hash : @common.Hash
expires_ms : UInt64
}
///|
/// Pure-MoonBit I2P Kademlia DHT state machine (routing table, token secret, peer store).
pub struct I2pDht {
local_id : Bytes // 20B Secure I2P Node ID
local_dest_hash : @common.Hash
query_port : UInt32
reply_port : UInt32
priv secret : Bytes
nodes : Array[DhtNode]
pending_txs : Array[DhtPendingTx]
priv peer_store : Array[(Bytes, Array[DhtPeerEntry])] // (info_hash_20B, peers)
mut next_tx_seq : UInt32
mut queries_sent : UInt64
mut responses_recv : UInt64
mut queries_recv : UInt64
mut peers_discovered : UInt64
}
///|
pub fn I2pDht::new(
local_dest_hash : @common.Hash,
rand14 : Bytes,
secret : Bytes,
query_port~ : UInt32 = 6881U,
reply_port~ : UInt32 = 6882U,
) -> I2pDht raise BtError {
let local_id = make_i2p_dht_node_id(local_dest_hash, query_port, rand14)
{
local_id,
local_dest_hash,
query_port,
reply_port,
secret,
nodes: [],
pending_txs: [],
peer_store: [],
next_tx_seq: 1U,
queries_sent: 0UL,
responses_recv: 0UL,
queries_recv: 0UL,
peers_discovered: 0UL,
}
}
///|
pub fn I2pDht::alloc_tx_id(self : I2pDht) -> Bytes {
let id = self.next_tx_seq
self.next_tx_seq = id + 1U
let w = @encoding.Writer::new(capacity=4)
w.write_u32_be(id)
w.to_bytes()
}
///|
pub fn I2pDht::register_pending_tx(
self : I2pDht,
tx_id : Bytes,
kind : String,
dest_hash : @common.Hash,
port : UInt32,
sent_ms : UInt64,
info_hash~ : Bytes? = None,
) -> Unit {
while self.pending_txs.length() >= 256 {
let _ = self.pending_txs.remove(0)
}
self.pending_txs.push({ tx_id, kind, info_hash, dest_hash, port, sent_ms, })
self.queries_sent += 1UL
}
///|
pub fn I2pDht::take_pending_tx(self : I2pDht, tx_id : Bytes) -> DhtPendingTx? {
for i = 0; i < self.pending_txs.length(); i = i + 1 {
if @crypto.ct_eq(self.pending_txs[i].tx_id, tx_id) {
self.responses_recv += 1UL
return Some(self.pending_txs.remove(i))
}
}
None
}
///|
pub fn I2pDht::record_query_recv(self : I2pDht) -> Unit {
self.queries_recv += 1UL
}
///|
pub fn I2pDht::record_peers_discovered(self : I2pDht, count : UInt64) -> Unit {
self.peers_discovered += count
}
///|
pub fn I2pDht::prune_expired_txs(self : I2pDht, now_ms : UInt64) -> Unit {
let mut i = 0
while i < self.pending_txs.length() {
if now_ms > self.pending_txs[i].sent_ms + 30000UL {
let _ = self.pending_txs.remove(i)
} else {
i += 1
}
}
}
///|
/// Inserts or refreshes a remote DHT node, enforcing Secure I2P Node ID verification by default.
pub fn I2pDht::upsert_node(
self : I2pDht,
node_id : Bytes,
dest_hash : @common.Hash,
port : UInt32,
now_ms : UInt64,
verify_secure_id~ : Bool = true,
) -> Bool {
if node_id.length() != 20 || port == 0U {
return false
}
if dest_hash == self.local_dest_hash {
return false
}
if verify_secure_id && !verify_i2p_dht_node_id(node_id, dest_hash, port) {
return false
}
for i = 0; i < self.nodes.length(); i = i + 1 {
if self.nodes[i].dest_hash == dest_hash && self.nodes[i].port == port {
self.nodes[i] = { node_id, dest_hash, port, last_seen_ms: now_ms, }
return true
}
}
if self.nodes.length() >= 160 {
// Evict oldest seen node outside top close neighborhood
let mut oldest_idx = 0
let mut oldest_ms = self.nodes[0].last_seen_ms
for i = 1; i < self.nodes.length(); i = i + 1 {
if self.nodes[i].last_seen_ms < oldest_ms {
oldest_ms = self.nodes[i].last_seen_ms
oldest_idx = i
}
}
let _ = self.nodes.remove(oldest_idx)
}
self.nodes.push({ node_id, dest_hash, port, last_seen_ms: now_ms, })
true
}
///|
/// Returns up to `limit` known DHT nodes sorted closest by 20-byte XOR distance to `target_20`.
pub fn I2pDht::closest_nodes(
self : I2pDht,
target_20 : Bytes,
limit~ : Int32 = 8,
) -> Array[DhtNode] {
let pairs : Array[(Bytes, DhtNode)] = Array(capacity=self.nodes.length())
for n in self.nodes {
pairs.push((xor_distance_20(n.node_id, target_20), n))
}
pairs.sort_by(fn(a, b) { cmp_distance_20(a.0, b.0) })
let out : Array[DhtNode] = []
let cap = if limit < pairs.length() { limit } else { pairs.length() }
for i = 0; i < cap; i = i + 1 {
out.push(pairs[i].1)
}
out
}
///|
pub fn I2pDht::make_token(self : I2pDht, sender_hash : @common.Hash) -> Bytes {
let w = @encoding.Writer::new(capacity=self.secret.length() + 32)
w.write_bytes(self.secret)
w.write_bytes(sender_hash.as_bytes())
@crypto.sha256(w.to_bytes())[:8].to_owned()
}
///|
pub fn I2pDht::verify_token(
self : I2pDht,
sender_hash : @common.Hash,
token : Bytes,
) -> Bool {
@crypto.ct_eq(self.make_token(sender_hash), token)
}
///|
pub fn I2pDht::store_peer(
self : I2pDht,
info_hash : Bytes,
peer_hash : @common.Hash,
now_ms : UInt64,
) -> Unit {
if info_hash.length() != 20 {
return
}
let expires_ms = now_ms + 1800000UL // 30 minutes
for entry in self.peer_store {
if @crypto.ct_eq(entry.0, info_hash) {
let mut updated = false
for j = 0; j < entry.1.length(); j = j + 1 {
if entry.1[j].peer_hash == peer_hash {
entry.1[j] = { peer_hash, expires_ms, }
updated = true
break
}
}
if !updated {
while entry.1.length() >= 64 {
let _ = entry.1.remove(0)
}
entry.1.push({ peer_hash, expires_ms, })
}
return
}
}
while self.peer_store.length() >= 128 {
let _ = self.peer_store.remove(0)
}
self.peer_store.push((info_hash, [{ peer_hash, expires_ms, }]))
}
///|
pub fn I2pDht::get_peers_local(
self : I2pDht,
info_hash : Bytes,
now_ms : UInt64,
) -> Array[@common.Hash] {
let out : Array[@common.Hash] = []
for entry in self.peer_store {
if @crypto.ct_eq(entry.0, info_hash) {
let mut j = 0
while j < entry.1.length() {
if entry.1[j].expires_ms <= now_ms {
let _ = entry.1.remove(j)
} else {
out.push(entry.1[j].peer_hash)
j += 1
}
}
break
}
}
out
}
+408
View File
@@ -0,0 +1,408 @@
///|
/// Pure-MoonBit BitTorrent Metainfo (`.torrent` BEP 3/12) and Magnet (BEP 9) parser
/// with path traversal sanitization and RFC 3986 percent-encoding helpers.
///|
#derive(Eq, Debug)
pub(all) struct TorrentFile {
path : Array[String]
length : Int64
}
///|
#derive(Eq, Debug)
pub(all) struct Metainfo {
info_hash : Bytes // 20-byte SHA-1
name : String
piece_length : Int64
piece_hashes : Array[Bytes]
total_length : Int64
files : Array[TorrentFile]
trackers : Array[String]
raw_info : Bytes
}
///|
#derive(Eq, Debug)
pub(all) struct MagnetLink {
info_hash : Bytes // 20-byte SHA-1
display_name : String
trackers : Array[String]
dht_nodes : Array[(String, UInt32)]
}
///|
fn check_safe_path_segment(seg : String) -> String raise BtError {
if seg.length() == 0 || seg == "." || seg == ".." {
raise InvalidMetainfo("unsafe path segment '\{seg}'")
}
for ch in seg {
if ch == '/' || ch == '\\' || ch.to_int() < 0x20 {
raise InvalidMetainfo(
"illegal character in torrent path segment '\{seg}'",
)
}
}
seg
}
///|
fn sanitize_path_segments(segs : Array[String]) -> Array[String] raise BtError {
if segs.length() == 0 {
raise InvalidMetainfo("empty torrent file path")
}
let out : Array[String] = Array(capacity=segs.length())
for s in segs {
out.push(check_safe_path_segment(s))
}
out
}
///|
fn append_unique_str(list : Array[String], val : String) -> Unit {
if val.length() == 0 {
return
}
for item in list {
if item == val {
return
}
}
list.push(val)
}
///|
/// Parses the raw `"info"` dictionary bytes (`BEP 9` / `.torrent` `"info"` value)
/// into a validated `Metainfo`.
pub fn parse_info_dict(
raw_info : Bytes,
trackers~ : Array[String] = [],
) -> Metainfo raise BtError {
let info = bencode_decode(raw_info)
if !(info is BDict(_)) {
raise InvalidMetainfo("info value must be a dictionary")
}
let raw_name = match bdict_get_string(info, "name") {
Some(n) => n
None => raise InvalidMetainfo("info dictionary missing UTF-8 'name'")
}
let name = check_safe_path_segment(raw_name)
let piece_length = match bdict_get_int(info, "piece length") {
Some(pl) if pl > 0L => pl
_ => raise InvalidMetainfo("info dictionary missing valid 'piece length'")
}
let pieces_blob = match bdict_get_bytes(info, "pieces") {
Some(pb) if pb.length() > 0 && pb.length() % 20 == 0 => pb
_ => raise InvalidMetainfo("info dictionary has invalid 'pieces' blob")
}
let num_pieces = pieces_blob.length() / 20
let piece_hashes : Array[Bytes] = Array(capacity=num_pieces)
for i = 0; i < num_pieces; i = i + 1 {
piece_hashes.push(pieces_blob[i * 20:(i + 1) * 20].to_owned())
}
let files : Array[TorrentFile] = []
let mut total_length = 0L
match bdict_get(info, "files") {
Some(BList(flist)) => {
if flist.length() == 0 {
raise InvalidMetainfo("multi-file torrent has empty 'files' list")
}
for entry in flist {
let flen = match bdict_get_int(entry, "length") {
Some(l) if l >= 0L => l
_ => raise InvalidMetainfo("file entry missing valid 'length'")
}
let segs : Array[String] = [name]
match bdict_get(entry, "path") {
Some(BList(plist)) => {
if plist.length() == 0 {
raise InvalidMetainfo("file entry has empty 'path'")
}
for pitem in plist {
match pitem {
BBytes(pb) => {
let ps = @encoding.utf8_bytes_to_string(pb) catch {
e => raise Encoding(e)
}
segs.push(ps)
}
_ => raise InvalidMetainfo("non-string element in file 'path'")
}
}
}
_ => raise InvalidMetainfo("file entry missing 'path' list")
}
let clean = sanitize_path_segments(segs)
files.push({ path: clean, length: flen, })
total_length = total_length + flen
}
}
Some(_) => raise InvalidMetainfo("'files' entry must be a list")
None => {
let flen = match bdict_get_int(info, "length") {
Some(l) if l >= 0L => l
_ => raise InvalidMetainfo("single-file torrent missing valid 'length'")
}
files.push({ path: [name], length: flen, })
total_length = flen
}
}
if total_length > 0L {
let expected_pieces = (total_length + piece_length - 1L) / piece_length
if expected_pieces != num_pieces.to_int64() {
raise InvalidMetainfo(
"piece hash count \{num_pieces} does not match length \{total_length} / piece_length \{piece_length}",
)
}
}
let clean_trackers : Array[String] = []
for tr in trackers {
append_unique_str(clean_trackers, tr)
}
{
info_hash: @crypto.sha1(raw_info),
name,
piece_length,
piece_hashes,
total_length,
files,
trackers: clean_trackers,
raw_info,
}
}
///|
/// Parses a full `.torrent` file (BEP 3 + BEP 12 `announce-list`) and validates all fields.
pub fn parse_torrent(torrent_bytes : Bytes) -> Metainfo raise BtError {
let root = bencode_decode(torrent_bytes)
let trackers : Array[String] = []
match bdict_get_string(root, "announce") {
Some(tr) => append_unique_str(trackers, tr.trim().to_owned())
None => ()
}
match bdict_get(root, "announce-list") {
Some(BList(tiers)) =>
for tier in tiers {
match tier {
BList(urls) =>
for u in urls {
match u {
BBytes(ub) => {
let us = @encoding.utf8_bytes_to_string(ub) catch { _ => "" }
append_unique_str(trackers, us.trim().to_owned())
}
_ => ()
}
}
_ => ()
}
}
_ => ()
}
let raw_info = extract_info_raw(torrent_bytes)
parse_info_dict(raw_info, trackers~)
}
///|
fn bt_hex_nibble(c : Int32) -> Int32 {
if c >= 48 && c <= 57 {
c - 48
} else if c >= 65 && c <= 70 {
c - 55
} else if c >= 97 && c <= 102 {
c - 87
} else {
-1
}
}
///|
fn percent_decode_param(s : String, plus_as_space~ : Bool = true) -> String {
let out : Array[Byte] = []
let raw = @encoding.string_to_utf8_bytes(s)
let mut i = 0
while i < raw.length() {
let b = raw[i]
if plus_as_space && b == b'+' {
out.push(b' ')
i += 1
} else if b == b'%' && i + 2 < raw.length() {
let hi = bt_hex_nibble(raw[i + 1].to_int())
let lo = bt_hex_nibble(raw[i + 2].to_int())
if hi >= 0 && lo >= 0 {
out.push(((hi << 4) | lo).to_byte())
i += 3
continue
}
out.push(b)
i += 1
} else {
out.push(b)
i += 1
}
}
@encoding.utf8_bytes_to_string(Bytes::from_array(out)) catch {
_ => s
}
}
///|
fn parse_u32_port_str(s : String) -> UInt32? {
if s.length() == 0 {
return None
}
let mut val = 0U
for ch in s {
if ch < '0' || ch > '9' {
return None
}
val = val * 10U + (ch.to_int() - '0'.to_int()).reinterpret_as_uint()
if val > 65535U {
return None
}
}
if val == 0U {
None
} else {
Some(val)
}
}
///|
fn parse_host_port_pair(spec : String) -> (String, UInt32)? {
let mut colon = -1
for i = 0; i < spec.length(); i = i + 1 {
if spec[i] == ':' {
colon = i
}
}
if colon <= 0 || colon + 1 >= spec.length() {
return None
}
let host = spec[:colon].to_owned().trim().to_owned()
let port_s = spec[colon + 1:].to_owned().trim().to_owned()
match parse_u32_port_str(port_s) {
Some(p) if host.length() > 0 => Some((host, p))
_ => None
}
}
///|
/// Parses a BitTorrent `magnet:?xt=urn:btih:...` URI (40-char hex or 32-char Base32 info_hash).
pub fn parse_magnet(uri : String) -> MagnetLink raise BtError {
let trimmed = uri.trim().to_owned()
if !trimmed.to_lower().has_prefix("magnet:?") {
raise InvalidMagnet("URI must start with 'magnet:?'")
}
let query = trimmed[8:].to_owned()
let mut info_hash : Bytes? = None
let mut display_name = ""
let trackers : Array[String] = []
let dht_nodes : Array[(String, UInt32)] = []
for part_view in query.split("&") {
let part = part_view.to_owned()
if part.length() == 0 {
continue
}
let mut eq = -1
for i = 0; i < part.length(); i = i + 1 {
if part[i] == '=' {
eq = i
break
}
}
if eq <= 0 {
continue
}
let key = part[:eq].to_owned().to_lower()
let raw_val = part[eq + 1:].to_owned()
if key == "xt" {
let decoded = percent_decode_param(raw_val, plus_as_space=false)
let lower_xt = decoded.to_lower()
if lower_xt.has_prefix("urn:btih:") {
let hash_str = decoded[9:].to_owned()
let parsed = if hash_str.length() == 40 {
@encoding.hex_decode(hash_str) catch {
e => raise Encoding(e)
}
} else if hash_str.length() == 32 {
@encoding.base32_decode(hash_str) catch {
e => raise Encoding(e)
}
} else {
raise InvalidMagnet(
"unsupported btih hash length: \{hash_str.length()}",
)
}
if parsed.length() != 20 {
raise InvalidMagnet("decoded btih must be 20 bytes")
}
info_hash = Some(parsed)
}
} else if key == "dn" {
display_name = percent_decode_param(raw_val, plus_as_space=true)
} else if key == "tr" {
let tr = percent_decode_param(raw_val, plus_as_space=false)
.trim()
.to_owned()
append_unique_str(trackers, tr)
} else if key == "dht" || key == "x.pe" {
let val = percent_decode_param(raw_val, plus_as_space=false)
match parse_host_port_pair(val) {
Some(pair) => dht_nodes.push(pair)
None => ()
}
}
}
let ih = match info_hash {
Some(h) => h
None => raise InvalidMagnet("magnet URI missing xt=urn:btih:<hash>")
}
let name = if display_name.length() > 0 {
display_name
} else {
@encoding.hex_encode(ih)
}
{ info_hash: ih, display_name: name, trackers, dht_nodes, }
}
///|
fn hex_upper_char(n : Int32) -> Char {
if n < 10 {
(48 + n).unsafe_to_char()
} else {
(65 + n - 10).unsafe_to_char()
}
}
///|
fn is_rfc3986_unreserved(b : Byte) -> Bool {
let v = b.to_int()
(v >= 65 && v <= 90) ||
(v >= 97 && v <= 122) ||
(v >= 48 && v <= 57) ||
v == 45 || // '-'
v == 95 || // '_'
v == 46 || // '.'
v == 126 // '~'
}
///|
/// Percent-encodes raw bytes (such as `info_hash` / `peer_id`) for BitTorrent tracker GET queries.
pub fn url_encode_bytes(data : Bytes) -> String {
let sb = StringBuilder(size_hint=data.length() * 3)
for i = 0; i < data.length(); i = i + 1 {
let b = data[i]
if is_rfc3986_unreserved(b) {
sb.write_char(b.to_int().unsafe_to_char())
} else {
let v = b.to_int()
sb.write_char('%')
sb.write_char(hex_upper_char((v >> 4) & 0xF))
sb.write_char(hex_upper_char(v & 0xF))
}
}
sb.to_string()
}
+5
View File
@@ -0,0 +1,5 @@
import {
"experiments/moon_i2p/encoding",
"experiments/moon_i2p/crypto",
"experiments/moon_i2p/common",
}
+251
View File
@@ -0,0 +1,251 @@
// Generated using `moon info`, DON'T EDIT IT
package "experiments/moon_i2p/bittorrent"
import {
"experiments/moon_i2p/common",
"experiments/moon_i2p/encoding",
"moonbitlang/core/debug",
}
// Values
pub fn bdict_get(BVal, String) -> BVal?
pub fn bdict_get_bytes(BVal, String) -> Bytes?
pub fn bdict_get_int(BVal, String) -> Int64?
pub fn bdict_get_string(BVal, String) -> String?
pub fn bencode_decode(Bytes) -> BVal raise BtError
pub fn bencode_decode_prefix(Bytes, start? : Int32) -> (BVal, Int32) raise BtError
pub fn bencode_encode(BVal) -> Bytes
pub let bt_block_size : Int32
pub let bt_protocol_string : Bytes
pub fn build_http_announce_request(TrackerUrl, Bytes, Bytes, Int64, Int64, Int64, event? : String, local_dest_b64? : String) -> String
pub fn cmp_distance_20(Bytes, Bytes) -> Int32
pub fn decode_compact_nodes(Bytes, now_ms? : UInt64) -> Array[DhtNode] raise BtError
pub fn decode_ext_handshake(Bytes) -> RemoteExtensions raise BtError
pub fn decode_handshake(Bytes) -> (Bytes, Bytes, Bytes) raise BtError
pub fn decode_i2p_dht_ext(Bytes) -> (UInt32, UInt32)?
pub fn decode_i2p_pex(Bytes) -> Array[@common.Hash]
pub fn decode_krpc(Bytes) -> KrpcMessage raise BtError
pub fn decode_metadata_msg(Bytes) -> MetadataMsg raise BtError
pub fn encode_compact_nodes(Array[DhtNode]) -> Bytes
pub fn encode_ext_handshake(metadata_size? : Int32?) -> Bytes
pub fn encode_handshake(Bytes, Bytes) -> Bytes raise BtError
pub fn encode_i2p_dht_ext(UInt32, UInt32) -> Bytes
pub fn encode_i2p_pex(Array[@common.Hash]) -> Bytes
pub fn encode_krpc(KrpcMessage) -> Bytes
pub fn encode_metadata_data(Int32, Int32, Bytes) -> Bytes
pub fn encode_metadata_reject(Int32) -> Bytes
pub fn encode_metadata_request(Int32) -> Bytes
pub fn encode_peer_message(PeerMessage) -> Bytes
pub let ext_id_i2p_dht : Byte
pub let ext_id_pex : Byte
pub let ext_id_ut_metadata : Byte
pub fn extract_info_raw(Bytes) -> Bytes raise BtError
pub fn make_i2p_dht_node_id(@common.Hash, UInt32, Bytes) -> Bytes raise BtError
pub fn parse_http_tracker_response(Bytes) -> TrackerResponse raise BtError
pub fn parse_http_tracker_url(String) -> TrackerUrl?
pub fn parse_info_dict(Bytes, trackers? : Array[String]) -> Metainfo raise BtError
pub fn parse_magnet(String) -> MagnetLink raise BtError
pub fn parse_torrent(Bytes) -> Metainfo raise BtError
pub fn try_decode_peer_message(Array[Byte]) -> PeerMessage? raise BtError
pub fn url_encode_bytes(Bytes) -> String
pub fn verify_i2p_dht_node_id(Bytes, @common.Hash, UInt32) -> Bool
pub fn xor_distance_20(Bytes, Bytes) -> Bytes
// Errors
#derive(Eq, @debug.Debug)
pub suberror BtError {
InvalidBencode(String)
InvalidMetainfo(String)
InvalidMagnet(String)
InvalidWire(String)
InvalidKrpc(String)
Encoding(@encoding.EncodingError)
Common(@common.CommonError)
}
// Types and methods
#derive(Eq, @debug.Debug)
pub(all) enum BVal {
BInt(Int64)
BBytes(Bytes)
BList(Array[BVal])
BDict(Array[(Bytes, BVal)])
}
#derive(Eq, @debug.Debug)
pub(all) struct DhtNode {
node_id : Bytes
dest_hash : @common.Hash
port : UInt32
last_seen_ms : UInt64
}
#derive(Eq, @debug.Debug)
pub(all) struct DhtPendingTx {
tx_id : Bytes
kind : String
info_hash : Bytes?
dest_hash : @common.Hash
port : UInt32
sent_ms : UInt64
}
pub struct I2pDht {
local_id : Bytes
local_dest_hash : @common.Hash
query_port : UInt32
reply_port : UInt32
nodes : Array[DhtNode]
pending_txs : Array[DhtPendingTx]
mut next_tx_seq : UInt32
mut queries_sent : UInt64
mut responses_recv : UInt64
mut queries_recv : UInt64
mut peers_discovered : UInt64
// private fields
}
pub fn I2pDht::alloc_tx_id(Self) -> Bytes
pub fn I2pDht::closest_nodes(Self, Bytes, limit? : Int32) -> Array[DhtNode]
pub fn I2pDht::get_peers_local(Self, Bytes, UInt64) -> Array[@common.Hash]
pub fn I2pDht::make_token(Self, @common.Hash) -> Bytes
pub fn I2pDht::new(@common.Hash, Bytes, Bytes, query_port? : UInt32, reply_port? : UInt32) -> Self raise BtError
pub fn I2pDht::prune_expired_txs(Self, UInt64) -> Unit
pub fn I2pDht::record_peers_discovered(Self, UInt64) -> Unit
pub fn I2pDht::record_query_recv(Self) -> Unit
pub fn I2pDht::register_pending_tx(Self, Bytes, String, @common.Hash, UInt32, UInt64, info_hash? : Bytes?) -> Unit
pub fn I2pDht::store_peer(Self, Bytes, @common.Hash, UInt64) -> Unit
pub fn I2pDht::take_pending_tx(Self, Bytes) -> DhtPendingTx?
pub fn I2pDht::upsert_node(Self, Bytes, @common.Hash, UInt32, UInt64, verify_secure_id? : Bool) -> Bool
pub fn I2pDht::verify_token(Self, @common.Hash, Bytes) -> Bool
#derive(Eq, @debug.Debug)
pub(all) enum KrpcMessage {
Query(tx_id~ : Bytes, sender_id~ : Bytes, kind~ : KrpcQueryKind)
Response(tx_id~ : Bytes, sender_id~ : Bytes, nodes~ : Bytes, values~ : Array[Bytes], token~ : Bytes?)
ErrorMsg(tx_id~ : Bytes, code~ : Int64, msg~ : String)
}
#derive(Eq, @debug.Debug)
pub(all) enum KrpcQueryKind {
Ping
FindNode(target~ : Bytes)
GetPeers(info_hash~ : Bytes)
AnnouncePeer(info_hash~ : Bytes, port~ : UInt32, token~ : Bytes, implied_port~ : Bool)
}
#derive(Eq, @debug.Debug)
pub(all) struct MagnetLink {
info_hash : Bytes
display_name : String
trackers : Array[String]
dht_nodes : Array[(String, UInt32)]
}
#derive(Eq, @debug.Debug)
pub(all) enum MetadataMsg {
MetaRequest(Int32)
MetaData(Int32, Int32, Bytes)
MetaReject(Int32)
}
#derive(Eq, @debug.Debug)
pub(all) struct Metainfo {
info_hash : Bytes
name : String
piece_length : Int64
piece_hashes : Array[Bytes]
total_length : Int64
files : Array[TorrentFile]
trackers : Array[String]
raw_info : Bytes
}
#derive(Eq, @debug.Debug)
pub(all) enum PeerMessage {
KeepAlive
Choke
Unchoke
Interested
NotInterested
Have(UInt32)
Bitfield(Bytes)
Request(Int32, Int32, Int32)
Piece(Int32, Int32, Bytes)
Cancel(Int32, Int32, Int32)
Extended(Byte, Bytes)
}
#derive(Eq, @debug.Debug)
pub(all) struct RemoteExtensions {
mut ut_metadata_id : Byte?
mut i2p_pex_id : Byte?
mut i2p_dht_id : Byte?
mut metadata_size : Int32?
}
#derive(Eq, @debug.Debug)
pub(all) struct TorrentFile {
path : Array[String]
length : Int64
}
#derive(Eq, @debug.Debug)
pub(all) struct TrackerResponse {
interval : Int32
complete : Int32
incomplete : Int32
peers : Array[@common.Hash]
failure_reason : String?
}
#derive(Eq, @debug.Debug)
pub(all) struct TrackerUrl {
host : String
port : UInt32
request_target : String
}
// Type aliases
// Traits
+686
View File
@@ -0,0 +1,686 @@
///|
/// Pure-MoonBit BitTorrent Peer Wire Protocol (BEP 3), Extension Protocol (BEP 10),
/// Metadata Exchange (`ut_metadata` BEP 9), I2P Peer Exchange (`i2p_pex`),
/// `i2p_dht` extension negotiation, and I2P HTTP Tracker Announce codec (32B compact hashes).
///|
pub let bt_protocol_string : Bytes = b"\x13BitTorrent protocol"
///|
pub let ext_id_pex : Byte = b'\x01'
///|
pub let ext_id_ut_metadata : Byte = b'\x02'
///|
pub let ext_id_i2p_dht : Byte = b'\x03'
///|
pub let bt_block_size : Int32 = 16384
///|
pub fn encode_handshake(
info_hash : Bytes,
peer_id : Bytes,
) -> Bytes raise BtError {
if info_hash.length() != 20 || peer_id.length() != 20 {
raise InvalidWire("BitTorrent handshake requires 20B info_hash and peer_id")
}
let w = @encoding.Writer::new(capacity=68)
w.write_bytes(bt_protocol_string)
let reserved = FixedArray::make(8, b'\x00')
reserved[5] = b'\x10' // BEP 10 Extension Protocol supported
w.write_bytes(Bytes::from_array(reserved))
w.write_bytes(info_hash)
w.write_bytes(peer_id)
w.to_bytes()
}
///|
/// Decodes the 68-byte BitTorrent peer handshake into `(reserved_8B, info_hash_20B, peer_id_20B)`.
pub fn decode_handshake(buf : Bytes) -> (Bytes, Bytes, Bytes) raise BtError {
if buf.length() < 68 {
raise InvalidWire("handshake shorter than 68 bytes")
}
let pstr = buf[:20].to_owned()
if !@crypto.ct_eq(pstr, bt_protocol_string) {
raise InvalidWire("invalid BitTorrent protocol header")
}
let reserved = buf[20:28].to_owned()
let info_hash = buf[28:48].to_owned()
let peer_id = buf[48:68].to_owned()
(reserved, info_hash, peer_id)
}
///|
#derive(Eq, Debug)
pub(all) enum PeerMessage {
KeepAlive
Choke
Unchoke
Interested
NotInterested
Have(UInt32)
Bitfield(Bytes)
Request(Int32, Int32, Int32)
Piece(Int32, Int32, Bytes)
Cancel(Int32, Int32, Int32)
Extended(Byte, Bytes)
}
///|
/// Encodes a framed Peer Wire message (`4B length BE || id || payload`).
pub fn encode_peer_message(msg : PeerMessage) -> Bytes {
let w = @encoding.Writer::new(capacity=32)
match msg {
KeepAlive => w.write_u32_be(0U)
Choke => {
w.write_u32_be(1U)
w.write_u8(b'\x00')
}
Unchoke => {
w.write_u32_be(1U)
w.write_u8(b'\x01')
}
Interested => {
w.write_u32_be(1U)
w.write_u8(b'\x02')
}
NotInterested => {
w.write_u32_be(1U)
w.write_u8(b'\x03')
}
Have(idx) => {
w.write_u32_be(5U)
w.write_u8(b'\x04')
w.write_u32_be(idx)
}
Bitfield(bf) => {
w.write_u32_be((1 + bf.length()).reinterpret_as_uint())
w.write_u8(b'\x05')
w.write_bytes(bf)
}
Request(idx, begin, len) => {
w.write_u32_be(13U)
w.write_u8(b'\x06')
w.write_u32_be(idx.reinterpret_as_uint())
w.write_u32_be(begin.reinterpret_as_uint())
w.write_u32_be(len.reinterpret_as_uint())
}
Piece(idx, begin, data) => {
w.write_u32_be((9 + data.length()).reinterpret_as_uint())
w.write_u8(b'\x07')
w.write_u32_be(idx.reinterpret_as_uint())
w.write_u32_be(begin.reinterpret_as_uint())
w.write_bytes(data)
}
Cancel(idx, begin, len) => {
w.write_u32_be(13U)
w.write_u8(b'\x08')
w.write_u32_be(idx.reinterpret_as_uint())
w.write_u32_be(begin.reinterpret_as_uint())
w.write_u32_be(len.reinterpret_as_uint())
}
Extended(ext_id, payload) => {
w.write_u32_be((2 + payload.length()).reinterpret_as_uint())
w.write_u8(b'\x14')
w.write_u8(ext_id)
w.write_bytes(payload)
}
}
w.to_bytes()
}
///|
fn be32_at(buf : Array[Byte], off : Int32) -> UInt32 {
(buf[off].to_uint() << 24) |
(buf[off + 1].to_uint() << 16) |
(buf[off + 2].to_uint() << 8) |
buf[off + 3].to_uint()
}
///|
fn consume_front_bytes(buf : Array[Byte], count : Int32) -> Unit {
if count >= buf.length() {
buf.clear()
return
}
let rem : Array[Byte] = Array(capacity=buf.length() - count)
for i = count; i < buf.length(); i = i + 1 {
rem.push(buf[i])
}
buf.clear()
for b in rem {
buf.push(b)
}
}
///|
/// Attempts to decode and pop one framed Peer Wire message from `buf`.
pub fn try_decode_peer_message(buf : Array[Byte]) -> PeerMessage? raise BtError {
if buf.length() < 4 {
return None
}
let msg_len_u = be32_at(buf, 0)
if msg_len_u > 2097152U {
raise InvalidWire("peer wire frame too large: \{msg_len_u}")
}
let msg_len = msg_len_u.reinterpret_as_int()
if buf.length() < 4 + msg_len {
return None
}
if msg_len == 0 {
consume_front_bytes(buf, 4)
return Some(KeepAlive)
}
let body = Bytes::from_array(buf[4:4 + msg_len])
consume_front_bytes(buf, 4 + msg_len)
let r = @encoding.Reader::new(body)
let msg_id = r.read_u8() catch { e => raise Encoding(e) }
match msg_id {
b'\x00' => Some(Choke)
b'\x01' => Some(Unchoke)
b'\x02' => Some(Interested)
b'\x03' => Some(NotInterested)
b'\x04' => {
let idx = r.read_u32_be() catch { e => raise Encoding(e) }
Some(Have(idx))
}
b'\x05' => Some(Bitfield(r.read_remaining()))
b'\x06' => {
let idx = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
let begin = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
let len = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
Some(Request(idx, begin, len))
}
b'\x07' => {
let idx = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
let begin = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
let block = r.read_remaining()
Some(Piece(idx, begin, block))
}
b'\x08' => {
let idx = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
let begin = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
let len = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
Some(Cancel(idx, begin, len))
}
b'\x14' => {
let ext_id = r.read_u8() catch { e => raise Encoding(e) }
Some(Extended(ext_id, r.read_remaining()))
}
_ => Some(KeepAlive)
}
}
///|
#derive(Eq, Debug)
pub(all) struct RemoteExtensions {
mut ut_metadata_id : Byte?
mut i2p_pex_id : Byte?
mut i2p_dht_id : Byte?
mut metadata_size : Int32?
}
///|
/// Builds a BEP 10 extended handshake (`ext_id = 0`) advertising `i2p_pex`,
/// `ut_metadata`, `i2p_dht`, and optional `metadata_size`.
pub fn encode_ext_handshake(metadata_size~ : Int32? = None) -> Bytes {
let m_entries : Array[(Bytes, BVal)] = [
(b"i2p_dht", BInt(ext_id_i2p_dht.to_int().to_int64())),
(b"i2p_pex", BInt(ext_id_pex.to_int().to_int64())),
(b"ut_metadata", BInt(ext_id_ut_metadata.to_int().to_int64())),
]
let root : Array[(Bytes, BVal)] = [
(b"m", BDict(m_entries)),
(b"reqq", BInt(64L)),
(b"v", BBytes(b"moon-i2p/0.1")),
]
match metadata_size {
Some(sz) if sz > 0 => root.push((b"metadata_size", BInt(sz.to_int64())))
_ => ()
}
bencode_encode(BDict(root))
}
///|
/// Parses a remote peer's BEP 10 extended handshake payload.
pub fn decode_ext_handshake(payload : Bytes) -> RemoteExtensions raise BtError {
let d = bencode_decode(payload)
let res : RemoteExtensions = {
ut_metadata_id: None,
i2p_pex_id: None,
i2p_dht_id: None,
metadata_size: None,
}
match bdict_get(d, "m") {
Some(m) => {
match bdict_get_int(m, "ut_metadata") {
Some(v) if v > 0L && v < 256L => res.ut_metadata_id = Some(v.to_byte())
_ => ()
}
match bdict_get_int(m, "i2p_pex") {
Some(v) if v > 0L && v < 256L => res.i2p_pex_id = Some(v.to_byte())
_ => ()
}
match bdict_get_int(m, "i2p_dht") {
Some(v) if v > 0L && v < 256L => res.i2p_dht_id = Some(v.to_byte())
_ => ()
}
}
None => ()
}
match bdict_get_int(d, "metadata_size") {
Some(sz) if sz > 0L && sz <= 16777216L =>
res.metadata_size = Some(sz.to_int())
_ => ()
}
res
}
///|
/// Encodes the I2P DHT extension payload (`{"port": query_port, "rport": reply_port}`).
pub fn encode_i2p_dht_ext(query_port : UInt32, reply_port : UInt32) -> Bytes {
bencode_encode(
BDict([
(b"port", BInt(query_port.to_int64())),
(b"rport", BInt(reply_port.to_int64())),
]),
)
}
///|
/// Decodes an `i2p_dht` extension message into `(query_port, reply_port)`.
pub fn decode_i2p_dht_ext(payload : Bytes) -> (UInt32, UInt32)? {
let d = bencode_decode(payload) catch { _ => return None }
let q = match bdict_get_int(d, "port") {
Some(p) if p > 0L && p <= 65535L => p.to_int().reinterpret_as_uint()
_ => return None
}
let r = match bdict_get_int(d, "rport") {
Some(rp) if rp > 0L && rp <= 65535L => rp.to_int().reinterpret_as_uint()
_ => q + 1U
}
Some((q, r))
}
///|
/// Encodes `i2p_pex` compact 32-byte destination hashes under key `"added"`.
pub fn encode_i2p_pex(peers : Array[@common.Hash]) -> Bytes {
let w = @encoding.Writer::new(capacity=peers.length() * 32)
for h in peers {
w.write_bytes(h.as_bytes())
}
bencode_encode(BDict([(b"added", BBytes(w.to_bytes()))]))
}
///|
/// Decodes an `i2p_pex` message's `"added"` field (`32 * N` byte destination hashes).
pub fn decode_i2p_pex(payload : Bytes) -> Array[@common.Hash] {
let out : Array[@common.Hash] = []
let d = bencode_decode(payload) catch { _ => return out }
match bdict_get_bytes(d, "added") {
Some(blob) => {
let count = blob.length() / 32
for i = 0; i < count; i = i + 1 {
let h = @common.Hash::from_bytes(blob[i * 32:(i + 1) * 32].to_owned()) catch {
_ => continue
}
out.push(h)
}
}
None => ()
}
out
}
///|
#derive(Eq, Debug)
pub(all) enum MetadataMsg {
MetaRequest(Int32)
MetaData(Int32, Int32, Bytes) // (piece, total_size, slice)
MetaReject(Int32)
}
///|
pub fn encode_metadata_request(piece : Int32) -> Bytes {
bencode_encode(
BDict([(b"msg_type", BInt(0L)), (b"piece", BInt(piece.to_int64()))]),
)
}
///|
pub fn encode_metadata_data(
piece : Int32,
total_size : Int32,
slice : Bytes,
) -> Bytes {
let hdr = bencode_encode(
BDict([
(b"msg_type", BInt(1L)),
(b"piece", BInt(piece.to_int64())),
(b"total_size", BInt(total_size.to_int64())),
]),
)
let w = @encoding.Writer::new(capacity=hdr.length() + slice.length())
w.write_bytes(hdr)
w.write_bytes(slice)
w.to_bytes()
}
///|
pub fn encode_metadata_reject(piece : Int32) -> Bytes {
bencode_encode(
BDict([(b"msg_type", BInt(2L)), (b"piece", BInt(piece.to_int64()))]),
)
}
///|
/// Decodes a BEP 9 `ut_metadata` message (dictionary header followed by optional metadata slice).
pub fn decode_metadata_msg(payload : Bytes) -> MetadataMsg raise BtError {
let (d, hdr_end) = bencode_decode_prefix(payload)
let msg_type = match bdict_get_int(d, "msg_type") {
Some(t) => t
None => raise InvalidWire("ut_metadata missing msg_type")
}
let piece = match bdict_get_int(d, "piece") {
Some(p) if p >= 0L => p.to_int()
_ => raise InvalidWire("ut_metadata missing valid piece index")
}
if msg_type == 0L {
return MetaRequest(piece)
}
if msg_type == 1L {
let total_size = match bdict_get_int(d, "total_size") {
Some(s) if s > 0L => s.to_int()
_ => raise InvalidWire("ut_metadata data missing valid total_size")
}
let slice = payload[hdr_end:].to_owned()
return MetaData(piece, total_size, slice)
}
if msg_type == 2L {
return MetaReject(piece)
}
raise InvalidWire("unknown ut_metadata msg_type: \{msg_type}")
}
///|
#derive(Eq, Debug)
pub(all) struct TrackerUrl {
host : String
port : UInt32
request_target : String
}
///|
/// Parses an `http://host[:port]/path` I2P tracker URL. Returns `None` for non-HTTP or non-`.i2p` URLs.
pub fn parse_http_tracker_url(url : String) -> TrackerUrl? {
let trimmed = url.trim().to_owned()
let lower = trimmed.to_lower()
if !lower.has_prefix("http://") {
return None
}
let rest = trimmed[7:].to_owned()
let mut split_at = rest.length()
for i = 0; i < rest.length(); i = i + 1 {
if rest[i] == '/' || rest[i] == '?' {
split_at = i
break
}
}
let auth = rest[:split_at].to_owned()
let tail = rest[split_at:].to_owned()
let request_target = if tail.length() == 0 {
"/"
} else if tail.has_prefix("?") {
"/" + tail
} else {
tail
}
let mut colon = -1
for i = 0; i < auth.length(); i = i + 1 {
if auth[i] == ':' {
colon = i
}
}
let (host_raw, port) = if colon < 0 {
(auth, 80U)
} else {
let ps = auth[colon + 1:].to_owned()
match parse_u32_port_str(ps) {
Some(p) => (auth[:colon].to_owned(), p)
None => return None
}
}
let host = host_raw.to_lower()
if !host.has_suffix(".i2p") || host.length() <= 4 {
return None
}
Some({ host, port, request_target, })
}
///|
/// Builds an HTTP/1.1 tracker announce GET request with I2P `compact=1` and optional `ip=<dest>.i2p`.
pub fn build_http_announce_request(
tracker : TrackerUrl,
info_hash : Bytes,
peer_id : Bytes,
uploaded : Int64,
downloaded : Int64,
left : Int64,
event~ : String = "",
local_dest_b64~ : String = "",
) -> String {
let sep = if tracker.request_target.contains("?") { "&" } else { "?" }
let qs = StringBuilder()
qs.write_string(tracker.request_target)
qs.write_string(sep)
qs.write_string("info_hash=")
qs.write_string(url_encode_bytes(info_hash))
qs.write_string("&peer_id=")
qs.write_string(url_encode_bytes(peer_id))
qs.write_string("&port=6881&uploaded=")
qs.write_string(uploaded.to_string())
qs.write_string("&downloaded=")
qs.write_string(downloaded.to_string())
qs.write_string("&left=")
qs.write_string(left.to_string())
qs.write_string("&compact=1&numwant=50")
if event.length() > 0 {
qs.write_string("&event=")
qs.write_string(event)
}
if local_dest_b64.length() > 0 {
qs.write_string("&ip=")
qs.write_string(local_dest_b64)
qs.write_string(".i2p")
}
let host_hdr = if tracker.port == 80U {
tracker.host
} else {
"\{tracker.host}:\{tracker.port}"
}
"GET \{qs.to_string()} HTTP/1.1\r\nHost: \{host_hdr}\r\nUser-Agent: moon-i2p/0.1\r\nAccept: */*\r\nConnection: close\r\n\r\n"
}
///|
#derive(Eq, Debug)
pub(all) struct TrackerResponse {
interval : Int32
complete : Int32
incomplete : Int32
peers : Array[@common.Hash]
failure_reason : String?
}
///|
fn find_http_body_split(raw : Bytes) -> (Int32, Int32)? {
let n = raw.length()
for i = 0; i < n; i = i + 1 {
if i + 3 < n &&
raw[i] == b'\r' &&
raw[i + 1] == b'\n' &&
raw[i + 2] == b'\r' &&
raw[i + 3] == b'\n' {
return Some((i, i + 4))
}
if i + 1 < n && raw[i] == b'\n' && raw[i + 1] == b'\n' {
return Some((i, i + 2))
}
}
None
}
///|
fn decode_http_chunked(raw : Bytes) -> Bytes raise BtError {
let w = @encoding.Writer::new(capacity=raw.length())
let mut pos = 0
while pos < raw.length() {
let mut line_end = -1
for i = pos; i < raw.length(); i = i + 1 {
if raw[i] == b'\n' {
line_end = i
break
}
}
if line_end < 0 {
raise InvalidWire("malformed chunked tracker response")
}
let trim_end = if line_end > pos && raw[line_end - 1] == b'\r' {
line_end - 1
} else {
line_end
}
let len_str = @encoding.utf8_bytes_to_string(raw[pos:trim_end].to_owned()) catch {
_ => raise InvalidWire("non-UTF8 chunk size")
}
let clean_len = match find_char_or_semi(len_str) {
Some(s) => s.trim().to_owned()
None => len_str.trim().to_owned()
}
let mut chunk_sz = 0
for ch in clean_len {
let n = bt_hex_nibble(ch.to_int())
if n < 0 {
raise InvalidWire("invalid hex chunk size: \{clean_len}")
}
chunk_sz = chunk_sz * 16 + n
}
pos = line_end + 1
if chunk_sz == 0 {
break
}
if pos + chunk_sz > raw.length() {
raise InvalidWire("truncated chunked tracker body")
}
w.write_bytes(raw[pos:pos + chunk_sz].to_owned())
pos += chunk_sz
if pos + 1 < raw.length() && raw[pos] == b'\r' && raw[pos + 1] == b'\n' {
pos += 2
} else if pos < raw.length() && raw[pos] == b'\n' {
pos += 1
}
}
w.to_bytes()
}
///|
fn find_char_or_semi(s : String) -> String? {
for i = 0; i < s.length(); i = i + 1 {
if s[i] == ';' {
return Some(s[:i].to_owned())
}
}
None
}
///|
fn decode_tracker_peer_str(s : String) -> @common.Hash? {
let lower = s.trim().to_owned()
let host_no_i2p = if lower.to_lower().has_suffix(".i2p") {
lower[:lower.length() - 4].to_owned()
} else {
lower
}
if host_no_i2p.to_lower().has_suffix(".b32") && host_no_i2p.length() >= 56 {
let b32 = host_no_i2p[:host_no_i2p.length() - 4].to_owned()
let raw = @encoding.base32_decode(b32) catch { _ => return None }
if raw.length() == 32 {
return Some(@common.Hash::from_bytes(raw)) catch { _ => None }
}
}
let dest = @common.Destination::from_base64(host_no_i2p) catch {
_ => return None
}
Some(dest.hash())
}
///|
/// Parses an HTTP tracker response (including chunked / gzip encoding and 32B I2P compact peers).
pub fn parse_http_tracker_response(
raw : Bytes,
) -> TrackerResponse raise BtError {
let (hdr_end, body_start) = match find_http_body_split(raw) {
Some(p) => p
None => raise InvalidWire("HTTP tracker response missing header terminator")
}
let hdr_text = @encoding.utf8_bytes_to_string(raw[:hdr_end].to_owned()) catch {
e => raise Encoding(e)
}
let lower_hdr = hdr_text.to_lower()
let first_line = match lower_hdr.split("\n").next() {
Some(l) => l.to_owned().trim().to_owned()
None => raise InvalidWire("empty HTTP tracker status line")
}
if !first_line.contains(" 200") && !first_line.contains(" 20") {
raise InvalidWire("tracker HTTP status error: \{first_line}")
}
let mut body = raw[body_start:].to_owned()
if lower_hdr.contains("transfer-encoding: chunked") {
body = decode_http_chunked(body)
}
if lower_hdr.contains("content-encoding: gzip") {
body = @encoding.gzip_decompress(body) catch { e => raise Encoding(e) }
}
let dict = bencode_decode(body)
let failure_reason = bdict_get_string(dict, "failure reason")
let interval = match bdict_get_int(dict, "interval") {
Some(i) if i > 0L => i.to_int()
_ => 300
}
let complete = match bdict_get_int(dict, "complete") {
Some(c) if c >= 0L => c.to_int()
_ => 0
}
let incomplete = match bdict_get_int(dict, "incomplete") {
Some(ic) if ic >= 0L => ic.to_int()
_ => 0
}
let peers : Array[@common.Hash] = []
match bdict_get(dict, "peers") {
Some(BBytes(compact)) => {
let count = compact.length() / 32
for i = 0; i < count; i = i + 1 {
let slice = compact[i * 32:(i + 1) * 32].to_owned()
let is_zero = @crypto.ct_eq(slice, Bytes::make(32, b'\x00'))
if !is_zero {
let h = @common.Hash::from_bytes(slice) catch { _ => continue }
peers.push(h)
}
}
}
Some(BList(plist)) =>
for p in plist {
match bdict_get_string(p, "ip") {
Some(ip_s) =>
match decode_tracker_peer_str(ip_s) {
Some(h) => peers.push(h)
None => ()
}
None => ()
}
}
_ => ()
}
{ interval, complete, incomplete, peers, failure_reason, }
}
+59
View File
@@ -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)", " --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(" --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 <dir> Download folder for I2P torrents (default: ~/Downloads/moon-i2p)",
)
println( println(
" --ntcp2-host <ip> NTCP2 advertise/bind IP (default: 127.0.0.1)", " --ntcp2-host <ip> 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_enabled = false
let mut http_proxy_host = "127.0.0.1" let mut http_proxy_host = "127.0.0.1"
let mut http_proxy_port = 4444 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_host = "127.0.0.1"
let mut ntcp2_port = 0 let mut ntcp2_port = 0
let mut floodfill = false let mut floodfill = false
@@ -146,6 +156,35 @@ fn main {
i += 1 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" => "--ntcp2-port" =>
if i + 1 < args.length() { if i + 1 < args.length() {
match parse_port(args[i + 1]) { 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 { for pf in peer_files {
let _ = r.load_peer_file(pf) catch { let _ = r.load_peer_file(pf) catch {
_ => { _ => {
@@ -333,6 +387,11 @@ fn main {
if http_proxy_enabled { if http_proxy_enabled {
println(" HTTP Proxy: \{http_proxy_host}:\{r.http_proxy_port()}") 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( println(
" NetDB peers: \{r.netdb.router_count()} (floodfills=\{r.netdb.floodfill_count()})", " NetDB peers: \{r.netdb.router_count()} (floodfills=\{r.netdb.floodfill_count()})",
) )
+18
View File
@@ -286,3 +286,21 @@ test "curve25519 elligator2 encode/decode reference vectors and properties" {
} }
assert_true(encodable_count >= 10) 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",
)
}
+12
View File
@@ -44,6 +44,8 @@ pub fn hmac_sha256(Bytes, Bytes) -> Bytes
pub fn poly1305_mac(Bytes, Bytes) -> Bytes raise CryptoError pub fn poly1305_mac(Bytes, Bytes) -> Bytes raise CryptoError
pub fn sha1(Bytes) -> Bytes
pub fn sha256(Bytes) -> Bytes pub fn sha256(Bytes) -> Bytes
pub fn sha512(Bytes) -> Bytes pub fn sha512(Bytes) -> Bytes
@@ -64,6 +66,16 @@ pub suberror CryptoError {
} }
// Types and methods // 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 { pub struct Sha256 {
state : FixedArray[UInt32] state : FixedArray[UInt32]
block : FixedArray[Byte] block : FixedArray[Byte]
+123
View File
@@ -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()
}
Binary file not shown.
@@ -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: ["<all_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" };
}
});
+71
View File
@@ -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
);
})();
+12
View File
@@ -0,0 +1,12 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96 96">
<defs>
<linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#6d5dfc"/>
<stop offset="100%" stop-color="#14b8a6"/>
</linearGradient>
</defs>
<rect width="96" height="96" rx="22" fill="#0f172a"/>
<circle cx="48" cy="48" r="34" fill="none" stroke="url(#g)" stroke-width="6"/>
<path d="M48 25v29m0 0-12-12m12 12 12-12" fill="none" stroke="#f8fafc" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M29 64h38" stroke="#14b8a6" stroke-width="6" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 618 B

+108
View File
@@ -0,0 +1,108 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Moon I2P Torrent &amp; DHT Manager</title>
<link rel="stylesheet" href="ui.css" />
</head>
<body class="manager">
<header>
<div class="brand">
<img src="icon.svg" alt="" />
<span>moon-i2p BitTorrent &amp; I2P DHT Manager</span>
</div>
<div class="row">
<span id="router-pill" class="pill offline">Offline</span>
<button id="start-router-btn">Start Router</button>
<button id="stop-router-btn" class="secondary" style="display:none;">Stop Router</button>
</div>
</header>
<div class="grid-2">
<section class="card">
<h2><span>I2P Router &amp; HTTP Proxy</span></h2>
<div class="grid-2">
<div class="stat">
<div class="stat-label">NetDB / Tunnels</div>
<div id="net-summary" class="stat-val">--</div>
</div>
<div class="stat">
<div class="stat-label">I2P Proxy (.i2p)</div>
<label class="row" style="gap:4px;">
<input id="proxy-enabled" type="checkbox" />
<span id="proxy-addr" class="mono">127.0.0.1:4444</span>
</label>
</div>
</div>
<div class="stat" style="margin-top:8px;">
<div class="stat-label">Torrent Session .b32.i2p (share with DHT peers)</div>
<div id="torrent-b32" class="stat-val mono">--</div>
</div>
</section>
<section class="card">
<h2>
<span>I2P Kademlia DHT (Proto 17 / 18)</span>
<span id="dht-summary" class="mono">0 nodes</span>
</h2>
<div class="grid-2">
<div class="stat">
<div class="stat-label">Secure Node ID (20B)</div>
<div id="dht-node-id" class="stat-val mono">--</div>
</div>
<div class="stat">
<div class="stat-label">Sent / Recv / Peers</div>
<div id="dht-stats" class="stat-val">0 / 0 / 0</div>
</div>
</div>
<form id="bootstrap-form" class="row" style="margin-top:8px;">
<input id="bootstrap-b32" type="text" placeholder="Bootstrap node .b32.i2p" />
<input id="bootstrap-port" type="number" value="6881" style="width:84px;" />
<button type="submit" class="secondary">Bootstrap</button>
</form>
<div id="dht-nodes-list" class="node-list mono"></div>
</section>
</div>
<section class="card">
<h2><span>Add Torrent or Magnet URI</span></h2>
<form id="magnet-form" class="row">
<input id="magnet-uri" type="text" placeholder="magnet:?xt=urn:btih:...&amp;dn=..." />
<button type="submit">Add Magnet</button>
</form>
<div id="dropzone" class="dropzone">
Drop a .torrent file here or click to select one from disk
<input id="torrent-file" type="file" accept=".torrent" style="display:none;" />
</div>
<div id="status-msg" class="msg"></div>
</section>
<section class="card">
<h2>
<span>Active &amp; Completed Torrents</span>
<span id="torrent-count" class="mono">0</span>
</h2>
<div id="torrents-list">No torrents added yet.</div>
</section>
<section class="card">
<h2><span>Extension &amp; Router Settings</span></h2>
<form id="settings-form">
<div class="grid-2">
<div><div class="stat-label">HTTP Proxy Port</div><input id="cfg-proxy-port" type="number" /></div>
<div><div class="stat-label">Torrent API Port</div><input id="cfg-api-port" type="number" /></div>
</div>
<div style="margin-top:8px;">
<div class="stat-label">Default Download Directory</div>
<input id="cfg-dl-dir" type="text" placeholder="~/Downloads/moon-i2p" />
</div>
<div class="row" style="margin-top:8px;justify-content:space-between;">
<label class="row"><input id="cfg-intercept" type="checkbox" /> <span>Intercept magnet: and .torrent links on .i2p pages</span></label>
<button type="submit">Save Settings</button>
</div>
</form>
</section>
<script src="ui.js"></script>
</body>
</html>
@@ -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"
}
]
}
+112
View File
@@ -0,0 +1,112 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Moon I2P Torrent</title>
<link rel="stylesheet" href="ui.css" />
</head>
<body class="popup">
<header>
<div class="brand">
<img src="icon.svg" alt="" />
<span>moon-i2p Torrent</span>
</div>
<div class="row">
<span id="router-pill" class="pill offline">Offline</span>
<button id="open-manager-btn" class="secondary">Full View</button>
</div>
</header>
<section class="card">
<h2>
<span>I2P Router &amp; Proxy</span>
<span class="row">
<button id="start-router-btn">Start Router</button>
<button id="stop-router-btn" class="secondary" style="display:none;">Stop</button>
</span>
</h2>
<div class="grid-2">
<div class="stat">
<div class="stat-label">NetDB / Tunnels</div>
<div id="net-summary" class="stat-val">--</div>
</div>
<div class="stat">
<div class="stat-label">I2P Proxy (.i2p)</div>
<div class="row">
<label class="row" style="gap:4px;">
<input id="proxy-enabled" type="checkbox" />
<span id="proxy-addr" class="mono">127.0.0.1:4444</span>
</label>
</div>
</div>
</div>
<div class="stat" style="margin-top:6px;">
<div class="stat-label">Torrent Session .b32.i2p</div>
<div id="torrent-b32" class="stat-val mono">--</div>
</div>
</section>
<section class="card">
<h2>
<span>I2P DHT</span>
<span id="dht-summary" class="mono">0 nodes</span>
</h2>
<div class="grid-2">
<div class="stat">
<div class="stat-label">DHT Node ID (20B)</div>
<div id="dht-node-id" class="stat-val mono">--</div>
</div>
<div class="stat">
<div class="stat-label">Sent / Recv / Peers</div>
<div id="dht-stats" class="stat-val">0 / 0 / 0</div>
</div>
</div>
<form id="bootstrap-form" class="row" style="margin-top:8px;">
<input id="bootstrap-b32" type="text" placeholder="Bootstrap node .b32.i2p" />
<input id="bootstrap-port" type="number" value="6881" style="width:74px;" />
<button type="submit" class="secondary">Ping</button>
</form>
</section>
<section class="card">
<h2><span>Add I2P Torrent</span></h2>
<form id="magnet-form" class="row">
<input id="magnet-uri" type="text" placeholder="magnet:?xt=urn:btih:..." />
<button type="submit">Add</button>
</form>
<div id="dropzone" class="dropzone">
Drop a .torrent file here or click to browse
<input id="torrent-file" type="file" accept=".torrent" style="display:none;" />
</div>
<div id="status-msg" class="msg"></div>
</section>
<section class="card">
<h2>
<span>Torrents</span>
<span id="torrent-count" class="mono">0</span>
</h2>
<div id="torrents-list" class="muted">No torrents added yet.</div>
</section>
<details class="card">
<summary>Settings (API, Proxy &amp; Download Folder)</summary>
<form id="settings-form" style="margin-top:8px;">
<div class="grid-2">
<div><div class="stat-label">Proxy Port</div><input id="cfg-proxy-port" type="number" /></div>
<div><div class="stat-label">Torrent API Port</div><input id="cfg-api-port" type="number" /></div>
</div>
<div style="margin-top:6px;">
<div class="stat-label">Download Directory</div>
<input id="cfg-dl-dir" type="text" placeholder="~/Downloads/moon-i2p" />
</div>
<div class="row" style="margin-top:8px;justify-content:space-between;">
<label class="row"><input id="cfg-intercept" type="checkbox" /> <span>Intercept .i2p magnets &amp; .torrent links</span></label>
<button type="submit" class="secondary">Save</button>
</div>
</form>
</details>
<script src="ui.js"></script>
</body>
</html>
+240
View File
@@ -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);
}
+241
View File
@@ -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) => ({
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#39;",
})[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
? "<span class='stat-label'>No DHT nodes yet. Bootstrap above or connect to a peer.</span>"
: nodes
.map(
(n) =>
`<div class="node-row">${escapeHtml(n.b32)}:${n.port} (${escapeHtml((n.node_id_hex || "").slice(0, 12))}...)</div>`
)
.join("");
}
const list = st.torrents || [];
$("torrent-count").textContent = String(list.length);
const tEl = $("torrents-list");
if (list.length === 0) {
tEl.innerHTML = "<div class='stat-label'>No active torrents. Paste a magnet link or drop a .torrent file above.</div>";
} 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 `
<div class="torrent-item" data-ih="${escapeHtml(t.info_hash)}">
<div class="row" style="justify-content:space-between;">
<strong>${escapeHtml(t.name)}</strong>
<span class="pill ${t.completed ? "online" : ""}">${escapeHtml(t.state)} · ${pct}%</span>
</div>
<div class="progress-track"><div class="progress-fill" style="width:${pct}%"></div></div>
<div class="row" style="justify-content:space-between;color:var(--muted);font-size:11px;">
<span>${fmtBytes(t.downloaded_bytes)} / ${fmtBytes(t.total_length)} · ${t.have_pieces}/${t.num_pieces} pcs · ${t.connected_peers}/${t.known_peers} peers</span>
<span class="row">
<button class="secondary act-btn" data-act="${toggleType}" data-ih="${escapeHtml(t.info_hash)}">${toggleLabel}</button>
<button class="danger act-btn" data-act="removeTorrent" data-ih="${escapeHtml(t.info_hash)}">Remove</button>
</span>
</div>
${t.error ? `<div class="msg err">${escapeHtml(t.error)}</div>` : ""}
</div>
`;
})
.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);
});
+10 -2
View File
@@ -11,10 +11,18 @@ build:
moon build --target native cmd/router moon build --target native cmd/router
moon build --target native cmd/client 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: proxy:
moon build --target native cmd/router 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 # Run all MoonBit tests across wasm, js, and native targets
test: test:
+109
View File
@@ -613,3 +613,112 @@ int32_t moon_i2p_net_fetch_https(
} }
return total; 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;
}
+82
View File
@@ -140,6 +140,34 @@ extern "C" fn c_fetch_https(
max_len : Int32, max_len : Int32,
) -> Int32 = "moon_i2p_net_fetch_https" ) -> 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 { fn last_os_error() -> String {
let n = c_last_error_len() 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() 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. /// Native POSIX TCP socket wrapper with exact-length reads and line reading.
pub struct TcpSocket { pub struct TcpSocket {
+15 -3
View File
@@ -446,12 +446,23 @@ fn send_http_proxy_error(
status : Int32, status : Int32,
reason : String, reason : String,
detail : String, detail : String,
refresh_sec~ : Int32 = 0,
) -> Unit { ) -> Unit {
let safe_reason = escape_html(reason) let safe_reason = escape_html(reason)
let safe_detail = escape_html(detail) let safe_detail = escape_html(detail)
let body = "<!doctype html><html><head><meta charset=\"utf-8\"><title>\{status} \{safe_reason}</title></head><body><h1>\{status} \{safe_reason}</h1><p>\{safe_detail}</p><hr><small>moon-i2p HTTP Proxy</small></body></html>\n" let refresh_meta = if refresh_sec > 0 {
"<meta http-equiv=\"refresh\" content=\"\{refresh_sec}\">"
} else {
""
}
let refresh_hdr = if refresh_sec > 0 {
"Retry-After: \{refresh_sec}\r\n"
} else {
""
}
let body = "<!doctype html><html><head><meta charset=\"utf-8\">\{refresh_meta}<title>\{status} \{safe_reason}</title></head><body><h1>\{status} \{safe_reason}</h1><p>\{safe_detail}</p><hr><small>moon-i2p HTTP Proxy</small></body></html>\n"
let body_bytes = @encoding.string_to_utf8_bytes(body) let 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 { let _ = sock.write_all(@encoding.string_to_utf8_bytes(hdr)) catch {
_ => return _ => return
} }
@@ -788,7 +799,8 @@ fn Router::step_http_proxy(self : Router) -> Bool {
pc.sock, pc.sock,
503, 503,
"Service Unavailable", "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.sock.close()
pc.closed = true pc.closed = true
+1
View File
@@ -11,6 +11,7 @@ import {
"experiments/moon_i2p/ratchet", "experiments/moon_i2p/ratchet",
"experiments/moon_i2p/streaming", "experiments/moon_i2p/streaming",
"experiments/moon_i2p/sam", "experiments/moon_i2p/sam",
"experiments/moon_i2p/bittorrent",
} }
supported_targets = "-all+native" supported_targets = "-all+native"
+25
View File
@@ -71,6 +71,9 @@ pub struct Router {
priv mut http_proxy_listener : @ntcp2_net.TcpListener? priv mut http_proxy_listener : @ntcp2_net.TcpListener?
priv http_proxy_conns : Array[HttpProxyConn] priv http_proxy_conns : Array[HttpProxyConn]
priv mut http_proxy_session_id : String? 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 lease_rr : Int32
priv mut outbound_rr : Int32 priv mut outbound_rr : Int32
priv mut last_bootstrap_ms : UInt64 priv mut last_bootstrap_ms : UInt64
@@ -263,6 +266,9 @@ pub fn Router::start(
http_proxy_listener: None, http_proxy_listener: None,
http_proxy_conns: [], http_proxy_conns: [],
http_proxy_session_id: None, http_proxy_session_id: None,
torrent_engine: None,
torrent_api_listener: None,
torrent_api_conns: [],
lease_rr: 0, lease_rr: 0,
outbound_rr: 0, outbound_rr: 0,
last_bootstrap_ms: 0UL, last_bootstrap_ms: 0UL,
@@ -432,6 +438,19 @@ pub fn Router::reseed_from_url(
///| ///|
pub fn Router::close(self : Router) -> Unit { 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 { for pc in self.http_proxy_conns {
if !pc.closed { if !pc.closed {
pc.sock.close() pc.sock.close()
@@ -564,6 +583,12 @@ pub fn Router::step(self : Router, poll_ms~ : Int32 = 10) -> Unit {
if self.step_http_proxy() { if self.step_http_proxy() {
did_work = true 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_netdb_lookups()
self.poll_tunnel_builds() self.poll_tunnel_builds()
if self.public_mode { if self.public_mode {
+217
View File
@@ -504,3 +504,220 @@ test "Proposal 157 Outbound tunnel replying via Inbound tunnel with OBEP ECIES G
} }
assert_true(built_out) 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()))
}
+907
View File
@@ -0,0 +1,907 @@
///|
/// Localhost-only JSON + .torrent HTTP control API for the Firefox WebExtension
/// and CLI tools (`--torrent-api 127.0.0.1:4445`).
///
/// Security model:
/// - Rejects any non-loopback `Host` header (`403 Forbidden`) to prevent DNS rebinding.
/// - Requires `X-Moon-I2P: 1` header on all mutating `POST` endpoints (`403 Forbidden`)
/// to prevent cross-site form/fetch CSRF from arbitrary web pages.
/// - CORS `Access-Control-Allow-Origin` is echoed ONLY for `moz-extension://`,
/// `http://127.0.0.1`, or `http://localhost` origins.
///|
priv struct TorrentApiConn {
sock : @ntcp2_net.TcpSocket
recv_buf : Array[Byte]
mut hdr_parsed : Bool
mut http_method : String
mut path : String
mut host_hdr : String
mut origin_hdr : String
mut has_csrf_hdr : Bool
mut content_type : String
mut content_len : Int32
body_buf : Array[Byte]
started_ms : UInt64
mut closed : Bool
}
///|
pub fn Router::start_torrent_api(
self : Router,
host~ : String = "127.0.0.1",
port~ : Int32 = 4445,
download_dir~ : String = "",
) -> Int32 raise RouterError {
self.enable_torrent_engine(download_dir~)
match self.torrent_api_listener {
Some(l) => return l.port
None => ()
}
let l = @ntcp2_net.TcpListener::bind(host, port) catch { e => raise Net(e) }
self.torrent_api_listener = Some(l)
l.port
}
///|
pub fn Router::torrent_api_port(self : Router) -> Int32 {
match self.torrent_api_listener {
Some(l) => l.port
None => 0
}
}
///|
fn api_json_escape(s : String) -> String {
let out = StringBuilder()
for ch in s {
let code = ch.to_int()
match ch {
'"' => out.write_string("\\\"")
'\\' => out.write_string("\\\\")
'\n' => out.write_string("\\n")
'\r' => out.write_string("\\r")
'\t' => out.write_string("\\t")
_ => if code < 32 { out.write_char(' ') } else { out.write_char(ch) }
}
}
out.to_string()
}
///|
fn api_is_loopback_host(host_hdr : String) -> Bool {
let lower = host_hdr.trim().to_lower()
if lower.length() == 0 {
return false
}
if lower == "127.0.0.1" ||
lower.has_prefix("127.0.0.1:") ||
lower == "localhost" ||
lower.has_prefix("localhost:") ||
lower == "[::1]" ||
lower.has_prefix("[::1]:") {
true
} else {
false
}
}
///|
fn api_is_allowed_origin(origin : String) -> Bool {
let lower = origin.trim().to_lower()
lower.has_prefix("moz-extension://") ||
lower.has_prefix("http://127.0.0.1") ||
lower.has_prefix("http://localhost")
}
///|
fn api_parse_decimal(s : String) -> Int32 {
let t = s.trim()
if t.length() == 0 {
return 0
}
let mut v = 0
for i = 0; i < t.length(); i = i + 1 {
let c = t[i].to_int()
if c < 48 || c > 57 {
return 0
}
if v > 10000000 {
return v
}
v = v * 10 + (c - 48)
}
v
}
///|
/// Minimal JSON string/integer field extractor for flat API payloads.
fn api_json_get_string(json : String, key : String) -> String? {
let needle = "\"\{key}\""
let n = json.length()
let mut pos = 0
while pos + needle.length() < n {
let mut matched = true
for j = 0; j < needle.length(); j = j + 1 {
if json[pos + j] != needle[j] {
matched = false
break
}
}
if matched {
let mut i = pos + needle.length()
while i < n &&
(
json[i] == ' ' ||
json[i] == '\t' ||
json[i] == '\n' ||
json[i] == '\r'
) {
i += 1
}
if i < n && json[i] == ':' {
i += 1
while i < n &&
(
json[i] == ' ' ||
json[i] == '\t' ||
json[i] == '\n' ||
json[i] == '\r'
) {
i += 1
}
if i < n && json[i] == '"' {
i += 1
let sb = StringBuilder()
while i < n {
let ch = json[i]
if ch == '"' {
return Some(sb.to_string())
}
if ch == '\\' && i + 1 < n {
let nxt = json[i + 1]
match nxt {
'"' => sb.write_char('"')
'\\' => sb.write_char('\\')
'/' => sb.write_char('/')
'n' => sb.write_char('\n')
'r' => sb.write_char('\r')
't' => sb.write_char('\t')
_ => sb.write_char(nxt.unsafe_to_char())
}
i += 2
} else {
sb.write_char(ch.unsafe_to_char())
i += 1
}
}
return None
}
}
}
pos += 1
}
None
}
///|
fn api_json_get_int(json : String, key : String) -> Int32? {
let needle = "\"\{key}\""
let n = json.length()
let mut pos = 0
while pos + needle.length() < n {
let mut matched = true
for j = 0; j < needle.length(); j = j + 1 {
if json[pos + j] != needle[j] {
matched = false
break
}
}
if matched {
let mut i = pos + needle.length()
while i < n && (json[i] == ' ' || json[i] == '\t') {
i += 1
}
if i < n && json[i] == ':' {
i += 1
while i < n && (json[i] == ' ' || json[i] == '\t') {
i += 1
}
let sb = StringBuilder()
while i < n && json[i] >= '0' && json[i] <= '9' {
sb.write_char(json[i].unsafe_to_char())
i += 1
}
let s = sb.to_string()
if s.length() > 0 {
return Some(api_parse_decimal(s))
}
}
}
pos += 1
}
None
}
///|
fn api_send_response(
sock : @ntcp2_net.TcpSocket,
status_code : Int32,
reason : String,
body_json : String,
origin_hdr : String,
) -> Unit {
let body_bytes = @encoding.string_to_utf8_bytes(body_json)
let sb = StringBuilder()
sb.write_string("HTTP/1.1 \{status_code} \{reason}\r\n")
sb.write_string("Content-Type: application/json; charset=utf-8\r\n")
sb.write_string("Content-Length: \{body_bytes.length()}\r\n")
sb.write_string("Cache-Control: no-store\r\n")
if api_is_allowed_origin(origin_hdr) {
sb.write_string(
"Access-Control-Allow-Origin: \{origin_hdr.trim().to_owned()}\r\n",
)
sb.write_string(
"Access-Control-Allow-Headers: Content-Type, X-Moon-I2P\r\n",
)
sb.write_string("Access-Control-Allow-Methods: GET, POST, OPTIONS\r\n")
}
sb.write_string("Connection: close\r\n\r\n")
let hdr_bytes = @encoding.string_to_utf8_bytes(sb.to_string())
let _ = sock.write_all(hdr_bytes) catch { _ => () }
if body_bytes.length() > 0 {
let _ = sock.write_all(body_bytes) catch { _ => () }
}
}
///|
fn api_router_err_msg(e : RouterError) -> String {
match e {
Net(_) => "network/disk I/O error"
Crypto(_) => "cryptography error"
Common(_) => "I2P structure error"
Noise(_) => "noise handshake error"
NetDb(_) => "NetDB error"
I2np(_) => "I2NP message error"
Tunnel(_) => "tunnel error"
Protocol(msg) => msg
}
}
///|
fn api_json_err(msg : String) -> String {
"{\"ok\":false,\"error\":\"\{api_json_escape(msg)}\"}"
}
///|
fn Router::build_api_status_json(self : Router) -> String {
let eng = match self.torrent_engine {
Some(e) => e
None => return "{\"ok\":false,\"error\":\"torrent engine not initialized\"}"
}
let mut seeding = 0
let mut active = 0
for t in eng.torrents {
if !t.paused {
active += 1
}
if t.completed {
seeding += 1
}
}
let tb32 = self.torrent_b32_address()
let dht_id = @encoding.hex_encode(eng.dht.local_id)
let sb = StringBuilder()
sb.write_string("{\"ok\":true,")
sb.write_string("\"router_b32\":\"\{self.router_hash().to_b32_address()}\",")
sb.write_string("\"public_mode\":\{self.public_mode},")
sb.write_string("\"netdb_routers\":\{self.netdb.router_count()},")
sb.write_string("\"netdb_floodfills\":\{self.netdb.floodfill_count()},")
sb.write_string("\"netdb_leasesets\":\{self.netdb.leaseset_count()},")
sb.write_string("\"inbound_tunnels\":\{self.tunnels.inbound.length()},")
sb.write_string("\"outbound_tunnels\":\{self.tunnels.outbound.length()},")
sb.write_string("\"http_proxy_port\":\{self.http_proxy_port()},")
sb.write_string("\"torrent_api_port\":\{self.torrent_api_port()},")
sb.write_string("\"torrent_b32\":\"\{api_json_escape(tb32)}\",")
sb.write_string("\"download_dir\":\"\{api_json_escape(eng.download_dir)}\",")
sb.write_string("\"torrent_count\":\{eng.torrents.length()},")
sb.write_string("\"active_torrents\":\{active},")
sb.write_string("\"completed_torrents\":\{seeding},")
sb.write_string("\"dht\":{")
sb.write_string("\"node_id_hex\":\"\{dht_id}\",")
sb.write_string("\"query_port\":\{eng.dht.query_port},")
sb.write_string("\"reply_port\":\{eng.dht.reply_port},")
sb.write_string("\"routing_table_nodes\":\{eng.dht.nodes.length()},")
sb.write_string("\"queries_sent\":\{eng.dht.queries_sent},")
sb.write_string("\"responses_recv\":\{eng.dht.responses_recv},")
sb.write_string("\"queries_recv\":\{eng.dht.queries_recv},")
sb.write_string("\"peers_discovered\":\{eng.dht.peers_discovered}")
sb.write_string("}}")
sb.to_string()
}
///|
fn Router::build_api_torrents_json(self : Router) -> String {
let eng = match self.torrent_engine {
Some(e) => e
None => return "{\"ok\":true,\"torrents\":[]}"
}
let sb = StringBuilder()
sb.write_string("{\"ok\":true,\"torrents\":[")
for i = 0; i < eng.torrents.length(); i = i + 1 {
if i > 0 {
sb.write_char(',')
}
let t = eng.torrents[i]
let total_len = match t.metainfo {
Some(m) => m.total_length
None => 0L
}
let num_pieces = t.have_pieces.length()
let mut have_cnt = 0
for h in t.have_pieces {
if h {
have_cnt += 1
}
}
let mut active_peers = 0
for p in t.peers {
if p.state == 3 {
active_peers += 1
}
}
let state_str = if t.error.length() > 0 {
"error"
} else if t.paused {
"paused"
} else if t.completed {
"seeding"
} else if t.metainfo is None {
"metadata"
} else {
"downloading"
}
let progress_pct = if t.completed {
100
} else if num_pieces > 0 {
have_cnt * 100 / num_pieces
} else {
0
}
sb.write_char('{')
sb.write_string("\"info_hash\":\"\{t.info_hash_hex}\",")
sb.write_string("\"name\":\"\{api_json_escape(t.name)}\",")
sb.write_string("\"state\":\"\{state_str}\",")
sb.write_string("\"paused\":\{t.paused},")
sb.write_string("\"completed\":\{t.completed},")
sb.write_string("\"has_metadata\":\{t.metainfo is Some(_)},")
sb.write_string("\"total_length\":\{total_len},")
sb.write_string("\"downloaded_bytes\":\{t.downloaded_bytes},")
sb.write_string("\"uploaded_bytes\":\{t.uploaded_bytes},")
sb.write_string("\"have_pieces\":\{have_cnt},")
sb.write_string("\"num_pieces\":\{num_pieces},")
sb.write_string("\"progress_pct\":\{progress_pct},")
sb.write_string("\"known_peers\":\{t.known_peers.length()},")
sb.write_string("\"connected_peers\":\{active_peers},")
sb.write_string("\"trackers\":\{t.trackers.length()},")
sb.write_string("\"download_dir\":\"\{api_json_escape(t.download_dir)}\",")
sb.write_string("\"error\":\"\{api_json_escape(t.error)}\"")
sb.write_char('}')
}
sb.write_string("]}")
sb.to_string()
}
///|
fn Router::build_api_dht_nodes_json(self : Router) -> String {
let eng = match self.torrent_engine {
Some(e) => e
None => return "{\"ok\":true,\"nodes\":[]}"
}
let sb = StringBuilder()
sb.write_string("{\"ok\":true,")
sb.write_string(
"\"local_id_hex\":\"\{@encoding.hex_encode(eng.dht.local_id)}\",",
)
sb.write_string("\"local_b32\":\"\{self.torrent_b32_address()}\",")
sb.write_string("\"query_port\":\{eng.dht.query_port},")
sb.write_string("\"reply_port\":\{eng.dht.reply_port},")
sb.write_string("\"queries_sent\":\{eng.dht.queries_sent},")
sb.write_string("\"responses_recv\":\{eng.dht.responses_recv},")
sb.write_string("\"queries_recv\":\{eng.dht.queries_recv},")
sb.write_string("\"peers_discovered\":\{eng.dht.peers_discovered},")
sb.write_string("\"nodes\":[")
for i = 0; i < eng.dht.nodes.length(); i = i + 1 {
if i > 0 {
sb.write_char(',')
}
let n = eng.dht.nodes[i]
sb.write_char('{')
sb.write_string("\"node_id_hex\":\"\{@encoding.hex_encode(n.node_id)}\",")
sb.write_string("\"b32\":\"\{n.dest_hash.to_b32_address()}\",")
sb.write_string("\"port\":\{n.port},")
sb.write_string("\"last_seen_ms\":\{n.last_seen_ms}")
sb.write_char('}')
}
sb.write_string("]}")
sb.to_string()
}
///|
fn api_parse_header_block(ac : TorrentApiConn, hdr_bytes : Bytes) -> Bool {
let text = @encoding.utf8_bytes_to_string(hdr_bytes) catch {
_ => return false
}
let lines : Array[String] = []
let sb = StringBuilder()
for i = 0; i < text.length(); i = i + 1 {
let ch = text[i]
if ch == '\r' {
continue
}
if ch == '\n' {
lines.push(sb.to_string())
sb.reset()
} else {
sb.write_char(ch.unsafe_to_char())
}
}
if sb.to_string().length() > 0 {
lines.push(sb.to_string())
}
if lines.length() == 0 {
return false
}
let first = lines[0]
let mut sp1 = -1
let mut sp2 = -1
for i = 0; i < first.length(); i = i + 1 {
if first[i] == ' ' {
if sp1 < 0 {
sp1 = i
} else {
sp2 = i
break
}
}
}
if sp1 <= 0 || sp2 <= sp1 + 1 {
return false
}
ac.http_method = first[:sp1].to_owned().to_upper()
let target = first[sp1 + 1:sp2].to_owned()
let mut qpos = target.length()
for i = 0; i < target.length(); i = i + 1 {
if target[i] == '?' {
qpos = i
break
}
}
ac.path = target[:qpos].to_owned()
for i = 1; i < lines.length(); i = i + 1 {
let line = lines[i]
let mut colon = -1
for j = 0; j < line.length(); j = j + 1 {
if line[j] == ':' {
colon = j
break
}
}
if colon > 0 {
let k = line[:colon].to_owned().trim().to_owned().to_lower()
let v = line[colon + 1:].to_owned().trim().to_owned()
match k {
"host" => ac.host_hdr = v
"origin" => ac.origin_hdr = v
"content-length" => ac.content_len = api_parse_decimal(v)
"content-type" => ac.content_type = v.to_lower()
"x-moon-i2p" =>
if v == "1" || v.to_lower() == "true" {
ac.has_csrf_hdr = true
}
_ => ()
}
}
}
ac.hdr_parsed = true
true
}
///|
fn Router::dispatch_torrent_api_request(
self : Router,
ac : TorrentApiConn,
) -> Unit {
if !api_is_loopback_host(ac.host_hdr) {
api_send_response(
ac.sock,
403,
"Forbidden",
api_json_err("forbidden host header"),
ac.origin_hdr,
)
return
}
if ac.http_method == "OPTIONS" {
api_send_response(ac.sock, 204, "No Content", "", ac.origin_hdr)
return
}
if ac.http_method == "GET" {
match ac.path {
"/api/status" =>
api_send_response(
ac.sock,
200,
"OK",
self.build_api_status_json(),
ac.origin_hdr,
)
"/api/torrents" =>
api_send_response(
ac.sock,
200,
"OK",
self.build_api_torrents_json(),
ac.origin_hdr,
)
"/api/dht/nodes" =>
api_send_response(
ac.sock,
200,
"OK",
self.build_api_dht_nodes_json(),
ac.origin_hdr,
)
_ =>
api_send_response(
ac.sock,
404,
"Not Found",
api_json_err("unknown endpoint"),
ac.origin_hdr,
)
}
return
}
if ac.http_method != "POST" {
api_send_response(
ac.sock,
405,
"Method Not Allowed",
api_json_err("method not allowed"),
ac.origin_hdr,
)
return
}
if !ac.has_csrf_hdr {
api_send_response(
ac.sock,
403,
"Forbidden",
api_json_err("missing X-Moon-I2P: 1 header"),
ac.origin_hdr,
)
return
}
let body = Bytes::from_array(ac.body_buf)
let body_str = @encoding.utf8_bytes_to_string(body) catch { _ => "" }
match ac.path {
"/api/torrents/add" => {
let raw_torrent = if ac.content_type.contains("application/json") ||
(body.length() > 0 && body[0] == b'{') {
match api_json_get_string(body_str, "torrent_b64") {
Some(b64) =>
@encoding.base64_decode(b64) catch {
_ => {
api_send_response(
ac.sock,
400,
"Bad Request",
api_json_err("invalid torrent_b64"),
ac.origin_hdr,
)
return
}
}
None => {
api_send_response(
ac.sock,
400,
"Bad Request",
api_json_err("missing torrent_b64"),
ac.origin_hdr,
)
return
}
}
} else {
body
}
let dl_dir = match api_json_get_string(body_str, "download_dir") {
Some(d) => d
None => ""
}
try {
let ih = self.add_torrent_bytes(raw_torrent, download_dir=dl_dir)
api_send_response(
ac.sock,
200,
"OK",
"{\"ok\":true,\"info_hash\":\"\{ih}\"}",
ac.origin_hdr,
)
} catch {
e =>
api_send_response(
ac.sock,
400,
"Bad Request",
api_json_err(api_router_err_msg(e)),
ac.origin_hdr,
)
}
}
"/api/torrents/magnet" => {
let uri = match api_json_get_string(body_str, "uri") {
Some(u) => u
None => {
api_send_response(
ac.sock,
400,
"Bad Request",
api_json_err("missing magnet uri"),
ac.origin_hdr,
)
return
}
}
let dl_dir = match api_json_get_string(body_str, "download_dir") {
Some(d) => d
None => ""
}
try {
let ih = self.add_torrent_magnet(uri, download_dir=dl_dir)
api_send_response(
ac.sock,
200,
"OK",
"{\"ok\":true,\"info_hash\":\"\{ih}\"}",
ac.origin_hdr,
)
} catch {
e =>
api_send_response(
ac.sock,
400,
"Bad Request",
api_json_err(api_router_err_msg(e)),
ac.origin_hdr,
)
}
}
"/api/torrents/pause" => {
let ih = api_json_get_string(body_str, "info_hash").unwrap_or("")
if self.pause_torrent(ih) {
api_send_response(ac.sock, 200, "OK", "{\"ok\":true}", ac.origin_hdr)
} else {
api_send_response(
ac.sock,
404,
"Not Found",
api_json_err("torrent not found"),
ac.origin_hdr,
)
}
}
"/api/torrents/resume" => {
let ih = api_json_get_string(body_str, "info_hash").unwrap_or("")
if self.resume_torrent(ih) {
api_send_response(ac.sock, 200, "OK", "{\"ok\":true}", ac.origin_hdr)
} else {
api_send_response(
ac.sock,
404,
"Not Found",
api_json_err("torrent not found"),
ac.origin_hdr,
)
}
}
"/api/torrents/remove" => {
let ih = api_json_get_string(body_str, "info_hash").unwrap_or("")
if self.remove_torrent(ih) {
api_send_response(ac.sock, 200, "OK", "{\"ok\":true}", ac.origin_hdr)
} else {
api_send_response(
ac.sock,
404,
"Not Found",
api_json_err("torrent not found"),
ac.origin_hdr,
)
}
}
"/api/dht/bootstrap" => {
let b32 = api_json_get_string(body_str, "b32").unwrap_or("")
let port = match api_json_get_int(body_str, "port") {
Some(p) if p > 0 && p <= 65535 => p.reinterpret_as_uint()
_ => 6881U
}
match self.resolve_i2p_host_hash(b32) {
Some(h) => {
let ok = self.dht_add_bootstrap_node(h, port~)
api_send_response(
ac.sock,
200,
"OK",
"{\"ok\":\{ok},\"b32\":\"\{h.to_b32_address()}\",\"port\":\{port}}",
ac.origin_hdr,
)
}
None =>
api_send_response(
ac.sock,
400,
"Bad Request",
api_json_err("invalid bootstrap b32/hash"),
ac.origin_hdr,
)
}
}
_ =>
api_send_response(
ac.sock,
404,
"Not Found",
api_json_err("unknown endpoint"),
ac.origin_hdr,
)
}
}
///|
fn Router::step_torrent_api(self : Router) -> Bool {
let listener = match self.torrent_api_listener {
Some(l) => l
None => return false
}
let mut did_work = false
let now_ms = @ntcp2_net.unix_time_ms()
for _i = 0; _i < 8; _i = _i + 1 {
match (listener.accept(timeout_ms=0) catch { _ => None }) {
Some(sock) => {
self.torrent_api_conns.push({
sock,
recv_buf: [],
hdr_parsed: false,
http_method: "",
path: "",
host_hdr: "",
origin_hdr: "",
has_csrf_hdr: false,
content_type: "",
content_len: 0,
body_buf: [],
started_ms: now_ms,
closed: false,
})
did_work = true
}
None => break
}
}
let mut i = 0
while i < self.torrent_api_conns.length() {
let ac = self.torrent_api_conns[i]
if ac.closed {
let _ = self.torrent_api_conns.remove(i)
continue
}
if now_ms > ac.started_ms + 15000UL {
api_send_response(
ac.sock,
408,
"Request Timeout",
api_json_err("request timeout"),
ac.origin_hdr,
)
ac.sock.close()
ac.closed = true
let _ = self.torrent_api_conns.remove(i)
did_work = true
continue
}
let prev_len = ac.recv_buf.length()
let eof = try {
let _ = ac.sock.pump_nonblocking(ac.recv_buf, 16384)
false
} catch {
_ => true
}
if ac.recv_buf.length() != prev_len {
did_work = true
}
if !ac.hdr_parsed {
if ac.recv_buf.length() > 65536 {
api_send_response(
ac.sock,
431,
"Request Header Fields Too Large",
api_json_err("headers too large"),
ac.origin_hdr,
)
ac.sock.close()
ac.closed = true
let _ = self.torrent_api_conns.remove(i)
continue
}
match find_http_header_end(ac.recv_buf) {
Some((hdr_end, sep_len)) => {
let all = Bytes::from_array(ac.recv_buf)
let hdr_bytes = all[:hdr_end].to_owned()
let rem = all[hdr_end + sep_len:].to_owned()
ac.recv_buf.clear()
if !api_parse_header_block(ac, hdr_bytes) {
api_send_response(
ac.sock,
400,
"Bad Request",
api_json_err("malformed HTTP request"),
ac.origin_hdr,
)
ac.sock.close()
ac.closed = true
let _ = self.torrent_api_conns.remove(i)
continue
}
if ac.content_len > 4 * 1024 * 1024 {
api_send_response(
ac.sock,
413,
"Payload Too Large",
api_json_err("body exceeds 4 MiB limit"),
ac.origin_hdr,
)
ac.sock.close()
ac.closed = true
let _ = self.torrent_api_conns.remove(i)
continue
}
for j = 0; j < rem.length(); j = j + 1 {
ac.body_buf.push(rem[j])
}
did_work = true
}
None => ()
}
} else if ac.recv_buf.length() > 0 {
for b in ac.recv_buf {
if ac.body_buf.length() <= 4 * 1024 * 1024 {
ac.body_buf.push(b)
}
}
ac.recv_buf.clear()
}
if ac.hdr_parsed && ac.body_buf.length() >= ac.content_len {
while ac.body_buf.length() > ac.content_len && ac.content_len >= 0 {
let _ = ac.body_buf.pop()
}
self.dispatch_torrent_api_request(ac)
ac.sock.close()
ac.closed = true
let _ = self.torrent_api_conns.remove(i)
did_work = true
continue
}
if eof {
ac.sock.close()
ac.closed = true
let _ = self.torrent_api_conns.remove(i)
continue
}
i += 1
}
did_work
}
File diff suppressed because it is too large. Load diff
+466
View File
@@ -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" <<EOF
{
"name": "moon_i2p_torrent",
"description": "moon-i2p native I2P router & BitTorrent/DHT controller",
"path": "$HOST_COPY",
"type": "stdio",
"allowed_extensions": [
"moon-i2p-torrent@local"
]
}
EOF
done
fi
PYTHON_BIN="$(command -v python3 || true)"
if [[ -n "$PYTHON_BIN" ]]; then
read -r PROXY_PORT API_PORT SAM_PORT < <("$PYTHON_BIN" -c '
import socket
def pick(pref):
for p in (pref, 0):
s = socket.socket()
try:
s.bind(("127.0.0.1", p))
port = s.getsockname()[1]
s.close()
return port
except OSError:
s.close()
raise RuntimeError("no free port")
print(pick(4444), pick(4445), pick(7656))
')
else
PROXY_PORT=4444
API_PORT=4445
SAM_PORT=7656
fi
cat > "$PROFILE_DIR/i2p.pac" <<EOF
function FindProxyForURL(url, host) {
var h = (host || "").toLowerCase();
if (h === "127.0.0.1" || h === "localhost" || h === "::1" || h === "[::1]") {
return "DIRECT";
}
if (h === "i2p" || h.endsWith(".i2p")) {
return "PROXY 127.0.0.1:$PROXY_PORT";
}
return "DIRECT";
}
EOF
cat > "$PROFILE_DIR/user.js" <<EOF
user_pref("browser.startup.homepage", "http://insulaocculta.i2p/");
user_pref("browser.startup.page", 1);
user_pref("network.proxy.type", 2);
user_pref("network.proxy.autoconfig_url", "file://$PROFILE_DIR/i2p.pac");
user_pref("xpinstall.signatures.required", false);
user_pref("extensions.autoDisableScopes", 0);
user_pref("extensions.enabledScopes", 15);
user_pref("dom.security.https_only_mode", false);
user_pref("dom.security.https_only_mode_pbm", false);
user_pref("dom.security.https_first", false);
user_pref("dom.security.https_first_pbm", false);
user_pref("browser.fixup.domainsuffixwhitelist.i2p", true);
user_pref("network.trr.mode", 5);
user_pref("network.proxy.socks_remote_dns", true);
user_pref("network.captive-portal-service.enabled", false);
user_pref("browser.shell.checkDefaultBrowser", false);
EOF
ROUTER_BIN="$APPDIR/usr/bin/moon-i2p-router"
ROUTER_PID=""
FF_PID=""
cleanup() {
local rc=$?
rm -f "$DATA_DIR/active_ports.json"
if [[ -n "$FF_PID" ]] && kill -0 "$FF_PID" 2>/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" <<EOF
{"proxy_port": $PROXY_PORT, "api_port": $API_PORT, "sam_port": $SAM_PORT, "router_pid": $ROUTER_PID}
EOF
if [[ -n "$PYTHON_BIN" ]]; then
"$PYTHON_BIN" -c '
import socket, sys, time
port = int(sys.argv[1])
deadline = time.time() + 5.0
while time.time() < deadline:
try:
with socket.create_connection(("127.0.0.1", port), timeout=0.2):
sys.exit(0)
except OSError:
time.sleep(0.1)
' "$API_PORT" || true
else
sleep 1
fi
export MOON_I2P_APPIMAGE=1
export MOON_I2P_ROUTER_BIN="$ROUTER_BIN"
export MOON_I2P_PROXY_HOST=127.0.0.1
export MOON_I2P_PROXY_PORT="$PROXY_PORT"
export MOON_I2P_API_HOST=127.0.0.1
export MOON_I2P_API_PORT="$API_PORT"
export MOON_I2P_DOWNLOAD_DIR="$DOWNLOAD_DIR"
"$APPDIR/usr/lib/firefox/firefox" \
--no-remote \
--profile "$PROFILE_DIR" \
--class "MoonI2PBrowser" \
"$@" &
FF_PID=$!
wait "$FF_PID"
'''
def main():
DIST_DIR.mkdir(parents=True, exist_ok=True)
CACHE_DIR.mkdir(parents=True, exist_ok=True)
router_bin = build_router_binary()
xpi_path = build_extension_xpi()
firefox_tar = download_cached(
FIREFOX_ESR_URL, CACHE_DIR / "firefox-esr-linux64.tar.xz", min_bytes=20_000_000
)
runtime_bin = download_cached(
APPIMAGE_RUNTIME_URL, CACHE_DIR / "runtime-x86_64", min_bytes=100_000
)
if runtime_bin.read_bytes()[:4] != b"\x7fELF":
raise RuntimeError(f"Invalid ELF AppImage runtime at {runtime_bin}")
if APP_DIR.exists():
shutil.rmtree(APP_DIR)
(APP_DIR / "usr" / "bin").mkdir(parents=True)
(APP_DIR / "usr" / "lib").mkdir(parents=True)
(APP_DIR / "usr" / "share" / "moon-i2p").mkdir(parents=True)
print(f"[build_appimage] Extracting {firefox_tar.name}...")
with tarfile.open(firefox_tar, "r:*") as tf:
tf.extractall(APP_DIR / "usr" / "lib")
firefox_dir = APP_DIR / "usr" / "lib" / "firefox"
if not (firefox_dir / "firefox").is_file():
raise RuntimeError(f"Expected Firefox binary at {firefox_dir / 'firefox'}")
dist_ext_dir = firefox_dir / "distribution" / "extensions"
dist_ext_dir.mkdir(parents=True, exist_ok=True)
shutil.copy2(xpi_path, dist_ext_dir / "moon-i2p-torrent@local.xpi")
shutil.copy2(xpi_path, APP_DIR / "usr" / "share" / "moon-i2p" / "moon-i2p-torrent@local.xpi")
write_firefox_configs(firefox_dir)
router_dest = APP_DIR / "usr" / "bin" / "moon-i2p-router"
shutil.copy2(router_bin, router_dest)
make_executable(router_dest)
host_dest = APP_DIR / "usr" / "bin" / "moon_i2p_native_host.py"
shutil.copy2(NATIVE_HOST_SRC, host_dest)
make_executable(host_dest)
# Render desktop PNG icon via rsvg-convert (fallback magick).
icon_png = APP_DIR / "moon-i2p-browser.png"
svg_src = EXT_SRC / "icon.svg"
if shutil.which("rsvg-convert"):
run(["rsvg-convert", "-w", "256", "-h", "256", str(svg_src), "-o", str(icon_png)])
elif shutil.which("magick"):
run(["magick", "-background", "none", str(svg_src), "-resize", "256x256", str(icon_png)])
else:
raise RuntimeError("Need rsvg-convert or magick to render AppImage icon")
dir_icon = APP_DIR / ".DirIcon"
if dir_icon.exists() or dir_icon.is_symlink():
dir_icon.unlink()
dir_icon.symlink_to("moon-i2p-browser.png")
(APP_DIR / "MoonI2P-Browser.desktop").write_text(
"[Desktop Entry]\n"
"Version=1.0\n"
"Type=Application\n"
"Name=Moon I2P Browser\n"
"Comment=Zero-setup I2P browser and BitTorrent/DHT client powered by moon-i2p\n"
"Exec=AppRun %u\n"
"Icon=moon-i2p-browser\n"
"Categories=Network;WebBrowser;P2P;\n"
"MimeType=text/html;x-scheme-handler/magnet;application/x-bittorrent;\n"
"StartupWMClass=MoonI2PBrowser\n",
encoding="utf-8",
)
app_run = APP_DIR / "AppRun"
app_run.write_text(APP_RUN_SH, encoding="utf-8")
make_executable(app_run)
squashfs_img = CACHE_DIR / "moon-i2p-browser.squashfs"
if squashfs_img.exists():
squashfs_img.unlink()
mk_res = subprocess.run(
[
"mksquashfs",
str(APP_DIR),
str(squashfs_img),
"-root-owned",
"-noappend",
"-comp",
"zstd",
"-b",
"1M",
]
)
if mk_res.returncode != 0:
run(
[
"mksquashfs",
str(APP_DIR),
str(squashfs_img),
"-root-owned",
"-noappend",
"-comp",
"gzip",
"-b",
"1M",
]
)
tmp_out = OUTPUT_APPIMAGE.with_suffix(".AppImage.part")
with open(tmp_out, "wb") as out_fp:
with open(runtime_bin, "rb") as rt_fp:
shutil.copyfileobj(rt_fp, out_fp, length=1024 * 256)
with open(squashfs_img, "rb") as sq_fp:
shutil.copyfileobj(sq_fp, out_fp, length=1024 * 1024)
make_executable(tmp_out)
tmp_out.replace(OUTPUT_APPIMAGE)
size_mb = OUTPUT_APPIMAGE.stat().st_size / (1024 * 1024)
print(f"[build_appimage] Built {OUTPUT_APPIMAGE} ({size_mb:.1f} MiB)")
if __name__ == "__main__":
main()
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Install Firefox Native Messaging manifest and build unsigned .xpi bundle."""
import json
import os
import stat
import zipfile
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
HOST_SCRIPT = REPO_ROOT / "scripts" / "moon_i2p_native_host.py"
EXT_DIR = REPO_ROOT / "extensions" / "firefox-i2p-torrent"
XPI_PATH = REPO_ROOT / "extensions" / "firefox-i2p-torrent.xpi"
MANIFEST_DIRS = [
Path.home() / ".mozilla" / "native-messaging-hosts",
Path.home() / ".config" / "mozilla" / "native-messaging-hosts",
]
HOST_MANIFEST = {
"name": "moon_i2p_torrent",
"description": "moon-i2p native I2P router & BitTorrent/DHT controller",
"path": str(HOST_SCRIPT),
"type": "stdio",
"allowed_extensions": ["moon-i2p-torrent@local"],
}
def main():
mode = os.stat(HOST_SCRIPT).st_mode
os.chmod(HOST_SCRIPT, mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
for target_dir in MANIFEST_DIRS:
target_dir.mkdir(parents=True, exist_ok=True)
dest = target_dir / "moon_i2p_torrent.json"
dest.write_text(json.dumps(HOST_MANIFEST, indent=2) + "\n", encoding="utf-8")
print(f"Installed native messaging manifest: {dest}")
XPI_PATH.parent.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(XPI_PATH, "w", compression=zipfile.ZIP_DEFLATED) as zf:
for path in sorted(EXT_DIR.rglob("*")):
if path.is_file():
arcname = path.relative_to(EXT_DIR).as_posix()
zf.write(path, arcname)
print(f"Built Firefox extension bundle: {XPI_PATH}")
if __name__ == "__main__":
main()
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env python3
"""Firefox Native Messaging Host for moon-i2p router + BitTorrent/DHT API."""
import json
import os
import signal
import socket
import struct
import subprocess
import sys
import time
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
PID_FILE = Path("/tmp/moon_i2p_native_host_router.pid")
LOG_FILE = Path("/tmp/moon_i2p_native_router.log")
def read_msg():
raw_len = sys.stdin.buffer.read(4)
if len(raw_len) < 4:
return None
msg_len = struct.unpack("<I", raw_len)[0]
if msg_len == 0 or msg_len > 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("<I", len(encoded)))
sys.stdout.buffer.write(encoded)
sys.stdout.buffer.flush()
def find_router_binary():
env_bin = os.environ.get("MOON_I2P_ROUTER_BIN", "").strip()
if env_bin and Path(env_bin).is_file():
return env_bin
candidates = [
REPO_ROOT / "_build" / "native" / "release" / "build" / "cmd" / "router" / "router.exe",
REPO_ROOT / "_build" / "native" / "debug" / "build" / "cmd" / "router" / "router.exe",
]
for c in candidates:
if c.is_file():
return str(c)
return None
def is_tcp_listening(host: str, port: int) -> 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()
+2
View File
@@ -110,6 +110,8 @@ pub struct StreamManager {
streams : Array[StreamConnection] streams : Array[StreamConnection]
pending_accept : Array[StreamConnection] pending_accept : Array[StreamConnection]
incoming_datagrams : Array[RepliableDatagram] 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::accept_next(Self) -> StreamConnection?
pub fn StreamManager::connect(Self, @common.Hash, UInt64, from_port? : UInt32, to_port? : UInt32) -> StreamConnection raise StreamingError pub fn StreamManager::connect(Self, @common.Hash, UInt64, from_port? : UInt32, to_port? : UInt32) -> StreamConnection raise StreamingError
+11
View File
@@ -657,6 +657,10 @@ pub struct StreamManager {
streams : Array[StreamConnection] streams : Array[StreamConnection]
pending_accept : Array[StreamConnection] pending_accept : Array[StreamConnection]
incoming_datagrams : Array[RepliableDatagram] 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: [], streams: [],
pending_accept: [], pending_accept: [],
incoming_datagrams: [], incoming_datagrams: [],
incoming_repliable_dgrams: [],
incoming_raw_dgrams: [],
} }
} }
@@ -736,9 +742,14 @@ pub fn StreamManager::handle_incoming_i2cp(
let dg = RepliableDatagram::decode(raw) let dg = RepliableDatagram::decode(raw)
if dg.verify() { if dg.verify() {
self.incoming_datagrams.push(dg) self.incoming_datagrams.push(dg)
self.incoming_repliable_dgrams.push((hdr, dg))
} }
return None return None
} }
if hdr.protocol == b'\x12' {
self.incoming_raw_dgrams.push((hdr, raw))
return None
}
if hdr.protocol != b'\x06' { if hdr.protocol != b'\x06' {
return None return None
} }
+27
View File
@@ -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.read_available(), b"HTTP/1.0 200 OK\r\n\r\nhi")
assert_eq(a_stream.is_eof(), true) 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")
}