File: dbus.c

package info (click to toggle)
ofono 2.18-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 12,064 kB
  • sloc: ansic: 224,979; sh: 5,012; python: 4,040; makefile: 956
file content (1938 lines) | stat: -rw-r--r-- 45,997 bytes parent folder | download | duplicates (4)
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
/*
 * Embedded Linux library
 * Copyright (C) 2011-2014  Intel Corporation
 *
 * SPDX-License-Identifier: LGPL-2.1-or-later
 */

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

#define _GNU_SOURCE
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netdb.h>
#include <errno.h>

#include "util.h"
#include "io.h"
#include "idle.h"
#include "queue.h"
#include "hashmap.h"
#include "dbus.h"
#include "private.h"
#include "useful.h"
#include "dbus-private.h"

#define DEFAULT_SYSTEM_BUS_ADDRESS "unix:path=/var/run/dbus/system_bus_socket"

#define DBUS_SERVICE_DBUS	"org.freedesktop.DBus"

#define DBUS_PATH_DBUS		"/org/freedesktop/DBus"

#define DBUS_MAXIMUM_MATCH_RULE_LENGTH	1024

enum auth_state {
	WAITING_FOR_OK,
	WAITING_FOR_AGREE_UNIX_FD,
	SETUP_DONE
};

struct l_dbus_ops {
	char version;
	bool (*send_message)(struct l_dbus *bus,
				struct l_dbus_message *message);
	struct l_dbus_message *(*recv_message)(struct l_dbus *bus);
	void (*free)(struct l_dbus *bus);
	struct _dbus_name_ops name_ops;
	struct _dbus_filter_ops filter_ops;
	uint32_t (*name_acquire)(struct l_dbus *dbus, const char *name,
				bool allow_replacement, bool replace_existing,
				bool queue, l_dbus_name_acquire_func_t callback,
				void *user_data);
};

struct l_dbus {
	struct l_io *io;
	char *guid;
	bool negotiate_unix_fd;
	bool support_unix_fd;
	bool is_ready;
	char *unique_name;
	unsigned int next_id;
	uint32_t next_serial;
	struct l_queue *message_queue;
	struct l_hashmap *message_list;
	struct l_hashmap *signal_list;
	l_dbus_ready_func_t ready_handler;
	l_dbus_destroy_func_t ready_destroy;
	void *ready_data;
	l_dbus_disconnect_func_t disconnect_handler;
	l_dbus_destroy_func_t disconnect_destroy;
	void *disconnect_data;
	l_dbus_debug_func_t debug_handler;
	l_dbus_destroy_func_t debug_destroy;
	void *debug_data;
	struct _dbus_object_tree *tree;
	struct _dbus_name_cache *name_cache;
	struct _dbus_filter *filter;
	bool name_notify_enabled;

	const struct l_dbus_ops *driver;
};

struct l_dbus_classic {
	struct l_dbus super;
	void *auth_command;
	enum auth_state auth_state;
	bool skip_hello;
	struct l_hashmap *match_strings;
	int *fd_buf;
	unsigned int num_fds;
};

struct message_callback {
	uint32_t serial;
	struct l_dbus_message *message;
	l_dbus_message_func_t callback;
	l_dbus_destroy_func_t destroy;
	void *user_data;
};

struct signal_callback {
	unsigned int id;
	l_dbus_message_func_t callback;
	l_dbus_destroy_func_t destroy;
	void *user_data;
};

static void message_queue_destroy(void *data)
{
	struct message_callback *callback = data;

	l_dbus_message_unref(callback->message);

	if (callback->destroy)
		callback->destroy(callback->user_data);

	l_free(callback);
}

static void message_list_destroy(void *value)
{
	message_queue_destroy(value);
}

static void signal_list_destroy(void *value)
{
	struct signal_callback *callback = value;

	if (callback->destroy)
		callback->destroy(callback->user_data);

	l_free(callback);
}

static bool message_write_handler(struct l_io *io, void *user_data)
{
	struct l_dbus *dbus = user_data;
	struct l_dbus_message *message;
	struct message_callback *callback;
	const void *header, *body;
	size_t header_size, body_size;

	callback = l_queue_pop_head(dbus->message_queue);
	if (!callback)
		return false;

	message = callback->message;
	if (_dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_METHOD_CALL &&
			callback->callback == NULL)
		l_dbus_message_set_no_reply(message, true);

	_dbus_message_set_serial(message, callback->serial);

	if (!dbus->driver->send_message(dbus, message)) {
		message_queue_destroy(callback);
		return false;
	}

	header = _dbus_message_get_header(message, &header_size);
	body = _dbus_message_get_body(message, &body_size);
	l_util_hexdump_two(false, header, header_size, body, body_size,
				dbus->debug_handler, dbus->debug_data);

	if (callback->callback == NULL) {
		message_queue_destroy(callback);
		goto done;
	}

	l_hashmap_insert(dbus->message_list,
				L_UINT_TO_PTR(callback->serial), callback);

done:
	if (l_queue_isempty(dbus->message_queue))
		return false;

	/* Only continue sending messages if the connection is ready */
	return dbus->is_ready;
}

static void handle_method_return(struct l_dbus *dbus,
					struct l_dbus_message *message)
{
	struct message_callback *callback;
	uint32_t reply_serial;

	reply_serial = _dbus_message_get_reply_serial(message);
	if (reply_serial == 0)
		return;

	callback = l_hashmap_remove(dbus->message_list,
					L_UINT_TO_PTR(reply_serial));
	if (!callback)
		return;

	if (callback->callback)
		callback->callback(message, callback->user_data);

	message_queue_destroy(callback);
}

static void handle_error(struct l_dbus *dbus, struct l_dbus_message *message)
{
	struct message_callback *callback;
	uint32_t reply_serial;

	reply_serial = _dbus_message_get_reply_serial(message);
	if (reply_serial == 0)
		return;

	callback = l_hashmap_remove(dbus->message_list,
					L_UINT_TO_PTR(reply_serial));
	if (!callback)
		return;

	if (callback->callback)
		callback->callback(message, callback->user_data);

	message_queue_destroy(callback);
}

static void process_signal(const void *key, void *value, void *user_data)
{
	struct signal_callback *callback = value;
	struct l_dbus_message *message = user_data;

	if (callback->callback)
		callback->callback(message, callback->user_data);
}

static void handle_signal(struct l_dbus *dbus, struct l_dbus_message *message)
{
	l_hashmap_foreach(dbus->signal_list, process_signal, message);
}

