feat: add non-blocking Noise handshake, SecureConnection transport
refactor
This commit is contained in:
@@ -20,8 +20,13 @@
|
||||
|
||||
const std = @import("std");
|
||||
|
||||
const builtin = @import("builtin");
|
||||
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
|
||||
|
||||
// Core components
|
||||
const core = @import("core");
|
||||
const platform = @import("platform");
|
||||
const platform_time = platform.time;
|
||||
const Error = core.errors.Error;
|
||||
const Address = core.Address;
|
||||
const Socket = core.Socket;
|
||||
@@ -31,6 +36,9 @@ const network = @import("network");
|
||||
const PeerId = network.peer.PeerId;
|
||||
const PeerConnection = network.PeerConnection;
|
||||
const SecureConnection = network.SecureConnection;
|
||||
const dos_protection = network.dos_protection;
|
||||
const noise = @import("noise");
|
||||
const NoiseKeyPair = noise.KeyPair;
|
||||
|
||||
// Protocol components
|
||||
const protocol = @import("protocol");
|
||||
@@ -120,7 +128,7 @@ pub fn connectToPeerImpl(p2p: *P2P, address: Address) Error!PeerId {
|
||||
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();
|
||||
|
||||
// Measure connection time
|
||||
const start_time = std.time.milliTimestamp();
|
||||
const start_time = platform_time.milliTimestamp();
|
||||
|
||||
// Actually connect
|
||||
socket.connect(address) catch |err| {
|
||||
@@ -197,7 +205,7 @@ pub fn attemptConnectionInternalImpl(p2p: *P2P, address: Address) Error!PeerId {
|
||||
};
|
||||
|
||||
// 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);
|
||||
|
||||
// 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;
|
||||
errdefer p2p.allocator.destroy(sec);
|
||||
|
||||
sec.* = SecureConnection.init(socket_ptr, kp, p2p.allocator);
|
||||
sec.init(socket_ptr, kp, p2p.allocator);
|
||||
|
||||
sec.initiateHandshake() catch |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;
|
||||
errdefer p2p.allocator.destroy(sec);
|
||||
|
||||
sec.* = SecureConnection.init(socket_ptr, kp, p2p.allocator);
|
||||
sec.init(socket_ptr, kp, p2p.allocator);
|
||||
|
||||
sec.acceptHandshake() catch |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));
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
p2p.peer_connections_mutex.lock();
|
||||
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)
|
||||
pub fn removePeerConnectionImpl(p2p: *P2P, peer_id: PeerId) ?*Socket {
|
||||
p2p.peer_connections_mutex.lock();
|
||||
defer p2p.peer_connections_mutex.unlock();
|
||||
if (p2p.peer_connections.fetchRemove(peer_id)) |kv| {
|
||||
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| {
|
||||
ps.deinit();
|
||||
}
|
||||
@@ -667,17 +719,15 @@ pub fn sendToPeerAtomicImpl(p2p: *P2P, peer_id: PeerId, data: []const u8) Error!
|
||||
peer_conn.send_mutex.lock();
|
||||
defer peer_conn.send_mutex.unlock();
|
||||
|
||||
const socket = peer_conn.socket;
|
||||
|
||||
const max_retries: u32 = 1000;
|
||||
const retry_delay_ns: u64 = 10 * std.time.ns_per_ms;
|
||||
|
||||
var sent: usize = 0;
|
||||
var retries: u32 = 0;
|
||||
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) {
|
||||
std.Thread.sleep(retry_delay_ns);
|
||||
platform.time.sleep(retry_delay_ns);
|
||||
retries += 1;
|
||||
continue;
|
||||
}
|
||||
@@ -779,19 +829,16 @@ pub fn sendSegmentsToPeerAtomicImpl(p2p: *P2P, peer_id: PeerId, segments: []cons
|
||||
return true; // Queued successfully
|
||||
}
|
||||
|
||||
const socket = peer_conn.socket;
|
||||
|
||||
// First, check if there's already a pending send for this peer
|
||||
if (peer_conn.pending_send) |*existing| {
|
||||
while (!existing.isComplete()) {
|
||||
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;
|
||||
break;
|
||||
};
|
||||
if (n == 0) break;
|
||||
existing.offset += n;
|
||||
socket.stats.recordSend(n);
|
||||
}
|
||||
|
||||
if (existing.isComplete()) {
|
||||
@@ -844,15 +891,13 @@ pub fn sendSegmentsToPeerAtomicImpl(p2p: *P2P, peer_id: PeerId, segments: []cons
|
||||
for (segments) |seg| {
|
||||
var seg_sent: usize = 0;
|
||||
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) {
|
||||
return savePartialSendToPeerImpl(p2p, peer_conn, segments, bytes_sent, seg_sent);
|
||||
}
|
||||
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].* });
|
||||
socket.close() catch |close_err| {
|
||||
std.log.debug("Socket close after framing corruption: {}", .{close_err});
|
||||
};
|
||||
peer_conn.transport_handle.close();
|
||||
}
|
||||
_ = p2p.stats.errors_total.fetchAdd(1, .monotonic);
|
||||
return err;
|
||||
@@ -884,9 +929,7 @@ pub fn savePartialSendToPeerImpl(p2p: *P2P, peer_conn: *PeerConnection, segments
|
||||
const new_size = old_remaining + remaining_size;
|
||||
const new_buffer = p2p.allocator.alloc(u8, new_size) catch {
|
||||
std.log.err("FRAMING-CORRUPT: OOM appending partial send, disconnecting", .{});
|
||||
peer_conn.socket.close() catch |close_err| {
|
||||
std.log.debug("Socket close during OOM handling: {}", .{close_err});
|
||||
};
|
||||
peer_conn.transport_handle.close();
|
||||
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 {
|
||||
std.log.err("FRAMING-CORRUPT: OOM saving partial send, disconnecting", .{});
|
||||
peer_conn.socket.close() catch |close_err| {
|
||||
std.log.debug("Socket close during OOM handling: {}", .{close_err});
|
||||
};
|
||||
peer_conn.transport_handle.close();
|
||||
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| {
|
||||
const socket = peer_conn.socket;
|
||||
|
||||
while (!pending.isComplete()) {
|
||||
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) {
|
||||
break;
|
||||
}
|
||||
std.log.err("FRAMING-CORRUPT: Drain failed, disconnecting peer", .{});
|
||||
pending.deinit();
|
||||
peer_conn.pending_send = null;
|
||||
socket.close() catch |close_err| {
|
||||
std.log.debug("Socket close during drain failure: {}", .{close_err});
|
||||
};
|
||||
peer_conn.transport_handle.close();
|
||||
break;
|
||||
};
|
||||
if (n == 0) {
|
||||
@@ -1039,7 +1076,6 @@ pub fn drainPendingSendsImpl(p2p: *P2P) void {
|
||||
break;
|
||||
}
|
||||
pending.offset += n;
|
||||
socket.stats.recordSend(n);
|
||||
}
|
||||
|
||||
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 {};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user