1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2009 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, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: David Zeuthen <davidz@redhat.com>
26 #include <glib/gi18n.h>
31 #include <gio/gunixsocketaddress.h>
35 #include "gdbusaddress.h"
36 #include "gdbusutils.h"
37 #include "gdbusconnection.h"
38 #include "gdbusserver.h"
39 #include "gioenumtypes.h"
40 #include "gdbusprivate.h"
41 #include "gdbusauthobserver.h"
42 #include "gio-marshal.h"
46 * @short_description: Helper for accepting connections
49 * #GDBusServer is a helper for listening to and accepting D-Bus
52 * <example id="gdbus-peer-to-peer"><title>D-Bus peer-to-peer example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-peer.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
55 struct _GDBusServerPrivate
57 GDBusServerFlags flags;
64 gchar *client_address;
66 GSocketListener *listener;
67 gboolean is_using_listener;
69 /* The result of g_main_context_get_thread_default() when the object
70 * was created (the GObject _init() function) - this is used for delivery
71 * of the :new-connection GObject signal.
73 GMainContext *main_context_at_construction;
77 GDBusAuthObserver *authentication_observer;
88 PROP_AUTHENTICATION_OBSERVER,
93 NEW_CONNECTION_SIGNAL,
97 guint _signals[LAST_SIGNAL] = {0};
99 static void initable_iface_init (GInitableIface *initable_iface);
101 G_DEFINE_TYPE_WITH_CODE (GDBusServer, g_dbus_server, G_TYPE_OBJECT,
102 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
106 g_dbus_server_finalize (GObject *object)
108 GDBusServer *server = G_DBUS_SERVER (object);
110 if (server->priv->authentication_observer != NULL)
111 g_object_unref (server->priv->authentication_observer);
113 if (server->priv->listener != NULL)
114 g_object_unref (server->priv->listener);
116 g_free (server->priv->address);
117 g_free (server->priv->guid);
118 g_free (server->priv->client_address);
119 if (server->priv->nonce != NULL)
121 memset (server->priv->nonce, '\0', 16);
122 g_free (server->priv->nonce);
124 /* we could unlink the nonce file but I don't
125 * think it's really worth the effort/risk
127 g_free (server->priv->nonce_file);
129 if (server->priv->main_context_at_construction != NULL)
130 g_main_context_unref (server->priv->main_context_at_construction);
132 if (G_OBJECT_CLASS (g_dbus_server_parent_class)->finalize != NULL)
133 G_OBJECT_CLASS (g_dbus_server_parent_class)->finalize (object);
137 g_dbus_server_get_property (GObject *object,
142 GDBusServer *server = G_DBUS_SERVER (object);
147 g_value_set_flags (value, server->priv->flags);
151 g_value_set_string (value, server->priv->guid);
155 g_value_set_string (value, server->priv->address);
158 case PROP_CLIENT_ADDRESS:
159 g_value_set_string (value, server->priv->client_address);
163 g_value_set_boolean (value, server->priv->active);
166 case PROP_AUTHENTICATION_OBSERVER:
167 g_value_set_object (value, server->priv->authentication_observer);
171 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
177 g_dbus_server_set_property (GObject *object,
182 GDBusServer *server = G_DBUS_SERVER (object);
187 server->priv->flags = g_value_get_flags (value);
191 server->priv->guid = g_value_dup_string (value);
195 server->priv->address = g_value_dup_string (value);
198 case PROP_AUTHENTICATION_OBSERVER:
199 server->priv->authentication_observer = g_value_dup_object (value);
203 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
209 g_dbus_server_class_init (GDBusServerClass *klass)
211 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
213 gobject_class->finalize = g_dbus_server_finalize;
214 gobject_class->set_property = g_dbus_server_set_property;
215 gobject_class->get_property = g_dbus_server_get_property;
220 * Flags from the #GDBusServerFlags enumeration.
224 g_object_class_install_property (gobject_class,
226 g_param_spec_flags ("flags",
228 _("Flags for the server"),
229 G_TYPE_DBUS_SERVER_FLAGS,
230 G_DBUS_SERVER_FLAGS_NONE,
233 G_PARAM_CONSTRUCT_ONLY |
234 G_PARAM_STATIC_NAME |
235 G_PARAM_STATIC_BLURB |
236 G_PARAM_STATIC_NICK));
241 * The guid of the server.
245 g_object_class_install_property (gobject_class,
247 g_param_spec_string ("guid",
249 _("The guid of the server"),
253 G_PARAM_CONSTRUCT_ONLY |
254 G_PARAM_STATIC_NAME |
255 G_PARAM_STATIC_BLURB |
256 G_PARAM_STATIC_NICK));
259 * GDBusServer:address:
261 * The D-Bus address to listen on.
265 g_object_class_install_property (gobject_class,
267 g_param_spec_string ("address",
269 _("The address to listen on"),
273 G_PARAM_CONSTRUCT_ONLY |
274 G_PARAM_STATIC_NAME |
275 G_PARAM_STATIC_BLURB |
276 G_PARAM_STATIC_NICK));
279 * GDBusServer:client-address:
281 * The D-Bus address that clients can use.
285 g_object_class_install_property (gobject_class,
287 g_param_spec_string ("client-address",
289 _("The address clients can use"),
292 G_PARAM_STATIC_NAME |
293 G_PARAM_STATIC_BLURB |
294 G_PARAM_STATIC_NICK));
297 * GDBusServer:active:
299 * Whether the server is currently active.
303 g_object_class_install_property (gobject_class,
305 g_param_spec_string ("active",
307 _("Whether the server is currently active"),
310 G_PARAM_STATIC_NAME |
311 G_PARAM_STATIC_BLURB |
312 G_PARAM_STATIC_NICK));
315 * GDBusServer:authentication-observer:
317 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
321 g_object_class_install_property (gobject_class,
322 PROP_AUTHENTICATION_OBSERVER,
323 g_param_spec_object ("authentication-observer",
324 _("Authentication Observer"),
325 _("Object used to assist in the authentication process"),
326 G_TYPE_DBUS_AUTH_OBSERVER,
329 G_PARAM_CONSTRUCT_ONLY |
330 G_PARAM_STATIC_NAME |
331 G_PARAM_STATIC_BLURB |
332 G_PARAM_STATIC_NICK));
335 * GDBusServer::new-connection:
336 * @server: The #GDBusServer emitting the signal.
337 * @connection: A #GDBusConnection for the new connection.
339 * Emitted when a new authenticated connection has been made. Use
340 * g_dbus_connection_get_peer_credentials() to figure out what
341 * identity (if any), was authenticated.
343 * If you want to accept the connection, simply ref the @connection
344 * object. Then call g_dbus_connection_close() and unref it when you
345 * are done with it. A typical thing to do when accepting a
346 * connection is to listen to the #GDBusConnection::closed signal.
348 * If #GDBusServer:flags contains %G_DBUS_SERVER_FLAGS_RUN_IN_THREAD
349 * then the signal is emitted in a new thread dedicated to the
350 * connection. Otherwise the signal is emitted in the <link
351 * linkend="g-main-context-push-thread-default">thread-default main
352 * loop</link> of the thread that @server was constructed in.
356 _signals[NEW_CONNECTION_SIGNAL] = g_signal_new ("new-connection",
359 G_STRUCT_OFFSET (GDBusServerClass, new_connection),
362 g_cclosure_marshal_VOID__OBJECT,
365 G_TYPE_DBUS_CONNECTION);
368 g_type_class_add_private (klass, sizeof (GDBusServerPrivate));
372 g_dbus_server_init (GDBusServer *server)
374 server->priv = G_TYPE_INSTANCE_GET_PRIVATE (server, G_TYPE_DBUS_SERVER, GDBusServerPrivate);
376 server->priv->main_context_at_construction = g_main_context_get_thread_default ();
377 if (server->priv->main_context_at_construction != NULL)
378 g_main_context_ref (server->priv->main_context_at_construction);
382 on_run (GSocketService *service,
383 GSocketConnection *socket_connection,
384 GObject *source_object,
388 * g_dbus_server_new_sync:
389 * @address: A D-Bus address.
390 * @flags: Flags from the #GDBusServerFlags enumeration.
391 * @guid: A D-Bus GUID.
392 * @observer: A #GDBusAuthObserver or %NULL.
393 * @cancellable: A #GCancellable or %NULL.
394 * @error: Return location for server or %NULL.
396 * Creates a new D-Bus server that listens on the first address in
397 * @address that works.
399 * Once constructed, you can use g_dbus_server_get_client_address() to
400 * get a D-Bus address string that clients can use to connect.
402 * Connect to the #GDBusServer::new-connection signal to handle
403 * incoming connections.
405 * The returned #GDBusServer isn't active - you have to start it with
406 * g_dbus_server_start().
408 * See <xref linkend="gdbus-peer-to-peer"/> for how #GDBusServer can
411 * This is a synchronous failable constructor. See
412 * g_dbus_server_new() for the asynchronous version.
414 * Returns: A #GDBusServer or %NULL if @error is set. Free with
420 g_dbus_server_new_sync (const gchar *address,
421 GDBusServerFlags flags,
423 GDBusAuthObserver *observer,
424 GCancellable *cancellable,
429 g_return_val_if_fail (address != NULL, NULL);
430 g_return_val_if_fail (g_dbus_is_guid (guid), NULL);
431 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
433 server = g_initable_new (G_TYPE_DBUS_SERVER,
439 "authentication-observer", observer,
443 /* Right now we don't have any transport not using the listener... */
444 g_assert (server->priv->is_using_listener);
445 g_signal_connect (G_SOCKET_SERVICE (server->priv->listener),
455 * g_dbus_server_get_client_address:
456 * @server: A #GDBusServer.
458 * Gets a D-Bus address string that can be used by clients to connect
461 * Returns: A D-Bus address string. Do not free, the string is owned
467 g_dbus_server_get_client_address (GDBusServer *server)
469 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
470 return server->priv->client_address;
474 * g_dbus_server_get_guid:
475 * @server: A #GDBusServer.
477 * Gets the GUID for @server.
479 * Returns: A D-Bus GUID. Do not free this string, it is owned by @server.
484 g_dbus_server_get_guid (GDBusServer *server)
486 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
487 return server->priv->guid;
491 * g_dbus_server_get_flags:
492 * @server: A #GDBusServer.
494 * Gets the flags for @server.
496 * Returns: A set of flags from the #GDBusServerFlags enumeration.
501 g_dbus_server_get_flags (GDBusServer *server)
503 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
504 return server->priv->flags;
508 * g_dbus_server_is_active:
509 * @server: A #GDBusServer.
511 * Gets whether @server is active.
513 * Returns: %TRUE if server is active, %FALSE otherwise.
518 g_dbus_server_is_active (GDBusServer *server)
520 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
521 return server->priv->active;
525 * g_dbus_server_start:
526 * @server: A #GDBusServer.
533 g_dbus_server_start (GDBusServer *server)
535 g_return_if_fail (G_IS_DBUS_SERVER (server));
536 if (server->priv->active)
538 /* Right now we don't have any transport not using the listener... */
539 g_assert (server->priv->is_using_listener);
540 g_socket_service_start (G_SOCKET_SERVICE (server->priv->listener));
541 server->priv->active = TRUE;
542 g_object_notify (G_OBJECT (server), "active");
546 * g_dbus_server_stop:
547 * @server: A #GDBusServer.
554 g_dbus_server_stop (GDBusServer *server)
556 g_return_if_fail (G_IS_DBUS_SERVER (server));
557 if (!server->priv->active)
559 /* Right now we don't have any transport not using the listener... */
560 g_assert (server->priv->is_using_listener);
561 g_socket_service_stop (G_SOCKET_SERVICE (server->priv->listener));
562 server->priv->active = FALSE;
563 g_object_notify (G_OBJECT (server), "active");
566 /* ---------------------------------------------------------------------------------------------------- */
574 ret = g_random_int_range (0, 60);
584 /* note that address_entry has already been validated => exactly one of path, tmpdir or abstract keys are set */
586 try_unix (GDBusServer *server,
587 const gchar *address_entry,
588 GHashTable *key_value_pairs,
594 const gchar *abstract;
595 GSocketAddress *address;
600 path = g_hash_table_lookup (key_value_pairs, "path");
601 tmpdir = g_hash_table_lookup (key_value_pairs, "tmpdir");
602 abstract = g_hash_table_lookup (key_value_pairs, "abstract");
606 address = g_unix_socket_address_new (path);
608 else if (tmpdir != NULL)
615 s = g_string_new (tmpdir);
616 g_string_append (s, "/dbus-");
617 for (n = 0; n < 8; n++)
618 g_string_append_c (s, random_ascii ());
620 /* prefer abstract namespace if available */
621 if (g_unix_socket_address_abstract_names_supported ())
622 address = g_unix_socket_address_new_with_type (s->str,
624 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
626 address = g_unix_socket_address_new (s->str);
627 g_string_free (s, TRUE);
630 if (!g_socket_listener_add_address (server->priv->listener,
632 G_SOCKET_TYPE_STREAM,
633 G_SOCKET_PROTOCOL_DEFAULT,
634 NULL, /* source_object */
635 NULL, /* effective_address */
638 if (local_error->domain == G_IO_ERROR && local_error->code == G_IO_ERROR_ADDRESS_IN_USE)
640 g_error_free (local_error);
643 g_propagate_error (error, local_error);
649 else if (abstract != NULL)
651 if (!g_unix_socket_address_abstract_names_supported ())
653 g_set_error_literal (error,
655 G_IO_ERROR_NOT_SUPPORTED,
656 _("Abstract name space not supported"));
659 address = g_unix_socket_address_new_with_type (abstract,
661 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
665 g_assert_not_reached ();
668 if (!g_socket_listener_add_address (server->priv->listener,
670 G_SOCKET_TYPE_STREAM,
671 G_SOCKET_PROTOCOL_DEFAULT,
672 NULL, /* source_object */
673 NULL, /* effective_address */
683 /* Fill out client_address if the connection attempt worked */
686 server->priv->is_using_listener = TRUE;
688 switch (g_unix_socket_address_get_address_type (G_UNIX_SOCKET_ADDRESS (address)))
690 case G_UNIX_SOCKET_ADDRESS_ABSTRACT:
691 server->priv->client_address = g_strdup_printf ("unix:abstract=%s",
692 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
695 case G_UNIX_SOCKET_ADDRESS_PATH:
696 server->priv->client_address = g_strdup_printf ("unix:path=%s",
697 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
701 g_assert_not_reached ();
705 g_object_unref (address);
711 /* ---------------------------------------------------------------------------------------------------- */
713 /* note that address_entry has already been validated =>
714 * both host and port (guranteed to be a number in [0, 65535]) are set (family is optional)
717 try_tcp (GDBusServer *server,
718 const gchar *address_entry,
719 GHashTable *key_value_pairs,
728 GSocketAddress *address;
730 GList *resolved_addresses;
736 resolved_addresses = NULL;
738 host = g_hash_table_lookup (key_value_pairs, "host");
739 port = g_hash_table_lookup (key_value_pairs, "port");
740 family = g_hash_table_lookup (key_value_pairs, "family");
741 if (g_hash_table_lookup (key_value_pairs, "noncefile") != NULL)
743 g_set_error_literal (error,
745 G_IO_ERROR_INVALID_ARGUMENT,
746 _("Cannot specify nonce file when creating a server"));
754 port_num = strtol (port, NULL, 10);
756 resolver = g_resolver_get_default ();
757 resolved_addresses = g_resolver_lookup_by_name (resolver,
761 if (resolved_addresses == NULL)
765 /* TODO: handle family */
766 for (l = resolved_addresses; l != NULL; l = l->next)
768 GInetAddress *address = G_INET_ADDRESS (l->data);
769 GSocketAddress *socket_address;
770 GSocketAddress *effective_address;
772 socket_address = g_inet_socket_address_new (address, port_num);
773 if (!g_socket_listener_add_address (server->priv->listener,
775 G_SOCKET_TYPE_STREAM,
776 G_SOCKET_PROTOCOL_TCP,
777 NULL, /* GObject *source_object */
781 g_object_unref (socket_address);
786 /* make sure we allocate the same port number for other listeners */
787 port_num = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (effective_address));
789 g_object_unref (effective_address);
790 g_object_unref (socket_address);
798 gsize bytes_remaining;
800 server->priv->nonce = g_new0 (guchar, 16);
801 for (n = 0; n < 16; n++)
802 server->priv->nonce[n] = g_random_int_range (0, 256);
803 fd = g_file_open_tmp ("gdbus-nonce-file-XXXXXX",
804 &server->priv->nonce_file,
808 g_socket_listener_close (server->priv->listener);
813 bytes_remaining = 16;
814 while (bytes_remaining > 0)
817 ret = write (fd, server->priv->nonce + bytes_written, bytes_remaining);
824 g_io_error_from_errno (errno),
825 _("Error writing nonce file at `%s': %s"),
826 server->priv->nonce_file,
830 bytes_written += ret;
831 bytes_remaining -= ret;
834 server->priv->client_address = g_strdup_printf ("nonce-tcp:host=%s,port=%d,noncefile=%s",
837 server->priv->nonce_file);
841 server->priv->client_address = g_strdup_printf ("tcp:host=%s,port=%d", host, port_num);
843 server->priv->is_using_listener = TRUE;
847 g_list_foreach (resolved_addresses, (GFunc) g_object_unref, NULL);
848 g_list_free (resolved_addresses);
849 g_object_unref (resolver);
853 /* ---------------------------------------------------------------------------------------------------- */
858 GDBusConnection *connection;
862 emit_idle_data_free (EmitIdleData *data)
864 g_object_unref (data->server);
865 g_object_unref (data->connection);
870 emit_new_connection_in_idle (gpointer user_data)
872 EmitIdleData *data = user_data;
874 g_signal_emit (data->server,
875 _signals[NEW_CONNECTION_SIGNAL],
878 g_object_unref (data->connection);
883 /* Called in new thread */
885 on_run (GSocketService *service,
886 GSocketConnection *socket_connection,
887 GObject *source_object,
890 GDBusServer *server = G_DBUS_SERVER (user_data);
891 GDBusConnection *connection;
892 GDBusConnectionFlags connection_flags;
894 if (server->priv->nonce != NULL)
899 if (!g_input_stream_read_all (g_io_stream_get_input_stream (G_IO_STREAM (socket_connection)),
903 NULL, /* GCancellable */
907 if (bytes_read != 16)
910 if (memcmp (buf, server->priv->nonce, 16) != 0)
914 connection_flags = G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER;
915 if (server->priv->flags & G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS)
916 connection_flags |= G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS;
918 connection = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
921 server->priv->authentication_observer,
922 NULL, /* GCancellable */
924 if (connection == NULL)
927 if (server->priv->flags & G_DBUS_SERVER_FLAGS_RUN_IN_THREAD)
929 g_signal_emit (server,
930 _signals[NEW_CONNECTION_SIGNAL],
933 g_object_unref (connection);
937 GSource *idle_source;
940 data = g_new0 (EmitIdleData, 1);
941 data->server = g_object_ref (server);
942 data->connection = g_object_ref (connection);
944 idle_source = g_idle_source_new ();
945 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
946 g_source_set_callback (idle_source,
947 emit_new_connection_in_idle,
949 (GDestroyNotify) emit_idle_data_free);
950 g_source_attach (idle_source, server->priv->main_context_at_construction);
951 g_source_unref (idle_source);
959 initable_init (GInitable *initable,
960 GCancellable *cancellable,
963 GDBusServer *server = G_DBUS_SERVER (initable);
972 if (!g_dbus_is_guid (server->priv->guid))
974 g_set_error (&last_error,
976 G_IO_ERROR_INVALID_ARGUMENT,
977 _("The string `%s' is not a valid D-Bus GUID"),
982 server->priv->listener = G_SOCKET_LISTENER (g_threaded_socket_service_new (-1));
984 addr_array = g_strsplit (server->priv->address, ";", 0);
986 for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
988 const gchar *address_entry = addr_array[n];
989 GHashTable *key_value_pairs;
990 gchar *transport_name;
994 if (g_dbus_is_supported_address (address_entry,
996 _g_dbus_address_parse_entry (address_entry,
1006 else if (g_strcmp0 (transport_name, "unix") == 0)
1008 ret = try_unix (server, address_entry, key_value_pairs, &this_error);
1011 else if (g_strcmp0 (transport_name, "tcp") == 0)
1013 ret = try_tcp (server, address_entry, key_value_pairs, FALSE, &this_error);
1015 else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
1017 ret = try_tcp (server, address_entry, key_value_pairs, TRUE, &this_error);
1021 g_set_error (&this_error,
1023 G_IO_ERROR_INVALID_ARGUMENT,
1024 _("Cannot listen on unsupported transport `%s'"),
1028 g_free (transport_name);
1029 if (key_value_pairs != NULL)
1030 g_hash_table_unref (key_value_pairs);
1034 g_assert (this_error == NULL);
1039 if (this_error != NULL)
1041 if (last_error != NULL)
1042 g_error_free (last_error);
1043 last_error = this_error;
1053 if (last_error != NULL)
1054 g_error_free (last_error);
1058 g_assert (last_error != NULL);
1059 g_propagate_error (error, last_error);
1066 initable_iface_init (GInitableIface *initable_iface)
1068 initable_iface->init = initable_init;
1071 /* ---------------------------------------------------------------------------------------------------- */