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