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