summaryrefslogtreecommitdiff
path: root/src/dkp-daemon.c
blob: be884e8851d10f4e48d2874878db7e43d75fb3da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*-
 *
 * Copyright (C) 2008 David Zeuthen <davidz@redhat.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif

#include <string.h>

#include <glib.h>
#include <glib/gi18n-lib.h>
#include <glib-object.h>
#include <dbus/dbus-glib.h>
#include <dbus/dbus-glib-lowlevel.h>
#include <devkit-gobject/devkit-gobject.h>

#include "egg-debug.h"
#include "egg-string.h"

#include "dkp-daemon.h"
#include "dkp-device.h"
#include "dkp-supply.h"
#include "dkp-csr.h"
#include "dkp-wup.h"
#include "dkp-hid.h"
#include "dkp-device-list.h"

#include "dkp-daemon-glue.h"
#include "dkp-marshal.h"

enum
{
	DEVICE_ADDED_SIGNAL,
	DEVICE_REMOVED_SIGNAL,
	DEVICE_CHANGED_SIGNAL,
	ON_BATTERY_CHANGED_SIGNAL,
	LOW_BATTERY_CHANGED_SIGNAL,
	LAST_SIGNAL,
};

static const gchar *subsystems[] = {"power_supply", "usb", "tty", NULL};

static guint signals[LAST_SIGNAL] = { 0 };

struct DkpDaemonPrivate
{
	DBusGConnection		*system_bus_connection;
	DBusGProxy		*system_bus_proxy;
	PolKitContext		*pk_context;
	PolKitTracker		*pk_tracker;

	DkpDeviceList		*list;
	gboolean		 on_battery;
	gboolean		 low_battery;

	DevkitClient		*devkit_client;
};

static void	dkp_daemon_class_init	(DkpDaemonClass *klass);
static void	dkp_daemon_init		(DkpDaemon	*seat);
static void	dkp_daemon_finalize	(GObject	*object);
static gboolean	dkp_daemon_get_on_battery_local (DkpDaemon *daemon);
static gboolean	dkp_daemon_get_low_battery_local (DkpDaemon *daemon);

G_DEFINE_TYPE (DkpDaemon, dkp_daemon, G_TYPE_OBJECT)

#define DKP_DAEMON_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), DKP_TYPE_DAEMON, DkpDaemonPrivate))

/**
 * dkp_daemon_error_quark:
 **/
GQuark
dkp_daemon_error_quark (void)
{
	static GQuark ret = 0;
	if (ret == 0)
		ret = g_quark_from_static_string ("dkp_daemon_error");
	return ret;
}

#define ENUM_ENTRY(NAME, DESC) { NAME, "" #NAME "", DESC }
/**
 * dkp_daemon_error_get_type:
 **/
GType
dkp_daemon_error_get_type (void)
{
	static GType etype = 0;

	if (etype == 0)
	{
		static const GEnumValue values[] =
			{
				ENUM_ENTRY (DKP_DAEMON_ERROR_GENERAL, "GeneralError"),
				ENUM_ENTRY (DKP_DAEMON_ERROR_NOT_SUPPORTED, "NotSupported"),
				ENUM_ENTRY (DKP_DAEMON_ERROR_NO_SUCH_DEVICE, "NoSuchDevice"),
				{ 0, 0, 0 }
			};
		g_assert (DKP_DAEMON_NUM_ERRORS == G_N_ELEMENTS (values) - 1);
		etype = g_enum_register_static ("DkpDaemonError", values);
	}
	return etype;
}

/**
 * dkp_daemon_constructor:
 **/
static GObject *
dkp_daemon_constructor (GType type, guint n_construct_properties, GObjectConstructParam *construct_properties)
{
	DkpDaemon *daemon;
	DkpDaemonClass *klass;

	klass = DKP_DAEMON_CLASS (g_type_class_peek (DKP_TYPE_DAEMON));
	daemon = DKP_DAEMON (G_OBJECT_CLASS (dkp_daemon_parent_class)->constructor (type, n_construct_properties, construct_properties));
	return G_OBJECT (daemon);
}

/**
 * dkp_daemon_class_init:
 **/
