Sfoglia il codice sorgente

Add NTP time sync to the Date & Time editor

Add a minimal SNTP client (ntp.c) that resolves the server, ARPs the
next hop and validates a 48-byte UDP reply's origin timestamp.  The new
SYS_NTP_SYNC syscall owns the NIC for the duration and returns the
server's UTC time as a struct sys_datetime.

The settime dialog gains an editable NTP server field (pool.ntp.org by
default) and a Sync NTP button that writes the fetched time through
SYS_RTC_SET.  Update AGENTS.md and the architecture pages.
Johannes Zellner 1 settimana fa
parent
commit
b23d957213
15 ha cambiato i file con 510 aggiunte e 56 eliminazioni
  1. 16 8
      AGENTS.md
  2. 6 3
      Makefile
  3. 5 2
      docs/drivers.html
  4. 2 2
      docs/graphics.html
  5. 1 1
      docs/index.html
  6. 36 11
      docs/network.html
  7. 2 2
      docs/userland.html
  8. 230 0
      ntp.c
  9. 17 0
      ntp.h
  10. 29 0
      sys_net.c
  11. 2 0
      sys_net.h
  12. 16 0
      syscall.c
  13. 13 0
      syscall.h
  14. 8 0
      ucmd_lib.h
  15. 127 27
      ucmd_settime.c

+ 16 - 8
AGENTS.md

@@ -407,8 +407,10 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   sees the right century.  `SYS_RTC_GET`/`SYS_RTC_SET` (104/105)
   expose the full `struct sys_datetime`; `SYS_RTC_HMS`/`SYS_RTC_DATETIME`
   (56/69) stay the small read-only views.  The WM top-bar date/time is a
-  click target that spawns `/ramfs/bin/settime`; the `date` command prints
-  the classic `date` line and a small `+FORMAT` subset.
+  click target that spawns `/ramfs/bin/settime`, whose "Sync NTP" button
+  fetches UTC through `SYS_NTP_SYNC` and writes it with `SYS_RTC_SET`; the
+  `date` command prints the classic `date` line and a small `+FORMAT`
+  subset.
 - **Fonts**: `ufont.c/h`, `ufont_ttf.c`, `ufont_draw.c`, `ufont_file.c` — a
   fixed-point (26.6, no FPU) TrueType parser and antialiased rasterizer for
   ring-3 text.  Latin-1 only for now; the faces are the Arimo regular/bold/
@@ -498,7 +500,13 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `netinfo`/`netrecv`/`netsend`/`netip`/`dhcp`/`pong`/`ping`/`netregs`
   commands.  `dns.c/h` — a minimal resolver (one recursive A query over UDP,
   name-compression aware; `netdns` shows/sets the server, `host <name>`
-  resolves).  `tcp.c/h` — a minimal TCP *client* (connect/send/recv/close, in-order
+  resolves).  `ntp.c/h` — a minimal SNTP client (RFC 4330): one 48-byte
+  request to UDP port 123, three one-second tries, origin-timestamp
+  validation and the reply's transmit timestamp converted from the 1900
+  epoch to UTC.  `SYS_NTP_SYNC` exposes it to the Date & Time app; the
+  default server is `pool.ntp.org`, the service takes the NIC receiver for
+  the duration and is refused with `SYS_NTP_EBUSY` while another command
+  owns it.  `tcp.c/h` — a minimal TCP *client* (connect/send/recv/close, in-order
   receive with an 8 KB receive queue so data arriving during a send is never
   lost, one segment of retransmit; the caller owns the NIC).
   `curl` — the ring-3 command: `http://` or `https://` GET with DNS, ARP,
@@ -821,8 +829,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   tests: `make test-images` (`img_test.c`, corpus in `testdata/images/`,
   generator `tools/gen_img_tests.py`).
 - **Network service**: `sys_net.c/h` — the NIC and the stack stay in the
-  kernel; ring-3 commands get `SYS_NET_INFO`/config, the DNS and DHCP clients
-  and the raw frame paths (`NET_TX/RX/DECODE/REPLY/LOOPBACK/REGS/RESET`), so
+  kernel; ring-3 commands get `SYS_NET_INFO`/config, the DNS, DHCP and NTP
+  clients and the raw frame paths (`NET_TX/RX/DECODE/REPLY/LOOPBACK/REGS/RESET`), so
   the packet-level commands ported unchanged.  The receiver is owned by one
   process at a time (`netdev_acquire`): the background kexec watcher pauses
   while a command owns it, and the reaper force-releases it if that process
@@ -830,7 +838,7 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   The TCP client is exposed as `TCP_CONNECT/PEER_MSS/SEND/RECV/CLOSE` (one
   connection at a time, `tcp.c` keeps the state) plus `NET_NEXT_HOP`/`NET_ARP`
   for the route to the peer.  Calls that wait inside the stack (ARP, DNS,
-  DHCP, TCP) re-enable interrupts for the duration: the syscall stub enters
+  DHCP, NTP, TCP) re-enable interrupts for the duration: the syscall stub enters
   with them off, and the deadlines spin on `get_ticks_ms()` -- a frozen tick
   counter would never satisfy them.  The netdev ownership already serializes
   net users, so being preempted mid-wait is safe.
@@ -1347,8 +1355,8 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
    compressed pack directly to `0x900000` with INT 15h AH=87h, so the cap is
    `PACK_MAX` 1 MB (not the old ~255 KB low-gap limit).  The browser and
    its ring-3 dependencies are compiled with function sections and linked
-   with `--gc-sections`; the current pack with the UI fonts is ~444 KiB
-   (455092 bytes), leaving ~580 KiB under the cap.  `libdeflate-gzip -12` is
+   with `--gc-sections`; the current pack with the UI fonts is ~445 KiB
+   (455591 bytes), leaving ~580 KiB under the cap.  `libdeflate-gzip -12` is
    still preferred for the extra headroom, though the 1 MB cap leaves room
    for `gzip -9` as a fallback.
 9. SMP is **ACPI/MADT only**: no Intel MP-table fallback, so a Pentium II SMP

+ 6 - 3
Makefile

