Răsfoiți Sursa

Add browser with HTML/CSS and shared HTTP client

The browser is a disk app (BROWSER) launched by a small in-pack command, so it can link ngui, the full image library, inflate, TLS and the shared HTTP client without growing the compressed command pack. It renders a tolerant HTML tree with the basic CSS subset, inline images, relative links, history, scrolling and a URL/status bar; files opens .htm/.html through it and the WM gets a Web button.

uhttp is extracted from curl and now owns URL handling, redirects, chunked decoding, timeouts and TLS for both commands.

SYS_SPAWN loads FAT ELFs through kmalloc with interrupts enabled for IRQ 6, replacing the 16 KB static fat_load_buf and allowing large disk commands to spawn; VFS_FILE_MAX is raised accordingly.
Johannes Zellner 2 săptămâni în urmă
părinte
comite
585f5fe11a
18 a modificat fișierele cu 4936 adăugiri și 690 ștergeri
  1. 35 5
      AGENTS.md
  2. 32 5
      Makefile
  3. 1841 0
      browser.c
  4. 1662 0
      browser_html.c
  5. 137 0
      browser_html.h
  6. 56 13
      ngui.c
  7. 5 0
      ngui.h
  8. 9 1
      syscall.c
  9. 51 0
      testdata/browser/demo.html
  10. 53 0
      ucmd_browser.c
  11. 71 654
      ucmd_curl.c
  12. 15 0
      ucmd_files.c
  13. 7 1
      ucmd_wm.c
  14. 831 0
      uhttp.c
  15. 107 0
      uhttp.h
  16. 16 9
      vfs.c
  17. 4 2
      vfs.h
  18. 4 0
      wm_abi.h

+ 35 - 5
AGENTS.md

@@ -23,8 +23,9 @@ make clean
 
 - Build flags (in `Makefile`): `-m32 -march=i586 -ffreestanding -fno-pie -nostdlib
   -fno-stack-protector -mno-sse -mno-sse2 -mno-mmx -O2`.
-- `root.img` is a second FAT12 floppy holding user binaries (`PROG.BIN`, `SPACE.BIN`)
-  and test files; it requires `mtools` to build.
+- `root.img` is a second FAT12 floppy holding user binaries (`PROG.BIN`, `SPACE.BIN`),
+  the external browser (`BROWSER`) and its `DEMO.HTM`/`PIC.BMP` test page, plus
+  a few test files; it requires `mtools` to build.
 - `make send PROGRAM=prog` transfers a binary to a real machine over serial.
 
 ## Boot chain
@@ -381,9 +382,29 @@ below the run area), so adding code no longer moves any address.
   `_start(const char *arg)` needs no crt0.  `ngui.c/h` is the shared userland
   GUI toolkit linked into `ucmd_files.c` (buttons, text fields, icons, layout
   cuts and scroll panes); `files` opens the selected text file through
-  `/ramfs/bin/edit` and image files through `/ramfs/bin/view`.  `ngui_end_ex()`
+  `/ramfs/bin/edit`, image files through `/ramfs/bin/view`, and `.htm`/`.html`
+  files through `/ramfs/bin/browser`.  `ngui_end_ex()`
   is the variant that runs the bookkeeping without publishing the canvas, for
   apps that poll input without redrawing.
+- **Browser**: `ucmd_browser.c` is a tiny `bin/browser` launcher; the real
+  browser is the external `BROWSER` on `root.img` (also looked up in `/share`
+  and on IDE/SATA FAT mounts) because it links ngui, the full image library,
+  inflate, TLS and uhttp and would not fit the compressed command pack.  The
+  launcher forwards its argument and cwd; `make run`/`run-net` attach
+  `root.img`, and a netbooted board can upload `browser.elf` to `/share`
+  (`make browser-dev` uses the board's `websrv`; stop `websrv` before browsing
+  HTTP, because it owns the NIC).
+  `uhttp.c/h` is the shared ring-3 HTTP client extracted from curl: URL
+  parsing/resolution, redirects, chunked decoding, timeouts and TLS; curl and
+  the browser both use it.  `browser_html.c/h` is a tolerant HTML tree + the
+  CSS subset (tag/class/id selectors, colours, backgrounds, font size/weight,
+  alignment, margins, padding, display); `browser.c` owns the layout/render,
+  URL bar, history, status bar and inline `<img>` decoding.  Page and image
+  buffers come from `SYS_MEM_ALLOC`; the DOM uses fixed static arenas.
+  There is no JavaScript, forms, external CSS or standalone image viewer
+  mode.  `SYS_SPAWN` loads FAT ELFs through `kmalloc` now (the old 16 KB
+  `fat_load_buf` is gone) and wraps the load in `sys_fs_enter/exit`, since the
+  floppy needs IRQ 6.
 - **Image library + viewer**: `img.h`, `img.c`, `img_mem.c`, `img_blit.c`,
   `img_png.c`, `img_bmp.c`, `img_gif.c`, `img_jpeg.c`, `img_tga.c`,
   `img_pnm.c`, `img_file.c/h` — freestanding RGB565 decoders with an optional
@@ -448,7 +469,7 @@ below the run area), so adding code no longer moves any address.
 `mkdir <path>`, `rmdir <path>`, `hello`, `reboot`, `poweroff`, `run <name>|<file>`, `space`,
 `prog`,
 `display`, `cpuinfo`, `mouseinfo`, `gfxbench`, `lsusb`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `meminfo`, `top`, `sched`, `format <device> [size]` (binary units, e.g. `format ide0 100mb` or `1gb`; no size formats the whole disk),
-`ps`, `renice <pid> <weight>`, `kill <pid>`, `idle [hlt|c2|c3|c2ap|c3ap]`, `spin [ms]`, `help`, `clear`, `serial test|recv`, `kexec`, `dbg`, and `view <file>` (image viewer; PNG, baseline/progressive JPEG, animated GIF, BMP, TGA, PNM, ICO, PAM).
+`ps`, `renice <pid> <weight>`, `kill <pid>`, `idle [hlt|c2|c3|c2ap|c3ap]`, `spin [ms]`, `help`, `clear`, `serial test|recv`, `kexec`, `dbg`, `view <file>` (image viewer; PNG, baseline/progressive JPEG, animated GIF, BMP, TGA, PNM, ICO, PAM), and `browser [url|file]` (disk app launcher).
 
 Network: `netinfo`, `netrecv`, `netsend`, `netip [a.b.c.d]`, `dhcp` (re-run the
 DHCP client), `pong` (responds to ARP/ICMP for our IP for 30 s),
@@ -894,5 +915,14 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
 
 22. The TCP backlog's early-request buffers cost 8 KB of kernel BSS
     (8 slots x 1 KB), and the FAT listing cache another 5 KB; `_end` is
-    within roughly 20 KB of the `0x7F000` wall.  Adding more kernel buffers
+    within roughly 30 KB of the `0x7F000` wall.  Adding more kernel buffers
     or commands should be paired with reclaiming space elsewhere.
+
+23. Browser limits: no JavaScript, forms, external stylesheets, floats,
+    flex/grid, tables with column widths or standalone image documents.  CSS
+    `font-size` maps to 1x/2x only, `vh`/`vw`/`em` units are approximated as
+    pixels, and images are decoded eagerly (up to 6, 4 MB/4 MP each) and
+    redrawn by `img_draw` on every repaint.  TLS is phase A (no certificate
+    verification); `https` is shown as unverified.  The disk app is loaded
+    from FAT at spawn time, so a cold floppy start takes a few seconds; the
+    8 KB user stack means the layout state is deliberately static.

+ 32 - 5
Makefile

@@ -13,7 +13,7 @@ ASFLAGS  = --32 -I.
 BOOT_LDFLAGS   = -T linker.ld -nostdlib -m elf_i386
 KERNEL_LDFLAGS = -T kernel.ld -nostdlib -m elf_i386
 
-.PHONY: all clean run run-smp run-floppy run-usb run-uhci run-net run-ahci test-usb run-serial floppy usb flash space prog bootstrap dev net-dev cmds-dev net-cmds netmon monitor test-crypto test-images test-images-asan
+.PHONY: all clean run run-smp run-floppy run-usb run-uhci run-net run-ahci test-usb run-serial floppy usb flash space prog bootstrap dev net-dev cmds-dev net-cmds browser-dev netmon monitor test-crypto test-images test-images-asan
 
 all: floppy.img usb.img final.bin root.img
 
@@ -392,7 +392,7 @@ UCMDS = ucmd_cpuinfo ucmd_ls ucmd_cat ucmd_save ucmd_rm ucmd_mkdir ucmd_rmdir \
         ucmd_netinfo ucmd_netip ucmd_netdns ucmd_host ucmd_dhcp \
         ucmd_netsend ucmd_netrecv ucmd_ping ucmd_pong ucmd_netlog \
         ucmd_netconsole ucmd_netregs ucmd_netloop ucmd_netreset ucmd_curl \
-        ucmd_files ucmd_view ucmd_sensors ucmd_mines ucmd_websrv
+        ucmd_files ucmd_view ucmd_sensors ucmd_mines ucmd_websrv ucmd_browser
 
 # Keep the linked ELFs around (make would treat them as disposable
 # intermediates between the pattern rules).
@@ -473,10 +473,27 @@ ucmd_view.elf: ucmd_view.o $(IMGLIB_OBJS) inflate.o ngui.o font_8x16.o ucmd.ld
 # the host (make test-crypto).
 TLSLIB_OBJS = tls_sha256.o tls_chacha20.o tls_x25519.o tls_rng.o tls.o
 
-ucmd_curl.elf: ucmd_curl.o $(TLSLIB_OBJS) ucmd.ld
+# Shared ring-3 HTTP/TLS client (curl and the browser).
+uhttp.o: uhttp.c uhttp.h ucmd_lib.h tls.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+ucmd_curl.elf: ucmd_curl.o uhttp.o $(TLSLIB_OBJS) ucmd.ld
 	$(LD) -T ucmd.ld -z max-page-size=0x100 -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(OBJCOPY) --strip-all $@ $@
 
+# browser: the real app is a disk image (BROWSER) because it links ngui, the
+# image library, TLS and uhttp.  ucmd_browser.c is the tiny PATH launcher.
+browser_html.o: browser_html.c browser_html.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+browser.o: browser.c ucmd_lib.h syscall.h wm_abi.h ngui.h browser_html.h uhttp.h img.h inflate.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+browser.elf: browser.o browser_html.o uhttp.o ngui.o font_8x16.o $(IMGLIB_OBJS) inflate.o $(TLSLIB_OBJS) ucmd.ld
+	$(LD) -T ucmd.ld -z max-page-size=0x100 -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
+	$(OBJCOPY) --strip-all $@ $@
+
+
 tls_sha256.o: tls_sha256.c tls_sha256.h
 	$(CC) $(CFLAGS) -o $@ $<
 
@@ -575,13 +592,16 @@ bootstrap.elf: bootstrap.o bootstrap.ld
 bootstrap.bin: bootstrap.elf
 	$(OBJCOPY) -O binary $< $@
 
-root.img: prog.bin space.bin
+root.img: prog.bin space.bin browser.elf testdata/browser/demo.html testdata/images/rgb.bmp
 	dd if=/dev/zero of=$@ bs=512 count=2880 2>/dev/null
 	mkfs.fat -F 12 -n "ROOTDISK" $@
 	echo "Hello from the second floppy!" | mcopy -i $@ - ::HELLO.TXT
 	echo "This is a test file on drive 1." | mcopy -i $@ - ::TEST.TXT
 	mcopy -i $@ prog.bin ::PROG.BIN
 	mcopy -i $@ space.bin ::SPACE.BIN
+	mcopy -i $@ browser.elf ::BROWSER
+	mcopy -i $@ testdata/browser/demo.html ::DEMO.HTM
+	mcopy -i $@ testdata/images/rgb.bmp ::PIC.BMP
 
 run: image.bin root.img
 	$(MAKE) run-floppy
@@ -710,6 +730,13 @@ net-cmds: cmds.pack netkexec_send
 	@echo "Sending cmds.pack to $(BOARD_IP):$(NETKEXEC_PORT)..."
 	./netkexec_send --payload $(BOARD_IP) $(NETKEXEC_PORT) cmds.pack
 
+# The browser is a disk app, not part of the pack.  Upload it to the board's
+# writable /share (the board must be running `websrv`; stop it before browsing
+# HTTP, since the WebDAV server owns the NIC).
+browser-dev: browser.elf
+	@echo "Uploading browser.elf to http://$(BOARD_IP):8080/share/BROWSER..."
+	curl -f -T browser.elf http://$(BOARD_IP):8080/share/BROWSER
+
 # Show the board's netlog stream (kernel debug + terminal text) like `make
 # monitor` does over serial.
 netmon: netmonitor
@@ -729,4 +756,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 entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o blit.o cpu.o thermal.o it87.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o panic.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_mem.o inflate.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o acpi.o lapic.o smp.o ap_tramp.o ap_tramp.elf ap_tramp.bin ap_tramp_embed.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 cmds.pack cmds_pack_gz.bin cmds_pack.o ramfs.o share.o payload.o mkpack uwm_lib.o ngui.o img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o img_jpeg.o img_tga.o img_pnm.o img_ico.o img_pam.o img_gif_anim.o img_file.o img_test img_test_asan *.boot.tmp $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) $(TLSLIB_OBJS) tls_test bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor
+	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o blit.o cpu.o thermal.o it87.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o panic.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_mem.o inflate.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o acpi.o lapic.o smp.o ap_tramp.o ap_tramp.elf ap_tramp.bin ap_tramp_embed.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 cmds.pack cmds_pack_gz.bin cmds_pack.o ramfs.o share.o payload.o mkpack uwm_lib.o ngui.o img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o img_jpeg.o img_tga.o img_pnm.o img_ico.o img_pam.o img_gif_anim.o img_file.o browser.o browser_html.o uhttp.o browser.elf img_test img_test_asan *.boot.tmp $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) $(TLSLIB_OBJS) tls_test bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor

+ 1841 - 0
browser.c

