MayaFlux 1.0.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
UnixSocket.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "Acquisition.hpp"
4#include "Process.hpp"
5
6#if defined(MAYAFLUX_PLATFORM_WINDOWS)
7#ifndef WIN32_LEAN_AND_MEAN
8#define WIN32_LEAN_AND_MEAN
9#endif
10#ifndef NOMINMAX
11#define NOMINMAX
12#endif
13#include <windows.h>
14#else
15#include <unistd.h>
16#endif
17
18namespace MayaFlux::Platform {
19
20/**
21 * @brief A Unix socket at an explicit file path, absolute or relative to the working directory.
22 */
24 std::filesystem::path path;
25};
26
27/**
28 * @brief A Unix socket given by file name, placed in the user's runtime directory.
29 *
30 * The directory is the first of runtime_directory_candidates() that exists.
31 */
33 std::string file_name;
34};
35
36using UnixSocketSource = std::variant<UnixSocketFromPath, UnixSocketFromName>;
37
38/**
39 * @brief A socket path that is safe to bind.
40 *
41 * replaced_stale is true when a socket file nothing answered on was removed.
42 */
43struct UnixSocket {
44 std::filesystem::path path;
46};
47
48inline constexpr std::string_view default_unix_socket_name = "mayaflux-lila.sock";
49
50#if defined(MAYAFLUX_PLATFORM_MACOS)
51inline constexpr size_t unix_socket_path_limit = 103;
52#else
53inline constexpr size_t unix_socket_path_limit = 107;
54#endif
55
56/**
57 * @brief Per-user directories a Unix socket may live in, in the order tried.
58 *
59 * Read from the environment on every call, so a changed variable is seen at once.
60 * Linux: XDG_RUNTIME_DIR, then /run/user/<uid>. macOS: TMPDIR. Windows: TEMP,
61 * then TMP. Variables that are empty or not absolute are skipped. Nothing here
62 * checks that a directory exists.
63 */
64[[nodiscard]] inline std::vector<std::filesystem::path> runtime_directory_candidates()
65{
66 std::vector<std::filesystem::path> directories;
67
68 const auto add_variable = [&directories](const char* name) {
69 const std::string value = safe_getenv(name);
70 if (value.empty()) {
71 return;
72 }
73 std::filesystem::path directory(value);
74 if (directory.is_absolute()) {
75 directories.push_back(std::move(directory));
76 }
77 };
78
79#if defined(MAYAFLUX_PLATFORM_WINDOWS)
80 add_variable("TEMP");
81 add_variable("TMP");
82#elif defined(MAYAFLUX_PLATFORM_MACOS)
83 add_variable("TMPDIR");
84#else
85 add_variable("XDG_RUNTIME_DIR");
86 directories.emplace_back("/run/user/" + std::to_string(::geteuid()));
87#endif
88
89 return directories;
90}
91
92namespace detail {
93
94 inline bool socket_directory_is_safe(const std::filesystem::path& directory)
95 {
96#if defined(MAYAFLUX_PLATFORM_WINDOWS)
97 (void)directory;
98 return true;
99#else
100 std::error_code ec;
101 const auto status = std::filesystem::status(directory, ec);
102 if (ec) {
103 return false;
104 }
105 const auto permissions = status.permissions();
106 const bool others_write = (permissions & std::filesystem::perms::others_write) != std::filesystem::perms::none;
107 const bool sticky = (permissions & std::filesystem::perms::sticky_bit) != std::filesystem::perms::none;
108 return !others_write || sticky;
109#endif
110 }
111
112 inline bool entry_is_socket(const std::filesystem::file_status& status, const std::filesystem::path& path)
113 {
114#if defined(MAYAFLUX_PLATFORM_WINDOWS)
115 if (status.type() == std::filesystem::file_type::socket) {
116 return true;
117 }
118 constexpr DWORD af_unix_reparse_tag = 0x80000023;
119 WIN32_FIND_DATAW found {};
120 const HANDLE handle = FindFirstFileW(path.c_str(), &found);
121 if (handle == INVALID_HANDLE_VALUE) {
122 return false;
123 }
124 FindClose(handle);
125 return (found.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0
126 && found.dwReserved0 == af_unix_reparse_tag;
127#else
128 (void)path;
129 return status.type() == std::filesystem::file_type::socket;
130#endif
131 }
132
134 {
135 return std::visit(Overloaded {
137 if (has_control_character(from.path.string())) {
138 return std::unexpected(make_failure(AcquireFailure::Reason::InvalidName, from.path.string()));
139 }
140 return resolve_absolute(from.path);
141 },
143 if (auto failure = check_file_name(from.file_name)) {
144 return std::unexpected(*failure);
145 }
146 std::vector<std::filesystem::path> tried;
147 for (const auto& directory : runtime_directory_candidates()) {
148 tried.push_back(directory);
149 if (path_is_directory(directory)) {
150 return directory / from.file_name;
151 }
152 }
153 return std::unexpected(make_failure(AcquireFailure::Reason::Missing, from.file_name, std::move(tried)));
154 } },
155 source);
156 }
157
158}
159
160/**
161 * @brief Whether a path holds a Unix socket file, without following a symbolic link.
162 *
163 * On Windows a socket file is a reparse point, which the standard library does not
164 * report as a socket, so it is recognised here by its reparse tag.
165 */
166[[nodiscard]] inline bool is_unix_socket(const std::filesystem::path& path)
167{
168 std::error_code ec;
169 const auto entry = std::filesystem::symlink_status(path, ec);
170 return !ec && detail::entry_is_socket(entry, path);
171}
172
173/**
174 * @brief The Unix sockets that sit in the user's runtime directories, sorted by path.
175 *
176 * Every directory of runtime_directory_candidates() that can be read is listed,
177 * once each however many candidates name it, and the entries that
178 * is_unix_socket() accepts are returned. Directories that are missing or
179 * unreadable are skipped. Nothing is probed: a socket nothing answers on is listed too.
180 */
181[[nodiscard]] inline std::vector<std::filesystem::path> list_unix_sockets()
182{
183 std::vector<std::filesystem::path> sockets;
184
185 for (const auto& directory : runtime_directory_candidates()) {
186 std::error_code ec;
187 std::filesystem::directory_iterator entry(directory, ec);
188 const std::filesystem::directory_iterator end;
189
190 while (!ec && entry != end) {
191 if (is_unix_socket(entry->path())) {
192 sockets.push_back(entry->path());
193 }
194 entry.increment(ec);
195 }
196 }
197
198 std::ranges::sort(sockets);
199 const auto duplicates = std::ranges::unique(sockets);
200 sockets.erase(duplicates.begin(), duplicates.end());
201 return sockets;
202}
203
204/**
205 * @brief Resolve a Unix socket request to a path, for a client that connects to an existing socket.
206 *
207 * Applies the same name and path resolution as acquire_unix_socket and checks nothing
208 * else: the entry is not inspected, nothing is removed and the length limit is not applied.
209 */
211{
212 return detail::resolve_socket_path(source);
213}
214
215/**
216 * @brief Check that a Unix socket path can be bound, removing a stale socket file.
217 *
218 * Refuses a path that is too long, whose directory is missing or writable by others,
219 * or that holds something other than a socket. A socket file that is_alive says
220 * answers is refused as in use. One that does not is removed. Nothing is created,
221 * and bind can still fail, since another process may take the path first.
222 *
223 * @param source The request.
224 * @param is_alive Called with an existing socket's path, returns true if a server answers on it.
225 * @return The socket path, or the reason it was refused and the paths checked.
226 */
227template <std::predicate<const std::filesystem::path&> Probe>
228[[nodiscard]] Acquired<UnixSocket> acquire_unix_socket(const UnixSocketSource& source, Probe&& is_alive)
229{
230 auto resolved = detail::resolve_socket_path(source);
231 if (!resolved) {
232 return std::unexpected(resolved.error());
233 }
234 const std::filesystem::path path = std::move(*resolved);
235
236 if (path.u8string().size() > unix_socket_path_limit) {
237 return std::unexpected(detail::make_failure(AcquireFailure::Reason::TooLong, path.string(), { path }));
238 }
239
240 const std::filesystem::path directory = path.parent_path();
241 if (!detail::path_exists(directory)) {
242 return std::unexpected(detail::make_failure(AcquireFailure::Reason::Missing, path.string(), { directory }));
243 }
244 if (!detail::path_is_directory(directory)) {
245 return std::unexpected(detail::make_failure(AcquireFailure::Reason::NotDirectory, path.string(), { directory }));
246 }
247 if (!detail::socket_directory_is_safe(directory)) {
248 return std::unexpected(detail::make_failure(AcquireFailure::Reason::Unsafe, path.string(), { directory }));
249 }
250
251 std::error_code ec;
252 const auto entry = std::filesystem::symlink_status(path, ec);
253 if (entry.type() == std::filesystem::file_type::not_found) {
254 return UnixSocket { .path = path, .replaced_stale = false };
255 }
256 if (ec) {
257 return std::unexpected(detail::make_failure(AcquireFailure::Reason::Unsafe, path.string(), { path }));
258 }
259 if (!detail::entry_is_socket(entry, path)) {
260 return std::unexpected(detail::make_failure(AcquireFailure::Reason::NotSocket, path.string(), { path }));
261 }
262
263 if (is_alive(path)) {
264 return std::unexpected(detail::make_failure(AcquireFailure::Reason::InUse, path.string(), { path }));
265 }
266
267 std::filesystem::remove(path, ec);
268 if (ec) {
269 return std::unexpected(detail::make_failure(AcquireFailure::Reason::StaleNotRemoved, path.string(), { path }));
270 }
271 return UnixSocket { .path = path, .replaced_stale = true };
272}
273
274/**
275 * @brief Make a bound socket file usable by its owner only.
276 *
277 * Call after bind. On POSIX the file mode becomes owner read and write, whatever
278 * the umask was. On Windows this does nothing and the file keeps the access its
279 * directory gives it.
280 */
281[[nodiscard]] inline Acquired<void> restrict_unix_socket_to_owner(const std::filesystem::path& path)
282{
283#if defined(MAYAFLUX_PLATFORM_WINDOWS)
284 (void)path;
285 return {};
286#else
287 std::error_code ec;
288 std::filesystem::permissions(path,
289 std::filesystem::perms::owner_read | std::filesystem::perms::owner_write,
290 std::filesystem::perm_options::replace, ec);
291 if (ec) {
292 return std::unexpected(detail::make_failure(AcquireFailure::Reason::Unsafe, path.string(), { path }));
293 }
294 return {};
295#endif
296}
297
298} // namespace MayaFlux::Platform
bool path_exists(const std::filesystem::path &path)
bool path_is_directory(const std::filesystem::path &path)
bool socket_directory_is_safe(const std::filesystem::path &directory)
std::optional< AcquireFailure > check_file_name(std::string_view name)
Acquired< std::filesystem::path > resolve_socket_path(const UnixSocketSource &source)
std::expected< std::filesystem::path, AcquireFailure > resolve_absolute(const std::filesystem::path &path)
AcquireFailure make_failure(AcquireFailure::Reason reason, std::string request, std::vector< std::filesystem::path > tried={})
bool has_control_character(std::string_view name)
bool entry_is_socket(const std::filesystem::file_status &status, const std::filesystem::path &path)
std::expected< T, AcquireFailure > Acquired
std::vector< std::filesystem::path > list_unix_sockets()
The Unix sockets that sit in the user's runtime directories, sorted by path.
std::variant< UnixSocketFromPath, UnixSocketFromName > UnixSocketSource
constexpr size_t unix_socket_path_limit
std::vector< std::filesystem::path > runtime_directory_candidates()
Per-user directories a Unix socket may live in, in the order tried.
Acquired< std::filesystem::path > resolve_unix_socket_path(const UnixSocketSource &source)
Resolve a Unix socket request to a path, for a client that connects to an existing socket.
std::string safe_getenv(const char *var)
Definition Process.hpp:11
constexpr std::string_view default_unix_socket_name
Acquired< UnixSocket > acquire_unix_socket(const UnixSocketSource &source, Probe &&is_alive)
Check that a Unix socket path can be bound, removing a stale socket file.
Acquired< void > restrict_unix_socket_to_owner(const std::filesystem::path &path)
Make a bound socket file usable by its owner only.
bool is_unix_socket(const std::filesystem::path &path)
Whether a path holds a Unix socket file, without following a symbolic link.
A Unix socket given by file name, placed in the user's runtime directory.
A Unix socket at an explicit file path, absolute or relative to the working directory.
std::filesystem::path path
A socket path that is safe to bind.