@@ -244,6 +244,9 @@ dhcp.o: dhcp.c dhcp.h io.h net.h netdev.h timer.h
 dns.o: dns.c dns.h io.h timer.h netdev.h net.h
 	$(CC) $(CFLAGS) -o $@ $<
 
+ntp.o: ntp.c ntp.h dns.h net.h netdev.h timer.h syscall.h
+	$(CC) $(CFLAGS) -o $@ $<
+
 tcp.o: tcp.c tcp.h io.h timer.h netdev.h net.h
 	$(CC) $(CFLAGS) -o $@ $<
 
@@ -367,13 +370,13 @@ inflate.o: inflate.c inflate.h
 sys_info.o: sys_info.c sys_info.h syscall.h ahci.h blkdev.h it87.h mm.h mouse.h thermal.h tpec.h usbhid.h vfs.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-sys_net.o: sys_net.c sys_net.h syscall.h dhcp.h dns.h net.h netdev.h netlog.h process.h sched.h
+sys_net.o: sys_net.c sys_net.h syscall.h dhcp.h dns.h net.h netdev.h netlog.h ntp.h process.h sched.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 syscall_stub.o: syscall_stub.S irqret.inc
 	$(AS) $(ASFLAGS) -o $@ $<
 
-kernel.elf: kernel.ld 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 reboot.o poweroff.o disk.o fat.o serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o display.o mouse.o i2c.o touchpad.o uhci.o ohci.o ehci.o xhci.o asix.o usb.o usbhid.o lsusb.o panic.o bootcon.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_mem.o sys_net.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o e1000e.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o acpi.o lapic.o smp.o ap_tramp_embed.o inflate.o ramfs.o share.o payload.o
+kernel.elf: kernel.ld 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 reboot.o poweroff.o disk.o fat.o serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o display.o mouse.o i2c.o touchpad.o uhci.o ohci.o ehci.o xhci.o asix.o usb.o usbhid.o lsusb.o panic.o bootcon.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_mem.o sys_net.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o e1000e.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o ntp.o tcp.o acpi.o lapic.o smp.o ap_tramp_embed.o inflate.o ramfs.o share.o payload.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $(filter-out kernel.ld,$^)
 
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
@@ -1152,4 +1155,4 @@ kernel-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 disk.o serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o display.o mouse.o i2c.o touchpad.o uhci.o ohci.o ehci.o xhci.o asix.o usb.o usbhid.o lsusb.o panic.o bootcon.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 e1000e.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 hello.elf cmds.pack cmds_pack_gz.bin cmds_pack.o rootfs.bin cmds.img mkrootfs 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)) gallery.o gallery.elf $(TLSLIB_OBJS) tls_test kexec_send netkexec_send netmonitor BOOTX64.EFI esp.img usb-efi.img efi/main.o efi/payload.o efi/tramp.o efi/tramp.elf efi/tramp.bin efi/efi_entry.h libc.a libc/*.o malloc_test format_test math_test div64_test setjmp_test mujs_test js_browser.o $(MUJS_DIR)/mujs.o ufont.o ufont_ttf.o ufont_draw.o ufont_file.o ufont_test ufont_test_asan
+	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 disk.o serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o display.o mouse.o i2c.o touchpad.o uhci.o ohci.o ehci.o xhci.o asix.o usb.o usbhid.o lsusb.o panic.o bootcon.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 e1000e.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o ntp.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 hello.elf cmds.pack cmds_pack_gz.bin cmds_pack.o rootfs.bin cmds.img mkrootfs 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)) gallery.o gallery.elf $(TLSLIB_OBJS) tls_test kexec_send netkexec_send netmonitor BOOTX64.EFI esp.img usb-efi.img efi/main.o efi/payload.o efi/tramp.o efi/tramp.elf efi/tramp.bin efi/efi_entry.h libc.a libc/*.o malloc_test format_test math_test div64_test setjmp_test mujs_test js_browser.o $(MUJS_DIR)/mujs.o ufont.o ufont_ttf.o ufont_draw.o ufont_file.o ufont_test ufont_test_asan

+ 5 - 2
docs/drivers.html

@@ -384,8 +384,11 @@
 			the full <code>struct sys_datetime</code>; the older
 			<code>SYS_RTC_HMS</code>/<code>SYS_RTC_DATETIME</code> calls remain
 			the small read-only views. The WM’s top-bar date/time is a click
-			target that opens <code>bin/settime</code>, and the <code>date</code>
-			command prints the same clock in the classic Linux format.
+			target that opens <code>bin/settime</code>; its <em>Sync NTP</em>
+			button fetches UTC through <code>SYS_NTP_SYNC</code> (106), backed
+			by the SNTP client in <span class="file">ntp.c</span>, and writes
+			it with <code>SYS_RTC_SET</code>. The <code>date</code> command
+			prints the same clock in the classic Linux format.
 		</p>
 	</section>
 

+ 2 - 2
docs/graphics.html

@@ -324,7 +324,7 @@
 			</div>
 			<div class="card">
 				<h3>clock / colors / settime</h3>
-				<p>Small canvas demos: an analog clock, a colour test window, and the Date &amp; Time editor. Clicking the top-bar date/time opens <code>settime</code>, which reads and writes the CMOS RTC.</p>
+				<p>Small canvas demos: an analog clock, a colour test window, and the Date &amp; Time editor. Clicking the top-bar date/time opens <code>settime</code>, which reads and writes the CMOS RTC and can fetch UTC from an SNTP server.</p>
 			</div>
 			<div class="card">
 				<h3>browser</h3>
@@ -368,7 +368,7 @@
 			<li><code>cpu.c</code> — SSE2 probing</li>
 			<li><code>wm.c</code>, <code>wm.h</code>, <code>wm_abi.h</code> — kernel window server and shared ABI</li>
 			<li><code>ucmd_wm.c</code>, <code>uwm_lib.c</code> — ring-3 WM</li>
-			<li><code>ucmd_settime.c</code>, <code>rtc.c</code> — Date &amp; Time editor and RTC access</li>
+			<li><code>ucmd_settime.c</code>, <code>rtc.c</code>, <code>ntp.c</code> — Date &amp; Time editor, RTC access and SNTP sync</li>
 			<li><code>gfx.c</code>, <code>gfx.h</code> — RGB565 window canvases</li>
 			<li><code>sys_wm.c</code>, <code>sys_wm.h</code> — WM/window ABI</li>
 			<li><code>browser.c</code>, <code>browser_html.c</code> — HTML/CSS renderer and inline SVG</li>

+ 1 - 1
docs/index.html

@@ -217,7 +217,7 @@
 			</a>
 			<a class="card" href="network.html">
 				<h3>Networking</h3>
-				<p>NIC registry, ARP/ICMP/UDP, DHCP, DNS, TCP client and listener, TLS 1.3, netconsole and netkexec.</p>
+				<p>NIC registry, ARP/ICMP/UDP, DHCP, DNS, NTP, TCP client and listener, TLS 1.3, netconsole and netkexec.</p>
 				<span class="card-tag">network.html</span>
 			</a>
 			<a class="card" href="userland.html">

+ 36 - 11
docs/network.html

@@ -4,7 +4,7 @@
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <title>Networking | NebOS Architecture</title>
-<meta name="description" content="NebOS networking: the netdev registry and NIC drivers, ARP/ICMP/UDP, DHCP, DNS, the TCP client and listener, TLS 1.3, sys_net ownership, netconsole and netkexec.">
+<meta name="description" content="NebOS networking: the netdev registry and NIC drivers, ARP/ICMP/UDP, DHCP, DNS, NTP, the TCP client and listener, TLS 1.3, sys_net ownership, netconsole and netkexec.">
 <link rel="icon" href="favicon.svg" type="image/svg+xml">
 <link rel="stylesheet" href="style.css">
 </head>
@@ -42,7 +42,7 @@
 		</p>
 		<div class="meta">
 			<span class="pill">ARP · ICMP · UDP · TCP</span>
-			<span class="pill">DHCP · DNS</span>
+			<span class="pill">DHCP · DNS · NTP</span>
 			<span class="pill">TLS 1.3 · X25519</span>
 			<span class="pill">netconsole + netkexec</span>
 		</div>
@@ -54,7 +54,7 @@
 			<li><a href="#stack">Protocol stack</a></li>
 			<li><a href="#netdev">NIC drivers</a></li>
 			<li><a href="#core">Link &amp; IP layer</a></li>
-			<li><a href="#dhcp">DHCP &amp; DNS</a></li>
+			<li><a href="#dhcp">DHCP, DNS &amp; NTP</a></li>
 			<li><a href="#tcp">TCP</a></li>
 			<li><a href="#tls">TLS</a></li>
 			<li><a href="#abi">sys_net ABI</a></li>
@@ -77,10 +77,10 @@
 		<figure class="figure">
 			<svg viewBox="0 0 920 380" role="img" aria-labelledby="net-title net-desc">
 				<title id="net-title">NebOS network stack</title>
-				<desc id="net-desc">Ring-3 curl, browser and websrv use uhttp and TLS, then sys_net syscalls, then TCP/DNS/DHCP, IPv4/ARP/ICMP, netdev drivers and the NIC.</desc>
+				<desc id="net-desc">Ring-3 curl, browser and websrv use uhttp and TLS, then sys_net syscalls, then TCP/DNS/DHCP/NTP, IPv4/ARP/ICMP, netdev drivers and the NIC.</desc>
 
 				<rect class="svg-box accent" x="70" y="18" width="780" height="58" rx="9"/>
-				<text class="svg-text" x="92" y="43">curl · browser · websrv · ping · dhcp</text>
+				<text class="svg-text" x="92" y="43">curl · browser · websrv · ping · dhcp · settime</text>
 				<text class="svg-sub" x="92" y="63">ring-3 programs</text>
 
 				<path class="svg-line" d="M460 76v20"/>
@@ -100,7 +100,7 @@
 				<path class="svg-line" d="M654 168l6 7 6-7"/>
 
 				<rect class="svg-box green" x="70" y="176" width="780" height="58" rx="9"/>
-				<text class="svg-text" x="92" y="201">SYS_NET_* · SYS_TCP_* · SYS_DNS_RESOLVE · SYS_DHCP_RUN</text>
+				<text class="svg-text" x="92" y="201">SYS_NET_* · SYS_TCP_* · SYS_DNS_RESOLVE · SYS_DHCP_RUN · SYS_NTP_SYNC</text>
 				<text class="svg-sub" x="92" y="221">one receiver owner · interrupt-enabled waits</text>
 
 				<path class="svg-line green" d="M460 234v20"/>
@@ -165,7 +165,7 @@
 			<li><strong>ARP</strong> resolves a next hop with three tries, one second apart; <code>net_arp_resolve()</code> polls the active NIC and the caller must own it.</li>
 			<li><strong>Routing</strong> sends off-subnet traffic to the gateway when one is known; <code>net_next_hop()</code> is shared by ping, DNS and TCP.</li>
 			<li><strong>ICMP echo</strong> backs <code>ping</code>, with ARP resolution and round-trip timing.</li>
-			<li><strong>UDP</strong> has send and parse helpers; DNS, DHCP and netlog are its users.</li>
+			<li><strong>UDP</strong> has send and parse helpers; DNS, DHCP, NTP and netlog are its users.</li>
 			<li><strong>Checksums</strong> use the Internet one's-complement sum, with a TCP pseudo-header variant.</li>
 		</ul>
 		<p>
@@ -179,7 +179,7 @@
 	</section>
 
 	<section id="dhcp">
-		<h2>DHCP &amp; DNS</h2>
+		<h2>DHCP, DNS &amp; NTP</h2>
 		<h3>DHCP</h3>
 		<p>
 			<span class="file">dhcp.c</span> is a minimal client:
@@ -195,6 +195,30 @@
 			shows or sets the server; <code>host &lt;name&gt;</code> resolves.
 			Numeric hosts skip DNS entirely.
 		</p>
+		<h3>NTP</h3>
+		<p>
+			<span class="file">ntp.c</span> is a minimal SNTP (RFC 4330)
+			client: one 48-byte request to UDP port 123, three one-second
+			tries, DNS unless the server is a dotted address, and the shared
+			ARP/router path.  An empty name uses <code>pool.ntp.org</code>.
+			A reply is accepted only when it comes from the
+			resolved server to the ephemeral source port, is a server/broadcast
+			reply with a valid stratum, and echoes the request's origin
+			timestamp; the transmit timestamp is converted from NTP's 1900 epoch
+			to a UTC <code>struct sys_datetime</code> (with the 2036 era wrap
+			handled).  <code>SYS_NTP_SYNC</code> returns that value to ring 3;
+			the Date &amp; Time editor then writes it through
+			<code>SYS_RTC_SET</code>.  The service owns the receiver for the
+			duration, so it reports <code>SYS_NTP_EBUSY</code> while another
+			network command owns the NIC.
+		</p>
+		<div class="warn">
+			<p><strong>NTP is unauthenticated.</strong> The origin-timestamp
+			check rejects unrelated datagrams but does not authenticate the
+			server; anyone who can answer for the configured name can set the
+			board's clock.  There is no NTS, no leap-second handling and no
+			delay/dispersion estimation — the CMOS RTC only resolves seconds.</p>
+		</div>
 	</section>
 
 	<section id="tcp">
@@ -247,12 +271,12 @@
 			<span class="file">sys_net.c</span> exposes NIC info, MAC/IP/mask/
 			gateway/DNS getters and setters, raw frame TX/RX, decode, reply,
 			loopback, register dump, reset, speed and MAC overrides. It also
-			exposes the DNS and DHCP clients and the TCP/HTTP helpers.
+			exposes the DNS, DHCP and NTP clients and the TCP/HTTP helpers.
 		</p>
 		<ul>
 			<li><strong>One owner.</strong> <code>SYS_NET_ACQUIRE</code> takes the receiver for the calling process; the background kexec watcher pauses while a command owns it.</li>
 			<li><strong>Reaper safety.</strong> If the owner dies, <code>sys_net_reap</code> force-releases the receiver through <code>netdev_release_all()</code>.</li>
-			<li><strong>Wait semantics.</strong> ARP, DNS, DHCP and TCP waits re-enable interrupts for their duration and spin on <code>get_ticks_ms()</code>; the syscall stub enters with interrupts off.</li>
+			<li><strong>Wait semantics.</strong> ARP, DNS, DHCP, NTP and TCP waits re-enable interrupts for their duration and spin on <code>get_ticks_ms()</code>; the syscall stub enters with interrupts off.</li>
 			<li><strong>No sockets.</strong> The connection state lives in the kernel, one connection at a time; this is why the browser opens a fresh connection per fetch job.</li>
 		</ul>
 	</section>
@@ -303,6 +327,7 @@
 					<tr><td>TLS certificates</td><td>Not verified</td><td>Encryption without authentication; MITM is undetected.</td></tr>
 					<tr><td>TLS DRBG</td><td>Weak (RDTSC/ticks/MAC)</td><td>Not suitable for high-value secrets.</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>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>One process at a time</td><td>Packet-level commands are mutually exclusive; 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>
 				</tbody>
@@ -316,7 +341,7 @@
 			<li><code>netdev.c</code>, <code>netdev.h</code> — registry</li>
 			<li><code>e1000e.c</code>, <code>r8168.c</code>, <code>ne2000.c</code>, <code>asix.c</code></li>
 			<li><code>net.c</code>, <code>net.h</code> — ARP/ICMP/UDP/IP</li>
-			<li><code>dhcp.c</code>, <code>dns.c</code></li>
+			<li><code>dhcp.c</code>, <code>dns.c</code>, <code>ntp.c</code></li>
 			<li><code>tcp.c</code>, <code>tcp.h</code> — client + listener</li>
 			<li><code>tls.c</code>, <code>tls_*.c</code> — TLS 1.3</li>
 			<li><code>sys_net.c</code> — ring-3 service</li>

+ 2 - 2
docs/userland.html

@@ -222,7 +222,7 @@
 					<tr><td>Console &amp; time</td><td>1–4, 56, 69, 104–105</td><td>putstr, ticks, sleep, exit, RTC time/date get/set</td></tr>
 					<tr><td>Files</td><td>5–11, 48, 98</td><td>whole-file read/write, list, unlink, mkdir/rmdir, mounts, cwd, stat</td></tr>
 					<tr><td>System info</td><td>12–16, 49–51, 91–92, 102–103</td><td>memory, E820, mouse, storage, blkdev, procinfo, cursor, CPU temp, sensors, EC sensors, AC/battery</td></tr>
-					<tr><td>Network</td><td>17–47</td><td>NIC config/acquire, raw frames, DHCP/DNS, TCP client, ARP, cwd</td></tr>
+					<tr><td>Network</td><td>17–47, 106</td><td>NIC config/acquire, raw frames, DHCP/DNS/NTP, TCP client, ARP, cwd</td></tr>
 					<tr><td>Window &amp; WM</td><td>55, 57–72, 80, 83–87</td><td>key poll, WM attach/info/map/present/create_term, window create/present/input/resize</td></tr>
 					<tr><td>Process &amp; memory</td><td>73–79, 81, 88–90</td><td>TTY, spawn, alive, kill, chdir, scheduler info, heap alloc/grow/free</td></tr>
 					<tr><td>TCP server</td><td>93–97, 99–101</td><td>listen, accept, server recv/send/close, peer, speed, MAC set</td></tr>
@@ -327,7 +327,7 @@
 			<li><strong>view</strong> — fit/1:1/zoom/pan image viewer, animated GIF playback.</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>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 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>wm</strong> / <strong>term</strong> — the ring-3 window manager and terminal launcher used by the desktop.</li>
 		</ul>
 		<p>

+ 230 - 0
ntp.c

@@ -0,0 +1,230 @@
+/* Minimal SNTP client (RFC 4330).
+ *
+ * One 48-byte client request to UDP port 123, three tries one second apart.
+ * The server is resolved through DNS (a dotted address skips it) and reached
+ * through the shared ARP/routing helpers.  The reply's origin timestamp must
+ * match the request's transmit timestamp, and its transmit timestamp is
+ * converted from NTP seconds (1900 epoch) to UTC `struct sys_datetime`.
+ *
+ * Like DNS and DHCP the polled caller owns the NIC; sys_ntp_sync() acquires
+ * it for ring-3 callers.  No NTP authentication/delay estimation is done:
+ * the RTC only has one-second resolution. */
+
+#include "ntp.h"
+#include "dns.h"
+#include "net.h"
+#include "netdev.h"
+#include "timer.h"
+
+#define NTP_PORT        123
+#define NTP_PACKET_LEN  48
+#define NTP_RETRY_MS    1000
+#define NTP_RETRIES     3
+#define NTP_DEFAULT_TIMEOUT_MS (NTP_RETRIES * NTP_RETRY_MS)
+
+/* 1900-01-01 -> 1970-01-01, and the Unix time of the NTP 32-bit wrap. */
+#define NTP_UNIX_EPOCH  2208988800u
+#define NTP_ERA1_BASE   2085978496u
+
+static unsigned int rd32be(const unsigned char *p)
+{
+	return ((unsigned int)p[0] << 24) | ((unsigned int)p[1] << 16) |
+	       ((unsigned int)p[2] << 8) | p[3];
+}
+
+static void wr32be(unsigned char *p, unsigned int v)
+{
+	p[0] = (unsigned char)(v >> 24);
+	p[1] = (unsigned char)(v >> 16);
+	p[2] = (unsigned char)(v >> 8);
+	p[3] = (unsigned char)v;
+}
+
+static int ip_eq(const unsigned char *a, const unsigned char *b)
+{
+	return a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3];
+}
+
+/* NTP seconds/fraction -> Unix seconds.  The 32-bit NTP seconds wrap in
+ * 2036; values below the 1968 boundary belong to era 1 then.  The RTC range
+ * is 1970-2069, so the 1968-1970 era-0 window is simply rejected. */
+static int ntp_to_unix(unsigned int secs, unsigned int frac,
+		       unsigned int *out)
+{
+	unsigned int t;
+
+	if (secs >= NTP_UNIX_EPOCH)
+		t = secs - NTP_UNIX_EPOCH;              /* era 0: 1970..2036 */
+	else if (secs < NTP_ERA1_BASE)
+		t = secs + NTP_ERA1_BASE;               /* era 1: 2036..2106 */
+	else
+		return -1;                              /* 1968..1970 */
+	if (frac >= 0x80000000u)                        /* round to nearest */
+		t++;
+	*out = t;
+	return 0;
+}
+
+/* Howard Hinnant's civil-from-days algorithm, all unsigned 32-bit. */
+static void unix_to_datetime(unsigned int t, struct sys_datetime *dt)
+{
+	unsigned int days = t / 86400u;
+	unsigned int rem = t % 86400u;
+	unsigned int z = days + 719468u;
+	unsigned int era = z / 146097u;
+	unsigned int doe = z - era * 146097u;
+	unsigned int yoe = (doe - doe / 1460u + doe / 36524u -
+			    doe / 146096u) / 365u;
+	unsigned int y = yoe + era * 400u;
+	unsigned int doy = doe - (365u * yoe + yoe / 4u - yoe / 100u);
+	unsigned int mp = (5u * doy + 2u) / 153u;
+	unsigned int d = doy - (153u * mp + 2u) / 5u + 1u;
+	unsigned int m = mp < 10u ? mp + 3u : mp - 9u;
+
+	if (m <= 2u)
+		y++;
+	dt->year = y;
+	dt->month = m;
+	dt->day = d;
+	dt->hour = rem / 3600u;
+	dt->minute = (rem % 3600u) / 60u;
+	dt->second = rem % 60u;
+	dt->wday = (days + 4u) % 7u;   /* 1970-01-01 was a Thursday */
+}
+
+/* 1 = a valid reply and *out filled, 0 = not ours, <0 = ours but unusable. */
+static int ntp_parse(const unsigned char *frame, unsigned int len,
+		     const unsigned char *server_ip, unsigned int server_port,
+		     unsigned int nonce, unsigned int nfrac,
+		     struct sys_datetime *out)
+{
+	unsigned char s_ip[4], d_ip[4];
+	const unsigned char *p;
+	unsigned int sport, dport, plen, secs, frac, unix_sec;
+	int mode;
+
+	if (!net_udp_parse(frame, len, s_ip, d_ip, &sport, &dport, &p, &plen))
+		return 0;
+	if (sport != NTP_PORT || dport != server_port ||
+	    !ip_eq(s_ip, server_ip))
+		return 0;
+	if (plen < NTP_PACKET_LEN)
+		return 0;
+
+	mode = p[0] & 0x07;
+	if (mode != 4 && mode != 5)          /* server or broadcast reply */
+		return 0;
+	if ((p[0] >> 6) == 3)                /* LI: server unsynchronised */
+		return -1;
+	if (p[1] == 0 || p[1] > 15)          /* kiss-o'-death / invalid */
+		return -1;
+	if (rd32be(p + 24) != nonce || rd32be(p + 28) != nfrac)
+		return 0;                    /* not a reply to this request */
+
+	secs = rd32be(p + 40);
+	frac = rd32be(p + 44);
+	if (!(secs | frac))                  /* no transmit timestamp */
+		return -1;
+	if (ntp_to_unix(secs, frac, &unix_sec) != 0)
+		return -1;
+	unix_to_datetime(unix_sec, out);
+	if (out->year < 1970 || out->year > 2069)
+		return -1;
+	return 1;
+}
+
+int ntp_sync(const char *server, unsigned int timeout_ms,
+	     struct sys_datetime *out)
+{
+	const struct netdev *nd = netdev_active();
+	unsigned char server_ip[4], hop[4], mac[6];
+	unsigned char *rxbuf;
+	unsigned char pkt[NTP_PACKET_LEN];
+	unsigned int nonce, nfrac, sport, tries, start, deadline, i;
+	char name[64];
+	unsigned int n = 0, e = 0;
+	int r;
+
+	if (!nd || !nd->rx || !nd->tx || !nd->get_mac)
+		return SYS_NTP_ENONIC;
+	if (!out)
+		return SYS_NTP_EREPLY;
+
+	/* The text field may have accidental surrounding spaces. */
+	if (server) {
+		while (server[n] == ' ' || server[n] == '\t')
+			n++;
+		while (server[n] && e + 1 < sizeof(name))
+			name[e++] = server[n++];
+		while (e && (name[e - 1] == ' ' || name[e - 1] == '\t'))
+			e--;
+	}
+	name[e] = '\0';
+	if (!name[0]) {
+		static const char fallback[] = NTP_DEFAULT_SERVER;
+
+		for (i = 0; fallback[i] && i + 1 < sizeof(name); i++)
+			name[i] = fallback[i];
+		name[i] = '\0';
+	}
+
+	if (net_parse_ip(name, server_ip) != 0) {
+		if (dns_resolve(name, server_ip) != 0)
+			return SYS_NTP_ENAME;
+	}
+	net_next_hop(server_ip, hop);
+	r = net_arp_resolve(hop, mac);
+	if (r == -2)
+		return SYS_NTP_ETX;
+	if (r != 0)
+		return SYS_NTP_EARP;
+
+	nonce = get_ticks_ms() ^ 0x4E545000u;    /* "NT" */
+	if (!nonce)
+		nonce = 1;
+	nfrac = 0x4E420000u;                     /* "NB" */
+	for (i = 0; i < NTP_PACKET_LEN; i++)
+		pkt[i] = 0;
+	pkt[0] = 0x23;                           /* LI 0, VN 4, mode 3 client */
+	pkt[2] = 6;                              /* poll exponent: 64 s */
+	pkt[3] = 0xEC;                           /* precision: -20 */
+	wr32be(pkt + 40, nonce);
+	wr32be(pkt + 44, nfrac);
+
+	/* Ephemeral source port; the reply must come back to it. */
+	sport = 49152u + (nonce & 0x3FFFu);
+	if (timeout_ms == 0)
+		timeout_ms = NTP_DEFAULT_TIMEOUT_MS;
+	if (timeout_ms > 15000)
+		timeout_ms = 15000;
+
+	rxbuf = netdev_rx_scratch();
+	start = get_ticks_ms();
+	for (tries = 0; tries < NTP_RETRIES; tries++) {
+		unsigned int now = get_ticks_ms();
+
+		if ((int)(now - (start + timeout_ms)) >= 0)
+			break;
+		deadline = now + NTP_RETRY_MS;
+		if ((int)(deadline - (start + timeout_ms)) > 0)
+			deadline = start + timeout_ms;
+
+		if (net_udp_send(mac, server_ip, sport, NTP_PORT,
+				 pkt, sizeof(pkt)) != 0)
+			return SYS_NTP_ETX;
+
+		while ((int)(get_ticks_ms() - deadline) < 0) {
+			int len = nd->rx(rxbuf, NETDEV_FRAME_MAX);
+
+			if (len < 0)
+				continue;
+			r = ntp_parse(rxbuf, (unsigned int)len, server_ip,
+				      sport, nonce, nfrac, out);
+			if (r > 0)
+				return SYS_NTP_OK;
+			if (r < 0)
+				return SYS_NTP_EREPLY;
+		}
+	}
+	return SYS_NTP_ETIMEOUT;
+}

