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"
40 #include "giomodule-priv.h"
41 #include "gdbusdaemon.h"
47 #include <sys/types.h>
48 #include <gio/gunixsocketaddress.h>
60 * SECTION:gdbusaddress
61 * @title: D-Bus Addresses
62 * @short_description: D-Bus connection endpoints
65 * Routines for working with D-Bus addresses. A D-Bus address is a string
66 * like `unix:tmpdir=/tmp/my-app-name`. The exact format of addresses
67 * is explained in detail in the
68 * [D-Bus specification](http://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
70 * TCP D-Bus connections are supported, but accessing them via a proxy is
71 * currently not supported.
74 static gchar
*get_session_address_platform_specific (GError
**error
);
75 static gchar
*get_session_address_dbus_launch (GError
**error
);
77 /* ---------------------------------------------------------------------------------------------------- */
83 * Checks if @string is a
84 * [D-Bus address](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
86 * This doesn't check if @string is actually supported by #GDBusServer
87 * or #GDBusConnection - use g_dbus_is_supported_address() to do more
90 * Returns: %TRUE if @string is a valid D-Bus address, %FALSE otherwise.
95 g_dbus_is_address (const gchar
*string
)
103 g_return_val_if_fail (string
!= NULL
, FALSE
);
105 a
= g_strsplit (string
, ";", 0);
109 for (n
= 0; a
[n
] != NULL
; n
++)
111 if (!_g_dbus_address_parse_entry (a
[n
],
126 is_valid_unix (const gchar
*address_entry
,
127 GHashTable
*key_value_pairs
,
135 const gchar
*abstract
;
143 keys
= g_hash_table_get_keys (key_value_pairs
);
144 for (l
= keys
; l
!= NULL
; l
= l
->next
)
146 const gchar
*key
= l
->data
;
147 if (g_strcmp0 (key
, "path") == 0)
148 path
= g_hash_table_lookup (key_value_pairs
, key
);
149 else if (g_strcmp0 (key
, "tmpdir") == 0)
150 tmpdir
= g_hash_table_lookup (key_value_pairs
, key
);
151 else if (g_strcmp0 (key
, "abstract") == 0)
152 abstract
= g_hash_table_lookup (key_value_pairs
, key
);
157 G_IO_ERROR_INVALID_ARGUMENT
,
158 _("Unsupported key “%s” in address entry “%s”"),
167 if (tmpdir
!= NULL
|| abstract
!= NULL
)
170 else if (tmpdir
!= NULL
)
172 if (path
!= NULL
|| abstract
!= NULL
)
175 else if (abstract
!= NULL
)
177 if (path
!= NULL
|| tmpdir
!= NULL
)
184 G_IO_ERROR_INVALID_ARGUMENT
,
185 _("Address “%s” is invalid (need exactly one of path, tmpdir or abstract keys)"),
197 G_IO_ERROR_INVALID_ARGUMENT
,
198 _("Meaningless key/value pair combination in address entry “%s”"),
208 is_valid_nonce_tcp (const gchar
*address_entry
,
209 GHashTable
*key_value_pairs
,
218 const gchar
*nonce_file
;
229 keys
= g_hash_table_get_keys (key_value_pairs
);
230 for (l
= keys
; l
!= NULL
; l
= l
->next
)
232 const gchar
*key
= l
->data
;
233 if (g_strcmp0 (key
, "host") == 0)
234 host
= g_hash_table_lookup (key_value_pairs
, key
);
235 else if (g_strcmp0 (key
, "port") == 0)
236 port
= g_hash_table_lookup (key_value_pairs
, key
);
237 else if (g_strcmp0 (key
, "family") == 0)
238 family
= g_hash_table_lookup (key_value_pairs
, key
);
239 else if (g_strcmp0 (key
, "noncefile") == 0)
240 nonce_file
= g_hash_table_lookup (key_value_pairs
, key
);
245 G_IO_ERROR_INVALID_ARGUMENT
,
246 _("Unsupported key “%s” in address entry “%s”"),
255 port_num
= strtol (port
, &endp
, 10);
256 if ((*port
== '\0' || *endp
!= '\0') || port_num
< 0 || port_num
>= 65536)
260 G_IO_ERROR_INVALID_ARGUMENT
,
261 _("Error in address “%s” — the port attribute is malformed"),
267 if (family
!= NULL
&& !(g_strcmp0 (family
, "ipv4") == 0 || g_strcmp0 (family
, "ipv6") == 0))
271 G_IO_ERROR_INVALID_ARGUMENT
,
272 _("Error in address “%s” — the family attribute is malformed"),
279 /* TODO: validate host */
282 nonce_file
= nonce_file
; /* To avoid -Wunused-but-set-variable */
293 is_valid_tcp (const gchar
*address_entry
,
294 GHashTable
*key_value_pairs
,
312 keys
= g_hash_table_get_keys (key_value_pairs
);
313 for (l
= keys
; l
!= NULL
; l
= l
->next
)
315 const gchar
*key
= l
->data
;
316 if (g_strcmp0 (key
, "host") == 0)
317 host
= g_hash_table_lookup (key_value_pairs
, key
);
318 else if (g_strcmp0 (key
, "port") == 0)
319 port
= g_hash_table_lookup (key_value_pairs
, key
);
320 else if (g_strcmp0 (key
, "family") == 0)
321 family
= g_hash_table_lookup (key_value_pairs
, key
);
326 G_IO_ERROR_INVALID_ARGUMENT
,
327 _("Unsupported key “%s” in address entry “%s”"),
336 port_num
= strtol (port
, &endp
, 10);
337 if ((*port
== '\0' || *endp
!= '\0') || port_num
< 0 || port_num
>= 65536)
341 G_IO_ERROR_INVALID_ARGUMENT
,
342 _("Error in address “%s” — the port attribute is malformed"),
348 if (family
!= NULL
&& !(g_strcmp0 (family
, "ipv4") == 0 || g_strcmp0 (family
, "ipv6") == 0))
352 G_IO_ERROR_INVALID_ARGUMENT
,
353 _("Error in address “%s” — the family attribute is malformed"),
360 /* TODO: validate host */
372 * g_dbus_is_supported_address:
374 * @error: Return location for error or %NULL.
376 * Like g_dbus_is_address() but also checks if the library supports the
377 * transports in @string and that key/value pairs for each transport
378 * are valid. See the specification of the
379 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
381 * Returns: %TRUE if @string is a valid D-Bus address that is
382 * supported by this library, %FALSE if @error is set.
387 g_dbus_is_supported_address (const gchar
*string
,
396 g_return_val_if_fail (string
!= NULL
, FALSE
);
397 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, FALSE
);
399 a
= g_strsplit (string
, ";", 0);
400 for (n
= 0; a
[n
] != NULL
; n
++)
402 gchar
*transport_name
;
403 GHashTable
*key_value_pairs
;
406 if (!_g_dbus_address_parse_entry (a
[n
],
413 if (g_strcmp0 (transport_name
, "unix") == 0)
414 supported
= is_valid_unix (a
[n
], key_value_pairs
, error
);
415 else if (g_strcmp0 (transport_name
, "tcp") == 0)
416 supported
= is_valid_tcp (a
[n
], key_value_pairs
, error
);
417 else if (g_strcmp0 (transport_name
, "nonce-tcp") == 0)
418 supported
= is_valid_nonce_tcp (a
[n
], key_value_pairs
, error
);
419 else if (g_strcmp0 (a
[n
], "autolaunch:") == 0)
422 g_free (transport_name
);
423 g_hash_table_unref (key_value_pairs
);
434 g_assert (ret
|| (!ret
&& (error
== NULL
|| *error
!= NULL
)));
440 _g_dbus_address_parse_entry (const gchar
*address_entry
,
441 gchar
**out_transport_name
,
442 GHashTable
**out_key_value_pairs
,
446 GHashTable
*key_value_pairs
;
447 gchar
*transport_name
;
454 transport_name
= NULL
;
455 key_value_pairs
= NULL
;
457 s
= strchr (address_entry
, ':');
462 G_IO_ERROR_INVALID_ARGUMENT
,
463 _("Address element “%s” does not contain a colon (:)"),
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
!= NULL
&& 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"),
491 key
= g_uri_unescape_segment (kv_pair
, s
, NULL
);
492 value
= g_uri_unescape_segment (s
+ 1, kv_pair
+ strlen (kv_pair
), NULL
);
493 if (key
== NULL
|| value
== NULL
)
497 G_IO_ERROR_INVALID_ARGUMENT
,
498 _("Error unescaping key or value in Key/Value pair %d, “%s”, in address element “%s”"),
506 g_hash_table_insert (key_value_pairs
, key
, value
);
512 g_strfreev (kv_pairs
);
515 if (out_transport_name
!= NULL
)
516 *out_transport_name
= transport_name
;
518 g_free (transport_name
);
519 if (out_key_value_pairs
!= NULL
)
520 *out_key_value_pairs
= key_value_pairs
;
521 else if (key_value_pairs
!= NULL
)
522 g_hash_table_unref (key_value_pairs
);
526 g_free (transport_name
);
527 if (key_value_pairs
!= NULL
)
528 g_hash_table_unref (key_value_pairs
);
533 /* ---------------------------------------------------------------------------------------------------- */
536 g_dbus_address_try_connect_one (const gchar
*address_entry
,
538 GCancellable
*cancellable
,
541 /* TODO: Declare an extension point called GDBusTransport (or similar)
542 * and move code below to extensions implementing said extension
543 * point. That way we can implement a D-Bus transport over X11 without
544 * making libgio link to libX11...
547 g_dbus_address_connect (const gchar
*address_entry
,
548 const gchar
*transport_name
,
549 GHashTable
*key_value_pairs
,
550 GCancellable
*cancellable
,
554 GSocketConnectable
*connectable
;
555 const gchar
*nonce_file
;
565 else if (g_strcmp0 (transport_name
, "unix") == 0)
568 const gchar
*abstract
;
569 path
= g_hash_table_lookup (key_value_pairs
, "path");
570 abstract
= g_hash_table_lookup (key_value_pairs
, "abstract");
571 if ((path
== NULL
&& abstract
== NULL
) || (path
!= NULL
&& abstract
!= NULL
))
575 G_IO_ERROR_INVALID_ARGUMENT
,
576 _("Error in address “%s” — the unix transport requires exactly one of the "
577 "keys “path” or “abstract” to be set"),
580 else if (path
!= NULL
)
582 connectable
= G_SOCKET_CONNECTABLE (g_unix_socket_address_new (path
));
584 else if (abstract
!= NULL
)
586 connectable
= G_SOCKET_CONNECTABLE (g_unix_socket_address_new_with_type (abstract
,
588 G_UNIX_SOCKET_ADDRESS_ABSTRACT
));
592 g_assert_not_reached ();
596 else if (g_strcmp0 (transport_name
, "tcp") == 0 || g_strcmp0 (transport_name
, "nonce-tcp") == 0)
604 is_nonce
= (g_strcmp0 (transport_name
, "nonce-tcp") == 0);
606 host
= g_hash_table_lookup (key_value_pairs
, "host");
611 G_IO_ERROR_INVALID_ARGUMENT
,
612 _("Error in address “%s” — the host attribute is missing or malformed"),
617 s
= g_hash_table_lookup (key_value_pairs
, "port");
620 port
= strtol (s
, &endp
, 10);
621 if ((*s
== '\0' || *endp
!= '\0') || port
< 0 || port
>= 65536)
625 G_IO_ERROR_INVALID_ARGUMENT
,
626 _("Error in address “%s” — the port attribute is missing or malformed"),
634 nonce_file
= g_hash_table_lookup (key_value_pairs
, "noncefile");
635 if (nonce_file
== NULL
)
639 G_IO_ERROR_INVALID_ARGUMENT
,
640 _("Error in address “%s” — the noncefile attribute is missing or malformed"),
646 /* TODO: deal with family key/value-pair */
647 connectable
= g_network_address_new (host
, port
);
649 else if (g_strcmp0 (address_entry
, "autolaunch:") == 0)
651 gchar
*autolaunch_address
;
652 autolaunch_address
= get_session_address_dbus_launch (error
);
653 if (autolaunch_address
!= NULL
)
655 ret
= g_dbus_address_try_connect_one (autolaunch_address
, NULL
, cancellable
, error
);
656 g_free (autolaunch_address
);
661 g_prefix_error (error
, _("Error auto-launching: "));
668 G_IO_ERROR_INVALID_ARGUMENT
,
669 _("Unknown or unsupported transport “%s” for address “%s”"),
674 if (connectable
!= NULL
)
676 GSocketClient
*client
;
677 GSocketConnection
*connection
;
679 g_assert (ret
== NULL
);
680 client
= g_socket_client_new ();
682 /* Disable proxy support to prevent a deadlock on startup, since loading a
683 * proxy resolver causes the GIO modules to be loaded, and there will
684 * almost certainly be one of them which then tries to use GDBus.
685 * See: https://bugzilla.gnome.org/show_bug.cgi?id=792499 */
686 g_socket_client_set_enable_proxy (client
, FALSE
);
688 connection
= g_socket_client_connect (client
,
692 g_object_unref (connectable
);
693 g_object_unref (client
);
694 if (connection
== NULL
)
697 ret
= G_IO_STREAM (connection
);
699 if (nonce_file
!= NULL
)
701 gchar nonce_contents
[16 + 1];
702 size_t num_bytes_read
;
706 /* be careful to read only 16 bytes - we also check that the file is only 16 bytes long */
707 f
= fopen (nonce_file
, "rb");
713 G_IO_ERROR_INVALID_ARGUMENT
,
714 _("Error opening nonce file “%s”: %s"),
717 g_object_unref (ret
);
721 num_bytes_read
= fread (nonce_contents
,
726 if (num_bytes_read
!= 16)
728 if (num_bytes_read
== 0)
732 G_IO_ERROR_INVALID_ARGUMENT
,
733 _("Error reading from nonce file “%s”: %s"),
741 G_IO_ERROR_INVALID_ARGUMENT
,
742 _("Error reading from nonce file “%s”, expected 16 bytes, got %d"),
744 (gint
) num_bytes_read
);
746 g_object_unref (ret
);
753 if (!g_output_stream_write_all (g_io_stream_get_output_stream (ret
),
760 g_prefix_error (error
, _("Error writing contents of nonce file “%s” to stream:"), nonce_file
);
761 g_object_unref (ret
);
774 g_dbus_address_try_connect_one (const gchar
*address_entry
,
776 GCancellable
*cancellable
,
780 GHashTable
*key_value_pairs
;
781 gchar
*transport_name
;
785 transport_name
= NULL
;
786 key_value_pairs
= NULL
;
788 if (!_g_dbus_address_parse_entry (address_entry
,
794 ret
= g_dbus_address_connect (address_entry
,
802 guid
= g_hash_table_lookup (key_value_pairs
, "guid");
803 if (guid
!= NULL
&& out_guid
!= NULL
)
804 *out_guid
= g_strdup (guid
);
807 g_free (transport_name
);
808 if (key_value_pairs
!= NULL
)
809 g_hash_table_unref (key_value_pairs
);
814 /* ---------------------------------------------------------------------------------------------------- */
822 get_stream_data_free (GetStreamData
*data
)
824 g_free (data
->address
);
830 get_stream_thread_func (GTask
*task
,
831 gpointer source_object
,
833 GCancellable
*cancellable
)
835 GetStreamData
*data
= task_data
;
837 GError
*error
= NULL
;
839 stream
= g_dbus_address_get_stream_sync (data
->address
,
844 g_task_return_pointer (task
, stream
, g_object_unref
);
846 g_task_return_error (task
, error
);
850 * g_dbus_address_get_stream:
851 * @address: A valid D-Bus address.
852 * @cancellable: (nullable): A #GCancellable or %NULL.
853 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
854 * @user_data: Data to pass to @callback.
856 * Asynchronously connects to an endpoint specified by @address and
857 * sets up the connection so it is in a state to run the client-side
858 * of the D-Bus authentication conversation. @address must be in the
859 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
861 * When the operation is finished, @callback will be invoked. You can
862 * then call g_dbus_address_get_stream_finish() to get the result of
865 * This is an asynchronous failable function. See
866 * g_dbus_address_get_stream_sync() for the synchronous version.
871 g_dbus_address_get_stream (const gchar
*address
,
872 GCancellable
*cancellable
,
873 GAsyncReadyCallback callback
,
879 g_return_if_fail (address
!= NULL
);
881 data
= g_new0 (GetStreamData
, 1);
882 data
->address
= g_strdup (address
);
884 task
= g_task_new (NULL
, cancellable
, callback
, user_data
);
885 g_task_set_source_tag (task
, g_dbus_address_get_stream
);
886 g_task_set_task_data (task
, data
, (GDestroyNotify
) get_stream_data_free
);
887 g_task_run_in_thread (task
, get_stream_thread_func
);
888 g_object_unref (task
);
892 * g_dbus_address_get_stream_finish:
893 * @res: A #GAsyncResult obtained from the GAsyncReadyCallback passed to g_dbus_address_get_stream().
894 * @out_guid: (optional) (out): %NULL or return location to store the GUID extracted from @address, if any.
895 * @error: Return location for error or %NULL.
897 * Finishes an operation started with g_dbus_address_get_stream().
899 * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
904 g_dbus_address_get_stream_finish (GAsyncResult
*res
,
912 g_return_val_if_fail (g_task_is_valid (res
, NULL
), NULL
);
913 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, NULL
);
916 ret
= g_task_propagate_pointer (task
, error
);
918 if (ret
!= NULL
&& out_guid
!= NULL
)
920 data
= g_task_get_task_data (task
);
921 *out_guid
= data
->guid
;
929 * g_dbus_address_get_stream_sync:
930 * @address: A valid D-Bus address.
931 * @out_guid: (optional) (out): %NULL or return location to store the GUID extracted from @address, if any.
932 * @cancellable: (nullable): A #GCancellable or %NULL.
933 * @error: Return location for error or %NULL.
935 * Synchronously connects to an endpoint specified by @address and
936 * sets up the connection so it is in a state to run the client-side
937 * of the D-Bus authentication conversation. @address must be in the
938 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
940 * This is a synchronous failable function. See
941 * g_dbus_address_get_stream() for the asynchronous version.
943 * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
948 g_dbus_address_get_stream_sync (const gchar
*address
,
950 GCancellable
*cancellable
,
958 g_return_val_if_fail (address
!= NULL
, NULL
);
959 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, NULL
);
964 addr_array
= g_strsplit (address
, ";", 0);
965 if (addr_array
!= NULL
&& addr_array
[0] == NULL
)
967 last_error
= g_error_new_literal (G_IO_ERROR
,
968 G_IO_ERROR_INVALID_ARGUMENT
,
969 _("The given address is empty"));
973 for (n
= 0; addr_array
!= NULL
&& addr_array
[n
] != NULL
; n
++)
975 const gchar
*addr
= addr_array
[n
];
979 ret
= g_dbus_address_try_connect_one (addr
,
989 g_assert (this_error
!= NULL
);
990 if (last_error
!= NULL
)
991 g_error_free (last_error
);
992 last_error
= this_error
;
999 if (last_error
!= NULL
)
1000 g_error_free (last_error
);
1004 g_assert (last_error
!= NULL
);
1005 g_propagate_error (error
, last_error
);
1008 g_strfreev (addr_array
);
1012 /* ---------------------------------------------------------------------------------------------------- */
1015 * Return the address of XDG_RUNTIME_DIR/bus if it exists, belongs to
1016 * us, and is a socket, and we are on Unix.
1019 get_session_address_xdg (void)
1027 bus
= g_build_filename (g_get_user_runtime_dir (), "bus", NULL
);
1029 /* if ENOENT, EPERM, etc., quietly don't use it */
1030 if (g_stat (bus
, &buf
) < 0)
1033 /* if it isn't ours, we have incorrectly inherited someone else's
1034 * XDG_RUNTIME_DIR; silently don't use it
1036 if (buf
.st_uid
!= geteuid ())
1039 /* if it isn't a socket, silently don't use it */
1040 if ((buf
.st_mode
& S_IFMT
) != S_IFSOCK
)
1043 tmp
= g_dbus_address_escape_value (bus
);
1044 ret
= g_strconcat ("unix:path=", tmp
, NULL
);
1055 /* ---------------------------------------------------------------------------------------------------- */
1059 get_session_address_dbus_launch (GError
**error
)
1063 gchar
*command_line
;
1064 gchar
*launch_stdout
;
1065 gchar
*launch_stderr
;
1067 gchar
*old_dbus_verbose
;
1068 gboolean restore_dbus_verbose
;
1072 command_line
= NULL
;
1073 launch_stdout
= NULL
;
1074 launch_stderr
= NULL
;
1075 restore_dbus_verbose
= FALSE
;
1076 old_dbus_verbose
= NULL
;
1078 /* Don't run binaries as root if we're setuid. */
1079 if (GLIB_PRIVATE_CALL (g_check_setuid
) ())
1081 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_FAILED
,
1082 _("Cannot spawn a message bus when setuid"));
1086 machine_id
= _g_dbus_get_machine_id (error
);
1087 if (machine_id
== NULL
)
1089 g_prefix_error (error
, _("Cannot spawn a message bus without a machine-id: "));
1093 if (g_getenv ("DISPLAY") == NULL
)
1095 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_FAILED
,
1096 _("Cannot autolaunch D-Bus without X11 $DISPLAY"));
1100 /* We're using private libdbus facilities here. When everything
1101 * (X11, Mac OS X, Windows) is spec'ed out correctly (not even the
1102 * X11 property is correctly documented right now) we should
1103 * consider using the spec instead of dbus-launch.
1105 * --autolaunch=MACHINEID
1106 * This option implies that dbus-launch should scan for a previ‐
1107 * ously-started session and reuse the values found there. If no
1108 * session is found, it will start a new session. The --exit-with-
1109 * session option is implied if --autolaunch is given. This option
1110 * is for the exclusive use of libdbus, you do not want to use it
1111 * manually. It may change in the future.
1114 /* TODO: maybe provide a variable for where to look for the dbus-launch binary? */
1115 command_line
= g_strdup_printf ("dbus-launch --autolaunch=%s --binary-syntax --close-stderr", machine_id
);
1117 if (G_UNLIKELY (_g_dbus_debug_address ()))
1119 _g_dbus_debug_print_lock ();
1120 g_print ("GDBus-debug:Address: Running '%s' to get bus address (possibly autolaunching)\n", command_line
);
1121 old_dbus_verbose
= g_strdup (g_getenv ("DBUS_VERBOSE"));
1122 restore_dbus_verbose
= TRUE
;
1123 g_setenv ("DBUS_VERBOSE", "1", TRUE
);
1124 _g_dbus_debug_print_unlock ();
1127 if (!g_spawn_command_line_sync (command_line
,
1136 if (!g_spawn_check_exit_status (exit_status
, error
))
1138 g_prefix_error (error
, _("Error spawning command line “%s”: "), command_line
);
1142 /* From the dbus-launch(1) man page:
1144 * --binary-syntax Write to stdout a nul-terminated bus address,
1145 * then the bus PID as a binary integer of size sizeof(pid_t),
1146 * then the bus X window ID as a binary integer of size
1147 * sizeof(long). Integers are in the machine's byte order, not
1148 * network byte order or any other canonical byte order.
1150 ret
= g_strdup (launch_stdout
);
1153 if (G_UNLIKELY (_g_dbus_debug_address ()))
1156 _g_dbus_debug_print_lock ();
1157 g_print ("GDBus-debug:Address: dbus-launch output:");
1158 if (launch_stdout
!= NULL
)
1160 s
= _g_dbus_hexdump (launch_stdout
, strlen (launch_stdout
) + 1 + sizeof (pid_t
) + sizeof (long), 2);
1161 g_print ("\n%s", s
);
1166 g_print (" (none)\n");
1168 g_print ("GDBus-debug:Address: dbus-launch stderr output:");
1169 if (launch_stderr
!= NULL
)
1170 g_print ("\n%s", launch_stderr
);
1172 g_print (" (none)\n");
1173 _g_dbus_debug_print_unlock ();
1176 g_free (machine_id
);
1177 g_free (command_line
);
1178 g_free (launch_stdout
);
1179 g_free (launch_stderr
);
1180 if (G_UNLIKELY (restore_dbus_verbose
))
1182 if (old_dbus_verbose
!= NULL
)
1183 g_setenv ("DBUS_VERBOSE", old_dbus_verbose
, TRUE
);
1185 g_unsetenv ("DBUS_VERBOSE");
1187 g_free (old_dbus_verbose
);
1191 /* end of G_OS_UNIX case */
1192 #elif defined(G_OS_WIN32)
1194 #define DBUS_DAEMON_ADDRESS_INFO "DBusDaemonAddressInfo"
1195 #define DBUS_DAEMON_MUTEX "DBusDaemonMutex"
1196 #define UNIQUE_DBUS_INIT_MUTEX "UniqueDBusInitMutex"
1197 #define DBUS_AUTOLAUNCH_MUTEX "DBusAutolaunchMutex"
1200 release_mutex (HANDLE mutex
)
1202 ReleaseMutex (mutex
);
1203 CloseHandle (mutex
);
1207 acquire_mutex (const char *mutexname
)
1212 mutex
= CreateMutexA (NULL
, FALSE
, mutexname
);
1216 res
= WaitForSingleObject (mutex
, INFINITE
);
1219 case WAIT_ABANDONED
:
1220 release_mutex (mutex
);
1231 is_mutex_owned (const char *mutexname
)
1234 gboolean res
= FALSE
;
1236 mutex
= CreateMutexA (NULL
, FALSE
, mutexname
);
1237 if (WaitForSingleObject (mutex
, 10) == WAIT_TIMEOUT
)
1240 ReleaseMutex (mutex
);
1241 CloseHandle (mutex
);
1247 read_shm (const char *shm_name
)
1256 for (i
= 0; i
< 20; i
++)
1258 shared_mem
= OpenFileMappingA (FILE_MAP_READ
, FALSE
, shm_name
);
1259 if (shared_mem
!= 0)
1264 if (shared_mem
!= 0)
1266 shared_data
= MapViewOfFile (shared_mem
, FILE_MAP_READ
, 0, 0, 0);
1267 if (shared_data
!= NULL
)
1269 res
= g_strdup (shared_data
);
1270 UnmapViewOfFile (shared_data
);
1272 CloseHandle (shared_mem
);
1279 set_shm (const char *shm_name
, const char *value
)
1284 shared_mem
= CreateFileMappingA (INVALID_HANDLE_VALUE
, NULL
, PAGE_READWRITE
,
1285 0, strlen (value
) + 1, shm_name
);
1286 if (shared_mem
== 0)
1289 shared_data
= MapViewOfFile (shared_mem
, FILE_MAP_WRITE
, 0, 0, 0 );
1290 if (shared_data
== NULL
)
1293 strcpy (shared_data
, value
);
1295 UnmapViewOfFile (shared_data
);
1300 /* These keep state between publish_session_bus and unpublish_session_bus */
1301 static HANDLE published_daemon_mutex
;
1302 static HANDLE published_shared_mem
;
1305 publish_session_bus (const char *address
)
1309 init_mutex
= acquire_mutex (UNIQUE_DBUS_INIT_MUTEX
);
1311 published_daemon_mutex
= CreateMutexA (NULL
, FALSE
, DBUS_DAEMON_MUTEX
);
1312 if (WaitForSingleObject (published_daemon_mutex
, 10 ) != WAIT_OBJECT_0
)
1314 release_mutex (init_mutex
);
1315 CloseHandle (published_daemon_mutex
);
1316 published_daemon_mutex
= NULL
;
1320 published_shared_mem
= set_shm (DBUS_DAEMON_ADDRESS_INFO
, address
);
1321 if (!published_shared_mem
)
1323 release_mutex (init_mutex
);
1324 CloseHandle (published_daemon_mutex
);
1325 published_daemon_mutex
= NULL
;
1329 release_mutex (init_mutex
);
1334 unpublish_session_bus (void)
1338 init_mutex
= acquire_mutex (UNIQUE_DBUS_INIT_MUTEX
);
1340 CloseHandle (published_shared_mem
);
1341 published_shared_mem
= NULL
;
1343 release_mutex (published_daemon_mutex
);
1344 published_daemon_mutex
= NULL
;
1346 release_mutex (init_mutex
);
1350 wait_console_window (void)
1352 FILE *console
= fopen ("CONOUT$", "w");
1354 SetConsoleTitleW (L
"gdbus-daemon output. Type any character to close this window.");
1355 fprintf (console
, _("(Type any character to close this window)\n"));
1361 open_console_window (void)
1363 if (((HANDLE
) _get_osfhandle (fileno (stdout
)) == INVALID_HANDLE_VALUE
||
1364 (HANDLE
) _get_osfhandle (fileno (stderr
)) == INVALID_HANDLE_VALUE
) && AllocConsole ())
1366 if ((HANDLE
) _get_osfhandle (fileno (stdout
)) == INVALID_HANDLE_VALUE
)
1367 freopen ("CONOUT$", "w", stdout
);
1369 if ((HANDLE
) _get_osfhandle (fileno (stderr
)) == INVALID_HANDLE_VALUE
)
1370 freopen ("CONOUT$", "w", stderr
);
1372 SetConsoleTitleW (L
"gdbus-daemon debug output.");
1374 atexit (wait_console_window
);
1379 idle_timeout_cb (GDBusDaemon
*daemon
, gpointer user_data
)
1381 GMainLoop
*loop
= user_data
;
1382 g_main_loop_quit (loop
);
1385 /* Satisfies STARTF_FORCEONFEEDBACK */
1387 turn_off_the_starting_cursor (void)
1392 PostQuitMessage (0);
1394 while ((bRet
= GetMessage (&msg
, 0, 0, 0)) != 0)
1399 TranslateMessage (&msg
);
1400 DispatchMessage (&msg
);
1404 __declspec(dllexport
) void CALLBACK
g_win32_run_session_bus (HWND hwnd
, HINSTANCE hinst
, char *cmdline
, int nCmdShow
);
1406 __declspec(dllexport
) void CALLBACK
1407 g_win32_run_session_bus (HWND hwnd
, HINSTANCE hinst
, char *cmdline
, int nCmdShow
)
1409 GDBusDaemon
*daemon
;
1411 const char *address
;
1412 GError
*error
= NULL
;
1414 turn_off_the_starting_cursor ();
1416 if (g_getenv ("GDBUS_DAEMON_DEBUG") != NULL
)
1417 open_console_window ();
1419 loop
= g_main_loop_new (NULL
, FALSE
);
1421 address
= "nonce-tcp:";
1422 daemon
= _g_dbus_daemon_new (address
, NULL
, &error
);
1425 g_printerr ("Can't init bus: %s\n", error
->message
);
1426 g_error_free (error
);
1430 g_signal_connect (daemon
, "idle-timeout", G_CALLBACK (idle_timeout_cb
), loop
);
1432 if (publish_session_bus (_g_dbus_daemon_get_address (daemon
)))
1434 g_main_loop_run (loop
);
1436 unpublish_session_bus ();
1439 g_main_loop_unref (loop
);
1440 g_object_unref (daemon
);
1444 get_session_address_dbus_launch (GError
**error
)
1446 HANDLE autolaunch_mutex
, init_mutex
;
1447 char *address
= NULL
;
1448 wchar_t gio_path
[MAX_PATH
+1+200];
1450 autolaunch_mutex
= acquire_mutex (DBUS_AUTOLAUNCH_MUTEX
);
1452 init_mutex
= acquire_mutex (UNIQUE_DBUS_INIT_MUTEX
);
1454 if (is_mutex_owned (DBUS_DAEMON_MUTEX
))
1455 address
= read_shm (DBUS_DAEMON_ADDRESS_INFO
);
1457 release_mutex (init_mutex
);
1459 if (address
== NULL
)
1461 gio_path
[MAX_PATH
] = 0;
1462 if (GetModuleFileNameW (_g_io_win32_get_module (), gio_path
, MAX_PATH
))
1464 PROCESS_INFORMATION pi
= { 0 };
1465 STARTUPINFOW si
= { 0 };
1467 wchar_t gio_path_short
[MAX_PATH
];
1468 wchar_t rundll_path
[MAX_PATH
*2];
1469 wchar_t args
[MAX_PATH
*4];
1471 GetShortPathNameW (gio_path
, gio_path_short
, MAX_PATH
);
1473 GetWindowsDirectoryW (rundll_path
, MAX_PATH
);
1474 wcscat (rundll_path
, L
"\\rundll32.exe");
1475 if (GetFileAttributesW (rundll_path
) == INVALID_FILE_ATTRIBUTES
)
1477 GetSystemDirectoryW (rundll_path
, MAX_PATH
);
1478 wcscat (rundll_path
, L
"\\rundll32.exe");
1481 wcscpy (args
, L
"\"");
1482 wcscat (args
, rundll_path
);
1483 wcscat (args
, L
"\" ");
1484 wcscat (args
, gio_path_short
);
1485 #if defined(_WIN64) || defined(_M_X64) || defined(_M_AMD64)
1486 wcscat (args
, L
",g_win32_run_session_bus");
1487 #elif defined (_MSC_VER)
1488 wcscat (args
, L
",_g_win32_run_session_bus@16");
1490 wcscat (args
, L
",g_win32_run_session_bus@16");
1493 res
= CreateProcessW (rundll_path
, args
,
1495 NORMAL_PRIORITY_CLASS
| CREATE_NO_WINDOW
| DETACHED_PROCESS
,
1496 0, NULL
/* TODO: Should be root */,
1499 address
= read_shm (DBUS_DAEMON_ADDRESS_INFO
);
1503 release_mutex (autolaunch_mutex
);
1505 if (address
== NULL
)
1509 _("Session dbus not running, and autolaunch failed"));
1513 #else /* neither G_OS_UNIX nor G_OS_WIN32 */
1515 get_session_address_dbus_launch (GError
**error
)
1520 _("Cannot determine session bus address (not implemented for this OS)"));
1523 #endif /* neither G_OS_UNIX nor G_OS_WIN32 */
1525 /* ---------------------------------------------------------------------------------------------------- */
1528 get_session_address_platform_specific (GError
**error
)
1532 /* Use XDG_RUNTIME_DIR/bus if it exists and is suitable. This is appropriate
1533 * for systems using the "a session is a user-session" model described in
1534 * <http://lists.freedesktop.org/archives/dbus/2015-January/016522.html>,
1535 * and implemented in dbus >= 1.9.14 and sd-bus.
1537 * On systems following the more traditional "a session is a login-session"
1538 * model, this will fail and we'll fall through to X11 autolaunching
1539 * (dbus-launch) below.
1541 ret
= get_session_address_xdg ();
1546 /* TODO (#694472): try launchd on OS X, like
1547 * _dbus_lookup_session_address_launchd() does, since
1548 * 'dbus-launch --autolaunch' probably won't work there
1551 /* As a last resort, try the "autolaunch:" transport. On Unix this means
1552 * X11 autolaunching; on Windows this means a different autolaunching
1553 * mechanism based on shared memory.
1555 return get_session_address_dbus_launch (error
);
1558 /* ---------------------------------------------------------------------------------------------------- */
1561 * g_dbus_address_get_for_bus_sync:
1562 * @bus_type: a #GBusType
1563 * @cancellable: (nullable): a #GCancellable or %NULL
1564 * @error: return location for error or %NULL
1566 * Synchronously looks up the D-Bus address for the well-known message
1567 * bus instance specified by @bus_type. This may involve using various
1568 * platform specific mechanisms.
1570 * The returned address will be in the
1571 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
1573 * Returns: a valid D-Bus address string for @bus_type or %NULL if
1579 g_dbus_address_get_for_bus_sync (GBusType bus_type
,
1580 GCancellable
*cancellable
,
1583 gchar
*ret
, *s
= NULL
;
1584 const gchar
*starter_bus
;
1585 GError
*local_error
;
1587 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, NULL
);
1592 if (G_UNLIKELY (_g_dbus_debug_address ()))
1595 _g_dbus_debug_print_lock ();
1596 s
= _g_dbus_enum_to_string (G_TYPE_BUS_TYPE
, bus_type
);
1597 g_print ("GDBus-debug:Address: In g_dbus_address_get_for_bus_sync() for bus type '%s'\n",
1600 for (n
= 0; n
< 3; n
++)
1606 case 0: k
= "DBUS_SESSION_BUS_ADDRESS"; break;
1607 case 1: k
= "DBUS_SYSTEM_BUS_ADDRESS"; break;
1608 case 2: k
= "DBUS_STARTER_BUS_TYPE"; break;
1609 default: g_assert_not_reached ();
1612 g_print ("GDBus-debug:Address: env var %s", k
);
1614 g_print ("='%s'\n", v
);
1616 g_print (" is not set\n");
1618 _g_dbus_debug_print_unlock ();
1623 case G_BUS_TYPE_SYSTEM
:
1624 ret
= g_strdup (g_getenv ("DBUS_SYSTEM_BUS_ADDRESS"));
1627 ret
= g_strdup ("unix:path=/var/run/dbus/system_bus_socket");
1631 case G_BUS_TYPE_SESSION
:
1632 ret
= g_strdup (g_getenv ("DBUS_SESSION_BUS_ADDRESS"));
1635 ret
= get_session_address_platform_specific (&local_error
);
1639 case G_BUS_TYPE_STARTER
:
1640 starter_bus
= g_getenv ("DBUS_STARTER_BUS_TYPE");
1641 if (g_strcmp0 (starter_bus
, "session") == 0)
1643 ret
= g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SESSION
, cancellable
, &local_error
);
1646 else if (g_strcmp0 (starter_bus
, "system") == 0)
1648 ret
= g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SYSTEM
, cancellable
, &local_error
);
1653 if (starter_bus
!= NULL
)
1655 g_set_error (&local_error
,
1658 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
1659 " — unknown value “%s”"),
1664 g_set_error_literal (&local_error
,
1667 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
1668 "variable is not set"));
1674 g_set_error (&local_error
,
1677 _("Unknown bus type %d"),
1683 if (G_UNLIKELY (_g_dbus_debug_address ()))
1685 _g_dbus_debug_print_lock ();
1686 s
= _g_dbus_enum_to_string (G_TYPE_BUS_TYPE
, bus_type
);
1689 g_print ("GDBus-debug:Address: Returning address '%s' for bus type '%s'\n",
1694 g_print ("GDBus-debug:Address: Cannot look-up address bus type '%s': %s\n",
1695 s
, local_error
? local_error
->message
: "");
1698 _g_dbus_debug_print_unlock ();
1701 if (local_error
!= NULL
)
1702 g_propagate_error (error
, local_error
);
1708 * g_dbus_address_escape_value:
1709 * @string: an unescaped string to be included in a D-Bus address
1710 * as the value in a key-value pair
1712 * Escape @string so it can appear in a D-Bus address as the value
1713 * part of a key-value pair.
1715 * For instance, if @string is `/run/bus-for-:0`,
1716 * this function would return `/run/bus-for-%3A0`,
1717 * which could be used in a D-Bus address like
1718 * `unix:nonce-tcp:host=127.0.0.1,port=42,noncefile=/run/bus-for-%3A0`.
1720 * Returns: (transfer full): a copy of @string with all
1721 * non-optionally-escaped bytes escaped
1726 g_dbus_address_escape_value (const gchar
*string
)
1731 g_return_val_if_fail (string
!= NULL
, NULL
);
1733 /* There will often not be anything needing escaping at all. */
1734 s
= g_string_sized_new (strlen (string
));
1736 /* D-Bus address escaping is mostly the same as URI escaping... */
1737 g_string_append_uri_escaped (s
, string
, "\\/", FALSE
);
1739 /* ... but '~' is an unreserved character in URIs, but a
1740 * non-optionally-escaped character in D-Bus addresses. */
1741 for (i
= 0; i
< s
->len
; i
++)
1743 if (G_UNLIKELY (s
->str
[i
] == '~'))
1746 g_string_insert (s
, i
+ 1, "7E");
1751 return g_string_free (s
, FALSE
);