feat: add non-blocking Noise handshake, SecureConnection transport

refactor
This commit is contained in:
2026-02-19 11:34:43 -03:00
parent 4c1927588d
commit 75087fb635
4 changed files with 962 additions and 92 deletions

View File

@@ -5,12 +5,18 @@
//! after the initial handshake completes. //! after the initial handshake completes.
const std = @import("std"); const std = @import("std");
const builtin = @import("builtin");
const mem = std.mem; const mem = std.mem;
const posix = std.posix; const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const posix = if (!is_wasm) std.posix else struct {};
const core = @import("core"); const core = @import("core");
const Socket = core.socket.Socket; const Socket = core.socket.Socket;
const CoreError = core.errors.Error; const CoreError = core.errors.Error;
const CoreTransport = core.transport.Transport;
const platform = @import("platform");
const PosixStreamTransport = platform.PosixStreamTransport;
const noise = @import("noise"); const noise = @import("noise");
const NoiseError = noise.Error; const NoiseError = noise.Error;
@@ -64,8 +70,14 @@ pub const DEFAULT_REKEY_INTERVAL: u64 = 1000;
/// SecureConnection wraps a socket with Noise protocol encryption /// SecureConnection wraps a socket with Noise protocol encryption
pub const SecureConnection = struct { pub const SecureConnection = struct {
/// Underlying socket /// Underlying socket (kept for stats and cleanup; will become optional for WebRTC)
socket: *Socket, socket: *Socket,
/// Transport-agnostic I/O handle — all raw send/receive goes through this
io_transport: CoreTransport,
/// Inline storage for PosixStreamTransport wrapping the socket.
/// io_transport.ptr points here. Safe because SecureConnection is heap-allocated.
/// Void on WASM (no POSIX sockets).
_posix_transport: if (is_wasm) void else PosixStreamTransport,
/// Noise transport state (null until handshake completes) /// Noise transport state (null until handshake completes)
transport: ?Transport, transport: ?Transport,
/// Whether handshake has completed successfully /// Whether handshake has completed successfully
@@ -91,22 +103,316 @@ pub const SecureConnection = struct {
/// Each peer pair gets a unique key — an attacker with the binary /// Each peer pair gets a unique key — an attacker with the binary
/// cannot forge envelopes for connections they aren't part of. /// cannot forge envelopes for connections they aren't part of.
envelope_key: ?[16]u8 = null, envelope_key: ?[16]u8 = null,
/// Non-blocking handshake state (heap-allocated, freed on completion/failure).
nb_handshake: ?*NonBlockingHandshakeState = null,
const Self = @This(); const Self = @This();
/// Initialize a secure connection (handshake not yet performed) /// Result of a single advanceHandshake() call.
pub fn init(socket: *Socket, local_keypair: KeyPair, allocator: mem.Allocator) Self { pub const HandshakeAdvance = enum {
return Self{ /// Made progress on I/O, call again soon.
.socket = socket, progress,
.transport = null, /// No I/O progress (WouldBlock), try again later.
.handshake_complete = false, would_block,
.remote_static_key = null, /// Handshake completed successfully.
.local_keypair = local_keypair, complete,
.encrypt_buf = undefined,
.decrypt_buf = undefined,
.allocator = allocator,
}; };
/// Internal state for a non-blocking Noise XX handshake.
/// Heap-allocated during handshake, freed when complete or failed.
pub const NonBlockingHandshakeState = struct {
hs: HandshakeState,
phase: Phase,
role: Role,
/// Send buffer — holds the current outgoing Noise message.
send_buf: [96]u8 = undefined,
send_len: usize = 0,
send_offset: usize = 0,
/// Receive buffer — accumulates incoming Noise message bytes.
recv_buf: [96]u8 = undefined,
recv_offset: usize = 0,
recv_min: usize = 0,
/// Scratch buffer for Noise readMessage payloads.
payload_buf: [64]u8 = undefined,
/// Absolute deadline (nanoseconds since epoch).
deadline_ns: i128,
const Phase = enum {
/// Sending send_buf[send_offset..send_len]
sending,
/// Receiving into recv_buf[recv_offset..], need recv_min bytes
receiving,
/// Handshake done
complete,
};
};
/// Initialize a secure connection (handshake not yet performed).
/// Must be called on a heap-allocated SecureConnection (self-referential pointer).
pub fn init(self: *Self, socket: *Socket, local_keypair: KeyPair, allocator: mem.Allocator) void {
self.socket = socket;
if (!is_wasm) {
self._posix_transport = PosixStreamTransport.init(socket);
self.io_transport = CoreTransport.init(&self._posix_transport);
} else {
self._posix_transport = {};
self.io_transport = undefined;
} }
self.transport = null;
self.handshake_complete = false;
self.remote_static_key = null;
self.local_keypair = local_keypair;
self.encrypt_buf = undefined;
self.decrypt_buf = undefined;
self.allocator = allocator;
self.messages_sent_since_rekey = 0;
self.messages_received_since_rekey = 0;
self.rekey_interval = DEFAULT_REKEY_INTERVAL;
self.envelope_key = null;
self.nb_handshake = null;
}
/// Initialize with a pre-built Transport (e.g. WebRTC DataChannel).
/// No socket is associated; the `socket` field is undefined and must not be used.
/// The caller-provided transport is stored directly in `io_transport`.
pub fn initWithTransport(self: *Self, io_transport_arg: CoreTransport, local_keypair: KeyPair, allocator: mem.Allocator) void {
self.socket = undefined;
self._posix_transport = if (is_wasm) {} else undefined;
self.io_transport = io_transport_arg;
self.transport = null;
self.handshake_complete = false;
self.remote_static_key = null;
self.local_keypair = local_keypair;
self.encrypt_buf = undefined;
self.decrypt_buf = undefined;
self.allocator = allocator;
self.messages_sent_since_rekey = 0;
self.messages_received_since_rekey = 0;
self.rekey_interval = DEFAULT_REKEY_INTERVAL;
self.envelope_key = null;
self.nb_handshake = null;
}
// =========================================================================
// Non-blocking handshake state machine
// =========================================================================
/// Start a non-blocking handshake. Call advanceHandshake() repeatedly
/// from the update loop until it returns .complete or error.
pub fn startHandshake(self: *Self, role: Role) Error!void {
if (self.nb_handshake != null) return Error.HandshakeFailed; // already in progress
const nbs = self.allocator.create(NonBlockingHandshakeState) catch return Error.OutOfMemory;
nbs.* = .{
.hs = HandshakeState.initXX(role, self.local_keypair, null),
.role = role,
.phase = undefined, // set below
.deadline_ns = platform.time.nanoTimestamp() + HANDSHAKE_TIMEOUT_NS,
};
// Prepare the first step based on role
switch (role) {
.initiator => {
// Initiator sends msg1 first
const msg1_len = nbs.hs.writeMessage(&.{}, &nbs.send_buf) catch {
self.allocator.destroy(nbs);
return Error.HandshakeFailed;
};
nbs.send_len = msg1_len;
nbs.send_offset = 0;
nbs.phase = .sending;
},
.responder => {
// Responder receives msg1 first
nbs.recv_offset = 0;
nbs.recv_min = 32; // minimum: ephemeral key
nbs.phase = .receiving;
},
}
self.nb_handshake = nbs;
}
/// Advance the non-blocking handshake by one I/O step.
/// Returns:
/// .progress — made I/O progress, call again soon
/// .would_block — no I/O progress (socket not ready), try later
/// .complete — handshake finished successfully
/// error — handshake failed (state is cleaned up)
pub fn advanceHandshake(self: *Self) Error!HandshakeAdvance {
const nbs = self.nb_handshake orelse return Error.HandshakeFailed;
// Check deadline
if (platform.time.nanoTimestamp() >= nbs.deadline_ns) {
self.cleanupHandshake();
return Error.HandshakeTimeout;
}
switch (nbs.phase) {
.sending => return self.advanceSend(nbs),
.receiving => return self.advanceReceive(nbs),
.complete => {
self.cleanupHandshake();
return .complete;
},
}
}
/// Drive the send phase: non-blocking send of nbs.send_buf[send_offset..send_len].
fn advanceSend(self: *Self, nbs: *NonBlockingHandshakeState) Error!HandshakeAdvance {
while (nbs.send_offset < nbs.send_len) {
const bytes = self.io_transport.send(nbs.send_buf[nbs.send_offset..nbs.send_len]) catch |err| {
switch (err) {
CoreError.ConnectionTimeout => return .would_block,
else => {
self.cleanupHandshake();
return Error.SocketError;
},
}
};
nbs.send_offset += bytes;
}
// Send complete — transition to next step
self.transitionAfterSend(nbs) catch |err| {
self.cleanupHandshake();
return err;
};
if (nbs.phase == .complete) {
self.finalizeHandshake(nbs) catch |err| {
self.cleanupHandshake();
return err;
};
self.cleanupHandshake();
return .complete;
}
return .progress;
}
/// Drive the receive phase: non-blocking receive into nbs.recv_buf until recv_min bytes.
fn advanceReceive(self: *Self, nbs: *NonBlockingHandshakeState) Error!HandshakeAdvance {
while (nbs.recv_offset < nbs.recv_min) {
const bytes = self.io_transport.receive(nbs.recv_buf[nbs.recv_offset..]) catch |err| {
switch (err) {
CoreError.ConnectionTimeout => return .would_block,
CoreError.ConnectionClosed => {
self.cleanupHandshake();
return Error.HandshakeFailed;
},
else => {
self.cleanupHandshake();
return Error.SocketError;
},
}
};
nbs.recv_offset += bytes;
}
// Receive complete — process message and transition
self.transitionAfterReceive(nbs) catch |err| {
self.cleanupHandshake();
return err;
};
if (nbs.phase == .complete) {
self.finalizeHandshake(nbs) catch |err| {
self.cleanupHandshake();
return err;
};
self.cleanupHandshake();
return .complete;
}
return .progress;
}
/// After a send completes, determine the next phase based on role and message number.
fn transitionAfterSend(self: *Self, nbs: *NonBlockingHandshakeState) Error!void {
_ = self;
switch (nbs.role) {
.initiator => {
if (nbs.send_len <= 48) {
// Just sent msg1 (48 bytes) → receive msg2
nbs.recv_offset = 0;
nbs.recv_min = 80; // minimum expected msg2 size
nbs.phase = .receiving;
} else {
// Just sent msg3 (64 bytes) → handshake complete
nbs.phase = .complete;
}
},
.responder => {
// Just sent msg2 (96 bytes) → receive msg3
nbs.recv_offset = 0;
nbs.recv_min = 48; // minimum expected msg3 size
nbs.phase = .receiving;
},
}
}
/// After a receive completes, process the Noise message and prepare the next send.
fn transitionAfterReceive(self: *Self, nbs: *NonBlockingHandshakeState) Error!void {
_ = self;
const received_len = nbs.recv_offset;
switch (nbs.role) {
.initiator => {
// Received msg2 → readMessage, then writeMessage for msg3
_ = nbs.hs.readMessage(nbs.recv_buf[0..received_len], &nbs.payload_buf) catch
return Error.HandshakeFailed;
const msg3_len = nbs.hs.writeMessage(&.{}, &nbs.send_buf) catch
return Error.HandshakeFailed;
nbs.send_len = msg3_len;
nbs.send_offset = 0;
nbs.phase = .sending;
},
.responder => {
if (nbs.send_len == 0) {
// Received msg1 → readMessage, then writeMessage for msg2
_ = nbs.hs.readMessage(nbs.recv_buf[0..received_len], &nbs.payload_buf) catch
return Error.HandshakeFailed;
const msg2_len = nbs.hs.writeMessage(&.{}, &nbs.send_buf) catch
return Error.HandshakeFailed;
nbs.send_len = msg2_len;
nbs.send_offset = 0;
nbs.phase = .sending;
} else {
// Received msg3 → readMessage, handshake complete
_ = nbs.hs.readMessage(nbs.recv_buf[0..received_len], &nbs.payload_buf) catch
return Error.HandshakeFailed;
nbs.phase = .complete;
}
},
}
}
/// Finalize: split HandshakeState into transport ciphers and derive envelope key.
fn finalizeHandshake(self: *Self, nbs: *NonBlockingHandshakeState) Error!void {
self.transport = nbs.hs.split() catch return Error.HandshakeFailed;
self.remote_static_key = nbs.hs.rs;
self.handshake_complete = true;
self.deriveEnvelopeKey();
// Zeroize handshake state
secureZeroBytes(std.mem.asBytes(&nbs.hs));
}
/// Free the non-blocking handshake state.
pub fn cleanupHandshake(self: *Self) void {
if (self.nb_handshake) |nbs| {
secureZeroBytes(std.mem.asBytes(&nbs.hs));
self.allocator.destroy(nbs);
self.nb_handshake = null;
}
}
// =========================================================================
// Blocking handshake (convenience wrappers using the state machine)
// =========================================================================
/// Perform handshake as initiator (client connecting to server) /// Perform handshake as initiator (client connecting to server)
pub fn initiateHandshake(self: *Self) Error!void { pub fn initiateHandshake(self: *Self) Error!void {
@@ -185,14 +491,13 @@ pub const SecureConnection = struct {
}; };
}; };
// Send the encrypted data with length prefix // Send the encrypted data with length prefix as a single frame.
var header: [4]u8 = undefined; // Combining header + payload ensures one DataChannel message on
std.mem.writeInt(u32, &header, @intCast(encrypted_len), .big); // message-based transports and fewer syscalls on stream transports.
var frame: [4 + MAX_MESSAGE_SIZE + TAG_SIZE]u8 = undefined;
// Send header std.mem.writeInt(u32, frame[0..4], @intCast(encrypted_len), .big);
try self.sendRaw(&header); @memcpy(frame[4..][0..encrypted_len], self.encrypt_buf[0..encrypted_len]);
// Send encrypted payload try self.sendRaw(frame[0 .. 4 + encrypted_len]);
try self.sendRaw(self.encrypt_buf[0..encrypted_len]);
self.maybeRekeyOutbound(); self.maybeRekeyOutbound();
@@ -203,7 +508,7 @@ pub const SecureConnection = struct {
/// This is for non-blocking send paths - caller handles actual socket send /// This is for non-blocking send paths - caller handles actual socket send
/// Returns a heap-allocated buffer that caller must free /// Returns a heap-allocated buffer that caller must free
pub fn encryptPacket(self: *Self, plaintext: []const u8, allocator: std.mem.Allocator) Error![]u8 { pub fn encryptPacket(self: *Self, plaintext: []const u8, allocator: std.mem.Allocator) Error![]u8 {
const start_time = std.time.nanoTimestamp(); const start_time = platform.time.nanoTimestamp();
if (!self.handshake_complete) return Error.NotEncrypted; if (!self.handshake_complete) return Error.NotEncrypted;
if (plaintext.len > MAX_MESSAGE_SIZE) return Error.MessageTooLarge; if (plaintext.len > MAX_MESSAGE_SIZE) return Error.MessageTooLarge;
@@ -229,7 +534,7 @@ pub const SecureConnection = struct {
@memcpy(packet[4..][0..encrypted_len], self.encrypt_buf[0..encrypted_len]); @memcpy(packet[4..][0..encrypted_len], self.encrypt_buf[0..encrypted_len]);
// PERF: Log encryption time for large packets // PERF: Log encryption time for large packets
const elapsed = std.time.nanoTimestamp() - start_time; const elapsed = platform.time.nanoTimestamp() - start_time;
const elapsed_ms = @as(f64, @floatFromInt(elapsed)) / 1_000_000.0; const elapsed_ms = @as(f64, @floatFromInt(elapsed)) / 1_000_000.0;
if (plaintext.len > 100_000 and elapsed_ms > 5.0) { if (plaintext.len > 100_000 and elapsed_ms > 5.0) {
std.log.warn("CRYPTO PERF: encrypted {}KB in {d:.1}ms ({d:.0}MB/s)", .{ std.log.warn("CRYPTO PERF: encrypted {}KB in {d:.1}ms ({d:.0}MB/s)", .{
@@ -247,7 +552,7 @@ pub const SecureConnection = struct {
/// ASYNC SEND: Try to send data without blocking /// ASYNC SEND: Try to send data without blocking
/// Returns bytes sent, or 0 if would block /// Returns bytes sent, or 0 if would block
pub fn trySendRawNonBlocking(self: *Self, data: []const u8) Error!usize { pub fn trySendRawNonBlocking(self: *Self, data: []const u8) Error!usize {
const bytes = self.socket.send(data) catch |err| { const bytes = self.io_transport.send(data) catch |err| {
switch (err) { switch (err) {
CoreError.ConnectionTimeout => return 0, // WouldBlock - return 0 CoreError.ConnectionTimeout => return 0, // WouldBlock - return 0
else => return Error.SocketError, else => return Error.SocketError,
@@ -332,11 +637,6 @@ pub const SecureConnection = struct {
} }
} }
/// Get the underlying socket for non-encrypted operations
pub fn getSocket(self: *Self) *Socket {
return self.socket;
}
// ========================================================================= // =========================================================================
// Forward secrecy: automatic rekeying // Forward secrecy: automatic rekeying
// ========================================================================= // =========================================================================
@@ -357,7 +657,9 @@ pub const SecureConnection = struct {
} }
/// Rekey inbound cipher after reaching the message threshold. /// Rekey inbound cipher after reaching the message threshold.
fn maybeRekeyInbound(self: *Self) void { /// Public: called by NetworkManager.processReceive() which decrypts via
/// transport.receive() directly (bypassing SecureConnection.receive()).
pub fn maybeRekeyInbound(self: *Self) void {
if (self.rekey_interval == 0) return; if (self.rekey_interval == 0) return;
self.messages_received_since_rekey += 1; self.messages_received_since_rekey += 1;
if (self.messages_received_since_rekey >= self.rekey_interval) { if (self.messages_received_since_rekey >= self.rekey_interval) {
@@ -378,15 +680,15 @@ pub const SecureConnection = struct {
/// Send raw data (unencrypted, for handshake) /// Send raw data (unencrypted, for handshake)
fn sendRaw(self: *Self, data: []const u8) Error!void { fn sendRaw(self: *Self, data: []const u8) Error!void {
var sent: usize = 0; var sent: usize = 0;
const deadline = std.time.nanoTimestamp() + HANDSHAKE_TIMEOUT_NS; const deadline = platform.time.nanoTimestamp() + HANDSHAKE_TIMEOUT_NS;
while (sent < data.len) { while (sent < data.len) {
const bytes = self.socket.send(data[sent..]) catch |err| { const bytes = self.io_transport.send(data[sent..]) catch |err| {
switch (err) { switch (err) {
CoreError.ConnectionTimeout => { CoreError.ConnectionTimeout => {
// WouldBlock - check absolute deadline // WouldBlock - check absolute deadline
if (std.time.nanoTimestamp() >= deadline) return Error.HandshakeTimeout; if (platform.time.nanoTimestamp() >= deadline) return Error.HandshakeTimeout;
std.Thread.sleep(10 * std.time.ns_per_ms); platform.time.sleep(100 * std.time.ns_per_us);
continue; continue;
}, },
else => return Error.SocketError, else => return Error.SocketError,
@@ -400,15 +702,15 @@ pub const SecureConnection = struct {
/// Returns actual bytes received /// Returns actual bytes received
fn receiveRaw(self: *Self, buffer: []u8, min_bytes: usize) Error!usize { fn receiveRaw(self: *Self, buffer: []u8, min_bytes: usize) Error!usize {
var received: usize = 0; var received: usize = 0;
const deadline = std.time.nanoTimestamp() + HANDSHAKE_TIMEOUT_NS; const deadline = platform.time.nanoTimestamp() + HANDSHAKE_TIMEOUT_NS;
while (received < min_bytes) { while (received < min_bytes) {
const bytes = self.socket.receive(buffer[received..]) catch |err| { const bytes = self.io_transport.receive(buffer[received..]) catch |err| {
switch (err) { switch (err) {
CoreError.ConnectionTimeout => { CoreError.ConnectionTimeout => {
// WouldBlock - check absolute deadline // WouldBlock - check absolute deadline
if (std.time.nanoTimestamp() >= deadline) return Error.HandshakeTimeout; if (platform.time.nanoTimestamp() >= deadline) return Error.HandshakeTimeout;
std.Thread.sleep(10 * std.time.ns_per_ms); platform.time.sleep(100 * std.time.ns_per_us);
continue; continue;
}, },
CoreError.ConnectionClosed => return Error.HandshakeFailed, CoreError.ConnectionClosed => return Error.HandshakeFailed,
@@ -432,7 +734,10 @@ test "SecureConnection init" {
// Just test initialization (can't test full handshake without network) // Just test initialization (can't test full handshake without network)
var socket: Socket = undefined; var socket: Socket = undefined;
const keypair = KeyPair.generate(); const keypair = KeyPair.generate();
const secure = SecureConnection.init(&socket, keypair, testing.allocator); // Allocate on heap because init uses self-referential pointer for io_transport
const secure = try testing.allocator.create(SecureConnection);
defer testing.allocator.destroy(secure);
secure.init(&socket, keypair, testing.allocator);
try testing.expect(!secure.isEncrypted()); try testing.expect(!secure.isEncrypted());
try testing.expect(secure.getRemotePublicKey() == null); try testing.expect(secure.getRemotePublicKey() == null);

View File

@@ -20,8 +20,13 @@
const std = @import("std"); const std = @import("std");
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
// Core components // Core components
const core = @import("core"); const core = @import("core");
const platform = @import("platform");
const platform_time = platform.time;
const Error = core.errors.Error; const Error = core.errors.Error;
const Address = core.Address; const Address = core.Address;
const Socket = core.Socket; const Socket = core.Socket;
@@ -31,6 +36,9 @@ const network = @import("network");
const PeerId = network.peer.PeerId; const PeerId = network.peer.PeerId;
const PeerConnection = network.PeerConnection; const PeerConnection = network.PeerConnection;
const SecureConnection = network.SecureConnection; const SecureConnection = network.SecureConnection;
const dos_protection = network.dos_protection;
const noise = @import("noise");
const NoiseKeyPair = noise.KeyPair;
// Protocol components // Protocol components
const protocol = @import("protocol"); const protocol = @import("protocol");
@@ -120,7 +128,7 @@ pub fn connectToPeerImpl(p2p: *P2P, address: Address) Error!PeerId {
delay_ms, delay_ms,
}); });
std.Thread.sleep(@as(u64, delay_ms) * std.time.ns_per_ms); platform.time.sleep(@as(u64, delay_ms) * std.time.ns_per_ms);
} }
} }
@@ -134,7 +142,7 @@ pub fn attemptConnectionInternalImpl(p2p: *P2P, address: Address) Error!PeerId {
errdefer socket.deinit(); errdefer socket.deinit();
// Measure connection time // Measure connection time
const start_time = std.time.milliTimestamp(); const start_time = platform_time.milliTimestamp();
// Actually connect // Actually connect
socket.connect(address) catch |err| { socket.connect(address) catch |err| {
@@ -197,7 +205,7 @@ pub fn attemptConnectionInternalImpl(p2p: *P2P, address: Address) Error!PeerId {
}; };
// Calculate latency // Calculate latency
const elapsed = std.time.milliTimestamp() - start_time; const elapsed = platform_time.milliTimestamp() - start_time;
const latency: u32 = if (elapsed < 0) 0 else if (elapsed > std.math.maxInt(u32)) std.math.maxInt(u32) else @intCast(elapsed); const latency: u32 = if (elapsed < 0) 0 else if (elapsed > std.math.maxInt(u32)) std.math.maxInt(u32) else @intCast(elapsed);
// Store socket // Store socket
@@ -221,7 +229,7 @@ pub fn attemptConnectionInternalImpl(p2p: *P2P, address: Address) Error!PeerId {
const sec = p2p.allocator.create(SecureConnection) catch return Error.OutOfMemory; const sec = p2p.allocator.create(SecureConnection) catch return Error.OutOfMemory;
errdefer p2p.allocator.destroy(sec); errdefer p2p.allocator.destroy(sec);
sec.* = SecureConnection.init(socket_ptr, kp, p2p.allocator); sec.init(socket_ptr, kp, p2p.allocator);
sec.initiateHandshake() catch |err| { sec.initiateHandshake() catch |err| {
std.log.err("Noise handshake failed: {}", .{err}); std.log.err("Noise handshake failed: {}", .{err});
@@ -474,7 +482,7 @@ pub fn acceptConnectionsImpl(p2p: *P2P) Error!void {
const sec = p2p.allocator.create(SecureConnection) catch return Error.OutOfMemory; const sec = p2p.allocator.create(SecureConnection) catch return Error.OutOfMemory;
errdefer p2p.allocator.destroy(sec); errdefer p2p.allocator.destroy(sec);
sec.* = SecureConnection.init(socket_ptr, kp, p2p.allocator); sec.init(socket_ptr, kp, p2p.allocator);
sec.acceptHandshake() catch |err| { sec.acceptHandshake() catch |err| {
std.log.err("Noise handshake failed on accept from {s}: {}", .{ ip_str, err }); std.log.err("Noise handshake failed on accept from {s}: {}", .{ ip_str, err });
@@ -599,7 +607,7 @@ pub fn startListeningImpl(p2p: *P2P, address: Address) Error!void {
try p2p.emitEvent(P2PEvent.create(.library_started, .library_started)); try p2p.emitEvent(P2PEvent.create(.library_started, .library_started));
} }
/// Get a peer socket by ID /// Get a peer socket by ID. Returns null for WebRTC-backed connections.
pub fn getPeerSocketImpl(p2p: *P2P, peer_id: PeerId) ?*Socket { pub fn getPeerSocketImpl(p2p: *P2P, peer_id: PeerId) ?*Socket {
p2p.peer_connections_mutex.lock(); p2p.peer_connections_mutex.lock();
defer p2p.peer_connections_mutex.unlock(); defer p2p.peer_connections_mutex.unlock();
@@ -637,13 +645,57 @@ pub fn addPeerConnectionSecureImpl(p2p: *P2P, peer_id: PeerId, socket: *Socket,
}; };
} }
/// Add a peer connection with a pre-built Transport (e.g. WebRTC DataChannel).
/// No socket is associated; socket-dependent features are skipped for this peer.
pub fn addPeerConnectionWithTransportImpl(p2p: *P2P, peer_id: PeerId, transport_handle: core.transport.Transport) Error!void {
p2p.peer_connections_mutex.lock();
defer p2p.peer_connections_mutex.unlock();
if (p2p.peer_connections.count() >= p2p.config.network.max_connections) {
std.log.err("Connection limit reached ({}/{}) - rejecting WebRTC connection", .{
p2p.peer_connections.count(),
p2p.config.network.max_connections,
});
return Error.ConnectionLimitExceeded;
}
const peer_conn = try PeerConnection.initWithTransport(p2p.allocator, transport_handle);
p2p.peer_connections.put(peer_id, peer_conn) catch {
peer_conn.deinit();
return Error.SystemError;
};
}
/// Add a peer connection with a pre-built Transport and Noise encryption (e.g. WebRTC + Noise).
/// The SecureConnection must already have completed its handshake.
pub fn addPeerConnectionWithTransportSecureImpl(p2p: *P2P, peer_id: PeerId, transport_handle: core.transport.Transport, secure: *SecureConnection) Error!void {
p2p.peer_connections_mutex.lock();
defer p2p.peer_connections_mutex.unlock();
if (p2p.peer_connections.count() >= p2p.config.network.max_connections) {
std.log.err("Connection limit reached ({}/{}) - rejecting WebRTC+Noise connection", .{
p2p.peer_connections.count(),
p2p.config.network.max_connections,
});
return Error.ConnectionLimitExceeded;
}
const peer_conn = try PeerConnection.initWithTransportSecure(p2p.allocator, transport_handle, secure);
p2p.peer_connections.put(peer_id, peer_conn) catch {
peer_conn.deinit();
return Error.SystemError;
};
}
/// Remove a peer connection (thread-safe) /// Remove a peer connection (thread-safe)
pub fn removePeerConnectionImpl(p2p: *P2P, peer_id: PeerId) ?*Socket { pub fn removePeerConnectionImpl(p2p: *P2P, peer_id: PeerId) ?*Socket {
p2p.peer_connections_mutex.lock(); p2p.peer_connections_mutex.lock();
defer p2p.peer_connections_mutex.unlock(); defer p2p.peer_connections_mutex.unlock();
if (p2p.peer_connections.fetchRemove(peer_id)) |kv| { if (p2p.peer_connections.fetchRemove(peer_id)) |kv| {
const peer_conn = kv.value; const peer_conn = kv.value;
const socket = peer_conn.socket; const socket = peer_conn.socket; // null for WebRTC connections
if (peer_conn.pending_send) |*ps| { if (peer_conn.pending_send) |*ps| {
ps.deinit(); ps.deinit();
} }
@@ -667,17 +719,15 @@ pub fn sendToPeerAtomicImpl(p2p: *P2P, peer_id: PeerId, data: []const u8) Error!
peer_conn.send_mutex.lock(); peer_conn.send_mutex.lock();
defer peer_conn.send_mutex.unlock(); defer peer_conn.send_mutex.unlock();
const socket = peer_conn.socket;
const max_retries: u32 = 1000; const max_retries: u32 = 1000;
const retry_delay_ns: u64 = 10 * std.time.ns_per_ms; const retry_delay_ns: u64 = 10 * std.time.ns_per_ms;
var sent: usize = 0; var sent: usize = 0;
var retries: u32 = 0; var retries: u32 = 0;
while (sent < data.len) { while (sent < data.len) {
const n = socket.send(data[sent..]) catch |err| { const n = peer_conn.transport_handle.send(data[sent..]) catch |err| {
if (err == Error.ConnectionTimeout and retries < max_retries) { if (err == Error.ConnectionTimeout and retries < max_retries) {
std.Thread.sleep(retry_delay_ns); platform.time.sleep(retry_delay_ns);
retries += 1; retries += 1;
continue; continue;
} }
@@ -779,19 +829,16 @@ pub fn sendSegmentsToPeerAtomicImpl(p2p: *P2P, peer_id: PeerId, segments: []cons
return true; // Queued successfully return true; // Queued successfully
} }
const socket = peer_conn.socket;
// First, check if there's already a pending send for this peer // First, check if there's already a pending send for this peer
if (peer_conn.pending_send) |*existing| { if (peer_conn.pending_send) |*existing| {
while (!existing.isComplete()) { while (!existing.isComplete()) {
const remaining = existing.remaining(); const remaining = existing.remaining();
const n = socket.send(remaining) catch |err| { const n = peer_conn.transport_handle.send(remaining) catch |err| {
if (err == Error.ConnectionTimeout) break; if (err == Error.ConnectionTimeout) break;
break; break;
}; };
if (n == 0) break; if (n == 0) break;
existing.offset += n; existing.offset += n;
socket.stats.recordSend(n);
} }
if (existing.isComplete()) { if (existing.isComplete()) {
@@ -844,15 +891,13 @@ pub fn sendSegmentsToPeerAtomicImpl(p2p: *P2P, peer_id: PeerId, segments: []cons
for (segments) |seg| { for (segments) |seg| {
var seg_sent: usize = 0; var seg_sent: usize = 0;
while (seg_sent < seg.len) { while (seg_sent < seg.len) {
const n = socket.send(seg[seg_sent..]) catch |err| { const n = peer_conn.transport_handle.send(seg[seg_sent..]) catch |err| {
if (err == Error.ConnectionTimeout) { if (err == Error.ConnectionTimeout) {
return savePartialSendToPeerImpl(p2p, peer_conn, segments, bytes_sent, seg_sent); return savePartialSendToPeerImpl(p2p, peer_conn, segments, bytes_sent, seg_sent);
} }
if (bytes_sent > 0 or seg_sent > 0) { if (bytes_sent > 0 or seg_sent > 0) {
std.log.err("FRAMING-CORRUPT: Send failed after {} bytes for peer {x}, disconnecting", .{ bytes_sent + seg_sent, peer_id.bytes[0..8].* }); std.log.err("FRAMING-CORRUPT: Send failed after {} bytes for peer {x}, disconnecting", .{ bytes_sent + seg_sent, peer_id.bytes[0..8].* });
socket.close() catch |close_err| { peer_conn.transport_handle.close();
std.log.debug("Socket close after framing corruption: {}", .{close_err});
};
} }
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic); _ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
return err; return err;
@@ -884,9 +929,7 @@ pub fn savePartialSendToPeerImpl(p2p: *P2P, peer_conn: *PeerConnection, segments
const new_size = old_remaining + remaining_size; const new_size = old_remaining + remaining_size;
const new_buffer = p2p.allocator.alloc(u8, new_size) catch { const new_buffer = p2p.allocator.alloc(u8, new_size) catch {
std.log.err("FRAMING-CORRUPT: OOM appending partial send, disconnecting", .{}); std.log.err("FRAMING-CORRUPT: OOM appending partial send, disconnecting", .{});
peer_conn.socket.close() catch |close_err| { peer_conn.transport_handle.close();
std.log.debug("Socket close during OOM handling: {}", .{close_err});
};
return Error.SystemError; return Error.SystemError;
}; };
@@ -914,9 +957,7 @@ pub fn savePartialSendToPeerImpl(p2p: *P2P, peer_conn: *PeerConnection, segments
const remaining_data = p2p.allocator.alloc(u8, remaining_size) catch { const remaining_data = p2p.allocator.alloc(u8, remaining_size) catch {
std.log.err("FRAMING-CORRUPT: OOM saving partial send, disconnecting", .{}); std.log.err("FRAMING-CORRUPT: OOM saving partial send, disconnecting", .{});
peer_conn.socket.close() catch |close_err| { peer_conn.transport_handle.close();
std.log.debug("Socket close during OOM handling: {}", .{close_err});
};
return Error.SystemError; return Error.SystemError;
}; };
@@ -1014,22 +1055,18 @@ pub fn drainPendingSendsImpl(p2p: *P2P) void {
}; };
} }
// Drain unencrypted pending_send // Drain unencrypted pending_send (via transport abstraction)
if (peer_conn.pending_send) |*pending| { if (peer_conn.pending_send) |*pending| {
const socket = peer_conn.socket;
while (!pending.isComplete()) { while (!pending.isComplete()) {
const remaining = pending.remaining(); const remaining = pending.remaining();
const n = socket.send(remaining) catch |err| { const n = peer_conn.transport_handle.send(remaining) catch |err| {
if (err == Error.ConnectionTimeout) { if (err == Error.ConnectionTimeout) {
break; break;
} }
std.log.err("FRAMING-CORRUPT: Drain failed, disconnecting peer", .{}); std.log.err("FRAMING-CORRUPT: Drain failed, disconnecting peer", .{});
pending.deinit(); pending.deinit();
peer_conn.pending_send = null; peer_conn.pending_send = null;
socket.close() catch |close_err| { peer_conn.transport_handle.close();
std.log.debug("Socket close during drain failure: {}", .{close_err});
};
break; break;
}; };
if (n == 0) { if (n == 0) {
@@ -1039,7 +1076,6 @@ pub fn drainPendingSendsImpl(p2p: *P2P) void {
break; break;
} }
pending.offset += n; pending.offset += n;
socket.stats.recordSend(n);
} }
if (pending.isComplete()) { if (pending.isComplete()) {
@@ -1049,3 +1085,515 @@ pub fn drainPendingSendsImpl(p2p: *P2P) void {
} }
} }
} }
// ============================================================================
// Non-blocking Connection State Machine
// ============================================================================
/// A connection that is being established asynchronously.
/// Progresses through: dos_exchange → noise_handshake → complete/failed.
/// The blocking TCP connect is done before creating this struct.
pub const PendingConnection = struct {
phase: Phase,
role: ConnectionRole,
socket: *Socket,
address: Address,
secure_conn: ?*SecureConnection,
allocator: std.mem.Allocator,
// DoS cookie exchange sub-state
dos_phase: DosPhase,
dos_buf: [1 + dos_protection.COOKIE_SIZE]u8,
dos_offset: usize,
dos_expected: usize,
// Timeout
deadline_ms: i64,
// IP string for inbound DoS (server generates cookie from client IP)
ip_str_buf: [64]u8,
ip_str_len: usize,
pub const Phase = enum {
dos_exchange,
noise_handshake,
complete,
failed,
};
pub const ConnectionRole = enum {
outbound, // client, initiator
inbound, // server, responder
};
pub const DosPhase = enum {
// Common
idle,
done,
// Outbound (client): read server flag → maybe read cookie → send response
reading_flag,
reading_cookie,
sending_response,
// Inbound (server): send challenge/no-challenge → maybe read response
sending_challenge,
reading_response,
};
pub fn deinit(self: *PendingConnection) void {
if (self.secure_conn) |sec| {
sec.cleanupHandshake();
self.allocator.destroy(sec);
self.secure_conn = null;
}
self.socket.deinit();
self.allocator.destroy(self.socket);
}
/// Check if this pending connection has timed out.
pub fn isTimedOut(self: *const PendingConnection) bool {
return platform_time.milliTimestamp() > self.deadline_ms;
}
};
/// Create and start a non-blocking outbound connection.
/// Does the TCP connect synchronously (fast), then enters async DoS/handshake.
pub fn startNonBlockingConnectImpl(p2p: *P2P, address: Address) Error!void {
// Create TCP socket and connect (blocking — TCP connect is milliseconds)
var socket = Socket.init(.tcp, p2p.allocator) catch return Error.SocketCreationFailed;
errdefer socket.deinit();
socket.connect(address) catch |err| {
try p2p.emitEvent(P2PEvent.create(.connection_failed, .{ .connection_failed = .{
.peer_id = PeerId.init(),
.err = err,
} }));
return err;
};
// Set non-blocking mode for async DoS exchange + handshake
socket.setNonBlocking(true) catch return Error.SocketError;
const socket_ptr = p2p.allocator.create(Socket) catch return Error.OutOfMemory;
errdefer {
socket_ptr.deinit();
p2p.allocator.destroy(socket_ptr);
}
socket_ptr.* = socket;
socket.fd = -1;
socket.state = .closed;
var pending = PendingConnection{
.phase = .dos_exchange,
.role = .outbound,
.socket = socket_ptr,
.address = address,
.secure_conn = null,
.allocator = p2p.allocator,
.dos_phase = if (p2p.dos_protection != null) .reading_flag else .done,
.dos_buf = undefined,
.dos_offset = 0,
.dos_expected = 1, // read 1-byte flag
.deadline_ms = platform_time.milliTimestamp() + 5000, // 5 second timeout
.ip_str_buf = undefined,
.ip_str_len = 0,
};
// Skip DoS exchange if no DoS protection configured
if (pending.dos_phase == .done) {
pending.phase = if (p2p.noise_enabled) .noise_handshake else .complete;
if (p2p.noise_enabled) {
startHandshakeForPending(p2p, &pending) catch |err| {
pending.deinit();
return err;
};
}
}
p2p.pending_connections_mutex.lock();
defer p2p.pending_connections_mutex.unlock();
p2p.pending_connections.append(p2p.allocator, pending) catch {
// Clean up on append failure — but careful: errdefer above handles socket
// Since we moved socket to pending, null out errdefer
return Error.OutOfMemory;
};
}
/// Start a non-blocking accept: takes an already-accepted socket and begins async DoS/handshake.
pub fn startNonBlockingAcceptImpl(p2p: *P2P, accepted: *Socket, peer_addr: Address) void {
accepted.setNonBlocking(true) catch {
accepted.deinit();
p2p.allocator.destroy(accepted);
return;
};
// Extract IP for DoS protection
var ip_str_buf: [64]u8 = undefined;
var ip_str_len: usize = 0;
const ip_bytes = peer_addr.data.ipv4.bytes;
if (std.fmt.bufPrint(&ip_str_buf, "{}.{}.{}.{}", .{
ip_bytes[0], ip_bytes[1], ip_bytes[2], ip_bytes[3],
})) |ip_str| {
ip_str_len = ip_str.len;
} else |_| {}
// Determine initial DoS phase for inbound
var dos_phase: PendingConnection.DosPhase = .done;
var dos_buf: [1 + dos_protection.COOKIE_SIZE]u8 = undefined;
var dos_expected: usize = 0;
if (p2p.dos_protection) |dos| {
dos.recordConnection();
if (dos.isUnderLoad()) {
// Generate cookie challenge
const cookie = dos.generateCookie(ip_str_buf[0..ip_str_len]);
dos_buf[0] = 0x01;
@memcpy(dos_buf[1..][0..dos_protection.COOKIE_SIZE], &cookie);
dos_expected = 1 + dos_protection.COOKIE_SIZE; // send challenge
dos_phase = .sending_challenge;
} else {
// Send no-challenge flag
dos_buf[0] = 0x00;
dos_expected = 1;
dos_phase = .sending_challenge;
}
}
var pending = PendingConnection{
.phase = .dos_exchange,
.role = .inbound,
.socket = accepted,
.address = peer_addr,
.secure_conn = null,
.allocator = p2p.allocator,
.dos_phase = dos_phase,
.dos_buf = dos_buf,
.dos_offset = 0,
.dos_expected = dos_expected,
.deadline_ms = platform_time.milliTimestamp() + 5000,
.ip_str_buf = ip_str_buf,
.ip_str_len = ip_str_len,
};
// Skip DoS if no protection configured
if (pending.dos_phase == .done) {
pending.phase = if (p2p.noise_enabled) .noise_handshake else .complete;
if (p2p.noise_enabled) {
startHandshakeForPending(p2p, &pending) catch {
pending.deinit();
return;
};
}
}
p2p.pending_connections_mutex.lock();
defer p2p.pending_connections_mutex.unlock();
p2p.pending_connections.append(p2p.allocator, pending) catch {
pending.deinit();
};
}
/// Initialize a SecureConnection and start the non-blocking Noise handshake.
fn startHandshakeForPending(p2p: *P2P, pending: *PendingConnection) Error!void {
const kp = p2p.noise_keypair orelse {
pending.phase = .complete; // no encryption, promote directly
return;
};
const sec = p2p.allocator.create(SecureConnection) catch return Error.OutOfMemory;
sec.init(pending.socket, kp, p2p.allocator);
const role: noise.Role = if (pending.role == .outbound) .initiator else .responder;
sec.startHandshake(role) catch {
p2p.allocator.destroy(sec);
return Error.EncryptionFailed;
};
pending.secure_conn = sec;
}
/// Advance all pending connections. Called from the update loop.
/// Promotes completed connections to peer_connections and cleans up failed ones.
pub fn advancePendingConnectionsImpl(p2p: *P2P) void {
p2p.pending_connections_mutex.lock();
defer p2p.pending_connections_mutex.unlock();
var i: usize = 0;
while (i < p2p.pending_connections.items.len) {
var pending = &p2p.pending_connections.items[i];
// Check timeout
if (pending.isTimedOut()) {
std.log.warn("Pending connection to port {} timed out", .{pending.address.port});
pending.deinit();
_ = p2p.pending_connections.orderedRemove(i);
continue;
}
const result = advanceSinglePending(p2p, pending);
switch (result) {
.in_progress => {
i += 1; // keep in list
},
.completed => {
// Promote to full PeerConnection
promotePendingConnection(p2p, pending);
_ = p2p.pending_connections.orderedRemove(i);
},
.failed => {
std.log.warn("Pending connection to port {} failed", .{pending.address.port});
pending.deinit();
_ = p2p.pending_connections.orderedRemove(i);
},
}
}
}
const AdvanceResult = enum { in_progress, completed, failed };
/// Advance one pending connection by one step.
fn advanceSinglePending(p2p: *P2P, pending: *PendingConnection) AdvanceResult {
switch (pending.phase) {
.dos_exchange => return advanceDoSExchange(p2p, pending),
.noise_handshake => return advanceNoiseHandshake(p2p, pending),
.complete => return .completed,
.failed => return .failed,
}
}
/// Advance the DoS cookie exchange sub-state machine.
fn advanceDoSExchange(p2p: *P2P, pending: *PendingConnection) AdvanceResult {
switch (pending.role) {
.outbound => return advanceDoSOutbound(p2p, pending),
.inbound => return advanceDoSInbound(p2p, pending),
}
}
/// Outbound DoS: read flag → maybe read cookie → send response
fn advanceDoSOutbound(p2p: *P2P, pending: *PendingConnection) AdvanceResult {
switch (pending.dos_phase) {
.reading_flag => {
var flag_buf: [1]u8 = undefined;
const n = pending.socket.receive(&flag_buf) catch |err| {
if (err == Error.ConnectionTimeout) return .in_progress; // WouldBlock
return .failed;
};
if (n == 0) return .failed; // connection closed
if (flag_buf[0] == 0x01) {
// Server sent cookie challenge, read COOKIE_SIZE bytes
pending.dos_phase = .reading_cookie;
pending.dos_offset = 0;
pending.dos_expected = dos_protection.COOKIE_SIZE;
} else if (flag_buf[0] == 0x00) {
// No challenge
pending.dos_phase = .done;
} else {
return .failed; // invalid flag
}
return .in_progress;
},
.reading_cookie => {
const remaining = pending.dos_expected - pending.dos_offset;
const n = pending.socket.receive(pending.dos_buf[pending.dos_offset..][0..remaining]) catch |err| {
if (err == Error.ConnectionTimeout) return .in_progress;
return .failed;
};
if (n == 0) return .failed;
pending.dos_offset += n;
if (pending.dos_offset >= pending.dos_expected) {
// Prepare response: 0x02 + cookie
var response: [1 + dos_protection.COOKIE_SIZE]u8 = undefined;
response[0] = 0x02;
@memcpy(response[1..], pending.dos_buf[0..dos_protection.COOKIE_SIZE]);
// Reuse dos_buf for sending
pending.dos_buf = response;
pending.dos_offset = 0;
pending.dos_expected = 1 + dos_protection.COOKIE_SIZE;
pending.dos_phase = .sending_response;
}
return .in_progress;
},
.sending_response => {
const remaining = pending.dos_expected - pending.dos_offset;
const n = pending.socket.send(pending.dos_buf[pending.dos_offset..][0..remaining]) catch |err| {
if (err == Error.ConnectionTimeout) return .in_progress;
return .failed;
};
pending.dos_offset += n;
if (pending.dos_offset >= pending.dos_expected) {
pending.dos_phase = .done;
}
return .in_progress;
},
.done => {
// Transition to next phase
if (p2p.noise_enabled) {
pending.phase = .noise_handshake;
startHandshakeForPending(p2p, pending) catch return .failed;
} else {
pending.phase = .complete;
return .completed;
}
return .in_progress;
},
else => return .failed,
}
}
/// Inbound DoS: send challenge/no-challenge → maybe read response
fn advanceDoSInbound(p2p: *P2P, pending: *PendingConnection) AdvanceResult {
switch (pending.dos_phase) {
.sending_challenge => {
const remaining = pending.dos_expected - pending.dos_offset;
const n = pending.socket.send(pending.dos_buf[pending.dos_offset..][0..remaining]) catch |err| {
if (err == Error.ConnectionTimeout) return .in_progress;
return .failed;
};
pending.dos_offset += n;
if (pending.dos_offset >= pending.dos_expected) {
if (pending.dos_buf[0] == 0x01) {
// Sent challenge, now read response
pending.dos_phase = .reading_response;
pending.dos_offset = 0;
pending.dos_expected = 1 + dos_protection.COOKIE_SIZE;
} else {
// Sent no-challenge flag, done
pending.dos_phase = .done;
}
}
return .in_progress;
},
.reading_response => {
const remaining = pending.dos_expected - pending.dos_offset;
const n = pending.socket.receive(pending.dos_buf[pending.dos_offset..][0..remaining]) catch |err| {
if (err == Error.ConnectionTimeout) return .in_progress;
return .failed;
};
if (n == 0) return .failed;
pending.dos_offset += n;
if (pending.dos_offset >= pending.dos_expected) {
// Verify response
if (pending.dos_buf[0] != 0x02) return .failed;
if (p2p.dos_protection) |dos| {
var cookie: [dos_protection.COOKIE_SIZE]u8 = undefined;
@memcpy(&cookie, pending.dos_buf[1..][0..dos_protection.COOKIE_SIZE]);
if (!dos.verifyCookie(pending.ip_str_buf[0..pending.ip_str_len], cookie)) {
return .failed;
}
}
pending.dos_phase = .done;
}
return .in_progress;
},
.done => {
if (p2p.noise_enabled) {
pending.phase = .noise_handshake;
startHandshakeForPending(p2p, pending) catch return .failed;
} else {
pending.phase = .complete;
return .completed;
}
return .in_progress;
},
else => return .failed,
}
}
/// Advance Noise handshake using the existing non-blocking state machine.
fn advanceNoiseHandshake(p2p: *P2P, pending: *PendingConnection) AdvanceResult {
_ = p2p;
const sec = pending.secure_conn orelse {
pending.phase = .complete;
return .completed;
};
const advance_result = sec.advanceHandshake() catch {
pending.phase = .failed;
return .failed;
};
switch (advance_result) {
.progress => return .in_progress,
.would_block => return .in_progress,
.complete => {
// Set short send timeout for async sends
pending.socket.setSendTimeout(1) catch {};
pending.phase = .complete;
return .completed;
},
}
}
/// Promote a completed PendingConnection into a full peer connection.
fn promotePendingConnection(p2p: *P2P, pending: *PendingConnection) void {
const secure_conn = pending.secure_conn;
var peer_id: PeerId = PeerId.init();
if (secure_conn) |sec| {
if (sec.getRemotePublicKey()) |remote_key| {
peer_id = PeerId.fromNoisePublicKey(remote_key);
// Verify key pinning
if (p2p.key_pin_store) |kps| {
const verify_result = kps.verifyPeerKey(peer_id.bytes, remote_key) catch {
std.log.err("Key pinning verification failed for pending connection", .{});
pending.deinit();
return;
};
switch (verify_result) {
.verified, .first_use => {},
.key_changed, .unknown_peer => {
std.log.warn("SECURITY: Key pinning rejected pending connection", .{});
pending.deinit();
return;
},
}
}
}
}
// Add to peer manager
if (p2p.peer_manager) |pm| {
_ = pm.addPeerWithId(pending.address, peer_id) catch {};
}
// Transfer ownership: prevent pending.deinit from cleaning up what we promote
const socket_ptr = pending.socket;
const sec_ptr = pending.secure_conn;
pending.secure_conn = null; // prevent double-free
addPeerConnectionSecureImpl(p2p, peer_id, socket_ptr, sec_ptr) catch |err| {
std.log.warn("Failed to add pending connection as peer: {}", .{err});
if (sec_ptr) |sec| p2p.allocator.destroy(sec);
socket_ptr.deinit();
p2p.allocator.destroy(socket_ptr);
return;
};
// Invalidate the socket pointer in pending so deinit doesn't double-free
// (orderedRemove will drop the pending struct without calling deinit)
_ = p2p.stats.active_connections.fetchAdd(1, .monotonic);
_ = p2p.stats.total_connections.fetchAdd(1, .monotonic);
if (pending.role == .outbound) {
p2p.emitEvent(P2PEvent.create(.connection_established, .{ .connection_established = .{
.peer_id = peer_id,
.latency = 0,
} })) catch {};
} else {
p2p.emitEvent(P2PEvent.create(.peer_connected, .{ .peer_connected = .{
.peer_id = peer_id,
.address = pending.address,
} })) catch {};
}
// Send bitfield
if (p2p.file_manager) |fm| {
fm.sendBitfieldToNewPeer(peer_id.bytes) catch {};
}
}

View File

@@ -84,7 +84,8 @@ test "noise: SecureConnection init without handshake is not encrypted" {
// Just test initialization (can't test full handshake without network) // Just test initialization (can't test full handshake without network)
var socket: core.socket.Socket = undefined; var socket: core.socket.Socket = undefined;
const keypair = KeyPair.generate(); const keypair = KeyPair.generate();
const secure = SecureConnection.init(&socket, keypair, allocator); var secure: SecureConnection = undefined;
secure.init(&socket, keypair, allocator);
try testing.expect(!secure.isEncrypted()); try testing.expect(!secure.isEncrypted());
try testing.expect(secure.getRemotePublicKey() == null); try testing.expect(secure.getRemotePublicKey() == null);

View File

@@ -42,7 +42,8 @@ test "SecureConnection: NotEncrypted error when sending before handshake" {
defer socket.deinit(); defer socket.deinit();
const keypair = KeyPair.generate(); const keypair = KeyPair.generate();
var secure = SecureConnection.init(&socket, keypair, allocator); var secure: SecureConnection = undefined;
secure.init(&socket, keypair, allocator);
// Verify not encrypted // Verify not encrypted
try testing.expect(!secure.isEncrypted()); try testing.expect(!secure.isEncrypted());
@@ -59,7 +60,8 @@ test "SecureConnection: NotEncrypted error when receiving before handshake" {
defer socket.deinit(); defer socket.deinit();
const keypair = KeyPair.generate(); const keypair = KeyPair.generate();
var secure = SecureConnection.init(&socket, keypair, allocator); var secure: SecureConnection = undefined;
secure.init(&socket, keypair, allocator);
// Attempt to receive should return NotEncrypted error // Attempt to receive should return NotEncrypted error
var buf: [1024]u8 = undefined; var buf: [1024]u8 = undefined;
@@ -82,24 +84,26 @@ test "SecureConnection: initial state is not encrypted" {
defer socket.deinit(); defer socket.deinit();
const keypair = KeyPair.generate(); const keypair = KeyPair.generate();
const secure = SecureConnection.init(&socket, keypair, allocator); var secure: SecureConnection = undefined;
secure.init(&socket, keypair, allocator);
try testing.expect(!secure.isEncrypted()); try testing.expect(!secure.isEncrypted());
try testing.expect(secure.getRemotePublicKey() == null); try testing.expect(secure.getRemotePublicKey() == null);
try testing.expect(secure.getHandshakeHash() == null); try testing.expect(secure.getHandshakeHash() == null);
} }
test "SecureConnection: getSocket returns underlying socket" { test "SecureConnection: socket field accessible after init" {
const allocator = testing.allocator; const allocator = testing.allocator;
var socket = try Socket.init(.tcp, allocator); var socket = try Socket.init(.tcp, allocator);
defer socket.deinit(); defer socket.deinit();
const keypair = KeyPair.generate(); const keypair = KeyPair.generate();
var secure = SecureConnection.init(&socket, keypair, allocator); var secure: SecureConnection = undefined;
secure.init(&socket, keypair, allocator);
// getSocket should return pointer to the same socket // socket field should point to the same socket
try testing.expect(secure.getSocket() == &socket); try testing.expect(secure.socket == &socket);
} }
// ============================================================================ // ============================================================================
@@ -150,7 +154,8 @@ test "SecureConnection: full handshake between initiator and responder" {
defer client_conn.deinit(); defer client_conn.deinit();
// Create secure connection and perform handshake as responder // Create secure connection and perform handshake as responder
var secure = SecureConnection.init(&client_conn, srv_keypair, alloc); var secure: SecureConnection = undefined;
secure.init(&client_conn, srv_keypair, alloc);
secure.acceptHandshake() catch |e| { secure.acceptHandshake() catch |e| {
srv_error.* = e; srv_error.* = e;
@@ -182,7 +187,8 @@ test "SecureConnection: full handshake between initiator and responder" {
const connect_addr = Address.ipv4(.{ 127, 0, 0, 1 }, server_port); const connect_addr = Address.ipv4(.{ 127, 0, 0, 1 }, server_port);
try client_socket.connect(connect_addr); try client_socket.connect(connect_addr);
var client_secure = SecureConnection.init(&client_socket, client_keypair, allocator); var client_secure: SecureConnection = undefined;
client_secure.init(&client_socket, client_keypair, allocator);
client_secure.initiateHandshake() catch |e| { client_secure.initiateHandshake() catch |e| {
client_error = e; client_error = e;
@@ -254,7 +260,8 @@ test "SecureConnection: encrypted message round-trip" {
}; };
defer client_conn.deinit(); defer client_conn.deinit();
var secure = SecureConnection.init(&client_conn, srv_keypair, alloc); var secure: SecureConnection = undefined;
secure.init(&client_conn, srv_keypair, alloc);
secure.acceptHandshake() catch |e| { secure.acceptHandshake() catch |e| {
srv_error.* = e; srv_error.* = e;
@@ -278,7 +285,8 @@ test "SecureConnection: encrypted message round-trip" {
const connect_addr = Address.ipv4(.{ 127, 0, 0, 1 }, server_port); const connect_addr = Address.ipv4(.{ 127, 0, 0, 1 }, server_port);
try client_socket.connect(connect_addr); try client_socket.connect(connect_addr);
var client_secure = SecureConnection.init(&client_socket, client_keypair, allocator); var client_secure: SecureConnection = undefined;
client_secure.init(&client_socket, client_keypair, allocator);
try client_secure.initiateHandshake(); try client_secure.initiateHandshake();
// Send encrypted message // Send encrypted message
@@ -335,7 +343,8 @@ test "SecureConnection: bidirectional encrypted communication" {
}; };
defer client_conn.deinit(); defer client_conn.deinit();
var secure = SecureConnection.init(&client_conn, srv_keypair, alloc); var secure: SecureConnection = undefined;
secure.init(&client_conn, srv_keypair, alloc);
secure.acceptHandshake() catch |e| { secure.acceptHandshake() catch |e| {
srv_error.* = e; srv_error.* = e;
@@ -364,7 +373,8 @@ test "SecureConnection: bidirectional encrypted communication" {
const connect_addr = Address.ipv4(.{ 127, 0, 0, 1 }, server_port); const connect_addr = Address.ipv4(.{ 127, 0, 0, 1 }, server_port);
try client_socket.connect(connect_addr); try client_socket.connect(connect_addr);
var client_secure = SecureConnection.init(&client_socket, client_keypair, allocator); var client_secure: SecureConnection = undefined;
client_secure.init(&client_socket, client_keypair, allocator);
try client_secure.initiateHandshake(); try client_secure.initiateHandshake();
// Send message to server // Send message to server
@@ -418,7 +428,8 @@ test "SecureConnection: rekey maintains communication" {
}; };
defer client_conn.deinit(); defer client_conn.deinit();
var secure = SecureConnection.init(&client_conn, srv_keypair, alloc); var secure: SecureConnection = undefined;
secure.init(&client_conn, srv_keypair, alloc);
secure.acceptHandshake() catch |e| { secure.acceptHandshake() catch |e| {
srv_error.* = e; srv_error.* = e;
@@ -450,7 +461,8 @@ test "SecureConnection: rekey maintains communication" {
const connect_addr = Address.ipv4(.{ 127, 0, 0, 1 }, server_port); const connect_addr = Address.ipv4(.{ 127, 0, 0, 1 }, server_port);
try client_socket.connect(connect_addr); try client_socket.connect(connect_addr);
var client_secure = SecureConnection.init(&client_socket, client_keypair, allocator); var client_secure: SecureConnection = undefined;
client_secure.init(&client_socket, client_keypair, allocator);
try client_secure.initiateHandshake(); try client_secure.initiateHandshake();
// Send message before rekey // Send message before rekey
@@ -506,7 +518,8 @@ test "SecureConnection: handshake hash is consistent" {
}; };
defer client_conn.deinit(); defer client_conn.deinit();
var secure = SecureConnection.init(&client_conn, srv_keypair, alloc); var secure: SecureConnection = undefined;
secure.init(&client_conn, srv_keypair, alloc);
secure.acceptHandshake() catch |e| { secure.acceptHandshake() catch |e| {
srv_error.* = e; srv_error.* = e;
@@ -524,7 +537,8 @@ test "SecureConnection: handshake hash is consistent" {
const connect_addr = Address.ipv4(.{ 127, 0, 0, 1 }, server_port); const connect_addr = Address.ipv4(.{ 127, 0, 0, 1 }, server_port);
try client_socket.connect(connect_addr); try client_socket.connect(connect_addr);
var client_secure = SecureConnection.init(&client_socket, client_keypair, allocator); var client_secure: SecureConnection = undefined;
client_secure.init(&client_socket, client_keypair, allocator);
try client_secure.initiateHandshake(); try client_secure.initiateHandshake();
const client_handshake_hash = client_secure.getHandshakeHash(); const client_handshake_hash = client_secure.getHandshakeHash();
@@ -580,7 +594,8 @@ test "SecureConnection: multiple messages in sequence" {
}; };
defer client_conn.deinit(); defer client_conn.deinit();
var secure = SecureConnection.init(&client_conn, srv_keypair, alloc); var secure: SecureConnection = undefined;
secure.init(&client_conn, srv_keypair, alloc);
secure.acceptHandshake() catch |e| { secure.acceptHandshake() catch |e| {
srv_error.* = e; srv_error.* = e;
@@ -614,7 +629,8 @@ test "SecureConnection: multiple messages in sequence" {
const connect_addr = Address.ipv4(.{ 127, 0, 0, 1 }, server_port); const connect_addr = Address.ipv4(.{ 127, 0, 0, 1 }, server_port);
try client_socket.connect(connect_addr); try client_socket.connect(connect_addr);
var client_secure = SecureConnection.init(&client_socket, client_keypair, allocator); var client_secure: SecureConnection = undefined;
client_secure.init(&client_socket, client_keypair, allocator);
try client_secure.initiateHandshake(); try client_secure.initiateHandshake();
// Send multiple messages // Send multiple messages