static bool message_read_handler(struct l_io *io, void *user_data)
{
	struct l_dbus *dbus = user_data;
	struct l_dbus_message *message;
	const void *header, *body;
	size_t header_size, body_size;
	enum dbus_message_type msgtype;

	message = dbus->driver->recv_message(dbus);
	if (!message)
		return true;

	header = _dbus_message_get_header(message, &header_size);
	body = _dbus_message_get_body(message, &body_size);
	l_util_hexdump_two(true, header, header_size, body, body_size,
				dbus->debug_handler, dbus->debug_data);

	msgtype = _dbus_message_get_type(message);

	switch (msgtype) {
	case DBUS_MESSAGE_TYPE_METHOD_RETURN:
		handle_method_return(dbus, message);
		break;
	case DBUS_MESSAGE_TYPE_ERROR:
		handle_error(dbus, message);
		break;
	case DBUS_MESSAGE_TYPE_SIGNAL:
		handle_signal(dbus, message);
		break;
	case DBUS_MESSAGE_TYPE_METHOD_CALL:
		if (!_dbus_object_tree_dispatch(dbus->tree, dbus, message)) {
			struct l_dbus_message *error;

			error = l_dbus_message_new_error(message,
					"org.freedesktop.DBus.Error.NotFound",
					"No matching method found");
			l_dbus_send(dbus, error);
		}

		break;
	}

	l_dbus_message_unref(message);

	return true;
}

static uint32_t send_message(struct l_dbus *dbus, bool priority,
				struct l_dbus_message *message,
				l_dbus_message_func_t function,
				void *user_data, l_dbus_destroy_func_t destroy)
{
	struct message_callback *callback;
	enum dbus_message_type type;
	const char *path;

	type = _dbus_message_get_type(message);

	if ((type == DBUS_MESSAGE_TYPE_METHOD_RETURN ||
				type == DBUS_MESSAGE_TYPE_ERROR) &&
			_dbus_message_get_reply_serial(message) == 0) {
		l_dbus_message_unref(message);
		return 0;
	}

	/* Default empty signature for method return messages */
	if (type == DBUS_MESSAGE_TYPE_METHOD_RETURN &&
			!l_dbus_message_get_signature(message))
		l_dbus_message_set_arguments(message, "");

	callback = l_new(struct message_callback, 1);

	callback->serial = dbus->next_serial++;
	callback->message = message;
	callback->callback = function;
	callback->destroy = destroy;
	callback->user_data = user_data;

	if (priority) {
		l_queue_push_head(dbus->message_queue, callback);

		l_io_set_write_handler(dbus->io, message_write_handler,
							dbus, NULL);

		return callback->serial;
	}

	path = l_dbus_message_get_path(message);
	if (path)
		_dbus_object_tree_signals_flush(dbus, path);

	l_queue_push_tail(dbus->message_queue, callback);

	if (dbus->is_ready)
		l_io_set_write_handler(dbus->io, message_write_handler,
							dbus, NULL);

	return callback->serial;
}

static void bus_ready(struct l_dbus *dbus)
{
	dbus->is_ready = true;

	if (dbus->ready_handler)
		dbus->ready_handler(dbus->ready_data);

	l_io_set_read_handler(dbus->io, message_read_handler, dbus, NULL);

	/* Check for messages added before the connection was ready */
	if (l_queue_isempty(dbus->message_queue))
		return;

	l_io_set_write_handler(dbus->io, message_write_handler, dbus, NULL);
}

static void hello_callback(struct l_dbus_message *message, void *user_data)
{
	struct l_dbus *dbus = user_data;
	const char *signature;
	const char *unique_name;

	signature = l_dbus_message_get_signature(message);
	if (!signature || strcmp(signature, "s")) {
		close(l_io_get_fd(dbus->io));
		return;
	}

	if (!l_dbus_message_get_arguments(message, "s", &unique_name)) {
		close(l_io_get_fd(dbus->io));
		return;
	}

	dbus->unique_name = l_strdup(unique_name);

	bus_ready(dbus);
}

static bool auth_write_handler(struct l_io *io, void *user_data)
{
	struct l_dbus_classic *classic = user_data;
	struct l_dbus *dbus = &classic->super;
	ssize_t written, len;
	int fd;

	fd = l_io_get_fd(io);

	if (!classic->auth_command)
		return false;

	len = strlen(classic->auth_command);
	if (!len)
		return false;

	written = L_TFR(send(fd, classic->auth_command, len, 0));
	if (written < 0)
		return false;

	l_util_hexdump(false, classic->auth_command, written,
					dbus->debug_handler, dbus->debug_data);

	if (written < len) {
		memmove(classic->auth_command, classic->auth_command + written,
				len + 1 - written);
		return true;
	}

	l_free(classic->auth_command);
	classic->auth_command = NULL;

	if (classic->auth_state == SETUP_DONE) {
		struct l_dbus_message *message;

		if (classic->skip_hello) {
			bus_ready(dbus);
			return true;
		}

		l_io_set_read_handler(dbus->io, message_read_handler,
							dbus, NULL);

		message = l_dbus_message_new_method_call(dbus,
							DBUS_SERVICE_DBUS,
							DBUS_PATH_DBUS,
							L_DBUS_INTERFACE_DBUS,
							"Hello");
		l_dbus_message_set_arguments(message, "");

		send_message(dbus, true, message, hello_callback, dbus, NULL);

		return true;
	}

	return false;
}

static bool auth_read_handler(struct l_io *io, void *user_data)
{
	struct l_dbus_classic *classic = user_data;
	struct l_dbus *dbus = &classic->super;
	char buffer[64];
	char *ptr, *end;
	ssize_t offset, len;
	int fd;

	fd = l_io_get_fd(io);

	ptr = buffer;
	offset = 0;

	while (1) {
		len = L_TFR(recv(fd, ptr + offset,
						sizeof(buffer) - offset,
						MSG_DONTWAIT));
		if (len < 0) {
			if (errno != EAGAIN)
				return false;

			break;
		}

		offset += len;
	}

	ptr = buffer;
	len = offset;

	if (!ptr || len < 3)
		return true;

	end = strstr(ptr, "\r\n");
	if (!end)
		return true;

	if (end - ptr + 2 != len)
		return true;

	l_util_hexdump(true, ptr, len, dbus->debug_handler, dbus->debug_data);

	*end = '\0';

	switch (classic->auth_state) {
	case WAITING_FOR_OK:
		if (!strncmp(ptr, "OK ", 3)) {
			enum auth_state state;
			const char *command;

			if (dbus->negotiate_unix_fd) {
				command = "NEGOTIATE_UNIX_FD\r\n";
				state = WAITING_FOR_AGREE_UNIX_FD;
			} else {
				command = "BEGIN\r\n";
				state = SETUP_DONE;
			}

			l_free(dbus->guid);
			dbus->guid = l_strdup(ptr + 3);

			classic->auth_command = l_strdup(command);
			classic->auth_state = state;
			break;
		} else if (!strncmp(ptr, "REJECTED ", 9)) {
			static const char *command = "AUTH ANONYMOUS\r\n";

			dbus->negotiate_unix_fd = true;

			classic->auth_command = l_strdup(command);
			classic->auth_state = WAITING_FOR_OK;
		}
		break;

	case WAITING_FOR_AGREE_UNIX_FD:
		if (!strncmp(ptr, "AGREE_UNIX_FD", 13)) {
			static const char *command = "BEGIN\r\n";

			dbus->support_unix_fd = true;

			classic->auth_command = l_strdup(command);
			classic->auth_state = SETUP_DONE;
			break;
		} else if (!strncmp(ptr, "ERROR", 5)) {
			static const char *command = "BEGIN\r\n";

			dbus->support_unix_fd = false;

			classic->auth_command = l_strdup(command);
			classic->auth_state = SETUP_DONE;
			break;
		}
		break;

	case SETUP_DONE:
		break;
	}

	l_io_set_write_handler(io, auth_write_handler, dbus, NULL);

	return true;
}

