kdbus: Fixup signal subscription
[platform/upstream/glib.git] / gio / gdbusaddress.c
1 /* GDBus - GLib D-Bus Library
2  *
3  * Copyright (C) 2008-2010 Red Hat, Inc.
4  *
5  * SPDX-License-Identifier: LGPL-2.1-or-later
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General
18  * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
19  *
20  * Author: David Zeuthen <davidz@redhat.com>
21  */
22
23 #include "config.h"
24
25 #include <stdlib.h>
26 #include <string.h>
27 #include <stdio.h>
28 #include <errno.h>
29
30 #include "gioerror.h"
31 #include "gdbusutils.h"
32 #include "gdbusaddress.h"
33 #include "gdbuserror.h"
34 #include "gioenumtypes.h"
35 #include "glib-private.h"
36 #include "gnetworkaddress.h"
37 #include "gsocketclient.h"
38 #include "giostream.h"
39 #include "gasyncresult.h"
40 #include "gtask.h"
41 #include "glib-private.h"
42 #include "gdbusprivate.h"
43 #include "gstdio.h"
44
45 #ifdef G_OS_UNIX
46 #include "gkdbus.h"
47 #endif
48 #ifdef HAVE_UNISTD_H
49 #include <unistd.h>
50 #endif
51 #include <sys/stat.h>
52 #include <sys/types.h>
53 #include <gio/gunixsocketaddress.h>
54
55 #ifdef G_OS_WIN32
56 #include <windows.h>
57 #endif
58
59 #ifdef G_OS_WIN32
60 #define FO_CLOEXEC ""
61 #else
62 #define FO_CLOEXEC "e"
63 #endif
64
65 #include "glibintl.h"
66
67 /**
68  * GDBusAddress:
69  *
70  * Routines for working with D-Bus addresses. A D-Bus address is a string
71  * like `unix:tmpdir=/tmp/my-app-name`. The exact format of addresses
72  * is explained in detail in the
73  * [D-Bus specification](http://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
74  *
75  * TCP D-Bus connections are supported, but accessing them via a proxy is
76  * currently not supported.
77  *
78  * Since GLib 2.72, `unix:` addresses are supported on Windows with `AF_UNIX`
79  * support (Windows 10).
80  */
81
82 static gchar *get_session_address_platform_specific (GError **error);
83 static gchar *get_session_address_dbus_launch       (GError **error);
84
85 /* ---------------------------------------------------------------------------------------------------- */
86
87 /**
88  * g_dbus_is_address:
89  * @string: A string.
90  *
91  * Checks if @string is a
92  * [D-Bus address](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
93  *
94  * This doesn't check if @string is actually supported by #GDBusServer
95  * or #GDBusConnection - use g_dbus_is_supported_address() to do more
96  * checks.
97  *
98  * Returns: %TRUE if @string is a valid D-Bus address, %FALSE otherwise.
99  *
100  * Since: 2.26
101  */
102 gboolean
103 g_dbus_is_address (const gchar *string)
104 {
105   guint n;
106   gchar **a;
107   gboolean ret;
108
109   ret = FALSE;
110
111   g_return_val_if_fail (string != NULL, FALSE);
112
113   a = g_strsplit (string, ";", 0);
114   if (a[0] == NULL)
115     goto out;
116
117   for (n = 0; a[n] != NULL; n++)
118     {
119       if (!_g_dbus_address_parse_entry (a[n],
120                                         NULL,
121                                         NULL,
122                                         NULL))
123         goto out;
124     }
125
126   ret = TRUE;
127
128  out:
129   g_strfreev (a);
130   return ret;
131 }
132
133 static gboolean
134 is_valid_unix (const gchar  *address_entry,
135                GHashTable   *key_value_pairs,
136                GError      **error)
137 {
138   gboolean ret;
139   GPtrArray *keys;
140   const gchar *path;
141   const gchar *dir;
142   const gchar *tmpdir;
143   const gchar *abstract;
144
145   ret = FALSE;
146   path = NULL;
147   dir = NULL;
148   tmpdir = NULL;
149   abstract = NULL;
150
151   keys = g_hash_table_get_keys_as_ptr_array (key_value_pairs);
152   for (guint i = 0; i < keys->len; ++i)
153     {
154       const gchar *key = g_ptr_array_index (keys, i);
155       if (g_strcmp0 (key, "path") == 0)
156         path = g_hash_table_lookup (key_value_pairs, key);
157       else if (g_strcmp0 (key, "dir") == 0)
158         dir = g_hash_table_lookup (key_value_pairs, key);
159       else if (g_strcmp0 (key, "tmpdir") == 0)
160         tmpdir = g_hash_table_lookup (key_value_pairs, key);
161       else if (g_strcmp0 (key, "abstract") == 0)
162         abstract = g_hash_table_lookup (key_value_pairs, key);
163       else if (g_strcmp0 (key, "guid") != 0)
164         {
165           g_set_error (error,
166                        G_IO_ERROR,
167                        G_IO_ERROR_INVALID_ARGUMENT,
168                        _("Unsupported key “%s” in address entry “%s”"),
169                        key,
170                        address_entry);
171           goto out;
172         }
173     }
174
175   /* Exactly one key must be set */
176   if ((path != NULL) + (dir != NULL) + (tmpdir != NULL) + (abstract != NULL) > 1)
177     {
178       g_set_error (error,
179              G_IO_ERROR,
180              G_IO_ERROR_INVALID_ARGUMENT,
181              _("Meaningless key/value pair combination in address entry “%s”"),
182              address_entry);
183       goto out;
184     }
185   else if (path == NULL && dir == NULL && tmpdir == NULL && abstract == NULL)
186     {
187       g_set_error (error,
188                    G_IO_ERROR,
189                    G_IO_ERROR_INVALID_ARGUMENT,
190                    _("Address “%s” is invalid (need exactly one of path, dir, tmpdir, or abstract keys)"),
191                    address_entry);
192       goto out;
193     }
194
195   ret = TRUE;
196
197  out:
198   g_ptr_array_unref (keys);
199
200   return ret;
201 }
202
203 static gboolean
204 is_valid_nonce_tcp (const gchar  *address_entry,
205                     GHashTable   *key_value_pairs,
206                     GError      **error)
207 {
208   gboolean ret;
209   GPtrArray *keys;
210   const gchar *host;
211   const gchar *port;
212   const gchar *family;
213   const gchar *nonce_file;
214   gint port_num;
215   gchar *endp;
216
217   ret = FALSE;
218   host = NULL;
219   port = NULL;
220   family = NULL;
221   nonce_file = NULL;
222
223   keys = g_hash_table_get_keys_as_ptr_array (key_value_pairs);
224   for (guint i = 0; i < keys->len; ++i)
225     {
226       const gchar *key = g_ptr_array_index (keys, i);
227       if (g_strcmp0 (key, "host") == 0)
228         host = g_hash_table_lookup (key_value_pairs, key);
229       else if (g_strcmp0 (key, "port") == 0)
230         port = g_hash_table_lookup (key_value_pairs, key);
231       else if (g_strcmp0 (key, "family") == 0)
232         family = g_hash_table_lookup (key_value_pairs, key);
233       else if (g_strcmp0 (key, "noncefile") == 0)
234         nonce_file = g_hash_table_lookup (key_value_pairs, key);
235       else if (g_strcmp0 (key, "guid") != 0)
236         {
237           g_set_error (error,
238                        G_IO_ERROR,
239                        G_IO_ERROR_INVALID_ARGUMENT,
240                        _("Unsupported key “%s” in address entry “%s”"),
241                        key,
242                        address_entry);
243           goto out;
244         }
245     }
246
247   if (port != NULL)
248     {
249       port_num = strtol (port, &endp, 10);
250       if ((*port == '\0' || *endp != '\0') || port_num < 0 || port_num >= 65536)
251         {
252           g_set_error (error,
253                        G_IO_ERROR,
254                        G_IO_ERROR_INVALID_ARGUMENT,
255                        _("Error in address “%s” — the “%s” attribute is malformed"),
256                        address_entry, "port");
257           goto out;
258         }
259     }
260
261   if (family != NULL && !(g_strcmp0 (family, "ipv4") == 0 || g_strcmp0 (family, "ipv6") == 0))
262     {
263       g_set_error (error,
264                    G_IO_ERROR,
265                    G_IO_ERROR_INVALID_ARGUMENT,
266                    _("Error in address “%s” — the “%s” attribute is malformed"),
267                    address_entry, "family");
268       goto out;
269     }
270
271   if (host != NULL)
272     {
273       /* TODO: validate host */
274     }
275
276   if (nonce_file != NULL && *nonce_file == '\0')
277     {
278       g_set_error (error,
279                    G_IO_ERROR,
280                    G_IO_ERROR_INVALID_ARGUMENT,
281                    _("Error in address “%s” — the “%s” attribute is malformed"),
282                    address_entry, "noncefile");
283       goto out;
284     }
285
286   ret = TRUE;
287
288  out:
289   g_ptr_array_unref (keys);
290
291   return ret;
292 }
293
294 static gboolean
295 is_valid_tcp (const gchar  *address_entry,
296               GHashTable   *key_value_pairs,
297               GError      **error)
298 {
299   gboolean ret;
300   GPtrArray *keys;
301   const gchar *host;
302   const gchar *port;
303   const gchar *family;
304   gint port_num;
305   gchar *endp;
306
307   ret = FALSE;
308   host = NULL;
309   port = NULL;
310   family = NULL;
311
312   keys = g_hash_table_get_keys_as_ptr_array (key_value_pairs);
313   for (guint i = 0; i < keys->len; ++i)
314     {
315       const gchar *key = g_ptr_array_index (keys, i);
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 if (g_strcmp0 (key, "guid") != 0)
323         {
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;
331         }
332     }
333
334   if (port != NULL)
335     {
336       port_num = strtol (port, &endp, 10);
337       if ((*port == '\0' || *endp != '\0') || port_num < 0 || port_num >= 65536)
338         {
339           g_set_error (error,
340                        G_IO_ERROR,
341                        G_IO_ERROR_INVALID_ARGUMENT,
342                        _("Error in address “%s” — the “%s” attribute is malformed"),
343                        address_entry, "port");
344           goto out;
345         }
346     }
347
348   if (family != NULL && !(g_strcmp0 (family, "ipv4") == 0 || g_strcmp0 (family, "ipv6") == 0))
349     {
350       g_set_error (error,
351                    G_IO_ERROR,
352                    G_IO_ERROR_INVALID_ARGUMENT,
353                    _("Error in address “%s” — the “%s” attribute is malformed"),
354                    address_entry, "family");
355       goto out;
356     }
357
358   if (host != NULL)
359     {
360       /* TODO: validate host */
361     }
362
363   ret= TRUE;
364
365  out:
366   g_ptr_array_unref (keys);
367
368   return ret;
369 }
370
371 /**
372  * g_dbus_is_supported_address:
373  * @string: A string.
374  * @error: Return location for error or %NULL.
375  *
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).
380  *
381  * Returns: %TRUE if @string is a valid D-Bus address that is
382  * supported by this library, %FALSE if @error is set.
383  *
384  * Since: 2.26
385  */
386 gboolean
387 g_dbus_is_supported_address (const gchar  *string,
388                              GError      **error)
389 {
390   guint n;
391   gchar **a;
392   gboolean ret;
393
394   ret = FALSE;
395
396   g_return_val_if_fail (string != NULL, FALSE);
397   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
398
399   a = g_strsplit (string, ";", 0);
400   for (n = 0; a[n] != NULL; n++)
401     {
402       gchar *transport_name;
403       GHashTable *key_value_pairs;
404       gboolean supported;
405
406       if (!_g_dbus_address_parse_entry (a[n],
407                                         &transport_name,
408                                         &key_value_pairs,
409                                         error))
410         goto out;
411
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;
421       else
422         g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
423                      _("Unknown or unsupported transport “%s” for address “%s”"),
424                      transport_name, a[n]);
425
426       g_free (transport_name);
427       g_hash_table_unref (key_value_pairs);
428
429       if (!supported)
430         goto out;
431     }
432
433   ret = TRUE;
434
435  out:
436   g_strfreev (a);
437
438   g_assert (ret || (!ret && (error == NULL || *error != NULL)));
439
440   return ret;
441 }
442
443 gboolean
444 _g_dbus_address_parse_entry (const gchar  *address_entry,
445                              gchar       **out_transport_name,
446                              GHashTable  **out_key_value_pairs,
447                              GError      **error)
448 {
449   gboolean ret;
450   GHashTable *key_value_pairs;
451   gchar *transport_name;
452   gchar **kv_pairs;
453   const gchar *s;
454   guint n;
455
456   ret = FALSE;
457   kv_pairs = NULL;
458   transport_name = NULL;
459   key_value_pairs = NULL;
460
461   s = strchr (address_entry, ':');
462   if (s == NULL)
463     {
464       g_set_error (error,
465                    G_IO_ERROR,
466                    G_IO_ERROR_INVALID_ARGUMENT,
467                    _("Address element “%s” does not contain a colon (:)"),
468                    address_entry);
469       goto out;
470     }
471   else if (s == address_entry)
472     {
473       g_set_error (error,
474                    G_IO_ERROR,
475                    G_IO_ERROR_INVALID_ARGUMENT,
476                    _("Transport name in address element “%s” must not be empty"),
477                    address_entry);
478       goto out;
479     }
480
481   transport_name = g_strndup (address_entry, s - address_entry);
482   key_value_pairs = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
483
484   kv_pairs = g_strsplit (s + 1, ",", 0);
485   for (n = 0; kv_pairs[n] != NULL; n++)
486     {
487       const gchar *kv_pair = kv_pairs[n];
488       gchar *key;
489       gchar *value;
490
491       s = strchr (kv_pair, '=');
492       if (s == NULL)
493         {
494           g_set_error (error,
495                        G_IO_ERROR,
496                        G_IO_ERROR_INVALID_ARGUMENT,
497                        _("Key/Value pair %d, “%s”, in address element “%s” does not contain an equal sign"),
498                        n,
499                        kv_pair,
500                        address_entry);
501           goto out;
502         }
503       else if (s == kv_pair)
504         {
505           g_set_error (error,
506                        G_IO_ERROR,
507                        G_IO_ERROR_INVALID_ARGUMENT,
508                        _("Key/Value pair %d, “%s”, in address element “%s” must not have an empty key"),
509                        n,
510                        kv_pair,
511                        address_entry);
512           goto out;
513         }
514
515       key = g_uri_unescape_segment (kv_pair, s, NULL);
516       value = g_uri_unescape_segment (s + 1, kv_pair + strlen (kv_pair), NULL);
517       if (key == NULL || value == NULL)
518         {
519           g_set_error (error,
520                        G_IO_ERROR,
521                        G_IO_ERROR_INVALID_ARGUMENT,
522                        _("Error unescaping key or value in Key/Value pair %d, “%s”, in address element “%s”"),
523                        n,
524                        kv_pair,
525                        address_entry);
526           g_free (key);
527           g_free (value);
528           goto out;
529         }
530       g_hash_table_insert (key_value_pairs, key, value);
531     }
532
533   ret = TRUE;
534
535 out:
536   if (ret)
537     {
538       if (out_transport_name != NULL)
539         *out_transport_name = g_steal_pointer (&transport_name);
540       if (out_key_value_pairs != NULL)
541         *out_key_value_pairs = g_steal_pointer (&key_value_pairs);
542     }
543
544   g_clear_pointer (&key_value_pairs, g_hash_table_unref);
545   g_free (transport_name);
546   g_strfreev (kv_pairs);
547
548   return ret;
549 }
550
551 /* ---------------------------------------------------------------------------------------------------- */
552
553 static GObject *
554 g_dbus_address_try_connect_one (const gchar   *address_entry,
555                                 gboolean       kdbus_okay,
556                                 gchar        **out_guid,
557                                 GCancellable  *cancellable,
558                                 GError       **error);
559
560 /* TODO: Declare an extension point called GDBusTransport (or similar)
561  * and move code below to extensions implementing said extension
562  * point. That way we can implement a D-Bus transport over X11 without
563  * making libgio link to libX11...
564  */
565 static GObject *
566 g_dbus_address_connect (const gchar   *address_entry,
567                         const gchar   *transport_name,
568                         gboolean       kdbus_okay,
569                         GHashTable    *key_value_pairs,
570                         GCancellable  *cancellable,
571                         GError       **error)
572 {
573   GObject *ret;
574   GSocketConnectable *connectable;
575   const gchar *nonce_file;
576
577   connectable = NULL;
578   ret = NULL;
579   nonce_file = NULL;
580
581   if (FALSE)
582     {
583     }
584 #if defined (G_OS_UNIX) && defined (KDBUS)
585   else if (kdbus_okay && g_str_equal (transport_name, "kernel"))
586     {
587       GKDBusWorker *worker;
588       const gchar *path;
589
590       path = g_hash_table_lookup (key_value_pairs, "path");
591
592       if (path == NULL)
593         {
594           g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT,
595                        _("Error in address '%s' - the kernel transport requires a path"),
596                        address_entry);
597         }
598       else
599         {
600           worker = _g_kdbus_worker_new (path, error);
601
602           if (worker == NULL)
603             return NULL;
604
605           return G_OBJECT (worker);
606         }
607     }
608 #endif
609   else if (g_strcmp0 (transport_name, "unix") == 0)
610     {
611       const gchar *path;
612       const gchar *abstract;
613       path = g_hash_table_lookup (key_value_pairs, "path");
614       abstract = g_hash_table_lookup (key_value_pairs, "abstract");
615       if ((path == NULL && abstract == NULL) || (path != NULL && abstract != NULL))
616         {
617           g_set_error (error,
618                        G_IO_ERROR,
619                        G_IO_ERROR_INVALID_ARGUMENT,
620                        _("Error in address “%s” — the unix transport requires exactly one of the "
621                          "keys “path” or “abstract” to be set"),
622                        address_entry);
623         }
624       else if (path != NULL)
625         {
626           connectable = G_SOCKET_CONNECTABLE (g_unix_socket_address_new (path));
627         }
628       else if (abstract != NULL)
629         {
630           connectable = G_SOCKET_CONNECTABLE (g_unix_socket_address_new_with_type (abstract,
631                                                                                    -1,
632                                                                                    G_UNIX_SOCKET_ADDRESS_ABSTRACT));
633         }
634       else
635         {
636           g_assert_not_reached ();
637         }
638     }
639   else if (g_strcmp0 (transport_name, "tcp") == 0 || g_strcmp0 (transport_name, "nonce-tcp") == 0)
640     {
641       const gchar *s;
642       const gchar *host;
643       glong port;
644       gchar *endp;
645       gboolean is_nonce;
646
647       is_nonce = (g_strcmp0 (transport_name, "nonce-tcp") == 0);
648
649       host = g_hash_table_lookup (key_value_pairs, "host");
650       if (host == NULL)
651         {
652           g_set_error (error,
653                        G_IO_ERROR,
654                        G_IO_ERROR_INVALID_ARGUMENT,
655                        _("Error in address “%s” — the host attribute is missing or malformed"),
656                        address_entry);
657           goto out;
658         }
659
660       s = g_hash_table_lookup (key_value_pairs, "port");
661       if (s == NULL)
662         s = "0";
663       port = strtol (s, &endp, 10);
664       if ((*s == '\0' || *endp != '\0') || port < 0 || port >= 65536)
665         {
666           g_set_error (error,
667                        G_IO_ERROR,
668                        G_IO_ERROR_INVALID_ARGUMENT,
669                        _("Error in address “%s” — the port attribute is missing or malformed"),
670                        address_entry);
671           goto out;
672         }
673
674
675       if (is_nonce)
676         {
677           nonce_file = g_hash_table_lookup (key_value_pairs, "noncefile");
678           if (nonce_file == NULL)
679             {
680               g_set_error (error,
681                            G_IO_ERROR,
682                            G_IO_ERROR_INVALID_ARGUMENT,
683                            _("Error in address “%s” — the noncefile attribute is missing or malformed"),
684                            address_entry);
685               goto out;
686             }
687         }
688
689       /* TODO: deal with family key/value-pair */
690       connectable = g_network_address_new (host, port);
691     }
692   else if (g_strcmp0 (address_entry, "autolaunch:") == 0)
693     {
694       gchar *autolaunch_address;
695       autolaunch_address = get_session_address_dbus_launch (error);
696       if (autolaunch_address != NULL)
697         {
698           ret = g_dbus_address_try_connect_one (autolaunch_address, kdbus_okay, NULL, cancellable, error);
699           g_free (autolaunch_address);
700           goto out;
701         }
702       else
703         {
704           g_prefix_error (error, _("Error auto-launching: "));
705         }
706     }
707   else
708     {
709       g_set_error (error,
710                    G_IO_ERROR,
711                    G_IO_ERROR_INVALID_ARGUMENT,
712                    _("Unknown or unsupported transport “%s” for address “%s”"),
713                    transport_name,
714                    address_entry);
715     }
716
717   if (connectable != NULL)
718     {
719       GSocketClient *client;
720       GSocketConnection *connection;
721
722       g_assert (ret == NULL);
723       client = g_socket_client_new ();
724
725       /* Disable proxy support to prevent a deadlock on startup, since loading a
726        * proxy resolver causes the GIO modules to be loaded, and there will
727        * almost certainly be one of them which then tries to use GDBus.
728        * See: https://bugzilla.gnome.org/show_bug.cgi?id=792499 */
729       g_socket_client_set_enable_proxy (client, FALSE);
730
731       connection = g_socket_client_connect (client,
732                                             connectable,
733                                             cancellable,
734                                             error);
735       g_object_unref (connectable);
736       g_object_unref (client);
737       if (connection == NULL)
738         goto out;
739
740       ret = G_OBJECT (connection);
741
742       if (nonce_file != NULL)
743         {
744           gchar nonce_contents[16 + 1];
745           size_t num_bytes_read;
746           FILE *f;
747           int errsv;
748
749           /* be careful to read only 16 bytes - we also check that the file is only 16 bytes long */
750           f = fopen (nonce_file, "rb" FO_CLOEXEC);
751           errsv = errno;
752           if (f == NULL)
753             {
754               g_set_error (error,
755                            G_IO_ERROR,
756                            G_IO_ERROR_INVALID_ARGUMENT,
757                            _("Error opening nonce file “%s”: %s"),
758                            nonce_file,
759                            g_strerror (errsv));
760               g_object_unref (ret);
761               ret = NULL;
762               goto out;
763             }
764           num_bytes_read = fread (nonce_contents,
765                                   sizeof (gchar),
766                                   16 + 1,
767                                   f);
768           errsv = errno;
769           if (num_bytes_read != 16)
770             {
771               if (num_bytes_read == 0)
772                 {
773                   g_set_error (error,
774                                G_IO_ERROR,
775                                G_IO_ERROR_INVALID_ARGUMENT,
776                                _("Error reading from nonce file “%s”: %s"),
777                                nonce_file,
778                                g_strerror (errsv));
779                 }
780               else
781                 {
782                   g_set_error (error,
783                                G_IO_ERROR,
784                                G_IO_ERROR_INVALID_ARGUMENT,
785                                _("Error reading from nonce file “%s”, expected 16 bytes, got %d"),
786                                nonce_file,
787                                (gint) num_bytes_read);
788                 }
789               g_object_unref (ret);
790               ret = NULL;
791               fclose (f);
792               goto out;
793             }
794           fclose (f);
795
796           if (!g_output_stream_write_all (g_io_stream_get_output_stream (G_IO_STREAM (connection)),
797                                           nonce_contents,
798                                           16,
799                                           NULL,
800                                           cancellable,
801                                           error))
802             {
803               g_prefix_error (error, _("Error writing contents of nonce file “%s” to stream:"), nonce_file);
804               g_object_unref (ret);
805               ret = NULL;
806               goto out;
807             }
808         }
809     }
810
811  out:
812
813   return ret;
814 }
815
816 static GObject *
817 g_dbus_address_try_connect_one (const gchar   *address_entry,
818                                 gboolean       kdbus_okay,
819                                 gchar        **out_guid,
820                                 GCancellable  *cancellable,
821                                 GError       **error)
822 {
823   GObject *ret;
824   GHashTable *key_value_pairs;
825   gchar *transport_name;
826   const gchar *guid;
827
828   ret = NULL;
829   transport_name = NULL;
830   key_value_pairs = NULL;
831
832   if (!_g_dbus_address_parse_entry (address_entry,
833                                     &transport_name,
834                                     &key_value_pairs,
835                                     error))
836     goto out;
837
838   ret = g_dbus_address_connect (address_entry,
839                                 transport_name,
840                                 kdbus_okay,
841                                 key_value_pairs,
842                                 cancellable,
843                                 error);
844   if (ret == NULL)
845     goto out;
846
847   guid = g_hash_table_lookup (key_value_pairs, "guid");
848   if (guid != NULL && out_guid != NULL)
849     *out_guid = g_strdup (guid);
850
851 out:
852   g_free (transport_name);
853   if (key_value_pairs != NULL)
854     g_hash_table_unref (key_value_pairs);
855   return ret;
856 }
857
858
859 /* ---------------------------------------------------------------------------------------------------- */
860
861 typedef struct {
862   gchar *address;
863   gchar *guid;
864 } GetStreamData;
865
866 static void
867 get_stream_data_free (GetStreamData *data)
868 {
869   g_free (data->address);
870   g_free (data->guid);
871   g_free (data);
872 }
873
874 static void
875 get_stream_thread_func (GTask         *task,
876                         gpointer       source_object,
877                         gpointer       task_data,
878                         GCancellable  *cancellable)
879 {
880   GetStreamData *data = task_data;
881   GIOStream *stream;
882   GError *error = NULL;
883
884   stream = g_dbus_address_get_stream_sync (data->address,
885                                            &data->guid,
886                                            cancellable,
887                                            &error);
888   if (stream)
889     g_task_return_pointer (task, stream, g_object_unref);
890   else
891     g_task_return_error (task, error);
892 }
893
894 /**
895  * g_dbus_address_get_stream:
896  * @address: A valid D-Bus address.
897  * @cancellable: (nullable): A #GCancellable or %NULL.
898  * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
899  * @user_data: Data to pass to @callback.
900  *
901  * Asynchronously connects to an endpoint specified by @address and
902  * sets up the connection so it is in a state to run the client-side
903  * of the D-Bus authentication conversation. @address must be in the
904  * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
905  *
906  * When the operation is finished, @callback will be invoked. You can
907  * then call g_dbus_address_get_stream_finish() to get the result of
908  * the operation.
909  *
910  * This is an asynchronous failable function. See
911  * g_dbus_address_get_stream_sync() for the synchronous version.
912  *
913  * Since: 2.26
914  */
915 void
916 g_dbus_address_get_stream (const gchar         *address,
917                            GCancellable        *cancellable,
918                            GAsyncReadyCallback  callback,
919                            gpointer             user_data)
920 {
921   GTask *task;
922   GetStreamData *data;
923
924   g_return_if_fail (address != NULL);
925
926   data = g_new0 (GetStreamData, 1);
927   data->address = g_strdup (address);
928
929   task = g_task_new (NULL, cancellable, callback, user_data);
930   g_task_set_source_tag (task, g_dbus_address_get_stream);
931   g_task_set_task_data (task, data, (GDestroyNotify) get_stream_data_free);
932   g_task_run_in_thread (task, get_stream_thread_func);
933   g_object_unref (task);
934 }
935
936 /**
937  * g_dbus_address_get_stream_finish:
938  * @res: A #GAsyncResult obtained from the GAsyncReadyCallback passed to g_dbus_address_get_stream().
939  * @out_guid: (optional) (out) (nullable): %NULL or return location to store the GUID extracted from @address, if any.
940  * @error: Return location for error or %NULL.
941  *
942  * Finishes an operation started with g_dbus_address_get_stream().
943  *
944  * A server is not required to set a GUID, so @out_guid may be set to %NULL
945  * even on success.
946  *
947  * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
948  *
949  * Since: 2.26
950  */
951 GIOStream *
952 g_dbus_address_get_stream_finish (GAsyncResult        *res,
953                                   gchar              **out_guid,
954                                   GError             **error)
955 {
956   GTask *task;
957   GetStreamData *data;
958   GIOStream *ret;
959
960   g_return_val_if_fail (g_task_is_valid (res, NULL), NULL);
961   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
962
963   task = G_TASK (res);
964   ret = g_task_propagate_pointer (task, error);
965
966   if (ret != NULL && out_guid != NULL)
967     {
968       data = g_task_get_task_data (task);
969       *out_guid = data->guid;
970       data->guid = NULL;
971     }
972
973   return ret;
974 }
975
976 /**
977  * g_dbus_address_get_stream_sync:
978  * @address: A valid D-Bus address.
979  * @out_guid: (optional) (out) (nullable): %NULL or return location to store the GUID extracted from @address, if any.
980  * @cancellable: (nullable): A #GCancellable or %NULL.
981  * @error: Return location for error or %NULL.
982  *
983  * Synchronously connects to an endpoint specified by @address and
984  * sets up the connection so it is in a state to run the client-side
985  * of the D-Bus authentication conversation. @address must be in the
986  * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
987  *
988  * A server is not required to set a GUID, so @out_guid may be set to %NULL
989  * even on success.
990  *
991  * This is a synchronous failable function. See
992  * g_dbus_address_get_stream() for the asynchronous version.
993  *
994  * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
995  *
996  * Since: 2.26
997  */
998 GIOStream *
999 g_dbus_address_get_stream_sync (const gchar   *address,
1000                                 gchar        **out_guid,
1001                                 GCancellable  *cancellable,
1002                                 GError       **error)
1003 {
1004   GObject *result;
1005
1006   result = g_dbus_address_get_stream_internal (address, FALSE, out_guid, cancellable, error);
1007   g_assert (result == NULL || G_IS_IO_STREAM (result));
1008
1009   if (result)
1010     return G_IO_STREAM (result);
1011
1012   return NULL;
1013 }
1014
1015 GObject *
1016 g_dbus_address_get_stream_internal (const gchar   *address,
1017                                     gboolean       kdbus_okay,
1018                                     gchar        **out_guid,
1019                                     GCancellable  *cancellable,
1020                                     GError       **error)
1021 {
1022   GObject *ret;
1023   gchar **addr_array;
1024   guint n;
1025   GError *last_error;
1026
1027   g_return_val_if_fail (address != NULL, NULL);
1028   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1029
1030   ret = NULL;
1031   last_error = NULL;
1032
1033   addr_array = g_strsplit (address, ";", 0);
1034   if (addr_array[0] == NULL)
1035     {
1036       last_error = g_error_new_literal (G_IO_ERROR,
1037                                         G_IO_ERROR_INVALID_ARGUMENT,
1038                                         _("The given address is empty"));
1039       goto out;
1040     }
1041
1042   for (n = 0; addr_array[n] != NULL; n++)
1043     {
1044       const gchar *addr = addr_array[n];
1045       GError *this_error;
1046
1047       this_error = NULL;
1048       ret = g_dbus_address_try_connect_one (addr,
1049                                             kdbus_okay,
1050                                             out_guid,
1051                                             cancellable,
1052                                             &this_error);
1053       if (ret != NULL)
1054         {
1055           goto out;
1056         }
1057       else
1058         {
1059           g_assert (this_error != NULL);
1060           if (last_error != NULL)
1061             g_error_free (last_error);
1062           last_error = this_error;
1063         }
1064     }
1065
1066  out:
1067   if (ret != NULL)
1068     {
1069       if (last_error != NULL)
1070         g_error_free (last_error);
1071     }
1072   else
1073     {
1074       g_assert (last_error != NULL);
1075       g_propagate_error (error, last_error);
1076     }
1077
1078   g_strfreev (addr_array);
1079   return ret;
1080 }
1081
1082 /* ---------------------------------------------------------------------------------------------------- */
1083
1084 /*
1085  * Return the address of XDG_RUNTIME_DIR/bus if it exists, belongs to
1086  * us, and is a socket, and we are on Unix.
1087  */
1088 static gchar *
1089 get_session_address_xdg (void)
1090 {
1091 #ifdef G_OS_UNIX
1092   gchar *ret = NULL;
1093   gchar *bus;
1094   gchar *tmp;
1095   GStatBuf buf;
1096
1097   bus = g_build_filename (g_get_user_runtime_dir (), "bus", NULL);
1098
1099   /* if ENOENT, EPERM, etc., quietly don't use it */
1100   if (g_stat (bus, &buf) < 0)
1101     goto out;
1102
1103   /* if it isn't ours, we have incorrectly inherited someone else's
1104    * XDG_RUNTIME_DIR; silently don't use it
1105    */
1106   if (buf.st_uid != geteuid ())
1107     goto out;
1108
1109   /* if it isn't a socket, silently don't use it */
1110   if ((buf.st_mode & S_IFMT) != S_IFSOCK)
1111     goto out;
1112
1113   tmp = g_dbus_address_escape_value (bus);
1114   ret = g_strconcat ("unix:path=", tmp, NULL);
1115   g_free (tmp);
1116
1117 out:
1118   g_free (bus);
1119   return ret;
1120 #else
1121   return NULL;
1122 #endif
1123 }
1124
1125 static gchar *
1126 get_session_address_kdbus (void)
1127 {
1128 #ifdef G_OS_UNIX
1129   gchar *ret = NULL;
1130   gchar *bus;
1131   GStatBuf buf;
1132
1133   bus = g_strdup_printf ("/sys/fs/kdbus/%d-user/bus", getuid());
1134
1135   /* if ENOENT, EPERM, etc., quietly don't use it */
1136   if (g_stat (bus, &buf) < 0)
1137     goto out;
1138
1139   ret = g_strconcat ("kernel:path=", bus, NULL);
1140
1141 out:
1142   g_free (bus);
1143   return ret;
1144 #else
1145   return NULL;
1146 #endif
1147 }
1148
1149 /* ---------------------------------------------------------------------------------------------------- */
1150
1151 #ifdef G_OS_UNIX
1152 static gchar *
1153 get_session_address_dbus_launch (GError **error)
1154 {
1155   gchar *ret;
1156   gchar *machine_id;
1157   gchar *command_line;
1158   gchar *launch_stdout;
1159   gchar *launch_stderr;
1160   gint wait_status;
1161   gchar *old_dbus_verbose;
1162   gboolean restore_dbus_verbose;
1163
1164   ret = NULL;
1165   machine_id = NULL;
1166   command_line = NULL;
1167   launch_stdout = NULL;
1168   launch_stderr = NULL;
1169   restore_dbus_verbose = FALSE;
1170   old_dbus_verbose = NULL;
1171
1172   /* Don't run binaries as root if we're setuid. */
1173   if (GLIB_PRIVATE_CALL (g_check_setuid) ())
1174     {
1175       g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1176                    _("Cannot spawn a message bus when AT_SECURE is set"));
1177       goto out;
1178     }
1179
1180   machine_id = _g_dbus_get_machine_id (error);
1181   if (machine_id == NULL)
1182     {
1183       g_prefix_error (error, _("Cannot spawn a message bus without a machine-id: "));
1184       goto out;
1185     }
1186
1187   if (g_getenv ("DISPLAY") == NULL)
1188     {
1189       g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1190                    _("Cannot autolaunch D-Bus without X11 $DISPLAY"));
1191       goto out;
1192     }
1193
1194   /* We're using private libdbus facilities here. When everything
1195    * (X11, Mac OS X, Windows) is spec'ed out correctly (not even the
1196    * X11 property is correctly documented right now) we should
1197    * consider using the spec instead of dbus-launch.
1198    *
1199    *   --autolaunch=MACHINEID
1200    *          This option implies that dbus-launch should scan  for  a  previ‐
1201    *          ously-started  session  and  reuse the values found there. If no
1202    *          session is found, it will start a new session. The  --exit-with-
1203    *          session option is implied if --autolaunch is given.  This option
1204    *          is for the exclusive use of libdbus, you do not want to  use  it
1205    *          manually. It may change in the future.
1206    */
1207
1208   /* TODO: maybe provide a variable for where to look for the dbus-launch binary? */
1209   command_line = g_strdup_printf ("dbus-launch --autolaunch=%s --binary-syntax --close-stderr", machine_id);
1210
1211   if (G_UNLIKELY (_g_dbus_debug_address ()))
1212     {
1213       _g_dbus_debug_print_lock ();
1214       g_print ("GDBus-debug:Address: Running '%s' to get bus address (possibly autolaunching)\n", command_line);
1215       old_dbus_verbose = g_strdup (g_getenv ("DBUS_VERBOSE"));
1216       restore_dbus_verbose = TRUE;
1217       g_setenv ("DBUS_VERBOSE", "1", TRUE);
1218       _g_dbus_debug_print_unlock ();
1219     }
1220
1221   if (!g_spawn_command_line_sync (command_line,
1222                                   &launch_stdout,
1223                                   &launch_stderr,
1224                                   &wait_status,
1225                                   error))
1226     {
1227       goto out;
1228     }
1229
1230   if (!g_spawn_check_wait_status (wait_status, error))
1231     {
1232       g_prefix_error (error, _("Error spawning command line “%s”: "), command_line);
1233       goto out;
1234     }
1235
1236   /* From the dbus-launch(1) man page:
1237    *
1238    *   --binary-syntax Write to stdout a nul-terminated bus address,
1239    *   then the bus PID as a binary integer of size sizeof(pid_t),
1240    *   then the bus X window ID as a binary integer of size
1241    *   sizeof(long).  Integers are in the machine's byte order, not
1242    *   network byte order or any other canonical byte order.
1243    */
1244   ret = g_strdup (launch_stdout);
1245
1246  out:
1247   if (G_UNLIKELY (_g_dbus_debug_address ()))
1248     {
1249       gchar *s;
1250       _g_dbus_debug_print_lock ();
1251       g_print ("GDBus-debug:Address: dbus-launch output:");
1252       if (launch_stdout != NULL)
1253         {
1254           s = _g_dbus_hexdump (launch_stdout, strlen (launch_stdout) + 1 + sizeof (pid_t) + sizeof (long), 2);
1255           g_print ("\n%s", s);
1256           g_free (s);
1257         }
1258       else
1259         {
1260           g_print (" (none)\n");
1261         }
1262       g_print ("GDBus-debug:Address: dbus-launch stderr output:");
1263       if (launch_stderr != NULL)
1264         g_print ("\n%s", launch_stderr);
1265       else
1266         g_print (" (none)\n");
1267       _g_dbus_debug_print_unlock ();
1268     }
1269
1270   g_free (machine_id);
1271   g_free (command_line);
1272   g_free (launch_stdout);
1273   g_free (launch_stderr);
1274   if (G_UNLIKELY (restore_dbus_verbose))
1275     {
1276       if (old_dbus_verbose != NULL)
1277         g_setenv ("DBUS_VERBOSE", old_dbus_verbose, TRUE);
1278       else
1279         g_unsetenv ("DBUS_VERBOSE");
1280     }
1281   g_free (old_dbus_verbose);
1282   return ret;
1283 }
1284
1285 /* end of G_OS_UNIX case */
1286 #elif defined(G_OS_WIN32)
1287
1288 static gchar *
1289 get_session_address_dbus_launch (GError **error)
1290 {
1291   return _g_dbus_win32_get_session_address_dbus_launch (error);
1292 }
1293
1294 #else /* neither G_OS_UNIX nor G_OS_WIN32 */
1295 static gchar *
1296 get_session_address_dbus_launch (GError **error)
1297 {
1298   g_set_error (error,
1299                G_IO_ERROR,
1300                G_IO_ERROR_FAILED,
1301                _("Cannot determine session bus address (not implemented for this OS)"));
1302   return NULL;
1303 }
1304 #endif /* neither G_OS_UNIX nor G_OS_WIN32 */
1305
1306 /* ---------------------------------------------------------------------------------------------------- */
1307
1308 static gchar *
1309 get_session_address_platform_specific (GError **error)
1310 {
1311   gchar *ret;
1312
1313   /* Use XDG_RUNTIME_DIR/bus if it exists and is suitable. This is appropriate
1314    * for systems using the "a session is a user-session" model described in
1315    * <http://lists.freedesktop.org/archives/dbus/2015-January/016522.html>,
1316    * and implemented in dbus >= 1.9.14 and sd-bus.
1317    *
1318    * On systems following the more traditional "a session is a login-session"
1319    * model, this will fail and we'll fall through to X11 autolaunching
1320    * (dbus-launch) below.
1321    */
1322   ret = get_session_address_xdg ();
1323
1324   if (ret != NULL)
1325     return ret;
1326
1327   /* TODO (#694472): try launchd on OS X, like
1328    * _dbus_lookup_session_address_launchd() does, since
1329    * 'dbus-launch --autolaunch' probably won't work there
1330    */
1331
1332   /* As a last resort, try the "autolaunch:" transport. On Unix this means
1333    * X11 autolaunching; on Windows this means a different autolaunching
1334    * mechanism based on shared memory.
1335    */
1336   return get_session_address_dbus_launch (error);
1337 }
1338
1339 /* ---------------------------------------------------------------------------------------------------- */
1340
1341 /**
1342  * g_dbus_address_get_for_bus_sync:
1343  * @bus_type: a #GBusType
1344  * @cancellable: (nullable): a #GCancellable or %NULL
1345  * @error: return location for error or %NULL
1346  *
1347  * Synchronously looks up the D-Bus address for the well-known message
1348  * bus instance specified by @bus_type. This may involve using various
1349  * platform specific mechanisms.
1350  *
1351  * The returned address will be in the
1352  * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
1353  *
1354  * Returns: (transfer full): a valid D-Bus address string for @bus_type or
1355  *     %NULL if @error is set
1356  *
1357  * Since: 2.26
1358  */
1359 gchar *
1360 g_dbus_address_get_for_bus_sync (GBusType       bus_type,
1361                                  GCancellable  *cancellable,
1362                                  GError       **error)
1363 {
1364   gboolean has_elevated_privileges = GLIB_PRIVATE_CALL (g_check_setuid) ();
1365   gchar *ret, *s = NULL;
1366   const gchar *starter_bus;
1367   GError *local_error;
1368
1369   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1370
1371   ret = NULL;
1372   local_error = NULL;
1373
1374   if (G_UNLIKELY (_g_dbus_debug_address ()))
1375     {
1376       guint n;
1377       gchar *s;
1378       _g_dbus_debug_print_lock ();
1379       s = _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type);
1380       g_print ("GDBus-debug:Address: In g_dbus_address_get_for_bus_sync() for bus type '%s'\n",
1381                s);
1382       g_free (s);
1383       for (n = 0; n < 3; n++)
1384         {
1385           const gchar *k;
1386           const gchar *v;
1387           switch (n)
1388             {
1389             case 0: k = "DBUS_SESSION_BUS_ADDRESS"; break;
1390             case 1: k = "DBUS_SYSTEM_BUS_ADDRESS"; break;
1391             case 2: k = "DBUS_STARTER_BUS_TYPE"; break;
1392             default: g_assert_not_reached ();
1393             }
1394           v = g_getenv (k);
1395           g_print ("GDBus-debug:Address: env var %s", k);
1396           if (v != NULL)
1397             g_print ("='%s'\n", v);
1398           else
1399             g_print (" is not set\n");
1400         }
1401       _g_dbus_debug_print_unlock ();
1402     }
1403
1404   /* Don’t load the addresses from the environment if running as setuid, as they
1405    * come from an unprivileged caller. */
1406   switch (bus_type)
1407     {
1408     case G_BUS_TYPE_SYSTEM:
1409       if (has_elevated_privileges)
1410         ret = NULL;
1411       else
1412         ret = g_strdup (g_getenv ("DBUS_SYSTEM_BUS_ADDRESS"));
1413
1414       if (ret == NULL)
1415         {
1416           /* While the D-Bus specification says this must be `/var/run/dbus/system_bus_socket`,
1417            * a footnote allows it to use localstatedir:
1418            * https://dbus.freedesktop.org/doc/dbus-specification.html#ftn.id-1.13.6.4.3.3
1419            * or, on systems where /run is the same as /var/run, runstatedir:
1420            * https://gitlab.freedesktop.org/dbus/dbus/-/merge_requests/209 */
1421           ret = g_strdup ("kernel:path=/sys/fs/kdbus/0-system/bus;unix:path=" GLIB_RUNSTATEDIR "/dbus/system_bus_socket");
1422         }
1423       break;
1424
1425     case G_BUS_TYPE_SESSION:
1426       if (has_elevated_privileges)
1427         ret = NULL;
1428       else
1429         ret = g_strdup (g_getenv ("DBUS_SESSION_BUS_ADDRESS"));
1430
1431       if (ret == NULL)
1432         {
1433           ret = get_session_address_kdbus ();
1434           if (ret == NULL)
1435             ret = get_session_address_platform_specific (&local_error);
1436           if (ret == NULL)
1437             goto out;
1438         }
1439       break;
1440
1441     case G_BUS_TYPE_STARTER:
1442       starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
1443       if (g_strcmp0 (starter_bus, "session") == 0)
1444         {
1445           ret = g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SESSION, cancellable, &local_error);
1446           goto out;
1447         }
1448       else if (g_strcmp0 (starter_bus, "system") == 0)
1449         {
1450           ret = g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SYSTEM, cancellable, &local_error);
1451           goto out;
1452         }
1453       else
1454         {
1455           if (starter_bus != NULL)
1456             {
1457               g_set_error (&local_error,
1458                            G_IO_ERROR,
1459                            G_IO_ERROR_FAILED,
1460                            _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
1461                              " — unknown value “%s”"),
1462                            starter_bus);
1463             }
1464           else
1465             {
1466               g_set_error_literal (&local_error,
1467                                    G_IO_ERROR,
1468                                    G_IO_ERROR_FAILED,
1469                                    _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
1470                                      "variable is not set"));
1471             }
1472         }
1473       break;
1474
1475     default:
1476       g_set_error (&local_error,
1477                    G_IO_ERROR,
1478                    G_IO_ERROR_FAILED,
1479                    _("Unknown bus type %d"),
1480                    bus_type);
1481       break;
1482     }
1483
1484  out:
1485   if (G_UNLIKELY (_g_dbus_debug_address ()))
1486     {
1487       _g_dbus_debug_print_lock ();
1488       s = _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type);
1489       if (ret != NULL)
1490         {
1491           g_print ("GDBus-debug:Address: Returning address '%s' for bus type '%s'\n",
1492                    ret, s);
1493         }
1494       else
1495         {
1496           g_print ("GDBus-debug:Address: Cannot look-up address bus type '%s': %s\n",
1497                    s, local_error ? local_error->message : "");
1498         }
1499       g_free (s);
1500       _g_dbus_debug_print_unlock ();
1501     }
1502
1503   if (local_error != NULL)
1504     g_propagate_error (error, local_error);
1505
1506   return ret;
1507 }
1508
1509 /**
1510  * g_dbus_address_escape_value:
1511  * @string: an unescaped string to be included in a D-Bus address
1512  *     as the value in a key-value pair
1513  *
1514  * Escape @string so it can appear in a D-Bus address as the value
1515  * part of a key-value pair.
1516  *
1517  * For instance, if @string is `/run/bus-for-:0`,
1518  * this function would return `/run/bus-for-%3A0`,
1519  * which could be used in a D-Bus address like
1520  * `unix:nonce-tcp:host=127.0.0.1,port=42,noncefile=/run/bus-for-%3A0`.
1521  *
1522  * Returns: (transfer full): a copy of @string with all
1523  *     non-optionally-escaped bytes escaped
1524  *
1525  * Since: 2.36
1526  */
1527 gchar *
1528 g_dbus_address_escape_value (const gchar *string)
1529 {
1530   GString *s;
1531   gsize i;
1532
1533   g_return_val_if_fail (string != NULL, NULL);
1534
1535   /* There will often not be anything needing escaping at all. */
1536   s = g_string_sized_new (strlen (string));
1537
1538   /* D-Bus address escaping is mostly the same as URI escaping... */
1539   g_string_append_uri_escaped (s, string, "\\/", FALSE);
1540
1541   /* ... but '~' is an unreserved character in URIs, but a
1542    * non-optionally-escaped character in D-Bus addresses. */
1543   for (i = 0; i < s->len; i++)
1544     {
1545       if (G_UNLIKELY (s->str[i] == '~'))
1546         {
1547           s->str[i] = '%';
1548           g_string_insert (s, i + 1, "7E");
1549           i += 2;
1550         }
1551     }
1552
1553   return g_string_free (s, FALSE);
1554 }