static void
dkp_daemon_class_init (DkpDaemonClass *klass)
{
	GObjectClass *object_class = G_OBJECT_CLASS (klass);

	object_class->constructor = dkp_daemon_constructor;
	object_class->finalize = dkp_daemon_finalize;

	g_type_class_add_private (klass, sizeof (DkpDaemonPrivate));

	signals[DEVICE_ADDED_SIGNAL] =
		g_signal_new ("device-added",
			      G_OBJECT_CLASS_TYPE (klass),
			      G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
			      0,
			      NULL, NULL,
			      g_cclosure_marshal_VOID__STRING,
			      G_TYPE_NONE, 1, G_TYPE_STRING);

	signals[DEVICE_REMOVED_SIGNAL] =
		g_signal_new ("device-removed",
			      G_OBJECT_CLASS_TYPE (klass),
			      G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
			      0,
			      NULL, NULL,
			      g_cclosure_marshal_VOID__STRING,
			      G_TYPE_NONE, 1, G_TYPE_STRING);

	signals[DEVICE_CHANGED_SIGNAL] =
		g_signal_new ("device-changed",
			      G_OBJECT_CLASS_TYPE (klass),
			      G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
			      0,
			      NULL, NULL,
			      g_cclosure_marshal_VOID__STRING,
			      G_TYPE_NONE, 1, G_TYPE_STRING);

	signals[ON_BATTERY_CHANGED_SIGNAL] =
		g_signal_new ("on-battery-changed",
			      G_OBJECT_CLASS_TYPE (klass),
			      G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
			      0,
			      NULL, NULL,
			      g_cclosure_marshal_VOID__BOOLEAN,
			      G_TYPE_NONE, 1, G_TYPE_BOOLEAN);

	signals[LOW_BATTERY_CHANGED_SIGNAL] =
		g_signal_new ("low-battery-changed",
			      G_OBJECT_CLASS_TYPE (klass),
			      G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
			      0,
			      NULL, NULL,
			      g_cclosure_marshal_VOID__BOOLEAN,
			      G_TYPE_NONE, 1, G_TYPE_BOOLEAN);

	dbus_g_object_type_install_info (DKP_TYPE_DAEMON, &dbus_glib_dkp_daemon_object_info);

	dbus_g_error_domain_register (DKP_DAEMON_ERROR, NULL, DKP_DAEMON_TYPE_ERROR);
}

/**
 * dkp_daemon_init:
 **/
static void
dkp_daemon_init (DkpDaemon *daemon)
{
	daemon->priv = DKP_DAEMON_GET_PRIVATE (daemon);
}

/**
 * dkp_daemon_finalize:
 **/
static void
dkp_daemon_finalize (GObject *object)
{
	DkpDaemon *daemon;

	g_return_if_fail (object != NULL);
	g_return_if_fail (DKP_IS_DAEMON (object));

	daemon = DKP_DAEMON (object);

	g_return_if_fail (daemon->priv != NULL);

	if (daemon->priv->pk_context != NULL)
		polkit_context_unref (daemon->priv->pk_context);
	if (daemon->priv->pk_tracker != NULL)
		polkit_tracker_unref (daemon->priv->pk_tracker);
	if (daemon->priv->system_bus_proxy != NULL)
		g_object_unref (daemon->priv->system_bus_proxy);
	if (daemon->priv->system_bus_connection != NULL)
		dbus_g_connection_unref (daemon->priv->system_bus_connection);
	if (daemon->priv->devkit_client != NULL)
		g_object_unref (daemon->priv->devkit_client);
	if (daemon->priv->list != NULL)
		g_object_unref (daemon->priv->list);

	G_OBJECT_CLASS (dkp_daemon_parent_class)->finalize (object);
}

/**
 * pk_io_watch_have_data:
 **/
static gboolean
pk_io_watch_have_data (GIOChannel *channel, GIOCondition condition, gpointer user_data)
{
	int fd;
	PolKitContext *pk_context = user_data;
	fd = g_io_channel_unix_get_fd (channel);
	polkit_context_io_func (pk_context, fd);
	return TRUE;
}

/**
 * pk_io_add_watch:
 **/
static int
pk_io_add_watch (PolKitContext *pk_context, int fd)
{
	guint id = 0;
	GIOChannel *channel;
	channel = g_io_channel_unix_new (fd);
	if (channel == NULL)
		goto out;
	id = g_io_add_watch (channel, G_IO_IN, pk_io_watch_have_data, pk_context);
	if (id == 0) {
		g_io_channel_unref (channel);
		goto out;
	}
	g_io_channel_unref (channel);
out:
	return id;
}

