Explorar el Código

Keep a list of saved WiFi networks in /data

WIFI.CFG is now a most-recently-used list of up to 16 SSID/passphrase records behind a small header instead of one record.  A re-connect replaces the record and moves it to the front, a full list evicts the least recently used network, and the old one-record file is still read.

- wifi_store.c/h: load/save/find/add/forget the list over the file service, with a 512-byte read slack for the FAT partial-sector write.
- ucmd_wifi.c: 'wifi saved', 'wifi forget [ssid]' (all without an SSID), and autoconnect scans once, joins the strongest saved network found, tries the others and rescans after three seconds.
- ucmd_netmenu.c: mark saved SSIDs, join with the stored passphrase, and add a Saved view with a Forget button per network.
- Makefile, .gitignore: build wifi_store and the host test.
- AGENTS.md and docs updated; make test-wifi-store and test-wpa pass.
Johannes Zellner hace 1 semana
padre
commit
c7fcd79baf
Se han modificado 14 ficheros con 849 adiciones y 215 borrados
  1. 1 0
      .gitignore
  2. 33 17
      AGENTS.md
  3. 18 6
      Makefile
  4. 3 1
      docs/development.html
  5. 1 1
      docs/filesystems.html
  6. 25 13
      docs/network.html
  7. 2 2
      docs/userland.html
  8. 4 3
      kernel.c
  9. 153 5
      ucmd_netmenu.c
  10. 195 160
      ucmd_wifi.c
  11. 24 7
      wifi_cfg.h
  12. 157 0
      wifi_store.c
  13. 28 0
      wifi_store.h
  14. 205 0
      wifi_store_test.c

+ 1 - 0
.gitignore

@@ -32,4 +32,5 @@ uhttp_cookie_test
 chat_login_test
 chat_login_test
 chat-test-out/
 chat-test-out/
 wpa_test
 wpa_test
+wifi_store_test
 firmware/
 firmware/

+ 33 - 17
AGENTS.md

@@ -84,6 +84,7 @@ make test-font-asan  # ASan/UBSan variant
 make test-svg   # host tests for the inline-SVG rasterizer (ASan/UBSan)
 make test-svg   # host tests for the inline-SVG rasterizer (ASan/UBSan)
 make test-touchpad  # host tests for the contact gesture engine
 make test-touchpad  # host tests for the contact gesture engine
 make test-wpa   # host tests for the WPA2-PSK supplicant (SHA-1/PBKDF2/PRF/AES, 4-way)
 make test-wpa   # host tests for the WPA2-PSK supplicant (SHA-1/PBKDF2/PRF/AES, 4-way)
+make test-wifi-store  # host tests for the saved-network list file
 make test-chat  # host tests: JSON parser, cookie jar, chat login parsers (ASan)
 make test-chat  # host tests: JSON parser, cookie jar, chat login parsers (ASan)
 make test-chat-e2e  # QEMU + tools/mock_chat.py chat end-to-end (CHAT_E2E=--totp...)
 make test-chat-e2e  # QEMU + tools/mock_chat.py chat end-to-end (CHAT_E2E=--totp...)
 make compat-serve  # serve the browser A/B ladder on port 8000
 make compat-serve  # serve the browser A/B ladder on port 8000
@@ -629,7 +630,9 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   failure.  The top-bar network icon opens `ucmd_netmenu.c`, which lists every
   failure.  The top-bar network icon opens `ucmd_netmenu.c`, which lists every
   present driver through `SYS_NET_DEVLIST` (111), selects one through
   present driver through `SYS_NET_DEVLIST` (111), selects one through
   `SYS_NET_SELECT` (112) and runs DHCP; the same window lists scanned WiFi
   `SYS_NET_SELECT` (112) and runs DHCP; the same window lists scanned WiFi
-  networks and asks for the WPA2 passphrase.  Hidden SSIDs are omitted, and
+  networks, marks the ones in `/data/WIFI.CFG` as saved, joins them with the
+  stored passphrase, and has a Saved view that forgets individual networks.
+  Hidden SSIDs are omitted, and
   BSSIDs that share an SSID/security collapse to the strongest entry (the
   BSSIDs that share an SSID/security collapse to the strongest entry (the
   active BSSID wins while connected).  `wifi.c` (the Intel
   active BSSID wins while connected).  `wifi.c` (the Intel
   7265D/3165 netdev, see the WiFi bullet) is
   7265D/3165 netdev, see the WiFi bullet) is
@@ -707,27 +710,37 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   7265D-29 firmware does not use correctly installed `ADD_STA_KEY` keys for
   7265D-29 firmware does not use correctly installed `ADD_STA_KEY` keys for
   RX even though TX (which embeds the TK in `TX_CMD`) works; there is no
   RX even though TX (which embeds the TK in `TX_CMD`) works; there is no
   software replay window yet.
   software replay window yet.
-  The firmware is loaded on the first `wifi` command, not at boot.
+  The firmware is loaded on first use (`wifi` or the boot autoconnect
+  helper), not during kernel init.
   `netdev_shutdown()` always calls `wifi_shutdown()` before a kexec (the RX
   `netdev_shutdown()` always calls `wifi_shutdown()` before a kexec (the RX
   ring would keep writing into reused pages).  The ring-3 side is
   ring would keep writing into reused pages).  The ring-3 side is
   `ucmd_wifi.c` (`wifi`, `wifi up|scan|connect <ssid> [pass]|disconnect`,
   `ucmd_wifi.c` (`wifi`, `wifi up|scan|connect <ssid> [pass]|disconnect`,
   `wifi connectfile <path>` for the network menu's staged SSID/pass/BSSID
   `wifi connectfile <path>` for the network menu's staged SSID/pass/BSSID
-  record, `wifi autoconnect` for the boot helper and `wifi forget`),
+  record, `wifi saved` to list the saved networks, `wifi autoconnect` for the
+  boot helper and `wifi forget [ssid]`),
   `wpa.c/h` (4-way + group handshake, key descriptor v2) and
   `wpa.c/h` (4-way + group handshake, key descriptor v2) and
   `wpa_crypto.c/h` (SHA-1, HMAC, PBKDF2, PRF, AES-128, RFC 3394 unwrap; host
   `wpa_crypto.c/h` (SHA-1, HMAC, PBKDF2, PRF, AES-128, RFC 3394 unwrap; host
   test `make test-wpa`).  After the handshake `wifi connect` installs the
   test `make test-wpa`).  After the handshake `wifi connect` installs the
   TK/GTK, calls `SYS_WIFI_AUTHORIZE` (data port open + `netdev_select
   TK/GTK, calls `SYS_WIFI_AUTHORIZE` (data port open + `netdev_select
   ("wifi")`), runs DHCP and leaves `wifi __keep` running for group rekeys.
   ("wifi")`), runs DHCP and leaves `wifi __keep` running for group rekeys.
-  A successful menu/CLI connect also writes the SSID and passphrase to
-  `/data/WIFI.CFG` (8.3, plaintext, BSSID zeroed so a mesh/repeater AP works);
-  after the storage scan and the boot DHCP attempt the `bootscan` thread spawns
+  A successful menu/CLI connect stores the SSID and passphrase through
+  `wifi_store.c/h` in `/data/WIFI.CFG` (8.3, plaintext), a
+  most-recently-used list of up to `WIFI_CFG_MAX` (16) fixed records behind
+  a list header; the old one-record file is still read.  Re-connecting a
+  known SSID replaces its record and moves it to the front, and a full list
+  drops the least recently used network.  Each record leaves the BSSID zero
+  so a mesh/repeater AP with the same SSID still works.  After the storage
+  scan and the boot DHCP attempt the `bootscan` thread spawns
   `/ramfs/bin/wifi autoconnect` when that file exists.  Autoconnect leaves a
   `/ramfs/bin/wifi autoconnect` when that file exists.  Autoconnect leaves a
-  wired link that is physically up alone and only tries WiFi when no wired
-  link is present; an already-linked WiFi card is also left alone.  `/data`
-  is the persistent FAT volume from the installer.
-  `wifi forget` removes the saved record.  A FAT read may write a final
-  partial sector past the requested length, so the credential reader keeps
-  512 bytes of slack on the stack.
+  wired link that is physically up alone, and an already-linked WiFi card
+  too.  Otherwise it scans once and joins the strongest network present whose
+  SSID is in the saved list, moves on to the other saved networks found if
+  one fails, and rescans after three seconds for a second pass.  `/data` is
+  the persistent FAT volume from the installer.  `wifi forget` without an
+  SSID removes the whole list, `wifi forget <ssid>` one record; the network
+  menu marks saved SSIDs and its Saved view forgets them individually.  A FAT
+  read may write a final partial sector past the requested length, so the
+  credential reader keeps 512 bytes of slack on the stack.
   The helper's PTK and EAPOL replay counter are kept in the kernel
   The helper's PTK and EAPOL replay counter are kept in the kernel
   (`SYS_WIFI_SET_PTK`/`SYS_WIFI_GET_PTK`) and fetched by connection ID, so
   (`SYS_WIFI_SET_PTK`/`SYS_WIFI_GET_PTK`) and fetched by connection ID, so
   the 64-byte `SYS_SPAWN` argument limit cannot truncate the rekey state.
   the 64-byte `SYS_SPAWN` argument limit cannot truncate the rekey state.
@@ -1934,11 +1947,11 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
    with `--gc-sections`; the current full pack with the UI fonts, both
    with `--gc-sections`; the current full pack with the UI fonts, both
    WiFi firmwares (7265D 1,036,312 bytes, ~442 KiB gzip; 6000 454,608 bytes,
    WiFi firmwares (7265D 1,036,312 bytes, ~442 KiB gzip; 6000 454,608 bytes,
    ~204 KiB gzip), the RTL8821A firmware and tables (31,898 + 11,668
    ~204 KiB gzip), the RTL8821A firmware and tables (31,898 + 11,668
-   bytes) and `install/kernel.bin` is ~1.75 MiB gzip (1,832,893
-   bytes, ~264 KB under the cap), inflating to ~3.6 MB, which adds about
+   bytes) and `install/kernel.bin` is ~1.75 MiB gzip (~260 KB under the
+   cap), inflating to ~3.6 MB, which adds about
    half a second to the boot; the floppy lite pack is ~930 KiB gzip and
    half a second to the boot; the floppy lite pack is ~930 KiB gzip and
    deliberately omits the firmware and `install/kernel.bin`.  `libdeflate-gzip -12` is still preferred.  Over
    deliberately omits the firmware and `install/kernel.bin`.  `libdeflate-gzip -12` is still preferred.  Over
