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