TCP/UDP `send #[]` returns early: succeeds on a closed TCP socket, and never sends the empty UDP datagram

Aperta
#16,807 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
3/5
Tempo stimato
1-2 giorni
Idoneità per principianti
72/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Ambito
networking

Direzione di ricerca

The affected entry points are lean_uv_tcp_send in src/runtime/uv/tcp.cpp and lean_uv_udp_send in src/runtime/uv/udp.cpp; read their empty-array branches and socket state checks first. Reproduce the TCP closed-socket case and UDP empty-datagram case with the supplied programs. Done means both behaviors match the issue’s expected results.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

bug
Prerequisites
  • Check that your issue is not already filed:
    https://github.com/leanprover/lean4/issues
  • Reduce the issue to a minimal, self-contained, reproducible test case.
    Avoid dependencies to Mathlib or Batteries.
  • Test your test case against the latest nightly release, for example on
    https://live.lean-lang.org/#project=lean-nightly
    (You can also use the settings there to switch to “Lean nightly”)
  • When reporting a perceived soundness bug: Does it affect lake check --paranoid?
    If in doubt, please reach out on [email protected] for responsible disclosure.
    (Not a soundness bug.)
Description

Both lean_uv_tcp_send and lean_uv_udp_send start with the same shortcut:

if (lean_array_size(data_array) == 0) {
    lean_object * promise = mk_mt_promise();
    resolve_with_code(0, promise);

    return lean_io_result_mk_ok(promise);
}

(src/runtime/uv/tcp.cpp:140-145, src/runtime/uv/udp.cpp:135-140). An empty buffer array returns a promise already resolved with .ok (), without consulting the socket and without submitting anything to libuv. This causes two different wrong results.

lean_uv_tcp_send: send #[] on a closed socket succeeds

The early return runs before the m_closed check at tcp.cpp:171. So send #[] on a closed socket succeeds, while send of one buffer fails with EBADF. The close docstring (src/Std/Internal/UV/TCP.lean:130-131) says every later operation on the socket fails, so this is a real inconsistency. But nothing is written, and the call does no harm.

The program creates a TCP server, binds and listens on 127.0.0.1:0, connects a client to it (the connect promise resolves ok), closes the client with Std.Internal.UV.TCP.Socket.close, and then calls send on that closed client twice, catching each error: once with the empty Array ByteArray #[] and once with #[ByteArray.mk #[1,2,3]]. The empty send reports success (an ok IO result holding a promise already resolved with .ok ()) although the socket was closed; it should have failed like the non-empty send on the same closed socket, which correctly returns IO.Error.invalidArgument (UV_EBADF). The only difference between the two calls is the number of buffers (0 versus 1).

Documented behavior it contradicts (docstring of Std.Internal.UV.TCP.Socket.close):

Closes a TCP socket. A pending read or accept fails, pending writes and shutdowns are cancelled, and
every later operation on the socket fails. Closing a closed socket does nothing.

lean_uv_udp_send: send #[] reports success but sends no datagram

udp.cpp:135-140 copies TCP's empty-array shortcut: send #[] resolves .ok () and never calls uv_udp_send. For TCP, zero buffers are a no-op, but for UDP a send is one datagram, and send #["".toUTF8] does deliver an empty datagram. So the number of buffers decides whether a datagram is sent, and recv (udp.cpp:202) treats an empty datagram as a real message. Std.Async.UDP send of an empty ByteArray wraps it as #[data] and is not affected; only sendAll #[] or the internal send #[] loses the datagram.

The program binds a receiver on 127.0.0.1, arms recv 65536 on it, then sends zero bytes to it with sender.send #[] (some addr) and waits for the send promise and (bounded by a 300 ms timer) for the receive: it prints "send ok" and then "NOTHING" — the send reports success yet no datagram is ever delivered. The same program with the single change #["".toUTF8] prints "send ok" and "RECEIVED 0": the same zero bytes are delivered as one empty datagram. So whether a zero-byte send reaches the peer depends only on how the zero bytes are split into buffers, which no documentation allows.

Context
  • Affected functions: lean_uv_tcp_send (src/runtime/uv/tcp.cpp), lean_uv_udp_send (src/runtime/uv/udp.cpp)
  • Upstream: no existing issue found; the cited code is unchanged in nightly-2026-11-26.
Steps to Reproduce
TCP
  1. Save the following as input.lean (imports only Init/Std):
import Std.Internal.UV.TCP
open Std.Net Std.Internal.UV

def report (label : String) (act : IO Unit) : IO Unit := do
  try
    act
    IO.println s!"{label}: ok"
  catch _ =>
    IO.println s!"{label}: error"

