Eradicate links and xrefs
[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, 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
46 #ifdef G_OS_UNIX
47 #include <unistd.h>
48 #endif
49 #ifdef G_OS_WIN32
50 #include <io.h>
51 #endif
52
53 #ifdef G_OS_UNIX
54 #include "gunixsocketaddress.h"
55 #endif
56
57 #include "glibintl.h"
58
59 /**
60  * SECTION:gdbusserver
61  * @short_description: Helper for accepting connections
62  * @include: gio/gio.h
63  *
64  * #GDBusServer is a helper for listening to and accepting D-Bus
65  * connections. This can be used to create a new D-Bus server, allowing two
66  * peers to use the D-Bus protocol for their own specialized communication.
67  * A server instance provided in this way will not perform message routing or
68  * implement the org.freedesktop.DBus interface.
69  *
70  * To just export an object on a well-known name on a message bus, such as the
71  * session or system bus, you should instead use g_bus_own_name().
72  *
73  * <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>
74  */
75
76 /**
77  * GDBusServer:
78  *
79  * The #GDBusServer structure contains only private data and
80  * should only be accessed using the provided API.
81  *
82  * Since: 2.26
83  */
84 struct _GDBusServer
85 {
86   /*< private >*/
87   GObject parent_instance;
88
89   GDBusServerFlags flags;
90   gchar *address;
91   gchar *guid;
92
93   guchar *nonce;
94   gchar *nonce_file;
95
96   gchar *client_address;
97
98   GSocketListener *listener;
99   gboolean is_using_listener;
100   gulong run_signal_handler_id;
101
102   /* The result of g_main_context_ref_thread_default() when the object
103    * was created (the GObject _init() function) - this is used for delivery
104    * of the :new-connection GObject signal.
105    */
106   GMainContext *main_context_at_construction;
107
108   gboolean active;
109
110   GDBusAuthObserver *authentication_observer;
111 };
112
113 typedef struct _GDBusServerClass GDBusServerClass;
114
115 /**
116  * GDBusServerClass:
117  * @new_connection: Signal class handler for the #GDBusServer::new-connection signal.
118  *
119  * Class structure for #GDBusServer.
120  *
121  * Since: 2.26
122  */
123 struct _GDBusServerClass
124 {
125   /*< private >*/
126   GObjectClass parent_class;
127
128   /*< public >*/
129   /* Signals */
130   gboolean (*new_connection) (GDBusServer      *server,
131                               GDBusConnection  *connection);
132 };
133
134 enum
135 {
136   PROP_0,
137   PROP_ADDRESS,
138   PROP_CLIENT_ADDRESS,
139   PROP_FLAGS,
140   PROP_GUID,
141   PROP_ACTIVE,
142   PROP_AUTHENTICATION_OBSERVER,
143 };
144
145 enum
146 {
147   NEW_CONNECTION_SIGNAL,
148   LAST_SIGNAL,
149 };
150
151 static guint _signals[LAST_SIGNAL] = {0};
152
153 static void initable_iface_init       (GInitableIface *initable_iface);
154
155 G_DEFINE_TYPE_WITH_CODE (GDBusServer, g_dbus_server, G_TYPE_OBJECT,
156                          G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
157                          );
158
159 static void
160 g_dbus_server_finalize (GObject *object)
161 {
162   GDBusServer *server = G_DBUS_SERVER (object);
163
164   if (server->authentication_observer != NULL)
165     g_object_unref (server->authentication_observer);
166
167   if (server->run_signal_handler_id > 0)
168     g_signal_handler_disconnect (server->listener, server->run_signal_handler_id);
169
170   if (server->listener != NULL)
171     g_object_unref (server->listener);
172
173   g_free (server->address);
174   g_free (server->guid);
175   g_free (server->client_address);
176   if (server->nonce != NULL)
177     {
178       memset (server->nonce, '\0', 16);
179       g_free (server->nonce);
180     }
181   /* we could unlink the nonce file but I don't
182    * think it's really worth the effort/risk
183    */
184   g_free (server->nonce_file);
185
186   g_main_context_unref (server->main_context_at_construction);
187
188   G_OBJECT_CLASS (g_dbus_server_parent_class)->finalize (object);
189 }
190
191 static void
192 g_dbus_server_get_property (GObject    *object,
193                             guint       prop_id,
194                             GValue     *value,
195                             GParamSpec *pspec)
196 {
197   GDBusServer *server = G_DBUS_SERVER (object);
198
199   switch (prop_id)
200     {
201     case PROP_FLAGS:
202       g_value_set_flags (value, server->flags);
203       break;
204
205     case PROP_GUID:
206       g_value_set_string (value, server->guid);
207       break;
208
209     case PROP_ADDRESS:
210       g_value_set_string (value, server->address);
211       break;
212
213     case PROP_CLIENT_ADDRESS:
214       g_value_set_string (value, server->client_address);
215       break;
216
217     case PROP_ACTIVE:
218       g_value_set_boolean (value, server->active);
219       break;
220
221     case PROP_AUTHENTICATION_OBSERVER:
222       g_value_set_object (value, server->authentication_observer);
223       break;
224
225     default:
226       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
227       break;
228     }
229 }
230
231 static void
232 g_dbus_server_set_property (GObject      *object,
233                             guint         prop_id,
234                             const GValue *value,
235                             GParamSpec   *pspec)
236 {
237   GDBusServer *server = G_DBUS_SERVER (object);
238
239   switch (prop_id)
240     {
241     case PROP_FLAGS:
242       server->flags = g_value_get_flags (value);
243       break;
244
245     case PROP_GUID:
246       server->guid = g_value_dup_string (value);
247       break;
248
249     case PROP_ADDRESS:
250       server->address = g_value_dup_string (value);
251       break;
252
253     case PROP_AUTHENTICATION_OBSERVER:
254       server->authentication_observer = g_value_dup_object (value);
255       break;
256
257     default:
258       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
259       break;
260     }
261 }
262
263 static void
264 g_dbus_server_class_init (GDBusServerClass *klass)
265 {
266   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
267
268   gobject_class->finalize     = g_dbus_server_finalize;
269   gobject_class->set_property = g_dbus_server_set_property;
270   gobject_class->get_property = g_dbus_server_get_property;
271
272   /**
273    * GDBusServer:flags:
274    *
275    * Flags from the #GDBusServerFlags enumeration.
276    *
277    * Since: 2.26
278    */
279   g_object_class_install_property (gobject_class,
280                                    PROP_FLAGS,
281                                    g_param_spec_flags ("flags",
282                                                        P_("Flags"),
283                                                        P_("Flags for the server"),
284                                                        G_TYPE_DBUS_SERVER_FLAGS,
285                                                        G_DBUS_SERVER_FLAGS_NONE,
286                                                        G_PARAM_READABLE |
287                                                        G_PARAM_WRITABLE |
288                                                        G_PARAM_CONSTRUCT_ONLY |
289                                                        G_PARAM_STATIC_NAME |
290                                                        G_PARAM_STATIC_BLURB |
291                                                        G_PARAM_STATIC_NICK));
292
293   /**
294    * GDBusServer:guid:
295    *
296    * The guid of the server.
297    *
298    * Since: 2.26
299    */
300   g_object_class_install_property (gobject_class,
301                                    PROP_GUID,
302                                    g_param_spec_string ("guid",
303                                                         P_("GUID"),
304                                                         P_("The guid of the server"),
305                                                         NULL,
306                                                         G_PARAM_READABLE |
307                                                         G_PARAM_WRITABLE |
308                                                         G_PARAM_CONSTRUCT_ONLY |
309                                                         G_PARAM_STATIC_NAME |
310                                                         G_PARAM_STATIC_BLURB |
311                                                         G_PARAM_STATIC_NICK));
312
313   /**
314    * GDBusServer:address:
315    *
316    * The D-Bus address to listen on.
317    *
318    * Since: 2.26
319    */
320   g_object_class_install_property (gobject_class,
321                                    PROP_ADDRESS,
322                                    g_param_spec_string ("address",
323                                                         P_("Address"),
324                                                         P_("The address to listen on"),
325                                                         NULL,
326                                                         G_PARAM_READABLE |
327                                                         G_PARAM_WRITABLE |
328                                                         G_PARAM_CONSTRUCT_ONLY |
329                                                         G_PARAM_STATIC_NAME |
330                                                         G_PARAM_STATIC_BLURB |
331                                                         G_PARAM_STATIC_NICK));
332
333   /**
334    * GDBusServer:client-address:
335    *
336    * The D-Bus address that clients can use.
337    *
338    * Since: 2.26
339    */
340   g_object_class_install_property (gobject_class,
341                                    PROP_CLIENT_ADDRESS,
342                                    g_param_spec_string ("client-address",
343                                                         P_("Client Address"),
344                                                         P_("The address clients can use"),
345                                                         NULL,
346                                                         G_PARAM_READABLE |
347                                                         G_PARAM_STATIC_NAME |
348                                                         G_PARAM_STATIC_BLURB |
349                                                         G_PARAM_STATIC_NICK));
350
351   /**
352    * GDBusServer:active:
353    *
354    * Whether the server is currently active.
355    *
356    * Since: 2.26
357    */
358   g_object_class_install_property (gobject_class,
359                                    PROP_ACTIVE,
360                                    g_param_spec_boolean ("active",
361                                                          P_("Active"),
362                                                          P_("Whether the server is currently active"),
363                                                          FALSE,
364                                                          G_PARAM_READABLE |
365                                                          G_PARAM_STATIC_NAME |
366                                                          G_PARAM_STATIC_BLURB |
367                                                          G_PARAM_STATIC_NICK));
368
369   /**
370    * GDBusServer:authentication-observer:
371    *
372    * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
373    *
374    * Since: 2.26
375    */
376   g_object_class_install_property (gobject_class,
377                                    PROP_AUTHENTICATION_OBSERVER,
378                                    g_param_spec_object ("authentication-observer",
379                                                         P_("Authentication Observer"),
380                                                         P_("Object used to assist in the authentication process"),
381                                                         G_TYPE_DBUS_AUTH_OBSERVER,
382                                                         G_PARAM_READABLE |
383                                                         G_PARAM_WRITABLE |
384                                                         G_PARAM_CONSTRUCT_ONLY |
385                                                         G_PARAM_STATIC_NAME |
386                                                         G_PARAM_STATIC_BLURB |
387                                                         G_PARAM_STATIC_NICK));
388
389   /**
390    * GDBusServer::new-connection:
391    * @server: The #GDBusServer emitting the signal.
392    * @connection: A #GDBusConnection for the new connection.
393    *
394    * Emitted when a new authenticated connection has been made. Use
395    * g_dbus_connection_get_peer_credentials() to figure out what
396    * identity (if any), was authenticated.
397    *
398    * If you want to accept the connection, take a reference to the
399    * @connection object and return %TRUE. When you are done with the
400    * connection call g_dbus_connection_close() and give up your
401    * reference. Note that the other peer may disconnect at any time -
402    * a typical thing to do when accepting a connection is to listen to
403    * the #GDBusConnection::closed signal.
404    *
405    * If #GDBusServer:flags contains %G_DBUS_SERVER_FLAGS_RUN_IN_THREAD
406    * then the signal is emitted in a new thread dedicated to the
407    * connection. Otherwise the signal is emitted in the
408    * [thread-default main context][g-main-context-push-thread-default]
409    * of the thread that @server was constructed in.
410    *
411    * You are guaranteed that signal handlers for this signal runs
412    * before incoming messages on @connection are processed. This means
413    * that it's suitable to call g_dbus_connection_register_object() or
414    * similar from the signal handler.
415    *
416    * Returns: %TRUE to claim @connection, %FALSE to let other handlers
417    * run.
418    *
419    * Since: 2.26
420    */
421   _signals[NEW_CONNECTION_SIGNAL] = g_signal_new ("new-connection",
422                                                   G_TYPE_DBUS_SERVER,
423                                                   G_SIGNAL_RUN_LAST,
424                                                   G_STRUCT_OFFSET (GDBusServerClass, new_connection),
425                                                   g_signal_accumulator_true_handled,
426                                                   NULL, /* accu_data */
427                                                   NULL,
428                                                   G_TYPE_BOOLEAN,
429                                                   1,
430                                                   G_TYPE_DBUS_CONNECTION);
431 }
432
433 static void
434 g_dbus_server_init (GDBusServer *server)
435 {
436   server->main_context_at_construction = g_main_context_ref_thread_default ();
437 }
438
439 static gboolean
440 on_run (GSocketService    *service,
441         GSocketConnection *socket_connection,
442         GObject           *source_object,
443         gpointer           user_data);
444
445 /**
446  * g_dbus_server_new_sync:
447  * @address: A D-Bus address.
448  * @flags: Flags from the #GDBusServerFlags enumeration.
449  * @guid: A D-Bus GUID.
450  * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
451  * @cancellable: (allow-none): A #GCancellable or %NULL.
452  * @error: Return location for server or %NULL.
453  *
454  * Creates a new D-Bus server that listens on the first address in
455  * @address that works.
456  *
457  * Once constructed, you can use g_dbus_server_get_client_address() to
458  * get a D-Bus address string that clients can use to connect.
459  *
460  * Connect to the #GDBusServer::new-connection signal to handle
461  * incoming connections.
462  *
463  * The returned #GDBusServer isn't active - you have to start it with
464  * g_dbus_server_start().
465  *
466  * #GDBusServer is used in this [example][gdbus-peer-to-peer].
467  *
468  * This is a synchronous failable constructor. See
469  * g_dbus_server_new() for the asynchronous version.
470  *
471  * Returns: A #GDBusServer or %NULL if @error is set. Free with
472  * g_object_unref().
473  *
474  * Since: 2.26
475  */
476 GDBusServer *
477 g_dbus_server_new_sync (const gchar        *address,
478                         GDBusServerFlags    flags,
479                         const gchar        *guid,
480                         GDBusAuthObserver  *observer,
481                         GCancellable       *cancellable,
482                         GError            **error)
483 {
484   GDBusServer *server;
485
486   g_return_val_if_fail (address != NULL, NULL);
487   g_return_val_if_fail (g_dbus_is_guid (guid), NULL);
488   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
489
490   server = g_initable_new (G_TYPE_DBUS_SERVER,
491                            cancellable,
492                            error,
493                            "address", address,
494                            "flags", flags,
495                            "guid", guid,
496                            "authentication-observer", observer,
497                            NULL);
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_assert (server->run_signal_handler_id > 0);
610   g_signal_handler_disconnect (server->listener, server->run_signal_handler_id);
611   server->run_signal_handler_id = 0;
612   g_socket_service_stop (G_SOCKET_SERVICE (server->listener));
613   server->active = FALSE;
614   g_object_notify (G_OBJECT (server), "active");
615 }
616
617 /* ---------------------------------------------------------------------------------------------------- */
618
619 #ifdef G_OS_UNIX
620
621 static gint
622 random_ascii (void)
623 {
624   gint ret;
625   ret = g_random_int_range (0, 60);
626   if (ret < 25)
627     ret += 'A';
628   else if (ret < 50)
629     ret += 'a' - 25;
630   else
631     ret += '0' - 50;
632   return ret;
633 }
634
635 /* note that address_entry has already been validated => exactly one of path, tmpdir or abstract keys are set */
636 static gboolean
637 try_unix (GDBusServer  *server,
638           const gchar  *address_entry,
639           GHashTable   *key_value_pairs,
640           GError      **error)
641 {
642   gboolean ret;
643   const gchar *path;
644   const gchar *tmpdir;
645   const gchar *abstract;
646   GSocketAddress *address;
647
648   ret = FALSE;
649   address = NULL;
650
651   path = g_hash_table_lookup (key_value_pairs, "path");
652   tmpdir = g_hash_table_lookup (key_value_pairs, "tmpdir");
653   abstract = g_hash_table_lookup (key_value_pairs, "abstract");
654
655   if (path != NULL)
656     {
657       address = g_unix_socket_address_new (path);
658     }
659   else if (tmpdir != NULL)
660     {
661       gint n;
662       GString *s;
663       GError *local_error;
664
665     retry:
666       s = g_string_new (tmpdir);
667       g_string_append (s, "/dbus-");
668       for (n = 0; n < 8; n++)
669         g_string_append_c (s, random_ascii ());
670
671       /* prefer abstract namespace if available */
672       if (g_unix_socket_address_abstract_names_supported ())
673         address = g_unix_socket_address_new_with_type (s->str,
674                                                        -1,
675                                                        G_UNIX_SOCKET_ADDRESS_ABSTRACT);
676       else
677         address = g_unix_socket_address_new (s->str);
678       g_string_free (s, TRUE);
679
680       local_error = NULL;
681       if (!g_socket_listener_add_address (server->listener,
682                                           address,
683                                           G_SOCKET_TYPE_STREAM,
684                                           G_SOCKET_PROTOCOL_DEFAULT,
685                                           NULL, /* source_object */
686                                           NULL, /* effective_address */
687                                           &local_error))
688         {
689           if (local_error->domain == G_IO_ERROR && local_error->code == G_IO_ERROR_ADDRESS_IN_USE)
690             {
691               g_error_free (local_error);
692               goto retry;
693             }
694           g_propagate_error (error, local_error);
695           goto out;
696         }
697       ret = TRUE;
698       goto out;
699     }
700   else if (abstract != NULL)
701     {
702       if (!g_unix_socket_address_abstract_names_supported ())
703         {
704           g_set_error_literal (error,
705                                G_IO_ERROR,
706                                G_IO_ERROR_NOT_SUPPORTED,
707                                _("Abstract name space not supported"));
708           goto out;
709         }
710       address = g_unix_socket_address_new_with_type (abstract,
711                                                      -1,
712                                                      G_UNIX_SOCKET_ADDRESS_ABSTRACT);
713     }
714   else
715     {
716       g_assert_not_reached ();
717     }
718
719   if (!g_socket_listener_add_address (server->listener,
720                                       address,
721                                       G_SOCKET_TYPE_STREAM,
722                                       G_SOCKET_PROTOCOL_DEFAULT,
723                                       NULL, /* source_object */
724                                       NULL, /* effective_address */
725                                       error))
726     goto out;
727
728   ret = TRUE;
729
730  out:
731
732   if (address != NULL)
733     {
734       /* Fill out client_address if the connection attempt worked */
735       if (ret)
736         {
737           server->is_using_listener = TRUE;
738
739           switch (g_unix_socket_address_get_address_type (G_UNIX_SOCKET_ADDRESS (address)))
740             {
741             case G_UNIX_SOCKET_ADDRESS_ABSTRACT:
742               server->client_address = g_strdup_printf ("unix:abstract=%s",
743                                                         g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
744               break;
745
746             case G_UNIX_SOCKET_ADDRESS_PATH:
747               server->client_address = g_strdup_printf ("unix:path=%s",
748                                                         g_unix_socket_address_get_path (G_UNIX_SOCKET_ADDRESS (address)));
749               break;
750
751             default:
752               g_assert_not_reached ();
753               break;
754             }
755         }
756       g_object_unref (address);
757     }
758   return ret;
759 }
760 #endif
761
762 /* ---------------------------------------------------------------------------------------------------- */
763
764 /* note that address_entry has already been validated =>
765  *  both host and port (guaranteed to be a number in [0, 65535]) are set (family is optional)
766  */
767 static gboolean
768 try_tcp (GDBusServer  *server,
769          const gchar  *address_entry,
770          GHashTable   *key_value_pairs,
771          gboolean      do_nonce,
772          GError      **error)
773 {
774   gboolean ret;
775   const gchar *host;
776   const gchar *port;
777   gint port_num;
778   GResolver *resolver;
779   GList *resolved_addresses;
780   GList *l;
781
782   ret = FALSE;
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       char *file_escaped;
846
847       server->nonce = g_new0 (guchar, 16);
848       for (n = 0; n < 16; n++)
849         server->nonce[n] = g_random_int_range (0, 256);
850       fd = g_file_open_tmp ("gdbus-nonce-file-XXXXXX",
851                             &server->nonce_file,
852                             error);
853       if (fd == -1)
854         {
855           g_socket_listener_close (server->listener);
856           goto out;
857         }
858     again:
859       bytes_written = 0;
860       bytes_remaining = 16;
861       while (bytes_remaining > 0)
862         {
863           gssize ret;
864           ret = write (fd, server->nonce + bytes_written, bytes_remaining);
865           if (ret == -1)
866             {
867               if (errno == EINTR)
868                 goto again;
869               g_set_error (error,
870                            G_IO_ERROR,
871                            g_io_error_from_errno (errno),
872                            _("Error writing nonce file at '%s': %s"),
873                            server->nonce_file,
874                            strerror (errno));
875               goto out;
876             }
877           bytes_written += ret;
878           bytes_remaining -= ret;
879         }
880       if (!g_close (fd, error))
881         goto out;
882       file_escaped = g_uri_escape_string (server->nonce_file, "/\\", FALSE);
883       server->client_address = g_strdup_printf ("nonce-tcp:host=%s,port=%d,noncefile=%s",
884                                                 host,
885                                                 port_num,
886                                                 file_escaped);
887       g_free (file_escaped);
888     }
889   else
890     {
891       server->client_address = g_strdup_printf ("tcp:host=%s,port=%d", host, port_num);
892     }
893   server->is_using_listener = TRUE;
894   ret = TRUE;
895
896  out:
897   g_list_free_full (resolved_addresses, g_object_unref);
898   if (resolver)
899     g_object_unref (resolver);
900   return ret;
901 }
902
903 /* ---------------------------------------------------------------------------------------------------- */
904
905 typedef struct
906 {
907   GDBusServer *server;
908   GDBusConnection *connection;
909 } EmitIdleData;
910
911 static void
912 emit_idle_data_free (EmitIdleData *data)
913 {
914   g_object_unref (data->server);
915   g_object_unref (data->connection);
916   g_free (data);
917 }
918
919 static gboolean
920 emit_new_connection_in_idle (gpointer user_data)
921 {
922   EmitIdleData *data = user_data;
923   gboolean claimed;
924
925   claimed = FALSE;
926   g_signal_emit (data->server,
927                  _signals[NEW_CONNECTION_SIGNAL],
928                  0,
929                  data->connection,
930                  &claimed);
931
932   if (claimed)
933     g_dbus_connection_start_message_processing (data->connection);
934   g_object_unref (data->connection);
935
936   return FALSE;
937 }
938
939 /* Called in new thread */
940 static gboolean
941 on_run (GSocketService    *service,
942         GSocketConnection *socket_connection,
943         GObject           *source_object,
944         gpointer           user_data)
945 {
946   GDBusServer *server = G_DBUS_SERVER (user_data);
947   GDBusConnection *connection;
948   GDBusConnectionFlags connection_flags;
949
950   if (server->nonce != NULL)
951     {
952       gchar buf[16];
953       gsize bytes_read;
954
955       if (!g_input_stream_read_all (g_io_stream_get_input_stream (G_IO_STREAM (socket_connection)),
956                                     buf,
957                                     16,
958                                     &bytes_read,
959                                     NULL,  /* GCancellable */
960                                     NULL)) /* GError */
961         goto out;
962
963       if (bytes_read != 16)
964         goto out;
965
966       if (memcmp (buf, server->nonce, 16) != 0)
967         goto out;
968     }
969
970   connection_flags =
971     G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER |
972     G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING;
973   if (server->flags & G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS)
974     connection_flags |= G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS;
975
976   connection = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
977                                            server->guid,
978                                            connection_flags,
979                                            server->authentication_observer,
980                                            NULL,  /* GCancellable */
981                                            NULL); /* GError */
982   if (connection == NULL)
983       goto out;
984
985   if (server->flags & G_DBUS_SERVER_FLAGS_RUN_IN_THREAD)
986     {
987       gboolean claimed;
988
989       claimed = FALSE;
990       g_signal_emit (server,
991                      _signals[NEW_CONNECTION_SIGNAL],
992                      0,
993                      connection,
994                      &claimed);
995       if (claimed)
996         g_dbus_connection_start_message_processing (connection);
997       g_object_unref (connection);
998     }
999   else
1000     {
1001       GSource *idle_source;
1002       EmitIdleData *data;
1003
1004       data = g_new0 (EmitIdleData, 1);
1005       data->server = g_object_ref (server);
1006       data->connection = g_object_ref (connection);
1007
1008       idle_source = g_idle_source_new ();
1009       g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1010       g_source_set_callback (idle_source,
1011                              emit_new_connection_in_idle,
1012                              data,
1013                              (GDestroyNotify) emit_idle_data_free);
1014       g_source_attach (idle_source, server->main_context_at_construction);
1015       g_source_unref (idle_source);
1016     }
1017
1018  out:
1019   return TRUE;
1020 }
1021
1022 static gboolean
1023 initable_init (GInitable     *initable,
1024                GCancellable  *cancellable,
1025                GError       **error)
1026 {
1027   GDBusServer *server = G_DBUS_SERVER (initable);
1028   gboolean ret;
1029   guint n;
1030   gchar **addr_array;
1031   GError *last_error;
1032
1033   ret = FALSE;
1034   addr_array = NULL;
1035   last_error = NULL;
1036
1037   if (!g_dbus_is_guid (server->guid))
1038     {
1039       g_set_error (&last_error,
1040                    G_IO_ERROR,
1041                    G_IO_ERROR_INVALID_ARGUMENT,
1042                    _("The string '%s' is not a valid D-Bus GUID"),
1043                    server->guid);
1044       goto out;
1045     }
1046
1047   server->listener = G_SOCKET_LISTENER (g_threaded_socket_service_new (-1));
1048
1049   addr_array = g_strsplit (server->address, ";", 0);
1050   last_error = NULL;
1051   for (n = 0; addr_array != NULL && addr_array[n] != NULL; n++)
1052     {
1053       const gchar *address_entry = addr_array[n];
1054       GHashTable *key_value_pairs;
1055       gchar *transport_name;
1056       GError *this_error;
1057
1058       this_error = NULL;
1059       if (g_dbus_is_supported_address (address_entry,
1060                                        &this_error) &&
1061           _g_dbus_address_parse_entry (address_entry,
1062                                        &transport_name,
1063                                        &key_value_pairs,
1064                                        &this_error))
1065         {
1066
1067           if (FALSE)
1068             {
1069             }
1070 #ifdef G_OS_UNIX
1071           else if (g_strcmp0 (transport_name, "unix") == 0)
1072             ret = try_unix (server, address_entry, key_value_pairs, &this_error);
1073 #endif
1074           else if (g_strcmp0 (transport_name, "tcp") == 0)
1075             ret = try_tcp (server, address_entry, key_value_pairs, FALSE, &this_error);
1076           else if (g_strcmp0 (transport_name, "nonce-tcp") == 0)
1077             ret = try_tcp (server, address_entry, key_value_pairs, TRUE, &this_error);
1078           else
1079             g_set_error (&this_error,
1080                          G_IO_ERROR,
1081                          G_IO_ERROR_INVALID_ARGUMENT,
1082                          _("Cannot listen on unsupported transport '%s'"),
1083                          transport_name);
1084
1085           g_free (transport_name);
1086           if (key_value_pairs != NULL)
1087             g_hash_table_unref (key_value_pairs);
1088
1089           if (ret)
1090             {
1091               g_assert (this_error == NULL);
1092               goto out;
1093             }
1094         }
1095
1096       if (this_error != NULL)
1097         {
1098           if (last_error != NULL)
1099             g_error_free (last_error);
1100           last_error = this_error;
1101         }
1102     }
1103
1104  out:
1105
1106   g_strfreev (addr_array);
1107
1108   if (ret)
1109     {
1110       if (last_error != NULL)
1111         g_error_free (last_error);
1112
1113       /* Right now we don't have any transport not using the listener... */
1114       g_assert (server->is_using_listener);
1115       server->run_signal_handler_id = g_signal_connect (G_SOCKET_SERVICE (server->listener),
1116                                                         "run",
1117                                                         G_CALLBACK (on_run),
1118                                                         server);
1119     }
1120   else
1121     {
1122       g_assert (last_error != NULL);
1123       g_propagate_error (error, last_error);
1124     }
1125   return ret;
1126 }
1127
1128
1129 static void
1130 initable_iface_init (GInitableIface *initable_iface)
1131 {
1132   initable_iface->init = initable_init;
1133 }
1134
1135 /* ---------------------------------------------------------------------------------------------------- */