feat: add ratchet, streaming, SU3 reseed, and router floodfill
- Add ratchet/ with ECIES-X25519-AEAD-Ratchet (Proposal 144), Garlic cloves, and ECIES DatabaseLookup replies - Add streaming/ with Ed25519-signed I2P Streaming (SYN/ACK/NACK/CLOSE/RESET, retransmit, window) and Repliable/Raw Datagrams - Add common/su3.mbt to parse and verify reseed .su3 bundles - Add Elligator2 encoding in crypto/ and OfflineSignature support in LeaseSet2 (flags bit 0) - Router: NTCP2 peer pool, floodfill NetDB crawl, transit tunnel relay, and Garlic/Streaming bridge - cmd/router: add --peer-dir, --su3, --reseed, --floodfill, --no-clock-skew - cmd/client: add --dest for persistent destination keys - Mark Phase 6 complete in README and document the transport scope (NTCP2 only, no SSU2)
This commit is contained in:
1 parent
8eafa11b22
commit
ae72b00323
54 files changed
+9607
-704
No files matched your search
+263
-470
@@ -1,6 +1,7 @@
|
||||
///|
|
||||
/// Native MoonBit I2P Router Core with transient identity, NetDB, TunnelManager,
|
||||
/// NTCP2 TCP listener, and embedded SAMv3 TCP bridge (single-threaded poll loop).
|
||||
/// Native MoonBit I2P Router Core with transient/persistent SAM sessions, NetDB floodfill
|
||||
/// protocol, Proposal 157 multi-hop TunnelManager, non-blocking NTCP2 peer pool,
|
||||
/// Proposal 144 ECIES-X25519-AEAD-Ratchet Garlic, and Ed25519 I2P Streaming.
|
||||
|
||||
///|
|
||||
#derive(Eq, Debug)
|
||||
@@ -10,6 +11,9 @@ pub suberror RouterError {
|
||||
Common(@common.CommonError)
|
||||
Noise(@noise.NoiseError)
|
||||
NetDb(@netdb.NetDbError)
|
||||
I2np(@i2np.I2npError)
|
||||
Tunnel(@tunnel.TunnelError)
|
||||
Protocol(String)
|
||||
}
|
||||
|
||||
///|
|
||||
@@ -31,31 +35,6 @@ pub fn RouterConfig::default() -> RouterConfig {
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
priv struct SamSession {
|
||||
id : String
|
||||
pub_b64 : String
|
||||
b32 : String
|
||||
}
|
||||
|
||||
///|
|
||||
priv struct SamClientConn {
|
||||
sock : @ntcp2_net.TcpSocket
|
||||
mut session_id : String?
|
||||
mut mode : Int32 // 0 = command, 1 = waiting_accept, 2 = bridged
|
||||
mut accept_session_id : String
|
||||
mut accept_silent : Bool
|
||||
mut closed : Bool
|
||||
}
|
||||
|
||||
///|
|
||||
priv struct StreamBridge {
|
||||
a : @ntcp2_net.TcpSocket
|
||||
b : @ntcp2_net.TcpSocket
|
||||
mut a_eof : Bool
|
||||
mut b_eof : Bool
|
||||
}
|
||||
|
||||
///|
|
||||
/// Live MoonBit I2P Router Core instance.
|
||||
pub struct Router {
|
||||
@@ -67,45 +46,93 @@ pub struct Router {
|
||||
tunnels : @tunnel.TunnelManager
|
||||
ntcp2_listener : @ntcp2_net.TcpListener
|
||||
sam_listener : @ntcp2_net.TcpListener
|
||||
check_clock_skew : Bool
|
||||
priv mut next_msg_id : UInt32
|
||||
priv mut next_tunnel_id : UInt32
|
||||
priv mut next_stream_id : UInt32
|
||||
priv replay_cache : @ntcp2.EphemeralReplayCache
|
||||
priv pending_accepts : Array[@ntcp2_net.PendingNtcp2Accept]
|
||||
priv pending_dials : Array[PendingPeerDial]
|
||||
priv peers : Array[PeerSession]
|
||||
priv pending_sends : Array[PendingPeerSend]
|
||||
priv pending_lookups : Array[PendingNetDbLookup]
|
||||
priv pending_builds : Array[PendingTunnelBuild]
|
||||
priv reassembler : @tunnel.FragmentReassembler
|
||||
priv sessions : Array[SamSession]
|
||||
priv sam_clients : Array[SamClientConn]
|
||||
priv bridges : Array[StreamBridge]
|
||||
priv remote_bridges : Array[RemoteStreamBridge]
|
||||
priv aliases : Array[(String, String)] // hostname -> pub_b64
|
||||
}
|
||||
|
||||
///|
|
||||
/// Generates a valid transient 391-byte X25519+Ed25519 I2P Destination and
|
||||
/// returns `(dest, pub_b64, priv_b64, ed_seed)`.
|
||||
fn generate_transient_destination() -> (
|
||||
@common.Destination,
|
||||
String,
|
||||
String,
|
||||
Bytes,
|
||||
) raise RouterError {
|
||||
let ed_seed = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) }
|
||||
let ed_pub = @crypto.ed25519_public_key(ed_seed) catch {
|
||||
e => raise Crypto(e)
|
||||
fn u32_from_be_prefix(b : Bytes) -> UInt32 {
|
||||
(
|
||||
(b[0].to_uint() << 24) |
|
||||
(b[1].to_uint() << 16) |
|
||||
(b[2].to_uint() << 8) |
|
||||
b[3].to_uint()
|
||||
) &
|
||||
0x7FFFFFFFU
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::alloc_msg_id(self : Router) -> UInt32 {
|
||||
let mut id = self.next_msg_id
|
||||
if id == 0U {
|
||||
id = 1U
|
||||
}
|
||||
let x_priv = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) }
|
||||
let x_pub = @crypto.x25519_public_key(x_priv) catch { e => raise Crypto(e) }
|
||||
let pad = @ntcp2_net.random_bytes(320) catch { e => raise Net(e) }
|
||||
let dest = @common.Destination::new_x25519_ed25519(x_pub, ed_pub, padding=pad) catch {
|
||||
e => raise Common(e)
|
||||
self.next_msg_id = id + 1U
|
||||
id
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::alloc_tunnel_id(self : Router) -> UInt32 {
|
||||
let mut id = self.next_tunnel_id
|
||||
if id == 0U {
|
||||
id = 1U
|
||||
}
|
||||
let pub_bytes = dest.to_bytes()
|
||||
let priv_w = @encoding.Writer::new(capacity=pub_bytes.length() + 64)
|
||||
priv_w.write_bytes(pub_bytes)
|
||||
priv_w.write_bytes(x_priv)
|
||||
priv_w.write_bytes(ed_seed)
|
||||
let pub_b64 = @encoding.base64_encode(pub_bytes)
|
||||
let priv_b64 = @encoding.base64_encode(priv_w.to_bytes())
|
||||
(dest, pub_b64, priv_b64, ed_seed)
|
||||
self.next_tunnel_id = id + 1U
|
||||
id
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::alloc_stream_id(self : Router) -> UInt32 {
|
||||
let mut id = self.next_stream_id
|
||||
if id == 0U {
|
||||
id = 1U
|
||||
}
|
||||
self.next_stream_id = id + 1U
|
||||
id
|
||||
}
|
||||
|
||||
///|
|
||||
fn next_rand_32() -> Bytes {
|
||||
@ntcp2_net.random_bytes(32) catch {
|
||||
_ => Bytes::make(32, b'\x42')
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn non_zero_random_bytes(n : Int32) -> Bytes {
|
||||
let raw = @ntcp2_net.random_bytes(n) catch {
|
||||
_ => return Bytes::make(n, b'\x01')
|
||||
}
|
||||
let out = FixedArray::make(n, b'\x01')
|
||||
for i = 0; i < raw.length(); i = i + 1 {
|
||||
out[i] = if raw[i] == b'\x00' { b'\x01' } else { raw[i] }
|
||||
}
|
||||
Bytes::from_array(out)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Starts the MoonBit I2P Router Core with transient keys, self-signed `RouterInfo`,
|
||||
/// NTCP2 TCP listener, and embedded SAMv3 TCP bridge.
|
||||
pub fn Router::start(config : RouterConfig) -> Router raise RouterError {
|
||||
pub fn Router::start(
|
||||
config : RouterConfig,
|
||||
floodfill~ : Bool = false,
|
||||
check_clock_skew~ : Bool = true,
|
||||
) -> Router raise RouterError {
|
||||
let ed_seed = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) }
|
||||
let ed_pub = @crypto.ed25519_public_key(ed_seed) catch {
|
||||
e => raise Crypto(e)
|
||||
@@ -143,12 +170,13 @@ pub fn Router::start(config : RouterConfig) -> Router raise RouterError {
|
||||
("s", @encoding.base64_encode(static_key.public_key)),
|
||||
("v", "2"),
|
||||
])
|
||||
let caps = if floodfill { "LRf" } else { "LR" }
|
||||
let ri : @common.RouterInfo = {
|
||||
identity: id,
|
||||
published: @ntcp2_net.unix_time_ms(),
|
||||
addresses: [@common.RouterAddress::new(b'\x03', "NTCP2", addr_opts)],
|
||||
options: @common.Mapping::from_entries([
|
||||
("caps", "LR"),
|
||||
("caps", caps),
|
||||
("netId", "2"),
|
||||
("router.version", "0.9.64"),
|
||||
]),
|
||||
@@ -157,7 +185,13 @@ pub fn Router::start(config : RouterConfig) -> Router raise RouterError {
|
||||
let signed_ri = ri.sign_ed25519(ed_seed) catch { e => raise Common(e) }
|
||||
let netdb = @netdb.NetDb::new()
|
||||
let _ = netdb.store_router_info(signed_ri) catch { e => raise NetDb(e) }
|
||||
let router : Router = {
|
||||
let rseed = @ntcp2_net.random_bytes(12) catch {
|
||||
_ => Bytes::make(12, b'\x01')
|
||||
}
|
||||
let m0 = u32_from_be_prefix(rseed[:4].to_owned()) | 1U
|
||||
let t0 = u32_from_be_prefix(rseed[4:8].to_owned()) % 0x0FFFFFFFU + 10000U
|
||||
let s0 = u32_from_be_prefix(rseed[8:12].to_owned()) % 0x0FFFFFFFU + 100U
|
||||
{
|
||||
ed_seed,
|
||||
static_key,
|
||||
ntcp2_iv,
|
||||
@@ -166,12 +200,24 @@ pub fn Router::start(config : RouterConfig) -> Router raise RouterError {
|
||||
tunnels: @tunnel.TunnelManager::new(),
|
||||
ntcp2_listener,
|
||||
sam_listener,
|
||||
check_clock_skew,
|
||||
next_msg_id: m0,
|
||||
next_tunnel_id: t0,
|
||||
next_stream_id: s0,
|
||||
replay_cache: @ntcp2.EphemeralReplayCache::new(max_entries=1024),
|
||||
pending_accepts: [],
|
||||
pending_dials: [],
|
||||
peers: [],
|
||||
pending_sends: [],
|
||||
pending_lookups: [],
|
||||
pending_builds: [],
|
||||
reassembler: @tunnel.FragmentReassembler::new(),
|
||||
sessions: [],
|
||||
sam_clients: [],
|
||||
bridges: [],
|
||||
remote_bridges: [],
|
||||
aliases: [],
|
||||
}
|
||||
router
|
||||
}
|
||||
|
||||
///|
|
||||
@@ -220,6 +266,69 @@ pub fn Router::load_peer_file(
|
||||
ri
|
||||
}
|
||||
|
||||
///|
|
||||
/// Scans a directory of `.dat` `RouterInfo` files, verifies Ed25519 signatures,
|
||||
/// and returns how many peer entries were loaded into `self.netdb`.
|
||||
pub fn Router::load_peer_dir(
|
||||
self : Router,
|
||||
dir_path : String,
|
||||
) -> Int32 raise RouterError {
|
||||
let files = @ntcp2_net.list_dir_files(dir_path) catch { e => raise Net(e) }
|
||||
let mut loaded = 0
|
||||
let sep = if dir_path.has_suffix("/") { "" } else { "/" }
|
||||
for fname in files {
|
||||
let full_path = "\{dir_path}\{sep}\{fname}"
|
||||
let ok = try {
|
||||
let _ = self.load_peer_file(full_path)
|
||||
true
|
||||
} catch {
|
||||
_ => false
|
||||
}
|
||||
if ok {
|
||||
loaded += 1
|
||||
}
|
||||
}
|
||||
loaded
|
||||
}
|
||||
|
||||
///|
|
||||
/// Parses raw `.su3` reseed bytes, verifies each contained `RouterInfo`'s Ed25519
|
||||
/// signature, and stores valid peers in `self.netdb`.
|
||||
pub fn Router::load_reseed_su3_bytes(
|
||||
self : Router,
|
||||
su3_bytes : Bytes,
|
||||
) -> Int32 raise RouterError {
|
||||
let ris = @common.parse_reseed_su3(su3_bytes) catch { e => raise Common(e) }
|
||||
let mut count = 0
|
||||
for ri in ris {
|
||||
let stored = self.netdb.store_router_info(ri) catch { _ => false }
|
||||
if stored {
|
||||
count += 1
|
||||
}
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
///|
|
||||
/// Loads a local `.su3` reseed file into `self.netdb`.
|
||||
pub fn Router::load_reseed_su3_file(
|
||||
self : Router,
|
||||
path : String,
|
||||
) -> Int32 raise RouterError {
|
||||
let raw = @ntcp2_net.read_file_bytes(path) catch { e => raise Net(e) }
|
||||
self.load_reseed_su3_bytes(raw)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Fetches an HTTPS `.su3` reseed bundle via system `curl` and imports verified peers.
|
||||
pub fn Router::reseed_from_url(
|
||||
self : Router,
|
||||
url : String,
|
||||
) -> Int32 raise RouterError {
|
||||
let raw = @ntcp2_net.fetch_https_bytes(url) catch { e => raise Net(e) }
|
||||
self.load_reseed_su3_bytes(raw)
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Router::close(self : Router) -> Unit {
|
||||
for c in self.sam_clients {
|
||||
@@ -232,440 +341,124 @@ pub fn Router::close(self : Router) -> Unit {
|
||||
b.a.close()
|
||||
b.b.close()
|
||||
}
|
||||
for rb in self.remote_bridges {
|
||||
if !rb.closed {
|
||||
rb.sock.close()
|
||||
rb.closed = true
|
||||
}
|
||||
}
|
||||
for pa in self.pending_accepts {
|
||||
pa.close()
|
||||
}
|
||||
for pd in self.pending_dials {
|
||||
pd.dial.close()
|
||||
}
|
||||
for p in self.peers {
|
||||
p.conn.close()
|
||||
}
|
||||
self.sam_listener.close()
|
||||
self.ntcp2_listener.close()
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::find_session_by_id(self : Router, id : String) -> SamSession? {
|
||||
for s in self.sessions {
|
||||
if s.id == id {
|
||||
return Some(s)
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::find_session_by_pub(self : Router, pub_b64 : String) -> SamSession? {
|
||||
for s in self.sessions {
|
||||
if s.pub_b64 == pub_b64 {
|
||||
return Some(s)
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::resolve_name(
|
||||
fn Router::handle_i2np_message(
|
||||
self : Router,
|
||||
name : String,
|
||||
client_session_id : String?,
|
||||
) -> String? {
|
||||
if name == "ME" {
|
||||
match client_session_id {
|
||||
Some(sid) =>
|
||||
match self.find_session_by_id(sid) {
|
||||
Some(s) => return Some(s.pub_b64)
|
||||
None => ()
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
return None
|
||||
}
|
||||
let lower = name.to_lower()
|
||||
// Check local aliases
|
||||
for entry in self.aliases {
|
||||
if entry.0 == lower {
|
||||
return Some(entry.1)
|
||||
}
|
||||
}
|
||||
// Check active local sessions by .b32.i2p
|
||||
for s in self.sessions {
|
||||
if s.b32 == lower {
|
||||
return Some(s.pub_b64)
|
||||
}
|
||||
}
|
||||
// Check NetDB LeaseSet2 entries by .b32.i2p
|
||||
let now_sec = @ntcp2_net.unix_time_sec()
|
||||
match self.netdb.get_lease_set2_by_b32(lower, now_sec) {
|
||||
Some(ls2) => return Some(ls2.destination.to_base64())
|
||||
None => ()
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
///|
|
||||
fn send_sam_line(sock : @ntcp2_net.TcpSocket, line : String) -> Bool {
|
||||
sock.write_all(@encoding.string_to_utf8_bytes(line + "\n")) catch {
|
||||
_ => return false
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::handle_sam_command(
|
||||
self : Router,
|
||||
client_idx : Int32,
|
||||
line : String,
|
||||
from_peer : @common.Hash?,
|
||||
hdr : @i2np.ShortHeader,
|
||||
payload : @i2np.I2npPayload,
|
||||
) -> Unit {
|
||||
let client = self.sam_clients[client_idx]
|
||||
let msg = @sam.SamMessage::parse(line) catch {
|
||||
_ => {
|
||||
let _ = send_sam_line(
|
||||
client.sock,
|
||||
"HELLO REPLY RESULT=I2P_ERROR MESSAGE=parse_error",
|
||||
let now_sec = @ntcp2_net.unix_time_sec()
|
||||
match payload {
|
||||
DatabaseStore(
|
||||
key~,
|
||||
store_type~,
|
||||
reply_token~,
|
||||
reply_tunnel_id~,
|
||||
reply_gateway~,
|
||||
data~
|
||||
) =>
|
||||
self.handle_database_store_msg(
|
||||
from_peer, key, store_type, reply_token, reply_tunnel_id, reply_gateway,
|
||||
data, now_sec,
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
match (msg.verb, msg.subcommand) {
|
||||
("HELLO", Some("VERSION")) => {
|
||||
let _ = send_sam_line(client.sock, "HELLO REPLY RESULT=OK VERSION=3.3")
|
||||
}
|
||||
("DEST", Some("GENERATE")) => {
|
||||
let (_dest, pub_b64, priv_b64, _seed) = generate_transient_destination() catch {
|
||||
_ => {
|
||||
let _ = send_sam_line(client.sock, "DEST REPLY RESULT=I2P_ERROR")
|
||||
return
|
||||
}
|
||||
}
|
||||
let _ = send_sam_line(
|
||||
client.sock,
|
||||
"DEST REPLY PUB=\{pub_b64} PRIV=\{priv_b64}",
|
||||
)
|
||||
}
|
||||
("NAMING", Some("LOOKUP")) => {
|
||||
let name = match msg.get("NAME") {
|
||||
Some(n) => n
|
||||
None => {
|
||||
let _ = send_sam_line(
|
||||
client.sock,
|
||||
"NAMING REPLY RESULT=INVALID_KEY NAME=",
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
match self.resolve_name(name, client.session_id) {
|
||||
Some(val) => {
|
||||
let _ = send_sam_line(
|
||||
client.sock,
|
||||
"NAMING REPLY RESULT=OK NAME=\{name} VALUE=\{val}",
|
||||
)
|
||||
}
|
||||
None => {
|
||||
let _ = send_sam_line(
|
||||
client.sock,
|
||||
"NAMING REPLY RESULT=KEY_NOT_FOUND NAME=\{name}",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
("SESSION", Some("CREATE")) => {
|
||||
let sid = match msg.get("ID") {
|
||||
Some(id) => id
|
||||
None => {
|
||||
let _ = send_sam_line(
|
||||
client.sock,
|
||||
"SESSION STATUS RESULT=I2P_ERROR MESSAGE=missing_id",
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
if self.find_session_by_id(sid) is Some(_) {
|
||||
let _ = send_sam_line(
|
||||
client.sock,
|
||||
"SESSION STATUS RESULT=DUPLICATED_ID",
|
||||
)
|
||||
return
|
||||
}
|
||||
let dest_param = match msg.get("DESTINATION") {
|
||||
Some(d) => d
|
||||
None => "TRANSIENT"
|
||||
}
|
||||
let (dest, pub_b64, priv_b64, opt_seed) = if dest_param == "TRANSIENT" {
|
||||
let (d, pb, prb, seed) = generate_transient_destination() catch {
|
||||
_ => {
|
||||
let _ = send_sam_line(
|
||||
client.sock,
|
||||
"SESSION STATUS RESULT=I2P_ERROR",
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
(d, pb, prb, Some(seed))
|
||||
} else {
|
||||
let raw = @encoding.base64_decode(dest_param) catch {
|
||||
_ => {
|
||||
let _ = send_sam_line(
|
||||
client.sock,
|
||||
"SESSION STATUS RESULT=INVALID_KEY",
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
let d = @common.Destination::decode(@encoding.Reader::new(raw)) catch {
|
||||
_ => {
|
||||
let _ = send_sam_line(
|
||||
client.sock,
|
||||
"SESSION STATUS RESULT=INVALID_KEY",
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
(d, d.to_base64(), dest_param, None)
|
||||
}
|
||||
let b32 = dest.b32_address()
|
||||
// Publish a signed LeaseSet2 for transient destinations into our NetDB
|
||||
match opt_seed {
|
||||
Some(seed) => {
|
||||
let now_sec = @ntcp2_net.unix_time_sec()
|
||||
let ls2 : @common.LeaseSet2 = {
|
||||
destination: dest,
|
||||
published_sec: now_sec,
|
||||
expires_offset: 600U,
|
||||
flags: 0U,
|
||||
options: @common.Mapping::new(),
|
||||
encryption_keys: [
|
||||
{ key_type: X25519, key_data: dest.inner.crypto_public_key(), },
|
||||
],
|
||||
leases: [
|
||||
{
|
||||
tunnel_gw: self.router_hash(),
|
||||
tunnel_id: (10000 + self.sessions.length()).reinterpret_as_uint(),
|
||||
end_date_sec: now_sec + 600U,
|
||||
},
|
||||
],
|
||||
signature: b"",
|
||||
}
|
||||
let signed_ls2 = ls2.sign_ed25519(seed) catch { _ => ls2 }
|
||||
let _ = self.netdb.store_lease_set2(signed_ls2, now_sec) catch {
|
||||
_ => false
|
||||
}
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
self.sessions.push({ id: sid, pub_b64, b32, })
|
||||
client.session_id = Some(sid)
|
||||
let _ = send_sam_line(
|
||||
client.sock,
|
||||
"SESSION STATUS RESULT=OK DESTINATION=\{priv_b64}",
|
||||
)
|
||||
}
|
||||
("STREAM", Some("ACCEPT")) => {
|
||||
let sid = match msg.get("ID") {
|
||||
Some(id) => id
|
||||
None => {
|
||||
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID")
|
||||
return
|
||||
}
|
||||
}
|
||||
if self.find_session_by_id(sid) is None {
|
||||
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID")
|
||||
return
|
||||
}
|
||||
let silent = match msg.get("SILENT") {
|
||||
Some(v) => v.to_lower() == "true"
|
||||
None => false
|
||||
}
|
||||
client.mode = 1
|
||||
client.accept_session_id = sid
|
||||
client.accept_silent = silent
|
||||
if !silent {
|
||||
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=OK")
|
||||
}
|
||||
}
|
||||
("STREAM", Some("CONNECT")) => {
|
||||
let sid = match msg.get("ID") {
|
||||
Some(id) => id
|
||||
None => {
|
||||
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID")
|
||||
return
|
||||
}
|
||||
}
|
||||
let caller_sess = match self.find_session_by_id(sid) {
|
||||
Some(s) => s
|
||||
None => {
|
||||
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID")
|
||||
return
|
||||
}
|
||||
}
|
||||
let dest_b64 = match msg.get("DESTINATION") {
|
||||
Some(d) => d
|
||||
None => {
|
||||
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_KEY")
|
||||
return
|
||||
}
|
||||
}
|
||||
let silent = match msg.get("SILENT") {
|
||||
Some(v) => v.to_lower() == "true"
|
||||
None => false
|
||||
}
|
||||
let target_sess = match self.find_session_by_pub(dest_b64) {
|
||||
Some(s) => s
|
||||
None => {
|
||||
if !silent {
|
||||
let _ = send_sam_line(
|
||||
client.sock,
|
||||
"STREAM STATUS RESULT=CANT_REACH_PEER",
|
||||
)
|
||||
}
|
||||
client.closed = true
|
||||
client.sock.close()
|
||||
return
|
||||
}
|
||||
}
|
||||
// Find a waiting STREAM ACCEPT client for target_sess.id
|
||||
let mut acceptor_idx = -1
|
||||
for i = 0; i < self.sam_clients.length(); i = i + 1 {
|
||||
let c = self.sam_clients[i]
|
||||
if !c.closed && c.mode == 1 && c.accept_session_id == target_sess.id {
|
||||
acceptor_idx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if acceptor_idx < 0 {
|
||||
if !silent {
|
||||
let _ = send_sam_line(
|
||||
client.sock,
|
||||
"STREAM STATUS RESULT=CANT_REACH_PEER",
|
||||
)
|
||||
}
|
||||
client.closed = true
|
||||
client.sock.close()
|
||||
return
|
||||
}
|
||||
let acceptor = self.sam_clients[acceptor_idx]
|
||||
if !silent {
|
||||
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=OK")
|
||||
}
|
||||
if !acceptor.accept_silent {
|
||||
let _ = send_sam_line(acceptor.sock, caller_sess.pub_b64)
|
||||
}
|
||||
// Promote both sockets into a bidirectional raw stream bridge
|
||||
client.mode = 2
|
||||
acceptor.mode = 2
|
||||
self.bridges.push({
|
||||
a: client.sock,
|
||||
b: acceptor.sock,
|
||||
a_eof: false,
|
||||
b_eof: false,
|
||||
})
|
||||
}
|
||||
_ => {
|
||||
let _ = send_sam_line(
|
||||
client.sock,
|
||||
"HELLO REPLY RESULT=I2P_ERROR MESSAGE=unsupported_command",
|
||||
DatabaseLookup(
|
||||
key~,
|
||||
from~,
|
||||
flags~,
|
||||
reply_tunnel_id~,
|
||||
excluded_peers~,
|
||||
reply_key~,
|
||||
reply_tags~
|
||||
) =>
|
||||
self.handle_database_lookup_msg(
|
||||
from_peer, key, from, flags, reply_tunnel_id, excluded_peers, reply_key,
|
||||
reply_tags, now_sec,
|
||||
)
|
||||
}
|
||||
DatabaseSearchReply(key~, peer_hashes~, from~) =>
|
||||
self.handle_database_search_reply_msg(key, peer_hashes, from)
|
||||
ShortTunnelBuild(records~) =>
|
||||
self.handle_short_tunnel_build(hdr.msg_id, records, now_sec)
|
||||
ShortTunnelBuildReply(records~) =>
|
||||
self.handle_short_tunnel_build_reply(hdr.msg_id, records)
|
||||
TunnelData(tunnel_id~, data~) => self.handle_tunnel_data(tunnel_id, data)
|
||||
TunnelGateway(tunnel_id~, data~) =>
|
||||
self.handle_tunnel_gateway(tunnel_id, data, now_sec)
|
||||
Garlic(data~) =>
|
||||
if !self.try_handle_lookup_garlic_reply(data, now_sec) {
|
||||
self.handle_incoming_garlic(data, now_sec)
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::push_sam_client(self : Router, sock : @ntcp2_net.TcpSocket) -> Unit {
|
||||
self.sam_clients.push({
|
||||
sock,
|
||||
recv_buf: [],
|
||||
session_id: None,
|
||||
mode: 0,
|
||||
accept_session_id: "",
|
||||
accept_silent: false,
|
||||
closed: false,
|
||||
})
|
||||
}
|
||||
|
||||
///|
|
||||
/// Runs one non-blocking event-loop tick (accepting SAMv3 & NTCP2 connections,
|
||||
/// processing SAMv3 commands, and pumping bridged stream relays).
|
||||
/// stepping handshakes & peer sessions, servicing NetDB/tunnel/Garlic/Streaming,
|
||||
/// and pumping SAMv3 stream relays). Sleeps up to `poll_ms` only when idle.
|
||||
pub fn Router::step(self : Router, poll_ms~ : Int32 = 10) -> Unit {
|
||||
// 1. Accept any pending SAMv3 TCP connection
|
||||
match (self.sam_listener.accept(timeout_ms=poll_ms) catch { _ => None }) {
|
||||
Some(sock) =>
|
||||
self.sam_clients.push({
|
||||
sock,
|
||||
session_id: None,
|
||||
mode: 0,
|
||||
accept_session_id: "",
|
||||
accept_silent: false,
|
||||
closed: false,
|
||||
})
|
||||
None => ()
|
||||
}
|
||||
|
||||
// 2. Accept any pending incoming NTCP2 TCP connection (non-blocking)
|
||||
match (self.ntcp2_listener.accept(timeout_ms=0) catch { _ => None }) {
|
||||
Some(sock) => {
|
||||
let res = try {
|
||||
let conn = @ntcp2_net.accept_ntcp2(
|
||||
sock,
|
||||
self.static_key,
|
||||
self.router_hash().as_bytes(),
|
||||
self.ntcp2_iv,
|
||||
timeout_ms=2000,
|
||||
)
|
||||
match conn.remote_router_info {
|
||||
Some(peer_ri) => {
|
||||
let _ = self.netdb.store_router_info(peer_ri) catch { _ => false }
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
conn.close()
|
||||
true
|
||||
} catch {
|
||||
_ => {
|
||||
sock.close()
|
||||
false
|
||||
}
|
||||
}
|
||||
let _ = res
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
|
||||
// 3. Process readable SAMv3 command sockets
|
||||
for i = 0; i < self.sam_clients.length(); i = i + 1 {
|
||||
let c = self.sam_clients[i]
|
||||
if c.closed || c.mode != 0 {
|
||||
continue
|
||||
}
|
||||
let ready = c.sock.poll_readable(0) catch { _ => false }
|
||||
if !ready {
|
||||
continue
|
||||
}
|
||||
match (c.sock.read_line() catch { _ => None }) {
|
||||
Some(line) => if line.length() > 0 { self.handle_sam_command(i, line) }
|
||||
None => {
|
||||
c.closed = true
|
||||
c.sock.close()
|
||||
let mut did_work = false
|
||||
for _i = 0; _i < 8; _i = _i + 1 {
|
||||
match (self.sam_listener.accept(timeout_ms=0) catch { _ => None }) {
|
||||
Some(sock) => {
|
||||
self.push_sam_client(sock)
|
||||
did_work = true
|
||||
}
|
||||
None => break
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Pump bidirectional raw byte bridges for active STREAM connections
|
||||
let mut bi = 0
|
||||
while bi < self.bridges.length() {
|
||||
let br = self.bridges[bi]
|
||||
if !br.a_eof {
|
||||
let r = br.a.poll_readable(0) catch { _ => false }
|
||||
if r {
|
||||
let data = br.a.read_some(4096) catch { _ => b"" }
|
||||
if data.length() == 0 {
|
||||
br.a_eof = true
|
||||
br.b.shutdown_write()
|
||||
} else {
|
||||
br.b.write_all(data) catch {
|
||||
_ => br.b_eof = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !br.b_eof {
|
||||
let r = br.b.poll_readable(0) catch { _ => false }
|
||||
if r {
|
||||
let data = br.b.read_some(4096) catch { _ => b"" }
|
||||
if data.length() == 0 {
|
||||
br.b_eof = true
|
||||
br.a.shutdown_write()
|
||||
} else {
|
||||
br.a.write_all(data) catch {
|
||||
_ => br.a_eof = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if br.a_eof && br.b_eof {
|
||||
br.a.close()
|
||||
br.b.close()
|
||||
let _ = self.bridges.remove(bi)
|
||||
} else {
|
||||
bi += 1
|
||||
if self.step_ntcp2_peers() {
|
||||
did_work = true
|
||||
}
|
||||
if self.step_sam_clients() {
|
||||
did_work = true
|
||||
}
|
||||
self.poll_netdb_lookups()
|
||||
self.poll_tunnel_builds()
|
||||
if self.step_bridges() {
|
||||
did_work = true
|
||||
}
|
||||
if self.step_remote_bridges() {
|
||||
did_work = true
|
||||
}
|
||||
|
||||
if !did_work && poll_ms > 0 {
|
||||
match (self.sam_listener.accept(timeout_ms=poll_ms) catch { _ => None }) {
|
||||
Some(sock) => self.push_sam_client(sock)
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user