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