Debian Codegraph @

src/trio/_highlevel_ssl_helpers.py

raw
1 from __future__ import annotations
2
3 import ssl
4 from typing import TYPE_CHECKING, NoReturn, TypeVar
5
6 import trio
7
8 from ._highlevel_open_tcp_stream import DEFAULT_DELAY
9
10 T = TypeVar("T")
11
12 if TYPE_CHECKING:
13 from collections.abc import Awaitable, Callable
14
15 from ._highlevel_socket import SocketStream
16
17
18 # It might have been nice to take a ssl_protocols= argument here to set up
19 # NPN/ALPN, but to do this we have to mutate the context object, which is OK
20 # if it's one we created, but not OK if it's one that was passed in... and
21 # the one major protocol using NPN/ALPN is HTTP/2, which mandates that you use
22 # a specially configured SSLContext anyway! I also thought maybe we could copy
23 # the given SSLContext and then mutate the copy, but it's no good as SSLContext
24 # objects can't be copied: https://bugs.python.org/issue33023.
25 # So... let's punt on that for now. Hopefully we'll be getting a new Python
26 # TLS API soon and can revisit this then.
27 async def open_ssl_over_tcp_stream(
28 host: str | bytes,
29 port: int,
30 *,
31 https_compatible: bool = False,
32 ssl_context: ssl.SSLContext | None = None,
33 happy_eyeballs_delay: float | None = DEFAULT_DELAY,
34 ) -> trio.SSLStream[SocketStream]:
35 """Make a TLS-encrypted Connection to the given host and port over TCP.
36
37 This is a convenience wrapper that calls :func:`open_tcp_stream` and
38 wraps the result in an :class:`~trio.SSLStream`.
39
40 This function does not perform the TLS handshake; you can do it
41 manually by calling :meth:`~trio.SSLStream.do_handshake`, or else
42 it will be performed automatically the first time you send or receive
43 data.
44
45 Args:
46 host (bytes or str): The host to connect to. We require the server
47 to have a TLS certificate valid for this hostname.
48 port (int): The port to connect to.
49 https_compatible (bool): Set this to True if you're connecting to a web
50 server. See :class:`~trio.SSLStream` for details. Default:
51 False.
52 ssl_context (:class:`~ssl.SSLContext` or None): The SSL context to
53 use. If None (the default), :func:`ssl.create_default_context`
54 will be called to create a context.
55 happy_eyeballs_delay (float): See :func:`open_tcp_stream`.
56
57 Returns:
58 trio.SSLStream: the encrypted connection to the server.
59
60 """
61 tcp_stream = await trio.open_tcp_stream(
62 host,
63 port,
64 happy_eyeballs_delay=happy_eyeballs_delay,
65 )
66 if ssl_context is None:
67 ssl_context = ssl.create_default_context()
68
69 if hasattr(ssl, "OP_IGNORE_UNEXPECTED_EOF"):
70 ssl_context.options &= ~ssl.OP_IGNORE_UNEXPECTED_EOF
71
72 return trio.SSLStream(
73 tcp_stream,
74 ssl_context,
75 server_hostname=host,
76 https_compatible=https_compatible,
77 )
78
79
80 async def open_ssl_over_tcp_listeners(
81 port: int,
82 ssl_context: ssl.SSLContext,
83 *,
84 host: str | bytes | None = None,
85 https_compatible: bool = False,
86 backlog: int | None = None,
87 ) -> list[trio.SSLListener[SocketStream]]:
88 """Start listening for SSL/TLS-encrypted TCP connections to the given port.
89
90 Args:
91 port (int): The port to listen on. See :func:`open_tcp_listeners`.
92 ssl_context (~ssl.SSLContext): The SSL context to use for all incoming
93 connections.
94 host (str, bytes, or None): The address to bind to; use ``None`` to bind
95 to the wildcard address. See :func:`open_tcp_listeners`.
96 https_compatible (bool): See :class:`~trio.SSLStream` for details.
97 backlog (int or None): See :func:`open_tcp_listeners` for details.
98
99 """
100 tcp_listeners = await trio.open_tcp_listeners(port, host=host, backlog=backlog)
101 ssl_listeners = [
102 trio.SSLListener(tcp_listener, ssl_context, https_compatible=https_compatible)
103 for tcp_listener in tcp_listeners
104 ]
105 return ssl_listeners
106
107
108 async def serve_ssl_over_tcp(
109 handler: Callable[[trio.SSLStream[SocketStream]], Awaitable[object]],
110 port: int,
111 ssl_context: ssl.SSLContext,
112 *,
113 host: str | bytes | None = None,
114 https_compatible: bool = False,
115 backlog: int | None = None,
116 handler_nursery: trio.Nursery | None = None,
117 task_status: trio.TaskStatus[
118 list[trio.SSLListener[SocketStream]]
119 ] = trio.TASK_STATUS_IGNORED,
120 ) -> NoReturn:
121 """Listen for incoming TCP connections, and for each one start a task
122 running ``handler(stream)``.
123
124 This is a thin convenience wrapper around
125 :func:`open_ssl_over_tcp_listeners` and :func:`serve_listeners` – see them
126 for full details.
127
128 .. warning::
129
130 If ``handler`` raises an exception, then this function doesn't do
131 anything special to catch it – so by default the exception will
132 propagate out and crash your server. If you don't want this, then catch
133 exceptions inside your ``handler``, or use a ``handler_nursery`` object
134 that responds to exceptions in some other way.
135
136 When used with ``nursery.start`` you get back the newly opened listeners.
137 See the documentation for :func:`serve_tcp` for an example where this is
138 useful.
139
140 Args:
141 handler: The handler to start for each incoming connection. Passed to
142 :func:`serve_listeners`.
143
144 port (int): The port to listen on. Use 0 to let the kernel pick
145 an open port. Ultimately passed to :func:`open_tcp_listeners`.
146
147 ssl_context (~ssl.SSLContext): The SSL context to use for all incoming
148 connections. Passed to :func:`open_ssl_over_tcp_listeners`.
149
150 host (str, bytes, or None): The address to bind to; use ``None`` to bind
151 to the wildcard address. Ultimately passed to
152 :func:`open_tcp_listeners`.
153
154 https_compatible (bool): Set this to True if you want to use
155 "HTTPS-style" TLS. See :class:`~trio.SSLStream` for details.
156
157 backlog (int or None): See :class:`~trio.SSLStream` for details.
158
159 handler_nursery: The nursery to start handlers in, or None to use an
160 internal nursery. Passed to :func:`serve_listeners`.
161
162 task_status: This function can be used with ``nursery.start``.
163
164 Returns:
165 This function only returns when cancelled.
166
167 """
168 listeners = await trio.open_ssl_over_tcp_listeners(
169 port,
170 ssl_context,
171 host=host,
172 https_compatible=https_compatible,
173 backlog=backlog,
174 )
175 await trio.serve_listeners(
176 handler,
177 listeners,
178 handler_nursery=handler_nursery,
179 task_status=task_status,
180 )