~xnox/ubuntu/vivid/upstart/fix-rotate-logs

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
/* upstart
 *
 * control.c - D-Bus connections, objects and methods
 *
 * Copyright  2009-2011 Canonical Ltd.
 * Author: Scott James Remnant <scott@netsplit.com>.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2, as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif /* HAVE_CONFIG_H */

#include <dbus/dbus.h>

#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <nih/macros.h>
#include <nih/alloc.h>
#include <nih/string.h>
#include <nih/list.h>
#include <nih/io.h>
#include <nih/main.h>
#include <nih/logging.h>
#include <nih/error.h>
#include <nih/errors.h>

#include <nih-dbus/dbus_error.h>
#include <nih-dbus/dbus_connection.h>
#include <nih-dbus/dbus_message.h>
#include <nih-dbus/dbus_object.h>

#include "dbus/upstart.h"

#include "environ.h"
#include "session.h"
#include "job_class.h"
#include "job.h"
#include "blocked.h"
#include "conf.h"
#include "control.h"
#include "errors.h"
#include "state.h"
#include "event.h"
#include "events.h"
#include "paths.h"
#include "xdg.h"

#include "com.ubuntu.Upstart.h"

#ifdef ENABLE_CGROUPS
#include "cgroup.h"
#endif /* ENABLE_CGROUPS */

/* Prototypes for static functions */
static int   control_server_connect      (DBusServer *server, DBusConnection *conn);
static void  control_disconnected        (DBusConnection *conn);
static void  control_register_all        (DBusConnection *conn);

static void  control_bus_flush           (void);
static int   control_get_origin_uid      (NihDBusMessage *message, uid_t *uid)
	__attribute__ ((warn_unused_result));
static int   control_check_permission    (NihDBusMessage *message)
	__attribute__ ((warn_unused_result));
static void  control_session_file_create (void);
static void  control_session_file_remove (void);

/**
 * use_session_bus:
 *
 * If TRUE, connect to the D-Bus session bus rather than the system bus.
 *
 * Used for testing to simulate (as far as possible) a system-like init
 * when running as a non-priv user (but not as a Session Init).
 **/
int use_session_bus = FALSE;

/**
 * dbus_bus_type:
 *
 * Type of D-Bus bus to connect to.
 **/
DBusBusType dbus_bus_type;

/**
 * control_server_address:
 *
 * Address on which the control server may be reached.
 **/
char *control_server_address = NULL;

/**
 * control_server:
 *
 * D-Bus server listening for new direct connections.
 **/
DBusServer *control_server = NULL;

/**
 * control_bus_address:
 *
 * Address on which the control bus may be reached.
 **/
char *control_bus_address = NULL;

/**
 * control_bus:
 *
 * Open connection to a D-Bus bus.  The connection may be opened with
 * control_bus_open() and if lost will become NULL.
 **/
DBusConnection *control_bus = NULL;

/**
 * control_conns:
 *
 * Open control connections, including the connection to a D-Bus
 * bus and any private client connections.
 **/
NihList *control_conns = NULL;

/* External definitions */
extern int      user_mode;
extern int      disable_respawn;
extern char    *session_file;

/**
 * control_init:
 *
 * Initialise the control connections list.
 **/
void
control_init (void)
{
	if (! control_conns)
		control_conns = NIH_MUST (nih_list_new (NULL));

	if (! control_server_address) {
		if (user_mode) {
			NIH_MUST (nih_strcat_sprintf (&control_server_address, NULL,
					    "%s-session/%d/%d", DBUS_ADDRESS_UPSTART, getuid (), getpid ()));

			control_session_file_create ();
		} else {
			control_server_address = NIH_MUST (nih_strdup (NULL, DBUS_ADDRESS_UPSTART));
		}
	}
}

/**
 * control_cleanup:
 *
 * Perform cleanup operations.
 **/
void
control_cleanup (void)
{
	control_session_file_remove ();
}

/**
 * control_server_open:
 *
 * Open a listening D-Bus server and store it in the control_server global.
 * New connections are permitted from the root user, and handled
 * automatically in the main loop.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_server_open (void)
{
	DBusServer *server;

	nih_assert (control_server == NULL);

	control_init ();

	server = nih_dbus_server (control_server_address,
				  control_server_connect,
				  control_disconnected);
	if (! server)
		return -1;

	control_server = server;

	return 0;
}

/**
 * control_server_connect:
 *
 * Called when a new client connects to our server and is used to register
 * objects on the new connection.
 *
 * Returns: always TRUE.
 **/
static int
control_server_connect (DBusServer     *server,
			DBusConnection *conn)
{
	NihListEntry *entry;

	nih_assert (server != NULL);
	nih_assert (server == control_server);
	nih_assert (conn != NULL);

	nih_info (_("Connection from private client"));

	/* Register objects on the connection. */
	control_register_all (conn);

	/* Add the connection to the list */
	entry = NIH_MUST (nih_list_entry_new (NULL));

	entry->data = conn;

	nih_list_add (control_conns, &entry->entry);

	return TRUE;
}

/**
 * control_server_close:
 *
 * Close the connection to the D-Bus system bus.  Since the connection is
 * shared inside libdbus, this really only drops our reference to it so
 * it's possible to have method and signal handlers called even after calling
 * this (normally to dispatch what's in the queue).
 **/
void
control_server_close (void)
{
	if (! control_server)
		return;

	dbus_server_disconnect (control_server);
	dbus_server_unref (control_server);

	control_server = NULL;
}

