summaryrefslogtreecommitdiff
path: root/src/ck-session.c
blob: 8a35044141e1a3b14049172b4cb6655cbcd15146 (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
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
 *
 * Copyright (C) 2006-2007 William Jon McCann <mccann@jhu.edu>
 *
 * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 */

#include "config.h"

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <pwd.h>
#include <sys/ioctl.h>

#ifdef HAVE_SYS_VT_H
#include <sys/vt.h>
#endif

#ifdef HAVE_SYS_KD_H
#include <sys/kd.h>
#endif

#ifdef HAVE_SYS_CONSIO_H
#include <sys/consio.h>
#endif

#ifdef HAVE_SYS_KBIO_H
#include <sys/kbio.h>
#endif

#ifdef HAVE_DEV_WSCONS_WSCONSIO_H
#include <dev/wscons/wsconsio.h>
#endif

#ifdef HAVE_DEV_WSCONS_WSDISPLAY_USL_IO_H
#include <dev/wscons/wsdisplay_usl_io.h>
#endif

#include <glib.h>
#include <glib-unix.h>
#include <glib/gi18n.h>
#include <glib/gstdio.h>
#include <gio/gio.h>
#include <gio/gunixfdlist.h>

#include "ck-tty-idle-monitor.h"
#include "ck-session.h"
#include "ck-seat.h"
#include "ck-marshal.h"
#include "ck-run-programs.h"
#include "ck-sysdeps.h"
#include "ck-device.h"

#define CK_SESSION_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), CK_TYPE_SESSION, CkSessionPrivate))

#define CK_SESSION_DBUS_NAME "org.freedesktop.ConsoleKit.Session"

#define NONULL_STRING(x) ((x) != NULL ? (x) : "")

#define IDLE_TIME_SECS 60

#ifndef KDSKBMUTE
#define KDSKBMUTE 0x4B51
#endif

#ifdef K_OFF
#define KBD_OFF_MODE K_OFF
#else
#define KBD_OFF_MODE K_RAW
#endif

struct CkSessionPrivate
{
        char            *id;
        char            *cookie;
        char            *seat_id;
        char            *runtime_dir;
        char            *login_session_id;

        gchar           *session_controller;
        guint            session_controller_watchid;
        GList           *devices;
        guint            pause_devices_timer;
        gint             tty_fd;
        gint             old_kbd_mode;
        guint            sig_watch_s1;
        guint            sig_watch_s2;

        GTimeVal         creation_time;

        CkTtyIdleMonitor *idle_monitor;

        GTimeVal         idle_since_hint;

        GDBusConnection *connection;
        GDBusProxy      *bus_proxy;
};

enum {
        ACTIVATE,
        LAST_SIGNAL
};

/* Private properties not exported over D-BUS */
enum {
        PROP_0,
        PROP_ID,
        PROP_COOKIE,
        PROP_LOGIN_SESSION_ID,
        PROP_SESSION_CONTROLLER,
};

static guint signals [LAST_SIGNAL] = { 0, };

static void     ck_session_iface_init           (ConsoleKitSessionIface *iface);
static void     ck_session_finalize             (GObject                *object);
static void     ck_session_remove_all_devices   (CkSession              *session);


G_DEFINE_TYPE_WITH_CODE (CkSession, ck_session, CONSOLE_KIT_TYPE_SESSION_SKELETON, G_IMPLEMENT_INTERFACE (CONSOLE_KIT_TYPE_SESSION, ck_session_iface_init));

static const GDBusErrorEntry ck_session_error_entries[] =
{
        { CK_SESSION_ERROR_FAILED,                  CK_SESSION_DBUS_NAME ".Error.Failed" },
        { CK_SESSION_ERROR_GENERAL,                 CK_SESSION_DBUS_NAME ".Error.General" },
        { CK_SESSION_ERROR_INSUFFICIENT_PERMISSION, CK_SESSION_DBUS_NAME ".Error.InsufficientPermission" },
        { CK_SESSION_ERROR_NOT_SUPPORTED,           CK_SESSION_DBUS_NAME ".Error.NotSupported" },
        { CK_SESSION_ERROR_ALREADY_ACTIVE,          CK_SESSION_DBUS_NAME ".Error.AlreadyActive" }
};

GQuark
ck_session_error_quark (void)
{
        static volatile gsize quark_volatile = 0;

        g_dbus_error_register_error_domain ("ck_session_error",
                                            &quark_volatile,
                                            ck_session_error_entries,
                                            G_N_ELEMENTS (ck_session_error_entries));

        return (GQuark) quark_volatile;
}
#define ENUM_ENTRY(NAME, DESC) { NAME, "" #NAME "", DESC }

GType
ck_session_error_get_type (void)
{
  static GType etype = 0;

  if (etype == 0)
    {
      static const GEnumValue values[] =
        {
          ENUM_ENTRY (CK_SESSION_ERROR_FAILED,                  "Failed"),
          ENUM_ENTRY (CK_SESSION_ERROR_GENERAL,                 "General"),
          ENUM_ENTRY (CK_SESSION_ERROR_INSUFFICIENT_PERMISSION, "InsufficientPermission"),
          ENUM_ENTRY (CK_SESSION_ERROR_NOT_SUPPORTED,           "NotSupported"),
          ENUM_ENTRY (CK_SESSION_ERROR_ALREADY_ACTIVE,          "AlreadyActive"),
          { 0, 0, 0 }
        };
      g_assert (CK_SESSION_NUM_ERRORS == G_N_ELEMENTS (values) - 1);
      etype = g_enum_register_static ("Error", values);
    }
  return etype;
}

static void
throw_error (GDBusMethodInvocation *context,
             gint                   error_code,
             const gchar           *format,
             ...)
{
        va_list args;
        gchar *message;

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

        g_debug ("session: throwing error: %s", message);

        g_dbus_method_invocation_return_error (context, CK_SESSION_ERROR, error_code, "%s", message);

        g_free (message);
}

static gboolean
register_session (CkSession *session, GDBusConnection *connection)
{
        GError *error = NULL;

        g_debug ("register session");

        error = NULL;

        if (connection == NULL) {
                g_critical ("CkSession-register_session:connection == NULL");
        } else {
                session->priv->connection = connection;
        }


        if (session->priv->connection == NULL) {
                if (error != NULL) {
                        g_critical ("error getting system bus: %s", error->message);
                        g_error_free (error);
                }
                return FALSE;
        }

        g_debug ("exporting path %s", session->priv->id);

        if (!g_dbus_interface_skeleton_export (G_DBUS_INTERFACE_SKELETON (CONSOLE_KIT_SESSION (session)),
                                               session->priv->connection,
                                               session->priv->id,
                                               &error)) {
                if (error != NULL) {
                        g_critical ("error exporting interface: %s", error->message);
                        g_error_free (error);
                        return FALSE;
                }
        }

        g_debug ("exported on %s", g_dbus_interface_skeleton_get_object_path (G_DBUS_INTERFACE_SKELETON (CONSOLE_KIT_SESSION (session))));

        /* connect to DBus for get_caller_info */
        session->priv->bus_proxy = g_dbus_proxy_new_sync (session->priv->connection,
                                                          G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES |
                                                          G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS,
                                                          NULL,
                                                          "org.freedesktop.DBus",
                                                          "/org/freedesktop/DBus/Bus",
                                                          "org.freedesktop.DBus",
                                                          NULL,
                                                          &error);
        if (session->priv->bus_proxy == NULL) {
                g_warning ("cannot connect to DBus: %s", error->message);
                g_error_free (error);
        }

        /* default to unspecified for the session type on startup */
        if (console_kit_session_get_session_type (CONSOLE_KIT_SESSION (session)) == NULL) {
                console_kit_session_set_session_type (CONSOLE_KIT_SESSION (session), "unspecified");
        }

        /* default to user for the session class on startup */
        if (console_kit_session_get_session_class (CONSOLE_KIT_SESSION (session)) == NULL) {
                console_kit_session_set_session_class (CONSOLE_KIT_SESSION (session), "user");
        }

        /* default to online for the session state on startup */
        if (console_kit_session_get_session_class (CONSOLE_KIT_SESSION (session)) == NULL) {
                console_kit_session_set_session_class (CONSOLE_KIT_SESSION (session), "online");
        }

        return TRUE;
}

/*
  lock and unlock are separate functions because we may want
  security policy to be handled separately
*/
void
ck_session_lock (CkSession *session)
{
        ConsoleKitSession     *cksession;

        TRACE ();

        g_return_if_fail (CK_IS_SESSION (session));

        cksession = CONSOLE_KIT_SESSION (session);

        g_debug ("Emitting lock for session %s", session->priv->id);
        console_kit_session_set_locked_hint (cksession, TRUE);
        console_kit_session_emit_lock (cksession);
}

void
ck_session_unlock (CkSession *session)
{
        ConsoleKitSession     *cksession;

        TRACE ();

        g_return_if_fail (CK_IS_SESSION (session));

        cksession = CONSOLE_KIT_SESSION (session);

        g_debug ("Emitting unlock for session %s", session->priv->id);
        console_kit_session_set_locked_hint (cksession, FALSE);
        console_kit_session_emit_unlock (cksession);
}

static gboolean
dbus_lock (ConsoleKitSession     *cksession,
           GDBusMethodInvocation *context)
{
        TRACE ();

        ck_session_lock (CK_SESSION (cksession));

        console_kit_session_complete_lock (cksession, context);
        return TRUE;
}

static gboolean
dbus_unlock (ConsoleKitSession     *cksession,
             GDBusMethodInvocation *context)
{
        TRACE ();

        ck_session_unlock (CK_SESSION (cksession));

        console_kit_session_complete_unlock (cksession, context);
        return TRUE;
}

/* adapted from PolicyKit */
static gboolean
get_caller_info (CkSession   *session,
                 const char  *sender,
                 uid_t       *calling_uid,
                 pid_t       *calling_pid)
{
        gboolean  res   = FALSE;
        GVariant *value = NULL;
        GError   *error = NULL;

        if (sender == NULL) {
                goto out;
        }

        value = g_dbus_proxy_call_sync (session->priv->bus_proxy, "GetConnectionUnixUser",
                                        g_variant_new ("(s)", sender),
                                        G_DBUS_CALL_FLAGS_NONE,
                                        2000,
                                        NULL,
                                        &error);

        if (value == NULL) {
                g_warning ("GetConnectionUnixUser() failed: %s", error->message);
                g_error_free (error);
                goto out;
        }
        g_variant_get (value, "(u)", calling_uid);
        g_variant_unref (value);

        value = g_dbus_proxy_call_sync (session->priv->bus_proxy, "GetConnectionUnixProcessID",
                                        g_variant_new ("(s)", sender),
                                        G_DBUS_CALL_FLAGS_NONE,
                                        2000,
                                        NULL,
                                        &error);

        if (value == NULL) {
                g_warning ("GetConnectionUnixProcessID() failed: %s", error->message);
                g_error_free (error);
                goto out;
        }
        g_variant_get (value, "(u)", calling_pid);
        g_variant_unref (value);

        res = TRUE;

        g_debug ("uid = %d", *calling_uid);
        g_debug ("pid = %d", *calling_pid);

out:
        return res;
}

static gboolean
session_set_idle_hint_internal (CkSession      *session,
                                gboolean        idle_hint)
{
        ConsoleKitSession *cksession = CONSOLE_KIT_SESSION (session);

        if (console_kit_session_get_idle_hint (cksession) != idle_hint) {
                console_kit_session_set_idle_hint (cksession, idle_hint);

                /* FIXME: can we get a time from the dbus message? */
                g_get_current_time (&session->priv->idle_since_hint);

                g_debug ("Emitting idle-changed for session %s", session->priv->id);
                console_kit_session_emit_idle_hint_changed (cksession, idle_hint);
        }

        return TRUE;
}

static gboolean
dbus_get_idle_since_hint (ConsoleKitSession     *cksession,
                          GDBusMethodInvocation *context)
{
        CkSession *session = CK_SESSION(cksession);
        char *date_str;

        TRACE ();

        g_return_val_if_fail (CK_IS_SESSION (cksession), FALSE);

        if (console_kit_session_get_idle_hint (cksession) == FALSE) {
                throw_error (context, CK_SESSION_ERROR_GENERAL, "idle since hint not set");
                return TRUE;
        }

        date_str = g_time_val_to_iso8601 (&session->priv->idle_since_hint);

        console_kit_session_complete_get_idle_since_hint (cksession, context, date_str);

        g_free (date_str);
        return TRUE;
}

static gboolean
dbus_get_idle_hint (ConsoleKitSession *cksession,
                    GDBusMethodInvocation *context)
{
        TRACE ();
        console_kit_session_complete_get_idle_hint (cksession, context, console_kit_session_get_idle_hint (cksession));
        return TRUE;
}

/*
  Example:
  dbus-send --system --dest=org.freedesktop.ConsoleKit \
  --type=method_call --print-reply --reply-timeout=2000 \
  /org/freedesktop/ConsoleKit/Session1 \
  org.freedesktop.ConsoleKit.Session.SetIdleHint boolean:TRUE
*/
static gboolean
dbus_set_idle_hint (ConsoleKitSession     *cksession,
                    GDBusMethodInvocation *context,
                    gboolean               idle_hint)
{
        const char *sender;
        uid_t       calling_uid = 0;
        pid_t       calling_pid = 0;
        gboolean    res;
        CkSession *session;

        TRACE ();

        g_return_val_if_fail (CK_IS_SESSION (cksession), FALSE);

        session = CK_SESSION(cksession);

        sender = g_dbus_method_invocation_get_sender (context);

        res = get_caller_info (session,
                               sender,
                               &calling_uid,
                               &calling_pid);

        if (! res) {
                g_warning ("stat on pid %d failed", calling_pid);
                throw_error (context, CK_SESSION_ERROR_FAILED, _("Unable to lookup information about calling process '%d'"), calling_pid);
                return TRUE;
        }

        /* only restrict this by UID for now */
        if (console_kit_session_get_unix_user (cksession) != calling_uid) {
                throw_error (context, CK_SESSION_ERROR_INSUFFICIENT_PERMISSION, _("Only session owner may set idle hint state"));
                return TRUE;
        }

        session_set_idle_hint_internal (session, idle_hint);

        console_kit_session_complete_set_idle_hint (cksession, context);
        return TRUE;
}

/*
  Example:
  dbus-send --system --dest=org.freedesktop.ConsoleKit \
  --type=method_call --print-reply --reply-timeout=2000 \
  /org/freedesktop/ConsoleKit/Session1 \
  org.freedesktop.ConsoleKit.Session.SetLockedHint boolean:TRUE
*/
static gboolean
dbus_set_locked_hint (ConsoleKitSession     *cksession,
                      GDBusMethodInvocation *context,
                      gboolean               arg_locked_hint)
{
        const char *sender;
        uid_t       calling_uid = 0;
        pid_t       calling_pid = 0;
        gboolean    res;
        CkSession *session;

        TRACE ();

        g_return_val_if_fail (CK_IS_SESSION (cksession), FALSE);

        session = CK_SESSION(cksession);

        sender = g_dbus_method_invocation_get_sender (context);

        res = get_caller_info (session,
                               sender,
                               &calling_uid,
                               &calling_pid);

        if (! res) {
                g_warning ("stat on pid %d failed", calling_pid);
                throw_error (context, CK_SESSION_ERROR_FAILED, _("Unable to lookup information about calling process '%d'"), calling_pid);
                return TRUE;
        }

        /* only restrict this by UID for now */
        if (console_kit_session_get_unix_user (cksession) != calling_uid) {
                throw_error (context, CK_SESSION_ERROR_INSUFFICIENT_PERMISSION, _("Only session owner may set locked hint state"));
                return TRUE;
        }

        console_kit_session_set_locked_hint (cksession, arg_locked_hint);

        console_kit_session_complete_set_idle_hint (cksession, context);
        return TRUE;
}

static gboolean
dbus_get_session_type (ConsoleKitSession     *cksession,
                       GDBusMethodInvocation *context)
{
        const gchar *session_type = console_kit_session_get_session_type (cksession);

        TRACE ();

        if (session_type == NULL) {
                /* default to unspecified */
                session_type = "unspecified";
        }

        console_kit_session_complete_get_session_type (cksession, context, session_type);
        return TRUE;
}

static gboolean
dbus_get_session_class (ConsoleKitSession     *cksession,
                        GDBusMethodInvocation *context)
{
        const gchar *session_class = console_kit_session_get_session_class (cksession);

        TRACE ();

        if (session_class == NULL) {
                /* default to user */
                session_class = "user";
        }

        console_kit_session_complete_get_session_class (cksession, context, session_class);
        return TRUE;
}

static gboolean
dbus_get_session_state (ConsoleKitSession     *cksession,
                        GDBusMethodInvocation *context)
{
        const gchar *state = console_kit_session_get_session_state (cksession);

        TRACE ();

        if (state == NULL) {
                /* default to online, but this shouldn't really happen */
                state = "online";
        }

        console_kit_session_complete_get_session_state (cksession, context, state);
        return TRUE;
}

static void
ck_session_print_list_size (CkSession *session)
{
#if defined(CONSOLEKIT_DEBUGGING)
        g_debug ("session %s list size is %d",
                 session->priv->id,
                 g_list_length (session->priv->devices));
#endif
}

static void
ck_session_check_paused_devices (CkSession *session)
{
        ConsoleKitSession *cksession = CONSOLE_KIT_SESSION (session);
        GList             *itr;

        TRACE ();

        ck_session_print_list_size (session);

        /* See if we've paused all the devices in the session */
        for (itr = session->priv->devices; itr != NULL; itr = g_list_next (itr)) {
                CkDevice *device = CK_DEVICE (itr->data);
                if (ck_device_get_active (device)) {
                        return;
                }
        }

        /* If we didn't force the state change, do it now */
        if (console_kit_session_get_active (cksession) != FALSE) {
                g_debug ("marking session %s inactive", session->priv->id);

                console_kit_session_set_active (cksession, FALSE);
                console_kit_session_emit_active_changed (cksession, FALSE);
                console_kit_session_set_session_state (cksession, "online");
        }

        if (session->priv->pause_devices_timer != 0) {
                g_source_remove (session->priv->pause_devices_timer);
                session->priv->pause_devices_timer = 0;
        }
}

static gboolean
force_pause_devices (CkSession *session)
{
        GList *itr;

        TRACE ();

        ck_session_print_list_size (session);

        for (itr = session->priv->devices; itr != NULL; itr = g_list_next (itr))
        {
                ck_device_set_active (CK_DEVICE (itr->data), FALSE);
        }

        session->priv->pause_devices_timer = 0;

        ck_session_check_paused_devices (session);

        return FALSE;
}

static void
ck_session_pause_all_devices (CkSession *session,
                              gboolean   force)
{
        ConsoleKitSession *cksession = CONSOLE_KIT_SESSION (session);
        GList             *itr;

        TRACE ();

        ck_session_print_list_size (session);

        for (itr = session->priv->devices; itr != NULL; itr = g_list_next (itr))
        {
                CkDevice *device = CK_DEVICE (itr->data);

                if (ck_device_get_active (device) == FALSE) {
                        g_debug ("device already paused");
                        continue;
                }

                /* Let the session controller know about the change */
                g_debug ("emit pause device for %d, %d, type %s",
                         ck_device_get_major (device),
                         ck_device_get_minor (device),
                         force ? "force" : "pause");

                console_kit_session_emit_pause_device (CONSOLE_KIT_SESSION (session),
                                                       ck_device_get_major (device),
                                                       ck_device_get_minor (device),
                                                       force ? "force" : "pause");

                if (force) {
                        ck_device_set_active (device, FALSE);
                }
        }

        if (force || session->priv->devices == NULL) {
                g_debug ("marking session %s inactive", session->priv->id);

                console_kit_session_set_active (cksession, FALSE);
                console_kit_session_emit_active_changed (cksession, FALSE);
                console_kit_session_set_session_state (cksession, "online");
        } else {
                session->priv->pause_devices_timer = g_timeout_add_seconds (3, (GSourceFunc)force_pause_devices, session);
        }
}

static void
ck_session_debug_print_dbus_message (CkSession    *session,
                                     GDBusMessage *message)
{
#if defined(CONSOLEKIT_DEBUGGING)
        gchar  *string = g_dbus_message_print (message, 4);
        gchar **split_string = g_strsplit (string, "\n", 0);
        gint    i;

        for (i = 0; split_string != NULL && split_string[i] != NULL; i++) {
                g_debug ("%s", split_string[i]);
        }

        g_strfreev (split_string);
        g_free (string);
#endif
}

static void
ck_session_resume_all_devices (CkSession *session)
{
        ConsoleKitSession *cksession = CONSOLE_KIT_SESSION (session);
        GList             *itr;
        gint               vtnr;

        TRACE ();

        vtnr = console_kit_session_get_vtnr (cksession);

        /* Give ownership of the active console device to the user */
        if (vtnr > 0) {
                struct passwd *pwent;
                gint           fd;
                gint           uid;

                uid = console_kit_session_get_unix_user (cksession);

                fd = ck_open_a_console (ck_get_console_device_for_num (vtnr));
                if (fd >= 0) {
                        errno = 0;
                        pwent = getpwuid (uid);
                        if (pwent == NULL) {
                                g_warning ("Unable to lookup UID: %s", g_strerror (errno));
                                errno = 0;
                        } else {
                                if (fchown (fd, uid, pwent->pw_gid) != 0) {
                                        g_warning ("Failed to chown console device, reason was: %s", strerror(errno));
                                        errno = 0;
                                }
                        }

                        g_close (fd, NULL);
                }
        }

        /* without a controller, we just mark ourselved active */
        if (session->priv->session_controller == NULL) {
                g_debug ("no session controller: marking session active");
                console_kit_session_set_active (cksession, TRUE);
                console_kit_session_emit_active_changed (cksession, TRUE);
                console_kit_session_set_session_state (cksession, "active");
                return;
        }

        ck_session_print_list_size (session);

        for (itr = session->priv->devices; itr != NULL; itr = g_list_next (itr))
        {
                CkDevice     *device = CK_DEVICE (itr->data);
                GVariant     *body;
                GDBusMessage *message;
                GUnixFDList  *out_fd_list = NULL;
                gint          fd = -1;
                gint          fd2 = -1;

                ck_device_set_active (device, TRUE);

                fd = ck_device_get_fd (device);

                if (fd < 0) {
                        g_debug ("Unable to signal ResumeDevice, failed to get device");
                        continue;
                }

                message = g_dbus_message_new_signal (session->priv->id,
                                                     CK_SESSION_DBUS_NAME,
                                                     "ResumeDevice");

                /* We always send to the session controller */
                g_dbus_message_set_destination (message, session->priv->session_controller);

                body = g_variant_new ("(uu@h)",
                                      ck_device_get_major (device),
                                      ck_device_get_minor (device),
                                      g_variant_new_handle (0));

                g_dbus_message_set_body (message, body);

                /* we need to copy this, because gdbus closes the fd on us */
                fd2 = dup (fd);
                out_fd_list = g_unix_fd_list_new_from_array (&fd2, 1);
                g_dbus_message_set_unix_fd_list (message, out_fd_list);

                g_debug ("sending ResumeDevice signal to session controller");

                ck_session_debug_print_dbus_message (session, message);

                /* Let only the session controller know about the change and
                 * give them the new fd. */
                g_dbus_connection_send_message (session->priv->connection,
                                                message,
                                                G_DBUS_SEND_MESSAGE_FLAGS_NONE,
                                                NULL,
                                                NULL);

                g_clear_object (&out_fd_list);
                g_clear_object (&message);
        }

        g_debug ("marking session active");
        console_kit_session_set_active (cksession, TRUE);
        console_kit_session_emit_active_changed (cksession, TRUE);
        console_kit_session_set_session_state (cksession, "active");
}

gboolean
ck_session_set_active (CkSession *session,
                       gboolean   active,
                       gboolean   force)
{
        ConsoleKitSession *cksession;

        TRACE ();

        g_return_val_if_fail (CK_IS_SESSION (session), FALSE);

        cksession = CONSOLE_KIT_SESSION (session);

        if (console_kit_session_get_active (cksession) == active) {
                /* redundant call, we shouldn't need to do anything */
                return TRUE;
        }


        if (session->priv->pause_devices_timer != 0) {
                g_source_remove (session->priv->pause_devices_timer);
                session->priv->pause_devices_timer = 0;
        }

        g_debug ("ck_session_set_active: session %s changing to %s, forced? %s",
                 session->priv->id,
                 active ? "active" : "not active",
                 force ? "yes" : "no");

        /* We handle device events then change the active state */
        if (active == FALSE) {
                ck_session_pause_all_devices (session, force);
        } else {
                ck_session_resume_all_devices (session);
        }

        return TRUE;
}

static gboolean
dbus_is_active (ConsoleKitSession     *cksession,
                GDBusMethodInvocation *context)
{
        TRACE ();
        console_kit_session_complete_is_active (cksession, context, console_kit_session_get_active (cksession));
        return TRUE;
}

static gboolean
dbus_activate (ConsoleKitSession     *cksession,
               GDBusMethodInvocation *context)
{
        GError    *error   = NULL;
        GError    *initial_error;
        CkSession *session = CK_SESSION (cksession);

        TRACE ();

        g_return_val_if_fail (session, FALSE);

        /* Set an initial error message in the event the signal isn't handeled */
        g_set_error (&error, CK_SESSION_ERROR, CK_SESSION_ERROR_NOT_SUPPORTED,
                     _("Activate signal not handeled. Session not attached to seat, or the seat doesn't support activation changes"));

        /* keep track of the starting error because the call to g_signal_emit
         * may change it and we still need to free it */
        initial_error = error;

        g_signal_emit (session, signals [ACTIVATE], 0, context, &error);
        if (error != NULL) {
                /* if the signal is not handled then either:
                   a) aren't attached to seat
                   b) seat doesn't support activation changes */
                g_debug ("Got error message: %s", error->message);

                /* translate and throw the error */
                switch (error->code) {
                case CK_SEAT_ERROR_ALREADY_ACTIVE:
                        /* Don't care */
                        break;
                case CK_SEAT_ERROR_NOT_SUPPORTED:
                        throw_error (context, CK_SESSION_ERROR_NOT_SUPPORTED, error->message);
                        break;
                default:
                        throw_error (context, CK_SESSION_ERROR_GENERAL, error->message);
                }

                g_clear_error (&error);
                g_clear_error (&initial_error);
                return TRUE;
        }

        g_clear_error (&initial_error);

        console_kit_session_complete_activate (cksession, context);
        return TRUE;
}

static gboolean
dbus_get_id (ConsoleKitSession     *cksession,
             GDBusMethodInvocation *context)
{
        CkSession *session = CK_SESSION (cksession);
        gchar     *id;

        TRACE ();

        g_return_val_if_fail (CK_IS_SESSION (session), FALSE);

        id = session->priv->id;

        if (id == NULL) {
                id = "";
        }

        console_kit_session_complete_get_id (cksession, context, session->priv->id);
        return TRUE;
}

gboolean
ck_session_get_id (CkSession *session,
                   char **id,
                   GError **error)
{
        g_return_val_if_fail (CK_IS_SESSION (session), FALSE);

        if (id != NULL) {
                *id = g_strdup (session->priv->id);
        }

        return TRUE;
}

static gboolean
dbus_get_seat_id (ConsoleKitSession     *cksession,
                  GDBusMethodInvocation *context)
{
        CkSession *session = CK_SESSION (cksession);
        const gchar *seat_id;

        TRACE ();

        g_return_val_if_fail (CK_IS_SESSION (session), FALSE);

        seat_id = session->priv->seat_id;
        if (seat_id == NULL) {
                throw_error (context, CK_SESSION_ERROR_FAILED, "session not attached to a seat");
                return TRUE;
        }

        console_kit_session_complete_get_seat_id (cksession, context, session->priv->seat_id);
        return TRUE;
}

gboolean
ck_session_get_seat_id (CkSession      *session,
                        char          **id,
                        GError        **error)
{
        g_return_val_if_fail (CK_IS_SESSION (session), FALSE);

        if (id != NULL) {
                *id = g_strdup (session->priv->seat_id);
        }

        return TRUE;
}

static gboolean
dbus_get_user (ConsoleKitSession     *cksession,
               GDBusMethodInvocation *context)
{
        TRACE ();
        console_kit_session_complete_get_unix_user (cksession, context, console_kit_session_get_unix_user (cksession));
        return TRUE;
}

static gboolean
dbus_get_unix_user (ConsoleKitSession     *cksession,
                    GDBusMethodInvocation *context)
{
        TRACE ();
        console_kit_session_complete_get_unix_user (cksession, context, console_kit_session_get_unix_user (cksession));
        return TRUE;
}

gboolean
ck_session_set_unix_user (CkSession      *session,
                          guint           uid,
                          GError        **error)
{
        g_return_val_if_fail (CK_IS_SESSION (session), FALSE);

        console_kit_session_set_unix_user (CONSOLE_KIT_SESSION (session), uid);

        return TRUE;
}

static gboolean
dbus_get_x11_display (ConsoleKitSession     *cksession,
                      GDBusMethodInvocation *context)
{
        const gchar *x11_display;

        TRACE ();

        x11_display = console_kit_session_get_x11_display (cksession);

        if (x11_display == NULL) {
                x11_display = "";
        }

        console_kit_session_complete_get_x11_display (cksession, context, x11_display);
        return TRUE;
}

gboolean
ck_session_set_x11_display (CkSession      *session,
                            const char     *x11_display,
                            GError        **error)
{
        g_return_val_if_fail (CK_IS_SESSION (session), FALSE);

        console_kit_session_set_x11_display (CONSOLE_KIT_SESSION (session), x11_display);

        return TRUE;
}

static gboolean
dbus_get_display_device (ConsoleKitSession     *cksession,
                             GDBusMethodInvocation *context)
{
        const gchar *display_device;
        TRACE ();

        display_device = console_kit_session_get_display_device (cksession);

        if (display_device == NULL) {
                display_device = "";
        }

        console_kit_session_complete_get_x11_display_device (cksession, context, display_device);
        return TRUE;
}

gboolean
ck_session_set_display_device (CkSession      *session,
                               const char     *display_device,
                               GError        **error)
{
        ConsoleKitSession *cksession;

        g_return_val_if_fail (CK_IS_SESSION (session), FALSE);

        cksession = CONSOLE_KIT_SESSION (session);

        console_kit_session_set_display_device (cksession, display_device);

        return TRUE;
}

static gboolean
dbus_get_x11_display_device (ConsoleKitSession     *cksession,
                             GDBusMethodInvocation *context)
{
        const gchar *x11_display_device;

        TRACE ();

        x11_display_device = console_kit_session_get_x11_display_device (cksession);

        if (x11_display_device == NULL) {
                x11_display_device = "";
        }

        console_kit_session_complete_get_x11_display_device (cksession, context, x11_display_device);
        return TRUE;
}

gboolean
ck_session_set_x11_display_device (CkSession      *session,
                                   const char     *x11_display_device,
                                   GError        **error)
{
        ConsoleKitSession *cksession;

        g_return_val_if_fail (CK_IS_SESSION (session), FALSE);

        cksession = CONSOLE_KIT_SESSION (session);

        console_kit_session_set_x11_display_device (cksession, x11_display_device);

        return TRUE;
}

static gboolean
dbus_get_remote_host_name (ConsoleKitSession     *cksession,
                           GDBusMethodInvocation *context)
{
        const gchar *remote_host_name = console_kit_session_get_remote_host_name (cksession);

        TRACE ();

        if (remote_host_name == NULL) {
                remote_host_name = "";
        }

        console_kit_session_complete_get_remote_host_name (cksession, context, remote_host_name);
        return TRUE;
}

gboolean
ck_session_set_remote_host_name (CkSession      *session,
                                 const char     *remote_host_name,
                                 GError        **error)
{
        ConsoleKitSession *cksession;

        g_return_val_if_fail (CK_IS_SESSION (session), FALSE);

        cksession = CONSOLE_KIT_SESSION (session);

        console_kit_session_set_remote_host_name (cksession, remote_host_name);

        return TRUE;
}

static gboolean
dbus_get_creation_time (ConsoleKitSession     *cksession,
                        GDBusMethodInvocation *context)
{
        CkSession *session = CK_SESSION(cksession);

        TRACE ();

        g_return_val_if_fail (CK_IS_SESSION (cksession), FALSE);

        console_kit_session_complete_get_creation_time (cksession, context, g_time_val_to_iso8601 (&session->priv->creation_time));
        return TRUE;
}

gboolean
ck_session_get_creation_time (CkSession      *session,
                              char          **iso8601_datetime,
                              GError        **error)
{
        g_return_val_if_fail (CK_IS_SESSION (session), FALSE);

        if (iso8601_datetime != NULL) {
                *iso8601_datetime = g_time_val_to_iso8601 (&session->priv->creation_time);
        }

        return TRUE;
}

static gboolean
dbus_is_local (ConsoleKitSession     *cksession,
               GDBusMethodInvocation *context)
{
        TRACE ();
        console_kit_session_complete_is_local (cksession, context, console_kit_session_get_is_local (cksession));
        return TRUE;
}

gboolean
ck_session_set_is_local (CkSession      *session,
                         gboolean        is_local,
                         GError        **error)
{
        g_return_val_if_fail (CK_IS_SESSION (session), FALSE);

        console_kit_session_set_is_local (CONSOLE_KIT_SESSION (session), is_local);

        return TRUE;
}

gboolean
ck_session_is_local (CkSession *session,
                     gboolean *local,
                     GError **error)
{
        g_return_val_if_fail (CK_IS_SESSION (session), FALSE);

        if (local != NULL) {
                *local = console_kit_session_get_is_local (CONSOLE_KIT_SESSION (session));
        }

        return TRUE;
}

gboolean
ck_session_set_id (CkSession      *session,
                   const char     *id,
                   GError        **error)
{
        g_return_val_if_fail (CK_IS_SESSION (session), FALSE);

        g_free (session->priv->id);
        session->priv->id = g_strdup (id);

        return TRUE;
}

gboolean
ck_session_set_cookie (CkSession      *session,
                       const char     *cookie,
                       GError        **error)
{
        g_return_val_if_fail (CK_IS_SESSION (session), FALSE);

        g_free (session->priv->cookie);
        session->priv->cookie = g_strdup (cookie);

        return TRUE;
}

gboolean
ck_session_set_seat_id (CkSession      *session,
                        const char     *id,
                        GError        **error)
{
        GVariant *seat = NULL;
        gchar **seat_split;

        g_return_val_if_fail (CK_IS_SESSION (session), FALSE);

        g_free (session->priv->seat_id);
        session->priv->seat_id = g_strdup (id);

        if (id != NULL) {
                /* we need to remove the prefix from the first seat_id returned */
                seat_split = g_strsplit (id, "/org/freedesktop/ConsoleKit/", 2);

                if (seat_split[0] == NULL) {
                        g_critical ("id %s is invalid or g_strsplit has changed", id);
                        return FALSE;
                }

                seat = g_variant_new ("(so)", seat_split[1], id);
                g_strfreev (seat_split);
        }

        console_kit_session_set_seat (CONSOLE_KIT_SESSION (session), seat);
        return TRUE;
}

/**
 * ck_session_set_runtime_dir
 * @session: CkSession object
 * @runtime_dir: The XDG_RUNTIME_DIR for the user of this session. For details, see:
 *  http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
 * returns: TRUE if successfully set, FALSE on failure.
 **/
gboolean
ck_session_set_runtime_dir (CkSession      *session,
                            const char     *runtime_dir)
{
        g_return_val_if_fail (CK_IS_SESSION (session), FALSE);

        g_free (session->priv->runtime_dir);
        session->priv->runtime_dir = g_strdup (runtime_dir);

        return TRUE;
}

/**
 * ck_session_get_runtime_dir
 * @session: CkSession object
 * returns: The XDG_RUNTIME_DIR. For details, see:
 *  http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
 **/
const char *
ck_session_get_runtime_dir (CkSession *session)
{
        g_return_val_if_fail (CK_IS_SESSION (session), NULL);
        return session->priv->runtime_dir;
}

static gboolean
dbus_get_runtime_dir (ConsoleKitSession     *cksession,
                      GDBusMethodInvocation *context)
{
        CkSession   *session = CK_SESSION(cksession);

        TRACE ();

        g_return_val_if_fail (CK_IS_SESSION (cksession), FALSE);

        /* if no login session id is set return an empty string */
        if (session->priv->runtime_dir == NULL) {
            throw_error (context, CK_SESSION_ERROR_FAILED, _("Failed to create the XDG_RUNTIME_DIR"));
            return TRUE;
        }

        console_kit_session_complete_get_xdgruntime_dir (cksession, context, session->priv->runtime_dir);
        return TRUE;
}

static gboolean
dbus_get_login_session_id (ConsoleKitSession     *cksession,
                           GDBusMethodInvocation *context)
{
        CkSession *session = CK_SESSION(cksession);
        const gchar *login_session_id;

        TRACE ();

        g_return_val_if_fail (CK_IS_SESSION (cksession), FALSE);

        login_session_id = session->priv->login_session_id;

        /* if no login session id is set return an empty string */
        if (login_session_id == NULL) {
            login_session_id = "";
        }

        console_kit_session_complete_get_login_session_id (cksession, context, login_session_id);
        return TRUE;
}

static gboolean
dbus_get_vtnr (ConsoleKitSession     *cksession,
               GDBusMethodInvocation *context)
{
        TRACE ();

        console_kit_session_complete_get_vtnr (cksession, context, console_kit_session_get_vtnr (cksession));
        return TRUE;
}

gboolean
ck_session_set_login_session_id (CkSession      *session,
                                 const char     *login_session_id,
                                 GError        **error)
{
        g_return_val_if_fail (CK_IS_SESSION (session), FALSE);

        g_free (session->priv->login_session_id);
        session->priv->login_session_id = g_strdup (login_session_id);

        return TRUE;
}

gboolean
ck_session_set_session_type (CkSession      *session,
                             const char     *type,
                             GError        **error)
{
        ConsoleKitSession *cksession = CONSOLE_KIT_SESSION (session);

        g_return_val_if_fail (CK_IS_SESSION (session), FALSE);

        console_kit_session_set_session_type (cksession, type);

        return TRUE;
}

static gboolean
vt_leave_handler (gpointer data)
{
        CkSession *session = CK_SESSION (data);

        TRACE ();

        /* g_unix_signal_add_full returns this callback in the GMainContext
         * so we don't have the limitations of POSIX signal handlers */

        /* Forcably disable all devices, we have to do this
         * now or we'll crash Xorg if it's running as root on
         * the new VT */
        ck_session_pause_all_devices (session, TRUE);

        /* release control */
#if defined(VT_RELDISP)
        ioctl (session->priv->tty_fd, VT_RELDISP, 1);
#endif

        return TRUE;
}

static gboolean
vt_acquire_handler (gpointer data)
{
        CkSession *session = CK_SESSION (data);

        TRACE ();

        /* g_unix_signal_add_full returns this callback in the GMainContext
         * so we don't have the limitations of POSIX signal handlers */

        /* ack that we are getting control, but let the normal
         * process handle granting access */
#if defined(VT_RELDISP)
        ioctl (session->priv->tty_fd, VT_RELDISP, VT_ACKACQ);
#endif

        return TRUE;
}

static void
ck_session_setup_vt_signal (CkSession *session,
                            guint      vtnr)
{
#if defined(KDGKBMODE) && defined(KDSETMODE) && defined(KD_GRAPHICS)
        struct vt_mode mode = { 0 };
        int    graphical_mode = KD_TEXT;

        session->priv->tty_fd = ck_open_a_console (ck_get_console_device_for_num (vtnr));

        if (session->priv->tty_fd < 0) {
                return;
        }

        ioctl(session->priv->tty_fd, KDGKBMODE, &session->priv->old_kbd_mode);

        /* So during setup here, we need to ensure we're in graphical mode,
         * otherwise it will try to draw stuff in the background */
#if defined(KDGETMODE)
        if (ioctl (session->priv->tty_fd, KDGETMODE, &graphical_mode) != 0) {
                g_warning ("failed to get current VT mode");
                return;
        }
#endif

        if (graphical_mode == KD_TEXT) {
                if (ioctl (session->priv->tty_fd, KDSETMODE, KD_GRAPHICS) != 0) {
                        g_warning ("failed to change VT to graphical mode");
                        return;
                }
        } else {
                g_debug ("already running in graphical mode? not messing with the tty or VT");
                return;
        }

/* We define KDSKBMUTE above so we can't do the usual check */
#if defined(__linux__)
        if (ioctl (session->priv->tty_fd, KDSKBMUTE, 1) != 0) {
                g_warning ("failed to mute FD with KDSKBMUTE");
        }
#endif /* defined(__linux__) */

#if defined(KDSKBMODE)
        if (ioctl (session->priv->tty_fd, KDSKBMODE, KBD_OFF_MODE) != 0) {
                g_warning ("failed to turn off keyboard");
        }
#endif

        mode.mode = VT_PROCESS;
        mode.relsig = SIGUSR1;
        mode.acqsig = SIGUSR2;
        mode.frsig = SIGIO; /* not used, but has to be set anyway */

        if (ioctl (session->priv->tty_fd, VT_SETMODE, &mode) < 0) {
                g_warning ("failed to take control of vt handling");
                return;
        }

        session->priv->sig_watch_s1 = g_unix_signal_add_full (G_PRIORITY_HIGH,
                                                              SIGUSR1,
                                                              (GSourceFunc)vt_leave_handler,
                                                              session,
                                                              NULL);
        session->priv->sig_watch_s2 = g_unix_signal_add_full (G_PRIORITY_HIGH,
                                                              SIGUSR2,
                                                              (GSourceFunc)vt_acquire_handler,
                                                              session,
                                                              NULL);
#endif /* defined(KDGKBMODE) && defined(KDSETMODE) && defined(KD_GRAPHICS) */
}

static void
session_controller_vanished (GDBusConnection *connection,
                             const gchar *name,
                             gpointer user_data)
{
        CkSession *session = CK_SESSION (user_data);

        TRACE ();

        session->priv->session_controller_watchid = 0;

        ck_session_set_session_controller (session, NULL);
}

static void
ck_session_controller_cleanup (CkSession *session)
{
        TRACE ();

        if (session->priv->session_controller_watchid != 0) {
                g_bus_unwatch_name (session->priv->session_controller_watchid);
                session->priv->session_controller_watchid = 0;
        }

        if (session->priv->pause_devices_timer != 0) {
                g_source_remove (session->priv->pause_devices_timer);
                session->priv->pause_devices_timer = 0;
        }

        if (session->priv->session_controller) {
                g_free (session->priv->session_controller);
                session->priv->session_controller = NULL;
        }

        ck_session_remove_all_devices (session);

#if defined(VT_SETMODE)
        /* Remove the old signal call backs, restore VT switching to auto
         * and text mode (put it back the way we found it) */
        if (session->priv->sig_watch_s1 != 0) {
                struct vt_mode mode = { 0 };
                mode.mode = VT_AUTO;

/* We define KDSKBMUTE above so we can't do the usual check */
#if defined(__linux__)
                if (ioctl (session->priv->tty_fd, KDSKBMUTE, 0) != 0) {
                        g_warning ("failed to unmute FD with KDSKBMUTE");
                }
#endif /* defined(__linux__) */

#if defined(KDSKBMODE)
                if (ioctl(session->priv->tty_fd, KDSKBMODE, session->priv->old_kbd_mode) != 0) {
                        g_warning ("failed to restore old keyboard mode");
                }
#endif /* defined(KDSKBMODE) */

                if (ioctl (session->priv->tty_fd, VT_SETMODE, &mode) < 0) {
                        g_warning ("failed to return control of vt handling");
                }

                if (ioctl (session->priv->tty_fd, KDSETMODE, KD_TEXT) < 0) {
                        g_warning ("failed to return to text mode for the VT");
                }

                g_source_remove (session->priv->sig_watch_s1);
                session->priv->sig_watch_s1 = 0;
                g_source_remove (session->priv->sig_watch_s2);
                session->priv->sig_watch_s2 = 0;
        }

        /* Close the old tty fd */
        if (session->priv->tty_fd != -1) {
                g_close (session->priv->tty_fd, NULL);
                session->priv->tty_fd = -1;
        }
#endif /* defined(VT_SETMODE) */
}

void
ck_session_set_session_controller (CkSession   *session,
                                   const gchar *bus_name)
{
        guint vtnr;

        TRACE ();

        /* clean up after the old controller */
        ck_session_controller_cleanup (session);

        /* There's no reason to go further if we're removing the session
         * controller */
        if (bus_name == NULL)
        {
                return;
        }

        session->priv->session_controller = g_strdup (bus_name);

        /* if the session controller crashes or exits, we need to drop access
         * to all the devices it requested and let someone else become the
         * session controller.
         */
        session->priv->session_controller_watchid = g_bus_watch_name_on_connection (session->priv->connection,
                                                                                    bus_name,
                                                                                    G_BUS_NAME_WATCHER_FLAGS_NONE,
                                                                                    NULL,
                                                                                    session_controller_vanished,
                                                                                    session,
                                                                                    NULL);

        vtnr = console_kit_session_get_vtnr (CONSOLE_KIT_SESSION (session));
        if (vtnr > 0) {
                ck_session_setup_vt_signal (session, vtnr);
        }
}

static gboolean
dbus_can_control_session (ConsoleKitSession *object,
                          GDBusMethodInvocation *invocation)
{
        console_kit_session_complete_can_control_session (object, invocation, ck_device_is_server_managed ());
        return TRUE;
}

static gboolean
dbus_take_control (ConsoleKitSession *object,
                   GDBusMethodInvocation *invocation,
                   gboolean arg_force)
{
        CkSession   *session = CK_SESSION (object);
        uid_t        uid = 0;
        pid_t        pid = 0;
        const gchar *sender = g_dbus_method_invocation_get_sender (invocation);

        TRACE ();

        if (!ck_device_is_server_managed ()) {
                throw_error (invocation, CK_SESSION_ERROR_NOT_SUPPORTED, _("Server managed devices not supported"));
                return TRUE;
        }

        if (!get_caller_info (session, sender, &uid, &pid))
        {
                throw_error (invocation, CK_SESSION_ERROR_GENERAL, _("Failed to get uid of dbus caller"));
                return TRUE;
        }

        if (g_strcmp0 (session->priv->session_controller, sender) == 0)
        {
                /* The current session controller is trying to take control
                 * again? Odd, but we'll just do nothing here.
                 */
        }
        else if (session->priv->session_controller == NULL || (arg_force == TRUE && uid == 0))
        {
                ck_session_set_session_controller (CK_SESSION (session), sender);
        }
        else
        {
                if (arg_force == TRUE) {
                        throw_error (invocation, CK_SESSION_ERROR_INSUFFICIENT_PERMISSION, _("Failed to replace the current session controller"));
                } else {
                        throw_error (invocation, CK_SESSION_ERROR_FAILED, _("Session controller already present"));
                }
                return TRUE;
        }

        console_kit_session_complete_take_control (object, invocation);
        return TRUE;
}

static gboolean
dbus_release_control (ConsoleKitSession *object,
                      GDBusMethodInvocation *invocation)
{
        CkSession   *session = CK_SESSION (object);
        const gchar *sender = g_dbus_method_invocation_get_sender (invocation);

        TRACE ();

        /* only the session controller can release it */
        if (g_strcmp0 (session->priv->session_controller, sender) == 0) {
                ck_session_set_session_controller (CK_SESSION (object), NULL);
        } else {
                throw_error (invocation, CK_SESSION_ERROR_FAILED, _("Only the session controller may use this function"));
                return TRUE;
        }

        console_kit_session_complete_release_control (object, invocation);
        return TRUE;
}

static CkDevice*
ck_session_get_device (CkSession *session,
                       guint major,
                       guint minor)
{
        GList *iter;

        TRACE ();

        ck_session_print_list_size (session);

        for (iter = session->priv->devices; iter != NULL; iter = g_list_next (iter)) {
                if (ck_device_compare (iter->data, major, minor)) {
                        g_debug ("found device");
                        return iter->data;
                }
        }

        g_debug ("failed to find deivce");
        return NULL;
}

static CkDevice*
ck_session_create_device (CkSession *session,
                          guint      major,
                          guint      minor)
{
        CkDevice *device = ck_session_get_device (session, major, minor);

        /* If the device already exists for this session don't
         * create it again */
        if (device == NULL) {
                g_debug ("creating new device");

                device = ck_device_new (major, minor,
                                        console_kit_session_get_active (CONSOLE_KIT_SESSION (session)));

                if (device != NULL && CK_IS_DEVICE (device)) {
                        g_debug ("adding device to the list");
                        session->priv->devices = g_list_prepend (session->priv->devices, device);
                        ck_session_print_list_size (session);
                }
        }

        return device;
}

static void
ck_session_remove_device (CkSession *session,
                          CkDevice  *device)
{
        TRACE ();
        ck_session_print_list_size (session);
        session->priv->devices = g_list_remove (session->priv->devices, device);
        ck_session_print_list_size (session);
}

static void
ck_session_remove_all_devices (CkSession *session)
{
        TRACE ();
        ck_session_print_list_size (session);
        g_list_free_full (session->priv->devices, g_object_unref);
        session->priv->devices = NULL;
        g_debug ("list size is now 0");
}

static gboolean
dbus_take_device (ConsoleKitSession *object,
                  GDBusMethodInvocation *invocation,
                  GUnixFDList *fd_list,
                  guint arg_major,
                  guint arg_minor)
{
        CkSession   *session = CK_SESSION (object);
        CkDevice    *device;
        const gchar *sender = g_dbus_method_invocation_get_sender (invocation);
        gint         fd = -1;
        GUnixFDList *out_fd_list = NULL;


        TRACE ();

        /* only the session controller can call us */
        if (g_strcmp0 (session->priv->session_controller, sender) != 0) {
                throw_error (invocation, CK_SESSION_ERROR_FAILED, _("Only the session controller may call this function"));
                return TRUE;
        }

        /* you can't request the device again, that's confusing */
        if (ck_session_get_device (session, arg_major, arg_minor)) {
                throw_error (invocation, CK_SESSION_ERROR_GENERAL, _("Device has already been requested"));
                return TRUE;
        }

        device = ck_session_create_device (session, arg_major, arg_minor);

        if (device == NULL) {
                throw_error (invocation, CK_SESSION_ERROR_NOT_SUPPORTED, _("Failed to create device"));
                return TRUE;
        }

        fd = ck_device_get_fd (device);

        if (fd == -1) {
                throw_error (invocation, CK_SESSION_ERROR_NOT_SUPPORTED, _("Failed to get file descriptor for device"));
                return TRUE;
        }

        out_fd_list = g_unix_fd_list_new_from_array (&fd, 1);

        console_kit_session_complete_take_device (object, invocation,
                                                  out_fd_list, g_variant_new_handle (0),
                                                  console_kit_session_get_active (object));
        return TRUE;
}

static gboolean
dbus_release_device (ConsoleKitSession *object,
                     GDBusMethodInvocation *invocation,
                     guint arg_major,
                     guint arg_minor)
{
        CkSession   *session = CK_SESSION (object);
        CkDevice    *device;
        const gchar *sender = g_dbus_method_invocation_get_sender (invocation);


        TRACE ();

        /* only the session controller can call us */
        if (g_strcmp0 (session->priv->session_controller, sender) != 0) {
                throw_error (invocation, CK_SESSION_ERROR_FAILED, _("Only the session controller may call this function"));
                return TRUE;
        }

        device = ck_session_get_device (session, arg_major, arg_minor);

        if (device == NULL) {
                throw_error (invocation, CK_SESSION_ERROR_FAILED, _("Device doesn't exist"));
                return TRUE;
        }

        ck_session_remove_device (session, device);
        g_object_unref (device);

        console_kit_session_complete_release_device (object, invocation);
        return TRUE;
}

static gboolean
dbus_pause_device_complete (ConsoleKitSession *object,
                            GDBusMethodInvocation *invocation,
                            guint arg_major,
                            guint arg_minor)
{
        CkSession   *session = CK_SESSION (object);
        CkDevice    *device;
        const gchar *sender = g_dbus_method_invocation_get_sender (invocation);

        TRACE ();

        /* only the session controller can call us */
        if (g_strcmp0 (session->priv->session_controller, sender) != 0) {
                throw_error (invocation, CK_SESSION_ERROR_FAILED, _("Only the session controller may call this function"));
                return TRUE;
        }

        device = ck_session_get_device (session, arg_major, arg_minor);

        if (device == NULL) {
                throw_error (invocation, CK_SESSION_ERROR_FAILED, _("Device doesn't exist"));
                return TRUE;
        }

        ck_device_set_active (device, FALSE);

        ck_session_check_paused_devices (session);

        console_kit_session_complete_pause_device_complete (object, invocation);
        return TRUE;
}

static void
ck_session_set_property (GObject            *object,
                         guint               prop_id,
                         const GValue       *value,
                         GParamSpec         *pspec)
{
        CkSession *self;

        self = CK_SESSION (object);

        switch (prop_id) {
        case PROP_ID:
                ck_session_set_id (self, g_value_get_string (value), NULL);
                break;
        case PROP_COOKIE:
                ck_session_set_cookie (self, g_value_get_string (value), NULL);
                break;
        case PROP_LOGIN_SESSION_ID:
                ck_session_set_login_session_id (self, g_value_get_string (value), NULL);
                break;
        case PROP_SESSION_CONTROLLER:
                ck_session_set_session_controller (self, g_value_get_string (value));
                break;
        default:
                G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
                break;
        }
}

static void
ck_session_get_property (GObject    *object,
                         guint       prop_id,
                         GValue     *value,
                         GParamSpec *pspec)
{
        CkSession *self;

        self = CK_SESSION (object);

        switch (prop_id) {
        case PROP_ID:
                g_value_set_string (value, self->priv->id);
                break;
        case PROP_COOKIE:
                g_value_set_string (value, self->priv->cookie);
                break;
        case PROP_LOGIN_SESSION_ID:
                g_value_set_string (value, self->priv->login_session_id);
                break;
        case PROP_SESSION_CONTROLLER:
                g_value_set_string (value, self->priv->session_controller);
                break;
        default:
                G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
                break;
        }
}

#define IS_STR_SET(x) (x != NULL && x[0] != '\0')
static gboolean
session_is_text (CkSession *session)
{
        ConsoleKitSession *cksession;
        gboolean ret;

        ret = FALSE;
        cksession = CONSOLE_KIT_SESSION (session);

        if (! IS_STR_SET (console_kit_session_get_x11_display_device (cksession))
            && ! IS_STR_SET (console_kit_session_get_x11_display (cksession))
            && IS_STR_SET (console_kit_session_get_display_device (cksession))) {
                ret = TRUE;
        }

        g_debug ("Identified session '%s' as %s",
                  session->priv->id,
                  ret ? "text" : "graphical");

        return ret;
}

static void
tty_idle_changed_cb (CkTtyIdleMonitor *monitor,
                     gboolean          idle_hint,
                     CkSession        *session)
{
        session_set_idle_hint_internal (session, idle_hint);
}

static void
session_add_activity_watch (CkSession *session)
{
        if (session->priv->idle_monitor == NULL) {
                session->priv->idle_monitor = ck_tty_idle_monitor_new (console_kit_session_get_display_device (CONSOLE_KIT_SESSION (session)));
                g_signal_connect (session->priv->idle_monitor,
                                  "idle-hint-changed",
                                  G_CALLBACK (tty_idle_changed_cb),
                                  session);

        }
        ck_tty_idle_monitor_start (session->priv->idle_monitor);
}

static void
session_remove_activity_watch (CkSession *session)
{
        TRACE ();

        if (session->priv->idle_monitor == NULL) {
                return;
        }

        ck_tty_idle_monitor_stop (session->priv->idle_monitor);
        g_object_unref (session->priv->idle_monitor);
        session->priv->idle_monitor = NULL;
}

static GObject *
ck_session_constructor (GType                  type,
                        guint                  n_construct_properties,
                        GObjectConstructParam *construct_properties)
{
        CkSession      *session;

        session = CK_SESSION (G_OBJECT_CLASS (ck_session_parent_class)->constructor (type,
                                                                                     n_construct_properties,
                                                                                     construct_properties));
        if (session_is_text (session)) {
                session_add_activity_watch (session);
        }

        return G_OBJECT (session);
}

static void
ck_session_class_init (CkSessionClass *klass)
{
        GObjectClass   *object_class = G_OBJECT_CLASS (klass);

        object_class->constructor = ck_session_constructor;
        object_class->get_property = ck_session_get_property;
        object_class->set_property = ck_session_set_property;
        object_class->finalize = ck_session_finalize;

        signals [ACTIVATE] =
                g_signal_new ("activate",
                              G_TYPE_FROM_CLASS (object_class),
                              G_SIGNAL_RUN_LAST,
                              G_STRUCT_OFFSET (CkSessionClass, activate),
                              NULL,
                              NULL,
                              ck_marshal_POINTER__POINTER,
                              G_TYPE_POINTER,
                              1, G_TYPE_POINTER);

        /* Install private properties we're not exporting over D-BUS */
        g_object_class_install_property (object_class,
                                         PROP_ID,
                                         g_param_spec_string ("id",
                                                              "id",
                                                              "id",
                                                              NULL,
                                                              G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
        g_object_class_install_property (object_class,
                                         PROP_COOKIE,
                                         g_param_spec_string ("cookie",
                                                              "cookie",
                                                              "cookie",
                                                              NULL,
                                                              G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
        g_object_class_install_property (object_class,
                                         PROP_LOGIN_SESSION_ID,
                                         g_param_spec_string ("login-session-id",
                                                              "login-session-id",
                                                              "login session id",
                                                              NULL,
                                                              G_PARAM_READWRITE | G_PARAM_CONSTRUCT));

        g_object_class_install_property (object_class,
                                         PROP_SESSION_CONTROLLER,
                                         g_param_spec_string ("session-controller",
                                                              "session-controller",
                                                              "session-controller",
                                                              NULL,
                                                              G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));

        g_type_class_add_private (klass, sizeof (CkSessionPrivate));
}

static void
ck_session_init (CkSession *session)
{
        session->priv = CK_SESSION_GET_PRIVATE (session);

        /* FIXME: should we have a property for this? */
        g_get_current_time (&session->priv->creation_time);

        session->priv->tty_fd = -1;
}

static void
ck_session_iface_init (ConsoleKitSessionIface *iface)
{
        iface->handle_activate               = dbus_activate;
        iface->handle_set_idle_hint          = dbus_set_idle_hint;
        iface->handle_set_locked_hint        = dbus_set_locked_hint;
        iface->handle_get_unix_user          = dbus_get_unix_user;
        iface->handle_get_seat_id            = dbus_get_seat_id;
        iface->handle_get_login_session_id   = dbus_get_login_session_id;
        iface->handle_get_vtnr               = dbus_get_vtnr;
        iface->handle_get_session_type       = dbus_get_session_type;
        iface->handle_get_session_class      = dbus_get_session_class;
        iface->handle_get_session_state      = dbus_get_session_state;
        iface->handle_get_x11_display_device = dbus_get_x11_display_device;
        iface->handle_get_display_device     = dbus_get_display_device;
        iface->handle_get_x11_display        = dbus_get_x11_display;
        iface->handle_is_active              = dbus_is_active;
        iface->handle_get_creation_time      = dbus_get_creation_time;
        iface->handle_get_remote_host_name   = dbus_get_remote_host_name;
        iface->handle_get_idle_since_hint    = dbus_get_idle_since_hint;
        iface->handle_is_local               = dbus_is_local;
        iface->handle_get_id                 = dbus_get_id;
        iface->handle_get_user               = dbus_get_user;
        iface->handle_lock                   = dbus_lock;
        iface->handle_unlock                 = dbus_unlock;
        iface->handle_get_idle_hint          = dbus_get_idle_hint;
        iface->handle_get_xdgruntime_dir     = dbus_get_runtime_dir;
        iface->handle_can_control_session    = dbus_can_control_session;
        iface->handle_take_control           = dbus_take_control;
        iface->handle_release_control        = dbus_release_control;
        iface->handle_take_device            = dbus_take_device;
        iface->handle_release_device         = dbus_release_device;
        iface->handle_pause_device_complete  = dbus_pause_device_complete;
}

static void
ck_session_finalize (GObject *object)
{
        CkSession *session;

        g_debug ("ck_session_finalize");

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

        session = CK_SESSION (object);

        g_return_if_fail (session->priv != NULL);

        session_remove_activity_watch (session);

        ck_session_set_session_controller (session, NULL);

        ck_session_remove_all_devices (session);

        g_free (session->priv->id);
        g_free (session->priv->cookie);
        g_free (session->priv->login_session_id);
        g_free (session->priv->runtime_dir);
        g_free (session->priv->seat_id);
        g_free (session->priv->session_controller);

        if (session->priv->bus_proxy) {
            g_object_unref(session->priv->bus_proxy);
        }

        if (session->priv->session_controller_watchid != 0) {
                g_bus_unwatch_name (session->priv->session_controller_watchid);
        }

        if (session->priv->pause_devices_timer != 0) {
                g_source_remove (session->priv->pause_devices_timer);
                session->priv->pause_devices_timer = 0;
        }

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

CkSession *
ck_session_new (const char      *ssid,
                const char      *cookie,
                GDBusConnection *connection)
{
        GObject *object;
        gboolean res;

        object = g_object_new (CK_TYPE_SESSION,
                               "id", ssid,
                               "cookie", cookie,
                               NULL);
        res = register_session (CK_SESSION (object), connection);
        if (! res) {
                g_object_unref (object);
                return NULL;
        }

        return CK_SESSION (object);
}

CkSession *
ck_session_new_with_parameters (const char      *ssid,
                                const char      *cookie,
                                const GVariant  *parameters,
                                GDBusConnection *connection)
{
        GObject      *object;
        gboolean      session_registered;
        GParameter   *params;
        guint         n_allocated_params;
        guint         n_params;
        GObjectClass *class;
        GType         object_type;
        GVariantIter *iter;
        gchar        *prop_name;
        GVariant     *value;

        object_type = CK_TYPE_SESSION;
        class = g_type_class_ref (object_type);

        g_variant_get ((GVariant *)parameters, "a{sv}", &iter);

        n_allocated_params = 2;
        if (parameters != NULL) {
                n_allocated_params += g_variant_iter_n_children (iter);
        }

        params = g_new0 (GParameter, n_allocated_params);

        n_params = 0;
        params[n_params].name = g_strdup ("id");
        params[n_params].value.g_type = 0;
        g_value_init (&params[n_params].value, G_TYPE_STRING);
        g_value_set_string (&params[n_params].value, ssid);
        n_params++;

        params[n_params].name = g_strdup ("cookie");
        params[n_params].value.g_type = 0;
        g_value_init (&params[n_params].value, G_TYPE_STRING);
        g_value_set_string (&params[n_params].value, cookie);
        n_params++;

        if (parameters != NULL) {
                while (g_variant_iter_next (iter, "{sv}", &prop_name, &value)) {
                        gboolean    res;
                        GValue      val_struct = { 0, };
                        GParamSpec *pspec;


                        if (prop_name == NULL) {
                                g_debug ("Skipping NULL parameter");
                                goto cleanup;
                        }

                        g_debug ("prop_name = '%s'", prop_name);

                        if (strcmp (prop_name, "id") == 0
                            || strcmp (prop_name, "cookie") == 0) {
                                g_debug ("Skipping restricted parameter: %s", prop_name);
                                goto cleanup;
                        }

                        pspec = g_object_class_find_property (class, prop_name);
                        if (! pspec) {
                                g_debug ("Skipping unknown parameter: %s", prop_name);
                                goto cleanup;
                        }

                        if (!(pspec->flags & G_PARAM_WRITABLE)) {
                                g_debug ("property '%s' is not writable", pspec->name);
                                goto cleanup;
                        }

                        params[n_params].name = g_strdup (prop_name);
                        params[n_params].value.g_type = 0;
                        g_value_init (&params[n_params].value, G_PARAM_SPEC_VALUE_TYPE (pspec));
                        g_dbus_gvariant_to_gvalue (value, &val_struct);
                        res = g_value_transform (&val_struct, &params[n_params].value);
                        if (! res) {
                                g_debug ("unable to transform property value for '%s'", pspec->name);
                                goto cleanup;
                        }

                        n_params++;
cleanup:
                        g_free(prop_name);
                        if (value) {
                            g_variant_unref(value);
                        }
                }
                g_variant_iter_free (iter);
        }

        object = g_object_newv (object_type, n_params, params);

        while (n_params--) {
                g_free ((char *)params[n_params].name);
                g_value_unset (&params[n_params].value);
        }
        g_free (params);
        g_type_class_unref (class);

        session_registered = register_session (CK_SESSION (object), connection);
        if (! session_registered) {
                g_object_unref (object);
                return NULL;
        }

        return CK_SESSION (object);
}

void
ck_session_run_programs (CkSession  *session,
                         const char *action)
{
        ConsoleKitSession *cksession;
        guint n;
        char *extra_env[11]; /* be sure to adjust this as needed */

        TRACE ();

        n = 0;
        cksession = CONSOLE_KIT_SESSION (session);

        extra_env[n++] = g_strdup_printf ("CK_SESSION_ID=%s", session->priv->id);
        if (console_kit_session_get_session_type (cksession) != NULL) {
                extra_env[n++] = g_strdup_printf ("CK_SESSION_TYPE=%s", console_kit_session_get_session_type (cksession));
        }
        extra_env[n++] = g_strdup_printf ("CK_SESSION_SEAT_ID=%s", session->priv->seat_id);
        extra_env[n++] = g_strdup_printf ("CK_SESSION_USER_UID=%d", console_kit_session_get_unix_user (cksession));
        if (console_kit_session_get_display_device (cksession) != NULL && strlen (console_kit_session_get_display_device (cksession)) > 0) {
                extra_env[n++] = g_strdup_printf ("CK_SESSION_DISPLAY_DEVICE=%s", console_kit_session_get_display_device (cksession));
        }
        if (console_kit_session_get_x11_display_device (cksession) != NULL && strlen (console_kit_session_get_x11_display_device (cksession) ) > 0) {
                extra_env[n++] = g_strdup_printf ("CK_SESSION_X11_DISPLAY_DEVICE=%s", console_kit_session_get_x11_display_device (cksession) );
        }
        extra_env[n++] = g_strdup_printf ("CK_SESSION_X11_DISPLAY=%s",
                console_kit_session_get_x11_display (cksession)  ? console_kit_session_get_x11_display (cksession)  : "");
        if (console_kit_session_get_remote_host_name (cksession)  != NULL && strlen (console_kit_session_get_remote_host_name (cksession)) > 0) {
                extra_env[n++] = g_strdup_printf ("CK_SESSION_REMOTE_HOST_NAME=%s", console_kit_session_get_remote_host_name (cksession));
        }
        extra_env[n++] = g_strdup_printf ("CK_SESSION_IS_ACTIVE=%s", console_kit_session_get_active (cksession) ? "true" : "false");
        extra_env[n++] = g_strdup_printf ("CK_SESSION_IS_LOCAL=%s", console_kit_session_get_is_local (cksession) ? "true" : "false");
        extra_env[n++] = NULL;

        g_assert(n <= G_N_ELEMENTS(extra_env));

        ck_run_programs (SYSCONFDIR "/ConsoleKit/run-session.d", action, extra_env);
        ck_run_programs (LIBDIR "/ConsoleKit/run-session.d", action, extra_env);

        for (n = 0; extra_env[n] != NULL; n++) {
                g_free (extra_env[n]);
        }
}

void
ck_session_dump (CkSession *session,
                 GKeyFile  *key_file)
{
        char *s;
        char *group_name;
        ConsoleKitSession *cksession;

        TRACE ();

        cksession = CONSOLE_KIT_SESSION (session);

        group_name = g_strdup_printf ("Session %s", session->priv->id);
        g_key_file_set_integer (key_file, group_name, "uid", console_kit_session_get_unix_user (cksession));
        g_key_file_set_string (key_file,
                               group_name,
                               "seat",
                               NONULL_STRING (session->priv->seat_id));
        if (console_kit_session_get_session_type (cksession) != NULL) {
                g_key_file_set_string (key_file,
                                       group_name,
                                       "type",
                                       NONULL_STRING (console_kit_session_get_session_type (cksession)));
        }
        if (session->priv->login_session_id != NULL && strlen (session->priv->login_session_id) > 0) {
                g_key_file_set_string (key_file,
                                       group_name,
                                       "login_session_id",
                                       NONULL_STRING (session->priv->login_session_id));
        }
        if (console_kit_session_get_display_device (cksession) != NULL && strlen (console_kit_session_get_display_device (cksession)) > 0) {
                g_key_file_set_string (key_file,
                                       group_name,
                                       "display_device",
                                       NONULL_STRING (console_kit_session_get_display_device (cksession)));
        }
        if (console_kit_session_get_x11_display_device (cksession) != NULL && strlen (console_kit_session_get_x11_display_device (cksession)) > 0) {
                g_key_file_set_string (key_file,
                                       group_name,
                                       "x11_display_device",
                                       NONULL_STRING (console_kit_session_get_x11_display_device (cksession)));
        }
        if (console_kit_session_get_x11_display (cksession) != NULL && strlen (console_kit_session_get_x11_display (cksession)) > 0) {
                g_key_file_set_string (key_file,
                                       group_name,
                                       "x11_display",
                                       NONULL_STRING (console_kit_session_get_x11_display (cksession)));
        }
        if (console_kit_session_get_remote_host_name (cksession) != NULL && strlen (console_kit_session_get_remote_host_name (cksession)) > 0) {
                g_key_file_set_string (key_file,
                                       group_name,
                                       "remote_host_name",
                                       NONULL_STRING (console_kit_session_get_remote_host_name (cksession)));
        }
        g_key_file_set_string (key_file,
                               group_name,
                               "remote_host_name",
                               NONULL_STRING (console_kit_session_get_remote_host_name (cksession)));

        g_key_file_set_boolean (key_file, group_name, "is_active", console_kit_session_get_active (cksession));
        g_key_file_set_boolean (key_file, group_name, "is_local", console_kit_session_get_is_local (cksession));
        g_key_file_set_string  (key_file, group_name, "XDG_RUNTIME_DIR", NONULL_STRING (session->priv->runtime_dir));

        s = g_time_val_to_iso8601 (&(session->priv->creation_time));
        g_key_file_set_string (key_file,
                               group_name,
                               "creation_time",
                               NONULL_STRING (s));
        g_free (s);

        g_free (group_name);
}