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>
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 if (G_OBJECT_CLASS (g_dbus_server_parent_class)->finalize != NULL)
138 G_OBJECT_CLASS (g_dbus_server_parent_class)->finalize (object);
142 g_dbus_server_get_property (GObject *object,
147 GDBusServer *server = G_DBUS_SERVER (object);
152 g_value_set_flags (value, server->priv->flags);
156 g_value_set_string (value, server->priv->guid);
160 g_value_set_string (value, server->priv->address);
163 case PROP_CLIENT_ADDRESS:
164 g_value_set_string (value, server->priv->client_address);
168 g_value_set_boolean (value, server->priv->active);
171 case PROP_AUTHENTICATION_OBSERVER:
172 g_value_set_object (value, server->priv->authentication_observer);
176 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
182 g_dbus_server_set_property (GObject *object,
187 GDBusServer *server = G_DBUS_SERVER (object);
192 server->priv->flags = g_value_get_flags (value);
196 server->priv->guid = g_value_dup_string (value);
200 server->priv->address = g_value_dup_string (value);
203 case PROP_AUTHENTICATION_OBSERVER:
204 server->priv->authentication_observer = g_value_dup_object (value);
208 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
214 g_dbus_server_class_init (GDBusServerClass *klass)
216 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
218 gobject_class->finalize = g_dbus_server_finalize;
219 gobject_class->set_property = g_dbus_server_set_property;
220 gobject_class->get_property = g_dbus_server_get_property;
225 * Flags from the #GDBusServerFlags enumeration.
229 g_object_class_install_property (gobject_class,
231 g_param_spec_flags ("flags",
233 _("Flags for the server"),
234 G_TYPE_DBUS_SERVER_FLAGS,
235 G_DBUS_SERVER_FLAGS_NONE,
238 G_PARAM_CONSTRUCT_ONLY |
239 G_PARAM_STATIC_NAME |
240 G_PARAM_STATIC_BLURB |
241 G_PARAM_STATIC_NICK));
246 * The guid of the server.
250 g_object_class_install_property (gobject_class,
252 g_param_spec_string ("guid",
254 _("The guid of the server"),
258 G_PARAM_CONSTRUCT_ONLY |
259 G_PARAM_STATIC_NAME |
260 G_PARAM_STATIC_BLURB |
261 G_PARAM_STATIC_NICK));
264 * GDBusServer:address:
266 * The D-Bus address to listen on.
270 g_object_class_install_property (gobject_class,
272 g_param_spec_string ("address",
274 _("The address to listen on"),
278 G_PARAM_CONSTRUCT_ONLY |
279 G_PARAM_STATIC_NAME |
280 G_PARAM_STATIC_BLURB |
281 G_PARAM_STATIC_NICK));
284 * GDBusServer:client-address:
286 * The D-Bus address that clients can use.
290 g_object_class_install_property (gobject_class,
292 g_param_spec_string ("client-address",
294 _("The address clients can use"),
297 G_PARAM_STATIC_NAME |
298 G_PARAM_STATIC_BLURB |
299 G_PARAM_STATIC_NICK));
302 * GDBusServer:active:
304 * Whether the server is currently active.
308 g_object_class_install_property (gobject_class,
310 g_param_spec_string ("active",
312 _("Whether the server is currently active"),
315 G_PARAM_STATIC_NAME |
316 G_PARAM_STATIC_BLURB |
317 G_PARAM_STATIC_NICK));
320 * GDBusServer:authentication-observer:
322 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
326 g_object_class_install_property (gobject_class,
327 PROP_AUTHENTICATION_OBSERVER,
328 g_param_spec_object ("authentication-observer",
329 _("Authentication Observer"),
330 _("Object used to assist in the authentication process"),
331 G_TYPE_DBUS_AUTH_OBSERVER,
334 G_PARAM_CONSTRUCT_ONLY |
335 G_PARAM_STATIC_NAME |
336 G_PARAM_STATIC_BLURB |
337 G_PARAM_STATIC_NICK));
340 * GDBusServer::new-connection:
341 * @server: The #GDBusServer emitting the signal.
342 * @connection: A #GDBusConnection for the new connection.
344 * Emitted when a new authenticated connection has been made. Use
345 * g_dbus_connection_get_peer_credentials() to figure out what
346 * identity (if any), was authenticated.
348 * If you want to accept the connection, simply ref the @connection
349 * object. Then call g_dbus_connection_close() and unref it when you
350 * are done with it. A typical thing to do when accepting a
351 * connection is to listen to the #GDBusConnection::closed signal.
353 * If #GDBusServer:flags contains %G_DBUS_SERVER_FLAGS_RUN_IN_THREAD
354 * then the signal is emitted in a new thread dedicated to the
355 * connection. Otherwise the signal is emitted in the <link
356 * linkend="g-main-context-push-thread-default">thread-default main
357 * loop</link> of the thread that @server was constructed in.
361 _signals[NEW_CONNECTION_SIGNAL] = g_signal_new ("new-connection",
364 G_STRUCT_OFFSET (GDBusServerClass, new_connection),
367 g_cclosure_marshal_VOID__OBJECT,
370 G_TYPE_DBUS_CONNECTION);
373 g_type_class_add_private (klass, sizeof (GDBusServerPrivate));
377 g_dbus_server_init (GDBusServer *server)
379 server->priv = G_TYPE_INSTANCE_GET_PRIVATE (server, G_TYPE_DBUS_SERVER, GDBusServerPrivate);
381 server->priv->main_context_at_construction = g_main_context_get_thread_default ();
382 if (server->priv->main_context_at_construction != NULL)
383 g_main_context_ref (server->priv->main_context_at_construction);
387 on_run (GSocketService *service,
388 GSocketConnection *socket_connection,
389 GObject *source_object,
393 * g_dbus_server_new_sync:
394 * @address: A D-Bus address.
395 * @flags: Flags from the #GDBusServerFlags enumeration.
396 * @guid: A D-Bus GUID.
397 * @observer: A #GDBusAuthObserver or %NULL.
398 * @cancellable: A #GCancellable or %NULL.
399 * @error: Return location for server or %NULL.
401 * Creates a new D-Bus server that listens on the first address in
402 * @address that works.
404 * Once constructed, you can use g_dbus_server_get_client_address() to
405 * get a D-Bus address string that clients can use to connect.
407 * Connect to the #GDBusServer::new-connection signal to handle
408 * incoming connections.
410 * The returned #GDBusServer isn't active - you have to start it with
411 * g_dbus_server_start().
413 * See <xref linkend="gdbus-peer-to-peer"/> for how #GDBusServer can
416 * This is a synchronous failable constructor. See
417 * g_dbus_server_new() for the asynchronous version.
419 * Returns: A #GDBusServer or %NULL if @error is set. Free with
425 g_dbus_server_new_sync (const gchar *address,
426 GDBusServerFlags flags,
428 GDBusAuthObserver *observer,
429 GCancellable *cancellable,
434 g_return_val_if_fail (address != NULL, NULL);
435 g_return_val_if_fail (g_dbus_is_guid (guid), NULL);
436 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
438 server = g_initable_new (G_TYPE_DBUS_SERVER,
444 "authentication-observer", observer,
448 /* Right now we don't have any transport not using the listener... */
449 g_assert (server->priv->is_using_listener);
450 g_signal_connect (G_SOCKET_SERVICE (server->priv->listener),
460 * g_dbus_server_get_client_address:
461 * @server: A #GDBusServer.
463 * Gets a D-Bus address string that can be used by clients to connect
466 * Returns: A D-Bus address string. Do not free, the string is owned
472 g_dbus_server_get_client_address (GDBusServer *server)
474 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
475 return server->priv->client_address;
479 * g_dbus_server_get_guid:
480 * @server: A #GDBusServer.
482 * Gets the GUID for @server.
484 * Returns: A D-Bus GUID. Do not free this string, it is owned by @server.
489 g_dbus_server_get_guid (GDBusServer *server)
491 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
492 return server->priv->guid;
496 * g_dbus_server_get_flags:
497 * @server: A #GDBusServer.
499 * Gets the flags for @server.
501 * Returns: A set of flags from the #GDBusServerFlags enumeration.
506 g_dbus_server_get_flags (GDBusServer *server)
508 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
509 return server->priv->flags;
513 * g_dbus_server_is_active:
514 * @server: A #GDBusServer.
516 * Gets whether @server is active.
518 * Returns: %TRUE if server is active, %FALSE otherwise.
523 g_dbus_server_is_active (GDBusServer *server)
525 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
526 return server->priv->active;
530 * g_dbus_server_start:
531 * @server: A #GDBusServer.
538 g_dbus_server_start (GDBusServer *server)
540 g_return_if_fail (G_IS_DBUS_SERVER (server));
541 if (server->priv->active)
543 /* Right now we don't have any transport not using the listener... */
544 g_assert (server->priv->is_using_listener);
545 g_socket_service_start (G_SOCKET_SERVICE (server->priv->listener));
546 server->priv->active = TRUE;
547 g_object_notify (G_OBJECT (server), "active");
551 * g_dbus_server_stop:
552 * @server: A #GDBusServer.
559 g_dbus_server_stop (GDBusServer *server)
561 g_return_if_fail (G_IS_DBUS_SERVER (server));
562 if (!server->priv->active)
564 /* Right now we don't have any transport not using the listener... */
565 g_assert (server->priv->is_using_listener);
566 g_socket_service_stop (G_SOCKET_SERVICE (server->priv->listener));
567 server->priv->active = FALSE;
568 g_object_notify (G_OBJECT (server), "active");
571 /* ---------------------------------------------------------------------------------------------------- */
579 ret = g_random_int_range (0, 60);
589 /* note that address_entry has already been validated => exactly one of path, tmpdir or abstract keys are set */
591 try_unix (GDBusServer *server,
592 const gchar *address_entry,
593 GHashTable *key_value_pairs,
599 const gchar *abstract;
600 GSocketAddress *address;
605 path = g_hash_table_lookup (key_value_pairs, "path");
606 tmpdir = g_hash_table_lookup (key_value_pairs, "tmpdir");
607 abstract = g_hash_table_lookup (key_value_pairs, "abstract");
611 address = g_unix_socket_address_new (path);
613 else if (tmpdir != NULL)
620 s = g_string_new (tmpdir);
621 g_string_append (s, "/dbus-");
622 for (n = 0; n < 8; n++)
623 g_string_append_c (s, random_ascii ());
625 /* prefer abstract namespace if available */
626 if (g_unix_socket_address_abstract_names_supported ())
627 address = g_unix_socket_address_new_with_type (s->str,
629 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
631 address = g_unix_socket_address_new (s->str);
632 g_string_free (s, TRUE);
635 if (!g_socket_listener_add_address (server->priv->listener,
637 G_SOCKET_TYPE_STREAM,
638 G_SOCKET_PROTOCOL_DEFAULT,
639 NULL, /* source_object */
640 NULL, /* effective_address */
643 if (local_error->domain == G_IO_ERROR && local_error->code == G_IO_ERROR_ADDRESS_IN_USE)
645 g_error_free (local_error);
648 g_propagate_error (error, local_error);
654 else if (abstract != NULL)
656 if (!g_unix_socket_address_abstract_names_supported ())
658 g_set_error_literal (error,
660 G_IO_ERROR_NOT_SUPPORTED,
661 _("Abstract name space not supported"));
664 address = g_unix_socket_address_new_with_type (abstract,
666 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
670 g_assert_not_reached ();
673 if (!g_socket_listener_add_address (server->priv->listener,
675 G_SOCKET_TYPE_STREAM,
676 G_SOCKET_PROTOCOL_DEFAULT,
677 NULL, /* source_object */
678 NULL, /* effective_address */
688 /* Fill out client_address if the connection attempt worked */
691 server->priv->is_using_listener = TRUE;
693 switch (g_unix_socket_address_get_address_type (G_UNIX_SOCKET_ADDRESS (address)))
695 case G_UNIX_SOCKET_ADDRESS_ABSTRACT:
696 server->priv->client_address = g_strdup_printf ("unix:abstract=%s",
697 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
700 case G_UNIX_SOCKET_ADDRESS_PATH:
701 server->priv->client_address = g_strdup_printf ("unix:path=%s",
702 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
706 g_assert_not_reached ();
710 g_object_unref (address);
716 /* ---------------------------------------------------------------------------------------------------- */
718 /* note that address_entry has already been validated =>
719 * both host and port (guranteed to be a number in [0, 65535]) are set (family is optional)
722 try_tcp (GDBusServer *server,
723 const gchar *address_entry,
724 GHashTable *key_value_pairs,
733 GSocketAddress *address;
735 GList *resolved_addresses;
741 resolved_addresses = NULL;
743 host = g_hash_table_lookup (key_value_pairs, "host");
744 port = g_hash_table_lookup (key_value_pairs, "port");
745 family = g_hash_table_lookup (key_value_pairs, "family");
746 if (g_hash_table_lookup (key_value_pairs, "noncefile") != NULL)
748 g_set_error_literal (error,
750 G_IO_ERROR_INVALID_ARGUMENT,
751 _("Cannot specify nonce file when creating a server"));
759 port_num = strtol (port, NULL, 10);
761 resolver = g_resolver_get_default ();
762 resolved_addresses = g_resolver_lookup_by_name (resolver,
766 if (resolved_addresses == NULL)
770 /* TODO: handle family */
771 for (l = resolved_addresses; l != NULL; l = l->next)
773 GInetAddress *address = G_INET_ADDRESS (l->data);
774 GSocketAddress *socket_address;
775 GSocketAddress *effective_address;
777 socket_address = g_inet_socket_address_new (address, port_num);
778 if (!g_socket_listener_add_address (server->priv->listener,
780 G_SOCKET_TYPE_STREAM,
781 G_SOCKET_PROTOCOL_TCP,
782 NULL, /* GObject *source_object */
786 g_object_unref (socket_address);
791 /* make sure we allocate the same port number for other listeners */
792 port_num = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (effective_address));
794 g_object_unref (effective_address);
795 g_object_unref (socket_address);
803 gsize bytes_remaining;
805 server->priv->nonce = g_new0 (guchar, 16);
806 for (n = 0; n < 16; n++)
807 server->priv->nonce[n] = g_random_int_range (0, 256);
808 fd = g_file_open_tmp ("gdbus-nonce-file-XXXXXX",
809 &server->priv->nonce_file,
813 g_socket_listener_close (server->priv->listener);
818 bytes_remaining = 16;
819 while (bytes_remaining > 0)
822 ret = write (fd, server->priv->nonce + bytes_written, bytes_remaining);
829 g_io_error_from_errno (errno),
830 _("Error writing nonce file at `%s': %s"),
831 server->priv->nonce_file,
835 bytes_written += ret;
836 bytes_remaining -= ret;
839 server->priv->client_address = g_strdup_printf ("nonce-tcp:host=%s,port=%d,noncefile=%s",
842 server->priv->nonce_file);
846 server->priv->client_address = g_strdup_printf ("tcp:host=%s,port=%d", host, port_num);
848 server->priv->is_using_listener = TRUE;
852 g_list_foreach (resolved_addresses, (GFunc) g_object_unref, NULL);
853 g_list_free (resolved_addresses);
854 g_object_unref (resolver);
858 /* ---------------------------------------------------------------------------------------------------- */
863 GDBusConnection *connection;
867 emit_idle_data_free (EmitIdleData *data)
869 g_object_unref (data->server);
870 g_object_unref (data->connection);
875 emit_new_connection_in_idle (gpointer user_data)
877 EmitIdleData *data = user_data;
879 g_signal_emit (data->server,
880 _signals[NEW_CONNECTION_SIGNAL],
883 g_object_unref (data->connection);
888 /* Called in new thread */
890 on_run (GSocketService *service,
891 GSocketConnection *socket_connection,
892 GObject *source_object,
895 GDBusServer *server = G_DBUS_SERVER (user_data);
896 GDBusConnection *connection;
897 GDBusConnectionFlags connection_flags;
899 if (server->priv->nonce != NULL)
904 if (!g_input_stream_read_all (g_io_stream_get_input_stream (G_IO_STREAM (socket_connection)),
908 NULL, /* GCancellable */
912 if (bytes_read != 16)
915 if (memcmp (buf, server->priv->nonce, 16) != 0)
919 connection_flags = G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER;
920 if (server->priv->flags & G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS)
921 connection_flags |= G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS;
923 connection = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
926 server->priv->authentication_observer,
927 NULL, /* GCancellable */
929 if (connection == NULL)
932 if (server->priv->flags & G_DBUS_SERVER_FLAGS_RUN_IN_THREAD)
934 g_signal_emit (server,
935 _signals[NEW_CONNECTION_SIGNAL],
938 g_object_unref (connection);
942 GSource *idle_source;
945 data = g_new0 (EmitIdleData, 1);
946 data->server = g_object_ref (server);
947 data->connection = g_object_ref (connection);
949 idle_source = g_idle_source_new ();
950 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
951 g_source_set_callback (idle_source,
952 emit_new_connection_in_idle,
954 (GDestroyNotify) emit_idle_data_free);
955 g_source_attach (idle_source, server->priv->main_context_at_construction);
956 g_source_unref (idle_source);
964 initable_init (GInitable *initable,
965 GCancellable *cancellable,
968 GDBusServer *server = G_DBUS_SERVER (initable);
977 if (!g_dbus_is_guid (server->priv->guid))
979 g_set_error (&last_error,
981 G_IO_ERROR_INVALID_ARGUMENT,
982 _("The string `%s' is not a valid D-Bus GUID"),
987 server->priv->listener = G_SOCKET_LISTENER (g_threaded_socket_service_new (-1));
989 addr_array = g_strsplit (server->priv->address, ";", 0);
991 for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
993 const gchar *address_entry = addr_array[n];
994 GHashTable *key_value_pairs;
995 gchar *transport_name;
999 if (g_dbus_is_supported_address (address_entry,
1001 _g_dbus_address_parse_entry (address_entry,
1011 else if (g_strcmp0 (transport_name, "unix") == 0)
1013 ret = try_unix (server, address_entry, key_value_pairs, &this_error);
1016 else if (g_strcmp0 (transport_name, "tcp") == 0)
1018 ret = try_tcp (server, address_entry, key_value_pairs, FALSE, &this_error);
1020 else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
1022 ret = try_tcp (server, address_entry, key_value_pairs, TRUE, &this_error);
1026 g_set_error (&this_error,
1028 G_IO_ERROR_INVALID_ARGUMENT,
1029 _("Cannot listen on unsupported transport `%s'"),
1033 g_free (transport_name);
1034 if (key_value_pairs != NULL)
1035 g_hash_table_unref (key_value_pairs);
1039 g_assert (this_error == NULL);
1044 if (this_error != NULL)
1046 if (last_error != NULL)
1047 g_error_free (last_error);
1048 last_error = this_error;
1058 if (last_error != NULL)
1059 g_error_free (last_error);
1063 g_assert (last_error != NULL);
1064 g_propagate_error (error, last_error);
1071 initable_iface_init (GInitableIface *initable_iface)
1073 initable_iface->init = initable_init;
1076 /* ---------------------------------------------------------------------------------------------------- */
1078 #define __G_DBUS_SERVER_C__
1079 #include "gioaliasdef.c"