1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
|
const base64Enc = std.base64.Base64Encoder.init(std.base64.standard_alphabet_chars, '=');
const base64Dec = std.base64.Base64Decoder.init(std.base64.standard_alphabet_chars, '=');
const native_endian = @import("builtin").cpu.arch.endian();
rand: Random,
writer: *std.Io.Writer,
const Self = @This();
const max_message_size = 2048;
pub fn init(writer: *std.Io.Writer) !Self {
var prng = Random.DefaultPrng.init(blk: {
var seed: u64 = undefined;
try posix.getrandom(mem.asBytes(&seed));
break :blk seed;
});
const rand = prng.random();
return .{
.rand = rand,
.writer = writer,
};
}
pub fn deinit(self: *Self) void {
self.writer.flush() catch {};
}
/// Used for relay messages and connection handshake.
/// Assumes Client .init has been called.
fn broadcastInitialInterestMessage(self: *Self, msg_bytes: []align(@alignOf(SaprusMessage)) u8) !void {
const writer = self.writer;
// const EthernetHeaders = packed struct {
// dest_mac: @Vector(6, u8),
// src_mac: @Vector(6, u8),
// ether_type: u16,
// };
const IpHeaders = packed struct {
_: u8 = 0x45,
// ip_version: u4,
// header_length: u4 = 0,
type_of_service: u8 = 0,
total_length: u16 = 0x04,
identification: u16 = 0,
__: u16 = 0x0,
// ethernet_flags: u3 = 0,
// fragment_offset: u13 = 0,
ttl: u8 = 0,
protocol: u8 = 0,
header_checksum: @Vector(2, u8) = .{ 0, 0 },
src_ip: @Vector(4, u8),
dest_ip: @Vector(4, u8),
};
const UdpHeaders = packed struct {
src_port: @Vector(2, u8),
dest_port: @Vector(2, u8),
length: u16,
checksum: @Vector(2, u8) = .{ 0, 0 },
};
// const total_len = ((@bitSizeOf(IpHeaders) + @bitSizeOf(UdpHeaders)) / 8) + msg_bytes.len;
const total_len = 130;
std.debug.assert(writer.buffer.len >= total_len);
_ = writer.consumeAll();
// var ether_headers: EthernetHeaders = .{
// .dest_mac = .{ 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff },
// // .src_mac = .{ 0xee, 0xee, 0xee, 0xee, 0xee, 0xee },
// .src_mac = blk: {
// var output_bytes: [6]u8 = undefined;
// // const r_bytes = try writer.writableArray(6);
// self.rand.bytes(&output_bytes);
// break :blk output_bytes;
// },
// .ether_type = 0x0800,
// };
var ip_headers: IpHeaders = .{
// .ip_version = 0x4,
// .header_length = 0x5,
// .total_length = 130, //@intCast(total_len - 8), // 8 is the ethernet frame length (macs + type)
.total_length = 0x00,
.ttl = 0x64,
.protocol = 0x11,
.src_ip = .{ 0xff, 0x02, 0x03, 0x04 },
.dest_ip = .{ 0xff, 0xff, 0xff, 0xff },
};
var udp_headers: UdpHeaders = .{
.src_port = .{ 0, 0x01 },
.dest_port = .{ 0xb8, 0x22 },
.length = @intCast(msg_bytes.len),
};
_ = &ip_headers;
_ = &udp_headers;
// _ = ðer_headers;
// _ = try writer.write(&@as([@bitSizeOf(UdpHeaders) / 8]u8, @bitCast(headers)));
// std.mem.byteSwapAllFields(EthernetHeaders, ðer_headers);
// try writer.writeStruct(ether_headers, native_endian);
std.mem.byteSwapAllFields(IpHeaders, &ip_headers);
try writer.writeStruct(ip_headers, native_endian);
// std.mem.byteSwapAllFields(UdpHeaders, &udp_headers);
// try writer.writeStruct(udp_headers, native_endian);
// // Ensure buffer is large enough
// std.debug.assert(writer.buffer.len > 38 + msg_bytes.len);
// // Ensure writer is clean
// writer.consumeAll();
// // Destination MAC addr to FF:FF:FF:FF:FF:FF
// try writer.write();
// // Source MAC to random bytes
// {
// }
// // 96 bits
// // Set EtherType to IPv4
// try writer.write(.{ 0x08, 0x00 });
// // 112 bits
// // Set IPv4 version to 4
// try writer.writeByte(0x45);
// // 120 bits
// // Unset section (Version, IHL, ToS)
// writer.advance(2);
// // 136 bits
// // Total length
// try write.writeInt(u16, 38 + msg_bytes.len);
// // Destination broadcast
// writer.splatByte(0xff, 0x22 - 0x1e);
// var packet_bytes: [_]u8 = comptime blk: {
// var b: [max_message_size]u8 = @splat(0);
// for (0x1e..0x22) |i| {
// b[i] = 0xff;
// }
// // Set TTL
// b[0x16] = 0x40;
// // Set IPv4 protocol to UDP
// b[0x17] = 0x11;
// // Set interest filter value to 8888.
// b[0x24] = 0x22;
// b[0x25] = 0xb8;
// break :blk &b;
// };
var msg: *SaprusMessage = try .bytesAsValue(msg_bytes);
try msg.networkFromNativeEndian();
defer msg.nativeFromNetworkEndian() catch unreachable;
// std.debug.print("headers: {x}\n", .{@as([@bitSizeOf(UdpHeaders) / 8]u8, @bitCast(headers))});
std.debug.print("bytes: {x}\n", .{writer.buffer[0..writer.end]});
_ = try writer.write(msg_bytes);
// The byte position within the packet that the saprus message starts at.
// const saprus_start_byte = 42;
// @memcpy(packet_bytes[saprus_start_byte .. saprus_start_byte + msg_bytes.len], msg_bytes);
// _ = try writer.write(packet_bytes[0 .. saprus_start_byte + msg_bytes.len]);
try writer.flush();
}
// fn broadcastSaprusMessage(msg_bytes: []align(@alignOf(SaprusMessage)) u8) !void {}
fn broadcastSaprusMessage(msg_bytes: []align(@alignOf(SaprusMessage)) u8, udp_port: u16) !void {
const msg: *SaprusMessage = try .bytesAsValue(msg_bytes);
try msg.networkFromNativeEndian();
defer msg.nativeFromNetworkEndian() catch unreachable;
var sock = try network.Socket.create(.ipv4, .udp);
defer sock.close();
try sock.setBroadcast(true);
// Bind to 0.0.0.0:0
const bind_addr = network.EndPoint{
.address = network.Address{ .ipv4 = network.Address.IPv4.any },
.port = 0,
};
const dest_addr = network.EndPoint{
.address = network.Address{ .ipv4 = network.Address.IPv4.broadcast },
.port = udp_port,
};
try sock.bind(bind_addr);
std.debug.print("{x}\n", .{msg_bytes});
_ = try sock.sendTo(dest_addr, msg_bytes);
}
pub fn sendRelay(self: *Self, payload: []const u8, dest: [4]u8) !void {
var buf: [max_message_size]u8 align(@alignOf(SaprusMessage)) = undefined;
const msg_bytes = buf[0..try SaprusMessage.calcSize(
.relay,
base64Enc.calcSize(payload.len),
)];
const msg: *SaprusMessage = .init(.relay, msg_bytes);
const relay = (try msg.getSaprusTypePayload()).relay;
relay.dest = dest;
_ = base64Enc.encode(relay.getPayload(), payload);
try self.broadcastInitialInterestMessage(msg_bytes);
}
fn randomPort(self: Self) u16 {
return self.rand.intRangeAtMost(u16, 1024, 65000);
}
pub fn sendInitialConnection(
self: Self,
payload: []const u8,
output_bytes: []align(@alignOf(SaprusMessage)) u8,
initial_port: u16,
) !*SaprusMessage {
const dest_port = self.randomPort();
const msg_bytes = output_bytes[0..try SaprusMessage.calcSize(
.connection,
base64Enc.calcSize(payload.len),
)];
const msg: *SaprusMessage = .init(.connection, msg_bytes);
const connection = (try msg.getSaprusTypePayload()).connection;
connection.src_port = initial_port;
connection.dest_port = dest_port;
_ = base64Enc.encode(connection.getPayload(), payload);
try broadcastSaprusMessage(msg_bytes, 8888);
return msg;
}
pub fn connect(self: Self, payload: []const u8) !?SaprusConnection {
const initial_port = self.randomPort();
var initial_conn_res: ?*SaprusMessage = null;
var sock = try network.Socket.create(.ipv4, .udp);
defer sock.close();
// Bind to 255.255.255.255:8888
const bind_addr = network.EndPoint{
.address = network.Address{ .ipv4 = network.Address.IPv4.broadcast },
.port = 8888,
};
// timeout 1s
try sock.setReadTimeout(1 * std.time.us_per_s);
try sock.bind(bind_addr);
var sent_msg_bytes: [max_message_size]u8 align(@alignOf(SaprusMessage)) = undefined;
const msg = try self.sendInitialConnection(payload, &sent_msg_bytes, initial_port);
var response_buf: [max_message_size]u8 align(@alignOf(SaprusMessage)) = undefined;
_ = try sock.receive(&response_buf); // Ignore message that I sent.
const len = try sock.receive(&response_buf);
initial_conn_res = try .networkBytesAsValue(response_buf[0..len]);
// Complete handshake after awaiting response
try broadcastSaprusMessage(msg.asBytes(), self.randomPort());
if (false) {
return initial_conn_res.?;
}
return null;
}
const SaprusMessage = @import("message.zig").Message;
const SaprusConnection = @import("Connection.zig");
const std = @import("std");
const Random = std.Random;
const posix = std.posix;
const mem = std.mem;
const network = @import("network");
|