| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import os |
| 4 |
from contextlib import contextmanager |
| 5 |
from typing import TYPE_CHECKING, Protocol, TypeVar |
| 6 |
|
| 7 |
import trio |
| 8 |
from trio.socket import SOCK_STREAM, socket |
| 9 |
|
| 10 |
if TYPE_CHECKING: |
| 11 |
from collections.abc import Generator |
| 12 |
|
| 13 |
|
| 14 |
class Closable(Protocol): |
| 15 |
def close(self) -> None: ... |
| 16 |
|
| 17 |
|
| 18 |
CloseT = TypeVar("CloseT", bound=Closable) |
| 19 |
|
| 20 |
|
| 21 |
try: |
| 22 |
from trio.socket import AF_UNIX |
| 23 |
|
| 24 |
has_unix = True |
| 25 |
except ImportError: |
| 26 |
has_unix = False |
| 27 |
|
| 28 |
|
| 29 |
@contextmanager |
| 30 |
def close_on_error(obj: CloseT) -> Generator[CloseT, None, None]: |
| 31 |
try: |
| 32 |
yield obj |
| 33 |
except: |
| 34 |
obj.close() |
| 35 |
raise |
| 36 |
|
| 37 |
|
| 38 |
async def open_unix_socket( |
| 39 |
filename: str | bytes | os.PathLike[str] | os.PathLike[bytes], |
| 40 |
) -> trio.SocketStream: |
| 41 |
"""Opens a connection to the specified |
| 42 |
`Unix domain socket <https://en.wikipedia.org/wiki/Unix_domain_socket>`__. |
| 43 |
|
| 44 |
You must have read/write permission on the specified file to connect. |
| 45 |
|
| 46 |
Args: |
| 47 |
filename (str or bytes): The filename to open the connection to. |
| 48 |
|
| 49 |
Returns: |
| 50 |
SocketStream: a :class:`~trio.abc.Stream` connected to the given file. |
| 51 |
|
| 52 |
Raises: |
| 53 |
OSError: If the socket file could not be connected to. |
| 54 |
RuntimeError: If AF_UNIX sockets are not supported. |
| 55 |
""" |
| 56 |
if not has_unix: |
| 57 |
raise RuntimeError("Unix sockets are not supported on this platform") |
| 58 |
|
| 59 |
# much more simplified logic vs tcp sockets - one socket type and only one |
| 60 |
# possible location to connect to |
| 61 |
sock = socket(AF_UNIX, SOCK_STREAM) |
| 62 |
with close_on_error(sock): |
| 63 |
await sock.connect(os.fspath(filename)) |
| 64 |
|
| 65 |
return trio.SocketStream(sock) |