/**
 * pk_io_remove_watch:
 **/
static void
pk_io_remove_watch (PolKitContext *pk_context, int watch_id)
{
	g_source_remove (watch_id);
}

/**
 * gpk_daemon_dbus_filter:
 **/
static DBusHandlerResult
gpk_daemon_dbus_filter (DBusConnection *connection, DBusMessage *message, void *user_data)
{
	DkpDaemon *daemon = DKP_DAEMON (user_data);
	const gchar *interface;

	interface = dbus_message_get_interface (message);

	if (dbus_message_is_signal (message, DBUS_INTERFACE_DBUS, "NameOwnerChanged")) {
		/* pass NameOwnerChanged signals from the bus to PolKitTracker */
		polkit_tracker_dbus_func (daemon->priv->pk_tracker, message);
	}

	if (interface != NULL && g_str_has_prefix (interface, "org.freedesktop.ConsoleKit")) {
		/* pass ConsoleKit signals to PolKitTracker */
		polkit_tracker_dbus_func (daemon->priv->pk_tracker, message);
	}

	/* other filters might want to process this message too */
	return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}

static gboolean gpk_daemon_device_add (DkpDaemon *daemon, DevkitDevice *d, gboolean emit_event);
static void gpk_daemon_device_remove (DkpDaemon *daemon, DevkitDevice *d);

/**
 * dkp_daemon_get_on_battery_local:
 *
 * As soon as _any_ battery goes discharging, this is true
 **/
static gboolean
dkp_daemon_get_on_battery_local (DkpDaemon *daemon)
{
	guint i;
	gboolean ret;
	gboolean result = FALSE;
	gboolean on_battery;
	DkpDevice *device;
	const GPtrArray *array;

	/* ask each device */
	array = dkp_device_list_get_array (daemon->priv->list);
	for (i=0; i<array->len; i++) {
		device = (DkpDevice *) g_ptr_array_index (array, i);
		ret = dkp_device_get_on_battery (device, &on_battery);
		if (ret && on_battery) {
			result = TRUE;
			break;
		}
	}
	return result;
}

/**
 * dkp_daemon_get_low_battery_local:
 *
 * As soon as _all_ batteries are low, this is true
 **/
static gboolean
dkp_daemon_get_low_battery_local (DkpDaemon *daemon)
{
	guint i;
	gboolean ret;
	gboolean result = TRUE;
	gboolean low_battery;
	DkpDevice *device;
	const GPtrArray *array;

	/* ask each device */
	array = dkp_device_list_get_array (daemon->priv->list);
	for (i=0; i<array->len; i++) {
		device = (DkpDevice *) g_ptr_array_index (array, i);
		ret = dkp_device_get_low_battery (device, &low_battery);
		if (ret && !low_battery) {
			result = FALSE;
			break;
		}
	}
	return result;
}

/**
 * gpk_daemon_device_changed:
 **/
static void
gpk_daemon_device_changed (DkpDaemon *daemon, DevkitDevice *d, gboolean synthesized)
{
	DkpDevice *device;
	gboolean ret;

	/* check if the on_battery and low_battery state has changed */
	ret = dkp_daemon_get_on_battery_local (daemon);
	if (ret != daemon->priv->on_battery) {
		daemon->priv->on_battery = ret;
		egg_debug ("now on_battery = %s", ret ? "yes" : "no");
		g_signal_emit (daemon, signals[ON_BATTERY_CHANGED_SIGNAL], 0, ret);
	}
	ret = dkp_daemon_get_low_battery_local (daemon);
	if (ret != daemon->priv->low_battery) {
		daemon->priv->low_battery = ret;
		egg_debug ("now low_battery = %s", ret ? "yes" : "no");
		g_signal_emit (daemon, signals[LOW_BATTERY_CHANGED_SIGNAL], 0, ret);
	}

	/* does the device exist in the db? */
	device = dkp_device_list_lookup (daemon->priv->list, d);
	if (device != NULL) {
		egg_debug ("changed %s", dkp_device_get_object_path (device));
		dkp_device_changed (device, d, synthesized);
	} else {
		egg_debug ("treating change event as add on %s", dkp_device_get_object_path (device));
		gpk_daemon_device_add (daemon, d, TRUE);
	}
}

