///| /// Pure-MoonBit BitTorrent Metainfo (`.torrent` BEP 3/12) and Magnet (BEP 9) parser /// with path traversal sanitization and RFC 3986 percent-encoding helpers. ///| #derive(Eq, Debug) pub(all) struct TorrentFile { path : Array[String] length : Int64 } ///| #derive(Eq, Debug) pub(all) struct Metainfo { info_hash : Bytes // 20-byte SHA-1 name : String piece_length : Int64 piece_hashes : Array[Bytes] total_length : Int64 files : Array[TorrentFile] trackers : Array[String] raw_info : Bytes } ///| #derive(Eq, Debug) pub(all) struct MagnetLink { info_hash : Bytes // 20-byte SHA-1 display_name : String trackers : Array[String] dht_nodes : Array[(String, UInt32)] } ///| fn check_safe_path_segment(seg : String) -> String raise BtError { if seg.length() == 0 || seg == "." || seg == ".." { raise InvalidMetainfo("unsafe path segment '\{seg}'") } for ch in seg { if ch == '/' || ch == '\\' || ch.to_int() < 0x20 { raise InvalidMetainfo( "illegal character in torrent path segment '\{seg}'", ) } } seg } ///| fn sanitize_path_segments(segs : Array[String]) -> Array[String] raise BtError { if segs.length() == 0 { raise InvalidMetainfo("empty torrent file path") } let out : Array[String] = Array(capacity=segs.length()) for s in segs { out.push(check_safe_path_segment(s)) } out } ///| fn append_unique_str(list : Array[String], val : String) -> Unit { if val.length() == 0 { return } for item in list { if item == val { return } } list.push(val) } ///| /// Parses the raw `"info"` dictionary bytes (`BEP 9` / `.torrent` `"info"` value) /// into a validated `Metainfo`. pub fn parse_info_dict( raw_info : Bytes, trackers~ : Array[String] = [], ) -> Metainfo raise BtError { let info = bencode_decode(raw_info) if !(info is BDict(_)) { raise InvalidMetainfo("info value must be a dictionary") } let raw_name = match bdict_get_string(info, "name") { Some(n) => n None => raise InvalidMetainfo("info dictionary missing UTF-8 'name'") } let name = check_safe_path_segment(raw_name) let piece_length = match bdict_get_int(info, "piece length") { Some(pl) if pl > 0L => pl _ => raise InvalidMetainfo("info dictionary missing valid 'piece length'") } let pieces_blob = match bdict_get_bytes(info, "pieces") { Some(pb) if pb.length() > 0 && pb.length() % 20 == 0 => pb _ => raise InvalidMetainfo("info dictionary has invalid 'pieces' blob") } let num_pieces = pieces_blob.length() / 20 let piece_hashes : Array[Bytes] = Array(capacity=num_pieces) for i = 0; i < num_pieces; i = i + 1 { piece_hashes.push(pieces_blob[i * 20:(i + 1) * 20].to_owned()) } let files : Array[TorrentFile] = [] let mut total_length = 0L match bdict_get(info, "files") { Some(BList(flist)) => { if flist.length() == 0 { raise InvalidMetainfo("multi-file torrent has empty 'files' list") } for entry in flist { let flen = match bdict_get_int(entry, "length") { Some(l) if l >= 0L => l _ => raise InvalidMetainfo("file entry missing valid 'length'") } let segs : Array[String] = [name] match bdict_get(entry, "path") { Some(BList(plist)) => { if plist.length() == 0 { raise InvalidMetainfo("file entry has empty 'path'") } for pitem in plist { match pitem { BBytes(pb) => { let ps = @encoding.utf8_bytes_to_string(pb) catch { e => raise Encoding(e) } segs.push(ps) } _ => raise InvalidMetainfo("non-string element in file 'path'") } } } _ => raise InvalidMetainfo("file entry missing 'path' list") } let clean = sanitize_path_segments(segs) files.push({ path: clean, length: flen, }) total_length = total_length + flen } } Some(_) => raise InvalidMetainfo("'files' entry must be a list") None => { let flen = match bdict_get_int(info, "length") { Some(l) if l >= 0L => l _ => raise InvalidMetainfo("single-file torrent missing valid 'length'") } files.push({ path: [name], length: flen, }) total_length = flen } } if total_length > 0L { let expected_pieces = (total_length + piece_length - 1L) / piece_length if expected_pieces != num_pieces.to_int64() { raise InvalidMetainfo( "piece hash count \{num_pieces} does not match length \{total_length} / piece_length \{piece_length}", ) } } let clean_trackers : Array[String] = [] for tr in trackers { append_unique_str(clean_trackers, tr) } { info_hash: @crypto.sha1(raw_info), name, piece_length, piece_hashes, total_length, files, trackers: clean_trackers, raw_info, } } ///| /// Parses a full `.torrent` file (BEP 3 + BEP 12 `announce-list`) and validates all fields. pub fn parse_torrent(torrent_bytes : Bytes) -> Metainfo raise BtError { let root = bencode_decode(torrent_bytes) let trackers : Array[String] = [] match bdict_get_string(root, "announce") { Some(tr) => append_unique_str(trackers, tr.trim().to_owned()) None => () } match bdict_get(root, "announce-list") { Some(BList(tiers)) => for tier in tiers { match tier { BList(urls) => for u in urls { match u { BBytes(ub) => { let us = @encoding.utf8_bytes_to_string(ub) catch { _ => "" } append_unique_str(trackers, us.trim().to_owned()) } _ => () } } _ => () } } _ => () } let raw_info = extract_info_raw(torrent_bytes) parse_info_dict(raw_info, trackers~) } ///| fn bt_hex_nibble(c : Int32) -> Int32 { if c >= 48 && c <= 57 { c - 48 } else if c >= 65 && c <= 70 { c - 55 } else if c >= 97 && c <= 102 { c - 87 } else { -1 } } ///| fn percent_decode_param(s : String, plus_as_space~ : Bool = true) -> String { let out : Array[Byte] = [] let raw = @encoding.string_to_utf8_bytes(s) let mut i = 0 while i < raw.length() { let b = raw[i] if plus_as_space && b == b'+' { out.push(b' ') i += 1 } else if b == b'%' && i + 2 < raw.length() { let hi = bt_hex_nibble(raw[i + 1].to_int()) let lo = bt_hex_nibble(raw[i + 2].to_int()) if hi >= 0 && lo >= 0 { out.push(((hi << 4) | lo).to_byte()) i += 3 continue } out.push(b) i += 1 } else { out.push(b) i += 1 } } @encoding.utf8_bytes_to_string(Bytes::from_array(out)) catch { _ => s } } ///| fn parse_u32_port_str(s : String) -> UInt32? { if s.length() == 0 { return None } let mut val = 0U for ch in s { if ch < '0' || ch > '9' { return None } val = val * 10U + (ch.to_int() - '0'.to_int()).reinterpret_as_uint() if val > 65535U { return None } } if val == 0U { None } else { Some(val) } } ///| fn parse_host_port_pair(spec : String) -> (String, UInt32)? { let mut colon = -1 for i = 0; i < spec.length(); i = i + 1 { if spec[i] == ':' { colon = i } } if colon <= 0 || colon + 1 >= spec.length() { return None } let host = spec[:colon].to_owned().trim().to_owned() let port_s = spec[colon + 1:].to_owned().trim().to_owned() match parse_u32_port_str(port_s) { Some(p) if host.length() > 0 => Some((host, p)) _ => None } } ///| /// Parses a BitTorrent `magnet:?xt=urn:btih:...` URI (40-char hex or 32-char Base32 info_hash). pub fn parse_magnet(uri : String) -> MagnetLink raise BtError { let trimmed = uri.trim().to_owned() if !trimmed.to_lower().has_prefix("magnet:?") { raise InvalidMagnet("URI must start with 'magnet:?'") } let query = trimmed[8:].to_owned() let mut info_hash : Bytes? = None let mut display_name = "" let trackers : Array[String] = [] let dht_nodes : Array[(String, UInt32)] = [] for part_view in query.split("&") { let part = part_view.to_owned() if part.length() == 0 { continue } let mut eq = -1 for i = 0; i < part.length(); i = i + 1 { if part[i] == '=' { eq = i break } } if eq <= 0 { continue } let key = part[:eq].to_owned().to_lower() let raw_val = part[eq + 1:].to_owned() if key == "xt" { let decoded = percent_decode_param(raw_val, plus_as_space=false) let lower_xt = decoded.to_lower() if lower_xt.has_prefix("urn:btih:") { let hash_str = decoded[9:].to_owned() let parsed = if hash_str.length() == 40 { @encoding.hex_decode(hash_str) catch { e => raise Encoding(e) } } else if hash_str.length() == 32 { @encoding.base32_decode(hash_str) catch { e => raise Encoding(e) } } else { raise InvalidMagnet( "unsupported btih hash length: \{hash_str.length()}", ) } if parsed.length() != 20 { raise InvalidMagnet("decoded btih must be 20 bytes") } info_hash = Some(parsed) } } else if key == "dn" { display_name = percent_decode_param(raw_val, plus_as_space=true) } else if key == "tr" { let tr = percent_decode_param(raw_val, plus_as_space=false) .trim() .to_owned() append_unique_str(trackers, tr) } else if key == "dht" || key == "x.pe" { let val = percent_decode_param(raw_val, plus_as_space=false) match parse_host_port_pair(val) { Some(pair) => dht_nodes.push(pair) None => () } } } let ih = match info_hash { Some(h) => h None => raise InvalidMagnet("magnet URI missing xt=urn:btih:") } let name = if display_name.length() > 0 { display_name } else { @encoding.hex_encode(ih) } { info_hash: ih, display_name: name, trackers, dht_nodes, } } ///| fn hex_upper_char(n : Int32) -> Char { if n < 10 { (48 + n).unsafe_to_char() } else { (65 + n - 10).unsafe_to_char() } } ///| fn is_rfc3986_unreserved(b : Byte) -> Bool { let v = b.to_int() (v >= 65 && v <= 90) || (v >= 97 && v <= 122) || (v >= 48 && v <= 57) || v == 45 || // '-' v == 95 || // '_' v == 46 || // '.' v == 126 // '~' } ///| /// Percent-encodes raw bytes (such as `info_hash` / `peer_id`) for BitTorrent tracker GET queries. pub fn url_encode_bytes(data : Bytes) -> String { let sb = StringBuilder(size_hint=data.length() * 3) for i = 0; i < data.length(); i = i + 1 { let b = data[i] if is_rfc3986_unreserved(b) { sb.write_char(b.to_int().unsafe_to_char()) } else { let v = b.to_int() sb.write_char('%') sb.write_char(hex_upper_char((v >> 4) & 0xF)) sb.write_char(hex_upper_char(v & 0xF)) } } sb.to_string() }