feat: persist I2P torrent list to EDN state file across restarts
- Save active and paused torrents to torrents.edn on add, remove, pause, resume, and metadata fetch, then restore them on router startup. - Default path is $MOON_I2P_DATA_DIR, then $XDG_DATA_HOME, then ~/.local/share/moon-i2p-browser. Add --torrent-state <file> to override, or --no-torrent-state to disable. - Write the state file atomically (temp file, fsync, rename). A corrupt or unsupported file logs a warning and does not block startup. - Verify restored pieces incrementally in the background for large torrents; these show as state "checking" in /api/torrents. - Expose state_file in /api/status and the startup banner. - Add standard RFC 4648 Base64 encode/decode helpers, used for the info-b64 field. - Add the moonedn dependency and pass --torrent-state from the Android service.
This commit is contained in:
1 parent
b803e79199
commit
dd5b132b5a
17 files changed
+1105
-39
No files matched your search
@@ -492,6 +492,8 @@ public class RouterService extends Service {
|
||||
cmd.add("127.0.0.1:" + sApiPort);
|
||||
cmd.add("--download-dir");
|
||||
cmd.add(sDownloadDir);
|
||||
cmd.add("--torrent-state");
|
||||
cmd.add(new File(getFilesDir(), "torrents.edn").getAbsolutePath());
|
||||
|
||||
logEvent("ROUTER", "Launching: " + String.join(" ", cmd));
|
||||
|
||||
|
||||
@@ -37,6 +37,51 @@ fn split_host_port(spec : String) -> (String, Int32)? {
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn trim_trailing_slash(dir : String) -> String {
|
||||
if dir.length() > 1 && dir.has_suffix("/") {
|
||||
dir[:dir.length() - 1].to_owned()
|
||||
} else {
|
||||
dir
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn default_torrent_state_file(download_dir : String) -> String {
|
||||
match @env.get_env_var("MOON_I2P_DATA_DIR") {
|
||||
Some(d) => {
|
||||
let t = d.trim().to_owned()
|
||||
if t.length() > 0 {
|
||||
return trim_trailing_slash(t) + "/torrents.edn"
|
||||
}
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
match @env.get_env_var("XDG_DATA_HOME") {
|
||||
Some(d) => {
|
||||
let t = d.trim().to_owned()
|
||||
if t.length() > 0 {
|
||||
return trim_trailing_slash(t) + "/moon-i2p-browser/torrents.edn"
|
||||
}
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
let home = match @env.get_env_var("HOME") {
|
||||
Some(h) if h.trim().to_owned().length() > 0 => h.trim().to_owned()
|
||||
_ => @ntcp2_net.get_home_dir().trim().to_owned()
|
||||
}
|
||||
if home.length() > 0 {
|
||||
return trim_trailing_slash(home) +
|
||||
"/.local/share/moon-i2p-browser/torrents.edn"
|
||||
}
|
||||
let dl = download_dir.trim().to_owned()
|
||||
if dl.length() > 0 {
|
||||
trim_trailing_slash(dl) + "/.moon-i2p-torrents.edn"
|
||||
} else {
|
||||
"./torrents.edn"
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn print_usage() -> Unit {
|
||||
println("moon-i2p native router daemon")
|
||||
@@ -58,6 +103,10 @@ fn print_usage() -> Unit {
|
||||
println(
|
||||
" --download-dir <dir> Download folder for I2P torrents (default: ~/Downloads/moon-i2p)",
|
||||
)
|
||||
println(
|
||||
" --torrent-state <file> EDN file to persist torrent list (default: $MOON_I2P_DATA_DIR/torrents.edn)",
|
||||
)
|
||||
println(" --no-torrent-state Disable EDN torrent list persistence")
|
||||
println(
|
||||
" --ntcp2-host <ip> NTCP2 advertise/bind IP (default: 127.0.0.1)",
|
||||
)
|
||||
@@ -101,6 +150,8 @@ fn main {
|
||||
let mut torrent_api_host = "127.0.0.1"
|
||||
let mut torrent_api_port = 4445
|
||||
let mut download_dir = ""
|
||||
let mut torrent_state = ""
|
||||
let mut no_torrent_state = false
|
||||
let mut ntcp2_host = "127.0.0.1"
|
||||
let mut ntcp2_port = 0
|
||||
let mut floodfill = false
|
||||
@@ -185,6 +236,17 @@ fn main {
|
||||
} else {
|
||||
i += 1
|
||||
}
|
||||
"--torrent-state" =>
|
||||
if i + 1 < args.length() {
|
||||
torrent_state = args[i + 1]
|
||||
i += 2
|
||||
} else {
|
||||
i += 1
|
||||
}
|
||||
"--no-torrent-state" => {
|
||||
no_torrent_state = true
|
||||
i += 1
|
||||
}
|
||||
"--ntcp2-port" =>
|
||||
if i + 1 < args.length() {
|
||||
match parse_port(args[i + 1]) {
|
||||
@@ -280,6 +342,9 @@ fn main {
|
||||
}
|
||||
}
|
||||
i += 1
|
||||
} else if args[i].has_prefix("--torrent-state=") {
|
||||
torrent_state = args[i][16:].to_owned()
|
||||
i += 1
|
||||
} else {
|
||||
i += 1
|
||||
}
|
||||
@@ -310,11 +375,19 @@ fn main {
|
||||
}
|
||||
}
|
||||
}
|
||||
let effective_state_file = if no_torrent_state {
|
||||
""
|
||||
} else if torrent_state.trim().to_owned().length() > 0 {
|
||||
torrent_state.trim().to_owned()
|
||||
} else {
|
||||
default_torrent_state_file(download_dir)
|
||||
}
|
||||
if torrent_api_enabled {
|
||||
let _ = r.start_torrent_api(
|
||||
host=torrent_api_host,
|
||||
port=torrent_api_port,
|
||||
download_dir~,
|
||||
state_file=effective_state_file,
|
||||
) catch {
|
||||
_ => {
|
||||
r.close()
|
||||
@@ -391,6 +464,9 @@ fn main {
|
||||
println(
|
||||
" Torrent API: \{torrent_api_host}:\{r.torrent_api_port()} (b32=\{r.torrent_b32_address()})",
|
||||
)
|
||||
if effective_state_file.length() > 0 {
|
||||
println(" Torrent State: \{effective_state_file}")
|
||||
}
|
||||
}
|
||||
println(
|
||||
" NetDB peers: \{r.netdb.router_count()} (floodfills=\{r.netdb.floodfill_count()})",
|
||||
|
||||
+63
-19
@@ -3,27 +3,33 @@
|
||||
let i2p_b64_alphabet : Bytes = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-~"
|
||||
|
||||
///|
|
||||
fn b64_decode_char(c : Int32) -> Int32 raise EncodingError {
|
||||
/// Standard RFC 4648 Base64 alphabet: `A-Z`, `a-z`, `0-9`, `+`, `/` with `=` padding.
|
||||
let std_b64_alphabet : Bytes = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
|
||||
|
||||
///|
|
||||
fn b64_decode_char_with_extras(
|
||||
c : Int32,
|
||||
c62 : Int32,
|
||||
c63 : Int32,
|
||||
label : String,
|
||||
) -> Int32 raise EncodingError {
|
||||
if c >= 65 && c <= 90 {
|
||||
c - 65
|
||||
} else if c >= 97 && c <= 122 {
|
||||
c - 97 + 26
|
||||
} else if c >= 48 && c <= 57 {
|
||||
c - 48 + 52
|
||||
} else if c == 45 {
|
||||
// '-'
|
||||
} else if c == c62 {
|
||||
62
|
||||
} else if c == 126 {
|
||||
// '~'
|
||||
} else if c == c63 {
|
||||
63
|
||||
} else {
|
||||
raise InvalidCharacter("invalid I2P Base64 character code: \{c}")
|
||||
raise InvalidCharacter("invalid \{label} Base64 character code: \{c}")
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Encodes bytes using the I2P Base64 alphabet (`-` and `~`, padded with `=`).
|
||||
pub fn base64_encode(data : Bytes) -> String {
|
||||
fn encode_b64_with_alphabet(data : Bytes, alphabet : Bytes) -> String {
|
||||
let len = data.length()
|
||||
if len == 0 {
|
||||
return ""
|
||||
@@ -42,15 +48,15 @@ pub fn base64_encode(data : Bytes) -> String {
|
||||
let c2 = ((b1 & 0x0F) << 2) | (b2 >> 6)
|
||||
let c3 = b2 & 0x3F
|
||||
|
||||
buf.write_char(i2p_b64_alphabet[c0].to_int().unsafe_to_char())
|
||||
buf.write_char(i2p_b64_alphabet[c1].to_int().unsafe_to_char())
|
||||
buf.write_char(alphabet[c0].to_int().unsafe_to_char())
|
||||
buf.write_char(alphabet[c1].to_int().unsafe_to_char())
|
||||
if has_b1 {
|
||||
buf.write_char(i2p_b64_alphabet[c2].to_int().unsafe_to_char())
|
||||
buf.write_char(alphabet[c2].to_int().unsafe_to_char())
|
||||
} else {
|
||||
buf.write_char('=')
|
||||
}
|
||||
if has_b2 {
|
||||
buf.write_char(i2p_b64_alphabet[c3].to_int().unsafe_to_char())
|
||||
buf.write_char(alphabet[c3].to_int().unsafe_to_char())
|
||||
} else {
|
||||
buf.write_char('=')
|
||||
}
|
||||
@@ -60,8 +66,12 @@ pub fn base64_encode(data : Bytes) -> String {
|
||||
}
|
||||
|
||||
///|
|
||||
/// Decodes an I2P Base64 string (`-` and `~`, optional `=` padding) into `Bytes`.
|
||||
pub fn base64_decode(input : String) -> Bytes raise EncodingError {
|
||||
fn decode_b64_with_extras(
|
||||
input : String,
|
||||
c62 : Int32,
|
||||
c63 : Int32,
|
||||
label : String,
|
||||
) -> Bytes raise EncodingError {
|
||||
let chars : Array[Int32] = []
|
||||
for ch in input {
|
||||
let c = ch.to_int()
|
||||
@@ -75,7 +85,9 @@ pub fn base64_decode(input : String) -> Bytes raise EncodingError {
|
||||
return b""
|
||||
}
|
||||
if len % 4 != 0 {
|
||||
raise InvalidLength("I2P Base64 length must be a multiple of 4, got \{len}")
|
||||
raise InvalidLength(
|
||||
"\{label} Base64 length must be a multiple of 4, got \{len}",
|
||||
)
|
||||
}
|
||||
let out : Array[Byte] = Array(capacity=len / 4 * 3)
|
||||
let mut i = 0
|
||||
@@ -84,8 +96,8 @@ pub fn base64_decode(input : String) -> Bytes raise EncodingError {
|
||||
let c1 = chars[i + 1]
|
||||
let c2 = chars[i + 2]
|
||||
let c3 = chars[i + 3]
|
||||
let v0 = b64_decode_char(c0)
|
||||
let v1 = b64_decode_char(c1)
|
||||
let v0 = b64_decode_char_with_extras(c0, c62, c63, label)
|
||||
let v1 = b64_decode_char_with_extras(c1, c62, c63, label)
|
||||
let pad2 = c2 == 61 // '='
|
||||
let pad3 = c3 == 61 // '='
|
||||
if pad2 && !pad3 {
|
||||
@@ -94,8 +106,16 @@ pub fn base64_decode(input : String) -> Bytes raise EncodingError {
|
||||
if (pad2 || pad3) && i + 4 < len {
|
||||
raise InvalidCharacter("Base64 padding before end of input")
|
||||
}
|
||||
let v2 = if pad2 { 0 } else { b64_decode_char(c2) }
|
||||
let v3 = if pad3 { 0 } else { b64_decode_char(c3) }
|
||||
let v2 = if pad2 {
|
||||
0
|
||||
} else {
|
||||
b64_decode_char_with_extras(c2, c62, c63, label)
|
||||
}
|
||||
let v3 = if pad3 {
|
||||
0
|
||||
} else {
|
||||
b64_decode_char_with_extras(c3, c62, c63, label)
|
||||
}
|
||||
|
||||
out.push(((v0 << 2) | (v1 >> 4)).to_byte())
|
||||
if !pad2 {
|
||||
@@ -108,3 +128,27 @@ pub fn base64_decode(input : String) -> Bytes raise EncodingError {
|
||||
}
|
||||
Bytes::from_array(out)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Encodes bytes using the I2P Base64 alphabet (`-` and `~`, padded with `=`).
|
||||
pub fn base64_encode(data : Bytes) -> String {
|
||||
encode_b64_with_alphabet(data, i2p_b64_alphabet)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Decodes an I2P Base64 string (`-` and `~`, optional `=` padding) into `Bytes`.
|
||||
pub fn base64_decode(input : String) -> Bytes raise EncodingError {
|
||||
decode_b64_with_extras(input, 45, 126, "I2P")
|
||||
}
|
||||
|
||||
///|
|
||||
/// Encodes bytes using the standard RFC 4648 Base64 alphabet (`+` and `/`, padded with `=`).
|
||||
pub fn base64_std_encode(data : Bytes) -> String {
|
||||
encode_b64_with_alphabet(data, std_b64_alphabet)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Decodes a standard RFC 4648 Base64 string (`+` and `/`, `=` padding) into `Bytes`.
|
||||
pub fn base64_std_decode(input : String) -> Bytes raise EncodingError {
|
||||
decode_b64_with_extras(input, 43, 47, "standard")
|
||||
}
|
||||
@@ -122,3 +122,37 @@ test "crc32, gzip dynamic Huffman inflate, deflate/gzip round-trip, I2CP mux, an
|
||||
assert_eq(zip_entries[1].1.length(), 940)
|
||||
assert_eq(@encoding.crc32(zip_entries[1].1), 0x51eab753U)
|
||||
}
|
||||
|
||||
///|
|
||||
test "standard RFC 4648 base64 uses + and / and round-trips" {
|
||||
let raw = b"\xfb\xff\xfe"
|
||||
let encoded = @encoding.base64_std_encode(raw)
|
||||
assert_eq(encoded, "+//+")
|
||||
assert_eq(@encoding.base64_std_decode(encoded), raw)
|
||||
|
||||
let cases : Array[(Bytes, String)] = [
|
||||
(b"", ""),
|
||||
(b"f", "Zg=="),
|
||||
(b"fo", "Zm8="),
|
||||
(b"foo", "Zm9v"),
|
||||
(b"foob", "Zm9vYg=="),
|
||||
(b"fooba", "Zm9vYmE="),
|
||||
(b"foobar", "Zm9vYmFy"),
|
||||
]
|
||||
for item in cases {
|
||||
let (bytes, expected) = item
|
||||
assert_eq(@encoding.base64_std_encode(bytes), expected)
|
||||
assert_eq(@encoding.base64_std_decode(expected), bytes)
|
||||
}
|
||||
assert_eq(@encoding.base64_std_decode(" +//+ \n"), raw)
|
||||
|
||||
// I2P alphabet '-' / '~' is rejected by standard Base64 decoder
|
||||
let mut bad_rejected = false
|
||||
let _ = @encoding.base64_std_decode("-~~-") catch {
|
||||
_ => {
|
||||
bad_rejected = true
|
||||
b""
|
||||
}
|
||||
}
|
||||
assert_true(bad_rejected)
|
||||
}
|
||||
@@ -14,6 +14,10 @@ pub fn base64_decode(String) -> Bytes raise EncodingError
|
||||
|
||||
pub fn base64_encode(Bytes) -> String
|
||||
|
||||
pub fn base64_std_decode(String) -> Bytes raise EncodingError
|
||||
|
||||
pub fn base64_std_encode(Bytes) -> String
|
||||
|
||||
pub fn crc32(Bytes) -> UInt32
|
||||
|
||||
pub fn deflate_raw(Bytes) -> Bytes
|
||||
|
||||
@@ -13,3 +13,7 @@ keywords = [ "i2p", "cryptography", "networking", "privacy", "noise", "ntcp2" ]
|
||||
preferred_target = "wasm"
|
||||
|
||||
description = "Pure MoonBit port of the I2P (Invisible Internet Project) protocol suite"
|
||||
|
||||
import {
|
||||
"jqlssg/moonedn@0.1.2",
|
||||
}
|
||||
@@ -741,6 +741,63 @@ int32_t moon_i2p_net_read_file_at(
|
||||
return total;
|
||||
}
|
||||
|
||||
MOONBIT_FFI_EXPORT
|
||||
int32_t moon_i2p_net_write_file_atomic(
|
||||
moonbit_bytes_t path_bytes,
|
||||
int32_t path_len,
|
||||
moonbit_bytes_t data,
|
||||
int32_t data_len) {
|
||||
if (path_len <= 0 || path_len >= 960 || data_len < 0) {
|
||||
net_set_error("invalid write_file_atomic arguments");
|
||||
return -1;
|
||||
}
|
||||
char path[1024];
|
||||
memcpy(path, path_bytes, (size_t)path_len);
|
||||
path[path_len] = '\0';
|
||||
char tmp_path[1024];
|
||||
int tn = snprintf(tmp_path, sizeof(tmp_path), "%s.tmp.%ld", path, (long)getpid());
|
||||
if (tn <= 0 || (size_t)tn >= sizeof(tmp_path)) {
|
||||
net_set_error("atomic temp path too long");
|
||||
return -1;
|
||||
}
|
||||
int fd = open(tmp_path, O_CREAT | O_WRONLY | O_TRUNC, 0644);
|
||||
if (fd < 0) {
|
||||
net_set_error(strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
int32_t written = 0;
|
||||
while (written < data_len) {
|
||||
ssize_t n = write(fd, data + written, (size_t)(data_len - written));
|
||||
if (n < 0) {
|
||||
if (errno == EINTR) continue;
|
||||
net_set_error(strerror(errno));
|
||||
close(fd);
|
||||
unlink(tmp_path);
|
||||
return -1;
|
||||
}
|
||||
written += (int32_t)n;
|
||||
}
|
||||
while (fsync(fd) < 0) {
|
||||
if (errno == EINTR) continue;
|
||||
if (errno == EINVAL) break;
|
||||
net_set_error(strerror(errno));
|
||||
close(fd);
|
||||
unlink(tmp_path);
|
||||
return -1;
|
||||
}
|
||||
if (close(fd) < 0) {
|
||||
net_set_error(strerror(errno));
|
||||
unlink(tmp_path);
|
||||
return -1;
|
||||
}
|
||||
if (rename(tmp_path, path) < 0) {
|
||||
net_set_error(strerror(errno));
|
||||
unlink(tmp_path);
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
MOONBIT_FFI_EXPORT
|
||||
int32_t moon_i2p_net_home_dir(moonbit_bytes_t dst, int32_t max_len) {
|
||||
const char *home = getenv("HOME");
|
||||
|
||||
@@ -194,3 +194,21 @@ test "PendingNtcp2Dial/Accept stay non-blocking and Ntcp2Conn::send_blocks_nb tr
|
||||
bob_conn.close()
|
||||
listener.close()
|
||||
}
|
||||
|
||||
///|
|
||||
test "write_file_atomic and file_exists replace longer files cleanly" {
|
||||
let rand_hex = @encoding.hex_encode(@ntcp2_net.random_bytes(4))
|
||||
let dir = "/tmp/moon_i2p_atomic_test_\{rand_hex}"
|
||||
@ntcp2_net.mkdir_p(dir)
|
||||
let path = "\{dir}/torrents.edn"
|
||||
assert_true(!@ntcp2_net.file_exists(path))
|
||||
|
||||
let long_bytes = b"0123456789abcdef0123456789abcdef-long-payload"
|
||||
@ntcp2_net.write_file_atomic(path, long_bytes)
|
||||
assert_true(@ntcp2_net.file_exists(path))
|
||||
assert_eq(@ntcp2_net.read_file_bytes(path), long_bytes)
|
||||
|
||||
let short_bytes = b"{:version 1}\n"
|
||||
@ntcp2_net.write_file_atomic(path, short_bytes)
|
||||
assert_eq(@ntcp2_net.read_file_bytes(path), short_bytes)
|
||||
}
|
||||
@@ -170,6 +170,15 @@ extern "C" fn c_read_file_at(
|
||||
max_len : Int32,
|
||||
) -> Int32 = "moon_i2p_net_read_file_at"
|
||||
|
||||
///|
|
||||
#borrow(path, data)
|
||||
extern "C" fn c_write_file_atomic(
|
||||
path : Bytes,
|
||||
path_len : Int32,
|
||||
data : Bytes,
|
||||
data_len : Int32,
|
||||
) -> Int32 = "moon_i2p_net_write_file_atomic"
|
||||
|
||||
///|
|
||||
#borrow(dst)
|
||||
extern "C" fn c_home_dir(dst : FixedArray[Byte], max_len : Int32) -> Int32 = "moon_i2p_net_home_dir"
|
||||
@@ -320,6 +329,25 @@ pub fn read_file_at(
|
||||
Bytes::from_array(buf)[:got].to_owned()
|
||||
}
|
||||
|
||||
///|
|
||||
/// Atomically replaces `path` with `data` via temp-file write + `fsync` + `rename`.
|
||||
pub fn write_file_atomic(
|
||||
path : String,
|
||||
data : Bytes,
|
||||
) -> Unit raise Ntcp2NetError {
|
||||
let pb = @encoding.string_to_utf8_bytes(path)
|
||||
if c_write_file_atomic(pb, pb.length(), data, data.length()) < 0 {
|
||||
raise IoError("write_file_atomic(\{path}) failed: \{last_os_error()}")
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Returns `true` if `path` exists and can be `stat`ed.
|
||||
pub fn file_exists(path : String) -> Bool {
|
||||
let pb = @encoding.string_to_utf8_bytes(path)
|
||||
c_file_size(pb, pb.length()) >= 0
|
||||
}
|
||||
|
||||
///|
|
||||
/// Returns the `HOME` directory path, or empty string if unset.
|
||||
pub fn get_home_dir() -> String {
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
"experiments/moon_i2p/streaming",
|
||||
"experiments/moon_i2p/sam",
|
||||
"experiments/moon_i2p/bittorrent",
|
||||
"jqlssg/moonedn" @edn,
|
||||
}
|
||||
|
||||
supported_targets = "-all+native"
|
||||
@@ -852,3 +852,240 @@ test "POST /api/torrents/add accepts standard, URL-safe, and rejects invalid Bas
|
||||
assert_true(bad_resp.contains("400 Bad Request"))
|
||||
assert_true(bad_resp.contains("invalid torrent_b64"))
|
||||
}
|
||||
|
||||
///|
|
||||
test "torrent list persists and reloads from EDN state file across restarts" {
|
||||
let rand_hex = @encoding.hex_encode(@ntcp2_net.random_bytes(4))
|
||||
let base_dir = "/tmp/moon_i2p_edn_persist_test_\{rand_hex}"
|
||||
let dl_dir = "\{base_dir}/downloads"
|
||||
let state_file = "\{base_dir}/torrents.edn"
|
||||
@ntcp2_net.mkdir_p(dl_dir)
|
||||
|
||||
let make_single_torrent = fn(
|
||||
name : Bytes,
|
||||
payload : Bytes,
|
||||
) -> (Bytes, String) {
|
||||
let piece_len = 16384
|
||||
let hashes = @encoding.Writer::new()
|
||||
let mut off = 0
|
||||
while off < payload.length() {
|
||||
let end = if off + piece_len < payload.length() {
|
||||
off + piece_len
|
||||
} else {
|
||||
payload.length()
|
||||
}
|
||||
hashes.write_bytes(@crypto.sha1(payload[off:end].to_owned()))
|
||||
off = end
|
||||
}
|
||||
let tbytes = @bittorrent.bencode_encode(
|
||||
BDict([
|
||||
(b"announce", BBytes(b"http://tracker.insulaocculta.i2p/a")),
|
||||
(
|
||||
b"info",
|
||||
BDict([
|
||||
(b"length", BInt(payload.length().to_int64())),
|
||||
(b"name", BBytes(name)),
|
||||
(b"piece length", BInt(piece_len.to_int64())),
|
||||
(b"pieces", BBytes(hashes.to_bytes())),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
)
|
||||
let meta = @bittorrent.parse_torrent(tbytes) catch {
|
||||
_ => abort("bad test torrent")
|
||||
}
|
||||
(tbytes, @encoding.hex_encode(meta.info_hash))
|
||||
}
|
||||
|
||||
let payload1 = Bytes::make(32768, b'\x5A')
|
||||
@ntcp2_net.write_file_at(dl_dir + "/complete.bin", 0L, payload1)
|
||||
let (t1_bytes, ih1) = make_single_torrent(b"complete.bin", payload1)
|
||||
let (t2_bytes, ih2) = make_single_torrent(
|
||||
b"paused.bin",
|
||||
Bytes::make(16384, b'\x33'),
|
||||
)
|
||||
let (t3_bytes, ih3) = make_single_torrent(
|
||||
b"removed.bin",
|
||||
Bytes::make(16384, b'\x44'),
|
||||
)
|
||||
let ih4 = "0123456789abcdef0123456789abcdef01234567"
|
||||
|
||||
let r1 = @router.Router::start({
|
||||
sam_host: "127.0.0.1",
|
||||
sam_port: 0,
|
||||
ntcp2_host: "127.0.0.1",
|
||||
ntcp2_port: 0,
|
||||
})
|
||||
let api1 = r1.start_torrent_api(
|
||||
host="127.0.0.1",
|
||||
port=0,
|
||||
download_dir=dl_dir,
|
||||
state_file~,
|
||||
)
|
||||
let rs1 = [r1]
|
||||
|
||||
for tb in [t1_bytes, t2_bytes, t3_bytes] {
|
||||
let b64 = @encoding.base64_std_encode(tb)
|
||||
let resp = test_http_api_request(
|
||||
api1,
|
||||
rs1,
|
||||
"POST",
|
||||
"/api/torrents/add",
|
||||
"127.0.0.1:\{api1}",
|
||||
[("Content-Type", "application/json"), ("X-Moon-I2P", "1")],
|
||||
"{\"torrent_b64\":\"\{b64}\"}",
|
||||
)
|
||||
assert_true(resp.contains("200 OK"))
|
||||
}
|
||||
|
||||
let mag_resp = test_http_api_request(
|
||||
api1,
|
||||
rs1,
|
||||
"POST",
|
||||
"/api/torrents/magnet",
|
||||
"127.0.0.1:\{api1}",
|
||||
[("Content-Type", "application/json"), ("X-Moon-I2P", "1")],
|
||||
"{\"uri\":\"magnet:?xt=urn:btih:\{ih4}&dn=pending-mag&tr=http://tracker.insulaocculta.i2p/a\"}",
|
||||
)
|
||||
assert_true(mag_resp.contains("200 OK"))
|
||||
assert_true(mag_resp.contains(ih4))
|
||||
|
||||
let pause_resp = test_http_api_request(
|
||||
api1,
|
||||
rs1,
|
||||
"POST",
|
||||
"/api/torrents/pause",
|
||||
"127.0.0.1:\{api1}",
|
||||
[("Content-Type", "application/json"), ("X-Moon-I2P", "1")],
|
||||
"{\"info_hash\":\"\{ih2}\"}",
|
||||
)
|
||||
assert_true(pause_resp.contains("200 OK"))
|
||||
|
||||
let rm_resp = test_http_api_request(
|
||||
api1,
|
||||
rs1,
|
||||
"POST",
|
||||
"/api/torrents/remove",
|
||||
"127.0.0.1:\{api1}",
|
||||
[("Content-Type", "application/json"), ("X-Moon-I2P", "1")],
|
||||
"{\"info_hash\":\"\{ih3}\"}",
|
||||
)
|
||||
assert_true(rm_resp.contains("200 OK"))
|
||||
r1.close()
|
||||
|
||||
// Verify persisted EDN structure and contents on disk
|
||||
assert_true(@ntcp2_net.file_exists(state_file))
|
||||
let edn_text = @encoding.utf8_bytes_to_string(
|
||||
@ntcp2_net.read_file_bytes(state_file),
|
||||
)
|
||||
assert_true(!edn_text.contains(ih3))
|
||||
let limits : @edn.Limits = {
|
||||
input: 64 * 1024 * 1024,
|
||||
depth: 64,
|
||||
nodes: 1000000,
|
||||
token: 16 * 1024 * 1024,
|
||||
container: 100000,
|
||||
}
|
||||
let parsed = @edn.read(edn_text, limits~)
|
||||
match parsed {
|
||||
Mapping(root) => {
|
||||
let mut found_ver = false
|
||||
let mut count = -1
|
||||
for entry in root {
|
||||
match entry.0 {
|
||||
Keyword(k) if k == "version" =>
|
||||
match entry.1 {
|
||||
Integer(v) => {
|
||||
assert_eq(v, "1")
|
||||
found_ver = true
|
||||
}
|
||||
_ => fail("expected integer version")
|
||||
}
|
||||
Keyword(k) if k == "torrents" =>
|
||||
match entry.1 {
|
||||
Vector(items) => count = items.length()
|
||||
_ => fail("expected torrents vector")
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
assert_true(found_ver)
|
||||
assert_eq(count, 3)
|
||||
}
|
||||
_ => fail("expected EDN mapping at root")
|
||||
}
|
||||
|
||||
// Restart router 2 with the same state_file and verify full restoration
|
||||
let r2 = @router.Router::start({
|
||||
sam_host: "127.0.0.1",
|
||||
sam_port: 0,
|
||||
ntcp2_host: "127.0.0.1",
|
||||
ntcp2_port: 0,
|
||||
})
|
||||
defer r2.close()
|
||||
let api2 = r2.start_torrent_api(
|
||||
host="127.0.0.1",
|
||||
port=0,
|
||||
download_dir=dl_dir,
|
||||
state_file~,
|
||||
)
|
||||
let rs2 = [r2]
|
||||
|
||||
let status2 = test_http_api_request(
|
||||
api2,
|
||||
rs2,
|
||||
"GET",
|
||||
"/api/status",
|
||||
"127.0.0.1:\{api2}",
|
||||
[],
|
||||
"",
|
||||
)
|
||||
assert_true(status2.contains("\"torrent_count\":3"))
|
||||
assert_true(status2.contains("\"state_file\":\"\{state_file}\""))
|
||||
|
||||
let list2 = test_http_api_request(
|
||||
api2,
|
||||
rs2,
|
||||
"GET",
|
||||
"/api/torrents",
|
||||
"127.0.0.1:\{api2}",
|
||||
[],
|
||||
"",
|
||||
)
|
||||
assert_true(list2.contains(ih1))
|
||||
assert_true(list2.contains(ih2))
|
||||
assert_true(list2.contains(ih4))
|
||||
assert_true(!list2.contains(ih3))
|
||||
assert_true(list2.contains("\"downloaded_bytes\":32768"))
|
||||
assert_true(list2.contains("\"completed\":true"))
|
||||
assert_true(list2.contains("\"state\":\"paused\""))
|
||||
assert_true(list2.contains("\"state\":\"metadata\""))
|
||||
assert_true(list2.contains("\"name\":\"pending-mag\""))
|
||||
|
||||
// Verify corrupt EDN file does not crash startup
|
||||
let bad_state = "\{base_dir}/corrupt.edn"
|
||||
@ntcp2_net.write_file_atomic(bad_state, b"{broken edn")
|
||||
let r3 = @router.Router::start({
|
||||
sam_host: "127.0.0.1",
|
||||
sam_port: 0,
|
||||
ntcp2_host: "127.0.0.1",
|
||||
ntcp2_port: 0,
|
||||
})
|
||||
defer r3.close()
|
||||
let api3 = r3.start_torrent_api(
|
||||
host="127.0.0.1",
|
||||
port=0,
|
||||
download_dir=dl_dir,
|
||||
state_file=bad_state,
|
||||
)
|
||||
let status3 = test_http_api_request(
|
||||
api3,
|
||||
[r3],
|
||||
"GET",
|
||||
"/api/status",
|
||||
"127.0.0.1:\{api3}",
|
||||
[],
|
||||
"",
|
||||
)
|
||||
assert_true(status3.contains("\"torrent_count\":0"))
|
||||
}
|
||||
@@ -32,8 +32,9 @@ pub fn Router::start_torrent_api(
|
||||
host~ : String = "127.0.0.1",
|
||||
port~ : Int32 = 4445,
|
||||
download_dir~ : String = "",
|
||||
state_file~ : String = "",
|
||||
) -> Int32 raise RouterError {
|
||||
self.enable_torrent_engine(download_dir~)
|
||||
self.enable_torrent_engine(download_dir~, state_file~)
|
||||
match self.torrent_api_listener {
|
||||
Some(l) => return l.port
|
||||
None => ()
|
||||
@@ -336,6 +337,7 @@ fn Router::build_api_status_json(self : Router) -> String {
|
||||
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("\"state_file\":\"\{api_json_escape(eng.state_file)}\",")
|
||||
sb.write_string("\"torrent_count\":\{eng.torrents.length()},")
|
||||
sb.write_string("\"active_torrents\":\{active},")
|
||||
sb.write_string("\"completed_torrents\":\{seeding},")
|
||||
@@ -426,6 +428,8 @@ fn Router::build_api_torrents_json(self : Router) -> String {
|
||||
let inflight_bytes = inflight_blocks.to_int64() * 16384L
|
||||
let state_str = if t.error.length() > 0 {
|
||||
"error"
|
||||
} else if t.verify_cursor >= 0 {
|
||||
"checking"
|
||||
} else if t.paused {
|
||||
"paused"
|
||||
} else if t.completed {
|
||||
|
||||
+120
-19
@@ -91,6 +91,7 @@ priv struct ActiveTorrent {
|
||||
mut uploaded_bytes : UInt64
|
||||
mut have_pieces : Array[Bool]
|
||||
inflight_pieces : Array[ActivePieceBuf]
|
||||
mut verify_cursor : Int32
|
||||
mut meta_size : Int32
|
||||
meta_pieces : Array[(Int32, Bytes)]
|
||||
mut meta_req_ms : UInt64
|
||||
@@ -107,6 +108,7 @@ priv struct TorrentEngine {
|
||||
session_id : String
|
||||
peer_id : Bytes
|
||||
mut download_dir : String
|
||||
mut state_file : String
|
||||
dht : @bittorrent.I2pDht
|
||||
torrents : Array[ActiveTorrent]
|
||||
pending_inbound : Array[TorrentInboundConn]
|
||||
@@ -384,6 +386,29 @@ fn bt_read_span_from_files(
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn bt_verify_piece_at(
|
||||
t : ActiveTorrent,
|
||||
meta : @bittorrent.Metainfo,
|
||||
piece_idx : Int32,
|
||||
) -> Int32 {
|
||||
let plen = bt_piece_length(meta, piece_idx)
|
||||
match bt_read_span_from_files(t, piece_idx, 0, plen) {
|
||||
Some(pbytes) =>
|
||||
if @crypto.ct_eq(@crypto.sha1(pbytes), meta.piece_hashes[piece_idx]) {
|
||||
t.have_pieces[piece_idx] = true
|
||||
plen
|
||||
} else {
|
||||
t.have_pieces[piece_idx] = false
|
||||
0
|
||||
}
|
||||
None => {
|
||||
t.have_pieces[piece_idx] = false
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn bt_verify_existing_pieces(t : ActiveTorrent) -> Unit {
|
||||
let meta = match t.metainfo {
|
||||
@@ -397,20 +422,11 @@ fn bt_verify_existing_pieces(t : ActiveTorrent) -> Unit {
|
||||
let mut done_bytes = 0UL
|
||||
let mut all_have = num > 0
|
||||
for i = 0; i < num; i = i + 1 {
|
||||
let plen = bt_piece_length(meta, i)
|
||||
match bt_read_span_from_files(t, i, 0, plen) {
|
||||
Some(pbytes) =>
|
||||
if @crypto.ct_eq(@crypto.sha1(pbytes), meta.piece_hashes[i]) {
|
||||
t.have_pieces[i] = true
|
||||
done_bytes += plen.to_uint64()
|
||||
} else {
|
||||
t.have_pieces[i] = false
|
||||
all_have = false
|
||||
}
|
||||
None => {
|
||||
t.have_pieces[i] = false
|
||||
all_have = false
|
||||
}
|
||||
let verified_len = bt_verify_piece_at(t, meta, i)
|
||||
if verified_len > 0 {
|
||||
done_bytes += verified_len.to_uint64()
|
||||
} else {
|
||||
all_have = false
|
||||
}
|
||||
}
|
||||
t.downloaded_bytes = done_bytes
|
||||
@@ -421,6 +437,7 @@ fn bt_verify_existing_pieces(t : ActiveTorrent) -> Unit {
|
||||
fn bt_init_torrent_metainfo(
|
||||
t : ActiveTorrent,
|
||||
meta : @bittorrent.Metainfo,
|
||||
defer_verify~ : Bool = false,
|
||||
) -> Unit {
|
||||
t.name = meta.name
|
||||
t.raw_info = meta.raw_info
|
||||
@@ -430,7 +447,66 @@ fn bt_init_torrent_metainfo(
|
||||
for tr in meta.trackers {
|
||||
bt_add_tracker_url(t, tr)
|
||||
}
|
||||
bt_verify_existing_pieces(t)
|
||||
if defer_verify && meta.total_length > 16L * 1024L * 1024L {
|
||||
t.verify_cursor = 0
|
||||
t.downloaded_bytes = 0UL
|
||||
t.completed = false
|
||||
} else {
|
||||
t.verify_cursor = -1
|
||||
bt_verify_existing_pieces(t)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::bt_step_verify_pieces(self : Router, eng : TorrentEngine) -> Bool {
|
||||
for t in eng.torrents {
|
||||
if t.verify_cursor < 0 {
|
||||
continue
|
||||
}
|
||||
let meta = match t.metainfo {
|
||||
Some(m) => m
|
||||
None => {
|
||||
t.verify_cursor = -1
|
||||
return false
|
||||
}
|
||||
}
|
||||
let num = meta.piece_hashes.length()
|
||||
if t.have_pieces.length() != num {
|
||||
t.have_pieces = Array::make(num, false)
|
||||
}
|
||||
let mut checked_bytes = 0L
|
||||
let mut checked_any = false
|
||||
while t.verify_cursor < num &&
|
||||
(checked_bytes == 0L || checked_bytes < 4L * 1024L * 1024L) {
|
||||
let i = t.verify_cursor
|
||||
let plen = bt_piece_length(meta, i)
|
||||
let verified_len = bt_verify_piece_at(t, meta, i)
|
||||
if verified_len > 0 {
|
||||
t.downloaded_bytes += verified_len.to_uint64()
|
||||
}
|
||||
t.verify_cursor += 1
|
||||
checked_bytes += plen.to_int64()
|
||||
checked_any = true
|
||||
}
|
||||
if t.verify_cursor >= num {
|
||||
let mut all_have = num > 0
|
||||
for h in t.have_pieces {
|
||||
if !h {
|
||||
all_have = false
|
||||
break
|
||||
}
|
||||
}
|
||||
t.completed = all_have
|
||||
t.verify_cursor = -1
|
||||
if self.debug {
|
||||
println(
|
||||
"[debug] bt verified \{t.info_hash_hex[:12]} (\{t.downloaded_bytes}/\{meta.total_length}B, completed=\{t.completed})",
|
||||
)
|
||||
}
|
||||
}
|
||||
return checked_any
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
///|
|
||||
@@ -629,10 +705,12 @@ fn Router::ensure_torrent_session(self : Router) -> SamSession? {
|
||||
pub fn Router::enable_torrent_engine(
|
||||
self : Router,
|
||||
download_dir~ : String = "",
|
||||
state_file~ : String = "",
|
||||
dht_query_port~ : UInt32 = 6881U,
|
||||
dht_reply_port~ : UInt32 = 6882U,
|
||||
) -> Unit raise RouterError {
|
||||
let dl_trimmed = download_dir.trim().to_owned()
|
||||
let st_trimmed = state_file.trim().to_owned()
|
||||
let clean_dir = if dl_trimmed.length() > 0 {
|
||||
bt_normalize_dir(dl_trimmed)
|
||||
} else {
|
||||
@@ -644,6 +722,10 @@ pub fn Router::enable_torrent_engine(
|
||||
if dl_trimmed.length() > 0 {
|
||||
eng.download_dir = clean_dir
|
||||
}
|
||||
if st_trimmed.length() > 0 && eng.state_file != st_trimmed {
|
||||
eng.state_file = st_trimmed
|
||||
self.load_torrent_state()
|
||||
}
|
||||
return
|
||||
}
|
||||
None => ()
|
||||
@@ -671,6 +753,7 @@ pub fn Router::enable_torrent_engine(
|
||||
session_id: sess.id,
|
||||
peer_id: pw.to_bytes(),
|
||||
download_dir: clean_dir,
|
||||
state_file: st_trimmed,
|
||||
dht,
|
||||
torrents: [],
|
||||
pending_inbound: [],
|
||||
@@ -682,6 +765,9 @@ pub fn Router::enable_torrent_engine(
|
||||
last_ls2_pub_tunnels: self.tunnels.inbound.length(),
|
||||
ls2_gen: 1,
|
||||
})
|
||||
if st_trimmed.length() > 0 {
|
||||
self.load_torrent_state()
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
@@ -769,6 +855,7 @@ pub fn Router::add_torrent_bytes(
|
||||
bt_add_tracker_url(existing, tr)
|
||||
}
|
||||
existing.paused = false
|
||||
self.save_torrent_state()
|
||||
return hex
|
||||
}
|
||||
None => ()
|
||||
@@ -789,6 +876,7 @@ pub fn Router::add_torrent_bytes(
|
||||
uploaded_bytes: 0UL,
|
||||
have_pieces: Array::make(meta.piece_hashes.length(), false),
|
||||
inflight_pieces: [],
|
||||
verify_cursor: -1,
|
||||
meta_size: meta.raw_info.length(),
|
||||
meta_pieces: [],
|
||||
meta_req_ms: 0UL,
|
||||
@@ -805,6 +893,7 @@ pub fn Router::add_torrent_bytes(
|
||||
Some(sess) => eng.dht.store_peer(t.info_hash, sess.hash, now_ms)
|
||||
None => ()
|
||||
}
|
||||
self.save_torrent_state()
|
||||
if self.debug {
|
||||
println(
|
||||
"[debug] bt added torrent \{hex[:12]} '\{meta.name}' (\{meta.piece_hashes.length()} pcs, \{meta.total_length}B, \{t.trackers.length()} trackers)",
|
||||
@@ -859,6 +948,7 @@ pub fn Router::add_torrent_magnet(
|
||||
}
|
||||
}
|
||||
existing.paused = false
|
||||
self.save_torrent_state()
|
||||
return hex
|
||||
}
|
||||
None => ()
|
||||
@@ -883,6 +973,7 @@ pub fn Router::add_torrent_magnet(
|
||||
uploaded_bytes: 0UL,
|
||||
have_pieces: [],
|
||||
inflight_pieces: [],
|
||||
verify_cursor: -1,
|
||||
meta_size: 0,
|
||||
meta_pieces: [],
|
||||
meta_req_ms: 0UL,
|
||||
@@ -909,6 +1000,7 @@ pub fn Router::add_torrent_magnet(
|
||||
Some(sess) => eng.dht.store_peer(t.info_hash, sess.hash, now_ms)
|
||||
None => ()
|
||||
}
|
||||
self.save_torrent_state()
|
||||
if self.debug {
|
||||
println(
|
||||
"[debug] bt added magnet \{hex[:12]} '\{t.name}' (\{t.trackers.length()} trackers)",
|
||||
@@ -947,6 +1039,7 @@ pub fn Router::pause_torrent(self : Router, info_hash_hex : String) -> Bool {
|
||||
}
|
||||
}
|
||||
t.peers.clear()
|
||||
self.save_torrent_state()
|
||||
true
|
||||
}
|
||||
None => false
|
||||
@@ -966,6 +1059,7 @@ pub fn Router::resume_torrent(self : Router, info_hash_hex : String) -> Bool {
|
||||
for tr in t.trackers {
|
||||
tr.next_announce_ms = 0UL
|
||||
}
|
||||
self.save_torrent_state()
|
||||
true
|
||||
}
|
||||
None => false
|
||||
@@ -1009,6 +1103,7 @@ pub fn Router::remove_torrent(self : Router, info_hash_hex : String) -> Bool {
|
||||
}
|
||||
}
|
||||
let _ = eng.torrents.remove(i)
|
||||
self.save_torrent_state()
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -1576,7 +1671,7 @@ fn Router::step_dht(
|
||||
// Per-torrent DHT peer lookup & announce
|
||||
let query_cd_ms = if self.public_mode { 60000UL } else { 1500UL }
|
||||
for t in eng.torrents {
|
||||
if t.paused || eng.dht.nodes.length() == 0 {
|
||||
if t.paused || t.verify_cursor >= 0 || eng.dht.nodes.length() == 0 {
|
||||
continue
|
||||
}
|
||||
eng.dht.store_peer(t.info_hash, sess.hash, now_ms)
|
||||
@@ -1632,7 +1727,7 @@ fn Router::step_trackers(
|
||||
let now_sec = (now_ms / 1000UL).to_uint()
|
||||
let mut did_work = false
|
||||
for t in eng.torrents {
|
||||
if t.paused {
|
||||
if t.paused || t.verify_cursor >= 0 {
|
||||
continue
|
||||
}
|
||||
for tr in t.trackers {
|
||||
@@ -2155,6 +2250,7 @@ fn Router::bt_handle_ext_message(
|
||||
}
|
||||
bt_init_torrent_metainfo(t, parsed)
|
||||
t.meta_pieces.clear()
|
||||
self.save_torrent_state()
|
||||
} else {
|
||||
t.meta_pieces.clear()
|
||||
}
|
||||
@@ -2769,6 +2865,11 @@ fn Router::step_torrent_engine(self : Router) -> Bool {
|
||||
self.publish_session_leaseset2(sess)
|
||||
}
|
||||
|
||||
// 0b. Incremental piece verification for restored large torrents
|
||||
if self.bt_step_verify_pieces(eng) {
|
||||
did_work = true
|
||||
}
|
||||
|
||||
// 1. Poll I2P DHT datagrams (proto 0x11 + 0x12) and run DHT maintenance
|
||||
if self.poll_dht_datagrams(eng, sess, mgr, now_ms) {
|
||||
did_work = true
|
||||
@@ -2850,7 +2951,7 @@ fn Router::step_torrent_engine(self : Router) -> Bool {
|
||||
match parsed_hs {
|
||||
Some((_ext, ih, _remote_pid)) =>
|
||||
match bt_find_torrent_by_ih(eng, ih) {
|
||||
Some(t) if !t.paused => {
|
||||
Some(t) if !t.paused && t.verify_cursor < 0 => {
|
||||
let _ = bt_add_known_peer(t, ib.peer_hash, sess.hash)
|
||||
bt_pop_front_bytes(ib.recv_buf, 68)
|
||||
let rem_buf : Array[Byte] = []
|
||||
@@ -2935,7 +3036,7 @@ fn Router::step_torrent_engine(self : Router) -> Bool {
|
||||
|
||||
// 4. Spawn outbound peer connections and pump active peer swarms
|
||||
for t in eng.torrents {
|
||||
if t.paused {
|
||||
if t.paused || t.verify_cursor >= 0 {
|
||||
continue
|
||||
}
|
||||
// Spawn up to 16 peers per torrent when incomplete
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
///|
|
||||
/// EDN persistence (`torrents.edn`) for active and paused I2P BitTorrent entries.
|
||||
|
||||
///|
|
||||
/// Explicit `moonedn` limits large enough for torrents with multi-hundred-KiB `:info-b64` blobs.
|
||||
let bt_edn_limits : @edn.Limits = {
|
||||
input: 64 * 1024 * 1024,
|
||||
depth: 64,
|
||||
nodes: 1000000,
|
||||
token: 16 * 1024 * 1024,
|
||||
container: 100000,
|
||||
}
|
||||
|
||||
///|
|
||||
fn bt_parent_dir_of_file(path : String) -> String {
|
||||
let mut i = path.length() - 1
|
||||
while i >= 0 {
|
||||
if path[i] == '/' {
|
||||
if i == 0 {
|
||||
return "/"
|
||||
}
|
||||
return path[:i].to_owned()
|
||||
}
|
||||
i -= 1
|
||||
}
|
||||
""
|
||||
}
|
||||
|
||||
///|
|
||||
fn bt_edn_map_get_kw(
|
||||
entries : Array[(@edn.Value, @edn.Value)],
|
||||
kw : String,
|
||||
) -> @edn.Value? {
|
||||
for e in entries {
|
||||
match e.0 {
|
||||
Keyword(k) if k == kw => return Some(e.1)
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
///|
|
||||
fn bt_encode_torrents_edn(
|
||||
torrents : Array[ActiveTorrent],
|
||||
) -> String raise @edn.EdnError {
|
||||
let items : Array[@edn.Value] = Array(capacity=torrents.length())
|
||||
for t in torrents {
|
||||
let trackers : Array[@edn.Value] = Array(capacity=t.trackers.length())
|
||||
for tr in t.trackers {
|
||||
trackers.push(@edn.Value::Text(tr.url))
|
||||
}
|
||||
let fields : Array[(@edn.Value, @edn.Value)] = [
|
||||
(@edn.Value::Keyword("info-hash"), @edn.Value::Text(t.info_hash_hex)),
|
||||
(@edn.Value::Keyword("name"), @edn.Value::Text(t.name)),
|
||||
(@edn.Value::Keyword("download-dir"), @edn.Value::Text(t.download_dir)),
|
||||
(@edn.Value::Keyword("paused"), @edn.Value::Bool(t.paused)),
|
||||
(@edn.Value::Keyword("trackers"), @edn.Value::Vector(trackers)),
|
||||
]
|
||||
if t.raw_info.length() > 0 {
|
||||
fields.push(
|
||||
(
|
||||
@edn.Value::Keyword("info-b64"),
|
||||
@edn.Value::Text(@encoding.base64_std_encode(t.raw_info)),
|
||||
),
|
||||
)
|
||||
}
|
||||
items.push(@edn.Value::Mapping(fields))
|
||||
}
|
||||
let doc = @edn.Value::Mapping([
|
||||
(@edn.Value::Keyword("version"), @edn.Value::Integer("1")),
|
||||
(@edn.Value::Keyword("torrents"), @edn.Value::Vector(items)),
|
||||
])
|
||||
let body = @edn.pretty(
|
||||
doc,
|
||||
layout={ width: 100, indent: 2, },
|
||||
limits=bt_edn_limits,
|
||||
)
|
||||
";; moon-i2p torrent list (EDN) — restored on router startup\n" +
|
||||
body +
|
||||
"\n"
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::save_torrent_state(self : Router) -> Unit {
|
||||
let eng = match self.torrent_engine {
|
||||
Some(e) => e
|
||||
None => return
|
||||
}
|
||||
if eng.state_file.length() == 0 {
|
||||
return
|
||||
}
|
||||
let parent = bt_parent_dir_of_file(eng.state_file)
|
||||
if parent.length() > 0 {
|
||||
let _ = @ntcp2_net.mkdir_p(parent) catch {
|
||||
e => {
|
||||
println(
|
||||
"warning: failed to create torrent state dir \{parent}: \{bt_net_err_msg(e)}",
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
let encoded = bt_encode_torrents_edn(eng.torrents) catch {
|
||||
_ => {
|
||||
println("warning: failed to serialize torrent state to EDN")
|
||||
return
|
||||
}
|
||||
}
|
||||
let bytes = @encoding.string_to_utf8_bytes(encoded)
|
||||
@ntcp2_net.write_file_atomic(eng.state_file, bytes) catch {
|
||||
e =>
|
||||
println(
|
||||
"warning: failed to persist torrent state \{eng.state_file}: \{bt_net_err_msg(e)}",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::load_torrent_state(self : Router) -> Unit {
|
||||
let eng = match self.torrent_engine {
|
||||
Some(e) => e
|
||||
None => return
|
||||
}
|
||||
if eng.state_file.length() == 0 || !@ntcp2_net.file_exists(eng.state_file) {
|
||||
return
|
||||
}
|
||||
let raw = @ntcp2_net.read_file_bytes(eng.state_file) catch {
|
||||
e => {
|
||||
println(
|
||||
"warning: failed to read torrent state \{eng.state_file}: \{bt_net_err_msg(e)}",
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
let text = @encoding.utf8_bytes_to_string(raw) catch {
|
||||
_ => {
|
||||
println("warning: invalid UTF-8 in torrent state \{eng.state_file}")
|
||||
return
|
||||
}
|
||||
}
|
||||
let root = @edn.read(text, limits=bt_edn_limits) catch {
|
||||
_ => {
|
||||
println("warning: invalid EDN in torrent state \{eng.state_file}")
|
||||
return
|
||||
}
|
||||
}
|
||||
let root_entries = match root {
|
||||
Mapping(entries) => entries
|
||||
_ => {
|
||||
println("warning: torrent state \{eng.state_file} must be an EDN map")
|
||||
return
|
||||
}
|
||||
}
|
||||
match bt_edn_map_get_kw(root_entries, "version") {
|
||||
Some(Integer("1")) | None => ()
|
||||
Some(_) => {
|
||||
println("warning: unsupported torrent state version in \{eng.state_file}")
|
||||
return
|
||||
}
|
||||
}
|
||||
let items = match bt_edn_map_get_kw(root_entries, "torrents") {
|
||||
Some(Vector(v)) => v
|
||||
_ => return
|
||||
}
|
||||
let now_ms = @ntcp2_net.unix_time_ms()
|
||||
let mut restored = 0
|
||||
for item in items {
|
||||
let fields = match item {
|
||||
Mapping(f) => f
|
||||
_ => continue
|
||||
}
|
||||
let hex_raw = match bt_edn_map_get_kw(fields, "info-hash") {
|
||||
Some(Text(s)) => bt_hex_lower(s.trim().to_owned())
|
||||
_ => continue
|
||||
}
|
||||
let ih = @encoding.hex_decode(hex_raw) catch { _ => continue }
|
||||
if ih.length() != 20 {
|
||||
continue
|
||||
}
|
||||
if bt_find_torrent_by_ih(eng, ih) is Some(_) {
|
||||
continue
|
||||
}
|
||||
let name = match bt_edn_map_get_kw(fields, "name") {
|
||||
Some(Text(s)) if s.length() > 0 => s
|
||||
_ => hex_raw
|
||||
}
|
||||
let target_dir = match bt_edn_map_get_kw(fields, "download-dir") {
|
||||
Some(Text(s)) => {
|
||||
let trimmed = s.trim().to_owned()
|
||||
if trimmed.length() > 0 {
|
||||
let norm = bt_normalize_dir(trimmed)
|
||||
let mk_ok = try {
|
||||
@ntcp2_net.mkdir_p(norm)
|
||||
true
|
||||
} catch {
|
||||
_ => false
|
||||
}
|
||||
if mk_ok {
|
||||
norm
|
||||
} else {
|
||||
eng.download_dir
|
||||
}
|
||||
} else {
|
||||
eng.download_dir
|
||||
}
|
||||
}
|
||||
_ => eng.download_dir
|
||||
}
|
||||
let paused = match bt_edn_map_get_kw(fields, "paused") {
|
||||
Some(Bool(b)) => b
|
||||
_ => false
|
||||
}
|
||||
let tracker_urls : Array[String] = []
|
||||
match bt_edn_map_get_kw(fields, "trackers") {
|
||||
Some(Vector(tv)) =>
|
||||
for entry in tv {
|
||||
match entry {
|
||||
Text(u) if u.length() > 0 => tracker_urls.push(u)
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
let mut meta_opt : @bittorrent.Metainfo? = None
|
||||
match bt_edn_map_get_kw(fields, "info-b64") {
|
||||
Some(Text(b64)) if b64.length() > 0 => {
|
||||
let raw_opt = Some(@encoding.base64_std_decode(b64)) catch {
|
||||
_ => {
|
||||
println(
|
||||
"warning: invalid :info-b64 for \{hex_raw[:12]} in \{eng.state_file}",
|
||||
)
|
||||
None
|
||||
}
|
||||
}
|
||||
match raw_opt {
|
||||
Some(raw_info) =>
|
||||
if @crypto.ct_eq(@crypto.sha1(raw_info), ih) {
|
||||
meta_opt = Some(
|
||||
@bittorrent.parse_info_dict(raw_info, trackers=tracker_urls),
|
||||
) catch {
|
||||
e => {
|
||||
println(
|
||||
"warning: invalid metainfo for \{hex_raw[:12]}: \{bt_err_msg(e)}",
|
||||
)
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
println(
|
||||
"warning: info_hash mismatch for \{hex_raw[:12]} in \{eng.state_file}; restoring without metainfo",
|
||||
)
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
let t : ActiveTorrent = {
|
||||
info_hash: ih,
|
||||
info_hash_hex: hex_raw,
|
||||
name,
|
||||
download_dir: target_dir,
|
||||
metainfo: None,
|
||||
raw_info: b"",
|
||||
paused,
|
||||
completed: false,
|
||||
error: "",
|
||||
last_tracker_status: "",
|
||||
downloaded_bytes: 0UL,
|
||||
uploaded_bytes: 0UL,
|
||||
have_pieces: [],
|
||||
inflight_pieces: [],
|
||||
verify_cursor: -1,
|
||||
meta_size: 0,
|
||||
meta_pieces: [],
|
||||
meta_req_ms: 0UL,
|
||||
known_peers: [],
|
||||
peer_backoff: [],
|
||||
peers: [],
|
||||
trackers: [],
|
||||
last_dht_lookup_ms: 0UL,
|
||||
last_pex_ms: 0UL,
|
||||
}
|
||||
for tr in tracker_urls {
|
||||
bt_add_tracker_url(t, tr)
|
||||
}
|
||||
match meta_opt {
|
||||
Some(meta) => bt_init_torrent_metainfo(t, meta, defer_verify=true)
|
||||
None => ()
|
||||
}
|
||||
eng.torrents.push(t)
|
||||
match self.find_session_by_id(eng.session_id) {
|
||||
Some(sess) => eng.dht.store_peer(t.info_hash, sess.hash, now_ms)
|
||||
None => ()
|
||||
}
|
||||
restored += 1
|
||||
}
|
||||
if restored > 0 {
|
||||
println(" Restored \{restored} torrent(s) from \{eng.state_file}")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
///|
|
||||
test "bt_step_verify_pieces verifies multi-MiB torrent incrementally across ticks" {
|
||||
let rand_hex = @encoding.hex_encode(@ntcp2_net.random_bytes(4))
|
||||
let base_dir = "/tmp/moon_i2p_incr_verify_test_\{rand_hex}"
|
||||
@ntcp2_net.mkdir_p(base_dir)
|
||||
|
||||
let piece_len = 1048576
|
||||
let num_pieces = 5
|
||||
let total_len = piece_len * num_pieces
|
||||
let piece0 = Bytes::make(piece_len, b'\x11')
|
||||
let piece1 = Bytes::make(piece_len, b'\x22')
|
||||
let piece2 = Bytes::make(piece_len, b'\x33')
|
||||
let piece3 = Bytes::make(piece_len, b'\x44')
|
||||
let piece4 = Bytes::make(piece_len, b'\x55')
|
||||
let pieces_data = [piece0, piece1, piece2, piece3, piece4]
|
||||
|
||||
let hashes = @encoding.Writer::new()
|
||||
for i = 0; i < num_pieces; i = i + 1 {
|
||||
@ntcp2_net.write_file_at(
|
||||
base_dir + "/incr.bin",
|
||||
(i * piece_len).to_int64(),
|
||||
pieces_data[i],
|
||||
)
|
||||
hashes.write_bytes(@crypto.sha1(pieces_data[i]))
|
||||
}
|
||||
let tbytes = @bittorrent.bencode_encode(
|
||||
BDict([
|
||||
(
|
||||
b"info",
|
||||
BDict([
|
||||
(b"length", BInt(total_len.to_int64())),
|
||||
(b"name", BBytes(b"incr.bin")),
|
||||
(b"piece length", BInt(piece_len.to_int64())),
|
||||
(b"pieces", BBytes(hashes.to_bytes())),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
)
|
||||
let meta = @bittorrent.parse_torrent(tbytes)
|
||||
let r = Router::start({
|
||||
sam_host: "127.0.0.1",
|
||||
sam_port: 0,
|
||||
ntcp2_host: "127.0.0.1",
|
||||
ntcp2_port: 0,
|
||||
})
|
||||
defer r.close()
|
||||
r.enable_torrent_engine(download_dir=base_dir)
|
||||
let eng = match r.torrent_engine {
|
||||
Some(e) => e
|
||||
None => fail("missing torrent engine")
|
||||
}
|
||||
let hex = @encoding.hex_encode(meta.info_hash)
|
||||
let t : ActiveTorrent = {
|
||||
info_hash: meta.info_hash,
|
||||
info_hash_hex: hex,
|
||||
name: meta.name,
|
||||
download_dir: base_dir,
|
||||
metainfo: Some(meta),
|
||||
raw_info: meta.raw_info,
|
||||
paused: false,
|
||||
completed: false,
|
||||
error: "",
|
||||
last_tracker_status: "",
|
||||
downloaded_bytes: 0UL,
|
||||
uploaded_bytes: 0UL,
|
||||
have_pieces: Array::make(num_pieces, false),
|
||||
inflight_pieces: [],
|
||||
verify_cursor: 0,
|
||||
meta_size: meta.raw_info.length(),
|
||||
meta_pieces: [],
|
||||
meta_req_ms: 0UL,
|
||||
known_peers: [],
|
||||
peer_backoff: [],
|
||||
peers: [],
|
||||
trackers: [],
|
||||
last_dht_lookup_ms: 0UL,
|
||||
last_pex_ms: 0UL,
|
||||
}
|
||||
eng.torrents.push(t)
|
||||
|
||||
assert_true(r.build_api_torrents_json().contains("\"state\":\"checking\""))
|
||||
// Tick 1: 4 MiB budget verifies pieces 0..3 and leaves piece 4 pending
|
||||
assert_true(r.bt_step_verify_pieces(eng))
|
||||
assert_eq(t.verify_cursor, 4)
|
||||
assert_eq(t.downloaded_bytes, (4 * piece_len).to_uint64())
|
||||
assert_true(!t.completed)
|
||||
assert_true(r.build_api_torrents_json().contains("\"state\":\"checking\""))
|
||||
|
||||
// Tick 2: finishes piece 4 and clears checking state
|
||||
assert_true(r.bt_step_verify_pieces(eng))
|
||||
assert_eq(t.verify_cursor, -1)
|
||||
assert_eq(t.downloaded_bytes, total_len.to_uint64())
|
||||
assert_true(t.completed)
|
||||
assert_eq(t.have_pieces, [true, true, true, true, true])
|
||||
assert_true(r.build_api_torrents_json().contains("\"state\":\"seeding\""))
|
||||
assert_true(!r.bt_step_verify_pieces(eng))
|
||||
}
|
||||
|
||||
///|
|
||||
test "EDN persistence round-trips large >64 KiB info-b64 payloads" {
|
||||
let rand_hex = @encoding.hex_encode(@ntcp2_net.random_bytes(4))
|
||||
let base_dir = "/tmp/moon_i2p_large_edn_test_\{rand_hex}"
|
||||
let dl_dir = "\{base_dir}/dl"
|
||||
let state_file = "\{base_dir}/torrents.edn"
|
||||
@ntcp2_net.mkdir_p(dl_dir)
|
||||
|
||||
// 3,000 pieces * 20 bytes = 60,000-byte raw pieces => >60 KiB raw_info => >80 KiB base64 token
|
||||
let raw_pieces = Bytes::make(60000, b'\xAB')
|
||||
let tbytes = @bittorrent.bencode_encode(
|
||||
BDict([
|
||||
(b"announce", BBytes(b"http://tracker.insulaocculta.i2p/a")),
|
||||
(
|
||||
b"info",
|
||||
BDict([
|
||||
(b"length", BInt(3000L * 262144L)),
|
||||
(b"name", BBytes(b"large-catalog.bin")),
|
||||
(b"piece length", BInt(262144L)),
|
||||
(b"pieces", BBytes(raw_pieces)),
|
||||
]),
|
||||
),
|
||||
]),
|
||||
)
|
||||
let meta = @bittorrent.parse_torrent(tbytes)
|
||||
assert_true(@encoding.base64_std_encode(meta.raw_info).length() > 70000)
|
||||
|
||||
let r1 = Router::start({
|
||||
sam_host: "127.0.0.1",
|
||||
sam_port: 0,
|
||||
ntcp2_host: "127.0.0.1",
|
||||
ntcp2_port: 0,
|
||||
})
|
||||
r1.enable_torrent_engine(download_dir=dl_dir, state_file~)
|
||||
let ih = r1.add_torrent_bytes(tbytes, download_dir=dl_dir)
|
||||
r1.close()
|
||||
|
||||
let r2 = Router::start({
|
||||
sam_host: "127.0.0.1",
|
||||
sam_port: 0,
|
||||
ntcp2_host: "127.0.0.1",
|
||||
ntcp2_port: 0,
|
||||
})
|
||||
defer r2.close()
|
||||
r2.enable_torrent_engine(download_dir=dl_dir, state_file~)
|
||||
let eng2 = match r2.torrent_engine {
|
||||
Some(e) => e
|
||||
None => fail("missing eng2")
|
||||
}
|
||||
assert_eq(eng2.torrents.length(), 1)
|
||||
assert_eq(eng2.torrents[0].info_hash_hex, ih)
|
||||
assert_eq(eng2.torrents[0].raw_info, meta.raw_info)
|
||||
assert_eq(eng2.torrents[0].verify_cursor, 0)
|
||||
}
|
||||
@@ -411,6 +411,7 @@ printf '\n=== Moon I2P Browser start %s appdir=%s proxy=%s api=%s sam=%s ===\n'
|
||||
--http-proxy "127.0.0.1:$PROXY_PORT" \
|
||||
--torrent-api "127.0.0.1:$API_PORT" \
|
||||
--download-dir "$DOWNLOAD_DIR" \
|
||||
--torrent-state "$DATA_DIR/torrents.edn" \
|
||||
9>&- >> "$LOG_FILE" 2>&1 &
|
||||
ROUTER_PID=$!
|
||||
|
||||
|
||||
@@ -293,6 +293,7 @@ def handle_request(req: dict) -> dict:
|
||||
]
|
||||
if download_dir:
|
||||
args.extend(["--download-dir", download_dir])
|
||||
args.extend(["--torrent-state", str(resolve_data_dir() / "torrents.edn")])
|
||||
with open(LOG_FILE, "ab") as log_fp:
|
||||
proc = subprocess.Popen(
|
||||
args,
|
||||
|
||||
Reference in new issue
Block a user