Skip to content

Commit fd5b30e

Browse files
authored
Align socket and socketserver with Python 3.15 (#9156)
Import the canonical socket libraries and tests through update_lib, preserving the existing AF_ALG expected failures. Match setsockopt index/buffer conversion and error ordering, mask optlen with the final CPython deprecation warning, reject oversized Windows buffers before the host call, and preserve arbitrary-precision getaddrinfo ports and empty canonical names. Assisted-by: OpenAI Codex:model version unavailable
1 parent 1ee9a29 commit fd5b30e

5 files changed

Lines changed: 317 additions & 101 deletions

File tree

‎Lib/socket.py‎

Lines changed: 79 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
import os
5757
import sys
5858
from enum import IntEnum, IntFlag
59+
from functools import partial
5960

6061
try:
6162
import errno
@@ -122,7 +123,7 @@ def _intenum_converter(value, enum_klass):
122123
10004: "The operation was interrupted.",
123124
10009: "A bad file handle was passed.",
124125
10013: "Permission denied.",
125-
10014: "A fault occurred on the network??",
126+
10014: "An invalid pointer was passed.",
126127
10022: "An invalid operation was attempted.",
127128
10024: "Too many open files.",
128129
10035: "The socket operation would block.",
@@ -180,7 +181,7 @@ def _intenum_converter(value, enum_klass):
180181
11001: "Host not found.",
181182
11002: "Nonauthoritative host not found.",
182183
11003: "This is a nonrecoverable error.",
183-
11004: "Valid name, no data record requested type.",
184+
11004: "Valid name, no data record of requested type.",
184185
11005: "QoS receivers.",
185186
11006: "QoS senders.",
186187
11007: "No QoS senders.",
@@ -196,7 +197,7 @@ def _intenum_converter(value, enum_klass):
196197
11017: "QoS flowspec error.",
197198
11018: "Invalid QoS provider buffer.",
198199
11019: "Invalid QoS filter style.",
199-
11020: "Invalid QoS filter style.",
200+
11020: "Invalid QoS filter type.",
200201
11021: "Incorrect QoS filter count.",
201202
11022: "Invalid QoS object length.",
202203
11023: "Incorrect QoS flow count.",
@@ -348,75 +349,83 @@ def makefile(self, mode="r", buffering=None, *,
348349
text.mode = mode
349350
return text
350351

351-
if hasattr(os, 'sendfile'):
352+
def _sendfile_zerocopy(self, zerocopy_func, giveup_exc_type, file,
353+
offset=0, count=None):
354+
"""
355+
Send a file using a zero-copy function.
356+
"""
357+
import selectors
352358

353-
def _sendfile_use_sendfile(self, file, offset=0, count=None):
354-
# Lazy import to improve module import time
355-
import selectors
359+
self._check_sendfile_params(file, offset, count)
360+
sockno = self.fileno()
361+
try:
362+
fileno = file.fileno()
363+
except (AttributeError, io.UnsupportedOperation) as err:
364+
raise giveup_exc_type(err) # not a regular file
365+
try:
366+
fsize = os.fstat(fileno).st_size
367+
except OSError as err:
368+
raise giveup_exc_type(err) # not a regular file
369+
if not fsize:
370+
return 0 # empty file
371+
# Truncate to 1GiB to avoid OverflowError, see bpo-38319.
372+
blocksize = min(count or fsize, 2 ** 30)
373+
timeout = self.gettimeout()
374+
if timeout == 0:
375+
raise ValueError("non-blocking sockets are not supported")
376+
# poll/select have the advantage of not requiring any
377+
# extra file descriptor, contrarily to epoll/kqueue
378+
# (also, they require a single syscall).
379+
if hasattr(selectors, 'PollSelector'):
380+
selector = selectors.PollSelector()
381+
else:
382+
selector = selectors.SelectSelector()
383+
selector.register(sockno, selectors.EVENT_WRITE)
356384

357-
self._check_sendfile_params(file, offset, count)
358-
sockno = self.fileno()
359-
try:
360-
fileno = file.fileno()
361-
except (AttributeError, io.UnsupportedOperation) as err:
362-
raise _GiveupOnSendfile(err) # not a regular file
363-
try:
364-
fsize = os.fstat(fileno).st_size
365-
except OSError as err:
366-
raise _GiveupOnSendfile(err) # not a regular file
367-
if not fsize:
368-
return 0 # empty file
369-
# Truncate to 1GiB to avoid OverflowError, see bpo-38319.
370-
blocksize = min(count or fsize, 2 ** 30)
371-
timeout = self.gettimeout()
372-
if timeout == 0:
373-
raise ValueError("non-blocking sockets are not supported")
374-
# poll/select have the advantage of not requiring any
375-
# extra file descriptor, contrarily to epoll/kqueue
376-
# (also, they require a single syscall).
377-
if hasattr(selectors, 'PollSelector'):
378-
selector = selectors.PollSelector()
379-
else:
380-
selector = selectors.SelectSelector()
381-
selector.register(sockno, selectors.EVENT_WRITE)
382-
383-
total_sent = 0
384-
# localize variable access to minimize overhead
385-
selector_select = selector.select
386-
os_sendfile = os.sendfile
387-
try:
388-
while True:
389-
if timeout and not selector_select(timeout):
390-
raise TimeoutError('timed out')
391-
if count:
392-
blocksize = min(count - total_sent, blocksize)
393-
if blocksize <= 0:
394-
break
395-
try:
396-
sent = os_sendfile(sockno, fileno, offset, blocksize)
397-
except BlockingIOError:
398-
if not timeout:
399-
# Block until the socket is ready to send some
400-
# data; avoids hogging CPU resources.
401-
selector_select()
402-
continue
403-
except OSError as err:
404-
if total_sent == 0:
405-
# We can get here for different reasons, the main
406-
# one being 'file' is not a regular mmap(2)-like
407-
# file, in which case we'll fall back on using
408-
# plain send().
409-
raise _GiveupOnSendfile(err)
410-
raise err from None
411-
else:
412-
if sent == 0:
413-
break # EOF
414-
offset += sent
415-
total_sent += sent
416-
return total_sent
417-
finally:
418-
if total_sent > 0 and hasattr(file, 'seek'):
419-
file.seek(offset)
385+
total_sent = 0
386+
# localize variable access to minimize overhead
387+
selector_select = selector.select
388+
try:
389+
while True:
390+
if timeout and not selector_select(timeout):
391+
raise TimeoutError('timed out')
392+
if count:
393+
blocksize = min(count - total_sent, blocksize)
394+
if blocksize <= 0:
395+
break
396+
try:
397+
sent = zerocopy_func(fileno, offset, blocksize)
398+
except BlockingIOError:
399+
if not timeout:
400+
# Block until the socket is ready to send some
401+
# data; avoids hogging CPU resources.
402+
selector_select()
403+
continue
404+
except OSError as err:
405+
if total_sent == 0:
406+
# We can get here for different reasons, the main
407+
# one being 'file' is not a regular mmap(2)-like
408+
# file, in which case we'll fall back on using
409+
# plain send().
410+
raise giveup_exc_type(err)
411+
raise err from None
412+
else:
413+
if sent == 0:
414+
break # EOF
415+
offset += sent
416+
total_sent += sent
417+
return total_sent
418+
finally:
419+
if total_sent > 0 and hasattr(file, 'seek'):
420+
file.seek(offset)
421+
422+
if hasattr(os, 'sendfile'):
423+
def _sendfile_use_sendfile(self, file, offset=0, count=None):
424+
return self._sendfile_zerocopy(
425+
partial(os.sendfile, self.fileno()),
426+
_GiveupOnSendfile,
427+
file, offset, count,
428+
)
420429
else:
421430
def _sendfile_use_sendfile(self, file, offset=0, count=None):
422431
raise _GiveupOnSendfile(

‎Lib/socketserver.py‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -120,9 +120,6 @@ class will essentially render the service "deaf" while one request is
120120

121121
# Author of the BaseServer patch: Luke Kenneth Casson Leighton
122122

123-
__version__ = "0.4"
124-
125-
126123
import socket
127124
import selectors
128125
import os
@@ -441,7 +438,7 @@ class TCPServer(BaseServer):
441438

442439
socket_type = socket.SOCK_STREAM
443440

444-
request_queue_size = 5
441+
request_queue_size = getattr(socket, "SOMAXCONN", 5)
445442

446443
allow_reuse_address = False
447444

@@ -861,3 +858,12 @@ def setup(self):
861858

862859
def finish(self):
863860
self.socket.sendto(self.wfile.getvalue(), self.client_address)
861+
862+
863+
def __getattr__(name):
864+
if name == "__version__":
865+
from warnings import _deprecated
866+
867+
_deprecated("__version__", remove=(3, 20))
868+
return "0.4" # Do not change
869+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")

‎Lib/test/test_socket.py‎

Lines changed: 88 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88
import _thread as thread
99
import array
1010
import contextlib
11+
import decimal
1112
import errno
13+
import fractions
1214
import gc
1315
import io
1416
import itertools
@@ -1349,10 +1351,20 @@ def testDefaultTimeout(self):
13491351
self.assertEqual(s.gettimeout(), None)
13501352

13511353
# Set the default timeout to 10, and see if it propagates
1352-
with socket_setdefaulttimeout(10):
1353-
self.assertEqual(socket.getdefaulttimeout(), 10)
1354+
with socket_setdefaulttimeout(10.125):
1355+
self.assertEqual(socket.getdefaulttimeout(), 10.125)
13541356
with socket.socket() as sock:
1355-
self.assertEqual(sock.gettimeout(), 10)
1357+
self.assertEqual(sock.gettimeout(), 10.125)
1358+
1359+
socket.setdefaulttimeout(decimal.Decimal('11.125'))
1360+
self.assertEqual(socket.getdefaulttimeout(), 11.125)
1361+
with socket.socket() as sock:
1362+
self.assertEqual(sock.gettimeout(), 11.125)
1363+
1364+
socket.setdefaulttimeout(fractions.Fraction(97, 8))
1365+
self.assertEqual(socket.getdefaulttimeout(), 12.125)
1366+
with socket.socket() as sock:
1367+
self.assertEqual(sock.gettimeout(), 12.125)
13561368

13571369
# Reset the default timeout to None, and see if it propagates
13581370
socket.setdefaulttimeout(None)
@@ -1580,6 +1592,40 @@ def testSetSockOpt(self):
15801592
reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
15811593
self.assertFalse(reuse == 0, "failed to set reuse mode")
15821594

1595+
def test_setsockopt_errors(self):
1596+
# See issue #107546.
1597+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1598+
self.addCleanup(sock.close)
1599+
1600+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # No error expected.
1601+
1602+
with self.assertRaises(OverflowError):
1603+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 2 ** 100)
1604+
1605+
with self.assertRaises(OverflowError):
1606+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, - 2 ** 100)
1607+
1608+
with self.assertRaises(OverflowError):
1609+
sock.setsockopt(socket.SOL_SOCKET, 2 ** 100, 1)
1610+
1611+
with self.assertRaises(OverflowError):
1612+
sock.setsockopt(2 ** 100, socket.SO_REUSEADDR, 1)
1613+
1614+
with self.assertRaisesRegex(TypeError, "socket option should be int, bytes-like object or None"):
1615+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, dict())
1616+
1617+
with self.assertRaisesRegex(TypeError, "requires 4 arguments when the third argument is None"):
1618+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, None)
1619+
1620+
with self.assertRaisesRegex(TypeError, "only takes 4 arguments when the third argument is None"):
1621+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1, 2)
1622+
1623+
with self.assertRaisesRegex(TypeError, "takes at least 3 arguments"):
1624+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
1625+
1626+
with self.assertRaisesRegex(TypeError, "takes at most 4 arguments"):
1627+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1, 2, 3)
1628+
15831629
def testSendAfterClose(self):
15841630
# testing send() after close() with timeout
15851631
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
@@ -2435,6 +2481,45 @@ def testCrucialConstants(self):
24352481
socket.CAN_ISOTP
24362482
socket.SOCK_DGRAM
24372483

