///| /// 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") }