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, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: David Zeuthen <davidz@redhat.com>
31 #include "gdbusutils.h"
32 #include "gdbusaddress.h"
33 #include "gdbuserror.h"
34 #include "gioenumtypes.h"
35 #include "gnetworkaddress.h"
36 #include "gsocketclient.h"
37 #include "giostream.h"
38 #include "gasyncresult.h"
39 #include "gsimpleasyncresult.h"
40 #include "glib-private.h"
41 #include "gdbusprivate.h"
42 #include "giomodule-priv.h"
43 #include "gdbusdaemon.h"
46 #include <gio/gunixsocketaddress.h>
58 * SECTION:gdbusaddress
59 * @title: D-Bus Addresses
60 * @short_description: D-Bus connection endpoints
63 * Routines for working with D-Bus addresses. A D-Bus address is a string
64 * like "unix:tmpdir=/tmp/my-app-name". The exact format of addresses
65 * is explained in detail in the <link linkend="http://dbus.freedesktop.org/doc/dbus-specification.html#addresses">D-Bus specification</link>.
68 static gchar *get_session_address_platform_specific (GError **error);
70 /* ---------------------------------------------------------------------------------------------------- */
76 * Checks if @string is a D-Bus address.
78 * This doesn't check if @string is actually supported by #GDBusServer
79 * or #GDBusConnection - use g_dbus_is_supported_address() to do more
82 * Returns: %TRUE if @string is a valid D-Bus address, %FALSE otherwise.
87 g_dbus_is_address (const gchar *string)
95 g_return_val_if_fail (string != NULL, FALSE);
97 a = g_strsplit (string, ";", 0);
101 for (n = 0; a[n] != NULL; n++)
103 if (!_g_dbus_address_parse_entry (a[n],
118 is_valid_unix (const gchar *address_entry,
119 GHashTable *key_value_pairs,
127 const gchar *abstract;
135 keys = g_hash_table_get_keys (key_value_pairs);
136 for (l = keys; l != NULL; l = l->next)
138 const gchar *key = l->data;
139 if (g_strcmp0 (key, "path") == 0)
140 path = g_hash_table_lookup (key_value_pairs, key);
141 else if (g_strcmp0 (key, "tmpdir") == 0)
142 tmpdir = g_hash_table_lookup (key_value_pairs, key);
143 else if (g_strcmp0 (key, "abstract") == 0)
144 abstract = g_hash_table_lookup (key_value_pairs, key);
149 G_IO_ERROR_INVALID_ARGUMENT,
150 _("Unsupported key '%s' in address entry '%s'"),
159 if (tmpdir != NULL || abstract != NULL)
162 else if (tmpdir != NULL)
164 if (path != NULL || abstract != NULL)
167 else if (abstract != NULL)
169 if (path != NULL || tmpdir != NULL)
176 G_IO_ERROR_INVALID_ARGUMENT,
177 _("Address '%s' is invalid (need exactly one of path, tmpdir or abstract keys)"),
189 G_IO_ERROR_INVALID_ARGUMENT,
190 _("Meaningless key/value pair combination in address entry '%s'"),
200 is_valid_nonce_tcp (const gchar *address_entry,
201 GHashTable *key_value_pairs,
210 const gchar *nonce_file;
221 keys = g_hash_table_get_keys (key_value_pairs);
222 for (l = keys; l != NULL; l = l->next)
224 const gchar *key = l->data;
225 if (g_strcmp0 (key, "host") == 0)
226 host = g_hash_table_lookup (key_value_pairs, key);
227 else if (g_strcmp0 (key, "port") == 0)
228 port = g_hash_table_lookup (key_value_pairs, key);
229 else if (g_strcmp0 (key, "family") == 0)
230 family = g_hash_table_lookup (key_value_pairs, key);
231 else if (g_strcmp0 (key, "noncefile") == 0)
232 nonce_file = g_hash_table_lookup (key_value_pairs, key);
237 G_IO_ERROR_INVALID_ARGUMENT,
238 _("Unsupported key '%s' in address entry '%s'"),
247 port_num = strtol (port, &endp, 10);
248 if ((*port == '\0' || *endp != '\0') || port_num < 0 || port_num >= 65536)
252 G_IO_ERROR_INVALID_ARGUMENT,
253 _("Error in address '%s' - the port attribute is malformed"),
259 if (family != NULL && !(g_strcmp0 (family, "ipv4") == 0 || g_strcmp0 (family, "ipv6") == 0))
263 G_IO_ERROR_INVALID_ARGUMENT,
264 _("Error in address '%s' - the family attribute is malformed"),
271 /* TODO: validate host */
274 nonce_file = nonce_file; /* To avoid -Wunused-but-set-variable */
285 is_valid_tcp (const gchar *address_entry,
286 GHashTable *key_value_pairs,
304 keys = g_hash_table_get_keys (key_value_pairs);
305 for (l = keys; l != NULL; l = l->next)
307 const gchar *key = l->data;
308 if (g_strcmp0 (key, "host") == 0)
309 host = g_hash_table_lookup (key_value_pairs, key);
310 else if (g_strcmp0 (key, "port") == 0)
311 port = g_hash_table_lookup (key_value_pairs, key);
312 else if (g_strcmp0 (key, "family") == 0)
313 family = g_hash_table_lookup (key_value_pairs, key);
318 G_IO_ERROR_INVALID_ARGUMENT,
319 _("Unsupported key '%s' in address entry '%s'"),
328 port_num = strtol (port, &endp, 10);
329 if ((*port == '\0' || *endp != '\0') || port_num < 0 || port_num >= 65536)
333 G_IO_ERROR_INVALID_ARGUMENT,
334 _("Error in address '%s' - the port attribute is malformed"),
340 if (family != NULL && !(g_strcmp0 (family, "ipv4") == 0 || g_strcmp0 (family, "ipv6") == 0))
344 G_IO_ERROR_INVALID_ARGUMENT,
345 _("Error in address '%s' - the family attribute is malformed"),
352 /* TODO: validate host */
364 * g_dbus_is_supported_address:
366 * @error: Return location for error or %NULL.
368 * Like g_dbus_is_address() but also checks if the library suppors the
369 * transports in @string and that key/value pairs for each transport
372 * Returns: %TRUE if @string is a valid D-Bus address that is
373 * supported by this library, %FALSE if @error is set.
378 g_dbus_is_supported_address (const gchar *string,
387 g_return_val_if_fail (string != NULL, FALSE);
388 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
390 a = g_strsplit (string, ";", 0);
391 for (n = 0; a[n] != NULL; n++)
393 gchar *transport_name;
394 GHashTable *key_value_pairs;
397 if (!_g_dbus_address_parse_entry (a[n],
404 if (g_strcmp0 (transport_name, "unix") == 0)
405 supported = is_valid_unix (a[n], key_value_pairs, error);
406 else if (g_strcmp0 (transport_name, "tcp") == 0)
407 supported = is_valid_tcp (a[n], key_value_pairs, error);
408 else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
409 supported = is_valid_nonce_tcp (a[n], key_value_pairs, error);
410 else if (g_strcmp0 (a[n], "autolaunch:") == 0)
413 g_free (transport_name);
414 g_hash_table_unref (key_value_pairs);
425 g_assert (ret || (!ret && (error == NULL || *error != NULL)));
431 _g_dbus_address_parse_entry (const gchar *address_entry,
432 gchar **out_transport_name,
433 GHashTable **out_key_value_pairs,
437 GHashTable *key_value_pairs;
438 gchar *transport_name;
445 transport_name = NULL;
446 key_value_pairs = NULL;
448 s = strchr (address_entry, ':');
453 G_IO_ERROR_INVALID_ARGUMENT,
454 _("Address element '%s' does not contain a colon (:)"),
459 transport_name = g_strndup (address_entry, s - address_entry);
460 key_value_pairs = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
462 kv_pairs = g_strsplit (s + 1, ",", 0);
463 for (n = 0; kv_pairs != NULL && kv_pairs[n] != NULL; n++)
465 const gchar *kv_pair = kv_pairs[n];
469 s = strchr (kv_pair, '=');
474 G_IO_ERROR_INVALID_ARGUMENT,
475 _("Key/Value pair %d, '%s', in address element '%s' does not contain an equal sign"),
482 key = g_uri_unescape_segment (kv_pair, s, NULL);
483 value = g_uri_unescape_segment (s + 1, kv_pair + strlen (kv_pair), NULL);
484 if (key == NULL || value == NULL)
488 G_IO_ERROR_INVALID_ARGUMENT,
489 _("Error unescaping key or value in Key/Value pair %d, '%s', in address element '%s'"),
497 g_hash_table_insert (key_value_pairs, key, value);
503 g_strfreev (kv_pairs);
506 if (out_transport_name != NULL)
507 *out_transport_name = transport_name;
509 g_free (transport_name);
510 if (out_key_value_pairs != NULL)
511 *out_key_value_pairs = key_value_pairs;
512 else if (key_value_pairs != NULL)
513 g_hash_table_unref (key_value_pairs);
517 g_free (transport_name);
518 if (key_value_pairs != NULL)
519 g_hash_table_unref (key_value_pairs);
524 /* ---------------------------------------------------------------------------------------------------- */
527 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,
540 GHashTable *key_value_pairs,
541 GCancellable *cancellable,
545 GSocketConnectable *connectable;
546 const gchar *nonce_file;
556 else if (g_strcmp0 (transport_name, "unix") == 0)
559 const gchar *abstract;
560 path = g_hash_table_lookup (key_value_pairs, "path");
561 abstract = g_hash_table_lookup (key_value_pairs, "abstract");
562 if ((path == NULL && abstract == NULL) || (path != NULL && abstract != NULL))
566 G_IO_ERROR_INVALID_ARGUMENT,
567 _("Error in address '%s' - the unix transport requires exactly one of the "
568 "keys 'path' or 'abstract' to be set"),
571 else if (path != NULL)
573 connectable = G_SOCKET_CONNECTABLE (g_unix_socket_address_new (path));
575 else if (abstract != NULL)
577 connectable = G_SOCKET_CONNECTABLE (g_unix_socket_address_new_with_type (abstract,
579 G_UNIX_SOCKET_ADDRESS_ABSTRACT));
583 g_assert_not_reached ();
587 else if (g_strcmp0 (transport_name, "tcp") == 0 || g_strcmp0 (transport_name, "nonce-tcp") == 0)
595 is_nonce = (g_strcmp0 (transport_name, "nonce-tcp") == 0);
597 host = g_hash_table_lookup (key_value_pairs, "host");
602 G_IO_ERROR_INVALID_ARGUMENT,
603 _("Error in address '%s' - the host attribute is missing or malformed"),
608 s = g_hash_table_lookup (key_value_pairs, "port");
611 port = strtol (s, &endp, 10);
612 if ((*s == '\0' || *endp != '\0') || port < 0 || port >= 65536)
616 G_IO_ERROR_INVALID_ARGUMENT,
617 _("Error in address '%s' - the port attribute is missing or malformed"),
625 nonce_file = g_hash_table_lookup (key_value_pairs, "noncefile");
626 if (nonce_file == NULL)
630 G_IO_ERROR_INVALID_ARGUMENT,
631 _("Error in address '%s' - the noncefile attribute is missing or malformed"),
637 /* TODO: deal with family key/value-pair */
638 connectable = g_network_address_new (host, port);
640 else if (g_strcmp0 (address_entry, "autolaunch:") == 0)
642 gchar *autolaunch_address;
643 autolaunch_address = get_session_address_platform_specific (error);
644 if (autolaunch_address != NULL)
646 ret = g_dbus_address_try_connect_one (autolaunch_address, NULL, cancellable, error);
647 g_free (autolaunch_address);
652 g_prefix_error (error, _("Error auto-launching: "));
659 G_IO_ERROR_INVALID_ARGUMENT,
660 _("Unknown or unsupported transport '%s' for address '%s'"),
665 if (connectable != NULL)
667 GSocketClient *client;
668 GSocketConnection *connection;
670 g_assert (ret == NULL);
671 client = g_socket_client_new ();
672 connection = g_socket_client_connect (client,
676 g_object_unref (connectable);
677 g_object_unref (client);
678 if (connection == NULL)
681 ret = G_IO_STREAM (connection);
683 if (nonce_file != NULL)
685 gchar nonce_contents[16 + 1];
686 size_t num_bytes_read;
689 /* be careful to read only 16 bytes - we also check that the file is only 16 bytes long */
690 f = fopen (nonce_file, "rb");
695 G_IO_ERROR_INVALID_ARGUMENT,
696 _("Error opening nonce file '%s': %s"),
699 g_object_unref (ret);
703 num_bytes_read = fread (nonce_contents,
707 if (num_bytes_read != 16)
709 if (num_bytes_read == 0)
713 G_IO_ERROR_INVALID_ARGUMENT,
714 _("Error reading from nonce file '%s': %s"),
722 G_IO_ERROR_INVALID_ARGUMENT,
723 _("Error reading from nonce file '%s', expected 16 bytes, got %d"),
725 (gint) num_bytes_read);
727 g_object_unref (ret);
734 if (!g_output_stream_write_all (g_io_stream_get_output_stream (ret),
741 g_prefix_error (error, _("Error writing contents of nonce file '%s' to stream:"), nonce_file);
742 g_object_unref (ret);
755 g_dbus_address_try_connect_one (const gchar *address_entry,
757 GCancellable *cancellable,
761 GHashTable *key_value_pairs;
762 gchar *transport_name;
766 transport_name = NULL;
767 key_value_pairs = NULL;
769 if (!_g_dbus_address_parse_entry (address_entry,
775 ret = g_dbus_address_connect (address_entry,
783 guid = g_hash_table_lookup (key_value_pairs, "guid");
784 if (guid != NULL && out_guid != NULL)
785 *out_guid = g_strdup (guid);
788 g_free (transport_name);
789 if (key_value_pairs != NULL)
790 g_hash_table_unref (key_value_pairs);
795 /* ---------------------------------------------------------------------------------------------------- */
804 get_stream_data_free (GetStreamData *data)
806 g_free (data->address);
807 if (data->stream != NULL)
808 g_object_unref (data->stream);
814 get_stream_thread_func (GSimpleAsyncResult *res,
816 GCancellable *cancellable)
821 data = g_simple_async_result_get_op_res_gpointer (res);
824 data->stream = g_dbus_address_get_stream_sync (data->address,
828 if (data->stream == NULL)
829 g_simple_async_result_take_error (res, error);
833 * g_dbus_address_get_stream:
834 * @address: A valid D-Bus address.
835 * @cancellable: (allow-none): A #GCancellable or %NULL.
836 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
837 * @user_data: Data to pass to @callback.
839 * Asynchronously connects to an endpoint specified by @address and
840 * sets up the connection so it is in a state to run the client-side
841 * of the D-Bus authentication conversation.
843 * When the operation is finished, @callback will be invoked. You can
844 * then call g_dbus_address_get_stream_finish() to get the result of
847 * This is an asynchronous failable function. See
848 * g_dbus_address_get_stream_sync() for the synchronous version.
853 g_dbus_address_get_stream (const gchar *address,
854 GCancellable *cancellable,
855 GAsyncReadyCallback callback,
858 GSimpleAsyncResult *res;
861 g_return_if_fail (address != NULL);
863 res = g_simple_async_result_new (NULL,
866 g_dbus_address_get_stream);
867 g_simple_async_result_set_check_cancellable (res, cancellable);
868 data = g_new0 (GetStreamData, 1);
869 data->address = g_strdup (address);
870 g_simple_async_result_set_op_res_gpointer (res,
872 (GDestroyNotify) get_stream_data_free);
873 g_simple_async_result_run_in_thread (res,
874 get_stream_thread_func,
877 g_object_unref (res);
881 * g_dbus_address_get_stream_finish:
882 * @res: A #GAsyncResult obtained from the GAsyncReadyCallback passed to g_dbus_address_get_stream().
883 * @out_guid: %NULL or return location to store the GUID extracted from @address, if any.
884 * @error: Return location for error or %NULL.
886 * Finishes an operation started with g_dbus_address_get_stream().
888 * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
893 g_dbus_address_get_stream_finish (GAsyncResult *res,
897 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
901 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
902 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
904 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_address_get_stream);
908 data = g_simple_async_result_get_op_res_gpointer (simple);
909 if (g_simple_async_result_propagate_error (simple, error))
912 ret = g_object_ref (data->stream);
913 if (out_guid != NULL)
914 *out_guid = g_strdup (data->guid);
921 * g_dbus_address_get_stream_sync:
922 * @address: A valid D-Bus address.
923 * @out_guid: %NULL or return location to store the GUID extracted from @address, if any.
924 * @cancellable: (allow-none): A #GCancellable or %NULL.
925 * @error: Return location for error or %NULL.
927 * Synchronously connects to an endpoint specified by @address and
928 * sets up the connection so it is in a state to run the client-side
929 * of the D-Bus authentication conversation.
931 * This is a synchronous failable function. See
932 * g_dbus_address_get_stream() for the asynchronous version.
934 * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
939 g_dbus_address_get_stream_sync (const gchar *address,
941 GCancellable *cancellable,
949 g_return_val_if_fail (address != NULL, NULL);
950 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
955 addr_array = g_strsplit (address, ";", 0);
956 if (addr_array != NULL && addr_array[0] == NULL)
958 last_error = g_error_new_literal (G_IO_ERROR,
959 G_IO_ERROR_INVALID_ARGUMENT,
960 _("The given address is empty"));
964 for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
966 const gchar *addr = addr_array[n];
970 ret = g_dbus_address_try_connect_one (addr,
980 g_assert (this_error != NULL);
981 if (last_error != NULL)
982 g_error_free (last_error);
983 last_error = this_error;
990 if (last_error != NULL)
991 g_error_free (last_error);
995 g_assert (last_error != NULL);
996 g_propagate_error (error, last_error);
999 g_strfreev (addr_array);
1003 /* ---------------------------------------------------------------------------------------------------- */
1007 get_session_address_dbus_launch (GError **error)
1011 gchar *command_line;
1012 gchar *launch_stdout;
1013 gchar *launch_stderr;
1015 gchar *old_dbus_verbose;
1016 gboolean restore_dbus_verbose;
1020 command_line = NULL;
1021 launch_stdout = NULL;
1022 launch_stderr = NULL;
1023 restore_dbus_verbose = FALSE;
1024 old_dbus_verbose = NULL;
1026 /* Don't run binaries as root if we're setuid. */
1027 if (GLIB_PRIVATE_CALL (g_check_setuid) ())
1029 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1030 _("Cannot spawn a message bus when setuid"));
1034 machine_id = _g_dbus_get_machine_id (error);
1035 if (machine_id == NULL)
1037 g_prefix_error (error, _("Cannot spawn a message bus without a machine-id: "));
1041 /* We're using private libdbus facilities here. When everything
1042 * (X11, Mac OS X, Windows) is spec'ed out correctly (not even the
1043 * X11 property is correctly documented right now) we should
1044 * consider using the spec instead of dbus-launch.
1046 * --autolaunch=MACHINEID
1047 * This option implies that dbus-launch should scan for a previ‐
1048 * ously-started session and reuse the values found there. If no
1049 * session is found, it will start a new session. The --exit-with-
1050 * session option is implied if --autolaunch is given. This option
1051 * is for the exclusive use of libdbus, you do not want to use it
1052 * manually. It may change in the future.
1055 /* TODO: maybe provide a variable for where to look for the dbus-launch binary? */
1056 command_line = g_strdup_printf ("dbus-launch --autolaunch=%s --binary-syntax --close-stderr", machine_id);
1058 if (G_UNLIKELY (_g_dbus_debug_address ()))
1060 _g_dbus_debug_print_lock ();
1061 g_print ("GDBus-debug:Address: Running '%s' to get bus address (possibly autolaunching)\n", command_line);
1062 old_dbus_verbose = g_strdup (g_getenv ("DBUS_VERBOSE"));
1063 restore_dbus_verbose = TRUE;
1064 g_setenv ("DBUS_VERBOSE", "1", TRUE);
1065 _g_dbus_debug_print_unlock ();
1068 if (!g_spawn_command_line_sync (command_line,
1077 if (!g_spawn_check_exit_status (exit_status, error))
1079 g_prefix_error (error, _("Error spawning command line '%s': "), command_line);
1083 /* From the dbus-launch(1) man page:
1085 * --binary-syntax Write to stdout a nul-terminated bus address,
1086 * then the bus PID as a binary integer of size sizeof(pid_t),
1087 * then the bus X window ID as a binary integer of size
1088 * sizeof(long). Integers are in the machine's byte order, not
1089 * network byte order or any other canonical byte order.
1091 ret = g_strdup (launch_stdout);
1094 if (G_UNLIKELY (_g_dbus_debug_address ()))
1097 _g_dbus_debug_print_lock ();
1098 g_print ("GDBus-debug:Address: dbus-launch output:");
1099 if (launch_stdout != NULL)
1101 s = _g_dbus_hexdump (launch_stdout, strlen (launch_stdout) + 1 + sizeof (pid_t) + sizeof (long), 2);
1102 g_print ("\n%s", s);
1107 g_print (" (none)\n");
1109 g_print ("GDBus-debug:Address: dbus-launch stderr output:");
1110 if (launch_stderr != NULL)
1111 g_print ("\n%s", launch_stderr);
1113 g_print (" (none)\n");
1114 _g_dbus_debug_print_unlock ();
1117 g_free (machine_id);
1118 g_free (command_line);
1119 g_free (launch_stdout);
1120 g_free (launch_stderr);
1121 if (G_UNLIKELY (restore_dbus_verbose))
1123 if (old_dbus_verbose != NULL)
1124 g_setenv ("DBUS_VERBOSE", old_dbus_verbose, TRUE);
1126 g_unsetenv ("DBUS_VERBOSE");
1128 g_free (old_dbus_verbose);
1135 #define DBUS_DAEMON_ADDRESS_INFO "DBusDaemonAddressInfo"
1136 #define DBUS_DAEMON_MUTEX "DBusDaemonMutex"
1137 #define UNIQUE_DBUS_INIT_MUTEX "UniqueDBusInitMutex"
1138 #define DBUS_AUTOLAUNCH_MUTEX "DBusAutolaunchMutex"
1141 release_mutex (HANDLE mutex)
1143 ReleaseMutex (mutex);
1144 CloseHandle (mutex);
1148 acquire_mutex (const char *mutexname)
1153 mutex = CreateMutexA (NULL, FALSE, mutexname);
1157 res = WaitForSingleObject (mutex, INFINITE);
1160 case WAIT_ABANDONED:
1161 release_mutex (mutex);
1172 is_mutex_owned (const char *mutexname)
1175 gboolean res = FALSE;
1177 mutex = CreateMutexA (NULL, FALSE, mutexname);
1178 if (WaitForSingleObject (mutex, 10) == WAIT_TIMEOUT)
1181 ReleaseMutex (mutex);
1182 CloseHandle (mutex);
1188 read_shm (const char *shm_name)
1197 for (i = 0; i < 20; i++)
1199 shared_mem = OpenFileMappingA (FILE_MAP_READ, FALSE, shm_name);
1200 if (shared_mem != 0)
1205 if (shared_mem != 0)
1207 shared_data = MapViewOfFile (shared_mem, FILE_MAP_READ, 0, 0, 0);
1208 if (shared_data != NULL)
1210 res = g_strdup (shared_data);
1211 UnmapViewOfFile (shared_data);
1213 CloseHandle (shared_mem);
1220 set_shm (const char *shm_name, const char *value)
1225 shared_mem = CreateFileMappingA (INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
1226 0, strlen (value) + 1, shm_name);
1227 if (shared_mem == 0)
1230 shared_data = MapViewOfFile (shared_mem, FILE_MAP_WRITE, 0, 0, 0 );
1231 if (shared_data == NULL)
1234 strcpy (shared_data, value);
1236 UnmapViewOfFile (shared_data);
1241 /* These keep state between publish_session_bus and unpublish_session_bus */
1242 static HANDLE published_daemon_mutex;
1243 static HANDLE published_shared_mem;
1246 publish_session_bus (const char *address)
1250 init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
1252 published_daemon_mutex = CreateMutexA (NULL, FALSE, DBUS_DAEMON_MUTEX);
1253 if (WaitForSingleObject (published_daemon_mutex, 10 ) != WAIT_OBJECT_0)
1255 release_mutex (init_mutex);
1256 CloseHandle (published_daemon_mutex);
1257 published_daemon_mutex = NULL;
1261 published_shared_mem = set_shm (DBUS_DAEMON_ADDRESS_INFO, address);
1262 if (!published_shared_mem)
1264 release_mutex (init_mutex);
1265 CloseHandle (published_daemon_mutex);
1266 published_daemon_mutex = NULL;
1270 release_mutex (init_mutex);
1275 unpublish_session_bus (void)
1279 init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
1281 CloseHandle (published_shared_mem);
1282 published_shared_mem = NULL;
1284 release_mutex (published_daemon_mutex);
1285 published_daemon_mutex = NULL;
1287 release_mutex (init_mutex);
1291 wait_console_window (void)
1293 FILE *console = fopen ("CONOUT$", "w");
1295 SetConsoleTitleW (L"gdbus-daemon output. Type any character to close this window.");
1296 fprintf (console, _("(Type any character to close this window)\n"));
1302 open_console_window (void)
1304 if (((HANDLE) _get_osfhandle (fileno (stdout)) == INVALID_HANDLE_VALUE ||
1305 (HANDLE) _get_osfhandle (fileno (stderr)) == INVALID_HANDLE_VALUE) && AllocConsole ())
1307 if ((HANDLE) _get_osfhandle (fileno (stdout)) == INVALID_HANDLE_VALUE)
1308 freopen ("CONOUT$", "w", stdout);
1310 if ((HANDLE) _get_osfhandle (fileno (stderr)) == INVALID_HANDLE_VALUE)
1311 freopen ("CONOUT$", "w", stderr);
1313 SetConsoleTitleW (L"gdbus-daemon debug output.");
1315 atexit (wait_console_window);
1319 idle_timeout_cb (GDBusDaemon *daemon, gpointer user_data)
1321 GMainLoop *loop = user_data;
1322 g_main_loop_quit (loop);
1325 __declspec(dllexport) void CALLBACK g_win32_run_session_bus (HWND hwnd, HINSTANCE hinst, char *cmdline, int nCmdShow);
1327 __declspec(dllexport) void CALLBACK
1328 g_win32_run_session_bus (HWND hwnd, HINSTANCE hinst, char *cmdline, int nCmdShow)
1330 GDBusDaemon *daemon;
1332 const char *address;
1333 GError *error = NULL;
1335 if (g_getenv ("GDBUS_DAEMON_DEBUG") != NULL)
1336 open_console_window ();
1338 loop = g_main_loop_new (NULL, FALSE);
1340 address = "nonce-tcp:";
1341 daemon = _g_dbus_daemon_new (address, NULL, &error);
1344 g_printerr ("Can't init bus: %s\n", error->message);
1348 g_signal_connect (daemon, "idle-timeout", G_CALLBACK (idle_timeout_cb), loop);
1350 if ( publish_session_bus (_g_dbus_daemon_get_address (daemon)))
1352 g_main_loop_run (loop);
1354 unpublish_session_bus ();
1357 g_main_loop_unref (loop);
1358 g_object_unref (daemon);
1362 get_session_address_dbus_launch (GError **error)
1364 HANDLE autolaunch_mutex, init_mutex;
1365 char *address = NULL;
1366 wchar_t gio_path[MAX_PATH+1+200];
1368 autolaunch_mutex = acquire_mutex (DBUS_AUTOLAUNCH_MUTEX);
1370 init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
1372 if (is_mutex_owned (DBUS_DAEMON_MUTEX))
1373 address = read_shm (DBUS_DAEMON_ADDRESS_INFO);
1375 release_mutex (init_mutex);
1377 if (address == NULL)
1379 gio_path[MAX_PATH] = 0;
1380 if (GetModuleFileNameW (_g_io_win32_get_module (), gio_path, MAX_PATH))
1382 PROCESS_INFORMATION pi = { 0 };
1383 STARTUPINFOW si = { 0 };
1385 wchar_t gio_path_short[MAX_PATH];
1386 wchar_t rundll_path[MAX_PATH*2];
1387 wchar_t args[MAX_PATH*4];
1389 GetShortPathNameW (gio_path, gio_path_short, MAX_PATH);
1391 GetWindowsDirectoryW (rundll_path, MAX_PATH);
1392 wcscat (rundll_path, L"\\rundll32.exe");
1393 if (GetFileAttributesW (rundll_path) == INVALID_FILE_ATTRIBUTES)
1395 GetSystemDirectoryW (rundll_path, MAX_PATH);
1396 wcscat (rundll_path, L"\\rundll32.exe");
1399 wcscpy (args, L"\"");
1400 wcscat (args, rundll_path);
1401 wcscat (args, L"\" ");
1402 wcscat (args, gio_path_short);
1403 #if defined(_WIN64) || defined(_M_X64) || defined(_M_AMD64)
1404 wcscat (args, L",g_win32_run_session_bus");
1405 #elif defined (_MSC_VER)
1406 wcscat (args, L",_g_win32_run_session_bus@16");
1408 wcscat (args, L",g_win32_run_session_bus@16");
1411 res = CreateProcessW (rundll_path, args,
1413 NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW | DETACHED_PROCESS,
1414 0, NULL /* TODO: Should be root */,
1417 address = read_shm (DBUS_DAEMON_ADDRESS_INFO);
1421 release_mutex (autolaunch_mutex);
1423 if (address == NULL)
1427 _("Session dbus not running, and autolaunch failed"));
1433 /* ---------------------------------------------------------------------------------------------------- */
1436 get_session_address_platform_specific (GError **error)
1439 #if defined (G_OS_UNIX) || defined(G_OS_WIN32)
1440 /* need to handle OS X in a different way since 'dbus-launch --autolaunch' probably won't work there */
1441 ret = get_session_address_dbus_launch (error);
1443 /* TODO: implement for OS X */
1448 _("Cannot determine session bus address (not implemented for this OS)"));
1453 /* ---------------------------------------------------------------------------------------------------- */
1456 * g_dbus_address_get_for_bus_sync:
1457 * @bus_type: A #GBusType.
1458 * @cancellable: (allow-none): A #GCancellable or %NULL.
1459 * @error: Return location for error or %NULL.
1461 * Synchronously looks up the D-Bus address for the well-known message
1462 * bus instance specified by @bus_type. This may involve using various
1463 * platform specific mechanisms.
1465 * Returns: A valid D-Bus address string for @bus_type or %NULL if @error is set.
1470 g_dbus_address_get_for_bus_sync (GBusType bus_type,
1471 GCancellable *cancellable,
1475 const gchar *starter_bus;
1476 GError *local_error;
1478 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1483 if (G_UNLIKELY (_g_dbus_debug_address ()))
1486 _g_dbus_debug_print_lock ();
1487 g_print ("GDBus-debug:Address: In g_dbus_address_get_for_bus_sync() for bus type '%s'\n",
1488 _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type));
1489 for (n = 0; n < 3; n++)
1495 case 0: k = "DBUS_SESSION_BUS_ADDRESS"; break;
1496 case 1: k = "DBUS_SYSTEM_BUS_ADDRESS"; break;
1497 case 2: k = "DBUS_STARTER_BUS_TYPE"; break;
1498 default: g_assert_not_reached ();
1501 g_print ("GDBus-debug:Address: env var %s", k);
1503 g_print ("='%s'\n", v);
1505 g_print (" is not set\n");
1507 _g_dbus_debug_print_unlock ();
1512 case G_BUS_TYPE_SYSTEM:
1513 ret = g_strdup (g_getenv ("DBUS_SYSTEM_BUS_ADDRESS"));
1516 ret = g_strdup ("unix:path=/var/run/dbus/system_bus_socket");
1520 case G_BUS_TYPE_SESSION:
1521 ret = g_strdup (g_getenv ("DBUS_SESSION_BUS_ADDRESS"));
1524 ret = get_session_address_platform_specific (&local_error);
1528 case G_BUS_TYPE_STARTER:
1529 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
1530 if (g_strcmp0 (starter_bus, "session") == 0)
1532 ret = g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SESSION, cancellable, &local_error);
1535 else if (g_strcmp0 (starter_bus, "system") == 0)
1537 ret = g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SYSTEM, cancellable, &local_error);
1542 if (starter_bus != NULL)
1544 g_set_error (&local_error,
1547 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
1548 " - unknown value '%s'"),
1553 g_set_error_literal (&local_error,
1556 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
1557 "variable is not set"));
1563 g_set_error (&local_error,
1566 _("Unknown bus type %d"),
1572 if (G_UNLIKELY (_g_dbus_debug_address ()))
1574 _g_dbus_debug_print_lock ();
1577 g_print ("GDBus-debug:Address: Returning address '%s' for bus type '%s'\n",
1579 _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type));
1583 g_print ("GDBus-debug:Address: Cannot look-up address bus type '%s': %s\n",
1584 _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type),
1585 local_error ? local_error->message : "");
1587 _g_dbus_debug_print_unlock ();
1590 if (local_error != NULL)
1591 g_propagate_error (error, local_error);
1597 * g_dbus_address_escape_value:
1598 * @string: an unescaped string to be included in a D-Bus address
1599 * as the value in a key-value pair
1601 * Escape @string so it can appear in a D-Bus address as the value
1602 * part of a key-value pair.
1604 * For instance, if @string is <code>/run/bus-for-:0</code>,
1605 * this function would return <code>/run/bus-for-%3A0</code>,
1606 * which could be used in a D-Bus address like
1607 * <code>unix:nonce-tcp:host=127.0.0.1,port=42,noncefile=/run/bus-for-%3A0</code>.
1609 * Returns: (transfer full): a copy of @string with all
1610 * non-optionally-escaped bytes escaped
1615 g_dbus_address_escape_value (const gchar *string)
1620 g_return_val_if_fail (string != NULL, NULL);
1622 /* There will often not be anything needing escaping at all. */
1623 s = g_string_sized_new (strlen (string));
1625 /* D-Bus address escaping is mostly the same as URI escaping... */
1626 g_string_append_uri_escaped (s, string, "\\/", FALSE);
1628 /* ... but '~' is an unreserved character in URIs, but a
1629 * non-optionally-escaped character in D-Bus addresses. */
1630 for (i = 0; i < s->len; i++)
1632 if (G_UNLIKELY (s->str[i] == '~'))
1635 g_string_insert (s, i + 1, "7E");
1640 return g_string_free (s, FALSE);