@@ -0,0 +1,1841 @@
+/* browser: a small HTML/CSS browser built on ngui, the image library and the
+ * shared uhttp client.
+ *
+ * No JavaScript, no forms, no external CSS; images are decoded with img.c and
+ * drawn inline.  Large buffers (page body, compressed body, image files and
+ * decode arenas) live in the per-process SYS_MEM_ALLOC heap; the DOM itself
+ * uses the fixed arenas in browser_html.c.
+ */
+
+#include "ucmd_lib.h"
+#include "ngui.h"
+#include "browser_html.h"
+#include "uhttp.h"
+#include "img.h"
+#include "inflate.h"
+
+#define BR_W            720
+#define BR_H            520
+#define BR_TOOLBAR_H    30
+#define BR_STATUS_H     18
+
+#define BR_HEAP_INIT    (6u * 1024u * 1024u)
+#define BR_HEAP_MAX     (28u * 1024u * 1024u)
+#define BR_PAGE_MAX     (512u * 1024u)
+#define BR_IMG_FILE_MAX (4u * 1024u * 1024u)
+#define BR_IMG_PIX_MAX  (4u * 1024u * 1024u)
+#define BR_MAX_IMAGES   6
+#define BR_HISTORY      16
+#define BR_URL_MAX      320
+#define BR_STATUS_MAX   200
+
+#define BR_IMG_RGB565(r, g, b) \
+	((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
+#define BR_WHITE  0xFFFF
+#define BR_BLACK  0x0000
+#define BR_GRAY   0x8410
+#define BR_LINK   0x001B
+
+enum {
+	ID_URL = 1,
+	ID_GO,
+	ID_BACK,
+	ID_FORWARD,
+	ID_RELOAD,
+	ID_HOME
+};
+
+#define ACT_NAV      (1u << 0)
+#define ACT_BACK     (1u << 1)
+#define ACT_FORWARD  (1u << 2)
+#define ACT_RELOAD   (1u << 3)
+#define ACT_HOME     (1u << 4)
+#define ACT_CLOSE    (1u << 5)
+
+struct br_image {
+	int state;                  /* 0 empty, 1 ready */
+	struct img_image img;
+	char err[32];
+};
+
+static struct ngui ui;
+static struct ngui_input url_in;
+static struct ngui_scroll page_scroll;
+
+static struct br_doc doc;
+static struct br_image images[BR_MAX_IMAGES];
+static int image_count;
+
+static unsigned char *heap;
+static unsigned int heap_size = 0;
+static unsigned int heap_used = 0;
+
+static char page_url[BR_URL_MAX];
+static char page_title[BR_TITLE_MAX];
+static char cwd[64];
+static int page_is_local;
+static int page_loading;
+
+static char status_text[BR_STATUS_MAX];
+static unsigned int status_until;
+static int status_error;
+
+static char history[BR_HISTORY][BR_URL_MAX];
+static int hist_len, hist_pos;
+
+static char click_url[BR_URL_MAX];
+static int quit;
+
+static struct ngui_rect page_rect;
+
+/* layout output */
+struct lay_run {
+	unsigned short off, len;
+	unsigned short gap;
+	unsigned short color;
+	unsigned short href;
+	char lit[28];
+	short img;
+	unsigned short iw, ih;
+	unsigned char scale, bold, underline;
+	unsigned char has_lit;
+};
+
+struct lay {
+	int draw;
+	struct ngui *ui;
+	int left, right;
+	int y;
+	int line_x, line_y, line_h;
+	int run_x;
+	int align;
+	int depth;
+	int space_pending;
+	struct lay_run runs[96];
+	int nruns;
+};
+
+struct hit {
+	int x, y, w, h;
+	unsigned short node;
+};
+
+#define HIT_MAX 96
+static struct hit hits[HIT_MAX];
+static int nhits;
+
+static unsigned short block_h[BR_MAX_NODES];
+static char li_marker[BR_MAX_NODES][6];
+
+/* one connection object; the browser fetches one resource at a time */
+static struct uhttp http;
+
+/* ---- tiny strings ---- */
+
+static unsigned int s_len(const char *s)
+{
+	unsigned int n = 0;
+
+	while (s && s[n])
+		n++;
+	return n;
+}
+
+static void s_copy(char *d, const char *s, unsigned int cap)
+{
+	unsigned int i = 0;
+
+	if (!cap)
+		return;
+	while (s && s[i] && i + 1 < cap) {
+		d[i] = s[i];
+		i++;
+	}
+	d[i] = '\0';
+}
+
+static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
+{
+	while (s && *s && *n + 1 < cap)
+		d[(*n)++] = *s++;
+	d[*n] = '\0';
+}
+
+static void s_append_dec(char *d, unsigned int *n, unsigned int v,
+			 unsigned int cap)
+{
+	char tmp[12];
+	unsigned int i = 0, j;
+
+	do {
+		tmp[i++] = (char)('0' + v % 10);
+		v /= 10;
+	} while (v && i < sizeof(tmp));
+	for (j = 0; j < i && *n + 1 < cap; j++)
+		d[(*n)++] = tmp[i - 1 - j];
+	d[*n] = '\0';
+}
+
+static int s_eq(const char *a, const char *b)
+{
+	while (*a && *b) {
+		if (*a != *b)
+			return 0;
+		a++;
+		b++;
+	}
+	return *a == *b;
+}
+
+static int starts_with(const char *s, const char *p)
+{
+	unsigned int i = 0;
+
+	while (p[i]) {
+		if (s[i] != p[i])
+			return 0;
+		i++;
+	}
+	return 1;
+}
+
+static int contains_ci(const char *s, const char *p)
+{
+	unsigned int i, j;
+
+	for (i = 0; s[i]; i++) {
+		for (j = 0; p[j]; j++) {
+			char a = s[i + j];
+			if (a >= 'A' && a <= 'Z')
+				a = (char)(a - 'A' + 'a');
+			if (a != p[j])
+				break;
+		}
+		if (!p[j])
+			return 1;
+	}
+	return 0;
+}
+
+static char *trim(char *s)
+{
+	unsigned int n;
+
+	while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
+		s++;
+	n = s_len(s);
+	while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
+		     s[n - 1] == '\r' || s[n - 1] == '\n'))
+		s[--n] = '\0';
+	return s;
+}
+
+/* ---- per-process heap ---- */
+
+static int heap_start(void)
+{
+	heap = (unsigned char *)u_mem_alloc(BR_HEAP_INIT);
+	if (!heap) {
+		heap_size = heap_used = 0;
+		return -1;
+	}
+	heap_size = BR_HEAP_INIT;
+	heap_used = 0;
+	return 0;
+}
+
+static void heap_clear(void)
+{
+	u_mem_free();
+	heap = 0;
+	heap_size = heap_used = 0;
+}
+
+static void *heap_alloc(unsigned int bytes, unsigned int align)
+{
+	unsigned int start, want;
+
+	if (!heap || bytes == 0)
+		return 0;
+	if (align < 1)
+		align = 1;
+	if (align & (align - 1))
+		return 0;
+	start = (heap_used + align - 1) & ~(align - 1);
+	if (start > BR_HEAP_MAX || bytes > BR_HEAP_MAX - start)
+		return 0;
+	if (start + bytes > heap_size) {
+		want = heap_size ? heap_size : BR_HEAP_INIT;
+		while (want < start + bytes) {
+			if (want > BR_HEAP_MAX / 2) {
+				want = BR_HEAP_MAX;
+				break;
+			}
+			want *= 2;
+		}
+		if (want < start + bytes || want > BR_HEAP_MAX)
+			return 0;
+		if (u_mem_grow(want) != 0)
+			return 0;
+		heap_size = want;
+	}
+	heap_used = start + bytes;
+	return heap + start;
+}
+
+/* ---- status ---- */
+
+static void set_status(const char *s, int err, unsigned int ttl_ms)
+{
+	s_copy(status_text, s, sizeof(status_text));
+	status_error = err;
+	status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
+	ngui_invalidate(&ui);
+}
+
+/* ---- images ---- */
+
+static void image_reset(void)
+{
+	int i;
+
+	for (i = 0; i < BR_MAX_IMAGES; i++) {
+		images[i].state = 0;
+		images[i].err[0] = '\0';
+	}
+	image_count = 0;
+}
+
+static int decode_image_data(const unsigned char *data, unsigned int len,
+			     struct br_image *bi)
+{
+	struct img_info info;
+	struct img_options opt;
+	struct img_mem mem;
+	void *arena;
+	unsigned int est;
+	int r;
+
+	if (img_sniff(data, len, &info) != 0) {
+		s_copy(bi->err, "unknown image format", sizeof(bi->err));
+		return -1;
+	}
+	est = img_estimate(&info);
+	if (est == 0xFFFFFFFFu || est > BR_HEAP_MAX / 2) {
+		s_copy(bi->err, "image too large", sizeof(bi->err));
+		return -1;
+	}
+	est += 64u * 1024u;
+	arena = heap_alloc(est, 16);
+	if (!arena) {
+		s_copy(bi->err, "out of memory", sizeof(bi->err));
+		return -1;
+	}
+	img_mem_init(&mem, arena, est);
+	opt.max_pixels = BR_IMG_PIX_MAX;
+	r = img_decode(data, len, &opt, &mem, &bi->img);
+	if (r != 0) {
+		s_copy(bi->err, img_error_string(r), sizeof(bi->err));
+		return -1;
+	}
+	bi->state = 1;
+	return 0;
+}
+
+/* ---- URL / local path handling ---- */
+
+static int is_http(const char *s)
+{
+	return starts_with(s, "http://") || starts_with(s, "https://");
+}
+
+/* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
+static int normalize_abs(const char *in, char *out, unsigned int cap)
+{
+	char seg[64];
+	unsigned int i = 0, o = 1;
+	int depth = 0;
+	int trailing;
+
+	if (!in || in[0] != '/' || cap < 2)
+		return -1;
+	trailing = 0;
+	{
+		unsigned int n = s_len(in);
+		if (n > 1 && in[n - 1] == '/')
+			trailing = 1;
+	}
+	out[0] = '/';
+	while (in[i]) {
+		unsigned int n = 0;
+
+		while (in[i] == '/')
+			i++;
+		while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
+			if (n + 1 < sizeof(seg))
+				seg[n++] = in[i];
+			i++;
+		}
+		seg[n] = '\0';
+		if (n == 0)
+			break;
+		if (s_eq(seg, "."))
+			continue;
+		if (s_eq(seg, "..")) {
+			if (depth > 0) {
+				while (o > 1 && out[o - 1] != '/')
+					o--;
+				if (o > 1)
+					o--;
+				depth--;
+			}
+			continue;
+		}
+		if (o > 1) {
+			if (o + 1 >= cap)
+				return -1;
+			out[o++] = '/';
+		}
+		if (o + n + 1 >= cap)
+			return -1;
+		{
+			unsigned int j;
+			for (j = 0; j < n; j++)
+				out[o++] = seg[j];
+		}
+		depth++;
+	}
+	if (trailing && o > 1) {
+		if (o + 1 >= cap)
+			return -1;
+		out[o++] = '/';
+	}
+	out[o] = '\0';
+	return 0;
+}
+
+static void make_abs_local(const char *in, char *out, unsigned int cap)
+{
+	char joined[BR_URL_MAX];
+
+	if (!in || !in[0]) {
+		s_copy(out, cwd[0] ? cwd : "/", cap);
+		return;
+	}
+	if (in[0] == '/') {
+		if (normalize_abs(in, out, cap) != 0)
+			s_copy(out, in, cap);
+		return;
+	}
+	{
+		unsigned int n = 0;
+		s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
+		s_append(joined, &n, "/", sizeof(joined));
+		s_append(joined, &n, in, sizeof(joined));
+	}
+	if (normalize_abs(joined, out, cap) != 0)
+		s_copy(out, joined, cap);
+}
+
+static int path_dir(const char *path, char *out, unsigned int cap)
+{
+	unsigned int i, last = 0;
+
+	for (i = 0; path[i]; i++)
+		if (path[i] == '/')
+			last = i;
+	if (last == 0) {
+		if (cap < 2)
+			return -1;
+		out[0] = '/';
+		out[1] = '\0';
+		return 0;
+	}
+	if (last + 1 >= cap)
+		return -1;
+	{
+		unsigned int j;
+		for (j = 0; j < last; j++)
+			out[j] = path[j];
+		out[last] = '\0';
+	}
+	return 0;
+}
+
+/* Resolve an href against the current page. 0 = ok, -1 = ignore. */
+static int resolve_link(const char *base, const char *href, char *out,
+			unsigned int cap)
+{
+	char joined[BR_URL_MAX];
+
+	if (!href || !href[0] || href[0] == '#')
+		return -1;
+	if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
+	    starts_with(href, "data:") || starts_with(href, "tel:"))
+		return -1;
+	if (starts_with(href, "about:")) {
+		s_copy(out, href, cap);
+		return 0;
+	}
+	if (is_http(href)) {
+		s_copy(out, href, cap);
+		return 0;
+	}
+	if (starts_with(href, "//")) {
+		if (is_http(base)) {
+			unsigned int n = 0;
+			s_append(out, &n, starts_with(base, "https:") ?
+				 "https:" : "http:", cap);
+			s_append(out, &n, href, cap);
+			return 0;
+		}
+		return -1;
+	}
+	if (is_http(base)) {
+		return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
+	}
+	/* local page */
+	if (href[0] == '/') {
+		if (normalize_abs(href, out, cap) != 0)
+			return -1;
+		return 0;
+	}
+	{
+		char dir[BR_URL_MAX];
+		unsigned int n = 0;
+
+		if (s_eq(base, "about:home"))
+			s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
+		else if (path_dir(base, dir, sizeof(dir)) != 0)
+			s_copy(dir, "/", sizeof(dir));
+		s_append(joined, &n, dir, sizeof(joined));
+		if (n == 0 || joined[n - 1] != '/')
+			s_append(joined, &n, "/", sizeof(joined));
+		s_append(joined, &n, href, sizeof(joined));
+	}
+	return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
+}
+
+/* ---- HTTP / file fetch ---- */
+
+static int read_url(const char *url, unsigned int cap, unsigned char **out,
+		    unsigned int *outlen, int *is_local, char *ctype,
+		    unsigned int ctcap, char *final, unsigned int finalcap,
+		    char *err, unsigned int errcap, int *truncated)
+{
+	unsigned char *buf = 0;
+	unsigned int total = 0;
+	int rv;
+
+	*out = 0;
+	*outlen = 0;
+	*truncated = 0;
+	if (final && finalcap)
+		final[0] = '\0';
+	if (ctype && ctcap)
+		ctype[0] = '\0';
+
+	if (url[0] == '/') {
+		buf = (unsigned char *)heap_alloc(cap, 16);
+		if (!buf) {
+			s_copy(err, "out of memory", errcap);
+			return -1;
+		}
+		rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf, (int)cap);
+		if (rv < 0) {
+			s_copy(err, "file not found", errcap);
+			return -1;
+		}
+		*out = buf;
+		*outlen = (unsigned int)rv;
+		*is_local = 1;
+		if (ctype)
+			s_copy(ctype, "text/html", ctcap);
+		if (final)
+			s_copy(final, url, finalcap);
+		if ((unsigned int)rv == cap)
+			*truncated = 1;
+		return 0;
+	}
+
+	uhttp_init(&http);
+	http.user_agent = "nebos-browser/0.1";
+	rv = uhttp_open(&http, url, UHTTP_GZIP, 0);
+	if (rv != 0) {
+		s_copy(err, uhttp_error_string(rv), errcap);
+		return -1;
+	}
+	if (ctype)
+		s_copy(ctype, http.resp.content_type, ctcap);
+	if (final && http.resp.final_url[0])
+		s_copy(final, http.resp.final_url, finalcap);
+	*is_local = 0;
+
+	if (http.resp.gzip ||
+	    contains_ci(http.resp.content_encoding, "gzip") ||
+	    contains_ci(http.resp.content_encoding, "deflate")) {
+		unsigned char *comp = (unsigned char *)heap_alloc(cap, 16);
+		unsigned int climit = cap * 2;
+		unsigned char *plain;
+		struct inflate *ws;
+		unsigned int plen = 0;
+		int zr;
+
+		if (climit > 4u * 1024u * 1024u)
+			climit = 4u * 1024u * 1024u;
+		if (!comp) {
+			s_copy(err, "out of memory", errcap);
+			uhttp_close(&http);
+			return -1;
+		}
+		total = 0;
+		for (;;) {
+			rv = uhttp_read(&http, comp + total, climit - total,
+					UHTTP_IDLE_TIMEOUT_MS);
+			if (rv > 0) {
+				total += (unsigned int)rv;
+				if (total >= climit) {
+					*truncated = 1;
+					break;
+				}
+				continue;
+			}
+			if (rv < 0) {
+				s_copy(err, uhttp_error_string(rv), errcap);
+				uhttp_close(&http);
+				return -1;
+			}
+			break;
+		}
+		uhttp_close(&http);
+		plain = (unsigned char *)heap_alloc(cap, 16);
+		ws = (struct inflate *)heap_alloc(sizeof(struct inflate), 16);
+		if (!plain || !ws) {
+			s_copy(err, "out of memory", errcap);
+			return -1;
+		}
+		if (contains_ci(http.resp.content_encoding, "deflate"))
+			zr = inflate_zlib_mem(comp, total, plain, cap, &plen, ws);
+		else
+			zr = inflate_gzip_mem(comp, total, plain, cap, &plen, ws);
+		if (zr != 0) {
+			s_copy(err, "compressed page is corrupt", errcap);
+			return -1;
+		}
+		*out = plain;
+		*outlen = plen;
+		return 0;
+	}
+
+	buf = (unsigned char *)heap_alloc(cap, 16);
+	if (!buf) {
+		s_copy(err, "out of memory", errcap);
+		uhttp_close(&http);
+		return -1;
+	}
+	for (;;) {
+		rv = uhttp_read(&http, buf + total, cap - total,
+				UHTTP_IDLE_TIMEOUT_MS);
+		if (rv > 0) {
+			total += (unsigned int)rv;
+			if (total >= cap) {
+				*truncated = 1;
+				break;
+			}
+			continue;
+		}
+		if (rv < 0) {
+			s_copy(err, uhttp_error_string(rv), errcap);
+			uhttp_close(&http);
+			return -1;
+		}
+		break;
+	}
+	uhttp_close(&http);
+	if (total == 0) {
+		s_copy(err, "empty response", errcap);
+		return -1;
+	}
+	*out = buf;
+	*outlen = total;
+	return 0;
+}
+
+/* ---- page loading ---- */
+
+static void redraw_now(void);
+
+static char error_page[1024];
+
+static void show_error(const char *title, const char *detail)
+{
+	char *page = error_page;
+	unsigned int n = 0;
+
+	s_append(page, &n, "<html><body><h2>", sizeof(error_page));
+	s_append(page, &n, title, sizeof(error_page));
+	s_append(page, &n, "</h2><p>", sizeof(error_page));
+	{
+		const char *p = detail;
+		while (*p && n + 1 < sizeof(error_page)) {
+			if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
+			else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
+			else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
+			else page[n++] = *p;
+			p++;
+		}
+	}
+	page[n] = '\0';
+	s_append(page, &n, "</p><p>", sizeof(error_page));
+	s_append(page, &n, page_url, sizeof(error_page));
+	s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
+		 sizeof(error_page));
+	br_parse(&doc, page, n);
+	s_copy(page_title, title, sizeof(page_title));
+	page_loading = 0;
+	set_status(title, 1, 0);
+	ngui_invalidate(&ui);
+}
+
+static int decode_direct_image(const unsigned char *data, unsigned int len,
+			       unsigned int node)
+{
+	if (image_count >= BR_MAX_IMAGES)
+		return -1;
+	if (decode_image_data(data, len, &images[0]) != 0)
+		return -1;
+	doc.nodes[node].img_index = 0;
+	image_count = 1;
+	return 0;
+}
+
+static void preload_images(void)
+{
+	unsigned int i;
+	int loaded = 0;
+
+	for (i = 0; i < doc.nnode && loaded < BR_MAX_IMAGES; i++) {
+		struct br_node *nd = &doc.nodes[i];
+		const char *src;
+		char url[BR_URL_MAX];
+		unsigned char *data;
+		unsigned int len;
+		int local, trunc;
+		char ctype[64];
+		char final[BR_URL_MAX];
+		char err[64];
+		char msg[64];
+		unsigned int n = 0;
+
+		if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_IMG ||
+		    nd->img_index >= 0)
+			continue;
+		src = br_src(&doc, i);
+		if (!src[0])
+			continue;
+		if (resolve_link(page_url, src, url, sizeof(url)) != 0)
+			continue;
+		s_append(msg, &n, "Loading images ", sizeof(msg));
+		s_append_dec(msg, &n, (unsigned int)loaded + 1, sizeof(msg));
+		s_append(msg, &n, "...", sizeof(msg));
+		s_copy(status_text, msg, sizeof(status_text));
+		status_until = 0;
+		status_error = 0;
+		redraw_now();
+
+		if (read_url(url, BR_IMG_FILE_MAX, &data, &len, &local, ctype,
+			     sizeof(ctype), final, sizeof(final), err,
+			     sizeof(err), &trunc) != 0) {
+			continue;
+		}
+		(void)local;
+		(void)trunc;
+		if (decode_image_data(data, len, &images[image_count]) != 0)
+			continue;
+		nd->img_index = (short)image_count;
+		image_count++;
+		loaded++;
+	}
+}
+
+static void history_push(const char *url)
+{
+	if (!url || !url[0])
+		return;
+	if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
+	    s_eq(history[hist_pos], url))
+		return;
+	if (hist_len > 0 && hist_pos + 1 < hist_len)
+		hist_len = hist_pos + 1;
+	if (hist_len < BR_HISTORY) {
+		s_copy(history[hist_len], url, BR_URL_MAX);
+		hist_pos = hist_len;
+		hist_len++;
+	} else {
+		int i;
+		for (i = 1; i < BR_HISTORY; i++)
+			s_copy(history[i - 1], history[i], BR_URL_MAX);
+		s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
+		hist_pos = BR_HISTORY - 1;
+	}
+}
+
+static void load_page(const char *url, int local, int push)
+{
+	unsigned char *body = 0;
+	unsigned int len = 0;
+	int truncated = 0;
+	struct img_info image_info;
+	char ctype[64];
+	char final[BR_URL_MAX];
+	char err[80];
+	const char *detail = 0;
+
+	final[0] = '\0';
+
+	heap_clear();
+	image_reset();
+	br_parse_plain(&doc, "", 0);    /* blank while loading */
+	page_title[0] = '\0';
+	page_loading = 1;
+	page_is_local = local;
+	s_copy(page_url, url, sizeof(page_url));
+	if (final[0])
+		final[0] = '\0';
+	if (push)
+		history_push(url);
+	set_status("Loading...", 0, 0);
+	redraw_now();
+
+	if (heap_start() != 0) {
+		show_error("Out of memory", "Cannot allocate the page buffer");
+		return;
+	}
+	if (read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
+		     sizeof(ctype), final, sizeof(final), err, sizeof(err),
+		     &truncated) != 0) {
+		detail = err;
+		show_error("Cannot load this page", detail);
+		s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
+		url_in.len = s_len(url_in.text);
+		url_in.cursor = url_in.len;
+		url_in.scroll = 0;
+		return;
+	}
+	page_is_local = local;
+	if (final[0])
+		s_copy(page_url, final, sizeof(page_url));
+
+	if (contains_ci(ctype, "text/plain")) {
+		br_parse_plain(&doc, (const char *)body, len);
+
+	} else if (contains_ci(ctype, "image/") ||
+		   (!contains_ci(ctype, "text/html") &&
+		    img_sniff(body, len, &image_info) == 0)) {
+		unsigned int node = br_parse_image_doc(&doc, page_url);
+		if (node)
+			decode_direct_image(body, len, node);
+		s_copy(page_title, "Image", sizeof(page_title));
+	} else {
+		br_parse(&doc, (const char *)body, len);
+		s_copy(page_title, doc.title[0] ? doc.title : page_url,
+		       sizeof(page_title));
+		preload_images();
+	}
+	if (truncated)
+		set_status("Page truncated at the buffer limit", 0, 6000);
+	else if (doc.truncated)
+		set_status("Page truncated by the parser", 0, 6000);
+	else if (starts_with(page_url, "https://"))
+		set_status("HTTPS: certificate NOT verified", 0, 6000);
+	else
+		set_status("", 0, 0);
+	page_loading = 0;
+	s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
+	url_in.len = s_len(url_in.text);
+	url_in.cursor = url_in.len;
+	url_in.scroll = 0;
+	ngui_set_focus(&ui, 0);
+	ngui_invalidate(&ui);
+}
+
+static void load_home(int push)
+{
+	heap_clear();
+	image_reset();
+	br_parse_plain(&doc, "", 0);
+	page_loading = 1;
+	page_is_local = 0;
+	s_copy(page_url, "about:home", sizeof(page_url));
+	if (push)
+		history_push(page_url);
+	redraw_now();
+	if (heap_start() != 0) {
+		show_error("Out of memory", "Cannot allocate the browser heap");
+		return;
+	}
+	{
+		static const char home[] =
+			"<html><head><title>Nebs Browser</title><style>"
+			"body { margin: 10px; color: #222222; }"
+			"h1 { color: #2255cc; }"
+			".box { background-color: #eeeeff; margin: 12px; "
+			"padding: 10px; }"
+			"a { color: #0033cc; }"
+			"pre { background-color: #f4f4f4; }"
+			"</style></head><body>"
+			"<h1>Nebs Browser</h1>"
+			"<p>A small HTML/CSS browser built on <b>ngui</b>, the "
+			"shared HTTP client and the image library.</p>"
+			"<div class=\"box\"><b>Try:</b>"
+			"<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
+			"floppy1/DEMO.HTM</a> on the root floppy</li>"
+			"<li><a href=\"http://10.0.2.2:8000/\">"
+			"http://10.0.2.2:8000/</a> on the QEMU host</li>"
+			"<li><a href=\"https://example.com/\">"
+			"https://example.com/</a> (TLS, not verified)</li>"
+			"</ul></div>"
+			"<p>Type a URL in the bar above.  Esc closes the "
+			"window, Ctrl+L focuses the address bar.</p>"
+			"<pre>javascript: not supported\nforms: not supported"
+			"\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
+			"</body></html>";
+		br_parse(&doc, home, sizeof(home) - 1);
+		s_copy(page_title, doc.title, sizeof(page_title));
+	}
+	page_loading = 0;
+	set_status("", 0, 0);
+	s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
+	url_in.len = s_len(url_in.text);
+	url_in.cursor = url_in.len;
+	url_in.scroll = 0;
+	ngui_set_focus(&ui, 0);
+	ngui_invalidate(&ui);
+}
+
+static void navigate(const char *input, int push)
+{
+	char target[BR_URL_MAX];
+	char *t;
+
+	if (!input)
+		return;
+	s_copy(target, input, sizeof(target));
+	t = trim(target);
+	if (!t[0])
+		return;
+	if (s_eq(t, "about:home")) {
+		load_home(push);
+		return;
+	}
+	if (starts_with(t, "file://")) {
+		make_abs_local(t + 7, target, sizeof(target));
+		load_page(target, 1, push);
+		return;
+	}
+	if (is_http(t)) {
+		load_page(t, 0, push);
+		return;
+	}
+	{
+		struct sys_stat st;
+
+		if (t[0] == '/' || (u_stat(t, &st) == 0 && !st.is_dir)) {
+			make_abs_local(t, target, sizeof(target));
+			load_page(target, 1, push);
+			return;
+		}
+	}
+	{
+		char with_scheme[BR_URL_MAX];
+		unsigned int n = 0;
+		s_append(with_scheme, &n, "http://", sizeof(with_scheme));
+		s_append(with_scheme, &n, t, sizeof(with_scheme));
+		load_page(with_scheme, 0, push);
+	}
+}
+
+/* ---- layout ---- */
+
+static struct br_style base_style(void)
+{
+	struct br_style s;
+
+	s.color = BR_BLACK;
+	s.bg = BR_WHITE;
+	s.has_bg = 0;
+	s.scale = 1;
+	s.bold = 0;
+	s.underline = 0;
+	s.align = BR_ALIGN_LEFT;
+	s.display = BR_DISPLAY_BLOCK;
+	s.mt = s.mb = s.ml = s.mr = 0;
+	s.pt = s.pb = s.pl = s.pr = 0;
+	return s;
+}
+
+static int run_width(const struct lay_run *r)
+{
+	if (r->img >= 0)
+		return r->iw;
+	{
+		unsigned int n = r->has_lit ? s_len(r->lit) : r->len;
+		return (int)(n * (unsigned int)(8 * r->scale) +
+			     (r->bold ? 1u : 0u));
+	}
+}
+
+static void flush_line(struct lay *l)
+{
+	int total, x, i;
+
+	if (!l->nruns && l->line_x == l->left) {
+		l->line_h = 0;
+		return;
+	}
+	total = l->line_x - l->left;
+	x = l->left;
+	if (l->align == BR_ALIGN_CENTER)
+		x += (l->right - l->left - total) / 2;
+	else if (l->align == BR_ALIGN_RIGHT)
+		x = l->right - total;
+	if (x < l->left)
+		x = l->left;
+	for (i = 0; i < l->nruns; i++) {
+		struct lay_run *r = &l->runs[i];
+		int w = run_width(r);
+
+		x += r->gap;
+		if (l->draw) {
+			if (r->img >= 0) {
+				struct br_image *bi = &images[r->img];
+				if (bi->state == 1) {
+					struct img_blit b;
+					b.dst = l->ui->px;
+					b.dst_w = l->ui->w;
+					b.dst_h = l->ui->h;
+					b.clip_x = page_rect.x;
+					b.clip_y = page_rect.y;
+					b.clip_w = page_rect.w - 12;
+					b.clip_h = page_rect.h;
+					b.x = x;
+					b.y = l->line_y;
+					b.scale = ((unsigned int)r->iw << 16) /
+						  bi->img.w;
+					b.bg = BR_WHITE;
+					b.bg2 = BR_WHITE;
+					b.flags = IMG_BLIT_OVER_DST;
+					img_draw(&bi->img, &b);
+				}
+			} else {
+				const char *s = r->has_lit ? r->lit :
+						doc.text + r->off;
+				unsigned int n = r->has_lit ? s_len(r->lit) :
+						r->len;
+				ngui_text_styled(l->ui, x, l->line_y, s, n,
+						 r->color, r->scale, r->bold);
+				if (r->underline)
+					ngui_fill_rect(l->ui,
+						(struct ngui_rect){x,
+						 l->line_y + 16 * r->scale - 2,
+						 w, 1}, r->color);
+			}
+			if (r->href) {
+				if (nhits < HIT_MAX) {
+					struct hit *h = &hits[nhits];
+					int hh = r->img >= 0 ? r->ih :
+						 16 * r->scale;
+					int merge = nhits > 0 &&
+						hits[nhits - 1].node == r->href &&
+						hits[nhits - 1].y == l->line_y &&
+						hits[nhits - 1].h == hh &&
+						x <= hits[nhits - 1].x +
+						     hits[nhits - 1].w + 2;
+					if (merge) {
+						struct hit *p = &hits[nhits - 1];
+						int end = x + w;
+						if (end > p->x + p->w)
+							p->w = end - p->x;
+					} else {
+						h->x = x;
+						h->y = l->line_y;
+						h->w = w;
+						h->h = hh;
+						h->node = r->href;
+						nhits++;
+					}
+				}
+			}
+		}
+		x += w;
+	}
+	l->y += l->line_h + 2;
+	l->nruns = 0;
+	l->line_x = l->left;
+	l->run_x = l->left;
+	l->line_h = 0;
+	l->space_pending = 0;
+}
+
+static void add_run(struct lay *l, unsigned short off, unsigned short len,
+		    const struct br_style *st, unsigned short href,
+		    const char *lit)
+{
+	unsigned int n = lit ? s_len(lit) : len;
+	int w = (int)(n * (unsigned int)(8 * st->scale) +
+		      (st->bold ? 1u : 0u));
+
+	if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
+		flush_line(l);
+	if (l->nruns == 0) {
+		l->line_y = l->y;
+		l->line_h = 0;
+	}
+	{
+		struct lay_run *r = &l->runs[l->nruns++];
+		int gap = l->line_x - l->run_x;
+
+		if (gap < 0)
+			gap = 0;
+		r->gap = (unsigned short)gap;
+		r->off = off;
+		r->len = len;
+		r->color = st->color;
+		r->href = href;
+		r->has_lit = 0;
+		r->lit[0] = '\0';
+		if (lit && lit[0]) {
+			unsigned int i;
+			for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
+				r->lit[i] = lit[i];
+			r->lit[i] = '\0';
+			r->has_lit = 1;
+		}
+		r->img = -1;
+		r->iw = r->ih = 0;
+		r->scale = st->scale;
+		r->bold = st->bold;
+		r->underline = st->underline;
+	}
+	l->line_x += w;
+	l->run_x = l->line_x;
+	if (l->line_h < 16 * st->scale)
+		l->line_h = 16 * st->scale;
+}
+
+static void add_image_run(struct lay *l, unsigned int node,
+			  const struct br_style *st, unsigned short href)
+{
+	struct br_image *bi = 0;
+	int idx = doc.nodes[node].img_index;
+	int dw, dh, maxw;
+
+	if (idx >= 0 && idx < image_count && images[idx].state == 1)
+		bi = &images[idx];
+	if (l->space_pending && (l->nruns > 0 || l->line_x > l->left)) {
+		if (l->line_x + 8 <= l->right)
+			l->line_x += 8;
+	}
+	l->space_pending = 0;
+	if (!bi) {
+		const char *alt = br_alt(&doc, node);
+		struct br_style gs = *st;
+		char tmp[96];
+		unsigned int n = 0;
+		int w;
+
+		gs.color = BR_GRAY;
+		gs.underline = 0;
+		s_append(tmp, &n, "[", sizeof(tmp));
+		s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
+		s_append(tmp, &n, "]", sizeof(tmp));
+		w = (int)(n * (unsigned int)(8 * gs.scale));
+		if (l->line_x + w > l->right &&
+		    (l->nruns > 0 || l->line_x > l->left))
+			flush_line(l);
+		add_run(l, 0, 0, &gs, href, tmp);
+		return;
+	}
+	if (l->space_pending && (l->nruns > 0 || l->line_x > l->left)) {
+		if (l->line_x + 8 <= l->right)
+			l->line_x += 8;
+	}
+	maxw = l->right - l->left;
+	dw = (int)bi->img.w;
+	dh = (int)bi->img.h;
+	if (doc.nodes[node].width_attr) {
+		int want = doc.nodes[node].width_attr;
+		dh = dh * want / dw;
+		dw = want;
+	}
+	if (doc.nodes[node].height_attr) {
+		int want = doc.nodes[node].height_attr;
+		if (dw > 0)
+			dw = dw * want / dh;
+		dh = want;
+	}
+	if (dw < 8)
+		dw = 8;
+	if (dh < 8)
+		dh = 8;
+	if (dw > maxw && maxw > 0) {
+		dh = dh * maxw / dw;
+		dw = maxw;
+	}
+	if (l->line_x + dw > l->right && (l->nruns > 0 ||
+					  l->line_x > l->left))
+		flush_line(l);
+	if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
+		flush_line(l);
+	if (l->nruns == 0) {
+		l->line_y = l->y;
+		l->line_h = 0;
+	}
+	{
+		struct lay_run *r = &l->runs[l->nruns++];
+		int gap = l->line_x - l->run_x;
+
+		if (gap < 0)
+			gap = 0;
+		r->gap = (unsigned short)gap;
+		r->off = 0;
+		r->len = 0;
+		r->color = 0;
+		r->href = href;
+		r->has_lit = 0;
+		r->lit[0] = '\0';
+		r->img = (short)idx;
+		r->iw = (unsigned short)dw;
+		r->ih = (unsigned short)dh;
+		r->scale = 1;
+		r->bold = 0;
+		r->underline = 0;
+	}
+	l->line_x += dw;
+	l->run_x = l->line_x;
+	if (l->line_h < dh)
+		l->line_h = dh;
+}
+
+static void emit_text(struct lay *l, const char *s, unsigned int len,
+		      const struct br_style *st, unsigned short href, int pre)
+{
+	unsigned int i = 0;
+	unsigned int base;
+	int cw = 8 * st->scale;
+	int adv = cw + (st->bold ? 1 : 0);
+
+	if (!s || !len)
+		return;
+	base = (unsigned int)(s - doc.text);
+	if (pre) {
+		while (i < len) {
+			unsigned int start;
+
+			if (s[i] == '\n') {
+				flush_line(l);
+				i++;
+				continue;
+			}
+			if (s[i] == ' ') {
+				if (l->line_x + cw > l->right &&
+				    (l->nruns > 0 || l->line_x > l->left))
+					flush_line(l);
+				else
+					l->line_x += cw;
+				i++;
+				continue;
+			}
+			start = i;
+			while (i < len && s[i] != ' ' && s[i] != '\n')
+				i++;
+			{
+				unsigned int n = i - start;
+				int w = (int)(n * (unsigned int)adv);
+
+				if (l->line_x + w > l->right &&
+				    (l->nruns > 0 || l->line_x > l->left))
+					flush_line(l);
+				if (w > l->right - l->left) {
+					int maxc = (l->right - l->left) / adv;
+					unsigned int off = start;
+					if (maxc < 1)
+						maxc = 1;
+					while (n > 0) {
+						unsigned int take = n >
+							(unsigned int)maxc ?
+							(unsigned int)maxc : n;
+						add_run(l, (unsigned short)(base + off),
+							(unsigned short)take,
+							st, href, 0);
+						off += take;
+						n -= take;
+						if (n)
+							flush_line(l);
+					}
+				} else {
+					add_run(l, (unsigned short)(base + start),
+						(unsigned short)n, st, href, 0);
+				}
+			}
+		}
+		return;
+	}
+	while (i < len) {
+		unsigned int start, n;
+		int w;
+
+		if (s[i] == ' ') {
+			l->space_pending = 1;
+			i++;
+			continue;
+		}
+		start = i;
+		while (i < len && s[i] != ' ')
+			i++;
+		n = i - start;
+		w = (int)(n * (unsigned int)adv);
+		if (l->space_pending &&
+		    (l->nruns > 0 || l->line_x > l->left)) {
+			if (l->line_x + cw <= l->right)
+				l->line_x += cw;
+		}
+		l->space_pending = 0;
+		if (l->line_x + w > l->right &&
+		    (l->nruns > 0 || l->line_x > l->left))
+			flush_line(l);
+		if (w > l->right - l->left) {
+			int maxc = (l->right - l->left) / adv;
+			unsigned int off = start;
+
+			if (maxc < 1)
+				maxc = 1;
+			while (n > 0) {
+				unsigned int take = n > (unsigned int)maxc ?
+					(unsigned int)maxc : n;
+				add_run(l, (unsigned short)(base + off),
+					(unsigned short)take, st, href, 0);
+				off += take;
+				n -= take;
+				if (n)
+					flush_line(l);
+			}
+		} else if (n) {
+			add_run(l, (unsigned short)(base + start),
+				(unsigned short)n, st, href, 0);
+		}
+	}
+}
+
+static int list_index(unsigned int parent, unsigned int node)
+{
+	unsigned int n = 0, i;
+
+	for (i = doc.nodes[parent].first; i && i != node;
+	     i = doc.nodes[i].next)
+		if (doc.nodes[i].tag == BR_TAG_LI)
+			n++;
+	return (int)n + 1;
+}
+
+static void layout_children(struct lay *l, unsigned int parent,
+			    const struct br_style *pst, int depth,
+			    unsigned short link);
+
+static void layout_block(struct lay *l, unsigned int node,
+			 const struct br_style *st, int depth,
+			 unsigned short link)
+{
+	int old_left = l->left, old_right = l->right, old_align = l->align;
+	int top, l0, r0;
+
+	if (depth > 24 || st->display == BR_DISPLAY_NONE)
+		return;
+	flush_line(l);
+	l->y += st->mt;
+	top = l->y;
+	l0 = old_left + st->ml;
+	r0 = old_right - st->mr;
+	if (r0 < l0 + 16)
+		r0 = l0 + 16;
+	if (l->draw && st->has_bg && block_h[node])
+		ngui_fill_rect(l->ui, (struct ngui_rect){l0, top, r0 - l0,
+							 block_h[node]},
+			       st->bg);
+	l->left = l0 + st->pl;
+	l->right = r0 - st->pr;
+	if (l->right < l->left + 8)
+		l->right = l->left + 8;
+	l->align = st->align;
+	l->y += st->pt;
+
+	if (doc.nodes[node].tag == BR_TAG_HR) {
+		if (l->draw)
+			ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
+				 l->y + 2, l->right - l->left, 1}, BR_GRAY);
+		l->y += 8;
+	} else {
+		if (doc.nodes[node].tag == BR_TAG_LI) {
+			char *m = li_marker[node];
+			if (!m[0]) {
+				unsigned int parent = doc.nodes[node].parent;
+				if (parent &&
+				    doc.nodes[parent].tag == BR_TAG_OL) {
+					int idx = list_index(parent, node);
+					unsigned int n = 0;
+					s_append_dec(m, &n, (unsigned int)idx, 6);
+					s_append(m, &n, ".", 6);
+				} else {
+					s_copy(m, "-", 6);
+				}
+			}
+			if (l->draw) {
+				int mw = (int)s_len(m) * 8;
+				ngui_text(l->ui, l->left - mw - 6, l->y, m,
+					  st->color);
+			}
+		}
+		layout_children(l, node, st, depth + 1, link);
+	}
+	flush_line(l);
+	l->y += st->pb;
+	l->left = old_left;
+	l->right = old_right;
+	l->align = old_align;
+	l->y += st->mb;
+	if (!l->draw) {
+		int h = l->y - top;
+		if (h < 0)
+			h = 0;
+		if (h > 65535)
+			h = 65535;
+		block_h[node] = (unsigned short)h;
+	}
+}
+
+static void layout_children(struct lay *l, unsigned int parent,
+			    const struct br_style *pst, int depth,
+			    unsigned short link)
+{
+	unsigned int n;
+
+	if (depth > 24)
+		return;
+	for (n = doc.nodes[parent].first; n; n = doc.nodes[n].next) {
+		struct br_node *nd = &doc.nodes[n];
+		struct br_style cs;
+		unsigned short lk = link;
+
+		if (nd->type == BR_NODE_TEXT) {
+			emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
+				  link, (nd->flags & BR_NODE_PREFORMAT) != 0);
+			continue;
+		}
+		br_style_for(&doc, n, pst, &cs);
+		if (cs.display == BR_DISPLAY_NONE)
+			continue;
+		if (nd->tag == BR_TAG_A && nd->href_off)
+			lk = (unsigned short)n;
+		if (nd->tag == BR_TAG_BR) {
+			flush_line(l);
+			continue;
+		}
+		if (nd->tag == BR_TAG_HR) {
+			flush_line(l);
+			if (l->draw)
+				ngui_fill_rect(l->ui,
+					(struct ngui_rect){l->left, l->y + 2,
+					l->right - l->left, 1}, BR_GRAY);
+			l->y += 8;
+			continue;
+		}
+		if (nd->tag == BR_TAG_IMG) {
+			add_image_run(l, n, &cs, lk);
+			continue;
+		}
+		if (cs.display == BR_DISPLAY_BLOCK || br_tag_is_block(nd->tag)) {
+			layout_block(l, n, &cs, depth + 1, lk);
+		} else {
+			layout_children(l, n, &cs, depth + 1, lk);
+			if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
+				l->space_pending = 1;
+		}
+	}
+}
+
+/* One layout state, kept out of the 8 KB user stack: it holds 96 line
+ * runs and a recursive page can otherwise overflow the stack. */
+static struct lay layout_state;
+
+static int measure_page(int left, int right)
+{
+	struct lay *l = &layout_state;
+	struct br_style base = base_style();
+	unsigned int i;
+
+	for (i = 0; i < BR_MAX_NODES; i++)
+		block_h[i] = 0;
+	l->draw = 0;
+	l->ui = 0;
+	l->left = left;
+	l->right = right;
+	l->y = 0;
+	l->line_x = left;
+	l->run_x = left;
+	l->line_y = 0;
+	l->line_h = 0;
+	l->align = BR_ALIGN_LEFT;
+	l->depth = 0;
+	l->nruns = 0;
+	l->space_pending = 0;
+	layout_children(l, doc.root, &base, 0, 0);
+	return l->y + 8;
+}
+
+static void render_page(int left, int right, int y0)
+{
+	struct lay *l = &layout_state;
+	struct br_style base = base_style();
+
+	l->draw = 1;
+	l->ui = &ui;
+	l->left = left;
+	l->right = right;
+	l->y = y0;
+	l->line_x = left;
+	l->run_x = left;
+	l->line_y = y0;
+	l->line_h = 0;
+	l->align = BR_ALIGN_LEFT;
+	l->depth = 0;
+	l->nruns = 0;
+	l->space_pending = 0;
+	nhits = 0;
+	layout_children(l, doc.root, &base, 0, 0);
+}
+
+/* ---- UI ---- */
+
+static int find_hit(int x, int y)
+{
+	int i;
+
+	for (i = nhits - 1; i >= 0; i--) {
+		struct hit *h = &hits[i];
+		if (x >= h->x && y >= h->y && x < h->x + h->w &&
+		    y < h->y + h->h)
+			return (int)h->node;
+	}
+	return 0;
+}
+
+static void draw_toolbar(struct ngui_rect r, unsigned int *action)
+{
+	int x = r.x + 4, y = r.y + 4, h = 22;
+	int compact = r.w < 560;
+	int go_w = r.w < 420 ? 32 : 42;
+	int in_x, in_w, res;
+
+	ngui_fill_rect(&ui, r, ui.theme.panel);
+	ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
+		       ui.theme.border);
+
+	if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
+			     NGUI_ICON_CHEVRON_LEFT))
+		*action |= ACT_BACK;
+	x += 32;
+	if (!compact) {
+		if (ngui_icon_button(&ui, ID_FORWARD,
+				     (struct ngui_rect){x, y, 28, h},
+				     NGUI_ICON_CHEVRON_RIGHT))
+			*action |= ACT_FORWARD;
+		x += 32;
+	}
+	if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
+			     NGUI_ICON_REFRESH))
+		*action |= ACT_RELOAD;
+	x += 32;
+	if (!compact) {
+		if (ngui_icon_button(&ui, ID_HOME,
+				     (struct ngui_rect){x, y, 28, h},
+				     NGUI_ICON_HOME))
+			*action |= ACT_HOME;
+		x += 32;
+	}
+
+	in_x = x + 2;
+	in_w = r.x + r.w - 6 - go_w - 4 - in_x;
+	if (in_w < 60)
+		in_w = 60;
+	res = ngui_text_input(&ui, ID_URL,
+			      (struct ngui_rect){in_x, y, in_w, h}, &url_in);
+	if (res & NGUI_INPUT_SUBMIT)
+		*action |= ACT_NAV;
+	if (res & NGUI_INPUT_CANCEL)
+		ngui_set_focus(&ui, 0);
+	if (ngui_button(&ui, ID_GO,
+			(struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
+			"Go"))
+		*action |= ACT_NAV;
+}
+
+static int page_hover_node(void)
+{
+	if (!ui.inside)
+		return 0;
+	if (ui.mouse_x < page_rect.x ||
+	    ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
+	    ui.mouse_y < page_rect.y ||
+	    ui.mouse_y >= page_rect.y + page_rect.h)
+		return 0;
+	return find_hit(ui.mouse_x, ui.mouse_y);
+}
+
+static void draw_page(struct ngui_rect page)
+{
+	int left, right, ch;
+	int old_panel, old_dim;
+
+	page_rect = page;
+	ngui_fill_rect(&ui, page, BR_WHITE);
+	if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
+		const char *s = page_loading ? "Loading..." : "No page";
+		int w = (int)ngui_text_width(s);
+		ngui_text(&ui, page.x + (page.w - w) / 2,
+			  page.y + page.h / 2 - 8, s, ui.theme.text_dim);
+		page_scroll.content_h = 0;
+		page_scroll.view_h = page.h;
+		return;
+	}
+	if (page.w < 40 || page.h < 40)
+		return;
+	left = page.x + 8;
+	right = page.x + page.w - 16;
+	ch = measure_page(left, right);
+	page_scroll.content_h = ch;
+	page_scroll.view_h = page.h;
+	ngui_scroll_begin(&ui, page, &page_scroll);
+	render_page(left, right, page.y + 4 - page_scroll.offset);
+	old_panel = ui.theme.panel_alt;
+	old_dim = ui.theme.text_dim;
+	ui.theme.panel_alt = 0xC618;
+	ui.theme.text_dim = 0x8410;
+	ngui_scroll_end(&ui, page, &page_scroll);
+	ui.theme.panel_alt = old_panel;
+	ui.theme.text_dim = old_dim;
+}
+
+static void draw_status(struct ngui_rect r)
+{
+	char msg[BR_URL_MAX + 32];
+	unsigned int n = 0;
+	int hover = page_hover_node();
+	unsigned short color;
+	const char *kind;
+
+	ngui_fill_rect(&ui, r, ui.theme.panel);
+	ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
+		       ui.theme.border);
+	if (hover) {
+		const char *href = br_href(&doc, (unsigned int)hover);
+		char url[BR_URL_MAX];
+		if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
+			s_append(msg, &n, "Link: ", sizeof(msg));
+			s_append(msg, &n, url, sizeof(msg));
+		} else {
+			s_copy(msg, "Link", sizeof(msg));
+		}
+		color = ui.theme.accent;
+	} else if (status_text[0]) {
+		s_copy(msg, status_text, sizeof(msg));
+		color = status_error ? ui.theme.error : ui.theme.text;
+	} else if (page_title[0]) {
+		s_copy(msg, page_title, sizeof(msg));
+		color = ui.theme.text;
+	} else {
+		s_copy(msg, "Ready", sizeof(msg));
+		color = ui.theme.text_dim;
+	}
+	kind = s_eq(page_url, "about:home") ? "HOME" :
+	       page_is_local ? "FILE" :
+	       (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
+	ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
+	{
+		int kw = (int)ngui_text_width(kind);
+		ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
+			  ui.theme.text_dim);
+	}
+}
+
+static void draw(unsigned int *action)
+{
+	struct ngui_rect r = {0, 0, ui.w, ui.h};
+	struct ngui_rect toolbar, status, page;
+
+	toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
+	status = ngui_cut_bottom(&r, BR_STATUS_H);
+	page = r;
+	draw_toolbar(toolbar, action);
+	draw_page(page);
+	draw_status(status);
+}
+
+static void redraw_now(void)
+{
+	unsigned int action = 0;
+
+	ngui_begin(&ui);
+	draw(&action);
+	ngui_end(&ui);
+}
+
+static void handle_keys(unsigned int *action)
+{
+	int k;
+
+	if (ngui_focus(&ui))
+		return;
+	if (ngui_scroll_keys(&ui, &page_scroll))
+		ngui_invalidate(&ui);
+	while ((k = ngui_key(&ui)) != 0) {
+		switch (k) {
+		case NGUI_KEY_ESC:
+			*action |= ACT_CLOSE;
+			break;
+		case NGUI_KEY_TAB:
+		case 0x0C:              /* Ctrl+L */
+			ngui_set_focus(&ui, ID_URL);
+			break;
+		case 0x12:              /* Ctrl+R */
+			*action |= ACT_RELOAD;
+			break;
+		case NGUI_KEY_BACKSPACE:
+			*action |= ACT_BACK;
+			break;
+		case NGUI_KEY_UP:
+			ngui_scroll_to(&page_scroll,
+				       page_scroll.offset - 24);
+			ngui_invalidate(&ui);
+			break;
+		case NGUI_KEY_DOWN:
+			ngui_scroll_to(&page_scroll,
+				       page_scroll.offset + 24);
+			ngui_invalidate(&ui);
+			break;
+		case NGUI_KEY_HOME:
+			ngui_scroll_to(&page_scroll, 0);
+			ngui_invalidate(&ui);
+			break;
+		case NGUI_KEY_END:
+			ngui_scroll_to(&page_scroll,
+				       page_scroll.content_h -
+				       page_scroll.view_h);
+			ngui_invalidate(&ui);
+			break;
+		default:
+			break;
+		}
+	}
+}
+
+static void handle_page_click(unsigned int *action)
+{
+	int node;
+	char url[BR_URL_MAX];
+
+	if (!ui.pressed || !ui.inside)
+		return;
+	if (ui.press_x < page_rect.x ||
+	    ui.press_x >= page_rect.x + page_rect.w - 12 ||
+	    ui.press_y < page_rect.y ||
+	    ui.press_y >= page_rect.y + page_rect.h)
+		return;
+	node = find_hit(ui.press_x, ui.press_y);
+	if (!node)
+		return;
+	if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
+			 sizeof(url)) != 0)
+		return;
+	s_copy(click_url, url, sizeof(click_url));
+	*action |= ACT_NAV;
+}
+
+void _start(const char *arg)
+{
+	struct win_info wi;
+
+	if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0) {
+		u_puts("browser: no graphics window\n");
+		u_exit(1);
+	}
+	ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
+	url_in.placeholder = "http://...";
+	br_doc_init(&doc);
+	if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
+		s_copy(cwd, "/", sizeof(cwd));
+	heap_clear();
+	page_scroll.offset = 0;
+	page_scroll.content_h = 0;
+
+	if (arg && arg[0])
+		navigate(arg, 1);
+	else
+		load_home(1);
+
+	for (;;) {
+		unsigned int action = 0;
+		unsigned int now;
+
+		click_url[0] = '\0';
+		now = u_ticks_ms();
+		if (status_until && (int)(now - status_until) >= 0) {
+			status_text[0] = '\0';
+			status_until = 0;
+			status_error = 0;
+			ngui_invalidate(&ui);
+		}
+		if (!ngui_begin(&ui)) {
+			u_sleep_ms(10);
+			continue;
+		}
+		draw(&action);
+		handle_keys(&action);
+		handle_page_click(&action);
+		ngui_end(&ui);
+		if (action & ACT_NAV) {
+			if (click_url[0]) {
+				navigate(click_url, 1);
+				click_url[0] = '\0';
+			} else {
+				navigate(url_in.text, 1);
+			}
+		}
+		if (action & ACT_BACK) {
+			if (hist_pos > 0) {
+				hist_pos--;
+				navigate(history[hist_pos], 0);
+			}
+		}
+		if (action & ACT_FORWARD) {
+			if (hist_pos + 1 < hist_len) {
+				hist_pos++;
+				navigate(history[hist_pos], 0);
+			}
+		}
+		if (action & ACT_RELOAD) {
+			if (s_eq(page_url, "about:home"))
+				load_home(0);
+			else
+				navigate(page_url, 0);
+		}
+		if (action & ACT_HOME)
+			load_home(1);
+		if (action & ACT_CLOSE)
+			quit = 1;
+		if (quit)
+			break;
+		u_sleep_ms(10);
+	}
+	u_win_close();
+	u_exit(0);
+}

