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>
30 #include "gdbusaddress.h"
31 #include "gdbusutils.h"
32 #include "gdbusconnection.h"
33 #include "gdbusserver.h"
34 #include "gioenumtypes.h"
35 #include "gdbusprivate.h"
36 #include "gdbusauthobserver.h"
37 #include "gio-marshal.h"
38 #include "ginitable.h"
39 #include "gsocketservice.h"
43 #include "gunixsocketaddress.h"
51 * @short_description: Helper for accepting connections
54 * #GDBusServer is a helper for listening to and accepting D-Bus
57 * <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>
60 struct _GDBusServerPrivate
62 GDBusServerFlags flags;
69 gchar *client_address;
71 GSocketListener *listener;
72 gboolean is_using_listener;
74 /* The result of g_main_context_get_thread_default() when the object
75 * was created (the GObject _init() function) - this is used for delivery
76 * of the :new-connection GObject signal.
78 GMainContext *main_context_at_construction;
82 GDBusAuthObserver *authentication_observer;
93 PROP_AUTHENTICATION_OBSERVER,
98 NEW_CONNECTION_SIGNAL,
102 guint _signals[LAST_SIGNAL] = {0};
104 static void initable_iface_init (GInitableIface *initable_iface);
106 G_DEFINE_TYPE_WITH_CODE (GDBusServer, g_dbus_server, G_TYPE_OBJECT,
107 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
111 g_dbus_server_finalize (GObject *object)
113 GDBusServer *server = G_DBUS_SERVER (object);
115 if (server->priv->authentication_observer != NULL)
116 g_object_unref (server->priv->authentication_observer);
118 if (server->priv->listener != NULL)
119 g_object_unref (server->priv->listener);
121 g_free (server->priv->address);
122 g_free (server->priv->guid);
123 g_free (server->priv->client_address);
124 if (server->priv->nonce != NULL)
126 memset (server->priv->nonce, '\0', 16);
127 g_free (server->priv->nonce);
129 /* we could unlink the nonce file but I don't
130 * think it's really worth the effort/risk
132 g_free (server->priv->nonce_file);
134 if (server->priv->main_context_at_construction != NULL)
135 g_main_context_unref (server->priv->main_context_at_construction);
137 G_OBJECT_CLASS (g_dbus_server_parent_class)->finalize (object);
141 g_dbus_server_get_property (GObject *object,
146 GDBusServer *server = G_DBUS_SERVER (object);
151 g_value_set_flags (value, server->priv->flags);
155 g_value_set_string (value, server->priv->guid);
159 g_value_set_string (value, server->priv->address);
162 case PROP_CLIENT_ADDRESS:
163 g_value_set_string (value, server->priv->client_address);
167 g_value_set_boolean (value, server->priv->active);
170 case PROP_AUTHENTICATION_OBSERVER:
171 g_value_set_object (value, server->priv->authentication_observer);
175 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
181 g_dbus_server_set_property (GObject *object,
186 GDBusServer *server = G_DBUS_SERVER (object);
191 server->priv->flags = g_value_get_flags (value);
195 server->priv->guid = g_value_dup_string (value);
199 server->priv->address = g_value_dup_string (value);
202 case PROP_AUTHENTICATION_OBSERVER:
203 server->priv->authentication_observer = g_value_dup_object (value);
207 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
213 g_dbus_server_class_init (GDBusServerClass *klass)
215 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
217 gobject_class->finalize = g_dbus_server_finalize;
218 gobject_class->set_property = g_dbus_server_set_property;
219 gobject_class->get_property = g_dbus_server_get_property;
224 * Flags from the #GDBusServerFlags enumeration.
228 g_object_class_install_property (gobject_class,
230 g_param_spec_flags ("flags",
232 P_("Flags for the server"),
233 G_TYPE_DBUS_SERVER_FLAGS,
234 G_DBUS_SERVER_FLAGS_NONE,
237 G_PARAM_CONSTRUCT_ONLY |
238 G_PARAM_STATIC_NAME |
239 G_PARAM_STATIC_BLURB |
240 G_PARAM_STATIC_NICK));
245 * The guid of the server.
249 g_object_class_install_property (gobject_class,
251 g_param_spec_string ("guid",
253 P_("The guid of the server"),
257 G_PARAM_CONSTRUCT_ONLY |
258 G_PARAM_STATIC_NAME |
259 G_PARAM_STATIC_BLURB |
260 G_PARAM_STATIC_NICK));
263 * GDBusServer:address:
265 * The D-Bus address to listen on.
269 g_object_class_install_property (gobject_class,
271 g_param_spec_string ("address",
273 P_("The address to listen on"),
277 G_PARAM_CONSTRUCT_ONLY |
278 G_PARAM_STATIC_NAME |
279 G_PARAM_STATIC_BLURB |
280 G_PARAM_STATIC_NICK));
283 * GDBusServer:client-address:
285 * The D-Bus address that clients can use.
289 g_object_class_install_property (gobject_class,
291 g_param_spec_string ("client-address",
292 P_("Client Address"),
293 P_("The address clients can use"),
296 G_PARAM_STATIC_NAME |
297 G_PARAM_STATIC_BLURB |
298 G_PARAM_STATIC_NICK));
301 * GDBusServer:active:
303 * Whether the server is currently active.
307 g_object_class_install_property (gobject_class,
309 g_param_spec_string ("active",
311 P_("Whether the server is currently active"),
314 G_PARAM_STATIC_NAME |
315 G_PARAM_STATIC_BLURB |
316 G_PARAM_STATIC_NICK));
319 * GDBusServer:authentication-observer:
321 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
325 g_object_class_install_property (gobject_class,
326 PROP_AUTHENTICATION_OBSERVER,
327 g_param_spec_object ("authentication-observer",
328 P_("Authentication Observer"),
329 P_("Object used to assist in the authentication process"),
330 G_TYPE_DBUS_AUTH_OBSERVER,
333 G_PARAM_CONSTRUCT_ONLY |
334 G_PARAM_STATIC_NAME |
335 G_PARAM_STATIC_BLURB |
336 G_PARAM_STATIC_NICK));
339 * GDBusServer::new-connection:
340 * @server: The #GDBusServer emitting the signal.
341 * @connection: A #GDBusConnection for the new connection.
343 * Emitted when a new authenticated connection has been made. Use
344 * g_dbus_connection_get_peer_credentials() to figure out what
345 * identity (if any), was authenticated.
347 * If you want to accept the connection, simply ref the @connection
348 * object. Then call g_dbus_connection_close() and unref it when you
349 * are done with it. A typical thing to do when accepting a
350 * connection is to listen to the #GDBusConnection::closed signal.
352 * If #GDBusServer:flags contains %G_DBUS_SERVER_FLAGS_RUN_IN_THREAD
353 * then the signal is emitted in a new thread dedicated to the
354 * connection. Otherwise the signal is emitted in the <link
355 * linkend="g-main-context-push-thread-default">thread-default main
356 * loop</link> of the thread that @server was constructed in.
360 _signals[NEW_CONNECTION_SIGNAL] = g_signal_new ("new-connection",
363 G_STRUCT_OFFSET (GDBusServerClass, new_connection),
366 g_cclosure_marshal_VOID__OBJECT,
369 G_TYPE_DBUS_CONNECTION);
372 g_type_class_add_private (klass, sizeof (GDBusServerPrivate));
376 g_dbus_server_init (GDBusServer *server)
378 server->priv = G_TYPE_INSTANCE_GET_PRIVATE (server, G_TYPE_DBUS_SERVER, GDBusServerPrivate);
380 server->priv->main_context_at_construction = g_main_context_get_thread_default ();
381 if (server->priv->main_context_at_construction != NULL)
382 g_main_context_ref (server->priv->main_context_at_construction);
386 on_run (GSocketService *service,
387 GSocketConnection *socket_connection,
388 GObject *source_object,
392 * g_dbus_server_new_sync:
393 * @address: A D-Bus address.
394 * @flags: Flags from the #GDBusServerFlags enumeration.
395 * @guid: A D-Bus GUID.
396 * @observer: A #GDBusAuthObserver or %NULL.
397 * @cancellable: A #GCancellable or %NULL.
398 * @error: Return location for server or %NULL.
400 * Creates a new D-Bus server that listens on the first address in
401 * @address that works.
403 * Once constructed, you can use g_dbus_server_get_client_address() to
404 * get a D-Bus address string that clients can use to connect.
406 * Connect to the #GDBusServer::new-connection signal to handle
407 * incoming connections.
409 * The returned #GDBusServer isn't active - you have to start it with
410 * g_dbus_server_start().
412 * See <xref linkend="gdbus-peer-to-peer"/> for how #GDBusServer can
415 * This is a synchronous failable constructor. See
416 * g_dbus_server_new() for the asynchronous version.
418 * Returns: A #GDBusServer or %NULL if @error is set. Free with
424 g_dbus_server_new_sync (const gchar *address,
425 GDBusServerFlags flags,
427 GDBusAuthObserver *observer,
428 GCancellable *cancellable,
433 g_return_val_if_fail (address != NULL, NULL);
434 g_return_val_if_fail (g_dbus_is_guid (guid), NULL);
435 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
437 server = g_initable_new (G_TYPE_DBUS_SERVER,
443 "authentication-observer", observer,
447 /* Right now we don't have any transport not using the listener... */
448 g_assert (server->priv->is_using_listener);
449 g_signal_connect (G_SOCKET_SERVICE (server->priv->listener),
459 * g_dbus_server_get_client_address:
460 * @server: A #GDBusServer.
462 * Gets a D-Bus address string that can be used by clients to connect
465 * Returns: A D-Bus address string. Do not free, the string is owned
471 g_dbus_server_get_client_address (GDBusServer *server)
473 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
474 return server->priv->client_address;
478 * g_dbus_server_get_guid:
479 * @server: A #GDBusServer.
481 * Gets the GUID for @server.
483 * Returns: A D-Bus GUID. Do not free this string, it is owned by @server.
488 g_dbus_server_get_guid (GDBusServer *server)
490 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
491 return server->priv->guid;
495 * g_dbus_server_get_flags:
496 * @server: A #GDBusServer.
498 * Gets the flags for @server.
500 * Returns: A set of flags from the #GDBusServerFlags enumeration.
505 g_dbus_server_get_flags (GDBusServer *server)
507 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
508 return server->priv->flags;
512 * g_dbus_server_is_active:
513 * @server: A #GDBusServer.
515 * Gets whether @server is active.
517 * Returns: %TRUE if server is active, %FALSE otherwise.
522 g_dbus_server_is_active (GDBusServer *server)
524 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
525 return server->priv->active;
529 * g_dbus_server_start:
530 * @server: A #GDBusServer.
537 g_dbus_server_start (GDBusServer *server)
539 g_return_if_fail (G_IS_DBUS_SERVER (server));
540 if (server->priv->active)
542 /* Right now we don't have any transport not using the listener... */
543 g_assert (server->priv->is_using_listener);
544 g_socket_service_start (G_SOCKET_SERVICE (server->priv->listener));
545 server->priv->active = TRUE;
546 g_object_notify (G_OBJECT (server), "active");
550 * g_dbus_server_stop:
551 * @server: A #GDBusServer.
558 g_dbus_server_stop (GDBusServer *server)
560 g_return_if_fail (G_IS_DBUS_SERVER (server));
561 if (!server->priv->active)
563 /* Right now we don't have any transport not using the listener... */
564 g_assert (server->priv->is_using_listener);
565 g_socket_service_stop (G_SOCKET_SERVICE (server->priv->listener));
566 server->priv->active = FALSE;
567 g_object_notify (G_OBJECT (server), "active");
570 /* ---------------------------------------------------------------------------------------------------- */
578 ret = g_random_int_range (0, 60);
588 /* note that address_entry has already been validated => exactly one of path, tmpdir or abstract keys are set */
590 try_unix (GDBusServer *server,
591 const gchar *address_entry,
592 GHashTable *key_value_pairs,
598 const gchar *abstract;
599 GSocketAddress *address;
604 path = g_hash_table_lookup (key_value_pairs, "path");
605 tmpdir = g_hash_table_lookup (key_value_pairs, "tmpdir");
606 abstract = g_hash_table_lookup (key_value_pairs, "abstract");
610 address = g_unix_socket_address_new (path);
612 else if (tmpdir != NULL)
619 s = g_string_new (tmpdir);
620 g_string_append (s, "/dbus-");
621 for (n = 0; n < 8; n++)
622 g_string_append_c (s, random_ascii ());
624 /* prefer abstract namespace if available */
625 if (g_unix_socket_address_abstract_names_supported ())
626 address = g_unix_socket_address_new_with_type (s->str,
628 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
630 address = g_unix_socket_address_new (s->str);
631 g_string_free (s, TRUE);
634 if (!g_socket_listener_add_address (server->priv->listener,
636 G_SOCKET_TYPE_STREAM,
637 G_SOCKET_PROTOCOL_DEFAULT,
638 NULL, /* source_object */
639 NULL, /* effective_address */
642 if (local_error->domain == G_IO_ERROR && local_error->code == G_IO_ERROR_ADDRESS_IN_USE)
644 g_error_free (local_error);
647 g_propagate_error (error, local_error);
653 else if (abstract != NULL)
655 if (!g_unix_socket_address_abstract_names_supported ())
657 g_set_error_literal (error,
659 G_IO_ERROR_NOT_SUPPORTED,
660 _("Abstract name space not supported"));
663 address = g_unix_socket_address_new_with_type (abstract,
665 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
669 g_assert_not_reached ();
672 if (!g_socket_listener_add_address (server->priv->listener,
674 G_SOCKET_TYPE_STREAM,
675 G_SOCKET_PROTOCOL_DEFAULT,
676 NULL, /* source_object */
677 NULL, /* effective_address */
687 /* Fill out client_address if the connection attempt worked */
690 server->priv->is_using_listener = TRUE;
692 switch (g_unix_socket_address_get_address_type (G_UNIX_SOCKET_ADDRESS (address)))
694 case G_UNIX_SOCKET_ADDRESS_ABSTRACT:
695 server->priv->client_address = g_strdup_printf ("unix:abstract=%s",
696 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
699 case G_UNIX_SOCKET_ADDRESS_PATH:
700 server->priv->client_address = g_strdup_printf ("unix:path=%s",
701 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
705 g_assert_not_reached ();
709 g_object_unref (address);
715 /* ---------------------------------------------------------------------------------------------------- */
717 /* note that address_entry has already been validated =>
718 * both host and port (guranteed to be a number in [0, 65535]) are set (family is optional)
721 try_tcp (GDBusServer *server,
722 const gchar *address_entry,
723 GHashTable *key_value_pairs,
732 GSocketAddress *address;
734 GList *resolved_addresses;
740 resolved_addresses = NULL;
742 host = g_hash_table_lookup (key_value_pairs, "host");
743 port = g_hash_table_lookup (key_value_pairs, "port");
744 family = g_hash_table_lookup (key_value_pairs, "family");
745 if (g_hash_table_lookup (key_value_pairs, "noncefile") != NULL)
747 g_set_error_literal (error,
749 G_IO_ERROR_INVALID_ARGUMENT,
750 _("Cannot specify nonce file when creating a server"));
758 port_num = strtol (port, NULL, 10);
760 resolver = g_resolver_get_default ();
761 resolved_addresses = g_resolver_lookup_by_name (resolver,
765 if (resolved_addresses == NULL)
768 /* TODO: handle family */
769 for (l = resolved_addresses; l != NULL; l = l->next)
771 GInetAddress *address = G_INET_ADDRESS (l->data);
772 GSocketAddress *socket_address;
773 GSocketAddress *effective_address;
775 socket_address = g_inet_socket_address_new (address, port_num);
776 if (!g_socket_listener_add_address (server->priv->listener,
778 G_SOCKET_TYPE_STREAM,
779 G_SOCKET_PROTOCOL_TCP,
780 NULL, /* GObject *source_object */
784 g_object_unref (socket_address);
788 /* make sure we allocate the same port number for other listeners */
789 port_num = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (effective_address));
791 g_object_unref (effective_address);
792 g_object_unref (socket_address);
800 gsize bytes_remaining;
802 server->priv->nonce = g_new0 (guchar, 16);
803 for (n = 0; n < 16; n++)
804 server->priv->nonce[n] = g_random_int_range (0, 256);
805 fd = g_file_open_tmp ("gdbus-nonce-file-XXXXXX",
806 &server->priv->nonce_file,
810 g_socket_listener_close (server->priv->listener);
815 bytes_remaining = 16;
816 while (bytes_remaining > 0)
819 ret = write (fd, server->priv->nonce + bytes_written, bytes_remaining);
826 g_io_error_from_errno (errno),
827 _("Error writing nonce file at `%s': %s"),
828 server->priv->nonce_file,
832 bytes_written += ret;
833 bytes_remaining -= ret;
836 server->priv->client_address = g_strdup_printf ("nonce-tcp:host=%s,port=%d,noncefile=%s",
839 server->priv->nonce_file);
843 server->priv->client_address = g_strdup_printf ("tcp:host=%s,port=%d", host, port_num);
845 server->priv->is_using_listener = TRUE;
849 g_list_foreach (resolved_addresses, (GFunc) g_object_unref, NULL);
850 g_list_free (resolved_addresses);
851 g_object_unref (resolver);
855 /* ---------------------------------------------------------------------------------------------------- */
860 GDBusConnection *connection;
864 emit_idle_data_free (EmitIdleData *data)
866 g_object_unref (data->server);
867 g_object_unref (data->connection);
872 emit_new_connection_in_idle (gpointer user_data)
874 EmitIdleData *data = user_data;
876 g_signal_emit (data->server,
877 _signals[NEW_CONNECTION_SIGNAL],
880 g_object_unref (data->connection);
885 /* Called in new thread */
887 on_run (GSocketService *service,
888 GSocketConnection *socket_connection,
889 GObject *source_object,
892 GDBusServer *server = G_DBUS_SERVER (user_data);
893 GDBusConnection *connection;
894 GDBusConnectionFlags connection_flags;
896 if (server->priv->nonce != NULL)
901 if (!g_input_stream_read_all (g_io_stream_get_input_stream (G_IO_STREAM (socket_connection)),
905 NULL, /* GCancellable */
909 if (bytes_read != 16)
912 if (memcmp (buf, server->priv->nonce, 16) != 0)
916 connection_flags = G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER;
917 if (server->priv->flags & G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS)
918 connection_flags |= G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS;
920 connection = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
923 server->priv->authentication_observer,
924 NULL, /* GCancellable */
926 if (connection == NULL)
929 if (server->priv->flags & G_DBUS_SERVER_FLAGS_RUN_IN_THREAD)
931 g_signal_emit (server,
932 _signals[NEW_CONNECTION_SIGNAL],
935 g_object_unref (connection);
939 GSource *idle_source;
942 data = g_new0 (EmitIdleData, 1);
943 data->server = g_object_ref (server);
944 data->connection = g_object_ref (connection);
946 idle_source = g_idle_source_new ();
947 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
948 g_source_set_callback (idle_source,
949 emit_new_connection_in_idle,
951 (GDestroyNotify) emit_idle_data_free);
952 g_source_attach (idle_source, server->priv->main_context_at_construction);
953 g_source_unref (idle_source);
961 initable_init (GInitable *initable,
962 GCancellable *cancellable,
965 GDBusServer *server = G_DBUS_SERVER (initable);
974 if (!g_dbus_is_guid (server->priv->guid))
976 g_set_error (&last_error,
978 G_IO_ERROR_INVALID_ARGUMENT,
979 _("The string `%s' is not a valid D-Bus GUID"),
984 server->priv->listener = G_SOCKET_LISTENER (g_threaded_socket_service_new (-1));
986 addr_array = g_strsplit (server->priv->address, ";", 0);
988 for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
990 const gchar *address_entry = addr_array[n];
991 GHashTable *key_value_pairs;
992 gchar *transport_name;
996 if (g_dbus_is_supported_address (address_entry,
998 _g_dbus_address_parse_entry (address_entry,
1008 else if (g_strcmp0 (transport_name, "unix") == 0)
1009 ret = try_unix (server, address_entry, key_value_pairs, &this_error);
1011 else if (g_strcmp0 (transport_name, "tcp") == 0)
1012 ret = try_tcp (server, address_entry, key_value_pairs, FALSE, &this_error);
1013 else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
1014 ret = try_tcp (server, address_entry, key_value_pairs, TRUE, &this_error);
1016 g_set_error (&this_error,
1018 G_IO_ERROR_INVALID_ARGUMENT,
1019 _("Cannot listen on unsupported transport `%s'"),
1022 g_free (transport_name);
1023 if (key_value_pairs != NULL)
1024 g_hash_table_unref (key_value_pairs);
1028 g_assert (this_error == NULL);
1033 if (this_error != NULL)
1035 if (last_error != NULL)
1036 g_error_free (last_error);
1037 last_error = this_error;
1047 if (last_error != NULL)
1048 g_error_free (last_error);
1052 g_assert (last_error != NULL);
1053 g_propagate_error (error, last_error);
1060 initable_iface_init (GInitableIface *initable_iface)
1062 initable_iface->init = initable_init;
1065 /* ---------------------------------------------------------------------------------------------------- */
1067 #define __G_DBUS_SERVER_C__
1068 #include "gioaliasdef.c"