srctree

Gregory Mullen parent 59560110 6c8286a9
move more send/recv code into Upstream

src/client.zig added: 28, removed: 22, total 6
@@ -16,8 +16,7 @@ pub fn main() !void {
}
}
 
const upstream = try DNS.Upstream.init(nameserver);
try upstream.connect();
const upstream = try DNS.Upstream.connect(nameserver, 53);
 
const msg = try DNS.Message.query(a, &[1][]const u8{domain orelse "gr.ht."});
var request: [1024]u8 = undefined;
 
src/dns.zig added: 28, removed: 22, total 6
@@ -13,10 +13,10 @@ pub const Upstream = struct {
sock: std.posix.socket_t,
 
/// TODO ipv6
pub fn init(addr_ip: [4]u8) !Upstream {
pub fn init(addr_ip: [4]u8, port: u16) !Upstream {
const up: Upstream = .{
.addr = .{ .in = .{ .sa = .{
.port = nativeToBig(u16, 53),
.port = nativeToBig(u16, port),
.addr = bytesToValue(u32, &addr_ip),
} } },
.sock = try std.posix.socket(std.posix.AF.INET, std.posix.SOCK.DGRAM, 0),
@@ -24,8 +24,16 @@ pub const Upstream = struct {
return up;
}
 
pub fn connect(up: Upstream) !void {
pub fn connect(addr_ip: [4]u8, port: u16) !Upstream {
const up: Upstream = try .init(addr_ip, port);
try std.posix.connect(up.sock, &up.addr.any, up.addr.getOsSockLen());
return up;
}
 
pub fn listen(addr_ip: [4]u8, port: u16) !Upstream {
const up: Upstream = try .init(addr_ip, port);
try std.posix.bind(up.sock, &up.addr.any, up.addr.getOsSockLen());
return up;
}
 
pub fn send(upstrm: Upstream, data: []const u8) !void {
@@ -38,6 +46,16 @@ pub const Upstream = struct {
const icnt = try std.posix.recv(upstrm.sock, buffer, 0);
return icnt;
}
 
pub fn recvFrom(upstrm: Upstream, buffer: []u8, addr: *std.net.Address) !usize {
if (buffer.len < 512) return error.BufferTooSmall;
var src_len: u32 = undefined;
const cnt = try std.posix.recvfrom(upstrm.sock, buffer, 0, &addr.any, &src_len);
if (cnt >= 512) {
@panic("packet too large");
}
return cnt;
}
};
 
pub const Message = struct {
 
src/server.zig added: 28, removed: 22, total 6
@@ -5,13 +5,7 @@ pub fn main() !void {
_ = arg;
}
 
const addr: std.net.Address = .{ .in = .{ .sa = .{
.port = @byteSwap(@as(u16, 53)),
.addr = std.mem.readInt(u32, &[4]u8{ 127, 0, 0, 1 }, .little),
} } };
const sock = try std.posix.socket(std.posix.AF.INET, std.posix.SOCK.DGRAM, 0);
const bind = try std.posix.bind(sock, &addr.any, addr.getOsSockLen());
_ = bind;
const upstream: DNS.Upstream = try .listen(.{ 127, 0, 0, 1 }, 53);
 
// nobody on my machine
if (std.os.linux.getuid() == 0) {
@@ -26,14 +20,9 @@ pub fn main() !void {
//var request: [1024]u8 = undefined;
//const msgsize = try msg.write(&request);
 
var src_addr: std.net.Address = .{ .any = undefined };
var src_len: u32 = 0;
 
var addr: std.net.Address = .{ .any = undefined };
var buffer: [1024]u8 = undefined;
const icnt = try std.posix.recvfrom(sock, &buffer, 0, &src_addr.any, &src_len);
if (icnt >= 512) {
@panic("packet too large");
}
const icnt = try upstream.recvFrom(&buffer, &addr);
std.debug.print("received {}\n", .{icnt});
std.debug.print("data {any}\n", .{buffer[0..icnt]});