add bootstrap node, MWP peer discovery, and DNS resolution
This commit is contained in:
@@ -31,6 +31,7 @@ const p2p_lib = @import("p2p");
|
||||
const webrtc_bridge = @import("webrtc_bridge");
|
||||
const network = @import("network");
|
||||
const path_security = @import("files").path_security;
|
||||
const mwp_mod = @import("mwp");
|
||||
|
||||
const P2P = p2p_lib.P2P;
|
||||
const P2PConfig = p2p_lib.P2PConfig;
|
||||
@@ -83,6 +84,7 @@ const APP_ID_FILE_COMPLETE: u8 = 0x23;
|
||||
const APP_ID_FILE_CANCEL: u8 = 0x24;
|
||||
const APP_ID_FILE_RESUME: u8 = 0x25;
|
||||
const APP_ID_FILE_PAUSE: u8 = 0x26;
|
||||
const APP_ID_DHT_EXCHANGE: u8 = 0x30;
|
||||
|
||||
const CHUNK_SIZE: usize = 64 * 1024;
|
||||
// Noise protocol limits plaintext to 65,535 bytes. TCP chunks go through:
|
||||
@@ -389,6 +391,8 @@ pub fn main() !void {
|
||||
var output_dir: []const u8 = ".";
|
||||
var tcp_port: u16 = 0;
|
||||
var tcp_connect: ?[]const u8 = null;
|
||||
var bootstrap_addr: ?[]const u8 = null;
|
||||
var mwp_target_name: ?[]const u8 = null;
|
||||
|
||||
var i: usize = 1;
|
||||
while (i < args.len) : (i += 1) {
|
||||
@@ -415,6 +419,12 @@ pub fn main() !void {
|
||||
} else if (std.mem.eql(u8, args[i], "--connect") and i + 1 < args.len) {
|
||||
i += 1;
|
||||
tcp_connect = args[i];
|
||||
} else if (std.mem.eql(u8, args[i], "--bootstrap") and i + 1 < args.len) {
|
||||
i += 1;
|
||||
bootstrap_addr = args[i];
|
||||
} else if (std.mem.eql(u8, args[i], "--mwp-connect") and i + 1 < args.len) {
|
||||
i += 1;
|
||||
mwp_target_name = args[i];
|
||||
} else if (std.mem.eql(u8, args[i], "--help")) {
|
||||
const stdout = std.fs.File.stdout();
|
||||
try stdout.writeAll(
|
||||
@@ -431,6 +441,8 @@ pub fn main() !void {
|
||||
\\ --share FILE Share a file with the first peer that connects
|
||||
\\ --output-dir DIR Where to save received files (default: .)
|
||||
\\ --port PORT TCP listen port for direct desktop-to-desktop connections
|
||||
\\ --bootstrap H:P Bootstrap node address (DHT ID exchanged automatically)
|
||||
\\ --mwp-connect NAME Target peer name for MWP discovery (deterministic keys)
|
||||
\\ --help Show this help
|
||||
\\
|
||||
);
|
||||
@@ -443,7 +455,7 @@ pub fn main() !void {
|
||||
config.network.listen_port = 0;
|
||||
config.network.enable_noise_encryption = true; // Noise over DTLS for mutual authentication
|
||||
// Default idle_timeout_ms (60s) works with keepalive pings (sent every 30s)
|
||||
if (tcp_port == 0) {
|
||||
if (tcp_port == 0 and bootstrap_addr == null) {
|
||||
config.network.enable_udp_listener = false;
|
||||
}
|
||||
config.events.enable_logging = false;
|
||||
@@ -458,6 +470,136 @@ pub fn main() !void {
|
||||
p2p.startListening(listen_addr) catch {};
|
||||
}
|
||||
|
||||
// Auto-map TCP port via UPnP or NAT-PMP so remote peers can connect
|
||||
var upnp: ?network.upnp.Upnp = null;
|
||||
var nat_pmp: ?network.nat_pmp.NatPmp = null;
|
||||
var mapped_external_ip: ?[4]u8 = null;
|
||||
defer {
|
||||
if (upnp) |*u| {
|
||||
u.unmapPort(.tcp, tcp_port) catch {};
|
||||
u.deinit();
|
||||
}
|
||||
if (nat_pmp) |*n| {
|
||||
n.unmapPort(.tcp, tcp_port) catch {};
|
||||
n.deinit();
|
||||
}
|
||||
}
|
||||
|
||||
if (tcp_port > 0) {
|
||||
// Try UPnP first
|
||||
if (network.upnp.Upnp.init(allocator)) |u| {
|
||||
upnp = u;
|
||||
if (upnp.?.mapPort(.tcp, tcp_port, tcp_port, 3600)) |mapping| {
|
||||
if (mapping) |m| {
|
||||
mapped_external_ip = m.external_ip;
|
||||
std.log.info("UPnP: mapped port {d} -> {d}.{d}.{d}.{d}:{d}", .{
|
||||
tcp_port, m.external_ip[0], m.external_ip[1], m.external_ip[2], m.external_ip[3], m.external_port,
|
||||
});
|
||||
}
|
||||
} else |_| {}
|
||||
} else |_| {
|
||||
// UPnP unavailable, try NAT-PMP
|
||||
if (network.nat_pmp.NatPmp.init(allocator)) |n| {
|
||||
nat_pmp = n;
|
||||
if (nat_pmp.?.mapPort(.tcp, tcp_port, tcp_port, 3600)) |mapping| {
|
||||
if (mapping) |m| {
|
||||
mapped_external_ip = m.external_ip;
|
||||
std.log.info("NAT-PMP: mapped port {d} -> {d}.{d}.{d}.{d}:{d}", .{
|
||||
tcp_port, m.external_ip[0], m.external_ip[1], m.external_ip[2], m.external_ip[3], m.external_port,
|
||||
});
|
||||
}
|
||||
} else |_| {}
|
||||
} else |_| {}
|
||||
}
|
||||
}
|
||||
|
||||
// Bootstrap: connect to DHT network for MWP peer discovery
|
||||
if (bootstrap_addr) |addr| {
|
||||
if (parseHostPort(addr)) |hp| {
|
||||
const boot_addr = coreAddress.ipv4(hp.host, hp.port);
|
||||
if (p2p.connectToPeer(boot_addr)) |connection_peer_id| {
|
||||
// Send our DHT ID to bootstrap
|
||||
if (p2p.getDhtLocalId()) |our_dht_id| {
|
||||
_ = p2p.sendMessage(connection_peer_id, APP_ID_DHT_EXCHANGE, &our_dht_id) catch {};
|
||||
}
|
||||
|
||||
// Wait for bootstrap's DHT ID exchange (up to 3s)
|
||||
var got_bootstrap_dht = false;
|
||||
for (0..60) |_| {
|
||||
p2p.update() catch {};
|
||||
while (p2p.getNextEvent()) |ev| {
|
||||
var event = ev;
|
||||
defer event.deinit();
|
||||
switch (event.data) {
|
||||
.message_received => |msg| {
|
||||
if (msg.message_type == APP_ID_DHT_EXCHANGE and msg.data.len == 32) {
|
||||
var remote_dht_id: [32]u8 = undefined;
|
||||
@memcpy(&remote_dht_id, msg.data[0..32]);
|
||||
p2p.registerDhtNodeId(remote_dht_id, msg.source) catch {};
|
||||
p2p.dhtAddPeer(remote_dht_id, boot_addr) catch {};
|
||||
got_bootstrap_dht = true;
|
||||
}
|
||||
},
|
||||
else => {},
|
||||
}
|
||||
}
|
||||
if (got_bootstrap_dht) break;
|
||||
std.Thread.sleep(50 * std.time.ns_per_ms);
|
||||
}
|
||||
|
||||
// Trigger IP Reflection via DHT lookup
|
||||
if (got_bootstrap_dht) {
|
||||
const dummy_key: [32]u8 = [_]u8{0xDE, 0xAD, 0xBE, 0xEF} ++ [_]u8{0} ** 28;
|
||||
_ = p2p.dhtFindValue(dummy_key) catch {};
|
||||
for (0..30) |_| {
|
||||
p2p.update() catch {};
|
||||
std.Thread.sleep(50 * std.time.ns_per_ms);
|
||||
}
|
||||
}
|
||||
} else |_| {}
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize MWP for peer discovery (when --bootstrap or --mwp-connect is set)
|
||||
var mwp_node: ?*mwp_mod.MWP = null;
|
||||
var mwp_target_pubkey: ?[32]u8 = null;
|
||||
var mwp_addrs: [1]mwp_mod.Address = .{mwp_mod.Address.initV4(.{ 127, 0, 0, 1 }, 9001)};
|
||||
var mwp_port: u16 = 9001;
|
||||
defer if (mwp_node) |m| m.deinit();
|
||||
|
||||
if (bootstrap_addr != null or mwp_target_name != null) {
|
||||
// Deterministic keypair from name (same scheme as mwp_demo)
|
||||
const keypair = deterministicKeypair(name);
|
||||
|
||||
// If --mwp-connect is set, compute target's pubkey from their name
|
||||
if (mwp_target_name) |target_name| {
|
||||
const target_kp = deterministicKeypair(target_name);
|
||||
mwp_target_pubkey = target_kp.public;
|
||||
}
|
||||
|
||||
// MWP address selection: UPnP/NAT-PMP > IP Reflection > localhost
|
||||
mwp_port = if (tcp_port > 0) tcp_port + 1 else 9001;
|
||||
if (mapped_external_ip) |ip| {
|
||||
mwp_addrs[0] = mwp_mod.Address.initV4(ip, mwp_port);
|
||||
} else if (p2p.getObservedPublicAddress()) |observed| {
|
||||
switch (observed.ip) {
|
||||
.v4 => |ip| {
|
||||
mwp_addrs[0] = mwp_mod.Address.initV4(ip, mwp_port);
|
||||
},
|
||||
.v6 => {
|
||||
mwp_addrs[0] = mwp_mod.Address.initV4(.{ 127, 0, 0, 1 }, mwp_port);
|
||||
},
|
||||
}
|
||||
} else {
|
||||
mwp_addrs[0] = mwp_mod.Address.initV4(.{ 127, 0, 0, 1 }, mwp_port);
|
||||
}
|
||||
|
||||
mwp_node = mwp_mod.MWP.init(allocator, &p2p, .{
|
||||
.keypair = keypair,
|
||||
.addresses = &mwp_addrs,
|
||||
}) catch null;
|
||||
}
|
||||
|
||||
// Initialize WebRTC bridge
|
||||
var bridge = WebRTCBridge.init(allocator, signaling_url, name);
|
||||
defer bridge.deinit();
|
||||
@@ -485,6 +627,21 @@ pub fn main() !void {
|
||||
var state = AppState.init(allocator, &p2p, &bridge, output_dir, share_path);
|
||||
defer state.deinit();
|
||||
|
||||
// Show connection info in chat
|
||||
if (tcp_port > 0) {
|
||||
if (mapped_external_ip) |ip| {
|
||||
var addr_buf: [64]u8 = undefined;
|
||||
const addr_msg = std.fmt.bufPrint(&addr_buf, "Listening on port {d} (public: {d}.{d}.{d}.{d}:{d})", .{
|
||||
tcp_port, ip[0], ip[1], ip[2], ip[3], tcp_port,
|
||||
}) catch "Listening (port mapped)";
|
||||
state.addStatus(addr_msg);
|
||||
} else {
|
||||
var addr_buf: [64]u8 = undefined;
|
||||
const addr_msg = std.fmt.bufPrint(&addr_buf, "Listening on port {d} (no UPnP/NAT-PMP — may need port forwarding)", .{tcp_port}) catch "Listening";
|
||||
state.addStatus(addr_msg);
|
||||
}
|
||||
}
|
||||
|
||||
// Open perf log file (per-instance: /tmp/tui_perf_<name>.log)
|
||||
var log_path_buf: [128]u8 = undefined;
|
||||
const log_path = std.fmt.bufPrint(&log_path_buf, "/tmp/tui_perf_{s}.log", .{name}) catch "/tmp/tui_perf.log";
|
||||
@@ -511,6 +668,22 @@ pub fn main() !void {
|
||||
state.addStatus(msg);
|
||||
}
|
||||
|
||||
// Show bootstrap info for node operators
|
||||
if (tcp_port > 0) {
|
||||
var share_buf: [128]u8 = undefined;
|
||||
const share_msg = std.fmt.bufPrint(&share_buf, "Peers can join: --bootstrap YOUR_IP:{d}", .{tcp_port}) catch "";
|
||||
if (share_msg.len > 0) state.addStatus(share_msg);
|
||||
}
|
||||
|
||||
if (mwp_node) |m| {
|
||||
const our_pubkey = m.getPublicKey();
|
||||
var pk_hex_buf: [64]u8 = undefined;
|
||||
_ = formatHex(&our_pubkey, &pk_hex_buf);
|
||||
var mwp_msg_buf: [256]u8 = undefined;
|
||||
const mwp_msg = std.fmt.bufPrint(&mwp_msg_buf, "MWP key: {s}", .{pk_hex_buf}) catch "MWP initialized";
|
||||
state.addStatus(mwp_msg);
|
||||
}
|
||||
|
||||
// Redirect stderr to a log file BEFORE entering TUI — the P2P library uses
|
||||
// std.debug.print which writes directly to fd 2 and would corrupt the
|
||||
// alternate screen. Use /tmp/tui_stderr_<name>.log for debugging.
|
||||
@@ -551,6 +724,12 @@ pub fn main() !void {
|
||||
|
||||
try writer.flush();
|
||||
|
||||
// MWP discovery state machine
|
||||
const MwpState = enum { idle, published, searching, done };
|
||||
var mwp_state: MwpState = .idle;
|
||||
var mwp_publication: ?mwp_mod.MeetingPublication = null;
|
||||
var mwp_last_search: i64 = 0;
|
||||
|
||||
// Main loop — poll-based (non-blocking) for p2p.update() integration
|
||||
var running = true;
|
||||
while (running) {
|
||||
@@ -608,6 +787,95 @@ pub fn main() !void {
|
||||
}
|
||||
}
|
||||
|
||||
// 2c. MWP peer discovery state machine
|
||||
if (mwp_node) |m| {
|
||||
if (mwp_target_pubkey) |target_pk| {
|
||||
switch (mwp_state) {
|
||||
.idle => {
|
||||
// Update MWP address from IP Reflection before publishing
|
||||
if (mapped_external_ip == null) {
|
||||
if (p2p.getObservedPublicAddress()) |observed| {
|
||||
switch (observed.ip) {
|
||||
.v4 => |ip| {
|
||||
mwp_addrs[0] = mwp_mod.Address.initV4(ip, mwp_port);
|
||||
},
|
||||
.v6 => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
// Publish our availability
|
||||
if (m.publishFor(target_pk, 300)) |pub_data| {
|
||||
mwp_publication = pub_data;
|
||||
mwp_state = .published;
|
||||
state.addStatus("MWP: Published availability, searching for peer...");
|
||||
} else |_| {
|
||||
state.addStatus("MWP: Failed to publish");
|
||||
}
|
||||
},
|
||||
.published, .searching => {
|
||||
mwp_state = .searching;
|
||||
// Search every 2 seconds
|
||||
if (now - mwp_last_search >= 2000) {
|
||||
mwp_last_search = now;
|
||||
if (m.findPeer(target_pk) catch null) |peer_pub| {
|
||||
state.addStatus("MWP: Found peer! Attempting hole punch...");
|
||||
// Use connectWithPublication (blocks ~10s max)
|
||||
const result = m.connectWithPublication(
|
||||
mwp_publication.?,
|
||||
peer_pub,
|
||||
.{ .timeout_ms = 10_000 },
|
||||
);
|
||||
var pub_copy = peer_pub;
|
||||
pub_copy.deinit(allocator);
|
||||
|
||||
switch (result) {
|
||||
.success => |info| {
|
||||
// TCP connect to discovered address
|
||||
const remote = coreAddress.ipv4(
|
||||
info.remote_address.ip.v4,
|
||||
info.remote_address.port,
|
||||
);
|
||||
p2p.startNonBlockingConnect(remote) catch {};
|
||||
var res_buf: [256]u8 = undefined;
|
||||
const res_msg = std.fmt.bufPrint(&res_buf, "MWP: Hole punch OK! Connecting to {d}.{d}.{d}.{d}:{d}", .{
|
||||
info.remote_address.ip.v4[0],
|
||||
info.remote_address.ip.v4[1],
|
||||
info.remote_address.ip.v4[2],
|
||||
info.remote_address.ip.v4[3],
|
||||
info.remote_address.port,
|
||||
}) catch "MWP: Connected!";
|
||||
state.addStatus(res_msg);
|
||||
mwp_state = .done;
|
||||
},
|
||||
.timeout => {
|
||||
state.addStatus("MWP: Hole punch timeout, retrying...");
|
||||
// Re-publish and keep searching
|
||||
if (m.publishFor(target_pk, 300)) |new_pub| {
|
||||
mwp_publication = new_pub;
|
||||
} else |_| {}
|
||||
},
|
||||
.hole_punch_failed => |err| {
|
||||
var err_buf: [256]u8 = undefined;
|
||||
const err_msg = std.fmt.bufPrint(&err_buf, "MWP: Hole punch failed: {s}", .{@tagName(err)}) catch "MWP: Hole punch failed";
|
||||
state.addStatus(err_msg);
|
||||
},
|
||||
.peer_not_found => {
|
||||
state.addStatus("MWP: Peer not found");
|
||||
},
|
||||
.other_error => |err| {
|
||||
var err_buf: [256]u8 = undefined;
|
||||
const err_msg = std.fmt.bufPrint(&err_buf, "MWP: Error: {s}", .{@errorName(err)}) catch "MWP: Error";
|
||||
state.addStatus(err_msg);
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
.done => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Check for new peer connections
|
||||
while (bridge.pollNewPeer()) |new_peer| {
|
||||
var already_tracked = false;
|
||||
@@ -663,6 +931,11 @@ pub fn main() !void {
|
||||
}
|
||||
state.addStatus("TCP peer connected (outbound)");
|
||||
|
||||
// Exchange DHT IDs automatically
|
||||
if (p2p.getDhtLocalId()) |our_dht_id| {
|
||||
_ = p2p.sendMessage(ce.peer_id, APP_ID_DHT_EXCHANGE, &our_dht_id) catch {};
|
||||
}
|
||||
|
||||
// Auto-offer file to TCP peer if --share is set
|
||||
if (state.share_path) |path| {
|
||||
if (!hasActiveSendTo(&state.transfers, ce.peer_id)) {
|
||||
@@ -692,6 +965,11 @@ pub fn main() !void {
|
||||
}
|
||||
state.addStatus("TCP peer connected (inbound)");
|
||||
|
||||
// Exchange DHT IDs automatically
|
||||
if (p2p.getDhtLocalId()) |our_dht_id| {
|
||||
_ = p2p.sendMessage(pc.peer_id, APP_ID_DHT_EXCHANGE, &our_dht_id) catch {};
|
||||
}
|
||||
|
||||
// Auto-offer file to TCP peer if --share is set
|
||||
if (state.share_path) |path| {
|
||||
if (!hasActiveSendTo(&state.transfers, pc.peer_id)) {
|
||||
@@ -722,6 +1000,13 @@ pub fn main() !void {
|
||||
handleFileCancel(msg.data, &state.transfers, &state);
|
||||
} else if (msg.message_type == APP_ID_FILE_PAUSE) {
|
||||
handleFilePause(msg.data, &state.transfers);
|
||||
} else if (msg.message_type == APP_ID_DHT_EXCHANGE) {
|
||||
if (msg.data.len == 32) {
|
||||
var remote_dht_id: [32]u8 = undefined;
|
||||
@memcpy(&remote_dht_id, msg.data[0..32]);
|
||||
p2p.registerDhtNodeId(remote_dht_id, msg.source) catch {};
|
||||
state.addStatus("DHT peer registered");
|
||||
}
|
||||
} else if (msg.message_type == APP_ID_CHAT) {
|
||||
if (msg.data.len > 0) {
|
||||
state.addChatMessage("peer", msg.data, false);
|
||||
@@ -2042,17 +2327,63 @@ fn parseHostPort(s: []const u8) ?struct { host: [4]u8, port: u16 } {
|
||||
const port_str = s[colon_idx + 1 ..];
|
||||
const port = std.fmt.parseInt(u16, port_str, 10) catch return null;
|
||||
|
||||
// Try IPv4 dotted notation first
|
||||
var parts: [4]u8 = undefined;
|
||||
var iter = std.mem.splitScalar(u8, host_str, '.');
|
||||
var idx: usize = 0;
|
||||
var is_ip = true;
|
||||
while (iter.next()) |part| {
|
||||
if (idx >= 4) return null;
|
||||
parts[idx] = std.fmt.parseInt(u8, part, 10) catch return null;
|
||||
if (idx >= 4) { is_ip = false; break; }
|
||||
parts[idx] = std.fmt.parseInt(u8, part, 10) catch { is_ip = false; break; };
|
||||
idx += 1;
|
||||
}
|
||||
if (idx != 4) return null;
|
||||
if (is_ip and idx == 4) return .{ .host = parts, .port = port };
|
||||
|
||||
return .{ .host = parts, .port = port };
|
||||
// Fall back to DNS resolution
|
||||
var gpa_alloc = std.heap.GeneralPurposeAllocator(.{}){};
|
||||
defer _ = gpa_alloc.deinit();
|
||||
const list = std.net.getAddressList(gpa_alloc.allocator(), host_str, port) catch return null;
|
||||
defer list.deinit();
|
||||
for (list.addrs) |addr| {
|
||||
if (addr.any.family == std.posix.AF.INET) {
|
||||
const bytes = @as(*const [4]u8, @ptrCast(&addr.in.sa.addr));
|
||||
return .{ .host = bytes.*, .port = port };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// MWP helpers — deterministic keypair, hex formatting
|
||||
// ============================================================================
|
||||
fn deterministicKeypair(seed: []const u8) mwp_mod.KeyPair {
|
||||
var seed_hash: [32]u8 = undefined;
|
||||
var hasher = std.crypto.hash.blake2.Blake2b256.init(.{});
|
||||
hasher.update("mwp-test-keypair-v1");
|
||||
hasher.update(seed);
|
||||
hasher.final(&seed_hash);
|
||||
|
||||
const kp = std.crypto.sign.Ed25519.KeyPair.generateDeterministic(seed_hash) catch unreachable;
|
||||
return .{
|
||||
.public = kp.public_key.toBytes(),
|
||||
.secret = kp.secret_key.toBytes(),
|
||||
};
|
||||
}
|
||||
|
||||
fn formatHex(bytes: []const u8, buf: []u8) []u8 {
|
||||
const charset = "0123456789abcdef";
|
||||
for (bytes, 0..) |b, idx| {
|
||||
buf[idx * 2] = charset[b >> 4];
|
||||
buf[idx * 2 + 1] = charset[b & 0x0f];
|
||||
}
|
||||
return buf[0 .. bytes.len * 2];
|
||||
}
|
||||
|
||||
fn parseHex(hex: []const u8, out: []u8) !void {
|
||||
if (hex.len != out.len * 2) return error.InvalidLength;
|
||||
for (0..out.len) |idx| {
|
||||
out[idx] = std.fmt.parseInt(u8, hex[idx * 2 ..][0..2], 16) catch return error.InvalidHex;
|
||||
}
|
||||
}
|
||||
|
||||
fn hasActiveSendTo(transfers: *const TransferMap, peer_id: PeerId) bool {
|
||||
|
||||
Reference in New Issue
Block a user