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 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 [D-Bus specification](http://dbus.freedesktop.org/doc/dbus-specification.html\#addresses).
70 static gchar
*get_session_address_platform_specific (GError
**error
);
71 static gchar
*get_session_address_dbus_launch (GError
**error
);
73 /* ---------------------------------------------------------------------------------------------------- */
79 * Checks if @string is a D-Bus address.
81 * This doesn't check if @string is actually supported by #GDBusServer
82 * or #GDBusConnection - use g_dbus_is_supported_address() to do more
85 * Returns: %TRUE if @string is a valid D-Bus address, %FALSE otherwise.
90 g_dbus_is_address (const gchar
*string
)
98 g_return_val_if_fail (string
!= NULL
, FALSE
);
100 a
= g_strsplit (string
, ";", 0);
104 for (n
= 0; a
[n
] != NULL
; n
++)
106 if (!_g_dbus_address_parse_entry (a
[n
],
121 is_valid_unix (const gchar
*address_entry
,
122 GHashTable
*key_value_pairs
,
130 const gchar
*abstract
;
138 keys
= g_hash_table_get_keys (key_value_pairs
);
139 for (l
= keys
; l
!= NULL
; l
= l
->next
)
141 const gchar
*key
= l
->data
;
142 if (g_strcmp0 (key
, "path") == 0)
143 path
= g_hash_table_lookup (key_value_pairs
, key
);
144 else if (g_strcmp0 (key
, "tmpdir") == 0)
145 tmpdir
= g_hash_table_lookup (key_value_pairs
, key
);
146 else if (g_strcmp0 (key
, "abstract") == 0)
147 abstract
= g_hash_table_lookup (key_value_pairs
, key
);
152 G_IO_ERROR_INVALID_ARGUMENT
,
153 _("Unsupported key '%s' in address entry '%s'"),
162 if (tmpdir
!= NULL
|| abstract
!= NULL
)
165 else if (tmpdir
!= NULL
)
167 if (path
!= NULL
|| abstract
!= NULL
)
170 else if (abstract
!= NULL
)
172 if (path
!= NULL
|| tmpdir
!= NULL
)
179 G_IO_ERROR_INVALID_ARGUMENT
,
180 _("Address '%s' is invalid (need exactly one of path, tmpdir or abstract keys)"),
192 G_IO_ERROR_INVALID_ARGUMENT
,
193 _("Meaningless key/value pair combination in address entry '%s'"),
203 is_valid_nonce_tcp (const gchar
*address_entry
,
204 GHashTable
*key_value_pairs
,
213 const gchar
*nonce_file
;
224 keys
= g_hash_table_get_keys (key_value_pairs
);
225 for (l
= keys
; l
!= NULL
; l
= l
->next
)
227 const gchar
*key
= l
->data
;
228 if (g_strcmp0 (key
, "host") == 0)
229 host
= g_hash_table_lookup (key_value_pairs
, key
);
230 else if (g_strcmp0 (key
, "port") == 0)
231 port
= g_hash_table_lookup (key_value_pairs
, key
);
232 else if (g_strcmp0 (key
, "family") == 0)
233 family
= g_hash_table_lookup (key_value_pairs
, key
);
234 else if (g_strcmp0 (key
, "noncefile") == 0)
235 nonce_file
= g_hash_table_lookup (key_value_pairs
, key
);
240 G_IO_ERROR_INVALID_ARGUMENT
,
241 _("Unsupported key '%s' in address entry '%s'"),
250 port_num
= strtol (port
, &endp
, 10);
251 if ((*port
== '\0' || *endp
!= '\0') || port_num
< 0 || port_num
>= 65536)
255 G_IO_ERROR_INVALID_ARGUMENT
,
256 _("Error in address '%s' - the port attribute is malformed"),
262 if (family
!= NULL
&& !(g_strcmp0 (family
, "ipv4") == 0 || g_strcmp0 (family
, "ipv6") == 0))
266 G_IO_ERROR_INVALID_ARGUMENT
,
267 _("Error in address '%s' - the family attribute is malformed"),
274 /* TODO: validate host */
277 nonce_file
= nonce_file
; /* To avoid -Wunused-but-set-variable */
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
);
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 port attribute is malformed"),
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 family attribute is malformed"),
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 suppors the
372 * transports in @string and that key/value pairs for each transport
375 * Returns: %TRUE if @string is a valid D-Bus address that is
376 * supported by this library, %FALSE if @error is set.
381 g_dbus_is_supported_address (const gchar
*string
,
390 g_return_val_if_fail (string
!= NULL
, FALSE
);
391 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, FALSE
);
393 a
= g_strsplit (string
, ";", 0);
394 for (n
= 0; a
[n
] != NULL
; n
++)
396 gchar
*transport_name
;
397 GHashTable
*key_value_pairs
;
400 if (!_g_dbus_address_parse_entry (a
[n
],
407 if (g_strcmp0 (transport_name
, "unix") == 0)
408 supported
= is_valid_unix (a
[n
], key_value_pairs
, error
);
409 else if (g_strcmp0 (transport_name
, "tcp") == 0)
410 supported
= is_valid_tcp (a
[n
], key_value_pairs
, error
);
411 else if (g_strcmp0 (transport_name
, "nonce-tcp") == 0)
412 supported
= is_valid_nonce_tcp (a
[n
], key_value_pairs
, error
);
413 else if (g_strcmp0 (a
[n
], "autolaunch:") == 0)
416 g_free (transport_name
);
417 g_hash_table_unref (key_value_pairs
);
428 g_assert (ret
|| (!ret
&& (error
== NULL
|| *error
!= NULL
)));
434 _g_dbus_address_parse_entry (const gchar
*address_entry
,
435 gchar
**out_transport_name
,
436 GHashTable
**out_key_value_pairs
,
440 GHashTable
*key_value_pairs
;
441 gchar
*transport_name
;
448 transport_name
= NULL
;
449 key_value_pairs
= NULL
;
451 s
= strchr (address_entry
, ':');
456 G_IO_ERROR_INVALID_ARGUMENT
,
457 _("Address element '%s' does not contain a colon (:)"),
462 transport_name
= g_strndup (address_entry
, s
- address_entry
);
463 key_value_pairs
= g_hash_table_new_full (g_str_hash
, g_str_equal
, g_free
, g_free
);
465 kv_pairs
= g_strsplit (s
+ 1, ",", 0);
466 for (n
= 0; kv_pairs
!= NULL
&& kv_pairs
[n
] != NULL
; n
++)
468 const gchar
*kv_pair
= kv_pairs
[n
];
472 s
= strchr (kv_pair
, '=');
477 G_IO_ERROR_INVALID_ARGUMENT
,
478 _("Key/Value pair %d, '%s', in address element '%s' does not contain an equal sign"),
485 key
= g_uri_unescape_segment (kv_pair
, s
, NULL
);
486 value
= g_uri_unescape_segment (s
+ 1, kv_pair
+ strlen (kv_pair
), NULL
);
487 if (key
== NULL
|| value
== NULL
)
491 G_IO_ERROR_INVALID_ARGUMENT
,
492 _("Error unescaping key or value in Key/Value pair %d, '%s', in address element '%s'"),
500 g_hash_table_insert (key_value_pairs
, key
, value
);
506 g_strfreev (kv_pairs
);
509 if (out_transport_name
!= NULL
)
510 *out_transport_name
= transport_name
;
512 g_free (transport_name
);
513 if (out_key_value_pairs
!= NULL
)
514 *out_key_value_pairs
= key_value_pairs
;
515 else if (key_value_pairs
!= NULL
)
516 g_hash_table_unref (key_value_pairs
);
520 g_free (transport_name
);
521 if (key_value_pairs
!= NULL
)
522 g_hash_table_unref (key_value_pairs
);
527 /* ---------------------------------------------------------------------------------------------------- */
530 g_dbus_address_try_connect_one (const gchar
*address_entry
,
532 GCancellable
*cancellable
,
535 /* TODO: Declare an extension point called GDBusTransport (or similar)
536 * and move code below to extensions implementing said extension
537 * point. That way we can implement a D-Bus transport over X11 without
538 * making libgio link to libX11...
541 g_dbus_address_connect (const gchar
*address_entry
,
542 const gchar
*transport_name
,
543 GHashTable
*key_value_pairs
,
544 GCancellable
*cancellable
,
548 GSocketConnectable
*connectable
;
549 const gchar
*nonce_file
;
559 else if (g_strcmp0 (transport_name
, "unix") == 0)
562 const gchar
*abstract
;
563 path
= g_hash_table_lookup (key_value_pairs
, "path");
564 abstract
= g_hash_table_lookup (key_value_pairs
, "abstract");
565 if ((path
== NULL
&& abstract
== NULL
) || (path
!= NULL
&& abstract
!= NULL
))
569 G_IO_ERROR_INVALID_ARGUMENT
,
570 _("Error in address '%s' - the unix transport requires exactly one of the "
571 "keys 'path' or 'abstract' to be set"),
574 else if (path
!= NULL
)
576 connectable
= G_SOCKET_CONNECTABLE (g_unix_socket_address_new (path
));
578 else if (abstract
!= NULL
)
580 connectable
= G_SOCKET_CONNECTABLE (g_unix_socket_address_new_with_type (abstract
,
582 G_UNIX_SOCKET_ADDRESS_ABSTRACT
));
586 g_assert_not_reached ();
590 else if (g_strcmp0 (transport_name
, "tcp") == 0 || g_strcmp0 (transport_name
, "nonce-tcp") == 0)
598 is_nonce
= (g_strcmp0 (transport_name
, "nonce-tcp") == 0);
600 host
= g_hash_table_lookup (key_value_pairs
, "host");
605 G_IO_ERROR_INVALID_ARGUMENT
,
606 _("Error in address '%s' - the host attribute is missing or malformed"),
611 s
= g_hash_table_lookup (key_value_pairs
, "port");
614 port
= strtol (s
, &endp
, 10);
615 if ((*s
== '\0' || *endp
!= '\0') || port
< 0 || port
>= 65536)
619 G_IO_ERROR_INVALID_ARGUMENT
,
620 _("Error in address '%s' - the port attribute is missing or malformed"),
628 nonce_file
= g_hash_table_lookup (key_value_pairs
, "noncefile");
629 if (nonce_file
== NULL
)
633 G_IO_ERROR_INVALID_ARGUMENT
,
634 _("Error in address '%s' - the noncefile attribute is missing or malformed"),
640 /* TODO: deal with family key/value-pair */
641 connectable
= g_network_address_new (host
, port
);
643 else if (g_strcmp0 (address_entry
, "autolaunch:") == 0)
645 gchar
*autolaunch_address
;
646 autolaunch_address
= get_session_address_dbus_launch (error
);
647 if (autolaunch_address
!= NULL
)
649 ret
= g_dbus_address_try_connect_one (autolaunch_address
, NULL
, cancellable
, error
);
650 g_free (autolaunch_address
);
655 g_prefix_error (error
, _("Error auto-launching: "));
662 G_IO_ERROR_INVALID_ARGUMENT
,
663 _("Unknown or unsupported transport '%s' for address '%s'"),
668 if (connectable
!= NULL
)
670 GSocketClient
*client
;
671 GSocketConnection
*connection
;
673 g_assert (ret
== NULL
);
674 client
= g_socket_client_new ();
675 connection
= g_socket_client_connect (client
,
679 g_object_unref (connectable
);
680 g_object_unref (client
);
681 if (connection
== NULL
)
684 ret
= G_IO_STREAM (connection
);
686 if (nonce_file
!= NULL
)
688 gchar nonce_contents
[16 + 1];
689 size_t num_bytes_read
;
692 /* be careful to read only 16 bytes - we also check that the file is only 16 bytes long */
693 f
= fopen (nonce_file
, "rb");
698 G_IO_ERROR_INVALID_ARGUMENT
,
699 _("Error opening nonce file '%s': %s"),
702 g_object_unref (ret
);
706 num_bytes_read
= fread (nonce_contents
,
710 if (num_bytes_read
!= 16)
712 if (num_bytes_read
== 0)
716 G_IO_ERROR_INVALID_ARGUMENT
,
717 _("Error reading from nonce file '%s': %s"),
725 G_IO_ERROR_INVALID_ARGUMENT
,
726 _("Error reading from nonce file '%s', expected 16 bytes, got %d"),
728 (gint
) num_bytes_read
);
730 g_object_unref (ret
);
737 if (!g_output_stream_write_all (g_io_stream_get_output_stream (ret
),
744 g_prefix_error (error
, _("Error writing contents of nonce file '%s' to stream:"), nonce_file
);
745 g_object_unref (ret
);
758 g_dbus_address_try_connect_one (const gchar
*address_entry
,
760 GCancellable
*cancellable
,
764 GHashTable
*key_value_pairs
;
765 gchar
*transport_name
;
769 transport_name
= NULL
;
770 key_value_pairs
= NULL
;
772 if (!_g_dbus_address_parse_entry (address_entry
,
778 ret
= g_dbus_address_connect (address_entry
,
786 guid
= g_hash_table_lookup (key_value_pairs
, "guid");
787 if (guid
!= NULL
&& out_guid
!= NULL
)
788 *out_guid
= g_strdup (guid
);
791 g_free (transport_name
);
792 if (key_value_pairs
!= NULL
)
793 g_hash_table_unref (key_value_pairs
);
798 /* ---------------------------------------------------------------------------------------------------- */
806 get_stream_data_free (GetStreamData
*data
)
808 g_free (data
->address
);
814 get_stream_thread_func (GTask
*task
,
815 gpointer source_object
,
817 GCancellable
*cancellable
)
819 GetStreamData
*data
= task_data
;
821 GError
*error
= NULL
;
823 stream
= g_dbus_address_get_stream_sync (data
->address
,
828 g_task_return_pointer (task
, stream
, g_object_unref
);
830 g_task_return_error (task
, error
);
834 * g_dbus_address_get_stream:
835 * @address: A valid D-Bus address.
836 * @cancellable: (allow-none): A #GCancellable or %NULL.
837 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
838 * @user_data: Data to pass to @callback.
840 * Asynchronously connects to an endpoint specified by @address and
841 * sets up the connection so it is in a state to run the client-side
842 * of the D-Bus authentication conversation.
844 * When the operation is finished, @callback will be invoked. You can
845 * then call g_dbus_address_get_stream_finish() to get the result of
848 * This is an asynchronous failable function. See
849 * g_dbus_address_get_stream_sync() for the synchronous version.
854 g_dbus_address_get_stream (const gchar
*address
,
855 GCancellable
*cancellable
,
856 GAsyncReadyCallback callback
,
862 g_return_if_fail (address
!= NULL
);
864 data
= g_new0 (GetStreamData
, 1);
865 data
->address
= g_strdup (address
);
867 task
= g_task_new (NULL
, cancellable
, callback
, user_data
);
868 g_task_set_task_data (task
, data
, (GDestroyNotify
) get_stream_data_free
);
869 g_task_run_in_thread (task
, get_stream_thread_func
);
870 g_object_unref (task
);
874 * g_dbus_address_get_stream_finish:
875 * @res: A #GAsyncResult obtained from the GAsyncReadyCallback passed to g_dbus_address_get_stream().
876 * @out_guid: (optional) (out): %NULL or return location to store the GUID extracted from @address, if any.
877 * @error: Return location for error or %NULL.
879 * Finishes an operation started with g_dbus_address_get_stream().
881 * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
886 g_dbus_address_get_stream_finish (GAsyncResult
*res
,
894 g_return_val_if_fail (g_task_is_valid (res
, NULL
), NULL
);
895 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, NULL
);
898 ret
= g_task_propagate_pointer (task
, error
);
900 if (ret
!= NULL
&& out_guid
!= NULL
)
902 data
= g_task_get_task_data (task
);
903 *out_guid
= data
->guid
;
911 * g_dbus_address_get_stream_sync:
912 * @address: A valid D-Bus address.
913 * @out_guid: (optional) (out): %NULL or return location to store the GUID extracted from @address, if any.
914 * @cancellable: (allow-none): A #GCancellable or %NULL.
915 * @error: Return location for error or %NULL.
917 * Synchronously connects to an endpoint specified by @address and
918 * sets up the connection so it is in a state to run the client-side
919 * of the D-Bus authentication conversation.
921 * This is a synchronous failable function. See
922 * g_dbus_address_get_stream() for the asynchronous version.
924 * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
929 g_dbus_address_get_stream_sync (const gchar
*address
,
931 GCancellable
*cancellable
,
939 g_return_val_if_fail (address
!= NULL
, NULL
);
940 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, NULL
);
945 addr_array
= g_strsplit (address
, ";", 0);
946 if (addr_array
!= NULL
&& addr_array
[0] == NULL
)
948 last_error
= g_error_new_literal (G_IO_ERROR
,
949 G_IO_ERROR_INVALID_ARGUMENT
,
950 _("The given address is empty"));
954 for (n
= 0; addr_array
!= NULL
&& addr_array
[n
] != NULL
; n
++)
956 const gchar
*addr
= addr_array
[n
];
960 ret
= g_dbus_address_try_connect_one (addr
,
970 g_assert (this_error
!= NULL
);
971 if (last_error
!= NULL
)
972 g_error_free (last_error
);
973 last_error
= this_error
;
980 if (last_error
!= NULL
)
981 g_error_free (last_error
);
985 g_assert (last_error
!= NULL
);
986 g_propagate_error (error
, last_error
);
989 g_strfreev (addr_array
);
993 /* ---------------------------------------------------------------------------------------------------- */
996 * Return the address of XDG_RUNTIME_DIR/bus if it exists, belongs to
997 * us, and is a socket, and we are on Unix.
1000 get_session_address_xdg (void)
1008 bus
= g_build_filename (g_get_user_runtime_dir (), "bus", NULL
);
1010 /* if ENOENT, EPERM, etc., quietly don't use it */
1011 if (g_stat (bus
, &buf
) < 0)
1014 /* if it isn't ours, we have incorrectly inherited someone else's
1015 * XDG_RUNTIME_DIR; silently don't use it
1017 if (buf
.st_uid
!= geteuid ())
1020 /* if it isn't a socket, silently don't use it */
1021 if ((buf
.st_mode
& S_IFMT
) != S_IFSOCK
)
1024 tmp
= g_dbus_address_escape_value (bus
);
1025 ret
= g_strconcat ("unix:path=", tmp
, NULL
);
1036 /* ---------------------------------------------------------------------------------------------------- */
1040 get_session_address_dbus_launch (GError
**error
)
1044 gchar
*command_line
;
1045 gchar
*launch_stdout
;
1046 gchar
*launch_stderr
;
1048 gchar
*old_dbus_verbose
;
1049 gboolean restore_dbus_verbose
;
1053 command_line
= NULL
;
1054 launch_stdout
= NULL
;
1055 launch_stderr
= NULL
;
1056 restore_dbus_verbose
= FALSE
;
1057 old_dbus_verbose
= NULL
;
1059 /* Don't run binaries as root if we're setuid. */
1060 if (GLIB_PRIVATE_CALL (g_check_setuid
) ())
1062 g_set_error (error
, G_IO_ERROR
, G_IO_ERROR_FAILED
,
1063 _("Cannot spawn a message bus when setuid"));
1067 machine_id
= _g_dbus_get_machine_id (error
);
1068 if (machine_id
== NULL
)
1070 g_prefix_error (error
, _("Cannot spawn a message bus without a machine-id: "));
1074 /* We're using private libdbus facilities here. When everything
1075 * (X11, Mac OS X, Windows) is spec'ed out correctly (not even the
1076 * X11 property is correctly documented right now) we should
1077 * consider using the spec instead of dbus-launch.
1079 * --autolaunch=MACHINEID
1080 * This option implies that dbus-launch should scan for a previ‐
1081 * ously-started session and reuse the values found there. If no
1082 * session is found, it will start a new session. The --exit-with-
1083 * session option is implied if --autolaunch is given. This option
1084 * is for the exclusive use of libdbus, you do not want to use it
1085 * manually. It may change in the future.
1088 /* TODO: maybe provide a variable for where to look for the dbus-launch binary? */
1089 command_line
= g_strdup_printf ("dbus-launch --autolaunch=%s --binary-syntax --close-stderr", machine_id
);
1091 if (G_UNLIKELY (_g_dbus_debug_address ()))
1093 _g_dbus_debug_print_lock ();
1094 g_print ("GDBus-debug:Address: Running '%s' to get bus address (possibly autolaunching)\n", command_line
);
1095 old_dbus_verbose
= g_strdup (g_getenv ("DBUS_VERBOSE"));
1096 restore_dbus_verbose
= TRUE
;
1097 g_setenv ("DBUS_VERBOSE", "1", TRUE
);
1098 _g_dbus_debug_print_unlock ();
1101 if (!g_spawn_command_line_sync (command_line
,
1110 if (!g_spawn_check_exit_status (exit_status
, error
))
1112 g_prefix_error (error
, _("Error spawning command line '%s': "), command_line
);
1116 /* From the dbus-launch(1) man page:
1118 * --binary-syntax Write to stdout a nul-terminated bus address,
1119 * then the bus PID as a binary integer of size sizeof(pid_t),
1120 * then the bus X window ID as a binary integer of size
1121 * sizeof(long). Integers are in the machine's byte order, not
1122 * network byte order or any other canonical byte order.
1124 ret
= g_strdup (launch_stdout
);
1127 if (G_UNLIKELY (_g_dbus_debug_address ()))
1130 _g_dbus_debug_print_lock ();
1131 g_print ("GDBus-debug:Address: dbus-launch output:");
1132 if (launch_stdout
!= NULL
)
1134 s
= _g_dbus_hexdump (launch_stdout
, strlen (launch_stdout
) + 1 + sizeof (pid_t
) + sizeof (long), 2);
1135 g_print ("\n%s", s
);
1140 g_print (" (none)\n");
1142 g_print ("GDBus-debug:Address: dbus-launch stderr output:");
1143 if (launch_stderr
!= NULL
)
1144 g_print ("\n%s", launch_stderr
);
1146 g_print (" (none)\n");
1147 _g_dbus_debug_print_unlock ();
1150 g_free (machine_id
);
1151 g_free (command_line
);
1152 g_free (launch_stdout
);
1153 g_free (launch_stderr
);
1154 if (G_UNLIKELY (restore_dbus_verbose
))
1156 if (old_dbus_verbose
!= NULL
)
1157 g_setenv ("DBUS_VERBOSE", old_dbus_verbose
, TRUE
);
1159 g_unsetenv ("DBUS_VERBOSE");
1161 g_free (old_dbus_verbose
);
1165 /* end of G_OS_UNIX case */
1166 #elif defined(G_OS_WIN32)
1168 #define DBUS_DAEMON_ADDRESS_INFO "DBusDaemonAddressInfo"
1169 #define DBUS_DAEMON_MUTEX "DBusDaemonMutex"
1170 #define UNIQUE_DBUS_INIT_MUTEX "UniqueDBusInitMutex"
1171 #define DBUS_AUTOLAUNCH_MUTEX "DBusAutolaunchMutex"
1174 release_mutex (HANDLE mutex
)
1176 ReleaseMutex (mutex
);
1177 CloseHandle (mutex
);
1181 acquire_mutex (const char *mutexname
)
1186 mutex
= CreateMutexA (NULL
, FALSE
, mutexname
);
1190 res
= WaitForSingleObject (mutex
, INFINITE
);
1193 case WAIT_ABANDONED
:
1194 release_mutex (mutex
);
1205 is_mutex_owned (const char *mutexname
)
1208 gboolean res
= FALSE
;
1210 mutex
= CreateMutexA (NULL
, FALSE
, mutexname
);
1211 if (WaitForSingleObject (mutex
, 10) == WAIT_TIMEOUT
)
1214 ReleaseMutex (mutex
);
1215 CloseHandle (mutex
);
1221 read_shm (const char *shm_name
)
1230 for (i
= 0; i
< 20; i
++)
1232 shared_mem
= OpenFileMappingA (FILE_MAP_READ
, FALSE
, shm_name
);
1233 if (shared_mem
!= 0)
1238 if (shared_mem
!= 0)
1240 shared_data
= MapViewOfFile (shared_mem
, FILE_MAP_READ
, 0, 0, 0);
1241 if (shared_data
!= NULL
)
1243 res
= g_strdup (shared_data
);
1244 UnmapViewOfFile (shared_data
);
1246 CloseHandle (shared_mem
);
1253 set_shm (const char *shm_name
, const char *value
)
1258 shared_mem
= CreateFileMappingA (INVALID_HANDLE_VALUE
, NULL
, PAGE_READWRITE
,
1259 0, strlen (value
) + 1, shm_name
);
1260 if (shared_mem
== 0)
1263 shared_data
= MapViewOfFile (shared_mem
, FILE_MAP_WRITE
, 0, 0, 0 );
1264 if (shared_data
== NULL
)
1267 strcpy (shared_data
, value
);
1269 UnmapViewOfFile (shared_data
);
1274 /* These keep state between publish_session_bus and unpublish_session_bus */
1275 static HANDLE published_daemon_mutex
;
1276 static HANDLE published_shared_mem
;
1279 publish_session_bus (const char *address
)
1283 init_mutex
= acquire_mutex (UNIQUE_DBUS_INIT_MUTEX
);
1285 published_daemon_mutex
= CreateMutexA (NULL
, FALSE
, DBUS_DAEMON_MUTEX
);
1286 if (WaitForSingleObject (published_daemon_mutex
, 10 ) != WAIT_OBJECT_0
)
1288 release_mutex (init_mutex
);
1289 CloseHandle (published_daemon_mutex
);
1290 published_daemon_mutex
= NULL
;
1294 published_shared_mem
= set_shm (DBUS_DAEMON_ADDRESS_INFO
, address
);
1295 if (!published_shared_mem
)
1297 release_mutex (init_mutex
);
1298 CloseHandle (published_daemon_mutex
);
1299 published_daemon_mutex
= NULL
;
1303 release_mutex (init_mutex
);
1308 unpublish_session_bus (void)
1312 init_mutex
= acquire_mutex (UNIQUE_DBUS_INIT_MUTEX
);
1314 CloseHandle (published_shared_mem
);
1315 published_shared_mem
= NULL
;
1317 release_mutex (published_daemon_mutex
);
1318 published_daemon_mutex
= NULL
;
1320 release_mutex (init_mutex
);
1324 wait_console_window (void)
1326 FILE *console
= fopen ("CONOUT$", "w");
1328 SetConsoleTitleW (L
"gdbus-daemon output. Type any character to close this window.");
1329 fprintf (console
, _("(Type any character to close this window)\n"));
1335 open_console_window (void)
1337 if (((HANDLE
) _get_osfhandle (fileno (stdout
)) == INVALID_HANDLE_VALUE
||
1338 (HANDLE
) _get_osfhandle (fileno (stderr
)) == INVALID_HANDLE_VALUE
) && AllocConsole ())
1340 if ((HANDLE
) _get_osfhandle (fileno (stdout
)) == INVALID_HANDLE_VALUE
)
1341 freopen ("CONOUT$", "w", stdout
);
1343 if ((HANDLE
) _get_osfhandle (fileno (stderr
)) == INVALID_HANDLE_VALUE
)
1344 freopen ("CONOUT$", "w", stderr
);
1346 SetConsoleTitleW (L
"gdbus-daemon debug output.");
1348 atexit (wait_console_window
);
1352 idle_timeout_cb (GDBusDaemon
*daemon
, gpointer user_data
)
1354 GMainLoop
*loop
= user_data
;
1355 g_main_loop_quit (loop
);
1358 /* Satisfies STARTF_FORCEONFEEDBACK */
1360 turn_off_the_starting_cursor (void)
1365 PostQuitMessage (0);
1367 while ((bRet
= GetMessage (&msg
, 0, 0, 0)) != 0)
1372 TranslateMessage (&msg
);
1373 DispatchMessage (&msg
);
1377 __declspec(dllexport
) void CALLBACK
g_win32_run_session_bus (HWND hwnd
, HINSTANCE hinst
, char *cmdline
, int nCmdShow
);
1379 __declspec(dllexport
) void CALLBACK
1380 g_win32_run_session_bus (HWND hwnd
, HINSTANCE hinst
, char *cmdline
, int nCmdShow
)
1382 GDBusDaemon
*daemon
;
1384 const char *address
;
1385 GError
*error
= NULL
;
1387 turn_off_the_starting_cursor ();
1389 if (g_getenv ("GDBUS_DAEMON_DEBUG") != NULL
)
1390 open_console_window ();
1392 loop
= g_main_loop_new (NULL
, FALSE
);
1394 address
= "nonce-tcp:";
1395 daemon
= _g_dbus_daemon_new (address
, NULL
, &error
);
1398 g_printerr ("Can't init bus: %s\n", error
->message
);
1402 g_signal_connect (daemon
, "idle-timeout", G_CALLBACK (idle_timeout_cb
), loop
);
1404 if ( publish_session_bus (_g_dbus_daemon_get_address (daemon
)))
1406 g_main_loop_run (loop
);
1408 unpublish_session_bus ();
1411 g_main_loop_unref (loop
);
1412 g_object_unref (daemon
);
1416 get_session_address_dbus_launch (GError
**error
)
1418 HANDLE autolaunch_mutex
, init_mutex
;
1419 char *address
= NULL
;
1420 wchar_t gio_path
[MAX_PATH
+1+200];
1422 autolaunch_mutex
= acquire_mutex (DBUS_AUTOLAUNCH_MUTEX
);
1424 init_mutex
= acquire_mutex (UNIQUE_DBUS_INIT_MUTEX
);
1426 if (is_mutex_owned (DBUS_DAEMON_MUTEX
))
1427 address
= read_shm (DBUS_DAEMON_ADDRESS_INFO
);
1429 release_mutex (init_mutex
);
1431 if (address
== NULL
)
1433 gio_path
[MAX_PATH
] = 0;
1434 if (GetModuleFileNameW (_g_io_win32_get_module (), gio_path
, MAX_PATH
))
1436 PROCESS_INFORMATION pi
= { 0 };
1437 STARTUPINFOW si
= { 0 };
1439 wchar_t gio_path_short
[MAX_PATH
];
1440 wchar_t rundll_path
[MAX_PATH
*2];
1441 wchar_t args
[MAX_PATH
*4];
1443 GetShortPathNameW (gio_path
, gio_path_short
, MAX_PATH
);
1445 GetWindowsDirectoryW (rundll_path
, MAX_PATH
);
1446 wcscat (rundll_path
, L
"\\rundll32.exe");
1447 if (GetFileAttributesW (rundll_path
) == INVALID_FILE_ATTRIBUTES
)
1449 GetSystemDirectoryW (rundll_path
, MAX_PATH
);
1450 wcscat (rundll_path
, L
"\\rundll32.exe");
1453 wcscpy (args
, L
"\"");
1454 wcscat (args
, rundll_path
);
1455 wcscat (args
, L
"\" ");
1456 wcscat (args
, gio_path_short
);
1457 #if defined(_WIN64) || defined(_M_X64) || defined(_M_AMD64)
1458 wcscat (args
, L
",g_win32_run_session_bus");
1459 #elif defined (_MSC_VER)
1460 wcscat (args
, L
",_g_win32_run_session_bus@16");
1462 wcscat (args
, L
",g_win32_run_session_bus@16");
1465 res
= CreateProcessW (rundll_path
, args
,
1467 NORMAL_PRIORITY_CLASS
| CREATE_NO_WINDOW
| DETACHED_PROCESS
,
1468 0, NULL
/* TODO: Should be root */,
1471 address
= read_shm (DBUS_DAEMON_ADDRESS_INFO
);
1475 release_mutex (autolaunch_mutex
);
1477 if (address
== NULL
)
1481 _("Session dbus not running, and autolaunch failed"));
1485 #else /* neither G_OS_UNIX nor G_OS_WIN32 */
1487 get_session_address_dbus_launch (GError
**error
)
1492 _("Cannot determine session bus address (not implemented for this OS)"));
1495 #endif /* neither G_OS_UNIX nor G_OS_WIN32 */
1497 /* ---------------------------------------------------------------------------------------------------- */
1500 get_session_address_platform_specific (GError
**error
)
1504 /* Use XDG_RUNTIME_DIR/bus if it exists and is suitable. This is appropriate
1505 * for systems using the "a session is a user-session" model described in
1506 * <http://lists.freedesktop.org/archives/dbus/2015-January/016522.html>,
1507 * and implemented in dbus >= 1.9.14 and sd-bus.
1509 * On systems following the more traditional "a session is a login-session"
1510 * model, this will fail and we'll fall through to X11 autolaunching
1511 * (dbus-launch) below.
1513 ret
= get_session_address_xdg ();
1518 /* TODO (#694472): try launchd on OS X, like
1519 * _dbus_lookup_session_address_launchd() does, since
1520 * 'dbus-launch --autolaunch' probably won't work there
1523 /* As a last resort, try the "autolaunch:" transport. On Unix this means
1524 * X11 autolaunching; on Windows this means a different autolaunching
1525 * mechanism based on shared memory.
1527 return get_session_address_dbus_launch (error
);
1530 /* ---------------------------------------------------------------------------------------------------- */
1533 * g_dbus_address_get_for_bus_sync:
1534 * @bus_type: a #GBusType
1535 * @cancellable: (allow-none): a #GCancellable or %NULL
1536 * @error: return location for error or %NULL
1538 * Synchronously looks up the D-Bus address for the well-known message
1539 * bus instance specified by @bus_type. This may involve using various
1540 * platform specific mechanisms.
1542 * Returns: a valid D-Bus address string for @bus_type or %NULL if
1548 g_dbus_address_get_for_bus_sync (GBusType bus_type
,
1549 GCancellable
*cancellable
,
1552 gchar
*ret
, *s
= NULL
;
1553 const gchar
*starter_bus
;
1554 GError
*local_error
;
1556 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, NULL
);
1561 if (G_UNLIKELY (_g_dbus_debug_address ()))
1564 _g_dbus_debug_print_lock ();
1565 s
= _g_dbus_enum_to_string (G_TYPE_BUS_TYPE
, bus_type
);
1566 g_print ("GDBus-debug:Address: In g_dbus_address_get_for_bus_sync() for bus type '%s'\n",
1569 for (n
= 0; n
< 3; n
++)
1575 case 0: k
= "DBUS_SESSION_BUS_ADDRESS"; break;
1576 case 1: k
= "DBUS_SYSTEM_BUS_ADDRESS"; break;
1577 case 2: k
= "DBUS_STARTER_BUS_TYPE"; break;
1578 default: g_assert_not_reached ();
1581 g_print ("GDBus-debug:Address: env var %s", k
);
1583 g_print ("='%s'\n", v
);
1585 g_print (" is not set\n");
1587 _g_dbus_debug_print_unlock ();
1592 case G_BUS_TYPE_SYSTEM
:
1593 ret
= g_strdup (g_getenv ("DBUS_SYSTEM_BUS_ADDRESS"));
1596 ret
= g_strdup ("unix:path=/var/run/dbus/system_bus_socket");
1600 case G_BUS_TYPE_SESSION
:
1601 ret
= g_strdup (g_getenv ("DBUS_SESSION_BUS_ADDRESS"));
1604 ret
= get_session_address_platform_specific (&local_error
);
1608 case G_BUS_TYPE_STARTER
:
1609 starter_bus
= g_getenv ("DBUS_STARTER_BUS_TYPE");
1610 if (g_strcmp0 (starter_bus
, "session") == 0)
1612 ret
= g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SESSION
, cancellable
, &local_error
);
1615 else if (g_strcmp0 (starter_bus
, "system") == 0)
1617 ret
= g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SYSTEM
, cancellable
, &local_error
);
1622 if (starter_bus
!= NULL
)
1624 g_set_error (&local_error
,
1627 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
1628 " - unknown value '%s'"),
1633 g_set_error_literal (&local_error
,
1636 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
1637 "variable is not set"));
1643 g_set_error (&local_error
,
1646 _("Unknown bus type %d"),
1652 if (G_UNLIKELY (_g_dbus_debug_address ()))
1654 _g_dbus_debug_print_lock ();
1655 s
= _g_dbus_enum_to_string (G_TYPE_BUS_TYPE
, bus_type
);
1658 g_print ("GDBus-debug:Address: Returning address '%s' for bus type '%s'\n",
1663 g_print ("GDBus-debug:Address: Cannot look-up address bus type '%s': %s\n",
1664 s
, local_error
? local_error
->message
: "");
1667 _g_dbus_debug_print_unlock ();
1670 if (local_error
!= NULL
)
1671 g_propagate_error (error
, local_error
);
1677 * g_dbus_address_escape_value:
1678 * @string: an unescaped string to be included in a D-Bus address
1679 * as the value in a key-value pair
1681 * Escape @string so it can appear in a D-Bus address as the value
1682 * part of a key-value pair.
1684 * For instance, if @string is "/run/bus-for-:0",
1685 * this function would return "/run/bus-for-%3A0",
1686 * which could be used in a D-Bus address like
1687 * "unix:nonce-tcp:host=127.0.0.1,port=42,noncefile=/run/bus-for-%3A0".
1689 * Returns: (transfer full): a copy of @string with all
1690 * non-optionally-escaped bytes escaped
1695 g_dbus_address_escape_value (const gchar
*string
)
1700 g_return_val_if_fail (string
!= NULL
, NULL
);
1702 /* There will often not be anything needing escaping at all. */
1703 s
= g_string_sized_new (strlen (string
));
1705 /* D-Bus address escaping is mostly the same as URI escaping... */
1706 g_string_append_uri_escaped (s
, string
, "\\/", FALSE
);
1708 /* ... but '~' is an unreserved character in URIs, but a
1709 * non-optionally-escaped character in D-Bus addresses. */
1710 for (i
= 0; i
< s
->len
; i
++)
1712 if (G_UNLIKELY (s
->str
[i
] == '~'))
1715 g_string_insert (s
, i
+ 1, "7E");
1720 return g_string_free (s
, FALSE
);