static void disconnect_handler(struct l_io *io, void *user_data)
{
	struct l_dbus *dbus = user_data;

	dbus->is_ready = false;

	l_util_debug(dbus->debug_handler, dbus->debug_data, "disconnect");

	if (dbus->disconnect_handler)
		dbus->disconnect_handler(dbus->disconnect_data);
}

static void dbus_init(struct l_dbus *dbus, int fd)
{
	dbus->io = l_io_new(fd);
	l_io_set_close_on_destroy(dbus->io, true);
	l_io_set_disconnect_handler(dbus->io, disconnect_handler, dbus, NULL);

	dbus->is_ready = false;
	dbus->next_id = 1;
	dbus->next_serial = 1;

	dbus->message_queue = l_queue_new();
	dbus->message_list = l_hashmap_new();
	dbus->signal_list = l_hashmap_new();

	dbus->tree = _dbus_object_tree_new();
}

static void classic_free(struct l_dbus *dbus)
{
	struct l_dbus_classic *classic =
		l_container_of(dbus, struct l_dbus_classic, super);
	unsigned int i;

	for (i = 0; i < classic->num_fds; i++)
		close(classic->fd_buf[i]);
	l_free(classic->fd_buf);

	l_free(classic->auth_command);
	l_hashmap_destroy(classic->match_strings, l_free);
	l_free(classic);
}

static bool classic_send_message(struct l_dbus *dbus,
					struct l_dbus_message *message)
{
	int fd = l_io_get_fd(dbus->io);
	struct msghdr msg;
	struct iovec iov[2], *iovpos;
	ssize_t r;
	int *fds = NULL;
	uint32_t num_fds = 0;
	struct cmsghdr *cmsg;
	int iovlen;

	iov[0].iov_base = _dbus_message_get_header(message, &iov[0].iov_len);
	iov[1].iov_base = _dbus_message_get_body(message, &iov[1].iov_len);

	if (dbus->support_unix_fd)
		fds = _dbus_message_get_fds(message, &num_fds);

	iovpos = iov;
	iovlen = 2;

	while (1) {
		memset(&msg, 0, sizeof(msg));
		msg.msg_iov = iovpos;
		msg.msg_iovlen = iovlen;

		if (num_fds) {
			msg.msg_control =
				alloca(CMSG_SPACE(num_fds * sizeof(int)));
			msg.msg_controllen = CMSG_LEN(num_fds * sizeof(int));

			cmsg = CMSG_FIRSTHDR(&msg);
			cmsg->cmsg_len = msg.msg_controllen;
			cmsg->cmsg_level = SOL_SOCKET;
			cmsg->cmsg_type = SCM_RIGHTS;
			memcpy(CMSG_DATA(cmsg), fds, num_fds * sizeof(int));
		}

		r = L_TFR(sendmsg(fd, &msg, 0));
		if (r < 0)
			return false;

		while ((size_t) r >= iovpos->iov_len) {
			r -= iovpos->iov_len;
			iovpos++;
			iovlen--;

			if (!iovlen)
				break;
		}

		if (!iovlen)
			break;

		iovpos->iov_base += r;
		iovpos->iov_len -= r;

		/* The FDs have been transmitted, don't retransmit */
		num_fds = 0;
	}

	return true;
}

static struct l_dbus_message *classic_recv_message(struct l_dbus *dbus)
{
	struct l_dbus_classic *classic =
		l_container_of(dbus, struct l_dbus_classic, super);
	int fd = l_io_get_fd(dbus->io);
	struct dbus_header hdr;
	struct msghdr msg;
	struct iovec iov[2], *iovpos;
	struct cmsghdr *cmsg;
	ssize_t len, r;
	void *header, *body;
	size_t header_size, body_size;
	union {
		uint8_t bytes[CMSG_SPACE(16 * sizeof(int))];
		struct cmsghdr align;
	} fd_buf;
	int *fds = NULL;
	uint32_t num_fds = 0;
	int iovlen;
	struct l_dbus_message *message;
	unsigned int i;

	len = recv(fd, &hdr, DBUS_HEADER_SIZE, MSG_PEEK | MSG_DONTWAIT);
	if (len != DBUS_HEADER_SIZE)
		return NULL;

	header_size = align_len(DBUS_HEADER_SIZE + hdr.dbus1.field_length, 8);
	header = l_malloc(header_size);

	body_size = hdr.dbus1.body_length;
	body = l_malloc(body_size);

	iov[0].iov_base = header;
	iov[0].iov_len  = header_size;
	iov[1].iov_base = body;
	iov[1].iov_len  = body_size;

	iovpos = iov;
	iovlen = 2;

	while (1) {
		memset(&msg, 0, sizeof(msg));
		msg.msg_iov = iovpos;
		msg.msg_iovlen = iovlen;
		msg.msg_control = &fd_buf;
		msg.msg_controllen = sizeof(fd_buf);

		r = L_TFR(recvmsg(fd, &msg,
					MSG_CMSG_CLOEXEC | MSG_WAITALL));
		if (r < 0)
			goto cmsg_fail;

		for (cmsg = CMSG_FIRSTHDR(&msg); cmsg;
				cmsg = CMSG_NXTHDR(&msg, cmsg)) {
			if (cmsg->cmsg_level != SOL_SOCKET ||
					cmsg->cmsg_type != SCM_RIGHTS)
				continue;

			num_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
			fds = (void *) CMSG_DATA(cmsg);

			/* Set FD_CLOEXEC on all file descriptors */
			for (i = 0; i < num_fds; i++) {
				long flags;

				flags = fcntl(fds[i], F_GETFD, NULL);
				if (flags < 0)
					continue;

				if (!(flags & FD_CLOEXEC))
					fcntl(fds[i], F_SETFD,
						flags | FD_CLOEXEC);
			}

			classic->fd_buf = l_realloc(classic->fd_buf,
						(classic->num_fds + num_fds) *
						sizeof(int));
			memcpy(classic->fd_buf + classic->num_fds, fds,
				num_fds * sizeof(int));
			classic->num_fds += num_fds;
		}

		while ((size_t) r >= iovpos->iov_len) {
			r -= iovpos->iov_len;
			iovpos++;
			iovlen--;

			if (!iovlen)
				break;
		}

		if (!iovlen)
			break;

		iovpos->iov_base += r;
		iovpos->iov_len -= r;
	}

