GTestDBus: Don't call into gvfs
[platform/upstream/glib.git] / gio / gtestdbus.c
1 /* GIO testing utilities
2  *
3  * Copyright (C) 2008-2010 Red Hat, Inc.
4  * Copyright (C) 2012 Collabora Ltd. <http://www.collabora.co.uk/>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General
17  * Public License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
19  * Boston, MA 02111-1307, USA.
20  *
21  * Authors: David Zeuthen <davidz@redhat.com>
22  *          Xavier Claessens <xavier.claessens@collabora.co.uk>
23  */
24
25 #include "config.h"
26
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <gstdio.h>
30 #ifdef HAVE_UNISTD_H
31 #include <unistd.h>
32 #endif
33
34 #include <glib.h>
35
36 #include "gdbusconnection.h"
37 #include "gdbusprivate.h"
38 #include "gfile.h"
39 #include "gioenumtypes.h"
40 #include "gtestdbus.h"
41
42 #include "glibintl.h"
43
44 #ifdef G_OS_WIN32
45 #define _WIN32_WINNT 0x0500
46 #include <windows.h>
47 #endif
48
49 /* -------------------------------------------------------------------------- */
50 /* Utility: Wait until object has a single ref  */
51
52 typedef struct
53 {
54   GMainLoop *loop;
55   gboolean   timed_out;
56 } WeakNotifyData;
57
58 static gboolean
59 on_weak_notify_timeout (gpointer user_data)
60 {
61   WeakNotifyData *data = user_data;
62   data->timed_out = TRUE;
63   g_main_loop_quit (data->loop);
64   return FALSE;
65 }
66
67 static gboolean
68 unref_on_idle (gpointer object)
69 {
70   g_object_unref (object);
71   return FALSE;
72 }
73
74 gboolean
75 _g_object_unref_and_wait_weak_notify (gpointer object)
76 {
77   WeakNotifyData data;
78   guint timeout_id;
79
80   data.loop = g_main_loop_new (NULL, FALSE);
81   data.timed_out = FALSE;
82
83   g_object_weak_ref (object, (GWeakNotify) g_main_loop_quit, data.loop);
84
85   /* Drop the ref in an idle callback, this is to make sure the mainloop
86    * is already running when weak notify happens */
87   g_idle_add (unref_on_idle, object);
88
89   /* Make sure we don't block forever */
90   timeout_id = g_timeout_add (30 * 1000, on_weak_notify_timeout, &data);
91
92   g_main_loop_run (data.loop);
93
94   g_source_remove (timeout_id);
95
96   if (data.timed_out)
97     {
98       g_warning ("Weak notify timeout, object ref_count=%d\n",
99           G_OBJECT (object)->ref_count);
100     }
101
102   return data.timed_out;
103 }
104
105 /* -------------------------------------------------------------------------- */
106 /* Utilities to cleanup the mess in the case unit test process crash */
107
108 #ifdef G_OS_WIN32
109
110 /* This could be interesting to expose in public API */
111 static void
112 _g_test_watcher_add_pid (GPid pid)
113 {
114   static gsize started = 0;
115   HANDLE job;
116
117   if (g_once_init_enter (&started))
118     {
119       JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
120
121       job = CreateJobObjectW (NULL, NULL);
122       memset (&info, 0, sizeof (info));
123       info.BasicLimitInformation.LimitFlags = 0x2000 /* JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE */;
124
125       if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &info, sizeof (info)))
126         g_warning ("Can't enable JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: %s", g_win32_error_message (GetLastError()));
127
128       g_once_init_leave (&started,(gsize)job);
129     }
130
131   job = (HANDLE)started;
132
133   if (!AssignProcessToJobObject(job, pid))
134     g_warning ("Can't assign process to job: %s", g_win32_error_message (GetLastError()));
135 }
136
137 static void
138 _g_test_watcher_remove_pid (GPid pid)
139 {
140   /* No need to unassign the process from the job object as the process
141      will be killed anyway */
142 }
143
144 #else
145
146 #define ADD_PID_FORMAT "add pid %d\n"
147 #define REMOVE_PID_FORMAT "remove pid %d\n"
148
149 static void
150 watch_parent (gint fd)
151 {
152   GIOChannel *channel;
153   GPollFD fds[1];
154   GArray *pids_to_kill;
155
156   channel = g_io_channel_unix_new (fd);
157
158   fds[0].fd = fd;
159   fds[0].events = G_IO_HUP | G_IO_IN;
160   fds[0].revents = 0;
161
162   pids_to_kill = g_array_new (FALSE, FALSE, sizeof (guint));
163
164   do
165     {
166       gint num_events;
167       gchar *command = NULL;
168       guint pid;
169       guint n;
170       GError *error = NULL;
171
172       num_events = g_poll (fds, 1, -1);
173       if (num_events == 0)
174         continue;
175
176       if (fds[0].revents == G_IO_HUP)
177         {
178           /* Parent quit, cleanup the mess and exit */
179           for (n = 0; n < pids_to_kill->len; n++)
180             {
181               pid = g_array_index (pids_to_kill, guint, n);
182               g_print ("cleaning up pid %d\n", pid);
183               kill (pid, SIGTERM);
184             }
185
186           g_array_unref (pids_to_kill);
187           g_io_channel_shutdown (channel, FALSE, &error);
188           g_assert_no_error (error);
189           g_io_channel_unref (channel);
190
191           exit (0);
192         }
193
194       /* Read the command from the input */
195       g_io_channel_read_line (channel, &command, NULL, NULL, &error);
196       g_assert_no_error (error);
197
198       /* Check for known commands */
199       if (sscanf (command, ADD_PID_FORMAT, &pid) == 1)
200         {
201           g_array_append_val (pids_to_kill, pid);
202         }
203       else if (sscanf (command, REMOVE_PID_FORMAT, &pid) == 1)
204         {
205           for (n = 0; n < pids_to_kill->len; n++)
206             {
207               if (g_array_index (pids_to_kill, guint, n) == pid)
208                 {
209                   g_array_remove_index (pids_to_kill, n);
210                   pid = 0;
211                   break;
212                 }
213             }
214           if (pid != 0)
215             {
216               g_warning ("unknown pid %d to remove", pid);
217             }
218         }
219       else
220         {
221           g_warning ("unknown command from parent '%s'", command);
222         }
223
224       g_free (command);
225     }
226   while (TRUE);
227 }
228
229 static GIOChannel *
230 watcher_init (void)
231 {
232   static gsize started = 0;
233   static GIOChannel *channel = NULL;
234
235   if (g_once_init_enter (&started))
236     {
237       gint pipe_fds[2];
238
239       /* fork a child to clean up when we are killed */
240       if (pipe (pipe_fds) != 0)
241         {
242           g_warning ("pipe() failed: %m");
243           g_assert_not_reached ();
244         }
245
246       switch (fork ())
247         {
248         case -1:
249           g_warning ("fork() failed: %m");
250           g_assert_not_reached ();
251           break;
252
253         case 0:
254           /* child */
255           close (pipe_fds[1]);
256           watch_parent (pipe_fds[0]);
257           break;
258
259         default:
260           /* parent */
261           close (pipe_fds[0]);
262           channel = g_io_channel_unix_new (pipe_fds[1]);
263         }
264
265       g_once_init_leave (&started, 1);
266     }
267
268   return channel;
269 }
270
271 static void
272 watcher_send_command (const gchar *command)
273 {
274   GIOChannel *channel;
275   GError *error = NULL;
276
277   channel = watcher_init ();
278
279   g_io_channel_write_chars (channel, command, -1, NULL, &error);
280   g_assert_no_error (error);
281
282   g_io_channel_flush (channel, &error);
283   g_assert_no_error (error);
284 }
285
286 /* This could be interesting to expose in public API */
287 static void
288 _g_test_watcher_add_pid (GPid pid)
289 {
290   gchar *command;
291
292   command = g_strdup_printf (ADD_PID_FORMAT, (guint) pid);
293   watcher_send_command (command);
294   g_free (command);
295 }
296
297 static void
298 _g_test_watcher_remove_pid (GPid pid)
299 {
300   gchar *command;
301
302   command = g_strdup_printf (REMOVE_PID_FORMAT, (guint) pid);
303   watcher_send_command (command);
304   g_free (command);
305 }
306
307 #endif
308
309 /* -------------------------------------------------------------------------- */
310 /* GTestDBus object implementation */
311
312 /**
313  * SECTION:gtestdbus
314  * @short_description: D-Bus testing helper
315  * @include: gio/gio.h
316  *
317  * Helper to test D-Bus code wihtout messing up with user' session bus.
318  */
319
320 typedef struct _GTestDBusClass   GTestDBusClass;
321 typedef struct _GTestDBusPrivate GTestDBusPrivate;
322
323 /**
324  * GTestDBus:
325  *
326  * The #GTestDBus structure contains only private data and
327  * should only be accessed using the provided API.
328  *
329  * Since: 2.34
330  */
331 struct _GTestDBus {
332   GObject parent;
333
334   GTestDBusPrivate *priv;
335 };
336
337 struct _GTestDBusClass {
338   GObjectClass parent_class;
339 };
340
341 struct _GTestDBusPrivate
342 {
343   GTestDBusFlags flags;
344   GPtrArray *service_dirs;
345   GPid bus_pid;
346   gchar *bus_address;
347   gboolean up;
348 };
349
350 enum
351 {
352   PROP_0,
353   PROP_FLAGS,
354 };
355
356 G_DEFINE_TYPE (GTestDBus, g_test_dbus, G_TYPE_OBJECT)
357
358 static void
359 g_test_dbus_init (GTestDBus *self)
360 {
361   self->priv = G_TYPE_INSTANCE_GET_PRIVATE ((self), G_TYPE_TEST_DBUS,
362       GTestDBusPrivate);
363
364   self->priv->service_dirs = g_ptr_array_new_with_free_func (g_free);
365 }
366
367 static void
368 g_test_dbus_dispose (GObject *object)
369 {
370   GTestDBus *self = (GTestDBus *) object;
371
372   if (self->priv->up)
373     g_test_dbus_down (self);
374
375   G_OBJECT_CLASS (g_test_dbus_parent_class)->dispose (object);
376 }
377
378 static void
379 g_test_dbus_finalize (GObject *object)
380 {
381   GTestDBus *self = (GTestDBus *) object;
382
383   g_ptr_array_unref (self->priv->service_dirs);
384   g_free (self->priv->bus_address);
385
386   G_OBJECT_CLASS (g_test_dbus_parent_class)->finalize (object);
387 }
388
389 static void
390 g_test_dbus_get_property (GObject *object,
391     guint property_id,
392     GValue *value,
393     GParamSpec *pspec)
394 {
395   GTestDBus *self = (GTestDBus *) object;
396
397   switch (property_id)
398     {
399       case PROP_FLAGS:
400         g_value_set_flags (value, g_test_dbus_get_flags (self));
401         break;
402       default:
403         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
404         break;
405     }
406 }
407
408 static void
409 g_test_dbus_set_property (GObject *object,
410     guint property_id,
411     const GValue *value,
412     GParamSpec *pspec)
413 {
414   GTestDBus *self = (GTestDBus *) object;
415
416   switch (property_id)
417     {
418       case PROP_FLAGS:
419         self->priv->flags = g_value_get_flags (value);
420         break;
421       default:
422         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
423         break;
424     }
425 }
426
427 static void
428 g_test_dbus_class_init (GTestDBusClass *klass)
429 {
430   GObjectClass *object_class = G_OBJECT_CLASS (klass);
431
432   object_class->dispose = g_test_dbus_dispose;
433   object_class->finalize = g_test_dbus_finalize;
434   object_class->get_property = g_test_dbus_get_property;
435   object_class->set_property = g_test_dbus_set_property;
436
437   g_type_class_add_private (object_class, sizeof (GTestDBusPrivate));
438
439   /**
440    * GTestDBus:flags:
441    *
442    * #GTestDBusFlags specifying the behaviour of the dbus session
443    *
444    * Since: 2.34
445    */
446   g_object_class_install_property (object_class, PROP_FLAGS,
447     g_param_spec_flags ("flags",
448                         P_("dbus session flags"),
449                         P_("Flags specifying the behaviour of the dbus session"),
450                         G_TYPE_TEST_DBUS_FLAGS, G_TEST_DBUS_NONE,
451                         G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
452                         G_PARAM_STATIC_STRINGS));
453
454 }
455
456 static GFile *
457 write_config_file (GTestDBus *self)
458 {
459   GString *contents;
460   GFile *file;
461   GFileIOStream *iostream;
462   guint i;
463   GError *error = NULL;
464
465   file = g_file_new_tmp ("g-test-dbus-XXXXXX", &iostream, &error);
466   g_assert_no_error (error);
467   g_object_unref (iostream);
468
469   contents = g_string_new (NULL);
470   g_string_append (contents,
471       "<busconfig>\n"
472       "  <type>session</type>\n"
473 #ifdef G_OS_WIN32
474       "  <listen>nonce-tcp:</listen>\n"
475 #else
476       "  <listen>unix:tmpdir=/tmp</listen>\n"
477 #endif
478                    );
479
480   for (i = 0; i < self->priv->service_dirs->len; i++)
481     {
482       const gchar *path = g_ptr_array_index (self->priv->service_dirs, i);
483
484       g_string_append_printf (contents,
485           "  <servicedir>%s</servicedir>\n", path);
486     }
487
488   g_string_append (contents,
489       "  <policy context=\"default\">\n"
490       "    <!-- Allow everything to be sent -->\n"
491       "    <allow send_destination=\"*\" eavesdrop=\"true\"/>\n"
492       "    <!-- Allow everything to be received -->\n"
493       "    <allow eavesdrop=\"true\"/>\n"
494       "    <!-- Allow anyone to own anything -->\n"
495       "    <allow own=\"*\"/>\n"
496       "  </policy>\n"
497       "</busconfig>\n");
498
499   g_file_replace_contents (file, contents->str, contents->len,
500       NULL, FALSE, G_FILE_CREATE_NONE, NULL, NULL, &error);
501   g_assert_no_error (error);
502
503   g_string_free (contents, TRUE);
504
505   return file;
506 }
507
508 static void
509 start_daemon (GTestDBus *self)
510 {
511   gchar *argv[] = {"dbus-daemon", "--print-address", "--config-file=foo", NULL};
512   GFile *file;
513   gchar *config_path;
514   gchar *config_arg;
515   gint stdout_fd;
516   GIOChannel *channel;
517   gsize termpos;
518   GError *error = NULL;
519
520   if (g_getenv ("G_TEST_DBUS_DAEMON") != NULL)
521     argv[0] = (gchar *)g_getenv ("G_TEST_DBUS_DAEMON");
522
523   /* Write config file and set its path in argv */
524   file = write_config_file (self);
525   config_path = g_file_get_path (file);
526   g_object_unref (file);
527   config_arg = g_strdup_printf ("--config-file=%s", config_path);
528   argv[2] = config_arg;
529
530   /* Spawn dbus-daemon */
531   g_spawn_async_with_pipes (NULL,
532                             argv,
533                             NULL,
534 #ifdef G_OS_WIN32
535                             /* We Need this to get the pid returned on win32 */
536                             G_SPAWN_DO_NOT_REAP_CHILD |
537 #endif
538                             G_SPAWN_SEARCH_PATH,
539                             NULL,
540                             NULL,
541                             &self->priv->bus_pid,
542                             NULL,
543                             &stdout_fd,
544                             NULL,
545                             &error);
546   g_assert_no_error (error);
547
548   _g_test_watcher_add_pid (self->priv->bus_pid);
549
550   /* Read bus address from daemon' stdout */
551   channel = g_io_channel_unix_new (stdout_fd);
552   g_io_channel_read_line (channel, &self->priv->bus_address, NULL,
553       &termpos, &error);
554   g_assert_no_error (error);
555   self->priv->bus_address[termpos] = '\0';
556
557   /* start dbus-monitor */
558   if (g_getenv ("G_DBUS_MONITOR") != NULL)
559     {
560       gchar *command;
561
562       command = g_strdup_printf ("dbus-monitor --address %s",
563           self->priv->bus_address);
564       g_spawn_command_line_async (command, NULL);
565       g_free (command);
566
567       g_usleep (500 * 1000);
568     }
569
570   /* Cleanup */
571   g_io_channel_shutdown (channel, FALSE, &error);
572   g_assert_no_error (error);
573   g_io_channel_unref (channel);
574
575   /* Don't use g_file_delete since it calls into gvfs */
576   if (g_unlink (config_path) != 0)
577     g_assert_not_reached ();
578
579   g_free (config_path);
580   g_free (config_arg);
581 }
582
583 static void
584 stop_daemon (GTestDBus *self)
585 {
586 #ifdef G_OS_WIN32
587   if (!TerminateProcess (self->priv->bus_pid, 0))
588     g_warning ("Can't terminate process: %s", g_win32_error_message (GetLastError()));
589 #else
590   kill (self->priv->bus_pid, SIGTERM);
591 #endif
592   _g_test_watcher_remove_pid (self->priv->bus_pid);
593   g_spawn_close_pid (self->priv->bus_pid);
594   self->priv->bus_pid = 0;
595
596   g_free (self->priv->bus_address);
597   self->priv->bus_address = NULL;
598 }
599
600 /**
601  * g_test_dbus_new:
602  * @flags: a #GTestDBusFlags
603  *
604  * Create a new #GTestDBus object.
605  *
606  * Returns: (transfer full): a new #GTestDBus.
607  */
608 GTestDBus *
609 g_test_dbus_new (GTestDBusFlags flags)
610 {
611   return g_object_new (G_TYPE_TEST_DBUS,
612       "flags", flags,
613       NULL);
614 }
615
616 /**
617  * g_test_dbus_get_flags:
618  * @self: a #GTestDBus
619  *
620  * Returns: the value of #GTestDBus:flags property
621  */
622 GTestDBusFlags
623 g_test_dbus_get_flags (GTestDBus *self)
624 {
625   g_return_val_if_fail (G_IS_TEST_DBUS (self), G_TEST_DBUS_NONE);
626
627   return self->priv->flags;
628 }
629
630 /**
631  * g_test_dbus_get_bus_address:
632  * @self: a #GTestDBus
633  *
634  * Get the address on which dbus-daemon is running. if g_test_dbus_up() has not
635  * been called yet, %NULL is returned. This can be used with
636  * g_dbus_connection_new_for_address()
637  *
638  * Returns: the address of the bus, or %NULL.
639  */
640 const gchar *
641 g_test_dbus_get_bus_address (GTestDBus *self)
642 {
643   g_return_val_if_fail (G_IS_TEST_DBUS (self), NULL);
644
645   return self->priv->bus_address;
646 }
647
648 /**
649  * g_test_dbus_add_service_dir:
650  * @self: a #GTestDBus
651  * @path: path to a directory containing .service files
652  *
653  * Add a path where dbus-daemon will lookup for .services files. This can't be
654  * called after g_test_dbus_up().
655  */
656 void
657 g_test_dbus_add_service_dir (GTestDBus *self,
658     const gchar *path)
659 {
660   g_return_if_fail (G_IS_TEST_DBUS (self));
661   g_return_if_fail (self->priv->bus_address == NULL);
662
663   g_ptr_array_add (self->priv->service_dirs, g_strdup (path));
664 }
665
666 /**
667  * g_test_dbus_up:
668  * @self: a #GTestDBus
669  *
670  * Start a dbus-daemon instance and set DBUS_SESSION_BUS_ADDRESS. After this
671  * call, it is safe for unit tests to start sending messages on the session bug.
672  *
673  * If this function is called from setup callback of g_test_add(),
674  * g_test_dbus_down() must be called in its teardown callback.
675  *
676  * If this function is called from unit test's main(), then g_test_dbus_down()
677  * must be called after g_test_run().
678  */
679 void
680 g_test_dbus_up (GTestDBus *self)
681 {
682   g_return_if_fail (G_IS_TEST_DBUS (self));
683   g_return_if_fail (self->priv->bus_address == NULL);
684   g_return_if_fail (!self->priv->up);
685
686   start_daemon (self);
687
688   g_setenv ("DBUS_SESSION_BUS_ADDRESS", self->priv->bus_address, TRUE);
689   self->priv->up = TRUE;
690 }
691
692
693 /**
694  * g_test_dbus_stop:
695  * @self: a #GTestDBus
696  *
697  * Stop the session bus started by g_test_dbus_up().
698  *
699  * Unlike g_test_dbus_down(), this won't verify the #GDBusConnection
700  * singleton returned by g_bus_get() or g_bus_get_sync() is destroyed. Unit
701  * tests wanting to verify behaviour after the session bus has been stopped
702  * can use this function but should still call g_test_dbus_down() when done.
703  */
704 void
705 g_test_dbus_stop (GTestDBus *self)
706 {
707   g_return_if_fail (G_IS_TEST_DBUS (self));
708   g_return_if_fail (self->priv->bus_address != NULL);
709
710   stop_daemon (self);
711 }
712
713 /**
714  * g_test_dbus_down:
715  * @self: a #GTestDBus
716  *
717  * Stop the session bus started by g_test_dbus_up().
718  *
719  * This will wait for the singleton returned by g_bus_get() or g_bus_get_sync()
720  * is destroyed. This is done to ensure that the next unit test won't get a
721  * leaked singleton from this test.
722  */
723 void
724 g_test_dbus_down (GTestDBus *self)
725 {
726   GDBusConnection *connection;
727
728   g_return_if_fail (G_IS_TEST_DBUS (self));
729   g_return_if_fail (self->priv->up);
730
731   connection = _g_bus_get_singleton_if_exists (G_BUS_TYPE_SESSION);
732   if (connection != NULL)
733     g_dbus_connection_set_exit_on_close (connection, FALSE);
734
735   if (self->priv->bus_address != NULL)
736     stop_daemon (self);
737
738   if (connection != NULL)
739     _g_object_unref_and_wait_weak_notify (connection);
740
741   g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");
742   self->priv->up = FALSE;
743 }
744
745 /**
746  * g_test_dbus_unset:
747  *
748  * Unset DISPLAY and DBUS_SESSION_BUS_ADDRESS env variables to ensure the test
749  * won't use user's session bus.
750  *
751  * This is useful for unit tests that want to verify behaviour when no session
752  * bus is running. It is not necessary to call this if unit test already calls
753  * g_test_dbus_up() before acquiring the session bus.
754  */
755 void
756 g_test_dbus_unset (void)
757 {
758   g_unsetenv ("DISPLAY");
759   g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");
760 }