From c8c22bfc511ac65036cd8f8462e0a01757eb4372 Mon Sep 17 00:00:00 2001 From: user Date: Fri, 17 Jul 2026 02:03:05 +0200 Subject: net: real IP stack, milestone A - ICMP echo (you can ping a Game Boy) Start of an actual TCP/IP stack on gbos (TLS stays in a proxy). netd is a userland IP responder over SLIP: our address is 10.0.0.2, the SLIP peer 10.0.0.1. It parses IPv4 headers, answers ICMP echo requests, and rebuilds the packet with correct IP + ICMP checksums (RFC 1071 one's-complement sum, carry-folded - works fine on the SM83). c/netd.c + register; tools/gateway.py gains --mode ping: it crafts ICMP echo requests over SLIP and verifies the replies. Verified: `netd` answers 4 pings, gateway reports reply from 10.0.0.2 with cksum=ok for each. Next: UDP, then TCP. --- c/netd.c | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 c/netd.c (limited to 'c') diff --git a/c/netd.c b/c/netd.c new file mode 100644 index 0000000..36435d4 --- /dev/null +++ b/c/netd.c @@ -0,0 +1,47 @@ +#include "netlib.h" +/* netd - a minimal IP stack over SLIP. Milestone A: answer ICMP echo (ping). + Our address is 10.0.0.2; the SLIP peer (gateway) is 10.0.0.1. + + Everything is done on raw byte arrays so endianness is explicit (network + byte order = big-endian): field[hi], field[lo]. */ + +/* Internet checksum (RFC 1071): 16-bit one's-complement sum with carry fold. */ +static unsigned int cksum(unsigned char *d, unsigned char len) { + unsigned int sum = 0, w; + unsigned char i = 0; + while ((unsigned char)(i + 1) < len) { + w = ((unsigned int)d[i] << 8) | d[i + 1]; + sum += w; if (sum < w) sum++; + i += 2; + } + if (len & 1) { w = (unsigned int)d[len - 1] << 8; sum += w; if (sum < w) sum++; } + return ~sum; +} + +void main(void) { + unsigned char pkt[128]; + unsigned char len, ihl, i, t; + unsigned int c; + puts("netd: IP/ICMP up (10.0.0.2)"); nl(); + for (;;) { + len = slip_recv((char *)pkt, 127); + if (len < 28) continue; /* IP(20) + ICMP(8) minimum */ + if ((pkt[0] >> 4) != 4) continue; /* IPv4 only */ + ihl = (pkt[0] & 0x0f) << 2; + if (pkt[9] != 1) continue; /* protocol 1 = ICMP */ + if (pkt[ihl] != 8) continue; /* ICMP type 8 = echo request */ + + /* turn the request into a reply, in place */ + for (i = 0; i < 4; i++) { t = pkt[12 + i]; pkt[12 + i] = pkt[16 + i]; pkt[16 + i] = t; } + pkt[8] = 64; /* reset TTL */ + pkt[ihl] = 0; /* ICMP type -> echo reply */ + pkt[ihl + 2] = 0; pkt[ihl + 3] = 0; /* recompute ICMP checksum */ + c = cksum(pkt + ihl, (unsigned char)(len - ihl)); + pkt[ihl + 2] = (unsigned char)(c >> 8); pkt[ihl + 3] = (unsigned char)c; + pkt[10] = 0; pkt[11] = 0; /* recompute IP header checksum */ + c = cksum(pkt, ihl); + pkt[10] = (unsigned char)(c >> 8); pkt[11] = (unsigned char)c; + + slip_send((char *)pkt, len); + } +} -- cgit v1.3.1-sl0p