	if (hdr.endian != DBUS_NATIVE_ENDIAN) {
		l_util_debug(dbus->debug_handler,
				dbus->debug_data, "Endianness incorrect");
		goto bad_msg;
	}

	if (hdr.version != 1) {
		l_util_debug(dbus->debug_handler,
				dbus->debug_data, "Protocol version incorrect");
		goto bad_msg;
	}

	num_fds = _dbus_message_unix_fds_from_header(header, header_size);
	if (num_fds > classic->num_fds)
		goto bad_msg;

	message = dbus_message_build(header, header_size, body, body_size,
					classic->fd_buf, num_fds);

	if (message && num_fds) {
		if (classic->num_fds > num_fds) {
			memmove(classic->fd_buf, classic->fd_buf + num_fds,
				(classic->num_fds - num_fds) * sizeof(int));
			classic->num_fds -= num_fds;
		} else {
			l_free(classic->fd_buf);

			classic->fd_buf = NULL;
			classic->num_fds = 0;
		}
	}

	if (message)
		return message;

bad_msg:
cmsg_fail:
	for (i = 0; i < classic->num_fds; i++)
		close(classic->fd_buf[i]);

	l_free(classic->fd_buf);

	classic->fd_buf = NULL;
	classic->num_fds = 0;

	l_free(header);
	l_free(body);

	return NULL;
}

static bool classic_add_match(struct l_dbus *dbus, unsigned int id,
				const struct _dbus_filter_condition *rule,
				int rule_len)
{
	struct l_dbus_classic *classic =
		l_container_of(dbus, struct l_dbus_classic, super);
	char *match_str;
	struct l_dbus_message *message;

	match_str = _dbus_filter_rule_to_str(rule, rule_len);

	l_hashmap_insert(classic->match_strings, L_UINT_TO_PTR(id), match_str);

	message = l_dbus_message_new_method_call(dbus,
						DBUS_SERVICE_DBUS,
						DBUS_PATH_DBUS,
						L_DBUS_INTERFACE_DBUS,
						"AddMatch");

	l_dbus_message_set_arguments(message, "s", match_str);

	send_message(dbus, false, message, NULL, NULL, NULL);

	return true;
}

static bool classic_remove_match(struct l_dbus *dbus, unsigned int id)
{
	struct l_dbus_classic *classic =
		l_container_of(dbus, struct l_dbus_classic, super);
	char *match_str = l_hashmap_remove(classic->match_strings,
						L_UINT_TO_PTR(id));
	struct l_dbus_message *message;

	if (!match_str)
		return false;

	message = l_dbus_message_new_method_call(dbus,
						DBUS_SERVICE_DBUS,
						DBUS_PATH_DBUS,
						L_DBUS_INTERFACE_DBUS,
						"RemoveMatch");

	l_dbus_message_set_arguments(message, "s", match_str);

	send_message(dbus, false, message, NULL, NULL, NULL);

	l_free(match_str);

	return true;
}

static void name_owner_changed_cb(struct l_dbus_message *message,
					void *user_data)
{
	struct l_dbus *dbus = user_data;
	char *name, *old, *new;

	if (!l_dbus_message_get_arguments(message, "sss", &name, &old, &new))
		return;

	_dbus_name_cache_notify(dbus->name_cache, name, new);
}

struct get_name_owner_request {
	struct l_dbus_message *message;
	struct l_dbus *dbus;
};

static void get_name_owner_reply_cb(struct l_dbus_message *reply,
					void *user_data)
{
	struct get_name_owner_request *req = user_data;
	const char *name, *owner;

	/* No name owner yet */
	if (l_dbus_message_is_error(reply))
		return;

	/* Shouldn't happen */
	if (!l_dbus_message_get_arguments(reply, "s", &owner))
		return;

	/* Shouldn't happen */
	if (!l_dbus_message_get_arguments(req->message, "s", &name))
		return;

	_dbus_name_cache_notify(req->dbus->name_cache, name, owner);
}

static bool classic_get_name_owner(struct l_dbus *bus, const char *name)
{
	struct get_name_owner_request *req;

	/* Name resolution is not performed for DBUS_SERVICE_DBUS */
	if (!strcmp(name, DBUS_SERVICE_DBUS))
		return false;

	req = l_new(struct get_name_owner_request, 1);
	req->dbus = bus;
	req->message = l_dbus_message_new_method_call(bus,
							DBUS_SERVICE_DBUS,
							DBUS_PATH_DBUS,
							L_DBUS_INTERFACE_DBUS,
							"GetNameOwner");

	l_dbus_message_set_arguments(req->message, "s", name);

	send_message(bus, false, req->message, get_name_owner_reply_cb,
			req, l_free);

	if (!bus->name_notify_enabled) {
		static struct _dbus_filter_condition rule[] = {
			{ L_DBUS_MATCH_TYPE,		"signal" },
			{ L_DBUS_MATCH_SENDER,		DBUS_SERVICE_DBUS },
			{ L_DBUS_MATCH_PATH,		DBUS_PATH_DBUS },
			{ L_DBUS_MATCH_INTERFACE,	L_DBUS_INTERFACE_DBUS },
			{ L_DBUS_MATCH_MEMBER,		"NameOwnerChanged" },
		};

		if (!bus->filter)
			bus->filter = _dbus_filter_new(bus,
						&bus->driver->filter_ops,
						bus->name_cache);

		_dbus_filter_add_rule(bus->filter, rule, L_ARRAY_SIZE(rule),
					name_owner_changed_cb, bus);

		bus->name_notify_enabled = true;
	}

	return true;
}

struct name_request {
	l_dbus_name_acquire_func_t callback;
	void *user_data;
	struct l_dbus *dbus;
};

enum dbus_name_flag {
	DBUS_NAME_FLAG_ALLOW_REPLACEMENT	= 0x1,
	DBUS_NAME_FLAG_REPLACE_EXISTING		= 0x2,
	DBUS_NAME_FLAG_DO_NOT_QUEUE		= 0x4,
};

enum dbus_name_reply {
	DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER	= 1,
	DBUS_REQUEST_NAME_REPLY_IN_QUEUE	= 2,
	DBUS_REQUEST_NAME_REPLY_EXISTS		= 3,
	DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER	= 4,
};

static void request_name_reply_cb(struct l_dbus_message *reply, void *user_data)
{
	struct name_request *req = user_data;
	bool success = false, queued = false;
	uint32_t retval;

	if (!req->callback)
		return;

	/* No name owner yet */
	if (l_dbus_message_is_error(reply))
		goto call_back;

	/* Shouldn't happen */
	if (!l_dbus_message_get_arguments(reply, "u", &retval))
		goto call_back;

	success = (retval == DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) ||
		(retval == DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER) ||
		(retval == DBUS_REQUEST_NAME_REPLY_IN_QUEUE);
	queued = (retval == DBUS_REQUEST_NAME_REPLY_IN_QUEUE);

call_back:
	req->callback(req->dbus, success, queued, req->user_data);
}

