Blender V5.3
GHOST_SystemDBusUnix.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2026 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#ifdef WITH_GHOST_DBUS
10
12
13# include "GHOST_Debug.hh"
14# include "GHOST_utildefines.hh"
15
16# ifdef WITH_GHOST_DBUS_DYNLOAD
17# include "dbus_dynload.h"
18# include "dbus_dynload_API.h"
19# else
20# include <dbus/dbus.h>
21# endif
22
23# include <array>
24# include <cerrno>
25# include <chrono>
26# include <condition_variable>
27# include <cstdlib>
28# include <cstring>
29# include <mutex>
30# include <utility>
31# include <vector>
32
33# include <fcntl.h>
34# include <poll.h>
35# include <sys/stat.h>
36# include <unistd.h>
37
38# include "CLG_log.h"
39
40static CLG_LogRef LOG = {"ghost.dbus"};
41
42static constexpr const char *PORTAL_SERVICE = "org.freedesktop.portal.Desktop";
43static constexpr const char *PORTAL_PATH = "/org/freedesktop/portal/desktop";
44static constexpr const char *PORTAL_SETTINGS_IFACE = "org.freedesktop.portal.Settings";
45static constexpr const char *PORTAL_SETTINGS_CHANGED = "SettingChanged";
46
52static constexpr int SETTING_READ_TIMEOUT_MS = 5000;
53
59class StopPipe {
60 int fds_[2] = {-1, -1};
61
62 public:
63 StopPipe() = default;
64 ~StopPipe()
65 {
66 this->close_write();
67 if (fds_[0] != -1) {
68 close(fds_[0]);
69 fds_[0] = -1;
70 }
71 }
72
73 StopPipe(const StopPipe &) = delete;
74 StopPipe &operator=(const StopPipe &) = delete;
75
76 bool open()
77 {
78 if (pipe2(fds_, O_CLOEXEC) != 0) {
79 fds_[0] = fds_[1] = -1;
80 return false;
81 }
82 return true;
83 }
84
86 int read_fd() const
87 {
88 return fds_[0];
89 }
90
92 void close_write()
93 {
94 if (fds_[1] != -1) {
95 close(fds_[1]);
96 fds_[1] = -1;
97 }
98 }
99};
100
101struct GHOST_SystemDBusUnix::Data {
102 struct Setting {
103 std::string name_space;
104 std::string key;
105 SettingChangedFn on_change;
106 };
107
109 std::vector<Setting> settings;
110
115 std::mutex mutex;
117 std::condition_variable initial_cond;
118 bool stop = false;
124 bool initial_done = false;
125
133 StopPipe stop_pipe;
134
139 std::vector<std::pair<size_t, GHOST_DBusValue>> pending;
140};
141
142using WatcherData = GHOST_SystemDBusUnix::Data;
143
144static bool value_from_iter(DBusMessageIter *iter, GHOST_DBusValue &r_value)
145{
146 switch (dbus_message_iter_get_arg_type(iter)) {
147 case DBUS_TYPE_BOOLEAN: {
148 dbus_bool_t value = FALSE;
149 dbus_message_iter_get_basic(iter, &value);
150 r_value = bool(value);
151 return true;
152 }
153 case DBUS_TYPE_INT32: {
154 dbus_int32_t value = 0;
155 dbus_message_iter_get_basic(iter, &value);
156 r_value = int32_t(value);
157 return true;
158 }
159 case DBUS_TYPE_UINT32: {
160 dbus_uint32_t value = 0;
161 dbus_message_iter_get_basic(iter, &value);
162 r_value = uint32_t(value);
163 return true;
164 }
165 case DBUS_TYPE_DOUBLE: {
166 double value = 0.0;
167 dbus_message_iter_get_basic(iter, &value);
168 r_value = value;
169 return true;
170 }
171 case DBUS_TYPE_STRING: {
172 const char *value = nullptr;
173 dbus_message_iter_get_basic(iter, &value);
174 r_value = std::string(value ? value : "");
175 return true;
176 }
177 }
178 return false;
179}
180
184static bool value_from_variant(DBusMessageIter *iter, GHOST_DBusValue &r_value)
185{
186 if (dbus_message_iter_get_arg_type(iter) == DBUS_TYPE_VARIANT) {
187 DBusMessageIter iter_inner;
188 dbus_message_iter_recurse(iter, &iter_inner);
189 return value_from_variant(&iter_inner, r_value);
190 }
191 return value_from_iter(iter, r_value);
192}
193
201static bool session_bus_is_available()
202{
203 const char *session_bus_address = getenv("DBUS_SESSION_BUS_ADDRESS");
204 if (session_bus_address && session_bus_address[0] != '\0') {
205 /* A common convention for disabling the session bus,
206 * support it to avoid a redundant connection attempt. */
207 if (STREQ(session_bus_address, "/dev/null")) {
208 return false;
209 }
210 return true;
211 }
212 /* `libdbus` checks this well known location before resorting to auto-launch. */
213 const char *runtime_dir = getenv("XDG_RUNTIME_DIR");
214 if (!runtime_dir || runtime_dir[0] == '\0') {
215 return false;
216 }
217 const std::string path = std::string(runtime_dir) + "/bus";
218 struct stat statbuf;
219 return (stat(path.c_str(), &statbuf) == 0) && S_ISSOCK(statbuf.st_mode);
220}
221
229static bool setting_read(DBusConnection *connection,
230 const WatcherData::Setting &setting,
231 GHOST_DBusValue &r_value)
232{
233 DBusMessage *message = dbus_message_new_method_call(
234 PORTAL_SERVICE, PORTAL_PATH, PORTAL_SETTINGS_IFACE, "Read");
235 if (!message) {
236 return false;
237 }
238
239 const char *name_space = setting.name_space.c_str();
240 const char *key = setting.key.c_str();
242 message, DBUS_TYPE_STRING, &name_space, DBUS_TYPE_STRING, &key, DBUS_TYPE_INVALID))
243 {
244 dbus_message_unref(message);
245 return false;
246 }
247
248 DBusError error;
249 dbus_error_init(&error);
251 connection, message, SETTING_READ_TIMEOUT_MS, &error);
252 dbus_message_unref(message);
253
254 if (dbus_error_is_set(&error)) {
255 CLOG_INFO(&LOG, "unable to read %s/%s: %s", name_space, key, error.message);
256 dbus_error_free(&error);
257 }
258 if (!reply) {
259 return false;
260 }
261
262 DBusMessageIter iter;
263 const bool ok = dbus_message_iter_init(reply, &iter) && value_from_variant(&iter, r_value);
264 if (!ok) {
265 CLOG_WARN(&LOG, "unexpected value type reading %s/%s", name_space, key);
266 }
267 dbus_message_unref(reply);
268 return ok;
269}
270
274static DBusHandlerResult filter_func(DBusConnection * /*connection*/,
275 DBusMessage *message,
276 void *user_data)
277{
278 WatcherData *data = static_cast<WatcherData *>(user_data);
279
280 if (!dbus_message_is_signal(message, PORTAL_SETTINGS_IFACE, PORTAL_SETTINGS_CHANGED)) {
281 return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
282 }
283
284 /* Signal arguments are `(s name_space, s key, v value)`. */
285 DBusMessageIter iter;
286 const char *name_space = nullptr;
287 const char *key = nullptr;
288 if (!dbus_message_iter_init(message, &iter) ||
289 dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
290 {
291 return DBUS_HANDLER_RESULT_HANDLED;
292 }
293 dbus_message_iter_get_basic(&iter, &name_space);
294 if (!dbus_message_iter_next(&iter) || dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
295 {
296 return DBUS_HANDLER_RESULT_HANDLED;
297 }
298 dbus_message_iter_get_basic(&iter, &key);
299 if (!dbus_message_iter_next(&iter)) {
300 return DBUS_HANDLER_RESULT_HANDLED;
301 }
302
303 for (size_t i = 0; i < data->settings.size(); i++) {
304 const WatcherData::Setting &setting = data->settings[i];
305 if ((setting.name_space != name_space) || (setting.key != key)) {
306 continue;
307 }
308 GHOST_DBusValue value;
309 if (value_from_variant(&iter, value)) {
310 data->pending.emplace_back(i, std::move(value));
311 }
312 else {
313 CLOG_WARN(&LOG, "unexpected value type in change signal for %s/%s", name_space, key);
314 }
315 break;
316 }
317
318 return DBUS_HANDLER_RESULT_HANDLED;
319}
320
327static void settings_changed_flush(WatcherData *data)
328{
329 if (data->pending.empty()) {
330 return;
331 }
332 {
333 std::lock_guard lock{data->mutex};
334 /* Skipped once the destructor has run: `on_change` may reference the watcher's owner. */
335 if (!data->stop) {
336 for (const std::pair<size_t, GHOST_DBusValue> &item : data->pending) {
337 data->settings[item.first].on_change(item.second);
338 }
339 }
340 }
341 data->pending.clear();
342}
343
345static DBusConnection *bus_connect()
346{
347 DBusError error;
348 dbus_error_init(&error);
349 /* A private connection: the shared one from `dbus_bus_get` is used by other libraries in the
350 * process, dispatching it here would steal their messages. */
351 DBusConnection *connection = dbus_bus_get_private(DBUS_BUS_SESSION, &error);
352 if (dbus_error_is_set(&error)) {
353 CLOG_WARN(&LOG, "unable to connect to the session bus: %s", error.message);
354 dbus_error_free(&error);
355 }
356 if (!connection) {
357 return nullptr;
358 }
360 return connection;
361}
362
363static bool settings_subscribe(WatcherData *data, DBusConnection *connection)
364{
365 for (const WatcherData::Setting &setting : data->settings) {
366 const std::string match_rule = std::string("type='signal',interface='") +
367 PORTAL_SETTINGS_IFACE + "',member='" + PORTAL_SETTINGS_CHANGED +
368 "',arg0='" + setting.name_space + "',arg1='" + setting.key +
369 "'";
370 DBusError error;
371 dbus_error_init(&error);
372 dbus_bus_add_match(connection, match_rule.c_str(), &error);
373 if (dbus_error_is_set(&error)) {
374 CLOG_WARN(&LOG,
375 "unable to subscribe to %s/%s: %s",
376 setting.name_space.c_str(),
377 setting.key.c_str(),
378 error.message);
379 dbus_error_free(&error);
380 return false;
381 }
382 CLOG_DEBUG(&LOG, "subscribed to %s/%s", setting.name_space.c_str(), setting.key.c_str());
383 }
384
385 if (!dbus_connection_add_filter(connection, filter_func, data, nullptr)) {
386 CLOG_WARN(&LOG, "unable to add the signal filter");
387 return false;
388 }
389 dbus_connection_flush(connection);
390 return true;
391}
392
394static void initial_done_set(WatcherData *data)
395{
396 {
397 std::lock_guard lock{data->mutex};
398 if (data->initial_done) {
399 return;
400 }
401 data->initial_done = true;
402 }
403 data->initial_cond.notify_all();
404}
405
406static bool thread_should_stop(WatcherData *data)
407{
408 std::lock_guard lock{data->mutex};
409 return data->stop;
410}
411
419static void thread_dispatch_loop(WatcherData *data, DBusConnection *connection)
420{
421 int connection_fd = -1;
422 if (!dbus_connection_get_unix_fd(connection, &connection_fd)) {
423 return;
424 }
425
426 for (;;) {
427 /* Process everything already queued. A single read can yield several messages, and the
428 * extra ones don't make the socket readable again, so they have to be drained before
429 * blocking or they would remain unprocessed until the next change arrived. */
430 do {
431 if (!dbus_connection_read_write_dispatch(connection, 0)) {
432 return;
433 }
434 settings_changed_flush(data);
435 } while (dbus_connection_get_dispatch_status(connection) == DBUS_DISPATCH_DATA_REMAINS);
436
437 if (thread_should_stop(data)) {
438 return;
439 }
440
441 /* Wait for something to do. This call makes watching cheap; the thread spends virtually its
442 * whole life waiting here.
443 *
444 * Two descriptors are watched, with either ending the wait:
445 * 1. The bus, once a signal has arrived for the drain above to dispatch.
446 * 2. #Data::stop_pipe. The destructor closing this shows as #POLLHUP.
447 *
448 * The -1 timeout blocks indefinitely. */
449 std::array<pollfd, 2> fds = {{
450 {connection_fd, POLLIN | POLLPRI, 0},
451 {data->stop_pipe.read_fd(), POLLIN, 0},
452 }};
453 if (poll(fds.data(), fds.size(), -1) == -1) {
454 /* Interrupted by a signal before anything was ready, simply wait again. */
455 if (errno == EINTR) {
456 continue;
457 }
458 return;
459 }
460 if (fds[1].revents != 0) {
461 /* The destructor asked this thread to stop. */
462 return;
463 }
464 if (fds[0].revents & (POLLHUP | POLLERR | POLLNVAL)) {
465 /* The bus is no longer available. */
466 return;
467 }
468 }
469}
470
475static void thread_watch(WatcherData *data, DBusConnection *connection)
476{
477 /* Subscribe before reading, otherwise a change made in between would be missed. */
478 if (!settings_subscribe(data, connection)) {
479 return;
480 }
481
482 for (size_t i = 0; i < data->settings.size(); i++) {
483 if (thread_should_stop(data)) {
484 return;
485 }
486 GHOST_DBusValue value;
487 if (setting_read(connection, data->settings[i], value)) {
488 data->pending.emplace_back(i, std::move(value));
489 }
490 }
491 settings_changed_flush(data);
492 initial_done_set(data);
493
494 thread_dispatch_loop(data, connection);
495}
496
497static void thread_run(std::shared_ptr<GHOST_SystemDBusUnix::Data> data_ptr)
498{
499 WatcherData *data = data_ptr.get();
500
501 DBusConnection *connection = bus_connect();
502 if (!connection) {
503 initial_done_set(data);
504 return;
505 }
506
507 thread_watch(data, connection);
508
509 /* A private connection must be closed before its last reference is dropped. */
510 dbus_connection_close(connection);
511 dbus_connection_unref(connection);
512
513 initial_done_set(data);
514}
515
516GHOST_SystemDBusUnix::GHOST_SystemDBusUnix() : data_(std::make_shared<Data>()) {}
517
518GHOST_SystemDBusUnix::~GHOST_SystemDBusUnix()
519{
520 if (!thread_.joinable()) {
521 return;
522 }
523
524 {
525 std::lock_guard lock{data_->mutex};
526 data_->stop = true;
527 /* Wakes the thread's #poll, see #Data::stop_pipe. */
528 data_->stop_pipe.close_write();
529 }
530
531 /* The connection is deliberately left for the thread to close. Doing it from here could end the
532 * initial #setting_read sooner, but tearing a connection down from a thread other than the one
533 * dispatching it is reported by ThreadSanitizer as a potential deadlock. Since this doesn't
534 * wait for the thread anyway, there is nothing to gain from it. */
535
536 /* Detached rather than joined: the thread stops on its own moments after the wake above, but
537 * neither `dbus_bus_get_private` nor a blocking #setting_read can be interrupted from here,
538 * so a dbus session that goes quiet mid-exchange would hold up Blender's exit for as long as
539 * `libdbus` waits on it, which is unnecessary: `data_` is shared with the thread and outlives
540 * this object, and `stop` (checked under `mutex` before every callback) keeps it from reaching
541 * into memory owned by this object. */
542 thread_.detach();
543}
544
545bool GHOST_SystemDBusUnix::wait_initial(const int timeout_ms)
546{
547 if (!thread_.joinable()) {
548 return false;
549 }
550 std::unique_lock lock{data_->mutex};
551 return data_->initial_cond.wait_for(
552 lock, std::chrono::milliseconds(timeout_ms), [this] { return data_->initial_done; });
553}
554
555void GHOST_SystemDBusUnix::setting_add(const char *name_space,
556 const char *key,
557 SettingChangedFn on_change)
558{
559 GHOST_ASSERT(!thread_.joinable(), "Settings must be added before starting the watcher");
560 Data::Setting &setting = data_->settings.emplace_back();
561 setting.name_space = name_space;
562 setting.key = key;
563 setting.on_change = std::move(on_change);
564}
565
566bool GHOST_SystemDBusUnix::start()
567{
568 if (data_->settings.empty()) {
569 return false;
570 }
571
572 if (!session_bus_is_available()) {
573 return false;
574 }
575
576# ifdef WITH_GHOST_DBUS_DYNLOAD
577 if (!dbus_dynload_init(false)) {
578 return false;
579 }
580# endif
581
582 /* Created here rather than on the thread so the destructor can always rely on it, even if it
583 * runs before the thread starts. */
584 if (!data_->stop_pipe.open()) {
585 return false;
586 }
587
588 thread_ = std::thread(thread_run, data_);
589 return true;
590}
591
592#endif /* WITH_GHOST_DBUS */
#define CLOG_DEBUG(clg_ref,...)
Definition CLG_log.h:191
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
#define CLOG_INFO(clg_ref,...)
Definition CLG_log.h:190
#define GHOST_ASSERT(x, info)
volatile int lock
#define STREQ(a, b)
btGeneric6DofConstraint & operator=(btGeneric6DofConstraint &other)
#define dbus_message_iter_get_arg_type(...)
#define dbus_connection_get_unix_fd(...)
#define dbus_error_free(...)
#define dbus_connection_get_dispatch_status(...)
#define dbus_message_new_method_call(...)
#define dbus_connection_close(...)
#define dbus_message_unref(...)
#define dbus_error_init(...)
#define dbus_connection_add_filter(...)
#define dbus_message_iter_get_basic(...)
#define dbus_bus_add_match(...)
#define dbus_message_iter_recurse(...)
#define dbus_connection_read_write_dispatch(...)
#define dbus_message_is_signal(...)
#define dbus_connection_set_exit_on_disconnect(...)
#define dbus_connection_send_with_reply_and_block(...)
#define dbus_bus_get_private(...)
#define dbus_connection_flush(...)
#define dbus_error_is_set(...)
#define dbus_connection_unref(...)
#define dbus_message_iter_next(...)
#define dbus_message_iter_init(...)
#define dbus_message_append_args(...)
bool dbus_dynload_init(bool verbose)
#define LOG(level)
Definition log.h:97
unsigned int uint32_t
Definition BKE_text.h:81
BMesh const char void * data