/**
 * gpk_daemon_device_went_away:
 **/
static void
gpk_daemon_device_went_away (gpointer user_data, GObject *_device)
{
	DkpDaemon *daemon = DKP_DAEMON (user_data);
	DkpDevice *device = DKP_DEVICE (_device);
	dkp_device_list_remove (daemon->priv->list, device);
}

/**
 * gpk_daemon_device_get:
 **/
static DkpDevice *
gpk_daemon_device_get (DkpDaemon *daemon, DevkitDevice *d)
{
	const gchar *subsys;
	const gchar *native_path;
	DkpDevice *device = NULL;
	gboolean ret;

	subsys = devkit_device_get_subsystem (d);
	if (egg_strequal (subsys, "power_supply")) {

		/* are we a valid power supply */
		device = DKP_DEVICE (dkp_supply_new ());
		ret = dkp_device_coldplug (device, daemon, d);
		if (ret)
			goto out;
		g_object_unref (device);

		/* no valid power supply object */
		device = NULL;

	} else if (egg_strequal (subsys, "tty")) {

		/* try to detect a Watts Up? Pro monitor */
		device = DKP_DEVICE (dkp_wup_new ());
		ret = dkp_device_coldplug (device, daemon, d);
		if (ret)
			goto out;
		g_object_unref (device);

		/* no valid TTY object ;-( */
		device = NULL;

	} else if (egg_strequal (subsys, "usb")) {

		/* see if this is a CSR mouse or keyboard */
		device = DKP_DEVICE (dkp_csr_new ());
		ret = dkp_device_coldplug (device, daemon, d);
		if (ret)
			goto out;
		g_object_unref (device);

		/* try to detect a HID UPS */
		device = DKP_DEVICE (dkp_hid_new ());
		ret = dkp_device_coldplug (device, daemon, d);
		if (ret)
			goto out;
		g_object_unref (device);

		/* no valid USB object ;-( */
		device = NULL;

	} else {
		native_path = devkit_device_get_native_path (d);
		egg_warning ("native path %s (%s) ignoring", native_path, subsys);
	}
out:
	return device;
}

/**
 * gpk_daemon_device_add:
 **/
static gboolean
gpk_daemon_device_add (DkpDaemon *daemon, DevkitDevice *d, gboolean emit_event)
{
	DkpDevice *device;
	gboolean ret = TRUE;

	/* does device exist in db? */
	device = dkp_device_list_lookup (daemon->priv->list, d);
	if (device != NULL) {
		/* we already have the device; treat as change event */
		egg_debug ("treating add event as change event on %s", dkp_device_get_object_path (device));
		gpk_daemon_device_changed (daemon, d, FALSE);
	} else {

		/* get the right sort of device */
		device = gpk_daemon_device_get (daemon, d);
		if (device == NULL) {
			egg_debug ("ignoring add event on %s", devkit_device_get_native_path (d));
			ret = FALSE;
			goto out;
		}
		/* only take a weak ref; the device will stay on the bus until
		 * it's unreffed. So if we ref it, it'll never go away.
		 */
		g_object_weak_ref (G_OBJECT (device), gpk_daemon_device_went_away, daemon);
		dkp_device_list_insert (daemon->priv->list, d, device);
		if (emit_event) {
			g_signal_emit (daemon, signals[DEVICE_ADDED_SIGNAL], 0,
				       dkp_device_get_object_path (device));
		}
	}
out:
	return ret;
}

/**
 * gpk_daemon_device_remove:
 **/
static void
gpk_daemon_device_remove (DkpDaemon *daemon, DevkitDevice *d)
{
	DkpDevice *device;

	/* does device exist in db? */
	device = dkp_device_list_lookup (daemon->priv->list, d);
	if (device == NULL) {
		egg_debug ("ignoring remove event on %s", devkit_device_get_native_path (d));
	} else {
		dkp_device_removed (device);
		g_signal_emit (daemon, signals[DEVICE_REMOVED_SIGNAL], 0,
			       dkp_device_get_object_path (device));
		g_object_unref (device);
	}
}

/**
 * gpk_daemon_device_event_signal_handler:
 **/
