diff options
author | Martin Ashby <martin@ashbysoft.com> | 2023-11-12 09:07:50 +0000 |
---|---|---|
committer | Martin Ashby <martin@ashbysoft.com> | 2023-11-12 09:07:50 +0000 |
commit | 536837b44823aedf3dab0b8ef844d57cbae7af74 (patch) | |
tree | 3c19f7757af9f7112ec02f320ae4cd40bfab5b89 /src/peer_protocol.zig | |
parent | e3c5be0a33e66b124ff261479cffa9f95ce53dc0 (diff) | |
download | zbt-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.zig | 26 |
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); + } +}; |