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
47 * @include: gdbus/gdbus.h
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.
222 g_object_class_install_property (gobject_class,
224 g_param_spec_flags ("flags",
226 _("Flags for the server"),
227 G_TYPE_DBUS_SERVER_FLAGS,
228 G_DBUS_SERVER_FLAGS_NONE,
231 G_PARAM_CONSTRUCT_ONLY |
232 G_PARAM_STATIC_NAME |
233 G_PARAM_STATIC_BLURB |
234 G_PARAM_STATIC_NICK));
239 * The guid of the server.
241 g_object_class_install_property (gobject_class,
243 g_param_spec_string ("guid",
245 _("The guid of the server"),
249 G_PARAM_CONSTRUCT_ONLY |
250 G_PARAM_STATIC_NAME |
251 G_PARAM_STATIC_BLURB |
252 G_PARAM_STATIC_NICK));
255 * GDBusServer:address:
257 * The D-Bus address to listen on.
259 g_object_class_install_property (gobject_class,
261 g_param_spec_string ("address",
263 _("The address to listen on"),
267 G_PARAM_CONSTRUCT_ONLY |
268 G_PARAM_STATIC_NAME |
269 G_PARAM_STATIC_BLURB |
270 G_PARAM_STATIC_NICK));
273 * GDBusServer:client-address:
275 * The D-Bus address that clients can use.
277 g_object_class_install_property (gobject_class,
279 g_param_spec_string ("client-address",
281 _("The address clients can use"),
284 G_PARAM_STATIC_NAME |
285 G_PARAM_STATIC_BLURB |
286 G_PARAM_STATIC_NICK));
289 * GDBusServer:active:
291 * Whether the server is currently active.
293 g_object_class_install_property (gobject_class,
295 g_param_spec_string ("active",
297 _("Whether the server is currently active"),
300 G_PARAM_STATIC_NAME |
301 G_PARAM_STATIC_BLURB |
302 G_PARAM_STATIC_NICK));
305 * GDBusServer:authentication-observer:
307 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
309 g_object_class_install_property (gobject_class,
310 PROP_AUTHENTICATION_OBSERVER,
311 g_param_spec_object ("authentication-observer",
312 _("Authentication Observer"),
313 _("Object used to assist in the authentication process"),
314 G_TYPE_DBUS_AUTH_OBSERVER,
317 G_PARAM_CONSTRUCT_ONLY |
318 G_PARAM_STATIC_NAME |
319 G_PARAM_STATIC_BLURB |
320 G_PARAM_STATIC_NICK));
323 * GDBusServer::new-connection:
324 * @server: The #GDBusServer emitting the signal.
325 * @connection: A #GDBusConnection for the new connection.
327 * Emitted when a new authenticated connection has been made. Use
328 * g_dbus_connection_get_peer_credentials() to figure out what
329 * identity (if any), was authenticated.
331 * If you want to accept the connection, simply ref the @connection
332 * object. Then call g_dbus_connection_close() and unref it when you
333 * are done with it. A typical thing to do when accepting a
334 * connection is to listen to the #GDBusConnection::closed signal.
336 * If #GDBusServer:flags contains %G_DBUS_SERVER_FLAGS_RUN_IN_THREAD
337 * then the signal is emitted in a new thread dedicated to the
338 * connection. Otherwise the signal is emitted in the <link
339 * linkend="g-main-context-push-thread-default">thread-default main
340 * loop</link> of the thread that @server was constructed in.
342 _signals[NEW_CONNECTION_SIGNAL] = g_signal_new ("new-connection",
345 G_STRUCT_OFFSET (GDBusServerClass, new_connection),
348 g_cclosure_marshal_VOID__OBJECT,
351 G_TYPE_DBUS_CONNECTION);
354 g_type_class_add_private (klass, sizeof (GDBusServerPrivate));
358 g_dbus_server_init (GDBusServer *server)
360 server->priv = G_TYPE_INSTANCE_GET_PRIVATE (server, G_TYPE_DBUS_SERVER, GDBusServerPrivate);
362 server->priv->main_context_at_construction = g_main_context_get_thread_default ();
363 if (server->priv->main_context_at_construction != NULL)
364 g_main_context_ref (server->priv->main_context_at_construction);
368 on_run (GSocketService *service,
369 GSocketConnection *socket_connection,
370 GObject *source_object,
374 * g_dbus_server_new_sync:
375 * @address: A D-Bus address.
376 * @flags: Flags from the #GDBusServerFlags enumeration.
377 * @guid: A D-Bus GUID.
378 * @observer: A #GDBusAuthObserver or %NULL.
379 * @cancellable: A #GCancellable or %NULL.
380 * @error: Return location for server or %NULL.
382 * Creates a new D-Bus server that listens on the first address in
383 * @address that works.
385 * Once constructed, you can use g_dbus_server_get_client_address() to
386 * get a D-Bus address string that clients can use to connect.
388 * Connect to the #GDBusServer::new-connection signal to handle
389 * incoming connections.
391 * The returned #GDBusServer isn't active - you have to start it with
392 * g_dbus_server_start().
394 * See <xref linkend="gdbus-peer-to-peer"/> for how #GDBusServer can
397 * This is a synchronous failable constructor. See
398 * g_dbus_server_new() for the asynchronous version.
400 * Returns: A #GDBusServer or %NULL if @error is set. Free with
404 g_dbus_server_new_sync (const gchar *address,
405 GDBusServerFlags flags,
407 GDBusAuthObserver *observer,
408 GCancellable *cancellable,
413 g_return_val_if_fail (address != NULL, NULL);
414 g_return_val_if_fail (g_dbus_is_guid (guid), NULL);
415 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
417 server = g_initable_new (G_TYPE_DBUS_SERVER,
423 "authentication-observer", observer,
427 /* Right now we don't have any transport not using the listener... */
428 g_assert (server->priv->is_using_listener);
429 g_signal_connect (G_SOCKET_SERVICE (server->priv->listener),
439 * g_dbus_server_get_client_address:
440 * @server: A #GDBusServer.
442 * Gets a D-Bus address string that can be used by clients to connect
445 * Returns: A D-Bus address string. Do not free, the string is owned
449 g_dbus_server_get_client_address (GDBusServer *server)
451 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
452 return server->priv->client_address;
456 * g_dbus_server_get_guid:
457 * @server: A #GDBusServer.
459 * Gets the GUID for @server.
461 * Returns: A D-Bus GUID. Do not free this string, it is owned by @server.
464 g_dbus_server_get_guid (GDBusServer *server)
466 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
467 return server->priv->guid;
471 * g_dbus_server_get_flags:
472 * @server: A #GDBusServer.
474 * Gets the flags for @server.
476 * Returns: A set of flags from the #GDBusServerFlags enumeration.
479 g_dbus_server_get_flags (GDBusServer *server)
481 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
482 return server->priv->flags;
486 * g_dbus_server_is_active:
487 * @server: A #GDBusServer.
489 * Gets whether @server is active.
491 * Returns: %TRUE if server is active, %FALSE otherwise.
494 g_dbus_server_is_active (GDBusServer *server)
496 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
497 return server->priv->active;
501 * g_dbus_server_start:
502 * @server: A #GDBusServer.
507 g_dbus_server_start (GDBusServer *server)
509 g_return_if_fail (G_IS_DBUS_SERVER (server));
510 if (server->priv->active)
512 /* Right now we don't have any transport not using the listener... */
513 g_assert (server->priv->is_using_listener);
514 g_socket_service_start (G_SOCKET_SERVICE (server->priv->listener));
515 server->priv->active = TRUE;
516 g_object_notify (G_OBJECT (server), "active");
520 * g_dbus_server_stop:
521 * @server: A #GDBusServer.
526 g_dbus_server_stop (GDBusServer *server)
528 g_return_if_fail (G_IS_DBUS_SERVER (server));
529 if (!server->priv->active)
531 /* Right now we don't have any transport not using the listener... */
532 g_assert (server->priv->is_using_listener);
533 g_socket_service_stop (G_SOCKET_SERVICE (server->priv->listener));
534 server->priv->active = FALSE;
535 g_object_notify (G_OBJECT (server), "active");
538 /* ---------------------------------------------------------------------------------------------------- */
546 ret = g_random_int_range (0, 60);
556 /* note that address_entry has already been validated => exactly one of path, tmpdir or abstract keys are set */
558 try_unix (GDBusServer *server,
559 const gchar *address_entry,
560 GHashTable *key_value_pairs,
566 const gchar *abstract;
567 GSocketAddress *address;
572 path = g_hash_table_lookup (key_value_pairs, "path");
573 tmpdir = g_hash_table_lookup (key_value_pairs, "tmpdir");
574 abstract = g_hash_table_lookup (key_value_pairs, "abstract");
578 address = g_unix_socket_address_new (path);
580 else if (tmpdir != NULL)
587 s = g_string_new (tmpdir);
588 g_string_append (s, "/dbus-");
589 for (n = 0; n < 8; n++)
590 g_string_append_c (s, random_ascii ());
592 /* prefer abstract namespace if available */
593 if (g_unix_socket_address_abstract_names_supported ())
594 address = g_unix_socket_address_new_with_type (s->str,
596 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
598 address = g_unix_socket_address_new (s->str);
599 g_string_free (s, TRUE);
602 if (!g_socket_listener_add_address (server->priv->listener,
604 G_SOCKET_TYPE_STREAM,
605 G_SOCKET_PROTOCOL_DEFAULT,
606 NULL, /* source_object */
607 NULL, /* effective_address */
610 if (local_error->domain == G_IO_ERROR && local_error->code == G_IO_ERROR_ADDRESS_IN_USE)
612 g_error_free (local_error);
615 g_propagate_error (error, local_error);
621 else if (abstract != NULL)
623 if (!g_unix_socket_address_abstract_names_supported ())
625 g_set_error_literal (error,
627 G_IO_ERROR_NOT_SUPPORTED,
628 _("Abstract name space not supported"));
631 address = g_unix_socket_address_new_with_type (abstract,
633 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
637 g_assert_not_reached ();
640 if (!g_socket_listener_add_address (server->priv->listener,
642 G_SOCKET_TYPE_STREAM,
643 G_SOCKET_PROTOCOL_DEFAULT,
644 NULL, /* source_object */
645 NULL, /* effective_address */
655 /* Fill out client_address if the connection attempt worked */
658 server->priv->is_using_listener = TRUE;
660 switch (g_unix_socket_address_get_address_type (G_UNIX_SOCKET_ADDRESS (address)))
662 case G_UNIX_SOCKET_ADDRESS_ABSTRACT:
663 server->priv->client_address = g_strdup_printf ("unix:abstract=%s",
664 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
667 case G_UNIX_SOCKET_ADDRESS_PATH:
668 server->priv->client_address = g_strdup_printf ("unix:path=%s",
669 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
673 g_assert_not_reached ();
677 g_object_unref (address);
683 /* ---------------------------------------------------------------------------------------------------- */
685 /* note that address_entry has already been validated =>
686 * both host and port (guranteed to be a number in [0, 65535]) are set (family is optional)
689 try_tcp (GDBusServer *server,
690 const gchar *address_entry,
691 GHashTable *key_value_pairs,
700 GSocketAddress *address;
702 GList *resolved_addresses;
708 resolved_addresses = NULL;
710 host = g_hash_table_lookup (key_value_pairs, "host");
711 port = g_hash_table_lookup (key_value_pairs, "port");
712 family = g_hash_table_lookup (key_value_pairs, "family");
713 if (g_hash_table_lookup (key_value_pairs, "noncefile") != NULL)
715 g_set_error_literal (error,
717 G_IO_ERROR_INVALID_ARGUMENT,
718 _("Cannot specify nonce file when creating a server"));
726 port_num = strtol (port, NULL, 10);
728 resolver = g_resolver_get_default ();
729 resolved_addresses = g_resolver_lookup_by_name (resolver,
733 if (resolved_addresses == NULL)
737 /* TODO: handle family */
738 for (l = resolved_addresses; l != NULL; l = l->next)
740 GInetAddress *address = G_INET_ADDRESS (l->data);
741 GSocketAddress *socket_address;
742 GSocketAddress *effective_address;
744 socket_address = g_inet_socket_address_new (address, port_num);
745 if (!g_socket_listener_add_address (server->priv->listener,
747 G_SOCKET_TYPE_STREAM,
748 G_SOCKET_PROTOCOL_TCP,
749 NULL, /* GObject *source_object */
753 g_object_unref (socket_address);
758 /* make sure we allocate the same port number for other listeners */
759 port_num = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (effective_address));
761 g_object_unref (effective_address);
762 g_object_unref (socket_address);
770 gsize bytes_remaining;
772 server->priv->nonce = g_new0 (guchar, 16);
773 for (n = 0; n < 16; n++)
774 server->priv->nonce[n] = g_random_int_range (0, 256);
775 fd = g_file_open_tmp ("gdbus-nonce-file-XXXXXX",
776 &server->priv->nonce_file,
780 g_socket_listener_close (server->priv->listener);
785 bytes_remaining = 16;
786 while (bytes_remaining > 0)
789 ret = write (fd, server->priv->nonce + bytes_written, bytes_remaining);
796 g_io_error_from_errno (errno),
797 _("Error writing nonce file at `%s': %s"),
798 server->priv->nonce_file,
802 bytes_written += ret;
803 bytes_remaining -= ret;
806 server->priv->client_address = g_strdup_printf ("nonce-tcp:host=%s,port=%d,noncefile=%s",
809 server->priv->nonce_file);
813 server->priv->client_address = g_strdup_printf ("tcp:host=%s,port=%d", host, port_num);
815 server->priv->is_using_listener = TRUE;
819 g_list_foreach (resolved_addresses, (GFunc) g_object_unref, NULL);
820 g_list_free (resolved_addresses);
821 g_object_unref (resolver);
825 /* ---------------------------------------------------------------------------------------------------- */
830 GDBusConnection *connection;
834 emit_idle_data_free (EmitIdleData *data)
836 g_object_unref (data->server);
837 g_object_unref (data->connection);
842 emit_new_connection_in_idle (gpointer user_data)
844 EmitIdleData *data = user_data;
846 g_signal_emit (data->server,
847 _signals[NEW_CONNECTION_SIGNAL],
850 g_object_unref (data->connection);
855 /* Called in new thread */
857 on_run (GSocketService *service,
858 GSocketConnection *socket_connection,
859 GObject *source_object,
862 GDBusServer *server = G_DBUS_SERVER (user_data);
863 GDBusConnection *connection;
864 GDBusConnectionFlags connection_flags;
866 if (server->priv->nonce != NULL)
871 if (!g_input_stream_read_all (g_io_stream_get_input_stream (G_IO_STREAM (socket_connection)),
875 NULL, /* GCancellable */
879 if (bytes_read != 16)
882 if (memcmp (buf, server->priv->nonce, 16) != 0)
886 connection_flags = G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER;
887 if (server->priv->flags & G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS)
888 connection_flags |= G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS;
890 connection = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
893 server->priv->authentication_observer,
894 NULL, /* GCancellable */
896 if (connection == NULL)
899 if (server->priv->flags & G_DBUS_SERVER_FLAGS_RUN_IN_THREAD)
901 g_signal_emit (server,
902 _signals[NEW_CONNECTION_SIGNAL],
905 g_object_unref (connection);
909 GSource *idle_source;
912 data = g_new0 (EmitIdleData, 1);
913 data->server = g_object_ref (server);
914 data->connection = g_object_ref (connection);
916 idle_source = g_idle_source_new ();
917 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
918 g_source_set_callback (idle_source,
919 emit_new_connection_in_idle,
921 (GDestroyNotify) emit_idle_data_free);
922 g_source_attach (idle_source, server->priv->main_context_at_construction);
923 g_source_unref (idle_source);
931 initable_init (GInitable *initable,
932 GCancellable *cancellable,
935 GDBusServer *server = G_DBUS_SERVER (initable);
944 if (!g_dbus_is_guid (server->priv->guid))
946 g_set_error (&last_error,
948 G_IO_ERROR_INVALID_ARGUMENT,
949 _("The string `%s' is not a valid D-Bus GUID"),
954 server->priv->listener = G_SOCKET_LISTENER (g_threaded_socket_service_new (-1));
956 addr_array = g_strsplit (server->priv->address, ";", 0);
958 for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
960 const gchar *address_entry = addr_array[n];
961 GHashTable *key_value_pairs;
962 gchar *transport_name;
966 if (g_dbus_is_supported_address (address_entry,
968 _g_dbus_address_parse_entry (address_entry,
978 else if (g_strcmp0 (transport_name, "unix") == 0)
980 ret = try_unix (server, address_entry, key_value_pairs, &this_error);
983 else if (g_strcmp0 (transport_name, "tcp") == 0)
985 ret = try_tcp (server, address_entry, key_value_pairs, FALSE, &this_error);
987 else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
989 ret = try_tcp (server, address_entry, key_value_pairs, TRUE, &this_error);
993 g_set_error (&this_error,
995 G_IO_ERROR_INVALID_ARGUMENT,
996 _("Cannot listen on unsupported transport `%s'"),
1000 g_free (transport_name);
1001 if (key_value_pairs != NULL)
1002 g_hash_table_unref (key_value_pairs);
1006 g_assert (this_error == NULL);
1011 if (this_error != NULL)
1013 if (last_error != NULL)
1014 g_error_free (last_error);
1015 last_error = this_error;
1025 if (last_error != NULL)
1026 g_error_free (last_error);
1030 g_assert (last_error != NULL);
1031 g_propagate_error (error, last_error);
1038 initable_iface_init (GInitableIface *initable_iface)
1040 initable_iface->init = initable_init;
1043 /* ---------------------------------------------------------------------------------------------------- */