Start proper connection handshake

This commit is contained in:
2025-04-05 21:22:43 -04:00
parent 433a97fe5a
commit b219fdc1f5
2 changed files with 54 additions and 4 deletions

View File

@@ -30,7 +30,9 @@ pub fn main() !void {
try Saprus.init();
defer Saprus.deinit();
try Saprus.sendInitialConnection(if (message.items.len > 0) message.items else "Hello darkness my old friend", 6868, gpa);
// _ = try Saprus.sendInitialConnection(if (message.items.len > 0) message.items else "Hello darkness my old friend", 6868, gpa);
try Saprus.connect(if (message.items.len > 0) message.items else "Hello darkness my old friend", gpa);
// try Saprus.sendRelay(if (message.items.len > 0) message.items else "Hello darkness my old friend", gpa);
}

View File

@@ -1,4 +1,12 @@
var rand: ?Random = null;
pub fn init() !void {
var prng = Random.DefaultPrng.init(blk: {
var seed: u64 = undefined;
try posix.getrandom(mem.asBytes(&seed));
break :blk seed;
});
rand = prng.random();
try network.init();
}
@@ -42,12 +50,17 @@ pub fn sendRelay(payload: []const u8, allocator: Allocator) !void {
try broadcastSaprusMessage(msg, allocator);
}
pub fn sendInitialConnection(payload: []const u8, initial_port: u16, allocator: Allocator) !void {
pub fn sendInitialConnection(payload: []const u8, initial_port: u16, allocator: Allocator) !SaprusMessage {
var dest_port: u16 = 0;
if (rand) |r| {
dest_port = r.intRangeAtMost(u16, 1024, 65000);
} else unreachable;
const msg = SaprusMessage{
.connection = .{
.header = .{
.src_port = initial_port,
.dest_port = 6868,
.dest_port = dest_port,
.seq_num = 1,
.msg_id = 2,
.reserved = 5,
@@ -57,10 +70,45 @@ pub fn sendInitialConnection(payload: []const u8, initial_port: u16, allocator:
};
try broadcastSaprusMessage(msg, allocator);
return msg;
}
fn awaitSentinelConnectionResponse(res: *?SaprusMessage) !void {
res.* = SaprusMessage{
.relay = .{
.header = .{
.dest = .{ 255, 255, 255, 255 },
},
.payload = "",
},
};
std.Thread.sleep(3 * 1000 * 1000 * 1000);
}
pub fn connect(payload: []const u8, allocator: Allocator) !void {
var initial_port: u16 = 0;
if (rand) |r| {
initial_port = r.intRangeAtMost(u16, 1024, 65000);
} else unreachable;
var initial_conn_res: ?SaprusMessage = null;
const response_thread = try std.Thread.spawn(.{}, awaitSentinelConnectionResponse, .{&initial_conn_res});
const msg = try sendInitialConnection(payload, initial_port, allocator);
std.debug.print("msg: {any}\n", .{msg});
response_thread.join();
std.debug.print("initial_conn_res: {any}\n", .{initial_conn_res});
}
const SaprusMessage = @import("./saprus_message.zig").SaprusMessage;
const std = @import("std");
const Random = std.Random;
const posix = std.posix;
const mem = std.mem;
const network = @import("network");
const Allocator = std.mem.Allocator;
const Allocator = mem.Allocator;