-   115200 serial a raw `cmds-dev` pack (2.6 MB) now takes about three
+   115200 serial a raw `cmds-dev` pack (3.5 MiB) now takes about four
    minutes; use `net-cmds`.
    minutes; use `net-cmds`.
 9. SMP is **ACPI/MADT only**: no Intel MP-table fallback, so a Pentium II SMP
 9. SMP is **ACPI/MADT only**: no Intel MP-table fallback, so a Pentium II SMP
     board that exposes only MP tables stays UP (deliberate; there is no test
     board that exposes only MP tables stays UP (deliberate; there is no test
@@ -2290,8 +2303,11 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     netmenu instances (e.g. one launched from a terminal) would overwrite
     netmenu instances (e.g. one launched from a terminal) would overwrite
     each other.  The `wifi` helper is asynchronous: closing the menu does not
     each other.  The `wifi` helper is asynchronous: closing the menu does not
     cancel a connection attempt.  Saved credentials live in plaintext
     cancel a connection attempt.  Saved credentials live in plaintext
-    `/data/WIFI.CFG` (8.3), hold one network, and are retried at boot; use
-    `wifi forget` to remove them.  There is no menu button for forgetting yet.
+    `/data/WIFI.CFG` (8.3), hold up to 16 networks, and are retried at boot;
+    `wifi saved` lists them, `wifi forget [ssid]` removes one and the menu's
+    Saved view has a Forget button per network.  A network saved with a wrong
+    passphrase is tried again at every boot until it is forgotten (Saved view
+    or `wifi forget <ssid>`) and joined again with the correct passphrase.
 
 
 37. `/data` limits: the data partition is a plain FAT volume, so file names
 37. `/data` limits: the data partition is a plain FAT volume, so file names
     are 8.3 until `fat.c` gains LFN write support; there is no fsck, resize or
     are 8.3 until `fat.c` gains LFN write support; there is no fsck, resize or

+ 18 - 6
Makefile

@@ -68,7 +68,7 @@ EFI_LDFLAGS = -nostdlib -Wl,--subsystem,10 -Wl,-e,efi_main \
               -Wl,--image-base,0x0 -Wl,--dynamicbase \
               -Wl,--image-base,0x0 -Wl,--dynamicbase \
               -Wl,--enable-reloc-section -Wl,--no-insert-timestamp
               -Wl,--enable-reloc-section -Wl,--no-insert-timestamp
 
 
-.PHONY: all clean run run-smp run-floppy run-usb run-uhci run-ehci run-ehci-asix run-xhci run-xhci-asix run-net run-rndis run-e1000 run-ahci test-usb test-install run-serial floppy usb uefi run-uefi test-uefi flash dev net-dev net-install cmds-dev net-cmds browser-dev gallery-dev compat-serve netmon monitor test-crypto test-wpa test-ccmp test-images test-images-asan test-libc test-font test-font-asan test-svg test-touchpad test-chat test-chat-e2e fonts kernel-dev kernel-net-dev rootfs
+.PHONY: all clean run run-smp run-floppy run-usb run-uhci run-ehci run-ehci-asix run-xhci run-xhci-asix run-net run-rndis run-e1000 run-ahci test-usb test-install run-serial floppy usb uefi run-uefi test-uefi flash dev net-dev net-install cmds-dev net-cmds browser-dev gallery-dev compat-serve netmon monitor test-crypto test-wpa test-ccmp test-images test-images-asan test-libc test-font test-font-asan test-svg test-touchpad test-chat test-chat-e2e test-wifi-store fonts kernel-dev kernel-net-dev rootfs
 
 
 all: floppy.img usb.img final.bin root.img image.bin
 all: floppy.img usb.img final.bin root.img image.bin
 
 
@@ -898,17 +898,23 @@ wpa.o: wpa.c wpa.h wpa_crypto.h
 wpa_crypto.o: wpa_crypto.c wpa_crypto.h
 wpa_crypto.o: wpa_crypto.c wpa_crypto.h
 	$(CC) $(CFLAGS) -O2 $(SECTION_CFLAGS) -o $@ $<
 	$(CC) $(CFLAGS) -O2 $(SECTION_CFLAGS) -o $@ $<
 
 
-ucmd_wifi.o: ucmd_wifi.c ucmd_lib.h syscall.h wpa.h tls_rng.h wifi_cfg.h
+ucmd_wifi.o: ucmd_wifi.c ucmd_lib.h syscall.h wpa.h tls_rng.h wifi_store.h \
+             wifi_cfg.h
 
 
-ucmd_wifi.elf: ucmd_wifi.o $(WPA_OBJS) tls_rng.o tls_sha256.o ucmd.ld libc.a
+wifi_store.o: wifi_store.c wifi_store.h wifi_cfg.h ucmd_lib.h syscall.h
+	$(CC) $(CFLAGS) -Ilibc/include -o $@ $<
+
+ucmd_wifi.elf: ucmd_wifi.o wifi_store.o $(WPA_OBJS) tls_rng.o tls_sha256.o ucmd.ld libc.a
 	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(OBJCOPY) --strip-all $@ $@
 	$(OBJCOPY) --strip-all $@ $@
 
 
-# Top-bar network menu: NIC list, WiFi scan and the WPA2 passphrase prompt.
-ucmd_netmenu.o: ucmd_netmenu.c ucmd_lib.h syscall.h ngui.h wifi_cfg.h
+# Top-bar network menu: NIC list, WiFi scan, saved networks and the WPA2
+# passphrase prompt.
+ucmd_netmenu.o: ucmd_netmenu.c ucmd_lib.h syscall.h ngui.h wifi_store.h \
+                wifi_cfg.h
 	$(CC) $(CFLAGS) -Ilibc/include -o $@ $<
 	$(CC) $(CFLAGS) -Ilibc/include -o $@ $<
 
 
-ucmd_netmenu.elf: ucmd_netmenu.o ngui.o font_8x16.o $(UFONT_OBJS) ucmd.ld libc.a
+ucmd_netmenu.elf: ucmd_netmenu.o wifi_store.o ngui.o font_8x16.o $(UFONT_OBJS) ucmd.ld libc.a
 	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(OBJCOPY) --strip-all $@ $@
 	$(OBJCOPY) --strip-all $@ $@
 
 
@@ -918,6 +924,12 @@ wpa_test: wpa_test.c wpa.c wpa_crypto.c wpa.h wpa_crypto.h
 test-wpa: wpa_test
 test-wpa: wpa_test
 	./wpa_test
 	./wpa_test
 
 
+wifi_store_test: wifi_store_test.c wifi_store.c wifi_store.h wifi_cfg.h syscall.h
+	gcc -m32 -O2 -Wall -Wextra -I. -o wifi_store_test wifi_store_test.c
+
+test-wifi-store: wifi_store_test
+	./wifi_store_test
+
 ccmp_test: ccmp_test.c ccmp.c ccmp.h
 ccmp_test: ccmp_test.c ccmp.c ccmp.h
 	gcc -O2 -Wall -Wextra -I. -o $@ ccmp_test.c
 	gcc -O2 -Wall -Wextra -I. -o $@ ccmp_test.c
 
 

+ 3 - 1
docs/development.html

@@ -182,6 +182,7 @@
 					<tr><td><code>make test-images</code> / <code>test-images-asan</code></td><td>Host image-decoder and blit tests, with an AddressSanitizer variant.</td></tr>
 					<tr><td><code>make test-images</code> / <code>test-images-asan</code></td><td>Host image-decoder and blit tests, with an AddressSanitizer variant.</td></tr>
 					<tr><td><code>make test-crypto</code></td><td>Host vectors for SHA-256, ChaCha20-Poly1305, X25519 and TLS helpers.</td></tr>
 					<tr><td><code>make test-crypto</code></td><td>Host vectors for SHA-256, ChaCha20-Poly1305, X25519 and TLS helpers.</td></tr>
 					<tr><td><code>make test-wpa</code></td><td>Host vectors for the WPA2 supplicant: SHA-1, RFC 6070 PBKDF2, the 802.11 PSK and PRF examples, FIPS-197 AES, RFC 3394 unwrap, plus a simulated 4-way handshake, group rekey, replay and wrong-passphrase case.</td></tr>
 					<tr><td><code>make test-wpa</code></td><td>Host vectors for the WPA2 supplicant: SHA-1, RFC 6070 PBKDF2, the 802.11 PSK and PRF examples, FIPS-197 AES, RFC 3394 unwrap, plus a simulated 4-way handshake, group rekey, replay and wrong-passphrase case.</td></tr>
+					<tr><td><code>make test-wifi-store</code></td><td>Host test for the saved-network file: newest-first ordering, passphrase update, LRU eviction at the 16-entry cap, per-SSID forget, the old one-record format and malformed or duplicate lists.</td></tr>
 					<tr><td><code>make test-libc</code></td><td>Host tests for the ring-3 malloc, stdio/float formatting, math, 64-bit division helpers and setjmp/longjmp.</td></tr>
 					<tr><td><code>make test-libc</code></td><td>Host tests for the ring-3 malloc, stdio/float formatting, math, 64-bit division helpers and setjmp/longjmp.</td></tr>
 					<tr><td><code>make test-js</code></td><td>Host tests (ASan/UBSan) for the vendored QuickJS engine through the <code>js_mu</code> stack API: modern syntax (classes, arrows, templates, destructuring, spread, async/await, BigInt, named regex groups), Promise jobs, C functions and <code>new</code>, thrown TypeErrors, userdata hooks and expandos, registry refs and the wall-clock interrupt.</td></tr>
 					<tr><td><code>make test-js</code></td><td>Host tests (ASan/UBSan) for the vendored QuickJS engine through the <code>js_mu</code> stack API: modern syntax (classes, arrows, templates, destructuring, spread, async/await, BigInt, named regex groups), Promise jobs, C functions and <code>new</code>, thrown TypeErrors, userdata hooks and expandos, registry refs and the wall-clock interrupt.</td></tr>
 					<tr><td><code>make test-font</code> / <code>test-font-asan</code></td><td>Host specimen test for the fixed-point TrueType parser/rasterizer and glyph cache, with an AddressSanitizer/UBSan variant.</td></tr>
 					<tr><td><code>make test-font</code> / <code>test-font-asan</code></td><td>Host specimen test for the fixed-point TrueType parser/rasterizer and glyph cache, with an AddressSanitizer/UBSan variant.</td></tr>
@@ -287,7 +288,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 			<li><strong>Installer.</strong> <code>make test-install</code> boots the dual image with its USB mass-storage source and a blank target, types <code>install ide1</code> through QMP, verifies the clone and boots the target in BIOS and (under OVMF) UEFI.</li>
 			<li><strong>Installer.</strong> <code>make test-install</code> boots the dual image with its USB mass-storage source and a blank target, types <code>install ide1</code> through QMP, verifies the clone and boots the target in BIOS and (under OVMF) UEFI.</li>
 			<li><strong>Image library.</strong> <code>make test-images</code> decodes a corpus of PNG/JPEG/GIF/BMP/TGA/PNM/ICO/PAM files and checks blits; the ASan variant catches memory errors.</li>
 			<li><strong>Image library.</strong> <code>make test-images</code> decodes a corpus of PNG/JPEG/GIF/BMP/TGA/PNM/ICO/PAM files and checks blits; the ASan variant catches memory errors.</li>
 			<li><strong>Crypto.</strong> <code>make test-crypto</code> runs host vectors for the freestanding crypto code.</li>
 			<li><strong>Crypto.</strong> <code>make test-crypto</code> runs host vectors for the freestanding crypto code.</li>
-			<li><strong>WPA2.</strong> <code>make test-wpa</code> runs <span class="file">wpa_test.c</span> against <span class="file">wpa_crypto.c</span> and <span class="file">wpa.c</span>. The WiFi driver itself has no QEMU model: test it on the Chromebook over <code>make net-dev</code> with the RNDIS phone or ASIX dongle as the management link and <code>make netmon</code> for the <code>iwl:</code>/<code>wifi:</code> trail.</li>
+			<li><strong>WPA2.</strong> <code>make test-wpa</code> runs <span class="file">wpa_test.c</span> against <span class="file">wpa_crypto.c</span> and <span class="file">wpa.c</span>. <code>make test-wifi-store</code> runs the saved-network list against an in-memory FAT file: ordering, update, eviction, forget and the legacy/malformed formats. The WiFi driver itself has no QEMU model: test it on the Chromebook over <code>make net-dev</code> with the RNDIS phone or ASIX dongle as the management link and <code>make netmon</code> for the <code>iwl:</code>/<code>wifi:</code> trail.</li>
 			<li><strong>Ring-3 libc.</strong> <code>make test-libc</code> runs the malloc stress test (64 MB simulated arena with poisoned pages), exact <code>snprintf</code> float/string checks against the host, x87 math values, the 64-bit division helpers and a 32-bit setjmp/longjmp test.</li>
 			<li><strong>Ring-3 libc.</strong> <code>make test-libc</code> runs the malloc stress test (64 MB simulated arena with poisoned pages), exact <code>snprintf</code> float/string checks against the host, x87 math values, the 64-bit division helpers and a 32-bit setjmp/longjmp test.</li>
 			<li><strong>Fonts.</strong> <code>make test-font</code> parses the checked-in Arimo subset on the host, measures Latin-1 text, renders composites (for example <code>Äé</code>) and writes a specimen PPM. The browser must also be exercised across a navigation to verify detach/reattach around <code>heap_reset()</code>.</li>
 			<li><strong>Fonts.</strong> <code>make test-font</code> parses the checked-in Arimo subset on the host, measures Latin-1 text, renders composites (for example <code>Äé</code>) and writes a specimen PPM. The browser must also be exercised across a navigation to verify detach/reattach around <code>heap_reset()</code>.</li>
 			<li><strong>Touchpad gestures.</strong> <code>make test-touchpad</code> feeds synthetic contact frames to <span class="file">touchpad_gesture.c</span> and checks one/two-finger taps, the corner and physical-button mapping, scroll start/direction, pointer freeze and re-anchoring, and the option switches.</li>
 			<li><strong>Touchpad gestures.</strong> <code>make test-touchpad</code> feeds synthetic contact frames to <span class="file">touchpad_gesture.c</span> and checks one/two-finger taps, the corner and physical-button mapping, scroll start/direction, pointer freeze and re-anchoring, and the option switches.</li>
@@ -373,6 +374,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 			<li><code>kernel.ld</code>, <code>ucmd.ld</code> — link limits</li>
 			<li><code>kernel.ld</code>, <code>ucmd.ld</code> — link limits</li>
 			<li><code>tools/</code> — QMP USB and installer tests</li>
 			<li><code>tools/</code> — QMP USB and installer tests</li>
 			<li><code>wpa_test.c</code> — WPA2 supplicant host test (<code>make test-wpa</code>)</li>
 			<li><code>wpa_test.c</code> — WPA2 supplicant host test (<code>make test-wpa</code>)</li>
+			<li><code>wifi_store_test.c</code> — saved WiFi list host test (<code>make test-wifi-store</code>)</li>
 			<li><code>AGENTS.md</code> — developer notes and maintenance rule</li>
 			<li><code>AGENTS.md</code> — developer notes and maintenance rule</li>
 		</ul>
 		</ul>
 	</section>
 	</section>

+ 1 - 1
docs/filesystems.html

@@ -311,7 +311,7 @@
 			<li><strong>Persistent.</strong> A reinstall or <code>install &lt;target&gt; self</code> replaces the OS partitions (P1 kernel, P2 rootfs pack, P3 ESP) and keeps P4. <code>net-install</code> writes only P1/P2.</li>
 			<li><strong>Persistent.</strong> A reinstall or <code>install &lt;target&gt; self</code> replaces the OS partitions (P1 kernel, P2 rootfs pack, P3 ESP) and keeps P4. <code>net-install</code> writes only P1/P2.</li>
 			<li><strong>First install is destructive.</strong> Creating P4 formats the rest of the target disk; an existing <code>NEBOSDATA</code> volume is detected and left untouched.</li>
 			<li><strong>First install is destructive.</strong> Creating P4 formats the rest of the target disk; an existing <code>NEBOSDATA</code> volume is detected and left untouched.</li>
 			<li><strong>8.3 names.</strong> The FAT driver creates and reads short names only; long names need VFAT LFN write support.</li>
 			<li><strong>8.3 names.</strong> The FAT driver creates and reads short names only; long names need VFAT LFN write support.</li>
-			<li><strong>WiFi credentials.</strong> A successful WiFi connect stores the SSID/passphrase in <code>WIFI.CFG</code>; the boot-time <code>wifi autoconnect</code> helper reads it. The file is plaintext and 8.3, like the rest of the volume.</li>
+			<li><strong>WiFi credentials.</strong> A successful WiFi connect adds the network to a most-recently-used list of up to 16 SSID/passphrase records in <code>WIFI.CFG</code>; the boot-time <code>wifi autoconnect</code> helper scans and joins the strongest saved network it finds. <code>wifi saved</code> lists them and <code>wifi forget [ssid]</code> removes one. The file is plaintext and 8.3, like the rest of the volume.</li>
 			<li><strong>Chat session.</strong> The Chat client stores its server and session cookie in <code>CHAT.CFG</code> when this volume is mounted; without it the client falls back to the RAM-only <code>/share/chat.cfg</code>. The cookie is a bearer credential, and the password is never stored.</li>
 			<li><strong>Chat session.</strong> The Chat client stores its server and session cookie in <code>CHAT.CFG</code> when this volume is mounted; without it the client falls back to the RAM-only <code>/share/chat.cfg</code>. The cookie is a bearer credential, and the password is never stored.</li>
 			<li><strong>Fixed start.</strong> P4 starts at LBA 34816. A BIOS-only install leaves the space between P2 and P4 unpartitioned, and a later disk clone does not resize P4.</li>
 			<li><strong>Fixed start.</strong> P4 starts at LBA 34816. A BIOS-only install leaves the space between P2 and P4 unpartitioned, and a later disk clone does not resize P4.</li>
 			<li><strong>No fsck.</strong> Like the other FAT mounts, the volume has no journal, repair tool or permissions; it is writable by every process.</li>
 			<li><strong>No fsck.</strong> Like the other FAT mounts, the volume has no journal, repair tool or permissions; it is writable by every process.</li>

+ 25 - 13
docs/network.html

@@ -193,17 +193,29 @@
 			after reading it.
 			after reading it.
 		</p>
 		</p>
 		<p>
 		<p>
-			A successful <code>wifi connect</code> (from the CLI or the menu) also saves
-			the SSID and passphrase to <code>/data/WIFI.CFG</code> on the
-			persistent <code>NEBOSDATA</code> partition. After the boot DHCP
-			attempt and the storage scan, the <code>bootscan</code> thread spawns
-			<code>wifi autoconnect</code> when that file exists. It samples the
-			active NIC's <code>link_up()</code> state: a wired cable that is
-			physically up keeps the Ethernet path, while no wired link lets
-			WiFi associate and run DHCP. An existing WiFi link is left alone.
-			<code>wifi forget</code> removes the saved record.
-			The file is a plaintext 8.3 FAT file with the BSSID zeroed so the
-			strongest AP advertising that SSID is used.
+			A successful <code>wifi connect</code> (from the CLI or the menu) adds
+			the network to a most-recently-used list of up to
+			<code>WIFI_CFG_MAX</code> (16) SSID/passphrase records in
+			<code>/data/WIFI.CFG</code> on the persistent <code>NEBOSDATA</code>
+			partition. The network menu marks every scanned SSID that is in the
+			list as <em>saved</em>, joins it with the stored passphrase without
+			asking again, and its <em>Saved</em> view lists the records with a
+			<em>Forget</em> button each. The <code>wifi saved</code> command
+			prints the same list and <code>wifi forget [ssid]</code> removes one
+			network (or all of them without an SSID).
+		</p>
+		<p>
+			After the boot DHCP attempt and the storage scan, the
+			<code>bootscan</code> thread spawns <code>wifi autoconnect</code>
+			when that file exists. It samples the active NIC's
+			<code>link_up()</code> state: a wired cable that is physically up
+			keeps the Ethernet path, while no wired link lets WiFi scan and
+			join the strongest network present whose SSID is in the saved list,
+			trying the other saved networks found if one fails and rescanning
+			once after three seconds. An existing WiFi link is left alone. The
+			file is a plaintext 8.3 FAT file (one list header plus fixed-size
+			records, most recently used first); no BSSID is stored, so the
+			strongest AP advertising a saved SSID is used.
 		</p>
 		</p>
 		<div class="table-wrap">
 		<div class="table-wrap">
 			<table>
 			<table>
@@ -465,7 +477,7 @@
 					<tr><td>WebDAV</td><td>No authentication</td><td>Anyone on the LAN can read mounts and write <code>/share</code>.</td></tr>
 					<tr><td>WebDAV</td><td>No authentication</td><td>Anyone on the LAN can read mounts and write <code>/share</code>.</td></tr>
 					<tr><td>Chat session</td><td>Cookie saved in <code>/data/CHAT.CFG</code>, or <code>/share/chat.cfg</code> without a <code>/data</code> mount</td><td>A bearer credential on disk while <code>/data</code> is mounted, otherwise RAM until sign-out; the password is sent over unverified TLS and never stored.</td></tr>
 					<tr><td>Chat session</td><td>Cookie saved in <code>/data/CHAT.CFG</code>, or <code>/share/chat.cfg</code> without a <code>/data</code> mount</td><td>A bearer credential on disk while <code>/data</code> is mounted, otherwise RAM until sign-out; the password is sent over unverified TLS and never stored.</td></tr>
 					<tr><td>WiFi WPA2</td><td>PSK/CCMP, handshake in ring 3</td><td>The SNonce comes from the weak TLS DRBG. The PTK/replay are kept in the kernel (<code>SYS_WIFI_SET_PTK</code>/<code>SYS_WIFI_GET_PTK</code>) and fetched by the <code>wifi __keep</code> helper by connection ID for group rekeys; no WPA3/PMF.</td></tr>
 					<tr><td>WiFi WPA2</td><td>PSK/CCMP, handshake in ring 3</td><td>The SNonce comes from the weak TLS DRBG. The PTK/replay are kept in the kernel (<code>SYS_WIFI_SET_PTK</code>/<code>SYS_WIFI_GET_PTK</code>) and fetched by the <code>wifi __keep</code> helper by connection ID for group rekeys; no WPA3/PMF.</td></tr>
-					<tr><td>Saved WiFi credentials</td><td>Plaintext <code>/data/WIFI.CFG</code></td><td>The SSID and passphrase are stored in an 8.3 FAT file so <code>wifi autoconnect</code> can reconnect at boot; anyone who can read the disk can read the passphrase. <code>wifi forget</code> removes it.</td></tr>
+					<tr><td>Saved WiFi credentials</td><td>Plaintext <code>/data/WIFI.CFG</code></td><td>Up to 16 SSID/passphrase pairs are stored in an 8.3 FAT file (most recently used first) so <code>wifi autoconnect</code> can join any known network at boot; anyone who can read the disk can read the passphrases. <code>wifi forget [ssid]</code> and the menu's <em>Saved</em> view remove records.</td></tr>
 					<tr><td>NTP</td><td>Unauthenticated SNTP</td><td>Anyone who can answer for the server name can set the clock.</td></tr>
 					<tr><td>NTP</td><td>Unauthenticated SNTP</td><td>Anyone who can answer for the server name can set the clock.</td></tr>
 					<tr><td>NIC ownership</td><td>Raw lease for packet commands; shared TCP client table</td><td>Raw commands are mutually exclusive; up to twelve processes can hold one TCP connection each.  A killed owner is force-released.</td></tr>
 					<tr><td>NIC ownership</td><td>Raw lease for packet commands; shared TCP client table</td><td>Raw commands are mutually exclusive; up to twelve processes can hold one TCP connection each.  A killed owner is force-released.</td></tr>
 					<tr><td>Kernel/user isolation</td><td>None (identity map)</td><td>A ring-3 bug can reach any mapped kernel page.</td></tr>
 					<tr><td>Kernel/user isolation</td><td>None (identity map)</td><td>A ring-3 bug can reach any mapped kernel page.</td></tr>
@@ -481,7 +493,7 @@
 			<li><code>e1000e.c</code>, <code>r8168.c</code>, <code>ne2000.c</code>, <code>asix.c</code>, <code>rndis.c</code></li>
 			<li><code>e1000e.c</code>, <code>r8168.c</code>, <code>ne2000.c</code>, <code>asix.c</code>, <code>rndis.c</code></li>
 			<li><code>wifi.c</code>, <code>wifi_fw.c</code>, <code>iwl_mvm.c</code>, <code>iwl_dvm.c</code>, <code>iwl_trans.c</code>, <code>rtl8821au.c</code> — Intel 7265D/3165 and 6200/6300 WiFi, Realtek RTL8821AU USB WiFi</li>
 			<li><code>wifi.c</code>, <code>wifi_fw.c</code>, <code>iwl_mvm.c</code>, <code>iwl_dvm.c</code>, <code>iwl_trans.c</code>, <code>rtl8821au.c</code> — Intel 7265D/3165 and 6200/6300 WiFi, Realtek RTL8821AU USB WiFi</li>
 			<li><code>wpa.c</code>, <code>wpa_crypto.c</code>, <code>ucmd_wifi.c</code> — WPA2-PSK supplicant and the <code>wifi</code> command (<code>make test-wpa</code>)</li>
 			<li><code>wpa.c</code>, <code>wpa_crypto.c</code>, <code>ucmd_wifi.c</code> — WPA2-PSK supplicant and the <code>wifi</code> command (<code>make test-wpa</code>)</li>
-			<li><code>ucmd_netmenu.c</code>, <code>wifi_cfg.h</code> — top-bar network menu and its staged WiFi connect request</li>
+			<li><code>ucmd_netmenu.c</code>, <code>wifi_cfg.h</code>, <code>wifi_store.c/h</code> — top-bar network menu, staged WiFi connect request and the saved-network list</li>
 			<li><code>net.c</code>, <code>net.h</code> — ARP cache/ICMP/UDP/IP</li>
 			<li><code>net.c</code>, <code>net.h</code> — ARP cache/ICMP/UDP/IP</li>
 			<li><code>netcore.c</code>, <code>netcore.h</code> — shared receive pump and IRQ helpers</li>
 			<li><code>netcore.c</code>, <code>netcore.h</code> — shared receive pump and IRQ helpers</li>
 			<li><code>dhcp.c</code>, <code>dns.c</code>, <code>ntp.c</code></li>
 			<li><code>dhcp.c</code>, <code>dns.c</code>, <code>ntp.c</code></li>

+ 2 - 2
docs/userland.html

@@ -347,7 +347,7 @@
 			<li><strong>edit</strong> — text editor that draws its own text with the 8x16 font.</li>
 			<li><strong>edit</strong> — text editor that draws its own text with the 8x16 font.</li>
 			<li><strong>clock</strong> / <strong>colors</strong> — small window canvas demos.</li>
 			<li><strong>clock</strong> / <strong>colors</strong> — small window canvas demos.</li>
 			<li><strong>settime</strong> — Date &amp; Time editor opened by clicking the top-bar clock. It reads and writes the CMOS RTC through <code>SYS_RTC_GET</code>/<code>SYS_RTC_SET</code>; the <em>Sync NTP</em> button asks the kernel's SNTP client (<code>SYS_NTP_SYNC</code>, 106) for UTC and writes the result to the RTC. The two-digit RTC year is expanded over 1970–2069 so dead-battery defaults such as 1980/1990 can be corrected.</li>
 			<li><strong>settime</strong> — Date &amp; Time editor opened by clicking the top-bar clock. It reads and writes the CMOS RTC through <code>SYS_RTC_GET</code>/<code>SYS_RTC_SET</code>; the <em>Sync NTP</em> button asks the kernel's SNTP client (<code>SYS_NTP_SYNC</code>, 106) for UTC and writes the result to the RTC. The two-digit RTC year is expanded over 1970–2069 so dead-battery defaults such as 1980/1990 can be corrected.</li>
-			<li><strong>netmenu</strong> — network menu opened by the top-bar status icon. Lists the present NICs from <code>SYS_NET_DEVLIST</code> (Ethernet, USB Ethernet, RNDIS tethering), selects one with <code>SYS_NET_SELECT</code> and runs DHCP. Its WiFi section scans through <code>SYS_WIFI_SCAN</code>/<code>RESULTS</code>, asks for a WPA2 passphrase when needed and starts the <code>wifi</code> helper through a <code>/share/netmenu.wifi</code> request, because the 64-byte <code>SYS_SPAWN</code> argument cannot hold a long SSID plus passphrase. On success the helper saves the SSID/passphrase to <code>/data/WIFI.CFG</code>; the next boot's <code>wifi autoconnect</code> helper reconnects from it. Duplicate BSSIDs for one SSID are collapsed to the strongest entry (or the active one), and hidden networks are omitted.</li>
+			<li><strong>netmenu</strong> — network menu opened by the top-bar status icon. Lists the present NICs from <code>SYS_NET_DEVLIST</code> (Ethernet, USB Ethernet, RNDIS tethering), selects one with <code>SYS_NET_SELECT</code> and runs DHCP. Its WiFi section scans through <code>SYS_WIFI_SCAN</code>/<code>RESULTS</code>, asks for a WPA2 passphrase when the network is not saved and starts the <code>wifi</code> helper through a <code>/share/netmenu.wifi</code> request, because the 64-byte <code>SYS_SPAWN</code> argument cannot hold a long SSID plus passphrase. Networks in <code>/data/WIFI.CFG</code> are marked <em>saved</em> and join with the stored passphrase; a <em>Saved</em> view lists them with a <em>Forget</em> button each. On success the helper moves the SSID/passphrase to the front of the saved list; the next boot's <code>wifi autoconnect</code> helper joins any saved network found. Duplicate BSSIDs for one SSID are collapsed to the strongest entry (or the active one), and hidden networks are omitted.</li>
 			<li><strong>wm</strong> / <strong>term</strong> — the ring-3 window manager and terminal launcher used by the desktop.</li>
 			<li><strong>wm</strong> / <strong>term</strong> — the ring-3 window manager and terminal launcher used by the desktop.</li>
 		</ul>
 		</ul>
 		<p>
 		<p>
@@ -430,7 +430,7 @@
 			<li><code>browser.c</code>, <code>browser_html.c</code>, <code>svg_raster.c/h</code> (+ <code>svg_test.c</code>), <code>js_browser.c/h</code>, <code>js_mu.c/h</code>, <code>third_party/quickjs/</code>, <code>gallery.c</code></li>
 			<li><code>browser.c</code>, <code>browser_html.c</code>, <code>svg_raster.c/h</code> (+ <code>svg_test.c</code>), <code>js_browser.c/h</code>, <code>js_mu.c/h</code>, <code>third_party/quickjs/</code>, <code>gallery.c</code></li>
 			<li><code>ucmd_chat.c</code>, <code>chat_login.c</code>, <code>ujson.c</code>, <code>uhttp_cookie.c</code> — chat client</li>
 			<li><code>ucmd_chat.c</code>, <code>chat_login.c</code>, <code>ujson.c</code>, <code>uhttp_cookie.c</code> — chat client</li>
 			<li><code>ucmd_wifi.c</code>, <code>wpa.c</code>, <code>wpa_crypto.c</code> — <code>wifi</code> command and the WPA2-PSK supplicant</li>
 			<li><code>ucmd_wifi.c</code>, <code>wpa.c</code>, <code>wpa_crypto.c</code> — <code>wifi</code> command and the WPA2-PSK supplicant</li>
-			<li><code>ucmd_netmenu.c</code>, <code>wifi_cfg.h</code> — top-bar network menu and its staged WiFi connect record</li>
+			<li><code>ucmd_netmenu.c</code>, <code>wifi_cfg.h</code>, <code>wifi_store.c/h</code> — top-bar network menu, staged WiFi connect record and saved-network list</li>
 		</ul>
 		</ul>
 	</section>
 	</section>
 </main>
 </main>

+ 4 - 3
kernel.c

@@ -368,9 +368,10 @@ static int net_restore_boot_config(void)
 	return dns[0] || dns[1] || dns[2] || dns[3];
 	return dns[0] || dns[1] || dns[2] || dns[3];
 }
 }
 
 
