aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCaleb Maclennan <caleb@alerque.com>2026-08-31 11:00:36 +0300
committerGitHub <noreply@github.com>2026-08-31 11:00:36 +0300
commitb836466de5a78e9b4f29ca6c85a2bdecd7c69da9 (patch)
tree465b3b3a8121b1625b7ee3c9fba2e1f3cdce8a3c
parent8f18ce95bb38c7f5c4bef5b3684cf1b0df1fc266 (diff)
parent75d638ac9cc613f39ec4513d3dc2e43a6f909da1 (diff)
downloadluasocket-b836466de5a78e9b4f29ca6c85a2bdecd7c69da9.tar.gz
luasocket-b836466de5a78e9b4f29ca6c85a2bdecd7c69da9.tar.bz2
luasocket-b836466de5a78e9b4f29ca6c85a2bdecd7c69da9.zip
Merge pull request #471 from lunarmodules/fix/zero-read
fix(receive): a receive 0 should immediately return, not block
-rw-r--r--.github/workflows/build.yml3
-rw-r--r--src/buffer.c23
-rw-r--r--src/udp.c12
-rw-r--r--src/usocket.c2
-rw-r--r--src/wsocket.c9
-rw-r--r--test/test_tcp_receive_zero.lua36
-rw-r--r--test/test_udp_receive_zero.lua267
-rw-r--r--test/test_unixdgram_receive_zero.lua200
8 files changed, 542 insertions, 10 deletions
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 53d6ebc..e8a4117 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -49,4 +49,7 @@ jobs:
49 lua mimetest.lua 49 lua mimetest.lua
50 lua urltest.lua 50 lua urltest.lua
51 lua test_socket_error.lua 51 lua test_socket_error.lua
52 lua test_tcp_receive_zero.lua
53 lua test_udp_receive_zero.lua
54 [ "$RUNNER_OS" = "Windows" ] || lua test_unixdgram_receive_zero.lua
52 kill %1 55 kill %1
diff --git a/src/buffer.c b/src/buffer.c
index 3d48a09..b7e97f7 100644
--- a/src/buffer.c
+++ b/src/buffer.c
@@ -11,7 +11,7 @@
11static int recvraw(p_buffer buf, size_t wanted, luaL_Buffer *b); 11static int recvraw(p_buffer buf, size_t wanted, luaL_Buffer *b);
12static int recvline(p_buffer buf, luaL_Buffer *b, size_t budget); 12static int recvline(p_buffer buf, luaL_Buffer *b, size_t budget);
13static int recvall(p_buffer buf, luaL_Buffer *b, size_t budget); 13static int recvall(p_buffer buf, luaL_Buffer *b, size_t budget);
14static int buffer_get(p_buffer buf, const char **data, size_t *count); 14static int buffer_get(p_buffer buf, const char **data, size_t *count, size_t wanted);
15static void buffer_skip(p_buffer buf, size_t count); 15static void buffer_skip(p_buffer buf, size_t count);
16static int sendraw(p_buffer buf, const char *data, size_t count, size_t *sent); 16static int sendraw(p_buffer buf, const char *data, size_t count, size_t *sent);
17 17
@@ -230,15 +230,14 @@ static int sendraw(p_buffer buf, const char *data, size_t count, size_t *sent) {
230static int recvraw(p_buffer buf, size_t wanted, luaL_Buffer *b) { 230static int recvraw(p_buffer buf, size_t wanted, luaL_Buffer *b) {
231 int err = IO_DONE; 231 int err = IO_DONE;
232 size_t total = 0; 232 size_t total = 0;
233 while (err == IO_DONE) { 233 do {
234 size_t count; const char *data; 234 size_t count; const char *data;
235 err = buffer_get(buf, &data, &count); 235 err = buffer_get(buf, &data, &count, wanted - total);
236 count = MIN(count, wanted - total); 236 count = MIN(count, wanted - total);
237 luaL_addlstring(b, data, count); 237 luaL_addlstring(b, data, count);
238 buffer_skip(buf, count); 238 buffer_skip(buf, count);
239 total += count; 239 total += count;
240 if (total >= wanted) break; 240 } while (total < wanted && err == IO_DONE);
241 }
242 return err; 241 return err;
243} 242}
244 243
@@ -253,7 +252,7 @@ static int recvall(p_buffer buf, luaL_Buffer *b, size_t budget) {
253 size_t total = 0; 252 size_t total = 0;
254 while (err == IO_DONE) { 253 while (err == IO_DONE) {
255 const char *data; size_t count; 254 const char *data; size_t count;
256 err = buffer_get(buf, &data, &count); 255 err = buffer_get(buf, &data, &count, BUF_SIZE);
257 if (budget && count > budget - total) { /* strictly more than fits */ 256 if (budget && count > budget - total) { /* strictly more than fits */
258 count = budget - total; 257 count = budget - total;
259 luaL_addlstring(b, data, count); 258 luaL_addlstring(b, data, count);
@@ -286,7 +285,7 @@ static int recvline(p_buffer buf, luaL_Buffer *b, size_t budget) {
286 size_t total = 0; 285 size_t total = 0;
287 while (err == IO_DONE) { 286 while (err == IO_DONE) {
288 size_t count, pos; const char *data; 287 size_t count, pos; const char *data;
289 err = buffer_get(buf, &data, &count); 288 err = buffer_get(buf, &data, &count, BUF_SIZE);
290 pos = 0; 289 pos = 0;
291 while (pos < count && data[pos] != '\n') { 290 while (pos < count && data[pos] != '\n') {
292 /* we ignore all \r's -- they are consumed but never counted */ 291 /* we ignore all \r's -- they are consumed but never counted */
@@ -325,15 +324,19 @@ static void buffer_skip(p_buffer buf, size_t count) {
325 324
326/*-------------------------------------------------------------------------*\ 325/*-------------------------------------------------------------------------*\
327* Return any data available in buffer, or get more data from transport layer 326* Return any data available in buffer, or get more data from transport layer
328* if buffer is empty 327* if buffer is empty. 'wanted' is how many more bytes the caller is still
328* after; when it is zero, the transport layer is still consulted (so an
329* already-closed connection is still reported), but no more than zero bytes
330* are requested from it, so a healthy connection with no data pending can
331* never block.
329\*-------------------------------------------------------------------------*/ 332\*-------------------------------------------------------------------------*/
330static int buffer_get(p_buffer buf, const char **data, size_t *count) { 333static int buffer_get(p_buffer buf, const char **data, size_t *count, size_t wanted) {
331 int err = IO_DONE; 334 int err = IO_DONE;
332 p_io io = buf->io; 335 p_io io = buf->io;
333 p_timeout tm = buf->tm; 336 p_timeout tm = buf->tm;
334 if (buffer_isempty(buf)) { 337 if (buffer_isempty(buf)) {
335 size_t got; 338 size_t got;
336 err = io->recv(io->ctx, buf->data, BUF_SIZE, &got, tm); 339 err = io->recv(io->ctx, buf->data, wanted == 0 ? 0 : BUF_SIZE, &got, tm);
337 buf->first = 0; 340 buf->first = 0;
338 buf->last = got; 341 buf->last = got;
339 } 342 }
diff --git a/src/udp.c b/src/udp.c
index 6c0d39e..6d017da 100644
--- a/src/udp.c
+++ b/src/udp.c
@@ -283,6 +283,7 @@ static int meth_receivefrom(lua_State *L) {
283 lua_pushliteral(L, "out of memory"); 283 lua_pushliteral(L, "out of memory");
284 return 2; 284 return 2;
285 } 285 }
286 memset(&addr, 0, sizeof(addr));
286 err = socket_recvfrom(&udp->sock, dgram, wanted, &got, (SA *) &addr, 287 err = socket_recvfrom(&udp->sock, dgram, wanted, &got, (SA *) &addr,
287 &addr_len, tm); 288 &addr_len, tm);
288 /* Unlike TCP, recv() of zero is not closed, but a zero-length packet. */ 289 /* Unlike TCP, recv() of zero is not closed, but a zero-length packet. */
@@ -292,6 +293,17 @@ static int meth_receivefrom(lua_State *L) {
292 if (wanted > sizeof(buf)) free(dgram); 293 if (wanted > sizeof(buf)) free(dgram);
293 return 2; 294 return 2;
294 } 295 }
296 /* a zero-length request may be satisfied by some kernels (notably
297 * Darwin/BSD) without ever touching the sender's address -- only
298 * resolve it when the OS actually reported one, instead of feeding
299 * getnameinfo() a garbage/zeroed sockaddr. */
300 if (addr.ss_family != AF_INET && addr.ss_family != AF_INET6) {
301 lua_pushlstring(L, dgram, got);
302 lua_pushnil(L);
303 lua_pushnil(L);
304 if (wanted > sizeof(buf)) free(dgram);
305 return 3;
306 }
295 err = getnameinfo((struct sockaddr *)&addr, addr_len, addrstr, 307 err = getnameinfo((struct sockaddr *)&addr, addr_len, addrstr,
296 INET6_ADDRSTRLEN, portstr, 6, NI_NUMERICHOST | NI_NUMERICSERV); 308 INET6_ADDRSTRLEN, portstr, 6, NI_NUMERICHOST | NI_NUMERICSERV);
297 if (err) { 309 if (err) {
diff --git a/src/usocket.c b/src/usocket.c
index 7965db6..e00c43d 100644
--- a/src/usocket.c
+++ b/src/usocket.c
@@ -258,6 +258,7 @@ int socket_recv(p_socket ps, char *data, size_t count, size_t *got, p_timeout tm
258 int err; 258 int err;
259 *got = 0; 259 *got = 0;
260 if (*ps == SOCKET_INVALID) return IO_CLOSED; 260 if (*ps == SOCKET_INVALID) return IO_CLOSED;
261 if (count == 0) return IO_DONE;
261 for ( ;; ) { 262 for ( ;; ) {
262 long taken = (long) recv(*ps, data, count, 0); 263 long taken = (long) recv(*ps, data, count, 0);
263 if (taken > 0) { 264 if (taken > 0) {
@@ -343,6 +344,7 @@ int socket_read(p_socket ps, char *data, size_t count, size_t *got, p_timeout tm
343 int err; 344 int err;
344 *got = 0; 345 *got = 0;
345 if (*ps == SOCKET_INVALID) return IO_CLOSED; 346 if (*ps == SOCKET_INVALID) return IO_CLOSED;
347 if (count == 0) return IO_DONE;
346 for ( ;; ) { 348 for ( ;; ) {
347 long taken = (long) read(*ps, data, count); 349 long taken = (long) read(*ps, data, count);
348 if (taken > 0) { 350 if (taken > 0) {
diff --git a/src/wsocket.c b/src/wsocket.c
index d3af9d4..b2b668c 100644
--- a/src/wsocket.c
+++ b/src/wsocket.c
@@ -247,6 +247,7 @@ int socket_recv(p_socket ps, char *data, size_t count, size_t *got,
247 int err, prev = IO_DONE; 247 int err, prev = IO_DONE;
248 *got = 0; 248 *got = 0;
249 if (*ps == SOCKET_INVALID) return IO_CLOSED; 249 if (*ps == SOCKET_INVALID) return IO_CLOSED;
250 if (count == 0) return IO_DONE;
250 for ( ;; ) { 251 for ( ;; ) {
251 int taken = recv(*ps, data, (int) count, 0); 252 int taken = recv(*ps, data, (int) count, 0);
252 if (taken > 0) { 253 if (taken > 0) {
@@ -285,6 +286,14 @@ int socket_recvfrom(p_socket ps, char *data, size_t count, size_t *got,
285 } 286 }
286 if (taken == 0) return IO_CLOSED; 287 if (taken == 0) return IO_CLOSED;
287 err = WSAGetLastError(); 288 err = WSAGetLastError();
289 /* a zero-length request is trivially "too small" for any
290 * non-empty datagram; unlike POSIX, which truncates and succeeds
291 * silently, Windows reports this as WSAEMSGSIZE even though the
292 * datagram -- and its sender's address, already written to addr/
293 * len above -- was still consumed. Normalize it to match POSIX's
294 * silent-truncation instead of surfacing a platform-specific
295 * error for what is otherwise a successful, if empty, receive. */
296 if (count == 0 && err == WSAEMSGSIZE) return IO_DONE;
288 /* On UDP, a connreset simply means the previous send failed. 297 /* On UDP, a connreset simply means the previous send failed.
289 * So we try again. 298 * So we try again.
290 * On TCP, it means our socket is now useless, so the error passes. 299 * On TCP, it means our socket is now useless, so the error passes.
diff --git a/test/test_tcp_receive_zero.lua b/test/test_tcp_receive_zero.lua
new file mode 100644
index 0000000..2259910
--- /dev/null
+++ b/test/test_tcp_receive_zero.lua
@@ -0,0 +1,36 @@
1-- a TCP receive(0) must never block: requesting zero bytes is trivially
2-- satisfied without touching the transport layer, POSIX recv(fd, buf, 0, 0)
3-- returns immediately regardless of whether data is available.
4local socket = require "socket"
5
6local host, port = "127.0.0.1", "5464"
7
8local server = assert(socket.bind(host, port))
9local client = assert(socket.connect(host, port))
10local peer = assert(server:accept())
11
12client:settimeout(2)
13
14-- no data has been sent by the peer: the read buffer is empty, so if
15-- receive(0) touches the network it will block until the timeout expires
16local t0 = socket.gettime()
17local data, err = client:receive(0)
18local elapsed = socket.gettime() - t0
19
20assert(data == "", "receive(0) on empty buffer returned " .. tostring(data))
21assert(err == nil, "receive(0) on empty buffer returned error " .. tostring(err))
22assert(elapsed < 1, "receive(0) on empty buffer blocked for " .. elapsed .. "s")
23
24-- receive(0) must also not consume any bytes when data *is* available
25assert(peer:send("hello"))
26data, err = client:receive(0)
27assert(data == "", "receive(0) with data pending returned " .. tostring(data))
28assert(err == nil, "receive(0) with data pending returned error " .. tostring(err))
29data = assert(client:receive(5))
30assert(data == "hello", "receive(0) consumed bytes meant for receive(5)")
31
32client:close()
33peer:close()
34server:close()
35
36print("done!")
diff --git a/test/test_udp_receive_zero.lua b/test/test_udp_receive_zero.lua
new file mode 100644
index 0000000..f3ca090
--- /dev/null
+++ b/test/test_udp_receive_zero.lua
@@ -0,0 +1,267 @@
1#!/usr/bin/env lua
2
3-- "receive 0 bytes" on a UDP socket is really two different requests that
4-- happen to share one call shape:
5--
6-- (a) "give me a side-effect-free readiness probe" -- don't touch
7-- anything, just tell me instantly whether I'd have blocked.
8-- (b) "my protocol's messages are always empty-payload signals (UDP
9-- explicitly allows a zero-length datagram on the wire -- see
10-- udp-zero-length-send-recv in this same directory); receive one
11-- like any other, I just don't need a payload back."
12--
13-- These two conflict on at least one real platform. A Darwin/BSD kernel's
14-- recvfrom() returns 0 bytes immediately for a zero-length request
15-- whether or not anything was actually queued -- so byte count alone can
16-- never distinguish (a) from (b) there. Linux and (per MSDN's
17-- recv()/recvfrom() docs -- no exception is carved out for SOCK_DGRAM the
18-- way there is for "byte stream-style sockets" and WSAEINVAL, though this
19-- is not independently confirmed against a live Windows kernel) Windows
20-- both block until something real arrives, so they don't have this
21-- ambiguity at all.
22--
23-- platform | nothing pending | datagram pending
24-- ------------+------------------------------+---------------------------
25-- Linux | blocks until one arrives | consumed & reported
26-- Windows | blocks until one arrives * | consumed & reported *
27-- Darwin/BSD | returns 0 immediately, | consumed & reported
28-- | never blocks |
29--
30-- What breaks the tie: receivefrom() also reports the sender's address,
31-- and that address comes back unpopulated when nothing was queued and
32-- correctly populated when a real datagram was consumed -- on every
33-- platform, Darwin included. So while byte count can't disambiguate (a)
34-- from (b) on Darwin, the address can. receivefrom(0) is therefore left
35-- to make the real recvfrom() call: it correctly serves use case (b)
36-- everywhere, and on Darwin specifically it gives an honest "nil address"
37-- for (a) instead of the alternative this test suite used to ship -- a
38-- crash out of getnameinfo() on a garbage/unpopulated sockaddr.
39--
40-- receive() has no such disambiguator (no address field to check), so
41-- unguarding it would only buy back blocking-until-signal on Linux/
42-- Windows while remaining just as ambiguous as before on Darwin. It's
43-- left as the deterministic no-op it already was (LuaSocket's TCP
44-- receive(0) fix, inherited via the shared socket_recv()) -- and that
45-- happens to be exactly what Python's socket.recv(0) already does
46-- (CPython's sock_recv_guts), for the same reason.
47--
48-- How other cross-platform standard libraries handle this, checked at the
49-- source level rather than the docs:
50--
51-- language | receive()-equivalent | receivefrom()-equivalent
52-- ---------+-------------------------+---------------------------------------
53-- Go | UDPConn.Read: guarded, | UDPConn.ReadFrom: unguarded, and built
54-- | deterministic no-op | the same way LuaSocket's own
55-- | (internal/poll. | socket_recvfrom() is: try the syscall
56-- | FD.Read) | first (internal/poll.FD.ReadFrom calls
57-- | | syscall.Recvfrom directly), only wait
58-- | | after EAGAIN. Almost certainly shares
59-- | | the Darwin quirk above as a result;
60-- | | not confirmed whether Go's sockaddr
61-- | | conversion crashes or silently zeroes
62-- | | on an address the kernel never filled
63-- | | in.
64-- Python | socket.recv(): | socket.recvfrom(): sock_recvfrom_guts
65-- | guarded, determin- | has no len==0 guard either, but does
66-- | istic no-op | NOT hit the Darwin quirk in practice --
67-- | (sock_recv_guts) | it blocks for the full timeout with
68-- | | nothing pending, same as Linux would.
69-- | | CPython's sock_call_ex runs a real
70-- | | select()/poll() readiness gate
71-- | | (internal_select()) before ever
72-- | | calling recvfrom(), for any operation
73-- | | with a timeout. That gate reports
74-- | | "not readable" honestly regardless of
75-- | | the requested length, so the quirk
76-- | | never gets a chance to fire. It's a
77-- | | side effect of Python's general
78-- | | blocking-with-timeout architecture,
79-- | | not anything specific to recvfrom()
80-- | | or to len==0.
81-- Rust | UdpSocket::recv: | UdpSocket::recv_from: unguarded,
82-- | unguarded, platform- | platform-dependent -- straight to
83-- | dependent | libc::recvfrom, no select-gate, no
84-- | | len==0 guard anywhere.
85--
86-- So "platform-dependent" isn't actually the right label for every
87-- unguarded implementation. Go shares LuaSocket's original exposure to
88-- the Darwin quirk because it shares the same try-syscall-first shape;
89-- Python avoids the quirk entirely, but via unrelated select-gating
90-- machinery, not via anything resembling the address-population check
91-- this fix adds. None of the three has that specific fix; LuaSocket adds
92-- it here.
93
94local socket = require "socket"
95
96local host = "127.0.0.1"
97
98local function new_pair(port)
99 local server = assert(socket.udp())
100 assert(server:setsockname(host, port))
101 local client = assert(socket.udp())
102 assert(client:setpeername(host, port))
103 server:settimeout(1)
104 return server, client
105end
106
107-- Detects which of the three documented recvfrom(0)-with-nothing-pending
108-- behaviors applies here, so the test below can assert the right one by
109-- name instead of accepting either shape. "unknown" is the honest answer
110-- when uname isn't available to tell Linux and Darwin/BSD apart (e.g. a
111-- locked-down sandbox); the test falls back to accepting either
112-- documented shape in that case, rather than guessing.
113local function detect_platform()
114 if package.config:sub(1, 1) == "\\" then
115 return "windows"
116 end
117 local handle = io.popen("uname -s 2>/dev/null")
118 if not handle then
119 return "unknown"
120 end
121 local name = handle:read("*l")
122 handle:close()
123 if not name then
124 return "unknown"
125 end
126 name = name:lower()
127 if name:find("linux") then
128 return "linux"
129 elseif name:find("darwin") or name:find("bsd") then
130 return "darwin"
131 end
132 return "unknown"
133end
134
135local platform = detect_platform()
136
137-- === receive(0): deterministic no-op, nothing pending ===
138do
139 local server, client = new_pair("5465")
140
141 local t0 = socket.gettime()
142 local data, err = server:receive(0)
143 local elapsed = socket.gettime() - t0
144 assert(data == "" and err == nil,
145 "receive(0) with nothing pending returned " .. tostring(data) .. ", " .. tostring(err))
146 assert(elapsed < 0.5,
147 "receive(0) with nothing pending blocked for " .. elapsed .. "s")
148
149 client:close()
150 server:close()
151end
152
153-- === receive(0): deterministic no-op, a datagram pending must be left untouched ===
154do
155 local server, client = new_pair("5466")
156
157 assert(client:send("world"))
158 socket.sleep(0.1)
159
160 local data, err = server:receive(0)
161 assert(data == "" and err == nil,
162 "receive(0) with data pending returned " .. tostring(data) .. ", " .. tostring(err))
163
164 data = assert(server:receive())
165 assert(data == "world",
166 "receive(0) consumed or corrupted the pending datagram: got " .. tostring(data))
167
168 client:close()
169 server:close()
170end
171
172-- === receivefrom(0): nothing pending -- the outcome is platform-specific
173-- (see the comment block at the top of this file), asserted explicitly
174-- per platform so it's clear which behavior is expected where ===
175do
176 local server, client = new_pair("5467")
177
178 local data, ip, port = server:receivefrom(0)
179
180 if platform == "linux" or platform == "windows" then
181 -- both block until a real datagram arrives; nothing does, so the
182 -- call must time out, not fabricate a result
183 assert(data == nil and ip == "timeout",
184 "receivefrom(0) with nothing pending on " .. platform ..
185 " should time out, got " .. tostring(data) .. ", " .. tostring(ip))
186
187 elseif platform == "darwin" then
188 -- the kernel's zero-length recvfrom() is always immediately
189 -- satisfiable, so this must return right away, with no address
190 assert(data == "" and ip == nil and port == nil,
191 "receivefrom(0) with nothing pending on darwin should return " ..
192 "immediately with no address, got " ..
193 tostring(data) .. ", " .. tostring(ip) .. ", " .. tostring(port))
194
195 else
196 -- platform could not be determined: accept either documented
197 -- shape rather than assert one and risk a false failure
198 local timed_out_like_linux_or_windows = data == nil and ip == "timeout"
199 local returned_immediately_like_darwin = data == "" and ip == nil and port == nil
200 assert(timed_out_like_linux_or_windows or returned_immediately_like_darwin,
201 "receivefrom(0) with nothing pending returned an unexpected shape: " ..
202 tostring(data) .. ", " .. tostring(ip) .. ", " .. tostring(port))
203 end
204
205 client:close()
206 server:close()
207end
208
209-- === receivefrom(0): a datagram is pending -- must be consumed and its
210-- sender correctly reported, on every platform ===
211do
212 local server, client = new_pair("5468")
213
214 assert(client:send("hello"))
215 socket.sleep(0.1)
216
217 local data, ip, port = server:receivefrom(0)
218 assert(data == "" and ip == "127.0.0.1" and type(port) == "number",
219 "receivefrom(0) with data pending returned " ..
220 tostring(data) .. ", " .. tostring(ip) .. ", " .. tostring(port))
221
222 -- the payload is gone (all that a 0-byte request can ever return), but
223 -- unlike a crash or a phantom no-op, the caller correctly learned that
224 -- something arrived and who sent it
225 server:settimeout(0.3)
226 data = server:receive()
227 assert(data == nil,
228 "receivefrom(0) did not actually consume the pending datagram: receive() still got " ..
229 tostring(data))
230
231 client:close()
232 server:close()
233end
234
235-- === the real-world case this whole file is about: a protocol whose
236-- messages are always empty-payload signals. A 0-length UDP datagram is
237-- a completely legitimate thing to put on the wire (see
238-- udp-zero-length-send-recv), and receivefrom(0) must work as a normal
239-- receive path for it -- reporting the (empty) payload and the sender --
240-- not just as a probe for some other, larger message. ===
241do
242 local server, client = new_pair("5469")
243
244 -- sanity check: a genuine zero-length datagram over the wire, read
245 -- with a normal-sized buffer, already works (untouched by any of this)
246 assert(client:send(""))
247 socket.sleep(0.1)
248 local data, ip, port = server:receivefrom()
249 assert(data == "" and ip == "127.0.0.1" and type(port) == "number",
250 "a real zero-length datagram, read normally, returned " ..
251 tostring(data) .. ", " .. tostring(ip) .. ", " .. tostring(port))
252
253 -- the actual point: a receiver that knows every message on this
254 -- socket is an empty signal can use receivefrom(0) as its normal
255 -- receive call, and still learn who signaled it
256 assert(client:send(""))
257 socket.sleep(0.1)
258 data, ip, port = server:receivefrom(0)
259 assert(data == "" and ip == "127.0.0.1" and type(port) == "number",
260 "receivefrom(0) as a normal receive path for a signal datagram returned " ..
261 tostring(data) .. ", " .. tostring(ip) .. ", " .. tostring(port))
262
263 client:close()
264 server:close()
265end
266
267print("done!")
diff --git a/test/test_unixdgram_receive_zero.lua b/test/test_unixdgram_receive_zero.lua
new file mode 100644
index 0000000..c91c3cd
--- /dev/null
+++ b/test/test_unixdgram_receive_zero.lua
@@ -0,0 +1,200 @@
1#!/usr/bin/env lua
2
3-- Same reasoning as test_udp_receive_zero.lua: "receive 0 bytes" on a
4-- datagram socket is really two different requests sharing one call
5-- shape -- (a) a side-effect-free readiness probe, and (b) "my protocol's
6-- messages are always empty-payload signals, receive one normally, I
7-- just don't need a payload back" (a zero-length datagram is a
8-- completely legitimate thing to put on the wire).
9--
10-- receive() has no sender-address field to disambiguate (a) from (b), so
11-- it stays the deterministic no-op it already was via the shared
12-- socket_recv() guard (unaffected here, same as TCP). receivefrom() does
13-- have that field: unlike inet UDP, unixdgram.c already handled an
14-- unpopulated sender path gracefully (it pre-zeroes sun_path and just
15-- returns whatever's there -- see the "may be empty when client sent
16-- without bind" comment in unixdgram.c), so receivefrom(0) here was
17-- never at risk of the getnameinfo crash inet UDP had. It's left making
18-- the real recvfrom() call: nothing pending is platform-dependent
19-- (blocks on Linux/Windows, returns immediately on Darwin/BSD -- see the
20-- platform table in test_udp_receive_zero.lua), but a pending datagram is
21-- always correctly consumed and its sender always correctly reported.
22
23local socket = require "socket"
24local unix = require "socket.unix"
25
26local function new_pair(server_path, client_path)
27 os.remove(server_path)
28 os.remove(client_path)
29 local server = assert(unix.dgram())
30 assert(server:bind(server_path))
31 local client = assert(unix.dgram())
32 assert(client:bind(client_path))
33 assert(client:connect(server_path))
34 server:settimeout(1)
35 return server, client
36end
37
38local function cleanup(server, client, server_path, client_path)
39 client:close()
40 server:close()
41 os.remove(server_path)
42 os.remove(client_path)
43end
44
45-- Detects which of the three documented recvfrom(0)-with-nothing-pending
46-- behaviors applies here, so the test below can assert the right one by
47-- name instead of accepting either shape. "unknown" is the honest answer
48-- when uname isn't available to tell Linux and Darwin/BSD apart (e.g. a
49-- locked-down sandbox); the test falls back to accepting either
50-- documented shape in that case, rather than guessing.
51local function detect_platform()
52 if package.config:sub(1, 1) == "\\" then
53 return "windows"
54 end
55 local handle = io.popen("uname -s 2>/dev/null")
56 if not handle then
57 return "unknown"
58 end
59 local name = handle:read("*l")
60 handle:close()
61 if not name then
62 return "unknown"
63 end
64 name = name:lower()
65 if name:find("linux") then
66 return "linux"
67 elseif name:find("darwin") or name:find("bsd") then
68 return "darwin"
69 end
70 return "unknown"
71end
72
73local platform = detect_platform()
74
75-- === receive(0): deterministic no-op, nothing pending ===
76do
77 local spath, cpath = "/tmp/luasocket-test-udgram-1-srv.sock", "/tmp/luasocket-test-udgram-1-clt.sock"
78 local server, client = new_pair(spath, cpath)
79
80 local t0 = socket.gettime()
81 local rdata, rerr = server:receive(0)
82 local elapsed = socket.gettime() - t0
83 assert(rdata == "" and rerr == nil,
84 "receive(0) with nothing pending returned " .. tostring(rdata) .. ", " .. tostring(rerr))
85 assert(elapsed < 0.5,
86 "receive(0) with nothing pending blocked for " .. elapsed .. "s")
87
88 cleanup(server, client, spath, cpath)
89end
90
91-- === receive(0): deterministic no-op, a datagram pending must be left untouched ===
92do
93 local spath, cpath = "/tmp/luasocket-test-udgram-2-srv.sock", "/tmp/luasocket-test-udgram-2-clt.sock"
94 local server, client = new_pair(spath, cpath)
95
96 assert(client:send("world"))
97 socket.sleep(0.1)
98
99 local data, err = server:receive(0)
100 assert(data == "" and err == nil,
101 "receive(0) with data pending returned " .. tostring(data) .. ", " .. tostring(err))
102
103 data, err = assert(server:receive())
104 assert(data == "world",
105 "receive(0) consumed or corrupted the pending datagram: got " .. tostring(data))
106
107 cleanup(server, client, spath, cpath)
108end
109
110-- === receivefrom(0): nothing pending -- the outcome is platform-specific
111-- (see the comment block at the top of test_udp_receive_zero.lua),
112-- asserted explicitly per platform so it's clear which behavior is
113-- expected where ===
114do
115 local spath, cpath = "/tmp/luasocket-test-udgram-3-srv.sock", "/tmp/luasocket-test-udgram-3-clt.sock"
116 local server, client = new_pair(spath, cpath)
117
118 local data, addr = server:receivefrom(0)
119
120 if platform == "linux" or platform == "windows" then
121 -- both block until a real datagram arrives; nothing does, so the
122 -- call must time out, not fabricate a result
123 assert(data == nil and addr == "timeout",
124 "receivefrom(0) with nothing pending on " .. platform ..
125 " should time out, got " .. tostring(data) .. ", " .. tostring(addr))
126
127 elseif platform == "darwin" then
128 -- the kernel's zero-length recvfrom() is always immediately
129 -- satisfiable, so this must return right away, with no sender path
130 assert(data == "" and addr == "",
131 "receivefrom(0) with nothing pending on darwin should return " ..
132 "immediately with no sender path, got " ..
133 tostring(data) .. ", " .. tostring(addr))
134
135 else
136 -- platform could not be determined: accept either documented
137 -- shape rather than assert one and risk a false failure
138 local timed_out_like_linux_or_windows = data == nil and addr == "timeout"
139 local returned_immediately_like_darwin = data == "" and addr == ""
140 assert(timed_out_like_linux_or_windows or returned_immediately_like_darwin,
141 "receivefrom(0) with nothing pending returned an unexpected shape: " ..
142 tostring(data) .. ", " .. tostring(addr))
143 end
144
145 cleanup(server, client, spath, cpath)
146end
147
148-- === receivefrom(0): a datagram is pending -- must be consumed and its
149-- sender correctly reported, on every platform ===
150do
151 local spath, cpath = "/tmp/luasocket-test-udgram-4-srv.sock", "/tmp/luasocket-test-udgram-4-clt.sock"
152 local server, client = new_pair(spath, cpath)
153
154 assert(client:send("hello"))
155 socket.sleep(0.1)
156
157 local data, addr = server:receivefrom(0)
158 assert(data == "" and addr == cpath,
159 "receivefrom(0) with data pending returned " .. tostring(data) .. ", " .. tostring(addr))
160
161 server:settimeout(0.3)
162 data = server:receive()
163 assert(data == nil,
164 "receivefrom(0) did not actually consume the pending datagram: receive() still got " ..
165 tostring(data))
166
167 cleanup(server, client, spath, cpath)
168end
169
170-- === the real-world case this whole file is about: a protocol whose
171-- messages are always empty-payload signals. receivefrom(0) must work as
172-- a normal receive path for it -- reporting the (empty) payload and the
173-- sender -- not just as a probe for some other, larger message. ===
174do
175 local spath, cpath = "/tmp/luasocket-test-udgram-5-srv.sock", "/tmp/luasocket-test-udgram-5-clt.sock"
176 local server, client = new_pair(spath, cpath)
177
178 -- sanity check: a genuine zero-length datagram, read with a
179 -- normal-sized buffer, already works (untouched by any of this)
180 assert(client:send(""))
181 socket.sleep(0.1)
182 local data, addr = server:receivefrom()
183 assert(data == "" and addr == cpath,
184 "a real zero-length datagram, read normally, returned " ..
185 tostring(data) .. ", " .. tostring(addr))
186
187 -- the actual point: a receiver that knows every message on this
188 -- socket is an empty signal can use receivefrom(0) as its normal
189 -- receive call, and still learn who signaled it
190 assert(client:send(""))
191 socket.sleep(0.1)
192 data, addr = server:receivefrom(0)
193 assert(data == "" and addr == cpath,
194 "receivefrom(0) as a normal receive path for a signal datagram returned " ..
195 tostring(data) .. ", " .. tostring(addr))
196
197 cleanup(server, client, spath, cpath)
198end
199
200print("done!")