feat: add working native SAMv3 TCP client and CLI with sane defaults
This commit is contained in:
1 parent
e527b84bc3
commit
4d79d78f06
13 files changed
+1910
-11
No files matched your search
@@ -12,7 +12,10 @@ moon-i2p/
|
|||||||
├── i2np/ # 16-byte standard & 9-byte NTCP2 short headers, SHA-256 checksums, core I2NP messages
|
├── i2np/ # 16-byte standard & 9-byte NTCP2 short headers, SHA-256 checksums, core I2NP messages
|
||||||
├── noise/ # Noise_XK_25519_ChaChaPoly_SHA256 handshake/transport + NTCP2 SipHash-2-4 length masking
|
├── noise/ # Noise_XK_25519_ChaChaPoly_SHA256 handshake/transport + NTCP2 SipHash-2-4 length masking
|
||||||
├── sam/ # SAMv3 text protocol parser, serializer, and command builders
|
├── sam/ # SAMv3 text protocol parser, serializer, and command builders
|
||||||
└── cmd/main/ # Demo CLI entrypoint
|
├── sam_client/ # Native POSIX TCP SAMv3 client with sane modern I2P defaults
|
||||||
|
├── cmd/main/ # Pure protocol demo CLI entrypoint
|
||||||
|
├── cmd/client/ # Native SAMv3 CLI (`keygen`, `lookup`, `http-get`, `dial`, `listen`)
|
||||||
|
└── scripts/ # Loopback SAMv3 bridge (`mock_sam.py`) and end-to-end test (`e2e_test.py`)
|
||||||
```
|
```
|
||||||
|
|
||||||
### Verified Test Vectors
|
### Verified Test Vectors
|
||||||
@@ -24,24 +27,54 @@ Every cryptographic primitive in `crypto/` is verified against official standard
|
|||||||
- **X25519**: RFC 7748 Sections 5.2 & 6.1
|
- **X25519**: RFC 7748 Sections 5.2 & 6.1
|
||||||
- **SipHash-2-4**: Official SipHash reference test vector
|
- **SipHash-2-4**: Official SipHash reference test vector
|
||||||
|
|
||||||
|
## Running the SAMv3 Client (Native)
|
||||||
|
|
||||||
|
The native client (`cmd/client`) connects to an I2P SAMv3 bridge with sane modern defaults:
|
||||||
|
- **Bridge:** `127.0.0.1:7656` (override with `--sam <host:port>` or `I2P_SAM_HOST` / `I2P_SAM_PORT`)
|
||||||
|
- **Protocol:** SAM `3.1`–`3.3`
|
||||||
|
- **Keys:** `TRANSIENT` destination, `SIGNATURE_TYPE=7` (`EdDSA_SHA512_Ed25519`)
|
||||||
|
- **I2CP Tunnel Defaults:** `i2cp.leaseSetEncType=4,0` (ECIES-X25519 preferred), 3-hop / 3-tunnel inbound & outbound pools
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Build the native client binary
|
||||||
|
moon build --target native cmd/client
|
||||||
|
|
||||||
|
# Start an I2P router with SAMv3 enabled (e.g. i2pd --sam.enabled=true)
|
||||||
|
# or use the bundled local loopback SAMv3 bridge for testing:
|
||||||
|
# python3 scripts/mock_sam.py
|
||||||
|
|
||||||
|
# Generate a new Ed25519 I2P destination
|
||||||
|
./_build/native/debug/build/cmd/client/client.exe keygen
|
||||||
|
|
||||||
|
# Resolve an I2P hostname
|
||||||
|
./_build/native/debug/build/cmd/client/client.exe lookup stats.i2p
|
||||||
|
|
||||||
|
# Fetch an eepsite over a transient STREAM session
|
||||||
|
./_build/native/debug/build/cmd/client/client.exe http-get stats.i2p /
|
||||||
|
|
||||||
|
# Peer-to-peer STREAM listener and dialer
|
||||||
|
./_build/native/debug/build/cmd/client/client.exe listen "hello back"
|
||||||
|
./_build/native/debug/build/cmd/client/client.exe dial <listener.b32.i2p> "hello over i2p"
|
||||||
|
```
|
||||||
|
|
||||||
## Running Checks & Tests
|
## Running Checks & Tests
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
moon check
|
moon check --target wasm
|
||||||
moon test
|
moon test --target wasm
|
||||||
|
moon check --target native
|
||||||
moon test --target native
|
moon test --target native
|
||||||
moon run cmd/main
|
moon build --target native cmd/client && python3 scripts/e2e_test.py
|
||||||
```
|
```
|
||||||
|
|
||||||
## Roadmap
|
## Roadmap
|
||||||
|
|
||||||
1. **Phase 1–2 (Completed):** Core encoding, pure-MoonBit modern crypto, I2P Common Structures, I2NP messages, `Noise_XK_25519_ChaChaPoly_SHA256` state machine, NTCP2 SipHash length masking, and SAMv3 protocol codec.
|
1. **Phase 1–2 (Completed):** Core encoding, pure-MoonBit modern crypto, I2P Common Structures, I2NP messages, `Noise_XK_25519_ChaChaPoly_SHA256` state machine, NTCP2 SipHash length masking, SAMv3 protocol codec, and working native SAMv3 TCP client + CLI (`sam_client/`, `cmd/client/`).
|
||||||
2. **Phase 3 (Signatures & Ratchet):**
|
2. **Phase 3 (Signatures & Ratchet):**
|
||||||
- Pure-MoonBit **Ed25519** signing & verification (`RouterInfo` & `LeaseSet2` signatures).
|
- Pure-MoonBit **Ed25519** signing & verification (`RouterInfo` & `LeaseSet2` signatures).
|
||||||
- **ECIES-X25519-AEAD-Ratchet** (Proposal 144) for Garlic encryption & end-to-end sessions.
|
- **ECIES-X25519-AEAD-Ratchet** (Proposal 144) for Garlic encryption & end-to-end sessions.
|
||||||
3. **Phase 4 (Transports & Networking):**
|
3. **Phase 4 (Direct Transports):**
|
||||||
- **NTCP2** full TCP transport (AES-256-CBC ephemeral key obfuscation, options/padding blocks, session manager).
|
- **NTCP2** full TCP transport (AES-256-CBC ephemeral key obfuscation, options/padding blocks, session manager).
|
||||||
- **SAMv3** live TCP client for interacting with an existing I2P/i2pd router.
|
|
||||||
4. **Phase 5 (Router Core):**
|
4. **Phase 5 (Router Core):**
|
||||||
- **NetDB** & Floodfill DHT (Kademlia XOR routing with daily routing key derivation).
|
- **NetDB** & Floodfill DHT (Kademlia XOR routing with daily routing key derivation).
|
||||||
- **Tunnel** builder (`ShortTunnelBuild` Proposal 157), layered tunnel encryption, and tunnel pool management.
|
- **Tunnel** builder (`ShortTunnelBuild` Proposal 157), layered tunnel encryption, and tunnel pool management.
|
||||||
|
|||||||
@@ -0,0 +1,253 @@
|
|||||||
|
///|
|
||||||
|
fn print_usage() -> Unit {
|
||||||
|
println("moon-i2p SAMv3 client (native)")
|
||||||
|
println("")
|
||||||
|
println("Usage:")
|
||||||
|
println(" moon-i2p [--sam <host:port>] <command> [args...]")
|
||||||
|
println("")
|
||||||
|
println("Commands:")
|
||||||
|
println(
|
||||||
|
" keygen Generate a new Ed25519 I2P destination",
|
||||||
|
)
|
||||||
|
println(
|
||||||
|
" lookup <name.i2p> Resolve a .i2p hostname via SAM NAMING LOOKUP",
|
||||||
|
)
|
||||||
|
println(
|
||||||
|
" http-get <host.i2p> [path] HTTP/1.1 GET over a transient I2P STREAM session",
|
||||||
|
)
|
||||||
|
println(
|
||||||
|
" dial <dest-or-host.i2p> [msg] Connect via I2P STREAM, send msg (or stdin), print reply",
|
||||||
|
)
|
||||||
|
println(
|
||||||
|
" listen [reply] Accept one I2P STREAM connection, print data, optionally reply",
|
||||||
|
)
|
||||||
|
println("")
|
||||||
|
println("Options:")
|
||||||
|
println(
|
||||||
|
" --sam <host:port> SAMv3 bridge address (default: 127.0.0.1:7656)",
|
||||||
|
)
|
||||||
|
println(" -h, --help Show this help message")
|
||||||
|
println("")
|
||||||
|
println("Environment:")
|
||||||
|
println(
|
||||||
|
" I2P_SAM_HOST SAMv3 bridge host (default: 127.0.0.1)",
|
||||||
|
)
|
||||||
|
println(" I2P_SAM_PORT SAMv3 bridge port (default: 7656)")
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn print_error_and_exit(err : @sam_client.SamClientError) -> Unit {
|
||||||
|
println("Error: \{err.message()}")
|
||||||
|
match err {
|
||||||
|
ConnectFailed(_, _, _) => {
|
||||||
|
println("")
|
||||||
|
println(
|
||||||
|
"Hint: Make sure an I2P router with SAMv3 enabled is running, e.g.:",
|
||||||
|
)
|
||||||
|
println(" i2pd --sam.enabled=true")
|
||||||
|
println("Or point to another SAMv3 bridge with:")
|
||||||
|
println(" I2P_SAM_HOST=<host> I2P_SAM_PORT=<port>")
|
||||||
|
println(" --sam <host>:<port>")
|
||||||
|
}
|
||||||
|
_ => ()
|
||||||
|
}
|
||||||
|
@env.exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn bytes_to_display_string(raw : Bytes) -> String {
|
||||||
|
@encoding.utf8_bytes_to_string(raw) catch {
|
||||||
|
_ => "<binary \{raw.length()} bytes: \{@encoding.hex_encode(raw)}>"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn cmd_keygen(
|
||||||
|
config : @sam_client.SamConfig,
|
||||||
|
) -> Unit raise @sam_client.SamClientError {
|
||||||
|
let client = @sam_client.SamClient::connect(config~)
|
||||||
|
defer client.close()
|
||||||
|
let dest = client.dest_generate()
|
||||||
|
println("SAM Version: \{client.version()}")
|
||||||
|
println("B32 Address: \{dest.b32_address}")
|
||||||
|
println("Public: \{dest.pub_b64}")
|
||||||
|
match dest.priv_b64 {
|
||||||
|
Some(priv_key) => println("Private: \{priv_key}")
|
||||||
|
None => ()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn cmd_lookup(
|
||||||
|
config : @sam_client.SamConfig,
|
||||||
|
name : String,
|
||||||
|
) -> Unit raise @sam_client.SamClientError {
|
||||||
|
let client = @sam_client.SamClient::connect(config~)
|
||||||
|
defer client.close()
|
||||||
|
let dest = client.naming_lookup(name)
|
||||||
|
println("Name: \{name}")
|
||||||
|
println("B32 Address: \{dest.b32_address}")
|
||||||
|
println("Destination: \{dest.pub_b64}")
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn cmd_http_get(
|
||||||
|
config : @sam_client.SamConfig,
|
||||||
|
host : String,
|
||||||
|
path : String,
|
||||||
|
) -> Unit raise @sam_client.SamClientError {
|
||||||
|
let client = @sam_client.SamClient::connect(config~)
|
||||||
|
let session = client.session_create()
|
||||||
|
defer session.close()
|
||||||
|
let resp = session.http_get(host, path~)
|
||||||
|
println(bytes_to_display_string(resp))
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn cmd_dial(
|
||||||
|
config : @sam_client.SamConfig,
|
||||||
|
target : String,
|
||||||
|
message : String?,
|
||||||
|
) -> Unit raise @sam_client.SamClientError {
|
||||||
|
let payload = match message {
|
||||||
|
Some(m) => @encoding.string_to_utf8_bytes(m)
|
||||||
|
None => @sam_client.read_all_stdin()
|
||||||
|
}
|
||||||
|
let client = @sam_client.SamClient::connect(config~)
|
||||||
|
let session = client.session_create()
|
||||||
|
defer session.close()
|
||||||
|
let stream = session.stream_connect(target)
|
||||||
|
defer stream.close()
|
||||||
|
if payload.length() > 0 {
|
||||||
|
stream.write_all(payload)
|
||||||
|
}
|
||||||
|
stream.shutdown_write()
|
||||||
|
let resp = stream.read_all()
|
||||||
|
if resp.length() > 0 {
|
||||||
|
println(bytes_to_display_string(resp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn cmd_listen(
|
||||||
|
config : @sam_client.SamConfig,
|
||||||
|
reply : String?,
|
||||||
|
) -> Unit raise @sam_client.SamClientError {
|
||||||
|
let client = @sam_client.SamClient::connect(config~)
|
||||||
|
let session = client.session_create()
|
||||||
|
defer session.close()
|
||||||
|
println("Session ID: \{session.id()}")
|
||||||
|
println("B32 Address: \{session.b32_address()}")
|
||||||
|
println("Destination: \{session.destination().pub_b64}")
|
||||||
|
println("Waiting for incoming I2P stream...")
|
||||||
|
@sam_client.flush_stdout()
|
||||||
|
let (peer, stream) = session.stream_accept()
|
||||||
|
defer stream.close()
|
||||||
|
println("Accepted from: \{peer.b32_address}")
|
||||||
|
@sam_client.flush_stdout()
|
||||||
|
let incoming = stream.read_all()
|
||||||
|
if incoming.length() > 0 {
|
||||||
|
println("Received: \{bytes_to_display_string(incoming)}")
|
||||||
|
}
|
||||||
|
match reply {
|
||||||
|
Some(r) => {
|
||||||
|
stream.write_string(r)
|
||||||
|
stream.shutdown_write()
|
||||||
|
}
|
||||||
|
None => ()
|
||||||
|
}
|
||||||
|
@sam_client.flush_stdout()
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn strip_prefix(s : String, prefix : String) -> String? {
|
||||||
|
if !s.has_prefix(prefix) {
|
||||||
|
return None
|
||||||
|
}
|
||||||
|
let chars : Array[Char] = []
|
||||||
|
for ch in s {
|
||||||
|
chars.push(ch)
|
||||||
|
}
|
||||||
|
let buf = StringBuilder()
|
||||||
|
for i = prefix.length(); i < chars.length(); i = i + 1 {
|
||||||
|
buf.write_char(chars[i])
|
||||||
|
}
|
||||||
|
Some(buf.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn run_cli() -> Unit raise @sam_client.SamClientError {
|
||||||
|
let raw_args = @env.args()
|
||||||
|
let mut config = @sam_client.SamConfig::from_env()
|
||||||
|
let positional : Array[String] = []
|
||||||
|
let mut i = 1
|
||||||
|
while i < raw_args.length() {
|
||||||
|
let arg = raw_args[i]
|
||||||
|
if arg == "-h" || arg == "--help" {
|
||||||
|
print_usage()
|
||||||
|
return
|
||||||
|
} else if arg == "--sam" {
|
||||||
|
i += 1
|
||||||
|
if i >= raw_args.length() {
|
||||||
|
println("Error: missing value after --sam")
|
||||||
|
@env.exit(2)
|
||||||
|
}
|
||||||
|
config = config.with_address(raw_args[i])
|
||||||
|
} else {
|
||||||
|
match strip_prefix(arg, "--sam=") {
|
||||||
|
Some(addr) => config = config.with_address(addr)
|
||||||
|
None => positional.push(arg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
i += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
if positional.length() == 0 {
|
||||||
|
print_usage()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let cmd = positional[0]
|
||||||
|
if cmd == "keygen" {
|
||||||
|
cmd_keygen(config)
|
||||||
|
} else if cmd == "lookup" {
|
||||||
|
if positional.length() < 2 {
|
||||||
|
println("Usage: moon-i2p lookup <name.i2p>")
|
||||||
|
@env.exit(2)
|
||||||
|
}
|
||||||
|
cmd_lookup(config, positional[1])
|
||||||
|
} else if cmd == "http-get" {
|
||||||
|
if positional.length() < 2 {
|
||||||
|
println("Usage: moon-i2p http-get <host.i2p> [path]")
|
||||||
|
@env.exit(2)
|
||||||
|
}
|
||||||
|
let path = if positional.length() >= 3 { positional[2] } else { "/" }
|
||||||
|
cmd_http_get(config, positional[1], path)
|
||||||
|
} else if cmd == "dial" {
|
||||||
|
if positional.length() < 2 {
|
||||||
|
println("Usage: moon-i2p dial <dest-or-host.i2p> [message]")
|
||||||
|
@env.exit(2)
|
||||||
|
}
|
||||||
|
let msg = if positional.length() >= 3 { Some(positional[2]) } else { None }
|
||||||
|
cmd_dial(config, positional[1], msg)
|
||||||
|
} else if cmd == "listen" {
|
||||||
|
let reply = if positional.length() >= 2 {
|
||||||
|
Some(positional[1])
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
cmd_listen(config, reply)
|
||||||
|
} else {
|
||||||
|
println("Unknown command: \{cmd}")
|
||||||
|
println("")
|
||||||
|
print_usage()
|
||||||
|
@env.exit(2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn main {
|
||||||
|
run_cli() catch {
|
||||||
|
err => print_error_and_exit(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import {
|
||||||
|
"moonbitlang/core/env",
|
||||||
|
"experiments/moon_i2p/encoding",
|
||||||
|
"experiments/moon_i2p/sam_client",
|
||||||
|
}
|
||||||
|
|
||||||
|
pkgtype(kind: "executable")
|
||||||
|
|
||||||
|
supported_targets = "-all+native"
|
||||||
@@ -12,7 +12,7 @@ pub fn hello_version(min? : String, max? : String) -> SamMessage
|
|||||||
|
|
||||||
pub fn naming_lookup(String) -> SamMessage
|
pub fn naming_lookup(String) -> SamMessage
|
||||||
|
|
||||||
pub fn session_create(String, String, destination? : String, signature_type? : String) -> SamMessage
|
pub fn session_create(String, String, destination? : String, signature_type? : String, options? : Array[(String, String)]) -> SamMessage
|
||||||
|
|
||||||
pub fn stream_accept(String, silent? : Bool) -> SamMessage
|
pub fn stream_accept(String, silent? : Bool) -> SamMessage
|
||||||
|
|
||||||
|
|||||||
+13
-3
@@ -230,18 +230,28 @@ pub fn hello_version(
|
|||||||
|
|
||||||
///|
|
///|
|
||||||
/// Builds `SESSION CREATE STYLE=<style> ID=<id> DESTINATION=<dest> ...`.
|
/// Builds `SESSION CREATE STYLE=<style> ID=<id> DESTINATION=<dest> ...`.
|
||||||
|
/// Per the SAMv3 specification, `SIGNATURE_TYPE` is only included when
|
||||||
|
/// `destination == "TRANSIENT"`. Additional I2CP / tunnel options can be passed
|
||||||
|
/// via `options`.
|
||||||
pub fn session_create(
|
pub fn session_create(
|
||||||
style : String,
|
style : String,
|
||||||
id : String,
|
id : String,
|
||||||
destination~ : String = "TRANSIENT",
|
destination~ : String = "TRANSIENT",
|
||||||
signature_type~ : String = "7",
|
signature_type~ : String = "7",
|
||||||
|
options~ : Array[(String, String)] = [],
|
||||||
) -> SamMessage {
|
) -> SamMessage {
|
||||||
SamMessage::new("SESSION", subcommand=Some("CREATE"), params=[
|
let params : Array[(String, String)] = [
|
||||||
("STYLE", style),
|
("STYLE", style),
|
||||||
("ID", id),
|
("ID", id),
|
||||||
("DESTINATION", destination),
|
("DESTINATION", destination),
|
||||||
("SIGNATURE_TYPE", signature_type),
|
]
|
||||||
])
|
if destination == "TRANSIENT" {
|
||||||
|
params.push(("SIGNATURE_TYPE", signature_type))
|
||||||
|
}
|
||||||
|
for opt in options {
|
||||||
|
params.push(opt)
|
||||||
|
}
|
||||||
|
SamMessage::new("SESSION", subcommand=Some("CREATE"), params~)
|
||||||
}
|
}
|
||||||
|
|
||||||
///|
|
///|
|
||||||
|
|||||||
@@ -0,0 +1,575 @@
|
|||||||
|
///|
|
||||||
|
/// Errors raised by the native SAMv3 client.
|
||||||
|
#derive(Eq, Debug)
|
||||||
|
pub suberror SamClientError {
|
||||||
|
ConnectFailed(String, Int32, String)
|
||||||
|
IoError(String)
|
||||||
|
UnexpectedEof(String)
|
||||||
|
Closed
|
||||||
|
ProtocolError(String)
|
||||||
|
SamReplyError(String, String)
|
||||||
|
InvalidConfig(String)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Formats a `SamClientError` into a human-readable message.
|
||||||
|
pub fn SamClientError::message(self : SamClientError) -> String {
|
||||||
|
match self {
|
||||||
|
ConnectFailed(host, port, reason) =>
|
||||||
|
"failed to connect to SAMv3 bridge at \{host}:\{port}: \{reason}"
|
||||||
|
IoError(msg) => "I/O error: \{msg}"
|
||||||
|
UnexpectedEof(msg) => "unexpected EOF: \{msg}"
|
||||||
|
Closed => "connection is closed"
|
||||||
|
ProtocolError(msg) => "SAMv3 protocol error: \{msg}"
|
||||||
|
SamReplyError(result, msg) =>
|
||||||
|
if msg.length() > 0 {
|
||||||
|
"SAMv3 error (\{result}): \{msg}"
|
||||||
|
} else {
|
||||||
|
"SAMv3 error (\{result})"
|
||||||
|
}
|
||||||
|
InvalidConfig(msg) => "invalid SAM configuration: \{msg}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Configuration for connecting to an I2P SAMv3 bridge with sane modern defaults.
|
||||||
|
#derive(Eq, Debug)
|
||||||
|
pub(all) struct SamConfig {
|
||||||
|
host : String
|
||||||
|
port : Int32
|
||||||
|
min_version : String
|
||||||
|
max_version : String
|
||||||
|
signature_type : Int32
|
||||||
|
destination : String
|
||||||
|
i2cp_options : Array[(String, String)]
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Returns sane modern I2P SAMv3 defaults:
|
||||||
|
/// - `127.0.0.1:7656`
|
||||||
|
/// - SAM `3.1`..`3.3`
|
||||||
|
/// - `SIGNATURE_TYPE=7` (EdDSA_SHA512_Ed25519)
|
||||||
|
/// - `DESTINATION=TRANSIENT`
|
||||||
|
/// - ECIES-X25519 leaseSet (`i2cp.leaseSetEncType=4,0`) and 3-hop, 3-tunnel pools.
|
||||||
|
pub fn SamConfig::default() -> SamConfig {
|
||||||
|
{
|
||||||
|
host: "127.0.0.1",
|
||||||
|
port: 7656,
|
||||||
|
min_version: "3.1",
|
||||||
|
max_version: "3.3",
|
||||||
|
signature_type: 7,
|
||||||
|
destination: "TRANSIENT",
|
||||||
|
i2cp_options: [
|
||||||
|
("i2cp.leaseSetEncType", "4,0"),
|
||||||
|
("inbound.quantity", "3"),
|
||||||
|
("outbound.quantity", "3"),
|
||||||
|
("inbound.length", "3"),
|
||||||
|
("outbound.length", "3"),
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Returns `SamConfig::default()` overridden by `I2P_SAM_HOST` and `I2P_SAM_PORT`
|
||||||
|
/// environment variables when present.
|
||||||
|
pub fn SamConfig::from_env() -> SamConfig raise SamClientError {
|
||||||
|
let base = SamConfig::default()
|
||||||
|
let host = match @env.get_env_var("I2P_SAM_HOST") {
|
||||||
|
Some(h) if h.length() > 0 => h
|
||||||
|
_ => base.host
|
||||||
|
}
|
||||||
|
let port = match @env.get_env_var("I2P_SAM_PORT") {
|
||||||
|
Some(p) if p.length() > 0 => parse_port(p)
|
||||||
|
_ => base.port
|
||||||
|
}
|
||||||
|
{ ..base, host, port, }
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Parses a `"host:port"` (or `"host"`) address string and returns an updated `SamConfig`.
|
||||||
|
pub fn SamConfig::with_address(
|
||||||
|
self : SamConfig,
|
||||||
|
addr : String,
|
||||||
|
) -> SamConfig raise SamClientError {
|
||||||
|
let chars : Array[Char] = []
|
||||||
|
for ch in addr {
|
||||||
|
chars.push(ch)
|
||||||
|
}
|
||||||
|
let mut last_colon = -1
|
||||||
|
for i = 0; i < chars.length(); i = i + 1 {
|
||||||
|
if chars[i] == ':' {
|
||||||
|
last_colon = i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if last_colon < 0 {
|
||||||
|
if addr.length() == 0 {
|
||||||
|
raise InvalidConfig("SAM address cannot be empty")
|
||||||
|
}
|
||||||
|
return { ..self, host: addr, }
|
||||||
|
}
|
||||||
|
let hbuf = StringBuilder()
|
||||||
|
for i = 0; i < last_colon; i = i + 1 {
|
||||||
|
hbuf.write_char(chars[i])
|
||||||
|
}
|
||||||
|
let pbuf = StringBuilder()
|
||||||
|
for i = last_colon + 1; i < chars.length(); i = i + 1 {
|
||||||
|
pbuf.write_char(chars[i])
|
||||||
|
}
|
||||||
|
let host = hbuf.to_string()
|
||||||
|
let port_str = pbuf.to_string()
|
||||||
|
if host.length() == 0 {
|
||||||
|
raise InvalidConfig("missing host in SAM address '\{addr}'")
|
||||||
|
}
|
||||||
|
let port = parse_port(port_str)
|
||||||
|
{ ..self, host, port, }
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn parse_port(s : String) -> Int32 raise SamClientError {
|
||||||
|
if s.length() == 0 {
|
||||||
|
raise InvalidConfig("empty port number")
|
||||||
|
}
|
||||||
|
let mut p = 0
|
||||||
|
for ch in s {
|
||||||
|
if ch < '0' || ch > '9' {
|
||||||
|
raise InvalidConfig("invalid port number '\{s}'")
|
||||||
|
}
|
||||||
|
p = p * 10 + (ch.to_int() - '0'.to_int())
|
||||||
|
if p > 65535 {
|
||||||
|
raise InvalidConfig("port out of range (1..65535): '\{s}'")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if p <= 0 {
|
||||||
|
raise InvalidConfig("port out of range (1..65535): \{p}")
|
||||||
|
}
|
||||||
|
p
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// An I2P Destination returned by SAMv3 (`DEST GENERATE`, `NAMING LOOKUP`, or `SESSION CREATE`).
|
||||||
|
#derive(Eq, Debug)
|
||||||
|
pub(all) struct SamDestination {
|
||||||
|
pub_b64 : String
|
||||||
|
priv_b64 : String?
|
||||||
|
b32_address : String
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Decodes an I2P Base64 public destination (or private key blob whose prefix
|
||||||
|
/// is the public Destination `KeysAndCert`) and computes its canonical
|
||||||
|
/// Base64 public destination and `.b32.i2p` address.
|
||||||
|
pub fn destination_from_base64(
|
||||||
|
b64 : String,
|
||||||
|
priv_b64~ : String? = None,
|
||||||
|
) -> SamDestination raise SamClientError {
|
||||||
|
let raw = @encoding.base64_decode(b64) catch {
|
||||||
|
_ => raise ProtocolError("invalid I2P Base64 destination")
|
||||||
|
}
|
||||||
|
let r = @encoding.Reader::new(raw)
|
||||||
|
let dest = @common.Destination::decode(r) catch {
|
||||||
|
_ => raise ProtocolError("invalid I2P Destination structure")
|
||||||
|
}
|
||||||
|
{ pub_b64: dest.to_base64(), priv_b64, b32_address: dest.b32_address(), }
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn parse_sam_reply(line : String) -> @sam.SamMessage raise SamClientError {
|
||||||
|
@sam.SamMessage::parse(line) catch {
|
||||||
|
_ => raise ProtocolError("failed to parse SAM line '\{line}'")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn ensure_ok(reply : @sam.SamMessage) -> Unit raise SamClientError {
|
||||||
|
if !reply.is_ok() {
|
||||||
|
let result = match reply.result() {
|
||||||
|
Some(r) => r
|
||||||
|
None => "UNKNOWN"
|
||||||
|
}
|
||||||
|
let msg = match reply.get("MESSAGE") {
|
||||||
|
Some(m) => m
|
||||||
|
None => ""
|
||||||
|
}
|
||||||
|
raise SamReplyError(result, msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn perform_hello(
|
||||||
|
conn : TcpConn,
|
||||||
|
config : SamConfig,
|
||||||
|
) -> String raise SamClientError {
|
||||||
|
let cmd = @sam.hello_version(min=config.min_version, max=config.max_version)
|
||||||
|
conn.write_string(cmd.serialize())
|
||||||
|
let reply = parse_sam_reply(conn.read_line())
|
||||||
|
if reply.verb != "HELLO" || reply.subcommand != Some("REPLY") {
|
||||||
|
raise ProtocolError("expected HELLO REPLY, got '\{reply.verb}'")
|
||||||
|
}
|
||||||
|
ensure_ok(reply)
|
||||||
|
match reply.get("VERSION") {
|
||||||
|
Some(v) => v
|
||||||
|
None => config.min_version
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn generate_session_id() -> String {
|
||||||
|
match @env.rand(6) {
|
||||||
|
Some(bytes) => "moon-i2p-\{@encoding.hex_encode(bytes)}"
|
||||||
|
None => "moon-i2p-\{@env.now()}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// A connected SAMv3 control client (after `HELLO VERSION` handshake).
|
||||||
|
pub struct SamClient {
|
||||||
|
config : SamConfig
|
||||||
|
version : String
|
||||||
|
conn : TcpConn
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Connects to the SAMv3 bridge over TCP and completes the `HELLO VERSION` handshake.
|
||||||
|
pub fn SamClient::connect(
|
||||||
|
config~ : SamConfig = SamConfig::default(),
|
||||||
|
) -> SamClient raise SamClientError {
|
||||||
|
let conn = TcpConn::connect(config.host, config.port)
|
||||||
|
errdefer conn.close()
|
||||||
|
let version = perform_hello(conn, config)
|
||||||
|
{ config, version, conn, }
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Returns the negotiated SAM protocol version (e.g., `"3.3"`).
|
||||||
|
pub fn SamClient::version(self : SamClient) -> String {
|
||||||
|
self.version
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Closes the underlying SAM control connection.
|
||||||
|
pub fn SamClient::close(self : SamClient) -> Unit {
|
||||||
|
self.conn.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Runs `DEST GENERATE SIGNATURE_TYPE=<sig>` and returns the generated keypair
|
||||||
|
/// and derived `.b32.i2p` address.
|
||||||
|
pub fn SamClient::dest_generate(
|
||||||
|
self : SamClient,
|
||||||
|
signature_type? : Int32,
|
||||||
|
) -> SamDestination raise SamClientError {
|
||||||
|
let sig = match signature_type {
|
||||||
|
Some(s) => s
|
||||||
|
None => self.config.signature_type
|
||||||
|
}
|
||||||
|
let cmd = @sam.dest_generate(signature_type=sig.to_string())
|
||||||
|
self.conn.write_string(cmd.serialize())
|
||||||
|
let reply = parse_sam_reply(self.conn.read_line())
|
||||||
|
if reply.verb != "DEST" || reply.subcommand != Some("REPLY") {
|
||||||
|
raise ProtocolError("expected DEST REPLY, got '\{reply.verb}'")
|
||||||
|
}
|
||||||
|
match reply.result() {
|
||||||
|
Some(r) if r != "OK" => {
|
||||||
|
let msg = reply.get("MESSAGE").unwrap_or("")
|
||||||
|
raise SamReplyError(r, msg)
|
||||||
|
}
|
||||||
|
_ => ()
|
||||||
|
}
|
||||||
|
let pub_b64 = match reply.get("PUB") {
|
||||||
|
Some(p) => p
|
||||||
|
None => raise ProtocolError("DEST REPLY missing PUB field")
|
||||||
|
}
|
||||||
|
let priv_b64 = reply.get("PRIV")
|
||||||
|
destination_from_base64(pub_b64, priv_b64~)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Runs `NAMING LOOKUP NAME=<name>` and resolves a `.i2p` hostname, `.b32.i2p`
|
||||||
|
/// address, or `ME` into a `SamDestination`.
|
||||||
|
pub fn SamClient::naming_lookup(
|
||||||
|
self : SamClient,
|
||||||
|
name : String,
|
||||||
|
) -> SamDestination raise SamClientError {
|
||||||
|
naming_lookup_on_conn(self.conn, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn naming_lookup_on_conn(
|
||||||
|
conn : TcpConn,
|
||||||
|
name : String,
|
||||||
|
) -> SamDestination raise SamClientError {
|
||||||
|
let cmd = @sam.naming_lookup(name)
|
||||||
|
conn.write_string(cmd.serialize())
|
||||||
|
let reply = parse_sam_reply(conn.read_line())
|
||||||
|
if reply.verb != "NAMING" || reply.subcommand != Some("REPLY") {
|
||||||
|
raise ProtocolError("expected NAMING REPLY, got '\{reply.verb}'")
|
||||||
|
}
|
||||||
|
ensure_ok(reply)
|
||||||
|
let value = match reply.get("VALUE") {
|
||||||
|
Some(v) => v
|
||||||
|
None => raise ProtocolError("NAMING REPLY missing VALUE field")
|
||||||
|
}
|
||||||
|
destination_from_base64(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Runs `SESSION CREATE` and transfers the control socket into a live `SamSession`.
|
||||||
|
/// The control socket remains open for the lifetime of the session; call
|
||||||
|
/// `session.close()` when finished.
|
||||||
|
pub fn SamClient::session_create(
|
||||||
|
self : SamClient,
|
||||||
|
session_id~ : String = "",
|
||||||
|
style~ : String = "STREAM",
|
||||||
|
destination? : String,
|
||||||
|
options? : Array[(String, String)],
|
||||||
|
) -> SamSession raise SamClientError {
|
||||||
|
let id = if session_id.length() > 0 {
|
||||||
|
session_id
|
||||||
|
} else {
|
||||||
|
generate_session_id()
|
||||||
|
}
|
||||||
|
let dest_arg = match destination {
|
||||||
|
Some(d) => d
|
||||||
|
None => self.config.destination
|
||||||
|
}
|
||||||
|
let opts = match options {
|
||||||
|
Some(o) => o
|
||||||
|
None => self.config.i2cp_options
|
||||||
|
}
|
||||||
|
let cmd = @sam.session_create(
|
||||||
|
style,
|
||||||
|
id,
|
||||||
|
destination=dest_arg,
|
||||||
|
signature_type=self.config.signature_type.to_string(),
|
||||||
|
options=opts,
|
||||||
|
)
|
||||||
|
self.conn.write_string(cmd.serialize())
|
||||||
|
let reply = parse_sam_reply(self.conn.read_line())
|
||||||
|
if reply.verb != "SESSION" || reply.subcommand != Some("STATUS") {
|
||||||
|
raise ProtocolError("expected SESSION STATUS, got '\{reply.verb}'")
|
||||||
|
}
|
||||||
|
ensure_ok(reply)
|
||||||
|
let dest_blob = match reply.get("DESTINATION") {
|
||||||
|
Some(d) => d
|
||||||
|
None => raise ProtocolError("SESSION STATUS missing DESTINATION field")
|
||||||
|
}
|
||||||
|
let resolved = destination_from_base64(dest_blob, priv_b64=Some(dest_blob))
|
||||||
|
{ config: self.config, id, style, destination: resolved, control: self.conn, }
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// A live SAMv3 session keeping the control TCP socket open.
|
||||||
|
pub struct SamSession {
|
||||||
|
config : SamConfig
|
||||||
|
id : String
|
||||||
|
style : String
|
||||||
|
destination : SamDestination
|
||||||
|
control : TcpConn
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn SamSession::id(self : SamSession) -> String {
|
||||||
|
self.id
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn SamSession::b32_address(self : SamSession) -> String {
|
||||||
|
self.destination.b32_address
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn SamSession::destination(self : SamSession) -> SamDestination {
|
||||||
|
self.destination
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Closes the SAM session control connection, tearing down the I2P tunnels.
|
||||||
|
pub fn SamSession::close(self : SamSession) -> Unit {
|
||||||
|
self.control.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Resolves a `.i2p` hostname, `.b32.i2p` address, or `ME` via this session's
|
||||||
|
/// control connection.
|
||||||
|
pub fn SamSession::naming_lookup(
|
||||||
|
self : SamSession,
|
||||||
|
name : String,
|
||||||
|
) -> SamDestination raise SamClientError {
|
||||||
|
if !self.control.is_open() {
|
||||||
|
raise Closed
|
||||||
|
}
|
||||||
|
naming_lookup_on_conn(self.control, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Resolves `target` if it looks like a `.i2p` hostname/b32 address, or returns
|
||||||
|
/// it as-is when it is already a raw Base64 I2P Destination.
|
||||||
|
pub fn SamSession::resolve_target(
|
||||||
|
self : SamSession,
|
||||||
|
target : String,
|
||||||
|
) -> String raise SamClientError {
|
||||||
|
if target.has_suffix(".i2p") || target == "ME" {
|
||||||
|
self.naming_lookup(target).pub_b64
|
||||||
|
} else {
|
||||||
|
target
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Opens a new SAM data socket, performs `HELLO` and `STREAM CONNECT`, checks
|
||||||
|
/// `STREAM STATUS RESULT=OK`, and returns a live `SamStream`.
|
||||||
|
pub fn SamSession::stream_connect(
|
||||||
|
self : SamSession,
|
||||||
|
target_dest : String,
|
||||||
|
) -> SamStream raise SamClientError {
|
||||||
|
if !self.control.is_open() {
|
||||||
|
raise Closed
|
||||||
|
}
|
||||||
|
let dest_b64 = self.resolve_target(target_dest)
|
||||||
|
let data_conn = TcpConn::connect(self.config.host, self.config.port)
|
||||||
|
errdefer data_conn.close()
|
||||||
|
let _ = perform_hello(data_conn, self.config)
|
||||||
|
let cmd = @sam.stream_connect(self.id, dest_b64, silent=false)
|
||||||
|
data_conn.write_string(cmd.serialize())
|
||||||
|
let reply = parse_sam_reply(data_conn.read_line())
|
||||||
|
if reply.verb != "STREAM" || reply.subcommand != Some("STATUS") {
|
||||||
|
raise ProtocolError("expected STREAM STATUS, got '\{reply.verb}'")
|
||||||
|
}
|
||||||
|
ensure_ok(reply)
|
||||||
|
{ conn: data_conn, }
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Opens a new SAM data socket, performs `HELLO` and `STREAM ACCEPT`, waits for
|
||||||
|
/// an incoming connection, reads the peer's Base64 destination line, and returns
|
||||||
|
/// `(peer_destination, SamStream)`.
|
||||||
|
pub fn SamSession::stream_accept(
|
||||||
|
self : SamSession,
|
||||||
|
) -> (SamDestination, SamStream) raise SamClientError {
|
||||||
|
if !self.control.is_open() {
|
||||||
|
raise Closed
|
||||||
|
}
|
||||||
|
let data_conn = TcpConn::connect(self.config.host, self.config.port)
|
||||||
|
errdefer data_conn.close()
|
||||||
|
let _ = perform_hello(data_conn, self.config)
|
||||||
|
let cmd = @sam.stream_accept(self.id, silent=false)
|
||||||
|
data_conn.write_string(cmd.serialize())
|
||||||
|
let reply = parse_sam_reply(data_conn.read_line())
|
||||||
|
if reply.verb != "STREAM" || reply.subcommand != Some("STATUS") {
|
||||||
|
raise ProtocolError("expected STREAM STATUS, got '\{reply.verb}'")
|
||||||
|
}
|
||||||
|
ensure_ok(reply)
|
||||||
|
// When SILENT=false, the first line after STREAM STATUS RESULT=OK is the
|
||||||
|
// remote peer's Base64 Destination (optionally followed by FROM_PORT/TO_PORT).
|
||||||
|
let peer_line = data_conn.read_line()
|
||||||
|
let peer_b64 = first_whitespace_token(peer_line)
|
||||||
|
let peer_dest = destination_from_base64(peer_b64)
|
||||||
|
(peer_dest, { conn: data_conn, })
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn first_whitespace_token(s : String) -> String {
|
||||||
|
let buf = StringBuilder()
|
||||||
|
let mut started = false
|
||||||
|
for ch in s {
|
||||||
|
if ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' {
|
||||||
|
if started {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
started = true
|
||||||
|
buf.write_char(ch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
buf.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Convenience helper that resolves `host` (if `.i2p` / `.b32.i2p`), dials via
|
||||||
|
/// `stream_connect`, sends an `HTTP/1.1 GET` request with `Host` and
|
||||||
|
/// `Connection: close`, and reads the full raw HTTP response bytes.
|
||||||
|
pub fn SamSession::http_get(
|
||||||
|
self : SamSession,
|
||||||
|
host : String,
|
||||||
|
path~ : String = "/",
|
||||||
|
) -> Bytes raise SamClientError {
|
||||||
|
let req_path = if path.length() == 0 {
|
||||||
|
"/"
|
||||||
|
} else if path.has_prefix("/") {
|
||||||
|
path
|
||||||
|
} else {
|
||||||
|
"/\{path}"
|
||||||
|
}
|
||||||
|
let stream = self.stream_connect(host)
|
||||||
|
defer stream.close()
|
||||||
|
let req = "GET \{req_path} HTTP/1.1\r\nHost: \{host}\r\nUser-Agent: moon-i2p/0.1\r\nAccept: */*\r\nConnection: close\r\n\r\n"
|
||||||
|
stream.write_string(req)
|
||||||
|
stream.read_all()
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Like `http_get`, returning the response decoded as UTF-8 text.
|
||||||
|
pub fn SamSession::http_get_string(
|
||||||
|
self : SamSession,
|
||||||
|
host : String,
|
||||||
|
path~ : String = "/",
|
||||||
|
) -> String raise SamClientError {
|
||||||
|
let raw = self.http_get(host, path~)
|
||||||
|
@encoding.utf8_bytes_to_string(raw) catch {
|
||||||
|
_ => raise ProtocolError("HTTP response is not valid UTF-8")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// A live bidirectional I2P stream backed by a SAMv3 data socket.
|
||||||
|
pub struct SamStream {
|
||||||
|
conn : TcpConn
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn SamStream::write(
|
||||||
|
self : SamStream,
|
||||||
|
data : Bytes,
|
||||||
|
) -> Int32 raise SamClientError {
|
||||||
|
self.conn.write(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn SamStream::write_all(
|
||||||
|
self : SamStream,
|
||||||
|
data : Bytes,
|
||||||
|
) -> Unit raise SamClientError {
|
||||||
|
self.conn.write_all(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn SamStream::write_string(
|
||||||
|
self : SamStream,
|
||||||
|
s : String,
|
||||||
|
) -> Unit raise SamClientError {
|
||||||
|
self.conn.write_string(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Half-closes the write side of the stream (`SHUT_WR`) while keeping reads open.
|
||||||
|
pub fn SamStream::shutdown_write(self : SamStream) -> Unit raise SamClientError {
|
||||||
|
self.conn.shutdown_write()
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn SamStream::read(
|
||||||
|
self : SamStream,
|
||||||
|
max_bytes~ : Int32 = 4096,
|
||||||
|
) -> Bytes raise SamClientError {
|
||||||
|
self.conn.read(max_bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn SamStream::read_all(self : SamStream) -> Bytes raise SamClientError {
|
||||||
|
self.conn.read_all()
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
pub fn SamStream::close(self : SamStream) -> Unit {
|
||||||
|
self.conn.close()
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
///|
|
||||||
|
test "SamConfig::default has sane modern I2P defaults" {
|
||||||
|
let cfg = @sam_client.SamConfig::default()
|
||||||
|
assert_eq(cfg.host, "127.0.0.1")
|
||||||
|
assert_eq(cfg.port, 7656)
|
||||||
|
assert_eq(cfg.min_version, "3.1")
|
||||||
|
assert_eq(cfg.max_version, "3.3")
|
||||||
|
assert_eq(cfg.signature_type, 7)
|
||||||
|
assert_eq(cfg.destination, "TRANSIENT")
|
||||||
|
assert_eq(cfg.i2cp_options.length(), 5)
|
||||||
|
assert_eq(cfg.i2cp_options[0], ("i2cp.leaseSetEncType", "4,0"))
|
||||||
|
assert_eq(cfg.i2cp_options[1], ("inbound.quantity", "3"))
|
||||||
|
assert_eq(cfg.i2cp_options[2], ("outbound.quantity", "3"))
|
||||||
|
assert_eq(cfg.i2cp_options[3], ("inbound.length", "3"))
|
||||||
|
assert_eq(cfg.i2cp_options[4], ("outbound.length", "3"))
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
test "SamConfig::with_address parses host:port and host-only" {
|
||||||
|
let base = @sam_client.SamConfig::default()
|
||||||
|
let c1 = base.with_address("10.0.0.5:17656")
|
||||||
|
assert_eq(c1.host, "10.0.0.5")
|
||||||
|
assert_eq(c1.port, 17656)
|
||||||
|
|
||||||
|
let c2 = base.with_address("sam.internal")
|
||||||
|
assert_eq(c2.host, "sam.internal")
|
||||||
|
assert_eq(c2.port, 7656)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
test "destination_from_base64 derives canonical b32.i2p address" {
|
||||||
|
let crypto_pub = FixedArray::make(32, b'\x11')
|
||||||
|
let sign_pub = FixedArray::make(32, b'\x22')
|
||||||
|
let dest = @common.Destination::new_x25519_ed25519(
|
||||||
|
Bytes::from_array(crypto_pub),
|
||||||
|
Bytes::from_array(sign_pub),
|
||||||
|
)
|
||||||
|
let b64 = dest.to_base64()
|
||||||
|
let parsed = @sam_client.destination_from_base64(b64)
|
||||||
|
assert_eq(parsed.pub_b64, b64)
|
||||||
|
assert_eq(parsed.b32_address, dest.b32_address())
|
||||||
|
assert_true(parsed.b32_address.has_suffix(".b32.i2p"))
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import {
|
||||||
|
"moonbitlang/core/env",
|
||||||
|
"experiments/moon_i2p/encoding",
|
||||||
|
"experiments/moon_i2p/common",
|
||||||
|
"experiments/moon_i2p/sam",
|
||||||
|
}
|
||||||
|
|
||||||
|
supported_targets = "-all+native"
|
||||||
|
|
||||||
|
options(
|
||||||
|
"native-stub": [ "tcp_stub.c" ],
|
||||||
|
)
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
///|
|
||||||
|
/// Low-level C FFI declarations backed by `tcp_stub.c`.
|
||||||
|
extern "C" fn c_last_error_len() -> Int32 = "moon_i2p_last_error_len"
|
||||||
|
|
||||||
|
///|
|
||||||
|
#borrow(dst)
|
||||||
|
extern "C" fn c_last_error_copy(
|
||||||
|
dst : FixedArray[Byte],
|
||||||
|
max_len : Int32,
|
||||||
|
) -> Int32 = "moon_i2p_last_error_copy"
|
||||||
|
|
||||||
|
///|
|
||||||
|
#borrow(host)
|
||||||
|
extern "C" fn c_tcp_connect(
|
||||||
|
host : Bytes,
|
||||||
|
host_len : Int32,
|
||||||
|
port : Int32,
|
||||||
|
) -> Int32 = "moon_i2p_tcp_connect"
|
||||||
|
|
||||||
|
///|
|
||||||
|
#borrow(data)
|
||||||
|
extern "C" fn c_tcp_send(
|
||||||
|
fd : Int32,
|
||||||
|
data : Bytes,
|
||||||
|
offset : Int32,
|
||||||
|
len : Int32,
|
||||||
|
) -> Int32 = "moon_i2p_tcp_send"
|
||||||
|
|
||||||
|
///|
|
||||||
|
#borrow(buf)
|
||||||
|
extern "C" fn c_tcp_recv(
|
||||||
|
fd : Int32,
|
||||||
|
buf : FixedArray[Byte],
|
||||||
|
max_len : Int32,
|
||||||
|
) -> Int32 = "moon_i2p_tcp_recv"
|
||||||
|
|
||||||
|
///|
|
||||||
|
extern "C" fn c_tcp_shutdown_write(fd : Int32) -> Int32 = "moon_i2p_tcp_shutdown_write"
|
||||||
|
|
||||||
|
///|
|
||||||
|
extern "C" fn c_tcp_close(fd : Int32) -> Int32 = "moon_i2p_tcp_close"
|
||||||
|
|
||||||
|
///|
|
||||||
|
#borrow(buf)
|
||||||
|
extern "C" fn c_read_stdin(buf : FixedArray[Byte], max_len : Int32) -> Int32 = "moon_i2p_read_stdin"
|
||||||
|
|
||||||
|
///|
|
||||||
|
extern "C" fn c_flush_stdout() -> Unit = "moon_i2p_flush_stdout"
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Flushes standard output (useful before blocking on `stream_accept`).
|
||||||
|
pub fn flush_stdout() -> Unit {
|
||||||
|
c_flush_stdout()
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn last_os_error() -> String {
|
||||||
|
let n = c_last_error_len()
|
||||||
|
if n <= 0 {
|
||||||
|
return "unknown OS error"
|
||||||
|
}
|
||||||
|
let buf = FixedArray::make(n, b'\x00')
|
||||||
|
let copied = c_last_error_copy(buf, n)
|
||||||
|
let bytes = Bytes::from_array(buf)
|
||||||
|
@encoding.utf8_bytes_to_string(bytes[:copied].to_owned()) catch {
|
||||||
|
_ => "OS error"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Reads all bytes from standard input until EOF.
|
||||||
|
pub fn read_all_stdin() -> Bytes raise SamClientError {
|
||||||
|
let out : Array[Byte] = []
|
||||||
|
let chunk = FixedArray::make(4096, b'\x00')
|
||||||
|
while true {
|
||||||
|
let n = c_read_stdin(chunk, 4096)
|
||||||
|
if n < 0 {
|
||||||
|
raise IoError("failed to read stdin: \{last_os_error()}")
|
||||||
|
}
|
||||||
|
if n == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
for i = 0; i < n; i = i + 1 {
|
||||||
|
out.push(chunk[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Bytes::from_array(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Buffered POSIX TCP connection. Preserves unconsumed bytes across line
|
||||||
|
/// reads and raw stream reads so SAMv3 transitions from text replies to
|
||||||
|
/// binary stream payloads never lose data.
|
||||||
|
struct TcpConn {
|
||||||
|
mut fd : Int32
|
||||||
|
buf : FixedArray[Byte]
|
||||||
|
mut pos : Int32
|
||||||
|
mut len : Int32
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn TcpConn::connect(
|
||||||
|
host : String,
|
||||||
|
port : Int32,
|
||||||
|
) -> TcpConn raise SamClientError {
|
||||||
|
let host_bytes = @encoding.string_to_utf8_bytes(host)
|
||||||
|
let fd = c_tcp_connect(host_bytes, host_bytes.length(), port)
|
||||||
|
if fd < 0 {
|
||||||
|
raise ConnectFailed(host, port, last_os_error())
|
||||||
|
}
|
||||||
|
{ fd, buf: FixedArray::make(4096, b'\x00'), pos: 0, len: 0, }
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn TcpConn::is_open(self : TcpConn) -> Bool {
|
||||||
|
self.fd >= 0
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn TcpConn::close(self : TcpConn) -> Unit {
|
||||||
|
if self.fd >= 0 {
|
||||||
|
let _ = c_tcp_close(self.fd)
|
||||||
|
self.fd = -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn TcpConn::shutdown_write(self : TcpConn) -> Unit raise SamClientError {
|
||||||
|
if self.fd < 0 {
|
||||||
|
raise Closed
|
||||||
|
}
|
||||||
|
if c_tcp_shutdown_write(self.fd) < 0 {
|
||||||
|
raise IoError("shutdown(SHUT_WR) failed: \{last_os_error()}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn TcpConn::write(self : TcpConn, data : Bytes) -> Int32 raise SamClientError {
|
||||||
|
if self.fd < 0 {
|
||||||
|
raise Closed
|
||||||
|
}
|
||||||
|
if data.length() == 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
let n = c_tcp_send(self.fd, data, 0, data.length())
|
||||||
|
if n < 0 {
|
||||||
|
raise IoError("send failed: \{last_os_error()}")
|
||||||
|
}
|
||||||
|
n
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn TcpConn::write_all(
|
||||||
|
self : TcpConn,
|
||||||
|
data : Bytes,
|
||||||
|
) -> Unit raise SamClientError {
|
||||||
|
if self.fd < 0 {
|
||||||
|
raise Closed
|
||||||
|
}
|
||||||
|
let total = data.length()
|
||||||
|
let mut sent = 0
|
||||||
|
while sent < total {
|
||||||
|
let n = c_tcp_send(self.fd, data, sent, total - sent)
|
||||||
|
if n < 0 {
|
||||||
|
raise IoError("send failed: \{last_os_error()}")
|
||||||
|
}
|
||||||
|
if n == 0 {
|
||||||
|
raise IoError("peer closed connection during write")
|
||||||
|
}
|
||||||
|
sent += n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn TcpConn::write_string(
|
||||||
|
self : TcpConn,
|
||||||
|
s : String,
|
||||||
|
) -> Unit raise SamClientError {
|
||||||
|
self.write_all(@encoding.string_to_utf8_bytes(s))
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
fn TcpConn::refill(self : TcpConn) -> Int32 raise SamClientError {
|
||||||
|
if self.fd < 0 {
|
||||||
|
raise Closed
|
||||||
|
}
|
||||||
|
let n = c_tcp_recv(self.fd, self.buf, self.buf.length())
|
||||||
|
if n < 0 {
|
||||||
|
raise IoError("recv failed: \{last_os_error()}")
|
||||||
|
}
|
||||||
|
self.pos = 0
|
||||||
|
self.len = n
|
||||||
|
n
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Reads a single `\n`-terminated UTF-8 line (stripping trailing `\r\n` or `\n`).
|
||||||
|
fn TcpConn::read_line(self : TcpConn) -> String raise SamClientError {
|
||||||
|
let line_bytes : Array[Byte] = []
|
||||||
|
while true {
|
||||||
|
while self.pos < self.len {
|
||||||
|
let b = self.buf[self.pos]
|
||||||
|
self.pos += 1
|
||||||
|
if b == b'\n' {
|
||||||
|
// Strip optional trailing '\r'
|
||||||
|
if line_bytes.length() > 0 &&
|
||||||
|
line_bytes[line_bytes.length() - 1] == b'\r' {
|
||||||
|
let _ = line_bytes.pop()
|
||||||
|
}
|
||||||
|
let raw = Bytes::from_array(line_bytes)
|
||||||
|
return @encoding.utf8_bytes_to_string(raw) catch {
|
||||||
|
_ => raise ProtocolError("invalid UTF-8 in SAM reply line")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
line_bytes.push(b)
|
||||||
|
}
|
||||||
|
let n = self.refill()
|
||||||
|
if n == 0 {
|
||||||
|
if line_bytes.length() == 0 {
|
||||||
|
raise UnexpectedEof("connection closed while waiting for SAM reply")
|
||||||
|
}
|
||||||
|
let raw = Bytes::from_array(line_bytes)
|
||||||
|
return @encoding.utf8_bytes_to_string(raw) catch {
|
||||||
|
_ => raise ProtocolError("invalid UTF-8 in SAM reply line")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Reads up to `max_bytes` from the connection (returning empty `Bytes` on EOF).
|
||||||
|
fn TcpConn::read(
|
||||||
|
self : TcpConn,
|
||||||
|
max_bytes : Int32,
|
||||||
|
) -> Bytes raise SamClientError {
|
||||||
|
if self.fd < 0 {
|
||||||
|
raise Closed
|
||||||
|
}
|
||||||
|
if max_bytes <= 0 {
|
||||||
|
return b""
|
||||||
|
}
|
||||||
|
if self.pos < self.len {
|
||||||
|
let avail = self.len - self.pos
|
||||||
|
let take = if avail < max_bytes { avail } else { max_bytes }
|
||||||
|
let out = FixedArray::make(take, b'\x00')
|
||||||
|
for i = 0; i < take; i = i + 1 {
|
||||||
|
out[i] = self.buf[self.pos + i]
|
||||||
|
}
|
||||||
|
self.pos += take
|
||||||
|
return Bytes::from_array(out)
|
||||||
|
}
|
||||||
|
let tmp = FixedArray::make(max_bytes, b'\x00')
|
||||||
|
let n = c_tcp_recv(self.fd, tmp, max_bytes)
|
||||||
|
if n < 0 {
|
||||||
|
raise IoError("recv failed: \{last_os_error()}")
|
||||||
|
}
|
||||||
|
if n == 0 {
|
||||||
|
return b""
|
||||||
|
}
|
||||||
|
let out = FixedArray::make(n, b'\x00')
|
||||||
|
for i = 0; i < n; i = i + 1 {
|
||||||
|
out[i] = tmp[i]
|
||||||
|
}
|
||||||
|
Bytes::from_array(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
/// Reads until EOF and returns all received bytes.
|
||||||
|
fn TcpConn::read_all(self : TcpConn) -> Bytes raise SamClientError {
|
||||||
|
let out : Array[Byte] = []
|
||||||
|
while self.pos < self.len {
|
||||||
|
out.push(self.buf[self.pos])
|
||||||
|
self.pos += 1
|
||||||
|
}
|
||||||
|
let chunk = FixedArray::make(4096, b'\x00')
|
||||||
|
while true {
|
||||||
|
let n = c_tcp_recv(self.fd, chunk, 4096)
|
||||||
|
if n < 0 {
|
||||||
|
raise IoError("recv failed: \{last_os_error()}")
|
||||||
|
}
|
||||||
|
if n == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
for i = 0; i < n; i = i + 1 {
|
||||||
|
out.push(chunk[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Bytes::from_array(out)
|
||||||
|
}
|
||||||
@@ -0,0 +1,194 @@
|
|||||||
|
/*
|
||||||
|
* Minimal POSIX TCP socket & stdin FFI stub for moon-i2p sam_client (native target).
|
||||||
|
*/
|
||||||
|
#define _POSIX_C_SOURCE 200809L
|
||||||
|
|
||||||
|
#include <errno.h>
|
||||||
|
#include <netdb.h>
|
||||||
|
#include <signal.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <sys/socket.h>
|
||||||
|
#include <sys/types.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
#include "moonbit.h"
|
||||||
|
|
||||||
|
#ifndef MSG_NOSIGNAL
|
||||||
|
#define MSG_NOSIGNAL 0
|
||||||
|
#endif
|
||||||
|
|
||||||
|
static char g_last_error[256] = {0};
|
||||||
|
|
||||||
|
static void set_last_error(const char *msg) {
|
||||||
|
if (msg == NULL) {
|
||||||
|
g_last_error[0] = '\0';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
strncpy(g_last_error, msg, sizeof(g_last_error) - 1);
|
||||||
|
g_last_error[sizeof(g_last_error) - 1] = '\0';
|
||||||
|
}
|
||||||
|
|
||||||
|
MOONBIT_FFI_EXPORT
|
||||||
|
int32_t moon_i2p_last_error_len(void) {
|
||||||
|
return (int32_t)strlen(g_last_error);
|
||||||
|
}
|
||||||
|
|
||||||
|
MOONBIT_FFI_EXPORT
|
||||||
|
int32_t moon_i2p_last_error_copy(moonbit_bytes_t dst, int32_t max_len) {
|
||||||
|
int32_t n = (int32_t)strlen(g_last_error);
|
||||||
|
if (n > max_len) {
|
||||||
|
n = max_len;
|
||||||
|
}
|
||||||
|
if (n > 0) {
|
||||||
|
memcpy(dst, g_last_error, (size_t)n);
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
MOONBIT_FFI_EXPORT
|
||||||
|
int32_t moon_i2p_tcp_connect(
|
||||||
|
moonbit_bytes_t host_bytes,
|
||||||
|
int32_t host_len,
|
||||||
|
int32_t port) {
|
||||||
|
if (host_len <= 0 || host_len >= 256 || port <= 0 || port > 65535) {
|
||||||
|
set_last_error("invalid host or port");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
char host_buf[256];
|
||||||
|
memcpy(host_buf, host_bytes, (size_t)host_len);
|
||||||
|
host_buf[host_len] = '\0';
|
||||||
|
|
||||||
|
char port_buf[16];
|
||||||
|
snprintf(port_buf, sizeof(port_buf), "%d", port);
|
||||||
|
|
||||||
|
struct addrinfo hints;
|
||||||
|
memset(&hints, 0, sizeof(hints));
|
||||||
|
hints.ai_family = AF_UNSPEC;
|
||||||
|
hints.ai_socktype = SOCK_STREAM;
|
||||||
|
hints.ai_protocol = IPPROTO_TCP;
|
||||||
|
|
||||||
|
struct addrinfo *res = NULL;
|
||||||
|
int gai_err = getaddrinfo(host_buf, port_buf, &hints, &res);
|
||||||
|
if (gai_err != 0) {
|
||||||
|
set_last_error(gai_strerror(gai_err));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
int fd = -1;
|
||||||
|
int saved_errno = 0;
|
||||||
|
for (struct addrinfo *p = res; p != NULL; p = p->ai_next) {
|
||||||
|
int s = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
|
||||||
|
if (s < 0) {
|
||||||
|
saved_errno = errno;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (connect(s, p->ai_addr, p->ai_addrlen) == 0) {
|
||||||
|
fd = s;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
saved_errno = errno;
|
||||||
|
close(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
freeaddrinfo(res);
|
||||||
|
|
||||||
|
if (fd < 0) {
|
||||||
|
set_last_error(saved_errno ? strerror(saved_errno) : "connect failed");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
g_last_error[0] = '\0';
|
||||||
|
return (int32_t)fd;
|
||||||
|
}
|
||||||
|
|
||||||
|
MOONBIT_FFI_EXPORT
|
||||||
|
int32_t moon_i2p_tcp_send(
|
||||||
|
int32_t fd,
|
||||||
|
moonbit_bytes_t data,
|
||||||
|
int32_t offset,
|
||||||
|
int32_t len) {
|
||||||
|
if (fd < 0 || offset < 0 || len < 0) {
|
||||||
|
set_last_error("invalid send arguments");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
if (len == 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
ssize_t n;
|
||||||
|
do {
|
||||||
|
n = send(fd, data + offset, (size_t)len, MSG_NOSIGNAL);
|
||||||
|
} while (n < 0 && errno == EINTR);
|
||||||
|
if (n < 0) {
|
||||||
|
set_last_error(strerror(errno));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
return (int32_t)n;
|
||||||
|
}
|
||||||
|
|
||||||
|
MOONBIT_FFI_EXPORT
|
||||||
|
int32_t moon_i2p_tcp_recv(
|
||||||
|
int32_t fd,
|
||||||
|
moonbit_bytes_t buf,
|
||||||
|
int32_t max_len) {
|
||||||
|
if (fd < 0 || max_len <= 0) {
|
||||||
|
set_last_error("invalid recv arguments");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
ssize_t n;
|
||||||
|
do {
|
||||||
|
n = recv(fd, buf, (size_t)max_len, 0);
|
||||||
|
} while (n < 0 && errno == EINTR);
|
||||||
|
if (n < 0) {
|
||||||
|
set_last_error(strerror(errno));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
return (int32_t)n;
|
||||||
|
}
|
||||||
|
|
||||||
|
MOONBIT_FFI_EXPORT
|
||||||
|
int32_t moon_i2p_tcp_shutdown_write(int32_t fd) {
|
||||||
|
if (fd < 0) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
if (shutdown(fd, SHUT_WR) < 0) {
|
||||||
|
set_last_error(strerror(errno));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
MOONBIT_FFI_EXPORT
|
||||||
|
int32_t moon_i2p_tcp_close(int32_t fd) {
|
||||||
|
if (fd < 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (close(fd) < 0) {
|
||||||
|
set_last_error(strerror(errno));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
MOONBIT_FFI_EXPORT
|
||||||
|
int32_t moon_i2p_read_stdin(moonbit_bytes_t buf, int32_t max_len) {
|
||||||
|
if (max_len <= 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
ssize_t n;
|
||||||
|
do {
|
||||||
|
n = read(STDIN_FILENO, buf, (size_t)max_len);
|
||||||
|
} while (n < 0 && errno == EINTR);
|
||||||
|
if (n < 0) {
|
||||||
|
set_last_error(strerror(errno));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
return (int32_t)n;
|
||||||
|
}
|
||||||
|
|
||||||
|
MOONBIT_FFI_EXPORT
|
||||||
|
void moon_i2p_flush_stdout(void) {
|
||||||
|
fflush(stdout);
|
||||||
|
}
|
||||||
Binary file not shown.
Executable
+129
@@ -0,0 +1,129 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
End-to-end TCP integration test for the compiled native moon-i2p SAMv3 client.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
from mock_sam import MockSamBridge
|
||||||
|
|
||||||
|
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
CLIENT_BIN = os.path.join(
|
||||||
|
REPO_ROOT, "_build", "native", "debug", "build", "cmd", "client", "client.exe"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def run_client(sam_addr: str, args: list[str], stdin_data: str | None = None) -> subprocess.CompletedProcess:
|
||||||
|
cmd = [CLIENT_BIN, "--sam", sam_addr] + args
|
||||||
|
return subprocess.run(
|
||||||
|
cmd,
|
||||||
|
input=stdin_data,
|
||||||
|
text=True,
|
||||||
|
capture_output=True,
|
||||||
|
timeout=15,
|
||||||
|
check=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
if not os.path.exists(CLIENT_BIN):
|
||||||
|
raise SystemExit(f"Client binary not found: {CLIENT_BIN}\nRun: moon build --target native cmd/client")
|
||||||
|
|
||||||
|
bridge = MockSamBridge("127.0.0.1", 0)
|
||||||
|
eepsite_b32 = bridge.register_mock_eepsite("hello.i2p")
|
||||||
|
port = bridge.start()
|
||||||
|
sam_addr = f"127.0.0.1:{port}"
|
||||||
|
print(f"[e2e] Started loopback SAMv3 bridge on {sam_addr} (hello.i2p -> {eepsite_b32})")
|
||||||
|
|
||||||
|
try:
|
||||||
|
# 1. keygen
|
||||||
|
res = run_client(sam_addr, ["keygen"])
|
||||||
|
assert "SAM Version: 3.3" in res.stdout, res.stdout
|
||||||
|
m = re.search(r"B32 Address:\s+([a-z2-7]{52}\.b32\.i2p)", res.stdout)
|
||||||
|
assert m is not None, f"missing valid b32 in keygen output:\n{res.stdout}"
|
||||||
|
assert "Public:" in res.stdout and "Private:" in res.stdout, res.stdout
|
||||||
|
print(f"[e2e] PASS keygen -> {m.group(1)}")
|
||||||
|
|
||||||
|
# 2. lookup
|
||||||
|
res = run_client(sam_addr, ["lookup", "hello.i2p"])
|
||||||
|
assert f"B32 Address: {eepsite_b32}" in res.stdout, res.stdout
|
||||||
|
print(f"[e2e] PASS lookup hello.i2p -> {eepsite_b32}")
|
||||||
|
|
||||||
|
# 3. http-get against mock eepsite over SAMv3 STREAM
|
||||||
|
res = run_client(sam_addr, ["http-get", "hello.i2p", "/status"])
|
||||||
|
assert "HTTP/1.1 200 OK" in res.stdout, res.stdout
|
||||||
|
assert f"Welcome to hello.i2p ({eepsite_b32})" in res.stdout, res.stdout
|
||||||
|
assert "Path: /status" in res.stdout, res.stdout
|
||||||
|
assert ".b32.i2p" in res.stdout, res.stdout
|
||||||
|
print("[e2e] PASS http-get hello.i2p /status -> HTTP/1.1 200 OK")
|
||||||
|
|
||||||
|
# 4. listen + dial: two real MoonBit native client processes talking over SAMv3!
|
||||||
|
listener = subprocess.Popen(
|
||||||
|
[CLIENT_BIN, "--sam", sam_addr, "listen", "pong from moon-i2p listener"],
|
||||||
|
stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.PIPE,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
listener_b32 = None
|
||||||
|
assert listener.stdout is not None
|
||||||
|
for _ in range(10):
|
||||||
|
line = listener.stdout.readline()
|
||||||
|
if not line:
|
||||||
|
break
|
||||||
|
m = re.search(r"B32 Address:\s+([a-z2-7]{52}\.b32\.i2p)", line)
|
||||||
|
if m:
|
||||||
|
listener_b32 = m.group(1)
|
||||||
|
if "Waiting for incoming I2P stream..." in line:
|
||||||
|
break
|
||||||
|
assert listener_b32 is not None, "listener did not print its .b32.i2p address"
|
||||||
|
# Give listener a tiny moment to issue STREAM ACCEPT
|
||||||
|
time.sleep(0.15)
|
||||||
|
|
||||||
|
dial_res = run_client(sam_addr, ["dial", listener_b32, "ping from moon-i2p dialer"])
|
||||||
|
assert "pong from moon-i2p listener" in dial_res.stdout, dial_res.stdout
|
||||||
|
|
||||||
|
listen_rest, listen_err = listener.communicate(timeout=10)
|
||||||
|
assert listener.returncode == 0, f"listener failed: {listen_err}"
|
||||||
|
assert "Accepted from:" in listen_rest, listen_rest
|
||||||
|
assert "Received: ping from moon-i2p dialer" in listen_rest, listen_rest
|
||||||
|
print(f"[e2e] PASS listen + dial ({listener_b32}) bidirectional exchange")
|
||||||
|
|
||||||
|
# 5. dial with stdin payload
|
||||||
|
listener2 = subprocess.Popen(
|
||||||
|
[CLIENT_BIN, "--sam", sam_addr, "listen", "stdin-ack"],
|
||||||
|
stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.PIPE,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
listener2_b32 = None
|
||||||
|
assert listener2.stdout is not None
|
||||||
|
for _ in range(10):
|
||||||
|
line = listener2.stdout.readline()
|
||||||
|
if not line:
|
||||||
|
break
|
||||||
|
m = re.search(r"B32 Address:\s+([a-z2-7]{52}\.b32\.i2p)", line)
|
||||||
|
if m:
|
||||||
|
listener2_b32 = m.group(1)
|
||||||
|
if "Waiting for incoming I2P stream..." in line:
|
||||||
|
break
|
||||||
|
assert listener2_b32 is not None
|
||||||
|
time.sleep(0.15)
|
||||||
|
|
||||||
|
dial_stdin = run_client(sam_addr, ["dial", listener2_b32], stdin_data="hello via stdin")
|
||||||
|
assert "stdin-ack" in dial_stdin.stdout, dial_stdin.stdout
|
||||||
|
listen2_rest, _ = listener2.communicate(timeout=10)
|
||||||
|
assert "Received: hello via stdin" in listen2_rest, listen2_rest
|
||||||
|
print("[e2e] PASS dial (stdin) + listen")
|
||||||
|
|
||||||
|
print("[e2e] ALL END-TO-END TESTS PASSED!")
|
||||||
|
finally:
|
||||||
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Executable
+351
@@ -0,0 +1,351 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Lightweight local loopback SAMv3 bridge for end-to-end testing of moon-i2p.
|
||||||
|
|
||||||
|
Implements the core SAMv3 text protocol over real TCP sockets:
|
||||||
|
- HELLO VERSION
|
||||||
|
- DEST GENERATE
|
||||||
|
- NAMING LOOKUP (ME, *.b32.i2p, and registered *.i2p aliases)
|
||||||
|
- SESSION CREATE (STYLE=STREAM, TRANSIENT or persistent destination)
|
||||||
|
- STREAM ACCEPT (SILENT=false)
|
||||||
|
- STREAM CONNECT (SILENT=false) with bidirectional TCP half-close bridging
|
||||||
|
|
||||||
|
Optionally hosts a built-in mock HTTP/1.1 eepsite (default: hello.i2p) so
|
||||||
|
`http-get` and `lookup` can be exercised out of the box.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import os
|
||||||
|
import queue
|
||||||
|
import shlex
|
||||||
|
import socket
|
||||||
|
import struct
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
|
||||||
|
I2P_B64_TRANS = str.maketrans("+/", "-~")
|
||||||
|
STD_B64_TRANS = str.maketrans("-~", "+/")
|
||||||
|
|
||||||
|
|
||||||
|
def i2p_b64encode(data: bytes) -> str:
|
||||||
|
return base64.b64encode(data).decode("ascii").translate(I2P_B64_TRANS)
|
||||||
|
|
||||||
|
|
||||||
|
def i2p_b64decode(s: str) -> bytes:
|
||||||
|
return base64.b64decode(s.translate(STD_B64_TRANS))
|
||||||
|
|
||||||
|
|
||||||
|
def generate_x25519_ed25519_dest() -> tuple[str, str, str]:
|
||||||
|
"""Generates a valid 391-byte I2P Destination (X25519 + Ed25519 KeyCert)."""
|
||||||
|
crypto_pub = os.urandom(32)
|
||||||
|
padding = os.urandom(320)
|
||||||
|
signing_pub = os.urandom(32)
|
||||||
|
# Certificate: type=5 (Key), length=4, sig_type=7 (Ed25519), crypto_type=4 (X25519)
|
||||||
|
cert = struct.pack(">BHHH", 5, 4, 7, 4)
|
||||||
|
pub_bytes = crypto_pub + padding + signing_pub + cert
|
||||||
|
assert len(pub_bytes) == 391
|
||||||
|
# Private key blob starts with public destination bytes + private key material
|
||||||
|
priv_bytes = pub_bytes + os.urandom(64)
|
||||||
|
b32 = base64.b32encode(hashlib.sha256(pub_bytes).digest()).decode("ascii").lower().rstrip("=") + ".b32.i2p"
|
||||||
|
return i2p_b64encode(pub_bytes), i2p_b64encode(priv_bytes), b32
|
||||||
|
|
||||||
|
|
||||||
|
def pub_from_dest_blob(b64_blob: str) -> tuple[str, str]:
|
||||||
|
raw = i2p_b64decode(b64_blob)
|
||||||
|
if len(raw) < 387:
|
||||||
|
raise ValueError("destination too short")
|
||||||
|
cert_type = raw[384]
|
||||||
|
cert_len = struct.unpack(">H", raw[385:387])[0]
|
||||||
|
pub_bytes = raw[: 387 + cert_len]
|
||||||
|
b32 = base64.b32encode(hashlib.sha256(pub_bytes).digest()).decode("ascii").lower().rstrip("=") + ".b32.i2p"
|
||||||
|
return i2p_b64encode(pub_bytes), b32
|
||||||
|
|
||||||
|
|
||||||
|
def parse_sam_line(line: str) -> tuple[str, str | None, dict[str, str]]:
|
||||||
|
tokens = shlex.split(line.strip())
|
||||||
|
if not tokens:
|
||||||
|
return "", None, {}
|
||||||
|
verb = tokens[0]
|
||||||
|
idx = 1
|
||||||
|
sub = None
|
||||||
|
if idx < len(tokens) and "=" not in tokens[idx]:
|
||||||
|
sub = tokens[idx]
|
||||||
|
idx += 1
|
||||||
|
params: dict[str, str] = {}
|
||||||
|
for tok in tokens[idx:]:
|
||||||
|
k, _, v = tok.partition("=")
|
||||||
|
params[k] = v
|
||||||
|
return verb, sub, params
|
||||||
|
|
||||||
|
|
||||||
|
def read_line(sock: socket.socket) -> str | None:
|
||||||
|
chunks = bytearray()
|
||||||
|
while True:
|
||||||
|
b = sock.recv(1)
|
||||||
|
if not b:
|
||||||
|
return chunks.decode("utf-8") if chunks else None
|
||||||
|
if b == b"\n":
|
||||||
|
return chunks.decode("utf-8").rstrip("\r")
|
||||||
|
chunks.extend(b)
|
||||||
|
|
||||||
|
|
||||||
|
def relay_half(src: socket.socket, dst: socket.socket) -> None:
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
data = src.recv(4096)
|
||||||
|
if not data:
|
||||||
|
try:
|
||||||
|
dst.shutdown(socket.SHUT_WR)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
break
|
||||||
|
dst.sendall(data)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def bridge_sockets(a: socket.socket, b: socket.socket) -> None:
|
||||||
|
t1 = threading.Thread(target=relay_half, args=(a, b), daemon=True)
|
||||||
|
t2 = threading.Thread(target=relay_half, args=(b, a), daemon=True)
|
||||||
|
t1.start()
|
||||||
|
t2.start()
|
||||||
|
t1.join()
|
||||||
|
t2.join()
|
||||||
|
for s in (a, b):
|
||||||
|
try:
|
||||||
|
s.close()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Session:
|
||||||
|
def __init__(self, sid: str, pub_b64: str, priv_b64: str, b32: str):
|
||||||
|
self.id = sid
|
||||||
|
self.pub_b64 = pub_b64
|
||||||
|
self.priv_b64 = priv_b64
|
||||||
|
self.b32 = b32
|
||||||
|
self.acceptors: queue.Queue[tuple[socket.socket, threading.Event]] = queue.Queue()
|
||||||
|
self.custom_handler = None # optional callable(peer_pub_b64, peer_b32, conn_sock)
|
||||||
|
|
||||||
|
|
||||||
|
class MockSamBridge:
|
||||||
|
def __init__(self, host: str = "127.0.0.1", port: int = 7656):
|
||||||
|
self.host = host
|
||||||
|
self.port = port
|
||||||
|
self.lock = threading.Lock()
|
||||||
|
self.sessions_by_id: dict[str, Session] = {}
|
||||||
|
self.sessions_by_pub: dict[str, Session] = {}
|
||||||
|
self.names: dict[str, str] = {} # hostname / b32 -> pub_b64
|
||||||
|
self.server_sock: socket.socket | None = None
|
||||||
|
self.running = False
|
||||||
|
|
||||||
|
def register_mock_eepsite(self, hostname: str) -> str:
|
||||||
|
pub_b64, priv_b64, b32 = generate_x25519_ed25519_dest()
|
||||||
|
sess = Session(f"eepsite-{hostname}", pub_b64, priv_b64, b32)
|
||||||
|
|
||||||
|
def handle_http(peer_pub: str, peer_b32: str, conn: socket.socket) -> None:
|
||||||
|
try:
|
||||||
|
req_data = bytearray()
|
||||||
|
while b"\r\n\r\n" not in req_data:
|
||||||
|
chunk = conn.recv(4096)
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
req_data.extend(chunk)
|
||||||
|
first_line = req_data.decode("utf-8", errors="replace").split("\r\n", 1)[0]
|
||||||
|
parts = first_line.split(" ")
|
||||||
|
path = parts[1] if len(parts) >= 2 else "/"
|
||||||
|
body = (
|
||||||
|
f"Welcome to {hostname} ({b32})\n"
|
||||||
|
f"Path: {path}\n"
|
||||||
|
f"Client: {peer_b32}\n"
|
||||||
|
).encode("utf-8")
|
||||||
|
resp = (
|
||||||
|
b"HTTP/1.1 200 OK\r\n"
|
||||||
|
b"Content-Type: text/plain; charset=utf-8\r\n"
|
||||||
|
+ f"Content-Length: {len(body)}\r\n".encode("ascii")
|
||||||
|
+ b"Connection: close\r\n\r\n"
|
||||||
|
+ body
|
||||||
|
)
|
||||||
|
conn.sendall(resp)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
conn.close()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
sess.custom_handler = handle_http
|
||||||
|
with self.lock:
|
||||||
|
self.sessions_by_id[sess.id] = sess
|
||||||
|
self.sessions_by_pub[pub_b64] = sess
|
||||||
|
self.names[hostname] = pub_b64
|
||||||
|
self.names[b32] = pub_b64
|
||||||
|
return b32
|
||||||
|
|
||||||
|
def start(self) -> int:
|
||||||
|
self.server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
self.server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||||
|
self.server_sock.bind((self.host, self.port))
|
||||||
|
self.server_sock.listen(64)
|
||||||
|
self.port = self.server_sock.getsockname()[1]
|
||||||
|
self.running = True
|
||||||
|
threading.Thread(target=self._accept_loop, daemon=True).start()
|
||||||
|
return self.port
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
self.running = False
|
||||||
|
if self.server_sock:
|
||||||
|
try:
|
||||||
|
self.server_sock.close()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _accept_loop(self) -> None:
|
||||||
|
assert self.server_sock is not None
|
||||||
|
while self.running:
|
||||||
|
try:
|
||||||
|
conn, _ = self.server_sock.accept()
|
||||||
|
except OSError:
|
||||||
|
break
|
||||||
|
threading.Thread(target=self._handle_client, args=(conn,), daemon=True).start()
|
||||||
|
|
||||||
|
def _handle_client(self, conn: socket.socket) -> None:
|
||||||
|
session: Session | None = None
|
||||||
|
handshaked = False
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
line = read_line(conn)
|
||||||
|
if line is None:
|
||||||
|
break
|
||||||
|
if not line.strip():
|
||||||
|
continue
|
||||||
|
verb, sub, params = parse_sam_line(line)
|
||||||
|
|
||||||
|
if verb == "HELLO" and sub == "VERSION":
|
||||||
|
handshaked = True
|
||||||
|
conn.sendall(b"HELLO REPLY RESULT=OK VERSION=3.3\n")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not handshaked:
|
||||||
|
conn.sendall(b"HELLO REPLY RESULT=I2P_ERROR MESSAGE=\"HELLO required\"\n")
|
||||||
|
break
|
||||||
|
|
||||||
|
if verb == "DEST" and sub == "GENERATE":
|
||||||
|
pub_b64, priv_b64, _ = generate_x25519_ed25519_dest()
|
||||||
|
conn.sendall(f"DEST REPLY PUB={pub_b64} PRIV={priv_b64}\n".encode("utf-8"))
|
||||||
|
continue
|
||||||
|
|
||||||
|
if verb == "NAMING" and sub == "LOOKUP":
|
||||||
|
name = params.get("NAME", "")
|
||||||
|
if name == "ME" and session is not None:
|
||||||
|
conn.sendall(f"NAMING REPLY RESULT=OK NAME=ME VALUE={session.pub_b64}\n".encode("utf-8"))
|
||||||
|
else:
|
||||||
|
with self.lock:
|
||||||
|
val = self.names.get(name)
|
||||||
|
if val:
|
||||||
|
conn.sendall(f"NAMING REPLY RESULT=OK NAME={name} VALUE={val}\n".encode("utf-8"))
|
||||||
|
else:
|
||||||
|
conn.sendall(f"NAMING REPLY RESULT=KEY_NOT_FOUND NAME={name}\n".encode("utf-8"))
|
||||||
|
continue
|
||||||
|
|
||||||
|
if verb == "SESSION" and sub == "CREATE":
|
||||||
|
sid = params.get("ID", "")
|
||||||
|
dest_arg = params.get("DESTINATION", "TRANSIENT")
|
||||||
|
if dest_arg == "TRANSIENT":
|
||||||
|
pub_b64, priv_b64, b32 = generate_x25519_ed25519_dest()
|
||||||
|
else:
|
||||||
|
pub_b64, b32 = pub_from_dest_blob(dest_arg)
|
||||||
|
priv_b64 = dest_arg
|
||||||
|
with self.lock:
|
||||||
|
if sid in self.sessions_by_id:
|
||||||
|
conn.sendall(b"SESSION STATUS RESULT=DUPLICATED_ID MESSAGE=\"Session ID already in use\"\n")
|
||||||
|
continue
|
||||||
|
session = Session(sid, pub_b64, priv_b64, b32)
|
||||||
|
self.sessions_by_id[sid] = session
|
||||||
|
self.sessions_by_pub[pub_b64] = session
|
||||||
|
self.names[b32] = pub_b64
|
||||||
|
conn.sendall(f"SESSION STATUS RESULT=OK DESTINATION={priv_b64}\n".encode("utf-8"))
|
||||||
|
continue
|
||||||
|
|
||||||
|
if verb == "STREAM" and sub == "ACCEPT":
|
||||||
|
sid = params.get("ID", "")
|
||||||
|
with self.lock:
|
||||||
|
target_sess = self.sessions_by_id.get(sid)
|
||||||
|
if target_sess is None:
|
||||||
|
conn.sendall(b"STREAM STATUS RESULT=INVALID_ID MESSAGE=\"Unknown session ID\"\n")
|
||||||
|
break
|
||||||
|
conn.sendall(b"STREAM STATUS RESULT=OK\n")
|
||||||
|
done = threading.Event()
|
||||||
|
target_sess.acceptors.put((conn, done))
|
||||||
|
# Ownership of `conn` passes to the bridge once matched
|
||||||
|
done.wait()
|
||||||
|
return
|
||||||
|
|
||||||
|
if verb == "STREAM" and sub == "CONNECT":
|
||||||
|
sid = params.get("ID", "")
|
||||||
|
target_dest = params.get("DESTINATION", "")
|
||||||
|
with self.lock:
|
||||||
|
src_sess = self.sessions_by_id.get(sid)
|
||||||
|
dst_sess = self.sessions_by_pub.get(target_dest)
|
||||||
|
if src_sess is None:
|
||||||
|
conn.sendall(b"STREAM STATUS RESULT=INVALID_ID MESSAGE=\"Unknown session ID\"\n")
|
||||||
|
break
|
||||||
|
if dst_sess is None:
|
||||||
|
conn.sendall(b"STREAM STATUS RESULT=CANT_REACH_PEER MESSAGE=\"Destination not found\"\n")
|
||||||
|
break
|
||||||
|
|
||||||
|
if dst_sess.custom_handler is not None:
|
||||||
|
conn.sendall(b"STREAM STATUS RESULT=OK\n")
|
||||||
|
dst_sess.custom_handler(src_sess.pub_b64, src_sess.b32, conn)
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
acc_sock, done_ev = dst_sess.acceptors.get(timeout=10.0)
|
||||||
|
except queue.Empty:
|
||||||
|
conn.sendall(b"STREAM STATUS RESULT=TIMEOUT MESSAGE=\"No pending STREAM ACCEPT\"\n")
|
||||||
|
break
|
||||||
|
|
||||||
|
conn.sendall(b"STREAM STATUS RESULT=OK\n")
|
||||||
|
acc_sock.sendall(f"{src_sess.pub_b64} FROM_PORT=0 TO_PORT=0\n".encode("utf-8"))
|
||||||
|
bridge_sockets(conn, acc_sock)
|
||||||
|
done_ev.set()
|
||||||
|
return
|
||||||
|
|
||||||
|
conn.sendall(f"ERROR MESSAGE=\"Unsupported command: {verb} {sub}\"\n".encode("utf-8"))
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
if session is not None:
|
||||||
|
with self.lock:
|
||||||
|
self.sessions_by_id.pop(session.id, None)
|
||||||
|
self.sessions_by_pub.pop(session.pub_b64, None)
|
||||||
|
self.names.pop(session.b32, None)
|
||||||
|
try:
|
||||||
|
conn.close()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
parser = argparse.ArgumentParser(description="Mock SAMv3 loopback bridge for moon-i2p")
|
||||||
|
parser.add_argument("--host", default="127.0.0.1")
|
||||||
|
parser.add_argument("--port", type=int, default=7656)
|
||||||
|
parser.add_argument("--eepsite", default="hello.i2p")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
bridge = MockSamBridge(args.host, args.port)
|
||||||
|
b32 = bridge.register_mock_eepsite(args.eepsite)
|
||||||
|
bound_port = bridge.start()
|
||||||
|
print(f"Mock SAMv3 bridge listening on {args.host}:{bound_port}", flush=True)
|
||||||
|
print(f"Mock eepsite {args.eepsite} -> {b32}", flush=True)
|
||||||
|
try:
|
||||||
|
threading.Event().wait()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in new issue
Block a user