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"
63 * @short_description: Helper for accepting connections
66 * #GDBusServer is a helper for listening to and accepting D-Bus
69 * <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>
72 struct _GDBusServerPrivate
74 GDBusServerFlags flags;
81 gchar *client_address;
83 GSocketListener *listener;
84 gboolean is_using_listener;
86 /* The result of g_main_context_get_thread_default() when the object
87 * was created (the GObject _init() function) - this is used for delivery
88 * of the :new-connection GObject signal.
90 GMainContext *main_context_at_construction;
94 GDBusAuthObserver *authentication_observer;
105 PROP_AUTHENTICATION_OBSERVER,
110 NEW_CONNECTION_SIGNAL,
114 guint _signals[LAST_SIGNAL] = {0};
116 static void initable_iface_init (GInitableIface *initable_iface);
118 G_DEFINE_TYPE_WITH_CODE (GDBusServer, g_dbus_server, G_TYPE_OBJECT,
119 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
123 g_dbus_server_finalize (GObject *object)
125 GDBusServer *server = G_DBUS_SERVER (object);
127 if (server->priv->authentication_observer != NULL)
128 g_object_unref (server->priv->authentication_observer);
130 if (server->priv->listener != NULL)
131 g_object_unref (server->priv->listener);
133 g_free (server->priv->address);
134 g_free (server->priv->guid);
135 g_free (server->priv->client_address);
136 if (server->priv->nonce != NULL)
138 memset (server->priv->nonce, '\0', 16);
139 g_free (server->priv->nonce);
141 /* we could unlink the nonce file but I don't
142 * think it's really worth the effort/risk
144 g_free (server->priv->nonce_file);
146 if (server->priv->main_context_at_construction != NULL)
147 g_main_context_unref (server->priv->main_context_at_construction);
149 G_OBJECT_CLASS (g_dbus_server_parent_class)->finalize (object);
153 g_dbus_server_get_property (GObject *object,
158 GDBusServer *server = G_DBUS_SERVER (object);
163 g_value_set_flags (value, server->priv->flags);
167 g_value_set_string (value, server->priv->guid);
171 g_value_set_string (value, server->priv->address);
174 case PROP_CLIENT_ADDRESS:
175 g_value_set_string (value, server->priv->client_address);
179 g_value_set_boolean (value, server->priv->active);
182 case PROP_AUTHENTICATION_OBSERVER:
183 g_value_set_object (value, server->priv->authentication_observer);
187 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
193 g_dbus_server_set_property (GObject *object,
198 GDBusServer *server = G_DBUS_SERVER (object);
203 server->priv->flags = g_value_get_flags (value);
207 server->priv->guid = g_value_dup_string (value);
211 server->priv->address = g_value_dup_string (value);
214 case PROP_AUTHENTICATION_OBSERVER:
215 server->priv->authentication_observer = g_value_dup_object (value);
219 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
225 g_dbus_server_class_init (GDBusServerClass *klass)
227 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
229 gobject_class->finalize = g_dbus_server_finalize;
230 gobject_class->set_property = g_dbus_server_set_property;
231 gobject_class->get_property = g_dbus_server_get_property;
236 * Flags from the #GDBusServerFlags enumeration.
240 g_object_class_install_property (gobject_class,
242 g_param_spec_flags ("flags",
244 P_("Flags for the server"),
245 G_TYPE_DBUS_SERVER_FLAGS,
246 G_DBUS_SERVER_FLAGS_NONE,
249 G_PARAM_CONSTRUCT_ONLY |
250 G_PARAM_STATIC_NAME |
251 G_PARAM_STATIC_BLURB |
252 G_PARAM_STATIC_NICK));
257 * The guid of the server.
261 g_object_class_install_property (gobject_class,
263 g_param_spec_string ("guid",
265 P_("The guid of the server"),
269 G_PARAM_CONSTRUCT_ONLY |
270 G_PARAM_STATIC_NAME |
271 G_PARAM_STATIC_BLURB |
272 G_PARAM_STATIC_NICK));
275 * GDBusServer:address:
277 * The D-Bus address to listen on.
281 g_object_class_install_property (gobject_class,
283 g_param_spec_string ("address",
285 P_("The address to listen on"),
289 G_PARAM_CONSTRUCT_ONLY |
290 G_PARAM_STATIC_NAME |
291 G_PARAM_STATIC_BLURB |
292 G_PARAM_STATIC_NICK));
295 * GDBusServer:client-address:
297 * The D-Bus address that clients can use.
301 g_object_class_install_property (gobject_class,
303 g_param_spec_string ("client-address",
304 P_("Client Address"),
305 P_("The address clients can use"),
308 G_PARAM_STATIC_NAME |
309 G_PARAM_STATIC_BLURB |
310 G_PARAM_STATIC_NICK));
313 * GDBusServer:active:
315 * Whether the server is currently active.
319 g_object_class_install_property (gobject_class,
321 g_param_spec_string ("active",
323 P_("Whether the server is currently active"),
326 G_PARAM_STATIC_NAME |
327 G_PARAM_STATIC_BLURB |
328 G_PARAM_STATIC_NICK));
331 * GDBusServer:authentication-observer:
333 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
337 g_object_class_install_property (gobject_class,
338 PROP_AUTHENTICATION_OBSERVER,
339 g_param_spec_object ("authentication-observer",
340 P_("Authentication Observer"),
341 P_("Object used to assist in the authentication process"),
342 G_TYPE_DBUS_AUTH_OBSERVER,
345 G_PARAM_CONSTRUCT_ONLY |
346 G_PARAM_STATIC_NAME |
347 G_PARAM_STATIC_BLURB |
348 G_PARAM_STATIC_NICK));
351 * GDBusServer::new-connection:
352 * @server: The #GDBusServer emitting the signal.
353 * @connection: A #GDBusConnection for the new connection.
355 * Emitted when a new authenticated connection has been made. Use
356 * g_dbus_connection_get_peer_credentials() to figure out what
357 * identity (if any), was authenticated.
359 * If you want to accept the connection, simply ref the @connection
360 * object. Then call g_dbus_connection_close() and unref it when you
361 * are done with it. A typical thing to do when accepting a
362 * connection is to listen to the #GDBusConnection::closed signal.
364 * If #GDBusServer:flags contains %G_DBUS_SERVER_FLAGS_RUN_IN_THREAD
365 * then the signal is emitted in a new thread dedicated to the
366 * connection. Otherwise the signal is emitted in the <link
367 * linkend="g-main-context-push-thread-default">thread-default main
368 * loop</link> of the thread that @server was constructed in.
372 _signals[NEW_CONNECTION_SIGNAL] = g_signal_new ("new-connection",
375 G_STRUCT_OFFSET (GDBusServerClass, new_connection),
378 g_cclosure_marshal_VOID__OBJECT,
381 G_TYPE_DBUS_CONNECTION);
384 g_type_class_add_private (klass, sizeof (GDBusServerPrivate));
388 g_dbus_server_init (GDBusServer *server)
390 server->priv = G_TYPE_INSTANCE_GET_PRIVATE (server, G_TYPE_DBUS_SERVER, GDBusServerPrivate);
392 server->priv->main_context_at_construction = g_main_context_get_thread_default ();
393 if (server->priv->main_context_at_construction != NULL)
394 g_main_context_ref (server->priv->main_context_at_construction);
398 on_run (GSocketService *service,
399 GSocketConnection *socket_connection,
400 GObject *source_object,
404 * g_dbus_server_new_sync:
405 * @address: A D-Bus address.
406 * @flags: Flags from the #GDBusServerFlags enumeration.
407 * @guid: A D-Bus GUID.
408 * @observer: A #GDBusAuthObserver or %NULL.
409 * @cancellable: A #GCancellable or %NULL.
410 * @error: Return location for server or %NULL.
412 * Creates a new D-Bus server that listens on the first address in
413 * @address that works.
415 * Once constructed, you can use g_dbus_server_get_client_address() to
416 * get a D-Bus address string that clients can use to connect.
418 * Connect to the #GDBusServer::new-connection signal to handle
419 * incoming connections.
421 * The returned #GDBusServer isn't active - you have to start it with
422 * g_dbus_server_start().
424 * See <xref linkend="gdbus-peer-to-peer"/> for how #GDBusServer can
427 * This is a synchronous failable constructor. See
428 * g_dbus_server_new() for the asynchronous version.
430 * Returns: A #GDBusServer or %NULL if @error is set. Free with
436 g_dbus_server_new_sync (const gchar *address,
437 GDBusServerFlags flags,
439 GDBusAuthObserver *observer,
440 GCancellable *cancellable,
445 g_return_val_if_fail (address != NULL, NULL);
446 g_return_val_if_fail (g_dbus_is_guid (guid), NULL);
447 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
449 server = g_initable_new (G_TYPE_DBUS_SERVER,
455 "authentication-observer", observer,
459 /* Right now we don't have any transport not using the listener... */
460 g_assert (server->priv->is_using_listener);
461 g_signal_connect (G_SOCKET_SERVICE (server->priv->listener),
471 * g_dbus_server_get_client_address:
472 * @server: A #GDBusServer.
474 * Gets a D-Bus address string that can be used by clients to connect
477 * Returns: A D-Bus address string. Do not free, the string is owned
483 g_dbus_server_get_client_address (GDBusServer *server)
485 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
486 return server->priv->client_address;
490 * g_dbus_server_get_guid:
491 * @server: A #GDBusServer.
493 * Gets the GUID for @server.
495 * Returns: A D-Bus GUID. Do not free this string, it is owned by @server.
500 g_dbus_server_get_guid (GDBusServer *server)
502 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
503 return server->priv->guid;
507 * g_dbus_server_get_flags:
508 * @server: A #GDBusServer.
510 * Gets the flags for @server.
512 * Returns: A set of flags from the #GDBusServerFlags enumeration.
517 g_dbus_server_get_flags (GDBusServer *server)
519 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
520 return server->priv->flags;
524 * g_dbus_server_is_active:
525 * @server: A #GDBusServer.
527 * Gets whether @server is active.
529 * Returns: %TRUE if server is active, %FALSE otherwise.
534 g_dbus_server_is_active (GDBusServer *server)
536 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
537 return server->priv->active;
541 * g_dbus_server_start:
542 * @server: A #GDBusServer.
549 g_dbus_server_start (GDBusServer *server)
551 g_return_if_fail (G_IS_DBUS_SERVER (server));
552 if (server->priv->active)
554 /* Right now we don't have any transport not using the listener... */
555 g_assert (server->priv->is_using_listener);
556 g_socket_service_start (G_SOCKET_SERVICE (server->priv->listener));
557 server->priv->active = TRUE;
558 g_object_notify (G_OBJECT (server), "active");
562 * g_dbus_server_stop:
563 * @server: A #GDBusServer.
570 g_dbus_server_stop (GDBusServer *server)
572 g_return_if_fail (G_IS_DBUS_SERVER (server));
573 if (!server->priv->active)
575 /* Right now we don't have any transport not using the listener... */
576 g_assert (server->priv->is_using_listener);
577 g_socket_service_stop (G_SOCKET_SERVICE (server->priv->listener));
578 server->priv->active = FALSE;
579 g_object_notify (G_OBJECT (server), "active");
582 /* ---------------------------------------------------------------------------------------------------- */
590 ret = g_random_int_range (0, 60);
600 /* note that address_entry has already been validated => exactly one of path, tmpdir or abstract keys are set */
602 try_unix (GDBusServer *server,
603 const gchar *address_entry,
604 GHashTable *key_value_pairs,
610 const gchar *abstract;
611 GSocketAddress *address;
616 path = g_hash_table_lookup (key_value_pairs, "path");
617 tmpdir = g_hash_table_lookup (key_value_pairs, "tmpdir");
618 abstract = g_hash_table_lookup (key_value_pairs, "abstract");
622 address = g_unix_socket_address_new (path);
624 else if (tmpdir != NULL)
631 s = g_string_new (tmpdir);
632 g_string_append (s, "/dbus-");
633 for (n = 0; n < 8; n++)
634 g_string_append_c (s, random_ascii ());
636 /* prefer abstract namespace if available */
637 if (g_unix_socket_address_abstract_names_supported ())
638 address = g_unix_socket_address_new_with_type (s->str,
640 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
642 address = g_unix_socket_address_new (s->str);
643 g_string_free (s, TRUE);
646 if (!g_socket_listener_add_address (server->priv->listener,
648 G_SOCKET_TYPE_STREAM,
649 G_SOCKET_PROTOCOL_DEFAULT,
650 NULL, /* source_object */
651 NULL, /* effective_address */
654 if (local_error->domain == G_IO_ERROR && local_error->code == G_IO_ERROR_ADDRESS_IN_USE)
656 g_error_free (local_error);
659 g_propagate_error (error, local_error);
665 else if (abstract != NULL)
667 if (!g_unix_socket_address_abstract_names_supported ())
669 g_set_error_literal (error,
671 G_IO_ERROR_NOT_SUPPORTED,
672 _("Abstract name space not supported"));
675 address = g_unix_socket_address_new_with_type (abstract,
677 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
681 g_assert_not_reached ();
684 if (!g_socket_listener_add_address (server->priv->listener,
686 G_SOCKET_TYPE_STREAM,
687 G_SOCKET_PROTOCOL_DEFAULT,
688 NULL, /* source_object */
689 NULL, /* effective_address */
699 /* Fill out client_address if the connection attempt worked */
702 server->priv->is_using_listener = TRUE;
704 switch (g_unix_socket_address_get_address_type (G_UNIX_SOCKET_ADDRESS (address)))
706 case G_UNIX_SOCKET_ADDRESS_ABSTRACT:
707 server->priv->client_address = g_strdup_printf ("unix:abstract=%s",
708 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
711 case G_UNIX_SOCKET_ADDRESS_PATH:
712 server->priv->client_address = g_strdup_printf ("unix:path=%s",
713 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
717 g_assert_not_reached ();
721 g_object_unref (address);
727 /* ---------------------------------------------------------------------------------------------------- */
729 /* note that address_entry has already been validated =>
730 * both host and port (guranteed to be a number in [0, 65535]) are set (family is optional)
733 try_tcp (GDBusServer *server,
734 const gchar *address_entry,
735 GHashTable *key_value_pairs,
744 GSocketAddress *address;
746 GList *resolved_addresses;
752 resolved_addresses = NULL;
754 host = g_hash_table_lookup (key_value_pairs, "host");
755 port = g_hash_table_lookup (key_value_pairs, "port");
756 family = g_hash_table_lookup (key_value_pairs, "family");
757 if (g_hash_table_lookup (key_value_pairs, "noncefile") != NULL)
759 g_set_error_literal (error,
761 G_IO_ERROR_INVALID_ARGUMENT,
762 _("Cannot specify nonce file when creating a server"));
770 port_num = strtol (port, NULL, 10);
772 resolver = g_resolver_get_default ();
773 resolved_addresses = g_resolver_lookup_by_name (resolver,
777 if (resolved_addresses == NULL)
780 /* TODO: handle family */
781 for (l = resolved_addresses; l != NULL; l = l->next)
783 GInetAddress *address = G_INET_ADDRESS (l->data);
784 GSocketAddress *socket_address;
785 GSocketAddress *effective_address;
787 socket_address = g_inet_socket_address_new (address, port_num);
788 if (!g_socket_listener_add_address (server->priv->listener,
790 G_SOCKET_TYPE_STREAM,
791 G_SOCKET_PROTOCOL_TCP,
792 NULL, /* GObject *source_object */
796 g_object_unref (socket_address);
800 /* make sure we allocate the same port number for other listeners */
801 port_num = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (effective_address));
803 g_object_unref (effective_address);
804 g_object_unref (socket_address);
812 gsize bytes_remaining;
814 server->priv->nonce = g_new0 (guchar, 16);
815 for (n = 0; n < 16; n++)
816 server->priv->nonce[n] = g_random_int_range (0, 256);
817 fd = g_file_open_tmp ("gdbus-nonce-file-XXXXXX",
818 &server->priv->nonce_file,
822 g_socket_listener_close (server->priv->listener);
827 bytes_remaining = 16;
828 while (bytes_remaining > 0)
831 ret = write (fd, server->priv->nonce + bytes_written, bytes_remaining);
838 g_io_error_from_errno (errno),
839 _("Error writing nonce file at `%s': %s"),
840 server->priv->nonce_file,
844 bytes_written += ret;
845 bytes_remaining -= ret;
848 server->priv->client_address = g_strdup_printf ("nonce-tcp:host=%s,port=%d,noncefile=%s",
851 server->priv->nonce_file);
855 server->priv->client_address = g_strdup_printf ("tcp:host=%s,port=%d", host, port_num);
857 server->priv->is_using_listener = TRUE;
861 g_list_foreach (resolved_addresses, (GFunc) g_object_unref, NULL);
862 g_list_free (resolved_addresses);
863 g_object_unref (resolver);
867 /* ---------------------------------------------------------------------------------------------------- */
872 GDBusConnection *connection;
876 emit_idle_data_free (EmitIdleData *data)
878 g_object_unref (data->server);
879 g_object_unref (data->connection);
884 emit_new_connection_in_idle (gpointer user_data)
886 EmitIdleData *data = user_data;
888 g_signal_emit (data->server,
889 _signals[NEW_CONNECTION_SIGNAL],
892 g_object_unref (data->connection);
897 /* Called in new thread */
899 on_run (GSocketService *service,
900 GSocketConnection *socket_connection,
901 GObject *source_object,
904 GDBusServer *server = G_DBUS_SERVER (user_data);
905 GDBusConnection *connection;
906 GDBusConnectionFlags connection_flags;
908 if (server->priv->nonce != NULL)
913 if (!g_input_stream_read_all (g_io_stream_get_input_stream (G_IO_STREAM (socket_connection)),
917 NULL, /* GCancellable */
921 if (bytes_read != 16)
924 if (memcmp (buf, server->priv->nonce, 16) != 0)
928 connection_flags = G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER;
929 if (server->priv->flags & G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS)
930 connection_flags |= G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS;
932 connection = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
935 server->priv->authentication_observer,
936 NULL, /* GCancellable */
938 if (connection == NULL)
941 if (server->priv->flags & G_DBUS_SERVER_FLAGS_RUN_IN_THREAD)
943 g_signal_emit (server,
944 _signals[NEW_CONNECTION_SIGNAL],
947 g_object_unref (connection);
951 GSource *idle_source;
954 data = g_new0 (EmitIdleData, 1);
955 data->server = g_object_ref (server);
956 data->connection = g_object_ref (connection);
958 idle_source = g_idle_source_new ();
959 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
960 g_source_set_callback (idle_source,
961 emit_new_connection_in_idle,
963 (GDestroyNotify) emit_idle_data_free);
964 g_source_attach (idle_source, server->priv->main_context_at_construction);
965 g_source_unref (idle_source);
973 initable_init (GInitable *initable,
974 GCancellable *cancellable,
977 GDBusServer *server = G_DBUS_SERVER (initable);
986 if (!g_dbus_is_guid (server->priv->guid))
988 g_set_error (&last_error,
990 G_IO_ERROR_INVALID_ARGUMENT,
991 _("The string `%s' is not a valid D-Bus GUID"),
996 server->priv->listener = G_SOCKET_LISTENER (g_threaded_socket_service_new (-1));
998 addr_array = g_strsplit (server->priv->address, ";", 0);
1000 for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
1002 const gchar *address_entry = addr_array[n];
1003 GHashTable *key_value_pairs;
1004 gchar *transport_name;
1008 if (g_dbus_is_supported_address (address_entry,
1010 _g_dbus_address_parse_entry (address_entry,
1020 else if (g_strcmp0 (transport_name, "unix") == 0)
1021 ret = try_unix (server, address_entry, key_value_pairs, &this_error);
1023 else if (g_strcmp0 (transport_name, "tcp") == 0)
1024 ret = try_tcp (server, address_entry, key_value_pairs, FALSE, &this_error);
1025 else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
1026 ret = try_tcp (server, address_entry, key_value_pairs, TRUE, &this_error);
1028 g_set_error (&this_error,
1030 G_IO_ERROR_INVALID_ARGUMENT,
1031 _("Cannot listen on unsupported transport `%s'"),
1034 g_free (transport_name);
1035 if (key_value_pairs != NULL)
1036 g_hash_table_unref (key_value_pairs);
1040 g_assert (this_error == NULL);
1045 if (this_error != NULL)
1047 if (last_error != NULL)
1048 g_error_free (last_error);
1049 last_error = this_error;
1059 if (last_error != NULL)
1060 g_error_free (last_error);
1064 g_assert (last_error != NULL);
1065 g_propagate_error (error, last_error);
1072 initable_iface_init (GInitableIface *initable_iface)
1074 initable_iface->init = initable_init;
1077 /* ---------------------------------------------------------------------------------------------------- */
1079 #define __G_DBUS_SERVER_C__
1080 #include "gioaliasdef.c"