فهرست منبع

Add curl (DNS + TCP + HTTP GET); grow the kernel region to 0x49000

The first active protocols on top of the UDP/ICMP stack:

dns.c/h: a minimal resolver -- one recursive A query over UDP to the
resolver learned from DHCP option 6 (`netdns <a.b.c.d>` overrides it,
the gateway is the fallback), three sends 1 s apart, a compression-
pointer aware answer walk, up to four A records, distinct NXDOMAIN/
SERVFAIL/truncated reporting.  `netdns` shows/sets the server,
`lookup <name>` resolves.

tcp.c/h: a client-only TCP subset -- SYN/SYN-ACK/ACK with an MSS option
(1460 advertised, the peer's parsed out of the SYN-ACK), 4096-byte
window, in-order receive with an ACK per segment, ~1 s retransmits (3
tries) for everything it sends, FIN/RST handling.  Out-of-order data is
dropped and left to the peer's retransmit; no congestion control, no
window scaling, no fragment reassembly; incoming checksums are not
validated, same as the UDP path.  The caller owns the NIC
(netdev_acquire), like the other net commands.

curl.c: `curl http://host[:port]/path` -- numeric hosts skip DNS, the
rest goes through dns.c; ARP for the next hop (net_next_hop picks the
gateway off-subnet); HTTP/1.0 GET with Host/User-Agent/Connection:
close; dumps the status line, headers and body (chunked decoded,
Content-Length bound, '\r' filtered); redirects are reported, not
followed.  No TLS: https:// is rejected with a message.

net.c/h: net_get_dns/net_set_dns, net_next_hop and the shared
net_arp_resolve (lifted from netping's static helpers), plus
net_checksum_tcp (IPv4 pseudo-header).  netdev.c/h: one shared
1518-byte rx scratch (netdev_rx_scratch) for the ARP/DNS/TCP receive
paths so none of them carries a frame buffer in BSS.

dhcp.c: parse option 6 (already requested, previously discarded) and
apply it after the ACK; `netinfo` prints dns=.  terminal.c: the three
new commands + help entries (tab completion picks them up).
Makefile: dns.o/tcp.o/curl.o and a `run-net` target (ne2k_pci on
QEMU's user network -> DHCP/DNS/NAT, host at 10.0.2.2).

Kernel region: the new code pushed _end past 0x44000, so grow by
another 0x5000 -- bound 0x49000, stack 0x49800, API 0x49F00, user load
0x4A000 (kernel.ld, vesa_stage.S, kexec_tramp.S, tss.c, process.c,
run.c, serial_recv.c, run_api.h, user.ld, bootstrap.c, comments in
kexec.*, colors.c, radeon.c, uhci.c, netcmd.c).  PROGRAM_LOAD_MAX is
clamped to 0x6000 so a program cannot run into the 0x50000 stack pool.

AGENTS.md: the new commands, modules, run-net target and addresses.

Verified on QEMU (slirp + ne2k_pci): DHCP learns dns 10.0.2.3,
`lookup example.com` returns both A records, `curl
http://10.0.2.2:8000/HELLO.TXT` fetches from a host python server and
`curl http://example.com/` gets a 200 with the body; also verified on
the board over the network.
Johannes Zellner 1 ماه پیش
والد
کامیت
abc9dc1b04
29فایلهای تغییر یافته به همراه1809 افزوده شده و 50 حذف شده
  1. 28 16
      AGENTS.md
  2. 19 3
      Makefile
  3. 4 4
      bootstrap.c
  4. 1 1
      colors.c
  5. 564 0
      curl.c
  6. 20 5
      dhcp.c
  7. 348 0
      dns.c
  8. 14 0
      dns.h
  9. 1 1
      kernel.ld
  10. 1 1
      kexec.c
  11. 1 1
      kexec.h
  12. 1 1
      kexec_tramp.S
  13. 157 0
      net.c
  14. 21 0
      net.h
  15. 11 1
      netcmd.c
  16. 10 0
      netdev.c
  17. 7 0
      netdev.h
  18. 1 1
      process.c
  19. 1 1
      radeon.c
  20. 4 4
      run.c
  21. 1 1
      run_api.h
  22. 3 3
      serial_recv.c
  23. 446 0
      tcp.c
  24. 41 0
      tcp.h
  25. 99 1
      terminal.c
  26. 1 1
      tss.c
  27. 1 1
      uhci.c
  28. 2 2
      user.ld
  29. 1 1
      vesa_stage.S

+ 28 - 16
AGENTS.md

@@ -13,6 +13,7 @@ make all        # floppy.img usb.img final.bin root.img
 make run        # boot floppy.img + root.img in QEMU (fallback: qemu-system-x86_64)
 make run-usb    # boot usb.img as an IDE disk
 make run-uhci   # like `make run` but with a UHCI controller + USB mouse
+make run-net    # like `make run` + a PCI NE2000 NIC on QEMU's user network (slirp; DHCP/DNS/NAT)
 make run-ahci   # like `make run` + an ICH9 AHCI controller and a 512 MB SATA disk (sata0)
 make test-usb   # headless USB mouse/keyboard regression tests (QEMU + python3)
 make clean
@@ -47,10 +48,10 @@ make clean
 | `0x1000`  | E820 memory map (`struct e820_map`, written by `vesa_stage.S`, parsed by `mm.c`) |
 | `0x3000`  | UHCI frame list (1024 × 4 B, 4 KB-aligned; `uhci.c`) |
 | `0x4000`  | ISA DMA buffer, one sector (`disk.c`) |
-| `0x44000` | Kernel upper bound (`kernel.ld` ASSERT) |
-| `0x44800` | Protected-mode stack top (`vesa_stage.S`, `kexec_tramp.S`) |
-| `0x44F00` | Program API struct (`PROGRAM_API_ADDR`, `run_api.h`) |
-| `0x45000` | User program load address (`run.c`, `user.ld`) |
+| `0x49000` | Kernel upper bound (`kernel.ld` ASSERT) |
+| `0x49800` | Protected-mode stack top (`vesa_stage.S`, `kexec_tramp.S`) |
+| `0x49F00` | Program API struct (`PROGRAM_API_ADDR`, `run_api.h`) |
+| `0x4A000` | User program load address (`run.c`, `user.ld`, max 0x6000 to the pool) |
 | `0x50000` | Fallback process stack pool (8 × 4 KB; primary stacks come from the frame allocator, ≥ `0x900000`, see `process.c`/`mm.c`) |
 | `0x58000` | kexec staging buffer (received kernel image, up to 0x3C200 B; ends below the VGA window) |
 | `0x100000`| VGA shadow buffer (`VGA_SHADOW_BASE`, `vga.h`) |
@@ -115,13 +116,21 @@ make clean
 - **Network**: `netdev.c/h` — NIC driver registry (`struct netdev`, first probe
   wins; drivers: `r8168.c` RTL8111/8168 (PCIe, polled, C+ mode) and `ne2000.c`
   RTL8029 (QEMU/ISA)). `net.c` — ARP + ICMP echo, IPv4/UDP send + parse helpers,
-  frame decode, `net_checksum()`. `dhcp.c` — minimal DHCP client (DISCOVER →
+  shared ARP resolution (`net_arp_resolve`) and routing (`net_next_hop`), frame
+  decode, `net_checksum()`/`net_checksum_tcp()`. `dhcp.c` — minimal DHCP client
+  (DISCOVER →
   OFFER → REQUEST → ACK; runs at boot when a NIC is present, 3 s budget, keeps
-  the static address when no server answers; `dhcp` re-runs it). `netcmd.c` —
-  the
+  the static address when no server answers; `dhcp` re-runs it; learns the DNS
+  server from option 6). `netcmd.c` — the
   `netinfo`/`netrecv`/`netsend`/`netip`/`dhcp`/`ping`/`netping`/`netregs`
-  commands.  Static IP default `192.168.178.240`, mask/gateway learned from
-  DHCP (off-subnet `netping` goes via the router).
+  commands.  `dns.c/h` — a minimal resolver (one recursive A query over UDP,
+  name-compression aware; `netdns` shows/sets the server, `lookup <name>`
+  resolves).  `tcp.c/h` — a minimal TCP *client* (connect/send/recv/close,
+  in-order receive, one segment of retransmit; the caller owns the NIC).
+  `curl.c` — the `curl` command: `http://host[:port]/path` GET with DNS, ARP,
+  HTTP/1.0 request and a dumped status/headers/body (no TLS, no redirects,
+  chunked decoded).  Static IP default `192.168.178.240`, mask/gateway learned
+  from DHCP (off-subnet traffic goes via the router).
 - **Hot-reload (kexec)**: `kexec.c/h`, `kexec_tramp.S`, `bootstrap.c`, and the
   host-side `kexec_send.c` — reload the kernel over serial without rebooting
   (C-light: reuses the current framebuffer, re-runs `kernel_main`).
@@ -148,7 +157,7 @@ make clean
   scan generation counter.
 - **Power/idle**: `idle.c` — `mwait` C-states, `hlt` fallback.
 - **User programs**: `run.c`, `run_api.h`, `prog.c`, `space.c` — raw binaries at
-  `0x45000`, API function-pointer struct at `0x44F00`.  `prog`/`space` are
+  `0x4A000`, API function-pointer struct at `0x49F00`.  `prog`/`space` are
   **embedded in the kernel image** (`prog_embed.o`/`space_embed.o`, like
   `hello.elf`), so `make dev`/`make net-dev` update them too and a board with
   no readable filesystem can still run them: `run <name>` and the `prog`/
@@ -170,11 +179,14 @@ DHCP client), `ping` (responds to ARP/ICMP for our IP for 30 s),
 `netping <a.b.c.d>` (active ARP + ICMP echo with RTT, via the gateway when the
 target is off-subnet), `netloop` (PHY loopback TX/RX self-test), `netreset`
 (full NIC re-init), `netlog <text>` (one UDP datagram to port 19290),
-`netconsole on|off|host <a.b.c.d>` (the debug-output mirror, see below) and
-`netregs` (register dump, decoded ISR + counters).  On boot, if a NIC is
-present, a DHCP client runs with a 3 s budget (requesting the current address)
-and falls back to the static default when no server answers.  The board also
-answers ARP/ICMP for its IP while idle.
+`netconsole on|off|host <a.b.c.d>` (the debug-output mirror, see below)
+`netregs` (register dump, decoded ISR + counters), `netdns [a.b.c.d]` (show or
+set the resolver) and `lookup <name>` (one DNS A query).  `curl <url>` fetches
+`http://host[:port]/path` with a minimal HTTP/1.0 GET and dumps the status
+line, headers and body (no TLS, no redirects; numeric hosts skip DNS).  On
+boot, if a NIC is present, a DHCP client runs with a 3 s budget (requesting the
+current address) and falls back to the static default when no server answers.
+The board also answers ARP/ICMP for its IP while idle.
 `lspci` lists every PCI function (one line each); with a filter (`lspci 8168`,
 `lspci 02`) it also prints BAR details, type and size for matching functions.
 `peek <addr> [len]` hex-dumps memory (identity map, so MMIO registers too).
@@ -478,7 +490,7 @@ Caveats:
 
 - Pixels are written directly to the LFB; WM full redraws overwrite them but
   the 1 Hz refresh brings them back.
-- Info rows cost ~0.5 KB BSS; the kernel must stay under the `0x44000`
+- Info rows cost ~0.5 KB BSS; the kernel must stay under the `0x49000`
   boundary (`kernel.ld` ASSERT).
 
 ## Conventions & gotchas

+ 19 - 3
Makefile

@@ -13,7 +13,7 @@ ASFLAGS  = --32
 BOOT_LDFLAGS   = -T linker.ld -nostdlib -m elf_i386
 KERNEL_LDFLAGS = -T kernel.ld -nostdlib -m elf_i386
 
-.PHONY: all clean run run-floppy run-usb run-uhci run-ahci test-usb run-serial floppy usb flash space prog bootstrap dev net-dev netmon monitor
+.PHONY: all clean run run-floppy run-usb run-uhci run-net run-ahci test-usb run-serial floppy usb flash space prog bootstrap dev net-dev netmon monitor
 
 all: floppy.img usb.img final.bin root.img
 
@@ -167,6 +167,15 @@ netlog.o: netlog.c netlog.h net.h netdev.h timer.h
 dhcp.o: dhcp.c dhcp.h io.h net.h netdev.h timer.h
 	$(CC) $(CFLAGS) -o $@ $<
 
+dns.o: dns.c dns.h io.h timer.h netdev.h net.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+tcp.o: tcp.c tcp.h io.h timer.h netdev.h net.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+curl.o: curl.c io.h timer.h netdev.h net.h dns.h tcp.h
+	$(CC) $(CFLAGS) -o $@ $<
+
 netdev.o: netdev.c netdev.h ne2000.h
 	$(CC) $(CFLAGS) -o $@ $<
 
@@ -263,7 +272,7 @@ syscall_stub.o: syscall_stub.S
 mem.o: mem.c mm.h io.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-kernel.elf: vesa_stage.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o mem.o screen.o io.o rtc.o terminal.o wm.o reboot.o poweroff.o disk.o fat.o ls.o cat.o run.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o vga_copy.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o clock.o colors.o display.o cpuinfo.o mouse.o mousecmd.o uhci.o ohci.o usb.o usbhid.o lsusb.o kdbg.o blkdev.o ata.o ahci.o fatdetect.o storage.o fatformat.o format.o vfs.o idle.o kexec.o kexec_tramp.o dbg.o save.o rm.o mkdir.o rmdir.o lspci.o peek.o ne2000.o r8168.o netdev.o netcmd.o net.o netkexec.o netlog.o dhcp.o hello_embed.o prog_embed.o space_embed.o
+kernel.elf: vesa_stage.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o mem.o screen.o io.o rtc.o terminal.o wm.o reboot.o poweroff.o disk.o fat.o ls.o cat.o run.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o vga_copy.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o clock.o colors.o display.o cpuinfo.o mouse.o mousecmd.o uhci.o ohci.o usb.o usbhid.o lsusb.o kdbg.o blkdev.o ata.o ahci.o fatdetect.o storage.o fatformat.o format.o vfs.o idle.o kexec.o kexec_tramp.o dbg.o save.o rm.o mkdir.o rmdir.o lspci.o peek.o ne2000.o r8168.o netdev.o netcmd.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o curl.o hello_embed.o prog_embed.o space_embed.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $^
 
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
@@ -411,6 +420,13 @@ run-uhci: floppy.img root.img
 	qemu-system-i386 -M pc -device piix3-usb-uhci -device usb-mouse -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy 2>/dev/null || \
 	qemu-system-x86_64 -M pc -device piix3-usb-uhci -device usb-mouse -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy
 
+# Network variant: a PCI NE2000 (RTL8029, the driver's QEMU match) on QEMU's
+# user-mode network (slirp).  DHCP/DNS come from slirp, the host is 10.0.2.2
+# (e.g. `python3 -m http.server` + `curl http://10.0.2.2:8000/` in a window).
+run-net: floppy.img root.img
+	qemu-system-i386 -M pc -device pci-ohci -device usb-mouse -device ne2k_pci,netdev=n0 -netdev user,id=n0 -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy 2>/dev/null || \
+	qemu-system-x86_64 -M pc -device pci-ohci -device usb-mouse -device ne2k_pci,netdev=n0 -netdev user,id=n0 -drive file=floppy.img,format=raw,if=floppy -drive file=root.img,format=raw,if=floppy
+
 # SATA/AHCI variant: an ICH9 AHCI controller with a test disk on port 0.
 # The disk image lives outside the repo and is created on first use; boot
 # stays on the floppy (order=a), the SATA disk shows up as sata0.
@@ -507,4 +523,4 @@ net-dev: kernel.bin netkexec_send
 	./netkexec_send $(BOARD_IP) $(NETKEXEC_PORT) 0x$$entry kernel.bin
 
 clean:
-	rm -f boot.o vesa_stage.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o mem.o screen.o io.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o ls.o cat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o vga_copy.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o clock.o colors.o display.o cpuinfo.o mouse.o mousecmd.o uhci.o ohci.o usb.o usbhid.o lsusb.o kdbg.o blkdev.o ata.o ahci.o fatdetect.o storage.o fatformat.o format.o vfs.o idle.o kexec.o kexec_tramp.o dbg.o save.o rm.o mkdir.o rmdir.o lspci.o peek.o ne2000.o r8168.o netdev.o netcmd.o net.o netkexec.o netlog.o dhcp.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img prog.o prog.elf prog.bin space.o space.elf space.bin hello.elf hello_embed.o prog_embed.o space_embed.o bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor
+	rm -f boot.o vesa_stage.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o mem.o screen.o io.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o ls.o cat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o vga_copy.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o clock.o colors.o display.o cpuinfo.o mouse.o mousecmd.o uhci.o ohci.o usb.o usbhid.o lsusb.o kdbg.o blkdev.o ata.o ahci.o fatdetect.o storage.o fatformat.o format.o vfs.o idle.o kexec.o kexec_tramp.o dbg.o save.o rm.o mkdir.o rmdir.o lspci.o peek.o ne2000.o r8168.o netdev.o netcmd.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o curl.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img prog.o prog.elf prog.bin space.o space.elf space.bin hello.elf hello_embed.o prog_embed.o space_embed.o bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor

+ 4 - 4
bootstrap.c

@@ -3,8 +3,8 @@
  * full hardware access: it switches COM1 to 115200, receives a new kernel image,
  * copies it over 0x7E00, and jumps to its kernel_main.
  *
- * Self-contained: no kernel symbols, no run_api dependency. We live at 0x45000
- * (outside the 0x7E00..0x44000 kernel region), so we can overwrite the kernel
+ * Self-contained: no kernel symbols, no run_api dependency. We live at 0x4A000
+ * (outside the 0x7E00..0x49000 kernel region), so we can overwrite the kernel
  * directly from our own code without a relocated trampoline.
  *
  * Wire protocol (host -> us), after we emit 'R':
@@ -18,7 +18,7 @@
 #define UART_BASE        0x3F8
 #define STAGE_ADDR       0x58000
 #define KERNEL_LOAD_ADDR 0x7E00
-#define BOOT_STACK       0x44800
+#define BOOT_STACK       0x49800
 #define MAGIC            0x4345584B /* "KXEC" little-endian */
 #define MAX_SIZE         0x3C200
 
@@ -148,7 +148,7 @@ void _start(void)
 	}
 
 	/* Copy staged kernel over 0x7E00, then jump to its kernel_main.
-	 * We live at 0x45000, outside the overwritten region, so this is safe. */
+	 * We live at 0x4A000, outside the overwritten region, so this is safe. */
 	setup_flat_gdt();
 	for (i = 0; i < size; i++)
 		((volatile unsigned char *)KERNEL_LOAD_ADDR)[i] =

+ 1 - 1
colors.c

@@ -16,7 +16,7 @@
 /* Precomputed hue-to-RGB lookup table. Packed as 0x00BBGGRR for fast 32-bit load.
  * The hue cycle is RAINBOW_FULL entries, but the table is decimated by
  * LUT_STEP: a 4-hue step is ~1.5% of a color segment and invisible, and the
- * smaller table keeps the kernel image under the 0x44000 memory-bound. */
+ * smaller table keeps the kernel image under the 0x49000 memory-bound. */
 #define LUT_STEP      4
 #define LUT_SIZE      (RAINBOW_FULL / LUT_STEP)
 

+ 564 - 0
curl.c

@@ -0,0 +1,564 @@
+/* curl: fetch one http:// URL with a minimal HTTP/1.0 GET and dump the
+ * status line, the headers and the body to the terminal.
+ *
+ * Deliberately small: no TLS, no redirect following (a Location header is
+ * reported), no gzip; a chunked response is decoded.  Uses the DNS resolver
+ * (dns.c) and the TCP client (tcp.c); the NIC is owned for the whole run. */
+
+#include "io.h"
+#include "timer.h"
+#include "netdev.h"
+#include "net.h"
+#include "dns.h"
+#include "tcp.h"
+
+#define URL_HOST_MAX 128
+#define URL_PATH_MAX 128
+#define REQ_MAX      512
+#define LINE_MAX_C   320
+#define READER_MAX   1024
+
+#define IDLE_TIMEOUT_MS  10000
+#define TOTAL_TIMEOUT_MS 60000
+
+struct url {
+	char host[URL_HOST_MAX];
+	char path[URL_PATH_MAX];
+	unsigned int port;
+};
+
+/* ---- small print helpers ---- */
+
+static void put_dec(unsigned int v)
+{
+	char b[12];
+	int i = 0;
+
+	if (v == 0) {
+		io_putchar('0');
+		return;
+	}
+	while (v) {
+		b[i++] = (char)('0' + (v % 10));
+		v /= 10;
+	}
+	while (i)
+		io_putchar(b[--i]);
+}
+
+static void put_ip(const unsigned char *ip)
+{
+	unsigned int i;
+
+	for (i = 0; i < 4; i++) {
+		if (i)
+			io_putchar('.');
+		put_dec(ip[i]);
+	}
+}
+
+static int starts_with(const char *s, const char *prefix)
+{
+	unsigned int i = 0;
+
+	while (prefix[i]) {
+		if (s[i] != prefix[i])
+			return 0;
+		i++;
+	}
+	return 1;
+}
+
+/* ---- URL parsing ---- */
+
+/* Parse http://host[:port][/path]; 0 on success, -1 error, -2 https. */
+static int url_parse(const char *s, struct url *u)
+{
+	const char *p = s, *h;
+	unsigned int i;
+
+	if (starts_with(s, "https://"))
+		return -2;
+	if (starts_with(s, "http://"))
+		p += 7;
+	else {
+		/* An unsupported scheme like ftp:// is easy to spot: a "://"
+		 * within the first few characters. */
+		for (i = 0; s[i] && i < 8; i++) {
+			if (s[i] == ':' && s[i + 1] == '/' && s[i + 2] == '/')
+				return -1;
+			if (s[i] == '/')
+				break;
+		}
+	}
+
+	h = p;
+	while (*p && *p != '/' && *p != ':')
+		p++;
+	if (p == h || (unsigned int)(p - h) >= URL_HOST_MAX)
+		return -1;
+	for (i = 0; i < (unsigned int)(p - h); i++)
+		u->host[i] = h[i];
+	u->host[i] = '\0';
+
+	u->port = 80;
+	if (*p == ':') {
+		unsigned int port = 0;
+
+		p++;
+		if (*p < '0' || *p > '9')
+			return -1;
+		while (*p >= '0' && *p <= '9') {
+			port = port * 10 + (unsigned int)(*p - '0');
+			if (port > 65535)
+				return -1;
+			p++;
+		}
+		if (port == 0 || (*p != '/' && *p != '\0'))
+			return -1;
+		u->port = port;
+	}
+
+	if (*p == '/') {
+		i = 0;
+		while (p[i]) {
+			if (i + 1 >= URL_PATH_MAX)
+				return -1;
+			u->path[i] = p[i];
+			i++;
+		}
+		u->path[i] = '\0';
+	} else {
+		u->path[0] = '/';
+		u->path[1] = '\0';
+	}
+	return 0;
+}
+
+/* ---- request building ---- */
+
+static unsigned int req_app(char *buf, unsigned int pos, const char *s)
+{
+	while (*s && pos < REQ_MAX - 1)
+		buf[pos++] = *s++;
+	return pos;
+}
+
+static unsigned int req_app_dec(char *buf, unsigned int pos, unsigned int v)
+{
+	char b[12];
+	int i = 0;
+
+	if (v == 0) {
+		if (pos < REQ_MAX - 1)
+			buf[pos++] = '0';
+		return pos;
+	}
+	while (v) {
+		b[i++] = (char)('0' + (v % 10));
+		v /= 10;
+	}
+	while (i) {
+		i--;
+		if (pos < REQ_MAX - 1)
+			buf[pos++] = b[i];
+	}
+	return pos;
+}
+
+/* ---- HTTP response reader (a refillable line/byte stream) ---- */
+
+struct reader {
+	struct tcp_conn *conn;
+	unsigned char buf[READER_MAX];
+	unsigned int len, pos;
+	unsigned int total_deadline;
+	int eof;
+	int error;              /* 0, -1 timeout, -2 reset */
+};
+
+/* Returns 1 when new data (or EOF) is available, 0 on timeout/reset. */
+static int reader_fill(struct reader *r)
+{
+	unsigned int deadline, idle;
+	int n;
+
+	if (r->eof)
+		return 0;
+
+	idle = get_ticks_ms() + IDLE_TIMEOUT_MS;
+	deadline = idle < r->total_deadline ? idle : r->total_deadline;
+
+	n = tcp_recv(r->conn, r->buf, sizeof(r->buf), deadline);
+	if (n > 0) {
+		r->len = (unsigned int)n;
+		r->pos = 0;
+		return 1;
+	}
+	if (n == 0) {
+		r->eof = 1;
+		return 0;
+	}
+	r->error = n;
+	return 0;
+}
+
+static int reader_getc(struct reader *r)
+{
+	if (r->pos >= r->len) {
+		if (!reader_fill(r))
+			return -1;
+	}
+	return r->buf[r->pos++];
+}
+
+/* Read up to (not including) the next '\n'; -1 on stream error/EOF. */
+static int reader_readline(struct reader *r, char *out, unsigned int max)
+{
+	unsigned int n = 0;
+	int c;
+
+	for (;;) {
+		c = reader_getc(r);
+		if (c < 0) {
+			out[n] = '\0';
+			return (n == 0) ? -1 : (int)n;
+		}
+		if (c == '\n') {
+			out[n] = '\0';
+			return (int)n;
+		}
+		if (c == '\r')
+			continue;
+		if (n + 1 < max)
+			out[n++] = (char)c;
+	}
+}
+
+/* ---- HTTP pieces ---- */
+
+/* Case-insensitive match of a header name; line must continue with ':'. */
+static int hdr_match(const char *line, const char *name)
+{
+	unsigned int i;
+
+	for (i = 0; name[i]; i++) {
+		char a = line[i];
+
+		if (a >= 'A' && a <= 'Z')
+			a = (char)(a - 'A' + 'a');
+		if (a != name[i])
+			return 0;
+	}
+	return line[i] == ':';
+}
+
+static int parse_dec_after_colon(const char *line, unsigned int *val)
+{
+	unsigned int i = 0, v = 0;
+	int digits = 0;
+
+	while (line[i] && line[i] != ':')
+		i++;
+	if (line[i] != ':')
+		return 0;
+	i++;
+	while (line[i] == ' ' || line[i] == '\t')
+		i++;
+	while (line[i] >= '0' && line[i] <= '9') {
+		v = v * 10 + (unsigned int)(line[i] - '0');
+		digits = 1;
+		i++;
+	}
+	if (!digits)
+		return 0;
+	*val = v;
+	return 1;
+}
+
+static void copy_after_colon(const char *line, char *out, unsigned int max)
+{
+	unsigned int i = 0, j = 0;
+
+	while (line[i] && line[i] != ':')
+		i++;
+	if (line[i] == ':')
+		i++;
+	while (line[i] == ' ' || line[i] == '\t')
+		i++;
+	while (line[i] && j + 1 < max)
+		out[j++] = line[i++];
+	out[j] = '\0';
+}
+
+static int contains_ci(const char *hay, const char *needle)
+{
+	unsigned int i, j;
+
+	for (i = 0; hay[i]; i++) {
+		for (j = 0; needle[j]; j++) {
+			char a = hay[i + j];
+
+			if (a >= 'A' && a <= 'Z')
+				a = (char)(a - 'A' + 'a');
+			if (a != needle[j])
+				break;
+		}
+		if (!needle[j])
+			return 1;
+	}
+	return 0;
+}
+
+static unsigned int parse_status(const char *line)
+{
+	unsigned int i = 0, v = 0, digits = 0;
+
+	while (line[i] && line[i] != ' ')
+		i++;
+	if (line[i] == ' ')
+		i++;
+	while (line[i] >= '0' && line[i] <= '9') {
+		v = v * 10 + (unsigned int)(line[i] - '0');
+		digits++;
+		i++;
+	}
+	return digits == 3 ? v : 0;
+}
+
+/* Dump the body, filtering '\r'.  With have_limit, stop after limit bytes. */
+static unsigned int dump_body(struct reader *r, int have_limit,
+			      unsigned int limit)
+{
+	unsigned int n = 0;
+	int c;
+
+	for (;;) {
+		if (have_limit && n >= limit)
+			break;
+		c = reader_getc(r);
+		if (c < 0)
+			break;
+		if (c == '\r')
+			continue;
+		io_putchar((char)c);
+		n++;
+	}
+	return n;
+}
+
+/* Decode a chunked body (hex size line, data, CRLF; size 0 ends it). */
+static unsigned int dump_chunked(struct reader *r)
+{
+	unsigned int total = 0;
+	char line[64];
+
+	for (;;) {
+		unsigned int sz = 0, k = 0, i;
+		int hl = reader_readline(r, line, sizeof(line));
+
+		if (hl <= 0)
+			return total;
+		while (line[k]) {
+			char ch = line[k];
+			unsigned int d;
+
+			if (ch >= '0' && ch <= '9')
+				d = (unsigned int)(ch - '0');
+			else if (ch >= 'a' && ch <= 'f')
+				d = (unsigned int)(ch - 'a' + 10);
+			else if (ch >= 'A' && ch <= 'F')
+				d = (unsigned int)(ch - 'A' + 10);
+			else
+				break;
+			sz = sz * 16 + d;
+			k++;
+		}
+		if (k == 0) {
+			io_putstr("curl: bad chunk size\n");
+			return total;
+		}
+		if (sz == 0) {
+			/* trailer lines up to the empty line */
+			while (reader_readline(r, line, sizeof(line)) > 0)
+				;
+			return total;
+		}
+		for (i = 0; i < sz; i++) {
+			int c = reader_getc(r);
+
+			if (c < 0)
+				return total;
+			io_putchar((char)c);
+			total++;
+		}
+		reader_readline(r, line, sizeof(line));   /* the CRLF */
+	}
+}
+
+/* ---- the command ---- */
+
+void program_curl_main(const char *arg)
+{
+	netdev_acquire();
+	{
+		static struct url u;
+		static char req[REQ_MAX];
+		static struct reader r;
+		const struct netdev *nd = netdev_active();
+		unsigned char ip[4], hop[4], mac[6];
+		struct tcp_conn conn;
+		char line[LINE_MAX_C];
+		char location[128];
+		unsigned int n, status = 0, body = 0, content_len = 0;
+		int have_loc = 0, have_len = 0, chunked = 0, rv;
+
+		if (arg[0] == '\0') {
+			io_putstr("curl: usage curl <http://host[:port]/[path]>\n");
+			goto out;
+		}
+		rv = url_parse(arg, &u);
+		if (rv == -2) {
+			io_putstr("curl: https is not supported (no TLS)\n");
+			goto out;
+		}
+		if (rv != 0) {
+			io_putstr("curl: bad URL\n");
+			goto out;
+		}
+		if (!nd) {
+			io_putstr("curl: no NIC found\n");
+			goto out;
+		}
+		if (!net_is_configured()) {
+			io_putstr("curl: no IP address (run dhcp or netip)\n");
+			goto out;
+		}
+
+		io_putstr("curl: GET http://");
+		io_putstr(u.host);
+		if (u.port != 80) {
+			io_putstr(":");
+			put_dec(u.port);
+		}
+		io_putstr(u.path);
+		io_putchar('\n');
+
+		if (net_parse_ip(u.host, ip) != 0) {
+			if (dns_resolve(u.host, ip) != 0)
+				goto out;
+		}
+
+		net_next_hop(ip, hop);
+		if (net_arp_resolve(hop, mac) != 0) {
+			io_putstr("curl: no ARP reply from ");
+			put_ip(hop);
+			io_putchar('\n');
+			goto out;
+		}
+
+		rv = tcp_connect(mac, ip, u.port, &conn);
+		if (rv == -1) {
+			io_putstr("curl: connect timeout\n");
+			goto out;
+		}
+		if (rv == -2) {
+			io_putstr("curl: connection refused\n");
+			goto out;
+		}
+		if (rv != 0) {
+			io_putstr("curl: connect failed\n");
+			goto out;
+		}
+		io_putstr("curl: connected, sending request\n");
+
+		n = req_app(req, 0, "GET ");
+		n = req_app(req, n, u.path);
+		n = req_app(req, n, " HTTP/1.0\r\nHost: ");
+		n = req_app(req, n, u.host);
+		if (u.port != 80) {
+			n = req_app(req, n, ":");
+			n = req_app_dec(req, n, u.port);
+		}
+		n = req_app(req, n, "\r\nUser-Agent: nebos-curl/0.1\r\n"
+				    "Accept: */*\r\nConnection: close\r\n\r\n");
+		if (n > conn.peer_mss) {
+			io_putstr("curl: request too long\n");
+			goto out;
+		}
+		rv = tcp_send(&conn, req, n);
+		if (rv != 0) {
+			io_putstr("curl: request send failed\n");
+			goto out;
+		}
+
+		r.conn = &conn;
+		r.len = 0;
+		r.pos = 0;
+		r.eof = 0;
+		r.error = 0;
+		r.total_deadline = get_ticks_ms() + TOTAL_TIMEOUT_MS;
+
+		rv = reader_readline(&r, line, sizeof(line));
+		if (rv < 0) {
+			io_putstr("curl: no response (");
+			io_putstr(r.error == -2 ? "reset" : "timeout");
+			io_putstr(")\n");
+			goto out;
+		}
+		status = parse_status(line);
+		io_putstr("curl: ");
+		io_putstr(line);
+		io_putchar('\n');
+
+		for (;;) {
+			rv = reader_readline(&r, line, sizeof(line));
+			if (rv < 0) {
+				io_putstr("curl: connection lost in headers\n");
+				goto out;
+			}
+			if (rv == 0)
+				break;              /* end of headers */
+			io_putstr(line);
+			io_putchar('\n');
+			if (hdr_match(line, "content-length"))
+				have_len = parse_dec_after_colon(line, &content_len);
+			else if (hdr_match(line, "transfer-encoding") &&
+				 contains_ci(line, "chunked"))
+				chunked = 1;
+			else if (hdr_match(line, "location")) {
+				copy_after_colon(line, location,
+						 sizeof(location));
+				have_loc = 1;
+			}
+		}
+
+		if (status >= 300 && status < 400 && have_loc) {
+			io_putstr("curl: redirect not followed: ");
+			io_putstr(location);
+			io_putchar('\n');
+		}
+
+		io_putchar('\n');
+		if (chunked)
+			body = dump_chunked(&r);
+		else
+			body = dump_body(&r, have_len, content_len);
+		io_putchar('\n');
+
+		if (r.error == -2)
+			io_putstr("curl: connection reset\n");
+		else if (r.error == -1)
+			io_putstr("curl: timeout while reading body\n");
+
+		io_putstr("curl: ");
+		put_dec(body);
+		io_putstr(" bytes received, status ");
+		put_dec(status);
+		io_putstr("\n");
+
+		tcp_close(&conn);
+	}
+out:
+	netdev_release();
+}

+ 20 - 5
dhcp.c

@@ -149,6 +149,7 @@ static int dhcp_parse(const unsigned char *frame, unsigned int len,
 		      unsigned int xid, const unsigned char *my_mac,
 		      unsigned char *type, unsigned char yiaddr[4],
 		      unsigned char mask[4], unsigned char gw[4],
+		      unsigned char dns[4],
 		      unsigned int *lease, unsigned char server[4])
 {
 	const unsigned char *p;
@@ -176,6 +177,7 @@ static int dhcp_parse(const unsigned char *frame, unsigned int len,
 		yiaddr[i] = p[16 + i];
 		mask[i] = 0;
 		gw[i] = 0;
+		dns[i] = 0;
 		server[i] = 0;
 	}
 	*lease = 0;
@@ -212,6 +214,11 @@ static int dhcp_parse(const unsigned char *frame, unsigned int len,
 				for (i = 0; i < 4; i++)
 					gw[i] = p[o + 2 + i];
 			break;
+		case 6:                 /* DNS servers (first one wins) */
+			if (olen >= 4)
+				for (i = 0; i < 4; i++)
+					dns[i] = p[o + 2 + i];
+			break;
 		case 51:
 			if (olen >= 4)
 				*lease = rd32be(p + o + 2);
@@ -235,18 +242,19 @@ static int dhcp_wait(const struct netdev *nd, unsigned int xid,
 		     const unsigned char *my_mac, unsigned int deadline,
 		     unsigned char want, unsigned char yiaddr[4],
 		     unsigned char mask[4], unsigned char gw[4],
+		     unsigned char dns[4],
 		     unsigned int *lease, unsigned char server[4])
 {
 	while ((int)(get_ticks_ms() - deadline) < 0) {
 		unsigned char type;
-		unsigned char ryi[4], rmask[4], rgw[4], rserver[4];
+		unsigned char ryi[4], rmask[4], rgw[4], rdns[4], rserver[4];
 		unsigned int rlease;
 		int len = nd->rx(rxbuf, sizeof(rxbuf));
 
 		if (len < 0)
 			continue;
 		if (!dhcp_parse(rxbuf, (unsigned int)len, xid, my_mac, &type,
-				ryi, rmask, rgw, &rlease, rserver))
+				ryi, rmask, rgw, rdns, &rlease, rserver))
 			continue;
 		if (type == DHCP_NAK)
 			return -2;
@@ -259,6 +267,7 @@ static int dhcp_wait(const struct netdev *nd, unsigned int xid,
 				yiaddr[i] = ryi[i];
 				mask[i] = rmask[i];
 				gw[i] = rgw[i];
+				dns[i] = rdns[i];
 				server[i] = rserver[i];
 			}
 		}
@@ -277,7 +286,7 @@ int dhcp_run(unsigned int timeout_ms)
 	static const unsigned char zero_ip[4] = { 0, 0, 0, 0 };
 	const struct netdev *nd = netdev_active();
 	unsigned char my_mac[6], want_ip[4], current[4];
-	unsigned char yiaddr[4], mask[4], gw[4], server[4];
+	unsigned char yiaddr[4], mask[4], gw[4], dns[4], server[4];
 	unsigned int xid, start, deadline, tries;
 	unsigned int lease = 0;
 
@@ -313,7 +322,7 @@ int dhcp_run(unsigned int timeout_ms)
 			return -2;
 		}
 		if (dhcp_wait(nd, xid, my_mac, wait_until, DHCP_OFFER,
-			      yiaddr, mask, gw, &lease, server) == 0)
+			      yiaddr, mask, gw, dns, &lease, server) == 0)
 			break;
 		if ((int)(get_ticks_ms() - deadline) >= 0)
 			break;
