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"
44 #include <gio/gunixsocketaddress.h>
45 #include <gio/gkdbusconnection.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_kdbus (const gchar *transport_name)
367 supported = g_strcmp0 (transport_name, "kernel") == 0;
373 * g_dbus_is_supported_address:
375 * @error: Return location for error or %NULL.
377 * Like g_dbus_is_address() but also checks if the library suppors the
378 * transports in @string and that key/value pairs for each transport
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 || g_dbus_is_supported_address_kdbus (transport_name))
415 supported = is_valid_unix (a[n], key_value_pairs, error);
416 else if (g_strcmp0 (transport_name, "tcp") == 0)
417 supported = is_valid_tcp (a[n], key_value_pairs, error);
418 else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
419 supported = is_valid_nonce_tcp (a[n], key_value_pairs, error);
420 else if (g_strcmp0 (a[n], "autolaunch:") == 0)
423 g_free (transport_name);
424 g_hash_table_unref (key_value_pairs);
435 g_assert (ret || (!ret && (error == NULL || *error != NULL)));
441 _g_dbus_address_parse_entry (const gchar *address_entry,
442 gchar **out_transport_name,
443 GHashTable **out_key_value_pairs,
447 GHashTable *key_value_pairs;
448 gchar *transport_name;
455 transport_name = NULL;
456 key_value_pairs = NULL;
458 s = strchr (address_entry, ':');
463 G_IO_ERROR_INVALID_ARGUMENT,
464 _("Address element '%s' does not contain a colon (:)"),
469 transport_name = g_strndup (address_entry, s - address_entry);
470 key_value_pairs = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
472 kv_pairs = g_strsplit (s + 1, ",", 0);
473 for (n = 0; kv_pairs != NULL && kv_pairs[n] != NULL; n++)
475 const gchar *kv_pair = kv_pairs[n];
479 s = strchr (kv_pair, '=');
484 G_IO_ERROR_INVALID_ARGUMENT,
485 _("Key/Value pair %d, '%s', in address element '%s' does not contain an equal sign"),
492 key = g_uri_unescape_segment (kv_pair, s, NULL);
493 value = g_uri_unescape_segment (s + 1, kv_pair + strlen (kv_pair), NULL);
494 if (key == NULL || value == NULL)
498 G_IO_ERROR_INVALID_ARGUMENT,
499 _("Error unescaping key or value in Key/Value pair %d, '%s', in address element '%s'"),
507 g_hash_table_insert (key_value_pairs, key, value);
513 g_strfreev (kv_pairs);
516 if (out_transport_name != NULL)
517 *out_transport_name = transport_name;
519 g_free (transport_name);
520 if (out_key_value_pairs != NULL)
521 *out_key_value_pairs = key_value_pairs;
522 else if (key_value_pairs != NULL)
523 g_hash_table_unref (key_value_pairs);
527 g_free (transport_name);
528 if (key_value_pairs != NULL)
529 g_hash_table_unref (key_value_pairs);
534 /* ---------------------------------------------------------------------------------------------------- */
537 g_dbus_address_try_connect_one (const gchar *address_entry,
539 GCancellable *cancellable,
542 /* TODO: Declare an extension point called GDBusTransport (or similar)
543 * and move code below to extensions implementing said extension
544 * point. That way we can implement a D-Bus transport over X11 without
545 * making libgio link to libX11...
548 g_dbus_address_connect (const gchar *address_entry,
549 const gchar *transport_name,
550 GHashTable *key_value_pairs,
551 GCancellable *cancellable,
555 GSocketConnectable *connectable;
556 const gchar *nonce_file;
566 if ((g_strcmp0 (transport_name, "unix") == 0)
567 || g_dbus_is_supported_address_kdbus (transport_name))
570 const gchar *abstract;
571 path = g_hash_table_lookup (key_value_pairs, "path");
572 abstract = g_hash_table_lookup (key_value_pairs, "abstract");
573 if ((path == NULL && abstract == NULL) || (path != NULL && abstract != NULL))
577 G_IO_ERROR_INVALID_ARGUMENT,
578 _("Error in address '%s' - the unix transport requires exactly one of the "
579 "keys 'path' or 'abstract' to be set"),
582 else if (path != NULL)
584 connectable = G_SOCKET_CONNECTABLE (g_unix_socket_address_new (path));
586 else if (abstract != NULL)
588 connectable = G_SOCKET_CONNECTABLE (g_unix_socket_address_new_with_type (abstract,
590 G_UNIX_SOCKET_ADDRESS_ABSTRACT));
594 g_assert_not_reached ();
598 else if (g_strcmp0 (transport_name, "tcp") == 0 || g_strcmp0 (transport_name, "nonce-tcp") == 0)
606 is_nonce = (g_strcmp0 (transport_name, "nonce-tcp") == 0);
608 host = g_hash_table_lookup (key_value_pairs, "host");
613 G_IO_ERROR_INVALID_ARGUMENT,
614 _("Error in address '%s' - the host attribute is missing or malformed"),
619 s = g_hash_table_lookup (key_value_pairs, "port");
622 port = strtol (s, &endp, 10);
623 if ((*s == '\0' || *endp != '\0') || port < 0 || port >= 65536)
627 G_IO_ERROR_INVALID_ARGUMENT,
628 _("Error in address '%s' - the port attribute is missing or malformed"),
636 nonce_file = g_hash_table_lookup (key_value_pairs, "noncefile");
637 if (nonce_file == NULL)
641 G_IO_ERROR_INVALID_ARGUMENT,
642 _("Error in address '%s' - the noncefile attribute is missing or malformed"),
648 /* TODO: deal with family key/value-pair */
649 connectable = g_network_address_new (host, port);
651 else if (g_strcmp0 (address_entry, "autolaunch:") == 0)
653 gchar *autolaunch_address;
654 autolaunch_address = get_session_address_platform_specific (error);
655 if (autolaunch_address != NULL)
657 ret = g_dbus_address_try_connect_one (autolaunch_address, NULL, cancellable, error);
658 g_free (autolaunch_address);
663 g_prefix_error (error, _("Error auto-launching: "));
670 G_IO_ERROR_INVALID_ARGUMENT,
671 _("Unknown or unsupported transport '%s' for address '%s'"),
676 if (connectable != NULL)
679 if (g_dbus_is_supported_address_kdbus (transport_name))
681 GKdbusConnection *connection;
685 path = g_hash_table_lookup (key_value_pairs, "path");
687 g_assert (ret == NULL);
688 connection = _g_kdbus_connection_new ();
689 status = _g_kdbus_connection_connect (connection,
693 g_object_unref (connectable);
698 ret = G_IO_STREAM (connection);
702 GSocketClient *client;
703 GSocketConnection *connection;
705 g_assert (ret == NULL);
706 client = g_socket_client_new ();
707 connection = g_socket_client_connect (client,
711 g_object_unref (connectable);
712 g_object_unref (client);
713 if (connection == NULL)
716 ret = G_IO_STREAM (connection);
719 if (nonce_file != NULL)
721 gchar nonce_contents[16 + 1];
722 size_t num_bytes_read;
725 /* be careful to read only 16 bytes - we also check that the file is only 16 bytes long */
726 f = fopen (nonce_file, "rb");
731 G_IO_ERROR_INVALID_ARGUMENT,
732 _("Error opening nonce file '%s': %s"),
735 g_object_unref (ret);
739 num_bytes_read = fread (nonce_contents,
743 if (num_bytes_read != 16)
745 if (num_bytes_read == 0)
749 G_IO_ERROR_INVALID_ARGUMENT,
750 _("Error reading from nonce file '%s': %s"),
758 G_IO_ERROR_INVALID_ARGUMENT,
759 _("Error reading from nonce file '%s', expected 16 bytes, got %d"),
761 (gint) num_bytes_read);
763 g_object_unref (ret);
770 if (!g_output_stream_write_all (g_io_stream_get_output_stream (ret),
777 g_prefix_error (error, _("Error writing contents of nonce file '%s' to stream:"), nonce_file);
778 g_object_unref (ret);
791 g_dbus_address_try_connect_one (const gchar *address_entry,
793 GCancellable *cancellable,
797 GHashTable *key_value_pairs;
798 gchar *transport_name;
802 transport_name = NULL;
803 key_value_pairs = NULL;
805 if (!_g_dbus_address_parse_entry (address_entry,
811 ret = g_dbus_address_connect (address_entry,
819 guid = g_hash_table_lookup (key_value_pairs, "guid");
820 if (guid != NULL && out_guid != NULL)
821 *out_guid = g_strdup (guid);
824 g_free (transport_name);
825 if (key_value_pairs != NULL)
826 g_hash_table_unref (key_value_pairs);
831 /* ---------------------------------------------------------------------------------------------------- */
840 get_stream_data_free (GetStreamData *data)
842 g_free (data->address);
843 if (data->stream != NULL)
844 g_object_unref (data->stream);
850 get_stream_thread_func (GSimpleAsyncResult *res,
852 GCancellable *cancellable)
857 data = g_simple_async_result_get_op_res_gpointer (res);
860 data->stream = g_dbus_address_get_stream_sync (data->address,
864 if (data->stream == NULL)
865 g_simple_async_result_take_error (res, error);
869 * g_dbus_address_get_stream:
870 * @address: A valid D-Bus address.
871 * @cancellable: (allow-none): A #GCancellable or %NULL.
872 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
873 * @user_data: Data to pass to @callback.
875 * Asynchronously connects to an endpoint specified by @address and
876 * sets up the connection so it is in a state to run the client-side
877 * of the D-Bus authentication conversation.
879 * When the operation is finished, @callback will be invoked. You can
880 * then call g_dbus_address_get_stream_finish() to get the result of
883 * This is an asynchronous failable function. See
884 * g_dbus_address_get_stream_sync() for the synchronous version.
889 g_dbus_address_get_stream (const gchar *address,
890 GCancellable *cancellable,
891 GAsyncReadyCallback callback,
894 GSimpleAsyncResult *res;
897 g_return_if_fail (address != NULL);
899 res = g_simple_async_result_new (NULL,
902 g_dbus_address_get_stream);
903 g_simple_async_result_set_check_cancellable (res, cancellable);
904 data = g_new0 (GetStreamData, 1);
905 data->address = g_strdup (address);
906 g_simple_async_result_set_op_res_gpointer (res,
908 (GDestroyNotify) get_stream_data_free);
909 g_simple_async_result_run_in_thread (res,
910 get_stream_thread_func,
913 g_object_unref (res);
917 * g_dbus_address_get_stream_finish:
918 * @res: A #GAsyncResult obtained from the GAsyncReadyCallback passed to g_dbus_address_get_stream().
919 * @out_guid: %NULL or return location to store the GUID extracted from @address, if any.
920 * @error: Return location for error or %NULL.
922 * Finishes an operation started with g_dbus_address_get_stream().
924 * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
929 g_dbus_address_get_stream_finish (GAsyncResult *res,
933 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
937 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
938 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
940 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_address_get_stream);
944 data = g_simple_async_result_get_op_res_gpointer (simple);
945 if (g_simple_async_result_propagate_error (simple, error))
948 ret = g_object_ref (data->stream);
949 if (out_guid != NULL)
950 *out_guid = g_strdup (data->guid);
957 * g_dbus_address_get_stream_sync:
958 * @address: A valid D-Bus address.
959 * @out_guid: %NULL or return location to store the GUID extracted from @address, if any.
960 * @cancellable: (allow-none): A #GCancellable or %NULL.
961 * @error: Return location for error or %NULL.
963 * Synchronously connects to an endpoint specified by @address and
964 * sets up the connection so it is in a state to run the client-side
965 * of the D-Bus authentication conversation.
967 * This is a synchronous failable function. See
968 * g_dbus_address_get_stream() for the asynchronous version.
970 * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
975 g_dbus_address_get_stream_sync (const gchar *address,
977 GCancellable *cancellable,
985 g_return_val_if_fail (address != NULL, NULL);
986 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
991 addr_array = g_strsplit (address, ";", 0);
992 if (addr_array != NULL && addr_array[0] == NULL)
994 last_error = g_error_new_literal (G_IO_ERROR,
995 G_IO_ERROR_INVALID_ARGUMENT,
996 _("The given address is empty"));
1000 for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
1002 const gchar *addr = addr_array[n];
1006 ret = g_dbus_address_try_connect_one (addr,
1016 g_assert (this_error != NULL);
1017 if (last_error != NULL)
1018 g_error_free (last_error);
1019 last_error = this_error;
1026 if (last_error != NULL)
1027 g_error_free (last_error);
1031 g_assert (last_error != NULL);
1032 g_propagate_error (error, last_error);
1035 g_strfreev (addr_array);
1039 /* ---------------------------------------------------------------------------------------------------- */
1043 get_session_address_dbus_launch (GError **error)
1047 gchar *command_line;
1048 gchar *launch_stdout;
1049 gchar *launch_stderr;
1051 gchar *old_dbus_verbose;
1052 gboolean restore_dbus_verbose;
1056 command_line = NULL;
1057 launch_stdout = NULL;
1058 launch_stderr = NULL;
1059 restore_dbus_verbose = FALSE;
1060 old_dbus_verbose = NULL;
1062 /* Don't run binaries as root if we're setuid. */
1063 if (GLIB_PRIVATE_CALL (g_check_setuid) ())
1065 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1066 _("Cannot spawn a message bus when setuid"));
1070 machine_id = _g_dbus_get_machine_id (error);
1071 if (machine_id == NULL)
1073 g_prefix_error (error, _("Cannot spawn a message bus without a machine-id: "));
1077 /* We're using private libdbus facilities here. When everything
1078 * (X11, Mac OS X, Windows) is spec'ed out correctly (not even the
1079 * X11 property is correctly documented right now) we should
1080 * consider using the spec instead of dbus-launch.
1082 * --autolaunch=MACHINEID
1083 * This option implies that dbus-launch should scan for a previ‐
1084 * ously-started session and reuse the values found there. If no
1085 * session is found, it will start a new session. The --exit-with-
1086 * session option is implied if --autolaunch is given. This option
1087 * is for the exclusive use of libdbus, you do not want to use it
1088 * manually. It may change in the future.
1091 /* TODO: maybe provide a variable for where to look for the dbus-launch binary? */
1092 command_line = g_strdup_printf ("dbus-launch --autolaunch=%s --binary-syntax --close-stderr", machine_id);
1094 if (G_UNLIKELY (_g_dbus_debug_address ()))
1096 _g_dbus_debug_print_lock ();
1097 g_print ("GDBus-debug:Address: Running '%s' to get bus address (possibly autolaunching)\n", command_line);
1098 old_dbus_verbose = g_strdup (g_getenv ("DBUS_VERBOSE"));
1099 restore_dbus_verbose = TRUE;
1100 g_setenv ("DBUS_VERBOSE", "1", TRUE);
1101 _g_dbus_debug_print_unlock ();
1104 if (!g_spawn_command_line_sync (command_line,
1113 if (!g_spawn_check_exit_status (exit_status, error))
1115 g_prefix_error (error, _("Error spawning command line '%s': "), command_line);
1119 /* From the dbus-launch(1) man page:
1121 * --binary-syntax Write to stdout a nul-terminated bus address,
1122 * then the bus PID as a binary integer of size sizeof(pid_t),
1123 * then the bus X window ID as a binary integer of size
1124 * sizeof(long). Integers are in the machine's byte order, not
1125 * network byte order or any other canonical byte order.
1127 ret = g_strdup (launch_stdout);
1130 if (G_UNLIKELY (_g_dbus_debug_address ()))
1133 _g_dbus_debug_print_lock ();
1134 g_print ("GDBus-debug:Address: dbus-launch output:");
1135 if (launch_stdout != NULL)
1137 s = _g_dbus_hexdump (launch_stdout, strlen (launch_stdout) + 1 + sizeof (pid_t) + sizeof (long), 2);
1138 g_print ("\n%s", s);
1143 g_print (" (none)\n");
1145 g_print ("GDBus-debug:Address: dbus-launch stderr output:");
1146 if (launch_stderr != NULL)
1147 g_print ("\n%s", launch_stderr);
1149 g_print (" (none)\n");
1150 _g_dbus_debug_print_unlock ();
1153 g_free (machine_id);
1154 g_free (command_line);
1155 g_free (launch_stdout);
1156 g_free (launch_stderr);
1157 if (G_UNLIKELY (restore_dbus_verbose))
1159 if (old_dbus_verbose != NULL)
1160 g_setenv ("DBUS_VERBOSE", old_dbus_verbose, TRUE);
1162 g_unsetenv ("DBUS_VERBOSE");
1164 g_free (old_dbus_verbose);
1171 #define DBUS_DAEMON_ADDRESS_INFO "DBusDaemonAddressInfo"
1172 #define DBUS_DAEMON_MUTEX "DBusDaemonMutex"
1173 #define UNIQUE_DBUS_INIT_MUTEX "UniqueDBusInitMutex"
1174 #define DBUS_AUTOLAUNCH_MUTEX "DBusAutolaunchMutex"
1177 release_mutex (HANDLE mutex)
1179 ReleaseMutex (mutex);
1180 CloseHandle (mutex);
1184 acquire_mutex (const char *mutexname)
1189 mutex = CreateMutexA (NULL, FALSE, mutexname);
1193 res = WaitForSingleObject (mutex, INFINITE);
1196 case WAIT_ABANDONED:
1197 release_mutex (mutex);
1208 is_mutex_owned (const char *mutexname)
1211 gboolean res = FALSE;
1213 mutex = CreateMutexA (NULL, FALSE, mutexname);
1214 if (WaitForSingleObject (mutex, 10) == WAIT_TIMEOUT)
1217 ReleaseMutex (mutex);
1218 CloseHandle (mutex);
1224 read_shm (const char *shm_name)
1233 for (i = 0; i < 20; i++)
1235 shared_mem = OpenFileMappingA (FILE_MAP_READ, FALSE, shm_name);
1236 if (shared_mem != 0)
1241 if (shared_mem != 0)
1243 shared_data = MapViewOfFile (shared_mem, FILE_MAP_READ, 0, 0, 0);
1244 if (shared_data != NULL)
1246 res = g_strdup (shared_data);
1247 UnmapViewOfFile (shared_data);
1249 CloseHandle (shared_mem);
1256 set_shm (const char *shm_name, const char *value)
1261 shared_mem = CreateFileMappingA (INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
1262 0, strlen (value) + 1, shm_name);
1263 if (shared_mem == 0)
1266 shared_data = MapViewOfFile (shared_mem, FILE_MAP_WRITE, 0, 0, 0 );
1267 if (shared_data == NULL)
1270 strcpy (shared_data, value);
1272 UnmapViewOfFile (shared_data);
1277 /* These keep state between publish_session_bus and unpublish_session_bus */
1278 static HANDLE published_daemon_mutex;
1279 static HANDLE published_shared_mem;
1282 publish_session_bus (const char *address)
1286 init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
1288 published_daemon_mutex = CreateMutexA (NULL, FALSE, DBUS_DAEMON_MUTEX);
1289 if (WaitForSingleObject (published_daemon_mutex, 10 ) != WAIT_OBJECT_0)
1291 release_mutex (init_mutex);
1292 CloseHandle (published_daemon_mutex);
1293 published_daemon_mutex = NULL;
1297 published_shared_mem = set_shm (DBUS_DAEMON_ADDRESS_INFO, address);
1298 if (!published_shared_mem)
1300 release_mutex (init_mutex);
1301 CloseHandle (published_daemon_mutex);
1302 published_daemon_mutex = NULL;
1306 release_mutex (init_mutex);
1311 unpublish_session_bus (void)
1315 init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
1317 CloseHandle (published_shared_mem);
1318 published_shared_mem = NULL;
1320 release_mutex (published_daemon_mutex);
1321 published_daemon_mutex = NULL;
1323 release_mutex (init_mutex);
1327 wait_console_window (void)
1329 FILE *console = fopen ("CONOUT$", "w");
1331 SetConsoleTitleW (L"gdbus-daemon output. Type any character to close this window.");
1332 fprintf (console, _("(Type any character to close this window)\n"));
1338 open_console_window (void)
1340 if (((HANDLE) _get_osfhandle (fileno (stdout)) == INVALID_HANDLE_VALUE ||
1341 (HANDLE) _get_osfhandle (fileno (stderr)) == INVALID_HANDLE_VALUE) && AllocConsole ())
1343 if ((HANDLE) _get_osfhandle (fileno (stdout)) == INVALID_HANDLE_VALUE)
1344 freopen ("CONOUT$", "w", stdout);
1346 if ((HANDLE) _get_osfhandle (fileno (stderr)) == INVALID_HANDLE_VALUE)
1347 freopen ("CONOUT$", "w", stderr);
1349 SetConsoleTitleW (L"gdbus-daemon debug output.");
1351 atexit (wait_console_window);
1355 idle_timeout_cb (GDBusDaemon *daemon, gpointer user_data)
1357 GMainLoop *loop = user_data;
1358 g_main_loop_quit (loop);
1361 __declspec(dllexport) void CALLBACK g_win32_run_session_bus (HWND hwnd, HINSTANCE hinst, char *cmdline, int nCmdShow);
1363 __declspec(dllexport) void CALLBACK
1364 g_win32_run_session_bus (HWND hwnd, HINSTANCE hinst, char *cmdline, int nCmdShow)
1366 GDBusDaemon *daemon;
1368 const char *address;
1369 GError *error = NULL;
1371 if (g_getenv ("GDBUS_DAEMON_DEBUG") != NULL)
1372 open_console_window ();
1374 loop = g_main_loop_new (NULL, FALSE);
1376 address = "nonce-tcp:";
1377 daemon = _g_dbus_daemon_new (address, NULL, &error);
1380 g_printerr ("Can't init bus: %s\n", error->message);
1384 g_signal_connect (daemon, "idle-timeout", G_CALLBACK (idle_timeout_cb), loop);
1386 if ( publish_session_bus (_g_dbus_daemon_get_address (daemon)))
1388 g_main_loop_run (loop);
1390 unpublish_session_bus ();
1393 g_main_loop_unref (loop);
1394 g_object_unref (daemon);
1398 get_session_address_dbus_launch (GError **error)
1400 HANDLE autolaunch_mutex, init_mutex;
1401 char *address = NULL;
1402 wchar_t gio_path[MAX_PATH+1+200];
1404 autolaunch_mutex = acquire_mutex (DBUS_AUTOLAUNCH_MUTEX);
1406 init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
1408 if (is_mutex_owned (DBUS_DAEMON_MUTEX))
1409 address = read_shm (DBUS_DAEMON_ADDRESS_INFO);
1411 release_mutex (init_mutex);
1413 if (address == NULL)
1415 gio_path[MAX_PATH] = 0;
1416 if (GetModuleFileNameW (_g_io_win32_get_module (), gio_path, MAX_PATH))
1418 PROCESS_INFORMATION pi = { 0 };
1419 STARTUPINFOW si = { 0 };
1421 wchar_t gio_path_short[MAX_PATH];
1422 wchar_t rundll_path[MAX_PATH*2];
1423 wchar_t args[MAX_PATH*4];
1425 GetShortPathNameW (gio_path, gio_path_short, MAX_PATH);
1427 GetWindowsDirectoryW (rundll_path, MAX_PATH);
1428 wcscat (rundll_path, L"\\rundll32.exe");
1429 if (GetFileAttributesW (rundll_path) == INVALID_FILE_ATTRIBUTES)
1431 GetSystemDirectoryW (rundll_path, MAX_PATH);
1432 wcscat (rundll_path, L"\\rundll32.exe");
1435 wcscpy (args, L"\"");
1436 wcscat (args, rundll_path);
1437 wcscat (args, L"\" ");
1438 wcscat (args, gio_path_short);
1439 #if defined(_WIN64) || defined(_M_X64) || defined(_M_AMD64)
1440 wcscat (args, L",g_win32_run_session_bus");
1441 #elif defined (_MSC_VER)
1442 wcscat (args, L",_g_win32_run_session_bus@16");
1444 wcscat (args, L",g_win32_run_session_bus@16");
1447 res = CreateProcessW (rundll_path, args,
1449 NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW | DETACHED_PROCESS,
1450 0, NULL /* TODO: Should be root */,
1453 address = read_shm (DBUS_DAEMON_ADDRESS_INFO);
1457 release_mutex (autolaunch_mutex);
1459 if (address == NULL)
1463 _("Session dbus not running, and autolaunch failed"));
1469 /* ---------------------------------------------------------------------------------------------------- */
1472 get_session_address_platform_specific (GError **error)
1475 #if defined (G_OS_UNIX) || defined(G_OS_WIN32)
1476 /* need to handle OS X in a different way since 'dbus-launch --autolaunch' probably won't work there */
1477 ret = get_session_address_dbus_launch (error);
1479 /* TODO: implement for OS X */
1484 _("Cannot determine session bus address (not implemented for this OS)"));
1489 /* ---------------------------------------------------------------------------------------------------- */
1492 * g_dbus_address_get_for_bus_sync:
1493 * @bus_type: a #GBusType
1494 * @cancellable: (allow-none): a #GCancellable or %NULL
1495 * @error: return location for error or %NULL
1497 * Synchronously looks up the D-Bus address for the well-known message
1498 * bus instance specified by @bus_type. This may involve using various
1499 * platform specific mechanisms.
1501 * Returns: a valid D-Bus address string for @bus_type or %NULL if
1507 g_dbus_address_get_for_bus_sync (GBusType bus_type,
1508 GCancellable *cancellable,
1512 const gchar *system_bus;
1513 const gchar *session_bus;
1514 const gchar *starter_bus;
1515 GError *local_error;
1517 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1522 if (G_UNLIKELY (_g_dbus_debug_address ()))
1525 _g_dbus_debug_print_lock ();
1526 g_print ("GDBus-debug:Address: In g_dbus_address_get_for_bus_sync() for bus type '%s'\n",
1527 _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type));
1528 for (n = 0; n < 3; n++)
1534 case 0: k = "DBUS_SESSION_BUS_ADDRESS"; break;
1535 case 1: k = "DBUS_SYSTEM_BUS_ADDRESS"; break;
1536 case 2: k = "DBUS_STARTER_BUS_TYPE"; break;
1537 default: g_assert_not_reached ();
1540 g_print ("GDBus-debug:Address: env var %s", k);
1542 g_print ("='%s'\n", v);
1544 g_print (" is not set\n");
1546 _g_dbus_debug_print_unlock ();
1551 case G_BUS_TYPE_SYSTEM:
1552 ret = g_strdup (g_getenv ("DBUS_SYSTEM_BUS_ADDRESS"));
1555 ret = g_strdup ("unix:path=/var/run/dbus/system_bus_socket");
1559 case G_BUS_TYPE_SESSION:
1560 ret = g_strdup (g_getenv ("DBUS_SESSION_BUS_ADDRESS"));
1563 ret = get_session_address_platform_specific (&local_error);
1567 case G_BUS_TYPE_MACHINE:
1568 system_bus = g_getenv ("DBUS_SYSTEM_BUS_ADDRESS");
1569 if (system_bus == NULL)
1570 ret = g_strdup ("kernel:path=/sys/fs/kdbus/0-system/bus;unix:path=/var/run/dbus/system_bus_socket");
1572 ret = g_strdup_printf ("kernel:path=/sys/fs/kdbus/0-system/bus;%s", system_bus);
1575 case G_BUS_TYPE_USER:
1576 session_bus = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
1577 if (session_bus == NULL)
1578 ret = g_strdup_printf ("kernel:path=/sys/fs/kdbus/%d-user/bus;%s", getuid(),
1579 get_session_address_platform_specific (&local_error));
1581 ret = g_strdup_printf ("kernel:path=/sys/fs/kdbus/%d-user/bus;%s", getuid(), session_bus);
1584 case G_BUS_TYPE_STARTER:
1585 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
1586 if (g_strcmp0 (starter_bus, "session") == 0)
1588 ret = g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SESSION, cancellable, &local_error);
1591 else if (g_strcmp0 (starter_bus, "system") == 0)
1593 ret = g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SYSTEM, cancellable, &local_error);
1598 if (starter_bus != NULL)
1600 g_set_error (&local_error,
1603 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
1604 " - unknown value '%s'"),
1609 g_set_error_literal (&local_error,
1612 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
1613 "variable is not set"));
1619 g_set_error (&local_error,
1622 _("Unknown bus type %d"),
1628 if (G_UNLIKELY (_g_dbus_debug_address ()))
1630 _g_dbus_debug_print_lock ();
1633 g_print ("GDBus-debug:Address: Returning address '%s' for bus type '%s'\n",
1635 _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type));
1639 g_print ("GDBus-debug:Address: Cannot look-up address bus type '%s': %s\n",
1640 _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type),
1641 local_error ? local_error->message : "");
1643 _g_dbus_debug_print_unlock ();
1646 if (local_error != NULL)
1647 g_propagate_error (error, local_error);
1653 * g_dbus_address_escape_value:
1654 * @string: an unescaped string to be included in a D-Bus address
1655 * as the value in a key-value pair
1657 * Escape @string so it can appear in a D-Bus address as the value
1658 * part of a key-value pair.
1660 * For instance, if @string is "/run/bus-for-:0",
1661 * this function would return "/run/bus-for-%3A0",
1662 * which could be used in a D-Bus address like
1663 * "unix:nonce-tcp:host=127.0.0.1,port=42,noncefile=/run/bus-for-%3A0".
1665 * Returns: (transfer full): a copy of @string with all
1666 * non-optionally-escaped bytes escaped
1671 g_dbus_address_escape_value (const gchar *string)
1676 g_return_val_if_fail (string != NULL, NULL);
1678 /* There will often not be anything needing escaping at all. */
1679 s = g_string_sized_new (strlen (string));
1681 /* D-Bus address escaping is mostly the same as URI escaping... */
1682 g_string_append_uri_escaped (s, string, "\\/", FALSE);
1684 /* ... but '~' is an unreserved character in URIs, but a
1685 * non-optionally-escaped character in D-Bus addresses. */
1686 for (i = 0; i < s->len; i++)
1688 if (G_UNLIKELY (s->str[i] == '~'))
1691 g_string_insert (s, i + 1, "7E");
1696 return g_string_free (s, FALSE);