Files
moon-i2p/cmd/router/main.mbt
T
nandi dd5b132b5a
Rolling Release / Test (MoonBit, Extension, Scripts) (push) Successful in 21s
Rolling Release / Build & Publish Rolling Release (push) Successful in 2m20s
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.
2026-11-29 02:46:23 -08:00

492 lines
13 KiB
MoonBit

///|
fn parse_port(s : String) -> Int32? {
if s.length() == 0 {
return None
}
let mut v = 0
for i = 0; i < s.length(); i = i + 1 {
let c = s[i].to_int()
if c < 48 || c > 57 {
return None
}
v = v * 10 + (c - 48)
}
if v >= 0 && v <= 65535 {
Some(v)
} else {
None
}
}
///|
fn split_host_port(spec : String) -> (String, Int32)? {
let mut colon = -1
for i = 0; i < spec.length(); i = i + 1 {
if spec[i] == ':' {
colon = i
}
}
if colon <= 0 {
return None
}
let host = spec[:colon].to_owned()
let port_s = spec[colon + 1:].to_owned()
match parse_port(port_s) {
Some(p) => Some((host, p))
None => None
}
}
///|
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")
println("")
println("Usage:")
println(" router.exe [options]")
println("")
println("Options:")
println(
" --sam <host:port> SAMv3 TCP listen address (default: 127.0.0.1:7656)",
)
println(
" --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(
" --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(
" --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)",
)
println(
" --ntcp2-port <port> NTCP2 TCP listen port (default: 0 = ephemeral)",
)
println(
" --public Join live public I2P network (auto-reseed + tunnels + NetDB)",
)
println(
" --hops <1..4> Inbound/Outbound tunnel hop count (default: 1)",
)
println(
" --hosts <hosts.txt> Load hostname=dest_or_b32 aliases into addressbook",
)
println(" --peer <ri.dat> Load a RouterInfo file into NetDB")
println(
" --peer-dir <dir> Load RouterInfo files from directory into NetDB",
)
println(
" --su3 <i2pseeds.su3> Import peers from local .su3 reseed file",
)
println(
" --reseed <https://...> Import peers from an HTTPS .su3 reseed URL",
)
println(" --floodfill Advertise LRf floodfill capabilities")
println(" --no-clock-skew Disable NTCP2 clock skew check")
println(" --debug Enable verbose router debug logs")
println(" -h, --help Show this help message")
}
///|
fn main {
let args = @env.args()
let mut sam_host = "127.0.0.1"
let mut sam_port = 7656
let mut http_proxy_enabled = false
let mut http_proxy_host = "127.0.0.1"
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 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
let mut check_clock_skew = true
let mut public_mode = false
let mut tunnel_hops = 1
let mut debug = false
let peer_files : Array[String] = []
let peer_dirs : Array[String] = []
let su3_files : Array[String] = []
let reseed_urls : Array[String] = []
let hosts_files : Array[String] = []
let mut i = 1
while i < args.length() {
match args[i] {
"-h" | "--help" => {
print_usage()
return
}
"--sam" =>
if i + 1 < args.length() {
match split_host_port(args[i + 1]) {
Some((h, p)) => {
sam_host = h
sam_port = p
}
None => println("warning: ignoring invalid --sam \{args[i + 1]}")
}
i += 2
} else {
i += 1
}
"--http-proxy" | "--proxy" => {
http_proxy_enabled = true
if i + 1 < args.length() && !args[i + 1].has_prefix("-") {
match split_host_port(args[i + 1]) {
Some((h, p)) => {
http_proxy_host = h
http_proxy_port = p
i += 2
}
None =>
match parse_port(args[i + 1]) {
Some(p) => {
http_proxy_port = p
i += 2
}
None => i += 1
}
}
} else {
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
}
"--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]) {
Some(p) => ntcp2_port = p
None => println("warning: ignoring invalid --ntcp2-port")
}
i += 2
} else {
i += 1
}
"--ntcp2-host" =>
if i + 1 < args.length() {
ntcp2_host = args[i + 1]
i += 2
} else {
i += 1
}
"--peer" =>
if i + 1 < args.length() {
peer_files.push(args[i + 1])
i += 2
} else {
i += 1
}
"--peer-dir" =>
if i + 1 < args.length() {
peer_dirs.push(args[i + 1])
i += 2
} else {
i += 1
}
"--su3" =>
if i + 1 < args.length() {
su3_files.push(args[i + 1])
i += 2
} else {
i += 1
}
"--reseed" =>
if i + 1 < args.length() {
reseed_urls.push(args[i + 1])
i += 2
} else {
i += 1
}
"--hosts" =>
if i + 1 < args.length() {
hosts_files.push(args[i + 1])
i += 2
} else {
i += 1
}
"--hops" =>
if i + 1 < args.length() {
match parse_port(args[i + 1]) {
Some(h) if h >= 1 && h <= 4 => tunnel_hops = h
_ => println("warning: ignoring invalid --hops \{args[i + 1]}")
}
i += 2
} else {
i += 1
}
"--public" => {
public_mode = true
i += 1
}
"--debug" => {
debug = true
i += 1
}
"--floodfill" => {
floodfill = true
i += 1
}
"--no-clock-skew" => {
check_clock_skew = false
i += 1
}
_ =>
if args[i].has_prefix("--http-proxy=") {
http_proxy_enabled = true
let spec = args[i][13:].to_owned()
match split_host_port(spec) {
Some((h, p)) => {
http_proxy_host = h
http_proxy_port = p
}
None =>
match parse_port(spec) {
Some(p) => http_proxy_port = p
None =>
println("warning: ignoring invalid --http-proxy \{spec}")
}
}
i += 1
} else if args[i].has_prefix("--torrent-state=") {
torrent_state = args[i][16:].to_owned()
i += 1
} else {
i += 1
}
}
}
let r = @i2p_router.Router::start(
{ sam_host, sam_port, ntcp2_host, ntcp2_port, },
floodfill~,
check_clock_skew~,
public_mode~,
tunnel_hops~,
debug~,
) catch {
_ => {
println("error: failed to start moon-i2p router")
return
}
}
if http_proxy_enabled {
let _ = r.start_http_proxy(host=http_proxy_host, port=http_proxy_port) catch {
_ => {
r.close()
println(
"error: failed to bind HTTP proxy on \{http_proxy_host}:\{http_proxy_port}",
)
return
}
}
}
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()
println(
"error: failed to bind Torrent API on \{torrent_api_host}:\{torrent_api_port}",
)
return
}
}
}
for pf in peer_files {
let _ = r.load_peer_file(pf) catch {
_ => {
println("warning: failed to load peer RouterInfo from \{pf}")
continue
}
}
}
for pd in peer_dirs {
let n = r.load_peer_dir(pd) catch {
_ => {
println("warning: failed to load peer dir \{pd}")
continue
}
}
println(" Loaded \{n} peer(s) from \{pd}")
}
for sf in su3_files {
let n = r.load_reseed_su3_file(sf) catch {
_ => {
println("warning: failed to load reseed .su3 from \{sf}")
continue
}
}
println(" Imported \{n} peer(s) from \{sf}")
}
for url in reseed_urls {
let n = r.reseed_from_url(url) catch {
_ => {
println("warning: reseed fetch failed for \{url}")
continue
}
}
println(" Reseeded \{n} peer(s) from \{url}")
}
if public_mode &&
reseed_urls.length() == 0 &&
su3_files.length() == 0 &&
peer_files.length() == 0 &&
peer_dirs.length() == 0 {
println("Reseeding from public I2P network...")
let _ = r.auto_reseed()
}
for hf in hosts_files {
let n = r.load_hosts_file(hf) catch {
_ => {
println("warning: failed to load hosts file \{hf}")
continue
}
}
println(" Loaded \{n} host alias(es) from \{hf}")
}
println("moon-i2p router started (transient identity)")
println(" Router Hash: \{r.router_hash().to_base64()}")
println(" Router B32: \{r.router_hash().to_b32_address()}")
println(
" NTCP2: \{ntcp2_host}:\{r.ntcp2_port()} (public=\{public_mode}, hops=\{tunnel_hops})",
)
println(" SAMv3: \{sam_host}:\{r.sam_port()}")
if http_proxy_enabled {
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()})",
)
if effective_state_file.length() > 0 {
println(" Torrent State: \{effective_state_file}")
}
}
println(
" NetDB peers: \{r.netdb.router_count()} (floodfills=\{r.netdb.floodfill_count()})",
)
@ntcp2_net.flush_stdout()
if public_mode {
let mut last_log_ms = @ntcp2_net.unix_time_ms()
while true {
r.step(poll_ms=10)
let now_ms = @ntcp2_net.unix_time_ms()
if now_ms >= last_log_ms + 5000UL {
last_log_ms = now_ms
println(
"[public] peers=\{r.peer_count()} dials=\{r.pending_dial_count()} netdb=\{r.netdb.router_count()}(ff=\{r.netdb.floodfill_count()},ls=\{r.netdb.leaseset_count()}) tunnels=in:\{r.inbound_tunnel_count()}/out:\{r.outbound_tunnel_count()} builds=\{r.pending_build_count()}",
)
@ntcp2_net.flush_stdout()
}
}
} else {
r.run()
}
}