Skip to content

gen_tcp: match OTP reuseaddr option - #2498

Open
UncleGrumpy wants to merge 4 commits into
atomvm:release-0.7from
UncleGrumpy:gen-tcp-reuseaddr
Open

UncleGrumpy wants to merge 4 commits into
atomvm:release-0.7from
UncleGrumpy:gen-tcp-reuseaddr

Conversation

@UncleGrumpy

Copy link
Copy Markdown
Collaborator

Make support for the gen_tcp reuseaddr option consistent with OTP on both backends and across platforms. Previously the option was not settable on any platform and was inconsistently enabled across platforms. Now matches OTP disabled by default.

Closes #2497

These changes are made under both the "Apache 2.0" and the "GNU Lesser General
Public License 2.1 or later" license terms (dual license).

SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later


start_server(Port, Router) ->
case gen_tcp:listen(Port, []) of
case gen_tcp:listen(Port, [{reuseaddr, true}]) of

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a temporary change needed for tests to pass. I have another PR coming that will make gen_tcp options passed here configurable to users, like inet_backend and reuseaddr options.

@petermm

petermm commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

AMP code, believe 1 and 2 should be ignored:

PR #2498 review: gen_tcp reuseaddr

Recommendation: request changes. The temporary HTTP opt-in prevents existing HTTP callers from starting on ESP-IDF 5.2 and 5.3. The new ESP32 runtime test also lacks a passing result in the failing Xtensa JIT job; the log shows a native-code mapping failure, not a demonstrated socket failure.

Reviewed all four commits in PR #2498, from base dd3d0ea93 to head a9f991d09. The local range matches the PR’s commit list:

  • 6499bc255 — report eaddrinuse on bind failure.
  • fb354983b — add opt-in reuse to inet.
  • 907f43006 — add the same option to socket.
  • a9f991d09 — opt HTTP into reuse and improve the HTTP test’s final retry error.

Findings

P1 — http_server:start_server/2 stops starting on ESP-IDF 5.2 and 5.3

http_server.erl:25–30 always requests {reuseaddr, true}. Without an explicit backend, gen_tcp.erl:247–252 selects inet. On ESP-IDF below 5.4, the ESP32 driver now rejects that option with {error, badarg} before binding, even on the first start on a free port. HTTP logs the error and never spawns an acceptor. Both older IDF versions are still in the CI matrix.

UncleGrumpy’s inline comment says the opt-in is temporary to keep tests passing and that a follow-up will expose inet_backend and reuseaddr to callers. Keep that API change in the follow-up, but preserve first-start behavior in this PR. One small interim fix is to retry without reuse only on the current unsupported-option result; do not retry on eaddrinuse or other bind failures. The fallback leaves older firmware with its original no-reuse behavior. If the driver gains a distinct unsupported-option error, match that instead.

--- a/libs/avm_network/src/http_server.erl
+++ b/libs/avm_network/src/http_server.erl
@@ start_server(Port, Router) ->
-    case gen_tcp:listen(Port, [{reuseaddr, true}]) of
+    ListenResult =
+        case gen_tcp:listen(Port, [{reuseaddr, true}]) of
+            {error, badarg} -> gen_tcp:listen(Port, []);
+            Result -> Result
+        end,
+    case ListenResult of

P2 — Duplicate options select different values on inet and socket

gen_tcp_inet.erl:102–113 forwards options in order. The generic Unix driver and ESP32 driver read the first occurrence, whereas gen_tcp_socket.erl:484–493 builds a last-wins map. Appending {reuseaddr, false} to defaults containing {reuseaddr, true} therefore keeps reuse enabled on inet and disables it on socket. On ESP-IDF below 5.4, the same list even fails on inet despite the final false. Stock OTP 29 returned the last value via inet:getopts/2 on both backends in both option orders.

Resolve only reuseaddr before backend dispatch, leaving precedence for unrelated options alone. Validate every occurrence while doing so: {reuseaddr, not_a_boolean} currently falls through as ignored, while OTP 29 rejects it with badarg on both backends, even when followed by a valid value. OTP 29 also rejects the bare reuseaddr atom on both backends.

--- a/libs/estdlib/src/gen_tcp.erl
+++ b/libs/estdlib/src/gen_tcp.erl
@@ listen(Port, Options) ->
     Module = get_inet_backend_module(Options),
-    case Module:listen(Port, Options) of
+    case Module:listen(Port, normalize_reuseaddr(Options)) of
@@
+normalize_reuseaddr(Options) ->
+    Value = lists:foldl(
+        fun
+            ({reuseaddr, Bool}, _) when is_boolean(Bool) -> Bool;
+            (Opt, _) when Opt =:= reuseaddr; element(1, Opt) =:= reuseaddr ->
+                erlang:error(badarg);
+            (_, Previous) -> Previous
+        end,
+        undefined,
+        Options
+    ),
+    case Value of
+        undefined -> Options;
+        _ -> [{reuseaddr, Value} | proplists:delete(reuseaddr, Options)]
+    end.

P2 — ESP32 inet reports success even when lwIP reuse is compiled out

The ESP32 driver checks only the IDF version. With ESP-IDF 5.4+ and CONFIG_LWIP_SO_REUSE disabled, it still sets the PCB flag and can return {ok, Socket} on a free port. ESP-IDF sets SO_REUSE to 0 in that configuration, and lwIP compiles out the reuse check. The listener cannot do what the option promises. This is a source-level finding for a non-default SDK configuration, not a hardware reproduction.

