- 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.
303 lines
7.9 KiB
MoonBit
303 lines
7.9 KiB
MoonBit
///|
|
|
/// 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}")
|
|
}
|
|
}
|