-/* Saved WiFi credentials on the writable /data volume: let the normal
- * supplicant reconnect in the background.  It leaves a wired link that is
- * physically up alone, and a missing /data or wifi helper is harmless. */
+/* Saved WiFi networks on the writable /data volume: let the normal
+ * supplicant scan and join any known network in the background.  It leaves a
+ * wired link that is physically up alone, and a missing /data or wifi helper
+ * is harmless. */
 static void boot_wifi_autoconnect(void)
 static void boot_wifi_autoconnect(void)
 {
 {
 	unsigned int sz = 0;
 	unsigned int sz = 0;

+ 153 - 5
ucmd_netmenu.c

@@ -3,9 +3,11 @@
  * Lists the NICs the kernel reports as present (Ethernet, USB Ethernet,
  * Lists the NICs the kernel reports as present (Ethernet, USB Ethernet,
  * RNDIS tethering) and the WiFi networks from a scan.  Selecting a wired or
  * RNDIS tethering) and the WiFi networks from a scan.  Selecting a wired or
  * USB device makes it the active netdev and runs DHCP; selecting a WiFi
  * USB device makes it the active netdev and runs DHCP; selecting a WiFi
- * network asks for the WPA2 passphrase when needed, then starts the existing
+ * network joins it with the passphrase saved in /data/WIFI.CFG when one is
+ * known, otherwise it asks for the WPA2 passphrase, then starts the existing
  * `wifi` supplicant with a staged /share/netmenu.wifi request (the SYS_SPAWN
  * `wifi` supplicant with a staged /share/netmenu.wifi request (the SYS_SPAWN
- * argument limit is too small for an SSID plus a long passphrase).  The
+ * argument limit is too small for an SSID plus a long passphrase).  A Saved
+ * view lists the known networks and forgets individual entries.  The
  * supplicant itself runs DHCP once the data port opens.
  * supplicant itself runs DHCP once the data port opens.
  *
  *
  * A small ngui canvas window; the WM places it under the network icon and
  * A small ngui canvas window; the WM places it under the network icon and
@@ -13,7 +15,7 @@
 
 
 #include "ucmd_lib.h"
 #include "ucmd_lib.h"
 #include "ngui.h"
 #include "ngui.h"
-#include "wifi_cfg.h"
+#include "wifi_store.h"
 
 
 #define MAX_DEVS 8
 #define MAX_DEVS 8
 #define MAX_BSS  32
 #define MAX_BSS  32
@@ -27,25 +29,33 @@
 #define ID_PASS_CANCEL   5
 #define ID_PASS_CANCEL   5
 #define ID_CONN_CANCEL   6
 #define ID_CONN_CANCEL   6
 #define ID_PASS          7
 #define ID_PASS          7
+#define ID_SAVED         8
+#define ID_SAVED_BACK    9
 #define ID_DEV_BASE      100
 #define ID_DEV_BASE      100
 #define ID_BSS_BASE      200
 #define ID_BSS_BASE      200
+#define ID_SAVED_BASE    300
 
 
 #define ACT_REFRESH    (1u << 0)
 #define ACT_REFRESH    (1u << 0)
 #define ACT_SCAN       (1u << 1)
 #define ACT_SCAN       (1u << 1)
 #define ACT_DISCONNECT (1u << 2)
 #define ACT_DISCONNECT (1u << 2)
 #define ACT_BACK       (1u << 3)
 #define ACT_BACK       (1u << 3)
 #define ACT_CONNECT    (1u << 4)
 #define ACT_CONNECT    (1u << 4)
+#define ACT_SAVED      (1u << 5)
+#define ACT_FORGET     (1u << 6)
 
 
-enum { VIEW_MAIN, VIEW_PASS, VIEW_CONNECT };
+enum { VIEW_MAIN, VIEW_PASS, VIEW_CONNECT, VIEW_SAVED };
 
 
 static struct ngui ui;
 static struct ngui ui;
 static struct ngui_input pass_in;
 static struct ngui_input pass_in;
 static struct ngui_scroll wifi_scroll;
 static struct ngui_scroll wifi_scroll;
+static struct ngui_scroll saved_scroll;
 
 
 static struct sys_netdev devs[MAX_DEVS];
 static struct sys_netdev devs[MAX_DEVS];
 static int ndev;
 static int ndev;
 static struct sys_wifi_bss bss[MAX_BSS];
 static struct sys_wifi_bss bss[MAX_BSS];
 static int nbss;
 static int nbss;
+static struct wifi_cfg saved[WIFI_CFG_MAX];
+static int nsaved;
 static struct sys_wifi_status wst;
 static struct sys_wifi_status wst;
 static struct sys_netinfo net;
 static struct sys_netinfo net;
 static int net_present;
 static int net_present;
@@ -71,6 +81,7 @@ static unsigned int status_until;
 static unsigned int actions;
 static unsigned int actions;
 static int action_dev = -1;
 static int action_dev = -1;
 static int action_bss = -1;
 static int action_bss = -1;
+static int action_saved = -1;
 
 
 static void draw(void);
 static void draw(void);
 static void paint_frame(void);
 static void paint_frame(void);
@@ -155,6 +166,29 @@ static void ssid_name(const struct sys_wifi_bss *b, char out[33])
 	}
 	}
 }
 }
 
 
