Do not expand autoptr macros when running introspection
[glib.git] / gio / gdbusserver.c
blob07757f40f37b0ac46d74dff666be2ebeeacc8ce6
1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 * Author: David Zeuthen <davidz@redhat.com>
21 #include "config.h"
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
27 #include "giotypes.h"
28 #include "gioerror.h"
29 #include "gdbusaddress.h"
30 #include "gdbusutils.h"
31 #include "gdbusconnection.h"
32 #include "gdbusserver.h"
33 #include "gioenumtypes.h"
34 #include "gdbusprivate.h"
35 #include "gdbusauthobserver.h"
36 #include "ginitable.h"
37 #include "gsocketservice.h"
38 #include "gthreadedsocketservice.h"
39 #include "gresolver.h"
40 #include "glib/gstdio.h"
41 #include "ginetaddress.h"
42 #include "ginetsocketaddress.h"
43 #include "ginputstream.h"
44 #include "giostream.h"
46 #ifdef G_OS_UNIX
47 #include <unistd.h>
48 #endif
49 #ifdef G_OS_WIN32
50 #include <io.h>
51 #endif
53 #ifdef G_OS_UNIX
54 #include "gunixsocketaddress.h"
55 #endif
57 #include "glibintl.h"
59 /**
60 * SECTION:gdbusserver
61 * @short_description: Helper for accepting connections
62 * @include: gio/gio.h
64 * #GDBusServer is a helper for listening to and accepting D-Bus
65 * connections. This can be used to create a new D-Bus server, allowing two
66 * peers to use the D-Bus protocol for their own specialized communication.
67 * A server instance provided in this way will not perform message routing or
68 * implement the org.freedesktop.DBus interface.
70 * To just export an object on a well-known name on a message bus, such as the
71 * session or system bus, you should instead use g_bus_own_name().
73 * An example of peer-to-peer communication with G-DBus can be found
74 * in [gdbus-example-peer.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-peer.c).
77 /**
78 * GDBusServer:
80 * The #GDBusServer structure contains only private data and
81 * should only be accessed using the provided API.
83 * Since: 2.26
85 struct _GDBusServer
87 /*< private >*/
88 GObject parent_instance;
90 GDBusServerFlags flags;
91 gchar *address;
92 gchar *guid;
94 guchar *nonce;
95 gchar *nonce_file;
97 gchar *client_address;
99 GSocketListener *listener;
100 gboolean is_using_listener;
101 gulong run_signal_handler_id;
103 /* The result of g_main_context_ref_thread_default() when the object
104 * was created (the GObject _init() function) - this is used for delivery
105 * of the :new-connection GObject signal.
107 GMainContext *main_context_at_construction;
109 gboolean active;
111 GDBusAuthObserver *authentication_observer;
114 typedef struct _GDBusServerClass GDBusServerClass;
117 * GDBusServerClass:
118 * @new_connection: Signal class handler for the #GDBusServer::new-connection signal.
120 * Class structure for #GDBusServer.
122 * Since: 2.26
124 struct _GDBusServerClass
126 /*< private >*/
127 GObjectClass parent_class;
129 /*< public >*/
130 /* Signals */
131 gboolean (*new_connection) (GDBusServer *server,
132 GDBusConnection *connection);
135 enum
137 PROP_0,
138 PROP_ADDRESS,
139 PROP_CLIENT_ADDRESS,
140 PROP_FLAGS,
141 PROP_GUID,
142 PROP_ACTIVE,
143 PROP_AUTHENTICATION_OBSERVER,
146 enum
148 NEW_CONNECTION_SIGNAL,
149 LAST_SIGNAL,
152 static guint _signals[LAST_SIGNAL] = {0};
154 static void initable_iface_init (GInitableIface *initable_iface);
156 G_DEFINE_TYPE_WITH_CODE (GDBusServer, g_dbus_server, G_TYPE_OBJECT,
157 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init))
159 static void
160 g_dbus_server_finalize (GObject *object)
162 GDBusServer *server = G_DBUS_SERVER (object);
164 if (server->authentication_observer != NULL)
165 g_object_unref (server->authentication_observer);
167 if (server->run_signal_handler_id > 0)
168 g_signal_handler_disconnect (server->listener, server->run_signal_handler_id);
170 if (server->listener != NULL)
171 g_object_unref (server->listener);
173 g_free (server->address);
174 g_free (server->guid);
175 g_free (server->client_address);
176 if (server->nonce != NULL)
178 memset (server->nonce, '\0', 16);
179 g_free (server->nonce);
181 /* we could unlink the nonce file but I don't
182 * think it's really worth the effort/risk
184 g_free (server->nonce_file);
186 g_main_context_unref (server->main_context_at_construction);
188 G_OBJECT_CLASS (g_dbus_server_parent_class)->finalize (object);
191 static void
192 g_dbus_server_get_property (GObject *object,
193 guint prop_id,
194 GValue *value,
195 GParamSpec *pspec)
197 GDBusServer *server = G_DBUS_SERVER (object);
199 switch (prop_id)
201 case PROP_FLAGS:
202 g_value_set_flags (value, server->flags);
203 break;
205 case PROP_GUID:
206 g_value_set_string (value, server->guid);
207 break;
209 case PROP_ADDRESS:
210 g_value_set_string (value, server->address);
211 break;
213 case PROP_CLIENT_ADDRESS:
214 g_value_set_string (value, server->client_address);
215 break;
217 case PROP_ACTIVE:
218 g_value_set_boolean (value, server->active);
219 break;
221 case PROP_AUTHENTICATION_OBSERVER:
222 g_value_set_object (value, server->authentication_observer);
223 break;
225 default:
226 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
227 break;
231 static void
232 g_dbus_server_set_property (GObject *object,
233 guint prop_id,
234 const GValue *value,
235 GParamSpec *pspec)
237 GDBusServer *server = G_DBUS_SERVER (object);
239 switch (prop_id)
241 case PROP_FLAGS:
242 server->flags = g_value_get_flags (value);
243 break;
245 case PROP_GUID:
246 server->guid = g_value_dup_string (value);
247 break;
249 case PROP_ADDRESS:
250 server->address = g_value_dup_string (value);
251 break;
253 case PROP_AUTHENTICATION_OBSERVER:
254 server->authentication_observer = g_value_dup_object (value);
255 break;
257 default:
258 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
259 break;
263 static void
264 g_dbus_server_class_init (GDBusServerClass *klass)
266 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
268 gobject_class->finalize = g_dbus_server_finalize;
269 gobject_class->set_property = g_dbus_server_set_property;
270 gobject_class->get_property = g_dbus_server_get_property;
273 * GDBusServer:flags:
275 * Flags from the #GDBusServerFlags enumeration.
277 * Since: 2.26
279 g_object_class_install_property (gobject_class,
280 PROP_FLAGS,
281 g_param_spec_flags ("flags",
282 P_("Flags"),
283 P_("Flags for the server"),
284 G_TYPE_DBUS_SERVER_FLAGS,
285 G_DBUS_SERVER_FLAGS_NONE,
286 G_PARAM_READABLE |
287 G_PARAM_WRITABLE |
288 G_PARAM_CONSTRUCT_ONLY |
289 G_PARAM_STATIC_NAME |
290 G_PARAM_STATIC_BLURB |
291 G_PARAM_STATIC_NICK));
294 * GDBusServer:guid:
296 * The guid of the server.
298 * Since: 2.26
300 g_object_class_install_property (gobject_class,
301 PROP_GUID,
302 g_param_spec_string ("guid",
303 P_("GUID"),
304 P_("The guid of the server"),
305 NULL,
306 G_PARAM_READABLE |
307 G_PARAM_WRITABLE |
308 G_PARAM_CONSTRUCT_ONLY |
309 G_PARAM_STATIC_NAME |
310 G_PARAM_STATIC_BLURB |
311 G_PARAM_STATIC_NICK));
314 * GDBusServer:address:
316 * The D-Bus address to listen on.
318 * Since: 2.26
320 g_object_class_install_property (gobject_class,
321 PROP_ADDRESS,
322 g_param_spec_string ("address",
323 P_("Address"),
324 P_("The address to listen on"),
325 NULL,
326 G_PARAM_READABLE |
327 G_PARAM_WRITABLE |
328 G_PARAM_CONSTRUCT_ONLY |
329 G_PARAM_STATIC_NAME |
330 G_PARAM_STATIC_BLURB |
331 G_PARAM_STATIC_NICK));
334 * GDBusServer:client-address:
336 * The D-Bus address that clients can use.
338 * Since: 2.26
340 g_object_class_install_property (gobject_class,
341 PROP_CLIENT_ADDRESS,
342 g_param_spec_string ("client-address",
343 P_("Client Address"),
344 P_("The address clients can use"),
345 NULL,
346 G_PARAM_READABLE |
347 G_PARAM_STATIC_NAME |
348 G_PARAM_STATIC_BLURB |
349 G_PARAM_STATIC_NICK));
352 * GDBusServer:active:
354 * Whether the server is currently active.
356 * Since: 2.26
358 g_object_class_install_property (gobject_class,
359 PROP_ACTIVE,
360 g_param_spec_boolean ("active",
361 P_("Active"),
362 P_("Whether the server is currently active"),
363 FALSE,
364 G_PARAM_READABLE |
365 G_PARAM_STATIC_NAME |
366 G_PARAM_STATIC_BLURB |
367 G_PARAM_STATIC_NICK));
370 * GDBusServer:authentication-observer:
372 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
374 * Since: 2.26
376 g_object_class_install_property (gobject_class,
377 PROP_AUTHENTICATION_OBSERVER,
378 g_param_spec_object ("authentication-observer",
379 P_("Authentication Observer"),
380 P_("Object used to assist in the authentication process"),
381 G_TYPE_DBUS_AUTH_OBSERVER,
382 G_PARAM_READABLE |
383 G_PARAM_WRITABLE |
384 G_PARAM_CONSTRUCT_ONLY |
385 G_PARAM_STATIC_NAME |
386 G_PARAM_STATIC_BLURB |
387 G_PARAM_STATIC_NICK));
390 * GDBusServer::new-connection:
391 * @server: The #GDBusServer emitting the signal.
392 * @connection: A #GDBusConnection for the new connection.
394 * Emitted when a new authenticated connection has been made. Use
395 * g_dbus_connection_get_peer_credentials() to figure out what
396 * identity (if any), was authenticated.
398 * If you want to accept the connection, take a reference to the
399 * @connection object and return %TRUE. When you are done with the
400 * connection call g_dbus_connection_close() and give up your
401 * reference. Note that the other peer may disconnect at any time -
402 * a typical thing to do when accepting a connection is to listen to
403 * the #GDBusConnection::closed signal.
405 * If #GDBusServer:flags contains %G_DBUS_SERVER_FLAGS_RUN_IN_THREAD
406 * then the signal is emitted in a new thread dedicated to the
407 * connection. Otherwise the signal is emitted in the
408 * [thread-default main context][g-main-context-push-thread-default]
409 * of the thread that @server was constructed in.
411 * You are guaranteed that signal handlers for this signal runs
412 * before incoming messages on @connection are processed. This means
413 * that it's suitable to call g_dbus_connection_register_object() or
414 * similar from the signal handler.
416 * Returns: %TRUE to claim @connection, %FALSE to let other handlers
417 * run.
419 * Since: 2.26
421 _signals[NEW_CONNECTION_SIGNAL] = g_signal_new (I_("new-connection"),
422 G_TYPE_DBUS_SERVER,
423 G_SIGNAL_RUN_LAST,
424 G_STRUCT_OFFSET (GDBusServerClass, new_connection),
425 g_signal_accumulator_true_handled,
426 NULL, /* accu_data */
427 NULL,
428 G_TYPE_BOOLEAN,
430 G_TYPE_DBUS_CONNECTION);
433 static void
434 g_dbus_server_init (GDBusServer *server)
436 server->main_context_at_construction = g_main_context_ref_thread_default ();
439 static gboolean
440 on_run (GSocketService *service,
441 GSocketConnection *socket_connection,
442 GObject *source_object,
443 gpointer user_data);
446 * g_dbus_server_new_sync:
447 * @address: A D-Bus address.
448 * @flags: Flags from the #GDBusServerFlags enumeration.
449 * @guid: A D-Bus GUID.
450 * @observer: (nullable): A #GDBusAuthObserver or %NULL.
451 * @cancellable: (nullable): A #GCancellable or %NULL.
452 * @error: Return location for server or %NULL.
454 * Creates a new D-Bus server that listens on the first address in
455 * @address that works.
457 * Once constructed, you can use g_dbus_server_get_client_address() to
458 * get a D-Bus address string that clients can use to connect.
460 * Connect to the #GDBusServer::new-connection signal to handle
461 * incoming connections.
463 * The returned #GDBusServer isn't active - you have to start it with
464 * g_dbus_server_start().
466 * #GDBusServer is used in this [example][gdbus-peer-to-peer].
468 * This is a synchronous failable constructor. See
469 * g_dbus_server_new() for the asynchronous version.
471 * Returns: A #GDBusServer or %NULL if @error is set. Free with
472 * g_object_unref().
474 * Since: 2.26
476 GDBusServer *
477 g_dbus_server_new_sync (const gchar *address,
478 GDBusServerFlags flags,
479 const gchar *guid,
480 GDBusAuthObserver *observer,
481 GCancellable *cancellable,
482 GError **error)
484 GDBusServer *server;
486 g_return_val_if_fail (address != NULL, NULL);
487 g_return_val_if_fail (g_dbus_is_guid (guid), NULL);
488 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
490 server = g_initable_new (G_TYPE_DBUS_SERVER,
491 cancellable,
492 error,
493 "address", address,
494 "flags", flags,
495 "guid", guid,
496 "authentication-observer", observer,
497 NULL);
499 return server;
503 * g_dbus_server_get_client_address:
504 * @server: A #GDBusServer.
506 * Gets a
507 * [D-Bus address](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses)
508 * string that can be used by clients to connect to @server.
510 * Returns: A D-Bus address string. Do not free, the string is owned
511 * by @server.
513 * Since: 2.26
515 const gchar *
516 g_dbus_server_get_client_address (GDBusServer *server)
518 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
519 return server->client_address;
523 * g_dbus_server_get_guid:
524 * @server: A #GDBusServer.
526 * Gets the GUID for @server.
528 * Returns: A D-Bus GUID. Do not free this string, it is owned by @server.
530 * Since: 2.26
532 const gchar *
533 g_dbus_server_get_guid (GDBusServer *server)
535 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
536 return server->guid;
540 * g_dbus_server_get_flags:
541 * @server: A #GDBusServer.
543 * Gets the flags for @server.
545 * Returns: A set of flags from the #GDBusServerFlags enumeration.
547 * Since: 2.26
549 GDBusServerFlags
550 g_dbus_server_get_flags (GDBusServer *server)
552 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
553 return server->flags;
557 * g_dbus_server_is_active:
558 * @server: A #GDBusServer.
560 * Gets whether @server is active.
562 * Returns: %TRUE if server is active, %FALSE otherwise.
564 * Since: 2.26
566 gboolean
567 g_dbus_server_is_active (GDBusServer *server)
569 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
570 return server->active;
574 * g_dbus_server_start:
575 * @server: A #GDBusServer.
577 * Starts @server.
579 * Since: 2.26
581 void
582 g_dbus_server_start (GDBusServer *server)
584 g_return_if_fail (G_IS_DBUS_SERVER (server));
585 if (server->active)
586 return;
587 /* Right now we don't have any transport not using the listener... */
588 g_assert (server->is_using_listener);
589 g_socket_service_start (G_SOCKET_SERVICE (server->listener));
590 server->active = TRUE;
591 g_object_notify (G_OBJECT (server), "active");
595 * g_dbus_server_stop:
596 * @server: A #GDBusServer.
598 * Stops @server.
600 * Since: 2.26
602 void
603 g_dbus_server_stop (GDBusServer *server)
605 g_return_if_fail (G_IS_DBUS_SERVER (server));
606 if (!server->active)
607 return;
608 /* Right now we don't have any transport not using the listener... */
609 g_assert (server->is_using_listener);
610 g_assert (server->run_signal_handler_id > 0);
611 g_signal_handler_disconnect (server->listener, server->run_signal_handler_id);
612 server->run_signal_handler_id = 0;
613 g_socket_service_stop (G_SOCKET_SERVICE (server->listener));
614 server->active = FALSE;
615 g_object_notify (G_OBJECT (server), "active");
618 /* ---------------------------------------------------------------------------------------------------- */
620 #ifdef G_OS_UNIX
622 static gint
623 random_ascii (void)
625 gint ret;
626 ret = g_random_int_range (0, 60);
627 if (ret < 25)
628 ret += 'A';
629 else if (ret < 50)
630 ret += 'a' - 25;
631 else
632 ret += '0' - 50;
633 return ret;
636 /* note that address_entry has already been validated => exactly one of path, tmpdir or abstract keys are set */
637 static gboolean
638 try_unix (GDBusServer *server,
639 const gchar *address_entry,
640 GHashTable *key_value_pairs,
641 GError **error)
643 gboolean ret;
644 const gchar *path;
645 const gchar *tmpdir;
646 const gchar *abstract;
647 GSocketAddress *address;
649 ret = FALSE;
650 address = NULL;
652 path = g_hash_table_lookup (key_value_pairs, "path");
653 tmpdir = g_hash_table_lookup (key_value_pairs, "tmpdir");
654 abstract = g_hash_table_lookup (key_value_pairs, "abstract");
656 if (path != NULL)
658 address = g_unix_socket_address_new (path);
660 else if (tmpdir != NULL)
662 gint n;
663 GString *s;
664 GError *local_error;
666 retry:
667 s = g_string_new (tmpdir);
668 g_string_append (s, "/dbus-");
669 for (n = 0; n < 8; n++)
670 g_string_append_c (s, random_ascii ());
672 /* prefer abstract namespace if available */
673 if (g_unix_socket_address_abstract_names_supported ())
674 address = g_unix_socket_address_new_with_type (s->str,
676 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
677 else
678 address = g_unix_socket_address_new (s->str);
679 g_string_free (s, TRUE);
681 local_error = NULL;
682 if (!g_socket_listener_add_address (server->listener,
683 address,
684 G_SOCKET_TYPE_STREAM,
685 G_SOCKET_PROTOCOL_DEFAULT,
686 NULL, /* source_object */
687 NULL, /* effective_address */
688 &local_error))
690 if (local_error->domain == G_IO_ERROR && local_error->code == G_IO_ERROR_ADDRESS_IN_USE)
692 g_error_free (local_error);
693 goto retry;
695 g_propagate_error (error, local_error);
696 goto out;
698 ret = TRUE;
699 goto out;
701 else if (abstract != NULL)
703 if (!g_unix_socket_address_abstract_names_supported ())
705 g_set_error_literal (error,
706 G_IO_ERROR,
707 G_IO_ERROR_NOT_SUPPORTED,
708 _("Abstract name space not supported"));
709 goto out;
711 address = g_unix_socket_address_new_with_type (abstract,
713 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
715 else
717 g_assert_not_reached ();
720 if (!g_socket_listener_add_address (server->listener,
721 address,
722 G_SOCKET_TYPE_STREAM,
723 G_SOCKET_PROTOCOL_DEFAULT,
724 NULL, /* source_object */
725 NULL, /* effective_address */
726 error))
727 goto out;
729 ret = TRUE;
731 out:
733 if (address != NULL)
735 /* Fill out client_address if the connection attempt worked */
736 if (ret)
738 server->is_using_listener = TRUE;
740 switch (g_unix_socket_address_get_address_type (G_UNIX_SOCKET_ADDRESS (address)))
742 case G_UNIX_SOCKET_ADDRESS_ABSTRACT:
743 server->client_address = g_strdup_printf ("unix:abstract=%s",
744 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
745 break;
747 case G_UNIX_SOCKET_ADDRESS_PATH:
748 server->client_address = g_strdup_printf ("unix:path=%s",
749 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
750 break;
752 default:
753 g_assert_not_reached ();
754 break;
757 g_object_unref (address);
759 return ret;
761 #endif
763 /* ---------------------------------------------------------------------------------------------------- */
765 /* note that address_entry has already been validated =>
766 * both host and port (guaranteed to be a number in [0, 65535]) are set (family is optional)
768 static gboolean
769 try_tcp (GDBusServer *server,
770 const gchar *address_entry,
771 GHashTable *key_value_pairs,
772 gboolean do_nonce,
773 GError **error)
775 gboolean ret;
776 const gchar *host;
777 const gchar *port;
778 gint port_num;
779 GResolver *resolver;
780 GList *resolved_addresses;
781 GList *l;
783 ret = FALSE;
784 resolver = NULL;
785 resolved_addresses = NULL;
787 host = g_hash_table_lookup (key_value_pairs, "host");
788 port = g_hash_table_lookup (key_value_pairs, "port");
789 /* family = g_hash_table_lookup (key_value_pairs, "family"); */
790 if (g_hash_table_lookup (key_value_pairs, "noncefile") != NULL)
792 g_set_error_literal (error,
793 G_IO_ERROR,
794 G_IO_ERROR_INVALID_ARGUMENT,
795 _("Cannot specify nonce file when creating a server"));
796 goto out;
799 if (host == NULL)
800 host = "localhost";
801 if (port == NULL)
802 port = "0";
803 port_num = strtol (port, NULL, 10);
805 resolver = g_resolver_get_default ();
806 resolved_addresses = g_resolver_lookup_by_name (resolver,
807 host,
808 NULL,
809 error);
810 if (resolved_addresses == NULL)
811 goto out;
813 /* TODO: handle family */
814 for (l = resolved_addresses; l != NULL; l = l->next)
816 GInetAddress *address = G_INET_ADDRESS (l->data);
817 GSocketAddress *socket_address;
818 GSocketAddress *effective_address;
820 socket_address = g_inet_socket_address_new (address, port_num);
821 if (!g_socket_listener_add_address (server->listener,
822 socket_address,
823 G_SOCKET_TYPE_STREAM,
824 G_SOCKET_PROTOCOL_TCP,
825 NULL, /* GObject *source_object */
826 &effective_address,
827 error))
829 g_object_unref (socket_address);
830 goto out;
832 if (port_num == 0)
833 /* make sure we allocate the same port number for other listeners */
834 port_num = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (effective_address));
836 g_object_unref (effective_address);
837 g_object_unref (socket_address);
840 if (do_nonce)
842 gint fd;
843 guint n;
844 gsize bytes_written;
845 gsize bytes_remaining;
846 char *file_escaped;
848 server->nonce = g_new0 (guchar, 16);
849 for (n = 0; n < 16; n++)
850 server->nonce[n] = g_random_int_range (0, 256);
851 fd = g_file_open_tmp ("gdbus-nonce-file-XXXXXX",
852 &server->nonce_file,
853 error);
854 if (fd == -1)
856 g_socket_listener_close (server->listener);
857 goto out;
859 again:
860 bytes_written = 0;
861 bytes_remaining = 16;
862 while (bytes_remaining > 0)
864 gssize ret;
865 int errsv;
867 ret = write (fd, server->nonce + bytes_written, bytes_remaining);
868 errsv = errno;
869 if (ret == -1)
871 if (errsv == EINTR)
872 goto again;
873 g_set_error (error,
874 G_IO_ERROR,
875 g_io_error_from_errno (errsv),
876 _("Error writing nonce file at “%s”: %s"),
877 server->nonce_file,
878 g_strerror (errsv));
879 goto out;
881 bytes_written += ret;
882 bytes_remaining -= ret;
884 if (!g_close (fd, error))
885 goto out;
886 file_escaped = g_uri_escape_string (server->nonce_file, "/\\", FALSE);
887 server->client_address = g_strdup_printf ("nonce-tcp:host=%s,port=%d,noncefile=%s",
888 host,
889 port_num,
890 file_escaped);
891 g_free (file_escaped);
893 else
895 server->client_address = g_strdup_printf ("tcp:host=%s,port=%d", host, port_num);
897 server->is_using_listener = TRUE;
898 ret = TRUE;
900 out:
901 g_list_free_full (resolved_addresses, g_object_unref);
902 if (resolver)
903 g_object_unref (resolver);
904 return ret;
907 /* ---------------------------------------------------------------------------------------------------- */
909 typedef struct
911 GDBusServer *server;
912 GDBusConnection *connection;
913 } EmitIdleData;
915 static void
916 emit_idle_data_free (EmitIdleData *data)
918 g_object_unref (data->server);
919 g_object_unref (data->connection);
920 g_free (data);
923 static gboolean
924 emit_new_connection_in_idle (gpointer user_data)
926 EmitIdleData *data = user_data;
927 gboolean claimed;
929 claimed = FALSE;
930 g_signal_emit (data->server,
931 _signals[NEW_CONNECTION_SIGNAL],
933 data->connection,
934 &claimed);
936 if (claimed)
937 g_dbus_connection_start_message_processing (data->connection);
938 g_object_unref (data->connection);
940 return FALSE;
943 /* Called in new thread */
944 static gboolean
945 on_run (GSocketService *service,
946 GSocketConnection *socket_connection,
947 GObject *source_object,
948 gpointer user_data)
950 GDBusServer *server = G_DBUS_SERVER (user_data);
951 GDBusConnection *connection;
952 GDBusConnectionFlags connection_flags;
954 if (server->nonce != NULL)
956 gchar buf[16];
957 gsize bytes_read;
959 if (!g_input_stream_read_all (g_io_stream_get_input_stream (G_IO_STREAM (socket_connection)),
960 buf,
962 &bytes_read,
963 NULL, /* GCancellable */
964 NULL)) /* GError */
965 goto out;
967 if (bytes_read != 16)
968 goto out;
970 if (memcmp (buf, server->nonce, 16) != 0)
971 goto out;
974 connection_flags =
975 G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER |
976 G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING;
977 if (server->flags & G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS)
978 connection_flags |= G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS;
980 connection = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
981 server->guid,
982 connection_flags,
983 server->authentication_observer,
984 NULL, /* GCancellable */
985 NULL); /* GError */
986 if (connection == NULL)
987 goto out;
989 if (server->flags & G_DBUS_SERVER_FLAGS_RUN_IN_THREAD)
991 gboolean claimed;
993 claimed = FALSE;
994 g_signal_emit (server,
995 _signals[NEW_CONNECTION_SIGNAL],
997 connection,
998 &claimed);
999 if (claimed)
1000 g_dbus_connection_start_message_processing (connection);
1001 g_object_unref (connection);
1003 else
1005 GSource *idle_source;
1006 EmitIdleData *data;
1008 data = g_new0 (EmitIdleData, 1);
1009 data->server = g_object_ref (server);
1010 data->connection = g_object_ref (connection);
1012 idle_source = g_idle_source_new ();
1013 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1014 g_source_set_callback (idle_source,
1015 emit_new_connection_in_idle,
1016 data,
1017 (GDestroyNotify) emit_idle_data_free);
1018 g_source_set_name (idle_source, "[gio] emit_new_connection_in_idle");
1019 g_source_attach (idle_source, server->main_context_at_construction);
1020 g_source_unref (idle_source);
1023 out:
1024 return TRUE;
1027 static gboolean
1028 initable_init (GInitable *initable,
1029 GCancellable *cancellable,
1030 GError **error)
1032 GDBusServer *server = G_DBUS_SERVER (initable);
1033 gboolean ret;
1034 guint n;
1035 gchar **addr_array;
1036 GError *last_error;
1038 ret = FALSE;
1039 addr_array = NULL;
1040 last_error = NULL;
1042 if (!g_dbus_is_guid (server->guid))
1044 g_set_error (&last_error,
1045 G_IO_ERROR,
1046 G_IO_ERROR_INVALID_ARGUMENT,
1047 _("The string “%s” is not a valid D-Bus GUID"),
1048 server->guid);
1049 goto out;
1052 server->listener = G_SOCKET_LISTENER (g_threaded_socket_service_new (-1));
1054 addr_array = g_strsplit (server->address, ";", 0);
1055 last_error = NULL;
1056 for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
1058 const gchar *address_entry = addr_array[n];
1059 GHashTable *key_value_pairs;
1060 gchar *transport_name;
1061 GError *this_error;
1063 this_error = NULL;
1064 if (g_dbus_is_supported_address (address_entry,
1065 &this_error) &&
1066 _g_dbus_address_parse_entry (address_entry,
1067 &transport_name,
1068 &key_value_pairs,
1069 &this_error))
1072 if (FALSE)
1075 #ifdef G_OS_UNIX
1076 else if (g_strcmp0 (transport_name, "unix") == 0)
1077 ret = try_unix (server, address_entry, key_value_pairs, &this_error);
1078 #endif
1079 else if (g_strcmp0 (transport_name, "tcp") == 0)
1080 ret = try_tcp (server, address_entry, key_value_pairs, FALSE, &this_error);
1081 else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
1082 ret = try_tcp (server, address_entry, key_value_pairs, TRUE, &this_error);
1083 else
1084 g_set_error (&this_error,
1085 G_IO_ERROR,
1086 G_IO_ERROR_INVALID_ARGUMENT,
1087 _("Cannot listen on unsupported transport “%s”"),
1088 transport_name);
1090 g_free (transport_name);
1091 if (key_value_pairs != NULL)
1092 g_hash_table_unref (key_value_pairs);
1094 if (ret)
1096 g_assert (this_error == NULL);
1097 goto out;
1101 if (this_error != NULL)
1103 if (last_error != NULL)
1104 g_error_free (last_error);
1105 last_error = this_error;
1109 out:
1111 g_strfreev (addr_array);
1113 if (ret)
1115 if (last_error != NULL)
1116 g_error_free (last_error);
1118 /* Right now we don't have any transport not using the listener... */
1119 g_assert (server->is_using_listener);
1120 server->run_signal_handler_id = g_signal_connect (G_SOCKET_SERVICE (server->listener),
1121 "run",
1122 G_CALLBACK (on_run),
1123 server);
1125 else
1127 g_assert (last_error != NULL);
1128 g_propagate_error (error, last_error);
1130 return ret;
1134 static void
1135 initable_iface_init (GInitableIface *initable_iface)
1137 initable_iface->init = initable_init;
1140 /* ---------------------------------------------------------------------------------------------------- */