Fix race in gdbus-connection test
[platform/upstream/glib.git] / gio / tests / gdbus-connection.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 <gio/gio.h>
24 #include <unistd.h>
25 #include <string.h>
26
27 #include <sys/types.h>
28 #include <sys/wait.h>
29
30 #include "gdbus-tests.h"
31
32 /* all tests rely on a shared mainloop */
33 static GMainLoop *loop = NULL;
34
35 #if 0
36 G_GNUC_UNUSED static void
37 _log (const gchar *format, ...)
38 {
39   GTimeVal now;
40   time_t now_time;
41   struct tm *now_tm;
42   gchar time_buf[128];
43   gchar *str;
44   va_list var_args;
45
46   va_start (var_args, format);
47   str = g_strdup_vprintf (format, var_args);
48   va_end (var_args);
49
50   g_get_current_time (&now);
51   now_time = (time_t) now.tv_sec;
52   now_tm = localtime (&now_time);
53   strftime (time_buf, sizeof time_buf, "%H:%M:%S", now_tm);
54
55   g_print ("%s.%06d: %s\n",
56            time_buf, (gint) now.tv_usec / 1000,
57            str);
58   g_free (str);
59 }
60 #else
61 #define _log(...)
62 #endif
63
64 static gboolean
65 test_connection_quit_mainloop (gpointer user_data)
66 {
67   volatile gboolean *quit_mainloop_fired = user_data;
68   _log ("quit_mainloop_fired");
69   *quit_mainloop_fired = TRUE;
70   g_main_loop_quit (loop);
71   return TRUE;
72 }
73
74 /* ---------------------------------------------------------------------------------------------------- */
75 /* Connection life-cycle testing */
76 /* ---------------------------------------------------------------------------------------------------- */
77
78 static const GDBusInterfaceInfo boo_interface_info =
79 {
80   -1,
81   "org.example.Boo",
82   (GDBusMethodInfo **) NULL,
83   (GDBusSignalInfo **) NULL,
84   (GDBusPropertyInfo **) NULL,
85   NULL,
86 };
87
88 static const GDBusInterfaceVTable boo_vtable =
89 {
90   NULL, /* _method_call */
91   NULL, /* _get_property */
92   NULL  /* _set_property */
93 };
94
95 static GDBusMessage *
96 some_filter_func (GDBusConnection *connection,
97                   GDBusMessage    *message,
98                   gboolean         incoming,
99                   gpointer         user_data)
100 {
101   return message;
102 }
103
104 static void
105 on_name_owner_changed (GDBusConnection *connection,
106                        const gchar     *sender_name,
107                        const gchar     *object_path,
108                        const gchar     *interface_name,
109                        const gchar     *signal_name,
110                        GVariant        *parameters,
111                        gpointer         user_data)
112 {
113 }
114
115 static void
116 a_gdestroynotify_that_sets_a_gboolean_to_true_and_quits_loop (gpointer user_data)
117 {
118   volatile gboolean *val = user_data;
119   *val = TRUE;
120   _log ("destroynotify fired for %p", val);
121   g_main_loop_quit (loop);
122 }
123
124 static void
125 test_connection_life_cycle (void)
126 {
127   gboolean ret;
128   GDBusConnection *c;
129   GDBusConnection *c2;
130   GError *error;
131   volatile gboolean on_signal_registration_freed_called;
132   volatile gboolean on_filter_freed_called;
133   volatile gboolean on_register_object_freed_called;
134   volatile gboolean quit_mainloop_fired;
135   guint quit_mainloop_id;
136   guint registration_id;
137
138   error = NULL;
139
140   /*
141    * Check for correct behavior when no bus is present
142    *
143    */
144   c = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);
145   _g_assert_error_domain (error, G_IO_ERROR);
146   g_assert (!g_dbus_error_is_remote_error (error));
147   g_assert (c == NULL);
148   g_error_free (error);
149
150   /*
151    *  Check for correct behavior when a bus is present
152    */
153   session_bus_up ();
154   /* case 1 */
155   error = NULL;
156   c = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);
157   g_assert_no_error (error);
158   g_assert (c != NULL);
159   g_assert (!g_dbus_connection_is_closed (c));
160
161   /*
162    * Check that singleton handling work
163    */
164   error = NULL;
165   c2 = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);
166   g_assert_no_error (error);
167   g_assert (c2 != NULL);
168   g_assert (c == c2);
169   g_object_unref (c2);
170
171   /*
172    * Check that private connections work
173    */
174   c2 = _g_bus_get_priv (G_BUS_TYPE_SESSION, NULL, &error);
175   g_assert_no_error (error);
176   g_assert (c2 != NULL);
177   g_assert (c != c2);
178   g_object_unref (c2);
179
180   c2 = _g_bus_get_priv (G_BUS_TYPE_SESSION, NULL, &error);
181   g_assert_no_error (error);
182   g_assert (c2 != NULL);
183   g_assert (!g_dbus_connection_is_closed (c2));
184   ret = g_dbus_connection_close_sync (c2, NULL, &error);
185   g_assert_no_error (error);
186   g_assert (ret);
187   _g_assert_signal_received (c2, "closed");
188   g_assert (g_dbus_connection_is_closed (c2));
189   ret = g_dbus_connection_close_sync (c2, NULL, &error);
190   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_CLOSED);
191   g_error_free (error);
192   g_assert (!ret);
193   g_object_unref (c2);
194
195   /*
196    * Check that the finalization code works
197    *
198    * (and that the GDestroyNotify for filters and objects and signal
199    * registrations are run as expected)
200    */
201   error = NULL;
202   c2 = _g_bus_get_priv (G_BUS_TYPE_SESSION, NULL, &error);
203   g_assert_no_error (error);
204   g_assert (c2 != NULL);
205   /* signal registration */
206   on_signal_registration_freed_called = FALSE;
207   g_dbus_connection_signal_subscribe (c2,
208                                       "org.freedesktop.DBus", /* bus name */
209                                       "org.freedesktop.DBus", /* interface */
210                                       "NameOwnerChanged",     /* member */
211                                       "/org/freesktop/DBus",  /* path */
212                                       NULL,                   /* arg0 */
213                                       G_DBUS_SIGNAL_FLAGS_NONE,
214                                       on_name_owner_changed,
215                                       (gpointer) &on_signal_registration_freed_called,
216                                       a_gdestroynotify_that_sets_a_gboolean_to_true_and_quits_loop);
217   /* filter func */
218   on_filter_freed_called = FALSE;
219   g_dbus_connection_add_filter (c2,
220                                 some_filter_func,
221                                 (gpointer) &on_filter_freed_called,
222                                 a_gdestroynotify_that_sets_a_gboolean_to_true_and_quits_loop);
223   /* object registration */
224   on_register_object_freed_called = FALSE;
225   error = NULL;
226   registration_id = g_dbus_connection_register_object (c2,
227                                                        "/foo",
228                                                        (GDBusInterfaceInfo *) &boo_interface_info,
229                                                        &boo_vtable,
230                                                        (gpointer) &on_register_object_freed_called,
231                                                        a_gdestroynotify_that_sets_a_gboolean_to_true_and_quits_loop,
232                                                        &error);
233   g_assert_no_error (error);
234   g_assert (registration_id > 0);
235   /* ok, finalize the connection and check that all the GDestroyNotify functions are invoked as expected */
236   g_object_unref (c2);
237   quit_mainloop_fired = FALSE;
238   quit_mainloop_id = g_timeout_add (30000, test_connection_quit_mainloop, (gpointer) &quit_mainloop_fired);
239   _log ("destroynotifies for\n"
240         " register_object %p\n"
241         " filter          %p\n"
242         " signal          %p",
243         &on_register_object_freed_called,
244         &on_filter_freed_called,
245         &on_signal_registration_freed_called);
246   while (TRUE)
247     {
248       if (on_signal_registration_freed_called &&
249           on_filter_freed_called &&
250           on_register_object_freed_called)
251         break;
252       if (quit_mainloop_fired)
253         break;
254       _log ("entering loop");
255       g_main_loop_run (loop);
256       _log ("exiting loop");
257     }
258   g_source_remove (quit_mainloop_id);
259   g_assert (on_signal_registration_freed_called);
260   g_assert (on_filter_freed_called);
261   g_assert (on_register_object_freed_called);
262   g_assert (!quit_mainloop_fired);
263
264   /*
265    *  Check for correct behavior when the bus goes away
266    *
267    */
268   g_assert (!g_dbus_connection_is_closed (c));
269   g_dbus_connection_set_exit_on_close (c, FALSE);
270   session_bus_stop ();
271   _g_assert_signal_received (c, "closed");
272   g_assert (g_dbus_connection_is_closed (c));
273   g_object_unref (c);
274
275   session_bus_down ();
276 }
277
278 /* ---------------------------------------------------------------------------------------------------- */
279 /* Test that sending and receiving messages work as expected */
280 /* ---------------------------------------------------------------------------------------------------- */
281
282 static void
283 msg_cb_expect_error_disconnected (GDBusConnection *connection,
284                                   GAsyncResult    *res,
285                                   gpointer         user_data)
286 {
287   GError *error;
288   GVariant *result;
289
290   error = NULL;
291   result = g_dbus_connection_call_finish (connection,
292                                           res,
293                                           &error);
294   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_CLOSED);
295   g_assert (!g_dbus_error_is_remote_error (error));
296   g_error_free (error);
297   g_assert (result == NULL);
298
299   g_main_loop_quit (loop);
300 }
301
302 static void
303 msg_cb_expect_error_unknown_method (GDBusConnection *connection,
304                                     GAsyncResult    *res,
305                                     gpointer         user_data)
306 {
307   GError *error;
308   GVariant *result;
309
310   error = NULL;
311   result = g_dbus_connection_call_finish (connection,
312                                           res,
313                                           &error);
314   g_assert_error (error, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD);
315   g_assert (g_dbus_error_is_remote_error (error));
316   g_error_free (error);
317   g_assert (result == NULL);
318
319   g_main_loop_quit (loop);
320 }
321
322 static void
323 msg_cb_expect_success (GDBusConnection *connection,
324                        GAsyncResult    *res,
325                        gpointer         user_data)
326 {
327   GError *error;
328   GVariant *result;
329
330   error = NULL;
331   result = g_dbus_connection_call_finish (connection,
332                                           res,
333                                           &error);
334   g_assert_no_error (error);
335   g_assert (result != NULL);
336   g_variant_unref (result);
337
338   g_main_loop_quit (loop);
339 }
340
341 static void
342 msg_cb_expect_error_cancelled (GDBusConnection *connection,
343                                GAsyncResult    *res,
344                                gpointer         user_data)
345 {
346   GError *error;
347   GVariant *result;
348
349   error = NULL;
350   result = g_dbus_connection_call_finish (connection,
351                                           res,
352                                           &error);
353   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_CANCELLED);
354   g_assert (!g_dbus_error_is_remote_error (error));
355   g_error_free (error);
356   g_assert (result == NULL);
357
358   g_main_loop_quit (loop);
359 }
360
361 static void
362 msg_cb_expect_error_cancelled_2 (GDBusConnection *connection,
363                                  GAsyncResult    *res,
364                                  gpointer         user_data)
365 {
366   GError *error;
367   GVariant *result;
368
369   error = NULL;
370   result = g_dbus_connection_call_finish (connection,
371                                           res,
372                                           &error);
373   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_CANCELLED);
374   g_assert (!g_dbus_error_is_remote_error (error));
375   g_error_free (error);
376   g_assert (result == NULL);
377
378   g_main_loop_quit (loop);
379 }
380
381 /* ---------------------------------------------------------------------------------------------------- */
382
383 static void
384 test_connection_send (void)
385 {
386   GDBusConnection *c;
387   GCancellable *ca;
388
389   session_bus_up ();
390
391   /* First, get an unopened connection */
392   c = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
393   g_assert (c != NULL);
394   g_assert (!g_dbus_connection_is_closed (c));
395
396   /*
397    * Check that we never actually send a message if the GCancellable
398    * is already cancelled - i.e.  we should get #G_IO_ERROR_CANCELLED
399    * when the actual connection is not up.
400    */
401   ca = g_cancellable_new ();
402   g_cancellable_cancel (ca);
403   g_dbus_connection_call (c,
404                           "org.freedesktop.DBus",  /* bus_name */
405                           "/org/freedesktop/DBus", /* object path */
406                           "org.freedesktop.DBus",  /* interface name */
407                           "GetId",                 /* method name */
408                           NULL, NULL,
409                           G_DBUS_CALL_FLAGS_NONE,
410                           -1,
411                           ca,
412                           (GAsyncReadyCallback) msg_cb_expect_error_cancelled,
413                           NULL);
414   g_main_loop_run (loop);
415   g_object_unref (ca);
416
417   /*
418    * Check that we get a reply to the GetId() method call.
419    */
420   g_dbus_connection_call (c,
421                           "org.freedesktop.DBus",  /* bus_name */
422                           "/org/freedesktop/DBus", /* object path */
423                           "org.freedesktop.DBus",  /* interface name */
424                           "GetId",                 /* method name */
425                           NULL, NULL,
426                           G_DBUS_CALL_FLAGS_NONE,
427                           -1,
428                           NULL,
429                           (GAsyncReadyCallback) msg_cb_expect_success,
430                           NULL);
431   g_main_loop_run (loop);
432
433   /*
434    * Check that we get an error reply to the NonExistantMethod() method call.
435    */
436   g_dbus_connection_call (c,
437                           "org.freedesktop.DBus",  /* bus_name */
438                           "/org/freedesktop/DBus", /* object path */
439                           "org.freedesktop.DBus",  /* interface name */
440                           "NonExistantMethod",     /* method name */
441                           NULL, NULL,
442                           G_DBUS_CALL_FLAGS_NONE,
443                           -1,
444                           NULL,
445                           (GAsyncReadyCallback) msg_cb_expect_error_unknown_method,
446                           NULL);
447   g_main_loop_run (loop);
448
449   /*
450    * Check that cancellation works when the message is already in flight.
451    */
452   ca = g_cancellable_new ();
453   g_dbus_connection_call (c,
454                           "org.freedesktop.DBus",  /* bus_name */
455                           "/org/freedesktop/DBus", /* object path */
456                           "org.freedesktop.DBus",  /* interface name */
457                           "GetId",                 /* method name */
458                           NULL, NULL,
459                           G_DBUS_CALL_FLAGS_NONE,
460                           -1,
461                           ca,
462                           (GAsyncReadyCallback) msg_cb_expect_error_cancelled_2,
463                           NULL);
464   g_cancellable_cancel (ca);
465   g_main_loop_run (loop);
466   g_object_unref (ca);
467
468   /*
469    * Check that we get an error when sending to a connection that is disconnected.
470    */
471   g_dbus_connection_set_exit_on_close (c, FALSE);
472   session_bus_stop ();
473   _g_assert_signal_received (c, "closed");
474   g_assert (g_dbus_connection_is_closed (c));
475
476   g_dbus_connection_call (c,
477                           "org.freedesktop.DBus",  /* bus_name */
478                           "/org/freedesktop/DBus", /* object path */
479                           "org.freedesktop.DBus",  /* interface name */
480                           "GetId",                 /* method name */
481                           NULL, NULL,
482                           G_DBUS_CALL_FLAGS_NONE,
483                           -1,
484                           NULL,
485                           (GAsyncReadyCallback) msg_cb_expect_error_disconnected,
486                           NULL);
487   g_main_loop_run (loop);
488
489   g_object_unref (c);
490
491   session_bus_down ();
492 }
493
494 /* ---------------------------------------------------------------------------------------------------- */
495 /* Connection signal tests */
496 /* ---------------------------------------------------------------------------------------------------- */
497
498 static void
499 test_connection_signal_handler (GDBusConnection  *connection,
500                                 const gchar      *sender_name,
501                                 const gchar      *object_path,
502                                 const gchar      *interface_name,
503                                 const gchar      *signal_name,
504                                 GVariant         *parameters,
505                                 gpointer         user_data)
506 {
507   gint *counter = user_data;
508   *counter += 1;
509
510   /*g_debug ("in test_connection_signal_handler (sender=%s path=%s interface=%s member=%s)",
511            sender_name,
512            object_path,
513            interface_name,
514            signal_name);*/
515
516   g_main_loop_quit (loop);
517 }
518
519 static void
520 test_connection_signals (void)
521 {
522   GDBusConnection *c1;
523   GDBusConnection *c2;
524   GDBusConnection *c3;
525   guint s1;
526   guint s1b;
527   guint s2;
528   guint s3;
529   gint count_s1;
530   gint count_s1b;
531   gint count_s2;
532   gint count_name_owner_changed;
533   GError *error;
534   gboolean ret;
535   GVariant *result;
536   gboolean quit_mainloop_fired;
537   guint quit_mainloop_id;
538
539   error = NULL;
540
541   /*
542    * Bring up first separate connections
543    */
544   session_bus_up ();
545   /* if running with dbus-monitor, it claims the name :1.0 - so if we don't run with the monitor
546    * emulate this
547    */
548   if (g_getenv ("G_DBUS_MONITOR") == NULL)
549     {
550       c1 = _g_bus_get_priv (G_BUS_TYPE_SESSION, NULL, NULL);
551       g_assert (c1 != NULL);
552       g_assert (!g_dbus_connection_is_closed (c1));
553       g_object_unref (c1);
554     }
555   c1 = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
556   g_assert (c1 != NULL);
557   g_assert (!g_dbus_connection_is_closed (c1));
558   g_assert_cmpstr (g_dbus_connection_get_unique_name (c1), ==, ":1.1");
559
560   /*
561    * Install two signal handlers for the first connection
562    *
563    *  - Listen to the signal "Foo" from :1.2 (e.g. c2)
564    *  - Listen to the signal "Foo" from anyone (e.g. both c2 and c3)
565    *
566    * and then count how many times this signal handler was invoked.
567    */
568   s1 = g_dbus_connection_signal_subscribe (c1,
569                                            ":1.2",
570                                            "org.gtk.GDBus.ExampleInterface",
571                                            "Foo",
572                                            "/org/gtk/GDBus/ExampleInterface",
573                                            NULL,
574                                            G_DBUS_SIGNAL_FLAGS_NONE,
575                                            test_connection_signal_handler,
576                                            &count_s1,
577                                            NULL);
578   s2 = g_dbus_connection_signal_subscribe (c1,
579                                            NULL, /* match any sender */
580                                            "org.gtk.GDBus.ExampleInterface",
581                                            "Foo",
582                                            "/org/gtk/GDBus/ExampleInterface",
583                                            NULL,
584                                            G_DBUS_SIGNAL_FLAGS_NONE,
585                                            test_connection_signal_handler,
586                                            &count_s2,
587                                            NULL);
588   s3 = g_dbus_connection_signal_subscribe (c1,
589                                            "org.freedesktop.DBus",  /* sender */
590                                            "org.freedesktop.DBus",  /* interface */
591                                            "NameOwnerChanged",      /* member */
592                                            "/org/freedesktop/DBus", /* path */
593                                            NULL,
594                                            G_DBUS_SIGNAL_FLAGS_NONE,
595                                            test_connection_signal_handler,
596                                            &count_name_owner_changed,
597                                            NULL);
598   /* Note that s1b is *just like* s1 - this is to catch a bug where N
599    * subscriptions of the same rule causes N calls to each of the N
600    * subscriptions instead of just 1 call to each of the N subscriptions.
601    */
602   s1b = g_dbus_connection_signal_subscribe (c1,
603                                             ":1.2",
604                                             "org.gtk.GDBus.ExampleInterface",
605                                             "Foo",
606                                             "/org/gtk/GDBus/ExampleInterface",
607                                             NULL,
608                                             G_DBUS_SIGNAL_FLAGS_NONE,
609                                             test_connection_signal_handler,
610                                             &count_s1b,
611                                             NULL);
612   g_assert (s1 != 0);
613   g_assert (s1b != 0);
614   g_assert (s2 != 0);
615   g_assert (s3 != 0);
616
617   count_s1 = 0;
618   count_s1b = 0;
619   count_s2 = 0;
620   count_name_owner_changed = 0;
621
622   /*
623    * Make c2 emit "Foo" - we should catch it twice
624    *
625    * Note that there is no way to be sure that the signal subscriptions
626    * on c1 are effective yet - for all we know, the AddMatch() messages
627    * could sit waiting in a buffer somewhere between this process and
628    * the message bus. And emitting signals on c2 (a completely other
629    * socket!) will not necessarily change this.
630    *
631    * To ensure this is not the case, do a synchronous call on c1.
632    */
633   result = g_dbus_connection_call_sync (c1,
634                                         "org.freedesktop.DBus",  /* bus name */
635                                         "/org/freedesktop/DBus", /* object path */
636                                         "org.freedesktop.DBus",  /* interface name */
637                                         "GetId",                 /* method name */
638                                         NULL,                    /* parameters */
639                                         NULL,                    /* return type */
640                                         G_DBUS_CALL_FLAGS_NONE,
641                                         -1,
642                                         NULL,
643                                         &error);
644   g_assert_no_error (error);
645   g_assert (result != NULL);
646   g_variant_unref (result);
647
648   /*
649    * Bring up two other connections
650    */
651   c2 = _g_bus_get_priv (G_BUS_TYPE_SESSION, NULL, NULL);
652   g_assert (c2 != NULL);
653   g_assert (!g_dbus_connection_is_closed (c2));
654   g_assert_cmpstr (g_dbus_connection_get_unique_name (c2), ==, ":1.2");
655   c3 = _g_bus_get_priv (G_BUS_TYPE_SESSION, NULL, NULL);
656   g_assert (c3 != NULL);
657   g_assert (!g_dbus_connection_is_closed (c3));
658   g_assert_cmpstr (g_dbus_connection_get_unique_name (c3), ==, ":1.3");
659
660   /* now, emit the signal on c2 */
661   ret = g_dbus_connection_emit_signal (c2,
662                                        NULL, /* destination bus name */
663                                        "/org/gtk/GDBus/ExampleInterface",
664                                        "org.gtk.GDBus.ExampleInterface",
665                                        "Foo",
666                                        NULL,
667                                        &error);
668   g_assert_no_error (error);
669   g_assert (ret);
670   while (!(count_s1 >= 1 && count_s2 >= 1))
671     g_main_loop_run (loop);
672   g_assert_cmpint (count_s1, ==, 1);
673   g_assert_cmpint (count_s2, ==, 1);
674
675   /*
676    * Make c3 emit "Foo" - we should catch it only once
677    */
678   ret = g_dbus_connection_emit_signal (c3,
679                                        NULL, /* destination bus name */
680                                        "/org/gtk/GDBus/ExampleInterface",
681                                        "org.gtk.GDBus.ExampleInterface",
682                                        "Foo",
683                                        NULL,
684                                        &error);
685   g_assert_no_error (error);
686   g_assert (ret);
687   while (!(count_s1 == 1 && count_s2 == 2))
688     g_main_loop_run (loop);
689   g_assert_cmpint (count_s1, ==, 1);
690   g_assert_cmpint (count_s2, ==, 2);
691
692   /*
693    * Also to check the total amount of NameOwnerChanged signals - use a 5 second ceiling
694    * to avoid spinning forever
695    */
696   quit_mainloop_fired = FALSE;
697   quit_mainloop_id = g_timeout_add (30000, test_connection_quit_mainloop, &quit_mainloop_fired);
698   while (count_name_owner_changed < 2 && !quit_mainloop_fired)
699     g_main_loop_run (loop);
700   g_source_remove (quit_mainloop_id);
701   g_assert_cmpint (count_s1, ==, 1);
702   g_assert_cmpint (count_s2, ==, 2);
703   g_assert_cmpint (count_name_owner_changed, ==, 2);
704
705   g_dbus_connection_signal_unsubscribe (c1, s1);
706   g_dbus_connection_signal_unsubscribe (c1, s2);
707   g_dbus_connection_signal_unsubscribe (c1, s3);
708   g_dbus_connection_signal_unsubscribe (c1, s1b);
709
710   g_object_unref (c1);
711   g_object_unref (c2);
712   g_object_unref (c3);
713
714   session_bus_down ();
715 }
716
717 /* ---------------------------------------------------------------------------------------------------- */
718
719 typedef struct
720 {
721   guint num_handled;
722   guint num_outgoing;
723   guint32 serial;
724 } FilterData;
725
726 static GDBusMessage *
727 filter_func (GDBusConnection *connection,
728              GDBusMessage    *message,
729              gboolean         incoming,
730              gpointer         user_data)
731 {
732   FilterData *data = user_data;
733   guint32 reply_serial;
734
735   if (incoming)
736     {
737       reply_serial = g_dbus_message_get_reply_serial (message);
738       if (reply_serial == data->serial)
739         data->num_handled += 1;
740     }
741   else
742     {
743       data->num_outgoing += 1;
744     }
745
746   return message;
747 }
748
749
750 typedef struct
751 {
752   gboolean alter_incoming;
753   gboolean alter_outgoing;
754 } FilterEffects;
755
756 static GDBusMessage *
757 other_filter_func (GDBusConnection *connection,
758                    GDBusMessage    *message,
759                    gboolean         incoming,
760                    gpointer         user_data)
761 {
762   FilterEffects *effects = user_data;
763   GDBusMessage *ret;
764   gboolean alter;
765
766   if (incoming)
767     alter = effects->alter_incoming;
768   else
769     alter = effects->alter_outgoing;
770
771   if (alter)
772     {
773       GDBusMessage *copy;
774       GVariant *body;
775       gchar *s;
776       gchar *s2;
777
778       copy = g_dbus_message_copy (message, NULL);
779       g_object_unref (message);
780
781       body = g_dbus_message_get_body (copy);
782       g_variant_get (body, "(s)", &s);
783       s2 = g_strdup_printf ("MOD: %s", s);
784       g_dbus_message_set_body (copy, g_variant_new ("(s)", s2));
785       g_free (s2);
786       g_free (s);
787
788       ret = copy;
789     }
790   else
791     {
792       ret = message;
793     }
794
795   return ret;
796 }
797
798 static void
799 test_connection_filter_name_owner_changed_signal_handler (GDBusConnection  *connection,
800                                                           const gchar      *sender_name,
801                                                           const gchar      *object_path,
802                                                           const gchar      *interface_name,
803                                                           const gchar      *signal_name,
804                                                           GVariant         *parameters,
805                                                           gpointer         user_data)
806 {
807   const gchar *name;
808   const gchar *old_owner;
809   const gchar *new_owner;
810
811   g_variant_get (parameters,
812                  "(&s&s&s)",
813                  &name,
814                  &old_owner,
815                  &new_owner);
816
817   if (g_strcmp0 (name, "com.example.TestService") == 0 && strlen (new_owner) > 0)
818     {
819       g_main_loop_quit (loop);
820     }
821 }
822
823 static gboolean
824 test_connection_filter_on_timeout (gpointer user_data)
825 {
826   g_printerr ("Timeout waiting 30 sec on service\n");
827   g_assert_not_reached ();
828   return FALSE;
829 }
830
831 static void
832 test_connection_filter (void)
833 {
834   GDBusConnection *c;
835   FilterData data;
836   GDBusMessage *m;
837   GDBusMessage *m2;
838   GDBusMessage *r;
839   GError *error;
840   guint filter_id;
841   guint timeout_mainloop_id;
842   guint signal_handler_id;
843   FilterEffects effects;
844   GVariant *result;
845   const gchar *s;
846
847   memset (&data, '\0', sizeof (FilterData));
848
849   session_bus_up ();
850
851   error = NULL;
852   c = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);
853   g_assert_no_error (error);
854   g_assert (c != NULL);
855
856   filter_id = g_dbus_connection_add_filter (c,
857                                             filter_func,
858                                             &data,
859                                             NULL);
860
861   m = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
862                                       "/org/freedesktop/DBus", /* path */
863                                       "org.freedesktop.DBus", /* interface */
864                                       "GetNameOwner");
865   g_dbus_message_set_body (m, g_variant_new ("(s)", "org.freedesktop.DBus"));
866   error = NULL;
867   g_dbus_connection_send_message (c, m, G_DBUS_SEND_MESSAGE_FLAGS_NONE, &data.serial, &error);
868   g_assert_no_error (error);
869
870   while (data.num_handled == 0)
871     g_thread_yield ();
872
873   m2 = g_dbus_message_copy (m, &error);
874   g_assert_no_error (error);
875   g_dbus_connection_send_message (c, m2, G_DBUS_SEND_MESSAGE_FLAGS_NONE, &data.serial, &error);
876   g_object_unref (m2);
877   g_assert_no_error (error);
878
879   while (data.num_handled == 1)
880     g_thread_yield ();
881
882   m2 = g_dbus_message_copy (m, &error);
883   g_assert_no_error (error);
884   g_dbus_message_set_serial (m2, data.serial);
885   /* lock the message to test PRESERVE_SERIAL flag. */
886   g_dbus_message_lock (m2);
887   g_dbus_connection_send_message (c, m2, G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL, &data.serial, &error);
888   g_object_unref (m2);
889   g_assert_no_error (error);
890
891   while (data.num_handled == 2)
892     g_thread_yield ();
893
894   m2 = g_dbus_message_copy (m, &error);
895   g_assert_no_error (error);
896   r = g_dbus_connection_send_message_with_reply_sync (c,
897                                                       m2,
898                                                       G_DBUS_SEND_MESSAGE_FLAGS_NONE,
899                                                       -1,
900                                                       &data.serial,
901                                                       NULL, /* GCancellable */
902                                                       &error);
903   g_object_unref (m2);
904   g_assert_no_error (error);
905   g_assert (r != NULL);
906   g_object_unref (r);
907   g_assert_cmpint (data.num_handled, ==, 4);
908
909   g_dbus_connection_remove_filter (c, filter_id);
910
911   m2 = g_dbus_message_copy (m, &error);
912   g_assert_no_error (error);
913   r = g_dbus_connection_send_message_with_reply_sync (c,
914                                                       m2,
915                                                       G_DBUS_SEND_MESSAGE_FLAGS_NONE,
916                                                       -1,
917                                                       &data.serial,
918                                                       NULL, /* GCancellable */
919                                                       &error);
920   g_object_unref (m2);
921   g_assert_no_error (error);
922   g_assert (r != NULL);
923   g_object_unref (r);
924   g_assert_cmpint (data.num_handled, ==, 4);
925   g_assert_cmpint (data.num_outgoing, ==, 4);
926
927   /* this is safe; testserver will exit once the bus goes away */
928   g_assert (g_spawn_command_line_async (SRCDIR "/gdbus-testserver.py", NULL));
929   /* wait for service to be available */
930   signal_handler_id = g_dbus_connection_signal_subscribe (c,
931                                                           "org.freedesktop.DBus", /* sender */
932                                                           "org.freedesktop.DBus",
933                                                           "NameOwnerChanged",
934                                                           "/org/freedesktop/DBus",
935                                                           NULL, /* arg0 */
936                                                           G_DBUS_SIGNAL_FLAGS_NONE,
937                                                           test_connection_filter_name_owner_changed_signal_handler,
938                                                           NULL,
939                                                           NULL);
940   g_assert_cmpint (signal_handler_id, !=, 0);
941   timeout_mainloop_id = g_timeout_add (30000, test_connection_filter_on_timeout, NULL);
942   g_main_loop_run (loop);
943   g_source_remove (timeout_mainloop_id);
944   g_dbus_connection_signal_unsubscribe (c, signal_handler_id);
945
946   /* now test some combinations... */
947   filter_id = g_dbus_connection_add_filter (c,
948                                             other_filter_func,
949                                             &effects,
950                                             NULL);
951   /* -- */
952   effects.alter_incoming = FALSE;
953   effects.alter_outgoing = FALSE;
954   error = NULL;
955   result = g_dbus_connection_call_sync (c,
956                                         "com.example.TestService",      /* bus name */
957                                         "/com/example/TestObject",      /* object path */
958                                         "com.example.Frob",             /* interface name */
959                                         "HelloWorld",                   /* method name */
960                                         g_variant_new ("(s)", "Cat"),   /* parameters */
961                                         G_VARIANT_TYPE ("(s)"),         /* return type */
962                                         G_DBUS_CALL_FLAGS_NONE,
963                                         -1,
964                                         NULL,
965                                         &error);
966   g_assert_no_error (error);
967   g_variant_get (result, "(&s)", &s);
968   g_assert_cmpstr (s, ==, "You greeted me with 'Cat'. Thanks!");
969   g_variant_unref (result);
970   /* -- */
971   effects.alter_incoming = TRUE;
972   effects.alter_outgoing = TRUE;
973   error = NULL;
974   result = g_dbus_connection_call_sync (c,
975                                         "com.example.TestService",      /* bus name */
976                                         "/com/example/TestObject",      /* object path */
977                                         "com.example.Frob",             /* interface name */
978                                         "HelloWorld",                   /* method name */
979                                         g_variant_new ("(s)", "Cat"),   /* parameters */
980                                         G_VARIANT_TYPE ("(s)"),         /* return type */
981                                         G_DBUS_CALL_FLAGS_NONE,
982                                         -1,
983                                         NULL,
984                                         &error);
985   g_assert_no_error (error);
986   g_variant_get (result, "(&s)", &s);
987   g_assert_cmpstr (s, ==, "MOD: You greeted me with 'MOD: Cat'. Thanks!");
988   g_variant_unref (result);
989
990
991   g_dbus_connection_remove_filter (c, filter_id);
992
993   g_object_unref (c);
994   g_object_unref (m);
995
996   session_bus_down ();
997 }
998
999 static void
1000 test_connection_basic (void)
1001 {
1002   GDBusConnection *connection;
1003   GError *error;
1004   GDBusCapabilityFlags flags;
1005   gchar *guid;
1006   gchar *name;
1007   gboolean closed;
1008   gboolean exit_on_close;
1009   GIOStream *stream;
1010   GCredentials *credentials;
1011
1012   session_bus_up ();
1013
1014   error = NULL;
1015   connection = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);
1016   g_assert_no_error (error);
1017   g_assert (connection != NULL);
1018
1019   flags = g_dbus_connection_get_capabilities (connection);
1020   g_assert (flags == G_DBUS_CAPABILITY_FLAGS_NONE ||
1021             flags == G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
1022
1023   credentials = g_dbus_connection_get_peer_credentials (connection);
1024   g_assert (credentials == NULL);
1025
1026   g_object_get (connection,
1027                 "stream", &stream,
1028                 "guid", &guid,
1029                 "unique-name", &name,
1030                 "closed", &closed,
1031                 "exit-on-close", &exit_on_close,
1032                 "capabilities", &flags,
1033                 NULL);
1034
1035   g_assert (G_IS_IO_STREAM (stream));
1036   g_assert (g_dbus_is_guid (guid));
1037   g_assert (g_dbus_is_unique_name (name));
1038   g_assert (!closed);
1039   g_assert (exit_on_close);
1040   g_assert (flags == G_DBUS_CAPABILITY_FLAGS_NONE ||
1041             flags == G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
1042   g_object_unref (stream);
1043   g_free (name);
1044   g_free (guid);
1045
1046   g_object_unref (connection);
1047
1048   session_bus_down ();
1049 }
1050
1051 /* ---------------------------------------------------------------------------------------------------- */
1052
1053 int
1054 main (int   argc,
1055       char *argv[])
1056 {
1057   g_type_init ();
1058   g_test_init (&argc, &argv, NULL);
1059
1060   /* all the tests rely on a shared main loop */
1061   loop = g_main_loop_new (NULL, FALSE);
1062
1063   g_test_dbus_unset ();
1064
1065   g_test_add_func ("/gdbus/connection/basic", test_connection_basic);
1066   g_test_add_func ("/gdbus/connection/life-cycle", test_connection_life_cycle);
1067   g_test_add_func ("/gdbus/connection/send", test_connection_send);
1068   g_test_add_func ("/gdbus/connection/signals", test_connection_signals);
1069   g_test_add_func ("/gdbus/connection/filter", test_connection_filter);
1070   return g_test_run();
1071 }