/**
 * control_bus_open:
 *
 * Open a connection to the appropriate D-Bus bus and store it in the
 * control_bus global. The connection is handled automatically
 * in the main loop.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_bus_open (void)
{
	DBusConnection *conn;
	DBusError       error;
	NihListEntry   *entry;
	int             ret;

	nih_assert (control_bus == NULL);

	dbus_error_init (&error);

	control_init ();

	dbus_bus_type = control_get_bus_type ();

	/* Connect to the appropriate D-Bus bus and hook everything up into
	 * our own main loop automatically.
	 */
	if (user_mode && control_bus_address) {
		conn = nih_dbus_connect (control_bus_address, control_disconnected);
		if (! conn)
			return -1;

		if (! dbus_bus_register (conn, &error)) {
			nih_dbus_error_raise (error.name, error.message);
			dbus_error_free (&error);
			return -1;
		}

		nih_debug ("Connected to notified D-Bus bus");
	} else {
		conn = nih_dbus_bus (use_session_bus ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM,
				control_disconnected);
		if (! conn)
			return -1;

		nih_debug ("Connected to D-Bus %s bus",
				dbus_bus_type == DBUS_BUS_SESSION
				? "session" : "system");
	}

	/* Register objects on the bus. */
	control_register_all (conn);

	/* Request our well-known name.  We do this last so that once it
	 * appears on the bus, clients can assume we're ready to talk to
	 * them.
	 */
	ret = dbus_bus_request_name (conn, DBUS_SERVICE_UPSTART,
				     DBUS_NAME_FLAG_DO_NOT_QUEUE, &error);
	if (ret < 0) {
		/* Error while requesting the name */
		nih_dbus_error_raise (error.name, error.message);
		dbus_error_free (&error);

		dbus_connection_unref (conn);
		return -1;
	} else if (ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
		/* Failed to obtain the name (already taken usually) */
		nih_error_raise (CONTROL_NAME_TAKEN,
				 _(CONTROL_NAME_TAKEN_STR));

		dbus_connection_unref (conn);
		return -1;
	}


	/* Add the connection to the list */
	entry = NIH_MUST (nih_list_entry_new (NULL));

	entry->data = conn;

	nih_list_add (control_conns, &entry->entry);


	control_bus = conn;

	return 0;
}

/**
 * control_bus_close:
 *
 * Close the connection to the D-Bus system bus.  Since the connection is
 * shared inside libdbus, this really only drops our reference to it so
 * it's possible to have method and signal handlers called even after calling
 * this (normally to dispatch what's in the queue).
 **/
void
control_bus_close (void)
{
	nih_assert (control_bus != NULL);

	dbus_connection_unref (control_bus);

	control_disconnected (control_bus);
}


/**
 * control_disconnected:
 *
 * This function is called when the connection to the D-Bus system bus,
 * or a client connection to our D-Bus server, is dropped and our reference
 * is about to be lost.  We clear the connection from our current list
 * and drop the control_bus global if relevant.
 **/
static void
control_disconnected (DBusConnection *conn)
{
	nih_assert (conn != NULL);

	if (conn == control_bus) {
		DBusError  error;

		dbus_error_init (&error);

		if (user_mode && control_bus_address) {
			nih_warn (_("Disconnected from notified D-Bus bus"));
		} else {
			nih_warn (_("Disconnected from D-Bus %s bus"),
					dbus_bus_type == DBUS_BUS_SESSION
					? "session" : "system");
		}

		control_bus = NULL;
	}

	/* Remove from the connections list */
	NIH_LIST_FOREACH_SAFE (control_conns, iter) {
		NihListEntry *entry = (NihListEntry *)iter;

		if (entry->data == conn)
			nih_free (entry);
	}
}


/**
 * control_register_all:
 * @conn: connection to register objects for.
 *
 * Registers the manager object and objects for all jobs and instances on
 * the given connection.
 **/
static void
control_register_all (DBusConnection *conn)
{
	nih_assert (conn != NULL);

	job_class_init ();

	/* Register the manager object, this is the primary point of contact
	 * for clients.  We only check for success, otherwise we're happy
	 * to let this object be tied to the lifetime of the connection.
	 */
	NIH_MUST (nih_dbus_object_new (NULL, conn, DBUS_PATH_UPSTART,
				       control_interfaces, NULL));

	/* Register objects for each currently registered job and its
	 * instances.
	 */
	NIH_HASH_FOREACH (job_classes, iter) {
		JobClass *class = (JobClass *)iter;

		job_class_register (class, conn, FALSE);
	}
}


/**
 * control_reload_configuration:
 * @data: not used,
 * @message: D-Bus connection and message received.
 *
 * Implements the ReloadConfiguration method of the com.ubuntu.Upstart
 * interface.
 *
 * Called to request that Upstart reloads its configuration from disk,
 * useful when inotify is not available or the user is generally paranoid.
 *
 * Notes: chroot sessions are permitted to make this call.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_reload_configuration (void           *data,
			      NihDBusMessage *message)
{
	nih_assert (message != NULL);

	if (! control_check_permission (message)) {
		nih_dbus_error_raise_printf (
			DBUS_INTERFACE_UPSTART ".Error.PermissionDenied",
			_("You do not have permission to reload configuration"));
		return -1;
	}

	nih_info (_("Reloading configuration"));

	/* This can only be called after deserialisation */
	conf_reload ();

	return 0;
}


/**
 * control_get_job_by_name:
 * @data: not used,
 * @message: D-Bus connection and message received,
 * @name: name of job to get,
 * @job: pointer for object path reply.
 *
 * Implements the GetJobByName method of the com.ubuntu.Upstart
 * interface.
 *
 * Called to obtain the path to a D-Bus object for the job named @name,
 * which will be stored in @job.  If no job class with that name exists,
 * the com.ubuntu.Upstart.Error.UnknownJob D-Bus error will be raised.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_get_job_by_name (void            *data,
			 NihDBusMessage  *message,
			 const char      *name,
			 char           **job)
{
	Session  *session;
	JobClass *class = NULL;
	JobClass *global_class = NULL;

	nih_assert (message != NULL);
	nih_assert (name != NULL);
	nih_assert (job != NULL);

	job_class_init ();

	/* Verify that the name is valid */
	if (! strlen (name)) {
		nih_dbus_error_raise_printf (DBUS_ERROR_INVALID_ARGS,
					     _("Name may not be empty string"));
		return -1;
	}

	/* Get the relevant session */
	session = session_from_dbus (NULL, message);

	/* Lookup the job */
	class = (JobClass *)nih_hash_search (job_classes, name, NULL);

	while (class && (class->session != session)) {

		/* Found a match in the global session which may be used
		 * later if no matching user session job exists.
		 */
		if ((! class->session) && (session && ! session->chroot))
			global_class = class;

		class = (JobClass *)nih_hash_search (job_classes, name,
				&class->entry);
	}

	/* If no job with the given name exists in the appropriate
	 * session, look in the global namespace (aka the NULL session).
	 */ 
	if (! class)
		class = global_class;

	if (! class) {
		nih_dbus_error_raise_printf (
			DBUS_INTERFACE_UPSTART ".Error.UnknownJob",
			_("Unknown job: %s"), name);
		return -1;
	}

	/* Copy the path */
	*job = nih_strdup (message, class->path);
	if (! *job)
		nih_return_system_error (-1);

	return 0;
}

