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 #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 
G_DEFINE_TYPE_WITH_CODE(GDBusServer,g_dbus_server,G_TYPE_OBJECT,G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,initable_iface_init))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
g_dbus_server_finalize(GObject * object)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
g_dbus_server_get_property(GObject * object,guint prop_id,GValue * value,GParamSpec * pspec)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
g_dbus_server_set_property(GObject * object,guint prop_id,const GValue * value,GParamSpec * pspec)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
g_dbus_server_class_init(GDBusServerClass * klass)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
g_dbus_server_init(GDBusServer * server)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 *
g_dbus_server_new_sync(const gchar * address,GDBusServerFlags flags,const gchar * guid,GDBusAuthObserver * observer,GCancellable * cancellable,GError ** error)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 *
g_dbus_server_get_client_address(GDBusServer * server)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 *
g_dbus_server_get_guid(GDBusServer * server)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
g_dbus_server_get_flags(GDBusServer * server)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
g_dbus_server_is_active(GDBusServer * server)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
g_dbus_server_start(GDBusServer * server)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                                                          0  /* flags */);
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
g_dbus_server_stop(GDBusServer * server)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 #ifdef G_OS_UNIX
677 
678 static gint
random_ascii(void)679 random_ascii (void)
680 {
681   gint ret;
682   ret = g_random_int_range (0, 60);
683   if (ret < 25)
684     ret += 'A';
685   else if (ret < 50)
686     ret += 'a' - 25;
687   else
688     ret += '0' - 50;
689   return ret;
690 }
691 
692 /* note that address_entry has already been validated => exactly one of path, dir, tmpdir, or abstract keys are set */
693 static gboolean
try_unix(GDBusServer * server,const gchar * address_entry,GHashTable * key_value_pairs,GError ** error)694 try_unix (GDBusServer  *server,
695           const gchar  *address_entry,
696           GHashTable   *key_value_pairs,
697           GError      **error)
698 {
699   gboolean ret;
700   const gchar *path;
701   const gchar *dir;
702   const gchar *tmpdir;
703   const gchar *abstract;
704   GSocketAddress *address;
705 
706   ret = FALSE;
707   address = NULL;
708 
709   path = g_hash_table_lookup (key_value_pairs, "path");
710   dir = g_hash_table_lookup (key_value_pairs, "dir");
711   tmpdir = g_hash_table_lookup (key_value_pairs, "tmpdir");
712   abstract = g_hash_table_lookup (key_value_pairs, "abstract");
713 
714   if (path != NULL)
715     {
716       address = g_unix_socket_address_new (path);
717     }
718   else if (dir != NULL || tmpdir != NULL)
719     {
720       gint n;
721       GString *s;
722       GError *local_error;
723 
724     retry:
725       s = g_string_new (tmpdir != NULL ? tmpdir : dir);
726       g_string_append (s, "/dbus-");
727       for (n = 0; n < 8; n++)
728         g_string_append_c (s, random_ascii ());
729 
730       /* prefer abstract namespace if available for tmpdir: addresses
731        * abstract namespace is disallowed for dir: addresses */
732       if (tmpdir != NULL && g_unix_socket_address_abstract_names_supported ())
733         address = g_unix_socket_address_new_with_type (s->str,
734                                                        -1,
735                                                        G_UNIX_SOCKET_ADDRESS_ABSTRACT);
736       else
737         address = g_unix_socket_address_new (s->str);
738       g_string_free (s, TRUE);
739 
740       local_error = NULL;
741       if (!g_socket_listener_add_address (server->listener,
742                                           address,
743                                           G_SOCKET_TYPE_STREAM,
744                                           G_SOCKET_PROTOCOL_DEFAULT,
745                                           NULL, /* source_object */
746                                           NULL, /* effective_address */
747                                           &local_error))
748         {
749           if (local_error->domain == G_IO_ERROR && local_error->code == G_IO_ERROR_ADDRESS_IN_USE)
750             {
751               g_error_free (local_error);
752               goto retry;
753             }
754           g_propagate_error (error, local_error);
755           goto out;
756         }
757       ret = TRUE;
758       goto out;
759     }
760   else if (abstract != NULL)
761     {
762       if (!g_unix_socket_address_abstract_names_supported ())
763         {
764           g_set_error_literal (error,
765                                G_IO_ERROR,
766                                G_IO_ERROR_NOT_SUPPORTED,
767                                _("Abstract namespace not supported"));
768           goto out;
769         }
770       address = g_unix_socket_address_new_with_type (abstract,
771                                                      -1,
772                                                      G_UNIX_SOCKET_ADDRESS_ABSTRACT);
773     }
774   else
775     {
776       g_assert_not_reached ();
777     }
778 
779   if (!g_socket_listener_add_address (server->listener,
780                                       address,
781                                       G_SOCKET_TYPE_STREAM,
782                                       G_SOCKET_PROTOCOL_DEFAULT,
783                                       NULL, /* source_object */
784                                       NULL, /* effective_address */
785                                       error))
786     goto out;
787 
788   ret = TRUE;
789 
790  out:
791 
792   if (address != NULL)
793     {
794       /* Fill out client_address if the connection attempt worked */
795       if (ret)
796         {
797           const char *address_path;
798           char *escaped_path;
799 
800           server->is_using_listener = TRUE;
801           address_path = g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address));
802           escaped_path = g_dbus_address_escape_value (address_path);
803 
804           switch (g_unix_socket_address_get_address_type (G_UNIX_SOCKET_ADDRESS (address)))
805             {
806             case G_UNIX_SOCKET_ADDRESS_ABSTRACT:
807               server->client_address = g_strdup_printf ("unix:abstract=%s", escaped_path);
808               break;
809 
810             case G_UNIX_SOCKET_ADDRESS_PATH:
811               server->client_address = g_strdup_printf ("unix:path=%s", escaped_path);
812               server->unix_socket_path = g_strdup (address_path);
813               break;
814 
815             default:
816               g_assert_not_reached ();
817               break;
818             }
819 
820           g_free (escaped_path);
821         }
822       g_object_unref (address);
823     }
824   return ret;
825 }
826 #endif
827 
828 /* ---------------------------------------------------------------------------------------------------- */
829 
830 /* note that address_entry has already been validated =>
831  *  both host and port (guaranteed to be a number in [0, 65535]) are set (family is optional)
832  */
833 static gboolean
try_tcp(GDBusServer * server,const gchar * address_entry,GHashTable * key_value_pairs,gboolean do_nonce,GError ** error)834 try_tcp (GDBusServer  *server,
835          const gchar  *address_entry,
836          GHashTable   *key_value_pairs,
837          gboolean      do_nonce,
838          GError      **error)
839 {
840   gboolean ret;
841   const gchar *host;
842   const gchar *port;
843   gint port_num;
844   GResolver *resolver;
845   GList *resolved_addresses;
846   GList *l;
847 
848   ret = FALSE;
849   resolver = NULL;
850   resolved_addresses = NULL;
851 
852   host = g_hash_table_lookup (key_value_pairs, "host");
853   port = g_hash_table_lookup (key_value_pairs, "port");
854   /* family = g_hash_table_lookup (key_value_pairs, "family"); */
855   if (g_hash_table_lookup (key_value_pairs, "noncefile") != NULL)
856     {
857       g_set_error_literal (error,
858                            G_IO_ERROR,
859                            G_IO_ERROR_INVALID_ARGUMENT,
860                            _("Cannot specify nonce file when creating a server"));
861       goto out;
862     }
863 
864   if (host == NULL)
865     host = "localhost";
866   if (port == NULL)
867     port = "0";
868   port_num = strtol (port, NULL, 10);
869 
870   resolver = g_resolver_get_default ();
871   resolved_addresses = g_resolver_lookup_by_name (resolver,
872                                                   host,
873                                                   NULL,
874                                                   error);
875   if (resolved_addresses == NULL)
876     goto out;
877 
878   /* TODO: handle family */
879   for (l = resolved_addresses; l != NULL; l = l->next)
880     {
881       GInetAddress *address = G_INET_ADDRESS (l->data);
882       GSocketAddress *socket_address;
883       GSocketAddress *effective_address;
884 
885       socket_address = g_inet_socket_address_new (address, port_num);
886       if (!g_socket_listener_add_address (server->listener,
887                                           socket_address,
888                                           G_SOCKET_TYPE_STREAM,
889                                           G_SOCKET_PROTOCOL_TCP,
890                                           NULL, /* GObject *source_object */
891                                           &effective_address,
892                                           error))
893         {
894           g_object_unref (socket_address);
895           goto out;
896         }
897       if (port_num == 0)
898         /* make sure we allocate the same port number for other listeners */
899         port_num = g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (effective_address));
900 
901       g_object_unref (effective_address);
902       g_object_unref (socket_address);
903     }
904 
905   if (do_nonce)
906     {
907       gint fd;
908       guint n;
909       gsize bytes_written;
910       gsize bytes_remaining;
911       char *file_escaped;
912       char *host_escaped;
913 
914       server->nonce = g_new0 (guchar, 16);
915       for (n = 0; n < 16; n++)
916         server->nonce[n] = g_random_int_range (0, 256);
917       fd = g_file_open_tmp ("gdbus-nonce-file-XXXXXX",
918                             &server->nonce_file,
919                             error);
920       if (fd == -1)
921         {
922           g_socket_listener_close (server->listener);
923           goto out;
924         }
925     again:
926       bytes_written = 0;
927       bytes_remaining = 16;
928       while (bytes_remaining > 0)
929         {
930           gssize ret;
931           int errsv;
932 
933           ret = write (fd, server->nonce + bytes_written, bytes_remaining);
934           errsv = errno;
935           if (ret == -1)
936             {
937               if (errsv == EINTR)
938                 goto again;
939               g_set_error (error,
940                            G_IO_ERROR,
941                            g_io_error_from_errno (errsv),
942                            _("Error writing nonce file at “%s”: %s"),
943                            server->nonce_file,
944                            g_strerror (errsv));
945               goto out;
946             }
947           bytes_written += ret;
948           bytes_remaining -= ret;
949         }
950       if (!g_close (fd, error))
951         goto out;
952       host_escaped = g_dbus_address_escape_value (host);
953       file_escaped = g_dbus_address_escape_value (server->nonce_file);
954       server->client_address = g_strdup_printf ("nonce-tcp:host=%s,port=%d,noncefile=%s",
955                                                 host_escaped,
956                                                 port_num,
957                                                 file_escaped);
958       g_free (host_escaped);
959       g_free (file_escaped);
960     }
961   else
962     {
963       server->client_address = g_strdup_printf ("tcp:host=%s,port=%d", host, port_num);
964     }
965   server->is_using_listener = TRUE;
966   ret = TRUE;
967 
968  out:
969   g_list_free_full (resolved_addresses, g_object_unref);
970   if (resolver)
971     g_object_unref (resolver);
972   return ret;
973 }
974 
975 /* ---------------------------------------------------------------------------------------------------- */
976 
977 typedef struct
978 {
979   GDBusServer *server;
980   GDBusConnection *connection;
981 } EmitIdleData;
982 
983 static void
emit_idle_data_free(EmitIdleData * data)984 emit_idle_data_free (EmitIdleData *data)
985 {
986   g_object_unref (data->server);
987   g_object_unref (data->connection);
988   g_free (data);
989 }
990 
991 static gboolean
emit_new_connection_in_idle(gpointer user_data)992 emit_new_connection_in_idle (gpointer user_data)
993 {
994   EmitIdleData *data = user_data;
995   gboolean claimed;
996 
997   claimed = FALSE;
998   g_signal_emit (data->server,
999                  _signals[NEW_CONNECTION_SIGNAL],
1000                  0,
1001                  data->connection,
1002                  &claimed);
1003 
1004   if (claimed)
1005     g_dbus_connection_start_message_processing (data->connection);
1006   g_object_unref (data->connection);
1007 
1008   return FALSE;
1009 }
1010 
1011 /* Called in new thread */
1012 static gboolean
on_run(GSocketService * service,GSocketConnection * socket_connection,GObject * source_object,gpointer user_data)1013 on_run (GSocketService    *service,
1014         GSocketConnection *socket_connection,
1015         GObject           *source_object,
1016         gpointer           user_data)
1017 {
1018   GDBusServer *server = G_DBUS_SERVER (user_data);
1019   GDBusConnection *connection;
1020   GDBusConnectionFlags connection_flags;
1021 
1022   if (server->nonce != NULL)
1023     {
1024       gchar buf[16];
1025       gsize bytes_read;
1026 
1027       if (!g_input_stream_read_all (g_io_stream_get_input_stream (G_IO_STREAM (socket_connection)),
1028                                     buf,
1029                                     16,
1030                                     &bytes_read,
1031                                     NULL,  /* GCancellable */
1032                                     NULL)) /* GError */
1033         goto out;
1034 
1035       if (bytes_read != 16)
1036         goto out;
1037 
1038       if (memcmp (buf, server->nonce, 16) != 0)
1039         goto out;
1040     }
1041 
1042   connection_flags =
1043     G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER |
1044     G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING;
1045   if (server->flags & G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS)
1046     connection_flags |= G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS;
1047   if (server->flags & G_DBUS_SERVER_FLAGS_AUTHENTICATION_REQUIRE_SAME_USER)
1048     connection_flags |= G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_REQUIRE_SAME_USER;
1049 
1050   connection = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
1051                                            server->guid,
1052                                            connection_flags,
1053                                            server->authentication_observer,
1054                                            NULL,  /* GCancellable */
1055                                            NULL); /* GError */
1056   if (connection == NULL)
1057       goto out;
1058 
1059   if (server->flags & G_DBUS_SERVER_FLAGS_RUN_IN_THREAD)
1060     {
1061       gboolean claimed;
1062 
1063       claimed = FALSE;
1064       g_signal_emit (server,
1065                      _signals[NEW_CONNECTION_SIGNAL],
1066                      0,
1067                      connection,
1068                      &claimed);
1069       if (claimed)
1070         g_dbus_connection_start_message_processing (connection);
1071       g_object_unref (connection);
1072     }
1073   else
1074     {
1075       GSource *idle_source;
1076       EmitIdleData *data;
1077 
1078       data = g_new0 (EmitIdleData, 1);
1079       data->server = g_object_ref (server);
1080       data->connection = g_object_ref (connection);
1081 
1082       idle_source = g_idle_source_new ();
1083       g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1084       g_source_set_callback (idle_source,
1085                              emit_new_connection_in_idle,
1086                              data,
1087                              (GDestroyNotify) emit_idle_data_free);
1088       g_source_set_static_name (idle_source, "[gio] emit_new_connection_in_idle");
1089       g_source_attach (idle_source, server->main_context_at_construction);
1090       g_source_unref (idle_source);
1091     }
1092 
1093  out:
1094   return TRUE;
1095 }
1096 
1097 static gboolean
initable_init(GInitable * initable,GCancellable * cancellable,GError ** error)1098 initable_init (GInitable     *initable,
1099                GCancellable  *cancellable,
1100                GError       **error)
1101 {
1102   GDBusServer *server = G_DBUS_SERVER (initable);
1103   gboolean ret;
1104   guint n;
1105   gchar **addr_array;
1106   GError *last_error;
1107 
1108   ret = FALSE;
1109   addr_array = NULL;
1110   last_error = NULL;
1111 
1112   if (!g_dbus_is_guid (server->guid))
1113     {
1114       g_set_error (&last_error,
1115                    G_IO_ERROR,
1116                    G_IO_ERROR_INVALID_ARGUMENT,
1117                    _("The string “%s” is not a valid D-Bus GUID"),
1118                    server->guid);
1119       goto out;
1120     }
1121 
1122   server->listener = G_SOCKET_LISTENER (g_threaded_socket_service_new (-1));
1123 
1124   addr_array = g_strsplit (server->address, ";", 0);
1125   last_error = NULL;
1126   for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
1127     {
1128       const gchar *address_entry = addr_array[n];
1129       GHashTable *key_value_pairs;
1130       gchar *transport_name;
1131       GError *this_error;
1132 
1133       this_error = NULL;
1134       if (g_dbus_is_supported_address (address_entry,
1135                                        &this_error) &&
1136           _g_dbus_address_parse_entry (address_entry,
1137                                        &transport_name,
1138                                        &key_value_pairs,
1139                                        &this_error))
1140         {
1141 
1142           if (FALSE)
1143             {
1144             }
1145 #ifdef G_OS_UNIX
1146           else if (g_strcmp0 (transport_name, "unix") == 0)
1147             ret = try_unix (server, address_entry, key_value_pairs, &this_error);
1148 #endif
1149           else if (g_strcmp0 (transport_name, "tcp") == 0)
1150             ret = try_tcp (server, address_entry, key_value_pairs, FALSE, &this_error);
1151           else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
1152             ret = try_tcp (server, address_entry, key_value_pairs, TRUE, &this_error);
1153           else
1154             g_set_error (&this_error,
1155                          G_IO_ERROR,
1156                          G_IO_ERROR_INVALID_ARGUMENT,
1157                          _("Cannot listen on unsupported transport “%s”"),
1158                          transport_name);
1159 
1160           g_free (transport_name);
1161           if (key_value_pairs != NULL)
1162             g_hash_table_unref (key_value_pairs);
1163 
1164           if (ret)
1165             {
1166               g_assert (this_error == NULL);
1167               goto out;
1168             }
1169         }
1170 
1171       if (this_error != NULL)
1172         {
1173           if (last_error != NULL)
1174             g_error_free (last_error);
1175           last_error = this_error;
1176         }
1177     }
1178 
1179  out:
1180 
1181   g_strfreev (addr_array);
1182 
1183   if (ret)
1184     {
1185       g_clear_error (&last_error);
1186     }
1187   else
1188     {
1189       g_assert (last_error != NULL);
1190       g_propagate_error (error, last_error);
1191     }
1192   return ret;
1193 }
1194 
1195 
1196 static void
initable_iface_init(GInitableIface * initable_iface)1197 initable_iface_init (GInitableIface *initable_iface)
1198 {
1199   initable_iface->init = initable_init;
1200 }
1201 
1202 /* ---------------------------------------------------------------------------------------------------- */
1203