static void
gpk_daemon_device_event_signal_handler (DevkitClient *client, const char *action,
					DevkitDevice *device, gpointer user_data)
{
	DkpDaemon *daemon = DKP_DAEMON (user_data);

	if (egg_strequal (action, "add")) {
		egg_debug ("add %s", devkit_device_get_native_path (device));
		gpk_daemon_device_add (daemon, device, TRUE);
	} else if (egg_strequal (action, "remove")) {
		egg_debug ("remove %s", devkit_device_get_native_path (device));
		gpk_daemon_device_remove (daemon, device);
	} else if (egg_strequal (action, "change")) {
		egg_debug ("change %s", devkit_device_get_native_path (device));
		gpk_daemon_device_changed (daemon, device, FALSE);
	} else {
		egg_warning ("unhandled action '%s' on %s", action, devkit_device_get_native_path (device));
	}
}

/**
 * gpk_daemon_register_power_daemon:
 **/
static gboolean
gpk_daemon_register_power_daemon (DkpDaemon *daemon)
{
	DBusConnection *connection;
	DBusError dbus_error;
	GError *error = NULL;
	guint i;

	daemon->priv->pk_context = polkit_context_new ();
	polkit_context_set_io_watch_functions (daemon->priv->pk_context, pk_io_add_watch, pk_io_remove_watch);
	if (!polkit_context_init (daemon->priv->pk_context, NULL)) {
		g_critical ("cannot initialize libpolkit");
		goto error;
	}

	error = NULL;
	daemon->priv->system_bus_connection = dbus_g_bus_get (DBUS_BUS_SYSTEM, &error);
	if (daemon->priv->system_bus_connection == NULL) {
		if (error != NULL) {
			g_critical ("error getting system bus: %s", error->message);
			g_error_free (error);
		}
		goto error;
	}
	connection = dbus_g_connection_get_connection (daemon->priv->system_bus_connection);

	daemon->priv->pk_tracker = polkit_tracker_new ();
	polkit_tracker_set_system_bus_connection (daemon->priv->pk_tracker, connection);
	polkit_tracker_init (daemon->priv->pk_tracker);

	dbus_g_connection_register_g_object (daemon->priv->system_bus_connection,
					     "/org/freedesktop/DeviceKit/Power",
					     G_OBJECT (daemon));

	daemon->priv->system_bus_proxy = dbus_g_proxy_new_for_name (daemon->priv->system_bus_connection,
								      DBUS_SERVICE_DBUS,
								      DBUS_PATH_DBUS,
								      DBUS_INTERFACE_DBUS);

	/* TODO FIXME: I'm pretty sure dbus-glib blows in a way that
	 * we can't say we're interested in all signals from all
	 * members on all interfaces for a given service... So we do
	 * this..
	 */

	dbus_error_init (&dbus_error);

	/* need to listen to NameOwnerChanged */
	dbus_bus_add_match (connection,
			    "type='signal'"
			    ",interface='"DBUS_INTERFACE_DBUS"'"
			    ",sender='"DBUS_SERVICE_DBUS"'"
			    ",member='NameOwnerChanged'",
			    &dbus_error);

	if (dbus_error_is_set (&dbus_error)) {
		egg_warning ("Cannot add match rule: %s: %s", dbus_error.name, dbus_error.message);
		dbus_error_free (&dbus_error);
		goto error;
	}

	/* need to listen to ConsoleKit signals */
	dbus_bus_add_match (connection,
			    "type='signal',sender='org.freedesktop.ConsoleKit'",
			    &dbus_error);

	if (dbus_error_is_set (&dbus_error)) {
		egg_warning ("Cannot add match rule: %s: %s", dbus_error.name, dbus_error.message);
		dbus_error_free (&dbus_error);
		goto error;
	}

	if (!dbus_connection_add_filter (connection,
					 gpk_daemon_dbus_filter,
					 daemon,
					 NULL)) {
		egg_warning ("Cannot add D-Bus filter: %s: %s", dbus_error.name, dbus_error.message);
		goto error;
	}

	/* connect to the DeviceKit daemon */
	for (i=0; subsystems[i] != NULL; i++)
		egg_debug ("registering subsystem : %s", subsystems[i]);
	daemon->priv->devkit_client = devkit_client_new (subsystems);
	if (!devkit_client_connect (daemon->priv->devkit_client, &error)) {
		egg_warning ("Couldn't open connection to DeviceKit daemon: %s", error->message);
		g_error_free (error);
		goto error;
	}
	g_signal_connect (daemon->priv->devkit_client, "device-event",
			  G_CALLBACK (gpk_daemon_device_event_signal_handler), daemon);

	return TRUE;
error:
	return FALSE;
}