static uint32_t classic_name_acquire(struct l_dbus *dbus, const char *name,
					bool allow_replacement,
					bool replace_existing, bool queue,
					l_dbus_name_acquire_func_t callback,
					void *user_data)
{
	struct name_request *req;
	struct l_dbus_message *message;
	uint32_t flags = 0;

	req = l_new(struct name_request, 1);
	req->dbus = dbus;
	req->user_data = user_data;
	req->callback = callback;

	message = l_dbus_message_new_method_call(dbus, DBUS_SERVICE_DBUS,
							DBUS_PATH_DBUS,
							L_DBUS_INTERFACE_DBUS,
							"RequestName");

	if (allow_replacement)
		flags |= DBUS_NAME_FLAG_ALLOW_REPLACEMENT;

	if (replace_existing)
		flags |= DBUS_NAME_FLAG_REPLACE_EXISTING;

	if (!queue)
		flags |= DBUS_NAME_FLAG_DO_NOT_QUEUE;

	l_dbus_message_set_arguments(message, "su", name, flags);

	return send_message(dbus, false, message, request_name_reply_cb,
				req, free);
}

static const struct l_dbus_ops classic_ops = {
	.version = 1,
	.send_message = classic_send_message,
	.recv_message = classic_recv_message,
	.free = classic_free,
	.name_ops = {
		.get_name_owner = classic_get_name_owner,
	},
	.filter_ops = {
		.add_match = classic_add_match,
		.remove_match = classic_remove_match,
	},
	.name_acquire = classic_name_acquire,
};

static struct l_dbus *setup_dbus1(int fd, const char *guid, bool skip_hello)
{
	static const unsigned char creds = 0x00;
	char uid[6], hexuid[12], *ptr = hexuid;
	struct l_dbus *dbus;
	struct l_dbus_classic *classic;
	ssize_t written;
	unsigned int i;

	if (snprintf(uid, sizeof(uid), "%d", geteuid()) < 1) {
		close(fd);
		return NULL;
	}

	for (i = 0; i < strlen(uid); i++)
		ptr += sprintf(ptr, "%02x", uid[i]);

	/* Send special credentials-passing nul byte */
	written = L_TFR(send(fd, &creds, 1, 0));
	if (written < 1) {
		close(fd);
		return NULL;
	}

	classic = l_new(struct l_dbus_classic, 1);
	dbus = &classic->super;
	dbus->driver = &classic_ops;

	classic->match_strings = l_hashmap_new();

	dbus_init(dbus, fd);
	dbus->guid = l_strdup(guid);

	classic->auth_command = l_strdup_printf("AUTH EXTERNAL %s\r\n", hexuid);
	classic->auth_state = WAITING_FOR_OK;
	classic->skip_hello = skip_hello;

	dbus->negotiate_unix_fd = true;
	dbus->support_unix_fd = false;

	l_io_set_read_handler(dbus->io, auth_read_handler, dbus, NULL);
	l_io_set_write_handler(dbus->io, auth_write_handler, dbus, NULL);

	return dbus;
}

static struct l_dbus *setup_unix(char *params)
{
	char *path = NULL, *guid = NULL;
	bool abstract = false;
	struct sockaddr_un addr;
	size_t len;
	int fd;

	while (params) {
		char *key = strsep(&params, ",");
		char *value;

		if (!key)
			break;

		value = strchr(key, '=');
		if (!value)
			continue;

		*value++ = '\0';

		if (!strcmp(key, "path")) {
			path = value;
			abstract = false;
		} else if (!strcmp(key, "abstract")) {
			path = value;
			abstract = true;
		} else if (!strcmp(key, "guid"))
			guid = value;
	}

	if (!path)
		return NULL;

	fd = socket(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
	if (fd < 0)
		return NULL;

	memset(&addr, 0, sizeof(addr));
	addr.sun_family = AF_UNIX;

	len = strlen(path);

	if (abstract) {
		if (len > sizeof(addr.sun_path) - 1) {
			close(fd);
			return NULL;
		}

		addr.sun_path[0] = '\0';
		strncpy(addr.sun_path + 1, path, sizeof(addr.sun_path) - 2);
		len++;
	} else {
		if (len > sizeof(addr.sun_path)) {
			close(fd);
			return NULL;
		}

		strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
	}

	if (connect(fd, (struct sockaddr *) &addr,
				sizeof(addr.sun_family) + len) < 0) {
		close(fd);
		return NULL;
	}

	return setup_dbus1(fd, guid, false);
}

static bool setup_tcp_cb(struct l_io *io, void *user_data)
{
	static const unsigned char creds = 0x00;
	struct l_dbus *dbus = user_data;
	struct l_dbus_classic *classic;
	ssize_t written;
	int fd = l_io_get_fd(io);

	/* Send special credentials-passing nul byte */
	written = L_TFR(send(fd, &creds, 1, 0));
	if (written < 1) {
		l_util_debug(dbus->debug_handler, dbus->debug_handler,
						"error writing NUL byte");
		close(fd);
		return false;
	}

	dbus->driver = &classic_ops;
	dbus->negotiate_unix_fd = false;
	dbus->support_unix_fd = false;

	classic = l_container_of(dbus, struct l_dbus_classic, super);
	classic->match_strings = l_hashmap_new();
	classic->auth_command = l_strdup("AUTH ANONYMOUS\r\n");
	classic->auth_state = WAITING_FOR_OK;

	l_io_set_read_handler(dbus->io, auth_read_handler, dbus, NULL);
	l_io_set_write_handler(dbus->io, auth_write_handler, dbus, NULL);

	return auth_write_handler(dbus->io, dbus);
}

static struct l_dbus *setup_tcp(char *params)
{
	char *host = NULL;
	char *port = NULL;
	char *family = NULL;
	struct addrinfo hints = { 0 };
	struct addrinfo *res;
	struct addrinfo *iter;
	struct l_dbus *dbus = NULL;

	while (params) {
		char *key = strsep(&params, ",");
		char *value;

		value = strchr(key, '=');
		if (!value)
			continue;

		*value++ = '\0';

		if (!strcmp(key, "host"))
			host = value;
		else if (!strcmp(key, "port"))
			port = value;
		else if (!strcmp(key, "family"))
			family = value;
	}

	if (!host || !port)
		return NULL;

	if (!family)
		hints.ai_family = AF_UNSPEC;
	else if (!strcmp(family, "ipv4"))
		hints.ai_family = AF_INET;
	else if (!strcmp(family, "ipv6"))
		hints.ai_family = AF_INET6;
	else
		return NULL;

	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
	hints.ai_protocol = IPPROTO_TCP;

