g_thread_new: never fail
[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   service_thread = g_thread_new ("test_peer",
605                                  service_thread_func,
606                                  &data);
607   while (service_loop == NULL)
608     g_thread_yield ();
609   g_assert (server != NULL);
610
611   /* bring up a connection and accept it */
612   data.accept_connection = TRUE;
613   error = NULL;
614   c = g_dbus_connection_new_for_address_sync (g_dbus_server_get_client_address (server),
615                                               G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
616                                               NULL, /* GDBusAuthObserver */
617                                               NULL, /* cancellable */
618                                               &error);
619   g_assert_no_error (error);
620   g_assert (c != NULL);
621   while (data.current_connections->len < 1)
622     g_main_loop_run (loop);
623   g_assert_cmpint (data.current_connections->len, ==, 1);
624   g_assert_cmpint (data.num_connection_attempts, ==, 1);
625   g_assert (g_dbus_connection_get_unique_name (c) == NULL);
626   g_assert_cmpstr (g_dbus_connection_get_guid (c), ==, test_guid);
627
628   /* check that we create a proxy, read properties, receive signals and invoke
629    * the HelloPeer() method. Since the server runs in another thread it's fine
630    * to use synchronous blocking API here.
631    */
632   error = NULL;
633   proxy = g_dbus_proxy_new_sync (c,
634                                  G_DBUS_PROXY_FLAGS_NONE,
635                                  NULL,
636                                  NULL, /* bus_name */
637                                  "/org/gtk/GDBus/PeerTestObject",
638                                  "org.gtk.GDBus.PeerTestInterface",
639                                  NULL, /* GCancellable */
640                                  &error);
641   g_assert_no_error (error);
642   g_assert (proxy != NULL);
643   error = NULL;
644   value = g_dbus_proxy_get_cached_property (proxy, "PeerProperty");
645   g_assert_cmpstr (g_variant_get_string (value, NULL), ==, "ThePropertyValue");
646
647   /* try invoking a method */
648   error = NULL;
649   result = g_dbus_proxy_call_sync (proxy,
650                                    "HelloPeer",
651                                    g_variant_new ("(s)", "Hey Peer!"),
652                                    G_DBUS_CALL_FLAGS_NONE,
653                                    -1,
654                                    NULL,  /* GCancellable */
655                                    &error);
656   g_assert_no_error (error);
657   g_variant_get (result, "(&s)", &s);
658   g_assert_cmpstr (s, ==, "You greeted me with 'Hey Peer!'.");
659   g_variant_unref (result);
660   g_assert_cmpint (data.num_method_calls, ==, 1);
661
662   /* make the other peer emit a signal - catch it */
663   signal_handler_id = g_signal_connect (proxy,
664                                         "g-signal",
665                                         G_CALLBACK (on_proxy_signal_received),
666                                         &data);
667   g_assert (!data.signal_received);
668   g_dbus_proxy_call (proxy,
669                      "EmitSignal",
670                      NULL,  /* no arguments */
671                      G_DBUS_CALL_FLAGS_NONE,
672                      -1,
673                      NULL,  /* GCancellable */
674                      NULL,  /* GAsyncReadyCallback - we don't care about the result */
675                      NULL); /* user_data */
676   g_main_loop_run (loop);
677   g_assert (data.signal_received);
678   g_assert_cmpint (data.num_method_calls, ==, 2);
679   g_signal_handler_disconnect (proxy, signal_handler_id);
680
681   /* Also ensure that messages with the sender header-field set gets
682    * delivered to the proxy - note that this doesn't really make sense
683    * e.g. names are meaning-less in a peer-to-peer case... but we
684    * support it because it makes sense in certain bridging
685    * applications - see e.g. #623815.
686    */
687   signal_handler_id = g_signal_connect (proxy,
688                                         "g-signal",
689                                         G_CALLBACK (on_proxy_signal_received_with_name_set),
690                                         &data);
691   data.signal_received = FALSE;
692   g_dbus_proxy_call (proxy,
693                      "EmitSignalWithNameSet",
694                      NULL,  /* no arguments */
695                      G_DBUS_CALL_FLAGS_NONE,
696                      -1,
697                      NULL,  /* GCancellable */
698                      NULL,  /* GAsyncReadyCallback - we don't care about the result */
699                      NULL); /* user_data */
700   g_main_loop_run (loop);
701   g_assert (data.signal_received);
702   g_assert_cmpint (data.num_method_calls, ==, 3);
703   g_signal_handler_disconnect (proxy, signal_handler_id);
704
705   /* check for UNIX fd passing */
706 #ifdef G_OS_UNIX
707   {
708     GDBusMessage *method_call_message;
709     GDBusMessage *method_reply_message;
710     GUnixFDList *fd_list;
711     gint fd;
712     gchar *buf;
713     gsize len;
714     gchar *buf2;
715     gsize len2;
716
717     method_call_message = g_dbus_message_new_method_call (NULL, /* name */
718                                                           "/org/gtk/GDBus/PeerTestObject",
719                                                           "org.gtk.GDBus.PeerTestInterface",
720                                                           "OpenFile");
721     g_dbus_message_set_body (method_call_message, g_variant_new ("(s)", "/etc/hosts"));
722     error = NULL;
723     method_reply_message = g_dbus_connection_send_message_with_reply_sync (c,
724                                                                            method_call_message,
725                                                                            G_DBUS_SEND_MESSAGE_FLAGS_NONE,
726                                                                            -1,
727                                                                            NULL, /* out_serial */
728                                                                            NULL, /* cancellable */
729                                                                            &error);
730     g_assert_no_error (error);
731     g_assert (g_dbus_message_get_message_type (method_reply_message) == G_DBUS_MESSAGE_TYPE_METHOD_RETURN);
732     fd_list = g_dbus_message_get_unix_fd_list (method_reply_message);
733     g_assert (fd_list != NULL);
734     g_assert_cmpint (g_unix_fd_list_get_length (fd_list), ==, 1);
735     error = NULL;
736     fd = g_unix_fd_list_get (fd_list, 0, &error);
737     g_assert_no_error (error);
738     g_object_unref (method_call_message);
739     g_object_unref (method_reply_message);
740
741     error = NULL;
742     len = 0;
743     buf = read_all_from_fd (fd, &len, &error);
744     g_assert_no_error (error);
745     g_assert (buf != NULL);
746     close (fd);
747
748     error = NULL;
749     g_file_get_contents ("/etc/hosts",
750                          &buf2,
751                          &len2,
752                          &error);
753     g_assert_no_error (error);
754     g_assert_cmpint (len, ==, len2);
755     g_assert (memcmp (buf, buf2, len) == 0);
756     g_free (buf2);
757     g_free (buf);
758   }
759 #else
760   error = NULL;
761   result = g_dbus_proxy_call_sync (proxy,
762                                    "OpenFile",
763                                    g_variant_new ("(s)", "boo"),
764                                    G_DBUS_CALL_FLAGS_NONE,
765                                    -1,
766                                    NULL,  /* GCancellable */
767                                    &error);
768   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_DBUS_ERROR);
769   g_assert (result == NULL);
770   g_error_free (error);
771 #endif /* G_OS_UNIX */
772
773   /* Check that g_socket_get_credentials() work - this really should
774    * be in a GSocket-specific test suite but no such test suite exists
775    * right now.
776    */
777   {
778     GSocket *socket;
779     GCredentials *credentials;
780     socket = g_socket_connection_get_socket (G_SOCKET_CONNECTION (g_dbus_connection_get_stream (c)));
781     g_assert (G_IS_SOCKET (socket));
782     error = NULL;
783     credentials = g_socket_get_credentials (socket, &error);
784 #ifdef __linux__
785     {
786       struct ucred *native_creds;
787       g_assert_no_error (error);
788       g_assert (G_IS_CREDENTIALS (credentials));
789       native_creds = g_credentials_get_native (credentials, G_CREDENTIALS_TYPE_LINUX_UCRED);
790       g_assert (native_creds != NULL);
791       g_assert (native_creds->uid == getuid ());
792       g_assert (native_creds->gid == getgid ());
793       g_assert (native_creds->pid == getpid ());
794     }
795     g_object_unref (credentials);
796 #elif defined (__OpenBSD__)
797     {
798       struct sockpeercred *native_creds;
799       g_assert_no_error (error);
800       g_assert (G_IS_CREDENTIALS (credentials));
801       native_creds = g_credentials_get_native (credentials, G_CREDENTIALS_TYPE_OPENBSD_SOCKPEERCRED);
802       g_assert (native_creds != NULL);
803       g_assert (native_creds->uid == getuid ());
804       g_assert (native_creds->gid == getgid ());
805       g_assert (native_creds->pid == getpid ());
806     }
807     g_object_unref (credentials);
808 #else
809     g_assert_error (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED);
810     g_assert (credentials == NULL);
811 #endif
812   }
813
814
815   /* bring up a connection - don't accept it - this should fail
816    */
817   data.accept_connection = FALSE;
818   error = NULL;
819   c2 = g_dbus_connection_new_for_address_sync (g_dbus_server_get_client_address (server),
820                                                G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
821                                                NULL, /* GDBusAuthObserver */
822                                                NULL, /* cancellable */
823                                                &error);
824   _g_assert_error_domain (error, G_IO_ERROR);
825   g_error_free (error);
826   g_assert (c2 == NULL);
827
828 #if 0
829   /* TODO: THIS TEST DOESN'T WORK YET */
830
831   /* bring up a connection - accept it.. then disconnect from the client side - check
832    * that the server side gets the disconnect signal.
833    */
834   error = NULL;
835   data.accept_connection = TRUE;
836   c2 = g_dbus_connection_new_for_address_sync (g_dbus_server_get_client_address (server),
837                                                G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
838                                                NULL, /* GDBusAuthObserver */
839                                                NULL, /* cancellable */
840                                                &error);
841   g_assert_no_error (error);
842   g_assert (c2 != NULL);
843   g_assert (!g_dbus_connection_get_is_disconnected (c2));
844   while (data.num_connection_attempts < 3)
845     g_main_loop_run (loop);
846   g_assert_cmpint (data.current_connections->len, ==, 2);
847   g_assert_cmpint (data.num_connection_attempts, ==, 3);
848   g_assert (!g_dbus_connection_get_is_disconnected (G_DBUS_CONNECTION (data.current_connections->pdata[1])));
849   g_idle_add (on_do_disconnect_in_idle, c2);
850   g_debug ("==================================================");
851   g_debug ("==================================================");
852   g_debug ("==================================================");
853   g_debug ("waiting for disconnect on connection %p, stream %p",
854            data.current_connections->pdata[1],
855            g_dbus_connection_get_stream (data.current_connections->pdata[1]));
856
857   g_timeout_add (2000, check_connection, &data);
858   //_g_assert_signal_received (G_DBUS_CONNECTION (data.current_connections->pdata[1]), "closed");
859   g_main_loop_run (loop);
860   g_assert (g_dbus_connection_get_is_disconnected (G_DBUS_CONNECTION (data.current_connections->pdata[1])));
861   g_ptr_array_set_size (data.current_connections, 1); /* remove disconnected connection object */
862 #endif
863
864   /* unref the server and stop listening for new connections
865    *
866    * This won't bring down the established connections - check that c is still connected
867    * by invoking a method
868    */
869   //g_socket_service_stop (service);
870   //g_object_unref (service);
871   g_dbus_server_stop (server);
872   g_object_unref (server);
873   server = NULL;
874
875   error = NULL;
876   result = g_dbus_proxy_call_sync (proxy,
877                                    "HelloPeer",
878                                    g_variant_new ("(s)", "Hey Again Peer!"),
879                                    G_DBUS_CALL_FLAGS_NONE,
880                                    -1,
881                                    NULL,  /* GCancellable */
882                                    &error);
883   g_assert_no_error (error);
884   g_variant_get (result, "(&s)", &s);
885   g_assert_cmpstr (s, ==, "You greeted me with 'Hey Again Peer!'.");
886   g_variant_unref (result);
887   g_assert_cmpint (data.num_method_calls, ==, 5);
888
889 #if 0
890   /* TODO: THIS TEST DOESN'T WORK YET */
891
892   /* now disconnect from the server side - check that the client side gets the signal */
893   g_assert_cmpint (data.current_connections->len, ==, 1);
894   g_assert (G_DBUS_CONNECTION (data.current_connections->pdata[0]) != c);
895   g_dbus_connection_disconnect (G_DBUS_CONNECTION (data.current_connections->pdata[0]));
896   if (!g_dbus_connection_get_is_disconnected (c))
897     _g_assert_signal_received (c, "closed");
898   g_assert (g_dbus_connection_get_is_disconnected (c));
899 #endif
900
901   g_object_unref (c);
902   g_ptr_array_unref (data.current_connections);
903   g_object_unref (proxy);
904
905   g_main_loop_quit (service_loop);
906   g_thread_join (service_thread);
907 }
908
909 /* ---------------------------------------------------------------------------------------------------- */
910
911 typedef struct
912 {
913   GDBusServer *server;
914   GMainContext *context;
915   GMainLoop *loop;
916
917   GList *connections;
918 } DmpData;
919
920 static void
921 dmp_data_free (DmpData *data)
922 {
923   g_main_loop_unref (data->loop);
924   g_main_context_unref (data->context);
925   g_object_unref (data->server);
926   g_list_foreach (data->connections, (GFunc) g_object_unref, NULL);
927   g_list_free (data->connections);
928   g_free (data);
929 }
930
931 static void
932 dmp_on_method_call (GDBusConnection       *connection,
933                     const gchar           *sender,
934                     const gchar           *object_path,
935                     const gchar           *interface_name,
936                     const gchar           *method_name,
937                     GVariant              *parameters,
938                     GDBusMethodInvocation *invocation,
939                     gpointer               user_data)
940 {
941   //DmpData *data = user_data;
942   gint32 first;
943   gint32 second;
944   g_variant_get (parameters,
945                  "(ii)",
946                  &first,
947                  &second);
948   g_dbus_method_invocation_return_value (invocation,
949                                          g_variant_new ("(i)", first + second));
950 }
951
952 static const GDBusInterfaceVTable dmp_interface_vtable =
953 {
954   dmp_on_method_call,
955   NULL,  /* get_property */
956   NULL   /* set_property */
957 };
958
959
960 /* Runs in thread we created GDBusServer in (since we didn't pass G_DBUS_SERVER_FLAGS_RUN_IN_THREAD) */
961 static gboolean
962 dmp_on_new_connection (GDBusServer     *server,
963                        GDBusConnection *connection,
964                        gpointer         user_data)
965 {
966   DmpData *data = user_data;
967   GDBusNodeInfo *node;
968   GError *error;
969
970   /* accept the connection */
971   data->connections = g_list_prepend (data->connections, g_object_ref (connection));
972
973   error = NULL;
974   node = g_dbus_node_info_new_for_xml ("<node>"
975                                        "  <interface name='org.gtk.GDBus.DmpInterface'>"
976                                        "    <method name='AddPair'>"
977                                        "      <arg type='i' name='first' direction='in'/>"
978                                        "      <arg type='i' name='second' direction='in'/>"
979                                        "      <arg type='i' name='sum' direction='out'/>"
980                                        "    </method>"
981                                        "  </interface>"
982                                        "</node>",
983                                        &error);
984   g_assert_no_error (error);
985
986   /* sleep 100ms before exporting an object - this is to test that
987    * G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING really works
988    * (GDBusServer uses this feature).
989    */
990   usleep (100 * 1000);
991
992   /* export an object */
993   error = NULL;
994   g_dbus_connection_register_object (connection,
995                                      "/dmp/test",
996                                      node->interfaces[0],
997                                      &dmp_interface_vtable,
998                                      data,
999                                      NULL,
1000                                      &error);
1001   g_dbus_node_info_unref (node);
1002
1003   return TRUE;
1004 }
1005
1006 static gpointer
1007 dmp_thread_func (gpointer user_data)
1008 {
1009   DmpData *data = user_data;
1010   GError *error;
1011   gchar *guid;
1012
1013   data->context = g_main_context_new ();
1014   g_main_context_push_thread_default (data->context);
1015
1016   error = NULL;
1017   guid = g_dbus_generate_guid ();
1018   data->server = g_dbus_server_new_sync (tmp_address,
1019                                          G_DBUS_SERVER_FLAGS_NONE,
1020                                          guid,
1021                                          NULL, /* GDBusAuthObserver */
1022                                          NULL, /* GCancellable */
1023                                          &error);
1024   g_assert_no_error (error);
1025   g_signal_connect (data->server,
1026                     "new-connection",
1027                     G_CALLBACK (dmp_on_new_connection),
1028                     data);
1029
1030   g_dbus_server_start (data->server);
1031
1032   data->loop = g_main_loop_new (data->context, FALSE);
1033   g_main_loop_run (data->loop);
1034
1035   g_main_context_pop_thread_default (data->context);
1036
1037   g_free (guid);
1038   return NULL;
1039 }
1040
1041 static void
1042 delayed_message_processing (void)
1043 {
1044   GError *error;
1045   DmpData *data;
1046   GThread *service_thread;
1047   guint n;
1048
1049   data = g_new0 (DmpData, 1);
1050
1051   service_thread = g_thread_new ("dmp",
1052                                  dmp_thread_func,
1053                                  data);
1054   while (data->server == NULL || !g_dbus_server_is_active (data->server))
1055     g_thread_yield ();
1056
1057   for (n = 0; n < 5; n++)
1058     {
1059       GDBusConnection *c;
1060       GVariant *res;
1061       gint32 val;
1062
1063       error = NULL;
1064       c = g_dbus_connection_new_for_address_sync (g_dbus_server_get_client_address (data->server),
1065                                                   G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
1066                                                   NULL, /* GDBusAuthObserver */
1067                                                   NULL, /* GCancellable */
1068                                                   &error);
1069       g_assert_no_error (error);
1070
1071       error = NULL;
1072       res = g_dbus_connection_call_sync (c,
1073                                          NULL,    /* bus name */
1074                                          "/dmp/test",
1075                                          "org.gtk.GDBus.DmpInterface",
1076                                          "AddPair",
1077                                          g_variant_new ("(ii)", 2, n),
1078                                          G_VARIANT_TYPE ("(i)"),
1079                                          G_DBUS_CALL_FLAGS_NONE,
1080                                          -1, /* timeout_msec */
1081                                          NULL, /* GCancellable */
1082                                          &error);
1083       g_assert_no_error (error);
1084       g_variant_get (res, "(i)", &val);
1085       g_assert_cmpint (val, ==, 2 + n);
1086       g_variant_unref (res);
1087       g_object_unref (c);
1088   }
1089
1090   g_main_loop_quit (data->loop);
1091   g_thread_join (service_thread);
1092   dmp_data_free (data);
1093 }
1094
1095 /* ---------------------------------------------------------------------------------------------------- */
1096
1097 static gboolean
1098 nonce_tcp_on_authorize_authenticated_peer (GDBusAuthObserver *observer,
1099                                            GIOStream         *stream,
1100                                            GCredentials      *credentials,
1101                                            gpointer           user_data)
1102 {
1103   PeerData *data = user_data;
1104   gboolean authorized;
1105
1106   data->num_connection_attempts++;
1107
1108   authorized = TRUE;
1109   if (!data->accept_connection)
1110     {
1111       authorized = FALSE;
1112       g_main_loop_quit (loop);
1113     }
1114
1115   return authorized;
1116 }
1117
1118 /* Runs in thread we created GDBusServer in (since we didn't pass G_DBUS_SERVER_FLAGS_RUN_IN_THREAD) */
1119 static gboolean
1120 nonce_tcp_on_new_connection (GDBusServer *server,
1121                              GDBusConnection *connection,
1122                              gpointer user_data)
1123 {
1124   PeerData *data = user_data;
1125
1126   g_ptr_array_add (data->current_connections, g_object_ref (connection));
1127
1128   g_main_loop_quit (loop);
1129
1130   return TRUE;
1131 }
1132
1133 static gpointer
1134 nonce_tcp_service_thread_func (gpointer user_data)
1135 {
1136   PeerData *data = user_data;
1137   GMainContext *service_context;
1138   GDBusAuthObserver *observer;
1139   GError *error;
1140
1141   service_context = g_main_context_new ();
1142   g_main_context_push_thread_default (service_context);
1143
1144   error = NULL;
1145   observer = g_dbus_auth_observer_new ();
1146   server = g_dbus_server_new_sync ("nonce-tcp:",
1147                                    G_DBUS_SERVER_FLAGS_NONE,
1148                                    test_guid,
1149                                    observer,
1150                                    NULL, /* cancellable */
1151                                    &error);
1152   g_assert_no_error (error);
1153
1154   g_signal_connect (server,
1155                     "new-connection",
1156                     G_CALLBACK (nonce_tcp_on_new_connection),
1157                     data);
1158   g_signal_connect (observer,
1159                     "authorize-authenticated-peer",
1160                     G_CALLBACK (nonce_tcp_on_authorize_authenticated_peer),
1161                     data);
1162   g_object_unref (observer);
1163
1164   g_dbus_server_start (server);
1165
1166   service_loop = g_main_loop_new (service_context, FALSE);
1167   g_main_loop_run (service_loop);
1168
1169   g_main_context_pop_thread_default (service_context);
1170
1171   g_main_loop_unref (service_loop);
1172   g_main_context_unref (service_context);
1173
1174   /* test code specifically unrefs the server - see below */
1175   g_assert (server == NULL);
1176
1177   return NULL;
1178 }
1179
1180 static void
1181 test_nonce_tcp (void)
1182 {
1183   PeerData data;
1184   GError *error;
1185   GThread *service_thread;
1186   GDBusConnection *c;
1187   gchar *s;
1188   gchar *nonce_file;
1189   gboolean res;
1190   const gchar *address;
1191
1192   memset (&data, '\0', sizeof (PeerData));
1193   data.current_connections = g_ptr_array_new_with_free_func (g_object_unref);
1194
1195   error = NULL;
1196   server = NULL;
1197   service_loop = NULL;
1198   service_thread = g_thread_new ("nonce-tcp-service",
1199                                  nonce_tcp_service_thread_func,
1200                                  &data);
1201   while (service_loop == NULL)
1202     g_thread_yield ();
1203   g_assert (server != NULL);
1204
1205
1206   /* bring up a connection and accept it */
1207   data.accept_connection = TRUE;
1208   error = NULL;
1209   c = g_dbus_connection_new_for_address_sync (g_dbus_server_get_client_address (server),
1210                                               G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
1211                                               NULL, /* GDBusAuthObserver */
1212                                               NULL, /* cancellable */
1213                                               &error);
1214   g_assert_no_error (error);
1215   g_assert (c != NULL);
1216   while (data.current_connections->len < 1)
1217     g_thread_yield ();
1218   g_assert_cmpint (data.current_connections->len, ==, 1);
1219   g_assert_cmpint (data.num_connection_attempts, ==, 1);
1220   g_assert (g_dbus_connection_get_unique_name (c) == NULL);
1221   g_assert_cmpstr (g_dbus_connection_get_guid (c), ==, test_guid);
1222   g_object_unref (c);
1223
1224   /* now, try to subvert the nonce file (this assumes noncefile is the last key/value pair)
1225    */
1226
1227   address = g_dbus_server_get_client_address (server);
1228
1229   s = strstr (address, "noncefile=");
1230   g_assert (s != NULL);
1231   s += sizeof "noncefile=" - 1;
1232   nonce_file = g_strdup (s);
1233
1234   /* First try invalid data in the nonce file - this will actually
1235    * make the client send this and the server will reject it. The way
1236    * it works is that if the nonce doesn't match, the server will
1237    * simply close the connection. So, from the client point of view,
1238    * we can see a variety of errors.
1239    */
1240   error = NULL;
1241   res = g_file_set_contents (nonce_file,
1242                              "0123456789012345",
1243                              -1,
1244                              &error);
1245   g_assert_no_error (error);
1246   g_assert (res);
1247   c = g_dbus_connection_new_for_address_sync (address,
1248                                               G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
1249                                               NULL, /* GDBusAuthObserver */
1250                                               NULL, /* cancellable */
1251                                               &error);
1252   _g_assert_error_domain (error, G_IO_ERROR);
1253   g_error_free (error);
1254   g_assert (c == NULL);
1255
1256   /* Then try with a nonce-file of incorrect length - this will make
1257    * the client complain - we won't even try connecting to the server
1258    * for this
1259    */
1260   error = NULL;
1261   res = g_file_set_contents (nonce_file,
1262                              "0123456789012345_",
1263                              -1,
1264                              &error);
1265   g_assert_no_error (error);
1266   g_assert (res);
1267   c = g_dbus_connection_new_for_address_sync (address,
1268                                               G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
1269                                               NULL, /* GDBusAuthObserver */
1270                                               NULL, /* cancellable */
1271                                               &error);
1272   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT);
1273   g_error_free (error);
1274   g_assert (c == NULL);
1275
1276   /* Finally try with no nonce-file at all */
1277   g_assert_cmpint (g_unlink (nonce_file), ==, 0);
1278   error = NULL;
1279   c = g_dbus_connection_new_for_address_sync (address,
1280                                               G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
1281                                               NULL, /* GDBusAuthObserver */
1282                                               NULL, /* cancellable */
1283                                               &error);
1284   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_ARGUMENT);
1285   g_error_free (error);
1286   g_assert (c == NULL);
1287
1288   g_free (nonce_file);
1289
1290   g_dbus_server_stop (server);
1291   g_object_unref (server);
1292   server = NULL;
1293
1294   g_main_loop_quit (service_loop);
1295   g_thread_join (service_thread);
1296 }
1297
1298 static void
1299 test_credentials (void)
1300 {
1301   GCredentials *c1, *c2;
1302   GError *error;
1303   gchar *desc;
1304
1305   c1 = g_credentials_new ();
1306   c2 = g_credentials_new ();
1307
1308   error = NULL;
1309   if (g_credentials_set_unix_user (c2, getuid (), &error))
1310     g_assert_no_error (error);
1311
1312   g_clear_error (&error);
1313   g_assert (g_credentials_is_same_user (c1, c2, &error));
1314   g_assert_no_error (error);
1315
1316   desc = g_credentials_to_string (c1);
1317   g_assert (desc != NULL);
1318   g_free (desc);
1319
1320   g_object_unref (c1);
1321   g_object_unref (c2);
1322 }
1323
1324 /* ---------------------------------------------------------------------------------------------------- */
1325
1326 #ifdef G_OS_UNIX
1327
1328 /* Chosen to be big enough to overflow the socket buffer */
1329 #define OVERFLOW_NUM_SIGNALS 5000
1330 #define OVERFLOW_TIMEOUT_SEC 10
1331
1332 static GDBusMessage *
1333 overflow_filter_func (GDBusConnection *connection,
1334                       GDBusMessage    *message,
1335                       gboolean         incoming,
1336                       gpointer         user_data)
1337 {
1338   volatile gint *counter = user_data;
1339   *counter += 1;
1340   return message;
1341 }
1342
1343 static gboolean
1344 overflow_on_500ms_later_func (gpointer user_data)
1345 {
1346   g_main_loop_quit (loop);
1347   return FALSE; /* don't keep the idle */
1348 }
1349
1350 static void
1351 test_overflow (void)
1352 {
1353   gint sv[2];
1354   gint n;
1355   GSocket *socket;
1356   GSocketConnection *socket_connection;
1357   GDBusConnection *producer, *consumer;
1358   GError *error;
1359   GTimer *timer;
1360   volatile gint n_messages_received;
1361   volatile gint n_messages_sent;
1362
1363   g_assert_cmpint (socketpair (AF_UNIX, SOCK_STREAM, 0, sv), ==, 0);
1364
1365   error = NULL;
1366   socket = g_socket_new_from_fd (sv[0], &error);
1367   g_assert_no_error (error);
1368   socket_connection = g_socket_connection_factory_create_connection (socket);
1369   g_assert (socket_connection != NULL);
1370   g_object_unref (socket);
1371   producer = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
1372                                          NULL, /* guid */
1373                                          G_DBUS_CONNECTION_FLAGS_NONE,
1374                                          NULL, /* GDBusAuthObserver */
1375                                          NULL, /* GCancellable */
1376                                          &error);
1377   g_dbus_connection_set_exit_on_close (producer, TRUE);
1378   g_assert_no_error (error);
1379   g_object_unref (socket_connection);
1380   n_messages_sent = 0;
1381   g_dbus_connection_add_filter (producer, overflow_filter_func, (gpointer) &n_messages_sent, NULL);
1382
1383   /* send enough data that we get an EAGAIN */
1384   for (n = 0; n < OVERFLOW_NUM_SIGNALS; n++)
1385     {
1386       error = NULL;
1387       g_dbus_connection_emit_signal (producer,
1388                                      NULL, /* destination */
1389                                      "/org/foo/Object",
1390                                      "org.foo.Interface",
1391                                      "Member",
1392                                      g_variant_new ("(s)", "a string"),
1393                                      &error);
1394       g_assert_no_error (error);
1395     }
1396
1397   /* sleep for 0.5 sec (to allow the GDBus IO thread to fill up the
1398    * kernel buffers) and verify that n_messages_sent <
1399    * OVERFLOW_NUM_SIGNALS
1400    *
1401    * This is to verify that not all the submitted messages have been
1402    * sent to the underlying transport.
1403    */
1404   g_timeout_add (500, overflow_on_500ms_later_func, NULL);
1405   g_main_loop_run (loop);
1406   g_assert_cmpint (n_messages_sent, <, OVERFLOW_NUM_SIGNALS);
1407
1408   /* now suck it all out as a client, and add it up */
1409   socket = g_socket_new_from_fd (sv[1], &error);
1410   g_assert_no_error (error);
1411   socket_connection = g_socket_connection_factory_create_connection (socket);
1412   g_assert (socket_connection != NULL);
1413   g_object_unref (socket);
1414   consumer = g_dbus_connection_new_sync (G_IO_STREAM (socket_connection),
1415                                          NULL, /* guid */
1416                                          G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING,
1417                                          NULL, /* GDBusAuthObserver */
1418                                          NULL, /* GCancellable */
1419                                          &error);
1420   g_assert_no_error (error);
1421   g_object_unref (socket_connection);
1422   n_messages_received = 0;
1423   g_dbus_connection_add_filter (consumer, overflow_filter_func, (gpointer) &n_messages_received, NULL);
1424   g_dbus_connection_start_message_processing (consumer);
1425
1426   timer = g_timer_new ();
1427   g_timer_start (timer);
1428
1429   while (n_messages_received < OVERFLOW_NUM_SIGNALS && g_timer_elapsed (timer, NULL) < OVERFLOW_TIMEOUT_SEC)
1430       g_main_context_iteration (NULL, FALSE);
1431
1432   g_assert_cmpint (n_messages_sent, ==, OVERFLOW_NUM_SIGNALS);
1433   g_assert_cmpint (n_messages_received, ==, OVERFLOW_NUM_SIGNALS);
1434
1435   g_timer_destroy (timer);
1436   g_object_unref (consumer);
1437   g_object_unref (producer);
1438 }
1439 #else
1440 static void
1441 test_overflow (void)
1442 {
1443   /* TODO: test this with e.g. GWin32InputStream/GWin32OutputStream */
1444 }
1445 #endif
1446
1447 /* ---------------------------------------------------------------------------------------------------- */
1448
1449 static gboolean
1450 tcp_anonymous_on_new_connection (GDBusServer     *server,
1451                                  GDBusConnection *connection,
1452                                  gpointer         user_data)
1453 {
1454   gboolean *seen_connection = user_data;
1455   *seen_connection = TRUE;
1456   return TRUE;
1457 }
1458
1459 static gpointer
1460 tcp_anonymous_service_thread_func (gpointer user_data)
1461 {
1462   gboolean *seen_connection = user_data;
1463   GMainContext *service_context;
1464   GError *error;
1465
1466   service_context = g_main_context_new ();
1467   g_main_context_push_thread_default (service_context);
1468
1469   error = NULL;
1470   server = g_dbus_server_new_sync ("tcp:",
1471                                    G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS,
1472                                    test_guid,
1473                                    NULL, /* GDBusObserver* */
1474                                    NULL, /* GCancellable* */
1475                                    &error);
1476   g_assert_no_error (error);
1477
1478   g_signal_connect (server,
1479                     "new-connection",
1480                     G_CALLBACK (tcp_anonymous_on_new_connection),
1481                     seen_connection);
1482
1483   g_dbus_server_start (server);
1484
1485   service_loop = g_main_loop_new (service_context, FALSE);
1486   g_main_loop_run (service_loop);
1487
1488   g_main_context_pop_thread_default (service_context);
1489
1490   g_main_loop_unref (service_loop);
1491   g_main_context_unref (service_context);
1492
1493   return NULL;
1494 }
1495
1496 static void
1497 test_tcp_anonymous (void)
1498 {
1499   gboolean seen_connection;
1500   GThread *service_thread;
1501   GDBusConnection *connection;
1502   GError *error;
1503
1504   seen_connection = FALSE;
1505   service_loop = NULL;
1506   service_thread = g_thread_new ("tcp-anon-service",
1507                                  tcp_anonymous_service_thread_func,
1508                                  &seen_connection);
1509   while (service_loop == NULL)
1510     g_thread_yield ();
1511   g_assert (server != NULL);
1512
1513   error = NULL;
1514   connection = g_dbus_connection_new_for_address_sync (g_dbus_server_get_client_address (server),
1515                                                        G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
1516                                                        NULL, /* GDBusAuthObserver* */
1517                                                        NULL, /* GCancellable */
1518                                                        &error);
1519   g_assert_no_error (error);
1520   g_assert (connection != NULL);
1521
1522   while (!seen_connection)
1523     g_thread_yield ();
1524
1525   g_object_unref (connection);
1526
1527   g_main_loop_quit (service_loop);
1528   g_dbus_server_stop (server);
1529   g_object_unref (server);
1530   server = NULL;
1531
1532   g_thread_join (service_thread);
1533 }
1534
1535 /* ---------------------------------------------------------------------------------------------------- */
1536
1537 int
1538 main (int   argc,
1539       char *argv[])
1540 {
1541   gint ret;
1542   GDBusNodeInfo *introspection_data = NULL;
1543   gchar *tmpdir = NULL;
1544
1545   g_type_init ();
1546   g_test_init (&argc, &argv, NULL);
1547
1548   g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");
1549
1550   introspection_data = g_dbus_node_info_new_for_xml (test_interface_introspection_xml, NULL);
1551   g_assert (introspection_data != NULL);
1552   test_interface_introspection_data = introspection_data->interfaces[0];
1553
1554   test_guid = g_dbus_generate_guid ();
1555
1556   if (is_unix)
1557     {
1558       if (g_unix_socket_address_abstract_names_supported ())
1559         tmp_address = g_strdup ("unix:tmpdir=/tmp/gdbus-test-");
1560       else
1561         {
1562           tmpdir = g_dir_make_tmp ("gdbus-test-XXXXXX", NULL);
1563           tmp_address = g_strdup_printf ("unix:tmpdir=%s", tmpdir);
1564         }
1565     }
1566   else
1567     tmp_address = g_strdup ("nonce-tcp:");
1568
1569   /* all the tests rely on a shared main loop */
1570   loop = g_main_loop_new (NULL, FALSE);
1571
1572   g_test_add_func ("/gdbus/peer-to-peer", test_peer);
1573   g_test_add_func ("/gdbus/delayed-message-processing", delayed_message_processing);
1574   g_test_add_func ("/gdbus/nonce-tcp", test_nonce_tcp);
1575   g_test_add_func ("/gdbus/tcp-anonymous", test_tcp_anonymous);
1576   g_test_add_func ("/gdbus/credentials", test_credentials);
1577   g_test_add_func ("/gdbus/overflow", test_overflow);
1578
1579   ret = g_test_run();
1580
1581   g_main_loop_unref (loop);
1582   g_free (test_guid);
1583   g_dbus_node_info_unref (introspection_data);
1584   if (is_unix)
1585     g_free (tmp_address);
1586   if (tmpdir)
1587     {
1588       g_rmdir (tmpdir);
1589       g_free (tmpdir);
1590     }
1591
1592   return ret;
1593 }