| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import errno |
| 4 |
import socket as stdlib_socket |
| 5 |
import sys |
| 6 |
from typing import TYPE_CHECKING |
| 7 |
|
| 8 |
import pytest |
| 9 |
|
| 10 |
from .. import _core, socket as tsocket |
| 11 |
from .._highlevel_socket import * |
| 12 |
from ..testing import ( |
| 13 |
assert_checkpoints, |
| 14 |
check_half_closeable_stream, |
| 15 |
wait_all_tasks_blocked, |
| 16 |
) |
| 17 |
from .test_socket import setsockopt_tests |
| 18 |
|
| 19 |
if TYPE_CHECKING: |
| 20 |
from collections.abc import Sequence |
| 21 |
|
| 22 |
|
| 23 |
async def test_SocketStream_basics() -> None: |
| 24 |
# stdlib socket bad (even if connected) |
| 25 |
stdlib_a, stdlib_b = stdlib_socket.socketpair() |
| 26 |
with stdlib_a, stdlib_b: |
| 27 |
with pytest.raises(TypeError): |
| 28 |
SocketStream(stdlib_a) # type: ignore[arg-type] |
| 29 |
|
| 30 |
# DGRAM socket bad |
| 31 |
with tsocket.socket(type=tsocket.SOCK_DGRAM) as sock: |
| 32 |
with pytest.raises( |
| 33 |
ValueError, |
| 34 |
match=r"^SocketStream requires a SOCK_STREAM socket$", |
| 35 |
): |
| 36 |
# TODO: does not raise an error? |
| 37 |
SocketStream(sock) |
| 38 |
|
| 39 |
a, b = tsocket.socketpair() |
| 40 |
with a, b: |
| 41 |
s = SocketStream(a) |
| 42 |
assert s.socket is a |
| 43 |
|
| 44 |
# Use a real, connected socket to test socket options, because |
| 45 |
# socketpair() might give us a unix socket that doesn't support any of |
| 46 |
# these options |
| 47 |
with tsocket.socket() as listen_sock: |
| 48 |
await listen_sock.bind(("127.0.0.1", 0)) |
| 49 |
listen_sock.listen(1) |
| 50 |
with tsocket.socket() as client_sock: |
| 51 |
await client_sock.connect(listen_sock.getsockname()) |
| 52 |
|
| 53 |
s = SocketStream(client_sock) |
| 54 |
|
| 55 |
# TCP_NODELAY enabled by default |
| 56 |
assert s.getsockopt(tsocket.IPPROTO_TCP, tsocket.TCP_NODELAY) |
| 57 |
# We can disable it though |
| 58 |
s.setsockopt(tsocket.IPPROTO_TCP, tsocket.TCP_NODELAY, False) |
| 59 |
assert not s.getsockopt(tsocket.IPPROTO_TCP, tsocket.TCP_NODELAY) |
| 60 |
|
| 61 |
res = s.getsockopt(tsocket.IPPROTO_TCP, tsocket.TCP_NODELAY, 1) |
| 62 |
assert isinstance(res, bytes) |
| 63 |
|
| 64 |
setsockopt_tests(s) |
| 65 |
|
| 66 |
|
| 67 |
async def test_SocketStream_send_all() -> None: |
| 68 |
BIG = 10000000 |
| 69 |
|
| 70 |
a_sock, b_sock = tsocket.socketpair() |
| 71 |
with a_sock, b_sock: |
| 72 |
a = SocketStream(a_sock) |
| 73 |
b = SocketStream(b_sock) |
| 74 |
|
| 75 |
# Check a send_all that has to be split into multiple parts (on most |
| 76 |
# platforms... on Windows every send() either succeeds or fails as a |
| 77 |
# whole) |
| 78 |
async def sender() -> None: |
| 79 |
data = bytearray(BIG) |
| 80 |
await a.send_all(data) |
| 81 |
# send_all uses memoryviews internally, which temporarily "lock" |
| 82 |
# the object they view. If it doesn't clean them up properly, then |
| 83 |
# some bytearray operations might raise an error afterwards, which |
| 84 |
# would be a pretty weird and annoying side-effect to spring on |
| 85 |
# users. So test that this doesn't happen, by forcing the |
| 86 |
# bytearray's underlying buffer to be realloc'ed: |
| 87 |
data += bytes(BIG) |
| 88 |
# (Note: the above line of code doesn't do a very good job at |
| 89 |
# testing anything, because: |
| 90 |
# - on CPython, the refcount GC generally cleans up memoryviews |
| 91 |
# for us even if we're sloppy. |
| 92 |
# - on PyPy3, at least as of 5.7.0, the memoryview code and the |
| 93 |
# bytearray code conspire so that resizing never fails – if |
| 94 |
# resizing forces the bytearray's internal buffer to move, then |
| 95 |
# all memoryview references are automagically updated (!!). |
| 96 |
# See: |
| 97 |
# https://gist.github.com/njsmith/0ffd38ec05ad8e34004f34a7dc492227 |
| 98 |
# But I'm leaving the test here in hopes that if this ever changes |
| 99 |
# and we break our implementation of send_all, then we'll get some |
| 100 |
# early warning...) |
| 101 |
|
| 102 |
async def receiver() -> None: |
| 103 |
# Make sure the sender fills up the kernel buffers and blocks |
| 104 |
await wait_all_tasks_blocked() |
| 105 |
nbytes = 0 |
| 106 |
while nbytes < BIG: |
| 107 |
nbytes += len(await b.receive_some(BIG)) |
| 108 |
assert nbytes == BIG |
| 109 |
|
| 110 |
async with _core.open_nursery() as nursery: |
| 111 |
nursery.start_soon(sender) |
| 112 |
nursery.start_soon(receiver) |
| 113 |
|
| 114 |
# We know that we received BIG bytes of NULs so far. Make sure that |
| 115 |
# was all the data in there. |
| 116 |
await a.send_all(b"e") |
| 117 |
assert await b.receive_some(10) == b"e" |
| 118 |
await a.send_eof() |
| 119 |
assert await b.receive_some(10) == b"" |
| 120 |
|
| 121 |
|
| 122 |
async def fill_stream(s: SocketStream) -> None: |
| 123 |
async def sender() -> None: |
| 124 |
while True: |
| 125 |
await s.send_all(b"x" * 10000) |
| 126 |
|
| 127 |
async def waiter(nursery: _core.Nursery) -> None: |
| 128 |
await wait_all_tasks_blocked() |
| 129 |
nursery.cancel_scope.cancel() |
| 130 |
|
| 131 |
async with _core.open_nursery() as nursery: |
| 132 |
nursery.start_soon(sender) |
| 133 |
nursery.start_soon(waiter, nursery) |
| 134 |
|
| 135 |
|
| 136 |
async def test_SocketStream_generic() -> None: |
| 137 |
async def stream_maker() -> tuple[ |
| 138 |
SocketStream, |
| 139 |
SocketStream, |
| 140 |
]: |
| 141 |
left, right = tsocket.socketpair() |
| 142 |
return SocketStream(left), SocketStream(right) |
| 143 |
|
| 144 |
async def clogged_stream_maker() -> tuple[SocketStream, SocketStream]: |
| 145 |
left, right = await stream_maker() |
| 146 |
await fill_stream(left) |
| 147 |
await fill_stream(right) |
| 148 |
return left, right |
| 149 |
|
| 150 |
await check_half_closeable_stream(stream_maker, clogged_stream_maker) |
| 151 |
|
| 152 |
|
| 153 |
async def test_SocketListener() -> None: |
| 154 |
# Not a Trio socket |
| 155 |
with stdlib_socket.socket() as s: |
| 156 |
s.bind(("127.0.0.1", 0)) |
| 157 |
s.listen(10) |
| 158 |
with pytest.raises(TypeError): |
| 159 |
SocketListener(s) # type: ignore[arg-type] |
| 160 |
|
| 161 |
# Not a SOCK_STREAM |
| 162 |
with tsocket.socket(type=tsocket.SOCK_DGRAM) as s: |
| 163 |
await s.bind(("127.0.0.1", 0)) |
| 164 |
with pytest.raises( |
| 165 |
ValueError, |
| 166 |
match=r"^SocketListener requires a SOCK_STREAM socket$", |
| 167 |
) as excinfo: |
| 168 |
SocketListener(s) |
| 169 |
excinfo.match(r".*SOCK_STREAM") |
| 170 |
|
| 171 |
# Didn't call .listen() |
| 172 |
# macOS has no way to check for this, so skip testing it there. |
| 173 |
if sys.platform != "darwin": |
| 174 |
with tsocket.socket() as s: |
| 175 |
await s.bind(("127.0.0.1", 0)) |
| 176 |
with pytest.raises( |
| 177 |
ValueError, |
| 178 |
match=r"^SocketListener requires a listening socket$", |
| 179 |
) as excinfo: |
| 180 |
SocketListener(s) |
| 181 |
excinfo.match(r".*listen") |
| 182 |
|
| 183 |
listen_sock = tsocket.socket() |
| 184 |
await listen_sock.bind(("127.0.0.1", 0)) |
| 185 |
listen_sock.listen(10) |
| 186 |
listener = SocketListener(listen_sock) |
| 187 |
|
| 188 |
assert listener.socket is listen_sock |
| 189 |
|
| 190 |
client_sock = tsocket.socket() |
| 191 |
await client_sock.connect(listen_sock.getsockname()) |
| 192 |
with assert_checkpoints(): |
| 193 |
server_stream = await listener.accept() |
| 194 |
assert isinstance(server_stream, SocketStream) |
| 195 |
assert server_stream.socket.getsockname() == listen_sock.getsockname() |
| 196 |
assert server_stream.socket.getpeername() == client_sock.getsockname() |
| 197 |
|
| 198 |
with assert_checkpoints(): |
| 199 |
await listener.aclose() |
| 200 |
|
| 201 |
with assert_checkpoints(): |
| 202 |
await listener.aclose() |
| 203 |
|
| 204 |
with assert_checkpoints(): |
| 205 |
with pytest.raises(_core.ClosedResourceError): |
| 206 |
await listener.accept() |
| 207 |
|
| 208 |
client_sock.close() |
| 209 |
await server_stream.aclose() |
| 210 |
|
| 211 |
|
| 212 |
async def test_SocketListener_socket_closed_underfoot() -> None: |
| 213 |
listen_sock = tsocket.socket() |
| 214 |
await listen_sock.bind(("127.0.0.1", 0)) |
| 215 |
listen_sock.listen(10) |
| 216 |
listener = SocketListener(listen_sock) |
| 217 |
|
| 218 |
# Close the socket, not the listener |
| 219 |
listen_sock.close() |
| 220 |
|
| 221 |
# SocketListener gives correct error |
| 222 |
with assert_checkpoints(): |
| 223 |
with pytest.raises(_core.ClosedResourceError): |
| 224 |
await listener.accept() |
| 225 |
|
| 226 |
|
| 227 |
async def test_SocketListener_accept_errors() -> None: |
| 228 |
class FakeSocket(tsocket.SocketType): |
| 229 |
def __init__(self, events: Sequence[SocketType | BaseException]) -> None: |
| 230 |
self._events = iter(events) |
| 231 |
|
| 232 |
type = tsocket.SOCK_STREAM |
| 233 |
|
| 234 |
# Fool the check for SO_ACCEPTCONN in SocketListener.__init__ |
| 235 |
@overload |
| 236 |
def getsockopt(self, /, level: int, optname: int) -> int: ... |
| 237 |
|
| 238 |
@overload |
| 239 |
def getsockopt( # noqa: F811 |
| 240 |
self, |
| 241 |
/, |
| 242 |
level: int, |
| 243 |
optname: int, |
| 244 |
buflen: int, |
| 245 |
) -> bytes: ... |
| 246 |
|
| 247 |
def getsockopt( # noqa: F811 |
| 248 |
self, |
| 249 |
/, |
| 250 |
level: int, |
| 251 |
optname: int, |
| 252 |
buflen: int | None = None, |
| 253 |
) -> int | bytes: |
| 254 |
return True |
| 255 |
|
| 256 |
@overload |
| 257 |
def setsockopt( |
| 258 |
self, |
| 259 |
/, |
| 260 |
level: int, |
| 261 |
optname: int, |
| 262 |
value: int | Buffer, |
| 263 |
) -> None: ... |
| 264 |
|
| 265 |
@overload |
| 266 |
def setsockopt( # noqa: F811 |
| 267 |
self, |
| 268 |
/, |
| 269 |
level: int, |
| 270 |
optname: int, |
| 271 |
value: None, |
| 272 |
optlen: int, |
| 273 |
) -> None: ... |
| 274 |
|
| 275 |
def setsockopt( # noqa: F811 |
| 276 |
self, |
| 277 |
/, |
| 278 |
level: int, |
| 279 |
optname: int, |
| 280 |
value: int | Buffer | None, |
| 281 |
optlen: int | None = None, |
| 282 |
) -> None: |
| 283 |
pass |
| 284 |
|
| 285 |
async def accept(self) -> tuple[SocketType, object]: |
| 286 |
await _core.checkpoint() |
| 287 |
event = next(self._events) |
| 288 |
if isinstance(event, BaseException): |
| 289 |
raise event |
| 290 |
else: |
| 291 |
return event, None |
| 292 |
|
| 293 |
fake_server_sock = FakeSocket([]) |
| 294 |
|
| 295 |
fake_listen_sock = FakeSocket( |
| 296 |
[ |
| 297 |
OSError(errno.ECONNABORTED, "Connection aborted"), |
| 298 |
OSError(errno.EPERM, "Permission denied"), |
| 299 |
OSError(errno.EPROTO, "Bad protocol"), |
| 300 |
fake_server_sock, |
| 301 |
OSError(errno.EMFILE, "Out of file descriptors"), |
| 302 |
OSError(errno.EFAULT, "attempt to write to read-only memory"), |
| 303 |
OSError(errno.ENOBUFS, "out of buffers"), |
| 304 |
fake_server_sock, |
| 305 |
], |
| 306 |
) |
| 307 |
|
| 308 |
listener = SocketListener(fake_listen_sock) |
| 309 |
|
| 310 |
with assert_checkpoints(): |
| 311 |
stream = await listener.accept() |
| 312 |
assert stream.socket is fake_server_sock |
| 313 |
|
| 314 |
for code, match in { |
| 315 |
errno.EMFILE: r"\[\w+ \d+\] Out of file descriptors$", |
| 316 |
errno.EFAULT: r"\[\w+ \d+\] attempt to write to read-only memory$", |
| 317 |
errno.ENOBUFS: r"\[\w+ \d+\] out of buffers$", |
| 318 |
}.items(): |
| 319 |
with assert_checkpoints(): |
| 320 |
with pytest.raises(OSError, match=match) as excinfo: |
| 321 |
await listener.accept() |
| 322 |
assert excinfo.value.errno == code |
| 323 |
|
| 324 |
with assert_checkpoints(): |
| 325 |
stream = await listener.accept() |
| 326 |
assert stream.socket is fake_server_sock |
| 327 |
|
| 328 |
|
| 329 |
async def test_socket_stream_works_when_peer_has_already_closed() -> None: |
| 330 |
sock_a, sock_b = tsocket.socketpair() |
| 331 |
with sock_a, sock_b: |
| 332 |
await sock_b.send(b"x") |
| 333 |
sock_b.close() |
| 334 |
stream = SocketStream(sock_a) |
| 335 |
assert await stream.receive_some(1) == b"x" |
| 336 |
assert await stream.receive_some(1) == b"" |