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