/**
 * control_get_all_jobs:
 * @data: not used,
 * @message: D-Bus connection and message received,
 * @jobs: pointer for array of object paths reply.
 *
 * Implements the GetAllJobs method of the com.ubuntu.Upstart
 * interface.
 *
 * Called to obtain the paths of all known jobs, which will be stored in
 * @jobs.  If no jobs are registered, @jobs will point to an empty array.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_get_all_jobs (void             *data,
		      NihDBusMessage   *message,
		      char           ***jobs)
{
	Session *session;
	char   **list;
	size_t   len;

	nih_assert (message != NULL);
	nih_assert (jobs != NULL);

	job_class_init ();

	len = 0;
	list = nih_str_array_new (message);
	if (! list)
		nih_return_system_error (-1);

	/* Get the relevant session */
	session = session_from_dbus (NULL, message);

	NIH_HASH_FOREACH (job_classes, iter) {
		JobClass *class = (JobClass *)iter;

		if ((class->session || (session && session->chroot))
		    && (class->session != session))
			continue;

		if (! nih_str_array_add (&list, message, &len,
					 class->path)) {
			nih_error_raise_system ();
			nih_free (list);
			return -1;
		}
	}

	*jobs = list;

	return 0;
}


int
control_emit_event (void            *data,
		    NihDBusMessage  *message,
		    const char      *name,
		    char * const    *env,
		    int              wait)
{
	return control_emit_event_with_file (data, message, name, env, wait, -1);
}

/**
 * control_emit_event_with_file:
 * @data: not used,
 * @message: D-Bus connection and message received,
 * @name: name of event to emit,
 * @env: environment of environment,
 * @wait: whether to wait for event completion before returning,
 * @file: file descriptor.
 *
 * Implements the top half of the EmitEvent method of the com.ubuntu.Upstart
 * interface, the bottom half may be found in event_finished().
 *
 * Called to emit an event with a given @name and @env, which will be
 * added to the event queue and processed asynchronously.  If @name or
 * @env are not valid, the org.freedesktop.DBus.Error.InvalidArgs D-Bus
 * error will be returned immediately.  If the event fails, the
 * com.ubuntu.Upstart.Error.EventFailed D-Bus error will be returned when
 * the event finishes.
 *
 * When @wait is TRUE the method call will not return until the event
 * has completed, which means that all jobs affected by the event have
 * finished starting (running for tasks) or stopping; when @wait is FALSE,
 * the method call returns once the event has been queued.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_emit_event_with_file (void            *data,
			      NihDBusMessage  *message,
			      const char      *name,
			      char * const    *env,
			      int              wait,
			      int              file)
{
	Event    *event;
	Blocked  *blocked;

	nih_assert (message != NULL);
	nih_assert (name != NULL);
	nih_assert (env != NULL);

	if (! control_check_permission (message)) {
		nih_dbus_error_raise_printf (
			DBUS_INTERFACE_UPSTART ".Error.PermissionDenied",
			_("You do not have permission to emit an event"));
		return -1;
	}

	/* Verify that the name is valid */
	if (! strlen (name)) {
		nih_dbus_error_raise_printf (DBUS_ERROR_INVALID_ARGS,
					     _("Name may not be empty string"));
		close (file);
		return -1;
	}

	/* Verify that the environment is valid */
	if (! environ_all_valid (env)) {
		nih_dbus_error_raise_printf (DBUS_ERROR_INVALID_ARGS,
					     _("Env must be KEY=VALUE pairs"));
		close (file);
		return -1;
	}

	/* Make the event and block the message on it */
	event = event_new (NULL, name, (char **)env);
	if (! event) {
		nih_error_raise_system ();
		close (file);
		return -1;
	}

	event->fd = file;
	if (event->fd >= 0) {
		long flags;

		flags = fcntl (event->fd, F_GETFD);
		flags &= ~FD_CLOEXEC;
		fcntl (event->fd, F_SETFD, flags);
	}

	/* Obtain the session */
	event->session = session_from_dbus (NULL, message);

	if (wait) {
		blocked = blocked_new (event, BLOCKED_EMIT_METHOD, message);
		if (! blocked) {
			nih_error_raise_system ();
			nih_free (event);
			close (file);
			return -1;
		}

		nih_list_add (&event->blocking, &blocked->entry);
	} else {
		NIH_ZERO (control_emit_event_reply (message));
	}

	return 0;
}