+ 1662 - 0
browser_html.c

@@ -0,0 +1,1662 @@
+/* browser_html: see browser_html.h.  A deliberately tolerant parser: bad
+ * nesting is repaired, unknown tags are transparent, and the CSS engine only
+ * implements the properties in the browser's documented subset. */
+
+#include "browser_html.h"
+
+/* ---- storage (one document per process) ---- */
+
+static struct br_node nodes_store[BR_MAX_NODES];
+static char text_store[BR_TEXT_SIZE];
+static char attr_store[BR_ATTR_SIZE];
+static struct br_rule rule_store[BR_MAX_RULES];
+static char css_store[BR_CSS_SIZE];
+
+/* ---- tag table ---- */
+
+struct tag_name {
+	const char *name;
+	unsigned char tag;
+};
+
+static const struct tag_name tag_names[] = {
+	{ "html", BR_TAG_HTML }, { "head", BR_TAG_HEAD },
+	{ "body", BR_TAG_BODY }, { "title", BR_TAG_TITLE },
+	{ "style", BR_TAG_STYLE }, { "script", BR_TAG_SCRIPT },
+	{ "meta", BR_TAG_META }, { "link", BR_TAG_LINK },
+	{ "base", BR_TAG_BASE }, { "noscript", BR_TAG_NOSCRIPT },
+	{ "p", BR_TAG_P }, { "div", BR_TAG_DIV }, { "span", BR_TAG_SPAN },
+	{ "a", BR_TAG_A }, { "b", BR_TAG_B }, { "strong", BR_TAG_STRONG },
+	{ "i", BR_TAG_I }, { "em", BR_TAG_EM }, { "u", BR_TAG_U },
+	{ "code", BR_TAG_CODE }, { "font", BR_TAG_FONT },
+	{ "small", BR_TAG_SMALL }, { "big", BR_TAG_BIG },
+	{ "br", BR_TAG_BR }, { "hr", BR_TAG_HR }, { "img", BR_TAG_IMG },
+	{ "h1", BR_TAG_H1 }, { "h2", BR_TAG_H2 }, { "h3", BR_TAG_H3 },
+	{ "h4", BR_TAG_H4 }, { "h5", BR_TAG_H5 }, { "h6", BR_TAG_H6 },
+	{ "ul", BR_TAG_UL }, { "ol", BR_TAG_OL }, { "li", BR_TAG_LI },
+	{ "blockquote", BR_TAG_BLOCKQUOTE }, { "pre", BR_TAG_PRE },
+	{ "center", BR_TAG_CENTER }, { "table", BR_TAG_TABLE },
+	{ "thead", BR_TAG_THEAD }, { "tbody", BR_TAG_TBODY },
+	{ "tfoot", BR_TAG_TFOOT }, { "tr", BR_TAG_TR },
+	{ "td", BR_TAG_TD }, { "th", BR_TAG_TH },
+	{ "caption", BR_TAG_CAPTION }, { "form", BR_TAG_FORM },
+	{ "input", BR_TAG_INPUT }, { "button", BR_TAG_BUTTON },
+	{ "label", BR_TAG_LABEL }, { "select", BR_TAG_SELECT },
+	{ "option", BR_TAG_OPTION }, { "textarea", BR_TAG_TEXTAREA },
+	{ "iframe", BR_TAG_IFRAME }, { "svg", BR_TAG_SVG },
+	{ "video", BR_TAG_VIDEO }, { "audio", BR_TAG_AUDIO },
+	{ "canvas", BR_TAG_CANVAS }, { "object", BR_TAG_OBJECT },
+	{ "main", BR_TAG_MAIN }, { "header", BR_TAG_HEADER },
+	{ "footer", BR_TAG_FOOTER }, { "nav", BR_TAG_NAV },
+	{ "section", BR_TAG_SECTION }, { "article", BR_TAG_ARTICLE },
+	{ "aside", BR_TAG_ASIDE }, { "figure", BR_TAG_FIGURE },
+	{ "figcaption", BR_TAG_FIGCAPTION }, { "details", BR_TAG_DETAILS },
+	{ "summary", BR_TAG_SUMMARY }, { "dl", BR_TAG_DL },
+	{ "dt", BR_TAG_DT }, { "dd", BR_TAG_DD },
+	{ "address", BR_TAG_ADDRESS }, { "mark", BR_TAG_MARK },
+	{ "time", BR_TAG_TIME }, { "abbr", BR_TAG_ABBR },
+	{ "cite", BR_TAG_CITE }, { "q", BR_TAG_Q }, { "s", BR_TAG_S },
+	{ "strike", BR_TAG_STRIKE }, { "sub", BR_TAG_SUB },
+	{ "sup", BR_TAG_SUP }, { "bgsound", BR_TAG_BGSOUND },
+	{ "embed", BR_TAG_EMBED }, { "param", BR_TAG_PARAM },
+	{ "source", BR_TAG_SOURCE }, { "track", BR_TAG_TRACK },
+	{ "wbr", BR_TAG_WBR }, { "area", BR_TAG_AREA },
+	{ "col", BR_TAG_COL }, { "colgroup", BR_TAG_COLGROUP },
+	{ 0, 0 }
+};
+
+const char *br_tag_name(unsigned int tag)
+{
+	unsigned int i;
+
+	for (i = 0; tag_names[i].name; i++)
+		if (tag_names[i].tag == tag)
+			return tag_names[i].name;
+	return "?";
+}
+
+unsigned int br_tag_from_name(const char *name)
+{
+	unsigned int i, j;
+	char lower[16];
+
+	for (i = 0; i < 15 && name[i]; i++) {
+		char c = name[i];
+
+		if (c >= 'A' && c <= 'Z')
+			c = (char)(c - 'A' + 'a');
+		lower[i] = c;
+	}
+	lower[i] = '\0';
+	for (i = 0; tag_names[i].name; i++) {
+		for (j = 0; lower[j] && tag_names[i].name[j] == lower[j]; j++)
+			;
+		if (!lower[j] && !tag_names[i].name[j])
+			return tag_names[i].tag;
+	}
+	return BR_TAG_UNKNOWN;
+}
+
+int br_tag_is_void(unsigned int tag)
+{
+	switch (tag) {
+	case BR_TAG_BR: case BR_TAG_HR: case BR_TAG_IMG:
+	case BR_TAG_META: case BR_TAG_LINK: case BR_TAG_BASE:
+	case BR_TAG_INPUT: case BR_TAG_EMBED: case BR_TAG_PARAM:
+	case BR_TAG_SOURCE: case BR_TAG_TRACK: case BR_TAG_WBR:
+	case BR_TAG_AREA: case BR_TAG_COL:
+		return 1;
+	default:
+		return 0;
+	}
+}
+
+int br_tag_is_block(unsigned int tag)
+{
+	switch (tag) {
+	case BR_TAG_HTML: case BR_TAG_BODY: case BR_TAG_P:
+	case BR_TAG_DIV: case BR_TAG_H1: case BR_TAG_H2: case BR_TAG_H3:
+	case BR_TAG_H4: case BR_TAG_H5: case BR_TAG_H6:
+	case BR_TAG_UL: case BR_TAG_OL: case BR_TAG_LI:
+	case BR_TAG_BLOCKQUOTE: case BR_TAG_PRE: case BR_TAG_CENTER:
+	case BR_TAG_TABLE: case BR_TAG_THEAD: case BR_TAG_TBODY:
+	case BR_TAG_TFOOT: case BR_TAG_TR: case BR_TAG_CAPTION:
+	case BR_TAG_FORM: case BR_TAG_MAIN: case BR_TAG_HEADER:
+	case BR_TAG_FOOTER: case BR_TAG_NAV: case BR_TAG_SECTION:
+	case BR_TAG_ARTICLE: case BR_TAG_ASIDE: case BR_TAG_FIGURE:
+	case BR_TAG_FIGCAPTION: case BR_TAG_DETAILS: case BR_TAG_SUMMARY:
+	case BR_TAG_DL: case BR_TAG_DT: case BR_TAG_DD:
+	case BR_TAG_ADDRESS: case BR_TAG_HR:
+		return 1;
+	default:
+		return 0;
+	}
+}
+
+/* ---- string / entity helpers ---- */
+
+static unsigned int s_len(const char *s)
+{
+	unsigned int n = 0;
+
+	while (s && s[n])
+		n++;
+	return n;
+}
+
+static void s_copy(char *d, const char *s, unsigned int cap)
+{
+	unsigned int i = 0;
+
+	if (!cap)
+		return;
+	while (s && s[i] && i + 1 < cap) {
+		d[i] = s[i];
+		i++;
+	}
+	d[i] = '\0';
+}
+
+static int ci_eq_n(const char *a, const char *b, unsigned int n)
+{
+	unsigned int i;
+
+	for (i = 0; i < n; i++) {
+		char ca = a[i], cb = b[i];
+
+		if (ca >= 'A' && ca <= 'Z')
+			ca = (char)(ca - 'A' + 'a');
+		if (cb >= 'A' && cb <= 'Z')
+			cb = (char)(cb - 'A' + 'a');
+		if (ca != cb)
+			return 0;
+	}
+	return 1;
+}
+
+static int find_ci(const char *hay, unsigned int len, const char *needle,
+		   unsigned int nlen, unsigned int from)
+{
+	unsigned int i;
+
+	if (nlen == 0 || from >= len)
+		return -1;
+	for (i = from; i + nlen <= len; i++)
+		if (ci_eq_n(hay + i, needle, nlen))
+			return (int)i;
+	return -1;
+}
+
+static const struct {
+	const char *name;
+	const char *text;
+} entities[] = {
+	{ "amp", "&" }, { "lt", "<" }, { "gt", ">" }, { "quot", "\"" },
+	{ "apos", "'" }, { "nbsp", " " }, { "copy", "(c)" },
+	{ "reg", "(r)" }, { "trade", "(tm)" }, { "hellip", "..." },
+	{ "mdash", "-" }, { "ndash", "-" }, { "laquo", "<<" },
+	{ "raquo", ">>" }, { "bull", "*" }, { "middot", "." },
+	{ "times", "x" }, { "divide", "/" }, { "deg", "o" },
+	{ "plusmn", "+-" }, { "euro", "EUR" }, { "pound", "GBP" },
+	{ "yen", "JPY" }, { "cent", "c" }, { "sect", "S" },
+	{ "para", "P" }, { "frac12", "1/2" }, { "frac14", "1/4" },
+	{ "frac34", "3/4" }, { "sup2", "2" }, { "sup3", "3" },
+	{ "micro", "u" }, { "alpha", "a" }, { "beta", "b" },
+	{ "pi", "p" }, { "larr", "<-" }, { "rarr", "->" },
+	{ 0, 0 }
+};
+
+static void emit(char *out, unsigned int cap, unsigned int *n, char c)
+{
+	if (*n + 1 < cap)
+		out[(*n)++] = c;
+}
+
+static void decode_entity(const char *s, unsigned int len, unsigned int *pos,
+			  char *out, unsigned int cap, unsigned int *n)
+{
+	unsigned int start = *pos + 1, i = start;
+	unsigned int code = 0;
+	int ok = 0;
+
+	while (i < len && s[i] != ';' && i - start < 12)
+		i++;
+	if (i >= len || s[i] != ';') {
+		emit(out, cap, n, '&');
+		return;
+	}
+	if (s[start] == '#') {
+		unsigned int j = start + 1;
+
+		if (j < i && (s[j] == 'x' || s[j] == 'X')) {
+			j++;
+			for (; j < i; j++) {
+				char c = s[j];
+				int d = -1;
+				if (c >= '0' && c <= '9') d = c - '0';
+				else if (c >= 'a' && c <= 'f') d = c - 'a' + 10;
+				else if (c >= 'A' && c <= 'F') d = c - 'A' + 10;
+				if (d < 0) break;
+				code = code * 16 + (unsigned int)d;
+				ok = 1;
+			}
+		} else {
+			for (; j < i; j++) {
+				if (s[j] < '0' || s[j] > '9')
+					break;
+				code = code * 10 + (unsigned int)(s[j] - '0');
+				ok = 1;
+			}
+		}
+	} else {
+		unsigned int k;
+
+		for (k = 0; entities[k].name; k++) {
+			unsigned int el = s_len(entities[k].name);
+			unsigned int j;
+
+			if (el != i - start)
+				continue;
+			for (j = 0; j < el; j++)
+				if (s[start + j] != entities[k].name[j])
+					break;
+			if (j == el) {
+				const char *t = entities[k].text;
+				while (*t)
+					emit(out, cap, n, *t++);
+				*pos = i + 1;
+				return;
+			}
+		}
+	}
+	if (ok && code) {
+		if (code == 0x00A0)
+			emit(out, cap, n, ' ');
+		else if (code == 0x2013 || code == 0x2014)
+			emit(out, cap, n, '-');
+		else if (code == 0x2018 || code == 0x2019)
+			emit(out, cap, n, '\'');
+		else if (code == 0x201C || code == 0x201D)
+			emit(out, cap, n, '"');
+		else if (code == 0x2026) {
+			emit(out, cap, n, '.'); emit(out, cap, n, '.');
+			emit(out, cap, n, '.');
+		} else if (code <= 0xFF) {
+			emit(out, cap, n, (char)code);
+		} else {
+			emit(out, cap, n, '?');
+		}
+	} else {
+		emit(out, cap, n, '?');
+	}
+	*pos = i + 1;
+}
+
+/* Decode UTF-8 and entities into out.  collapse folds whitespace runs to one
+ * space and drops leading spaces.  Returns the output length. */
+static unsigned int decode_text(const char *s, unsigned int len, char *out,
+				unsigned int cap, int collapse)
+{
+	unsigned int i = 0, n = 0;
+
+	while (i < len) {
+		unsigned char c = (unsigned char)s[i];
+
+		if (c == '&') {
+			decode_entity(s, len, &i, out, cap, &n);
+			continue;
+		}
+		if (c < 0x80) {
+			i++;
+			if (collapse && (c == ' ' || c == '\t' || c == '\n' ||
+					 c == '\r' || c == '\f')) {
+				if (n > 0 && out[n - 1] == ' ')
+					continue;
+				emit(out, cap, &n, ' ');
+				continue;
+			}
+			if (!collapse && c == '\t') {
+				emit(out, cap, &n, ' ');
+				emit(out, cap, &n, ' ');
+				emit(out, cap, &n, ' ');
+				emit(out, cap, &n, ' ');
+				continue;
+			}
+			emit(out, cap, &n, (char)c);
+			continue;
+		}
+		/* UTF-8 -> Latin-1 where possible (the 8x16 font has those). */
+		if ((c & 0xE0) == 0xC0 && i + 1 < len) {
+			unsigned int cp = ((c & 0x1F) << 6) |
+					  ((unsigned char)s[i + 1] & 0x3F);
+			i += 2;
+			if (cp == 0xA0)
+				cp = ' ';
+			if (cp <= 0xFF)
+				emit(out, cap, &n, (char)cp);
+			else
+				emit(out, cap, &n, '?');
+		} else if ((c & 0xF0) == 0xE0 && i + 2 < len) {
+			unsigned int cp = ((c & 0x0F) << 12) |
+					  (((unsigned char)s[i + 1] & 0x3F) << 6) |
+					  ((unsigned char)s[i + 2] & 0x3F);
+			i += 3;
+			if (cp == 0x2013 || cp == 0x2014) {
+				emit(out, cap, &n, '-');
+			} else if (cp == 0x2018 || cp == 0x2019) {
+				emit(out, cap, &n, '\'');
+			} else if (cp == 0x201C || cp == 0x201D) {
+				emit(out, cap, &n, '"');
+			} else if (cp == 0x2026) {
+				emit(out, cap, &n, '.'); emit(out, cap, &n, '.');
+				emit(out, cap, &n, '.');
+			} else {
+				emit(out, cap, &n, '?');
+			}
+		} else {
+			i++;
+			emit(out, cap, &n, '?');
+		}
+	}
+	out[n] = '\0';
+	return n;
+}
+
+/* Store an attribute string (entity-decoded) in the attr arena.  0 = no
+ * space / empty. */
+static unsigned short store_attr(struct br_doc *d, const char *s,
+				 unsigned int len, unsigned int limit)
+{
+	unsigned int n;
+
+	if (d->attrs_used + 2 >= BR_ATTR_SIZE)
+		return 0;
+	if (len > limit)
+		len = limit;
+	n = decode_text(s, len, d->attrs + d->attrs_used,
+			BR_ATTR_SIZE - d->attrs_used, 0);
+	if (n == 0)
+		return 0;
+	{
+		unsigned short off = (unsigned short)d->attrs_used;
+		d->attrs_used += n + 1;
+		return off;
+	}
+}
+
+static const char *attr_ptr(struct br_doc *d, unsigned short off)
+{
+	return off ? d->attrs + off : "";
+}
+
+const char *br_href(struct br_doc *d, unsigned int node)
+{
+	return attr_ptr(d, d->nodes[node].href_off);
+}
+
+const char *br_src(struct br_doc *d, unsigned int node)
+{
+	return attr_ptr(d, d->nodes[node].src_off);
+}
+
+const char *br_alt(struct br_doc *d, unsigned int node)
+{
+	return attr_ptr(d, d->nodes[node].alt_off);
+}
+
+/* ---- document setup / node append ---- */
+
+void br_doc_init(struct br_doc *d)
+{
+	unsigned int i;
+
+	for (i = 0; i < sizeof(*d); i++)
+		((unsigned char *)d)[i] = 0;
+	d->nodes = nodes_store;
+	d->text = text_store;
+	d->attrs = attr_store;
+	d->rules = rule_store;
+	d->attrs_used = 1;      /* offset 0 = "no attribute" */
+	d->attrs[0] = '\0';
+	d->root = 0;
+}
+
+static void doc_reset(struct br_doc *d)
+{
+	unsigned int i;
+
+	d->nnode = 0;
+	d->text_used = 0;
+	d->attrs_used = 1;
+	d->attrs[0] = '\0';
+	d->nrules = 0;
+	d->title[0] = '\0';
+	d->truncated = 0;
+	d->plain = 0;
+	for (i = 0; i < BR_MAX_NODES; i++) {
+		d->nodes[i].type = BR_NODE_ELEM;
+		d->nodes[i].tag = BR_TAG_UNKNOWN;
+		d->nodes[i].flags = 0;
+		d->nodes[i].parent = 0;
+		d->nodes[i].first = d->nodes[i].last = 0;
+		d->nodes[i].next = 0;
+		d->nodes[i].text_off = d->nodes[i].text_len = 0;
+		d->nodes[i].href_off = d->nodes[i].class_off = 0;
+		d->nodes[i].id_off = d->nodes[i].style_off = 0;
+		d->nodes[i].src_off = d->nodes[i].alt_off = 0;
+		d->nodes[i].color_off = 0;
+		d->nodes[i].width_attr = d->nodes[i].height_attr = 0;
+		d->nodes[i].img_index = -1;
+	}
+}
+
+static unsigned int node_append(struct br_doc *d, unsigned int parent,
+				unsigned char type, unsigned char tag)
+{
+	unsigned int idx;
+	struct br_node *n;
+
+	if (d->nnode >= BR_MAX_NODES) {
+		d->truncated = 1;
+		return 0;
+	}
+	idx = d->nnode++;
+	n = &d->nodes[idx];
+	n->type = type;
+	n->tag = tag;
+	n->parent = (unsigned short)parent;
+	n->img_index = -1;
+	if (d->nodes[parent].last)
+		d->nodes[d->nodes[parent].last].next = (unsigned short)idx;
+	else
+		d->nodes[parent].first = (unsigned short)idx;
+	d->nodes[parent].last = (unsigned short)idx;
+	return idx;
+}
+
+static unsigned int append_text(struct br_doc *d, unsigned int parent,
+				const char *s, unsigned int len, int pre)
+{
+	char *dst;
+	unsigned int n;
+	unsigned int idx;
+
+	if (len == 0)
+		return 0;
+	if (d->text_used + 2 >= BR_TEXT_SIZE) {
+		d->truncated = 1;
+		return 0;
+	}
+	dst = d->text + d->text_used;
+	n = decode_text(s, len, dst, BR_TEXT_SIZE - d->text_used, !pre);
+	if (n == 0) {
+		d->text[d->text_used] = '\0';
+		return 0;
+	}
+	idx = node_append(d, parent, BR_NODE_TEXT, 0);
+	if (!idx)
+		return 0;
+	d->nodes[idx].text_off = (unsigned short)d->text_used;
+	d->nodes[idx].text_len = (unsigned short)n;
+	d->nodes[idx].flags = pre ? BR_NODE_PREFORMAT : 0;
+	d->text_used += n + 1;
+	return idx;
+}
+
+/* ---- attribute parsing ---- */
+
+static int is_space(char c)
+{
+	return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
+}
+
+static int str_eq(const char *a, const char *b);
+
+static unsigned int parse_uint(const char *s, unsigned int len)
+{
+	unsigned int i = 0, v = 0;
+
+	while (i < len && is_space(s[i]))
+		i++;
+	while (i < len && s[i] >= '0' && s[i] <= '9') {
+		v = v * 10 + (unsigned int)(s[i] - '0');
+		if (v > 4096)
+			v = 4096;
+		i++;
+	}
+	return v;
+}
+
+/* Parse attributes from `s` (between the tag name and '>'). */
+static void parse_attrs(struct br_doc *d, struct br_node *n,
+			const char *s, unsigned int len)
+{
+	unsigned int i = 0;
+
+	while (i < len) {
+		char name[16];
+		unsigned int nl = 0, vstart, vlen;
+		char quote = 0;
+
+		while (i < len && is_space(s[i]))
+			i++;
+		if (i >= len || s[i] == '/')
+			break;
+		while (i < len && !is_space(s[i]) && s[i] != '=' && s[i] != '>') {
+			char c = s[i++];
+			if (c >= 'A' && c <= 'Z')
+				c = (char)(c - 'A' + 'a');
+			if (nl + 1 < sizeof(name))
+				name[nl++] = c;
+		}
+		name[nl] = '\0';
+		while (i < len && is_space(s[i]))
+			i++;
+		if (i >= len || s[i] != '=') {
+			/* boolean attribute; nothing we use needs it */
+			continue;
+		}
+		i++;
+		while (i < len && is_space(s[i]))
+			i++;
+		if (i < len && (s[i] == '"' || s[i] == '\'')) {
+			quote = s[i++];
+			vstart = i;
+			while (i < len && s[i] != quote)
+				i++;
+			vlen = i - vstart;
+			if (i < len)
+				i++;
+		} else {
+			vstart = i;
+			while (i < len && !is_space(s[i]) && s[i] != '>')
+				i++;
+			vlen = i - vstart;
+		}
+		if (!nl)
+			continue;
+		if (str_eq(name, "href"))
+			n->href_off = store_attr(d, s + vstart, vlen, 220);
+		else if (str_eq(name, "class"))
+			n->class_off = store_attr(d, s + vstart, vlen, 120);
+		else if (str_eq(name, "id"))
+			n->id_off = store_attr(d, s + vstart, vlen, 64);
+		else if (str_eq(name, "style"))
+			n->style_off = store_attr(d, s + vstart, vlen, 240);
+		else if (str_eq(name, "src"))
+			n->src_off = store_attr(d, s + vstart, vlen, 220);
+		else if (str_eq(name, "alt"))
+			n->alt_off = store_attr(d, s + vstart, vlen, 120);
+		else if (str_eq(name, "color"))
+			n->color_off = store_attr(d, s + vstart, vlen, 32);
+		else if (str_eq(name, "width"))
+			n->width_attr = (unsigned short)parse_uint(s + vstart, vlen);
+		else if (str_eq(name, "height"))
+			n->height_attr = (unsigned short)parse_uint(s + vstart, vlen);
+	}
+}
+
+static int str_eq(const char *a, const char *b)
+{
+	unsigned int i = 0;
+
+	while (a[i] && b[i] && a[i] == b[i])
+		i++;
+	return a[i] == '\0' && b[i] == '\0';
+}
+
+/* ---- CSS ---- */
+
+enum {
+	PROP_COLOR, PROP_BG, PROP_SCALE, PROP_BOLD, PROP_ALIGN, PROP_UNDERLINE,
+	PROP_DISPLAY, PROP_MT, PROP_MR, PROP_MB, PROP_ML,
+	PROP_PT, PROP_PR, PROP_PB, PROP_PL, PROP_COUNT
+};
+
+struct color_name {
+	const char *name;
+	unsigned short rgb;
+};
+
+static const struct color_name color_names[] = {
+	{ "black", 0x0000 }, { "white", 0xFFFF }, { "red", 0xF800 },
+	{ "lime", 0x07E0 }, { "green", 0x0400 }, { "blue", 0x001F },
+	{ "yellow", 0xFFE0 }, { "cyan", 0x07FF }, { "aqua", 0x07FF },
+	{ "magenta", 0xF81F }, { "fuchsia", 0xF81F }, { "gray", 0x8410 },
+	{ "grey", 0x8410 }, { "silver", 0xC618 }, { "maroon", 0x8000 },
+	{ "olive", 0x8400 }, { "navy", 0x0010 }, { "purple", 0x8010 },
+	{ "teal", 0x0410 }, { "orange", 0xFD20 }, { "brown", 0xA145 },
+	{ "pink", 0xFE19 }, { "gold", 0xFEA0 }, { "lightgray", 0xD69A },
+	{ "lightgrey", 0xD69A }, { "darkgray", 0x528A },
+	{ "darkgrey", 0x528A }, { 0, 0 }
+};
+
+static int hexval(char c)
+{
+	if (c >= '0' && c <= '9')
+		return c - '0';
+	if (c >= 'a' && c <= 'f')
+		return c - 'a' + 10;
+	if (c >= 'A' && c <= 'F')
+		return c - 'A' + 10;
+	return -1;
+}
+
+static int named_color(const char *s, unsigned int len, unsigned short *out)
+{
+	unsigned int i;
+
+	for (i = 0; color_names[i].name; i++) {
+		unsigned int j, n = s_len(color_names[i].name);
+
+		if (n != len)
+			continue;
+		for (j = 0; j < n; j++) {
+			char c = s[j];
+			if (c >= 'A' && c <= 'Z')
+				c = (char)(c - 'A' + 'a');
+			if (c != color_names[i].name[j])
+				break;
+		}
+		if (j == n) {
+			*out = color_names[i].rgb;
+			return 1;
+		}
+	}
+	return 0;
+}
+
+/* Parse #rgb/#rrggbb/rgb(r,g,b)/a named colour. */
+static int parse_color(const char *s, unsigned int len, unsigned short *out)
+{
+	unsigned int i = 0;
+
+	while (i < len && is_space(s[i]))
+		i++;
+	if (i < len && s[i] == '#') {
+		int d[6], nd = 0;
+
+		i++;
+		while (i < len && nd < 6 && hexval(s[i]) >= 0)
+			d[nd++] = hexval(s[i++]);
+		if (nd == 3) {
+			unsigned int r = (unsigned int)d[0], g = (unsigned int)d[1];
+			unsigned int b = (unsigned int)d[2];
+			*out = (unsigned short)(((r * 17 >> 3) << 11) |
+						((g * 17 >> 2) << 5) |
+						(b * 17 >> 3));
+			return 1;
+		}
+		if (nd >= 6) {
+			unsigned int r = (unsigned int)(d[0] * 16 + d[1]);
+			unsigned int g = (unsigned int)(d[2] * 16 + d[3]);
+			unsigned int b = (unsigned int)(d[4] * 16 + d[5]);
+			*out = (unsigned short)(((r >> 3) << 11) |
+						((g >> 2) << 5) | (b >> 3));
+			return 1;
+		}
+		return 0;
+	}
+	if (i + 3 < len && ci_eq_n(s + i, "rgb", 3)) {
+		unsigned int v[3], k = 0;
+
+		while (i < len && s[i] != '(')
+			i++;
+		if (i >= len)
+			return 0;
+		i++;
+		while (k < 3 && i < len) {
+			unsigned int x = 0;
+			while (i < len && is_space(s[i]))
+				i++;
+			while (i < len && s[i] >= '0' && s[i] <= '9') {
+				x = x * 10 + (unsigned int)(s[i] - '0');
+				i++;
+			}
+			if (x > 255)
+				x = 255;
+			v[k++] = x;
+			while (i < len && s[i] != ',' && s[i] != ')')
+				i++;
+			if (i < len && s[i] == ',')
+				i++;
+		}
+		if (k == 3) {
+			*out = (unsigned short)(((v[0] >> 3) << 11) |
+						((v[1] >> 2) << 5) | (v[2] >> 3));
+			return 1;
+		}
+		return 0;
+	}
+	{
+		unsigned int j = i;
+
+		while (i < len && !is_space(s[i]))
+			i++;
+		return named_color(s + j, i - j, out);
+	}
+}
+
+static int parse_len(const char *s, unsigned int len, unsigned int *pos)
+{
+	unsigned int i = *pos;
+	int sign = 1;
+	int v = 0;
+
+	while (i < len && is_space(s[i]))
+		i++;
+	if (i < len && (s[i] == '-' || s[i] == '+')) {
+		if (s[i] == '-')
+			sign = -1;
+		i++;
+	}
+	while (i < len && s[i] >= '0' && s[i] <= '9') {
+		v = v * 10 + (s[i] - '0');
+		i++;
+	}
+	if (i < len && s[i] == '.') {
+		i++;
+		while (i < len && s[i] >= '0' && s[i] <= '9')
+			i++;
+	}
+	while (i < len && (s[i] == 'p' || s[i] == 'x' || s[i] == '%' ||
+			   s[i] == 'e' || s[i] == 'm' || s[i] == 'r' ||
+			   s[i] == 'a' || s[i] == 'd'))
+		i++;
+	*pos = i;
+	v *= sign;
+	if (v < -32)
+		v = -32;
+	if (v > 96)
+		v = 96;
+	return v;
+}
+
+static int parse_display(const char *s, unsigned int len)
+{
+	unsigned int i;
+
+	while (len && is_space(s[0])) { s++; len--; }
+	for (i = 0; i < len && !is_space(s[i]) && s[i] != ';'; i++)
+		;
+	if (i == 4 && ci_eq_n(s, "none", 4))
+		return BR_DISPLAY_NONE;
+	if (i == 5 && ci_eq_n(s, "block", 5))
+		return BR_DISPLAY_BLOCK;
+	if (i == 6 && ci_eq_n(s, "inline", 6))
+		return BR_DISPLAY_INLINE;
+	if (i == 12 && ci_eq_n(s, "inline-block", 12))
+		return BR_DISPLAY_INLINE;
+	if (i == 10 && ci_eq_n(s, "list-item", 10))
+		return BR_DISPLAY_BLOCK;
+	return BR_DISPLAY_INLINE;
+}
+
+static void parse_decls(const char *s, unsigned int len, struct br_decl *out,
+			unsigned int *nout)
+{
+	unsigned int i = 0;
+
+	*nout = 0;
+	while (i < len && *nout < 8) {
+		unsigned int pstart, pend, vstart, vend, k;
+		char prop[24];
+
+		while (i < len && (is_space(s[i]) || s[i] == ';'))
+			i++;
+		if (i >= len)
+			break;
+		pstart = i;
+		while (i < len && s[i] != ':' && s[i] != ';')
+			i++;
+		pend = i;
+		if (i >= len || s[i] != ':')
+			continue;
+		i++;
+		vstart = i;
+		while (i < len && s[i] != ';')
+			i++;
+		vend = i;
+		while (pstart < pend && is_space(s[pstart]))
+			pstart++;
+		while (pend > pstart && is_space(s[pend - 1]))
+			pend--;
+		while (vstart < vend && is_space(s[vstart]))
+			vstart++;
+		while (vend > vstart && is_space(s[vend - 1]))
+			vend--;
+		for (k = 0; k < sizeof(prop) - 1 && pstart + k < pend; k++) {
+			char c = s[pstart + k];
+			if (c >= 'A' && c <= 'Z')
+				c = (char)(c - 'A' + 'a');
+			prop[k] = c;
+		}
+		prop[k] = '\0';
+		if (str_eq(prop, "color")) {
+			unsigned short c;
+			if (parse_color(s + vstart, vend - vstart, &c)) {
+				out[*nout].prop = PROP_COLOR;
+				out[*nout].val = (short)c;
+				(*nout)++;
+			}
+		} else if (str_eq(prop, "background-color") ||
+			   str_eq(prop, "background")) {
+			unsigned short c;
+			if (parse_color(s + vstart, vend - vstart, &c)) {
+				out[*nout].prop = PROP_BG;
+				out[*nout].val = (short)c;
+				(*nout)++;
+			}
+		} else if (str_eq(prop, "font-size")) {
+			unsigned int pos = 0;
+			int v = parse_len(s + vstart, vend - vstart, &pos);
+			int scale = 1;
+
+			if (v >= 20)
+				scale = 2;
+			if (vend - vstart >= 5 &&
+			    ci_eq_n(s + vstart, "large", 5))
+				scale = 2;
+			if (vend - vstart >= 6 &&
+			    ci_eq_n(s + vstart, "x-large", 7))
+				scale = 2;
+			out[*nout].prop = PROP_SCALE;
+			out[*nout].val = (short)scale;
+			(*nout)++;
+		} else if (str_eq(prop, "font-weight")) {
+			int bold = 0;
+			if ((vend - vstart >= 4 &&
+			     ci_eq_n(s + vstart, "bold", 4)) ||
+			    (vend - vstart >= 3 &&
+			     ci_eq_n(s + vstart, "700", 3)) ||
+			    (vend - vstart >= 3 &&
+			     ci_eq_n(s + vstart, "800", 3)) ||
+			    (vend - vstart >= 3 &&
+			     ci_eq_n(s + vstart, "900", 3)))
+				bold = 1;
+			out[*nout].prop = PROP_BOLD;
+			out[*nout].val = (short)bold;
+			(*nout)++;
+		} else if (str_eq(prop, "text-align")) {
+			int a = BR_ALIGN_LEFT;
+			if ((vend - vstart >= 6 &&
+			     ci_eq_n(s + vstart, "center", 6)))
+				a = BR_ALIGN_CENTER;
+			else if ((vend - vstart >= 5 &&
+				  ci_eq_n(s + vstart, "right", 5)))
+				a = BR_ALIGN_RIGHT;
+			out[*nout].prop = PROP_ALIGN;
+			out[*nout].val = (short)a;
+			(*nout)++;
+		} else if (str_eq(prop, "text-decoration")) {
+			int u = 0;
+			if (vend - vstart >= 9 &&
+			    ci_eq_n(s + vstart, "underline", 9))
+				u = 1;
+			out[*nout].prop = PROP_UNDERLINE;
+			out[*nout].val = (short)u;
+			(*nout)++;
+		} else if (str_eq(prop, "display")) {
+			out[*nout].prop = PROP_DISPLAY;
+			out[*nout].val = (short)parse_display(s + vstart,
+							      vend - vstart);
+			(*nout)++;
+		} else if (str_eq(prop, "margin") || str_eq(prop, "padding")) {
+			int vals[4], nv = 0;
+			unsigned int pos = 0;
+			int is_pad = prop[0] == 'p';
+			unsigned char base = is_pad ? PROP_PT : PROP_MT;
+
+			while (pos < vend - vstart && nv < 4) {
+				vals[nv++] = parse_len(s + vstart,
+						       vend - vstart, &pos);
+				while (pos < vend - vstart &&
+				       is_space(s[vstart + pos]))
+					pos++;
+			}
+			if (nv == 1) {
+				vals[1] = vals[2] = vals[3] = vals[0];
+			} else if (nv == 2) {
+				vals[2] = vals[0];
+				vals[3] = vals[1];
+			} else if (nv == 3) {
+				vals[3] = vals[1];
+			}
+			if (nv > 0) {
+				/* props are T, R, B, L adjacent */
+				out[*nout].prop = base;
+				out[*nout].val = (short)vals[0];
+				(*nout)++;
+				out[*nout].prop = (unsigned char)(base + 1);
+				out[*nout].val = (short)vals[1];
+				(*nout)++;
+				out[*nout].prop = (unsigned char)(base + 2);
+				out[*nout].val = (short)vals[2];
+				(*nout)++;
+				out[*nout].prop = (unsigned char)(base + 3);
+				out[*nout].val = (short)vals[3];
+				(*nout)++;
+			}
+		} else if (str_eq(prop, "margin-top") ||
+			   str_eq(prop, "margin-right") ||
+			   str_eq(prop, "margin-bottom") ||
+			   str_eq(prop, "margin-left") ||
+			   str_eq(prop, "padding-top") ||
+			   str_eq(prop, "padding-right") ||
+			   str_eq(prop, "padding-bottom") ||
+			   str_eq(prop, "padding-left")) {
+			unsigned int pos = 0;
+			int v = parse_len(s + vstart, vend - vstart, &pos);
+			unsigned char p = PROP_MT;
+
+			if (prop[0] == 'p')
+				p = PROP_PT;
+			if (str_eq(prop + 7, "right"))
+				p = (unsigned char)(p + 1);
+			else if (str_eq(prop + 7, "bottom"))
+				p = (unsigned char)(p + 2);
+			else if (str_eq(prop + 7, "left"))
+				p = (unsigned char)(p + 3);
+			out[*nout].prop = p;
+			out[*nout].val = (short)v;
+			(*nout)++;
+		}
+	}
+}
+
+static void parse_css(struct br_doc *d, const char *s, unsigned int len)
+{
+	unsigned int i = 0;
+
+	while (i < len && d->nrules < BR_MAX_RULES) {
+		unsigned int sstart, send, bstart, bend, j;
+		struct br_decl decls[8];
+		unsigned int nd;
+
+		while (i < len && is_space(s[i]))
+			i++;
+		if (i + 1 < len && s[i] == '/' && s[i + 1] == '*') {
+			i += 2;
+			while (i + 1 < len && !(s[i] == '*' && s[i + 1] == '/'))
+				i++;
+			i += 2;
+			continue;
+		}
+		if (i >= len || s[i] == '}')
+			break;
+		sstart = i;
+		while (i < len && s[i] != '{')
+			i++;
+		if (i >= len)
+			break;
+		send = i;
+		i++;
+		bstart = i;
+		while (i < len && s[i] != '}')
+			i++;
+		bend = i;
+		if (i < len)
+			i++;
+		while (sstart < send && is_space(s[sstart]))
+			sstart++;
+		while (send > sstart && is_space(s[send - 1]))
+			send--;
+		if (sstart == send)
+			continue;
+		if (s[sstart] == '@')
+			continue;
+		/* Ignore sibling combinators and pseudo-classes: they need
+		 * state we do not model. */
+		for (j = sstart; j < send; j++)
+			if (s[j] == '+' || s[j] == '~' || s[j] == ':')
+				break;
+		if (j < send)
+			continue;
+		parse_decls(s + bstart, bend - bstart, decls, &nd);
+		if (!nd)
+			continue;
+		/* Split a comma-separated selector list into separate rules. */
+		j = sstart;
+		while (j <= send && d->nrules < BR_MAX_RULES) {
+			unsigned int q = j, e, k;
+			char sel[80];
+			unsigned int off;
+
+			while (q < send && s[q] != ',')
+				q++;
+			e = q;
+			while (j < e && is_space(s[j]))
+				j++;
+			while (e > j && is_space(s[e - 1]))
+				e--;
+			if (e > j) {
+				for (k = 0; k < sizeof(sel) - 1 && j + k < e; k++)
+					sel[k] = s[j + k];
+				sel[k] = '\0';
+				off = store_attr(d, sel, k, 79);
+				if (off) {
+					struct br_rule *r = &d->rules[d->nrules++];
+					r->sel_off = (unsigned short)off;
+					r->nd = (unsigned char)nd;
+					for (k = 0; k < nd; k++)
+						r->d[k] = decls[k];
+				}
+			}
+			j = q + 1;
+			if (q >= send)
+				break;
+		}
+	}
+}
+
+/* ---- selector matching ---- */
+
+static int class_has(struct br_doc *d, unsigned int node, const char *cls,
+		     unsigned int clen)
+{
+	const char *s = attr_ptr(d, d->nodes[node].class_off);
+	unsigned int i = 0;
+
+	while (s[i]) {
+		unsigned int st, n;
+
+		while (s[i] && is_space(s[i]))
+			i++;
+		st = i;
+		while (s[i] && !is_space(s[i]))
+			i++;
+		n = i - st;
+		if (n == clen && ci_eq_n(s + st, cls, n))
+			return 1;
+	}
+	return 0;
+}
+
+static int id_eq(struct br_doc *d, unsigned int node, const char *id,
+		 unsigned int len)
+{
+	const char *s = attr_ptr(d, d->nodes[node].id_off);
+	unsigned int i;
+
+	for (i = 0; i < len; i++)
+		if (s[i] != id[i])
+			return 0;
+	return s[len] == '\0';
+}
+
+static int is_ident(char c)
+{
+	return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
+	       (c >= '0' && c <= '9') || c == '-' || c == '_';
+}
+
+static int compound_match(struct br_doc *d, unsigned int node, const char *s,
+			  unsigned int len)
+{
+	unsigned int i = 0;
+	int got = 0;
+
+	if (i < len && s[i] == '*') {
+		i++;
+		got = 1;
+	} else if (i < len && is_ident(s[i])) {
+		char name[16];
+		unsigned int n = 0, tag;
+
+		while (i < len && is_ident(s[i]) && n + 1 < sizeof(name))
+			name[n++] = s[i++];
+		name[n] = '\0';
+		tag = br_tag_from_name(name);
+		if (tag != d->nodes[node].tag)
+			return 0;
+		got = 1;
+	}
+	while (i < len) {
+		if (s[i] == '.') {
+			unsigned int st;
+			i++;
+			st = i;
+			while (i < len && is_ident(s[i]))
+				i++;
+			if (!class_has(d, node, s + st, i - st))
+				return 0;
+			got = 1;
+		} else if (s[i] == '#') {
+			unsigned int st;
+			i++;
+			st = i;
+			while (i < len && is_ident(s[i]))
+				i++;
+			if (!id_eq(d, node, s + st, i - st))
+				return 0;
+			got = 1;
+		} else if (s[i] == ':') {
+			return 0;      /* pseudo-classes are not modelled */
+		} else {
+			i++;
+		}
+	}
+	return got;
+}
+
+static unsigned int selector_specificity(const char *s, unsigned int len)
+{
+	unsigned int i, spec = 0;
+
+	for (i = 0; i < len; i++) {
+		if (s[i] == '#')
+			spec += 100;
+		else if (s[i] == '.')
+			spec += 10;
+		else if (i == 0 || is_space(s[i - 1]) || s[i - 1] == '>') {
+			if (is_ident(s[i]))
+				spec += 1;
+		}
+	}
+	return spec;
+}
+
+/* Match one complex selector; returns specificity or -1. */
+static int selector_match(struct br_doc *d, unsigned int node, const char *s,
+			  unsigned int len)
+{
+	struct {
+		unsigned int start, end;
+		int child;
+	} parts[8];
+	int np = 0;
+	unsigned int i = 0;
+	int right;
+
+	while (i < len) {
+		int child = 0;
+		unsigned int st, e;
+
+		while (i < len && is_space(s[i]))
+			i++;
+		if (i < len && s[i] == '>') {
+			child = 1;
+			i++;
+			while (i < len && is_space(s[i]))
+				i++;
+		}
+		if (i >= len)
+			break;
+		st = i;
+		while (i < len && !is_space(s[i]) && s[i] != '>')
+			i++;
+		e = i;
+		if (np < 8) {
+			parts[np].start = st;
+			parts[np].end = e;
+			parts[np].child = child;
+			np++;
+		}
+	}
+	if (!np)
+		return -1;
+	if (!compound_match(d, node, s + parts[np - 1].start,
+			    parts[np - 1].end - parts[np - 1].start))
+		return -1;
+	right = np - 1;
+	while (right > 0) {
+		unsigned int p = d->nodes[node].parent;
+
+		if (!p)
+			return -1;
+		if (parts[right].child) {
+			if (!compound_match(d, p, s + parts[right - 1].start,
+					    parts[right - 1].end -
+					    parts[right - 1].start))
+				return -1;
+			node = p;
+		} else {
+			while (p && !compound_match(d, p,
+						    s + parts[right - 1].start,
+						    parts[right - 1].end -
+						    parts[right - 1].start))
+				p = d->nodes[p].parent;
+			if (!p)
+				return -1;
+			node = p;
+		}
+		right--;
+	}
+	return (int)selector_specificity(s, len);
+}
+
+static void apply_decl(struct br_style *st, const struct br_decl *dcl)
+{
+	switch (dcl->prop) {
+	case PROP_COLOR:
+		st->color = (unsigned short)dcl->val;
+		break;
+	case PROP_BG:
+		st->bg = (unsigned short)dcl->val;
+		st->has_bg = 1;
+		break;
+	case PROP_SCALE:
+		st->scale = (unsigned char)(dcl->val >= 2 ? 2 : 1);
+		break;
+	case PROP_BOLD:
+		st->bold = (unsigned char)(dcl->val != 0);
+		break;
+	case PROP_ALIGN:
+		st->align = (unsigned char)dcl->val;
+		break;
+	case PROP_UNDERLINE:
+		st->underline = (unsigned char)(dcl->val != 0);
+		break;
+	case PROP_DISPLAY:
+		st->display = (unsigned char)dcl->val;
+		break;
+	case PROP_MT: st->mt = dcl->val; break;
+	case PROP_MR: st->mr = dcl->val; break;
+	case PROP_MB: st->mb = dcl->val; break;
+	case PROP_ML: st->ml = dcl->val; break;
+	case PROP_PT: st->pt = dcl->val; break;
+	case PROP_PR: st->pr = dcl->val; break;
+	case PROP_PB: st->pb = dcl->val; break;
+	case PROP_PL: st->pl = dcl->val; break;
+	default: break;
+	}
+}
+
+void br_style_for(struct br_doc *d, unsigned int node,
+		  const struct br_style *parent, struct br_style *out)
+{
+	unsigned int tag;
+	short best[PROP_COUNT];
+	unsigned int i;
+
+	*out = *parent;
+	out->has_bg = 0;
+	out->mt = out->mr = out->mb = out->ml = 0;
+	out->pt = out->pr = out->pb = out->pl = 0;
+	tag = d->nodes[node].tag;
+	out->display = br_tag_is_block(tag) ? BR_DISPLAY_BLOCK :
+					      BR_DISPLAY_INLINE;
+	for (i = 0; i < PROP_COUNT; i++)
+		best[i] = -1;
+
+	switch (tag) {
+	case BR_TAG_HEAD:
+	case BR_TAG_TITLE:
+	case BR_TAG_META:
+	case BR_TAG_LINK:
+	case BR_TAG_BASE:
+	case BR_TAG_SCRIPT:
+	case BR_TAG_STYLE:
+		out->display = BR_DISPLAY_NONE;
+		break;
+	case BR_TAG_BODY:
+		out->mt = out->mb = out->ml = out->mr = 4;
+		break;
+	case BR_TAG_P:
+		out->mt = out->mb = 8;
+		break;
+	case BR_TAG_H1:
+		out->scale = 2; out->bold = 1;
+		out->mt = 10; out->mb = 6;
+		break;
+	case BR_TAG_H2:
+		out->scale = 2; out->bold = 1;
+		out->mt = 8; out->mb = 4;
+		break;
+	case BR_TAG_H3: case BR_TAG_H4: case BR_TAG_H5: case BR_TAG_H6:
+		out->bold = 1; out->mt = 6; out->mb = 3;
+		break;
+	case BR_TAG_UL: case BR_TAG_OL:
+		out->mt = out->mb = 6; out->pl = 20;
+		break;
+	case BR_TAG_LI:
+		out->mt = out->mb = 2;
+		break;
+	case BR_TAG_BLOCKQUOTE:
+		out->mt = out->mb = 6; out->ml = out->mr = 16;
+		break;
+	case BR_TAG_PRE:
+		out->mt = out->mb = 8; out->pl = 8;
+		out->has_bg = 1; out->bg = 0xEF5D;
+		break;
+	case BR_TAG_CENTER:
+		out->align = BR_ALIGN_CENTER;
+		break;
+	case BR_TAG_A:
+		out->color = 0x001B; out->underline = 1;
+		break;
+	case BR_TAG_B: case BR_TAG_STRONG:
+		out->bold = 1;
+		break;
+	case BR_TAG_CODE:
+		out->color = 0x8010;
+		break;
+	case BR_TAG_TD: case BR_TAG_TH:
+		out->pr = 12;
+		break;
+	default:
+		break;
+	}
+
+	/* presentational <font color>: author CSS below still wins */
+	if (d->nodes[node].color_off) {
+		unsigned short c;
+		const char *v = attr_ptr(d, d->nodes[node].color_off);
+		if (parse_color(v, s_len(v), &c))
+			out->color = c;
+	}
+
+	for (i = 0; i < d->nrules; i++) {
+		struct br_rule *r = &d->rules[i];
+		const char *sel = attr_ptr(d, r->sel_off);
+		int spec = selector_match(d, node, sel, s_len(sel));
+		unsigned int k;
+
+		if (spec < 0)
+			continue;
+		for (k = 0; k < r->nd; k++) {
+			unsigned char p = r->d[k].prop;
+			if (spec >= best[p]) {
+				apply_decl(out, &r->d[k]);
+				best[p] = (short)spec;
+			}
+		}
+	}
+
+	if (d->nodes[node].style_off) {
+		struct br_decl decls[8];
+		unsigned int nd, k;
+		const char *v = attr_ptr(d, d->nodes[node].style_off);
+
+		parse_decls(v, s_len(v), decls, &nd);
+		for (k = 0; k < nd; k++)
+			apply_decl(out, &decls[k]);
+	}
+}
+
+/* ---- HTML parser ---- */
+
+static void stack_recount_pre(struct br_doc *d, unsigned short *stack,
+			      unsigned int sp, int *pre)
+{
+	unsigned int i;
+
+	*pre = 0;
+	for (i = 1; i <= sp; i++)
+		if (d->nodes[stack[i]].tag == BR_TAG_PRE)
+			(*pre)++;
+}
+
+static void implicit_close(struct br_doc *d, unsigned short *stack,
+			   unsigned int *sp, unsigned int tag)
+{
+	while (*sp > 0) {
+		unsigned int top = d->nodes[stack[*sp]].tag;
+
+		if (top == BR_TAG_P && br_tag_is_block(tag)) {
+			(*sp)--;
+			continue;
+		}
+		if (top == BR_TAG_LI && tag == BR_TAG_LI) {
+			(*sp)--;
+			continue;
+		}
+		if ((top == BR_TAG_TD || top == BR_TAG_TH) &&
+		    (tag == BR_TAG_TD || tag == BR_TAG_TH || tag == BR_TAG_TR)) {
+			(*sp)--;
+			continue;
+		}
+		if (top == BR_TAG_TR && tag == BR_TAG_TR) {
+			(*sp)--;
+			continue;
+		}
+		break;
+	}
+}
+
+int br_parse(struct br_doc *d, const char *html, unsigned int len)
+{
+	unsigned short stack[64];
+	unsigned int sp = 0;
+	unsigned int i = 0;
+	int pre = 0;
+	unsigned int css_len = 0;
+
+	if (!d)
+		return -1;
+	if (!d->nodes)
+		br_doc_init(d);
+	doc_reset(d);
+	stack[0] = 0;
+	d->nodes[0].type = BR_NODE_ELEM;
+	d->nodes[0].tag = BR_TAG_UNKNOWN;
+
+	while (i < len) {
+		if (html[i] != '<') {
+			unsigned int st = i;
+
+			while (i < len && html[i] != '<')
+				i++;
+			if (sp <= 63)
+				append_text(d, stack[sp], html + st, i - st, pre);
+			continue;
+		}
+
+		if (i + 3 < len && html[i + 1] == '!' && html[i + 2] == '-' &&
+		    html[i + 3] == '-') {
+			int p = find_ci(html, len, "-->", 3, i + 4);
+			i = p >= 0 ? (unsigned int)p + 3 : len;
+			continue;
+		}
+		if (i + 1 < len && (html[i + 1] == '!' || html[i + 1] == '?')) {
+			while (i < len && html[i] != '>')
+				i++;
+			if (i < len)
+				i++;
+			continue;
+		}
+		if (i + 1 < len && html[i + 1] == '/') {
+			unsigned int ns = i + 2, ne, tag;
+
+			while (ns < len && is_space(html[ns]))
+				ns++;
+			ne = ns;
+			while (ne < len && is_ident(html[ne]))
+				ne++;
+			if (ne == ns) {
+				i++;
+				continue;
+			}
+			{
+				char name[16];
+				unsigned int k, n = ne - ns;
+				if (n >= sizeof(name))
+					n = sizeof(name) - 1;
+				for (k = 0; k < n; k++)
+					name[k] = html[ns + k];
+				name[n] = '\0';
+				tag = br_tag_from_name(name);
+			}
+			i = ne;
+			while (i < len && html[i] != '>')
+				i++;
+			if (i < len)
+				i++;
+			{
+				unsigned int k;
+				for (k = sp; k > 0; k--) {
+					if (d->nodes[stack[k]].tag == tag) {
+						sp = k - 1;
+						break;
+					}
+				}
+				stack_recount_pre(d, stack, sp, &pre);
+			}
+			continue;
+		}
+
+		/* start tag */
+		{
+			unsigned int ns = i + 1, ne, tag, k, n;
+			char name[16];
+			unsigned int attr_start, attr_end;
+			int selfclose = 0;
+
+			while (ns < len && is_space(html[ns]))
+				ns++;
+			ne = ns;
+			while (ne < len && (is_ident(html[ne]) || html[ne] == ':'))
+				ne++;
+			if (ne == ns) {
+				/* stray '<' */
+				append_text(d, stack[sp], html + i, 1, pre);
+				i++;
+				continue;
+			}
+			n = ne - ns;
+			if (n >= sizeof(name))
+				n = sizeof(name) - 1;
+			for (k = 0; k < n; k++)
+				name[k] = html[ns + k];
+			name[n] = '\0';
+			tag = br_tag_from_name(name);
+
+			attr_start = ne;
+			{
+				unsigned int q = ne;
+				char quote = 0;
+				while (q < len) {
+					char c = html[q];
+					if (quote) {
+						if (c == quote)
+							quote = 0;
+					} else if (c == '"' || c == '\'') {
+						quote = c;
+					} else if (c == '>') {
+						break;
+					}
+					q++;
+				}
+				attr_end = q;
+				if (q > attr_start && html[q - 1] == '/')
+					selfclose = 1;
+				i = q < len ? q + 1 : len;
+			}
+
+			if (tag == BR_TAG_SCRIPT) {
+				int p = find_ci(html, len, "</script", 8, i);
+				i = p >= 0 ? (unsigned int)p + 8 : len;
+				while (i < len && html[i] != '>')
+					i++;
+				if (i < len)
+					i++;
+				continue;
+			}
+			if (tag == BR_TAG_STYLE) {
+				int p = find_ci(html, len, "</style", 7, i);
+				unsigned int end = p >= 0 ? (unsigned int)p : len;
+				unsigned int cend = end;
+				while (cend > i && is_space(html[cend - 1]))
+					cend--;
+				if (css_len + (cend - i) + 2 < BR_CSS_SIZE) {
+					for (k = i; k < cend; k++)
+						css_store[css_len++] = html[k];
+					css_store[css_len++] = '\n';
+				}
+				i = p >= 0 ? (unsigned int)p + 7 : len;
+				while (i < len && html[i] != '>')
+					i++;
+				if (i < len)
+					i++;
+				continue;
+			}
+			if (tag == BR_TAG_TITLE) {
+				int p = find_ci(html, len, "</title", 7, i);
+				unsigned int end = p >= 0 ? (unsigned int)p : len;
+				unsigned int tn = 0;
+				char tmp[BR_TITLE_MAX];
+
+				tn = decode_text(html + i, end - i, tmp,
+						 sizeof(tmp), 1);
+				(void)tn;
+				s_copy(d->title, tmp, sizeof(d->title));
+				i = p >= 0 ? (unsigned int)p + 7 : len;
+				while (i < len && html[i] != '>')
+					i++;
+				if (i < len)
+					i++;
+				continue;
+			}
+
+			if (tag == BR_TAG_BR || tag == BR_TAG_HR ||
+			    tag == BR_TAG_IMG || br_tag_is_void(tag)) {
+				unsigned int idx;
+				implicit_close(d, stack, &sp, tag);
+				idx = node_append(d, stack[sp], BR_NODE_ELEM,
+						  (unsigned char)tag);
+				if (idx)
+					parse_attrs(d, &d->nodes[idx],
+						    html + attr_start,
+						    attr_end - attr_start);
+				continue;
+			}
+
+			if (sp >= 63) {
+				d->truncated = 1;
+				continue;
+			}
+			implicit_close(d, stack, &sp, tag);
+			{
+				unsigned int idx = node_append(d, stack[sp],
+							       BR_NODE_ELEM,
+							       (unsigned char)tag);
+				if (!idx)
+					continue;
+				parse_attrs(d, &d->nodes[idx],
+					    html + attr_start,
+					    attr_end - attr_start);
+				if (!selfclose) {
+					sp++;
+					stack[sp] = (unsigned short)idx;
+					if (tag == BR_TAG_PRE)
+						pre++;
+				}
+			}
+		}
+	}
+
+	if (css_len)
+		parse_css(d, css_store, css_len);
+	return 0;
+}
+
+int br_parse_plain(struct br_doc *d, const char *text, unsigned int len)
+{
+	if (!d->nodes)
+		br_doc_init(d);
+	doc_reset(d);
+	d->plain = 1;
+	d->nodes[0].type = BR_NODE_ELEM;
+	d->nodes[0].tag = BR_TAG_UNKNOWN;
+	append_text(d, 0, text, len, 1);
+	return 0;
+}
+
+/* A standalone image response: a synthetic document with one <img>.  The
+ * caller decodes the already-fetched body into image slot 0 and sets the
+ * returned node's img_index. */
+unsigned int br_parse_image_doc(struct br_doc *d, const char *src)
+{
+	unsigned int idx;
+
+	if (!d->nodes)
+		br_doc_init(d);
+	doc_reset(d);
+	d->nodes[0].type = BR_NODE_ELEM;
+	d->nodes[0].tag = BR_TAG_UNKNOWN;
+	idx = node_append(d, 0, BR_NODE_ELEM, BR_TAG_IMG);
+	if (!idx)
+		return 0;
+	d->nodes[idx].src_off = store_attr(d, src, s_len(src), 220);
+	return idx;
+}

+ 137 - 0
browser_html.h

@@ -0,0 +1,137 @@
+/* browser_html: a small tolerant HTML tree + CSS cascade for the browser.
+ *
+ * Freestanding and independent of ngui: it parses a byte buffer into a static
+ * node/string arena and resolves the subset of CSS the browser understands.
+ * One document is live at a time (the browser is single-threaded). */
+#ifndef BROWSER_HTML_H
+#define BROWSER_HTML_H
+
+#define BR_MAX_NODES     1536
+#define BR_TEXT_SIZE     24576
+#define BR_ATTR_SIZE     16384
+#define BR_CSS_SIZE      12288
+#define BR_MAX_RULES     96
+#define BR_TITLE_MAX     96
+
+/* Node types. */
+#define BR_NODE_TEXT     0
+#define BR_NODE_ELEM     1
+
+/* Text-node flag: whitespace was preserved (<pre>). */
+#define BR_NODE_PREFORMAT 1
+
+/* Display values in struct br_style. */
+#define BR_DISPLAY_INLINE 0
+#define BR_DISPLAY_BLOCK  1
+#define BR_DISPLAY_NONE   2
+
+/* Text alignment. */
+#define BR_ALIGN_LEFT   0
+#define BR_ALIGN_CENTER 1
+#define BR_ALIGN_RIGHT  2
+
+enum br_tag {
+	BR_TAG_UNKNOWN = 0,
+	BR_TAG_HTML, BR_TAG_HEAD, BR_TAG_BODY, BR_TAG_TITLE, BR_TAG_STYLE,
+	BR_TAG_SCRIPT, BR_TAG_META, BR_TAG_LINK, BR_TAG_BASE, BR_TAG_NOSCRIPT,
+	BR_TAG_P, BR_TAG_DIV, BR_TAG_SPAN, BR_TAG_A, BR_TAG_B, BR_TAG_STRONG,
+	BR_TAG_I, BR_TAG_EM, BR_TAG_U, BR_TAG_CODE, BR_TAG_FONT, BR_TAG_SMALL,
+	BR_TAG_BIG, BR_TAG_BR, BR_TAG_HR, BR_TAG_IMG,
+	BR_TAG_H1, BR_TAG_H2, BR_TAG_H3, BR_TAG_H4, BR_TAG_H5, BR_TAG_H6,
+	BR_TAG_UL, BR_TAG_OL, BR_TAG_LI, BR_TAG_BLOCKQUOTE, BR_TAG_PRE,
+	BR_TAG_CENTER, BR_TAG_TABLE, BR_TAG_THEAD, BR_TAG_TBODY, BR_TAG_TFOOT,
+	BR_TAG_TR, BR_TAG_TD, BR_TAG_TH, BR_TAG_CAPTION,
+	BR_TAG_FORM, BR_TAG_INPUT, BR_TAG_BUTTON, BR_TAG_LABEL, BR_TAG_SELECT,
+	BR_TAG_OPTION, BR_TAG_TEXTAREA, BR_TAG_IFRAME, BR_TAG_SVG,
+	BR_TAG_VIDEO, BR_TAG_AUDIO, BR_TAG_CANVAS, BR_TAG_OBJECT,
+	BR_TAG_MAIN, BR_TAG_HEADER, BR_TAG_FOOTER, BR_TAG_NAV, BR_TAG_SECTION,
+	BR_TAG_ARTICLE, BR_TAG_ASIDE, BR_TAG_FIGURE, BR_TAG_FIGCAPTION,
+	BR_TAG_DETAILS, BR_TAG_SUMMARY, BR_TAG_DL, BR_TAG_DT, BR_TAG_DD,
+	BR_TAG_ADDRESS, BR_TAG_MARK, BR_TAG_TIME, BR_TAG_ABBR, BR_TAG_CITE,
+	BR_TAG_Q, BR_TAG_S, BR_TAG_STRIKE, BR_TAG_SUB, BR_TAG_SUP,
+	BR_TAG_BGSOUND, BR_TAG_EMBED, BR_TAG_PARAM, BR_TAG_SOURCE,
+	BR_TAG_TRACK, BR_TAG_WBR, BR_TAG_AREA, BR_TAG_COL, BR_TAG_COLGROUP
+};
+
+struct br_style {
+	unsigned short color;
+	unsigned short bg;
+	unsigned char has_bg;
+	unsigned char scale;        /* 1 or 2 */
+	unsigned char bold;
+	unsigned char underline;
+	unsigned char align;        /* BR_ALIGN_* */
+	unsigned char display;      /* BR_DISPLAY_* */
+	signed short mt, mb, ml, mr;
+	signed short pt, pb, pl, pr;
+};
+
+struct br_node {
+	unsigned char type;
+	unsigned char tag;
+	unsigned char flags;
+	unsigned char spare;
+	unsigned short parent;
+	unsigned short first;
+	unsigned short last;
+	unsigned short next;
+	unsigned short text_off;    /* text arena offset (text nodes) */
+	unsigned short text_len;
+	unsigned short href_off;
+	unsigned short class_off;
+	unsigned short id_off;
+	unsigned short style_off;
+	unsigned short src_off;
+	unsigned short alt_off;
+	unsigned short color_off;
+	unsigned short width_attr;
+	unsigned short height_attr;
+	short img_index;            /* -1 until the image is loaded */
+};
+
+struct br_decl {
+	unsigned char prop;
+	short val;
+};
+
+struct br_rule {
+	unsigned short sel_off;     /* selector text in the attr arena */
+	unsigned char nd;
+	struct br_decl d[8];
+};
+
+struct br_doc {
+	struct br_node *nodes;
+	unsigned int nnode;
+	unsigned int root;
+	char *text;
+	unsigned int text_used;
+	char *attrs;
+	unsigned int attrs_used;
+	struct br_rule *rules;
+	unsigned int nrules;
+	char title[BR_TITLE_MAX];
+	int truncated;
+	int plain;                  /* text/plain: one preformatted text node */
+};
+
+void br_doc_init(struct br_doc *d);
+int  br_parse(struct br_doc *d, const char *html, unsigned int len);
+int  br_parse_plain(struct br_doc *d, const char *text, unsigned int len);
+unsigned int br_parse_image_doc(struct br_doc *d, const char *src);
+
+/* A node's style: parent inherited values, UA defaults, matching rules, then
+ * the inline style attribute. */
+void br_style_for(struct br_doc *d, unsigned int node,
+		  const struct br_style *parent, struct br_style *out);
+
+int  br_tag_is_block(unsigned int tag);
+int  br_tag_is_void(unsigned int tag);
+const char *br_tag_name(unsigned int tag);
+unsigned int br_tag_from_name(const char *name);
+
+const char *br_href(struct br_doc *d, unsigned int node);
+const char *br_src(struct br_doc *d, unsigned int node);
+const char *br_alt(struct br_doc *d, unsigned int node);
+
+#endif

