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"
37 #include "gsimpleasyncresult.h"
38 #include "glib-private.h"
39 #include "gdbusprivate.h"
40 #include "giomodule-priv.h"
41 #include "gdbusdaemon.h"
45 #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 [D-Bus specification](http://dbus.freedesktop.org/doc/dbus-specification.html\#addresses).
67 static gchar *get_session_address_platform_specific (GError **error);
69 /* ---------------------------------------------------------------------------------------------------- */
75 * Checks if @string is a D-Bus address.
77 * This doesn't check if @string is actually supported by #GDBusServer
78 * or #GDBusConnection - use g_dbus_is_supported_address() to do more
81 * Returns: %TRUE if @string is a valid D-Bus address, %FALSE otherwise.
86 g_dbus_is_address (const gchar *string)
94 g_return_val_if_fail (string != NULL, FALSE);
96 a = g_strsplit (string, ";", 0);
100 for (n = 0; a[n] != NULL; n++)
102 if (!_g_dbus_address_parse_entry (a[n],
117 is_valid_unix (const gchar *address_entry,
118 GHashTable *key_value_pairs,
126 const gchar *abstract;
134 keys = g_hash_table_get_keys (key_value_pairs);
135 for (l = keys; l != NULL; l = l->next)
137 const gchar *key = l->data;
138 if (g_strcmp0 (key, "path") == 0)
139 path = g_hash_table_lookup (key_value_pairs, key);
140 else if (g_strcmp0 (key, "tmpdir") == 0)
141 tmpdir = g_hash_table_lookup (key_value_pairs, key);
142 else if (g_strcmp0 (key, "abstract") == 0)
143 abstract = g_hash_table_lookup (key_value_pairs, key);
148 G_IO_ERROR_INVALID_ARGUMENT,
149 _("Unsupported key '%s' in address entry '%s'"),
158 if (tmpdir != NULL || abstract != NULL)
161 else if (tmpdir != NULL)
163 if (path != NULL || abstract != NULL)
166 else if (abstract != NULL)
168 if (path != NULL || tmpdir != NULL)
175 G_IO_ERROR_INVALID_ARGUMENT,
176 _("Address '%s' is invalid (need exactly one of path, tmpdir or abstract keys)"),
188 G_IO_ERROR_INVALID_ARGUMENT,
189 _("Meaningless key/value pair combination in address entry '%s'"),
199 is_valid_nonce_tcp (const gchar *address_entry,
200 GHashTable *key_value_pairs,
209 const gchar *nonce_file;
220 keys = g_hash_table_get_keys (key_value_pairs);
221 for (l = keys; l != NULL; l = l->next)
223 const gchar *key = l->data;
224 if (g_strcmp0 (key, "host") == 0)
225 host = g_hash_table_lookup (key_value_pairs, key);
226 else if (g_strcmp0 (key, "port") == 0)
227 port = g_hash_table_lookup (key_value_pairs, key);
228 else if (g_strcmp0 (key, "family") == 0)
229 family = g_hash_table_lookup (key_value_pairs, key);
230 else if (g_strcmp0 (key, "noncefile") == 0)
231 nonce_file = g_hash_table_lookup (key_value_pairs, key);
236 G_IO_ERROR_INVALID_ARGUMENT,
237 _("Unsupported key '%s' in address entry '%s'"),
246 port_num = strtol (port, &endp, 10);
247 if ((*port == '\0' || *endp != '\0') || port_num < 0 || port_num >= 65536)
251 G_IO_ERROR_INVALID_ARGUMENT,
252 _("Error in address '%s' - the port attribute is malformed"),
258 if (family != NULL && !(g_strcmp0 (family, "ipv4") == 0 || g_strcmp0 (family, "ipv6") == 0))
262 G_IO_ERROR_INVALID_ARGUMENT,
263 _("Error in address '%s' - the family attribute is malformed"),
270 /* TODO: validate host */
273 nonce_file = nonce_file; /* To avoid -Wunused-but-set-variable */
284 is_valid_tcp (const gchar *address_entry,
285 GHashTable *key_value_pairs,
303 keys = g_hash_table_get_keys (key_value_pairs);
304 for (l = keys; l != NULL; l = l->next)
306 const gchar *key = l->data;
307 if (g_strcmp0 (key, "host") == 0)
308 host = g_hash_table_lookup (key_value_pairs, key);
309 else if (g_strcmp0 (key, "port") == 0)
310 port = g_hash_table_lookup (key_value_pairs, key);
311 else if (g_strcmp0 (key, "family") == 0)
312 family = g_hash_table_lookup (key_value_pairs, key);
317 G_IO_ERROR_INVALID_ARGUMENT,
318 _("Unsupported key '%s' in address entry '%s'"),
327 port_num = strtol (port, &endp, 10);
328 if ((*port == '\0' || *endp != '\0') || port_num < 0 || port_num >= 65536)
332 G_IO_ERROR_INVALID_ARGUMENT,
333 _("Error in address '%s' - the port attribute is malformed"),
339 if (family != NULL && !(g_strcmp0 (family, "ipv4") == 0 || g_strcmp0 (family, "ipv6") == 0))
343 G_IO_ERROR_INVALID_ARGUMENT,
344 _("Error in address '%s' - the family attribute is malformed"),
351 /* TODO: validate host */
363 * g_dbus_is_supported_address:
365 * @error: Return location for error or %NULL.
367 * Like g_dbus_is_address() but also checks if the library suppors the
368 * transports in @string and that key/value pairs for each transport
371 * Returns: %TRUE if @string is a valid D-Bus address that is
372 * supported by this library, %FALSE if @error is set.
377 g_dbus_is_supported_address (const gchar *string,
386 g_return_val_if_fail (string != NULL, FALSE);
387 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
389 a = g_strsplit (string, ";", 0);
390 for (n = 0; a[n] != NULL; n++)
392 gchar *transport_name;
393 GHashTable *key_value_pairs;
396 if (!_g_dbus_address_parse_entry (a[n],
403 if (g_strcmp0 (transport_name, "unix") == 0)
404 supported = is_valid_unix (a[n], key_value_pairs, error);
405 else if (g_strcmp0 (transport_name, "tcp") == 0)
406 supported = is_valid_tcp (a[n], key_value_pairs, error);
407 else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
408 supported = is_valid_nonce_tcp (a[n], key_value_pairs, error);
409 else if (g_strcmp0 (a[n], "autolaunch:") == 0)
412 g_free (transport_name);
413 g_hash_table_unref (key_value_pairs);
424 g_assert (ret || (!ret && (error == NULL || *error != NULL)));
430 _g_dbus_address_parse_entry (const gchar *address_entry,
431 gchar **out_transport_name,
432 GHashTable **out_key_value_pairs,
436 GHashTable *key_value_pairs;
437 gchar *transport_name;
444 transport_name = NULL;
445 key_value_pairs = NULL;
447 s = strchr (address_entry, ':');
452 G_IO_ERROR_INVALID_ARGUMENT,
453 _("Address element '%s' does not contain a colon (:)"),
458 transport_name = g_strndup (address_entry, s - address_entry);
459 key_value_pairs = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
461 kv_pairs = g_strsplit (s + 1, ",", 0);
462 for (n = 0; kv_pairs != NULL && kv_pairs[n] != NULL; n++)
464 const gchar *kv_pair = kv_pairs[n];
468 s = strchr (kv_pair, '=');
473 G_IO_ERROR_INVALID_ARGUMENT,
474 _("Key/Value pair %d, '%s', in address element '%s' does not contain an equal sign"),
481 key = g_uri_unescape_segment (kv_pair, s, NULL);
482 value = g_uri_unescape_segment (s + 1, kv_pair + strlen (kv_pair), NULL);
483 if (key == NULL || value == NULL)
487 G_IO_ERROR_INVALID_ARGUMENT,
488 _("Error unescaping key or value in Key/Value pair %d, '%s', in address element '%s'"),
496 g_hash_table_insert (key_value_pairs, key, value);
502 g_strfreev (kv_pairs);
505 if (out_transport_name != NULL)
506 *out_transport_name = transport_name;
508 g_free (transport_name);
509 if (out_key_value_pairs != NULL)
510 *out_key_value_pairs = key_value_pairs;
511 else if (key_value_pairs != NULL)
512 g_hash_table_unref (key_value_pairs);
516 g_free (transport_name);
517 if (key_value_pairs != NULL)
518 g_hash_table_unref (key_value_pairs);
523 /* ---------------------------------------------------------------------------------------------------- */
526 g_dbus_address_try_connect_one (const gchar *address_entry,
529 GCancellable *cancellable,
532 /* TODO: Declare an extension point called GDBusTransport (or similar)
533 * and move code below to extensions implementing said extension
534 * point. That way we can implement a D-Bus transport over X11 without
535 * making libgio link to libX11...
538 g_dbus_address_connect (const gchar *address_entry,
539 const gchar *transport_name,
541 GHashTable *key_value_pairs,
542 GCancellable *cancellable,
546 GSocketConnectable *connectable;
547 const gchar *nonce_file;
557 else if (kdbus_okay || g_str_equal (transport_name, "kernel"))
559 GKDBusWorker *worker;
562 path = g_hash_table_lookup (key_value_pairs, "path");
566 g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
567 _("Error in address '%s' - the kernel transport requires a path"),
571 worker = g_kdbus_worker_new (path, error);
576 return G_OBJECT (worker);
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_platform_specific (error);
666 if (autolaunch_address != NULL)
668 ret = g_dbus_address_try_connect_one (autolaunch_address, kdbus_okay, 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 ();
694 connection = g_socket_client_connect (client,
698 g_object_unref (connectable);
699 g_object_unref (client);
700 if (connection == NULL)
703 ret = G_OBJECT (connection);
705 if (nonce_file != NULL)
707 gchar nonce_contents[16 + 1];
708 size_t num_bytes_read;
711 /* be careful to read only 16 bytes - we also check that the file is only 16 bytes long */
712 f = fopen (nonce_file, "rb");
717 G_IO_ERROR_INVALID_ARGUMENT,
718 _("Error opening nonce file '%s': %s"),
721 g_object_unref (ret);
725 num_bytes_read = fread (nonce_contents,
729 if (num_bytes_read != 16)
731 if (num_bytes_read == 0)
735 G_IO_ERROR_INVALID_ARGUMENT,
736 _("Error reading from nonce file '%s': %s"),
744 G_IO_ERROR_INVALID_ARGUMENT,
745 _("Error reading from nonce file '%s', expected 16 bytes, got %d"),
747 (gint) num_bytes_read);
749 g_object_unref (ret);
756 if (!g_output_stream_write_all (g_io_stream_get_output_stream (G_IO_STREAM (connection)),
763 g_prefix_error (error, _("Error writing contents of nonce file '%s' to stream:"), nonce_file);
764 g_object_unref (ret);
777 g_dbus_address_try_connect_one (const gchar *address_entry,
780 GCancellable *cancellable,
784 GHashTable *key_value_pairs;
785 gchar *transport_name;
789 transport_name = NULL;
790 key_value_pairs = NULL;
792 if (!_g_dbus_address_parse_entry (address_entry,
798 ret = g_dbus_address_connect (address_entry,
807 guid = g_hash_table_lookup (key_value_pairs, "guid");
808 if (guid != NULL && out_guid != NULL)
809 *out_guid = g_strdup (guid);
812 g_free (transport_name);
813 if (key_value_pairs != NULL)
814 g_hash_table_unref (key_value_pairs);
819 /* ---------------------------------------------------------------------------------------------------- */
828 get_stream_data_free (GetStreamData *data)
830 g_free (data->address);
831 if (data->stream != NULL)
832 g_object_unref (data->stream);
838 get_stream_thread_func (GSimpleAsyncResult *res,
840 GCancellable *cancellable)
845 data = g_simple_async_result_get_op_res_gpointer (res);
848 data->stream = g_dbus_address_get_stream_sync (data->address,
852 if (data->stream == NULL)
853 g_simple_async_result_take_error (res, error);
857 * g_dbus_address_get_stream:
858 * @address: A valid D-Bus address.
859 * @cancellable: (allow-none): A #GCancellable or %NULL.
860 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
861 * @user_data: Data to pass to @callback.
863 * Asynchronously connects to an endpoint specified by @address and
864 * sets up the connection so it is in a state to run the client-side
865 * of the D-Bus authentication conversation.
867 * When the operation is finished, @callback will be invoked. You can
868 * then call g_dbus_address_get_stream_finish() to get the result of
871 * This is an asynchronous failable function. See
872 * g_dbus_address_get_stream_sync() for the synchronous version.
877 g_dbus_address_get_stream (const gchar *address,
878 GCancellable *cancellable,
879 GAsyncReadyCallback callback,
882 GSimpleAsyncResult *res;
885 g_return_if_fail (address != NULL);
887 res = g_simple_async_result_new (NULL,
890 g_dbus_address_get_stream);
891 g_simple_async_result_set_check_cancellable (res, cancellable);
892 data = g_new0 (GetStreamData, 1);
893 data->address = g_strdup (address);
894 g_simple_async_result_set_op_res_gpointer (res,
896 (GDestroyNotify) get_stream_data_free);
897 g_simple_async_result_run_in_thread (res,
898 get_stream_thread_func,
901 g_object_unref (res);
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: %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 * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
917 g_dbus_address_get_stream_finish (GAsyncResult *res,
921 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
925 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
926 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
928 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_address_get_stream);
932 data = g_simple_async_result_get_op_res_gpointer (simple);
933 if (g_simple_async_result_propagate_error (simple, error))
936 ret = g_object_ref (data->stream);
937 if (out_guid != NULL)
938 *out_guid = g_strdup (data->guid);
945 * g_dbus_address_get_stream_sync:
946 * @address: A valid D-Bus address.
947 * @out_guid: %NULL or return location to store the GUID extracted from @address, if any.
948 * @cancellable: (allow-none): 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.
955 * This is a synchronous failable function. See
956 * g_dbus_address_get_stream() for the asynchronous version.
958 * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
963 g_dbus_address_get_stream_sync (const gchar *address,
965 GCancellable *cancellable,
970 result = g_dbus_address_get_stream_internal (address, FALSE, out_guid, cancellable, error);
971 g_assert (result == NULL || G_IS_IO_STREAM (result));
974 return G_IO_STREAM (result);
980 g_dbus_address_get_stream_internal (const gchar *address,
983 GCancellable *cancellable,
991 g_return_val_if_fail (address != NULL, NULL);
992 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
997 addr_array = g_strsplit (address, ";", 0);
998 if (addr_array != NULL && addr_array[0] == NULL)
1000 last_error = g_error_new_literal (G_IO_ERROR,
1001 G_IO_ERROR_INVALID_ARGUMENT,
1002 _("The given address is empty"));
1006 for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
1008 const gchar *addr = addr_array[n];
1012 ret = g_dbus_address_try_connect_one (addr,
1023 g_assert (this_error != NULL);
1024 if (last_error != NULL)
1025 g_error_free (last_error);
1026 last_error = this_error;
1033 if (last_error != NULL)
1034 g_error_free (last_error);
1038 g_assert (last_error != NULL);
1039 g_propagate_error (error, last_error);
1042 g_strfreev (addr_array);
1046 /* ---------------------------------------------------------------------------------------------------- */
1050 get_session_address_dbus_launch (GError **error)
1054 gchar *command_line;
1055 gchar *launch_stdout;
1056 gchar *launch_stderr;
1058 gchar *old_dbus_verbose;
1059 gboolean restore_dbus_verbose;
1063 command_line = NULL;
1064 launch_stdout = NULL;
1065 launch_stderr = NULL;
1066 restore_dbus_verbose = FALSE;
1067 old_dbus_verbose = NULL;
1069 /* Don't run binaries as root if we're setuid. */
1070 if (GLIB_PRIVATE_CALL (g_check_setuid) ())
1072 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1073 _("Cannot spawn a message bus when setuid"));
1077 machine_id = _g_dbus_get_machine_id (error);
1078 if (machine_id == NULL)
1080 g_prefix_error (error, _("Cannot spawn a message bus without a machine-id: "));
1084 /* We're using private libdbus facilities here. When everything
1085 * (X11, Mac OS X, Windows) is spec'ed out correctly (not even the
1086 * X11 property is correctly documented right now) we should
1087 * consider using the spec instead of dbus-launch.
1089 * --autolaunch=MACHINEID
1090 * This option implies that dbus-launch should scan for a previ‐
1091 * ously-started session and reuse the values found there. If no
1092 * session is found, it will start a new session. The --exit-with-
1093 * session option is implied if --autolaunch is given. This option
1094 * is for the exclusive use of libdbus, you do not want to use it
1095 * manually. It may change in the future.
1098 /* TODO: maybe provide a variable for where to look for the dbus-launch binary? */
1099 command_line = g_strdup_printf ("dbus-launch --autolaunch=%s --binary-syntax --close-stderr", machine_id);
1101 if (G_UNLIKELY (_g_dbus_debug_address ()))
1103 _g_dbus_debug_print_lock ();
1104 g_print ("GDBus-debug:Address: Running '%s' to get bus address (possibly autolaunching)\n", command_line);
1105 old_dbus_verbose = g_strdup (g_getenv ("DBUS_VERBOSE"));
1106 restore_dbus_verbose = TRUE;
1107 g_setenv ("DBUS_VERBOSE", "1", TRUE);
1108 _g_dbus_debug_print_unlock ();
1111 if (!g_spawn_command_line_sync (command_line,
1120 if (!g_spawn_check_exit_status (exit_status, error))
1122 g_prefix_error (error, _("Error spawning command line '%s': "), command_line);
1126 /* From the dbus-launch(1) man page:
1128 * --binary-syntax Write to stdout a nul-terminated bus address,
1129 * then the bus PID as a binary integer of size sizeof(pid_t),
1130 * then the bus X window ID as a binary integer of size
1131 * sizeof(long). Integers are in the machine's byte order, not
1132 * network byte order or any other canonical byte order.
1134 ret = g_strdup (launch_stdout);
1137 if (G_UNLIKELY (_g_dbus_debug_address ()))
1140 _g_dbus_debug_print_lock ();
1141 g_print ("GDBus-debug:Address: dbus-launch output:");
1142 if (launch_stdout != NULL)
1144 s = _g_dbus_hexdump (launch_stdout, strlen (launch_stdout) + 1 + sizeof (pid_t) + sizeof (long), 2);
1145 g_print ("\n%s", s);
1150 g_print (" (none)\n");
1152 g_print ("GDBus-debug:Address: dbus-launch stderr output:");
1153 if (launch_stderr != NULL)
1154 g_print ("\n%s", launch_stderr);
1156 g_print (" (none)\n");
1157 _g_dbus_debug_print_unlock ();
1160 g_free (machine_id);
1161 g_free (command_line);
1162 g_free (launch_stdout);
1163 g_free (launch_stderr);
1164 if (G_UNLIKELY (restore_dbus_verbose))
1166 if (old_dbus_verbose != NULL)
1167 g_setenv ("DBUS_VERBOSE", old_dbus_verbose, TRUE);
1169 g_unsetenv ("DBUS_VERBOSE");
1171 g_free (old_dbus_verbose);
1178 #define DBUS_DAEMON_ADDRESS_INFO "DBusDaemonAddressInfo"
1179 #define DBUS_DAEMON_MUTEX "DBusDaemonMutex"
1180 #define UNIQUE_DBUS_INIT_MUTEX "UniqueDBusInitMutex"
1181 #define DBUS_AUTOLAUNCH_MUTEX "DBusAutolaunchMutex"
1184 release_mutex (HANDLE mutex)
1186 ReleaseMutex (mutex);
1187 CloseHandle (mutex);
1191 acquire_mutex (const char *mutexname)
1196 mutex = CreateMutexA (NULL, FALSE, mutexname);
1200 res = WaitForSingleObject (mutex, INFINITE);
1203 case WAIT_ABANDONED:
1204 release_mutex (mutex);
1215 is_mutex_owned (const char *mutexname)
1218 gboolean res = FALSE;
1220 mutex = CreateMutexA (NULL, FALSE, mutexname);
1221 if (WaitForSingleObject (mutex, 10) == WAIT_TIMEOUT)
1224 ReleaseMutex (mutex);
1225 CloseHandle (mutex);
1231 read_shm (const char *shm_name)
1240 for (i = 0; i < 20; i++)
1242 shared_mem = OpenFileMappingA (FILE_MAP_READ, FALSE, shm_name);
1243 if (shared_mem != 0)
1248 if (shared_mem != 0)
1250 shared_data = MapViewOfFile (shared_mem, FILE_MAP_READ, 0, 0, 0);
1251 if (shared_data != NULL)
1253 res = g_strdup (shared_data);
1254 UnmapViewOfFile (shared_data);
1256 CloseHandle (shared_mem);
1263 set_shm (const char *shm_name, const char *value)
1268 shared_mem = CreateFileMappingA (INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
1269 0, strlen (value) + 1, shm_name);
1270 if (shared_mem == 0)
1273 shared_data = MapViewOfFile (shared_mem, FILE_MAP_WRITE, 0, 0, 0 );
1274 if (shared_data == NULL)
1277 strcpy (shared_data, value);
1279 UnmapViewOfFile (shared_data);
1284 /* These keep state between publish_session_bus and unpublish_session_bus */
1285 static HANDLE published_daemon_mutex;
1286 static HANDLE published_shared_mem;
1289 publish_session_bus (const char *address)
1293 init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
1295 published_daemon_mutex = CreateMutexA (NULL, FALSE, DBUS_DAEMON_MUTEX);
1296 if (WaitForSingleObject (published_daemon_mutex, 10 ) != WAIT_OBJECT_0)
1298 release_mutex (init_mutex);
1299 CloseHandle (published_daemon_mutex);
1300 published_daemon_mutex = NULL;
1304 published_shared_mem = set_shm (DBUS_DAEMON_ADDRESS_INFO, address);
1305 if (!published_shared_mem)
1307 release_mutex (init_mutex);
1308 CloseHandle (published_daemon_mutex);
1309 published_daemon_mutex = NULL;
1313 release_mutex (init_mutex);
1318 unpublish_session_bus (void)
1322 init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
1324 CloseHandle (published_shared_mem);
1325 published_shared_mem = NULL;
1327 release_mutex (published_daemon_mutex);
1328 published_daemon_mutex = NULL;
1330 release_mutex (init_mutex);
1334 wait_console_window (void)
1336 FILE *console = fopen ("CONOUT$", "w");
1338 SetConsoleTitleW (L"gdbus-daemon output. Type any character to close this window.");
1339 fprintf (console, _("(Type any character to close this window)\n"));
1345 open_console_window (void)
1347 if (((HANDLE) _get_osfhandle (fileno (stdout)) == INVALID_HANDLE_VALUE ||
1348 (HANDLE) _get_osfhandle (fileno (stderr)) == INVALID_HANDLE_VALUE) && AllocConsole ())
1350 if ((HANDLE) _get_osfhandle (fileno (stdout)) == INVALID_HANDLE_VALUE)
1351 freopen ("CONOUT$", "w", stdout);
1353 if ((HANDLE) _get_osfhandle (fileno (stderr)) == INVALID_HANDLE_VALUE)
1354 freopen ("CONOUT$", "w", stderr);
1356 SetConsoleTitleW (L"gdbus-daemon debug output.");
1358 atexit (wait_console_window);
1362 idle_timeout_cb (GDBusDaemon *daemon, gpointer user_data)
1364 GMainLoop *loop = user_data;
1365 g_main_loop_quit (loop);
1368 __declspec(dllexport) void CALLBACK g_win32_run_session_bus (HWND hwnd, HINSTANCE hinst, char *cmdline, int nCmdShow);
1370 __declspec(dllexport) void CALLBACK
1371 g_win32_run_session_bus (HWND hwnd, HINSTANCE hinst, char *cmdline, int nCmdShow)
1373 GDBusDaemon *daemon;
1375 const char *address;
1376 GError *error = NULL;
1378 if (g_getenv ("GDBUS_DAEMON_DEBUG") != NULL)
1379 open_console_window ();
1381 loop = g_main_loop_new (NULL, FALSE);
1383 address = "nonce-tcp:";
1384 daemon = _g_dbus_daemon_new (address, NULL, &error);
1387 g_printerr ("Can't init bus: %s\n", error->message);
1391 g_signal_connect (daemon, "idle-timeout", G_CALLBACK (idle_timeout_cb), loop);
1393 if ( publish_session_bus (_g_dbus_daemon_get_address (daemon)))
1395 g_main_loop_run (loop);
1397 unpublish_session_bus ();
1400 g_main_loop_unref (loop);
1401 g_object_unref (daemon);
1405 get_session_address_dbus_launch (GError **error)
1407 HANDLE autolaunch_mutex, init_mutex;
1408 char *address = NULL;
1409 wchar_t gio_path[MAX_PATH+1+200];
1411 autolaunch_mutex = acquire_mutex (DBUS_AUTOLAUNCH_MUTEX);
1413 init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
1415 if (is_mutex_owned (DBUS_DAEMON_MUTEX))
1416 address = read_shm (DBUS_DAEMON_ADDRESS_INFO);
1418 release_mutex (init_mutex);
1420 if (address == NULL)
1422 gio_path[MAX_PATH] = 0;
1423 if (GetModuleFileNameW (_g_io_win32_get_module (), gio_path, MAX_PATH))
1425 PROCESS_INFORMATION pi = { 0 };
1426 STARTUPINFOW si = { 0 };
1428 wchar_t gio_path_short[MAX_PATH];
1429 wchar_t rundll_path[MAX_PATH*2];
1430 wchar_t args[MAX_PATH*4];
1432 GetShortPathNameW (gio_path, gio_path_short, MAX_PATH);
1434 GetWindowsDirectoryW (rundll_path, MAX_PATH);
1435 wcscat (rundll_path, L"\\rundll32.exe");
1436 if (GetFileAttributesW (rundll_path) == INVALID_FILE_ATTRIBUTES)
1438 GetSystemDirectoryW (rundll_path, MAX_PATH);
1439 wcscat (rundll_path, L"\\rundll32.exe");
1442 wcscpy (args, L"\"");
1443 wcscat (args, rundll_path);
1444 wcscat (args, L"\" ");
1445 wcscat (args, gio_path_short);
1446 #if defined(_WIN64) || defined(_M_X64) || defined(_M_AMD64)
1447 wcscat (args, L",g_win32_run_session_bus");
1448 #elif defined (_MSC_VER)
1449 wcscat (args, L",_g_win32_run_session_bus@16");
1451 wcscat (args, L",g_win32_run_session_bus@16");
1454 res = CreateProcessW (rundll_path, args,
1456 NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW | DETACHED_PROCESS,
1457 0, NULL /* TODO: Should be root */,
1460 address = read_shm (DBUS_DAEMON_ADDRESS_INFO);
1464 release_mutex (autolaunch_mutex);
1466 if (address == NULL)
1470 _("Session dbus not running, and autolaunch failed"));
1476 /* ---------------------------------------------------------------------------------------------------- */
1479 get_session_address_platform_specific (GError **error)
1482 #if defined (G_OS_UNIX) || defined(G_OS_WIN32)
1483 /* need to handle OS X in a different way since 'dbus-launch --autolaunch' probably won't work there */
1484 ret = get_session_address_dbus_launch (error);
1486 /* TODO: implement for OS X */
1491 _("Cannot determine session bus address (not implemented for this OS)"));
1496 /* ---------------------------------------------------------------------------------------------------- */
1499 * g_dbus_address_get_for_bus_sync:
1500 * @bus_type: a #GBusType
1501 * @cancellable: (allow-none): a #GCancellable or %NULL
1502 * @error: return location for error or %NULL
1504 * Synchronously looks up the D-Bus address for the well-known message
1505 * bus instance specified by @bus_type. This may involve using various
1506 * platform specific mechanisms.
1508 * Returns: a valid D-Bus address string for @bus_type or %NULL if
1514 g_dbus_address_get_for_bus_sync (GBusType bus_type,
1515 GCancellable *cancellable,
1519 const gchar *system_bus;
1520 const gchar *session_bus;
1521 const gchar *starter_bus;
1522 GError *local_error;
1524 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1529 if (G_UNLIKELY (_g_dbus_debug_address ()))
1532 _g_dbus_debug_print_lock ();
1533 g_print ("GDBus-debug:Address: In g_dbus_address_get_for_bus_sync() for bus type '%s'\n",
1534 _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type));
1535 for (n = 0; n < 3; n++)
1541 case 0: k = "DBUS_SESSION_BUS_ADDRESS"; break;
1542 case 1: k = "DBUS_SYSTEM_BUS_ADDRESS"; break;
1543 case 2: k = "DBUS_STARTER_BUS_TYPE"; break;
1544 default: g_assert_not_reached ();
1547 g_print ("GDBus-debug:Address: env var %s", k);
1549 g_print ("='%s'\n", v);
1551 g_print (" is not set\n");
1553 _g_dbus_debug_print_unlock ();
1558 case G_BUS_TYPE_SYSTEM:
1559 ret = g_strdup (g_getenv ("DBUS_SYSTEM_BUS_ADDRESS"));
1562 ret = g_strdup ("unix:path=/var/run/dbus/system_bus_socket");
1566 case G_BUS_TYPE_SESSION:
1567 ret = g_strdup (g_getenv ("DBUS_SESSION_BUS_ADDRESS"));
1570 ret = get_session_address_platform_specific (&local_error);
1574 case G_BUS_TYPE_MACHINE:
1575 system_bus = g_getenv ("DBUS_SYSTEM_BUS_ADDRESS");
1576 if (system_bus == NULL)
1577 ret = g_strdup ("kernel:path=/sys/fs/kdbus/0-system/bus;unix:path=/var/run/dbus/system_bus_socket");
1579 ret = g_strdup_printf ("kernel:path=/sys/fs/kdbus/0-system/bus;%s", system_bus);
1582 case G_BUS_TYPE_USER:
1583 session_bus = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
1584 if (session_bus == NULL)
1585 ret = g_strdup_printf ("kernel:path=%s/kdbus;%s", g_get_user_runtime_dir (),
1586 get_session_address_platform_specific (&local_error));
1588 ret = g_strdup_printf ("kernel:path=%s/kdbus;%s", g_get_user_runtime_dir (), session_bus);
1591 case G_BUS_TYPE_STARTER:
1592 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
1593 if (g_strcmp0 (starter_bus, "session") == 0)
1595 ret = g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SESSION, cancellable, &local_error);
1598 else if (g_strcmp0 (starter_bus, "system") == 0)
1600 ret = g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SYSTEM, cancellable, &local_error);
1605 if (starter_bus != NULL)
1607 g_set_error (&local_error,
1610 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
1611 " - unknown value '%s'"),
1616 g_set_error_literal (&local_error,
1619 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
1620 "variable is not set"));
1626 g_set_error (&local_error,
1629 _("Unknown bus type %d"),
1635 if (G_UNLIKELY (_g_dbus_debug_address ()))
1637 _g_dbus_debug_print_lock ();
1640 g_print ("GDBus-debug:Address: Returning address '%s' for bus type '%s'\n",
1642 _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type));
1646 g_print ("GDBus-debug:Address: Cannot look-up address bus type '%s': %s\n",
1647 _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type),
1648 local_error ? local_error->message : "");
1650 _g_dbus_debug_print_unlock ();
1653 if (local_error != NULL)
1654 g_propagate_error (error, local_error);
1660 * g_dbus_address_escape_value:
1661 * @string: an unescaped string to be included in a D-Bus address
1662 * as the value in a key-value pair
1664 * Escape @string so it can appear in a D-Bus address as the value
1665 * part of a key-value pair.
1667 * For instance, if @string is "/run/bus-for-:0",
1668 * this function would return "/run/bus-for-%3A0",
1669 * which could be used in a D-Bus address like
1670 * "unix:nonce-tcp:host=127.0.0.1,port=42,noncefile=/run/bus-for-%3A0".
1672 * Returns: (transfer full): a copy of @string with all
1673 * non-optionally-escaped bytes escaped
1678 g_dbus_address_escape_value (const gchar *string)
1683 g_return_val_if_fail (string != NULL, NULL);
1685 /* There will often not be anything needing escaping at all. */
1686 s = g_string_sized_new (strlen (string));
1688 /* D-Bus address escaping is mostly the same as URI escaping... */
1689 g_string_append_uri_escaped (s, string, "\\/", FALSE);
1691 /* ... but '~' is an unreserved character in URIs, but a
1692 * non-optionally-escaped character in D-Bus addresses. */
1693 for (i = 0; i < s->len; i++)
1695 if (G_UNLIKELY (s->str[i] == '~'))
1698 g_string_insert (s, i + 1, "7E");
1703 return g_string_free (s, FALSE);