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
const std = @import("std");
const posix = std.posix;
/// enable TCP keepalive so reads don't block forever when a peer
/// disappears without FIN/RST (network partition, crash, power loss).
/// detection time: 10s idle + 5s × 2 probes = 20s.
pub fn configure(fd: posix.socket_t) void {
const builtin = @import("builtin");
set(fd, posix.SOL.SOCKET, posix.SO.KEEPALIVE, 1) catch return;
const tcp: i32 = @intCast(posix.IPPROTO.TCP);
if (builtin.os.tag == .linux) {
set(fd, tcp, posix.TCP.KEEPIDLE, 10) catch return;
} else if (builtin.os.tag == .macos) {
set(fd, tcp, posix.TCP.KEEPALIVE, 10) catch return;
}
set(fd, tcp, posix.TCP.KEEPINTVL, 5) catch return;
set(fd, tcp, posix.TCP.KEEPCNT, 2) catch return;
}
/// std.posix.setsockopt treats BADF, NOTSOCK, and INVAL as unreachable. On a
/// connection socket the peer can reset it between the handshake and this
/// call, and macOS then reports INVAL. Keepalive is advisory, and the next
/// read reports a dead socket, so treat those as a socket to leave alone.
fn set(fd: posix.socket_t, level: i32, optname: u32, value: i32) error{Unavailable}!void {
const bytes = std.mem.toBytes(value);
switch (posix.errno(posix.system.setsockopt(fd, level, optname, &bytes, bytes.len))) {
.SUCCESS => {},
else => return error.Unavailable,
}
}
test "keepalive setup on a socket that already died is a no-op" {
const io = std.testing.io;
var listener = try (std.Io.net.IpAddress{ .ip4 = .loopback(0) }).listen(io, .{ .reuse_address = true });
const fd = listener.socket.handle;
listener.deinit(io);
configure(fd);
}