Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions Lib/test/test_socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -3286,6 +3286,26 @@ def testRecvFromNegative(self):
def _testRecvFromNegative(self):
self.cli.sendto(MSG, 0, (HOST, self.port))

# gh-160622: with MSG_TRUNC, recv() and recvfrom() must not return
# more bytes than requested, even if the datagram was longer.
@requireAttrs(socket, "MSG_TRUNC")
@unittest.skipIf(sys.platform == "win32", "Windows raises WSAEMSGSIZE")
def testRecvTrunc(self):
msg = self.serv.recv(2, socket.MSG_TRUNC)
self.assertEqual(msg, MSG[:2])

def _testRecvTrunc(self):
self.cli.sendto(MSG, 0, (HOST, self.port))

@requireAttrs(socket, "MSG_TRUNC")
@unittest.skipIf(sys.platform == "win32", "Windows raises WSAEMSGSIZE")
def testRecvFromTrunc(self):
msg, addr = self.serv.recvfrom(2, socket.MSG_TRUNC)
self.assertEqual(msg, MSG[:2])

def _testRecvFromTrunc(self):
self.cli.sendto(MSG, 0, (HOST, self.port))


@unittest.skipUnless(HAVE_SOCKET_UDPLITE,
'UDPLITE sockets required for this test.')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
:meth:`socket.socket.recv` and :meth:`socket.socket.recvfrom` no longer
raise :exc:`ValueError` and lose the datagram when called with
``MSG_TRUNC`` and the datagram is longer than *bufsize*. Only the bytes
actually received are returned now.
10 changes: 10 additions & 0 deletions Modules/socketmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -4066,6 +4066,12 @@ _socket_socket_recv_impl(PySocketSockObject *s, Py_ssize_t recvlen,
PyBytesWriter_Discard(writer);
return NULL;
}
/* With MSG_TRUNC, recv() can return the real length of the datagram,
which may be larger than the buffer. Only recvlen bytes were
written. */
if (outlen > recvlen) {
outlen = recvlen;
}

return PyBytesWriter_FinishWithSize(writer, outlen);
}
Expand Down Expand Up @@ -4242,6 +4248,10 @@ _socket_socket_recvfrom_impl(PySocketSockObject *s, Py_ssize_t recvlen,
PyBytesWriter_Discard(writer);
goto error;
}
/* See the comment in _socket_socket_recv_impl(). */
if (outlen > recvlen) {
outlen = recvlen;
}

PyObject *buf = PyBytesWriter_FinishWithSize(writer, outlen);
if (buf == NULL) {
Expand Down
Loading