/**
 * control_get_version:
 * @data: not used,
 * @message: D-Bus connection and message received,
 * @version: pointer for reply string.
 *
 * Implements the get method for the version property of the
 * com.ubuntu.Upstart interface.
 *
 * Called to obtain the version of the init daemon, which will be stored
 * as a string in @version.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_get_version (void *          data,
		     NihDBusMessage *message,
		     char **         version)
{
	nih_assert (message != NULL);
	nih_assert (version != NULL);

	*version = nih_strdup (message, package_string);
	if (! *version)
		nih_return_no_memory_error (-1);

	return 0;
}

/**
 * control_get_log_priority:
 * @data: not used,
 * @message: D-Bus connection and message received,
 * @log_priority: pointer for reply string.
 *
 * Implements the get method for the log_priority property of the
 * com.ubuntu.Upstart interface.
 *
 * Called to obtain the init daemon's current logging level, which will
 * be stored as a string in @log_priority.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_get_log_priority (void *          data,
			  NihDBusMessage *message,
			  char **         log_priority)
{
	const char *priority;

	nih_assert (message != NULL);
	nih_assert (log_priority != NULL);

	switch (nih_log_priority) {
	case NIH_LOG_DEBUG:
		priority = "debug";
		break;
	case NIH_LOG_INFO:
		priority = "info";
		break;
	case NIH_LOG_MESSAGE:
		priority = "message";
		break;
	case NIH_LOG_WARN:
		priority = "warn";
		break;
	case NIH_LOG_ERROR:
		priority = "error";
		break;
	case NIH_LOG_FATAL:
		priority = "fatal";
		break;
	default:
		nih_assert_not_reached ();
	}

	*log_priority = nih_strdup (message, priority);
	if (! *log_priority)
		nih_return_no_memory_error (-1);

	return 0;
}

/**
 * control_set_log_priority:
 * @data: not used,
 * @message: D-Bus connection and message received,
 * @log_priority: string log priority to be set.
 *
 * Implements the get method for the log_priority property of the
 * com.ubuntu.Upstart interface.
 *
 * Called to change the init daemon's current logging level to that given
 * as a string in @log_priority.  If the string is not recognised, the
 * com.ubuntu.Upstart.Error.InvalidLogPriority error will be returned.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_set_log_priority (void *          data,
			  NihDBusMessage *message,
			  const char *    log_priority)
{
	nih_assert (message != NULL);
	nih_assert (log_priority != NULL);

	if (! control_check_permission (message)) {
		nih_dbus_error_raise_printf (
			DBUS_INTERFACE_UPSTART ".Error.PermissionDenied",
			_("You do not have permission to set log priority"));
		return -1;
	}

	if (! strcmp (log_priority, "debug")) {
		nih_log_set_priority (NIH_LOG_DEBUG);

	} else if (! strcmp (log_priority, "info")) {
		nih_log_set_priority (NIH_LOG_INFO);

	} else if (! strcmp (log_priority, "message")) {
		nih_log_set_priority (NIH_LOG_MESSAGE);

	} else if (! strcmp (log_priority, "warn")) {
		nih_log_set_priority (NIH_LOG_WARN);

	} else if (! strcmp (log_priority, "error")) {
		nih_log_set_priority (NIH_LOG_ERROR);

	} else if (! strcmp (log_priority, "fatal")) {
		nih_log_set_priority (NIH_LOG_FATAL);

	} else {
		nih_dbus_error_raise (DBUS_ERROR_INVALID_ARGS,
				      _("The log priority given was not recognised"));
		return -1;
	}

	return 0;
}

/**
 * control_get_bus_type:
 *
 * Determine D-Bus bus type to connect to.
 *
 * Returns: Type of D-Bus bus to connect to.
 **/
DBusBusType
control_get_bus_type (void)
{
	return (use_session_bus || user_mode) 
		? DBUS_BUS_SESSION
		: DBUS_BUS_SYSTEM;
}

/**
 * control_notify_disk_writeable:
 * @data: not used,
 * @message: D-Bus connection and message received,
 *
 * Implements the NotifyDiskWriteable method of the
 * com.ubuntu.Upstart interface.
 *
 * Called to flush the job logs for all jobs that ended before the log
 * disk became writeable.
 *
 * Notes: Session Inits are permitted to make this call. In the common
 * case of starting a Session Init as a child of a Display Manager this
 * is somewhat meaningless, but it does mean that if a Session Init were
 * started from a system job, behaviour would be as expected.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_notify_disk_writeable (void   *data,
		     NihDBusMessage *message)
{
	int       ret;
	Session  *session;

	nih_assert (message != NULL);

	if (! control_check_permission (message)) {
		nih_dbus_error_raise_printf (
			DBUS_INTERFACE_UPSTART ".Error.PermissionDenied",
			_("You do not have permission to notify disk is writeable"));
		return -1;
	}

	/* Get the relevant session */
	session = session_from_dbus (NULL, message);

	/* "nop" when run from a chroot */
	if (session && session->chroot)
		return 0;

	ret = log_clear_unflushed ();

	if (ret < 0) {
		nih_error_raise_system ();
		return -1;
	}

	return 0;
}

/**
 * control_notify_dbus_address:
 * @data: not used,
 * @message: D-Bus connection and message received,
 * @address: Address of D-Bus to connect to.
 *
 * Implements the NotifyDBusAddress method of the
 * com.ubuntu.Upstart interface.
 *
 * Called to allow the Session Init to connect to the D-Bus
 * Session Bus when available.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_notify_dbus_address (void            *data,
			     NihDBusMessage  *message,
			     const char      *address)
{
	nih_assert (message);
	nih_assert (address);

	if (getpid () == 1) {
		nih_dbus_error_raise_printf (
			DBUS_INTERFACE_UPSTART ".Error.PermissionDenied",
			_("Not permissible to notify D-Bus address for PID 1"));
		return -1;
	}

	if (! control_check_permission (message)) {
		nih_dbus_error_raise_printf (
			DBUS_INTERFACE_UPSTART ".Error.PermissionDenied",
			_("You do not have permission to notify D-Bus address"));
		return -1;
	}

	/* Ignore as already connected */
	if (control_bus)
		return 0;

	control_bus_address = nih_strdup (NULL, address);
	if (! control_bus_address) {
		nih_dbus_error_raise_printf (DBUS_ERROR_NO_MEMORY,
				_("Out of Memory"));
		return -1;
	}

	if (control_bus_open () < 0)
		return -1;

	return 0;
}

/**
 * control_notify_cgroup_manager_address:
 * @data: not used,
 * @message: D-Bus connection and message received,
 * @address: D-Bus address that cgroup manager is connected to.
 *
 * Implements the NotifyCGroupManagerAddress method of the
 * com.ubuntu.Upstart interface.
 *
 * Called to allow the cgroup manager to be contacted,
 * thus enabling the cgroup stanza.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_notify_cgroup_manager_address (void            *data,
				       NihDBusMessage  *message,
				       const char      *address)
{
	nih_assert (message);
	nih_assert (address);

	if (! control_check_permission (message)) {
		nih_dbus_error_raise_printf (
			DBUS_INTERFACE_UPSTART ".Error.PermissionDenied",
			_("You do not have permission to notify cgroup manager address"));
		return -1;
	}

#ifdef ENABLE_CGROUPS
	if (! cgroup_support_enabled ())
		return 0;

	/* Already called */
	if (cgroup_manager_available ())
		return 0;

	if (! cgroup_manager_set_address (address)) {
		nih_dbus_error_raise_printf (DBUS_ERROR_NO_MEMORY,
				_("Out of Memory"));
		return -1;
	}

	nih_debug ("set cgroup manager address");

	if (! job_class_induct_jobs ()) {
		nih_dbus_error_raise_printf (DBUS_ERROR_NO_MEMORY,
				_("Out of Memory"));
		return -1;
	}

#else
	nih_debug ("cgroup support not available");
#endif /* ENABLE_CGROUPS */

	return 0;
}

/**
 * control_bus_flush:
 *
 * Drain any remaining messages in the D-Bus queue.
 **/
