sockat 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sockat-0.1.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yoshiaki Kawazu (@kawaz)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
sockat-0.1.1/PKG-INFO ADDED
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.4
2
+ Name: sockat
3
+ Version: 0.1.1
4
+ Summary: Bind / connect Unix domain sockets at paths longer than sun_path
5
+ Keywords: unix,socket,sun_path,AF_UNIX,ENAMETOOLONG
6
+ Author: Yoshiaki Kawazu
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: POSIX
12
+ Classifier: Operating System :: POSIX :: Linux
13
+ Classifier: Operating System :: POSIX :: BSD
14
+ Classifier: Operating System :: MacOS
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Topic :: System :: Networking
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.11
20
+ Project-URL: Homepage, https://github.com/kawaz/sockat-py
21
+ Project-URL: Repository, https://github.com/kawaz/sockat-py
22
+ Project-URL: Specification, https://github.com/kawaz/sockat/blob/main/docs/SPEC.md
23
+ Description-Content-Type: text/markdown
24
+
25
+ # sockat
26
+
27
+ > English | [日本語](./README-ja.md)
28
+
29
+ A Python library that binds and connects Unix domain sockets even when the path is longer than `sun_path` allows (104 bytes on macOS and the BSDs, 108 on Linux, NUL included).
30
+
31
+ The language-independent behaviour is defined by the [sockat specification](https://github.com/kawaz/sockat/blob/main/docs/SPEC.md); sockat-py is its Python implementation.
32
+
33
+ ```python
34
+ import sockat
35
+
36
+ listener = sockat.bind("/a/very/deep/directory/.../server.sock")
37
+ client = sockat.connect("/a/very/deep/directory/.../server.sock")
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ ```sh
43
+ pip install sockat
44
+ ```
45
+
46
+ Use `sockat.bind` / `sockat.connect` instead of creating a `socket.socket(AF_UNIX, SOCK_STREAM)` and calling `bind` + `listen` / `connect`. In an event loop such as asyncio, use `sockat.connect_nonblocking`, which does not wait and returns a nonblocking socket.
47
+
48
+ | Function | Standard library code it replaces | Returns |
49
+ |---|---|---|
50
+ | `sockat.bind(path)` | `socket()` → `bind(path)` → `listen()` | a listening `socket.socket` |
51
+ | `sockat.connect(path)` | `socket()` → `connect(path)` | a `socket.socket` |
52
+ | `sockat.connect_nonblocking(path)` | `socket()` → `setblocking(False)` → `connect(path)` | a nonblocking `socket.socket` |
53
+
54
+ - The results are the standard library's own `socket.socket`
55
+ - A path that the standard library accepts is handed to it unchanged, so it behaves exactly as with the standard library
56
+ - Even for a long path, the socket file is created at the path given
57
+ - `path` is a `str` / `bytes` / `os.PathLike`
58
+ - Python 3.11 or later. No dependencies (pure Python)
59
+
60
+ ## Why
61
+
62
+ The standard library's `socket.bind` / `socket.connect` refuse a path that does not fit `sun_path` with `OSError('AF_UNIX path too long')`. The file system has no such limit, but deep temporary directories hit it quickly (macOS's `$TMPDIR` alone is about 50 bytes, and test harnesses and sandboxes nest further). The limit applies to the argument passed to `bind(2)` / `connect(2)`, so sockat hands the kernel a short spelling that names the same place.
63
+
64
+ ## How a long path is reached
65
+
66
+ A path that the standard library accepts (up to `sun_path` − 1 bytes) is handed to it unchanged.
67
+
68
+ | OS | Handed to the standard library |
69
+ |---|---|
70
+ | Linux / Android / illumos | up to 107 bytes |
71
+ | macOS / iOS / FreeBSD / NetBSD / OpenBSD | up to 103 bytes |
72
+
73
+ A longer path is tried on the routes below, in this order per OS, and bound / connected on the first route that can be used.
74
+
75
+ | OS | Order tried |
76
+ |---|---|
77
+ | Linux / Android (`/proc` usable) | /proc |
78
+ | Linux / Android (`/proc` not usable) | relative path → symlink → thread cwd |
79
+ | FreeBSD | bindat |
80
+ | macOS / iOS | relative path → widened sockaddr → symlink → thread cwd |
81
+ | NetBSD / OpenBSD / illumos / other Unix | relative path → symlink |
82
+ | Windows | not supported (`ImportError` on import) |
83
+
84
+ | Route | How |
85
+ |---|---|
86
+ | /proc | open the directory and pass `/proc/self/fd/<fd>/<file name>` |
87
+ | bindat | `bindat(2)` / `connectat(2)`, by the file name relative to the directory fd |
88
+ | relative path | pass the path relative to the cwd. Only the string is rewritten; the cwd is never changed |
89
+ | widened sockaddr | pass a sockaddr carrying up to 253 bytes, which the macOS kernel accepts |
90
+ | symlink | create a short symlink under `TMPDIR` or `/tmp`, go through it, and remove it at once. It is created only in a place where no other user can replace it |
91
+ | thread cwd | move the cwd of a throwaway thread alone into the directory and pass the file name. The process's cwd is never changed |
92
+ | fork | **none** (the specification's fork route is not built. Neither are the specification's `connect_any` variants) |
93
+
94
+ - None of the routes changes the calling process's cwd, so they can be used from multi-threaded programs
95
+ - A path that fits no route gets `ENAMETOOLONG` (an `OSError` with errno), as a path too long for the standard library does
96
+ - On macOS / Linux, where the thread cwd route can be used, a path is reached at any depth as long as the file name is within 253 bytes (107 on Linux). Linux cannot use the thread cwd route under a seccomp filter (docker's default, for example)
97
+ - The length limits of each route, and where a path stops being reached, are in [docs/MANUAL.md](./docs/MANUAL.md#how-a-long-path-is-reached)
98
+
99
+ ## What differs from the standard library for a long path
100
+
101
+ - `getsockname()` / `getpeername()` do not return the original path: they return the spelling handed to the kernel at bind time (a relative path, `/proc/self/fd/...`, a path through a symlink that no longer exists, the file name alone, ...). Keep the original path yourself
102
+ - A path too long for the standard library that does not end with a name (ending in `dir/`, `dir/.`, `..`) is a `ValueError`
103
+ - A path containing a NUL anywhere but at its start is a `ValueError` at any length (the standard library silently truncates at the NUL). On Linux a path starting with a NUL (abstract namespace) is handed to the standard library unchanged
104
+ - The rest (the directory being looked up first, a symlink that may be left behind) is in [docs/MANUAL.md](./docs/MANUAL.md#what-differs-from-the-standard-library-for-a-long-path)
105
+
106
+ ## asyncio
107
+
108
+ ```python
109
+ listener = sockat.bind(path)
110
+ server = await asyncio.start_unix_server(handle, sock=listener)
111
+
112
+ reader, writer = await asyncio.open_unix_connection(sock=sockat.connect_nonblocking(path))
113
+ ```
114
+
115
+ ## Documentation
116
+
117
+ - [docs/MANUAL.md](./docs/MANUAL.md) — usage, the routes in detail, what differs from the standard library, errors
118
+ - [docs/decisions/](./docs/decisions/INDEX.md) — design decisions (DRs, in Japanese)
119
+
120
+ ## License
121
+
122
+ MIT License, Yoshiaki Kawazu (@kawaz)
sockat-0.1.1/README.md ADDED
@@ -0,0 +1,98 @@
1
+ # sockat
2
+
3
+ > English | [日本語](./README-ja.md)
4
+
5
+ A Python library that binds and connects Unix domain sockets even when the path is longer than `sun_path` allows (104 bytes on macOS and the BSDs, 108 on Linux, NUL included).
6
+
7
+ The language-independent behaviour is defined by the [sockat specification](https://github.com/kawaz/sockat/blob/main/docs/SPEC.md); sockat-py is its Python implementation.
8
+
9
+ ```python
10
+ import sockat
11
+
12
+ listener = sockat.bind("/a/very/deep/directory/.../server.sock")
13
+ client = sockat.connect("/a/very/deep/directory/.../server.sock")
14
+ ```
15
+
16
+ ## Usage
17
+
18
+ ```sh
19
+ pip install sockat
20
+ ```
21
+
22
+ Use `sockat.bind` / `sockat.connect` instead of creating a `socket.socket(AF_UNIX, SOCK_STREAM)` and calling `bind` + `listen` / `connect`. In an event loop such as asyncio, use `sockat.connect_nonblocking`, which does not wait and returns a nonblocking socket.
23
+
24
+ | Function | Standard library code it replaces | Returns |
25
+ |---|---|---|
26
+ | `sockat.bind(path)` | `socket()` → `bind(path)` → `listen()` | a listening `socket.socket` |
27
+ | `sockat.connect(path)` | `socket()` → `connect(path)` | a `socket.socket` |
28
+ | `sockat.connect_nonblocking(path)` | `socket()` → `setblocking(False)` → `connect(path)` | a nonblocking `socket.socket` |
29
+
30
+ - The results are the standard library's own `socket.socket`
31
+ - A path that the standard library accepts is handed to it unchanged, so it behaves exactly as with the standard library
32
+ - Even for a long path, the socket file is created at the path given
33
+ - `path` is a `str` / `bytes` / `os.PathLike`
34
+ - Python 3.11 or later. No dependencies (pure Python)
35
+
36
+ ## Why
37
+
38
+ The standard library's `socket.bind` / `socket.connect` refuse a path that does not fit `sun_path` with `OSError('AF_UNIX path too long')`. The file system has no such limit, but deep temporary directories hit it quickly (macOS's `$TMPDIR` alone is about 50 bytes, and test harnesses and sandboxes nest further). The limit applies to the argument passed to `bind(2)` / `connect(2)`, so sockat hands the kernel a short spelling that names the same place.
39
+
40
+ ## How a long path is reached
41
+
42
+ A path that the standard library accepts (up to `sun_path` − 1 bytes) is handed to it unchanged.
43
+
44
+ | OS | Handed to the standard library |
45
+ |---|---|
46
+ | Linux / Android / illumos | up to 107 bytes |
47
+ | macOS / iOS / FreeBSD / NetBSD / OpenBSD | up to 103 bytes |
48
+
49
+ A longer path is tried on the routes below, in this order per OS, and bound / connected on the first route that can be used.
50
+
51
+ | OS | Order tried |
52
+ |---|---|
53
+ | Linux / Android (`/proc` usable) | /proc |
54
+ | Linux / Android (`/proc` not usable) | relative path → symlink → thread cwd |
55
+ | FreeBSD | bindat |
56
+ | macOS / iOS | relative path → widened sockaddr → symlink → thread cwd |
57
+ | NetBSD / OpenBSD / illumos / other Unix | relative path → symlink |
58
+ | Windows | not supported (`ImportError` on import) |
59
+
60
+ | Route | How |
61
+ |---|---|
62
+ | /proc | open the directory and pass `/proc/self/fd/<fd>/<file name>` |
63
+ | bindat | `bindat(2)` / `connectat(2)`, by the file name relative to the directory fd |
64
+ | relative path | pass the path relative to the cwd. Only the string is rewritten; the cwd is never changed |
65
+ | widened sockaddr | pass a sockaddr carrying up to 253 bytes, which the macOS kernel accepts |
66
+ | symlink | create a short symlink under `TMPDIR` or `/tmp`, go through it, and remove it at once. It is created only in a place where no other user can replace it |
67
+ | thread cwd | move the cwd of a throwaway thread alone into the directory and pass the file name. The process's cwd is never changed |
68
+ | fork | **none** (the specification's fork route is not built. Neither are the specification's `connect_any` variants) |
69
+
70
+ - None of the routes changes the calling process's cwd, so they can be used from multi-threaded programs
71
+ - A path that fits no route gets `ENAMETOOLONG` (an `OSError` with errno), as a path too long for the standard library does
72
+ - On macOS / Linux, where the thread cwd route can be used, a path is reached at any depth as long as the file name is within 253 bytes (107 on Linux). Linux cannot use the thread cwd route under a seccomp filter (docker's default, for example)
73
+ - The length limits of each route, and where a path stops being reached, are in [docs/MANUAL.md](./docs/MANUAL.md#how-a-long-path-is-reached)
74
+
75
+ ## What differs from the standard library for a long path
76
+
77
+ - `getsockname()` / `getpeername()` do not return the original path: they return the spelling handed to the kernel at bind time (a relative path, `/proc/self/fd/...`, a path through a symlink that no longer exists, the file name alone, ...). Keep the original path yourself
78
+ - A path too long for the standard library that does not end with a name (ending in `dir/`, `dir/.`, `..`) is a `ValueError`
79
+ - A path containing a NUL anywhere but at its start is a `ValueError` at any length (the standard library silently truncates at the NUL). On Linux a path starting with a NUL (abstract namespace) is handed to the standard library unchanged
80
+ - The rest (the directory being looked up first, a symlink that may be left behind) is in [docs/MANUAL.md](./docs/MANUAL.md#what-differs-from-the-standard-library-for-a-long-path)
81
+
82
+ ## asyncio
83
+
84
+ ```python
85
+ listener = sockat.bind(path)
86
+ server = await asyncio.start_unix_server(handle, sock=listener)
87
+
88
+ reader, writer = await asyncio.open_unix_connection(sock=sockat.connect_nonblocking(path))
89
+ ```
90
+
91
+ ## Documentation
92
+
93
+ - [docs/MANUAL.md](./docs/MANUAL.md) — usage, the routes in detail, what differs from the standard library, errors
94
+ - [docs/decisions/](./docs/decisions/INDEX.md) — design decisions (DRs, in Japanese)
95
+
96
+ ## License
97
+
98
+ MIT License, Yoshiaki Kawazu (@kawaz)
@@ -0,0 +1,80 @@
1
+ [project]
2
+ name = "sockat"
3
+ version = "0.1.1"
4
+ description = "Bind / connect Unix domain sockets at paths longer than sun_path"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.11"
9
+ dependencies = []
10
+ keywords = [
11
+ "unix",
12
+ "socket",
13
+ "sun_path",
14
+ "AF_UNIX",
15
+ "ENAMETOOLONG",
16
+ ]
17
+ classifiers = [
18
+ "Development Status :: 4 - Beta",
19
+ "Intended Audience :: Developers",
20
+ "Operating System :: POSIX",
21
+ "Operating System :: POSIX :: Linux",
22
+ "Operating System :: POSIX :: BSD",
23
+ "Operating System :: MacOS",
24
+ "Programming Language :: Python :: 3",
25
+ "Programming Language :: Python :: 3 :: Only",
26
+ "Topic :: System :: Networking",
27
+ "Typing :: Typed",
28
+ ]
29
+
30
+ [[project.authors]]
31
+ name = "Yoshiaki Kawazu"
32
+
33
+ [project.urls]
34
+ Homepage = "https://github.com/kawaz/sockat-py"
35
+ Repository = "https://github.com/kawaz/sockat-py"
36
+ Specification = "https://github.com/kawaz/sockat/blob/main/docs/SPEC.md"
37
+
38
+ [build-system]
39
+ requires = ["uv_build>=0.13,<0.14"]
40
+ build-backend = "uv_build"
41
+
42
+ [dependency-groups]
43
+ dev = [
44
+ "pytest>=9",
45
+ "mypy>=2",
46
+ "ruff>=0.17",
47
+ ]
48
+
49
+ [tool.ruff]
50
+ line-length = 120
51
+ target-version = "py311"
52
+
53
+ [tool.ruff.lint]
54
+ select = [
55
+ "E",
56
+ "F",
57
+ "W",
58
+ "I",
59
+ "B",
60
+ "UP",
61
+ "SIM",
62
+ "RUF",
63
+ "PT",
64
+ "ANN",
65
+ ]
66
+
67
+ [tool.mypy]
68
+ strict = true
69
+ python_version = "3.11"
70
+ files = [
71
+ "src",
72
+ "tests",
73
+ ]
74
+
75
+ [tool.pytest.ini_options]
76
+ testpaths = ["tests"]
77
+ addopts = [
78
+ "-ra",
79
+ "--strict-markers",
80
+ ]
@@ -0,0 +1,51 @@
1
+ [project]
2
+ name = "sockat"
3
+ version = "0.1.1"
4
+ description = "Bind / connect Unix domain sockets at paths longer than sun_path"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "Yoshiaki Kawazu" }]
9
+ requires-python = ">=3.11"
10
+ dependencies = []
11
+ keywords = ["unix", "socket", "sun_path", "AF_UNIX", "ENAMETOOLONG"]
12
+ classifiers = [
13
+ "Development Status :: 4 - Beta",
14
+ "Intended Audience :: Developers",
15
+ "Operating System :: POSIX",
16
+ "Operating System :: POSIX :: Linux",
17
+ "Operating System :: POSIX :: BSD",
18
+ "Operating System :: MacOS",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Topic :: System :: Networking",
22
+ "Typing :: Typed",
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/kawaz/sockat-py"
27
+ Repository = "https://github.com/kawaz/sockat-py"
28
+ Specification = "https://github.com/kawaz/sockat/blob/main/docs/SPEC.md"
29
+
30
+ [build-system]
31
+ requires = ["uv_build>=0.13,<0.14"]
32
+ build-backend = "uv_build"
33
+
34
+ [dependency-groups]
35
+ dev = ["pytest>=9", "mypy>=2", "ruff>=0.17"]
36
+
37
+ [tool.ruff]
38
+ line-length = 120
39
+ target-version = "py311"
40
+
41
+ [tool.ruff.lint]
42
+ select = ["E", "F", "W", "I", "B", "UP", "SIM", "RUF", "PT", "ANN"]
43
+
44
+ [tool.mypy]
45
+ strict = true
46
+ python_version = "3.11"
47
+ files = ["src", "tests"]
48
+
49
+ [tool.pytest.ini_options]
50
+ testpaths = ["tests"]
51
+ addopts = ["-ra", "--strict-markers"]
@@ -0,0 +1,70 @@
1
+ """Bind / connect Unix domain sockets at paths longer than ``sun_path``.
2
+
3
+ Use :func:`bind` / :func:`connect` where you would create an ``AF_UNIX``
4
+ socket and call ``bind`` + ``listen`` / ``connect`` on it::
5
+
6
+ import sockat
7
+
8
+ listener = sockat.bind("/a/very/deep/directory/.../server.sock")
9
+ client = sockat.connect("/a/very/deep/directory/.../server.sock")
10
+
11
+ * The return value is a plain :class:`socket.socket`.
12
+ * A path the :mod:`socket` module accepts (``sun_path`` less 1 byte: 107 on
13
+ Linux, 103 on macOS and the BSDs) goes to it unchanged, so it behaves as the
14
+ standard library does.
15
+ * A longer path is reached by the routes of the sockat SPEC
16
+ (https://github.com/kawaz/sockat/blob/main/docs/SPEC.md), and the socket
17
+ file is created at the given path.
18
+
19
+ Errors are :class:`OSError` with the ``errno`` of the system call (so its
20
+ subclasses such as :class:`FileNotFoundError`), :class:`ValueError` for a
21
+ long path that does not end with a file name or contains a NUL byte, and an
22
+ :class:`OSError` without ``errno`` when the cwd changed during a bind /
23
+ connect through a path relative to it.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import socket
29
+ import sys
30
+
31
+ if sys.platform == "win32": # pragma: no cover
32
+ raise ImportError("sockat supports Unix systems only")
33
+
34
+ from ._route import BIND, CONNECT, CONNECT_NONBLOCKING, StrOrBytesPath, run
35
+
36
+ __all__ = ["bind", "connect", "connect_nonblocking"]
37
+
38
+
39
+ def bind(path: StrOrBytesPath) -> socket.socket:
40
+ """Create an ``AF_UNIX`` stream socket, bind it to ``path`` and listen
41
+ with the :mod:`socket` module's default backlog.
42
+
43
+ The same as ``socket.socket(AF_UNIX, SOCK_STREAM)`` followed by
44
+ ``bind(path)`` and ``listen()``, for any length of ``path``. The socket
45
+ file is not removed when the socket is closed (as with the standard
46
+ library); remove it with ``os.unlink(path)``.
47
+ """
48
+ return run(BIND, path)[0]
49
+
50
+
51
+ def connect(path: StrOrBytesPath) -> socket.socket:
52
+ """Create an ``AF_UNIX`` stream socket and connect it to ``path``
53
+ (blocking).
54
+
55
+ The same as ``socket.socket(AF_UNIX, SOCK_STREAM)`` followed by
56
+ ``connect(path)``, for any length of ``path``.
57
+ """
58
+ return run(CONNECT, path)[0]
59
+
60
+
61
+ def connect_nonblocking(path: StrOrBytesPath) -> socket.socket:
62
+ """Like :func:`connect`, but the socket is made nonblocking before the
63
+ connect and returned so, ready for an event loop (for example
64
+ ``asyncio.open_unix_connection(sock=...)``).
65
+
66
+ A Unix-domain connect completes or fails within the call, so nothing is
67
+ left to wait for. When the listener's backlog is full it fails at once
68
+ (Linux: :class:`BlockingIOError`, macOS: :class:`ConnectionRefusedError`).
69
+ """
70
+ return run(CONNECT_NONBLOCKING, path)[0]
@@ -0,0 +1,95 @@
1
+ """Pure path arithmetic on the bytes of a socket path: splitting it into its
2
+ directory and file name, and spelling an absolute path relative to a working
3
+ directory. Nothing here touches the file system."""
4
+
5
+ from __future__ import annotations
6
+
7
+
8
+ def split(path: bytes) -> tuple[bytes, bytes]:
9
+ """Split a socket path into the directory that holds the socket and the
10
+ socket's file name, by the bytes after the last ``/``.
11
+
12
+ The split is done on the bytes rather than through a normalising path
13
+ library, which would drop a trailing ``/`` and ``.``: ``a/b/`` and
14
+ ``a/b/.`` would both come out as file name ``b``, while the kernel would
15
+ resolve them as the directory ``a/b`` itself. Such paths do not name a
16
+ socket file, so they are refused rather than silently retargeted.
17
+
18
+ ============== =========== =========
19
+ path directory file name
20
+ ============== =========== =========
21
+ ``/d/e/s.sock`` ``/d/e`` ``s.sock``
22
+ ``/s.sock`` ``/`` ``s.sock``
23
+ ``s.sock`` ``.`` ``s.sock``
24
+ ``d//s.sock`` ``d/`` ``s.sock``
25
+ ``d/``, ``d/.``, ``d/..``, ``..`` (ValueError)
26
+ ============== =========== =========
27
+
28
+ Raises:
29
+ ValueError: the last segment is empty, ``.`` or ``..``.
30
+ """
31
+ i = path.rfind(b"/")
32
+ if i == 0:
33
+ directory, name = b"/", path[1:]
34
+ elif i > 0:
35
+ directory, name = path[:i], path[i + 1 :]
36
+ else:
37
+ directory, name = b".", path
38
+ if name in (b"", b".", b".."):
39
+ raise ValueError("socket path must end with a file name (not '/', '.' or '..')")
40
+ return directory, name
41
+
42
+
43
+ def components(path: bytes) -> list[bytes]:
44
+ """The components of an absolute path after the root, as the kernel walks
45
+ them: empty segments (doubled slashes) and ``.`` are dropped, ``..`` is
46
+ kept as it is (it is not interpreted)."""
47
+ return [c for c in path.split(b"/") if c not in (b"", b".")]
48
+
49
+
50
+ def below(target: bytes, prefix: bytes) -> bytes | None:
51
+ """The part of ``target`` below the directory ``prefix``, when ``target``
52
+ starts with ``prefix`` component by component (``/a/b`` is a prefix of
53
+ ``/a/b/c`` but not of ``/a/bc``).
54
+
55
+ The result only descends from ``prefix`` along ``target``'s own
56
+ components, so it resolves through the same symlinks ``target`` does.
57
+ ``None`` when either is not absolute or ``prefix`` is not a proper prefix
58
+ (including ``target == prefix``, which leaves no file name).
59
+ """
60
+ if not target.startswith(b"/") or not prefix.startswith(b"/"):
61
+ return None
62
+ t = components(target)
63
+ p = components(prefix)
64
+ if len(t) <= len(p) or t[: len(p)] != p:
65
+ return None
66
+ return b"/".join(t[len(p) :])
67
+
68
+
69
+ def relative(target: bytes, cwd: bytes) -> bytes | None:
70
+ """Spell the absolute path ``target`` relative to the absolute directory
71
+ ``cwd``: climb with ``..`` out of the part of ``cwd`` that ``target`` does
72
+ not share, then descend along the rest of ``target``.
73
+
74
+ This is component arithmetic and is only meaningful when both inputs are
75
+ real paths (no symlinks, ``.`` or ``..``): ``cwd`` as ``getcwd(3)`` reports
76
+ it and ``target`` with its directory passed through ``realpath(3)``. Then
77
+ each ``..`` climbs out of a real directory, which is what the kernel does.
78
+ The caller still confirms that the result names the same directory before
79
+ using it.
80
+
81
+ ``None`` when either path is not absolute, or when ``target`` is ``cwd``
82
+ itself or one of its ancestors (there would be no file name left).
83
+ """
84
+ if not target.startswith(b"/") or not cwd.startswith(b"/"):
85
+ return None
86
+ t = components(target)
87
+ c = components(cwd)
88
+ common = 0
89
+ for a, b in zip(t, c, strict=False):
90
+ if a != b:
91
+ break
92
+ common += 1
93
+ if common >= len(t):
94
+ return None
95
+ return b"/".join([b".."] * (len(c) - common) + t[common:])