| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
import asyncio |
| 6 |
import asyncio.sslproto |
| 7 |
import contextlib |
| 8 |
import gc |
| 9 |
import logging |
| 10 |
import select |
| 11 |
import socket |
| 12 |
import sys |
| 13 |
import tempfile |
| 14 |
import threading |
| 15 |
import time |
| 16 |
import weakref |
| 17 |
import unittest |
| 18 |
|
| 19 |
try: |
| 20 |
import ssl |
| 21 |
except ImportError: |
| 22 |
ssl = None |
| 23 |
|
| 24 |
from test import support |
| 25 |
from test.test_asyncio import utils as test_utils |
| 26 |
|
| 27 |
|
| 28 |
MACOS = (sys.platform == 'darwin') |
| 29 |
BUF_MULTIPLIER = 1024 if not MACOS else 64 |
| 30 |
|
| 31 |
|
| 32 |
def tearDownModule(): |
| 33 |
asyncio.set_event_loop_policy(None) |
| 34 |
|
| 35 |
|
| 36 |
class MyBaseProto(asyncio.Protocol): |
| 37 |
connected = None |
| 38 |
done = None |
| 39 |
|
| 40 |
def __init__(self, loop=None): |
| 41 |
self.transport = None |
| 42 |
self.state = 'INITIAL' |
| 43 |
self.nbytes = 0 |
| 44 |
if loop is not None: |
| 45 |
self.connected = asyncio.Future(loop=loop) |
| 46 |
self.done = asyncio.Future(loop=loop) |
| 47 |
|
| 48 |
def connection_made(self, transport): |
| 49 |
self.transport = transport |
| 50 |
assert self.state == 'INITIAL', self.state |
| 51 |
self.state = 'CONNECTED' |
| 52 |
if self.connected: |
| 53 |
self.connected.set_result(None) |
| 54 |
|
| 55 |
def data_received(self, data): |
| 56 |
assert self.state == 'CONNECTED', self.state |
| 57 |
self.nbytes += len(data) |
| 58 |
|
| 59 |
def eof_received(self): |
| 60 |
assert self.state == 'CONNECTED', self.state |
| 61 |
self.state = 'EOF' |
| 62 |
|
| 63 |
def connection_lost(self, exc): |
| 64 |
assert self.state in ('CONNECTED', 'EOF'), self.state |
| 65 |
self.state = 'CLOSED' |
| 66 |
if self.done: |
| 67 |
self.done.set_result(None) |
| 68 |
|
| 69 |
|
| 70 |
class MessageOutFilter(logging.Filter): |
| 71 |
def __init__(self, msg): |
| 72 |
self.msg = msg |
| 73 |
|
| 74 |
def filter(self, record): |
| 75 |
if self.msg in record.msg: |
| 76 |
return False |
| 77 |
return True |
| 78 |
|
| 79 |
|
| 80 |
@unittest.skipIf(ssl is None, 'No ssl module') |
| 81 |
class TestSSL(test_utils.TestCase): |
| 82 |
|
| 83 |
PAYLOAD_SIZE = 1024 * 100 |
| 84 |
TIMEOUT = support.LONG_TIMEOUT |
| 85 |
|
| 86 |
def setUp(self): |
| 87 |
super().setUp() |
| 88 |
self.loop = asyncio.new_event_loop() |
| 89 |
self.set_event_loop(self.loop) |
| 90 |
self.addCleanup(self.loop.close) |
| 91 |
|
| 92 |
def tearDown(self): |
| 93 |
|
| 94 |
if not self.loop.is_closed(): |
| 95 |
test_utils.run_briefly(self.loop) |
| 96 |
|
| 97 |
self.doCleanups() |
| 98 |
support.gc_collect() |
| 99 |
super().tearDown() |
| 100 |
|
| 101 |
def tcp_server(self, server_prog, *, |
| 102 |
family=socket.AF_INET, |
| 103 |
addr=None, |
| 104 |
timeout=support.SHORT_TIMEOUT, |
| 105 |
backlog=1, |
| 106 |
max_clients=10): |
| 107 |
|
| 108 |
if addr is None: |
| 109 |
if family == getattr(socket, "AF_UNIX", None): |
| 110 |
with tempfile.NamedTemporaryFile() as tmp: |
| 111 |
addr = tmp.name |
| 112 |
else: |
| 113 |
addr = ('127.0.0.1', 0) |
| 114 |
|
| 115 |
sock = socket.socket(family, socket.SOCK_STREAM) |
| 116 |
|
| 117 |
if timeout is None: |
| 118 |
raise RuntimeError('timeout is required') |
| 119 |
if timeout <= 0: |
| 120 |
raise RuntimeError('only blocking sockets are supported') |
| 121 |
sock.settimeout(timeout) |
| 122 |
|
| 123 |
try: |
| 124 |
sock.bind(addr) |
| 125 |
sock.listen(backlog) |
| 126 |
except OSError as ex: |
| 127 |
sock.close() |
| 128 |
raise ex |
| 129 |
|
| 130 |
return TestThreadedServer( |
| 131 |
self, sock, server_prog, timeout, max_clients) |
| 132 |
|
| 133 |
def tcp_client(self, client_prog, |
| 134 |
family=socket.AF_INET, |
| 135 |
timeout=support.SHORT_TIMEOUT): |
| 136 |
|
| 137 |
sock = socket.socket(family, socket.SOCK_STREAM) |
| 138 |
|
| 139 |
if timeout is None: |
| 140 |
raise RuntimeError('timeout is required') |
| 141 |
if timeout <= 0: |
| 142 |
raise RuntimeError('only blocking sockets are supported') |
| 143 |
sock.settimeout(timeout) |
| 144 |
|
| 145 |
return TestThreadedClient( |
| 146 |
self, sock, client_prog, timeout) |
| 147 |
|
| 148 |
def unix_server(self, *args, **kwargs): |
| 149 |
return self.tcp_server(*args, family=socket.AF_UNIX, **kwargs) |
| 150 |
|
| 151 |
def unix_client(self, *args, **kwargs): |
| 152 |
return self.tcp_client(*args, family=socket.AF_UNIX, **kwargs) |
| 153 |
|
| 154 |
def _create_server_ssl_context(self, certfile, keyfile=None): |
| 155 |
sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 156 |
sslcontext.options |= ssl.OP_NO_SSLv2 |
| 157 |
sslcontext.load_cert_chain(certfile, keyfile) |
| 158 |
return sslcontext |
| 159 |
|
| 160 |
def _create_client_ssl_context(self, *, disable_verify=True): |
| 161 |
sslcontext = ssl.create_default_context() |
| 162 |
sslcontext.check_hostname = False |
| 163 |
if disable_verify: |
| 164 |
sslcontext.verify_mode = ssl.CERT_NONE |
| 165 |
return sslcontext |
| 166 |
|
| 167 |
@contextlib.contextmanager |
| 168 |
def _silence_eof_received_warning(self): |
| 169 |
|
| 170 |
logger = logging.getLogger('asyncio') |
| 171 |
filter = MessageOutFilter('has no effect when using ssl') |
| 172 |
logger.addFilter(filter) |
| 173 |
try: |
| 174 |
yield |
| 175 |
finally: |
| 176 |
logger.removeFilter(filter) |
| 177 |
|
| 178 |
def _abort_socket_test(self, ex): |
| 179 |
try: |
| 180 |
self.loop.stop() |
| 181 |
finally: |
| 182 |
self.fail(ex) |
| 183 |
|
| 184 |
def new_loop(self): |
| 185 |
return asyncio.new_event_loop() |
| 186 |
|
| 187 |
def new_policy(self): |
| 188 |
return asyncio.DefaultEventLoopPolicy() |
| 189 |
|
| 190 |
async def wait_closed(self, obj): |
| 191 |
if not isinstance(obj, asyncio.StreamWriter): |
| 192 |
return |
| 193 |
try: |
| 194 |
await obj.wait_closed() |
| 195 |
except (BrokenPipeError, ConnectionError): |
| 196 |
pass |
| 197 |
|
| 198 |
def test_create_server_ssl_1(self): |
| 199 |
CNT = 0 |
| 200 |
TOTAL_CNT = 25 |
| 201 |
TIMEOUT = support.LONG_TIMEOUT |
| 202 |
|
| 203 |
A_DATA = b'A' * 1024 * BUF_MULTIPLIER |
| 204 |
B_DATA = b'B' * 1024 * BUF_MULTIPLIER |
| 205 |
|
| 206 |
sslctx = self._create_server_ssl_context( |
| 207 |
test_utils.ONLYCERT, test_utils.ONLYKEY |
| 208 |
) |
| 209 |
client_sslctx = self._create_client_ssl_context() |
| 210 |
|
| 211 |
clients = [] |
| 212 |
|
| 213 |
async def handle_client(reader, writer): |
| 214 |
nonlocal CNT |
| 215 |
|
| 216 |
data = await reader.readexactly(len(A_DATA)) |
| 217 |
self.assertEqual(data, A_DATA) |
| 218 |
writer.write(b'OK') |
| 219 |
|
| 220 |
data = await reader.readexactly(len(B_DATA)) |
| 221 |
self.assertEqual(data, B_DATA) |
| 222 |
writer.writelines([b'SP', bytearray(b'A'), memoryview(b'M')]) |
| 223 |
|
| 224 |
await writer.drain() |
| 225 |
writer.close() |
| 226 |
|
| 227 |
CNT += 1 |
| 228 |
|
| 229 |
async def test_client(addr): |
| 230 |
fut = asyncio.Future() |
| 231 |
|
| 232 |
def prog(sock): |
| 233 |
try: |
| 234 |
sock.starttls(client_sslctx) |
| 235 |
sock.connect(addr) |
| 236 |
sock.send(A_DATA) |
| 237 |
|
| 238 |
data = sock.recv_all(2) |
| 239 |
self.assertEqual(data, b'OK') |
| 240 |
|
| 241 |
sock.send(B_DATA) |
| 242 |
data = sock.recv_all(4) |
| 243 |
self.assertEqual(data, b'SPAM') |
| 244 |
|
| 245 |
sock.close() |
| 246 |
|
| 247 |
except Exception as ex: |
| 248 |
self.loop.call_soon_threadsafe(fut.set_exception, ex) |
| 249 |
else: |
| 250 |
self.loop.call_soon_threadsafe(fut.set_result, None) |
| 251 |
|
| 252 |
client = self.tcp_client(prog) |
| 253 |
client.start() |
| 254 |
clients.append(client) |
| 255 |
|
| 256 |
await fut |
| 257 |
|
| 258 |
async def start_server(): |
| 259 |
extras = {} |
| 260 |
extras = dict(ssl_handshake_timeout=support.SHORT_TIMEOUT) |
| 261 |
|
| 262 |
srv = await asyncio.start_server( |
| 263 |
handle_client, |
| 264 |
'127.0.0.1', 0, |
| 265 |
family=socket.AF_INET, |
| 266 |
ssl=sslctx, |
| 267 |
**extras) |
| 268 |
|
| 269 |
try: |
| 270 |
srv_socks = srv.sockets |
| 271 |
self.assertTrue(srv_socks) |
| 272 |
|
| 273 |
addr = srv_socks[0].getsockname() |
| 274 |
|
| 275 |
tasks = [] |
| 276 |
for _ in range(TOTAL_CNT): |
| 277 |
tasks.append(test_client(addr)) |
| 278 |
|
| 279 |
await asyncio.wait_for(asyncio.gather(*tasks), TIMEOUT) |
| 280 |
|
| 281 |
finally: |
| 282 |
self.loop.call_soon(srv.close) |
| 283 |
await srv.wait_closed() |
| 284 |
|
| 285 |
with self._silence_eof_received_warning(): |
| 286 |
self.loop.run_until_complete(start_server()) |
| 287 |
|
| 288 |
self.assertEqual(CNT, TOTAL_CNT) |
| 289 |
|
| 290 |
for client in clients: |
| 291 |
client.stop() |
| 292 |
|
| 293 |
def test_create_connection_ssl_1(self): |
| 294 |
self.loop.set_exception_handler(None) |
| 295 |
|
| 296 |
CNT = 0 |
| 297 |
TOTAL_CNT = 25 |
| 298 |
|
| 299 |
A_DATA = b'A' * 1024 * BUF_MULTIPLIER |
| 300 |
B_DATA = b'B' * 1024 * BUF_MULTIPLIER |
| 301 |
|
| 302 |
sslctx = self._create_server_ssl_context( |
| 303 |
test_utils.ONLYCERT, |
| 304 |
test_utils.ONLYKEY |
| 305 |
) |
| 306 |
client_sslctx = self._create_client_ssl_context() |
| 307 |
|
| 308 |
def server(sock): |
| 309 |
sock.starttls( |
| 310 |
sslctx, |
| 311 |
server_side=True) |
| 312 |
|
| 313 |
data = sock.recv_all(len(A_DATA)) |
| 314 |
self.assertEqual(data, A_DATA) |
| 315 |
sock.send(b'OK') |
| 316 |
|
| 317 |
data = sock.recv_all(len(B_DATA)) |
| 318 |
self.assertEqual(data, B_DATA) |
| 319 |
sock.send(b'SPAM') |
| 320 |
|
| 321 |
sock.close() |
| 322 |
|
| 323 |
async def client(addr): |
| 324 |
extras = {} |
| 325 |
extras = dict(ssl_handshake_timeout=support.SHORT_TIMEOUT) |
| 326 |
|
| 327 |
reader, writer = await asyncio.open_connection( |
| 328 |
*addr, |
| 329 |
ssl=client_sslctx, |
| 330 |
server_hostname='', |
| 331 |
**extras) |
| 332 |
|
| 333 |
writer.write(A_DATA) |
| 334 |
self.assertEqual(await reader.readexactly(2), b'OK') |
| 335 |
|
| 336 |
writer.write(B_DATA) |
| 337 |
self.assertEqual(await reader.readexactly(4), b'SPAM') |
| 338 |
|
| 339 |
nonlocal CNT |
| 340 |
CNT += 1 |
| 341 |
|
| 342 |
writer.close() |
| 343 |
await self.wait_closed(writer) |
| 344 |
|
| 345 |
async def client_sock(addr): |
| 346 |
sock = socket.socket() |
| 347 |
sock.connect(addr) |
| 348 |
reader, writer = await asyncio.open_connection( |
| 349 |
sock=sock, |
| 350 |
ssl=client_sslctx, |
| 351 |
server_hostname='') |
| 352 |
|
| 353 |
writer.write(A_DATA) |
| 354 |
self.assertEqual(await reader.readexactly(2), b'OK') |
| 355 |
|
| 356 |
writer.write(B_DATA) |
| 357 |
self.assertEqual(await reader.readexactly(4), b'SPAM') |
| 358 |
|
| 359 |
nonlocal CNT |
| 360 |
CNT += 1 |
| 361 |
|
| 362 |
writer.close() |
| 363 |
await self.wait_closed(writer) |
| 364 |
sock.close() |
| 365 |
|
| 366 |
def run(coro): |
| 367 |
nonlocal CNT |
| 368 |
CNT = 0 |
| 369 |
|
| 370 |
async def _gather(*tasks): |
| 371 |
|
| 372 |
return await asyncio.gather(*tasks) |
| 373 |
|
| 374 |
with self.tcp_server(server, |
| 375 |
max_clients=TOTAL_CNT, |
| 376 |
backlog=TOTAL_CNT) as srv: |
| 377 |
tasks = [] |
| 378 |
for _ in range(TOTAL_CNT): |
| 379 |
tasks.append(coro(srv.addr)) |
| 380 |
|
| 381 |
self.loop.run_until_complete(_gather(*tasks)) |
| 382 |
|
| 383 |
self.assertEqual(CNT, TOTAL_CNT) |
| 384 |
|
| 385 |
with self._silence_eof_received_warning(): |
| 386 |
run(client) |
| 387 |
|
| 388 |
with self._silence_eof_received_warning(): |
| 389 |
run(client_sock) |
| 390 |
|
| 391 |
def test_create_connection_ssl_slow_handshake(self): |
| 392 |
client_sslctx = self._create_client_ssl_context() |
| 393 |
|
| 394 |
|
| 395 |
self.loop.set_exception_handler(lambda *args: None) |
| 396 |
|
| 397 |
def server(sock): |
| 398 |
try: |
| 399 |
sock.recv_all(1024 * 1024) |
| 400 |
except ConnectionAbortedError: |
| 401 |
pass |
| 402 |
finally: |
| 403 |
sock.close() |
| 404 |
|
| 405 |
async def client(addr): |
| 406 |
reader, writer = await asyncio.open_connection( |
| 407 |
*addr, |
| 408 |
ssl=client_sslctx, |
| 409 |
server_hostname='', |
| 410 |
ssl_handshake_timeout=1.0) |
| 411 |
writer.close() |
| 412 |
await self.wait_closed(writer) |
| 413 |
|
| 414 |
with self.tcp_server(server, |
| 415 |
max_clients=1, |
| 416 |
backlog=1) as srv: |
| 417 |
|
| 418 |
with self.assertRaisesRegex( |
| 419 |
ConnectionAbortedError, |
| 420 |
r'SSL handshake.*is taking longer'): |
| 421 |
|
| 422 |
self.loop.run_until_complete(client(srv.addr)) |
| 423 |
|
| 424 |
def test_create_connection_ssl_failed_certificate(self): |
| 425 |
|
| 426 |
self.loop.set_exception_handler(lambda *args: None) |
| 427 |
|
| 428 |
sslctx = self._create_server_ssl_context( |
| 429 |
test_utils.ONLYCERT, |
| 430 |
test_utils.ONLYKEY |
| 431 |
) |
| 432 |
client_sslctx = self._create_client_ssl_context(disable_verify=False) |
| 433 |
|
| 434 |
def server(sock): |
| 435 |
try: |
| 436 |
sock.starttls( |
| 437 |
sslctx, |
| 438 |
server_side=True) |
| 439 |
sock.connect() |
| 440 |
except (ssl.SSLError, OSError): |
| 441 |
pass |
| 442 |
finally: |
| 443 |
sock.close() |
| 444 |
|
| 445 |
async def client(addr): |
| 446 |
reader, writer = await asyncio.open_connection( |
| 447 |
*addr, |
| 448 |
ssl=client_sslctx, |
| 449 |
server_hostname='', |
| 450 |
ssl_handshake_timeout=support.SHORT_TIMEOUT) |
| 451 |
writer.close() |
| 452 |
await self.wait_closed(writer) |
| 453 |
|
| 454 |
with self.tcp_server(server, |
| 455 |
max_clients=1, |
| 456 |
backlog=1) as srv: |
| 457 |
|
| 458 |
with self.assertRaises(ssl.SSLCertVerificationError): |
| 459 |
self.loop.run_until_complete(client(srv.addr)) |
| 460 |
|
| 461 |
def test_ssl_handshake_timeout(self): |
| 462 |
|
| 463 |
|
| 464 |
client_sslctx = test_utils.simple_client_sslcontext() |
| 465 |
|
| 466 |
|
| 467 |
messages = [] |
| 468 |
self.loop.set_exception_handler(lambda loop, ctx: messages.append(ctx)) |
| 469 |
|
| 470 |
server_side_aborted = False |
| 471 |
|
| 472 |
def server(sock): |
| 473 |
nonlocal server_side_aborted |
| 474 |
try: |
| 475 |
sock.recv_all(1024 * 1024) |
| 476 |
except ConnectionAbortedError: |
| 477 |
server_side_aborted = True |
| 478 |
finally: |
| 479 |
sock.close() |
| 480 |
|
| 481 |
async def client(addr): |
| 482 |
await asyncio.wait_for( |
| 483 |
self.loop.create_connection( |
| 484 |
asyncio.Protocol, |
| 485 |
*addr, |
| 486 |
ssl=client_sslctx, |
| 487 |
server_hostname='', |
| 488 |
ssl_handshake_timeout=10.0), |
| 489 |
0.5) |
| 490 |
|
| 491 |
with self.tcp_server(server, |
| 492 |
max_clients=1, |
| 493 |
backlog=1) as srv: |
| 494 |
|
| 495 |
with self.assertRaises(asyncio.TimeoutError): |
| 496 |
self.loop.run_until_complete(client(srv.addr)) |
| 497 |
|
| 498 |
self.assertTrue(server_side_aborted) |
| 499 |
|
| 500 |
|
| 501 |
|
| 502 |
self.assertEqual(messages, []) |
| 503 |
|
| 504 |
def test_ssl_handshake_connection_lost(self): |
| 505 |
|
| 506 |
|
| 507 |
|
| 508 |
client_sslctx = test_utils.simple_client_sslcontext() |
| 509 |
|
| 510 |
|
| 511 |
self.loop.set_exception_handler(lambda loop, ctx: None) |
| 512 |
|
| 513 |
connection_made_called = False |
| 514 |
connection_lost_called = False |
| 515 |
|
| 516 |
def server(sock): |
| 517 |
sock.recv(1024) |
| 518 |
|
| 519 |
sock.close() |
| 520 |
|
| 521 |
class ClientProto(asyncio.Protocol): |
| 522 |
def connection_made(self, transport): |
| 523 |
nonlocal connection_made_called |
| 524 |
connection_made_called = True |
| 525 |
|
| 526 |
def connection_lost(self, exc): |
| 527 |
nonlocal connection_lost_called |
| 528 |
connection_lost_called = True |
| 529 |
|
| 530 |
async def client(addr): |
| 531 |
await self.loop.create_connection( |
| 532 |
ClientProto, |
| 533 |
*addr, |
| 534 |
ssl=client_sslctx, |
| 535 |
server_hostname=''), |
| 536 |
|
| 537 |
with self.tcp_server(server, |
| 538 |
max_clients=1, |
| 539 |
backlog=1) as srv: |
| 540 |
|
| 541 |
with self.assertRaises(ConnectionResetError): |
| 542 |
self.loop.run_until_complete(client(srv.addr)) |
| 543 |
|
| 544 |
if connection_lost_called: |
| 545 |
if connection_made_called: |
| 546 |
self.fail("unexpected call to connection_lost()") |
| 547 |
else: |
| 548 |
self.fail("unexpected call to connection_lost() without" |
| 549 |
"calling connection_made()") |
| 550 |
elif connection_made_called: |
| 551 |
self.fail("unexpected call to connection_made()") |
| 552 |
|
| 553 |
def test_ssl_connect_accepted_socket(self): |
| 554 |
proto = ssl.PROTOCOL_TLS_SERVER |
| 555 |
server_context = ssl.SSLContext(proto) |
| 556 |
server_context.load_cert_chain(test_utils.ONLYCERT, test_utils.ONLYKEY) |
| 557 |
if hasattr(server_context, 'check_hostname'): |
| 558 |
server_context.check_hostname = False |
| 559 |
server_context.verify_mode = ssl.CERT_NONE |
| 560 |
|
| 561 |
client_context = ssl.SSLContext(proto) |
| 562 |
if hasattr(server_context, 'check_hostname'): |
| 563 |
client_context.check_hostname = False |
| 564 |
client_context.verify_mode = ssl.CERT_NONE |
| 565 |
|
| 566 |
def test_connect_accepted_socket(self, server_ssl=None, client_ssl=None): |
| 567 |
loop = self.loop |
| 568 |
|
| 569 |
class MyProto(MyBaseProto): |
| 570 |
|
| 571 |
def connection_lost(self, exc): |
| 572 |
super().connection_lost(exc) |
| 573 |
loop.call_soon(loop.stop) |
| 574 |
|
| 575 |
def data_received(self, data): |
| 576 |
super().data_received(data) |
| 577 |
self.transport.write(expected_response) |
| 578 |
|
| 579 |
lsock = socket.socket(socket.AF_INET) |
| 580 |
lsock.bind(('127.0.0.1', 0)) |
| 581 |
lsock.listen(1) |
| 582 |
addr = lsock.getsockname() |
| 583 |
|
| 584 |
message = b'test data' |
| 585 |
response = None |
| 586 |
expected_response = b'roger' |
| 587 |
|
| 588 |
def client(): |
| 589 |
nonlocal response |
| 590 |
try: |
| 591 |
csock = socket.socket(socket.AF_INET) |
| 592 |
if client_ssl is not None: |
| 593 |
csock = client_ssl.wrap_socket(csock) |
| 594 |
csock.connect(addr) |
| 595 |
csock.sendall(message) |
| 596 |
response = csock.recv(99) |
| 597 |
csock.close() |
| 598 |
except Exception as exc: |
| 599 |
print( |
| 600 |
"Failure in client thread in test_connect_accepted_socket", |
| 601 |
exc) |
| 602 |
|
| 603 |
thread = threading.Thread(target=client, daemon=True) |
| 604 |
thread.start() |
| 605 |
|
| 606 |
conn, _ = lsock.accept() |
| 607 |
proto = MyProto(loop=loop) |
| 608 |
proto.loop = loop |
| 609 |
|
| 610 |
extras = {} |
| 611 |
if server_ssl: |
| 612 |
extras = dict(ssl_handshake_timeout=support.SHORT_TIMEOUT) |
| 613 |
|
| 614 |
f = loop.create_task( |
| 615 |
loop.connect_accepted_socket( |
| 616 |
(lambda: proto), conn, ssl=server_ssl, |
| 617 |
**extras)) |
| 618 |
loop.run_forever() |
| 619 |
conn.close() |
| 620 |
lsock.close() |
| 621 |
|
| 622 |
thread.join(1) |
| 623 |
self.assertFalse(thread.is_alive()) |
| 624 |
self.assertEqual(proto.state, 'CLOSED') |
| 625 |
self.assertEqual(proto.nbytes, len(message)) |
| 626 |
self.assertEqual(response, expected_response) |
| 627 |
tr, _ = f.result() |
| 628 |
|
| 629 |
if server_ssl: |
| 630 |
self.assertIn('SSL', tr.__class__.__name__) |
| 631 |
|
| 632 |
tr.close() |
| 633 |
|
| 634 |
self.loop.run_until_complete(asyncio.sleep(0.1)) |
| 635 |
|
| 636 |
def test_start_tls_client_corrupted_ssl(self): |
| 637 |
self.loop.set_exception_handler(lambda loop, ctx: None) |
| 638 |
|
| 639 |
sslctx = test_utils.simple_server_sslcontext() |
| 640 |
client_sslctx = test_utils.simple_client_sslcontext() |
| 641 |
|
| 642 |
def server(sock): |
| 643 |
orig_sock = sock.dup() |
| 644 |
try: |
| 645 |
sock.starttls( |
| 646 |
sslctx, |
| 647 |
server_side=True) |
| 648 |
sock.sendall(b'A\n') |
| 649 |
sock.recv_all(1) |
| 650 |
orig_sock.send(b'please corrupt the SSL connection') |
| 651 |
except ssl.SSLError: |
| 652 |
pass |
| 653 |
finally: |
| 654 |
sock.close() |
| 655 |
orig_sock.close() |
| 656 |
|
| 657 |
async def client(addr): |
| 658 |
reader, writer = await asyncio.open_connection( |
| 659 |
*addr, |
| 660 |
ssl=client_sslctx, |
| 661 |
server_hostname='') |
| 662 |
|
| 663 |
self.assertEqual(await reader.readline(), b'A\n') |
| 664 |
writer.write(b'B') |
| 665 |
with self.assertRaises(ssl.SSLError): |
| 666 |
await reader.readline() |
| 667 |
writer.close() |
| 668 |
try: |
| 669 |
await self.wait_closed(writer) |
| 670 |
except ssl.SSLError: |
| 671 |
pass |
| 672 |
return 'OK' |
| 673 |
|
| 674 |
with self.tcp_server(server, |
| 675 |
max_clients=1, |
| 676 |
backlog=1) as srv: |
| 677 |
|
| 678 |
res = self.loop.run_until_complete(client(srv.addr)) |
| 679 |
|
| 680 |
self.assertEqual(res, 'OK') |
| 681 |
|
| 682 |
def test_start_tls_client_reg_proto_1(self): |
| 683 |
HELLO_MSG = b'1' * self.PAYLOAD_SIZE |
| 684 |
|
| 685 |
server_context = test_utils.simple_server_sslcontext() |
| 686 |
client_context = test_utils.simple_client_sslcontext() |
| 687 |
|
| 688 |
def serve(sock): |
| 689 |
sock.settimeout(self.TIMEOUT) |
| 690 |
|
| 691 |
data = sock.recv_all(len(HELLO_MSG)) |
| 692 |
self.assertEqual(len(data), len(HELLO_MSG)) |
| 693 |
|
| 694 |
sock.starttls(server_context, server_side=True) |
| 695 |
|
| 696 |
sock.sendall(b'O') |
| 697 |
data = sock.recv_all(len(HELLO_MSG)) |
| 698 |
self.assertEqual(len(data), len(HELLO_MSG)) |
| 699 |
|
| 700 |
sock.unwrap() |
| 701 |
sock.close() |
| 702 |
|
| 703 |
class ClientProto(asyncio.Protocol): |
| 704 |
def __init__(self, on_data, on_eof): |
| 705 |
self.on_data = on_data |
| 706 |
self.on_eof = on_eof |
| 707 |
self.con_made_cnt = 0 |
| 708 |
|
| 709 |
def connection_made(proto, tr): |
| 710 |
proto.con_made_cnt += 1 |
| 711 |
|
| 712 |
self.assertEqual(proto.con_made_cnt, 1) |
| 713 |
|
| 714 |
def data_received(self, data): |
| 715 |
self.on_data.set_result(data) |
| 716 |
|
| 717 |
def eof_received(self): |
| 718 |
self.on_eof.set_result(True) |
| 719 |
|
| 720 |
async def client(addr): |
| 721 |
await asyncio.sleep(0.5) |
| 722 |
|
| 723 |
on_data = self.loop.create_future() |
| 724 |
on_eof = self.loop.create_future() |
| 725 |
|
| 726 |
tr, proto = await self.loop.create_connection( |
| 727 |
lambda: ClientProto(on_data, on_eof), *addr) |
| 728 |
|
| 729 |
tr.write(HELLO_MSG) |
| 730 |
new_tr = await self.loop.start_tls(tr, proto, client_context) |
| 731 |
|
| 732 |
self.assertEqual(await on_data, b'O') |
| 733 |
new_tr.write(HELLO_MSG) |
| 734 |
await on_eof |
| 735 |
|
| 736 |
new_tr.close() |
| 737 |
|
| 738 |
with self.tcp_server(serve, timeout=self.TIMEOUT) as srv: |
| 739 |
self.loop.run_until_complete( |
| 740 |
asyncio.wait_for(client(srv.addr), |
| 741 |
timeout=support.SHORT_TIMEOUT)) |
| 742 |
|
| 743 |
def test_create_connection_memory_leak(self): |
| 744 |
HELLO_MSG = b'1' * self.PAYLOAD_SIZE |
| 745 |
|
| 746 |
server_context = self._create_server_ssl_context( |
| 747 |
test_utils.ONLYCERT, test_utils.ONLYKEY) |
| 748 |
client_context = self._create_client_ssl_context() |
| 749 |
|
| 750 |
def serve(sock): |
| 751 |
sock.settimeout(self.TIMEOUT) |
| 752 |
|
| 753 |
sock.starttls(server_context, server_side=True) |
| 754 |
|
| 755 |
sock.sendall(b'O') |
| 756 |
data = sock.recv_all(len(HELLO_MSG)) |
| 757 |
self.assertEqual(len(data), len(HELLO_MSG)) |
| 758 |
|
| 759 |
sock.unwrap() |
| 760 |
sock.close() |
| 761 |
|
| 762 |
class ClientProto(asyncio.Protocol): |
| 763 |
def __init__(self, on_data, on_eof): |
| 764 |
self.on_data = on_data |
| 765 |
self.on_eof = on_eof |
| 766 |
self.con_made_cnt = 0 |
| 767 |
|
| 768 |
def connection_made(proto, tr): |
| 769 |
|
| 770 |
proto.tr = tr |
| 771 |
proto.con_made_cnt += 1 |
| 772 |
|
| 773 |
self.assertEqual(proto.con_made_cnt, 1) |
| 774 |
|
| 775 |
def data_received(self, data): |
| 776 |
self.on_data.set_result(data) |
| 777 |
|
| 778 |
def eof_received(self): |
| 779 |
self.on_eof.set_result(True) |
| 780 |
|
| 781 |
async def client(addr): |
| 782 |
await asyncio.sleep(0.5) |
| 783 |
|
| 784 |
on_data = self.loop.create_future() |
| 785 |
on_eof = self.loop.create_future() |
| 786 |
|
| 787 |
tr, proto = await self.loop.create_connection( |
| 788 |
lambda: ClientProto(on_data, on_eof), *addr, |
| 789 |
ssl=client_context) |
| 790 |
|
| 791 |
self.assertEqual(await on_data, b'O') |
| 792 |
tr.write(HELLO_MSG) |
| 793 |
await on_eof |
| 794 |
|
| 795 |
tr.close() |
| 796 |
|
| 797 |
with self.tcp_server(serve, timeout=self.TIMEOUT) as srv: |
| 798 |
self.loop.run_until_complete( |
| 799 |
asyncio.wait_for(client(srv.addr), |
| 800 |
timeout=support.SHORT_TIMEOUT)) |
| 801 |
|
| 802 |
|
| 803 |
|
| 804 |
client_context = weakref.ref(client_context) |
| 805 |
|
| 806 |
support.gc_collect() |
| 807 |
self.assertIsNone(client_context()) |
| 808 |
|
| 809 |
def test_start_tls_client_buf_proto_1(self): |
| 810 |
HELLO_MSG = b'1' * self.PAYLOAD_SIZE |
| 811 |
|
| 812 |
server_context = test_utils.simple_server_sslcontext() |
| 813 |
client_context = test_utils.simple_client_sslcontext() |
| 814 |
|
| 815 |
client_con_made_calls = 0 |
| 816 |
|
| 817 |
def serve(sock): |
| 818 |
sock.settimeout(self.TIMEOUT) |
| 819 |
|
| 820 |
data = sock.recv_all(len(HELLO_MSG)) |
| 821 |
self.assertEqual(len(data), len(HELLO_MSG)) |
| 822 |
|
| 823 |
sock.starttls(server_context, server_side=True) |
| 824 |
|
| 825 |
sock.sendall(b'O') |
| 826 |
data = sock.recv_all(len(HELLO_MSG)) |
| 827 |
self.assertEqual(len(data), len(HELLO_MSG)) |
| 828 |
|
| 829 |
sock.sendall(b'2') |
| 830 |
data = sock.recv_all(len(HELLO_MSG)) |
| 831 |
self.assertEqual(len(data), len(HELLO_MSG)) |
| 832 |
|
| 833 |
sock.unwrap() |
| 834 |
sock.close() |
| 835 |
|
| 836 |
class ClientProtoFirst(asyncio.BufferedProtocol): |
| 837 |
def __init__(self, on_data): |
| 838 |
self.on_data = on_data |
| 839 |
self.buf = bytearray(1) |
| 840 |
|
| 841 |
def connection_made(self, tr): |
| 842 |
nonlocal client_con_made_calls |
| 843 |
client_con_made_calls += 1 |
| 844 |
|
| 845 |
def get_buffer(self, sizehint): |
| 846 |
return self.buf |
| 847 |
|
| 848 |
def buffer_updated(self, nsize): |
| 849 |
assert nsize == 1 |
| 850 |
self.on_data.set_result(bytes(self.buf[:nsize])) |
| 851 |
|
| 852 |
def eof_received(self): |
| 853 |
pass |
| 854 |
|
| 855 |
class ClientProtoSecond(asyncio.Protocol): |
| 856 |
def __init__(self, on_data, on_eof): |
| 857 |
self.on_data = on_data |
| 858 |
self.on_eof = on_eof |
| 859 |
self.con_made_cnt = 0 |
| 860 |
|
| 861 |
def connection_made(self, tr): |
| 862 |
nonlocal client_con_made_calls |
| 863 |
client_con_made_calls += 1 |
| 864 |
|
| 865 |
def data_received(self, data): |
| 866 |
self.on_data.set_result(data) |
| 867 |
|
| 868 |
def eof_received(self): |
| 869 |
self.on_eof.set_result(True) |
| 870 |
|
| 871 |
async def client(addr): |
| 872 |
await asyncio.sleep(0.5) |
| 873 |
|
| 874 |
on_data1 = self.loop.create_future() |
| 875 |
on_data2 = self.loop.create_future() |
| 876 |
on_eof = self.loop.create_future() |
| 877 |
|
| 878 |
tr, proto = await self.loop.create_connection( |
| 879 |
lambda: ClientProtoFirst(on_data1), *addr) |
| 880 |
|
| 881 |
tr.write(HELLO_MSG) |
| 882 |
new_tr = await self.loop.start_tls(tr, proto, client_context) |
| 883 |
|
| 884 |
self.assertEqual(await on_data1, b'O') |
| 885 |
new_tr.write(HELLO_MSG) |
| 886 |
|
| 887 |
new_tr.set_protocol(ClientProtoSecond(on_data2, on_eof)) |
| 888 |
self.assertEqual(await on_data2, b'2') |
| 889 |
new_tr.write(HELLO_MSG) |
| 890 |
await on_eof |
| 891 |
|
| 892 |
new_tr.close() |
| 893 |
|
| 894 |
|
| 895 |
|
| 896 |
|
| 897 |
self.assertEqual(client_con_made_calls, 1) |
| 898 |
|
| 899 |
with self.tcp_server(serve, timeout=self.TIMEOUT) as srv: |
| 900 |
self.loop.run_until_complete( |
| 901 |
asyncio.wait_for(client(srv.addr), |
| 902 |
timeout=self.TIMEOUT)) |
| 903 |
|
| 904 |
def test_start_tls_slow_client_cancel(self): |
| 905 |
HELLO_MSG = b'1' * self.PAYLOAD_SIZE |
| 906 |
|
| 907 |
client_context = test_utils.simple_client_sslcontext() |
| 908 |
server_waits_on_handshake = self.loop.create_future() |
| 909 |
|
| 910 |
def serve(sock): |
| 911 |
sock.settimeout(self.TIMEOUT) |
| 912 |
|
| 913 |
data = sock.recv_all(len(HELLO_MSG)) |
| 914 |
self.assertEqual(len(data), len(HELLO_MSG)) |
| 915 |
|
| 916 |
try: |
| 917 |
self.loop.call_soon_threadsafe( |
| 918 |
server_waits_on_handshake.set_result, None) |
| 919 |
data = sock.recv_all(1024 * 1024) |
| 920 |
except ConnectionAbortedError: |
| 921 |
pass |
| 922 |
finally: |
| 923 |
sock.close() |
| 924 |
|
| 925 |
class ClientProto(asyncio.Protocol): |
| 926 |
def __init__(self, on_data, on_eof): |
| 927 |
self.on_data = on_data |
| 928 |
self.on_eof = on_eof |
| 929 |
self.con_made_cnt = 0 |
| 930 |
|
| 931 |
def connection_made(proto, tr): |
| 932 |
proto.con_made_cnt += 1 |
| 933 |
|
| 934 |
self.assertEqual(proto.con_made_cnt, 1) |
| 935 |
|
| 936 |
def data_received(self, data): |
| 937 |
self.on_data.set_result(data) |
| 938 |
|
| 939 |
def eof_received(self): |
| 940 |
self.on_eof.set_result(True) |
| 941 |
|
| 942 |
async def client(addr): |
| 943 |
await asyncio.sleep(0.5) |
| 944 |
|
| 945 |
on_data = self.loop.create_future() |
| 946 |
on_eof = self.loop.create_future() |
| 947 |
|
| 948 |
tr, proto = await self.loop.create_connection( |
| 949 |
lambda: ClientProto(on_data, on_eof), *addr) |
| 950 |
|
| 951 |
tr.write(HELLO_MSG) |
| 952 |
|
| 953 |
await server_waits_on_handshake |
| 954 |
|
| 955 |
with self.assertRaises(asyncio.TimeoutError): |
| 956 |
await asyncio.wait_for( |
| 957 |
self.loop.start_tls(tr, proto, client_context), |
| 958 |
0.5) |
| 959 |
|
| 960 |
with self.tcp_server(serve, timeout=self.TIMEOUT) as srv: |
| 961 |
self.loop.run_until_complete( |
| 962 |
asyncio.wait_for(client(srv.addr), |
| 963 |
timeout=support.SHORT_TIMEOUT)) |
| 964 |
|
| 965 |
def test_start_tls_server_1(self): |
| 966 |
HELLO_MSG = b'1' * self.PAYLOAD_SIZE |
| 967 |
|
| 968 |
server_context = test_utils.simple_server_sslcontext() |
| 969 |
client_context = test_utils.simple_client_sslcontext() |
| 970 |
|
| 971 |
def client(sock, addr): |
| 972 |
sock.settimeout(self.TIMEOUT) |
| 973 |
|
| 974 |
sock.connect(addr) |
| 975 |
data = sock.recv_all(len(HELLO_MSG)) |
| 976 |
self.assertEqual(len(data), len(HELLO_MSG)) |
| 977 |
|
| 978 |
sock.starttls(client_context) |
| 979 |
sock.sendall(HELLO_MSG) |
| 980 |
|
| 981 |
sock.unwrap() |
| 982 |
sock.close() |
| 983 |
|
| 984 |
class ServerProto(asyncio.Protocol): |
| 985 |
def __init__(self, on_con, on_eof, on_con_lost): |
| 986 |
self.on_con = on_con |
| 987 |
self.on_eof = on_eof |
| 988 |
self.on_con_lost = on_con_lost |
| 989 |
self.data = b'' |
| 990 |
|
| 991 |
def connection_made(self, tr): |
| 992 |
self.on_con.set_result(tr) |
| 993 |
|
| 994 |
def data_received(self, data): |
| 995 |
self.data += data |
| 996 |
|
| 997 |
def eof_received(self): |
| 998 |
self.on_eof.set_result(1) |
| 999 |
|
| 1000 |
def connection_lost(self, exc): |
| 1001 |
if exc is None: |
| 1002 |
self.on_con_lost.set_result(None) |
| 1003 |
else: |
| 1004 |
self.on_con_lost.set_exception(exc) |
| 1005 |
|
| 1006 |
async def main(proto, on_con, on_eof, on_con_lost): |
| 1007 |
tr = await on_con |
| 1008 |
tr.write(HELLO_MSG) |
| 1009 |
|
| 1010 |
self.assertEqual(proto.data, b'') |
| 1011 |
|
| 1012 |
new_tr = await self.loop.start_tls( |
| 1013 |
tr, proto, server_context, |
| 1014 |
server_side=True, |
| 1015 |
ssl_handshake_timeout=self.TIMEOUT) |
| 1016 |
|
| 1017 |
await on_eof |
| 1018 |
await on_con_lost |
| 1019 |
self.assertEqual(proto.data, HELLO_MSG) |
| 1020 |
new_tr.close() |
| 1021 |
|
| 1022 |
async def run_main(): |
| 1023 |
on_con = self.loop.create_future() |
| 1024 |
on_eof = self.loop.create_future() |
| 1025 |
on_con_lost = self.loop.create_future() |
| 1026 |
proto = ServerProto(on_con, on_eof, on_con_lost) |
| 1027 |
|
| 1028 |
server = await self.loop.create_server( |
| 1029 |
lambda: proto, '127.0.0.1', 0) |
| 1030 |
addr = server.sockets[0].getsockname() |
| 1031 |
|
| 1032 |
with self.tcp_client(lambda sock: client(sock, addr), |
| 1033 |
timeout=self.TIMEOUT): |
| 1034 |
await asyncio.wait_for( |
| 1035 |
main(proto, on_con, on_eof, on_con_lost), |
| 1036 |
timeout=self.TIMEOUT) |
| 1037 |
|
| 1038 |
server.close() |
| 1039 |
await server.wait_closed() |
| 1040 |
|
| 1041 |
self.loop.run_until_complete(run_main()) |
| 1042 |
|
| 1043 |
def test_create_server_ssl_over_ssl(self): |
| 1044 |
CNT = 0 |
| 1045 |
TOTAL_CNT = 25 |
| 1046 |
TIMEOUT = support.LONG_TIMEOUT |
| 1047 |
|
| 1048 |
A_DATA = b'A' * 1024 * BUF_MULTIPLIER |
| 1049 |
B_DATA = b'B' * 1024 * BUF_MULTIPLIER |
| 1050 |
|
| 1051 |
sslctx_1 = self._create_server_ssl_context( |
| 1052 |
test_utils.ONLYCERT, test_utils.ONLYKEY) |
| 1053 |
client_sslctx_1 = self._create_client_ssl_context() |
| 1054 |
sslctx_2 = self._create_server_ssl_context( |
| 1055 |
test_utils.ONLYCERT, test_utils.ONLYKEY) |
| 1056 |
client_sslctx_2 = self._create_client_ssl_context() |
| 1057 |
|
| 1058 |
clients = [] |
| 1059 |
|
| 1060 |
async def handle_client(reader, writer): |
| 1061 |
nonlocal CNT |
| 1062 |
|
| 1063 |
data = await reader.readexactly(len(A_DATA)) |
| 1064 |
self.assertEqual(data, A_DATA) |
| 1065 |
writer.write(b'OK') |
| 1066 |
|
| 1067 |
data = await reader.readexactly(len(B_DATA)) |
| 1068 |
self.assertEqual(data, B_DATA) |
| 1069 |
writer.writelines([b'SP', bytearray(b'A'), memoryview(b'M')]) |
| 1070 |
|
| 1071 |
await writer.drain() |
| 1072 |
writer.close() |
| 1073 |
|
| 1074 |
CNT += 1 |
| 1075 |
|
| 1076 |
class ServerProtocol(asyncio.StreamReaderProtocol): |
| 1077 |
def connection_made(self, transport): |
| 1078 |
super_ = super() |
| 1079 |
transport.pause_reading() |
| 1080 |
fut = self._loop.create_task(self._loop.start_tls( |
| 1081 |
transport, self, sslctx_2, server_side=True)) |
| 1082 |
|
| 1083 |
def cb(_): |
| 1084 |
try: |
| 1085 |
tr = fut.result() |
| 1086 |
except Exception as ex: |
| 1087 |
super_.connection_lost(ex) |
| 1088 |
else: |
| 1089 |
super_.connection_made(tr) |
| 1090 |
fut.add_done_callback(cb) |
| 1091 |
|
| 1092 |
def server_protocol_factory(): |
| 1093 |
reader = asyncio.StreamReader() |
| 1094 |
protocol = ServerProtocol(reader, handle_client) |
| 1095 |
return protocol |
| 1096 |
|
| 1097 |
async def test_client(addr): |
| 1098 |
fut = asyncio.Future() |
| 1099 |
|
| 1100 |
def prog(sock): |
| 1101 |
try: |
| 1102 |
sock.connect(addr) |
| 1103 |
sock.starttls(client_sslctx_1) |
| 1104 |
|
| 1105 |
|
| 1106 |
|
| 1107 |
incoming = ssl.MemoryBIO() |
| 1108 |
outgoing = ssl.MemoryBIO() |
| 1109 |
sslobj = client_sslctx_2.wrap_bio(incoming, outgoing) |
| 1110 |
|
| 1111 |
def do(func, *args): |
| 1112 |
while True: |
| 1113 |
try: |
| 1114 |
rv = func(*args) |
| 1115 |
break |
| 1116 |
except ssl.SSLWantReadError: |
| 1117 |
if outgoing.pending: |
| 1118 |
sock.send(outgoing.read()) |
| 1119 |
incoming.write(sock.recv(65536)) |
| 1120 |
if outgoing.pending: |
| 1121 |
sock.send(outgoing.read()) |
| 1122 |
return rv |
| 1123 |
|
| 1124 |
do(sslobj.do_handshake) |
| 1125 |
|
| 1126 |
do(sslobj.write, A_DATA) |
| 1127 |
data = do(sslobj.read, 2) |
| 1128 |
self.assertEqual(data, b'OK') |
| 1129 |
|
| 1130 |
do(sslobj.write, B_DATA) |
| 1131 |
data = b'' |
| 1132 |
while True: |
| 1133 |
chunk = do(sslobj.read, 4) |
| 1134 |
if not chunk: |
| 1135 |
break |
| 1136 |
data += chunk |
| 1137 |
self.assertEqual(data, b'SPAM') |
| 1138 |
|
| 1139 |
do(sslobj.unwrap) |
| 1140 |
sock.close() |
| 1141 |
|
| 1142 |
except Exception as ex: |
| 1143 |
self.loop.call_soon_threadsafe(fut.set_exception, ex) |
| 1144 |
sock.close() |
| 1145 |
else: |
| 1146 |
self.loop.call_soon_threadsafe(fut.set_result, None) |
| 1147 |
|
| 1148 |
client = self.tcp_client(prog) |
| 1149 |
client.start() |
| 1150 |
clients.append(client) |
| 1151 |
|
| 1152 |
await fut |
| 1153 |
|
| 1154 |
async def start_server(): |
| 1155 |
extras = {} |
| 1156 |
|
| 1157 |
srv = await self.loop.create_server( |
| 1158 |
server_protocol_factory, |
| 1159 |
'127.0.0.1', 0, |
| 1160 |
family=socket.AF_INET, |
| 1161 |
ssl=sslctx_1, |
| 1162 |
**extras) |
| 1163 |
|
| 1164 |
try: |
| 1165 |
srv_socks = srv.sockets |
| 1166 |
self.assertTrue(srv_socks) |
| 1167 |
|
| 1168 |
addr = srv_socks[0].getsockname() |
| 1169 |
|
| 1170 |
tasks = [] |
| 1171 |
for _ in range(TOTAL_CNT): |
| 1172 |
tasks.append(test_client(addr)) |
| 1173 |
|
| 1174 |
await asyncio.wait_for(asyncio.gather(*tasks), TIMEOUT) |
| 1175 |
|
| 1176 |
finally: |
| 1177 |
self.loop.call_soon(srv.close) |
| 1178 |
await srv.wait_closed() |
| 1179 |
|
| 1180 |
with self._silence_eof_received_warning(): |
| 1181 |
self.loop.run_until_complete(start_server()) |
| 1182 |
|
| 1183 |
self.assertEqual(CNT, TOTAL_CNT) |
| 1184 |
|
| 1185 |
for client in clients: |
| 1186 |
client.stop() |
| 1187 |
|
| 1188 |
def test_shutdown_cleanly(self): |
| 1189 |
CNT = 0 |
| 1190 |
TOTAL_CNT = 25 |
| 1191 |
|
| 1192 |
A_DATA = b'A' * 1024 * BUF_MULTIPLIER |
| 1193 |
|
| 1194 |
sslctx = self._create_server_ssl_context( |
| 1195 |
test_utils.ONLYCERT, test_utils.ONLYKEY) |
| 1196 |
client_sslctx = self._create_client_ssl_context() |
| 1197 |
|
| 1198 |
def server(sock): |
| 1199 |
sock.starttls( |
| 1200 |
sslctx, |
| 1201 |
server_side=True) |
| 1202 |
|
| 1203 |
data = sock.recv_all(len(A_DATA)) |
| 1204 |
self.assertEqual(data, A_DATA) |
| 1205 |
sock.send(b'OK') |
| 1206 |
|
| 1207 |
sock.unwrap() |
| 1208 |
|
| 1209 |
sock.close() |
| 1210 |
|
| 1211 |
async def client(addr): |
| 1212 |
extras = {} |
| 1213 |
extras = dict(ssl_handshake_timeout=support.SHORT_TIMEOUT) |
| 1214 |
|
| 1215 |
reader, writer = await asyncio.open_connection( |
| 1216 |
*addr, |
| 1217 |
ssl=client_sslctx, |
| 1218 |
server_hostname='', |
| 1219 |
**extras) |
| 1220 |
|
| 1221 |
writer.write(A_DATA) |
| 1222 |
self.assertEqual(await reader.readexactly(2), b'OK') |
| 1223 |
|
| 1224 |
self.assertEqual(await reader.read(), b'') |
| 1225 |
|
| 1226 |
nonlocal CNT |
| 1227 |
CNT += 1 |
| 1228 |
|
| 1229 |
writer.close() |
| 1230 |
await self.wait_closed(writer) |
| 1231 |
|
| 1232 |
def run(coro): |
| 1233 |
nonlocal CNT |
| 1234 |
CNT = 0 |
| 1235 |
|
| 1236 |
async def _gather(*tasks): |
| 1237 |
return await asyncio.gather(*tasks) |
| 1238 |
|
| 1239 |
with self.tcp_server(server, |
| 1240 |
max_clients=TOTAL_CNT, |
| 1241 |
backlog=TOTAL_CNT) as srv: |
| 1242 |
tasks = [] |
| 1243 |
for _ in range(TOTAL_CNT): |
| 1244 |
tasks.append(coro(srv.addr)) |
| 1245 |
|
| 1246 |
self.loop.run_until_complete( |
| 1247 |
_gather(*tasks)) |
| 1248 |
|
| 1249 |
self.assertEqual(CNT, TOTAL_CNT) |
| 1250 |
|
| 1251 |
with self._silence_eof_received_warning(): |
| 1252 |
run(client) |
| 1253 |
|
| 1254 |
def test_flush_before_shutdown(self): |
| 1255 |
CHUNK = 1024 * 128 |
| 1256 |
SIZE = 32 |
| 1257 |
|
| 1258 |
sslctx = self._create_server_ssl_context( |
| 1259 |
test_utils.ONLYCERT, test_utils.ONLYKEY) |
| 1260 |
client_sslctx = self._create_client_ssl_context() |
| 1261 |
|
| 1262 |
future = None |
| 1263 |
|
| 1264 |
def server(sock): |
| 1265 |
sock.starttls(sslctx, server_side=True) |
| 1266 |
self.assertEqual(sock.recv_all(4), b'ping') |
| 1267 |
sock.send(b'pong') |
| 1268 |
time.sleep(0.5) |
| 1269 |
data = sock.recv_all(CHUNK * SIZE) |
| 1270 |
self.assertEqual(len(data), CHUNK * SIZE) |
| 1271 |
sock.close() |
| 1272 |
|
| 1273 |
def run(meth): |
| 1274 |
def wrapper(sock): |
| 1275 |
try: |
| 1276 |
meth(sock) |
| 1277 |
except Exception as ex: |
| 1278 |
self.loop.call_soon_threadsafe(future.set_exception, ex) |
| 1279 |
else: |
| 1280 |
self.loop.call_soon_threadsafe(future.set_result, None) |
| 1281 |
return wrapper |
| 1282 |
|
| 1283 |
async def client(addr): |
| 1284 |
nonlocal future |
| 1285 |
future = self.loop.create_future() |
| 1286 |
reader, writer = await asyncio.open_connection( |
| 1287 |
*addr, |
| 1288 |
ssl=client_sslctx, |
| 1289 |
server_hostname='') |
| 1290 |
sslprotocol = writer.transport._ssl_protocol |
| 1291 |
writer.write(b'ping') |
| 1292 |
data = await reader.readexactly(4) |
| 1293 |
self.assertEqual(data, b'pong') |
| 1294 |
|
| 1295 |
sslprotocol.pause_writing() |
| 1296 |
for _ in range(SIZE): |
| 1297 |
writer.write(b'x' * CHUNK) |
| 1298 |
|
| 1299 |
writer.close() |
| 1300 |
sslprotocol.resume_writing() |
| 1301 |
|
| 1302 |
await self.wait_closed(writer) |
| 1303 |
try: |
| 1304 |
data = await reader.read() |
| 1305 |
self.assertEqual(data, b'') |
| 1306 |
except ConnectionResetError: |
| 1307 |
pass |
| 1308 |
await future |
| 1309 |
|
| 1310 |
with self.tcp_server(run(server)) as srv: |
| 1311 |
self.loop.run_until_complete(client(srv.addr)) |
| 1312 |
|
| 1313 |
def test_remote_shutdown_receives_trailing_data(self): |
| 1314 |
CHUNK = 1024 * 128 |
| 1315 |
SIZE = 32 |
| 1316 |
|
| 1317 |
sslctx = self._create_server_ssl_context( |
| 1318 |
test_utils.ONLYCERT, |
| 1319 |
test_utils.ONLYKEY |
| 1320 |
) |
| 1321 |
client_sslctx = self._create_client_ssl_context() |
| 1322 |
future = None |
| 1323 |
|
| 1324 |
def server(sock): |
| 1325 |
incoming = ssl.MemoryBIO() |
| 1326 |
outgoing = ssl.MemoryBIO() |
| 1327 |
sslobj = sslctx.wrap_bio(incoming, outgoing, server_side=True) |
| 1328 |
|
| 1329 |
while True: |
| 1330 |
try: |
| 1331 |
sslobj.do_handshake() |
| 1332 |
except ssl.SSLWantReadError: |
| 1333 |
if outgoing.pending: |
| 1334 |
sock.send(outgoing.read()) |
| 1335 |
incoming.write(sock.recv(16384)) |
| 1336 |
else: |
| 1337 |
if outgoing.pending: |
| 1338 |
sock.send(outgoing.read()) |
| 1339 |
break |
| 1340 |
|
| 1341 |
while True: |
| 1342 |
try: |
| 1343 |
data = sslobj.read(4) |
| 1344 |
except ssl.SSLWantReadError: |
| 1345 |
incoming.write(sock.recv(16384)) |
| 1346 |
else: |
| 1347 |
break |
| 1348 |
|
| 1349 |
self.assertEqual(data, b'ping') |
| 1350 |
sslobj.write(b'pong') |
| 1351 |
sock.send(outgoing.read()) |
| 1352 |
|
| 1353 |
time.sleep(0.2) |
| 1354 |
|
| 1355 |
|
| 1356 |
with self.assertRaises(ssl.SSLWantReadError): |
| 1357 |
sslobj.unwrap() |
| 1358 |
sock.send(outgoing.read()) |
| 1359 |
|
| 1360 |
|
| 1361 |
data_len = 0 |
| 1362 |
while True: |
| 1363 |
try: |
| 1364 |
chunk = len(sslobj.read(16384)) |
| 1365 |
data_len += chunk |
| 1366 |
except ssl.SSLWantReadError: |
| 1367 |
incoming.write(sock.recv(16384)) |
| 1368 |
except ssl.SSLZeroReturnError: |
| 1369 |
break |
| 1370 |
|
| 1371 |
self.assertEqual(data_len, CHUNK * SIZE) |
| 1372 |
|
| 1373 |
|
| 1374 |
sslobj.unwrap() |
| 1375 |
|
| 1376 |
sock.close() |
| 1377 |
|
| 1378 |
def eof_server(sock): |
| 1379 |
sock.starttls(sslctx, server_side=True) |
| 1380 |
self.assertEqual(sock.recv_all(4), b'ping') |
| 1381 |
sock.send(b'pong') |
| 1382 |
|
| 1383 |
time.sleep(0.2) |
| 1384 |
|
| 1385 |
|
| 1386 |
sock.shutdown(socket.SHUT_WR) |
| 1387 |
|
| 1388 |
|
| 1389 |
data = sock.recv_all(CHUNK * SIZE) |
| 1390 |
self.assertEqual(len(data), CHUNK * SIZE) |
| 1391 |
|
| 1392 |
sock.close() |
| 1393 |
|
| 1394 |
async def client(addr): |
| 1395 |
nonlocal future |
| 1396 |
future = self.loop.create_future() |
| 1397 |
|
| 1398 |
reader, writer = await asyncio.open_connection( |
| 1399 |
*addr, |
| 1400 |
ssl=client_sslctx, |
| 1401 |
server_hostname='') |
| 1402 |
writer.write(b'ping') |
| 1403 |
data = await reader.readexactly(4) |
| 1404 |
self.assertEqual(data, b'pong') |
| 1405 |
|
| 1406 |
|
| 1407 |
for _ in range(SIZE): |
| 1408 |
writer.transport._test__append_write_backlog(b'x' * CHUNK) |
| 1409 |
|
| 1410 |
try: |
| 1411 |
data = await reader.read() |
| 1412 |
self.assertEqual(data, b'') |
| 1413 |
except (BrokenPipeError, ConnectionResetError): |
| 1414 |
pass |
| 1415 |
|
| 1416 |
await future |
| 1417 |
|
| 1418 |
writer.close() |
| 1419 |
await self.wait_closed(writer) |
| 1420 |
|
| 1421 |
def run(meth): |
| 1422 |
def wrapper(sock): |
| 1423 |
try: |
| 1424 |
meth(sock) |
| 1425 |
except Exception as ex: |
| 1426 |
self.loop.call_soon_threadsafe(future.set_exception, ex) |
| 1427 |
else: |
| 1428 |
self.loop.call_soon_threadsafe(future.set_result, None) |
| 1429 |
return wrapper |
| 1430 |
|
| 1431 |
with self.tcp_server(run(server)) as srv: |
| 1432 |
self.loop.run_until_complete(client(srv.addr)) |
| 1433 |
|
| 1434 |
with self.tcp_server(run(eof_server)) as srv: |
| 1435 |
self.loop.run_until_complete(client(srv.addr)) |
| 1436 |
|
| 1437 |
def test_connect_timeout_warning(self): |
| 1438 |
s = socket.socket(socket.AF_INET) |
| 1439 |
s.bind(('127.0.0.1', 0)) |
| 1440 |
addr = s.getsockname() |
| 1441 |
|
| 1442 |
async def test(): |
| 1443 |
try: |
| 1444 |
await asyncio.wait_for( |
| 1445 |
self.loop.create_connection(asyncio.Protocol, |
| 1446 |
*addr, ssl=True), |
| 1447 |
0.1) |
| 1448 |
except (ConnectionRefusedError, asyncio.TimeoutError): |
| 1449 |
pass |
| 1450 |
else: |
| 1451 |
self.fail('TimeoutError is not raised') |
| 1452 |
|
| 1453 |
with s: |
| 1454 |
try: |
| 1455 |
with self.assertWarns(ResourceWarning) as cm: |
| 1456 |
self.loop.run_until_complete(test()) |
| 1457 |
gc.collect() |
| 1458 |
gc.collect() |
| 1459 |
gc.collect() |
| 1460 |
except AssertionError as e: |
| 1461 |
self.assertEqual(str(e), 'ResourceWarning not triggered') |
| 1462 |
else: |
| 1463 |
self.fail('Unexpected ResourceWarning: {}'.format(cm.warning)) |
| 1464 |
|
| 1465 |
def test_handshake_timeout_handler_leak(self): |
| 1466 |
s = socket.socket(socket.AF_INET) |
| 1467 |
s.bind(('127.0.0.1', 0)) |
| 1468 |
s.listen(1) |
| 1469 |
addr = s.getsockname() |
| 1470 |
|
| 1471 |
async def test(ctx): |
| 1472 |
try: |
| 1473 |
await asyncio.wait_for( |
| 1474 |
self.loop.create_connection(asyncio.Protocol, *addr, |
| 1475 |
ssl=ctx), |
| 1476 |
0.1) |
| 1477 |
except (ConnectionRefusedError, asyncio.TimeoutError): |
| 1478 |
pass |
| 1479 |
else: |
| 1480 |
self.fail('TimeoutError is not raised') |
| 1481 |
|
| 1482 |
with s: |
| 1483 |
ctx = ssl.create_default_context() |
| 1484 |
self.loop.run_until_complete(test(ctx)) |
| 1485 |
ctx = weakref.ref(ctx) |
| 1486 |
|
| 1487 |
|
| 1488 |
support.gc_collect() |
| 1489 |
|
| 1490 |
self.assertIsNone(ctx()) |
| 1491 |
|
| 1492 |
def test_shutdown_timeout_handler_leak(self): |
| 1493 |
loop = self.loop |
| 1494 |
|
| 1495 |
def server(sock): |
| 1496 |
sslctx = self._create_server_ssl_context( |
| 1497 |
test_utils.ONLYCERT, |
| 1498 |
test_utils.ONLYKEY |
| 1499 |
) |
| 1500 |
sock = sslctx.wrap_socket(sock, server_side=True) |
| 1501 |
sock.recv(32) |
| 1502 |
sock.close() |
| 1503 |
|
| 1504 |
class Protocol(asyncio.Protocol): |
| 1505 |
def __init__(self): |
| 1506 |
self.fut = asyncio.Future(loop=loop) |
| 1507 |
|
| 1508 |
def connection_lost(self, exc): |
| 1509 |
self.fut.set_result(None) |
| 1510 |
|
| 1511 |
async def client(addr, ctx): |
| 1512 |
tr, pr = await loop.create_connection(Protocol, *addr, ssl=ctx) |
| 1513 |
tr.close() |
| 1514 |
await pr.fut |
| 1515 |
|
| 1516 |
with self.tcp_server(server) as srv: |
| 1517 |
ctx = self._create_client_ssl_context() |
| 1518 |
loop.run_until_complete(client(srv.addr, ctx)) |
| 1519 |
ctx = weakref.ref(ctx) |
| 1520 |
|
| 1521 |
|
| 1522 |
|
| 1523 |
|
| 1524 |
gc.collect() |
| 1525 |
gc.collect() |
| 1526 |
gc.collect() |
| 1527 |
|
| 1528 |
|
| 1529 |
self.assertIsNone(ctx()) |
| 1530 |
|
| 1531 |
def test_shutdown_timeout_handler_not_set(self): |
| 1532 |
loop = self.loop |
| 1533 |
eof = asyncio.Event() |
| 1534 |
extra = None |
| 1535 |
|
| 1536 |
def server(sock): |
| 1537 |
sslctx = self._create_server_ssl_context( |
| 1538 |
test_utils.ONLYCERT, |
| 1539 |
test_utils.ONLYKEY |
| 1540 |
) |
| 1541 |
sock = sslctx.wrap_socket(sock, server_side=True) |
| 1542 |
sock.send(b'hello') |
| 1543 |
assert sock.recv(1024) == b'world' |
| 1544 |
sock.send(b'extra bytes') |
| 1545 |
|
| 1546 |
sock.shutdown(socket.SHUT_WR) |
| 1547 |
loop.call_soon_threadsafe(eof.set) |
| 1548 |
|
| 1549 |
assert sock.recv(1024) == b'' |
| 1550 |
sock.close() |
| 1551 |
|
| 1552 |
class Protocol(asyncio.Protocol): |
| 1553 |
def __init__(self): |
| 1554 |
self.fut = asyncio.Future(loop=loop) |
| 1555 |
self.transport = None |
| 1556 |
|
| 1557 |
def connection_made(self, transport): |
| 1558 |
self.transport = transport |
| 1559 |
|
| 1560 |
def data_received(self, data): |
| 1561 |
if data == b'hello': |
| 1562 |
self.transport.write(b'world') |
| 1563 |
|
| 1564 |
self.transport.pause_reading() |
| 1565 |
else: |
| 1566 |
nonlocal extra |
| 1567 |
extra = data |
| 1568 |
|
| 1569 |
def connection_lost(self, exc): |
| 1570 |
if exc is None: |
| 1571 |
self.fut.set_result(None) |
| 1572 |
else: |
| 1573 |
self.fut.set_exception(exc) |
| 1574 |
|
| 1575 |
async def client(addr): |
| 1576 |
ctx = self._create_client_ssl_context() |
| 1577 |
tr, pr = await loop.create_connection(Protocol, *addr, ssl=ctx) |
| 1578 |
await eof.wait() |
| 1579 |
tr.resume_reading() |
| 1580 |
await pr.fut |
| 1581 |
tr.close() |
| 1582 |
assert extra == b'extra bytes' |
| 1583 |
|
| 1584 |
with self.tcp_server(server) as srv: |
| 1585 |
loop.run_until_complete(client(srv.addr)) |
| 1586 |
|
| 1587 |
|
| 1588 |
|
| 1589 |
|
| 1590 |
|
| 1591 |
|
| 1592 |
|
| 1593 |
class TestSocketWrapper: |
| 1594 |
|
| 1595 |
def __init__(self, sock): |
| 1596 |
self.__sock = sock |
| 1597 |
|
| 1598 |
def recv_all(self, n): |
| 1599 |
buf = b'' |
| 1600 |
while len(buf) < n: |
| 1601 |
data = self.recv(n - len(buf)) |
| 1602 |
if data == b'': |
| 1603 |
raise ConnectionAbortedError |
| 1604 |
buf += data |
| 1605 |
return buf |
| 1606 |
|
| 1607 |
def starttls(self, ssl_context, *, |
| 1608 |
server_side=False, |
| 1609 |
server_hostname=None, |
| 1610 |
do_handshake_on_connect=True): |
| 1611 |
|
| 1612 |
assert isinstance(ssl_context, ssl.SSLContext) |
| 1613 |
|
| 1614 |
ssl_sock = ssl_context.wrap_socket( |
| 1615 |
self.__sock, server_side=server_side, |
| 1616 |
server_hostname=server_hostname, |
| 1617 |
do_handshake_on_connect=do_handshake_on_connect) |
| 1618 |
|
| 1619 |
if server_side: |
| 1620 |
ssl_sock.do_handshake() |
| 1621 |
|
| 1622 |
self.__sock.close() |
| 1623 |
self.__sock = ssl_sock |
| 1624 |
|
| 1625 |
def __getattr__(self, name): |
| 1626 |
return getattr(self.__sock, name) |
| 1627 |
|
| 1628 |
def __repr__(self): |
| 1629 |
return '<{} {!r}>'.format(type(self).__name__, self.__sock) |
| 1630 |
|
| 1631 |
|
| 1632 |
class SocketThread(threading.Thread): |
| 1633 |
|
| 1634 |
def stop(self): |
| 1635 |
self._active = False |
| 1636 |
self.join() |
| 1637 |
|
| 1638 |
def __enter__(self): |
| 1639 |
self.start() |
| 1640 |
return self |
| 1641 |
|
| 1642 |
def __exit__(self, *exc): |
| 1643 |
self.stop() |
| 1644 |
|
| 1645 |
|
| 1646 |
class TestThreadedClient(SocketThread): |
| 1647 |
|
| 1648 |
def __init__(self, test, sock, prog, timeout): |
| 1649 |
threading.Thread.__init__(self, None, None, 'test-client') |
| 1650 |
self.daemon = True |
| 1651 |
|
| 1652 |
self._timeout = timeout |
| 1653 |
self._sock = sock |
| 1654 |
self._active = True |
| 1655 |
self._prog = prog |
| 1656 |
self._test = test |
| 1657 |
|
| 1658 |
def run(self): |
| 1659 |
try: |
| 1660 |
self._prog(TestSocketWrapper(self._sock)) |
| 1661 |
except (KeyboardInterrupt, SystemExit): |
| 1662 |
raise |
| 1663 |
except BaseException as ex: |
| 1664 |
self._test._abort_socket_test(ex) |
| 1665 |
|
| 1666 |
|
| 1667 |
class TestThreadedServer(SocketThread): |
| 1668 |
|
| 1669 |
def __init__(self, test, sock, prog, timeout, max_clients): |
| 1670 |
threading.Thread.__init__(self, None, None, 'test-server') |
| 1671 |
self.daemon = True |
| 1672 |
|
| 1673 |
self._clients = 0 |
| 1674 |
self._finished_clients = 0 |
| 1675 |
self._max_clients = max_clients |
| 1676 |
self._timeout = timeout |
| 1677 |
self._sock = sock |
| 1678 |
self._active = True |
| 1679 |
|
| 1680 |
self._prog = prog |
| 1681 |
|
| 1682 |
self._s1, self._s2 = socket.socketpair() |
| 1683 |
self._s1.setblocking(False) |
| 1684 |
|
| 1685 |
self._test = test |
| 1686 |
|
| 1687 |
def stop(self): |
| 1688 |
try: |
| 1689 |
if self._s2 and self._s2.fileno() != -1: |
| 1690 |
try: |
| 1691 |
self._s2.send(b'stop') |
| 1692 |
except OSError: |
| 1693 |
pass |
| 1694 |
finally: |
| 1695 |
super().stop() |
| 1696 |
|
| 1697 |
def run(self): |
| 1698 |
try: |
| 1699 |
with self._sock: |
| 1700 |
self._sock.setblocking(False) |
| 1701 |
self._run() |
| 1702 |
finally: |
| 1703 |
self._s1.close() |
| 1704 |
self._s2.close() |
| 1705 |
|
| 1706 |
def _run(self): |
| 1707 |
while self._active: |
| 1708 |
if self._clients >= self._max_clients: |
| 1709 |
return |
| 1710 |
|
| 1711 |
r, w, x = select.select( |
| 1712 |
[self._sock, self._s1], [], [], self._timeout) |
| 1713 |
|
| 1714 |
if self._s1 in r: |
| 1715 |
return |
| 1716 |
|
| 1717 |
if self._sock in r: |
| 1718 |
try: |
| 1719 |
conn, addr = self._sock.accept() |
| 1720 |
except BlockingIOError: |
| 1721 |
continue |
| 1722 |
except socket.timeout: |
| 1723 |
if not self._active: |
| 1724 |
return |
| 1725 |
else: |
| 1726 |
raise |
| 1727 |
else: |
| 1728 |
self._clients += 1 |
| 1729 |
conn.settimeout(self._timeout) |
| 1730 |
try: |
| 1731 |
with conn: |
| 1732 |
self._handle_client(conn) |
| 1733 |
except (KeyboardInterrupt, SystemExit): |
| 1734 |
raise |
| 1735 |
except BaseException as ex: |
| 1736 |
self._active = False |
| 1737 |
try: |
| 1738 |
raise |
| 1739 |
finally: |
| 1740 |
self._test._abort_socket_test(ex) |
| 1741 |
|
| 1742 |
def _handle_client(self, sock): |
| 1743 |
self._prog(TestSocketWrapper(sock)) |
| 1744 |
|
| 1745 |
@property |
| 1746 |
def addr(self): |
| 1747 |
return self._sock.getsockname() |
| 1748 |
|
| 1749 |
|
| 1750 |
if __name__ == '__main__': |
| 1751 |
unittest.main() |