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.
370 * You are guaranteed that signal handlers for this signal runs
371 * before incoming messages on @connection are processed. This means
372 * that it's suitable to call g_dbus_connection_register_object() or
373 * similar from the signal handler.
377 _signals[NEW_CONNECTION_SIGNAL] = g_signal_new ("new-connection",
380 G_STRUCT_OFFSET (GDBusServerClass, new_connection),
383 g_cclosure_marshal_VOID__OBJECT,
386 G_TYPE_DBUS_CONNECTION);
389 g_type_class_add_private (klass, sizeof (GDBusServerPrivate));
393 g_dbus_server_init (GDBusServer *server)
395 server->priv = G_TYPE_INSTANCE_GET_PRIVATE (server, G_TYPE_DBUS_SERVER, GDBusServerPrivate);
397 server->priv->main_context_at_construction = g_main_context_get_thread_default ();
398 if (server->priv->main_context_at_construction != NULL)
399 g_main_context_ref (server->priv->main_context_at_construction);
403 on_run (GSocketService *service,
404 GSocketConnection *socket_connection,
405 GObject *source_object,
409 * g_dbus_server_new_sync:
410 * @address: A D-Bus address.
411 * @flags: Flags from the #GDBusServerFlags enumeration.
412 * @guid: A D-Bus GUID.
413 * @observer: A #GDBusAuthObserver or %NULL.
414 * @cancellable: A #GCancellable or %NULL.
415 * @error: Return location for server or %NULL.
417 * Creates a new D-Bus server that listens on the first address in
418 * @address that works.
420 * Once constructed, you can use g_dbus_server_get_client_address() to
421 * get a D-Bus address string that clients can use to connect.
423 * Connect to the #GDBusServer::new-connection signal to handle
424 * incoming connections.
426 * The returned #GDBusServer isn't active - you have to start it with
427 * g_dbus_server_start().
429 * See <xref linkend="gdbus-peer-to-peer"/> for how #GDBusServer can
432 * This is a synchronous failable constructor. See
433 * g_dbus_server_new() for the asynchronous version.
435 * Returns: A #GDBusServer or %NULL if @error is set. Free with
441 g_dbus_server_new_sync (const gchar *address,
442 GDBusServerFlags flags,
444 GDBusAuthObserver *observer,
445 GCancellable *cancellable,
450 g_return_val_if_fail (address != NULL, NULL);
451 g_return_val_if_fail (g_dbus_is_guid (guid), NULL);
452 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
454 server = g_initable_new (G_TYPE_DBUS_SERVER,
460 "authentication-observer", observer,
464 /* Right now we don't have any transport not using the listener... */
465 g_assert (server->priv->is_using_listener);
466 g_signal_connect (G_SOCKET_SERVICE (server->priv->listener),
476 * g_dbus_server_get_client_address:
477 * @server: A #GDBusServer.
479 * Gets a D-Bus address string that can be used by clients to connect
482 * Returns: A D-Bus address string. Do not free, the string is owned
488 g_dbus_server_get_client_address (GDBusServer *server)
490 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
491 return server->priv->client_address;
495 * g_dbus_server_get_guid:
496 * @server: A #GDBusServer.
498 * Gets the GUID for @server.
500 * Returns: A D-Bus GUID. Do not free this string, it is owned by @server.
505 g_dbus_server_get_guid (GDBusServer *server)
507 g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
508 return server->priv->guid;
512 * g_dbus_server_get_flags:
513 * @server: A #GDBusServer.
515 * Gets the flags for @server.
517 * Returns: A set of flags from the #GDBusServerFlags enumeration.
522 g_dbus_server_get_flags (GDBusServer *server)
524 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
525 return server->priv->flags;
529 * g_dbus_server_is_active:
530 * @server: A #GDBusServer.
532 * Gets whether @server is active.
534 * Returns: %TRUE if server is active, %FALSE otherwise.
539 g_dbus_server_is_active (GDBusServer *server)
541 g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
542 return server->priv->active;
546 * g_dbus_server_start:
547 * @server: A #GDBusServer.
554 g_dbus_server_start (GDBusServer *server)
556 g_return_if_fail (G_IS_DBUS_SERVER (server));
557 if (server->priv->active)
559 /* Right now we don't have any transport not using the listener... */
560 g_assert (server->priv->is_using_listener);
561 g_socket_service_start (G_SOCKET_SERVICE (server->priv->listener));
562 server->priv->active = TRUE;
563 g_object_notify (G_OBJECT (server), "active");
567 * g_dbus_server_stop:
568 * @server: A #GDBusServer.
575 g_dbus_server_stop (GDBusServer *server)
577 g_return_if_fail (G_IS_DBUS_SERVER (server));
578 if (!server->priv->active)
580 /* Right now we don't have any transport not using the listener... */
581 g_assert (server->priv->is_using_listener);
582 g_socket_service_stop (G_SOCKET_SERVICE (server->priv->listener));
583 server->priv->active = FALSE;
584 g_object_notify (G_OBJECT (server), "active");
587 /* ---------------------------------------------------------------------------------------------------- */
595 ret = g_random_int_range (0, 60);
605 /* note that address_entry has already been validated => exactly one of path, tmpdir or abstract keys are set */
607 try_unix (GDBusServer *server,
608 const gchar *address_entry,
609 GHashTable *key_value_pairs,
615 const gchar *abstract;
616 GSocketAddress *address;
621 path = g_hash_table_lookup (key_value_pairs, "path");
622 tmpdir = g_hash_table_lookup (key_value_pairs, "tmpdir");
623 abstract = g_hash_table_lookup (key_value_pairs, "abstract");
627 address = g_unix_socket_address_new (path);
629 else if (tmpdir != NULL)
636 s = g_string_new (tmpdir);
637 g_string_append (s, "/dbus-");
638 for (n = 0; n < 8; n++)
639 g_string_append_c (s, random_ascii ());
641 /* prefer abstract namespace if available */
642 if (g_unix_socket_address_abstract_names_supported ())
643 address = g_unix_socket_address_new_with_type (s->str,
645 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
647 address = g_unix_socket_address_new (s->str);
648 g_string_free (s, TRUE);
651 if (!g_socket_listener_add_address (server->priv->listener,
653 G_SOCKET_TYPE_STREAM,
654 G_SOCKET_PROTOCOL_DEFAULT,
655 NULL, /* source_object */
656 NULL, /* effective_address */
659 if (local_error->domain == G_IO_ERROR && local_error->code == G_IO_ERROR_ADDRESS_IN_USE)
661 g_error_free (local_error);
664 g_propagate_error (error, local_error);
670 else if (abstract != NULL)
672 if (!g_unix_socket_address_abstract_names_supported ())
674 g_set_error_literal (error,
676 G_IO_ERROR_NOT_SUPPORTED,
677 _("Abstract name space not supported"));
680 address = g_unix_socket_address_new_with_type (abstract,
682 G_UNIX_SOCKET_ADDRESS_ABSTRACT);
686 g_assert_not_reached ();
689 if (!g_socket_listener_add_address (server->priv->listener,
691 G_SOCKET_TYPE_STREAM,
692 G_SOCKET_PROTOCOL_DEFAULT,
693 NULL, /* source_object */
694 NULL, /* effective_address */
704 /* Fill out client_address if the connection attempt worked */
707 server->priv->is_using_listener = TRUE;
709 switch (g_unix_socket_address_get_address_type (G_UNIX_SOCKET_ADDRESS (address)))
711 case G_UNIX_SOCKET_ADDRESS_ABSTRACT:
712 server->priv->client_address = g_strdup_printf ("unix:abstract=%s",
713 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
716 case G_UNIX_SOCKET_ADDRESS_PATH:
717 server->priv->client_address = g_strdup_printf ("unix:path=%s",
718 g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
722 g_assert_not_reached ();
726 g_object_unref (address);
732 /* ---------------------------------------------------------------------------------------------------- */
734 /* note that address_entry has already been validated =>
735 * both host and port (guranteed to be a number in [0, 65535]) are set (family is optional)
738 try_tcp (GDBusServer *server,
739 const gchar *address_entry,
740 GHashTable *key_value_pairs,
749 GSocketAddress *address;
751 GList *resolved_addresses;
757 resolved_addresses = NULL;
759 host = g_hash_table_lookup (key_value_pairs, "host");
760 port = g_hash_table_lookup (key_value_pairs, "port");
761 family = g_hash_table_lookup (key_value_pairs, "family");
762 if (g_hash_table_lookup (key_value_pairs, "noncefile") != NULL)
764 g_set_error_literal (error,
766 G_IO_ERROR_INVALID_ARGUMENT,
767 _("Cannot specify nonce file when creating a server"));
775 port_num = strtol (port, NULL, 10);
777 resolver = g_resolver_get_default ();
778 resolved_addresses = g_resolver_lookup_by_name (resolver,
782 if (resolved_addresses == NULL)
785 /* TODO: handle family */
786 for (l = resolved_addresses; l != NULL; l = l->next)
788 GInetAddress *address = G_INET_ADDRESS (l->data);
789 GSocketAddress *socket_address;
790 GSocketAddress *effective_address;
792 socket_address = g_inet_socket_address_new (address, port_num);
793 if (!g_socket_listener_add_address (server->priv->listener,
795 G_SOCKET_TYPE_STREAM,
796 G_SOCKET_PROTOCOL_TCP,
797 NULL, /* GObject *source_object */
801 g_object_unref (socket_address);
805 /* make sure we allocate the same port number for other listeners */
806 port_num = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (effective_address));
808 g_object_unref (effective_address);
809 g_object_unref (socket_address);
817 gsize bytes_remaining;
819 server->priv->nonce = g_new0 (guchar, 16);
820 for (n = 0; n < 16; n++)
821 server->priv->nonce[n] = g_random_int_range (0, 256);
822 fd = g_file_open_tmp ("gdbus-nonce-file-XXXXXX",
823 &server->priv->nonce_file,
827 g_socket_listener_close (server->priv->listener);
832 bytes_remaining = 16;
833 while (bytes_remaining > 0)
836 ret = write (fd, server->priv->nonce + bytes_written, bytes_remaining);
843 g_io_error_from_errno (errno),
844 _("Error writing nonce file at `%s': %s"),
845 server->priv->nonce_file,
849 bytes_written += ret;
850 bytes_remaining -= ret;
853 server->priv->client_address = g_strdup_printf ("nonce-tcp:host=%s,port=%d,noncefile=%s",
856 server->priv->nonce_file);
860 server->priv->client_address = g_strdup_printf ("tcp:host=%s,port=%d", host, port_num);
862 server->priv->is_using_listener = TRUE;
866 g_list_foreach (resolved_addresses, (GFunc) g_object_unref, NULL);
867 g_list_free (resolved_addresses);
868 g_object_unref (resolver);
872 /* ---------------------------------------------------------------------------------------------------- */
877 GDBusConnection *connection;
881 emit_idle_data_free (EmitIdleData *data)
883 g_object_unref (data->server);
884 g_object_unref (data->connection);
889 emit_new_connection_in_idle (gpointer user_data)
891 EmitIdleData *data = user_data;
893 g_signal_emit (data->server,
894 _signals[NEW_CONNECTION_SIGNAL],
897 g_dbus_connection_start_message_processing (data->connection);
898 g_object_unref (data->connection);
903 /* Called in new thread */
905 on_run (GSocketService *service,
906 GSocketConnection *socket_connection,
907 GObject *source_object,
910 GDBusServer *server = G_DBUS_SERVER (user_data);
911 GDBusConnection *connection;
912 GDBusConnectionFlags connection_flags;
914 if (server->priv->nonce != NULL)
919 if (!g_input_stream_read_all (g_io_stream_get_input_stream (G_IO_STREAM (socket_connection)),
923 NULL, /* GCancellable */
927 if (bytes_read != 16)
930 if (memcmp (buf, server->priv->nonce, 16) != 0)
935 G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER |
936 G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING;
937 if (server->priv->flags & G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS)
938 connection_flags |= G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS;
940 connection = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
943 server->priv->authentication_observer,
944 NULL, /* GCancellable */
946 if (connection == NULL)
949 if (server->priv->flags & G_DBUS_SERVER_FLAGS_RUN_IN_THREAD)
951 g_signal_emit (server,
952 _signals[NEW_CONNECTION_SIGNAL],
955 g_dbus_connection_start_message_processing (connection);
956 g_object_unref (connection);
960 GSource *idle_source;
963 data = g_new0 (EmitIdleData, 1);
964 data->server = g_object_ref (server);
965 data->connection = g_object_ref (connection);
967 idle_source = g_idle_source_new ();
968 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
969 g_source_set_callback (idle_source,
970 emit_new_connection_in_idle,
972 (GDestroyNotify) emit_idle_data_free);
973 g_source_attach (idle_source, server->priv->main_context_at_construction);
974 g_source_unref (idle_source);
982 initable_init (GInitable *initable,
983 GCancellable *cancellable,
986 GDBusServer *server = G_DBUS_SERVER (initable);
995 if (!g_dbus_is_guid (server->priv->guid))
997 g_set_error (&last_error,
999 G_IO_ERROR_INVALID_ARGUMENT,
1000 _("The string `%s' is not a valid D-Bus GUID"),
1001 server->priv->guid);
1005 server->priv->listener = G_SOCKET_LISTENER (g_threaded_socket_service_new (-1));
1007 addr_array = g_strsplit (server->priv->address, ";", 0);
1009 for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
1011 const gchar *address_entry = addr_array[n];
1012 GHashTable *key_value_pairs;
1013 gchar *transport_name;
1017 if (g_dbus_is_supported_address (address_entry,
1019 _g_dbus_address_parse_entry (address_entry,
1029 else if (g_strcmp0 (transport_name, "unix") == 0)
1030 ret = try_unix (server, address_entry, key_value_pairs, &this_error);
1032 else if (g_strcmp0 (transport_name, "tcp") == 0)
1033 ret = try_tcp (server, address_entry, key_value_pairs, FALSE, &this_error);
1034 else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
1035 ret = try_tcp (server, address_entry, key_value_pairs, TRUE, &this_error);
1037 g_set_error (&this_error,
1039 G_IO_ERROR_INVALID_ARGUMENT,
1040 _("Cannot listen on unsupported transport `%s'"),
1043 g_free (transport_name);
1044 if (key_value_pairs != NULL)
1045 g_hash_table_unref (key_value_pairs);
1049 g_assert (this_error == NULL);
1054 if (this_error != NULL)
1056 if (last_error != NULL)
1057 g_error_free (last_error);
1058 last_error = this_error;
1068 if (last_error != NULL)
1069 g_error_free (last_error);
1073 g_assert (last_error != NULL);
1074 g_propagate_error (error, last_error);
1081 initable_iface_init (GInitableIface *initable_iface)
1083 initable_iface->init = initable_init;
1086 /* ---------------------------------------------------------------------------------------------------- */
1088 #define __G_DBUS_SERVER_C__
1089 #include "gioaliasdef.c"