	if (getaddrinfo(host, port, &hints, &res) != 0)
		return NULL;

	for (iter = res; iter; iter = iter->ai_next) {
		int fd;
		struct l_dbus_classic *classic;

		fd = socket(iter->ai_family, iter->ai_socktype | SOCK_NONBLOCK,
					iter->ai_protocol);
		if (fd < 0)
			continue;

		if (connect(fd, iter->ai_addr, iter->ai_addrlen) < 0) {
			if (errno != EINPROGRESS) {
				close(fd);
				continue;
			}
		}

		classic = l_new(struct l_dbus_classic, 1);
		dbus = &classic->super;
		dbus_init(dbus, fd);
		l_io_set_write_handler(dbus->io, setup_tcp_cb, dbus, NULL);
		break;
	}

	freeaddrinfo(res);
	return dbus;
}

static struct l_dbus *setup_address(const char *address)
{
	struct l_dbus *dbus = NULL;
	char *address_copy;

	address_copy = strdupa(address);

	while (address_copy) {
		char *transport = strsep(&address_copy, ";");
		char *params;

		if (!transport)
			break;

		params = strchr(transport, ':');
		if (params)
			*params++ = '\0';

		if (!strcmp(transport, "unix")) {
			/* Function will modify params string */
			dbus = setup_unix(params);
			break;
		} else if (!strcmp(transport, "tcp")) {
			dbus = setup_tcp(params);
			break;
		}
	}

	return dbus;
}

LIB_EXPORT struct l_dbus *l_dbus_new(const char *address)
{
	if (unlikely(!address))
		return NULL;

	return setup_address(address);
}

LIB_EXPORT struct l_dbus *l_dbus_new_default(enum l_dbus_bus bus)
{
	const char *address;

	switch (bus) {
	case L_DBUS_SYSTEM_BUS:
		address = getenv("DBUS_SYSTEM_BUS_ADDRESS");
		if (!address)
			address = DEFAULT_SYSTEM_BUS_ADDRESS;
		break;
	case L_DBUS_SESSION_BUS:
		address = getenv("DBUS_SESSION_BUS_ADDRESS");
		if (!address)
			return NULL;
		break;
	default:
		return NULL;
	}

	return setup_address(address);
}

LIB_EXPORT struct l_dbus *l_dbus_new_private(int fd)
{
	return setup_dbus1(fd, NULL, true);
}

LIB_EXPORT void l_dbus_destroy(struct l_dbus *dbus)
{
	if (unlikely(!dbus))
		return;

	if (dbus->ready_destroy)
		dbus->ready_destroy(dbus->ready_data);

	_dbus_filter_free(dbus->filter);

	_dbus_name_cache_free(dbus->name_cache);

	l_hashmap_destroy(dbus->signal_list, signal_list_destroy);
	l_hashmap_destroy(dbus->message_list, message_list_destroy);
	l_queue_destroy(dbus->message_queue, message_queue_destroy);

	l_io_destroy(dbus->io);

	if (dbus->disconnect_destroy)
		dbus->disconnect_destroy(dbus->disconnect_data);

	if (dbus->debug_destroy)
		dbus->debug_destroy(dbus->debug_data);

	l_free(dbus->guid);
	l_free(dbus->unique_name);

	_dbus_object_tree_free(dbus->tree);

	dbus->driver->free(dbus);
}

LIB_EXPORT bool l_dbus_set_ready_handler(struct l_dbus *dbus,
				l_dbus_ready_func_t function,
				void *user_data, l_dbus_destroy_func_t destroy)
{
	if (unlikely(!dbus))
		return false;

	if (dbus->ready_destroy)
		dbus->ready_destroy(dbus->ready_data);

	dbus->ready_handler = function;
	dbus->ready_destroy = destroy;
	dbus->ready_data = user_data;

	return true;
}

LIB_EXPORT bool l_dbus_set_disconnect_handler(struct l_dbus *dbus,
				l_dbus_disconnect_func_t function,
				void *user_data, l_dbus_destroy_func_t destroy)
{
	if (unlikely(!dbus))
		return false;

	if (dbus->disconnect_destroy)
		dbus->disconnect_destroy(dbus->disconnect_data);

	dbus->disconnect_handler = function;
	dbus->disconnect_destroy = destroy;
	dbus->disconnect_data = user_data;

	return true;
}

LIB_EXPORT bool l_dbus_set_debug(struct l_dbus *dbus,
				l_dbus_debug_func_t function,
				void *user_data, l_dbus_destroy_func_t destroy)
{
	if (unlikely(!dbus))
		return false;

	if (dbus->debug_destroy)
		dbus->debug_destroy(dbus->debug_data);

	dbus->debug_handler = function;
	dbus->debug_destroy = destroy;
	dbus->debug_data = user_data;

	/* l_io_set_debug(dbus->io, function, user_data, NULL); */

	return true;
}

LIB_EXPORT uint32_t l_dbus_send_with_reply(struct l_dbus *dbus,
						struct l_dbus_message *message,
						l_dbus_message_func_t function,
						void *user_data,
						l_dbus_destroy_func_t destroy)
{
	if (unlikely(!dbus || !message))
		return 0;

	return send_message(dbus, false, message, function, user_data, destroy);
}

LIB_EXPORT uint32_t l_dbus_send(struct l_dbus *dbus,
				struct l_dbus_message *message)
{
	if (unlikely(!dbus || !message))
		return 0;