@@ -348,7 +357,7 @@ int dhcp_run(unsigned int timeout_ms)
 			return -2;
 		}
 		r = dhcp_wait(nd, xid, my_mac, wait_until, DHCP_ACK,
-			      yiaddr, mask, gw, &lease, server);
+			      yiaddr, mask, gw, dns, &lease, server);
 		if (r == 0)
 			break;
 		if (r == -2) {          /* NAK: start over */
@@ -368,6 +377,8 @@ int dhcp_run(unsigned int timeout_ms)
 	}
 
 	net_configure(yiaddr, mask, gw);
+	if (dns[0] || dns[1] || dns[2] || dns[3])
+		net_set_dns(dns);
 	have_info = 1;
 	{
 		unsigned int i;
@@ -383,6 +394,10 @@ int dhcp_run(unsigned int timeout_ms)
 	put_ip(mask);
 	io_putstr(" gw ");
 	put_ip(gw);
+	if (dns[0] || dns[1] || dns[2] || dns[3]) {
+		io_putstr(" dns ");
+		put_ip(dns);
+	}
 	io_putstr(" lease ");
 	put_dec(lease);
 	io_putstr("s\n");

+ 348 - 0
dns.c

@@ -0,0 +1,348 @@
+/* Minimal DNS resolver: an A-record query over UDP (RFC 1035).
+ *
+ * One question, up to four answers, three sends one second apart.  Name
+ * compression is handled when skipping over the answer section; the reply's
+ * checksum is not validated, matching the rest of the stack (net_udp_send()
+ * sends with the UDP checksum disabled too).
+ *
+ * Polled like every other net command: the caller owns the NIC
+ * (netdev_acquire) while dns_resolve() runs. */
+
+#include "io.h"
+#include "timer.h"
+#include "netdev.h"
+#include "net.h"
+#include "dns.h"
+
+#define DNS_PORT        53
+#define DNS_MAX_ANSWERS 4
+#define DNS_RETRY_MS    1000
+#define DNS_RETRIES     3
+
+/* Query buffer: 12-byte header + a 255-byte name + qtype/qclass. */
+static unsigned char query_buf[12 + 260 + 4];
+
+static void put_dec(unsigned int v)
+{
+	char b[12];
+	int i = 0;
+
+	if (v == 0) {
+		io_putchar('0');
+		return;
+	}
+	while (v) {
+		b[i++] = (char)('0' + (v % 10));
+		v /= 10;
+	}
+	while (i)
+		io_putchar(b[--i]);
+}
+
+static void put_ip(const unsigned char *ip)
+{
+	unsigned int i;
+
+	for (i = 0; i < 4; i++) {
+		if (i)
+			io_putchar('.');
+		put_dec(ip[i]);
+	}
+}
+
+static int ip_eq(const unsigned char *a, const unsigned char *b)
+{
+	return a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3];
+}
+
+/* Encode a dotted name as DNS labels (no trailing dot needed); 0 on error. */
+static int dns_encode_name(const char *name, unsigned char *out,
+			   unsigned int max)
+{
+	const char *p = name;
+	unsigned int o = 0;
+
+	if (!*name)
+		return -1;
+	for (;;) {
+		const char *q = p;
+		unsigned int n = 0;
+
+		while (*q && *q != '.') {
+			q++;
+			n++;
+		}
+		if (n == 0 || n > 63)
+			return -1;
+		/* length byte + label + a possible terminator must fit */
+		if (o + 1 + n + 1 > max || o + 1 + n > 254)
+			return -1;
+		out[o++] = (unsigned char)n;
+		while (p < q)
+			out[o++] = (unsigned char)*p++;
+		if (!*p)
+			break;
+		p++;                    /* skip the '.' */
+		if (!*p)                /* trailing dot */
+			break;
+	}
+	out[o++] = 0;
+	return (int)o;
+}
+
+/* Skip one (possibly compressed) name; 0, or -1 when malformed. */
+static int dns_skip_name(const unsigned char *p, unsigned int plen,
+			 unsigned int *pos)
+{
+	while (*pos < plen) {
+		unsigned char b = p[*pos];
+
+		if (b == 0) {
+			(*pos)++;
+			return 0;
+		}
+		if ((b & 0xC0) == 0xC0) {
+			if (*pos + 2 > plen)
+				return -1;
+			*pos += 2;       /* pointer: nothing else to skip */
+			return 0;
+		}
+		if (b & 0xC0)
+			return -1;
+		if (*pos + 1 + b > plen)
+			return -1;
+		*pos += 1 + b;
+	}
+	return -1;
+}
+
+/* Check one frame as a reply to our query.  Returns:
+ *   1 = at least one A record (ip and extras filled),
+ *   0 = not our reply (keep waiting),
+ *  -1 = our reply but a DNS-level failure (already reported). */
+static int dns_parse(const unsigned char *frame, unsigned int len,
+		     unsigned short id, const unsigned char *server,
+		     unsigned char ip[4], unsigned char extra[DNS_MAX_ANSWERS][4],
+		     unsigned int *count)
+{
+	unsigned char s_ip[4], d_ip[4];
+	const unsigned char *p;
+	unsigned int sport, dport, plen, pos, qd, an, i;
+
+	if (!net_udp_parse(frame, len, s_ip, d_ip, &sport, &dport, &p, &plen))
+		return 0;
+	if (sport != DNS_PORT || !ip_eq(s_ip, server))
+		return 0;
+	if (plen < 12)
+		return 0;
+	if ((((unsigned int)p[0] << 8) | p[1]) != id)
+		return 0;
+	if (!(p[2] & 0x80))                      /* QR: must be a reply */
+		return 0;
+	if (p[2] & 0x02) {                       /* TC: truncated */
+		io_putstr("dns: reply truncated (TC)\n");
+		return -1;
+	}
+	switch (p[3] & 0x0F) {
+	case 0:
+		break;
+	case 3:
+		io_putstr("dns: no such name (NXDOMAIN)\n");
+		return -1;
+	case 2:
+		io_putstr("dns: server failure (SERVFAIL)\n");
+		return -1;
+	default:
+		io_putstr("dns: rcode ");
+		put_dec(p[3] & 0x0F);
+		io_putchar('\n');
+		return -1;
+	}
+
+	qd = ((unsigned int)p[4] << 8) | p[5];
+	an = ((unsigned int)p[6] << 8) | p[7];
+
+	pos = 12;
+	for (i = 0; i < qd; i++) {
+		if (dns_skip_name(p, plen, &pos) != 0 || pos + 4 > plen)
+			return 0;
+		pos += 4;                        /* qtype + qclass */
+	}
+
+	*count = 0;
+	for (i = 0; i < an; i++) {
+		unsigned int type, class_, rdlen;
+
+		if (dns_skip_name(p, plen, &pos) != 0 || pos + 10 > plen)
+			return 0;
+		type = ((unsigned int)p[pos] << 8) | p[pos + 1];
+		class_ = ((unsigned int)p[pos + 2] << 8) | p[pos + 3];
+		rdlen = ((unsigned int)p[pos + 8] << 8) | p[pos + 9];
+		pos += 10;
+		if (pos + rdlen > plen)
+			return 0;
+		if (type == 1 && class_ == 1 && rdlen == 4) {
+			unsigned int k;
+
+			if (*count == 0) {
+				for (k = 0; k < 4; k++)
+					ip[k] = p[pos + k];
+			} else if (*count < DNS_MAX_ANSWERS) {
+				for (k = 0; k < 4; k++)
+					extra[*count - 1][k] = p[pos + k];
+			}
+			(*count)++;
+		}
+		pos += rdlen;
+	}
+	return *count > 0 ? 1 : 0;
+}
+
+int dns_resolve(const char *name, unsigned char ip[4])
+{
+	unsigned char server[4], hop[4], server_mac[6];
+	unsigned char extra[DNS_MAX_ANSWERS][4];
+	unsigned char *rx_buf = netdev_rx_scratch();
+	const struct netdev *nd = netdev_active();
+	unsigned short id;
+	unsigned int sport, qlen, tries, count, i;
+	int r;
+
+	if (!nd) {
+		io_putstr("dns: no NIC found\n");
+		return -1;
+	}
+
+	net_get_dns(server);
+	if (!(server[0] || server[1] || server[2] || server[3])) {
+		/* Home routers usually proxy DNS for their clients. */
+		net_get_gateway(server);
+		if (!(server[0] || server[1] || server[2] || server[3])) {
+			io_putstr("dns: no resolver (run netdns <a.b.c.d>)\n");
+			return -1;
+		}
+	}
+
+	for (i = 0; i < 12; i++)
+		query_buf[i] = 0;
+	id = (unsigned short)(get_ticks_ms() ^
+			      ((unsigned int)(unsigned char)name[0] << 8) ^
+			      0x4E42);
+	query_buf[0] = (unsigned char)(id >> 8);
+	query_buf[1] = (unsigned char)id;
+	query_buf[2] = 0x01;                  /* RD=1: recursion desired */
+	query_buf[5] = 1;                     /* QDCOUNT=1 */
+	qlen = 12;
+	{
+		int n = dns_encode_name(name, query_buf + 12,
+					sizeof(query_buf) - 12 - 4);
+
+		if (n <= 0) {
+			io_putstr("dns: bad name\n");
+			return -1;
+		}
+		qlen += (unsigned int)n;
+	}
+	query_buf[qlen++] = 0;                /* QTYPE A */
+	query_buf[qlen++] = 1;
+	query_buf[qlen++] = 0;                /* QCLASS IN */
+	query_buf[qlen++] = 1;
+
+	sport = 45000 + (id & 0x0FFF);
+
+	net_next_hop(server, hop);
+	if (net_arp_resolve(hop, server_mac) != 0) {
+		io_putstr("dns: no ARP reply from ");
+		put_ip(hop);
+		io_putchar('\n');
+		return -1;
+	}
+
+	for (tries = 0; tries < DNS_RETRIES; tries++) {
+		unsigned int deadline = get_ticks_ms() + DNS_RETRY_MS;
+
+		if (net_udp_send(server_mac, server, sport, DNS_PORT,
+				 query_buf, qlen) != 0) {
+			io_putstr("dns: send failed\n");
+			return -1;
+		}
+
+		while ((int)(get_ticks_ms() - deadline) < 0) {
+			int len = nd->rx(rx_buf, NETDEV_FRAME_MAX);
+
+			if (len < 0)
+				continue;
+			r = dns_parse(rx_buf, (unsigned int)len, id, server,
+				      ip, extra, &count);
+			if (r < 0)
+				return -1;
+			if (r == 0)
+				continue;
+			io_putstr("dns: ");
+			io_putstr(name);
+			io_putstr(" -> ");
+			put_ip(ip);
+			for (i = 1; i < count && i < DNS_MAX_ANSWERS; i++) {
+				io_putstr(", ");
+				put_ip(extra[i - 1]);
+			}
+			io_putchar('\n');
+			return 0;
+		}
+	}
+
+	io_putstr("dns: no reply from ");
+	put_ip(server);
+	io_putchar('\n');
+	return -1;
+}
+
+/* ---- commands ---- */
+
+void program_netdns_main(const char *arg)
+{
+	unsigned char dns[4], gw[4];
+
+	if (arg[0] == '\0') {
+		net_get_dns(dns);
+		if (dns[0] || dns[1] || dns[2] || dns[3]) {
+			io_putstr("dns=");
+			put_ip(dns);
+			io_putchar('\n');
+			return;
+		}
+		net_get_gateway(gw);
+		io_putstr("dns: unset");
+		if (gw[0] || gw[1] || gw[2] || gw[3]) {
+			io_putstr(" (fallback: gateway ");
+			put_ip(gw);
+			io_putchar(')');
+		}
+		io_putchar('\n');
+		return;
+	}
+
+	if (net_parse_ip(arg, dns) != 0) {
+		io_putstr("netdns: usage netdns [a.b.c.d]\n");
+		return;
+	}
+
+	net_set_dns(dns);
+	io_putstr("dns set to ");
+	put_ip(dns);
+	io_putchar('\n');
+}
+
+void program_lookup_main(const char *arg)
+{
+	unsigned char ip[4];
+
+	if (arg[0] == '\0') {
+		io_putstr("lookup: usage lookup <name>\n");
+		return;
+	}
+
+	netdev_acquire();
+	dns_resolve(arg, ip);
+	netdev_release();
+}

