Files
moon-i2p/sam/sam.mbt
T
nandi 4d79d78f06
check / check (macos-latest) (push) Failing after 28s
check / check (ubuntu-latest) (push) Failing after 29s
check / check (windows-latest) (push) Failing after 30s
feat: add working native SAMv3 TCP client and CLI with sane defaults
2026-11-27 19:10:01 +00:00

293 lines
6.5 KiB
MoonBit

///|
/// Errors raised when parsing SAMv3 protocol lines.
#derive(Eq, Debug)
pub suberror SamError {
EmptyMessage
UnterminatedQuote
MalformedToken(String)
}
///|
/// A parsed SAMv3 protocol command or reply line:
/// `VERB [SUBCOMMAND] [KEY=VALUE ...]` terminated by `\n`.
#derive(Eq, Debug)
pub(all) struct SamMessage {
verb : String
subcommand : String?
params : Array[(String, String)]
}
///|
pub fn SamMessage::new(
verb : String,
subcommand~ : String? = None,
params~ : Array[(String, String)] = [],
) -> SamMessage {
{ verb, subcommand, params, }
}
///|
pub fn SamMessage::get(self : SamMessage, key : String) -> String? {
for entry in self.params {
if entry.0 == key {
return Some(entry.1)
}
}
None
}
///|
pub fn SamMessage::result(self : SamMessage) -> String? {
self.get("RESULT")
}
///|
pub fn SamMessage::is_ok(self : SamMessage) -> Bool {
self.result() == Some("OK")
}
///|
fn needs_quoting(s : String) -> Bool {
if s.length() == 0 {
return true
}
for ch in s {
if ch == ' ' ||
ch == '\t' ||
ch == '"' ||
ch == '\\' ||
ch == '\n' ||
ch == '\r' {
return true
}
}
false
}
///|
fn quote_value(s : String) -> String {
if !needs_quoting(s) {
return s
}
let buf = StringBuilder(capacity=s.length() + 2)
buf.write_char('"')
for ch in s {
if ch == '"' || ch == '\\' {
buf.write_char('\\')
}
buf.write_char(ch)
}
buf.write_char('"')
buf.to_string()
}
///|
/// Serializes a `SamMessage` into a single `\n`-terminated SAMv3 wire line.
pub fn SamMessage::serialize(self : SamMessage) -> String {
let buf = StringBuilder()
buf.write_string(self.verb)
match self.subcommand {
Some(sub) => {
buf.write_char(' ')
buf.write_string(sub)
}
None => ()
}
for entry in self.params {
buf.write_char(' ')
buf.write_string(entry.0)
buf.write_char('=')
buf.write_string(quote_value(entry.1))
}
buf.write_char('\n')
buf.to_string()
}
///|
/// Tokenizes a SAMv3 line respecting `"..."` quoted values and `\"` escapes.
fn tokenize_sam_line(line : String) -> Array[String] raise SamError {
let chars : Array[Char] = []
for ch in line {
if ch != '\r' && ch != '\n' {
chars.push(ch)
}
}
let tokens : Array[String] = []
let len = chars.length()
let mut i = 0
while i < len {
while i < len && (chars[i] == ' ' || chars[i] == '\t') {
i += 1
}
if i >= len {
break
}
let buf = StringBuilder()
let mut in_quotes = false
while i < len {
let c = chars[i]
if in_quotes {
if c == '\\' {
i += 1
if i >= len {
raise UnterminatedQuote
}
buf.write_char(chars[i])
i += 1
} else if c == '"' {
in_quotes = false
i += 1
} else {
buf.write_char(c)
i += 1
}
} else if c == ' ' || c == '\t' {
break
} else if c == '"' {
in_quotes = true
i += 1
} else {
buf.write_char(c)
i += 1
}
}
if in_quotes {
raise UnterminatedQuote
}
tokens.push(buf.to_string())
}
tokens
}
///|
fn split_kv(token : String) -> (String, String)? {
let chars : Array[Char] = []
for ch in token {
chars.push(ch)
}
let mut eq_idx = -1
for i = 0; i < chars.length(); i = i + 1 {
if chars[i] == '=' {
eq_idx = i
break
}
}
if eq_idx <= 0 {
return None
}
let kbuf = StringBuilder(capacity=eq_idx)
for i = 0; i < eq_idx; i = i + 1 {
kbuf.write_char(chars[i])
}
let vbuf = StringBuilder(capacity=chars.length() - eq_idx - 1)
for i = eq_idx + 1; i < chars.length(); i = i + 1 {
vbuf.write_char(chars[i])
}
Some((kbuf.to_string(), vbuf.to_string()))
}
///|
/// Parses a SAMv3 protocol line into a `SamMessage`.
pub fn SamMessage::parse(line : String) -> SamMessage raise SamError {
let tokens = tokenize_sam_line(line)
if tokens.length() == 0 {
raise EmptyMessage
}
let verb = tokens[0]
let mut idx = 1
let mut subcommand : String? = None
if idx < tokens.length() {
match split_kv(tokens[idx]) {
None => {
subcommand = Some(tokens[idx])
idx += 1
}
Some(_) => ()
}
}
let params : Array[(String, String)] = []
while idx < tokens.length() {
match split_kv(tokens[idx]) {
Some(kv) => params.push(kv)
None => raise MalformedToken(tokens[idx])
}
idx += 1
}
{ verb, subcommand, params, }
}
///|
/// Builds `HELLO VERSION MIN=3.1 MAX=3.3`.
pub fn hello_version(
min~ : String = "3.1",
max~ : String = "3.3",
) -> SamMessage {
SamMessage::new("HELLO", subcommand=Some("VERSION"), params=[
("MIN", min),
("MAX", max),
])
}
///|
/// 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(
style : String,
id : String,
destination~ : String = "TRANSIENT",
signature_type~ : String = "7",
options~ : Array[(String, String)] = [],
) -> SamMessage {
let params : Array[(String, String)] = [
("STYLE", style),
("ID", id),
("DESTINATION", destination),
]
if destination == "TRANSIENT" {
params.push(("SIGNATURE_TYPE", signature_type))
}
for opt in options {
params.push(opt)
}
SamMessage::new("SESSION", subcommand=Some("CREATE"), params~)
}
///|
/// Builds `STREAM CONNECT ID=<id> DESTINATION=<dest> SILENT=<silent>`.
pub fn stream_connect(
id : String,
destination : String,
silent~ : Bool = false,
) -> SamMessage {
SamMessage::new("STREAM", subcommand=Some("CONNECT"), params=[
("ID", id),
("DESTINATION", destination),
("SILENT", if silent { "true" } else { "false" }),
])
}
///|
/// Builds `STREAM ACCEPT ID=<id> SILENT=<silent>`.
pub fn stream_accept(id : String, silent~ : Bool = false) -> SamMessage {
SamMessage::new("STREAM", subcommand=Some("ACCEPT"), params=[
("ID", id),
("SILENT", if silent { "true" } else { "false" }),
])
}
///|
/// Builds `NAMING LOOKUP NAME=<name>`.
pub fn naming_lookup(name : String) -> SamMessage {
SamMessage::new("NAMING", subcommand=Some("LOOKUP"), params=[("NAME", name)])
}
///|
/// Builds `DEST GENERATE SIGNATURE_TYPE=<sig_type>` (default `7` = EdDSA_SHA512_Ed25519).
pub fn dest_generate(signature_type~ : String = "7") -> SamMessage {
SamMessage::new("DEST", subcommand=Some("GENERATE"), params=[
("SIGNATURE_TYPE", signature_type),
])
}