Don't use GIO in GTestDBus setup
[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 gchar *
457 write_config_file (GTestDBus *self)
458 {
459   GString *contents;
460   gint fd;
461   guint i;
462   GError *error = NULL;
463   gchar *path = NULL;
464
465   fd = g_file_open_tmp ("g-test-dbus-XXXXXX", &path, &error);
466   g_assert_no_error (error);
467
468   contents = g_string_new (NULL);
469   g_string_append (contents,
470       "<busconfig>\n"
471       "  <type>session</type>\n"
472 #ifdef G_OS_WIN32
473       "  <listen>nonce-tcp:</listen>\n"
474 #else
475       "  <listen>unix:tmpdir=/tmp</listen>\n"
476 #endif
477                    );
478
479   for (i = 0; i < self->priv->service_dirs->len; i++)
480     {
481       const gchar *path = g_ptr_array_index (self->priv->service_dirs, i);
482
483       g_string_append_printf (contents,
484           "  <servicedir>%s</servicedir>\n", path);
485     }
486
487   g_string_append (contents,
488       "  <policy context=\"default\">\n"
489       "    <!-- Allow everything to be sent -->\n"
490       "    <allow send_destination=\"*\" eavesdrop=\"true\"/>\n"
491       "    <!-- Allow everything to be received -->\n"
492       "    <allow eavesdrop=\"true\"/>\n"
493       "    <!-- Allow anyone to own anything -->\n"
494       "    <allow own=\"*\"/>\n"
495       "  </policy>\n"
496       "</busconfig>\n");
497
498   g_file_set_contents (path, contents->str, contents->len, &error);
499   g_assert_no_error (error);
500
501   g_string_free (contents, TRUE);
502
503   close (fd);
504
505   return path;
506 }
507
508 static void
509 start_daemon (GTestDBus *self)
510 {
511   gchar *argv[] = {"dbus-daemon", "--print-address", "--config-file=foo", NULL};
512   gchar *config_path;
513   gchar *config_arg;
514   gint stdout_fd;
515   GIOChannel *channel;
516   gsize termpos;
517   GError *error = NULL;
518
519   if (g_getenv ("G_TEST_DBUS_DAEMON") != NULL)
520     argv[0] = (gchar *)g_getenv ("G_TEST_DBUS_DAEMON");
521
522   /* Write config file and set its path in argv */
523   config_path = write_config_file (self);
524   config_arg = g_strdup_printf ("--config-file=%s", config_path);
525   argv[2] = config_arg;
526
527   /* Spawn dbus-daemon */
528   g_spawn_async_with_pipes (NULL,
529                             argv,
530                             NULL,
531 #ifdef G_OS_WIN32
532                             /* We Need this to get the pid returned on win32 */
533                             G_SPAWN_DO_NOT_REAP_CHILD |
534 #endif
535                             G_SPAWN_SEARCH_PATH,
536                             NULL,
537                             NULL,
538                             &self->priv->bus_pid,
539                             NULL,
540                             &stdout_fd,
541                             NULL,
542                             &error);
543   g_assert_no_error (error);
544
545   _g_test_watcher_add_pid (self->priv->bus_pid);
546
547   /* Read bus address from daemon' stdout */
548   channel = g_io_channel_unix_new (stdout_fd);
549   g_io_channel_read_line (channel, &self->priv->bus_address, NULL,
550       &termpos, &error);
551   g_assert_no_error (error);
552   self->priv->bus_address[termpos] = '\0';
553
554   /* start dbus-monitor */
555   if (g_getenv ("G_DBUS_MONITOR") != NULL)
556     {
557       gchar *command;
558
559       command = g_strdup_printf ("dbus-monitor --address %s",
560           self->priv->bus_address);
561       g_spawn_command_line_async (command, NULL);
562       g_free (command);
563
564       g_usleep (500 * 1000);
565     }
566
567   /* Cleanup */
568   g_io_channel_shutdown (channel, FALSE, &error);
569   g_assert_no_error (error);
570   g_io_channel_unref (channel);
571
572   /* Don't use g_file_delete since it calls into gvfs */
573   if (g_unlink (config_path) != 0)
574     g_assert_not_reached ();
575
576   g_free (config_path);
577   g_free (config_arg);
578 }
579
580 static void
581 stop_daemon (GTestDBus *self)
582 {
583 #ifdef G_OS_WIN32
584   if (!TerminateProcess (self->priv->bus_pid, 0))
585     g_warning ("Can't terminate process: %s", g_win32_error_message (GetLastError()));
586 #else
587   kill (self->priv->bus_pid, SIGTERM);
588 #endif
589   _g_test_watcher_remove_pid (self->priv->bus_pid);
590   g_spawn_close_pid (self->priv->bus_pid);
591   self->priv->bus_pid = 0;
592
593   g_free (self->priv->bus_address);
594   self->priv->bus_address = NULL;
595 }
596
597 /**
598  * g_test_dbus_new:
599  * @flags: a #GTestDBusFlags
600  *
601  * Create a new #GTestDBus object.
602  *
603  * Returns: (transfer full): a new #GTestDBus.
604  */
605 GTestDBus *
606 g_test_dbus_new (GTestDBusFlags flags)
607 {
608   return g_object_new (G_TYPE_TEST_DBUS,
609       "flags", flags,
610       NULL);
611 }
612
613 /**
614  * g_test_dbus_get_flags:
615  * @self: a #GTestDBus
616  *
617  * Returns: the value of #GTestDBus:flags property
618  */
619 GTestDBusFlags
620 g_test_dbus_get_flags (GTestDBus *self)
621 {
622   g_return_val_if_fail (G_IS_TEST_DBUS (self), G_TEST_DBUS_NONE);
623
624   return self->priv->flags;
625 }
626
627 /**
628  * g_test_dbus_get_bus_address:
629  * @self: a #GTestDBus
630  *
631  * Get the address on which dbus-daemon is running. if g_test_dbus_up() has not
632  * been called yet, %NULL is returned. This can be used with
633  * g_dbus_connection_new_for_address()
634  *
635  * Returns: the address of the bus, or %NULL.
636  */
637 const gchar *
638 g_test_dbus_get_bus_address (GTestDBus *self)
639 {
640   g_return_val_if_fail (G_IS_TEST_DBUS (self), NULL);
641
642   return self->priv->bus_address;
643 }
644
645 /**
646  * g_test_dbus_add_service_dir:
647  * @self: a #GTestDBus
648  * @path: path to a directory containing .service files
649  *
650  * Add a path where dbus-daemon will lookup for .services files. This can't be
651  * called after g_test_dbus_up().
652  */
653 void
654 g_test_dbus_add_service_dir (GTestDBus *self,
655     const gchar *path)
656 {
657   g_return_if_fail (G_IS_TEST_DBUS (self));
658   g_return_if_fail (self->priv->bus_address == NULL);
659
660   g_ptr_array_add (self->priv->service_dirs, g_strdup (path));
661 }
662
663 /**
664  * g_test_dbus_up:
665  * @self: a #GTestDBus
666  *
667  * Start a dbus-daemon instance and set DBUS_SESSION_BUS_ADDRESS. After this
668  * call, it is safe for unit tests to start sending messages on the session bug.
669  *
670  * If this function is called from setup callback of g_test_add(),
671  * g_test_dbus_down() must be called in its teardown callback.
672  *
673  * If this function is called from unit test's main(), then g_test_dbus_down()
674  * must be called after g_test_run().
675  */
676 void
677 g_test_dbus_up (GTestDBus *self)
678 {
679   g_return_if_fail (G_IS_TEST_DBUS (self));
680   g_return_if_fail (self->priv->bus_address == NULL);
681   g_return_if_fail (!self->priv->up);
682
683   start_daemon (self);
684
685   g_setenv ("DBUS_SESSION_BUS_ADDRESS", self->priv->bus_address, TRUE);
686   self->priv->up = TRUE;
687 }
688
689
690 /**
691  * g_test_dbus_stop:
692  * @self: a #GTestDBus
693  *
694  * Stop the session bus started by g_test_dbus_up().
695  *
696  * Unlike g_test_dbus_down(), this won't verify the #GDBusConnection
697  * singleton returned by g_bus_get() or g_bus_get_sync() is destroyed. Unit
698  * tests wanting to verify behaviour after the session bus has been stopped
699  * can use this function but should still call g_test_dbus_down() when done.
700  */
701 void
702 g_test_dbus_stop (GTestDBus *self)
703 {
704   g_return_if_fail (G_IS_TEST_DBUS (self));
705   g_return_if_fail (self->priv->bus_address != NULL);
706
707   stop_daemon (self);
708 }
709
710 /**
711  * g_test_dbus_down:
712  * @self: a #GTestDBus
713  *
714  * Stop the session bus started by g_test_dbus_up().
715  *
716  * This will wait for the singleton returned by g_bus_get() or g_bus_get_sync()
717  * is destroyed. This is done to ensure that the next unit test won't get a
718  * leaked singleton from this test.
719  */
720 void
721 g_test_dbus_down (GTestDBus *self)
722 {
723   GDBusConnection *connection;
724
725   g_return_if_fail (G_IS_TEST_DBUS (self));
726   g_return_if_fail (self->priv->up);
727
728   connection = _g_bus_get_singleton_if_exists (G_BUS_TYPE_SESSION);
729   if (connection != NULL)
730     g_dbus_connection_set_exit_on_close (connection, FALSE);
731
732   if (self->priv->bus_address != NULL)
733     stop_daemon (self);
734
735   if (connection != NULL)
736     _g_object_unref_and_wait_weak_notify (connection);
737
738   g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");
739   self->priv->up = FALSE;
740 }
741
742 /**
743  * g_test_dbus_unset:
744  *
745  * Unset DISPLAY and DBUS_SESSION_BUS_ADDRESS env variables to ensure the test
746  * won't use user's session bus.
747  *
748  * This is useful for unit tests that want to verify behaviour when no session
749  * bus is running. It is not necessary to call this if unit test already calls
750  * g_test_dbus_up() before acquiring the session bus.
751  */
752 void
753 g_test_dbus_unset (void)
754 {
755   g_unsetenv ("DISPLAY");
756   g_unsetenv ("DBUS_SESSION_BUS_ADDRESS");
757 }