+ 14 - 0
dns.h

@@ -0,0 +1,14 @@
+/* Minimal DNS resolver (A records over UDP, RFC 1035): see dns.c. */
+#ifndef DNS_H
+#define DNS_H
+
+/* Resolve `name` to an IPv4 address with a recursive query to the configured
+ * resolver (DHCP option 6, else the gateway).  Prints a `dns:` line.
+ * Returns 0 on success.  The caller must own the NIC (netdev_acquire). */
+int dns_resolve(const char *name, unsigned char ip[4]);
+
+/* `netdns [a.b.c.d]` (show/set the resolver) and `lookup <name>`. */
+void program_netdns_main(const char *arg);
+void program_lookup_main(const char *arg);
+
+#endif

+ 1 - 1
kernel.ld

@@ -17,4 +17,4 @@ SECTIONS
 	}
 	_end = .;
 }
-ASSERT(_end <= 0x44000, "Kernel too large would overwrite stack/DMA at 0x44000");
+ASSERT(_end <= 0x49000, "Kernel too large would overwrite stack/DMA at 0x49000");

+ 1 - 1
kexec.c

@@ -5,7 +5,7 @@
  * LFB are still valid) and jump straight to the new kernel's kernel_main,
  * which re-inits IDT/PIC/PIT/mouse/process/VGA-shadow/terminal from scratch.
  *