2484+
@unittest.skipUnless(hasattr(socket, "SOL_CAN_ISOTP"),
2485+
"missing <linux/can/isotp.h>")
2486+
def testISOTP(self):
2487+
socket.SOL_CAN_ISOTP
2488+
2489+
socket.CAN_ISOTP_OPTS
2490+
socket.CAN_ISOTP_RECV_FC
2491+
2492+
socket.CAN_ISOTP_TX_STMIN
2493+
socket.CAN_ISOTP_RX_STMIN
2494+
socket.CAN_ISOTP_LL_OPTS
2495+
2496+
socket.CAN_ISOTP_LISTEN_MODE
2497+
socket.CAN_ISOTP_EXTEND_ADDR
2498+
socket.CAN_ISOTP_TX_PADDING
2499+
socket.CAN_ISOTP_RX_PADDING
2500+
socket.CAN_ISOTP_CHK_PAD_LEN
2501+
socket.CAN_ISOTP_CHK_PAD_DATA
2502+
socket.CAN_ISOTP_HALF_DUPLEX
2503+
socket.CAN_ISOTP_FORCE_TXSTMIN
2504+
socket.CAN_ISOTP_FORCE_RXSTMIN
2505+
socket.CAN_ISOTP_RX_EXT_ADDR
2506+
socket.CAN_ISOTP_WAIT_TX_DONE
2507+
# This constant is not always available
2508+
# socket.CAN_ISOTP_SF_BROADCAST
2509+
2510+
socket.CAN_ISOTP_DEFAULT_FLAGS
2511+
socket.CAN_ISOTP_DEFAULT_EXT_ADDRESS
2512+
socket.CAN_ISOTP_DEFAULT_PAD_CONTENT
2513+
socket.CAN_ISOTP_DEFAULT_FRAME_TXTIME
2514+
socket.CAN_ISOTP_DEFAULT_RECV_BS
2515+
socket.CAN_ISOTP_DEFAULT_EXT_ADDRESS
2516+
socket.CAN_ISOTP_DEFAULT_RECV_STMIN
2517+
socket.CAN_ISOTP_DEFAULT_RECV_WFTMAX
2518+
2519+
socket.CAN_ISOTP_DEFAULT_LL_MTU
2520+
socket.CAN_ISOTP_DEFAULT_LL_TX_DL
2521+
socket.CAN_ISOTP_DEFAULT_LL_TX_FLAGS
2522+
24382523
def testCreateSocket(self):
24392524
with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s:
24402525
pass

0 commit comments

Comments
 (0)