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