+ 17 - 0
ntp.h

@@ -0,0 +1,17 @@
+/* Minimal SNTP client (RFC 4330): see ntp.c. */
+#ifndef NTP_H
+#define NTP_H
+
+#include "syscall.h"
+
+/* Server used when the caller passes an empty name. */
+#define NTP_DEFAULT_SERVER "pool.ntp.org"
+
+/* Resolve `server` (a dotted address skips DNS), ARP the next hop, send one
+ * NTP client request and wait for the reply.  Returns a SYS_NTP_* code and,
+ * on success, fills `out` with the server's UTC transmit time.  The caller
+ * must own the receiver (sys_ntp_sync() takes care of that for ring 3). */
+int ntp_sync(const char *server, unsigned int timeout_ms,
+	     struct sys_datetime *out);
+
+#endif

+ 29 - 0
sys_net.c

@@ -16,6 +16,7 @@
 #include "netdev.h"
 #include "netkexec.h"
 #include "netlog.h"
+#include "ntp.h"
 #include "process.h"
 #include "tcp.h"
 #include "timer.h"
@@ -275,6 +276,34 @@ int sys_dns_resolve(const char *name, unsigned char ip[4])
 	return r;
 }
 
+/* SNTP sync for ring-3 callers.  The service owns the receiver for the
+ * duration (unless the caller already does), so settime does not have to
+ * take SYS_NET_ACQUIRE itself.  A second network user gets SYS_NTP_EBUSY. */
+int sys_ntp_sync(const char *server, unsigned int timeout_ms,
+		 struct sys_datetime *out)
+{
+	unsigned int pid = caller_pid();
+	int acquired = 0;
+	int r;
+
+	if (!netdev_active())
+		return SYS_NTP_ENONIC;
+	if (netdev_in_use()) {
+		if (netdev_owner() != pid)
+			return SYS_NTP_EBUSY;
+	} else {
+		netdev_acquire();
+		acquired = 1;
+	}
+
+	net_enter();
+	r = ntp_sync(server, timeout_ms, out);
+	net_exit();
+	if (acquired)
+		netdev_release();
+	return r;
+}
+
 /* ---- TCP client ---- */
 
 int sys_tcp_connect(const unsigned char mac[6], const unsigned char ip[4],

+ 2 - 0
sys_net.h

@@ -31,6 +31,8 @@ int sys_net_mac_set(const unsigned char mac[6]);
 int sys_dhcp_run(unsigned int timeout_ms);
 int sys_dhcp_info(unsigned char server[4], unsigned int *lease);
 int sys_dns_resolve(const char *name, unsigned char ip[4]);
+int sys_ntp_sync(const char *server, unsigned int timeout_ms,
+		 struct sys_datetime *out);
 int sys_netlog(const char *text);
 int sys_netlog_conf(int enabled, const unsigned char *ip);
 int sys_tcp_connect(const unsigned char mac[6], const unsigned char ip[4],

+ 16 - 0
syscall.c

@@ -231,6 +231,22 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 			d[i] = in[i];
 		return rtc_set_datetime(&dt);
 	}
+	case SYS_NTP_SYNC: {
+		struct sys_datetime dt;
+		struct sys_datetime *out = (struct sys_datetime *)a3;
+		char server[64];
+		int r;
+
+		if (!paging_user_range_ok(current_proc()->cr3, (unsigned int)out,
+					  sizeof(dt), 1))
+			return -1;
+		if (copy_user_string(server, sizeof(server), (const char *)a1) != 0)
+			return -1;
+		r = sys_ntp_sync(server, (unsigned int)a2, &dt);
+		if (r == 0)
+			*out = dt;
+		return r;
+	}
 	case SYS_WM_ATTACH:
 		return sys_wm_attach((struct wm_screen_info *)a1);
 	case SYS_WM_INFO:

+ 13 - 0
syscall.h

@@ -76,6 +76,19 @@
 #define SYS_RTC_HMS      56  /* (struct sys_time *out) -> 0/-1 */
 #define SYS_RTC_GET     104  /* (struct sys_datetime *out) -> 0/-1 */
 #define SYS_RTC_SET     105  /* (const struct sys_datetime *in) -> 0/-1 */
+#define SYS_NTP_SYNC    106  /* (const char *server, unsigned timeout_ms,
+				struct sys_datetime *out) -> SYS_NTP_*;
+				the service owns the NIC for the duration */
+
+/* SYS_NTP_SYNC results. */
+#define SYS_NTP_OK       0
+#define SYS_NTP_ENONIC  (-1)  /* no NIC */
+#define SYS_NTP_ENAME   (-2)  /* server name could not be resolved */
+#define SYS_NTP_EARP    (-3)  /* no ARP reply for the next hop */
+#define SYS_NTP_ETX     (-4)  /* NIC transmit failed */
+#define SYS_NTP_ETIMEOUT (-5) /* no NTP reply */
+#define SYS_NTP_EREPLY  (-6)  /* malformed, unsynchronised or KoD reply */
+#define SYS_NTP_EBUSY   (-7)  /* another process owns the receiver */
 
 /* Window-manager service (see wm_abi.h).  Only the kernel-spawned WM process
  * may call the WM_* entries; ordinary commands get -1. */

