webrtc-transport #6

Open
mdt wants to merge 13 commits from webrtc-transport into main
76 changed files with 5088 additions and 1374 deletions
Showing only changes of commit 3da00503a2 - Show all commits

View File

@@ -3,9 +3,13 @@
//! Handles the actual NAT traversal via simultaneous connection attempts. //! Handles the actual NAT traversal via simultaneous connection attempts.
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;
const platform = @import("platform");
const platform_time = platform.time;
const types = @import("types.zig"); const types = @import("types.zig");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const os = std.os; const os = if (!is_wasm) std.os else struct {};
const Address = types.Address; const Address = types.Address;
const HolePunchPacket = types.HolePunchPacket; const HolePunchPacket = types.HolePunchPacket;
@@ -16,7 +20,24 @@ const HolePunchError = types.HolePunchError;
const Defaults = types.Defaults; const Defaults = types.Defaults;
/// Socket wrapper for cross-platform UDP /// Socket wrapper for cross-platform UDP
pub const UdpSocket = struct { pub const UdpSocket = if (is_wasm) struct {
fd: u32 = 0,
bound_address: ?Address = null,
pub fn init() !UdpSocket {
return error.OperationNotSupported;
}
pub fn deinit(_: *UdpSocket) void {}
pub fn bind(_: *UdpSocket, _: u16) !void {
return error.OperationNotSupported;
}
pub fn sendTo(_: *UdpSocket, _: Address, _: []const u8) !void {
return error.OperationNotSupported;
}
pub fn recvFrom(_: *UdpSocket, _: []u8) !struct { len: usize, addr: Address } {
return error.OperationNotSupported;
}
} else struct {
fd: std.posix.socket_t, fd: std.posix.socket_t,
bound_address: ?Address, bound_address: ?Address,
@@ -148,24 +169,24 @@ pub const HolePunchEngine = struct {
options: types.ConnectOptions, options: types.ConnectOptions,
) ConnectionResult { ) ConnectionResult {
self.stats.attempts += 1; self.stats.attempts += 1;
const start_time = std.time.milliTimestamp(); const start_time = platform_time.milliTimestamp();
// Wait until rendezvous time // Wait until rendezvous time
const now = std.time.milliTimestamp(); const now = platform_time.milliTimestamp();
if (params.rendezvous_time > now) { if (params.rendezvous_time > now) {
const wait_ns = @as(u64, @intCast(params.rendezvous_time - now)) * std.time.ns_per_ms; const wait_ns = @as(u64, @intCast(params.rendezvous_time - now)) * std.time.ns_per_ms;
if (options.send_keepalives) { if (options.send_keepalives) {
self.waitWithKeepalives(target_addresses, wait_ns) catch {}; self.waitWithKeepalives(target_addresses, wait_ns) catch {};
} else { } else {
std.Thread.sleep(wait_ns); platform.time.sleep(wait_ns);
} }
} }
// Try with retries // Try with retries
for (Defaults.retry_intervals) |delay| { for (Defaults.retry_intervals) |delay| {
if (delay > 0) { if (delay > 0) {
std.Thread.sleep(delay * std.time.ns_per_ms); platform.time.sleep(delay * std.time.ns_per_ms);
} }
const result = self.singleAttempt(target_addresses, params, options); const result = self.singleAttempt(target_addresses, params, options);
@@ -173,7 +194,7 @@ pub const HolePunchEngine = struct {
switch (result) { switch (result) {
.success => |info| { .success => |info| {
self.stats.successes += 1; self.stats.successes += 1;
const elapsed = @as(u64, @intCast(std.time.milliTimestamp() - start_time)); const elapsed = @as(u64, @intCast(platform_time.milliTimestamp() - start_time));
self.updateAvgTime(elapsed); self.updateAvgTime(elapsed);
return .{ .success = info }; return .{ .success = info };
}, },
@@ -254,10 +275,10 @@ pub const HolePunchEngine = struct {
} }
// Wait for responses // Wait for responses
const deadline = std.time.milliTimestamp() + @as(i64, @intCast(Defaults.hole_punch_timeout_ms)); const deadline = platform_time.milliTimestamp() + @as(i64, @intCast(Defaults.hole_punch_timeout_ms));
var recv_buf: [256]u8 = undefined; var recv_buf: [256]u8 = undefined;
while (std.time.milliTimestamp() < deadline) { while (platform_time.milliTimestamp() < deadline) {
for (contexts.items) |*ctx| { for (contexts.items) |*ctx| {
const result = ctx.socket.recvFrom(&recv_buf) catch |err| { const result = ctx.socket.recvFrom(&recv_buf) catch |err| {
if (err == error.WouldBlock) continue; if (err == error.WouldBlock) continue;
@@ -280,7 +301,7 @@ pub const HolePunchEngine = struct {
} }
// Success! // Success!
const elapsed = @as(u64, @intCast(std.time.milliTimestamp() - const elapsed = @as(u64, @intCast(platform_time.milliTimestamp() -
(params.rendezvous_time - Defaults.rendezvous_buffer_ms))); (params.rendezvous_time - Defaults.rendezvous_buffer_ms)));
return .{ return .{
@@ -296,7 +317,7 @@ pub const HolePunchEngine = struct {
} }
// Small sleep to avoid busy loop // Small sleep to avoid busy loop
std.Thread.sleep(1 * std.time.ns_per_ms); platform.time.sleep(1 * std.time.ns_per_ms);
} }
return .{ .hole_punch_failed = .timeout }; return .{ .hole_punch_failed = .timeout };
@@ -307,7 +328,7 @@ pub const HolePunchEngine = struct {
var packet = HolePunchPacket{ var packet = HolePunchPacket{
.connection_id = params.connection_id, .connection_id = params.connection_id,
.sender_id = self.our_keypair.public, .sender_id = self.our_keypair.public,
.timestamp = std.time.milliTimestamp(), .timestamp = platform_time.milliTimestamp(),
.signature = undefined, .signature = undefined,
}; };
@@ -335,12 +356,12 @@ pub const HolePunchEngine = struct {
while (remaining > 0) { while (remaining > 0) {
const sleep_time = @min(remaining, interval_ns); const sleep_time = @min(remaining, interval_ns);
std.Thread.sleep(sleep_time); platform.time.sleep(sleep_time);
remaining -= sleep_time; remaining -= sleep_time;
if (remaining > 0) { if (remaining > 0) {
// Send keepalive to all addresses // Send keepalive to all addresses
std.mem.writeInt(i64, keepalive[4..12], std.time.milliTimestamp(), .big); std.mem.writeInt(i64, keepalive[4..12], platform_time.milliTimestamp(), .big);
for (target_addresses) |addr| { for (target_addresses) |addr| {
socket.sendTo(addr, &keepalive) catch continue; socket.sendTo(addr, &keepalive) catch continue;
} }
@@ -408,12 +429,12 @@ pub const HolePunchListener = struct {
from: Address, from: Address,
} { } {
var buf: [256]u8 = undefined; var buf: [256]u8 = undefined;
const deadline = std.time.milliTimestamp() + @as(i64, @intCast(timeout_ms)); const deadline = platform_time.milliTimestamp() + @as(i64, @intCast(timeout_ms));
while (std.time.milliTimestamp() < deadline) { while (platform_time.milliTimestamp() < deadline) {
const result = self.socket.recvFrom(&buf) catch |err| { const result = self.socket.recvFrom(&buf) catch |err| {
if (err == error.WouldBlock) { if (err == error.WouldBlock) {
std.Thread.sleep(1 * std.time.ns_per_ms); platform.time.sleep(1 * std.time.ns_per_ms);
continue; continue;
} }
return err; return err;
@@ -448,7 +469,7 @@ pub const HolePunchListener = struct {
var packet = HolePunchPacket{ var packet = HolePunchPacket{
.connection_id = connection_id, .connection_id = connection_id,
.sender_id = self.our_keypair.public, .sender_id = self.our_keypair.public,
.timestamp = std.time.milliTimestamp(), .timestamp = platform_time.milliTimestamp(),
.signature = undefined, .signature = undefined,
}; };

View File

@@ -3,6 +3,9 @@
//! Handles the DHT-based meeting point where peers find each other. //! Handles the DHT-based meeting point where peers find each other.
const std = @import("std"); const std = @import("std");
const platform = @import("platform");
const platform_time = platform.time;
const platform_random = platform.random;
const types = @import("types.zig"); const types = @import("types.zig");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
@@ -111,14 +114,14 @@ pub const MeetingPoint = struct {
.peer_id = self.our_keypair.public, .peer_id = self.our_keypair.public,
.addresses = self.our_addresses, .addresses = self.our_addresses,
.nonce = undefined, .nonce = undefined,
.timestamp = std.time.milliTimestamp(), .timestamp = platform_time.milliTimestamp(),
.ttl = ttl, .ttl = ttl,
.sequence = self.next_sequence, .sequence = self.next_sequence,
.signature = undefined, .signature = undefined,
}; };
// Generate random nonce // Generate random nonce
std.crypto.random.bytes(&pub_data.nonce); platform_random.bytes(&pub_data.nonce);
// Sign // Sign
const hash = pub_data.computeHash(); const hash = pub_data.computeHash();
@@ -149,9 +152,9 @@ pub const MeetingPoint = struct {
timeout_ms: u64, timeout_ms: u64,
) !struct { publication: MeetingPublication, seen_time: i64 } { ) !struct { publication: MeetingPublication, seen_time: i64 } {
const meeting_key = computeMeetingKey(self.our_keypair.public, their_pubkey); const meeting_key = computeMeetingKey(self.our_keypair.public, their_pubkey);
const deadline = std.time.milliTimestamp() + @as(i64, @intCast(timeout_ms)); const deadline = platform_time.milliTimestamp() + @as(i64, @intCast(timeout_ms));
while (std.time.milliTimestamp() < deadline) { while (platform_time.milliTimestamp() < deadline) {
// Query DHT // Query DHT
const entries = try self.dht.getAll(meeting_key, self.allocator); const entries = try self.dht.getAll(meeting_key, self.allocator);
defer { defer {
@@ -186,12 +189,12 @@ pub const MeetingPoint = struct {
// Found valid publication // Found valid publication
return .{ return .{
.publication = publication, .publication = publication,
.seen_time = std.time.milliTimestamp(), .seen_time = platform_time.milliTimestamp(),
}; };
} }
// Poll interval // Poll interval
std.Thread.sleep(Defaults.dht_poll_interval_ms * std.time.ns_per_ms); platform.time.sleep(Defaults.dht_poll_interval_ms * std.time.ns_per_ms);
} }
return error.Timeout; return error.Timeout;
@@ -309,8 +312,8 @@ test "computeRendezvousParams produces same result for both peers" {
// Simulate two peers with their publications // Simulate two peers with their publications
var our_nonce: [32]u8 = undefined; var our_nonce: [32]u8 = undefined;
var their_nonce: [32]u8 = undefined; var their_nonce: [32]u8 = undefined;
std.crypto.random.bytes(&our_nonce); platform_random.bytes(&our_nonce);
std.crypto.random.bytes(&their_nonce); platform_random.bytes(&their_nonce);
const our_pub = MeetingPublication{ const our_pub = MeetingPublication{
.peer_id = [_]u8{1} ** 32, .peer_id = [_]u8{1} ** 32,

View File

@@ -4,6 +4,7 @@
const std = @import("std"); const std = @import("std");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const platform_time = @import("platform").time;
/// Protocol version /// Protocol version
pub const PROTOCOL_VERSION: u8 = 0x01; pub const PROTOCOL_VERSION: u8 = 0x01;
@@ -183,7 +184,7 @@ pub const MeetingPublication = struct {
/// Check if publication is expired /// Check if publication is expired
pub fn isExpired(self: MeetingPublication) bool { pub fn isExpired(self: MeetingPublication) bool {
const now_ms = std.time.milliTimestamp(); const now_ms = platform_time.milliTimestamp();
const expiry_ms = self.timestamp + (@as(i64, self.ttl) * 1000); const expiry_ms = self.timestamp + (@as(i64, self.ttl) * 1000);
return now_ms > expiry_ms; return now_ms > expiry_ms;
} }

View File

@@ -29,7 +29,12 @@
//! ``` //! ```
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;
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const platform = @import("platform");
const platform_time = platform.time;
const platform_random = platform.random;
// Import zig-p2p P2P module // Import zig-p2p P2P module
const p2p_mod = @import("p2p"); const p2p_mod = @import("p2p");
@@ -150,13 +155,13 @@ pub const MWP = struct {
.peer_id = self.keypair.public, .peer_id = self.keypair.public,
.addresses = self.our_addresses, .addresses = self.our_addresses,
.nonce = undefined, .nonce = undefined,
.timestamp = std.time.milliTimestamp(), .timestamp = platform_time.milliTimestamp(),
.ttl = ttl, .ttl = ttl,
.sequence = self.next_sequence, .sequence = self.next_sequence,
.signature = undefined, .signature = undefined,
}; };
std.crypto.random.bytes(&pub_data.nonce); platform_random.bytes(&pub_data.nonce);
const hash = pub_data.computeHash(); const hash = pub_data.computeHash();
pub_data.signature = try self.keypair.sign(hash); pub_data.signature = try self.keypair.sign(hash);
@@ -211,7 +216,7 @@ pub const MWP = struct {
// SECURITY: Reject publications with far-future timestamps // SECURITY: Reject publications with far-future timestamps
// A malicious peer could use this to delay rendezvous arbitrarily // A malicious peer could use this to delay rendezvous arbitrarily
const now_ms = std.time.milliTimestamp(); const now_ms = platform_time.milliTimestamp();
if (publication.timestamp > now_ms + MAX_TIMESTAMP_SKEW_MS) { if (publication.timestamp > now_ms + MAX_TIMESTAMP_SKEW_MS) {
std.log.warn("MWP: Rejecting publication with far-future timestamp (skew: {}ms)", .{ std.log.warn("MWP: Rejecting publication with far-future timestamp (skew: {}ms)", .{
publication.timestamp - now_ms, publication.timestamp - now_ms,
@@ -228,9 +233,9 @@ pub const MWP = struct {
/// Wait for peer's publication (blocking with timeout) /// Wait for peer's publication (blocking with timeout)
pub fn waitForPeer(self: *MWP, their_pubkey: [32]u8, timeout_ms: u64) !MeetingPublication { pub fn waitForPeer(self: *MWP, their_pubkey: [32]u8, timeout_ms: u64) !MeetingPublication {
const deadline = std.time.milliTimestamp() + @as(i64, @intCast(timeout_ms)); const deadline = platform_time.milliTimestamp() + @as(i64, @intCast(timeout_ms));
while (std.time.milliTimestamp() < deadline) { while (platform_time.milliTimestamp() < deadline) {
// CRITICAL: Must call p2p.update() to process incoming network messages // CRITICAL: Must call p2p.update() to process incoming network messages
// Without this, DHT responses are never received // Without this, DHT responses are never received
self.p2p.update() catch |err| { self.p2p.update() catch |err| {
@@ -240,7 +245,7 @@ pub const MWP = struct {
if (try self.findPeer(their_pubkey)) |publication| { if (try self.findPeer(their_pubkey)) |publication| {
return publication; return publication;
} }
std.Thread.sleep(100 * std.time.ns_per_ms); platform.time.sleep(100 * std.time.ns_per_ms);
} }
return error.Timeout; return error.Timeout;
@@ -287,7 +292,7 @@ pub const MWP = struct {
options: ConnectOptions, options: ConnectOptions,
) ConnectionResult { ) ConnectionResult {
// SECURITY: Reject peer publications with far-future timestamps // SECURITY: Reject peer publications with far-future timestamps
const now_ms = std.time.milliTimestamp(); const now_ms = platform_time.milliTimestamp();
if (peer_publication.timestamp > now_ms + MAX_TIMESTAMP_SKEW_MS) { if (peer_publication.timestamp > now_ms + MAX_TIMESTAMP_SKEW_MS) {
std.log.warn("MWP: Peer publication has far-future timestamp (skew: {}ms), rejecting", .{ std.log.warn("MWP: Peer publication has far-future timestamp (skew: {}ms), rejecting", .{
peer_publication.timestamp - now_ms, peer_publication.timestamp - now_ms,
@@ -339,13 +344,14 @@ pub const MWP = struct {
params: RendezvousParams, params: RendezvousParams,
options: ConnectOptions, options: ConnectOptions,
) ConnectionResult { ) ConnectionResult {
if (is_wasm) return .{ .hole_punch_failed = .all_addresses_failed };
_ = options; _ = options;
// Wait until rendezvous time // Wait until rendezvous time
const now = std.time.milliTimestamp(); const now = platform_time.milliTimestamp();
if (params.rendezvous_time > now) { if (params.rendezvous_time > now) {
const wait_ns = @as(u64, @intCast(params.rendezvous_time - now)) * std.time.ns_per_ms; const wait_ns = @as(u64, @intCast(params.rendezvous_time - now)) * std.time.ns_per_ms;
std.Thread.sleep(wait_ns); platform.time.sleep(wait_ns);
} }
// Create UDP socket // Create UDP socket
@@ -384,7 +390,7 @@ pub const MWP = struct {
var pkt = HolePunchPacket{ var pkt = HolePunchPacket{
.connection_id = params.connection_id, .connection_id = params.connection_id,
.sender_id = self.keypair.public, .sender_id = self.keypair.public,
.timestamp = std.time.milliTimestamp(), .timestamp = platform_time.milliTimestamp(),
.signature = undefined, .signature = undefined,
}; };
const hash = pkt.computeHash(); const hash = pkt.computeHash();
@@ -397,13 +403,13 @@ pub const MWP = struct {
// Both peers send at the rendezvous time, but if one peer's packet arrives // Both peers send at the rendezvous time, but if one peer's packet arrives
// before the other's socket is bound, it's lost. Resending every 500ms // before the other's socket is bound, it's lost. Resending every 500ms
// ensures the peer will eventually receive our packet. // ensures the peer will eventually receive our packet.
const deadline = std.time.milliTimestamp() + 30000; // 30 second timeout const deadline = platform_time.milliTimestamp() + 30000; // 30 second timeout
var recv_buf: [256]u8 = undefined; var recv_buf: [256]u8 = undefined;
var last_send: i64 = 0; var last_send: i64 = 0;
while (std.time.milliTimestamp() < deadline) { while (platform_time.milliTimestamp() < deadline) {
// Send (or resend) to all target addresses every 500ms // Send (or resend) to all target addresses every 500ms
const loop_now = std.time.milliTimestamp(); const loop_now = platform_time.milliTimestamp();
if (loop_now - last_send >= 500) { if (loop_now - last_send >= 500) {
last_send = loop_now; last_send = loop_now;
for (target_addresses) |addr| { for (target_addresses) |addr| {
@@ -425,7 +431,7 @@ pub const MWP = struct {
const len = std.posix.recvfrom(fd, &recv_buf, 0, @ptrCast(&src_addr), &addr_len) catch |err| { const len = std.posix.recvfrom(fd, &recv_buf, 0, @ptrCast(&src_addr), &addr_len) catch |err| {
if (err == error.WouldBlock) { if (err == error.WouldBlock) {
std.Thread.sleep(1 * std.time.ns_per_ms); platform.time.sleep(1 * std.time.ns_per_ms);
continue; continue;
} }
std.log.warn("MWP: recvfrom error: {}", .{err}); std.log.warn("MWP: recvfrom error: {}", .{err});
@@ -476,7 +482,7 @@ pub const MWP = struct {
.remote_address = remote_address, .remote_address = remote_address,
.local_address = Address.initV4(.{ 0, 0, 0, 0 }, 0), .local_address = Address.initV4(.{ 0, 0, 0, 0 }, 0),
.connection_id = params.connection_id, .connection_id = params.connection_id,
.establishment_time_ms = @as(u64, @intCast(std.time.milliTimestamp() - params.rendezvous_time + 500)), .establishment_time_ms = @as(u64, @intCast(platform_time.milliTimestamp() - params.rendezvous_time + 500)),
}, },
}; };
} }