	return send_message(dbus, false, message, NULL, NULL, NULL);
}

static bool remove_entry(void *data, void *user_data)
{
	struct message_callback *callback = data;
	uint32_t serial = L_PTR_TO_UINT(user_data);

	if (callback->serial == serial) {
		message_queue_destroy(callback);
		return true;
	}

	return false;
}

LIB_EXPORT bool l_dbus_cancel(struct l_dbus *dbus, uint32_t serial)
{
	struct message_callback *callback;
	unsigned int count;

	if (unlikely(!dbus || !serial))
		return false;

	callback = l_hashmap_remove(dbus->message_list, L_UINT_TO_PTR(serial));
        if (callback) {
		message_queue_destroy(callback);
		return true;
	}

	count = l_queue_foreach_remove(dbus->message_queue, remove_entry,
							L_UINT_TO_PTR(serial));
	if (!count)
		return false;

	return true;
}

LIB_EXPORT unsigned int l_dbus_register(struct l_dbus *dbus,
				l_dbus_message_func_t function,
				void *user_data, l_dbus_destroy_func_t destroy)
{
	struct signal_callback *callback;

	if (unlikely(!dbus))
		return 0;

	callback = l_new(struct signal_callback, 1);

	callback->id = dbus->next_id++;
	callback->callback = function;
	callback->destroy = destroy;
	callback->user_data = user_data;

	l_hashmap_insert(dbus->signal_list,
				L_UINT_TO_PTR(callback->id), callback);

	return callback->id;
}

LIB_EXPORT bool l_dbus_unregister(struct l_dbus *dbus, unsigned int id)
{
	struct signal_callback *callback;

	if (unlikely(!dbus || !id))
		return false;

	callback = l_hashmap_remove(dbus->signal_list, L_UINT_TO_PTR(id));
	if (!callback)
		return false;

	signal_list_destroy(callback);

	return true;
}

LIB_EXPORT uint32_t l_dbus_method_call(struct l_dbus *dbus,
				const char *destination, const char *path,
				const char *interface, const char *method,
				l_dbus_message_func_t setup,
				l_dbus_message_func_t function,
				void *user_data, l_dbus_destroy_func_t destroy)
{
	struct l_dbus_message *message;

	if (unlikely(!dbus))
		return 0;

	message = l_dbus_message_new_method_call(dbus, destination, path,
							interface, method);

	if (setup)
		setup(message, user_data);
	else
		l_dbus_message_set_arguments(message, "");

	return send_message(dbus, false, message, function, user_data, destroy);
}

uint8_t _dbus_get_version(struct l_dbus *dbus)
{
	return dbus->driver->version;
}

int _dbus_get_fd(struct l_dbus *dbus)
{
	return l_io_get_fd(dbus->io);
}

struct _dbus_object_tree *_dbus_get_tree(struct l_dbus *dbus)
{
	return dbus->tree;
}

/**
 * l_dbus_register_interface:
 * @dbus: D-Bus connection as returned by @l_dbus_new*
 * @interface: interface name string
 * @setup_func: function that sets up the methods, signals and properties by
 *              using the #dbus-service.h API.
 * @destroy: optional destructor to be called every time an instance of this
 *           interface is being removed from an object on this bus.
 * @handle_old_style_properties: whether to automatically handle SetProperty and
 *                               GetProperties for any properties registered by
 *                               @setup_func.
 *
 * Registers an interface.  If successful the interface can then be added
 * to any number of objects with @l_dbus_object_add_interface.
 *
 * Returns: whether the interface was successfully registered
 **/
LIB_EXPORT bool l_dbus_register_interface(struct l_dbus *dbus,
				const char *interface,
				l_dbus_interface_setup_func_t setup_func,
				l_dbus_destroy_func_t destroy,
				bool handle_old_style_properties)
{
	if (unlikely(!dbus))
		return false;

	if (unlikely(!dbus->tree))
		return false;

	return _dbus_object_tree_register_interface(dbus->tree, interface,
						setup_func, destroy,
						handle_old_style_properties);
}

LIB_EXPORT bool l_dbus_unregister_interface(struct l_dbus *dbus,
						const char *interface)
{
	if (unlikely(!dbus))
		return false;

	if (unlikely(!dbus->tree))
		return false;

	return _dbus_object_tree_unregister_interface(dbus->tree, interface);
}

/**
 * l_dbus_register_object:
 * @dbus: D-Bus connection
 * @path: new object path
 * @user_data: user pointer to be passed to @destroy if any
 * @destroy: optional destructor to be called when object dropped from the tree
 * @...: NULL-terminated list of 0 or more interfaces to be present on the
 *       object from the moment of creation.  For every interface the interface
 *       name string is expected followed by the @user_data pointer same as
 *       would be passed as @l_dbus_object_add_interface's last two parameters.
 *
 * Create a new D-Bus object on the tree visible to D-Bus peers.  For example:
 * 	success = l_dbus_register_object(bus, "/org/example/ExampleManager",
 * 						NULL, NULL,
 * 						"org.example.Manager",
 * 						manager_data,
 * 						NULL);
 *
 * Returns: whether the object path was successfully registered
 **/
LIB_EXPORT bool l_dbus_register_object(struct l_dbus *dbus, const char *path,
					void *user_data,
					l_dbus_destroy_func_t destroy, ...)
{
	va_list args;
	const char *interface;
	void *if_user_data;
	bool r = true;

	if (unlikely(!dbus))
		return false;

	if (unlikely(!dbus->tree))
		return false;

	if (!_dbus_object_tree_new_object(dbus->tree, path, user_data, destroy))
		return false;

	va_start(args, destroy);
	while ((interface = va_arg(args, const char *))) {
		if_user_data = va_arg(args, void *);

		if (!_dbus_object_tree_add_interface(dbus->tree, path,
							interface,
							if_user_data)) {
			_dbus_object_tree_object_destroy(dbus->tree, path);
			r = false;

			break;
		}
	}
	va_end(args);

	return r;
}

LIB_EXPORT bool l_dbus_unregister_object(struct l_dbus *dbus,
						const char *object)
{
	if (unlikely(!dbus))
		return false;

	if (unlikely(!dbus->tree))
		return false;

	return _dbus_object_tree_object_destroy(dbus->tree, object);
}

/**
 * l_dbus_object_add_interface:
 * @dbus: D-Bus connection
 * @object: object path as passed to @l_dbus_register_object
 * @interface: interface name as passed to @l_dbus_register_interface
 * @user_data: user data pointer to be passed to any method and property
 *             callbacks provided by the @setup_func and to the @destroy
 *             callback as passed to @l_dbus_register_interface
 *
 * Creates an instance of given interface at the given path in the
 * connection's object tree.  If no object was registered at this path
 * before @l_dbus_register_object gets called automatically.
 *
 * The addition of an interface to the object may trigger a query of
 * all the properties on this interface and
 * #org.freedesktop.DBus.ObjectManager.InterfacesAdded signals.
 *
 * Returns: whether the interface was successfully added.
 **/
LIB_EXPORT bool l_dbus_object_add_interface(struct l_dbus *dbus,
						const char *object,
						const char *interface,
						void *user_data)
{
	if (unlikely(!dbus))
		return false;

	if (unlikely(!dbus->tree))
		return false;

	return _dbus_object_tree_add_interface(dbus->tree, object, interface,
						user_data);
}

LIB_EXPORT bool l_dbus_object_remove_interface(struct l_dbus *dbus,
						const char *object,
						const char *interface)
{
	if (unlikely(!dbus))
		return false;

	if (unlikely(!dbus->tree))
		return false;

	return _dbus_object_tree_remove_interface(dbus->tree, object,
							interface);
}

LIB_EXPORT void *l_dbus_object_get_data(struct l_dbus *dbus, const char *object,
					const char *interface)
{
	if (unlikely(!dbus))
		return NULL;

	if (unlikely(!dbus->tree))
		return NULL;

	return _dbus_object_tree_get_interface_data(dbus->tree, object,
							interface);
}

LIB_EXPORT bool l_dbus_object_set_data(struct l_dbus *dbus, const char *object,
				const char *interface, void *user_data)
{
	if (unlikely(!dbus))
		return false;

	if (unlikely(!dbus->tree))
		return false;

	return _dbus_object_tree_set_interface_data(dbus->tree, object,
							interface, user_data);
}

LIB_EXPORT bool l_dbus_object_manager_enable(struct l_dbus *dbus,
						const char *root)
{
	if (unlikely(!dbus))
		return false;

	if (unlikely(!dbus->tree))
		return false;

	return _dbus_object_tree_add_interface(dbus->tree, root,
						L_DBUS_INTERFACE_OBJECT_MANAGER,
						dbus);
}

LIB_EXPORT unsigned int l_dbus_add_disconnect_watch(struct l_dbus *dbus,
					const char *name,
					l_dbus_watch_func_t disconnect_func,
					void *user_data,
					l_dbus_destroy_func_t destroy)
{
	return l_dbus_add_service_watch(dbus, name, NULL, disconnect_func,
					user_data, destroy);
}

LIB_EXPORT unsigned int l_dbus_add_service_watch(struct l_dbus *dbus,
					const char *name,
					l_dbus_watch_func_t connect_func,
					l_dbus_watch_func_t disconnect_func,
					void *user_data,
					l_dbus_destroy_func_t destroy)
{
	if (!name)
		return 0;

	if (!dbus->name_cache)
		dbus->name_cache = _dbus_name_cache_new(dbus,
						&dbus->driver->name_ops);

	return _dbus_name_cache_add_watch(dbus->name_cache, name, connect_func,
						disconnect_func, user_data,
						destroy);
}

LIB_EXPORT bool l_dbus_remove_watch(struct l_dbus *dbus, unsigned int id)
{
	if (!dbus->name_cache)
		return false;

	return _dbus_name_cache_remove_watch(dbus->name_cache, id);
}

/**
 * l_dbus_add_signal_watch:
 * @dbus: D-Bus connection
 * @sender: bus name to match the signal sender against or NULL to
 *          match any sender
 * @path: object path to match the signal path against or NULL to
 *        match any path
 * @interface: interface name to match the signal interface against
 *             or NULL to match any interface
 * @member: name to match the signal name against or NULL to match any
 *          signal
 * @...: a list of further conditions to be met by the signal followed
 *       by three more mandatory parameters:
 *       enum l_dbus_match_type list_end_marker,
 *       l_dbus_message_func callback,
 *       void *user_data,
 *       The value L_DBUS_MATCH_NONE must be passed as the end of list
 *       marker, followed by the signal match callback and user_data.
 *       In the list, every condition is a pair of parameters:
 *       enum l_dbus_match_type match_type, const char *value.
 *
 * Subscribe to a group of signals based on a set of conditions that
 * compare the signal's header fields and string arguments against given
 * values.  For example:
 * 	signal_id = l_dbus_add_signal_watch(bus, "org.example", "/"
 * 						"org.example.Manager",
 * 						"PropertyChanged",
 * 						L_DBUS_MATCH_ARGUMENT(0),
 * 						"ExampleProperty",
 * 						L_DBUS_MATCH_NONE
 * 						manager_property_change_cb,
 * 						NULL);
  *
 * Returns: a non-zero signal filter identifier that can be passed to
 *          l_dbus_remove_signal_watch to remove this filter rule, or
 *          zero on failure.
 **/
LIB_EXPORT unsigned int l_dbus_add_signal_watch(struct l_dbus *dbus,
						const char *sender,
						const char *path,
						const char *interface,
						const char *member, ...)
{
	struct _dbus_filter_condition *rule;
	int rule_len;
	va_list args;
	const char *value;
	l_dbus_message_func_t signal_func;
	enum l_dbus_match_type type;
	void *user_data;
	unsigned int id;

	va_start(args, member);

	rule_len = 0;
	while (true) {
		type = va_arg(args, enum l_dbus_match_type);
		if (type == L_DBUS_MATCH_NONE)
			break;

		va_arg(args, const char *);
		rule_len++;
	}

	va_end(args);

	rule = l_new(struct _dbus_filter_condition, rule_len + 5);

	rule_len = 0;

	rule[rule_len].type = L_DBUS_MATCH_TYPE;
	rule[rule_len++].value = "signal";

	if (sender) {
		rule[rule_len].type = L_DBUS_MATCH_SENDER;
		rule[rule_len++].value = sender;
	}

	if (path) {
		rule[rule_len].type = L_DBUS_MATCH_PATH;
		rule[rule_len++].value = path;
	}

	if (interface) {
		rule[rule_len].type = L_DBUS_MATCH_INTERFACE;
		rule[rule_len++].value = interface;
	}

	if (member) {
		rule[rule_len].type = L_DBUS_MATCH_MEMBER;
		rule[rule_len++].value = member;
	}

	va_start(args, member);

	while (true) {
		type = va_arg(args, enum l_dbus_match_type);
		if (type == L_DBUS_MATCH_NONE)
			break;

		value = va_arg(args, const char *);

		rule[rule_len].type = type;
		rule[rule_len++].value = value;
	}

	signal_func = va_arg(args, l_dbus_message_func_t);
	user_data = va_arg(args, void *);

	va_end(args);

	if (!dbus->filter) {
		if (!dbus->name_cache)
			dbus->name_cache = _dbus_name_cache_new(dbus,
						&dbus->driver->name_ops);

		dbus->filter = _dbus_filter_new(dbus,
						&dbus->driver->filter_ops,
						dbus->name_cache);
	}

	id = _dbus_filter_add_rule(dbus->filter, rule, rule_len,
					signal_func, user_data);

	l_free(rule);

	return id;
}

LIB_EXPORT bool l_dbus_remove_signal_watch(struct l_dbus *dbus, unsigned int id)
{
	if (!dbus->filter)
		return false;

	return _dbus_filter_remove_rule(dbus->filter, id);
}

/**
 * l_dbus_name_acquire:
 * @dbus: D-Bus connection
 * @name: Well-known bus name to be acquired
 * @allow_replacement: Whether to allow another peer's name request to
 *                     take the name ownership away from this connection
 * @replace_existing: Whether to allow D-Bus to take the name's ownership
 *                    away from another peer in case the name is already
 *                    owned and allows replacement.  Ignored if name is
 *                    currently free.
 * @queue: Whether to allow the name request to be queued by D-Bus in
 *         case it cannot be acquired now, rather than to return a failure.
 * @callback: Callback to receive the request result when done.
 *
 * Acquire a well-known bus name (service name) on the bus.
 *
 * Returns: a non-zero request serial that can be passed to l_dbus_cancel
 *          while waiting for the callback or zero if the callback has
 *          has happened while l_dbus_name_acquire was running.
 **/
LIB_EXPORT uint32_t l_dbus_name_acquire(struct l_dbus *dbus, const char *name,
				bool allow_replacement, bool replace_existing,
				bool queue, l_dbus_name_acquire_func_t callback,
				void *user_data)
{
	return dbus->driver->name_acquire(dbus, name, allow_replacement,
						replace_existing, queue,
						callback, user_data);
}