Merge remote-tracking branch 'gvdb/master'
[platform/upstream/glib.git] / gio / tests / gdbus-peer.c
1 /* GLib testing framework examples and tests
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 <gio/gio.h>
26 #include <unistd.h>
27 #include <string.h>
28
29 /* for open(2) */
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <string.h>
34
35 /* for g_unlink() */
36 #include <glib/gstdio.h>
37
38 #include <gio/gnetworkingprivate.h>
39 #include <gio/gunixsocketaddress.h>
40 #include <gio/gunixfdlist.h>
41
42 /* used in test_overflow */
43 #ifdef G_OS_UNIX
44 #include <gio/gunixconnection.h>
45 #include <errno.h>
46 #endif
47
48 #include "gdbus-tests.h"
49
50 #ifdef G_OS_UNIX
51 static gboolean is_unix = TRUE;
52 #else
53 static gboolean is_unix = FALSE;
54 #endif
55
56 static gchar *tmp_address = NULL;
57 static gchar *test_guid = NULL;
58 static GMainLoop *service_loop = NULL;
59 static GDBusServer *server = NULL;
60 static GMainLoop *loop = NULL;
61
62 /* ---------------------------------------------------------------------------------------------------- */
63 /* Test that peer-to-peer connections work */
64 /* ---------------------------------------------------------------------------------------------------- */
65
66
67 typedef struct
68 {
69   gboolean accept_connection;
70   gint num_connection_attempts;
71   GPtrArray *current_connections;
72   guint num_method_calls;
73   gboolean signal_received;
74 } PeerData;
75
76 static const gchar *test_interface_introspection_xml =
77   "<node>"
78   "  <interface name='org.gtk.GDBus.PeerTestInterface'>"
79   "    <method name='HelloPeer'>"
80   "      <arg type='s' name='greeting' direction='in'/>"
81   "      <arg type='s' name='response' direction='out'/>"
82   "    </method>"
83   "    <method name='EmitSignal'/>"
84   "    <method name='EmitSignalWithNameSet'/>"
85   "    <method name='OpenFile'>"
86   "      <arg type='s' name='path' direction='in'/>"
87   "    </method>"
88   "    <signal name='PeerSignal'>"
89   "      <arg type='s' name='a_string'/>"
90   "    </signal>"
91   "    <property type='s' name='PeerProperty' access='read'/>"
92   "  </interface>"
93   "</node>";
94 static GDBusInterfaceInfo *test_interface_introspection_data = NULL;
95
96 static void
97 test_interface_method_call (GDBusConnection       *connection,
98                             const gchar           *sender,
99                             const gchar           *object_path,
100                             const gchar           *interface_name,
101                             const gchar           *method_name,
102                             GVariant              *parameters,
103                             GDBusMethodInvocation *invocation,
104                             gpointer               user_data)
105 {
106   PeerData *data = user_data;
107   const GDBusMethodInfo *info;
108
109   data->num_method_calls++;
110
111   g_assert_cmpstr (object_path, ==, "/org/gtk/GDBus/PeerTestObject");
112   g_assert_cmpstr (interface_name, ==, "org.gtk.GDBus.PeerTestInterface");
113
114   info = g_dbus_method_invocation_get_method_info (invocation);
115   g_assert_cmpstr (info->name, ==, method_name);
116
117   if (g_strcmp0 (method_name, "HelloPeer") == 0)
118     {
119       const gchar *greeting;
120       gchar *response;
121
122       g_variant_get (parameters, "(&s)", &greeting);
123
124       response = g_strdup_printf ("You greeted me with '%s'.",
125                                   greeting);
126       g_dbus_method_invocation_return_value (invocation,
127                                              g_variant_new ("(s)", response));
128       g_free (response);
129     }
130   else if (g_strcmp0 (method_name, "EmitSignal") == 0)
131     {
132       GError *error;
133
134       error = NULL;
135       g_dbus_connection_emit_signal (connection,
136                                      NULL,
137                                      "/org/gtk/GDBus/PeerTestObject",
138                                      "org.gtk.GDBus.PeerTestInterface",
139                                      "PeerSignal",
140                                      NULL,
141                                      &error);
142       g_assert_no_error (error);
143       g_dbus_method_invocation_return_value (invocation, NULL);
144     }
145   else if (g_strcmp0 (method_name, "EmitSignalWithNameSet") == 0)
146     {
147       GError *error;
148       gboolean ret;
149       GDBusMessage *message;
150
151       message = g_dbus_message_new_signal ("/org/gtk/GDBus/PeerTestObject",
152                                            "org.gtk.GDBus.PeerTestInterface",
153                                            "PeerSignalWithNameSet");
154       g_dbus_message_set_sender (message, ":1.42");
155
156       error = NULL;
157       ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, &error);
158       g_assert_no_error (error);
159       g_assert (ret);
160       g_object_unref (message);
161
162       g_dbus_method_invocation_return_value (invocation, NULL);
163     }
164   else if (g_strcmp0 (method_name, "OpenFile") == 0)
165     {
166 #ifdef G_OS_UNIX
167       const gchar *path;
168       GDBusMessage *reply;
169       GError *error;
170       gint fd;
171       GUnixFDList *fd_list;
172
173       g_variant_get (parameters, "(&s)", &path);
174
175       fd_list = g_unix_fd_list_new ();
176
177       error = NULL;
178
179       fd = open (path, O_RDONLY);
180       g_unix_fd_list_append (fd_list, fd, &error);
181       g_assert_no_error (error);
182       close (fd);
183
184       reply = g_dbus_message_new_method_reply (g_dbus_method_invocation_get_message (invocation));
185       g_dbus_message_set_unix_fd_list (reply, fd_list);
186       g_object_unref (fd_list);
187       g_object_unref (invocation);
188
189       error = NULL;
190       g_dbus_connection_send_message (connection,
191                                       reply,
192                                       G_DBUS_SEND_MESSAGE_FLAGS_NONE,
193                                       NULL, /* out_serial */
194                                       &error);
195       g_assert_no_error (error);
196       g_object_unref (reply);
197 #else
198       g_dbus_method_invocation_return_dbus_error (invocation,
199                                                   "org.gtk.GDBus.NotOnUnix",
200                                                   "Your OS does not support file descriptor passing");
201 #endif
202     }
203   else
204     {
205       g_assert_not_reached ();
206     }
207 }
208
209 static GVariant *
210 test_interface_get_property (GDBusConnection  *connection,
211                              const gchar      *sender,
212                              const gchar      *object_path,
213                              const gchar      *interface_name,
214                              const gchar      *property_name,
215                              GError          **error,
216                              gpointer          user_data)
217 {
218   g_assert_cmpstr (object_path, ==, "/org/gtk/GDBus/PeerTestObject");
219   g_assert_cmpstr (interface_name, ==, "org.gtk.GDBus.PeerTestInterface");
220   g_assert_cmpstr (property_name, ==, "PeerProperty");
221
222   return g_variant_new_string ("ThePropertyValue");
223 }
224
225
226 static const GDBusInterfaceVTable test_interface_vtable =
227 {
228   test_interface_method_call,
229   test_interface_get_property,
230   NULL  /* set_property */
231 };
232
233 static void
234 on_proxy_signal_received (GDBusProxy *proxy,
235                           gchar      *sender_name,
236                           gchar      *signal_name,
237                           GVariant   *parameters,
238                           gpointer    user_data)
239 {
240   PeerData *data = user_data;
241
242   data->signal_received = TRUE;
243
244   g_assert (sender_name == NULL);
245   g_assert_cmpstr (signal_name, ==, "PeerSignal");
246   g_main_loop_quit (loop);
247 }
248
249 static void
250 on_proxy_signal_received_with_name_set (GDBusProxy *proxy,
251                                         gchar      *sender_name,
252                                         gchar      *signal_name,
253                                         GVariant   *parameters,
254                                         gpointer    user_data)
255 {
256   PeerData *data = user_data;
257
258   data->signal_received = TRUE;
259
260   g_assert_cmpstr (sender_name, ==, ":1.42");
261   g_assert_cmpstr (signal_name, ==, "PeerSignalWithNameSet");
262   g_main_loop_quit (loop);
263 }
264
265 /* ---------------------------------------------------------------------------------------------------- */
266
267 static gboolean
268 on_authorize_authenticated_peer (GDBusAuthObserver *observer,
269                                  GIOStream         *stream,
270                                  GCredentials      *credentials,
271                                  gpointer           user_data)
272 {
273   PeerData *data = user_data;
274   gboolean authorized;
275
276   data->num_connection_attempts++;
277
278   authorized = TRUE;
279   if (!data->accept_connection)
280     {
281       authorized = FALSE;
282       g_main_loop_quit (loop);
283     }
284
285   return authorized;
286 }
287
288 /* Runs in thread we created GDBusServer in (since we didn't pass G_DBUS_SERVER_FLAGS_RUN_IN_THREAD) */
289 static gboolean
290 on_new_connection (GDBusServer *server,
291                    GDBusConnection *connection,
292                    gpointer user_data)
293 {
294   PeerData *data = user_data;
295   GError *error;
296   guint reg_id;
297
298   //g_print ("Client connected.\n"
299   //         "Negotiated capabilities: unix-fd-passing=%d\n",
300   //         g_dbus_connection_get_capabilities (connection) & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
301
302   g_ptr_array_add (data->current_connections, g_object_ref (connection));
303
304   /* export object on the newly established connection */
305   error = NULL;
306   reg_id = g_dbus_connection_register_object (connection,
307                                               "/org/gtk/GDBus/PeerTestObject",
308                                               test_interface_introspection_data,
309                                               &test_interface_vtable,
310                                               data,
311                                               NULL, /* GDestroyNotify for data */
312                                               &error);
313   g_assert_no_error (error);
314   g_assert (reg_id > 0);
315
316   g_main_loop_quit (loop);
317
318   return TRUE;
319 }
320
321 static gpointer
322 service_thread_func (gpointer user_data)
323 {
324   PeerData *data = user_data;
325   GMainContext *service_context;
326   GDBusAuthObserver *observer;
327   GError *error;
328
329   service_context = g_main_context_new ();
330   g_main_context_push_thread_default (service_context);
331
332   error = NULL;
333   observer = g_dbus_auth_observer_new ();
334   server = g_dbus_server_new_sync (tmp_address,
335                                    G_DBUS_SERVER_FLAGS_NONE,
336                                    test_guid,
337                                    observer,
338                                    NULL, /* cancellable */
339                                    &error);
340   g_assert_no_error (error);
341
342   g_signal_connect (server,
343                     "new-connection",
344                     G_CALLBACK (on_new_connection),
345                     data);
346   g_signal_connect (observer,
347                     "authorize-authenticated-peer",
348                     G_CALLBACK (on_authorize_authenticated_peer),
349                     data);
350   g_object_unref (observer);
351
352   g_dbus_server_start (server);
353
354   service_loop = g_main_loop_new (service_context, FALSE);
355   g_main_loop_run (service_loop);
356
357   g_main_context_pop_thread_default (service_context);
358
359   g_main_loop_unref (service_loop);
360   g_main_context_unref (service_context);
361
362   /* test code specifically unrefs the server - see below */
363   g_assert (server == NULL);
364
365   return NULL;
366 }
367
368 #if 0
369 static gboolean
370 on_incoming_connection (GSocketService     *service,
371                         GSocketConnection  *socket_connection,
372                         GObject            *source_object,
373                         gpointer           user_data)
374 {
375   PeerData *data = user_data;
376
377   if (data->accept_connection)
378     {
379       GError *error;
380       guint reg_id;
381       GDBusConnection *connection;
382
383       error = NULL;
384       connection = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
385                                                test_guid,
386                                                G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER,
387                                                NULL, /* cancellable */
388                                                &error);
389       g_assert_no_error (error);
390
391       g_ptr_array_add (data->current_connections, connection);
392
393       /* export object on the newly established connection */
394       error = NULL;
395       reg_id = g_dbus_connection_register_object (connection,
396                                                   "/org/gtk/GDBus/PeerTestObject",
397                                                   &test_interface_introspection_data,
398                                                   &test_interface_vtable,
399                                                   data,
400                                                   NULL, /* GDestroyNotify for data */
401                                                   &error);
402       g_assert_no_error (error);
403       g_assert (reg_id > 0);
404
405     }
406   else
407     {
408       /* don't do anything */
409     }
410
411   data->num_connection_attempts++;
412
413   g_main_loop_quit (loop);
414
415   /* stops other signal handlers from being invoked */
416   return TRUE;
417 }
418
419 static gpointer
420 service_thread_func (gpointer data)
421 {
422   GMainContext *service_context;
423   gchar *socket_path;
424   GSocketAddress *address;
425   GError *error;
426
427   service_context = g_main_context_new ();
428   g_main_context_push_thread_default (service_context);
429
430   socket_path = g_strdup_printf ("/tmp/gdbus-test-pid-%d", getpid ());
431   address = g_unix_socket_address_new (socket_path);
432
433   service = g_socket_service_new ();
434   error = NULL;
435   g_socket_listener_add_address (G_SOCKET_LISTENER (service),
436                                  address,
437                                  G_SOCKET_TYPE_STREAM,
438                                  G_SOCKET_PROTOCOL_DEFAULT,
439                                  NULL, /* source_object */
440                                  NULL, /* effective_address */
441                                  &error);
442   g_assert_no_error (error);
443   g_signal_connect (service,
444                     "incoming",
445                     G_CALLBACK (on_incoming_connection),
446                     data);
447   g_socket_service_start (service);
448
449   service_loop = g_main_loop_new (service_context, FALSE);
450   g_main_loop_run (service_loop);
451
452   g_main_context_pop_thread_default (service_context);
453
454   g_main_loop_unref (service_loop);
455   g_main_context_unref (service_context);
456
457   g_object_unref (address);
458   g_free (socket_path);
459   return NULL;
460 }
461 #endif
462
463 /* ---------------------------------------------------------------------------------------------------- */
464
465 #if 0
466 static gboolean
467 check_connection (gpointer user_data)
468 {
469   PeerData *data = user_data;
470   guint n;
471
472   for (n = 0; n < data->current_connections->len; n++)
473     {
474       GDBusConnection *c;
475       GIOStream *stream;
476
477       c = G_DBUS_CONNECTION (data->current_connections->pdata[n]);
478       stream = g_dbus_connection_get_stream (c);
479
480       g_debug ("In check_connection for %d: connection %p, stream %p", n, c, stream);
481       g_debug ("closed = %d", g_io_stream_is_closed (stream));
482
483       GSocket *socket;
484       socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (stream));
485       g_debug ("socket_closed = %d", g_socket_is_closed (socket));
486       g_debug ("socket_condition_check = %d", g_socket_condition_check (socket, G_IO_IN|G_IO_OUT|G_IO_ERR|G_IO_HUP));
487
488       gchar buf[128];
489       GError *error;
490       gssize num_read;
491       error = NULL;
492       num_read = g_input_stream_read (g_io_stream_get_input_stream (stream),
493                                       buf,
494                                       128,
495                                       NULL,
496                                       &error);
497       if (num_read < 0)
498         {
499           g_debug ("error: %s", error->message);
500           g_error_free (error);
501         }
502       else
503         {
504           g_debug ("no error, read %d bytes", (gint) num_read);
505         }
506     }
507
508   return FALSE;
509 }
510
511 static gboolean
512 on_do_disconnect_in_idle (gpointer data)
513 {
514   GDBusConnection *c = G_DBUS_CONNECTION (data);
515   g_debug ("GDC %p has ref_count %d", c, G_OBJECT (c)->ref_count);
516   g_dbus_connection_disconnect (c);
517   g_object_unref (c);
518   return FALSE;
519 }
520 #endif
521
522 #ifdef G_OS_UNIX
523 static gchar *
524 read_all_from_fd (gint fd, gsize *out_len, GError **error)
525 {
526   GString *str;
527   gchar buf[64];
528   gssize num_read;
529
530   str = g_string_new (NULL);
531
532   do
533     {
534       num_read = read (fd, buf, sizeof (buf));
535       if (num_read == -1)
536         {
537           if (errno == EAGAIN || errno == EWOULDBLOCK)
538             continue;
539           g_set_error (error,
540                        G_IO_ERROR,
541                        g_io_error_from_errno (errno),
542                        "Failed reading %d bytes into offset %d: %s",
543                        (gint) sizeof (buf),
544                        (gint) str->len,
545                        strerror (errno));
546           goto error;
547         }
548       else if (num_read > 0)
549         {
550           g_string_append_len (str, buf, num_read);
551         }
552       else if (num_read == 0)
553         {
554           break;
555         }
556     }
557   while (TRUE);
558
559   if (out_len != NULL)
560     *out_len = str->len;
561   return g_string_free (str, FALSE);
562
563  error:
564   if (out_len != NULL)
565     out_len = 0;
566   g_string_free (str, TRUE);
567   return NULL;
568 }
569 #endif
570
571 static void
572 test_peer (void)
573 {
574   GDBusConnection *c;
575   GDBusConnection *c2;
576   GDBusProxy *proxy;
577   GError *error;
578   PeerData data;
579   GVariant *value;
580   GVariant *result;
581   const gchar *s;
582   GThread *service_thread;
583   gulong signal_handler_id;
584
585   memset (&data, '\0', sizeof (PeerData));
586   data.current_connections = g_ptr_array_new_with_free_func (g_object_unref);
587
588   /* first try to connect when there is no server */
589   error = NULL;
590   c = g_dbus_connection_new_for_address_sync (is_unix ? "unix:path=/tmp/gdbus-test-does-not-exist-pid" :
591                                               /* NOTE: Even if something is listening on port 12345 the connection
592                                                * will fail because the nonce file doesn't exist */
593                                               "nonce-tcp:host=localhost,port=12345,noncefile=this-does-not-exist-gdbus",
594                                               G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
595                                               NULL, /* GDBusAuthObserver */
596                                               NULL, /* cancellable */
597                                               &error);
598   _g_assert_error_domain (error, G_IO_ERROR);
599   g_assert (!g_dbus_error_is_remote_error (error));
600   g_clear_error (&error);
601   g_assert (c == NULL);
602
603   /* bring up a server - we run the server in a different thread to avoid deadlocks */
604   error = NULL;
605   service_thread = g_thread_create (service_thread_func,
606                                     &data,
607                                     TRUE,
608                                     &error);
609   while (service_loop == NULL)
610     g_thread_yield ();
611   g_assert (server != NULL);
612
613   /* bring up a connection and accept it */
614   data.accept_connection = TRUE;
615   error = NULL;
616   c = g_dbus_connection_new_for_address_sync (g_dbus_server_get_client_address (server),
617                                               G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
618                                               NULL, /* GDBusAuthObserver */
619                                               NULL, /* cancellable */
620                                               &error);
621   g_assert_no_error (error);
622   g_assert (c != NULL);
623   while (data.current_connections->len < 1)
624     g_main_loop_run (loop);
625   g_assert_cmpint (data.current_connections->len, ==, 1);
626   g_assert_cmpint (data.num_connection_attempts, ==, 1);
627   g_assert (g_dbus_connection_get_unique_name (c) == NULL);
628   g_assert_cmpstr (g_dbus_connection_get_guid (c), ==, test_guid);
629
630   /* check that we create a proxy, read properties, receive signals and invoke
631    * the HelloPeer() method. Since the server runs in another thread it's fine
632    * to use synchronous blocking API here.
633    */
634   error = NULL;
635   proxy = g_dbus_proxy_new_sync (c,
636                                  G_DBUS_PROXY_FLAGS_NONE,
637                                  NULL,
638                                  NULL, /* bus_name */
639                                  "/org/gtk/GDBus/PeerTestObject",
640                                  "org.gtk.GDBus.PeerTestInterface",
641                                  NULL, /* GCancellable */
642                                  &error);
643   g_assert_no_error (error);
644   g_assert (proxy != NULL);
645   error = NULL;
646   value = g_dbus_proxy_get_cached_property (proxy, "PeerProperty");
647   g_assert_cmpstr (g_variant_get_string (value, NULL), ==, "ThePropertyValue");
648
649   /* try invoking a method */
650   error = NULL;
651   result = g_dbus_proxy_call_sync (proxy,
652                                    "HelloPeer",
653                                    g_variant_new ("(s)", "Hey Peer!"),
654                                    G_DBUS_CALL_FLAGS_NONE,
655                                    -1,
656                                    NULL,  /* GCancellable */
657                                    &error);
658   g_assert_no_error (error);
659   g_variant_get (result, "(&s)", &s);
660   g_assert_cmpstr (s, ==, "You greeted me with 'Hey Peer!'.");
661   g_variant_unref (result);
662   g_assert_cmpint (data.num_method_calls, ==, 1);
663
664   /* make the other peer emit a signal - catch it */
665   signal_handler_id = g_signal_connect (proxy,
666                                         "g-signal",
667                                         G_CALLBACK (on_proxy_signal_received),
668                                         &data);
669   g_assert (!data.signal_received);
670   g_dbus_proxy_call (proxy,
671                      "EmitSignal",
672                      NULL,  /* no arguments */
673                      G_DBUS_CALL_FLAGS_NONE,
674                      -1,
675                      NULL,  /* GCancellable */
676                      NULL,  /* GAsyncReadyCallback - we don't care about the result */
677                      NULL); /* user_data */
678   g_main_loop_run (loop);
679   g_assert (data.signal_received);
680   g_assert_cmpint (data.num_method_calls, ==, 2);
681   g_signal_handler_disconnect (proxy, signal_handler_id);
682
683   /* Also ensure that messages with the sender header-field set gets
684    * delivered to the proxy - note that this doesn't really make sense
685    * e.g. names are meaning-less in a peer-to-peer case... but we
686    * support it because it makes sense in certain bridging
687    * applications - see e.g. #623815.
688    */
689   signal_handler_id = g_signal_connect (proxy,
690                                         "g-signal",
691                                         G_CALLBACK (on_proxy_signal_received_with_name_set),
692                                         &data);
693   data.signal_received = FALSE;
694   g_dbus_proxy_call (proxy,
695                      "EmitSignalWithNameSet",
696                      NULL,  /* no arguments */
697                      G_DBUS_CALL_FLAGS_NONE,
698                      -1,
699                      NULL,  /* GCancellable */
700                      NULL,  /* GAsyncReadyCallback - we don't care about the result */
701                      NULL); /* user_data */
702   g_main_loop_run (loop);
703   g_assert (data.signal_received);
704   g_assert_cmpint (data.num_method_calls, ==, 3);
705   g_signal_handler_disconnect (proxy, signal_handler_id);
706
707   /* check for UNIX fd passing */
708 #ifdef G_OS_UNIX
709   {
710     GDBusMessage *method_call_message;
711     GDBusMessage *method_reply_message;
712     GUnixFDList *fd_list;
713     gint fd;
714     gchar *buf;
715     gsize len;
716     gchar *buf2;
717     gsize len2;
718
719     method_call_message = g_dbus_message_new_method_call (NULL, /* name */
720                                                           "/org/gtk/GDBus/PeerTestObject",
721                                                           "org.gtk.GDBus.PeerTestInterface",
722                                                           "OpenFile");
723     g_dbus_message_set_body (method_call_message, g_variant_new ("(s)", "/etc/hosts"));
724     error = NULL;
725     method_reply_message = g_dbus_connection_send_message_with_reply_sync (c,
726                                                                            method_call_message,
727                                                                            G_DBUS_SEND_MESSAGE_FLAGS_NONE,
728                                                                            -1,
729                                                                            NULL, /* out_serial */
730                                                                            NULL, /* cancellable */
731                                                                            &error);
732     g_assert_no_error (error);
733     g_assert (g_dbus_message_get_message_type (method_reply_message) == G_DBUS_MESSAGE_TYPE_METHOD_RETURN);
734     fd_list = g_dbus_message_get_unix_fd_list (method_reply_message);
735     g_assert (fd_list != NULL);
736     g_assert_cmpint (g_unix_fd_list_get_length (fd_list), ==, 1);
737     error = NULL;
738     fd = g_unix_fd_list_get (fd_list, 0, &error);
739     g_assert_no_error (error);
740     g_object_unref (method_call_message);
741     g_object_unref (method_reply_message);
742
743     error = NULL;
744     len = 0;
745     buf = read_all_from_fd (fd, &len, &error);
746     g_assert_no_error (error);
747     g_assert (buf != NULL);
748     close (fd);
749
750     error = NULL;
751     g_file_get_contents ("/etc/hosts",
752                          &buf2,
753                          &len2,
754                          &error);
755     g_assert_no_error (error);
756     g_assert_cmpint (len, ==, len2);
757     g_assert (memcmp (buf, buf2, len) == 0);
758     g_free (buf2);
759     g_free (buf);
760   }
761 #else
762   error = NULL;
763   result = g_dbus_proxy_call_sync (proxy,
764                                    "OpenFile",
765                                    g_variant_new ("(s)", "boo"),
766                                    G_DBUS_CALL_FLAGS_NONE,
767                                    -1,
768                                    NULL,  /* GCancellable */
769                                    &error);
770   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_DBUS_ERROR);
771   g_assert (result == NULL);
772   g_error_free (error);
773 #endif /* G_OS_UNIX */
774
775   /* Check that g_socket_get_credentials() work - this really should
776    * be in a GSocket-specific test suite but no such test suite exists
777    * right now.
778    */
779   {
780     GSocket *socket;
781     GCredentials *credentials;
782     socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (g_dbus_connection_get_stream (c)));
783     g_assert (G_IS_SOCKET (socket));
784     error = NULL;
785     credentials = g_socket_get_credentials (socket, &error);
786 #ifdef __linux__
787     {
788       struct ucred *native_creds;
789       g_assert_no_error (error);
790       g_assert (G_IS_CREDENTIALS (credentials));
791       native_creds = g_credentials_get_native (credentials, G_CREDENTIALS_TYPE_LINUX_UCRED);
792       g_assert (native_creds != NULL);
793       g_assert (native_creds->uid == getuid ());
794       g_assert (native_creds->gid == getgid ());
795       g_assert (native_creds->pid == getpid ());
796     }
797     g_object_unref (credentials);
798 #else
799     g_assert_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED);
800     g_assert (credentials == NULL);
801 #endif
802   }
803
804
805   /* bring up a connection - don't accept it - this should fail
806    */
807   data.accept_connection = FALSE;
808   error = NULL;
809   c2 = g_dbus_connection_new_for_address_sync (g_dbus_server_get_client_address (server),
810                                                G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
811                                                NULL, /* GDBusAuthObserver */
812                                                NULL, /* cancellable */
813                                                &error);
814   _g_assert_error_domain (error, G_IO_ERROR);
815   g_error_free (error);
816   g_assert (c2 == NULL);
817
818 #if 0
819   /* TODO: THIS TEST DOESN'T WORK YET */
820
821   /* bring up a connection - accept it.. then disconnect from the client side - check
822    * that the server side gets the disconnect signal.
823    */
824   error = NULL;
825   data.accept_connection = TRUE;
826   c2 = g_dbus_connection_new_for_address_sync (g_dbus_server_get_client_address (server),
827                                                G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
828                                                NULL, /* GDBusAuthObserver */
829                                                NULL, /* cancellable */
830                                                &error);
831   g_assert_no_error (error);
832   g_assert (c2 != NULL);
833   g_assert (!g_dbus_connection_get_is_disconnected (c2));
834   while (data.num_connection_attempts < 3)
835     g_main_loop_run (loop);
836   g_assert_cmpint (data.current_connections->len, ==, 2);
837   g_assert_cmpint (data.num_connection_attempts, ==, 3);
838   g_assert (!g_dbus_connection_get_is_disconnected (G_DBUS_CONNECTION (data.current_connections->pdata[1])));
839   g_idle_add (on_do_disconnect_in_idle, c2);
840   g_debug ("==================================================");
841   g_debug ("==================================================");
842   g_debug ("==================================================");
843   g_debug ("waiting for disconnect on connection %p, stream %p",
844            data.current_connections->pdata[1],
845            g_dbus_connection_get_stream (data.current_connections->pdata[1]));
846
847   g_timeout_add (2000, check_connection, &data);
848   //_g_assert_signal_received (G_DBUS_CONNECTION (data.current_connections->pdata[1]), "closed");
849   g_main_loop_run (loop);
850   g_assert (g_dbus_connection_get_is_disconnected (G_DBUS_CONNECTION (data.current_connections->pdata[1])));
851   g_ptr_array_set_size (data.current_connections, 1); /* remove disconnected connection object */
852 #endif
853
854   /* unref the server and stop listening for new connections
855    *
856    * This won't bring down the established connections - check that c is still connected
857    * by invoking a method
858    */
859   //g_socket_service_stop (service);
860   //g_object_unref (service);
861   g_dbus_server_stop (server);
862   g_object_unref (server);
863   server = NULL;
864
865   error = NULL;
866   result = g_dbus_proxy_call_sync (proxy,
867                                    "HelloPeer",
868                                    g_variant_new ("(s)", "Hey Again Peer!"),
869                                    G_DBUS_CALL_FLAGS_NONE,
870                                    -1,
871                                    NULL,  /* GCancellable */
872                                    &error);
873   g_assert_no_error (error);
874   g_variant_get (result, "(&s)", &s);
875   g_assert_cmpstr (s, ==, "You greeted me with 'Hey Again Peer!'.");
876   g_variant_unref (result);
877   g_assert_cmpint (data.num_method_calls, ==, 5);
878
879 #if 0
880   /* TODO: THIS TEST DOESN'T WORK YET */
881
882   /* now disconnect from the server side - check that the client side gets the signal */
883   g_assert_cmpint (data.current_connections->len, ==, 1);
884   g_assert (G_DBUS_CONNECTION (data.current_connections->pdata[0]) != c);
885   g_dbus_connection_disconnect (G_DBUS_CONNECTION (data.current_connections->pdata[0]));
886   if (!g_dbus_connection_get_is_disconnected (c))
887     _g_assert_signal_received (c, "closed");
888   g_assert (g_dbus_connection_get_is_disconnected (c));
889 #endif
890
891   g_object_unref (c);
892   g_ptr_array_unref (data.current_connections);
893   g_object_unref (proxy);
894
895   g_main_loop_quit (service_loop);
896   g_thread_join (service_thread);
897 }
898
899 /* ---------------------------------------------------------------------------------------------------- */
900
901 typedef struct
902 {
903   GDBusServer *server;
904   GMainContext *context;
905   GMainLoop *loop;
906
907   GList *connections;
908 } DmpData;
909
910 static void
911 dmp_data_free (DmpData *data)
912 {
913   g_main_loop_unref (data->loop);
914   g_main_context_unref (data->context);
915   g_object_unref (data->server);
916   g_list_foreach (data->connections, (GFunc) g_object_unref, NULL);
917   g_list_free (data->connections);
918   g_free (data);
919 }
920
921 static void
922 dmp_on_method_call (GDBusConnection       *connection,
923                     const gchar           *sender,
924                     const gchar           *object_path,
925                     const gchar           *interface_name,
926                     const gchar           *method_name,
927                     GVariant              *parameters,
928                     GDBusMethodInvocation *invocation,
929                     gpointer               user_data)
930 {
931   //DmpData *data = user_data;
932   gint32 first;
933   gint32 second;
934   g_variant_get (parameters,
935                  "(ii)",
936                  &first,
937                  &second);
938   g_dbus_method_invocation_return_value (invocation,
939                                          g_variant_new ("(i)", first + second));
940 }
941
942 static const GDBusInterfaceVTable dmp_interface_vtable =
943 {
944   dmp_on_method_call,
945   NULL,  /* get_property */
946   NULL   /* set_property */
947 };
948
949
950 /* Runs in thread we created GDBusServer in (since we didn't pass G_DBUS_SERVER_FLAGS_RUN_IN_THREAD) */
951 static gboolean
952 dmp_on_new_connection (GDBusServer     *server,
953                        GDBusConnection *connection,
954                        gpointer         user_data)
955 {
956   DmpData *data = user_data;
957   GDBusNodeInfo *node;
958   GError *error;
959
960   /* accept the connection */
961   data->connections = g_list_prepend (data->connections, g_object_ref (connection));
962
963   error = NULL;
964   node = g_dbus_node_info_new_for_xml ("<node>"
965                                        "  <interface name='org.gtk.GDBus.DmpInterface'>"
966                                        "    <method name='AddPair'>"
967                                        "      <arg type='i' name='first' direction='in'/>"
968                                        "      <arg type='i' name='second' direction='in'/>"
969                                        "      <arg type='i' name='sum' direction='out'/>"
970                                        "    </method>"
971                                        "  </interface>"
972                                        "</node>",
973                                        &error);
974   g_assert_no_error (error);
975
976   /* sleep 100ms before exporting an object - this is to test that
977    * G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING really works
978    * (GDBusServer uses this feature).
979    */
980   usleep (100 * 1000);
981
982   /* export an object */
983   error = NULL;
984   g_dbus_connection_register_object (connection,
985                                      "/dmp/test",
986                                      node->interfaces[0],
987                                      &dmp_interface_vtable,
988                                      data,
989                                      NULL,
990                                      &error);
991   g_dbus_node_info_unref (node);
992
993   return TRUE;
994 }
995
996 static gpointer
997 dmp_thread_func (gpointer user_data)
998 {
999   DmpData *data = user_data;
1000   GError *error;
1001   gchar *guid;
1002
1003   data->context = g_main_context_new ();
1004   g_main_context_push_thread_default (data->context);
1005
1006   error = NULL;
1007   guid = g_dbus_generate_guid ();
1008   data->server = g_dbus_server_new_sync (tmp_address,
1009                                          G_DBUS_SERVER_FLAGS_NONE,
1010                                          guid,
1011                                          NULL, /* GDBusAuthObserver */
1012                                          NULL, /* GCancellable */
1013                                          &error);
1014   g_assert_no_error (error);
1015   g_signal_connect (data->server,
1016                     "new-connection",
1017                     G_CALLBACK (dmp_on_new_connection),
1018                     data);
1019
1020   g_dbus_server_start (data->server);
1021
1022   data->loop = g_main_loop_new (data->context, FALSE);
1023   g_main_loop_run (data->loop);
1024
1025   g_main_context_pop_thread_default (data->context);
1026
1027   g_free (guid);
1028   return NULL;
1029 }
1030
1031 static void
1032 delayed_message_processing (void)
1033 {
1034   GError *error;
1035   DmpData *data;
1036   GThread *service_thread;
1037   guint n;
1038
1039   data = g_new0 (DmpData, 1);
1040
1041   error = NULL;
1042   service_thread = g_thread_create (dmp_thread_func,
1043                                     data,
1044                                     TRUE,
1045                                     &error);
1046   while (data->server == NULL || !g_dbus_server_is_active (data->server))
1047     g_thread_yield ();
1048
1049   for (n = 0; n < 5; n++)
1050     {
1051       GDBusConnection *c;
1052       GVariant *res;
1053       gint32 val;
1054
1055       error = NULL;
1056       c = g_dbus_connection_new_for_address_sync (g_dbus_server_get_client_address (data->server),
1057                                                   G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
1058                                                   NULL, /* GDBusAuthObserver */
1059                                                   NULL, /* GCancellable */
1060                                                   &error);
1061       g_assert_no_error (error);
1062
1063       error = NULL;
1064       res = g_dbus_connection_call_sync (c,
1065                                          NULL,    /* bus name */
1066                                          "/dmp/test",
1067                                          "org.gtk.GDBus.DmpInterface",
1068                                          "AddPair",
1069                                          g_variant_new ("(ii)", 2, n),
1070                                          G_VARIANT_TYPE ("(i)"),
1071                                          G_DBUS_CALL_FLAGS_NONE,
1072                                          -1, /* timeout_msec */
1073                                          NULL, /* GCancellable */
1074                                          &error);
1075       g_assert_no_error (error);
1076       g_variant_get (res, "(i)", &val);
1077       g_assert_cmpint (val, ==, 2 + n);
1078       g_variant_unref (res);
1079       g_object_unref (c);
1080   }
1081
1082   g_main_loop_quit (data->loop);
1083   g_thread_join (service_thread);
1084   dmp_data_free (data);
1085 }
1086
1087 /* ---------------------------------------------------------------------------------------------------- */
1088
1089 static gboolean
1090 nonce_tcp_on_authorize_authenticated_peer (GDBusAuthObserver *observer,
1091                                            GIOStream         *stream,
1092                                            GCredentials      *credentials,
1093                                            gpointer           user_data)
1094 {
1095   PeerData *data = user_data;
1096   gboolean authorized;
1097
1098   data->num_connection_attempts++;
1099
1100   authorized = TRUE;
1101   if (!data->accept_connection)
1102     {
1103       authorized = FALSE;
1104       g_main_loop_quit (loop);
1105     }
1106
1107   return authorized;
1108 }
1109
1110 /* Runs in thread we created GDBusServer in (since we didn't pass G_DBUS_SERVER_FLAGS_RUN_IN_THREAD) */
1111 static gboolean
1112 nonce_tcp_on_new_connection (GDBusServer *server,
1113                              GDBusConnection *connection,
1114                              gpointer user_data)
1115 {
1116   PeerData *data = user_data;
1117
1118   g_ptr_array_add (data->current_connections, g_object_ref (connection));
1119
1120   g_main_loop_quit (loop);
1121
1122   return TRUE;
1123 }
1124
1125 static gpointer
1126 nonce_tcp_service_thread_func (gpointer user_data)
1127 {
1128   PeerData *data = user_data;
1129   GMainContext *service_context;
1130   GDBusAuthObserver *observer;
1131   GError *error;
1132
1133   service_context = g_main_context_new ();
1134   g_main_context_push_thread_default (service_context);
1135
1136   error = NULL;
1137   observer = g_dbus_auth_observer_new ();
1138   server = g_dbus_server_new_sync ("nonce-tcp:",
1139                                    G_DBUS_SERVER_FLAGS_NONE,
1140                                    test_guid,
1141                                    observer,
1142                                    NULL, /* cancellable */
1143                                    &error);
1144   g_assert_no_error (error);
1145
1146   g_signal_connect (server,
1147                     "new-connection",
1148                     G_CALLBACK (nonce_tcp_on_new_connection),
1149                     data);
1150   g_signal_connect (observer,
1151                     "authorize-authenticated-peer",
1152                     G_CALLBACK (nonce_tcp_on_authorize_authenticated_peer),
1153                     data);
1154   g_object_unref (observer);
1155
1156   g_dbus_server_start (server);
1157
1158   service_loop = g_main_loop_new (service_context, FALSE);
1159   g_main_loop_run (service_loop);
1160
1161   g_main_context_pop_thread_default (service_context);
1162
1163   g_main_loop_unref (service_loop);
1164   g_main_context_unref (service_context);
1165
1166   /* test code specifically unrefs the server - see below */
1167   g_assert (server == NULL);
1168
1169   return NULL;
1170 }
1171
1172 static void
1173 test_nonce_tcp (void)
1174 {
1175   PeerData data;
1176   GError *error;
1177   GThread *service_thread;
1178   GDBusConnection *c;
1179   gchar *s;
1180   gchar *nonce_file;
1181   gboolean res;
1182   const gchar *address;
1183
1184   memset (&data, '\0', sizeof (PeerData));
1185   data.current_connections = g_ptr_array_new_with_free_func (g_object_unref);
1186
1187   error = NULL;
1188   server = NULL;
1189   service_loop = NULL;
1190   service_thread = g_thread_create (nonce_tcp_service_thread_func,
1191                                     &data,
1192                                     TRUE,
1193                                     &error);
1194   while (service_loop == NULL)
1195     g_thread_yield ();
1196   g_assert (server != NULL);
1197
1198
1199   /* bring up a connection and accept it */
1200   data.accept_connection = TRUE;
1201   error = NULL;
1202   c = g_dbus_connection_new_for_address_sync (g_dbus_server_get_client_address (server),
1203                                               G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
1204                                               NULL, /* GDBusAuthObserver */
1205                                               NULL, /* cancellable */
1206                                               &error);
1207   g_assert_no_error (error);
1208   g_assert (c != NULL);
1209   while (data.current_connections->len < 1)
1210     g_thread_yield ();
1211   g_assert_cmpint (data.current_connections->len, ==, 1);
1212   g_assert_cmpint (data.num_connection_attempts, ==, 1);
1213   g_assert (g_dbus_connection_get_unique_name (c) == NULL);
1214   g_assert_cmpstr (g_dbus_connection_get_guid (c), ==, test_guid);
1215   g_object_unref (c);
1216
1217   /* now, try to subvert the nonce file (this assumes noncefile is the last key/value pair)
1218    */
1219
1220   address = g_dbus_server_get_client_address (server);
1221
1222   s = strstr (address, "noncefile=");
1223   g_assert (s != NULL);
1224   s += sizeof "noncefile=" - 1;
1225   nonce_file = g_strdup (s);
1226
1227   /* First try invalid data in the nonce file - this will actually
1228    * make the client send this and the server will reject it. The way
1229    * it works is that if the nonce doesn't match, the server will
1230    * simply close the connection. So, from the client point of view,
1231    * we can see a variety of errors.
1232    */
1233   error = NULL;
1234   res = g_file_set_contents (nonce_file,
1235                              "0123456789012345",
1236                              -1,
1237                              &error);
1238   g_assert_no_error (error);
1239   g_assert (res);
1240   c = g_dbus_connection_new_for_address_sync (address,
1241                                               G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
1242                                               NULL, /* GDBusAuthObserver */
1243                                               NULL, /* cancellable */
1244                                               &error);
1245   _g_assert_error_domain (error, G_IO_ERROR);
1246   g_error_free (error);
1247   g_assert (c == NULL);
1248
1249   /* Then try with a nonce-file of incorrect length - this will make
1250    * the client complain - we won't even try connecting to the server
1251    * for this
1252    */
1253   error = NULL;
1254   res = g_file_set_contents (nonce_file,
1255                              "0123456789012345_",
1256                              -1,
1257                              &error);
1258   g_assert_no_error (error);
1259   g_assert (res);
1260   c = g_dbus_connection_new_for_address_sync (address,
1261                                               G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
1262                                               NULL, /* GDBusAuthObserver */
1263                                               NULL, /* cancellable */
1264                                               &error);
1265   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT);
1266   g_error_free (error);
1267   g_assert (c == NULL);
1268
1269   /* Finally try with no nonce-file at all */
1270   g_assert_cmpint (g_unlink (nonce_file), ==, 0);
1271   error = NULL;
1272   c = g_dbus_connection_new_for_address_sync (address,
1273                                               G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
1274                                               NULL, /* GDBusAuthObserver */
1275                                               NULL, /* cancellable */
1276                                               &error);
1277   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT);
1278   g_error_free (error);
1279   g_assert (c == NULL);
1280
1281   g_free (nonce_file);
1282
1283   g_dbus_server_stop (server);
1284   g_object_unref (server);
1285   server = NULL;
1286
1287   g_main_loop_quit (service_loop);
1288   g_thread_join (service_thread);
1289 }
1290
1291 static void
1292 test_credentials (void)
1293 {
1294   GCredentials *c1, *c2;
1295   GError *error;
1296   gchar *desc;
1297
1298   c1 = g_credentials_new ();
1299   c2 = g_credentials_new ();
1300
1301   error = NULL;
1302   if (g_credentials_set_unix_user (c2, getuid (), &error))
1303     g_assert_no_error (error);
1304
1305   g_clear_error (&error);
1306   g_assert (g_credentials_is_same_user (c1, c2, &error));
1307   g_assert_no_error (error);
1308
1309   desc = g_credentials_to_string (c1);
1310   g_assert (desc != NULL);
1311   g_free (desc);
1312
1313   g_object_unref (c1);
1314   g_object_unref (c2);
1315 }
1316
1317 /* ---------------------------------------------------------------------------------------------------- */
1318
1319 #ifdef G_OS_UNIX
1320
1321 /* Chosen to be big enough to overflow the socket buffer */
1322 #define OVERFLOW_NUM_SIGNALS 5000
1323 #define OVERFLOW_TIMEOUT_SEC 10
1324
1325 static GDBusMessage *
1326 overflow_filter_func (GDBusConnection *connection,
1327                       GDBusMessage    *message,
1328                       gboolean         incoming,
1329                       gpointer         user_data)
1330 {
1331   volatile gint *counter = user_data;
1332   *counter += 1;
1333   return message;
1334 }
1335
1336 static gboolean
1337 overflow_on_500ms_later_func (gpointer user_data)
1338 {
1339   g_main_loop_quit (loop);
1340   return FALSE; /* don't keep the idle */
1341 }
1342
1343 static void
1344 test_overflow (void)
1345 {
1346   gint sv[2];
1347   gint n;
1348   GSocket *socket;
1349   GSocketConnection *socket_connection;
1350   GDBusConnection *producer, *consumer;
1351   GError *error;
1352   GTimer *timer;
1353   volatile gint n_messages_received;
1354   volatile gint n_messages_sent;
1355
1356   g_assert_cmpint (socketpair (AF_UNIX, SOCK_STREAM, 0, sv), ==, 0);
1357
1358   error = NULL;
1359   socket = g_socket_new_from_fd (sv[0], &error);
1360   g_assert_no_error (error);
1361   socket_connection = g_socket_connection_factory_create_connection (socket);
1362   g_assert (socket_connection != NULL);
1363   g_object_unref (socket);
1364   producer = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
1365                                          NULL, /* guid */
1366                                          G_DBUS_CONNECTION_FLAGS_NONE,
1367                                          NULL, /* GDBusAuthObserver */
1368                                          NULL, /* GCancellable */
1369                                          &error);
1370   g_dbus_connection_set_exit_on_close (producer, TRUE);
1371   g_assert_no_error (error);
1372   g_object_unref (socket_connection);
1373   n_messages_sent = 0;
1374   g_dbus_connection_add_filter (producer, overflow_filter_func, (gpointer) &n_messages_sent, NULL);
1375
1376   /* send enough data that we get an EAGAIN */
1377   for (n = 0; n < OVERFLOW_NUM_SIGNALS; n++)
1378     {
1379       error = NULL;
1380       g_dbus_connection_emit_signal (producer,
1381                                      NULL, /* destination */
1382                                      "/org/foo/Object",
1383                                      "org.foo.Interface",
1384                                      "Member",
1385                                      g_variant_new ("(s)", "a string"),
1386                                      &error);
1387       g_assert_no_error (error);
1388     }
1389
1390   /* sleep for 0.5 sec (to allow the GDBus IO thread to fill up the
1391    * kernel buffers) and verify that n_messages_sent <
1392    * OVERFLOW_NUM_SIGNALS
1393    *
1394    * This is to verify that not all the submitted messages have been
1395    * sent to the underlying transport.
1396    */
1397   g_timeout_add (500, overflow_on_500ms_later_func, NULL);
1398   g_main_loop_run (loop);
1399   g_assert_cmpint (n_messages_sent, <, OVERFLOW_NUM_SIGNALS);
1400
1401   /* now suck it all out as a client, and add it up */
1402   socket = g_socket_new_from_fd (sv[1], &error);
1403   g_assert_no_error (error);
1404   socket_connection = g_socket_connection_factory_create_connection (socket);
1405   g_assert (socket_connection != NULL);
1406   g_object_unref (socket);
1407   consumer = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
1408                                          NULL, /* guid */
1409                                          G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING,
1410                                          NULL, /* GDBusAuthObserver */
1411                                          NULL, /* GCancellable */
1412                                          &error);
1413   g_assert_no_error (error);
1414   g_object_unref (socket_connection);
1415   n_messages_received = 0;
1416   g_dbus_connection_add_filter (consumer, overflow_filter_func, (gpointer) &n_messages_received, NULL);
1417   g_dbus_connection_start_message_processing (consumer);
1418
1419   timer = g_timer_new ();
1420   g_timer_start (timer);
1421
1422   while (n_messages_received < OVERFLOW_NUM_SIGNALS && g_timer_elapsed (timer, NULL) < OVERFLOW_TIMEOUT_SEC)
1423       g_main_context_iteration (NULL, FALSE);
1424
1425   g_assert_cmpint (n_messages_sent, ==, OVERFLOW_NUM_SIGNALS);
1426   g_assert_cmpint (n_messages_received, ==, OVERFLOW_NUM_SIGNALS);
1427
1428   g_timer_destroy (timer);
1429   g_object_unref (consumer);
1430   g_object_unref (producer);
1431 }
1432 #else
1433 static void
1434 test_overflow (void)
1435 {
1436   /* TODO: test this with e.g. GWin32InputStream/GWin32OutputStream */
1437 }
1438 #endif
1439
1440 /* ---------------------------------------------------------------------------------------------------- */
1441
1442 static gboolean
1443 tcp_anonymous_on_new_connection (GDBusServer     *server,
1444                                  GDBusConnection *connection,
1445                                  gpointer         user_data)
1446 {
1447   gboolean *seen_connection = user_data;
1448   *seen_connection = TRUE;
1449   return TRUE;
1450 }
1451
1452 static gpointer
1453 tcp_anonymous_service_thread_func (gpointer user_data)
1454 {
1455   gboolean *seen_connection = user_data;
1456   GMainContext *service_context;
1457   GError *error;
1458
1459   service_context = g_main_context_new ();
1460   g_main_context_push_thread_default (service_context);
1461
1462   error = NULL;
1463   server = g_dbus_server_new_sync ("tcp:",
1464                                    G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS,
1465                                    test_guid,
1466                                    NULL, /* GDBusObserver* */
1467                                    NULL, /* GCancellable* */
1468                                    &error);
1469   g_assert_no_error (error);
1470
1471   g_signal_connect (server,
1472                     "new-connection",
1473                     G_CALLBACK (tcp_anonymous_on_new_connection),
1474                     seen_connection);
1475
1476   g_dbus_server_start (server);
1477
1478   service_loop = g_main_loop_new (service_context, FALSE);
1479   g_main_loop_run (service_loop);
1480
1481   g_main_context_pop_thread_default (service_context);
1482
1483   g_main_loop_unref (service_loop);
1484   g_main_context_unref (service_context);
1485
1486   return NULL;
1487 }
1488
1489 static void
1490 test_tcp_anonymous (void)
1491 {
1492   gboolean seen_connection;
1493   GThread *service_thread;
1494   GDBusConnection *connection;
1495   GError *error;
1496
1497   seen_connection = FALSE;
1498   service_loop = NULL;
1499   service_thread = g_thread_create (tcp_anonymous_service_thread_func,
1500                                     &seen_connection, /* user_data */
1501                                     TRUE, /* joinable */
1502                                     &error);
1503   while (service_loop == NULL)
1504     g_thread_yield ();
1505   g_assert (server != NULL);
1506
1507   error = NULL;
1508   connection = g_dbus_connection_new_for_address_sync (g_dbus_server_get_client_address (server),
1509                                                        G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
1510                                                        NULL, /* GDBusAuthObserver* */
1511                                                        NULL, /* GCancellable */
1512                                                        &error);
1513   g_assert_no_error (error);
1514   g_assert (connection != NULL);
1515
1516   while (!seen_connection)
1517     g_thread_yield ();
1518
1519   g_object_unref (connection);
1520
1521   g_main_loop_quit (service_loop);
1522   g_dbus_server_stop (server);
1523   g_object_unref (server);
1524   server = NULL;
1525
1526   g_thread_join (service_thread);
1527 }
1528
1529 /* ---------------------------------------------------------------------------------------------------- */
1530
1531 int
1532 main (int   argc,
1533       char *argv[])
1534 {
1535   gint ret;
1536   GDBusNodeInfo *introspection_data = NULL;
1537   gchar *tmpdir = NULL;
1538
1539   g_type_init ();
1540   g_thread_init (NULL);
1541   g_test_init (&argc, &argv, NULL);
1542
1543   g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");
1544
1545   introspection_data = g_dbus_node_info_new_for_xml (test_interface_introspection_xml, NULL);
1546   g_assert (introspection_data != NULL);
1547   test_interface_introspection_data = introspection_data->interfaces[0];
1548
1549   test_guid = g_dbus_generate_guid ();
1550
1551   if (is_unix)
1552     {
1553       if (g_unix_socket_address_abstract_names_supported ())
1554         tmp_address = g_strdup ("unix:tmpdir=/tmp/gdbus-test-");
1555       else
1556         {
1557           tmpdir = g_dir_make_tmp ("gdbus-test-XXXXXX", NULL);
1558           tmp_address = g_strdup_printf ("unix:tmpdir=%s", tmpdir);
1559         }
1560     }
1561   else
1562     tmp_address = g_strdup ("nonce-tcp:");
1563
1564   /* all the tests rely on a shared main loop */
1565   loop = g_main_loop_new (NULL, FALSE);
1566
1567   g_test_add_func ("/gdbus/peer-to-peer", test_peer);
1568   g_test_add_func ("/gdbus/delayed-message-processing", delayed_message_processing);
1569   g_test_add_func ("/gdbus/nonce-tcp", test_nonce_tcp);
1570   g_test_add_func ("/gdbus/tcp-anonymous", test_tcp_anonymous);
1571   g_test_add_func ("/gdbus/credentials", test_credentials);
1572   g_test_add_func ("/gdbus/overflow", test_overflow);
1573
1574   ret = g_test_run();
1575
1576   g_main_loop_unref (loop);
1577   g_free (test_guid);
1578   g_dbus_node_info_unref (introspection_data);
1579   if (is_unix)
1580     g_free (tmp_address);
1581   if (tmpdir)
1582     {
1583       g_rmdir (tmpdir);
1584       g_free (tmpdir);
1585     }
1586
1587   return ret;
1588 }