/**
 * dkp_daemon_new:
 **/
DkpDaemon *
dkp_daemon_new (void)
{
	DkpDaemon *daemon;
	GError *error = NULL;
	GList *devices;
	GList *l;

	daemon = DKP_DAEMON (g_object_new (DKP_TYPE_DAEMON, NULL));

	daemon->priv->list = dkp_device_list_new ();
	if (!gpk_daemon_register_power_daemon (DKP_DAEMON (daemon))) {
		g_object_unref (daemon);
		return NULL;
	}

	devices = devkit_client_enumerate_by_subsystem (daemon->priv->devkit_client, subsystems, &error);
	if (error != NULL) {
		egg_warning ("Cannot enumerate devices: %s", error->message);
		g_error_free (error);
		g_object_unref (daemon);
		return NULL;
	}

	for (l = devices; l != NULL; l = l->next) {
		DevkitDevice *device = l->data;
		gpk_daemon_device_add (daemon, device, FALSE);
	}
	g_list_foreach (devices, (GFunc) g_object_unref, NULL);
	g_list_free (devices);

	daemon->priv->on_battery = dkp_daemon_get_on_battery_local (daemon);
	daemon->priv->low_battery = dkp_daemon_get_low_battery_local (daemon);

	return daemon;
}

/**
 * dkp_daemon_local_get_caller_for_context:
 **/
PolKitCaller *
dkp_daemon_local_get_caller_for_context (DkpDaemon *daemon, DBusGMethodInvocation *context)
{
	const gchar *sender;
	GError *error;
	DBusError dbus_error;
	PolKitCaller *pk_caller;

	sender = dbus_g_method_get_sender (context);
	dbus_error_init (&dbus_error);
	pk_caller = polkit_tracker_get_caller_from_dbus_name (daemon->priv->pk_tracker,
							      sender,
							      &dbus_error);
	if (pk_caller == NULL) {
		error = g_error_new (DKP_DAEMON_ERROR,
				     DKP_DAEMON_ERROR_GENERAL,
				     "Error getting information about caller: %s: %s",
				     dbus_error.name, dbus_error.message);
		dbus_error_free (&dbus_error);
		dbus_g_method_return_error (context, error);
		g_error_free (error);
		return NULL;
	}

	return pk_caller;
}

/**
 * dkp_daemon_local_check_auth:
 **/
gboolean
dkp_daemon_local_check_auth (DkpDaemon *daemon, PolKitCaller *pk_caller, const char *action_id, DBusGMethodInvocation *context)
{
	gboolean ret = FALSE;
	GError *error;
	DBusError d_error;
	PolKitAction *pk_action;
	PolKitResult pk_result;

	pk_action = polkit_action_new ();
	polkit_action_set_action_id (pk_action, action_id);
	pk_result = polkit_context_is_caller_authorized (daemon->priv->pk_context, pk_action, pk_caller, TRUE, NULL);
	if (pk_result == POLKIT_RESULT_YES) {
		ret = TRUE;
	} else {
		dbus_error_init (&d_error);
		polkit_dbus_error_generate (pk_action, pk_result, &d_error);
		error = NULL;
		dbus_set_g_error (&error, &d_error);
		dbus_g_method_return_error (context, error);
		g_error_free (error);
		dbus_error_free (&d_error);
	}
	polkit_action_unref (pk_action);
	return ret;
}

#if 0
/**
 * gpk_daemon_throw_error:
 **/
static gboolean
gpk_daemon_throw_error (DBusGMethodInvocation *context, int error_code, const char *format, ...)
{
	GError *error;
	va_list args;
	gchar *message;

	va_start (args, format);
	message = g_strdup_vprintf (format, args);
	va_end (args);

	error = g_error_new (DKP_DAEMON_ERROR,
			     error_code,
			     message);
	dbus_g_method_return_error (context, error);
	g_error_free (error);
	g_free (message);
	return TRUE;
}
#endif

/* exported methods */

/**
 * dkp_daemon_enumerate_devices:
 **/