def main : IO Unit := do
  let server ← TCP.Socket.new
  TCP.Socket.bind server (SocketAddressV4.mk (.ofParts 127 0 0 1) 0)
  TCP.Socket.listen server 16
  let addr ← TCP.Socket.getSockName server
  let client ← TCP.Socket.new
  let connected ← TCP.Socket.connect client addr
  match connected.result?.get with
  | some (.ok _) => IO.println "connected"
  | some (.error _) => IO.println "connect-failed"
  | none => IO.println "connect-dropped"
  TCP.Socket.close client
  report "empty" (TCP.Socket.send client #[] >>= fun _ => pure ())
  report "nonempty" (TCP.Socket.send client #[ByteArray.mk #[1, 2, 3]] >>= fun _ => pure ())
  TCP.Socket.close server
  IO.println "done"
  1. Compile: lean -c input.c input.lean && leanc -o prog input.c
  2. Run: ./prog

Expected behavior:

connected
empty: error
nonempty: error
done

Actual behavior:

connected
empty: ok
nonempty: error
done
UDP
  1. Save the following as input.lean (imports only Init/Std):
import Std.Internal.UV.UDP
import Std.Internal.UV.Timer
import Std.Net.Addr

open Std.Net

def loopback : SocketAddress := .v4 (SocketAddressV4.mk (.ofParts 127 0 0 1) 0)

def main : IO Unit := do
  let receiver ← Std.Internal.UV.UDP.Socket.new
  receiver.bind loopback
  let addr ← receiver.getSockName
  let sender ← Std.Internal.UV.UDP.Socket.new
  sender.bind loopback
  let recvP ← receiver.recv 65536
  let sendP ← sender.send #[] (some addr)
  match ← IO.wait sendP.result? with
  | some (.ok ()) => IO.println "send ok"
  | some (.error e) => IO.println s!"send error: {e}"
  | none => IO.println "send promise dropped"
  let timer ← Std.Internal.UV.Timer.mk 300 false
  let timerP ← timer.next
  let recvT : Task String := recvP.result?.map (sync := true) fun
    | some (.ok (bytes, _)) => s!"RECEIVED {bytes.size}"
    | some (.error _) => "RECVERR"
    | none => "RECVDROPPED"
  let timerT : Task String := timerP.result?.map (sync := true) fun _ => "NOTHING"
  IO.println (← IO.waitAny [recvT, timerT])
  1. Compile and run as above. For comparison, change sender.send #[] (some addr) to sender.send #["".toUTF8] (some addr) (the only difference).

Expected behavior (as with #["".toUTF8], which prints exactly this):

send ok
RECEIVED 0

Actual behavior with #[]:

send ok
NOTHING
Versions

Lean (version 4.38.0-nightly-2026-11-26, arm64-apple-darwin24.6.0, commit e1228b8b45918ece1a00d68e5fc5e6a685ca59ee, Release)
macOS 26.6.2 (arm64)

Additional Information

Root cause analysis (TCP). The only functions on this path are lean_to_uv_tcp_socket, mk_mt_promise and resolve_with_code, which do what they should; the decision to answer without consulting the socket's closed state is taken inside lean_uv_tcp_send by the lean_array_size(data_array) == 0 early return at tcp.cpp:140-145, which runs before the m_closed ? UV_EBADF : uv_write(...) test at tcp.cpp:171.

Suggested fix (TCP): check m_closed before (or inside) the empty-array branch and return io_result_mk_uv_error(UV_EBADF).

Root cause analysis (UDP). The call receives input callers may pass: a live bound UDP socket, opt_addr = some a and data = #[] — exactly what Std.Internal.UV.UDP.Socket.send #[] (some a) (and Std.Async.UDP.Socket.sendAll s #[] (some a)) pass. It returns .ok of a promise it has already resolved with .ok () and submits no send at all, so the peer bound at a waits forever; it should have handed libuv one zero-length buffer through uv_udp_send — the same call with #["".toUTF8] does exactly that and its receiver gets the empty datagram, which is also what libuv does with a single zero-length buffer (recv_cb nread=0).

Suggested fix (UDP): drop the UDP short-circuit (or map the empty array to one zero-length buffer) so uv_udp_send is called and the completion callback resolves the promise, matching lean_uv_udp_recv's handling of a zero-length datagram.

Impact
  • TCP: only code that sends an empty buffer array after closing the socket sees a success instead of an error, with no data lost or memory affected.
  • UDP: code that sends an empty datagram (for example a heartbeat) as an empty buffer array reports success but sends nothing.

Add 👍 to issues you consider important. If others are impacted by this issue, please ask them to add 👍 to it.

Lingua principale
Lean
Stelle
10.3k
Fork
1.1k
Merge medio
16h 45m
PR unite (30g)
361

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di leanprover/lean4

Tutte le issue di leanprover/lean4

Issue simili

Altre issue su Networking

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.