+ 56 - 13
ngui.c

@@ -442,19 +442,34 @@ void ngui_line(struct ngui *ui, int x0, int y0, int x1, int y1,
 }
 
 static void ngui_glyph(struct ngui *ui, int x, int y, unsigned char c,
-		       unsigned short color)
+		       unsigned short color, int scale, int bold)
 {
 	const unsigned char *g = &font_8x16[(unsigned int)c * FONT_8X16_ROWS];
-	int row, col;
+	int row, col, sx, sy;
 
+	if (scale < 1)
+		scale = 1;
 	for (row = 0; row < FONT_8X16_ROWS; row++) {
 		unsigned char bits = g[row];
 
 		if (!bits)
 			continue;
-		for (col = 0; col < 8; col++)
-			if (bits & (0x80u >> col))
-				ngui_pixel(ui, x + col, y + row, color);
+		for (col = 0; col < 8; col++) {
+			if (!(bits & (0x80u >> col)))
+				continue;
+			for (sy = 0; sy < scale; sy++) {
+				for (sx = 0; sx < scale; sx++) {
+					ngui_pixel(ui,
+						   x + col * scale + sx +
+							(bold && scale == 1 ? 1 : 0),
+						   y + row * scale + sy,
+						   color);
+				}
+			}
+			if (bold && scale > 1)
+				ngui_pixel(ui, x + col * scale + scale,
+					   y + row * scale, color);
+		}
 	}
 }
 