static void
control_bus_flush (void)
{
	control_init ();

	if (! control_bus)
		return;

	while (dbus_connection_dispatch (control_bus) == DBUS_DISPATCH_DATA_REMAINS)
		;
}

/**
 * control_prepare_reexec:
 *
 * Prepare for a re-exec by allowing the bus connection to be retained
 * over re-exec and clearing all queued messages.
 **/
void
control_prepare_reexec (void)
{
	control_init ();

	/* Necessary to disallow further commands but also to allow the
	 * new instance to open the control server.
	 */
	if (control_server)
		control_server_close ();

	control_bus_flush ();

}


/**
 * control_conn_to_index:
 *
 * @connection: D-Bus connection.
 *
 * Convert a control (DBusConnection) connection to an index number
 * the list of control connections.
 *
 * Returns: connection index, or -1 on error.
 **/
int
control_conn_to_index (const DBusConnection *connection)
{
	int conn_index = 0;
	int found = FALSE;

	nih_assert (connection);

	NIH_LIST_FOREACH (control_conns, iter) {
		NihListEntry    *entry = (NihListEntry *)iter;
		DBusConnection  *conn = (DBusConnection *)entry->data;

		if (connection == conn) {
			found = TRUE;
			break;
		}

		conn_index++;
	}
	if (! found)
		return -1;

	return conn_index;
}

/**
 * control_conn_from_index:
 *
 * @conn_index: control connection index number.
 *
 * Lookup control connection based on index number.
 *
 * Returns: existing connection on success, or NULL if connection
 * not found.
 **/
DBusConnection *
control_conn_from_index (int conn_index)
{
	int i = 0;

	nih_assert (conn_index >= 0);
	nih_assert (control_conns);

	NIH_LIST_FOREACH (control_conns, iter) {
		NihListEntry    *entry = (NihListEntry *)iter;
		DBusConnection  *conn = (DBusConnection *)entry->data;

		if (i == conn_index)
			return conn;
		i++;
	}

	return NULL;
}

/**
 * control_bus_release_name:
 *
 * Unregister well-known D-Bus name.
 *
 * Returns: 0 on success, -1 on raised error.
 **/
int
control_bus_release_name (void)
{
	DBusError  error;
	int        ret;

	if (! control_bus)
		return 0;

	dbus_error_init (&error);
	ret = dbus_bus_release_name (control_bus,
				     DBUS_SERVICE_UPSTART,
				     &error);
	if (ret < 0) {
		nih_dbus_error_raise (error.name, error.message);
		dbus_error_free (&error);
		return -1;
	}

	return 0;
}

/**
 * control_get_state:
 *
 * @data: not used,
 * @message: D-Bus connection and message received,
 * @state: output string returned to client.
 *
 * Convert internal state to JSON string.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_get_state (void           *data,
		   NihDBusMessage  *message,
		   char           **state)
{
	Session  *session;
	size_t    len;

	nih_assert (message);
	nih_assert (state);

	if (! control_check_permission (message)) {
		nih_dbus_error_raise_printf (
			DBUS_INTERFACE_UPSTART ".Error.PermissionDenied",
			_("You do not have permission to request state"));
		return -1;
	}

	/* Get the relevant session */
	session = session_from_dbus (NULL, message);

	/* We don't want chroot sessions snooping outside their domain.
	 *
	 * Ideally, we'd allow them to query their own session, but the
	 * current implementation doesn't lend itself to that.
	 */
	if (session && session->chroot) {
		nih_warn (_("Ignoring state query from chroot session"));
		return 0;
	}

	if (state_to_string (state, &len) < 0)
		goto error;

	nih_ref (*state, message);

	return 0;

error:
	nih_dbus_error_raise_printf (DBUS_ERROR_NO_MEMORY,
			_("Out of Memory"));
	return -1;
}

/**
 * control_restart:
 *
 * @data: not used,
 * @message: D-Bus connection and message received.
 *
 * Implements the Restart method of the com.ubuntu.Upstart
 * interface.
 *
 * Called to request that Upstart performs a stateful re-exec.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_restart (void           *data,
		 NihDBusMessage *message)
{
	Session  *session;

	nih_assert (message != NULL);

	if (! control_check_permission (message)) {
		nih_dbus_error_raise_printf (
			DBUS_INTERFACE_UPSTART ".Error.PermissionDenied",
			_("You do not have permission to request restart"));
		return -1;
	}

	/* Get the relevant session */
	session = session_from_dbus (NULL, message);

	/* Chroot sessions must not be able to influence
	 * the outside system.
	 *
	 * Making this a NOP is safe since it is the Upstart outside the
	 * chroot which manages all chroot jobs.
	 */
	if (session && session->chroot) {
		nih_warn (_("Ignoring restart request from chroot session"));
		return 0;
	}

	nih_info (_("Restarting"));

	stateful_reexec ();

	return 0;
}

/**
 * control_notify_event_emitted
 *
 * @event: Event.
 *
 * Re-emits an event over DBUS using the EventEmitted signal
 **/
void
control_notify_event_emitted (Event *event)
{
	nih_assert (event != NULL);

	control_init ();

	NIH_LIST_FOREACH (control_conns, iter) {
		NihListEntry   *entry = (NihListEntry *)iter;
		DBusConnection *conn = (DBusConnection *)entry->data;

		NIH_ZERO (control_emit_event_emitted (conn, DBUS_PATH_UPSTART,
							    event->name, event->env));
	}
}

/**
 * control_notify_restarted
 *
 * DBUS signal sent when upstart has re-executed itself.
 **/
void
control_notify_restarted (void)
{
	control_init ();

	NIH_LIST_FOREACH (control_conns, iter) {
		NihListEntry   *entry = (NihListEntry *)iter;
		DBusConnection *conn = (DBusConnection *)entry->data;

		NIH_ZERO (control_emit_restarted (conn, DBUS_PATH_UPSTART));
	}
}