+ 8 - 0
ucmd_lib.h

@@ -194,6 +194,14 @@ static inline int u_rtc_set(const struct sys_datetime *t)
 	return u_syscall1(SYS_RTC_SET, (int)t);
 }
 
+/* Fetch the UTC time from an SNTP server (empty name = pool.ntp.org) and
+ * fill `dt`.  Returns SYS_NTP_*; the kernel owns the NIC for the duration. */
+static inline int u_ntp_sync(const char *server, unsigned int timeout_ms,
+			     struct sys_datetime *dt)
+{
+	return u_syscall3(SYS_NTP_SYNC, (int)server, (int)timeout_ms, (int)dt);
+}
+
 /* Window-manager service (only the kernel-spawned /ramfs/bin/wm may use it). */
 static inline int u_wm_attach(struct wm_screen_info *out)
 {

+ 127 - 27
ucmd_settime.c

@@ -1,9 +1,11 @@
 /* settime: Date & Time editor.
  *
  * A small ngui canvas window that reads the CMOS RTC through SYS_RTC_GET and
- * writes it through SYS_RTC_SET.  The RTC stores a two-digit year, so the
- * kernel expands it with a 1970-2069 window; this app accepts the same range
- * so a dead-battery default such as 1980 or 1990 can be corrected. */
+ * writes it through SYS_RTC_SET.  The "Sync NTP" button fetches UTC from an
+ * SNTP server through SYS_NTP_SYNC and writes the returned time to the RTC.
+ * The RTC stores a two-digit year, so the kernel expands it with a 1970-2069
+ * window; this app accepts the same range so a dead-battery default such as
+ * 1980 or 1990 can be corrected. */
 
 #include "ucmd_lib.h"
 #include "ngui.h"
@@ -12,13 +14,17 @@
 #define ID_TIME 2
 #define ID_SET  3
 #define ID_NOW  4
+#define ID_NTP  5
+#define ID_SERVER 6
 
 #define ACT_SET (1u << 0)
 #define ACT_NOW (1u << 1)
+#define ACT_NTP (1u << 2)
 
 static struct ngui ui;
 static struct ngui_input date_in;
 static struct ngui_input time_in;
+static struct ngui_input ntp_in;
 static struct sys_datetime current;
 static char status[64];
 static int status_error;
@@ -89,25 +95,30 @@ static void set_status(const char *msg, int err)
 	ngui_invalidate(&ui);
 }
 