@@ -463,13 +478,41 @@ unsigned int ngui_text_width(const char *s)
 	return slen(s) * 8;
 }
 
+unsigned int ngui_text_width_n(const char *s, unsigned int n, int scale)
+{
+	unsigned int i = 0;
+
+	(void)s;
+	if (scale < 1)
+		scale = 1;
+	return n * 8u * (unsigned int)scale;
+}
+
+void ngui_text_n(struct ngui *ui, int x, int y, const char *s, unsigned int n,
+		 unsigned short color)
+{
+	unsigned int i;
+
+	for (i = 0; i < n && s && s[i]; i++)
+		ngui_glyph(ui, x + (int)i * 8, y, (unsigned char)s[i], color, 1, 0);
+}
+
 void ngui_text(struct ngui *ui, int x, int y, const char *s,
 	       unsigned short color)
 {
-	int i;
+	ngui_text_n(ui, x, y, s, slen(s), color);
+}
+
+void ngui_text_styled(struct ngui *ui, int x, int y, const char *s,
+		      unsigned int n, unsigned short color, int scale, int bold)
+{
+	unsigned int i;
 
-	for (i = 0; s && s[i]; i++)
-		ngui_glyph(ui, x + i * 8, y, (unsigned char)s[i], color);
+	if (scale < 1)
+		scale = 1;
+	for (i = 0; i < n && s && s[i]; i++)
+		ngui_glyph(ui, x + (int)i * 8 * scale, y, (unsigned char)s[i],
+			   color, scale, bold);
 }
 
 void ngui_text_ellipsis(struct ngui *ui, struct ngui_rect r, int x, int y,
@@ -484,14 +527,14 @@ void ngui_text_ellipsis(struct ngui *ui, struct ngui_rect r, int x, int y,
 	if (n <= (unsigned int)max || max < 4) {
 		for (i = 0; i < n && (int)i < max; i++)
 			ngui_glyph(ui, x + (int)i * 8, y,
-				   (unsigned char)s[i], color);
+				   (unsigned char)s[i], color, 1, 0);
 		return;
 	}
 	for (i = 0; i < (unsigned int)(max - 3); i++)
-		ngui_glyph(ui, x + (int)i * 8, y, (unsigned char)s[i], color);
-	ngui_glyph(ui, x + (max - 3) * 8, y, '.', color);
-	ngui_glyph(ui, x + (max - 2) * 8, y, '.', color);
-	ngui_glyph(ui, x + (max - 1) * 8, y, '.', color);
+		ngui_glyph(ui, x + (int)i * 8, y, (unsigned char)s[i], color, 1, 0);
+	ngui_glyph(ui, x + (max - 3) * 8, y, '.', color, 1, 0);
+	ngui_glyph(ui, x + (max - 2) * 8, y, '.', color, 1, 0);
+	ngui_glyph(ui, x + (max - 1) * 8, y, '.', color, 1, 0);
 }
 
 void ngui_icon(struct ngui *ui, struct ngui_rect r, enum ngui_icon icon,

+ 5 - 0
ngui.h

@@ -151,9 +151,14 @@ void ngui_line(struct ngui *ui, int x0, int y0, int x1, int y1,
 	       unsigned short color);
 void ngui_text(struct ngui *ui, int x, int y, const char *s,
 	       unsigned short color);
+void ngui_text_n(struct ngui *ui, int x, int y, const char *s,
+		 unsigned int n, unsigned short color);
+void ngui_text_styled(struct ngui *ui, int x, int y, const char *s,
+		      unsigned int n, unsigned short color, int scale, int bold);
 void ngui_text_ellipsis(struct ngui *ui, struct ngui_rect r, int x, int y,
 			const char *s, unsigned short color);
 unsigned int ngui_text_width(const char *s);
+unsigned int ngui_text_width_n(const char *s, unsigned int n, int scale);
 void ngui_icon(struct ngui *ui, struct ngui_rect r, enum ngui_icon icon,
 	       unsigned short color);
 

+ 9 - 1
syscall.c

@@ -303,6 +303,7 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 		char path[VFS_PATH_MAX], arg[VFS_PATH_MAX], cwd[VFS_PATH_MAX];
 		const char *name;
 		int pid;
+		int lr;
 
 		if (!paging_user_range_ok(current_proc()->cr3,
 					  (unsigned int)a1, sizeof(in), 0))
@@ -321,7 +322,14 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 		    copy_user_string(arg, sizeof(arg), in.arg) != 0 ||
 		    copy_user_string(cwd, sizeof(cwd), in.cwd) != 0)
 			return -1;
