1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 * Author: David Zeuthen <davidz@redhat.com>
29 #include "gdbusutils.h"
30 #include "gdbusaddress.h"
31 #include "gdbuserror.h"
32 #include "gioenumtypes.h"
33 #include "gnetworkaddress.h"
34 #include "gsocketclient.h"
35 #include "giostream.h"
36 #include "gasyncresult.h"
38 #include "glib-private.h"
39 #include "gdbusprivate.h"
46 #include <sys/types.h>
47 #include <gio/gunixsocketaddress.h>
57 * SECTION:gdbusaddress
58 * @title: D-Bus Addresses
59 * @short_description: D-Bus connection endpoints
62 * Routines for working with D-Bus addresses. A D-Bus address is a string
63 * like `unix:tmpdir=/tmp/my-app-name`. The exact format of addresses
64 * is explained in detail in the
65 * [D-Bus specification](http://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
67 * TCP D-Bus connections are supported, but accessing them via a proxy is
68 * currently not supported.
71 static gchar *get_session_address_platform_specific (GError **error);
72 static gchar *get_session_address_dbus_launch (GError **error);
74 /* ---------------------------------------------------------------------------------------------------- */
80 * Checks if @string is a
81 * [D-Bus address](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
83 * This doesn't check if @string is actually supported by #GDBusServer
84 * or #GDBusConnection - use g_dbus_is_supported_address() to do more
87 * Returns: %TRUE if @string is a valid D-Bus address, %FALSE otherwise.
92 g_dbus_is_address (const gchar *string)
100 g_return_val_if_fail (string != NULL, FALSE);
102 a = g_strsplit (string, ";", 0);
106 for (n = 0; a[n] != NULL; n++)
108 if (!_g_dbus_address_parse_entry (a[n],
123 is_valid_unix (const gchar *address_entry,
124 GHashTable *key_value_pairs,
133 const gchar *abstract;
142 keys = g_hash_table_get_keys (key_value_pairs);
143 for (l = keys; l != NULL; l = l->next)
145 const gchar *key = l->data;
146 if (g_strcmp0 (key, "path") == 0)
147 path = g_hash_table_lookup (key_value_pairs, key);
148 else if (g_strcmp0 (key, "dir") == 0)
149 dir = g_hash_table_lookup (key_value_pairs, key);
150 else if (g_strcmp0 (key, "tmpdir") == 0)
151 tmpdir = g_hash_table_lookup (key_value_pairs, key);
152 else if (g_strcmp0 (key, "abstract") == 0)
153 abstract = g_hash_table_lookup (key_value_pairs, key);
154 else if (g_strcmp0 (key, "guid") != 0)
158 G_IO_ERROR_INVALID_ARGUMENT,
159 _("Unsupported key “%s” in address entry “%s”"),
166 /* Exactly one key must be set */
167 if ((path != NULL) + (dir != NULL) + (tmpdir != NULL) + (abstract != NULL) > 1)
171 G_IO_ERROR_INVALID_ARGUMENT,
172 _("Meaningless key/value pair combination in address entry “%s”"),
176 else if (path == NULL && dir == NULL && tmpdir == NULL && abstract == NULL)
180 G_IO_ERROR_INVALID_ARGUMENT,
181 _("Address “%s” is invalid (need exactly one of path, dir, tmpdir, or abstract keys)"),
195 is_valid_nonce_tcp (const gchar *address_entry,
196 GHashTable *key_value_pairs,
205 const gchar *nonce_file;
216 keys = g_hash_table_get_keys (key_value_pairs);
217 for (l = keys; l != NULL; l = l->next)
219 const gchar *key = l->data;
220 if (g_strcmp0 (key, "host") == 0)
221 host = g_hash_table_lookup (key_value_pairs, key);
222 else if (g_strcmp0 (key, "port") == 0)
223 port = g_hash_table_lookup (key_value_pairs, key);
224 else if (g_strcmp0 (key, "family") == 0)
225 family = g_hash_table_lookup (key_value_pairs, key);
226 else if (g_strcmp0 (key, "noncefile") == 0)
227 nonce_file = g_hash_table_lookup (key_value_pairs, key);
228 else if (g_strcmp0 (key, "guid") != 0)
232 G_IO_ERROR_INVALID_ARGUMENT,
233 _("Unsupported key “%s” in address entry “%s”"),
242 port_num = strtol (port, &endp, 10);
243 if ((*port == '\0' || *endp != '\0') || port_num < 0 || port_num >= 65536)
247 G_IO_ERROR_INVALID_ARGUMENT,
248 _("Error in address “%s” — the port attribute is malformed"),
254 if (family != NULL && !(g_strcmp0 (family, "ipv4") == 0 || g_strcmp0 (family, "ipv6") == 0))
258 G_IO_ERROR_INVALID_ARGUMENT,
259 _("Error in address “%s” — the family attribute is malformed"),
266 /* TODO: validate host */
269 nonce_file = nonce_file; /* To avoid -Wunused-but-set-variable */
280 is_valid_tcp (const gchar *address_entry,
281 GHashTable *key_value_pairs,
299 keys = g_hash_table_get_keys (key_value_pairs);
300 for (l = keys; l != NULL; l = l->next)
302 const gchar *key = l->data;
303 if (g_strcmp0 (key, "host") == 0)
304 host = g_hash_table_lookup (key_value_pairs, key);
305 else if (g_strcmp0 (key, "port") == 0)
306 port = g_hash_table_lookup (key_value_pairs, key);
307 else if (g_strcmp0 (key, "family") == 0)
308 family = g_hash_table_lookup (key_value_pairs, key);
309 else if (g_strcmp0 (key, "guid") != 0)
313 G_IO_ERROR_INVALID_ARGUMENT,
314 _("Unsupported key “%s” in address entry “%s”"),
323 port_num = strtol (port, &endp, 10);
324 if ((*port == '\0' || *endp != '\0') || port_num < 0 || port_num >= 65536)
328 G_IO_ERROR_INVALID_ARGUMENT,
329 _("Error in address “%s” — the port attribute is malformed"),
335 if (family != NULL && !(g_strcmp0 (family, "ipv4") == 0 || g_strcmp0 (family, "ipv6") == 0))
339 G_IO_ERROR_INVALID_ARGUMENT,
340 _("Error in address “%s” — the family attribute is malformed"),
347 /* TODO: validate host */
359 * g_dbus_is_supported_address:
361 * @error: Return location for error or %NULL.
363 * Like g_dbus_is_address() but also checks if the library supports the
364 * transports in @string and that key/value pairs for each transport
365 * are valid. See the specification of the
366 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
368 * Returns: %TRUE if @string is a valid D-Bus address that is
369 * supported by this library, %FALSE if @error is set.
374 g_dbus_is_supported_address (const gchar *string,
383 g_return_val_if_fail (string != NULL, FALSE);
384 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
386 a = g_strsplit (string, ";", 0);
387 for (n = 0; a[n] != NULL; n++)
389 gchar *transport_name;
390 GHashTable *key_value_pairs;
393 if (!_g_dbus_address_parse_entry (a[n],
400 if (g_strcmp0 (transport_name, "unix") == 0)
401 supported = is_valid_unix (a[n], key_value_pairs, error);
402 else if (g_strcmp0 (transport_name, "tcp") == 0)
403 supported = is_valid_tcp (a[n], key_value_pairs, error);
404 else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
405 supported = is_valid_nonce_tcp (a[n], key_value_pairs, error);
406 else if (g_strcmp0 (a[n], "autolaunch:") == 0)
409 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
410 _("Unknown or unsupported transport “%s” for address “%s”"),
411 transport_name, a[n]);
413 g_free (transport_name);
414 g_hash_table_unref (key_value_pairs);
425 g_assert (ret || (!ret && (error == NULL || *error != NULL)));
431 _g_dbus_address_parse_entry (const gchar *address_entry,
432 gchar **out_transport_name,
433 GHashTable **out_key_value_pairs,
437 GHashTable *key_value_pairs;
438 gchar *transport_name;
445 transport_name = NULL;
446 key_value_pairs = NULL;
448 s = strchr (address_entry, ':');
453 G_IO_ERROR_INVALID_ARGUMENT,
454 _("Address element “%s” does not contain a colon (:)"),
458 else if (s == address_entry)
462 G_IO_ERROR_INVALID_ARGUMENT,
463 _("Transport name in address element “%s” must not be empty"),
468 transport_name = g_strndup (address_entry, s - address_entry);
469 key_value_pairs = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
471 kv_pairs = g_strsplit (s + 1, ",", 0);
472 for (n = 0; kv_pairs[n] != NULL; n++)
474 const gchar *kv_pair = kv_pairs[n];
478 s = strchr (kv_pair, '=');
483 G_IO_ERROR_INVALID_ARGUMENT,
484 _("Key/Value pair %d, “%s”, in address element “%s” does not contain an equal sign"),
490 else if (s == kv_pair)
494 G_IO_ERROR_INVALID_ARGUMENT,
495 _("Key/Value pair %d, “%s”, in address element “%s” must not have an empty key"),
502 key = g_uri_unescape_segment (kv_pair, s, NULL);
503 value = g_uri_unescape_segment (s + 1, kv_pair + strlen (kv_pair), NULL);
504 if (key == NULL || value == NULL)
508 G_IO_ERROR_INVALID_ARGUMENT,
509 _("Error unescaping key or value in Key/Value pair %d, “%s”, in address element “%s”"),
517 g_hash_table_insert (key_value_pairs, key, value);
525 if (out_transport_name != NULL)
526 *out_transport_name = g_steal_pointer (&transport_name);
527 if (out_key_value_pairs != NULL)
528 *out_key_value_pairs = g_steal_pointer (&key_value_pairs);
531 g_clear_pointer (&key_value_pairs, g_hash_table_unref);
532 g_free (transport_name);
533 g_strfreev (kv_pairs);
538 /* ---------------------------------------------------------------------------------------------------- */
541 g_dbus_address_try_connect_one (const gchar *address_entry,
544 GCancellable *cancellable,
547 /* TODO: Declare an extension point called GDBusTransport (or similar)
548 * and move code below to extensions implementing said extension
549 * point. That way we can implement a D-Bus transport over X11 without
550 * making libgio link to libX11...
553 g_dbus_address_connect (const gchar *address_entry,
554 const gchar *transport_name,
556 GHashTable *key_value_pairs,
557 GCancellable *cancellable,
561 GSocketConnectable *connectable;
562 const gchar *nonce_file;
573 else if (kdbus_okay && g_str_equal (transport_name, "kernel"))
575 GKDBusWorker *worker;
578 path = g_hash_table_lookup (key_value_pairs, "path");
582 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
583 _("Error in address '%s' - the kernel transport requires a path"),
588 worker = _g_kdbus_worker_new (path, error);
593 return G_OBJECT (worker);
597 else if (g_strcmp0 (transport_name, "unix") == 0)
600 const gchar *abstract;
601 path = g_hash_table_lookup (key_value_pairs, "path");
602 abstract = g_hash_table_lookup (key_value_pairs, "abstract");
603 if ((path == NULL && abstract == NULL) || (path != NULL && abstract != NULL))
607 G_IO_ERROR_INVALID_ARGUMENT,
608 _("Error in address “%s” — the unix transport requires exactly one of the "
609 "keys “path” or “abstract” to be set"),
612 else if (path != NULL)
614 connectable = G_SOCKET_CONNECTABLE (g_unix_socket_address_new (path));
616 else if (abstract != NULL)
618 connectable = G_SOCKET_CONNECTABLE (g_unix_socket_address_new_with_type (abstract,
620 G_UNIX_SOCKET_ADDRESS_ABSTRACT));
624 g_assert_not_reached ();
628 else if (g_strcmp0 (transport_name, "tcp") == 0 || g_strcmp0 (transport_name, "nonce-tcp") == 0)
636 is_nonce = (g_strcmp0 (transport_name, "nonce-tcp") == 0);
638 host = g_hash_table_lookup (key_value_pairs, "host");
643 G_IO_ERROR_INVALID_ARGUMENT,
644 _("Error in address “%s” — the host attribute is missing or malformed"),
649 s = g_hash_table_lookup (key_value_pairs, "port");
652 port = strtol (s, &endp, 10);
653 if ((*s == '\0' || *endp != '\0') || port < 0 || port >= 65536)
657 G_IO_ERROR_INVALID_ARGUMENT,
658 _("Error in address “%s” — the port attribute is missing or malformed"),
666 nonce_file = g_hash_table_lookup (key_value_pairs, "noncefile");
667 if (nonce_file == NULL)
671 G_IO_ERROR_INVALID_ARGUMENT,
672 _("Error in address “%s” — the noncefile attribute is missing or malformed"),
678 /* TODO: deal with family key/value-pair */
679 connectable = g_network_address_new (host, port);
681 else if (g_strcmp0 (address_entry, "autolaunch:") == 0)
683 gchar *autolaunch_address;
684 autolaunch_address = get_session_address_dbus_launch (error);
685 if (autolaunch_address != NULL)
687 ret = g_dbus_address_try_connect_one (autolaunch_address, kdbus_okay, NULL, cancellable, error);
688 g_free (autolaunch_address);
693 g_prefix_error (error, _("Error auto-launching: "));
700 G_IO_ERROR_INVALID_ARGUMENT,
701 _("Unknown or unsupported transport “%s” for address “%s”"),
706 if (connectable != NULL)
708 GSocketClient *client;
709 GSocketConnection *connection;
711 g_assert (ret == NULL);
712 client = g_socket_client_new ();
714 /* Disable proxy support to prevent a deadlock on startup, since loading a
715 * proxy resolver causes the GIO modules to be loaded, and there will
716 * almost certainly be one of them which then tries to use GDBus.
717 * See: https://bugzilla.gnome.org/show_bug.cgi?id=792499 */
718 g_socket_client_set_enable_proxy (client, FALSE);
720 connection = g_socket_client_connect (client,
724 g_object_unref (connectable);
725 g_object_unref (client);
726 if (connection == NULL)
729 ret = G_OBJECT (connection);
731 if (nonce_file != NULL)
733 gchar nonce_contents[16 + 1];
734 size_t num_bytes_read;
738 /* be careful to read only 16 bytes - we also check that the file is only 16 bytes long */
739 f = fopen (nonce_file, "rb");
745 G_IO_ERROR_INVALID_ARGUMENT,
746 _("Error opening nonce file “%s”: %s"),
749 g_object_unref (ret);
753 num_bytes_read = fread (nonce_contents,
758 if (num_bytes_read != 16)
760 if (num_bytes_read == 0)
764 G_IO_ERROR_INVALID_ARGUMENT,
765 _("Error reading from nonce file “%s”: %s"),
773 G_IO_ERROR_INVALID_ARGUMENT,
774 _("Error reading from nonce file “%s”, expected 16 bytes, got %d"),
776 (gint) num_bytes_read);
778 g_object_unref (ret);
785 if (!g_output_stream_write_all (g_io_stream_get_output_stream (G_IO_STREAM (connection)),
792 g_prefix_error (error, _("Error writing contents of nonce file “%s” to stream:"), nonce_file);
793 g_object_unref (ret);
806 g_dbus_address_try_connect_one (const gchar *address_entry,
809 GCancellable *cancellable,
813 GHashTable *key_value_pairs;
814 gchar *transport_name;
818 transport_name = NULL;
819 key_value_pairs = NULL;
821 if (!_g_dbus_address_parse_entry (address_entry,
827 ret = g_dbus_address_connect (address_entry,
836 guid = g_hash_table_lookup (key_value_pairs, "guid");
837 if (guid != NULL && out_guid != NULL)
838 *out_guid = g_strdup (guid);
841 g_free (transport_name);
842 if (key_value_pairs != NULL)
843 g_hash_table_unref (key_value_pairs);
848 /* ---------------------------------------------------------------------------------------------------- */
856 get_stream_data_free (GetStreamData *data)
858 g_free (data->address);
864 get_stream_thread_func (GTask *task,
865 gpointer source_object,
867 GCancellable *cancellable)
869 GetStreamData *data = task_data;
871 GError *error = NULL;
873 stream = g_dbus_address_get_stream_sync (data->address,
878 g_task_return_pointer (task, stream, g_object_unref);
880 g_task_return_error (task, error);
884 * g_dbus_address_get_stream:
885 * @address: A valid D-Bus address.
886 * @cancellable: (nullable): A #GCancellable or %NULL.
887 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
888 * @user_data: Data to pass to @callback.
890 * Asynchronously connects to an endpoint specified by @address and
891 * sets up the connection so it is in a state to run the client-side
892 * of the D-Bus authentication conversation. @address must be in the
893 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
895 * When the operation is finished, @callback will be invoked. You can
896 * then call g_dbus_address_get_stream_finish() to get the result of
899 * This is an asynchronous failable function. See
900 * g_dbus_address_get_stream_sync() for the synchronous version.
905 g_dbus_address_get_stream (const gchar *address,
906 GCancellable *cancellable,
907 GAsyncReadyCallback callback,
913 g_return_if_fail (address != NULL);
915 data = g_new0 (GetStreamData, 1);
916 data->address = g_strdup (address);
918 task = g_task_new (NULL, cancellable, callback, user_data);
919 g_task_set_source_tag (task, g_dbus_address_get_stream);
920 g_task_set_task_data (task, data, (GDestroyNotify) get_stream_data_free);
921 g_task_run_in_thread (task, get_stream_thread_func);
922 g_object_unref (task);
926 * g_dbus_address_get_stream_finish:
927 * @res: A #GAsyncResult obtained from the GAsyncReadyCallback passed to g_dbus_address_get_stream().
928 * @out_guid: (optional) (out): %NULL or return location to store the GUID extracted from @address, if any.
929 * @error: Return location for error or %NULL.
931 * Finishes an operation started with g_dbus_address_get_stream().
933 * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
938 g_dbus_address_get_stream_finish (GAsyncResult *res,
946 g_return_val_if_fail (g_task_is_valid (res, NULL), NULL);
947 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
950 ret = g_task_propagate_pointer (task, error);
952 if (ret != NULL && out_guid != NULL)
954 data = g_task_get_task_data (task);
955 *out_guid = data->guid;
963 * g_dbus_address_get_stream_sync:
964 * @address: A valid D-Bus address.
965 * @out_guid: (optional) (out): %NULL or return location to store the GUID extracted from @address, if any.
966 * @cancellable: (nullable): A #GCancellable or %NULL.
967 * @error: Return location for error or %NULL.
969 * Synchronously connects to an endpoint specified by @address and
970 * sets up the connection so it is in a state to run the client-side
971 * of the D-Bus authentication conversation. @address must be in the
972 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
974 * This is a synchronous failable function. See
975 * g_dbus_address_get_stream() for the asynchronous version.
977 * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
982 g_dbus_address_get_stream_sync (const gchar *address,
984 GCancellable *cancellable,
989 result = g_dbus_address_get_stream_internal (address, FALSE, out_guid, cancellable, error);
990 g_assert (result == NULL || G_IS_IO_STREAM (result));
993 return G_IO_STREAM (result);
999 g_dbus_address_get_stream_internal (const gchar *address,
1000 gboolean kdbus_okay,
1002 GCancellable *cancellable,
1010 g_return_val_if_fail (address != NULL, NULL);
1011 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1016 addr_array = g_strsplit (address, ";", 0);
1017 if (addr_array[0] == NULL)
1019 last_error = g_error_new_literal (G_IO_ERROR,
1020 G_IO_ERROR_INVALID_ARGUMENT,
1021 _("The given address is empty"));
1025 for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
1027 const gchar *addr = addr_array[n];
1031 ret = g_dbus_address_try_connect_one (addr,
1042 g_assert (this_error != NULL);
1043 if (last_error != NULL)
1044 g_error_free (last_error);
1045 last_error = this_error;
1052 if (last_error != NULL)
1053 g_error_free (last_error);
1057 g_assert (last_error != NULL);
1058 g_propagate_error (error, last_error);
1061 g_strfreev (addr_array);
1065 /* ---------------------------------------------------------------------------------------------------- */
1068 * Return the address of XDG_RUNTIME_DIR/bus if it exists, belongs to
1069 * us, and is a socket, and we are on Unix.
1072 get_session_address_xdg (void)
1080 bus = g_build_filename (g_get_user_runtime_dir (), "bus", NULL);
1082 /* if ENOENT, EPERM, etc., quietly don't use it */
1083 if (g_stat (bus, &buf) < 0)
1086 /* if it isn't ours, we have incorrectly inherited someone else's
1087 * XDG_RUNTIME_DIR; silently don't use it
1089 if (buf.st_uid != geteuid ())
1092 /* if it isn't a socket, silently don't use it */
1093 if ((buf.st_mode & S_IFMT) != S_IFSOCK)
1096 tmp = g_dbus_address_escape_value (bus);
1097 ret = g_strconcat ("unix:path=", tmp, NULL);
1109 get_session_address_kdbus (void)
1116 bus = g_strdup_printf ("/sys/fs/kdbus/%d-user/bus", getuid());
1118 /* if ENOENT, EPERM, etc., quietly don't use it */
1119 if (g_stat (bus, &buf) < 0)
1122 ret = g_strconcat ("kernel:path=", bus, NULL);
1132 /* ---------------------------------------------------------------------------------------------------- */
1136 get_session_address_dbus_launch (GError **error)
1140 gchar *command_line;
1141 gchar *launch_stdout;
1142 gchar *launch_stderr;
1144 gchar *old_dbus_verbose;
1145 gboolean restore_dbus_verbose;
1149 command_line = NULL;
1150 launch_stdout = NULL;
1151 launch_stderr = NULL;
1152 restore_dbus_verbose = FALSE;
1153 old_dbus_verbose = NULL;
1155 /* Don't run binaries as root if we're setuid. */
1156 if (GLIB_PRIVATE_CALL (g_check_setuid) ())
1158 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1159 _("Cannot spawn a message bus when setuid"));
1163 machine_id = _g_dbus_get_machine_id (error);
1164 if (machine_id == NULL)
1166 g_prefix_error (error, _("Cannot spawn a message bus without a machine-id: "));
1170 if (g_getenv ("DISPLAY") == NULL)
1172 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1173 _("Cannot autolaunch D-Bus without X11 $DISPLAY"));
1177 /* We're using private libdbus facilities here. When everything
1178 * (X11, Mac OS X, Windows) is spec'ed out correctly (not even the
1179 * X11 property is correctly documented right now) we should
1180 * consider using the spec instead of dbus-launch.
1182 * --autolaunch=MACHINEID
1183 * This option implies that dbus-launch should scan for a previ‐
1184 * ously-started session and reuse the values found there. If no
1185 * session is found, it will start a new session. The --exit-with-
1186 * session option is implied if --autolaunch is given. This option
1187 * is for the exclusive use of libdbus, you do not want to use it
1188 * manually. It may change in the future.
1191 /* TODO: maybe provide a variable for where to look for the dbus-launch binary? */
1192 command_line = g_strdup_printf ("dbus-launch --autolaunch=%s --binary-syntax --close-stderr", machine_id);
1194 if (G_UNLIKELY (_g_dbus_debug_address ()))
1196 _g_dbus_debug_print_lock ();
1197 g_print ("GDBus-debug:Address: Running '%s' to get bus address (possibly autolaunching)\n", command_line);
1198 old_dbus_verbose = g_strdup (g_getenv ("DBUS_VERBOSE"));
1199 restore_dbus_verbose = TRUE;
1200 g_setenv ("DBUS_VERBOSE", "1", TRUE);
1201 _g_dbus_debug_print_unlock ();
1204 if (!g_spawn_command_line_sync (command_line,
1213 if (!g_spawn_check_exit_status (exit_status, error))
1215 g_prefix_error (error, _("Error spawning command line “%s”: "), command_line);
1219 /* From the dbus-launch(1) man page:
1221 * --binary-syntax Write to stdout a nul-terminated bus address,
1222 * then the bus PID as a binary integer of size sizeof(pid_t),
1223 * then the bus X window ID as a binary integer of size
1224 * sizeof(long). Integers are in the machine's byte order, not
1225 * network byte order or any other canonical byte order.
1227 ret = g_strdup (launch_stdout);
1230 if (G_UNLIKELY (_g_dbus_debug_address ()))
1233 _g_dbus_debug_print_lock ();
1234 g_print ("GDBus-debug:Address: dbus-launch output:");
1235 if (launch_stdout != NULL)
1237 s = _g_dbus_hexdump (launch_stdout, strlen (launch_stdout) + 1 + sizeof (pid_t) + sizeof (long), 2);
1238 g_print ("\n%s", s);
1243 g_print (" (none)\n");
1245 g_print ("GDBus-debug:Address: dbus-launch stderr output:");
1246 if (launch_stderr != NULL)
1247 g_print ("\n%s", launch_stderr);
1249 g_print (" (none)\n");
1250 _g_dbus_debug_print_unlock ();
1253 g_free (machine_id);
1254 g_free (command_line);
1255 g_free (launch_stdout);
1256 g_free (launch_stderr);
1257 if (G_UNLIKELY (restore_dbus_verbose))
1259 if (old_dbus_verbose != NULL)
1260 g_setenv ("DBUS_VERBOSE", old_dbus_verbose, TRUE);
1262 g_unsetenv ("DBUS_VERBOSE");
1264 g_free (old_dbus_verbose);
1268 /* end of G_OS_UNIX case */
1269 #elif defined(G_OS_WIN32)
1272 get_session_address_dbus_launch (GError **error)
1274 return _g_dbus_win32_get_session_address_dbus_launch (error);
1277 #else /* neither G_OS_UNIX nor G_OS_WIN32 */
1279 get_session_address_dbus_launch (GError **error)
1284 _("Cannot determine session bus address (not implemented for this OS)"));
1287 #endif /* neither G_OS_UNIX nor G_OS_WIN32 */
1289 /* ---------------------------------------------------------------------------------------------------- */
1292 get_session_address_platform_specific (GError **error)
1296 /* Use XDG_RUNTIME_DIR/bus if it exists and is suitable. This is appropriate
1297 * for systems using the "a session is a user-session" model described in
1298 * <http://lists.freedesktop.org/archives/dbus/2015-January/016522.html>,
1299 * and implemented in dbus >= 1.9.14 and sd-bus.
1301 * On systems following the more traditional "a session is a login-session"
1302 * model, this will fail and we'll fall through to X11 autolaunching
1303 * (dbus-launch) below.
1305 ret = get_session_address_xdg ();
1310 /* TODO (#694472): try launchd on OS X, like
1311 * _dbus_lookup_session_address_launchd() does, since
1312 * 'dbus-launch --autolaunch' probably won't work there
1315 /* As a last resort, try the "autolaunch:" transport. On Unix this means
1316 * X11 autolaunching; on Windows this means a different autolaunching
1317 * mechanism based on shared memory.
1319 return get_session_address_dbus_launch (error);
1322 /* ---------------------------------------------------------------------------------------------------- */
1325 * g_dbus_address_get_for_bus_sync:
1326 * @bus_type: a #GBusType
1327 * @cancellable: (nullable): a #GCancellable or %NULL
1328 * @error: return location for error or %NULL
1330 * Synchronously looks up the D-Bus address for the well-known message
1331 * bus instance specified by @bus_type. This may involve using various
1332 * platform specific mechanisms.
1334 * The returned address will be in the
1335 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
1337 * Returns: (transfer full): a valid D-Bus address string for @bus_type or
1338 * %NULL if @error is set
1343 g_dbus_address_get_for_bus_sync (GBusType bus_type,
1344 GCancellable *cancellable,
1347 gchar *ret, *s = NULL;
1348 const gchar *starter_bus;
1349 GError *local_error;
1351 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1356 if (G_UNLIKELY (_g_dbus_debug_address ()))
1360 _g_dbus_debug_print_lock ();
1361 s = _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type);
1362 g_print ("GDBus-debug:Address: In g_dbus_address_get_for_bus_sync() for bus type '%s'\n",
1365 for (n = 0; n < 3; n++)
1371 case 0: k = "DBUS_SESSION_BUS_ADDRESS"; break;
1372 case 1: k = "DBUS_SYSTEM_BUS_ADDRESS"; break;
1373 case 2: k = "DBUS_STARTER_BUS_TYPE"; break;
1374 default: g_assert_not_reached ();
1377 g_print ("GDBus-debug:Address: env var %s", k);
1379 g_print ("='%s'\n", v);
1381 g_print (" is not set\n");
1383 _g_dbus_debug_print_unlock ();
1388 case G_BUS_TYPE_SYSTEM:
1389 ret = g_strdup (g_getenv ("DBUS_SYSTEM_BUS_ADDRESS"));
1392 ret = g_strdup ("kernel:path=/sys/fs/kdbus/0-system/bus;unix:path=/var/run/dbus/system_bus_socket");
1396 case G_BUS_TYPE_SESSION:
1397 ret = g_strdup (g_getenv ("DBUS_SESSION_BUS_ADDRESS"));
1400 ret = get_session_address_kdbus ();
1402 ret = get_session_address_platform_specific (&local_error);
1408 case G_BUS_TYPE_STARTER:
1409 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
1410 if (g_strcmp0 (starter_bus, "session") == 0)
1412 ret = g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SESSION, cancellable, &local_error);
1415 else if (g_strcmp0 (starter_bus, "system") == 0)
1417 ret = g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SYSTEM, cancellable, &local_error);
1422 if (starter_bus != NULL)
1424 g_set_error (&local_error,
1427 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
1428 " — unknown value “%s”"),
1433 g_set_error_literal (&local_error,
1436 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
1437 "variable is not set"));
1443 g_set_error (&local_error,
1446 _("Unknown bus type %d"),
1452 if (G_UNLIKELY (_g_dbus_debug_address ()))
1454 _g_dbus_debug_print_lock ();
1455 s = _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type);
1458 g_print ("GDBus-debug:Address: Returning address '%s' for bus type '%s'\n",
1463 g_print ("GDBus-debug:Address: Cannot look-up address bus type '%s': %s\n",
1464 s, local_error ? local_error->message : "");
1467 _g_dbus_debug_print_unlock ();
1470 if (local_error != NULL)
1471 g_propagate_error (error, local_error);
1477 * g_dbus_address_escape_value:
1478 * @string: an unescaped string to be included in a D-Bus address
1479 * as the value in a key-value pair
1481 * Escape @string so it can appear in a D-Bus address as the value
1482 * part of a key-value pair.
1484 * For instance, if @string is `/run/bus-for-:0`,
1485 * this function would return `/run/bus-for-%3A0`,
1486 * which could be used in a D-Bus address like
1487 * `unix:nonce-tcp:host=127.0.0.1,port=42,noncefile=/run/bus-for-%3A0`.
1489 * Returns: (transfer full): a copy of @string with all
1490 * non-optionally-escaped bytes escaped
1495 g_dbus_address_escape_value (const gchar *string)
1500 g_return_val_if_fail (string != NULL, NULL);
1502 /* There will often not be anything needing escaping at all. */
1503 s = g_string_sized_new (strlen (string));
1505 /* D-Bus address escaping is mostly the same as URI escaping... */
1506 g_string_append_uri_escaped (s, string, "\\/", FALSE);
1508 /* ... but '~' is an unreserved character in URIs, but a
1509 * non-optionally-escaped character in D-Bus addresses. */
1510 for (i = 0; i < s->len; i++)
1512 if (G_UNLIKELY (s->str[i] == '~'))
1515 g_string_insert (s, i + 1, "7E");
1520 return g_string_free (s, FALSE);