- * Because this code lives at 0x7E00..0x44000 (inside the region we overwrite),
+ * Because this code lives at 0x7E00..0x49000 (inside the region we overwrite),
  * the final "copy image to 0x7E00 and jump" is done by a small
  * position-independent trampoline relocated to 0x800 (below the kernel).
  *

+ 1 - 1
kexec.h

@@ -5,7 +5,7 @@
 void program_kexec_main(void);
 
 /* Staging buffer for a received kernel image, and the maximum image size
- * (the kernel region 0x7E00..0x44000).  Below the VGA window; see AGENTS.md. */
+ * (the kernel region 0x7E00..0x49000).  Below the VGA window; see AGENTS.md. */
 #define KEXEC_STAGE 0x58000
 #define KEXEC_LOAD  0x7E00
 #define KEXEC_MAX   0x3C200

+ 1 - 1
kexec_tramp.S

@@ -66,7 +66,7 @@ kexec_trampoline:
 	 * this the jump below can execute stale instructions. */
 	wbinvd
 
-	movl  $0x44800, %esp
+	movl  $0x49800, %esp
 	jmp   *%edx
 
 .globl kexec_trampoline_end

+ 157 - 0
net.c

@@ -4,10 +4,12 @@
 #include "io.h"
 #include "netdev.h"
 #include "net.h"