-static void load_current(int fill_fields)
+static void set_fields(const struct sys_datetime *dt)
 {
-	struct sys_datetime dt;
 	char b[24];
 	char *p;
 
+	p = put_date(b, dt);
+	*p = '\0';
+	ngui_input_set(&date_in, b);
+	p = put_time(b, dt);
+	*p = '\0';
+	ngui_input_set(&time_in, b);
+}
+
+static void load_current(int fill)
+{
+	struct sys_datetime dt;
+
 	if (u_rtc_get(&dt) != 0) {
 		set_status("Cannot read the RTC", 1);
 		return;
 	}
 	current = dt;
-	if (!fill_fields)
-		return;
-	p = put_date(b, &dt);
-	*p = '\0';
-	ngui_input_set(&date_in, b);
-	p = put_time(b, &dt);
-	*p = '\0';
-	ngui_input_set(&time_in, b);
+	if (fill)
+		set_fields(&dt);
 }
 
 static int parse_num(const char *s, unsigned int n, unsigned int *out)
@@ -205,9 +216,31 @@ static void apply_now(void)
 	set_status("Date and time updated", 0);
 }
 
+static const char *ntp_error(int r)
+{
+	switch (r) {
+	case SYS_NTP_ENONIC:
+		return "NTP: no network adapter";
+	case SYS_NTP_ENAME:
+		return "NTP: cannot resolve the server";
+	case SYS_NTP_EARP:
+		return "NTP: server is unreachable (ARP)";
+	case SYS_NTP_ETX:
+		return "NTP: transmit failed";
+	case SYS_NTP_ETIMEOUT:
+		return "NTP: server did not respond";
+	case SYS_NTP_EREPLY:
+		return "NTP: invalid server reply";
+	case SYS_NTP_EBUSY:
+		return "NTP: network is busy";
+	default:
+		return "NTP: sync failed";
+	}
+}
+
 static unsigned int draw(void)
 {
-	struct ngui_rect body, r, date_r, time_r, set_r, now_r;
+	struct ngui_rect body, r, date_r, time_r, server_r, set_r, now_r, ntp_r;
 	unsigned int action = 0;
 	char line[64];
 	char *p;
@@ -246,23 +279,36 @@ static unsigned int draw(void)
 	time_r = ngui_cut_top(&body, 32);
 	ngui_cut_top(&body, 8);
 
+	r = ngui_cut_top(&body, 18);
+	ngui_text(&ui, r.x, r.y, "NTP server (UTC)", ui.theme.text_dim);
+	server_r = ngui_cut_top(&body, 32);
+	ngui_cut_top(&body, 8);
+
 	if (ngui_text_input(&ui, ID_DATE, date_r, &date_in) &
 	    NGUI_INPUT_SUBMIT)
 		action |= ACT_SET;
 	if (ngui_text_input(&ui, ID_TIME, time_r, &time_in) &
 	    NGUI_INPUT_SUBMIT)
 		action |= ACT_SET;
+	if (ngui_text_input(&ui, ID_SERVER, server_r, &ntp_in) &
+	    NGUI_INPUT_SUBMIT)
+		action |= ACT_NTP;
 
 	r = ngui_cut_top(&body, 40);
 	set_r = r;
-	set_r.w = 96;
+	set_r.w = 88;
 	now_r = r;
-	now_r.x = r.x + 104;
-	now_r.w = 96;
+	now_r.x = r.x + 96;
+	now_r.w = 88;
+	ntp_r = r;
+	ntp_r.x = r.x + 192;
+	ntp_r.w = 112;
 	if (ngui_button(&ui, ID_SET, set_r, "Set"))
 		action |= ACT_SET;
 	if (ngui_button(&ui, ID_NOW, now_r, "Now"))
 		action |= ACT_NOW;
+	if (ngui_button(&ui, ID_NTP, ntp_r, "Sync NTP"))
+		action |= ACT_NTP;
 
 	r = ngui_cut_top(&body, 24);
 	if (status[0] && status_until &&
@@ -271,6 +317,10 @@ static unsigned int draw(void)
 			  status_error ? ui.theme.error : ui.theme.accent);
 
 	r = ngui_cut_top(&body, 20);
+	ngui_text(&ui, r.x, r.y,
+		  "Sync NTP fetches UTC and writes the RTC.",
+		  ui.theme.text_dim);
+	r = ngui_cut_top(&body, 20);
 	ngui_text(&ui, r.x, r.y,
 		  "RTC year range: 1970-2069.  Enter applies the change.",
 		  ui.theme.text_dim);
@@ -278,13 +328,67 @@ static unsigned int draw(void)
 	return action;
 }
 
