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
@@ -3,9 +3,13 @@ import {
|
||||
"experiments/moon_i2p/crypto",
|
||||
"experiments/moon_i2p/common",
|
||||
"experiments/moon_i2p/noise",
|
||||
"experiments/moon_i2p/i2np",
|
||||
"experiments/moon_i2p/ntcp2",
|
||||
"experiments/moon_i2p/ntcp2_net",
|
||||
"experiments/moon_i2p/netdb",
|
||||
"experiments/moon_i2p/tunnel",
|
||||
"experiments/moon_i2p/ratchet",
|
||||
"experiments/moon_i2p/streaming",
|
||||
"experiments/moon_i2p/sam",
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,504 @@
|
||||
///|
|
||||
/// Active Floodfill NetDB protocol handlers (`DatabaseStore`, ECIES `DatabaseLookup`,
|
||||
/// and iterative `DatabaseSearchReply` Kademlia lookup crawl).
|
||||
|
||||
///|
|
||||
priv struct PendingNetDbLookup {
|
||||
target_hash : @common.Hash
|
||||
reply_key : Bytes
|
||||
reply_tag : Bytes
|
||||
queried_peers : Array[@common.Hash]
|
||||
candidate_peers : Array[@common.Hash]
|
||||
started_ms : UInt64
|
||||
kind : Int32 // 0 = NAMING LOOKUP (.b32), 1 = STREAM CONNECT awaiting LeaseSet2
|
||||
client_idx : Int32
|
||||
req_name : String
|
||||
session_id : String
|
||||
silent : Bool
|
||||
}
|
||||
|
||||
///|
|
||||
fn is_hash_in(h : @common.Hash, list : Array[@common.Hash]) -> Bool {
|
||||
for item in list {
|
||||
if item == h {
|
||||
return true
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::build_session_leaseset2(
|
||||
self : Router,
|
||||
sess : SamSession,
|
||||
now_sec : UInt32,
|
||||
) -> @common.LeaseSet2? {
|
||||
let seed = match sess.ed_seed {
|
||||
Some(s) => s
|
||||
None => return None
|
||||
}
|
||||
let leases : Array[@common.Lease2] = []
|
||||
let max_leases = 3
|
||||
for t in self.tunnels.inbound {
|
||||
if t.expires_sec > now_sec &&
|
||||
t.hops.length() > 0 &&
|
||||
leases.length() < max_leases {
|
||||
leases.push({
|
||||
tunnel_gw: t.hops[0].router_hash,
|
||||
tunnel_id: t.hops[0].receive_tunnel_id,
|
||||
end_date_sec: t.expires_sec,
|
||||
})
|
||||
}
|
||||
}
|
||||
if leases.length() == 0 {
|
||||
leases.push({
|
||||
tunnel_gw: self.router_hash(),
|
||||
tunnel_id: sess.virtual_tid,
|
||||
end_date_sec: now_sec + 600U,
|
||||
})
|
||||
}
|
||||
let ls2 : @common.LeaseSet2 = {
|
||||
destination: sess.dest,
|
||||
published_sec: now_sec,
|
||||
expires_offset: 600U,
|
||||
flags: 0U,
|
||||
offline_sig: None,
|
||||
options: @common.Mapping::new(),
|
||||
encryption_keys: [
|
||||
{ key_type: X25519, key_data: sess.dest.inner.crypto_public_key(), },
|
||||
],
|
||||
leases,
|
||||
signature: b"",
|
||||
}
|
||||
let signed = ls2.sign_ed25519(seed) catch { _ => return None }
|
||||
let _ = self.netdb.store_lease_set2(signed, now_sec) catch { _ => false }
|
||||
Some(signed)
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::publish_session_leaseset2(self : Router, sess : SamSession) -> Unit {
|
||||
let now_sec = @ntcp2_net.unix_time_sec()
|
||||
let ls2 = match self.build_session_leaseset2(sess, now_sec) {
|
||||
Some(l) => l
|
||||
None => return
|
||||
}
|
||||
let raw = ls2.to_bytes() catch { _ => return }
|
||||
let utc_date = @netdb.format_utc_date(now_sec.to_uint64())
|
||||
let floodfills = self.netdb.closest_peers(
|
||||
sess.hash,
|
||||
utc_date,
|
||||
3,
|
||||
floodfills_only=true,
|
||||
excluded=[self.router_hash()],
|
||||
)
|
||||
let payload : @i2np.I2npPayload = DatabaseStore(
|
||||
key=sess.hash,
|
||||
store_type=b'\x03',
|
||||
reply_token=0U,
|
||||
reply_tunnel_id=0U,
|
||||
reply_gateway=None,
|
||||
data=raw,
|
||||
)
|
||||
for ff in floodfills {
|
||||
let _ = self.send_i2np_to_peer(ff.identity.hash(), payload)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::republish_all_sessions(self : Router) -> Unit {
|
||||
for sess in self.sessions {
|
||||
self.publish_session_leaseset2(sess)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::select_lookup_peers(
|
||||
self : Router,
|
||||
target_hash : @common.Hash,
|
||||
excluded : Array[@common.Hash],
|
||||
now_sec : UInt32,
|
||||
limit : Int32,
|
||||
) -> Array[@common.Hash] {
|
||||
let utc_date = @netdb.format_utc_date(now_sec.to_uint64())
|
||||
let excl : Array[@common.Hash] = [self.router_hash()]
|
||||
for e in excluded {
|
||||
excl.push(e)
|
||||
}
|
||||
let ffs = self.netdb.closest_peers(
|
||||
target_hash,
|
||||
utc_date,
|
||||
limit,
|
||||
floodfills_only=true,
|
||||
excluded=excl,
|
||||
)
|
||||
let peers = if ffs.length() > 0 {
|
||||
ffs
|
||||
} else {
|
||||
self.netdb.closest_peers(
|
||||
target_hash,
|
||||
utc_date,
|
||||
limit,
|
||||
floodfills_only=false,
|
||||
excluded=excl,
|
||||
)
|
||||
}
|
||||
let out : Array[@common.Hash] = []
|
||||
for p in peers {
|
||||
out.push(p.identity.hash())
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::send_lookup_query(
|
||||
self : Router,
|
||||
lk : PendingNetDbLookup,
|
||||
peer_hash : @common.Hash,
|
||||
) -> Unit {
|
||||
if !is_hash_in(peer_hash, lk.queried_peers) {
|
||||
lk.queried_peers.push(peer_hash)
|
||||
}
|
||||
// Proposal 154 ECIES encrypted reply (0x10) + LeaseSet lookup type (0x04)
|
||||
let lookup : @i2np.I2npPayload = DatabaseLookup(
|
||||
key=lk.target_hash,
|
||||
from=self.router_hash(),
|
||||
flags=b'\x14',
|
||||
reply_tunnel_id=None,
|
||||
excluded_peers=lk.queried_peers,
|
||||
reply_key=Some(lk.reply_key),
|
||||
reply_tags=[lk.reply_tag],
|
||||
)
|
||||
let _ = self.send_i2np_to_peer(peer_hash, lookup)
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::start_netdb_lookup(
|
||||
self : Router,
|
||||
target_hash : @common.Hash,
|
||||
kind : Int32,
|
||||
client_idx : Int32,
|
||||
req_name : String,
|
||||
session_id : String,
|
||||
silent : Bool,
|
||||
) -> Bool {
|
||||
let now_sec = @ntcp2_net.unix_time_sec()
|
||||
let initial_peers = self.select_lookup_peers(target_hash, [], now_sec, 3)
|
||||
if initial_peers.length() == 0 {
|
||||
return false
|
||||
}
|
||||
let reply_key = next_rand_32()
|
||||
let tag_rand = @ntcp2_net.random_bytes(8) catch {
|
||||
_ => Bytes::make(8, b'\x77')
|
||||
}
|
||||
let lk : PendingNetDbLookup = {
|
||||
target_hash,
|
||||
reply_key,
|
||||
reply_tag: tag_rand,
|
||||
queried_peers: [],
|
||||
candidate_peers: [],
|
||||
started_ms: @ntcp2_net.unix_time_ms(),
|
||||
kind,
|
||||
client_idx,
|
||||
req_name,
|
||||
session_id,
|
||||
silent,
|
||||
}
|
||||
self.pending_lookups.push(lk)
|
||||
self.send_lookup_query(lk, initial_peers[0])
|
||||
for i = 1; i < initial_peers.length(); i = i + 1 {
|
||||
lk.candidate_peers.push(initial_peers[i])
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::handle_database_store_msg(
|
||||
self : Router,
|
||||
from_peer : @common.Hash?,
|
||||
key : @common.Hash,
|
||||
store_type : Byte,
|
||||
reply_token : UInt32,
|
||||
reply_tunnel_id : UInt32,
|
||||
reply_gateway : @common.Hash?,
|
||||
data : Bytes,
|
||||
now_sec : UInt32,
|
||||
) -> Unit {
|
||||
let stored = self.netdb.handle_database_store(store_type, key, data, now_sec) catch {
|
||||
_ => false
|
||||
}
|
||||
if stored && (store_type.to_int() & 0x0F) == 3 {
|
||||
self.complete_lookups_for_hash(key, now_sec)
|
||||
}
|
||||
if reply_token != 0U {
|
||||
let status : @i2np.I2npPayload = DeliveryStatus(
|
||||
msg_id=reply_token,
|
||||
timestamp_ms=@ntcp2_net.unix_time_ms(),
|
||||
)
|
||||
match reply_gateway {
|
||||
Some(gw) =>
|
||||
if reply_tunnel_id != 0U {
|
||||
let std = @i2np.encode_standard_message(
|
||||
self.alloc_msg_id(),
|
||||
@ntcp2_net.unix_time_ms() + 60000UL,
|
||||
status,
|
||||
) catch {
|
||||
_ => return
|
||||
}
|
||||
let _ = self.send_i2np_to_peer(
|
||||
gw,
|
||||
TunnelGateway(tunnel_id=reply_tunnel_id, data=std),
|
||||
)
|
||||
} else {
|
||||
let _ = self.send_i2np_to_peer(gw, status)
|
||||
}
|
||||
None =>
|
||||
match from_peer {
|
||||
Some(ph) => {
|
||||
let _ = self.send_i2np_to_peer(ph, status)
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::handle_database_lookup_msg(
|
||||
self : Router,
|
||||
from_peer : @common.Hash?,
|
||||
key : @common.Hash,
|
||||
from : @common.Hash,
|
||||
flags : Byte,
|
||||
reply_tunnel_id : UInt32?,
|
||||
excluded_peers : Array[@common.Hash],
|
||||
reply_key : Bytes?,
|
||||
reply_tags : Array[Bytes],
|
||||
now_sec : UInt32,
|
||||
) -> Unit {
|
||||
let reply = self.netdb.handle_database_lookup(
|
||||
self.router_hash(),
|
||||
key,
|
||||
flags,
|
||||
excluded_peers,
|
||||
now_sec,
|
||||
) catch {
|
||||
_ => return
|
||||
}
|
||||
let enc_ecies = (flags.to_int() & 0x10) != 0
|
||||
let wire_reply : @i2np.I2npPayload = if enc_ecies &&
|
||||
reply is DatabaseStore(..) {
|
||||
match reply_key {
|
||||
Some(rk) if reply_tags.length() > 0 => {
|
||||
let exp_sec = now_sec + 60U
|
||||
let clove = @ratchet.garlic_clove_block(
|
||||
Local,
|
||||
self.alloc_msg_id(),
|
||||
exp_sec,
|
||||
reply,
|
||||
) catch {
|
||||
_ => return
|
||||
}
|
||||
let enc = @ratchet.encrypt_ecies_lookup_reply(rk, reply_tags[0], [clove]) catch {
|
||||
_ => return
|
||||
}
|
||||
Garlic(data=enc)
|
||||
}
|
||||
_ => reply
|
||||
}
|
||||
} else {
|
||||
reply
|
||||
}
|
||||
if (flags.to_int() & 0x01) != 0 {
|
||||
match reply_tunnel_id {
|
||||
Some(tid) => {
|
||||
let std = @i2np.encode_standard_message(
|
||||
self.alloc_msg_id(),
|
||||
@ntcp2_net.unix_time_ms() + 60000UL,
|
||||
wire_reply,
|
||||
) catch {
|
||||
_ => return
|
||||
}
|
||||
let _ = self.send_i2np_to_peer(
|
||||
from,
|
||||
TunnelGateway(tunnel_id=tid, data=std),
|
||||
)
|
||||
return
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
let dest_peer = match self.netdb.get_router_info(from) {
|
||||
Some(_) => from
|
||||
None =>
|
||||
match from_peer {
|
||||
Some(p) => p
|
||||
None => from
|
||||
}
|
||||
}
|
||||
let _ = self.send_i2np_to_peer(dest_peer, wire_reply)
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::handle_database_search_reply_msg(
|
||||
self : Router,
|
||||
key : @common.Hash,
|
||||
peer_hashes : Array[@common.Hash],
|
||||
from : @common.Hash,
|
||||
) -> Unit {
|
||||
for lk in self.pending_lookups {
|
||||
if lk.target_hash == key {
|
||||
if !is_hash_in(from, lk.queried_peers) {
|
||||
lk.queried_peers.push(from)
|
||||
}
|
||||
for ph in peer_hashes {
|
||||
if ph != self.router_hash() &&
|
||||
!is_hash_in(ph, lk.queried_peers) &&
|
||||
!is_hash_in(ph, lk.candidate_peers) &&
|
||||
self.netdb.get_router_info(ph) is Some(_) {
|
||||
lk.candidate_peers.push(ph)
|
||||
}
|
||||
}
|
||||
while lk.candidate_peers.length() > 0 && lk.queried_peers.length() < 8 {
|
||||
let next_peer = lk.candidate_peers.remove(0)
|
||||
if !is_hash_in(next_peer, lk.queried_peers) {
|
||||
self.send_lookup_query(lk, next_peer)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::try_handle_lookup_garlic_reply(
|
||||
self : Router,
|
||||
garlic_data : Bytes,
|
||||
now_sec : UInt32,
|
||||
) -> Bool {
|
||||
if garlic_data.length() < 24 {
|
||||
return false
|
||||
}
|
||||
let wire_tag = garlic_data[:8].to_owned()
|
||||
let mut matched_idx = -1
|
||||
for i = 0; i < self.pending_lookups.length(); i = i + 1 {
|
||||
if @crypto.ct_eq(wire_tag, self.pending_lookups[i].reply_tag) {
|
||||
matched_idx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if matched_idx < 0 {
|
||||
return false
|
||||
}
|
||||
let lk = self.pending_lookups[matched_idx]
|
||||
let blocks = @ratchet.decrypt_ecies_lookup_reply(
|
||||
lk.reply_key,
|
||||
lk.reply_tag,
|
||||
garlic_data,
|
||||
) catch {
|
||||
_ => return false
|
||||
}
|
||||
for blk in blocks {
|
||||
match blk {
|
||||
GarlicClove(i2np_short~, ..) => {
|
||||
let decoded = Some(@ratchet.decode_garlic_clove_i2np(i2np_short)) catch {
|
||||
_ => None
|
||||
}
|
||||
match decoded {
|
||||
Some((hdr, inner)) => self.handle_i2np_message(None, hdr, inner)
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
let _ = now_sec
|
||||
true
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::complete_lookups_for_hash(
|
||||
self : Router,
|
||||
key : @common.Hash,
|
||||
now_sec : UInt32,
|
||||
) -> Unit {
|
||||
let ls2 = match self.netdb.get_lease_set2(key, now_sec) {
|
||||
Some(l) => l
|
||||
None => return
|
||||
}
|
||||
let mut i = 0
|
||||
while i < self.pending_lookups.length() {
|
||||
let lk = self.pending_lookups[i]
|
||||
if lk.target_hash == key {
|
||||
let _ = self.pending_lookups.remove(i)
|
||||
if lk.client_idx < self.sam_clients.length() {
|
||||
let c = self.sam_clients[lk.client_idx]
|
||||
if !c.closed {
|
||||
if lk.kind == 0 {
|
||||
let val = ls2.destination.to_base64()
|
||||
let _ = send_sam_line(
|
||||
c.sock,
|
||||
"NAMING REPLY RESULT=OK NAME=\{lk.req_name} VALUE=\{val}",
|
||||
)
|
||||
} else {
|
||||
self.finish_remote_stream_connect(lk, ls2)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::poll_netdb_lookups(self : Router) -> Unit {
|
||||
let now_ms = @ntcp2_net.unix_time_ms()
|
||||
let now_sec = (now_ms / 1000UL).to_uint()
|
||||
let mut i = 0
|
||||
while i < self.pending_lookups.length() {
|
||||
let lk = self.pending_lookups[i]
|
||||
match self.netdb.get_lease_set2(lk.target_hash, now_sec) {
|
||||
Some(ls2) => {
|
||||
let _ = self.pending_lookups.remove(i)
|
||||
if lk.client_idx < self.sam_clients.length() &&
|
||||
!self.sam_clients[lk.client_idx].closed {
|
||||
if lk.kind == 0 {
|
||||
let _ = send_sam_line(
|
||||
self.sam_clients[lk.client_idx].sock,
|
||||
"NAMING REPLY RESULT=OK NAME=\{lk.req_name} VALUE=\{ls2.destination.to_base64()}",
|
||||
)
|
||||
} else {
|
||||
self.finish_remote_stream_connect(lk, ls2)
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
if now_ms > lk.started_ms + 8000UL {
|
||||
let _ = self.pending_lookups.remove(i)
|
||||
if lk.client_idx < self.sam_clients.length() {
|
||||
let c = self.sam_clients[lk.client_idx]
|
||||
if !c.closed {
|
||||
if lk.kind == 0 {
|
||||
let _ = send_sam_line(
|
||||
c.sock,
|
||||
"NAMING REPLY RESULT=KEY_NOT_FOUND NAME=\{lk.req_name}",
|
||||
)
|
||||
} else {
|
||||
if !lk.silent {
|
||||
let _ = send_sam_line(
|
||||
c.sock,
|
||||
"STREAM STATUS RESULT=CANT_REACH_PEER",
|
||||
)
|
||||
}
|
||||
c.closed = true
|
||||
c.sock.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
///|
|
||||
/// Non-blocking NTCP2 peer pool, outbound dialer, and Data Phase frame dispatcher.
|
||||
|
||||
///|
|
||||
priv struct PendingPeerDial {
|
||||
peer_hash : @common.Hash
|
||||
dial : @ntcp2_net.PendingNtcp2Dial
|
||||
}
|
||||
|
||||
///|
|
||||
priv struct PeerSession {
|
||||
hash : @common.Hash
|
||||
conn : @ntcp2_net.Ntcp2Conn
|
||||
mut last_active_ms : UInt64
|
||||
}
|
||||
|
||||
///|
|
||||
priv struct PendingPeerSend {
|
||||
target_hash : @common.Hash
|
||||
msg_id : UInt32
|
||||
expiration_sec : UInt32
|
||||
payload : @i2np.I2npPayload
|
||||
queued_ms : UInt64
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Router::peer_count(self : Router) -> Int32 {
|
||||
self.peers.length()
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::find_peer_hash_by_static(
|
||||
self : Router,
|
||||
static_pub : Bytes,
|
||||
) -> @common.Hash? {
|
||||
for entry in self.netdb.routers {
|
||||
for addr in entry.1.addresses {
|
||||
if addr.transport_style == "NTCP2" {
|
||||
match addr.options.get("s") {
|
||||
Some(s_b64) => {
|
||||
let s_bytes = @encoding.base64_decode(s_b64) catch { _ => b"" }
|
||||
if s_bytes.length() == 32 && @crypto.ct_eq(s_bytes, static_pub) {
|
||||
return Some(entry.0)
|
||||
}
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::has_pending_dial(self : Router, target_hash : @common.Hash) -> Bool {
|
||||
for pd in self.pending_dials {
|
||||
if pd.peer_hash == target_hash {
|
||||
return true
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::ensure_peer_dial(self : Router, target_hash : @common.Hash) -> Unit {
|
||||
if target_hash == self.router_hash() || self.has_pending_dial(target_hash) {
|
||||
return
|
||||
}
|
||||
let ri = match self.netdb.get_router_info(target_hash) {
|
||||
Some(r) => r
|
||||
None => return
|
||||
}
|
||||
let peer_info = @ntcp2_net.extract_ntcp2_peer(ri) catch { _ => return }
|
||||
let dial = @ntcp2_net.PendingNtcp2Dial::start(
|
||||
peer_info,
|
||||
self.static_key,
|
||||
self.router_info,
|
||||
check_clock_skew=self.check_clock_skew,
|
||||
remote_ri=Some(ri),
|
||||
) catch {
|
||||
_ => return
|
||||
}
|
||||
self.pending_dials.push({ peer_hash: target_hash, dial, })
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::send_i2np_to_peer(
|
||||
self : Router,
|
||||
target_hash : @common.Hash,
|
||||
payload : @i2np.I2npPayload,
|
||||
msg_id_override~ : UInt32? = None,
|
||||
) -> UInt32 {
|
||||
let mid = match msg_id_override {
|
||||
Some(id) => id
|
||||
None => self.alloc_msg_id()
|
||||
}
|
||||
let now_ms = @ntcp2_net.unix_time_ms()
|
||||
let exp_sec = (now_ms / 1000UL).to_uint() + 60U
|
||||
if target_hash == self.router_hash() {
|
||||
self.pending_sends.push({
|
||||
target_hash,
|
||||
msg_id: mid,
|
||||
expiration_sec: exp_sec,
|
||||
payload,
|
||||
queued_ms: now_ms,
|
||||
})
|
||||
return mid
|
||||
}
|
||||
// Prefer most recently active live session for target_hash
|
||||
let mut idx = self.peers.length() - 1
|
||||
while idx >= 0 {
|
||||
if self.peers[idx].hash == target_hash {
|
||||
let ok = try {
|
||||
self.peers[idx].conn.send_i2np(mid, exp_sec, payload)
|
||||
true
|
||||
} catch {
|
||||
_ => false
|
||||
}
|
||||
if ok {
|
||||
self.peers[idx].last_active_ms = now_ms
|
||||
return mid
|
||||
}
|
||||
self.peers[idx].conn.close()
|
||||
let _ = self.peers.remove(idx)
|
||||
}
|
||||
idx -= 1
|
||||
}
|
||||
self.pending_sends.push({
|
||||
target_hash,
|
||||
msg_id: mid,
|
||||
expiration_sec: exp_sec,
|
||||
payload,
|
||||
queued_ms: now_ms,
|
||||
})
|
||||
self.ensure_peer_dial(target_hash)
|
||||
mid
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::send_routed_i2np(
|
||||
self : Router,
|
||||
target_gw : @common.Hash,
|
||||
target_tid : UInt32?,
|
||||
payload : @i2np.I2npPayload,
|
||||
) -> Unit {
|
||||
if self.tunnels.outbound.length() > 0 {
|
||||
let out_t = self.tunnels.outbound[0]
|
||||
let target : @tunnel.DeliveryTarget = match target_tid {
|
||||
Some(tid) => Tunnel(tunnel_id=tid, gateway=target_gw)
|
||||
None => Router(router_hash=target_gw)
|
||||
}
|
||||
let routed = try {
|
||||
self.send_through_tunnel(out_t.id, target, payload)
|
||||
true
|
||||
} catch {
|
||||
_ => false
|
||||
}
|
||||
if routed {
|
||||
return
|
||||
}
|
||||
}
|
||||
match target_tid {
|
||||
Some(tid) => {
|
||||
let mid = self.alloc_msg_id()
|
||||
let exp_ms = @ntcp2_net.unix_time_ms() + 60000UL
|
||||
let std_bytes = @i2np.encode_standard_message(mid, exp_ms, payload) catch {
|
||||
_ => return
|
||||
}
|
||||
let _ = self.send_i2np_to_peer(
|
||||
target_gw,
|
||||
TunnelGateway(tunnel_id=tid, data=std_bytes),
|
||||
)
|
||||
}
|
||||
None => {
|
||||
let _ = self.send_i2np_to_peer(target_gw, payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::flush_pending_sends_for(
|
||||
self : Router,
|
||||
target_hash : @common.Hash,
|
||||
peer : PeerSession,
|
||||
) -> Bool {
|
||||
let mut i = 0
|
||||
while i < self.pending_sends.length() {
|
||||
let ps = self.pending_sends[i]
|
||||
if ps.target_hash == target_hash {
|
||||
let ok = try {
|
||||
peer.conn.send_i2np(ps.msg_id, ps.expiration_sec, ps.payload)
|
||||
true
|
||||
} catch {
|
||||
_ => false
|
||||
}
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
peer.last_active_ms = @ntcp2_net.unix_time_ms()
|
||||
let _ = self.pending_sends.remove(i)
|
||||
} else {
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::handle_peer_blocks(
|
||||
self : Router,
|
||||
peer_hash : @common.Hash,
|
||||
blocks : Array[@ntcp2.Ntcp2Block],
|
||||
) -> Bool {
|
||||
let mut should_close = false
|
||||
for blk in blocks {
|
||||
match blk {
|
||||
I2np(short_bytes) => {
|
||||
let decoded = Some(
|
||||
@i2np.decode_short_message(@encoding.Reader::new(short_bytes)),
|
||||
) catch {
|
||||
_ => None
|
||||
}
|
||||
match decoded {
|
||||
Some((hdr, payload)) =>
|
||||
self.handle_i2np_message(Some(peer_hash), hdr, payload)
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
RouterInfo(router_info~, ..) => {
|
||||
let ri = @common.RouterInfo::decode(@encoding.Reader::new(router_info)) catch {
|
||||
_ => continue
|
||||
}
|
||||
let _ = self.netdb.store_router_info(ri) catch { _ => false }
|
||||
}
|
||||
Termination(..) => should_close = true
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
should_close
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::step_ntcp2_peers(self : Router) -> Bool {
|
||||
let now_ms = @ntcp2_net.unix_time_ms()
|
||||
let mut did_work = false
|
||||
|
||||
// 1. Accept any newly arrived TCP sockets into non-blocking responder handshakes
|
||||
for _a = 0; _a < 8; _a = _a + 1 {
|
||||
match (self.ntcp2_listener.accept_nonblocking() catch { _ => None }) {
|
||||
Some(sock) => {
|
||||
let pa_opt = Some(
|
||||
@ntcp2_net.PendingNtcp2Accept::start(
|
||||
sock,
|
||||
self.static_key,
|
||||
self.router_hash().as_bytes(),
|
||||
self.ntcp2_iv,
|
||||
replay_cache=Some(self.replay_cache),
|
||||
check_clock_skew=self.check_clock_skew,
|
||||
),
|
||||
) catch {
|
||||
_ => None
|
||||
}
|
||||
match pa_opt {
|
||||
Some(pa) => {
|
||||
self.pending_accepts.push(pa)
|
||||
did_work = true
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
None => break
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Step pending inbound NTCP2 handshakes
|
||||
let mut ai = 0
|
||||
while ai < self.pending_accepts.length() {
|
||||
let pa = self.pending_accepts[ai]
|
||||
if now_ms > pa.started_at_ms() + 10000UL {
|
||||
pa.close()
|
||||
let _ = self.pending_accepts.remove(ai)
|
||||
did_work = true
|
||||
continue
|
||||
}
|
||||
let stepped = (pa.step(), false) catch { _ => (None, true) }
|
||||
if stepped.1 {
|
||||
pa.close()
|
||||
let _ = self.pending_accepts.remove(ai)
|
||||
did_work = true
|
||||
continue
|
||||
}
|
||||
match stepped.0 {
|
||||
Some(conn) => {
|
||||
did_work = true
|
||||
let _ = self.pending_accepts.remove(ai)
|
||||
let mut peer_hash : @common.Hash? = None
|
||||
match conn.remote_router_info {
|
||||
Some(ri) => {
|
||||
let _ = self.netdb.store_router_info(ri) catch { _ => false }
|
||||
peer_hash = Some(ri.identity.hash())
|
||||
}
|
||||
None =>
|
||||
peer_hash = self.find_peer_hash_by_static(
|
||||
conn.session.remote_static(),
|
||||
)
|
||||
}
|
||||
match peer_hash {
|
||||
Some(ph) => {
|
||||
let ps : PeerSession = { hash: ph, conn, last_active_ms: now_ms, }
|
||||
self.peers.push(ps)
|
||||
let _ = self.flush_pending_sends_for(ph, ps)
|
||||
}
|
||||
None => conn.close()
|
||||
}
|
||||
}
|
||||
None => ai += 1
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Step pending outbound NTCP2 dials
|
||||
let mut di = 0
|
||||
while di < self.pending_dials.length() {
|
||||
let pd = self.pending_dials[di]
|
||||
if now_ms > pd.dial.started_at_ms() + 10000UL {
|
||||
pd.dial.close()
|
||||
let _ = self.pending_dials.remove(di)
|
||||
did_work = true
|
||||
continue
|
||||
}
|
||||
let stepped = (pd.dial.step(), false) catch { _ => (None, true) }
|
||||
if stepped.1 {
|
||||
pd.dial.close()
|
||||
let _ = self.pending_dials.remove(di)
|
||||
did_work = true
|
||||
continue
|
||||
}
|
||||
match stepped.0 {
|
||||
Some(conn) => {
|
||||
did_work = true
|
||||
let _ = self.pending_dials.remove(di)
|
||||
let ps : PeerSession = {
|
||||
hash: pd.peer_hash,
|
||||
conn,
|
||||
last_active_ms: now_ms,
|
||||
}
|
||||
self.peers.push(ps)
|
||||
let _ = self.flush_pending_sends_for(pd.peer_hash, ps)
|
||||
}
|
||||
None => di += 1
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Deliver any local loopback sends or retry/expire orphaned pending sends
|
||||
let local_msgs : Array[PendingPeerSend] = []
|
||||
let mut si = 0
|
||||
while si < self.pending_sends.length() {
|
||||
let ps = self.pending_sends[si]
|
||||
if ps.target_hash == self.router_hash() {
|
||||
local_msgs.push(ps)
|
||||
let _ = self.pending_sends.remove(si)
|
||||
did_work = true
|
||||
} else if now_ms > ps.queued_ms + 15000UL {
|
||||
let _ = self.pending_sends.remove(si)
|
||||
} else {
|
||||
si += 1
|
||||
}
|
||||
}
|
||||
for ps in local_msgs {
|
||||
self.handle_i2np_message(
|
||||
Some(self.router_hash()),
|
||||
{
|
||||
msg_type: ps.payload.msg_type(),
|
||||
msg_id: ps.msg_id,
|
||||
expiration_sec: ps.expiration_sec,
|
||||
},
|
||||
ps.payload,
|
||||
)
|
||||
}
|
||||
|
||||
// 5. Non-blocking read & dispatch on all active NTCP2 peer sessions
|
||||
let mut pi = 0
|
||||
while pi < self.peers.length() {
|
||||
let peer = self.peers[pi]
|
||||
let mut alive = true
|
||||
for _frame = 0; _frame < 32; _frame = _frame + 1 {
|
||||
let recv_opt = peer.conn.try_recv_blocks() catch {
|
||||
_ => {
|
||||
alive = false
|
||||
None
|
||||
}
|
||||
}
|
||||
match recv_opt {
|
||||
Some(blocks) => {
|
||||
did_work = true
|
||||
peer.last_active_ms = now_ms
|
||||
if self.handle_peer_blocks(peer.hash, blocks) {
|
||||
alive = false
|
||||
break
|
||||
}
|
||||
}
|
||||
None => break
|
||||
}
|
||||
}
|
||||
if !alive || now_ms > peer.last_active_ms + 120000UL {
|
||||
peer.conn.close()
|
||||
let _ = self.peers.remove(pi)
|
||||
} else {
|
||||
pi += 1
|
||||
}
|
||||
}
|
||||
did_work
|
||||
}
|
||||
+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 => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+267
-17
@@ -1,3 +1,52 @@
|
||||
///|
|
||||
fn step_routers(rs : Array[@router.Router], count : Int32) -> Unit {
|
||||
for _i = 0; _i < count; _i = _i + 1 {
|
||||
for r in rs {
|
||||
r.step(poll_ms=1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn pump_read_line(
|
||||
sock : @ntcp2_net.TcpSocket,
|
||||
rs : Array[@router.Router],
|
||||
max_ticks~ : Int32 = 1000,
|
||||
) -> String raise {
|
||||
for _i = 0; _i < max_ticks; _i = _i + 1 {
|
||||
step_routers(rs, 1)
|
||||
if sock.poll_readable(0) {
|
||||
match sock.read_line() {
|
||||
Some(l) => return l
|
||||
None => fail("unexpected EOF while waiting for SAM line")
|
||||
}
|
||||
}
|
||||
}
|
||||
fail("timed out waiting for SAM line")
|
||||
}
|
||||
|
||||
///|
|
||||
fn pump_read_until_eof(
|
||||
sock : @ntcp2_net.TcpSocket,
|
||||
rs : Array[@router.Router],
|
||||
max_ticks~ : Int32 = 1500,
|
||||
) -> Bytes raise {
|
||||
let out : Array[Byte] = []
|
||||
for _i = 0; _i < max_ticks; _i = _i + 1 {
|
||||
step_routers(rs, 1)
|
||||
while sock.poll_readable(0) {
|
||||
let chunk = sock.read_some(4096)
|
||||
if chunk.length() == 0 {
|
||||
return Bytes::from_array(out)
|
||||
}
|
||||
for j = 0; j < chunk.length(); j = j + 1 {
|
||||
out.push(chunk[j])
|
||||
}
|
||||
}
|
||||
}
|
||||
fail("timed out waiting for EOF on stream socket")
|
||||
}
|
||||
|
||||
///|
|
||||
test "Router transient startup, self-signed RouterInfo, and embedded SAMv3 bridge" {
|
||||
let r = @router.Router::start({
|
||||
@@ -16,36 +65,237 @@ test "Router transient startup, self-signed RouterInfo, and embedded SAMv3 bridg
|
||||
r.step(poll_ms=50)
|
||||
|
||||
sock.write_all(b"HELLO VERSION MIN=3.1 MAX=3.3\n")
|
||||
r.step(poll_ms=50)
|
||||
assert_eq(sock.read_line(), Some("HELLO REPLY RESULT=OK VERSION=3.3"))
|
||||
assert_eq(pump_read_line(sock, [r]), "HELLO REPLY RESULT=OK VERSION=3.3")
|
||||
|
||||
sock.write_all(b"DEST GENERATE SIGNATURE_TYPE=7\n")
|
||||
r.step(poll_ms=50)
|
||||
let dest_line = match sock.read_line() {
|
||||
Some(l) => l
|
||||
None => fail("expected DEST REPLY")
|
||||
}
|
||||
let dest_line = pump_read_line(sock, [r])
|
||||
assert_true(dest_line.has_prefix("DEST REPLY PUB="))
|
||||
|
||||
sock.write_all(
|
||||
b"SESSION CREATE STYLE=STREAM ID=test1 DESTINATION=TRANSIENT\n",
|
||||
)
|
||||
r.step(poll_ms=50)
|
||||
let sess_line = match sock.read_line() {
|
||||
Some(l) => l
|
||||
None => fail("expected SESSION STATUS")
|
||||
}
|
||||
let sess_line = pump_read_line(sock, [r])
|
||||
assert_true(sess_line.has_prefix("SESSION STATUS RESULT=OK DESTINATION="))
|
||||
assert_eq(r.netdb.leaseset_count(), 1)
|
||||
|
||||
sock.write_all(b"NAMING LOOKUP NAME=ME\n")
|
||||
r.step(poll_ms=50)
|
||||
let lookup_line = match sock.read_line() {
|
||||
Some(l) => l
|
||||
None => fail("expected NAMING REPLY")
|
||||
}
|
||||
let lookup_line = pump_read_line(sock, [r])
|
||||
assert_true(lookup_line.has_prefix("NAMING REPLY RESULT=OK NAME=ME VALUE="))
|
||||
|
||||
sock.close()
|
||||
r.close()
|
||||
}
|
||||
|
||||
///|
|
||||
fn sam_connect_and_hello(
|
||||
port : Int32,
|
||||
rs : Array[@router.Router],
|
||||
) -> @ntcp2_net.TcpSocket raise {
|
||||
let sock = @ntcp2_net.TcpSocket::connect("127.0.0.1", port)
|
||||
sock.write_all(b"HELLO VERSION MIN=3.1 MAX=3.3\n")
|
||||
let reply = pump_read_line(sock, rs)
|
||||
assert_eq(reply, "HELLO REPLY RESULT=OK VERSION=3.3")
|
||||
sock
|
||||
}
|
||||
|
||||
///|
|
||||
fn extract_kv(line : String, key : String) -> String {
|
||||
let prefix = key + "="
|
||||
let tokens = line.split(" ").collect()
|
||||
for t in tokens {
|
||||
let ts = t.to_owned()
|
||||
if ts.has_prefix(prefix) {
|
||||
return ts[prefix.length():].to_owned()
|
||||
}
|
||||
}
|
||||
""
|
||||
}
|
||||
|
||||
///|
|
||||
test "Two live routers end-to-end: NTCP2 + ECIES NetDB + Garlic Ratchet + Ed25519 Streaming" {
|
||||
let router_b = @router.Router::start(
|
||||
{
|
||||
sam_host: "127.0.0.1",
|
||||
sam_port: 0,
|
||||
ntcp2_host: "127.0.0.1",
|
||||
ntcp2_port: 0,
|
||||
},
|
||||
floodfill=true,
|
||||
)
|
||||
defer router_b.close()
|
||||
let router_a = @router.Router::start({
|
||||
sam_host: "127.0.0.1",
|
||||
sam_port: 0,
|
||||
ntcp2_host: "127.0.0.1",
|
||||
ntcp2_port: 0,
|
||||
})
|
||||
defer router_a.close()
|
||||
let _ = router_a.netdb.store_router_info(router_b.router_info)
|
||||
let _ = router_b.netdb.store_router_info(router_a.router_info)
|
||||
let rs = [router_a, router_b]
|
||||
|
||||
// Bob opens SAM control session + STREAM ACCEPT on router B
|
||||
let bob_ctrl = sam_connect_and_hello(router_b.sam_port(), rs)
|
||||
defer bob_ctrl.close()
|
||||
bob_ctrl.write_all(
|
||||
b"SESSION CREATE STYLE=STREAM ID=bob DESTINATION=TRANSIENT\n",
|
||||
)
|
||||
let bob_sess = pump_read_line(bob_ctrl, rs)
|
||||
assert_true(bob_sess.has_prefix("SESSION STATUS RESULT=OK"))
|
||||
bob_ctrl.write_all(b"NAMING LOOKUP NAME=ME\n")
|
||||
let bob_me = pump_read_line(bob_ctrl, rs)
|
||||
let bob_pub_b64 = extract_kv(bob_me, "VALUE")
|
||||
let bob_dest = @common.Destination::from_base64(bob_pub_b64)
|
||||
let bob_b32 = bob_dest.b32_address()
|
||||
|
||||
let bob_acc = sam_connect_and_hello(router_b.sam_port(), rs)
|
||||
defer bob_acc.close()
|
||||
bob_acc.write_all(b"STREAM ACCEPT ID=bob SILENT=false\n")
|
||||
assert_eq(pump_read_line(bob_acc, rs), "STREAM STATUS RESULT=OK")
|
||||
|
||||
// Alice creates SAM control session on router A and looks up Bob's .b32.i2p via live NTCP2 ECIES NetDB
|
||||
let alice_ctrl = sam_connect_and_hello(router_a.sam_port(), rs)
|
||||
defer alice_ctrl.close()
|
||||
alice_ctrl.write_all(
|
||||
b"SESSION CREATE STYLE=STREAM ID=alice DESTINATION=TRANSIENT\n",
|
||||
)
|
||||
let alice_sess = pump_read_line(alice_ctrl, rs)
|
||||
assert_true(alice_sess.has_prefix("SESSION STATUS RESULT=OK"))
|
||||
|
||||
alice_ctrl.write_all(
|
||||
@encoding.string_to_utf8_bytes("NAMING LOOKUP NAME=\{bob_b32}\n"),
|
||||
)
|
||||
let alice_lookup = pump_read_line(alice_ctrl, rs)
|
||||
assert_true(alice_lookup.has_prefix("NAMING REPLY RESULT=OK"))
|
||||
assert_eq(extract_kv(alice_lookup, "VALUE"), bob_pub_b64)
|
||||
|
||||
// Alice connects over ECIES-X25519-AEAD-Ratchet Garlic + Ed25519 Streaming
|
||||
let alice_data = sam_connect_and_hello(router_a.sam_port(), rs)
|
||||
defer alice_data.close()
|
||||
alice_data.write_all(
|
||||
@encoding.string_to_utf8_bytes(
|
||||
"STREAM CONNECT ID=alice DESTINATION=\{bob_pub_b64} SILENT=false\n",
|
||||
),
|
||||
)
|
||||
assert_eq(pump_read_line(alice_data, rs), "STREAM STATUS RESULT=OK")
|
||||
let seen_peer_b64 = pump_read_line(bob_acc, rs)
|
||||
assert_true(seen_peer_b64.length() > 100)
|
||||
|
||||
// Bidirectional Streaming payload + close exchange
|
||||
alice_data.write_all(b"hello-over-ecies-streaming")
|
||||
alice_data.shutdown_write()
|
||||
let got_on_bob = pump_read_until_eof(bob_acc, rs)
|
||||
assert_eq(got_on_bob, b"hello-over-ecies-streaming")
|
||||
|
||||
bob_acc.write_all(b"ack-from-bob")
|
||||
bob_acc.shutdown_write()
|
||||
let got_on_alice = pump_read_until_eof(alice_data, rs)
|
||||
assert_eq(got_on_alice, b"ack-from-bob")
|
||||
}
|
||||
|
||||
///|
|
||||
test "Three-router live Proposal 157 multi-hop tunnel build and fragmented 2500B TunnelData stream" {
|
||||
let router_b = @router.Router::start(
|
||||
{
|
||||
sam_host: "127.0.0.1",
|
||||
sam_port: 0,
|
||||
ntcp2_host: "127.0.0.1",
|
||||
ntcp2_port: 0,
|
||||
},
|
||||
floodfill=true,
|
||||
)
|
||||
defer router_b.close()
|
||||
let router_c = @router.Router::start({
|
||||
sam_host: "127.0.0.1",
|
||||
sam_port: 0,
|
||||
ntcp2_host: "127.0.0.1",
|
||||
ntcp2_port: 0,
|
||||
})
|
||||
defer router_c.close()
|
||||
let router_a = @router.Router::start({
|
||||
sam_host: "127.0.0.1",
|
||||
sam_port: 0,
|
||||
ntcp2_host: "127.0.0.1",
|
||||
ntcp2_port: 0,
|
||||
})
|
||||
defer router_a.close()
|
||||
|
||||
for r in [router_a, router_b, router_c] {
|
||||
let _ = r.netdb.store_router_info(router_a.router_info)
|
||||
let _ = r.netdb.store_router_info(router_b.router_info)
|
||||
let _ = r.netdb.store_router_info(router_c.router_info)
|
||||
}
|
||||
let rs = [router_a, router_b, router_c]
|
||||
|
||||
// Router A builds 2-hop Outbound [B -> C] and 2-hop Inbound [B -> C -> A] tunnels via Proposal 157
|
||||
let out_tid = router_a.build_tunnel(
|
||||
[router_b.router_hash(), router_c.router_hash()],
|
||||
Outbound,
|
||||
)
|
||||
let in_tid = router_a.build_tunnel(
|
||||
[router_b.router_hash(), router_c.router_hash()],
|
||||
Inbound,
|
||||
)
|
||||
let mut built = false
|
||||
for _i = 0; _i < 1000; _i = _i + 1 {
|
||||
step_routers(rs, 1)
|
||||
if router_a.has_tunnel(out_tid) && router_a.has_tunnel(in_tid) {
|
||||
built = true
|
||||
break
|
||||
}
|
||||
}
|
||||
assert_true(built)
|
||||
assert_true(router_b.tunnels.transit_count() >= 2)
|
||||
assert_true(router_c.tunnels.transit_count() >= 2)
|
||||
|
||||
// Router C hosts Bob; Router A hosts Alice (whose LS2 uses her Inbound [B -> C -> A] tunnel lease)
|
||||
let bob_ctrl = sam_connect_and_hello(router_c.sam_port(), rs)
|
||||
defer bob_ctrl.close()
|
||||
bob_ctrl.write_all(
|
||||
b"SESSION CREATE STYLE=STREAM ID=bob3 DESTINATION=TRANSIENT\n",
|
||||
)
|
||||
assert_true(
|
||||
pump_read_line(bob_ctrl, rs).has_prefix("SESSION STATUS RESULT=OK"),
|
||||
)
|
||||
bob_ctrl.write_all(b"NAMING LOOKUP NAME=ME\n")
|
||||
let bob_pub_b64 = extract_kv(pump_read_line(bob_ctrl, rs), "VALUE")
|
||||
let bob_b32 = @common.Destination::from_base64(bob_pub_b64).b32_address()
|
||||
|
||||
let bob_acc = sam_connect_and_hello(router_c.sam_port(), rs)
|
||||
defer bob_acc.close()
|
||||
bob_acc.write_all(b"STREAM ACCEPT ID=bob3 SILENT=false\n")
|
||||
assert_eq(pump_read_line(bob_acc, rs), "STREAM STATUS RESULT=OK")
|
||||
|
||||
let alice_ctrl = sam_connect_and_hello(router_a.sam_port(), rs)
|
||||
defer alice_ctrl.close()
|
||||
alice_ctrl.write_all(
|
||||
b"SESSION CREATE STYLE=STREAM ID=alice3 DESTINATION=TRANSIENT\n",
|
||||
)
|
||||
assert_true(
|
||||
pump_read_line(alice_ctrl, rs).has_prefix("SESSION STATUS RESULT=OK"),
|
||||
)
|
||||
alice_ctrl.write_all(
|
||||
@encoding.string_to_utf8_bytes("NAMING LOOKUP NAME=\{bob_b32}\n"),
|
||||
)
|
||||
assert_eq(extract_kv(pump_read_line(alice_ctrl, rs), "VALUE"), bob_pub_b64)
|
||||
|
||||
let alice_data = sam_connect_and_hello(router_a.sam_port(), rs)
|
||||
defer alice_data.close()
|
||||
alice_data.write_all(
|
||||
@encoding.string_to_utf8_bytes(
|
||||
"STREAM CONNECT ID=alice3 DESTINATION=\{bob_pub_b64} SILENT=false\n",
|
||||
),
|
||||
)
|
||||
assert_eq(pump_read_line(alice_data, rs), "STREAM STATUS RESULT=OK")
|
||||
let _ = pump_read_line(bob_acc, rs)
|
||||
|
||||
// Send 2500 bytes (spanning multiple Streaming packets & fragmented 1024B TunnelData cells)
|
||||
let big_payload = Bytes::make(2500, b'\x41')
|
||||
alice_data.write_all(big_payload)
|
||||
alice_data.shutdown_write()
|
||||
assert_eq(pump_read_until_eof(bob_acc, rs), big_payload)
|
||||
|
||||
bob_acc.write_all(b"tunneled-ok")
|
||||
bob_acc.shutdown_write()
|
||||
assert_eq(pump_read_until_eof(alice_data, rs), b"tunneled-ok")
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,480 @@
|
||||
///|
|
||||
/// Live Proposal 157 ShortTunnelBuild engine and AES-256-CBC `TunnelData`/`TunnelGateway` relay.
|
||||
|
||||
///|
|
||||
priv struct PendingTunnelBuild {
|
||||
tunnel_id : UInt32
|
||||
direction : @tunnel.TunnelDirection
|
||||
hops : Array[@tunnel.TunnelHop]
|
||||
hop_slots_and_keys : Array[(Int32, @tunnel.HopKeys)]
|
||||
build_msg_id : UInt32
|
||||
created_sec : UInt32
|
||||
expires_sec : UInt32
|
||||
started_ms : UInt64
|
||||
}
|
||||
|
||||
///|
|
||||
/// Returns `true` if `tunnel_id` has completed building and is active in `self.tunnels`.
|
||||
pub fn Router::has_tunnel(self : Router, tunnel_id : UInt32) -> Bool {
|
||||
for t in self.tunnels.inbound {
|
||||
if t.id == tunnel_id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for t in self.tunnels.outbound {
|
||||
if t.id == tunnel_id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
///|
|
||||
/// Initiates a Proposal 157 `ShortTunnelBuild` along `hop_hashes` (1..8 routers).
|
||||
/// Returns the allocated local tunnel ID; drive completion with `Router::step()`
|
||||
/// and check readiness via `Router::has_tunnel(tid)`.
|
||||
pub fn Router::build_tunnel(
|
||||
self : Router,
|
||||
hop_hashes : Array[@common.Hash],
|
||||
direction : @tunnel.TunnelDirection,
|
||||
expiration_sec~ : UInt32 = 600U,
|
||||
) -> UInt32 raise RouterError {
|
||||
let hop_count = hop_hashes.length()
|
||||
if hop_count < 1 || hop_count > 8 {
|
||||
raise Protocol("tunnel hop count must be 1..8, got \{hop_count}")
|
||||
}
|
||||
let now_ms = @ntcp2_net.unix_time_ms()
|
||||
let now_sec = (now_ms / 1000UL).to_uint()
|
||||
let req_time_min = now_sec / 60U
|
||||
let local_tid = self.alloc_tunnel_id()
|
||||
let build_msg_id = self.alloc_msg_id()
|
||||
|
||||
let hop_recv_tids : Array[UInt32] = Array(capacity=hop_count)
|
||||
let hop_static_pubs : Array[Bytes] = Array(capacity=hop_count)
|
||||
for h in hop_hashes {
|
||||
let ri = match self.netdb.get_router_info(h) {
|
||||
Some(r) => r
|
||||
None => raise Protocol("missing RouterInfo for tunnel hop")
|
||||
}
|
||||
let x_pub = ri.identity.inner.crypto_public_key()
|
||||
if x_pub.length() != 32 {
|
||||
raise Protocol("tunnel hop lacks X25519 identity key")
|
||||
}
|
||||
hop_static_pubs.push(x_pub)
|
||||
hop_recv_tids.push(self.alloc_tunnel_id())
|
||||
}
|
||||
|
||||
let total_slots = if hop_count <= 4 { 4 } else { 8 }
|
||||
let specs : Array[@tunnel.ShortHopBuildSpec] = Array(capacity=hop_count)
|
||||
let next_tids : Array[UInt32] = Array(capacity=hop_count)
|
||||
for i = 0; i < hop_count; i = i + 1 {
|
||||
let next_tid = if i + 1 < hop_count {
|
||||
hop_recv_tids[i + 1]
|
||||
} else if direction == Inbound {
|
||||
local_tid
|
||||
} else {
|
||||
0U
|
||||
}
|
||||
next_tids.push(next_tid)
|
||||
let next_ident = if i + 1 < hop_count {
|
||||
hop_hashes[i + 1]
|
||||
} else {
|
||||
self.router_hash()
|
||||
}
|
||||
let flag : Byte = if direction == Inbound && i == 0 {
|
||||
b'\x80'
|
||||
} else if direction == Outbound && i == hop_count - 1 {
|
||||
b'\x40'
|
||||
} else {
|
||||
b'\x00'
|
||||
}
|
||||
let epriv = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) }
|
||||
let ephem = @noise.KeyPair::from_private(epriv) catch {
|
||||
e => raise Noise(e)
|
||||
}
|
||||
let pad = @ntcp2_net.random_bytes(8) catch { _ => b"" }
|
||||
specs.push({
|
||||
slot_idx: i,
|
||||
hop_ident: hop_hashes[i],
|
||||
hop_static_pub: hop_static_pubs[i],
|
||||
ephemeral: ephem,
|
||||
record: {
|
||||
receive_tunnel_id: hop_recv_tids[i],
|
||||
next_tunnel_id: next_tid,
|
||||
next_ident,
|
||||
flag,
|
||||
layer_enc_type: b'\x00',
|
||||
request_time_min: req_time_min,
|
||||
request_expiration_sec: expiration_sec,
|
||||
send_message_id: build_msg_id,
|
||||
options: @common.Mapping::new(),
|
||||
},
|
||||
padding: pad,
|
||||
})
|
||||
}
|
||||
|
||||
let dummies : Array[Bytes] = []
|
||||
for _d = hop_count; _d < total_slots; _d = _d + 1 {
|
||||
let dummy = @ntcp2_net.random_bytes(218) catch {
|
||||
_ => Bytes::make(218, b'\x5a')
|
||||
}
|
||||
dummies.push(dummy)
|
||||
}
|
||||
let (records, hop_slots_and_keys) = @tunnel.build_short_tunnel_request(
|
||||
total_slots, specs, dummies,
|
||||
) catch {
|
||||
e => raise Tunnel(e)
|
||||
}
|
||||
|
||||
let tunnel_hops : Array[@tunnel.TunnelHop] = Array(capacity=hop_count)
|
||||
for i = 0; i < hop_count; i = i + 1 {
|
||||
let keys = hop_slots_and_keys[i].1
|
||||
tunnel_hops.push({
|
||||
router_hash: hop_hashes[i],
|
||||
receive_tunnel_id: hop_recv_tids[i],
|
||||
next_tunnel_id: next_tids[i],
|
||||
layer_key: keys.layer_key,
|
||||
iv_key: keys.iv_key,
|
||||
})
|
||||
}
|
||||
self.pending_builds.push({
|
||||
tunnel_id: local_tid,
|
||||
direction,
|
||||
hops: tunnel_hops,
|
||||
hop_slots_and_keys,
|
||||
build_msg_id,
|
||||
created_sec: now_sec,
|
||||
expires_sec: now_sec + expiration_sec,
|
||||
started_ms: now_ms,
|
||||
})
|
||||
let _ = self.send_i2np_to_peer(
|
||||
hop_hashes[0],
|
||||
ShortTunnelBuild(records~),
|
||||
msg_id_override=Some(build_msg_id),
|
||||
)
|
||||
local_tid
|
||||
}
|
||||
|
||||
///|
|
||||
/// Sends an I2NP message encrypted through a built active `Outbound` tunnel.
|
||||
pub fn Router::send_through_tunnel(
|
||||
self : Router,
|
||||
outbound_tunnel_id : UInt32,
|
||||
target : @tunnel.DeliveryTarget,
|
||||
payload : @i2np.I2npPayload,
|
||||
) -> Unit raise RouterError {
|
||||
let mut out_tun : @tunnel.Tunnel? = None
|
||||
for t in self.tunnels.outbound {
|
||||
if t.id == outbound_tunnel_id {
|
||||
out_tun = Some(t)
|
||||
break
|
||||
}
|
||||
}
|
||||
let tun = match out_tun {
|
||||
Some(t) => t
|
||||
None => raise Protocol("unknown outbound tunnel \{outbound_tunnel_id}")
|
||||
}
|
||||
if tun.hops.length() == 0 {
|
||||
raise Protocol("outbound tunnel has zero hops")
|
||||
}
|
||||
let now_ms = @ntcp2_net.unix_time_ms()
|
||||
let inner_mid = self.alloc_msg_id()
|
||||
let std_bytes = @i2np.encode_standard_message(
|
||||
inner_mid,
|
||||
now_ms + 60000UL,
|
||||
payload,
|
||||
) catch {
|
||||
e => raise I2np(e)
|
||||
}
|
||||
let base_iv = @ntcp2_net.random_bytes(16) catch { e => raise Net(e) }
|
||||
let pad = non_zero_random_bytes(1024)
|
||||
let cells = @tunnel.fragment_message_to_cells(
|
||||
target,
|
||||
self.alloc_msg_id(),
|
||||
std_bytes,
|
||||
base_iv,
|
||||
padding=pad,
|
||||
) catch {
|
||||
e => raise Tunnel(e)
|
||||
}
|
||||
let first_hop = tun.hops[0]
|
||||
for cell in cells {
|
||||
let enc_cell = tun.prepare_outbound_cell(cell) catch {
|
||||
e => raise Tunnel(e)
|
||||
}
|
||||
let _ = self.send_i2np_to_peer(
|
||||
first_hop.router_hash,
|
||||
TunnelData(tunnel_id=first_hop.receive_tunnel_id, data=enc_cell),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::try_complete_pending_tunnel_build(
|
||||
self : Router,
|
||||
build_msg_id : UInt32,
|
||||
records : Array[Bytes],
|
||||
) -> Bool {
|
||||
let mut idx = -1
|
||||
for i = 0; i < self.pending_builds.length(); i = i + 1 {
|
||||
if self.pending_builds[i].build_msg_id == build_msg_id {
|
||||
idx = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if idx < 0 {
|
||||
return false
|
||||
}
|
||||
let pb = self.pending_builds.remove(idx)
|
||||
let codes = @tunnel.decrypt_short_tunnel_replies(
|
||||
records,
|
||||
pb.hop_slots_and_keys,
|
||||
) catch {
|
||||
_ => return true
|
||||
}
|
||||
for c in codes {
|
||||
if c != b'\x00' {
|
||||
return true
|
||||
}
|
||||
}
|
||||
let dir = pb.direction
|
||||
self.tunnels.add_tunnel({
|
||||
id: pb.tunnel_id,
|
||||
direction: dir,
|
||||
hops: pb.hops,
|
||||
created_sec: pb.created_sec,
|
||||
expires_sec: pb.expires_sec,
|
||||
})
|
||||
if dir == Inbound {
|
||||
self.republish_all_sessions()
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::handle_short_tunnel_build(
|
||||
self : Router,
|
||||
msg_id : UInt32,
|
||||
records : Array[Bytes],
|
||||
now_sec : UInt32,
|
||||
) -> Unit {
|
||||
if self.try_complete_pending_tunnel_build(msg_id, records) {
|
||||
return
|
||||
}
|
||||
let reply_pad = @ntcp2_net.random_bytes(8) catch { _ => b"" }
|
||||
let (rec, keys, _slot, out_records) = @tunnel.process_short_tunnel_build_hop(
|
||||
records,
|
||||
self.router_hash(),
|
||||
self.static_key,
|
||||
b'\x00',
|
||||
reply_padding=reply_pad,
|
||||
) catch {
|
||||
_ => return
|
||||
}
|
||||
let is_obep = (rec.flag.to_int() & 0x40) != 0
|
||||
let exp_sec = now_sec +
|
||||
(if rec.request_expiration_sec > 0U {
|
||||
rec.request_expiration_sec
|
||||
} else {
|
||||
600U
|
||||
})
|
||||
self.tunnels.add_transit_hop({
|
||||
receive_tunnel_id: rec.receive_tunnel_id,
|
||||
next_tunnel_id: rec.next_tunnel_id,
|
||||
next_router: rec.next_ident,
|
||||
layer_key: keys.layer_key,
|
||||
iv_key: keys.iv_key,
|
||||
is_obep,
|
||||
expires_sec: exp_sec,
|
||||
})
|
||||
if is_obep {
|
||||
let reply_payload : @i2np.I2npPayload = ShortTunnelBuildReply(
|
||||
records=out_records,
|
||||
)
|
||||
if rec.next_tunnel_id != 0U {
|
||||
let std = @i2np.encode_standard_message(
|
||||
rec.send_message_id,
|
||||
@ntcp2_net.unix_time_ms() + 60000UL,
|
||||
reply_payload,
|
||||
) catch {
|
||||
_ => return
|
||||
}
|
||||
let _ = self.send_i2np_to_peer(
|
||||
rec.next_ident,
|
||||
TunnelGateway(tunnel_id=rec.next_tunnel_id, data=std),
|
||||
)
|
||||
} else {
|
||||
let _ = self.send_i2np_to_peer(
|
||||
rec.next_ident,
|
||||
reply_payload,
|
||||
msg_id_override=Some(rec.send_message_id),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
let _ = self.send_i2np_to_peer(
|
||||
rec.next_ident,
|
||||
ShortTunnelBuild(records=out_records),
|
||||
msg_id_override=Some(rec.send_message_id),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::handle_short_tunnel_build_reply(
|
||||
self : Router,
|
||||
msg_id : UInt32,
|
||||
records : Array[Bytes],
|
||||
) -> Unit {
|
||||
let _ = self.try_complete_pending_tunnel_build(msg_id, records)
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::deliver_reassembled_payload(
|
||||
self : Router,
|
||||
target : @tunnel.DeliveryTarget,
|
||||
full_payload : Bytes,
|
||||
now_sec : UInt32,
|
||||
) -> Unit {
|
||||
let (hdr, inner_payload) = @i2np.decode_standard_message(
|
||||
@encoding.Reader::new(full_payload),
|
||||
) catch {
|
||||
_ => return
|
||||
}
|
||||
match target {
|
||||
Local =>
|
||||
self.handle_i2np_message(
|
||||
None,
|
||||
{
|
||||
msg_type: hdr.msg_type,
|
||||
msg_id: hdr.msg_id,
|
||||
expiration_sec: now_sec + 60U,
|
||||
},
|
||||
inner_payload,
|
||||
)
|
||||
Router(router_hash~) => {
|
||||
let _ = self.send_i2np_to_peer(
|
||||
router_hash,
|
||||
inner_payload,
|
||||
msg_id_override=Some(hdr.msg_id),
|
||||
)
|
||||
}
|
||||
Tunnel(tunnel_id~, gateway~) => {
|
||||
let _ = self.send_i2np_to_peer(
|
||||
gateway,
|
||||
TunnelGateway(tunnel_id~, data=full_payload),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::consume_cleartext_cell(
|
||||
self : Router,
|
||||
cleartext_cell : Bytes,
|
||||
now_sec : UInt32,
|
||||
) -> Unit {
|
||||
let frags = @tunnel.unpack_tunnel_cell(cleartext_cell) catch { _ => return }
|
||||
for frag in frags {
|
||||
match self.reassembler.push(frag) {
|
||||
Some((target, full_payload)) =>
|
||||
self.deliver_reassembled_payload(target, full_payload, now_sec)
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::handle_tunnel_data(
|
||||
self : Router,
|
||||
tunnel_id : UInt32,
|
||||
data : Bytes,
|
||||
) -> Unit {
|
||||
let now_sec = @ntcp2_net.unix_time_sec()
|
||||
// 1. Check if we are the inbound tunnel endpoint (IBEP)
|
||||
for in_t in self.tunnels.inbound {
|
||||
if in_t.id == tunnel_id {
|
||||
let clear = in_t.decrypt_inbound_cell(data) catch { _ => return }
|
||||
self.consume_cleartext_cell(clear, now_sec)
|
||||
return
|
||||
}
|
||||
}
|
||||
// 2. Otherwise check transit hops (IBGW / intermediate / OBEP)
|
||||
let relay_res = self.tunnels.relay_cell(tunnel_id, data) catch { _ => None }
|
||||
match relay_res {
|
||||
Some((next_router, next_tid, next_cell, is_obep)) =>
|
||||
if is_obep {
|
||||
self.consume_cleartext_cell(next_cell, now_sec)
|
||||
} else {
|
||||
let _ = self.send_i2np_to_peer(
|
||||
next_router,
|
||||
TunnelData(tunnel_id=next_tid, data=next_cell),
|
||||
)
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::handle_tunnel_gateway(
|
||||
self : Router,
|
||||
tunnel_id : UInt32,
|
||||
data : Bytes,
|
||||
now_sec : UInt32,
|
||||
) -> Unit {
|
||||
// Check if tunnel_id corresponds to a transit hop where we act as IBGW
|
||||
let mut is_transit = false
|
||||
for hop in self.tunnels.transit {
|
||||
if hop.receive_tunnel_id == tunnel_id {
|
||||
is_transit = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if is_transit {
|
||||
let base_iv = @ntcp2_net.random_bytes(16) catch { _ => return }
|
||||
let pad = non_zero_random_bytes(1024)
|
||||
let cells = @tunnel.fragment_message_to_cells(
|
||||
Local,
|
||||
self.alloc_msg_id(),
|
||||
data,
|
||||
base_iv,
|
||||
padding=pad,
|
||||
) catch {
|
||||
_ => return
|
||||
}
|
||||
for cell in cells {
|
||||
let relay_res = self.tunnels.relay_cell(tunnel_id, cell) catch {
|
||||
_ => None
|
||||
}
|
||||
match relay_res {
|
||||
Some((next_router, next_tid, next_cell, is_obep)) =>
|
||||
if is_obep {
|
||||
self.consume_cleartext_cell(next_cell, now_sec)
|
||||
} else {
|
||||
let _ = self.send_i2np_to_peer(
|
||||
next_router,
|
||||
TunnelData(tunnel_id=next_tid, data=next_cell),
|
||||
)
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
// Direct 0-hop session delivery or forwarded standard I2NP message
|
||||
self.deliver_reassembled_payload(Local, data, now_sec)
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::poll_tunnel_builds(self : Router) -> Unit {
|
||||
let now_ms = @ntcp2_net.unix_time_ms()
|
||||
let now_sec = (now_ms / 1000UL).to_uint()
|
||||
let _ = self.tunnels.prune_expired(now_sec)
|
||||
let mut i = 0
|
||||
while i < self.pending_builds.length() {
|
||||
if now_ms > self.pending_builds[i].started_ms + 10000UL {
|
||||
let _ = self.pending_builds.remove(i)
|
||||
} else {
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user