+#include "timer.h"
 
 static unsigned char my_ip[4] = { 192, 168, 178, 240 };
 static unsigned char my_mask[4];
 static unsigned char my_gw[4];
+static unsigned char my_dns[4];
 
 /* ---- small print helpers (framebuffer console) ---- */
 
@@ -84,6 +86,33 @@ unsigned short net_checksum(const void *data, unsigned int len)
 	return (unsigned short)(~sum);
 }
 
+/* TCP checksum: the IPv4 pseudo-header plus the segment. */
+unsigned short net_checksum_tcp(const unsigned char *src_ip,
+				const unsigned char *dst_ip,
+				const unsigned char *tcp, unsigned int len)
+{
+	const unsigned char *p = tcp;
+	unsigned int sum = 0, i;
+
+	for (i = 0; i < 4; i += 2)
+		sum += ((unsigned int)src_ip[i] << 8) | src_ip[i + 1];
+	for (i = 0; i < 4; i += 2)
+		sum += ((unsigned int)dst_ip[i] << 8) | dst_ip[i + 1];
+	sum += IPPROTO_TCP;             /* pseudo-header protocol (0x0006) */
+	sum += len;                     /* TCP length */
+
+	while (len > 1) {
+		sum += ((unsigned int)p[0] << 8) | p[1];
+		p += 2;
+		len -= 2;
+	}
+	if (len)
+		sum += (unsigned int)p[0] << 8;
+	while (sum >> 16)
+		sum = (sum & 0xFFFFu) + (sum >> 16);
+	return (unsigned short)(~sum);
+}
+
 /* ---- IP address config ---- */
 
 void net_set_ip(const unsigned char ip[4])
@@ -137,6 +166,46 @@ int net_is_configured(void)
 	return my_ip[0] || my_ip[1] || my_ip[2] || my_ip[3];
 }
 
