| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import ssl |
| 4 |
from math import inf |
| 5 |
from typing import Any, Generator, Optional |
| 6 |
|
| 7 |
import trio |
| 8 |
|
| 9 |
from .task_group import TaskGroup |
| 10 |
from .worker_context import WorkerContext |
| 11 |
from ..config import Config |
| 12 |
from ..events import Closed, Event, RawData, Updated |
| 13 |
from ..protocol import ProtocolWrapper |
| 14 |
from ..typing import AppWrapper |
| 15 |
from ..utils import parse_socket_addr |
| 16 |
|
| 17 |
MAX_RECV = 2**16 |
| 18 |
|
| 19 |
|
| 20 |
class TCPServer: |
| 21 |
def __init__( |
| 22 |
self, app: AppWrapper, config: Config, context: WorkerContext, stream: trio.abc.Stream |
| 23 |
) -> None: |
| 24 |
self.app = app |
| 25 |
self.config = config |
| 26 |
self.context = context |
| 27 |
self.protocol: ProtocolWrapper |
| 28 |
self.send_lock = trio.Lock() |
| 29 |
self.idle_lock = trio.Lock() |
| 30 |
self.stream = stream |
| 31 |
|
| 32 |
self._idle_handle: Optional[trio.CancelScope] = None |
| 33 |
|
| 34 |
def __await__(self) -> Generator[Any, None, None]: |
| 35 |
return self.run().__await__() |
| 36 |
|
| 37 |
async def run(self) -> None: |
| 38 |
try: |
| 39 |
try: |
| 40 |
with trio.fail_after(self.config.ssl_handshake_timeout): |
| 41 |
await self.stream.do_handshake() |
| 42 |
except (trio.BrokenResourceError, trio.TooSlowError): |
| 43 |
return # Handshake failed |
| 44 |
alpn_protocol = self.stream.selected_alpn_protocol() |
| 45 |
socket = self.stream.transport_stream.socket |
| 46 |
|
| 47 |
tls = {"alpn_protocol": alpn_protocol} |
| 48 |
client_certificate = self.stream.getpeercert(binary_form=False) |
| 49 |
if client_certificate: |
| 50 |
tls["client_cert_name"] = ", ".join( |
| 51 |
[f"{part[0][0]}={part[0][1]}" for part in client_certificate["subject"]] |
| 52 |
) |
| 53 |
except AttributeError: # Not SSL |
| 54 |
alpn_protocol = "http/1.1" |
| 55 |
socket = self.stream.socket |
| 56 |
tls = None |
| 57 |
|
| 58 |
try: |
| 59 |
client = parse_socket_addr(socket.family, socket.getpeername()) |
| 60 |
server = parse_socket_addr(socket.family, socket.getsockname()) |
| 61 |
|
| 62 |
async with TaskGroup() as task_group: |
| 63 |
self._task_group = task_group |
| 64 |
self.protocol = ProtocolWrapper( |
| 65 |
self.app, |
| 66 |
self.config, |
| 67 |
self.context, |
| 68 |
task_group, |
| 69 |
tls, |
| 70 |
client, |
| 71 |
server, |
| 72 |
self.protocol_send, |
| 73 |
alpn_protocol, |
| 74 |
self.stream, |
| 75 |
) |
| 76 |
await self.protocol.initiate() |
| 77 |
await self._start_idle() |
| 78 |
await self._read_data() |
| 79 |
except OSError: |
| 80 |
pass |
| 81 |
finally: |
| 82 |
await self._close() |
| 83 |
|
| 84 |
async def protocol_send(self, event: Event) -> None: |
| 85 |
if isinstance(event, RawData): |
| 86 |
async with self.send_lock: |
| 87 |
try: |
| 88 |
with trio.CancelScope() as cancel_scope: |
| 89 |
cancel_scope.shield = True |
| 90 |
await self.stream.send_all(event.data) |
| 91 |
except (trio.BrokenResourceError, trio.ClosedResourceError): |
| 92 |
await self.protocol.handle(Closed()) |
| 93 |
elif isinstance(event, Closed): |
| 94 |
await self._close() |
| 95 |
await self.protocol.handle(Closed()) |
| 96 |
elif isinstance(event, Updated): |
| 97 |
if event.idle: |
| 98 |
await self._start_idle() |
| 99 |
else: |
| 100 |
await self._stop_idle() |
| 101 |
|
| 102 |
async def _read_data(self) -> None: |
| 103 |
while True: |
| 104 |
try: |
| 105 |
with trio.fail_after(self.config.read_timeout or inf): |
| 106 |
data = await self.stream.receive_some(MAX_RECV) |
| 107 |
except ( |
| 108 |
trio.ClosedResourceError, |
| 109 |
trio.BrokenResourceError, |
| 110 |
trio.TooSlowError, |
| 111 |
): |
| 112 |
break |
| 113 |
else: |
| 114 |
await self.protocol.handle(RawData(data)) |
| 115 |
if data == b"": |
| 116 |
break |
| 117 |
await self.protocol.handle(Closed()) |
| 118 |
|
| 119 |
async def _close(self) -> None: |
| 120 |
try: |
| 121 |
await self.stream.send_eof() |
| 122 |
except ( |
| 123 |
trio.BrokenResourceError, |
| 124 |
AttributeError, |
| 125 |
trio.BusyResourceError, |
| 126 |
trio.ClosedResourceError, |
| 127 |
): |
| 128 |
# They're already gone, nothing to do |
| 129 |
# Or it is a SSL stream |
| 130 |
pass |
| 131 |
await self.stream.aclose() |
| 132 |
|
| 133 |
async def _initiate_server_close(self) -> None: |
| 134 |
await self.protocol.handle(Closed()) |
| 135 |
await self.stream.aclose() |
| 136 |
|
| 137 |
async def _start_idle(self) -> None: |
| 138 |
async with self.idle_lock: |
| 139 |
if self._idle_handle is None: |
| 140 |
self._idle_handle = await self._task_group._nursery.start(self._run_idle) |
| 141 |
|
| 142 |
async def _stop_idle(self) -> None: |
| 143 |
async with self.idle_lock: |
| 144 |
if self._idle_handle is not None: |
| 145 |
self._idle_handle.cancel() |
| 146 |
self._idle_handle = None |
| 147 |
|
| 148 |
async def _run_idle( |
| 149 |
self, |
| 150 |
task_status: trio._core._run._TaskStatus = trio.TASK_STATUS_IGNORED, |
| 151 |
) -> None: |
| 152 |
cancel_scope = trio.CancelScope() |
| 153 |
task_status.started(cancel_scope) |
| 154 |
with cancel_scope: |
| 155 |
with trio.move_on_after(self.config.keep_alive_timeout): |
| 156 |
await self.context.terminated.wait() |
| 157 |
|
| 158 |
cancel_scope.shield = True |
| 159 |
await self._initiate_server_close() |