SchOS/cmd/socktest/main.c
Nexoniarz c362e308d0 net: the socket layer stops saying yes to things it did not do, and ping works
setsockopt was `return 0;` and getsockopt wrote a zero for whatever was asked.
The comment said it was so a server setting SO_REUSEADDR and treating failure as
fatal would not fail. That trade is the wrong way round: a caller told "no"
adapts, a caller told "yes" changes its behaviour on the strength of it -- sets
SO_RCVTIMEO and then blocks forever in a read it believes will time out, sets
TCP_NODELAY and reports latency numbers that measure Nagle. The failure is
silent, remote from the call, and indistinguishable from a bug in the stack.

Six options are honoured now and everything else is ENOPROTOOPT. SO_REUSEADDR,
SO_KEEPALIVE, SO_BROADCAST and TCP_NODELAY reach lwIP's pcb; SO_SNDBUF/SO_RCVBUF
are accepted and report the real size on read. SO_REUSEADDR is implemented rather
than refused precisely because of the original comment's concern -- it is the one
option a server really does set and really does check.

accept4 becomes its own table entry rather than an alias for accept. It has to
be: accept takes three arguments, so a shared handler reading a fourth register
reads whatever the caller last left there and invents a SOCK_NONBLOCK out of
stack litter. SOCK_CLOEXEC and SOCK_NONBLOCK are now honoured by socket(),
socketpair() and accept4() -- a dropped CLOEXEC leaks a listening socket across
every exec, and a dropped NONBLOCK has the caller block forever in what it
believes is a poll loop.

ICMP ping sockets: socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP), on lwIP's raw API,
with the callback stripping the variable-length IP header. Only echo replies are
eaten, and that restriction is load-bearing -- raw_input runs before lwIP's own
icmp_input, so consuming every ICMP message would swallow the echo *requests* and
this machine would silently stop answering pings from outside.

Loopback, so 127.0.0.1 is a real destination. LWIP_NETIF_LOOPBACK is the half
that is easy to miss: without it a packet addressed to an interface's own address
goes out of the wire and never comes back. With NO_SYS=1 nothing drains the
loopback queue, so the network thread calls netif_poll_all().

cmd/ping is first-party rather than toybox's, and the reason is a limitation not
a preference: toybox reads replies with recvmsg(2) and wants the TTL through an
IP_RECVTTL control message, and SchOS has neither. recvmsg is item 1 of
docs/plan/foundations.md, where it is wanted for SCM_RIGHTS anyway, and should
not be rushed to make one applet run.

Two bugs found on the way. Every AF_INET socket failed with ENFILE until DHCP
bound, because inet_new() demanded an *address* before handing out a socket and
reported it as "file table overflow"; net_is_ready() (lwIP up) is now distinct
from net_is_up() (DHCP bound). And that bug was hiding a bad test: socktest
asserted "AF_INET is refused, not faked", true when written, false since AF_INET
landed, and green the whole time because the suite runs before DHCP binds and the
ENFILE made the refusal look real. Fixing the kernel is what turned it red.

Verified: ping to 127.0.0.1, localhost, the gateway, 1.1.1.1 and 9.9.9.9, all
0% loss; socktest ALL CHECKS PASSED with ten new checks, including a setsockopt
round trip and an unknown option that must be refused -- a permissive stub cannot
pass both at once.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VQ7Qx8E1q1M1bbCq8QLHS2
2026-09-12 17:14:35 +02:00

426 lines
13 KiB
C