+void net_get_dns(unsigned char dns[4])
+{
+	unsigned int i;
+
+	for (i = 0; i < 4; i++)
+		dns[i] = my_dns[i];
+}
+
+void net_set_dns(const unsigned char dns[4])
+{
+	unsigned int i;
+
+	for (i = 0; i < 4; i++)
+		my_dns[i] = dns ? dns[i] : 0;
+}
+
+void net_next_hop(const unsigned char dst[4], unsigned char hop[4])
+{
+	unsigned int i, off = 0;
+
+	for (i = 0; i < 4; i++)
+		hop[i] = dst[i];
+
+	/* Without a mask/gateway (manual netip) keep treating the target as
+	 * directly reachable, like netping does. */
+	if (!(my_mask[0] || my_mask[1] || my_mask[2] || my_mask[3]) ||
+	    !(my_gw[0] || my_gw[1] || my_gw[2] || my_gw[3]))
+		return;
+
+	for (i = 0; i < 4; i++) {
+		if ((dst[i] & my_mask[i]) != (my_ip[i] & my_mask[i])) {
+			off = 1;
+			break;
+		}
+	}
+	if (off)
+		for (i = 0; i < 4; i++)
+			hop[i] = my_gw[i];
+}
+
 int net_parse_ip(const char *s, unsigned char ip[4])
 {
 	unsigned int i, val = 0, nparts = 0;
@@ -286,6 +355,94 @@ int net_udp_parse(const unsigned char *f, unsigned int len,
 	return 1;
 }
 
+/* ---- ARP resolution (shared by the DNS resolver and the TCP client) ---- */
+
+/* ARP request "who has target? tell my_ip" -> 42-byte frame. */
+static unsigned int arp_build_request(const unsigned char *my_mac,
+				      const unsigned char *my_ip,
+				      const unsigned char *target_ip,
+				      unsigned char *out)
+{
+	unsigned char *a = out + 14;
+	unsigned int i;
+
+	for (i = 0; i < 6; i++)
+		out[i] = 0xFF;                        /* broadcast */
+	for (i = 0; i < 6; i++)
+		out[6 + i] = my_mac[i];
+	out[12] = 0x08;
+	out[13] = 0x06;
+	a[0] = 0; a[1] = 1;                           /* htype Ethernet */
+	a[2] = 0x08; a[3] = 0;                        /* ptype IPv4 */
+	a[4] = 6; a[5] = 4;
+	a[6] = 0; a[7] = 1;                           /* opcode request */
+	for (i = 0; i < 6; i++)                       /* sha */
+		a[8 + i] = my_mac[i];
+	for (i = 0; i < 4; i++)                       /* spa */
+		a[14 + i] = my_ip[i];
+	for (i = 0; i < 6; i++)                       /* tha */
+		a[18 + i] = 0;
+	for (i = 0; i < 4; i++)                       /* tpa */
+		a[24 + i] = target_ip[i];
+	return 42;
+}
+
+/* 1 + peer MAC if frame is an ARP reply from target_ip. */
+static int arp_parse_reply(const unsigned char *f, unsigned int len,
+			   const unsigned char *target_ip, unsigned char *mac)
+{
+	const unsigned char *a = f + 14;
+	unsigned int i;
+
+	if (len < 14 + 28)
+		return 0;
+	if ((((unsigned int)f[12] << 8) | f[13]) != ET_ARP)
+		return 0;
+	if ((((unsigned int)a[6] << 8) | a[7]) != 2)   /* opcode reply */
+		return 0;
+	if (a[4] != 6 || a[5] != 4)
+		return 0;
+	if (!ip_eq(a + 14, target_ip))                 /* sender IP == target */
+		return 0;
+	for (i = 0; i < 6; i++)
+		mac[i] = a[8 + i];
+	return 1;
+}
+
+int net_arp_resolve(const unsigned char *dst_ip, unsigned char mac[6])
+{
+	const struct netdev *nd = netdev_active();
+	unsigned char my_mac[6], my_ip[4];
+	unsigned char req[64];
+	unsigned char *rxbuf = netdev_rx_scratch();
+	unsigned int tries;
+
+	if (!nd || !nd->get_mac)
+		return -2;
+	nd->get_mac(my_mac);
+	net_get_ip(my_ip);
+
+	for (tries = 0; tries < 3; tries++) {
+		unsigned int deadline = get_ticks_ms() + 1000;
+		unsigned int reqlen = arp_build_request(my_mac, my_ip,
+							dst_ip, req);
+
+		if (nd->tx(req, reqlen) != 0)
+			return -2;
+
+		while ((int)(get_ticks_ms() - deadline) < 0) {
+			int len = nd->rx(rxbuf, NETDEV_FRAME_MAX);
+
+			if (len < 0)
+				continue;
+			if (arp_parse_reply(rxbuf, (unsigned int)len,
+					    dst_ip, mac))
+				return 0;
+		}
+	}
+	return -1;
+}
+
 /* ---- ethertype naming ---- */
 const char *net_ethertype_name(unsigned short et)
 {

+ 21 - 0
net.h

@@ -31,11 +31,32 @@ void net_get_mask(unsigned char mask[4]);
 void net_get_gateway(unsigned char gw[4]);
 int  net_is_configured(void);   /* ip != 0.0.0.0 */
 
+/* DNS resolver address (DHCP option 6 or the `netdns` command); zero when
+ * unknown.  Kept across net_set_ip()/net_configure() so a manual setting
+ * survives a dhcp run without option 6. */
+void net_get_dns(unsigned char dns[4]);
+void net_set_dns(const unsigned char dns[4]);
+
+/* Next hop towards dst: the gateway when dst is off-subnet and a gateway is
+ * known, else dst itself. */
+void net_next_hop(const unsigned char dst[4], unsigned char hop[4]);
+
+/* Resolve dst_ip's MAC by ARP (3 tries, 1 s apart), polling the active NIC.
+ * Returns 0 on success, -1 when no reply arrived, -2 on transmit error.
+ * The caller must own the NIC (netdev_acquire). */
+int net_arp_resolve(const unsigned char *dst_ip, unsigned char mac[6]);
+
 const char *net_ethertype_name(unsigned short et);
 
 /* Internet checksum (16-bit one's complement, network byte order). */
 unsigned short net_checksum(const void *data, unsigned int len);
 
+/* TCP checksum over the IPv4 pseudo-header (src/dst/proto/length) plus the
+ * TCP header and payload; result is in network byte order. */
+unsigned short net_checksum_tcp(const unsigned char *src_ip,
+				const unsigned char *dst_ip,
+				const unsigned char *tcp, unsigned int len);
+
 /* Largest UDP payload net_udp_send() accepts. */
 #define NET_UDP_MAX 1400
 

+ 11 - 1
netcmd.c

@@ -10,7 +10,7 @@
 
 /* Shared frame buffers (file scope, not stack: the 4 KB process stack can't
    hold a full-size frame, and keeping them out of BSS-as-much-as-possible
-   avoids bloating the kernel past its 0x44000 limit). Max Ethernet frame is
+   avoids bloating the kernel past its 0x49000 limit). Max Ethernet frame is
    1518 bytes (14 header + 1500 payload + 4 VLAN). */
 #define NET_FRAME_MAX 1518
 static unsigned char net_rx_buf[NET_FRAME_MAX];
@@ -99,6 +99,16 @@ void program_netinfo_main(void)
 		put_ip(gw);
 		io_putchar('\n');
 	}
+	{
+		unsigned char dns[4];
+
+		net_get_dns(dns);
+		if (dns[0] || dns[1] || dns[2] || dns[3]) {
+			io_putstr("dns=");
+			put_ip(dns);
+			io_putchar('\n');
+		}
+	}
 	if (dhcp_last_info(server, &lease)) {
 		io_putstr("dhcp: server ");
 		put_ip(server);

+ 10 - 0
netdev.c

@@ -14,6 +14,16 @@ static const struct netdev *active;
 static int probed;
 static unsigned int busy;
 
+/* Shared receive scratch: see netdev.h.  One buffer, reused by every protocol
+ * that polls frames (they never run at the same time: the NIC is owned by one
+ * command via netdev_acquire()). */
+static unsigned char rx_scratch[NETDEV_FRAME_MAX];
+
+unsigned char *netdev_rx_scratch(void)
+{
+	return rx_scratch;
+}
+
 void netdev_acquire(void)
 {
 	busy++;

+ 7 - 0
netdev.h

@@ -33,4 +33,11 @@ int  netdev_in_use(void);
 /* Fill the active NIC's MAC; -1 (and a zero MAC) when there is no NIC. */
 int netdev_get_mac(unsigned char mac[6]);
 
+/* One shared frame-receive scratch buffer (1518 bytes) for protocol code that
+ * just needs somewhere for nd->rx() to land.  Only valid while the caller
+ * owns the NIC, and only until the next rx().  Shared so the DNS/TCP/ARP
+ * paths don't each carry their own frame buffer in the kernel's BSS. */
+unsigned char *netdev_rx_scratch(void);
+#define NETDEV_FRAME_MAX 1518
+
 #endif

+ 1 - 1
process.c

@@ -118,7 +118,7 @@ void process_init(void)
 	procs[0].screen     = (void *)0;
 	procs[0].stack_base = 0;  /* bootstrap stack, never freed */
 	procs[0].cr3        = paging_current_cr3();
-	procs[0].kstack_top = 0x44800;  /* bootstrap stack top */
+	procs[0].kstack_top = 0x49800;  /* bootstrap stack top */
 	name_copy(procs[0].name, "wm");
 	current_pid = 0;
 }

+ 1 - 1
radeon.c

@@ -17,7 +17,7 @@
  *  - Cursor mode is RADEON_CRTC_CUR_MODE_24BPP (2) in bits 22:20.
  *
  * NOTE: the bitmap is written straight into VRAM.  Do not use a local
- * [16 KB] array -- the kernel stack is only 2 KB (0x44800..0x44000) and a
+ * [16 KB] array -- the kernel stack is only 2 KB (0x49800..0x49000) and a
  * 16 KB stack allocation overflows it.
  */
 

+ 4 - 4
run.c

@@ -1,4 +1,4 @@
-/* run command: load raw binary from a FAT filesystem to 0x45000 and execute.
+/* run command: load raw binary from a FAT filesystem to 0x4A000 and execute.
  * Usage: run /<device>/<file>. */
 
 #include "fat.h"
@@ -10,8 +10,8 @@
 #include "vga.h"
 #include "vfs.h"
 
-#define PROGRAM_LOAD_ADDR 0x45000
-#define PROGRAM_LOAD_MAX  0x9000   /* up to 0x4E000, below the 0x50000 stack pool */
+#define PROGRAM_LOAD_ADDR 0x4A000
+#define PROGRAM_LOAD_MAX  0x6000   /* up to 0x50000, below the stack pool */
 
 /* User programs embedded in the kernel image (like hello.elf): they travel
  * with `make dev`/`make net-dev`, so a board with no readable filesystem can
@@ -147,7 +147,7 @@ void program_run_main(const char *filename)
 	((void (*)(void))PROGRAM_LOAD_ADDR)();
 }
 
-/* run serial: execute the binary already loaded at 0x45000 via serial_recv. */
+/* run serial: execute the binary already loaded at 0x4A000 via serial_recv. */
 
 void program_run_serial_main(const char *arg)
 {

+ 1 - 1
run_api.h

@@ -3,7 +3,7 @@
 #ifndef RUN_API_H
 #define RUN_API_H
 
-#define PROGRAM_API_ADDR 0x44F00
+#define PROGRAM_API_ADDR 0x49F00
 #define IO_KEY_ESC       0x1B
 #define IO_KEY_SPACE     0x20
 #define IO_KEY_LEFT      0x100

+ 3 - 3
serial_recv.c

@@ -1,11 +1,11 @@
-/* Serial receive command: receives a binary via serial into 0x45000. */
+/* Serial receive command: receives a binary via serial into 0x4A000. */
 
 #include "io.h"
 #include "serial.h"
 #include "bin_recv.h"
 
-#define PROGRAM_LOAD_ADDR 0x45000
-#define PROGRAM_LOAD_MAX  0x9000   /* up to 0x4E000, below the 0x50000 stack pool */
+#define PROGRAM_LOAD_ADDR 0x4A000
+#define PROGRAM_LOAD_MAX  0x6000   /* up to 0x50000, below the stack pool */
 
 unsigned int serial_recv_size;
 

+ 446 - 0
tcp.c

@@ -0,0 +1,446 @@
+/* Minimal TCP client: see tcp.h. */
+
+#include "io.h"
+#include "timer.h"
+#include "netdev.h"
+#include "net.h"
+#include "tcp.h"
+
+/* TCP flags. */
+#define TCP_FIN 0x01
+#define TCP_SYN 0x02
+#define TCP_RST 0x04
+#define TCP_PSH 0x08
+#define TCP_ACK 0x10
+
+#define TCP_MSS_OURS  1460
+#define TCP_WINDOW    4096
+#define TCP_RETRY_MS  1000
+#define TCP_RETRIES   3
+
+/* Frame buffers are file scope: a 4 KB process stack cannot hold them.  The
+ * receive side uses the shared frame scratch (netdev_rx_scratch()). */
+static unsigned char tx_frame[14 + 20 + 20 + TCP_MSS_OURS];
+
+/* Payload of a segment larger than the caller's buffer is held here, so no
+ * bytes are lost; at most one segment can be outstanding. */
+static unsigned char hold_buf[TCP_MSS_OURS];
+static unsigned int hold_len;
+static unsigned int hold_pos;
+
+static unsigned int rd16(const unsigned char *p)
+{
+	return ((unsigned int)p[0] << 8) | p[1];
+}
+
+static void wr16(unsigned char *p, unsigned int v)
+{
+	p[0] = (unsigned char)(v >> 8);
+	p[1] = (unsigned char)v;
+}
+
+static unsigned int rd32(const unsigned char *p)
+{
+	return ((unsigned int)p[0] << 24) | ((unsigned int)p[1] << 16) |
+	       ((unsigned int)p[2] << 8) | p[3];
+}
+
+static void wr32(unsigned char *p, unsigned int v)
+{
+	p[0] = (unsigned char)(v >> 24);
+	p[1] = (unsigned char)(v >> 16);
+	p[2] = (unsigned char)(v >> 8);
+	p[3] = (unsigned char)v;
+}
+
+/* Build and transmit one segment.  `seq` is the sequence of the first byte
+ * (for SYN/FIN that is the flag's own sequence).  Returns 0 / -1 (tx). */
+static int tcp_send_segment(struct tcp_conn *c, unsigned char flags,
+			    unsigned int seq, unsigned int ack,
+			    const unsigned char *payload, unsigned int len,
+			    int with_mss)
+{
+	const struct netdev *nd = netdev_active();
+	unsigned char my_mac[6], my_ip[4];
+	unsigned char *ip = tx_frame + 14;
+	unsigned char *tcp = ip + 20;
+	unsigned short cs;
+	unsigned int total, optlen = 0, i;
+
+	if (!nd)
+		return -1;
+	nd->get_mac(my_mac);
+	net_get_ip(my_ip);
+
+	/* Ethernet. */
+	for (i = 0; i < 6; i++)
+		tx_frame[i] = c->dst_mac[i];
+	for (i = 0; i < 6; i++)
+		tx_frame[6 + i] = my_mac[i];
+	tx_frame[12] = 0x08;
+	tx_frame[13] = 0x00;
+
+	/* IPv4 header (IHL 5, no options). */
+	total = 20 + 20 + (with_mss ? 4 : 0) + len;
+	for (i = 0; i < 20; i++)
+		ip[i] = 0;
+	ip[0] = 0x45;
+	wr16(ip + 2, total);
+	ip[8] = 64;                       /* TTL */
+	ip[9] = IPPROTO_TCP;
+	for (i = 0; i < 4; i++)
+		ip[12 + i] = my_ip[i];
+	for (i = 0; i < 4; i++)
+		ip[16 + i] = c->dst_ip[i];
+	cs = net_checksum(ip, 20);
+	wr16(ip + 10, cs);
+
+	/* TCP header (+ MSS option on SYN). */
+	if (with_mss) {
+		tcp[20] = 2;              /* kind: MSS */
+		tcp[21] = 4;              /* length */
+		wr16(tcp + 22, TCP_MSS_OURS);
+		optlen = 4;
+	}
+	wr16(tcp + 0, c->sport);
+	wr16(tcp + 2, c->dport);
+	wr32(tcp + 4, seq);
+	wr32(tcp + 8, ack);
+	tcp[12] = (unsigned char)((5 + optlen / 4) << 4);
+	tcp[13] = flags;
+	wr16(tcp + 14, TCP_WINDOW);
+	wr16(tcp + 16, 0);                /* checksum */
+	wr16(tcp + 18, 0);                /* urgent pointer */
+	for (i = 0; i < len; i++)
+		tcp[20 + optlen + i] = payload[i];
+
+	cs = net_checksum_tcp(my_ip, c->dst_ip, tcp, 20 + optlen + len);
+	wr16(tcp + 16, cs);
+
+	return nd->tx(tx_frame, 14 + total);
+}
+
+/* One received segment. */
+struct tcp_seg {
+	unsigned int  seq, ack;
+	unsigned char flags;
+	const unsigned char *data;
+	unsigned int  len;
+	const unsigned char *tcp;   /* for option parsing */
+	unsigned int  doff;
+};
+
+/* Parse one frame as a TCP segment from the peer.  Returns 1 on match.
+ * Incoming checksums are not validated (same as the UDP path). */
+static int tcp_parse(const unsigned char *f, unsigned int flen,
+		     const unsigned char *peer_ip,
+		     unsigned int peer_port, unsigned int local_port,
+		     struct tcp_seg *s)
+{
+	const unsigned char *ip = f + 14;
+	const unsigned char *tcp;
+	unsigned char my_ip[4];
+	unsigned int i, ihl, ip_len, doff;
+
+	if (flen < 14 + 20)
+		return 0;
+	if ((((unsigned int)f[12] << 8) | f[13]) != ET_IPV4)
+		return 0;
+	if ((ip[0] >> 4) != 4)
+		return 0;
+	ihl = (unsigned int)(ip[0] & 0x0F) * 4;
+	if (ihl < 20 || ip[9] != IPPROTO_TCP)
+		return 0;
+	/* Fragments are not reassembled: MF or a nonzero offset. */
+	if ((ip[6] & 0x3F) != 0 || ip[7] != 0)
+		return 0;
+	ip_len = rd16(ip + 2);
+	if (ip_len < ihl + 20 || ip_len > flen - 14)
+		return 0;
+
+	net_get_ip(my_ip);
+	for (i = 0; i < 4; i++) {
+		if (ip[12 + i] != peer_ip[i])
+			return 0;
+		if (ip[16 + i] != my_ip[i])
+			return 0;
+	}
+
+	tcp = ip + ihl;
+	if (rd16(tcp + 0) != peer_port || rd16(tcp + 2) != local_port)
+		return 0;
+	doff = (unsigned int)(tcp[12] >> 4) * 4;
+	if (doff < 20 || ihl + doff > ip_len)
+		return 0;
+
+	s->seq = rd32(tcp + 4);
+	s->ack = rd32(tcp + 8);
+	s->flags = tcp[13];
+	s->data = tcp + doff;
+	s->len = ip_len - ihl - doff;
+	s->tcp = tcp;
+	s->doff = doff;
+	return 1;
+}
+
+/* Parse the peer's MSS option (default stays when absent); 1 if present. */
+static int tcp_parse_mss(const unsigned char *tcp, unsigned int doff,
+			 unsigned int *mss)
+{
+	unsigned int o = 20;
+
+	while (o < doff) {
+		unsigned char kind = tcp[o];
+
+		if (kind == 0)                    /* end of options */
+			return 0;
+		if (kind == 1) {                  /* NOP */
+			o++;
+			continue;
+		}
+		if (o + 1 >= doff)
+			return 0;
+		if (tcp[o + 1] < 2 || o + tcp[o + 1] > doff)
+			return 0;
+		if (kind == 2 && tcp[o + 1] == 4) {
+			*mss = rd16(tcp + o + 2);
+			return 1;
+		}
+		o += tcp[o + 1];
+	}
+	return 0;
+}
+
+int tcp_connect(const unsigned char *dst_mac, const unsigned char *dst_ip,
+		unsigned int dport, struct tcp_conn *c)
+{
+	const struct netdev *nd = netdev_active();
+	unsigned char *rxbuf = netdev_rx_scratch();
+	unsigned int tries, i;
+
+	if (!nd || !net_is_configured())
+		return -3;
+
+	for (i = 0; i < 6; i++)
+		c->dst_mac[i] = dst_mac[i];
+	for (i = 0; i < 4; i++)
+		c->dst_ip[i] = dst_ip[i];
+	c->dport = dport;
+	c->sport = 0xC000u | (get_ticks_ms() & 0x3FFFu);
+	c->snd_una = c->snd_nxt = (get_ticks_ms() << 16) ^ 0x5EED0000u;
+	c->rcv_nxt = 0;
+	c->peer_mss = 536;
+	c->peer_fin = 0;
+	hold_len = hold_pos = 0;
+
+	for (tries = 0; tries < TCP_RETRIES; tries++) {
+		unsigned int deadline = get_ticks_ms() + TCP_RETRY_MS;
+
+		if (tcp_send_segment(c, TCP_SYN, c->snd_nxt, 0, 0, 0, 1) != 0)
+			return -3;
+
+		while ((int)(get_ticks_ms() - deadline) < 0) {
+			struct tcp_seg s;
+			int len = nd->rx(rxbuf, NETDEV_FRAME_MAX);
+
+			if (len < 0)
+				continue;
+			if (!tcp_parse(rxbuf, (unsigned int)len, c->dst_ip,
+				       c->dport, c->sport, &s))
+				continue;
+			if (s.flags & TCP_RST)
+				return -2;
+			if ((s.flags & (TCP_SYN | TCP_ACK)) ==
+			    (TCP_SYN | TCP_ACK) && s.ack == c->snd_nxt + 1) {
+				unsigned int mss;
+
+				c->rcv_nxt = s.seq + 1;
+				c->snd_nxt++;
+				c->snd_una = c->snd_nxt;
+				if (tcp_parse_mss(s.tcp, s.doff, &mss) &&
+				    mss >= 64 && mss <= TCP_MSS_OURS)
+					c->peer_mss = mss;
+				if (tcp_send_segment(c, TCP_ACK, c->snd_nxt,
+						     c->rcv_nxt, 0, 0, 0) != 0)
+					return -3;
+				return 0;
+			}
+		}
+	}
+	return -1;
+}
+
+int tcp_send(struct tcp_conn *c, const void *data, unsigned int len)
+{
+	const struct netdev *nd = netdev_active();
+	unsigned char *rxbuf = netdev_rx_scratch();
+	unsigned int tries;
+
+	if (!nd || len > c->peer_mss)
+		return -3;
+
+	for (tries = 0; tries < TCP_RETRIES; tries++) {
+		unsigned int deadline = get_ticks_ms() + TCP_RETRY_MS;
+
+		if (tcp_send_segment(c, TCP_PSH | TCP_ACK, c->snd_nxt,
+				     c->rcv_nxt, (const unsigned char *)data,
+				     len, 0) != 0)
+			return -3;
+
+		while ((int)(get_ticks_ms() - deadline) < 0) {
+			struct tcp_seg s;
+			int rlen = nd->rx(rxbuf, NETDEV_FRAME_MAX);
+
+			if (rlen < 0)
+				continue;
+			if (!tcp_parse(rxbuf, (unsigned int)rlen, c->dst_ip,
+				       c->dport, c->sport, &s))
+				continue;
+			if (s.flags & TCP_RST)
+				return -2;
+			if (s.ack == c->snd_nxt + len) {
+				c->snd_una = s.ack;
+				c->snd_nxt = s.ack;
+				return 0;
+			}
+			/* Data before the request is fully acked: ACK it and
+			 * drop it; the peer retransmits if it cares. */
+			if (s.len) {
+				if (s.seq == c->rcv_nxt)
+					c->rcv_nxt += s.len;
+				tcp_send_segment(c, TCP_ACK, c->snd_nxt,
+						 c->rcv_nxt, 0, 0, 0);
+			}
+		}
+	}
+	return -1;
+}
+
+int tcp_recv(struct tcp_conn *c, unsigned char *out, unsigned int maxlen,
+	     unsigned int deadline_ms)
+{
+	const struct netdev *nd = netdev_active();
+	unsigned char *rxbuf = netdev_rx_scratch();
+
+	if (!nd)
+		return -2;
+
+	/* Drain a partially consumed segment first. */
+	if (hold_pos < hold_len) {
+		unsigned int n = hold_len - hold_pos;
+		unsigned int i;
+
+		if (n > maxlen)
+			n = maxlen;
+		for (i = 0; i < n; i++)
+			out[i] = hold_buf[hold_pos + i];
+		hold_pos += n;
+		return (int)n;
+	}
+	if (c->peer_fin)
+		return 0;
+
+	while ((int)(get_ticks_ms() - deadline_ms) < 0) {
+		struct tcp_seg s;
+		int len = nd->rx(rxbuf, NETDEV_FRAME_MAX);
+
+		if (len < 0)
+			continue;
+		if (!tcp_parse(rxbuf, (unsigned int)len, c->dst_ip,
+			       c->dport, c->sport, &s))
+			continue;
+		if (s.flags & TCP_RST)
+			return -2;
+
+		/* Track our send window (nothing pending here, but keeps
+		 * snd_una meaningful for the ACKs we emit). */
+		if ((unsigned)(s.ack - c->snd_una) <=
+		    (unsigned)(c->snd_nxt - c->snd_una))
+			c->snd_una = s.ack;
+
+		if (s.len) {
+			if (s.len > sizeof(hold_buf))     /* not ours to store */
+				continue;
+			if (s.seq == c->rcv_nxt) {
+				unsigned int take = s.len < maxlen ? s.len : maxlen;
+				unsigned int i;
+
+				for (i = 0; i < take; i++)
+					out[i] = s.data[i];
+				c->rcv_nxt += s.len;
+				if (s.len > take) {       /* hold the rest */
+					for (i = take; i < s.len; i++)
+						hold_buf[i - take] = s.data[i];
+					hold_len = s.len - take;
+					hold_pos = 0;
+				}
+				/* A FIN riding on the data consumes the next
+				 * sequence number after the payload. */
+				if ((s.flags & TCP_FIN) && !c->peer_fin) {
+					c->peer_fin = 1;
+					c->rcv_nxt++;
+				}
+				tcp_send_segment(c, TCP_ACK, c->snd_nxt,
+						 c->rcv_nxt, 0, 0, 0);
+				return (int)take;
+			}
+			/* Duplicate or out-of-order data: re-ACK to resync. */
+			tcp_send_segment(c, TCP_ACK, c->snd_nxt, c->rcv_nxt,
+					 0, 0, 0);
+			continue;
+		}
+		if (s.flags & TCP_FIN) {
+			if (s.seq == c->rcv_nxt) {
+				c->rcv_nxt++;
+				c->peer_fin = 1;
+				tcp_send_segment(c, TCP_ACK, c->snd_nxt,
+						 c->rcv_nxt, 0, 0, 0);
+				return 0;
+			}
+		}
+	}
+	return -1;
+}
+
+void tcp_close(struct tcp_conn *c)
+{
+	const struct netdev *nd = netdev_active();
+	unsigned char *rxbuf = netdev_rx_scratch();
+	unsigned int fin_seq = c->snd_nxt;
+	unsigned int tries;
+
+	if (!nd)
+		return;
+
+	for (tries = 0; tries < 2; tries++) {
+		unsigned int deadline = get_ticks_ms() + 500;
+		struct tcp_seg s;
+
+		if (tcp_send_segment(c, TCP_FIN | TCP_ACK, fin_seq,
+				     c->rcv_nxt, 0, 0, 0) != 0)
+			return;
+		c->snd_nxt = fin_seq + 1;
+
+		while ((int)(get_ticks_ms() - deadline) < 0) {
+			int len = nd->rx(rxbuf, NETDEV_FRAME_MAX);
+
+			if (len < 0)
+				continue;
+			if (!tcp_parse(rxbuf, (unsigned int)len, c->dst_ip,
+				       c->dport, c->sport, &s))
+				continue;
+			if (s.flags & TCP_RST)
+				return;
+			/* Our FIN acked (or their FIN first). */
+			if ((s.flags & TCP_FIN) && s.seq == c->rcv_nxt) {
+				c->rcv_nxt++;
+				c->peer_fin = 1;
+				tcp_send_segment(c, TCP_ACK, c->snd_nxt,
+						 c->rcv_nxt, 0, 0, 0);
+				return;
+			}
+			if (s.ack == c->snd_nxt)
+				return;
+		}
+	}
+}

+ 41 - 0
tcp.h

@@ -0,0 +1,41 @@
+/* Minimal TCP client (RFC 793 subset) for outgoing connections.
+ *
+ * Single connection, in-order receive only, no congestion control, no
+ * window scaling, no out-of-order reassembly, no fragmentation.  Everything
+ * is polled from the netdev rx() call, matching the rest of the kernel.
+ * The caller owns the NIC (netdev_acquire) from connect until close. */
+#ifndef TCP_H
+#define TCP_H
+
+struct tcp_conn {
+	unsigned char dst_mac[6];
+	unsigned char dst_ip[4];
+	unsigned int  sport, dport;
+	unsigned int  snd_una;    /* oldest unacknowledged sequence */
+	unsigned int  snd_nxt;    /* next sequence number to send */
+	unsigned int  rcv_nxt;    /* next sequence number expected from peer */
+	unsigned int  peer_mss;   /* from the SYN-ACK option; 536 when absent */
+	int           peer_fin;   /* peer FIN consumed (EOF) */
+};
+
+/* Open a connection (SYN -> SYN-ACK -> ACK).  Returns:
+ *   0 = established,
+ *  -1 = no reply (timeout),
+ *  -2 = refused (RST),
+ *  -3 = transmit failed / no NIC / no IP. */
+int tcp_connect(const unsigned char *dst_mac, const unsigned char *dst_ip,
+		unsigned int dport, struct tcp_conn *c);
+
+/* Send one segment (len must be <= peer_mss), retransmitting until acked.
+ * Returns 0, or -1 timeout / -2 reset / -3 transmit failed. */
+int tcp_send(struct tcp_conn *c, const void *data, unsigned int len);
+
+/* Read the next in-order payload bytes into out.  Returns >0 = byte count,
+ * 0 = peer closed (EOF), -1 = deadline passed, -2 = reset. */
+int tcp_recv(struct tcp_conn *c, unsigned char *out, unsigned int maxlen,
+	     unsigned int deadline_ms);
+
+/* Send FIN and drain the close handshake briefly (best effort). */
+void tcp_close(struct tcp_conn *c);
+
+#endif

+ 99 - 1
terminal.c

@@ -48,6 +48,9 @@ extern void program_netregs_main(void);
 extern void program_netloop_main(void);
 extern void program_netreset_main(void);
 extern void program_ping_main(void);
+extern void program_curl_main(const char *arg);
+extern void program_netdns_main(const char *arg);
+extern void program_lookup_main(const char *arg);
 
 /* Print the prompt (with the current directory) and set line_start. */
 static void term_print_prompt(struct term *t, int first)
@@ -590,6 +593,91 @@ static int is_cmd_netping(const char *line, unsigned int line_len, char *arg_buf
 	return (i == line_len);
 }
 
+/* One optional single-token argument (URL, name or dotted IP). */
+static int is_cmd_curl(const char *line, unsigned int line_len, char *arg_buf, unsigned int buf_size)
+{
+	unsigned int i = 0, j = 0;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i + 4 > line_len)
+		return 0;
+	if (line[i] != 'c' || line[i+1] != 'u' || line[i+2] != 'r' ||
+	    line[i+3] != 'l')
+		return 0;
+	i += 4;
+	if (i < line_len && line[i] != ' ')
+		return 0;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i >= line_len) {
+		if (buf_size > 0)
+			arg_buf[0] = '\0';
+		return 1;
+	}
+	while (i < line_len && j + 1 < buf_size)
+		arg_buf[j++] = line[i++];
+	arg_buf[j] = '\0';
+	while (i < line_len && line[i] == ' ')
+		i++;
+	return (i == line_len);
+}
+
+static int is_cmd_netdns(const char *line, unsigned int line_len, char *arg_buf, unsigned int buf_size)
+{
+	unsigned int i = 0, j = 0;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i + 6 > line_len)
+		return 0;
+	if (line[i] != 'n' || line[i+1] != 'e' || line[i+2] != 't' ||
+	    line[i+3] != 'd' || line[i+4] != 'n' || line[i+5] != 's')
+		return 0;
+	i += 6;
+	if (i < line_len && line[i] != ' ')
+		return 0;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i >= line_len) {
+		if (buf_size > 0)
+			arg_buf[0] = '\0';
+		return 1;
+	}
+	while (i < line_len && j + 1 < buf_size)
+		arg_buf[j++] = line[i++];
+	arg_buf[j] = '\0';
+	while (i < line_len && line[i] == ' ')
+		i++;
+	return (i == line_len);
+}
+
+static int is_cmd_lookup(const char *line, unsigned int line_len, char *arg_buf, unsigned int buf_size)
+{
+	unsigned int i = 0, j = 0;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i + 6 > line_len)
+		return 0;
+	if (line[i] != 'l' || line[i+1] != 'o' || line[i+2] != 'o' ||
+	    line[i+3] != 'k' || line[i+4] != 'u' || line[i+5] != 'p')
+		return 0;
+	i += 6;
+	if (i < line_len && line[i] != ' ')
+		return 0;
+	while (i < line_len && line[i] == ' ')
+		i++;
+	if (i >= line_len) {
+		if (buf_size > 0)
+			arg_buf[0] = '\0';
+		return 1;
+	}
+	while (i < line_len && j + 1 < buf_size)
+		arg_buf[j++] = line[i++];
+	arg_buf[j] = '\0';
+	while (i < line_len && line[i] == ' ')
+		i++;
+	return (i == line_len);
+}
+
 static int is_cmd_ping(const char *line, unsigned int line_len)
 {
 	unsigned int i = 0;
@@ -827,7 +915,8 @@ static const char *const help_items[] = {
 	"netrecv", "netsend", "netip [a.b.c.d]", "netping <a.b.c.d>",
 	"netlog <text>", "netconsole [on|off|host <ip>]", "dhcp", "netregs",
 	"netloop", "netreset", "ping", "ps", "kill <pid>", "kexec", "dbg",
-	"serial test|recv", "clear",
+	"serial test|recv", "clear", "curl <url>", "netdns [a.b.c.d]",
+	"lookup <name>",
 };
 
 static void help_puts(const char *s)
@@ -1642,6 +1731,9 @@ void term_run(struct term *t)
 					char netping_arg[16];
 					char netlog_arg[NET_UDP_ARG_MAX];
 					char netconsole_arg[NET_UDP_ARG_MAX];
+					char curl_arg[128];
+					char netdns_arg[32];
+					char lookup_arg[64];
 					char lspci_arg[16];
 					char peek_arg[32];
 					char resolved[VFS_PATH_MAX];
@@ -1702,6 +1794,12 @@ void term_run(struct term *t)
 						term_spawn(t, "netloop", program_netloop_main);
 					} else if (is_cmd_netreset(t->line, t->line_len)) {
 						term_spawn(t, "netreset", program_netreset_main);
+					} else if (is_cmd_netdns(t->line, t->line_len, netdns_arg, sizeof(netdns_arg))) {
+						term_spawn_arg(t, "netdns", program_netdns_main, netdns_arg);
+					} else if (is_cmd_curl(t->line, t->line_len, curl_arg, sizeof(curl_arg))) {
+						term_spawn_arg(t, "curl", program_curl_main, curl_arg);
+					} else if (is_cmd_lookup(t->line, t->line_len, lookup_arg, sizeof(lookup_arg))) {
+						term_spawn_arg(t, "lookup", program_lookup_main, lookup_arg);
 					} else if (is_cmd_ping(t->line, t->line_len)) {
 						term_spawn(t, "ping", program_ping_main);
 					} else if (is_cmd_storage(t->line, t->line_len)) {

+ 1 - 1
tss.c

@@ -57,7 +57,7 @@ void gdt_tss_init(void)
 	__asm__ volatile ("lgdt %0" : : "m"(gdtp));
 
 	tss.ss0  = 0x10;    /* kernel data segment */
-	tss.esp0 = 0x44800; /* bootstrap stack; updated by switch.S per process */
+	tss.esp0 = 0x49800; /* bootstrap stack; updated by switch.S per process */
 	tss.iomap_base = 0xFFFF;  /* no I/O permission bitmap (deny ring-3 I/O) */
 	__asm__ volatile ("ltr %0" : : "r"((unsigned short)0x28));
 }