/**
 * control_set_env_list:
 *
 * @data: not used,
 * @message: D-Bus connection and message received,
 * @job_details: name and instance of job to apply operation to,
 * @vars: array of name[/value] pairs of environment variables to set,
 * @replace: TRUE if @name should be overwritten if already set, else
 *  FALSE.
 *
 * Implements the SetEnvList method of the com.ubuntu.Upstart
 * interface.
 *
 * Called to request Upstart store one or more name/value pairs.
 *
 * If @job_details is empty, change will be applied to all job
 * environments, else only apply changes to specific job environment
 * encoded within @job_details.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_set_env_list (void            *data,
		      NihDBusMessage  *message,
		      char * const    *job_details,
		      char * const    *vars,
		      int              replace)
{
	Session         *session;
	Job             *job = NULL;
	char            *job_name = NULL;
	char            *instance = NULL;
	char * const    *var;

	nih_assert (message);
	nih_assert (job_details);
	nih_assert (vars);

	if (! control_check_permission (message)) {
		nih_dbus_error_raise_printf (
			DBUS_INTERFACE_UPSTART ".Error.PermissionDenied",
			_("You do not have permission to modify job environment"));
		return -1;
	}

	if (getpid () == 1) {
		nih_dbus_error_raise_printf (
			DBUS_INTERFACE_UPSTART ".Error.PermissionDenied",
			_("Not permissible to modify PID 1 job environment"));
		return -1;
	}

	if (job_details[0]) {
		job_name = job_details[0];

		/* this can be a null value */
		instance = job_details[1];
	}

	/* Verify that job name is valid */
	if (job_name && ! strlen (job_name)) {
		nih_dbus_error_raise_printf (DBUS_ERROR_INVALID_ARGS,
					     _("Job may not be empty string"));
		return -1;
	}

	/* Get the relevant session */
	session = session_from_dbus (NULL, message);

	/* Chroot sessions must not be able to influence
	 * the outside system.
	 */
	if (session && session->chroot) {
		nih_warn (_("Ignoring set env request from chroot session"));
		return 0;
	}

	/* Lookup the job */
	control_get_job (session, job, job_name, instance);

	for (var = vars; var && *var; var++) {
		nih_local char *envvar = NULL;

		if (! *var) {
			nih_dbus_error_raise_printf (DBUS_ERROR_INVALID_ARGS,
					_("Variable may not be empty string"));
			return -1;
		}

		/* If variable does not contain a delimiter, add one to ensure
		 * it gets entered into the job environment table. Without the
		 * delimiter, the variable will be silently ignored unless it's
		 * already set in inits environment. But in that case there is
		 * no point in setting such a variable to its already existing
		 * value.
		 */
		if (! strchr (*var, '=')) {
			envvar = NIH_MUST (nih_sprintf (NULL, "%s=", *var));
		} else {
			envvar = NIH_MUST (nih_strdup (NULL, *var));
		}

		if (job) {
			/* Modify job-specific environment */
			nih_assert (job->env);

			NIH_MUST (environ_add (&job->env, job, NULL, replace, envvar));
		} else if (job_class_environment_set (envvar, replace) < 0) {
			nih_return_no_memory_error (-1);
		}
	}

	return 0;
}

/**
 * control_set_env:
 *
 * @data: not used,
 * @message: D-Bus connection and message received,
 * @job_details: name and instance of job to apply operation to,
 * @var: name[/value] pair of environment variable to set,
 * @replace: TRUE if @name should be overwritten if already set, else
 *  FALSE.
 *
 * Implements the SetEnv method of the com.ubuntu.Upstart
 * interface.
 *
 * Called to request Upstart store a particular name/value pair.
 *
 * If @job_details is empty, change will be applied to all job
 * environments, else only apply changes to specific job environment
 * encoded within @job_details.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_set_env (void            *data,
		 NihDBusMessage  *message,
		 char * const    *job_details,
		 const char      *var,
		 int              replace)
{
	nih_local char **vars = NULL;
	
	if (! var) {
		nih_dbus_error_raise_printf (DBUS_ERROR_INVALID_ARGS,
					_("Variable may not be empty string"));
		return -1;
	}

	vars = NIH_MUST (nih_str_array_new (NULL));

	NIH_MUST (nih_str_array_add (&vars, NULL, NULL, var));

	return control_set_env_list (data, message, job_details, vars, replace);
}

/**
 * control_unset_env_list:
 *
 * @data: not used,
 * @message: D-Bus connection and message received,
 * @job_details: name and instance of job to apply operation to,
 * @names: array of variables to clear from the job environment array.
 *
 * Implements the UnsetEnvList method of the com.ubuntu.Upstart
 * interface.
 *
 * Called to request Upstart remove one or more variables from the job
 * environment array.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_unset_env_list (void            *data,
			NihDBusMessage  *message,
			char * const    *job_details,
			char * const    *names)
{
	Session         *session;
	Job             *job = NULL;
	char            *job_name = NULL;
	char            *instance = NULL;
	char * const    *name;

	nih_assert (message);
	nih_assert (job_details);
	nih_assert (names);

	if (! control_check_permission (message)) {
		nih_dbus_error_raise_printf (
			DBUS_INTERFACE_UPSTART ".Error.PermissionDenied",
			_("You do not have permission to modify job environment"));
		return -1;
	}

	if (getpid () == 1) {
		nih_dbus_error_raise_printf (
			DBUS_INTERFACE_UPSTART ".Error.PermissionDenied",
			_("Not permissible to modify PID 1 job environment"));
		return -1;
	}

	if (job_details[0]) {
		job_name = job_details[0];

		/* this can be a null value */
		instance = job_details[1];
	}

	/* Verify that job name is valid */
	if (job_name && ! strlen (job_name)) {
		nih_dbus_error_raise_printf (DBUS_ERROR_INVALID_ARGS,
					     _("Job may not be empty string"));
		return -1;
	}

	/* Get the relevant session */
	session = session_from_dbus (NULL, message);

	/* Chroot sessions must not be able to influence
	 * the outside system.
	 */
	if (session && session->chroot) {
		nih_warn (_("Ignoring unset env request from chroot session"));
		return 0;
	}

	/* Lookup the job */
	control_get_job (session, job, job_name, instance);

	for (name = names; name && *name; name++) {
		if (! *name) {
			nih_dbus_error_raise_printf (DBUS_ERROR_INVALID_ARGS,
					_("Variable may not be empty string"));
			return -1;
		}

		if (job) {
			/* Modify job-specific environment */
			nih_assert (job->env);

			if (! environ_remove (&job->env, job, NULL, *name))
				return -1;
		} else if (job_class_environment_unset (*name) < 0) {
			goto error;
		}
	}

	return 0;

