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>
75 * The #GDBusServer structure contains only private data and
76 * should only be accessed using the provided API.
83 GObject parent_instance;
85 GDBusServerFlags flags;
92 gchar *client_address;
94 GSocketListener *listener;
95 gboolean is_using_listener;
97 /* The result of g_main_context_get_thread_default() when the object
98 * was created (the GObject _init() function) - this is used for delivery
99 * of the :new-connection GObject signal.
101 GMainContext *main_context_at_construction;
105 GDBusAuthObserver *authentication_observer;
108 typedef struct _GDBusServerClass GDBusServerClass;
112 * @new_connection: Signal class handler for the #GDBusServer::new-connection signal.
114 * Class structure for #GDBusServer.
118 struct _GDBusServerClass
121 GObjectClass parent_class;
125 void (*new_connection) (GDBusServer *server,
126 GDBusConnection *connection);
137 PROP_AUTHENTICATION_OBSERVER,
142 NEW_CONNECTION_SIGNAL,
146 guint _signals[LAST_SIGNAL] = {0};
148 static void initable_iface_init (GInitableIface *initable_iface);
150 G_DEFINE_TYPE_WITH_CODE (GDBusServer, g_dbus_server, G_TYPE_OBJECT,
151 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
155 g_dbus_server_finalize (GObject *object)
157 GDBusServer *server = G_DBUS_SERVER (object);
159 if (server->authentication_observer != NULL)
160 g_object_unref (server->authentication_observer);
162 if (server->listener != NULL)
163 g_object_unref (server->listener);
165 g_free (server->address);
166 g_free (server->guid);
167 g_free (server->client_address);
168 if (server->nonce != NULL)
170 memset (server->nonce, '\0', 16);
171 g_free (server->nonce);
173 /* we could unlink the nonce file but I don't
174 * think it's really worth the effort/risk
176 g_free (server->nonce_file);
178 if (server->main_context_at_construction != NULL)
179 g_main_context_unref (server->main_context_at_construction);
181 G_OBJECT_CLASS (g_dbus_server_parent_class)->finalize (object);
185 g_dbus_server_get_property (GObject *object,
190 GDBusServer *server = G_DBUS_SERVER (object);
195 g_value_set_flags (value, server->flags);
199 g_value_set_string (value, server->guid);
203 g_value_set_string (value, server->address);
206 case PROP_CLIENT_ADDRESS:
207 g_value_set_string (value, server->client_address);
211 g_value_set_boolean (value, server->active);
214 case PROP_AUTHENTICATION_OBSERVER:
215 g_value_set_object (value, server->authentication_observer);
219 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
225 g_dbus_server_set_property (GObject *object,
230 GDBusServer *server = G_DBUS_SERVER (object);
235 server->flags = g_value_get_flags (value);
239 server->guid = g_value_dup_string (value);
243 server->address = g_value_dup_string (value);
246 case PROP_AUTHENTICATION_OBSERVER:
247 server->authentication_observer = g_value_dup_object (value);
251 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
257 g_dbus_server_class_init (GDBusServerClass *klass)
259 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
261 gobject_class->finalize = g_dbus_server_finalize;
262 gobject_class->set_property = g_dbus_server_set_property;
263 gobject_class->get_property = g_dbus_server_get_property;
268 * Flags from the #GDBusServerFlags enumeration.
272 g_object_class_install_property (gobject_class,
274 g_param_spec_flags ("flags",
276 P_("Flags for the server"),
277 G_TYPE_DBUS_SERVER_FLAGS,
278 G_DBUS_SERVER_FLAGS_NONE,
281 G_PARAM_CONSTRUCT_ONLY |
282 G_PARAM_STATIC_NAME |
283 G_PARAM_STATIC_BLURB |
284 G_PARAM_STATIC_NICK));
289 * The guid of the server.
293 g_object_class_install_property (gobject_class,
295 g_param_spec_string ("guid",
297 P_("The guid of the server"),
301 G_PARAM_CONSTRUCT_ONLY |
302 G_PARAM_STATIC_NAME |
303 G_PARAM_STATIC_BLURB |
304 G_PARAM_STATIC_NICK));
307 * GDBusServer:address:
309 * The D-Bus address to listen on.
313 g_object_class_install_property (gobject_class,
315 g_param_spec_string ("address",
317 P_("The address to listen on"),
321 G_PARAM_CONSTRUCT_ONLY |
322 G_PARAM_STATIC_NAME |
323 G_PARAM_STATIC_BLURB |
324 G_PARAM_STATIC_NICK));
327 * GDBusServer:client-address:
329 * The D-Bus address that clients can use.
333 g_object_class_install_property (gobject_class,
335 g_param_spec_string ("client-address",
336 P_("Client Address"),
337 P_("The address clients can use"),
340 G_PARAM_STATIC_NAME |
341 G_PARAM_STATIC_BLURB |
342 G_PARAM_STATIC_NICK));
345 * GDBusServer:active:
347 * Whether the server is currently active.
351 g_object_class_install_property (gobject_class,
353 g_param_spec_string ("active",
355 P_("Whether the server is currently active"),
358 G_PARAM_STATIC_NAME |
359 G_PARAM_STATIC_BLURB |
360 G_PARAM_STATIC_NICK));
363 * GDBusServer:authentication-observer:
365 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
369 g_object_class_install_property (gobject_class,
370 PROP_AUTHENTICATION_OBSERVER,
371 g_param_spec_object ("authentication-observer",
372 P_("Authentication Observer"),
373 P_("Object used to assist in the authentication process"),
374 G_TYPE_DBUS_AUTH_OBSERVER,
377 G_PARAM_CONSTRUCT_ONLY |
378 G_PARAM_STATIC_NAME |
379 G_PARAM_STATIC_BLURB |
380 G_PARAM_STATIC_NICK));
383 * GDBusServer::new-connection:
384 * @server: The #GDBusServer emitting the signal.
385 * @connection: A #GDBusConnection for the new connection.
387 * Emitted when a new authenticated connection has been made. Use
388 * g_dbus_connection_get_peer_credentials() to figure out what
389 * identity (if any), was authenticated.
391 * If you want to accept the connection, simply ref the @connection
392 * object. Then call g_dbus_connection_close() and unref it when you
393 * are done with it. A typical thing to do when accepting a
394 * connection is to listen to the #GDBusConnection::closed signal.
396 * If #GDBusServer:flags contains %G_DBUS_SERVER_FLAGS_RUN_IN_THREAD
397 * then the signal is emitted in a new thread dedicated to the
398 * connection. Otherwise the signal is emitted in the <link
399 * linkend="g-main-context-push-thread-default">thread-default main
400 * loop</link> of the thread that @server was constructed in.
402 * You are guaranteed that signal handlers for this signal runs
403 * before incoming messages on @connection are processed. This means
404 * that it's suitable to call g_dbus_connection_register_object() or
405 * similar from the signal handler.
409 _signals[NEW_CONNECTION_SIGNAL] = g_signal_new ("new-connection",
412 G_STRUCT_OFFSET (GDBusServerClass, new_connection),
415 g_cclosure_marshal_VOID__OBJECT,
418 G_TYPE_DBUS_CONNECTION);
422 g_dbus_server_init (GDBusServer *server)
424 server->main_context_at_construction = g_main_context_get_thread_default ();
425 if (server->main_context_at_construction != NULL)
426 g_main_context_ref (server->main_context_at_construction);
430 on_run (GSocketService *service,
431 GSocketConnection *socket_connection,
432 GObject *source_object,
436 * g_dbus_server_new_sync:
437 * @address: A D-Bus address.
438 * @flags: Flags from the #GDBusServerFlags enumeration.
439 * @guid: A D-Bus GUID.
440 * @observer: A #GDBusAuthObserver or %NULL.
441 * @cancellable: A #GCancellable or %NULL.
442 * @error: Return location for server or %NULL.
444 * Creates a new D-Bus server that listens on the first address in
445 * @address that works.
447 * Once constructed, you can use g_dbus_server_get_client_address() to
448 * get a D-Bus address string that clients can use to connect.
450 * Connect to the #GDBusServer::new-connection signal to handle
451 * incoming connections.
453 * The returned #GDBusServer isn't active - you have to start it with
454 * g_dbus_server_start().
456 * See <xref linkend="gdbus-peer-to-peer"/> for how #GDBusServer can
459 * This is a synchronous failable constructor. See
460 * g_dbus_server_new() for the asynchronous version.
462 * Returns: A #GDBusServer or %NULL if @error is set. Free with
468 g_dbus_server_new_sync (const gchar *address,
469 GDBusServerFlags flags,
471 GDBusAuthObserver *observer,
472 GCancellable *cancellable,
477 g_return_val_if_fail (address != NULL, NULL);
478 g_return_val_if_fail (g_dbus_is_guid (guid), NULL);
479 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
481 server = g_initable_new (G_TYPE_DBUS_SERVER,
487 "authentication-observer", observer,
491 /* Right now we don't have any transport not using the listener... */
492 g_assert (server->is_using_listener);
493 g_signal_connect (G_SOCKET_SERVICE (server->listener),
503 * g_dbus_server_get_client_address:
504 * @server: A #GDBusServer.
506 * Gets a D-Bus address string that can be used by clients to connect
509 * Returns: A D-Bus address string. Do not free, the string is owned
515 g_dbus_server_get_client_address (GDBusServer *server)
517 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
518 return server->client_address;
522 * g_dbus_server_get_guid:
523 * @server: A #GDBusServer.
525 * Gets the GUID for @server.
527 * Returns: A D-Bus GUID. Do not free this string, it is owned by @server.
532 g_dbus_server_get_guid (GDBusServer *server)
534 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
539 * g_dbus_server_get_flags:
540 * @server: A #GDBusServer.
542 * Gets the flags for @server.
544 * Returns: A set of flags from the #GDBusServerFlags enumeration.
549 g_dbus_server_get_flags (GDBusServer *server)
551 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
552 return server->flags;
556 * g_dbus_server_is_active:
557 * @server: A #GDBusServer.
559 * Gets whether @server is active.
561 * Returns: %TRUE if server is active, %FALSE otherwise.
566 g_dbus_server_is_active (GDBusServer *server)
568 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
569 return server->active;
573 * g_dbus_server_start:
574 * @server: A #GDBusServer.
581 g_dbus_server_start (GDBusServer *server)
583 g_return_if_fail (G_IS_DBUS_SERVER (server));
586 /* Right now we don't have any transport not using the listener... */
587 g_assert (server->is_using_listener);
588 g_socket_service_start (G_SOCKET_SERVICE (server->listener));
589 server->active = TRUE;
590 g_object_notify (G_OBJECT (server), "active");
594 * g_dbus_server_stop:
595 * @server: A #GDBusServer.
602 g_dbus_server_stop (GDBusServer *server)
604 g_return_if_fail (G_IS_DBUS_SERVER (server));
607 /* Right now we don't have any transport not using the listener... */
608 g_assert (server->is_using_listener);
609 g_socket_service_stop (G_SOCKET_SERVICE (server->listener));
610 server->active = FALSE;
611 g_object_notify (G_OBJECT (server), "active");
614 /* ---------------------------------------------------------------------------------------------------- */
622 ret = g_random_int_range (0, 60);
632 /* note that address_entry has already been validated => exactly one of path, tmpdir or abstract keys are set */
634 try_unix (GDBusServer *server,
635 const gchar *address_entry,
636 GHashTable *key_value_pairs,
642 const gchar *abstract;
643 GSocketAddress *address;
648 path = g_hash_table_lookup (key_value_pairs, "path");
649 tmpdir = g_hash_table_lookup (key_value_pairs, "tmpdir");
650 abstract = g_hash_table_lookup (key_value_pairs, "abstract");
654 address = g_unix_socket_address_new (path);
656 else if (tmpdir != NULL)
663 s = g_string_new (tmpdir);
664 g_string_append (s, "/dbus-");
665 for (n = 0; n < 8; n++)
666 g_string_append_c (s, random_ascii ());
668 /* prefer abstract namespace if available */
669 if (g_unix_socket_address_abstract_names_supported ())
670 address = g_unix_socket_address_new_with_type (s->str,
672 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
674 address = g_unix_socket_address_new (s->str);
675 g_string_free (s, TRUE);
678 if (!g_socket_listener_add_address (server->listener,
680 G_SOCKET_TYPE_STREAM,
681 G_SOCKET_PROTOCOL_DEFAULT,
682 NULL, /* source_object */
683 NULL, /* effective_address */
686 if (local_error->domain == G_IO_ERROR && local_error->code == G_IO_ERROR_ADDRESS_IN_USE)
688 g_error_free (local_error);
691 g_propagate_error (error, local_error);
697 else if (abstract != NULL)
699 if (!g_unix_socket_address_abstract_names_supported ())
701 g_set_error_literal (error,
703 G_IO_ERROR_NOT_SUPPORTED,
704 _("Abstract name space not supported"));
707 address = g_unix_socket_address_new_with_type (abstract,
709 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
713 g_assert_not_reached ();
716 if (!g_socket_listener_add_address (server->listener,
718 G_SOCKET_TYPE_STREAM,
719 G_SOCKET_PROTOCOL_DEFAULT,
720 NULL, /* source_object */
721 NULL, /* effective_address */
731 /* Fill out client_address if the connection attempt worked */
734 server->is_using_listener = TRUE;
736 switch (g_unix_socket_address_get_address_type (G_UNIX_SOCKET_ADDRESS (address)))
738 case G_UNIX_SOCKET_ADDRESS_ABSTRACT:
739 server->client_address = g_strdup_printf ("unix:abstract=%s",
740 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
743 case G_UNIX_SOCKET_ADDRESS_PATH:
744 server->client_address = g_strdup_printf ("unix:path=%s",
745 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
749 g_assert_not_reached ();
753 g_object_unref (address);
759 /* ---------------------------------------------------------------------------------------------------- */
761 /* note that address_entry has already been validated =>
762 * both host and port (guranteed to be a number in [0, 65535]) are set (family is optional)
765 try_tcp (GDBusServer *server,
766 const gchar *address_entry,
767 GHashTable *key_value_pairs,
776 GSocketAddress *address;
778 GList *resolved_addresses;
784 resolved_addresses = NULL;
786 host = g_hash_table_lookup (key_value_pairs, "host");
787 port = g_hash_table_lookup (key_value_pairs, "port");
788 family = g_hash_table_lookup (key_value_pairs, "family");
789 if (g_hash_table_lookup (key_value_pairs, "noncefile") != NULL)
791 g_set_error_literal (error,
793 G_IO_ERROR_INVALID_ARGUMENT,
794 _("Cannot specify nonce file when creating a server"));
802 port_num = strtol (port, NULL, 10);
804 resolver = g_resolver_get_default ();
805 resolved_addresses = g_resolver_lookup_by_name (resolver,
809 if (resolved_addresses == NULL)
812 /* TODO: handle family */
813 for (l = resolved_addresses; l != NULL; l = l->next)
815 GInetAddress *address = G_INET_ADDRESS (l->data);
816 GSocketAddress *socket_address;
817 GSocketAddress *effective_address;
819 socket_address = g_inet_socket_address_new (address, port_num);
820 if (!g_socket_listener_add_address (server->listener,
822 G_SOCKET_TYPE_STREAM,
823 G_SOCKET_PROTOCOL_TCP,
824 NULL, /* GObject *source_object */
828 g_object_unref (socket_address);
832 /* make sure we allocate the same port number for other listeners */
833 port_num = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (effective_address));
835 g_object_unref (effective_address);
836 g_object_unref (socket_address);
844 gsize bytes_remaining;
846 server->nonce = g_new0 (guchar, 16);
847 for (n = 0; n < 16; n++)
848 server->nonce[n] = g_random_int_range (0, 256);
849 fd = g_file_open_tmp ("gdbus-nonce-file-XXXXXX",
854 g_socket_listener_close (server->listener);
859 bytes_remaining = 16;
860 while (bytes_remaining > 0)
863 ret = write (fd, server->nonce + bytes_written, bytes_remaining);
870 g_io_error_from_errno (errno),
871 _("Error writing nonce file at `%s': %s"),
876 bytes_written += ret;
877 bytes_remaining -= ret;
880 server->client_address = g_strdup_printf ("nonce-tcp:host=%s,port=%d,noncefile=%s",
887 server->client_address = g_strdup_printf ("tcp:host=%s,port=%d", host, port_num);
889 server->is_using_listener = TRUE;
893 g_list_foreach (resolved_addresses, (GFunc) g_object_unref, NULL);
894 g_list_free (resolved_addresses);
895 g_object_unref (resolver);
899 /* ---------------------------------------------------------------------------------------------------- */
904 GDBusConnection *connection;
908 emit_idle_data_free (EmitIdleData *data)
910 g_object_unref (data->server);
911 g_object_unref (data->connection);
916 emit_new_connection_in_idle (gpointer user_data)
918 EmitIdleData *data = user_data;
920 g_signal_emit (data->server,
921 _signals[NEW_CONNECTION_SIGNAL],
924 g_dbus_connection_start_message_processing (data->connection);
925 g_object_unref (data->connection);
930 /* Called in new thread */
932 on_run (GSocketService *service,
933 GSocketConnection *socket_connection,
934 GObject *source_object,
937 GDBusServer *server = G_DBUS_SERVER (user_data);
938 GDBusConnection *connection;
939 GDBusConnectionFlags connection_flags;
941 if (server->nonce != NULL)
946 if (!g_input_stream_read_all (g_io_stream_get_input_stream (G_IO_STREAM (socket_connection)),
950 NULL, /* GCancellable */
954 if (bytes_read != 16)
957 if (memcmp (buf, server->nonce, 16) != 0)
962 G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER |
963 G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING;
964 if (server->flags & G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS)
965 connection_flags |= G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS;
967 connection = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
970 server->authentication_observer,
971 NULL, /* GCancellable */
973 if (connection == NULL)
976 if (server->flags & G_DBUS_SERVER_FLAGS_RUN_IN_THREAD)
978 g_signal_emit (server,
979 _signals[NEW_CONNECTION_SIGNAL],
982 g_dbus_connection_start_message_processing (connection);
983 g_object_unref (connection);
987 GSource *idle_source;
990 data = g_new0 (EmitIdleData, 1);
991 data->server = g_object_ref (server);
992 data->connection = g_object_ref (connection);
994 idle_source = g_idle_source_new ();
995 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
996 g_source_set_callback (idle_source,
997 emit_new_connection_in_idle,
999 (GDestroyNotify) emit_idle_data_free);
1000 g_source_attach (idle_source, server->main_context_at_construction);
1001 g_source_unref (idle_source);
1009 initable_init (GInitable *initable,
1010 GCancellable *cancellable,
1013 GDBusServer *server = G_DBUS_SERVER (initable);
1022 if (!g_dbus_is_guid (server->guid))
1024 g_set_error (&last_error,
1026 G_IO_ERROR_INVALID_ARGUMENT,
1027 _("The string `%s' is not a valid D-Bus GUID"),
1032 server->listener = G_SOCKET_LISTENER (g_threaded_socket_service_new (-1));
1034 addr_array = g_strsplit (server->address, ";", 0);
1036 for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
1038 const gchar *address_entry = addr_array[n];
1039 GHashTable *key_value_pairs;
1040 gchar *transport_name;
1044 if (g_dbus_is_supported_address (address_entry,
1046 _g_dbus_address_parse_entry (address_entry,
1056 else if (g_strcmp0 (transport_name, "unix") == 0)
1057 ret = try_unix (server, address_entry, key_value_pairs, &this_error);
1059 else if (g_strcmp0 (transport_name, "tcp") == 0)
1060 ret = try_tcp (server, address_entry, key_value_pairs, FALSE, &this_error);
1061 else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
1062 ret = try_tcp (server, address_entry, key_value_pairs, TRUE, &this_error);
1064 g_set_error (&this_error,
1066 G_IO_ERROR_INVALID_ARGUMENT,
1067 _("Cannot listen on unsupported transport `%s'"),
1070 g_free (transport_name);
1071 if (key_value_pairs != NULL)
1072 g_hash_table_unref (key_value_pairs);
1076 g_assert (this_error == NULL);
1081 if (this_error != NULL)
1083 if (last_error != NULL)
1084 g_error_free (last_error);
1085 last_error = this_error;
1095 if (last_error != NULL)
1096 g_error_free (last_error);
1100 g_assert (last_error != NULL);
1101 g_propagate_error (error, last_error);
1108 initable_iface_init (GInitableIface *initable_iface)
1110 initable_iface->init = initable_init;
1113 /* ---------------------------------------------------------------------------------------------------- */
1115 #define __G_DBUS_SERVER_C__
1116 #include "gioaliasdef.c"