+ 1 - 1
uhci.c

@@ -72,7 +72,7 @@ struct uhci_qh {
 #define UHCI_NUM_TD 16
 
 /* Frame list lives in low memory (below the kernel at 0x7E00) to avoid
-   bloating the kernel's BSS past the 0x44000 linker budget. It must be
+   bloating the kernel's BSS past the 0x49000 linker budget. It must be
    4 KB aligned; 0x3000 is free after boot (see AGENTS.md memory map). */
 #define UHCI_FRAME_LIST_ADDR 0x3000u
 

+ 2 - 2
user.ld

@@ -1,9 +1,9 @@
-/* User program: load at 0x45000, same as run.c PROGRAM_LOAD_ADDR. */
+/* User program: load at 0x4A000, same as run.c PROGRAM_LOAD_ADDR. */
 ENTRY(_start)
 
 SECTIONS
 {
-	. = 0x45000;
+	. = 0x4A000;
 	.text : { *(.text .text.*) }
 	.rodata : { *(.rodata .rodata.*) }
 	.data : { *(.data .data.*) }

+ 1 - 1
vesa_stage.S

@@ -223,7 +223,7 @@ stage2_pm:
 	movw  %ax, %fs
 	movw  %ax, %gs
 	movw  %ax, %ss
-	movl  $0x44800, %esp
+	movl  $0x49800, %esp
 	jmp   kernel_main
 
 .align 4