gio-querymodules: Call setlocale in main function
[glib.git] / gio / gdbusaddress.c
blob7c294f7f15ad32e6370706ca688be0d7bc464142
1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 * Author: David Zeuthen <davidz@redhat.com>
21 #include "config.h"
23 #include <stdlib.h>
24 #include <string.h>
25 #include <stdio.h>
26 #include <errno.h>
28 #include "gioerror.h"
29 #include "gdbusutils.h"
30 #include "gdbusaddress.h"
31 #include "gdbuserror.h"
32 #include "gioenumtypes.h"
33 #include "gnetworkaddress.h"
34 #include "gsocketclient.h"
35 #include "giostream.h"
36 #include "gasyncresult.h"
37 #include "gtask.h"
38 #include "glib-private.h"
39 #include "gdbusprivate.h"
40 #include "giomodule-priv.h"
41 #include "gdbusdaemon.h"
42 #include "gstdio.h"
44 #ifdef G_OS_UNIX
45 #include <unistd.h>
46 #include <sys/stat.h>
47 #include <sys/types.h>
48 #include <gio/gunixsocketaddress.h>
49 #endif
51 #ifdef G_OS_WIN32
52 #include <windows.h>
53 #include <io.h>
54 #include <conio.h>
55 #endif
57 #include "glibintl.h"
59 /**
60 * SECTION:gdbusaddress
61 * @title: D-Bus Addresses
62 * @short_description: D-Bus connection endpoints
63 * @include: gio/gio.h
65 * Routines for working with D-Bus addresses. A D-Bus address is a string
66 * like "unix:tmpdir=/tmp/my-app-name". The exact format of addresses
67 * is explained in detail in the [D-Bus specification](http://dbus.freedesktop.org/doc/dbus-specification.html\#addresses).
70 static gchar *get_session_address_platform_specific (GError **error);
71 static gchar *get_session_address_dbus_launch (GError **error);
73 /* ---------------------------------------------------------------------------------------------------- */
75 /**
76 * g_dbus_is_address:
77 * @string: A string.
79 * Checks if @string is a D-Bus address.
81 * This doesn't check if @string is actually supported by #GDBusServer
82 * or #GDBusConnection - use g_dbus_is_supported_address() to do more
83 * checks.
85 * Returns: %TRUE if @string is a valid D-Bus address, %FALSE otherwise.
87 * Since: 2.26
89 gboolean
90 g_dbus_is_address (const gchar *string)
92 guint n;
93 gchar **a;
94 gboolean ret;
96 ret = FALSE;
98 g_return_val_if_fail (string != NULL, FALSE);
100 a = g_strsplit (string, ";", 0);
101 if (a[0] == NULL)
102 goto out;
104 for (n = 0; a[n] != NULL; n++)
106 if (!_g_dbus_address_parse_entry (a[n],
107 NULL,
108 NULL,
109 NULL))
110 goto out;
113 ret = TRUE;
115 out:
116 g_strfreev (a);
117 return ret;
120 static gboolean
121 is_valid_unix (const gchar *address_entry,
122 GHashTable *key_value_pairs,
123 GError **error)
125 gboolean ret;
126 GList *keys;
127 GList *l;
128 const gchar *path;
129 const gchar *tmpdir;
130 const gchar *abstract;
132 ret = FALSE;
133 keys = NULL;
134 path = NULL;
135 tmpdir = NULL;
136 abstract = NULL;
138 keys = g_hash_table_get_keys (key_value_pairs);
139 for (l = keys; l != NULL; l = l->next)
141 const gchar *key = l->data;
142 if (g_strcmp0 (key, "path") == 0)
143 path = g_hash_table_lookup (key_value_pairs, key);
144 else if (g_strcmp0 (key, "tmpdir") == 0)
145 tmpdir = g_hash_table_lookup (key_value_pairs, key);
146 else if (g_strcmp0 (key, "abstract") == 0)
147 abstract = g_hash_table_lookup (key_value_pairs, key);
148 else
150 g_set_error (error,
151 G_IO_ERROR,
152 G_IO_ERROR_INVALID_ARGUMENT,
153 _("Unsupported key '%s' in address entry '%s'"),
154 key,
155 address_entry);
156 goto out;
160 if (path != NULL)
162 if (tmpdir != NULL || abstract != NULL)
163 goto meaningless;
165 else if (tmpdir != NULL)
167 if (path != NULL || abstract != NULL)
168 goto meaningless;
170 else if (abstract != NULL)
172 if (path != NULL || tmpdir != NULL)
173 goto meaningless;
175 else
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, tmpdir or abstract keys)"),
181 address_entry);
182 goto out;
186 ret= TRUE;
187 goto out;
189 meaningless:
190 g_set_error (error,
191 G_IO_ERROR,
192 G_IO_ERROR_INVALID_ARGUMENT,
193 _("Meaningless key/value pair combination in address entry '%s'"),
194 address_entry);
196 out:
197 g_list_free (keys);
199 return ret;
202 static gboolean
203 is_valid_nonce_tcp (const gchar *address_entry,
204 GHashTable *key_value_pairs,
205 GError **error)
207 gboolean ret;
208 GList *keys;
209 GList *l;
210 const gchar *host;
211 const gchar *port;
212 const gchar *family;
213 const gchar *nonce_file;
214 gint port_num;
215 gchar *endp;
217 ret = FALSE;
218 keys = NULL;
219 host = NULL;
220 port = NULL;
221 family = NULL;
222 nonce_file = NULL;
224 keys = g_hash_table_get_keys (key_value_pairs);
225 for (l = keys; l != NULL; l = l->next)
227 const gchar *key = l->data;
228 if (g_strcmp0 (key, "host") == 0)
229 host = g_hash_table_lookup (key_value_pairs, key);
230 else if (g_strcmp0 (key, "port") == 0)
231 port = g_hash_table_lookup (key_value_pairs, key);
232 else if (g_strcmp0 (key, "family") == 0)
233 family = g_hash_table_lookup (key_value_pairs, key);
234 else if (g_strcmp0 (key, "noncefile") == 0)
235 nonce_file = g_hash_table_lookup (key_value_pairs, key);
236 else
238 g_set_error (error,
239 G_IO_ERROR,
240 G_IO_ERROR_INVALID_ARGUMENT,
241 _("Unsupported key '%s' in address entry '%s'"),
242 key,
243 address_entry);
244 goto out;
248 if (port != NULL)
250 port_num = strtol (port, &endp, 10);
251 if ((*port == '\0' || *endp != '\0') || port_num < 0 || port_num >= 65536)
253 g_set_error (error,
254 G_IO_ERROR,
255 G_IO_ERROR_INVALID_ARGUMENT,
256 _("Error in address '%s' - the port attribute is malformed"),
257 address_entry);
258 goto out;
262 if (family != NULL && !(g_strcmp0 (family, "ipv4") == 0 || g_strcmp0 (family, "ipv6") == 0))
264 g_set_error (error,
265 G_IO_ERROR,
266 G_IO_ERROR_INVALID_ARGUMENT,
267 _("Error in address '%s' - the family attribute is malformed"),
268 address_entry);
269 goto out;
272 if (host != NULL)
274 /* TODO: validate host */
277 nonce_file = nonce_file; /* To avoid -Wunused-but-set-variable */
279 ret= TRUE;
281 out:
282 g_list_free (keys);
284 return ret;
287 static gboolean
288 is_valid_tcp (const gchar *address_entry,
289 GHashTable *key_value_pairs,
290 GError **error)
292 gboolean ret;
293 GList *keys;
294 GList *l;
295 const gchar *host;
296 const gchar *port;
297 const gchar *family;
298 gint port_num;
299 gchar *endp;
301 ret = FALSE;
302 keys = NULL;
303 host = NULL;
304 port = NULL;
305 family = NULL;
307 keys = g_hash_table_get_keys (key_value_pairs);
308 for (l = keys; l != NULL; l = l->next)
310 const gchar *key = l->data;
311 if (g_strcmp0 (key, "host") == 0)
312 host = g_hash_table_lookup (key_value_pairs, key);
313 else if (g_strcmp0 (key, "port") == 0)
314 port = g_hash_table_lookup (key_value_pairs, key);
315 else if (g_strcmp0 (key, "family") == 0)
316 family = g_hash_table_lookup (key_value_pairs, key);
317 else
319 g_set_error (error,
320 G_IO_ERROR,
321 G_IO_ERROR_INVALID_ARGUMENT,
322 _("Unsupported key '%s' in address entry '%s'"),
323 key,
324 address_entry);
325 goto out;
329 if (port != NULL)
331 port_num = strtol (port, &endp, 10);
332 if ((*port == '\0' || *endp != '\0') || port_num < 0 || port_num >= 65536)
334 g_set_error (error,
335 G_IO_ERROR,
336 G_IO_ERROR_INVALID_ARGUMENT,
337 _("Error in address '%s' - the port attribute is malformed"),
338 address_entry);
339 goto out;
343 if (family != NULL && !(g_strcmp0 (family, "ipv4") == 0 || g_strcmp0 (family, "ipv6") == 0))
345 g_set_error (error,
346 G_IO_ERROR,
347 G_IO_ERROR_INVALID_ARGUMENT,
348 _("Error in address '%s' - the family attribute is malformed"),
349 address_entry);
350 goto out;
353 if (host != NULL)
355 /* TODO: validate host */
358 ret= TRUE;
360 out:
361 g_list_free (keys);
363 return ret;
367 * g_dbus_is_supported_address:
368 * @string: A string.
369 * @error: Return location for error or %NULL.
371 * Like g_dbus_is_address() but also checks if the library suppors the
372 * transports in @string and that key/value pairs for each transport
373 * are valid.
375 * Returns: %TRUE if @string is a valid D-Bus address that is
376 * supported by this library, %FALSE if @error is set.
378 * Since: 2.26
380 gboolean
381 g_dbus_is_supported_address (const gchar *string,
382 GError **error)
384 guint n;
385 gchar **a;
386 gboolean ret;
388 ret = FALSE;
390 g_return_val_if_fail (string != NULL, FALSE);
391 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
393 a = g_strsplit (string, ";", 0);
394 for (n = 0; a[n] != NULL; n++)
396 gchar *transport_name;
397 GHashTable *key_value_pairs;
398 gboolean supported;
400 if (!_g_dbus_address_parse_entry (a[n],
401 &transport_name,
402 &key_value_pairs,
403 error))
404 goto out;
406 supported = FALSE;
407 if (g_strcmp0 (transport_name, "unix") == 0)
408 supported = is_valid_unix (a[n], key_value_pairs, error);
409 else if (g_strcmp0 (transport_name, "tcp") == 0)
410 supported = is_valid_tcp (a[n], key_value_pairs, error);
411 else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
412 supported = is_valid_nonce_tcp (a[n], key_value_pairs, error);
413 else if (g_strcmp0 (a[n], "autolaunch:") == 0)
414 supported = TRUE;
416 g_free (transport_name);
417 g_hash_table_unref (key_value_pairs);
419 if (!supported)
420 goto out;
423 ret = TRUE;
425 out:
426 g_strfreev (a);
428 g_assert (ret || (!ret && (error == NULL || *error != NULL)));
430 return ret;
433 gboolean
434 _g_dbus_address_parse_entry (const gchar *address_entry,
435 gchar **out_transport_name,
436 GHashTable **out_key_value_pairs,
437 GError **error)
439 gboolean ret;
440 GHashTable *key_value_pairs;
441 gchar *transport_name;
442 gchar **kv_pairs;
443 const gchar *s;
444 guint n;
446 ret = FALSE;
447 kv_pairs = NULL;
448 transport_name = NULL;
449 key_value_pairs = NULL;
451 s = strchr (address_entry, ':');
452 if (s == NULL)
454 g_set_error (error,
455 G_IO_ERROR,
456 G_IO_ERROR_INVALID_ARGUMENT,
457 _("Address element '%s' does not contain a colon (:)"),
458 address_entry);
459 goto out;
462 transport_name = g_strndup (address_entry, s - address_entry);
463 key_value_pairs = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
465 kv_pairs = g_strsplit (s + 1, ",", 0);
466 for (n = 0; kv_pairs != NULL && kv_pairs[n] != NULL; n++)
468 const gchar *kv_pair = kv_pairs[n];
469 gchar *key;
470 gchar *value;
472 s = strchr (kv_pair, '=');
473 if (s == NULL)
475 g_set_error (error,
476 G_IO_ERROR,
477 G_IO_ERROR_INVALID_ARGUMENT,
478 _("Key/Value pair %d, '%s', in address element '%s' does not contain an equal sign"),
480 kv_pair,
481 address_entry);
482 goto out;
485 key = g_uri_unescape_segment (kv_pair, s, NULL);
486 value = g_uri_unescape_segment (s + 1, kv_pair + strlen (kv_pair), NULL);
487 if (key == NULL || value == NULL)
489 g_set_error (error,
490 G_IO_ERROR,
491 G_IO_ERROR_INVALID_ARGUMENT,
492 _("Error unescaping key or value in Key/Value pair %d, '%s', in address element '%s'"),
494 kv_pair,
495 address_entry);
496 g_free (key);
497 g_free (value);
498 goto out;
500 g_hash_table_insert (key_value_pairs, key, value);
503 ret = TRUE;
505 out:
506 g_strfreev (kv_pairs);
507 if (ret)
509 if (out_transport_name != NULL)
510 *out_transport_name = transport_name;
511 else
512 g_free (transport_name);
513 if (out_key_value_pairs != NULL)
514 *out_key_value_pairs = key_value_pairs;
515 else if (key_value_pairs != NULL)
516 g_hash_table_unref (key_value_pairs);
518 else
520 g_free (transport_name);
521 if (key_value_pairs != NULL)
522 g_hash_table_unref (key_value_pairs);
524 return ret;
527 /* ---------------------------------------------------------------------------------------------------- */
529 static GIOStream *
530 g_dbus_address_try_connect_one (const gchar *address_entry,
531 gchar **out_guid,
532 GCancellable *cancellable,
533 GError **error);
535 /* TODO: Declare an extension point called GDBusTransport (or similar)
536 * and move code below to extensions implementing said extension
537 * point. That way we can implement a D-Bus transport over X11 without
538 * making libgio link to libX11...
540 static GIOStream *
541 g_dbus_address_connect (const gchar *address_entry,
542 const gchar *transport_name,
543 GHashTable *key_value_pairs,
544 GCancellable *cancellable,
545 GError **error)
547 GIOStream *ret;
548 GSocketConnectable *connectable;
549 const gchar *nonce_file;
551 connectable = NULL;
552 ret = NULL;
553 nonce_file = NULL;
555 if (FALSE)
558 #ifdef G_OS_UNIX
559 else if (g_strcmp0 (transport_name, "unix") == 0)
561 const gchar *path;
562 const gchar *abstract;
563 path = g_hash_table_lookup (key_value_pairs, "path");
564 abstract = g_hash_table_lookup (key_value_pairs, "abstract");
565 if ((path == NULL && abstract == NULL) || (path != NULL && abstract != NULL))
567 g_set_error (error,
568 G_IO_ERROR,
569 G_IO_ERROR_INVALID_ARGUMENT,
570 _("Error in address '%s' - the unix transport requires exactly one of the "
571 "keys 'path' or 'abstract' to be set"),
572 address_entry);
574 else if (path != NULL)
576 connectable = G_SOCKET_CONNECTABLE (g_unix_socket_address_new (path));
578 else if (abstract != NULL)
580 connectable = G_SOCKET_CONNECTABLE (g_unix_socket_address_new_with_type (abstract,
582 G_UNIX_SOCKET_ADDRESS_ABSTRACT));
584 else
586 g_assert_not_reached ();
589 #endif
590 else if (g_strcmp0 (transport_name, "tcp") == 0 || g_strcmp0 (transport_name, "nonce-tcp") == 0)
592 const gchar *s;
593 const gchar *host;
594 glong port;
595 gchar *endp;
596 gboolean is_nonce;
598 is_nonce = (g_strcmp0 (transport_name, "nonce-tcp") == 0);
600 host = g_hash_table_lookup (key_value_pairs, "host");
601 if (host == NULL)
603 g_set_error (error,
604 G_IO_ERROR,
605 G_IO_ERROR_INVALID_ARGUMENT,
606 _("Error in address '%s' - the host attribute is missing or malformed"),
607 address_entry);
608 goto out;
611 s = g_hash_table_lookup (key_value_pairs, "port");
612 if (s == NULL)
613 s = "0";
614 port = strtol (s, &endp, 10);
615 if ((*s == '\0' || *endp != '\0') || port < 0 || port >= 65536)
617 g_set_error (error,
618 G_IO_ERROR,
619 G_IO_ERROR_INVALID_ARGUMENT,
620 _("Error in address '%s' - the port attribute is missing or malformed"),
621 address_entry);
622 goto out;
626 if (is_nonce)
628 nonce_file = g_hash_table_lookup (key_value_pairs, "noncefile");
629 if (nonce_file == NULL)
631 g_set_error (error,
632 G_IO_ERROR,
633 G_IO_ERROR_INVALID_ARGUMENT,
634 _("Error in address '%s' - the noncefile attribute is missing or malformed"),
635 address_entry);
636 goto out;
640 /* TODO: deal with family key/value-pair */
641 connectable = g_network_address_new (host, port);
643 else if (g_strcmp0 (address_entry, "autolaunch:") == 0)
645 gchar *autolaunch_address;
646 autolaunch_address = get_session_address_dbus_launch (error);
647 if (autolaunch_address != NULL)
649 ret = g_dbus_address_try_connect_one (autolaunch_address, NULL, cancellable, error);
650 g_free (autolaunch_address);
651 goto out;
653 else
655 g_prefix_error (error, _("Error auto-launching: "));
658 else
660 g_set_error (error,
661 G_IO_ERROR,
662 G_IO_ERROR_INVALID_ARGUMENT,
663 _("Unknown or unsupported transport '%s' for address '%s'"),
664 transport_name,
665 address_entry);
668 if (connectable != NULL)
670 GSocketClient *client;
671 GSocketConnection *connection;
673 g_assert (ret == NULL);
674 client = g_socket_client_new ();
675 connection = g_socket_client_connect (client,
676 connectable,
677 cancellable,
678 error);
679 g_object_unref (connectable);
680 g_object_unref (client);
681 if (connection == NULL)
682 goto out;
684 ret = G_IO_STREAM (connection);
686 if (nonce_file != NULL)
688 gchar nonce_contents[16 + 1];
689 size_t num_bytes_read;
690 FILE *f;
692 /* be careful to read only 16 bytes - we also check that the file is only 16 bytes long */
693 f = fopen (nonce_file, "rb");
694 if (f == NULL)
696 g_set_error (error,
697 G_IO_ERROR,
698 G_IO_ERROR_INVALID_ARGUMENT,
699 _("Error opening nonce file '%s': %s"),
700 nonce_file,
701 g_strerror (errno));
702 g_object_unref (ret);
703 ret = NULL;
704 goto out;
706 num_bytes_read = fread (nonce_contents,
707 sizeof (gchar),
708 16 + 1,
710 if (num_bytes_read != 16)
712 if (num_bytes_read == 0)
714 g_set_error (error,
715 G_IO_ERROR,
716 G_IO_ERROR_INVALID_ARGUMENT,
717 _("Error reading from nonce file '%s': %s"),
718 nonce_file,
719 g_strerror (errno));
721 else
723 g_set_error (error,
724 G_IO_ERROR,
725 G_IO_ERROR_INVALID_ARGUMENT,
726 _("Error reading from nonce file '%s', expected 16 bytes, got %d"),
727 nonce_file,
728 (gint) num_bytes_read);
730 g_object_unref (ret);
731 ret = NULL;
732 fclose (f);
733 goto out;
735 fclose (f);
737 if (!g_output_stream_write_all (g_io_stream_get_output_stream (ret),
738 nonce_contents,
740 NULL,
741 cancellable,
742 error))
744 g_prefix_error (error, _("Error writing contents of nonce file '%s' to stream:"), nonce_file);
745 g_object_unref (ret);
746 ret = NULL;
747 goto out;
752 out:
754 return ret;
757 static GIOStream *
758 g_dbus_address_try_connect_one (const gchar *address_entry,
759 gchar **out_guid,
760 GCancellable *cancellable,
761 GError **error)
763 GIOStream *ret;
764 GHashTable *key_value_pairs;
765 gchar *transport_name;
766 const gchar *guid;
768 ret = NULL;
769 transport_name = NULL;
770 key_value_pairs = NULL;
772 if (!_g_dbus_address_parse_entry (address_entry,
773 &transport_name,
774 &key_value_pairs,
775 error))
776 goto out;
778 ret = g_dbus_address_connect (address_entry,
779 transport_name,
780 key_value_pairs,
781 cancellable,
782 error);
783 if (ret == NULL)
784 goto out;
786 guid = g_hash_table_lookup (key_value_pairs, "guid");
787 if (guid != NULL && out_guid != NULL)
788 *out_guid = g_strdup (guid);
790 out:
791 g_free (transport_name);
792 if (key_value_pairs != NULL)
793 g_hash_table_unref (key_value_pairs);
794 return ret;
798 /* ---------------------------------------------------------------------------------------------------- */
800 typedef struct {
801 gchar *address;
802 gchar *guid;
803 } GetStreamData;
805 static void
806 get_stream_data_free (GetStreamData *data)
808 g_free (data->address);
809 g_free (data->guid);
810 g_free (data);
813 static void
814 get_stream_thread_func (GTask *task,
815 gpointer source_object,
816 gpointer task_data,
817 GCancellable *cancellable)
819 GetStreamData *data = task_data;
820 GIOStream *stream;
821 GError *error = NULL;
823 stream = g_dbus_address_get_stream_sync (data->address,
824 &data->guid,
825 cancellable,
826 &error);
827 if (stream)
828 g_task_return_pointer (task, stream, g_object_unref);
829 else
830 g_task_return_error (task, error);
834 * g_dbus_address_get_stream:
835 * @address: A valid D-Bus address.
836 * @cancellable: (allow-none): A #GCancellable or %NULL.
837 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
838 * @user_data: Data to pass to @callback.
840 * Asynchronously connects to an endpoint specified by @address and
841 * sets up the connection so it is in a state to run the client-side
842 * of the D-Bus authentication conversation.
844 * When the operation is finished, @callback will be invoked. You can
845 * then call g_dbus_address_get_stream_finish() to get the result of
846 * the operation.
848 * This is an asynchronous failable function. See
849 * g_dbus_address_get_stream_sync() for the synchronous version.
851 * Since: 2.26
853 void
854 g_dbus_address_get_stream (const gchar *address,
855 GCancellable *cancellable,
856 GAsyncReadyCallback callback,
857 gpointer user_data)
859 GTask *task;
860 GetStreamData *data;
862 g_return_if_fail (address != NULL);
864 data = g_new0 (GetStreamData, 1);
865 data->address = g_strdup (address);
867 task = g_task_new (NULL, cancellable, callback, user_data);
868 g_task_set_task_data (task, data, (GDestroyNotify) get_stream_data_free);
869 g_task_run_in_thread (task, get_stream_thread_func);
870 g_object_unref (task);
874 * g_dbus_address_get_stream_finish:
875 * @res: A #GAsyncResult obtained from the GAsyncReadyCallback passed to g_dbus_address_get_stream().
876 * @out_guid: (optional) (out): %NULL or return location to store the GUID extracted from @address, if any.
877 * @error: Return location for error or %NULL.
879 * Finishes an operation started with g_dbus_address_get_stream().
881 * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
883 * Since: 2.26
885 GIOStream *
886 g_dbus_address_get_stream_finish (GAsyncResult *res,
887 gchar **out_guid,
888 GError **error)
890 GTask *task;
891 GetStreamData *data;
892 GIOStream *ret;
894 g_return_val_if_fail (g_task_is_valid (res, NULL), NULL);
895 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
897 task = G_TASK (res);
898 ret = g_task_propagate_pointer (task, error);
900 if (ret != NULL && out_guid != NULL)
902 data = g_task_get_task_data (task);
903 *out_guid = data->guid;
904 data->guid = NULL;
907 return ret;
911 * g_dbus_address_get_stream_sync:
912 * @address: A valid D-Bus address.
913 * @out_guid: (optional) (out): %NULL or return location to store the GUID extracted from @address, if any.
914 * @cancellable: (allow-none): A #GCancellable or %NULL.
915 * @error: Return location for error or %NULL.
917 * Synchronously connects to an endpoint specified by @address and
918 * sets up the connection so it is in a state to run the client-side
919 * of the D-Bus authentication conversation.
921 * This is a synchronous failable function. See
922 * g_dbus_address_get_stream() for the asynchronous version.
924 * Returns: (transfer full): A #GIOStream or %NULL if @error is set.
926 * Since: 2.26
928 GIOStream *
929 g_dbus_address_get_stream_sync (const gchar *address,
930 gchar **out_guid,
931 GCancellable *cancellable,
932 GError **error)
934 GIOStream *ret;
935 gchar **addr_array;
936 guint n;
937 GError *last_error;
939 g_return_val_if_fail (address != NULL, NULL);
940 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
942 ret = NULL;
943 last_error = NULL;
945 addr_array = g_strsplit (address, ";", 0);
946 if (addr_array != NULL && addr_array[0] == NULL)
948 last_error = g_error_new_literal (G_IO_ERROR,
949 G_IO_ERROR_INVALID_ARGUMENT,
950 _("The given address is empty"));
951 goto out;
954 for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
956 const gchar *addr = addr_array[n];
957 GError *this_error;
959 this_error = NULL;
960 ret = g_dbus_address_try_connect_one (addr,
961 out_guid,
962 cancellable,
963 &this_error);
964 if (ret != NULL)
966 goto out;
968 else
970 g_assert (this_error != NULL);
971 if (last_error != NULL)
972 g_error_free (last_error);
973 last_error = this_error;
977 out:
978 if (ret != NULL)
980 if (last_error != NULL)
981 g_error_free (last_error);
983 else
985 g_assert (last_error != NULL);
986 g_propagate_error (error, last_error);
989 g_strfreev (addr_array);
990 return ret;
993 /* ---------------------------------------------------------------------------------------------------- */
996 * Return the address of XDG_RUNTIME_DIR/bus if it exists, belongs to
997 * us, and is a socket, and we are on Unix.
999 static gchar *
1000 get_session_address_xdg (void)
1002 #ifdef G_OS_UNIX
1003 gchar *ret = NULL;
1004 gchar *bus;
1005 gchar *tmp;
1006 GStatBuf buf;
1008 bus = g_build_filename (g_get_user_runtime_dir (), "bus", NULL);
1010 /* if ENOENT, EPERM, etc., quietly don't use it */
1011 if (g_stat (bus, &buf) < 0)
1012 goto out;
1014 /* if it isn't ours, we have incorrectly inherited someone else's
1015 * XDG_RUNTIME_DIR; silently don't use it
1017 if (buf.st_uid != geteuid ())
1018 goto out;
1020 /* if it isn't a socket, silently don't use it */
1021 if ((buf.st_mode & S_IFMT) != S_IFSOCK)
1022 goto out;
1024 tmp = g_dbus_address_escape_value (bus);
1025 ret = g_strconcat ("unix:path=", tmp, NULL);
1026 g_free (tmp);
1028 out:
1029 g_free (bus);
1030 return ret;
1031 #else
1032 return NULL;
1033 #endif
1036 /* ---------------------------------------------------------------------------------------------------- */
1038 #ifdef G_OS_UNIX
1039 static gchar *
1040 get_session_address_dbus_launch (GError **error)
1042 gchar *ret;
1043 gchar *machine_id;
1044 gchar *command_line;
1045 gchar *launch_stdout;
1046 gchar *launch_stderr;
1047 gint exit_status;
1048 gchar *old_dbus_verbose;
1049 gboolean restore_dbus_verbose;
1051 ret = NULL;
1052 machine_id = NULL;
1053 command_line = NULL;
1054 launch_stdout = NULL;
1055 launch_stderr = NULL;
1056 restore_dbus_verbose = FALSE;
1057 old_dbus_verbose = NULL;
1059 /* Don't run binaries as root if we're setuid. */
1060 if (GLIB_PRIVATE_CALL (g_check_setuid) ())
1062 g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1063 _("Cannot spawn a message bus when setuid"));
1064 goto out;
1067 machine_id = _g_dbus_get_machine_id (error);
1068 if (machine_id == NULL)
1070 g_prefix_error (error, _("Cannot spawn a message bus without a machine-id: "));
1071 goto out;
1074 /* We're using private libdbus facilities here. When everything
1075 * (X11, Mac OS X, Windows) is spec'ed out correctly (not even the
1076 * X11 property is correctly documented right now) we should
1077 * consider using the spec instead of dbus-launch.
1079 * --autolaunch=MACHINEID
1080 * This option implies that dbus-launch should scan for a previ‐
1081 * ously-started session and reuse the values found there. If no
1082 * session is found, it will start a new session. The --exit-with-
1083 * session option is implied if --autolaunch is given. This option
1084 * is for the exclusive use of libdbus, you do not want to use it
1085 * manually. It may change in the future.
1088 /* TODO: maybe provide a variable for where to look for the dbus-launch binary? */
1089 command_line = g_strdup_printf ("dbus-launch --autolaunch=%s --binary-syntax --close-stderr", machine_id);
1091 if (G_UNLIKELY (_g_dbus_debug_address ()))
1093 _g_dbus_debug_print_lock ();
1094 g_print ("GDBus-debug:Address: Running '%s' to get bus address (possibly autolaunching)\n", command_line);
1095 old_dbus_verbose = g_strdup (g_getenv ("DBUS_VERBOSE"));
1096 restore_dbus_verbose = TRUE;
1097 g_setenv ("DBUS_VERBOSE", "1", TRUE);
1098 _g_dbus_debug_print_unlock ();
1101 if (!g_spawn_command_line_sync (command_line,
1102 &launch_stdout,
1103 &launch_stderr,
1104 &exit_status,
1105 error))
1107 goto out;
1110 if (!g_spawn_check_exit_status (exit_status, error))
1112 g_prefix_error (error, _("Error spawning command line '%s': "), command_line);
1113 goto out;
1116 /* From the dbus-launch(1) man page:
1118 * --binary-syntax Write to stdout a nul-terminated bus address,
1119 * then the bus PID as a binary integer of size sizeof(pid_t),
1120 * then the bus X window ID as a binary integer of size
1121 * sizeof(long). Integers are in the machine's byte order, not
1122 * network byte order or any other canonical byte order.
1124 ret = g_strdup (launch_stdout);
1126 out:
1127 if (G_UNLIKELY (_g_dbus_debug_address ()))
1129 gchar *s;
1130 _g_dbus_debug_print_lock ();
1131 g_print ("GDBus-debug:Address: dbus-launch output:");
1132 if (launch_stdout != NULL)
1134 s = _g_dbus_hexdump (launch_stdout, strlen (launch_stdout) + 1 + sizeof (pid_t) + sizeof (long), 2);
1135 g_print ("\n%s", s);
1136 g_free (s);
1138 else
1140 g_print (" (none)\n");
1142 g_print ("GDBus-debug:Address: dbus-launch stderr output:");
1143 if (launch_stderr != NULL)
1144 g_print ("\n%s", launch_stderr);
1145 else
1146 g_print (" (none)\n");
1147 _g_dbus_debug_print_unlock ();
1150 g_free (machine_id);
1151 g_free (command_line);
1152 g_free (launch_stdout);
1153 g_free (launch_stderr);
1154 if (G_UNLIKELY (restore_dbus_verbose))
1156 if (old_dbus_verbose != NULL)
1157 g_setenv ("DBUS_VERBOSE", old_dbus_verbose, TRUE);
1158 else
1159 g_unsetenv ("DBUS_VERBOSE");
1161 g_free (old_dbus_verbose);
1162 return ret;
1165 /* end of G_OS_UNIX case */
1166 #elif defined(G_OS_WIN32)
1168 #define DBUS_DAEMON_ADDRESS_INFO "DBusDaemonAddressInfo"
1169 #define DBUS_DAEMON_MUTEX "DBusDaemonMutex"
1170 #define UNIQUE_DBUS_INIT_MUTEX "UniqueDBusInitMutex"
1171 #define DBUS_AUTOLAUNCH_MUTEX "DBusAutolaunchMutex"
1173 static void
1174 release_mutex (HANDLE mutex)
1176 ReleaseMutex (mutex);
1177 CloseHandle (mutex);
1180 static HANDLE
1181 acquire_mutex (const char *mutexname)
1183 HANDLE mutex;
1184 DWORD res;
1186 mutex = CreateMutexA (NULL, FALSE, mutexname);
1187 if (!mutex)
1188 return 0;
1190 res = WaitForSingleObject (mutex, INFINITE);
1191 switch (res)
1193 case WAIT_ABANDONED:
1194 release_mutex (mutex);
1195 return 0;
1196 case WAIT_FAILED:
1197 case WAIT_TIMEOUT:
1198 return 0;
1201 return mutex;
1204 static gboolean
1205 is_mutex_owned (const char *mutexname)
1207 HANDLE mutex;
1208 gboolean res = FALSE;
1210 mutex = CreateMutexA (NULL, FALSE, mutexname);
1211 if (WaitForSingleObject (mutex, 10) == WAIT_TIMEOUT)
1212 res = TRUE;
1213 else
1214 ReleaseMutex (mutex);
1215 CloseHandle (mutex);
1217 return res;
1220 static char *
1221 read_shm (const char *shm_name)
1223 HANDLE shared_mem;
1224 char *shared_data;
1225 char *res;
1226 int i;
1228 res = NULL;
1230 for (i = 0; i < 20; i++)
1232 shared_mem = OpenFileMappingA (FILE_MAP_READ, FALSE, shm_name);
1233 if (shared_mem != 0)
1234 break;
1235 Sleep (100);
1238 if (shared_mem != 0)
1240 shared_data = MapViewOfFile (shared_mem, FILE_MAP_READ, 0, 0, 0);
1241 if (shared_data != NULL)
1243 res = g_strdup (shared_data);
1244 UnmapViewOfFile (shared_data);
1246 CloseHandle (shared_mem);
1249 return res;
1252 static HANDLE
1253 set_shm (const char *shm_name, const char *value)
1255 HANDLE shared_mem;
1256 char *shared_data;
1258 shared_mem = CreateFileMappingA (INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE,
1259 0, strlen (value) + 1, shm_name);
1260 if (shared_mem == 0)
1261 return 0;
1263 shared_data = MapViewOfFile (shared_mem, FILE_MAP_WRITE, 0, 0, 0 );
1264 if (shared_data == NULL)
1265 return 0;
1267 strcpy (shared_data, value);
1269 UnmapViewOfFile (shared_data);
1271 return shared_mem;
1274 /* These keep state between publish_session_bus and unpublish_session_bus */
1275 static HANDLE published_daemon_mutex;
1276 static HANDLE published_shared_mem;
1278 static gboolean
1279 publish_session_bus (const char *address)
1281 HANDLE init_mutex;
1283 init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
1285 published_daemon_mutex = CreateMutexA (NULL, FALSE, DBUS_DAEMON_MUTEX);
1286 if (WaitForSingleObject (published_daemon_mutex, 10 ) != WAIT_OBJECT_0)
1288 release_mutex (init_mutex);
1289 CloseHandle (published_daemon_mutex);
1290 published_daemon_mutex = NULL;
1291 return FALSE;
1294 published_shared_mem = set_shm (DBUS_DAEMON_ADDRESS_INFO, address);
1295 if (!published_shared_mem)
1297 release_mutex (init_mutex);
1298 CloseHandle (published_daemon_mutex);
1299 published_daemon_mutex = NULL;
1300 return FALSE;
1303 release_mutex (init_mutex);
1304 return TRUE;
1307 static void
1308 unpublish_session_bus (void)
1310 HANDLE init_mutex;
1312 init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
1314 CloseHandle (published_shared_mem);
1315 published_shared_mem = NULL;
1317 release_mutex (published_daemon_mutex);
1318 published_daemon_mutex = NULL;
1320 release_mutex (init_mutex);
1323 static void
1324 wait_console_window (void)
1326 FILE *console = fopen ("CONOUT$", "w");
1328 SetConsoleTitleW (L"gdbus-daemon output. Type any character to close this window.");
1329 fprintf (console, _("(Type any character to close this window)\n"));
1330 fflush (console);
1331 _getch ();
1334 static void
1335 open_console_window (void)
1337 if (((HANDLE) _get_osfhandle (fileno (stdout)) == INVALID_HANDLE_VALUE ||
1338 (HANDLE) _get_osfhandle (fileno (stderr)) == INVALID_HANDLE_VALUE) && AllocConsole ())
1340 if ((HANDLE) _get_osfhandle (fileno (stdout)) == INVALID_HANDLE_VALUE)
1341 freopen ("CONOUT$", "w", stdout);
1343 if ((HANDLE) _get_osfhandle (fileno (stderr)) == INVALID_HANDLE_VALUE)
1344 freopen ("CONOUT$", "w", stderr);
1346 SetConsoleTitleW (L"gdbus-daemon debug output.");
1348 atexit (wait_console_window);
1351 static void
1352 idle_timeout_cb (GDBusDaemon *daemon, gpointer user_data)
1354 GMainLoop *loop = user_data;
1355 g_main_loop_quit (loop);
1358 /* Satisfies STARTF_FORCEONFEEDBACK */
1359 static void
1360 turn_off_the_starting_cursor (void)
1362 MSG msg;
1363 BOOL bRet;
1365 PostQuitMessage (0);
1367 while ((bRet = GetMessage (&msg, 0, 0, 0)) != 0)
1369 if (bRet == -1)
1370 continue;
1372 TranslateMessage (&msg);
1373 DispatchMessage (&msg);
1377 __declspec(dllexport) void CALLBACK g_win32_run_session_bus (HWND hwnd, HINSTANCE hinst, char *cmdline, int nCmdShow);
1379 __declspec(dllexport) void CALLBACK
1380 g_win32_run_session_bus (HWND hwnd, HINSTANCE hinst, char *cmdline, int nCmdShow)
1382 GDBusDaemon *daemon;
1383 GMainLoop *loop;
1384 const char *address;
1385 GError *error = NULL;
1387 turn_off_the_starting_cursor ();
1389 if (g_getenv ("GDBUS_DAEMON_DEBUG") != NULL)
1390 open_console_window ();
1392 loop = g_main_loop_new (NULL, FALSE);
1394 address = "nonce-tcp:";
1395 daemon = _g_dbus_daemon_new (address, NULL, &error);
1396 if (daemon == NULL)
1398 g_printerr ("Can't init bus: %s\n", error->message);
1399 return;
1402 g_signal_connect (daemon, "idle-timeout", G_CALLBACK (idle_timeout_cb), loop);
1404 if ( publish_session_bus (_g_dbus_daemon_get_address (daemon)))
1406 g_main_loop_run (loop);
1408 unpublish_session_bus ();
1411 g_main_loop_unref (loop);
1412 g_object_unref (daemon);
1415 static gchar *
1416 get_session_address_dbus_launch (GError **error)
1418 HANDLE autolaunch_mutex, init_mutex;
1419 char *address = NULL;
1420 wchar_t gio_path[MAX_PATH+1+200];
1422 autolaunch_mutex = acquire_mutex (DBUS_AUTOLAUNCH_MUTEX);
1424 init_mutex = acquire_mutex (UNIQUE_DBUS_INIT_MUTEX);
1426 if (is_mutex_owned (DBUS_DAEMON_MUTEX))
1427 address = read_shm (DBUS_DAEMON_ADDRESS_INFO);
1429 release_mutex (init_mutex);
1431 if (address == NULL)
1433 gio_path[MAX_PATH] = 0;
1434 if (GetModuleFileNameW (_g_io_win32_get_module (), gio_path, MAX_PATH))
1436 PROCESS_INFORMATION pi = { 0 };
1437 STARTUPINFOW si = { 0 };
1438 BOOL res;
1439 wchar_t gio_path_short[MAX_PATH];
1440 wchar_t rundll_path[MAX_PATH*2];
1441 wchar_t args[MAX_PATH*4];
1443 GetShortPathNameW (gio_path, gio_path_short, MAX_PATH);
1445 GetWindowsDirectoryW (rundll_path, MAX_PATH);
1446 wcscat (rundll_path, L"\\rundll32.exe");
1447 if (GetFileAttributesW (rundll_path) == INVALID_FILE_ATTRIBUTES)
1449 GetSystemDirectoryW (rundll_path, MAX_PATH);
1450 wcscat (rundll_path, L"\\rundll32.exe");
1453 wcscpy (args, L"\"");
1454 wcscat (args, rundll_path);
1455 wcscat (args, L"\" ");
1456 wcscat (args, gio_path_short);
1457 #if defined(_WIN64) || defined(_M_X64) || defined(_M_AMD64)
1458 wcscat (args, L",g_win32_run_session_bus");
1459 #elif defined (_MSC_VER)
1460 wcscat (args, L",_g_win32_run_session_bus@16");
1461 #else
1462 wcscat (args, L",g_win32_run_session_bus@16");
1463 #endif
1465 res = CreateProcessW (rundll_path, args,
1466 0, 0, FALSE,
1467 NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW | DETACHED_PROCESS,
1468 0, NULL /* TODO: Should be root */,
1469 &si, &pi);
1470 if (res)
1471 address = read_shm (DBUS_DAEMON_ADDRESS_INFO);
1475 release_mutex (autolaunch_mutex);
1477 if (address == NULL)
1478 g_set_error (error,
1479 G_IO_ERROR,
1480 G_IO_ERROR_FAILED,
1481 _("Session dbus not running, and autolaunch failed"));
1483 return address;
1485 #else /* neither G_OS_UNIX nor G_OS_WIN32 */
1486 static gchar *
1487 get_session_address_dbus_launch (GError **error)
1489 g_set_error (error,
1490 G_IO_ERROR,
1491 G_IO_ERROR_FAILED,
1492 _("Cannot determine session bus address (not implemented for this OS)"));
1493 return NULL;
1495 #endif /* neither G_OS_UNIX nor G_OS_WIN32 */
1497 /* ---------------------------------------------------------------------------------------------------- */
1499 static gchar *
1500 get_session_address_platform_specific (GError **error)
1502 gchar *ret;
1504 /* Use XDG_RUNTIME_DIR/bus if it exists and is suitable. This is appropriate
1505 * for systems using the "a session is a user-session" model described in
1506 * <http://lists.freedesktop.org/archives/dbus/2015-January/016522.html>,
1507 * and implemented in dbus >= 1.9.14 and sd-bus.
1509 * On systems following the more traditional "a session is a login-session"
1510 * model, this will fail and we'll fall through to X11 autolaunching
1511 * (dbus-launch) below.
1513 ret = get_session_address_xdg ();
1515 if (ret != NULL)
1516 return ret;
1518 /* TODO (#694472): try launchd on OS X, like
1519 * _dbus_lookup_session_address_launchd() does, since
1520 * 'dbus-launch --autolaunch' probably won't work there
1523 /* As a last resort, try the "autolaunch:" transport. On Unix this means
1524 * X11 autolaunching; on Windows this means a different autolaunching
1525 * mechanism based on shared memory.
1527 return get_session_address_dbus_launch (error);
1530 /* ---------------------------------------------------------------------------------------------------- */
1533 * g_dbus_address_get_for_bus_sync:
1534 * @bus_type: a #GBusType
1535 * @cancellable: (allow-none): a #GCancellable or %NULL
1536 * @error: return location for error or %NULL
1538 * Synchronously looks up the D-Bus address for the well-known message
1539 * bus instance specified by @bus_type. This may involve using various
1540 * platform specific mechanisms.
1542 * Returns: a valid D-Bus address string for @bus_type or %NULL if
1543 * @error is set
1545 * Since: 2.26
1547 gchar *
1548 g_dbus_address_get_for_bus_sync (GBusType bus_type,
1549 GCancellable *cancellable,
1550 GError **error)
1552 gchar *ret, *s = NULL;
1553 const gchar *starter_bus;
1554 GError *local_error;
1556 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1558 ret = NULL;
1559 local_error = NULL;
1561 if (G_UNLIKELY (_g_dbus_debug_address ()))
1563 guint n;
1564 _g_dbus_debug_print_lock ();
1565 s = _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type);
1566 g_print ("GDBus-debug:Address: In g_dbus_address_get_for_bus_sync() for bus type '%s'\n",
1568 g_free (s);
1569 for (n = 0; n < 3; n++)
1571 const gchar *k;
1572 const gchar *v;
1573 switch (n)
1575 case 0: k = "DBUS_SESSION_BUS_ADDRESS"; break;
1576 case 1: k = "DBUS_SYSTEM_BUS_ADDRESS"; break;
1577 case 2: k = "DBUS_STARTER_BUS_TYPE"; break;
1578 default: g_assert_not_reached ();
1580 v = g_getenv (k);
1581 g_print ("GDBus-debug:Address: env var %s", k);
1582 if (v != NULL)
1583 g_print ("='%s'\n", v);
1584 else
1585 g_print (" is not set\n");
1587 _g_dbus_debug_print_unlock ();
1590 switch (bus_type)
1592 case G_BUS_TYPE_SYSTEM:
1593 ret = g_strdup (g_getenv ("DBUS_SYSTEM_BUS_ADDRESS"));
1594 if (ret == NULL)
1596 ret = g_strdup ("unix:path=/var/run/dbus/system_bus_socket");
1598 break;
1600 case G_BUS_TYPE_SESSION:
1601 ret = g_strdup (g_getenv ("DBUS_SESSION_BUS_ADDRESS"));
1602 if (ret == NULL)
1604 ret = get_session_address_platform_specific (&local_error);
1606 break;
1608 case G_BUS_TYPE_STARTER:
1609 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
1610 if (g_strcmp0 (starter_bus, "session") == 0)
1612 ret = g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SESSION, cancellable, &local_error);
1613 goto out;
1615 else if (g_strcmp0 (starter_bus, "system") == 0)
1617 ret = g_dbus_address_get_for_bus_sync (G_BUS_TYPE_SYSTEM, cancellable, &local_error);
1618 goto out;
1620 else
1622 if (starter_bus != NULL)
1624 g_set_error (&local_error,
1625 G_IO_ERROR,
1626 G_IO_ERROR_FAILED,
1627 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
1628 " - unknown value '%s'"),
1629 starter_bus);
1631 else
1633 g_set_error_literal (&local_error,
1634 G_IO_ERROR,
1635 G_IO_ERROR_FAILED,
1636 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
1637 "variable is not set"));
1640 break;
1642 default:
1643 g_set_error (&local_error,
1644 G_IO_ERROR,
1645 G_IO_ERROR_FAILED,
1646 _("Unknown bus type %d"),
1647 bus_type);
1648 break;
1651 out:
1652 if (G_UNLIKELY (_g_dbus_debug_address ()))
1654 _g_dbus_debug_print_lock ();
1655 s = _g_dbus_enum_to_string (G_TYPE_BUS_TYPE, bus_type);
1656 if (ret != NULL)
1658 g_print ("GDBus-debug:Address: Returning address '%s' for bus type '%s'\n",
1659 ret, s);
1661 else
1663 g_print ("GDBus-debug:Address: Cannot look-up address bus type '%s': %s\n",
1664 s, local_error ? local_error->message : "");
1666 g_free (s);
1667 _g_dbus_debug_print_unlock ();
1670 if (local_error != NULL)
1671 g_propagate_error (error, local_error);
1673 return ret;
1677 * g_dbus_address_escape_value:
1678 * @string: an unescaped string to be included in a D-Bus address
1679 * as the value in a key-value pair
1681 * Escape @string so it can appear in a D-Bus address as the value
1682 * part of a key-value pair.
1684 * For instance, if @string is "/run/bus-for-:0",
1685 * this function would return "/run/bus-for-%3A0",
1686 * which could be used in a D-Bus address like
1687 * "unix:nonce-tcp:host=127.0.0.1,port=42,noncefile=/run/bus-for-%3A0".
1689 * Returns: (transfer full): a copy of @string with all
1690 * non-optionally-escaped bytes escaped
1692 * Since: 2.36
1694 gchar *
1695 g_dbus_address_escape_value (const gchar *string)
1697 GString *s;
1698 gsize i;
1700 g_return_val_if_fail (string != NULL, NULL);
1702 /* There will often not be anything needing escaping at all. */
1703 s = g_string_sized_new (strlen (string));
1705 /* D-Bus address escaping is mostly the same as URI escaping... */
1706 g_string_append_uri_escaped (s, string, "\\/", FALSE);
1708 /* ... but '~' is an unreserved character in URIs, but a
1709 * non-optionally-escaped character in D-Bus addresses. */
1710 for (i = 0; i < s->len; i++)
1712 if (G_UNLIKELY (s->str[i] == '~'))
1714 s->str[i] = '%';
1715 g_string_insert (s, i + 1, "7E");
1716 i += 2;
1720 return g_string_free (s, FALSE);