error:
	nih_dbus_error_raise_printf (DBUS_ERROR_INVALID_ARGS,
			"%s: %s",
			_("No such variable"), *name);
	return -1;
}

/**
 * control_unset_env:
 *
 * @data: not used,
 * @message: D-Bus connection and message received,
 * @job_details: name and instance of job to apply operation to,
 * @name: variable to clear from the job environment array.
 *
 * Implements the UnsetEnv method of the com.ubuntu.Upstart
 * interface.
 *
 * Called to request Upstart remove a particular variable from the job
 * environment array.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_unset_env (void            *data,
		   NihDBusMessage  *message,
		   char * const    *job_details,
		   const char      *name)
{
	nih_local char **names = NULL;

	if (! name) {
		nih_dbus_error_raise_printf (DBUS_ERROR_INVALID_ARGS,
					_("Variable may not be empty string"));
		return -1;
	}
	
	names = NIH_MUST (nih_str_array_new (NULL));

	NIH_MUST (nih_str_array_add (&names, NULL, NULL, name));

	return control_unset_env_list (data, message, job_details, names);
}

/**
 * control_get_env:
 *
 * @data: not used,
 * @message: D-Bus connection and message received,
 * @job_details: name and instance of job to apply operation to,
 * @name: name of environment variable to retrieve,
 * @value: value of @name.
 *
 * Implements the GetEnv method of the com.ubuntu.Upstart
 * interface.
 *
 * Called to obtain the value of a specified job environment variable.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_get_env (void             *data,
		 NihDBusMessage   *message,
		 char * const     *job_details,
		 const char       *name,
		 char            **value)
{
	Session     *session;
	const char  *tmp;
	Job         *job = NULL;
	char        *job_name = NULL;
	char        *instance = NULL;

	nih_assert (message != NULL);
	nih_assert (job_details);

	if (! control_check_permission (message)) {
		nih_dbus_error_raise_printf (
			DBUS_INTERFACE_UPSTART ".Error.PermissionDenied",
			_("You do not have permission to query job environment"));
		return -1;
	}

	if (! name || ! *name) {
		nih_dbus_error_raise_printf (DBUS_ERROR_INVALID_ARGS,
				_("Variable may not be empty string"));
		return -1;
	}

	if (job_details[0]) {
		job_name = job_details[0];

		/* this can be a null value */
		instance = job_details[1];
	}

	/* Verify that job name is valid */
	if (job_name && ! strlen (job_name)) {
		nih_dbus_error_raise_printf (DBUS_ERROR_INVALID_ARGS,
					     _("Job may not be empty string"));
		return -1;
	}

	/* Get the relevant session */
	session = session_from_dbus (NULL, message);

	/* Chroot sessions must not be able to influence
	 * the outside system.
	 */
	if (session && session->chroot) {
		nih_warn (_("Ignoring get env request from chroot session"));
		return 0;
	}

	/* Lookup the job */
	control_get_job (session, job, job_name, instance);

	if (job) {
		tmp = environ_get (job->env, name);
		if (! tmp)
			goto error;

		*value = nih_strdup (message, tmp);
		if (! *value)
			nih_return_no_memory_error (-1);

		return 0;
	}

	tmp = job_class_environment_get (name);

	if (! tmp)
		goto error;

	*value = nih_strdup (message, tmp);
	if (! *value)
		nih_return_no_memory_error (-1);

	return 0;

error:
	nih_dbus_error_raise_printf (DBUS_ERROR_INVALID_ARGS,
			"%s: %s",
			_("No such variable"), name);
	return -1;
}

/**
 * control_list_env:
 *
 * @data: not used,
 * @message: D-Bus connection and message received,
 * @job_details: name and instance of job to apply operation to,
 * @env: pointer to array of all job environment variables.
 *
 * Implements the ListEnv method of the com.ubuntu.Upstart
 * interface.
 *
 * Called to obtain an unsorted array of all environment variables
 * that will be set in a jobs environment.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_list_env (void             *data,
		 NihDBusMessage    *message,
		 char * const      *job_details,
		 char            ***env)
{
	Session   *session;
	Job       *job = NULL;
	char      *job_name = NULL;
	char      *instance = NULL;

	nih_assert (message);
	nih_assert (job_details);
	nih_assert (env);

	if (! control_check_permission (message)) {
		nih_dbus_error_raise_printf (
			DBUS_INTERFACE_UPSTART ".Error.PermissionDenied",
			_("You do not have permission to query job environment"));
		return -1;
	}

	if (job_details[0]) {
		job_name = job_details[0];

		/* this can be a null value */
		instance = job_details[1];
	}

	/* Verify that job name is valid */
	if (job_name && ! strlen (job_name)) {
		nih_dbus_error_raise_printf (DBUS_ERROR_INVALID_ARGS,
					     _("Job may not be empty string"));
		return -1;
	}

	/* Get the relevant session */
	session = session_from_dbus (NULL, message);

	/* Lookup the job */
	control_get_job (session, job, job_name, instance);

	if (job) {
		*env = nih_str_array_copy (job, NULL, job->env);
		if (! *env)
			nih_return_no_memory_error (-1);

		return 0;
	}

	*env = job_class_environment_get_all (message);
	if (! *env)
		nih_return_no_memory_error (-1);

	return 0;
}

/**
 * control_reset_env:
 *
 * @data: not used,
 * @message: D-Bus connection and message received,
 * @job_details: name and instance of job to apply operation to.
 *
 * Implements the ResetEnv method of the com.ubuntu.Upstart
 * interface.
 *
 * Called to reset the environment all subsequent jobs will run in to
 * the default minimal environment.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_reset_env (void           *data,
		 NihDBusMessage   *message,
		 char * const    *job_details)
{
	Session    *session;
	Job        *job = NULL;
	char       *job_name = NULL;
	char       *instance = NULL;

	nih_assert (message);
	nih_assert (job_details);

	if (! control_check_permission (message)) {
		nih_dbus_error_raise_printf (
			DBUS_INTERFACE_UPSTART ".Error.PermissionDenied",
			_("You do not have permission to modify job environment"));
		return -1;
	}

	if (getpid () == 1) {
		nih_dbus_error_raise_printf (
			DBUS_INTERFACE_UPSTART ".Error.PermissionDenied",
			_("Not permissible to modify PID 1 job environment"));
		return -1;
	}

	if (job_details[0]) {
		job_name = job_details[0];

		/* this can be a null value */
		instance = job_details[1];
	}

	/* Verify that job name is valid */
	if (job_name && ! strlen (job_name)) {
		nih_dbus_error_raise_printf (DBUS_ERROR_INVALID_ARGS,
					     _("Job may not be empty string"));
		return -1;
	}

	/* Get the relevant session */
	session = session_from_dbus (NULL, message);

	/* Chroot sessions must not be able to influence
	 * the outside system.
	 */
	if (session && session->chroot) {
		nih_warn (_("Ignoring reset env request from chroot session"));
		return 0;
	}

	/* Lookup the job */
	control_get_job (session, job, job_name, instance);


	if (job) {
		size_t len;
		if (job->env) {
			nih_free (job->env);
			job->env = NULL;
		}

		job->env = job_class_environment (job, job->class, &len);
		if (! job->env)
			nih_return_system_error (-1);

		return 0;
	}

	job_class_environment_reset ();

	return 0;
}

