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>
37 #include "gdbusaddress.h"
38 #include "gdbusutils.h"
39 #include "gdbusconnection.h"
40 #include "gdbusserver.h"
41 #include "gioenumtypes.h"
42 #include "gdbusprivate.h"
43 #include "gdbusauthobserver.h"
44 #include "gio-marshal.h"
45 #include "ginitable.h"
46 #include "gsocketservice.h"
47 #include "gthreadedsocketservice.h"
48 #include "gresolver.h"
49 #include "ginetaddress.h"
50 #include "ginetsocketaddress.h"
51 #include "ginputstream.h"
52 #include "giostream.h"
55 #include "gunixsocketaddress.h"
62 * @short_description: Helper for accepting connections
65 * #GDBusServer is a helper for listening to and accepting D-Bus
68 * <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>
74 * The #GDBusServer structure contains only private data and
75 * should only be accessed using the provided API.
82 GObject parent_instance;
84 GDBusServerFlags flags;
91 gchar *client_address;
93 GSocketListener *listener;
94 gboolean is_using_listener;
96 /* The result of g_main_context_get_thread_default() when the object
97 * was created (the GObject _init() function) - this is used for delivery
98 * of the :new-connection GObject signal.
100 GMainContext *main_context_at_construction;
104 GDBusAuthObserver *authentication_observer;
107 typedef struct _GDBusServerClass GDBusServerClass;
111 * @new_connection: Signal class handler for the #GDBusServer::new-connection signal.
113 * Class structure for #GDBusServer.
117 struct _GDBusServerClass
120 GObjectClass parent_class;
124 void (*new_connection) (GDBusServer *server,
125 GDBusConnection *connection);
136 PROP_AUTHENTICATION_OBSERVER,
141 NEW_CONNECTION_SIGNAL,
145 guint _signals[LAST_SIGNAL] = {0};
147 static void initable_iface_init (GInitableIface *initable_iface);
149 G_DEFINE_TYPE_WITH_CODE (GDBusServer, g_dbus_server, G_TYPE_OBJECT,
150 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
154 g_dbus_server_finalize (GObject *object)
156 GDBusServer *server = G_DBUS_SERVER (object);
158 if (server->authentication_observer != NULL)
159 g_object_unref (server->authentication_observer);
161 if (server->listener != NULL)
162 g_object_unref (server->listener);
164 g_free (server->address);
165 g_free (server->guid);
166 g_free (server->client_address);
167 if (server->nonce != NULL)
169 memset (server->nonce, '\0', 16);
170 g_free (server->nonce);
172 /* we could unlink the nonce file but I don't
173 * think it's really worth the effort/risk
175 g_free (server->nonce_file);
177 if (server->main_context_at_construction != NULL)
178 g_main_context_unref (server->main_context_at_construction);
180 G_OBJECT_CLASS (g_dbus_server_parent_class)->finalize (object);
184 g_dbus_server_get_property (GObject *object,
189 GDBusServer *server = G_DBUS_SERVER (object);
194 g_value_set_flags (value, server->flags);
198 g_value_set_string (value, server->guid);
202 g_value_set_string (value, server->address);
205 case PROP_CLIENT_ADDRESS:
206 g_value_set_string (value, server->client_address);
210 g_value_set_boolean (value, server->active);
213 case PROP_AUTHENTICATION_OBSERVER:
214 g_value_set_object (value, server->authentication_observer);
218 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
224 g_dbus_server_set_property (GObject *object,
229 GDBusServer *server = G_DBUS_SERVER (object);
234 server->flags = g_value_get_flags (value);
238 server->guid = g_value_dup_string (value);
242 server->address = g_value_dup_string (value);
245 case PROP_AUTHENTICATION_OBSERVER:
246 server->authentication_observer = g_value_dup_object (value);
250 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
256 g_dbus_server_class_init (GDBusServerClass *klass)
258 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
260 gobject_class->finalize = g_dbus_server_finalize;
261 gobject_class->set_property = g_dbus_server_set_property;
262 gobject_class->get_property = g_dbus_server_get_property;
267 * Flags from the #GDBusServerFlags enumeration.
271 g_object_class_install_property (gobject_class,
273 g_param_spec_flags ("flags",
275 P_("Flags for the server"),
276 G_TYPE_DBUS_SERVER_FLAGS,
277 G_DBUS_SERVER_FLAGS_NONE,
280 G_PARAM_CONSTRUCT_ONLY |
281 G_PARAM_STATIC_NAME |
282 G_PARAM_STATIC_BLURB |
283 G_PARAM_STATIC_NICK));
288 * The guid of the server.
292 g_object_class_install_property (gobject_class,
294 g_param_spec_string ("guid",
296 P_("The guid of the server"),
300 G_PARAM_CONSTRUCT_ONLY |
301 G_PARAM_STATIC_NAME |
302 G_PARAM_STATIC_BLURB |
303 G_PARAM_STATIC_NICK));
306 * GDBusServer:address:
308 * The D-Bus address to listen on.
312 g_object_class_install_property (gobject_class,
314 g_param_spec_string ("address",
316 P_("The address to listen on"),
320 G_PARAM_CONSTRUCT_ONLY |
321 G_PARAM_STATIC_NAME |
322 G_PARAM_STATIC_BLURB |
323 G_PARAM_STATIC_NICK));
326 * GDBusServer:client-address:
328 * The D-Bus address that clients can use.
332 g_object_class_install_property (gobject_class,
334 g_param_spec_string ("client-address",
335 P_("Client Address"),
336 P_("The address clients can use"),
339 G_PARAM_STATIC_NAME |
340 G_PARAM_STATIC_BLURB |
341 G_PARAM_STATIC_NICK));
344 * GDBusServer:active:
346 * Whether the server is currently active.
350 g_object_class_install_property (gobject_class,
352 g_param_spec_string ("active",
354 P_("Whether the server is currently active"),
357 G_PARAM_STATIC_NAME |
358 G_PARAM_STATIC_BLURB |
359 G_PARAM_STATIC_NICK));
362 * GDBusServer:authentication-observer:
364 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
368 g_object_class_install_property (gobject_class,
369 PROP_AUTHENTICATION_OBSERVER,
370 g_param_spec_object ("authentication-observer",
371 P_("Authentication Observer"),
372 P_("Object used to assist in the authentication process"),
373 G_TYPE_DBUS_AUTH_OBSERVER,
376 G_PARAM_CONSTRUCT_ONLY |
377 G_PARAM_STATIC_NAME |
378 G_PARAM_STATIC_BLURB |
379 G_PARAM_STATIC_NICK));
382 * GDBusServer::new-connection:
383 * @server: The #GDBusServer emitting the signal.
384 * @connection: A #GDBusConnection for the new connection.
386 * Emitted when a new authenticated connection has been made. Use
387 * g_dbus_connection_get_peer_credentials() to figure out what
388 * identity (if any), was authenticated.
390 * If you want to accept the connection, simply ref the @connection
391 * object. Then call g_dbus_connection_close() and unref it when you
392 * are done with it. A typical thing to do when accepting a
393 * connection is to listen to the #GDBusConnection::closed signal.
395 * If #GDBusServer:flags contains %G_DBUS_SERVER_FLAGS_RUN_IN_THREAD
396 * then the signal is emitted in a new thread dedicated to the
397 * connection. Otherwise the signal is emitted in the <link
398 * linkend="g-main-context-push-thread-default">thread-default main
399 * loop</link> of the thread that @server was constructed in.
401 * You are guaranteed that signal handlers for this signal runs
402 * before incoming messages on @connection are processed. This means
403 * that it's suitable to call g_dbus_connection_register_object() or
404 * similar from the signal handler.
408 _signals[NEW_CONNECTION_SIGNAL] = g_signal_new ("new-connection",
411 G_STRUCT_OFFSET (GDBusServerClass, new_connection),
414 g_cclosure_marshal_VOID__OBJECT,
417 G_TYPE_DBUS_CONNECTION);
421 g_dbus_server_init (GDBusServer *server)
423 server->main_context_at_construction = g_main_context_get_thread_default ();
424 if (server->main_context_at_construction != NULL)
425 g_main_context_ref (server->main_context_at_construction);
429 on_run (GSocketService *service,
430 GSocketConnection *socket_connection,
431 GObject *source_object,
435 * g_dbus_server_new_sync:
436 * @address: A D-Bus address.
437 * @flags: Flags from the #GDBusServerFlags enumeration.
438 * @guid: A D-Bus GUID.
439 * @observer: A #GDBusAuthObserver or %NULL.
440 * @cancellable: A #GCancellable or %NULL.
441 * @error: Return location for server or %NULL.
443 * Creates a new D-Bus server that listens on the first address in
444 * @address that works.
446 * Once constructed, you can use g_dbus_server_get_client_address() to
447 * get a D-Bus address string that clients can use to connect.
449 * Connect to the #GDBusServer::new-connection signal to handle
450 * incoming connections.
452 * The returned #GDBusServer isn't active - you have to start it with
453 * g_dbus_server_start().
455 * See <xref linkend="gdbus-peer-to-peer"/> for how #GDBusServer can
458 * This is a synchronous failable constructor. See
459 * g_dbus_server_new() for the asynchronous version.
461 * Returns: A #GDBusServer or %NULL if @error is set. Free with
467 g_dbus_server_new_sync (const gchar *address,
468 GDBusServerFlags flags,
470 GDBusAuthObserver *observer,
471 GCancellable *cancellable,
476 g_return_val_if_fail (address != NULL, NULL);
477 g_return_val_if_fail (g_dbus_is_guid (guid), NULL);
478 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
480 server = g_initable_new (G_TYPE_DBUS_SERVER,
486 "authentication-observer", observer,
490 /* Right now we don't have any transport not using the listener... */
491 g_assert (server->is_using_listener);
492 g_signal_connect (G_SOCKET_SERVICE (server->listener),
502 * g_dbus_server_get_client_address:
503 * @server: A #GDBusServer.
505 * Gets a D-Bus address string that can be used by clients to connect
508 * Returns: A D-Bus address string. Do not free, the string is owned
514 g_dbus_server_get_client_address (GDBusServer *server)
516 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
517 return server->client_address;
521 * g_dbus_server_get_guid:
522 * @server: A #GDBusServer.
524 * Gets the GUID for @server.
526 * Returns: A D-Bus GUID. Do not free this string, it is owned by @server.
531 g_dbus_server_get_guid (GDBusServer *server)
533 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
538 * g_dbus_server_get_flags:
539 * @server: A #GDBusServer.
541 * Gets the flags for @server.
543 * Returns: A set of flags from the #GDBusServerFlags enumeration.
548 g_dbus_server_get_flags (GDBusServer *server)
550 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
551 return server->flags;
555 * g_dbus_server_is_active:
556 * @server: A #GDBusServer.
558 * Gets whether @server is active.
560 * Returns: %TRUE if server is active, %FALSE otherwise.
565 g_dbus_server_is_active (GDBusServer *server)
567 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
568 return server->active;
572 * g_dbus_server_start:
573 * @server: A #GDBusServer.
580 g_dbus_server_start (GDBusServer *server)
582 g_return_if_fail (G_IS_DBUS_SERVER (server));
585 /* Right now we don't have any transport not using the listener... */
586 g_assert (server->is_using_listener);
587 g_socket_service_start (G_SOCKET_SERVICE (server->listener));
588 server->active = TRUE;
589 g_object_notify (G_OBJECT (server), "active");
593 * g_dbus_server_stop:
594 * @server: A #GDBusServer.
601 g_dbus_server_stop (GDBusServer *server)
603 g_return_if_fail (G_IS_DBUS_SERVER (server));
606 /* Right now we don't have any transport not using the listener... */
607 g_assert (server->is_using_listener);
608 g_socket_service_stop (G_SOCKET_SERVICE (server->listener));
609 server->active = FALSE;
610 g_object_notify (G_OBJECT (server), "active");
613 /* ---------------------------------------------------------------------------------------------------- */
621 ret = g_random_int_range (0, 60);
631 /* note that address_entry has already been validated => exactly one of path, tmpdir or abstract keys are set */
633 try_unix (GDBusServer *server,
634 const gchar *address_entry,
635 GHashTable *key_value_pairs,
641 const gchar *abstract;
642 GSocketAddress *address;
647 path = g_hash_table_lookup (key_value_pairs, "path");
648 tmpdir = g_hash_table_lookup (key_value_pairs, "tmpdir");
649 abstract = g_hash_table_lookup (key_value_pairs, "abstract");
653 address = g_unix_socket_address_new (path);
655 else if (tmpdir != NULL)
662 s = g_string_new (tmpdir);
663 g_string_append (s, "/dbus-");
664 for (n = 0; n < 8; n++)
665 g_string_append_c (s, random_ascii ());
667 /* prefer abstract namespace if available */
668 if (g_unix_socket_address_abstract_names_supported ())
669 address = g_unix_socket_address_new_with_type (s->str,
671 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
673 address = g_unix_socket_address_new (s->str);
674 g_string_free (s, TRUE);
677 if (!g_socket_listener_add_address (server->listener,
679 G_SOCKET_TYPE_STREAM,
680 G_SOCKET_PROTOCOL_DEFAULT,
681 NULL, /* source_object */
682 NULL, /* effective_address */
685 if (local_error->domain == G_IO_ERROR && local_error->code == G_IO_ERROR_ADDRESS_IN_USE)
687 g_error_free (local_error);
690 g_propagate_error (error, local_error);
696 else if (abstract != NULL)
698 if (!g_unix_socket_address_abstract_names_supported ())
700 g_set_error_literal (error,
702 G_IO_ERROR_NOT_SUPPORTED,
703 _("Abstract name space not supported"));
706 address = g_unix_socket_address_new_with_type (abstract,
708 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
712 g_assert_not_reached ();
715 if (!g_socket_listener_add_address (server->listener,
717 G_SOCKET_TYPE_STREAM,
718 G_SOCKET_PROTOCOL_DEFAULT,
719 NULL, /* source_object */
720 NULL, /* effective_address */
730 /* Fill out client_address if the connection attempt worked */
733 server->is_using_listener = TRUE;
735 switch (g_unix_socket_address_get_address_type (G_UNIX_SOCKET_ADDRESS (address)))
737 case G_UNIX_SOCKET_ADDRESS_ABSTRACT:
738 server->client_address = g_strdup_printf ("unix:abstract=%s",
739 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
742 case G_UNIX_SOCKET_ADDRESS_PATH:
743 server->client_address = g_strdup_printf ("unix:path=%s",
744 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
748 g_assert_not_reached ();
752 g_object_unref (address);
758 /* ---------------------------------------------------------------------------------------------------- */
760 /* note that address_entry has already been validated =>
761 * both host and port (guranteed to be a number in [0, 65535]) are set (family is optional)
764 try_tcp (GDBusServer *server,
765 const gchar *address_entry,
766 GHashTable *key_value_pairs,
775 GSocketAddress *address;
777 GList *resolved_addresses;
783 resolved_addresses = NULL;
785 host = g_hash_table_lookup (key_value_pairs, "host");
786 port = g_hash_table_lookup (key_value_pairs, "port");
787 family = g_hash_table_lookup (key_value_pairs, "family");
788 if (g_hash_table_lookup (key_value_pairs, "noncefile") != NULL)
790 g_set_error_literal (error,
792 G_IO_ERROR_INVALID_ARGUMENT,
793 _("Cannot specify nonce file when creating a server"));
801 port_num = strtol (port, NULL, 10);
803 resolver = g_resolver_get_default ();
804 resolved_addresses = g_resolver_lookup_by_name (resolver,
808 if (resolved_addresses == NULL)
811 /* TODO: handle family */
812 for (l = resolved_addresses; l != NULL; l = l->next)
814 GInetAddress *address = G_INET_ADDRESS (l->data);
815 GSocketAddress *socket_address;
816 GSocketAddress *effective_address;
818 socket_address = g_inet_socket_address_new (address, port_num);
819 if (!g_socket_listener_add_address (server->listener,
821 G_SOCKET_TYPE_STREAM,
822 G_SOCKET_PROTOCOL_TCP,
823 NULL, /* GObject *source_object */
827 g_object_unref (socket_address);
831 /* make sure we allocate the same port number for other listeners */
832 port_num = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (effective_address));
834 g_object_unref (effective_address);
835 g_object_unref (socket_address);
843 gsize bytes_remaining;
845 server->nonce = g_new0 (guchar, 16);
846 for (n = 0; n < 16; n++)
847 server->nonce[n] = g_random_int_range (0, 256);
848 fd = g_file_open_tmp ("gdbus-nonce-file-XXXXXX",
853 g_socket_listener_close (server->listener);
858 bytes_remaining = 16;
859 while (bytes_remaining > 0)
862 ret = write (fd, server->nonce + bytes_written, bytes_remaining);
869 g_io_error_from_errno (errno),
870 _("Error writing nonce file at `%s': %s"),
875 bytes_written += ret;
876 bytes_remaining -= ret;
879 server->client_address = g_strdup_printf ("nonce-tcp:host=%s,port=%d,noncefile=%s",
886 server->client_address = g_strdup_printf ("tcp:host=%s,port=%d", host, port_num);
888 server->is_using_listener = TRUE;
892 g_list_foreach (resolved_addresses, (GFunc) g_object_unref, NULL);
893 g_list_free (resolved_addresses);
894 g_object_unref (resolver);
898 /* ---------------------------------------------------------------------------------------------------- */
903 GDBusConnection *connection;
907 emit_idle_data_free (EmitIdleData *data)
909 g_object_unref (data->server);
910 g_object_unref (data->connection);
915 emit_new_connection_in_idle (gpointer user_data)
917 EmitIdleData *data = user_data;
919 g_signal_emit (data->server,
920 _signals[NEW_CONNECTION_SIGNAL],
923 g_dbus_connection_start_message_processing (data->connection);
924 g_object_unref (data->connection);
929 /* Called in new thread */
931 on_run (GSocketService *service,
932 GSocketConnection *socket_connection,
933 GObject *source_object,
936 GDBusServer *server = G_DBUS_SERVER (user_data);
937 GDBusConnection *connection;
938 GDBusConnectionFlags connection_flags;
940 if (server->nonce != NULL)
945 if (!g_input_stream_read_all (g_io_stream_get_input_stream (G_IO_STREAM (socket_connection)),
949 NULL, /* GCancellable */
953 if (bytes_read != 16)
956 if (memcmp (buf, server->nonce, 16) != 0)
961 G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER |
962 G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING;
963 if (server->flags & G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS)
964 connection_flags |= G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS;
966 connection = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
969 server->authentication_observer,
970 NULL, /* GCancellable */
972 if (connection == NULL)
975 if (server->flags & G_DBUS_SERVER_FLAGS_RUN_IN_THREAD)
977 g_signal_emit (server,
978 _signals[NEW_CONNECTION_SIGNAL],
981 g_dbus_connection_start_message_processing (connection);
982 g_object_unref (connection);
986 GSource *idle_source;
989 data = g_new0 (EmitIdleData, 1);
990 data->server = g_object_ref (server);
991 data->connection = g_object_ref (connection);
993 idle_source = g_idle_source_new ();
994 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
995 g_source_set_callback (idle_source,
996 emit_new_connection_in_idle,
998 (GDestroyNotify) emit_idle_data_free);
999 g_source_attach (idle_source, server->main_context_at_construction);
1000 g_source_unref (idle_source);
1008 initable_init (GInitable *initable,
1009 GCancellable *cancellable,
1012 GDBusServer *server = G_DBUS_SERVER (initable);
1021 if (!g_dbus_is_guid (server->guid))
1023 g_set_error (&last_error,
1025 G_IO_ERROR_INVALID_ARGUMENT,
1026 _("The string `%s' is not a valid D-Bus GUID"),
1031 server->listener = G_SOCKET_LISTENER (g_threaded_socket_service_new (-1));
1033 addr_array = g_strsplit (server->address, ";", 0);
1035 for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
1037 const gchar *address_entry = addr_array[n];
1038 GHashTable *key_value_pairs;
1039 gchar *transport_name;
1043 if (g_dbus_is_supported_address (address_entry,
1045 _g_dbus_address_parse_entry (address_entry,
1055 else if (g_strcmp0 (transport_name, "unix") == 0)
1056 ret = try_unix (server, address_entry, key_value_pairs, &this_error);
1058 else if (g_strcmp0 (transport_name, "tcp") == 0)
1059 ret = try_tcp (server, address_entry, key_value_pairs, FALSE, &this_error);
1060 else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
1061 ret = try_tcp (server, address_entry, key_value_pairs, TRUE, &this_error);
1063 g_set_error (&this_error,
1065 G_IO_ERROR_INVALID_ARGUMENT,
1066 _("Cannot listen on unsupported transport `%s'"),
1069 g_free (transport_name);
1070 if (key_value_pairs != NULL)
1071 g_hash_table_unref (key_value_pairs);
1075 g_assert (this_error == NULL);
1080 if (this_error != NULL)
1082 if (last_error != NULL)
1083 g_error_free (last_error);
1084 last_error = this_error;
1094 if (last_error != NULL)
1095 g_error_free (last_error);
1099 g_assert (last_error != NULL);
1100 g_propagate_error (error, last_error);
1107 initable_iface_init (GInitableIface *initable_iface)
1109 initable_iface->init = initable_init;
1112 /* ---------------------------------------------------------------------------------------------------- */