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