+static void cfg_ssid_name(const struct wifi_cfg *c, char out[33])
+{
+	unsigned int i, n = c->ssid_len;
+
+	if (n > 32)
+		n = 32;
+	for (i = 0; i < n; i++)
+		out[i] = (char)c->ssid[i];
+	out[n] = '\0';
+}
+
+static void load_saved(void)
+{
+	int n = wifi_store_load(saved, WIFI_CFG_MAX);
+
+	nsaved = n > 0 ? n : 0;
+}
+
+static int bss_saved(const struct sys_wifi_bss *b)
+{
+	return wifi_store_find(saved, nsaved, b->ssid, b->ssid_len);
+}
+
 static const char *security_name(unsigned int s)
 static const char *security_name(unsigned int s)
 {
 {
 	return s == SYS_WIFI_SEC_OPEN ? "open" :
 	return s == SYS_WIFI_SEC_OPEN ? "open" :
@@ -457,6 +491,7 @@ static void poll_connect(void)
 	if (!u_alive((unsigned int)connect_pid)) {
 	if (!u_alive((unsigned int)connect_pid)) {
 		connect_pid = -1;
 		connect_pid = -1;
 		load_status();
 		load_status();
+		load_saved();
 		if (wst.state >= SYS_WIFI_ST_LINK) {
 		if (wst.state >= SYS_WIFI_ST_LINK) {
 			int have_ip = 0;
 			int have_ip = 0;
 
 
@@ -529,6 +564,20 @@ static void select_bss(int i)
 		return;
 		return;
 	}
 	}
 	if (bss[i].security == SYS_WIFI_SEC_PSK) {
 	if (bss[i].security == SYS_WIFI_SEC_PSK) {
+		int si = bss_saved(&bss[i]);
+
+		if (si >= 0 && saved[si].pass_len > 0) {
+			char pass[65];
+			unsigned int j;
+
+			for (j = 0; j < saved[si].pass_len; j++)
+				pass[j] = saved[si].pass[j];
+			pass[saved[si].pass_len] = '\0';
+			start_connect(pass);
+			for (j = 0; j < sizeof(pass); j++)
+				((volatile char *)pass)[j] = 0;
+			return;
+		}
 		ngui_input_set(&pass_in, "");
 		ngui_input_set(&pass_in, "");
 		pass_in.secret = 1;
 		pass_in.secret = 1;
 		pass_in.placeholder = "WPA2 passphrase";
 		pass_in.placeholder = "WPA2 passphrase";
@@ -544,11 +593,12 @@ static void select_bss(int i)
 static void handle_actions(void)
 static void handle_actions(void)
 {
 {
 	unsigned int a = actions;
 	unsigned int a = actions;
-	int di = action_dev, bi = action_bss;
+	int di = action_dev, bi = action_bss, fi = action_saved;
 
 
 	actions = 0;
 	actions = 0;
 	action_dev = -1;
 	action_dev = -1;
 	action_bss = -1;
 	action_bss = -1;
+	action_saved = -1;
 
 
 	if (a & ACT_BACK) {
 	if (a & ACT_BACK) {
 		if (view == VIEW_CONNECT)
 		if (view == VIEW_CONNECT)
@@ -559,6 +609,28 @@ static void handle_actions(void)
 		}
 		}
 		return;
 		return;
 	}
 	}
+	if (a & ACT_SAVED) {
+		load_saved();
+		saved_scroll.offset = 0;
+		view = VIEW_SAVED;
+		set_status("", 0);
+		ngui_invalidate(&ui);
+		return;
+	}
+	if (a & ACT_FORGET) {
+		if (fi >= 0 && fi < nsaved) {
+			if (wifi_store_forget(saved[fi].ssid,
+					      saved[fi].ssid_len) > 0) {
+				load_saved();
+				saved_scroll.offset = 0;
+				set_status("Saved network removed", 0);
+			} else {
+				set_status("Could not remove the saved network", 1);
+			}
+		}
+		ngui_invalidate(&ui);
+		return;
+	}
 	if (a & ACT_CONNECT) {
 	if (a & ACT_CONNECT) {
 		char pass[65];
 		char pass[65];
 		unsigned int i, n;
 		unsigned int i, n;
@@ -683,6 +755,8 @@ static void draw_wifi_list(struct ngui_rect area)
 		ssid_name(b, ssid);
 		ssid_name(b, ssid);
 		sput(label, ssid);
 		sput(label, ssid);
 		sput(shortcut, security_name(b->security));
 		sput(shortcut, security_name(b->security));
+		if (bss_saved(b) >= 0)
+			sput(shortcut + slen(shortcut), " saved");
 		clicked = ngui_menu_item_utf8(&ui, ID_BSS_BASE + i, rr, label,
 		clicked = ngui_menu_item_utf8(&ui, ID_BSS_BASE + i, rr, label,
 					 shortcut, bss_is_active(b));
 					 shortcut, bss_is_active(b));
 
 
@@ -797,6 +871,14 @@ static void draw_main(void)
 	rb.x = r.x + r.w - 96;
 	rb.x = r.x + r.w - 96;
 	rb.w = 96;
 	rb.w = 96;
 	rb.h = 22;
 	rb.h = 22;
+	if (nsaved > 0) {
+		struct ngui_rect sb = rb;
+
+		sb.x = rb.x - 68;
+		sb.w = 64;
+		if (ngui_button(&ui, ID_SAVED, sb, "Saved"))
+			actions |= ACT_SAVED;
+	}
 	if (wifi_present) {
 	if (wifi_present) {
 		if (wst.state >= SYS_WIFI_ST_ASSOC) {
 		if (wst.state >= SYS_WIFI_ST_ASSOC) {
 			if (ngui_button(&ui, ID_DISCONNECT, rb, "Disconnect"))
 			if (ngui_button(&ui, ID_DISCONNECT, rb, "Disconnect"))
@@ -924,6 +1006,65 @@ static void draw_connect(void)
 		actions |= ACT_BACK;
 		actions |= ACT_BACK;
 }
 }
 
 
+static void draw_saved(void)
+{
+	struct ngui_rect body = { 10, 10, ui.w - 20, ui.h - 40 };
+	struct ngui_rect r, b, row, bt;
+	char line[96], *p;
+	int i;
+
+	r = ngui_cut_top(&body, 24);
+	ngui_text(&ui, r.x, r.y, "Saved WiFi networks", ui.theme.text);
+	body.y += 4;
+	body.h -= 4;
+	body.h -= 34;                 /* room for the Back button */
+
+	if (!nsaved) {
+		ngui_text(&ui, body.x + 2, body.y + 4,
+			  "No saved networks", ui.theme.text_dim);
+	} else {
+		saved_scroll.content_h = nsaved * 28;
+		ngui_scroll_begin(&ui, body, &saved_scroll);
+		ngui_scroll_wheel(&ui, body, &saved_scroll);
+		ngui_scroll_keys(&ui, &saved_scroll);
+		for (i = 0; i < nsaved; i++) {
+			char ssid[33];
+
+			row.x = body.x;
+			row.y = body.y - saved_scroll.offset + i * 28;
+			row.w = body.w - 16;
+			row.h = 26;
+			if (row.y + row.h <= body.y ||
+			    row.y >= body.y + body.h)
+				continue;
+			cfg_ssid_name(&saved[i], ssid);
+			bt = row;
+			bt.x = row.x + row.w - 64;
+			bt.w = 60;
+			bt.h = 22;
+			row.w -= 70;
+			p = sput(line, ssid);
+			p = sput(p, saved[i].pass_len ? "   WPA2" : "   open");
+			*p = '\0';
+			ngui_text_ellipsis_utf8(&ui, row, row.x, row.y + 3,
+						line, ui.theme.text);
+			if (ngui_button(&ui, ID_SAVED_BASE + i, bt,
+					"Forget")) {
+				action_saved = i;
+				actions |= ACT_FORGET;
+			}
+		}
+		ngui_scroll_end(&ui, body, &saved_scroll);
+	}
+
+	b.x = body.x;
+	b.y = body.y + body.h + 6;
+	b.w = 100;
+	b.h = 24;
+	if (ngui_button(&ui, ID_SAVED_BACK, b, "Back"))
+		actions |= ACT_BACK;
+}
+
 static void draw(void)
 static void draw(void)
 {
 {
 	ngui_fill_rect(&ui, (struct ngui_rect){ 0, 0, ui.w, ui.h },
 	ngui_fill_rect(&ui, (struct ngui_rect){ 0, 0, ui.w, ui.h },
@@ -932,6 +1073,8 @@ static void draw(void)
 		draw_pass();
 		draw_pass();
 	else if (view == VIEW_CONNECT)
 	else if (view == VIEW_CONNECT)
 		draw_connect();
 		draw_connect();
+	else if (view == VIEW_SAVED)
+		draw_saved();
 	else
 	else
 		draw_main();
 		draw_main();
 	if (view != VIEW_PASS && view != VIEW_CONNECT)
 	if (view != VIEW_PASS && view != VIEW_CONNECT)
@@ -947,6 +1090,7 @@ static void paint_frame(void)
 	actions = 0;
 	actions = 0;
 	action_dev = -1;
 	action_dev = -1;
 	action_bss = -1;
 	action_bss = -1;
+	action_saved = -1;
 }
 }
 
 
 void _start(const char *arg)
 void _start(const char *arg)
@@ -968,6 +1112,7 @@ void _start(const char *arg)
 
 
 	load_devices();
 	load_devices();
 	load_status();
 	load_status();
+	load_saved();
 	if (wifi_present && wst.state != SYS_WIFI_ST_DOWN &&
 	if (wifi_present && wst.state != SYS_WIFI_ST_DOWN &&
 	    wst.state < SYS_WIFI_ST_ASSOC) {
 	    wst.state < SYS_WIFI_ST_ASSOC) {
 		start_scan();
 		start_scan();
@@ -1005,6 +1150,9 @@ void _start(const char *arg)
 				set_status("", 0);
 				set_status("", 0);
 			} else if (view == VIEW_CONNECT) {
 			} else if (view == VIEW_CONNECT) {
 				cancel_connect();
 				cancel_connect();
+			} else if (view == VIEW_SAVED) {
+				view = VIEW_MAIN;
+				set_status("", 0);
 			} else if (ui.focus == 0) {
 			} else if (ui.focus == 0) {
 				break;
 				break;
 			}
 			}

+ 195 - 160
ucmd_wifi.c

@@ -10,17 +10,21 @@
  *   wifi connectfile <path>      join using an SSID/passphrase/BSSID record
  *   wifi connectfile <path>      join using an SSID/passphrase/BSSID record
  *                                staged by the network menu (SYS_SPAWN's
  *                                staged by the network menu (SYS_SPAWN's
  *                                argument buffer is only 64 bytes)
  *                                argument buffer is only 64 bytes)
- *   wifi autoconnect            reconnect from /data/WIFI.CFG (boot helper)
- *   wifi forget                 remove the saved credentials
+ *   wifi saved                  list the networks saved in /data/WIFI.CFG
+ *   wifi autoconnect            join any saved network found (boot helper)
+ *   wifi forget [ssid]          remove one saved network, or all without an
+ *                                argument
  *   wifi disconnect
  *   wifi disconnect
  *
  *
- * The WPA2 handshake (wpa.c) runs here; a small background copy of this
- * command (`wifi __keep <state>`) stays alive after `connect` to answer
- * group-key rekeys, and exits when the connection changes. */
+ * A successful connect adds the SSID/passphrase to a most-recently-used list
+ * (up to WIFI_CFG_MAX networks) in /data/WIFI.CFG.  The WPA2 handshake (wpa.c)
+ * runs here; a small background copy of this command (`wifi __keep <state>`)
+ * stays alive after `connect` to answer group-key rekeys, and exits when the
+ * connection changes. */
 
 
 #include "ucmd_lib.h"
 #include "ucmd_lib.h"
 #include "tls_rng.h"
 #include "tls_rng.h"
-#include "wifi_cfg.h"
+#include "wifi_store.h"
 #include "wpa.h"
 #include "wpa.h"
 
 
 #define MAX_BSS 32
 #define MAX_BSS 32
@@ -43,34 +47,15 @@ static int name_eq(const char *a, const char *b)
 	return *a == *b;
 	return *a == *b;
 }
 }
 
 
-static int bssid_zero(const unsigned char b[6])
+/* Add the network to /data/WIFI.CFG, replacing an older record for the same
+ * SSID and moving it to the front (most recently used).  The BSSID is
+ * deliberately left zero so a mesh/repeater AP with the same SSID still
+ * works; /data is a plain FAT partition, so the file is 8.3 and the
+ * passphrase is stored in clear. */
+static int remember_wifi(const unsigned char *ssid, unsigned int ssid_len,
+			 const char *pass, unsigned int pass_len)
 {
 {
-	unsigned int i;
-
-	for (i = 0; i < 6; i++)
-		if (b[i])
-			return 0;
-	return 1;
-}
-
-static void wipe_cfg(struct wifi_cfg *cfg)
-{
-	unsigned int i;
-
-	for (i = 0; i < sizeof(*cfg); i++)
-		((volatile unsigned char *)cfg)[i] = 0;
-}
-
-/* Save the network for the next boot.  The BSSID is deliberately left zero
- * so a mesh/repeater AP with the same SSID still works; /data is a plain FAT
- * partition, so WIFI.CFG is 8.3 and the password is stored in clear. */
-static int save_wifi_cred(const unsigned char *ssid, unsigned int ssid_len,
-			  const char *pass, unsigned int pass_len)
-{
-	/* FAT writes may read a final partial sector past the source length;
-	 * keep slack after the record as well. */
-	unsigned char buf[sizeof(struct wifi_cfg) + 512];
-	struct wifi_cfg *cfg = (struct wifi_cfg *)buf;
+	struct wifi_cfg rec;
 	unsigned int i;
 	unsigned int i;
 	int r;
 	int r;
 
 
@@ -78,51 +63,21 @@ static int save_wifi_cred(const unsigned char *ssid, unsigned int ssid_len,
 		ssid_len = 32;
 		ssid_len = 32;
 	if (pass_len > 64)
 	if (pass_len > 64)
 		pass_len = 64;
 		pass_len = 64;
-	for (i = 0; i < sizeof(buf); i++)
-		buf[i] = 0;
-	cfg->magic = WIFI_CFG_MAGIC;
-	cfg->ssid_len = (unsigned char)ssid_len;
-	cfg->pass_len = (unsigned char)pass_len;
+	for (i = 0; i < sizeof(rec); i++)
+		((unsigned char *)&rec)[i] = 0;
+	rec.magic = WIFI_CFG_MAGIC;
+	rec.ssid_len = (unsigned char)ssid_len;
+	rec.pass_len = (unsigned char)pass_len;
 	for (i = 0; i < ssid_len; i++)
 	for (i = 0; i < ssid_len; i++)
-		cfg->ssid[i] = ssid[i];
+		rec.ssid[i] = ssid[i];
 	for (i = 0; i < pass_len; i++)
 	for (i = 0; i < pass_len; i++)
-		cfg->pass[i] = pass[i];
-	r = u_syscall3(SYS_WRITE_FILE, (int)WIFI_CRED_PATH,
-		       (int)cfg, (int)sizeof(*cfg));
-	for (i = 0; i < sizeof(buf); i++)
-		buf[i] = 0;
+		rec.pass[i] = pass[i];
+	r = wifi_store_remember(&rec);
+	for (i = 0; i < sizeof(rec); i++)
+		((volatile unsigned char *)&rec)[i] = 0;
 	return r;
 	return r;
 }
 }
 
 
-static int load_wifi_cred(struct wifi_cfg *cfg)
-{
-	/* FAT reads can write a final partial sector past the requested
-	 * length; keep 512 bytes of slack so the stack top is never touched. */
-	unsigned char buf[sizeof(struct wifi_cfg) + 512];
-	unsigned int i;
-	int r;
-
-	wipe_cfg(cfg);
-	r = u_syscall3(SYS_READ_FILE, (int)WIFI_CRED_PATH,
-		       (int)buf, (int)sizeof(*cfg));
-	if (r < (int)sizeof(*cfg) || ((struct wifi_cfg *)buf)->magic !=
-	    WIFI_CFG_MAGIC) {
-		for (i = 0; i < sizeof(buf); i++)
-			buf[i] = 0;
-		return -1;
-	}
-	for (i = 0; i < sizeof(*cfg); i++)
-		((unsigned char *)cfg)[i] = buf[i];
-	for (i = 0; i < sizeof(buf); i++)
-		buf[i] = 0;
-	if (cfg->ssid_len == 0 || cfg->ssid_len > 32 ||
-	    cfg->pass_len > 64) {
-		wipe_cfg(cfg);
-		return -1;
-	}
-	return 0;
-}
-
 static void put_ssid(const unsigned char *s, unsigned int n)
 static void put_ssid(const unsigned char *s, unsigned int n)
 {
 {
 	unsigned int i;
 	unsigned int i;
@@ -441,50 +396,19 @@ static void spawn_keeper(struct wpa_sm *sm, unsigned int conn_id)
 		       "drop at the next group rekey\n");
 		       "drop at the next group rekey\n");
 }
 }
 
 
-static int connect_bss(const char *ssid, const char *pass,
-		       const unsigned char *want_bssid)
+/* Join one BSS from a completed scan.  `pass` is empty for an open network.
+ * Returns 0 when the data port is open, 1 on failure. */
+static int join_bss(const struct sys_wifi_bss *b, const char *pass)
 {
 {
 	struct sys_wifi_connect c;
 	struct sys_wifi_connect c;
 	struct sys_wifi_status st;
 	struct sys_wifi_status st;
 	static struct wpa_sm sm;
 	static struct wpa_sm sm;
 	unsigned char pmk[32];
 	unsigned char pmk[32];
-	struct sys_wifi_bss *b = 0;
-	int n, i, r;
-	unsigned int ssid_len;
-	int have_bssid = want_bssid != 0;
-
-	ssid_len = (unsigned int)slen(ssid);
-	if (!ssid_len) {
-		u_puts("usage: wifi connect <ssid> [passphrase]\n");
-		return 1;
-	}
-	if (bring_up() < 0)
-		return 1;
-	wifi(SYS_WIFI_DISCONNECT, 0, 0);
-	u_puts("wifi: scanning for \""); u_puts(ssid); u_puts("\"...\n");
-	n = do_scan();
-	if (n < 0)
-		return 1;
-	for (i = 0; i < n; i++) {
-		unsigned int j;
+	unsigned int ssid_len = b->ssid_len;
+	int i, r;
 
 
-		if (bss[i].ssid_len != ssid_len)
-			continue;
-		if (have_bssid) {
-			for (j = 0; j < 6 && bss[i].bssid[j] == want_bssid[j]; j++)
-				;
-			if (j != 6)
-				continue;
-		}
-		for (j = 0; j < ssid_len && bss[i].ssid[j] == (unsigned char)ssid[j]; j++)
-			;
-		if (j == ssid_len) {
-			b = &bss[i];       /* sorted: first match is strongest */
-			break;
-		}
-	}
-	if (!b) {
-		u_puts("wifi: network not found\n");
+	if (ssid_len == 0 || ssid_len > 32) {
+		u_puts("wifi: malformed SSID in scan result\n");
 		return 1;
 		return 1;
 	}
 	}
 	if (b->security == SYS_WIFI_SEC_OTHER) {
 	if (b->security == SYS_WIFI_SEC_OTHER) {
@@ -500,9 +424,9 @@ static int connect_bss(const char *ssid, const char *pass,
 	for (i = 0; i < 6; i++)
 	for (i = 0; i < 6; i++)
 		c.bssid[i] = b->bssid[i];
 		c.bssid[i] = b->bssid[i];
 	c.channel = b->channel;
 	c.channel = b->channel;
-	c.ssid_len = ssid_len;
+	c.ssid_len = (unsigned char)ssid_len;
 	for (i = 0; i < (int)ssid_len; i++)
 	for (i = 0; i < (int)ssid_len; i++)
-		c.ssid[i] = (unsigned char)ssid[i];
+		c.ssid[i] = b->ssid[i];
 	c.beacon_int = b->beacon_int;
 	c.beacon_int = b->beacon_int;
 	c.dtim = b->dtim;
 	c.dtim = b->dtim;
 	if (b->security == SYS_WIFI_SEC_PSK) {
 	if (b->security == SYS_WIFI_SEC_PSK) {
@@ -549,6 +473,51 @@ static int connect_bss(const char *ssid, const char *pass,
 	return r == 0 ? 0 : 1;
 	return r == 0 ? 0 : 1;
 }
 }
 
 
+static int connect_bss(const char *ssid, const char *pass,
+		       const unsigned char *want_bssid)
+{
+	struct sys_wifi_bss *b = 0;
+	int n, i;
+	unsigned int ssid_len;
+	int have_bssid = want_bssid != 0;
+
+	ssid_len = (unsigned int)slen(ssid);
+	if (!ssid_len) {
+		u_puts("usage: wifi connect <ssid> [passphrase]\n");
+		return 1;
+	}
+	if (bring_up() < 0)
+		return 1;
+	wifi(SYS_WIFI_DISCONNECT, 0, 0);
+	u_puts("wifi: scanning for \""); u_puts(ssid); u_puts("\"...\n");
+	n = do_scan();
+	if (n < 0)
+		return 1;
+	for (i = 0; i < n; i++) {
+		unsigned int j;
+
+		if (bss[i].ssid_len != ssid_len)
+			continue;
+		if (have_bssid) {
+			for (j = 0; j < 6 && bss[i].bssid[j] == want_bssid[j]; j++)
+				;
+			if (j != 6)
+				continue;
+		}
+		for (j = 0; j < ssid_len && bss[i].ssid[j] == (unsigned char)ssid[j]; j++)
+			;
+		if (j == ssid_len) {
+			b = &bss[i];       /* sorted: first match is strongest */
+			break;
+		}
+	}
+	if (!b) {
+		u_puts("wifi: network not found\n");
+		return 1;
+	}
+	return join_bss(b, pass);
+}
+
 static int cmd_connect(const char *args)
 static int cmd_connect(const char *args)
 {
 {
 	char ssid[33], pass[80], bssid_s[13];
 	char ssid[33], pass[80], bssid_s[13];
@@ -569,9 +538,9 @@ static int cmd_connect(const char *args)
 	}
 	}
 	r = connect_bss(ssid, pass, have_bssid ? want_bssid : 0);
 	r = connect_bss(ssid, pass, have_bssid ? want_bssid : 0);
 	if (r == 0) {
 	if (r == 0) {
-		if (save_wifi_cred((const unsigned char *)ssid,
-				   (unsigned int)slen(ssid), pass,
-				   (unsigned int)slen(pass)) == 0)
+		if (remember_wifi((const unsigned char *)ssid,
+				  (unsigned int)slen(ssid), pass,
+				  (unsigned int)slen(pass)) == 0)
 			u_puts("wifi: saved for auto-connect\n");
 			u_puts("wifi: saved for auto-connect\n");
 		else
 		else
 			u_puts("wifi: note: could not save credentials to /data\n");
 			u_puts("wifi: note: could not save credentials to /data\n");
@@ -611,8 +580,8 @@ static int cmd_connect_file(const char *args)
 	pass[cfg.pass_len] = '\0';
 	pass[cfg.pass_len] = '\0';
 	r = connect_bss(ssid, pass, cfg.bssid);
 	r = connect_bss(ssid, pass, cfg.bssid);
 	if (r == 0) {
 	if (r == 0) {
-		if (save_wifi_cred(cfg.ssid, cfg.ssid_len, cfg.pass,
-				   cfg.pass_len) == 0)
+		if (remember_wifi(cfg.ssid, cfg.ssid_len, cfg.pass,
+				  cfg.pass_len) == 0)
 			u_puts("wifi: saved for auto-connect\n");
 			u_puts("wifi: saved for auto-connect\n");
 		else
 		else
 			u_puts("wifi: note: credentials not saved (no writable /data)\n");
 			u_puts("wifi: note: credentials not saved (no writable /data)\n");
@@ -624,66 +593,130 @@ static int cmd_connect_file(const char *args)
 	return r;
 	return r;
 }
 }
 
 
-/* Boot-time helper: reconnect to the network saved in /data/WIFI.CFG.  A
- * wired link that is physically up wins; an existing WiFi link is left
- * alone. */
+/* Boot-time helper: scan once, then join the strongest network present whose
+ * SSID is in /data/WIFI.CFG.  If none succeeds, scan again after three
+ * seconds.  A wired link that is physically up wins; an existing WiFi link
+ * is left alone. */
 static int cmd_autoconnect(void)
 static int cmd_autoconnect(void)
 {
 {
-	struct wifi_cfg cfg;
+	struct wifi_cfg nets[WIFI_CFG_MAX];
 	struct sys_wifi_status ws;
 	struct sys_wifi_status ws;
 	struct sys_netinfo ni;
 	struct sys_netinfo ni;
-	char ssid[33], pass[65];
-	unsigned int i;
-	int attempt, r = 1;
+	char pass[65];
+	int count, n, i, round, r = 1;
 
 
-	if (load_wifi_cred(&cfg) != 0)
+	count = wifi_store_load(nets, WIFI_CFG_MAX);
+	if (count <= 0)
 		return 0;
 		return 0;
 	/* A wired link that is physically up wins: do not even probe the WiFi
 	/* A wired link that is physically up wins: do not even probe the WiFi
 	 * card in that case.  Only fall back to WiFi when no cable is
 	 * card in that case.  Only fall back to WiFi when no cable is
 	 * connected. */
 	 * connected. */
 	if (u_net_info(&ni) == 1 && ni.present && ni.link &&
 	if (u_net_info(&ni) == 1 && ni.present && ni.link &&
-	    !name_eq(ni.name, "wifi")) {
-		wipe_cfg(&cfg);
-		return 0;
-	}
-	if (u_wifi(SYS_WIFI_STATUS, (int)&ws, 0) != 0 || !ws.present) {
-		wipe_cfg(&cfg);
-		return 0;
-	}
-	if (ws.state >= SYS_WIFI_ST_LINK) {
-		wipe_cfg(&cfg);
-		return 0;
-	}
-	for (i = 0; i < cfg.ssid_len; i++)
-		ssid[i] = (char)cfg.ssid[i];
-	ssid[cfg.ssid_len] = '\0';
-	for (i = 0; i < cfg.pass_len; i++)
-		pass[i] = cfg.pass[i];
-	pass[cfg.pass_len] = '\0';
-	for (attempt = 0; attempt < 2; attempt++) {
-		r = connect_bss(ssid, pass,
-				bssid_zero(cfg.bssid) ? 0 : cfg.bssid);
-		if (r == 0)
-			break;
-		if (attempt == 0)
+	    !name_eq(ni.name, "wifi"))
+		goto out;
+	if (u_wifi(SYS_WIFI_STATUS, (int)&ws, 0) != 0 || !ws.present)
+		goto out;
+	if (ws.state >= SYS_WIFI_ST_LINK)
+		goto out;
+	if (bring_up() < 0)
+		goto out;
+	for (round = 0; round < 2 && r; round++) {
+		unsigned char tried[WIFI_CFG_MAX];
+		unsigned int j;
+
+		if (round)
 			u_sleep_ms(3000);
 			u_sleep_ms(3000);
+		for (j = 0; j < WIFI_CFG_MAX; j++)
+			tried[j] = 0;
+		wifi(SYS_WIFI_DISCONNECT, 0, 0);
+		n = do_scan();
+		if (n < 0)
+			continue;
+		for (i = 0; i < n && r; i++) {
+			struct sys_wifi_bss *b = &bss[i];
+			int ci;
+
+			if (b->security == SYS_WIFI_SEC_OTHER)
+				continue;
+			ci = wifi_store_find(nets, count, b->ssid,
+					     b->ssid_len);
+			if (ci < 0 || tried[ci])
+				continue;
+			if (b->security == SYS_WIFI_SEC_PSK &&
+			    nets[ci].pass_len == 0)
+				continue;
+			tried[ci] = 1;
+			for (j = 0; j < nets[ci].pass_len; j++)
+				pass[j] = nets[ci].pass[j];
+			pass[nets[ci].pass_len] = '\0';
+			u_puts("wifi: auto-connect \"");
+			put_ssid(b->ssid, b->ssid_len);
+			u_puts("\"\n");
+			r = join_bss(b, pass);
+			for (j = 0; j < sizeof(pass); j++)
+				((volatile char *)pass)[j] = 0;
+			if (r != 0)
+				wifi(SYS_WIFI_DISCONNECT, 0, 0);
+		}
 	}
 	}
-	for (i = 0; i < sizeof(cfg); i++)
-		((unsigned char *)&cfg)[i] = 0;
-	for (i = 0; i < sizeof(pass); i++)
+out:
+	for (i = 0; i < (int)sizeof(nets); i++)
+		((volatile unsigned char *)nets)[i] = 0;
+	for (i = 0; i < (int)sizeof(pass); i++)
 		((volatile char *)pass)[i] = 0;
 		((volatile char *)pass)[i] = 0;
 	return r;
 	return r;
 }
 }
 
 
-static int cmd_forget(void)
+static int cmd_saved(void)
 {
 {
-	if (u_syscall1(SYS_UNLINK, (int)WIFI_CRED_PATH) == 0)
-		u_puts("wifi: saved credentials removed\n");
-	else
-		u_puts("wifi: no saved credentials\n");
+	struct wifi_cfg list[WIFI_CFG_MAX];
+	int n, i;
+	unsigned int j;
+
+	n = wifi_store_load(list, WIFI_CFG_MAX);
+	if (n <= 0) {
+		u_puts("wifi: no saved networks\n");
+		return 0;
+	}
+	u_puts("saved networks (");
+	u_putdec((unsigned int)n);
+	u_puts("):\n");
+	for (i = 0; i < n; i++) {
+		u_puts("  \"");
+		put_ssid(list[i].ssid, list[i].ssid_len);
+		u_puts("\"  ");
+		u_puts(list[i].pass_len ? "WPA2-PSK" : "open");
+		u_puts("\n");
+	}
+	for (j = 0; j < sizeof(list); j++)
+		((volatile unsigned char *)list)[j] = 0;
 	return 0;
 	return 0;
 }
 }
 
 
+static int cmd_forget(const char *args)
+{
+	char ssid[33];
+	int r;
+
+	args = word(args, ssid, sizeof(ssid));
+	if (!ssid[0]) {
+		if (u_syscall1(SYS_UNLINK, (int)WIFI_CRED_PATH) == 0)
+			u_puts("wifi: saved networks removed\n");
+		else
+			u_puts("wifi: no saved networks\n");
+		return 0;
+	}
+	r = wifi_store_forget((const unsigned char *)ssid,
+			      (unsigned int)slen(ssid));
+	if (r > 0)
+		u_puts("wifi: saved network removed\n");
+	else if (r == 0)
+		u_puts("wifi: network is not saved\n");
+	else
+		u_puts("wifi: could not update /data/WIFI.CFG\n");
+	return r < 0 ? 1 : 0;
+}
+
 /* Background: answer group-key rekeys until the connection changes. */
 /* Background: answer group-key rekeys until the connection changes. */
 static int keeper(const char *args)
 static int keeper(const char *args)
 {
 {
@@ -763,15 +796,17 @@ void _start(const char *arg)
 		r = cmd_connect(a + 8);
 		r = cmd_connect(a + 8);
 	else if (starts(a, "connectfile "))
 	else if (starts(a, "connectfile "))
 		r = cmd_connect_file(a + 12);
 		r = cmd_connect_file(a + 12);
+	else if (starts(a, "saved"))
+		r = cmd_saved();
 	else if (starts(a, "autoconnect"))
 	else if (starts(a, "autoconnect"))
 		r = cmd_autoconnect();
 		r = cmd_autoconnect();
 	else if (starts(a, "forget"))
 	else if (starts(a, "forget"))
-		r = cmd_forget();
+		r = cmd_forget(a + 6);
 	else if (starts(a, "disconnect")) {
 	else if (starts(a, "disconnect")) {
 		wifi(SYS_WIFI_DISCONNECT, 0, 0);
 		wifi(SYS_WIFI_DISCONNECT, 0, 0);
 		u_puts("wifi: disconnected\n");
 		u_puts("wifi: disconnected\n");
 	} else {
 	} else {
-		u_puts("usage: wifi [up|scan|connect <ssid> [pass] [bssid]|connectfile <path>|autoconnect|forget|disconnect]\n");
+		u_puts("usage: wifi [up|scan|connect <ssid> [pass] [bssid]|connectfile <path>|saved|autoconnect|forget [ssid]|disconnect]\n");
 		r = 1;
 		r = 1;
 	}
 	}
 	u_exit(r);
 	u_exit(r);

+ 24 - 7
wifi_cfg.h

@@ -1,16 +1,26 @@
-/* Staged WiFi connect request, written by the network menu and read by
- * `wifi connectfile <path>`.
+/* WiFi credential records: the staged connect request written by the network
+ * menu and read by `wifi connectfile <path>`, plus the saved-network list in
+ * /data/WIFI.CFG (see wifi_store.c).
  *
  *
  * The normal `wifi connect <ssid> <pass>` command arguments are limited by
  * The normal `wifi connect <ssid> <pass>` command arguments are limited by
  * SYS_SPAWN's VFS_PATH_MAX buffer (64 bytes), which is too small for a long
  * SYS_SPAWN's VFS_PATH_MAX buffer (64 bytes), which is too small for a long
- * SSID plus a 63-character WPA2 passphrase.  The menu therefore writes this
- * fixed-size record to a /share file and spawns a helper with a short path. */
+ * SSID plus a 63-character WPA2 passphrase.  The menu therefore writes the
+ * single fixed-size record to a /share file and spawns a helper with a short
+ * path.
+ *
+ * /data/WIFI.CFG is a header (`struct wifi_cfg_list`) followed by `count`
+ * `struct wifi_cfg` records, most recently connected first.  A file that
+ * starts directly with WIFI_CFG_MAGIC is the old one-record format and is
+ * accepted as a one-entry list. */
 #ifndef WIFI_CFG_H
 #ifndef WIFI_CFG_H
 #define WIFI_CFG_H
 #define WIFI_CFG_H
 
 
-#define WIFI_CFG_MAGIC 0x4E425746u   /* "NBWF" */
-#define WIFI_CFG_STAGED "/share/netmenu.wifi"
-#define WIFI_CRED_PATH  "/data/WIFI.CFG"
+#define WIFI_CFG_MAGIC      0x4E425746u   /* "NBWF": one network record */
+#define WIFI_CFG_LIST_MAGIC 0x4E42574Cu   /* "NBWL": saved-network list */
+#define WIFI_CFG_LIST_VER   1u
+#define WIFI_CFG_MAX        16            /* saved networks in /data/WIFI.CFG */
+#define WIFI_CFG_STAGED     "/share/netmenu.wifi"
+#define WIFI_CRED_PATH      "/data/WIFI.CFG"
 
 
 struct wifi_cfg {
 struct wifi_cfg {
 	unsigned int magic;
 	unsigned int magic;
@@ -21,4 +31,11 @@ struct wifi_cfg {
 	char pass[65];                   /* NUL terminated, pass_len used */
 	char pass[65];                   /* NUL terminated, pass_len used */
 };
 };
 
 
+struct wifi_cfg_list {
+	unsigned int magic;
+	unsigned int version;
+	unsigned int count;
+	struct wifi_cfg net[WIFI_CFG_MAX];
+};
+
 #endif
 #endif

+ 157 - 0
wifi_store.c

@@ -0,0 +1,157 @@
+/* Saved WiFi networks: a small fixed-capacity list in one 8.3 FAT file.
+ * Everything is read/written whole; the network menu and the boot helper
+ * both go through this module. */
+
+#include "ucmd_lib.h"
+#include "wifi_store.h"
+
+#define CFG_SLACK 512   /* FAT may write a final partial sector */
+
+static void wipe(void *p, unsigned int n)
+{
+	volatile unsigned char *b = (volatile unsigned char *)p;
+
+	while (n--)
+		*b++ = 0;
+}
+
+static int cfg_valid(const struct wifi_cfg *c)
+{
+	return c->magic == WIFI_CFG_MAGIC && c->ssid_len >= 1 &&
+	       c->ssid_len <= 32 && c->pass_len <= 64;
+}
+
+int wifi_store_find(const struct wifi_cfg *list, int count,
+		    const unsigned char *ssid, unsigned int ssid_len)
+{
+	int i;
+
+	if (!list || !ssid || ssid_len == 0 || ssid_len > 32)
+		return -1;
+	for (i = 0; i < count; i++) {
+		unsigned int j;
+
+		if (list[i].ssid_len != ssid_len)
+			continue;
+		for (j = 0; j < ssid_len; j++)
+			if (list[i].ssid[j] != ssid[j])
+				break;
+		if (j == ssid_len)
+			return i;
+	}
+	return -1;
+}
+
+int wifi_store_load(struct wifi_cfg *out, int max)
+{
+	union {
+		struct wifi_cfg_list list;
+		struct wifi_cfg one;
+		unsigned char raw[sizeof(struct wifi_cfg_list) + CFG_SLACK];
+	} buf;
+	int r, n = 0, i;
+
+	if (!out || max <= 0)
+		return 0;
+	r = u_syscall3(SYS_READ_FILE, (int)WIFI_CRED_PATH, (int)buf.raw,
+		       (int)sizeof(buf.raw));
+	if (r >= 4 && buf.list.magic == WIFI_CFG_LIST_MAGIC) {
+		int count;
+
+		if (r < 12 || buf.list.version != WIFI_CFG_LIST_VER)
+			goto done;
+		count = (int)buf.list.count;
+		if (count > WIFI_CFG_MAX)
+			count = WIFI_CFG_MAX;
+		if ((unsigned int)r < 12u +
+		    (unsigned int)count * sizeof(struct wifi_cfg))
+			count = (r - 12) / (int)sizeof(struct wifi_cfg);
+		for (i = 0; i < count && n < max; i++) {
+			const struct wifi_cfg *c = &buf.list.net[i];
+
+			if (!cfg_valid(c))
+				continue;
+			if (wifi_store_find(out, n, c->ssid, c->ssid_len) >= 0)
+				continue;
+			out[n++] = *c;
+		}
+	} else if (r >= (int)sizeof(struct wifi_cfg) && cfg_valid(&buf.one)) {
+		out[0] = buf.one;
+		n = 1;
+	}
+done:
+	wipe(buf.raw, sizeof(buf.raw));
+	return n;
+}
+
+int wifi_store_save(const struct wifi_cfg *list, int count)
+{
+	union {
+		struct wifi_cfg_list list;
+		unsigned char raw[sizeof(struct wifi_cfg_list) + CFG_SLACK];
+	} buf;
+	unsigned int len;
+	int i, r;
+
+	if (!list || count <= 0) {
+		u_syscall1(SYS_UNLINK, (int)WIFI_CRED_PATH);
+		return 0;
+	}
+	if (count > WIFI_CFG_MAX)
+		count = WIFI_CFG_MAX;
+	wipe(buf.raw, sizeof(buf.raw));
+	buf.list.magic = WIFI_CFG_LIST_MAGIC;
+	buf.list.version = WIFI_CFG_LIST_VER;
+	buf.list.count = (unsigned int)count;
+	for (i = 0; i < count; i++)
+		buf.list.net[i] = list[i];
+	len = 12u + (unsigned int)count * sizeof(struct wifi_cfg);
+	r = u_syscall3(SYS_WRITE_FILE, (int)WIFI_CRED_PATH, (int)buf.raw,
+		       (int)len);
+	wipe(buf.raw, sizeof(buf.raw));
+	return r == 0 ? 0 : -1;
+}
+
+int wifi_store_remember(const struct wifi_cfg *rec)
+{
+	struct wifi_cfg list[WIFI_CFG_MAX];
+	int n, i, idx, r;
+
+	if (!rec || !cfg_valid(rec))
+		return -1;
+	n = wifi_store_load(list, WIFI_CFG_MAX);
+	idx = wifi_store_find(list, n, rec->ssid, rec->ssid_len);
+	if (idx >= 0) {
+		for (i = idx; i + 1 < n; i++)
+			list[i] = list[i + 1];
+		n--;
+	}
+	if (n >= WIFI_CFG_MAX)
+		n = WIFI_CFG_MAX - 1;      /* drop the least recently used */
+	for (i = n; i > 0; i--)
+		list[i] = list[i - 1];
+	list[0] = *rec;
+	list[0].magic = WIFI_CFG_MAGIC;
+	r = wifi_store_save(list, n + 1);
+	wipe(list, sizeof(list));
+	return r;
+}
+
+int wifi_store_forget(const unsigned char *ssid, unsigned int ssid_len)
+{
+	struct wifi_cfg list[WIFI_CFG_MAX];
+	int n, i, idx, r;
+
+	n = wifi_store_load(list, WIFI_CFG_MAX);
+	idx = wifi_store_find(list, n, ssid, ssid_len);
+	if (idx < 0) {
+		wipe(list, sizeof(list));
+		return 0;
+	}
+	for (i = idx; i + 1 < n; i++)
+		list[i] = list[i + 1];
+	n--;
+	r = wifi_store_save(list, n) == 0 ? 1 : -1;
+	wipe(list, sizeof(list));
+	return r;
+}

+ 28 - 0
wifi_store.h

@@ -0,0 +1,28 @@
+/* Saved WiFi networks in /data/WIFI.CFG, shared by the `wifi` command and the
+ * network menu.  The file is a wifi_cfg_list header + record array; the old
+ * one-record format is still read.  See wifi_cfg.h for the layout. */
+#ifndef WIFI_STORE_H
+#define WIFI_STORE_H
+
+#include "wifi_cfg.h"
+
+/* Read the saved list into `out` (most recently used first), dropping
+ * malformed and duplicate records.  Returns 0..max, or 0 when the file is
+ * absent, empty or unreadable. */
+int wifi_store_load(struct wifi_cfg *out, int max);
+
+/* Rewrite the list.  An empty list removes the file.  -> 0 / -1 */
+int wifi_store_save(const struct wifi_cfg *list, int count);
+
+/* Move `rec` to the front (replacing a record with the same SSID, dropping
+ * the least recently used entry when the list is full) and write it. */
+int wifi_store_remember(const struct wifi_cfg *rec);
+
+/* Index of the record whose SSID matches, or -1. */
+int wifi_store_find(const struct wifi_cfg *list, int count,
+		    const unsigned char *ssid, unsigned int ssid_len);
+
+/* Remove one network: 1 removed, 0 not found, -1 write error. */
+int wifi_store_forget(const unsigned char *ssid, unsigned int ssid_len);
+
+#endif

+ 205 - 0
wifi_store_test.c

@@ -0,0 +1,205 @@
+/* Host test for the saved-WiFi list (wifi_store.c).  The syscall layer is
+ * replaced by a small in-memory FAT file, so the real load/save/remember/
+ * forget paths run unchanged. */
+
+#include <stdio.h>
+#include <string.h>
+
+#include "syscall.h"
+
+/* Skip the real ucmd_lib.h (its wrappers are inline `int 0x80` calls) and
+ * provide the two syscalls the store uses. */
+#define UCMD_LIB_H
+
+static unsigned char flash[8192];
+static unsigned int flash_len;
+static int flash_present;
+
+static int fake_syscall1(int num, int a1)
+{
+	(void)a1;
+	if (num == SYS_UNLINK) {
+		flash_present = 0;
+		flash_len = 0;
+		return 0;
+	}
+	return -1;
+}
+
+static int fake_syscall3(int num, int a1, int a2, int a3)
+{
+	(void)a1;
+	if (num == SYS_READ_FILE) {
+		unsigned int n;
+
+		if (!flash_present)
+			return -1;
+		n = flash_len < (unsigned int)a3 ? flash_len : (unsigned int)a3;
+		memcpy((void *)a2, flash, n);
+		return (int)n;
+	}
+	if (num == SYS_WRITE_FILE) {
+		if ((unsigned int)a3 > sizeof(flash))
+			return -1;
+		memcpy(flash, (const void *)a2, (unsigned int)a3);
+		flash_len = (unsigned int)a3;
+		flash_present = 1;
+		return 0;
+	}
+	return -1;
+}
+
+#define u_syscall1 fake_syscall1
+#define u_syscall3 fake_syscall3
+#include "wifi_store.c"
+
+static int failures;
+
+static void check(int ok, const char *what)
+{
+	if (!ok) {
+		printf("FAIL: %s\n", what);
+		failures++;
+	}
+}
+
+static struct wifi_cfg rec(const char *ssid, const char *pass, int extra)
+{
+	struct wifi_cfg c;
+	unsigned int i;
+
+	memset(&c, 0, sizeof(c));
+	c.magic = WIFI_CFG_MAGIC;
+	c.ssid_len = (unsigned char)strlen(ssid);
+	c.pass_len = (unsigned char)strlen(pass);
+	for (i = 0; i < c.ssid_len; i++)
+		c.ssid[i] = (unsigned char)ssid[i];
+	for (i = 0; i < c.pass_len; i++)
+		c.pass[i] = pass[i];
+	c.pass[63] = (char)('a' + extra % 26);
+	return c;
+}
+
+static int is(const struct wifi_cfg *c, const char *ssid, const char *pass)
+{
+	return c->ssid_len == strlen(ssid) &&
+	       memcmp(c->ssid, ssid, c->ssid_len) == 0 &&
+	       c->pass_len == strlen(pass) &&
+	       memcmp(c->pass, pass, c->pass_len) == 0;
+}
+
+static void reset(void)
+{
+	memset(flash, 0, sizeof(flash));
+	flash_len = 0;
+	flash_present = 0;
+}
+
+int main(void)
+{
+	struct wifi_cfg list[WIFI_CFG_MAX];
+	struct wifi_cfg r;
+	struct wifi_cfg_list *l;
+	int i, n;
+
+	/* An empty list removes the file. */
+	reset();
+	check(wifi_store_save(NULL, 0) == 0, "save empty");
+	check(!flash_present, "empty file removed");
+
+	/* Newest first. */
+	check(wifi_store_remember(&(struct wifi_cfg){0}) < 0,
+	      "reject invalid record");
+	r = rec("alpha", "pass-one", 0);
+	check(wifi_store_remember(&r) == 0, "remember alpha");
+	r = rec("bravo", "pass-two", 1);
+	check(wifi_store_remember(&r) == 0, "remember bravo");
+	n = wifi_store_load(list, WIFI_CFG_MAX);
+	check(n == 2, "two records");
+	check(is(&list[0], "bravo", "pass-two"), "bravo first");
+	check(is(&list[1], "alpha", "pass-one"), "alpha second");
+
+	/* Reconnecting updates the passphrase and moves the record to front. */
+	r = rec("alpha", "new-pass", 2);
+	check(wifi_store_remember(&r) == 0, "update alpha");
+	n = wifi_store_load(list, WIFI_CFG_MAX);
+	check(n == 2, "still two records");
+	check(is(&list[0], "alpha", "new-pass"), "alpha updated and first");
+	check(is(&list[1], "bravo", "pass-two"), "bravo second");
+	check(wifi_store_find(list, n, (const unsigned char *)"alpha", 5) == 0,
+	      "find alpha");
+	check(wifi_store_find(list, n, (const unsigned char *)"zulu", 4) == -1,
+	      "find missing");
+
+	/* Full list drops the least recently used entry. */
+	reset();
+	for (i = 0; i < WIFI_CFG_MAX + 1; i++) {
+		char ssid[16];
+
+		snprintf(ssid, sizeof(ssid), "net%d", i);
+		r = rec(ssid, "password", i);
+		check(wifi_store_remember(&r) == 0, "remember full-list entry");
+	}
+	n = wifi_store_load(list, WIFI_CFG_MAX);
+	check(n == WIFI_CFG_MAX, "list capped");
+	check(is(&list[0], "net16", "password"), "newest kept");
+	check(is(&list[WIFI_CFG_MAX - 1], "net1", "password"),
+	      "oldest dropped");
+
+	/* Forget one record; forgetting a missing SSID reports not found. */
+	check(wifi_store_forget((const unsigned char *)"net16", 5) == 1,
+	      "forget present");
+	check(wifi_store_forget((const unsigned char *)"net16", 5) == 0,
+	      "forget missing");
+	n = wifi_store_load(list, WIFI_CFG_MAX);
+	check(n == WIFI_CFG_MAX - 1, "forget shrinks the list");
+	check(is(&list[0], "net15", "password"), "next record promoted");
+
+	/* The old one-record file is still read. */
+	reset();
+	r = rec("legacy", "oldpass", 0);
+	memcpy(flash, &r, sizeof(r));
+	flash_len = sizeof(r);
+	flash_present = 1;
+	n = wifi_store_load(list, WIFI_CFG_MAX);
+	check(n == 1 && is(&list[0], "legacy", "oldpass"),
+	      "legacy record accepted");
+
+	/* A truncated header and duplicate SSIDs are handled. */
+	reset();
+	memcpy(flash, &(unsigned int){ WIFI_CFG_LIST_MAGIC }, 4);
+	flash_len = 8;
+	flash_present = 1;
+	check(wifi_store_load(list, WIFI_CFG_MAX) == 0, "truncated header");
+
+	reset();
+	l = (struct wifi_cfg_list *)flash;
+	l->magic = WIFI_CFG_LIST_MAGIC;
+	l->version = WIFI_CFG_LIST_VER;
+	l->count = 2;
+	l->net[0] = rec("dup", "pass", 0);
+	l->net[1] = rec("dup", "pass", 0);
+	flash_len = 12 + 2 * sizeof(struct wifi_cfg);
+	flash_present = 1;
+	n = wifi_store_load(list, WIFI_CFG_MAX);
+	check(n == 1 && is(&list[0], "dup", "pass"), "duplicate dropped");
+
+	/* A header that promises more records than the file holds is clamped
+	 * to the bytes actually present. */
+	reset();
+	l = (struct wifi_cfg_list *)flash;
+	l->magic = WIFI_CFG_LIST_MAGIC;
+	l->version = WIFI_CFG_LIST_VER;
+	l->count = 5;
+	l->net[0] = rec("first", "pass", 0);
+	l->net[1] = rec("second", "pass", 0);
+	flash_len = 12 + 2 * sizeof(struct wifi_cfg);
+	flash_present = 1;
+	n = wifi_store_load(list, WIFI_CFG_MAX);
+	check(n == 2 && is(&list[0], "first", "pass") &&
+	      is(&list[1], "second", "pass"), "short list clamped");
+
+	if (!failures)
+		printf("wifi_store_test: all checks passed\n");
+	return failures ? 1 : 0;
+}