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>
34 #include "gdbusaddress.h"
35 #include "gdbusutils.h"
36 #include "gdbusconnection.h"
37 #include "gdbusserver.h"
38 #include "gioenumtypes.h"
39 #include "gdbusprivate.h"
40 #include "gdbusauthobserver.h"
41 #include "gio-marshal.h"
42 #include "ginitable.h"
43 #include "gsocketservice.h"
44 #include "gthreadedsocketservice.h"
45 #include "gresolver.h"
46 #include "ginetaddress.h"
47 #include "ginetsocketaddress.h"
48 #include "ginputstream.h"
49 #include "giostream.h"
52 #include "gunixsocketaddress.h"
60 * @short_description: Helper for accepting connections
63 * #GDBusServer is a helper for listening to and accepting D-Bus
66 * <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>
69 struct _GDBusServerPrivate
71 GDBusServerFlags flags;
78 gchar *client_address;
80 GSocketListener *listener;
81 gboolean is_using_listener;
83 /* The result of g_main_context_get_thread_default() when the object
84 * was created (the GObject _init() function) - this is used for delivery
85 * of the :new-connection GObject signal.
87 GMainContext *main_context_at_construction;
91 GDBusAuthObserver *authentication_observer;
102 PROP_AUTHENTICATION_OBSERVER,
107 NEW_CONNECTION_SIGNAL,
111 guint _signals[LAST_SIGNAL] = {0};
113 static void initable_iface_init (GInitableIface *initable_iface);
115 G_DEFINE_TYPE_WITH_CODE (GDBusServer, g_dbus_server, G_TYPE_OBJECT,
116 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
120 g_dbus_server_finalize (GObject *object)
122 GDBusServer *server = G_DBUS_SERVER (object);
124 if (server->priv->authentication_observer != NULL)
125 g_object_unref (server->priv->authentication_observer);
127 if (server->priv->listener != NULL)
128 g_object_unref (server->priv->listener);
130 g_free (server->priv->address);
131 g_free (server->priv->guid);
132 g_free (server->priv->client_address);
133 if (server->priv->nonce != NULL)
135 memset (server->priv->nonce, '\0', 16);
136 g_free (server->priv->nonce);
138 /* we could unlink the nonce file but I don't
139 * think it's really worth the effort/risk
141 g_free (server->priv->nonce_file);
143 if (server->priv->main_context_at_construction != NULL)
144 g_main_context_unref (server->priv->main_context_at_construction);
146 G_OBJECT_CLASS (g_dbus_server_parent_class)->finalize (object);
150 g_dbus_server_get_property (GObject *object,
155 GDBusServer *server = G_DBUS_SERVER (object);
160 g_value_set_flags (value, server->priv->flags);
164 g_value_set_string (value, server->priv->guid);
168 g_value_set_string (value, server->priv->address);
171 case PROP_CLIENT_ADDRESS:
172 g_value_set_string (value, server->priv->client_address);
176 g_value_set_boolean (value, server->priv->active);
179 case PROP_AUTHENTICATION_OBSERVER:
180 g_value_set_object (value, server->priv->authentication_observer);
184 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
190 g_dbus_server_set_property (GObject *object,
195 GDBusServer *server = G_DBUS_SERVER (object);
200 server->priv->flags = g_value_get_flags (value);
204 server->priv->guid = g_value_dup_string (value);
208 server->priv->address = g_value_dup_string (value);
211 case PROP_AUTHENTICATION_OBSERVER:
212 server->priv->authentication_observer = g_value_dup_object (value);
216 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
222 g_dbus_server_class_init (GDBusServerClass *klass)
224 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
226 gobject_class->finalize = g_dbus_server_finalize;
227 gobject_class->set_property = g_dbus_server_set_property;
228 gobject_class->get_property = g_dbus_server_get_property;
233 * Flags from the #GDBusServerFlags enumeration.
237 g_object_class_install_property (gobject_class,
239 g_param_spec_flags ("flags",
241 P_("Flags for the server"),
242 G_TYPE_DBUS_SERVER_FLAGS,
243 G_DBUS_SERVER_FLAGS_NONE,
246 G_PARAM_CONSTRUCT_ONLY |
247 G_PARAM_STATIC_NAME |
248 G_PARAM_STATIC_BLURB |
249 G_PARAM_STATIC_NICK));
254 * The guid of the server.
258 g_object_class_install_property (gobject_class,
260 g_param_spec_string ("guid",
262 P_("The guid of the server"),
266 G_PARAM_CONSTRUCT_ONLY |
267 G_PARAM_STATIC_NAME |
268 G_PARAM_STATIC_BLURB |
269 G_PARAM_STATIC_NICK));
272 * GDBusServer:address:
274 * The D-Bus address to listen on.
278 g_object_class_install_property (gobject_class,
280 g_param_spec_string ("address",
282 P_("The address to listen on"),
286 G_PARAM_CONSTRUCT_ONLY |
287 G_PARAM_STATIC_NAME |
288 G_PARAM_STATIC_BLURB |
289 G_PARAM_STATIC_NICK));
292 * GDBusServer:client-address:
294 * The D-Bus address that clients can use.
298 g_object_class_install_property (gobject_class,
300 g_param_spec_string ("client-address",
301 P_("Client Address"),
302 P_("The address clients can use"),
305 G_PARAM_STATIC_NAME |
306 G_PARAM_STATIC_BLURB |
307 G_PARAM_STATIC_NICK));
310 * GDBusServer:active:
312 * Whether the server is currently active.
316 g_object_class_install_property (gobject_class,
318 g_param_spec_string ("active",
320 P_("Whether the server is currently active"),
323 G_PARAM_STATIC_NAME |
324 G_PARAM_STATIC_BLURB |
325 G_PARAM_STATIC_NICK));
328 * GDBusServer:authentication-observer:
330 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
334 g_object_class_install_property (gobject_class,
335 PROP_AUTHENTICATION_OBSERVER,
336 g_param_spec_object ("authentication-observer",
337 P_("Authentication Observer"),
338 P_("Object used to assist in the authentication process"),
339 G_TYPE_DBUS_AUTH_OBSERVER,
342 G_PARAM_CONSTRUCT_ONLY |
343 G_PARAM_STATIC_NAME |
344 G_PARAM_STATIC_BLURB |
345 G_PARAM_STATIC_NICK));
348 * GDBusServer::new-connection:
349 * @server: The #GDBusServer emitting the signal.
350 * @connection: A #GDBusConnection for the new connection.
352 * Emitted when a new authenticated connection has been made. Use
353 * g_dbus_connection_get_peer_credentials() to figure out what
354 * identity (if any), was authenticated.
356 * If you want to accept the connection, simply ref the @connection
357 * object. Then call g_dbus_connection_close() and unref it when you
358 * are done with it. A typical thing to do when accepting a
359 * connection is to listen to the #GDBusConnection::closed signal.
361 * If #GDBusServer:flags contains %G_DBUS_SERVER_FLAGS_RUN_IN_THREAD
362 * then the signal is emitted in a new thread dedicated to the
363 * connection. Otherwise the signal is emitted in the <link
364 * linkend="g-main-context-push-thread-default">thread-default main
365 * loop</link> of the thread that @server was constructed in.
369 _signals[NEW_CONNECTION_SIGNAL] = g_signal_new ("new-connection",
372 G_STRUCT_OFFSET (GDBusServerClass, new_connection),
375 g_cclosure_marshal_VOID__OBJECT,
378 G_TYPE_DBUS_CONNECTION);
381 g_type_class_add_private (klass, sizeof (GDBusServerPrivate));
385 g_dbus_server_init (GDBusServer *server)
387 server->priv = G_TYPE_INSTANCE_GET_PRIVATE (server, G_TYPE_DBUS_SERVER, GDBusServerPrivate);
389 server->priv->main_context_at_construction = g_main_context_get_thread_default ();
390 if (server->priv->main_context_at_construction != NULL)
391 g_main_context_ref (server->priv->main_context_at_construction);
395 on_run (GSocketService *service,
396 GSocketConnection *socket_connection,
397 GObject *source_object,
401 * g_dbus_server_new_sync:
402 * @address: A D-Bus address.
403 * @flags: Flags from the #GDBusServerFlags enumeration.
404 * @guid: A D-Bus GUID.
405 * @observer: A #GDBusAuthObserver or %NULL.
406 * @cancellable: A #GCancellable or %NULL.
407 * @error: Return location for server or %NULL.
409 * Creates a new D-Bus server that listens on the first address in
410 * @address that works.
412 * Once constructed, you can use g_dbus_server_get_client_address() to
413 * get a D-Bus address string that clients can use to connect.
415 * Connect to the #GDBusServer::new-connection signal to handle
416 * incoming connections.
418 * The returned #GDBusServer isn't active - you have to start it with
419 * g_dbus_server_start().
421 * See <xref linkend="gdbus-peer-to-peer"/> for how #GDBusServer can
424 * This is a synchronous failable constructor. See
425 * g_dbus_server_new() for the asynchronous version.
427 * Returns: A #GDBusServer or %NULL if @error is set. Free with
433 g_dbus_server_new_sync (const gchar *address,
434 GDBusServerFlags flags,
436 GDBusAuthObserver *observer,
437 GCancellable *cancellable,
442 g_return_val_if_fail (address != NULL, NULL);
443 g_return_val_if_fail (g_dbus_is_guid (guid), NULL);
444 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
446 server = g_initable_new (G_TYPE_DBUS_SERVER,
452 "authentication-observer", observer,
456 /* Right now we don't have any transport not using the listener... */
457 g_assert (server->priv->is_using_listener);
458 g_signal_connect (G_SOCKET_SERVICE (server->priv->listener),
468 * g_dbus_server_get_client_address:
469 * @server: A #GDBusServer.
471 * Gets a D-Bus address string that can be used by clients to connect
474 * Returns: A D-Bus address string. Do not free, the string is owned
480 g_dbus_server_get_client_address (GDBusServer *server)
482 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
483 return server->priv->client_address;
487 * g_dbus_server_get_guid:
488 * @server: A #GDBusServer.
490 * Gets the GUID for @server.
492 * Returns: A D-Bus GUID. Do not free this string, it is owned by @server.
497 g_dbus_server_get_guid (GDBusServer *server)
499 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
500 return server->priv->guid;
504 * g_dbus_server_get_flags:
505 * @server: A #GDBusServer.
507 * Gets the flags for @server.
509 * Returns: A set of flags from the #GDBusServerFlags enumeration.
514 g_dbus_server_get_flags (GDBusServer *server)
516 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
517 return server->priv->flags;
521 * g_dbus_server_is_active:
522 * @server: A #GDBusServer.
524 * Gets whether @server is active.
526 * Returns: %TRUE if server is active, %FALSE otherwise.
531 g_dbus_server_is_active (GDBusServer *server)
533 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
534 return server->priv->active;
538 * g_dbus_server_start:
539 * @server: A #GDBusServer.
546 g_dbus_server_start (GDBusServer *server)
548 g_return_if_fail (G_IS_DBUS_SERVER (server));
549 if (server->priv->active)
551 /* Right now we don't have any transport not using the listener... */
552 g_assert (server->priv->is_using_listener);
553 g_socket_service_start (G_SOCKET_SERVICE (server->priv->listener));
554 server->priv->active = TRUE;
555 g_object_notify (G_OBJECT (server), "active");
559 * g_dbus_server_stop:
560 * @server: A #GDBusServer.
567 g_dbus_server_stop (GDBusServer *server)
569 g_return_if_fail (G_IS_DBUS_SERVER (server));
570 if (!server->priv->active)
572 /* Right now we don't have any transport not using the listener... */
573 g_assert (server->priv->is_using_listener);
574 g_socket_service_stop (G_SOCKET_SERVICE (server->priv->listener));
575 server->priv->active = FALSE;
576 g_object_notify (G_OBJECT (server), "active");
579 /* ---------------------------------------------------------------------------------------------------- */
587 ret = g_random_int_range (0, 60);
597 /* note that address_entry has already been validated => exactly one of path, tmpdir or abstract keys are set */
599 try_unix (GDBusServer *server,
600 const gchar *address_entry,
601 GHashTable *key_value_pairs,
607 const gchar *abstract;
608 GSocketAddress *address;
613 path = g_hash_table_lookup (key_value_pairs, "path");
614 tmpdir = g_hash_table_lookup (key_value_pairs, "tmpdir");
615 abstract = g_hash_table_lookup (key_value_pairs, "abstract");
619 address = g_unix_socket_address_new (path);
621 else if (tmpdir != NULL)
628 s = g_string_new (tmpdir);
629 g_string_append (s, "/dbus-");
630 for (n = 0; n < 8; n++)
631 g_string_append_c (s, random_ascii ());
633 /* prefer abstract namespace if available */
634 if (g_unix_socket_address_abstract_names_supported ())
635 address = g_unix_socket_address_new_with_type (s->str,
637 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
639 address = g_unix_socket_address_new (s->str);
640 g_string_free (s, TRUE);
643 if (!g_socket_listener_add_address (server->priv->listener,
645 G_SOCKET_TYPE_STREAM,
646 G_SOCKET_PROTOCOL_DEFAULT,
647 NULL, /* source_object */
648 NULL, /* effective_address */
651 if (local_error->domain == G_IO_ERROR && local_error->code == G_IO_ERROR_ADDRESS_IN_USE)
653 g_error_free (local_error);
656 g_propagate_error (error, local_error);
662 else if (abstract != NULL)
664 if (!g_unix_socket_address_abstract_names_supported ())
666 g_set_error_literal (error,
668 G_IO_ERROR_NOT_SUPPORTED,
669 _("Abstract name space not supported"));
672 address = g_unix_socket_address_new_with_type (abstract,
674 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
678 g_assert_not_reached ();
681 if (!g_socket_listener_add_address (server->priv->listener,
683 G_SOCKET_TYPE_STREAM,
684 G_SOCKET_PROTOCOL_DEFAULT,
685 NULL, /* source_object */
686 NULL, /* effective_address */
696 /* Fill out client_address if the connection attempt worked */
699 server->priv->is_using_listener = TRUE;
701 switch (g_unix_socket_address_get_address_type (G_UNIX_SOCKET_ADDRESS (address)))
703 case G_UNIX_SOCKET_ADDRESS_ABSTRACT:
704 server->priv->client_address = g_strdup_printf ("unix:abstract=%s",
705 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
708 case G_UNIX_SOCKET_ADDRESS_PATH:
709 server->priv->client_address = g_strdup_printf ("unix:path=%s",
710 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
714 g_assert_not_reached ();
718 g_object_unref (address);
724 /* ---------------------------------------------------------------------------------------------------- */
726 /* note that address_entry has already been validated =>
727 * both host and port (guranteed to be a number in [0, 65535]) are set (family is optional)
730 try_tcp (GDBusServer *server,
731 const gchar *address_entry,
732 GHashTable *key_value_pairs,
741 GSocketAddress *address;
743 GList *resolved_addresses;
749 resolved_addresses = NULL;
751 host = g_hash_table_lookup (key_value_pairs, "host");
752 port = g_hash_table_lookup (key_value_pairs, "port");
753 family = g_hash_table_lookup (key_value_pairs, "family");
754 if (g_hash_table_lookup (key_value_pairs, "noncefile") != NULL)
756 g_set_error_literal (error,
758 G_IO_ERROR_INVALID_ARGUMENT,
759 _("Cannot specify nonce file when creating a server"));
767 port_num = strtol (port, NULL, 10);
769 resolver = g_resolver_get_default ();
770 resolved_addresses = g_resolver_lookup_by_name (resolver,
774 if (resolved_addresses == NULL)
777 /* TODO: handle family */
778 for (l = resolved_addresses; l != NULL; l = l->next)
780 GInetAddress *address = G_INET_ADDRESS (l->data);
781 GSocketAddress *socket_address;
782 GSocketAddress *effective_address;
784 socket_address = g_inet_socket_address_new (address, port_num);
785 if (!g_socket_listener_add_address (server->priv->listener,
787 G_SOCKET_TYPE_STREAM,
788 G_SOCKET_PROTOCOL_TCP,
789 NULL, /* GObject *source_object */
793 g_object_unref (socket_address);
797 /* make sure we allocate the same port number for other listeners */
798 port_num = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (effective_address));
800 g_object_unref (effective_address);
801 g_object_unref (socket_address);
809 gsize bytes_remaining;
811 server->priv->nonce = g_new0 (guchar, 16);
812 for (n = 0; n < 16; n++)
813 server->priv->nonce[n] = g_random_int_range (0, 256);
814 fd = g_file_open_tmp ("gdbus-nonce-file-XXXXXX",
815 &server->priv->nonce_file,
819 g_socket_listener_close (server->priv->listener);
824 bytes_remaining = 16;
825 while (bytes_remaining > 0)
828 ret = write (fd, server->priv->nonce + bytes_written, bytes_remaining);
835 g_io_error_from_errno (errno),
836 _("Error writing nonce file at `%s': %s"),
837 server->priv->nonce_file,
841 bytes_written += ret;
842 bytes_remaining -= ret;
845 server->priv->client_address = g_strdup_printf ("nonce-tcp:host=%s,port=%d,noncefile=%s",
848 server->priv->nonce_file);
852 server->priv->client_address = g_strdup_printf ("tcp:host=%s,port=%d", host, port_num);
854 server->priv->is_using_listener = TRUE;
858 g_list_foreach (resolved_addresses, (GFunc) g_object_unref, NULL);
859 g_list_free (resolved_addresses);
860 g_object_unref (resolver);
864 /* ---------------------------------------------------------------------------------------------------- */
869 GDBusConnection *connection;
873 emit_idle_data_free (EmitIdleData *data)
875 g_object_unref (data->server);
876 g_object_unref (data->connection);
881 emit_new_connection_in_idle (gpointer user_data)
883 EmitIdleData *data = user_data;
885 g_signal_emit (data->server,
886 _signals[NEW_CONNECTION_SIGNAL],
889 g_object_unref (data->connection);
894 /* Called in new thread */
896 on_run (GSocketService *service,
897 GSocketConnection *socket_connection,
898 GObject *source_object,
901 GDBusServer *server = G_DBUS_SERVER (user_data);
902 GDBusConnection *connection;
903 GDBusConnectionFlags connection_flags;
905 if (server->priv->nonce != NULL)
910 if (!g_input_stream_read_all (g_io_stream_get_input_stream (G_IO_STREAM (socket_connection)),
914 NULL, /* GCancellable */
918 if (bytes_read != 16)
921 if (memcmp (buf, server->priv->nonce, 16) != 0)
925 connection_flags = G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER;
926 if (server->priv->flags & G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS)
927 connection_flags |= G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS;
929 connection = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
932 server->priv->authentication_observer,
933 NULL, /* GCancellable */
935 if (connection == NULL)
938 if (server->priv->flags & G_DBUS_SERVER_FLAGS_RUN_IN_THREAD)
940 g_signal_emit (server,
941 _signals[NEW_CONNECTION_SIGNAL],
944 g_object_unref (connection);
948 GSource *idle_source;
951 data = g_new0 (EmitIdleData, 1);
952 data->server = g_object_ref (server);
953 data->connection = g_object_ref (connection);
955 idle_source = g_idle_source_new ();
956 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
957 g_source_set_callback (idle_source,
958 emit_new_connection_in_idle,
960 (GDestroyNotify) emit_idle_data_free);
961 g_source_attach (idle_source, server->priv->main_context_at_construction);
962 g_source_unref (idle_source);
970 initable_init (GInitable *initable,
971 GCancellable *cancellable,
974 GDBusServer *server = G_DBUS_SERVER (initable);
983 if (!g_dbus_is_guid (server->priv->guid))
985 g_set_error (&last_error,
987 G_IO_ERROR_INVALID_ARGUMENT,
988 _("The string `%s' is not a valid D-Bus GUID"),
993 server->priv->listener = G_SOCKET_LISTENER (g_threaded_socket_service_new (-1));
995 addr_array = g_strsplit (server->priv->address, ";", 0);
997 for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
999 const gchar *address_entry = addr_array[n];
1000 GHashTable *key_value_pairs;
1001 gchar *transport_name;
1005 if (g_dbus_is_supported_address (address_entry,
1007 _g_dbus_address_parse_entry (address_entry,
1017 else if (g_strcmp0 (transport_name, "unix") == 0)
1018 ret = try_unix (server, address_entry, key_value_pairs, &this_error);
1020 else if (g_strcmp0 (transport_name, "tcp") == 0)
1021 ret = try_tcp (server, address_entry, key_value_pairs, FALSE, &this_error);
1022 else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
1023 ret = try_tcp (server, address_entry, key_value_pairs, TRUE, &this_error);
1025 g_set_error (&this_error,
1027 G_IO_ERROR_INVALID_ARGUMENT,
1028 _("Cannot listen on unsupported transport `%s'"),
1031 g_free (transport_name);
1032 if (key_value_pairs != NULL)
1033 g_hash_table_unref (key_value_pairs);
1037 g_assert (this_error == NULL);
1042 if (this_error != NULL)
1044 if (last_error != NULL)
1045 g_error_free (last_error);
1046 last_error = this_error;
1056 if (last_error != NULL)
1057 g_error_free (last_error);
1061 g_assert (last_error != NULL);
1062 g_propagate_error (error, last_error);
1069 initable_iface_init (GInitableIface *initable_iface)
1071 initable_iface->init = initable_init;
1074 /* ---------------------------------------------------------------------------------------------------- */
1076 #define __G_DBUS_SERVER_C__
1077 #include "gioaliasdef.c"