+static void set_contact_status(const char *server)
+{
+	static const char prefix[] = "Contacting ";
+	unsigned int i, n;
+
+	for (i = 0; prefix[i] && i + 1 < sizeof(status); i++)
+		status[i] = prefix[i];
+	for (n = 0; server[n] && i + 3 < sizeof(status); n++)
+		status[i++] = server[n];
+	status[i++] = '.';
+	status[i++] = '.';
+	status[i++] = '.';
+	status[i] = '\0';
+	status_error = 0;
+	status_until = u_ticks_ms() + 30000;
+	ngui_invalidate(&ui);
+}
+
+/* Publish the contact status before the blocking syscall. */
+static void paint_frame(void)
+{
+	if (!ngui_begin(&ui))
+		return;
+	draw();
+	ngui_end(&ui);
+}
+
+static void sync_ntp(void)
+{
+	struct sys_datetime dt;
+	const char *server = ntp_in.text[0] ? ntp_in.text : "pool.ntp.org";
+	int r;
+
+	set_contact_status(server);
+	paint_frame();
+
+	r = u_ntp_sync(ntp_in.text, 5000, &dt);
+	if (r != 0) {
+		set_status(ntp_error(r), 1);
+		return;
+	}
+	if (dt.year < 1970 || dt.year > 2069) {
+		set_status("NTP time is outside the RTC range", 1);
+		return;
+	}
+	if (u_rtc_set(&dt) != 0) {
+		set_status("NTP time received, RTC write failed", 1);
+		return;
+	}
+	current = dt;
+	set_fields(&dt);
+	set_status("NTP time applied (UTC)", 0);
+}
+
 void _start(const char *arg)
 {
 	struct win_info wi;
 	int quit = 0;
 
 	(void)arg;
-	if (u_win_create(460, 320, "Date & Time", &wi) != 0) {
+	if (u_win_create(460, 400, "Date & Time", &wi) != 0) {
 		u_puts("settime: no graphics window\n");
 		u_exit(1);
 	}
@@ -292,17 +396,11 @@ void _start(const char *arg)
 	ngui_font_attach(&ui);
 	date_in.placeholder = "YYYY-MM-DD";
 	time_in.placeholder = "HH:MM:SS";
+	ntp_in.placeholder = "pool.ntp.org";
+	ngui_input_set(&ntp_in, "pool.ntp.org");
 
 	if (u_rtc_get(&current) == 0) {
-		char b[24];
-		char *p;
-
-		p = put_date(b, &current);
-		*p = '\0';
-		ngui_input_set(&date_in, b);
-		p = put_time(b, &current);
-		*p = '\0';
-		ngui_input_set(&time_in, b);
+		set_fields(&current);
 	} else {
 		set_status("Cannot read the RTC", 1);
 	}
@@ -337,6 +435,8 @@ void _start(const char *arg)
 			apply_now();
 		if (action & ACT_NOW)
 			load_current(1);
+		if (action & ACT_NTP)
+			sync_ntp();
 		if (quit)
 			break;
 		u_sleep_ms(10);