Repository navigation
Conversation
… port Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
@JC-000, thank you for including me, and for building a working prototype instead of just asking. I owe you a clarification, though: my network work (the Ethernet drivers) is finished, and I should have taken myself off the contacts list for |
|
Hi @JC-000, nice work! About your questions, I left a comment on this topic on the issue that sparked this PR. It would be great if you could apply my comment and suggestion to your questions, carefully assess and compare the alternatives, and then suggest what the overall most defensible answers would be, and why. This would make the decision process more defensible and help reviewers understand which alternatives you considered. As part of this, it would also be interesting to think outside the box and check whether we could have addressed the user's original problem (playing games on C64U machines that communicate directly with each other) through other means, and what the pros and cons of those approaches would have been. Basically, taking a step back and assessing the overall design alternatives. There are usually many ways to solve a problem, and comparing them systematically first can help us decide more objectively. It often also helps to prototype and compare different prototypes before settling on one. I'm not saying that the approach you ended up taking isn't the ideal one, or that we will find a better one, but without further analysis, it's hard to say. It would be good to add this analysis to the PR description. Many thanks. |
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
@JC-000, thanks for building and testing this. @mfidder2026, thanks for testing direct play on two C64 Ultimates; that is useful evidence for the LAN game use case. Answering your question in #962: From the UCI side, For Q2, status numbers are target-local, so I would leave the proposed nonblocking READ as a separate follow-up after #1016, with its alternatives compared as Christian suggested. |
Ident (64), the DHCP client (68) and the VIC stream palette (53248) bind their port at a time of their own: when switched on, when a link comes up, when a stream starts. A socket holding the port then keeps the service down. Ident and the palette retry; the DHCP client never re-binds port 68 (lwIP ignores udp_bind's result, and udp_connect then takes an ephemeral port). OPEN_UDP_LOCAL now answers 89,PORT IN USE for those three ports on every product, whether or not the service is up. New E2E scenario udp-local-service-port-reserved switches ident off first, so only the reservation can refuse port 64, then expects 89 for 64 and 53248. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
@barryw @chrisgleissner Updated.
On TLS: #997's Written with Claude Opus 5.5 in Claude Code. |
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> # Conflicts: # software/io/network/network_target.cc
|
Merged the current master into this branch (596fc62). The conflicts were in network_target.cc. Master's new sliced connect and send now sit alongside this PR's local-port bind and its refusal of writes to a 0.0.0.0 remote, and both are kept. The socket is still tracked the way master requires, so an aborted OPEN_UDP_LOCAL closes its bound port. Written with Claude Sonnet 5.5 and Claude Opus 5.5 in Claude Code. |
|
@JC-000, thanks for adding and testing the service-port reservation. Yes: refusing ports 64, 68 and 53248 even when their services are inactive addresses the future-bind race I raised for the firmware's current fixed UDP ports. The normal bind failure covers ports already in use. I consider Q3 resolved; Gideon's remaining protocol questions and approval are separate. |
For #962. Ready for review. @barryw has reviewed the UCI side, and his and Christian's points are addressed below. Questions Q5–Q7 and approval of the protocol are @GideonZ's decision; the design analysis below sets them out.
What it does
NET_CMD_OPEN_UDP_LOCAL($0A) isOPEN_UDPwith a local port you choose. The socket is bound to that port before it is connected, so a program can be reached at a known UDP port (a game server that peers connect back to, UDP hole punching after a STUN lookup).OPEN_UDPdoes today.<HOST>is a dotted IPv4 address or a name, 1 to 253 bytes, with at most one trailing$00and nothing after it.$16(Spike for #807: NET_CMD_WRITE_SOCKET_CHUNK ($16), a payload larger than one command as one datagram #835) and CLOSE work on the handle as on anyOPEN_UDPsocket.OPEN_UDP: it only receives datagrams from that address and port. Opened to0.0.0.0, it receives from any address whose source port is the remote port, and a WRITE on it answers12,SEND ERROR: <errno>(EDESTADDRREQ) and sends nothing (Q7 in the design analysis).89,PORT IN USE, Q3), name resolution (84),socket()(85),bind()(89,PORT IN USEon EADDRINUSE, else 85),connect()(the existing11,ERROR ON CONNECT), read back the bound port (86 if that fails). The host is resolved before the bind, so a bad host never leaves a port bound.89,PORT IN USE. Status numbers are per target; 89 already meansCONFIG FILE HAD ERRORSin the control target andNOT A DISK IMAGEin the DOS target. 89 is the only free number in 81-97 of the network target (Q2).$03 $0A $00 $00 $00 $00 "0"(any host of 1-253 bytes): new firmware answers82,PARAMETER(S) OUT OF RANGEand opens nothing, older firmware answers21,UNKNOWN COMMAND. An empty host answers 81, because the command format is checked first.$80on the target byte) is refused with 81: a handle nobody reads can never be closed, and a leaked fixed port would stay bound. Same rule as TLS client sockets for the U64, through its ESP32 #997's$21.SO_REUSEADDR. A port held by anything on the UDP list, including firmware services (ident on 64 while enabled, DHCP on 68 while the device uses DHCP), answers 89; this is by readingudp_bind, I did not open 64 or 68. TCP sockets are on a separate list and never clash. A C64 reset closes the socket and frees the port; CLOSE frees it at once.OPEN_TCPandOPEN_UDPare unchanged: their call sites are untouched andopen_socketgets two defaulted parameters.Change
software/io/network/network_target.{h,cc}: +112/-7, both files CRLF and still CRLF. No ESP32 or lwIP configuration change, so no module IDENT change.tests/e2e/io/command_interface/net_target_test.py: eleven device scenarios, each on the rest and native routes.TESTSlist); I will rebase whichever lands second.Tests
Added to
net_target_test.py(profile DEEP, same helpers and both routes as the existing scenarios):udp-local-fixed-port-echoudp-local-port-zeroudp-local-port-in-useOPEN_UDPsource port answer 89 with no data; the owner still works; reopen after close; 20 refusals leak no descriptorudp-local-tcp-port-not-a-clashudp-local-bad-paramsudp-local-bad-host-keeps-port-freeudp-local-support-probeudp-local-pcb-exhaustionudp-local-reset-frees-portudp-local-any-host-is-receive-only0.0.0.0with the remote port of a host socket: a datagram from that port is read; a WRITE answers12,SEND ERROR: 121(EDESTADDRREQ) withFF FF, and the host sees no datagram within 3 sudp-local-service-port-reserved89,PORT IN USEwith no data; 68 is not tried, as DHCP holds itLossy datagram probes are retried as the file already does (
PROBE_ATTEMPTS). Three scenarios (fixed-port-echo, port-zero, port-in-use) compare the device's port with the source port the host sees, so host and device must be on the same LAN with no NAT between them.Hardware evidence
Current runs: red/green of the refusal and of the service-port reservation, on both devices. Images of master
99784768a(with #1018's route hook) plus #835 (full-size UDP, an open PR the bench images carry) plus this PR. RED is this PR's head before the refusal (43ef32cb5); GREEN is RED plus the refusal commit (b2ed34e0d, cherry-picked); the two differ only by that commit. Devices, both core 1.50: an Ultimate 64 Elite with master's ESP32 module, and a C64 Ultimate with a newer development build of its control module that was already on it (the updater kept it on the RED flash and, by the same version rule, on GREEN; not read back). Suites:uci-net-targetover Ethernet, and the tenudp-local-*scenarios over WiFi, each on the rest and native routes.udp-local-any-host-is-receive-onlyfails, on Ethernet and WiFi, both routes: its WRITE answers00,OKinstead of12,SEND ERROR: 121; everything else passesuci-net-targetin one attempt, the tenudp-local-*over WiFi on both routesuci-net-targetin one attempt, the tenudp-local-*over WiFi on both routesOn GREEN the new scenario gets
12,SEND ERROR: 121and the host receives no datagram within 3 s (the scenario's own check; no packet capture). This also covers the re-run of theudp-local-*scenarios on current master with #1018, on both interfaces.Service-port reservation (Q3). RED is the GREEN image above, without the reservation; GREEN2 is it plus the reservation commit (
269fecc7d, cherry-picked), the only difference. Same devices and modules.udp-local-service-port-reservedfails on both routes: local port 64 with ident off answers00,OK(the scenario stops at the first port)uci-net-targetover Ethernet in one attempt, the elevenudp-local-*over WiFi on both routes; 64 and 53248 answer89with no dataPort 68 is not tried on a device: DHCP already holds it, so the in-use check answers
89there anyway. The reservation covers it by code.Earlier run, before the refusal and before #1018: exact firmware on a C64 Ultimate. The same test file and host throughout (this Mac, macOS 27, Python 3.13, wired on the device's subnet with no NAT). RED is the official C64 Ultimate firmware 1.1.0 (FPGA 122, core 1.49): all 18
udp-local-*scenario runs (nine scenarios x rest and native) fail, every first$0Aanswering21,UNKNOWN COMMAND. GREEN is an image of master plus this PR plus #835,80b7b5a8(firmware 3.15a, FPGA 126, core 1.50, u64ctrl module 1.14 from master): the nineudp-local-*scenarios and the tenchunked-write-*scenarios of #835, both routes, 38 scenario runs, 129 checks, all OK. The GREEN run used the test file from the branch that merges #835; theudp-local-*scenarios in it are the ones in this PR. I did not run the standard profile.2180b7b5a8Secondary evidence: bench images. Earlier runs of only the nine new scenarios (18 rows each), same host, on bench builds:
42d8134e(no$0A)21b0b1978a(42d8134e+ this change)f8e673df(no$0A)2168fe10cfDisclosure for the bench rows: those images carry other open work besides this change: #835 and #953 on both, the WiFi modules on ESP-IDF 6 (#996, and a C64 Ultimate control-module port that is not proposed yet), and on the U64E also #997 and two bench-only merge fixes. This change was cherry-picked into them (
b0b1978a,e084ce00) with patch lines identical toc6e1f854. The new scenarios use only$0A, OPEN_TCP/OPEN_UDP, READ, WRITE and CLOSE.Not run on hardware: U2/U2+/U2+L and the plain U64 (the rig has a U64E and a C64U). The code is the same source for every target.
Targets built
Six buildable targets use this file. I built
u64(Nios II) andu64ii(RISC-V): no warning fromnetwork_target.cc, U64 1229.1 KiB of 1472.0 KiB (master 1228.7). CI builds the rest; the tightest, U2, has 34.4 KiB free at master. MicroBlaze (u2) is unbuildable at master since 7ea644d deletedsoftware/lwip-1.4.1, which its makefile still builds from; the code does not depend on byte order anyway (the port is built with shifts andntohs/PP_NTOHS).Device-free suites on
43ef32cb: macOS (Python 3.13) and Kubuntu 24.04 (Python 3.12.3). On both,lintpasses andregistryfails identically atcc4af99e(directory_rename_test.pyunregistered). On macOS the observability suite also fails identically atcc4af99e, with Homebrew ffmpeg 9.0.2 (-vsyncremoved). On Kubuntu 15 suites pass, including observability; the two manual suitesweb-themeandweb-indexfail because the image has no browser.Design analysis
The need behind #962: two C64 Ultimates run the same lockstep game and exchange joystick inputs every frame (50/60 Hz, 17-20 ms), on one LAN, ideally also across the internet, and find each other without typing an IP. Line numbers are at master
99784768; lwIP is thesoftware/lwipsubmodule.The same need is being met in parallel on other 8-bit platforms. On the NES, nesp32 maps controller input to packets: patched two-player builds of Contra, Dr. Mario, Tetris and TMNT II exchange controller input over UDP, meet through a rendezvous, learn their public address from Cloudflare's (
stun.cloudflare.com, 3478/udp, "free and unlimited") and Google's STUN servers, and punch through both routers (MULTIPLAYER.md). That is the setup in your 10-05 comment, each machine running its own game and exchanging inputs, and the hole punching$0Amakes possible here: a fixed local port, so the address STUN reports is the one the peer can reach.Could it be done without a firmware change?
What the firmware offers today: the UCI opens (
$07,$08) dosocket()andconnect()with nobind()and reply with the handle only (network_target.cc:184-251); there is no listen, accept or recvfrom. A connected UDP socket accepts only datagrams from its remote's address and port (lwIPsrc/core/udp.c:289-291). Every UCI socket waits up to 40 ms on an empty READ (network_target.cc:247-250), and one task runs every UCI command (command_intf.cc:59,167), so that wait holds up the next WRITE too. Outside the UCI, the modem emulation listens on TCP (modem.cc:71,:891-892), and the DMA service and REST can write another machine's memory. Every UCI route needs the Command Interface, which is disabled by default (c64.cc:115).Options with no firmware change
$08(Michel ships one: mfidder2026/Commodore64_Gameserver)ATD host:3000through its own ACIA, or opens$07to itATDon both sides the game needs only a SwiftLink driver and no Command Interface; received bytes land in the ACIA's receive buffer (modem.cc:204-221), so a driver in IRQ or NMI mode has no READ to wait onrecv()times out, so up to the Loop Delay (20 ms default, 10 ms minimum,modem.cc:89,:159-165,:186-262) on the sending side; the guest gets the connect banner on every connection, unless the Connect Text setting points to an existing empty file (modem.cc:287-289,:845-857); TCP holds back later inputs behind a lost segment; one connection at a time, so two players (modem.cc:280-281); internet only with a port forward$08udp.c:100-119), so a third party could help a program guess, but any other ephemeral open in between (a streamer, SNTP, another UCI socket) breaks the guessnetwork_config.cc:22) or RESTwritememsocket_dma.cc:109-116,:476-479); each write stops the peer's CPU for the transfer (c64_subsys.cc:589-591; not measured); the receiver can only poll its RAMModem-route figures are from the code, not run.
So the relay works everywhere, and the modem emulation already gives a direct LAN link between two C64 Ultimates with one setting. The modem route's real costs are TCP's stall on loss, up to one Loop Delay on each send, two players at most, and a port forward for the internet.
Alternatives that need a change
Options with a firmware or setup change
$0A, this PR)$08; hole punching after a STUN lookup behind endpoint-independent NATs; Michel's test program (C64U-H2H) and his games' head-to-head mode use it (Commodore64_Gameserver README)21, so a game can fall back); symmetric NATs still need a relay; the 40 ms READ wait applies, as on every UCI socket$00on$08$00(network_target.cc:196,:202) and opens and connects a socket on an ephemeral port before the program can see, from the 1-byte reply, that the port was not taken; and any existing program that sends bytes there would change behaviour on new firmware. Ruled out$12-$15(numbers already in xlar54's and barryw's libraries)RECVFROM/SENDTO)Against your criteria, for the realistic choices:
$08)$0A$07/$08, same socket modelnetwork_target.cconly$07/$08udp-local-*scenarios on both routes, run red/green on a U64 Elite and a C64 Ultimate21: fall back21: fall back0.0.0.0for discovery, Q7)Answer: keep this PR at its current size. It is the smallest change that gives a UCI program a port its peer can reach, and it keeps the socket model games already use with a relay, so one game can do both. The modem emulation is a real alternative on a LAN, and it beats every UCI route on receive today, because the UCI's 40 ms READ wait hits
$0Aas hard as$08. That wait is a separate problem with its own follow-up in #962 (a READ that doesn't wait), not a reason to prefer TCP's stalls and the modem's send delay.$0Ais not the whole internet answer: a rendezvous server is still needed, and symmetric NATs still need a relay.The PR's own questions
Q1. Command number. Agreed by @barryw.
$0A, next to the other opens. The alternative "a byte after the host's$00on$08" is ruled out above; another free number gains nothing; one generic OPEN with a type byte mixes TCP's TIME_WAIT rebind rules into UDP.$0Akeeps$0Bfree for an OPEN_TCP_LOCAL with the same layout. None of xlar54's, barryw's or Michel's libraries use$0A-$0Ffor anything else.Q2. Port in use. Agreed by @barryw (status numbers are per target).
89,PORT IN USE. Alternatives:10,ERROR ON BIND: <errno>(1x codes carry an errno, like11and12, but the program would parse the errno for the one case it acts on); reusing85(can't be told apart from running out of sockets). 87 and 88 are taken by #953. Status numbers are already per target (87 and 88 differ between the control and DOS targets), so 89 meaning something else elsewhere only affects a library that maps numbers to text without the target.Q3. Service ports.
$0Arefuses the three UDP ports the firmware binds itself, with89,PORT IN USEand no data, on every product, whether that service is on or not: 64 (ident), 68 (DHCP client) and 53248 (the VIC stream's palette, U64 family). @barryw pointed out that an in-use check protects only a service that is already bound, and each of these can bind later: ident when switched on (socket_dma.cc:537-563), DHCP when a link comes up or DHCP is switched on (network_interface.cc:354-360,:426-438), the palette when a VIC stream with palette starts (data_streamer.cc:358-383). If a program held the port then, ident and the palette retry and recover once it is free. The DHCP client does not: lwIP ignores the failed bind (dhcp.c:288), connect then gives it a random port (udp.c:1084-1085), and it gets no lease until every DHCP interface goes down (from the code, not run). Every other port stays open, below 1024 too. TCP services can't collide: lwIP keeps UDP and TCP ports apart.udp-local-service-port-reservedswitches ident off, checks that 64 and 53248 answer89with no data, and restores the setting. RED without the reservation (64 answers00,OK) and GREEN with it, on a U64 Elite and a C64 Ultimate. Port 68 isn't tried on a device, because DHCP already holds it there and the in-use check answers89anyway; the reservation covers it by code.Q4. Refusals. Agreed by @barryw. Remote port 0 →
82: a connected socket with remote port 0 matches only a sender using source port 0 (udp.c:289), and the refusal makes the support probe side-effect free. No-reply bit →81: the reply is dropped (command_intf.cc:170-171), so the handle would never be seen and the port would stay bound until reset. Bytes afterhost $00→81: refusing keeps that space for a detectable option later, which$07/$08lost by ignoring them.Q5.
MEMP_NUM_UDP_PCB= 8 (software/network/config/lwipopts.h:197). No change in this PR. A game needs 2 sockets (rendezvous and peer; the STUN lookup goes out from the peer's local port before that socket is opened to the peer; Michel's H2H holds 2 while searching). Counted from the code, the samelwipopts.hfor the U64/U64E (Nios) and the Elite II/C64U (RISC-V):UDP pcbs the firmware holds
src/core/ipv4/dhcp.c:234-235,:275-293)network_config.cc:29,sntp_time.cc:21-31)network_config.cc:21,socket_dma.cc:543)network_config.cc:26,syslog.cc:112)palette=1(data_streamer.cc:358-388,:402-411)data_streamer.cc:144); starting one opens a socket for an ARP probe and closes it (:325-356)DNS_TABLE_SIZE(lwipopts.h:547;dns.c:146-152,:884-907,:1000-1013); with the pool empty a lookup shares another lookup's pcb if one is in flight, and otherwise fails (:919-948)mdns_resp_init()is never called, so its pcb is never madeOn defaults that leaves 5, which matches the 5 a program could open on both test devices (measured, streams off). A DNS lookup in flight (SNTP's, or a stream started by name) or a stream's ARP probe takes one more for a moment, so a program could see
85on its second open only if two of those moments overlap while every optional user is on. A pcb is 40 bytes on these 32-bit, IPv4-only builds (lwIPsrc/include/lwip/udp.h:81-113), so 16 would cost 320 bytes. Sockets stay capped byMEMP_NUM_NETCONN= 16 (lwipopts.h:255) after a raise. If you want that margin, I'll send it as its own one-line change.With every optional user on (VIC palette, syslog), 3 are left (from the code), so 2 fit with one to spare. Measured on the C64U with the VIC, audio and debug streams running: still 5, the sixth open answers
85, so the streams hold none. The palette and syslog cases are counted from the code, not measured.Q6. Wired and WiFi both up. Follow the route, as
$07/$08do; no change in this PR.$0AbindsINADDR_ANY, so #1018's route hook applies (network_interface.cc:511-514,route_select.h): a peer on a local subnet goes by the wired interface first. For a peer on the internet the hook makes no choice and lwIP uses its default interface, the first one that is up with an address (network_interface.cc:221-233); interface 0 is the wired port (data_streamer.cc:144), so with both up an internet peer goes wired too. Same LAN or not, the wired link almost always gives lower and steadier latency than WiFi, which is why the route matters for games and why wired first is the right default. Pinning would belong to all opens at once (the disabledNET_CMD_SET_INTERFACE,network_target.cc:67-79).Q7. Discovery:
$0Ato0.0.0.0. Supported, receive-only. Michel's C64U-H2H finds the other C64 by broadcasting a HELLO from one$0Asocket and listening on another opened to0.0.0.0; neither side writes to its0.0.0.0socket (#962,src/main.c:472-580). What this means:0.0.0.0(or a host that resolves to it) with a remote port: the socket accepts a datagram from any address whose source port is that remote port, and drops the rest (lwIPsrc/core/udp.c:289-291). Remote port 0 is still refused (Q4), so there is no "any port" form.$0Asocket, and returns subnet broadcasts too: lwIP's per-socket broadcast filters are off on every product (IP_SOF_BROADCASTandIP_SOF_BROADCAST_RECV= 0,software/network/config/lwipopts.h:401,:407).12,SEND ERROR: <errno>(EDESTADDRREQ), the existing WRITE-failure format, and sends nothing. Refusing at open instead would break the receive-only use. Without the refusal lwIP sends it, as$08does today (observed on a C64U: an$08WRITE to0.0.0.0returned00,OKand left as an Ethernet broadcast with IP destination0.0.0.0, which a Mac on the LAN delivered to its socket):udp_send()goes to the default interface (ip4.c:204-227), andetharp_output()treats0.0.0.0as a broadcast (ip4_addr.c:63-66,etharp.c:807-809), so the datagram leaves as an Ethernet broadcast with IP destination0.0.0.0. RFC 1122 3.2.1.3(a):0.0.0.0"MUST NOT be sent, except as a source address"; 3.3.6 tolerates it only as an old BSD broadcast form, off by default. Fixing$08is a separate change, and a fix must weigh that other lwIP stacks accept destination0.0.0.0as a broadcast, so an$08program may rely on it. To announce, a program opens a second$0Ato the subnet broadcast address, as Michel's host does.connect()to0.0.0.0means this host (FreeBSDsys/netinet/in_pcb.c: the primary local address; Linuxnet/ipv4/route.c: loopback). Here it means "any sender", from lwIP. The documentation will say so.Still open: Q5, Q6 and Q7 (
0.0.0.0as receive-only), and approval of the protocol, from @GideonZ. Q1, Q2 and Q4 are agreed by @barryw for the UCI side, and Q3 is answered by the reserved ports (@barryw: say if this covers the race you meant).Before it leaves draft: @GideonZ's decisions above, and the docs#37 update (the reserved ports, Q7's meaning, and the relay and modem routes as the options on older firmware).
Follow-ups (OPEN_TCP_LOCAL
$0B, the TCP listener at$12-$15, unconnected UDP, a READ that doesn't wait) are discussed in #962 and not part of this PR. The nonblocking READ comes after #1016, with its own comparison of alternatives. Nothing that depends on this PR will be opened before it is merged.Like
OPEN_UDP,$0Aresolves a host name withgethostbyname_ron the UCI Server task (software/io/network/network_target.cc:252), so a slow DNS lookup holds the UCI until it finishes. This PR does not change that. Moving network waits off the UCI Server task is the separate problem raised in #1043.The same socket model is the base for encryption later. #997 (draft, U64 and U64 Elite) adds TLS client sockets:
$21opens one and returns an ordinary handle, the ESP32 module runs the handshake and the crypto, and READ, WRITE and CLOSE work on it unchanged (plan in #952, issue #995). #997 defines$21-$25; its own open is$21OPEN_TLS. TLS from a fixed local port would be a future$0B(OPEN_TCP_LOCAL) followed by #997's$24START_TLS, which upgrades a connected TCP socket. DTLS (encrypted UDP) on$0A-style sockets is planned, not built, and has no command number yet. Neither is part of this PR or promised by it.AI use
Code, tests and docs were written with Claude Sonnet 5.5 in Claude Code, including the
0.0.0.0WRITE refusal and the service-port reservation commits. The design analysis was written with Claude Opus 5.5 in Claude Code. Separate Claude Opus 5.5 sessions reviewed the spec, the code and tests, and this PR before it was opened, and their findings are fixed in it. I have read and can explain every line.cc @barryw (UCI) @chrisgleissner (
tests/) @GideonZ🤖 Generated with Claude Code