Python non-blocking SSL socket unwrap: how to detect completion of shutdown handshake?

Viewed 1085

Given a non-blocking socket...

import asyncio
import socket

server_sock = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM, proto=socket.IPPROTO_TCP)
server_sock.setblocking(False)
server_sock.bind(('', port))
server_sock.listen(socket.IPPROTO_TCP)

loop = asyncio.get_event_loop()
sock, _ = await loop.sock_accept(server_sock)

... that is wrapped with ssl...

import ssl
ssl_context = ssl.SSLContext(PROTOCOL_TLSv1_2)
ssl_context.load_cert_chain(f'ssl.crt', keyfile=f'ssl.key')
ssl_sock = ssl_context.wrap_socket(sock, server_side=True, do_handshake_on_connect=False)

... and has had the setup handshake performed by do_handshake and a loop...

while True:
    try:
        ssl_sock.do_handshake()
        break
    except (ssl.SSLWantReadError, ssl.SSLWantWriteError):
        # We could have something more efficient, e.g. doing things
        # with the readers/writers, but it works
        await asyncio.sleep(0)

... and then the unwrap method called to initiate the shutdown handshake...

try:
    ssl_sock.unwrap()
except (SSLWantReadError, SSLWantWriteError):
    pass

... then how can I wait for completion of the shutdown handshake? So I can write something like...

await ssl_shutdown_handshake_complete()

?

0 Answers
Related