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