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>
56 * SECTION:gdbusaddress
57 * @title: D-Bus Addresses
58 * @short_description: D-Bus connection endpoints
61 * Routines for working with D-Bus addresses. A D-Bus address is a string
62 * like "unix:tmpdir=/tmp/my-app-name". The exact format of addresses
63 * is explained in detail in the [D-Bus specification](http://dbus.freedesktop.org/doc/dbus-specification.html\#addresses).
66 static gchar *get_session_address_platform_specific (GError **error);
68 /* ---------------------------------------------------------------------------------------------------- */
74 * Checks if @string is a D-Bus address.
76 * This doesn't check if @string is actually supported by #GDBusServer
77 * or #GDBusConnection - use g_dbus_is_supported_address() to do more
80 * Returns: %TRUE if @string is a valid D-Bus address, %FALSE otherwise.
85 g_dbus_is_address (const gchar *string)
93 g_return_val_if_fail (string != NULL, FALSE);
95 a = g_strsplit (string, ";", 0);
99 for (n = 0; a[n] != NULL; n++)
101 if (!_g_dbus_address_parse_entry (a[n],
116 is_valid_unix (const gchar *address_entry,
117 GHashTable *key_value_pairs,
125 const gchar *abstract;
133 keys = g_hash_table_get_keys (key_value_pairs);
134 for (l = keys; l != NULL; l = l->next)
136 const gchar *key = l->data;
137 if (g_strcmp0 (key, "path") == 0)
138 path = g_hash_table_lookup (key_value_pairs, key);
139 else if (g_strcmp0 (key, "tmpdir") == 0)
140 tmpdir = g_hash_table_lookup (key_value_pairs, key);
141 else if (g_strcmp0 (key, "abstract") == 0)
142 abstract = g_hash_table_lookup (key_value_pairs, key);
147 G_IO_ERROR_INVALID_ARGUMENT,
148 _("Unsupported key '%s' in address entry '%s'"),
157 if (tmpdir != NULL || abstract != NULL)
160 else if (tmpdir != NULL)
162 if (path != NULL || abstract != NULL)
165 else if (abstract != NULL)
167 if (path != NULL || tmpdir != NULL)
174 G_IO_ERROR_INVALID_ARGUMENT,
175 _("Address '%s' is invalid (need exactly one of path, tmpdir or abstract keys)"),
187 G_IO_ERROR_INVALID_ARGUMENT,
188 _("Meaningless key/value pair combination in address entry '%s'"),
198 is_valid_nonce_tcp (const gchar *address_entry,
199 GHashTable *key_value_pairs,
208 const gchar *nonce_file;
219 keys = g_hash_table_get_keys (key_value_pairs);
220 for (l = keys; l != NULL; l = l->next)
222 const gchar *key = l->data;
223 if (g_strcmp0 (key, "host") == 0)
224 host = g_hash_table_lookup (key_value_pairs, key);
225 else if (g_strcmp0 (key, "port") == 0)
226 port = g_hash_table_lookup (key_value_pairs, key);
227 else if (g_strcmp0 (key, "family") == 0)
228 family = g_hash_table_lookup (key_value_pairs, key);
229 else if (g_strcmp0 (key, "noncefile") == 0)
230 nonce_file = g_hash_table_lookup (key_value_pairs, key);
235 G_IO_ERROR_INVALID_ARGUMENT,
236 _("Unsupported key '%s' in address entry '%s'"),
245 port_num = strtol (port, &endp, 10);
246 if ((*port == '\0' || *endp != '\0') || port_num < 0 || port_num >= 65536)
250 G_IO_ERROR_INVALID_ARGUMENT,
251 _("Error in address '%s' - the port attribute is malformed"),
257 if (family != NULL && !(g_strcmp0 (family, "ipv4") == 0 || g_strcmp0 (family, "ipv6") == 0))
261 G_IO_ERROR_INVALID_ARGUMENT,
262 _("Error in address '%s' - the family attribute is malformed"),
269 /* TODO: validate host */
272 nonce_file = nonce_file; /* To avoid -Wunused-but-set-variable */
283 is_valid_tcp (const gchar *address_entry,
284 GHashTable *key_value_pairs,
302 keys = g_hash_table_get_keys (key_value_pairs);
303 for (l = keys; l != NULL; l = l->next)
305 const gchar *key = l->data;
306 if (g_strcmp0 (key, "host") == 0)
307 host = g_hash_table_lookup (key_value_pairs, key);
308 else if (g_strcmp0 (key, "port") == 0)
309 port = g_hash_table_lookup (key_value_pairs, key);
310 else if (g_strcmp0 (key, "family") == 0)
311 family = g_hash_table_lookup (key_value_pairs, key);
316 G_IO_ERROR_INVALID_ARGUMENT,
317 _("Unsupported key '%s' in address entry '%s'"),
326 port_num = strtol (port, &endp, 10);
327 if ((*port == '\0' || *endp != '\0') || port_num < 0 || port_num >= 65536)
331 G_IO_ERROR_INVALID_ARGUMENT,
332 _("Error in address '%s' - the port attribute is malformed"),
338 if (family != NULL && !(g_strcmp0 (family, "ipv4") == 0 || g_strcmp0 (family, "ipv6") == 0))
342 G_IO_ERROR_INVALID_ARGUMENT,
343 _("Error in address '%s' - the family attribute is malformed"),
350 /* TODO: validate host */
362 * g_dbus_is_supported_address:
364 * @error: Return location for error or %NULL.
366 * Like g_dbus_is_address() but also checks if the library suppors the
367 * transports in @string and that key/value pairs for each transport
370 * Returns: %TRUE if @string is a valid D-Bus address that is
371 * supported by this library, %FALSE if @error is set.
376 g_dbus_is_supported_address (const gchar *string,
385 g_return_val_if_fail (string != NULL, FALSE);
386 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
388 a = g_strsplit (string, ";", 0);
389 for (n = 0; a[n] != NULL; n++)
391 gchar *transport_name;
392 GHashTable *key_value_pairs;
395 if (!_g_dbus_address_parse_entry (a[n],
402 if (g_strcmp0 (transport_name, "unix") == 0)
403 supported = is_valid_unix (a[n], key_value_pairs, error);
404 else if (g_strcmp0 (transport_name, "tcp") == 0)
405 supported = is_valid_tcp (a[n], key_value_pairs, error);
406 else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
407 supported = is_valid_nonce_tcp (a[n], key_value_pairs, error);
408 else if (g_strcmp0 (a[n], "autolaunch:") == 0)
411 g_free (transport_name);
412 g_hash_table_unref (key_value_pairs);
423 g_assert (ret || (!ret && (error == NULL || *error != NULL)));
429 _g_dbus_address_parse_entry (const gchar *address_entry,
430 gchar **out_transport_name,
431 GHashTable **out_key_value_pairs,
435 GHashTable *key_value_pairs;
436 gchar *transport_name;
443 transport_name = NULL;
444 key_value_pairs = NULL;
446 s = strchr (address_entry, ':');
451 G_IO_ERROR_INVALID_ARGUMENT,
452 _("Address element '%s' does not contain a colon (:)"),
457 transport_name = g_strndup (address_entry, s - address_entry);
458 key_value_pairs = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
460 kv_pairs = g_strsplit (s + 1, ",", 0);
461 for (n = 0; kv_pairs != NULL && kv_pairs[n] != NULL; n++)
463 const gchar *kv_pair = kv_pairs[n];
467 s = strchr (kv_pair, '=');
472 G_IO_ERROR_INVALID_ARGUMENT,
473 _("Key/Value pair %d, '%s', in address element '%s' does not contain an equal sign"),
480 key = g_uri_unescape_segment (kv_pair, s, NULL);
481 value = g_uri_unescape_segment (s + 1, kv_pair + strlen (kv_pair), NULL);
482 if (key == NULL || value == NULL)
486 G_IO_ERROR_INVALID_ARGUMENT,
487 _("Error unescaping key or value in Key/Value pair %d, '%s', in address element '%s'"),
495 g_hash_table_insert (key_value_pairs, key, value);
501 g_strfreev (kv_pairs);
504 if (out_transport_name != NULL)
505 *out_transport_name = transport_name;
507 g_free (transport_name);
508 if (out_key_value_pairs != NULL)
509 *out_key_value_pairs = key_value_pairs;
510 else if (key_value_pairs != NULL)
511 g_hash_table_unref (key_value_pairs);
515 g_free (transport_name);
516 if (key_value_pairs != NULL)
517 g_hash_table_unref (key_value_pairs);
522 /* ---------------------------------------------------------------------------------------------------- */
525 g_dbus_address_try_connect_one (const gchar *address_entry,
527 GCancellable *cancellable,
530 /* TODO: Declare an extension point called GDBusTransport (or similar)
531 * and move code below to extensions implementing said extension
532 * point. That way we can implement a D-Bus transport over X11 without
533 * making libgio link to libX11...
536 g_dbus_address_connect (const gchar *address_entry,
537 const gchar *transport_name,
538 GHashTable *key_value_pairs,
539 GCancellable *cancellable,
543 GSocketConnectable *connectable;
544 const gchar *nonce_file;
554 else if (g_strcmp0 (transport_name, "unix") == 0)
557 const gchar *abstract;
558 path = g_hash_table_lookup (key_value_pairs, "path");
559 abstract = g_hash_table_lookup (key_value_pairs, "abstract");
560 if ((path == NULL && abstract == NULL) || (path != NULL && abstract != NULL))
564 G_IO_ERROR_INVALID_ARGUMENT,
565 _("Error in address '%s' - the unix transport requires exactly one of the "
566 "keys 'path' or 'abstract' to be set"),
569 else if (path != NULL)
571 connectable = G_SOCKET_CONNECTABLE (g_unix_socket_address_new (path));
573 else if (abstract != NULL)
575 connectable = G_SOCKET_CONNECTABLE (g_unix_socket_address_new_with_type (abstract,
577 G_UNIX_SOCKET_ADDRESS_ABSTRACT));
581 g_assert_not_reached ();
585 else if (g_strcmp0 (transport_name, "tcp") == 0 || g_strcmp0 (transport_name, "nonce-tcp") == 0)
593 is_nonce = (g_strcmp0 (transport_name, "nonce-tcp") == 0);
595 host = g_hash_table_lookup (key_value_pairs, "host");
600 G_IO_ERROR_INVALID_ARGUMENT,
601 _("Error in address '%s' - the host attribute is missing or malformed"),
606 s = g_hash_table_lookup (key_value_pairs, "port");
609 port = strtol (s, &endp, 10);
610 if ((*s == '\0' || *endp != '\0') || port < 0 || port >= 65536)
614 G_IO_ERROR_INVALID_ARGUMENT,
615 _("Error in address '%s' - the port attribute is missing or malformed"),
623 nonce_file = g_hash_table_lookup (key_value_pairs, "noncefile");
624 if (nonce_file == NULL)
628 G_IO_ERROR_INVALID_ARGUMENT,
629 _("Error in address '%s' - the noncefile attribute is missing or malformed"),
635 /* TODO: deal with family key/value-pair */
636 connectable = g_network_address_new (host, port);
638 else if (g_strcmp0 (address_entry, "autolaunch:") == 0)
640 gchar *autolaunch_address;
641 autolaunch_address = get_session_address_platform_specific (error);
642 if (autolaunch_address != NULL)
644 ret = g_dbus_address_try_connect_one (autolaunch_address, NULL, cancellable, error);
645 g_free (autolaunch_address);
650 g_prefix_error (error, _("Error auto-launching: "));
657 G_IO_ERROR_INVALID_ARGUMENT,
658 _("Unknown or unsupported transport '%s' for address '%s'"),
663 if (connectable != NULL)
665 GSocketClient *client;
666 GSocketConnection *connection;
668 g_assert (ret == NULL);
669 client = g_socket_client_new ();
670 connection = g_socket_client_connect (client,
674 g_object_unref (connectable);
675 g_object_unref (client);
676 if (connection == NULL)
679 ret = G_IO_STREAM (connection);
681 if (nonce_file != NULL)
683 gchar nonce_contents[16 + 1];
684 size_t num_bytes_read;
687 /* be careful to read only 16 bytes - we also check that the file is only 16 bytes long */
688 f = fopen (nonce_file, "rb");
693 G_IO_ERROR_INVALID_ARGUMENT,
694 _("Error opening nonce file '%s': %s"),
697 g_object_unref (ret);
701 num_bytes_read = fread (nonce_contents,
705 if (num_bytes_read != 16)
707 if (num_bytes_read == 0)
711 G_IO_ERROR_INVALID_ARGUMENT,
712 _("Error reading from nonce file '%s': %s"),
720 G_IO_ERROR_INVALID_ARGUMENT,
721 _("Error reading from nonce file '%s', expected 16 bytes, got %d"),
723 (gint) num_bytes_read);
725 g_object_unref (ret);
732 if (!g_output_stream_write_all (g_io_stream_get_output_stream (ret),
739 g_prefix_error (error, _("Error writing contents of nonce file '%s' to stream:"), nonce_file);
740 g_object_unref (ret);
753 g_dbus_address_try_connect_one (const gchar *address_entry,
755 GCancellable *cancellable,
759 GHashTable *key_value_pairs;
760 gchar *transport_name;
764 transport_name = NULL;
765 key_value_pairs = NULL;
767 if (!_g_dbus_address_parse_entry (address_entry,
773 ret = g_dbus_address_connect (address_entry,
781 guid = g_hash_table_lookup (key_value_pairs, "guid");
782 if (guid != NULL && out_guid != NULL)
783 *out_guid = g_strdup (guid);
786 g_free (transport_name);
787 if (key_value_pairs != NULL)
788 g_hash_table_unref (key_value_pairs);
793 /* ---------------------------------------------------------------------------------------------------- */
802 get_stream_data_free (GetStreamData *data)
804 g_free (data->address);
805 if (data->stream != NULL)
806 g_object_unref (data->stream);
812 get_stream_thread_func (GSimpleAsyncResult *res,
814 GCancellable *cancellable)
819 data = g_simple_async_result_get_op_res_gpointer (res);
822 data->stream = g_dbus_address_get_stream_sync (data->address,
826 if (data->stream == NULL)
827 g_simple_async_result_take_error (res, error);
831 * g_dbus_address_get_stream:
832 * @address: A valid D-Bus address.
833 * @cancellable: (allow-none): A #GCancellable or %NULL.
834 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
835 * @user_data: Data to pass to @callback.
837 * Asynchronously connects to an endpoint specified by @address and
838 * sets up the connection so it is in a state to run the client-side
839 * of the D-Bus authentication conversation.
841 * When the operation is finished, @callback will be invoked. You can
842 * then call g_dbus_address_get_stream_finish() to get the result of
845 * This is an asynchronous failable function. See
846 * g_dbus_address_get_stream_sync() for the synchronous version.
851 g_dbus_address_get_stream (const gchar *address,
852 GCancellable *cancellable,
853 GAsyncReadyCallback callback,
856 GSimpleAsyncResult *res;
859 g_return_if_fail (address != NULL);
861 res = g_simple_async_result_new (NULL,
864 g_dbus_address_get_stream);
865 g_simple_async_result_set_check_cancellable (res, cancellable);
866 data = g_new0 (GetStreamData, 1);
867 data->address = g_strdup (address);
868 g_simple_async_result_set_op_res_gpointer (res,
870 (GDestroyNotify) get_stream_data_free);
871 g_simple_async_result_run_in_thread (res,
872 get_stream_thread_func,
875 g_object_unref (res);
879 * g_dbus_address_get_stream_finish:
880 * @res: A #GAsyncResult obtained from the GAsyncReadyCallback passed to g_dbus_address_get_stream().
881 * @out_guid: %NULL or return location to store the GUID extracted from @address, if any.
882 * @error: Return location for error or %NULL.
884 * Finishes an operation started with g_dbus_address_get_stream().
886 * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
891 g_dbus_address_get_stream_finish (GAsyncResult *res,
895 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
899 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
900 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
902 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_address_get_stream);
906 data = g_simple_async_result_get_op_res_gpointer (simple);
907 if (g_simple_async_result_propagate_error (simple, error))
910 ret = g_object_ref (data->stream);
911 if (out_guid != NULL)
912 *out_guid = g_strdup (data->guid);
919 * g_dbus_address_get_stream_sync:
920 * @address: A valid D-Bus address.
921 * @out_guid: %NULL or return location to store the GUID extracted from @address, if any.
922 * @cancellable: (allow-none): A #GCancellable or %NULL.
923 * @error: Return location for error or %NULL.
925 * Synchronously connects to an endpoint specified by @address and
926 * sets up the connection so it is in a state to run the client-side
927 * of the D-Bus authentication conversation.
929 * This is a synchronous failable function. See
930 * g_dbus_address_get_stream() for the asynchronous version.
932 * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
937 g_dbus_address_get_stream_sync (const gchar *address,
939 GCancellable *cancellable,
947 g_return_val_if_fail (address != NULL, NULL);
948 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
953 addr_array = g_strsplit (address, ";", 0);
954 if (addr_array != NULL && addr_array[0] == NULL)
956 last_error = g_error_new_literal (G_IO_ERROR,
957 G_IO_ERROR_INVALID_ARGUMENT,
958 _("The given address is empty"));
962 for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
964 const gchar *addr = addr_array[n];
968 ret = g_dbus_address_try_connect_one (addr,
978 g_assert (this_error != NULL);
979 if (last_error != NULL)
980 g_error_free (last_error);
981 last_error = this_error;
988 if (last_error != NULL)
989 g_error_free (last_error);
993 g_assert (last_error != NULL);
994 g_propagate_error (error, last_error);
997 g_strfreev (addr_array);
1001 /* ---------------------------------------------------------------------------------------------------- */
1005 get_session_address_dbus_launch (GError **error)
1009 gchar *command_line;
1010 gchar *launch_stdout;
1011 gchar *launch_stderr;
1013 gchar *old_dbus_verbose;
1014 gboolean restore_dbus_verbose;
1018 command_line = NULL;
1019 launch_stdout = NULL;
1020 launch_stderr = NULL;
1021 restore_dbus_verbose = FALSE;
1022 old_dbus_verbose = NULL;
1024 /* Don't run binaries as root if we're setuid. */
1025 if (GLIB_PRIVATE_CALL (g_check_setuid) ())
1027 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1028 _("Cannot spawn a message bus when setuid"));
1032 machine_id = _g_dbus_get_machine_id (error);
1033 if (machine_id == NULL)
1035 g_prefix_error (error, _("Cannot spawn a message bus without a machine-id: "));
1039 /* We're using private libdbus facilities here. When everything
1040 * (X11, Mac OS X, Windows) is spec'ed out correctly (not even the
1041 * X11 property is correctly documented right now) we should
1042 * consider using the spec instead of dbus-launch.
1044 * --autolaunch=MACHINEID
1045 * This option implies that dbus-launch should scan for a previ‐
1046 * ously-started session and reuse the values found there. If no
1047 * session is found, it will start a new session. The --exit-with-
1048 * session option is implied if --autolaunch is given. This option
1049 * is for the exclusive use of libdbus, you do not want to use it
1050 * manually. It may change in the future.
1053 /* TODO: maybe provide a variable for where to look for the dbus-launch binary? */
1054 command_line = g_strdup_printf ("dbus-launch --autolaunch=%s --binary-syntax --close-stderr", machine_id);
1056 if (G_UNLIKELY (_g_dbus_debug_address ()))
1058 _g_dbus_debug_print_lock ();
1059 g_print ("GDBus-debug:Address: Running '%s' to get bus address (possibly autolaunching)\n", command_line);
1060 old_dbus_verbose = g_strdup (g_getenv ("DBUS_VERBOSE"));
1061 restore_dbus_verbose = TRUE;
1062 g_setenv ("DBUS_VERBOSE", "1", TRUE);
1063 _g_dbus_debug_print_unlock ();
1066 if (!g_spawn_command_line_sync (command_line,
1075 if (!g_spawn_check_exit_status (exit_status, error))
1077 g_prefix_error (error, _("Error spawning command line '%s': "), command_line);
1081 /* From the dbus-launch(1) man page:
1083 * --binary-syntax Write to stdout a nul-terminated bus address,
1084 * then the bus PID as a binary integer of size sizeof(pid_t),
1085 * then the bus X window ID as a binary integer of size
1086 * sizeof(long). Integers are in the machine's byte order, not
1087 * network byte order or any other canonical byte order.
1089 ret = g_strdup (launch_stdout);
1092 if (G_UNLIKELY (_g_dbus_debug_address ()))
1095 _g_dbus_debug_print_lock ();
1096 g_print ("GDBus-debug:Address: dbus-launch output:");
1097 if (launch_stdout != NULL)
1099 s = _g_dbus_hexdump (launch_stdout, strlen (launch_stdout) + 1 + sizeof (pid_t) + sizeof (long), 2);
1100 g_print ("\n%s", s);
1105 g_print (" (none)\n");
1107 g_print ("GDBus-debug:Address: dbus-launch stderr output:");
1108 if (launch_stderr != NULL)
1109 g_print ("\n%s", launch_stderr);
1111 g_print (" (none)\n");
1112 _g_dbus_debug_print_unlock ();
1115 g_free (machine_id);
1116 g_free (command_line);
1117 g_free (launch_stdout);
1118 g_free (launch_stderr);
1119 if (G_UNLIKELY (restore_dbus_verbose))
1121 if (old_dbus_verbose != NULL)
1122 g_setenv ("DBUS_VERBOSE", old_dbus_verbose, TRUE);
1124 g_unsetenv ("DBUS_VERBOSE");
1126 g_free (old_dbus_verbose);
1133 #define DBUS_DAEMON_ADDRESS_INFO "DBusDaemonAddressInfo"
1134 #define DBUS_DAEMON_MUTEX "DBusDaemonMutex"
1135 #define UNIQUE_DBUS_INIT_MUTEX "UniqueDBusInitMutex"
1136 #define DBUS_AUTOLAUNCH_MUTEX "DBusAutolaunchMutex"
1139 release_mutex (HANDLE mutex)
1141 ReleaseMutex (mutex);
1142 CloseHandle (mutex);
1146 acquire_mutex (const char *mutexname)
1151 mutex = CreateMutexA (NULL, FALSE, mutexname);
1155 res = WaitForSingleObject (mutex, INFINITE);
1158 case WAIT_ABANDONED:
1159 release_mutex (mutex);
1170 is_mutex_owned (const char *mutexname)
1173 gboolean res = FALSE;
1175 mutex = CreateMutexA (NULL, FALSE, mutexname);
1176 if (WaitForSingleObject (mutex, 10) == WAIT_TIMEOUT)
1179 ReleaseMutex (mutex);
1180 CloseHandle (mutex);
1186 read_shm (const char *shm_name)
1195 for (i = 0; i < 20; i++)
1197 shared_mem = OpenFileMappingA (FILE_MAP_READ, FALSE, shm_name);
1198 if (shared_mem != 0)
1203 if (shared_mem != 0)
1205 shared_data = MapViewOfFile (shared_mem, FILE_MAP_READ, 0, 0, 0);
1206 if (shared_data != NULL)
1208 res = g_strdup (shared_data);
1209 UnmapViewOfFile (shared_data);
1211 CloseHandle (shared_mem);
1218 set_shm (const char *shm_name, const char *value)
1223 shared_mem = CreateFileMappingA (INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
1224 0, strlen (value) + 1, shm_name);
1225 if (shared_mem == 0)
1228 shared_data = MapViewOfFile (shared_mem, FILE_MAP_WRITE, 0, 0, 0 );
1229 if (shared_data == NULL)
1232 strcpy (shared_data, value);
1234 UnmapViewOfFile (shared_data);
1239 /* These keep state between publish_session_bus and unpublish_session_bus */
1240 static HANDLE published_daemon_mutex;
1241 static HANDLE published_shared_mem;
1244 publish_session_bus (const char *address)
1248 init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
1250 published_daemon_mutex = CreateMutexA (NULL, FALSE, DBUS_DAEMON_MUTEX);
1251 if (WaitForSingleObject (published_daemon_mutex, 10 ) != WAIT_OBJECT_0)
1253 release_mutex (init_mutex);
1254 CloseHandle (published_daemon_mutex);
1255 published_daemon_mutex = NULL;
1259 published_shared_mem = set_shm (DBUS_DAEMON_ADDRESS_INFO, address);
1260 if (!published_shared_mem)
1262 release_mutex (init_mutex);
1263 CloseHandle (published_daemon_mutex);
1264 published_daemon_mutex = NULL;
1268 release_mutex (init_mutex);
1273 unpublish_session_bus (void)
1277 init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
1279 CloseHandle (published_shared_mem);
1280 published_shared_mem = NULL;
1282 release_mutex (published_daemon_mutex);
1283 published_daemon_mutex = NULL;
1285 release_mutex (init_mutex);
1289 wait_console_window (void)
1291 FILE *console = fopen ("CONOUT$", "w");
1293 SetConsoleTitleW (L"gdbus-daemon output. Type any character to close this window.");
1294 fprintf (console, _("(Type any character to close this window)\n"));
1300 open_console_window (void)
1302 if (((HANDLE) _get_osfhandle (fileno (stdout)) == INVALID_HANDLE_VALUE ||
1303 (HANDLE) _get_osfhandle (fileno (stderr)) == INVALID_HANDLE_VALUE) && AllocConsole ())
1305 if ((HANDLE) _get_osfhandle (fileno (stdout)) == INVALID_HANDLE_VALUE)
1306 freopen ("CONOUT$", "w", stdout);
1308 if ((HANDLE) _get_osfhandle (fileno (stderr)) == INVALID_HANDLE_VALUE)
1309 freopen ("CONOUT$", "w", stderr);
1311 SetConsoleTitleW (L"gdbus-daemon debug output.");
1313 atexit (wait_console_window);
1317 idle_timeout_cb (GDBusDaemon *daemon, gpointer user_data)
1319 GMainLoop *loop = user_data;
1320 g_main_loop_quit (loop);
1323 __declspec(dllexport) void CALLBACK g_win32_run_session_bus (HWND hwnd, HINSTANCE hinst, char *cmdline, int nCmdShow);
1325 __declspec(dllexport) void CALLBACK
1326 g_win32_run_session_bus (HWND hwnd, HINSTANCE hinst, char *cmdline, int nCmdShow)
1328 GDBusDaemon *daemon;
1330 const char *address;
1331 GError *error = NULL;
1333 if (g_getenv ("GDBUS_DAEMON_DEBUG") != NULL)
1334 open_console_window ();
1336 loop = g_main_loop_new (NULL, FALSE);
1338 address = "nonce-tcp:";
1339 daemon = _g_dbus_daemon_new (address, NULL, &error);
1342 g_printerr ("Can't init bus: %s\n", error->message);
1346 g_signal_connect (daemon, "idle-timeout", G_CALLBACK (idle_timeout_cb), loop);
1348 if ( publish_session_bus (_g_dbus_daemon_get_address (daemon)))
1350 g_main_loop_run (loop);
1352 unpublish_session_bus ();
1355 g_main_loop_unref (loop);
1356 g_object_unref (daemon);
1360 get_session_address_dbus_launch (GError **error)
1362 HANDLE autolaunch_mutex, init_mutex;
1363 char *address = NULL;
1364 wchar_t gio_path[MAX_PATH+1+200];
1366 autolaunch_mutex = acquire_mutex (DBUS_AUTOLAUNCH_MUTEX);
1368 init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
1370 if (is_mutex_owned (DBUS_DAEMON_MUTEX))
1371 address = read_shm (DBUS_DAEMON_ADDRESS_INFO);
1373 release_mutex (init_mutex);
1375 if (address == NULL)
1377 gio_path[MAX_PATH] = 0;
1378 if (GetModuleFileNameW (_g_io_win32_get_module (), gio_path, MAX_PATH))
1380 PROCESS_INFORMATION pi = { 0 };
1381 STARTUPINFOW si = { 0 };
1383 wchar_t gio_path_short[MAX_PATH];
1384 wchar_t rundll_path[MAX_PATH*2];
1385 wchar_t args[MAX_PATH*4];
1387 GetShortPathNameW (gio_path, gio_path_short, MAX_PATH);
1389 GetWindowsDirectoryW (rundll_path, MAX_PATH);
1390 wcscat (rundll_path, L"\\rundll32.exe");
1391 if (GetFileAttributesW (rundll_path) == INVALID_FILE_ATTRIBUTES)
1393 GetSystemDirectoryW (rundll_path, MAX_PATH);
1394 wcscat (rundll_path, L"\\rundll32.exe");
1397 wcscpy (args, L"\"");
1398 wcscat (args, rundll_path);
1399 wcscat (args, L"\" ");
1400 wcscat (args, gio_path_short);
1401 #if defined(_WIN64) || defined(_M_X64) || defined(_M_AMD64)
1402 wcscat (args, L",g_win32_run_session_bus");
1403 #elif defined (_MSC_VER)
1404 wcscat (args, L",_g_win32_run_session_bus@16");
1406 wcscat (args, L",g_win32_run_session_bus@16");
1409 res = CreateProcessW (rundll_path, args,
1411 NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW | DETACHED_PROCESS,
1412 0, NULL /* TODO: Should be root */,
1415 address = read_shm (DBUS_DAEMON_ADDRESS_INFO);
1419 release_mutex (autolaunch_mutex);
1421 if (address == NULL)
1425 _("Session dbus not running, and autolaunch failed"));
1431 /* ---------------------------------------------------------------------------------------------------- */
1434 get_session_address_platform_specific (GError **error)
1437 #if defined (G_OS_UNIX) || defined(G_OS_WIN32)
1438 /* need to handle OS X in a different way since 'dbus-launch --autolaunch' probably won't work there */
1439 ret = get_session_address_dbus_launch (error);
1441 /* TODO: implement for OS X */
1446 _("Cannot determine session bus address (not implemented for this OS)"));
1451 /* ---------------------------------------------------------------------------------------------------- */
1454 * g_dbus_address_get_for_bus_sync:
1455 * @bus_type: a #GBusType
1456 * @cancellable: (allow-none): a #GCancellable or %NULL
1457 * @error: return location for error or %NULL
1459 * Synchronously looks up the D-Bus address for the well-known message
1460 * bus instance specified by @bus_type. This may involve using various
1461 * platform specific mechanisms.
1463 * Returns: a valid D-Bus address string for @bus_type or %NULL if
1469 g_dbus_address_get_for_bus_sync (GBusType bus_type,
1470 GCancellable *cancellable,
1474 const gchar *starter_bus;
1475 GError *local_error;
1477 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1482 if (G_UNLIKELY (_g_dbus_debug_address ()))
1485 _g_dbus_debug_print_lock ();
1486 g_print ("GDBus-debug:Address: In g_dbus_address_get_for_bus_sync() for bus type '%s'\n",
1487 _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type));
1488 for (n = 0; n < 3; n++)
1494 case 0: k = "DBUS_SESSION_BUS_ADDRESS"; break;
1495 case 1: k = "DBUS_SYSTEM_BUS_ADDRESS"; break;
1496 case 2: k = "DBUS_STARTER_BUS_TYPE"; break;
1497 default: g_assert_not_reached ();
1500 g_print ("GDBus-debug:Address: env var %s", k);
1502 g_print ("='%s'\n", v);
1504 g_print (" is not set\n");
1506 _g_dbus_debug_print_unlock ();
1511 case G_BUS_TYPE_SYSTEM:
1512 ret = g_strdup (g_getenv ("DBUS_SYSTEM_BUS_ADDRESS"));
1515 ret = g_strdup ("unix:path=/var/run/dbus/system_bus_socket");
1519 case G_BUS_TYPE_SESSION:
1520 ret = g_strdup (g_getenv ("DBUS_SESSION_BUS_ADDRESS"));
1523 ret = get_session_address_platform_specific (&local_error);
1527 case G_BUS_TYPE_STARTER:
1528 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
1529 if (g_strcmp0 (starter_bus, "session") == 0)
1531 ret = g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SESSION, cancellable, &local_error);
1534 else if (g_strcmp0 (starter_bus, "system") == 0)
1536 ret = g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SYSTEM, cancellable, &local_error);
1541 if (starter_bus != NULL)
1543 g_set_error (&local_error,
1546 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
1547 " - unknown value '%s'"),
1552 g_set_error_literal (&local_error,
1555 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
1556 "variable is not set"));
1562 g_set_error (&local_error,
1565 _("Unknown bus type %d"),
1571 if (G_UNLIKELY (_g_dbus_debug_address ()))
1573 _g_dbus_debug_print_lock ();
1576 g_print ("GDBus-debug:Address: Returning address '%s' for bus type '%s'\n",
1578 _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type));
1582 g_print ("GDBus-debug:Address: Cannot look-up address bus type '%s': %s\n",
1583 _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type),
1584 local_error ? local_error->message : "");
1586 _g_dbus_debug_print_unlock ();
1589 if (local_error != NULL)
1590 g_propagate_error (error, local_error);
1596 * g_dbus_address_escape_value:
1597 * @string: an unescaped string to be included in a D-Bus address
1598 * as the value in a key-value pair
1600 * Escape @string so it can appear in a D-Bus address as the value
1601 * part of a key-value pair.
1603 * For instance, if @string is "/run/bus-for-:0",
1604 * this function would return "/run/bus-for-%3A0",
1605 * which could be used in a D-Bus address like
1606 * "unix:nonce-tcp:host=127.0.0.1,port=42,noncefile=/run/bus-for-%3A0".
1608 * Returns: (transfer full): a copy of @string with all
1609 * non-optionally-escaped bytes escaped
1614 g_dbus_address_escape_value (const gchar *string)
1619 g_return_val_if_fail (string != NULL, NULL);
1621 /* There will often not be anything needing escaping at all. */
1622 s = g_string_sized_new (strlen (string));
1624 /* D-Bus address escaping is mostly the same as URI escaping... */
1625 g_string_append_uri_escaped (s, string, "\\/", FALSE);
1627 /* ... but '~' is an unreserved character in URIs, but a
1628 * non-optionally-escaped character in D-Bus addresses. */
1629 for (i = 0; i < s->len; i++)
1631 if (G_UNLIKELY (s->str[i] == '~'))
1634 g_string_insert (s, i + 1, "7E");
1639 return g_string_free (s, FALSE);