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, 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>
33 #include "gdbusaddress.h"
34 #include "gdbusutils.h"
35 #include "gdbusconnection.h"
36 #include "gdbusserver.h"
37 #include "gioenumtypes.h"
38 #include "gdbusprivate.h"
39 #include "gdbusauthobserver.h"
40 #include "gio-marshal.h"
41 #include "ginitable.h"
42 #include "gsocketservice.h"
45 #include "gunixsocketaddress.h"
53 * @short_description: Helper for accepting connections
56 * #GDBusServer is a helper for listening to and accepting D-Bus
59 * <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>
62 struct _GDBusServerPrivate
64 GDBusServerFlags flags;
71 gchar *client_address;
73 GSocketListener *listener;
74 gboolean is_using_listener;
76 /* The result of g_main_context_get_thread_default() when the object
77 * was created (the GObject _init() function) - this is used for delivery
78 * of the :new-connection GObject signal.
80 GMainContext *main_context_at_construction;
84 GDBusAuthObserver *authentication_observer;
95 PROP_AUTHENTICATION_OBSERVER,
100 NEW_CONNECTION_SIGNAL,
104 guint _signals[LAST_SIGNAL] = {0};
106 static void initable_iface_init (GInitableIface *initable_iface);
108 G_DEFINE_TYPE_WITH_CODE (GDBusServer, g_dbus_server, G_TYPE_OBJECT,
109 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
113 g_dbus_server_finalize (GObject *object)
115 GDBusServer *server = G_DBUS_SERVER (object);
117 if (server->priv->authentication_observer != NULL)
118 g_object_unref (server->priv->authentication_observer);
120 if (server->priv->listener != NULL)
121 g_object_unref (server->priv->listener);
123 g_free (server->priv->address);
124 g_free (server->priv->guid);
125 g_free (server->priv->client_address);
126 if (server->priv->nonce != NULL)
128 memset (server->priv->nonce, '\0', 16);
129 g_free (server->priv->nonce);
131 /* we could unlink the nonce file but I don't
132 * think it's really worth the effort/risk
134 g_free (server->priv->nonce_file);
136 if (server->priv->main_context_at_construction != NULL)
137 g_main_context_unref (server->priv->main_context_at_construction);
139 G_OBJECT_CLASS (g_dbus_server_parent_class)->finalize (object);
143 g_dbus_server_get_property (GObject *object,
148 GDBusServer *server = G_DBUS_SERVER (object);
153 g_value_set_flags (value, server->priv->flags);
157 g_value_set_string (value, server->priv->guid);
161 g_value_set_string (value, server->priv->address);
164 case PROP_CLIENT_ADDRESS:
165 g_value_set_string (value, server->priv->client_address);
169 g_value_set_boolean (value, server->priv->active);
172 case PROP_AUTHENTICATION_OBSERVER:
173 g_value_set_object (value, server->priv->authentication_observer);
177 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
183 g_dbus_server_set_property (GObject *object,
188 GDBusServer *server = G_DBUS_SERVER (object);
193 server->priv->flags = g_value_get_flags (value);
197 server->priv->guid = g_value_dup_string (value);
201 server->priv->address = g_value_dup_string (value);
204 case PROP_AUTHENTICATION_OBSERVER:
205 server->priv->authentication_observer = g_value_dup_object (value);
209 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
215 g_dbus_server_class_init (GDBusServerClass *klass)
217 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
219 gobject_class->finalize = g_dbus_server_finalize;
220 gobject_class->set_property = g_dbus_server_set_property;
221 gobject_class->get_property = g_dbus_server_get_property;
226 * Flags from the #GDBusServerFlags enumeration.
230 g_object_class_install_property (gobject_class,
232 g_param_spec_flags ("flags",
234 P_("Flags for the server"),
235 G_TYPE_DBUS_SERVER_FLAGS,
236 G_DBUS_SERVER_FLAGS_NONE,
239 G_PARAM_CONSTRUCT_ONLY |
240 G_PARAM_STATIC_NAME |
241 G_PARAM_STATIC_BLURB |
242 G_PARAM_STATIC_NICK));
247 * The guid of the server.
251 g_object_class_install_property (gobject_class,
253 g_param_spec_string ("guid",
255 P_("The guid of the server"),
259 G_PARAM_CONSTRUCT_ONLY |
260 G_PARAM_STATIC_NAME |
261 G_PARAM_STATIC_BLURB |
262 G_PARAM_STATIC_NICK));
265 * GDBusServer:address:
267 * The D-Bus address to listen on.
271 g_object_class_install_property (gobject_class,
273 g_param_spec_string ("address",
275 P_("The address to listen on"),
279 G_PARAM_CONSTRUCT_ONLY |
280 G_PARAM_STATIC_NAME |
281 G_PARAM_STATIC_BLURB |
282 G_PARAM_STATIC_NICK));
285 * GDBusServer:client-address:
287 * The D-Bus address that clients can use.
291 g_object_class_install_property (gobject_class,
293 g_param_spec_string ("client-address",
294 P_("Client Address"),
295 P_("The address clients can use"),
298 G_PARAM_STATIC_NAME |
299 G_PARAM_STATIC_BLURB |
300 G_PARAM_STATIC_NICK));
303 * GDBusServer:active:
305 * Whether the server is currently active.
309 g_object_class_install_property (gobject_class,
311 g_param_spec_string ("active",
313 P_("Whether the server is currently active"),
316 G_PARAM_STATIC_NAME |
317 G_PARAM_STATIC_BLURB |
318 G_PARAM_STATIC_NICK));
321 * GDBusServer:authentication-observer:
323 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
327 g_object_class_install_property (gobject_class,
328 PROP_AUTHENTICATION_OBSERVER,
329 g_param_spec_object ("authentication-observer",
330 P_("Authentication Observer"),
331 P_("Object used to assist in the authentication process"),
332 G_TYPE_DBUS_AUTH_OBSERVER,
335 G_PARAM_CONSTRUCT_ONLY |
336 G_PARAM_STATIC_NAME |
337 G_PARAM_STATIC_BLURB |
338 G_PARAM_STATIC_NICK));
341 * GDBusServer::new-connection:
342 * @server: The #GDBusServer emitting the signal.
343 * @connection: A #GDBusConnection for the new connection.
345 * Emitted when a new authenticated connection has been made. Use
346 * g_dbus_connection_get_peer_credentials() to figure out what
347 * identity (if any), was authenticated.
349 * If you want to accept the connection, simply ref the @connection
350 * object. Then call g_dbus_connection_close() and unref it when you
351 * are done with it. A typical thing to do when accepting a
352 * connection is to listen to the #GDBusConnection::closed signal.
354 * If #GDBusServer:flags contains %G_DBUS_SERVER_FLAGS_RUN_IN_THREAD
355 * then the signal is emitted in a new thread dedicated to the
356 * connection. Otherwise the signal is emitted in the <link
357 * linkend="g-main-context-push-thread-default">thread-default main
358 * loop</link> of the thread that @server was constructed in.
362 _signals[NEW_CONNECTION_SIGNAL] = g_signal_new ("new-connection",
365 G_STRUCT_OFFSET (GDBusServerClass, new_connection),
368 g_cclosure_marshal_VOID__OBJECT,
371 G_TYPE_DBUS_CONNECTION);
374 g_type_class_add_private (klass, sizeof (GDBusServerPrivate));
378 g_dbus_server_init (GDBusServer *server)
380 server->priv = G_TYPE_INSTANCE_GET_PRIVATE (server, G_TYPE_DBUS_SERVER, GDBusServerPrivate);
382 server->priv->main_context_at_construction = g_main_context_get_thread_default ();
383 if (server->priv->main_context_at_construction != NULL)
384 g_main_context_ref (server->priv->main_context_at_construction);
388 on_run (GSocketService *service,
389 GSocketConnection *socket_connection,
390 GObject *source_object,
394 * g_dbus_server_new_sync:
395 * @address: A D-Bus address.
396 * @flags: Flags from the #GDBusServerFlags enumeration.
397 * @guid: A D-Bus GUID.
398 * @observer: A #GDBusAuthObserver or %NULL.
399 * @cancellable: A #GCancellable or %NULL.
400 * @error: Return location for server or %NULL.
402 * Creates a new D-Bus server that listens on the first address in
403 * @address that works.
405 * Once constructed, you can use g_dbus_server_get_client_address() to
406 * get a D-Bus address string that clients can use to connect.
408 * Connect to the #GDBusServer::new-connection signal to handle
409 * incoming connections.
411 * The returned #GDBusServer isn't active - you have to start it with
412 * g_dbus_server_start().
414 * See <xref linkend="gdbus-peer-to-peer"/> for how #GDBusServer can
417 * This is a synchronous failable constructor. See
418 * g_dbus_server_new() for the asynchronous version.
420 * Returns: A #GDBusServer or %NULL if @error is set. Free with
426 g_dbus_server_new_sync (const gchar *address,
427 GDBusServerFlags flags,
429 GDBusAuthObserver *observer,
430 GCancellable *cancellable,
435 g_return_val_if_fail (address != NULL, NULL);
436 g_return_val_if_fail (g_dbus_is_guid (guid), NULL);
437 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
439 server = g_initable_new (G_TYPE_DBUS_SERVER,
445 "authentication-observer", observer,
449 /* Right now we don't have any transport not using the listener... */
450 g_assert (server->priv->is_using_listener);
451 g_signal_connect (G_SOCKET_SERVICE (server->priv->listener),
461 * g_dbus_server_get_client_address:
462 * @server: A #GDBusServer.
464 * Gets a D-Bus address string that can be used by clients to connect
467 * Returns: A D-Bus address string. Do not free, the string is owned
473 g_dbus_server_get_client_address (GDBusServer *server)
475 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
476 return server->priv->client_address;
480 * g_dbus_server_get_guid:
481 * @server: A #GDBusServer.
483 * Gets the GUID for @server.
485 * Returns: A D-Bus GUID. Do not free this string, it is owned by @server.
490 g_dbus_server_get_guid (GDBusServer *server)
492 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
493 return server->priv->guid;
497 * g_dbus_server_get_flags:
498 * @server: A #GDBusServer.
500 * Gets the flags for @server.
502 * Returns: A set of flags from the #GDBusServerFlags enumeration.
507 g_dbus_server_get_flags (GDBusServer *server)
509 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
510 return server->priv->flags;
514 * g_dbus_server_is_active:
515 * @server: A #GDBusServer.
517 * Gets whether @server is active.
519 * Returns: %TRUE if server is active, %FALSE otherwise.
524 g_dbus_server_is_active (GDBusServer *server)
526 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
527 return server->priv->active;
531 * g_dbus_server_start:
532 * @server: A #GDBusServer.
539 g_dbus_server_start (GDBusServer *server)
541 g_return_if_fail (G_IS_DBUS_SERVER (server));
542 if (server->priv->active)
544 /* Right now we don't have any transport not using the listener... */
545 g_assert (server->priv->is_using_listener);
546 g_socket_service_start (G_SOCKET_SERVICE (server->priv->listener));
547 server->priv->active = TRUE;
548 g_object_notify (G_OBJECT (server), "active");
552 * g_dbus_server_stop:
553 * @server: A #GDBusServer.
560 g_dbus_server_stop (GDBusServer *server)
562 g_return_if_fail (G_IS_DBUS_SERVER (server));
563 if (!server->priv->active)
565 /* Right now we don't have any transport not using the listener... */
566 g_assert (server->priv->is_using_listener);
567 g_socket_service_stop (G_SOCKET_SERVICE (server->priv->listener));
568 server->priv->active = FALSE;
569 g_object_notify (G_OBJECT (server), "active");
572 /* ---------------------------------------------------------------------------------------------------- */
580 ret = g_random_int_range (0, 60);
590 /* note that address_entry has already been validated => exactly one of path, tmpdir or abstract keys are set */
592 try_unix (GDBusServer *server,
593 const gchar *address_entry,
594 GHashTable *key_value_pairs,
600 const gchar *abstract;
601 GSocketAddress *address;
606 path = g_hash_table_lookup (key_value_pairs, "path");
607 tmpdir = g_hash_table_lookup (key_value_pairs, "tmpdir");
608 abstract = g_hash_table_lookup (key_value_pairs, "abstract");
612 address = g_unix_socket_address_new (path);
614 else if (tmpdir != NULL)
621 s = g_string_new (tmpdir);
622 g_string_append (s, "/dbus-");
623 for (n = 0; n < 8; n++)
624 g_string_append_c (s, random_ascii ());
626 /* prefer abstract namespace if available */
627 if (g_unix_socket_address_abstract_names_supported ())
628 address = g_unix_socket_address_new_with_type (s->str,
630 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
632 address = g_unix_socket_address_new (s->str);
633 g_string_free (s, TRUE);
636 if (!g_socket_listener_add_address (server->priv->listener,
638 G_SOCKET_TYPE_STREAM,
639 G_SOCKET_PROTOCOL_DEFAULT,
640 NULL, /* source_object */
641 NULL, /* effective_address */
644 if (local_error->domain == G_IO_ERROR && local_error->code == G_IO_ERROR_ADDRESS_IN_USE)
646 g_error_free (local_error);
649 g_propagate_error (error, local_error);
655 else if (abstract != NULL)
657 if (!g_unix_socket_address_abstract_names_supported ())
659 g_set_error_literal (error,
661 G_IO_ERROR_NOT_SUPPORTED,
662 _("Abstract name space not supported"));
665 address = g_unix_socket_address_new_with_type (abstract,
667 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
671 g_assert_not_reached ();
674 if (!g_socket_listener_add_address (server->priv->listener,
676 G_SOCKET_TYPE_STREAM,
677 G_SOCKET_PROTOCOL_DEFAULT,
678 NULL, /* source_object */
679 NULL, /* effective_address */
689 /* Fill out client_address if the connection attempt worked */
692 server->priv->is_using_listener = TRUE;
694 switch (g_unix_socket_address_get_address_type (G_UNIX_SOCKET_ADDRESS (address)))
696 case G_UNIX_SOCKET_ADDRESS_ABSTRACT:
697 server->priv->client_address = g_strdup_printf ("unix:abstract=%s",
698 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
701 case G_UNIX_SOCKET_ADDRESS_PATH:
702 server->priv->client_address = g_strdup_printf ("unix:path=%s",
703 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
707 g_assert_not_reached ();
711 g_object_unref (address);
717 /* ---------------------------------------------------------------------------------------------------- */
719 /* note that address_entry has already been validated =>
720 * both host and port (guranteed to be a number in [0, 65535]) are set (family is optional)
723 try_tcp (GDBusServer *server,
724 const gchar *address_entry,
725 GHashTable *key_value_pairs,
734 GSocketAddress *address;
736 GList *resolved_addresses;
742 resolved_addresses = NULL;
744 host = g_hash_table_lookup (key_value_pairs, "host");
745 port = g_hash_table_lookup (key_value_pairs, "port");
746 family = g_hash_table_lookup (key_value_pairs, "family");
747 if (g_hash_table_lookup (key_value_pairs, "noncefile") != NULL)
749 g_set_error_literal (error,
751 G_IO_ERROR_INVALID_ARGUMENT,
752 _("Cannot specify nonce file when creating a server"));
760 port_num = strtol (port, NULL, 10);
762 resolver = g_resolver_get_default ();
763 resolved_addresses = g_resolver_lookup_by_name (resolver,
767 if (resolved_addresses == NULL)
770 /* TODO: handle family */
771 for (l = resolved_addresses; l != NULL; l = l->next)
773 GInetAddress *address = G_INET_ADDRESS (l->data);
774 GSocketAddress *socket_address;
775 GSocketAddress *effective_address;
777 socket_address = g_inet_socket_address_new (address, port_num);
778 if (!g_socket_listener_add_address (server->priv->listener,
780 G_SOCKET_TYPE_STREAM,
781 G_SOCKET_PROTOCOL_TCP,
782 NULL, /* GObject *source_object */
786 g_object_unref (socket_address);
790 /* make sure we allocate the same port number for other listeners */
791 port_num = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (effective_address));
793 g_object_unref (effective_address);
794 g_object_unref (socket_address);
802 gsize bytes_remaining;
804 server->priv->nonce = g_new0 (guchar, 16);
805 for (n = 0; n < 16; n++)
806 server->priv->nonce[n] = g_random_int_range (0, 256);
807 fd = g_file_open_tmp ("gdbus-nonce-file-XXXXXX",
808 &server->priv->nonce_file,
812 g_socket_listener_close (server->priv->listener);
817 bytes_remaining = 16;
818 while (bytes_remaining > 0)
821 ret = write (fd, server->priv->nonce + bytes_written, bytes_remaining);
828 g_io_error_from_errno (errno),
829 _("Error writing nonce file at `%s': %s"),
830 server->priv->nonce_file,
834 bytes_written += ret;
835 bytes_remaining -= ret;
838 server->priv->client_address = g_strdup_printf ("nonce-tcp:host=%s,port=%d,noncefile=%s",
841 server->priv->nonce_file);
845 server->priv->client_address = g_strdup_printf ("tcp:host=%s,port=%d", host, port_num);
847 server->priv->is_using_listener = TRUE;
851 g_list_foreach (resolved_addresses, (GFunc) g_object_unref, NULL);
852 g_list_free (resolved_addresses);
853 g_object_unref (resolver);
857 /* ---------------------------------------------------------------------------------------------------- */
862 GDBusConnection *connection;
866 emit_idle_data_free (EmitIdleData *data)
868 g_object_unref (data->server);
869 g_object_unref (data->connection);
874 emit_new_connection_in_idle (gpointer user_data)
876 EmitIdleData *data = user_data;
878 g_signal_emit (data->server,
879 _signals[NEW_CONNECTION_SIGNAL],
882 g_object_unref (data->connection);
887 /* Called in new thread */
889 on_run (GSocketService *service,
890 GSocketConnection *socket_connection,
891 GObject *source_object,
894 GDBusServer *server = G_DBUS_SERVER (user_data);
895 GDBusConnection *connection;
896 GDBusConnectionFlags connection_flags;
898 if (server->priv->nonce != NULL)
903 if (!g_input_stream_read_all (g_io_stream_get_input_stream (G_IO_STREAM (socket_connection)),
907 NULL, /* GCancellable */
911 if (bytes_read != 16)
914 if (memcmp (buf, server->priv->nonce, 16) != 0)
918 connection_flags = G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER;
919 if (server->priv->flags & G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS)
920 connection_flags |= G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS;
922 connection = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
925 server->priv->authentication_observer,
926 NULL, /* GCancellable */
928 if (connection == NULL)
931 if (server->priv->flags & G_DBUS_SERVER_FLAGS_RUN_IN_THREAD)
933 g_signal_emit (server,
934 _signals[NEW_CONNECTION_SIGNAL],
937 g_object_unref (connection);
941 GSource *idle_source;
944 data = g_new0 (EmitIdleData, 1);
945 data->server = g_object_ref (server);
946 data->connection = g_object_ref (connection);
948 idle_source = g_idle_source_new ();
949 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
950 g_source_set_callback (idle_source,
951 emit_new_connection_in_idle,
953 (GDestroyNotify) emit_idle_data_free);
954 g_source_attach (idle_source, server->priv->main_context_at_construction);
955 g_source_unref (idle_source);
963 initable_init (GInitable *initable,
964 GCancellable *cancellable,
967 GDBusServer *server = G_DBUS_SERVER (initable);
976 if (!g_dbus_is_guid (server->priv->guid))
978 g_set_error (&last_error,
980 G_IO_ERROR_INVALID_ARGUMENT,
981 _("The string `%s' is not a valid D-Bus GUID"),
986 server->priv->listener = G_SOCKET_LISTENER (g_threaded_socket_service_new (-1));
988 addr_array = g_strsplit (server->priv->address, ";", 0);
990 for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
992 const gchar *address_entry = addr_array[n];
993 GHashTable *key_value_pairs;
994 gchar *transport_name;
998 if (g_dbus_is_supported_address (address_entry,
1000 _g_dbus_address_parse_entry (address_entry,
1010 else if (g_strcmp0 (transport_name, "unix") == 0)
1011 ret = try_unix (server, address_entry, key_value_pairs, &this_error);
1013 else if (g_strcmp0 (transport_name, "tcp") == 0)
1014 ret = try_tcp (server, address_entry, key_value_pairs, FALSE, &this_error);
1015 else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
1016 ret = try_tcp (server, address_entry, key_value_pairs, TRUE, &this_error);
1018 g_set_error (&this_error,
1020 G_IO_ERROR_INVALID_ARGUMENT,
1021 _("Cannot listen on unsupported transport `%s'"),
1024 g_free (transport_name);
1025 if (key_value_pairs != NULL)
1026 g_hash_table_unref (key_value_pairs);
1030 g_assert (this_error == NULL);
1035 if (this_error != NULL)
1037 if (last_error != NULL)
1038 g_error_free (last_error);
1039 last_error = this_error;
1049 if (last_error != NULL)
1050 g_error_free (last_error);
1054 g_assert (last_error != NULL);
1055 g_propagate_error (error, last_error);
1062 initable_iface_init (GInitableIface *initable_iface)
1064 initable_iface->init = initable_init;
1067 /* ---------------------------------------------------------------------------------------------------- */
1069 #define __G_DBUS_SERVER_C__
1070 #include "gioaliasdef.c"