Merge branch 'master' into gdbus-codegen
[platform/upstream/glib.git] / gio / gdbusserver.c
1 /* GDBus - GLib D-Bus Library
2  *
3  * Copyright (C) 2008-2010 Red Hat, Inc.
4  *
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.
9  *
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.
14  *
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.
19  *
20  * Author: David Zeuthen <davidz@redhat.com>
21  */
22
23 #include "config.h"
24
25 #include <stdlib.h>
26 #include <string.h>
27 #include <errno.h>
28 #ifdef HAVE_UNISTD_H
29 #include <unistd.h>
30 #endif
31 #ifdef _WIN32
32 #include <io.h>
33 #endif
34
35 #include "giotypes.h"
36 #include "gioerror.h"
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"
53
54 #ifdef G_OS_UNIX
55 #include "gunixsocketaddress.h"
56 #endif
57
58 #include "glibintl.h"
59
60 /**
61  * SECTION:gdbusserver
62  * @short_description: Helper for accepting connections
63  * @include: gio/gio.h
64  *
65  * #GDBusServer is a helper for listening to and accepting D-Bus
66  * connections. This can be used to create a new D-Bus server, allowing two
67  * peers to use the D-Bus protocol for their own specialized communication.
68  * A server instance provided in this way will not perform message routing or
69  * implement the org.freedesktop.DBus interface.
70  *
71  * To just export an object on a well-known name on a message bus, such as the
72  * session or system bus, you should instead use g_bus_own_name().
73  *
74  * <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  */
76
77 /**
78  * GDBusServer:
79  *
80  * The #GDBusServer structure contains only private data and
81  * should only be accessed using the provided API.
82  *
83  * Since: 2.26
84  */
85 struct _GDBusServer
86 {
87   /*< private >*/
88   GObject parent_instance;
89
90   GDBusServerFlags flags;
91   gchar *address;
92   gchar *guid;
93
94   guchar *nonce;
95   gchar *nonce_file;
96
97   gchar *client_address;
98
99   GSocketListener *listener;
100   gboolean is_using_listener;
101   gulong run_signal_handler_id;
102
103   /* The result of g_main_context_get_thread_default() when the object
104    * was created (the GObject _init() function) - this is used for delivery
105    * of the :new-connection GObject signal.
106    */
107   GMainContext *main_context_at_construction;
108
109   gboolean active;
110
111   GDBusAuthObserver *authentication_observer;
112 };
113
114 typedef struct _GDBusServerClass GDBusServerClass;
115
116 /**
117  * GDBusServerClass:
118  * @new_connection: Signal class handler for the #GDBusServer::new-connection signal.
119  *
120  * Class structure for #GDBusServer.
121  *
122  * Since: 2.26
123  */
124 struct _GDBusServerClass
125 {
126   /*< private >*/
127   GObjectClass parent_class;
128
129   /*< public >*/
130   /* Signals */
131   gboolean (*new_connection) (GDBusServer      *server,
132                               GDBusConnection  *connection);
133 };
134
135 enum
136 {
137   PROP_0,
138   PROP_ADDRESS,
139   PROP_CLIENT_ADDRESS,
140   PROP_FLAGS,
141   PROP_GUID,
142   PROP_ACTIVE,
143   PROP_AUTHENTICATION_OBSERVER,
144 };
145
146 enum
147 {
148   NEW_CONNECTION_SIGNAL,
149   LAST_SIGNAL,
150 };
151
152 guint _signals[LAST_SIGNAL] = {0};
153
154 static void initable_iface_init       (GInitableIface *initable_iface);
155
156 G_DEFINE_TYPE_WITH_CODE (GDBusServer, g_dbus_server, G_TYPE_OBJECT,
157                          G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
158                          );
159
160 static void
161 g_dbus_server_finalize (GObject *object)
162 {
163   GDBusServer *server = G_DBUS_SERVER (object);
164
165   if (server->authentication_observer != NULL)
166     g_object_unref (server->authentication_observer);
167
168   if (server->run_signal_handler_id > 0)
169     g_signal_handler_disconnect (server->listener, server->run_signal_handler_id);
170
171   if (server->listener != NULL)
172     g_object_unref (server->listener);
173
174   g_free (server->address);
175   g_free (server->guid);
176   g_free (server->client_address);
177   if (server->nonce != NULL)
178     {
179       memset (server->nonce, '\0', 16);
180       g_free (server->nonce);
181     }
182   /* we could unlink the nonce file but I don't
183    * think it's really worth the effort/risk
184    */
185   g_free (server->nonce_file);
186
187   if (server->main_context_at_construction != NULL)
188     g_main_context_unref (server->main_context_at_construction);
189
190   G_OBJECT_CLASS (g_dbus_server_parent_class)->finalize (object);
191 }
192
193 static void
194 g_dbus_server_get_property (GObject    *object,
195                             guint       prop_id,
196                             GValue     *value,
197                             GParamSpec *pspec)
198 {
199   GDBusServer *server = G_DBUS_SERVER (object);
200
201   switch (prop_id)
202     {
203     case PROP_FLAGS:
204       g_value_set_flags (value, server->flags);
205       break;
206
207     case PROP_GUID:
208       g_value_set_string (value, server->guid);
209       break;
210
211     case PROP_ADDRESS:
212       g_value_set_string (value, server->address);
213       break;
214
215     case PROP_CLIENT_ADDRESS:
216       g_value_set_string (value, server->client_address);
217       break;
218
219     case PROP_ACTIVE:
220       g_value_set_boolean (value, server->active);
221       break;
222
223     case PROP_AUTHENTICATION_OBSERVER:
224       g_value_set_object (value, server->authentication_observer);
225       break;
226
227     default:
228       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
229       break;
230     }
231 }
232
233 static void
234 g_dbus_server_set_property (GObject      *object,
235                             guint         prop_id,
236                             const GValue *value,
237                             GParamSpec   *pspec)
238 {
239   GDBusServer *server = G_DBUS_SERVER (object);
240
241   switch (prop_id)
242     {
243     case PROP_FLAGS:
244       server->flags = g_value_get_flags (value);
245       break;
246
247     case PROP_GUID:
248       server->guid = g_value_dup_string (value);
249       break;
250
251     case PROP_ADDRESS:
252       server->address = g_value_dup_string (value);
253       break;
254
255     case PROP_AUTHENTICATION_OBSERVER:
256       server->authentication_observer = g_value_dup_object (value);
257       break;
258
259     default:
260       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
261       break;
262     }
263 }
264
265 static void
266 g_dbus_server_class_init (GDBusServerClass *klass)
267 {
268   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
269
270   gobject_class->finalize     = g_dbus_server_finalize;
271   gobject_class->set_property = g_dbus_server_set_property;
272   gobject_class->get_property = g_dbus_server_get_property;
273
274   /**
275    * GDBusServer:flags:
276    *
277    * Flags from the #GDBusServerFlags enumeration.
278    *
279    * Since: 2.26
280    */
281   g_object_class_install_property (gobject_class,
282                                    PROP_FLAGS,
283                                    g_param_spec_flags ("flags",
284                                                        P_("Flags"),
285                                                        P_("Flags for the server"),
286                                                        G_TYPE_DBUS_SERVER_FLAGS,
287                                                        G_DBUS_SERVER_FLAGS_NONE,
288                                                        G_PARAM_READABLE |
289                                                        G_PARAM_WRITABLE |
290                                                        G_PARAM_CONSTRUCT_ONLY |
291                                                        G_PARAM_STATIC_NAME |
292                                                        G_PARAM_STATIC_BLURB |
293                                                        G_PARAM_STATIC_NICK));
294
295   /**
296    * GDBusServer:guid:
297    *
298    * The guid of the server.
299    *
300    * Since: 2.26
301    */
302   g_object_class_install_property (gobject_class,
303                                    PROP_GUID,
304                                    g_param_spec_string ("guid",
305                                                         P_("GUID"),
306                                                         P_("The guid of the server"),
307                                                         NULL,
308                                                         G_PARAM_READABLE |
309                                                         G_PARAM_WRITABLE |
310                                                         G_PARAM_CONSTRUCT_ONLY |
311                                                         G_PARAM_STATIC_NAME |
312                                                         G_PARAM_STATIC_BLURB |
313                                                         G_PARAM_STATIC_NICK));
314
315   /**
316    * GDBusServer:address:
317    *
318    * The D-Bus address to listen on.
319    *
320    * Since: 2.26
321    */
322   g_object_class_install_property (gobject_class,
323                                    PROP_ADDRESS,
324                                    g_param_spec_string ("address",
325                                                         P_("Address"),
326                                                         P_("The address to listen on"),
327                                                         NULL,
328                                                         G_PARAM_READABLE |
329                                                         G_PARAM_WRITABLE |
330                                                         G_PARAM_CONSTRUCT_ONLY |
331                                                         G_PARAM_STATIC_NAME |
332                                                         G_PARAM_STATIC_BLURB |
333                                                         G_PARAM_STATIC_NICK));
334
335   /**
336    * GDBusServer:client-address:
337    *
338    * The D-Bus address that clients can use.
339    *
340    * Since: 2.26
341    */
342   g_object_class_install_property (gobject_class,
343                                    PROP_CLIENT_ADDRESS,
344                                    g_param_spec_string ("client-address",
345                                                         P_("Client Address"),
346                                                         P_("The address clients can use"),
347                                                         NULL,
348                                                         G_PARAM_READABLE |
349                                                         G_PARAM_STATIC_NAME |
350                                                         G_PARAM_STATIC_BLURB |
351                                                         G_PARAM_STATIC_NICK));
352
353   /**
354    * GDBusServer:active:
355    *
356    * Whether the server is currently active.
357    *
358    * Since: 2.26
359    */
360   g_object_class_install_property (gobject_class,
361                                    PROP_ACTIVE,
362                                    g_param_spec_boolean ("active",
363                                                          P_("Active"),
364                                                          P_("Whether the server is currently active"),
365                                                          FALSE,
366                                                          G_PARAM_READABLE |
367                                                          G_PARAM_STATIC_NAME |
368                                                          G_PARAM_STATIC_BLURB |
369                                                          G_PARAM_STATIC_NICK));
370
371   /**
372    * GDBusServer:authentication-observer:
373    *
374    * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
375    *
376    * Since: 2.26
377    */
378   g_object_class_install_property (gobject_class,
379                                    PROP_AUTHENTICATION_OBSERVER,
380                                    g_param_spec_object ("authentication-observer",
381                                                         P_("Authentication Observer"),
382                                                         P_("Object used to assist in the authentication process"),
383                                                         G_TYPE_DBUS_AUTH_OBSERVER,
384                                                         G_PARAM_READABLE |
385                                                         G_PARAM_WRITABLE |
386                                                         G_PARAM_CONSTRUCT_ONLY |
387                                                         G_PARAM_STATIC_NAME |
388                                                         G_PARAM_STATIC_BLURB |
389                                                         G_PARAM_STATIC_NICK));
390
391   /**
392    * GDBusServer::new-connection:
393    * @server: The #GDBusServer emitting the signal.
394    * @connection: A #GDBusConnection for the new connection.
395    *
396    * Emitted when a new authenticated connection has been made. Use
397    * g_dbus_connection_get_peer_credentials() to figure out what
398    * identity (if any), was authenticated.
399    *
400    * If you want to accept the connection, take a reference to the
401    * @connection object and return %TRUE. When you are done with the
402    * connection call g_dbus_connection_close() and give up your
403    * reference. Note that the other peer may disconnect at any time -
404    * a typical thing to do when accepting a connection is to listen to
405    * the #GDBusConnection::closed signal.
406    *
407    * If #GDBusServer:flags contains %G_DBUS_SERVER_FLAGS_RUN_IN_THREAD
408    * then the signal is emitted in a new thread dedicated to the
409    * connection. Otherwise the signal is emitted in the <link
410    * linkend="g-main-context-push-thread-default">thread-default main
411    * loop</link> of the thread that @server was constructed in.
412    *
413    * You are guaranteed that signal handlers for this signal runs
414    * before incoming messages on @connection are processed. This means
415    * that it's suitable to call g_dbus_connection_register_object() or
416    * similar from the signal handler.
417    *
418    * Returns: %TRUE to claim @connection, %FALSE to let other handlers
419    * run.
420    *
421    * Since: 2.26
422    */
423   _signals[NEW_CONNECTION_SIGNAL] = g_signal_new ("new-connection",
424                                                   G_TYPE_DBUS_SERVER,
425                                                   G_SIGNAL_RUN_LAST,
426                                                   G_STRUCT_OFFSET (GDBusServerClass, new_connection),
427                                                   g_signal_accumulator_true_handled,
428                                                   NULL, /* accu_data */
429                                                   _gio_marshal_BOOLEAN__OBJECT,
430                                                   G_TYPE_BOOLEAN,
431                                                   1,
432                                                   G_TYPE_DBUS_CONNECTION);
433 }
434
435 static void
436 g_dbus_server_init (GDBusServer *server)
437 {
438   server->main_context_at_construction = g_main_context_get_thread_default ();
439   if (server->main_context_at_construction != NULL)
440     g_main_context_ref (server->main_context_at_construction);
441 }
442
443 static gboolean
444 on_run (GSocketService    *service,
445         GSocketConnection *socket_connection,
446         GObject           *source_object,
447         gpointer           user_data);
448
449 /**
450  * g_dbus_server_new_sync:
451  * @address: A D-Bus address.
452  * @flags: Flags from the #GDBusServerFlags enumeration.
453  * @guid: A D-Bus GUID.
454  * @observer: A #GDBusAuthObserver or %NULL.
455  * @cancellable: A #GCancellable or %NULL.
456  * @error: Return location for server or %NULL.
457  *
458  * Creates a new D-Bus server that listens on the first address in
459  * @address that works.
460  *
461  * Once constructed, you can use g_dbus_server_get_client_address() to
462  * get a D-Bus address string that clients can use to connect.
463  *
464  * Connect to the #GDBusServer::new-connection signal to handle
465  * incoming connections.
466  *
467  * The returned #GDBusServer isn't active - you have to start it with
468  * g_dbus_server_start().
469  *
470  * See <xref linkend="gdbus-peer-to-peer"/> for how #GDBusServer can
471  * be used.
472  *
473  * This is a synchronous failable constructor. See
474  * g_dbus_server_new() for the asynchronous version.
475  *
476  * Returns: A #GDBusServer or %NULL if @error is set. Free with
477  * g_object_unref().
478  *
479  * Since: 2.26
480  */
481 GDBusServer *
482 g_dbus_server_new_sync (const gchar        *address,
483                         GDBusServerFlags    flags,
484                         const gchar        *guid,
485                         GDBusAuthObserver  *observer,
486                         GCancellable       *cancellable,
487                         GError            **error)
488 {
489   GDBusServer *server;
490
491   g_return_val_if_fail (address != NULL, NULL);
492   g_return_val_if_fail (g_dbus_is_guid (guid), NULL);
493   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
494
495   server = g_initable_new (G_TYPE_DBUS_SERVER,
496                            cancellable,
497                            error,
498                            "address", address,
499                            "flags", flags,
500                            "guid", guid,
501                            "authentication-observer", observer,
502                            NULL);
503
504   return server;
505 }
506
507 /**
508  * g_dbus_server_get_client_address:
509  * @server: A #GDBusServer.
510  *
511  * Gets a D-Bus address string that can be used by clients to connect
512  * to @server.
513  *
514  * Returns: A D-Bus address string. Do not free, the string is owned
515  * by @server.
516  *
517  * Since: 2.26
518  */
519 const gchar *
520 g_dbus_server_get_client_address (GDBusServer *server)
521 {
522   g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
523   return server->client_address;
524 }
525
526 /**
527  * g_dbus_server_get_guid:
528  * @server: A #GDBusServer.
529  *
530  * Gets the GUID for @server.
531  *
532  * Returns: A D-Bus GUID. Do not free this string, it is owned by @server.
533  *
534  * Since: 2.26
535  */
536 const gchar *
537 g_dbus_server_get_guid (GDBusServer *server)
538 {
539   g_return_val_if_fail (G_IS_DBUS_SERVER (server), NULL);
540   return server->guid;
541 }
542
543 /**
544  * g_dbus_server_get_flags:
545  * @server: A #GDBusServer.
546  *
547  * Gets the flags for @server.
548  *
549  * Returns: A set of flags from the #GDBusServerFlags enumeration.
550  *
551  * Since: 2.26
552  */
553 GDBusServerFlags
554 g_dbus_server_get_flags (GDBusServer *server)
555 {
556   g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
557   return server->flags;
558 }
559
560 /**
561  * g_dbus_server_is_active:
562  * @server: A #GDBusServer.
563  *
564  * Gets whether @server is active.
565  *
566  * Returns: %TRUE if server is active, %FALSE otherwise.
567  *
568  * Since: 2.26
569  */
570 gboolean
571 g_dbus_server_is_active (GDBusServer *server)
572 {
573   g_return_val_if_fail (G_IS_DBUS_SERVER (server), G_DBUS_SERVER_FLAGS_NONE);
574   return server->active;
575 }
576
577 /**
578  * g_dbus_server_start:
579  * @server: A #GDBusServer.
580  *
581  * Starts @server.
582  *
583  * Since: 2.26
584  */
585 void
586 g_dbus_server_start (GDBusServer *server)
587 {
588   g_return_if_fail (G_IS_DBUS_SERVER (server));
589   if (server->active)
590     return;
591   /* Right now we don't have any transport not using the listener... */
592   g_assert (server->is_using_listener);
593   g_socket_service_start (G_SOCKET_SERVICE (server->listener));
594   server->active = TRUE;
595   g_object_notify (G_OBJECT (server), "active");
596 }
597
598 /**
599  * g_dbus_server_stop:
600  * @server: A #GDBusServer.
601  *
602  * Stops @server.
603  *
604  * Since: 2.26
605  */
606 void
607 g_dbus_server_stop (GDBusServer *server)
608 {
609   g_return_if_fail (G_IS_DBUS_SERVER (server));
610   if (!server->active)
611     return;
612   /* Right now we don't have any transport not using the listener... */
613   g_assert (server->is_using_listener);
614   g_assert (server->run_signal_handler_id > 0);
615   g_signal_handler_disconnect (server->listener, server->run_signal_handler_id);
616   server->run_signal_handler_id = 0;
617   g_socket_service_stop (G_SOCKET_SERVICE (server->listener));
618   server->active = FALSE;
619   g_object_notify (G_OBJECT (server), "active");
620 }
621
622 /* ---------------------------------------------------------------------------------------------------- */
623
624 #ifdef G_OS_UNIX
625
626 static gint
627 random_ascii (void)
628 {
629   gint ret;
630   ret = g_random_int_range (0, 60);
631   if (ret < 25)
632     ret += 'A';
633   else if (ret < 50)
634     ret += 'a' - 25;
635   else
636     ret += '0' - 50;
637   return ret;
638 }
639
640 /* note that address_entry has already been validated => exactly one of path, tmpdir or abstract keys are set */
641 static gboolean
642 try_unix (GDBusServer  *server,
643           const gchar  *address_entry,
644           GHashTable   *key_value_pairs,
645           GError      **error)
646 {
647   gboolean ret;
648   const gchar *path;
649   const gchar *tmpdir;
650   const gchar *abstract;
651   GSocketAddress *address;
652
653   ret = FALSE;
654   address = NULL;
655
656   path = g_hash_table_lookup (key_value_pairs, "path");
657   tmpdir = g_hash_table_lookup (key_value_pairs, "tmpdir");
658   abstract = g_hash_table_lookup (key_value_pairs, "abstract");
659
660   if (path != NULL)
661     {
662       address = g_unix_socket_address_new (path);
663     }
664   else if (tmpdir != NULL)
665     {
666       gint n;
667       GString *s;
668       GError *local_error;
669
670     retry:
671       s = g_string_new (tmpdir);
672       g_string_append (s, "/dbus-");
673       for (n = 0; n < 8; n++)
674         g_string_append_c (s, random_ascii ());
675
676       /* prefer abstract namespace if available */
677       if (g_unix_socket_address_abstract_names_supported ())
678         address = g_unix_socket_address_new_with_type (s->str,
679                                                        -1,
680                                                        G_UNIX_SOCKET_ADDRESS_ABSTRACT);
681       else
682         address = g_unix_socket_address_new (s->str);
683       g_string_free (s, TRUE);
684
685       local_error = NULL;
686       if (!g_socket_listener_add_address (server->listener,
687                                           address,
688                                           G_SOCKET_TYPE_STREAM,
689                                           G_SOCKET_PROTOCOL_DEFAULT,
690                                           NULL, /* source_object */
691                                           NULL, /* effective_address */
692                                           &local_error))
693         {
694           if (local_error->domain == G_IO_ERROR && local_error->code == G_IO_ERROR_ADDRESS_IN_USE)
695             {
696               g_error_free (local_error);
697               goto retry;
698             }
699           g_propagate_error (error, local_error);
700           goto out;
701         }
702       ret = TRUE;
703       goto out;
704     }
705   else if (abstract != NULL)
706     {
707       if (!g_unix_socket_address_abstract_names_supported ())
708         {
709           g_set_error_literal (error,
710                                G_IO_ERROR,
711                                G_IO_ERROR_NOT_SUPPORTED,
712                                _("Abstract name space not supported"));
713           goto out;
714         }
715       address = g_unix_socket_address_new_with_type (abstract,
716                                                      -1,
717                                                      G_UNIX_SOCKET_ADDRESS_ABSTRACT);
718     }
719   else
720     {
721       g_assert_not_reached ();
722     }
723
724   if (!g_socket_listener_add_address (server->listener,
725                                       address,
726                                       G_SOCKET_TYPE_STREAM,
727                                       G_SOCKET_PROTOCOL_DEFAULT,
728                                       NULL, /* source_object */
729                                       NULL, /* effective_address */
730                                       error))
731     goto out;
732
733   ret = TRUE;
734
735  out:
736
737   if (address != NULL)
738     {
739       /* Fill out client_address if the connection attempt worked */
740       if (ret)
741         {
742           server->is_using_listener = TRUE;
743
744           switch (g_unix_socket_address_get_address_type (G_UNIX_SOCKET_ADDRESS (address)))
745             {
746             case G_UNIX_SOCKET_ADDRESS_ABSTRACT:
747               server->client_address = g_strdup_printf ("unix:abstract=%s",
748                                                         g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
749               break;
750
751             case G_UNIX_SOCKET_ADDRESS_PATH:
752               server->client_address = g_strdup_printf ("unix:path=%s",
753                                                         g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
754               break;
755
756             default:
757               g_assert_not_reached ();
758               break;
759             }
760         }
761       g_object_unref (address);
762     }
763   return ret;
764 }
765 #endif
766
767 /* ---------------------------------------------------------------------------------------------------- */
768
769 /* note that address_entry has already been validated =>
770  *  both host and port (guranteed to be a number in [0, 65535]) are set (family is optional)
771  */
772 static gboolean
773 try_tcp (GDBusServer  *server,
774          const gchar  *address_entry,
775          GHashTable   *key_value_pairs,
776          gboolean      do_nonce,
777          GError      **error)
778 {
779   gboolean ret;
780   const gchar *host;
781   const gchar *port;
782   gint port_num;
783   GResolver *resolver;
784   GList *resolved_addresses;
785   GList *l;
786
787   ret = FALSE;
788   resolver = NULL;
789   resolved_addresses = NULL;
790
791   host = g_hash_table_lookup (key_value_pairs, "host");
792   port = g_hash_table_lookup (key_value_pairs, "port");
793   /* family = g_hash_table_lookup (key_value_pairs, "family"); */
794   if (g_hash_table_lookup (key_value_pairs, "noncefile") != NULL)
795     {
796       g_set_error_literal (error,
797                            G_IO_ERROR,
798                            G_IO_ERROR_INVALID_ARGUMENT,
799                            _("Cannot specify nonce file when creating a server"));
800       goto out;
801     }
802
803   if (host == NULL)
804     host = "localhost";
805   if (port == NULL)
806     port = "0";
807   port_num = strtol (port, NULL, 10);
808
809   resolver = g_resolver_get_default ();
810   resolved_addresses = g_resolver_lookup_by_name (resolver,
811                                                   host,
812                                                   NULL,
813                                                   error);
814   if (resolved_addresses == NULL)
815     goto out;
816
817   /* TODO: handle family */
818   for (l = resolved_addresses; l != NULL; l = l->next)
819     {
820       GInetAddress *address = G_INET_ADDRESS (l->data);
821       GSocketAddress *socket_address;
822       GSocketAddress *effective_address;
823
824       socket_address = g_inet_socket_address_new (address, port_num);
825       if (!g_socket_listener_add_address (server->listener,
826                                           socket_address,
827                                           G_SOCKET_TYPE_STREAM,
828                                           G_SOCKET_PROTOCOL_TCP,
829                                           NULL, /* GObject *source_object */
830                                           &effective_address,
831                                           error))
832         {
833           g_object_unref (socket_address);
834           goto out;
835         }
836       if (port_num == 0)
837         /* make sure we allocate the same port number for other listeners */
838         port_num = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (effective_address));
839
840       g_object_unref (effective_address);
841       g_object_unref (socket_address);
842     }
843
844   if (do_nonce)
845     {
846       gint fd;
847       guint n;
848       gsize bytes_written;
849       gsize bytes_remaining;
850
851       server->nonce = g_new0 (guchar, 16);
852       for (n = 0; n < 16; n++)
853         server->nonce[n] = g_random_int_range (0, 256);
854       fd = g_file_open_tmp ("gdbus-nonce-file-XXXXXX",
855                             &server->nonce_file,
856                             error);
857       if (fd == -1)
858         {
859           g_socket_listener_close (server->listener);
860           goto out;
861         }
862     again:
863       bytes_written = 0;
864       bytes_remaining = 16;
865       while (bytes_remaining > 0)
866         {
867           gssize ret;
868           ret = write (fd, server->nonce + bytes_written, bytes_remaining);
869           if (ret == -1)
870             {
871               if (errno == EINTR)
872                 goto again;
873               g_set_error (error,
874                            G_IO_ERROR,
875                            g_io_error_from_errno (errno),
876                            _("Error writing nonce file at `%s': %s"),
877                            server->nonce_file,
878                            strerror (errno));
879               goto out;
880             }
881           bytes_written += ret;
882           bytes_remaining -= ret;
883         }
884       close (fd);
885       server->client_address = g_strdup_printf ("nonce-tcp:host=%s,port=%d,noncefile=%s",
886                                                 host,
887                                                 port_num,
888                                                 server->nonce_file);
889     }
890   else
891     {
892       server->client_address = g_strdup_printf ("tcp:host=%s,port=%d", host, port_num);
893     }
894   server->is_using_listener = TRUE;
895   ret = TRUE;
896
897  out:
898   g_list_foreach (resolved_addresses, (GFunc) g_object_unref, NULL);
899   g_list_free (resolved_addresses);
900   g_object_unref (resolver);
901   return ret;
902 }
903
904 /* ---------------------------------------------------------------------------------------------------- */
905
906 typedef struct
907 {
908   GDBusServer *server;
909   GDBusConnection *connection;
910 } EmitIdleData;
911
912 static void
913 emit_idle_data_free (EmitIdleData *data)
914 {
915   g_object_unref (data->server);
916   g_object_unref (data->connection);
917   g_free (data);
918 }
919
920 static gboolean
921 emit_new_connection_in_idle (gpointer user_data)
922 {
923   EmitIdleData *data = user_data;
924   gboolean claimed;
925
926   claimed = FALSE;
927   g_signal_emit (data->server,
928                  _signals[NEW_CONNECTION_SIGNAL],
929                  0,
930                  data->connection,
931                  &claimed);
932
933   if (claimed)
934     g_dbus_connection_start_message_processing (data->connection);
935   g_object_unref (data->connection);
936
937   return FALSE;
938 }
939
940 /* Called in new thread */
941 static gboolean
942 on_run (GSocketService    *service,
943         GSocketConnection *socket_connection,
944         GObject           *source_object,
945         gpointer           user_data)
946 {
947   GDBusServer *server = G_DBUS_SERVER (user_data);
948   GDBusConnection *connection;
949   GDBusConnectionFlags connection_flags;
950
951   if (server->nonce != NULL)
952     {
953       gchar buf[16];
954       gsize bytes_read;
955
956       if (!g_input_stream_read_all (g_io_stream_get_input_stream (G_IO_STREAM (socket_connection)),
957                                     buf,
958                                     16,
959                                     &bytes_read,
960                                     NULL,  /* GCancellable */
961                                     NULL)) /* GError */
962         goto out;
963
964       if (bytes_read != 16)
965         goto out;
966
967       if (memcmp (buf, server->nonce, 16) != 0)
968         goto out;
969     }
970
971   connection_flags =
972     G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER |
973     G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING;
974   if (server->flags & G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS)
975     connection_flags |= G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS;
976
977   connection = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
978                                            server->guid,
979                                            connection_flags,
980                                            server->authentication_observer,
981                                            NULL,  /* GCancellable */
982                                            NULL); /* GError */
983   if (connection == NULL)
984       goto out;
985
986   if (server->flags & G_DBUS_SERVER_FLAGS_RUN_IN_THREAD)
987     {
988       gboolean claimed;
989
990       claimed = FALSE;
991       g_signal_emit (server,
992                      _signals[NEW_CONNECTION_SIGNAL],
993                      0,
994                      connection,
995                      &claimed);
996       if (claimed)
997         g_dbus_connection_start_message_processing (connection);
998       g_object_unref (connection);
999     }
1000   else
1001     {
1002       GSource *idle_source;
1003       EmitIdleData *data;
1004
1005       data = g_new0 (EmitIdleData, 1);
1006       data->server = g_object_ref (server);
1007       data->connection = g_object_ref (connection);
1008
1009       idle_source = g_idle_source_new ();
1010       g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1011       g_source_set_callback (idle_source,
1012                              emit_new_connection_in_idle,
1013                              data,
1014                              (GDestroyNotify) emit_idle_data_free);
1015       g_source_attach (idle_source, server->main_context_at_construction);
1016       g_source_unref (idle_source);
1017     }
1018
1019  out:
1020   return TRUE;
1021 }
1022
1023 static gboolean
1024 initable_init (GInitable     *initable,
1025                GCancellable  *cancellable,
1026                GError       **error)
1027 {
1028   GDBusServer *server = G_DBUS_SERVER (initable);
1029   gboolean ret;
1030   guint n;
1031   gchar **addr_array;
1032   GError *last_error;
1033
1034   ret = FALSE;
1035   addr_array = NULL;
1036   last_error = NULL;
1037
1038   if (!g_dbus_is_guid (server->guid))
1039     {
1040       g_set_error (&last_error,
1041                    G_IO_ERROR,
1042                    G_IO_ERROR_INVALID_ARGUMENT,
1043                    _("The string `%s' is not a valid D-Bus GUID"),
1044                    server->guid);
1045       goto out;
1046     }
1047
1048   server->listener = G_SOCKET_LISTENER (g_threaded_socket_service_new (-1));
1049
1050   addr_array = g_strsplit (server->address, ";", 0);
1051   last_error = NULL;
1052   for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
1053     {
1054       const gchar *address_entry = addr_array[n];
1055       GHashTable *key_value_pairs;
1056       gchar *transport_name;
1057       GError *this_error;
1058
1059       this_error = NULL;
1060       if (g_dbus_is_supported_address (address_entry,
1061                                        &this_error) &&
1062           _g_dbus_address_parse_entry (address_entry,
1063                                        &transport_name,
1064                                        &key_value_pairs,
1065                                        &this_error))
1066         {
1067
1068           if (FALSE)
1069             {
1070             }
1071 #ifdef G_OS_UNIX
1072           else if (g_strcmp0 (transport_name, "unix") == 0)
1073             ret = try_unix (server, address_entry, key_value_pairs, &this_error);
1074 #endif
1075           else if (g_strcmp0 (transport_name, "tcp") == 0)
1076             ret = try_tcp (server, address_entry, key_value_pairs, FALSE, &this_error);
1077           else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
1078             ret = try_tcp (server, address_entry, key_value_pairs, TRUE, &this_error);
1079           else
1080             g_set_error (&this_error,
1081                          G_IO_ERROR,
1082                          G_IO_ERROR_INVALID_ARGUMENT,
1083                          _("Cannot listen on unsupported transport `%s'"),
1084                          transport_name);
1085
1086           g_free (transport_name);
1087           if (key_value_pairs != NULL)
1088             g_hash_table_unref (key_value_pairs);
1089
1090           if (ret)
1091             {
1092               g_assert (this_error == NULL);
1093               goto out;
1094             }
1095         }
1096
1097       if (this_error != NULL)
1098         {
1099           if (last_error != NULL)
1100             g_error_free (last_error);
1101           last_error = this_error;
1102         }
1103     }
1104
1105  out:
1106
1107   g_strfreev (addr_array);
1108
1109   if (ret)
1110     {
1111       if (last_error != NULL)
1112         g_error_free (last_error);
1113
1114       /* Right now we don't have any transport not using the listener... */
1115       g_assert (server->is_using_listener);
1116       server->run_signal_handler_id = g_signal_connect (G_SOCKET_SERVICE (server->listener),
1117                                                         "run",
1118                                                         G_CALLBACK (on_run),
1119                                                         server);
1120     }
1121   else
1122     {
1123       g_assert (last_error != NULL);
1124       g_propagate_error (error, last_error);
1125     }
1126   return ret;
1127 }
1128
1129
1130 static void
1131 initable_iface_init (GInitableIface *initable_iface)
1132 {
1133   initable_iface->init = initable_init;
1134 }
1135
1136 /* ---------------------------------------------------------------------------------------------------- */