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