-		if (vfs_load_file(path, &f, &m) != 0)
+
+		/* A FAT load reads the floppy through IRQ 6, so open the
+		 * syscall's interrupts-off section for the duration (the same
+		 * window SYS_READ_FILE uses). */
+		sys_fs_enter();
+		lr = vfs_load_file(path, &f, &m);
+		sys_fs_exit();
+		if (lr != 0)
 			return -1;
 		name = path;
 		{

+ 51 - 0
testdata/browser/demo.html

@@ -0,0 +1,51 @@
+<html>
+<head>
+<title>Nebs demo</title>
+<style>
+body { margin: 10px; color: #222222; }
+h1 { color: #cc3300; }
+h2 { color: #2255cc; }
+.note { background-color: #fff4cc; margin: 10px; padding: 8px; }
+pre { background-color: #eeeeee; padding: 6px; }
+a { color: #0044cc; }
+td { padding-right: 18px; }
+</style>
+</head>
+<body>
+<h1>Local browser demo</h1>
+<p>This page came from <b>/floppy1/DEMO.HTM</b> and was rendered by the
+Nebs browser: HTML, a little CSS and an inline image, with no JavaScript.</p>
+
+<div class="note">
+<b>Inline styles and classes:</b>
+<span style="color:#008000;">green span</span>,
+<span style="background-color:#ddddff;">light background</span>,
+<b>bold</b>, <u>underlined</u> and <a href="TEST.TXT">a relative link</a>.
+</div>
+
+<h2>Lists</h2>
+<ul>
+<li>one item</li>
+<li>another item with a <a href="/floppy1/HELLO.TXT">link to HELLO.TXT</a></li>
+</ul>
+<ol>
+<li>first</li>
+<li>second</li>
+</ol>
+
+<h2>Table and image</h2>
+<table>
+<tr><td><b>Format</b></td><td><b>Source</b></td></tr>
+<tr><td>BMP</td><td>PIC.BMP on this floppy</td></tr>
+<tr><td>PNG/JPEG/GIF</td><td>served over HTTP</td></tr>
+</table>
+<p><img src="PIC.BMP" width="240" alt="test bitmap"></p>
+
+<h2>Preformatted</h2>
+<pre>if (browser) {
+    render(html);
+}</pre>
+
+<p><a href="about:home">Back to the browser home page</a></p>
+</body>
+</html>

+ 53 - 0
ucmd_browser.c

@@ -0,0 +1,53 @@
+/* browser launcher: the real browser is a large disk app (BROWSER on a FAT
+ * mount) because it links ngui, the full image library, TLS and uhttp.  This
+ * tiny command keeps `browser` on PATH and in the WM's Web button. */
+
+#include "ucmd_lib.h"
+
+/* The sentinel is part of the array; do not size it to the number of
+ * candidate strings or the loop reads past the end (that was a user #PF at
+ * 0x40001000 in the first net-dev build). */
+static const char *const candidates[] = {
+	"/share/BROWSER",
+	"/share/BROWSER.ELF",
+	"/floppy1/BROWSER",
+	"/floppy1/BROWSER.ELF",
+	"/ide0p1/BROWSER",
+	"/sata0p1/BROWSER",
+	"/ide0/BROWSER",
+	"/sata0/BROWSER",
+	0
+};
+
+void _start(const char *arg)
+{
+	char cwd[64];
+	char argbuf[64];
+	unsigned int i, n = 0;
+
+	while (arg && arg[n] && n + 1 < sizeof(argbuf)) {
+		argbuf[n] = arg[n];
+		n++;
+	}
+	argbuf[n] = '\0';
+
+	if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0]) {
+		cwd[0] = '/';
+		cwd[1] = '\0';
+	}
+
+	for (i = 0; i < sizeof(candidates) / sizeof(candidates[0]) &&
+		     candidates[i]; i++) {
+		int pid = u_spawn(candidates[i], argbuf, 0, cwd);
+
+		if (pid > 0) {
+			u_puts("browser: started ");
+			u_puts(candidates[i]);
+			u_puts("\n");
+			u_exit(0);
+		}
+	}
+	u_puts("browser: BROWSER is not installed on a mounted disk\n");
+	u_puts("  put browser.elf on the root floppy or /share\n");
+	u_exit(1);
+}

+ 71 - 654
ucmd_curl.c

@@ -1,693 +1,110 @@
-/* curl: ring-3 command.  Fetch one http:// or https:// URL with a minimal
- * HTTP GET and dump the status line, the headers and the body to the terminal.
+/* curl: ring-3 command.  Fetch one http:// or https:// URL with the shared
+ * uhttp client and dump the status line, headers and body to the terminal.
  *
- * https uses the tls.c client (TLS 1.3, ChaCha20-Poly1305, X25519) WITHOUT
- * certificate verification (phase A): the handshake is encrypted, but a
- * man-in-the-middle is not detected; the leaf fingerprint is printed for a
- * manual check.  Redirects (3xx + Location) are followed up to
- * MAX_REDIRECTS hops: absolute URLs, absolute paths and relative paths
- * (resolved against the current path, "."/".." collapsed).  No gzip; a
- * chunked response is decoded.  The TCP client (tcp.c) and the DNS resolver
- * stay in the kernel; the nic is owned for the run (SYS_NET_ACQUIRE) and
- * TCP goes through the SYS_TCP_* calls. */
+ * The TLS and HTTP code lives in uhttp.c (shared with the browser); this file
+ * only keeps the CLI and the verbose output hooks. */
 
 #include "ucmd_lib.h"
-#include "tls.h"
+#include "uhttp.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 LOCATION_MAX 256
-#define MAX_REDIRECTS 5
+#define LINE_MAX_C 320
 
-#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;
-	int secure;
-};
-
-static struct url u;
-
-/* ---- transport: plain TCP or TLS ---- */
-
-static int xport_send(const void *buf, unsigned int len)
-{
-	if (u.secure)
-		return tls_send(buf, len);
-	return (int)u_syscall2(SYS_TCP_SEND, (int)buf, (int)len);
-}
-
-static int xport_recv(void *buf, unsigned int max, unsigned int timeout_ms)
-{
-	if (u.secure)
-		return tls_recv(buf, max, timeout_ms);
-	return (int)u_syscall3(SYS_TCP_RECV, (int)buf, (int)max,
-			       (int)timeout_ms);
-}
-
-static int starts_with(const char *s, const char *prefix)
+static void on_connected(void *ctx, int secure)
 {
-	unsigned int i = 0;
-
-	while (prefix[i]) {
-		if (s[i] != prefix[i])
-			return 0;
-		i++;
-	}
-	return 1;
-}
-
-/* ---- URL parsing ---- */
-
-/* Parse http:// or https:// host[:port][/path]; 0 on success, -1 error. */
-static int url_parse(const char *s, struct url *u)
-{
-	const char *p = s, *h;
-	unsigned int i;
-	int secure = 0;
-
-	if (starts_with(s, "https://")) {
-		secure = 1;
-		p += 8;
-	} else if (starts_with(s, "http://")) {
-		p += 7;
+	(void)ctx;
+	if (secure) {
+		u_puts("curl: connected, TLS handshake\n");
 	} 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;
-		}
+		u_puts("curl: connected, sending request\n");
 	}
-	u->secure = secure;
-
-	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 = secure ? 443 : 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;
 }
 
-/* ---- redirect target handling ---- */
-
-/* Normalize an absolute URL path in place: collapse "//", "." and ".." and
- * keep the leading '/' plus a trailing one.  0 ok, -1 too long. */
-static int path_normalize(char *path)
+static void on_status(void *ctx, int code, const char *line)
 {
-	char tmp[URL_PATH_MAX];
-	unsigned int i, o = 1, len = 0, start, seglen, j;
-	int trailing;
-
-	while (path[len])
-		len++;
-	if (len == 0 || path[0] != '/')
-		return 0;
-	trailing = (len > 1 && path[len - 1] == '/');
-	tmp[0] = '/';
-	i = 1;
-	while (path[i]) {
-		while (path[i] == '/')
-			i++;
-		start = i;
-		while (path[i] && path[i] != '/')
-			i++;
-		seglen = i - start;
-		if (seglen == 0)
-			break;
-		if (seglen == 1 && path[start] == '.')
-			continue;
-		if (seglen == 2 && path[start] == '.' &&
-		    path[start + 1] == '.') {
-			while (o > 1 && tmp[o - 1] != '/')
-				o--;
-			if (o > 1)
-				o--;
-			continue;
-		}
-		if (o + seglen + 2 > sizeof(tmp))
-			return -1;
-		if (o > 1)
-			tmp[o++] = '/';
-		for (j = 0; j < seglen; j++)
-			tmp[o++] = path[start + j];
-	}
-	if (trailing && o > 1 && tmp[o - 1] != '/') {
-		if (o + 2 > sizeof(tmp))
-			return -1;
-		tmp[o++] = '/';
-	}
-	tmp[o] = '\0';
-	for (i = 0; i <= o; i++)
-		path[i] = tmp[i];
-	return 0;
-}
-
-/* Apply a Location header to the current URL.  Supports absolute URLs,
- * absolute paths and relative paths (joined to the current path's
- * directory).  0 ok, -1 unparsable/too long. */
-static int url_apply_location(struct url *u, const char *loc)
-{
-	char joined[URL_PATH_MAX];
-	unsigned int i, dirlen = 1, n = 0;
-
-	if (starts_with(loc, "http://") || starts_with(loc, "https://"))
-		return url_parse(loc, u);
-
-	if (loc[0] == '/') {
-		if (loc[1] == '/')
-			return -1;              /* scheme-relative: unsupported */
-		for (i = 0; loc[i]; i++) {
-			if (i + 1 >= URL_PATH_MAX)
-				return -1;
-			u->path[i] = loc[i];
-		}
-		u->path[i] = '\0';
-		return path_normalize(u->path);
-	}
-
-	/* Relative: keep the directory part of the current path. */
-	for (i = 0; u->path[i]; i++) {
-		if (u->path[i] == '/')
-			dirlen = i + 1;
-	}
-	while (loc[n])
-		n++;
-	if (dirlen + n + 1 > URL_PATH_MAX)
-		return -1;
-	for (i = 0; i < dirlen; i++)
-		joined[i] = u->path[i];
-	for (i = 0; i < n; i++)
-		joined[dirlen + i] = loc[i];
-	joined[dirlen + n] = '\0';
-	for (i = 0; i <= dirlen + n; i++)
-		u->path[i] = joined[i];
-	return path_normalize(u->path);
+	(void)ctx;
+	(void)code;
+	u_puts("curl: ");
+	u_puts(line);
+	u_putc('\n');
 }
 
-/* ---- request building ---- */
-
-static unsigned int req_app(char *buf, unsigned int pos, const char *s)
+static void on_header(void *ctx, const char *line)
 {
-	while (*s && pos < REQ_MAX - 1)
-		buf[pos++] = *s++;
-	return pos;
+	(void)ctx;
+	u_puts(line);
+	u_putc('\n');
 }
 
-static unsigned int req_app_dec(char *buf, unsigned int pos, unsigned int v)
+static void on_redirect(void *ctx, const char *location)
 {
-	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;
+	(void)ctx;
+	u_puts("curl: redirect -> ");
+	u_puts(location);
+	u_putc('\n');
 }
 
-/* ---- HTTP response reader (a refillable line/byte stream) ---- */
-
-struct reader {
-	unsigned char buf[READER_MAX];
-	unsigned int len, pos;
-	unsigned int total_deadline;
-	int eof;
-	int error;              /* 0, -1 timeout, -2 reset */
+static const struct uhttp_hooks hooks = {
+	.connected = on_connected,
+	.status = on_status,
+	.header = on_header,
+	.redirect = on_redirect,
 };
 
-/* Returns 1 when new data (or EOF) is available, 0 on timeout/reset. */
-static int reader_fill(struct reader *r)
-{
-	unsigned int now, idle, deadline, rel;
-	int n;
-
-	if (r->eof)
-		return 0;
-
-	now = u_ticks_ms();
-	idle = now + IDLE_TIMEOUT_MS;
-	deadline = idle < r->total_deadline ? idle : r->total_deadline;
-	rel = (int)(deadline - now) > 0 ? deadline - now : 1;
-
-	n = xport_recv(r->buf, sizeof(r->buf), rel);
-	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;
-		u_putc((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) {
-			u_puts("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;
-			u_putc((char)c);
-			total++;
-		}
-		reader_readline(r, line, sizeof(line));   /* the CRLF */
-	}
-}
-
 void _start(const char *arg)
 {
-	static char req[REQ_MAX];
-	static struct reader r;
-	struct sys_netinfo ni;
-	char line[LINE_MAX_C];
-	char location[LOCATION_MAX];
-	unsigned int status = 0, body = 0, content_len = 0;
-	unsigned int hops = 0;
-	int have_loc, have_len, chunked, rv, connected = 0, follow = 1;
+	static struct uhttp h;
+	unsigned char buf[512];
+	unsigned int total = 0;
+	int rv;
 
 	if (!arg || !arg[0]) {
 		u_puts("curl: usage curl <http|https://host[:port]/[path]>\n");
 		u_exit(1);
 	}
 
-	rv = url_parse(arg, &u);
+	uhttp_init(&h);
+	h.user_agent = "nebos-curl/0.1";
+
+	u_puts("curl: GET ");
+	u_puts(arg);
+	u_putc('\n');
+
+	rv = uhttp_open(&h, arg, 0, &hooks);
 	if (rv != 0) {
-		u_puts("curl: bad URL\n");
-		u_exit(1);
-	}
-	if (u_syscall1(SYS_NET_INFO, (int)&ni) != 1) {
-		u_puts("curl: no NIC found\n");
-		u_exit(1);
-	}
-	if (u_syscall0(SYS_NET_CONFIGURED) != 1) {
-		u_puts("curl: no IP address (run dhcp or netip)\n");
-		u_exit(1);
-	}
-	if (u_syscall0(SYS_NET_ACQUIRE) != 0) {
-		u_puts("curl: NIC busy\n");
+		u_puts("curl: ");
+		u_puts(uhttp_error_string(rv));
+		u_putc('\n');
+		uhttp_close(&h);
 		u_exit(1);
 	}
+	if (h.url.secure)
+		u_puts("curl: WARNING: certificate NOT verified "
+		       "(trust-all mode)\n");
 
+	u_putc('\n');
 	for (;;) {
-		unsigned char ip[4], hop[4], mac[6];
-		unsigned int n;
-
-		have_loc = have_len = chunked = 0;
-		content_len = 0;
-
-		u_puts(u.secure ? "curl: GET https://" : "curl: GET http://");
-		u_puts(u.host);
-		if (u.port != (u.secure ? 443u : 80u)) {
-			u_puts(":");
-			u_putdec(u.port);
-		}
-		u_puts(u.path);
-		u_putc('\n');
+		rv = uhttp_read(&h, buf, sizeof(buf), UHTTP_IDLE_TIMEOUT_MS);
+		if (rv > 0) {
+			int i;
 
-		if (u_parse_ip(u.host, ip) != 0) {
-			if (u_syscall2(SYS_DNS_RESOLVE, (int)u.host, (int)ip) != 0)
-				goto out;
-		}
-
-		u_syscall2(SYS_NET_NEXT_HOP, (int)ip, (int)hop);
-		rv = u_syscall2(SYS_NET_ARP, (int)hop, (int)mac);
-		if (rv != 0) {
-			u_puts("curl: no ARP reply from ");
-			u_put_ip(hop);
-			u_putc('\n');
-			goto out;
-		}
-
-		rv = u_syscall3(SYS_TCP_CONNECT, (int)mac, (int)ip, (int)u.port);
-		if (rv == -1) {
-			u_puts("curl: connect timeout\n");
-			goto out;
-		}
-		if (rv == -2) {
-			u_puts("curl: connection refused\n");
-			goto out;
-		}
-		if (rv != 0) {
-			u_puts("curl: connect failed\n");
-			goto out;
-		}
-		connected = 1;
-
-		if (u.secure) {
-			u_puts("curl: connected, TLS handshake\n");
-			if (tls_connect(u.host) != 0)
-				goto out;
-			u_puts("curl: WARNING: certificate NOT verified "
-			       "(trust-all mode)\n");
-		} else {
-			u_puts("curl: connected, sending request\n");
-		}
-
-		n = req_app(req, 0, "GET ");
-		n = req_app(req, n, u.path);
-		n = req_app(req, n, u.secure ? " HTTP/1.1\r\nHost: "
-					     : " HTTP/1.0\r\nHost: ");
-		n = req_app(req, n, u.host);
-		if (u.port != (u.secure ? 443u : 80u)) {
-			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 ((int)n > u_syscall0(SYS_TCP_PEER_MSS)) {
-			u_puts("curl: request too long\n");
-			goto out;
-		}
-		rv = xport_send(req, n);
-		if (rv != 0) {
-			u_puts("curl: request send failed\n");
-			goto out;
+			for (i = 0; i < rv; i++)
+				u_putc((char)buf[i]);
+			total += (unsigned int)rv;
+			continue;
 		}
-
-		r.len = 0;
-		r.pos = 0;
-		r.eof = 0;
-		r.error = 0;
-		r.total_deadline = u_ticks_ms() + TOTAL_TIMEOUT_MS;
-
-		rv = reader_readline(&r, line, sizeof(line));
 		if (rv < 0) {
-			u_puts("curl: no response (");
-			u_puts(r.error == -2 ? "reset" : "timeout");
-			u_puts(")\n");
-			goto out;
-		}
-		status = parse_status(line);
-		u_puts("curl: ");
-		u_puts(line);
-		u_putc('\n');
-
-		for (;;) {
-			rv = reader_readline(&r, line, sizeof(line));
-			if (rv < 0) {
-				u_puts("curl: connection lost in headers\n");
-				goto out;
-			}
-			if (rv == 0)
-				break;              /* end of headers */
-			u_puts(line);
-			u_putc('\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)
-			break;                  /* final response: dump the body */
-
-		if (hops >= MAX_REDIRECTS) {
-			u_puts("curl: too many redirects\n");
-			follow = 0;
-			break;
-		}
-		u_puts("curl: redirect -> ");
-		u_puts(location);
-		u_putc('\n');
-		tls_close();
-		u_syscall0(SYS_TCP_CLOSE);
-		connected = 0;
-		if (url_apply_location(&u, location) != 0) {
-			u_puts("curl: bad redirect target\n");
-			follow = 0;
-			break;
-		}
-		hops++;
-	}
-
-	if (follow && connected) {
-		u_putc('\n');
-		if (chunked)
-			body = dump_chunked(&r);
-		else
-			body = dump_body(&r, have_len, content_len);
-		u_putc('\n');
-
-		if (r.error == -2)
-			u_puts("curl: connection reset\n");
-		else if (r.error == -1)
-			u_puts("curl: timeout while reading body\n");
-
-		u_puts("curl: ");
-		u_putdec(body);
-		u_puts(" bytes received, status ");
-		u_putdec(status);
-		u_putc('\n');
-	}
-
-out:
-	if (connected) {
-		tls_close();
-		u_syscall0(SYS_TCP_CLOSE);
-	}
-	u_syscall0(SYS_NET_RELEASE);
+			u_puts("\ncurl: ");
+			u_puts(uhttp_error_string(rv));
+			u_puts(" while reading body\n");
+		}
+		break;
+	}
+	u_putc('\n');
+	u_puts("curl: ");
+	u_putdec(total);
+	u_puts(" bytes received, status ");
+	u_putdec((unsigned int)h.resp.status);
+	u_putc('\n');
+	uhttp_close(&h);
 	u_exit(0);
 }

+ 15 - 0
ucmd_files.c

@@ -182,6 +182,12 @@ static int is_image_name(const char *name)
 	       ext_is(name, ".cur") || ext_is(name, ".pam");
 }
 
+static int is_html_name(const char *name)
+{
+	return ext_is(name, ".htm") || ext_is(name, ".html") ||
+	       ext_is(name, ".xhtml");
+}
+
 static void path_join(const char *dir, const char *name, char *out,
 		      unsigned int cap)
 {
@@ -504,6 +510,15 @@ static void open_selected(void)
 		load_path(path);
 		return;
 	}
+	if (is_html_name(e->name)) {
+		path_join(cwd, e->name, path, sizeof(path));
+		pid = u_spawn("/ramfs/bin/browser", path, 0, cwd);
+		if (pid <= 0)
+			set_status("Cannot launch the browser", 1);
+		else
+			set_status("Opened in the browser", 0);
+		return;
+	}
 	if (is_image_name(e->name)) {
 		if (e->size > IMG_FILE_MAX) {
 			set_status("Image is larger than 4 MB", 1);

+ 7 - 1
ucmd_wm.c

@@ -135,9 +135,11 @@ static void draw_bar(void)
 		   WM_BTN_FILES_H, "Files");
 	bar_button(WM_BTN_MINES_X, WM_BTN_MINES_Y, WM_BTN_MINES_W,
 		   WM_BTN_MINES_H, "Mines");
+	bar_button(WM_BTN_WEB_X, WM_BTN_WEB_Y, WM_BTN_WEB_W,
+		   WM_BTN_WEB_H, "Web");
 	if (bar_msg_until &&
 	    (int)(u_ticks_ms() - bar_msg_until) < 0)
-		usurf_text(&screen, (int)(WM_BTN_MINES_X + WM_BTN_MINES_W + 8),
+		usurf_text(&screen, (int)(WM_BTN_WEB_X + WM_BTN_WEB_W + 8),
 			   5, bar_msg, 0xFFD250u, 0, 0, fbw, WM_BAR_H);
 
 	/* Rainbow separator (same y as the kernel's old bar). */
@@ -590,6 +592,10 @@ static void handle_mouse(struct wm_status *st)
 			   mx < WM_BTN_MINES_X + WM_BTN_MINES_W &&
 			   my < WM_BTN_MINES_Y + WM_BTN_MINES_H) {
 			spawn_app_checked("/ramfs/bin/mines");
+		} else if (mx >= WM_BTN_WEB_X && my >= WM_BTN_WEB_Y &&
+			   mx < WM_BTN_WEB_X + WM_BTN_WEB_W &&
+			   my < WM_BTN_WEB_Y + WM_BTN_WEB_H) {
+			spawn_app_checked("/ramfs/bin/browser");
 		} else {
 			int idx = window_at(mx, my);
 

+ 831 - 0
uhttp.c

@@ -0,0 +1,831 @@
+/* uhttp: see uhttp.h.  Extracted from the original ucmd_curl.c so curl and
+ * the browser share one HTTP/TLS path. */
+
+#include "uhttp.h"
+#include "tls.h"
+
+/* ---- tiny string helpers ---- */
+
+static unsigned int s_len(const char *s)
+{
+	unsigned int n = 0;
+
+	while (s && s[n])
+		n++;
+	return n;
+}
+
+static void s_copy(char *d, const char *s, unsigned int cap)
+{
+	unsigned int i = 0;
+
+	if (!cap)
+		return;
+	while (s && s[i] && i + 1 < cap) {
+		d[i] = s[i];
+		i++;
+	}
+	d[i] = '\0';
+}
+
+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;
+}
+
+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;
+}
+
+/* ---- URL parsing / resolution ---- */
+
+int uhttp_parse_url(const char *s, struct uhttp_url *u)
+{
+	const char *p = s, *h;
+	unsigned int i;
+	int secure = 0;
+
+	if (!s || !u)
+		return UHTTP_ERR_URL;
+	if (starts_with(s, "https://")) {
+		secure = 1;
+		p += 8;
+	} else if (starts_with(s, "http://")) {
+		p += 7;
+	} else {
+		for (i = 0; s[i] && i < 8; i++) {
+			if (s[i] == ':' && s[i + 1] == '/' && s[i + 2] == '/')
+				return UHTTP_ERR_URL;
+			if (s[i] == '/')
+				break;
+		}
+	}
+	u->secure = secure;
+
+	h = p;
+	while (*p && *p != '/' && *p != ':')
+		p++;
+	if (p == h || (unsigned int)(p - h) >= UHTTP_HOST_MAX)
+		return UHTTP_ERR_URL;
+	for (i = 0; i < (unsigned int)(p - h); i++)
+		u->host[i] = h[i];
+	u->host[i] = '\0';
+
+	u->port = secure ? 443 : 80;
+	if (*p == ':') {
+		unsigned int port = 0;
+
+		p++;
+		if (*p < '0' || *p > '9')
+			return UHTTP_ERR_URL;
+		while (*p >= '0' && *p <= '9') {
+			port = port * 10 + (unsigned int)(*p - '0');
+			if (port > 65535)
+				return UHTTP_ERR_URL;
+			p++;
+		}
+		if (port == 0 || (*p != '/' && *p != '\0'))
+			return UHTTP_ERR_URL;
+		u->port = port;
+	}
+
+	i = 0;
+	if (*p == '/') {
+		while (p[i]) {
+			if (p[i] == '#')
+				break;
+			if (i + 1 >= UHTTP_PATH_MAX)
+				return UHTTP_ERR_URL;
+			u->path[i] = p[i];
+			i++;
+		}
+	}
+	u->path[i] = '\0';
+	if (i == 0) {
+		u->path[0] = '/';
+		u->path[1] = '\0';
+	}
+	return 0;
+}
+
+static void url_build(const struct uhttp_url *u, char *out, unsigned int cap)
+{
+	unsigned int n = 0;
+
+#define APP(s) do { const char *ap = (s); \
+	while (*ap && n + 1 < cap) out[n++] = *ap++; } while (0)
+	APP(u->secure ? "https://" : "http://");
+	APP(u->host);
+	if (u->port != (u->secure ? 443u : 80u)) {
+		char tmp[8];
+		unsigned int v = u->port, k = 0, j;
+
+		if (v == 0) {
+			tmp[k++] = '0';
+		} else {
+			while (v && k < sizeof(tmp)) {
+				tmp[k++] = (char)('0' + v % 10);
+				v /= 10;
+			}
+		}
+		if (n + 1 < cap)
+			out[n++] = ':';
+		for (j = 0; j < k && n + 1 < cap; j++)
+			out[n++] = tmp[k - 1 - j];
+	}
+	APP(u->path);
+#undef APP
+	out[n] = '\0';
+}
+
+/* Normalize an absolute URL path in place: collapse "//", "." and "..".
+ * 0 ok, -1 too long. */
+static int path_normalize(char *path)
+{
+	char tmp[UHTTP_PATH_MAX];
+	unsigned int i, o = 1, len = 0, start, seglen, j;
+	int trailing;
+
+	while (path[len])
+		len++;
+	if (len == 0 || path[0] != '/')
+		return 0;
+	trailing = (len > 1 && path[len - 1] == '/');
+	tmp[0] = '/';
+	i = 1;
+	while (path[i]) {
+		while (path[i] == '/')
+			i++;
+		start = i;
+		while (path[i] && path[i] != '/')
+			i++;
+		seglen = i - start;
+		if (seglen == 0)
+			break;
+		if (seglen == 1 && path[start] == '.')
+			continue;
+		if (seglen == 2 && path[start] == '.' && path[start + 1] == '.') {
+			while (o > 1 && tmp[o - 1] != '/')
+				o--;
+			if (o > 1)
+				o--;
+			continue;
+		}
+		if (o + seglen + 2 > sizeof(tmp))
+			return -1;
+		if (o > 1)
+			tmp[o++] = '/';
+		for (j = 0; j < seglen; j++)
+			tmp[o++] = path[start + j];
+	}
+	if (trailing && o > 1 && tmp[o - 1] != '/') {
+		if (o + 2 > sizeof(tmp))
+			return -1;
+		tmp[o++] = '/';
+	}
+	tmp[o] = '\0';
+	for (i = 0; i <= o; i++)
+		path[i] = tmp[i];
+	return 0;
+}
+
+/* Apply a Location header to the current URL. */
+static int url_apply_location(struct uhttp_url *u, const char *loc)
+{
+	char joined[UHTTP_PATH_MAX];
+	char scheme[8];
+	unsigned int i, dirlen = 1, n = 0;
+
+	if (starts_with(loc, "http://") || starts_with(loc, "https://"))
+		return uhttp_parse_url(loc, u);
+
+	if (loc[0] == '/' && loc[1] == '/') {
+		/* scheme-relative */
+		s_copy(scheme, u->secure ? "https:" : "http:", sizeof(scheme));
+		if (s_len(scheme) + s_len(loc) + 1 > UHTTP_LOC_MAX)
+			return -1;
+		{
+			char full[UHTTP_LOC_MAX];
+			unsigned int k = 0;
+			while (scheme[k]) {
+				full[k] = scheme[k];
+				k++;
+			}
+			for (i = 0; loc[i] && k + 1 < sizeof(full); i++)
+				full[k++] = loc[i];
+			full[k] = '\0';
+			return uhttp_parse_url(full, u);
+		}
+	}
+
+	if (loc[0] == '/') {
+		for (i = 0; loc[i]; i++) {
+			if (i + 1 >= UHTTP_PATH_MAX)
+				return -1;
+			u->path[i] = loc[i];
+		}
+		u->path[i] = '\0';
+		return path_normalize(u->path);
+	}
+
+	for (i = 0; u->path[i]; i++)
+		if (u->path[i] == '/')
+			dirlen = i + 1;
+	while (loc[n])
+		n++;
+	if (dirlen + n + 1 > UHTTP_PATH_MAX)
+		return -1;
+	for (i = 0; i < dirlen; i++)
+		joined[i] = u->path[i];
+	for (i = 0; i < n; i++)
+		joined[dirlen + i] = loc[i];
+	joined[dirlen + n] = '\0';
+	for (i = 0; i <= dirlen + n; i++)
+		u->path[i] = joined[i];
+	return path_normalize(u->path);
+}
+
+int uhttp_resolve(const char *base, const char *href, char *out,
+		  unsigned int cap)
+{
+	struct uhttp_url u;
+
+	if (!base || !href || !out || cap == 0)
+		return UHTTP_ERR_URL;
+	if (uhttp_parse_url(base, &u) != 0)
+		return UHTTP_ERR_URL;
+	if (href[0] == '#') {
+		s_copy(out, base, cap);
+		return 0;
+	}
+	if (url_apply_location(&u, href) != 0)
+		return UHTTP_ERR_URL;
+	url_build(&u, out, cap);
+	return 0;
+}
+
+/* ---- HTTP header helpers ---- */
+
+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 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;
+}
+
+/* ---- transport ---- */
+
+static int xport_send(struct uhttp *h, const void *buf, unsigned int len)
+{
+	if (h->url.secure)
+		return tls_send(buf, len);
+	return (int)u_syscall2(SYS_TCP_SEND, (int)buf, (int)len);
+}
+
+static int xport_recv(struct uhttp *h, void *buf, unsigned int max,
+		      unsigned int timeout_ms)
+{
+	if (h->url.secure)
+		return tls_recv(buf, max, timeout_ms);
+	return (int)u_syscall3(SYS_TCP_RECV, (int)buf, (int)max,
+			       (int)timeout_ms);
+}
+
+static void transport_close(struct uhttp *h)
+{
+	if (!h->connected)
+		return;
+	if (h->url.secure)
+		tls_close();
+	u_syscall0(SYS_TCP_CLOSE);
+	h->connected = 0;
+}
+
+/* Connect to h->url (TCP + TLS).  Keeps the NIC acquired. */
+static int http_connect(struct uhttp *h)
+{
+	unsigned char ip[4], hop[4], mac[6];
+	int rv;
+
+	if (u_parse_ip(h->url.host, ip) != 0) {
+		if (u_syscall2(SYS_DNS_RESOLVE, (int)h->url.host, (int)ip) != 0)
+			return UHTTP_ERR_DNS;
+	}
+	u_syscall2(SYS_NET_NEXT_HOP, (int)ip, (int)hop);
+	rv = u_syscall2(SYS_NET_ARP, (int)hop, (int)mac);
+	if (rv != 0)
+		return UHTTP_ERR_ARP;
+
+	rv = u_syscall3(SYS_TCP_CONNECT, (int)mac, (int)ip, (int)h->url.port);
+	if (rv == -1)
+		return UHTTP_ERR_TIMEOUT;
+	if (rv == -2)
+		return UHTTP_ERR_REFUSED;
+	if (rv != 0)
+		return UHTTP_ERR_CONNECT;
+	h->connected = 1;
+	if (h->url.secure) {
+		if (tls_connect(h->url.host) != 0) {
+			transport_close(h);
+			return UHTTP_ERR_TLS;
+		}
+	}
+	return 0;
+}
+
+/* ---- response reader ---- */
+
+static int reader_fill(struct uhttp *h, unsigned int timeout_ms)
+{
+	unsigned int now, deadline, rel;
+	int n;
+
+	if (h->eof)
+		return 0;
+	now = u_ticks_ms();
+	deadline = now + timeout_ms;
+	if ((int)(h->total_deadline - deadline) < 0)
+		deadline = h->total_deadline;
+	rel = (int)(deadline - now) > 0 ? deadline - now : 1;
+
+	n = xport_recv(h, h->buf, sizeof(h->buf), rel);
+	if (n > 0) {
+		h->len = (unsigned int)n;
+		h->pos = 0;
+		return 1;
+	}
+	if (n == 0) {
+		h->eof = 1;
+		return 0;
+	}
+	h->error = (n == -1) ? UHTTP_ERR_TIMEOUT : UHTTP_ERR_RESET;
+	return 0;
+}
+
+static int reader_getc(struct uhttp *h, unsigned int timeout_ms)
+{
+	if (h->pos >= h->len) {
+		if (!reader_fill(h, timeout_ms))
+			return -1;
+	}
+	return h->buf[h->pos++];
+}
+
+static int reader_readline(struct uhttp *h, char *out, unsigned int max,
+			   unsigned int timeout_ms)
+{
+	unsigned int n = 0;
+	int c;
+
+	for (;;) {
+		c = reader_getc(h, timeout_ms);
+		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;
+	}
+}
+
+/* ---- request / response ---- */
+
+static unsigned int req_app(char *buf, unsigned int pos, unsigned int cap,
+			    const char *s)
+{
+	while (*s && pos + 1 < cap)
+		buf[pos++] = *s++;
+	buf[pos] = '\0';
+	return pos;
+}
+
+static unsigned int req_app_dec(char *buf, unsigned int pos, unsigned int cap,
+				unsigned int v)
+{
+	char b[12];
+	int i = 0;
+
+	if (v == 0) {
+		if (pos + 1 < cap)
+			buf[pos++] = '0';
+		buf[pos] = '\0';
+		return pos;
+	}
+	while (v) {
+		b[i++] = (char)('0' + (v % 10));
+		v /= 10;
+	}
+	while (i) {
+		i--;
+		if (pos + 1 < cap)
+			buf[pos++] = b[i];
+	}
+	buf[pos] = '\0';
+	return pos;
+}
+
+/* Read the status line and headers of the current response.  Returns 0 and
+ * sets redirect/location when the response is a redirect with a target. */
+static int read_response_head(struct uhttp *h, char *location, int *have_loc)
+{
+	char line[UHTTP_LINE_MAX];
+	unsigned int status = 0;
+	int rv;
+
+	h->resp.status = 0;
+	h->resp.chunked = 0;
+	h->resp.have_length = 0;
+	h->resp.content_length = 0;
+	h->resp.gzip = 0;
+	h->resp.content_type[0] = '\0';
+	h->resp.content_encoding[0] = '\0';
+	h->chunk_state = 0;
+	h->chunk_left = 0;
+	h->body_read = 0;
+	h->len = h->pos = 0;
+	h->eof = 0;
+	h->error = 0;
+	*have_loc = 0;
+	location[0] = '\0';
+
+	rv = reader_readline(h, line, sizeof(line), UHTTP_IDLE_TIMEOUT_MS);
+	if (rv < 0)
+		return (h->error == UHTTP_ERR_RESET) ? UHTTP_ERR_RESET :
+						       UHTTP_ERR_TIMEOUT;
+	status = parse_status(line);
+	h->resp.status = (int)status;
+	if (h->hooks && h->hooks->status)
+		h->hooks->status(h->hooks->ctx, (int)status, line);
+
+	for (;;) {
+		rv = reader_readline(h, line, sizeof(line), UHTTP_IDLE_TIMEOUT_MS);
+		if (rv < 0)
+			return (h->error == UHTTP_ERR_RESET) ? UHTTP_ERR_RESET :
+							       UHTTP_ERR_TIMEOUT;
+		if (rv == 0)
+			break;
+		if (h->hooks && h->hooks->header)
+			h->hooks->header(h->hooks->ctx, line);
+		if (hdr_match(line, "content-length"))
+			h->resp.have_length =
+				parse_dec_after_colon(line, &h->resp.content_length);
+		else if (hdr_match(line, "transfer-encoding") &&
+			 contains_ci(line, "chunked"))
+			h->resp.chunked = 1;
+		else if (hdr_match(line, "content-encoding")) {
+			copy_after_colon(line, h->resp.content_encoding,
+					 sizeof(h->resp.content_encoding));
+			if (contains_ci(h->resp.content_encoding, "gzip"))
+				h->resp.gzip = 1;
+		}
+		else if (hdr_match(line, "content-type")) {
+			copy_after_colon(line, h->resp.content_type,
+					 sizeof(h->resp.content_type));
+		} else if (hdr_match(line, "location")) {
+			copy_after_colon(line, location, UHTTP_LOC_MAX);
+			*have_loc = location[0] != '\0';
+		}
+	}
+	return 0;
+}
+
+static int send_request(struct uhttp *h, unsigned int flags)
+{
+	char req[640];
+	unsigned int n = 0;
+	int rv;
+
+	n = req_app(req, 0, sizeof(req), "GET ");
+	n = req_app(req, n, sizeof(req), h->url.path);
+	n = req_app(req, n, sizeof(req), " HTTP/1.1\r\nHost: ");
+	n = req_app(req, n, sizeof(req), h->url.host);
+	if (h->url.port != (h->url.secure ? 443u : 80u)) {
+		n = req_app(req, n, sizeof(req), ":");
+		n = req_app_dec(req, n, sizeof(req), h->url.port);
+	}
+	n = req_app(req, n, sizeof(req), "\r\nUser-Agent: ");
+	n = req_app(req, n, sizeof(req), h->user_agent);
+	n = req_app(req, n, sizeof(req), "\r\nAccept: */*\r\n");
+	if (flags & UHTTP_GZIP)
+		n = req_app(req, n, sizeof(req), "Accept-Encoding: gzip\r\n");
+	n = req_app(req, n, sizeof(req), "Connection: close\r\n\r\n");
+
+	if ((int)n > u_syscall0(SYS_TCP_PEER_MSS))
+		return UHTTP_ERR_TOOLONG;
+	rv = xport_send(h, req, n);
+	if (rv != 0)
+		return UHTTP_ERR_SEND;
+	return 0;
+}
+
+void uhttp_init(struct uhttp *h)
+{
+	unsigned int i;
+
+	for (i = 0; i < sizeof(*h); i++)
+		((unsigned char *)h)[i] = 0;
+	h->user_agent = "nebos-uhttp/0.1";
+}
+
+int uhttp_open(struct uhttp *h, const char *url, unsigned int flags,
+	       const struct uhttp_hooks *hooks)
+{
+	char location[UHTTP_LOC_MAX];
+	unsigned int hops = 0;
+	int rv;
+
+	h->hooks = hooks;
+	if (!h->user_agent)
+		h->user_agent = "nebos-uhttp/0.1";
+	h->len = h->pos = 0;
+	h->eof = 0;
+	h->error = 0;
+	h->connected = 0;
+	h->owns_nic = 0;
+
+	if (uhttp_parse_url(url, &h->url) != 0)
+		return UHTTP_ERR_URL;
+	url_build(&h->url, h->resp.final_url, sizeof(h->resp.final_url));
+
+	{
+		struct sys_netinfo ni;
+
+		if (u_syscall1(SYS_NET_INFO, (int)&ni) != 1)
+			return UHTTP_ERR_NIC;
+		if (u_syscall0(SYS_NET_CONFIGURED) != 1)
+			return UHTTP_ERR_IP;
+		if (u_syscall0(SYS_NET_ACQUIRE) != 0)
+			return UHTTP_ERR_BUSY;
+		h->owns_nic = 1;
+	}
+
+	h->total_deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS;
+
+	for (;;) {
+		int have_loc;
+
+		rv = http_connect(h);
+		if (rv != 0)
+			goto fail;
+		if (h->hooks && h->hooks->connected)
+			h->hooks->connected(h->hooks->ctx, h->url.secure);
+
+		rv = send_request(h, flags);
+		if (rv != 0)
+			goto fail;
+
+		rv = read_response_head(h, location, &have_loc);
+		if (rv != 0)
+			goto fail;
+
+		if (h->resp.status >= 300 && h->resp.status < 400 && have_loc) {
+			if (h->hooks && h->hooks->redirect)
+				h->hooks->redirect(h->hooks->ctx, location);
+			if (hops >= UHTTP_MAX_REDIRECTS) {
+				rv = UHTTP_ERR_TOOMANY;
+				goto fail;
+			}
+			transport_close(h);
+			if (url_apply_location(&h->url, location) != 0) {
+				rv = UHTTP_ERR_REDIRECT;
+				goto fail;
+			}
+			url_build(&h->url, h->resp.final_url,
+				  sizeof(h->resp.final_url));
+			hops++;
+			continue;
+		}
+		break;
+	}
+	return 0;
+
+fail:
+	uhttp_close(h);
+	return rv;
+}
+
+/* Copy up to max decoded body bytes; >0 data, 0 EOF, <0 error. */
+int uhttp_read(struct uhttp *h, void *vbuf, unsigned int max,
+	       unsigned int timeout_ms)
+{
+	unsigned char *out = (unsigned char *)vbuf;
+	unsigned int n = 0;
+	int c;
+
+	if (h->error)
+		return h->error;
+	if (h->eof && h->chunk_state != 1 &&
+	    !(h->resp.have_length && h->body_read < h->resp.content_length))
+		return 0;
+	if (max == 0)
+		return 0;
+
+	if (!h->resp.chunked && h->resp.have_length &&
+	    h->body_read >= h->resp.content_length) {
+		h->eof = 1;
+		return 0;
+	}
+
+	while (n < max) {
+		if (h->resp.chunked) {
+			if (h->chunk_state == 0) {
+				char line[64];
+				unsigned int sz = 0, k = 0;
+				int hl = reader_readline(h, line, sizeof(line),
+							 timeout_ms);
+
+				if (hl < 0) {
+					if (n)
+						break;
+					return h->error ? h->error : 0;
+				}
+				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) {
+					h->error = UHTTP_ERR_RESET;
+					return n ? (int)n : h->error;
+				}
+				if (sz == 0) {
+					h->chunk_state = 3;
+				} else {
+					h->chunk_left = sz;
+					h->chunk_state = 1;
+				}
+			} else if (h->chunk_state == 1) {
+				c = reader_getc(h, timeout_ms);
+				if (c < 0) {
+					if (n)
+						break;
+					return h->error ? h->error : 0;
+				}
+				out[n++] = (unsigned char)c;
+				h->body_read++;
+				if (--h->chunk_left == 0)
+					h->chunk_state = 2;
+			} else if (h->chunk_state == 2) {
+				(void)reader_getc(h, timeout_ms); /* CR */
+				(void)reader_getc(h, timeout_ms); /* LF */
+				h->chunk_state = 0;
+			} else {
+				char line[64];
+				int hl = reader_readline(h, line, sizeof(line),
+							 timeout_ms);
+
+				if (hl <= 0) {
+					h->eof = 1;
+					break;
+				}
+			}
+		} else {
+			if (h->resp.have_length &&
+			    h->body_read >= h->resp.content_length) {
+				h->eof = 1;
+				break;
+			}
+			c = reader_getc(h, timeout_ms);
+			if (c < 0) {
+				if (n)
+					break;
+				return h->error ? h->error : 0;
+			}
+			out[n++] = (unsigned char)c;
+			h->body_read++;
+		}
+	}
+	return (int)n;
+}
+
+void uhttp_close(struct uhttp *h)
+{
+	transport_close(h);
+	if (h->owns_nic) {
+		u_syscall0(SYS_NET_RELEASE);
+		h->owns_nic = 0;
+	}
+}
+
+const char *uhttp_error_string(int err)
+{
+	switch (err) {
+	case 0:                  return "ok";
+	case UHTTP_ERR_URL:      return "bad URL";
+	case UHTTP_ERR_NIC:      return "no NIC found";
+	case UHTTP_ERR_IP:       return "no IP address (run dhcp or netip)";
+	case UHTTP_ERR_BUSY:     return "network busy";
+	case UHTTP_ERR_DNS:      return "DNS lookup failed";
+	case UHTTP_ERR_ARP:      return "no ARP reply";
+	case UHTTP_ERR_CONNECT:  return "connection failed";
+	case UHTTP_ERR_REFUSED:  return "connection refused";
+	case UHTTP_ERR_TLS:      return "TLS handshake failed";
+	case UHTTP_ERR_SEND:     return "request send failed";
+	case UHTTP_ERR_TIMEOUT:  return "timeout";
+	case UHTTP_ERR_RESET:    return "connection reset";
+	case UHTTP_ERR_REDIRECT: return "bad redirect target";
+	case UHTTP_ERR_TOOMANY:  return "too many redirects";
+	case UHTTP_ERR_TOOLONG:  return "request too long";
+	default:                 return "network error";
+	}
+}

+ 107 - 0
uhttp.h

@@ -0,0 +1,107 @@
+/* uhttp: small ring-3 HTTP/1.1 GET client shared by curl and the browser.
+ *
+ * The kernel owns the NIC and the TCP stack; this module drives them through
+ * the SYS_NET_* / SYS_TCP_* calls, optionally wraps the connection in TLS
+ * (tls.c), follows redirects and de-chunks the response.  The caller supplies
+ * the connection object, so there is no allocation.
+ *
+ * https uses the phase-A tls.c client: encrypted but WITHOUT certificate
+ * verification.  The caller can show a warning (curl does).
+ */
+#ifndef UHTTP_H
+#define UHTTP_H
+
+#include "ucmd_lib.h"
+
+#define UHTTP_HOST_MAX       128
+#define UHTTP_PATH_MAX       192
+#define UHTTP_LOC_MAX        256
+#define UHTTP_LINE_MAX       320
+#define UHTTP_READER_MAX     2048
+#define UHTTP_MAX_REDIRECTS  5
+#define UHTTP_IDLE_TIMEOUT_MS  10000
+#define UHTTP_TOTAL_TIMEOUT_MS 60000
+
+/* uhttp_open flags. */
+#define UHTTP_GZIP  1   /* send Accept-Encoding: gzip (caller decodes) */
+
+/* Error codes (uhttp_open/uhttp_read return 0 on success). */
+#define UHTTP_ERR_URL        (-1)
+#define UHTTP_ERR_NIC        (-2)
+#define UHTTP_ERR_IP         (-3)
+#define UHTTP_ERR_BUSY       (-4)
+#define UHTTP_ERR_DNS        (-5)
+#define UHTTP_ERR_ARP        (-6)
+#define UHTTP_ERR_CONNECT    (-7)
+#define UHTTP_ERR_REFUSED    (-8)
+#define UHTTP_ERR_TLS        (-9)
+#define UHTTP_ERR_SEND       (-10)
+#define UHTTP_ERR_TIMEOUT    (-11)
+#define UHTTP_ERR_RESET      (-12)
+#define UHTTP_ERR_REDIRECT   (-13)
+#define UHTTP_ERR_TOOMANY    (-14)
+#define UHTTP_ERR_TOOLONG    (-15)
+
+struct uhttp_url {
+	char host[UHTTP_HOST_MAX];
+	char path[UHTTP_PATH_MAX];
+	unsigned int port;
+	int secure;
+};
+
+struct uhttp_response {
+	int status;
+	int chunked;
+	int have_length;
+	unsigned int content_length;
+	int gzip;                       /* Content-Encoding: gzip */
+	char content_type[64];
+	char content_encoding[16];
+	char final_url[UHTTP_HOST_MAX + UHTTP_PATH_MAX + 16];
+};
+
+/* Optional callbacks; curl uses them for its existing verbose output, the
+ * browser passes NULL. */
+struct uhttp_hooks {
+	void (*connected)(void *ctx, int secure);
+	void (*status)(void *ctx, int code, const char *line);
+	void (*header)(void *ctx, const char *line);
+	void (*redirect)(void *ctx, const char *location);
+	void *ctx;
+};
+
+struct uhttp {
+	struct uhttp_url url;
+	struct uhttp_response resp;
+	const struct uhttp_hooks *hooks;
+	const char *user_agent;
+
+	unsigned char buf[UHTTP_READER_MAX];
+	unsigned int len, pos;
+	unsigned int total_deadline;
+	int eof;
+	int error;                      /* UHTTP_ERR_* once a read failed */
+	int connected;
+	int owns_nic;
+
+	/* chunked transfer state */
+	int chunk_state;                /* 0 size line, 1 data, 2 crlf, 3 trailers */
+	unsigned int chunk_left;
+	unsigned int body_read;
+};
+
+void uhttp_init(struct uhttp *h);
+int  uhttp_parse_url(const char *s, struct uhttp_url *u);
+int  uhttp_open(struct uhttp *h, const char *url, unsigned int flags,
+		const struct uhttp_hooks *hooks);
+int  uhttp_read(struct uhttp *h, void *buf, unsigned int max,
+		unsigned int timeout_ms);
+void uhttp_close(struct uhttp *h);
+const char *uhttp_error_string(int err);
+
+/* Resolve an href against a base URL (absolute, absolute-path, relative and
+ * scheme-relative forms).  0 on success. */
+int uhttp_resolve(const char *base, const char *href, char *out,
+		  unsigned int cap);
+
+#endif

+ 16 - 9
vfs.c

@@ -5,6 +5,7 @@
 #include "vfs.h"
 #include "fatdetect.h"
 #include "io.h"
+#include "kmalloc.h"
 #include "ramfs.h"
 #include "share.h"
 
@@ -89,10 +90,6 @@ static void copy_bounded(char *dst, const char *src, unsigned int size)
 
 static void fat_cache_clear(void);
 
-/* One load buffer for the shell: only one command is loaded at a time and the
- * ELF loader has copied the segments out before we return. */
-static unsigned char fat_load_buf[VFS_FILE_MAX];
-
 static int fat_op_read_file(struct vfs_mount *m, const char *path,
 			    void *buf, unsigned int max)
 {
@@ -129,16 +126,24 @@ static int fat_op_load_file(struct vfs_mount *m, const char *path,
 {
 	unsigned int size = 0;
 	int is_dir = 0, r;
+	void *buf;
 
 	r = fat_op_stat(m, path, &size, &is_dir);
 	if (r != 0)
 		return r;
-	if (is_dir || size == 0 || size > sizeof(fat_load_buf))
+	if (is_dir || size == 0 || size > VFS_FILE_MAX)
 		return VFS_EINVAL;
-	r = fat_op_read_file(m, path, fat_load_buf, sizeof(fat_load_buf));
-	if (r < 0)
+	/* One command is loaded at a time; the ELF loader has copied the
+	 * segments out before release_file() runs, so a heap buffer is safe. */
+	buf = kmalloc(size);
+	if (!buf)
+		return VFS_EINVAL;
+	r = fat_op_read_file(m, path, buf, size);
+	if (r < 0) {
+		kfree(buf);
 		return r;
-	out->data = fat_load_buf;
+	}
+	out->data = buf;
 	out->size = (unsigned int)r;
 	return 0;
 }
@@ -146,7 +151,9 @@ static int fat_op_load_file(struct vfs_mount *m, const char *path,
 static void fat_op_release_file(struct vfs_mount *m, struct vfs_file *f)
 {
 	(void)m;
-	(void)f;
+	kfree((void *)f->data);
+	f->data = 0;
+	f->size = 0;
 }
 
 static int fat_op_write_file(struct vfs_mount *m, const char *path,

+ 4 - 2
vfs.h

@@ -7,8 +7,10 @@
 #include "blkdev.h"
 #include "fat.h"
 
-/* Largest file the shell will load from a filesystem into a kernel buffer. */
-#define VFS_FILE_MAX (16 * 1024)
+/* Largest file the shell will load from a filesystem into a kernel buffer.
+ * The buffer is allocated from the kernel heap (not a static BSS array), so a
+ * large ELF on a FAT mount can be spawned without moving the low-memory wall. */
+#define VFS_FILE_MAX (2u * 1024u * 1024u)
 
 struct vfs_mount;
 struct fs_ops;

+ 4 - 0
wm_abi.h

@@ -30,6 +30,10 @@
 #define WM_BTN_MINES_Y WM_BTN_Y
 #define WM_BTN_MINES_W 56
 #define WM_BTN_MINES_H WM_BTN_H
+#define WM_BTN_WEB_X (WM_BTN_MINES_X + WM_BTN_MINES_W + WM_BTN_GAP)
+#define WM_BTN_WEB_Y WM_BTN_Y
+#define WM_BTN_WEB_W 56
+#define WM_BTN_WEB_H WM_BTN_H
 #define WM_TITLE_H 22
 #define WM_CLOSE_W 16