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