gboolean
dkp_daemon_enumerate_devices (DkpDaemon *daemon, DBusGMethodInvocation *context)
{
	guint i;
	const GPtrArray *array;
	GPtrArray *object_paths;
	DkpDevice *device;

	/* build a pointer array of the object paths */
	object_paths = g_ptr_array_new ();
	array = dkp_device_list_get_array (daemon->priv->list);
	for (i=0; i<array->len; i++) {
		device = (DkpDevice *) g_ptr_array_index (array, i);
		g_ptr_array_add (object_paths, g_strdup (dkp_device_get_object_path (device)));
	}

	/* return it on the bus */
	dbus_g_method_return (context, object_paths);

	/* free */
	g_ptr_array_foreach (object_paths, (GFunc) g_free, NULL);
	g_ptr_array_free (object_paths, TRUE);
	return TRUE;
}

/**
 * dkp_daemon_get_on_battery:
 **/
gboolean
dkp_daemon_get_on_battery (DkpDaemon *daemon, DBusGMethodInvocation *context)
{
	/* this is cached as it's expensive to check all sources */
	dbus_g_method_return (context, daemon->priv->on_battery);
	return TRUE;
}

/**
 * dkp_daemon_get_low_battery:
 **/
gboolean
dkp_daemon_get_low_battery (DkpDaemon *daemon, DBusGMethodInvocation *context)
{
	/* this is cached as it's expensive to check all sources */
	dbus_g_method_return (context, daemon->priv->low_battery);
	return TRUE;
}

/**
 * dkp_daemon_can_suspend:
 *
 * TODO: Ask PolicyKit and check in DeviceKit.conf
 **/
gboolean
dkp_daemon_can_suspend (DkpDaemon *daemon, gboolean interactive, DBusGMethodInvocation *context)
{
	/* for now, assume we can suspend under all circumstances */
	dbus_g_method_return (context, TRUE);
	return TRUE;
}

/**
 * dkp_daemon_can_hibernate:
 *
 * TODO: Ask PolicyKit and check in DeviceKit.conf
 **/
gboolean
dkp_daemon_can_hibernate (DkpDaemon *daemon, gboolean interactive, DBusGMethodInvocation *context)
{
	/* for now, assume we can hibernate under all circumstances */
	dbus_g_method_return (context, TRUE);
	return TRUE;
}

/**
 * dkp_daemon_suspend:
 **/
gboolean
dkp_daemon_suspend (DkpDaemon *daemon, DBusGMethodInvocation *context)
{
	gboolean ret;
	GError *error;
	GError *error_local = NULL;
	PolKitCaller *pk_caller;

	pk_caller = dkp_daemon_local_get_caller_for_context (daemon, context);
	if (pk_caller == NULL)
		goto out;

	if (!dkp_daemon_local_check_auth (daemon, pk_caller, "org.freedesktop.devicekit.power.suspend", context))
		goto out;

	ret = g_spawn_command_line_async ("/usr/sbin/pm-suspend", &error_local);
	if (!ret) {
		error = g_error_new (DKP_DAEMON_ERROR,
				     DKP_DAEMON_ERROR_GENERAL,
				     "Cannot spawn: %s", error_local->message);
		g_error_free (error_local);
		dbus_g_method_return_error (context, error);
		goto out;
	}
	dbus_g_method_return (context, NULL);
out:
	if (pk_caller != NULL)
		polkit_caller_unref (pk_caller);
	return TRUE;
}

/**
 * dkp_daemon_hibernate:
 **/
gboolean
dkp_daemon_hibernate (DkpDaemon *daemon, DBusGMethodInvocation *context)
{
	gboolean ret;
	GError *error;
	GError *error_local = NULL;
	PolKitCaller *pk_caller;

	pk_caller = dkp_daemon_local_get_caller_for_context (daemon, context);
	if (pk_caller == NULL)
		goto out;

	if (!dkp_daemon_local_check_auth (daemon, pk_caller, "org.freedesktop.devicekit.power.hibernate", context))
		goto out;

	ret = g_spawn_command_line_async ("/usr/sbin/pm-hibernate", &error_local);
	if (!ret) {
		error = g_error_new (DKP_DAEMON_ERROR,
				     DKP_DAEMON_ERROR_GENERAL,
				     "Cannot spawn: %s", error_local->message);
		g_error_free (error_local);
		dbus_g_method_return_error (context, error);
		goto out;
	}
	dbus_g_method_return (context, NULL);
out:
	if (pk_caller != NULL)
		polkit_caller_unref (pk_caller);
	return TRUE;
}