Use the same capability condition for the callback definition, the do_listen branch, and the two Unity expectations, with <lwip/opt.h> visible. The ESP32 tests should also make their socket expectation conditional: its setsockopt path can reject the option when lwIP support is disabled.

--- a/src/platforms/esp32/components/avm_builtins/socket_driver.c
+++ b/src/platforms/esp32/components/avm_builtins/socket_driver.c
@@ callback definition and do_listen guard (both sites)
-#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 0)
+#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 0) && SO_REUSE

P3 — Generic Unix changes more bind errors than advertised

do_bind is shared by TCP and UDP. Converting every errno, rather than just EADDRINUSE, removes the existing {bind, Errno} wrapper for other failures, such as EADDRNOTAVAIL when binding to a nonlocal address. If that compatibility change is intentional, document it for both protocols and test a non-EADDRINUSE case. If the commit is only about port collisions, preserve the old shape for other failures:

--- a/src/platforms/generic_unix/lib/socket_driver.c
+++ b/src/platforms/generic_unix/lib/socket_driver.c
@@ bind error path
-        // Match OTP, which reports the errno (e.g. eaddrinuse) for a failed bind
-        return port_create_error_tuple(ctx, posix_errno_to_term(errno, ctx->global));
+        int err = errno;
+        if (err == EADDRINUSE) {
+            return port_create_error_tuple(ctx, posix_errno_to_term(err, ctx->global));
+        }
+        return port_create_sys_error_tuple(ctx, BIND_ATOM, err);

Test suggestions and CI evidence

  • Make the server-first close deterministic. The generic Unix inet close handler replies before it closes the fd. On SMP, the subsequent client close can run first; the later timer:sleep(50) cannot repair that ordering. No flake was reproduced. Wait for EOF on the passive client before closing it. Apply the same sequencing to the connected ESP32 case and add explicit false as a negative control where TIME_WAIT blocks rebinding. The ESP32 listen-only test cannot show TIME_WAIT reuse because it never establishes a connection.

    --- a/tests/libs/estdlib/test_gen_tcp.erl
    +++ b/tests/libs/estdlib/test_gen_tcp.erl
    @@ rebind_after_server_close(InetBackend, ListenOpts) ->
         ok = gen_tcp:close(Socket),
    +    {error, closed} = gen_tcp:recv(ClientSocket, 0, 5000),
         ok = gen_tcp:close(ClientSocket),
  • Do not count the Xtensa JIT job as coverage. In the ESP32 v5.5.5 JIT log, test_tcp_reuseaddr starts, spi_flash_mmap(INST) fails, the loader reports no usable native chunk, and Unity fails the assertion at test_main.c:651. The existing test_socket also logs a native mapping failure; the run later panics and times out. Compare that job against the base revision and get a passing run of both new cases on ESP32 before attributing the failure to TCP or treating the behavior as covered. The sampled OTP comparison job instead reported test_binary_to_term failing; that log is not evidence of a TCP failure.

  • Do not count the HTTP test as a restart check. test_http_server.erl:27–35 starts the server once and kills the original handler after the request. accept/2 has already spawned its successor, and the test does not close the listener or rebind the port. This is a pre-existing lifecycle limitation, not a new regression. For the temporary opt-in, first add a first-start compatibility check on an older supported ESP-IDF build.

Local checks: git diff --check passed for the reviewed range. The extracted bind-collision and TIME_WAIT tests passed for both backends on stock OTP 29/macOS, which checks the reference behavior, not the AtomVM implementation. Consulted the oracle and checked its findings against the source. No local AtomVM or ESP32 runtime tests were run, and the snippets above were not applied.

Map EADDRINUSE in posix_errno_to_term, so the socket NIFs return
{error, eaddrinuse} instead of {error, 98}, and have the generic_unix
inet backend do_bind return {error, eaddrinuse} instead of
{error, {bind, 98}}, matching OTP.  The esp32 inet backend already
reported eaddrinuse (ERR_USE).

Signed-off-by: Winford <winford@object.stream>
The generic_unix inet backend set SO_REUSEADDR unconditionally on
listening sockets; make it opt-in with the {reuseaddr, true} option,
matching OTP where it defaults to off.  The esp32 inet backend, which
never set it, gains the same opt-in support on builds with ESP-IDF 5.4
or newer: SOF_REUSEADDR is set on the listener pcb before bind, from
the TCP/IP thread, as lwIP checks it in tcp_bind.  Older ESP-IDF ships
lwIP without the synchronous tcp/ip callback needed to safely set the
flag before bind, so there the option is rejected with
{error, badarg}.

Signed-off-by: Winford <winford@object.stream>
Apply the option to the listening socket before bind, mirroring OTP's
gen_tcp_socket, which sets the listen options before binding.  The
option is opt-in and defaults to off, as on OTP.

Signed-off-by: Winford <winford@object.stream>
Make http_server reuse addresses, this allows http_server to use ports
that are in free, but in TIME_WAIT (after being released).

Update test to return a connection error on failure, rather than crash
with an ambiguous function clause error.

Signed-off-by: Winford <winford@object.stream>
@UncleGrumpy

Copy link
Copy Markdown
Collaborator Author

AMP code, believe 1 and 2 should be ignored:

2 was valid, we want to be consistent with OTP, but I did not address P1. I will be opening a draft of the follow-on PR in the next day or so.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants