///| /// 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=` 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=` 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() }