/**
 * control_get_origin_uid:
 * @message: D-Bus connection and message received,
 * @uid: returned uid value.
 *
 * Returns TRUE: if @uid now contains uid corresponding to @message,
 * else FALSE.
 **/
static int
control_get_origin_uid (NihDBusMessage *message, uid_t *uid)
{
	DBusError       dbus_error;
	unsigned long   unix_user = 0;
	const char     *sender;

	nih_assert (message);
	nih_assert (uid);

	dbus_error_init (&dbus_error);

	if (! message->message || ! message->connection)
		return FALSE;

	sender = dbus_message_get_sender (message->message);
	if (sender) {
		unix_user = dbus_bus_get_unix_user (message->connection, sender,
						    &dbus_error);
		if (unix_user == (unsigned long)-1) {
			dbus_error_free (&dbus_error);
			return FALSE;
		}
	} else {
		if (! dbus_connection_get_unix_user (message->connection,
						     &unix_user)) {
			return FALSE;
		}
	}

	*uid = (uid_t)unix_user;

	return TRUE;
}

/**
 * control_check_permission:
 *
 * @message: D-Bus connection and message received.
 *
 * Determine if caller should be allowed to make a control request.
 *
 * Note that these permission checks rely on D-Bus to limit
 * session bus access to the same user.
 *
 * Returns: TRUE if permission is granted, else FALSE.
 **/
static int
control_check_permission (NihDBusMessage *message)
{
	int    ret;
	uid_t  uid;
	pid_t  pid;
	uid_t  origin_uid = 0;

	nih_assert (message);

	uid = getuid ();
	pid = getpid ();

	ret = control_get_origin_uid (message, &origin_uid);

	/* Its possible that D-Bus might be unable to determine the user
	 * making the request. In this case, deny the request unless
	 * we're running as a Session Init or via the test harness.
	 */
	if ((ret && origin_uid == uid) || user_mode || (uid && pid != 1))
		return TRUE;

	return FALSE;
}

/**
 * control_session_file_create:
 *
 * Create session file if possible.
 *
 * Errors are not fatal - the file is just not created.
 **/
static void
control_session_file_create (void)
{
	nih_local char *session_dir = NULL;
	FILE           *f;
	int             ret;

	nih_assert (control_server_address);

	session_dir = get_session_dir ();

	if (! session_dir)
		return;

	NIH_MUST (nih_strcat_sprintf (&session_file, NULL, "%s/%d%s",
				session_dir, (int)getpid (), SESSION_EXT));

	f = fopen (session_file, "w");
	if (! f) {
		nih_error ("%s: %s", _("unable to create session file"), session_file);
		return;
	}

	ret = fprintf (f, SESSION_ENV "=%s\n", control_server_address);

	if (ret < 0)
		nih_error ("%s: %s", _("unable to write session file"), session_file);

	fclose (f);
}

/**
 * control_session_file_remove:
 *
 * Delete session file.
 *
 * Errors are not fatal.
 **/
static void
control_session_file_remove (void)
{
	if (session_file)
		(void)unlink (session_file);
}

/**
 * control_session_end:
 *
 * @data: not used,
 * @message: D-Bus connection and message received.
 *
 * Implements the EndSession method of the com.ubuntu.Upstart
 * interface.
 *
 * Called to request that Upstart stop all jobs and exit. Only
 * appropriate when running as a Session Init and user wishes to
 * 'logout'.
 *
 * Returns: zero on success, negative value on raised error.
 **/
int
control_end_session (void             *data,
		     NihDBusMessage   *message)
{
	Session  *session;

	nih_assert (message);

	/* Not supported at the system level */
	if (getpid () == 1)
		return 0;

	if (! control_check_permission (message)) {
		nih_dbus_error_raise_printf (
			DBUS_INTERFACE_UPSTART ".Error.PermissionDenied",
			_("You do not have permission to end session"));
		return -1;
	}

	/* Get the relevant session */
	session = session_from_dbus (NULL, message);

	if (session && session->chroot) {
		nih_warn (_("Ignoring session end request from chroot session"));
		return 0;
	}

	quiesce (QUIESCE_REQUESTER_SESSION);

	return 0;
}

/**
 * control_serialise_bus_address:
 *
 * Convert control_bus_address into JSON representation.
 *
 * Returns: JSON string representing control_bus_address or NULL if
 * control_bus_address not set or on error.
 *
 * Note: If NULL is returned, check the value of control_bus_address
 * itself to determine if the error is real.
 **/
json_object *
control_serialise_bus_address (void)
{
	control_init ();

	/* A NULL return represents a JSON null */
	return control_bus_address
		? json_object_new_string (control_bus_address)
		: NULL;
}

/**
 * control_deserialise_bus_address:
 *
 * @json: root of JSON-serialised state.
 *
 * Convert JSON representation of control_bus_address back into a native
 * string.
 *
 * Returns: 0 on success, -1 on error.
 **/
int
control_deserialise_bus_address (json_object *json)
{
	const char  *address;

	nih_assert (json);
	nih_assert (! control_bus_address);

	control_init ();

	/* control_bus_address was never set */
	if (state_check_json_type (json, null))
		return 0;

	if (! state_check_json_type (json, string))
		goto error;

	address = json_object_get_string (json);
	if (! address)
		goto error;

	control_bus_address = nih_strdup (NULL, address);
	if (! control_bus_address)
		goto error;

	return 0;

error:
	return -1;
}