// socktest -- prove that Unix domain sockets carry data between processes.
//
// Every part of a socket is invisible from a return value. bind() returning 0
// proves nothing; a socket layer that accepts every call and drops every byte
// would pass a test built on return codes alone. So each check here has one
// process write and a *different* process read, and compares the bytes.
//
// socktest run every check
//
// Prints one line per check and a final verdict a script can grep for.
#include "types.h"
#include "user.h"
#include "socket.h"
static int failures;
static void
puts_(const char *s)
{
int n = 0;
while (s[n]) n++;
write(1, (void*)s, n);
}
static void
putn_(int v)
{
char buf[12];
int i = 0, neg = 0;
if (v < 0) { neg = 1; v = -v; }
if (v == 0) buf[i++] = '0';
while (v) { buf[i++] = '0' + (v % 10); v /= 10; }
if (neg) buf[i++] = '-';
while (i--) write(1, &buf[i], 1);
}
static void
check(int ok, const char *what)
{
puts_(ok ? " [ok] " : " FAIL: ");
puts_(what);
puts_("\n");
if (!ok) failures++;
}
static int
streq(const char *a, const char *b)
{
while (*a && *a == *b) { a++; b++; }
return *a == *b;
}
// Fill a sockaddr_un and return the length to pass to bind/connect: the
// family plus the path plus its NUL, which is what musl computes and what the
// kernel side is written to expect.
static int
mkaddr(struct sockaddr_un *sa, const char *path)
{
int i = 0;
for (i = 0; i < UNIX_PATH_MAX - 1 && path[i]; i++)
sa->sun_path[i] = path[i];
sa->sun_path[i] = '\0';
sa->sun_family = AF_UNIX;
return (int)sizeof(sa->sun_family) + i + 1;
}
// ---------------------------------------------------------------------------
// 1. A round trip over a named socket, between two processes.
// ---------------------------------------------------------------------------
static void
test_roundtrip(void)
{
struct sockaddr_un sa;
int len = mkaddr(&sa, "/tmp/socktest");
int srv, pid, cli, n;
char buf[64];
puts_("named socket, two processes:\n");
srv = socket(AF_UNIX, SOCK_STREAM, 0);
check(srv >= 0, "socket() returns a descriptor");
if (srv < 0) return;
check(bind(srv, (struct sockaddr *)&sa, len) == 0, "bind() to /tmp/socktest");
check(listen(srv, 4) == 0, "listen()");
// A second bind to the same name must be refused, or two servers can
// silently steal each other's clients.
{
int dup_ = socket(AF_UNIX, SOCK_STREAM, 0);
check(bind(dup_, (struct sockaddr *)&sa, len) < 0,
"a second bind to the same name is refused");
close(dup_);
}
pid = fork();
if (pid == 0) {
// Child: the client. Connects, sends a question, reads the answer.
int c = socket(AF_UNIX, SOCK_STREAM, 0);
char reply[64];
int r;
close(srv);
if (connect(c, (struct sockaddr *)&sa, len) < 0) {
puts_(" FAIL: child connect()\n");
exit();
}
write(c, "ping", 4);
r = read(c, reply, sizeof(reply) - 1);
if (r < 0) r = 0;
reply[r] = '\0';
if (!streq(reply, "pong"))
puts_(" FAIL: child did not receive pong\n");
close(c);
exit();
}
cli = accept(srv, 0, 0);
check(cli >= 0, "accept() returns a connection");
if (cli < 0) { close(srv); wait(); return; }
n = read(cli, buf, sizeof(buf) - 1);
if (n < 0) n = 0;
buf[n] = '\0';
check(streq(buf, "ping"), "server read the client's bytes");
check(write(cli, "pong", 4) == 4, "server replied on the same socket");
close(cli);
close(srv);
wait();
}
// ---------------------------------------------------------------------------
// 2. Errors that must actually be errors.
// ---------------------------------------------------------------------------
static void
test_errors(void)
{
struct sockaddr_un sa;
int len = mkaddr(&sa, "/tmp/nobody-listening");
int s;
puts_("error paths:\n");
s = socket(AF_UNIX, SOCK_STREAM, 0);
check(connect(s, (struct sockaddr *)&sa, len) < 0,
"connect() to a name nobody bound fails");
close(s);
// This used to assert that AF_INET was *refused*, which was true when this
// file was written and stopped being true the day AF_INET landed. It kept
// passing anyway, and the reason is worth keeping: socktest runs seconds
// after boot, DHCP had not bound yet, and inet_new() refused every socket
// until it did -- reported as ENFILE. So the check saw "< 0" and called it
// a pass for a reason that had nothing to do with what it was testing.
//
// Two lessons, both already written down elsewhere in this tree and both
// learned again here: a test that asserts a *failure* has to say which
// failure, and a green suite is not evidence until something has checked
// that it can go red.
//
// What is left are the refusals that are unconditionally true, whatever the
// link is doing.
check(socket(99, SOCK_STREAM, 0) < 0, "an unknown address family is refused");
check(socket(AF_INET, SOCK_STREAM, 99) < 0,
"AF_INET with a nonsense protocol is refused");
check(socket(AF_UNIX, SOCK_DGRAM, 0) < 0, "SOCK_DGRAM is refused, not faked");
// read/write on a plain file descriptor must not be mistaken for a socket,
// and socket calls on one must be refused.
check(listen(1, 4) < 0, "listen() on a non-socket fd fails");
}
// ---------------------------------------------------------------------------
// 3. End-of-file. A reader whose peer closes must be told, not left hanging.
// ---------------------------------------------------------------------------
static void
test_eof(void)
{
struct sockaddr_un sa;
int len = mkaddr(&sa, "/tmp/socktest-eof");
int srv, cli, pid, n;
char buf[16];
puts_("end of file:\n");
srv = socket(AF_UNIX, SOCK_STREAM, 0);
bind(srv, (struct sockaddr *)&sa, len);
listen(srv, 4);
pid = fork();
if (pid == 0) {
int c = socket(AF_UNIX, SOCK_STREAM, 0);
close(srv);
connect(c, (struct sockaddr *)&sa, len);
write(c, "x", 1);
close(c); // the peer goes away with the byte still unread
exit();
}
cli = accept(srv, 0, 0);
n = read(cli, buf, sizeof(buf));
check(n == 1, "the byte sent before close() is still delivered");
n = read(cli, buf, sizeof(buf));
check(n == 0, "the next read returns 0 rather than blocking");
close(cli);
close(srv);
wait();
}
// ---------------------------------------------------------------------------
// 4. socketpair: bidirectional, no name, no listener.
// ---------------------------------------------------------------------------
static void
test_socketpair(void)
{
int sv[2], n;
char buf[16];
puts_("socketpair:\n");
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) < 0) {
check(0, "socketpair() succeeds");
return;
}
check(1, "socketpair() succeeds");
write(sv[0], "a", 1);
n = read(sv[1], buf, sizeof(buf));
check(n == 1 && buf[0] == 'a', "0 -> 1 carries a byte");
write(sv[1], "b", 1);
n = read(sv[0], buf, sizeof(buf));
check(n == 1 && buf[0] == 'b', "1 -> 0 carries a byte, on the same pair");
close(sv[0]);
close(sv[1]);
}
// ---------------------------------------------------------------------------
// 5. A message longer than the socket buffer, so the writer has to block and
// the reader has to drain in more than one go.
// ---------------------------------------------------------------------------
#define BIG 12000
static void
test_big(void)
{
int sv[2], pid, got = 0, ok = 1, i;
static char out[BIG], in[BIG];
puts_("a transfer larger than the buffer:\n");
for (i = 0; i < BIG; i++)
out[i] = (char)('A' + (i % 26));
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) < 0) {
check(0, "socketpair() for the big transfer");
return;
}
pid = fork();
if (pid == 0) {
int sent = 0, r;
close(sv[1]);
while (sent < BIG) {
r = write(sv[0], out + sent, BIG - sent);
if (r <= 0) break;
sent += r;
}
close(sv[0]);
exit();
}
close(sv[0]);
while (got < BIG) {
int r = read(sv[1], in + got, BIG - got);
if (r <= 0) break;
got += r;
}
close(sv[1]);
wait();
check(got == BIG, "every byte arrived");
if (got != BIG) {
puts_(" got ");
putn_(got);
puts_(" of ");
putn_(BIG);
puts_("\n");
}
for (i = 0; i < got; i++)
if (in[i] != out[i]) { ok = 0; break; }
check(ok, "and in the right order");
}
// ---------------------------------------------------------------------------
// Socket options.
//
// Both calls used to succeed unconditionally: setsockopt was `return 0;` and
// getsockopt wrote a zero for whatever was asked. So the only check that proves
// anything is a *round trip* -- set a value, read it back, and see the value
// rather than a zero -- plus one option that must be refused. A stub passes
// "does setsockopt return 0"; it cannot pass both of these at once.
// ---------------------------------------------------------------------------
#define T_SOL_SOCKET 1
#define T_SO_REUSEADDR 2
#define T_SO_TYPE 3
#define T_SO_RCVBUF 8
#define T_SO_NOSUCH 0x7ffe // not an option Linux defines either
static void
test_sockopt(void)
{
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
int val, len;
puts_("-- socket options\n");
if (fd < 0) { check(0, "socket()"); return; }
// SO_TYPE must report what this socket actually is, not zero.
val = -1; len = sizeof(val);
check(getsockopt(fd, T_SOL_SOCKET, T_SO_TYPE, &val, &len) == 0 &&
val == SOCK_STREAM, "getsockopt SO_TYPE says SOCK_STREAM");
// The round trip. A stub that ignores the set and zeroes the get fails here.
val = 1;
check(setsockopt(fd, T_SOL_SOCKET, T_SO_REUSEADDR, &val, sizeof(val)) == 0,
"setsockopt SO_REUSEADDR accepted");
val = -1; len = sizeof(val);
check(getsockopt(fd, T_SOL_SOCKET, T_SO_REUSEADDR, &val, &len) == 0 &&
val == 1, "getsockopt SO_REUSEADDR reads back 1");
// And back off again, so the answer is not just "always non-zero".
val = 0;
setsockopt(fd, T_SOL_SOCKET, T_SO_REUSEADDR, &val, sizeof(val));
val = -1; len = sizeof(val);
check(getsockopt(fd, T_SOL_SOCKET, T_SO_REUSEADDR, &val, &len) == 0 &&
val == 0, "and reads back 0 once cleared");
// A real buffer size, not zero.
val = -1; len = sizeof(val);
check(getsockopt(fd, T_SOL_SOCKET, T_SO_RCVBUF, &val, &len) == 0 && val > 0,
"getsockopt SO_RCVBUF is a real size");
// The refusal. This is the half that a permissive stub cannot fake.
val = 1;
check(setsockopt(fd, T_SOL_SOCKET, T_SO_NOSUCH, &val, sizeof(val)) < 0,
"setsockopt of an unknown option is refused");
len = sizeof(val);
check(getsockopt(fd, T_SOL_SOCKET, T_SO_NOSUCH, &val, &len) < 0,
"getsockopt of an unknown option is refused");
close(fd);
}
// ---------------------------------------------------------------------------
// SOCK_NONBLOCK, end to end.
//
// Checking that socket() accepts the flag proves nothing -- it was accepted
// before, and discarded. What proves it is a read that *returns* on a socket
// with nothing in it, where a blocking socket would sleep forever.
// ---------------------------------------------------------------------------
#define T_SOCK_NONBLOCK 0x800
#define T_F_GETFL 3
#define T_O_NONBLOCK 04000
static void
test_nonblock(void)
{
int sv[2];
char c;
puts_("-- SOCK_NONBLOCK\n");
if (socketpair(AF_UNIX, SOCK_STREAM | T_SOCK_NONBLOCK, 0, sv) < 0) {
check(0, "socketpair(SOCK_NONBLOCK)");
return;
}
check((fcntl(sv[0], T_F_GETFL, 0) & T_O_NONBLOCK) != 0,
"fcntl(F_GETFL) reports O_NONBLOCK");
// Nothing has been written, so a blocking read would never return. If this
// test hangs, the flag was dropped -- which is exactly what it used to be.
check(read(sv[0], &c, 1) < 0, "read on an empty non-blocking socket returns");
// And it still carries data, so the flag did not break the socket.
write(sv[1], "x", 1);
c = 0;
check(read(sv[0], &c, 1) == 1 && c == 'x', "and still delivers a byte");
close(sv[0]);
close(sv[1]);
}
int
main(void)
{
puts_("socktest: unix domain sockets\n");
test_roundtrip();
test_errors();
test_eof();
test_socketpair();
test_big();
test_sockopt();
test_nonblock();
if (failures == 0)
puts_("socktest: ALL CHECKS PASSED\n");
else {
puts_("socktest: ");
putn_(failures);
puts_(" CHECK(S) FAILED\n");
}
exit();
}