Skip to content

bpo-41317: Remove reader on cancellation in asyncio.loop.sock_accept() #21595

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 23, 2020
Merged
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
13 changes: 6 additions & 7 deletions Lib/asyncio/selector_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -555,20 +555,19 @@ async def sock_accept(self, sock):
if self._debug and sock.gettimeout() != 0:
raise ValueError("the socket must be non-blocking")
fut = self.create_future()
self._sock_accept(fut, False, sock)
self._sock_accept(fut, sock)
return await fut

def _sock_accept(self, fut, registered, sock):
def _sock_accept(self, fut, sock):
fd = sock.fileno()
if registered:
self.remove_reader(fd)
if fut.done():
return
try:
conn, address = sock.accept()
conn.setblocking(False)
except (BlockingIOError, InterruptedError):
self.add_reader(fd, self._sock_accept, fut, True, sock)
self._ensure_fd_no_transport(fd)
handle = self._add_reader(fd, self._sock_accept, fut, sock)
fut.add_done_callback(
functools.partial(self._sock_read_done, fd, handle=handle))
except (SystemExit, KeyboardInterrupt):
raise
except BaseException as exc:
Expand Down
19 changes: 19 additions & 0 deletions Lib/test/test_asyncio/test_sock_lowlevel.py
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,25 @@ def test_sock_accept(self):
conn.close()
listener.close()

def test_cancel_sock_accept(self):
listener = socket.socket()
listener.setblocking(False)
listener.bind(('127.0.0.1', 0))
listener.listen(1)
sockaddr = listener.getsockname()
f = asyncio.wait_for(self.loop.sock_accept(listener), 0.1)
with self.assertRaises(asyncio.TimeoutError):
self.loop.run_until_complete(f)

listener.close()
client = socket.socket()
client.setblocking(False)
f = self.loop.sock_connect(client, sockaddr)
with self.assertRaises(ConnectionRefusedError):
self.loop.run_until_complete(f)

client.close()

def test_create_connection_sock(self):
with test_utils.run_test_server() as httpd:
sock = None
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Use add_done_callback() in asyncio.loop.sock_accept() to unsubscribe reader
early on cancellation.