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 "glib-private.h"
34 #include "gnetworkaddress.h"
35 #include "gsocketclient.h"
36 #include "giostream.h"
37 #include "gasyncresult.h"
39 #include "glib-private.h"
40 #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 “%s” attribute is malformed"),
249 address_entry, "port");
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 “%s” attribute is malformed"),
260 address_entry, "family");
266 /* TODO: validate host */
269 if (nonce_file != NULL && *nonce_file == '\0')
273 G_IO_ERROR_INVALID_ARGUMENT,
274 _("Error in address “%s” — the “%s” attribute is malformed"),
275 address_entry, "noncefile");
288 is_valid_tcp (const gchar *address_entry,
289 GHashTable *key_value_pairs,
307 keys = g_hash_table_get_keys (key_value_pairs);
308 for (l = keys; l != NULL; l = l->next)
310 const gchar *key = l->data;
311 if (g_strcmp0 (key, "host") == 0)
312 host = g_hash_table_lookup (key_value_pairs, key);
313 else if (g_strcmp0 (key, "port") == 0)
314 port = g_hash_table_lookup (key_value_pairs, key);
315 else if (g_strcmp0 (key, "family") == 0)
316 family = g_hash_table_lookup (key_value_pairs, key);
317 else if (g_strcmp0 (key, "guid") != 0)
321 G_IO_ERROR_INVALID_ARGUMENT,
322 _("Unsupported key “%s” in address entry “%s”"),
331 port_num = strtol (port, &endp, 10);
332 if ((*port == '\0' || *endp != '\0') || port_num < 0 || port_num >= 65536)
336 G_IO_ERROR_INVALID_ARGUMENT,
337 _("Error in address “%s” — the “%s” attribute is malformed"),
338 address_entry, "port");
343 if (family != NULL && !(g_strcmp0 (family, "ipv4") == 0 || g_strcmp0 (family, "ipv6") == 0))
347 G_IO_ERROR_INVALID_ARGUMENT,
348 _("Error in address “%s” — the “%s” attribute is malformed"),
349 address_entry, "family");
355 /* TODO: validate host */
367 * g_dbus_is_supported_address:
369 * @error: Return location for error or %NULL.
371 * Like g_dbus_is_address() but also checks if the library supports the
372 * transports in @string and that key/value pairs for each transport
373 * are valid. See the specification of the
374 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
376 * Returns: %TRUE if @string is a valid D-Bus address that is
377 * supported by this library, %FALSE if @error is set.
382 g_dbus_is_supported_address (const gchar *string,
391 g_return_val_if_fail (string != NULL, FALSE);
392 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
394 a = g_strsplit (string, ";", 0);
395 for (n = 0; a[n] != NULL; n++)
397 gchar *transport_name;
398 GHashTable *key_value_pairs;
401 if (!_g_dbus_address_parse_entry (a[n],
408 if (g_strcmp0 (transport_name, "unix") == 0)
409 supported = is_valid_unix (a[n], key_value_pairs, error);
410 else if (g_strcmp0 (transport_name, "tcp") == 0)
411 supported = is_valid_tcp (a[n], key_value_pairs, error);
412 else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
413 supported = is_valid_nonce_tcp (a[n], key_value_pairs, error);
414 else if (g_strcmp0 (a[n], "autolaunch:") == 0)
417 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
418 _("Unknown or unsupported transport “%s” for address “%s”"),
419 transport_name, a[n]);
421 g_free (transport_name);
422 g_hash_table_unref (key_value_pairs);
433 g_assert (ret || (!ret && (error == NULL || *error != NULL)));
439 _g_dbus_address_parse_entry (const gchar *address_entry,
440 gchar **out_transport_name,
441 GHashTable **out_key_value_pairs,
445 GHashTable *key_value_pairs;
446 gchar *transport_name;
453 transport_name = NULL;
454 key_value_pairs = NULL;
456 s = strchr (address_entry, ':');
461 G_IO_ERROR_INVALID_ARGUMENT,
462 _("Address element “%s” does not contain a colon (:)"),
466 else if (s == address_entry)
470 G_IO_ERROR_INVALID_ARGUMENT,
471 _("Transport name in address element “%s” must not be empty"),
476 transport_name = g_strndup (address_entry, s - address_entry);
477 key_value_pairs = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
479 kv_pairs = g_strsplit (s + 1, ",", 0);
480 for (n = 0; kv_pairs[n] != NULL; n++)
482 const gchar *kv_pair = kv_pairs[n];
486 s = strchr (kv_pair, '=');
491 G_IO_ERROR_INVALID_ARGUMENT,
492 _("Key/Value pair %d, “%s”, in address element “%s” does not contain an equal sign"),
498 else if (s == kv_pair)
502 G_IO_ERROR_INVALID_ARGUMENT,
503 _("Key/Value pair %d, “%s”, in address element “%s” must not have an empty key"),
510 key = g_uri_unescape_segment (kv_pair, s, NULL);
511 value = g_uri_unescape_segment (s + 1, kv_pair + strlen (kv_pair), NULL);
512 if (key == NULL || value == NULL)
516 G_IO_ERROR_INVALID_ARGUMENT,
517 _("Error unescaping key or value in Key/Value pair %d, “%s”, in address element “%s”"),
525 g_hash_table_insert (key_value_pairs, key, value);
533 if (out_transport_name != NULL)
534 *out_transport_name = g_steal_pointer (&transport_name);
535 if (out_key_value_pairs != NULL)
536 *out_key_value_pairs = g_steal_pointer (&key_value_pairs);
539 g_clear_pointer (&key_value_pairs, g_hash_table_unref);
540 g_free (transport_name);
541 g_strfreev (kv_pairs);
546 /* ---------------------------------------------------------------------------------------------------- */
549 g_dbus_address_try_connect_one (const gchar *address_entry,
551 GCancellable *cancellable,
554 /* TODO: Declare an extension point called GDBusTransport (or similar)
555 * and move code below to extensions implementing said extension
556 * point. That way we can implement a D-Bus transport over X11 without
557 * making libgio link to libX11...
560 g_dbus_address_connect (const gchar *address_entry,
561 const gchar *transport_name,
562 GHashTable *key_value_pairs,
563 GCancellable *cancellable,
567 GSocketConnectable *connectable;
568 const gchar *nonce_file;
578 else if (g_strcmp0 (transport_name, "unix") == 0)
581 const gchar *abstract;
582 path = g_hash_table_lookup (key_value_pairs, "path");
583 abstract = g_hash_table_lookup (key_value_pairs, "abstract");
584 if ((path == NULL && abstract == NULL) || (path != NULL && abstract != NULL))
588 G_IO_ERROR_INVALID_ARGUMENT,
589 _("Error in address “%s” — the unix transport requires exactly one of the "
590 "keys “path” or “abstract” to be set"),
593 else if (path != NULL)
595 connectable = G_SOCKET_CONNECTABLE (g_unix_socket_address_new (path));
597 else if (abstract != NULL)
599 connectable = G_SOCKET_CONNECTABLE (g_unix_socket_address_new_with_type (abstract,
601 G_UNIX_SOCKET_ADDRESS_ABSTRACT));
605 g_assert_not_reached ();
609 else if (g_strcmp0 (transport_name, "tcp") == 0 || g_strcmp0 (transport_name, "nonce-tcp") == 0)
617 is_nonce = (g_strcmp0 (transport_name, "nonce-tcp") == 0);
619 host = g_hash_table_lookup (key_value_pairs, "host");
624 G_IO_ERROR_INVALID_ARGUMENT,
625 _("Error in address “%s” — the host attribute is missing or malformed"),
630 s = g_hash_table_lookup (key_value_pairs, "port");
633 port = strtol (s, &endp, 10);
634 if ((*s == '\0' || *endp != '\0') || port < 0 || port >= 65536)
638 G_IO_ERROR_INVALID_ARGUMENT,
639 _("Error in address “%s” — the port attribute is missing or malformed"),
647 nonce_file = g_hash_table_lookup (key_value_pairs, "noncefile");
648 if (nonce_file == NULL)
652 G_IO_ERROR_INVALID_ARGUMENT,
653 _("Error in address “%s” — the noncefile attribute is missing or malformed"),
659 /* TODO: deal with family key/value-pair */
660 connectable = g_network_address_new (host, port);
662 else if (g_strcmp0 (address_entry, "autolaunch:") == 0)
664 gchar *autolaunch_address;
665 autolaunch_address = get_session_address_dbus_launch (error);
666 if (autolaunch_address != NULL)
668 ret = g_dbus_address_try_connect_one (autolaunch_address, NULL, cancellable, error);
669 g_free (autolaunch_address);
674 g_prefix_error (error, _("Error auto-launching: "));
681 G_IO_ERROR_INVALID_ARGUMENT,
682 _("Unknown or unsupported transport “%s” for address “%s”"),
687 if (connectable != NULL)
689 GSocketClient *client;
690 GSocketConnection *connection;
692 g_assert (ret == NULL);
693 client = g_socket_client_new ();
695 /* Disable proxy support to prevent a deadlock on startup, since loading a
696 * proxy resolver causes the GIO modules to be loaded, and there will
697 * almost certainly be one of them which then tries to use GDBus.
698 * See: https://bugzilla.gnome.org/show_bug.cgi?id=792499 */
699 g_socket_client_set_enable_proxy (client, FALSE);
701 connection = g_socket_client_connect (client,
705 g_object_unref (connectable);
706 g_object_unref (client);
707 if (connection == NULL)
710 ret = G_IO_STREAM (connection);
712 if (nonce_file != NULL)
714 gchar nonce_contents[16 + 1];
715 size_t num_bytes_read;
719 /* be careful to read only 16 bytes - we also check that the file is only 16 bytes long */
720 f = fopen (nonce_file, "rb");
726 G_IO_ERROR_INVALID_ARGUMENT,
727 _("Error opening nonce file “%s”: %s"),
730 g_object_unref (ret);
734 num_bytes_read = fread (nonce_contents,
739 if (num_bytes_read != 16)
741 if (num_bytes_read == 0)
745 G_IO_ERROR_INVALID_ARGUMENT,
746 _("Error reading from nonce file “%s”: %s"),
754 G_IO_ERROR_INVALID_ARGUMENT,
755 _("Error reading from nonce file “%s”, expected 16 bytes, got %d"),
757 (gint) num_bytes_read);
759 g_object_unref (ret);
766 if (!g_output_stream_write_all (g_io_stream_get_output_stream (ret),
773 g_prefix_error (error, _("Error writing contents of nonce file “%s” to stream:"), nonce_file);
774 g_object_unref (ret);
787 g_dbus_address_try_connect_one (const gchar *address_entry,
789 GCancellable *cancellable,
793 GHashTable *key_value_pairs;
794 gchar *transport_name;
798 transport_name = NULL;
799 key_value_pairs = NULL;
801 if (!_g_dbus_address_parse_entry (address_entry,
807 ret = g_dbus_address_connect (address_entry,
815 guid = g_hash_table_lookup (key_value_pairs, "guid");
816 if (guid != NULL && out_guid != NULL)
817 *out_guid = g_strdup (guid);
820 g_free (transport_name);
821 if (key_value_pairs != NULL)
822 g_hash_table_unref (key_value_pairs);
827 /* ---------------------------------------------------------------------------------------------------- */
835 get_stream_data_free (GetStreamData *data)
837 g_free (data->address);
843 get_stream_thread_func (GTask *task,
844 gpointer source_object,
846 GCancellable *cancellable)
848 GetStreamData *data = task_data;
850 GError *error = NULL;
852 stream = g_dbus_address_get_stream_sync (data->address,
857 g_task_return_pointer (task, stream, g_object_unref);
859 g_task_return_error (task, error);
863 * g_dbus_address_get_stream:
864 * @address: A valid D-Bus address.
865 * @cancellable: (nullable): A #GCancellable or %NULL.
866 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
867 * @user_data: Data to pass to @callback.
869 * Asynchronously connects to an endpoint specified by @address and
870 * sets up the connection so it is in a state to run the client-side
871 * of the D-Bus authentication conversation. @address must be in the
872 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
874 * When the operation is finished, @callback will be invoked. You can
875 * then call g_dbus_address_get_stream_finish() to get the result of
878 * This is an asynchronous failable function. See
879 * g_dbus_address_get_stream_sync() for the synchronous version.
884 g_dbus_address_get_stream (const gchar *address,
885 GCancellable *cancellable,
886 GAsyncReadyCallback callback,
892 g_return_if_fail (address != NULL);
894 data = g_new0 (GetStreamData, 1);
895 data->address = g_strdup (address);
897 task = g_task_new (NULL, cancellable, callback, user_data);
898 g_task_set_source_tag (task, g_dbus_address_get_stream);
899 g_task_set_task_data (task, data, (GDestroyNotify) get_stream_data_free);
900 g_task_run_in_thread (task, get_stream_thread_func);
901 g_object_unref (task);
905 * g_dbus_address_get_stream_finish:
906 * @res: A #GAsyncResult obtained from the GAsyncReadyCallback passed to g_dbus_address_get_stream().
907 * @out_guid: (optional) (out) (nullable): %NULL or return location to store the GUID extracted from @address, if any.
908 * @error: Return location for error or %NULL.
910 * Finishes an operation started with g_dbus_address_get_stream().
912 * A server is not required to set a GUID, so @out_guid may be set to %NULL
915 * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
920 g_dbus_address_get_stream_finish (GAsyncResult *res,
928 g_return_val_if_fail (g_task_is_valid (res, NULL), NULL);
929 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
932 ret = g_task_propagate_pointer (task, error);
934 if (ret != NULL && out_guid != NULL)
936 data = g_task_get_task_data (task);
937 *out_guid = data->guid;
945 * g_dbus_address_get_stream_sync:
946 * @address: A valid D-Bus address.
947 * @out_guid: (optional) (out) (nullable): %NULL or return location to store the GUID extracted from @address, if any.
948 * @cancellable: (nullable): A #GCancellable or %NULL.
949 * @error: Return location for error or %NULL.
951 * Synchronously connects to an endpoint specified by @address and
952 * sets up the connection so it is in a state to run the client-side
953 * of the D-Bus authentication conversation. @address must be in the
954 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
956 * A server is not required to set a GUID, so @out_guid may be set to %NULL
959 * This is a synchronous failable function. See
960 * g_dbus_address_get_stream() for the asynchronous version.
962 * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
967 g_dbus_address_get_stream_sync (const gchar *address,
969 GCancellable *cancellable,
977 g_return_val_if_fail (address != NULL, NULL);
978 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
983 addr_array = g_strsplit (address, ";", 0);
984 if (addr_array[0] == NULL)
986 last_error = g_error_new_literal (G_IO_ERROR,
987 G_IO_ERROR_INVALID_ARGUMENT,
988 _("The given address is empty"));
992 for (n = 0; addr_array[n] != NULL; n++)
994 const gchar *addr = addr_array[n];
998 ret = g_dbus_address_try_connect_one (addr,
1008 g_assert (this_error != NULL);
1009 if (last_error != NULL)
1010 g_error_free (last_error);
1011 last_error = this_error;
1018 if (last_error != NULL)
1019 g_error_free (last_error);
1023 g_assert (last_error != NULL);
1024 g_propagate_error (error, last_error);
1027 g_strfreev (addr_array);
1031 /* ---------------------------------------------------------------------------------------------------- */
1034 * Return the address of XDG_RUNTIME_DIR/bus if it exists, belongs to
1035 * us, and is a socket, and we are on Unix.
1038 get_session_address_xdg (void)
1046 bus = g_build_filename (g_get_user_runtime_dir (), "bus", NULL);
1048 /* if ENOENT, EPERM, etc., quietly don't use it */
1049 if (g_stat (bus, &buf) < 0)
1052 /* if it isn't ours, we have incorrectly inherited someone else's
1053 * XDG_RUNTIME_DIR; silently don't use it
1055 if (buf.st_uid != geteuid ())
1058 /* if it isn't a socket, silently don't use it */
1059 if ((buf.st_mode & S_IFMT) != S_IFSOCK)
1062 tmp = g_dbus_address_escape_value (bus);
1063 ret = g_strconcat ("unix:path=", tmp, NULL);
1074 /* ---------------------------------------------------------------------------------------------------- */
1078 get_session_address_dbus_launch (GError **error)
1082 gchar *command_line;
1083 gchar *launch_stdout;
1084 gchar *launch_stderr;
1086 gchar *old_dbus_verbose;
1087 gboolean restore_dbus_verbose;
1091 command_line = NULL;
1092 launch_stdout = NULL;
1093 launch_stderr = NULL;
1094 restore_dbus_verbose = FALSE;
1095 old_dbus_verbose = NULL;
1097 /* Don't run binaries as root if we're setuid. */
1098 if (GLIB_PRIVATE_CALL (g_check_setuid) ())
1100 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1101 _("Cannot spawn a message bus when setuid"));
1105 machine_id = _g_dbus_get_machine_id (error);
1106 if (machine_id == NULL)
1108 g_prefix_error (error, _("Cannot spawn a message bus without a machine-id: "));
1112 if (g_getenv ("DISPLAY") == NULL)
1114 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1115 _("Cannot autolaunch D-Bus without X11 $DISPLAY"));
1119 /* We're using private libdbus facilities here. When everything
1120 * (X11, Mac OS X, Windows) is spec'ed out correctly (not even the
1121 * X11 property is correctly documented right now) we should
1122 * consider using the spec instead of dbus-launch.
1124 * --autolaunch=MACHINEID
1125 * This option implies that dbus-launch should scan for a previ‐
1126 * ously-started session and reuse the values found there. If no
1127 * session is found, it will start a new session. The --exit-with-
1128 * session option is implied if --autolaunch is given. This option
1129 * is for the exclusive use of libdbus, you do not want to use it
1130 * manually. It may change in the future.
1133 /* TODO: maybe provide a variable for where to look for the dbus-launch binary? */
1134 command_line = g_strdup_printf ("dbus-launch --autolaunch=%s --binary-syntax --close-stderr", machine_id);
1136 if (G_UNLIKELY (_g_dbus_debug_address ()))
1138 _g_dbus_debug_print_lock ();
1139 g_print ("GDBus-debug:Address: Running '%s' to get bus address (possibly autolaunching)\n", command_line);
1140 old_dbus_verbose = g_strdup (g_getenv ("DBUS_VERBOSE"));
1141 restore_dbus_verbose = TRUE;
1142 g_setenv ("DBUS_VERBOSE", "1", TRUE);
1143 _g_dbus_debug_print_unlock ();
1146 if (!g_spawn_command_line_sync (command_line,
1155 if (!g_spawn_check_wait_status (wait_status, error))
1157 g_prefix_error (error, _("Error spawning command line “%s”: "), command_line);
1161 /* From the dbus-launch(1) man page:
1163 * --binary-syntax Write to stdout a nul-terminated bus address,
1164 * then the bus PID as a binary integer of size sizeof(pid_t),
1165 * then the bus X window ID as a binary integer of size
1166 * sizeof(long). Integers are in the machine's byte order, not
1167 * network byte order or any other canonical byte order.
1169 ret = g_strdup (launch_stdout);
1172 if (G_UNLIKELY (_g_dbus_debug_address ()))
1175 _g_dbus_debug_print_lock ();
1176 g_print ("GDBus-debug:Address: dbus-launch output:");
1177 if (launch_stdout != NULL)
1179 s = _g_dbus_hexdump (launch_stdout, strlen (launch_stdout) + 1 + sizeof (pid_t) + sizeof (long), 2);
1180 g_print ("\n%s", s);
1185 g_print (" (none)\n");
1187 g_print ("GDBus-debug:Address: dbus-launch stderr output:");
1188 if (launch_stderr != NULL)
1189 g_print ("\n%s", launch_stderr);
1191 g_print (" (none)\n");
1192 _g_dbus_debug_print_unlock ();
1195 g_free (machine_id);
1196 g_free (command_line);
1197 g_free (launch_stdout);
1198 g_free (launch_stderr);
1199 if (G_UNLIKELY (restore_dbus_verbose))
1201 if (old_dbus_verbose != NULL)
1202 g_setenv ("DBUS_VERBOSE", old_dbus_verbose, TRUE);
1204 g_unsetenv ("DBUS_VERBOSE");
1206 g_free (old_dbus_verbose);
1210 /* end of G_OS_UNIX case */
1211 #elif defined(G_OS_WIN32)
1214 get_session_address_dbus_launch (GError **error)
1216 return _g_dbus_win32_get_session_address_dbus_launch (error);
1219 #else /* neither G_OS_UNIX nor G_OS_WIN32 */
1221 get_session_address_dbus_launch (GError **error)
1226 _("Cannot determine session bus address (not implemented for this OS)"));
1229 #endif /* neither G_OS_UNIX nor G_OS_WIN32 */
1231 /* ---------------------------------------------------------------------------------------------------- */
1234 get_session_address_platform_specific (GError **error)
1238 /* Use XDG_RUNTIME_DIR/bus if it exists and is suitable. This is appropriate
1239 * for systems using the "a session is a user-session" model described in
1240 * <http://lists.freedesktop.org/archives/dbus/2015-January/016522.html>,
1241 * and implemented in dbus >= 1.9.14 and sd-bus.
1243 * On systems following the more traditional "a session is a login-session"
1244 * model, this will fail and we'll fall through to X11 autolaunching
1245 * (dbus-launch) below.
1247 ret = get_session_address_xdg ();
1252 /* TODO (#694472): try launchd on OS X, like
1253 * _dbus_lookup_session_address_launchd() does, since
1254 * 'dbus-launch --autolaunch' probably won't work there
1257 /* As a last resort, try the "autolaunch:" transport. On Unix this means
1258 * X11 autolaunching; on Windows this means a different autolaunching
1259 * mechanism based on shared memory.
1261 return get_session_address_dbus_launch (error);
1264 /* ---------------------------------------------------------------------------------------------------- */
1267 * g_dbus_address_get_for_bus_sync:
1268 * @bus_type: a #GBusType
1269 * @cancellable: (nullable): a #GCancellable or %NULL
1270 * @error: return location for error or %NULL
1272 * Synchronously looks up the D-Bus address for the well-known message
1273 * bus instance specified by @bus_type. This may involve using various
1274 * platform specific mechanisms.
1276 * The returned address will be in the
1277 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
1279 * Returns: (transfer full): a valid D-Bus address string for @bus_type or
1280 * %NULL if @error is set
1285 g_dbus_address_get_for_bus_sync (GBusType bus_type,
1286 GCancellable *cancellable,
1289 gboolean has_elevated_privileges = GLIB_PRIVATE_CALL (g_check_setuid) ();
1290 gchar *ret, *s = NULL;
1291 const gchar *starter_bus;
1292 GError *local_error;
1294 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1299 if (G_UNLIKELY (_g_dbus_debug_address ()))
1302 _g_dbus_debug_print_lock ();
1303 s = _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type);
1304 g_print ("GDBus-debug:Address: In g_dbus_address_get_for_bus_sync() for bus type '%s'\n",
1307 for (n = 0; n < 3; n++)
1313 case 0: k = "DBUS_SESSION_BUS_ADDRESS"; break;
1314 case 1: k = "DBUS_SYSTEM_BUS_ADDRESS"; break;
1315 case 2: k = "DBUS_STARTER_BUS_TYPE"; break;
1316 default: g_assert_not_reached ();
1319 g_print ("GDBus-debug:Address: env var %s", k);
1321 g_print ("='%s'\n", v);
1323 g_print (" is not set\n");
1325 _g_dbus_debug_print_unlock ();
1328 /* Don’t load the addresses from the environment if running as setuid, as they
1329 * come from an unprivileged caller. */
1332 case G_BUS_TYPE_SYSTEM:
1333 if (has_elevated_privileges)
1336 ret = g_strdup (g_getenv ("DBUS_SYSTEM_BUS_ADDRESS"));
1340 ret = g_strdup ("unix:path=/var/run/dbus/system_bus_socket");
1344 case G_BUS_TYPE_SESSION:
1345 if (has_elevated_privileges)
1348 ret = g_strdup (g_getenv ("DBUS_SESSION_BUS_ADDRESS"));
1352 ret = get_session_address_platform_specific (&local_error);
1356 case G_BUS_TYPE_STARTER:
1357 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
1358 if (g_strcmp0 (starter_bus, "session") == 0)
1360 ret = g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SESSION, cancellable, &local_error);
1363 else if (g_strcmp0 (starter_bus, "system") == 0)
1365 ret = g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SYSTEM, cancellable, &local_error);
1370 if (starter_bus != NULL)
1372 g_set_error (&local_error,
1375 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
1376 " — unknown value “%s”"),
1381 g_set_error_literal (&local_error,
1384 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
1385 "variable is not set"));
1391 g_set_error (&local_error,
1394 _("Unknown bus type %d"),
1400 if (G_UNLIKELY (_g_dbus_debug_address ()))
1402 _g_dbus_debug_print_lock ();
1403 s = _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type);
1406 g_print ("GDBus-debug:Address: Returning address '%s' for bus type '%s'\n",
1411 g_print ("GDBus-debug:Address: Cannot look-up address bus type '%s': %s\n",
1412 s, local_error ? local_error->message : "");
1415 _g_dbus_debug_print_unlock ();
1418 if (local_error != NULL)
1419 g_propagate_error (error, local_error);
1425 * g_dbus_address_escape_value:
1426 * @string: an unescaped string to be included in a D-Bus address
1427 * as the value in a key-value pair
1429 * Escape @string so it can appear in a D-Bus address as the value
1430 * part of a key-value pair.
1432 * For instance, if @string is `/run/bus-for-:0`,
1433 * this function would return `/run/bus-for-%3A0`,
1434 * which could be used in a D-Bus address like
1435 * `unix:nonce-tcp:host=127.0.0.1,port=42,noncefile=/run/bus-for-%3A0`.
1437 * Returns: (transfer full): a copy of @string with all
1438 * non-optionally-escaped bytes escaped
1443 g_dbus_address_escape_value (const gchar *string)
1448 g_return_val_if_fail (string != NULL, NULL);
1450 /* There will often not be anything needing escaping at all. */
1451 s = g_string_sized_new (strlen (string));
1453 /* D-Bus address escaping is mostly the same as URI escaping... */
1454 g_string_append_uri_escaped (s, string, "\\/", FALSE);
1456 /* ... but '~' is an unreserved character in URIs, but a
1457 * non-optionally-escaped character in D-Bus addresses. */
1458 for (i = 0; i < s->len; i++)
1460 if (G_UNLIKELY (s->str[i] == '~'))
1463 g_string_insert (s, i + 1, "7E");
1468 return g_string_free (s, FALSE);