aboutsummaryrefslogtreecommitdiff
path: root/src/peer_protocol.zig
diff options
context:
space:
mode:
authorMartin Ashby <martin@ashbysoft.com>2023-11-12 09:07:50 +0000
committerMartin Ashby <martin@ashbysoft.com>2023-11-12 09:07:50 +0000
commit536837b44823aedf3dab0b8ef844d57cbae7af74 (patch)
tree3c19f7757af9f7112ec02f320ae4cd40bfab5b89 /src/peer_protocol.zig
parente3c5be0a33e66b124ff261479cffa9f95ce53dc0 (diff)
downloadzbt-536837b44823aedf3dab0b8ef844d57cbae7af74.tar.gz
zbt-536837b44823aedf3dab0b8ef844d57cbae7af74.tar.bz2
zbt-536837b44823aedf3dab0b8ef844d57cbae7af74.tar.xz
zbt-536837b44823aedf3dab0b8ef844d57cbae7af74.zip
Handshake a peer
Diffstat (limited to 'src/peer_protocol.zig')
-rw-r--r--src/peer_protocol.zig26
1 files changed, 26 insertions, 0 deletions
diff --git a/src/peer_protocol.zig b/src/peer_protocol.zig
new file mode 100644
index 0000000..cd70ad2
--- /dev/null
+++ b/src/peer_protocol.zig
@@ -0,0 +1,26 @@
+const std = @import("std");
+
+pub const Handshake = struct {
+ info_hash: [20]u8,
+ peer_id: [20]u8,
+
+ pub fn read(reader: anytype) !Handshake {
+ var msg = [_]u8{0} ** 68;
+ try reader.readNoEof(&msg);
+ if (msg[0] != 19) return error.ProtocolError;
+ if (!std.mem.eql(u8, msg[1..20], "BitTorrent protocol")) return error.ProtocolError;
+ //if (!std.mem.allEqual(u8, msg[20..28], 0)) return error.ProtocolError;
+ var res: Handshake = undefined;
+ @memcpy(&res.info_hash, msg[28..48]);
+ @memcpy(&res.peer_id, msg[48..68]);
+ return res;
+ }
+
+ pub fn write(self: Handshake, writer: anytype) !void {
+ try writer.writeByte(19);
+ try writer.writeAll("BitTorrent protocol");
+ try writer.writeByteNTimes(0, 8);
+ try writer.writeAll(&self.info_hash);
+ try writer.writeAll(&self.peer_id);
+ }
+};