Remove developer script not needed in git repository
[glib.git] / gio / gdbusaddress.c
blob2191c115a30c9a70956f4811a4eff49cf43597b8
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.1 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>
21 #include "config.h"
23 #include <stdlib.h>
24 #include <string.h>
25 #include <stdio.h>
26 #include <errno.h>
28 #include "gioerror.h"
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 "gtask.h"
38 #include "glib-private.h"
39 #include "gdbusprivate.h"
40 #include "giomodule-priv.h"
41 #include "gdbusdaemon.h"
42 #include "gstdio.h"
44 #ifdef G_OS_UNIX
45 #include <unistd.h>
46 #include <sys/stat.h>
47 #include <sys/types.h>
48 #include <gio/gunixsocketaddress.h>
49 #endif
51 #ifdef G_OS_WIN32
52 #include <windows.h>
53 #include <io.h>
54 #include <conio.h>
55 #endif
57 #include "glibintl.h"
59 /**
60 * SECTION:gdbusaddress
61 * @title: D-Bus Addresses
62 * @short_description: D-Bus connection endpoints
63 * @include: gio/gio.h
65 * Routines for working with D-Bus addresses. A D-Bus address is a string
66 * like `unix:tmpdir=/tmp/my-app-name`. The exact format of addresses
67 * is explained in detail in the
68 * [D-Bus specification](http://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
70 * TCP D-Bus connections are supported, but accessing them via a proxy is
71 * currently not supported.
74 static gchar *get_session_address_platform_specific (GError **error);
75 static gchar *get_session_address_dbus_launch (GError **error);
77 /* ---------------------------------------------------------------------------------------------------- */
79 /**
80 * g_dbus_is_address:
81 * @string: A string.
83 * Checks if @string is a
84 * [D-Bus address](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
86 * This doesn't check if @string is actually supported by #GDBusServer
87 * or #GDBusConnection - use g_dbus_is_supported_address() to do more
88 * checks.
90 * Returns: %TRUE if @string is a valid D-Bus address, %FALSE otherwise.
92 * Since: 2.26
94 gboolean
95 g_dbus_is_address (const gchar *string)
97 guint n;
98 gchar **a;
99 gboolean ret;
101 ret = FALSE;
103 g_return_val_if_fail (string != NULL, FALSE);
105 a = g_strsplit (string, ";", 0);
106 if (a[0] == NULL)
107 goto out;
109 for (n = 0; a[n] != NULL; n++)
111 if (!_g_dbus_address_parse_entry (a[n],
112 NULL,
113 NULL,
114 NULL))
115 goto out;
118 ret = TRUE;
120 out:
121 g_strfreev (a);
122 return ret;
125 static gboolean
126 is_valid_unix (const gchar *address_entry,
127 GHashTable *key_value_pairs,
128 GError **error)
130 gboolean ret;
131 GList *keys;
132 GList *l;
133 const gchar *path;
134 const gchar *tmpdir;
135 const gchar *abstract;
137 ret = FALSE;
138 keys = NULL;
139 path = NULL;
140 tmpdir = NULL;
141 abstract = NULL;
143 keys = g_hash_table_get_keys (key_value_pairs);
144 for (l = keys; l != NULL; l = l->next)
146 const gchar *key = l->data;
147 if (g_strcmp0 (key, "path") == 0)
148 path = g_hash_table_lookup (key_value_pairs, key);
149 else if (g_strcmp0 (key, "tmpdir") == 0)
150 tmpdir = g_hash_table_lookup (key_value_pairs, key);
151 else if (g_strcmp0 (key, "abstract") == 0)
152 abstract = g_hash_table_lookup (key_value_pairs, key);
153 else
155 g_set_error (error,
156 G_IO_ERROR,
157 G_IO_ERROR_INVALID_ARGUMENT,
158 _("Unsupported key “%s” in address entry “%s”"),
159 key,
160 address_entry);
161 goto out;
165 if (path != NULL)
167 if (tmpdir != NULL || abstract != NULL)
168 goto meaningless;
170 else if (tmpdir != NULL)
172 if (path != NULL || abstract != NULL)
173 goto meaningless;
175 else if (abstract != NULL)
177 if (path != NULL || tmpdir != NULL)
178 goto meaningless;
180 else
182 g_set_error (error,
183 G_IO_ERROR,
184 G_IO_ERROR_INVALID_ARGUMENT,
185 _("Address “%s” is invalid (need exactly one of path, tmpdir or abstract keys)"),
186 address_entry);
187 goto out;
191 ret= TRUE;
192 goto out;
194 meaningless:
195 g_set_error (error,
196 G_IO_ERROR,
197 G_IO_ERROR_INVALID_ARGUMENT,
198 _("Meaningless key/value pair combination in address entry “%s”"),
199 address_entry);
201 out:
202 g_list_free (keys);
204 return ret;
207 static gboolean
208 is_valid_nonce_tcp (const gchar *address_entry,
209 GHashTable *key_value_pairs,
210 GError **error)
212 gboolean ret;
213 GList *keys;
214 GList *l;
215 const gchar *host;
216 const gchar *port;
217 const gchar *family;
218 const gchar *nonce_file;
219 gint port_num;
220 gchar *endp;
222 ret = FALSE;
223 keys = NULL;
224 host = NULL;
225 port = NULL;
226 family = NULL;
227 nonce_file = NULL;
229 keys = g_hash_table_get_keys (key_value_pairs);
230 for (l = keys; l != NULL; l = l->next)
232 const gchar *key = l->data;
233 if (g_strcmp0 (key, "host") == 0)
234 host = g_hash_table_lookup (key_value_pairs, key);
235 else if (g_strcmp0 (key, "port") == 0)
236 port = g_hash_table_lookup (key_value_pairs, key);
237 else if (g_strcmp0 (key, "family") == 0)
238 family = g_hash_table_lookup (key_value_pairs, key);
239 else if (g_strcmp0 (key, "noncefile") == 0)
240 nonce_file = g_hash_table_lookup (key_value_pairs, key);
241 else
243 g_set_error (error,
244 G_IO_ERROR,
245 G_IO_ERROR_INVALID_ARGUMENT,
246 _("Unsupported key “%s” in address entry “%s”"),
247 key,
248 address_entry);
249 goto out;
253 if (port != NULL)
255 port_num = strtol (port, &endp, 10);
256 if ((*port == '\0' || *endp != '\0') || port_num < 0 || port_num >= 65536)
258 g_set_error (error,
259 G_IO_ERROR,
260 G_IO_ERROR_INVALID_ARGUMENT,
261 _("Error in address “%s” — the port attribute is malformed"),
262 address_entry);
263 goto out;
267 if (family != NULL && !(g_strcmp0 (family, "ipv4") == 0 || g_strcmp0 (family, "ipv6") == 0))
269 g_set_error (error,
270 G_IO_ERROR,
271 G_IO_ERROR_INVALID_ARGUMENT,
272 _("Error in address “%s” — the family attribute is malformed"),
273 address_entry);
274 goto out;
277 if (host != NULL)
279 /* TODO: validate host */
282 nonce_file = nonce_file; /* To avoid -Wunused-but-set-variable */
284 ret= TRUE;
286 out:
287 g_list_free (keys);
289 return ret;
292 static gboolean
293 is_valid_tcp (const gchar *address_entry,
294 GHashTable *key_value_pairs,
295 GError **error)
297 gboolean ret;
298 GList *keys;
299 GList *l;
300 const gchar *host;
301 const gchar *port;
302 const gchar *family;
303 gint port_num;
304 gchar *endp;
306 ret = FALSE;
307 keys = NULL;
308 host = NULL;
309 port = NULL;
310 family = NULL;
312 keys = g_hash_table_get_keys (key_value_pairs);
313 for (l = keys; l != NULL; l = l->next)
315 const gchar *key = l->data;
316 if (g_strcmp0 (key, "host") == 0)
317 host = g_hash_table_lookup (key_value_pairs, key);
318 else if (g_strcmp0 (key, "port") == 0)
319 port = g_hash_table_lookup (key_value_pairs, key);
320 else if (g_strcmp0 (key, "family") == 0)
321 family = g_hash_table_lookup (key_value_pairs, key);
322 else
324 g_set_error (error,
325 G_IO_ERROR,
326 G_IO_ERROR_INVALID_ARGUMENT,
327 _("Unsupported key “%s” in address entry “%s”"),
328 key,
329 address_entry);
330 goto out;
334 if (port != NULL)
336 port_num = strtol (port, &endp, 10);
337 if ((*port == '\0' || *endp != '\0') || port_num < 0 || port_num >= 65536)
339 g_set_error (error,
340 G_IO_ERROR,
341 G_IO_ERROR_INVALID_ARGUMENT,
342 _("Error in address “%s” — the port attribute is malformed"),
343 address_entry);
344 goto out;
348 if (family != NULL && !(g_strcmp0 (family, "ipv4") == 0 || g_strcmp0 (family, "ipv6") == 0))
350 g_set_error (error,
351 G_IO_ERROR,
352 G_IO_ERROR_INVALID_ARGUMENT,
353 _("Error in address “%s” — the family attribute is malformed"),
354 address_entry);
355 goto out;
358 if (host != NULL)
360 /* TODO: validate host */
363 ret= TRUE;
365 out:
366 g_list_free (keys);
368 return ret;
372 * g_dbus_is_supported_address:
373 * @string: A string.
374 * @error: Return location for error or %NULL.
376 * Like g_dbus_is_address() but also checks if the library supports the
377 * transports in @string and that key/value pairs for each transport
378 * are valid. See the specification of the
379 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
381 * Returns: %TRUE if @string is a valid D-Bus address that is
382 * supported by this library, %FALSE if @error is set.
384 * Since: 2.26
386 gboolean
387 g_dbus_is_supported_address (const gchar *string,
388 GError **error)
390 guint n;
391 gchar **a;
392 gboolean ret;
394 ret = FALSE;
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;
404 gboolean supported;
406 if (!_g_dbus_address_parse_entry (a[n],
407 &transport_name,
408 &key_value_pairs,
409 error))
410 goto out;
412 supported = FALSE;
413 if (g_strcmp0 (transport_name, "unix") == 0)
414 supported = is_valid_unix (a[n], key_value_pairs, error);
415 else if (g_strcmp0 (transport_name, "tcp") == 0)
416 supported = is_valid_tcp (a[n], key_value_pairs, error);
417 else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
418 supported = is_valid_nonce_tcp (a[n], key_value_pairs, error);
419 else if (g_strcmp0 (a[n], "autolaunch:") == 0)
420 supported = TRUE;
422 g_free (transport_name);
423 g_hash_table_unref (key_value_pairs);
425 if (!supported)
426 goto out;
429 ret = TRUE;
431 out:
432 g_strfreev (a);
434 g_assert (ret || (!ret && (error == NULL || *error != NULL)));
436 return ret;
439 gboolean
440 _g_dbus_address_parse_entry (const gchar *address_entry,
441 gchar **out_transport_name,
442 GHashTable **out_key_value_pairs,
443 GError **error)
445 gboolean ret;
446 GHashTable *key_value_pairs;
447 gchar *transport_name;
448 gchar **kv_pairs;
449 const gchar *s;
450 guint n;
452 ret = FALSE;
453 kv_pairs = NULL;
454 transport_name = NULL;
455 key_value_pairs = NULL;
457 s = strchr (address_entry, ':');
458 if (s == NULL)
460 g_set_error (error,
461 G_IO_ERROR,
462 G_IO_ERROR_INVALID_ARGUMENT,
463 _("Address element “%s” does not contain a colon (:)"),
464 address_entry);
465 goto out;
468 transport_name = g_strndup (address_entry, s - address_entry);
469 key_value_pairs = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
471 kv_pairs = g_strsplit (s + 1, ",", 0);
472 for (n = 0; kv_pairs != NULL && kv_pairs[n] != NULL; n++)
474 const gchar *kv_pair = kv_pairs[n];
475 gchar *key;
476 gchar *value;
478 s = strchr (kv_pair, '=');
479 if (s == NULL)
481 g_set_error (error,
482 G_IO_ERROR,
483 G_IO_ERROR_INVALID_ARGUMENT,
484 _("Key/Value pair %d, “%s”, in address element “%s” does not contain an equal sign"),
486 kv_pair,
487 address_entry);
488 goto out;
491 key = g_uri_unescape_segment (kv_pair, s, NULL);
492 value = g_uri_unescape_segment (s + 1, kv_pair + strlen (kv_pair), NULL);
493 if (key == NULL || value == NULL)
495 g_set_error (error,
496 G_IO_ERROR,
497 G_IO_ERROR_INVALID_ARGUMENT,
498 _("Error unescaping key or value in Key/Value pair %d, “%s”, in address element “%s”"),
500 kv_pair,
501 address_entry);
502 g_free (key);
503 g_free (value);
504 goto out;
506 g_hash_table_insert (key_value_pairs, key, value);
509 ret = TRUE;
511 out:
512 g_strfreev (kv_pairs);
513 if (ret)
515 if (out_transport_name != NULL)
516 *out_transport_name = transport_name;
517 else
518 g_free (transport_name);
519 if (out_key_value_pairs != NULL)
520 *out_key_value_pairs = key_value_pairs;
521 else if (key_value_pairs != NULL)
522 g_hash_table_unref (key_value_pairs);
524 else
526 g_free (transport_name);
527 if (key_value_pairs != NULL)
528 g_hash_table_unref (key_value_pairs);
530 return ret;
533 /* ---------------------------------------------------------------------------------------------------- */
535 static GIOStream *
536 g_dbus_address_try_connect_one (const gchar *address_entry,
537 gchar **out_guid,
538 GCancellable *cancellable,
539 GError **error);
541 /* TODO: Declare an extension point called GDBusTransport (or similar)
542 * and move code below to extensions implementing said extension
543 * point. That way we can implement a D-Bus transport over X11 without
544 * making libgio link to libX11...
546 static GIOStream *
547 g_dbus_address_connect (const gchar *address_entry,
548 const gchar *transport_name,
549 GHashTable *key_value_pairs,
550 GCancellable *cancellable,
551 GError **error)
553 GIOStream *ret;
554 GSocketConnectable *connectable;
555 const gchar *nonce_file;
557 connectable = NULL;
558 ret = NULL;
559 nonce_file = NULL;
561 if (FALSE)
564 #ifdef G_OS_UNIX
565 else if (g_strcmp0 (transport_name, "unix") == 0)
567 const gchar *path;
568 const gchar *abstract;
569 path = g_hash_table_lookup (key_value_pairs, "path");
570 abstract = g_hash_table_lookup (key_value_pairs, "abstract");
571 if ((path == NULL && abstract == NULL) || (path != NULL && abstract != NULL))
573 g_set_error (error,
574 G_IO_ERROR,
575 G_IO_ERROR_INVALID_ARGUMENT,
576 _("Error in address “%s” — the unix transport requires exactly one of the "
577 "keys “path” or “abstract” to be set"),
578 address_entry);
580 else if (path != NULL)
582 connectable = G_SOCKET_CONNECTABLE (g_unix_socket_address_new (path));
584 else if (abstract != NULL)
586 connectable = G_SOCKET_CONNECTABLE (g_unix_socket_address_new_with_type (abstract,
588 G_UNIX_SOCKET_ADDRESS_ABSTRACT));
590 else
592 g_assert_not_reached ();
595 #endif
596 else if (g_strcmp0 (transport_name, "tcp") == 0 || g_strcmp0 (transport_name, "nonce-tcp") == 0)
598 const gchar *s;
599 const gchar *host;
600 glong port;
601 gchar *endp;
602 gboolean is_nonce;
604 is_nonce = (g_strcmp0 (transport_name, "nonce-tcp") == 0);
606 host = g_hash_table_lookup (key_value_pairs, "host");
607 if (host == NULL)
609 g_set_error (error,
610 G_IO_ERROR,
611 G_IO_ERROR_INVALID_ARGUMENT,
612 _("Error in address “%s” — the host attribute is missing or malformed"),
613 address_entry);
614 goto out;
617 s = g_hash_table_lookup (key_value_pairs, "port");
618 if (s == NULL)
619 s = "0";
620 port = strtol (s, &endp, 10);
621 if ((*s == '\0' || *endp != '\0') || port < 0 || port >= 65536)
623 g_set_error (error,
624 G_IO_ERROR,
625 G_IO_ERROR_INVALID_ARGUMENT,
626 _("Error in address “%s” — the port attribute is missing or malformed"),
627 address_entry);
628 goto out;
632 if (is_nonce)
634 nonce_file = g_hash_table_lookup (key_value_pairs, "noncefile");
635 if (nonce_file == NULL)
637 g_set_error (error,
638 G_IO_ERROR,
639 G_IO_ERROR_INVALID_ARGUMENT,
640 _("Error in address “%s” — the noncefile attribute is missing or malformed"),
641 address_entry);
642 goto out;
646 /* TODO: deal with family key/value-pair */
647 connectable = g_network_address_new (host, port);
649 else if (g_strcmp0 (address_entry, "autolaunch:") == 0)
651 gchar *autolaunch_address;
652 autolaunch_address = get_session_address_dbus_launch (error);
653 if (autolaunch_address != NULL)
655 ret = g_dbus_address_try_connect_one (autolaunch_address, NULL, cancellable, error);
656 g_free (autolaunch_address);
657 goto out;
659 else
661 g_prefix_error (error, _("Error auto-launching: "));
664 else
666 g_set_error (error,
667 G_IO_ERROR,
668 G_IO_ERROR_INVALID_ARGUMENT,
669 _("Unknown or unsupported transport “%s” for address “%s”"),
670 transport_name,
671 address_entry);
674 if (connectable != NULL)
676 GSocketClient *client;
677 GSocketConnection *connection;
679 g_assert (ret == NULL);
680 client = g_socket_client_new ();
682 /* Disable proxy support to prevent a deadlock on startup, since loading a
683 * proxy resolver causes the GIO modules to be loaded, and there will
684 * almost certainly be one of them which then tries to use GDBus.
685 * See: https://bugzilla.gnome.org/show_bug.cgi?id=792499 */
686 g_socket_client_set_enable_proxy (client, FALSE);
688 connection = g_socket_client_connect (client,
689 connectable,
690 cancellable,
691 error);
692 g_object_unref (connectable);
693 g_object_unref (client);
694 if (connection == NULL)
695 goto out;
697 ret = G_IO_STREAM (connection);
699 if (nonce_file != NULL)
701 gchar nonce_contents[16 + 1];
702 size_t num_bytes_read;
703 FILE *f;
704 int errsv;
706 /* be careful to read only 16 bytes - we also check that the file is only 16 bytes long */
707 f = fopen (nonce_file, "rb");
708 errsv = errno;
709 if (f == NULL)
711 g_set_error (error,
712 G_IO_ERROR,
713 G_IO_ERROR_INVALID_ARGUMENT,
714 _("Error opening nonce file “%s”: %s"),
715 nonce_file,
716 g_strerror (errsv));
717 g_object_unref (ret);
718 ret = NULL;
719 goto out;
721 num_bytes_read = fread (nonce_contents,
722 sizeof (gchar),
723 16 + 1,
725 errsv = errno;
726 if (num_bytes_read != 16)
728 if (num_bytes_read == 0)
730 g_set_error (error,
731 G_IO_ERROR,
732 G_IO_ERROR_INVALID_ARGUMENT,
733 _("Error reading from nonce file “%s”: %s"),
734 nonce_file,
735 g_strerror (errsv));
737 else
739 g_set_error (error,
740 G_IO_ERROR,
741 G_IO_ERROR_INVALID_ARGUMENT,
742 _("Error reading from nonce file “%s”, expected 16 bytes, got %d"),
743 nonce_file,
744 (gint) num_bytes_read);
746 g_object_unref (ret);
747 ret = NULL;
748 fclose (f);
749 goto out;
751 fclose (f);
753 if (!g_output_stream_write_all (g_io_stream_get_output_stream (ret),
754 nonce_contents,
756 NULL,
757 cancellable,
758 error))
760 g_prefix_error (error, _("Error writing contents of nonce file “%s” to stream:"), nonce_file);
761 g_object_unref (ret);
762 ret = NULL;
763 goto out;
768 out:
770 return ret;
773 static GIOStream *
774 g_dbus_address_try_connect_one (const gchar *address_entry,
775 gchar **out_guid,
776 GCancellable *cancellable,
777 GError **error)
779 GIOStream *ret;
780 GHashTable *key_value_pairs;
781 gchar *transport_name;
782 const gchar *guid;
784 ret = NULL;
785 transport_name = NULL;
786 key_value_pairs = NULL;
788 if (!_g_dbus_address_parse_entry (address_entry,
789 &transport_name,
790 &key_value_pairs,
791 error))
792 goto out;
794 ret = g_dbus_address_connect (address_entry,
795 transport_name,
796 key_value_pairs,
797 cancellable,
798 error);
799 if (ret == NULL)
800 goto out;
802 guid = g_hash_table_lookup (key_value_pairs, "guid");
803 if (guid != NULL && out_guid != NULL)
804 *out_guid = g_strdup (guid);
806 out:
807 g_free (transport_name);
808 if (key_value_pairs != NULL)
809 g_hash_table_unref (key_value_pairs);
810 return ret;
814 /* ---------------------------------------------------------------------------------------------------- */
816 typedef struct {
817 gchar *address;
818 gchar *guid;
819 } GetStreamData;
821 static void
822 get_stream_data_free (GetStreamData *data)
824 g_free (data->address);
825 g_free (data->guid);
826 g_free (data);
829 static void
830 get_stream_thread_func (GTask *task,
831 gpointer source_object,
832 gpointer task_data,
833 GCancellable *cancellable)
835 GetStreamData *data = task_data;
836 GIOStream *stream;
837 GError *error = NULL;
839 stream = g_dbus_address_get_stream_sync (data->address,
840 &data->guid,
841 cancellable,
842 &error);
843 if (stream)
844 g_task_return_pointer (task, stream, g_object_unref);
845 else
846 g_task_return_error (task, error);
850 * g_dbus_address_get_stream:
851 * @address: A valid D-Bus address.
852 * @cancellable: (nullable): A #GCancellable or %NULL.
853 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
854 * @user_data: Data to pass to @callback.
856 * Asynchronously connects to an endpoint specified by @address and
857 * sets up the connection so it is in a state to run the client-side
858 * of the D-Bus authentication conversation. @address must be in the
859 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
861 * When the operation is finished, @callback will be invoked. You can
862 * then call g_dbus_address_get_stream_finish() to get the result of
863 * the operation.
865 * This is an asynchronous failable function. See
866 * g_dbus_address_get_stream_sync() for the synchronous version.
868 * Since: 2.26
870 void
871 g_dbus_address_get_stream (const gchar *address,
872 GCancellable *cancellable,
873 GAsyncReadyCallback callback,
874 gpointer user_data)
876 GTask *task;
877 GetStreamData *data;
879 g_return_if_fail (address != NULL);
881 data = g_new0 (GetStreamData, 1);
882 data->address = g_strdup (address);
884 task = g_task_new (NULL, cancellable, callback, user_data);
885 g_task_set_source_tag (task, g_dbus_address_get_stream);
886 g_task_set_task_data (task, data, (GDestroyNotify) get_stream_data_free);
887 g_task_run_in_thread (task, get_stream_thread_func);
888 g_object_unref (task);
892 * g_dbus_address_get_stream_finish:
893 * @res: A #GAsyncResult obtained from the GAsyncReadyCallback passed to g_dbus_address_get_stream().
894 * @out_guid: (optional) (out): %NULL or return location to store the GUID extracted from @address, if any.
895 * @error: Return location for error or %NULL.
897 * Finishes an operation started with g_dbus_address_get_stream().
899 * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
901 * Since: 2.26
903 GIOStream *
904 g_dbus_address_get_stream_finish (GAsyncResult *res,
905 gchar **out_guid,
906 GError **error)
908 GTask *task;
909 GetStreamData *data;
910 GIOStream *ret;
912 g_return_val_if_fail (g_task_is_valid (res, NULL), NULL);
913 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
915 task = G_TASK (res);
916 ret = g_task_propagate_pointer (task, error);
918 if (ret != NULL && out_guid != NULL)
920 data = g_task_get_task_data (task);
921 *out_guid = data->guid;
922 data->guid = NULL;
925 return ret;
929 * g_dbus_address_get_stream_sync:
930 * @address: A valid D-Bus address.
931 * @out_guid: (optional) (out): %NULL or return location to store the GUID extracted from @address, if any.
932 * @cancellable: (nullable): A #GCancellable or %NULL.
933 * @error: Return location for error or %NULL.
935 * Synchronously connects to an endpoint specified by @address and
936 * sets up the connection so it is in a state to run the client-side
937 * of the D-Bus authentication conversation. @address must be in the
938 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
940 * This is a synchronous failable function. See
941 * g_dbus_address_get_stream() for the asynchronous version.
943 * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
945 * Since: 2.26
947 GIOStream *
948 g_dbus_address_get_stream_sync (const gchar *address,
949 gchar **out_guid,
950 GCancellable *cancellable,
951 GError **error)
953 GIOStream *ret;
954 gchar **addr_array;
955 guint n;
956 GError *last_error;
958 g_return_val_if_fail (address != NULL, NULL);
959 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
961 ret = NULL;
962 last_error = NULL;
964 addr_array = g_strsplit (address, ";", 0);
965 if (addr_array != NULL && addr_array[0] == NULL)
967 last_error = g_error_new_literal (G_IO_ERROR,
968 G_IO_ERROR_INVALID_ARGUMENT,
969 _("The given address is empty"));
970 goto out;
973 for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
975 const gchar *addr = addr_array[n];
976 GError *this_error;
978 this_error = NULL;
979 ret = g_dbus_address_try_connect_one (addr,
980 out_guid,
981 cancellable,
982 &this_error);
983 if (ret != NULL)
985 goto out;
987 else
989 g_assert (this_error != NULL);
990 if (last_error != NULL)
991 g_error_free (last_error);
992 last_error = this_error;
996 out:
997 if (ret != NULL)
999 if (last_error != NULL)
1000 g_error_free (last_error);
1002 else
1004 g_assert (last_error != NULL);
1005 g_propagate_error (error, last_error);
1008 g_strfreev (addr_array);
1009 return ret;
1012 /* ---------------------------------------------------------------------------------------------------- */
1015 * Return the address of XDG_RUNTIME_DIR/bus if it exists, belongs to
1016 * us, and is a socket, and we are on Unix.
1018 static gchar *
1019 get_session_address_xdg (void)
1021 #ifdef G_OS_UNIX
1022 gchar *ret = NULL;
1023 gchar *bus;
1024 gchar *tmp;
1025 GStatBuf buf;
1027 bus = g_build_filename (g_get_user_runtime_dir (), "bus", NULL);
1029 /* if ENOENT, EPERM, etc., quietly don't use it */
1030 if (g_stat (bus, &buf) < 0)
1031 goto out;
1033 /* if it isn't ours, we have incorrectly inherited someone else's
1034 * XDG_RUNTIME_DIR; silently don't use it
1036 if (buf.st_uid != geteuid ())
1037 goto out;
1039 /* if it isn't a socket, silently don't use it */
1040 if ((buf.st_mode & S_IFMT) != S_IFSOCK)
1041 goto out;
1043 tmp = g_dbus_address_escape_value (bus);
1044 ret = g_strconcat ("unix:path=", tmp, NULL);
1045 g_free (tmp);
1047 out:
1048 g_free (bus);
1049 return ret;
1050 #else
1051 return NULL;
1052 #endif
1055 /* ---------------------------------------------------------------------------------------------------- */
1057 #ifdef G_OS_UNIX
1058 static gchar *
1059 get_session_address_dbus_launch (GError **error)
1061 gchar *ret;
1062 gchar *machine_id;
1063 gchar *command_line;
1064 gchar *launch_stdout;
1065 gchar *launch_stderr;
1066 gint exit_status;
1067 gchar *old_dbus_verbose;
1068 gboolean restore_dbus_verbose;
1070 ret = NULL;
1071 machine_id = NULL;
1072 command_line = NULL;
1073 launch_stdout = NULL;
1074 launch_stderr = NULL;
1075 restore_dbus_verbose = FALSE;
1076 old_dbus_verbose = NULL;
1078 /* Don't run binaries as root if we're setuid. */
1079 if (GLIB_PRIVATE_CALL (g_check_setuid) ())
1081 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1082 _("Cannot spawn a message bus when setuid"));
1083 goto out;
1086 machine_id = _g_dbus_get_machine_id (error);
1087 if (machine_id == NULL)
1089 g_prefix_error (error, _("Cannot spawn a message bus without a machine-id: "));
1090 goto out;
1093 if (g_getenv ("DISPLAY") == NULL)
1095 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1096 _("Cannot autolaunch D-Bus without X11 $DISPLAY"));
1097 goto out;
1100 /* We're using private libdbus facilities here. When everything
1101 * (X11, Mac OS X, Windows) is spec'ed out correctly (not even the
1102 * X11 property is correctly documented right now) we should
1103 * consider using the spec instead of dbus-launch.
1105 * --autolaunch=MACHINEID
1106 * This option implies that dbus-launch should scan for a previ‐
1107 * ously-started session and reuse the values found there. If no
1108 * session is found, it will start a new session. The --exit-with-
1109 * session option is implied if --autolaunch is given. This option
1110 * is for the exclusive use of libdbus, you do not want to use it
1111 * manually. It may change in the future.
1114 /* TODO: maybe provide a variable for where to look for the dbus-launch binary? */
1115 command_line = g_strdup_printf ("dbus-launch --autolaunch=%s --binary-syntax --close-stderr", machine_id);
1117 if (G_UNLIKELY (_g_dbus_debug_address ()))
1119 _g_dbus_debug_print_lock ();
1120 g_print ("GDBus-debug:Address: Running '%s' to get bus address (possibly autolaunching)\n", command_line);
1121 old_dbus_verbose = g_strdup (g_getenv ("DBUS_VERBOSE"));
1122 restore_dbus_verbose = TRUE;
1123 g_setenv ("DBUS_VERBOSE", "1", TRUE);
1124 _g_dbus_debug_print_unlock ();
1127 if (!g_spawn_command_line_sync (command_line,
1128 &launch_stdout,
1129 &launch_stderr,
1130 &exit_status,
1131 error))
1133 goto out;
1136 if (!g_spawn_check_exit_status (exit_status, error))
1138 g_prefix_error (error, _("Error spawning command line “%s”: "), command_line);
1139 goto out;
1142 /* From the dbus-launch(1) man page:
1144 * --binary-syntax Write to stdout a nul-terminated bus address,
1145 * then the bus PID as a binary integer of size sizeof(pid_t),
1146 * then the bus X window ID as a binary integer of size
1147 * sizeof(long). Integers are in the machine's byte order, not
1148 * network byte order or any other canonical byte order.
1150 ret = g_strdup (launch_stdout);
1152 out:
1153 if (G_UNLIKELY (_g_dbus_debug_address ()))
1155 gchar *s;
1156 _g_dbus_debug_print_lock ();
1157 g_print ("GDBus-debug:Address: dbus-launch output:");
1158 if (launch_stdout != NULL)
1160 s = _g_dbus_hexdump (launch_stdout, strlen (launch_stdout) + 1 + sizeof (pid_t) + sizeof (long), 2);
1161 g_print ("\n%s", s);
1162 g_free (s);
1164 else
1166 g_print (" (none)\n");
1168 g_print ("GDBus-debug:Address: dbus-launch stderr output:");
1169 if (launch_stderr != NULL)
1170 g_print ("\n%s", launch_stderr);
1171 else
1172 g_print (" (none)\n");
1173 _g_dbus_debug_print_unlock ();
1176 g_free (machine_id);
1177 g_free (command_line);
1178 g_free (launch_stdout);
1179 g_free (launch_stderr);
1180 if (G_UNLIKELY (restore_dbus_verbose))
1182 if (old_dbus_verbose != NULL)
1183 g_setenv ("DBUS_VERBOSE", old_dbus_verbose, TRUE);
1184 else
1185 g_unsetenv ("DBUS_VERBOSE");
1187 g_free (old_dbus_verbose);
1188 return ret;
1191 /* end of G_OS_UNIX case */
1192 #elif defined(G_OS_WIN32)
1194 #define DBUS_DAEMON_ADDRESS_INFO "DBusDaemonAddressInfo"
1195 #define DBUS_DAEMON_MUTEX "DBusDaemonMutex"
1196 #define UNIQUE_DBUS_INIT_MUTEX "UniqueDBusInitMutex"
1197 #define DBUS_AUTOLAUNCH_MUTEX "DBusAutolaunchMutex"
1199 static void
1200 release_mutex (HANDLE mutex)
1202 ReleaseMutex (mutex);
1203 CloseHandle (mutex);
1206 static HANDLE
1207 acquire_mutex (const char *mutexname)
1209 HANDLE mutex;
1210 DWORD res;
1212 mutex = CreateMutexA (NULL, FALSE, mutexname);
1213 if (!mutex)
1214 return 0;
1216 res = WaitForSingleObject (mutex, INFINITE);
1217 switch (res)
1219 case WAIT_ABANDONED:
1220 release_mutex (mutex);
1221 return 0;
1222 case WAIT_FAILED:
1223 case WAIT_TIMEOUT:
1224 return 0;
1227 return mutex;
1230 static gboolean
1231 is_mutex_owned (const char *mutexname)
1233 HANDLE mutex;
1234 gboolean res = FALSE;
1236 mutex = CreateMutexA (NULL, FALSE, mutexname);
1237 if (WaitForSingleObject (mutex, 10) == WAIT_TIMEOUT)
1238 res = TRUE;
1239 else
1240 ReleaseMutex (mutex);
1241 CloseHandle (mutex);
1243 return res;
1246 static char *
1247 read_shm (const char *shm_name)
1249 HANDLE shared_mem;
1250 char *shared_data;
1251 char *res;
1252 int i;
1254 res = NULL;
1256 for (i = 0; i < 20; i++)
1258 shared_mem = OpenFileMappingA (FILE_MAP_READ, FALSE, shm_name);
1259 if (shared_mem != 0)
1260 break;
1261 Sleep (100);
1264 if (shared_mem != 0)
1266 shared_data = MapViewOfFile (shared_mem, FILE_MAP_READ, 0, 0, 0);
1267 if (shared_data != NULL)
1269 res = g_strdup (shared_data);
1270 UnmapViewOfFile (shared_data);
1272 CloseHandle (shared_mem);
1275 return res;
1278 static HANDLE
1279 set_shm (const char *shm_name, const char *value)
1281 HANDLE shared_mem;
1282 char *shared_data;
1284 shared_mem = CreateFileMappingA (INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
1285 0, strlen (value) + 1, shm_name);
1286 if (shared_mem == 0)
1287 return 0;
1289 shared_data = MapViewOfFile (shared_mem, FILE_MAP_WRITE, 0, 0, 0 );
1290 if (shared_data == NULL)
1291 return 0;
1293 strcpy (shared_data, value);
1295 UnmapViewOfFile (shared_data);
1297 return shared_mem;
1300 /* These keep state between publish_session_bus and unpublish_session_bus */
1301 static HANDLE published_daemon_mutex;
1302 static HANDLE published_shared_mem;
1304 static gboolean
1305 publish_session_bus (const char *address)
1307 HANDLE init_mutex;
1309 init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
1311 published_daemon_mutex = CreateMutexA (NULL, FALSE, DBUS_DAEMON_MUTEX);
1312 if (WaitForSingleObject (published_daemon_mutex, 10 ) != WAIT_OBJECT_0)
1314 release_mutex (init_mutex);
1315 CloseHandle (published_daemon_mutex);
1316 published_daemon_mutex = NULL;
1317 return FALSE;
1320 published_shared_mem = set_shm (DBUS_DAEMON_ADDRESS_INFO, address);
1321 if (!published_shared_mem)
1323 release_mutex (init_mutex);
1324 CloseHandle (published_daemon_mutex);
1325 published_daemon_mutex = NULL;
1326 return FALSE;
1329 release_mutex (init_mutex);
1330 return TRUE;
1333 static void
1334 unpublish_session_bus (void)
1336 HANDLE init_mutex;
1338 init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
1340 CloseHandle (published_shared_mem);
1341 published_shared_mem = NULL;
1343 release_mutex (published_daemon_mutex);
1344 published_daemon_mutex = NULL;
1346 release_mutex (init_mutex);
1349 static void
1350 wait_console_window (void)
1352 FILE *console = fopen ("CONOUT$", "w");
1354 SetConsoleTitleW (L"gdbus-daemon output. Type any character to close this window.");
1355 fprintf (console, _("(Type any character to close this window)\n"));
1356 fflush (console);
1357 _getch ();
1360 static void
1361 open_console_window (void)
1363 if (((HANDLE) _get_osfhandle (fileno (stdout)) == INVALID_HANDLE_VALUE ||
1364 (HANDLE) _get_osfhandle (fileno (stderr)) == INVALID_HANDLE_VALUE) && AllocConsole ())
1366 if ((HANDLE) _get_osfhandle (fileno (stdout)) == INVALID_HANDLE_VALUE)
1367 freopen ("CONOUT$", "w", stdout);
1369 if ((HANDLE) _get_osfhandle (fileno (stderr)) == INVALID_HANDLE_VALUE)
1370 freopen ("CONOUT$", "w", stderr);
1372 SetConsoleTitleW (L"gdbus-daemon debug output.");
1374 atexit (wait_console_window);
1378 static void
1379 idle_timeout_cb (GDBusDaemon *daemon, gpointer user_data)
1381 GMainLoop *loop = user_data;
1382 g_main_loop_quit (loop);
1385 /* Satisfies STARTF_FORCEONFEEDBACK */
1386 static void
1387 turn_off_the_starting_cursor (void)
1389 MSG msg;
1390 BOOL bRet;
1392 PostQuitMessage (0);
1394 while ((bRet = GetMessage (&msg, 0, 0, 0)) != 0)
1396 if (bRet == -1)
1397 continue;
1399 TranslateMessage (&msg);
1400 DispatchMessage (&msg);
1404 __declspec(dllexport) void CALLBACK g_win32_run_session_bus (HWND hwnd, HINSTANCE hinst, char *cmdline, int nCmdShow);
1406 __declspec(dllexport) void CALLBACK
1407 g_win32_run_session_bus (HWND hwnd, HINSTANCE hinst, char *cmdline, int nCmdShow)
1409 GDBusDaemon *daemon;
1410 GMainLoop *loop;
1411 const char *address;
1412 GError *error = NULL;
1414 turn_off_the_starting_cursor ();
1416 if (g_getenv ("GDBUS_DAEMON_DEBUG") != NULL)
1417 open_console_window ();
1419 loop = g_main_loop_new (NULL, FALSE);
1421 address = "nonce-tcp:";
1422 daemon = _g_dbus_daemon_new (address, NULL, &error);
1423 if (daemon == NULL)
1425 g_printerr ("Can't init bus: %s\n", error->message);
1426 g_error_free (error);
1427 return;
1430 g_signal_connect (daemon, "idle-timeout", G_CALLBACK (idle_timeout_cb), loop);
1432 if (publish_session_bus (_g_dbus_daemon_get_address (daemon)))
1434 g_main_loop_run (loop);
1436 unpublish_session_bus ();
1439 g_main_loop_unref (loop);
1440 g_object_unref (daemon);
1443 static gchar *
1444 get_session_address_dbus_launch (GError **error)
1446 HANDLE autolaunch_mutex, init_mutex;
1447 char *address = NULL;
1448 wchar_t gio_path[MAX_PATH+1+200];
1450 autolaunch_mutex = acquire_mutex (DBUS_AUTOLAUNCH_MUTEX);
1452 init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
1454 if (is_mutex_owned (DBUS_DAEMON_MUTEX))
1455 address = read_shm (DBUS_DAEMON_ADDRESS_INFO);
1457 release_mutex (init_mutex);
1459 if (address == NULL)
1461 gio_path[MAX_PATH] = 0;
1462 if (GetModuleFileNameW (_g_io_win32_get_module (), gio_path, MAX_PATH))
1464 PROCESS_INFORMATION pi = { 0 };
1465 STARTUPINFOW si = { 0 };
1466 BOOL res;
1467 wchar_t gio_path_short[MAX_PATH];
1468 wchar_t rundll_path[MAX_PATH*2];
1469 wchar_t args[MAX_PATH*4];
1471 GetShortPathNameW (gio_path, gio_path_short, MAX_PATH);
1473 GetWindowsDirectoryW (rundll_path, MAX_PATH);
1474 wcscat (rundll_path, L"\\rundll32.exe");
1475 if (GetFileAttributesW (rundll_path) == INVALID_FILE_ATTRIBUTES)
1477 GetSystemDirectoryW (rundll_path, MAX_PATH);
1478 wcscat (rundll_path, L"\\rundll32.exe");
1481 wcscpy (args, L"\"");
1482 wcscat (args, rundll_path);
1483 wcscat (args, L"\" ");
1484 wcscat (args, gio_path_short);
1485 #if defined(_WIN64) || defined(_M_X64) || defined(_M_AMD64)
1486 wcscat (args, L",g_win32_run_session_bus");
1487 #elif defined (_MSC_VER)
1488 wcscat (args, L",_g_win32_run_session_bus@16");
1489 #else
1490 wcscat (args, L",g_win32_run_session_bus@16");
1491 #endif
1493 res = CreateProcessW (rundll_path, args,
1494 0, 0, FALSE,
1495 NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW | DETACHED_PROCESS,
1496 0, NULL /* TODO: Should be root */,
1497 &si, &pi);
1498 if (res)
1499 address = read_shm (DBUS_DAEMON_ADDRESS_INFO);
1503 release_mutex (autolaunch_mutex);
1505 if (address == NULL)
1506 g_set_error (error,
1507 G_IO_ERROR,
1508 G_IO_ERROR_FAILED,
1509 _("Session dbus not running, and autolaunch failed"));
1511 return address;
1513 #else /* neither G_OS_UNIX nor G_OS_WIN32 */
1514 static gchar *
1515 get_session_address_dbus_launch (GError **error)
1517 g_set_error (error,
1518 G_IO_ERROR,
1519 G_IO_ERROR_FAILED,
1520 _("Cannot determine session bus address (not implemented for this OS)"));
1521 return NULL;
1523 #endif /* neither G_OS_UNIX nor G_OS_WIN32 */
1525 /* ---------------------------------------------------------------------------------------------------- */
1527 static gchar *
1528 get_session_address_platform_specific (GError **error)
1530 gchar *ret;
1532 /* Use XDG_RUNTIME_DIR/bus if it exists and is suitable. This is appropriate
1533 * for systems using the "a session is a user-session" model described in
1534 * <http://lists.freedesktop.org/archives/dbus/2015-January/016522.html>,
1535 * and implemented in dbus >= 1.9.14 and sd-bus.
1537 * On systems following the more traditional "a session is a login-session"
1538 * model, this will fail and we'll fall through to X11 autolaunching
1539 * (dbus-launch) below.
1541 ret = get_session_address_xdg ();
1543 if (ret != NULL)
1544 return ret;
1546 /* TODO (#694472): try launchd on OS X, like
1547 * _dbus_lookup_session_address_launchd() does, since
1548 * 'dbus-launch --autolaunch' probably won't work there
1551 /* As a last resort, try the "autolaunch:" transport. On Unix this means
1552 * X11 autolaunching; on Windows this means a different autolaunching
1553 * mechanism based on shared memory.
1555 return get_session_address_dbus_launch (error);
1558 /* ---------------------------------------------------------------------------------------------------- */
1561 * g_dbus_address_get_for_bus_sync:
1562 * @bus_type: a #GBusType
1563 * @cancellable: (nullable): a #GCancellable or %NULL
1564 * @error: return location for error or %NULL
1566 * Synchronously looks up the D-Bus address for the well-known message
1567 * bus instance specified by @bus_type. This may involve using various
1568 * platform specific mechanisms.
1570 * The returned address will be in the
1571 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
1573 * Returns: a valid D-Bus address string for @bus_type or %NULL if
1574 * @error is set
1576 * Since: 2.26
1578 gchar *
1579 g_dbus_address_get_for_bus_sync (GBusType bus_type,
1580 GCancellable *cancellable,
1581 GError **error)
1583 gchar *ret, *s = NULL;
1584 const gchar *starter_bus;
1585 GError *local_error;
1587 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1589 ret = NULL;
1590 local_error = NULL;
1592 if (G_UNLIKELY (_g_dbus_debug_address ()))
1594 guint n;
1595 _g_dbus_debug_print_lock ();
1596 s = _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type);
1597 g_print ("GDBus-debug:Address: In g_dbus_address_get_for_bus_sync() for bus type '%s'\n",
1599 g_free (s);
1600 for (n = 0; n < 3; n++)
1602 const gchar *k;
1603 const gchar *v;
1604 switch (n)
1606 case 0: k = "DBUS_SESSION_BUS_ADDRESS"; break;
1607 case 1: k = "DBUS_SYSTEM_BUS_ADDRESS"; break;
1608 case 2: k = "DBUS_STARTER_BUS_TYPE"; break;
1609 default: g_assert_not_reached ();
1611 v = g_getenv (k);
1612 g_print ("GDBus-debug:Address: env var %s", k);
1613 if (v != NULL)
1614 g_print ("='%s'\n", v);
1615 else
1616 g_print (" is not set\n");
1618 _g_dbus_debug_print_unlock ();
1621 switch (bus_type)
1623 case G_BUS_TYPE_SYSTEM:
1624 ret = g_strdup (g_getenv ("DBUS_SYSTEM_BUS_ADDRESS"));
1625 if (ret == NULL)
1627 ret = g_strdup ("unix:path=/var/run/dbus/system_bus_socket");
1629 break;
1631 case G_BUS_TYPE_SESSION:
1632 ret = g_strdup (g_getenv ("DBUS_SESSION_BUS_ADDRESS"));
1633 if (ret == NULL)
1635 ret = get_session_address_platform_specific (&local_error);
1637 break;
1639 case G_BUS_TYPE_STARTER:
1640 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
1641 if (g_strcmp0 (starter_bus, "session") == 0)
1643 ret = g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SESSION, cancellable, &local_error);
1644 goto out;
1646 else if (g_strcmp0 (starter_bus, "system") == 0)
1648 ret = g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SYSTEM, cancellable, &local_error);
1649 goto out;
1651 else
1653 if (starter_bus != NULL)
1655 g_set_error (&local_error,
1656 G_IO_ERROR,
1657 G_IO_ERROR_FAILED,
1658 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
1659 " — unknown value “%s”"),
1660 starter_bus);
1662 else
1664 g_set_error_literal (&local_error,
1665 G_IO_ERROR,
1666 G_IO_ERROR_FAILED,
1667 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
1668 "variable is not set"));
1671 break;
1673 default:
1674 g_set_error (&local_error,
1675 G_IO_ERROR,
1676 G_IO_ERROR_FAILED,
1677 _("Unknown bus type %d"),
1678 bus_type);
1679 break;
1682 out:
1683 if (G_UNLIKELY (_g_dbus_debug_address ()))
1685 _g_dbus_debug_print_lock ();
1686 s = _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type);
1687 if (ret != NULL)
1689 g_print ("GDBus-debug:Address: Returning address '%s' for bus type '%s'\n",
1690 ret, s);
1692 else
1694 g_print ("GDBus-debug:Address: Cannot look-up address bus type '%s': %s\n",
1695 s, local_error ? local_error->message : "");
1697 g_free (s);
1698 _g_dbus_debug_print_unlock ();
1701 if (local_error != NULL)
1702 g_propagate_error (error, local_error);
1704 return ret;
1708 * g_dbus_address_escape_value:
1709 * @string: an unescaped string to be included in a D-Bus address
1710 * as the value in a key-value pair
1712 * Escape @string so it can appear in a D-Bus address as the value
1713 * part of a key-value pair.
1715 * For instance, if @string is `/run/bus-for-:0`,
1716 * this function would return `/run/bus-for-%3A0`,
1717 * which could be used in a D-Bus address like
1718 * `unix:nonce-tcp:host=127.0.0.1,port=42,noncefile=/run/bus-for-%3A0`.
1720 * Returns: (transfer full): a copy of @string with all
1721 * non-optionally-escaped bytes escaped
1723 * Since: 2.36
1725 gchar *
1726 g_dbus_address_escape_value (const gchar *string)
1728 GString *s;
1729 gsize i;
1731 g_return_val_if_fail (string != NULL, NULL);
1733 /* There will often not be anything needing escaping at all. */
1734 s = g_string_sized_new (strlen (string));
1736 /* D-Bus address escaping is mostly the same as URI escaping... */
1737 g_string_append_uri_escaped (s, string, "\\/", FALSE);
1739 /* ... but '~' is an unreserved character in URIs, but a
1740 * non-optionally-escaped character in D-Bus addresses. */
1741 for (i = 0; i < s->len; i++)
1743 if (G_UNLIKELY (s->str[i] == '~'))
1745 s->str[i] = '%';
1746 g_string_insert (s, i + 1, "7E");
1747 i += 2;
1751 return g_string_free (s, FALSE);